ZTWHHH commited on
Commit
7601ef0
·
verified ·
1 Parent(s): 6feb4b7

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. .gitattributes +7 -0
  2. infer_4_37_2/lib/python3.10/site-packages/pandas/_libs/groupby.cpython-310-x86_64-linux-gnu.so +3 -0
  3. infer_4_37_2/lib/python3.10/site-packages/pandas/_libs/hashing.cpython-310-x86_64-linux-gnu.so +3 -0
  4. infer_4_37_2/lib/python3.10/site-packages/pandas/_libs/index.cpython-310-x86_64-linux-gnu.so +3 -0
  5. infer_4_37_2/lib/python3.10/site-packages/pandas/_libs/lib.cpython-310-x86_64-linux-gnu.so +3 -0
  6. infer_4_37_2/lib/python3.10/site-packages/pandas/_libs/missing.cpython-310-x86_64-linux-gnu.so +3 -0
  7. infer_4_37_2/lib/python3.10/site-packages/pandas/_libs/ops_dispatch.cpython-310-x86_64-linux-gnu.so +0 -0
  8. infer_4_37_2/lib/python3.10/site-packages/pandas/_libs/reshape.pyi +16 -0
  9. infer_4_37_2/lib/python3.10/site-packages/pandas/_libs/tslib.cpython-310-x86_64-linux-gnu.so +3 -0
  10. janus/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/__init__.cpython-310.pyc +0 -0
  11. janus/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/fp_groups.cpython-310.pyc +0 -0
  12. janus/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/galois.cpython-310.pyc +0 -0
  13. janus/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/graycode.cpython-310.pyc +0 -0
  14. janus/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/group_numbers.cpython-310.pyc +0 -0
  15. janus/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/partitions.cpython-310.pyc +0 -0
  16. janus/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/pc_groups.cpython-310.pyc +0 -0
  17. janus/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/permutations.cpython-310.pyc +0 -0
  18. janus/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/polyhedron.cpython-310.pyc +0 -0
  19. janus/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/rewritingsystem_fsm.cpython-310.pyc +0 -0
  20. janus/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/tensor_can.cpython-310.pyc +0 -0
  21. janus/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/testutil.cpython-310.pyc +0 -0
  22. janus/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/util.cpython-310.pyc +0 -0
  23. janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_coset_table.cpython-310.pyc +0 -0
  24. janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_group_numbers.cpython-310.pyc +0 -0
  25. janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_util.cpython-310.pyc +0 -0
  26. janus/lib/python3.10/site-packages/sympy/concrete/guess.py +473 -0
  27. janus/lib/python3.10/site-packages/sympy/geometry/__init__.py +45 -0
  28. janus/lib/python3.10/site-packages/sympy/geometry/__pycache__/curve.cpython-310.pyc +0 -0
  29. janus/lib/python3.10/site-packages/sympy/geometry/__pycache__/ellipse.cpython-310.pyc +0 -0
  30. janus/lib/python3.10/site-packages/sympy/geometry/__pycache__/line.cpython-310.pyc +0 -0
  31. janus/lib/python3.10/site-packages/sympy/geometry/__pycache__/parabola.cpython-310.pyc +0 -0
  32. janus/lib/python3.10/site-packages/sympy/geometry/__pycache__/plane.cpython-310.pyc +0 -0
  33. janus/lib/python3.10/site-packages/sympy/geometry/curve.py +424 -0
  34. janus/lib/python3.10/site-packages/sympy/geometry/ellipse.py +1767 -0
  35. janus/lib/python3.10/site-packages/sympy/geometry/entity.py +641 -0
  36. janus/lib/python3.10/site-packages/sympy/geometry/exceptions.py +5 -0
  37. janus/lib/python3.10/site-packages/sympy/geometry/line.py +2877 -0
  38. janus/lib/python3.10/site-packages/sympy/geometry/plane.py +885 -0
  39. janus/lib/python3.10/site-packages/sympy/geometry/point.py +1378 -0
  40. janus/lib/python3.10/site-packages/sympy/geometry/polygon.py +2891 -0
  41. janus/lib/python3.10/site-packages/sympy/geometry/tests/__init__.py +0 -0
  42. janus/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/test_geometrysets.cpython-310.pyc +0 -0
  43. janus/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/test_plane.cpython-310.pyc +0 -0
  44. janus/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/test_point.cpython-310.pyc +0 -0
  45. janus/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/test_util.cpython-310.pyc +0 -0
  46. janus/lib/python3.10/site-packages/sympy/geometry/tests/test_curve.py +120 -0
  47. janus/lib/python3.10/site-packages/sympy/geometry/tests/test_entity.py +120 -0
  48. janus/lib/python3.10/site-packages/sympy/geometry/tests/test_geometrysets.py +38 -0
  49. janus/lib/python3.10/site-packages/sympy/geometry/tests/test_polygon.py +676 -0
  50. janus/lib/python3.10/site-packages/sympy/geometry/tests/test_util.py +170 -0
.gitattributes CHANGED
@@ -1134,3 +1134,10 @@ infer_4_37_2/lib/python3.10/site-packages/pandas/_libs/arrays.cpython-310-x86_64
1134
  infer_4_37_2/lib/python3.10/site-packages/pandas/_libs/parsers.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1135
  infer_4_37_2/lib/python3.10/site-packages/nvidia/curand/lib/libcurand.so.10 filter=lfs diff=lfs merge=lfs -text
1136
  infer_4_37_2/lib/python3.10/site-packages/pandas/_libs/algos.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
1134
  infer_4_37_2/lib/python3.10/site-packages/pandas/_libs/parsers.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1135
  infer_4_37_2/lib/python3.10/site-packages/nvidia/curand/lib/libcurand.so.10 filter=lfs diff=lfs merge=lfs -text
1136
  infer_4_37_2/lib/python3.10/site-packages/pandas/_libs/algos.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1137
+ infer_4_37_2/lib/python3.10/site-packages/pandas/_libs/groupby.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1138
+ infer_4_37_2/lib/python3.10/site-packages/pandas/_libs/hashing.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1139
+ infer_4_37_2/lib/python3.10/site-packages/pandas/_libs/index.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1140
+ infer_4_37_2/lib/python3.10/site-packages/pandas/_libs/tslib.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1141
+ infer_4_37_2/lib/python3.10/site-packages/pandas/_libs/missing.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1142
+ infer_4_37_2/lib/python3.10/site-packages/pandas/_libs/lib.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1143
+ janus/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_matrixbase.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
infer_4_37_2/lib/python3.10/site-packages/pandas/_libs/groupby.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:41230fbdf558575fed8f6530dbc235130d3792987366204e2c417b04eb0da552
3
+ size 2601544
infer_4_37_2/lib/python3.10/site-packages/pandas/_libs/hashing.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aaa580f281abd4927103eb650b5862847f009d36cac26208f065eafec29d2fa4
3
+ size 221160
infer_4_37_2/lib/python3.10/site-packages/pandas/_libs/index.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b7c4ebb97b90fed30f3c3a62d1b4157dd99a13aad68363e8f4362f30baa1ba3c
3
+ size 988040
infer_4_37_2/lib/python3.10/site-packages/pandas/_libs/lib.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:524c92ee2ccb5583f8ca8adac91ae0afa3f43db0ea0456ab0aece9ccacb87273
3
+ size 933480
infer_4_37_2/lib/python3.10/site-packages/pandas/_libs/missing.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fe110ce6b3b10095c1c4c2f7745c02223aec6fcd4aa6cbc6782f83df72e77620
3
+ size 211400
infer_4_37_2/lib/python3.10/site-packages/pandas/_libs/ops_dispatch.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (61.7 kB). View file
 
infer_4_37_2/lib/python3.10/site-packages/pandas/_libs/reshape.pyi ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from pandas._typing import npt
4
+
5
+ def unstack(
6
+ values: np.ndarray, # reshape_t[:, :]
7
+ mask: np.ndarray, # const uint8_t[:]
8
+ stride: int,
9
+ length: int,
10
+ width: int,
11
+ new_values: np.ndarray, # reshape_t[:, :]
12
+ new_mask: np.ndarray, # uint8_t[:, :]
13
+ ) -> None: ...
14
+ def explode(
15
+ values: npt.NDArray[np.object_],
16
+ ) -> tuple[npt.NDArray[np.object_], npt.NDArray[np.int64]]: ...
infer_4_37_2/lib/python3.10/site-packages/pandas/_libs/tslib.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f28ec212e94a75d6066e383be4243e1317de1339e61ad445b8a79f0aed216136
3
+ size 340264
janus/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.6 kB). View file
 
janus/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/fp_groups.cpython-310.pyc ADDED
Binary file (38.1 kB). View file
 
janus/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/galois.cpython-310.pyc ADDED
Binary file (17.2 kB). View file
 
janus/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/graycode.cpython-310.pyc ADDED
Binary file (11.7 kB). View file
 
janus/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/group_numbers.cpython-310.pyc ADDED
Binary file (9.52 kB). View file
 
janus/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/partitions.cpython-310.pyc ADDED
Binary file (21.9 kB). View file
 
janus/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/pc_groups.cpython-310.pyc ADDED
Binary file (20 kB). View file
 
janus/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/permutations.cpython-310.pyc ADDED
Binary file (90 kB). View file
 
janus/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/polyhedron.cpython-310.pyc ADDED
Binary file (33.6 kB). View file
 
janus/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/rewritingsystem_fsm.cpython-310.pyc ADDED
Binary file (2.99 kB). View file
 
janus/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/tensor_can.cpython-310.pyc ADDED
Binary file (38 kB). View file
 
janus/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/testutil.cpython-310.pyc ADDED
Binary file (9.88 kB). View file
 
janus/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/util.cpython-310.pyc ADDED
Binary file (14.6 kB). View file
 
janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_coset_table.cpython-310.pyc ADDED
Binary file (28.4 kB). View file
 
janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_group_numbers.cpython-310.pyc ADDED
Binary file (4.58 kB). View file
 
janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_util.cpython-310.pyc ADDED
Binary file (4.11 kB). View file
 
janus/lib/python3.10/site-packages/sympy/concrete/guess.py ADDED
@@ -0,0 +1,473 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Various algorithms for helping identifying numbers and sequences."""
2
+
3
+
4
+ from sympy.concrete.products import (Product, product)
5
+ from sympy.core import Function, S
6
+ from sympy.core.add import Add
7
+ from sympy.core.numbers import Integer, Rational
8
+ from sympy.core.symbol import Symbol, symbols
9
+ from sympy.core.sympify import sympify
10
+ from sympy.functions.elementary.exponential import exp
11
+ from sympy.functions.elementary.integers import floor
12
+ from sympy.integrals.integrals import integrate
13
+ from sympy.polys.polyfuncs import rational_interpolate as rinterp
14
+ from sympy.polys.polytools import lcm
15
+ from sympy.simplify.radsimp import denom
16
+ from sympy.utilities import public
17
+
18
+
19
+ @public
20
+ def find_simple_recurrence_vector(l):
21
+ """
22
+ This function is used internally by other functions from the
23
+ sympy.concrete.guess module. While most users may want to rather use the
24
+ function find_simple_recurrence when looking for recurrence relations
25
+ among rational numbers, the current function may still be useful when
26
+ some post-processing has to be done.
27
+
28
+ Explanation
29
+ ===========
30
+
31
+ The function returns a vector of length n when a recurrence relation of
32
+ order n is detected in the sequence of rational numbers v.
33
+
34
+ If the returned vector has a length 1, then the returned value is always
35
+ the list [0], which means that no relation has been found.
36
+
37
+ While the functions is intended to be used with rational numbers, it should
38
+ work for other kinds of real numbers except for some cases involving
39
+ quadratic numbers; for that reason it should be used with some caution when
40
+ the argument is not a list of rational numbers.
41
+
42
+ Examples
43
+ ========
44
+
45
+ >>> from sympy.concrete.guess import find_simple_recurrence_vector
46
+ >>> from sympy import fibonacci
47
+ >>> find_simple_recurrence_vector([fibonacci(k) for k in range(12)])
48
+ [1, -1, -1]
49
+
50
+ See Also
51
+ ========
52
+
53
+ See the function sympy.concrete.guess.find_simple_recurrence which is more
54
+ user-friendly.
55
+
56
+ """
57
+ q1 = [0]
58
+ q2 = [1]
59
+ b, z = 0, len(l) >> 1
60
+ while len(q2) <= z:
61
+ while l[b]==0:
62
+ b += 1
63
+ if b == len(l):
64
+ c = 1
65
+ for x in q2:
66
+ c = lcm(c, denom(x))
67
+ if q2[0]*c < 0: c = -c
68
+ for k in range(len(q2)):
69
+ q2[k] = int(q2[k]*c)
70
+ return q2
71
+ a = S.One/l[b]
72
+ m = [a]
73
+ for k in range(b+1, len(l)):
74
+ m.append(-sum(l[j+1]*m[b-j-1] for j in range(b, k))*a)
75
+ l, m = m, [0] * max(len(q2), b+len(q1))
76
+ for k, q in enumerate(q2):
77
+ m[k] = a*q
78
+ for k, q in enumerate(q1):
79
+ m[k+b] += q
80
+ while m[-1]==0: m.pop() # because trailing zeros can occur
81
+ q1, q2, b = q2, m, 1
82
+ return [0]
83
+
84
+ @public
85
+ def find_simple_recurrence(v, A=Function('a'), N=Symbol('n')):
86
+ """
87
+ Detects and returns a recurrence relation from a sequence of several integer
88
+ (or rational) terms. The name of the function in the returned expression is
89
+ 'a' by default; the main variable is 'n' by default. The smallest index in
90
+ the returned expression is always n (and never n-1, n-2, etc.).
91
+
92
+ Examples
93
+ ========
94
+
95
+ >>> from sympy.concrete.guess import find_simple_recurrence
96
+ >>> from sympy import fibonacci
97
+ >>> find_simple_recurrence([fibonacci(k) for k in range(12)])
98
+ -a(n) - a(n + 1) + a(n + 2)
99
+
100
+ >>> from sympy import Function, Symbol
101
+ >>> a = [1, 1, 1]
102
+ >>> for k in range(15): a.append(5*a[-1]-3*a[-2]+8*a[-3])
103
+ >>> find_simple_recurrence(a, A=Function('f'), N=Symbol('i'))
104
+ -8*f(i) + 3*f(i + 1) - 5*f(i + 2) + f(i + 3)
105
+
106
+ """
107
+ p = find_simple_recurrence_vector(v)
108
+ n = len(p)
109
+ if n <= 1: return S.Zero
110
+
111
+ return Add(*[A(N+n-1-k)*p[k] for k in range(n)])
112
+
113
+
114
+ @public
115
+ def rationalize(x, maxcoeff=10000):
116
+ """
117
+ Helps identifying a rational number from a float (or mpmath.mpf) value by
118
+ using a continued fraction. The algorithm stops as soon as a large partial
119
+ quotient is detected (greater than 10000 by default).
120
+
121
+ Examples
122
+ ========
123
+
124
+ >>> from sympy.concrete.guess import rationalize
125
+ >>> from mpmath import cos, pi
126
+ >>> rationalize(cos(pi/3))
127
+ 1/2
128
+
129
+ >>> from mpmath import mpf
130
+ >>> rationalize(mpf("0.333333333333333"))
131
+ 1/3
132
+
133
+ While the function is rather intended to help 'identifying' rational
134
+ values, it may be used in some cases for approximating real numbers.
135
+ (Though other functions may be more relevant in that case.)
136
+
137
+ >>> rationalize(pi, maxcoeff = 250)
138
+ 355/113
139
+
140
+ See Also
141
+ ========
142
+
143
+ Several other methods can approximate a real number as a rational, like:
144
+
145
+ * fractions.Fraction.from_decimal
146
+ * fractions.Fraction.from_float
147
+ * mpmath.identify
148
+ * mpmath.pslq by using the following syntax: mpmath.pslq([x, 1])
149
+ * mpmath.findpoly by using the following syntax: mpmath.findpoly(x, 1)
150
+ * sympy.simplify.nsimplify (which is a more general function)
151
+
152
+ The main difference between the current function and all these variants is
153
+ that control focuses on magnitude of partial quotients here rather than on
154
+ global precision of the approximation. If the real is "known to be" a
155
+ rational number, the current function should be able to detect it correctly
156
+ with the default settings even when denominator is great (unless its
157
+ expansion contains unusually big partial quotients) which may occur
158
+ when studying sequences of increasing numbers. If the user cares more
159
+ on getting simple fractions, other methods may be more convenient.
160
+
161
+ """
162
+ p0, p1 = 0, 1
163
+ q0, q1 = 1, 0
164
+ a = floor(x)
165
+ while a < maxcoeff or q1==0:
166
+ p = a*p1 + p0
167
+ q = a*q1 + q0
168
+ p0, p1 = p1, p
169
+ q0, q1 = q1, q
170
+ if x==a: break
171
+ x = 1/(x-a)
172
+ a = floor(x)
173
+ return sympify(p) / q
174
+
175
+
176
+ @public
177
+ def guess_generating_function_rational(v, X=Symbol('x')):
178
+ """
179
+ Tries to "guess" a rational generating function for a sequence of rational
180
+ numbers v.
181
+
182
+ Examples
183
+ ========
184
+
185
+ >>> from sympy.concrete.guess import guess_generating_function_rational
186
+ >>> from sympy import fibonacci
187
+ >>> l = [fibonacci(k) for k in range(5,15)]
188
+ >>> guess_generating_function_rational(l)
189
+ (3*x + 5)/(-x**2 - x + 1)
190
+
191
+ See Also
192
+ ========
193
+
194
+ sympy.series.approximants
195
+ mpmath.pade
196
+
197
+ """
198
+ # a) compute the denominator as q
199
+ q = find_simple_recurrence_vector(v)
200
+ n = len(q)
201
+ if n <= 1: return None
202
+ # b) compute the numerator as p
203
+ p = [sum(v[i-k]*q[k] for k in range(min(i+1, n)))
204
+ for i in range(len(v)>>1)]
205
+ return (sum(p[k]*X**k for k in range(len(p)))
206
+ / sum(q[k]*X**k for k in range(n)))
207
+
208
+
209
+ @public
210
+ def guess_generating_function(v, X=Symbol('x'), types=['all'], maxsqrtn=2):
211
+ """
212
+ Tries to "guess" a generating function for a sequence of rational numbers v.
213
+ Only a few patterns are implemented yet.
214
+
215
+ Explanation
216
+ ===========
217
+
218
+ The function returns a dictionary where keys are the name of a given type of
219
+ generating function. Six types are currently implemented:
220
+
221
+ type | formal definition
222
+ -------+----------------------------------------------------------------
223
+ ogf | f(x) = Sum( a_k * x^k , k: 0..infinity )
224
+ egf | f(x) = Sum( a_k * x^k / k! , k: 0..infinity )
225
+ lgf | f(x) = Sum( (-1)^(k+1) a_k * x^k / k , k: 1..infinity )
226
+ | (with initial index being hold as 1 rather than 0)
227
+ hlgf | f(x) = Sum( a_k * x^k / k , k: 1..infinity )
228
+ | (with initial index being hold as 1 rather than 0)
229
+ lgdogf | f(x) = derivate( log(Sum( a_k * x^k, k: 0..infinity )), x)
230
+ lgdegf | f(x) = derivate( log(Sum( a_k * x^k / k!, k: 0..infinity )), x)
231
+
232
+ In order to spare time, the user can select only some types of generating
233
+ functions (default being ['all']). While forgetting to use a list in the
234
+ case of a single type may seem to work most of the time as in: types='ogf'
235
+ this (convenient) syntax may lead to unexpected extra results in some cases.
236
+
237
+ Discarding a type when calling the function does not mean that the type will
238
+ not be present in the returned dictionary; it only means that no extra
239
+ computation will be performed for that type, but the function may still add
240
+ it in the result when it can be easily converted from another type.
241
+
242
+ Two generating functions (lgdogf and lgdegf) are not even computed if the
243
+ initial term of the sequence is 0; it may be useful in that case to try
244
+ again after having removed the leading zeros.
245
+
246
+ Examples
247
+ ========
248
+
249
+ >>> from sympy.concrete.guess import guess_generating_function as ggf
250
+ >>> ggf([k+1 for k in range(12)], types=['ogf', 'lgf', 'hlgf'])
251
+ {'hlgf': 1/(1 - x), 'lgf': 1/(x + 1), 'ogf': 1/(x**2 - 2*x + 1)}
252
+
253
+ >>> from sympy import sympify
254
+ >>> l = sympify("[3/2, 11/2, 0, -121/2, -363/2, 121]")
255
+ >>> ggf(l)
256
+ {'ogf': (x + 3/2)/(11*x**2 - 3*x + 1)}
257
+
258
+ >>> from sympy import fibonacci
259
+ >>> ggf([fibonacci(k) for k in range(5, 15)], types=['ogf'])
260
+ {'ogf': (3*x + 5)/(-x**2 - x + 1)}
261
+
262
+ >>> from sympy import factorial
263
+ >>> ggf([factorial(k) for k in range(12)], types=['ogf', 'egf', 'lgf'])
264
+ {'egf': 1/(1 - x)}
265
+
266
+ >>> ggf([k+1 for k in range(12)], types=['egf'])
267
+ {'egf': (x + 1)*exp(x), 'lgdegf': (x + 2)/(x + 1)}
268
+
269
+ N-th root of a rational function can also be detected (below is an example
270
+ coming from the sequence A108626 from https://oeis.org).
271
+ The greatest n-th root to be tested is specified as maxsqrtn (default 2).
272
+
273
+ >>> ggf([1, 2, 5, 14, 41, 124, 383, 1200, 3799, 12122, 38919])['ogf']
274
+ sqrt(1/(x**4 + 2*x**2 - 4*x + 1))
275
+
276
+ References
277
+ ==========
278
+
279
+ .. [1] "Concrete Mathematics", R.L. Graham, D.E. Knuth, O. Patashnik
280
+ .. [2] https://oeis.org/wiki/Generating_functions
281
+
282
+ """
283
+ # List of all types of all g.f. known by the algorithm
284
+ if 'all' in types:
285
+ types = ('ogf', 'egf', 'lgf', 'hlgf', 'lgdogf', 'lgdegf')
286
+
287
+ result = {}
288
+
289
+ # Ordinary Generating Function (ogf)
290
+ if 'ogf' in types:
291
+ # Perform some convolutions of the sequence with itself
292
+ t = [1] + [0]*(len(v) - 1)
293
+ for d in range(max(1, maxsqrtn)):
294
+ t = [sum(t[n-i]*v[i] for i in range(n+1)) for n in range(len(v))]
295
+ g = guess_generating_function_rational(t, X=X)
296
+ if g:
297
+ result['ogf'] = g**Rational(1, d+1)
298
+ break
299
+
300
+ # Exponential Generating Function (egf)
301
+ if 'egf' in types:
302
+ # Transform sequence (division by factorial)
303
+ w, f = [], S.One
304
+ for i, k in enumerate(v):
305
+ f *= i if i else 1
306
+ w.append(k/f)
307
+ # Perform some convolutions of the sequence with itself
308
+ t = [1] + [0]*(len(w) - 1)
309
+ for d in range(max(1, maxsqrtn)):
310
+ t = [sum(t[n-i]*w[i] for i in range(n+1)) for n in range(len(w))]
311
+ g = guess_generating_function_rational(t, X=X)
312
+ if g:
313
+ result['egf'] = g**Rational(1, d+1)
314
+ break
315
+
316
+ # Logarithmic Generating Function (lgf)
317
+ if 'lgf' in types:
318
+ # Transform sequence (multiplication by (-1)^(n+1) / n)
319
+ w, f = [], S.NegativeOne
320
+ for i, k in enumerate(v):
321
+ f = -f
322
+ w.append(f*k/Integer(i+1))
323
+ # Perform some convolutions of the sequence with itself
324
+ t = [1] + [0]*(len(w) - 1)
325
+ for d in range(max(1, maxsqrtn)):
326
+ t = [sum(t[n-i]*w[i] for i in range(n+1)) for n in range(len(w))]
327
+ g = guess_generating_function_rational(t, X=X)
328
+ if g:
329
+ result['lgf'] = g**Rational(1, d+1)
330
+ break
331
+
332
+ # Hyperbolic logarithmic Generating Function (hlgf)
333
+ if 'hlgf' in types:
334
+ # Transform sequence (division by n+1)
335
+ w = []
336
+ for i, k in enumerate(v):
337
+ w.append(k/Integer(i+1))
338
+ # Perform some convolutions of the sequence with itself
339
+ t = [1] + [0]*(len(w) - 1)
340
+ for d in range(max(1, maxsqrtn)):
341
+ t = [sum(t[n-i]*w[i] for i in range(n+1)) for n in range(len(w))]
342
+ g = guess_generating_function_rational(t, X=X)
343
+ if g:
344
+ result['hlgf'] = g**Rational(1, d+1)
345
+ break
346
+
347
+ # Logarithmic derivative of ordinary generating Function (lgdogf)
348
+ if v[0] != 0 and ('lgdogf' in types
349
+ or ('ogf' in types and 'ogf' not in result)):
350
+ # Transform sequence by computing f'(x)/f(x)
351
+ # because log(f(x)) = integrate( f'(x)/f(x) )
352
+ a, w = sympify(v[0]), []
353
+ for n in range(len(v)-1):
354
+ w.append(
355
+ (v[n+1]*(n+1) - sum(w[-i-1]*v[i+1] for i in range(n)))/a)
356
+ # Perform some convolutions of the sequence with itself
357
+ t = [1] + [0]*(len(w) - 1)
358
+ for d in range(max(1, maxsqrtn)):
359
+ t = [sum(t[n-i]*w[i] for i in range(n+1)) for n in range(len(w))]
360
+ g = guess_generating_function_rational(t, X=X)
361
+ if g:
362
+ result['lgdogf'] = g**Rational(1, d+1)
363
+ if 'ogf' not in result:
364
+ result['ogf'] = exp(integrate(result['lgdogf'], X))
365
+ break
366
+
367
+ # Logarithmic derivative of exponential generating Function (lgdegf)
368
+ if v[0] != 0 and ('lgdegf' in types
369
+ or ('egf' in types and 'egf' not in result)):
370
+ # Transform sequence / step 1 (division by factorial)
371
+ z, f = [], S.One
372
+ for i, k in enumerate(v):
373
+ f *= i if i else 1
374
+ z.append(k/f)
375
+ # Transform sequence / step 2 by computing f'(x)/f(x)
376
+ # because log(f(x)) = integrate( f'(x)/f(x) )
377
+ a, w = z[0], []
378
+ for n in range(len(z)-1):
379
+ w.append(
380
+ (z[n+1]*(n+1) - sum(w[-i-1]*z[i+1] for i in range(n)))/a)
381
+ # Perform some convolutions of the sequence with itself
382
+ t = [1] + [0]*(len(w) - 1)
383
+ for d in range(max(1, maxsqrtn)):
384
+ t = [sum(t[n-i]*w[i] for i in range(n+1)) for n in range(len(w))]
385
+ g = guess_generating_function_rational(t, X=X)
386
+ if g:
387
+ result['lgdegf'] = g**Rational(1, d+1)
388
+ if 'egf' not in result:
389
+ result['egf'] = exp(integrate(result['lgdegf'], X))
390
+ break
391
+
392
+ return result
393
+
394
+
395
+ @public
396
+ def guess(l, all=False, evaluate=True, niter=2, variables=None):
397
+ """
398
+ This function is adapted from the Rate.m package for Mathematica
399
+ written by Christian Krattenthaler.
400
+ It tries to guess a formula from a given sequence of rational numbers.
401
+
402
+ Explanation
403
+ ===========
404
+
405
+ In order to speed up the process, the 'all' variable is set to False by
406
+ default, stopping the computation as some results are returned during an
407
+ iteration; the variable can be set to True if more iterations are needed
408
+ (other formulas may be found; however they may be equivalent to the first
409
+ ones).
410
+
411
+ Another option is the 'evaluate' variable (default is True); setting it
412
+ to False will leave the involved products unevaluated.
413
+
414
+ By default, the number of iterations is set to 2 but a greater value (up
415
+ to len(l)-1) can be specified with the optional 'niter' variable.
416
+ More and more convoluted results are found when the order of the
417
+ iteration gets higher:
418
+
419
+ * first iteration returns polynomial or rational functions;
420
+ * second iteration returns products of rising factorials and their
421
+ inverses;
422
+ * third iteration returns products of products of rising factorials
423
+ and their inverses;
424
+ * etc.
425
+
426
+ The returned formulas contain symbols i0, i1, i2, ... where the main
427
+ variables is i0 (and auxiliary variables are i1, i2, ...). A list of
428
+ other symbols can be provided in the 'variables' option; the length of
429
+ the least should be the value of 'niter' (more is acceptable but only
430
+ the first symbols will be used); in this case, the main variable will be
431
+ the first symbol in the list.
432
+
433
+ Examples
434
+ ========
435
+
436
+ >>> from sympy.concrete.guess import guess
437
+ >>> guess([1,2,6,24,120], evaluate=False)
438
+ [Product(i1 + 1, (i1, 1, i0 - 1))]
439
+
440
+ >>> from sympy import symbols
441
+ >>> r = guess([1,2,7,42,429,7436,218348,10850216], niter=4)
442
+ >>> i0 = symbols("i0")
443
+ >>> [r[0].subs(i0,n).doit() for n in range(1,10)]
444
+ [1, 2, 7, 42, 429, 7436, 218348, 10850216, 911835460]
445
+ """
446
+ if any(a==0 for a in l[:-1]):
447
+ return []
448
+ N = len(l)
449
+ niter = min(N-1, niter)
450
+ myprod = product if evaluate else Product
451
+ g = []
452
+ res = []
453
+ if variables is None:
454
+ symb = symbols('i:'+str(niter))
455
+ else:
456
+ symb = variables
457
+ for k, s in enumerate(symb):
458
+ g.append(l)
459
+ n, r = len(l), []
460
+ for i in range(n-2-1, -1, -1):
461
+ ri = rinterp(enumerate(g[k][:-1], start=1), i, X=s)
462
+ if ((denom(ri).subs({s:n}) != 0)
463
+ and (ri.subs({s:n}) - g[k][-1] == 0)
464
+ and ri not in r):
465
+ r.append(ri)
466
+ if r:
467
+ for i in range(k-1, -1, -1):
468
+ r = [g[i][0]
469
+ * myprod(v, (symb[i+1], 1, symb[i]-1)) for v in r]
470
+ if not all: return r
471
+ res += r
472
+ l = [Rational(l[i+1], l[i]) for i in range(N-k-1)]
473
+ return res
janus/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
+ ]
janus/lib/python3.10/site-packages/sympy/geometry/__pycache__/curve.cpython-310.pyc ADDED
Binary file (11.7 kB). View file
 
janus/lib/python3.10/site-packages/sympy/geometry/__pycache__/ellipse.cpython-310.pyc ADDED
Binary file (48 kB). View file
 
janus/lib/python3.10/site-packages/sympy/geometry/__pycache__/line.cpython-310.pyc ADDED
Binary file (71.9 kB). View file
 
janus/lib/python3.10/site-packages/sympy/geometry/__pycache__/parabola.cpython-310.pyc ADDED
Binary file (11.1 kB). View file
 
janus/lib/python3.10/site-packages/sympy/geometry/__pycache__/plane.cpython-310.pyc ADDED
Binary file (25.7 kB). View file
 
janus/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)
janus/lib/python3.10/site-packages/sympy/geometry/ellipse.py ADDED
@@ -0,0 +1,1767 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Elliptical geometrical entities.
2
+
3
+ Contains
4
+ * Ellipse
5
+ * Circle
6
+
7
+ """
8
+
9
+ from sympy.core.expr import Expr
10
+ from sympy.core.relational import Eq
11
+ from sympy.core import S, pi, sympify
12
+ from sympy.core.evalf import N
13
+ from sympy.core.parameters import global_parameters
14
+ from sympy.core.logic import fuzzy_bool
15
+ from sympy.core.numbers import Rational, oo
16
+ from sympy.core.sorting import ordered
17
+ from sympy.core.symbol import Dummy, uniquely_named_symbol, _symbol
18
+ from sympy.simplify import simplify, trigsimp
19
+ from sympy.functions.elementary.miscellaneous import sqrt, Max
20
+ from sympy.functions.elementary.trigonometric import cos, sin
21
+ from sympy.functions.special.elliptic_integrals import elliptic_e
22
+ from .entity import GeometryEntity, GeometrySet
23
+ from .exceptions import GeometryError
24
+ from .line import Line, Segment, Ray2D, Segment2D, Line2D, LinearEntity3D
25
+ from .point import Point, Point2D, Point3D
26
+ from .util import idiff, find
27
+ from sympy.polys import DomainError, Poly, PolynomialError
28
+ from sympy.polys.polyutils import _not_a_coeff, _nsort
29
+ from sympy.solvers import solve
30
+ from sympy.solvers.solveset import linear_coeffs
31
+ from sympy.utilities.misc import filldedent, func_name
32
+
33
+ from mpmath.libmp.libmpf import prec_to_dps
34
+
35
+ import random
36
+
37
+ x, y = [Dummy('ellipse_dummy', real=True) for i in range(2)]
38
+
39
+
40
+ class Ellipse(GeometrySet):
41
+ """An elliptical GeometryEntity.
42
+
43
+ Parameters
44
+ ==========
45
+
46
+ center : Point, optional
47
+ Default value is Point(0, 0)
48
+ hradius : number or SymPy expression, optional
49
+ vradius : number or SymPy expression, optional
50
+ eccentricity : number or SymPy expression, optional
51
+ Two of `hradius`, `vradius` and `eccentricity` must be supplied to
52
+ create an Ellipse. The third is derived from the two supplied.
53
+
54
+ Attributes
55
+ ==========
56
+
57
+ center
58
+ hradius
59
+ vradius
60
+ area
61
+ circumference
62
+ eccentricity
63
+ periapsis
64
+ apoapsis
65
+ focus_distance
66
+ foci
67
+
68
+ Raises
69
+ ======
70
+
71
+ GeometryError
72
+ When `hradius`, `vradius` and `eccentricity` are incorrectly supplied
73
+ as parameters.
74
+ TypeError
75
+ When `center` is not a Point.
76
+
77
+ See Also
78
+ ========
79
+
80
+ Circle
81
+
82
+ Notes
83
+ -----
84
+ Constructed from a center and two radii, the first being the horizontal
85
+ radius (along the x-axis) and the second being the vertical radius (along
86
+ the y-axis).
87
+
88
+ When symbolic value for hradius and vradius are used, any calculation that
89
+ refers to the foci or the major or minor axis will assume that the ellipse
90
+ has its major radius on the x-axis. If this is not true then a manual
91
+ rotation is necessary.
92
+
93
+ Examples
94
+ ========
95
+
96
+ >>> from sympy import Ellipse, Point, Rational
97
+ >>> e1 = Ellipse(Point(0, 0), 5, 1)
98
+ >>> e1.hradius, e1.vradius
99
+ (5, 1)
100
+ >>> e2 = Ellipse(Point(3, 1), hradius=3, eccentricity=Rational(4, 5))
101
+ >>> e2
102
+ Ellipse(Point2D(3, 1), 3, 9/5)
103
+
104
+ """
105
+
106
+ def __contains__(self, o):
107
+ if isinstance(o, Point):
108
+ res = self.equation(x, y).subs({x: o.x, y: o.y})
109
+ return trigsimp(simplify(res)) is S.Zero
110
+ elif isinstance(o, Ellipse):
111
+ return self == o
112
+ return False
113
+
114
+ def __eq__(self, o):
115
+ """Is the other GeometryEntity the same as this ellipse?"""
116
+ return isinstance(o, Ellipse) and (self.center == o.center and
117
+ self.hradius == o.hradius and
118
+ self.vradius == o.vradius)
119
+
120
+ def __hash__(self):
121
+ return super().__hash__()
122
+
123
+ def __new__(
124
+ cls, center=None, hradius=None, vradius=None, eccentricity=None, **kwargs):
125
+
126
+ hradius = sympify(hradius)
127
+ vradius = sympify(vradius)
128
+
129
+ if center is None:
130
+ center = Point(0, 0)
131
+ else:
132
+ if len(center) != 2:
133
+ raise ValueError('The center of "{}" must be a two dimensional point'.format(cls))
134
+ center = Point(center, dim=2)
135
+
136
+ if len(list(filter(lambda x: x is not None, (hradius, vradius, eccentricity)))) != 2:
137
+ raise ValueError(filldedent('''
138
+ Exactly two arguments of "hradius", "vradius", and
139
+ "eccentricity" must not be None.'''))
140
+
141
+ if eccentricity is not None:
142
+ eccentricity = sympify(eccentricity)
143
+ if eccentricity.is_negative:
144
+ raise GeometryError("Eccentricity of ellipse/circle should lie between [0, 1)")
145
+ elif hradius is None:
146
+ hradius = vradius / sqrt(1 - eccentricity**2)
147
+ elif vradius is None:
148
+ vradius = hradius * sqrt(1 - eccentricity**2)
149
+
150
+ if hradius == vradius:
151
+ return Circle(center, hradius, **kwargs)
152
+
153
+ if S.Zero in (hradius, vradius):
154
+ return Segment(Point(center[0] - hradius, center[1] - vradius), Point(center[0] + hradius, center[1] + vradius))
155
+
156
+ if hradius.is_real is False or vradius.is_real is False:
157
+ raise GeometryError("Invalid value encountered when computing hradius / vradius.")
158
+
159
+ return GeometryEntity.__new__(cls, center, hradius, vradius, **kwargs)
160
+
161
+ def _svg(self, scale_factor=1., fill_color="#66cc99"):
162
+ """Returns SVG ellipse element for the Ellipse.
163
+
164
+ Parameters
165
+ ==========
166
+
167
+ scale_factor : float
168
+ Multiplication factor for the SVG stroke-width. Default is 1.
169
+ fill_color : str, optional
170
+ Hex string for fill color. Default is "#66cc99".
171
+ """
172
+
173
+ c = N(self.center)
174
+ h, v = N(self.hradius), N(self.vradius)
175
+ return (
176
+ '<ellipse fill="{1}" stroke="#555555" '
177
+ 'stroke-width="{0}" opacity="0.6" cx="{2}" cy="{3}" rx="{4}" ry="{5}"/>'
178
+ ).format(2. * scale_factor, fill_color, c.x, c.y, h, v)
179
+
180
+ @property
181
+ def ambient_dimension(self):
182
+ return 2
183
+
184
+ @property
185
+ def apoapsis(self):
186
+ """The apoapsis of the ellipse.
187
+
188
+ The greatest distance between the focus and the contour.
189
+
190
+ Returns
191
+ =======
192
+
193
+ apoapsis : number
194
+
195
+ See Also
196
+ ========
197
+
198
+ periapsis : Returns shortest distance between foci and contour
199
+
200
+ Examples
201
+ ========
202
+
203
+ >>> from sympy import Point, Ellipse
204
+ >>> p1 = Point(0, 0)
205
+ >>> e1 = Ellipse(p1, 3, 1)
206
+ >>> e1.apoapsis
207
+ 2*sqrt(2) + 3
208
+
209
+ """
210
+ return self.major * (1 + self.eccentricity)
211
+
212
+ def arbitrary_point(self, parameter='t'):
213
+ """A parameterized point on the ellipse.
214
+
215
+ Parameters
216
+ ==========
217
+
218
+ parameter : str, optional
219
+ Default value is 't'.
220
+
221
+ Returns
222
+ =======
223
+
224
+ arbitrary_point : Point
225
+
226
+ Raises
227
+ ======
228
+
229
+ ValueError
230
+ When `parameter` already appears in the functions.
231
+
232
+ See Also
233
+ ========
234
+
235
+ sympy.geometry.point.Point
236
+
237
+ Examples
238
+ ========
239
+
240
+ >>> from sympy import Point, Ellipse
241
+ >>> e1 = Ellipse(Point(0, 0), 3, 2)
242
+ >>> e1.arbitrary_point()
243
+ Point2D(3*cos(t), 2*sin(t))
244
+
245
+ """
246
+ t = _symbol(parameter, real=True)
247
+ if t.name in (f.name for f in self.free_symbols):
248
+ raise ValueError(filldedent('Symbol %s already appears in object '
249
+ 'and cannot be used as a parameter.' % t.name))
250
+ return Point(self.center.x + self.hradius*cos(t),
251
+ self.center.y + self.vradius*sin(t))
252
+
253
+ @property
254
+ def area(self):
255
+ """The area of the ellipse.
256
+
257
+ Returns
258
+ =======
259
+
260
+ area : number
261
+
262
+ Examples
263
+ ========
264
+
265
+ >>> from sympy import Point, Ellipse
266
+ >>> p1 = Point(0, 0)
267
+ >>> e1 = Ellipse(p1, 3, 1)
268
+ >>> e1.area
269
+ 3*pi
270
+
271
+ """
272
+ return simplify(S.Pi * self.hradius * self.vradius)
273
+
274
+ @property
275
+ def bounds(self):
276
+ """Return a tuple (xmin, ymin, xmax, ymax) representing the bounding
277
+ rectangle for the geometric figure.
278
+
279
+ """
280
+
281
+ h, v = self.hradius, self.vradius
282
+ return (self.center.x - h, self.center.y - v, self.center.x + h, self.center.y + v)
283
+
284
+ @property
285
+ def center(self):
286
+ """The center of the ellipse.
287
+
288
+ Returns
289
+ =======
290
+
291
+ center : number
292
+
293
+ See Also
294
+ ========
295
+
296
+ sympy.geometry.point.Point
297
+
298
+ Examples
299
+ ========
300
+
301
+ >>> from sympy import Point, Ellipse
302
+ >>> p1 = Point(0, 0)
303
+ >>> e1 = Ellipse(p1, 3, 1)
304
+ >>> e1.center
305
+ Point2D(0, 0)
306
+
307
+ """
308
+ return self.args[0]
309
+
310
+ @property
311
+ def circumference(self):
312
+ """The circumference of the ellipse.
313
+
314
+ Examples
315
+ ========
316
+
317
+ >>> from sympy import Point, Ellipse
318
+ >>> p1 = Point(0, 0)
319
+ >>> e1 = Ellipse(p1, 3, 1)
320
+ >>> e1.circumference
321
+ 12*elliptic_e(8/9)
322
+
323
+ """
324
+ if self.eccentricity == 1:
325
+ # degenerate
326
+ return 4*self.major
327
+ elif self.eccentricity == 0:
328
+ # circle
329
+ return 2*pi*self.hradius
330
+ else:
331
+ return 4*self.major*elliptic_e(self.eccentricity**2)
332
+
333
+ @property
334
+ def eccentricity(self):
335
+ """The eccentricity of the ellipse.
336
+
337
+ Returns
338
+ =======
339
+
340
+ eccentricity : number
341
+
342
+ Examples
343
+ ========
344
+
345
+ >>> from sympy import Point, Ellipse, sqrt
346
+ >>> p1 = Point(0, 0)
347
+ >>> e1 = Ellipse(p1, 3, sqrt(2))
348
+ >>> e1.eccentricity
349
+ sqrt(7)/3
350
+
351
+ """
352
+ return self.focus_distance / self.major
353
+
354
+ def encloses_point(self, p):
355
+ """
356
+ Return True if p is enclosed by (is inside of) self.
357
+
358
+ Notes
359
+ -----
360
+ Being on the border of self is considered False.
361
+
362
+ Parameters
363
+ ==========
364
+
365
+ p : Point
366
+
367
+ Returns
368
+ =======
369
+
370
+ encloses_point : True, False or None
371
+
372
+ See Also
373
+ ========
374
+
375
+ sympy.geometry.point.Point
376
+
377
+ Examples
378
+ ========
379
+
380
+ >>> from sympy import Ellipse, S
381
+ >>> from sympy.abc import t
382
+ >>> e = Ellipse((0, 0), 3, 2)
383
+ >>> e.encloses_point((0, 0))
384
+ True
385
+ >>> e.encloses_point(e.arbitrary_point(t).subs(t, S.Half))
386
+ False
387
+ >>> e.encloses_point((4, 0))
388
+ False
389
+
390
+ """
391
+ p = Point(p, dim=2)
392
+ if p in self:
393
+ return False
394
+
395
+ if len(self.foci) == 2:
396
+ # if the combined distance from the foci to p (h1 + h2) is less
397
+ # than the combined distance from the foci to the minor axis
398
+ # (which is the same as the major axis length) then p is inside
399
+ # the ellipse
400
+ h1, h2 = [f.distance(p) for f in self.foci]
401
+ test = 2*self.major - (h1 + h2)
402
+ else:
403
+ test = self.radius - self.center.distance(p)
404
+
405
+ return fuzzy_bool(test.is_positive)
406
+
407
+ def equation(self, x='x', y='y', _slope=None):
408
+ """
409
+ Returns the equation of an ellipse aligned with the x and y axes;
410
+ when slope is given, the equation returned corresponds to an ellipse
411
+ with a major axis having that slope.
412
+
413
+ Parameters
414
+ ==========
415
+
416
+ x : str, optional
417
+ Label for the x-axis. Default value is 'x'.
418
+ y : str, optional
419
+ Label for the y-axis. Default value is 'y'.
420
+ _slope : Expr, optional
421
+ The slope of the major axis. Ignored when 'None'.
422
+
423
+ Returns
424
+ =======
425
+
426
+ equation : SymPy expression
427
+
428
+ See Also
429
+ ========
430
+
431
+ arbitrary_point : Returns parameterized point on ellipse
432
+
433
+ Examples
434
+ ========
435
+
436
+ >>> from sympy import Point, Ellipse, pi
437
+ >>> from sympy.abc import x, y
438
+ >>> e1 = Ellipse(Point(1, 0), 3, 2)
439
+ >>> eq1 = e1.equation(x, y); eq1
440
+ y**2/4 + (x/3 - 1/3)**2 - 1
441
+ >>> eq2 = e1.equation(x, y, _slope=1); eq2
442
+ (-x + y + 1)**2/8 + (x + y - 1)**2/18 - 1
443
+
444
+ A point on e1 satisfies eq1. Let's use one on the x-axis:
445
+
446
+ >>> p1 = e1.center + Point(e1.major, 0)
447
+ >>> assert eq1.subs(x, p1.x).subs(y, p1.y) == 0
448
+
449
+ When rotated the same as the rotated ellipse, about the center
450
+ point of the ellipse, it will satisfy the rotated ellipse's
451
+ equation, too:
452
+
453
+ >>> r1 = p1.rotate(pi/4, e1.center)
454
+ >>> assert eq2.subs(x, r1.x).subs(y, r1.y) == 0
455
+
456
+ References
457
+ ==========
458
+
459
+ .. [1] https://math.stackexchange.com/questions/108270/what-is-the-equation-of-an-ellipse-that-is-not-aligned-with-the-axis
460
+ .. [2] https://en.wikipedia.org/wiki/Ellipse#Shifted_ellipse
461
+
462
+ """
463
+
464
+ x = _symbol(x, real=True)
465
+ y = _symbol(y, real=True)
466
+
467
+ dx = x - self.center.x
468
+ dy = y - self.center.y
469
+
470
+ if _slope is not None:
471
+ L = (dy - _slope*dx)**2
472
+ l = (_slope*dy + dx)**2
473
+ h = 1 + _slope**2
474
+ b = h*self.major**2
475
+ a = h*self.minor**2
476
+ return l/b + L/a - 1
477
+
478
+ else:
479
+ t1 = (dx/self.hradius)**2
480
+ t2 = (dy/self.vradius)**2
481
+ return t1 + t2 - 1
482
+
483
+ def evolute(self, x='x', y='y'):
484
+ """The equation of evolute of the ellipse.
485
+
486
+ Parameters
487
+ ==========
488
+
489
+ x : str, optional
490
+ Label for the x-axis. Default value is 'x'.
491
+ y : str, optional
492
+ Label for the y-axis. Default value is 'y'.
493
+
494
+ Returns
495
+ =======
496
+
497
+ equation : SymPy expression
498
+
499
+ Examples
500
+ ========
501
+
502
+ >>> from sympy import Point, Ellipse
503
+ >>> e1 = Ellipse(Point(1, 0), 3, 2)
504
+ >>> e1.evolute()
505
+ 2**(2/3)*y**(2/3) + (3*x - 3)**(2/3) - 5**(2/3)
506
+ """
507
+ if len(self.args) != 3:
508
+ raise NotImplementedError('Evolute of arbitrary Ellipse is not supported.')
509
+ x = _symbol(x, real=True)
510
+ y = _symbol(y, real=True)
511
+ t1 = (self.hradius*(x - self.center.x))**Rational(2, 3)
512
+ t2 = (self.vradius*(y - self.center.y))**Rational(2, 3)
513
+ return t1 + t2 - (self.hradius**2 - self.vradius**2)**Rational(2, 3)
514
+
515
+ @property
516
+ def foci(self):
517
+ """The foci of the ellipse.
518
+
519
+ Notes
520
+ -----
521
+ The foci can only be calculated if the major/minor axes are known.
522
+
523
+ Raises
524
+ ======
525
+
526
+ ValueError
527
+ When the major and minor axis cannot be determined.
528
+
529
+ See Also
530
+ ========
531
+
532
+ sympy.geometry.point.Point
533
+ focus_distance : Returns the distance between focus and center
534
+
535
+ Examples
536
+ ========
537
+
538
+ >>> from sympy import Point, Ellipse
539
+ >>> p1 = Point(0, 0)
540
+ >>> e1 = Ellipse(p1, 3, 1)
541
+ >>> e1.foci
542
+ (Point2D(-2*sqrt(2), 0), Point2D(2*sqrt(2), 0))
543
+
544
+ """
545
+ c = self.center
546
+ hr, vr = self.hradius, self.vradius
547
+ if hr == vr:
548
+ return (c, c)
549
+
550
+ # calculate focus distance manually, since focus_distance calls this
551
+ # routine
552
+ fd = sqrt(self.major**2 - self.minor**2)
553
+ if hr == self.minor:
554
+ # foci on the y-axis
555
+ return (c + Point(0, -fd), c + Point(0, fd))
556
+ elif hr == self.major:
557
+ # foci on the x-axis
558
+ return (c + Point(-fd, 0), c + Point(fd, 0))
559
+
560
+ @property
561
+ def focus_distance(self):
562
+ """The focal distance of the ellipse.
563
+
564
+ The distance between the center and one focus.
565
+
566
+ Returns
567
+ =======
568
+
569
+ focus_distance : number
570
+
571
+ See Also
572
+ ========
573
+
574
+ foci
575
+
576
+ Examples
577
+ ========
578
+
579
+ >>> from sympy import Point, Ellipse
580
+ >>> p1 = Point(0, 0)
581
+ >>> e1 = Ellipse(p1, 3, 1)
582
+ >>> e1.focus_distance
583
+ 2*sqrt(2)
584
+
585
+ """
586
+ return Point.distance(self.center, self.foci[0])
587
+
588
+ @property
589
+ def hradius(self):
590
+ """The horizontal radius of the ellipse.
591
+
592
+ Returns
593
+ =======
594
+
595
+ hradius : number
596
+
597
+ See Also
598
+ ========
599
+
600
+ vradius, major, minor
601
+
602
+ Examples
603
+ ========
604
+
605
+ >>> from sympy import Point, Ellipse
606
+ >>> p1 = Point(0, 0)
607
+ >>> e1 = Ellipse(p1, 3, 1)
608
+ >>> e1.hradius
609
+ 3
610
+
611
+ """
612
+ return self.args[1]
613
+
614
+ def intersection(self, o):
615
+ """The intersection of this ellipse and another geometrical entity
616
+ `o`.
617
+
618
+ Parameters
619
+ ==========
620
+
621
+ o : GeometryEntity
622
+
623
+ Returns
624
+ =======
625
+
626
+ intersection : list of GeometryEntity objects
627
+
628
+ Notes
629
+ -----
630
+ Currently supports intersections with Point, Line, Segment, Ray,
631
+ Circle and Ellipse types.
632
+
633
+ See Also
634
+ ========
635
+
636
+ sympy.geometry.entity.GeometryEntity
637
+
638
+ Examples
639
+ ========
640
+
641
+ >>> from sympy import Ellipse, Point, Line
642
+ >>> e = Ellipse(Point(0, 0), 5, 7)
643
+ >>> e.intersection(Point(0, 0))
644
+ []
645
+ >>> e.intersection(Point(5, 0))
646
+ [Point2D(5, 0)]
647
+ >>> e.intersection(Line(Point(0,0), Point(0, 1)))
648
+ [Point2D(0, -7), Point2D(0, 7)]
649
+ >>> e.intersection(Line(Point(5,0), Point(5, 1)))
650
+ [Point2D(5, 0)]
651
+ >>> e.intersection(Line(Point(6,0), Point(6, 1)))
652
+ []
653
+ >>> e = Ellipse(Point(-1, 0), 4, 3)
654
+ >>> e.intersection(Ellipse(Point(1, 0), 4, 3))
655
+ [Point2D(0, -3*sqrt(15)/4), Point2D(0, 3*sqrt(15)/4)]
656
+ >>> e.intersection(Ellipse(Point(5, 0), 4, 3))
657
+ [Point2D(2, -3*sqrt(7)/4), Point2D(2, 3*sqrt(7)/4)]
658
+ >>> e.intersection(Ellipse(Point(100500, 0), 4, 3))
659
+ []
660
+ >>> e.intersection(Ellipse(Point(0, 0), 3, 4))
661
+ [Point2D(3, 0), Point2D(-363/175, -48*sqrt(111)/175), Point2D(-363/175, 48*sqrt(111)/175)]
662
+ >>> e.intersection(Ellipse(Point(-1, 0), 3, 4))
663
+ [Point2D(-17/5, -12/5), Point2D(-17/5, 12/5), Point2D(7/5, -12/5), Point2D(7/5, 12/5)]
664
+ """
665
+ # TODO: Replace solve with nonlinsolve, when nonlinsolve will be able to solve in real domain
666
+
667
+ if isinstance(o, Point):
668
+ if o in self:
669
+ return [o]
670
+ else:
671
+ return []
672
+
673
+ elif isinstance(o, (Segment2D, Ray2D)):
674
+ ellipse_equation = self.equation(x, y)
675
+ result = solve([ellipse_equation, Line(
676
+ o.points[0], o.points[1]).equation(x, y)], [x, y],
677
+ set=True)[1]
678
+ return list(ordered([Point(i) for i in result if i in o]))
679
+
680
+ elif isinstance(o, Polygon):
681
+ return o.intersection(self)
682
+
683
+ elif isinstance(o, (Ellipse, Line2D)):
684
+ if o == self:
685
+ return self
686
+ else:
687
+ ellipse_equation = self.equation(x, y)
688
+ return list(ordered([Point(i) for i in solve(
689
+ [ellipse_equation, o.equation(x, y)], [x, y],
690
+ set=True)[1]]))
691
+ elif isinstance(o, LinearEntity3D):
692
+ raise TypeError('Entity must be two dimensional, not three dimensional')
693
+ else:
694
+ raise TypeError('Intersection not handled for %s' % func_name(o))
695
+
696
+ def is_tangent(self, o):
697
+ """Is `o` tangent to the ellipse?
698
+
699
+ Parameters
700
+ ==========
701
+
702
+ o : GeometryEntity
703
+ An Ellipse, LinearEntity or Polygon
704
+
705
+ Raises
706
+ ======
707
+
708
+ NotImplementedError
709
+ When the wrong type of argument is supplied.
710
+
711
+ Returns
712
+ =======
713
+
714
+ is_tangent: boolean
715
+ True if o is tangent to the ellipse, False otherwise.
716
+
717
+ See Also
718
+ ========
719
+
720
+ tangent_lines
721
+
722
+ Examples
723
+ ========
724
+
725
+ >>> from sympy import Point, Ellipse, Line
726
+ >>> p0, p1, p2 = Point(0, 0), Point(3, 0), Point(3, 3)
727
+ >>> e1 = Ellipse(p0, 3, 2)
728
+ >>> l1 = Line(p1, p2)
729
+ >>> e1.is_tangent(l1)
730
+ True
731
+
732
+ """
733
+ if isinstance(o, Point2D):
734
+ return False
735
+ elif isinstance(o, Ellipse):
736
+ intersect = self.intersection(o)
737
+ if isinstance(intersect, Ellipse):
738
+ return True
739
+ elif intersect:
740
+ return all((self.tangent_lines(i)[0]).equals(o.tangent_lines(i)[0]) for i in intersect)
741
+ else:
742
+ return False
743
+ elif isinstance(o, Line2D):
744
+ hit = self.intersection(o)
745
+ if not hit:
746
+ return False
747
+ if len(hit) == 1:
748
+ return True
749
+ # might return None if it can't decide
750
+ return hit[0].equals(hit[1])
751
+ elif isinstance(o, (Segment2D, Ray2D)):
752
+ intersect = self.intersection(o)
753
+ if len(intersect) == 1:
754
+ return o in self.tangent_lines(intersect[0])[0]
755
+ else:
756
+ return False
757
+ elif isinstance(o, Polygon):
758
+ return all(self.is_tangent(s) for s in o.sides)
759
+ elif isinstance(o, (LinearEntity3D, Point3D)):
760
+ raise TypeError('Entity must be two dimensional, not three dimensional')
761
+ else:
762
+ raise TypeError('Is_tangent not handled for %s' % func_name(o))
763
+
764
+ @property
765
+ def major(self):
766
+ """Longer axis of the ellipse (if it can be determined) else hradius.
767
+
768
+ Returns
769
+ =======
770
+
771
+ major : number or expression
772
+
773
+ See Also
774
+ ========
775
+
776
+ hradius, vradius, minor
777
+
778
+ Examples
779
+ ========
780
+
781
+ >>> from sympy import Point, Ellipse, Symbol
782
+ >>> p1 = Point(0, 0)
783
+ >>> e1 = Ellipse(p1, 3, 1)
784
+ >>> e1.major
785
+ 3
786
+
787
+ >>> a = Symbol('a')
788
+ >>> b = Symbol('b')
789
+ >>> Ellipse(p1, a, b).major
790
+ a
791
+ >>> Ellipse(p1, b, a).major
792
+ b
793
+
794
+ >>> m = Symbol('m')
795
+ >>> M = m + 1
796
+ >>> Ellipse(p1, m, M).major
797
+ m + 1
798
+
799
+ """
800
+ ab = self.args[1:3]
801
+ if len(ab) == 1:
802
+ return ab[0]
803
+ a, b = ab
804
+ o = b - a < 0
805
+ if o == True:
806
+ return a
807
+ elif o == False:
808
+ return b
809
+ return self.hradius
810
+
811
+ @property
812
+ def minor(self):
813
+ """Shorter axis of the ellipse (if it can be determined) else vradius.
814
+
815
+ Returns
816
+ =======
817
+
818
+ minor : number or expression
819
+
820
+ See Also
821
+ ========
822
+
823
+ hradius, vradius, major
824
+
825
+ Examples
826
+ ========
827
+
828
+ >>> from sympy import Point, Ellipse, Symbol
829
+ >>> p1 = Point(0, 0)
830
+ >>> e1 = Ellipse(p1, 3, 1)
831
+ >>> e1.minor
832
+ 1
833
+
834
+ >>> a = Symbol('a')
835
+ >>> b = Symbol('b')
836
+ >>> Ellipse(p1, a, b).minor
837
+ b
838
+ >>> Ellipse(p1, b, a).minor
839
+ a
840
+
841
+ >>> m = Symbol('m')
842
+ >>> M = m + 1
843
+ >>> Ellipse(p1, m, M).minor
844
+ m
845
+
846
+ """
847
+ ab = self.args[1:3]
848
+ if len(ab) == 1:
849
+ return ab[0]
850
+ a, b = ab
851
+ o = a - b < 0
852
+ if o == True:
853
+ return a
854
+ elif o == False:
855
+ return b
856
+ return self.vradius
857
+
858
+ def normal_lines(self, p, prec=None):
859
+ """Normal lines between `p` and the ellipse.
860
+
861
+ Parameters
862
+ ==========
863
+
864
+ p : Point
865
+
866
+ Returns
867
+ =======
868
+
869
+ normal_lines : list with 1, 2 or 4 Lines
870
+
871
+ Examples
872
+ ========
873
+
874
+ >>> from sympy import Point, Ellipse
875
+ >>> e = Ellipse((0, 0), 2, 3)
876
+ >>> c = e.center
877
+ >>> e.normal_lines(c + Point(1, 0))
878
+ [Line2D(Point2D(0, 0), Point2D(1, 0))]
879
+ >>> e.normal_lines(c)
880
+ [Line2D(Point2D(0, 0), Point2D(0, 1)), Line2D(Point2D(0, 0), Point2D(1, 0))]
881
+
882
+ Off-axis points require the solution of a quartic equation. This
883
+ often leads to very large expressions that may be of little practical
884
+ use. An approximate solution of `prec` digits can be obtained by
885
+ passing in the desired value:
886
+
887
+ >>> e.normal_lines((3, 3), prec=2)
888
+ [Line2D(Point2D(-0.81, -2.7), Point2D(0.19, -1.2)),
889
+ Line2D(Point2D(1.5, -2.0), Point2D(2.5, -2.7))]
890
+
891
+ Whereas the above solution has an operation count of 12, the exact
892
+ solution has an operation count of 2020.
893
+ """
894
+ p = Point(p, dim=2)
895
+
896
+ # XXX change True to something like self.angle == 0 if the arbitrarily
897
+ # rotated ellipse is introduced.
898
+ # https://github.com/sympy/sympy/issues/2815)
899
+ if True:
900
+ rv = []
901
+ if p.x == self.center.x:
902
+ rv.append(Line(self.center, slope=oo))
903
+ if p.y == self.center.y:
904
+ rv.append(Line(self.center, slope=0))
905
+ if rv:
906
+ # at these special orientations of p either 1 or 2 normals
907
+ # exist and we are done
908
+ return rv
909
+
910
+ # find the 4 normal points and construct lines through them with
911
+ # the corresponding slope
912
+ eq = self.equation(x, y)
913
+ dydx = idiff(eq, y, x)
914
+ norm = -1/dydx
915
+ slope = Line(p, (x, y)).slope
916
+ seq = slope - norm
917
+
918
+ # TODO: Replace solve with solveset, when this line is tested
919
+ yis = solve(seq, y)[0]
920
+ xeq = eq.subs(y, yis).as_numer_denom()[0].expand()
921
+ if len(xeq.free_symbols) == 1:
922
+ try:
923
+ # this is so much faster, it's worth a try
924
+ xsol = Poly(xeq, x).real_roots()
925
+ except (DomainError, PolynomialError, NotImplementedError):
926
+ # TODO: Replace solve with solveset, when these lines are tested
927
+ xsol = _nsort(solve(xeq, x), separated=True)[0]
928
+ points = [Point(i, solve(eq.subs(x, i), y)[0]) for i in xsol]
929
+ else:
930
+ raise NotImplementedError(
931
+ 'intersections for the general ellipse are not supported')
932
+ slopes = [norm.subs(zip((x, y), pt.args)) for pt in points]
933
+ if prec is not None:
934
+ points = [pt.n(prec) for pt in points]
935
+ slopes = [i if _not_a_coeff(i) else i.n(prec) for i in slopes]
936
+ return [Line(pt, slope=s) for pt, s in zip(points, slopes)]
937
+
938
+ @property
939
+ def periapsis(self):
940
+ """The periapsis of the ellipse.
941
+
942
+ The shortest distance between the focus and the contour.
943
+
944
+ Returns
945
+ =======
946
+
947
+ periapsis : number
948
+
949
+ See Also
950
+ ========
951
+
952
+ apoapsis : Returns greatest distance between focus and contour
953
+
954
+ Examples
955
+ ========
956
+
957
+ >>> from sympy import Point, Ellipse
958
+ >>> p1 = Point(0, 0)
959
+ >>> e1 = Ellipse(p1, 3, 1)
960
+ >>> e1.periapsis
961
+ 3 - 2*sqrt(2)
962
+
963
+ """
964
+ return self.major * (1 - self.eccentricity)
965
+
966
+ @property
967
+ def semilatus_rectum(self):
968
+ """
969
+ Calculates the semi-latus rectum of the Ellipse.
970
+
971
+ Semi-latus rectum is defined as one half of the chord through a
972
+ focus parallel to the conic section directrix of a conic section.
973
+
974
+ Returns
975
+ =======
976
+
977
+ semilatus_rectum : number
978
+
979
+ See Also
980
+ ========
981
+
982
+ apoapsis : Returns greatest distance between focus and contour
983
+
984
+ periapsis : The shortest distance between the focus and the contour
985
+
986
+ Examples
987
+ ========
988
+
989
+ >>> from sympy import Point, Ellipse
990
+ >>> p1 = Point(0, 0)
991
+ >>> e1 = Ellipse(p1, 3, 1)
992
+ >>> e1.semilatus_rectum
993
+ 1/3
994
+
995
+ References
996
+ ==========
997
+
998
+ .. [1] https://mathworld.wolfram.com/SemilatusRectum.html
999
+ .. [2] https://en.wikipedia.org/wiki/Ellipse#Semi-latus_rectum
1000
+
1001
+ """
1002
+ return self.major * (1 - self.eccentricity ** 2)
1003
+
1004
+ def auxiliary_circle(self):
1005
+ """Returns a Circle whose diameter is the major axis of the ellipse.
1006
+
1007
+ Examples
1008
+ ========
1009
+
1010
+ >>> from sympy import Ellipse, Point, symbols
1011
+ >>> c = Point(1, 2)
1012
+ >>> Ellipse(c, 8, 7).auxiliary_circle()
1013
+ Circle(Point2D(1, 2), 8)
1014
+ >>> a, b = symbols('a b')
1015
+ >>> Ellipse(c, a, b).auxiliary_circle()
1016
+ Circle(Point2D(1, 2), Max(a, b))
1017
+ """
1018
+ return Circle(self.center, Max(self.hradius, self.vradius))
1019
+
1020
+ def director_circle(self):
1021
+ """
1022
+ Returns a Circle consisting of all points where two perpendicular
1023
+ tangent lines to the ellipse cross each other.
1024
+
1025
+ Returns
1026
+ =======
1027
+
1028
+ Circle
1029
+ A director circle returned as a geometric object.
1030
+
1031
+ Examples
1032
+ ========
1033
+
1034
+ >>> from sympy import Ellipse, Point, symbols
1035
+ >>> c = Point(3,8)
1036
+ >>> Ellipse(c, 7, 9).director_circle()
1037
+ Circle(Point2D(3, 8), sqrt(130))
1038
+ >>> a, b = symbols('a b')
1039
+ >>> Ellipse(c, a, b).director_circle()
1040
+ Circle(Point2D(3, 8), sqrt(a**2 + b**2))
1041
+
1042
+ References
1043
+ ==========
1044
+
1045
+ .. [1] https://en.wikipedia.org/wiki/Director_circle
1046
+
1047
+ """
1048
+ return Circle(self.center, sqrt(self.hradius**2 + self.vradius**2))
1049
+
1050
+ def plot_interval(self, parameter='t'):
1051
+ """The plot interval for the default geometric plot of the Ellipse.
1052
+
1053
+ Parameters
1054
+ ==========
1055
+
1056
+ parameter : str, optional
1057
+ Default value is 't'.
1058
+
1059
+ Returns
1060
+ =======
1061
+
1062
+ plot_interval : list
1063
+ [parameter, lower_bound, upper_bound]
1064
+
1065
+ Examples
1066
+ ========
1067
+
1068
+ >>> from sympy import Point, Ellipse
1069
+ >>> e1 = Ellipse(Point(0, 0), 3, 2)
1070
+ >>> e1.plot_interval()
1071
+ [t, -pi, pi]
1072
+
1073
+ """
1074
+ t = _symbol(parameter, real=True)
1075
+ return [t, -S.Pi, S.Pi]
1076
+
1077
+ def random_point(self, seed=None):
1078
+ """A random point on the ellipse.
1079
+
1080
+ Returns
1081
+ =======
1082
+
1083
+ point : Point
1084
+
1085
+ Examples
1086
+ ========
1087
+
1088
+ >>> from sympy import Point, Ellipse
1089
+ >>> e1 = Ellipse(Point(0, 0), 3, 2)
1090
+ >>> e1.random_point() # gives some random point
1091
+ Point2D(...)
1092
+ >>> p1 = e1.random_point(seed=0); p1.n(2)
1093
+ Point2D(2.1, 1.4)
1094
+
1095
+ Notes
1096
+ =====
1097
+
1098
+ When creating a random point, one may simply replace the
1099
+ parameter with a random number. When doing so, however, the
1100
+ random number should be made a Rational or else the point
1101
+ may not test as being in the ellipse:
1102
+
1103
+ >>> from sympy.abc import t
1104
+ >>> from sympy import Rational
1105
+ >>> arb = e1.arbitrary_point(t); arb
1106
+ Point2D(3*cos(t), 2*sin(t))
1107
+ >>> arb.subs(t, .1) in e1
1108
+ False
1109
+ >>> arb.subs(t, Rational(.1)) in e1
1110
+ True
1111
+ >>> arb.subs(t, Rational('.1')) in e1
1112
+ True
1113
+
1114
+ See Also
1115
+ ========
1116
+ sympy.geometry.point.Point
1117
+ arbitrary_point : Returns parameterized point on ellipse
1118
+ """
1119
+ t = _symbol('t', real=True)
1120
+ x, y = self.arbitrary_point(t).args
1121
+ # get a random value in [-1, 1) corresponding to cos(t)
1122
+ # and confirm that it will test as being in the ellipse
1123
+ if seed is not None:
1124
+ rng = random.Random(seed)
1125
+ else:
1126
+ rng = random
1127
+ # simplify this now or else the Float will turn s into a Float
1128
+ r = Rational(rng.random())
1129
+ c = 2*r - 1
1130
+ s = sqrt(1 - c**2)
1131
+ return Point(x.subs(cos(t), c), y.subs(sin(t), s))
1132
+
1133
+ def reflect(self, line):
1134
+ """Override GeometryEntity.reflect since the radius
1135
+ is not a GeometryEntity.
1136
+
1137
+ Examples
1138
+ ========
1139
+
1140
+ >>> from sympy import Circle, Line
1141
+ >>> Circle((0, 1), 1).reflect(Line((0, 0), (1, 1)))
1142
+ Circle(Point2D(1, 0), -1)
1143
+ >>> from sympy import Ellipse, Line, Point
1144
+ >>> Ellipse(Point(3, 4), 1, 3).reflect(Line(Point(0, -4), Point(5, 0)))
1145
+ Traceback (most recent call last):
1146
+ ...
1147
+ NotImplementedError:
1148
+ General Ellipse is not supported but the equation of the reflected
1149
+ Ellipse is given by the zeros of: f(x, y) = (9*x/41 + 40*y/41 +
1150
+ 37/41)**2 + (40*x/123 - 3*y/41 - 364/123)**2 - 1
1151
+
1152
+ Notes
1153
+ =====
1154
+
1155
+ Until the general ellipse (with no axis parallel to the x-axis) is
1156
+ supported a NotImplemented error is raised and the equation whose
1157
+ zeros define the rotated ellipse is given.
1158
+
1159
+ """
1160
+
1161
+ if line.slope in (0, oo):
1162
+ c = self.center
1163
+ c = c.reflect(line)
1164
+ return self.func(c, -self.hradius, self.vradius)
1165
+ else:
1166
+ x, y = [uniquely_named_symbol(
1167
+ name, (self, line), modify=lambda s: '_' + s, real=True)
1168
+ for name in 'xy']
1169
+ expr = self.equation(x, y)
1170
+ p = Point(x, y).reflect(line)
1171
+ result = expr.subs(zip((x, y), p.args
1172
+ ), simultaneous=True)
1173
+ raise NotImplementedError(filldedent(
1174
+ 'General Ellipse is not supported but the equation '
1175
+ 'of the reflected Ellipse is given by the zeros of: ' +
1176
+ "f(%s, %s) = %s" % (str(x), str(y), str(result))))
1177
+
1178
+ def rotate(self, angle=0, pt=None):
1179
+ """Rotate ``angle`` radians counterclockwise about Point ``pt``.
1180
+
1181
+ Note: since the general ellipse is not supported, only rotations that
1182
+ are integer multiples of pi/2 are allowed.
1183
+
1184
+ Examples
1185
+ ========
1186
+
1187
+ >>> from sympy import Ellipse, pi
1188
+ >>> Ellipse((1, 0), 2, 1).rotate(pi/2)
1189
+ Ellipse(Point2D(0, 1), 1, 2)
1190
+ >>> Ellipse((1, 0), 2, 1).rotate(pi)
1191
+ Ellipse(Point2D(-1, 0), 2, 1)
1192
+ """
1193
+ if self.hradius == self.vradius:
1194
+ return self.func(self.center.rotate(angle, pt), self.hradius)
1195
+ if (angle/S.Pi).is_integer:
1196
+ return super().rotate(angle, pt)
1197
+ if (2*angle/S.Pi).is_integer:
1198
+ return self.func(self.center.rotate(angle, pt), self.vradius, self.hradius)
1199
+ # XXX see https://github.com/sympy/sympy/issues/2815 for general ellipes
1200
+ raise NotImplementedError('Only rotations of pi/2 are currently supported for Ellipse.')
1201
+
1202
+ def scale(self, x=1, y=1, pt=None):
1203
+ """Override GeometryEntity.scale since it is the major and minor
1204
+ axes which must be scaled and they are not GeometryEntities.
1205
+
1206
+ Examples
1207
+ ========
1208
+
1209
+ >>> from sympy import Ellipse
1210
+ >>> Ellipse((0, 0), 2, 1).scale(2, 4)
1211
+ Circle(Point2D(0, 0), 4)
1212
+ >>> Ellipse((0, 0), 2, 1).scale(2)
1213
+ Ellipse(Point2D(0, 0), 4, 1)
1214
+ """
1215
+ c = self.center
1216
+ if pt:
1217
+ pt = Point(pt, dim=2)
1218
+ return self.translate(*(-pt).args).scale(x, y).translate(*pt.args)
1219
+ h = self.hradius
1220
+ v = self.vradius
1221
+ return self.func(c.scale(x, y), hradius=h*x, vradius=v*y)
1222
+
1223
+ def tangent_lines(self, p):
1224
+ """Tangent lines between `p` and the ellipse.
1225
+
1226
+ If `p` is on the ellipse, returns the tangent line through point `p`.
1227
+ Otherwise, returns the tangent line(s) from `p` to the ellipse, or
1228
+ None if no tangent line is possible (e.g., `p` inside ellipse).
1229
+
1230
+ Parameters
1231
+ ==========
1232
+
1233
+ p : Point
1234
+
1235
+ Returns
1236
+ =======
1237
+
1238
+ tangent_lines : list with 1 or 2 Lines
1239
+
1240
+ Raises
1241
+ ======
1242
+
1243
+ NotImplementedError
1244
+ Can only find tangent lines for a point, `p`, on the ellipse.
1245
+
1246
+ See Also
1247
+ ========
1248
+
1249
+ sympy.geometry.point.Point, sympy.geometry.line.Line
1250
+
1251
+ Examples
1252
+ ========
1253
+
1254
+ >>> from sympy import Point, Ellipse
1255
+ >>> e1 = Ellipse(Point(0, 0), 3, 2)
1256
+ >>> e1.tangent_lines(Point(3, 0))
1257
+ [Line2D(Point2D(3, 0), Point2D(3, -12))]
1258
+
1259
+ """
1260
+ p = Point(p, dim=2)
1261
+ if self.encloses_point(p):
1262
+ return []
1263
+
1264
+ if p in self:
1265
+ delta = self.center - p
1266
+ rise = (self.vradius**2)*delta.x
1267
+ run = -(self.hradius**2)*delta.y
1268
+ p2 = Point(simplify(p.x + run),
1269
+ simplify(p.y + rise))
1270
+ return [Line(p, p2)]
1271
+ else:
1272
+ if len(self.foci) == 2:
1273
+ f1, f2 = self.foci
1274
+ maj = self.hradius
1275
+ test = (2*maj -
1276
+ Point.distance(f1, p) -
1277
+ Point.distance(f2, p))
1278
+ else:
1279
+ test = self.radius - Point.distance(self.center, p)
1280
+ if test.is_number and test.is_positive:
1281
+ return []
1282
+ # else p is outside the ellipse or we can't tell. In case of the
1283
+ # latter, the solutions returned will only be valid if
1284
+ # the point is not inside the ellipse; if it is, nan will result.
1285
+ eq = self.equation(x, y)
1286
+ dydx = idiff(eq, y, x)
1287
+ slope = Line(p, Point(x, y)).slope
1288
+
1289
+ # TODO: Replace solve with solveset, when this line is tested
1290
+ tangent_points = solve([slope - dydx, eq], [x, y])
1291
+
1292
+ # handle horizontal and vertical tangent lines
1293
+ if len(tangent_points) == 1:
1294
+ if tangent_points[0][
1295
+ 0] == p.x or tangent_points[0][1] == p.y:
1296
+ return [Line(p, p + Point(1, 0)), Line(p, p + Point(0, 1))]
1297
+ else:
1298
+ return [Line(p, p + Point(0, 1)), Line(p, tangent_points[0])]
1299
+
1300
+ # others
1301
+ return [Line(p, tangent_points[0]), Line(p, tangent_points[1])]
1302
+
1303
+ @property
1304
+ def vradius(self):
1305
+ """The vertical radius of the ellipse.
1306
+
1307
+ Returns
1308
+ =======
1309
+
1310
+ vradius : number
1311
+
1312
+ See Also
1313
+ ========
1314
+
1315
+ hradius, major, minor
1316
+
1317
+ Examples
1318
+ ========
1319
+
1320
+ >>> from sympy import Point, Ellipse
1321
+ >>> p1 = Point(0, 0)
1322
+ >>> e1 = Ellipse(p1, 3, 1)
1323
+ >>> e1.vradius
1324
+ 1
1325
+
1326
+ """
1327
+ return self.args[2]
1328
+
1329
+
1330
+ def second_moment_of_area(self, point=None):
1331
+ """Returns the second moment and product moment area of an ellipse.
1332
+
1333
+ Parameters
1334
+ ==========
1335
+
1336
+ point : Point, two-tuple of sympifiable objects, or None(default=None)
1337
+ point is the point about which second moment of area is to be found.
1338
+ If "point=None" it will be calculated about the axis passing through the
1339
+ centroid of the ellipse.
1340
+
1341
+ Returns
1342
+ =======
1343
+
1344
+ I_xx, I_yy, I_xy : number or SymPy expression
1345
+ I_xx, I_yy are second moment of area of an ellise.
1346
+ I_xy is product moment of area of an ellipse.
1347
+
1348
+ Examples
1349
+ ========
1350
+
1351
+ >>> from sympy import Point, Ellipse
1352
+ >>> p1 = Point(0, 0)
1353
+ >>> e1 = Ellipse(p1, 3, 1)
1354
+ >>> e1.second_moment_of_area()
1355
+ (3*pi/4, 27*pi/4, 0)
1356
+
1357
+ References
1358
+ ==========
1359
+
1360
+ .. [1] https://en.wikipedia.org/wiki/List_of_second_moments_of_area
1361
+
1362
+ """
1363
+
1364
+ I_xx = (S.Pi*(self.hradius)*(self.vradius**3))/4
1365
+ I_yy = (S.Pi*(self.hradius**3)*(self.vradius))/4
1366
+ I_xy = 0
1367
+
1368
+ if point is None:
1369
+ return I_xx, I_yy, I_xy
1370
+
1371
+ # parallel axis theorem
1372
+ I_xx = I_xx + self.area*((point[1] - self.center.y)**2)
1373
+ I_yy = I_yy + self.area*((point[0] - self.center.x)**2)
1374
+ I_xy = I_xy + self.area*(point[0] - self.center.x)*(point[1] - self.center.y)
1375
+
1376
+ return I_xx, I_yy, I_xy
1377
+
1378
+
1379
+ def polar_second_moment_of_area(self):
1380
+ """Returns the polar second moment of area of an Ellipse
1381
+
1382
+ It is a constituent of the second moment of area, linked through
1383
+ the perpendicular axis theorem. While the planar second moment of
1384
+ area describes an object's resistance to deflection (bending) when
1385
+ subjected to a force applied to a plane parallel to the central
1386
+ axis, the polar second moment of area describes an object's
1387
+ resistance to deflection when subjected to a moment applied in a
1388
+ plane perpendicular to the object's central axis (i.e. parallel to
1389
+ the cross-section)
1390
+
1391
+ Examples
1392
+ ========
1393
+
1394
+ >>> from sympy import symbols, Circle, Ellipse
1395
+ >>> c = Circle((5, 5), 4)
1396
+ >>> c.polar_second_moment_of_area()
1397
+ 128*pi
1398
+ >>> a, b = symbols('a, b')
1399
+ >>> e = Ellipse((0, 0), a, b)
1400
+ >>> e.polar_second_moment_of_area()
1401
+ pi*a**3*b/4 + pi*a*b**3/4
1402
+
1403
+ References
1404
+ ==========
1405
+
1406
+ .. [1] https://en.wikipedia.org/wiki/Polar_moment_of_inertia
1407
+
1408
+ """
1409
+ second_moment = self.second_moment_of_area()
1410
+ return second_moment[0] + second_moment[1]
1411
+
1412
+
1413
+ def section_modulus(self, point=None):
1414
+ """Returns a tuple with the section modulus of an ellipse
1415
+
1416
+ Section modulus is a geometric property of an ellipse defined as the
1417
+ ratio of second moment of area to the distance of the extreme end of
1418
+ the ellipse from the centroidal axis.
1419
+
1420
+ Parameters
1421
+ ==========
1422
+
1423
+ point : Point, two-tuple of sympifyable objects, or None(default=None)
1424
+ point is the point at which section modulus is to be found.
1425
+ If "point=None" section modulus will be calculated for the
1426
+ point farthest from the centroidal axis of the ellipse.
1427
+
1428
+ Returns
1429
+ =======
1430
+
1431
+ S_x, S_y: numbers or SymPy expressions
1432
+ S_x is the section modulus with respect to the x-axis
1433
+ S_y is the section modulus with respect to the y-axis
1434
+ A negative sign indicates that the section modulus is
1435
+ determined for a point below the centroidal axis.
1436
+
1437
+ Examples
1438
+ ========
1439
+
1440
+ >>> from sympy import Symbol, Ellipse, Circle, Point2D
1441
+ >>> d = Symbol('d', positive=True)
1442
+ >>> c = Circle((0, 0), d/2)
1443
+ >>> c.section_modulus()
1444
+ (pi*d**3/32, pi*d**3/32)
1445
+ >>> e = Ellipse(Point2D(0, 0), 2, 4)
1446
+ >>> e.section_modulus()
1447
+ (8*pi, 4*pi)
1448
+ >>> e.section_modulus((2, 2))
1449
+ (16*pi, 4*pi)
1450
+
1451
+ References
1452
+ ==========
1453
+
1454
+ .. [1] https://en.wikipedia.org/wiki/Section_modulus
1455
+
1456
+ """
1457
+ x_c, y_c = self.center
1458
+ if point is None:
1459
+ # taking x and y as maximum distances from centroid
1460
+ x_min, y_min, x_max, y_max = self.bounds
1461
+ y = max(y_c - y_min, y_max - y_c)
1462
+ x = max(x_c - x_min, x_max - x_c)
1463
+ else:
1464
+ # taking x and y as distances of the given point from the center
1465
+ point = Point2D(point)
1466
+ y = point.y - y_c
1467
+ x = point.x - x_c
1468
+
1469
+ second_moment = self.second_moment_of_area()
1470
+ S_x = second_moment[0]/y
1471
+ S_y = second_moment[1]/x
1472
+
1473
+ return S_x, S_y
1474
+
1475
+
1476
+ class Circle(Ellipse):
1477
+ """A circle in space.
1478
+
1479
+ Constructed simply from a center and a radius, from three
1480
+ non-collinear points, or the equation of a circle.
1481
+
1482
+ Parameters
1483
+ ==========
1484
+
1485
+ center : Point
1486
+ radius : number or SymPy expression
1487
+ points : sequence of three Points
1488
+ equation : equation of a circle
1489
+
1490
+ Attributes
1491
+ ==========
1492
+
1493
+ radius (synonymous with hradius, vradius, major and minor)
1494
+ circumference
1495
+ equation
1496
+
1497
+ Raises
1498
+ ======
1499
+
1500
+ GeometryError
1501
+ When the given equation is not that of a circle.
1502
+ When trying to construct circle from incorrect parameters.
1503
+
1504
+ See Also
1505
+ ========
1506
+
1507
+ Ellipse, sympy.geometry.point.Point
1508
+
1509
+ Examples
1510
+ ========
1511
+
1512
+ >>> from sympy import Point, Circle, Eq
1513
+ >>> from sympy.abc import x, y, a, b
1514
+
1515
+ A circle constructed from a center and radius:
1516
+
1517
+ >>> c1 = Circle(Point(0, 0), 5)
1518
+ >>> c1.hradius, c1.vradius, c1.radius
1519
+ (5, 5, 5)
1520
+
1521
+ A circle constructed from three points:
1522
+
1523
+ >>> c2 = Circle(Point(0, 0), Point(1, 1), Point(1, 0))
1524
+ >>> c2.hradius, c2.vradius, c2.radius, c2.center
1525
+ (sqrt(2)/2, sqrt(2)/2, sqrt(2)/2, Point2D(1/2, 1/2))
1526
+
1527
+ A circle can be constructed from an equation in the form
1528
+ `a*x**2 + by**2 + gx + hy + c = 0`, too:
1529
+
1530
+ >>> Circle(x**2 + y**2 - 25)
1531
+ Circle(Point2D(0, 0), 5)
1532
+
1533
+ If the variables corresponding to x and y are named something
1534
+ else, their name or symbol can be supplied:
1535
+
1536
+ >>> Circle(Eq(a**2 + b**2, 25), x='a', y=b)
1537
+ Circle(Point2D(0, 0), 5)
1538
+ """
1539
+
1540
+ def __new__(cls, *args, **kwargs):
1541
+ evaluate = kwargs.get('evaluate', global_parameters.evaluate)
1542
+ if len(args) == 1 and isinstance(args[0], (Expr, Eq)):
1543
+ x = kwargs.get('x', 'x')
1544
+ y = kwargs.get('y', 'y')
1545
+ equation = args[0].expand()
1546
+ if isinstance(equation, Eq):
1547
+ equation = equation.lhs - equation.rhs
1548
+ x = find(x, equation)
1549
+ y = find(y, equation)
1550
+
1551
+ try:
1552
+ a, b, c, d, e = linear_coeffs(equation, x**2, y**2, x, y)
1553
+ except ValueError:
1554
+ raise GeometryError("The given equation is not that of a circle.")
1555
+
1556
+ if S.Zero in (a, b) or a != b:
1557
+ raise GeometryError("The given equation is not that of a circle.")
1558
+
1559
+ center_x = -c/a/2
1560
+ center_y = -d/b/2
1561
+ r2 = (center_x**2) + (center_y**2) - e/a
1562
+
1563
+ return Circle((center_x, center_y), sqrt(r2), evaluate=evaluate)
1564
+
1565
+ else:
1566
+ c, r = None, None
1567
+ if len(args) == 3:
1568
+ args = [Point(a, dim=2, evaluate=evaluate) for a in args]
1569
+ t = Triangle(*args)
1570
+ if not isinstance(t, Triangle):
1571
+ return t
1572
+ c = t.circumcenter
1573
+ r = t.circumradius
1574
+ elif len(args) == 2:
1575
+ # Assume (center, radius) pair
1576
+ c = Point(args[0], dim=2, evaluate=evaluate)
1577
+ r = args[1]
1578
+ # this will prohibit imaginary radius
1579
+ try:
1580
+ r = Point(r, 0, evaluate=evaluate).x
1581
+ except ValueError:
1582
+ raise GeometryError("Circle with imaginary radius is not permitted")
1583
+
1584
+ if not (c is None or r is None):
1585
+ if r == 0:
1586
+ return c
1587
+ return GeometryEntity.__new__(cls, c, r, **kwargs)
1588
+
1589
+ raise GeometryError("Circle.__new__ received unknown arguments")
1590
+
1591
+ def _eval_evalf(self, prec=15, **options):
1592
+ pt, r = self.args
1593
+ dps = prec_to_dps(prec)
1594
+ pt = pt.evalf(n=dps, **options)
1595
+ r = r.evalf(n=dps, **options)
1596
+ return self.func(pt, r, evaluate=False)
1597
+
1598
+ @property
1599
+ def circumference(self):
1600
+ """The circumference of the circle.
1601
+
1602
+ Returns
1603
+ =======
1604
+
1605
+ circumference : number or SymPy expression
1606
+
1607
+ Examples
1608
+ ========
1609
+
1610
+ >>> from sympy import Point, Circle
1611
+ >>> c1 = Circle(Point(3, 4), 6)
1612
+ >>> c1.circumference
1613
+ 12*pi
1614
+
1615
+ """
1616
+ return 2 * S.Pi * self.radius
1617
+
1618
+ def equation(self, x='x', y='y'):
1619
+ """The equation of the circle.
1620
+
1621
+ Parameters
1622
+ ==========
1623
+
1624
+ x : str or Symbol, optional
1625
+ Default value is 'x'.
1626
+ y : str or Symbol, optional
1627
+ Default value is 'y'.
1628
+
1629
+ Returns
1630
+ =======
1631
+
1632
+ equation : SymPy expression
1633
+
1634
+ Examples
1635
+ ========
1636
+
1637
+ >>> from sympy import Point, Circle
1638
+ >>> c1 = Circle(Point(0, 0), 5)
1639
+ >>> c1.equation()
1640
+ x**2 + y**2 - 25
1641
+
1642
+ """
1643
+ x = _symbol(x, real=True)
1644
+ y = _symbol(y, real=True)
1645
+ t1 = (x - self.center.x)**2
1646
+ t2 = (y - self.center.y)**2
1647
+ return t1 + t2 - self.major**2
1648
+
1649
+ def intersection(self, o):
1650
+ """The intersection of this circle with another geometrical entity.
1651
+
1652
+ Parameters
1653
+ ==========
1654
+
1655
+ o : GeometryEntity
1656
+
1657
+ Returns
1658
+ =======
1659
+
1660
+ intersection : list of GeometryEntities
1661
+
1662
+ Examples
1663
+ ========
1664
+
1665
+ >>> from sympy import Point, Circle, Line, Ray
1666
+ >>> p1, p2, p3 = Point(0, 0), Point(5, 5), Point(6, 0)
1667
+ >>> p4 = Point(5, 0)
1668
+ >>> c1 = Circle(p1, 5)
1669
+ >>> c1.intersection(p2)
1670
+ []
1671
+ >>> c1.intersection(p4)
1672
+ [Point2D(5, 0)]
1673
+ >>> c1.intersection(Ray(p1, p2))
1674
+ [Point2D(5*sqrt(2)/2, 5*sqrt(2)/2)]
1675
+ >>> c1.intersection(Line(p2, p3))
1676
+ []
1677
+
1678
+ """
1679
+ return Ellipse.intersection(self, o)
1680
+
1681
+ @property
1682
+ def radius(self):
1683
+ """The radius of the circle.
1684
+
1685
+ Returns
1686
+ =======
1687
+
1688
+ radius : number or SymPy expression
1689
+
1690
+ See Also
1691
+ ========
1692
+
1693
+ Ellipse.major, Ellipse.minor, Ellipse.hradius, Ellipse.vradius
1694
+
1695
+ Examples
1696
+ ========
1697
+
1698
+ >>> from sympy import Point, Circle
1699
+ >>> c1 = Circle(Point(3, 4), 6)
1700
+ >>> c1.radius
1701
+ 6
1702
+
1703
+ """
1704
+ return self.args[1]
1705
+
1706
+ def reflect(self, line):
1707
+ """Override GeometryEntity.reflect since the radius
1708
+ is not a GeometryEntity.
1709
+
1710
+ Examples
1711
+ ========
1712
+
1713
+ >>> from sympy import Circle, Line
1714
+ >>> Circle((0, 1), 1).reflect(Line((0, 0), (1, 1)))
1715
+ Circle(Point2D(1, 0), -1)
1716
+ """
1717
+ c = self.center
1718
+ c = c.reflect(line)
1719
+ return self.func(c, -self.radius)
1720
+
1721
+ def scale(self, x=1, y=1, pt=None):
1722
+ """Override GeometryEntity.scale since the radius
1723
+ is not a GeometryEntity.
1724
+
1725
+ Examples
1726
+ ========
1727
+
1728
+ >>> from sympy import Circle
1729
+ >>> Circle((0, 0), 1).scale(2, 2)
1730
+ Circle(Point2D(0, 0), 2)
1731
+ >>> Circle((0, 0), 1).scale(2, 4)
1732
+ Ellipse(Point2D(0, 0), 2, 4)
1733
+ """
1734
+ c = self.center
1735
+ if pt:
1736
+ pt = Point(pt, dim=2)
1737
+ return self.translate(*(-pt).args).scale(x, y).translate(*pt.args)
1738
+ c = c.scale(x, y)
1739
+ x, y = [abs(i) for i in (x, y)]
1740
+ if x == y:
1741
+ return self.func(c, x*self.radius)
1742
+ h = v = self.radius
1743
+ return Ellipse(c, hradius=h*x, vradius=v*y)
1744
+
1745
+ @property
1746
+ def vradius(self):
1747
+ """
1748
+ This Ellipse property is an alias for the Circle's radius.
1749
+
1750
+ Whereas hradius, major and minor can use Ellipse's conventions,
1751
+ the vradius does not exist for a circle. It is always a positive
1752
+ value in order that the Circle, like Polygons, will have an
1753
+ area that can be positive or negative as determined by the sign
1754
+ of the hradius.
1755
+
1756
+ Examples
1757
+ ========
1758
+
1759
+ >>> from sympy import Point, Circle
1760
+ >>> c1 = Circle(Point(3, 4), 6)
1761
+ >>> c1.vradius
1762
+ 6
1763
+ """
1764
+ return abs(self.radius)
1765
+
1766
+
1767
+ from .polygon import Polygon, Triangle
janus/lib/python3.10/site-packages/sympy/geometry/entity.py ADDED
@@ -0,0 +1,641 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The definition of the base geometrical entity with attributes common to
2
+ all derived geometrical entities.
3
+
4
+ Contains
5
+ ========
6
+
7
+ GeometryEntity
8
+ GeometricSet
9
+
10
+ Notes
11
+ =====
12
+
13
+ A GeometryEntity is any object that has special geometric properties.
14
+ A GeometrySet is a superclass of any GeometryEntity that can also
15
+ be viewed as a sympy.sets.Set. In particular, points are the only
16
+ GeometryEntity not considered a Set.
17
+
18
+ Rn is a GeometrySet representing n-dimensional Euclidean space. R2 and
19
+ R3 are currently the only ambient spaces implemented.
20
+
21
+ """
22
+ from __future__ import annotations
23
+
24
+ from sympy.core.basic import Basic
25
+ from sympy.core.containers import Tuple
26
+ from sympy.core.evalf import EvalfMixin, N
27
+ from sympy.core.numbers import oo
28
+ from sympy.core.symbol import Dummy
29
+ from sympy.core.sympify import sympify
30
+ from sympy.functions.elementary.trigonometric import cos, sin, atan
31
+ from sympy.matrices import eye
32
+ from sympy.multipledispatch import dispatch
33
+ from sympy.printing import sstr
34
+ from sympy.sets import Set, Union, FiniteSet
35
+ from sympy.sets.handlers.intersection import intersection_sets
36
+ from sympy.sets.handlers.union import union_sets
37
+ from sympy.solvers.solvers import solve
38
+ from sympy.utilities.misc import func_name
39
+ from sympy.utilities.iterables import is_sequence
40
+
41
+
42
+ # How entities are ordered; used by __cmp__ in GeometryEntity
43
+ ordering_of_classes = [
44
+ "Point2D",
45
+ "Point3D",
46
+ "Point",
47
+ "Segment2D",
48
+ "Ray2D",
49
+ "Line2D",
50
+ "Segment3D",
51
+ "Line3D",
52
+ "Ray3D",
53
+ "Segment",
54
+ "Ray",
55
+ "Line",
56
+ "Plane",
57
+ "Triangle",
58
+ "RegularPolygon",
59
+ "Polygon",
60
+ "Circle",
61
+ "Ellipse",
62
+ "Curve",
63
+ "Parabola"
64
+ ]
65
+
66
+
67
+ x, y = [Dummy('entity_dummy') for i in range(2)]
68
+ T = Dummy('entity_dummy', real=True)
69
+
70
+
71
+ class GeometryEntity(Basic, EvalfMixin):
72
+ """The base class for all geometrical entities.
73
+
74
+ This class does not represent any particular geometric entity, it only
75
+ provides the implementation of some methods common to all subclasses.
76
+
77
+ """
78
+
79
+ __slots__: tuple[str, ...] = ()
80
+
81
+ def __cmp__(self, other):
82
+ """Comparison of two GeometryEntities."""
83
+ n1 = self.__class__.__name__
84
+ n2 = other.__class__.__name__
85
+ c = (n1 > n2) - (n1 < n2)
86
+ if not c:
87
+ return 0
88
+
89
+ i1 = -1
90
+ for cls in self.__class__.__mro__:
91
+ try:
92
+ i1 = ordering_of_classes.index(cls.__name__)
93
+ break
94
+ except ValueError:
95
+ i1 = -1
96
+ if i1 == -1:
97
+ return c
98
+
99
+ i2 = -1
100
+ for cls in other.__class__.__mro__:
101
+ try:
102
+ i2 = ordering_of_classes.index(cls.__name__)
103
+ break
104
+ except ValueError:
105
+ i2 = -1
106
+ if i2 == -1:
107
+ return c
108
+
109
+ return (i1 > i2) - (i1 < i2)
110
+
111
+ def __contains__(self, other):
112
+ """Subclasses should implement this method for anything more complex than equality."""
113
+ if type(self) is type(other):
114
+ return self == other
115
+ raise NotImplementedError()
116
+
117
+ def __getnewargs__(self):
118
+ """Returns a tuple that will be passed to __new__ on unpickling."""
119
+ return tuple(self.args)
120
+
121
+ def __ne__(self, o):
122
+ """Test inequality of two geometrical entities."""
123
+ return not self == o
124
+
125
+ def __new__(cls, *args, **kwargs):
126
+ # Points are sequences, but they should not
127
+ # be converted to Tuples, so use this detection function instead.
128
+ def is_seq_and_not_point(a):
129
+ # we cannot use isinstance(a, Point) since we cannot import Point
130
+ if hasattr(a, 'is_Point') and a.is_Point:
131
+ return False
132
+ return is_sequence(a)
133
+
134
+ args = [Tuple(*a) if is_seq_and_not_point(a) else sympify(a) for a in args]
135
+ return Basic.__new__(cls, *args)
136
+
137
+ def __radd__(self, a):
138
+ """Implementation of reverse add method."""
139
+ return a.__add__(self)
140
+
141
+ def __rtruediv__(self, a):
142
+ """Implementation of reverse division method."""
143
+ return a.__truediv__(self)
144
+
145
+ def __repr__(self):
146
+ """String representation of a GeometryEntity that can be evaluated
147
+ by sympy."""
148
+ return type(self).__name__ + repr(self.args)
149
+
150
+ def __rmul__(self, a):
151
+ """Implementation of reverse multiplication method."""
152
+ return a.__mul__(self)
153
+
154
+ def __rsub__(self, a):
155
+ """Implementation of reverse subtraction method."""
156
+ return a.__sub__(self)
157
+
158
+ def __str__(self):
159
+ """String representation of a GeometryEntity."""
160
+ return type(self).__name__ + sstr(self.args)
161
+
162
+ def _eval_subs(self, old, new):
163
+ from sympy.geometry.point import Point, Point3D
164
+ if is_sequence(old) or is_sequence(new):
165
+ if isinstance(self, Point3D):
166
+ old = Point3D(old)
167
+ new = Point3D(new)
168
+ else:
169
+ old = Point(old)
170
+ new = Point(new)
171
+ return self._subs(old, new)
172
+
173
+ def _repr_svg_(self):
174
+ """SVG representation of a GeometryEntity suitable for IPython"""
175
+
176
+ try:
177
+ bounds = self.bounds
178
+ except (NotImplementedError, TypeError):
179
+ # if we have no SVG representation, return None so IPython
180
+ # will fall back to the next representation
181
+ return None
182
+
183
+ if not all(x.is_number and x.is_finite for x in bounds):
184
+ return None
185
+
186
+ svg_top = '''<svg xmlns="http://www.w3.org/2000/svg"
187
+ xmlns:xlink="http://www.w3.org/1999/xlink"
188
+ width="{1}" height="{2}" viewBox="{0}"
189
+ preserveAspectRatio="xMinYMin meet">
190
+ <defs>
191
+ <marker id="markerCircle" markerWidth="8" markerHeight="8"
192
+ refx="5" refy="5" markerUnits="strokeWidth">
193
+ <circle cx="5" cy="5" r="1.5" style="stroke: none; fill:#000000;"/>
194
+ </marker>
195
+ <marker id="markerArrow" markerWidth="13" markerHeight="13" refx="2" refy="4"
196
+ orient="auto" markerUnits="strokeWidth">
197
+ <path d="M2,2 L2,6 L6,4" style="fill: #000000;" />
198
+ </marker>
199
+ <marker id="markerReverseArrow" markerWidth="13" markerHeight="13" refx="6" refy="4"
200
+ orient="auto" markerUnits="strokeWidth">
201
+ <path d="M6,2 L6,6 L2,4" style="fill: #000000;" />
202
+ </marker>
203
+ </defs>'''
204
+
205
+ # Establish SVG canvas that will fit all the data + small space
206
+ xmin, ymin, xmax, ymax = map(N, bounds)
207
+ if xmin == xmax and ymin == ymax:
208
+ # This is a point; buffer using an arbitrary size
209
+ xmin, ymin, xmax, ymax = xmin - .5, ymin -.5, xmax + .5, ymax + .5
210
+ else:
211
+ # Expand bounds by a fraction of the data ranges
212
+ expand = 0.1 # or 10%; this keeps arrowheads in view (R plots use 4%)
213
+ widest_part = max([xmax - xmin, ymax - ymin])
214
+ expand_amount = widest_part * expand
215
+ xmin -= expand_amount
216
+ ymin -= expand_amount
217
+ xmax += expand_amount
218
+ ymax += expand_amount
219
+ dx = xmax - xmin
220
+ dy = ymax - ymin
221
+ width = min([max([100., dx]), 300])
222
+ height = min([max([100., dy]), 300])
223
+
224
+ scale_factor = 1. if max(width, height) == 0 else max(dx, dy) / max(width, height)
225
+ try:
226
+ svg = self._svg(scale_factor)
227
+ except (NotImplementedError, TypeError):
228
+ # if we have no SVG representation, return None so IPython
229
+ # will fall back to the next representation
230
+ return None
231
+
232
+ view_box = "{} {} {} {}".format(xmin, ymin, dx, dy)
233
+ transform = "matrix(1,0,0,-1,0,{})".format(ymax + ymin)
234
+ svg_top = svg_top.format(view_box, width, height)
235
+
236
+ return svg_top + (
237
+ '<g transform="{}">{}</g></svg>'
238
+ ).format(transform, svg)
239
+
240
+ def _svg(self, scale_factor=1., fill_color="#66cc99"):
241
+ """Returns SVG path element for the GeometryEntity.
242
+
243
+ Parameters
244
+ ==========
245
+
246
+ scale_factor : float
247
+ Multiplication factor for the SVG stroke-width. Default is 1.
248
+ fill_color : str, optional
249
+ Hex string for fill color. Default is "#66cc99".
250
+ """
251
+ raise NotImplementedError()
252
+
253
+ def _sympy_(self):
254
+ return self
255
+
256
+ @property
257
+ def ambient_dimension(self):
258
+ """What is the dimension of the space that the object is contained in?"""
259
+ raise NotImplementedError()
260
+
261
+ @property
262
+ def bounds(self):
263
+ """Return a tuple (xmin, ymin, xmax, ymax) representing the bounding
264
+ rectangle for the geometric figure.
265
+
266
+ """
267
+
268
+ raise NotImplementedError()
269
+
270
+ def encloses(self, o):
271
+ """
272
+ Return True if o is inside (not on or outside) the boundaries of self.
273
+
274
+ The object will be decomposed into Points and individual Entities need
275
+ only define an encloses_point method for their class.
276
+
277
+ See Also
278
+ ========
279
+
280
+ sympy.geometry.ellipse.Ellipse.encloses_point
281
+ sympy.geometry.polygon.Polygon.encloses_point
282
+
283
+ Examples
284
+ ========
285
+
286
+ >>> from sympy import RegularPolygon, Point, Polygon
287
+ >>> t = Polygon(*RegularPolygon(Point(0, 0), 1, 3).vertices)
288
+ >>> t2 = Polygon(*RegularPolygon(Point(0, 0), 2, 3).vertices)
289
+ >>> t2.encloses(t)
290
+ True
291
+ >>> t.encloses(t2)
292
+ False
293
+
294
+ """
295
+
296
+ from sympy.geometry.point import Point
297
+ from sympy.geometry.line import Segment, Ray, Line
298
+ from sympy.geometry.ellipse import Ellipse
299
+ from sympy.geometry.polygon import Polygon, RegularPolygon
300
+
301
+ if isinstance(o, Point):
302
+ return self.encloses_point(o)
303
+ elif isinstance(o, Segment):
304
+ return all(self.encloses_point(x) for x in o.points)
305
+ elif isinstance(o, (Ray, Line)):
306
+ return False
307
+ elif isinstance(o, Ellipse):
308
+ return self.encloses_point(o.center) and \
309
+ self.encloses_point(
310
+ Point(o.center.x + o.hradius, o.center.y)) and \
311
+ not self.intersection(o)
312
+ elif isinstance(o, Polygon):
313
+ if isinstance(o, RegularPolygon):
314
+ if not self.encloses_point(o.center):
315
+ return False
316
+ return all(self.encloses_point(v) for v in o.vertices)
317
+ raise NotImplementedError()
318
+
319
+ def equals(self, o):
320
+ return self == o
321
+
322
+ def intersection(self, o):
323
+ """
324
+ Returns a list of all of the intersections of self with o.
325
+
326
+ Notes
327
+ =====
328
+
329
+ An entity is not required to implement this method.
330
+
331
+ If two different types of entities can intersect, the item with
332
+ higher index in ordering_of_classes should implement
333
+ intersections with anything having a lower index.
334
+
335
+ See Also
336
+ ========
337
+
338
+ sympy.geometry.util.intersection
339
+
340
+ """
341
+ raise NotImplementedError()
342
+
343
+ def is_similar(self, other):
344
+ """Is this geometrical entity similar to another geometrical entity?
345
+
346
+ Two entities are similar if a uniform scaling (enlarging or
347
+ shrinking) of one of the entities will allow one to obtain the other.
348
+
349
+ Notes
350
+ =====
351
+
352
+ This method is not intended to be used directly but rather
353
+ through the `are_similar` function found in util.py.
354
+ An entity is not required to implement this method.
355
+ If two different types of entities can be similar, it is only
356
+ required that one of them be able to determine this.
357
+
358
+ See Also
359
+ ========
360
+
361
+ scale
362
+
363
+ """
364
+ raise NotImplementedError()
365
+
366
+ def reflect(self, line):
367
+ """
368
+ Reflects an object across a line.
369
+
370
+ Parameters
371
+ ==========
372
+
373
+ line: Line
374
+
375
+ Examples
376
+ ========
377
+
378
+ >>> from sympy import pi, sqrt, Line, RegularPolygon
379
+ >>> l = Line((0, pi), slope=sqrt(2))
380
+ >>> pent = RegularPolygon((1, 2), 1, 5)
381
+ >>> rpent = pent.reflect(l)
382
+ >>> rpent
383
+ RegularPolygon(Point2D(-2*sqrt(2)*pi/3 - 1/3 + 4*sqrt(2)/3, 2/3 + 2*sqrt(2)/3 + 2*pi/3), -1, 5, -atan(2*sqrt(2)) + 3*pi/5)
384
+
385
+ >>> from sympy import pi, Line, Circle, Point
386
+ >>> l = Line((0, pi), slope=1)
387
+ >>> circ = Circle(Point(0, 0), 5)
388
+ >>> rcirc = circ.reflect(l)
389
+ >>> rcirc
390
+ Circle(Point2D(-pi, pi), -5)
391
+
392
+ """
393
+ from sympy.geometry.point import Point
394
+
395
+ g = self
396
+ l = line
397
+ o = Point(0, 0)
398
+ if l.slope.is_zero:
399
+ v = l.args[0].y
400
+ if not v: # x-axis
401
+ return g.scale(y=-1)
402
+ reps = [(p, p.translate(y=2*(v - p.y))) for p in g.atoms(Point)]
403
+ elif l.slope is oo:
404
+ v = l.args[0].x
405
+ if not v: # y-axis
406
+ return g.scale(x=-1)
407
+ reps = [(p, p.translate(x=2*(v - p.x))) for p in g.atoms(Point)]
408
+ else:
409
+ if not hasattr(g, 'reflect') and not all(
410
+ isinstance(arg, Point) for arg in g.args):
411
+ raise NotImplementedError(
412
+ 'reflect undefined or non-Point args in %s' % g)
413
+ a = atan(l.slope)
414
+ c = l.coefficients
415
+ d = -c[-1]/c[1] # y-intercept
416
+ # apply the transform to a single point
417
+ xf = Point(x, y)
418
+ xf = xf.translate(y=-d).rotate(-a, o).scale(y=-1
419
+ ).rotate(a, o).translate(y=d)
420
+ # replace every point using that transform
421
+ reps = [(p, xf.xreplace({x: p.x, y: p.y})) for p in g.atoms(Point)]
422
+ return g.xreplace(dict(reps))
423
+
424
+ def rotate(self, angle, pt=None):
425
+ """Rotate ``angle`` radians counterclockwise about Point ``pt``.
426
+
427
+ The default pt is the origin, Point(0, 0)
428
+
429
+ See Also
430
+ ========
431
+
432
+ scale, translate
433
+
434
+ Examples
435
+ ========
436
+
437
+ >>> from sympy import Point, RegularPolygon, Polygon, pi
438
+ >>> t = Polygon(*RegularPolygon(Point(0, 0), 1, 3).vertices)
439
+ >>> t # vertex on x axis
440
+ Triangle(Point2D(1, 0), Point2D(-1/2, sqrt(3)/2), Point2D(-1/2, -sqrt(3)/2))
441
+ >>> t.rotate(pi/2) # vertex on y axis now
442
+ Triangle(Point2D(0, 1), Point2D(-sqrt(3)/2, -1/2), Point2D(sqrt(3)/2, -1/2))
443
+
444
+ """
445
+ newargs = []
446
+ for a in self.args:
447
+ if isinstance(a, GeometryEntity):
448
+ newargs.append(a.rotate(angle, pt))
449
+ else:
450
+ newargs.append(a)
451
+ return type(self)(*newargs)
452
+
453
+ def scale(self, x=1, y=1, pt=None):
454
+ """Scale the object by multiplying the x,y-coordinates by x and y.
455
+
456
+ If pt is given, the scaling is done relative to that point; the
457
+ object is shifted by -pt, scaled, and shifted by pt.
458
+
459
+ See Also
460
+ ========
461
+
462
+ rotate, translate
463
+
464
+ Examples
465
+ ========
466
+
467
+ >>> from sympy import RegularPolygon, Point, Polygon
468
+ >>> t = Polygon(*RegularPolygon(Point(0, 0), 1, 3).vertices)
469
+ >>> t
470
+ Triangle(Point2D(1, 0), Point2D(-1/2, sqrt(3)/2), Point2D(-1/2, -sqrt(3)/2))
471
+ >>> t.scale(2)
472
+ Triangle(Point2D(2, 0), Point2D(-1, sqrt(3)/2), Point2D(-1, -sqrt(3)/2))
473
+ >>> t.scale(2, 2)
474
+ Triangle(Point2D(2, 0), Point2D(-1, sqrt(3)), Point2D(-1, -sqrt(3)))
475
+
476
+ """
477
+ from sympy.geometry.point import Point
478
+ if pt:
479
+ pt = Point(pt, dim=2)
480
+ return self.translate(*(-pt).args).scale(x, y).translate(*pt.args)
481
+ return type(self)(*[a.scale(x, y) for a in self.args]) # if this fails, override this class
482
+
483
+ def translate(self, x=0, y=0):
484
+ """Shift the object by adding to the x,y-coordinates the values x and y.
485
+
486
+ See Also
487
+ ========
488
+
489
+ rotate, scale
490
+
491
+ Examples
492
+ ========
493
+
494
+ >>> from sympy import RegularPolygon, Point, Polygon
495
+ >>> t = Polygon(*RegularPolygon(Point(0, 0), 1, 3).vertices)
496
+ >>> t
497
+ Triangle(Point2D(1, 0), Point2D(-1/2, sqrt(3)/2), Point2D(-1/2, -sqrt(3)/2))
498
+ >>> t.translate(2)
499
+ Triangle(Point2D(3, 0), Point2D(3/2, sqrt(3)/2), Point2D(3/2, -sqrt(3)/2))
500
+ >>> t.translate(2, 2)
501
+ Triangle(Point2D(3, 2), Point2D(3/2, sqrt(3)/2 + 2), Point2D(3/2, 2 - sqrt(3)/2))
502
+
503
+ """
504
+ newargs = []
505
+ for a in self.args:
506
+ if isinstance(a, GeometryEntity):
507
+ newargs.append(a.translate(x, y))
508
+ else:
509
+ newargs.append(a)
510
+ return self.func(*newargs)
511
+
512
+ def parameter_value(self, other, t):
513
+ """Return the parameter corresponding to the given point.
514
+ Evaluating an arbitrary point of the entity at this parameter
515
+ value will return the given point.
516
+
517
+ Examples
518
+ ========
519
+
520
+ >>> from sympy import Line, Point
521
+ >>> from sympy.abc import t
522
+ >>> a = Point(0, 0)
523
+ >>> b = Point(2, 2)
524
+ >>> Line(a, b).parameter_value((1, 1), t)
525
+ {t: 1/2}
526
+ >>> Line(a, b).arbitrary_point(t).subs(_)
527
+ Point2D(1, 1)
528
+ """
529
+ from sympy.geometry.point import Point
530
+ if not isinstance(other, GeometryEntity):
531
+ other = Point(other, dim=self.ambient_dimension)
532
+ if not isinstance(other, Point):
533
+ raise ValueError("other must be a point")
534
+ sol = solve(self.arbitrary_point(T) - other, T, dict=True)
535
+ if not sol:
536
+ raise ValueError("Given point is not on %s" % func_name(self))
537
+ return {t: sol[0][T]}
538
+
539
+
540
+ class GeometrySet(GeometryEntity, Set):
541
+ """Parent class of all GeometryEntity that are also Sets
542
+ (compatible with sympy.sets)
543
+ """
544
+ __slots__ = ()
545
+
546
+ def _contains(self, other):
547
+ """sympy.sets uses the _contains method, so include it for compatibility."""
548
+
549
+ if isinstance(other, Set) and other.is_FiniteSet:
550
+ return all(self.__contains__(i) for i in other)
551
+
552
+ return self.__contains__(other)
553
+
554
+ @dispatch(GeometrySet, Set) # type:ignore # noqa:F811
555
+ def union_sets(self, o): # noqa:F811
556
+ """ Returns the union of self and o
557
+ for use with sympy.sets.Set, if possible. """
558
+
559
+
560
+ # if its a FiniteSet, merge any points
561
+ # we contain and return a union with the rest
562
+ if o.is_FiniteSet:
563
+ other_points = [p for p in o if not self._contains(p)]
564
+ if len(other_points) == len(o):
565
+ return None
566
+ return Union(self, FiniteSet(*other_points))
567
+ if self._contains(o):
568
+ return self
569
+ return None
570
+
571
+
572
+ @dispatch(GeometrySet, Set) # type: ignore # noqa:F811
573
+ def intersection_sets(self, o): # noqa:F811
574
+ """ Returns a sympy.sets.Set of intersection objects,
575
+ if possible. """
576
+
577
+ from sympy.geometry.point import Point
578
+
579
+ try:
580
+ # if o is a FiniteSet, find the intersection directly
581
+ # to avoid infinite recursion
582
+ if o.is_FiniteSet:
583
+ inter = FiniteSet(*(p for p in o if self.contains(p)))
584
+ else:
585
+ inter = self.intersection(o)
586
+ except NotImplementedError:
587
+ # sympy.sets.Set.reduce expects None if an object
588
+ # doesn't know how to simplify
589
+ return None
590
+
591
+ # put the points in a FiniteSet
592
+ points = FiniteSet(*[p for p in inter if isinstance(p, Point)])
593
+ non_points = [p for p in inter if not isinstance(p, Point)]
594
+
595
+ return Union(*(non_points + [points]))
596
+
597
+ def translate(x, y):
598
+ """Return the matrix to translate a 2-D point by x and y."""
599
+ rv = eye(3)
600
+ rv[2, 0] = x
601
+ rv[2, 1] = y
602
+ return rv
603
+
604
+
605
+ def scale(x, y, pt=None):
606
+ """Return the matrix to multiply a 2-D point's coordinates by x and y.
607
+
608
+ If pt is given, the scaling is done relative to that point."""
609
+ rv = eye(3)
610
+ rv[0, 0] = x
611
+ rv[1, 1] = y
612
+ if pt:
613
+ from sympy.geometry.point import Point
614
+ pt = Point(pt, dim=2)
615
+ tr1 = translate(*(-pt).args)
616
+ tr2 = translate(*pt.args)
617
+ return tr1*rv*tr2
618
+ return rv
619
+
620
+
621
+ def rotate(th):
622
+ """Return the matrix to rotate a 2-D point about the origin by ``angle``.
623
+
624
+ The angle is measured in radians. To Point a point about a point other
625
+ then the origin, translate the Point, do the rotation, and
626
+ translate it back:
627
+
628
+ >>> from sympy.geometry.entity import rotate, translate
629
+ >>> from sympy import Point, pi
630
+ >>> rot_about_11 = translate(-1, -1)*rotate(pi/2)*translate(1, 1)
631
+ >>> Point(1, 1).transform(rot_about_11)
632
+ Point2D(1, 1)
633
+ >>> Point(0, 0).transform(rot_about_11)
634
+ Point2D(2, 0)
635
+ """
636
+ s = sin(th)
637
+ rv = eye(3)*cos(th)
638
+ rv[0, 1] = s
639
+ rv[1, 0] = -s
640
+ rv[2, 2] = 1
641
+ return rv
janus/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
janus/lib/python3.10/site-packages/sympy/geometry/line.py ADDED
@@ -0,0 +1,2877 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Line-like geometrical entities.
2
+
3
+ Contains
4
+ ========
5
+ LinearEntity
6
+ Line
7
+ Ray
8
+ Segment
9
+ LinearEntity2D
10
+ Line2D
11
+ Ray2D
12
+ Segment2D
13
+ LinearEntity3D
14
+ Line3D
15
+ Ray3D
16
+ Segment3D
17
+
18
+ """
19
+
20
+ from sympy.core.containers import Tuple
21
+ from sympy.core.evalf import N
22
+ from sympy.core.expr import Expr
23
+ from sympy.core.numbers import Rational, oo, Float
24
+ from sympy.core.relational import Eq
25
+ from sympy.core.singleton import S
26
+ from sympy.core.sorting import ordered
27
+ from sympy.core.symbol import _symbol, Dummy, uniquely_named_symbol
28
+ from sympy.core.sympify import sympify
29
+ from sympy.functions.elementary.piecewise import Piecewise
30
+ from sympy.functions.elementary.trigonometric import (_pi_coeff, acos, tan, atan2)
31
+ from .entity import GeometryEntity, GeometrySet
32
+ from .exceptions import GeometryError
33
+ from .point import Point, Point3D
34
+ from .util import find, intersection
35
+ from sympy.logic.boolalg import And
36
+ from sympy.matrices import Matrix
37
+ from sympy.sets.sets import Intersection
38
+ from sympy.simplify.simplify import simplify
39
+ from sympy.solvers.solvers import solve
40
+ from sympy.solvers.solveset import linear_coeffs
41
+ from sympy.utilities.misc import Undecidable, filldedent
42
+
43
+
44
+ import random
45
+
46
+
47
+ t, u = [Dummy('line_dummy') for i in range(2)]
48
+
49
+
50
+ class LinearEntity(GeometrySet):
51
+ """A base class for all linear entities (Line, Ray and Segment)
52
+ in n-dimensional Euclidean space.
53
+
54
+ Attributes
55
+ ==========
56
+
57
+ ambient_dimension
58
+ direction
59
+ length
60
+ p1
61
+ p2
62
+ points
63
+
64
+ Notes
65
+ =====
66
+
67
+ This is an abstract class and is not meant to be instantiated.
68
+
69
+ See Also
70
+ ========
71
+
72
+ sympy.geometry.entity.GeometryEntity
73
+
74
+ """
75
+ def __new__(cls, p1, p2=None, **kwargs):
76
+ p1, p2 = Point._normalize_dimension(p1, p2)
77
+ if p1 == p2:
78
+ # sometimes we return a single point if we are not given two unique
79
+ # points. This is done in the specific subclass
80
+ raise ValueError(
81
+ "%s.__new__ requires two unique Points." % cls.__name__)
82
+ if len(p1) != len(p2):
83
+ raise ValueError(
84
+ "%s.__new__ requires two Points of equal dimension." % cls.__name__)
85
+
86
+ return GeometryEntity.__new__(cls, p1, p2, **kwargs)
87
+
88
+ def __contains__(self, other):
89
+ """Return a definitive answer or else raise an error if it cannot
90
+ be determined that other is on the boundaries of self."""
91
+ result = self.contains(other)
92
+
93
+ if result is not None:
94
+ return result
95
+ else:
96
+ raise Undecidable(
97
+ "Cannot decide whether '%s' contains '%s'" % (self, other))
98
+
99
+ def _span_test(self, other):
100
+ """Test whether the point `other` lies in the positive span of `self`.
101
+ A point x is 'in front' of a point y if x.dot(y) >= 0. Return
102
+ -1 if `other` is behind `self.p1`, 0 if `other` is `self.p1` and
103
+ and 1 if `other` is in front of `self.p1`."""
104
+ if self.p1 == other:
105
+ return 0
106
+
107
+ rel_pos = other - self.p1
108
+ d = self.direction
109
+ if d.dot(rel_pos) > 0:
110
+ return 1
111
+ return -1
112
+
113
+ @property
114
+ def ambient_dimension(self):
115
+ """A property method that returns the dimension of LinearEntity
116
+ object.
117
+
118
+ Parameters
119
+ ==========
120
+
121
+ p1 : LinearEntity
122
+
123
+ Returns
124
+ =======
125
+
126
+ dimension : integer
127
+
128
+ Examples
129
+ ========
130
+
131
+ >>> from sympy import Point, Line
132
+ >>> p1, p2 = Point(0, 0), Point(1, 1)
133
+ >>> l1 = Line(p1, p2)
134
+ >>> l1.ambient_dimension
135
+ 2
136
+
137
+ >>> from sympy import Point, Line
138
+ >>> p1, p2 = Point(0, 0, 0), Point(1, 1, 1)
139
+ >>> l1 = Line(p1, p2)
140
+ >>> l1.ambient_dimension
141
+ 3
142
+
143
+ """
144
+ return len(self.p1)
145
+
146
+ def angle_between(l1, l2):
147
+ """Return the non-reflex angle formed by rays emanating from
148
+ the origin with directions the same as the direction vectors
149
+ of the linear entities.
150
+
151
+ Parameters
152
+ ==========
153
+
154
+ l1 : LinearEntity
155
+ l2 : LinearEntity
156
+
157
+ Returns
158
+ =======
159
+
160
+ angle : angle in radians
161
+
162
+ Notes
163
+ =====
164
+
165
+ From the dot product of vectors v1 and v2 it is known that:
166
+
167
+ ``dot(v1, v2) = |v1|*|v2|*cos(A)``
168
+
169
+ where A is the angle formed between the two vectors. We can
170
+ get the directional vectors of the two lines and readily
171
+ find the angle between the two using the above formula.
172
+
173
+ See Also
174
+ ========
175
+
176
+ is_perpendicular, Ray2D.closing_angle
177
+
178
+ Examples
179
+ ========
180
+
181
+ >>> from sympy import Line
182
+ >>> e = Line((0, 0), (1, 0))
183
+ >>> ne = Line((0, 0), (1, 1))
184
+ >>> sw = Line((1, 1), (0, 0))
185
+ >>> ne.angle_between(e)
186
+ pi/4
187
+ >>> sw.angle_between(e)
188
+ 3*pi/4
189
+
190
+ To obtain the non-obtuse angle at the intersection of lines, use
191
+ the ``smallest_angle_between`` method:
192
+
193
+ >>> sw.smallest_angle_between(e)
194
+ pi/4
195
+
196
+ >>> from sympy import Point3D, Line3D
197
+ >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(-1, 2, 0)
198
+ >>> l1, l2 = Line3D(p1, p2), Line3D(p2, p3)
199
+ >>> l1.angle_between(l2)
200
+ acos(-sqrt(2)/3)
201
+ >>> l1.smallest_angle_between(l2)
202
+ acos(sqrt(2)/3)
203
+ """
204
+ if not isinstance(l1, LinearEntity) and not isinstance(l2, LinearEntity):
205
+ raise TypeError('Must pass only LinearEntity objects')
206
+
207
+ v1, v2 = l1.direction, l2.direction
208
+ return acos(v1.dot(v2)/(abs(v1)*abs(v2)))
209
+
210
+ def smallest_angle_between(l1, l2):
211
+ """Return the smallest angle formed at the intersection of the
212
+ lines containing the linear entities.
213
+
214
+ Parameters
215
+ ==========
216
+
217
+ l1 : LinearEntity
218
+ l2 : LinearEntity
219
+
220
+ Returns
221
+ =======
222
+
223
+ angle : angle in radians
224
+
225
+ Examples
226
+ ========
227
+
228
+ >>> from sympy import Point, Line
229
+ >>> p1, p2, p3 = Point(0, 0), Point(0, 4), Point(2, -2)
230
+ >>> l1, l2 = Line(p1, p2), Line(p1, p3)
231
+ >>> l1.smallest_angle_between(l2)
232
+ pi/4
233
+
234
+ See Also
235
+ ========
236
+
237
+ angle_between, is_perpendicular, Ray2D.closing_angle
238
+ """
239
+ if not isinstance(l1, LinearEntity) and not isinstance(l2, LinearEntity):
240
+ raise TypeError('Must pass only LinearEntity objects')
241
+
242
+ v1, v2 = l1.direction, l2.direction
243
+ return acos(abs(v1.dot(v2))/(abs(v1)*abs(v2)))
244
+
245
+ def arbitrary_point(self, parameter='t'):
246
+ """A parameterized point on the Line.
247
+
248
+ Parameters
249
+ ==========
250
+
251
+ parameter : str, optional
252
+ The name of the parameter which will be used for the parametric
253
+ point. The default value is 't'. When this parameter is 0, the
254
+ first point used to define the line will be returned, and when
255
+ it is 1 the second point will be returned.
256
+
257
+ Returns
258
+ =======
259
+
260
+ point : Point
261
+
262
+ Raises
263
+ ======
264
+
265
+ ValueError
266
+ When ``parameter`` already appears in the Line's definition.
267
+
268
+ See Also
269
+ ========
270
+
271
+ sympy.geometry.point.Point
272
+
273
+ Examples
274
+ ========
275
+
276
+ >>> from sympy import Point, Line
277
+ >>> p1, p2 = Point(1, 0), Point(5, 3)
278
+ >>> l1 = Line(p1, p2)
279
+ >>> l1.arbitrary_point()
280
+ Point2D(4*t + 1, 3*t)
281
+ >>> from sympy import Point3D, Line3D
282
+ >>> p1, p2 = Point3D(1, 0, 0), Point3D(5, 3, 1)
283
+ >>> l1 = Line3D(p1, p2)
284
+ >>> l1.arbitrary_point()
285
+ Point3D(4*t + 1, 3*t, t)
286
+
287
+ """
288
+ t = _symbol(parameter, real=True)
289
+ if t.name in (f.name for f in self.free_symbols):
290
+ raise ValueError(filldedent('''
291
+ Symbol %s already appears in object
292
+ and cannot be used as a parameter.
293
+ ''' % t.name))
294
+ # multiply on the right so the variable gets
295
+ # combined with the coordinates of the point
296
+ return self.p1 + (self.p2 - self.p1)*t
297
+
298
+ @staticmethod
299
+ def are_concurrent(*lines):
300
+ """Is a sequence of linear entities concurrent?
301
+
302
+ Two or more linear entities are concurrent if they all
303
+ intersect at a single point.
304
+
305
+ Parameters
306
+ ==========
307
+
308
+ lines
309
+ A sequence of linear entities.
310
+
311
+ Returns
312
+ =======
313
+
314
+ True : if the set of linear entities intersect in one point
315
+ False : otherwise.
316
+
317
+ See Also
318
+ ========
319
+
320
+ sympy.geometry.util.intersection
321
+
322
+ Examples
323
+ ========
324
+
325
+ >>> from sympy import Point, Line
326
+ >>> p1, p2 = Point(0, 0), Point(3, 5)
327
+ >>> p3, p4 = Point(-2, -2), Point(0, 2)
328
+ >>> l1, l2, l3 = Line(p1, p2), Line(p1, p3), Line(p1, p4)
329
+ >>> Line.are_concurrent(l1, l2, l3)
330
+ True
331
+ >>> l4 = Line(p2, p3)
332
+ >>> Line.are_concurrent(l2, l3, l4)
333
+ False
334
+ >>> from sympy import Point3D, Line3D
335
+ >>> p1, p2 = Point3D(0, 0, 0), Point3D(3, 5, 2)
336
+ >>> p3, p4 = Point3D(-2, -2, -2), Point3D(0, 2, 1)
337
+ >>> l1, l2, l3 = Line3D(p1, p2), Line3D(p1, p3), Line3D(p1, p4)
338
+ >>> Line3D.are_concurrent(l1, l2, l3)
339
+ True
340
+ >>> l4 = Line3D(p2, p3)
341
+ >>> Line3D.are_concurrent(l2, l3, l4)
342
+ False
343
+
344
+ """
345
+ common_points = Intersection(*lines)
346
+ if common_points.is_FiniteSet and len(common_points) == 1:
347
+ return True
348
+ return False
349
+
350
+ def contains(self, other):
351
+ """Subclasses should implement this method and should return
352
+ True if other is on the boundaries of self;
353
+ False if not on the boundaries of self;
354
+ None if a determination cannot be made."""
355
+ raise NotImplementedError()
356
+
357
+ @property
358
+ def direction(self):
359
+ """The direction vector of the LinearEntity.
360
+
361
+ Returns
362
+ =======
363
+
364
+ p : a Point; the ray from the origin to this point is the
365
+ direction of `self`
366
+
367
+ Examples
368
+ ========
369
+
370
+ >>> from sympy import Line
371
+ >>> a, b = (1, 1), (1, 3)
372
+ >>> Line(a, b).direction
373
+ Point2D(0, 2)
374
+ >>> Line(b, a).direction
375
+ Point2D(0, -2)
376
+
377
+ This can be reported so the distance from the origin is 1:
378
+
379
+ >>> Line(b, a).direction.unit
380
+ Point2D(0, -1)
381
+
382
+ See Also
383
+ ========
384
+
385
+ sympy.geometry.point.Point.unit
386
+
387
+ """
388
+ return self.p2 - self.p1
389
+
390
+ def intersection(self, other):
391
+ """The intersection with another geometrical entity.
392
+
393
+ Parameters
394
+ ==========
395
+
396
+ o : Point or LinearEntity
397
+
398
+ Returns
399
+ =======
400
+
401
+ intersection : list of geometrical entities
402
+
403
+ See Also
404
+ ========
405
+
406
+ sympy.geometry.point.Point
407
+
408
+ Examples
409
+ ========
410
+
411
+ >>> from sympy import Point, Line, Segment
412
+ >>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(7, 7)
413
+ >>> l1 = Line(p1, p2)
414
+ >>> l1.intersection(p3)
415
+ [Point2D(7, 7)]
416
+ >>> p4, p5 = Point(5, 0), Point(0, 3)
417
+ >>> l2 = Line(p4, p5)
418
+ >>> l1.intersection(l2)
419
+ [Point2D(15/8, 15/8)]
420
+ >>> p6, p7 = Point(0, 5), Point(2, 6)
421
+ >>> s1 = Segment(p6, p7)
422
+ >>> l1.intersection(s1)
423
+ []
424
+ >>> from sympy import Point3D, Line3D, Segment3D
425
+ >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(7, 7, 7)
426
+ >>> l1 = Line3D(p1, p2)
427
+ >>> l1.intersection(p3)
428
+ [Point3D(7, 7, 7)]
429
+ >>> l1 = Line3D(Point3D(4,19,12), Point3D(5,25,17))
430
+ >>> l2 = Line3D(Point3D(-3, -15, -19), direction_ratio=[2,8,8])
431
+ >>> l1.intersection(l2)
432
+ [Point3D(1, 1, -3)]
433
+ >>> p6, p7 = Point3D(0, 5, 2), Point3D(2, 6, 3)
434
+ >>> s1 = Segment3D(p6, p7)
435
+ >>> l1.intersection(s1)
436
+ []
437
+
438
+ """
439
+ def intersect_parallel_rays(ray1, ray2):
440
+ if ray1.direction.dot(ray2.direction) > 0:
441
+ # rays point in the same direction
442
+ # so return the one that is "in front"
443
+ return [ray2] if ray1._span_test(ray2.p1) >= 0 else [ray1]
444
+ else:
445
+ # rays point in opposite directions
446
+ st = ray1._span_test(ray2.p1)
447
+ if st < 0:
448
+ return []
449
+ elif st == 0:
450
+ return [ray2.p1]
451
+ return [Segment(ray1.p1, ray2.p1)]
452
+
453
+ def intersect_parallel_ray_and_segment(ray, seg):
454
+ st1, st2 = ray._span_test(seg.p1), ray._span_test(seg.p2)
455
+ if st1 < 0 and st2 < 0:
456
+ return []
457
+ elif st1 >= 0 and st2 >= 0:
458
+ return [seg]
459
+ elif st1 >= 0: # st2 < 0:
460
+ return [Segment(ray.p1, seg.p1)]
461
+ else: # st1 < 0 and st2 >= 0:
462
+ return [Segment(ray.p1, seg.p2)]
463
+
464
+ def intersect_parallel_segments(seg1, seg2):
465
+ if seg1.contains(seg2):
466
+ return [seg2]
467
+ if seg2.contains(seg1):
468
+ return [seg1]
469
+
470
+ # direct the segments so they're oriented the same way
471
+ if seg1.direction.dot(seg2.direction) < 0:
472
+ seg2 = Segment(seg2.p2, seg2.p1)
473
+ # order the segments so seg1 is "behind" seg2
474
+ if seg1._span_test(seg2.p1) < 0:
475
+ seg1, seg2 = seg2, seg1
476
+ if seg2._span_test(seg1.p2) < 0:
477
+ return []
478
+ return [Segment(seg2.p1, seg1.p2)]
479
+
480
+ if not isinstance(other, GeometryEntity):
481
+ other = Point(other, dim=self.ambient_dimension)
482
+ if other.is_Point:
483
+ if self.contains(other):
484
+ return [other]
485
+ else:
486
+ return []
487
+ elif isinstance(other, LinearEntity):
488
+ # break into cases based on whether
489
+ # the lines are parallel, non-parallel intersecting, or skew
490
+ pts = Point._normalize_dimension(self.p1, self.p2, other.p1, other.p2)
491
+ rank = Point.affine_rank(*pts)
492
+
493
+ if rank == 1:
494
+ # we're collinear
495
+ if isinstance(self, Line):
496
+ return [other]
497
+ if isinstance(other, Line):
498
+ return [self]
499
+
500
+ if isinstance(self, Ray) and isinstance(other, Ray):
501
+ return intersect_parallel_rays(self, other)
502
+ if isinstance(self, Ray) and isinstance(other, Segment):
503
+ return intersect_parallel_ray_and_segment(self, other)
504
+ if isinstance(self, Segment) and isinstance(other, Ray):
505
+ return intersect_parallel_ray_and_segment(other, self)
506
+ if isinstance(self, Segment) and isinstance(other, Segment):
507
+ return intersect_parallel_segments(self, other)
508
+ elif rank == 2:
509
+ # we're in the same plane
510
+ l1 = Line(*pts[:2])
511
+ l2 = Line(*pts[2:])
512
+
513
+ # check to see if we're parallel. If we are, we can't
514
+ # be intersecting, since the collinear case was already
515
+ # handled
516
+ if l1.direction.is_scalar_multiple(l2.direction):
517
+ return []
518
+
519
+ # find the intersection as if everything were lines
520
+ # by solving the equation t*d + p1 == s*d' + p1'
521
+ m = Matrix([l1.direction, -l2.direction]).transpose()
522
+ v = Matrix([l2.p1 - l1.p1]).transpose()
523
+
524
+ # we cannot use m.solve(v) because that only works for square matrices
525
+ m_rref, pivots = m.col_insert(2, v).rref(simplify=True)
526
+ # rank == 2 ensures we have 2 pivots, but let's check anyway
527
+ if len(pivots) != 2:
528
+ raise GeometryError("Failed when solving Mx=b when M={} and b={}".format(m, v))
529
+ coeff = m_rref[0, 2]
530
+ line_intersection = l1.direction*coeff + self.p1
531
+
532
+ # if both are lines, skip a containment check
533
+ if isinstance(self, Line) and isinstance(other, Line):
534
+ return [line_intersection]
535
+
536
+ if ((isinstance(self, Line) or
537
+ self.contains(line_intersection)) and
538
+ other.contains(line_intersection)):
539
+ return [line_intersection]
540
+ if not self.atoms(Float) and not other.atoms(Float):
541
+ # if it can fail when there are no Floats then
542
+ # maybe the following parametric check should be
543
+ # done
544
+ return []
545
+ # floats may fail exact containment so check that the
546
+ # arbitrary points, when equal, both give a
547
+ # non-negative parameter when the arbitrary point
548
+ # coordinates are equated
549
+ tu = solve(self.arbitrary_point(t) - other.arbitrary_point(u),
550
+ t, u, dict=True)[0]
551
+ def ok(p, l):
552
+ if isinstance(l, Line):
553
+ # p > -oo
554
+ return True
555
+ if isinstance(l, Ray):
556
+ # p >= 0
557
+ return p.is_nonnegative
558
+ if isinstance(l, Segment):
559
+ # 0 <= p <= 1
560
+ return p.is_nonnegative and (1 - p).is_nonnegative
561
+ raise ValueError("unexpected line type")
562
+ if ok(tu[t], self) and ok(tu[u], other):
563
+ return [line_intersection]
564
+ return []
565
+ else:
566
+ # we're skew
567
+ return []
568
+
569
+ return other.intersection(self)
570
+
571
+ def is_parallel(l1, l2):
572
+ """Are two linear entities parallel?
573
+
574
+ Parameters
575
+ ==========
576
+
577
+ l1 : LinearEntity
578
+ l2 : LinearEntity
579
+
580
+ Returns
581
+ =======
582
+
583
+ True : if l1 and l2 are parallel,
584
+ False : otherwise.
585
+
586
+ See Also
587
+ ========
588
+
589
+ coefficients
590
+
591
+ Examples
592
+ ========
593
+
594
+ >>> from sympy import Point, Line
595
+ >>> p1, p2 = Point(0, 0), Point(1, 1)
596
+ >>> p3, p4 = Point(3, 4), Point(6, 7)
597
+ >>> l1, l2 = Line(p1, p2), Line(p3, p4)
598
+ >>> Line.is_parallel(l1, l2)
599
+ True
600
+ >>> p5 = Point(6, 6)
601
+ >>> l3 = Line(p3, p5)
602
+ >>> Line.is_parallel(l1, l3)
603
+ False
604
+ >>> from sympy import Point3D, Line3D
605
+ >>> p1, p2 = Point3D(0, 0, 0), Point3D(3, 4, 5)
606
+ >>> p3, p4 = Point3D(2, 1, 1), Point3D(8, 9, 11)
607
+ >>> l1, l2 = Line3D(p1, p2), Line3D(p3, p4)
608
+ >>> Line3D.is_parallel(l1, l2)
609
+ True
610
+ >>> p5 = Point3D(6, 6, 6)
611
+ >>> l3 = Line3D(p3, p5)
612
+ >>> Line3D.is_parallel(l1, l3)
613
+ False
614
+
615
+ """
616
+ if not isinstance(l1, LinearEntity) and not isinstance(l2, LinearEntity):
617
+ raise TypeError('Must pass only LinearEntity objects')
618
+
619
+ return l1.direction.is_scalar_multiple(l2.direction)
620
+
621
+ def is_perpendicular(l1, l2):
622
+ """Are two linear entities perpendicular?
623
+
624
+ Parameters
625
+ ==========
626
+
627
+ l1 : LinearEntity
628
+ l2 : LinearEntity
629
+
630
+ Returns
631
+ =======
632
+
633
+ True : if l1 and l2 are perpendicular,
634
+ False : otherwise.
635
+
636
+ See Also
637
+ ========
638
+
639
+ coefficients
640
+
641
+ Examples
642
+ ========
643
+
644
+ >>> from sympy import Point, Line
645
+ >>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(-1, 1)
646
+ >>> l1, l2 = Line(p1, p2), Line(p1, p3)
647
+ >>> l1.is_perpendicular(l2)
648
+ True
649
+ >>> p4 = Point(5, 3)
650
+ >>> l3 = Line(p1, p4)
651
+ >>> l1.is_perpendicular(l3)
652
+ False
653
+ >>> from sympy import Point3D, Line3D
654
+ >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(-1, 2, 0)
655
+ >>> l1, l2 = Line3D(p1, p2), Line3D(p2, p3)
656
+ >>> l1.is_perpendicular(l2)
657
+ False
658
+ >>> p4 = Point3D(5, 3, 7)
659
+ >>> l3 = Line3D(p1, p4)
660
+ >>> l1.is_perpendicular(l3)
661
+ False
662
+
663
+ """
664
+ if not isinstance(l1, LinearEntity) and not isinstance(l2, LinearEntity):
665
+ raise TypeError('Must pass only LinearEntity objects')
666
+
667
+ return S.Zero.equals(l1.direction.dot(l2.direction))
668
+
669
+ def is_similar(self, other):
670
+ """
671
+ Return True if self and other are contained in the same line.
672
+
673
+ Examples
674
+ ========
675
+
676
+ >>> from sympy import Point, Line
677
+ >>> p1, p2, p3 = Point(0, 1), Point(3, 4), Point(2, 3)
678
+ >>> l1 = Line(p1, p2)
679
+ >>> l2 = Line(p1, p3)
680
+ >>> l1.is_similar(l2)
681
+ True
682
+ """
683
+ l = Line(self.p1, self.p2)
684
+ return l.contains(other)
685
+
686
+ @property
687
+ def length(self):
688
+ """
689
+ The length of the line.
690
+
691
+ Examples
692
+ ========
693
+
694
+ >>> from sympy import Point, Line
695
+ >>> p1, p2 = Point(0, 0), Point(3, 5)
696
+ >>> l1 = Line(p1, p2)
697
+ >>> l1.length
698
+ oo
699
+ """
700
+ return S.Infinity
701
+
702
+ @property
703
+ def p1(self):
704
+ """The first defining point of a linear entity.
705
+
706
+ See Also
707
+ ========
708
+
709
+ sympy.geometry.point.Point
710
+
711
+ Examples
712
+ ========
713
+
714
+ >>> from sympy import Point, Line
715
+ >>> p1, p2 = Point(0, 0), Point(5, 3)
716
+ >>> l = Line(p1, p2)
717
+ >>> l.p1
718
+ Point2D(0, 0)
719
+
720
+ """
721
+ return self.args[0]
722
+
723
+ @property
724
+ def p2(self):
725
+ """The second defining point of a linear entity.
726
+
727
+ See Also
728
+ ========
729
+
730
+ sympy.geometry.point.Point
731
+
732
+ Examples
733
+ ========
734
+
735
+ >>> from sympy import Point, Line
736
+ >>> p1, p2 = Point(0, 0), Point(5, 3)
737
+ >>> l = Line(p1, p2)
738
+ >>> l.p2
739
+ Point2D(5, 3)
740
+
741
+ """
742
+ return self.args[1]
743
+
744
+ def parallel_line(self, p):
745
+ """Create a new Line parallel to this linear entity which passes
746
+ through the point `p`.
747
+
748
+ Parameters
749
+ ==========
750
+
751
+ p : Point
752
+
753
+ Returns
754
+ =======
755
+
756
+ line : Line
757
+
758
+ See Also
759
+ ========
760
+
761
+ is_parallel
762
+
763
+ Examples
764
+ ========
765
+
766
+ >>> from sympy import Point, Line
767
+ >>> p1, p2, p3 = Point(0, 0), Point(2, 3), Point(-2, 2)
768
+ >>> l1 = Line(p1, p2)
769
+ >>> l2 = l1.parallel_line(p3)
770
+ >>> p3 in l2
771
+ True
772
+ >>> l1.is_parallel(l2)
773
+ True
774
+ >>> from sympy import Point3D, Line3D
775
+ >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(2, 3, 4), Point3D(-2, 2, 0)
776
+ >>> l1 = Line3D(p1, p2)
777
+ >>> l2 = l1.parallel_line(p3)
778
+ >>> p3 in l2
779
+ True
780
+ >>> l1.is_parallel(l2)
781
+ True
782
+
783
+ """
784
+ p = Point(p, dim=self.ambient_dimension)
785
+ return Line(p, p + self.direction)
786
+
787
+ def perpendicular_line(self, p):
788
+ """Create a new Line perpendicular to this linear entity which passes
789
+ through the point `p`.
790
+
791
+ Parameters
792
+ ==========
793
+
794
+ p : Point
795
+
796
+ Returns
797
+ =======
798
+
799
+ line : Line
800
+
801
+ See Also
802
+ ========
803
+
804
+ sympy.geometry.line.LinearEntity.is_perpendicular, perpendicular_segment
805
+
806
+ Examples
807
+ ========
808
+
809
+ >>> from sympy import Point3D, Line3D
810
+ >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(2, 3, 4), Point3D(-2, 2, 0)
811
+ >>> L = Line3D(p1, p2)
812
+ >>> P = L.perpendicular_line(p3); P
813
+ Line3D(Point3D(-2, 2, 0), Point3D(4/29, 6/29, 8/29))
814
+ >>> L.is_perpendicular(P)
815
+ True
816
+
817
+ In 3D the, the first point used to define the line is the point
818
+ through which the perpendicular was required to pass; the
819
+ second point is (arbitrarily) contained in the given line:
820
+
821
+ >>> P.p2 in L
822
+ True
823
+ """
824
+ p = Point(p, dim=self.ambient_dimension)
825
+ if p in self:
826
+ p = p + self.direction.orthogonal_direction
827
+ return Line(p, self.projection(p))
828
+
829
+ def perpendicular_segment(self, p):
830
+ """Create a perpendicular line segment from `p` to this line.
831
+
832
+ The endpoints of the segment are ``p`` and the closest point in
833
+ the line containing self. (If self is not a line, the point might
834
+ not be in self.)
835
+
836
+ Parameters
837
+ ==========
838
+
839
+ p : Point
840
+
841
+ Returns
842
+ =======
843
+
844
+ segment : Segment
845
+
846
+ Notes
847
+ =====
848
+
849
+ Returns `p` itself if `p` is on this linear entity.
850
+
851
+ See Also
852
+ ========
853
+
854
+ perpendicular_line
855
+
856
+ Examples
857
+ ========
858
+
859
+ >>> from sympy import Point, Line
860
+ >>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(0, 2)
861
+ >>> l1 = Line(p1, p2)
862
+ >>> s1 = l1.perpendicular_segment(p3)
863
+ >>> l1.is_perpendicular(s1)
864
+ True
865
+ >>> p3 in s1
866
+ True
867
+ >>> l1.perpendicular_segment(Point(4, 0))
868
+ Segment2D(Point2D(4, 0), Point2D(2, 2))
869
+ >>> from sympy import Point3D, Line3D
870
+ >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(0, 2, 0)
871
+ >>> l1 = Line3D(p1, p2)
872
+ >>> s1 = l1.perpendicular_segment(p3)
873
+ >>> l1.is_perpendicular(s1)
874
+ True
875
+ >>> p3 in s1
876
+ True
877
+ >>> l1.perpendicular_segment(Point3D(4, 0, 0))
878
+ Segment3D(Point3D(4, 0, 0), Point3D(4/3, 4/3, 4/3))
879
+
880
+ """
881
+ p = Point(p, dim=self.ambient_dimension)
882
+ if p in self:
883
+ return p
884
+ l = self.perpendicular_line(p)
885
+ # The intersection should be unique, so unpack the singleton
886
+ p2, = Intersection(Line(self.p1, self.p2), l)
887
+
888
+ return Segment(p, p2)
889
+
890
+ @property
891
+ def points(self):
892
+ """The two points used to define this linear entity.
893
+
894
+ Returns
895
+ =======
896
+
897
+ points : tuple of Points
898
+
899
+ See Also
900
+ ========
901
+
902
+ sympy.geometry.point.Point
903
+
904
+ Examples
905
+ ========
906
+
907
+ >>> from sympy import Point, Line
908
+ >>> p1, p2 = Point(0, 0), Point(5, 11)
909
+ >>> l1 = Line(p1, p2)
910
+ >>> l1.points
911
+ (Point2D(0, 0), Point2D(5, 11))
912
+
913
+ """
914
+ return (self.p1, self.p2)
915
+
916
+ def projection(self, other):
917
+ """Project a point, line, ray, or segment onto this linear entity.
918
+
919
+ Parameters
920
+ ==========
921
+
922
+ other : Point or LinearEntity (Line, Ray, Segment)
923
+
924
+ Returns
925
+ =======
926
+
927
+ projection : Point or LinearEntity (Line, Ray, Segment)
928
+ The return type matches the type of the parameter ``other``.
929
+
930
+ Raises
931
+ ======
932
+
933
+ GeometryError
934
+ When method is unable to perform projection.
935
+
936
+ Notes
937
+ =====
938
+
939
+ A projection involves taking the two points that define
940
+ the linear entity and projecting those points onto a
941
+ Line and then reforming the linear entity using these
942
+ projections.
943
+ A point P is projected onto a line L by finding the point
944
+ on L that is closest to P. This point is the intersection
945
+ of L and the line perpendicular to L that passes through P.
946
+
947
+ See Also
948
+ ========
949
+
950
+ sympy.geometry.point.Point, perpendicular_line
951
+
952
+ Examples
953
+ ========
954
+
955
+ >>> from sympy import Point, Line, Segment, Rational
956
+ >>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(Rational(1, 2), 0)
957
+ >>> l1 = Line(p1, p2)
958
+ >>> l1.projection(p3)
959
+ Point2D(1/4, 1/4)
960
+ >>> p4, p5 = Point(10, 0), Point(12, 1)
961
+ >>> s1 = Segment(p4, p5)
962
+ >>> l1.projection(s1)
963
+ Segment2D(Point2D(5, 5), Point2D(13/2, 13/2))
964
+ >>> p1, p2, p3 = Point(0, 0, 1), Point(1, 1, 2), Point(2, 0, 1)
965
+ >>> l1 = Line(p1, p2)
966
+ >>> l1.projection(p3)
967
+ Point3D(2/3, 2/3, 5/3)
968
+ >>> p4, p5 = Point(10, 0, 1), Point(12, 1, 3)
969
+ >>> s1 = Segment(p4, p5)
970
+ >>> l1.projection(s1)
971
+ Segment3D(Point3D(10/3, 10/3, 13/3), Point3D(5, 5, 6))
972
+
973
+ """
974
+ if not isinstance(other, GeometryEntity):
975
+ other = Point(other, dim=self.ambient_dimension)
976
+
977
+ def proj_point(p):
978
+ return Point.project(p - self.p1, self.direction) + self.p1
979
+
980
+ if isinstance(other, Point):
981
+ return proj_point(other)
982
+ elif isinstance(other, LinearEntity):
983
+ p1, p2 = proj_point(other.p1), proj_point(other.p2)
984
+ # test to see if we're degenerate
985
+ if p1 == p2:
986
+ return p1
987
+ projected = other.__class__(p1, p2)
988
+ projected = Intersection(self, projected)
989
+ if projected.is_empty:
990
+ return projected
991
+ # if we happen to have intersected in only a point, return that
992
+ if projected.is_FiniteSet and len(projected) == 1:
993
+ # projected is a set of size 1, so unpack it in `a`
994
+ a, = projected
995
+ return a
996
+ # order args so projection is in the same direction as self
997
+ if self.direction.dot(projected.direction) < 0:
998
+ p1, p2 = projected.args
999
+ projected = projected.func(p2, p1)
1000
+ return projected
1001
+
1002
+ raise GeometryError(
1003
+ "Do not know how to project %s onto %s" % (other, self))
1004
+
1005
+ def random_point(self, seed=None):
1006
+ """A random point on a LinearEntity.
1007
+
1008
+ Returns
1009
+ =======
1010
+
1011
+ point : Point
1012
+
1013
+ See Also
1014
+ ========
1015
+
1016
+ sympy.geometry.point.Point
1017
+
1018
+ Examples
1019
+ ========
1020
+
1021
+ >>> from sympy import Point, Line, Ray, Segment
1022
+ >>> p1, p2 = Point(0, 0), Point(5, 3)
1023
+ >>> line = Line(p1, p2)
1024
+ >>> r = line.random_point(seed=42) # seed value is optional
1025
+ >>> r.n(3)
1026
+ Point2D(-0.72, -0.432)
1027
+ >>> r in line
1028
+ True
1029
+ >>> Ray(p1, p2).random_point(seed=42).n(3)
1030
+ Point2D(0.72, 0.432)
1031
+ >>> Segment(p1, p2).random_point(seed=42).n(3)
1032
+ Point2D(3.2, 1.92)
1033
+
1034
+ """
1035
+ if seed is not None:
1036
+ rng = random.Random(seed)
1037
+ else:
1038
+ rng = random
1039
+ pt = self.arbitrary_point(t)
1040
+ if isinstance(self, Ray):
1041
+ v = abs(rng.gauss(0, 1))
1042
+ elif isinstance(self, Segment):
1043
+ v = rng.random()
1044
+ elif isinstance(self, Line):
1045
+ v = rng.gauss(0, 1)
1046
+ else:
1047
+ raise NotImplementedError('unhandled line type')
1048
+ return pt.subs(t, Rational(v))
1049
+
1050
+ def bisectors(self, other):
1051
+ """Returns the perpendicular lines which pass through the intersections
1052
+ of self and other that are in the same plane.
1053
+
1054
+ Parameters
1055
+ ==========
1056
+
1057
+ line : Line3D
1058
+
1059
+ Returns
1060
+ =======
1061
+
1062
+ list: two Line instances
1063
+
1064
+ Examples
1065
+ ========
1066
+
1067
+ >>> from sympy import Point3D, Line3D
1068
+ >>> r1 = Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0))
1069
+ >>> r2 = Line3D(Point3D(0, 0, 0), Point3D(0, 1, 0))
1070
+ >>> r1.bisectors(r2)
1071
+ [Line3D(Point3D(0, 0, 0), Point3D(1, 1, 0)), Line3D(Point3D(0, 0, 0), Point3D(1, -1, 0))]
1072
+
1073
+ """
1074
+ if not isinstance(other, LinearEntity):
1075
+ raise GeometryError("Expecting LinearEntity, not %s" % other)
1076
+
1077
+ l1, l2 = self, other
1078
+
1079
+ # make sure dimensions match or else a warning will rise from
1080
+ # intersection calculation
1081
+ if l1.p1.ambient_dimension != l2.p1.ambient_dimension:
1082
+ if isinstance(l1, Line2D):
1083
+ l1, l2 = l2, l1
1084
+ _, p1 = Point._normalize_dimension(l1.p1, l2.p1, on_morph='ignore')
1085
+ _, p2 = Point._normalize_dimension(l1.p2, l2.p2, on_morph='ignore')
1086
+ l2 = Line(p1, p2)
1087
+
1088
+ point = intersection(l1, l2)
1089
+
1090
+ # Three cases: Lines may intersect in a point, may be equal or may not intersect.
1091
+ if not point:
1092
+ raise GeometryError("The lines do not intersect")
1093
+ else:
1094
+ pt = point[0]
1095
+ if isinstance(pt, Line):
1096
+ # Intersection is a line because both lines are coincident
1097
+ return [self]
1098
+
1099
+
1100
+ d1 = l1.direction.unit
1101
+ d2 = l2.direction.unit
1102
+
1103
+ bis1 = Line(pt, pt + d1 + d2)
1104
+ bis2 = Line(pt, pt + d1 - d2)
1105
+
1106
+ return [bis1, bis2]
1107
+
1108
+
1109
+ class Line(LinearEntity):
1110
+ """An infinite line in space.
1111
+
1112
+ A 2D line is declared with two distinct points, point and slope, or
1113
+ an equation. A 3D line may be defined with a point and a direction ratio.
1114
+
1115
+ Parameters
1116
+ ==========
1117
+
1118
+ p1 : Point
1119
+ p2 : Point
1120
+ slope : SymPy expression
1121
+ direction_ratio : list
1122
+ equation : equation of a line
1123
+
1124
+ Notes
1125
+ =====
1126
+
1127
+ `Line` will automatically subclass to `Line2D` or `Line3D` based
1128
+ on the dimension of `p1`. The `slope` argument is only relevant
1129
+ for `Line2D` and the `direction_ratio` argument is only relevant
1130
+ for `Line3D`.
1131
+
1132
+ The order of the points will define the direction of the line
1133
+ which is used when calculating the angle between lines.
1134
+
1135
+ See Also
1136
+ ========
1137
+
1138
+ sympy.geometry.point.Point
1139
+ sympy.geometry.line.Line2D
1140
+ sympy.geometry.line.Line3D
1141
+
1142
+ Examples
1143
+ ========
1144
+
1145
+ >>> from sympy import Line, Segment, Point, Eq
1146
+ >>> from sympy.abc import x, y, a, b
1147
+
1148
+ >>> L = Line(Point(2,3), Point(3,5))
1149
+ >>> L
1150
+ Line2D(Point2D(2, 3), Point2D(3, 5))
1151
+ >>> L.points
1152
+ (Point2D(2, 3), Point2D(3, 5))
1153
+ >>> L.equation()
1154
+ -2*x + y + 1
1155
+ >>> L.coefficients
1156
+ (-2, 1, 1)
1157
+
1158
+ Instantiate with keyword ``slope``:
1159
+
1160
+ >>> Line(Point(0, 0), slope=0)
1161
+ Line2D(Point2D(0, 0), Point2D(1, 0))
1162
+
1163
+ Instantiate with another linear object
1164
+
1165
+ >>> s = Segment((0, 0), (0, 1))
1166
+ >>> Line(s).equation()
1167
+ x
1168
+
1169
+ The line corresponding to an equation in the for `ax + by + c = 0`,
1170
+ can be entered:
1171
+
1172
+ >>> Line(3*x + y + 18)
1173
+ Line2D(Point2D(0, -18), Point2D(1, -21))
1174
+
1175
+ If `x` or `y` has a different name, then they can be specified, too,
1176
+ as a string (to match the name) or symbol:
1177
+
1178
+ >>> Line(Eq(3*a + b, -18), x='a', y=b)
1179
+ Line2D(Point2D(0, -18), Point2D(1, -21))
1180
+ """
1181
+ def __new__(cls, *args, **kwargs):
1182
+ if len(args) == 1 and isinstance(args[0], (Expr, Eq)):
1183
+ missing = uniquely_named_symbol('?', args)
1184
+ if not kwargs:
1185
+ x = 'x'
1186
+ y = 'y'
1187
+ else:
1188
+ x = kwargs.pop('x', missing)
1189
+ y = kwargs.pop('y', missing)
1190
+ if kwargs:
1191
+ raise ValueError('expecting only x and y as keywords')
1192
+
1193
+ equation = args[0]
1194
+ if isinstance(equation, Eq):
1195
+ equation = equation.lhs - equation.rhs
1196
+
1197
+ def find_or_missing(x):
1198
+ try:
1199
+ return find(x, equation)
1200
+ except ValueError:
1201
+ return missing
1202
+ x = find_or_missing(x)
1203
+ y = find_or_missing(y)
1204
+
1205
+ a, b, c = linear_coeffs(equation, x, y)
1206
+
1207
+ if b:
1208
+ return Line((0, -c/b), slope=-a/b)
1209
+ if a:
1210
+ return Line((-c/a, 0), slope=oo)
1211
+
1212
+ raise ValueError('not found in equation: %s' % (set('xy') - {x, y}))
1213
+
1214
+ else:
1215
+ if len(args) > 0:
1216
+ p1 = args[0]
1217
+ if len(args) > 1:
1218
+ p2 = args[1]
1219
+ else:
1220
+ p2 = None
1221
+
1222
+ if isinstance(p1, LinearEntity):
1223
+ if p2:
1224
+ raise ValueError('If p1 is a LinearEntity, p2 must be None.')
1225
+ dim = len(p1.p1)
1226
+ else:
1227
+ p1 = Point(p1)
1228
+ dim = len(p1)
1229
+ if p2 is not None or isinstance(p2, Point) and p2.ambient_dimension != dim:
1230
+ p2 = Point(p2)
1231
+
1232
+ if dim == 2:
1233
+ return Line2D(p1, p2, **kwargs)
1234
+ elif dim == 3:
1235
+ return Line3D(p1, p2, **kwargs)
1236
+ return LinearEntity.__new__(cls, p1, p2, **kwargs)
1237
+
1238
+ def contains(self, other):
1239
+ """
1240
+ Return True if `other` is on this Line, or False otherwise.
1241
+
1242
+ Examples
1243
+ ========
1244
+
1245
+ >>> from sympy import Line,Point
1246
+ >>> p1, p2 = Point(0, 1), Point(3, 4)
1247
+ >>> l = Line(p1, p2)
1248
+ >>> l.contains(p1)
1249
+ True
1250
+ >>> l.contains((0, 1))
1251
+ True
1252
+ >>> l.contains((0, 0))
1253
+ False
1254
+ >>> a = (0, 0, 0)
1255
+ >>> b = (1, 1, 1)
1256
+ >>> c = (2, 2, 2)
1257
+ >>> l1 = Line(a, b)
1258
+ >>> l2 = Line(b, a)
1259
+ >>> l1 == l2
1260
+ False
1261
+ >>> l1 in l2
1262
+ True
1263
+
1264
+ """
1265
+ if not isinstance(other, GeometryEntity):
1266
+ other = Point(other, dim=self.ambient_dimension)
1267
+ if isinstance(other, Point):
1268
+ return Point.is_collinear(other, self.p1, self.p2)
1269
+ if isinstance(other, LinearEntity):
1270
+ return Point.is_collinear(self.p1, self.p2, other.p1, other.p2)
1271
+ return False
1272
+
1273
+ def distance(self, other):
1274
+ """
1275
+ Finds the shortest distance between a line and a point.
1276
+
1277
+ Raises
1278
+ ======
1279
+
1280
+ NotImplementedError is raised if `other` is not a Point
1281
+
1282
+ Examples
1283
+ ========
1284
+
1285
+ >>> from sympy import Point, Line
1286
+ >>> p1, p2 = Point(0, 0), Point(1, 1)
1287
+ >>> s = Line(p1, p2)
1288
+ >>> s.distance(Point(-1, 1))
1289
+ sqrt(2)
1290
+ >>> s.distance((-1, 2))
1291
+ 3*sqrt(2)/2
1292
+ >>> p1, p2 = Point(0, 0, 0), Point(1, 1, 1)
1293
+ >>> s = Line(p1, p2)
1294
+ >>> s.distance(Point(-1, 1, 1))
1295
+ 2*sqrt(6)/3
1296
+ >>> s.distance((-1, 1, 1))
1297
+ 2*sqrt(6)/3
1298
+
1299
+ """
1300
+ if not isinstance(other, GeometryEntity):
1301
+ other = Point(other, dim=self.ambient_dimension)
1302
+ if self.contains(other):
1303
+ return S.Zero
1304
+ return self.perpendicular_segment(other).length
1305
+
1306
+ def equals(self, other):
1307
+ """Returns True if self and other are the same mathematical entities"""
1308
+ if not isinstance(other, Line):
1309
+ return False
1310
+ return Point.is_collinear(self.p1, other.p1, self.p2, other.p2)
1311
+
1312
+ def plot_interval(self, parameter='t'):
1313
+ """The plot interval for the default geometric plot of line. Gives
1314
+ values that will produce a line that is +/- 5 units long (where a
1315
+ unit is the distance between the two points that define the line).
1316
+
1317
+ Parameters
1318
+ ==========
1319
+
1320
+ parameter : str, optional
1321
+ Default value is 't'.
1322
+
1323
+ Returns
1324
+ =======
1325
+
1326
+ plot_interval : list (plot interval)
1327
+ [parameter, lower_bound, upper_bound]
1328
+
1329
+ Examples
1330
+ ========
1331
+
1332
+ >>> from sympy import Point, Line
1333
+ >>> p1, p2 = Point(0, 0), Point(5, 3)
1334
+ >>> l1 = Line(p1, p2)
1335
+ >>> l1.plot_interval()
1336
+ [t, -5, 5]
1337
+
1338
+ """
1339
+ t = _symbol(parameter, real=True)
1340
+ return [t, -5, 5]
1341
+
1342
+
1343
+ class Ray(LinearEntity):
1344
+ """A Ray is a semi-line in the space with a source point and a direction.
1345
+
1346
+ Parameters
1347
+ ==========
1348
+
1349
+ p1 : Point
1350
+ The source of the Ray
1351
+ p2 : Point or radian value
1352
+ This point determines the direction in which the Ray propagates.
1353
+ If given as an angle it is interpreted in radians with the positive
1354
+ direction being ccw.
1355
+
1356
+ Attributes
1357
+ ==========
1358
+
1359
+ source
1360
+
1361
+ See Also
1362
+ ========
1363
+
1364
+ sympy.geometry.line.Ray2D
1365
+ sympy.geometry.line.Ray3D
1366
+ sympy.geometry.point.Point
1367
+ sympy.geometry.line.Line
1368
+
1369
+ Notes
1370
+ =====
1371
+
1372
+ `Ray` will automatically subclass to `Ray2D` or `Ray3D` based on the
1373
+ dimension of `p1`.
1374
+
1375
+ Examples
1376
+ ========
1377
+
1378
+ >>> from sympy import Ray, Point, pi
1379
+ >>> r = Ray(Point(2, 3), Point(3, 5))
1380
+ >>> r
1381
+ Ray2D(Point2D(2, 3), Point2D(3, 5))
1382
+ >>> r.points
1383
+ (Point2D(2, 3), Point2D(3, 5))
1384
+ >>> r.source
1385
+ Point2D(2, 3)
1386
+ >>> r.xdirection
1387
+ oo
1388
+ >>> r.ydirection
1389
+ oo
1390
+ >>> r.slope
1391
+ 2
1392
+ >>> Ray(Point(0, 0), angle=pi/4).slope
1393
+ 1
1394
+
1395
+ """
1396
+ def __new__(cls, p1, p2=None, **kwargs):
1397
+ p1 = Point(p1)
1398
+ if p2 is not None:
1399
+ p1, p2 = Point._normalize_dimension(p1, Point(p2))
1400
+ dim = len(p1)
1401
+
1402
+ if dim == 2:
1403
+ return Ray2D(p1, p2, **kwargs)
1404
+ elif dim == 3:
1405
+ return Ray3D(p1, p2, **kwargs)
1406
+ return LinearEntity.__new__(cls, p1, p2, **kwargs)
1407
+
1408
+ def _svg(self, scale_factor=1., fill_color="#66cc99"):
1409
+ """Returns SVG path element for the LinearEntity.
1410
+
1411
+ Parameters
1412
+ ==========
1413
+
1414
+ scale_factor : float
1415
+ Multiplication factor for the SVG stroke-width. Default is 1.
1416
+ fill_color : str, optional
1417
+ Hex string for fill color. Default is "#66cc99".
1418
+ """
1419
+ verts = (N(self.p1), N(self.p2))
1420
+ coords = ["{},{}".format(p.x, p.y) for p in verts]
1421
+ path = "M {} L {}".format(coords[0], " L ".join(coords[1:]))
1422
+
1423
+ return (
1424
+ '<path fill-rule="evenodd" fill="{2}" stroke="#555555" '
1425
+ 'stroke-width="{0}" opacity="0.6" d="{1}" '
1426
+ 'marker-start="url(#markerCircle)" marker-end="url(#markerArrow)"/>'
1427
+ ).format(2.*scale_factor, path, fill_color)
1428
+
1429
+ def contains(self, other):
1430
+ """
1431
+ Is other GeometryEntity contained in this Ray?
1432
+
1433
+ Examples
1434
+ ========
1435
+
1436
+ >>> from sympy import Ray,Point,Segment
1437
+ >>> p1, p2 = Point(0, 0), Point(4, 4)
1438
+ >>> r = Ray(p1, p2)
1439
+ >>> r.contains(p1)
1440
+ True
1441
+ >>> r.contains((1, 1))
1442
+ True
1443
+ >>> r.contains((1, 3))
1444
+ False
1445
+ >>> s = Segment((1, 1), (2, 2))
1446
+ >>> r.contains(s)
1447
+ True
1448
+ >>> s = Segment((1, 2), (2, 5))
1449
+ >>> r.contains(s)
1450
+ False
1451
+ >>> r1 = Ray((2, 2), (3, 3))
1452
+ >>> r.contains(r1)
1453
+ True
1454
+ >>> r1 = Ray((2, 2), (3, 5))
1455
+ >>> r.contains(r1)
1456
+ False
1457
+ """
1458
+ if not isinstance(other, GeometryEntity):
1459
+ other = Point(other, dim=self.ambient_dimension)
1460
+ if isinstance(other, Point):
1461
+ if Point.is_collinear(self.p1, self.p2, other):
1462
+ # if we're in the direction of the ray, our
1463
+ # direction vector dot the ray's direction vector
1464
+ # should be non-negative
1465
+ return bool((self.p2 - self.p1).dot(other - self.p1) >= S.Zero)
1466
+ return False
1467
+ elif isinstance(other, Ray):
1468
+ if Point.is_collinear(self.p1, self.p2, other.p1, other.p2):
1469
+ return bool((self.p2 - self.p1).dot(other.p2 - other.p1) > S.Zero)
1470
+ return False
1471
+ elif isinstance(other, Segment):
1472
+ return other.p1 in self and other.p2 in self
1473
+
1474
+ # No other known entity can be contained in a Ray
1475
+ return False
1476
+
1477
+ def distance(self, other):
1478
+ """
1479
+ Finds the shortest distance between the ray and a point.
1480
+
1481
+ Raises
1482
+ ======
1483
+
1484
+ NotImplementedError is raised if `other` is not a Point
1485
+
1486
+ Examples
1487
+ ========
1488
+
1489
+ >>> from sympy import Point, Ray
1490
+ >>> p1, p2 = Point(0, 0), Point(1, 1)
1491
+ >>> s = Ray(p1, p2)
1492
+ >>> s.distance(Point(-1, -1))
1493
+ sqrt(2)
1494
+ >>> s.distance((-1, 2))
1495
+ 3*sqrt(2)/2
1496
+ >>> p1, p2 = Point(0, 0, 0), Point(1, 1, 2)
1497
+ >>> s = Ray(p1, p2)
1498
+ >>> s
1499
+ Ray3D(Point3D(0, 0, 0), Point3D(1, 1, 2))
1500
+ >>> s.distance(Point(-1, -1, 2))
1501
+ 4*sqrt(3)/3
1502
+ >>> s.distance((-1, -1, 2))
1503
+ 4*sqrt(3)/3
1504
+
1505
+ """
1506
+ if not isinstance(other, GeometryEntity):
1507
+ other = Point(other, dim=self.ambient_dimension)
1508
+ if self.contains(other):
1509
+ return S.Zero
1510
+
1511
+ proj = Line(self.p1, self.p2).projection(other)
1512
+ if self.contains(proj):
1513
+ return abs(other - proj)
1514
+ else:
1515
+ return abs(other - self.source)
1516
+
1517
+ def equals(self, other):
1518
+ """Returns True if self and other are the same mathematical entities"""
1519
+ if not isinstance(other, Ray):
1520
+ return False
1521
+ return self.source == other.source and other.p2 in self
1522
+
1523
+ def plot_interval(self, parameter='t'):
1524
+ """The plot interval for the default geometric plot of the Ray. Gives
1525
+ values that will produce a ray that is 10 units long (where a unit is
1526
+ the distance between the two points that define the ray).
1527
+
1528
+ Parameters
1529
+ ==========
1530
+
1531
+ parameter : str, optional
1532
+ Default value is 't'.
1533
+
1534
+ Returns
1535
+ =======
1536
+
1537
+ plot_interval : list
1538
+ [parameter, lower_bound, upper_bound]
1539
+
1540
+ Examples
1541
+ ========
1542
+
1543
+ >>> from sympy import Ray, pi
1544
+ >>> r = Ray((0, 0), angle=pi/4)
1545
+ >>> r.plot_interval()
1546
+ [t, 0, 10]
1547
+
1548
+ """
1549
+ t = _symbol(parameter, real=True)
1550
+ return [t, 0, 10]
1551
+
1552
+ @property
1553
+ def source(self):
1554
+ """The point from which the ray emanates.
1555
+
1556
+ See Also
1557
+ ========
1558
+
1559
+ sympy.geometry.point.Point
1560
+
1561
+ Examples
1562
+ ========
1563
+
1564
+ >>> from sympy import Point, Ray
1565
+ >>> p1, p2 = Point(0, 0), Point(4, 1)
1566
+ >>> r1 = Ray(p1, p2)
1567
+ >>> r1.source
1568
+ Point2D(0, 0)
1569
+ >>> p1, p2 = Point(0, 0, 0), Point(4, 1, 5)
1570
+ >>> r1 = Ray(p2, p1)
1571
+ >>> r1.source
1572
+ Point3D(4, 1, 5)
1573
+
1574
+ """
1575
+ return self.p1
1576
+
1577
+
1578
+ class Segment(LinearEntity):
1579
+ """A line segment in space.
1580
+
1581
+ Parameters
1582
+ ==========
1583
+
1584
+ p1 : Point
1585
+ p2 : Point
1586
+
1587
+ Attributes
1588
+ ==========
1589
+
1590
+ length : number or SymPy expression
1591
+ midpoint : Point
1592
+
1593
+ See Also
1594
+ ========
1595
+
1596
+ sympy.geometry.line.Segment2D
1597
+ sympy.geometry.line.Segment3D
1598
+ sympy.geometry.point.Point
1599
+ sympy.geometry.line.Line
1600
+
1601
+ Notes
1602
+ =====
1603
+
1604
+ If 2D or 3D points are used to define `Segment`, it will
1605
+ be automatically subclassed to `Segment2D` or `Segment3D`.
1606
+
1607
+ Examples
1608
+ ========
1609
+
1610
+ >>> from sympy import Point, Segment
1611
+ >>> Segment((1, 0), (1, 1)) # tuples are interpreted as pts
1612
+ Segment2D(Point2D(1, 0), Point2D(1, 1))
1613
+ >>> s = Segment(Point(4, 3), Point(1, 1))
1614
+ >>> s.points
1615
+ (Point2D(4, 3), Point2D(1, 1))
1616
+ >>> s.slope
1617
+ 2/3
1618
+ >>> s.length
1619
+ sqrt(13)
1620
+ >>> s.midpoint
1621
+ Point2D(5/2, 2)
1622
+ >>> Segment((1, 0, 0), (1, 1, 1)) # tuples are interpreted as pts
1623
+ Segment3D(Point3D(1, 0, 0), Point3D(1, 1, 1))
1624
+ >>> s = Segment(Point(4, 3, 9), Point(1, 1, 7)); s
1625
+ Segment3D(Point3D(4, 3, 9), Point3D(1, 1, 7))
1626
+ >>> s.points
1627
+ (Point3D(4, 3, 9), Point3D(1, 1, 7))
1628
+ >>> s.length
1629
+ sqrt(17)
1630
+ >>> s.midpoint
1631
+ Point3D(5/2, 2, 8)
1632
+
1633
+ """
1634
+ def __new__(cls, p1, p2, **kwargs):
1635
+ p1, p2 = Point._normalize_dimension(Point(p1), Point(p2))
1636
+ dim = len(p1)
1637
+
1638
+ if dim == 2:
1639
+ return Segment2D(p1, p2, **kwargs)
1640
+ elif dim == 3:
1641
+ return Segment3D(p1, p2, **kwargs)
1642
+ return LinearEntity.__new__(cls, p1, p2, **kwargs)
1643
+
1644
+ def contains(self, other):
1645
+ """
1646
+ Is the other GeometryEntity contained within this Segment?
1647
+
1648
+ Examples
1649
+ ========
1650
+
1651
+ >>> from sympy import Point, Segment
1652
+ >>> p1, p2 = Point(0, 1), Point(3, 4)
1653
+ >>> s = Segment(p1, p2)
1654
+ >>> s2 = Segment(p2, p1)
1655
+ >>> s.contains(s2)
1656
+ True
1657
+ >>> from sympy import Point3D, Segment3D
1658
+ >>> p1, p2 = Point3D(0, 1, 1), Point3D(3, 4, 5)
1659
+ >>> s = Segment3D(p1, p2)
1660
+ >>> s2 = Segment3D(p2, p1)
1661
+ >>> s.contains(s2)
1662
+ True
1663
+ >>> s.contains((p1 + p2)/2)
1664
+ True
1665
+ """
1666
+ if not isinstance(other, GeometryEntity):
1667
+ other = Point(other, dim=self.ambient_dimension)
1668
+ if isinstance(other, Point):
1669
+ if Point.is_collinear(other, self.p1, self.p2):
1670
+ if isinstance(self, Segment2D):
1671
+ # if it is collinear and is in the bounding box of the
1672
+ # segment then it must be on the segment
1673
+ vert = (1/self.slope).equals(0)
1674
+ if vert is False:
1675
+ isin = (self.p1.x - other.x)*(self.p2.x - other.x) <= 0
1676
+ if isin in (True, False):
1677
+ return isin
1678
+ if vert is True:
1679
+ isin = (self.p1.y - other.y)*(self.p2.y - other.y) <= 0
1680
+ if isin in (True, False):
1681
+ return isin
1682
+ # use the triangle inequality
1683
+ d1, d2 = other - self.p1, other - self.p2
1684
+ d = self.p2 - self.p1
1685
+ # without the call to simplify, SymPy cannot tell that an expression
1686
+ # like (a+b)*(a/2+b/2) is always non-negative. If it cannot be
1687
+ # determined, raise an Undecidable error
1688
+ try:
1689
+ # the triangle inequality says that |d1|+|d2| >= |d| and is strict
1690
+ # only if other lies in the line segment
1691
+ return bool(simplify(Eq(abs(d1) + abs(d2) - abs(d), 0)))
1692
+ except TypeError:
1693
+ raise Undecidable("Cannot determine if {} is in {}".format(other, self))
1694
+ if isinstance(other, Segment):
1695
+ return other.p1 in self and other.p2 in self
1696
+
1697
+ return False
1698
+
1699
+ def equals(self, other):
1700
+ """Returns True if self and other are the same mathematical entities"""
1701
+ return isinstance(other, self.func) and list(
1702
+ ordered(self.args)) == list(ordered(other.args))
1703
+
1704
+ def distance(self, other):
1705
+ """
1706
+ Finds the shortest distance between a line segment and a point.
1707
+
1708
+ Raises
1709
+ ======
1710
+
1711
+ NotImplementedError is raised if `other` is not a Point
1712
+
1713
+ Examples
1714
+ ========
1715
+
1716
+ >>> from sympy import Point, Segment
1717
+ >>> p1, p2 = Point(0, 1), Point(3, 4)
1718
+ >>> s = Segment(p1, p2)
1719
+ >>> s.distance(Point(10, 15))
1720
+ sqrt(170)
1721
+ >>> s.distance((0, 12))
1722
+ sqrt(73)
1723
+ >>> from sympy import Point3D, Segment3D
1724
+ >>> p1, p2 = Point3D(0, 0, 3), Point3D(1, 1, 4)
1725
+ >>> s = Segment3D(p1, p2)
1726
+ >>> s.distance(Point3D(10, 15, 12))
1727
+ sqrt(341)
1728
+ >>> s.distance((10, 15, 12))
1729
+ sqrt(341)
1730
+ """
1731
+ if not isinstance(other, GeometryEntity):
1732
+ other = Point(other, dim=self.ambient_dimension)
1733
+ if isinstance(other, Point):
1734
+ vp1 = other - self.p1
1735
+ vp2 = other - self.p2
1736
+
1737
+ dot_prod_sign_1 = self.direction.dot(vp1) >= 0
1738
+ dot_prod_sign_2 = self.direction.dot(vp2) <= 0
1739
+ if dot_prod_sign_1 and dot_prod_sign_2:
1740
+ return Line(self.p1, self.p2).distance(other)
1741
+ if dot_prod_sign_1 and not dot_prod_sign_2:
1742
+ return abs(vp2)
1743
+ if not dot_prod_sign_1 and dot_prod_sign_2:
1744
+ return abs(vp1)
1745
+ raise NotImplementedError()
1746
+
1747
+ @property
1748
+ def length(self):
1749
+ """The length of the line segment.
1750
+
1751
+ See Also
1752
+ ========
1753
+
1754
+ sympy.geometry.point.Point.distance
1755
+
1756
+ Examples
1757
+ ========
1758
+
1759
+ >>> from sympy import Point, Segment
1760
+ >>> p1, p2 = Point(0, 0), Point(4, 3)
1761
+ >>> s1 = Segment(p1, p2)
1762
+ >>> s1.length
1763
+ 5
1764
+ >>> from sympy import Point3D, Segment3D
1765
+ >>> p1, p2 = Point3D(0, 0, 0), Point3D(4, 3, 3)
1766
+ >>> s1 = Segment3D(p1, p2)
1767
+ >>> s1.length
1768
+ sqrt(34)
1769
+
1770
+ """
1771
+ return Point.distance(self.p1, self.p2)
1772
+
1773
+ @property
1774
+ def midpoint(self):
1775
+ """The midpoint of the line segment.
1776
+
1777
+ See Also
1778
+ ========
1779
+
1780
+ sympy.geometry.point.Point.midpoint
1781
+
1782
+ Examples
1783
+ ========
1784
+
1785
+ >>> from sympy import Point, Segment
1786
+ >>> p1, p2 = Point(0, 0), Point(4, 3)
1787
+ >>> s1 = Segment(p1, p2)
1788
+ >>> s1.midpoint
1789
+ Point2D(2, 3/2)
1790
+ >>> from sympy import Point3D, Segment3D
1791
+ >>> p1, p2 = Point3D(0, 0, 0), Point3D(4, 3, 3)
1792
+ >>> s1 = Segment3D(p1, p2)
1793
+ >>> s1.midpoint
1794
+ Point3D(2, 3/2, 3/2)
1795
+
1796
+ """
1797
+ return Point.midpoint(self.p1, self.p2)
1798
+
1799
+ def perpendicular_bisector(self, p=None):
1800
+ """The perpendicular bisector of this segment.
1801
+
1802
+ If no point is specified or the point specified is not on the
1803
+ bisector then the bisector is returned as a Line. Otherwise a
1804
+ Segment is returned that joins the point specified and the
1805
+ intersection of the bisector and the segment.
1806
+
1807
+ Parameters
1808
+ ==========
1809
+
1810
+ p : Point
1811
+
1812
+ Returns
1813
+ =======
1814
+
1815
+ bisector : Line or Segment
1816
+
1817
+ See Also
1818
+ ========
1819
+
1820
+ LinearEntity.perpendicular_segment
1821
+
1822
+ Examples
1823
+ ========
1824
+
1825
+ >>> from sympy import Point, Segment
1826
+ >>> p1, p2, p3 = Point(0, 0), Point(6, 6), Point(5, 1)
1827
+ >>> s1 = Segment(p1, p2)
1828
+ >>> s1.perpendicular_bisector()
1829
+ Line2D(Point2D(3, 3), Point2D(-3, 9))
1830
+
1831
+ >>> s1.perpendicular_bisector(p3)
1832
+ Segment2D(Point2D(5, 1), Point2D(3, 3))
1833
+
1834
+ """
1835
+ l = self.perpendicular_line(self.midpoint)
1836
+ if p is not None:
1837
+ p2 = Point(p, dim=self.ambient_dimension)
1838
+ if p2 in l:
1839
+ return Segment(p2, self.midpoint)
1840
+ return l
1841
+
1842
+ def plot_interval(self, parameter='t'):
1843
+ """The plot interval for the default geometric plot of the Segment gives
1844
+ values that will produce the full segment in a plot.
1845
+
1846
+ Parameters
1847
+ ==========
1848
+
1849
+ parameter : str, optional
1850
+ Default value is 't'.
1851
+
1852
+ Returns
1853
+ =======
1854
+
1855
+ plot_interval : list
1856
+ [parameter, lower_bound, upper_bound]
1857
+
1858
+ Examples
1859
+ ========
1860
+
1861
+ >>> from sympy import Point, Segment
1862
+ >>> p1, p2 = Point(0, 0), Point(5, 3)
1863
+ >>> s1 = Segment(p1, p2)
1864
+ >>> s1.plot_interval()
1865
+ [t, 0, 1]
1866
+
1867
+ """
1868
+ t = _symbol(parameter, real=True)
1869
+ return [t, 0, 1]
1870
+
1871
+
1872
+ class LinearEntity2D(LinearEntity):
1873
+ """A base class for all linear entities (line, ray and segment)
1874
+ in a 2-dimensional Euclidean space.
1875
+
1876
+ Attributes
1877
+ ==========
1878
+
1879
+ p1
1880
+ p2
1881
+ coefficients
1882
+ slope
1883
+ points
1884
+
1885
+ Notes
1886
+ =====
1887
+
1888
+ This is an abstract class and is not meant to be instantiated.
1889
+
1890
+ See Also
1891
+ ========
1892
+
1893
+ sympy.geometry.entity.GeometryEntity
1894
+
1895
+ """
1896
+ @property
1897
+ def bounds(self):
1898
+ """Return a tuple (xmin, ymin, xmax, ymax) representing the bounding
1899
+ rectangle for the geometric figure.
1900
+
1901
+ """
1902
+ verts = self.points
1903
+ xs = [p.x for p in verts]
1904
+ ys = [p.y for p in verts]
1905
+ return (min(xs), min(ys), max(xs), max(ys))
1906
+
1907
+ def perpendicular_line(self, p):
1908
+ """Create a new Line perpendicular to this linear entity which passes
1909
+ through the point `p`.
1910
+
1911
+ Parameters
1912
+ ==========
1913
+
1914
+ p : Point
1915
+
1916
+ Returns
1917
+ =======
1918
+
1919
+ line : Line
1920
+
1921
+ See Also
1922
+ ========
1923
+
1924
+ sympy.geometry.line.LinearEntity.is_perpendicular, perpendicular_segment
1925
+
1926
+ Examples
1927
+ ========
1928
+
1929
+ >>> from sympy import Point, Line
1930
+ >>> p1, p2, p3 = Point(0, 0), Point(2, 3), Point(-2, 2)
1931
+ >>> L = Line(p1, p2)
1932
+ >>> P = L.perpendicular_line(p3); P
1933
+ Line2D(Point2D(-2, 2), Point2D(-5, 4))
1934
+ >>> L.is_perpendicular(P)
1935
+ True
1936
+
1937
+ In 2D, the first point of the perpendicular line is the
1938
+ point through which was required to pass; the second
1939
+ point is arbitrarily chosen. To get a line that explicitly
1940
+ uses a point in the line, create a line from the perpendicular
1941
+ segment from the line to the point:
1942
+
1943
+ >>> Line(L.perpendicular_segment(p3))
1944
+ Line2D(Point2D(-2, 2), Point2D(4/13, 6/13))
1945
+ """
1946
+ p = Point(p, dim=self.ambient_dimension)
1947
+ # any two lines in R^2 intersect, so blindly making
1948
+ # a line through p in an orthogonal direction will work
1949
+ # and is faster than finding the projection point as in 3D
1950
+ return Line(p, p + self.direction.orthogonal_direction)
1951
+
1952
+ @property
1953
+ def slope(self):
1954
+ """The slope of this linear entity, or infinity if vertical.
1955
+
1956
+ Returns
1957
+ =======
1958
+
1959
+ slope : number or SymPy expression
1960
+
1961
+ See Also
1962
+ ========
1963
+
1964
+ coefficients
1965
+
1966
+ Examples
1967
+ ========
1968
+
1969
+ >>> from sympy import Point, Line
1970
+ >>> p1, p2 = Point(0, 0), Point(3, 5)
1971
+ >>> l1 = Line(p1, p2)
1972
+ >>> l1.slope
1973
+ 5/3
1974
+
1975
+ >>> p3 = Point(0, 4)
1976
+ >>> l2 = Line(p1, p3)
1977
+ >>> l2.slope
1978
+ oo
1979
+
1980
+ """
1981
+ d1, d2 = (self.p1 - self.p2).args
1982
+ if d1 == 0:
1983
+ return S.Infinity
1984
+ return simplify(d2/d1)
1985
+
1986
+
1987
+ class Line2D(LinearEntity2D, Line):
1988
+ """An infinite line in space 2D.
1989
+
1990
+ A line is declared with two distinct points or a point and slope
1991
+ as defined using keyword `slope`.
1992
+
1993
+ Parameters
1994
+ ==========
1995
+
1996
+ p1 : Point
1997
+ pt : Point
1998
+ slope : SymPy expression
1999
+
2000
+ See Also
2001
+ ========
2002
+
2003
+ sympy.geometry.point.Point
2004
+
2005
+ Examples
2006
+ ========
2007
+
2008
+ >>> from sympy import Line, Segment, Point
2009
+ >>> L = Line(Point(2,3), Point(3,5))
2010
+ >>> L
2011
+ Line2D(Point2D(2, 3), Point2D(3, 5))
2012
+ >>> L.points
2013
+ (Point2D(2, 3), Point2D(3, 5))
2014
+ >>> L.equation()
2015
+ -2*x + y + 1
2016
+ >>> L.coefficients
2017
+ (-2, 1, 1)
2018
+
2019
+ Instantiate with keyword ``slope``:
2020
+
2021
+ >>> Line(Point(0, 0), slope=0)
2022
+ Line2D(Point2D(0, 0), Point2D(1, 0))
2023
+
2024
+ Instantiate with another linear object
2025
+
2026
+ >>> s = Segment((0, 0), (0, 1))
2027
+ >>> Line(s).equation()
2028
+ x
2029
+ """
2030
+ def __new__(cls, p1, pt=None, slope=None, **kwargs):
2031
+ if isinstance(p1, LinearEntity):
2032
+ if pt is not None:
2033
+ raise ValueError('When p1 is a LinearEntity, pt should be None')
2034
+ p1, pt = Point._normalize_dimension(*p1.args, dim=2)
2035
+ else:
2036
+ p1 = Point(p1, dim=2)
2037
+ if pt is not None and slope is None:
2038
+ try:
2039
+ p2 = Point(pt, dim=2)
2040
+ except (NotImplementedError, TypeError, ValueError):
2041
+ raise ValueError(filldedent('''
2042
+ The 2nd argument was not a valid Point.
2043
+ If it was a slope, enter it with keyword "slope".
2044
+ '''))
2045
+ elif slope is not None and pt is None:
2046
+ slope = sympify(slope)
2047
+ if slope.is_finite is False:
2048
+ # when infinite slope, don't change x
2049
+ dx = 0
2050
+ dy = 1
2051
+ else:
2052
+ # go over 1 up slope
2053
+ dx = 1
2054
+ dy = slope
2055
+ # XXX avoiding simplification by adding to coords directly
2056
+ p2 = Point(p1.x + dx, p1.y + dy, evaluate=False)
2057
+ else:
2058
+ raise ValueError('A 2nd Point or keyword "slope" must be used.')
2059
+ return LinearEntity2D.__new__(cls, p1, p2, **kwargs)
2060
+
2061
+ def _svg(self, scale_factor=1., fill_color="#66cc99"):
2062
+ """Returns SVG path element for the LinearEntity.
2063
+
2064
+ Parameters
2065
+ ==========
2066
+
2067
+ scale_factor : float
2068
+ Multiplication factor for the SVG stroke-width. Default is 1.
2069
+ fill_color : str, optional
2070
+ Hex string for fill color. Default is "#66cc99".
2071
+ """
2072
+ verts = (N(self.p1), N(self.p2))
2073
+ coords = ["{},{}".format(p.x, p.y) for p in verts]
2074
+ path = "M {} L {}".format(coords[0], " L ".join(coords[1:]))
2075
+
2076
+ return (
2077
+ '<path fill-rule="evenodd" fill="{2}" stroke="#555555" '
2078
+ 'stroke-width="{0}" opacity="0.6" d="{1}" '
2079
+ 'marker-start="url(#markerReverseArrow)" marker-end="url(#markerArrow)"/>'
2080
+ ).format(2.*scale_factor, path, fill_color)
2081
+
2082
+ @property
2083
+ def coefficients(self):
2084
+ """The coefficients (`a`, `b`, `c`) for `ax + by + c = 0`.
2085
+
2086
+ See Also
2087
+ ========
2088
+
2089
+ sympy.geometry.line.Line2D.equation
2090
+
2091
+ Examples
2092
+ ========
2093
+
2094
+ >>> from sympy import Point, Line
2095
+ >>> from sympy.abc import x, y
2096
+ >>> p1, p2 = Point(0, 0), Point(5, 3)
2097
+ >>> l = Line(p1, p2)
2098
+ >>> l.coefficients
2099
+ (-3, 5, 0)
2100
+
2101
+ >>> p3 = Point(x, y)
2102
+ >>> l2 = Line(p1, p3)
2103
+ >>> l2.coefficients
2104
+ (-y, x, 0)
2105
+
2106
+ """
2107
+ p1, p2 = self.points
2108
+ if p1.x == p2.x:
2109
+ return (S.One, S.Zero, -p1.x)
2110
+ elif p1.y == p2.y:
2111
+ return (S.Zero, S.One, -p1.y)
2112
+ return tuple([simplify(i) for i in
2113
+ (self.p1.y - self.p2.y,
2114
+ self.p2.x - self.p1.x,
2115
+ self.p1.x*self.p2.y - self.p1.y*self.p2.x)])
2116
+
2117
+ def equation(self, x='x', y='y'):
2118
+ """The equation of the line: ax + by + c.
2119
+
2120
+ Parameters
2121
+ ==========
2122
+
2123
+ x : str, optional
2124
+ The name to use for the x-axis, default value is 'x'.
2125
+ y : str, optional
2126
+ The name to use for the y-axis, default value is 'y'.
2127
+
2128
+ Returns
2129
+ =======
2130
+
2131
+ equation : SymPy expression
2132
+
2133
+ See Also
2134
+ ========
2135
+
2136
+ sympy.geometry.line.Line2D.coefficients
2137
+
2138
+ Examples
2139
+ ========
2140
+
2141
+ >>> from sympy import Point, Line
2142
+ >>> p1, p2 = Point(1, 0), Point(5, 3)
2143
+ >>> l1 = Line(p1, p2)
2144
+ >>> l1.equation()
2145
+ -3*x + 4*y + 3
2146
+
2147
+ """
2148
+ x = _symbol(x, real=True)
2149
+ y = _symbol(y, real=True)
2150
+ p1, p2 = self.points
2151
+ if p1.x == p2.x:
2152
+ return x - p1.x
2153
+ elif p1.y == p2.y:
2154
+ return y - p1.y
2155
+
2156
+ a, b, c = self.coefficients
2157
+ return a*x + b*y + c
2158
+
2159
+
2160
+ class Ray2D(LinearEntity2D, Ray):
2161
+ """
2162
+ A Ray is a semi-line in the space with a source point and a direction.
2163
+
2164
+ Parameters
2165
+ ==========
2166
+
2167
+ p1 : Point
2168
+ The source of the Ray
2169
+ p2 : Point or radian value
2170
+ This point determines the direction in which the Ray propagates.
2171
+ If given as an angle it is interpreted in radians with the positive
2172
+ direction being ccw.
2173
+
2174
+ Attributes
2175
+ ==========
2176
+
2177
+ source
2178
+ xdirection
2179
+ ydirection
2180
+
2181
+ See Also
2182
+ ========
2183
+
2184
+ sympy.geometry.point.Point, Line
2185
+
2186
+ Examples
2187
+ ========
2188
+
2189
+ >>> from sympy import Point, pi, Ray
2190
+ >>> r = Ray(Point(2, 3), Point(3, 5))
2191
+ >>> r
2192
+ Ray2D(Point2D(2, 3), Point2D(3, 5))
2193
+ >>> r.points
2194
+ (Point2D(2, 3), Point2D(3, 5))
2195
+ >>> r.source
2196
+ Point2D(2, 3)
2197
+ >>> r.xdirection
2198
+ oo
2199
+ >>> r.ydirection
2200
+ oo
2201
+ >>> r.slope
2202
+ 2
2203
+ >>> Ray(Point(0, 0), angle=pi/4).slope
2204
+ 1
2205
+
2206
+ """
2207
+ def __new__(cls, p1, pt=None, angle=None, **kwargs):
2208
+ p1 = Point(p1, dim=2)
2209
+ if pt is not None and angle is None:
2210
+ try:
2211
+ p2 = Point(pt, dim=2)
2212
+ except (NotImplementedError, TypeError, ValueError):
2213
+ raise ValueError(filldedent('''
2214
+ The 2nd argument was not a valid Point; if
2215
+ it was meant to be an angle it should be
2216
+ given with keyword "angle".'''))
2217
+ if p1 == p2:
2218
+ raise ValueError('A Ray requires two distinct points.')
2219
+ elif angle is not None and pt is None:
2220
+ # we need to know if the angle is an odd multiple of pi/2
2221
+ angle = sympify(angle)
2222
+ c = _pi_coeff(angle)
2223
+ p2 = None
2224
+ if c is not None:
2225
+ if c.is_Rational:
2226
+ if c.q == 2:
2227
+ if c.p == 1:
2228
+ p2 = p1 + Point(0, 1)
2229
+ elif c.p == 3:
2230
+ p2 = p1 + Point(0, -1)
2231
+ elif c.q == 1:
2232
+ if c.p == 0:
2233
+ p2 = p1 + Point(1, 0)
2234
+ elif c.p == 1:
2235
+ p2 = p1 + Point(-1, 0)
2236
+ if p2 is None:
2237
+ c *= S.Pi
2238
+ else:
2239
+ c = angle % (2*S.Pi)
2240
+ if not p2:
2241
+ m = 2*c/S.Pi
2242
+ left = And(1 < m, m < 3) # is it in quadrant 2 or 3?
2243
+ x = Piecewise((-1, left), (Piecewise((0, Eq(m % 1, 0)), (1, True)), True))
2244
+ y = Piecewise((-tan(c), left), (Piecewise((1, Eq(m, 1)), (-1, Eq(m, 3)), (tan(c), True)), True))
2245
+ p2 = p1 + Point(x, y)
2246
+ else:
2247
+ raise ValueError('A 2nd point or keyword "angle" must be used.')
2248
+
2249
+ return LinearEntity2D.__new__(cls, p1, p2, **kwargs)
2250
+
2251
+ @property
2252
+ def xdirection(self):
2253
+ """The x direction of the ray.
2254
+
2255
+ Positive infinity if the ray points in the positive x direction,
2256
+ negative infinity if the ray points in the negative x direction,
2257
+ or 0 if the ray is vertical.
2258
+
2259
+ See Also
2260
+ ========
2261
+
2262
+ ydirection
2263
+
2264
+ Examples
2265
+ ========
2266
+
2267
+ >>> from sympy import Point, Ray
2268
+ >>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(0, -1)
2269
+ >>> r1, r2 = Ray(p1, p2), Ray(p1, p3)
2270
+ >>> r1.xdirection
2271
+ oo
2272
+ >>> r2.xdirection
2273
+ 0
2274
+
2275
+ """
2276
+ if self.p1.x < self.p2.x:
2277
+ return S.Infinity
2278
+ elif self.p1.x == self.p2.x:
2279
+ return S.Zero
2280
+ else:
2281
+ return S.NegativeInfinity
2282
+
2283
+ @property
2284
+ def ydirection(self):
2285
+ """The y direction of the ray.
2286
+
2287
+ Positive infinity if the ray points in the positive y direction,
2288
+ negative infinity if the ray points in the negative y direction,
2289
+ or 0 if the ray is horizontal.
2290
+
2291
+ See Also
2292
+ ========
2293
+
2294
+ xdirection
2295
+
2296
+ Examples
2297
+ ========
2298
+
2299
+ >>> from sympy import Point, Ray
2300
+ >>> p1, p2, p3 = Point(0, 0), Point(-1, -1), Point(-1, 0)
2301
+ >>> r1, r2 = Ray(p1, p2), Ray(p1, p3)
2302
+ >>> r1.ydirection
2303
+ -oo
2304
+ >>> r2.ydirection
2305
+ 0
2306
+
2307
+ """
2308
+ if self.p1.y < self.p2.y:
2309
+ return S.Infinity
2310
+ elif self.p1.y == self.p2.y:
2311
+ return S.Zero
2312
+ else:
2313
+ return S.NegativeInfinity
2314
+
2315
+ def closing_angle(r1, r2):
2316
+ """Return the angle by which r2 must be rotated so it faces the same
2317
+ direction as r1.
2318
+
2319
+ Parameters
2320
+ ==========
2321
+
2322
+ r1 : Ray2D
2323
+ r2 : Ray2D
2324
+
2325
+ Returns
2326
+ =======
2327
+
2328
+ angle : angle in radians (ccw angle is positive)
2329
+
2330
+ See Also
2331
+ ========
2332
+
2333
+ LinearEntity.angle_between
2334
+
2335
+ Examples
2336
+ ========
2337
+
2338
+ >>> from sympy import Ray, pi
2339
+ >>> r1 = Ray((0, 0), (1, 0))
2340
+ >>> r2 = r1.rotate(-pi/2)
2341
+ >>> angle = r1.closing_angle(r2); angle
2342
+ pi/2
2343
+ >>> r2.rotate(angle).direction.unit == r1.direction.unit
2344
+ True
2345
+ >>> r2.closing_angle(r1)
2346
+ -pi/2
2347
+ """
2348
+ if not all(isinstance(r, Ray2D) for r in (r1, r2)):
2349
+ # although the direction property is defined for
2350
+ # all linear entities, only the Ray is truly a
2351
+ # directed object
2352
+ raise TypeError('Both arguments must be Ray2D objects.')
2353
+
2354
+ a1 = atan2(*list(reversed(r1.direction.args)))
2355
+ a2 = atan2(*list(reversed(r2.direction.args)))
2356
+ if a1*a2 < 0:
2357
+ a1 = 2*S.Pi + a1 if a1 < 0 else a1
2358
+ a2 = 2*S.Pi + a2 if a2 < 0 else a2
2359
+ return a1 - a2
2360
+
2361
+
2362
+ class Segment2D(LinearEntity2D, Segment):
2363
+ """A line segment in 2D space.
2364
+
2365
+ Parameters
2366
+ ==========
2367
+
2368
+ p1 : Point
2369
+ p2 : Point
2370
+
2371
+ Attributes
2372
+ ==========
2373
+
2374
+ length : number or SymPy expression
2375
+ midpoint : Point
2376
+
2377
+ See Also
2378
+ ========
2379
+
2380
+ sympy.geometry.point.Point, Line
2381
+
2382
+ Examples
2383
+ ========
2384
+
2385
+ >>> from sympy import Point, Segment
2386
+ >>> Segment((1, 0), (1, 1)) # tuples are interpreted as pts
2387
+ Segment2D(Point2D(1, 0), Point2D(1, 1))
2388
+ >>> s = Segment(Point(4, 3), Point(1, 1)); s
2389
+ Segment2D(Point2D(4, 3), Point2D(1, 1))
2390
+ >>> s.points
2391
+ (Point2D(4, 3), Point2D(1, 1))
2392
+ >>> s.slope
2393
+ 2/3
2394
+ >>> s.length
2395
+ sqrt(13)
2396
+ >>> s.midpoint
2397
+ Point2D(5/2, 2)
2398
+
2399
+ """
2400
+ def __new__(cls, p1, p2, **kwargs):
2401
+ p1 = Point(p1, dim=2)
2402
+ p2 = Point(p2, dim=2)
2403
+
2404
+ if p1 == p2:
2405
+ return p1
2406
+
2407
+ return LinearEntity2D.__new__(cls, p1, p2, **kwargs)
2408
+
2409
+ def _svg(self, scale_factor=1., fill_color="#66cc99"):
2410
+ """Returns SVG path element for the LinearEntity.
2411
+
2412
+ Parameters
2413
+ ==========
2414
+
2415
+ scale_factor : float
2416
+ Multiplication factor for the SVG stroke-width. Default is 1.
2417
+ fill_color : str, optional
2418
+ Hex string for fill color. Default is "#66cc99".
2419
+ """
2420
+ verts = (N(self.p1), N(self.p2))
2421
+ coords = ["{},{}".format(p.x, p.y) for p in verts]
2422
+ path = "M {} L {}".format(coords[0], " L ".join(coords[1:]))
2423
+ return (
2424
+ '<path fill-rule="evenodd" fill="{2}" stroke="#555555" '
2425
+ 'stroke-width="{0}" opacity="0.6" d="{1}" />'
2426
+ ).format(2.*scale_factor, path, fill_color)
2427
+
2428
+
2429
+ class LinearEntity3D(LinearEntity):
2430
+ """An base class for all linear entities (line, ray and segment)
2431
+ in a 3-dimensional Euclidean space.
2432
+
2433
+ Attributes
2434
+ ==========
2435
+
2436
+ p1
2437
+ p2
2438
+ direction_ratio
2439
+ direction_cosine
2440
+ points
2441
+
2442
+ Notes
2443
+ =====
2444
+
2445
+ This is a base class and is not meant to be instantiated.
2446
+ """
2447
+ def __new__(cls, p1, p2, **kwargs):
2448
+ p1 = Point3D(p1, dim=3)
2449
+ p2 = Point3D(p2, dim=3)
2450
+ if p1 == p2:
2451
+ # if it makes sense to return a Point, handle in subclass
2452
+ raise ValueError(
2453
+ "%s.__new__ requires two unique Points." % cls.__name__)
2454
+
2455
+ return GeometryEntity.__new__(cls, p1, p2, **kwargs)
2456
+
2457
+ ambient_dimension = 3
2458
+
2459
+ @property
2460
+ def direction_ratio(self):
2461
+ """The direction ratio of a given line in 3D.
2462
+
2463
+ See Also
2464
+ ========
2465
+
2466
+ sympy.geometry.line.Line3D.equation
2467
+
2468
+ Examples
2469
+ ========
2470
+
2471
+ >>> from sympy import Point3D, Line3D
2472
+ >>> p1, p2 = Point3D(0, 0, 0), Point3D(5, 3, 1)
2473
+ >>> l = Line3D(p1, p2)
2474
+ >>> l.direction_ratio
2475
+ [5, 3, 1]
2476
+ """
2477
+ p1, p2 = self.points
2478
+ return p1.direction_ratio(p2)
2479
+
2480
+ @property
2481
+ def direction_cosine(self):
2482
+ """The normalized direction ratio of a given line in 3D.
2483
+
2484
+ See Also
2485
+ ========
2486
+
2487
+ sympy.geometry.line.Line3D.equation
2488
+
2489
+ Examples
2490
+ ========
2491
+
2492
+ >>> from sympy import Point3D, Line3D
2493
+ >>> p1, p2 = Point3D(0, 0, 0), Point3D(5, 3, 1)
2494
+ >>> l = Line3D(p1, p2)
2495
+ >>> l.direction_cosine
2496
+ [sqrt(35)/7, 3*sqrt(35)/35, sqrt(35)/35]
2497
+ >>> sum(i**2 for i in _)
2498
+ 1
2499
+ """
2500
+ p1, p2 = self.points
2501
+ return p1.direction_cosine(p2)
2502
+
2503
+
2504
+ class Line3D(LinearEntity3D, Line):
2505
+ """An infinite 3D line in space.
2506
+
2507
+ A line is declared with two distinct points or a point and direction_ratio
2508
+ as defined using keyword `direction_ratio`.
2509
+
2510
+ Parameters
2511
+ ==========
2512
+
2513
+ p1 : Point3D
2514
+ pt : Point3D
2515
+ direction_ratio : list
2516
+
2517
+ See Also
2518
+ ========
2519
+
2520
+ sympy.geometry.point.Point3D
2521
+ sympy.geometry.line.Line
2522
+ sympy.geometry.line.Line2D
2523
+
2524
+ Examples
2525
+ ========
2526
+
2527
+ >>> from sympy import Line3D, Point3D
2528
+ >>> L = Line3D(Point3D(2, 3, 4), Point3D(3, 5, 1))
2529
+ >>> L
2530
+ Line3D(Point3D(2, 3, 4), Point3D(3, 5, 1))
2531
+ >>> L.points
2532
+ (Point3D(2, 3, 4), Point3D(3, 5, 1))
2533
+ """
2534
+ def __new__(cls, p1, pt=None, direction_ratio=(), **kwargs):
2535
+ if isinstance(p1, LinearEntity3D):
2536
+ if pt is not None:
2537
+ raise ValueError('if p1 is a LinearEntity, pt must be None.')
2538
+ p1, pt = p1.args
2539
+ else:
2540
+ p1 = Point(p1, dim=3)
2541
+ if pt is not None and len(direction_ratio) == 0:
2542
+ pt = Point(pt, dim=3)
2543
+ elif len(direction_ratio) == 3 and pt is None:
2544
+ pt = Point3D(p1.x + direction_ratio[0], p1.y + direction_ratio[1],
2545
+ p1.z + direction_ratio[2])
2546
+ else:
2547
+ raise ValueError('A 2nd Point or keyword "direction_ratio" must '
2548
+ 'be used.')
2549
+
2550
+ return LinearEntity3D.__new__(cls, p1, pt, **kwargs)
2551
+
2552
+ def equation(self, x='x', y='y', z='z'):
2553
+ """Return the equations that define the line in 3D.
2554
+
2555
+ Parameters
2556
+ ==========
2557
+
2558
+ x : str, optional
2559
+ The name to use for the x-axis, default value is 'x'.
2560
+ y : str, optional
2561
+ The name to use for the y-axis, default value is 'y'.
2562
+ z : str, optional
2563
+ The name to use for the z-axis, default value is 'z'.
2564
+
2565
+ Returns
2566
+ =======
2567
+
2568
+ equation : Tuple of simultaneous equations
2569
+
2570
+ Examples
2571
+ ========
2572
+
2573
+ >>> from sympy import Point3D, Line3D, solve
2574
+ >>> from sympy.abc import x, y, z
2575
+ >>> p1, p2 = Point3D(1, 0, 0), Point3D(5, 3, 0)
2576
+ >>> l1 = Line3D(p1, p2)
2577
+ >>> eq = l1.equation(x, y, z); eq
2578
+ (-3*x + 4*y + 3, z)
2579
+ >>> solve(eq.subs(z, 0), (x, y, z))
2580
+ {x: 4*y/3 + 1}
2581
+ """
2582
+ x, y, z, k = [_symbol(i, real=True) for i in (x, y, z, 'k')]
2583
+ p1, p2 = self.points
2584
+ d1, d2, d3 = p1.direction_ratio(p2)
2585
+ x1, y1, z1 = p1
2586
+ eqs = [-d1*k + x - x1, -d2*k + y - y1, -d3*k + z - z1]
2587
+ # eliminate k from equations by solving first eq with k for k
2588
+ for i, e in enumerate(eqs):
2589
+ if e.has(k):
2590
+ kk = solve(eqs[i], k)[0]
2591
+ eqs.pop(i)
2592
+ break
2593
+ return Tuple(*[i.subs(k, kk).as_numer_denom()[0] for i in eqs])
2594
+
2595
+ def distance(self, other):
2596
+ """
2597
+ Finds the shortest distance between a line and another object.
2598
+
2599
+ Parameters
2600
+ ==========
2601
+
2602
+ Point3D, Line3D, Plane, tuple, list
2603
+
2604
+ Returns
2605
+ =======
2606
+
2607
+ distance
2608
+
2609
+ Notes
2610
+ =====
2611
+
2612
+ This method accepts only 3D entities as it's parameter
2613
+
2614
+ Tuples and lists are converted to Point3D and therefore must be of
2615
+ length 3, 2 or 1.
2616
+
2617
+ NotImplementedError is raised if `other` is not an instance of one
2618
+ of the specified classes: Point3D, Line3D, or Plane.
2619
+
2620
+ Examples
2621
+ ========
2622
+
2623
+ >>> from sympy.geometry import Line3D
2624
+ >>> l1 = Line3D((0, 0, 0), (0, 0, 1))
2625
+ >>> l2 = Line3D((0, 1, 0), (1, 1, 1))
2626
+ >>> l1.distance(l2)
2627
+ 1
2628
+
2629
+ The computed distance may be symbolic, too:
2630
+
2631
+ >>> from sympy.abc import x, y
2632
+ >>> l1 = Line3D((0, 0, 0), (0, 0, 1))
2633
+ >>> l2 = Line3D((0, x, 0), (y, x, 1))
2634
+ >>> l1.distance(l2)
2635
+ Abs(x*y)/Abs(sqrt(y**2))
2636
+
2637
+ """
2638
+
2639
+ from .plane import Plane # Avoid circular import
2640
+
2641
+ if isinstance(other, (tuple, list)):
2642
+ try:
2643
+ other = Point3D(other)
2644
+ except ValueError:
2645
+ pass
2646
+
2647
+ if isinstance(other, Point3D):
2648
+ return super().distance(other)
2649
+
2650
+ if isinstance(other, Line3D):
2651
+ if self == other:
2652
+ return S.Zero
2653
+ if self.is_parallel(other):
2654
+ return super().distance(other.p1)
2655
+
2656
+ # Skew lines
2657
+ self_direction = Matrix(self.direction_ratio)
2658
+ other_direction = Matrix(other.direction_ratio)
2659
+ normal = self_direction.cross(other_direction)
2660
+ plane_through_self = Plane(p1=self.p1, normal_vector=normal)
2661
+ return other.p1.distance(plane_through_self)
2662
+
2663
+ if isinstance(other, Plane):
2664
+ return other.distance(self)
2665
+
2666
+ msg = f"{other} has type {type(other)}, which is unsupported"
2667
+ raise NotImplementedError(msg)
2668
+
2669
+
2670
+ class Ray3D(LinearEntity3D, Ray):
2671
+ """
2672
+ A Ray is a semi-line in the space with a source point and a direction.
2673
+
2674
+ Parameters
2675
+ ==========
2676
+
2677
+ p1 : Point3D
2678
+ The source of the Ray
2679
+ p2 : Point or a direction vector
2680
+ direction_ratio: Determines the direction in which the Ray propagates.
2681
+
2682
+
2683
+ Attributes
2684
+ ==========
2685
+
2686
+ source
2687
+ xdirection
2688
+ ydirection
2689
+ zdirection
2690
+
2691
+ See Also
2692
+ ========
2693
+
2694
+ sympy.geometry.point.Point3D, Line3D
2695
+
2696
+
2697
+ Examples
2698
+ ========
2699
+
2700
+ >>> from sympy import Point3D, Ray3D
2701
+ >>> r = Ray3D(Point3D(2, 3, 4), Point3D(3, 5, 0))
2702
+ >>> r
2703
+ Ray3D(Point3D(2, 3, 4), Point3D(3, 5, 0))
2704
+ >>> r.points
2705
+ (Point3D(2, 3, 4), Point3D(3, 5, 0))
2706
+ >>> r.source
2707
+ Point3D(2, 3, 4)
2708
+ >>> r.xdirection
2709
+ oo
2710
+ >>> r.ydirection
2711
+ oo
2712
+ >>> r.direction_ratio
2713
+ [1, 2, -4]
2714
+
2715
+ """
2716
+ def __new__(cls, p1, pt=None, direction_ratio=(), **kwargs):
2717
+ if isinstance(p1, LinearEntity3D):
2718
+ if pt is not None:
2719
+ raise ValueError('If p1 is a LinearEntity, pt must be None')
2720
+ p1, pt = p1.args
2721
+ else:
2722
+ p1 = Point(p1, dim=3)
2723
+ if pt is not None and len(direction_ratio) == 0:
2724
+ pt = Point(pt, dim=3)
2725
+ elif len(direction_ratio) == 3 and pt is None:
2726
+ pt = Point3D(p1.x + direction_ratio[0], p1.y + direction_ratio[1],
2727
+ p1.z + direction_ratio[2])
2728
+ else:
2729
+ raise ValueError(filldedent('''
2730
+ A 2nd Point or keyword "direction_ratio" must be used.
2731
+ '''))
2732
+
2733
+ return LinearEntity3D.__new__(cls, p1, pt, **kwargs)
2734
+
2735
+ @property
2736
+ def xdirection(self):
2737
+ """The x direction of the ray.
2738
+
2739
+ Positive infinity if the ray points in the positive x direction,
2740
+ negative infinity if the ray points in the negative x direction,
2741
+ or 0 if the ray is vertical.
2742
+
2743
+ See Also
2744
+ ========
2745
+
2746
+ ydirection
2747
+
2748
+ Examples
2749
+ ========
2750
+
2751
+ >>> from sympy import Point3D, Ray3D
2752
+ >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(0, -1, 0)
2753
+ >>> r1, r2 = Ray3D(p1, p2), Ray3D(p1, p3)
2754
+ >>> r1.xdirection
2755
+ oo
2756
+ >>> r2.xdirection
2757
+ 0
2758
+
2759
+ """
2760
+ if self.p1.x < self.p2.x:
2761
+ return S.Infinity
2762
+ elif self.p1.x == self.p2.x:
2763
+ return S.Zero
2764
+ else:
2765
+ return S.NegativeInfinity
2766
+
2767
+ @property
2768
+ def ydirection(self):
2769
+ """The y direction of the ray.
2770
+
2771
+ Positive infinity if the ray points in the positive y direction,
2772
+ negative infinity if the ray points in the negative y direction,
2773
+ or 0 if the ray is horizontal.
2774
+
2775
+ See Also
2776
+ ========
2777
+
2778
+ xdirection
2779
+
2780
+ Examples
2781
+ ========
2782
+
2783
+ >>> from sympy import Point3D, Ray3D
2784
+ >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(-1, -1, -1), Point3D(-1, 0, 0)
2785
+ >>> r1, r2 = Ray3D(p1, p2), Ray3D(p1, p3)
2786
+ >>> r1.ydirection
2787
+ -oo
2788
+ >>> r2.ydirection
2789
+ 0
2790
+
2791
+ """
2792
+ if self.p1.y < self.p2.y:
2793
+ return S.Infinity
2794
+ elif self.p1.y == self.p2.y:
2795
+ return S.Zero
2796
+ else:
2797
+ return S.NegativeInfinity
2798
+
2799
+ @property
2800
+ def zdirection(self):
2801
+ """The z direction of the ray.
2802
+
2803
+ Positive infinity if the ray points in the positive z direction,
2804
+ negative infinity if the ray points in the negative z direction,
2805
+ or 0 if the ray is horizontal.
2806
+
2807
+ See Also
2808
+ ========
2809
+
2810
+ xdirection
2811
+
2812
+ Examples
2813
+ ========
2814
+
2815
+ >>> from sympy import Point3D, Ray3D
2816
+ >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(-1, -1, -1), Point3D(-1, 0, 0)
2817
+ >>> r1, r2 = Ray3D(p1, p2), Ray3D(p1, p3)
2818
+ >>> r1.ydirection
2819
+ -oo
2820
+ >>> r2.ydirection
2821
+ 0
2822
+ >>> r2.zdirection
2823
+ 0
2824
+
2825
+ """
2826
+ if self.p1.z < self.p2.z:
2827
+ return S.Infinity
2828
+ elif self.p1.z == self.p2.z:
2829
+ return S.Zero
2830
+ else:
2831
+ return S.NegativeInfinity
2832
+
2833
+
2834
+ class Segment3D(LinearEntity3D, Segment):
2835
+ """A line segment in a 3D space.
2836
+
2837
+ Parameters
2838
+ ==========
2839
+
2840
+ p1 : Point3D
2841
+ p2 : Point3D
2842
+
2843
+ Attributes
2844
+ ==========
2845
+
2846
+ length : number or SymPy expression
2847
+ midpoint : Point3D
2848
+
2849
+ See Also
2850
+ ========
2851
+
2852
+ sympy.geometry.point.Point3D, Line3D
2853
+
2854
+ Examples
2855
+ ========
2856
+
2857
+ >>> from sympy import Point3D, Segment3D
2858
+ >>> Segment3D((1, 0, 0), (1, 1, 1)) # tuples are interpreted as pts
2859
+ Segment3D(Point3D(1, 0, 0), Point3D(1, 1, 1))
2860
+ >>> s = Segment3D(Point3D(4, 3, 9), Point3D(1, 1, 7)); s
2861
+ Segment3D(Point3D(4, 3, 9), Point3D(1, 1, 7))
2862
+ >>> s.points
2863
+ (Point3D(4, 3, 9), Point3D(1, 1, 7))
2864
+ >>> s.length
2865
+ sqrt(17)
2866
+ >>> s.midpoint
2867
+ Point3D(5/2, 2, 8)
2868
+
2869
+ """
2870
+ def __new__(cls, p1, p2, **kwargs):
2871
+ p1 = Point(p1, dim=3)
2872
+ p2 = Point(p2, dim=3)
2873
+
2874
+ if p1 == p2:
2875
+ return p1
2876
+
2877
+ return LinearEntity3D.__new__(cls, p1, p2, **kwargs)
janus/lib/python3.10/site-packages/sympy/geometry/plane.py ADDED
@@ -0,0 +1,885 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Geometrical Planes.
2
+
3
+ Contains
4
+ ========
5
+ Plane
6
+
7
+ """
8
+
9
+ from sympy.core import Dummy, Rational, S, Symbol
10
+ from sympy.core.symbol import _symbol
11
+ from sympy.functions.elementary.trigonometric import cos, sin, acos, asin, sqrt
12
+ from .entity import GeometryEntity
13
+ from .line import (Line, Ray, Segment, Line3D, LinearEntity, LinearEntity3D,
14
+ Ray3D, Segment3D)
15
+ from .point import Point, Point3D
16
+ from sympy.matrices import Matrix
17
+ from sympy.polys.polytools import cancel
18
+ from sympy.solvers import solve, linsolve
19
+ from sympy.utilities.iterables import uniq, is_sequence
20
+ from sympy.utilities.misc import filldedent, func_name, Undecidable
21
+
22
+ from mpmath.libmp.libmpf import prec_to_dps
23
+
24
+ import random
25
+
26
+
27
+ x, y, z, t = [Dummy('plane_dummy') for i in range(4)]
28
+
29
+
30
+ class Plane(GeometryEntity):
31
+ """
32
+ A plane is a flat, two-dimensional surface. A plane is the two-dimensional
33
+ analogue of a point (zero-dimensions), a line (one-dimension) and a solid
34
+ (three-dimensions). A plane can generally be constructed by two types of
35
+ inputs. They are:
36
+ - three non-collinear points
37
+ - a point and the plane's normal vector
38
+
39
+ Attributes
40
+ ==========
41
+
42
+ p1
43
+ normal_vector
44
+
45
+ Examples
46
+ ========
47
+
48
+ >>> from sympy import Plane, Point3D
49
+ >>> Plane(Point3D(1, 1, 1), Point3D(2, 3, 4), Point3D(2, 2, 2))
50
+ Plane(Point3D(1, 1, 1), (-1, 2, -1))
51
+ >>> Plane((1, 1, 1), (2, 3, 4), (2, 2, 2))
52
+ Plane(Point3D(1, 1, 1), (-1, 2, -1))
53
+ >>> Plane(Point3D(1, 1, 1), normal_vector=(1,4,7))
54
+ Plane(Point3D(1, 1, 1), (1, 4, 7))
55
+
56
+ """
57
+ def __new__(cls, p1, a=None, b=None, **kwargs):
58
+ p1 = Point3D(p1, dim=3)
59
+ if a and b:
60
+ p2 = Point(a, dim=3)
61
+ p3 = Point(b, dim=3)
62
+ if Point3D.are_collinear(p1, p2, p3):
63
+ raise ValueError('Enter three non-collinear points')
64
+ a = p1.direction_ratio(p2)
65
+ b = p1.direction_ratio(p3)
66
+ normal_vector = tuple(Matrix(a).cross(Matrix(b)))
67
+ else:
68
+ a = kwargs.pop('normal_vector', a)
69
+ evaluate = kwargs.get('evaluate', True)
70
+ if is_sequence(a) and len(a) == 3:
71
+ normal_vector = Point3D(a).args if evaluate else a
72
+ else:
73
+ raise ValueError(filldedent('''
74
+ Either provide 3 3D points or a point with a
75
+ normal vector expressed as a sequence of length 3'''))
76
+ if all(coord.is_zero for coord in normal_vector):
77
+ raise ValueError('Normal vector cannot be zero vector')
78
+ return GeometryEntity.__new__(cls, p1, normal_vector, **kwargs)
79
+
80
+ def __contains__(self, o):
81
+ k = self.equation(x, y, z)
82
+ if isinstance(o, (LinearEntity, LinearEntity3D)):
83
+ d = Point3D(o.arbitrary_point(t))
84
+ e = k.subs([(x, d.x), (y, d.y), (z, d.z)])
85
+ return e.equals(0)
86
+ try:
87
+ o = Point(o, dim=3, strict=True)
88
+ d = k.xreplace(dict(zip((x, y, z), o.args)))
89
+ return d.equals(0)
90
+ except TypeError:
91
+ return False
92
+
93
+ def _eval_evalf(self, prec=15, **options):
94
+ pt, tup = self.args
95
+ dps = prec_to_dps(prec)
96
+ pt = pt.evalf(n=dps, **options)
97
+ tup = tuple([i.evalf(n=dps, **options) for i in tup])
98
+ return self.func(pt, normal_vector=tup, evaluate=False)
99
+
100
+ def angle_between(self, o):
101
+ """Angle between the plane and other geometric entity.
102
+
103
+ Parameters
104
+ ==========
105
+
106
+ LinearEntity3D, Plane.
107
+
108
+ Returns
109
+ =======
110
+
111
+ angle : angle in radians
112
+
113
+ Notes
114
+ =====
115
+
116
+ This method accepts only 3D entities as it's parameter, but if you want
117
+ to calculate the angle between a 2D entity and a plane you should
118
+ first convert to a 3D entity by projecting onto a desired plane and
119
+ then proceed to calculate the angle.
120
+
121
+ Examples
122
+ ========
123
+
124
+ >>> from sympy import Point3D, Line3D, Plane
125
+ >>> a = Plane(Point3D(1, 2, 2), normal_vector=(1, 2, 3))
126
+ >>> b = Line3D(Point3D(1, 3, 4), Point3D(2, 2, 2))
127
+ >>> a.angle_between(b)
128
+ -asin(sqrt(21)/6)
129
+
130
+ """
131
+ if isinstance(o, LinearEntity3D):
132
+ a = Matrix(self.normal_vector)
133
+ b = Matrix(o.direction_ratio)
134
+ c = a.dot(b)
135
+ d = sqrt(sum(i**2 for i in self.normal_vector))
136
+ e = sqrt(sum(i**2 for i in o.direction_ratio))
137
+ return asin(c/(d*e))
138
+ if isinstance(o, Plane):
139
+ a = Matrix(self.normal_vector)
140
+ b = Matrix(o.normal_vector)
141
+ c = a.dot(b)
142
+ d = sqrt(sum(i**2 for i in self.normal_vector))
143
+ e = sqrt(sum(i**2 for i in o.normal_vector))
144
+ return acos(c/(d*e))
145
+
146
+
147
+ def arbitrary_point(self, u=None, v=None):
148
+ """ Returns an arbitrary point on the Plane. If given two
149
+ parameters, the point ranges over the entire plane. If given 1
150
+ or no parameters, returns a point with one parameter which,
151
+ when varying from 0 to 2*pi, moves the point in a circle of
152
+ radius 1 about p1 of the Plane.
153
+
154
+ Examples
155
+ ========
156
+
157
+ >>> from sympy import Plane, Ray
158
+ >>> from sympy.abc import u, v, t, r
159
+ >>> p = Plane((1, 1, 1), normal_vector=(1, 0, 0))
160
+ >>> p.arbitrary_point(u, v)
161
+ Point3D(1, u + 1, v + 1)
162
+ >>> p.arbitrary_point(t)
163
+ Point3D(1, cos(t) + 1, sin(t) + 1)
164
+
165
+ While arbitrary values of u and v can move the point anywhere in
166
+ the plane, the single-parameter point can be used to construct a
167
+ ray whose arbitrary point can be located at angle t and radius
168
+ r from p.p1:
169
+
170
+ >>> Ray(p.p1, _).arbitrary_point(r)
171
+ Point3D(1, r*cos(t) + 1, r*sin(t) + 1)
172
+
173
+ Returns
174
+ =======
175
+
176
+ Point3D
177
+
178
+ """
179
+ circle = v is None
180
+ if circle:
181
+ u = _symbol(u or 't', real=True)
182
+ else:
183
+ u = _symbol(u or 'u', real=True)
184
+ v = _symbol(v or 'v', real=True)
185
+ x, y, z = self.normal_vector
186
+ a, b, c = self.p1.args
187
+ # x1, y1, z1 is a nonzero vector parallel to the plane
188
+ if x.is_zero and y.is_zero:
189
+ x1, y1, z1 = S.One, S.Zero, S.Zero
190
+ else:
191
+ x1, y1, z1 = -y, x, S.Zero
192
+ # x2, y2, z2 is also parallel to the plane, and orthogonal to x1, y1, z1
193
+ x2, y2, z2 = tuple(Matrix((x, y, z)).cross(Matrix((x1, y1, z1))))
194
+ if circle:
195
+ x1, y1, z1 = (w/sqrt(x1**2 + y1**2 + z1**2) for w in (x1, y1, z1))
196
+ x2, y2, z2 = (w/sqrt(x2**2 + y2**2 + z2**2) for w in (x2, y2, z2))
197
+ p = Point3D(a + x1*cos(u) + x2*sin(u), \
198
+ b + y1*cos(u) + y2*sin(u), \
199
+ c + z1*cos(u) + z2*sin(u))
200
+ else:
201
+ p = Point3D(a + x1*u + x2*v, b + y1*u + y2*v, c + z1*u + z2*v)
202
+ return p
203
+
204
+
205
+ @staticmethod
206
+ def are_concurrent(*planes):
207
+ """Is a sequence of Planes concurrent?
208
+
209
+ Two or more Planes are concurrent if their intersections
210
+ are a common line.
211
+
212
+ Parameters
213
+ ==========
214
+
215
+ planes: list
216
+
217
+ Returns
218
+ =======
219
+
220
+ Boolean
221
+
222
+ Examples
223
+ ========
224
+
225
+ >>> from sympy import Plane, Point3D
226
+ >>> a = Plane(Point3D(5, 0, 0), normal_vector=(1, -1, 1))
227
+ >>> b = Plane(Point3D(0, -2, 0), normal_vector=(3, 1, 1))
228
+ >>> c = Plane(Point3D(0, -1, 0), normal_vector=(5, -1, 9))
229
+ >>> Plane.are_concurrent(a, b)
230
+ True
231
+ >>> Plane.are_concurrent(a, b, c)
232
+ False
233
+
234
+ """
235
+ planes = list(uniq(planes))
236
+ for i in planes:
237
+ if not isinstance(i, Plane):
238
+ raise ValueError('All objects should be Planes but got %s' % i.func)
239
+ if len(planes) < 2:
240
+ return False
241
+ planes = list(planes)
242
+ first = planes.pop(0)
243
+ sol = first.intersection(planes[0])
244
+ if sol == []:
245
+ return False
246
+ else:
247
+ line = sol[0]
248
+ for i in planes[1:]:
249
+ l = first.intersection(i)
250
+ if not l or l[0] not in line:
251
+ return False
252
+ return True
253
+
254
+
255
+ def distance(self, o):
256
+ """Distance between the plane and another geometric entity.
257
+
258
+ Parameters
259
+ ==========
260
+
261
+ Point3D, LinearEntity3D, Plane.
262
+
263
+ Returns
264
+ =======
265
+
266
+ distance
267
+
268
+ Notes
269
+ =====
270
+
271
+ This method accepts only 3D entities as it's parameter, but if you want
272
+ to calculate the distance between a 2D entity and a plane you should
273
+ first convert to a 3D entity by projecting onto a desired plane and
274
+ then proceed to calculate the distance.
275
+
276
+ Examples
277
+ ========
278
+
279
+ >>> from sympy import Point3D, Line3D, Plane
280
+ >>> a = Plane(Point3D(1, 1, 1), normal_vector=(1, 1, 1))
281
+ >>> b = Point3D(1, 2, 3)
282
+ >>> a.distance(b)
283
+ sqrt(3)
284
+ >>> c = Line3D(Point3D(2, 3, 1), Point3D(1, 2, 2))
285
+ >>> a.distance(c)
286
+ 0
287
+
288
+ """
289
+ if self.intersection(o) != []:
290
+ return S.Zero
291
+
292
+ if isinstance(o, (Segment3D, Ray3D)):
293
+ a, b = o.p1, o.p2
294
+ pi, = self.intersection(Line3D(a, b))
295
+ if pi in o:
296
+ return self.distance(pi)
297
+ elif a in Segment3D(pi, b):
298
+ return self.distance(a)
299
+ else:
300
+ assert isinstance(o, Segment3D) is True
301
+ return self.distance(b)
302
+
303
+ # following code handles `Point3D`, `LinearEntity3D`, `Plane`
304
+ a = o if isinstance(o, Point3D) else o.p1
305
+ n = Point3D(self.normal_vector).unit
306
+ d = (a - self.p1).dot(n)
307
+ return abs(d)
308
+
309
+
310
+ def equals(self, o):
311
+ """
312
+ Returns True if self and o are the same mathematical entities.
313
+
314
+ Examples
315
+ ========
316
+
317
+ >>> from sympy import Plane, Point3D
318
+ >>> a = Plane(Point3D(1, 2, 3), normal_vector=(1, 1, 1))
319
+ >>> b = Plane(Point3D(1, 2, 3), normal_vector=(2, 2, 2))
320
+ >>> c = Plane(Point3D(1, 2, 3), normal_vector=(-1, 4, 6))
321
+ >>> a.equals(a)
322
+ True
323
+ >>> a.equals(b)
324
+ True
325
+ >>> a.equals(c)
326
+ False
327
+ """
328
+ if isinstance(o, Plane):
329
+ a = self.equation()
330
+ b = o.equation()
331
+ return cancel(a/b).is_constant()
332
+ else:
333
+ return False
334
+
335
+
336
+ def equation(self, x=None, y=None, z=None):
337
+ """The equation of the Plane.
338
+
339
+ Examples
340
+ ========
341
+
342
+ >>> from sympy import Point3D, Plane
343
+ >>> a = Plane(Point3D(1, 1, 2), Point3D(2, 4, 7), Point3D(3, 5, 1))
344
+ >>> a.equation()
345
+ -23*x + 11*y - 2*z + 16
346
+ >>> a = Plane(Point3D(1, 4, 2), normal_vector=(6, 6, 6))
347
+ >>> a.equation()
348
+ 6*x + 6*y + 6*z - 42
349
+
350
+ """
351
+ x, y, z = [i if i else Symbol(j, real=True) for i, j in zip((x, y, z), 'xyz')]
352
+ a = Point3D(x, y, z)
353
+ b = self.p1.direction_ratio(a)
354
+ c = self.normal_vector
355
+ return (sum(i*j for i, j in zip(b, c)))
356
+
357
+
358
+ def intersection(self, o):
359
+ """ The intersection with other geometrical entity.
360
+
361
+ Parameters
362
+ ==========
363
+
364
+ Point, Point3D, LinearEntity, LinearEntity3D, Plane
365
+
366
+ Returns
367
+ =======
368
+
369
+ List
370
+
371
+ Examples
372
+ ========
373
+
374
+ >>> from sympy import Point3D, Line3D, Plane
375
+ >>> a = Plane(Point3D(1, 2, 3), normal_vector=(1, 1, 1))
376
+ >>> b = Point3D(1, 2, 3)
377
+ >>> a.intersection(b)
378
+ [Point3D(1, 2, 3)]
379
+ >>> c = Line3D(Point3D(1, 4, 7), Point3D(2, 2, 2))
380
+ >>> a.intersection(c)
381
+ [Point3D(2, 2, 2)]
382
+ >>> d = Plane(Point3D(6, 0, 0), normal_vector=(2, -5, 3))
383
+ >>> e = Plane(Point3D(2, 0, 0), normal_vector=(3, 4, -3))
384
+ >>> d.intersection(e)
385
+ [Line3D(Point3D(78/23, -24/23, 0), Point3D(147/23, 321/23, 23))]
386
+
387
+ """
388
+ if not isinstance(o, GeometryEntity):
389
+ o = Point(o, dim=3)
390
+ if isinstance(o, Point):
391
+ if o in self:
392
+ return [o]
393
+ else:
394
+ return []
395
+ if isinstance(o, (LinearEntity, LinearEntity3D)):
396
+ # recast to 3D
397
+ p1, p2 = o.p1, o.p2
398
+ if isinstance(o, Segment):
399
+ o = Segment3D(p1, p2)
400
+ elif isinstance(o, Ray):
401
+ o = Ray3D(p1, p2)
402
+ elif isinstance(o, Line):
403
+ o = Line3D(p1, p2)
404
+ else:
405
+ raise ValueError('unhandled linear entity: %s' % o.func)
406
+ if o in self:
407
+ return [o]
408
+ else:
409
+ a = Point3D(o.arbitrary_point(t))
410
+ p1, n = self.p1, Point3D(self.normal_vector)
411
+
412
+ # TODO: Replace solve with solveset, when this line is tested
413
+ c = solve((a - p1).dot(n), t)
414
+ if not c:
415
+ return []
416
+ else:
417
+ c = [i for i in c if i.is_real is not False]
418
+ if len(c) > 1:
419
+ c = [i for i in c if i.is_real]
420
+ if len(c) != 1:
421
+ raise Undecidable("not sure which point is real")
422
+ p = a.subs(t, c[0])
423
+ if p not in o:
424
+ return [] # e.g. a segment might not intersect a plane
425
+ return [p]
426
+ if isinstance(o, Plane):
427
+ if self.equals(o):
428
+ return [self]
429
+ if self.is_parallel(o):
430
+ return []
431
+ else:
432
+ x, y, z = map(Dummy, 'xyz')
433
+ a, b = Matrix([self.normal_vector]), Matrix([o.normal_vector])
434
+ c = list(a.cross(b))
435
+ d = self.equation(x, y, z)
436
+ e = o.equation(x, y, z)
437
+ result = list(linsolve([d, e], x, y, z))[0]
438
+ for i in (x, y, z): result = result.subs(i, 0)
439
+ return [Line3D(Point3D(result), direction_ratio=c)]
440
+
441
+
442
+ def is_coplanar(self, o):
443
+ """ Returns True if `o` is coplanar with self, else False.
444
+
445
+ Examples
446
+ ========
447
+
448
+ >>> from sympy import Plane
449
+ >>> o = (0, 0, 0)
450
+ >>> p = Plane(o, (1, 1, 1))
451
+ >>> p2 = Plane(o, (2, 2, 2))
452
+ >>> p == p2
453
+ False
454
+ >>> p.is_coplanar(p2)
455
+ True
456
+ """
457
+ if isinstance(o, Plane):
458
+ return not cancel(self.equation(x, y, z)/o.equation(x, y, z)).has(x, y, z)
459
+ if isinstance(o, Point3D):
460
+ return o in self
461
+ elif isinstance(o, LinearEntity3D):
462
+ return all(i in self for i in self)
463
+ elif isinstance(o, GeometryEntity): # XXX should only be handling 2D objects now
464
+ return all(i == 0 for i in self.normal_vector[:2])
465
+
466
+
467
+ def is_parallel(self, l):
468
+ """Is the given geometric entity parallel to the plane?
469
+
470
+ Parameters
471
+ ==========
472
+
473
+ LinearEntity3D or Plane
474
+
475
+ Returns
476
+ =======
477
+
478
+ Boolean
479
+
480
+ Examples
481
+ ========
482
+
483
+ >>> from sympy import Plane, Point3D
484
+ >>> a = Plane(Point3D(1,4,6), normal_vector=(2, 4, 6))
485
+ >>> b = Plane(Point3D(3,1,3), normal_vector=(4, 8, 12))
486
+ >>> a.is_parallel(b)
487
+ True
488
+
489
+ """
490
+ if isinstance(l, LinearEntity3D):
491
+ a = l.direction_ratio
492
+ b = self.normal_vector
493
+ c = sum(i*j for i, j in zip(a, b))
494
+ if c == 0:
495
+ return True
496
+ else:
497
+ return False
498
+ elif isinstance(l, Plane):
499
+ a = Matrix(l.normal_vector)
500
+ b = Matrix(self.normal_vector)
501
+ if a.cross(b).is_zero_matrix:
502
+ return True
503
+ else:
504
+ return False
505
+
506
+
507
+ def is_perpendicular(self, l):
508
+ """Is the given geometric entity perpendicualar to the given plane?
509
+
510
+ Parameters
511
+ ==========
512
+
513
+ LinearEntity3D or Plane
514
+
515
+ Returns
516
+ =======
517
+
518
+ Boolean
519
+
520
+ Examples
521
+ ========
522
+
523
+ >>> from sympy import Plane, Point3D
524
+ >>> a = Plane(Point3D(1,4,6), normal_vector=(2, 4, 6))
525
+ >>> b = Plane(Point3D(2, 2, 2), normal_vector=(-1, 2, -1))
526
+ >>> a.is_perpendicular(b)
527
+ True
528
+
529
+ """
530
+ if isinstance(l, LinearEntity3D):
531
+ a = Matrix(l.direction_ratio)
532
+ b = Matrix(self.normal_vector)
533
+ if a.cross(b).is_zero_matrix:
534
+ return True
535
+ else:
536
+ return False
537
+ elif isinstance(l, Plane):
538
+ a = Matrix(l.normal_vector)
539
+ b = Matrix(self.normal_vector)
540
+ if a.dot(b) == 0:
541
+ return True
542
+ else:
543
+ return False
544
+ else:
545
+ return False
546
+
547
+ @property
548
+ def normal_vector(self):
549
+ """Normal vector of the given plane.
550
+
551
+ Examples
552
+ ========
553
+
554
+ >>> from sympy import Point3D, Plane
555
+ >>> a = Plane(Point3D(1, 1, 1), Point3D(2, 3, 4), Point3D(2, 2, 2))
556
+ >>> a.normal_vector
557
+ (-1, 2, -1)
558
+ >>> a = Plane(Point3D(1, 1, 1), normal_vector=(1, 4, 7))
559
+ >>> a.normal_vector
560
+ (1, 4, 7)
561
+
562
+ """
563
+ return self.args[1]
564
+
565
+ @property
566
+ def p1(self):
567
+ """The only defining point of the plane. Others can be obtained from the
568
+ arbitrary_point method.
569
+
570
+ See Also
571
+ ========
572
+
573
+ sympy.geometry.point.Point3D
574
+
575
+ Examples
576
+ ========
577
+
578
+ >>> from sympy import Point3D, Plane
579
+ >>> a = Plane(Point3D(1, 1, 1), Point3D(2, 3, 4), Point3D(2, 2, 2))
580
+ >>> a.p1
581
+ Point3D(1, 1, 1)
582
+
583
+ """
584
+ return self.args[0]
585
+
586
+ def parallel_plane(self, pt):
587
+ """
588
+ Plane parallel to the given plane and passing through the point pt.
589
+
590
+ Parameters
591
+ ==========
592
+
593
+ pt: Point3D
594
+
595
+ Returns
596
+ =======
597
+
598
+ Plane
599
+
600
+ Examples
601
+ ========
602
+
603
+ >>> from sympy import Plane, Point3D
604
+ >>> a = Plane(Point3D(1, 4, 6), normal_vector=(2, 4, 6))
605
+ >>> a.parallel_plane(Point3D(2, 3, 5))
606
+ Plane(Point3D(2, 3, 5), (2, 4, 6))
607
+
608
+ """
609
+ a = self.normal_vector
610
+ return Plane(pt, normal_vector=a)
611
+
612
+ def perpendicular_line(self, pt):
613
+ """A line perpendicular to the given plane.
614
+
615
+ Parameters
616
+ ==========
617
+
618
+ pt: Point3D
619
+
620
+ Returns
621
+ =======
622
+
623
+ Line3D
624
+
625
+ Examples
626
+ ========
627
+
628
+ >>> from sympy import Plane, Point3D
629
+ >>> a = Plane(Point3D(1,4,6), normal_vector=(2, 4, 6))
630
+ >>> a.perpendicular_line(Point3D(9, 8, 7))
631
+ Line3D(Point3D(9, 8, 7), Point3D(11, 12, 13))
632
+
633
+ """
634
+ a = self.normal_vector
635
+ return Line3D(pt, direction_ratio=a)
636
+
637
+ def perpendicular_plane(self, *pts):
638
+ """
639
+ Return a perpendicular passing through the given points. If the
640
+ direction ratio between the points is the same as the Plane's normal
641
+ vector then, to select from the infinite number of possible planes,
642
+ a third point will be chosen on the z-axis (or the y-axis
643
+ if the normal vector is already parallel to the z-axis). If less than
644
+ two points are given they will be supplied as follows: if no point is
645
+ given then pt1 will be self.p1; if a second point is not given it will
646
+ be a point through pt1 on a line parallel to the z-axis (if the normal
647
+ is not already the z-axis, otherwise on the line parallel to the
648
+ y-axis).
649
+
650
+ Parameters
651
+ ==========
652
+
653
+ pts: 0, 1 or 2 Point3D
654
+
655
+ Returns
656
+ =======
657
+
658
+ Plane
659
+
660
+ Examples
661
+ ========
662
+
663
+ >>> from sympy import Plane, Point3D
664
+ >>> a, b = Point3D(0, 0, 0), Point3D(0, 1, 0)
665
+ >>> Z = (0, 0, 1)
666
+ >>> p = Plane(a, normal_vector=Z)
667
+ >>> p.perpendicular_plane(a, b)
668
+ Plane(Point3D(0, 0, 0), (1, 0, 0))
669
+ """
670
+ if len(pts) > 2:
671
+ raise ValueError('No more than 2 pts should be provided.')
672
+
673
+ pts = list(pts)
674
+ if len(pts) == 0:
675
+ pts.append(self.p1)
676
+ if len(pts) == 1:
677
+ x, y, z = self.normal_vector
678
+ if x == y == 0:
679
+ dir = (0, 1, 0)
680
+ else:
681
+ dir = (0, 0, 1)
682
+ pts.append(pts[0] + Point3D(*dir))
683
+
684
+ p1, p2 = [Point(i, dim=3) for i in pts]
685
+ l = Line3D(p1, p2)
686
+ n = Line3D(p1, direction_ratio=self.normal_vector)
687
+ if l in n: # XXX should an error be raised instead?
688
+ # there are infinitely many perpendicular planes;
689
+ x, y, z = self.normal_vector
690
+ if x == y == 0:
691
+ # the z axis is the normal so pick a pt on the y-axis
692
+ p3 = Point3D(0, 1, 0) # case 1
693
+ else:
694
+ # else pick a pt on the z axis
695
+ p3 = Point3D(0, 0, 1) # case 2
696
+ # in case that point is already given, move it a bit
697
+ if p3 in l:
698
+ p3 *= 2 # case 3
699
+ else:
700
+ p3 = p1 + Point3D(*self.normal_vector) # case 4
701
+ return Plane(p1, p2, p3)
702
+
703
+ def projection_line(self, line):
704
+ """Project the given line onto the plane through the normal plane
705
+ containing the line.
706
+
707
+ Parameters
708
+ ==========
709
+
710
+ LinearEntity or LinearEntity3D
711
+
712
+ Returns
713
+ =======
714
+
715
+ Point3D, Line3D, Ray3D or Segment3D
716
+
717
+ Notes
718
+ =====
719
+
720
+ For the interaction between 2D and 3D lines(segments, rays), you should
721
+ convert the line to 3D by using this method. For example for finding the
722
+ intersection between a 2D and a 3D line, convert the 2D line to a 3D line
723
+ by projecting it on a required plane and then proceed to find the
724
+ intersection between those lines.
725
+
726
+ Examples
727
+ ========
728
+
729
+ >>> from sympy import Plane, Line, Line3D, Point3D
730
+ >>> a = Plane(Point3D(1, 1, 1), normal_vector=(1, 1, 1))
731
+ >>> b = Line(Point3D(1, 1), Point3D(2, 2))
732
+ >>> a.projection_line(b)
733
+ Line3D(Point3D(4/3, 4/3, 1/3), Point3D(5/3, 5/3, -1/3))
734
+ >>> c = Line3D(Point3D(1, 1, 1), Point3D(2, 2, 2))
735
+ >>> a.projection_line(c)
736
+ Point3D(1, 1, 1)
737
+
738
+ """
739
+ if not isinstance(line, (LinearEntity, LinearEntity3D)):
740
+ raise NotImplementedError('Enter a linear entity only')
741
+ a, b = self.projection(line.p1), self.projection(line.p2)
742
+ if a == b:
743
+ # projection does not imply intersection so for
744
+ # this case (line parallel to plane's normal) we
745
+ # return the projection point
746
+ return a
747
+ if isinstance(line, (Line, Line3D)):
748
+ return Line3D(a, b)
749
+ if isinstance(line, (Ray, Ray3D)):
750
+ return Ray3D(a, b)
751
+ if isinstance(line, (Segment, Segment3D)):
752
+ return Segment3D(a, b)
753
+
754
+ def projection(self, pt):
755
+ """Project the given point onto the plane along the plane normal.
756
+
757
+ Parameters
758
+ ==========
759
+
760
+ Point or Point3D
761
+
762
+ Returns
763
+ =======
764
+
765
+ Point3D
766
+
767
+ Examples
768
+ ========
769
+
770
+ >>> from sympy import Plane, Point3D
771
+ >>> A = Plane(Point3D(1, 1, 2), normal_vector=(1, 1, 1))
772
+
773
+ The projection is along the normal vector direction, not the z
774
+ axis, so (1, 1) does not project to (1, 1, 2) on the plane A:
775
+
776
+ >>> b = Point3D(1, 1)
777
+ >>> A.projection(b)
778
+ Point3D(5/3, 5/3, 2/3)
779
+ >>> _ in A
780
+ True
781
+
782
+ But the point (1, 1, 2) projects to (1, 1) on the XY-plane:
783
+
784
+ >>> XY = Plane((0, 0, 0), (0, 0, 1))
785
+ >>> XY.projection((1, 1, 2))
786
+ Point3D(1, 1, 0)
787
+ """
788
+ rv = Point(pt, dim=3)
789
+ if rv in self:
790
+ return rv
791
+ return self.intersection(Line3D(rv, rv + Point3D(self.normal_vector)))[0]
792
+
793
+ def random_point(self, seed=None):
794
+ """ Returns a random point on the Plane.
795
+
796
+ Returns
797
+ =======
798
+
799
+ Point3D
800
+
801
+ Examples
802
+ ========
803
+
804
+ >>> from sympy import Plane
805
+ >>> p = Plane((1, 0, 0), normal_vector=(0, 1, 0))
806
+ >>> r = p.random_point(seed=42) # seed value is optional
807
+ >>> r.n(3)
808
+ Point3D(2.29, 0, -1.35)
809
+
810
+ The random point can be moved to lie on the circle of radius
811
+ 1 centered on p1:
812
+
813
+ >>> c = p.p1 + (r - p.p1).unit
814
+ >>> c.distance(p.p1).equals(1)
815
+ True
816
+ """
817
+ if seed is not None:
818
+ rng = random.Random(seed)
819
+ else:
820
+ rng = random
821
+ params = {
822
+ x: 2*Rational(rng.gauss(0, 1)) - 1,
823
+ y: 2*Rational(rng.gauss(0, 1)) - 1}
824
+ return self.arbitrary_point(x, y).subs(params)
825
+
826
+ def parameter_value(self, other, u, v=None):
827
+ """Return the parameter(s) corresponding to the given point.
828
+
829
+ Examples
830
+ ========
831
+
832
+ >>> from sympy import pi, Plane
833
+ >>> from sympy.abc import t, u, v
834
+ >>> p = Plane((2, 0, 0), (0, 0, 1), (0, 1, 0))
835
+
836
+ By default, the parameter value returned defines a point
837
+ that is a distance of 1 from the Plane's p1 value and
838
+ in line with the given point:
839
+
840
+ >>> on_circle = p.arbitrary_point(t).subs(t, pi/4)
841
+ >>> on_circle.distance(p.p1)
842
+ 1
843
+ >>> p.parameter_value(on_circle, t)
844
+ {t: pi/4}
845
+
846
+ Moving the point twice as far from p1 does not change
847
+ the parameter value:
848
+
849
+ >>> off_circle = p.p1 + (on_circle - p.p1)*2
850
+ >>> off_circle.distance(p.p1)
851
+ 2
852
+ >>> p.parameter_value(off_circle, t)
853
+ {t: pi/4}
854
+
855
+ If the 2-value parameter is desired, supply the two
856
+ parameter symbols and a replacement dictionary will
857
+ be returned:
858
+
859
+ >>> p.parameter_value(on_circle, u, v)
860
+ {u: sqrt(10)/10, v: sqrt(10)/30}
861
+ >>> p.parameter_value(off_circle, u, v)
862
+ {u: sqrt(10)/5, v: sqrt(10)/15}
863
+ """
864
+ if not isinstance(other, GeometryEntity):
865
+ other = Point(other, dim=self.ambient_dimension)
866
+ if not isinstance(other, Point):
867
+ raise ValueError("other must be a point")
868
+ if other == self.p1:
869
+ return other
870
+ if isinstance(u, Symbol) and v is None:
871
+ delta = self.arbitrary_point(u) - self.p1
872
+ eq = delta - (other - self.p1).unit
873
+ sol = solve(eq, u, dict=True)
874
+ elif isinstance(u, Symbol) and isinstance(v, Symbol):
875
+ pt = self.arbitrary_point(u, v)
876
+ sol = solve(pt - other, (u, v), dict=True)
877
+ else:
878
+ raise ValueError('expecting 1 or 2 symbols')
879
+ if not sol:
880
+ raise ValueError("Given point is not on %s" % func_name(self))
881
+ return sol[0] # {t: tval} or {u: uval, v: vval}
882
+
883
+ @property
884
+ def ambient_dimension(self):
885
+ return self.p1.ambient_dimension
janus/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]
janus/lib/python3.10/site-packages/sympy/geometry/polygon.py ADDED
@@ -0,0 +1,2891 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import Expr, S, oo, pi, sympify
2
+ from sympy.core.evalf import N
3
+ from sympy.core.sorting import default_sort_key, ordered
4
+ from sympy.core.symbol import _symbol, Dummy, Symbol
5
+ from sympy.functions.elementary.complexes import sign
6
+ from sympy.functions.elementary.piecewise import Piecewise
7
+ from sympy.functions.elementary.trigonometric import cos, sin, tan
8
+ from .ellipse import Circle
9
+ from .entity import GeometryEntity, GeometrySet
10
+ from .exceptions import GeometryError
11
+ from .line import Line, Segment, Ray
12
+ from .point import Point
13
+ from sympy.logic import And
14
+ from sympy.matrices import Matrix
15
+ from sympy.simplify.simplify import simplify
16
+ from sympy.solvers.solvers import solve
17
+ from sympy.utilities.iterables import has_dups, has_variety, uniq, rotate_left, least_rotation
18
+ from sympy.utilities.misc import as_int, func_name
19
+
20
+ from mpmath.libmp.libmpf import prec_to_dps
21
+
22
+ import warnings
23
+
24
+
25
+ x, y, T = [Dummy('polygon_dummy', real=True) for i in range(3)]
26
+
27
+
28
+ class Polygon(GeometrySet):
29
+ """A two-dimensional polygon.
30
+
31
+ A simple polygon in space. Can be constructed from a sequence of points
32
+ or from a center, radius, number of sides and rotation angle.
33
+
34
+ Parameters
35
+ ==========
36
+
37
+ vertices
38
+ A sequence of points.
39
+
40
+ n : int, optional
41
+ If $> 0$, an n-sided RegularPolygon is created.
42
+ Default value is $0$.
43
+
44
+ Attributes
45
+ ==========
46
+
47
+ area
48
+ angles
49
+ perimeter
50
+ vertices
51
+ centroid
52
+ sides
53
+
54
+ Raises
55
+ ======
56
+
57
+ GeometryError
58
+ If all parameters are not Points.
59
+
60
+ See Also
61
+ ========
62
+
63
+ sympy.geometry.point.Point, sympy.geometry.line.Segment, Triangle
64
+
65
+ Notes
66
+ =====
67
+
68
+ Polygons are treated as closed paths rather than 2D areas so
69
+ some calculations can be be negative or positive (e.g., area)
70
+ based on the orientation of the points.
71
+
72
+ Any consecutive identical points are reduced to a single point
73
+ and any points collinear and between two points will be removed
74
+ unless they are needed to define an explicit intersection (see examples).
75
+
76
+ A Triangle, Segment or Point will be returned when there are 3 or
77
+ fewer points provided.
78
+
79
+ Examples
80
+ ========
81
+
82
+ >>> from sympy import Polygon, pi
83
+ >>> p1, p2, p3, p4, p5 = [(0, 0), (1, 0), (5, 1), (0, 1), (3, 0)]
84
+ >>> Polygon(p1, p2, p3, p4)
85
+ Polygon(Point2D(0, 0), Point2D(1, 0), Point2D(5, 1), Point2D(0, 1))
86
+ >>> Polygon(p1, p2)
87
+ Segment2D(Point2D(0, 0), Point2D(1, 0))
88
+ >>> Polygon(p1, p2, p5)
89
+ Segment2D(Point2D(0, 0), Point2D(3, 0))
90
+
91
+ The area of a polygon is calculated as positive when vertices are
92
+ traversed in a ccw direction. When the sides of a polygon cross the
93
+ area will have positive and negative contributions. The following
94
+ defines a Z shape where the bottom right connects back to the top
95
+ left.
96
+
97
+ >>> Polygon((0, 2), (2, 2), (0, 0), (2, 0)).area
98
+ 0
99
+
100
+ When the keyword `n` is used to define the number of sides of the
101
+ Polygon then a RegularPolygon is created and the other arguments are
102
+ interpreted as center, radius and rotation. The unrotated RegularPolygon
103
+ will always have a vertex at Point(r, 0) where `r` is the radius of the
104
+ circle that circumscribes the RegularPolygon. Its method `spin` can be
105
+ used to increment that angle.
106
+
107
+ >>> p = Polygon((0,0), 1, n=3)
108
+ >>> p
109
+ RegularPolygon(Point2D(0, 0), 1, 3, 0)
110
+ >>> p.vertices[0]
111
+ Point2D(1, 0)
112
+ >>> p.args[0]
113
+ Point2D(0, 0)
114
+ >>> p.spin(pi/2)
115
+ >>> p.vertices[0]
116
+ Point2D(0, 1)
117
+
118
+ """
119
+
120
+ __slots__ = ()
121
+
122
+ def __new__(cls, *args, n = 0, **kwargs):
123
+ if n:
124
+ args = list(args)
125
+ # return a virtual polygon with n sides
126
+ if len(args) == 2: # center, radius
127
+ args.append(n)
128
+ elif len(args) == 3: # center, radius, rotation
129
+ args.insert(2, n)
130
+ return RegularPolygon(*args, **kwargs)
131
+
132
+ vertices = [Point(a, dim=2, **kwargs) for a in args]
133
+
134
+ # remove consecutive duplicates
135
+ nodup = []
136
+ for p in vertices:
137
+ if nodup and p == nodup[-1]:
138
+ continue
139
+ nodup.append(p)
140
+ if len(nodup) > 1 and nodup[-1] == nodup[0]:
141
+ nodup.pop() # last point was same as first
142
+
143
+ # remove collinear points
144
+ i = -3
145
+ while i < len(nodup) - 3 and len(nodup) > 2:
146
+ a, b, c = nodup[i], nodup[i + 1], nodup[i + 2]
147
+ if Point.is_collinear(a, b, c):
148
+ nodup.pop(i + 1)
149
+ if a == c:
150
+ nodup.pop(i)
151
+ else:
152
+ i += 1
153
+
154
+ vertices = list(nodup)
155
+
156
+ if len(vertices) > 3:
157
+ return GeometryEntity.__new__(cls, *vertices, **kwargs)
158
+ elif len(vertices) == 3:
159
+ return Triangle(*vertices, **kwargs)
160
+ elif len(vertices) == 2:
161
+ return Segment(*vertices, **kwargs)
162
+ else:
163
+ return Point(*vertices, **kwargs)
164
+
165
+ @property
166
+ def area(self):
167
+ """
168
+ The area of the polygon.
169
+
170
+ Notes
171
+ =====
172
+
173
+ The area calculation can be positive or negative based on the
174
+ orientation of the points. If any side of the polygon crosses
175
+ any other side, there will be areas having opposite signs.
176
+
177
+ See Also
178
+ ========
179
+
180
+ sympy.geometry.ellipse.Ellipse.area
181
+
182
+ Examples
183
+ ========
184
+
185
+ >>> from sympy import Point, Polygon
186
+ >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)])
187
+ >>> poly = Polygon(p1, p2, p3, p4)
188
+ >>> poly.area
189
+ 3
190
+
191
+ In the Z shaped polygon (with the lower right connecting back
192
+ to the upper left) the areas cancel out:
193
+
194
+ >>> Z = Polygon((0, 1), (1, 1), (0, 0), (1, 0))
195
+ >>> Z.area
196
+ 0
197
+
198
+ In the M shaped polygon, areas do not cancel because no side
199
+ crosses any other (though there is a point of contact).
200
+
201
+ >>> M = Polygon((0, 0), (0, 1), (2, 0), (3, 1), (3, 0))
202
+ >>> M.area
203
+ -3/2
204
+
205
+ """
206
+ area = 0
207
+ args = self.args
208
+ for i in range(len(args)):
209
+ x1, y1 = args[i - 1].args
210
+ x2, y2 = args[i].args
211
+ area += x1*y2 - x2*y1
212
+ return simplify(area) / 2
213
+
214
+ @staticmethod
215
+ def _is_clockwise(a, b, c):
216
+ """Return True/False for cw/ccw orientation.
217
+
218
+ Examples
219
+ ========
220
+
221
+ >>> from sympy import Point, Polygon
222
+ >>> a, b, c = [Point(i) for i in [(0, 0), (1, 1), (1, 0)]]
223
+ >>> Polygon._is_clockwise(a, b, c)
224
+ True
225
+ >>> Polygon._is_clockwise(a, c, b)
226
+ False
227
+ """
228
+ ba = b - a
229
+ ca = c - a
230
+ t_area = simplify(ba.x*ca.y - ca.x*ba.y)
231
+ res = t_area.is_nonpositive
232
+ if res is None:
233
+ raise ValueError("Can't determine orientation")
234
+ return res
235
+
236
+ @property
237
+ def angles(self):
238
+ """The internal angle at each vertex.
239
+
240
+ Returns
241
+ =======
242
+
243
+ angles : dict
244
+ A dictionary where each key is a vertex and each value is the
245
+ internal angle at that vertex. The vertices are represented as
246
+ Points.
247
+
248
+ See Also
249
+ ========
250
+
251
+ sympy.geometry.point.Point, sympy.geometry.line.LinearEntity.angle_between
252
+
253
+ Examples
254
+ ========
255
+
256
+ >>> from sympy import Point, Polygon
257
+ >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)])
258
+ >>> poly = Polygon(p1, p2, p3, p4)
259
+ >>> poly.angles[p1]
260
+ pi/2
261
+ >>> poly.angles[p2]
262
+ acos(-4*sqrt(17)/17)
263
+
264
+ """
265
+
266
+ args = self.vertices
267
+ n = len(args)
268
+ ret = {}
269
+ for i in range(n):
270
+ a, b, c = args[i - 2], args[i - 1], args[i]
271
+ reflex_ang = Ray(b, a).angle_between(Ray(b, c))
272
+ if self._is_clockwise(a, b, c):
273
+ ret[b] = 2*S.Pi - reflex_ang
274
+ else:
275
+ ret[b] = reflex_ang
276
+
277
+ # internal sum should be pi*(n - 2), not pi*(n+2)
278
+ # so if ratio is (n+2)/(n-2) > 1 it is wrong
279
+ wrong = ((sum(ret.values())/S.Pi-1)/(n - 2) - 1).is_positive
280
+ if wrong:
281
+ two_pi = 2*S.Pi
282
+ for b in ret:
283
+ ret[b] = two_pi - ret[b]
284
+ elif wrong is None:
285
+ raise ValueError("could not determine Polygon orientation.")
286
+ return ret
287
+
288
+ @property
289
+ def ambient_dimension(self):
290
+ return self.vertices[0].ambient_dimension
291
+
292
+ @property
293
+ def perimeter(self):
294
+ """The perimeter of the polygon.
295
+
296
+ Returns
297
+ =======
298
+
299
+ perimeter : number or Basic instance
300
+
301
+ See Also
302
+ ========
303
+
304
+ sympy.geometry.line.Segment.length
305
+
306
+ Examples
307
+ ========
308
+
309
+ >>> from sympy import Point, Polygon
310
+ >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)])
311
+ >>> poly = Polygon(p1, p2, p3, p4)
312
+ >>> poly.perimeter
313
+ sqrt(17) + 7
314
+ """
315
+ p = 0
316
+ args = self.vertices
317
+ for i in range(len(args)):
318
+ p += args[i - 1].distance(args[i])
319
+ return simplify(p)
320
+
321
+ @property
322
+ def vertices(self):
323
+ """The vertices of the polygon.
324
+
325
+ Returns
326
+ =======
327
+
328
+ vertices : list of Points
329
+
330
+ Notes
331
+ =====
332
+
333
+ When iterating over the vertices, it is more efficient to index self
334
+ rather than to request the vertices and index them. Only use the
335
+ vertices when you want to process all of them at once. This is even
336
+ more important with RegularPolygons that calculate each vertex.
337
+
338
+ See Also
339
+ ========
340
+
341
+ sympy.geometry.point.Point
342
+
343
+ Examples
344
+ ========
345
+
346
+ >>> from sympy import Point, Polygon
347
+ >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)])
348
+ >>> poly = Polygon(p1, p2, p3, p4)
349
+ >>> poly.vertices
350
+ [Point2D(0, 0), Point2D(1, 0), Point2D(5, 1), Point2D(0, 1)]
351
+ >>> poly.vertices[0]
352
+ Point2D(0, 0)
353
+
354
+ """
355
+ return list(self.args)
356
+
357
+ @property
358
+ def centroid(self):
359
+ """The centroid of the polygon.
360
+
361
+ Returns
362
+ =======
363
+
364
+ centroid : Point
365
+
366
+ See Also
367
+ ========
368
+
369
+ sympy.geometry.point.Point, sympy.geometry.util.centroid
370
+
371
+ Examples
372
+ ========
373
+
374
+ >>> from sympy import Point, Polygon
375
+ >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)])
376
+ >>> poly = Polygon(p1, p2, p3, p4)
377
+ >>> poly.centroid
378
+ Point2D(31/18, 11/18)
379
+
380
+ """
381
+ A = 1/(6*self.area)
382
+ cx, cy = 0, 0
383
+ args = self.args
384
+ for i in range(len(args)):
385
+ x1, y1 = args[i - 1].args
386
+ x2, y2 = args[i].args
387
+ v = x1*y2 - x2*y1
388
+ cx += v*(x1 + x2)
389
+ cy += v*(y1 + y2)
390
+ return Point(simplify(A*cx), simplify(A*cy))
391
+
392
+
393
+ def second_moment_of_area(self, point=None):
394
+ """Returns the second moment and product moment of area of a two dimensional polygon.
395
+
396
+ Parameters
397
+ ==========
398
+
399
+ point : Point, two-tuple of sympifyable objects, or None(default=None)
400
+ point is the point about which second moment of area is to be found.
401
+ If "point=None" it will be calculated about the axis passing through the
402
+ centroid of the polygon.
403
+
404
+ Returns
405
+ =======
406
+
407
+ I_xx, I_yy, I_xy : number or SymPy expression
408
+ I_xx, I_yy are second moment of area of a two dimensional polygon.
409
+ I_xy is product moment of area of a two dimensional polygon.
410
+
411
+ Examples
412
+ ========
413
+
414
+ >>> from sympy import Polygon, symbols
415
+ >>> a, b = symbols('a, b')
416
+ >>> p1, p2, p3, p4, p5 = [(0, 0), (a, 0), (a, b), (0, b), (a/3, b/3)]
417
+ >>> rectangle = Polygon(p1, p2, p3, p4)
418
+ >>> rectangle.second_moment_of_area()
419
+ (a*b**3/12, a**3*b/12, 0)
420
+ >>> rectangle.second_moment_of_area(p5)
421
+ (a*b**3/9, a**3*b/9, a**2*b**2/36)
422
+
423
+ References
424
+ ==========
425
+
426
+ .. [1] https://en.wikipedia.org/wiki/Second_moment_of_area
427
+
428
+ """
429
+
430
+ I_xx, I_yy, I_xy = 0, 0, 0
431
+ args = self.vertices
432
+ for i in range(len(args)):
433
+ x1, y1 = args[i-1].args
434
+ x2, y2 = args[i].args
435
+ v = x1*y2 - x2*y1
436
+ I_xx += (y1**2 + y1*y2 + y2**2)*v
437
+ I_yy += (x1**2 + x1*x2 + x2**2)*v
438
+ I_xy += (x1*y2 + 2*x1*y1 + 2*x2*y2 + x2*y1)*v
439
+ A = self.area
440
+ c_x = self.centroid[0]
441
+ c_y = self.centroid[1]
442
+ # parallel axis theorem
443
+ I_xx_c = (I_xx/12) - (A*(c_y**2))
444
+ I_yy_c = (I_yy/12) - (A*(c_x**2))
445
+ I_xy_c = (I_xy/24) - (A*(c_x*c_y))
446
+ if point is None:
447
+ return I_xx_c, I_yy_c, I_xy_c
448
+
449
+ I_xx = (I_xx_c + A*((point[1]-c_y)**2))
450
+ I_yy = (I_yy_c + A*((point[0]-c_x)**2))
451
+ I_xy = (I_xy_c + A*((point[0]-c_x)*(point[1]-c_y)))
452
+
453
+ return I_xx, I_yy, I_xy
454
+
455
+
456
+ def first_moment_of_area(self, point=None):
457
+ """
458
+ Returns the first moment of area of a two-dimensional polygon with
459
+ respect to a certain point of interest.
460
+
461
+ First moment of area is a measure of the distribution of the area
462
+ of a polygon in relation to an axis. The first moment of area of
463
+ the entire polygon about its own centroid is always zero. Therefore,
464
+ here it is calculated for an area, above or below a certain point
465
+ of interest, that makes up a smaller portion of the polygon. This
466
+ area is bounded by the point of interest and the extreme end
467
+ (top or bottom) of the polygon. The first moment for this area is
468
+ is then determined about the centroidal axis of the initial polygon.
469
+
470
+ References
471
+ ==========
472
+
473
+ .. [1] https://skyciv.com/docs/tutorials/section-tutorials/calculating-the-statical-or-first-moment-of-area-of-beam-sections/?cc=BMD
474
+ .. [2] https://mechanicalc.com/reference/cross-sections
475
+
476
+ Parameters
477
+ ==========
478
+
479
+ point: Point, two-tuple of sympifyable objects, or None (default=None)
480
+ point is the point above or below which the area of interest lies
481
+ If ``point=None`` then the centroid acts as the point of interest.
482
+
483
+ Returns
484
+ =======
485
+
486
+ Q_x, Q_y: number or SymPy expressions
487
+ Q_x is the first moment of area about the x-axis
488
+ Q_y is the first moment of area about the y-axis
489
+ A negative sign indicates that the section modulus is
490
+ determined for a section below (or left of) the centroidal axis
491
+
492
+ Examples
493
+ ========
494
+
495
+ >>> from sympy import Point, Polygon
496
+ >>> a, b = 50, 10
497
+ >>> p1, p2, p3, p4 = [(0, b), (0, 0), (a, 0), (a, b)]
498
+ >>> p = Polygon(p1, p2, p3, p4)
499
+ >>> p.first_moment_of_area()
500
+ (625, 3125)
501
+ >>> p.first_moment_of_area(point=Point(30, 7))
502
+ (525, 3000)
503
+ """
504
+ if point:
505
+ xc, yc = self.centroid
506
+ else:
507
+ point = self.centroid
508
+ xc, yc = point
509
+
510
+ h_line = Line(point, slope=0)
511
+ v_line = Line(point, slope=S.Infinity)
512
+
513
+ h_poly = self.cut_section(h_line)
514
+ v_poly = self.cut_section(v_line)
515
+
516
+ poly_1 = h_poly[0] if h_poly[0].area <= h_poly[1].area else h_poly[1]
517
+ poly_2 = v_poly[0] if v_poly[0].area <= v_poly[1].area else v_poly[1]
518
+
519
+ Q_x = (poly_1.centroid.y - yc)*poly_1.area
520
+ Q_y = (poly_2.centroid.x - xc)*poly_2.area
521
+
522
+ return Q_x, Q_y
523
+
524
+
525
+ def polar_second_moment_of_area(self):
526
+ """Returns the polar modulus of a two-dimensional polygon
527
+
528
+ It is a constituent of the second moment of area, linked through
529
+ the perpendicular axis theorem. While the planar second moment of
530
+ area describes an object's resistance to deflection (bending) when
531
+ subjected to a force applied to a plane parallel to the central
532
+ axis, the polar second moment of area describes an object's
533
+ resistance to deflection when subjected to a moment applied in a
534
+ plane perpendicular to the object's central axis (i.e. parallel to
535
+ the cross-section)
536
+
537
+ Examples
538
+ ========
539
+
540
+ >>> from sympy import Polygon, symbols
541
+ >>> a, b = symbols('a, b')
542
+ >>> rectangle = Polygon((0, 0), (a, 0), (a, b), (0, b))
543
+ >>> rectangle.polar_second_moment_of_area()
544
+ a**3*b/12 + a*b**3/12
545
+
546
+ References
547
+ ==========
548
+
549
+ .. [1] https://en.wikipedia.org/wiki/Polar_moment_of_inertia
550
+
551
+ """
552
+ second_moment = self.second_moment_of_area()
553
+ return second_moment[0] + second_moment[1]
554
+
555
+
556
+ def section_modulus(self, point=None):
557
+ """Returns a tuple with the section modulus of a two-dimensional
558
+ polygon.
559
+
560
+ Section modulus is a geometric property of a polygon defined as the
561
+ ratio of second moment of area to the distance of the extreme end of
562
+ the polygon from the centroidal axis.
563
+
564
+ Parameters
565
+ ==========
566
+
567
+ point : Point, two-tuple of sympifyable objects, or None(default=None)
568
+ point is the point at which section modulus is to be found.
569
+ If "point=None" it will be calculated for the point farthest from the
570
+ centroidal axis of the polygon.
571
+
572
+ Returns
573
+ =======
574
+
575
+ S_x, S_y: numbers or SymPy expressions
576
+ S_x is the section modulus with respect to the x-axis
577
+ S_y is the section modulus with respect to the y-axis
578
+ A negative sign indicates that the section modulus is
579
+ determined for a point below the centroidal axis
580
+
581
+ Examples
582
+ ========
583
+
584
+ >>> from sympy import symbols, Polygon, Point
585
+ >>> a, b = symbols('a, b', positive=True)
586
+ >>> rectangle = Polygon((0, 0), (a, 0), (a, b), (0, b))
587
+ >>> rectangle.section_modulus()
588
+ (a*b**2/6, a**2*b/6)
589
+ >>> rectangle.section_modulus(Point(a/4, b/4))
590
+ (-a*b**2/3, -a**2*b/3)
591
+
592
+ References
593
+ ==========
594
+
595
+ .. [1] https://en.wikipedia.org/wiki/Section_modulus
596
+
597
+ """
598
+ x_c, y_c = self.centroid
599
+ if point is None:
600
+ # taking x and y as maximum distances from centroid
601
+ x_min, y_min, x_max, y_max = self.bounds
602
+ y = max(y_c - y_min, y_max - y_c)
603
+ x = max(x_c - x_min, x_max - x_c)
604
+ else:
605
+ # taking x and y as distances of the given point from the centroid
606
+ y = point.y - y_c
607
+ x = point.x - x_c
608
+
609
+ second_moment= self.second_moment_of_area()
610
+ S_x = second_moment[0]/y
611
+ S_y = second_moment[1]/x
612
+
613
+ return S_x, S_y
614
+
615
+
616
+ @property
617
+ def sides(self):
618
+ """The directed line segments that form the sides of the polygon.
619
+
620
+ Returns
621
+ =======
622
+
623
+ sides : list of sides
624
+ Each side is a directed Segment.
625
+
626
+ See Also
627
+ ========
628
+
629
+ sympy.geometry.point.Point, sympy.geometry.line.Segment
630
+
631
+ Examples
632
+ ========
633
+
634
+ >>> from sympy import Point, Polygon
635
+ >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)])
636
+ >>> poly = Polygon(p1, p2, p3, p4)
637
+ >>> poly.sides
638
+ [Segment2D(Point2D(0, 0), Point2D(1, 0)),
639
+ Segment2D(Point2D(1, 0), Point2D(5, 1)),
640
+ Segment2D(Point2D(5, 1), Point2D(0, 1)), Segment2D(Point2D(0, 1), Point2D(0, 0))]
641
+
642
+ """
643
+ res = []
644
+ args = self.vertices
645
+ for i in range(-len(args), 0):
646
+ res.append(Segment(args[i], args[i + 1]))
647
+ return res
648
+
649
+ @property
650
+ def bounds(self):
651
+ """Return a tuple (xmin, ymin, xmax, ymax) representing the bounding
652
+ rectangle for the geometric figure.
653
+
654
+ """
655
+
656
+ verts = self.vertices
657
+ xs = [p.x for p in verts]
658
+ ys = [p.y for p in verts]
659
+ return (min(xs), min(ys), max(xs), max(ys))
660
+
661
+ def is_convex(self):
662
+ """Is the polygon convex?
663
+
664
+ A polygon is convex if all its interior angles are less than 180
665
+ degrees and there are no intersections between sides.
666
+
667
+ Returns
668
+ =======
669
+
670
+ is_convex : boolean
671
+ True if this polygon is convex, False otherwise.
672
+
673
+ See Also
674
+ ========
675
+
676
+ sympy.geometry.util.convex_hull
677
+
678
+ Examples
679
+ ========
680
+
681
+ >>> from sympy import Point, Polygon
682
+ >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)])
683
+ >>> poly = Polygon(p1, p2, p3, p4)
684
+ >>> poly.is_convex()
685
+ True
686
+
687
+ """
688
+ # Determine orientation of points
689
+ args = self.vertices
690
+ cw = self._is_clockwise(args[-2], args[-1], args[0])
691
+ for i in range(1, len(args)):
692
+ if cw ^ self._is_clockwise(args[i - 2], args[i - 1], args[i]):
693
+ return False
694
+ # check for intersecting sides
695
+ sides = self.sides
696
+ for i, si in enumerate(sides):
697
+ pts = si.args
698
+ # exclude the sides connected to si
699
+ for j in range(1 if i == len(sides) - 1 else 0, i - 1):
700
+ sj = sides[j]
701
+ if sj.p1 not in pts and sj.p2 not in pts:
702
+ hit = si.intersection(sj)
703
+ if hit:
704
+ return False
705
+ return True
706
+
707
+ def encloses_point(self, p):
708
+ """
709
+ Return True if p is enclosed by (is inside of) self.
710
+
711
+ Notes
712
+ =====
713
+
714
+ Being on the border of self is considered False.
715
+
716
+ Parameters
717
+ ==========
718
+
719
+ p : Point
720
+
721
+ Returns
722
+ =======
723
+
724
+ encloses_point : True, False or None
725
+
726
+ See Also
727
+ ========
728
+
729
+ sympy.geometry.point.Point, sympy.geometry.ellipse.Ellipse.encloses_point
730
+
731
+ Examples
732
+ ========
733
+
734
+ >>> from sympy import Polygon, Point
735
+ >>> p = Polygon((0, 0), (4, 0), (4, 4))
736
+ >>> p.encloses_point(Point(2, 1))
737
+ True
738
+ >>> p.encloses_point(Point(2, 2))
739
+ False
740
+ >>> p.encloses_point(Point(5, 5))
741
+ False
742
+
743
+ References
744
+ ==========
745
+
746
+ .. [1] https://paulbourke.net/geometry/polygonmesh/#insidepoly
747
+
748
+ """
749
+ p = Point(p, dim=2)
750
+ if p in self.vertices or any(p in s for s in self.sides):
751
+ return False
752
+
753
+ # move to p, checking that the result is numeric
754
+ lit = []
755
+ for v in self.vertices:
756
+ lit.append(v - p) # the difference is simplified
757
+ if lit[-1].free_symbols:
758
+ return None
759
+
760
+ poly = Polygon(*lit)
761
+
762
+ # polygon closure is assumed in the following test but Polygon removes duplicate pts so
763
+ # the last point has to be added so all sides are computed. Using Polygon.sides is
764
+ # not good since Segments are unordered.
765
+ args = poly.args
766
+ indices = list(range(-len(args), 1))
767
+
768
+ if poly.is_convex():
769
+ orientation = None
770
+ for i in indices:
771
+ a = args[i]
772
+ b = args[i + 1]
773
+ test = ((-a.y)*(b.x - a.x) - (-a.x)*(b.y - a.y)).is_negative
774
+ if orientation is None:
775
+ orientation = test
776
+ elif test is not orientation:
777
+ return False
778
+ return True
779
+
780
+ hit_odd = False
781
+ p1x, p1y = args[0].args
782
+ for i in indices[1:]:
783
+ p2x, p2y = args[i].args
784
+ if 0 > min(p1y, p2y):
785
+ if 0 <= max(p1y, p2y):
786
+ if 0 <= max(p1x, p2x):
787
+ if p1y != p2y:
788
+ xinters = (-p1y)*(p2x - p1x)/(p2y - p1y) + p1x
789
+ if p1x == p2x or 0 <= xinters:
790
+ hit_odd = not hit_odd
791
+ p1x, p1y = p2x, p2y
792
+ return hit_odd
793
+
794
+ def arbitrary_point(self, parameter='t'):
795
+ """A parameterized point on the polygon.
796
+
797
+ The parameter, varying from 0 to 1, assigns points to the position on
798
+ the perimeter that is that fraction of the total perimeter. So the
799
+ point evaluated at t=1/2 would return the point from the first vertex
800
+ that is 1/2 way around the polygon.
801
+
802
+ Parameters
803
+ ==========
804
+
805
+ parameter : str, optional
806
+ Default value is 't'.
807
+
808
+ Returns
809
+ =======
810
+
811
+ arbitrary_point : Point
812
+
813
+ Raises
814
+ ======
815
+
816
+ ValueError
817
+ When `parameter` already appears in the Polygon's definition.
818
+
819
+ See Also
820
+ ========
821
+
822
+ sympy.geometry.point.Point
823
+
824
+ Examples
825
+ ========
826
+
827
+ >>> from sympy import Polygon, Symbol
828
+ >>> t = Symbol('t', real=True)
829
+ >>> tri = Polygon((0, 0), (1, 0), (1, 1))
830
+ >>> p = tri.arbitrary_point('t')
831
+ >>> perimeter = tri.perimeter
832
+ >>> s1, s2 = [s.length for s in tri.sides[:2]]
833
+ >>> p.subs(t, (s1 + s2/2)/perimeter)
834
+ Point2D(1, 1/2)
835
+
836
+ """
837
+ t = _symbol(parameter, real=True)
838
+ if t.name in (f.name for f in self.free_symbols):
839
+ raise ValueError('Symbol %s already appears in object and cannot be used as a parameter.' % t.name)
840
+ sides = []
841
+ perimeter = self.perimeter
842
+ perim_fraction_start = 0
843
+ for s in self.sides:
844
+ side_perim_fraction = s.length/perimeter
845
+ perim_fraction_end = perim_fraction_start + side_perim_fraction
846
+ pt = s.arbitrary_point(parameter).subs(
847
+ t, (t - perim_fraction_start)/side_perim_fraction)
848
+ sides.append(
849
+ (pt, (And(perim_fraction_start <= t, t < perim_fraction_end))))
850
+ perim_fraction_start = perim_fraction_end
851
+ return Piecewise(*sides)
852
+
853
+ def parameter_value(self, other, t):
854
+ if not isinstance(other,GeometryEntity):
855
+ other = Point(other, dim=self.ambient_dimension)
856
+ if not isinstance(other,Point):
857
+ raise ValueError("other must be a point")
858
+ if other.free_symbols:
859
+ raise NotImplementedError('non-numeric coordinates')
860
+ unknown = False
861
+ p = self.arbitrary_point(T)
862
+ for pt, cond in p.args:
863
+ sol = solve(pt - other, T, dict=True)
864
+ if not sol:
865
+ continue
866
+ value = sol[0][T]
867
+ if simplify(cond.subs(T, value)) == True:
868
+ return {t: value}
869
+ unknown = True
870
+ if unknown:
871
+ raise ValueError("Given point may not be on %s" % func_name(self))
872
+ raise ValueError("Given point is not on %s" % func_name(self))
873
+
874
+ def plot_interval(self, parameter='t'):
875
+ """The plot interval for the default geometric plot of the polygon.
876
+
877
+ Parameters
878
+ ==========
879
+
880
+ parameter : str, optional
881
+ Default value is 't'.
882
+
883
+ Returns
884
+ =======
885
+
886
+ plot_interval : list (plot interval)
887
+ [parameter, lower_bound, upper_bound]
888
+
889
+ Examples
890
+ ========
891
+
892
+ >>> from sympy import Polygon
893
+ >>> p = Polygon((0, 0), (1, 0), (1, 1))
894
+ >>> p.plot_interval()
895
+ [t, 0, 1]
896
+
897
+ """
898
+ t = Symbol(parameter, real=True)
899
+ return [t, 0, 1]
900
+
901
+ def intersection(self, o):
902
+ """The intersection of polygon and geometry entity.
903
+
904
+ The intersection may be empty and can contain individual Points and
905
+ complete Line Segments.
906
+
907
+ Parameters
908
+ ==========
909
+
910
+ other: GeometryEntity
911
+
912
+ Returns
913
+ =======
914
+
915
+ intersection : list
916
+ The list of Segments and Points
917
+
918
+ See Also
919
+ ========
920
+
921
+ sympy.geometry.point.Point, sympy.geometry.line.Segment
922
+
923
+ Examples
924
+ ========
925
+
926
+ >>> from sympy import Point, Polygon, Line
927
+ >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)])
928
+ >>> poly1 = Polygon(p1, p2, p3, p4)
929
+ >>> p5, p6, p7 = map(Point, [(3, 2), (1, -1), (0, 2)])
930
+ >>> poly2 = Polygon(p5, p6, p7)
931
+ >>> poly1.intersection(poly2)
932
+ [Point2D(1/3, 1), Point2D(2/3, 0), Point2D(9/5, 1/5), Point2D(7/3, 1)]
933
+ >>> poly1.intersection(Line(p1, p2))
934
+ [Segment2D(Point2D(0, 0), Point2D(1, 0))]
935
+ >>> poly1.intersection(p1)
936
+ [Point2D(0, 0)]
937
+ """
938
+ intersection_result = []
939
+ k = o.sides if isinstance(o, Polygon) else [o]
940
+ for side in self.sides:
941
+ for side1 in k:
942
+ intersection_result.extend(side.intersection(side1))
943
+
944
+ intersection_result = list(uniq(intersection_result))
945
+ points = [entity for entity in intersection_result if isinstance(entity, Point)]
946
+ segments = [entity for entity in intersection_result if isinstance(entity, Segment)]
947
+
948
+ if points and segments:
949
+ points_in_segments = list(uniq([point for point in points for segment in segments if point in segment]))
950
+ if points_in_segments:
951
+ for i in points_in_segments:
952
+ points.remove(i)
953
+ return list(ordered(segments + points))
954
+ else:
955
+ return list(ordered(intersection_result))
956
+
957
+
958
+ def cut_section(self, line):
959
+ """
960
+ Returns a tuple of two polygon segments that lie above and below
961
+ the intersecting line respectively.
962
+
963
+ Parameters
964
+ ==========
965
+
966
+ line: Line object of geometry module
967
+ line which cuts the Polygon. The part of the Polygon that lies
968
+ above and below this line is returned.
969
+
970
+ Returns
971
+ =======
972
+
973
+ upper_polygon, lower_polygon: Polygon objects or None
974
+ upper_polygon is the polygon that lies above the given line.
975
+ lower_polygon is the polygon that lies below the given line.
976
+ upper_polygon and lower polygon are ``None`` when no polygon
977
+ exists above the line or below the line.
978
+
979
+ Raises
980
+ ======
981
+
982
+ ValueError: When the line does not intersect the polygon
983
+
984
+ Examples
985
+ ========
986
+
987
+ >>> from sympy import Polygon, Line
988
+ >>> a, b = 20, 10
989
+ >>> p1, p2, p3, p4 = [(0, b), (0, 0), (a, 0), (a, b)]
990
+ >>> rectangle = Polygon(p1, p2, p3, p4)
991
+ >>> t = rectangle.cut_section(Line((0, 5), slope=0))
992
+ >>> t
993
+ (Polygon(Point2D(0, 10), Point2D(0, 5), Point2D(20, 5), Point2D(20, 10)),
994
+ Polygon(Point2D(0, 5), Point2D(0, 0), Point2D(20, 0), Point2D(20, 5)))
995
+ >>> upper_segment, lower_segment = t
996
+ >>> upper_segment.area
997
+ 100
998
+ >>> upper_segment.centroid
999
+ Point2D(10, 15/2)
1000
+ >>> lower_segment.centroid
1001
+ Point2D(10, 5/2)
1002
+
1003
+ References
1004
+ ==========
1005
+
1006
+ .. [1] https://github.com/sympy/sympy/wiki/A-method-to-return-a-cut-section-of-any-polygon-geometry
1007
+
1008
+ """
1009
+ intersection_points = self.intersection(line)
1010
+ if not intersection_points:
1011
+ raise ValueError("This line does not intersect the polygon")
1012
+
1013
+ points = list(self.vertices)
1014
+ points.append(points[0])
1015
+
1016
+ eq = line.equation(x, y)
1017
+
1018
+ # considering equation of line to be `ax +by + c`
1019
+ a = eq.coeff(x)
1020
+ b = eq.coeff(y)
1021
+
1022
+ upper_vertices = []
1023
+ lower_vertices = []
1024
+ # prev is true when previous point is above the line
1025
+ prev = True
1026
+ prev_point = None
1027
+ for point in points:
1028
+ # when coefficient of y is 0, right side of the line is
1029
+ # considered
1030
+ compare = eq.subs({x: point.x, y: point.y})/b if b \
1031
+ else eq.subs(x, point.x)/a
1032
+
1033
+ # if point lies above line
1034
+ if compare > 0:
1035
+ if not prev:
1036
+ # if previous point lies below the line, the intersection
1037
+ # point of the polygon edge and the line has to be included
1038
+ edge = Line(point, prev_point)
1039
+ new_point = edge.intersection(line)
1040
+ upper_vertices.append(new_point[0])
1041
+ lower_vertices.append(new_point[0])
1042
+
1043
+ upper_vertices.append(point)
1044
+ prev = True
1045
+ else:
1046
+ if prev and prev_point:
1047
+ edge = Line(point, prev_point)
1048
+ new_point = edge.intersection(line)
1049
+ upper_vertices.append(new_point[0])
1050
+ lower_vertices.append(new_point[0])
1051
+ lower_vertices.append(point)
1052
+ prev = False
1053
+ prev_point = point
1054
+
1055
+ upper_polygon, lower_polygon = None, None
1056
+ if upper_vertices and isinstance(Polygon(*upper_vertices), Polygon):
1057
+ upper_polygon = Polygon(*upper_vertices)
1058
+ if lower_vertices and isinstance(Polygon(*lower_vertices), Polygon):
1059
+ lower_polygon = Polygon(*lower_vertices)
1060
+
1061
+ return upper_polygon, lower_polygon
1062
+
1063
+
1064
+ def distance(self, o):
1065
+ """
1066
+ Returns the shortest distance between self and o.
1067
+
1068
+ If o is a point, then self does not need to be convex.
1069
+ If o is another polygon self and o must be convex.
1070
+
1071
+ Examples
1072
+ ========
1073
+
1074
+ >>> from sympy import Point, Polygon, RegularPolygon
1075
+ >>> p1, p2 = map(Point, [(0, 0), (7, 5)])
1076
+ >>> poly = Polygon(*RegularPolygon(p1, 1, 3).vertices)
1077
+ >>> poly.distance(p2)
1078
+ sqrt(61)
1079
+ """
1080
+ if isinstance(o, Point):
1081
+ dist = oo
1082
+ for side in self.sides:
1083
+ current = side.distance(o)
1084
+ if current == 0:
1085
+ return S.Zero
1086
+ elif current < dist:
1087
+ dist = current
1088
+ return dist
1089
+ elif isinstance(o, Polygon) and self.is_convex() and o.is_convex():
1090
+ return self._do_poly_distance(o)
1091
+ raise NotImplementedError()
1092
+
1093
+ def _do_poly_distance(self, e2):
1094
+ """
1095
+ Calculates the least distance between the exteriors of two
1096
+ convex polygons e1 and e2. Does not check for the convexity
1097
+ of the polygons as this is checked by Polygon.distance.
1098
+
1099
+ Notes
1100
+ =====
1101
+
1102
+ - Prints a warning if the two polygons possibly intersect as the return
1103
+ value will not be valid in such a case. For a more through test of
1104
+ intersection use intersection().
1105
+
1106
+ See Also
1107
+ ========
1108
+
1109
+ sympy.geometry.point.Point.distance
1110
+
1111
+ Examples
1112
+ ========
1113
+
1114
+ >>> from sympy import Point, Polygon
1115
+ >>> square = Polygon(Point(0, 0), Point(0, 1), Point(1, 1), Point(1, 0))
1116
+ >>> triangle = Polygon(Point(1, 2), Point(2, 2), Point(2, 1))
1117
+ >>> square._do_poly_distance(triangle)
1118
+ sqrt(2)/2
1119
+
1120
+ Description of method used
1121
+ ==========================
1122
+
1123
+ Method:
1124
+ [1] https://web.archive.org/web/20150509035744/http://cgm.cs.mcgill.ca/~orm/mind2p.html
1125
+ Uses rotating calipers:
1126
+ [2] https://en.wikipedia.org/wiki/Rotating_calipers
1127
+ and antipodal points:
1128
+ [3] https://en.wikipedia.org/wiki/Antipodal_point
1129
+ """
1130
+ e1 = self
1131
+
1132
+ '''Tests for a possible intersection between the polygons and outputs a warning'''
1133
+ e1_center = e1.centroid
1134
+ e2_center = e2.centroid
1135
+ e1_max_radius = S.Zero
1136
+ e2_max_radius = S.Zero
1137
+ for vertex in e1.vertices:
1138
+ r = Point.distance(e1_center, vertex)
1139
+ if e1_max_radius < r:
1140
+ e1_max_radius = r
1141
+ for vertex in e2.vertices:
1142
+ r = Point.distance(e2_center, vertex)
1143
+ if e2_max_radius < r:
1144
+ e2_max_radius = r
1145
+ center_dist = Point.distance(e1_center, e2_center)
1146
+ if center_dist <= e1_max_radius + e2_max_radius:
1147
+ warnings.warn("Polygons may intersect producing erroneous output",
1148
+ stacklevel=3)
1149
+
1150
+ '''
1151
+ Find the upper rightmost vertex of e1 and the lowest leftmost vertex of e2
1152
+ '''
1153
+ e1_ymax = Point(0, -oo)
1154
+ e2_ymin = Point(0, oo)
1155
+
1156
+ for vertex in e1.vertices:
1157
+ if vertex.y > e1_ymax.y or (vertex.y == e1_ymax.y and vertex.x > e1_ymax.x):
1158
+ e1_ymax = vertex
1159
+ for vertex in e2.vertices:
1160
+ if vertex.y < e2_ymin.y or (vertex.y == e2_ymin.y and vertex.x < e2_ymin.x):
1161
+ e2_ymin = vertex
1162
+ min_dist = Point.distance(e1_ymax, e2_ymin)
1163
+
1164
+ '''
1165
+ Produce a dictionary with vertices of e1 as the keys and, for each vertex, the points
1166
+ to which the vertex is connected as its value. The same is then done for e2.
1167
+ '''
1168
+ e1_connections = {}
1169
+ e2_connections = {}
1170
+
1171
+ for side in e1.sides:
1172
+ if side.p1 in e1_connections:
1173
+ e1_connections[side.p1].append(side.p2)
1174
+ else:
1175
+ e1_connections[side.p1] = [side.p2]
1176
+
1177
+ if side.p2 in e1_connections:
1178
+ e1_connections[side.p2].append(side.p1)
1179
+ else:
1180
+ e1_connections[side.p2] = [side.p1]
1181
+
1182
+ for side in e2.sides:
1183
+ if side.p1 in e2_connections:
1184
+ e2_connections[side.p1].append(side.p2)
1185
+ else:
1186
+ e2_connections[side.p1] = [side.p2]
1187
+
1188
+ if side.p2 in e2_connections:
1189
+ e2_connections[side.p2].append(side.p1)
1190
+ else:
1191
+ e2_connections[side.p2] = [side.p1]
1192
+
1193
+ e1_current = e1_ymax
1194
+ e2_current = e2_ymin
1195
+ support_line = Line(Point(S.Zero, S.Zero), Point(S.One, S.Zero))
1196
+
1197
+ '''
1198
+ Determine which point in e1 and e2 will be selected after e2_ymin and e1_ymax,
1199
+ this information combined with the above produced dictionaries determines the
1200
+ path that will be taken around the polygons
1201
+ '''
1202
+ point1 = e1_connections[e1_ymax][0]
1203
+ point2 = e1_connections[e1_ymax][1]
1204
+ angle1 = support_line.angle_between(Line(e1_ymax, point1))
1205
+ angle2 = support_line.angle_between(Line(e1_ymax, point2))
1206
+ if angle1 < angle2:
1207
+ e1_next = point1
1208
+ elif angle2 < angle1:
1209
+ e1_next = point2
1210
+ elif Point.distance(e1_ymax, point1) > Point.distance(e1_ymax, point2):
1211
+ e1_next = point2
1212
+ else:
1213
+ e1_next = point1
1214
+
1215
+ point1 = e2_connections[e2_ymin][0]
1216
+ point2 = e2_connections[e2_ymin][1]
1217
+ angle1 = support_line.angle_between(Line(e2_ymin, point1))
1218
+ angle2 = support_line.angle_between(Line(e2_ymin, point2))
1219
+ if angle1 > angle2:
1220
+ e2_next = point1
1221
+ elif angle2 > angle1:
1222
+ e2_next = point2
1223
+ elif Point.distance(e2_ymin, point1) > Point.distance(e2_ymin, point2):
1224
+ e2_next = point2
1225
+ else:
1226
+ e2_next = point1
1227
+
1228
+ '''
1229
+ Loop which determines the distance between anti-podal pairs and updates the
1230
+ minimum distance accordingly. It repeats until it reaches the starting position.
1231
+ '''
1232
+ while True:
1233
+ e1_angle = support_line.angle_between(Line(e1_current, e1_next))
1234
+ e2_angle = pi - support_line.angle_between(Line(
1235
+ e2_current, e2_next))
1236
+
1237
+ if (e1_angle < e2_angle) is True:
1238
+ support_line = Line(e1_current, e1_next)
1239
+ e1_segment = Segment(e1_current, e1_next)
1240
+ min_dist_current = e1_segment.distance(e2_current)
1241
+
1242
+ if min_dist_current.evalf() < min_dist.evalf():
1243
+ min_dist = min_dist_current
1244
+
1245
+ if e1_connections[e1_next][0] != e1_current:
1246
+ e1_current = e1_next
1247
+ e1_next = e1_connections[e1_next][0]
1248
+ else:
1249
+ e1_current = e1_next
1250
+ e1_next = e1_connections[e1_next][1]
1251
+ elif (e1_angle > e2_angle) is True:
1252
+ support_line = Line(e2_next, e2_current)
1253
+ e2_segment = Segment(e2_current, e2_next)
1254
+ min_dist_current = e2_segment.distance(e1_current)
1255
+
1256
+ if min_dist_current.evalf() < min_dist.evalf():
1257
+ min_dist = min_dist_current
1258
+
1259
+ if e2_connections[e2_next][0] != e2_current:
1260
+ e2_current = e2_next
1261
+ e2_next = e2_connections[e2_next][0]
1262
+ else:
1263
+ e2_current = e2_next
1264
+ e2_next = e2_connections[e2_next][1]
1265
+ else:
1266
+ support_line = Line(e1_current, e1_next)
1267
+ e1_segment = Segment(e1_current, e1_next)
1268
+ e2_segment = Segment(e2_current, e2_next)
1269
+ min1 = e1_segment.distance(e2_next)
1270
+ min2 = e2_segment.distance(e1_next)
1271
+
1272
+ min_dist_current = min(min1, min2)
1273
+ if min_dist_current.evalf() < min_dist.evalf():
1274
+ min_dist = min_dist_current
1275
+
1276
+ if e1_connections[e1_next][0] != e1_current:
1277
+ e1_current = e1_next
1278
+ e1_next = e1_connections[e1_next][0]
1279
+ else:
1280
+ e1_current = e1_next
1281
+ e1_next = e1_connections[e1_next][1]
1282
+
1283
+ if e2_connections[e2_next][0] != e2_current:
1284
+ e2_current = e2_next
1285
+ e2_next = e2_connections[e2_next][0]
1286
+ else:
1287
+ e2_current = e2_next
1288
+ e2_next = e2_connections[e2_next][1]
1289
+ if e1_current == e1_ymax and e2_current == e2_ymin:
1290
+ break
1291
+ return min_dist
1292
+
1293
+ def _svg(self, scale_factor=1., fill_color="#66cc99"):
1294
+ """Returns SVG path element for the Polygon.
1295
+
1296
+ Parameters
1297
+ ==========
1298
+
1299
+ scale_factor : float
1300
+ Multiplication factor for the SVG stroke-width. Default is 1.
1301
+ fill_color : str, optional
1302
+ Hex string for fill color. Default is "#66cc99".
1303
+ """
1304
+ verts = map(N, self.vertices)
1305
+ coords = ["{},{}".format(p.x, p.y) for p in verts]
1306
+ path = "M {} L {} z".format(coords[0], " L ".join(coords[1:]))
1307
+ return (
1308
+ '<path fill-rule="evenodd" fill="{2}" stroke="#555555" '
1309
+ 'stroke-width="{0}" opacity="0.6" d="{1}" />'
1310
+ ).format(2. * scale_factor, path, fill_color)
1311
+
1312
+ def _hashable_content(self):
1313
+
1314
+ D = {}
1315
+ def ref_list(point_list):
1316
+ kee = {}
1317
+ for i, p in enumerate(ordered(set(point_list))):
1318
+ kee[p] = i
1319
+ D[i] = p
1320
+ return [kee[p] for p in point_list]
1321
+
1322
+ S1 = ref_list(self.args)
1323
+ r_nor = rotate_left(S1, least_rotation(S1))
1324
+ S2 = ref_list(list(reversed(self.args)))
1325
+ r_rev = rotate_left(S2, least_rotation(S2))
1326
+ if r_nor < r_rev:
1327
+ r = r_nor
1328
+ else:
1329
+ r = r_rev
1330
+ canonical_args = [ D[order] for order in r ]
1331
+ return tuple(canonical_args)
1332
+
1333
+ def __contains__(self, o):
1334
+ """
1335
+ Return True if o is contained within the boundary lines of self.altitudes
1336
+
1337
+ Parameters
1338
+ ==========
1339
+
1340
+ other : GeometryEntity
1341
+
1342
+ Returns
1343
+ =======
1344
+
1345
+ contained in : bool
1346
+ The points (and sides, if applicable) are contained in self.
1347
+
1348
+ See Also
1349
+ ========
1350
+
1351
+ sympy.geometry.entity.GeometryEntity.encloses
1352
+
1353
+ Examples
1354
+ ========
1355
+
1356
+ >>> from sympy import Line, Segment, Point
1357
+ >>> p = Point(0, 0)
1358
+ >>> q = Point(1, 1)
1359
+ >>> s = Segment(p, q*2)
1360
+ >>> l = Line(p, q)
1361
+ >>> p in q
1362
+ False
1363
+ >>> p in s
1364
+ True
1365
+ >>> q*3 in s
1366
+ False
1367
+ >>> s in l
1368
+ True
1369
+
1370
+ """
1371
+
1372
+ if isinstance(o, Polygon):
1373
+ return self == o
1374
+ elif isinstance(o, Segment):
1375
+ return any(o in s for s in self.sides)
1376
+ elif isinstance(o, Point):
1377
+ if o in self.vertices:
1378
+ return True
1379
+ for side in self.sides:
1380
+ if o in side:
1381
+ return True
1382
+
1383
+ return False
1384
+
1385
+ def bisectors(p, prec=None):
1386
+ """Returns angle bisectors of a polygon. If prec is given
1387
+ then approximate the point defining the ray to that precision.
1388
+
1389
+ The distance between the points defining the bisector ray is 1.
1390
+
1391
+ Examples
1392
+ ========
1393
+
1394
+ >>> from sympy import Polygon, Point
1395
+ >>> p = Polygon(Point(0, 0), Point(2, 0), Point(1, 1), Point(0, 3))
1396
+ >>> p.bisectors(2)
1397
+ {Point2D(0, 0): Ray2D(Point2D(0, 0), Point2D(0.71, 0.71)),
1398
+ Point2D(0, 3): Ray2D(Point2D(0, 3), Point2D(0.23, 2.0)),
1399
+ Point2D(1, 1): Ray2D(Point2D(1, 1), Point2D(0.19, 0.42)),
1400
+ Point2D(2, 0): Ray2D(Point2D(2, 0), Point2D(1.1, 0.38))}
1401
+ """
1402
+ b = {}
1403
+ pts = list(p.args)
1404
+ pts.append(pts[0]) # close it
1405
+ cw = Polygon._is_clockwise(*pts[:3])
1406
+ if cw:
1407
+ pts = list(reversed(pts))
1408
+ for v, a in p.angles.items():
1409
+ i = pts.index(v)
1410
+ p1, p2 = Point._normalize_dimension(pts[i], pts[i + 1])
1411
+ ray = Ray(p1, p2).rotate(a/2, v)
1412
+ dir = ray.direction
1413
+ ray = Ray(ray.p1, ray.p1 + dir/dir.distance((0, 0)))
1414
+ if prec is not None:
1415
+ ray = Ray(ray.p1, ray.p2.n(prec))
1416
+ b[v] = ray
1417
+ return b
1418
+
1419
+
1420
+ class RegularPolygon(Polygon):
1421
+ """
1422
+ A regular polygon.
1423
+
1424
+ Such a polygon has all internal angles equal and all sides the same length.
1425
+
1426
+ Parameters
1427
+ ==========
1428
+
1429
+ center : Point
1430
+ radius : number or Basic instance
1431
+ The distance from the center to a vertex
1432
+ n : int
1433
+ The number of sides
1434
+
1435
+ Attributes
1436
+ ==========
1437
+
1438
+ vertices
1439
+ center
1440
+ radius
1441
+ rotation
1442
+ apothem
1443
+ interior_angle
1444
+ exterior_angle
1445
+ circumcircle
1446
+ incircle
1447
+ angles
1448
+
1449
+ Raises
1450
+ ======
1451
+
1452
+ GeometryError
1453
+ If the `center` is not a Point, or the `radius` is not a number or Basic
1454
+ instance, or the number of sides, `n`, is less than three.
1455
+
1456
+ Notes
1457
+ =====
1458
+
1459
+ A RegularPolygon can be instantiated with Polygon with the kwarg n.
1460
+
1461
+ Regular polygons are instantiated with a center, radius, number of sides
1462
+ and a rotation angle. Whereas the arguments of a Polygon are vertices, the
1463
+ vertices of the RegularPolygon must be obtained with the vertices method.
1464
+
1465
+ See Also
1466
+ ========
1467
+
1468
+ sympy.geometry.point.Point, Polygon
1469
+
1470
+ Examples
1471
+ ========
1472
+
1473
+ >>> from sympy import RegularPolygon, Point
1474
+ >>> r = RegularPolygon(Point(0, 0), 5, 3)
1475
+ >>> r
1476
+ RegularPolygon(Point2D(0, 0), 5, 3, 0)
1477
+ >>> r.vertices[0]
1478
+ Point2D(5, 0)
1479
+
1480
+ """
1481
+
1482
+ __slots__ = ('_n', '_center', '_radius', '_rot')
1483
+
1484
+ def __new__(self, c, r, n, rot=0, **kwargs):
1485
+ r, n, rot = map(sympify, (r, n, rot))
1486
+ c = Point(c, dim=2, **kwargs)
1487
+ if not isinstance(r, Expr):
1488
+ raise GeometryError("r must be an Expr object, not %s" % r)
1489
+ if n.is_Number:
1490
+ as_int(n) # let an error raise if necessary
1491
+ if n < 3:
1492
+ raise GeometryError("n must be a >= 3, not %s" % n)
1493
+
1494
+ obj = GeometryEntity.__new__(self, c, r, n, **kwargs)
1495
+ obj._n = n
1496
+ obj._center = c
1497
+ obj._radius = r
1498
+ obj._rot = rot % (2*S.Pi/n) if rot.is_number else rot
1499
+ return obj
1500
+
1501
+ def _eval_evalf(self, prec=15, **options):
1502
+ c, r, n, a = self.args
1503
+ dps = prec_to_dps(prec)
1504
+ c, r, a = [i.evalf(n=dps, **options) for i in (c, r, a)]
1505
+ return self.func(c, r, n, a)
1506
+
1507
+ @property
1508
+ def args(self):
1509
+ """
1510
+ Returns the center point, the radius,
1511
+ the number of sides, and the orientation angle.
1512
+
1513
+ Examples
1514
+ ========
1515
+
1516
+ >>> from sympy import RegularPolygon, Point
1517
+ >>> r = RegularPolygon(Point(0, 0), 5, 3)
1518
+ >>> r.args
1519
+ (Point2D(0, 0), 5, 3, 0)
1520
+ """
1521
+ return self._center, self._radius, self._n, self._rot
1522
+
1523
+ def __str__(self):
1524
+ return 'RegularPolygon(%s, %s, %s, %s)' % tuple(self.args)
1525
+
1526
+ def __repr__(self):
1527
+ return 'RegularPolygon(%s, %s, %s, %s)' % tuple(self.args)
1528
+
1529
+ @property
1530
+ def area(self):
1531
+ """Returns the area.
1532
+
1533
+ Examples
1534
+ ========
1535
+
1536
+ >>> from sympy import RegularPolygon
1537
+ >>> square = RegularPolygon((0, 0), 1, 4)
1538
+ >>> square.area
1539
+ 2
1540
+ >>> _ == square.length**2
1541
+ True
1542
+ """
1543
+ c, r, n, rot = self.args
1544
+ return sign(r)*n*self.length**2/(4*tan(pi/n))
1545
+
1546
+ @property
1547
+ def length(self):
1548
+ """Returns the length of the sides.
1549
+
1550
+ The half-length of the side and the apothem form two legs
1551
+ of a right triangle whose hypotenuse is the radius of the
1552
+ regular polygon.
1553
+
1554
+ Examples
1555
+ ========
1556
+
1557
+ >>> from sympy import RegularPolygon
1558
+ >>> from sympy import sqrt
1559
+ >>> s = square_in_unit_circle = RegularPolygon((0, 0), 1, 4)
1560
+ >>> s.length
1561
+ sqrt(2)
1562
+ >>> sqrt((_/2)**2 + s.apothem**2) == s.radius
1563
+ True
1564
+
1565
+ """
1566
+ return self.radius*2*sin(pi/self._n)
1567
+
1568
+ @property
1569
+ def center(self):
1570
+ """The center of the RegularPolygon
1571
+
1572
+ This is also the center of the circumscribing circle.
1573
+
1574
+ Returns
1575
+ =======
1576
+
1577
+ center : Point
1578
+
1579
+ See Also
1580
+ ========
1581
+
1582
+ sympy.geometry.point.Point, sympy.geometry.ellipse.Ellipse.center
1583
+
1584
+ Examples
1585
+ ========
1586
+
1587
+ >>> from sympy import RegularPolygon, Point
1588
+ >>> rp = RegularPolygon(Point(0, 0), 5, 4)
1589
+ >>> rp.center
1590
+ Point2D(0, 0)
1591
+ """
1592
+ return self._center
1593
+
1594
+ centroid = center
1595
+
1596
+ @property
1597
+ def circumcenter(self):
1598
+ """
1599
+ Alias for center.
1600
+
1601
+ Examples
1602
+ ========
1603
+
1604
+ >>> from sympy import RegularPolygon, Point
1605
+ >>> rp = RegularPolygon(Point(0, 0), 5, 4)
1606
+ >>> rp.circumcenter
1607
+ Point2D(0, 0)
1608
+ """
1609
+ return self.center
1610
+
1611
+ @property
1612
+ def radius(self):
1613
+ """Radius of the RegularPolygon
1614
+
1615
+ This is also the radius of the circumscribing circle.
1616
+
1617
+ Returns
1618
+ =======
1619
+
1620
+ radius : number or instance of Basic
1621
+
1622
+ See Also
1623
+ ========
1624
+
1625
+ sympy.geometry.line.Segment.length, sympy.geometry.ellipse.Circle.radius
1626
+
1627
+ Examples
1628
+ ========
1629
+
1630
+ >>> from sympy import Symbol
1631
+ >>> from sympy import RegularPolygon, Point
1632
+ >>> radius = Symbol('r')
1633
+ >>> rp = RegularPolygon(Point(0, 0), radius, 4)
1634
+ >>> rp.radius
1635
+ r
1636
+
1637
+ """
1638
+ return self._radius
1639
+
1640
+ @property
1641
+ def circumradius(self):
1642
+ """
1643
+ Alias for radius.
1644
+
1645
+ Examples
1646
+ ========
1647
+
1648
+ >>> from sympy import Symbol
1649
+ >>> from sympy import RegularPolygon, Point
1650
+ >>> radius = Symbol('r')
1651
+ >>> rp = RegularPolygon(Point(0, 0), radius, 4)
1652
+ >>> rp.circumradius
1653
+ r
1654
+ """
1655
+ return self.radius
1656
+
1657
+ @property
1658
+ def rotation(self):
1659
+ """CCW angle by which the RegularPolygon is rotated
1660
+
1661
+ Returns
1662
+ =======
1663
+
1664
+ rotation : number or instance of Basic
1665
+
1666
+ Examples
1667
+ ========
1668
+
1669
+ >>> from sympy import pi
1670
+ >>> from sympy.abc import a
1671
+ >>> from sympy import RegularPolygon, Point
1672
+ >>> RegularPolygon(Point(0, 0), 3, 4, pi/4).rotation
1673
+ pi/4
1674
+
1675
+ Numerical rotation angles are made canonical:
1676
+
1677
+ >>> RegularPolygon(Point(0, 0), 3, 4, a).rotation
1678
+ a
1679
+ >>> RegularPolygon(Point(0, 0), 3, 4, pi).rotation
1680
+ 0
1681
+
1682
+ """
1683
+ return self._rot
1684
+
1685
+ @property
1686
+ def apothem(self):
1687
+ """The inradius of the RegularPolygon.
1688
+
1689
+ The apothem/inradius is the radius of the inscribed circle.
1690
+
1691
+ Returns
1692
+ =======
1693
+
1694
+ apothem : number or instance of Basic
1695
+
1696
+ See Also
1697
+ ========
1698
+
1699
+ sympy.geometry.line.Segment.length, sympy.geometry.ellipse.Circle.radius
1700
+
1701
+ Examples
1702
+ ========
1703
+
1704
+ >>> from sympy import Symbol
1705
+ >>> from sympy import RegularPolygon, Point
1706
+ >>> radius = Symbol('r')
1707
+ >>> rp = RegularPolygon(Point(0, 0), radius, 4)
1708
+ >>> rp.apothem
1709
+ sqrt(2)*r/2
1710
+
1711
+ """
1712
+ return self.radius * cos(S.Pi/self._n)
1713
+
1714
+ @property
1715
+ def inradius(self):
1716
+ """
1717
+ Alias for apothem.
1718
+
1719
+ Examples
1720
+ ========
1721
+
1722
+ >>> from sympy import Symbol
1723
+ >>> from sympy import RegularPolygon, Point
1724
+ >>> radius = Symbol('r')
1725
+ >>> rp = RegularPolygon(Point(0, 0), radius, 4)
1726
+ >>> rp.inradius
1727
+ sqrt(2)*r/2
1728
+ """
1729
+ return self.apothem
1730
+
1731
+ @property
1732
+ def interior_angle(self):
1733
+ """Measure of the interior angles.
1734
+
1735
+ Returns
1736
+ =======
1737
+
1738
+ interior_angle : number
1739
+
1740
+ See Also
1741
+ ========
1742
+
1743
+ sympy.geometry.line.LinearEntity.angle_between
1744
+
1745
+ Examples
1746
+ ========
1747
+
1748
+ >>> from sympy import RegularPolygon, Point
1749
+ >>> rp = RegularPolygon(Point(0, 0), 4, 8)
1750
+ >>> rp.interior_angle
1751
+ 3*pi/4
1752
+
1753
+ """
1754
+ return (self._n - 2)*S.Pi/self._n
1755
+
1756
+ @property
1757
+ def exterior_angle(self):
1758
+ """Measure of the exterior angles.
1759
+
1760
+ Returns
1761
+ =======
1762
+
1763
+ exterior_angle : number
1764
+
1765
+ See Also
1766
+ ========
1767
+
1768
+ sympy.geometry.line.LinearEntity.angle_between
1769
+
1770
+ Examples
1771
+ ========
1772
+
1773
+ >>> from sympy import RegularPolygon, Point
1774
+ >>> rp = RegularPolygon(Point(0, 0), 4, 8)
1775
+ >>> rp.exterior_angle
1776
+ pi/4
1777
+
1778
+ """
1779
+ return 2*S.Pi/self._n
1780
+
1781
+ @property
1782
+ def circumcircle(self):
1783
+ """The circumcircle of the RegularPolygon.
1784
+
1785
+ Returns
1786
+ =======
1787
+
1788
+ circumcircle : Circle
1789
+
1790
+ See Also
1791
+ ========
1792
+
1793
+ circumcenter, sympy.geometry.ellipse.Circle
1794
+
1795
+ Examples
1796
+ ========
1797
+
1798
+ >>> from sympy import RegularPolygon, Point
1799
+ >>> rp = RegularPolygon(Point(0, 0), 4, 8)
1800
+ >>> rp.circumcircle
1801
+ Circle(Point2D(0, 0), 4)
1802
+
1803
+ """
1804
+ return Circle(self.center, self.radius)
1805
+
1806
+ @property
1807
+ def incircle(self):
1808
+ """The incircle of the RegularPolygon.
1809
+
1810
+ Returns
1811
+ =======
1812
+
1813
+ incircle : Circle
1814
+
1815
+ See Also
1816
+ ========
1817
+
1818
+ inradius, sympy.geometry.ellipse.Circle
1819
+
1820
+ Examples
1821
+ ========
1822
+
1823
+ >>> from sympy import RegularPolygon, Point
1824
+ >>> rp = RegularPolygon(Point(0, 0), 4, 7)
1825
+ >>> rp.incircle
1826
+ Circle(Point2D(0, 0), 4*cos(pi/7))
1827
+
1828
+ """
1829
+ return Circle(self.center, self.apothem)
1830
+
1831
+ @property
1832
+ def angles(self):
1833
+ """
1834
+ Returns a dictionary with keys, the vertices of the Polygon,
1835
+ and values, the interior angle at each vertex.
1836
+
1837
+ Examples
1838
+ ========
1839
+
1840
+ >>> from sympy import RegularPolygon, Point
1841
+ >>> r = RegularPolygon(Point(0, 0), 5, 3)
1842
+ >>> r.angles
1843
+ {Point2D(-5/2, -5*sqrt(3)/2): pi/3,
1844
+ Point2D(-5/2, 5*sqrt(3)/2): pi/3,
1845
+ Point2D(5, 0): pi/3}
1846
+ """
1847
+ ret = {}
1848
+ ang = self.interior_angle
1849
+ for v in self.vertices:
1850
+ ret[v] = ang
1851
+ return ret
1852
+
1853
+ def encloses_point(self, p):
1854
+ """
1855
+ Return True if p is enclosed by (is inside of) self.
1856
+
1857
+ Notes
1858
+ =====
1859
+
1860
+ Being on the border of self is considered False.
1861
+
1862
+ The general Polygon.encloses_point method is called only if
1863
+ a point is not within or beyond the incircle or circumcircle,
1864
+ respectively.
1865
+
1866
+ Parameters
1867
+ ==========
1868
+
1869
+ p : Point
1870
+
1871
+ Returns
1872
+ =======
1873
+
1874
+ encloses_point : True, False or None
1875
+
1876
+ See Also
1877
+ ========
1878
+
1879
+ sympy.geometry.ellipse.Ellipse.encloses_point
1880
+
1881
+ Examples
1882
+ ========
1883
+
1884
+ >>> from sympy import RegularPolygon, S, Point, Symbol
1885
+ >>> p = RegularPolygon((0, 0), 3, 4)
1886
+ >>> p.encloses_point(Point(0, 0))
1887
+ True
1888
+ >>> r, R = p.inradius, p.circumradius
1889
+ >>> p.encloses_point(Point((r + R)/2, 0))
1890
+ True
1891
+ >>> p.encloses_point(Point(R/2, R/2 + (R - r)/10))
1892
+ False
1893
+ >>> t = Symbol('t', real=True)
1894
+ >>> p.encloses_point(p.arbitrary_point().subs(t, S.Half))
1895
+ False
1896
+ >>> p.encloses_point(Point(5, 5))
1897
+ False
1898
+
1899
+ """
1900
+
1901
+ c = self.center
1902
+ d = Segment(c, p).length
1903
+ if d >= self.radius:
1904
+ return False
1905
+ elif d < self.inradius:
1906
+ return True
1907
+ else:
1908
+ # now enumerate the RegularPolygon like a general polygon.
1909
+ return Polygon.encloses_point(self, p)
1910
+
1911
+ def spin(self, angle):
1912
+ """Increment *in place* the virtual Polygon's rotation by ccw angle.
1913
+
1914
+ See also: rotate method which moves the center.
1915
+
1916
+ >>> from sympy import Polygon, Point, pi
1917
+ >>> r = Polygon(Point(0,0), 1, n=3)
1918
+ >>> r.vertices[0]
1919
+ Point2D(1, 0)
1920
+ >>> r.spin(pi/6)
1921
+ >>> r.vertices[0]
1922
+ Point2D(sqrt(3)/2, 1/2)
1923
+
1924
+ See Also
1925
+ ========
1926
+
1927
+ rotation
1928
+ rotate : Creates a copy of the RegularPolygon rotated about a Point
1929
+
1930
+ """
1931
+ self._rot += angle
1932
+
1933
+ def rotate(self, angle, pt=None):
1934
+ """Override GeometryEntity.rotate to first rotate the RegularPolygon
1935
+ about its center.
1936
+
1937
+ >>> from sympy import Point, RegularPolygon, pi
1938
+ >>> t = RegularPolygon(Point(1, 0), 1, 3)
1939
+ >>> t.vertices[0] # vertex on x-axis
1940
+ Point2D(2, 0)
1941
+ >>> t.rotate(pi/2).vertices[0] # vertex on y axis now
1942
+ Point2D(0, 2)
1943
+
1944
+ See Also
1945
+ ========
1946
+
1947
+ rotation
1948
+ spin : Rotates a RegularPolygon in place
1949
+
1950
+ """
1951
+
1952
+ r = type(self)(*self.args) # need a copy or else changes are in-place
1953
+ r._rot += angle
1954
+ return GeometryEntity.rotate(r, angle, pt)
1955
+
1956
+ def scale(self, x=1, y=1, pt=None):
1957
+ """Override GeometryEntity.scale since it is the radius that must be
1958
+ scaled (if x == y) or else a new Polygon must be returned.
1959
+
1960
+ >>> from sympy import RegularPolygon
1961
+
1962
+ Symmetric scaling returns a RegularPolygon:
1963
+
1964
+ >>> RegularPolygon((0, 0), 1, 4).scale(2, 2)
1965
+ RegularPolygon(Point2D(0, 0), 2, 4, 0)
1966
+
1967
+ Asymmetric scaling returns a kite as a Polygon:
1968
+
1969
+ >>> RegularPolygon((0, 0), 1, 4).scale(2, 1)
1970
+ Polygon(Point2D(2, 0), Point2D(0, 1), Point2D(-2, 0), Point2D(0, -1))
1971
+
1972
+ """
1973
+ if pt:
1974
+ pt = Point(pt, dim=2)
1975
+ return self.translate(*(-pt).args).scale(x, y).translate(*pt.args)
1976
+ if x != y:
1977
+ return Polygon(*self.vertices).scale(x, y)
1978
+ c, r, n, rot = self.args
1979
+ r *= x
1980
+ return self.func(c, r, n, rot)
1981
+
1982
+ def reflect(self, line):
1983
+ """Override GeometryEntity.reflect since this is not made of only
1984
+ points.
1985
+
1986
+ Examples
1987
+ ========
1988
+
1989
+ >>> from sympy import RegularPolygon, Line
1990
+
1991
+ >>> RegularPolygon((0, 0), 1, 4).reflect(Line((0, 1), slope=-2))
1992
+ RegularPolygon(Point2D(4/5, 2/5), -1, 4, atan(4/3))
1993
+
1994
+ """
1995
+ c, r, n, rot = self.args
1996
+ v = self.vertices[0]
1997
+ d = v - c
1998
+ cc = c.reflect(line)
1999
+ vv = v.reflect(line)
2000
+ dd = vv - cc
2001
+ # calculate rotation about the new center
2002
+ # which will align the vertices
2003
+ l1 = Ray((0, 0), dd)
2004
+ l2 = Ray((0, 0), d)
2005
+ ang = l1.closing_angle(l2)
2006
+ rot += ang
2007
+ # change sign of radius as point traversal is reversed
2008
+ return self.func(cc, -r, n, rot)
2009
+
2010
+ @property
2011
+ def vertices(self):
2012
+ """The vertices of the RegularPolygon.
2013
+
2014
+ Returns
2015
+ =======
2016
+
2017
+ vertices : list
2018
+ Each vertex is a Point.
2019
+
2020
+ See Also
2021
+ ========
2022
+
2023
+ sympy.geometry.point.Point
2024
+
2025
+ Examples
2026
+ ========
2027
+
2028
+ >>> from sympy import RegularPolygon, Point
2029
+ >>> rp = RegularPolygon(Point(0, 0), 5, 4)
2030
+ >>> rp.vertices
2031
+ [Point2D(5, 0), Point2D(0, 5), Point2D(-5, 0), Point2D(0, -5)]
2032
+
2033
+ """
2034
+ c = self._center
2035
+ r = abs(self._radius)
2036
+ rot = self._rot
2037
+ v = 2*S.Pi/self._n
2038
+
2039
+ return [Point(c.x + r*cos(k*v + rot), c.y + r*sin(k*v + rot))
2040
+ for k in range(self._n)]
2041
+
2042
+ def __eq__(self, o):
2043
+ if not isinstance(o, Polygon):
2044
+ return False
2045
+ elif not isinstance(o, RegularPolygon):
2046
+ return Polygon.__eq__(o, self)
2047
+ return self.args == o.args
2048
+
2049
+ def __hash__(self):
2050
+ return super().__hash__()
2051
+
2052
+
2053
+ class Triangle(Polygon):
2054
+ """
2055
+ A polygon with three vertices and three sides.
2056
+
2057
+ Parameters
2058
+ ==========
2059
+
2060
+ points : sequence of Points
2061
+ keyword: asa, sas, or sss to specify sides/angles of the triangle
2062
+
2063
+ Attributes
2064
+ ==========
2065
+
2066
+ vertices
2067
+ altitudes
2068
+ orthocenter
2069
+ circumcenter
2070
+ circumradius
2071
+ circumcircle
2072
+ inradius
2073
+ incircle
2074
+ exradii
2075
+ medians
2076
+ medial
2077
+ nine_point_circle
2078
+
2079
+ Raises
2080
+ ======
2081
+
2082
+ GeometryError
2083
+ If the number of vertices is not equal to three, or one of the vertices
2084
+ is not a Point, or a valid keyword is not given.
2085
+
2086
+ See Also
2087
+ ========
2088
+
2089
+ sympy.geometry.point.Point, Polygon
2090
+
2091
+ Examples
2092
+ ========
2093
+
2094
+ >>> from sympy import Triangle, Point
2095
+ >>> Triangle(Point(0, 0), Point(4, 0), Point(4, 3))
2096
+ Triangle(Point2D(0, 0), Point2D(4, 0), Point2D(4, 3))
2097
+
2098
+ Keywords sss, sas, or asa can be used to give the desired
2099
+ side lengths (in order) and interior angles (in degrees) that
2100
+ define the triangle:
2101
+
2102
+ >>> Triangle(sss=(3, 4, 5))
2103
+ Triangle(Point2D(0, 0), Point2D(3, 0), Point2D(3, 4))
2104
+ >>> Triangle(asa=(30, 1, 30))
2105
+ Triangle(Point2D(0, 0), Point2D(1, 0), Point2D(1/2, sqrt(3)/6))
2106
+ >>> Triangle(sas=(1, 45, 2))
2107
+ Triangle(Point2D(0, 0), Point2D(2, 0), Point2D(sqrt(2)/2, sqrt(2)/2))
2108
+
2109
+ """
2110
+
2111
+ def __new__(cls, *args, **kwargs):
2112
+ if len(args) != 3:
2113
+ if 'sss' in kwargs:
2114
+ return _sss(*[simplify(a) for a in kwargs['sss']])
2115
+ if 'asa' in kwargs:
2116
+ return _asa(*[simplify(a) for a in kwargs['asa']])
2117
+ if 'sas' in kwargs:
2118
+ return _sas(*[simplify(a) for a in kwargs['sas']])
2119
+ msg = "Triangle instantiates with three points or a valid keyword."
2120
+ raise GeometryError(msg)
2121
+
2122
+ vertices = [Point(a, dim=2, **kwargs) for a in args]
2123
+
2124
+ # remove consecutive duplicates
2125
+ nodup = []
2126
+ for p in vertices:
2127
+ if nodup and p == nodup[-1]:
2128
+ continue
2129
+ nodup.append(p)
2130
+ if len(nodup) > 1 and nodup[-1] == nodup[0]:
2131
+ nodup.pop() # last point was same as first
2132
+
2133
+ # remove collinear points
2134
+ i = -3
2135
+ while i < len(nodup) - 3 and len(nodup) > 2:
2136
+ a, b, c = sorted(
2137
+ [nodup[i], nodup[i + 1], nodup[i + 2]], key=default_sort_key)
2138
+ if Point.is_collinear(a, b, c):
2139
+ nodup[i] = a
2140
+ nodup[i + 1] = None
2141
+ nodup.pop(i + 1)
2142
+ i += 1
2143
+
2144
+ vertices = list(filter(lambda x: x is not None, nodup))
2145
+
2146
+ if len(vertices) == 3:
2147
+ return GeometryEntity.__new__(cls, *vertices, **kwargs)
2148
+ elif len(vertices) == 2:
2149
+ return Segment(*vertices, **kwargs)
2150
+ else:
2151
+ return Point(*vertices, **kwargs)
2152
+
2153
+ @property
2154
+ def vertices(self):
2155
+ """The triangle's vertices
2156
+
2157
+ Returns
2158
+ =======
2159
+
2160
+ vertices : tuple
2161
+ Each element in the tuple is a Point
2162
+
2163
+ See Also
2164
+ ========
2165
+
2166
+ sympy.geometry.point.Point
2167
+
2168
+ Examples
2169
+ ========
2170
+
2171
+ >>> from sympy import Triangle, Point
2172
+ >>> t = Triangle(Point(0, 0), Point(4, 0), Point(4, 3))
2173
+ >>> t.vertices
2174
+ (Point2D(0, 0), Point2D(4, 0), Point2D(4, 3))
2175
+
2176
+ """
2177
+ return self.args
2178
+
2179
+ def is_similar(t1, t2):
2180
+ """Is another triangle similar to this one.
2181
+
2182
+ Two triangles are similar if one can be uniformly scaled to the other.
2183
+
2184
+ Parameters
2185
+ ==========
2186
+
2187
+ other: Triangle
2188
+
2189
+ Returns
2190
+ =======
2191
+
2192
+ is_similar : boolean
2193
+
2194
+ See Also
2195
+ ========
2196
+
2197
+ sympy.geometry.entity.GeometryEntity.is_similar
2198
+
2199
+ Examples
2200
+ ========
2201
+
2202
+ >>> from sympy import Triangle, Point
2203
+ >>> t1 = Triangle(Point(0, 0), Point(4, 0), Point(4, 3))
2204
+ >>> t2 = Triangle(Point(0, 0), Point(-4, 0), Point(-4, -3))
2205
+ >>> t1.is_similar(t2)
2206
+ True
2207
+
2208
+ >>> t2 = Triangle(Point(0, 0), Point(-4, 0), Point(-4, -4))
2209
+ >>> t1.is_similar(t2)
2210
+ False
2211
+
2212
+ """
2213
+ if not isinstance(t2, Polygon):
2214
+ return False
2215
+
2216
+ s1_1, s1_2, s1_3 = [side.length for side in t1.sides]
2217
+ s2 = [side.length for side in t2.sides]
2218
+
2219
+ def _are_similar(u1, u2, u3, v1, v2, v3):
2220
+ e1 = simplify(u1/v1)
2221
+ e2 = simplify(u2/v2)
2222
+ e3 = simplify(u3/v3)
2223
+ return bool(e1 == e2) and bool(e2 == e3)
2224
+
2225
+ # There's only 6 permutations, so write them out
2226
+ return _are_similar(s1_1, s1_2, s1_3, *s2) or \
2227
+ _are_similar(s1_1, s1_3, s1_2, *s2) or \
2228
+ _are_similar(s1_2, s1_1, s1_3, *s2) or \
2229
+ _are_similar(s1_2, s1_3, s1_1, *s2) or \
2230
+ _are_similar(s1_3, s1_1, s1_2, *s2) or \
2231
+ _are_similar(s1_3, s1_2, s1_1, *s2)
2232
+
2233
+ def is_equilateral(self):
2234
+ """Are all the sides the same length?
2235
+
2236
+ Returns
2237
+ =======
2238
+
2239
+ is_equilateral : boolean
2240
+
2241
+ See Also
2242
+ ========
2243
+
2244
+ sympy.geometry.entity.GeometryEntity.is_similar, RegularPolygon
2245
+ is_isosceles, is_right, is_scalene
2246
+
2247
+ Examples
2248
+ ========
2249
+
2250
+ >>> from sympy import Triangle, Point
2251
+ >>> t1 = Triangle(Point(0, 0), Point(4, 0), Point(4, 3))
2252
+ >>> t1.is_equilateral()
2253
+ False
2254
+
2255
+ >>> from sympy import sqrt
2256
+ >>> t2 = Triangle(Point(0, 0), Point(10, 0), Point(5, 5*sqrt(3)))
2257
+ >>> t2.is_equilateral()
2258
+ True
2259
+
2260
+ """
2261
+ return not has_variety(s.length for s in self.sides)
2262
+
2263
+ def is_isosceles(self):
2264
+ """Are two or more of the sides the same length?
2265
+
2266
+ Returns
2267
+ =======
2268
+
2269
+ is_isosceles : boolean
2270
+
2271
+ See Also
2272
+ ========
2273
+
2274
+ is_equilateral, is_right, is_scalene
2275
+
2276
+ Examples
2277
+ ========
2278
+
2279
+ >>> from sympy import Triangle, Point
2280
+ >>> t1 = Triangle(Point(0, 0), Point(4, 0), Point(2, 4))
2281
+ >>> t1.is_isosceles()
2282
+ True
2283
+
2284
+ """
2285
+ return has_dups(s.length for s in self.sides)
2286
+
2287
+ def is_scalene(self):
2288
+ """Are all the sides of the triangle of different lengths?
2289
+
2290
+ Returns
2291
+ =======
2292
+
2293
+ is_scalene : boolean
2294
+
2295
+ See Also
2296
+ ========
2297
+
2298
+ is_equilateral, is_isosceles, is_right
2299
+
2300
+ Examples
2301
+ ========
2302
+
2303
+ >>> from sympy import Triangle, Point
2304
+ >>> t1 = Triangle(Point(0, 0), Point(4, 0), Point(1, 4))
2305
+ >>> t1.is_scalene()
2306
+ True
2307
+
2308
+ """
2309
+ return not has_dups(s.length for s in self.sides)
2310
+
2311
+ def is_right(self):
2312
+ """Is the triangle right-angled.
2313
+
2314
+ Returns
2315
+ =======
2316
+
2317
+ is_right : boolean
2318
+
2319
+ See Also
2320
+ ========
2321
+
2322
+ sympy.geometry.line.LinearEntity.is_perpendicular
2323
+ is_equilateral, is_isosceles, is_scalene
2324
+
2325
+ Examples
2326
+ ========
2327
+
2328
+ >>> from sympy import Triangle, Point
2329
+ >>> t1 = Triangle(Point(0, 0), Point(4, 0), Point(4, 3))
2330
+ >>> t1.is_right()
2331
+ True
2332
+
2333
+ """
2334
+ s = self.sides
2335
+ return Segment.is_perpendicular(s[0], s[1]) or \
2336
+ Segment.is_perpendicular(s[1], s[2]) or \
2337
+ Segment.is_perpendicular(s[0], s[2])
2338
+
2339
+ @property
2340
+ def altitudes(self):
2341
+ """The altitudes of the triangle.
2342
+
2343
+ An altitude of a triangle is a segment through a vertex,
2344
+ perpendicular to the opposite side, with length being the
2345
+ height of the vertex measured from the line containing the side.
2346
+
2347
+ Returns
2348
+ =======
2349
+
2350
+ altitudes : dict
2351
+ The dictionary consists of keys which are vertices and values
2352
+ which are Segments.
2353
+
2354
+ See Also
2355
+ ========
2356
+
2357
+ sympy.geometry.point.Point, sympy.geometry.line.Segment.length
2358
+
2359
+ Examples
2360
+ ========
2361
+
2362
+ >>> from sympy import Point, Triangle
2363
+ >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1)
2364
+ >>> t = Triangle(p1, p2, p3)
2365
+ >>> t.altitudes[p1]
2366
+ Segment2D(Point2D(0, 0), Point2D(1/2, 1/2))
2367
+
2368
+ """
2369
+ s = self.sides
2370
+ v = self.vertices
2371
+ return {v[0]: s[1].perpendicular_segment(v[0]),
2372
+ v[1]: s[2].perpendicular_segment(v[1]),
2373
+ v[2]: s[0].perpendicular_segment(v[2])}
2374
+
2375
+ @property
2376
+ def orthocenter(self):
2377
+ """The orthocenter of the triangle.
2378
+
2379
+ The orthocenter is the intersection of the altitudes of a triangle.
2380
+ It may lie inside, outside or on the triangle.
2381
+
2382
+ Returns
2383
+ =======
2384
+
2385
+ orthocenter : Point
2386
+
2387
+ See Also
2388
+ ========
2389
+
2390
+ sympy.geometry.point.Point
2391
+
2392
+ Examples
2393
+ ========
2394
+
2395
+ >>> from sympy import Point, Triangle
2396
+ >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1)
2397
+ >>> t = Triangle(p1, p2, p3)
2398
+ >>> t.orthocenter
2399
+ Point2D(0, 0)
2400
+
2401
+ """
2402
+ a = self.altitudes
2403
+ v = self.vertices
2404
+ return Line(a[v[0]]).intersection(Line(a[v[1]]))[0]
2405
+
2406
+ @property
2407
+ def circumcenter(self):
2408
+ """The circumcenter of the triangle
2409
+
2410
+ The circumcenter is the center of the circumcircle.
2411
+
2412
+ Returns
2413
+ =======
2414
+
2415
+ circumcenter : Point
2416
+
2417
+ See Also
2418
+ ========
2419
+
2420
+ sympy.geometry.point.Point
2421
+
2422
+ Examples
2423
+ ========
2424
+
2425
+ >>> from sympy import Point, Triangle
2426
+ >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1)
2427
+ >>> t = Triangle(p1, p2, p3)
2428
+ >>> t.circumcenter
2429
+ Point2D(1/2, 1/2)
2430
+ """
2431
+ a, b, c = [x.perpendicular_bisector() for x in self.sides]
2432
+ return a.intersection(b)[0]
2433
+
2434
+ @property
2435
+ def circumradius(self):
2436
+ """The radius of the circumcircle of the triangle.
2437
+
2438
+ Returns
2439
+ =======
2440
+
2441
+ circumradius : number of Basic instance
2442
+
2443
+ See Also
2444
+ ========
2445
+
2446
+ sympy.geometry.ellipse.Circle.radius
2447
+
2448
+ Examples
2449
+ ========
2450
+
2451
+ >>> from sympy import Symbol
2452
+ >>> from sympy import Point, Triangle
2453
+ >>> a = Symbol('a')
2454
+ >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, a)
2455
+ >>> t = Triangle(p1, p2, p3)
2456
+ >>> t.circumradius
2457
+ sqrt(a**2/4 + 1/4)
2458
+ """
2459
+ return Point.distance(self.circumcenter, self.vertices[0])
2460
+
2461
+ @property
2462
+ def circumcircle(self):
2463
+ """The circle which passes through the three vertices of the triangle.
2464
+
2465
+ Returns
2466
+ =======
2467
+
2468
+ circumcircle : Circle
2469
+
2470
+ See Also
2471
+ ========
2472
+
2473
+ sympy.geometry.ellipse.Circle
2474
+
2475
+ Examples
2476
+ ========
2477
+
2478
+ >>> from sympy import Point, Triangle
2479
+ >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1)
2480
+ >>> t = Triangle(p1, p2, p3)
2481
+ >>> t.circumcircle
2482
+ Circle(Point2D(1/2, 1/2), sqrt(2)/2)
2483
+
2484
+ """
2485
+ return Circle(self.circumcenter, self.circumradius)
2486
+
2487
+ def bisectors(self):
2488
+ """The angle bisectors of the triangle.
2489
+
2490
+ An angle bisector of a triangle is a straight line through a vertex
2491
+ which cuts the corresponding angle in half.
2492
+
2493
+ Returns
2494
+ =======
2495
+
2496
+ bisectors : dict
2497
+ Each key is a vertex (Point) and each value is the corresponding
2498
+ bisector (Segment).
2499
+
2500
+ See Also
2501
+ ========
2502
+
2503
+ sympy.geometry.point.Point, sympy.geometry.line.Segment
2504
+
2505
+ Examples
2506
+ ========
2507
+
2508
+ >>> from sympy import Point, Triangle, Segment
2509
+ >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1)
2510
+ >>> t = Triangle(p1, p2, p3)
2511
+ >>> from sympy import sqrt
2512
+ >>> t.bisectors()[p2] == Segment(Point(1, 0), Point(0, sqrt(2) - 1))
2513
+ True
2514
+
2515
+ """
2516
+ # use lines containing sides so containment check during
2517
+ # intersection calculation can be avoided, thus reducing
2518
+ # the processing time for calculating the bisectors
2519
+ s = [Line(l) for l in self.sides]
2520
+ v = self.vertices
2521
+ c = self.incenter
2522
+ l1 = Segment(v[0], Line(v[0], c).intersection(s[1])[0])
2523
+ l2 = Segment(v[1], Line(v[1], c).intersection(s[2])[0])
2524
+ l3 = Segment(v[2], Line(v[2], c).intersection(s[0])[0])
2525
+ return {v[0]: l1, v[1]: l2, v[2]: l3}
2526
+
2527
+ @property
2528
+ def incenter(self):
2529
+ """The center of the incircle.
2530
+
2531
+ The incircle is the circle which lies inside the triangle and touches
2532
+ all three sides.
2533
+
2534
+ Returns
2535
+ =======
2536
+
2537
+ incenter : Point
2538
+
2539
+ See Also
2540
+ ========
2541
+
2542
+ incircle, sympy.geometry.point.Point
2543
+
2544
+ Examples
2545
+ ========
2546
+
2547
+ >>> from sympy import Point, Triangle
2548
+ >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1)
2549
+ >>> t = Triangle(p1, p2, p3)
2550
+ >>> t.incenter
2551
+ Point2D(1 - sqrt(2)/2, 1 - sqrt(2)/2)
2552
+
2553
+ """
2554
+ s = self.sides
2555
+ l = Matrix([s[i].length for i in [1, 2, 0]])
2556
+ p = sum(l)
2557
+ v = self.vertices
2558
+ x = simplify(l.dot(Matrix([vi.x for vi in v]))/p)
2559
+ y = simplify(l.dot(Matrix([vi.y for vi in v]))/p)
2560
+ return Point(x, y)
2561
+
2562
+ @property
2563
+ def inradius(self):
2564
+ """The radius of the incircle.
2565
+
2566
+ Returns
2567
+ =======
2568
+
2569
+ inradius : number of Basic instance
2570
+
2571
+ See Also
2572
+ ========
2573
+
2574
+ incircle, sympy.geometry.ellipse.Circle.radius
2575
+
2576
+ Examples
2577
+ ========
2578
+
2579
+ >>> from sympy import Point, Triangle
2580
+ >>> p1, p2, p3 = Point(0, 0), Point(4, 0), Point(0, 3)
2581
+ >>> t = Triangle(p1, p2, p3)
2582
+ >>> t.inradius
2583
+ 1
2584
+
2585
+ """
2586
+ return simplify(2 * self.area / self.perimeter)
2587
+
2588
+ @property
2589
+ def incircle(self):
2590
+ """The incircle of the triangle.
2591
+
2592
+ The incircle is the circle which lies inside the triangle and touches
2593
+ all three sides.
2594
+
2595
+ Returns
2596
+ =======
2597
+
2598
+ incircle : Circle
2599
+
2600
+ See Also
2601
+ ========
2602
+
2603
+ sympy.geometry.ellipse.Circle
2604
+
2605
+ Examples
2606
+ ========
2607
+
2608
+ >>> from sympy import Point, Triangle
2609
+ >>> p1, p2, p3 = Point(0, 0), Point(2, 0), Point(0, 2)
2610
+ >>> t = Triangle(p1, p2, p3)
2611
+ >>> t.incircle
2612
+ Circle(Point2D(2 - sqrt(2), 2 - sqrt(2)), 2 - sqrt(2))
2613
+
2614
+ """
2615
+ return Circle(self.incenter, self.inradius)
2616
+
2617
+ @property
2618
+ def exradii(self):
2619
+ """The radius of excircles of a triangle.
2620
+
2621
+ An excircle of the triangle is a circle lying outside the triangle,
2622
+ tangent to one of its sides and tangent to the extensions of the
2623
+ other two.
2624
+
2625
+ Returns
2626
+ =======
2627
+
2628
+ exradii : dict
2629
+
2630
+ See Also
2631
+ ========
2632
+
2633
+ sympy.geometry.polygon.Triangle.inradius
2634
+
2635
+ Examples
2636
+ ========
2637
+
2638
+ The exradius touches the side of the triangle to which it is keyed, e.g.
2639
+ the exradius touching side 2 is:
2640
+
2641
+ >>> from sympy import Point, Triangle
2642
+ >>> p1, p2, p3 = Point(0, 0), Point(6, 0), Point(0, 2)
2643
+ >>> t = Triangle(p1, p2, p3)
2644
+ >>> t.exradii[t.sides[2]]
2645
+ -2 + sqrt(10)
2646
+
2647
+ References
2648
+ ==========
2649
+
2650
+ .. [1] https://mathworld.wolfram.com/Exradius.html
2651
+ .. [2] https://mathworld.wolfram.com/Excircles.html
2652
+
2653
+ """
2654
+
2655
+ side = self.sides
2656
+ a = side[0].length
2657
+ b = side[1].length
2658
+ c = side[2].length
2659
+ s = (a+b+c)/2
2660
+ area = self.area
2661
+ exradii = {self.sides[0]: simplify(area/(s-a)),
2662
+ self.sides[1]: simplify(area/(s-b)),
2663
+ self.sides[2]: simplify(area/(s-c))}
2664
+
2665
+ return exradii
2666
+
2667
+ @property
2668
+ def excenters(self):
2669
+ """Excenters of the triangle.
2670
+
2671
+ An excenter is the center of a circle that is tangent to a side of the
2672
+ triangle and the extensions of the other two sides.
2673
+
2674
+ Returns
2675
+ =======
2676
+
2677
+ excenters : dict
2678
+
2679
+
2680
+ Examples
2681
+ ========
2682
+
2683
+ The excenters are keyed to the side of the triangle to which their corresponding
2684
+ excircle is tangent: The center is keyed, e.g. the excenter of a circle touching
2685
+ side 0 is:
2686
+
2687
+ >>> from sympy import Point, Triangle
2688
+ >>> p1, p2, p3 = Point(0, 0), Point(6, 0), Point(0, 2)
2689
+ >>> t = Triangle(p1, p2, p3)
2690
+ >>> t.excenters[t.sides[0]]
2691
+ Point2D(12*sqrt(10), 2/3 + sqrt(10)/3)
2692
+
2693
+ See Also
2694
+ ========
2695
+
2696
+ sympy.geometry.polygon.Triangle.exradii
2697
+
2698
+ References
2699
+ ==========
2700
+
2701
+ .. [1] https://mathworld.wolfram.com/Excircles.html
2702
+
2703
+ """
2704
+
2705
+ s = self.sides
2706
+ v = self.vertices
2707
+ a = s[0].length
2708
+ b = s[1].length
2709
+ c = s[2].length
2710
+ x = [v[0].x, v[1].x, v[2].x]
2711
+ y = [v[0].y, v[1].y, v[2].y]
2712
+
2713
+ exc_coords = {
2714
+ "x1": simplify(-a*x[0]+b*x[1]+c*x[2]/(-a+b+c)),
2715
+ "x2": simplify(a*x[0]-b*x[1]+c*x[2]/(a-b+c)),
2716
+ "x3": simplify(a*x[0]+b*x[1]-c*x[2]/(a+b-c)),
2717
+ "y1": simplify(-a*y[0]+b*y[1]+c*y[2]/(-a+b+c)),
2718
+ "y2": simplify(a*y[0]-b*y[1]+c*y[2]/(a-b+c)),
2719
+ "y3": simplify(a*y[0]+b*y[1]-c*y[2]/(a+b-c))
2720
+ }
2721
+
2722
+ excenters = {
2723
+ s[0]: Point(exc_coords["x1"], exc_coords["y1"]),
2724
+ s[1]: Point(exc_coords["x2"], exc_coords["y2"]),
2725
+ s[2]: Point(exc_coords["x3"], exc_coords["y3"])
2726
+ }
2727
+
2728
+ return excenters
2729
+
2730
+ @property
2731
+ def medians(self):
2732
+ """The medians of the triangle.
2733
+
2734
+ A median of a triangle is a straight line through a vertex and the
2735
+ midpoint of the opposite side, and divides the triangle into two
2736
+ equal areas.
2737
+
2738
+ Returns
2739
+ =======
2740
+
2741
+ medians : dict
2742
+ Each key is a vertex (Point) and each value is the median (Segment)
2743
+ at that point.
2744
+
2745
+ See Also
2746
+ ========
2747
+
2748
+ sympy.geometry.point.Point.midpoint, sympy.geometry.line.Segment.midpoint
2749
+
2750
+ Examples
2751
+ ========
2752
+
2753
+ >>> from sympy import Point, Triangle
2754
+ >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1)
2755
+ >>> t = Triangle(p1, p2, p3)
2756
+ >>> t.medians[p1]
2757
+ Segment2D(Point2D(0, 0), Point2D(1/2, 1/2))
2758
+
2759
+ """
2760
+ s = self.sides
2761
+ v = self.vertices
2762
+ return {v[0]: Segment(v[0], s[1].midpoint),
2763
+ v[1]: Segment(v[1], s[2].midpoint),
2764
+ v[2]: Segment(v[2], s[0].midpoint)}
2765
+
2766
+ @property
2767
+ def medial(self):
2768
+ """The medial triangle of the triangle.
2769
+
2770
+ The triangle which is formed from the midpoints of the three sides.
2771
+
2772
+ Returns
2773
+ =======
2774
+
2775
+ medial : Triangle
2776
+
2777
+ See Also
2778
+ ========
2779
+
2780
+ sympy.geometry.line.Segment.midpoint
2781
+
2782
+ Examples
2783
+ ========
2784
+
2785
+ >>> from sympy import Point, Triangle
2786
+ >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1)
2787
+ >>> t = Triangle(p1, p2, p3)
2788
+ >>> t.medial
2789
+ Triangle(Point2D(1/2, 0), Point2D(1/2, 1/2), Point2D(0, 1/2))
2790
+
2791
+ """
2792
+ s = self.sides
2793
+ return Triangle(s[0].midpoint, s[1].midpoint, s[2].midpoint)
2794
+
2795
+ @property
2796
+ def nine_point_circle(self):
2797
+ """The nine-point circle of the triangle.
2798
+
2799
+ Nine-point circle is the circumcircle of the medial triangle, which
2800
+ passes through the feet of altitudes and the middle points of segments
2801
+ connecting the vertices and the orthocenter.
2802
+
2803
+ Returns
2804
+ =======
2805
+
2806
+ nine_point_circle : Circle
2807
+
2808
+ See also
2809
+ ========
2810
+
2811
+ sympy.geometry.line.Segment.midpoint
2812
+ sympy.geometry.polygon.Triangle.medial
2813
+ sympy.geometry.polygon.Triangle.orthocenter
2814
+
2815
+ Examples
2816
+ ========
2817
+
2818
+ >>> from sympy import Point, Triangle
2819
+ >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1)
2820
+ >>> t = Triangle(p1, p2, p3)
2821
+ >>> t.nine_point_circle
2822
+ Circle(Point2D(1/4, 1/4), sqrt(2)/4)
2823
+
2824
+ """
2825
+ return Circle(*self.medial.vertices)
2826
+
2827
+ @property
2828
+ def eulerline(self):
2829
+ """The Euler line of the triangle.
2830
+
2831
+ The line which passes through circumcenter, centroid and orthocenter.
2832
+
2833
+ Returns
2834
+ =======
2835
+
2836
+ eulerline : Line (or Point for equilateral triangles in which case all
2837
+ centers coincide)
2838
+
2839
+ Examples
2840
+ ========
2841
+
2842
+ >>> from sympy import Point, Triangle
2843
+ >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1)
2844
+ >>> t = Triangle(p1, p2, p3)
2845
+ >>> t.eulerline
2846
+ Line2D(Point2D(0, 0), Point2D(1/2, 1/2))
2847
+
2848
+ """
2849
+ if self.is_equilateral():
2850
+ return self.orthocenter
2851
+ return Line(self.orthocenter, self.circumcenter)
2852
+
2853
+ def rad(d):
2854
+ """Return the radian value for the given degrees (pi = 180 degrees)."""
2855
+ return d*pi/180
2856
+
2857
+
2858
+ def deg(r):
2859
+ """Return the degree value for the given radians (pi = 180 degrees)."""
2860
+ return r/pi*180
2861
+
2862
+
2863
+ def _slope(d):
2864
+ rv = tan(rad(d))
2865
+ return rv
2866
+
2867
+
2868
+ def _asa(d1, l, d2):
2869
+ """Return triangle having side with length l on the x-axis."""
2870
+ xy = Line((0, 0), slope=_slope(d1)).intersection(
2871
+ Line((l, 0), slope=_slope(180 - d2)))[0]
2872
+ return Triangle((0, 0), (l, 0), xy)
2873
+
2874
+
2875
+ def _sss(l1, l2, l3):
2876
+ """Return triangle having side of length l1 on the x-axis."""
2877
+ c1 = Circle((0, 0), l3)
2878
+ c2 = Circle((l1, 0), l2)
2879
+ inter = [a for a in c1.intersection(c2) if a.y.is_nonnegative]
2880
+ if not inter:
2881
+ return None
2882
+ pt = inter[0]
2883
+ return Triangle((0, 0), (l1, 0), pt)
2884
+
2885
+
2886
+ def _sas(l1, d, l2):
2887
+ """Return triangle having side with length l2 on the x-axis."""
2888
+ p1 = Point(0, 0)
2889
+ p2 = Point(l2, 0)
2890
+ p3 = Point(cos(rad(d))*l1, sin(rad(d))*l1)
2891
+ return Triangle(p1, p2, p3)
janus/lib/python3.10/site-packages/sympy/geometry/tests/__init__.py ADDED
File without changes
janus/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/test_geometrysets.cpython-310.pyc ADDED
Binary file (1.6 kB). View file
 
janus/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/test_plane.cpython-310.pyc ADDED
Binary file (9.56 kB). View file
 
janus/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/test_point.cpython-310.pyc ADDED
Binary file (15.7 kB). View file
 
janus/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/test_util.cpython-310.pyc ADDED
Binary file (7.04 kB). View file
 
janus/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)
janus/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))
janus/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)))
janus/lib/python3.10/site-packages/sympy/geometry/tests/test_polygon.py ADDED
@@ -0,0 +1,676 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import (Float, Rational, oo, pi)
2
+ from sympy.core.singleton import S
3
+ from sympy.core.symbol import (Symbol, symbols)
4
+ from sympy.functions.elementary.complexes import Abs
5
+ from sympy.functions.elementary.miscellaneous import sqrt
6
+ from sympy.functions.elementary.trigonometric import (acos, cos, sin)
7
+ from sympy.functions.elementary.trigonometric import tan
8
+ from sympy.geometry import (Circle, Ellipse, GeometryError, Point, Point2D,
9
+ Polygon, Ray, RegularPolygon, Segment, Triangle,
10
+ are_similar, convex_hull, intersection, Line, Ray2D)
11
+ from sympy.testing.pytest import raises, slow, warns
12
+ from sympy.core.random import verify_numerically
13
+ from sympy.geometry.polygon import rad, deg
14
+ from sympy.integrals.integrals import integrate
15
+ from sympy.utilities.iterables import rotate_left
16
+
17
+
18
+ def feq(a, b):
19
+ """Test if two floating point values are 'equal'."""
20
+ t_float = Float("1.0E-10")
21
+ return -t_float < a - b < t_float
22
+
23
+ @slow
24
+ def test_polygon():
25
+ x = Symbol('x', real=True)
26
+ y = Symbol('y', real=True)
27
+ q = Symbol('q', real=True)
28
+ u = Symbol('u', real=True)
29
+ v = Symbol('v', real=True)
30
+ w = Symbol('w', real=True)
31
+ x1 = Symbol('x1', real=True)
32
+ half = S.Half
33
+ a, b, c = Point(0, 0), Point(2, 0), Point(3, 3)
34
+ t = Triangle(a, b, c)
35
+ assert Polygon(Point(0, 0)) == Point(0, 0)
36
+ assert Polygon(a, Point(1, 0), b, c) == t
37
+ assert Polygon(Point(1, 0), b, c, a) == t
38
+ assert Polygon(b, c, a, Point(1, 0)) == t
39
+ # 2 "remove folded" tests
40
+ assert Polygon(a, Point(3, 0), b, c) == t
41
+ assert Polygon(a, b, Point(3, -1), b, c) == t
42
+ # remove multiple collinear points
43
+ assert Polygon(Point(-4, 15), Point(-11, 15), Point(-15, 15),
44
+ Point(-15, 33/5), Point(-15, -87/10), Point(-15, -15),
45
+ Point(-42/5, -15), Point(-2, -15), Point(7, -15), Point(15, -15),
46
+ Point(15, -3), Point(15, 10), Point(15, 15)) == \
47
+ Polygon(Point(-15, -15), Point(15, -15), Point(15, 15), Point(-15, 15))
48
+
49
+ p1 = Polygon(
50
+ Point(0, 0), Point(3, -1),
51
+ Point(6, 0), Point(4, 5),
52
+ Point(2, 3), Point(0, 3))
53
+ p2 = Polygon(
54
+ Point(6, 0), Point(3, -1),
55
+ Point(0, 0), Point(0, 3),
56
+ Point(2, 3), Point(4, 5))
57
+ p3 = Polygon(
58
+ Point(0, 0), Point(3, 0),
59
+ Point(5, 2), Point(4, 4))
60
+ p4 = Polygon(
61
+ Point(0, 0), Point(4, 4),
62
+ Point(5, 2), Point(3, 0))
63
+ p5 = Polygon(
64
+ Point(0, 0), Point(4, 4),
65
+ Point(0, 4))
66
+ p6 = Polygon(
67
+ Point(-11, 1), Point(-9, 6.6),
68
+ Point(-4, -3), Point(-8.4, -8.7))
69
+ p7 = Polygon(
70
+ Point(x, y), Point(q, u),
71
+ Point(v, w))
72
+ p8 = Polygon(
73
+ Point(x, y), Point(v, w),
74
+ Point(q, u))
75
+ p9 = Polygon(
76
+ Point(0, 0), Point(4, 4),
77
+ Point(3, 0), Point(5, 2))
78
+ p10 = Polygon(
79
+ Point(0, 2), Point(2, 2),
80
+ Point(0, 0), Point(2, 0))
81
+ p11 = Polygon(Point(0, 0), 1, n=3)
82
+ p12 = Polygon(Point(0, 0), 1, 0, n=3)
83
+ p13 = Polygon(
84
+ Point(0, 0),Point(8, 8),
85
+ Point(23, 20),Point(0, 20))
86
+ p14 = Polygon(*rotate_left(p13.args, 1))
87
+
88
+
89
+ r = Ray(Point(-9, 6.6), Point(-9, 5.5))
90
+ #
91
+ # General polygon
92
+ #
93
+ assert p1 == p2
94
+ assert len(p1.args) == 6
95
+ assert len(p1.sides) == 6
96
+ assert p1.perimeter == 5 + 2*sqrt(10) + sqrt(29) + sqrt(8)
97
+ assert p1.area == 22
98
+ assert not p1.is_convex()
99
+ assert Polygon((-1, 1), (2, -1), (2, 1), (-1, -1), (3, 0)
100
+ ).is_convex() is False
101
+ # ensure convex for both CW and CCW point specification
102
+ assert p3.is_convex()
103
+ assert p4.is_convex()
104
+ dict5 = p5.angles
105
+ assert dict5[Point(0, 0)] == pi / 4
106
+ assert dict5[Point(0, 4)] == pi / 2
107
+ assert p5.encloses_point(Point(x, y)) is None
108
+ assert p5.encloses_point(Point(1, 3))
109
+ assert p5.encloses_point(Point(0, 0)) is False
110
+ assert p5.encloses_point(Point(4, 0)) is False
111
+ assert p1.encloses(Circle(Point(2.5, 2.5), 5)) is False
112
+ assert p1.encloses(Ellipse(Point(2.5, 2), 5, 6)) is False
113
+ assert p5.plot_interval('x') == [x, 0, 1]
114
+ assert p5.distance(
115
+ Polygon(Point(10, 10), Point(14, 14), Point(10, 14))) == 6 * sqrt(2)
116
+ assert p5.distance(
117
+ Polygon(Point(1, 8), Point(5, 8), Point(8, 12), Point(1, 12))) == 4
118
+ with warns(UserWarning, \
119
+ match="Polygons may intersect producing erroneous output"):
120
+ Polygon(Point(0, 0), Point(1, 0), Point(1, 1)).distance(
121
+ Polygon(Point(0, 0), Point(0, 1), Point(1, 1)))
122
+ assert hash(p5) == hash(Polygon(Point(0, 0), Point(4, 4), Point(0, 4)))
123
+ assert hash(p1) == hash(p2)
124
+ assert hash(p7) == hash(p8)
125
+ assert hash(p3) != hash(p9)
126
+ assert p5 == Polygon(Point(4, 4), Point(0, 4), Point(0, 0))
127
+ assert Polygon(Point(4, 4), Point(0, 4), Point(0, 0)) in p5
128
+ assert p5 != Point(0, 4)
129
+ assert Point(0, 1) in p5
130
+ assert p5.arbitrary_point('t').subs(Symbol('t', real=True), 0) == \
131
+ Point(0, 0)
132
+ raises(ValueError, lambda: Polygon(
133
+ Point(x, 0), Point(0, y), Point(x, y)).arbitrary_point('x'))
134
+ assert p6.intersection(r) == [Point(-9, Rational(-84, 13)), Point(-9, Rational(33, 5))]
135
+ assert p10.area == 0
136
+ assert p11 == RegularPolygon(Point(0, 0), 1, 3, 0)
137
+ assert p11 == p12
138
+ assert p11.vertices[0] == Point(1, 0)
139
+ assert p11.args[0] == Point(0, 0)
140
+ p11.spin(pi/2)
141
+ assert p11.vertices[0] == Point(0, 1)
142
+ #
143
+ # Regular polygon
144
+ #
145
+ p1 = RegularPolygon(Point(0, 0), 10, 5)
146
+ p2 = RegularPolygon(Point(0, 0), 5, 5)
147
+ raises(GeometryError, lambda: RegularPolygon(Point(0, 0), Point(0,
148
+ 1), Point(1, 1)))
149
+ raises(GeometryError, lambda: RegularPolygon(Point(0, 0), 1, 2))
150
+ raises(ValueError, lambda: RegularPolygon(Point(0, 0), 1, 2.5))
151
+
152
+ assert p1 != p2
153
+ assert p1.interior_angle == pi*Rational(3, 5)
154
+ assert p1.exterior_angle == pi*Rational(2, 5)
155
+ assert p2.apothem == 5*cos(pi/5)
156
+ assert p2.circumcenter == p1.circumcenter == Point(0, 0)
157
+ assert p1.circumradius == p1.radius == 10
158
+ assert p2.circumcircle == Circle(Point(0, 0), 5)
159
+ assert p2.incircle == Circle(Point(0, 0), p2.apothem)
160
+ assert p2.inradius == p2.apothem == (5 * (1 + sqrt(5)) / 4)
161
+ p2.spin(pi / 10)
162
+ dict1 = p2.angles
163
+ assert dict1[Point(0, 5)] == 3 * pi / 5
164
+ assert p1.is_convex()
165
+ assert p1.rotation == 0
166
+ assert p1.encloses_point(Point(0, 0))
167
+ assert p1.encloses_point(Point(11, 0)) is False
168
+ assert p2.encloses_point(Point(0, 4.9))
169
+ p1.spin(pi/3)
170
+ assert p1.rotation == pi/3
171
+ assert p1.vertices[0] == Point(5, 5*sqrt(3))
172
+ for var in p1.args:
173
+ if isinstance(var, Point):
174
+ assert var == Point(0, 0)
175
+ else:
176
+ assert var in (5, 10, pi / 3)
177
+ assert p1 != Point(0, 0)
178
+ assert p1 != p5
179
+
180
+ # while spin works in place (notice that rotation is 2pi/3 below)
181
+ # rotate returns a new object
182
+ p1_old = p1
183
+ assert p1.rotate(pi/3) == RegularPolygon(Point(0, 0), 10, 5, pi*Rational(2, 3))
184
+ assert p1 == p1_old
185
+
186
+ assert p1.area == (-250*sqrt(5) + 1250)/(4*tan(pi/5))
187
+ assert p1.length == 20*sqrt(-sqrt(5)/8 + Rational(5, 8))
188
+ assert p1.scale(2, 2) == \
189
+ RegularPolygon(p1.center, p1.radius*2, p1._n, p1.rotation)
190
+ assert RegularPolygon((0, 0), 1, 4).scale(2, 3) == \
191
+ Polygon(Point(2, 0), Point(0, 3), Point(-2, 0), Point(0, -3))
192
+
193
+ assert repr(p1) == str(p1)
194
+
195
+ #
196
+ # Angles
197
+ #
198
+ angles = p4.angles
199
+ assert feq(angles[Point(0, 0)].evalf(), Float("0.7853981633974483"))
200
+ assert feq(angles[Point(4, 4)].evalf(), Float("1.2490457723982544"))
201
+ assert feq(angles[Point(5, 2)].evalf(), Float("1.8925468811915388"))
202
+ assert feq(angles[Point(3, 0)].evalf(), Float("2.3561944901923449"))
203
+
204
+ angles = p3.angles
205
+ assert feq(angles[Point(0, 0)].evalf(), Float("0.7853981633974483"))
206
+ assert feq(angles[Point(4, 4)].evalf(), Float("1.2490457723982544"))
207
+ assert feq(angles[Point(5, 2)].evalf(), Float("1.8925468811915388"))
208
+ assert feq(angles[Point(3, 0)].evalf(), Float("2.3561944901923449"))
209
+
210
+ # https://github.com/sympy/sympy/issues/24885
211
+ interior_angles_sum = sum(p13.angles.values())
212
+ assert feq(interior_angles_sum, (len(p13.angles) - 2)*pi )
213
+ interior_angles_sum = sum(p14.angles.values())
214
+ assert feq(interior_angles_sum, (len(p14.angles) - 2)*pi )
215
+
216
+ #
217
+ # Triangle
218
+ #
219
+ p1 = Point(0, 0)
220
+ p2 = Point(5, 0)
221
+ p3 = Point(0, 5)
222
+ t1 = Triangle(p1, p2, p3)
223
+ t2 = Triangle(p1, p2, Point(Rational(5, 2), sqrt(Rational(75, 4))))
224
+ t3 = Triangle(p1, Point(x1, 0), Point(0, x1))
225
+ s1 = t1.sides
226
+ assert Triangle(p1, p2, p1) == Polygon(p1, p2, p1) == Segment(p1, p2)
227
+ raises(GeometryError, lambda: Triangle(Point(0, 0)))
228
+
229
+ # Basic stuff
230
+ assert Triangle(p1, p1, p1) == p1
231
+ assert Triangle(p2, p2*2, p2*3) == Segment(p2, p2*3)
232
+ assert t1.area == Rational(25, 2)
233
+ assert t1.is_right()
234
+ assert t2.is_right() is False
235
+ assert t3.is_right()
236
+ assert p1 in t1
237
+ assert t1.sides[0] in t1
238
+ assert Segment((0, 0), (1, 0)) in t1
239
+ assert Point(5, 5) not in t2
240
+ assert t1.is_convex()
241
+ assert feq(t1.angles[p1].evalf(), pi.evalf()/2)
242
+
243
+ assert t1.is_equilateral() is False
244
+ assert t2.is_equilateral()
245
+ assert t3.is_equilateral() is False
246
+ assert are_similar(t1, t2) is False
247
+ assert are_similar(t1, t3)
248
+ assert are_similar(t2, t3) is False
249
+ assert t1.is_similar(Point(0, 0)) is False
250
+ assert t1.is_similar(t2) is False
251
+
252
+ # Bisectors
253
+ bisectors = t1.bisectors()
254
+ assert bisectors[p1] == Segment(
255
+ p1, Point(Rational(5, 2), Rational(5, 2)))
256
+ assert t2.bisectors()[p2] == Segment(
257
+ Point(5, 0), Point(Rational(5, 4), 5*sqrt(3)/4))
258
+ p4 = Point(0, x1)
259
+ assert t3.bisectors()[p4] == Segment(p4, Point(x1*(sqrt(2) - 1), 0))
260
+ ic = (250 - 125*sqrt(2))/50
261
+ assert t1.incenter == Point(ic, ic)
262
+
263
+ # Inradius
264
+ assert t1.inradius == t1.incircle.radius == 5 - 5*sqrt(2)/2
265
+ assert t2.inradius == t2.incircle.radius == 5*sqrt(3)/6
266
+ assert t3.inradius == t3.incircle.radius == x1**2/((2 + sqrt(2))*Abs(x1))
267
+
268
+ # Exradius
269
+ assert t1.exradii[t1.sides[2]] == 5*sqrt(2)/2
270
+
271
+ # Excenters
272
+ assert t1.excenters[t1.sides[2]] == Point2D(25*sqrt(2), -5*sqrt(2)/2)
273
+
274
+ # Circumcircle
275
+ assert t1.circumcircle.center == Point(2.5, 2.5)
276
+
277
+ # Medians + Centroid
278
+ m = t1.medians
279
+ assert t1.centroid == Point(Rational(5, 3), Rational(5, 3))
280
+ assert m[p1] == Segment(p1, Point(Rational(5, 2), Rational(5, 2)))
281
+ assert t3.medians[p1] == Segment(p1, Point(x1/2, x1/2))
282
+ assert intersection(m[p1], m[p2], m[p3]) == [t1.centroid]
283
+ assert t1.medial == Triangle(Point(2.5, 0), Point(0, 2.5), Point(2.5, 2.5))
284
+
285
+ # Nine-point circle
286
+ assert t1.nine_point_circle == Circle(Point(2.5, 0),
287
+ Point(0, 2.5), Point(2.5, 2.5))
288
+ assert t1.nine_point_circle == Circle(Point(0, 0),
289
+ Point(0, 2.5), Point(2.5, 2.5))
290
+
291
+ # Perpendicular
292
+ altitudes = t1.altitudes
293
+ assert altitudes[p1] == Segment(p1, Point(Rational(5, 2), Rational(5, 2)))
294
+ assert altitudes[p2].equals(s1[0])
295
+ assert altitudes[p3] == s1[2]
296
+ assert t1.orthocenter == p1
297
+ t = S('''Triangle(
298
+ Point(100080156402737/5000000000000, 79782624633431/500000000000),
299
+ Point(39223884078253/2000000000000, 156345163124289/1000000000000),
300
+ Point(31241359188437/1250000000000, 338338270939941/1000000000000000))''')
301
+ assert t.orthocenter == S('''Point(-780660869050599840216997'''
302
+ '''79471538701955848721853/80368430960602242240789074233100000000000000,'''
303
+ '''20151573611150265741278060334545897615974257/16073686192120448448157'''
304
+ '''8148466200000000000)''')
305
+
306
+ # Ensure
307
+ assert len(intersection(*bisectors.values())) == 1
308
+ assert len(intersection(*altitudes.values())) == 1
309
+ assert len(intersection(*m.values())) == 1
310
+
311
+ # Distance
312
+ p1 = Polygon(
313
+ Point(0, 0), Point(1, 0),
314
+ Point(1, 1), Point(0, 1))
315
+ p2 = Polygon(
316
+ Point(0, Rational(5)/4), Point(1, Rational(5)/4),
317
+ Point(1, Rational(9)/4), Point(0, Rational(9)/4))
318
+ p3 = Polygon(
319
+ Point(1, 2), Point(2, 2),
320
+ Point(2, 1))
321
+ p4 = Polygon(
322
+ Point(1, 1), Point(Rational(6)/5, 1),
323
+ Point(1, Rational(6)/5))
324
+ pt1 = Point(half, half)
325
+ pt2 = Point(1, 1)
326
+
327
+ '''Polygon to Point'''
328
+ assert p1.distance(pt1) == half
329
+ assert p1.distance(pt2) == 0
330
+ assert p2.distance(pt1) == Rational(3)/4
331
+ assert p3.distance(pt2) == sqrt(2)/2
332
+
333
+ '''Polygon to Polygon'''
334
+ # p1.distance(p2) emits a warning
335
+ with warns(UserWarning, \
336
+ match="Polygons may intersect producing erroneous output"):
337
+ assert p1.distance(p2) == half/2
338
+
339
+ assert p1.distance(p3) == sqrt(2)/2
340
+
341
+ # p3.distance(p4) emits a warning
342
+ with warns(UserWarning, \
343
+ match="Polygons may intersect producing erroneous output"):
344
+ assert p3.distance(p4) == (sqrt(2)/2 - sqrt(Rational(2)/25)/2)
345
+
346
+
347
+ def test_convex_hull():
348
+ p = [Point(-5, -1), Point(-2, 1), Point(-2, -1), Point(-1, -3), \
349
+ Point(0, 0), Point(1, 1), Point(2, 2), Point(2, -1), Point(3, 1), \
350
+ Point(4, -1), Point(6, 2)]
351
+ ch = Polygon(p[0], p[3], p[9], p[10], p[6], p[1])
352
+ #test handling of duplicate points
353
+ p.append(p[3])
354
+
355
+ #more than 3 collinear points
356
+ another_p = [Point(-45, -85), Point(-45, 85), Point(-45, 26), \
357
+ Point(-45, -24)]
358
+ ch2 = Segment(another_p[0], another_p[1])
359
+
360
+ assert convex_hull(*another_p) == ch2
361
+ assert convex_hull(*p) == ch
362
+ assert convex_hull(p[0]) == p[0]
363
+ assert convex_hull(p[0], p[1]) == Segment(p[0], p[1])
364
+
365
+ # no unique points
366
+ assert convex_hull(*[p[-1]]*3) == p[-1]
367
+
368
+ # collection of items
369
+ assert convex_hull(*[Point(0, 0), \
370
+ Segment(Point(1, 0), Point(1, 1)), \
371
+ RegularPolygon(Point(2, 0), 2, 4)]) == \
372
+ Polygon(Point(0, 0), Point(2, -2), Point(4, 0), Point(2, 2))
373
+
374
+
375
+ def test_encloses():
376
+ # square with a dimpled left side
377
+ s = Polygon(Point(0, 0), Point(1, 0), Point(1, 1), Point(0, 1), \
378
+ Point(S.Half, S.Half))
379
+ # the following is True if the polygon isn't treated as closing on itself
380
+ assert s.encloses(Point(0, S.Half)) is False
381
+ assert s.encloses(Point(S.Half, S.Half)) is False # it's a vertex
382
+ assert s.encloses(Point(Rational(3, 4), S.Half)) is True
383
+
384
+
385
+ def test_triangle_kwargs():
386
+ assert Triangle(sss=(3, 4, 5)) == \
387
+ Triangle(Point(0, 0), Point(3, 0), Point(3, 4))
388
+ assert Triangle(asa=(30, 2, 30)) == \
389
+ Triangle(Point(0, 0), Point(2, 0), Point(1, sqrt(3)/3))
390
+ assert Triangle(sas=(1, 45, 2)) == \
391
+ Triangle(Point(0, 0), Point(2, 0), Point(sqrt(2)/2, sqrt(2)/2))
392
+ assert Triangle(sss=(1, 2, 5)) is None
393
+ assert deg(rad(180)) == 180
394
+
395
+
396
+ def test_transform():
397
+ pts = [Point(0, 0), Point(S.Half, Rational(1, 4)), Point(1, 1)]
398
+ pts_out = [Point(-4, -10), Point(-3, Rational(-37, 4)), Point(-2, -7)]
399
+ assert Triangle(*pts).scale(2, 3, (4, 5)) == Triangle(*pts_out)
400
+ assert RegularPolygon((0, 0), 1, 4).scale(2, 3, (4, 5)) == \
401
+ Polygon(Point(-2, -10), Point(-4, -7), Point(-6, -10), Point(-4, -13))
402
+ # Checks for symmetric scaling
403
+ assert RegularPolygon((0, 0), 1, 4).scale(2, 2) == \
404
+ RegularPolygon(Point2D(0, 0), 2, 4, 0)
405
+
406
+ def test_reflect():
407
+ x = Symbol('x', real=True)
408
+ y = Symbol('y', real=True)
409
+ b = Symbol('b')
410
+ m = Symbol('m')
411
+ l = Line((0, b), slope=m)
412
+ p = Point(x, y)
413
+ r = p.reflect(l)
414
+ dp = l.perpendicular_segment(p).length
415
+ dr = l.perpendicular_segment(r).length
416
+
417
+ assert verify_numerically(dp, dr)
418
+
419
+ assert Polygon((1, 0), (2, 0), (2, 2)).reflect(Line((3, 0), slope=oo)) \
420
+ == Triangle(Point(5, 0), Point(4, 0), Point(4, 2))
421
+ assert Polygon((1, 0), (2, 0), (2, 2)).reflect(Line((0, 3), slope=oo)) \
422
+ == Triangle(Point(-1, 0), Point(-2, 0), Point(-2, 2))
423
+ assert Polygon((1, 0), (2, 0), (2, 2)).reflect(Line((0, 3), slope=0)) \
424
+ == Triangle(Point(1, 6), Point(2, 6), Point(2, 4))
425
+ assert Polygon((1, 0), (2, 0), (2, 2)).reflect(Line((3, 0), slope=0)) \
426
+ == Triangle(Point(1, 0), Point(2, 0), Point(2, -2))
427
+
428
+ def test_bisectors():
429
+ p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1)
430
+ p = Polygon(Point(0, 0), Point(2, 0), Point(1, 1), Point(0, 3))
431
+ q = Polygon(Point(1, 0), Point(2, 0), Point(3, 3), Point(-1, 5))
432
+ poly = Polygon(Point(3, 4), Point(0, 0), Point(8, 7), Point(-1, 1), Point(19, -19))
433
+ t = Triangle(p1, p2, p3)
434
+ assert t.bisectors()[p2] == Segment(Point(1, 0), Point(0, sqrt(2) - 1))
435
+ assert p.bisectors()[Point2D(0, 3)] == Ray2D(Point2D(0, 3), \
436
+ Point2D(sin(acos(2*sqrt(5)/5)/2), 3 - cos(acos(2*sqrt(5)/5)/2)))
437
+ assert q.bisectors()[Point2D(-1, 5)] == \
438
+ Ray2D(Point2D(-1, 5), Point2D(-1 + sqrt(29)*(5*sin(acos(9*sqrt(145)/145)/2) + \
439
+ 2*cos(acos(9*sqrt(145)/145)/2))/29, sqrt(29)*(-5*cos(acos(9*sqrt(145)/145)/2) + \
440
+ 2*sin(acos(9*sqrt(145)/145)/2))/29 + 5))
441
+ assert poly.bisectors()[Point2D(-1, 1)] == Ray2D(Point2D(-1, 1), \
442
+ Point2D(-1 + sin(acos(sqrt(26)/26)/2 + pi/4), 1 - sin(-acos(sqrt(26)/26)/2 + pi/4)))
443
+
444
+ def test_incenter():
445
+ assert Triangle(Point(0, 0), Point(1, 0), Point(0, 1)).incenter \
446
+ == Point(1 - sqrt(2)/2, 1 - sqrt(2)/2)
447
+
448
+ def test_inradius():
449
+ assert Triangle(Point(0, 0), Point(4, 0), Point(0, 3)).inradius == 1
450
+
451
+ def test_incircle():
452
+ assert Triangle(Point(0, 0), Point(2, 0), Point(0, 2)).incircle \
453
+ == Circle(Point(2 - sqrt(2), 2 - sqrt(2)), 2 - sqrt(2))
454
+
455
+ def test_exradii():
456
+ t = Triangle(Point(0, 0), Point(6, 0), Point(0, 2))
457
+ assert t.exradii[t.sides[2]] == (-2 + sqrt(10))
458
+
459
+ def test_medians():
460
+ t = Triangle(Point(0, 0), Point(1, 0), Point(0, 1))
461
+ assert t.medians[Point(0, 0)] == Segment(Point(0, 0), Point(S.Half, S.Half))
462
+
463
+ def test_medial():
464
+ assert Triangle(Point(0, 0), Point(1, 0), Point(0, 1)).medial \
465
+ == Triangle(Point(S.Half, 0), Point(S.Half, S.Half), Point(0, S.Half))
466
+
467
+ def test_nine_point_circle():
468
+ assert Triangle(Point(0, 0), Point(1, 0), Point(0, 1)).nine_point_circle \
469
+ == Circle(Point2D(Rational(1, 4), Rational(1, 4)), sqrt(2)/4)
470
+
471
+ def test_eulerline():
472
+ assert Triangle(Point(0, 0), Point(1, 0), Point(0, 1)).eulerline \
473
+ == Line(Point2D(0, 0), Point2D(S.Half, S.Half))
474
+ assert Triangle(Point(0, 0), Point(10, 0), Point(5, 5*sqrt(3))).eulerline \
475
+ == Point2D(5, 5*sqrt(3)/3)
476
+ assert Triangle(Point(4, -6), Point(4, -1), Point(-3, 3)).eulerline \
477
+ == Line(Point2D(Rational(64, 7), 3), Point2D(Rational(-29, 14), Rational(-7, 2)))
478
+
479
+ def test_intersection():
480
+ poly1 = Triangle(Point(0, 0), Point(1, 0), Point(0, 1))
481
+ poly2 = Polygon(Point(0, 1), Point(-5, 0),
482
+ Point(0, -4), Point(0, Rational(1, 5)),
483
+ Point(S.Half, -0.1), Point(1, 0), Point(0, 1))
484
+
485
+ assert poly1.intersection(poly2) == [Point2D(Rational(1, 3), 0),
486
+ Segment(Point(0, Rational(1, 5)), Point(0, 0)),
487
+ Segment(Point(1, 0), Point(0, 1))]
488
+ assert poly2.intersection(poly1) == [Point(Rational(1, 3), 0),
489
+ Segment(Point(0, 0), Point(0, Rational(1, 5))),
490
+ Segment(Point(1, 0), Point(0, 1))]
491
+ assert poly1.intersection(Point(0, 0)) == [Point(0, 0)]
492
+ assert poly1.intersection(Point(-12, -43)) == []
493
+ assert poly2.intersection(Line((-12, 0), (12, 0))) == [Point(-5, 0),
494
+ Point(0, 0), Point(Rational(1, 3), 0), Point(1, 0)]
495
+ assert poly2.intersection(Line((-12, 12), (12, 12))) == []
496
+ assert poly2.intersection(Ray((-3, 4), (1, 0))) == [Segment(Point(1, 0),
497
+ Point(0, 1))]
498
+ assert poly2.intersection(Circle((0, -1), 1)) == [Point(0, -2),
499
+ Point(0, 0)]
500
+ assert poly1.intersection(poly1) == [Segment(Point(0, 0), Point(1, 0)),
501
+ Segment(Point(0, 1), Point(0, 0)), Segment(Point(1, 0), Point(0, 1))]
502
+ assert poly2.intersection(poly2) == [Segment(Point(-5, 0), Point(0, -4)),
503
+ Segment(Point(0, -4), Point(0, Rational(1, 5))),
504
+ Segment(Point(0, Rational(1, 5)), Point(S.Half, Rational(-1, 10))),
505
+ Segment(Point(0, 1), Point(-5, 0)),
506
+ Segment(Point(S.Half, Rational(-1, 10)), Point(1, 0)),
507
+ Segment(Point(1, 0), Point(0, 1))]
508
+ assert poly2.intersection(Triangle(Point(0, 1), Point(1, 0), Point(-1, 1))) \
509
+ == [Point(Rational(-5, 7), Rational(6, 7)), Segment(Point2D(0, 1), Point(1, 0))]
510
+ assert poly1.intersection(RegularPolygon((-12, -15), 3, 3)) == []
511
+
512
+
513
+ def test_parameter_value():
514
+ t = Symbol('t')
515
+ sq = Polygon((0, 0), (0, 1), (1, 1), (1, 0))
516
+ assert sq.parameter_value((0.5, 1), t) == {t: Rational(3, 8)}
517
+ q = Polygon((0, 0), (2, 1), (2, 4), (4, 0))
518
+ assert q.parameter_value((4, 0), t) == {t: -6 + 3*sqrt(5)} # ~= 0.708
519
+
520
+ raises(ValueError, lambda: sq.parameter_value((5, 6), t))
521
+ raises(ValueError, lambda: sq.parameter_value(Circle(Point(0, 0), 1), t))
522
+
523
+
524
+ def test_issue_12966():
525
+ poly = Polygon(Point(0, 0), Point(0, 10), Point(5, 10), Point(5, 5),
526
+ Point(10, 5), Point(10, 0))
527
+ t = Symbol('t')
528
+ pt = poly.arbitrary_point(t)
529
+ DELTA = 5/poly.perimeter
530
+ assert [pt.subs(t, DELTA*i) for i in range(int(1/DELTA))] == [
531
+ Point(0, 0), Point(0, 5), Point(0, 10), Point(5, 10),
532
+ Point(5, 5), Point(10, 5), Point(10, 0), Point(5, 0)]
533
+
534
+
535
+ def test_second_moment_of_area():
536
+ x, y = symbols('x, y')
537
+ # triangle
538
+ p1, p2, p3 = [(0, 0), (4, 0), (0, 2)]
539
+ p = (0, 0)
540
+ # equation of hypotenuse
541
+ eq_y = (1-x/4)*2
542
+ I_yy = integrate((x**2) * (integrate(1, (y, 0, eq_y))), (x, 0, 4))
543
+ I_xx = integrate(1 * (integrate(y**2, (y, 0, eq_y))), (x, 0, 4))
544
+ I_xy = integrate(x * (integrate(y, (y, 0, eq_y))), (x, 0, 4))
545
+
546
+ triangle = Polygon(p1, p2, p3)
547
+
548
+ assert (I_xx - triangle.second_moment_of_area(p)[0]) == 0
549
+ assert (I_yy - triangle.second_moment_of_area(p)[1]) == 0
550
+ assert (I_xy - triangle.second_moment_of_area(p)[2]) == 0
551
+
552
+ # rectangle
553
+ p1, p2, p3, p4=[(0, 0), (4, 0), (4, 2), (0, 2)]
554
+ I_yy = integrate((x**2) * integrate(1, (y, 0, 2)), (x, 0, 4))
555
+ I_xx = integrate(1 * integrate(y**2, (y, 0, 2)), (x, 0, 4))
556
+ I_xy = integrate(x * integrate(y, (y, 0, 2)), (x, 0, 4))
557
+
558
+ rectangle = Polygon(p1, p2, p3, p4)
559
+
560
+ assert (I_xx - rectangle.second_moment_of_area(p)[0]) == 0
561
+ assert (I_yy - rectangle.second_moment_of_area(p)[1]) == 0
562
+ assert (I_xy - rectangle.second_moment_of_area(p)[2]) == 0
563
+
564
+
565
+ r = RegularPolygon(Point(0, 0), 5, 3)
566
+ assert r.second_moment_of_area() == (1875*sqrt(3)/S(32), 1875*sqrt(3)/S(32), 0)
567
+
568
+
569
+ def test_first_moment():
570
+ a, b = symbols('a, b', positive=True)
571
+ # rectangle
572
+ p1 = Polygon((0, 0), (a, 0), (a, b), (0, b))
573
+ assert p1.first_moment_of_area() == (a*b**2/8, a**2*b/8)
574
+ assert p1.first_moment_of_area((a/3, b/4)) == (-3*a*b**2/32, -a**2*b/9)
575
+
576
+ p1 = Polygon((0, 0), (40, 0), (40, 30), (0, 30))
577
+ assert p1.first_moment_of_area() == (4500, 6000)
578
+
579
+ # triangle
580
+ p2 = Polygon((0, 0), (a, 0), (a/2, b))
581
+ assert p2.first_moment_of_area() == (4*a*b**2/81, a**2*b/24)
582
+ assert p2.first_moment_of_area((a/8, b/6)) == (-25*a*b**2/648, -5*a**2*b/768)
583
+
584
+ p2 = Polygon((0, 0), (12, 0), (12, 30))
585
+ assert p2.first_moment_of_area() == (S(1600)/3, -S(640)/3)
586
+
587
+
588
+ def test_section_modulus_and_polar_second_moment_of_area():
589
+ a, b = symbols('a, b', positive=True)
590
+ x, y = symbols('x, y')
591
+ rectangle = Polygon((0, b), (0, 0), (a, 0), (a, b))
592
+ assert rectangle.section_modulus(Point(x, y)) == (a*b**3/12/(-b/2 + y), a**3*b/12/(-a/2 + x))
593
+ assert rectangle.polar_second_moment_of_area() == a**3*b/12 + a*b**3/12
594
+
595
+ convex = RegularPolygon((0, 0), 1, 6)
596
+ assert convex.section_modulus() == (Rational(5, 8), sqrt(3)*Rational(5, 16))
597
+ assert convex.polar_second_moment_of_area() == 5*sqrt(3)/S(8)
598
+
599
+ concave = Polygon((0, 0), (1, 8), (3, 4), (4, 6), (7, 1))
600
+ assert concave.section_modulus() == (Rational(-6371, 429), Rational(-9778, 519))
601
+ assert concave.polar_second_moment_of_area() == Rational(-38669, 252)
602
+
603
+
604
+ def test_cut_section():
605
+ # concave polygon
606
+ p = Polygon((-1, -1), (1, Rational(5, 2)), (2, 1), (3, Rational(5, 2)), (4, 2), (5, 3), (-1, 3))
607
+ l = Line((0, 0), (Rational(9, 2), 3))
608
+ p1 = p.cut_section(l)[0]
609
+ p2 = p.cut_section(l)[1]
610
+ assert p1 == Polygon(
611
+ Point2D(Rational(-9, 13), Rational(-6, 13)), Point2D(1, Rational(5, 2)), Point2D(Rational(24, 13), Rational(16, 13)),
612
+ Point2D(Rational(12, 5), Rational(8, 5)), Point2D(3, Rational(5, 2)), Point2D(Rational(24, 7), Rational(16, 7)),
613
+ Point2D(Rational(9, 2), 3), Point2D(-1, 3), Point2D(-1, Rational(-2, 3)))
614
+ assert p2 == Polygon(Point2D(-1, -1), Point2D(Rational(-9, 13), Rational(-6, 13)), Point2D(Rational(24, 13), Rational(16, 13)),
615
+ Point2D(2, 1), Point2D(Rational(12, 5), Rational(8, 5)), Point2D(Rational(24, 7), Rational(16, 7)), Point2D(4, 2), Point2D(5, 3),
616
+ Point2D(Rational(9, 2), 3), Point2D(-1, Rational(-2, 3)))
617
+
618
+ # convex polygon
619
+ p = RegularPolygon(Point2D(0, 0), 6, 6)
620
+ s = p.cut_section(Line((0, 0), slope=1))
621
+ assert s[0] == Polygon(Point2D(-3*sqrt(3) + 9, -3*sqrt(3) + 9), Point2D(3, 3*sqrt(3)),
622
+ Point2D(-3, 3*sqrt(3)), Point2D(-6, 0), Point2D(-9 + 3*sqrt(3), -9 + 3*sqrt(3)))
623
+ assert s[1] == Polygon(Point2D(6, 0), Point2D(-3*sqrt(3) + 9, -3*sqrt(3) + 9),
624
+ Point2D(-9 + 3*sqrt(3), -9 + 3*sqrt(3)), Point2D(-3, -3*sqrt(3)), Point2D(3, -3*sqrt(3)))
625
+
626
+ # case where line does not intersects but coincides with the edge of polygon
627
+ a, b = 20, 10
628
+ t1, t2, t3, t4 = [(0, b), (0, 0), (a, 0), (a, b)]
629
+ p = Polygon(t1, t2, t3, t4)
630
+ p1, p2 = p.cut_section(Line((0, b), slope=0))
631
+ assert p1 == None
632
+ assert p2 == Polygon(Point2D(0, 10), Point2D(0, 0), Point2D(20, 0), Point2D(20, 10))
633
+
634
+ p3, p4 = p.cut_section(Line((0, 0), slope=0))
635
+ assert p3 == Polygon(Point2D(0, 10), Point2D(0, 0), Point2D(20, 0), Point2D(20, 10))
636
+ assert p4 == None
637
+
638
+ # case where the line does not intersect with a polygon at all
639
+ raises(ValueError, lambda: p.cut_section(Line((0, a), slope=0)))
640
+
641
+ def test_type_of_triangle():
642
+ # Isoceles triangle
643
+ p1 = Polygon(Point(0, 0), Point(5, 0), Point(2, 4))
644
+ assert p1.is_isosceles() == True
645
+ assert p1.is_scalene() == False
646
+ assert p1.is_equilateral() == False
647
+
648
+ # Scalene triangle
649
+ p2 = Polygon (Point(0, 0), Point(0, 2), Point(4, 0))
650
+ assert p2.is_isosceles() == False
651
+ assert p2.is_scalene() == True
652
+ assert p2.is_equilateral() == False
653
+
654
+ # Equilateral triagle
655
+ p3 = Polygon(Point(0, 0), Point(6, 0), Point(3, sqrt(27)))
656
+ assert p3.is_isosceles() == True
657
+ assert p3.is_scalene() == False
658
+ assert p3.is_equilateral() == True
659
+
660
+ def test_do_poly_distance():
661
+ # Non-intersecting polygons
662
+ square1 = Polygon (Point(0, 0), Point(0, 1), Point(1, 1), Point(1, 0))
663
+ triangle1 = Polygon(Point(1, 2), Point(2, 2), Point(2, 1))
664
+ assert square1._do_poly_distance(triangle1) == sqrt(2)/2
665
+
666
+ # Polygons which sides intersect
667
+ square2 = Polygon(Point(1, 0), Point(2, 0), Point(2, 1), Point(1, 1))
668
+ with warns(UserWarning, \
669
+ match="Polygons may intersect producing erroneous output", test_stacklevel=False):
670
+ assert square1._do_poly_distance(square2) == 0
671
+
672
+ # Polygons which bodies intersect
673
+ triangle2 = Polygon(Point(0, -1), Point(2, -1), Point(S.Half, S.Half))
674
+ with warns(UserWarning, \
675
+ match="Polygons may intersect producing erroneous output", test_stacklevel=False):
676
+ assert triangle2._do_poly_distance(square1) == 0
janus/lib/python3.10/site-packages/sympy/geometry/tests/test_util.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ from sympy.core.numbers import Float
3
+ from sympy.core.function import (Derivative, Function)
4
+ from sympy.core.singleton import S
5
+ from sympy.core.symbol import Symbol
6
+ from sympy.functions import exp, cos, sin, tan, cosh, sinh
7
+ from sympy.functions.elementary.miscellaneous import sqrt
8
+ from sympy.geometry import Point, Point2D, Line, Polygon, Segment, convex_hull,\
9
+ intersection, centroid, Point3D, Line3D, Ray, Ellipse
10
+ from sympy.geometry.util import idiff, closest_points, farthest_points, _ordered_points, are_coplanar
11
+ from sympy.solvers.solvers import solve
12
+ from sympy.testing.pytest import raises
13
+
14
+
15
+ def test_idiff():
16
+ x = Symbol('x', real=True)
17
+ y = Symbol('y', real=True)
18
+ t = Symbol('t', real=True)
19
+ f = Function('f')
20
+ g = Function('g')
21
+ # the use of idiff in ellipse also provides coverage
22
+ circ = x**2 + y**2 - 4
23
+ ans = -3*x*(x**2/y**2 + 1)/y**3
24
+ assert ans == idiff(circ, y, x, 3), idiff(circ, y, x, 3)
25
+ assert ans == idiff(circ, [y], x, 3)
26
+ assert idiff(circ, y, x, 3) == ans
27
+ explicit = 12*x/sqrt(-x**2 + 4)**5
28
+ assert ans.subs(y, solve(circ, y)[0]).equals(explicit)
29
+ assert True in [sol.diff(x, 3).equals(explicit) for sol in solve(circ, y)]
30
+ assert idiff(x + t + y, [y, t], x) == -Derivative(t, x) - 1
31
+ assert idiff(f(x) * exp(f(x)) - x * exp(x), f(x), x) == (x + 1)*exp(x)*exp(-f(x))/(f(x) + 1)
32
+ assert idiff(f(x) - y * exp(x), [f(x), y], x) == (y + Derivative(y, x))*exp(x)
33
+ assert idiff(f(x) - y * exp(x), [y, f(x)], x) == -y + Derivative(f(x), x)*exp(-x)
34
+ assert idiff(f(x) - g(x), [f(x), g(x)], x) == Derivative(g(x), x)
35
+ # this should be fast
36
+ fxy = y - (-10*(-sin(x) + 1/x)**2 + tan(x)**2 + 2*cosh(x/10))
37
+ assert idiff(fxy, y, x) == -20*sin(x)*cos(x) + 2*tan(x)**3 + \
38
+ 2*tan(x) + sinh(x/10)/5 + 20*cos(x)/x - 20*sin(x)/x**2 + 20/x**3
39
+
40
+
41
+ def test_intersection():
42
+ assert intersection(Point(0, 0)) == []
43
+ raises(TypeError, lambda: intersection(Point(0, 0), 3))
44
+ assert intersection(
45
+ Segment((0, 0), (2, 0)),
46
+ Segment((-1, 0), (1, 0)),
47
+ Line((0, 0), (0, 1)), pairwise=True) == [
48
+ Point(0, 0), Segment((0, 0), (1, 0))]
49
+ assert intersection(
50
+ Line((0, 0), (0, 1)),
51
+ Segment((0, 0), (2, 0)),
52
+ Segment((-1, 0), (1, 0)), pairwise=True) == [
53
+ Point(0, 0), Segment((0, 0), (1, 0))]
54
+ assert intersection(
55
+ Line((0, 0), (0, 1)),
56
+ Segment((0, 0), (2, 0)),
57
+ Segment((-1, 0), (1, 0)),
58
+ Line((0, 0), slope=1), pairwise=True) == [
59
+ Point(0, 0), Segment((0, 0), (1, 0))]
60
+ R = 4.0
61
+ c = intersection(
62
+ Ray(Point2D(0.001, -1),
63
+ Point2D(0.0008, -1.7)),
64
+ Ellipse(center=Point2D(0, 0), hradius=R, vradius=2.0), pairwise=True)[0].coordinates
65
+ assert c == pytest.approx(
66
+ Point2D(0.000714285723396502, -1.99999996811224, evaluate=False).coordinates)
67
+ # check this is responds to a lower precision parameter
68
+ R = Float(4, 5)
69
+ c2 = intersection(
70
+ Ray(Point2D(0.001, -1),
71
+ Point2D(0.0008, -1.7)),
72
+ Ellipse(center=Point2D(0, 0), hradius=R, vradius=2.0), pairwise=True)[0].coordinates
73
+ assert c2 == pytest.approx(
74
+ Point2D(0.000714285723396502, -1.99999996811224, evaluate=False).coordinates)
75
+ assert c[0]._prec == 53
76
+ assert c2[0]._prec == 20
77
+
78
+
79
+ def test_convex_hull():
80
+ raises(TypeError, lambda: convex_hull(Point(0, 0), 3))
81
+ points = [(1, -1), (1, -2), (3, -1), (-5, -2), (15, -4)]
82
+ assert convex_hull(*points, **{"polygon": False}) == (
83
+ [Point2D(-5, -2), Point2D(1, -1), Point2D(3, -1), Point2D(15, -4)],
84
+ [Point2D(-5, -2), Point2D(15, -4)])
85
+
86
+
87
+ def test_centroid():
88
+ p = Polygon((0, 0), (10, 0), (10, 10))
89
+ q = p.translate(0, 20)
90
+ assert centroid(p, q) == Point(20, 40)/3
91
+ p = Segment((0, 0), (2, 0))
92
+ q = Segment((0, 0), (2, 2))
93
+ assert centroid(p, q) == Point(1, -sqrt(2) + 2)
94
+ assert centroid(Point(0, 0), Point(2, 0)) == Point(2, 0)/2
95
+ assert centroid(Point(0, 0), Point(0, 0), Point(2, 0)) == Point(2, 0)/3
96
+
97
+
98
+ def test_farthest_points_closest_points():
99
+ from sympy.core.random import randint
100
+ from sympy.utilities.iterables import subsets
101
+
102
+ for how in (min, max):
103
+ if how == min:
104
+ func = closest_points
105
+ else:
106
+ func = farthest_points
107
+
108
+ raises(ValueError, lambda: func(Point2D(0, 0), Point2D(0, 0)))
109
+
110
+ # 3rd pt dx is close and pt is closer to 1st pt
111
+ p1 = [Point2D(0, 0), Point2D(3, 0), Point2D(1, 1)]
112
+ # 3rd pt dx is close and pt is closer to 2nd pt
113
+ p2 = [Point2D(0, 0), Point2D(3, 0), Point2D(2, 1)]
114
+ # 3rd pt dx is close and but pt is not closer
115
+ p3 = [Point2D(0, 0), Point2D(3, 0), Point2D(1, 10)]
116
+ # 3rd pt dx is not closer and it's closer to 2nd pt
117
+ p4 = [Point2D(0, 0), Point2D(3, 0), Point2D(4, 0)]
118
+ # 3rd pt dx is not closer and it's closer to 1st pt
119
+ p5 = [Point2D(0, 0), Point2D(3, 0), Point2D(-1, 0)]
120
+ # duplicate point doesn't affect outcome
121
+ dup = [Point2D(0, 0), Point2D(3, 0), Point2D(3, 0), Point2D(-1, 0)]
122
+ # symbolic
123
+ x = Symbol('x', positive=True)
124
+ s = [Point2D(a) for a in ((x, 1), (x + 3, 2), (x + 2, 2))]
125
+
126
+ for points in (p1, p2, p3, p4, p5, dup, s):
127
+ d = how(i.distance(j) for i, j in subsets(set(points), 2))
128
+ ans = a, b = list(func(*points))[0]
129
+ assert a.distance(b) == d
130
+ assert ans == _ordered_points(ans)
131
+
132
+ # if the following ever fails, the above tests were not sufficient
133
+ # and the logical error in the routine should be fixed
134
+ points = set()
135
+ while len(points) != 7:
136
+ points.add(Point2D(randint(1, 100), randint(1, 100)))
137
+ points = list(points)
138
+ d = how(i.distance(j) for i, j in subsets(points, 2))
139
+ ans = a, b = list(func(*points))[0]
140
+ assert a.distance(b) == d
141
+ assert ans == _ordered_points(ans)
142
+
143
+ # equidistant points
144
+ a, b, c = (
145
+ Point2D(0, 0), Point2D(1, 0), Point2D(S.Half, sqrt(3)/2))
146
+ ans = {_ordered_points((i, j))
147
+ for i, j in subsets((a, b, c), 2)}
148
+ assert closest_points(b, c, a) == ans
149
+ assert farthest_points(b, c, a) == ans
150
+
151
+ # unique to farthest
152
+ points = [(1, 1), (1, 2), (3, 1), (-5, 2), (15, 4)]
153
+ assert farthest_points(*points) == {
154
+ (Point2D(-5, 2), Point2D(15, 4))}
155
+ points = [(1, -1), (1, -2), (3, -1), (-5, -2), (15, -4)]
156
+ assert farthest_points(*points) == {
157
+ (Point2D(-5, -2), Point2D(15, -4))}
158
+ assert farthest_points((1, 1), (0, 0)) == {
159
+ (Point2D(0, 0), Point2D(1, 1))}
160
+ raises(ValueError, lambda: farthest_points((1, 1)))
161
+
162
+
163
+ def test_are_coplanar():
164
+ a = Line3D(Point3D(5, 0, 0), Point3D(1, -1, 1))
165
+ b = Line3D(Point3D(0, -2, 0), Point3D(3, 1, 1))
166
+ c = Line3D(Point3D(0, -1, 0), Point3D(5, -1, 9))
167
+ d = Line(Point2D(0, 3), Point2D(1, 5))
168
+
169
+ assert are_coplanar(a, b, c) == False
170
+ assert are_coplanar(a, d) == False