applied-ai-018 commited on
Commit
023080d
·
verified ·
1 Parent(s): 5a178ff

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. llmeval-env/lib/python3.10/site-packages/sympy/geometry/__init__.py +45 -0
  2. llmeval-env/lib/python3.10/site-packages/sympy/geometry/__pycache__/__init__.cpython-310.pyc +0 -0
  3. llmeval-env/lib/python3.10/site-packages/sympy/geometry/__pycache__/curve.cpython-310.pyc +0 -0
  4. llmeval-env/lib/python3.10/site-packages/sympy/geometry/__pycache__/ellipse.cpython-310.pyc +0 -0
  5. llmeval-env/lib/python3.10/site-packages/sympy/geometry/__pycache__/entity.cpython-310.pyc +0 -0
  6. llmeval-env/lib/python3.10/site-packages/sympy/geometry/__pycache__/exceptions.cpython-310.pyc +0 -0
  7. llmeval-env/lib/python3.10/site-packages/sympy/geometry/__pycache__/line.cpython-310.pyc +0 -0
  8. llmeval-env/lib/python3.10/site-packages/sympy/geometry/__pycache__/parabola.cpython-310.pyc +0 -0
  9. llmeval-env/lib/python3.10/site-packages/sympy/geometry/__pycache__/plane.cpython-310.pyc +0 -0
  10. llmeval-env/lib/python3.10/site-packages/sympy/geometry/__pycache__/point.cpython-310.pyc +0 -0
  11. llmeval-env/lib/python3.10/site-packages/sympy/geometry/__pycache__/polygon.cpython-310.pyc +0 -0
  12. llmeval-env/lib/python3.10/site-packages/sympy/geometry/__pycache__/util.cpython-310.pyc +0 -0
  13. llmeval-env/lib/python3.10/site-packages/sympy/geometry/curve.py +424 -0
  14. llmeval-env/lib/python3.10/site-packages/sympy/geometry/ellipse.py +1780 -0
  15. llmeval-env/lib/python3.10/site-packages/sympy/geometry/exceptions.py +5 -0
  16. llmeval-env/lib/python3.10/site-packages/sympy/geometry/line.py +2803 -0
  17. llmeval-env/lib/python3.10/site-packages/sympy/geometry/parabola.py +422 -0
  18. llmeval-env/lib/python3.10/site-packages/sympy/geometry/plane.py +884 -0
  19. llmeval-env/lib/python3.10/site-packages/sympy/geometry/point.py +1378 -0
  20. llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/__init__.py +0 -0
  21. llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  22. llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/test_curve.cpython-310.pyc +0 -0
  23. llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/test_ellipse.cpython-310.pyc +0 -0
  24. llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/test_entity.cpython-310.pyc +0 -0
  25. llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/test_geometrysets.cpython-310.pyc +0 -0
  26. llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/test_line.cpython-310.pyc +0 -0
  27. llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/test_parabola.cpython-310.pyc +0 -0
  28. llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/test_plane.cpython-310.pyc +0 -0
  29. llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/test_point.cpython-310.pyc +0 -0
  30. llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/test_polygon.cpython-310.pyc +0 -0
  31. llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/test_util.cpython-310.pyc +0 -0
  32. llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/test_curve.py +120 -0
  33. llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/test_ellipse.py +601 -0
  34. llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/test_entity.py +120 -0
  35. llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/test_geometrysets.py +38 -0
  36. llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/test_line.py +852 -0
  37. llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/test_parabola.py +143 -0
  38. llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/test_plane.py +268 -0
  39. llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/test_point.py +481 -0
  40. llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/test_polygon.py +664 -0
  41. llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/test_util.py +151 -0
  42. llmeval-env/lib/python3.10/site-packages/sympy/solvers/__init__.py +71 -0
  43. llmeval-env/lib/python3.10/site-packages/sympy/solvers/benchmarks/__init__.py +0 -0
  44. llmeval-env/lib/python3.10/site-packages/sympy/solvers/benchmarks/__pycache__/__init__.cpython-310.pyc +0 -0
  45. llmeval-env/lib/python3.10/site-packages/sympy/solvers/benchmarks/__pycache__/bench_solvers.cpython-310.pyc +0 -0
  46. llmeval-env/lib/python3.10/site-packages/sympy/solvers/benchmarks/bench_solvers.py +12 -0
  47. llmeval-env/lib/python3.10/site-packages/sympy/solvers/bivariate.py +509 -0
  48. llmeval-env/lib/python3.10/site-packages/sympy/solvers/decompogen.py +126 -0
  49. llmeval-env/lib/python3.10/site-packages/sympy/solvers/deutils.py +273 -0
  50. llmeval-env/lib/python3.10/site-packages/sympy/solvers/inequalities.py +984 -0
llmeval-env/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
+ ]
llmeval-env/lib/python3.10/site-packages/sympy/geometry/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.47 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/geometry/__pycache__/curve.cpython-310.pyc ADDED
Binary file (11.8 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/geometry/__pycache__/ellipse.cpython-310.pyc ADDED
Binary file (48.4 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/geometry/__pycache__/entity.cpython-310.pyc ADDED
Binary file (21.2 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/geometry/__pycache__/exceptions.cpython-310.pyc ADDED
Binary file (460 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/geometry/__pycache__/line.cpython-310.pyc ADDED
Binary file (70.2 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/geometry/__pycache__/parabola.cpython-310.pyc ADDED
Binary file (11.1 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/geometry/__pycache__/plane.cpython-310.pyc ADDED
Binary file (25.8 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/geometry/__pycache__/point.cpython-310.pyc ADDED
Binary file (39.3 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/geometry/__pycache__/polygon.cpython-310.pyc ADDED
Binary file (78 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/geometry/__pycache__/util.cpython-310.pyc ADDED
Binary file (20.2 kB). View file
 
llmeval-env/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)
llmeval-env/lib/python3.10/site-packages/sympy/geometry/ellipse.py ADDED
@@ -0,0 +1,1780 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, Ray2D):
752
+ intersect = self.intersection(o)
753
+ if len(intersect) == 1:
754
+ return intersect[0] != o.source and not self.encloses_point(o.source)
755
+ else:
756
+ return False
757
+ elif isinstance(o, (Segment2D, Polygon)):
758
+ all_tangents = False
759
+ segments = o.sides if isinstance(o, Polygon) else [o]
760
+ for segment in segments:
761
+ intersect = self.intersection(segment)
762
+ if len(intersect) == 1:
763
+ if not any(intersect[0] in i for i in segment.points) \
764
+ and not any(self.encloses_point(i) for i in segment.points):
765
+ all_tangents = True
766
+ continue
767
+ else:
768
+ return False
769
+ else:
770
+ return all_tangents
771
+ return all_tangents
772
+ elif isinstance(o, (LinearEntity3D, Point3D)):
773
+ raise TypeError('Entity must be two dimensional, not three dimensional')
774
+ else:
775
+ raise TypeError('Is_tangent not handled for %s' % func_name(o))
776
+
777
+ @property
778
+ def major(self):
779
+ """Longer axis of the ellipse (if it can be determined) else hradius.
780
+
781
+ Returns
782
+ =======
783
+
784
+ major : number or expression
785
+
786
+ See Also
787
+ ========
788
+
789
+ hradius, vradius, minor
790
+
791
+ Examples
792
+ ========
793
+
794
+ >>> from sympy import Point, Ellipse, Symbol
795
+ >>> p1 = Point(0, 0)
796
+ >>> e1 = Ellipse(p1, 3, 1)
797
+ >>> e1.major
798
+ 3
799
+
800
+ >>> a = Symbol('a')
801
+ >>> b = Symbol('b')
802
+ >>> Ellipse(p1, a, b).major
803
+ a
804
+ >>> Ellipse(p1, b, a).major
805
+ b
806
+
807
+ >>> m = Symbol('m')
808
+ >>> M = m + 1
809
+ >>> Ellipse(p1, m, M).major
810
+ m + 1
811
+
812
+ """
813
+ ab = self.args[1:3]
814
+ if len(ab) == 1:
815
+ return ab[0]
816
+ a, b = ab
817
+ o = b - a < 0
818
+ if o == True:
819
+ return a
820
+ elif o == False:
821
+ return b
822
+ return self.hradius
823
+
824
+ @property
825
+ def minor(self):
826
+ """Shorter axis of the ellipse (if it can be determined) else vradius.
827
+
828
+ Returns
829
+ =======
830
+
831
+ minor : number or expression
832
+
833
+ See Also
834
+ ========
835
+
836
+ hradius, vradius, major
837
+
838
+ Examples
839
+ ========
840
+
841
+ >>> from sympy import Point, Ellipse, Symbol
842
+ >>> p1 = Point(0, 0)
843
+ >>> e1 = Ellipse(p1, 3, 1)
844
+ >>> e1.minor
845
+ 1
846
+
847
+ >>> a = Symbol('a')
848
+ >>> b = Symbol('b')
849
+ >>> Ellipse(p1, a, b).minor
850
+ b
851
+ >>> Ellipse(p1, b, a).minor
852
+ a
853
+
854
+ >>> m = Symbol('m')
855
+ >>> M = m + 1
856
+ >>> Ellipse(p1, m, M).minor
857
+ m
858
+
859
+ """
860
+ ab = self.args[1:3]
861
+ if len(ab) == 1:
862
+ return ab[0]
863
+ a, b = ab
864
+ o = a - b < 0
865
+ if o == True:
866
+ return a
867
+ elif o == False:
868
+ return b
869
+ return self.vradius
870
+
871
+ def normal_lines(self, p, prec=None):
872
+ """Normal lines between `p` and the ellipse.
873
+
874
+ Parameters
875
+ ==========
876
+
877
+ p : Point
878
+
879
+ Returns
880
+ =======
881
+
882
+ normal_lines : list with 1, 2 or 4 Lines
883
+
884
+ Examples
885
+ ========
886
+
887
+ >>> from sympy import Point, Ellipse
888
+ >>> e = Ellipse((0, 0), 2, 3)
889
+ >>> c = e.center
890
+ >>> e.normal_lines(c + Point(1, 0))
891
+ [Line2D(Point2D(0, 0), Point2D(1, 0))]
892
+ >>> e.normal_lines(c)
893
+ [Line2D(Point2D(0, 0), Point2D(0, 1)), Line2D(Point2D(0, 0), Point2D(1, 0))]
894
+
895
+ Off-axis points require the solution of a quartic equation. This
896
+ often leads to very large expressions that may be of little practical
897
+ use. An approximate solution of `prec` digits can be obtained by
898
+ passing in the desired value:
899
+
900
+ >>> e.normal_lines((3, 3), prec=2)
901
+ [Line2D(Point2D(-0.81, -2.7), Point2D(0.19, -1.2)),
902
+ Line2D(Point2D(1.5, -2.0), Point2D(2.5, -2.7))]
903
+
904
+ Whereas the above solution has an operation count of 12, the exact
905
+ solution has an operation count of 2020.
906
+ """
907
+ p = Point(p, dim=2)
908
+
909
+ # XXX change True to something like self.angle == 0 if the arbitrarily
910
+ # rotated ellipse is introduced.
911
+ # https://github.com/sympy/sympy/issues/2815)
912
+ if True:
913
+ rv = []
914
+ if p.x == self.center.x:
915
+ rv.append(Line(self.center, slope=oo))
916
+ if p.y == self.center.y:
917
+ rv.append(Line(self.center, slope=0))
918
+ if rv:
919
+ # at these special orientations of p either 1 or 2 normals
920
+ # exist and we are done
921
+ return rv
922
+
923
+ # find the 4 normal points and construct lines through them with
924
+ # the corresponding slope
925
+ eq = self.equation(x, y)
926
+ dydx = idiff(eq, y, x)
927
+ norm = -1/dydx
928
+ slope = Line(p, (x, y)).slope
929
+ seq = slope - norm
930
+
931
+ # TODO: Replace solve with solveset, when this line is tested
932
+ yis = solve(seq, y)[0]
933
+ xeq = eq.subs(y, yis).as_numer_denom()[0].expand()
934
+ if len(xeq.free_symbols) == 1:
935
+ try:
936
+ # this is so much faster, it's worth a try
937
+ xsol = Poly(xeq, x).real_roots()
938
+ except (DomainError, PolynomialError, NotImplementedError):
939
+ # TODO: Replace solve with solveset, when these lines are tested
940
+ xsol = _nsort(solve(xeq, x), separated=True)[0]
941
+ points = [Point(i, solve(eq.subs(x, i), y)[0]) for i in xsol]
942
+ else:
943
+ raise NotImplementedError(
944
+ 'intersections for the general ellipse are not supported')
945
+ slopes = [norm.subs(zip((x, y), pt.args)) for pt in points]
946
+ if prec is not None:
947
+ points = [pt.n(prec) for pt in points]
948
+ slopes = [i if _not_a_coeff(i) else i.n(prec) for i in slopes]
949
+ return [Line(pt, slope=s) for pt, s in zip(points, slopes)]
950
+
951
+ @property
952
+ def periapsis(self):
953
+ """The periapsis of the ellipse.
954
+
955
+ The shortest distance between the focus and the contour.
956
+
957
+ Returns
958
+ =======
959
+
960
+ periapsis : number
961
+
962
+ See Also
963
+ ========
964
+
965
+ apoapsis : Returns greatest distance between focus and contour
966
+
967
+ Examples
968
+ ========
969
+
970
+ >>> from sympy import Point, Ellipse
971
+ >>> p1 = Point(0, 0)
972
+ >>> e1 = Ellipse(p1, 3, 1)
973
+ >>> e1.periapsis
974
+ 3 - 2*sqrt(2)
975
+
976
+ """
977
+ return self.major * (1 - self.eccentricity)
978
+
979
+ @property
980
+ def semilatus_rectum(self):
981
+ """
982
+ Calculates the semi-latus rectum of the Ellipse.
983
+
984
+ Semi-latus rectum is defined as one half of the chord through a
985
+ focus parallel to the conic section directrix of a conic section.
986
+
987
+ Returns
988
+ =======
989
+
990
+ semilatus_rectum : number
991
+
992
+ See Also
993
+ ========
994
+
995
+ apoapsis : Returns greatest distance between focus and contour
996
+
997
+ periapsis : The shortest distance between the focus and the contour
998
+
999
+ Examples
1000
+ ========
1001
+
1002
+ >>> from sympy import Point, Ellipse
1003
+ >>> p1 = Point(0, 0)
1004
+ >>> e1 = Ellipse(p1, 3, 1)
1005
+ >>> e1.semilatus_rectum
1006
+ 1/3
1007
+
1008
+ References
1009
+ ==========
1010
+
1011
+ .. [1] https://mathworld.wolfram.com/SemilatusRectum.html
1012
+ .. [2] https://en.wikipedia.org/wiki/Ellipse#Semi-latus_rectum
1013
+
1014
+ """
1015
+ return self.major * (1 - self.eccentricity ** 2)
1016
+
1017
+ def auxiliary_circle(self):
1018
+ """Returns a Circle whose diameter is the major axis of the ellipse.
1019
+
1020
+ Examples
1021
+ ========
1022
+
1023
+ >>> from sympy import Ellipse, Point, symbols
1024
+ >>> c = Point(1, 2)
1025
+ >>> Ellipse(c, 8, 7).auxiliary_circle()
1026
+ Circle(Point2D(1, 2), 8)
1027
+ >>> a, b = symbols('a b')
1028
+ >>> Ellipse(c, a, b).auxiliary_circle()
1029
+ Circle(Point2D(1, 2), Max(a, b))
1030
+ """
1031
+ return Circle(self.center, Max(self.hradius, self.vradius))
1032
+
1033
+ def director_circle(self):
1034
+ """
1035
+ Returns a Circle consisting of all points where two perpendicular
1036
+ tangent lines to the ellipse cross each other.
1037
+
1038
+ Returns
1039
+ =======
1040
+
1041
+ Circle
1042
+ A director circle returned as a geometric object.
1043
+
1044
+ Examples
1045
+ ========
1046
+
1047
+ >>> from sympy import Ellipse, Point, symbols
1048
+ >>> c = Point(3,8)
1049
+ >>> Ellipse(c, 7, 9).director_circle()
1050
+ Circle(Point2D(3, 8), sqrt(130))
1051
+ >>> a, b = symbols('a b')
1052
+ >>> Ellipse(c, a, b).director_circle()
1053
+ Circle(Point2D(3, 8), sqrt(a**2 + b**2))
1054
+
1055
+ References
1056
+ ==========
1057
+
1058
+ .. [1] https://en.wikipedia.org/wiki/Director_circle
1059
+
1060
+ """
1061
+ return Circle(self.center, sqrt(self.hradius**2 + self.vradius**2))
1062
+
1063
+ def plot_interval(self, parameter='t'):
1064
+ """The plot interval for the default geometric plot of the Ellipse.
1065
+
1066
+ Parameters
1067
+ ==========
1068
+
1069
+ parameter : str, optional
1070
+ Default value is 't'.
1071
+
1072
+ Returns
1073
+ =======
1074
+
1075
+ plot_interval : list
1076
+ [parameter, lower_bound, upper_bound]
1077
+
1078
+ Examples
1079
+ ========
1080
+
1081
+ >>> from sympy import Point, Ellipse
1082
+ >>> e1 = Ellipse(Point(0, 0), 3, 2)
1083
+ >>> e1.plot_interval()
1084
+ [t, -pi, pi]
1085
+
1086
+ """
1087
+ t = _symbol(parameter, real=True)
1088
+ return [t, -S.Pi, S.Pi]
1089
+
1090
+ def random_point(self, seed=None):
1091
+ """A random point on the ellipse.
1092
+
1093
+ Returns
1094
+ =======
1095
+
1096
+ point : Point
1097
+
1098
+ Examples
1099
+ ========
1100
+
1101
+ >>> from sympy import Point, Ellipse
1102
+ >>> e1 = Ellipse(Point(0, 0), 3, 2)
1103
+ >>> e1.random_point() # gives some random point
1104
+ Point2D(...)
1105
+ >>> p1 = e1.random_point(seed=0); p1.n(2)
1106
+ Point2D(2.1, 1.4)
1107
+
1108
+ Notes
1109
+ =====
1110
+
1111
+ When creating a random point, one may simply replace the
1112
+ parameter with a random number. When doing so, however, the
1113
+ random number should be made a Rational or else the point
1114
+ may not test as being in the ellipse:
1115
+
1116
+ >>> from sympy.abc import t
1117
+ >>> from sympy import Rational
1118
+ >>> arb = e1.arbitrary_point(t); arb
1119
+ Point2D(3*cos(t), 2*sin(t))
1120
+ >>> arb.subs(t, .1) in e1
1121
+ False
1122
+ >>> arb.subs(t, Rational(.1)) in e1
1123
+ True
1124
+ >>> arb.subs(t, Rational('.1')) in e1
1125
+ True
1126
+
1127
+ See Also
1128
+ ========
1129
+ sympy.geometry.point.Point
1130
+ arbitrary_point : Returns parameterized point on ellipse
1131
+ """
1132
+ t = _symbol('t', real=True)
1133
+ x, y = self.arbitrary_point(t).args
1134
+ # get a random value in [-1, 1) corresponding to cos(t)
1135
+ # and confirm that it will test as being in the ellipse
1136
+ if seed is not None:
1137
+ rng = random.Random(seed)
1138
+ else:
1139
+ rng = random
1140
+ # simplify this now or else the Float will turn s into a Float
1141
+ r = Rational(rng.random())
1142
+ c = 2*r - 1
1143
+ s = sqrt(1 - c**2)
1144
+ return Point(x.subs(cos(t), c), y.subs(sin(t), s))
1145
+
1146
+ def reflect(self, line):
1147
+ """Override GeometryEntity.reflect since the radius
1148
+ is not a GeometryEntity.
1149
+
1150
+ Examples
1151
+ ========
1152
+
1153
+ >>> from sympy import Circle, Line
1154
+ >>> Circle((0, 1), 1).reflect(Line((0, 0), (1, 1)))
1155
+ Circle(Point2D(1, 0), -1)
1156
+ >>> from sympy import Ellipse, Line, Point
1157
+ >>> Ellipse(Point(3, 4), 1, 3).reflect(Line(Point(0, -4), Point(5, 0)))
1158
+ Traceback (most recent call last):
1159
+ ...
1160
+ NotImplementedError:
1161
+ General Ellipse is not supported but the equation of the reflected
1162
+ Ellipse is given by the zeros of: f(x, y) = (9*x/41 + 40*y/41 +
1163
+ 37/41)**2 + (40*x/123 - 3*y/41 - 364/123)**2 - 1
1164
+
1165
+ Notes
1166
+ =====
1167
+
1168
+ Until the general ellipse (with no axis parallel to the x-axis) is
1169
+ supported a NotImplemented error is raised and the equation whose
1170
+ zeros define the rotated ellipse is given.
1171
+
1172
+ """
1173
+
1174
+ if line.slope in (0, oo):
1175
+ c = self.center
1176
+ c = c.reflect(line)
1177
+ return self.func(c, -self.hradius, self.vradius)
1178
+ else:
1179
+ x, y = [uniquely_named_symbol(
1180
+ name, (self, line), modify=lambda s: '_' + s, real=True)
1181
+ for name in 'xy']
1182
+ expr = self.equation(x, y)
1183
+ p = Point(x, y).reflect(line)
1184
+ result = expr.subs(zip((x, y), p.args
1185
+ ), simultaneous=True)
1186
+ raise NotImplementedError(filldedent(
1187
+ 'General Ellipse is not supported but the equation '
1188
+ 'of the reflected Ellipse is given by the zeros of: ' +
1189
+ "f(%s, %s) = %s" % (str(x), str(y), str(result))))
1190
+
1191
+ def rotate(self, angle=0, pt=None):
1192
+ """Rotate ``angle`` radians counterclockwise about Point ``pt``.
1193
+
1194
+ Note: since the general ellipse is not supported, only rotations that
1195
+ are integer multiples of pi/2 are allowed.
1196
+
1197
+ Examples
1198
+ ========
1199
+
1200
+ >>> from sympy import Ellipse, pi
1201
+ >>> Ellipse((1, 0), 2, 1).rotate(pi/2)
1202
+ Ellipse(Point2D(0, 1), 1, 2)
1203
+ >>> Ellipse((1, 0), 2, 1).rotate(pi)
1204
+ Ellipse(Point2D(-1, 0), 2, 1)
1205
+ """
1206
+ if self.hradius == self.vradius:
1207
+ return self.func(self.center.rotate(angle, pt), self.hradius)
1208
+ if (angle/S.Pi).is_integer:
1209
+ return super().rotate(angle, pt)
1210
+ if (2*angle/S.Pi).is_integer:
1211
+ return self.func(self.center.rotate(angle, pt), self.vradius, self.hradius)
1212
+ # XXX see https://github.com/sympy/sympy/issues/2815 for general ellipes
1213
+ raise NotImplementedError('Only rotations of pi/2 are currently supported for Ellipse.')
1214
+
1215
+ def scale(self, x=1, y=1, pt=None):
1216
+ """Override GeometryEntity.scale since it is the major and minor
1217
+ axes which must be scaled and they are not GeometryEntities.
1218
+
1219
+ Examples
1220
+ ========
1221
+
1222
+ >>> from sympy import Ellipse
1223
+ >>> Ellipse((0, 0), 2, 1).scale(2, 4)
1224
+ Circle(Point2D(0, 0), 4)
1225
+ >>> Ellipse((0, 0), 2, 1).scale(2)
1226
+ Ellipse(Point2D(0, 0), 4, 1)
1227
+ """
1228
+ c = self.center
1229
+ if pt:
1230
+ pt = Point(pt, dim=2)
1231
+ return self.translate(*(-pt).args).scale(x, y).translate(*pt.args)
1232
+ h = self.hradius
1233
+ v = self.vradius
1234
+ return self.func(c.scale(x, y), hradius=h*x, vradius=v*y)
1235
+
1236
+ def tangent_lines(self, p):
1237
+ """Tangent lines between `p` and the ellipse.
1238
+
1239
+ If `p` is on the ellipse, returns the tangent line through point `p`.
1240
+ Otherwise, returns the tangent line(s) from `p` to the ellipse, or
1241
+ None if no tangent line is possible (e.g., `p` inside ellipse).
1242
+
1243
+ Parameters
1244
+ ==========
1245
+
1246
+ p : Point
1247
+
1248
+ Returns
1249
+ =======
1250
+
1251
+ tangent_lines : list with 1 or 2 Lines
1252
+
1253
+ Raises
1254
+ ======
1255
+
1256
+ NotImplementedError
1257
+ Can only find tangent lines for a point, `p`, on the ellipse.
1258
+
1259
+ See Also
1260
+ ========
1261
+
1262
+ sympy.geometry.point.Point, sympy.geometry.line.Line
1263
+
1264
+ Examples
1265
+ ========
1266
+
1267
+ >>> from sympy import Point, Ellipse
1268
+ >>> e1 = Ellipse(Point(0, 0), 3, 2)
1269
+ >>> e1.tangent_lines(Point(3, 0))
1270
+ [Line2D(Point2D(3, 0), Point2D(3, -12))]
1271
+
1272
+ """
1273
+ p = Point(p, dim=2)
1274
+ if self.encloses_point(p):
1275
+ return []
1276
+
1277
+ if p in self:
1278
+ delta = self.center - p
1279
+ rise = (self.vradius**2)*delta.x
1280
+ run = -(self.hradius**2)*delta.y
1281
+ p2 = Point(simplify(p.x + run),
1282
+ simplify(p.y + rise))
1283
+ return [Line(p, p2)]
1284
+ else:
1285
+ if len(self.foci) == 2:
1286
+ f1, f2 = self.foci
1287
+ maj = self.hradius
1288
+ test = (2*maj -
1289
+ Point.distance(f1, p) -
1290
+ Point.distance(f2, p))
1291
+ else:
1292
+ test = self.radius - Point.distance(self.center, p)
1293
+ if test.is_number and test.is_positive:
1294
+ return []
1295
+ # else p is outside the ellipse or we can't tell. In case of the
1296
+ # latter, the solutions returned will only be valid if
1297
+ # the point is not inside the ellipse; if it is, nan will result.
1298
+ eq = self.equation(x, y)
1299
+ dydx = idiff(eq, y, x)
1300
+ slope = Line(p, Point(x, y)).slope
1301
+
1302
+ # TODO: Replace solve with solveset, when this line is tested
1303
+ tangent_points = solve([slope - dydx, eq], [x, y])
1304
+
1305
+ # handle horizontal and vertical tangent lines
1306
+ if len(tangent_points) == 1:
1307
+ if tangent_points[0][
1308
+ 0] == p.x or tangent_points[0][1] == p.y:
1309
+ return [Line(p, p + Point(1, 0)), Line(p, p + Point(0, 1))]
1310
+ else:
1311
+ return [Line(p, p + Point(0, 1)), Line(p, tangent_points[0])]
1312
+
1313
+ # others
1314
+ return [Line(p, tangent_points[0]), Line(p, tangent_points[1])]
1315
+
1316
+ @property
1317
+ def vradius(self):
1318
+ """The vertical radius of the ellipse.
1319
+
1320
+ Returns
1321
+ =======
1322
+
1323
+ vradius : number
1324
+
1325
+ See Also
1326
+ ========
1327
+
1328
+ hradius, major, minor
1329
+
1330
+ Examples
1331
+ ========
1332
+
1333
+ >>> from sympy import Point, Ellipse
1334
+ >>> p1 = Point(0, 0)
1335
+ >>> e1 = Ellipse(p1, 3, 1)
1336
+ >>> e1.vradius
1337
+ 1
1338
+
1339
+ """
1340
+ return self.args[2]
1341
+
1342
+
1343
+ def second_moment_of_area(self, point=None):
1344
+ """Returns the second moment and product moment area of an ellipse.
1345
+
1346
+ Parameters
1347
+ ==========
1348
+
1349
+ point : Point, two-tuple of sympifiable objects, or None(default=None)
1350
+ point is the point about which second moment of area is to be found.
1351
+ If "point=None" it will be calculated about the axis passing through the
1352
+ centroid of the ellipse.
1353
+
1354
+ Returns
1355
+ =======
1356
+
1357
+ I_xx, I_yy, I_xy : number or SymPy expression
1358
+ I_xx, I_yy are second moment of area of an ellise.
1359
+ I_xy is product moment of area of an ellipse.
1360
+
1361
+ Examples
1362
+ ========
1363
+
1364
+ >>> from sympy import Point, Ellipse
1365
+ >>> p1 = Point(0, 0)
1366
+ >>> e1 = Ellipse(p1, 3, 1)
1367
+ >>> e1.second_moment_of_area()
1368
+ (3*pi/4, 27*pi/4, 0)
1369
+
1370
+ References
1371
+ ==========
1372
+
1373
+ .. [1] https://en.wikipedia.org/wiki/List_of_second_moments_of_area
1374
+
1375
+ """
1376
+
1377
+ I_xx = (S.Pi*(self.hradius)*(self.vradius**3))/4
1378
+ I_yy = (S.Pi*(self.hradius**3)*(self.vradius))/4
1379
+ I_xy = 0
1380
+
1381
+ if point is None:
1382
+ return I_xx, I_yy, I_xy
1383
+
1384
+ # parallel axis theorem
1385
+ I_xx = I_xx + self.area*((point[1] - self.center.y)**2)
1386
+ I_yy = I_yy + self.area*((point[0] - self.center.x)**2)
1387
+ I_xy = I_xy + self.area*(point[0] - self.center.x)*(point[1] - self.center.y)
1388
+
1389
+ return I_xx, I_yy, I_xy
1390
+
1391
+
1392
+ def polar_second_moment_of_area(self):
1393
+ """Returns the polar second moment of area of an Ellipse
1394
+
1395
+ It is a constituent of the second moment of area, linked through
1396
+ the perpendicular axis theorem. While the planar second moment of
1397
+ area describes an object's resistance to deflection (bending) when
1398
+ subjected to a force applied to a plane parallel to the central
1399
+ axis, the polar second moment of area describes an object's
1400
+ resistance to deflection when subjected to a moment applied in a
1401
+ plane perpendicular to the object's central axis (i.e. parallel to
1402
+ the cross-section)
1403
+
1404
+ Examples
1405
+ ========
1406
+
1407
+ >>> from sympy import symbols, Circle, Ellipse
1408
+ >>> c = Circle((5, 5), 4)
1409
+ >>> c.polar_second_moment_of_area()
1410
+ 128*pi
1411
+ >>> a, b = symbols('a, b')
1412
+ >>> e = Ellipse((0, 0), a, b)
1413
+ >>> e.polar_second_moment_of_area()
1414
+ pi*a**3*b/4 + pi*a*b**3/4
1415
+
1416
+ References
1417
+ ==========
1418
+
1419
+ .. [1] https://en.wikipedia.org/wiki/Polar_moment_of_inertia
1420
+
1421
+ """
1422
+ second_moment = self.second_moment_of_area()
1423
+ return second_moment[0] + second_moment[1]
1424
+
1425
+
1426
+ def section_modulus(self, point=None):
1427
+ """Returns a tuple with the section modulus of an ellipse
1428
+
1429
+ Section modulus is a geometric property of an ellipse defined as the
1430
+ ratio of second moment of area to the distance of the extreme end of
1431
+ the ellipse from the centroidal axis.
1432
+
1433
+ Parameters
1434
+ ==========
1435
+
1436
+ point : Point, two-tuple of sympifyable objects, or None(default=None)
1437
+ point is the point at which section modulus is to be found.
1438
+ If "point=None" section modulus will be calculated for the
1439
+ point farthest from the centroidal axis of the ellipse.
1440
+
1441
+ Returns
1442
+ =======
1443
+
1444
+ S_x, S_y: numbers or SymPy expressions
1445
+ S_x is the section modulus with respect to the x-axis
1446
+ S_y is the section modulus with respect to the y-axis
1447
+ A negative sign indicates that the section modulus is
1448
+ determined for a point below the centroidal axis.
1449
+
1450
+ Examples
1451
+ ========
1452
+
1453
+ >>> from sympy import Symbol, Ellipse, Circle, Point2D
1454
+ >>> d = Symbol('d', positive=True)
1455
+ >>> c = Circle((0, 0), d/2)
1456
+ >>> c.section_modulus()
1457
+ (pi*d**3/32, pi*d**3/32)
1458
+ >>> e = Ellipse(Point2D(0, 0), 2, 4)
1459
+ >>> e.section_modulus()
1460
+ (8*pi, 4*pi)
1461
+ >>> e.section_modulus((2, 2))
1462
+ (16*pi, 4*pi)
1463
+
1464
+ References
1465
+ ==========
1466
+
1467
+ .. [1] https://en.wikipedia.org/wiki/Section_modulus
1468
+
1469
+ """
1470
+ x_c, y_c = self.center
1471
+ if point is None:
1472
+ # taking x and y as maximum distances from centroid
1473
+ x_min, y_min, x_max, y_max = self.bounds
1474
+ y = max(y_c - y_min, y_max - y_c)
1475
+ x = max(x_c - x_min, x_max - x_c)
1476
+ else:
1477
+ # taking x and y as distances of the given point from the center
1478
+ point = Point2D(point)
1479
+ y = point.y - y_c
1480
+ x = point.x - x_c
1481
+
1482
+ second_moment = self.second_moment_of_area()
1483
+ S_x = second_moment[0]/y
1484
+ S_y = second_moment[1]/x
1485
+
1486
+ return S_x, S_y
1487
+
1488
+
1489
+ class Circle(Ellipse):
1490
+ """A circle in space.
1491
+
1492
+ Constructed simply from a center and a radius, from three
1493
+ non-collinear points, or the equation of a circle.
1494
+
1495
+ Parameters
1496
+ ==========
1497
+
1498
+ center : Point
1499
+ radius : number or SymPy expression
1500
+ points : sequence of three Points
1501
+ equation : equation of a circle
1502
+
1503
+ Attributes
1504
+ ==========
1505
+
1506
+ radius (synonymous with hradius, vradius, major and minor)
1507
+ circumference
1508
+ equation
1509
+
1510
+ Raises
1511
+ ======
1512
+
1513
+ GeometryError
1514
+ When the given equation is not that of a circle.
1515
+ When trying to construct circle from incorrect parameters.
1516
+
1517
+ See Also
1518
+ ========
1519
+
1520
+ Ellipse, sympy.geometry.point.Point
1521
+
1522
+ Examples
1523
+ ========
1524
+
1525
+ >>> from sympy import Point, Circle, Eq
1526
+ >>> from sympy.abc import x, y, a, b
1527
+
1528
+ A circle constructed from a center and radius:
1529
+
1530
+ >>> c1 = Circle(Point(0, 0), 5)
1531
+ >>> c1.hradius, c1.vradius, c1.radius
1532
+ (5, 5, 5)
1533
+
1534
+ A circle constructed from three points:
1535
+
1536
+ >>> c2 = Circle(Point(0, 0), Point(1, 1), Point(1, 0))
1537
+ >>> c2.hradius, c2.vradius, c2.radius, c2.center
1538
+ (sqrt(2)/2, sqrt(2)/2, sqrt(2)/2, Point2D(1/2, 1/2))
1539
+
1540
+ A circle can be constructed from an equation in the form
1541
+ `a*x**2 + by**2 + gx + hy + c = 0`, too:
1542
+
1543
+ >>> Circle(x**2 + y**2 - 25)
1544
+ Circle(Point2D(0, 0), 5)
1545
+
1546
+ If the variables corresponding to x and y are named something
1547
+ else, their name or symbol can be supplied:
1548
+
1549
+ >>> Circle(Eq(a**2 + b**2, 25), x='a', y=b)
1550
+ Circle(Point2D(0, 0), 5)
1551
+ """
1552
+
1553
+ def __new__(cls, *args, **kwargs):
1554
+ evaluate = kwargs.get('evaluate', global_parameters.evaluate)
1555
+ if len(args) == 1 and isinstance(args[0], (Expr, Eq)):
1556
+ x = kwargs.get('x', 'x')
1557
+ y = kwargs.get('y', 'y')
1558
+ equation = args[0].expand()
1559
+ if isinstance(equation, Eq):
1560
+ equation = equation.lhs - equation.rhs
1561
+ x = find(x, equation)
1562
+ y = find(y, equation)
1563
+
1564
+ try:
1565
+ a, b, c, d, e = linear_coeffs(equation, x**2, y**2, x, y)
1566
+ except ValueError:
1567
+ raise GeometryError("The given equation is not that of a circle.")
1568
+
1569
+ if S.Zero in (a, b) or a != b:
1570
+ raise GeometryError("The given equation is not that of a circle.")
1571
+
1572
+ center_x = -c/a/2
1573
+ center_y = -d/b/2
1574
+ r2 = (center_x**2) + (center_y**2) - e/a
1575
+
1576
+ return Circle((center_x, center_y), sqrt(r2), evaluate=evaluate)
1577
+
1578
+ else:
1579
+ c, r = None, None
1580
+ if len(args) == 3:
1581
+ args = [Point(a, dim=2, evaluate=evaluate) for a in args]
1582
+ t = Triangle(*args)
1583
+ if not isinstance(t, Triangle):
1584
+ return t
1585
+ c = t.circumcenter
1586
+ r = t.circumradius
1587
+ elif len(args) == 2:
1588
+ # Assume (center, radius) pair
1589
+ c = Point(args[0], dim=2, evaluate=evaluate)
1590
+ r = args[1]
1591
+ # this will prohibit imaginary radius
1592
+ try:
1593
+ r = Point(r, 0, evaluate=evaluate).x
1594
+ except ValueError:
1595
+ raise GeometryError("Circle with imaginary radius is not permitted")
1596
+
1597
+ if not (c is None or r is None):
1598
+ if r == 0:
1599
+ return c
1600
+ return GeometryEntity.__new__(cls, c, r, **kwargs)
1601
+
1602
+ raise GeometryError("Circle.__new__ received unknown arguments")
1603
+
1604
+ def _eval_evalf(self, prec=15, **options):
1605
+ pt, r = self.args
1606
+ dps = prec_to_dps(prec)
1607
+ pt = pt.evalf(n=dps, **options)
1608
+ r = r.evalf(n=dps, **options)
1609
+ return self.func(pt, r, evaluate=False)
1610
+
1611
+ @property
1612
+ def circumference(self):
1613
+ """The circumference of the circle.
1614
+
1615
+ Returns
1616
+ =======
1617
+
1618
+ circumference : number or SymPy expression
1619
+
1620
+ Examples
1621
+ ========
1622
+
1623
+ >>> from sympy import Point, Circle
1624
+ >>> c1 = Circle(Point(3, 4), 6)
1625
+ >>> c1.circumference
1626
+ 12*pi
1627
+
1628
+ """
1629
+ return 2 * S.Pi * self.radius
1630
+
1631
+ def equation(self, x='x', y='y'):
1632
+ """The equation of the circle.
1633
+
1634
+ Parameters
1635
+ ==========
1636
+
1637
+ x : str or Symbol, optional
1638
+ Default value is 'x'.
1639
+ y : str or Symbol, optional
1640
+ Default value is 'y'.
1641
+
1642
+ Returns
1643
+ =======
1644
+
1645
+ equation : SymPy expression
1646
+
1647
+ Examples
1648
+ ========
1649
+
1650
+ >>> from sympy import Point, Circle
1651
+ >>> c1 = Circle(Point(0, 0), 5)
1652
+ >>> c1.equation()
1653
+ x**2 + y**2 - 25
1654
+
1655
+ """
1656
+ x = _symbol(x, real=True)
1657
+ y = _symbol(y, real=True)
1658
+ t1 = (x - self.center.x)**2
1659
+ t2 = (y - self.center.y)**2
1660
+ return t1 + t2 - self.major**2
1661
+
1662
+ def intersection(self, o):
1663
+ """The intersection of this circle with another geometrical entity.
1664
+
1665
+ Parameters
1666
+ ==========
1667
+
1668
+ o : GeometryEntity
1669
+
1670
+ Returns
1671
+ =======
1672
+
1673
+ intersection : list of GeometryEntities
1674
+
1675
+ Examples
1676
+ ========
1677
+
1678
+ >>> from sympy import Point, Circle, Line, Ray
1679
+ >>> p1, p2, p3 = Point(0, 0), Point(5, 5), Point(6, 0)
1680
+ >>> p4 = Point(5, 0)
1681
+ >>> c1 = Circle(p1, 5)
1682
+ >>> c1.intersection(p2)
1683
+ []
1684
+ >>> c1.intersection(p4)
1685
+ [Point2D(5, 0)]
1686
+ >>> c1.intersection(Ray(p1, p2))
1687
+ [Point2D(5*sqrt(2)/2, 5*sqrt(2)/2)]
1688
+ >>> c1.intersection(Line(p2, p3))
1689
+ []
1690
+
1691
+ """
1692
+ return Ellipse.intersection(self, o)
1693
+
1694
+ @property
1695
+ def radius(self):
1696
+ """The radius of the circle.
1697
+
1698
+ Returns
1699
+ =======
1700
+
1701
+ radius : number or SymPy expression
1702
+
1703
+ See Also
1704
+ ========
1705
+
1706
+ Ellipse.major, Ellipse.minor, Ellipse.hradius, Ellipse.vradius
1707
+
1708
+ Examples
1709
+ ========
1710
+
1711
+ >>> from sympy import Point, Circle
1712
+ >>> c1 = Circle(Point(3, 4), 6)
1713
+ >>> c1.radius
1714
+ 6
1715
+
1716
+ """
1717
+ return self.args[1]
1718
+
1719
+ def reflect(self, line):
1720
+ """Override GeometryEntity.reflect since the radius
1721
+ is not a GeometryEntity.
1722
+
1723
+ Examples
1724
+ ========
1725
+
1726
+ >>> from sympy import Circle, Line
1727
+ >>> Circle((0, 1), 1).reflect(Line((0, 0), (1, 1)))
1728
+ Circle(Point2D(1, 0), -1)
1729
+ """
1730
+ c = self.center
1731
+ c = c.reflect(line)
1732
+ return self.func(c, -self.radius)
1733
+
1734
+ def scale(self, x=1, y=1, pt=None):
1735
+ """Override GeometryEntity.scale since the radius
1736
+ is not a GeometryEntity.
1737
+
1738
+ Examples
1739
+ ========
1740
+
1741
+ >>> from sympy import Circle
1742
+ >>> Circle((0, 0), 1).scale(2, 2)
1743
+ Circle(Point2D(0, 0), 2)
1744
+ >>> Circle((0, 0), 1).scale(2, 4)
1745
+ Ellipse(Point2D(0, 0), 2, 4)
1746
+ """
1747
+ c = self.center
1748
+ if pt:
1749
+ pt = Point(pt, dim=2)
1750
+ return self.translate(*(-pt).args).scale(x, y).translate(*pt.args)
1751
+ c = c.scale(x, y)
1752
+ x, y = [abs(i) for i in (x, y)]
1753
+ if x == y:
1754
+ return self.func(c, x*self.radius)
1755
+ h = v = self.radius
1756
+ return Ellipse(c, hradius=h*x, vradius=v*y)
1757
+
1758
+ @property
1759
+ def vradius(self):
1760
+ """
1761
+ This Ellipse property is an alias for the Circle's radius.
1762
+
1763
+ Whereas hradius, major and minor can use Ellipse's conventions,
1764
+ the vradius does not exist for a circle. It is always a positive
1765
+ value in order that the Circle, like Polygons, will have an
1766
+ area that can be positive or negative as determined by the sign
1767
+ of the hradius.
1768
+
1769
+ Examples
1770
+ ========
1771
+
1772
+ >>> from sympy import Point, Circle
1773
+ >>> c1 = Circle(Point(3, 4), 6)
1774
+ >>> c1.vradius
1775
+ 6
1776
+ """
1777
+ return abs(self.radius)
1778
+
1779
+
1780
+ from .polygon import Polygon, Triangle
llmeval-env/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
llmeval-env/lib/python3.10/site-packages/sympy/geometry/line.py ADDED
@@ -0,0 +1,2803 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
2596
+ class Ray3D(LinearEntity3D, Ray):
2597
+ """
2598
+ A Ray is a semi-line in the space with a source point and a direction.
2599
+
2600
+ Parameters
2601
+ ==========
2602
+
2603
+ p1 : Point3D
2604
+ The source of the Ray
2605
+ p2 : Point or a direction vector
2606
+ direction_ratio: Determines the direction in which the Ray propagates.
2607
+
2608
+
2609
+ Attributes
2610
+ ==========
2611
+
2612
+ source
2613
+ xdirection
2614
+ ydirection
2615
+ zdirection
2616
+
2617
+ See Also
2618
+ ========
2619
+
2620
+ sympy.geometry.point.Point3D, Line3D
2621
+
2622
+
2623
+ Examples
2624
+ ========
2625
+
2626
+ >>> from sympy import Point3D, Ray3D
2627
+ >>> r = Ray3D(Point3D(2, 3, 4), Point3D(3, 5, 0))
2628
+ >>> r
2629
+ Ray3D(Point3D(2, 3, 4), Point3D(3, 5, 0))
2630
+ >>> r.points
2631
+ (Point3D(2, 3, 4), Point3D(3, 5, 0))
2632
+ >>> r.source
2633
+ Point3D(2, 3, 4)
2634
+ >>> r.xdirection
2635
+ oo
2636
+ >>> r.ydirection
2637
+ oo
2638
+ >>> r.direction_ratio
2639
+ [1, 2, -4]
2640
+
2641
+ """
2642
+ def __new__(cls, p1, pt=None, direction_ratio=(), **kwargs):
2643
+ if isinstance(p1, LinearEntity3D):
2644
+ if pt is not None:
2645
+ raise ValueError('If p1 is a LinearEntity, pt must be None')
2646
+ p1, pt = p1.args
2647
+ else:
2648
+ p1 = Point(p1, dim=3)
2649
+ if pt is not None and len(direction_ratio) == 0:
2650
+ pt = Point(pt, dim=3)
2651
+ elif len(direction_ratio) == 3 and pt is None:
2652
+ pt = Point3D(p1.x + direction_ratio[0], p1.y + direction_ratio[1],
2653
+ p1.z + direction_ratio[2])
2654
+ else:
2655
+ raise ValueError(filldedent('''
2656
+ A 2nd Point or keyword "direction_ratio" must be used.
2657
+ '''))
2658
+
2659
+ return LinearEntity3D.__new__(cls, p1, pt, **kwargs)
2660
+
2661
+ @property
2662
+ def xdirection(self):
2663
+ """The x direction of the ray.
2664
+
2665
+ Positive infinity if the ray points in the positive x direction,
2666
+ negative infinity if the ray points in the negative x direction,
2667
+ or 0 if the ray is vertical.
2668
+
2669
+ See Also
2670
+ ========
2671
+
2672
+ ydirection
2673
+
2674
+ Examples
2675
+ ========
2676
+
2677
+ >>> from sympy import Point3D, Ray3D
2678
+ >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(0, -1, 0)
2679
+ >>> r1, r2 = Ray3D(p1, p2), Ray3D(p1, p3)
2680
+ >>> r1.xdirection
2681
+ oo
2682
+ >>> r2.xdirection
2683
+ 0
2684
+
2685
+ """
2686
+ if self.p1.x < self.p2.x:
2687
+ return S.Infinity
2688
+ elif self.p1.x == self.p2.x:
2689
+ return S.Zero
2690
+ else:
2691
+ return S.NegativeInfinity
2692
+
2693
+ @property
2694
+ def ydirection(self):
2695
+ """The y direction of the ray.
2696
+
2697
+ Positive infinity if the ray points in the positive y direction,
2698
+ negative infinity if the ray points in the negative y direction,
2699
+ or 0 if the ray is horizontal.
2700
+
2701
+ See Also
2702
+ ========
2703
+
2704
+ xdirection
2705
+
2706
+ Examples
2707
+ ========
2708
+
2709
+ >>> from sympy import Point3D, Ray3D
2710
+ >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(-1, -1, -1), Point3D(-1, 0, 0)
2711
+ >>> r1, r2 = Ray3D(p1, p2), Ray3D(p1, p3)
2712
+ >>> r1.ydirection
2713
+ -oo
2714
+ >>> r2.ydirection
2715
+ 0
2716
+
2717
+ """
2718
+ if self.p1.y < self.p2.y:
2719
+ return S.Infinity
2720
+ elif self.p1.y == self.p2.y:
2721
+ return S.Zero
2722
+ else:
2723
+ return S.NegativeInfinity
2724
+
2725
+ @property
2726
+ def zdirection(self):
2727
+ """The z direction of the ray.
2728
+
2729
+ Positive infinity if the ray points in the positive z direction,
2730
+ negative infinity if the ray points in the negative z direction,
2731
+ or 0 if the ray is horizontal.
2732
+
2733
+ See Also
2734
+ ========
2735
+
2736
+ xdirection
2737
+
2738
+ Examples
2739
+ ========
2740
+
2741
+ >>> from sympy import Point3D, Ray3D
2742
+ >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(-1, -1, -1), Point3D(-1, 0, 0)
2743
+ >>> r1, r2 = Ray3D(p1, p2), Ray3D(p1, p3)
2744
+ >>> r1.ydirection
2745
+ -oo
2746
+ >>> r2.ydirection
2747
+ 0
2748
+ >>> r2.zdirection
2749
+ 0
2750
+
2751
+ """
2752
+ if self.p1.z < self.p2.z:
2753
+ return S.Infinity
2754
+ elif self.p1.z == self.p2.z:
2755
+ return S.Zero
2756
+ else:
2757
+ return S.NegativeInfinity
2758
+
2759
+
2760
+ class Segment3D(LinearEntity3D, Segment):
2761
+ """A line segment in a 3D space.
2762
+
2763
+ Parameters
2764
+ ==========
2765
+
2766
+ p1 : Point3D
2767
+ p2 : Point3D
2768
+
2769
+ Attributes
2770
+ ==========
2771
+
2772
+ length : number or SymPy expression
2773
+ midpoint : Point3D
2774
+
2775
+ See Also
2776
+ ========
2777
+
2778
+ sympy.geometry.point.Point3D, Line3D
2779
+
2780
+ Examples
2781
+ ========
2782
+
2783
+ >>> from sympy import Point3D, Segment3D
2784
+ >>> Segment3D((1, 0, 0), (1, 1, 1)) # tuples are interpreted as pts
2785
+ Segment3D(Point3D(1, 0, 0), Point3D(1, 1, 1))
2786
+ >>> s = Segment3D(Point3D(4, 3, 9), Point3D(1, 1, 7)); s
2787
+ Segment3D(Point3D(4, 3, 9), Point3D(1, 1, 7))
2788
+ >>> s.points
2789
+ (Point3D(4, 3, 9), Point3D(1, 1, 7))
2790
+ >>> s.length
2791
+ sqrt(17)
2792
+ >>> s.midpoint
2793
+ Point3D(5/2, 2, 8)
2794
+
2795
+ """
2796
+ def __new__(cls, p1, p2, **kwargs):
2797
+ p1 = Point(p1, dim=3)
2798
+ p2 = Point(p2, dim=3)
2799
+
2800
+ if p1 == p2:
2801
+ return p1
2802
+
2803
+ return LinearEntity3D.__new__(cls, p1, p2, **kwargs)
llmeval-env/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
llmeval-env/lib/python3.10/site-packages/sympy/geometry/plane.py ADDED
@@ -0,0 +1,884 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 three non-collinear points and a point and the plane's
36
+ normal vector.
37
+
38
+ Attributes
39
+ ==========
40
+
41
+ p1
42
+ normal_vector
43
+
44
+ Examples
45
+ ========
46
+
47
+ >>> from sympy import Plane, Point3D
48
+ >>> Plane(Point3D(1, 1, 1), Point3D(2, 3, 4), Point3D(2, 2, 2))
49
+ Plane(Point3D(1, 1, 1), (-1, 2, -1))
50
+ >>> Plane((1, 1, 1), (2, 3, 4), (2, 2, 2))
51
+ Plane(Point3D(1, 1, 1), (-1, 2, -1))
52
+ >>> Plane(Point3D(1, 1, 1), normal_vector=(1,4,7))
53
+ Plane(Point3D(1, 1, 1), (1, 4, 7))
54
+
55
+ """
56
+ def __new__(cls, p1, a=None, b=None, **kwargs):
57
+ p1 = Point3D(p1, dim=3)
58
+ if a and b:
59
+ p2 = Point(a, dim=3)
60
+ p3 = Point(b, dim=3)
61
+ if Point3D.are_collinear(p1, p2, p3):
62
+ raise ValueError('Enter three non-collinear points')
63
+ a = p1.direction_ratio(p2)
64
+ b = p1.direction_ratio(p3)
65
+ normal_vector = tuple(Matrix(a).cross(Matrix(b)))
66
+ else:
67
+ a = kwargs.pop('normal_vector', a)
68
+ evaluate = kwargs.get('evaluate', True)
69
+ if is_sequence(a) and len(a) == 3:
70
+ normal_vector = Point3D(a).args if evaluate else a
71
+ else:
72
+ raise ValueError(filldedent('''
73
+ Either provide 3 3D points or a point with a
74
+ normal vector expressed as a sequence of length 3'''))
75
+ if all(coord.is_zero for coord in normal_vector):
76
+ raise ValueError('Normal vector cannot be zero vector')
77
+ return GeometryEntity.__new__(cls, p1, normal_vector, **kwargs)
78
+
79
+ def __contains__(self, o):
80
+ k = self.equation(x, y, z)
81
+ if isinstance(o, (LinearEntity, LinearEntity3D)):
82
+ d = Point3D(o.arbitrary_point(t))
83
+ e = k.subs([(x, d.x), (y, d.y), (z, d.z)])
84
+ return e.equals(0)
85
+ try:
86
+ o = Point(o, dim=3, strict=True)
87
+ d = k.xreplace(dict(zip((x, y, z), o.args)))
88
+ return d.equals(0)
89
+ except TypeError:
90
+ return False
91
+
92
+ def _eval_evalf(self, prec=15, **options):
93
+ pt, tup = self.args
94
+ dps = prec_to_dps(prec)
95
+ pt = pt.evalf(n=dps, **options)
96
+ tup = tuple([i.evalf(n=dps, **options) for i in tup])
97
+ return self.func(pt, normal_vector=tup, evaluate=False)
98
+
99
+ def angle_between(self, o):
100
+ """Angle between the plane and other geometric entity.
101
+
102
+ Parameters
103
+ ==========
104
+
105
+ LinearEntity3D, Plane.
106
+
107
+ Returns
108
+ =======
109
+
110
+ angle : angle in radians
111
+
112
+ Notes
113
+ =====
114
+
115
+ This method accepts only 3D entities as it's parameter, but if you want
116
+ to calculate the angle between a 2D entity and a plane you should
117
+ first convert to a 3D entity by projecting onto a desired plane and
118
+ then proceed to calculate the angle.
119
+
120
+ Examples
121
+ ========
122
+
123
+ >>> from sympy import Point3D, Line3D, Plane
124
+ >>> a = Plane(Point3D(1, 2, 2), normal_vector=(1, 2, 3))
125
+ >>> b = Line3D(Point3D(1, 3, 4), Point3D(2, 2, 2))
126
+ >>> a.angle_between(b)
127
+ -asin(sqrt(21)/6)
128
+
129
+ """
130
+ if isinstance(o, LinearEntity3D):
131
+ a = Matrix(self.normal_vector)
132
+ b = Matrix(o.direction_ratio)
133
+ c = a.dot(b)
134
+ d = sqrt(sum([i**2 for i in self.normal_vector]))
135
+ e = sqrt(sum([i**2 for i in o.direction_ratio]))
136
+ return asin(c/(d*e))
137
+ if isinstance(o, Plane):
138
+ a = Matrix(self.normal_vector)
139
+ b = Matrix(o.normal_vector)
140
+ c = a.dot(b)
141
+ d = sqrt(sum([i**2 for i in self.normal_vector]))
142
+ e = sqrt(sum([i**2 for i in o.normal_vector]))
143
+ return acos(c/(d*e))
144
+
145
+
146
+ def arbitrary_point(self, u=None, v=None):
147
+ """ Returns an arbitrary point on the Plane. If given two
148
+ parameters, the point ranges over the entire plane. If given 1
149
+ or no parameters, returns a point with one parameter which,
150
+ when varying from 0 to 2*pi, moves the point in a circle of
151
+ radius 1 about p1 of the Plane.
152
+
153
+ Examples
154
+ ========
155
+
156
+ >>> from sympy import Plane, Ray
157
+ >>> from sympy.abc import u, v, t, r
158
+ >>> p = Plane((1, 1, 1), normal_vector=(1, 0, 0))
159
+ >>> p.arbitrary_point(u, v)
160
+ Point3D(1, u + 1, v + 1)
161
+ >>> p.arbitrary_point(t)
162
+ Point3D(1, cos(t) + 1, sin(t) + 1)
163
+
164
+ While arbitrary values of u and v can move the point anywhere in
165
+ the plane, the single-parameter point can be used to construct a
166
+ ray whose arbitrary point can be located at angle t and radius
167
+ r from p.p1:
168
+
169
+ >>> Ray(p.p1, _).arbitrary_point(r)
170
+ Point3D(1, r*cos(t) + 1, r*sin(t) + 1)
171
+
172
+ Returns
173
+ =======
174
+
175
+ Point3D
176
+
177
+ """
178
+ circle = v is None
179
+ if circle:
180
+ u = _symbol(u or 't', real=True)
181
+ else:
182
+ u = _symbol(u or 'u', real=True)
183
+ v = _symbol(v or 'v', real=True)
184
+ x, y, z = self.normal_vector
185
+ a, b, c = self.p1.args
186
+ # x1, y1, z1 is a nonzero vector parallel to the plane
187
+ if x.is_zero and y.is_zero:
188
+ x1, y1, z1 = S.One, S.Zero, S.Zero
189
+ else:
190
+ x1, y1, z1 = -y, x, S.Zero
191
+ # x2, y2, z2 is also parallel to the plane, and orthogonal to x1, y1, z1
192
+ x2, y2, z2 = tuple(Matrix((x, y, z)).cross(Matrix((x1, y1, z1))))
193
+ if circle:
194
+ x1, y1, z1 = (w/sqrt(x1**2 + y1**2 + z1**2) for w in (x1, y1, z1))
195
+ x2, y2, z2 = (w/sqrt(x2**2 + y2**2 + z2**2) for w in (x2, y2, z2))
196
+ p = Point3D(a + x1*cos(u) + x2*sin(u), \
197
+ b + y1*cos(u) + y2*sin(u), \
198
+ c + z1*cos(u) + z2*sin(u))
199
+ else:
200
+ p = Point3D(a + x1*u + x2*v, b + y1*u + y2*v, c + z1*u + z2*v)
201
+ return p
202
+
203
+
204
+ @staticmethod
205
+ def are_concurrent(*planes):
206
+ """Is a sequence of Planes concurrent?
207
+
208
+ Two or more Planes are concurrent if their intersections
209
+ are a common line.
210
+
211
+ Parameters
212
+ ==========
213
+
214
+ planes: list
215
+
216
+ Returns
217
+ =======
218
+
219
+ Boolean
220
+
221
+ Examples
222
+ ========
223
+
224
+ >>> from sympy import Plane, Point3D
225
+ >>> a = Plane(Point3D(5, 0, 0), normal_vector=(1, -1, 1))
226
+ >>> b = Plane(Point3D(0, -2, 0), normal_vector=(3, 1, 1))
227
+ >>> c = Plane(Point3D(0, -1, 0), normal_vector=(5, -1, 9))
228
+ >>> Plane.are_concurrent(a, b)
229
+ True
230
+ >>> Plane.are_concurrent(a, b, c)
231
+ False
232
+
233
+ """
234
+ planes = list(uniq(planes))
235
+ for i in planes:
236
+ if not isinstance(i, Plane):
237
+ raise ValueError('All objects should be Planes but got %s' % i.func)
238
+ if len(planes) < 2:
239
+ return False
240
+ planes = list(planes)
241
+ first = planes.pop(0)
242
+ sol = first.intersection(planes[0])
243
+ if sol == []:
244
+ return False
245
+ else:
246
+ line = sol[0]
247
+ for i in planes[1:]:
248
+ l = first.intersection(i)
249
+ if not l or l[0] not in line:
250
+ return False
251
+ return True
252
+
253
+
254
+ def distance(self, o):
255
+ """Distance between the plane and another geometric entity.
256
+
257
+ Parameters
258
+ ==========
259
+
260
+ Point3D, LinearEntity3D, Plane.
261
+
262
+ Returns
263
+ =======
264
+
265
+ distance
266
+
267
+ Notes
268
+ =====
269
+
270
+ This method accepts only 3D entities as it's parameter, but if you want
271
+ to calculate the distance between a 2D entity and a plane you should
272
+ first convert to a 3D entity by projecting onto a desired plane and
273
+ then proceed to calculate the distance.
274
+
275
+ Examples
276
+ ========
277
+
278
+ >>> from sympy import Point3D, Line3D, Plane
279
+ >>> a = Plane(Point3D(1, 1, 1), normal_vector=(1, 1, 1))
280
+ >>> b = Point3D(1, 2, 3)
281
+ >>> a.distance(b)
282
+ sqrt(3)
283
+ >>> c = Line3D(Point3D(2, 3, 1), Point3D(1, 2, 2))
284
+ >>> a.distance(c)
285
+ 0
286
+
287
+ """
288
+ if self.intersection(o) != []:
289
+ return S.Zero
290
+
291
+ if isinstance(o, (Segment3D, Ray3D)):
292
+ a, b = o.p1, o.p2
293
+ pi, = self.intersection(Line3D(a, b))
294
+ if pi in o:
295
+ return self.distance(pi)
296
+ elif a in Segment3D(pi, b):
297
+ return self.distance(a)
298
+ else:
299
+ assert isinstance(o, Segment3D) is True
300
+ return self.distance(b)
301
+
302
+ # following code handles `Point3D`, `LinearEntity3D`, `Plane`
303
+ a = o if isinstance(o, Point3D) else o.p1
304
+ n = Point3D(self.normal_vector).unit
305
+ d = (a - self.p1).dot(n)
306
+ return abs(d)
307
+
308
+
309
+ def equals(self, o):
310
+ """
311
+ Returns True if self and o are the same mathematical entities.
312
+
313
+ Examples
314
+ ========
315
+
316
+ >>> from sympy import Plane, Point3D
317
+ >>> a = Plane(Point3D(1, 2, 3), normal_vector=(1, 1, 1))
318
+ >>> b = Plane(Point3D(1, 2, 3), normal_vector=(2, 2, 2))
319
+ >>> c = Plane(Point3D(1, 2, 3), normal_vector=(-1, 4, 6))
320
+ >>> a.equals(a)
321
+ True
322
+ >>> a.equals(b)
323
+ True
324
+ >>> a.equals(c)
325
+ False
326
+ """
327
+ if isinstance(o, Plane):
328
+ a = self.equation()
329
+ b = o.equation()
330
+ return cancel(a/b).is_constant()
331
+ else:
332
+ return False
333
+
334
+
335
+ def equation(self, x=None, y=None, z=None):
336
+ """The equation of the Plane.
337
+
338
+ Examples
339
+ ========
340
+
341
+ >>> from sympy import Point3D, Plane
342
+ >>> a = Plane(Point3D(1, 1, 2), Point3D(2, 4, 7), Point3D(3, 5, 1))
343
+ >>> a.equation()
344
+ -23*x + 11*y - 2*z + 16
345
+ >>> a = Plane(Point3D(1, 4, 2), normal_vector=(6, 6, 6))
346
+ >>> a.equation()
347
+ 6*x + 6*y + 6*z - 42
348
+
349
+ """
350
+ x, y, z = [i if i else Symbol(j, real=True) for i, j in zip((x, y, z), 'xyz')]
351
+ a = Point3D(x, y, z)
352
+ b = self.p1.direction_ratio(a)
353
+ c = self.normal_vector
354
+ return (sum(i*j for i, j in zip(b, c)))
355
+
356
+
357
+ def intersection(self, o):
358
+ """ The intersection with other geometrical entity.
359
+
360
+ Parameters
361
+ ==========
362
+
363
+ Point, Point3D, LinearEntity, LinearEntity3D, Plane
364
+
365
+ Returns
366
+ =======
367
+
368
+ List
369
+
370
+ Examples
371
+ ========
372
+
373
+ >>> from sympy import Point3D, Line3D, Plane
374
+ >>> a = Plane(Point3D(1, 2, 3), normal_vector=(1, 1, 1))
375
+ >>> b = Point3D(1, 2, 3)
376
+ >>> a.intersection(b)
377
+ [Point3D(1, 2, 3)]
378
+ >>> c = Line3D(Point3D(1, 4, 7), Point3D(2, 2, 2))
379
+ >>> a.intersection(c)
380
+ [Point3D(2, 2, 2)]
381
+ >>> d = Plane(Point3D(6, 0, 0), normal_vector=(2, -5, 3))
382
+ >>> e = Plane(Point3D(2, 0, 0), normal_vector=(3, 4, -3))
383
+ >>> d.intersection(e)
384
+ [Line3D(Point3D(78/23, -24/23, 0), Point3D(147/23, 321/23, 23))]
385
+
386
+ """
387
+ if not isinstance(o, GeometryEntity):
388
+ o = Point(o, dim=3)
389
+ if isinstance(o, Point):
390
+ if o in self:
391
+ return [o]
392
+ else:
393
+ return []
394
+ if isinstance(o, (LinearEntity, LinearEntity3D)):
395
+ # recast to 3D
396
+ p1, p2 = o.p1, o.p2
397
+ if isinstance(o, Segment):
398
+ o = Segment3D(p1, p2)
399
+ elif isinstance(o, Ray):
400
+ o = Ray3D(p1, p2)
401
+ elif isinstance(o, Line):
402
+ o = Line3D(p1, p2)
403
+ else:
404
+ raise ValueError('unhandled linear entity: %s' % o.func)
405
+ if o in self:
406
+ return [o]
407
+ else:
408
+ a = Point3D(o.arbitrary_point(t))
409
+ p1, n = self.p1, Point3D(self.normal_vector)
410
+
411
+ # TODO: Replace solve with solveset, when this line is tested
412
+ c = solve((a - p1).dot(n), t)
413
+ if not c:
414
+ return []
415
+ else:
416
+ c = [i for i in c if i.is_real is not False]
417
+ if len(c) > 1:
418
+ c = [i for i in c if i.is_real]
419
+ if len(c) != 1:
420
+ raise Undecidable("not sure which point is real")
421
+ p = a.subs(t, c[0])
422
+ if p not in o:
423
+ return [] # e.g. a segment might not intersect a plane
424
+ return [p]
425
+ if isinstance(o, Plane):
426
+ if self.equals(o):
427
+ return [self]
428
+ if self.is_parallel(o):
429
+ return []
430
+ else:
431
+ x, y, z = map(Dummy, 'xyz')
432
+ a, b = Matrix([self.normal_vector]), Matrix([o.normal_vector])
433
+ c = list(a.cross(b))
434
+ d = self.equation(x, y, z)
435
+ e = o.equation(x, y, z)
436
+ result = list(linsolve([d, e], x, y, z))[0]
437
+ for i in (x, y, z): result = result.subs(i, 0)
438
+ return [Line3D(Point3D(result), direction_ratio=c)]
439
+
440
+
441
+ def is_coplanar(self, o):
442
+ """ Returns True if `o` is coplanar with self, else False.
443
+
444
+ Examples
445
+ ========
446
+
447
+ >>> from sympy import Plane
448
+ >>> o = (0, 0, 0)
449
+ >>> p = Plane(o, (1, 1, 1))
450
+ >>> p2 = Plane(o, (2, 2, 2))
451
+ >>> p == p2
452
+ False
453
+ >>> p.is_coplanar(p2)
454
+ True
455
+ """
456
+ if isinstance(o, Plane):
457
+ return not cancel(self.equation(x, y, z)/o.equation(x, y, z)).has(x, y, z)
458
+ if isinstance(o, Point3D):
459
+ return o in self
460
+ elif isinstance(o, LinearEntity3D):
461
+ return all(i in self for i in self)
462
+ elif isinstance(o, GeometryEntity): # XXX should only be handling 2D objects now
463
+ return all(i == 0 for i in self.normal_vector[:2])
464
+
465
+
466
+ def is_parallel(self, l):
467
+ """Is the given geometric entity parallel to the plane?
468
+
469
+ Parameters
470
+ ==========
471
+
472
+ LinearEntity3D or Plane
473
+
474
+ Returns
475
+ =======
476
+
477
+ Boolean
478
+
479
+ Examples
480
+ ========
481
+
482
+ >>> from sympy import Plane, Point3D
483
+ >>> a = Plane(Point3D(1,4,6), normal_vector=(2, 4, 6))
484
+ >>> b = Plane(Point3D(3,1,3), normal_vector=(4, 8, 12))
485
+ >>> a.is_parallel(b)
486
+ True
487
+
488
+ """
489
+ if isinstance(l, LinearEntity3D):
490
+ a = l.direction_ratio
491
+ b = self.normal_vector
492
+ c = sum([i*j for i, j in zip(a, b)])
493
+ if c == 0:
494
+ return True
495
+ else:
496
+ return False
497
+ elif isinstance(l, Plane):
498
+ a = Matrix(l.normal_vector)
499
+ b = Matrix(self.normal_vector)
500
+ if a.cross(b).is_zero_matrix:
501
+ return True
502
+ else:
503
+ return False
504
+
505
+
506
+ def is_perpendicular(self, l):
507
+ """Is the given geometric entity perpendicualar to the given plane?
508
+
509
+ Parameters
510
+ ==========
511
+
512
+ LinearEntity3D or Plane
513
+
514
+ Returns
515
+ =======
516
+
517
+ Boolean
518
+
519
+ Examples
520
+ ========
521
+
522
+ >>> from sympy import Plane, Point3D
523
+ >>> a = Plane(Point3D(1,4,6), normal_vector=(2, 4, 6))
524
+ >>> b = Plane(Point3D(2, 2, 2), normal_vector=(-1, 2, -1))
525
+ >>> a.is_perpendicular(b)
526
+ True
527
+
528
+ """
529
+ if isinstance(l, LinearEntity3D):
530
+ a = Matrix(l.direction_ratio)
531
+ b = Matrix(self.normal_vector)
532
+ if a.cross(b).is_zero_matrix:
533
+ return True
534
+ else:
535
+ return False
536
+ elif isinstance(l, Plane):
537
+ a = Matrix(l.normal_vector)
538
+ b = Matrix(self.normal_vector)
539
+ if a.dot(b) == 0:
540
+ return True
541
+ else:
542
+ return False
543
+ else:
544
+ return False
545
+
546
+ @property
547
+ def normal_vector(self):
548
+ """Normal vector of the given plane.
549
+
550
+ Examples
551
+ ========
552
+
553
+ >>> from sympy import Point3D, Plane
554
+ >>> a = Plane(Point3D(1, 1, 1), Point3D(2, 3, 4), Point3D(2, 2, 2))
555
+ >>> a.normal_vector
556
+ (-1, 2, -1)
557
+ >>> a = Plane(Point3D(1, 1, 1), normal_vector=(1, 4, 7))
558
+ >>> a.normal_vector
559
+ (1, 4, 7)
560
+
561
+ """
562
+ return self.args[1]
563
+
564
+ @property
565
+ def p1(self):
566
+ """The only defining point of the plane. Others can be obtained from the
567
+ arbitrary_point method.
568
+
569
+ See Also
570
+ ========
571
+
572
+ sympy.geometry.point.Point3D
573
+
574
+ Examples
575
+ ========
576
+
577
+ >>> from sympy import Point3D, Plane
578
+ >>> a = Plane(Point3D(1, 1, 1), Point3D(2, 3, 4), Point3D(2, 2, 2))
579
+ >>> a.p1
580
+ Point3D(1, 1, 1)
581
+
582
+ """
583
+ return self.args[0]
584
+
585
+ def parallel_plane(self, pt):
586
+ """
587
+ Plane parallel to the given plane and passing through the point pt.
588
+
589
+ Parameters
590
+ ==========
591
+
592
+ pt: Point3D
593
+
594
+ Returns
595
+ =======
596
+
597
+ Plane
598
+
599
+ Examples
600
+ ========
601
+
602
+ >>> from sympy import Plane, Point3D
603
+ >>> a = Plane(Point3D(1, 4, 6), normal_vector=(2, 4, 6))
604
+ >>> a.parallel_plane(Point3D(2, 3, 5))
605
+ Plane(Point3D(2, 3, 5), (2, 4, 6))
606
+
607
+ """
608
+ a = self.normal_vector
609
+ return Plane(pt, normal_vector=a)
610
+
611
+ def perpendicular_line(self, pt):
612
+ """A line perpendicular to the given plane.
613
+
614
+ Parameters
615
+ ==========
616
+
617
+ pt: Point3D
618
+
619
+ Returns
620
+ =======
621
+
622
+ Line3D
623
+
624
+ Examples
625
+ ========
626
+
627
+ >>> from sympy import Plane, Point3D
628
+ >>> a = Plane(Point3D(1,4,6), normal_vector=(2, 4, 6))
629
+ >>> a.perpendicular_line(Point3D(9, 8, 7))
630
+ Line3D(Point3D(9, 8, 7), Point3D(11, 12, 13))
631
+
632
+ """
633
+ a = self.normal_vector
634
+ return Line3D(pt, direction_ratio=a)
635
+
636
+ def perpendicular_plane(self, *pts):
637
+ """
638
+ Return a perpendicular passing through the given points. If the
639
+ direction ratio between the points is the same as the Plane's normal
640
+ vector then, to select from the infinite number of possible planes,
641
+ a third point will be chosen on the z-axis (or the y-axis
642
+ if the normal vector is already parallel to the z-axis). If less than
643
+ two points are given they will be supplied as follows: if no point is
644
+ given then pt1 will be self.p1; if a second point is not given it will
645
+ be a point through pt1 on a line parallel to the z-axis (if the normal
646
+ is not already the z-axis, otherwise on the line parallel to the
647
+ y-axis).
648
+
649
+ Parameters
650
+ ==========
651
+
652
+ pts: 0, 1 or 2 Point3D
653
+
654
+ Returns
655
+ =======
656
+
657
+ Plane
658
+
659
+ Examples
660
+ ========
661
+
662
+ >>> from sympy import Plane, Point3D
663
+ >>> a, b = Point3D(0, 0, 0), Point3D(0, 1, 0)
664
+ >>> Z = (0, 0, 1)
665
+ >>> p = Plane(a, normal_vector=Z)
666
+ >>> p.perpendicular_plane(a, b)
667
+ Plane(Point3D(0, 0, 0), (1, 0, 0))
668
+ """
669
+ if len(pts) > 2:
670
+ raise ValueError('No more than 2 pts should be provided.')
671
+
672
+ pts = list(pts)
673
+ if len(pts) == 0:
674
+ pts.append(self.p1)
675
+ if len(pts) == 1:
676
+ x, y, z = self.normal_vector
677
+ if x == y == 0:
678
+ dir = (0, 1, 0)
679
+ else:
680
+ dir = (0, 0, 1)
681
+ pts.append(pts[0] + Point3D(*dir))
682
+
683
+ p1, p2 = [Point(i, dim=3) for i in pts]
684
+ l = Line3D(p1, p2)
685
+ n = Line3D(p1, direction_ratio=self.normal_vector)
686
+ if l in n: # XXX should an error be raised instead?
687
+ # there are infinitely many perpendicular planes;
688
+ x, y, z = self.normal_vector
689
+ if x == y == 0:
690
+ # the z axis is the normal so pick a pt on the y-axis
691
+ p3 = Point3D(0, 1, 0) # case 1
692
+ else:
693
+ # else pick a pt on the z axis
694
+ p3 = Point3D(0, 0, 1) # case 2
695
+ # in case that point is already given, move it a bit
696
+ if p3 in l:
697
+ p3 *= 2 # case 3
698
+ else:
699
+ p3 = p1 + Point3D(*self.normal_vector) # case 4
700
+ return Plane(p1, p2, p3)
701
+
702
+ def projection_line(self, line):
703
+ """Project the given line onto the plane through the normal plane
704
+ containing the line.
705
+
706
+ Parameters
707
+ ==========
708
+
709
+ LinearEntity or LinearEntity3D
710
+
711
+ Returns
712
+ =======
713
+
714
+ Point3D, Line3D, Ray3D or Segment3D
715
+
716
+ Notes
717
+ =====
718
+
719
+ For the interaction between 2D and 3D lines(segments, rays), you should
720
+ convert the line to 3D by using this method. For example for finding the
721
+ intersection between a 2D and a 3D line, convert the 2D line to a 3D line
722
+ by projecting it on a required plane and then proceed to find the
723
+ intersection between those lines.
724
+
725
+ Examples
726
+ ========
727
+
728
+ >>> from sympy import Plane, Line, Line3D, Point3D
729
+ >>> a = Plane(Point3D(1, 1, 1), normal_vector=(1, 1, 1))
730
+ >>> b = Line(Point3D(1, 1), Point3D(2, 2))
731
+ >>> a.projection_line(b)
732
+ Line3D(Point3D(4/3, 4/3, 1/3), Point3D(5/3, 5/3, -1/3))
733
+ >>> c = Line3D(Point3D(1, 1, 1), Point3D(2, 2, 2))
734
+ >>> a.projection_line(c)
735
+ Point3D(1, 1, 1)
736
+
737
+ """
738
+ if not isinstance(line, (LinearEntity, LinearEntity3D)):
739
+ raise NotImplementedError('Enter a linear entity only')
740
+ a, b = self.projection(line.p1), self.projection(line.p2)
741
+ if a == b:
742
+ # projection does not imply intersection so for
743
+ # this case (line parallel to plane's normal) we
744
+ # return the projection point
745
+ return a
746
+ if isinstance(line, (Line, Line3D)):
747
+ return Line3D(a, b)
748
+ if isinstance(line, (Ray, Ray3D)):
749
+ return Ray3D(a, b)
750
+ if isinstance(line, (Segment, Segment3D)):
751
+ return Segment3D(a, b)
752
+
753
+ def projection(self, pt):
754
+ """Project the given point onto the plane along the plane normal.
755
+
756
+ Parameters
757
+ ==========
758
+
759
+ Point or Point3D
760
+
761
+ Returns
762
+ =======
763
+
764
+ Point3D
765
+
766
+ Examples
767
+ ========
768
+
769
+ >>> from sympy import Plane, Point3D
770
+ >>> A = Plane(Point3D(1, 1, 2), normal_vector=(1, 1, 1))
771
+
772
+ The projection is along the normal vector direction, not the z
773
+ axis, so (1, 1) does not project to (1, 1, 2) on the plane A:
774
+
775
+ >>> b = Point3D(1, 1)
776
+ >>> A.projection(b)
777
+ Point3D(5/3, 5/3, 2/3)
778
+ >>> _ in A
779
+ True
780
+
781
+ But the point (1, 1, 2) projects to (1, 1) on the XY-plane:
782
+
783
+ >>> XY = Plane((0, 0, 0), (0, 0, 1))
784
+ >>> XY.projection((1, 1, 2))
785
+ Point3D(1, 1, 0)
786
+ """
787
+ rv = Point(pt, dim=3)
788
+ if rv in self:
789
+ return rv
790
+ return self.intersection(Line3D(rv, rv + Point3D(self.normal_vector)))[0]
791
+
792
+ def random_point(self, seed=None):
793
+ """ Returns a random point on the Plane.
794
+
795
+ Returns
796
+ =======
797
+
798
+ Point3D
799
+
800
+ Examples
801
+ ========
802
+
803
+ >>> from sympy import Plane
804
+ >>> p = Plane((1, 0, 0), normal_vector=(0, 1, 0))
805
+ >>> r = p.random_point(seed=42) # seed value is optional
806
+ >>> r.n(3)
807
+ Point3D(2.29, 0, -1.35)
808
+
809
+ The random point can be moved to lie on the circle of radius
810
+ 1 centered on p1:
811
+
812
+ >>> c = p.p1 + (r - p.p1).unit
813
+ >>> c.distance(p.p1).equals(1)
814
+ True
815
+ """
816
+ if seed is not None:
817
+ rng = random.Random(seed)
818
+ else:
819
+ rng = random
820
+ params = {
821
+ x: 2*Rational(rng.gauss(0, 1)) - 1,
822
+ y: 2*Rational(rng.gauss(0, 1)) - 1}
823
+ return self.arbitrary_point(x, y).subs(params)
824
+
825
+ def parameter_value(self, other, u, v=None):
826
+ """Return the parameter(s) corresponding to the given point.
827
+
828
+ Examples
829
+ ========
830
+
831
+ >>> from sympy import pi, Plane
832
+ >>> from sympy.abc import t, u, v
833
+ >>> p = Plane((2, 0, 0), (0, 0, 1), (0, 1, 0))
834
+
835
+ By default, the parameter value returned defines a point
836
+ that is a distance of 1 from the Plane's p1 value and
837
+ in line with the given point:
838
+
839
+ >>> on_circle = p.arbitrary_point(t).subs(t, pi/4)
840
+ >>> on_circle.distance(p.p1)
841
+ 1
842
+ >>> p.parameter_value(on_circle, t)
843
+ {t: pi/4}
844
+
845
+ Moving the point twice as far from p1 does not change
846
+ the parameter value:
847
+
848
+ >>> off_circle = p.p1 + (on_circle - p.p1)*2
849
+ >>> off_circle.distance(p.p1)
850
+ 2
851
+ >>> p.parameter_value(off_circle, t)
852
+ {t: pi/4}
853
+
854
+ If the 2-value parameter is desired, supply the two
855
+ parameter symbols and a replacement dictionary will
856
+ be returned:
857
+
858
+ >>> p.parameter_value(on_circle, u, v)
859
+ {u: sqrt(10)/10, v: sqrt(10)/30}
860
+ >>> p.parameter_value(off_circle, u, v)
861
+ {u: sqrt(10)/5, v: sqrt(10)/15}
862
+ """
863
+ if not isinstance(other, GeometryEntity):
864
+ other = Point(other, dim=self.ambient_dimension)
865
+ if not isinstance(other, Point):
866
+ raise ValueError("other must be a point")
867
+ if other == self.p1:
868
+ return other
869
+ if isinstance(u, Symbol) and v is None:
870
+ delta = self.arbitrary_point(u) - self.p1
871
+ eq = delta - (other - self.p1).unit
872
+ sol = solve(eq, u, dict=True)
873
+ elif isinstance(u, Symbol) and isinstance(v, Symbol):
874
+ pt = self.arbitrary_point(u, v)
875
+ sol = solve(pt - other, (u, v), dict=True)
876
+ else:
877
+ raise ValueError('expecting 1 or 2 symbols')
878
+ if not sol:
879
+ raise ValueError("Given point is not on %s" % func_name(self))
880
+ return sol[0] # {t: tval} or {u: uval, v: vval}
881
+
882
+ @property
883
+ def ambient_dimension(self):
884
+ return self.p1.ambient_dimension
llmeval-env/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]
llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/__init__.py ADDED
File without changes
llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (193 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/test_curve.cpython-310.pyc ADDED
Binary file (5.26 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/test_ellipse.cpython-310.pyc ADDED
Binary file (23.6 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/test_entity.cpython-310.pyc ADDED
Binary file (4.42 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/test_geometrysets.cpython-310.pyc ADDED
Binary file (1.62 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/test_line.cpython-310.pyc ADDED
Binary file (31.1 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/test_parabola.cpython-310.pyc ADDED
Binary file (5.35 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/test_plane.cpython-310.pyc ADDED
Binary file (9.58 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/test_point.cpython-310.pyc ADDED
Binary file (15.7 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/test_polygon.cpython-310.pyc ADDED
Binary file (22.9 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/test_util.cpython-310.pyc ADDED
Binary file (6.5 kB). View file
 
llmeval-env/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)
llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/test_ellipse.py ADDED
@@ -0,0 +1,601 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import expand
2
+ from sympy.core.numbers import (Rational, oo, pi)
3
+ from sympy.core.relational import Eq
4
+ from sympy.core.singleton import S
5
+ from sympy.core.symbol import (Symbol, symbols)
6
+ from sympy.functions.elementary.complexes import Abs
7
+ from sympy.functions.elementary.miscellaneous import sqrt
8
+ from sympy.functions.elementary.trigonometric import sec
9
+ from sympy.geometry.line import Segment2D
10
+ from sympy.geometry.point import Point2D
11
+ from sympy.geometry import (Circle, Ellipse, GeometryError, Line, Point,
12
+ Polygon, Ray, RegularPolygon, Segment,
13
+ Triangle, intersection)
14
+ from sympy.testing.pytest import raises, slow
15
+ from sympy.integrals.integrals import integrate
16
+ from sympy.functions.special.elliptic_integrals import elliptic_e
17
+ from sympy.functions.elementary.miscellaneous import Max
18
+
19
+
20
+ def test_ellipse_equation_using_slope():
21
+ from sympy.abc import x, y
22
+
23
+ e1 = Ellipse(Point(1, 0), 3, 2)
24
+ assert str(e1.equation(_slope=1)) == str((-x + y + 1)**2/8 + (x + y - 1)**2/18 - 1)
25
+
26
+ e2 = Ellipse(Point(0, 0), 4, 1)
27
+ assert str(e2.equation(_slope=1)) == str((-x + y)**2/2 + (x + y)**2/32 - 1)
28
+
29
+ e3 = Ellipse(Point(1, 5), 6, 2)
30
+ assert str(e3.equation(_slope=2)) == str((-2*x + y - 3)**2/20 + (x + 2*y - 11)**2/180 - 1)
31
+
32
+
33
+ def test_object_from_equation():
34
+ from sympy.abc import x, y, a, b, c, d, e
35
+ assert Circle(x**2 + y**2 + 3*x + 4*y - 8) == Circle(Point2D(S(-3) / 2, -2), sqrt(57) / 2)
36
+ assert Circle(x**2 + y**2 + 6*x + 8*y + 25) == Circle(Point2D(-3, -4), 0)
37
+ assert Circle(a**2 + b**2 + 6*a + 8*b + 25, x='a', y='b') == Circle(Point2D(-3, -4), 0)
38
+ assert Circle(x**2 + y**2 - 25) == Circle(Point2D(0, 0), 5)
39
+ assert Circle(x**2 + y**2) == Circle(Point2D(0, 0), 0)
40
+ assert Circle(a**2 + b**2, x='a', y='b') == Circle(Point2D(0, 0), 0)
41
+ assert Circle(x**2 + y**2 + 6*x + 8) == Circle(Point2D(-3, 0), 1)
42
+ assert Circle(x**2 + y**2 + 6*y + 8) == Circle(Point2D(0, -3), 1)
43
+ assert Circle((x - 1)**2 + y**2 - 9) == Circle(Point2D(1, 0), 3)
44
+ assert Circle(6*(x**2) + 6*(y**2) + 6*x + 8*y - 25) == Circle(Point2D(Rational(-1, 2), Rational(-2, 3)), 5*sqrt(7)/6)
45
+ assert Circle(Eq(a**2 + b**2, 25), x='a', y=b) == Circle(Point2D(0, 0), 5)
46
+ raises(GeometryError, lambda: Circle(x**2 + y**2 + 3*x + 4*y + 26))
47
+ raises(GeometryError, lambda: Circle(x**2 + y**2 + 25))
48
+ raises(GeometryError, lambda: Circle(a**2 + b**2 + 25, x='a', y='b'))
49
+ raises(GeometryError, lambda: Circle(x**2 + 6*y + 8))
50
+ raises(GeometryError, lambda: Circle(6*(x ** 2) + 4*(y**2) + 6*x + 8*y + 25))
51
+ raises(ValueError, lambda: Circle(a**2 + b**2 + 3*a + 4*b - 8))
52
+ # .equation() adds 'real=True' assumption; '==' would fail if assumptions differed
53
+ x, y = symbols('x y', real=True)
54
+ eq = a*x**2 + a*y**2 + c*x + d*y + e
55
+ assert expand(Circle(eq).equation()*a) == eq
56
+
57
+
58
+ @slow
59
+ def test_ellipse_geom():
60
+ x = Symbol('x', real=True)
61
+ y = Symbol('y', real=True)
62
+ t = Symbol('t', real=True)
63
+ y1 = Symbol('y1', real=True)
64
+ half = S.Half
65
+ p1 = Point(0, 0)
66
+ p2 = Point(1, 1)
67
+ p4 = Point(0, 1)
68
+
69
+ e1 = Ellipse(p1, 1, 1)
70
+ e2 = Ellipse(p2, half, 1)
71
+ e3 = Ellipse(p1, y1, y1)
72
+ c1 = Circle(p1, 1)
73
+ c2 = Circle(p2, 1)
74
+ c3 = Circle(Point(sqrt(2), sqrt(2)), 1)
75
+ l1 = Line(p1, p2)
76
+
77
+ # Test creation with three points
78
+ cen, rad = Point(3*half, 2), 5*half
79
+ assert Circle(Point(0, 0), Point(3, 0), Point(0, 4)) == Circle(cen, rad)
80
+ assert Circle(Point(0, 0), Point(1, 1), Point(2, 2)) == Segment2D(Point2D(0, 0), Point2D(2, 2))
81
+
82
+ raises(ValueError, lambda: Ellipse(None, None, None, 1))
83
+ raises(ValueError, lambda: Ellipse())
84
+ raises(GeometryError, lambda: Circle(Point(0, 0)))
85
+ raises(GeometryError, lambda: Circle(Symbol('x')*Symbol('y')))
86
+
87
+ # Basic Stuff
88
+ assert Ellipse(None, 1, 1).center == Point(0, 0)
89
+ assert e1 == c1
90
+ assert e1 != e2
91
+ assert e1 != l1
92
+ assert p4 in e1
93
+ assert e1 in e1
94
+ assert e2 in e2
95
+ assert 1 not in e2
96
+ assert p2 not in e2
97
+ assert e1.area == pi
98
+ assert e2.area == pi/2
99
+ assert e3.area == pi*y1*abs(y1)
100
+ assert c1.area == e1.area
101
+ assert c1.circumference == e1.circumference
102
+ assert e3.circumference == 2*pi*y1
103
+ assert e1.plot_interval() == e2.plot_interval() == [t, -pi, pi]
104
+ assert e1.plot_interval(x) == e2.plot_interval(x) == [x, -pi, pi]
105
+
106
+ assert c1.minor == 1
107
+ assert c1.major == 1
108
+ assert c1.hradius == 1
109
+ assert c1.vradius == 1
110
+
111
+ assert Ellipse((1, 1), 0, 0) == Point(1, 1)
112
+ assert Ellipse((1, 1), 1, 0) == Segment(Point(0, 1), Point(2, 1))
113
+ assert Ellipse((1, 1), 0, 1) == Segment(Point(1, 0), Point(1, 2))
114
+
115
+ # Private Functions
116
+ assert hash(c1) == hash(Circle(Point(1, 0), Point(0, 1), Point(0, -1)))
117
+ assert c1 in e1
118
+ assert (Line(p1, p2) in e1) is False
119
+ assert e1.__cmp__(e1) == 0
120
+ assert e1.__cmp__(Point(0, 0)) > 0
121
+
122
+ # Encloses
123
+ assert e1.encloses(Segment(Point(-0.5, -0.5), Point(0.5, 0.5))) is True
124
+ assert e1.encloses(Line(p1, p2)) is False
125
+ assert e1.encloses(Ray(p1, p2)) is False
126
+ assert e1.encloses(e1) is False
127
+ assert e1.encloses(
128
+ Polygon(Point(-0.5, -0.5), Point(-0.5, 0.5), Point(0.5, 0.5))) is True
129
+ assert e1.encloses(RegularPolygon(p1, 0.5, 3)) is True
130
+ assert e1.encloses(RegularPolygon(p1, 5, 3)) is False
131
+ assert e1.encloses(RegularPolygon(p2, 5, 3)) is False
132
+
133
+ assert e2.arbitrary_point() in e2
134
+ raises(ValueError, lambda: Ellipse(Point(x, y), 1, 1).arbitrary_point(parameter='x'))
135
+
136
+ # Foci
137
+ f1, f2 = Point(sqrt(12), 0), Point(-sqrt(12), 0)
138
+ ef = Ellipse(Point(0, 0), 4, 2)
139
+ assert ef.foci in [(f1, f2), (f2, f1)]
140
+
141
+ # Tangents
142
+ v = sqrt(2) / 2
143
+ p1_1 = Point(v, v)
144
+ p1_2 = p2 + Point(half, 0)
145
+ p1_3 = p2 + Point(0, 1)
146
+ assert e1.tangent_lines(p4) == c1.tangent_lines(p4)
147
+ assert e2.tangent_lines(p1_2) == [Line(Point(Rational(3, 2), 1), Point(Rational(3, 2), S.Half))]
148
+ assert e2.tangent_lines(p1_3) == [Line(Point(1, 2), Point(Rational(5, 4), 2))]
149
+ assert c1.tangent_lines(p1_1) != [Line(p1_1, Point(0, sqrt(2)))]
150
+ assert c1.tangent_lines(p1) == []
151
+ assert e2.is_tangent(Line(p1_2, p2 + Point(half, 1)))
152
+ assert e2.is_tangent(Line(p1_3, p2 + Point(half, 1)))
153
+ assert c1.is_tangent(Line(p1_1, Point(0, sqrt(2))))
154
+ assert e1.is_tangent(Line(Point(0, 0), Point(1, 1))) is False
155
+ assert c1.is_tangent(e1) is True
156
+ assert c1.is_tangent(Ellipse(Point(2, 0), 1, 1)) is True
157
+ assert c1.is_tangent(
158
+ Polygon(Point(1, 1), Point(1, -1), Point(2, 0))) is True
159
+ assert c1.is_tangent(
160
+ Polygon(Point(1, 1), Point(1, 0), Point(2, 0))) is False
161
+ assert Circle(Point(5, 5), 3).is_tangent(Circle(Point(0, 5), 1)) is False
162
+
163
+ assert Ellipse(Point(5, 5), 2, 1).tangent_lines(Point(0, 0)) == \
164
+ [Line(Point(0, 0), Point(Rational(77, 25), Rational(132, 25))),
165
+ Line(Point(0, 0), Point(Rational(33, 5), Rational(22, 5)))]
166
+ assert Ellipse(Point(5, 5), 2, 1).tangent_lines(Point(3, 4)) == \
167
+ [Line(Point(3, 4), Point(4, 4)), Line(Point(3, 4), Point(3, 5))]
168
+ assert Circle(Point(5, 5), 2).tangent_lines(Point(3, 3)) == \
169
+ [Line(Point(3, 3), Point(4, 3)), Line(Point(3, 3), Point(3, 4))]
170
+ assert Circle(Point(5, 5), 2).tangent_lines(Point(5 - 2*sqrt(2), 5)) == \
171
+ [Line(Point(5 - 2*sqrt(2), 5), Point(5 - sqrt(2), 5 - sqrt(2))),
172
+ Line(Point(5 - 2*sqrt(2), 5), Point(5 - sqrt(2), 5 + sqrt(2))), ]
173
+ assert Circle(Point(5, 5), 5).tangent_lines(Point(4, 0)) == \
174
+ [Line(Point(4, 0), Point(Rational(40, 13), Rational(5, 13))),
175
+ Line(Point(4, 0), Point(5, 0))]
176
+ assert Circle(Point(5, 5), 5).tangent_lines(Point(0, 6)) == \
177
+ [Line(Point(0, 6), Point(0, 7)),
178
+ Line(Point(0, 6), Point(Rational(5, 13), Rational(90, 13)))]
179
+
180
+ # for numerical calculations, we shouldn't demand exact equality,
181
+ # so only test up to the desired precision
182
+ def lines_close(l1, l2, prec):
183
+ """ tests whether l1 and 12 are within 10**(-prec)
184
+ of each other """
185
+ return abs(l1.p1 - l2.p1) < 10**(-prec) and abs(l1.p2 - l2.p2) < 10**(-prec)
186
+ def line_list_close(ll1, ll2, prec):
187
+ return all(lines_close(l1, l2, prec) for l1, l2 in zip(ll1, ll2))
188
+
189
+ e = Ellipse(Point(0, 0), 2, 1)
190
+ assert e.normal_lines(Point(0, 0)) == \
191
+ [Line(Point(0, 0), Point(0, 1)), Line(Point(0, 0), Point(1, 0))]
192
+ assert e.normal_lines(Point(1, 0)) == \
193
+ [Line(Point(0, 0), Point(1, 0))]
194
+ assert e.normal_lines((0, 1)) == \
195
+ [Line(Point(0, 0), Point(0, 1))]
196
+ assert line_list_close(e.normal_lines(Point(1, 1), 2), [
197
+ Line(Point(Rational(-51, 26), Rational(-1, 5)), Point(Rational(-25, 26), Rational(17, 83))),
198
+ Line(Point(Rational(28, 29), Rational(-7, 8)), Point(Rational(57, 29), Rational(-9, 2)))], 2)
199
+ # test the failure of Poly.intervals and checks a point on the boundary
200
+ p = Point(sqrt(3), S.Half)
201
+ assert p in e
202
+ assert line_list_close(e.normal_lines(p, 2), [
203
+ Line(Point(Rational(-341, 171), Rational(-1, 13)), Point(Rational(-170, 171), Rational(5, 64))),
204
+ Line(Point(Rational(26, 15), Rational(-1, 2)), Point(Rational(41, 15), Rational(-43, 26)))], 2)
205
+ # be sure to use the slope that isn't undefined on boundary
206
+ e = Ellipse((0, 0), 2, 2*sqrt(3)/3)
207
+ assert line_list_close(e.normal_lines((1, 1), 2), [
208
+ Line(Point(Rational(-64, 33), Rational(-20, 71)), Point(Rational(-31, 33), Rational(2, 13))),
209
+ Line(Point(1, -1), Point(2, -4))], 2)
210
+ # general ellipse fails except under certain conditions
211
+ e = Ellipse((0, 0), x, 1)
212
+ assert e.normal_lines((x + 1, 0)) == [Line(Point(0, 0), Point(1, 0))]
213
+ raises(NotImplementedError, lambda: e.normal_lines((x + 1, 1)))
214
+ # Properties
215
+ major = 3
216
+ minor = 1
217
+ e4 = Ellipse(p2, minor, major)
218
+ assert e4.focus_distance == sqrt(major**2 - minor**2)
219
+ ecc = e4.focus_distance / major
220
+ assert e4.eccentricity == ecc
221
+ assert e4.periapsis == major*(1 - ecc)
222
+ assert e4.apoapsis == major*(1 + ecc)
223
+ assert e4.semilatus_rectum == major*(1 - ecc ** 2)
224
+ # independent of orientation
225
+ e4 = Ellipse(p2, major, minor)
226
+ assert e4.focus_distance == sqrt(major**2 - minor**2)
227
+ ecc = e4.focus_distance / major
228
+ assert e4.eccentricity == ecc
229
+ assert e4.periapsis == major*(1 - ecc)
230
+ assert e4.apoapsis == major*(1 + ecc)
231
+
232
+ # Intersection
233
+ l1 = Line(Point(1, -5), Point(1, 5))
234
+ l2 = Line(Point(-5, -1), Point(5, -1))
235
+ l3 = Line(Point(-1, -1), Point(1, 1))
236
+ l4 = Line(Point(-10, 0), Point(0, 10))
237
+ pts_c1_l3 = [Point(sqrt(2)/2, sqrt(2)/2), Point(-sqrt(2)/2, -sqrt(2)/2)]
238
+
239
+ assert intersection(e2, l4) == []
240
+ assert intersection(c1, Point(1, 0)) == [Point(1, 0)]
241
+ assert intersection(c1, l1) == [Point(1, 0)]
242
+ assert intersection(c1, l2) == [Point(0, -1)]
243
+ assert intersection(c1, l3) in [pts_c1_l3, [pts_c1_l3[1], pts_c1_l3[0]]]
244
+ assert intersection(c1, c2) == [Point(0, 1), Point(1, 0)]
245
+ assert intersection(c1, c3) == [Point(sqrt(2)/2, sqrt(2)/2)]
246
+ assert e1.intersection(l1) == [Point(1, 0)]
247
+ assert e2.intersection(l4) == []
248
+ assert e1.intersection(Circle(Point(0, 2), 1)) == [Point(0, 1)]
249
+ assert e1.intersection(Circle(Point(5, 0), 1)) == []
250
+ assert e1.intersection(Ellipse(Point(2, 0), 1, 1)) == [Point(1, 0)]
251
+ assert e1.intersection(Ellipse(Point(5, 0), 1, 1)) == []
252
+ assert e1.intersection(Point(2, 0)) == []
253
+ assert e1.intersection(e1) == e1
254
+ assert intersection(Ellipse(Point(0, 0), 2, 1), Ellipse(Point(3, 0), 1, 2)) == [Point(2, 0)]
255
+ assert intersection(Circle(Point(0, 0), 2), Circle(Point(3, 0), 1)) == [Point(2, 0)]
256
+ assert intersection(Circle(Point(0, 0), 2), Circle(Point(7, 0), 1)) == []
257
+ assert intersection(Ellipse(Point(0, 0), 5, 17), Ellipse(Point(4, 0), 1, 0.2)) == [Point(5, 0)]
258
+ assert intersection(Ellipse(Point(0, 0), 5, 17), Ellipse(Point(4, 0), 0.999, 0.2)) == []
259
+ assert Circle((0, 0), S.Half).intersection(
260
+ Triangle((-1, 0), (1, 0), (0, 1))) == [
261
+ Point(Rational(-1, 2), 0), Point(S.Half, 0)]
262
+ raises(TypeError, lambda: intersection(e2, Line((0, 0, 0), (0, 0, 1))))
263
+ raises(TypeError, lambda: intersection(e2, Rational(12)))
264
+ raises(TypeError, lambda: Ellipse.intersection(e2, 1))
265
+ # some special case intersections
266
+ csmall = Circle(p1, 3)
267
+ cbig = Circle(p1, 5)
268
+ cout = Circle(Point(5, 5), 1)
269
+ # one circle inside of another
270
+ assert csmall.intersection(cbig) == []
271
+ # separate circles
272
+ assert csmall.intersection(cout) == []
273
+ # coincident circles
274
+ assert csmall.intersection(csmall) == csmall
275
+
276
+ v = sqrt(2)
277
+ t1 = Triangle(Point(0, v), Point(0, -v), Point(v, 0))
278
+ points = intersection(t1, c1)
279
+ assert len(points) == 4
280
+ assert Point(0, 1) in points
281
+ assert Point(0, -1) in points
282
+ assert Point(v/2, v/2) in points
283
+ assert Point(v/2, -v/2) in points
284
+
285
+ circ = Circle(Point(0, 0), 5)
286
+ elip = Ellipse(Point(0, 0), 5, 20)
287
+ assert intersection(circ, elip) in \
288
+ [[Point(5, 0), Point(-5, 0)], [Point(-5, 0), Point(5, 0)]]
289
+ assert elip.tangent_lines(Point(0, 0)) == []
290
+ elip = Ellipse(Point(0, 0), 3, 2)
291
+ assert elip.tangent_lines(Point(3, 0)) == \
292
+ [Line(Point(3, 0), Point(3, -12))]
293
+
294
+ e1 = Ellipse(Point(0, 0), 5, 10)
295
+ e2 = Ellipse(Point(2, 1), 4, 8)
296
+ a = Rational(53, 17)
297
+ c = 2*sqrt(3991)/17
298
+ ans = [Point(a - c/8, a/2 + c), Point(a + c/8, a/2 - c)]
299
+ assert e1.intersection(e2) == ans
300
+ e2 = Ellipse(Point(x, y), 4, 8)
301
+ c = sqrt(3991)
302
+ ans = [Point(-c/68 + a, c*Rational(2, 17) + a/2), Point(c/68 + a, c*Rational(-2, 17) + a/2)]
303
+ assert [p.subs({x: 2, y:1}) for p in e1.intersection(e2)] == ans
304
+
305
+ # Combinations of above
306
+ assert e3.is_tangent(e3.tangent_lines(p1 + Point(y1, 0))[0])
307
+
308
+ e = Ellipse((1, 2), 3, 2)
309
+ assert e.tangent_lines(Point(10, 0)) == \
310
+ [Line(Point(10, 0), Point(1, 0)),
311
+ Line(Point(10, 0), Point(Rational(14, 5), Rational(18, 5)))]
312
+
313
+ # encloses_point
314
+ e = Ellipse((0, 0), 1, 2)
315
+ assert e.encloses_point(e.center)
316
+ assert e.encloses_point(e.center + Point(0, e.vradius - Rational(1, 10)))
317
+ assert e.encloses_point(e.center + Point(e.hradius - Rational(1, 10), 0))
318
+ assert e.encloses_point(e.center + Point(e.hradius, 0)) is False
319
+ assert e.encloses_point(
320
+ e.center + Point(e.hradius + Rational(1, 10), 0)) is False
321
+ e = Ellipse((0, 0), 2, 1)
322
+ assert e.encloses_point(e.center)
323
+ assert e.encloses_point(e.center + Point(0, e.vradius - Rational(1, 10)))
324
+ assert e.encloses_point(e.center + Point(e.hradius - Rational(1, 10), 0))
325
+ assert e.encloses_point(e.center + Point(e.hradius, 0)) is False
326
+ assert e.encloses_point(
327
+ e.center + Point(e.hradius + Rational(1, 10), 0)) is False
328
+ assert c1.encloses_point(Point(1, 0)) is False
329
+ assert c1.encloses_point(Point(0.3, 0.4)) is True
330
+
331
+ assert e.scale(2, 3) == Ellipse((0, 0), 4, 3)
332
+ assert e.scale(3, 6) == Ellipse((0, 0), 6, 6)
333
+ assert e.rotate(pi) == e
334
+ assert e.rotate(pi, (1, 2)) == Ellipse(Point(2, 4), 2, 1)
335
+ raises(NotImplementedError, lambda: e.rotate(pi/3))
336
+
337
+ # Circle rotation tests (Issue #11743)
338
+ # Link - https://github.com/sympy/sympy/issues/11743
339
+ cir = Circle(Point(1, 0), 1)
340
+ assert cir.rotate(pi/2) == Circle(Point(0, 1), 1)
341
+ assert cir.rotate(pi/3) == Circle(Point(S.Half, sqrt(3)/2), 1)
342
+ assert cir.rotate(pi/3, Point(1, 0)) == Circle(Point(1, 0), 1)
343
+ assert cir.rotate(pi/3, Point(0, 1)) == Circle(Point(S.Half + sqrt(3)/2, S.Half + sqrt(3)/2), 1)
344
+
345
+
346
+ def test_construction():
347
+ e1 = Ellipse(hradius=2, vradius=1, eccentricity=None)
348
+ assert e1.eccentricity == sqrt(3)/2
349
+
350
+ e2 = Ellipse(hradius=2, vradius=None, eccentricity=sqrt(3)/2)
351
+ assert e2.vradius == 1
352
+
353
+ e3 = Ellipse(hradius=None, vradius=1, eccentricity=sqrt(3)/2)
354
+ assert e3.hradius == 2
355
+
356
+ # filter(None, iterator) filters out anything falsey, including 0
357
+ # eccentricity would be filtered out in this case and the constructor would throw an error
358
+ e4 = Ellipse(Point(0, 0), hradius=1, eccentricity=0)
359
+ assert e4.vradius == 1
360
+
361
+ #tests for eccentricity > 1
362
+ raises(GeometryError, lambda: Ellipse(Point(3, 1), hradius=3, eccentricity = S(3)/2))
363
+ raises(GeometryError, lambda: Ellipse(Point(3, 1), hradius=3, eccentricity=sec(5)))
364
+ raises(GeometryError, lambda: Ellipse(Point(3, 1), hradius=3, eccentricity=S.Pi-S(2)))
365
+
366
+ #tests for eccentricity = 1
367
+ #if vradius is not defined
368
+ assert Ellipse(None, 1, None, 1).length == 2
369
+ #if hradius is not defined
370
+ raises(GeometryError, lambda: Ellipse(None, None, 1, eccentricity = 1))
371
+
372
+ #tests for eccentricity < 0
373
+ raises(GeometryError, lambda: Ellipse(Point(3, 1), hradius=3, eccentricity = -3))
374
+ raises(GeometryError, lambda: Ellipse(Point(3, 1), hradius=3, eccentricity = -0.5))
375
+
376
+ def test_ellipse_random_point():
377
+ y1 = Symbol('y1', real=True)
378
+ e3 = Ellipse(Point(0, 0), y1, y1)
379
+ rx, ry = Symbol('rx'), Symbol('ry')
380
+ for ind in range(0, 5):
381
+ r = e3.random_point()
382
+ # substitution should give zero*y1**2
383
+ assert e3.equation(rx, ry).subs(zip((rx, ry), r.args)).equals(0)
384
+ # test for the case with seed
385
+ r = e3.random_point(seed=1)
386
+ assert e3.equation(rx, ry).subs(zip((rx, ry), r.args)).equals(0)
387
+
388
+
389
+ def test_repr():
390
+ assert repr(Circle((0, 1), 2)) == 'Circle(Point2D(0, 1), 2)'
391
+
392
+
393
+ def test_transform():
394
+ c = Circle((1, 1), 2)
395
+ assert c.scale(-1) == Circle((-1, 1), 2)
396
+ assert c.scale(y=-1) == Circle((1, -1), 2)
397
+ assert c.scale(2) == Ellipse((2, 1), 4, 2)
398
+
399
+ assert Ellipse((0, 0), 2, 3).scale(2, 3, (4, 5)) == \
400
+ Ellipse(Point(-4, -10), 4, 9)
401
+ assert Circle((0, 0), 2).scale(2, 3, (4, 5)) == \
402
+ Ellipse(Point(-4, -10), 4, 6)
403
+ assert Ellipse((0, 0), 2, 3).scale(3, 3, (4, 5)) == \
404
+ Ellipse(Point(-8, -10), 6, 9)
405
+ assert Circle((0, 0), 2).scale(3, 3, (4, 5)) == \
406
+ Circle(Point(-8, -10), 6)
407
+ assert Circle(Point(-8, -10), 6).scale(Rational(1, 3), Rational(1, 3), (4, 5)) == \
408
+ Circle((0, 0), 2)
409
+ assert Circle((0, 0), 2).translate(4, 5) == \
410
+ Circle((4, 5), 2)
411
+ assert Circle((0, 0), 2).scale(3, 3) == \
412
+ Circle((0, 0), 6)
413
+
414
+
415
+ def test_bounds():
416
+ e1 = Ellipse(Point(0, 0), 3, 5)
417
+ e2 = Ellipse(Point(2, -2), 7, 7)
418
+ c1 = Circle(Point(2, -2), 7)
419
+ c2 = Circle(Point(-2, 0), Point(0, 2), Point(2, 0))
420
+ assert e1.bounds == (-3, -5, 3, 5)
421
+ assert e2.bounds == (-5, -9, 9, 5)
422
+ assert c1.bounds == (-5, -9, 9, 5)
423
+ assert c2.bounds == (-2, -2, 2, 2)
424
+
425
+
426
+ def test_reflect():
427
+ b = Symbol('b')
428
+ m = Symbol('m')
429
+ l = Line((0, b), slope=m)
430
+ t1 = Triangle((0, 0), (1, 0), (2, 3))
431
+ assert t1.area == -t1.reflect(l).area
432
+ e = Ellipse((1, 0), 1, 2)
433
+ assert e.area == -e.reflect(Line((1, 0), slope=0)).area
434
+ assert e.area == -e.reflect(Line((1, 0), slope=oo)).area
435
+ raises(NotImplementedError, lambda: e.reflect(Line((1, 0), slope=m)))
436
+ assert Circle((0, 1), 1).reflect(Line((0, 0), (1, 1))) == Circle(Point2D(1, 0), -1)
437
+
438
+
439
+ def test_is_tangent():
440
+ e1 = Ellipse(Point(0, 0), 3, 5)
441
+ c1 = Circle(Point(2, -2), 7)
442
+ assert e1.is_tangent(Point(0, 0)) is False
443
+ assert e1.is_tangent(Point(3, 0)) is False
444
+ assert e1.is_tangent(e1) is True
445
+ assert e1.is_tangent(Ellipse((0, 0), 1, 2)) is False
446
+ assert e1.is_tangent(Ellipse((0, 0), 3, 2)) is True
447
+ assert c1.is_tangent(Ellipse((2, -2), 7, 1)) is True
448
+ assert c1.is_tangent(Circle((11, -2), 2)) is True
449
+ assert c1.is_tangent(Circle((7, -2), 2)) is True
450
+ assert c1.is_tangent(Ray((-5, -2), (-15, -20))) is False
451
+ assert c1.is_tangent(Ray((-3, -2), (-15, -20))) is False
452
+ assert c1.is_tangent(Ray((-3, -22), (15, 20))) is False
453
+ assert c1.is_tangent(Ray((9, 20), (9, -20))) is True
454
+ assert e1.is_tangent(Segment((2, 2), (-7, 7))) is False
455
+ assert e1.is_tangent(Segment((0, 0), (1, 2))) is False
456
+ assert c1.is_tangent(Segment((0, 0), (-5, -2))) is False
457
+ assert e1.is_tangent(Segment((3, 0), (12, 12))) is False
458
+ assert e1.is_tangent(Segment((12, 12), (3, 0))) is False
459
+ assert e1.is_tangent(Segment((-3, 0), (3, 0))) is False
460
+ assert e1.is_tangent(Segment((-3, 5), (3, 5))) is True
461
+ assert e1.is_tangent(Line((10, 0), (10, 10))) is False
462
+ assert e1.is_tangent(Line((0, 0), (1, 1))) is False
463
+ assert e1.is_tangent(Line((-3, 0), (-2.99, -0.001))) is False
464
+ assert e1.is_tangent(Line((-3, 0), (-3, 1))) is True
465
+ assert e1.is_tangent(Polygon((0, 0), (5, 5), (5, -5))) is False
466
+ assert e1.is_tangent(Polygon((-100, -50), (-40, -334), (-70, -52))) is False
467
+ assert e1.is_tangent(Polygon((-3, 0), (3, 0), (0, 1))) is False
468
+ assert e1.is_tangent(Polygon((-3, 0), (3, 0), (0, 5))) is False
469
+ assert e1.is_tangent(Polygon((-3, 0), (0, -5), (3, 0), (0, 5))) is False
470
+ assert e1.is_tangent(Polygon((-3, -5), (-3, 5), (3, 5), (3, -5))) is True
471
+ assert c1.is_tangent(Polygon((-3, -5), (-3, 5), (3, 5), (3, -5))) is False
472
+ assert e1.is_tangent(Polygon((0, 0), (3, 0), (7, 7), (0, 5))) is False
473
+ assert e1.is_tangent(Polygon((3, 12), (3, -12), (6, 5))) is True
474
+ assert e1.is_tangent(Polygon((3, 12), (3, -12), (0, -5), (0, 5))) is False
475
+ assert e1.is_tangent(Polygon((3, 0), (5, 7), (6, -5))) is False
476
+ raises(TypeError, lambda: e1.is_tangent(Point(0, 0, 0)))
477
+ raises(TypeError, lambda: e1.is_tangent(Rational(5)))
478
+
479
+
480
+ def test_parameter_value():
481
+ t = Symbol('t')
482
+ e = Ellipse(Point(0, 0), 3, 5)
483
+ assert e.parameter_value((3, 0), t) == {t: 0}
484
+ raises(ValueError, lambda: e.parameter_value((4, 0), t))
485
+
486
+
487
+ @slow
488
+ def test_second_moment_of_area():
489
+ x, y = symbols('x, y')
490
+ e = Ellipse(Point(0, 0), 5, 4)
491
+ I_yy = 2*4*integrate(sqrt(25 - x**2)*x**2, (x, -5, 5))/5
492
+ I_xx = 2*5*integrate(sqrt(16 - y**2)*y**2, (y, -4, 4))/4
493
+ Y = 3*sqrt(1 - x**2/5**2)
494
+ I_xy = integrate(integrate(y, (y, -Y, Y))*x, (x, -5, 5))
495
+ assert I_yy == e.second_moment_of_area()[1]
496
+ assert I_xx == e.second_moment_of_area()[0]
497
+ assert I_xy == e.second_moment_of_area()[2]
498
+ #checking for other point
499
+ t1 = e.second_moment_of_area(Point(6,5))
500
+ t2 = (580*pi, 845*pi, 600*pi)
501
+ assert t1==t2
502
+
503
+
504
+ def test_section_modulus_and_polar_second_moment_of_area():
505
+ d = Symbol('d', positive=True)
506
+ c = Circle((3, 7), 8)
507
+ assert c.polar_second_moment_of_area() == 2048*pi
508
+ assert c.section_modulus() == (128*pi, 128*pi)
509
+ c = Circle((2, 9), d/2)
510
+ assert c.polar_second_moment_of_area() == pi*d**3*Abs(d)/64 + pi*d*Abs(d)**3/64
511
+ assert c.section_modulus() == (pi*d**3/S(32), pi*d**3/S(32))
512
+
513
+ a, b = symbols('a, b', positive=True)
514
+ e = Ellipse((4, 6), a, b)
515
+ assert e.section_modulus() == (pi*a*b**2/S(4), pi*a**2*b/S(4))
516
+ assert e.polar_second_moment_of_area() == pi*a**3*b/S(4) + pi*a*b**3/S(4)
517
+ e = e.rotate(pi/2) # no change in polar and section modulus
518
+ assert e.section_modulus() == (pi*a**2*b/S(4), pi*a*b**2/S(4))
519
+ assert e.polar_second_moment_of_area() == pi*a**3*b/S(4) + pi*a*b**3/S(4)
520
+
521
+ e = Ellipse((a, b), 2, 6)
522
+ assert e.section_modulus() == (18*pi, 6*pi)
523
+ assert e.polar_second_moment_of_area() == 120*pi
524
+
525
+ e = Ellipse(Point(0, 0), 2, 2)
526
+ assert e.section_modulus() == (2*pi, 2*pi)
527
+ assert e.section_modulus(Point(2, 2)) == (2*pi, 2*pi)
528
+ assert e.section_modulus((2, 2)) == (2*pi, 2*pi)
529
+
530
+
531
+ def test_circumference():
532
+ M = Symbol('M')
533
+ m = Symbol('m')
534
+ assert Ellipse(Point(0, 0), M, m).circumference == 4 * M * elliptic_e((M ** 2 - m ** 2) / M**2)
535
+
536
+ assert Ellipse(Point(0, 0), 5, 4).circumference == 20 * elliptic_e(S(9) / 25)
537
+
538
+ # circle
539
+ assert Ellipse(None, 1, None, 0).circumference == 2*pi
540
+
541
+ # test numerically
542
+ assert abs(Ellipse(None, hradius=5, vradius=3).circumference.evalf(16) - 25.52699886339813) < 1e-10
543
+
544
+
545
+ def test_issue_15259():
546
+ assert Circle((1, 2), 0) == Point(1, 2)
547
+
548
+
549
+ def test_issue_15797_equals():
550
+ Ri = 0.024127189424130748
551
+ Ci = (0.0864931002830291, 0.0819863295239654)
552
+ A = Point(0, 0.0578591400998346)
553
+ c = Circle(Ci, Ri) # evaluated
554
+ assert c.is_tangent(c.tangent_lines(A)[0]) == True
555
+ assert c.center.x.is_Rational
556
+ assert c.center.y.is_Rational
557
+ assert c.radius.is_Rational
558
+ u = Circle(Ci, Ri, evaluate=False) # unevaluated
559
+ assert u.center.x.is_Float
560
+ assert u.center.y.is_Float
561
+ assert u.radius.is_Float
562
+
563
+
564
+ def test_auxiliary_circle():
565
+ x, y, a, b = symbols('x y a b')
566
+ e = Ellipse((x, y), a, b)
567
+ # the general result
568
+ assert e.auxiliary_circle() == Circle((x, y), Max(a, b))
569
+ # a special case where Ellipse is a Circle
570
+ assert Circle((3, 4), 8).auxiliary_circle() == Circle((3, 4), 8)
571
+
572
+
573
+ def test_director_circle():
574
+ x, y, a, b = symbols('x y a b')
575
+ e = Ellipse((x, y), a, b)
576
+ # the general result
577
+ assert e.director_circle() == Circle((x, y), sqrt(a**2 + b**2))
578
+ # a special case where Ellipse is a Circle
579
+ assert Circle((3, 4), 8).director_circle() == Circle((3, 4), 8*sqrt(2))
580
+
581
+
582
+ def test_evolute():
583
+ #ellipse centered at h,k
584
+ x, y, h, k = symbols('x y h k',real = True)
585
+ a, b = symbols('a b')
586
+ e = Ellipse(Point(h, k), a, b)
587
+ t1 = (e.hradius*(x - e.center.x))**Rational(2, 3)
588
+ t2 = (e.vradius*(y - e.center.y))**Rational(2, 3)
589
+ E = t1 + t2 - (e.hradius**2 - e.vradius**2)**Rational(2, 3)
590
+ assert e.evolute() == E
591
+ #Numerical Example
592
+ e = Ellipse(Point(1, 1), 6, 3)
593
+ t1 = (6*(x - 1))**Rational(2, 3)
594
+ t2 = (3*(y - 1))**Rational(2, 3)
595
+ E = t1 + t2 - (27)**Rational(2, 3)
596
+ assert e.evolute() == E
597
+
598
+
599
+ def test_svg():
600
+ e1 = Ellipse(Point(1, 0), 3, 2)
601
+ assert e1._svg(2, "#FFAAFF") == '<ellipse fill="#FFAAFF" stroke="#555555" stroke-width="4.0" opacity="0.6" cx="1.00000000000000" cy="0" rx="3.00000000000000" ry="2.00000000000000"/>'
llmeval-env/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))
llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/test_geometrysets.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import Rational
2
+ from sympy.core.singleton import S
3
+ from sympy.geometry import Circle, Line, Point, Polygon, Segment
4
+ from sympy.sets import FiniteSet, Union, Intersection, EmptySet
5
+
6
+
7
+ def test_booleans():
8
+ """ test basic unions and intersections """
9
+ half = S.Half
10
+
11
+ p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)])
12
+ p5, p6, p7 = map(Point, [(3, 2), (1, -1), (0, 2)])
13
+ l1 = Line(Point(0,0), Point(1,1))
14
+ l2 = Line(Point(half, half), Point(5,5))
15
+ l3 = Line(p2, p3)
16
+ l4 = Line(p3, p4)
17
+ poly1 = Polygon(p1, p2, p3, p4)
18
+ poly2 = Polygon(p5, p6, p7)
19
+ poly3 = Polygon(p1, p2, p5)
20
+ assert Union(l1, l2).equals(l1)
21
+ assert Intersection(l1, l2).equals(l1)
22
+ assert Intersection(l1, l4) == FiniteSet(Point(1,1))
23
+ assert Intersection(Union(l1, l4), l3) == FiniteSet(Point(Rational(-1, 3), Rational(-1, 3)), Point(5, 1))
24
+ assert Intersection(l1, FiniteSet(Point(7,-7))) == EmptySet
25
+ assert Intersection(Circle(Point(0,0), 3), Line(p1,p2)) == FiniteSet(Point(-3,0), Point(3,0))
26
+ assert Intersection(l1, FiniteSet(p1)) == FiniteSet(p1)
27
+ assert Union(l1, FiniteSet(p1)) == l1
28
+
29
+ fs = FiniteSet(Point(Rational(1, 3), 1), Point(Rational(2, 3), 0), Point(Rational(9, 5), Rational(1, 5)), Point(Rational(7, 3), 1))
30
+ # test the intersection of polygons
31
+ assert Intersection(poly1, poly2) == fs
32
+ # make sure if we union polygons with subsets, the subsets go away
33
+ assert Union(poly1, poly2, fs) == Union(poly1, poly2)
34
+ # make sure that if we union with a FiniteSet that isn't a subset,
35
+ # that the points in the intersection stop being listed
36
+ assert Union(poly1, FiniteSet(Point(0,0), Point(3,5))) == Union(poly1, FiniteSet(Point(3,5)))
37
+ # intersect two polygons that share an edge
38
+ assert Intersection(poly1, poly3) == Union(FiniteSet(Point(Rational(3, 2), 1), Point(2, 1)), Segment(Point(0, 0), Point(1, 0)))
llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/test_line.py ADDED
@@ -0,0 +1,852 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import (Float, Rational, oo, pi)
2
+ from sympy.core.relational import Eq
3
+ from sympy.core.singleton import S
4
+ from sympy.core.symbol import (Symbol, symbols)
5
+ from sympy.functions.elementary.miscellaneous import sqrt
6
+ from sympy.functions.elementary.trigonometric import (acos, cos, sin)
7
+ from sympy.sets import EmptySet
8
+ from sympy.simplify.simplify import simplify
9
+ from sympy.functions.elementary.trigonometric import tan
10
+ from sympy.geometry import (Circle, GeometryError, Line, Point, Ray,
11
+ Segment, Triangle, intersection, Point3D, Line3D, Ray3D, Segment3D,
12
+ Point2D, Line2D)
13
+ from sympy.geometry.line import Undecidable
14
+ from sympy.geometry.polygon import _asa as asa
15
+ from sympy.utilities.iterables import cartes
16
+ from sympy.testing.pytest import raises, warns
17
+
18
+
19
+ x = Symbol('x', real=True)
20
+ y = Symbol('y', real=True)
21
+ z = Symbol('z', real=True)
22
+ k = Symbol('k', real=True)
23
+ x1 = Symbol('x1', real=True)
24
+ y1 = Symbol('y1', real=True)
25
+ t = Symbol('t', real=True)
26
+ a, b = symbols('a,b', real=True)
27
+ m = symbols('m', real=True)
28
+
29
+
30
+ def test_object_from_equation():
31
+ from sympy.abc import x, y, a, b
32
+ assert Line(3*x + y + 18) == Line2D(Point2D(0, -18), Point2D(1, -21))
33
+ assert Line(3*x + 5 * y + 1) == Line2D(
34
+ Point2D(0, Rational(-1, 5)), Point2D(1, Rational(-4, 5)))
35
+ assert Line(3*a + b + 18, x="a", y="b") == Line2D(
36
+ Point2D(0, -18), Point2D(1, -21))
37
+ assert Line(3*x + y) == Line2D(Point2D(0, 0), Point2D(1, -3))
38
+ assert Line(x + y) == Line2D(Point2D(0, 0), Point2D(1, -1))
39
+ assert Line(Eq(3*a + b, -18), x="a", y=b) == Line2D(
40
+ Point2D(0, -18), Point2D(1, -21))
41
+ # issue 22361
42
+ assert Line(x - 1) == Line2D(Point2D(1, 0), Point2D(1, 1))
43
+ assert Line(2*x - 2, y=x) == Line2D(Point2D(0, 1), Point2D(1, 1))
44
+ assert Line(y) == Line2D(Point2D(0, 0), Point2D(1, 0))
45
+ assert Line(2*y, x=y) == Line2D(Point2D(0, 0), Point2D(0, 1))
46
+ assert Line(y, x=y) == Line2D(Point2D(0, 0), Point2D(0, 1))
47
+ raises(ValueError, lambda: Line(x / y))
48
+ raises(ValueError, lambda: Line(a / b, x='a', y='b'))
49
+ raises(ValueError, lambda: Line(y / x))
50
+ raises(ValueError, lambda: Line(b / a, x='a', y='b'))
51
+ raises(ValueError, lambda: Line((x + 1)**2 + y))
52
+
53
+
54
+ def feq(a, b):
55
+ """Test if two floating point values are 'equal'."""
56
+ t_float = Float("1.0E-10")
57
+ return -t_float < a - b < t_float
58
+
59
+
60
+ def test_angle_between():
61
+ a = Point(1, 2, 3, 4)
62
+ b = a.orthogonal_direction
63
+ o = a.origin
64
+ assert feq(Line.angle_between(Line(Point(0, 0), Point(1, 1)),
65
+ Line(Point(0, 0), Point(5, 0))).evalf(), pi.evalf() / 4)
66
+ assert Line(a, o).angle_between(Line(b, o)) == pi / 2
67
+ z = Point3D(0, 0, 0)
68
+ assert Line3D.angle_between(Line3D(z, Point3D(1, 1, 1)),
69
+ Line3D(z, Point3D(5, 0, 0))) == acos(sqrt(3) / 3)
70
+ # direction of points is used to determine angle
71
+ assert Line3D.angle_between(Line3D(z, Point3D(1, 1, 1)),
72
+ Line3D(Point3D(5, 0, 0), z)) == acos(-sqrt(3) / 3)
73
+
74
+
75
+ def test_closing_angle():
76
+ a = Ray((0, 0), angle=0)
77
+ b = Ray((1, 2), angle=pi/2)
78
+ assert a.closing_angle(b) == -pi/2
79
+ assert b.closing_angle(a) == pi/2
80
+ assert a.closing_angle(a) == 0
81
+
82
+
83
+ def test_smallest_angle():
84
+ a = Line(Point(1, 1), Point(1, 2))
85
+ b = Line(Point(1, 1),Point(2, 3))
86
+ assert a.smallest_angle_between(b) == acos(2*sqrt(5)/5)
87
+
88
+
89
+ def test_svg():
90
+ a = Line(Point(1, 1),Point(1, 2))
91
+ assert a._svg() == '<path fill-rule="evenodd" fill="#66cc99" stroke="#555555" stroke-width="2.0" opacity="0.6" d="M 1.00000000000000,1.00000000000000 L 1.00000000000000,2.00000000000000" marker-start="url(#markerReverseArrow)" marker-end="url(#markerArrow)"/>'
92
+ a = Segment(Point(1, 0),Point(1, 1))
93
+ assert a._svg() == '<path fill-rule="evenodd" fill="#66cc99" stroke="#555555" stroke-width="2.0" opacity="0.6" d="M 1.00000000000000,0 L 1.00000000000000,1.00000000000000" />'
94
+ a = Ray(Point(2, 3), Point(3, 5))
95
+ assert a._svg() == '<path fill-rule="evenodd" fill="#66cc99" stroke="#555555" stroke-width="2.0" opacity="0.6" d="M 2.00000000000000,3.00000000000000 L 3.00000000000000,5.00000000000000" marker-start="url(#markerCircle)" marker-end="url(#markerArrow)"/>'
96
+
97
+
98
+ def test_arbitrary_point():
99
+ l1 = Line3D(Point3D(0, 0, 0), Point3D(1, 1, 1))
100
+ l2 = Line(Point(x1, x1), Point(y1, y1))
101
+ assert l2.arbitrary_point() in l2
102
+ assert Ray((1, 1), angle=pi / 4).arbitrary_point() == \
103
+ Point(t + 1, t + 1)
104
+ assert Segment((1, 1), (2, 3)).arbitrary_point() == Point(1 + t, 1 + 2 * t)
105
+ assert l1.perpendicular_segment(l1.arbitrary_point()) == l1.arbitrary_point()
106
+ assert Ray3D((1, 1, 1), direction_ratio=[1, 2, 3]).arbitrary_point() == \
107
+ Point3D(t + 1, 2 * t + 1, 3 * t + 1)
108
+ assert Segment3D(Point3D(0, 0, 0), Point3D(1, 1, 1)).midpoint == \
109
+ Point3D(S.Half, S.Half, S.Half)
110
+ assert Segment3D(Point3D(x1, x1, x1), Point3D(y1, y1, y1)).length == sqrt(3) * sqrt((x1 - y1) ** 2)
111
+ assert Segment3D((1, 1, 1), (2, 3, 4)).arbitrary_point() == \
112
+ Point3D(t + 1, 2 * t + 1, 3 * t + 1)
113
+ raises(ValueError, (lambda: Line((x, 1), (2, 3)).arbitrary_point(x)))
114
+
115
+
116
+ def test_are_concurrent_2d():
117
+ l1 = Line(Point(0, 0), Point(1, 1))
118
+ l2 = Line(Point(x1, x1), Point(x1, 1 + x1))
119
+ assert Line.are_concurrent(l1) is False
120
+ assert Line.are_concurrent(l1, l2)
121
+ assert Line.are_concurrent(l1, l1, l1, l2)
122
+ assert Line.are_concurrent(l1, l2, Line(Point(5, x1), Point(Rational(-3, 5), x1)))
123
+ assert Line.are_concurrent(l1, Line(Point(0, 0), Point(-x1, x1)), l2) is False
124
+
125
+
126
+ def test_are_concurrent_3d():
127
+ p1 = Point3D(0, 0, 0)
128
+ l1 = Line(p1, Point3D(1, 1, 1))
129
+ parallel_1 = Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0))
130
+ parallel_2 = Line3D(Point3D(0, 1, 0), Point3D(1, 1, 0))
131
+ assert Line3D.are_concurrent(l1) is False
132
+ assert Line3D.are_concurrent(l1, Line(Point3D(x1, x1, x1), Point3D(y1, y1, y1))) is False
133
+ assert Line3D.are_concurrent(l1, Line3D(p1, Point3D(x1, x1, x1)),
134
+ Line(Point3D(x1, x1, x1), Point3D(x1, 1 + x1, 1))) is True
135
+ assert Line3D.are_concurrent(parallel_1, parallel_2) is False
136
+
137
+
138
+ def test_arguments():
139
+ """Functions accepting `Point` objects in `geometry`
140
+ should also accept tuples, lists, and generators and
141
+ automatically convert them to points."""
142
+ from sympy.utilities.iterables import subsets
143
+
144
+ singles2d = ((1, 2), [1, 3], Point(1, 5))
145
+ doubles2d = subsets(singles2d, 2)
146
+ l2d = Line(Point2D(1, 2), Point2D(2, 3))
147
+ singles3d = ((1, 2, 3), [1, 2, 4], Point(1, 2, 6))
148
+ doubles3d = subsets(singles3d, 2)
149
+ l3d = Line(Point3D(1, 2, 3), Point3D(1, 1, 2))
150
+ singles4d = ((1, 2, 3, 4), [1, 2, 3, 5], Point(1, 2, 3, 7))
151
+ doubles4d = subsets(singles4d, 2)
152
+ l4d = Line(Point(1, 2, 3, 4), Point(2, 2, 2, 2))
153
+ # test 2D
154
+ test_single = ['contains', 'distance', 'equals', 'parallel_line', 'perpendicular_line', 'perpendicular_segment',
155
+ 'projection', 'intersection']
156
+ for p in doubles2d:
157
+ Line2D(*p)
158
+ for func in test_single:
159
+ for p in singles2d:
160
+ getattr(l2d, func)(p)
161
+ # test 3D
162
+ for p in doubles3d:
163
+ Line3D(*p)
164
+ for func in test_single:
165
+ for p in singles3d:
166
+ getattr(l3d, func)(p)
167
+ # test 4D
168
+ for p in doubles4d:
169
+ Line(*p)
170
+ for func in test_single:
171
+ for p in singles4d:
172
+ getattr(l4d, func)(p)
173
+
174
+
175
+ def test_basic_properties_2d():
176
+ p1 = Point(0, 0)
177
+ p2 = Point(1, 1)
178
+ p10 = Point(2000, 2000)
179
+ p_r3 = Ray(p1, p2).random_point()
180
+ p_r4 = Ray(p2, p1).random_point()
181
+
182
+ l1 = Line(p1, p2)
183
+ l3 = Line(Point(x1, x1), Point(x1, 1 + x1))
184
+ l4 = Line(p1, Point(1, 0))
185
+
186
+ r1 = Ray(p1, Point(0, 1))
187
+ r2 = Ray(Point(0, 1), p1)
188
+
189
+ s1 = Segment(p1, p10)
190
+ p_s1 = s1.random_point()
191
+
192
+ assert Line((1, 1), slope=1) == Line((1, 1), (2, 2))
193
+ assert Line((1, 1), slope=oo) == Line((1, 1), (1, 2))
194
+ assert Line((1, 1), slope=oo).bounds == (1, 1, 1, 2)
195
+ assert Line((1, 1), slope=-oo) == Line((1, 1), (1, 2))
196
+ assert Line(p1, p2).scale(2, 1) == Line(p1, Point(2, 1))
197
+ assert Line(p1, p2) == Line(p1, p2)
198
+ assert Line(p1, p2) != Line(p2, p1)
199
+ assert l1 != Line(Point(x1, x1), Point(y1, y1))
200
+ assert l1 != l3
201
+ assert Line(p1, p10) != Line(p10, p1)
202
+ assert Line(p1, p10) != p1
203
+ assert p1 in l1 # is p1 on the line l1?
204
+ assert p1 not in l3
205
+ assert s1 in Line(p1, p10)
206
+ assert Ray(Point(0, 0), Point(0, 1)) in Ray(Point(0, 0), Point(0, 2))
207
+ assert Ray(Point(0, 0), Point(0, 2)) in Ray(Point(0, 0), Point(0, 1))
208
+ assert Ray(Point(0, 0), Point(0, 2)).xdirection == S.Zero
209
+ assert Ray(Point(0, 0), Point(1, 2)).xdirection == S.Infinity
210
+ assert Ray(Point(0, 0), Point(-1, 2)).xdirection == S.NegativeInfinity
211
+ assert Ray(Point(0, 0), Point(2, 0)).ydirection == S.Zero
212
+ assert Ray(Point(0, 0), Point(2, 2)).ydirection == S.Infinity
213
+ assert Ray(Point(0, 0), Point(2, -2)).ydirection == S.NegativeInfinity
214
+ assert (r1 in s1) is False
215
+ assert Segment(p1, p2) in s1
216
+ assert Ray(Point(x1, x1), Point(x1, 1 + x1)) != Ray(p1, Point(-1, 5))
217
+ assert Segment(p1, p2).midpoint == Point(S.Half, S.Half)
218
+ assert Segment(p1, Point(-x1, x1)).length == sqrt(2 * (x1 ** 2))
219
+
220
+ assert l1.slope == 1
221
+ assert l3.slope is oo
222
+ assert l4.slope == 0
223
+ assert Line(p1, Point(0, 1)).slope is oo
224
+ assert Line(r1.source, r1.random_point()).slope == r1.slope
225
+ assert Line(r2.source, r2.random_point()).slope == r2.slope
226
+ assert Segment(Point(0, -1), Segment(p1, Point(0, 1)).random_point()).slope == Segment(p1, Point(0, 1)).slope
227
+
228
+ assert l4.coefficients == (0, 1, 0)
229
+ assert Line((-x, x), (-x + 1, x - 1)).coefficients == (1, 1, 0)
230
+ assert Line(p1, Point(0, 1)).coefficients == (1, 0, 0)
231
+ # issue 7963
232
+ r = Ray((0, 0), angle=x)
233
+ assert r.subs(x, 3 * pi / 4) == Ray((0, 0), (-1, 1))
234
+ assert r.subs(x, 5 * pi / 4) == Ray((0, 0), (-1, -1))
235
+ assert r.subs(x, -pi / 4) == Ray((0, 0), (1, -1))
236
+ assert r.subs(x, pi / 2) == Ray((0, 0), (0, 1))
237
+ assert r.subs(x, -pi / 2) == Ray((0, 0), (0, -1))
238
+
239
+ for ind in range(0, 5):
240
+ assert l3.random_point() in l3
241
+
242
+ assert p_r3.x >= p1.x and p_r3.y >= p1.y
243
+ assert p_r4.x <= p2.x and p_r4.y <= p2.y
244
+ assert p1.x <= p_s1.x <= p10.x and p1.y <= p_s1.y <= p10.y
245
+ assert hash(s1) != hash(Segment(p10, p1))
246
+
247
+ assert s1.plot_interval() == [t, 0, 1]
248
+ assert Line(p1, p10).plot_interval() == [t, -5, 5]
249
+ assert Ray((0, 0), angle=pi / 4).plot_interval() == [t, 0, 10]
250
+
251
+
252
+ def test_basic_properties_3d():
253
+ p1 = Point3D(0, 0, 0)
254
+ p2 = Point3D(1, 1, 1)
255
+ p3 = Point3D(x1, x1, x1)
256
+ p5 = Point3D(x1, 1 + x1, 1)
257
+
258
+ l1 = Line3D(p1, p2)
259
+ l3 = Line3D(p3, p5)
260
+
261
+ r1 = Ray3D(p1, Point3D(-1, 5, 0))
262
+ r3 = Ray3D(p1, p2)
263
+
264
+ s1 = Segment3D(p1, p2)
265
+
266
+ assert Line3D((1, 1, 1), direction_ratio=[2, 3, 4]) == Line3D(Point3D(1, 1, 1), Point3D(3, 4, 5))
267
+ assert Line3D((1, 1, 1), direction_ratio=[1, 5, 7]) == Line3D(Point3D(1, 1, 1), Point3D(2, 6, 8))
268
+ assert Line3D((1, 1, 1), direction_ratio=[1, 2, 3]) == Line3D(Point3D(1, 1, 1), Point3D(2, 3, 4))
269
+ assert Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0)).direction_cosine == [1, 0, 0]
270
+ assert Line3D(Line3D(p1, Point3D(0, 1, 0))) == Line3D(p1, Point3D(0, 1, 0))
271
+ assert Ray3D(Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0))) == Ray3D(p1, Point3D(1, 0, 0))
272
+ assert Line3D(p1, p2) != Line3D(p2, p1)
273
+ assert l1 != l3
274
+ assert l1 != Line3D(p3, Point3D(y1, y1, y1))
275
+ assert r3 != r1
276
+ assert Ray3D(Point3D(0, 0, 0), Point3D(1, 1, 1)) in Ray3D(Point3D(0, 0, 0), Point3D(2, 2, 2))
277
+ assert Ray3D(Point3D(0, 0, 0), Point3D(2, 2, 2)) in Ray3D(Point3D(0, 0, 0), Point3D(1, 1, 1))
278
+ assert Ray3D(Point3D(0, 0, 0), Point3D(2, 2, 2)).xdirection == S.Infinity
279
+ assert Ray3D(Point3D(0, 0, 0), Point3D(2, 2, 2)).ydirection == S.Infinity
280
+ assert Ray3D(Point3D(0, 0, 0), Point3D(2, 2, 2)).zdirection == S.Infinity
281
+ assert Ray3D(Point3D(0, 0, 0), Point3D(-2, 2, 2)).xdirection == S.NegativeInfinity
282
+ assert Ray3D(Point3D(0, 0, 0), Point3D(2, -2, 2)).ydirection == S.NegativeInfinity
283
+ assert Ray3D(Point3D(0, 0, 0), Point3D(2, 2, -2)).zdirection == S.NegativeInfinity
284
+ assert Ray3D(Point3D(0, 0, 0), Point3D(0, 2, 2)).xdirection == S.Zero
285
+ assert Ray3D(Point3D(0, 0, 0), Point3D(2, 0, 2)).ydirection == S.Zero
286
+ assert Ray3D(Point3D(0, 0, 0), Point3D(2, 2, 0)).zdirection == S.Zero
287
+ assert p1 in l1
288
+ assert p1 not in l3
289
+
290
+ assert l1.direction_ratio == [1, 1, 1]
291
+
292
+ assert s1.midpoint == Point3D(S.Half, S.Half, S.Half)
293
+ # Test zdirection
294
+ assert Ray3D(p1, Point3D(0, 0, -1)).zdirection is S.NegativeInfinity
295
+
296
+
297
+ def test_contains():
298
+ p1 = Point(0, 0)
299
+
300
+ r = Ray(p1, Point(4, 4))
301
+ r1 = Ray3D(p1, Point3D(0, 0, -1))
302
+ r2 = Ray3D(p1, Point3D(0, 1, 0))
303
+ r3 = Ray3D(p1, Point3D(0, 0, 1))
304
+
305
+ l = Line(Point(0, 1), Point(3, 4))
306
+ # Segment contains
307
+ assert Point(0, (a + b) / 2) in Segment((0, a), (0, b))
308
+ assert Point((a + b) / 2, 0) in Segment((a, 0), (b, 0))
309
+ assert Point3D(0, 1, 0) in Segment3D((0, 1, 0), (0, 1, 0))
310
+ assert Point3D(1, 0, 0) in Segment3D((1, 0, 0), (1, 0, 0))
311
+ assert Segment3D(Point3D(0, 0, 0), Point3D(1, 0, 0)).contains([]) is True
312
+ assert Segment3D(Point3D(0, 0, 0), Point3D(1, 0, 0)).contains(
313
+ Segment3D(Point3D(2, 2, 2), Point3D(3, 2, 2))) is False
314
+ # Line contains
315
+ assert l.contains(Point(0, 1)) is True
316
+ assert l.contains((0, 1)) is True
317
+ assert l.contains((0, 0)) is False
318
+ # Ray contains
319
+ assert r.contains(p1) is True
320
+ assert r.contains((1, 1)) is True
321
+ assert r.contains((1, 3)) is False
322
+ assert r.contains(Segment((1, 1), (2, 2))) is True
323
+ assert r.contains(Segment((1, 2), (2, 5))) is False
324
+ assert r.contains(Ray((2, 2), (3, 3))) is True
325
+ assert r.contains(Ray((2, 2), (3, 5))) is False
326
+ assert r1.contains(Segment3D(p1, Point3D(0, 0, -10))) is True
327
+ assert r1.contains(Segment3D(Point3D(1, 1, 1), Point3D(2, 2, 2))) is False
328
+ assert r2.contains(Point3D(0, 0, 0)) is True
329
+ assert r3.contains(Point3D(0, 0, 0)) is True
330
+ assert Ray3D(Point3D(1, 1, 1), Point3D(1, 0, 0)).contains([]) is False
331
+ assert Line3D((0, 0, 0), (x, y, z)).contains((2 * x, 2 * y, 2 * z))
332
+ with warns(UserWarning, test_stacklevel=False):
333
+ assert Line3D(p1, Point3D(0, 1, 0)).contains(Point(1.0, 1.0)) is False
334
+
335
+ with warns(UserWarning, test_stacklevel=False):
336
+ assert r3.contains(Point(1.0, 1.0)) is False
337
+
338
+
339
+ def test_contains_nonreal_symbols():
340
+ u, v, w, z = symbols('u, v, w, z')
341
+ l = Segment(Point(u, w), Point(v, z))
342
+ p = Point(u*Rational(2, 3) + v/3, w*Rational(2, 3) + z/3)
343
+ assert l.contains(p)
344
+
345
+
346
+ def test_distance_2d():
347
+ p1 = Point(0, 0)
348
+ p2 = Point(1, 1)
349
+ half = S.Half
350
+
351
+ s1 = Segment(Point(0, 0), Point(1, 1))
352
+ s2 = Segment(Point(half, half), Point(1, 0))
353
+
354
+ r = Ray(p1, p2)
355
+
356
+ assert s1.distance(Point(0, 0)) == 0
357
+ assert s1.distance((0, 0)) == 0
358
+ assert s2.distance(Point(0, 0)) == 2 ** half / 2
359
+ assert s2.distance(Point(Rational(3) / 2, Rational(3) / 2)) == 2 ** half
360
+ assert Line(p1, p2).distance(Point(-1, 1)) == sqrt(2)
361
+ assert Line(p1, p2).distance(Point(1, -1)) == sqrt(2)
362
+ assert Line(p1, p2).distance(Point(2, 2)) == 0
363
+ assert Line(p1, p2).distance((-1, 1)) == sqrt(2)
364
+ assert Line((0, 0), (0, 1)).distance(p1) == 0
365
+ assert Line((0, 0), (0, 1)).distance(p2) == 1
366
+ assert Line((0, 0), (1, 0)).distance(p1) == 0
367
+ assert Line((0, 0), (1, 0)).distance(p2) == 1
368
+ assert r.distance(Point(-1, -1)) == sqrt(2)
369
+ assert r.distance(Point(1, 1)) == 0
370
+ assert r.distance(Point(-1, 1)) == sqrt(2)
371
+ assert Ray((1, 1), (2, 2)).distance(Point(1.5, 3)) == 3 * sqrt(2) / 4
372
+ assert r.distance((1, 1)) == 0
373
+
374
+
375
+ def test_dimension_normalization():
376
+ with warns(UserWarning, test_stacklevel=False):
377
+ assert Ray((1, 1), (2, 1, 2)) == Ray((1, 1, 0), (2, 1, 2))
378
+
379
+
380
+ def test_distance_3d():
381
+ p1, p2 = Point3D(0, 0, 0), Point3D(1, 1, 1)
382
+ p3 = Point3D(Rational(3) / 2, Rational(3) / 2, Rational(3) / 2)
383
+
384
+ s1 = Segment3D(Point3D(0, 0, 0), Point3D(1, 1, 1))
385
+ s2 = Segment3D(Point3D(S.Half, S.Half, S.Half), Point3D(1, 0, 1))
386
+
387
+ r = Ray3D(p1, p2)
388
+
389
+ assert s1.distance(p1) == 0
390
+ assert s2.distance(p1) == sqrt(3) / 2
391
+ assert s2.distance(p3) == 2 * sqrt(6) / 3
392
+ assert s1.distance((0, 0, 0)) == 0
393
+ assert s2.distance((0, 0, 0)) == sqrt(3) / 2
394
+ assert s1.distance(p1) == 0
395
+ assert s2.distance(p1) == sqrt(3) / 2
396
+ assert s2.distance(p3) == 2 * sqrt(6) / 3
397
+ assert s1.distance((0, 0, 0)) == 0
398
+ assert s2.distance((0, 0, 0)) == sqrt(3) / 2
399
+ # Line to point
400
+ assert Line3D(p1, p2).distance(Point3D(-1, 1, 1)) == 2 * sqrt(6) / 3
401
+ assert Line3D(p1, p2).distance(Point3D(1, -1, 1)) == 2 * sqrt(6) / 3
402
+ assert Line3D(p1, p2).distance(Point3D(2, 2, 2)) == 0
403
+ assert Line3D(p1, p2).distance((2, 2, 2)) == 0
404
+ assert Line3D(p1, p2).distance((1, -1, 1)) == 2 * sqrt(6) / 3
405
+ assert Line3D((0, 0, 0), (0, 1, 0)).distance(p1) == 0
406
+ assert Line3D((0, 0, 0), (0, 1, 0)).distance(p2) == sqrt(2)
407
+ assert Line3D((0, 0, 0), (1, 0, 0)).distance(p1) == 0
408
+ assert Line3D((0, 0, 0), (1, 0, 0)).distance(p2) == sqrt(2)
409
+ # Ray to point
410
+ assert r.distance(Point3D(-1, -1, -1)) == sqrt(3)
411
+ assert r.distance(Point3D(1, 1, 1)) == 0
412
+ assert r.distance((-1, -1, -1)) == sqrt(3)
413
+ assert r.distance((1, 1, 1)) == 0
414
+ assert Ray3D((0, 0, 0), (1, 1, 2)).distance((-1, -1, 2)) == 4 * sqrt(3) / 3
415
+ assert Ray3D((1, 1, 1), (2, 2, 2)).distance(Point3D(1.5, -3, -1)) == Rational(9) / 2
416
+ assert Ray3D((1, 1, 1), (2, 2, 2)).distance(Point3D(1.5, 3, 1)) == sqrt(78) / 6
417
+
418
+
419
+ def test_equals():
420
+ p1 = Point(0, 0)
421
+ p2 = Point(1, 1)
422
+
423
+ l1 = Line(p1, p2)
424
+ l2 = Line((0, 5), slope=m)
425
+ l3 = Line(Point(x1, x1), Point(x1, 1 + x1))
426
+
427
+ assert l1.perpendicular_line(p1.args).equals(Line(Point(0, 0), Point(1, -1)))
428
+ assert l1.perpendicular_line(p1).equals(Line(Point(0, 0), Point(1, -1)))
429
+ assert Line(Point(x1, x1), Point(y1, y1)).parallel_line(Point(-x1, x1)). \
430
+ equals(Line(Point(-x1, x1), Point(-y1, 2 * x1 - y1)))
431
+ assert l3.parallel_line(p1.args).equals(Line(Point(0, 0), Point(0, -1)))
432
+ assert l3.parallel_line(p1).equals(Line(Point(0, 0), Point(0, -1)))
433
+ assert (l2.distance(Point(2, 3)) - 2 * abs(m + 1) / sqrt(m ** 2 + 1)).equals(0)
434
+ assert Line3D(p1, Point3D(0, 1, 0)).equals(Point(1.0, 1.0)) is False
435
+ assert Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0)).equals(Line3D(Point3D(-5, 0, 0), Point3D(-1, 0, 0))) is True
436
+ assert Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0)).equals(Line3D(p1, Point3D(0, 1, 0))) is False
437
+ assert Ray3D(p1, Point3D(0, 0, -1)).equals(Point(1.0, 1.0)) is False
438
+ assert Ray3D(p1, Point3D(0, 0, -1)).equals(Ray3D(p1, Point3D(0, 0, -1))) is True
439
+ assert Line3D((0, 0), (t, t)).perpendicular_line(Point(0, 1, 0)).equals(
440
+ Line3D(Point3D(0, 1, 0), Point3D(S.Half, S.Half, 0)))
441
+ assert Line3D((0, 0), (t, t)).perpendicular_segment(Point(0, 1, 0)).equals(Segment3D((0, 1), (S.Half, S.Half)))
442
+ assert Line3D(p1, Point3D(0, 1, 0)).equals(Point(1.0, 1.0)) is False
443
+
444
+
445
+ def test_equation():
446
+ p1 = Point(0, 0)
447
+ p2 = Point(1, 1)
448
+ l1 = Line(p1, p2)
449
+ l3 = Line(Point(x1, x1), Point(x1, 1 + x1))
450
+
451
+ assert simplify(l1.equation()) in (x - y, y - x)
452
+ assert simplify(l3.equation()) in (x - x1, x1 - x)
453
+ assert simplify(l1.equation()) in (x - y, y - x)
454
+ assert simplify(l3.equation()) in (x - x1, x1 - x)
455
+
456
+ assert Line(p1, Point(1, 0)).equation(x=x, y=y) == y
457
+ assert Line(p1, Point(0, 1)).equation() == x
458
+ assert Line(Point(2, 0), Point(2, 1)).equation() == x - 2
459
+ assert Line(p2, Point(2, 1)).equation() == y - 1
460
+
461
+ assert Line3D(Point(x1, x1, x1), Point(y1, y1, y1)
462
+ ).equation() == (-x + y, -x + z)
463
+ assert Line3D(Point(1, 2, 3), Point(2, 3, 4)
464
+ ).equation() == (-x + y - 1, -x + z - 2)
465
+ assert Line3D(Point(1, 2, 3), Point(1, 3, 4)
466
+ ).equation() == (x - 1, -y + z - 1)
467
+ assert Line3D(Point(1, 2, 3), Point(2, 2, 4)
468
+ ).equation() == (y - 2, -x + z - 2)
469
+ assert Line3D(Point(1, 2, 3), Point(2, 3, 3)
470
+ ).equation() == (-x + y - 1, z - 3)
471
+ assert Line3D(Point(1, 2, 3), Point(1, 2, 4)
472
+ ).equation() == (x - 1, y - 2)
473
+ assert Line3D(Point(1, 2, 3), Point(1, 3, 3)
474
+ ).equation() == (x - 1, z - 3)
475
+ assert Line3D(Point(1, 2, 3), Point(2, 2, 3)
476
+ ).equation() == (y - 2, z - 3)
477
+
478
+
479
+ def test_intersection_2d():
480
+ p1 = Point(0, 0)
481
+ p2 = Point(1, 1)
482
+ p3 = Point(x1, x1)
483
+ p4 = Point(y1, y1)
484
+
485
+ l1 = Line(p1, p2)
486
+ l3 = Line(Point(0, 0), Point(3, 4))
487
+
488
+ r1 = Ray(Point(1, 1), Point(2, 2))
489
+ r2 = Ray(Point(0, 0), Point(3, 4))
490
+ r4 = Ray(p1, p2)
491
+ r6 = Ray(Point(0, 1), Point(1, 2))
492
+ r7 = Ray(Point(0.5, 0.5), Point(1, 1))
493
+
494
+ s1 = Segment(p1, p2)
495
+ s2 = Segment(Point(0.25, 0.25), Point(0.5, 0.5))
496
+ s3 = Segment(Point(0, 0), Point(3, 4))
497
+
498
+ assert intersection(l1, p1) == [p1]
499
+ assert intersection(l1, Point(x1, 1 + x1)) == []
500
+ assert intersection(l1, Line(p3, p4)) in [[l1], [Line(p3, p4)]]
501
+ assert intersection(l1, l1.parallel_line(Point(x1, 1 + x1))) == []
502
+ assert intersection(l3, l3) == [l3]
503
+ assert intersection(l3, r2) == [r2]
504
+ assert intersection(l3, s3) == [s3]
505
+ assert intersection(s3, l3) == [s3]
506
+ assert intersection(Segment(Point(-10, 10), Point(10, 10)), Segment(Point(-5, -5), Point(-5, 5))) == []
507
+ assert intersection(r2, l3) == [r2]
508
+ assert intersection(r1, Ray(Point(2, 2), Point(0, 0))) == [Segment(Point(1, 1), Point(2, 2))]
509
+ assert intersection(r1, Ray(Point(1, 1), Point(-1, -1))) == [Point(1, 1)]
510
+ assert intersection(r1, Segment(Point(0, 0), Point(2, 2))) == [Segment(Point(1, 1), Point(2, 2))]
511
+
512
+ assert r4.intersection(s2) == [s2]
513
+ assert r4.intersection(Segment(Point(2, 3), Point(3, 4))) == []
514
+ assert r4.intersection(Segment(Point(-1, -1), Point(0.5, 0.5))) == [Segment(p1, Point(0.5, 0.5))]
515
+ assert r4.intersection(Ray(p2, p1)) == [s1]
516
+ assert Ray(p2, p1).intersection(r6) == []
517
+ assert r4.intersection(r7) == r7.intersection(r4) == [r7]
518
+ assert Ray3D((0, 0), (3, 0)).intersection(Ray3D((1, 0), (3, 0))) == [Ray3D((1, 0), (3, 0))]
519
+ assert Ray3D((1, 0), (3, 0)).intersection(Ray3D((0, 0), (3, 0))) == [Ray3D((1, 0), (3, 0))]
520
+ assert Ray(Point(0, 0), Point(0, 4)).intersection(Ray(Point(0, 1), Point(0, -1))) == \
521
+ [Segment(Point(0, 0), Point(0, 1))]
522
+
523
+ assert Segment3D((0, 0), (3, 0)).intersection(
524
+ Segment3D((1, 0), (2, 0))) == [Segment3D((1, 0), (2, 0))]
525
+ assert Segment3D((1, 0), (2, 0)).intersection(
526
+ Segment3D((0, 0), (3, 0))) == [Segment3D((1, 0), (2, 0))]
527
+ assert Segment3D((0, 0), (3, 0)).intersection(
528
+ Segment3D((3, 0), (4, 0))) == [Point3D((3, 0))]
529
+ assert Segment3D((0, 0), (3, 0)).intersection(
530
+ Segment3D((2, 0), (5, 0))) == [Segment3D((2, 0), (3, 0))]
531
+ assert Segment3D((0, 0), (3, 0)).intersection(
532
+ Segment3D((-2, 0), (1, 0))) == [Segment3D((0, 0), (1, 0))]
533
+ assert Segment3D((0, 0), (3, 0)).intersection(
534
+ Segment3D((-2, 0), (0, 0))) == [Point3D(0, 0)]
535
+ assert s1.intersection(Segment(Point(1, 1), Point(2, 2))) == [Point(1, 1)]
536
+ assert s1.intersection(Segment(Point(0.5, 0.5), Point(1.5, 1.5))) == [Segment(Point(0.5, 0.5), p2)]
537
+ assert s1.intersection(Segment(Point(4, 4), Point(5, 5))) == []
538
+ assert s1.intersection(Segment(Point(-1, -1), p1)) == [p1]
539
+ assert s1.intersection(Segment(Point(-1, -1), Point(0.5, 0.5))) == [Segment(p1, Point(0.5, 0.5))]
540
+ assert s1.intersection(Line(Point(1, 0), Point(2, 1))) == []
541
+ assert s1.intersection(s2) == [s2]
542
+ assert s2.intersection(s1) == [s2]
543
+
544
+ assert asa(120, 8, 52) == \
545
+ Triangle(
546
+ Point(0, 0),
547
+ Point(8, 0),
548
+ Point(-4 * cos(19 * pi / 90) / sin(2 * pi / 45),
549
+ 4 * sqrt(3) * cos(19 * pi / 90) / sin(2 * pi / 45)))
550
+ assert Line((0, 0), (1, 1)).intersection(Ray((1, 0), (1, 2))) == [Point(1, 1)]
551
+ assert Line((0, 0), (1, 1)).intersection(Segment((1, 0), (1, 2))) == [Point(1, 1)]
552
+ assert Ray((0, 0), (1, 1)).intersection(Ray((1, 0), (1, 2))) == [Point(1, 1)]
553
+ assert Ray((0, 0), (1, 1)).intersection(Segment((1, 0), (1, 2))) == [Point(1, 1)]
554
+ assert Ray((0, 0), (10, 10)).contains(Segment((1, 1), (2, 2))) is True
555
+ assert Segment((1, 1), (2, 2)) in Line((0, 0), (10, 10))
556
+ assert s1.intersection(Ray((1, 1), (4, 4))) == [Point(1, 1)]
557
+
558
+ # This test is disabled because it hangs after rref changes which simplify
559
+ # intermediate results and return a different representation from when the
560
+ # test was written.
561
+ # # 16628 - this should be fast
562
+ # p0 = Point2D(Rational(249, 5), Rational(497999, 10000))
563
+ # p1 = Point2D((-58977084786*sqrt(405639795226) + 2030690077184193 +
564
+ # 20112207807*sqrt(630547164901) + 99600*sqrt(255775022850776494562626))
565
+ # /(2000*sqrt(255775022850776494562626) + 1991998000*sqrt(405639795226)
566
+ # + 1991998000*sqrt(630547164901) + 1622561172902000),
567
+ # (-498000*sqrt(255775022850776494562626) - 995999*sqrt(630547164901) +
568
+ # 90004251917891999 +
569
+ # 496005510002*sqrt(405639795226))/(10000*sqrt(255775022850776494562626)
570
+ # + 9959990000*sqrt(405639795226) + 9959990000*sqrt(630547164901) +
571
+ # 8112805864510000))
572
+ # p2 = Point2D(Rational(497, 10), Rational(-497, 10))
573
+ # p3 = Point2D(Rational(-497, 10), Rational(-497, 10))
574
+ # l = Line(p0, p1)
575
+ # s = Segment(p2, p3)
576
+ # n = (-52673223862*sqrt(405639795226) - 15764156209307469 -
577
+ # 9803028531*sqrt(630547164901) +
578
+ # 33200*sqrt(255775022850776494562626))
579
+ # d = sqrt(405639795226) + 315274080450 + 498000*sqrt(
580
+ # 630547164901) + sqrt(255775022850776494562626)
581
+ # assert intersection(l, s) == [
582
+ # Point2D(n/d*Rational(3, 2000), Rational(-497, 10))]
583
+
584
+
585
+ def test_line_intersection():
586
+ # see also test_issue_11238 in test_matrices.py
587
+ x0 = tan(pi*Rational(13, 45))
588
+ x1 = sqrt(3)
589
+ x2 = x0**2
590
+ x, y = [8*x0/(x0 + x1), (24*x0 - 8*x1*x2)/(x2 - 3)]
591
+ assert Line(Point(0, 0), Point(1, -sqrt(3))).contains(Point(x, y)) is True
592
+
593
+
594
+ def test_intersection_3d():
595
+ p1 = Point3D(0, 0, 0)
596
+ p2 = Point3D(1, 1, 1)
597
+
598
+ l1 = Line3D(p1, p2)
599
+ l2 = Line3D(Point3D(0, 0, 0), Point3D(3, 4, 0))
600
+
601
+ r1 = Ray3D(Point3D(1, 1, 1), Point3D(2, 2, 2))
602
+ r2 = Ray3D(Point3D(0, 0, 0), Point3D(3, 4, 0))
603
+
604
+ s1 = Segment3D(Point3D(0, 0, 0), Point3D(3, 4, 0))
605
+
606
+ assert intersection(l1, p1) == [p1]
607
+ assert intersection(l1, Point3D(x1, 1 + x1, 1)) == []
608
+ assert intersection(l1, l1.parallel_line(p1)) == [Line3D(Point3D(0, 0, 0), Point3D(1, 1, 1))]
609
+ assert intersection(l2, r2) == [r2]
610
+ assert intersection(l2, s1) == [s1]
611
+ assert intersection(r2, l2) == [r2]
612
+ assert intersection(r1, Ray3D(Point3D(1, 1, 1), Point3D(-1, -1, -1))) == [Point3D(1, 1, 1)]
613
+ assert intersection(r1, Segment3D(Point3D(0, 0, 0), Point3D(2, 2, 2))) == [
614
+ Segment3D(Point3D(1, 1, 1), Point3D(2, 2, 2))]
615
+ assert intersection(Ray3D(Point3D(1, 0, 0), Point3D(-1, 0, 0)), Ray3D(Point3D(0, 1, 0), Point3D(0, -1, 0))) \
616
+ == [Point3D(0, 0, 0)]
617
+ assert intersection(r1, Ray3D(Point3D(2, 2, 2), Point3D(0, 0, 0))) == \
618
+ [Segment3D(Point3D(1, 1, 1), Point3D(2, 2, 2))]
619
+ assert intersection(s1, r2) == [s1]
620
+
621
+ assert Line3D(Point3D(4, 0, 1), Point3D(0, 4, 1)).intersection(Line3D(Point3D(0, 0, 1), Point3D(4, 4, 1))) == \
622
+ [Point3D(2, 2, 1)]
623
+ assert Line3D((0, 1, 2), (0, 2, 3)).intersection(Line3D((0, 1, 2), (0, 1, 1))) == [Point3D(0, 1, 2)]
624
+ assert Line3D((0, 0), (t, t)).intersection(Line3D((0, 1), (t, t))) == \
625
+ [Point3D(t, t)]
626
+
627
+ assert Ray3D(Point3D(0, 0, 0), Point3D(0, 4, 0)).intersection(Ray3D(Point3D(0, 1, 1), Point3D(0, -1, 1))) == []
628
+
629
+
630
+ def test_is_parallel():
631
+ p1 = Point3D(0, 0, 0)
632
+ p2 = Point3D(1, 1, 1)
633
+ p3 = Point3D(x1, x1, x1)
634
+
635
+ l2 = Line(Point(x1, x1), Point(y1, y1))
636
+ l2_1 = Line(Point(x1, x1), Point(x1, 1 + x1))
637
+
638
+ assert Line.is_parallel(Line(Point(0, 0), Point(1, 1)), l2)
639
+ assert Line.is_parallel(l2, Line(Point(x1, x1), Point(x1, 1 + x1))) is False
640
+ assert Line.is_parallel(l2, l2.parallel_line(Point(-x1, x1)))
641
+ assert Line.is_parallel(l2_1, l2_1.parallel_line(Point(0, 0)))
642
+ assert Line3D(p1, p2).is_parallel(Line3D(p1, p2)) # same as in 2D
643
+ assert Line3D(Point3D(4, 0, 1), Point3D(0, 4, 1)).is_parallel(Line3D(Point3D(0, 0, 1), Point3D(4, 4, 1))) is False
644
+ assert Line3D(p1, p2).parallel_line(p3) == Line3D(Point3D(x1, x1, x1),
645
+ Point3D(x1 + 1, x1 + 1, x1 + 1))
646
+ assert Line3D(p1, p2).parallel_line(p3.args) == \
647
+ Line3D(Point3D(x1, x1, x1), Point3D(x1 + 1, x1 + 1, x1 + 1))
648
+ assert Line3D(Point3D(4, 0, 1), Point3D(0, 4, 1)).is_parallel(Line3D(Point3D(0, 0, 1), Point3D(4, 4, 1))) is False
649
+
650
+
651
+ def test_is_perpendicular():
652
+ p1 = Point(0, 0)
653
+ p2 = Point(1, 1)
654
+
655
+ l1 = Line(p1, p2)
656
+ l2 = Line(Point(x1, x1), Point(y1, y1))
657
+ l1_1 = Line(p1, Point(-x1, x1))
658
+ # 2D
659
+ assert Line.is_perpendicular(l1, l1_1)
660
+ assert Line.is_perpendicular(l1, l2) is False
661
+ p = l1.random_point()
662
+ assert l1.perpendicular_segment(p) == p
663
+ # 3D
664
+ assert Line3D.is_perpendicular(Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0)),
665
+ Line3D(Point3D(0, 0, 0), Point3D(0, 1, 0))) is True
666
+ assert Line3D.is_perpendicular(Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0)),
667
+ Line3D(Point3D(0, 1, 0), Point3D(1, 1, 0))) is False
668
+ assert Line3D.is_perpendicular(Line3D(Point3D(0, 0, 0), Point3D(1, 1, 1)),
669
+ Line3D(Point3D(x1, x1, x1), Point3D(y1, y1, y1))) is False
670
+
671
+
672
+ def test_is_similar():
673
+ p1 = Point(2000, 2000)
674
+ p2 = p1.scale(2, 2)
675
+
676
+ r1 = Ray3D(Point3D(1, 1, 1), Point3D(1, 0, 0))
677
+ r2 = Ray(Point(0, 0), Point(0, 1))
678
+
679
+ s1 = Segment(Point(0, 0), p1)
680
+
681
+ assert s1.is_similar(Segment(p1, p2))
682
+ assert s1.is_similar(r2) is False
683
+ assert r1.is_similar(Line3D(Point3D(1, 1, 1), Point3D(1, 0, 0))) is True
684
+ assert r1.is_similar(Line3D(Point3D(0, 0, 0), Point3D(0, 1, 0))) is False
685
+
686
+
687
+ def test_length():
688
+ s2 = Segment3D(Point3D(x1, x1, x1), Point3D(y1, y1, y1))
689
+ assert Line(Point(0, 0), Point(1, 1)).length is oo
690
+ assert s2.length == sqrt(3) * sqrt((x1 - y1) ** 2)
691
+ assert Line3D(Point3D(0, 0, 0), Point3D(1, 1, 1)).length is oo
692
+
693
+
694
+ def test_projection():
695
+ p1 = Point(0, 0)
696
+ p2 = Point3D(0, 0, 0)
697
+ p3 = Point(-x1, x1)
698
+
699
+ l1 = Line(p1, Point(1, 1))
700
+ l2 = Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0))
701
+ l3 = Line3D(p2, Point3D(1, 1, 1))
702
+
703
+ r1 = Ray(Point(1, 1), Point(2, 2))
704
+
705
+ s1 = Segment(Point2D(0, 0), Point2D(0, 1))
706
+ s2 = Segment(Point2D(1, 0), Point2D(2, 1/2))
707
+
708
+ assert Line(Point(x1, x1), Point(y1, y1)).projection(Point(y1, y1)) == Point(y1, y1)
709
+ assert Line(Point(x1, x1), Point(x1, 1 + x1)).projection(Point(1, 1)) == Point(x1, 1)
710
+ assert Segment(Point(-2, 2), Point(0, 4)).projection(r1) == Segment(Point(-1, 3), Point(0, 4))
711
+ assert Segment(Point(0, 4), Point(-2, 2)).projection(r1) == Segment(Point(0, 4), Point(-1, 3))
712
+ assert s2.projection(s1) == EmptySet
713
+ assert l1.projection(p3) == p1
714
+ assert l1.projection(Ray(p1, Point(-1, 5))) == Ray(Point(0, 0), Point(2, 2))
715
+ assert l1.projection(Ray(p1, Point(-1, 1))) == p1
716
+ assert r1.projection(Ray(Point(1, 1), Point(-1, -1))) == Point(1, 1)
717
+ assert r1.projection(Ray(Point(0, 4), Point(-1, -5))) == Segment(Point(1, 1), Point(2, 2))
718
+ assert r1.projection(Segment(Point(-1, 5), Point(-5, -10))) == Segment(Point(1, 1), Point(2, 2))
719
+ assert r1.projection(Ray(Point(1, 1), Point(-1, -1))) == Point(1, 1)
720
+ assert r1.projection(Ray(Point(0, 4), Point(-1, -5))) == Segment(Point(1, 1), Point(2, 2))
721
+ assert r1.projection(Segment(Point(-1, 5), Point(-5, -10))) == Segment(Point(1, 1), Point(2, 2))
722
+
723
+ assert l3.projection(Ray3D(p2, Point3D(-1, 5, 0))) == Ray3D(Point3D(0, 0, 0), Point3D(Rational(4, 3), Rational(4, 3), Rational(4, 3)))
724
+ assert l3.projection(Ray3D(p2, Point3D(-1, 1, 1))) == Ray3D(Point3D(0, 0, 0), Point3D(Rational(1, 3), Rational(1, 3), Rational(1, 3)))
725
+ assert l2.projection(Point3D(5, 5, 0)) == Point3D(5, 0)
726
+ assert l2.projection(Line3D(Point3D(0, 1, 0), Point3D(1, 1, 0))).equals(l2)
727
+
728
+
729
+ def test_perpendicular_line():
730
+ # 3d - requires a particular orthogonal to be selected
731
+ p1, p2, p3 = Point(0, 0, 0), Point(2, 3, 4), Point(-2, 2, 0)
732
+ l = Line(p1, p2)
733
+ p = l.perpendicular_line(p3)
734
+ assert p.p1 == p3
735
+ assert p.p2 in l
736
+ # 2d - does not require special selection
737
+ p1, p2, p3 = Point(0, 0), Point(2, 3), Point(-2, 2)
738
+ l = Line(p1, p2)
739
+ p = l.perpendicular_line(p3)
740
+ assert p.p1 == p3
741
+ # p is directed from l to p3
742
+ assert p.direction.unit == (p3 - l.projection(p3)).unit
743
+
744
+
745
+ def test_perpendicular_bisector():
746
+ s1 = Segment(Point(0, 0), Point(1, 1))
747
+ aline = Line(Point(S.Half, S.Half), Point(Rational(3, 2), Rational(-1, 2)))
748
+ on_line = Segment(Point(S.Half, S.Half), Point(Rational(3, 2), Rational(-1, 2))).midpoint
749
+
750
+ assert s1.perpendicular_bisector().equals(aline)
751
+ assert s1.perpendicular_bisector(on_line).equals(Segment(s1.midpoint, on_line))
752
+ assert s1.perpendicular_bisector(on_line + (1, 0)).equals(aline)
753
+
754
+
755
+ def test_raises():
756
+ d, e = symbols('a,b', real=True)
757
+ s = Segment((d, 0), (e, 0))
758
+
759
+ raises(TypeError, lambda: Line((1, 1), 1))
760
+ raises(ValueError, lambda: Line(Point(0, 0), Point(0, 0)))
761
+ raises(Undecidable, lambda: Point(2 * d, 0) in s)
762
+ raises(ValueError, lambda: Ray3D(Point(1.0, 1.0)))
763
+ raises(ValueError, lambda: Line3D(Point3D(0, 0, 0), Point3D(0, 0, 0)))
764
+ raises(TypeError, lambda: Line3D((1, 1), 1))
765
+ raises(ValueError, lambda: Line3D(Point3D(0, 0, 0)))
766
+ raises(TypeError, lambda: Ray((1, 1), 1))
767
+ raises(GeometryError, lambda: Line(Point(0, 0), Point(1, 0))
768
+ .projection(Circle(Point(0, 0), 1)))
769
+
770
+
771
+ def test_ray_generation():
772
+ assert Ray((1, 1), angle=pi / 4) == Ray((1, 1), (2, 2))
773
+ assert Ray((1, 1), angle=pi / 2) == Ray((1, 1), (1, 2))
774
+ assert Ray((1, 1), angle=-pi / 2) == Ray((1, 1), (1, 0))
775
+ assert Ray((1, 1), angle=-3 * pi / 2) == Ray((1, 1), (1, 2))
776
+ assert Ray((1, 1), angle=5 * pi / 2) == Ray((1, 1), (1, 2))
777
+ assert Ray((1, 1), angle=5.0 * pi / 2) == Ray((1, 1), (1, 2))
778
+ assert Ray((1, 1), angle=pi) == Ray((1, 1), (0, 1))
779
+ assert Ray((1, 1), angle=3.0 * pi) == Ray((1, 1), (0, 1))
780
+ assert Ray((1, 1), angle=4.0 * pi) == Ray((1, 1), (2, 1))
781
+ assert Ray((1, 1), angle=0) == Ray((1, 1), (2, 1))
782
+ assert Ray((1, 1), angle=4.05 * pi) == Ray(Point(1, 1),
783
+ Point(2, -sqrt(5) * sqrt(2 * sqrt(5) + 10) / 4 - sqrt(
784
+ 2 * sqrt(5) + 10) / 4 + 2 + sqrt(5)))
785
+ assert Ray((1, 1), angle=4.02 * pi) == Ray(Point(1, 1),
786
+ Point(2, 1 + tan(4.02 * pi)))
787
+ assert Ray((1, 1), angle=5) == Ray((1, 1), (2, 1 + tan(5)))
788
+
789
+ assert Ray3D((1, 1, 1), direction_ratio=[4, 4, 4]) == Ray3D(Point3D(1, 1, 1), Point3D(5, 5, 5))
790
+ assert Ray3D((1, 1, 1), direction_ratio=[1, 2, 3]) == Ray3D(Point3D(1, 1, 1), Point3D(2, 3, 4))
791
+ assert Ray3D((1, 1, 1), direction_ratio=[1, 1, 1]) == Ray3D(Point3D(1, 1, 1), Point3D(2, 2, 2))
792
+
793
+
794
+ def test_issue_7814():
795
+ circle = Circle(Point(x, 0), y)
796
+ line = Line(Point(k, z), slope=0)
797
+ _s = sqrt((y - z)*(y + z))
798
+ assert line.intersection(circle) == [Point2D(x + _s, z), Point2D(x - _s, z)]
799
+
800
+
801
+ def test_issue_2941():
802
+ def _check():
803
+ for f, g in cartes(*[(Line, Ray, Segment)] * 2):
804
+ l1 = f(a, b)
805
+ l2 = g(c, d)
806
+ assert l1.intersection(l2) == l2.intersection(l1)
807
+ # intersect at end point
808
+ c, d = (-2, -2), (-2, 0)
809
+ a, b = (0, 0), (1, 1)
810
+ _check()
811
+ # midline intersection
812
+ c, d = (-2, -3), (-2, 0)
813
+ _check()
814
+
815
+
816
+ def test_parameter_value():
817
+ t = Symbol('t')
818
+ p1, p2 = Point(0, 1), Point(5, 6)
819
+ l = Line(p1, p2)
820
+ assert l.parameter_value((5, 6), t) == {t: 1}
821
+ raises(ValueError, lambda: l.parameter_value((0, 0), t))
822
+
823
+
824
+ def test_bisectors():
825
+ r1 = Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0))
826
+ r2 = Line3D(Point3D(0, 0, 0), Point3D(0, 1, 0))
827
+ bisections = r1.bisectors(r2)
828
+ assert bisections == [Line3D(Point3D(0, 0, 0), Point3D(1, 1, 0)),
829
+ Line3D(Point3D(0, 0, 0), Point3D(1, -1, 0))]
830
+ ans = [Line3D(Point3D(0, 0, 0), Point3D(1, 0, 1)),
831
+ Line3D(Point3D(0, 0, 0), Point3D(-1, 0, 1))]
832
+ l1 = (0, 0, 0), (0, 0, 1)
833
+ l2 = (0, 0), (1, 0)
834
+ for a, b in cartes((Line, Segment, Ray), repeat=2):
835
+ assert a(*l1).bisectors(b(*l2)) == ans
836
+
837
+
838
+ def test_issue_8615():
839
+ a = Line3D(Point3D(6, 5, 0), Point3D(6, -6, 0))
840
+ b = Line3D(Point3D(6, -1, 19/10), Point3D(6, -1, 0))
841
+ assert a.intersection(b) == [Point3D(6, -1, 0)]
842
+
843
+
844
+ def test_issue_12598():
845
+ r1 = Ray(Point(0, 1), Point(0.98, 0.79).n(2))
846
+ r2 = Ray(Point(0, 0), Point(0.71, 0.71).n(2))
847
+ assert str(r1.intersection(r2)[0]) == 'Point2D(0.82, 0.82)'
848
+ l1 = Line((0, 0), (1, 1))
849
+ l2 = Segment((-1, 1), (0, -1)).n(2)
850
+ assert str(l1.intersection(l2)[0]) == 'Point2D(-0.33, -0.33)'
851
+ l2 = Segment((-1, 1), (-1/2, 1/2)).n(2)
852
+ assert not l1.intersection(l2)
llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/test_parabola.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import (Rational, oo)
2
+ from sympy.core.singleton import S
3
+ from sympy.core.symbol import symbols
4
+ from sympy.functions.elementary.complexes import sign
5
+ from sympy.functions.elementary.miscellaneous import sqrt
6
+ from sympy.geometry.ellipse import (Circle, Ellipse)
7
+ from sympy.geometry.line import (Line, Ray2D, Segment2D)
8
+ from sympy.geometry.parabola import Parabola
9
+ from sympy.geometry.point import (Point, Point2D)
10
+ from sympy.testing.pytest import raises
11
+
12
+ from sympy.abc import x, y
13
+
14
+ def test_parabola_geom():
15
+ a, b = symbols('a b')
16
+ p1 = Point(0, 0)
17
+ p2 = Point(3, 7)
18
+ p3 = Point(0, 4)
19
+ p4 = Point(6, 0)
20
+ p5 = Point(a, a)
21
+ d1 = Line(Point(4, 0), Point(4, 9))
22
+ d2 = Line(Point(7, 6), Point(3, 6))
23
+ d3 = Line(Point(4, 0), slope=oo)
24
+ d4 = Line(Point(7, 6), slope=0)
25
+ d5 = Line(Point(b, a), slope=oo)
26
+ d6 = Line(Point(a, b), slope=0)
27
+
28
+ half = S.Half
29
+
30
+ pa1 = Parabola(None, d2)
31
+ pa2 = Parabola(directrix=d1)
32
+ pa3 = Parabola(p1, d1)
33
+ pa4 = Parabola(p2, d2)
34
+ pa5 = Parabola(p2, d4)
35
+ pa6 = Parabola(p3, d2)
36
+ pa7 = Parabola(p2, d1)
37
+ pa8 = Parabola(p4, d1)
38
+ pa9 = Parabola(p4, d3)
39
+ pa10 = Parabola(p5, d5)
40
+ pa11 = Parabola(p5, d6)
41
+ d = Line(Point(3, 7), Point(2, 9))
42
+ pa12 = Parabola(Point(7, 8), d)
43
+ pa12r = Parabola(Point(7, 8).reflect(d), d)
44
+
45
+ raises(ValueError, lambda:
46
+ Parabola(Point(7, 8, 9), Line(Point(6, 7), Point(7, 7))))
47
+ raises(ValueError, lambda:
48
+ Parabola(Point(0, 2), Line(Point(7, 2), Point(6, 2))))
49
+ raises(ValueError, lambda: Parabola(Point(7, 8), Point(3, 8)))
50
+
51
+ # Basic Stuff
52
+ assert pa1.focus == Point(0, 0)
53
+ assert pa1.ambient_dimension == S(2)
54
+ assert pa2 == pa3
55
+ assert pa4 != pa7
56
+ assert pa6 != pa7
57
+ assert pa6.focus == Point2D(0, 4)
58
+ assert pa6.focal_length == 1
59
+ assert pa6.p_parameter == -1
60
+ assert pa6.vertex == Point2D(0, 5)
61
+ assert pa6.eccentricity == 1
62
+ assert pa7.focus == Point2D(3, 7)
63
+ assert pa7.focal_length == half
64
+ assert pa7.p_parameter == -half
65
+ assert pa7.vertex == Point2D(7*half, 7)
66
+ assert pa4.focal_length == half
67
+ assert pa4.p_parameter == half
68
+ assert pa4.vertex == Point2D(3, 13*half)
69
+ assert pa8.focal_length == 1
70
+ assert pa8.p_parameter == 1
71
+ assert pa8.vertex == Point2D(5, 0)
72
+ assert pa4.focal_length == pa5.focal_length
73
+ assert pa4.p_parameter == pa5.p_parameter
74
+ assert pa4.vertex == pa5.vertex
75
+ assert pa4.equation() == pa5.equation()
76
+ assert pa8.focal_length == pa9.focal_length
77
+ assert pa8.p_parameter == pa9.p_parameter
78
+ assert pa8.vertex == pa9.vertex
79
+ assert pa8.equation() == pa9.equation()
80
+ assert pa10.focal_length == pa11.focal_length == sqrt((a - b) ** 2) / 2 # if a, b real == abs(a - b)/2
81
+ assert pa11.vertex == Point(*pa10.vertex[::-1]) == Point(a,
82
+ a - sqrt((a - b)**2)*sign(a - b)/2) # change axis x->y, y->x on pa10
83
+ aos = pa12.axis_of_symmetry
84
+ assert aos == Line(Point(7, 8), Point(5, 7))
85
+ assert pa12.directrix == Line(Point(3, 7), Point(2, 9))
86
+ assert pa12.directrix.angle_between(aos) == S.Pi/2
87
+ assert pa12.eccentricity == 1
88
+ assert pa12.equation(x, y) == (x - 7)**2 + (y - 8)**2 - (-2*x - y + 13)**2/5
89
+ assert pa12.focal_length == 9*sqrt(5)/10
90
+ assert pa12.focus == Point(7, 8)
91
+ assert pa12.p_parameter == 9*sqrt(5)/10
92
+ assert pa12.vertex == Point2D(S(26)/5, S(71)/10)
93
+ assert pa12r.focal_length == 9*sqrt(5)/10
94
+ assert pa12r.focus == Point(-S(1)/5, S(22)/5)
95
+ assert pa12r.p_parameter == -9*sqrt(5)/10
96
+ assert pa12r.vertex == Point(S(8)/5, S(53)/10)
97
+
98
+
99
+ def test_parabola_intersection():
100
+ l1 = Line(Point(1, -2), Point(-1,-2))
101
+ l2 = Line(Point(1, 2), Point(-1,2))
102
+ l3 = Line(Point(1, 0), Point(-1,0))
103
+
104
+ p1 = Point(0,0)
105
+ p2 = Point(0, -2)
106
+ p3 = Point(120, -12)
107
+ parabola1 = Parabola(p1, l1)
108
+
109
+ # parabola with parabola
110
+ assert parabola1.intersection(parabola1) == [parabola1]
111
+ assert parabola1.intersection(Parabola(p1, l2)) == [Point2D(-2, 0), Point2D(2, 0)]
112
+ assert parabola1.intersection(Parabola(p2, l3)) == [Point2D(0, -1)]
113
+ assert parabola1.intersection(Parabola(Point(16, 0), l1)) == [Point2D(8, 15)]
114
+ assert parabola1.intersection(Parabola(Point(0, 16), l1)) == [Point2D(-6, 8), Point2D(6, 8)]
115
+ assert parabola1.intersection(Parabola(p3, l3)) == []
116
+ # parabola with point
117
+ assert parabola1.intersection(p1) == []
118
+ assert parabola1.intersection(Point2D(0, -1)) == [Point2D(0, -1)]
119
+ assert parabola1.intersection(Point2D(4, 3)) == [Point2D(4, 3)]
120
+ # parabola with line
121
+ assert parabola1.intersection(Line(Point2D(-7, 3), Point(12, 3))) == [Point2D(-4, 3), Point2D(4, 3)]
122
+ assert parabola1.intersection(Line(Point(-4, -1), Point(4, -1))) == [Point(0, -1)]
123
+ assert parabola1.intersection(Line(Point(2, 0), Point(0, -2))) == [Point2D(2, 0)]
124
+ raises(TypeError, lambda: parabola1.intersection(Line(Point(0, 0, 0), Point(1, 1, 1))))
125
+ # parabola with segment
126
+ assert parabola1.intersection(Segment2D((-4, -5), (4, 3))) == [Point2D(0, -1), Point2D(4, 3)]
127
+ assert parabola1.intersection(Segment2D((0, -5), (0, 6))) == [Point2D(0, -1)]
128
+ assert parabola1.intersection(Segment2D((-12, -65), (14, -68))) == []
129
+ # parabola with ray
130
+ assert parabola1.intersection(Ray2D((-4, -5), (4, 3))) == [Point2D(0, -1), Point2D(4, 3)]
131
+ assert parabola1.intersection(Ray2D((0, 7), (1, 14))) == [Point2D(14 + 2*sqrt(57), 105 + 14*sqrt(57))]
132
+ assert parabola1.intersection(Ray2D((0, 7), (0, 14))) == []
133
+ # parabola with ellipse/circle
134
+ assert parabola1.intersection(Circle(p1, 2)) == [Point2D(-2, 0), Point2D(2, 0)]
135
+ assert parabola1.intersection(Circle(p2, 1)) == [Point2D(0, -1)]
136
+ assert parabola1.intersection(Ellipse(p2, 2, 1)) == [Point2D(0, -1)]
137
+ assert parabola1.intersection(Ellipse(Point(0, 19), 5, 7)) == []
138
+ assert parabola1.intersection(Ellipse((0, 3), 12, 4)) == [
139
+ Point2D(0, -1),
140
+ Point2D(-4*sqrt(17)/3, Rational(59, 9)),
141
+ Point2D(4*sqrt(17)/3, Rational(59, 9))]
142
+ # parabola with unsupported type
143
+ raises(TypeError, lambda: parabola1.intersection(2))
llmeval-env/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))
llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/test_point.py ADDED
@@ -0,0 +1,481 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.basic import Basic
2
+ from sympy.core.numbers import (I, Rational, pi)
3
+ from sympy.core.parameters import evaluate
4
+ from sympy.core.singleton import S
5
+ from sympy.core.symbol import Symbol
6
+ from sympy.core.sympify import sympify
7
+ from sympy.functions.elementary.miscellaneous import sqrt
8
+ from sympy.geometry import Line, Point, Point2D, Point3D, Line3D, Plane
9
+ from sympy.geometry.entity import rotate, scale, translate, GeometryEntity
10
+ from sympy.matrices import Matrix
11
+ from sympy.utilities.iterables import subsets, permutations, cartes
12
+ from sympy.utilities.misc import Undecidable
13
+ from sympy.testing.pytest import raises, warns
14
+
15
+
16
+ def test_point():
17
+ x = Symbol('x', real=True)
18
+ y = Symbol('y', real=True)
19
+ x1 = Symbol('x1', real=True)
20
+ x2 = Symbol('x2', real=True)
21
+ y1 = Symbol('y1', real=True)
22
+ y2 = Symbol('y2', real=True)
23
+ half = S.Half
24
+ p1 = Point(x1, x2)
25
+ p2 = Point(y1, y2)
26
+ p3 = Point(0, 0)
27
+ p4 = Point(1, 1)
28
+ p5 = Point(0, 1)
29
+ line = Line(Point(1, 0), slope=1)
30
+
31
+ assert p1 in p1
32
+ assert p1 not in p2
33
+ assert p2.y == y2
34
+ assert (p3 + p4) == p4
35
+ assert (p2 - p1) == Point(y1 - x1, y2 - x2)
36
+ assert -p2 == Point(-y1, -y2)
37
+ raises(TypeError, lambda: Point(1))
38
+ raises(ValueError, lambda: Point([1]))
39
+ raises(ValueError, lambda: Point(3, I))
40
+ raises(ValueError, lambda: Point(2*I, I))
41
+ raises(ValueError, lambda: Point(3 + I, I))
42
+
43
+ assert Point(34.05, sqrt(3)) == Point(Rational(681, 20), sqrt(3))
44
+ assert Point.midpoint(p3, p4) == Point(half, half)
45
+ assert Point.midpoint(p1, p4) == Point(half + half*x1, half + half*x2)
46
+ assert Point.midpoint(p2, p2) == p2
47
+ assert p2.midpoint(p2) == p2
48
+ assert p1.origin == Point(0, 0)
49
+
50
+ assert Point.distance(p3, p4) == sqrt(2)
51
+ assert Point.distance(p1, p1) == 0
52
+ assert Point.distance(p3, p2) == sqrt(p2.x**2 + p2.y**2)
53
+ raises(TypeError, lambda: Point.distance(p1, 0))
54
+ raises(TypeError, lambda: Point.distance(p1, GeometryEntity()))
55
+
56
+ # distance should be symmetric
57
+ assert p1.distance(line) == line.distance(p1)
58
+ assert p4.distance(line) == line.distance(p4)
59
+
60
+ assert Point.taxicab_distance(p4, p3) == 2
61
+
62
+ assert Point.canberra_distance(p4, p5) == 1
63
+ raises(ValueError, lambda: Point.canberra_distance(p3, p3))
64
+
65
+ p1_1 = Point(x1, x1)
66
+ p1_2 = Point(y2, y2)
67
+ p1_3 = Point(x1 + 1, x1)
68
+ assert Point.is_collinear(p3)
69
+
70
+ with warns(UserWarning, test_stacklevel=False):
71
+ assert Point.is_collinear(p3, Point(p3, dim=4))
72
+ assert p3.is_collinear()
73
+ assert Point.is_collinear(p3, p4)
74
+ assert Point.is_collinear(p3, p4, p1_1, p1_2)
75
+ assert Point.is_collinear(p3, p4, p1_1, p1_3) is False
76
+ assert Point.is_collinear(p3, p3, p4, p5) is False
77
+
78
+ raises(TypeError, lambda: Point.is_collinear(line))
79
+ raises(TypeError, lambda: p1_1.is_collinear(line))
80
+
81
+ assert p3.intersection(Point(0, 0)) == [p3]
82
+ assert p3.intersection(p4) == []
83
+ assert p3.intersection(line) == []
84
+ with warns(UserWarning, test_stacklevel=False):
85
+ assert Point.intersection(Point(0, 0, 0), Point(0, 0)) == [Point(0, 0, 0)]
86
+
87
+ x_pos = Symbol('x', positive=True)
88
+ p2_1 = Point(x_pos, 0)
89
+ p2_2 = Point(0, x_pos)
90
+ p2_3 = Point(-x_pos, 0)
91
+ p2_4 = Point(0, -x_pos)
92
+ p2_5 = Point(x_pos, 5)
93
+ assert Point.is_concyclic(p2_1)
94
+ assert Point.is_concyclic(p2_1, p2_2)
95
+ assert Point.is_concyclic(p2_1, p2_2, p2_3, p2_4)
96
+ for pts in permutations((p2_1, p2_2, p2_3, p2_5)):
97
+ assert Point.is_concyclic(*pts) is False
98
+ assert Point.is_concyclic(p4, p4 * 2, p4 * 3) is False
99
+ assert Point(0, 0).is_concyclic((1, 1), (2, 2), (2, 1)) is False
100
+ assert Point.is_concyclic(Point(0, 0, 0, 0), Point(1, 0, 0, 0), Point(1, 1, 0, 0), Point(1, 1, 1, 0)) is False
101
+
102
+ assert p1.is_scalar_multiple(p1)
103
+ assert p1.is_scalar_multiple(2*p1)
104
+ assert not p1.is_scalar_multiple(p2)
105
+ assert Point.is_scalar_multiple(Point(1, 1), (-1, -1))
106
+ assert Point.is_scalar_multiple(Point(0, 0), (0, -1))
107
+ # test when is_scalar_multiple can't be determined
108
+ raises(Undecidable, lambda: Point.is_scalar_multiple(Point(sympify("x1%y1"), sympify("x2%y2")), Point(0, 1)))
109
+
110
+ assert Point(0, 1).orthogonal_direction == Point(1, 0)
111
+ assert Point(1, 0).orthogonal_direction == Point(0, 1)
112
+
113
+ assert p1.is_zero is None
114
+ assert p3.is_zero
115
+ assert p4.is_zero is False
116
+ assert p1.is_nonzero is None
117
+ assert p3.is_nonzero is False
118
+ assert p4.is_nonzero
119
+
120
+ assert p4.scale(2, 3) == Point(2, 3)
121
+ assert p3.scale(2, 3) == p3
122
+
123
+ assert p4.rotate(pi, Point(0.5, 0.5)) == p3
124
+ assert p1.__radd__(p2) == p1.midpoint(p2).scale(2, 2)
125
+ assert (-p3).__rsub__(p4) == p3.midpoint(p4).scale(2, 2)
126
+
127
+ assert p4 * 5 == Point(5, 5)
128
+ assert p4 / 5 == Point(0.2, 0.2)
129
+ assert 5 * p4 == Point(5, 5)
130
+
131
+ raises(ValueError, lambda: Point(0, 0) + 10)
132
+
133
+ # Point differences should be simplified
134
+ assert Point(x*(x - 1), y) - Point(x**2 - x, y + 1) == Point(0, -1)
135
+
136
+ a, b = S.Half, Rational(1, 3)
137
+ assert Point(a, b).evalf(2) == \
138
+ Point(a.n(2), b.n(2), evaluate=False)
139
+ raises(ValueError, lambda: Point(1, 2) + 1)
140
+
141
+ # test project
142
+ assert Point.project((0, 1), (1, 0)) == Point(0, 0)
143
+ assert Point.project((1, 1), (1, 0)) == Point(1, 0)
144
+ raises(ValueError, lambda: Point.project(p1, Point(0, 0)))
145
+
146
+ # test transformations
147
+ p = Point(1, 0)
148
+ assert p.rotate(pi/2) == Point(0, 1)
149
+ assert p.rotate(pi/2, p) == p
150
+ p = Point(1, 1)
151
+ assert p.scale(2, 3) == Point(2, 3)
152
+ assert p.translate(1, 2) == Point(2, 3)
153
+ assert p.translate(1) == Point(2, 1)
154
+ assert p.translate(y=1) == Point(1, 2)
155
+ assert p.translate(*p.args) == Point(2, 2)
156
+
157
+ # Check invalid input for transform
158
+ raises(ValueError, lambda: p3.transform(p3))
159
+ raises(ValueError, lambda: p.transform(Matrix([[1, 0], [0, 1]])))
160
+
161
+ # test __contains__
162
+ assert 0 in Point(0, 0, 0, 0)
163
+ assert 1 not in Point(0, 0, 0, 0)
164
+
165
+ # test affine_rank
166
+ assert Point.affine_rank() == -1
167
+
168
+
169
+ def test_point3D():
170
+ x = Symbol('x', real=True)
171
+ y = Symbol('y', real=True)
172
+ x1 = Symbol('x1', real=True)
173
+ x2 = Symbol('x2', real=True)
174
+ x3 = Symbol('x3', real=True)
175
+ y1 = Symbol('y1', real=True)
176
+ y2 = Symbol('y2', real=True)
177
+ y3 = Symbol('y3', real=True)
178
+ half = S.Half
179
+ p1 = Point3D(x1, x2, x3)
180
+ p2 = Point3D(y1, y2, y3)
181
+ p3 = Point3D(0, 0, 0)
182
+ p4 = Point3D(1, 1, 1)
183
+ p5 = Point3D(0, 1, 2)
184
+
185
+ assert p1 in p1
186
+ assert p1 not in p2
187
+ assert p2.y == y2
188
+ assert (p3 + p4) == p4
189
+ assert (p2 - p1) == Point3D(y1 - x1, y2 - x2, y3 - x3)
190
+ assert -p2 == Point3D(-y1, -y2, -y3)
191
+
192
+ assert Point(34.05, sqrt(3)) == Point(Rational(681, 20), sqrt(3))
193
+ assert Point3D.midpoint(p3, p4) == Point3D(half, half, half)
194
+ assert Point3D.midpoint(p1, p4) == Point3D(half + half*x1, half + half*x2,
195
+ half + half*x3)
196
+ assert Point3D.midpoint(p2, p2) == p2
197
+ assert p2.midpoint(p2) == p2
198
+
199
+ assert Point3D.distance(p3, p4) == sqrt(3)
200
+ assert Point3D.distance(p1, p1) == 0
201
+ assert Point3D.distance(p3, p2) == sqrt(p2.x**2 + p2.y**2 + p2.z**2)
202
+
203
+ p1_1 = Point3D(x1, x1, x1)
204
+ p1_2 = Point3D(y2, y2, y2)
205
+ p1_3 = Point3D(x1 + 1, x1, x1)
206
+ Point3D.are_collinear(p3)
207
+ assert Point3D.are_collinear(p3, p4)
208
+ assert Point3D.are_collinear(p3, p4, p1_1, p1_2)
209
+ assert Point3D.are_collinear(p3, p4, p1_1, p1_3) is False
210
+ assert Point3D.are_collinear(p3, p3, p4, p5) is False
211
+
212
+ assert p3.intersection(Point3D(0, 0, 0)) == [p3]
213
+ assert p3.intersection(p4) == []
214
+
215
+
216
+ assert p4 * 5 == Point3D(5, 5, 5)
217
+ assert p4 / 5 == Point3D(0.2, 0.2, 0.2)
218
+ assert 5 * p4 == Point3D(5, 5, 5)
219
+
220
+ raises(ValueError, lambda: Point3D(0, 0, 0) + 10)
221
+
222
+ # Test coordinate properties
223
+ assert p1.coordinates == (x1, x2, x3)
224
+ assert p2.coordinates == (y1, y2, y3)
225
+ assert p3.coordinates == (0, 0, 0)
226
+ assert p4.coordinates == (1, 1, 1)
227
+ assert p5.coordinates == (0, 1, 2)
228
+ assert p5.x == 0
229
+ assert p5.y == 1
230
+ assert p5.z == 2
231
+
232
+ # Point differences should be simplified
233
+ assert Point3D(x*(x - 1), y, 2) - Point3D(x**2 - x, y + 1, 1) == \
234
+ Point3D(0, -1, 1)
235
+
236
+ a, b, c = S.Half, Rational(1, 3), Rational(1, 4)
237
+ assert Point3D(a, b, c).evalf(2) == \
238
+ Point(a.n(2), b.n(2), c.n(2), evaluate=False)
239
+ raises(ValueError, lambda: Point3D(1, 2, 3) + 1)
240
+
241
+ # test transformations
242
+ p = Point3D(1, 1, 1)
243
+ assert p.scale(2, 3) == Point3D(2, 3, 1)
244
+ assert p.translate(1, 2) == Point3D(2, 3, 1)
245
+ assert p.translate(1) == Point3D(2, 1, 1)
246
+ assert p.translate(z=1) == Point3D(1, 1, 2)
247
+ assert p.translate(*p.args) == Point3D(2, 2, 2)
248
+
249
+ # Test __new__
250
+ assert Point3D(0.1, 0.2, evaluate=False, on_morph='ignore').args[0].is_Float
251
+
252
+ # Test length property returns correctly
253
+ assert p.length == 0
254
+ assert p1_1.length == 0
255
+ assert p1_2.length == 0
256
+
257
+ # Test are_colinear type error
258
+ raises(TypeError, lambda: Point3D.are_collinear(p, x))
259
+
260
+ # Test are_coplanar
261
+ assert Point.are_coplanar()
262
+ assert Point.are_coplanar((1, 2, 0), (1, 2, 0), (1, 3, 0))
263
+ assert Point.are_coplanar((1, 2, 0), (1, 2, 3))
264
+ with warns(UserWarning, test_stacklevel=False):
265
+ raises(ValueError, lambda: Point2D.are_coplanar((1, 2), (1, 2, 3)))
266
+ assert Point3D.are_coplanar((1, 2, 0), (1, 2, 3))
267
+ assert Point.are_coplanar((0, 0, 0), (1, 1, 0), (1, 1, 1), (1, 2, 1)) is False
268
+ planar2 = Point3D(1, -1, 1)
269
+ planar3 = Point3D(-1, 1, 1)
270
+ assert Point3D.are_coplanar(p, planar2, planar3) == True
271
+ assert Point3D.are_coplanar(p, planar2, planar3, p3) == False
272
+ assert Point.are_coplanar(p, planar2)
273
+ planar2 = Point3D(1, 1, 2)
274
+ planar3 = Point3D(1, 1, 3)
275
+ assert Point3D.are_coplanar(p, planar2, planar3) # line, not plane
276
+ plane = Plane((1, 2, 1), (2, 1, 0), (3, 1, 2))
277
+ assert Point.are_coplanar(*[plane.projection(((-1)**i, i)) for i in range(4)])
278
+
279
+ # all 2D points are coplanar
280
+ assert Point.are_coplanar(Point(x, y), Point(x, x + y), Point(y, x + 2)) is True
281
+
282
+ # Test Intersection
283
+ assert planar2.intersection(Line3D(p, planar3)) == [Point3D(1, 1, 2)]
284
+
285
+ # Test Scale
286
+ assert planar2.scale(1, 1, 1) == planar2
287
+ assert planar2.scale(2, 2, 2, planar3) == Point3D(1, 1, 1)
288
+ assert planar2.scale(1, 1, 1, p3) == planar2
289
+
290
+ # Test Transform
291
+ identity = Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
292
+ assert p.transform(identity) == p
293
+ trans = Matrix([[1, 0, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1], [0, 0, 0, 1]])
294
+ assert p.transform(trans) == Point3D(2, 2, 2)
295
+ raises(ValueError, lambda: p.transform(p))
296
+ raises(ValueError, lambda: p.transform(Matrix([[1, 0], [0, 1]])))
297
+
298
+ # Test Equals
299
+ assert p.equals(x1) == False
300
+
301
+ # Test __sub__
302
+ p_4d = Point(0, 0, 0, 1)
303
+ with warns(UserWarning, test_stacklevel=False):
304
+ assert p - p_4d == Point(1, 1, 1, -1)
305
+ p_4d3d = Point(0, 0, 1, 0)
306
+ with warns(UserWarning, test_stacklevel=False):
307
+ assert p - p_4d3d == Point(1, 1, 0, 0)
308
+
309
+
310
+ def test_Point2D():
311
+
312
+ # Test Distance
313
+ p1 = Point2D(1, 5)
314
+ p2 = Point2D(4, 2.5)
315
+ p3 = (6, 3)
316
+ assert p1.distance(p2) == sqrt(61)/2
317
+ assert p2.distance(p3) == sqrt(17)/2
318
+
319
+ # Test coordinates
320
+ assert p1.x == 1
321
+ assert p1.y == 5
322
+ assert p2.x == 4
323
+ assert p2.y == S(5)/2
324
+ assert p1.coordinates == (1, 5)
325
+ assert p2.coordinates == (4, S(5)/2)
326
+
327
+ # test bounds
328
+ assert p1.bounds == (1, 5, 1, 5)
329
+
330
+ def test_issue_9214():
331
+ p1 = Point3D(4, -2, 6)
332
+ p2 = Point3D(1, 2, 3)
333
+ p3 = Point3D(7, 2, 3)
334
+
335
+ assert Point3D.are_collinear(p1, p2, p3) is False
336
+
337
+
338
+ def test_issue_11617():
339
+ p1 = Point3D(1,0,2)
340
+ p2 = Point2D(2,0)
341
+
342
+ with warns(UserWarning, test_stacklevel=False):
343
+ assert p1.distance(p2) == sqrt(5)
344
+
345
+
346
+ def test_transform():
347
+ p = Point(1, 1)
348
+ assert p.transform(rotate(pi/2)) == Point(-1, 1)
349
+ assert p.transform(scale(3, 2)) == Point(3, 2)
350
+ assert p.transform(translate(1, 2)) == Point(2, 3)
351
+ assert Point(1, 1).scale(2, 3, (4, 5)) == \
352
+ Point(-2, -7)
353
+ assert Point(1, 1).translate(4, 5) == \
354
+ Point(5, 6)
355
+
356
+
357
+ def test_concyclic_doctest_bug():
358
+ p1, p2 = Point(-1, 0), Point(1, 0)
359
+ p3, p4 = Point(0, 1), Point(-1, 2)
360
+ assert Point.is_concyclic(p1, p2, p3)
361
+ assert not Point.is_concyclic(p1, p2, p3, p4)
362
+
363
+
364
+ def test_arguments():
365
+ """Functions accepting `Point` objects in `geometry`
366
+ should also accept tuples and lists and
367
+ automatically convert them to points."""
368
+
369
+ singles2d = ((1,2), [1,2], Point(1,2))
370
+ singles2d2 = ((1,3), [1,3], Point(1,3))
371
+ doubles2d = cartes(singles2d, singles2d2)
372
+ p2d = Point2D(1,2)
373
+ singles3d = ((1,2,3), [1,2,3], Point(1,2,3))
374
+ doubles3d = subsets(singles3d, 2)
375
+ p3d = Point3D(1,2,3)
376
+ singles4d = ((1,2,3,4), [1,2,3,4], Point(1,2,3,4))
377
+ doubles4d = subsets(singles4d, 2)
378
+ p4d = Point(1,2,3,4)
379
+
380
+ # test 2D
381
+ test_single = ['distance', 'is_scalar_multiple', 'taxicab_distance', 'midpoint', 'intersection', 'dot', 'equals', '__add__', '__sub__']
382
+ test_double = ['is_concyclic', 'is_collinear']
383
+ for p in singles2d:
384
+ Point2D(p)
385
+ for func in test_single:
386
+ for p in singles2d:
387
+ getattr(p2d, func)(p)
388
+ for func in test_double:
389
+ for p in doubles2d:
390
+ getattr(p2d, func)(*p)
391
+
392
+ # test 3D
393
+ test_double = ['is_collinear']
394
+ for p in singles3d:
395
+ Point3D(p)
396
+ for func in test_single:
397
+ for p in singles3d:
398
+ getattr(p3d, func)(p)
399
+ for func in test_double:
400
+ for p in doubles3d:
401
+ getattr(p3d, func)(*p)
402
+
403
+ # test 4D
404
+ test_double = ['is_collinear']
405
+ for p in singles4d:
406
+ Point(p)
407
+ for func in test_single:
408
+ for p in singles4d:
409
+ getattr(p4d, func)(p)
410
+ for func in test_double:
411
+ for p in doubles4d:
412
+ getattr(p4d, func)(*p)
413
+
414
+ # test evaluate=False for ops
415
+ x = Symbol('x')
416
+ a = Point(0, 1)
417
+ assert a + (0.1, x) == Point(0.1, 1 + x, evaluate=False)
418
+ a = Point(0, 1)
419
+ assert a/10.0 == Point(0, 0.1, evaluate=False)
420
+ a = Point(0, 1)
421
+ assert a*10.0 == Point(0.0, 10.0, evaluate=False)
422
+
423
+ # test evaluate=False when changing dimensions
424
+ u = Point(.1, .2, evaluate=False)
425
+ u4 = Point(u, dim=4, on_morph='ignore')
426
+ assert u4.args == (.1, .2, 0, 0)
427
+ assert all(i.is_Float for i in u4.args[:2])
428
+ # and even when *not* changing dimensions
429
+ assert all(i.is_Float for i in Point(u).args)
430
+
431
+ # never raise error if creating an origin
432
+ assert Point(dim=3, on_morph='error')
433
+
434
+ # raise error with unmatched dimension
435
+ raises(ValueError, lambda: Point(1, 1, dim=3, on_morph='error'))
436
+ # test unknown on_morph
437
+ raises(ValueError, lambda: Point(1, 1, dim=3, on_morph='unknown'))
438
+ # test invalid expressions
439
+ raises(TypeError, lambda: Point(Basic(), Basic()))
440
+
441
+ def test_unit():
442
+ assert Point(1, 1).unit == Point(sqrt(2)/2, sqrt(2)/2)
443
+
444
+
445
+ def test_dot():
446
+ raises(TypeError, lambda: Point(1, 2).dot(Line((0, 0), (1, 1))))
447
+
448
+
449
+ def test__normalize_dimension():
450
+ assert Point._normalize_dimension(Point(1, 2), Point(3, 4)) == [
451
+ Point(1, 2), Point(3, 4)]
452
+ assert Point._normalize_dimension(
453
+ Point(1, 2), Point(3, 4, 0), on_morph='ignore') == [
454
+ Point(1, 2, 0), Point(3, 4, 0)]
455
+
456
+
457
+ def test_issue_22684():
458
+ # Used to give an error
459
+ with evaluate(False):
460
+ Point(1, 2)
461
+
462
+
463
+ def test_direction_cosine():
464
+ p1 = Point3D(0, 0, 0)
465
+ p2 = Point3D(1, 1, 1)
466
+
467
+ assert p1.direction_cosine(Point3D(1, 0, 0)) == [1, 0, 0]
468
+ assert p1.direction_cosine(Point3D(0, 1, 0)) == [0, 1, 0]
469
+ assert p1.direction_cosine(Point3D(0, 0, pi)) == [0, 0, 1]
470
+
471
+ assert p1.direction_cosine(Point3D(5, 0, 0)) == [1, 0, 0]
472
+ assert p1.direction_cosine(Point3D(0, sqrt(3), 0)) == [0, 1, 0]
473
+ assert p1.direction_cosine(Point3D(0, 0, 5)) == [0, 0, 1]
474
+
475
+ assert p1.direction_cosine(Point3D(2.4, 2.4, 0)) == [sqrt(2)/2, sqrt(2)/2, 0]
476
+ assert p1.direction_cosine(Point3D(1, 1, 1)) == [sqrt(3) / 3, sqrt(3) / 3, sqrt(3) / 3]
477
+ assert p1.direction_cosine(Point3D(-12, 0 -15)) == [-4*sqrt(41)/41, -5*sqrt(41)/41, 0]
478
+
479
+ assert p2.direction_cosine(Point3D(0, 0, 0)) == [-sqrt(3) / 3, -sqrt(3) / 3, -sqrt(3) / 3]
480
+ assert p2.direction_cosine(Point3D(1, 1, 12)) == [0, 0, 1]
481
+ assert p2.direction_cosine(Point3D(12, 1, 12)) == [sqrt(2) / 2, 0, sqrt(2) / 2]
llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/test_polygon.py ADDED
@@ -0,0 +1,664 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
16
+
17
+ def feq(a, b):
18
+ """Test if two floating point values are 'equal'."""
19
+ t_float = Float("1.0E-10")
20
+ return -t_float < a - b < t_float
21
+
22
+ @slow
23
+ def test_polygon():
24
+ x = Symbol('x', real=True)
25
+ y = Symbol('y', real=True)
26
+ q = Symbol('q', real=True)
27
+ u = Symbol('u', real=True)
28
+ v = Symbol('v', real=True)
29
+ w = Symbol('w', real=True)
30
+ x1 = Symbol('x1', real=True)
31
+ half = S.Half
32
+ a, b, c = Point(0, 0), Point(2, 0), Point(3, 3)
33
+ t = Triangle(a, b, c)
34
+ assert Polygon(Point(0, 0)) == Point(0, 0)
35
+ assert Polygon(a, Point(1, 0), b, c) == t
36
+ assert Polygon(Point(1, 0), b, c, a) == t
37
+ assert Polygon(b, c, a, Point(1, 0)) == t
38
+ # 2 "remove folded" tests
39
+ assert Polygon(a, Point(3, 0), b, c) == t
40
+ assert Polygon(a, b, Point(3, -1), b, c) == t
41
+ # remove multiple collinear points
42
+ assert Polygon(Point(-4, 15), Point(-11, 15), Point(-15, 15),
43
+ Point(-15, 33/5), Point(-15, -87/10), Point(-15, -15),
44
+ Point(-42/5, -15), Point(-2, -15), Point(7, -15), Point(15, -15),
45
+ Point(15, -3), Point(15, 10), Point(15, 15)) == \
46
+ Polygon(Point(-15, -15), Point(15, -15), Point(15, 15), Point(-15, 15))
47
+
48
+ p1 = Polygon(
49
+ Point(0, 0), Point(3, -1),
50
+ Point(6, 0), Point(4, 5),
51
+ Point(2, 3), Point(0, 3))
52
+ p2 = Polygon(
53
+ Point(6, 0), Point(3, -1),
54
+ Point(0, 0), Point(0, 3),
55
+ Point(2, 3), Point(4, 5))
56
+ p3 = Polygon(
57
+ Point(0, 0), Point(3, 0),
58
+ Point(5, 2), Point(4, 4))
59
+ p4 = Polygon(
60
+ Point(0, 0), Point(4, 4),
61
+ Point(5, 2), Point(3, 0))
62
+ p5 = Polygon(
63
+ Point(0, 0), Point(4, 4),
64
+ Point(0, 4))
65
+ p6 = Polygon(
66
+ Point(-11, 1), Point(-9, 6.6),
67
+ Point(-4, -3), Point(-8.4, -8.7))
68
+ p7 = Polygon(
69
+ Point(x, y), Point(q, u),
70
+ Point(v, w))
71
+ p8 = Polygon(
72
+ Point(x, y), Point(v, w),
73
+ Point(q, u))
74
+ p9 = Polygon(
75
+ Point(0, 0), Point(4, 4),
76
+ Point(3, 0), Point(5, 2))
77
+ p10 = Polygon(
78
+ Point(0, 2), Point(2, 2),
79
+ Point(0, 0), Point(2, 0))
80
+ p11 = Polygon(Point(0, 0), 1, n=3)
81
+ p12 = Polygon(Point(0, 0), 1, 0, n=3)
82
+
83
+ r = Ray(Point(-9, 6.6), Point(-9, 5.5))
84
+ #
85
+ # General polygon
86
+ #
87
+ assert p1 == p2
88
+ assert len(p1.args) == 6
89
+ assert len(p1.sides) == 6
90
+ assert p1.perimeter == 5 + 2*sqrt(10) + sqrt(29) + sqrt(8)
91
+ assert p1.area == 22
92
+ assert not p1.is_convex()
93
+ assert Polygon((-1, 1), (2, -1), (2, 1), (-1, -1), (3, 0)
94
+ ).is_convex() is False
95
+ # ensure convex for both CW and CCW point specification
96
+ assert p3.is_convex()
97
+ assert p4.is_convex()
98
+ dict5 = p5.angles
99
+ assert dict5[Point(0, 0)] == pi / 4
100
+ assert dict5[Point(0, 4)] == pi / 2
101
+ assert p5.encloses_point(Point(x, y)) is None
102
+ assert p5.encloses_point(Point(1, 3))
103
+ assert p5.encloses_point(Point(0, 0)) is False
104
+ assert p5.encloses_point(Point(4, 0)) is False
105
+ assert p1.encloses(Circle(Point(2.5, 2.5), 5)) is False
106
+ assert p1.encloses(Ellipse(Point(2.5, 2), 5, 6)) is False
107
+ assert p5.plot_interval('x') == [x, 0, 1]
108
+ assert p5.distance(
109
+ Polygon(Point(10, 10), Point(14, 14), Point(10, 14))) == 6 * sqrt(2)
110
+ assert p5.distance(
111
+ Polygon(Point(1, 8), Point(5, 8), Point(8, 12), Point(1, 12))) == 4
112
+ with warns(UserWarning, \
113
+ match="Polygons may intersect producing erroneous output"):
114
+ Polygon(Point(0, 0), Point(1, 0), Point(1, 1)).distance(
115
+ Polygon(Point(0, 0), Point(0, 1), Point(1, 1)))
116
+ assert hash(p5) == hash(Polygon(Point(0, 0), Point(4, 4), Point(0, 4)))
117
+ assert hash(p1) == hash(p2)
118
+ assert hash(p7) == hash(p8)
119
+ assert hash(p3) != hash(p9)
120
+ assert p5 == Polygon(Point(4, 4), Point(0, 4), Point(0, 0))
121
+ assert Polygon(Point(4, 4), Point(0, 4), Point(0, 0)) in p5
122
+ assert p5 != Point(0, 4)
123
+ assert Point(0, 1) in p5
124
+ assert p5.arbitrary_point('t').subs(Symbol('t', real=True), 0) == \
125
+ Point(0, 0)
126
+ raises(ValueError, lambda: Polygon(
127
+ Point(x, 0), Point(0, y), Point(x, y)).arbitrary_point('x'))
128
+ assert p6.intersection(r) == [Point(-9, Rational(-84, 13)), Point(-9, Rational(33, 5))]
129
+ assert p10.area == 0
130
+ assert p11 == RegularPolygon(Point(0, 0), 1, 3, 0)
131
+ assert p11 == p12
132
+ assert p11.vertices[0] == Point(1, 0)
133
+ assert p11.args[0] == Point(0, 0)
134
+ p11.spin(pi/2)
135
+ assert p11.vertices[0] == Point(0, 1)
136
+ #
137
+ # Regular polygon
138
+ #
139
+ p1 = RegularPolygon(Point(0, 0), 10, 5)
140
+ p2 = RegularPolygon(Point(0, 0), 5, 5)
141
+ raises(GeometryError, lambda: RegularPolygon(Point(0, 0), Point(0,
142
+ 1), Point(1, 1)))
143
+ raises(GeometryError, lambda: RegularPolygon(Point(0, 0), 1, 2))
144
+ raises(ValueError, lambda: RegularPolygon(Point(0, 0), 1, 2.5))
145
+
146
+ assert p1 != p2
147
+ assert p1.interior_angle == pi*Rational(3, 5)
148
+ assert p1.exterior_angle == pi*Rational(2, 5)
149
+ assert p2.apothem == 5*cos(pi/5)
150
+ assert p2.circumcenter == p1.circumcenter == Point(0, 0)
151
+ assert p1.circumradius == p1.radius == 10
152
+ assert p2.circumcircle == Circle(Point(0, 0), 5)
153
+ assert p2.incircle == Circle(Point(0, 0), p2.apothem)
154
+ assert p2.inradius == p2.apothem == (5 * (1 + sqrt(5)) / 4)
155
+ p2.spin(pi / 10)
156
+ dict1 = p2.angles
157
+ assert dict1[Point(0, 5)] == 3 * pi / 5
158
+ assert p1.is_convex()
159
+ assert p1.rotation == 0
160
+ assert p1.encloses_point(Point(0, 0))
161
+ assert p1.encloses_point(Point(11, 0)) is False
162
+ assert p2.encloses_point(Point(0, 4.9))
163
+ p1.spin(pi/3)
164
+ assert p1.rotation == pi/3
165
+ assert p1.vertices[0] == Point(5, 5*sqrt(3))
166
+ for var in p1.args:
167
+ if isinstance(var, Point):
168
+ assert var == Point(0, 0)
169
+ else:
170
+ assert var in (5, 10, pi / 3)
171
+ assert p1 != Point(0, 0)
172
+ assert p1 != p5
173
+
174
+ # while spin works in place (notice that rotation is 2pi/3 below)
175
+ # rotate returns a new object
176
+ p1_old = p1
177
+ assert p1.rotate(pi/3) == RegularPolygon(Point(0, 0), 10, 5, pi*Rational(2, 3))
178
+ assert p1 == p1_old
179
+
180
+ assert p1.area == (-250*sqrt(5) + 1250)/(4*tan(pi/5))
181
+ assert p1.length == 20*sqrt(-sqrt(5)/8 + Rational(5, 8))
182
+ assert p1.scale(2, 2) == \
183
+ RegularPolygon(p1.center, p1.radius*2, p1._n, p1.rotation)
184
+ assert RegularPolygon((0, 0), 1, 4).scale(2, 3) == \
185
+ Polygon(Point(2, 0), Point(0, 3), Point(-2, 0), Point(0, -3))
186
+
187
+ assert repr(p1) == str(p1)
188
+
189
+ #
190
+ # Angles
191
+ #
192
+ angles = p4.angles
193
+ assert feq(angles[Point(0, 0)].evalf(), Float("0.7853981633974483"))
194
+ assert feq(angles[Point(4, 4)].evalf(), Float("1.2490457723982544"))
195
+ assert feq(angles[Point(5, 2)].evalf(), Float("1.8925468811915388"))
196
+ assert feq(angles[Point(3, 0)].evalf(), Float("2.3561944901923449"))
197
+
198
+ angles = p3.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
+ #
205
+ # Triangle
206
+ #
207
+ p1 = Point(0, 0)
208
+ p2 = Point(5, 0)
209
+ p3 = Point(0, 5)
210
+ t1 = Triangle(p1, p2, p3)
211
+ t2 = Triangle(p1, p2, Point(Rational(5, 2), sqrt(Rational(75, 4))))
212
+ t3 = Triangle(p1, Point(x1, 0), Point(0, x1))
213
+ s1 = t1.sides
214
+ assert Triangle(p1, p2, p1) == Polygon(p1, p2, p1) == Segment(p1, p2)
215
+ raises(GeometryError, lambda: Triangle(Point(0, 0)))
216
+
217
+ # Basic stuff
218
+ assert Triangle(p1, p1, p1) == p1
219
+ assert Triangle(p2, p2*2, p2*3) == Segment(p2, p2*3)
220
+ assert t1.area == Rational(25, 2)
221
+ assert t1.is_right()
222
+ assert t2.is_right() is False
223
+ assert t3.is_right()
224
+ assert p1 in t1
225
+ assert t1.sides[0] in t1
226
+ assert Segment((0, 0), (1, 0)) in t1
227
+ assert Point(5, 5) not in t2
228
+ assert t1.is_convex()
229
+ assert feq(t1.angles[p1].evalf(), pi.evalf()/2)
230
+
231
+ assert t1.is_equilateral() is False
232
+ assert t2.is_equilateral()
233
+ assert t3.is_equilateral() is False
234
+ assert are_similar(t1, t2) is False
235
+ assert are_similar(t1, t3)
236
+ assert are_similar(t2, t3) is False
237
+ assert t1.is_similar(Point(0, 0)) is False
238
+ assert t1.is_similar(t2) is False
239
+
240
+ # Bisectors
241
+ bisectors = t1.bisectors()
242
+ assert bisectors[p1] == Segment(
243
+ p1, Point(Rational(5, 2), Rational(5, 2)))
244
+ assert t2.bisectors()[p2] == Segment(
245
+ Point(5, 0), Point(Rational(5, 4), 5*sqrt(3)/4))
246
+ p4 = Point(0, x1)
247
+ assert t3.bisectors()[p4] == Segment(p4, Point(x1*(sqrt(2) - 1), 0))
248
+ ic = (250 - 125*sqrt(2))/50
249
+ assert t1.incenter == Point(ic, ic)
250
+
251
+ # Inradius
252
+ assert t1.inradius == t1.incircle.radius == 5 - 5*sqrt(2)/2
253
+ assert t2.inradius == t2.incircle.radius == 5*sqrt(3)/6
254
+ assert t3.inradius == t3.incircle.radius == x1**2/((2 + sqrt(2))*Abs(x1))
255
+
256
+ # Exradius
257
+ assert t1.exradii[t1.sides[2]] == 5*sqrt(2)/2
258
+
259
+ # Excenters
260
+ assert t1.excenters[t1.sides[2]] == Point2D(25*sqrt(2), -5*sqrt(2)/2)
261
+
262
+ # Circumcircle
263
+ assert t1.circumcircle.center == Point(2.5, 2.5)
264
+
265
+ # Medians + Centroid
266
+ m = t1.medians
267
+ assert t1.centroid == Point(Rational(5, 3), Rational(5, 3))
268
+ assert m[p1] == Segment(p1, Point(Rational(5, 2), Rational(5, 2)))
269
+ assert t3.medians[p1] == Segment(p1, Point(x1/2, x1/2))
270
+ assert intersection(m[p1], m[p2], m[p3]) == [t1.centroid]
271
+ assert t1.medial == Triangle(Point(2.5, 0), Point(0, 2.5), Point(2.5, 2.5))
272
+
273
+ # Nine-point circle
274
+ assert t1.nine_point_circle == Circle(Point(2.5, 0),
275
+ Point(0, 2.5), Point(2.5, 2.5))
276
+ assert t1.nine_point_circle == Circle(Point(0, 0),
277
+ Point(0, 2.5), Point(2.5, 2.5))
278
+
279
+ # Perpendicular
280
+ altitudes = t1.altitudes
281
+ assert altitudes[p1] == Segment(p1, Point(Rational(5, 2), Rational(5, 2)))
282
+ assert altitudes[p2].equals(s1[0])
283
+ assert altitudes[p3] == s1[2]
284
+ assert t1.orthocenter == p1
285
+ t = S('''Triangle(
286
+ Point(100080156402737/5000000000000, 79782624633431/500000000000),
287
+ Point(39223884078253/2000000000000, 156345163124289/1000000000000),
288
+ Point(31241359188437/1250000000000, 338338270939941/1000000000000000))''')
289
+ assert t.orthocenter == S('''Point(-780660869050599840216997'''
290
+ '''79471538701955848721853/80368430960602242240789074233100000000000000,'''
291
+ '''20151573611150265741278060334545897615974257/16073686192120448448157'''
292
+ '''8148466200000000000)''')
293
+
294
+ # Ensure
295
+ assert len(intersection(*bisectors.values())) == 1
296
+ assert len(intersection(*altitudes.values())) == 1
297
+ assert len(intersection(*m.values())) == 1
298
+
299
+ # Distance
300
+ p1 = Polygon(
301
+ Point(0, 0), Point(1, 0),
302
+ Point(1, 1), Point(0, 1))
303
+ p2 = Polygon(
304
+ Point(0, Rational(5)/4), Point(1, Rational(5)/4),
305
+ Point(1, Rational(9)/4), Point(0, Rational(9)/4))
306
+ p3 = Polygon(
307
+ Point(1, 2), Point(2, 2),
308
+ Point(2, 1))
309
+ p4 = Polygon(
310
+ Point(1, 1), Point(Rational(6)/5, 1),
311
+ Point(1, Rational(6)/5))
312
+ pt1 = Point(half, half)
313
+ pt2 = Point(1, 1)
314
+
315
+ '''Polygon to Point'''
316
+ assert p1.distance(pt1) == half
317
+ assert p1.distance(pt2) == 0
318
+ assert p2.distance(pt1) == Rational(3)/4
319
+ assert p3.distance(pt2) == sqrt(2)/2
320
+
321
+ '''Polygon to Polygon'''
322
+ # p1.distance(p2) emits a warning
323
+ with warns(UserWarning, \
324
+ match="Polygons may intersect producing erroneous output"):
325
+ assert p1.distance(p2) == half/2
326
+
327
+ assert p1.distance(p3) == sqrt(2)/2
328
+
329
+ # p3.distance(p4) emits a warning
330
+ with warns(UserWarning, \
331
+ match="Polygons may intersect producing erroneous output"):
332
+ assert p3.distance(p4) == (sqrt(2)/2 - sqrt(Rational(2)/25)/2)
333
+
334
+
335
+ def test_convex_hull():
336
+ p = [Point(-5, -1), Point(-2, 1), Point(-2, -1), Point(-1, -3), \
337
+ Point(0, 0), Point(1, 1), Point(2, 2), Point(2, -1), Point(3, 1), \
338
+ Point(4, -1), Point(6, 2)]
339
+ ch = Polygon(p[0], p[3], p[9], p[10], p[6], p[1])
340
+ #test handling of duplicate points
341
+ p.append(p[3])
342
+
343
+ #more than 3 collinear points
344
+ another_p = [Point(-45, -85), Point(-45, 85), Point(-45, 26), \
345
+ Point(-45, -24)]
346
+ ch2 = Segment(another_p[0], another_p[1])
347
+
348
+ assert convex_hull(*another_p) == ch2
349
+ assert convex_hull(*p) == ch
350
+ assert convex_hull(p[0]) == p[0]
351
+ assert convex_hull(p[0], p[1]) == Segment(p[0], p[1])
352
+
353
+ # no unique points
354
+ assert convex_hull(*[p[-1]]*3) == p[-1]
355
+
356
+ # collection of items
357
+ assert convex_hull(*[Point(0, 0), \
358
+ Segment(Point(1, 0), Point(1, 1)), \
359
+ RegularPolygon(Point(2, 0), 2, 4)]) == \
360
+ Polygon(Point(0, 0), Point(2, -2), Point(4, 0), Point(2, 2))
361
+
362
+
363
+ def test_encloses():
364
+ # square with a dimpled left side
365
+ s = Polygon(Point(0, 0), Point(1, 0), Point(1, 1), Point(0, 1), \
366
+ Point(S.Half, S.Half))
367
+ # the following is True if the polygon isn't treated as closing on itself
368
+ assert s.encloses(Point(0, S.Half)) is False
369
+ assert s.encloses(Point(S.Half, S.Half)) is False # it's a vertex
370
+ assert s.encloses(Point(Rational(3, 4), S.Half)) is True
371
+
372
+
373
+ def test_triangle_kwargs():
374
+ assert Triangle(sss=(3, 4, 5)) == \
375
+ Triangle(Point(0, 0), Point(3, 0), Point(3, 4))
376
+ assert Triangle(asa=(30, 2, 30)) == \
377
+ Triangle(Point(0, 0), Point(2, 0), Point(1, sqrt(3)/3))
378
+ assert Triangle(sas=(1, 45, 2)) == \
379
+ Triangle(Point(0, 0), Point(2, 0), Point(sqrt(2)/2, sqrt(2)/2))
380
+ assert Triangle(sss=(1, 2, 5)) is None
381
+ assert deg(rad(180)) == 180
382
+
383
+
384
+ def test_transform():
385
+ pts = [Point(0, 0), Point(S.Half, Rational(1, 4)), Point(1, 1)]
386
+ pts_out = [Point(-4, -10), Point(-3, Rational(-37, 4)), Point(-2, -7)]
387
+ assert Triangle(*pts).scale(2, 3, (4, 5)) == Triangle(*pts_out)
388
+ assert RegularPolygon((0, 0), 1, 4).scale(2, 3, (4, 5)) == \
389
+ Polygon(Point(-2, -10), Point(-4, -7), Point(-6, -10), Point(-4, -13))
390
+ # Checks for symmetric scaling
391
+ assert RegularPolygon((0, 0), 1, 4).scale(2, 2) == \
392
+ RegularPolygon(Point2D(0, 0), 2, 4, 0)
393
+
394
+ def test_reflect():
395
+ x = Symbol('x', real=True)
396
+ y = Symbol('y', real=True)
397
+ b = Symbol('b')
398
+ m = Symbol('m')
399
+ l = Line((0, b), slope=m)
400
+ p = Point(x, y)
401
+ r = p.reflect(l)
402
+ dp = l.perpendicular_segment(p).length
403
+ dr = l.perpendicular_segment(r).length
404
+
405
+ assert verify_numerically(dp, dr)
406
+
407
+ assert Polygon((1, 0), (2, 0), (2, 2)).reflect(Line((3, 0), slope=oo)) \
408
+ == Triangle(Point(5, 0), Point(4, 0), Point(4, 2))
409
+ assert Polygon((1, 0), (2, 0), (2, 2)).reflect(Line((0, 3), slope=oo)) \
410
+ == Triangle(Point(-1, 0), Point(-2, 0), Point(-2, 2))
411
+ assert Polygon((1, 0), (2, 0), (2, 2)).reflect(Line((0, 3), slope=0)) \
412
+ == Triangle(Point(1, 6), Point(2, 6), Point(2, 4))
413
+ assert Polygon((1, 0), (2, 0), (2, 2)).reflect(Line((3, 0), slope=0)) \
414
+ == Triangle(Point(1, 0), Point(2, 0), Point(2, -2))
415
+
416
+ def test_bisectors():
417
+ p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1)
418
+ p = Polygon(Point(0, 0), Point(2, 0), Point(1, 1), Point(0, 3))
419
+ q = Polygon(Point(1, 0), Point(2, 0), Point(3, 3), Point(-1, 5))
420
+ poly = Polygon(Point(3, 4), Point(0, 0), Point(8, 7), Point(-1, 1), Point(19, -19))
421
+ t = Triangle(p1, p2, p3)
422
+ assert t.bisectors()[p2] == Segment(Point(1, 0), Point(0, sqrt(2) - 1))
423
+ assert p.bisectors()[Point2D(0, 3)] == Ray2D(Point2D(0, 3), \
424
+ Point2D(sin(acos(2*sqrt(5)/5)/2), 3 - cos(acos(2*sqrt(5)/5)/2)))
425
+ assert q.bisectors()[Point2D(-1, 5)] == \
426
+ Ray2D(Point2D(-1, 5), Point2D(-1 + sqrt(29)*(5*sin(acos(9*sqrt(145)/145)/2) + \
427
+ 2*cos(acos(9*sqrt(145)/145)/2))/29, sqrt(29)*(-5*cos(acos(9*sqrt(145)/145)/2) + \
428
+ 2*sin(acos(9*sqrt(145)/145)/2))/29 + 5))
429
+ assert poly.bisectors()[Point2D(-1, 1)] == Ray2D(Point2D(-1, 1), \
430
+ Point2D(-1 + sin(acos(sqrt(26)/26)/2 + pi/4), 1 - sin(-acos(sqrt(26)/26)/2 + pi/4)))
431
+
432
+ def test_incenter():
433
+ assert Triangle(Point(0, 0), Point(1, 0), Point(0, 1)).incenter \
434
+ == Point(1 - sqrt(2)/2, 1 - sqrt(2)/2)
435
+
436
+ def test_inradius():
437
+ assert Triangle(Point(0, 0), Point(4, 0), Point(0, 3)).inradius == 1
438
+
439
+ def test_incircle():
440
+ assert Triangle(Point(0, 0), Point(2, 0), Point(0, 2)).incircle \
441
+ == Circle(Point(2 - sqrt(2), 2 - sqrt(2)), 2 - sqrt(2))
442
+
443
+ def test_exradii():
444
+ t = Triangle(Point(0, 0), Point(6, 0), Point(0, 2))
445
+ assert t.exradii[t.sides[2]] == (-2 + sqrt(10))
446
+
447
+ def test_medians():
448
+ t = Triangle(Point(0, 0), Point(1, 0), Point(0, 1))
449
+ assert t.medians[Point(0, 0)] == Segment(Point(0, 0), Point(S.Half, S.Half))
450
+
451
+ def test_medial():
452
+ assert Triangle(Point(0, 0), Point(1, 0), Point(0, 1)).medial \
453
+ == Triangle(Point(S.Half, 0), Point(S.Half, S.Half), Point(0, S.Half))
454
+
455
+ def test_nine_point_circle():
456
+ assert Triangle(Point(0, 0), Point(1, 0), Point(0, 1)).nine_point_circle \
457
+ == Circle(Point2D(Rational(1, 4), Rational(1, 4)), sqrt(2)/4)
458
+
459
+ def test_eulerline():
460
+ assert Triangle(Point(0, 0), Point(1, 0), Point(0, 1)).eulerline \
461
+ == Line(Point2D(0, 0), Point2D(S.Half, S.Half))
462
+ assert Triangle(Point(0, 0), Point(10, 0), Point(5, 5*sqrt(3))).eulerline \
463
+ == Point2D(5, 5*sqrt(3)/3)
464
+ assert Triangle(Point(4, -6), Point(4, -1), Point(-3, 3)).eulerline \
465
+ == Line(Point2D(Rational(64, 7), 3), Point2D(Rational(-29, 14), Rational(-7, 2)))
466
+
467
+ def test_intersection():
468
+ poly1 = Triangle(Point(0, 0), Point(1, 0), Point(0, 1))
469
+ poly2 = Polygon(Point(0, 1), Point(-5, 0),
470
+ Point(0, -4), Point(0, Rational(1, 5)),
471
+ Point(S.Half, -0.1), Point(1, 0), Point(0, 1))
472
+
473
+ assert poly1.intersection(poly2) == [Point2D(Rational(1, 3), 0),
474
+ Segment(Point(0, Rational(1, 5)), Point(0, 0)),
475
+ Segment(Point(1, 0), Point(0, 1))]
476
+ assert poly2.intersection(poly1) == [Point(Rational(1, 3), 0),
477
+ Segment(Point(0, 0), Point(0, Rational(1, 5))),
478
+ Segment(Point(1, 0), Point(0, 1))]
479
+ assert poly1.intersection(Point(0, 0)) == [Point(0, 0)]
480
+ assert poly1.intersection(Point(-12, -43)) == []
481
+ assert poly2.intersection(Line((-12, 0), (12, 0))) == [Point(-5, 0),
482
+ Point(0, 0), Point(Rational(1, 3), 0), Point(1, 0)]
483
+ assert poly2.intersection(Line((-12, 12), (12, 12))) == []
484
+ assert poly2.intersection(Ray((-3, 4), (1, 0))) == [Segment(Point(1, 0),
485
+ Point(0, 1))]
486
+ assert poly2.intersection(Circle((0, -1), 1)) == [Point(0, -2),
487
+ Point(0, 0)]
488
+ assert poly1.intersection(poly1) == [Segment(Point(0, 0), Point(1, 0)),
489
+ Segment(Point(0, 1), Point(0, 0)), Segment(Point(1, 0), Point(0, 1))]
490
+ assert poly2.intersection(poly2) == [Segment(Point(-5, 0), Point(0, -4)),
491
+ Segment(Point(0, -4), Point(0, Rational(1, 5))),
492
+ Segment(Point(0, Rational(1, 5)), Point(S.Half, Rational(-1, 10))),
493
+ Segment(Point(0, 1), Point(-5, 0)),
494
+ Segment(Point(S.Half, Rational(-1, 10)), Point(1, 0)),
495
+ Segment(Point(1, 0), Point(0, 1))]
496
+ assert poly2.intersection(Triangle(Point(0, 1), Point(1, 0), Point(-1, 1))) \
497
+ == [Point(Rational(-5, 7), Rational(6, 7)), Segment(Point2D(0, 1), Point(1, 0))]
498
+ assert poly1.intersection(RegularPolygon((-12, -15), 3, 3)) == []
499
+
500
+
501
+ def test_parameter_value():
502
+ t = Symbol('t')
503
+ sq = Polygon((0, 0), (0, 1), (1, 1), (1, 0))
504
+ assert sq.parameter_value((0.5, 1), t) == {t: Rational(3, 8)}
505
+ q = Polygon((0, 0), (2, 1), (2, 4), (4, 0))
506
+ assert q.parameter_value((4, 0), t) == {t: -6 + 3*sqrt(5)} # ~= 0.708
507
+
508
+ raises(ValueError, lambda: sq.parameter_value((5, 6), t))
509
+ raises(ValueError, lambda: sq.parameter_value(Circle(Point(0, 0), 1), t))
510
+
511
+
512
+ def test_issue_12966():
513
+ poly = Polygon(Point(0, 0), Point(0, 10), Point(5, 10), Point(5, 5),
514
+ Point(10, 5), Point(10, 0))
515
+ t = Symbol('t')
516
+ pt = poly.arbitrary_point(t)
517
+ DELTA = 5/poly.perimeter
518
+ assert [pt.subs(t, DELTA*i) for i in range(int(1/DELTA))] == [
519
+ Point(0, 0), Point(0, 5), Point(0, 10), Point(5, 10),
520
+ Point(5, 5), Point(10, 5), Point(10, 0), Point(5, 0)]
521
+
522
+
523
+ def test_second_moment_of_area():
524
+ x, y = symbols('x, y')
525
+ # triangle
526
+ p1, p2, p3 = [(0, 0), (4, 0), (0, 2)]
527
+ p = (0, 0)
528
+ # equation of hypotenuse
529
+ eq_y = (1-x/4)*2
530
+ I_yy = integrate((x**2) * (integrate(1, (y, 0, eq_y))), (x, 0, 4))
531
+ I_xx = integrate(1 * (integrate(y**2, (y, 0, eq_y))), (x, 0, 4))
532
+ I_xy = integrate(x * (integrate(y, (y, 0, eq_y))), (x, 0, 4))
533
+
534
+ triangle = Polygon(p1, p2, p3)
535
+
536
+ assert (I_xx - triangle.second_moment_of_area(p)[0]) == 0
537
+ assert (I_yy - triangle.second_moment_of_area(p)[1]) == 0
538
+ assert (I_xy - triangle.second_moment_of_area(p)[2]) == 0
539
+
540
+ # rectangle
541
+ p1, p2, p3, p4=[(0, 0), (4, 0), (4, 2), (0, 2)]
542
+ I_yy = integrate((x**2) * integrate(1, (y, 0, 2)), (x, 0, 4))
543
+ I_xx = integrate(1 * integrate(y**2, (y, 0, 2)), (x, 0, 4))
544
+ I_xy = integrate(x * integrate(y, (y, 0, 2)), (x, 0, 4))
545
+
546
+ rectangle = Polygon(p1, p2, p3, p4)
547
+
548
+ assert (I_xx - rectangle.second_moment_of_area(p)[0]) == 0
549
+ assert (I_yy - rectangle.second_moment_of_area(p)[1]) == 0
550
+ assert (I_xy - rectangle.second_moment_of_area(p)[2]) == 0
551
+
552
+
553
+ r = RegularPolygon(Point(0, 0), 5, 3)
554
+ assert r.second_moment_of_area() == (1875*sqrt(3)/S(32), 1875*sqrt(3)/S(32), 0)
555
+
556
+
557
+ def test_first_moment():
558
+ a, b = symbols('a, b', positive=True)
559
+ # rectangle
560
+ p1 = Polygon((0, 0), (a, 0), (a, b), (0, b))
561
+ assert p1.first_moment_of_area() == (a*b**2/8, a**2*b/8)
562
+ assert p1.first_moment_of_area((a/3, b/4)) == (-3*a*b**2/32, -a**2*b/9)
563
+
564
+ p1 = Polygon((0, 0), (40, 0), (40, 30), (0, 30))
565
+ assert p1.first_moment_of_area() == (4500, 6000)
566
+
567
+ # triangle
568
+ p2 = Polygon((0, 0), (a, 0), (a/2, b))
569
+ assert p2.first_moment_of_area() == (4*a*b**2/81, a**2*b/24)
570
+ assert p2.first_moment_of_area((a/8, b/6)) == (-25*a*b**2/648, -5*a**2*b/768)
571
+
572
+ p2 = Polygon((0, 0), (12, 0), (12, 30))
573
+ assert p2.first_moment_of_area() == (S(1600)/3, -S(640)/3)
574
+
575
+
576
+ def test_section_modulus_and_polar_second_moment_of_area():
577
+ a, b = symbols('a, b', positive=True)
578
+ x, y = symbols('x, y')
579
+ rectangle = Polygon((0, b), (0, 0), (a, 0), (a, b))
580
+ assert rectangle.section_modulus(Point(x, y)) == (a*b**3/12/(-b/2 + y), a**3*b/12/(-a/2 + x))
581
+ assert rectangle.polar_second_moment_of_area() == a**3*b/12 + a*b**3/12
582
+
583
+ convex = RegularPolygon((0, 0), 1, 6)
584
+ assert convex.section_modulus() == (Rational(5, 8), sqrt(3)*Rational(5, 16))
585
+ assert convex.polar_second_moment_of_area() == 5*sqrt(3)/S(8)
586
+
587
+ concave = Polygon((0, 0), (1, 8), (3, 4), (4, 6), (7, 1))
588
+ assert concave.section_modulus() == (Rational(-6371, 429), Rational(-9778, 519))
589
+ assert concave.polar_second_moment_of_area() == Rational(-38669, 252)
590
+
591
+
592
+ def test_cut_section():
593
+ # concave polygon
594
+ p = Polygon((-1, -1), (1, Rational(5, 2)), (2, 1), (3, Rational(5, 2)), (4, 2), (5, 3), (-1, 3))
595
+ l = Line((0, 0), (Rational(9, 2), 3))
596
+ p1 = p.cut_section(l)[0]
597
+ p2 = p.cut_section(l)[1]
598
+ assert p1 == Polygon(
599
+ Point2D(Rational(-9, 13), Rational(-6, 13)), Point2D(1, Rational(5, 2)), Point2D(Rational(24, 13), Rational(16, 13)),
600
+ Point2D(Rational(12, 5), Rational(8, 5)), Point2D(3, Rational(5, 2)), Point2D(Rational(24, 7), Rational(16, 7)),
601
+ Point2D(Rational(9, 2), 3), Point2D(-1, 3), Point2D(-1, Rational(-2, 3)))
602
+ assert p2 == Polygon(Point2D(-1, -1), Point2D(Rational(-9, 13), Rational(-6, 13)), Point2D(Rational(24, 13), Rational(16, 13)),
603
+ Point2D(2, 1), Point2D(Rational(12, 5), Rational(8, 5)), Point2D(Rational(24, 7), Rational(16, 7)), Point2D(4, 2), Point2D(5, 3),
604
+ Point2D(Rational(9, 2), 3), Point2D(-1, Rational(-2, 3)))
605
+
606
+ # convex polygon
607
+ p = RegularPolygon(Point2D(0, 0), 6, 6)
608
+ s = p.cut_section(Line((0, 0), slope=1))
609
+ assert s[0] == Polygon(Point2D(-3*sqrt(3) + 9, -3*sqrt(3) + 9), Point2D(3, 3*sqrt(3)),
610
+ Point2D(-3, 3*sqrt(3)), Point2D(-6, 0), Point2D(-9 + 3*sqrt(3), -9 + 3*sqrt(3)))
611
+ assert s[1] == Polygon(Point2D(6, 0), Point2D(-3*sqrt(3) + 9, -3*sqrt(3) + 9),
612
+ Point2D(-9 + 3*sqrt(3), -9 + 3*sqrt(3)), Point2D(-3, -3*sqrt(3)), Point2D(3, -3*sqrt(3)))
613
+
614
+ # case where line does not intersects but coincides with the edge of polygon
615
+ a, b = 20, 10
616
+ t1, t2, t3, t4 = [(0, b), (0, 0), (a, 0), (a, b)]
617
+ p = Polygon(t1, t2, t3, t4)
618
+ p1, p2 = p.cut_section(Line((0, b), slope=0))
619
+ assert p1 == None
620
+ assert p2 == Polygon(Point2D(0, 10), Point2D(0, 0), Point2D(20, 0), Point2D(20, 10))
621
+
622
+ p3, p4 = p.cut_section(Line((0, 0), slope=0))
623
+ assert p3 == Polygon(Point2D(0, 10), Point2D(0, 0), Point2D(20, 0), Point2D(20, 10))
624
+ assert p4 == None
625
+
626
+ # case where the line does not intersect with a polygon at all
627
+ raises(ValueError, lambda: p.cut_section(Line((0, a), slope=0)))
628
+
629
+ def test_type_of_triangle():
630
+ # Isoceles triangle
631
+ p1 = Polygon(Point(0, 0), Point(5, 0), Point(2, 4))
632
+ assert p1.is_isosceles() == True
633
+ assert p1.is_scalene() == False
634
+ assert p1.is_equilateral() == False
635
+
636
+ # Scalene triangle
637
+ p2 = Polygon (Point(0, 0), Point(0, 2), Point(4, 0))
638
+ assert p2.is_isosceles() == False
639
+ assert p2.is_scalene() == True
640
+ assert p2.is_equilateral() == False
641
+
642
+ # Equilateral triagle
643
+ p3 = Polygon(Point(0, 0), Point(6, 0), Point(3, sqrt(27)))
644
+ assert p3.is_isosceles() == True
645
+ assert p3.is_scalene() == False
646
+ assert p3.is_equilateral() == True
647
+
648
+ def test_do_poly_distance():
649
+ # Non-intersecting polygons
650
+ square1 = Polygon (Point(0, 0), Point(0, 1), Point(1, 1), Point(1, 0))
651
+ triangle1 = Polygon(Point(1, 2), Point(2, 2), Point(2, 1))
652
+ assert square1._do_poly_distance(triangle1) == sqrt(2)/2
653
+
654
+ # Polygons which sides intersect
655
+ square2 = Polygon(Point(1, 0), Point(2, 0), Point(2, 1), Point(1, 1))
656
+ with warns(UserWarning, \
657
+ match="Polygons may intersect producing erroneous output", test_stacklevel=False):
658
+ assert square1._do_poly_distance(square2) == 0
659
+
660
+ # Polygons which bodies intersect
661
+ triangle2 = Polygon(Point(0, -1), Point(2, -1), Point(S.Half, S.Half))
662
+ with warns(UserWarning, \
663
+ match="Polygons may intersect producing erroneous output", test_stacklevel=False):
664
+ assert triangle2._do_poly_distance(square1) == 0
llmeval-env/lib/python3.10/site-packages/sympy/geometry/tests/test_util.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.function import (Derivative, Function)
2
+ from sympy.core.singleton import S
3
+ from sympy.core.symbol import Symbol
4
+ from sympy.functions import exp, cos, sin, tan, cosh, sinh
5
+ from sympy.functions.elementary.miscellaneous import sqrt
6
+ from sympy.geometry import Point, Point2D, Line, Polygon, Segment, convex_hull,\
7
+ intersection, centroid, Point3D, Line3D
8
+ from sympy.geometry.util import idiff, closest_points, farthest_points, _ordered_points, are_coplanar
9
+ from sympy.solvers.solvers import solve
10
+ from sympy.testing.pytest import raises
11
+
12
+
13
+ def test_idiff():
14
+ x = Symbol('x', real=True)
15
+ y = Symbol('y', real=True)
16
+ t = Symbol('t', real=True)
17
+ f = Function('f')
18
+ g = Function('g')
19
+ # the use of idiff in ellipse also provides coverage
20
+ circ = x**2 + y**2 - 4
21
+ ans = -3*x*(x**2/y**2 + 1)/y**3
22
+ assert ans == idiff(circ, y, x, 3), idiff(circ, y, x, 3)
23
+ assert ans == idiff(circ, [y], x, 3)
24
+ assert idiff(circ, y, x, 3) == ans
25
+ explicit = 12*x/sqrt(-x**2 + 4)**5
26
+ assert ans.subs(y, solve(circ, y)[0]).equals(explicit)
27
+ assert True in [sol.diff(x, 3).equals(explicit) for sol in solve(circ, y)]
28
+ assert idiff(x + t + y, [y, t], x) == -Derivative(t, x) - 1
29
+ assert idiff(f(x) * exp(f(x)) - x * exp(x), f(x), x) == (x + 1)*exp(x)*exp(-f(x))/(f(x) + 1)
30
+ assert idiff(f(x) - y * exp(x), [f(x), y], x) == (y + Derivative(y, x))*exp(x)
31
+ assert idiff(f(x) - y * exp(x), [y, f(x)], x) == -y + Derivative(f(x), x)*exp(-x)
32
+ assert idiff(f(x) - g(x), [f(x), g(x)], x) == Derivative(g(x), x)
33
+ # this should be fast
34
+ fxy = y - (-10*(-sin(x) + 1/x)**2 + tan(x)**2 + 2*cosh(x/10))
35
+ assert idiff(fxy, y, x) == -20*sin(x)*cos(x) + 2*tan(x)**3 + \
36
+ 2*tan(x) + sinh(x/10)/5 + 20*cos(x)/x - 20*sin(x)/x**2 + 20/x**3
37
+
38
+
39
+ def test_intersection():
40
+ assert intersection(Point(0, 0)) == []
41
+ raises(TypeError, lambda: intersection(Point(0, 0), 3))
42
+ assert intersection(
43
+ Segment((0, 0), (2, 0)),
44
+ Segment((-1, 0), (1, 0)),
45
+ Line((0, 0), (0, 1)), pairwise=True) == [
46
+ Point(0, 0), Segment((0, 0), (1, 0))]
47
+ assert intersection(
48
+ Line((0, 0), (0, 1)),
49
+ Segment((0, 0), (2, 0)),
50
+ Segment((-1, 0), (1, 0)), pairwise=True) == [
51
+ Point(0, 0), Segment((0, 0), (1, 0))]
52
+ assert intersection(
53
+ Line((0, 0), (0, 1)),
54
+ Segment((0, 0), (2, 0)),
55
+ Segment((-1, 0), (1, 0)),
56
+ Line((0, 0), slope=1), pairwise=True) == [
57
+ Point(0, 0), Segment((0, 0), (1, 0))]
58
+
59
+
60
+ def test_convex_hull():
61
+ raises(TypeError, lambda: convex_hull(Point(0, 0), 3))
62
+ points = [(1, -1), (1, -2), (3, -1), (-5, -2), (15, -4)]
63
+ assert convex_hull(*points, **{"polygon": False}) == (
64
+ [Point2D(-5, -2), Point2D(1, -1), Point2D(3, -1), Point2D(15, -4)],
65
+ [Point2D(-5, -2), Point2D(15, -4)])
66
+
67
+
68
+ def test_centroid():
69
+ p = Polygon((0, 0), (10, 0), (10, 10))
70
+ q = p.translate(0, 20)
71
+ assert centroid(p, q) == Point(20, 40)/3
72
+ p = Segment((0, 0), (2, 0))
73
+ q = Segment((0, 0), (2, 2))
74
+ assert centroid(p, q) == Point(1, -sqrt(2) + 2)
75
+ assert centroid(Point(0, 0), Point(2, 0)) == Point(2, 0)/2
76
+ assert centroid(Point(0, 0), Point(0, 0), Point(2, 0)) == Point(2, 0)/3
77
+
78
+
79
+ def test_farthest_points_closest_points():
80
+ from sympy.core.random import randint
81
+ from sympy.utilities.iterables import subsets
82
+
83
+ for how in (min, max):
84
+ if how == min:
85
+ func = closest_points
86
+ else:
87
+ func = farthest_points
88
+
89
+ raises(ValueError, lambda: func(Point2D(0, 0), Point2D(0, 0)))
90
+
91
+ # 3rd pt dx is close and pt is closer to 1st pt
92
+ p1 = [Point2D(0, 0), Point2D(3, 0), Point2D(1, 1)]
93
+ # 3rd pt dx is close and pt is closer to 2nd pt
94
+ p2 = [Point2D(0, 0), Point2D(3, 0), Point2D(2, 1)]
95
+ # 3rd pt dx is close and but pt is not closer
96
+ p3 = [Point2D(0, 0), Point2D(3, 0), Point2D(1, 10)]
97
+ # 3rd pt dx is not closer and it's closer to 2nd pt
98
+ p4 = [Point2D(0, 0), Point2D(3, 0), Point2D(4, 0)]
99
+ # 3rd pt dx is not closer and it's closer to 1st pt
100
+ p5 = [Point2D(0, 0), Point2D(3, 0), Point2D(-1, 0)]
101
+ # duplicate point doesn't affect outcome
102
+ dup = [Point2D(0, 0), Point2D(3, 0), Point2D(3, 0), Point2D(-1, 0)]
103
+ # symbolic
104
+ x = Symbol('x', positive=True)
105
+ s = [Point2D(a) for a in ((x, 1), (x + 3, 2), (x + 2, 2))]
106
+
107
+ for points in (p1, p2, p3, p4, p5, dup, s):
108
+ d = how(i.distance(j) for i, j in subsets(set(points), 2))
109
+ ans = a, b = list(func(*points))[0]
110
+ assert a.distance(b) == d
111
+ assert ans == _ordered_points(ans)
112
+
113
+ # if the following ever fails, the above tests were not sufficient
114
+ # and the logical error in the routine should be fixed
115
+ points = set()
116
+ while len(points) != 7:
117
+ points.add(Point2D(randint(1, 100), randint(1, 100)))
118
+ points = list(points)
119
+ d = how(i.distance(j) for i, j in subsets(points, 2))
120
+ ans = a, b = list(func(*points))[0]
121
+ assert a.distance(b) == d
122
+ assert ans == _ordered_points(ans)
123
+
124
+ # equidistant points
125
+ a, b, c = (
126
+ Point2D(0, 0), Point2D(1, 0), Point2D(S.Half, sqrt(3)/2))
127
+ ans = {_ordered_points((i, j))
128
+ for i, j in subsets((a, b, c), 2)}
129
+ assert closest_points(b, c, a) == ans
130
+ assert farthest_points(b, c, a) == ans
131
+
132
+ # unique to farthest
133
+ points = [(1, 1), (1, 2), (3, 1), (-5, 2), (15, 4)]
134
+ assert farthest_points(*points) == {
135
+ (Point2D(-5, 2), Point2D(15, 4))}
136
+ points = [(1, -1), (1, -2), (3, -1), (-5, -2), (15, -4)]
137
+ assert farthest_points(*points) == {
138
+ (Point2D(-5, -2), Point2D(15, -4))}
139
+ assert farthest_points((1, 1), (0, 0)) == {
140
+ (Point2D(0, 0), Point2D(1, 1))}
141
+ raises(ValueError, lambda: farthest_points((1, 1)))
142
+
143
+
144
+ def test_are_coplanar():
145
+ a = Line3D(Point3D(5, 0, 0), Point3D(1, -1, 1))
146
+ b = Line3D(Point3D(0, -2, 0), Point3D(3, 1, 1))
147
+ c = Line3D(Point3D(0, -1, 0), Point3D(5, -1, 9))
148
+ d = Line(Point2D(0, 3), Point2D(1, 5))
149
+
150
+ assert are_coplanar(a, b, c) == False
151
+ assert are_coplanar(a, d) == False
llmeval-env/lib/python3.10/site-packages/sympy/solvers/__init__.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A module for solving all kinds of equations.
2
+
3
+ Examples
4
+ ========
5
+
6
+ >>> from sympy.solvers import solve
7
+ >>> from sympy.abc import x
8
+ >>> solve(x**5+5*x**4+10*x**3+10*x**2+5*x+1,x)
9
+ [-1]
10
+ """
11
+ from sympy.core.assumptions import check_assumptions, failing_assumptions
12
+
13
+ from .solvers import solve, solve_linear_system, solve_linear_system_LU, \
14
+ solve_undetermined_coeffs, nsolve, solve_linear, checksol, \
15
+ det_quick, inv_quick
16
+
17
+ from .diophantine import diophantine
18
+
19
+ from .recurr import rsolve, rsolve_poly, rsolve_ratio, rsolve_hyper
20
+
21
+ from .ode import checkodesol, classify_ode, dsolve, \
22
+ homogeneous_order
23
+
24
+ from .polysys import solve_poly_system, solve_triangulated
25
+
26
+ from .pde import pde_separate, pde_separate_add, pde_separate_mul, \
27
+ pdsolve, classify_pde, checkpdesol
28
+
29
+ from .deutils import ode_order
30
+
31
+ from .inequalities import reduce_inequalities, reduce_abs_inequality, \
32
+ reduce_abs_inequalities, solve_poly_inequality, solve_rational_inequalities, solve_univariate_inequality
33
+
34
+ from .decompogen import decompogen
35
+
36
+ from .solveset import solveset, linsolve, linear_eq_to_matrix, nonlinsolve, substitution
37
+
38
+ # This is here instead of sympy/sets/__init__.py to avoid circular import issues
39
+ from ..core.singleton import S
40
+ Complexes = S.Complexes
41
+
42
+ __all__ = [
43
+ 'solve', 'solve_linear_system', 'solve_linear_system_LU',
44
+ 'solve_undetermined_coeffs', 'nsolve', 'solve_linear', 'checksol',
45
+ 'det_quick', 'inv_quick', 'check_assumptions', 'failing_assumptions',
46
+
47
+ 'diophantine',
48
+
49
+ 'rsolve', 'rsolve_poly', 'rsolve_ratio', 'rsolve_hyper',
50
+
51
+ 'checkodesol', 'classify_ode', 'dsolve', 'homogeneous_order',
52
+
53
+ 'solve_poly_system', 'solve_triangulated',
54
+
55
+ 'pde_separate', 'pde_separate_add', 'pde_separate_mul', 'pdsolve',
56
+ 'classify_pde', 'checkpdesol',
57
+
58
+ 'ode_order',
59
+
60
+ 'reduce_inequalities', 'reduce_abs_inequality', 'reduce_abs_inequalities',
61
+ 'solve_poly_inequality', 'solve_rational_inequalities',
62
+ 'solve_univariate_inequality',
63
+
64
+ 'decompogen',
65
+
66
+ 'solveset', 'linsolve', 'linear_eq_to_matrix', 'nonlinsolve',
67
+ 'substitution',
68
+
69
+ # This is here instead of sympy/sets/__init__.py to avoid circular import issues
70
+ 'Complexes',
71
+ ]
llmeval-env/lib/python3.10/site-packages/sympy/solvers/benchmarks/__init__.py ADDED
File without changes
llmeval-env/lib/python3.10/site-packages/sympy/solvers/benchmarks/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (197 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/solvers/benchmarks/__pycache__/bench_solvers.cpython-310.pyc ADDED
Binary file (737 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/solvers/benchmarks/bench_solvers.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.symbol import Symbol
2
+ from sympy.matrices.dense import (eye, zeros)
3
+ from sympy.solvers.solvers import solve_linear_system
4
+
5
+ N = 8
6
+ M = zeros(N, N + 1)
7
+ M[:, :N] = eye(N)
8
+ S = [Symbol('A%i' % i) for i in range(N)]
9
+
10
+
11
+ def timeit_linsolve_trivial():
12
+ solve_linear_system(M, *S)
llmeval-env/lib/python3.10/site-packages/sympy/solvers/bivariate.py ADDED
@@ -0,0 +1,509 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.add import Add
2
+ from sympy.core.exprtools import factor_terms
3
+ from sympy.core.function import expand_log, _mexpand
4
+ from sympy.core.power import Pow
5
+ from sympy.core.singleton import S
6
+ from sympy.core.sorting import ordered
7
+ from sympy.core.symbol import Dummy
8
+ from sympy.functions.elementary.exponential import (LambertW, exp, log)
9
+ from sympy.functions.elementary.miscellaneous import root
10
+ from sympy.polys.polyroots import roots
11
+ from sympy.polys.polytools import Poly, factor
12
+ from sympy.simplify.simplify import separatevars
13
+ from sympy.simplify.radsimp import collect
14
+ from sympy.simplify.simplify import powsimp
15
+ from sympy.solvers.solvers import solve, _invert
16
+ from sympy.utilities.iterables import uniq
17
+
18
+
19
+ def _filtered_gens(poly, symbol):
20
+ """process the generators of ``poly``, returning the set of generators that
21
+ have ``symbol``. If there are two generators that are inverses of each other,
22
+ prefer the one that has no denominator.
23
+
24
+ Examples
25
+ ========
26
+
27
+ >>> from sympy.solvers.bivariate import _filtered_gens
28
+ >>> from sympy import Poly, exp
29
+ >>> from sympy.abc import x
30
+ >>> _filtered_gens(Poly(x + 1/x + exp(x)), x)
31
+ {x, exp(x)}
32
+
33
+ """
34
+ # TODO it would be good to pick the smallest divisible power
35
+ # instead of the base for something like x**4 + x**2 -->
36
+ # return x**2 not x
37
+ gens = {g for g in poly.gens if symbol in g.free_symbols}
38
+ for g in list(gens):
39
+ ag = 1/g
40
+ if g in gens and ag in gens:
41
+ if ag.as_numer_denom()[1] is not S.One:
42
+ g = ag
43
+ gens.remove(g)
44
+ return gens
45
+
46
+
47
+ def _mostfunc(lhs, func, X=None):
48
+ """Returns the term in lhs which contains the most of the
49
+ func-type things e.g. log(log(x)) wins over log(x) if both terms appear.
50
+
51
+ ``func`` can be a function (exp, log, etc...) or any other SymPy object,
52
+ like Pow.
53
+
54
+ If ``X`` is not ``None``, then the function returns the term composed with the
55
+ most ``func`` having the specified variable.
56
+
57
+ Examples
58
+ ========
59
+
60
+ >>> from sympy.solvers.bivariate import _mostfunc
61
+ >>> from sympy import exp
62
+ >>> from sympy.abc import x, y
63
+ >>> _mostfunc(exp(x) + exp(exp(x) + 2), exp)
64
+ exp(exp(x) + 2)
65
+ >>> _mostfunc(exp(x) + exp(exp(y) + 2), exp)
66
+ exp(exp(y) + 2)
67
+ >>> _mostfunc(exp(x) + exp(exp(y) + 2), exp, x)
68
+ exp(x)
69
+ >>> _mostfunc(x, exp, x) is None
70
+ True
71
+ >>> _mostfunc(exp(x) + exp(x*y), exp, x)
72
+ exp(x)
73
+ """
74
+ fterms = [tmp for tmp in lhs.atoms(func) if (not X or
75
+ X.is_Symbol and X in tmp.free_symbols or
76
+ not X.is_Symbol and tmp.has(X))]
77
+ if len(fterms) == 1:
78
+ return fterms[0]
79
+ elif fterms:
80
+ return max(list(ordered(fterms)), key=lambda x: x.count(func))
81
+ return None
82
+
83
+
84
+ def _linab(arg, symbol):
85
+ """Return ``a, b, X`` assuming ``arg`` can be written as ``a*X + b``
86
+ where ``X`` is a symbol-dependent factor and ``a`` and ``b`` are
87
+ independent of ``symbol``.
88
+
89
+ Examples
90
+ ========
91
+
92
+ >>> from sympy.solvers.bivariate import _linab
93
+ >>> from sympy.abc import x, y
94
+ >>> from sympy import exp, S
95
+ >>> _linab(S(2), x)
96
+ (2, 0, 1)
97
+ >>> _linab(2*x, x)
98
+ (2, 0, x)
99
+ >>> _linab(y + y*x + 2*x, x)
100
+ (y + 2, y, x)
101
+ >>> _linab(3 + 2*exp(x), x)
102
+ (2, 3, exp(x))
103
+ """
104
+ arg = factor_terms(arg.expand())
105
+ ind, dep = arg.as_independent(symbol)
106
+ if arg.is_Mul and dep.is_Add:
107
+ a, b, x = _linab(dep, symbol)
108
+ return ind*a, ind*b, x
109
+ if not arg.is_Add:
110
+ b = 0
111
+ a, x = ind, dep
112
+ else:
113
+ b = ind
114
+ a, x = separatevars(dep).as_independent(symbol, as_Add=False)
115
+ if x.could_extract_minus_sign():
116
+ a = -a
117
+ x = -x
118
+ return a, b, x
119
+
120
+
121
+ def _lambert(eq, x):
122
+ """
123
+ Given an expression assumed to be in the form
124
+ ``F(X, a..f) = a*log(b*X + c) + d*X + f = 0``
125
+ where X = g(x) and x = g^-1(X), return the Lambert solution,
126
+ ``x = g^-1(-c/b + (a/d)*W(d/(a*b)*exp(c*d/a/b)*exp(-f/a)))``.
127
+ """
128
+ eq = _mexpand(expand_log(eq))
129
+ mainlog = _mostfunc(eq, log, x)
130
+ if not mainlog:
131
+ return [] # violated assumptions
132
+ other = eq.subs(mainlog, 0)
133
+ if isinstance(-other, log):
134
+ eq = (eq - other).subs(mainlog, mainlog.args[0])
135
+ mainlog = mainlog.args[0]
136
+ if not isinstance(mainlog, log):
137
+ return [] # violated assumptions
138
+ other = -(-other).args[0]
139
+ eq += other
140
+ if x not in other.free_symbols:
141
+ return [] # violated assumptions
142
+ d, f, X2 = _linab(other, x)
143
+ logterm = collect(eq - other, mainlog)
144
+ a = logterm.as_coefficient(mainlog)
145
+ if a is None or x in a.free_symbols:
146
+ return [] # violated assumptions
147
+ logarg = mainlog.args[0]
148
+ b, c, X1 = _linab(logarg, x)
149
+ if X1 != X2:
150
+ return [] # violated assumptions
151
+
152
+ # invert the generator X1 so we have x(u)
153
+ u = Dummy('rhs')
154
+ xusolns = solve(X1 - u, x)
155
+
156
+ # There are infinitely many branches for LambertW
157
+ # but only branches for k = -1 and 0 might be real. The k = 0
158
+ # branch is real and the k = -1 branch is real if the LambertW argumen
159
+ # in in range [-1/e, 0]. Since `solve` does not return infinite
160
+ # solutions we will only include the -1 branch if it tests as real.
161
+ # Otherwise, inclusion of any LambertW in the solution indicates to
162
+ # the user that there are imaginary solutions corresponding to
163
+ # different k values.
164
+ lambert_real_branches = [-1, 0]
165
+ sol = []
166
+
167
+ # solution of the given Lambert equation is like
168
+ # sol = -c/b + (a/d)*LambertW(arg, k),
169
+ # where arg = d/(a*b)*exp((c*d-b*f)/a/b) and k in lambert_real_branches.
170
+ # Instead of considering the single arg, `d/(a*b)*exp((c*d-b*f)/a/b)`,
171
+ # the individual `p` roots obtained when writing `exp((c*d-b*f)/a/b)`
172
+ # as `exp(A/p) = exp(A)**(1/p)`, where `p` is an Integer, are used.
173
+
174
+ # calculating args for LambertW
175
+ num, den = ((c*d-b*f)/a/b).as_numer_denom()
176
+ p, den = den.as_coeff_Mul()
177
+ e = exp(num/den)
178
+ t = Dummy('t')
179
+ args = [d/(a*b)*t for t in roots(t**p - e, t).keys()]
180
+
181
+ # calculating solutions from args
182
+ for arg in args:
183
+ for k in lambert_real_branches:
184
+ w = LambertW(arg, k)
185
+ if k and not w.is_real:
186
+ continue
187
+ rhs = -c/b + (a/d)*w
188
+
189
+ sol.extend(xu.subs(u, rhs) for xu in xusolns)
190
+ return sol
191
+
192
+
193
+ def _solve_lambert(f, symbol, gens):
194
+ """Return solution to ``f`` if it is a Lambert-type expression
195
+ else raise NotImplementedError.
196
+
197
+ For ``f(X, a..f) = a*log(b*X + c) + d*X - f = 0`` the solution
198
+ for ``X`` is ``X = -c/b + (a/d)*W(d/(a*b)*exp(c*d/a/b)*exp(f/a))``.
199
+ There are a variety of forms for `f(X, a..f)` as enumerated below:
200
+
201
+ 1a1)
202
+ if B**B = R for R not in [0, 1] (since those cases would already
203
+ be solved before getting here) then log of both sides gives
204
+ log(B) + log(log(B)) = log(log(R)) and
205
+ X = log(B), a = 1, b = 1, c = 0, d = 1, f = log(log(R))
206
+ 1a2)
207
+ if B*(b*log(B) + c)**a = R then log of both sides gives
208
+ log(B) + a*log(b*log(B) + c) = log(R) and
209
+ X = log(B), d=1, f=log(R)
210
+ 1b)
211
+ if a*log(b*B + c) + d*B = R and
212
+ X = B, f = R
213
+ 2a)
214
+ if (b*B + c)*exp(d*B + g) = R then log of both sides gives
215
+ log(b*B + c) + d*B + g = log(R) and
216
+ X = B, a = 1, f = log(R) - g
217
+ 2b)
218
+ if g*exp(d*B + h) - b*B = c then the log form is
219
+ log(g) + d*B + h - log(b*B + c) = 0 and
220
+ X = B, a = -1, f = -h - log(g)
221
+ 3)
222
+ if d*p**(a*B + g) - b*B = c then the log form is
223
+ log(d) + (a*B + g)*log(p) - log(b*B + c) = 0 and
224
+ X = B, a = -1, d = a*log(p), f = -log(d) - g*log(p)
225
+ """
226
+
227
+ def _solve_even_degree_expr(expr, t, symbol):
228
+ """Return the unique solutions of equations derived from
229
+ ``expr`` by replacing ``t`` with ``+/- symbol``.
230
+
231
+ Parameters
232
+ ==========
233
+
234
+ expr : Expr
235
+ The expression which includes a dummy variable t to be
236
+ replaced with +symbol and -symbol.
237
+
238
+ symbol : Symbol
239
+ The symbol for which a solution is being sought.
240
+
241
+ Returns
242
+ =======
243
+
244
+ List of unique solution of the two equations generated by
245
+ replacing ``t`` with positive and negative ``symbol``.
246
+
247
+ Notes
248
+ =====
249
+
250
+ If ``expr = 2*log(t) + x/2` then solutions for
251
+ ``2*log(x) + x/2 = 0`` and ``2*log(-x) + x/2 = 0`` are
252
+ returned by this function. Though this may seem
253
+ counter-intuitive, one must note that the ``expr`` being
254
+ solved here has been derived from a different expression. For
255
+ an expression like ``eq = x**2*g(x) = 1``, if we take the
256
+ log of both sides we obtain ``log(x**2) + log(g(x)) = 0``. If
257
+ x is positive then this simplifies to
258
+ ``2*log(x) + log(g(x)) = 0``; the Lambert-solving routines will
259
+ return solutions for this, but we must also consider the
260
+ solutions for ``2*log(-x) + log(g(x))`` since those must also
261
+ be a solution of ``eq`` which has the same value when the ``x``
262
+ in ``x**2`` is negated. If `g(x)` does not have even powers of
263
+ symbol then we do not want to replace the ``x`` there with
264
+ ``-x``. So the role of the ``t`` in the expression received by
265
+ this function is to mark where ``+/-x`` should be inserted
266
+ before obtaining the Lambert solutions.
267
+
268
+ """
269
+ nlhs, plhs = [
270
+ expr.xreplace({t: sgn*symbol}) for sgn in (-1, 1)]
271
+ sols = _solve_lambert(nlhs, symbol, gens)
272
+ if plhs != nlhs:
273
+ sols.extend(_solve_lambert(plhs, symbol, gens))
274
+ # uniq is needed for a case like
275
+ # 2*log(t) - log(-z**2) + log(z + log(x) + log(z))
276
+ # where substituting t with +/-x gives all the same solution;
277
+ # uniq, rather than list(set()), is used to maintain canonical
278
+ # order
279
+ return list(uniq(sols))
280
+
281
+ nrhs, lhs = f.as_independent(symbol, as_Add=True)
282
+ rhs = -nrhs
283
+
284
+ lamcheck = [tmp for tmp in gens
285
+ if (tmp.func in [exp, log] or
286
+ (tmp.is_Pow and symbol in tmp.exp.free_symbols))]
287
+ if not lamcheck:
288
+ raise NotImplementedError()
289
+
290
+ if lhs.is_Add or lhs.is_Mul:
291
+ # replacing all even_degrees of symbol with dummy variable t
292
+ # since these will need special handling; non-Add/Mul do not
293
+ # need this handling
294
+ t = Dummy('t', **symbol.assumptions0)
295
+ lhs = lhs.replace(
296
+ lambda i: # find symbol**even
297
+ i.is_Pow and i.base == symbol and i.exp.is_even,
298
+ lambda i: # replace t**even
299
+ t**i.exp)
300
+
301
+ if lhs.is_Add and lhs.has(t):
302
+ t_indep = lhs.subs(t, 0)
303
+ t_term = lhs - t_indep
304
+ _rhs = rhs - t_indep
305
+ if not t_term.is_Add and _rhs and not (
306
+ t_term.has(S.ComplexInfinity, S.NaN)):
307
+ eq = expand_log(log(t_term) - log(_rhs))
308
+ return _solve_even_degree_expr(eq, t, symbol)
309
+ elif lhs.is_Mul and rhs:
310
+ # this needs to happen whether t is present or not
311
+ lhs = expand_log(log(lhs), force=True)
312
+ rhs = log(rhs)
313
+ if lhs.has(t) and lhs.is_Add:
314
+ # it expanded from Mul to Add
315
+ eq = lhs - rhs
316
+ return _solve_even_degree_expr(eq, t, symbol)
317
+
318
+ # restore symbol in lhs
319
+ lhs = lhs.xreplace({t: symbol})
320
+
321
+ lhs = powsimp(factor(lhs, deep=True))
322
+
323
+ # make sure we have inverted as completely as possible
324
+ r = Dummy()
325
+ i, lhs = _invert(lhs - r, symbol)
326
+ rhs = i.xreplace({r: rhs})
327
+
328
+ # For the first forms:
329
+ #
330
+ # 1a1) B**B = R will arrive here as B*log(B) = log(R)
331
+ # lhs is Mul so take log of both sides:
332
+ # log(B) + log(log(B)) = log(log(R))
333
+ # 1a2) B*(b*log(B) + c)**a = R will arrive unchanged so
334
+ # lhs is Mul, so take log of both sides:
335
+ # log(B) + a*log(b*log(B) + c) = log(R)
336
+ # 1b) d*log(a*B + b) + c*B = R will arrive unchanged so
337
+ # lhs is Add, so isolate c*B and expand log of both sides:
338
+ # log(c) + log(B) = log(R - d*log(a*B + b))
339
+
340
+ soln = []
341
+ if not soln:
342
+ mainlog = _mostfunc(lhs, log, symbol)
343
+ if mainlog:
344
+ if lhs.is_Mul and rhs != 0:
345
+ soln = _lambert(log(lhs) - log(rhs), symbol)
346
+ elif lhs.is_Add:
347
+ other = lhs.subs(mainlog, 0)
348
+ if other and not other.is_Add and [
349
+ tmp for tmp in other.atoms(Pow)
350
+ if symbol in tmp.free_symbols]:
351
+ if not rhs:
352
+ diff = log(other) - log(other - lhs)
353
+ else:
354
+ diff = log(lhs - other) - log(rhs - other)
355
+ soln = _lambert(expand_log(diff), symbol)
356
+ else:
357
+ #it's ready to go
358
+ soln = _lambert(lhs - rhs, symbol)
359
+
360
+ # For the next forms,
361
+ #
362
+ # collect on main exp
363
+ # 2a) (b*B + c)*exp(d*B + g) = R
364
+ # lhs is mul, so take log of both sides:
365
+ # log(b*B + c) + d*B = log(R) - g
366
+ # 2b) g*exp(d*B + h) - b*B = R
367
+ # lhs is add, so add b*B to both sides,
368
+ # take the log of both sides and rearrange to give
369
+ # log(R + b*B) - d*B = log(g) + h
370
+
371
+ if not soln:
372
+ mainexp = _mostfunc(lhs, exp, symbol)
373
+ if mainexp:
374
+ lhs = collect(lhs, mainexp)
375
+ if lhs.is_Mul and rhs != 0:
376
+ soln = _lambert(expand_log(log(lhs) - log(rhs)), symbol)
377
+ elif lhs.is_Add:
378
+ # move all but mainexp-containing term to rhs
379
+ other = lhs.subs(mainexp, 0)
380
+ mainterm = lhs - other
381
+ rhs = rhs - other
382
+ if (mainterm.could_extract_minus_sign() and
383
+ rhs.could_extract_minus_sign()):
384
+ mainterm *= -1
385
+ rhs *= -1
386
+ diff = log(mainterm) - log(rhs)
387
+ soln = _lambert(expand_log(diff), symbol)
388
+
389
+ # For the last form:
390
+ #
391
+ # 3) d*p**(a*B + g) - b*B = c
392
+ # collect on main pow, add b*B to both sides,
393
+ # take log of both sides and rearrange to give
394
+ # a*B*log(p) - log(b*B + c) = -log(d) - g*log(p)
395
+ if not soln:
396
+ mainpow = _mostfunc(lhs, Pow, symbol)
397
+ if mainpow and symbol in mainpow.exp.free_symbols:
398
+ lhs = collect(lhs, mainpow)
399
+ if lhs.is_Mul and rhs != 0:
400
+ # b*B = 0
401
+ soln = _lambert(expand_log(log(lhs) - log(rhs)), symbol)
402
+ elif lhs.is_Add:
403
+ # move all but mainpow-containing term to rhs
404
+ other = lhs.subs(mainpow, 0)
405
+ mainterm = lhs - other
406
+ rhs = rhs - other
407
+ diff = log(mainterm) - log(rhs)
408
+ soln = _lambert(expand_log(diff), symbol)
409
+
410
+ if not soln:
411
+ raise NotImplementedError('%s does not appear to have a solution in '
412
+ 'terms of LambertW' % f)
413
+
414
+ return list(ordered(soln))
415
+
416
+
417
+ def bivariate_type(f, x, y, *, first=True):
418
+ """Given an expression, f, 3 tests will be done to see what type
419
+ of composite bivariate it might be, options for u(x, y) are::
420
+
421
+ x*y
422
+ x+y
423
+ x*y+x
424
+ x*y+y
425
+
426
+ If it matches one of these types, ``u(x, y)``, ``P(u)`` and dummy
427
+ variable ``u`` will be returned. Solving ``P(u)`` for ``u`` and
428
+ equating the solutions to ``u(x, y)`` and then solving for ``x`` or
429
+ ``y`` is equivalent to solving the original expression for ``x`` or
430
+ ``y``. If ``x`` and ``y`` represent two functions in the same
431
+ variable, e.g. ``x = g(t)`` and ``y = h(t)``, then if ``u(x, y) - p``
432
+ can be solved for ``t`` then these represent the solutions to
433
+ ``P(u) = 0`` when ``p`` are the solutions of ``P(u) = 0``.
434
+
435
+ Only positive values of ``u`` are considered.
436
+
437
+ Examples
438
+ ========
439
+
440
+ >>> from sympy import solve
441
+ >>> from sympy.solvers.bivariate import bivariate_type
442
+ >>> from sympy.abc import x, y
443
+ >>> eq = (x**2 - 3).subs(x, x + y)
444
+ >>> bivariate_type(eq, x, y)
445
+ (x + y, _u**2 - 3, _u)
446
+ >>> uxy, pu, u = _
447
+ >>> usol = solve(pu, u); usol
448
+ [sqrt(3)]
449
+ >>> [solve(uxy - s) for s in solve(pu, u)]
450
+ [[{x: -y + sqrt(3)}]]
451
+ >>> all(eq.subs(s).equals(0) for sol in _ for s in sol)
452
+ True
453
+
454
+ """
455
+
456
+ u = Dummy('u', positive=True)
457
+
458
+ if first:
459
+ p = Poly(f, x, y)
460
+ f = p.as_expr()
461
+ _x = Dummy()
462
+ _y = Dummy()
463
+ rv = bivariate_type(Poly(f.subs({x: _x, y: _y}), _x, _y), _x, _y, first=False)
464
+ if rv:
465
+ reps = {_x: x, _y: y}
466
+ return rv[0].xreplace(reps), rv[1].xreplace(reps), rv[2]
467
+ return
468
+
469
+ p = f
470
+ f = p.as_expr()
471
+
472
+ # f(x*y)
473
+ args = Add.make_args(p.as_expr())
474
+ new = []
475
+ for a in args:
476
+ a = _mexpand(a.subs(x, u/y))
477
+ free = a.free_symbols
478
+ if x in free or y in free:
479
+ break
480
+ new.append(a)
481
+ else:
482
+ return x*y, Add(*new), u
483
+
484
+ def ok(f, v, c):
485
+ new = _mexpand(f.subs(v, c))
486
+ free = new.free_symbols
487
+ return None if (x in free or y in free) else new
488
+
489
+ # f(a*x + b*y)
490
+ new = []
491
+ d = p.degree(x)
492
+ if p.degree(y) == d:
493
+ a = root(p.coeff_monomial(x**d), d)
494
+ b = root(p.coeff_monomial(y**d), d)
495
+ new = ok(f, x, (u - b*y)/a)
496
+ if new is not None:
497
+ return a*x + b*y, new, u
498
+
499
+ # f(a*x*y + b*y)
500
+ new = []
501
+ d = p.degree(x)
502
+ if p.degree(y) == d:
503
+ for itry in range(2):
504
+ a = root(p.coeff_monomial(x**d*y**d), d)
505
+ b = root(p.coeff_monomial(y**d), d)
506
+ new = ok(f, x, (u - b*y)/a/y)
507
+ if new is not None:
508
+ return a*x*y + b*y, new, u
509
+ x, y = y, x
llmeval-env/lib/python3.10/site-packages/sympy/solvers/decompogen.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import (Function, Pow, sympify, Expr)
2
+ from sympy.core.relational import Relational
3
+ from sympy.core.singleton import S
4
+ from sympy.polys import Poly, decompose
5
+ from sympy.utilities.misc import func_name
6
+ from sympy.functions.elementary.miscellaneous import Min, Max
7
+
8
+
9
+ def decompogen(f, symbol):
10
+ """
11
+ Computes General functional decomposition of ``f``.
12
+ Given an expression ``f``, returns a list ``[f_1, f_2, ..., f_n]``,
13
+ where::
14
+ f = f_1 o f_2 o ... f_n = f_1(f_2(... f_n))
15
+
16
+ Note: This is a General decomposition function. It also decomposes
17
+ Polynomials. For only Polynomial decomposition see ``decompose`` in polys.
18
+
19
+ Examples
20
+ ========
21
+
22
+ >>> from sympy.abc import x
23
+ >>> from sympy import decompogen, sqrt, sin, cos
24
+ >>> decompogen(sin(cos(x)), x)
25
+ [sin(x), cos(x)]
26
+ >>> decompogen(sin(x)**2 + sin(x) + 1, x)
27
+ [x**2 + x + 1, sin(x)]
28
+ >>> decompogen(sqrt(6*x**2 - 5), x)
29
+ [sqrt(x), 6*x**2 - 5]
30
+ >>> decompogen(sin(sqrt(cos(x**2 + 1))), x)
31
+ [sin(x), sqrt(x), cos(x), x**2 + 1]
32
+ >>> decompogen(x**4 + 2*x**3 - x - 1, x)
33
+ [x**2 - x - 1, x**2 + x]
34
+
35
+ """
36
+ f = sympify(f)
37
+ if not isinstance(f, Expr) or isinstance(f, Relational):
38
+ raise TypeError('expecting Expr but got: `%s`' % func_name(f))
39
+ if symbol not in f.free_symbols:
40
+ return [f]
41
+
42
+
43
+ # ===== Simple Functions ===== #
44
+ if isinstance(f, (Function, Pow)):
45
+ if f.is_Pow and f.base == S.Exp1:
46
+ arg = f.exp
47
+ else:
48
+ arg = f.args[0]
49
+ if arg == symbol:
50
+ return [f]
51
+ return [f.subs(arg, symbol)] + decompogen(arg, symbol)
52
+
53
+ # ===== Min/Max Functions ===== #
54
+ if isinstance(f, (Min, Max)):
55
+ args = list(f.args)
56
+ d0 = None
57
+ for i, a in enumerate(args):
58
+ if not a.has_free(symbol):
59
+ continue
60
+ d = decompogen(a, symbol)
61
+ if len(d) == 1:
62
+ d = [symbol] + d
63
+ if d0 is None:
64
+ d0 = d[1:]
65
+ elif d[1:] != d0:
66
+ # decomposition is not the same for each arg:
67
+ # mark as having no decomposition
68
+ d = [symbol]
69
+ break
70
+ args[i] = d[0]
71
+ if d[0] == symbol:
72
+ return [f]
73
+ return [f.func(*args)] + d0
74
+
75
+ # ===== Convert to Polynomial ===== #
76
+ fp = Poly(f)
77
+ gens = list(filter(lambda x: symbol in x.free_symbols, fp.gens))
78
+
79
+ if len(gens) == 1 and gens[0] != symbol:
80
+ f1 = f.subs(gens[0], symbol)
81
+ f2 = gens[0]
82
+ return [f1] + decompogen(f2, symbol)
83
+
84
+ # ===== Polynomial decompose() ====== #
85
+ try:
86
+ return decompose(f)
87
+ except ValueError:
88
+ return [f]
89
+
90
+
91
+ def compogen(g_s, symbol):
92
+ """
93
+ Returns the composition of functions.
94
+ Given a list of functions ``g_s``, returns their composition ``f``,
95
+ where:
96
+ f = g_1 o g_2 o .. o g_n
97
+
98
+ Note: This is a General composition function. It also composes Polynomials.
99
+ For only Polynomial composition see ``compose`` in polys.
100
+
101
+ Examples
102
+ ========
103
+
104
+ >>> from sympy.solvers.decompogen import compogen
105
+ >>> from sympy.abc import x
106
+ >>> from sympy import sqrt, sin, cos
107
+ >>> compogen([sin(x), cos(x)], x)
108
+ sin(cos(x))
109
+ >>> compogen([x**2 + x + 1, sin(x)], x)
110
+ sin(x)**2 + sin(x) + 1
111
+ >>> compogen([sqrt(x), 6*x**2 - 5], x)
112
+ sqrt(6*x**2 - 5)
113
+ >>> compogen([sin(x), sqrt(x), cos(x), x**2 + 1], x)
114
+ sin(sqrt(cos(x**2 + 1)))
115
+ >>> compogen([x**2 - x - 1, x**2 + x], x)
116
+ -x**2 - x + (x**2 + x)**2 - 1
117
+ """
118
+ if len(g_s) == 1:
119
+ return g_s[0]
120
+
121
+ foo = g_s[0].subs(symbol, g_s[1])
122
+
123
+ if len(g_s) == 2:
124
+ return foo
125
+
126
+ return compogen([foo] + g_s[2:], symbol)
llmeval-env/lib/python3.10/site-packages/sympy/solvers/deutils.py ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Utility functions for classifying and solving
2
+ ordinary and partial differential equations.
3
+
4
+ Contains
5
+ ========
6
+ _preprocess
7
+ ode_order
8
+ _desolve
9
+
10
+ """
11
+ from sympy.core import Pow
12
+ from sympy.core.function import Derivative, AppliedUndef
13
+ from sympy.core.relational import Equality
14
+ from sympy.core.symbol import Wild
15
+
16
+ def _preprocess(expr, func=None, hint='_Integral'):
17
+ """Prepare expr for solving by making sure that differentiation
18
+ is done so that only func remains in unevaluated derivatives and
19
+ (if hint does not end with _Integral) that doit is applied to all
20
+ other derivatives. If hint is None, do not do any differentiation.
21
+ (Currently this may cause some simple differential equations to
22
+ fail.)
23
+
24
+ In case func is None, an attempt will be made to autodetect the
25
+ function to be solved for.
26
+
27
+ >>> from sympy.solvers.deutils import _preprocess
28
+ >>> from sympy import Derivative, Function
29
+ >>> from sympy.abc import x, y, z
30
+ >>> f, g = map(Function, 'fg')
31
+
32
+ If f(x)**p == 0 and p>0 then we can solve for f(x)=0
33
+ >>> _preprocess((f(x).diff(x)-4)**5, f(x))
34
+ (Derivative(f(x), x) - 4, f(x))
35
+
36
+ Apply doit to derivatives that contain more than the function
37
+ of interest:
38
+
39
+ >>> _preprocess(Derivative(f(x) + x, x))
40
+ (Derivative(f(x), x) + 1, f(x))
41
+
42
+ Do others if the differentiation variable(s) intersect with those
43
+ of the function of interest or contain the function of interest:
44
+
45
+ >>> _preprocess(Derivative(g(x), y, z), f(y))
46
+ (0, f(y))
47
+ >>> _preprocess(Derivative(f(y), z), f(y))
48
+ (0, f(y))
49
+
50
+ Do others if the hint does not end in '_Integral' (the default
51
+ assumes that it does):
52
+
53
+ >>> _preprocess(Derivative(g(x), y), f(x))
54
+ (Derivative(g(x), y), f(x))
55
+ >>> _preprocess(Derivative(f(x), y), f(x), hint='')
56
+ (0, f(x))
57
+
58
+ Do not do any derivatives if hint is None:
59
+
60
+ >>> eq = Derivative(f(x) + 1, x) + Derivative(f(x), y)
61
+ >>> _preprocess(eq, f(x), hint=None)
62
+ (Derivative(f(x) + 1, x) + Derivative(f(x), y), f(x))
63
+
64
+ If it's not clear what the function of interest is, it must be given:
65
+
66
+ >>> eq = Derivative(f(x) + g(x), x)
67
+ >>> _preprocess(eq, g(x))
68
+ (Derivative(f(x), x) + Derivative(g(x), x), g(x))
69
+ >>> try: _preprocess(eq)
70
+ ... except ValueError: print("A ValueError was raised.")
71
+ A ValueError was raised.
72
+
73
+ """
74
+ if isinstance(expr, Pow):
75
+ # if f(x)**p=0 then f(x)=0 (p>0)
76
+ if (expr.exp).is_positive:
77
+ expr = expr.base
78
+ derivs = expr.atoms(Derivative)
79
+ if not func:
80
+ funcs = set().union(*[d.atoms(AppliedUndef) for d in derivs])
81
+ if len(funcs) != 1:
82
+ raise ValueError('The function cannot be '
83
+ 'automatically detected for %s.' % expr)
84
+ func = funcs.pop()
85
+ fvars = set(func.args)
86
+ if hint is None:
87
+ return expr, func
88
+ reps = [(d, d.doit()) for d in derivs if not hint.endswith('_Integral') or
89
+ d.has(func) or set(d.variables) & fvars]
90
+ eq = expr.subs(reps)
91
+ return eq, func
92
+
93
+
94
+ def ode_order(expr, func):
95
+ """
96
+ Returns the order of a given differential
97
+ equation with respect to func.
98
+
99
+ This function is implemented recursively.
100
+
101
+ Examples
102
+ ========
103
+
104
+ >>> from sympy import Function
105
+ >>> from sympy.solvers.deutils import ode_order
106
+ >>> from sympy.abc import x
107
+ >>> f, g = map(Function, ['f', 'g'])
108
+ >>> ode_order(f(x).diff(x, 2) + f(x).diff(x)**2 +
109
+ ... f(x).diff(x), f(x))
110
+ 2
111
+ >>> ode_order(f(x).diff(x, 2) + g(x).diff(x, 3), f(x))
112
+ 2
113
+ >>> ode_order(f(x).diff(x, 2) + g(x).diff(x, 3), g(x))
114
+ 3
115
+
116
+ """
117
+ a = Wild('a', exclude=[func])
118
+ if expr.match(a):
119
+ return 0
120
+
121
+ if isinstance(expr, Derivative):
122
+ if expr.args[0] == func:
123
+ return len(expr.variables)
124
+ else:
125
+ args = expr.args[0].args
126
+ rv = len(expr.variables)
127
+ if args:
128
+ rv += max(ode_order(_, func) for _ in args)
129
+ return rv
130
+ else:
131
+ return max(ode_order(_, func) for _ in expr.args) if expr.args else 0
132
+
133
+
134
+ def _desolve(eq, func=None, hint="default", ics=None, simplify=True, *, prep=True, **kwargs):
135
+ """This is a helper function to dsolve and pdsolve in the ode
136
+ and pde modules.
137
+
138
+ If the hint provided to the function is "default", then a dict with
139
+ the following keys are returned
140
+
141
+ 'func' - It provides the function for which the differential equation
142
+ has to be solved. This is useful when the expression has
143
+ more than one function in it.
144
+
145
+ 'default' - The default key as returned by classifier functions in ode
146
+ and pde.py
147
+
148
+ 'hint' - The hint given by the user for which the differential equation
149
+ is to be solved. If the hint given by the user is 'default',
150
+ then the value of 'hint' and 'default' is the same.
151
+
152
+ 'order' - The order of the function as returned by ode_order
153
+
154
+ 'match' - It returns the match as given by the classifier functions, for
155
+ the default hint.
156
+
157
+ If the hint provided to the function is not "default" and is not in
158
+ ('all', 'all_Integral', 'best'), then a dict with the above mentioned keys
159
+ is returned along with the keys which are returned when dict in
160
+ classify_ode or classify_pde is set True
161
+
162
+ If the hint given is in ('all', 'all_Integral', 'best'), then this function
163
+ returns a nested dict, with the keys, being the set of classified hints
164
+ returned by classifier functions, and the values being the dict of form
165
+ as mentioned above.
166
+
167
+ Key 'eq' is a common key to all the above mentioned hints which returns an
168
+ expression if eq given by user is an Equality.
169
+
170
+ See Also
171
+ ========
172
+ classify_ode(ode.py)
173
+ classify_pde(pde.py)
174
+ """
175
+ if isinstance(eq, Equality):
176
+ eq = eq.lhs - eq.rhs
177
+
178
+ # preprocess the equation and find func if not given
179
+ if prep or func is None:
180
+ eq, func = _preprocess(eq, func)
181
+ prep = False
182
+
183
+ # type is an argument passed by the solve functions in ode and pde.py
184
+ # that identifies whether the function caller is an ordinary
185
+ # or partial differential equation. Accordingly corresponding
186
+ # changes are made in the function.
187
+ type = kwargs.get('type', None)
188
+ xi = kwargs.get('xi')
189
+ eta = kwargs.get('eta')
190
+ x0 = kwargs.get('x0', 0)
191
+ terms = kwargs.get('n')
192
+
193
+ if type == 'ode':
194
+ from sympy.solvers.ode import classify_ode, allhints
195
+ classifier = classify_ode
196
+ string = 'ODE '
197
+ dummy = ''
198
+
199
+ elif type == 'pde':
200
+ from sympy.solvers.pde import classify_pde, allhints
201
+ classifier = classify_pde
202
+ string = 'PDE '
203
+ dummy = 'p'
204
+
205
+ # Magic that should only be used internally. Prevents classify_ode from
206
+ # being called more than it needs to be by passing its results through
207
+ # recursive calls.
208
+ if kwargs.get('classify', True):
209
+ hints = classifier(eq, func, dict=True, ics=ics, xi=xi, eta=eta,
210
+ n=terms, x0=x0, hint=hint, prep=prep)
211
+
212
+ else:
213
+ # Here is what all this means:
214
+ #
215
+ # hint: The hint method given to _desolve() by the user.
216
+ # hints: The dictionary of hints that match the DE, along with other
217
+ # information (including the internal pass-through magic).
218
+ # default: The default hint to return, the first hint from allhints
219
+ # that matches the hint; obtained from classify_ode().
220
+ # match: Dictionary containing the match dictionary for each hint
221
+ # (the parts of the DE for solving). When going through the
222
+ # hints in "all", this holds the match string for the current
223
+ # hint.
224
+ # order: The order of the DE, as determined by ode_order().
225
+ hints = kwargs.get('hint',
226
+ {'default': hint,
227
+ hint: kwargs['match'],
228
+ 'order': kwargs['order']})
229
+ if not hints['default']:
230
+ # classify_ode will set hints['default'] to None if no hints match.
231
+ if hint not in allhints and hint != 'default':
232
+ raise ValueError("Hint not recognized: " + hint)
233
+ elif hint not in hints['ordered_hints'] and hint != 'default':
234
+ raise ValueError(string + str(eq) + " does not match hint " + hint)
235
+ # If dsolve can't solve the purely algebraic equation then dsolve will raise
236
+ # ValueError
237
+ elif hints['order'] == 0:
238
+ raise ValueError(
239
+ str(eq) + " is not a solvable differential equation in " + str(func))
240
+ else:
241
+ raise NotImplementedError(dummy + "solve" + ": Cannot solve " + str(eq))
242
+ if hint == 'default':
243
+ return _desolve(eq, func, ics=ics, hint=hints['default'], simplify=simplify,
244
+ prep=prep, x0=x0, classify=False, order=hints['order'],
245
+ match=hints[hints['default']], xi=xi, eta=eta, n=terms, type=type)
246
+ elif hint in ('all', 'all_Integral', 'best'):
247
+ retdict = {}
248
+ gethints = set(hints) - {'order', 'default', 'ordered_hints'}
249
+ if hint == 'all_Integral':
250
+ for i in hints:
251
+ if i.endswith('_Integral'):
252
+ gethints.remove(i[:-len('_Integral')])
253
+ # special cases
254
+ for k in ["1st_homogeneous_coeff_best", "1st_power_series",
255
+ "lie_group", "2nd_power_series_ordinary", "2nd_power_series_regular"]:
256
+ if k in gethints:
257
+ gethints.remove(k)
258
+ for i in gethints:
259
+ sol = _desolve(eq, func, ics=ics, hint=i, x0=x0, simplify=simplify, prep=prep,
260
+ classify=False, n=terms, order=hints['order'], match=hints[i], type=type)
261
+ retdict[i] = sol
262
+ retdict['all'] = True
263
+ retdict['eq'] = eq
264
+ return retdict
265
+ elif hint not in allhints: # and hint not in ('default', 'ordered_hints'):
266
+ raise ValueError("Hint not recognized: " + hint)
267
+ elif hint not in hints:
268
+ raise ValueError(string + str(eq) + " does not match hint " + hint)
269
+ else:
270
+ # Key added to identify the hint needed to solve the equation
271
+ hints['hint'] = hint
272
+ hints.update({'func': func, 'eq': eq})
273
+ return hints
llmeval-env/lib/python3.10/site-packages/sympy/solvers/inequalities.py ADDED
@@ -0,0 +1,984 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tools for solving inequalities and systems of inequalities. """
2
+ import itertools
3
+
4
+ from sympy.calculus.util import (continuous_domain, periodicity,
5
+ function_range)
6
+ from sympy.core import Symbol, Dummy, sympify
7
+ from sympy.core.exprtools import factor_terms
8
+ from sympy.core.relational import Relational, Eq, Ge, Lt
9
+ from sympy.sets.sets import Interval, FiniteSet, Union, Intersection
10
+ from sympy.core.singleton import S
11
+ from sympy.core.function import expand_mul
12
+ from sympy.functions.elementary.complexes import im, Abs
13
+ from sympy.logic import And
14
+ from sympy.polys import Poly, PolynomialError, parallel_poly_from_expr
15
+ from sympy.polys.polyutils import _nsort
16
+ from sympy.solvers.solveset import solvify, solveset
17
+ from sympy.utilities.iterables import sift, iterable
18
+ from sympy.utilities.misc import filldedent
19
+
20
+
21
+ def solve_poly_inequality(poly, rel):
22
+ """Solve a polynomial inequality with rational coefficients.
23
+
24
+ Examples
25
+ ========
26
+
27
+ >>> from sympy import solve_poly_inequality, Poly
28
+ >>> from sympy.abc import x
29
+
30
+ >>> solve_poly_inequality(Poly(x, x, domain='ZZ'), '==')
31
+ [{0}]
32
+
33
+ >>> solve_poly_inequality(Poly(x**2 - 1, x, domain='ZZ'), '!=')
34
+ [Interval.open(-oo, -1), Interval.open(-1, 1), Interval.open(1, oo)]
35
+
36
+ >>> solve_poly_inequality(Poly(x**2 - 1, x, domain='ZZ'), '==')
37
+ [{-1}, {1}]
38
+
39
+ See Also
40
+ ========
41
+ solve_poly_inequalities
42
+ """
43
+ if not isinstance(poly, Poly):
44
+ raise ValueError(
45
+ 'For efficiency reasons, `poly` should be a Poly instance')
46
+ if poly.as_expr().is_number:
47
+ t = Relational(poly.as_expr(), 0, rel)
48
+ if t is S.true:
49
+ return [S.Reals]
50
+ elif t is S.false:
51
+ return [S.EmptySet]
52
+ else:
53
+ raise NotImplementedError(
54
+ "could not determine truth value of %s" % t)
55
+
56
+ reals, intervals = poly.real_roots(multiple=False), []
57
+
58
+ if rel == '==':
59
+ for root, _ in reals:
60
+ interval = Interval(root, root)
61
+ intervals.append(interval)
62
+ elif rel == '!=':
63
+ left = S.NegativeInfinity
64
+
65
+ for right, _ in reals + [(S.Infinity, 1)]:
66
+ interval = Interval(left, right, True, True)
67
+ intervals.append(interval)
68
+ left = right
69
+ else:
70
+ if poly.LC() > 0:
71
+ sign = +1
72
+ else:
73
+ sign = -1
74
+
75
+ eq_sign, equal = None, False
76
+
77
+ if rel == '>':
78
+ eq_sign = +1
79
+ elif rel == '<':
80
+ eq_sign = -1
81
+ elif rel == '>=':
82
+ eq_sign, equal = +1, True
83
+ elif rel == '<=':
84
+ eq_sign, equal = -1, True
85
+ else:
86
+ raise ValueError("'%s' is not a valid relation" % rel)
87
+
88
+ right, right_open = S.Infinity, True
89
+
90
+ for left, multiplicity in reversed(reals):
91
+ if multiplicity % 2:
92
+ if sign == eq_sign:
93
+ intervals.insert(
94
+ 0, Interval(left, right, not equal, right_open))
95
+
96
+ sign, right, right_open = -sign, left, not equal
97
+ else:
98
+ if sign == eq_sign and not equal:
99
+ intervals.insert(
100
+ 0, Interval(left, right, True, right_open))
101
+ right, right_open = left, True
102
+ elif sign != eq_sign and equal:
103
+ intervals.insert(0, Interval(left, left))
104
+
105
+ if sign == eq_sign:
106
+ intervals.insert(
107
+ 0, Interval(S.NegativeInfinity, right, True, right_open))
108
+
109
+ return intervals
110
+
111
+
112
+ def solve_poly_inequalities(polys):
113
+ """Solve polynomial inequalities with rational coefficients.
114
+
115
+ Examples
116
+ ========
117
+
118
+ >>> from sympy import Poly
119
+ >>> from sympy.solvers.inequalities import solve_poly_inequalities
120
+ >>> from sympy.abc import x
121
+ >>> solve_poly_inequalities(((
122
+ ... Poly(x**2 - 3), ">"), (
123
+ ... Poly(-x**2 + 1), ">")))
124
+ Union(Interval.open(-oo, -sqrt(3)), Interval.open(-1, 1), Interval.open(sqrt(3), oo))
125
+ """
126
+ return Union(*[s for p in polys for s in solve_poly_inequality(*p)])
127
+
128
+
129
+ def solve_rational_inequalities(eqs):
130
+ """Solve a system of rational inequalities with rational coefficients.
131
+
132
+ Examples
133
+ ========
134
+
135
+ >>> from sympy.abc import x
136
+ >>> from sympy import solve_rational_inequalities, Poly
137
+
138
+ >>> solve_rational_inequalities([[
139
+ ... ((Poly(-x + 1), Poly(1, x)), '>='),
140
+ ... ((Poly(-x + 1), Poly(1, x)), '<=')]])
141
+ {1}
142
+
143
+ >>> solve_rational_inequalities([[
144
+ ... ((Poly(x), Poly(1, x)), '!='),
145
+ ... ((Poly(-x + 1), Poly(1, x)), '>=')]])
146
+ Union(Interval.open(-oo, 0), Interval.Lopen(0, 1))
147
+
148
+ See Also
149
+ ========
150
+ solve_poly_inequality
151
+ """
152
+ result = S.EmptySet
153
+
154
+ for _eqs in eqs:
155
+ if not _eqs:
156
+ continue
157
+
158
+ global_intervals = [Interval(S.NegativeInfinity, S.Infinity)]
159
+
160
+ for (numer, denom), rel in _eqs:
161
+ numer_intervals = solve_poly_inequality(numer*denom, rel)
162
+ denom_intervals = solve_poly_inequality(denom, '==')
163
+
164
+ intervals = []
165
+
166
+ for numer_interval, global_interval in itertools.product(
167
+ numer_intervals, global_intervals):
168
+ interval = numer_interval.intersect(global_interval)
169
+
170
+ if interval is not S.EmptySet:
171
+ intervals.append(interval)
172
+
173
+ global_intervals = intervals
174
+
175
+ intervals = []
176
+
177
+ for global_interval in global_intervals:
178
+ for denom_interval in denom_intervals:
179
+ global_interval -= denom_interval
180
+
181
+ if global_interval is not S.EmptySet:
182
+ intervals.append(global_interval)
183
+
184
+ global_intervals = intervals
185
+
186
+ if not global_intervals:
187
+ break
188
+
189
+ for interval in global_intervals:
190
+ result = result.union(interval)
191
+
192
+ return result
193
+
194
+
195
+ def reduce_rational_inequalities(exprs, gen, relational=True):
196
+ """Reduce a system of rational inequalities with rational coefficients.
197
+
198
+ Examples
199
+ ========
200
+
201
+ >>> from sympy import Symbol
202
+ >>> from sympy.solvers.inequalities import reduce_rational_inequalities
203
+
204
+ >>> x = Symbol('x', real=True)
205
+
206
+ >>> reduce_rational_inequalities([[x**2 <= 0]], x)
207
+ Eq(x, 0)
208
+
209
+ >>> reduce_rational_inequalities([[x + 2 > 0]], x)
210
+ -2 < x
211
+ >>> reduce_rational_inequalities([[(x + 2, ">")]], x)
212
+ -2 < x
213
+ >>> reduce_rational_inequalities([[x + 2]], x)
214
+ Eq(x, -2)
215
+
216
+ This function find the non-infinite solution set so if the unknown symbol
217
+ is declared as extended real rather than real then the result may include
218
+ finiteness conditions:
219
+
220
+ >>> y = Symbol('y', extended_real=True)
221
+ >>> reduce_rational_inequalities([[y + 2 > 0]], y)
222
+ (-2 < y) & (y < oo)
223
+ """
224
+ exact = True
225
+ eqs = []
226
+ solution = S.Reals if exprs else S.EmptySet
227
+ for _exprs in exprs:
228
+ _eqs = []
229
+
230
+ for expr in _exprs:
231
+ if isinstance(expr, tuple):
232
+ expr, rel = expr
233
+ else:
234
+ if expr.is_Relational:
235
+ expr, rel = expr.lhs - expr.rhs, expr.rel_op
236
+ else:
237
+ expr, rel = expr, '=='
238
+
239
+ if expr is S.true:
240
+ numer, denom, rel = S.Zero, S.One, '=='
241
+ elif expr is S.false:
242
+ numer, denom, rel = S.One, S.One, '=='
243
+ else:
244
+ numer, denom = expr.together().as_numer_denom()
245
+
246
+ try:
247
+ (numer, denom), opt = parallel_poly_from_expr(
248
+ (numer, denom), gen)
249
+ except PolynomialError:
250
+ raise PolynomialError(filldedent('''
251
+ only polynomials and rational functions are
252
+ supported in this context.
253
+ '''))
254
+
255
+ if not opt.domain.is_Exact:
256
+ numer, denom, exact = numer.to_exact(), denom.to_exact(), False
257
+
258
+ domain = opt.domain.get_exact()
259
+
260
+ if not (domain.is_ZZ or domain.is_QQ):
261
+ expr = numer/denom
262
+ expr = Relational(expr, 0, rel)
263
+ solution &= solve_univariate_inequality(expr, gen, relational=False)
264
+ else:
265
+ _eqs.append(((numer, denom), rel))
266
+
267
+ if _eqs:
268
+ eqs.append(_eqs)
269
+
270
+ if eqs:
271
+ solution &= solve_rational_inequalities(eqs)
272
+ exclude = solve_rational_inequalities([[((d, d.one), '==')
273
+ for i in eqs for ((n, d), _) in i if d.has(gen)]])
274
+ solution -= exclude
275
+
276
+ if not exact and solution:
277
+ solution = solution.evalf()
278
+
279
+ if relational:
280
+ solution = solution.as_relational(gen)
281
+
282
+ return solution
283
+
284
+
285
+ def reduce_abs_inequality(expr, rel, gen):
286
+ """Reduce an inequality with nested absolute values.
287
+
288
+ Examples
289
+ ========
290
+
291
+ >>> from sympy import reduce_abs_inequality, Abs, Symbol
292
+ >>> x = Symbol('x', real=True)
293
+
294
+ >>> reduce_abs_inequality(Abs(x - 5) - 3, '<', x)
295
+ (2 < x) & (x < 8)
296
+
297
+ >>> reduce_abs_inequality(Abs(x + 2)*3 - 13, '<', x)
298
+ (-19/3 < x) & (x < 7/3)
299
+
300
+ See Also
301
+ ========
302
+
303
+ reduce_abs_inequalities
304
+ """
305
+ if gen.is_extended_real is False:
306
+ raise TypeError(filldedent('''
307
+ Cannot solve inequalities with absolute values containing
308
+ non-real variables.
309
+ '''))
310
+
311
+ def _bottom_up_scan(expr):
312
+ exprs = []
313
+
314
+ if expr.is_Add or expr.is_Mul:
315
+ op = expr.func
316
+
317
+ for arg in expr.args:
318
+ _exprs = _bottom_up_scan(arg)
319
+
320
+ if not exprs:
321
+ exprs = _exprs
322
+ else:
323
+ exprs = [(op(expr, _expr), conds + _conds) for (expr, conds), (_expr, _conds) in
324
+ itertools.product(exprs, _exprs)]
325
+ elif expr.is_Pow:
326
+ n = expr.exp
327
+ if not n.is_Integer:
328
+ raise ValueError("Only Integer Powers are allowed on Abs.")
329
+
330
+ exprs.extend((expr**n, conds) for expr, conds in _bottom_up_scan(expr.base))
331
+ elif isinstance(expr, Abs):
332
+ _exprs = _bottom_up_scan(expr.args[0])
333
+
334
+ for expr, conds in _exprs:
335
+ exprs.append(( expr, conds + [Ge(expr, 0)]))
336
+ exprs.append((-expr, conds + [Lt(expr, 0)]))
337
+ else:
338
+ exprs = [(expr, [])]
339
+
340
+ return exprs
341
+
342
+ mapping = {'<': '>', '<=': '>='}
343
+ inequalities = []
344
+
345
+ for expr, conds in _bottom_up_scan(expr):
346
+ if rel not in mapping.keys():
347
+ expr = Relational( expr, 0, rel)
348
+ else:
349
+ expr = Relational(-expr, 0, mapping[rel])
350
+
351
+ inequalities.append([expr] + conds)
352
+
353
+ return reduce_rational_inequalities(inequalities, gen)
354
+
355
+
356
+ def reduce_abs_inequalities(exprs, gen):
357
+ """Reduce a system of inequalities with nested absolute values.
358
+
359
+ Examples
360
+ ========
361
+
362
+ >>> from sympy import reduce_abs_inequalities, Abs, Symbol
363
+ >>> x = Symbol('x', extended_real=True)
364
+
365
+ >>> reduce_abs_inequalities([(Abs(3*x - 5) - 7, '<'),
366
+ ... (Abs(x + 25) - 13, '>')], x)
367
+ (-2/3 < x) & (x < 4) & (((-oo < x) & (x < -38)) | ((-12 < x) & (x < oo)))
368
+
369
+ >>> reduce_abs_inequalities([(Abs(x - 4) + Abs(3*x - 5) - 7, '<')], x)
370
+ (1/2 < x) & (x < 4)
371
+
372
+ See Also
373
+ ========
374
+
375
+ reduce_abs_inequality
376
+ """
377
+ return And(*[ reduce_abs_inequality(expr, rel, gen)
378
+ for expr, rel in exprs ])
379
+
380
+
381
+ def solve_univariate_inequality(expr, gen, relational=True, domain=S.Reals, continuous=False):
382
+ """Solves a real univariate inequality.
383
+
384
+ Parameters
385
+ ==========
386
+
387
+ expr : Relational
388
+ The target inequality
389
+ gen : Symbol
390
+ The variable for which the inequality is solved
391
+ relational : bool
392
+ A Relational type output is expected or not
393
+ domain : Set
394
+ The domain over which the equation is solved
395
+ continuous: bool
396
+ True if expr is known to be continuous over the given domain
397
+ (and so continuous_domain() does not need to be called on it)
398
+
399
+ Raises
400
+ ======
401
+
402
+ NotImplementedError
403
+ The solution of the inequality cannot be determined due to limitation
404
+ in :func:`sympy.solvers.solveset.solvify`.
405
+
406
+ Notes
407
+ =====
408
+
409
+ Currently, we cannot solve all the inequalities due to limitations in
410
+ :func:`sympy.solvers.solveset.solvify`. Also, the solution returned for trigonometric inequalities
411
+ are restricted in its periodic interval.
412
+
413
+ See Also
414
+ ========
415
+
416
+ sympy.solvers.solveset.solvify: solver returning solveset solutions with solve's output API
417
+
418
+ Examples
419
+ ========
420
+
421
+ >>> from sympy import solve_univariate_inequality, Symbol, sin, Interval, S
422
+ >>> x = Symbol('x')
423
+
424
+ >>> solve_univariate_inequality(x**2 >= 4, x)
425
+ ((2 <= x) & (x < oo)) | ((-oo < x) & (x <= -2))
426
+
427
+ >>> solve_univariate_inequality(x**2 >= 4, x, relational=False)
428
+ Union(Interval(-oo, -2), Interval(2, oo))
429
+
430
+ >>> domain = Interval(0, S.Infinity)
431
+ >>> solve_univariate_inequality(x**2 >= 4, x, False, domain)
432
+ Interval(2, oo)
433
+
434
+ >>> solve_univariate_inequality(sin(x) > 0, x, relational=False)
435
+ Interval.open(0, pi)
436
+
437
+ """
438
+ from sympy.solvers.solvers import denoms
439
+
440
+ if domain.is_subset(S.Reals) is False:
441
+ raise NotImplementedError(filldedent('''
442
+ Inequalities in the complex domain are
443
+ not supported. Try the real domain by
444
+ setting domain=S.Reals'''))
445
+ elif domain is not S.Reals:
446
+ rv = solve_univariate_inequality(
447
+ expr, gen, relational=False, continuous=continuous).intersection(domain)
448
+ if relational:
449
+ rv = rv.as_relational(gen)
450
+ return rv
451
+ else:
452
+ pass # continue with attempt to solve in Real domain
453
+
454
+ # This keeps the function independent of the assumptions about `gen`.
455
+ # `solveset` makes sure this function is called only when the domain is
456
+ # real.
457
+ _gen = gen
458
+ _domain = domain
459
+ if gen.is_extended_real is False:
460
+ rv = S.EmptySet
461
+ return rv if not relational else rv.as_relational(_gen)
462
+ elif gen.is_extended_real is None:
463
+ gen = Dummy('gen', extended_real=True)
464
+ try:
465
+ expr = expr.xreplace({_gen: gen})
466
+ except TypeError:
467
+ raise TypeError(filldedent('''
468
+ When gen is real, the relational has a complex part
469
+ which leads to an invalid comparison like I < 0.
470
+ '''))
471
+
472
+ rv = None
473
+
474
+ if expr is S.true:
475
+ rv = domain
476
+
477
+ elif expr is S.false:
478
+ rv = S.EmptySet
479
+
480
+ else:
481
+ e = expr.lhs - expr.rhs
482
+ period = periodicity(e, gen)
483
+ if period == S.Zero:
484
+ e = expand_mul(e)
485
+ const = expr.func(e, 0)
486
+ if const is S.true:
487
+ rv = domain
488
+ elif const is S.false:
489
+ rv = S.EmptySet
490
+ elif period is not None:
491
+ frange = function_range(e, gen, domain)
492
+
493
+ rel = expr.rel_op
494
+ if rel in ('<', '<='):
495
+ if expr.func(frange.sup, 0):
496
+ rv = domain
497
+ elif not expr.func(frange.inf, 0):
498
+ rv = S.EmptySet
499
+
500
+ elif rel in ('>', '>='):
501
+ if expr.func(frange.inf, 0):
502
+ rv = domain
503
+ elif not expr.func(frange.sup, 0):
504
+ rv = S.EmptySet
505
+
506
+ inf, sup = domain.inf, domain.sup
507
+ if sup - inf is S.Infinity:
508
+ domain = Interval(0, period, False, True).intersect(_domain)
509
+ _domain = domain
510
+
511
+ if rv is None:
512
+ n, d = e.as_numer_denom()
513
+ try:
514
+ if gen not in n.free_symbols and len(e.free_symbols) > 1:
515
+ raise ValueError
516
+ # this might raise ValueError on its own
517
+ # or it might give None...
518
+ solns = solvify(e, gen, domain)
519
+ if solns is None:
520
+ # in which case we raise ValueError
521
+ raise ValueError
522
+ except (ValueError, NotImplementedError):
523
+ # replace gen with generic x since it's
524
+ # univariate anyway
525
+ raise NotImplementedError(filldedent('''
526
+ The inequality, %s, cannot be solved using
527
+ solve_univariate_inequality.
528
+ ''' % expr.subs(gen, Symbol('x'))))
529
+
530
+ expanded_e = expand_mul(e)
531
+ def valid(x):
532
+ # this is used to see if gen=x satisfies the
533
+ # relational by substituting it into the
534
+ # expanded form and testing against 0, e.g.
535
+ # if expr = x*(x + 1) < 2 then e = x*(x + 1) - 2
536
+ # and expanded_e = x**2 + x - 2; the test is
537
+ # whether a given value of x satisfies
538
+ # x**2 + x - 2 < 0
539
+ #
540
+ # expanded_e, expr and gen used from enclosing scope
541
+ v = expanded_e.subs(gen, expand_mul(x))
542
+ try:
543
+ r = expr.func(v, 0)
544
+ except TypeError:
545
+ r = S.false
546
+ if r in (S.true, S.false):
547
+ return r
548
+ if v.is_extended_real is False:
549
+ return S.false
550
+ else:
551
+ v = v.n(2)
552
+ if v.is_comparable:
553
+ return expr.func(v, 0)
554
+ # not comparable or couldn't be evaluated
555
+ raise NotImplementedError(
556
+ 'relationship did not evaluate: %s' % r)
557
+
558
+ singularities = []
559
+ for d in denoms(expr, gen):
560
+ singularities.extend(solvify(d, gen, domain))
561
+ if not continuous:
562
+ domain = continuous_domain(expanded_e, gen, domain)
563
+
564
+ include_x = '=' in expr.rel_op and expr.rel_op != '!='
565
+
566
+ try:
567
+ discontinuities = set(domain.boundary -
568
+ FiniteSet(domain.inf, domain.sup))
569
+ # remove points that are not between inf and sup of domain
570
+ critical_points = FiniteSet(*(solns + singularities + list(
571
+ discontinuities))).intersection(
572
+ Interval(domain.inf, domain.sup,
573
+ domain.inf not in domain, domain.sup not in domain))
574
+ if all(r.is_number for r in critical_points):
575
+ reals = _nsort(critical_points, separated=True)[0]
576
+ else:
577
+ sifted = sift(critical_points, lambda x: x.is_extended_real)
578
+ if sifted[None]:
579
+ # there were some roots that weren't known
580
+ # to be real
581
+ raise NotImplementedError
582
+ try:
583
+ reals = sifted[True]
584
+ if len(reals) > 1:
585
+ reals = sorted(reals)
586
+ except TypeError:
587
+ raise NotImplementedError
588
+ except NotImplementedError:
589
+ raise NotImplementedError('sorting of these roots is not supported')
590
+
591
+ # If expr contains imaginary coefficients, only take real
592
+ # values of x for which the imaginary part is 0
593
+ make_real = S.Reals
594
+ if im(expanded_e) != S.Zero:
595
+ check = True
596
+ im_sol = FiniteSet()
597
+ try:
598
+ a = solveset(im(expanded_e), gen, domain)
599
+ if not isinstance(a, Interval):
600
+ for z in a:
601
+ if z not in singularities and valid(z) and z.is_extended_real:
602
+ im_sol += FiniteSet(z)
603
+ else:
604
+ start, end = a.inf, a.sup
605
+ for z in _nsort(critical_points + FiniteSet(end)):
606
+ valid_start = valid(start)
607
+ if start != end:
608
+ valid_z = valid(z)
609
+ pt = _pt(start, z)
610
+ if pt not in singularities and pt.is_extended_real and valid(pt):
611
+ if valid_start and valid_z:
612
+ im_sol += Interval(start, z)
613
+ elif valid_start:
614
+ im_sol += Interval.Ropen(start, z)
615
+ elif valid_z:
616
+ im_sol += Interval.Lopen(start, z)
617
+ else:
618
+ im_sol += Interval.open(start, z)
619
+ start = z
620
+ for s in singularities:
621
+ im_sol -= FiniteSet(s)
622
+ except (TypeError):
623
+ im_sol = S.Reals
624
+ check = False
625
+
626
+ if im_sol is S.EmptySet:
627
+ raise ValueError(filldedent('''
628
+ %s contains imaginary parts which cannot be
629
+ made 0 for any value of %s satisfying the
630
+ inequality, leading to relations like I < 0.
631
+ ''' % (expr.subs(gen, _gen), _gen)))
632
+
633
+ make_real = make_real.intersect(im_sol)
634
+
635
+ sol_sets = [S.EmptySet]
636
+
637
+ start = domain.inf
638
+ if start in domain and valid(start) and start.is_finite:
639
+ sol_sets.append(FiniteSet(start))
640
+
641
+ for x in reals:
642
+ end = x
643
+
644
+ if valid(_pt(start, end)):
645
+ sol_sets.append(Interval(start, end, True, True))
646
+
647
+ if x in singularities:
648
+ singularities.remove(x)
649
+ else:
650
+ if x in discontinuities:
651
+ discontinuities.remove(x)
652
+ _valid = valid(x)
653
+ else: # it's a solution
654
+ _valid = include_x
655
+ if _valid:
656
+ sol_sets.append(FiniteSet(x))
657
+
658
+ start = end
659
+
660
+ end = domain.sup
661
+ if end in domain and valid(end) and end.is_finite:
662
+ sol_sets.append(FiniteSet(end))
663
+
664
+ if valid(_pt(start, end)):
665
+ sol_sets.append(Interval.open(start, end))
666
+
667
+ if im(expanded_e) != S.Zero and check:
668
+ rv = (make_real).intersect(_domain)
669
+ else:
670
+ rv = Intersection(
671
+ (Union(*sol_sets)), make_real, _domain).subs(gen, _gen)
672
+
673
+ return rv if not relational else rv.as_relational(_gen)
674
+
675
+
676
+ def _pt(start, end):
677
+ """Return a point between start and end"""
678
+ if not start.is_infinite and not end.is_infinite:
679
+ pt = (start + end)/2
680
+ elif start.is_infinite and end.is_infinite:
681
+ pt = S.Zero
682
+ else:
683
+ if (start.is_infinite and start.is_extended_positive is None or
684
+ end.is_infinite and end.is_extended_positive is None):
685
+ raise ValueError('cannot proceed with unsigned infinite values')
686
+ if (end.is_infinite and end.is_extended_negative or
687
+ start.is_infinite and start.is_extended_positive):
688
+ start, end = end, start
689
+ # if possible, use a multiple of self which has
690
+ # better behavior when checking assumptions than
691
+ # an expression obtained by adding or subtracting 1
692
+ if end.is_infinite:
693
+ if start.is_extended_positive:
694
+ pt = start*2
695
+ elif start.is_extended_negative:
696
+ pt = start*S.Half
697
+ else:
698
+ pt = start + 1
699
+ elif start.is_infinite:
700
+ if end.is_extended_positive:
701
+ pt = end*S.Half
702
+ elif end.is_extended_negative:
703
+ pt = end*2
704
+ else:
705
+ pt = end - 1
706
+ return pt
707
+
708
+
709
+ def _solve_inequality(ie, s, linear=False):
710
+ """Return the inequality with s isolated on the left, if possible.
711
+ If the relationship is non-linear, a solution involving And or Or
712
+ may be returned. False or True are returned if the relationship
713
+ is never True or always True, respectively.
714
+
715
+ If `linear` is True (default is False) an `s`-dependent expression
716
+ will be isolated on the left, if possible
717
+ but it will not be solved for `s` unless the expression is linear
718
+ in `s`. Furthermore, only "safe" operations which do not change the
719
+ sense of the relationship are applied: no division by an unsigned
720
+ value is attempted unless the relationship involves Eq or Ne and
721
+ no division by a value not known to be nonzero is ever attempted.
722
+
723
+ Examples
724
+ ========
725
+
726
+ >>> from sympy import Eq, Symbol
727
+ >>> from sympy.solvers.inequalities import _solve_inequality as f
728
+ >>> from sympy.abc import x, y
729
+
730
+ For linear expressions, the symbol can be isolated:
731
+
732
+ >>> f(x - 2 < 0, x)
733
+ x < 2
734
+ >>> f(-x - 6 < x, x)
735
+ x > -3
736
+
737
+ Sometimes nonlinear relationships will be False
738
+
739
+ >>> f(x**2 + 4 < 0, x)
740
+ False
741
+
742
+ Or they may involve more than one region of values:
743
+
744
+ >>> f(x**2 - 4 < 0, x)
745
+ (-2 < x) & (x < 2)
746
+
747
+ To restrict the solution to a relational, set linear=True
748
+ and only the x-dependent portion will be isolated on the left:
749
+
750
+ >>> f(x**2 - 4 < 0, x, linear=True)
751
+ x**2 < 4
752
+
753
+ Division of only nonzero quantities is allowed, so x cannot
754
+ be isolated by dividing by y:
755
+
756
+ >>> y.is_nonzero is None # it is unknown whether it is 0 or not
757
+ True
758
+ >>> f(x*y < 1, x)
759
+ x*y < 1
760
+
761
+ And while an equality (or inequality) still holds after dividing by a
762
+ non-zero quantity
763
+
764
+ >>> nz = Symbol('nz', nonzero=True)
765
+ >>> f(Eq(x*nz, 1), x)
766
+ Eq(x, 1/nz)
767
+
768
+ the sign must be known for other inequalities involving > or <:
769
+
770
+ >>> f(x*nz <= 1, x)
771
+ nz*x <= 1
772
+ >>> p = Symbol('p', positive=True)
773
+ >>> f(x*p <= 1, x)
774
+ x <= 1/p
775
+
776
+ When there are denominators in the original expression that
777
+ are removed by expansion, conditions for them will be returned
778
+ as part of the result:
779
+
780
+ >>> f(x < x*(2/x - 1), x)
781
+ (x < 1) & Ne(x, 0)
782
+ """
783
+ from sympy.solvers.solvers import denoms
784
+ if s not in ie.free_symbols:
785
+ return ie
786
+ if ie.rhs == s:
787
+ ie = ie.reversed
788
+ if ie.lhs == s and s not in ie.rhs.free_symbols:
789
+ return ie
790
+
791
+ def classify(ie, s, i):
792
+ # return True or False if ie evaluates when substituting s with
793
+ # i else None (if unevaluated) or NaN (when there is an error
794
+ # in evaluating)
795
+ try:
796
+ v = ie.subs(s, i)
797
+ if v is S.NaN:
798
+ return v
799
+ elif v not in (True, False):
800
+ return
801
+ return v
802
+ except TypeError:
803
+ return S.NaN
804
+
805
+ rv = None
806
+ oo = S.Infinity
807
+ expr = ie.lhs - ie.rhs
808
+ try:
809
+ p = Poly(expr, s)
810
+ if p.degree() == 0:
811
+ rv = ie.func(p.as_expr(), 0)
812
+ elif not linear and p.degree() > 1:
813
+ # handle in except clause
814
+ raise NotImplementedError
815
+ except (PolynomialError, NotImplementedError):
816
+ if not linear:
817
+ try:
818
+ rv = reduce_rational_inequalities([[ie]], s)
819
+ except PolynomialError:
820
+ rv = solve_univariate_inequality(ie, s)
821
+ # remove restrictions wrt +/-oo that may have been
822
+ # applied when using sets to simplify the relationship
823
+ okoo = classify(ie, s, oo)
824
+ if okoo is S.true and classify(rv, s, oo) is S.false:
825
+ rv = rv.subs(s < oo, True)
826
+ oknoo = classify(ie, s, -oo)
827
+ if (oknoo is S.true and
828
+ classify(rv, s, -oo) is S.false):
829
+ rv = rv.subs(-oo < s, True)
830
+ rv = rv.subs(s > -oo, True)
831
+ if rv is S.true:
832
+ rv = (s <= oo) if okoo is S.true else (s < oo)
833
+ if oknoo is not S.true:
834
+ rv = And(-oo < s, rv)
835
+ else:
836
+ p = Poly(expr)
837
+
838
+ conds = []
839
+ if rv is None:
840
+ e = p.as_expr() # this is in expanded form
841
+ # Do a safe inversion of e, moving non-s terms
842
+ # to the rhs and dividing by a nonzero factor if
843
+ # the relational is Eq/Ne; for other relationals
844
+ # the sign must also be positive or negative
845
+ rhs = 0
846
+ b, ax = e.as_independent(s, as_Add=True)
847
+ e -= b
848
+ rhs -= b
849
+ ef = factor_terms(e)
850
+ a, e = ef.as_independent(s, as_Add=False)
851
+ if (a.is_zero != False or # don't divide by potential 0
852
+ a.is_negative ==
853
+ a.is_positive is None and # if sign is not known then
854
+ ie.rel_op not in ('!=', '==')): # reject if not Eq/Ne
855
+ e = ef
856
+ a = S.One
857
+ rhs /= a
858
+ if a.is_positive:
859
+ rv = ie.func(e, rhs)
860
+ else:
861
+ rv = ie.reversed.func(e, rhs)
862
+
863
+ # return conditions under which the value is
864
+ # valid, too.
865
+ beginning_denoms = denoms(ie.lhs) | denoms(ie.rhs)
866
+ current_denoms = denoms(rv)
867
+ for d in beginning_denoms - current_denoms:
868
+ c = _solve_inequality(Eq(d, 0), s, linear=linear)
869
+ if isinstance(c, Eq) and c.lhs == s:
870
+ if classify(rv, s, c.rhs) is S.true:
871
+ # rv is permitting this value but it shouldn't
872
+ conds.append(~c)
873
+ for i in (-oo, oo):
874
+ if (classify(rv, s, i) is S.true and
875
+ classify(ie, s, i) is not S.true):
876
+ conds.append(s < i if i is oo else i < s)
877
+
878
+ conds.append(rv)
879
+ return And(*conds)
880
+
881
+
882
+ def _reduce_inequalities(inequalities, symbols):
883
+ # helper for reduce_inequalities
884
+
885
+ poly_part, abs_part = {}, {}
886
+ other = []
887
+
888
+ for inequality in inequalities:
889
+
890
+ expr, rel = inequality.lhs, inequality.rel_op # rhs is 0
891
+
892
+ # check for gens using atoms which is more strict than free_symbols to
893
+ # guard against EX domain which won't be handled by
894
+ # reduce_rational_inequalities
895
+ gens = expr.atoms(Symbol)
896
+
897
+ if len(gens) == 1:
898
+ gen = gens.pop()
899
+ else:
900
+ common = expr.free_symbols & symbols
901
+ if len(common) == 1:
902
+ gen = common.pop()
903
+ other.append(_solve_inequality(Relational(expr, 0, rel), gen))
904
+ continue
905
+ else:
906
+ raise NotImplementedError(filldedent('''
907
+ inequality has more than one symbol of interest.
908
+ '''))
909
+
910
+ if expr.is_polynomial(gen):
911
+ poly_part.setdefault(gen, []).append((expr, rel))
912
+ else:
913
+ components = expr.find(lambda u:
914
+ u.has(gen) and (
915
+ u.is_Function or u.is_Pow and not u.exp.is_Integer))
916
+ if components and all(isinstance(i, Abs) for i in components):
917
+ abs_part.setdefault(gen, []).append((expr, rel))
918
+ else:
919
+ other.append(_solve_inequality(Relational(expr, 0, rel), gen))
920
+
921
+ poly_reduced = [reduce_rational_inequalities([exprs], gen) for gen, exprs in poly_part.items()]
922
+ abs_reduced = [reduce_abs_inequalities(exprs, gen) for gen, exprs in abs_part.items()]
923
+
924
+ return And(*(poly_reduced + abs_reduced + other))
925
+
926
+
927
+ def reduce_inequalities(inequalities, symbols=[]):
928
+ """Reduce a system of inequalities with rational coefficients.
929
+
930
+ Examples
931
+ ========
932
+
933
+ >>> from sympy.abc import x, y
934
+ >>> from sympy import reduce_inequalities
935
+
936
+ >>> reduce_inequalities(0 <= x + 3, [])
937
+ (-3 <= x) & (x < oo)
938
+
939
+ >>> reduce_inequalities(0 <= x + y*2 - 1, [x])
940
+ (x < oo) & (x >= 1 - 2*y)
941
+ """
942
+ if not iterable(inequalities):
943
+ inequalities = [inequalities]
944
+ inequalities = [sympify(i) for i in inequalities]
945
+
946
+ gens = set().union(*[i.free_symbols for i in inequalities])
947
+
948
+ if not iterable(symbols):
949
+ symbols = [symbols]
950
+ symbols = (set(symbols) or gens) & gens
951
+ if any(i.is_extended_real is False for i in symbols):
952
+ raise TypeError(filldedent('''
953
+ inequalities cannot contain symbols that are not real.
954
+ '''))
955
+
956
+ # make vanilla symbol real
957
+ recast = {i: Dummy(i.name, extended_real=True)
958
+ for i in gens if i.is_extended_real is None}
959
+ inequalities = [i.xreplace(recast) for i in inequalities]
960
+ symbols = {i.xreplace(recast) for i in symbols}
961
+
962
+ # prefilter
963
+ keep = []
964
+ for i in inequalities:
965
+ if isinstance(i, Relational):
966
+ i = i.func(i.lhs.as_expr() - i.rhs.as_expr(), 0)
967
+ elif i not in (True, False):
968
+ i = Eq(i, 0)
969
+ if i == True:
970
+ continue
971
+ elif i == False:
972
+ return S.false
973
+ if i.lhs.is_number:
974
+ raise NotImplementedError(
975
+ "could not determine truth value of %s" % i)
976
+ keep.append(i)
977
+ inequalities = keep
978
+ del keep
979
+
980
+ # solve system
981
+ rv = _reduce_inequalities(inequalities, symbols)
982
+
983
+ # restore original symbols and return
984
+ return rv.xreplace({v: k for k, v in recast.items()})