Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- env-llmeval/lib/python3.10/site-packages/sympy/geometry/curve.py +424 -0
- env-llmeval/lib/python3.10/site-packages/sympy/geometry/line.py +2803 -0
- env-llmeval/lib/python3.10/site-packages/sympy/geometry/parabola.py +422 -0
- env-llmeval/lib/python3.10/site-packages/sympy/geometry/plane.py +884 -0
- env-llmeval/lib/python3.10/site-packages/sympy/geometry/point.py +1378 -0
- env-llmeval/lib/python3.10/site-packages/sympy/printing/pretty/__init__.py +12 -0
- env-llmeval/lib/python3.10/site-packages/sympy/printing/pretty/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/printing/pretty/__pycache__/pretty.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/printing/pretty/__pycache__/pretty_symbology.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/printing/pretty/__pycache__/stringpict.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/printing/pretty/pretty.py +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/printing/pretty/pretty_symbology.py +643 -0
- env-llmeval/lib/python3.10/site-packages/sympy/printing/pretty/stringpict.py +538 -0
- env-llmeval/lib/python3.10/site-packages/sympy/printing/pretty/tests/__init__.py +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/printing/pretty/tests/test_pretty.py +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/sets/__init__.py +36 -0
- env-llmeval/lib/python3.10/site-packages/sympy/sets/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/sets/__pycache__/conditionset.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/sets/__pycache__/contains.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/sets/__pycache__/ordinals.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/sets/conditionset.py +246 -0
- env-llmeval/lib/python3.10/site-packages/sympy/sets/contains.py +48 -0
- env-llmeval/lib/python3.10/site-packages/sympy/sets/fancysets.py +1521 -0
- env-llmeval/lib/python3.10/site-packages/sympy/sets/handlers/__init__.py +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/comparison.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/functions.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/mul.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/sets/handlers/add.py +79 -0
- env-llmeval/lib/python3.10/site-packages/sympy/sets/handlers/comparison.py +53 -0
- env-llmeval/lib/python3.10/site-packages/sympy/sets/handlers/functions.py +262 -0
- env-llmeval/lib/python3.10/site-packages/sympy/sets/handlers/intersection.py +514 -0
- env-llmeval/lib/python3.10/site-packages/sympy/sets/handlers/issubset.py +144 -0
- env-llmeval/lib/python3.10/site-packages/sympy/sets/handlers/mul.py +79 -0
- env-llmeval/lib/python3.10/site-packages/sympy/sets/handlers/power.py +107 -0
- env-llmeval/lib/python3.10/site-packages/sympy/sets/handlers/union.py +147 -0
- env-llmeval/lib/python3.10/site-packages/sympy/sets/ordinals.py +282 -0
- env-llmeval/lib/python3.10/site-packages/sympy/sets/powerset.py +119 -0
- env-llmeval/lib/python3.10/site-packages/sympy/sets/setexpr.py +97 -0
- env-llmeval/lib/python3.10/site-packages/sympy/sets/sets.py +2749 -0
- env-llmeval/lib/python3.10/site-packages/sympy/sets/tests/__init__.py +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_conditionset.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_contains.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_fancysets.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_ordinals.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_powerset.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_setexpr.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_sets.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/sets/tests/test_conditionset.py +294 -0
- env-llmeval/lib/python3.10/site-packages/sympy/sets/tests/test_contains.py +50 -0
env-llmeval/lib/python3.10/site-packages/sympy/geometry/curve.py
ADDED
@@ -0,0 +1,424 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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)
|
env-llmeval/lib/python3.10/site-packages/sympy/geometry/line.py
ADDED
@@ -0,0 +1,2803 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
12 |
+
Segment2D
|
13 |
+
LinearEntity3D
|
14 |
+
Line3D
|
15 |
+
Ray3D
|
16 |
+
Segment3D
|
17 |
+
|
18 |
+
"""
|
19 |
+
|
20 |
+
from sympy.core.containers import Tuple
|
21 |
+
from sympy.core.evalf import N
|
22 |
+
from sympy.core.expr import Expr
|
23 |
+
from sympy.core.numbers import Rational, oo, Float
|
24 |
+
from sympy.core.relational import Eq
|
25 |
+
from sympy.core.singleton import S
|
26 |
+
from sympy.core.sorting import ordered
|
27 |
+
from sympy.core.symbol import _symbol, Dummy, uniquely_named_symbol
|
28 |
+
from sympy.core.sympify import sympify
|
29 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
30 |
+
from sympy.functions.elementary.trigonometric import (_pi_coeff, acos, tan, atan2)
|
31 |
+
from .entity import GeometryEntity, GeometrySet
|
32 |
+
from .exceptions import GeometryError
|
33 |
+
from .point import Point, Point3D
|
34 |
+
from .util import find, intersection
|
35 |
+
from sympy.logic.boolalg import And
|
36 |
+
from sympy.matrices import Matrix
|
37 |
+
from sympy.sets.sets import Intersection
|
38 |
+
from sympy.simplify.simplify import simplify
|
39 |
+
from sympy.solvers.solvers import solve
|
40 |
+
from sympy.solvers.solveset import linear_coeffs
|
41 |
+
from sympy.utilities.misc import Undecidable, filldedent
|
42 |
+
|
43 |
+
|
44 |
+
import random
|
45 |
+
|
46 |
+
|
47 |
+
t, u = [Dummy('line_dummy') for i in range(2)]
|
48 |
+
|
49 |
+
|
50 |
+
class LinearEntity(GeometrySet):
|
51 |
+
"""A base class for all linear entities (Line, Ray and Segment)
|
52 |
+
in n-dimensional Euclidean space.
|
53 |
+
|
54 |
+
Attributes
|
55 |
+
==========
|
56 |
+
|
57 |
+
ambient_dimension
|
58 |
+
direction
|
59 |
+
length
|
60 |
+
p1
|
61 |
+
p2
|
62 |
+
points
|
63 |
+
|
64 |
+
Notes
|
65 |
+
=====
|
66 |
+
|
67 |
+
This is an abstract class and is not meant to be instantiated.
|
68 |
+
|
69 |
+
See Also
|
70 |
+
========
|
71 |
+
|
72 |
+
sympy.geometry.entity.GeometryEntity
|
73 |
+
|
74 |
+
"""
|
75 |
+
def __new__(cls, p1, p2=None, **kwargs):
|
76 |
+
p1, p2 = Point._normalize_dimension(p1, p2)
|
77 |
+
if p1 == p2:
|
78 |
+
# sometimes we return a single point if we are not given two unique
|
79 |
+
# points. This is done in the specific subclass
|
80 |
+
raise ValueError(
|
81 |
+
"%s.__new__ requires two unique Points." % cls.__name__)
|
82 |
+
if len(p1) != len(p2):
|
83 |
+
raise ValueError(
|
84 |
+
"%s.__new__ requires two Points of equal dimension." % cls.__name__)
|
85 |
+
|
86 |
+
return GeometryEntity.__new__(cls, p1, p2, **kwargs)
|
87 |
+
|
88 |
+
def __contains__(self, other):
|
89 |
+
"""Return a definitive answer or else raise an error if it cannot
|
90 |
+
be determined that other is on the boundaries of self."""
|
91 |
+
result = self.contains(other)
|
92 |
+
|
93 |
+
if result is not None:
|
94 |
+
return result
|
95 |
+
else:
|
96 |
+
raise Undecidable(
|
97 |
+
"Cannot decide whether '%s' contains '%s'" % (self, other))
|
98 |
+
|
99 |
+
def _span_test(self, other):
|
100 |
+
"""Test whether the point `other` lies in the positive span of `self`.
|
101 |
+
A point x is 'in front' of a point y if x.dot(y) >= 0. Return
|
102 |
+
-1 if `other` is behind `self.p1`, 0 if `other` is `self.p1` and
|
103 |
+
and 1 if `other` is in front of `self.p1`."""
|
104 |
+
if self.p1 == other:
|
105 |
+
return 0
|
106 |
+
|
107 |
+
rel_pos = other - self.p1
|
108 |
+
d = self.direction
|
109 |
+
if d.dot(rel_pos) > 0:
|
110 |
+
return 1
|
111 |
+
return -1
|
112 |
+
|
113 |
+
@property
|
114 |
+
def ambient_dimension(self):
|
115 |
+
"""A property method that returns the dimension of LinearEntity
|
116 |
+
object.
|
117 |
+
|
118 |
+
Parameters
|
119 |
+
==========
|
120 |
+
|
121 |
+
p1 : LinearEntity
|
122 |
+
|
123 |
+
Returns
|
124 |
+
=======
|
125 |
+
|
126 |
+
dimension : integer
|
127 |
+
|
128 |
+
Examples
|
129 |
+
========
|
130 |
+
|
131 |
+
>>> from sympy import Point, Line
|
132 |
+
>>> p1, p2 = Point(0, 0), Point(1, 1)
|
133 |
+
>>> l1 = Line(p1, p2)
|
134 |
+
>>> l1.ambient_dimension
|
135 |
+
2
|
136 |
+
|
137 |
+
>>> from sympy import Point, Line
|
138 |
+
>>> p1, p2 = Point(0, 0, 0), Point(1, 1, 1)
|
139 |
+
>>> l1 = Line(p1, p2)
|
140 |
+
>>> l1.ambient_dimension
|
141 |
+
3
|
142 |
+
|
143 |
+
"""
|
144 |
+
return len(self.p1)
|
145 |
+
|
146 |
+
def angle_between(l1, l2):
|
147 |
+
"""Return the non-reflex angle formed by rays emanating from
|
148 |
+
the origin with directions the same as the direction vectors
|
149 |
+
of the linear entities.
|
150 |
+
|
151 |
+
Parameters
|
152 |
+
==========
|
153 |
+
|
154 |
+
l1 : LinearEntity
|
155 |
+
l2 : LinearEntity
|
156 |
+
|
157 |
+
Returns
|
158 |
+
=======
|
159 |
+
|
160 |
+
angle : angle in radians
|
161 |
+
|
162 |
+
Notes
|
163 |
+
=====
|
164 |
+
|
165 |
+
From the dot product of vectors v1 and v2 it is known that:
|
166 |
+
|
167 |
+
``dot(v1, v2) = |v1|*|v2|*cos(A)``
|
168 |
+
|
169 |
+
where A is the angle formed between the two vectors. We can
|
170 |
+
get the directional vectors of the two lines and readily
|
171 |
+
find the angle between the two using the above formula.
|
172 |
+
|
173 |
+
See Also
|
174 |
+
========
|
175 |
+
|
176 |
+
is_perpendicular, Ray2D.closing_angle
|
177 |
+
|
178 |
+
Examples
|
179 |
+
========
|
180 |
+
|
181 |
+
>>> from sympy import Line
|
182 |
+
>>> e = Line((0, 0), (1, 0))
|
183 |
+
>>> ne = Line((0, 0), (1, 1))
|
184 |
+
>>> sw = Line((1, 1), (0, 0))
|
185 |
+
>>> ne.angle_between(e)
|
186 |
+
pi/4
|
187 |
+
>>> sw.angle_between(e)
|
188 |
+
3*pi/4
|
189 |
+
|
190 |
+
To obtain the non-obtuse angle at the intersection of lines, use
|
191 |
+
the ``smallest_angle_between`` method:
|
192 |
+
|
193 |
+
>>> sw.smallest_angle_between(e)
|
194 |
+
pi/4
|
195 |
+
|
196 |
+
>>> from sympy import Point3D, Line3D
|
197 |
+
>>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(-1, 2, 0)
|
198 |
+
>>> l1, l2 = Line3D(p1, p2), Line3D(p2, p3)
|
199 |
+
>>> l1.angle_between(l2)
|
200 |
+
acos(-sqrt(2)/3)
|
201 |
+
>>> l1.smallest_angle_between(l2)
|
202 |
+
acos(sqrt(2)/3)
|
203 |
+
"""
|
204 |
+
if not isinstance(l1, LinearEntity) and not isinstance(l2, LinearEntity):
|
205 |
+
raise TypeError('Must pass only LinearEntity objects')
|
206 |
+
|
207 |
+
v1, v2 = l1.direction, l2.direction
|
208 |
+
return acos(v1.dot(v2)/(abs(v1)*abs(v2)))
|
209 |
+
|
210 |
+
def smallest_angle_between(l1, l2):
|
211 |
+
"""Return the smallest angle formed at the intersection of the
|
212 |
+
lines containing the linear entities.
|
213 |
+
|
214 |
+
Parameters
|
215 |
+
==========
|
216 |
+
|
217 |
+
l1 : LinearEntity
|
218 |
+
l2 : LinearEntity
|
219 |
+
|
220 |
+
Returns
|
221 |
+
=======
|
222 |
+
|
223 |
+
angle : angle in radians
|
224 |
+
|
225 |
+
Examples
|
226 |
+
========
|
227 |
+
|
228 |
+
>>> from sympy import Point, Line
|
229 |
+
>>> p1, p2, p3 = Point(0, 0), Point(0, 4), Point(2, -2)
|
230 |
+
>>> l1, l2 = Line(p1, p2), Line(p1, p3)
|
231 |
+
>>> l1.smallest_angle_between(l2)
|
232 |
+
pi/4
|
233 |
+
|
234 |
+
See Also
|
235 |
+
========
|
236 |
+
|
237 |
+
angle_between, is_perpendicular, Ray2D.closing_angle
|
238 |
+
"""
|
239 |
+
if not isinstance(l1, LinearEntity) and not isinstance(l2, LinearEntity):
|
240 |
+
raise TypeError('Must pass only LinearEntity objects')
|
241 |
+
|
242 |
+
v1, v2 = l1.direction, l2.direction
|
243 |
+
return acos(abs(v1.dot(v2))/(abs(v1)*abs(v2)))
|
244 |
+
|
245 |
+
def arbitrary_point(self, parameter='t'):
|
246 |
+
"""A parameterized point on the Line.
|
247 |
+
|
248 |
+
Parameters
|
249 |
+
==========
|
250 |
+
|
251 |
+
parameter : str, optional
|
252 |
+
The name of the parameter which will be used for the parametric
|
253 |
+
point. The default value is 't'. When this parameter is 0, the
|
254 |
+
first point used to define the line will be returned, and when
|
255 |
+
it is 1 the second point will be returned.
|
256 |
+
|
257 |
+
Returns
|
258 |
+
=======
|
259 |
+
|
260 |
+
point : Point
|
261 |
+
|
262 |
+
Raises
|
263 |
+
======
|
264 |
+
|
265 |
+
ValueError
|
266 |
+
When ``parameter`` already appears in the Line's definition.
|
267 |
+
|
268 |
+
See Also
|
269 |
+
========
|
270 |
+
|
271 |
+
sympy.geometry.point.Point
|
272 |
+
|
273 |
+
Examples
|
274 |
+
========
|
275 |
+
|
276 |
+
>>> from sympy import Point, Line
|
277 |
+
>>> p1, p2 = Point(1, 0), Point(5, 3)
|
278 |
+
>>> l1 = Line(p1, p2)
|
279 |
+
>>> l1.arbitrary_point()
|
280 |
+
Point2D(4*t + 1, 3*t)
|
281 |
+
>>> from sympy import Point3D, Line3D
|
282 |
+
>>> p1, p2 = Point3D(1, 0, 0), Point3D(5, 3, 1)
|
283 |
+
>>> l1 = Line3D(p1, p2)
|
284 |
+
>>> l1.arbitrary_point()
|
285 |
+
Point3D(4*t + 1, 3*t, t)
|
286 |
+
|
287 |
+
"""
|
288 |
+
t = _symbol(parameter, real=True)
|
289 |
+
if t.name in (f.name for f in self.free_symbols):
|
290 |
+
raise ValueError(filldedent('''
|
291 |
+
Symbol %s already appears in object
|
292 |
+
and cannot be used as a parameter.
|
293 |
+
''' % t.name))
|
294 |
+
# multiply on the right so the variable gets
|
295 |
+
# combined with the coordinates of the point
|
296 |
+
return self.p1 + (self.p2 - self.p1)*t
|
297 |
+
|
298 |
+
@staticmethod
|
299 |
+
def are_concurrent(*lines):
|
300 |
+
"""Is a sequence of linear entities concurrent?
|
301 |
+
|
302 |
+
Two or more linear entities are concurrent if they all
|
303 |
+
intersect at a single point.
|
304 |
+
|
305 |
+
Parameters
|
306 |
+
==========
|
307 |
+
|
308 |
+
lines
|
309 |
+
A sequence of linear entities.
|
310 |
+
|
311 |
+
Returns
|
312 |
+
=======
|
313 |
+
|
314 |
+
True : if the set of linear entities intersect in one point
|
315 |
+
False : otherwise.
|
316 |
+
|
317 |
+
See Also
|
318 |
+
========
|
319 |
+
|
320 |
+
sympy.geometry.util.intersection
|
321 |
+
|
322 |
+
Examples
|
323 |
+
========
|
324 |
+
|
325 |
+
>>> from sympy import Point, Line
|
326 |
+
>>> p1, p2 = Point(0, 0), Point(3, 5)
|
327 |
+
>>> p3, p4 = Point(-2, -2), Point(0, 2)
|
328 |
+
>>> l1, l2, l3 = Line(p1, p2), Line(p1, p3), Line(p1, p4)
|
329 |
+
>>> Line.are_concurrent(l1, l2, l3)
|
330 |
+
True
|
331 |
+
>>> l4 = Line(p2, p3)
|
332 |
+
>>> Line.are_concurrent(l2, l3, l4)
|
333 |
+
False
|
334 |
+
>>> from sympy import Point3D, Line3D
|
335 |
+
>>> p1, p2 = Point3D(0, 0, 0), Point3D(3, 5, 2)
|
336 |
+
>>> p3, p4 = Point3D(-2, -2, -2), Point3D(0, 2, 1)
|
337 |
+
>>> l1, l2, l3 = Line3D(p1, p2), Line3D(p1, p3), Line3D(p1, p4)
|
338 |
+
>>> Line3D.are_concurrent(l1, l2, l3)
|
339 |
+
True
|
340 |
+
>>> l4 = Line3D(p2, p3)
|
341 |
+
>>> Line3D.are_concurrent(l2, l3, l4)
|
342 |
+
False
|
343 |
+
|
344 |
+
"""
|
345 |
+
common_points = Intersection(*lines)
|
346 |
+
if common_points.is_FiniteSet and len(common_points) == 1:
|
347 |
+
return True
|
348 |
+
return False
|
349 |
+
|
350 |
+
def contains(self, other):
|
351 |
+
"""Subclasses should implement this method and should return
|
352 |
+
True if other is on the boundaries of self;
|
353 |
+
False if not on the boundaries of self;
|
354 |
+
None if a determination cannot be made."""
|
355 |
+
raise NotImplementedError()
|
356 |
+
|
357 |
+
@property
|
358 |
+
def direction(self):
|
359 |
+
"""The direction vector of the LinearEntity.
|
360 |
+
|
361 |
+
Returns
|
362 |
+
=======
|
363 |
+
|
364 |
+
p : a Point; the ray from the origin to this point is the
|
365 |
+
direction of `self`
|
366 |
+
|
367 |
+
Examples
|
368 |
+
========
|
369 |
+
|
370 |
+
>>> from sympy import Line
|
371 |
+
>>> a, b = (1, 1), (1, 3)
|
372 |
+
>>> Line(a, b).direction
|
373 |
+
Point2D(0, 2)
|
374 |
+
>>> Line(b, a).direction
|
375 |
+
Point2D(0, -2)
|
376 |
+
|
377 |
+
This can be reported so the distance from the origin is 1:
|
378 |
+
|
379 |
+
>>> Line(b, a).direction.unit
|
380 |
+
Point2D(0, -1)
|
381 |
+
|
382 |
+
See Also
|
383 |
+
========
|
384 |
+
|
385 |
+
sympy.geometry.point.Point.unit
|
386 |
+
|
387 |
+
"""
|
388 |
+
return self.p2 - self.p1
|
389 |
+
|
390 |
+
def intersection(self, other):
|
391 |
+
"""The intersection with another geometrical entity.
|
392 |
+
|
393 |
+
Parameters
|
394 |
+
==========
|
395 |
+
|
396 |
+
o : Point or LinearEntity
|
397 |
+
|
398 |
+
Returns
|
399 |
+
=======
|
400 |
+
|
401 |
+
intersection : list of geometrical entities
|
402 |
+
|
403 |
+
See Also
|
404 |
+
========
|
405 |
+
|
406 |
+
sympy.geometry.point.Point
|
407 |
+
|
408 |
+
Examples
|
409 |
+
========
|
410 |
+
|
411 |
+
>>> from sympy import Point, Line, Segment
|
412 |
+
>>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(7, 7)
|
413 |
+
>>> l1 = Line(p1, p2)
|
414 |
+
>>> l1.intersection(p3)
|
415 |
+
[Point2D(7, 7)]
|
416 |
+
>>> p4, p5 = Point(5, 0), Point(0, 3)
|
417 |
+
>>> l2 = Line(p4, p5)
|
418 |
+
>>> l1.intersection(l2)
|
419 |
+
[Point2D(15/8, 15/8)]
|
420 |
+
>>> p6, p7 = Point(0, 5), Point(2, 6)
|
421 |
+
>>> s1 = Segment(p6, p7)
|
422 |
+
>>> l1.intersection(s1)
|
423 |
+
[]
|
424 |
+
>>> from sympy import Point3D, Line3D, Segment3D
|
425 |
+
>>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(7, 7, 7)
|
426 |
+
>>> l1 = Line3D(p1, p2)
|
427 |
+
>>> l1.intersection(p3)
|
428 |
+
[Point3D(7, 7, 7)]
|
429 |
+
>>> l1 = Line3D(Point3D(4,19,12), Point3D(5,25,17))
|
430 |
+
>>> l2 = Line3D(Point3D(-3, -15, -19), direction_ratio=[2,8,8])
|
431 |
+
>>> l1.intersection(l2)
|
432 |
+
[Point3D(1, 1, -3)]
|
433 |
+
>>> p6, p7 = Point3D(0, 5, 2), Point3D(2, 6, 3)
|
434 |
+
>>> s1 = Segment3D(p6, p7)
|
435 |
+
>>> l1.intersection(s1)
|
436 |
+
[]
|
437 |
+
|
438 |
+
"""
|
439 |
+
def intersect_parallel_rays(ray1, ray2):
|
440 |
+
if ray1.direction.dot(ray2.direction) > 0:
|
441 |
+
# rays point in the same direction
|
442 |
+
# so return the one that is "in front"
|
443 |
+
return [ray2] if ray1._span_test(ray2.p1) >= 0 else [ray1]
|
444 |
+
else:
|
445 |
+
# rays point in opposite directions
|
446 |
+
st = ray1._span_test(ray2.p1)
|
447 |
+
if st < 0:
|
448 |
+
return []
|
449 |
+
elif st == 0:
|
450 |
+
return [ray2.p1]
|
451 |
+
return [Segment(ray1.p1, ray2.p1)]
|
452 |
+
|
453 |
+
def intersect_parallel_ray_and_segment(ray, seg):
|
454 |
+
st1, st2 = ray._span_test(seg.p1), ray._span_test(seg.p2)
|
455 |
+
if st1 < 0 and st2 < 0:
|
456 |
+
return []
|
457 |
+
elif st1 >= 0 and st2 >= 0:
|
458 |
+
return [seg]
|
459 |
+
elif st1 >= 0: # st2 < 0:
|
460 |
+
return [Segment(ray.p1, seg.p1)]
|
461 |
+
else: # st1 < 0 and st2 >= 0:
|
462 |
+
return [Segment(ray.p1, seg.p2)]
|
463 |
+
|
464 |
+
def intersect_parallel_segments(seg1, seg2):
|
465 |
+
if seg1.contains(seg2):
|
466 |
+
return [seg2]
|
467 |
+
if seg2.contains(seg1):
|
468 |
+
return [seg1]
|
469 |
+
|
470 |
+
# direct the segments so they're oriented the same way
|
471 |
+
if seg1.direction.dot(seg2.direction) < 0:
|
472 |
+
seg2 = Segment(seg2.p2, seg2.p1)
|
473 |
+
# order the segments so seg1 is "behind" seg2
|
474 |
+
if seg1._span_test(seg2.p1) < 0:
|
475 |
+
seg1, seg2 = seg2, seg1
|
476 |
+
if seg2._span_test(seg1.p2) < 0:
|
477 |
+
return []
|
478 |
+
return [Segment(seg2.p1, seg1.p2)]
|
479 |
+
|
480 |
+
if not isinstance(other, GeometryEntity):
|
481 |
+
other = Point(other, dim=self.ambient_dimension)
|
482 |
+
if other.is_Point:
|
483 |
+
if self.contains(other):
|
484 |
+
return [other]
|
485 |
+
else:
|
486 |
+
return []
|
487 |
+
elif isinstance(other, LinearEntity):
|
488 |
+
# break into cases based on whether
|
489 |
+
# the lines are parallel, non-parallel intersecting, or skew
|
490 |
+
pts = Point._normalize_dimension(self.p1, self.p2, other.p1, other.p2)
|
491 |
+
rank = Point.affine_rank(*pts)
|
492 |
+
|
493 |
+
if rank == 1:
|
494 |
+
# we're collinear
|
495 |
+
if isinstance(self, Line):
|
496 |
+
return [other]
|
497 |
+
if isinstance(other, Line):
|
498 |
+
return [self]
|
499 |
+
|
500 |
+
if isinstance(self, Ray) and isinstance(other, Ray):
|
501 |
+
return intersect_parallel_rays(self, other)
|
502 |
+
if isinstance(self, Ray) and isinstance(other, Segment):
|
503 |
+
return intersect_parallel_ray_and_segment(self, other)
|
504 |
+
if isinstance(self, Segment) and isinstance(other, Ray):
|
505 |
+
return intersect_parallel_ray_and_segment(other, self)
|
506 |
+
if isinstance(self, Segment) and isinstance(other, Segment):
|
507 |
+
return intersect_parallel_segments(self, other)
|
508 |
+
elif rank == 2:
|
509 |
+
# we're in the same plane
|
510 |
+
l1 = Line(*pts[:2])
|
511 |
+
l2 = Line(*pts[2:])
|
512 |
+
|
513 |
+
# check to see if we're parallel. If we are, we can't
|
514 |
+
# be intersecting, since the collinear case was already
|
515 |
+
# handled
|
516 |
+
if l1.direction.is_scalar_multiple(l2.direction):
|
517 |
+
return []
|
518 |
+
|
519 |
+
# find the intersection as if everything were lines
|
520 |
+
# by solving the equation t*d + p1 == s*d' + p1'
|
521 |
+
m = Matrix([l1.direction, -l2.direction]).transpose()
|
522 |
+
v = Matrix([l2.p1 - l1.p1]).transpose()
|
523 |
+
|
524 |
+
# we cannot use m.solve(v) because that only works for square matrices
|
525 |
+
m_rref, pivots = m.col_insert(2, v).rref(simplify=True)
|
526 |
+
# rank == 2 ensures we have 2 pivots, but let's check anyway
|
527 |
+
if len(pivots) != 2:
|
528 |
+
raise GeometryError("Failed when solving Mx=b when M={} and b={}".format(m, v))
|
529 |
+
coeff = m_rref[0, 2]
|
530 |
+
line_intersection = l1.direction*coeff + self.p1
|
531 |
+
|
532 |
+
# if both are lines, skip a containment check
|
533 |
+
if isinstance(self, Line) and isinstance(other, Line):
|
534 |
+
return [line_intersection]
|
535 |
+
|
536 |
+
if ((isinstance(self, Line) or
|
537 |
+
self.contains(line_intersection)) and
|
538 |
+
other.contains(line_intersection)):
|
539 |
+
return [line_intersection]
|
540 |
+
if not self.atoms(Float) and not other.atoms(Float):
|
541 |
+
# if it can fail when there are no Floats then
|
542 |
+
# maybe the following parametric check should be
|
543 |
+
# done
|
544 |
+
return []
|
545 |
+
# floats may fail exact containment so check that the
|
546 |
+
# arbitrary points, when equal, both give a
|
547 |
+
# non-negative parameter when the arbitrary point
|
548 |
+
# coordinates are equated
|
549 |
+
tu = solve(self.arbitrary_point(t) - other.arbitrary_point(u),
|
550 |
+
t, u, dict=True)[0]
|
551 |
+
def ok(p, l):
|
552 |
+
if isinstance(l, Line):
|
553 |
+
# p > -oo
|
554 |
+
return True
|
555 |
+
if isinstance(l, Ray):
|
556 |
+
# p >= 0
|
557 |
+
return p.is_nonnegative
|
558 |
+
if isinstance(l, Segment):
|
559 |
+
# 0 <= p <= 1
|
560 |
+
return p.is_nonnegative and (1 - p).is_nonnegative
|
561 |
+
raise ValueError("unexpected line type")
|
562 |
+
if ok(tu[t], self) and ok(tu[u], other):
|
563 |
+
return [line_intersection]
|
564 |
+
return []
|
565 |
+
else:
|
566 |
+
# we're skew
|
567 |
+
return []
|
568 |
+
|
569 |
+
return other.intersection(self)
|
570 |
+
|
571 |
+
def is_parallel(l1, l2):
|
572 |
+
"""Are two linear entities parallel?
|
573 |
+
|
574 |
+
Parameters
|
575 |
+
==========
|
576 |
+
|
577 |
+
l1 : LinearEntity
|
578 |
+
l2 : LinearEntity
|
579 |
+
|
580 |
+
Returns
|
581 |
+
=======
|
582 |
+
|
583 |
+
True : if l1 and l2 are parallel,
|
584 |
+
False : otherwise.
|
585 |
+
|
586 |
+
See Also
|
587 |
+
========
|
588 |
+
|
589 |
+
coefficients
|
590 |
+
|
591 |
+
Examples
|
592 |
+
========
|
593 |
+
|
594 |
+
>>> from sympy import Point, Line
|
595 |
+
>>> p1, p2 = Point(0, 0), Point(1, 1)
|
596 |
+
>>> p3, p4 = Point(3, 4), Point(6, 7)
|
597 |
+
>>> l1, l2 = Line(p1, p2), Line(p3, p4)
|
598 |
+
>>> Line.is_parallel(l1, l2)
|
599 |
+
True
|
600 |
+
>>> p5 = Point(6, 6)
|
601 |
+
>>> l3 = Line(p3, p5)
|
602 |
+
>>> Line.is_parallel(l1, l3)
|
603 |
+
False
|
604 |
+
>>> from sympy import Point3D, Line3D
|
605 |
+
>>> p1, p2 = Point3D(0, 0, 0), Point3D(3, 4, 5)
|
606 |
+
>>> p3, p4 = Point3D(2, 1, 1), Point3D(8, 9, 11)
|
607 |
+
>>> l1, l2 = Line3D(p1, p2), Line3D(p3, p4)
|
608 |
+
>>> Line3D.is_parallel(l1, l2)
|
609 |
+
True
|
610 |
+
>>> p5 = Point3D(6, 6, 6)
|
611 |
+
>>> l3 = Line3D(p3, p5)
|
612 |
+
>>> Line3D.is_parallel(l1, l3)
|
613 |
+
False
|
614 |
+
|
615 |
+
"""
|
616 |
+
if not isinstance(l1, LinearEntity) and not isinstance(l2, LinearEntity):
|
617 |
+
raise TypeError('Must pass only LinearEntity objects')
|
618 |
+
|
619 |
+
return l1.direction.is_scalar_multiple(l2.direction)
|
620 |
+
|
621 |
+
def is_perpendicular(l1, l2):
|
622 |
+
"""Are two linear entities perpendicular?
|
623 |
+
|
624 |
+
Parameters
|
625 |
+
==========
|
626 |
+
|
627 |
+
l1 : LinearEntity
|
628 |
+
l2 : LinearEntity
|
629 |
+
|
630 |
+
Returns
|
631 |
+
=======
|
632 |
+
|
633 |
+
True : if l1 and l2 are perpendicular,
|
634 |
+
False : otherwise.
|
635 |
+
|
636 |
+
See Also
|
637 |
+
========
|
638 |
+
|
639 |
+
coefficients
|
640 |
+
|
641 |
+
Examples
|
642 |
+
========
|
643 |
+
|
644 |
+
>>> from sympy import Point, Line
|
645 |
+
>>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(-1, 1)
|
646 |
+
>>> l1, l2 = Line(p1, p2), Line(p1, p3)
|
647 |
+
>>> l1.is_perpendicular(l2)
|
648 |
+
True
|
649 |
+
>>> p4 = Point(5, 3)
|
650 |
+
>>> l3 = Line(p1, p4)
|
651 |
+
>>> l1.is_perpendicular(l3)
|
652 |
+
False
|
653 |
+
>>> from sympy import Point3D, Line3D
|
654 |
+
>>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(-1, 2, 0)
|
655 |
+
>>> l1, l2 = Line3D(p1, p2), Line3D(p2, p3)
|
656 |
+
>>> l1.is_perpendicular(l2)
|
657 |
+
False
|
658 |
+
>>> p4 = Point3D(5, 3, 7)
|
659 |
+
>>> l3 = Line3D(p1, p4)
|
660 |
+
>>> l1.is_perpendicular(l3)
|
661 |
+
False
|
662 |
+
|
663 |
+
"""
|
664 |
+
if not isinstance(l1, LinearEntity) and not isinstance(l2, LinearEntity):
|
665 |
+
raise TypeError('Must pass only LinearEntity objects')
|
666 |
+
|
667 |
+
return S.Zero.equals(l1.direction.dot(l2.direction))
|
668 |
+
|
669 |
+
def is_similar(self, other):
|
670 |
+
"""
|
671 |
+
Return True if self and other are contained in the same line.
|
672 |
+
|
673 |
+
Examples
|
674 |
+
========
|
675 |
+
|
676 |
+
>>> from sympy import Point, Line
|
677 |
+
>>> p1, p2, p3 = Point(0, 1), Point(3, 4), Point(2, 3)
|
678 |
+
>>> l1 = Line(p1, p2)
|
679 |
+
>>> l2 = Line(p1, p3)
|
680 |
+
>>> l1.is_similar(l2)
|
681 |
+
True
|
682 |
+
"""
|
683 |
+
l = Line(self.p1, self.p2)
|
684 |
+
return l.contains(other)
|
685 |
+
|
686 |
+
@property
|
687 |
+
def length(self):
|
688 |
+
"""
|
689 |
+
The length of the line.
|
690 |
+
|
691 |
+
Examples
|
692 |
+
========
|
693 |
+
|
694 |
+
>>> from sympy import Point, Line
|
695 |
+
>>> p1, p2 = Point(0, 0), Point(3, 5)
|
696 |
+
>>> l1 = Line(p1, p2)
|
697 |
+
>>> l1.length
|
698 |
+
oo
|
699 |
+
"""
|
700 |
+
return S.Infinity
|
701 |
+
|
702 |
+
@property
|
703 |
+
def p1(self):
|
704 |
+
"""The first defining point of a linear entity.
|
705 |
+
|
706 |
+
See Also
|
707 |
+
========
|
708 |
+
|
709 |
+
sympy.geometry.point.Point
|
710 |
+
|
711 |
+
Examples
|
712 |
+
========
|
713 |
+
|
714 |
+
>>> from sympy import Point, Line
|
715 |
+
>>> p1, p2 = Point(0, 0), Point(5, 3)
|
716 |
+
>>> l = Line(p1, p2)
|
717 |
+
>>> l.p1
|
718 |
+
Point2D(0, 0)
|
719 |
+
|
720 |
+
"""
|
721 |
+
return self.args[0]
|
722 |
+
|
723 |
+
@property
|
724 |
+
def p2(self):
|
725 |
+
"""The second defining point of a linear entity.
|
726 |
+
|
727 |
+
See Also
|
728 |
+
========
|
729 |
+
|
730 |
+
sympy.geometry.point.Point
|
731 |
+
|
732 |
+
Examples
|
733 |
+
========
|
734 |
+
|
735 |
+
>>> from sympy import Point, Line
|
736 |
+
>>> p1, p2 = Point(0, 0), Point(5, 3)
|
737 |
+
>>> l = Line(p1, p2)
|
738 |
+
>>> l.p2
|
739 |
+
Point2D(5, 3)
|
740 |
+
|
741 |
+
"""
|
742 |
+
return self.args[1]
|
743 |
+
|
744 |
+
def parallel_line(self, p):
|
745 |
+
"""Create a new Line parallel to this linear entity which passes
|
746 |
+
through the point `p`.
|
747 |
+
|
748 |
+
Parameters
|
749 |
+
==========
|
750 |
+
|
751 |
+
p : Point
|
752 |
+
|
753 |
+
Returns
|
754 |
+
=======
|
755 |
+
|
756 |
+
line : Line
|
757 |
+
|
758 |
+
See Also
|
759 |
+
========
|
760 |
+
|
761 |
+
is_parallel
|
762 |
+
|
763 |
+
Examples
|
764 |
+
========
|
765 |
+
|
766 |
+
>>> from sympy import Point, Line
|
767 |
+
>>> p1, p2, p3 = Point(0, 0), Point(2, 3), Point(-2, 2)
|
768 |
+
>>> l1 = Line(p1, p2)
|
769 |
+
>>> l2 = l1.parallel_line(p3)
|
770 |
+
>>> p3 in l2
|
771 |
+
True
|
772 |
+
>>> l1.is_parallel(l2)
|
773 |
+
True
|
774 |
+
>>> from sympy import Point3D, Line3D
|
775 |
+
>>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(2, 3, 4), Point3D(-2, 2, 0)
|
776 |
+
>>> l1 = Line3D(p1, p2)
|
777 |
+
>>> l2 = l1.parallel_line(p3)
|
778 |
+
>>> p3 in l2
|
779 |
+
True
|
780 |
+
>>> l1.is_parallel(l2)
|
781 |
+
True
|
782 |
+
|
783 |
+
"""
|
784 |
+
p = Point(p, dim=self.ambient_dimension)
|
785 |
+
return Line(p, p + self.direction)
|
786 |
+
|
787 |
+
def perpendicular_line(self, p):
|
788 |
+
"""Create a new Line perpendicular to this linear entity which passes
|
789 |
+
through the point `p`.
|
790 |
+
|
791 |
+
Parameters
|
792 |
+
==========
|
793 |
+
|
794 |
+
p : Point
|
795 |
+
|
796 |
+
Returns
|
797 |
+
=======
|
798 |
+
|
799 |
+
line : Line
|
800 |
+
|
801 |
+
See Also
|
802 |
+
========
|
803 |
+
|
804 |
+
sympy.geometry.line.LinearEntity.is_perpendicular, perpendicular_segment
|
805 |
+
|
806 |
+
Examples
|
807 |
+
========
|
808 |
+
|
809 |
+
>>> from sympy import Point3D, Line3D
|
810 |
+
>>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(2, 3, 4), Point3D(-2, 2, 0)
|
811 |
+
>>> L = Line3D(p1, p2)
|
812 |
+
>>> P = L.perpendicular_line(p3); P
|
813 |
+
Line3D(Point3D(-2, 2, 0), Point3D(4/29, 6/29, 8/29))
|
814 |
+
>>> L.is_perpendicular(P)
|
815 |
+
True
|
816 |
+
|
817 |
+
In 3D the, the first point used to define the line is the point
|
818 |
+
through which the perpendicular was required to pass; the
|
819 |
+
second point is (arbitrarily) contained in the given line:
|
820 |
+
|
821 |
+
>>> P.p2 in L
|
822 |
+
True
|
823 |
+
"""
|
824 |
+
p = Point(p, dim=self.ambient_dimension)
|
825 |
+
if p in self:
|
826 |
+
p = p + self.direction.orthogonal_direction
|
827 |
+
return Line(p, self.projection(p))
|
828 |
+
|
829 |
+
def perpendicular_segment(self, p):
|
830 |
+
"""Create a perpendicular line segment from `p` to this line.
|
831 |
+
|
832 |
+
The endpoints of the segment are ``p`` and the closest point in
|
833 |
+
the line containing self. (If self is not a line, the point might
|
834 |
+
not be in self.)
|
835 |
+
|
836 |
+
Parameters
|
837 |
+
==========
|
838 |
+
|
839 |
+
p : Point
|
840 |
+
|
841 |
+
Returns
|
842 |
+
=======
|
843 |
+
|
844 |
+
segment : Segment
|
845 |
+
|
846 |
+
Notes
|
847 |
+
=====
|
848 |
+
|
849 |
+
Returns `p` itself if `p` is on this linear entity.
|
850 |
+
|
851 |
+
See Also
|
852 |
+
========
|
853 |
+
|
854 |
+
perpendicular_line
|
855 |
+
|
856 |
+
Examples
|
857 |
+
========
|
858 |
+
|
859 |
+
>>> from sympy import Point, Line
|
860 |
+
>>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(0, 2)
|
861 |
+
>>> l1 = Line(p1, p2)
|
862 |
+
>>> s1 = l1.perpendicular_segment(p3)
|
863 |
+
>>> l1.is_perpendicular(s1)
|
864 |
+
True
|
865 |
+
>>> p3 in s1
|
866 |
+
True
|
867 |
+
>>> l1.perpendicular_segment(Point(4, 0))
|
868 |
+
Segment2D(Point2D(4, 0), Point2D(2, 2))
|
869 |
+
>>> from sympy import Point3D, Line3D
|
870 |
+
>>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(0, 2, 0)
|
871 |
+
>>> l1 = Line3D(p1, p2)
|
872 |
+
>>> s1 = l1.perpendicular_segment(p3)
|
873 |
+
>>> l1.is_perpendicular(s1)
|
874 |
+
True
|
875 |
+
>>> p3 in s1
|
876 |
+
True
|
877 |
+
>>> l1.perpendicular_segment(Point3D(4, 0, 0))
|
878 |
+
Segment3D(Point3D(4, 0, 0), Point3D(4/3, 4/3, 4/3))
|
879 |
+
|
880 |
+
"""
|
881 |
+
p = Point(p, dim=self.ambient_dimension)
|
882 |
+
if p in self:
|
883 |
+
return p
|
884 |
+
l = self.perpendicular_line(p)
|
885 |
+
# The intersection should be unique, so unpack the singleton
|
886 |
+
p2, = Intersection(Line(self.p1, self.p2), l)
|
887 |
+
|
888 |
+
return Segment(p, p2)
|
889 |
+
|
890 |
+
@property
|
891 |
+
def points(self):
|
892 |
+
"""The two points used to define this linear entity.
|
893 |
+
|
894 |
+
Returns
|
895 |
+
=======
|
896 |
+
|
897 |
+
points : tuple of Points
|
898 |
+
|
899 |
+
See Also
|
900 |
+
========
|
901 |
+
|
902 |
+
sympy.geometry.point.Point
|
903 |
+
|
904 |
+
Examples
|
905 |
+
========
|
906 |
+
|
907 |
+
>>> from sympy import Point, Line
|
908 |
+
>>> p1, p2 = Point(0, 0), Point(5, 11)
|
909 |
+
>>> l1 = Line(p1, p2)
|
910 |
+
>>> l1.points
|
911 |
+
(Point2D(0, 0), Point2D(5, 11))
|
912 |
+
|
913 |
+
"""
|
914 |
+
return (self.p1, self.p2)
|
915 |
+
|
916 |
+
def projection(self, other):
|
917 |
+
"""Project a point, line, ray, or segment onto this linear entity.
|
918 |
+
|
919 |
+
Parameters
|
920 |
+
==========
|
921 |
+
|
922 |
+
other : Point or LinearEntity (Line, Ray, Segment)
|
923 |
+
|
924 |
+
Returns
|
925 |
+
=======
|
926 |
+
|
927 |
+
projection : Point or LinearEntity (Line, Ray, Segment)
|
928 |
+
The return type matches the type of the parameter ``other``.
|
929 |
+
|
930 |
+
Raises
|
931 |
+
======
|
932 |
+
|
933 |
+
GeometryError
|
934 |
+
When method is unable to perform projection.
|
935 |
+
|
936 |
+
Notes
|
937 |
+
=====
|
938 |
+
|
939 |
+
A projection involves taking the two points that define
|
940 |
+
the linear entity and projecting those points onto a
|
941 |
+
Line and then reforming the linear entity using these
|
942 |
+
projections.
|
943 |
+
A point P is projected onto a line L by finding the point
|
944 |
+
on L that is closest to P. This point is the intersection
|
945 |
+
of L and the line perpendicular to L that passes through P.
|
946 |
+
|
947 |
+
See Also
|
948 |
+
========
|
949 |
+
|
950 |
+
sympy.geometry.point.Point, perpendicular_line
|
951 |
+
|
952 |
+
Examples
|
953 |
+
========
|
954 |
+
|
955 |
+
>>> from sympy import Point, Line, Segment, Rational
|
956 |
+
>>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(Rational(1, 2), 0)
|
957 |
+
>>> l1 = Line(p1, p2)
|
958 |
+
>>> l1.projection(p3)
|
959 |
+
Point2D(1/4, 1/4)
|
960 |
+
>>> p4, p5 = Point(10, 0), Point(12, 1)
|
961 |
+
>>> s1 = Segment(p4, p5)
|
962 |
+
>>> l1.projection(s1)
|
963 |
+
Segment2D(Point2D(5, 5), Point2D(13/2, 13/2))
|
964 |
+
>>> p1, p2, p3 = Point(0, 0, 1), Point(1, 1, 2), Point(2, 0, 1)
|
965 |
+
>>> l1 = Line(p1, p2)
|
966 |
+
>>> l1.projection(p3)
|
967 |
+
Point3D(2/3, 2/3, 5/3)
|
968 |
+
>>> p4, p5 = Point(10, 0, 1), Point(12, 1, 3)
|
969 |
+
>>> s1 = Segment(p4, p5)
|
970 |
+
>>> l1.projection(s1)
|
971 |
+
Segment3D(Point3D(10/3, 10/3, 13/3), Point3D(5, 5, 6))
|
972 |
+
|
973 |
+
"""
|
974 |
+
if not isinstance(other, GeometryEntity):
|
975 |
+
other = Point(other, dim=self.ambient_dimension)
|
976 |
+
|
977 |
+
def proj_point(p):
|
978 |
+
return Point.project(p - self.p1, self.direction) + self.p1
|
979 |
+
|
980 |
+
if isinstance(other, Point):
|
981 |
+
return proj_point(other)
|
982 |
+
elif isinstance(other, LinearEntity):
|
983 |
+
p1, p2 = proj_point(other.p1), proj_point(other.p2)
|
984 |
+
# test to see if we're degenerate
|
985 |
+
if p1 == p2:
|
986 |
+
return p1
|
987 |
+
projected = other.__class__(p1, p2)
|
988 |
+
projected = Intersection(self, projected)
|
989 |
+
if projected.is_empty:
|
990 |
+
return projected
|
991 |
+
# if we happen to have intersected in only a point, return that
|
992 |
+
if projected.is_FiniteSet and len(projected) == 1:
|
993 |
+
# projected is a set of size 1, so unpack it in `a`
|
994 |
+
a, = projected
|
995 |
+
return a
|
996 |
+
# order args so projection is in the same direction as self
|
997 |
+
if self.direction.dot(projected.direction) < 0:
|
998 |
+
p1, p2 = projected.args
|
999 |
+
projected = projected.func(p2, p1)
|
1000 |
+
return projected
|
1001 |
+
|
1002 |
+
raise GeometryError(
|
1003 |
+
"Do not know how to project %s onto %s" % (other, self))
|
1004 |
+
|
1005 |
+
def random_point(self, seed=None):
|
1006 |
+
"""A random point on a LinearEntity.
|
1007 |
+
|
1008 |
+
Returns
|
1009 |
+
=======
|
1010 |
+
|
1011 |
+
point : Point
|
1012 |
+
|
1013 |
+
See Also
|
1014 |
+
========
|
1015 |
+
|
1016 |
+
sympy.geometry.point.Point
|
1017 |
+
|
1018 |
+
Examples
|
1019 |
+
========
|
1020 |
+
|
1021 |
+
>>> from sympy import Point, Line, Ray, Segment
|
1022 |
+
>>> p1, p2 = Point(0, 0), Point(5, 3)
|
1023 |
+
>>> line = Line(p1, p2)
|
1024 |
+
>>> r = line.random_point(seed=42) # seed value is optional
|
1025 |
+
>>> r.n(3)
|
1026 |
+
Point2D(-0.72, -0.432)
|
1027 |
+
>>> r in line
|
1028 |
+
True
|
1029 |
+
>>> Ray(p1, p2).random_point(seed=42).n(3)
|
1030 |
+
Point2D(0.72, 0.432)
|
1031 |
+
>>> Segment(p1, p2).random_point(seed=42).n(3)
|
1032 |
+
Point2D(3.2, 1.92)
|
1033 |
+
|
1034 |
+
"""
|
1035 |
+
if seed is not None:
|
1036 |
+
rng = random.Random(seed)
|
1037 |
+
else:
|
1038 |
+
rng = random
|
1039 |
+
pt = self.arbitrary_point(t)
|
1040 |
+
if isinstance(self, Ray):
|
1041 |
+
v = abs(rng.gauss(0, 1))
|
1042 |
+
elif isinstance(self, Segment):
|
1043 |
+
v = rng.random()
|
1044 |
+
elif isinstance(self, Line):
|
1045 |
+
v = rng.gauss(0, 1)
|
1046 |
+
else:
|
1047 |
+
raise NotImplementedError('unhandled line type')
|
1048 |
+
return pt.subs(t, Rational(v))
|
1049 |
+
|
1050 |
+
def bisectors(self, other):
|
1051 |
+
"""Returns the perpendicular lines which pass through the intersections
|
1052 |
+
of self and other that are in the same plane.
|
1053 |
+
|
1054 |
+
Parameters
|
1055 |
+
==========
|
1056 |
+
|
1057 |
+
line : Line3D
|
1058 |
+
|
1059 |
+
Returns
|
1060 |
+
=======
|
1061 |
+
|
1062 |
+
list: two Line instances
|
1063 |
+
|
1064 |
+
Examples
|
1065 |
+
========
|
1066 |
+
|
1067 |
+
>>> from sympy import Point3D, Line3D
|
1068 |
+
>>> r1 = Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0))
|
1069 |
+
>>> r2 = Line3D(Point3D(0, 0, 0), Point3D(0, 1, 0))
|
1070 |
+
>>> r1.bisectors(r2)
|
1071 |
+
[Line3D(Point3D(0, 0, 0), Point3D(1, 1, 0)), Line3D(Point3D(0, 0, 0), Point3D(1, -1, 0))]
|
1072 |
+
|
1073 |
+
"""
|
1074 |
+
if not isinstance(other, LinearEntity):
|
1075 |
+
raise GeometryError("Expecting LinearEntity, not %s" % other)
|
1076 |
+
|
1077 |
+
l1, l2 = self, other
|
1078 |
+
|
1079 |
+
# make sure dimensions match or else a warning will rise from
|
1080 |
+
# intersection calculation
|
1081 |
+
if l1.p1.ambient_dimension != l2.p1.ambient_dimension:
|
1082 |
+
if isinstance(l1, Line2D):
|
1083 |
+
l1, l2 = l2, l1
|
1084 |
+
_, p1 = Point._normalize_dimension(l1.p1, l2.p1, on_morph='ignore')
|
1085 |
+
_, p2 = Point._normalize_dimension(l1.p2, l2.p2, on_morph='ignore')
|
1086 |
+
l2 = Line(p1, p2)
|
1087 |
+
|
1088 |
+
point = intersection(l1, l2)
|
1089 |
+
|
1090 |
+
# Three cases: Lines may intersect in a point, may be equal or may not intersect.
|
1091 |
+
if not point:
|
1092 |
+
raise GeometryError("The lines do not intersect")
|
1093 |
+
else:
|
1094 |
+
pt = point[0]
|
1095 |
+
if isinstance(pt, Line):
|
1096 |
+
# Intersection is a line because both lines are coincident
|
1097 |
+
return [self]
|
1098 |
+
|
1099 |
+
|
1100 |
+
d1 = l1.direction.unit
|
1101 |
+
d2 = l2.direction.unit
|
1102 |
+
|
1103 |
+
bis1 = Line(pt, pt + d1 + d2)
|
1104 |
+
bis2 = Line(pt, pt + d1 - d2)
|
1105 |
+
|
1106 |
+
return [bis1, bis2]
|
1107 |
+
|
1108 |
+
|
1109 |
+
class Line(LinearEntity):
|
1110 |
+
"""An infinite line in space.
|
1111 |
+
|
1112 |
+
A 2D line is declared with two distinct points, point and slope, or
|
1113 |
+
an equation. A 3D line may be defined with a point and a direction ratio.
|
1114 |
+
|
1115 |
+
Parameters
|
1116 |
+
==========
|
1117 |
+
|
1118 |
+
p1 : Point
|
1119 |
+
p2 : Point
|
1120 |
+
slope : SymPy expression
|
1121 |
+
direction_ratio : list
|
1122 |
+
equation : equation of a line
|
1123 |
+
|
1124 |
+
Notes
|
1125 |
+
=====
|
1126 |
+
|
1127 |
+
`Line` will automatically subclass to `Line2D` or `Line3D` based
|
1128 |
+
on the dimension of `p1`. The `slope` argument is only relevant
|
1129 |
+
for `Line2D` and the `direction_ratio` argument is only relevant
|
1130 |
+
for `Line3D`.
|
1131 |
+
|
1132 |
+
The order of the points will define the direction of the line
|
1133 |
+
which is used when calculating the angle between lines.
|
1134 |
+
|
1135 |
+
See Also
|
1136 |
+
========
|
1137 |
+
|
1138 |
+
sympy.geometry.point.Point
|
1139 |
+
sympy.geometry.line.Line2D
|
1140 |
+
sympy.geometry.line.Line3D
|
1141 |
+
|
1142 |
+
Examples
|
1143 |
+
========
|
1144 |
+
|
1145 |
+
>>> from sympy import Line, Segment, Point, Eq
|
1146 |
+
>>> from sympy.abc import x, y, a, b
|
1147 |
+
|
1148 |
+
>>> L = Line(Point(2,3), Point(3,5))
|
1149 |
+
>>> L
|
1150 |
+
Line2D(Point2D(2, 3), Point2D(3, 5))
|
1151 |
+
>>> L.points
|
1152 |
+
(Point2D(2, 3), Point2D(3, 5))
|
1153 |
+
>>> L.equation()
|
1154 |
+
-2*x + y + 1
|
1155 |
+
>>> L.coefficients
|
1156 |
+
(-2, 1, 1)
|
1157 |
+
|
1158 |
+
Instantiate with keyword ``slope``:
|
1159 |
+
|
1160 |
+
>>> Line(Point(0, 0), slope=0)
|
1161 |
+
Line2D(Point2D(0, 0), Point2D(1, 0))
|
1162 |
+
|
1163 |
+
Instantiate with another linear object
|
1164 |
+
|
1165 |
+
>>> s = Segment((0, 0), (0, 1))
|
1166 |
+
>>> Line(s).equation()
|
1167 |
+
x
|
1168 |
+
|
1169 |
+
The line corresponding to an equation in the for `ax + by + c = 0`,
|
1170 |
+
can be entered:
|
1171 |
+
|
1172 |
+
>>> Line(3*x + y + 18)
|
1173 |
+
Line2D(Point2D(0, -18), Point2D(1, -21))
|
1174 |
+
|
1175 |
+
If `x` or `y` has a different name, then they can be specified, too,
|
1176 |
+
as a string (to match the name) or symbol:
|
1177 |
+
|
1178 |
+
>>> Line(Eq(3*a + b, -18), x='a', y=b)
|
1179 |
+
Line2D(Point2D(0, -18), Point2D(1, -21))
|
1180 |
+
"""
|
1181 |
+
def __new__(cls, *args, **kwargs):
|
1182 |
+
if len(args) == 1 and isinstance(args[0], (Expr, Eq)):
|
1183 |
+
missing = uniquely_named_symbol('?', args)
|
1184 |
+
if not kwargs:
|
1185 |
+
x = 'x'
|
1186 |
+
y = 'y'
|
1187 |
+
else:
|
1188 |
+
x = kwargs.pop('x', missing)
|
1189 |
+
y = kwargs.pop('y', missing)
|
1190 |
+
if kwargs:
|
1191 |
+
raise ValueError('expecting only x and y as keywords')
|
1192 |
+
|
1193 |
+
equation = args[0]
|
1194 |
+
if isinstance(equation, Eq):
|
1195 |
+
equation = equation.lhs - equation.rhs
|
1196 |
+
|
1197 |
+
def find_or_missing(x):
|
1198 |
+
try:
|
1199 |
+
return find(x, equation)
|
1200 |
+
except ValueError:
|
1201 |
+
return missing
|
1202 |
+
x = find_or_missing(x)
|
1203 |
+
y = find_or_missing(y)
|
1204 |
+
|
1205 |
+
a, b, c = linear_coeffs(equation, x, y)
|
1206 |
+
|
1207 |
+
if b:
|
1208 |
+
return Line((0, -c/b), slope=-a/b)
|
1209 |
+
if a:
|
1210 |
+
return Line((-c/a, 0), slope=oo)
|
1211 |
+
|
1212 |
+
raise ValueError('not found in equation: %s' % (set('xy') - {x, y}))
|
1213 |
+
|
1214 |
+
else:
|
1215 |
+
if len(args) > 0:
|
1216 |
+
p1 = args[0]
|
1217 |
+
if len(args) > 1:
|
1218 |
+
p2 = args[1]
|
1219 |
+
else:
|
1220 |
+
p2 = None
|
1221 |
+
|
1222 |
+
if isinstance(p1, LinearEntity):
|
1223 |
+
if p2:
|
1224 |
+
raise ValueError('If p1 is a LinearEntity, p2 must be None.')
|
1225 |
+
dim = len(p1.p1)
|
1226 |
+
else:
|
1227 |
+
p1 = Point(p1)
|
1228 |
+
dim = len(p1)
|
1229 |
+
if p2 is not None or isinstance(p2, Point) and p2.ambient_dimension != dim:
|
1230 |
+
p2 = Point(p2)
|
1231 |
+
|
1232 |
+
if dim == 2:
|
1233 |
+
return Line2D(p1, p2, **kwargs)
|
1234 |
+
elif dim == 3:
|
1235 |
+
return Line3D(p1, p2, **kwargs)
|
1236 |
+
return LinearEntity.__new__(cls, p1, p2, **kwargs)
|
1237 |
+
|
1238 |
+
def contains(self, other):
|
1239 |
+
"""
|
1240 |
+
Return True if `other` is on this Line, or False otherwise.
|
1241 |
+
|
1242 |
+
Examples
|
1243 |
+
========
|
1244 |
+
|
1245 |
+
>>> from sympy import Line,Point
|
1246 |
+
>>> p1, p2 = Point(0, 1), Point(3, 4)
|
1247 |
+
>>> l = Line(p1, p2)
|
1248 |
+
>>> l.contains(p1)
|
1249 |
+
True
|
1250 |
+
>>> l.contains((0, 1))
|
1251 |
+
True
|
1252 |
+
>>> l.contains((0, 0))
|
1253 |
+
False
|
1254 |
+
>>> a = (0, 0, 0)
|
1255 |
+
>>> b = (1, 1, 1)
|
1256 |
+
>>> c = (2, 2, 2)
|
1257 |
+
>>> l1 = Line(a, b)
|
1258 |
+
>>> l2 = Line(b, a)
|
1259 |
+
>>> l1 == l2
|
1260 |
+
False
|
1261 |
+
>>> l1 in l2
|
1262 |
+
True
|
1263 |
+
|
1264 |
+
"""
|
1265 |
+
if not isinstance(other, GeometryEntity):
|
1266 |
+
other = Point(other, dim=self.ambient_dimension)
|
1267 |
+
if isinstance(other, Point):
|
1268 |
+
return Point.is_collinear(other, self.p1, self.p2)
|
1269 |
+
if isinstance(other, LinearEntity):
|
1270 |
+
return Point.is_collinear(self.p1, self.p2, other.p1, other.p2)
|
1271 |
+
return False
|
1272 |
+
|
1273 |
+
def distance(self, other):
|
1274 |
+
"""
|
1275 |
+
Finds the shortest distance between a line and a point.
|
1276 |
+
|
1277 |
+
Raises
|
1278 |
+
======
|
1279 |
+
|
1280 |
+
NotImplementedError is raised if `other` is not a Point
|
1281 |
+
|
1282 |
+
Examples
|
1283 |
+
========
|
1284 |
+
|
1285 |
+
>>> from sympy import Point, Line
|
1286 |
+
>>> p1, p2 = Point(0, 0), Point(1, 1)
|
1287 |
+
>>> s = Line(p1, p2)
|
1288 |
+
>>> s.distance(Point(-1, 1))
|
1289 |
+
sqrt(2)
|
1290 |
+
>>> s.distance((-1, 2))
|
1291 |
+
3*sqrt(2)/2
|
1292 |
+
>>> p1, p2 = Point(0, 0, 0), Point(1, 1, 1)
|
1293 |
+
>>> s = Line(p1, p2)
|
1294 |
+
>>> s.distance(Point(-1, 1, 1))
|
1295 |
+
2*sqrt(6)/3
|
1296 |
+
>>> s.distance((-1, 1, 1))
|
1297 |
+
2*sqrt(6)/3
|
1298 |
+
|
1299 |
+
"""
|
1300 |
+
if not isinstance(other, GeometryEntity):
|
1301 |
+
other = Point(other, dim=self.ambient_dimension)
|
1302 |
+
if self.contains(other):
|
1303 |
+
return S.Zero
|
1304 |
+
return self.perpendicular_segment(other).length
|
1305 |
+
|
1306 |
+
def equals(self, other):
|
1307 |
+
"""Returns True if self and other are the same mathematical entities"""
|
1308 |
+
if not isinstance(other, Line):
|
1309 |
+
return False
|
1310 |
+
return Point.is_collinear(self.p1, other.p1, self.p2, other.p2)
|
1311 |
+
|
1312 |
+
def plot_interval(self, parameter='t'):
|
1313 |
+
"""The plot interval for the default geometric plot of line. Gives
|
1314 |
+
values that will produce a line that is +/- 5 units long (where a
|
1315 |
+
unit is the distance between the two points that define the line).
|
1316 |
+
|
1317 |
+
Parameters
|
1318 |
+
==========
|
1319 |
+
|
1320 |
+
parameter : str, optional
|
1321 |
+
Default value is 't'.
|
1322 |
+
|
1323 |
+
Returns
|
1324 |
+
=======
|
1325 |
+
|
1326 |
+
plot_interval : list (plot interval)
|
1327 |
+
[parameter, lower_bound, upper_bound]
|
1328 |
+
|
1329 |
+
Examples
|
1330 |
+
========
|
1331 |
+
|
1332 |
+
>>> from sympy import Point, Line
|
1333 |
+
>>> p1, p2 = Point(0, 0), Point(5, 3)
|
1334 |
+
>>> l1 = Line(p1, p2)
|
1335 |
+
>>> l1.plot_interval()
|
1336 |
+
[t, -5, 5]
|
1337 |
+
|
1338 |
+
"""
|
1339 |
+
t = _symbol(parameter, real=True)
|
1340 |
+
return [t, -5, 5]
|
1341 |
+
|
1342 |
+
|
1343 |
+
class Ray(LinearEntity):
|
1344 |
+
"""A Ray is a semi-line in the space with a source point and a direction.
|
1345 |
+
|
1346 |
+
Parameters
|
1347 |
+
==========
|
1348 |
+
|
1349 |
+
p1 : Point
|
1350 |
+
The source of the Ray
|
1351 |
+
p2 : Point or radian value
|
1352 |
+
This point determines the direction in which the Ray propagates.
|
1353 |
+
If given as an angle it is interpreted in radians with the positive
|
1354 |
+
direction being ccw.
|
1355 |
+
|
1356 |
+
Attributes
|
1357 |
+
==========
|
1358 |
+
|
1359 |
+
source
|
1360 |
+
|
1361 |
+
See Also
|
1362 |
+
========
|
1363 |
+
|
1364 |
+
sympy.geometry.line.Ray2D
|
1365 |
+
sympy.geometry.line.Ray3D
|
1366 |
+
sympy.geometry.point.Point
|
1367 |
+
sympy.geometry.line.Line
|
1368 |
+
|
1369 |
+
Notes
|
1370 |
+
=====
|
1371 |
+
|
1372 |
+
`Ray` will automatically subclass to `Ray2D` or `Ray3D` based on the
|
1373 |
+
dimension of `p1`.
|
1374 |
+
|
1375 |
+
Examples
|
1376 |
+
========
|
1377 |
+
|
1378 |
+
>>> from sympy import Ray, Point, pi
|
1379 |
+
>>> r = Ray(Point(2, 3), Point(3, 5))
|
1380 |
+
>>> r
|
1381 |
+
Ray2D(Point2D(2, 3), Point2D(3, 5))
|
1382 |
+
>>> r.points
|
1383 |
+
(Point2D(2, 3), Point2D(3, 5))
|
1384 |
+
>>> r.source
|
1385 |
+
Point2D(2, 3)
|
1386 |
+
>>> r.xdirection
|
1387 |
+
oo
|
1388 |
+
>>> r.ydirection
|
1389 |
+
oo
|
1390 |
+
>>> r.slope
|
1391 |
+
2
|
1392 |
+
>>> Ray(Point(0, 0), angle=pi/4).slope
|
1393 |
+
1
|
1394 |
+
|
1395 |
+
"""
|
1396 |
+
def __new__(cls, p1, p2=None, **kwargs):
|
1397 |
+
p1 = Point(p1)
|
1398 |
+
if p2 is not None:
|
1399 |
+
p1, p2 = Point._normalize_dimension(p1, Point(p2))
|
1400 |
+
dim = len(p1)
|
1401 |
+
|
1402 |
+
if dim == 2:
|
1403 |
+
return Ray2D(p1, p2, **kwargs)
|
1404 |
+
elif dim == 3:
|
1405 |
+
return Ray3D(p1, p2, **kwargs)
|
1406 |
+
return LinearEntity.__new__(cls, p1, p2, **kwargs)
|
1407 |
+
|
1408 |
+
def _svg(self, scale_factor=1., fill_color="#66cc99"):
|
1409 |
+
"""Returns SVG path element for the LinearEntity.
|
1410 |
+
|
1411 |
+
Parameters
|
1412 |
+
==========
|
1413 |
+
|
1414 |
+
scale_factor : float
|
1415 |
+
Multiplication factor for the SVG stroke-width. Default is 1.
|
1416 |
+
fill_color : str, optional
|
1417 |
+
Hex string for fill color. Default is "#66cc99".
|
1418 |
+
"""
|
1419 |
+
verts = (N(self.p1), N(self.p2))
|
1420 |
+
coords = ["{},{}".format(p.x, p.y) for p in verts]
|
1421 |
+
path = "M {} L {}".format(coords[0], " L ".join(coords[1:]))
|
1422 |
+
|
1423 |
+
return (
|
1424 |
+
'<path fill-rule="evenodd" fill="{2}" stroke="#555555" '
|
1425 |
+
'stroke-width="{0}" opacity="0.6" d="{1}" '
|
1426 |
+
'marker-start="url(#markerCircle)" marker-end="url(#markerArrow)"/>'
|
1427 |
+
).format(2.*scale_factor, path, fill_color)
|
1428 |
+
|
1429 |
+
def contains(self, other):
|
1430 |
+
"""
|
1431 |
+
Is other GeometryEntity contained in this Ray?
|
1432 |
+
|
1433 |
+
Examples
|
1434 |
+
========
|
1435 |
+
|
1436 |
+
>>> from sympy import Ray,Point,Segment
|
1437 |
+
>>> p1, p2 = Point(0, 0), Point(4, 4)
|
1438 |
+
>>> r = Ray(p1, p2)
|
1439 |
+
>>> r.contains(p1)
|
1440 |
+
True
|
1441 |
+
>>> r.contains((1, 1))
|
1442 |
+
True
|
1443 |
+
>>> r.contains((1, 3))
|
1444 |
+
False
|
1445 |
+
>>> s = Segment((1, 1), (2, 2))
|
1446 |
+
>>> r.contains(s)
|
1447 |
+
True
|
1448 |
+
>>> s = Segment((1, 2), (2, 5))
|
1449 |
+
>>> r.contains(s)
|
1450 |
+
False
|
1451 |
+
>>> r1 = Ray((2, 2), (3, 3))
|
1452 |
+
>>> r.contains(r1)
|
1453 |
+
True
|
1454 |
+
>>> r1 = Ray((2, 2), (3, 5))
|
1455 |
+
>>> r.contains(r1)
|
1456 |
+
False
|
1457 |
+
"""
|
1458 |
+
if not isinstance(other, GeometryEntity):
|
1459 |
+
other = Point(other, dim=self.ambient_dimension)
|
1460 |
+
if isinstance(other, Point):
|
1461 |
+
if Point.is_collinear(self.p1, self.p2, other):
|
1462 |
+
# if we're in the direction of the ray, our
|
1463 |
+
# direction vector dot the ray's direction vector
|
1464 |
+
# should be non-negative
|
1465 |
+
return bool((self.p2 - self.p1).dot(other - self.p1) >= S.Zero)
|
1466 |
+
return False
|
1467 |
+
elif isinstance(other, Ray):
|
1468 |
+
if Point.is_collinear(self.p1, self.p2, other.p1, other.p2):
|
1469 |
+
return bool((self.p2 - self.p1).dot(other.p2 - other.p1) > S.Zero)
|
1470 |
+
return False
|
1471 |
+
elif isinstance(other, Segment):
|
1472 |
+
return other.p1 in self and other.p2 in self
|
1473 |
+
|
1474 |
+
# No other known entity can be contained in a Ray
|
1475 |
+
return False
|
1476 |
+
|
1477 |
+
def distance(self, other):
|
1478 |
+
"""
|
1479 |
+
Finds the shortest distance between the ray and a point.
|
1480 |
+
|
1481 |
+
Raises
|
1482 |
+
======
|
1483 |
+
|
1484 |
+
NotImplementedError is raised if `other` is not a Point
|
1485 |
+
|
1486 |
+
Examples
|
1487 |
+
========
|
1488 |
+
|
1489 |
+
>>> from sympy import Point, Ray
|
1490 |
+
>>> p1, p2 = Point(0, 0), Point(1, 1)
|
1491 |
+
>>> s = Ray(p1, p2)
|
1492 |
+
>>> s.distance(Point(-1, -1))
|
1493 |
+
sqrt(2)
|
1494 |
+
>>> s.distance((-1, 2))
|
1495 |
+
3*sqrt(2)/2
|
1496 |
+
>>> p1, p2 = Point(0, 0, 0), Point(1, 1, 2)
|
1497 |
+
>>> s = Ray(p1, p2)
|
1498 |
+
>>> s
|
1499 |
+
Ray3D(Point3D(0, 0, 0), Point3D(1, 1, 2))
|
1500 |
+
>>> s.distance(Point(-1, -1, 2))
|
1501 |
+
4*sqrt(3)/3
|
1502 |
+
>>> s.distance((-1, -1, 2))
|
1503 |
+
4*sqrt(3)/3
|
1504 |
+
|
1505 |
+
"""
|
1506 |
+
if not isinstance(other, GeometryEntity):
|
1507 |
+
other = Point(other, dim=self.ambient_dimension)
|
1508 |
+
if self.contains(other):
|
1509 |
+
return S.Zero
|
1510 |
+
|
1511 |
+
proj = Line(self.p1, self.p2).projection(other)
|
1512 |
+
if self.contains(proj):
|
1513 |
+
return abs(other - proj)
|
1514 |
+
else:
|
1515 |
+
return abs(other - self.source)
|
1516 |
+
|
1517 |
+
def equals(self, other):
|
1518 |
+
"""Returns True if self and other are the same mathematical entities"""
|
1519 |
+
if not isinstance(other, Ray):
|
1520 |
+
return False
|
1521 |
+
return self.source == other.source and other.p2 in self
|
1522 |
+
|
1523 |
+
def plot_interval(self, parameter='t'):
|
1524 |
+
"""The plot interval for the default geometric plot of the Ray. Gives
|
1525 |
+
values that will produce a ray that is 10 units long (where a unit is
|
1526 |
+
the distance between the two points that define the ray).
|
1527 |
+
|
1528 |
+
Parameters
|
1529 |
+
==========
|
1530 |
+
|
1531 |
+
parameter : str, optional
|
1532 |
+
Default value is 't'.
|
1533 |
+
|
1534 |
+
Returns
|
1535 |
+
=======
|
1536 |
+
|
1537 |
+
plot_interval : list
|
1538 |
+
[parameter, lower_bound, upper_bound]
|
1539 |
+
|
1540 |
+
Examples
|
1541 |
+
========
|
1542 |
+
|
1543 |
+
>>> from sympy import Ray, pi
|
1544 |
+
>>> r = Ray((0, 0), angle=pi/4)
|
1545 |
+
>>> r.plot_interval()
|
1546 |
+
[t, 0, 10]
|
1547 |
+
|
1548 |
+
"""
|
1549 |
+
t = _symbol(parameter, real=True)
|
1550 |
+
return [t, 0, 10]
|
1551 |
+
|
1552 |
+
@property
|
1553 |
+
def source(self):
|
1554 |
+
"""The point from which the ray emanates.
|
1555 |
+
|
1556 |
+
See Also
|
1557 |
+
========
|
1558 |
+
|
1559 |
+
sympy.geometry.point.Point
|
1560 |
+
|
1561 |
+
Examples
|
1562 |
+
========
|
1563 |
+
|
1564 |
+
>>> from sympy import Point, Ray
|
1565 |
+
>>> p1, p2 = Point(0, 0), Point(4, 1)
|
1566 |
+
>>> r1 = Ray(p1, p2)
|
1567 |
+
>>> r1.source
|
1568 |
+
Point2D(0, 0)
|
1569 |
+
>>> p1, p2 = Point(0, 0, 0), Point(4, 1, 5)
|
1570 |
+
>>> r1 = Ray(p2, p1)
|
1571 |
+
>>> r1.source
|
1572 |
+
Point3D(4, 1, 5)
|
1573 |
+
|
1574 |
+
"""
|
1575 |
+
return self.p1
|
1576 |
+
|
1577 |
+
|
1578 |
+
class Segment(LinearEntity):
|
1579 |
+
"""A line segment in space.
|
1580 |
+
|
1581 |
+
Parameters
|
1582 |
+
==========
|
1583 |
+
|
1584 |
+
p1 : Point
|
1585 |
+
p2 : Point
|
1586 |
+
|
1587 |
+
Attributes
|
1588 |
+
==========
|
1589 |
+
|
1590 |
+
length : number or SymPy expression
|
1591 |
+
midpoint : Point
|
1592 |
+
|
1593 |
+
See Also
|
1594 |
+
========
|
1595 |
+
|
1596 |
+
sympy.geometry.line.Segment2D
|
1597 |
+
sympy.geometry.line.Segment3D
|
1598 |
+
sympy.geometry.point.Point
|
1599 |
+
sympy.geometry.line.Line
|
1600 |
+
|
1601 |
+
Notes
|
1602 |
+
=====
|
1603 |
+
|
1604 |
+
If 2D or 3D points are used to define `Segment`, it will
|
1605 |
+
be automatically subclassed to `Segment2D` or `Segment3D`.
|
1606 |
+
|
1607 |
+
Examples
|
1608 |
+
========
|
1609 |
+
|
1610 |
+
>>> from sympy import Point, Segment
|
1611 |
+
>>> Segment((1, 0), (1, 1)) # tuples are interpreted as pts
|
1612 |
+
Segment2D(Point2D(1, 0), Point2D(1, 1))
|
1613 |
+
>>> s = Segment(Point(4, 3), Point(1, 1))
|
1614 |
+
>>> s.points
|
1615 |
+
(Point2D(4, 3), Point2D(1, 1))
|
1616 |
+
>>> s.slope
|
1617 |
+
2/3
|
1618 |
+
>>> s.length
|
1619 |
+
sqrt(13)
|
1620 |
+
>>> s.midpoint
|
1621 |
+
Point2D(5/2, 2)
|
1622 |
+
>>> Segment((1, 0, 0), (1, 1, 1)) # tuples are interpreted as pts
|
1623 |
+
Segment3D(Point3D(1, 0, 0), Point3D(1, 1, 1))
|
1624 |
+
>>> s = Segment(Point(4, 3, 9), Point(1, 1, 7)); s
|
1625 |
+
Segment3D(Point3D(4, 3, 9), Point3D(1, 1, 7))
|
1626 |
+
>>> s.points
|
1627 |
+
(Point3D(4, 3, 9), Point3D(1, 1, 7))
|
1628 |
+
>>> s.length
|
1629 |
+
sqrt(17)
|
1630 |
+
>>> s.midpoint
|
1631 |
+
Point3D(5/2, 2, 8)
|
1632 |
+
|
1633 |
+
"""
|
1634 |
+
def __new__(cls, p1, p2, **kwargs):
|
1635 |
+
p1, p2 = Point._normalize_dimension(Point(p1), Point(p2))
|
1636 |
+
dim = len(p1)
|
1637 |
+
|
1638 |
+
if dim == 2:
|
1639 |
+
return Segment2D(p1, p2, **kwargs)
|
1640 |
+
elif dim == 3:
|
1641 |
+
return Segment3D(p1, p2, **kwargs)
|
1642 |
+
return LinearEntity.__new__(cls, p1, p2, **kwargs)
|
1643 |
+
|
1644 |
+
def contains(self, other):
|
1645 |
+
"""
|
1646 |
+
Is the other GeometryEntity contained within this Segment?
|
1647 |
+
|
1648 |
+
Examples
|
1649 |
+
========
|
1650 |
+
|
1651 |
+
>>> from sympy import Point, Segment
|
1652 |
+
>>> p1, p2 = Point(0, 1), Point(3, 4)
|
1653 |
+
>>> s = Segment(p1, p2)
|
1654 |
+
>>> s2 = Segment(p2, p1)
|
1655 |
+
>>> s.contains(s2)
|
1656 |
+
True
|
1657 |
+
>>> from sympy import Point3D, Segment3D
|
1658 |
+
>>> p1, p2 = Point3D(0, 1, 1), Point3D(3, 4, 5)
|
1659 |
+
>>> s = Segment3D(p1, p2)
|
1660 |
+
>>> s2 = Segment3D(p2, p1)
|
1661 |
+
>>> s.contains(s2)
|
1662 |
+
True
|
1663 |
+
>>> s.contains((p1 + p2)/2)
|
1664 |
+
True
|
1665 |
+
"""
|
1666 |
+
if not isinstance(other, GeometryEntity):
|
1667 |
+
other = Point(other, dim=self.ambient_dimension)
|
1668 |
+
if isinstance(other, Point):
|
1669 |
+
if Point.is_collinear(other, self.p1, self.p2):
|
1670 |
+
if isinstance(self, Segment2D):
|
1671 |
+
# if it is collinear and is in the bounding box of the
|
1672 |
+
# segment then it must be on the segment
|
1673 |
+
vert = (1/self.slope).equals(0)
|
1674 |
+
if vert is False:
|
1675 |
+
isin = (self.p1.x - other.x)*(self.p2.x - other.x) <= 0
|
1676 |
+
if isin in (True, False):
|
1677 |
+
return isin
|
1678 |
+
if vert is True:
|
1679 |
+
isin = (self.p1.y - other.y)*(self.p2.y - other.y) <= 0
|
1680 |
+
if isin in (True, False):
|
1681 |
+
return isin
|
1682 |
+
# use the triangle inequality
|
1683 |
+
d1, d2 = other - self.p1, other - self.p2
|
1684 |
+
d = self.p2 - self.p1
|
1685 |
+
# without the call to simplify, SymPy cannot tell that an expression
|
1686 |
+
# like (a+b)*(a/2+b/2) is always non-negative. If it cannot be
|
1687 |
+
# determined, raise an Undecidable error
|
1688 |
+
try:
|
1689 |
+
# the triangle inequality says that |d1|+|d2| >= |d| and is strict
|
1690 |
+
# only if other lies in the line segment
|
1691 |
+
return bool(simplify(Eq(abs(d1) + abs(d2) - abs(d), 0)))
|
1692 |
+
except TypeError:
|
1693 |
+
raise Undecidable("Cannot determine if {} is in {}".format(other, self))
|
1694 |
+
if isinstance(other, Segment):
|
1695 |
+
return other.p1 in self and other.p2 in self
|
1696 |
+
|
1697 |
+
return False
|
1698 |
+
|
1699 |
+
def equals(self, other):
|
1700 |
+
"""Returns True if self and other are the same mathematical entities"""
|
1701 |
+
return isinstance(other, self.func) and list(
|
1702 |
+
ordered(self.args)) == list(ordered(other.args))
|
1703 |
+
|
1704 |
+
def distance(self, other):
|
1705 |
+
"""
|
1706 |
+
Finds the shortest distance between a line segment and a point.
|
1707 |
+
|
1708 |
+
Raises
|
1709 |
+
======
|
1710 |
+
|
1711 |
+
NotImplementedError is raised if `other` is not a Point
|
1712 |
+
|
1713 |
+
Examples
|
1714 |
+
========
|
1715 |
+
|
1716 |
+
>>> from sympy import Point, Segment
|
1717 |
+
>>> p1, p2 = Point(0, 1), Point(3, 4)
|
1718 |
+
>>> s = Segment(p1, p2)
|
1719 |
+
>>> s.distance(Point(10, 15))
|
1720 |
+
sqrt(170)
|
1721 |
+
>>> s.distance((0, 12))
|
1722 |
+
sqrt(73)
|
1723 |
+
>>> from sympy import Point3D, Segment3D
|
1724 |
+
>>> p1, p2 = Point3D(0, 0, 3), Point3D(1, 1, 4)
|
1725 |
+
>>> s = Segment3D(p1, p2)
|
1726 |
+
>>> s.distance(Point3D(10, 15, 12))
|
1727 |
+
sqrt(341)
|
1728 |
+
>>> s.distance((10, 15, 12))
|
1729 |
+
sqrt(341)
|
1730 |
+
"""
|
1731 |
+
if not isinstance(other, GeometryEntity):
|
1732 |
+
other = Point(other, dim=self.ambient_dimension)
|
1733 |
+
if isinstance(other, Point):
|
1734 |
+
vp1 = other - self.p1
|
1735 |
+
vp2 = other - self.p2
|
1736 |
+
|
1737 |
+
dot_prod_sign_1 = self.direction.dot(vp1) >= 0
|
1738 |
+
dot_prod_sign_2 = self.direction.dot(vp2) <= 0
|
1739 |
+
if dot_prod_sign_1 and dot_prod_sign_2:
|
1740 |
+
return Line(self.p1, self.p2).distance(other)
|
1741 |
+
if dot_prod_sign_1 and not dot_prod_sign_2:
|
1742 |
+
return abs(vp2)
|
1743 |
+
if not dot_prod_sign_1 and dot_prod_sign_2:
|
1744 |
+
return abs(vp1)
|
1745 |
+
raise NotImplementedError()
|
1746 |
+
|
1747 |
+
@property
|
1748 |
+
def length(self):
|
1749 |
+
"""The length of the line segment.
|
1750 |
+
|
1751 |
+
See Also
|
1752 |
+
========
|
1753 |
+
|
1754 |
+
sympy.geometry.point.Point.distance
|
1755 |
+
|
1756 |
+
Examples
|
1757 |
+
========
|
1758 |
+
|
1759 |
+
>>> from sympy import Point, Segment
|
1760 |
+
>>> p1, p2 = Point(0, 0), Point(4, 3)
|
1761 |
+
>>> s1 = Segment(p1, p2)
|
1762 |
+
>>> s1.length
|
1763 |
+
5
|
1764 |
+
>>> from sympy import Point3D, Segment3D
|
1765 |
+
>>> p1, p2 = Point3D(0, 0, 0), Point3D(4, 3, 3)
|
1766 |
+
>>> s1 = Segment3D(p1, p2)
|
1767 |
+
>>> s1.length
|
1768 |
+
sqrt(34)
|
1769 |
+
|
1770 |
+
"""
|
1771 |
+
return Point.distance(self.p1, self.p2)
|
1772 |
+
|
1773 |
+
@property
|
1774 |
+
def midpoint(self):
|
1775 |
+
"""The midpoint of the line segment.
|
1776 |
+
|
1777 |
+
See Also
|
1778 |
+
========
|
1779 |
+
|
1780 |
+
sympy.geometry.point.Point.midpoint
|
1781 |
+
|
1782 |
+
Examples
|
1783 |
+
========
|
1784 |
+
|
1785 |
+
>>> from sympy import Point, Segment
|
1786 |
+
>>> p1, p2 = Point(0, 0), Point(4, 3)
|
1787 |
+
>>> s1 = Segment(p1, p2)
|
1788 |
+
>>> s1.midpoint
|
1789 |
+
Point2D(2, 3/2)
|
1790 |
+
>>> from sympy import Point3D, Segment3D
|
1791 |
+
>>> p1, p2 = Point3D(0, 0, 0), Point3D(4, 3, 3)
|
1792 |
+
>>> s1 = Segment3D(p1, p2)
|
1793 |
+
>>> s1.midpoint
|
1794 |
+
Point3D(2, 3/2, 3/2)
|
1795 |
+
|
1796 |
+
"""
|
1797 |
+
return Point.midpoint(self.p1, self.p2)
|
1798 |
+
|
1799 |
+
def perpendicular_bisector(self, p=None):
|
1800 |
+
"""The perpendicular bisector of this segment.
|
1801 |
+
|
1802 |
+
If no point is specified or the point specified is not on the
|
1803 |
+
bisector then the bisector is returned as a Line. Otherwise a
|
1804 |
+
Segment is returned that joins the point specified and the
|
1805 |
+
intersection of the bisector and the segment.
|
1806 |
+
|
1807 |
+
Parameters
|
1808 |
+
==========
|
1809 |
+
|
1810 |
+
p : Point
|
1811 |
+
|
1812 |
+
Returns
|
1813 |
+
=======
|
1814 |
+
|
1815 |
+
bisector : Line or Segment
|
1816 |
+
|
1817 |
+
See Also
|
1818 |
+
========
|
1819 |
+
|
1820 |
+
LinearEntity.perpendicular_segment
|
1821 |
+
|
1822 |
+
Examples
|
1823 |
+
========
|
1824 |
+
|
1825 |
+
>>> from sympy import Point, Segment
|
1826 |
+
>>> p1, p2, p3 = Point(0, 0), Point(6, 6), Point(5, 1)
|
1827 |
+
>>> s1 = Segment(p1, p2)
|
1828 |
+
>>> s1.perpendicular_bisector()
|
1829 |
+
Line2D(Point2D(3, 3), Point2D(-3, 9))
|
1830 |
+
|
1831 |
+
>>> s1.perpendicular_bisector(p3)
|
1832 |
+
Segment2D(Point2D(5, 1), Point2D(3, 3))
|
1833 |
+
|
1834 |
+
"""
|
1835 |
+
l = self.perpendicular_line(self.midpoint)
|
1836 |
+
if p is not None:
|
1837 |
+
p2 = Point(p, dim=self.ambient_dimension)
|
1838 |
+
if p2 in l:
|
1839 |
+
return Segment(p2, self.midpoint)
|
1840 |
+
return l
|
1841 |
+
|
1842 |
+
def plot_interval(self, parameter='t'):
|
1843 |
+
"""The plot interval for the default geometric plot of the Segment gives
|
1844 |
+
values that will produce the full segment in a plot.
|
1845 |
+
|
1846 |
+
Parameters
|
1847 |
+
==========
|
1848 |
+
|
1849 |
+
parameter : str, optional
|
1850 |
+
Default value is 't'.
|
1851 |
+
|
1852 |
+
Returns
|
1853 |
+
=======
|
1854 |
+
|
1855 |
+
plot_interval : list
|
1856 |
+
[parameter, lower_bound, upper_bound]
|
1857 |
+
|
1858 |
+
Examples
|
1859 |
+
========
|
1860 |
+
|
1861 |
+
>>> from sympy import Point, Segment
|
1862 |
+
>>> p1, p2 = Point(0, 0), Point(5, 3)
|
1863 |
+
>>> s1 = Segment(p1, p2)
|
1864 |
+
>>> s1.plot_interval()
|
1865 |
+
[t, 0, 1]
|
1866 |
+
|
1867 |
+
"""
|
1868 |
+
t = _symbol(parameter, real=True)
|
1869 |
+
return [t, 0, 1]
|
1870 |
+
|
1871 |
+
|
1872 |
+
class LinearEntity2D(LinearEntity):
|
1873 |
+
"""A base class for all linear entities (line, ray and segment)
|
1874 |
+
in a 2-dimensional Euclidean space.
|
1875 |
+
|
1876 |
+
Attributes
|
1877 |
+
==========
|
1878 |
+
|
1879 |
+
p1
|
1880 |
+
p2
|
1881 |
+
coefficients
|
1882 |
+
slope
|
1883 |
+
points
|
1884 |
+
|
1885 |
+
Notes
|
1886 |
+
=====
|
1887 |
+
|
1888 |
+
This is an abstract class and is not meant to be instantiated.
|
1889 |
+
|
1890 |
+
See Also
|
1891 |
+
========
|
1892 |
+
|
1893 |
+
sympy.geometry.entity.GeometryEntity
|
1894 |
+
|
1895 |
+
"""
|
1896 |
+
@property
|
1897 |
+
def bounds(self):
|
1898 |
+
"""Return a tuple (xmin, ymin, xmax, ymax) representing the bounding
|
1899 |
+
rectangle for the geometric figure.
|
1900 |
+
|
1901 |
+
"""
|
1902 |
+
verts = self.points
|
1903 |
+
xs = [p.x for p in verts]
|
1904 |
+
ys = [p.y for p in verts]
|
1905 |
+
return (min(xs), min(ys), max(xs), max(ys))
|
1906 |
+
|
1907 |
+
def perpendicular_line(self, p):
|
1908 |
+
"""Create a new Line perpendicular to this linear entity which passes
|
1909 |
+
through the point `p`.
|
1910 |
+
|
1911 |
+
Parameters
|
1912 |
+
==========
|
1913 |
+
|
1914 |
+
p : Point
|
1915 |
+
|
1916 |
+
Returns
|
1917 |
+
=======
|
1918 |
+
|
1919 |
+
line : Line
|
1920 |
+
|
1921 |
+
See Also
|
1922 |
+
========
|
1923 |
+
|
1924 |
+
sympy.geometry.line.LinearEntity.is_perpendicular, perpendicular_segment
|
1925 |
+
|
1926 |
+
Examples
|
1927 |
+
========
|
1928 |
+
|
1929 |
+
>>> from sympy import Point, Line
|
1930 |
+
>>> p1, p2, p3 = Point(0, 0), Point(2, 3), Point(-2, 2)
|
1931 |
+
>>> L = Line(p1, p2)
|
1932 |
+
>>> P = L.perpendicular_line(p3); P
|
1933 |
+
Line2D(Point2D(-2, 2), Point2D(-5, 4))
|
1934 |
+
>>> L.is_perpendicular(P)
|
1935 |
+
True
|
1936 |
+
|
1937 |
+
In 2D, the first point of the perpendicular line is the
|
1938 |
+
point through which was required to pass; the second
|
1939 |
+
point is arbitrarily chosen. To get a line that explicitly
|
1940 |
+
uses a point in the line, create a line from the perpendicular
|
1941 |
+
segment from the line to the point:
|
1942 |
+
|
1943 |
+
>>> Line(L.perpendicular_segment(p3))
|
1944 |
+
Line2D(Point2D(-2, 2), Point2D(4/13, 6/13))
|
1945 |
+
"""
|
1946 |
+
p = Point(p, dim=self.ambient_dimension)
|
1947 |
+
# any two lines in R^2 intersect, so blindly making
|
1948 |
+
# a line through p in an orthogonal direction will work
|
1949 |
+
# and is faster than finding the projection point as in 3D
|
1950 |
+
return Line(p, p + self.direction.orthogonal_direction)
|
1951 |
+
|
1952 |
+
@property
|
1953 |
+
def slope(self):
|
1954 |
+
"""The slope of this linear entity, or infinity if vertical.
|
1955 |
+
|
1956 |
+
Returns
|
1957 |
+
=======
|
1958 |
+
|
1959 |
+
slope : number or SymPy expression
|
1960 |
+
|
1961 |
+
See Also
|
1962 |
+
========
|
1963 |
+
|
1964 |
+
coefficients
|
1965 |
+
|
1966 |
+
Examples
|
1967 |
+
========
|
1968 |
+
|
1969 |
+
>>> from sympy import Point, Line
|
1970 |
+
>>> p1, p2 = Point(0, 0), Point(3, 5)
|
1971 |
+
>>> l1 = Line(p1, p2)
|
1972 |
+
>>> l1.slope
|
1973 |
+
5/3
|
1974 |
+
|
1975 |
+
>>> p3 = Point(0, 4)
|
1976 |
+
>>> l2 = Line(p1, p3)
|
1977 |
+
>>> l2.slope
|
1978 |
+
oo
|
1979 |
+
|
1980 |
+
"""
|
1981 |
+
d1, d2 = (self.p1 - self.p2).args
|
1982 |
+
if d1 == 0:
|
1983 |
+
return S.Infinity
|
1984 |
+
return simplify(d2/d1)
|
1985 |
+
|
1986 |
+
|
1987 |
+
class Line2D(LinearEntity2D, Line):
|
1988 |
+
"""An infinite line in space 2D.
|
1989 |
+
|
1990 |
+
A line is declared with two distinct points or a point and slope
|
1991 |
+
as defined using keyword `slope`.
|
1992 |
+
|
1993 |
+
Parameters
|
1994 |
+
==========
|
1995 |
+
|
1996 |
+
p1 : Point
|
1997 |
+
pt : Point
|
1998 |
+
slope : SymPy expression
|
1999 |
+
|
2000 |
+
See Also
|
2001 |
+
========
|
2002 |
+
|
2003 |
+
sympy.geometry.point.Point
|
2004 |
+
|
2005 |
+
Examples
|
2006 |
+
========
|
2007 |
+
|
2008 |
+
>>> from sympy import Line, Segment, Point
|
2009 |
+
>>> L = Line(Point(2,3), Point(3,5))
|
2010 |
+
>>> L
|
2011 |
+
Line2D(Point2D(2, 3), Point2D(3, 5))
|
2012 |
+
>>> L.points
|
2013 |
+
(Point2D(2, 3), Point2D(3, 5))
|
2014 |
+
>>> L.equation()
|
2015 |
+
-2*x + y + 1
|
2016 |
+
>>> L.coefficients
|
2017 |
+
(-2, 1, 1)
|
2018 |
+
|
2019 |
+
Instantiate with keyword ``slope``:
|
2020 |
+
|
2021 |
+
>>> Line(Point(0, 0), slope=0)
|
2022 |
+
Line2D(Point2D(0, 0), Point2D(1, 0))
|
2023 |
+
|
2024 |
+
Instantiate with another linear object
|
2025 |
+
|
2026 |
+
>>> s = Segment((0, 0), (0, 1))
|
2027 |
+
>>> Line(s).equation()
|
2028 |
+
x
|
2029 |
+
"""
|
2030 |
+
def __new__(cls, p1, pt=None, slope=None, **kwargs):
|
2031 |
+
if isinstance(p1, LinearEntity):
|
2032 |
+
if pt is not None:
|
2033 |
+
raise ValueError('When p1 is a LinearEntity, pt should be None')
|
2034 |
+
p1, pt = Point._normalize_dimension(*p1.args, dim=2)
|
2035 |
+
else:
|
2036 |
+
p1 = Point(p1, dim=2)
|
2037 |
+
if pt is not None and slope is None:
|
2038 |
+
try:
|
2039 |
+
p2 = Point(pt, dim=2)
|
2040 |
+
except (NotImplementedError, TypeError, ValueError):
|
2041 |
+
raise ValueError(filldedent('''
|
2042 |
+
The 2nd argument was not a valid Point.
|
2043 |
+
If it was a slope, enter it with keyword "slope".
|
2044 |
+
'''))
|
2045 |
+
elif slope is not None and pt is None:
|
2046 |
+
slope = sympify(slope)
|
2047 |
+
if slope.is_finite is False:
|
2048 |
+
# when infinite slope, don't change x
|
2049 |
+
dx = 0
|
2050 |
+
dy = 1
|
2051 |
+
else:
|
2052 |
+
# go over 1 up slope
|
2053 |
+
dx = 1
|
2054 |
+
dy = slope
|
2055 |
+
# XXX avoiding simplification by adding to coords directly
|
2056 |
+
p2 = Point(p1.x + dx, p1.y + dy, evaluate=False)
|
2057 |
+
else:
|
2058 |
+
raise ValueError('A 2nd Point or keyword "slope" must be used.')
|
2059 |
+
return LinearEntity2D.__new__(cls, p1, p2, **kwargs)
|
2060 |
+
|
2061 |
+
def _svg(self, scale_factor=1., fill_color="#66cc99"):
|
2062 |
+
"""Returns SVG path element for the LinearEntity.
|
2063 |
+
|
2064 |
+
Parameters
|
2065 |
+
==========
|
2066 |
+
|
2067 |
+
scale_factor : float
|
2068 |
+
Multiplication factor for the SVG stroke-width. Default is 1.
|
2069 |
+
fill_color : str, optional
|
2070 |
+
Hex string for fill color. Default is "#66cc99".
|
2071 |
+
"""
|
2072 |
+
verts = (N(self.p1), N(self.p2))
|
2073 |
+
coords = ["{},{}".format(p.x, p.y) for p in verts]
|
2074 |
+
path = "M {} L {}".format(coords[0], " L ".join(coords[1:]))
|
2075 |
+
|
2076 |
+
return (
|
2077 |
+
'<path fill-rule="evenodd" fill="{2}" stroke="#555555" '
|
2078 |
+
'stroke-width="{0}" opacity="0.6" d="{1}" '
|
2079 |
+
'marker-start="url(#markerReverseArrow)" marker-end="url(#markerArrow)"/>'
|
2080 |
+
).format(2.*scale_factor, path, fill_color)
|
2081 |
+
|
2082 |
+
@property
|
2083 |
+
def coefficients(self):
|
2084 |
+
"""The coefficients (`a`, `b`, `c`) for `ax + by + c = 0`.
|
2085 |
+
|
2086 |
+
See Also
|
2087 |
+
========
|
2088 |
+
|
2089 |
+
sympy.geometry.line.Line2D.equation
|
2090 |
+
|
2091 |
+
Examples
|
2092 |
+
========
|
2093 |
+
|
2094 |
+
>>> from sympy import Point, Line
|
2095 |
+
>>> from sympy.abc import x, y
|
2096 |
+
>>> p1, p2 = Point(0, 0), Point(5, 3)
|
2097 |
+
>>> l = Line(p1, p2)
|
2098 |
+
>>> l.coefficients
|
2099 |
+
(-3, 5, 0)
|
2100 |
+
|
2101 |
+
>>> p3 = Point(x, y)
|
2102 |
+
>>> l2 = Line(p1, p3)
|
2103 |
+
>>> l2.coefficients
|
2104 |
+
(-y, x, 0)
|
2105 |
+
|
2106 |
+
"""
|
2107 |
+
p1, p2 = self.points
|
2108 |
+
if p1.x == p2.x:
|
2109 |
+
return (S.One, S.Zero, -p1.x)
|
2110 |
+
elif p1.y == p2.y:
|
2111 |
+
return (S.Zero, S.One, -p1.y)
|
2112 |
+
return tuple([simplify(i) for i in
|
2113 |
+
(self.p1.y - self.p2.y,
|
2114 |
+
self.p2.x - self.p1.x,
|
2115 |
+
self.p1.x*self.p2.y - self.p1.y*self.p2.x)])
|
2116 |
+
|
2117 |
+
def equation(self, x='x', y='y'):
|
2118 |
+
"""The equation of the line: ax + by + c.
|
2119 |
+
|
2120 |
+
Parameters
|
2121 |
+
==========
|
2122 |
+
|
2123 |
+
x : str, optional
|
2124 |
+
The name to use for the x-axis, default value is 'x'.
|
2125 |
+
y : str, optional
|
2126 |
+
The name to use for the y-axis, default value is 'y'.
|
2127 |
+
|
2128 |
+
Returns
|
2129 |
+
=======
|
2130 |
+
|
2131 |
+
equation : SymPy expression
|
2132 |
+
|
2133 |
+
See Also
|
2134 |
+
========
|
2135 |
+
|
2136 |
+
sympy.geometry.line.Line2D.coefficients
|
2137 |
+
|
2138 |
+
Examples
|
2139 |
+
========
|
2140 |
+
|
2141 |
+
>>> from sympy import Point, Line
|
2142 |
+
>>> p1, p2 = Point(1, 0), Point(5, 3)
|
2143 |
+
>>> l1 = Line(p1, p2)
|
2144 |
+
>>> l1.equation()
|
2145 |
+
-3*x + 4*y + 3
|
2146 |
+
|
2147 |
+
"""
|
2148 |
+
x = _symbol(x, real=True)
|
2149 |
+
y = _symbol(y, real=True)
|
2150 |
+
p1, p2 = self.points
|
2151 |
+
if p1.x == p2.x:
|
2152 |
+
return x - p1.x
|
2153 |
+
elif p1.y == p2.y:
|
2154 |
+
return y - p1.y
|
2155 |
+
|
2156 |
+
a, b, c = self.coefficients
|
2157 |
+
return a*x + b*y + c
|
2158 |
+
|
2159 |
+
|
2160 |
+
class Ray2D(LinearEntity2D, Ray):
|
2161 |
+
"""
|
2162 |
+
A Ray is a semi-line in the space with a source point and a direction.
|
2163 |
+
|
2164 |
+
Parameters
|
2165 |
+
==========
|
2166 |
+
|
2167 |
+
p1 : Point
|
2168 |
+
The source of the Ray
|
2169 |
+
p2 : Point or radian value
|
2170 |
+
This point determines the direction in which the Ray propagates.
|
2171 |
+
If given as an angle it is interpreted in radians with the positive
|
2172 |
+
direction being ccw.
|
2173 |
+
|
2174 |
+
Attributes
|
2175 |
+
==========
|
2176 |
+
|
2177 |
+
source
|
2178 |
+
xdirection
|
2179 |
+
ydirection
|
2180 |
+
|
2181 |
+
See Also
|
2182 |
+
========
|
2183 |
+
|
2184 |
+
sympy.geometry.point.Point, Line
|
2185 |
+
|
2186 |
+
Examples
|
2187 |
+
========
|
2188 |
+
|
2189 |
+
>>> from sympy import Point, pi, Ray
|
2190 |
+
>>> r = Ray(Point(2, 3), Point(3, 5))
|
2191 |
+
>>> r
|
2192 |
+
Ray2D(Point2D(2, 3), Point2D(3, 5))
|
2193 |
+
>>> r.points
|
2194 |
+
(Point2D(2, 3), Point2D(3, 5))
|
2195 |
+
>>> r.source
|
2196 |
+
Point2D(2, 3)
|
2197 |
+
>>> r.xdirection
|
2198 |
+
oo
|
2199 |
+
>>> r.ydirection
|
2200 |
+
oo
|
2201 |
+
>>> r.slope
|
2202 |
+
2
|
2203 |
+
>>> Ray(Point(0, 0), angle=pi/4).slope
|
2204 |
+
1
|
2205 |
+
|
2206 |
+
"""
|
2207 |
+
def __new__(cls, p1, pt=None, angle=None, **kwargs):
|
2208 |
+
p1 = Point(p1, dim=2)
|
2209 |
+
if pt is not None and angle is None:
|
2210 |
+
try:
|
2211 |
+
p2 = Point(pt, dim=2)
|
2212 |
+
except (NotImplementedError, TypeError, ValueError):
|
2213 |
+
raise ValueError(filldedent('''
|
2214 |
+
The 2nd argument was not a valid Point; if
|
2215 |
+
it was meant to be an angle it should be
|
2216 |
+
given with keyword "angle".'''))
|
2217 |
+
if p1 == p2:
|
2218 |
+
raise ValueError('A Ray requires two distinct points.')
|
2219 |
+
elif angle is not None and pt is None:
|
2220 |
+
# we need to know if the angle is an odd multiple of pi/2
|
2221 |
+
angle = sympify(angle)
|
2222 |
+
c = _pi_coeff(angle)
|
2223 |
+
p2 = None
|
2224 |
+
if c is not None:
|
2225 |
+
if c.is_Rational:
|
2226 |
+
if c.q == 2:
|
2227 |
+
if c.p == 1:
|
2228 |
+
p2 = p1 + Point(0, 1)
|
2229 |
+
elif c.p == 3:
|
2230 |
+
p2 = p1 + Point(0, -1)
|
2231 |
+
elif c.q == 1:
|
2232 |
+
if c.p == 0:
|
2233 |
+
p2 = p1 + Point(1, 0)
|
2234 |
+
elif c.p == 1:
|
2235 |
+
p2 = p1 + Point(-1, 0)
|
2236 |
+
if p2 is None:
|
2237 |
+
c *= S.Pi
|
2238 |
+
else:
|
2239 |
+
c = angle % (2*S.Pi)
|
2240 |
+
if not p2:
|
2241 |
+
m = 2*c/S.Pi
|
2242 |
+
left = And(1 < m, m < 3) # is it in quadrant 2 or 3?
|
2243 |
+
x = Piecewise((-1, left), (Piecewise((0, Eq(m % 1, 0)), (1, True)), True))
|
2244 |
+
y = Piecewise((-tan(c), left), (Piecewise((1, Eq(m, 1)), (-1, Eq(m, 3)), (tan(c), True)), True))
|
2245 |
+
p2 = p1 + Point(x, y)
|
2246 |
+
else:
|
2247 |
+
raise ValueError('A 2nd point or keyword "angle" must be used.')
|
2248 |
+
|
2249 |
+
return LinearEntity2D.__new__(cls, p1, p2, **kwargs)
|
2250 |
+
|
2251 |
+
@property
|
2252 |
+
def xdirection(self):
|
2253 |
+
"""The x direction of the ray.
|
2254 |
+
|
2255 |
+
Positive infinity if the ray points in the positive x direction,
|
2256 |
+
negative infinity if the ray points in the negative x direction,
|
2257 |
+
or 0 if the ray is vertical.
|
2258 |
+
|
2259 |
+
See Also
|
2260 |
+
========
|
2261 |
+
|
2262 |
+
ydirection
|
2263 |
+
|
2264 |
+
Examples
|
2265 |
+
========
|
2266 |
+
|
2267 |
+
>>> from sympy import Point, Ray
|
2268 |
+
>>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(0, -1)
|
2269 |
+
>>> r1, r2 = Ray(p1, p2), Ray(p1, p3)
|
2270 |
+
>>> r1.xdirection
|
2271 |
+
oo
|
2272 |
+
>>> r2.xdirection
|
2273 |
+
0
|
2274 |
+
|
2275 |
+
"""
|
2276 |
+
if self.p1.x < self.p2.x:
|
2277 |
+
return S.Infinity
|
2278 |
+
elif self.p1.x == self.p2.x:
|
2279 |
+
return S.Zero
|
2280 |
+
else:
|
2281 |
+
return S.NegativeInfinity
|
2282 |
+
|
2283 |
+
@property
|
2284 |
+
def ydirection(self):
|
2285 |
+
"""The y direction of the ray.
|
2286 |
+
|
2287 |
+
Positive infinity if the ray points in the positive y direction,
|
2288 |
+
negative infinity if the ray points in the negative y direction,
|
2289 |
+
or 0 if the ray is horizontal.
|
2290 |
+
|
2291 |
+
See Also
|
2292 |
+
========
|
2293 |
+
|
2294 |
+
xdirection
|
2295 |
+
|
2296 |
+
Examples
|
2297 |
+
========
|
2298 |
+
|
2299 |
+
>>> from sympy import Point, Ray
|
2300 |
+
>>> p1, p2, p3 = Point(0, 0), Point(-1, -1), Point(-1, 0)
|
2301 |
+
>>> r1, r2 = Ray(p1, p2), Ray(p1, p3)
|
2302 |
+
>>> r1.ydirection
|
2303 |
+
-oo
|
2304 |
+
>>> r2.ydirection
|
2305 |
+
0
|
2306 |
+
|
2307 |
+
"""
|
2308 |
+
if self.p1.y < self.p2.y:
|
2309 |
+
return S.Infinity
|
2310 |
+
elif self.p1.y == self.p2.y:
|
2311 |
+
return S.Zero
|
2312 |
+
else:
|
2313 |
+
return S.NegativeInfinity
|
2314 |
+
|
2315 |
+
def closing_angle(r1, r2):
|
2316 |
+
"""Return the angle by which r2 must be rotated so it faces the same
|
2317 |
+
direction as r1.
|
2318 |
+
|
2319 |
+
Parameters
|
2320 |
+
==========
|
2321 |
+
|
2322 |
+
r1 : Ray2D
|
2323 |
+
r2 : Ray2D
|
2324 |
+
|
2325 |
+
Returns
|
2326 |
+
=======
|
2327 |
+
|
2328 |
+
angle : angle in radians (ccw angle is positive)
|
2329 |
+
|
2330 |
+
See Also
|
2331 |
+
========
|
2332 |
+
|
2333 |
+
LinearEntity.angle_between
|
2334 |
+
|
2335 |
+
Examples
|
2336 |
+
========
|
2337 |
+
|
2338 |
+
>>> from sympy import Ray, pi
|
2339 |
+
>>> r1 = Ray((0, 0), (1, 0))
|
2340 |
+
>>> r2 = r1.rotate(-pi/2)
|
2341 |
+
>>> angle = r1.closing_angle(r2); angle
|
2342 |
+
pi/2
|
2343 |
+
>>> r2.rotate(angle).direction.unit == r1.direction.unit
|
2344 |
+
True
|
2345 |
+
>>> r2.closing_angle(r1)
|
2346 |
+
-pi/2
|
2347 |
+
"""
|
2348 |
+
if not all(isinstance(r, Ray2D) for r in (r1, r2)):
|
2349 |
+
# although the direction property is defined for
|
2350 |
+
# all linear entities, only the Ray is truly a
|
2351 |
+
# directed object
|
2352 |
+
raise TypeError('Both arguments must be Ray2D objects.')
|
2353 |
+
|
2354 |
+
a1 = atan2(*list(reversed(r1.direction.args)))
|
2355 |
+
a2 = atan2(*list(reversed(r2.direction.args)))
|
2356 |
+
if a1*a2 < 0:
|
2357 |
+
a1 = 2*S.Pi + a1 if a1 < 0 else a1
|
2358 |
+
a2 = 2*S.Pi + a2 if a2 < 0 else a2
|
2359 |
+
return a1 - a2
|
2360 |
+
|
2361 |
+
|
2362 |
+
class Segment2D(LinearEntity2D, Segment):
|
2363 |
+
"""A line segment in 2D space.
|
2364 |
+
|
2365 |
+
Parameters
|
2366 |
+
==========
|
2367 |
+
|
2368 |
+
p1 : Point
|
2369 |
+
p2 : Point
|
2370 |
+
|
2371 |
+
Attributes
|
2372 |
+
==========
|
2373 |
+
|
2374 |
+
length : number or SymPy expression
|
2375 |
+
midpoint : Point
|
2376 |
+
|
2377 |
+
See Also
|
2378 |
+
========
|
2379 |
+
|
2380 |
+
sympy.geometry.point.Point, Line
|
2381 |
+
|
2382 |
+
Examples
|
2383 |
+
========
|
2384 |
+
|
2385 |
+
>>> from sympy import Point, Segment
|
2386 |
+
>>> Segment((1, 0), (1, 1)) # tuples are interpreted as pts
|
2387 |
+
Segment2D(Point2D(1, 0), Point2D(1, 1))
|
2388 |
+
>>> s = Segment(Point(4, 3), Point(1, 1)); s
|
2389 |
+
Segment2D(Point2D(4, 3), Point2D(1, 1))
|
2390 |
+
>>> s.points
|
2391 |
+
(Point2D(4, 3), Point2D(1, 1))
|
2392 |
+
>>> s.slope
|
2393 |
+
2/3
|
2394 |
+
>>> s.length
|
2395 |
+
sqrt(13)
|
2396 |
+
>>> s.midpoint
|
2397 |
+
Point2D(5/2, 2)
|
2398 |
+
|
2399 |
+
"""
|
2400 |
+
def __new__(cls, p1, p2, **kwargs):
|
2401 |
+
p1 = Point(p1, dim=2)
|
2402 |
+
p2 = Point(p2, dim=2)
|
2403 |
+
|
2404 |
+
if p1 == p2:
|
2405 |
+
return p1
|
2406 |
+
|
2407 |
+
return LinearEntity2D.__new__(cls, p1, p2, **kwargs)
|
2408 |
+
|
2409 |
+
def _svg(self, scale_factor=1., fill_color="#66cc99"):
|
2410 |
+
"""Returns SVG path element for the LinearEntity.
|
2411 |
+
|
2412 |
+
Parameters
|
2413 |
+
==========
|
2414 |
+
|
2415 |
+
scale_factor : float
|
2416 |
+
Multiplication factor for the SVG stroke-width. Default is 1.
|
2417 |
+
fill_color : str, optional
|
2418 |
+
Hex string for fill color. Default is "#66cc99".
|
2419 |
+
"""
|
2420 |
+
verts = (N(self.p1), N(self.p2))
|
2421 |
+
coords = ["{},{}".format(p.x, p.y) for p in verts]
|
2422 |
+
path = "M {} L {}".format(coords[0], " L ".join(coords[1:]))
|
2423 |
+
return (
|
2424 |
+
'<path fill-rule="evenodd" fill="{2}" stroke="#555555" '
|
2425 |
+
'stroke-width="{0}" opacity="0.6" d="{1}" />'
|
2426 |
+
).format(2.*scale_factor, path, fill_color)
|
2427 |
+
|
2428 |
+
|
2429 |
+
class LinearEntity3D(LinearEntity):
|
2430 |
+
"""An base class for all linear entities (line, ray and segment)
|
2431 |
+
in a 3-dimensional Euclidean space.
|
2432 |
+
|
2433 |
+
Attributes
|
2434 |
+
==========
|
2435 |
+
|
2436 |
+
p1
|
2437 |
+
p2
|
2438 |
+
direction_ratio
|
2439 |
+
direction_cosine
|
2440 |
+
points
|
2441 |
+
|
2442 |
+
Notes
|
2443 |
+
=====
|
2444 |
+
|
2445 |
+
This is a base class and is not meant to be instantiated.
|
2446 |
+
"""
|
2447 |
+
def __new__(cls, p1, p2, **kwargs):
|
2448 |
+
p1 = Point3D(p1, dim=3)
|
2449 |
+
p2 = Point3D(p2, dim=3)
|
2450 |
+
if p1 == p2:
|
2451 |
+
# if it makes sense to return a Point, handle in subclass
|
2452 |
+
raise ValueError(
|
2453 |
+
"%s.__new__ requires two unique Points." % cls.__name__)
|
2454 |
+
|
2455 |
+
return GeometryEntity.__new__(cls, p1, p2, **kwargs)
|
2456 |
+
|
2457 |
+
ambient_dimension = 3
|
2458 |
+
|
2459 |
+
@property
|
2460 |
+
def direction_ratio(self):
|
2461 |
+
"""The direction ratio of a given line in 3D.
|
2462 |
+
|
2463 |
+
See Also
|
2464 |
+
========
|
2465 |
+
|
2466 |
+
sympy.geometry.line.Line3D.equation
|
2467 |
+
|
2468 |
+
Examples
|
2469 |
+
========
|
2470 |
+
|
2471 |
+
>>> from sympy import Point3D, Line3D
|
2472 |
+
>>> p1, p2 = Point3D(0, 0, 0), Point3D(5, 3, 1)
|
2473 |
+
>>> l = Line3D(p1, p2)
|
2474 |
+
>>> l.direction_ratio
|
2475 |
+
[5, 3, 1]
|
2476 |
+
"""
|
2477 |
+
p1, p2 = self.points
|
2478 |
+
return p1.direction_ratio(p2)
|
2479 |
+
|
2480 |
+
@property
|
2481 |
+
def direction_cosine(self):
|
2482 |
+
"""The normalized direction ratio of a given line in 3D.
|
2483 |
+
|
2484 |
+
See Also
|
2485 |
+
========
|
2486 |
+
|
2487 |
+
sympy.geometry.line.Line3D.equation
|
2488 |
+
|
2489 |
+
Examples
|
2490 |
+
========
|
2491 |
+
|
2492 |
+
>>> from sympy import Point3D, Line3D
|
2493 |
+
>>> p1, p2 = Point3D(0, 0, 0), Point3D(5, 3, 1)
|
2494 |
+
>>> l = Line3D(p1, p2)
|
2495 |
+
>>> l.direction_cosine
|
2496 |
+
[sqrt(35)/7, 3*sqrt(35)/35, sqrt(35)/35]
|
2497 |
+
>>> sum(i**2 for i in _)
|
2498 |
+
1
|
2499 |
+
"""
|
2500 |
+
p1, p2 = self.points
|
2501 |
+
return p1.direction_cosine(p2)
|
2502 |
+
|
2503 |
+
|
2504 |
+
class Line3D(LinearEntity3D, Line):
|
2505 |
+
"""An infinite 3D line in space.
|
2506 |
+
|
2507 |
+
A line is declared with two distinct points or a point and direction_ratio
|
2508 |
+
as defined using keyword `direction_ratio`.
|
2509 |
+
|
2510 |
+
Parameters
|
2511 |
+
==========
|
2512 |
+
|
2513 |
+
p1 : Point3D
|
2514 |
+
pt : Point3D
|
2515 |
+
direction_ratio : list
|
2516 |
+
|
2517 |
+
See Also
|
2518 |
+
========
|
2519 |
+
|
2520 |
+
sympy.geometry.point.Point3D
|
2521 |
+
sympy.geometry.line.Line
|
2522 |
+
sympy.geometry.line.Line2D
|
2523 |
+
|
2524 |
+
Examples
|
2525 |
+
========
|
2526 |
+
|
2527 |
+
>>> from sympy import Line3D, Point3D
|
2528 |
+
>>> L = Line3D(Point3D(2, 3, 4), Point3D(3, 5, 1))
|
2529 |
+
>>> L
|
2530 |
+
Line3D(Point3D(2, 3, 4), Point3D(3, 5, 1))
|
2531 |
+
>>> L.points
|
2532 |
+
(Point3D(2, 3, 4), Point3D(3, 5, 1))
|
2533 |
+
"""
|
2534 |
+
def __new__(cls, p1, pt=None, direction_ratio=(), **kwargs):
|
2535 |
+
if isinstance(p1, LinearEntity3D):
|
2536 |
+
if pt is not None:
|
2537 |
+
raise ValueError('if p1 is a LinearEntity, pt must be None.')
|
2538 |
+
p1, pt = p1.args
|
2539 |
+
else:
|
2540 |
+
p1 = Point(p1, dim=3)
|
2541 |
+
if pt is not None and len(direction_ratio) == 0:
|
2542 |
+
pt = Point(pt, dim=3)
|
2543 |
+
elif len(direction_ratio) == 3 and pt is None:
|
2544 |
+
pt = Point3D(p1.x + direction_ratio[0], p1.y + direction_ratio[1],
|
2545 |
+
p1.z + direction_ratio[2])
|
2546 |
+
else:
|
2547 |
+
raise ValueError('A 2nd Point or keyword "direction_ratio" must '
|
2548 |
+
'be used.')
|
2549 |
+
|
2550 |
+
return LinearEntity3D.__new__(cls, p1, pt, **kwargs)
|
2551 |
+
|
2552 |
+
def equation(self, x='x', y='y', z='z'):
|
2553 |
+
"""Return the equations that define the line in 3D.
|
2554 |
+
|
2555 |
+
Parameters
|
2556 |
+
==========
|
2557 |
+
|
2558 |
+
x : str, optional
|
2559 |
+
The name to use for the x-axis, default value is 'x'.
|
2560 |
+
y : str, optional
|
2561 |
+
The name to use for the y-axis, default value is 'y'.
|
2562 |
+
z : str, optional
|
2563 |
+
The name to use for the z-axis, default value is 'z'.
|
2564 |
+
|
2565 |
+
Returns
|
2566 |
+
=======
|
2567 |
+
|
2568 |
+
equation : Tuple of simultaneous equations
|
2569 |
+
|
2570 |
+
Examples
|
2571 |
+
========
|
2572 |
+
|
2573 |
+
>>> from sympy import Point3D, Line3D, solve
|
2574 |
+
>>> from sympy.abc import x, y, z
|
2575 |
+
>>> p1, p2 = Point3D(1, 0, 0), Point3D(5, 3, 0)
|
2576 |
+
>>> l1 = Line3D(p1, p2)
|
2577 |
+
>>> eq = l1.equation(x, y, z); eq
|
2578 |
+
(-3*x + 4*y + 3, z)
|
2579 |
+
>>> solve(eq.subs(z, 0), (x, y, z))
|
2580 |
+
{x: 4*y/3 + 1}
|
2581 |
+
"""
|
2582 |
+
x, y, z, k = [_symbol(i, real=True) for i in (x, y, z, 'k')]
|
2583 |
+
p1, p2 = self.points
|
2584 |
+
d1, d2, d3 = p1.direction_ratio(p2)
|
2585 |
+
x1, y1, z1 = p1
|
2586 |
+
eqs = [-d1*k + x - x1, -d2*k + y - y1, -d3*k + z - z1]
|
2587 |
+
# eliminate k from equations by solving first eq with k for k
|
2588 |
+
for i, e in enumerate(eqs):
|
2589 |
+
if e.has(k):
|
2590 |
+
kk = solve(eqs[i], k)[0]
|
2591 |
+
eqs.pop(i)
|
2592 |
+
break
|
2593 |
+
return Tuple(*[i.subs(k, kk).as_numer_denom()[0] for i in eqs])
|
2594 |
+
|
2595 |
+
|
2596 |
+
class Ray3D(LinearEntity3D, Ray):
|
2597 |
+
"""
|
2598 |
+
A Ray is a semi-line in the space with a source point and a direction.
|
2599 |
+
|
2600 |
+
Parameters
|
2601 |
+
==========
|
2602 |
+
|
2603 |
+
p1 : Point3D
|
2604 |
+
The source of the Ray
|
2605 |
+
p2 : Point or a direction vector
|
2606 |
+
direction_ratio: Determines the direction in which the Ray propagates.
|
2607 |
+
|
2608 |
+
|
2609 |
+
Attributes
|
2610 |
+
==========
|
2611 |
+
|
2612 |
+
source
|
2613 |
+
xdirection
|
2614 |
+
ydirection
|
2615 |
+
zdirection
|
2616 |
+
|
2617 |
+
See Also
|
2618 |
+
========
|
2619 |
+
|
2620 |
+
sympy.geometry.point.Point3D, Line3D
|
2621 |
+
|
2622 |
+
|
2623 |
+
Examples
|
2624 |
+
========
|
2625 |
+
|
2626 |
+
>>> from sympy import Point3D, Ray3D
|
2627 |
+
>>> r = Ray3D(Point3D(2, 3, 4), Point3D(3, 5, 0))
|
2628 |
+
>>> r
|
2629 |
+
Ray3D(Point3D(2, 3, 4), Point3D(3, 5, 0))
|
2630 |
+
>>> r.points
|
2631 |
+
(Point3D(2, 3, 4), Point3D(3, 5, 0))
|
2632 |
+
>>> r.source
|
2633 |
+
Point3D(2, 3, 4)
|
2634 |
+
>>> r.xdirection
|
2635 |
+
oo
|
2636 |
+
>>> r.ydirection
|
2637 |
+
oo
|
2638 |
+
>>> r.direction_ratio
|
2639 |
+
[1, 2, -4]
|
2640 |
+
|
2641 |
+
"""
|
2642 |
+
def __new__(cls, p1, pt=None, direction_ratio=(), **kwargs):
|
2643 |
+
if isinstance(p1, LinearEntity3D):
|
2644 |
+
if pt is not None:
|
2645 |
+
raise ValueError('If p1 is a LinearEntity, pt must be None')
|
2646 |
+
p1, pt = p1.args
|
2647 |
+
else:
|
2648 |
+
p1 = Point(p1, dim=3)
|
2649 |
+
if pt is not None and len(direction_ratio) == 0:
|
2650 |
+
pt = Point(pt, dim=3)
|
2651 |
+
elif len(direction_ratio) == 3 and pt is None:
|
2652 |
+
pt = Point3D(p1.x + direction_ratio[0], p1.y + direction_ratio[1],
|
2653 |
+
p1.z + direction_ratio[2])
|
2654 |
+
else:
|
2655 |
+
raise ValueError(filldedent('''
|
2656 |
+
A 2nd Point or keyword "direction_ratio" must be used.
|
2657 |
+
'''))
|
2658 |
+
|
2659 |
+
return LinearEntity3D.__new__(cls, p1, pt, **kwargs)
|
2660 |
+
|
2661 |
+
@property
|
2662 |
+
def xdirection(self):
|
2663 |
+
"""The x direction of the ray.
|
2664 |
+
|
2665 |
+
Positive infinity if the ray points in the positive x direction,
|
2666 |
+
negative infinity if the ray points in the negative x direction,
|
2667 |
+
or 0 if the ray is vertical.
|
2668 |
+
|
2669 |
+
See Also
|
2670 |
+
========
|
2671 |
+
|
2672 |
+
ydirection
|
2673 |
+
|
2674 |
+
Examples
|
2675 |
+
========
|
2676 |
+
|
2677 |
+
>>> from sympy import Point3D, Ray3D
|
2678 |
+
>>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(0, -1, 0)
|
2679 |
+
>>> r1, r2 = Ray3D(p1, p2), Ray3D(p1, p3)
|
2680 |
+
>>> r1.xdirection
|
2681 |
+
oo
|
2682 |
+
>>> r2.xdirection
|
2683 |
+
0
|
2684 |
+
|
2685 |
+
"""
|
2686 |
+
if self.p1.x < self.p2.x:
|
2687 |
+
return S.Infinity
|
2688 |
+
elif self.p1.x == self.p2.x:
|
2689 |
+
return S.Zero
|
2690 |
+
else:
|
2691 |
+
return S.NegativeInfinity
|
2692 |
+
|
2693 |
+
@property
|
2694 |
+
def ydirection(self):
|
2695 |
+
"""The y direction of the ray.
|
2696 |
+
|
2697 |
+
Positive infinity if the ray points in the positive y direction,
|
2698 |
+
negative infinity if the ray points in the negative y direction,
|
2699 |
+
or 0 if the ray is horizontal.
|
2700 |
+
|
2701 |
+
See Also
|
2702 |
+
========
|
2703 |
+
|
2704 |
+
xdirection
|
2705 |
+
|
2706 |
+
Examples
|
2707 |
+
========
|
2708 |
+
|
2709 |
+
>>> from sympy import Point3D, Ray3D
|
2710 |
+
>>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(-1, -1, -1), Point3D(-1, 0, 0)
|
2711 |
+
>>> r1, r2 = Ray3D(p1, p2), Ray3D(p1, p3)
|
2712 |
+
>>> r1.ydirection
|
2713 |
+
-oo
|
2714 |
+
>>> r2.ydirection
|
2715 |
+
0
|
2716 |
+
|
2717 |
+
"""
|
2718 |
+
if self.p1.y < self.p2.y:
|
2719 |
+
return S.Infinity
|
2720 |
+
elif self.p1.y == self.p2.y:
|
2721 |
+
return S.Zero
|
2722 |
+
else:
|
2723 |
+
return S.NegativeInfinity
|
2724 |
+
|
2725 |
+
@property
|
2726 |
+
def zdirection(self):
|
2727 |
+
"""The z direction of the ray.
|
2728 |
+
|
2729 |
+
Positive infinity if the ray points in the positive z direction,
|
2730 |
+
negative infinity if the ray points in the negative z direction,
|
2731 |
+
or 0 if the ray is horizontal.
|
2732 |
+
|
2733 |
+
See Also
|
2734 |
+
========
|
2735 |
+
|
2736 |
+
xdirection
|
2737 |
+
|
2738 |
+
Examples
|
2739 |
+
========
|
2740 |
+
|
2741 |
+
>>> from sympy import Point3D, Ray3D
|
2742 |
+
>>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(-1, -1, -1), Point3D(-1, 0, 0)
|
2743 |
+
>>> r1, r2 = Ray3D(p1, p2), Ray3D(p1, p3)
|
2744 |
+
>>> r1.ydirection
|
2745 |
+
-oo
|
2746 |
+
>>> r2.ydirection
|
2747 |
+
0
|
2748 |
+
>>> r2.zdirection
|
2749 |
+
0
|
2750 |
+
|
2751 |
+
"""
|
2752 |
+
if self.p1.z < self.p2.z:
|
2753 |
+
return S.Infinity
|
2754 |
+
elif self.p1.z == self.p2.z:
|
2755 |
+
return S.Zero
|
2756 |
+
else:
|
2757 |
+
return S.NegativeInfinity
|
2758 |
+
|
2759 |
+
|
2760 |
+
class Segment3D(LinearEntity3D, Segment):
|
2761 |
+
"""A line segment in a 3D space.
|
2762 |
+
|
2763 |
+
Parameters
|
2764 |
+
==========
|
2765 |
+
|
2766 |
+
p1 : Point3D
|
2767 |
+
p2 : Point3D
|
2768 |
+
|
2769 |
+
Attributes
|
2770 |
+
==========
|
2771 |
+
|
2772 |
+
length : number or SymPy expression
|
2773 |
+
midpoint : Point3D
|
2774 |
+
|
2775 |
+
See Also
|
2776 |
+
========
|
2777 |
+
|
2778 |
+
sympy.geometry.point.Point3D, Line3D
|
2779 |
+
|
2780 |
+
Examples
|
2781 |
+
========
|
2782 |
+
|
2783 |
+
>>> from sympy import Point3D, Segment3D
|
2784 |
+
>>> Segment3D((1, 0, 0), (1, 1, 1)) # tuples are interpreted as pts
|
2785 |
+
Segment3D(Point3D(1, 0, 0), Point3D(1, 1, 1))
|
2786 |
+
>>> s = Segment3D(Point3D(4, 3, 9), Point3D(1, 1, 7)); s
|
2787 |
+
Segment3D(Point3D(4, 3, 9), Point3D(1, 1, 7))
|
2788 |
+
>>> s.points
|
2789 |
+
(Point3D(4, 3, 9), Point3D(1, 1, 7))
|
2790 |
+
>>> s.length
|
2791 |
+
sqrt(17)
|
2792 |
+
>>> s.midpoint
|
2793 |
+
Point3D(5/2, 2, 8)
|
2794 |
+
|
2795 |
+
"""
|
2796 |
+
def __new__(cls, p1, p2, **kwargs):
|
2797 |
+
p1 = Point(p1, dim=3)
|
2798 |
+
p2 = Point(p2, dim=3)
|
2799 |
+
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Parabolic geometrical entity.
|
2 |
+
|
3 |
+
Contains
|
4 |
+
* Parabola
|
5 |
+
|
6 |
+
"""
|
7 |
+
|
8 |
+
from sympy.core import S
|
9 |
+
from sympy.core.sorting import ordered
|
10 |
+
from sympy.core.symbol import _symbol, symbols
|
11 |
+
from sympy.geometry.entity import GeometryEntity, GeometrySet
|
12 |
+
from sympy.geometry.point import Point, Point2D
|
13 |
+
from sympy.geometry.line import Line, Line2D, Ray2D, Segment2D, LinearEntity3D
|
14 |
+
from sympy.geometry.ellipse import Ellipse
|
15 |
+
from sympy.functions import sign
|
16 |
+
from sympy.simplify import simplify
|
17 |
+
from sympy.solvers.solvers import solve
|
18 |
+
|
19 |
+
|
20 |
+
class Parabola(GeometrySet):
|
21 |
+
"""A parabolic GeometryEntity.
|
22 |
+
|
23 |
+
A parabola is declared with a point, that is called 'focus', and
|
24 |
+
a line, that is called 'directrix'.
|
25 |
+
Only vertical or horizontal parabolas are currently supported.
|
26 |
+
|
27 |
+
Parameters
|
28 |
+
==========
|
29 |
+
|
30 |
+
focus : Point
|
31 |
+
Default value is Point(0, 0)
|
32 |
+
directrix : Line
|
33 |
+
|
34 |
+
Attributes
|
35 |
+
==========
|
36 |
+
|
37 |
+
focus
|
38 |
+
directrix
|
39 |
+
axis of symmetry
|
40 |
+
focal length
|
41 |
+
p parameter
|
42 |
+
vertex
|
43 |
+
eccentricity
|
44 |
+
|
45 |
+
Raises
|
46 |
+
======
|
47 |
+
ValueError
|
48 |
+
When `focus` is not a two dimensional point.
|
49 |
+
When `focus` is a point of directrix.
|
50 |
+
NotImplementedError
|
51 |
+
When `directrix` is neither horizontal nor vertical.
|
52 |
+
|
53 |
+
Examples
|
54 |
+
========
|
55 |
+
|
56 |
+
>>> from sympy import Parabola, Point, Line
|
57 |
+
>>> p1 = Parabola(Point(0, 0), Line(Point(5, 8), Point(7,8)))
|
58 |
+
>>> p1.focus
|
59 |
+
Point2D(0, 0)
|
60 |
+
>>> p1.directrix
|
61 |
+
Line2D(Point2D(5, 8), Point2D(7, 8))
|
62 |
+
|
63 |
+
"""
|
64 |
+
|
65 |
+
def __new__(cls, focus=None, directrix=None, **kwargs):
|
66 |
+
|
67 |
+
if focus:
|
68 |
+
focus = Point(focus, dim=2)
|
69 |
+
else:
|
70 |
+
focus = Point(0, 0)
|
71 |
+
|
72 |
+
directrix = Line(directrix)
|
73 |
+
|
74 |
+
if directrix.contains(focus):
|
75 |
+
raise ValueError('The focus must not be a point of directrix')
|
76 |
+
|
77 |
+
return GeometryEntity.__new__(cls, focus, directrix, **kwargs)
|
78 |
+
|
79 |
+
@property
|
80 |
+
def ambient_dimension(self):
|
81 |
+
"""Returns the ambient dimension of parabola.
|
82 |
+
|
83 |
+
Returns
|
84 |
+
=======
|
85 |
+
|
86 |
+
ambient_dimension : integer
|
87 |
+
|
88 |
+
Examples
|
89 |
+
========
|
90 |
+
|
91 |
+
>>> from sympy import Parabola, Point, Line
|
92 |
+
>>> f1 = Point(0, 0)
|
93 |
+
>>> p1 = Parabola(f1, Line(Point(5, 8), Point(7, 8)))
|
94 |
+
>>> p1.ambient_dimension
|
95 |
+
2
|
96 |
+
|
97 |
+
"""
|
98 |
+
return 2
|
99 |
+
|
100 |
+
@property
|
101 |
+
def axis_of_symmetry(self):
|
102 |
+
"""Return the axis of symmetry of the parabola: a line
|
103 |
+
perpendicular to the directrix passing through the focus.
|
104 |
+
|
105 |
+
Returns
|
106 |
+
=======
|
107 |
+
|
108 |
+
axis_of_symmetry : Line
|
109 |
+
|
110 |
+
See Also
|
111 |
+
========
|
112 |
+
|
113 |
+
sympy.geometry.line.Line
|
114 |
+
|
115 |
+
Examples
|
116 |
+
========
|
117 |
+
|
118 |
+
>>> from sympy import Parabola, Point, Line
|
119 |
+
>>> p1 = Parabola(Point(0, 0), Line(Point(5, 8), Point(7, 8)))
|
120 |
+
>>> p1.axis_of_symmetry
|
121 |
+
Line2D(Point2D(0, 0), Point2D(0, 1))
|
122 |
+
|
123 |
+
"""
|
124 |
+
return self.directrix.perpendicular_line(self.focus)
|
125 |
+
|
126 |
+
@property
|
127 |
+
def directrix(self):
|
128 |
+
"""The directrix of the parabola.
|
129 |
+
|
130 |
+
Returns
|
131 |
+
=======
|
132 |
+
|
133 |
+
directrix : Line
|
134 |
+
|
135 |
+
See Also
|
136 |
+
========
|
137 |
+
|
138 |
+
sympy.geometry.line.Line
|
139 |
+
|
140 |
+
Examples
|
141 |
+
========
|
142 |
+
|
143 |
+
>>> from sympy import Parabola, Point, Line
|
144 |
+
>>> l1 = Line(Point(5, 8), Point(7, 8))
|
145 |
+
>>> p1 = Parabola(Point(0, 0), l1)
|
146 |
+
>>> p1.directrix
|
147 |
+
Line2D(Point2D(5, 8), Point2D(7, 8))
|
148 |
+
|
149 |
+
"""
|
150 |
+
return self.args[1]
|
151 |
+
|
152 |
+
@property
|
153 |
+
def eccentricity(self):
|
154 |
+
"""The eccentricity of the parabola.
|
155 |
+
|
156 |
+
Returns
|
157 |
+
=======
|
158 |
+
|
159 |
+
eccentricity : number
|
160 |
+
|
161 |
+
A parabola may also be characterized as a conic section with an
|
162 |
+
eccentricity of 1. As a consequence of this, all parabolas are
|
163 |
+
similar, meaning that while they can be different sizes,
|
164 |
+
they are all the same shape.
|
165 |
+
|
166 |
+
See Also
|
167 |
+
========
|
168 |
+
|
169 |
+
https://en.wikipedia.org/wiki/Parabola
|
170 |
+
|
171 |
+
|
172 |
+
Examples
|
173 |
+
========
|
174 |
+
|
175 |
+
>>> from sympy import Parabola, Point, Line
|
176 |
+
>>> p1 = Parabola(Point(0, 0), Line(Point(5, 8), Point(7, 8)))
|
177 |
+
>>> p1.eccentricity
|
178 |
+
1
|
179 |
+
|
180 |
+
Notes
|
181 |
+
-----
|
182 |
+
The eccentricity for every Parabola is 1 by definition.
|
183 |
+
|
184 |
+
"""
|
185 |
+
return S.One
|
186 |
+
|
187 |
+
def equation(self, x='x', y='y'):
|
188 |
+
"""The equation of the parabola.
|
189 |
+
|
190 |
+
Parameters
|
191 |
+
==========
|
192 |
+
x : str, optional
|
193 |
+
Label for the x-axis. Default value is 'x'.
|
194 |
+
y : str, optional
|
195 |
+
Label for the y-axis. Default value is 'y'.
|
196 |
+
|
197 |
+
Returns
|
198 |
+
=======
|
199 |
+
equation : SymPy expression
|
200 |
+
|
201 |
+
Examples
|
202 |
+
========
|
203 |
+
|
204 |
+
>>> from sympy import Parabola, Point, Line
|
205 |
+
>>> p1 = Parabola(Point(0, 0), Line(Point(5, 8), Point(7, 8)))
|
206 |
+
>>> p1.equation()
|
207 |
+
-x**2 - 16*y + 64
|
208 |
+
>>> p1.equation('f')
|
209 |
+
-f**2 - 16*y + 64
|
210 |
+
>>> p1.equation(y='z')
|
211 |
+
-x**2 - 16*z + 64
|
212 |
+
|
213 |
+
"""
|
214 |
+
x = _symbol(x, real=True)
|
215 |
+
y = _symbol(y, real=True)
|
216 |
+
|
217 |
+
m = self.directrix.slope
|
218 |
+
if m is S.Infinity:
|
219 |
+
t1 = 4 * (self.p_parameter) * (x - self.vertex.x)
|
220 |
+
t2 = (y - self.vertex.y)**2
|
221 |
+
elif m == 0:
|
222 |
+
t1 = 4 * (self.p_parameter) * (y - self.vertex.y)
|
223 |
+
t2 = (x - self.vertex.x)**2
|
224 |
+
else:
|
225 |
+
a, b = self.focus
|
226 |
+
c, d = self.directrix.coefficients[:2]
|
227 |
+
t1 = (x - a)**2 + (y - b)**2
|
228 |
+
t2 = self.directrix.equation(x, y)**2/(c**2 + d**2)
|
229 |
+
return t1 - t2
|
230 |
+
|
231 |
+
@property
|
232 |
+
def focal_length(self):
|
233 |
+
"""The focal length of the parabola.
|
234 |
+
|
235 |
+
Returns
|
236 |
+
=======
|
237 |
+
|
238 |
+
focal_lenght : number or symbolic expression
|
239 |
+
|
240 |
+
Notes
|
241 |
+
=====
|
242 |
+
|
243 |
+
The distance between the vertex and the focus
|
244 |
+
(or the vertex and directrix), measured along the axis
|
245 |
+
of symmetry, is the "focal length".
|
246 |
+
|
247 |
+
See Also
|
248 |
+
========
|
249 |
+
|
250 |
+
https://en.wikipedia.org/wiki/Parabola
|
251 |
+
|
252 |
+
Examples
|
253 |
+
========
|
254 |
+
|
255 |
+
>>> from sympy import Parabola, Point, Line
|
256 |
+
>>> p1 = Parabola(Point(0, 0), Line(Point(5, 8), Point(7, 8)))
|
257 |
+
>>> p1.focal_length
|
258 |
+
4
|
259 |
+
|
260 |
+
"""
|
261 |
+
distance = self.directrix.distance(self.focus)
|
262 |
+
focal_length = distance/2
|
263 |
+
|
264 |
+
return focal_length
|
265 |
+
|
266 |
+
@property
|
267 |
+
def focus(self):
|
268 |
+
"""The focus of the parabola.
|
269 |
+
|
270 |
+
Returns
|
271 |
+
=======
|
272 |
+
|
273 |
+
focus : Point
|
274 |
+
|
275 |
+
See Also
|
276 |
+
========
|
277 |
+
|
278 |
+
sympy.geometry.point.Point
|
279 |
+
|
280 |
+
Examples
|
281 |
+
========
|
282 |
+
|
283 |
+
>>> from sympy import Parabola, Point, Line
|
284 |
+
>>> f1 = Point(0, 0)
|
285 |
+
>>> p1 = Parabola(f1, Line(Point(5, 8), Point(7, 8)))
|
286 |
+
>>> p1.focus
|
287 |
+
Point2D(0, 0)
|
288 |
+
|
289 |
+
"""
|
290 |
+
return self.args[0]
|
291 |
+
|
292 |
+
def intersection(self, o):
|
293 |
+
"""The intersection of the parabola and another geometrical entity `o`.
|
294 |
+
|
295 |
+
Parameters
|
296 |
+
==========
|
297 |
+
|
298 |
+
o : GeometryEntity, LinearEntity
|
299 |
+
|
300 |
+
Returns
|
301 |
+
=======
|
302 |
+
|
303 |
+
intersection : list of GeometryEntity objects
|
304 |
+
|
305 |
+
Examples
|
306 |
+
========
|
307 |
+
|
308 |
+
>>> from sympy import Parabola, Point, Ellipse, Line, Segment
|
309 |
+
>>> p1 = Point(0,0)
|
310 |
+
>>> l1 = Line(Point(1, -2), Point(-1,-2))
|
311 |
+
>>> parabola1 = Parabola(p1, l1)
|
312 |
+
>>> parabola1.intersection(Ellipse(Point(0, 0), 2, 5))
|
313 |
+
[Point2D(-2, 0), Point2D(2, 0)]
|
314 |
+
>>> parabola1.intersection(Line(Point(-7, 3), Point(12, 3)))
|
315 |
+
[Point2D(-4, 3), Point2D(4, 3)]
|
316 |
+
>>> parabola1.intersection(Segment((-12, -65), (14, -68)))
|
317 |
+
[]
|
318 |
+
|
319 |
+
"""
|
320 |
+
x, y = symbols('x y', real=True)
|
321 |
+
parabola_eq = self.equation()
|
322 |
+
if isinstance(o, Parabola):
|
323 |
+
if o in self:
|
324 |
+
return [o]
|
325 |
+
else:
|
326 |
+
return list(ordered([Point(i) for i in solve(
|
327 |
+
[parabola_eq, o.equation()], [x, y], set=True)[1]]))
|
328 |
+
elif isinstance(o, Point2D):
|
329 |
+
if simplify(parabola_eq.subs([(x, o._args[0]), (y, o._args[1])])) == 0:
|
330 |
+
return [o]
|
331 |
+
else:
|
332 |
+
return []
|
333 |
+
elif isinstance(o, (Segment2D, Ray2D)):
|
334 |
+
result = solve([parabola_eq,
|
335 |
+
Line2D(o.points[0], o.points[1]).equation()],
|
336 |
+
[x, y], set=True)[1]
|
337 |
+
return list(ordered([Point2D(i) for i in result if i in o]))
|
338 |
+
elif isinstance(o, (Line2D, Ellipse)):
|
339 |
+
return list(ordered([Point2D(i) for i in solve(
|
340 |
+
[parabola_eq, o.equation()], [x, y], set=True)[1]]))
|
341 |
+
elif isinstance(o, LinearEntity3D):
|
342 |
+
raise TypeError('Entity must be two dimensional, not three dimensional')
|
343 |
+
else:
|
344 |
+
raise TypeError('Wrong type of argument were put')
|
345 |
+
|
346 |
+
@property
|
347 |
+
def p_parameter(self):
|
348 |
+
"""P is a parameter of parabola.
|
349 |
+
|
350 |
+
Returns
|
351 |
+
=======
|
352 |
+
|
353 |
+
p : number or symbolic expression
|
354 |
+
|
355 |
+
Notes
|
356 |
+
=====
|
357 |
+
|
358 |
+
The absolute value of p is the focal length. The sign on p tells
|
359 |
+
which way the parabola faces. Vertical parabolas that open up
|
360 |
+
and horizontal that open right, give a positive value for p.
|
361 |
+
Vertical parabolas that open down and horizontal that open left,
|
362 |
+
give a negative value for p.
|
363 |
+
|
364 |
+
|
365 |
+
See Also
|
366 |
+
========
|
367 |
+
|
368 |
+
https://www.sparknotes.com/math/precalc/conicsections/section2/
|
369 |
+
|
370 |
+
Examples
|
371 |
+
========
|
372 |
+
|
373 |
+
>>> from sympy import Parabola, Point, Line
|
374 |
+
>>> p1 = Parabola(Point(0, 0), Line(Point(5, 8), Point(7, 8)))
|
375 |
+
>>> p1.p_parameter
|
376 |
+
-4
|
377 |
+
|
378 |
+
"""
|
379 |
+
m = self.directrix.slope
|
380 |
+
if m is S.Infinity:
|
381 |
+
x = self.directrix.coefficients[2]
|
382 |
+
p = sign(self.focus.args[0] + x)
|
383 |
+
elif m == 0:
|
384 |
+
y = self.directrix.coefficients[2]
|
385 |
+
p = sign(self.focus.args[1] + y)
|
386 |
+
else:
|
387 |
+
d = self.directrix.projection(self.focus)
|
388 |
+
p = sign(self.focus.x - d.x)
|
389 |
+
return p * self.focal_length
|
390 |
+
|
391 |
+
@property
|
392 |
+
def vertex(self):
|
393 |
+
"""The vertex of the parabola.
|
394 |
+
|
395 |
+
Returns
|
396 |
+
=======
|
397 |
+
|
398 |
+
vertex : Point
|
399 |
+
|
400 |
+
See Also
|
401 |
+
========
|
402 |
+
|
403 |
+
sympy.geometry.point.Point
|
404 |
+
|
405 |
+
Examples
|
406 |
+
========
|
407 |
+
|
408 |
+
>>> from sympy import Parabola, Point, Line
|
409 |
+
>>> p1 = Parabola(Point(0, 0), Line(Point(5, 8), Point(7, 8)))
|
410 |
+
>>> p1.vertex
|
411 |
+
Point2D(0, 4)
|
412 |
+
|
413 |
+
"""
|
414 |
+
focus = self.focus
|
415 |
+
m = self.directrix.slope
|
416 |
+
if m is S.Infinity:
|
417 |
+
vertex = Point(focus.args[0] - self.p_parameter, focus.args[1])
|
418 |
+
elif m == 0:
|
419 |
+
vertex = Point(focus.args[0], focus.args[1] - self.p_parameter)
|
420 |
+
else:
|
421 |
+
vertex = self.axis_of_symmetry.intersection(self)[0]
|
422 |
+
return vertex
|
env-llmeval/lib/python3.10/site-packages/sympy/geometry/plane.py
ADDED
@@ -0,0 +1,884 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Geometrical Planes.
|
2 |
+
|
3 |
+
Contains
|
4 |
+
========
|
5 |
+
Plane
|
6 |
+
|
7 |
+
"""
|
8 |
+
|
9 |
+
from sympy.core import Dummy, Rational, S, Symbol
|
10 |
+
from sympy.core.symbol import _symbol
|
11 |
+
from sympy.functions.elementary.trigonometric import cos, sin, acos, asin, sqrt
|
12 |
+
from .entity import GeometryEntity
|
13 |
+
from .line import (Line, Ray, Segment, Line3D, LinearEntity, LinearEntity3D,
|
14 |
+
Ray3D, Segment3D)
|
15 |
+
from .point import Point, Point3D
|
16 |
+
from sympy.matrices import Matrix
|
17 |
+
from sympy.polys.polytools import cancel
|
18 |
+
from sympy.solvers import solve, linsolve
|
19 |
+
from sympy.utilities.iterables import uniq, is_sequence
|
20 |
+
from sympy.utilities.misc import filldedent, func_name, Undecidable
|
21 |
+
|
22 |
+
from mpmath.libmp.libmpf import prec_to_dps
|
23 |
+
|
24 |
+
import random
|
25 |
+
|
26 |
+
|
27 |
+
x, y, z, t = [Dummy('plane_dummy') for i in range(4)]
|
28 |
+
|
29 |
+
|
30 |
+
class Plane(GeometryEntity):
|
31 |
+
"""
|
32 |
+
A plane is a flat, two-dimensional surface. A plane is the two-dimensional
|
33 |
+
analogue of a point (zero-dimensions), a line (one-dimension) and a solid
|
34 |
+
(three-dimensions). A plane can generally be constructed by two types of
|
35 |
+
inputs. They are three non-collinear points and a point and the plane's
|
36 |
+
normal vector.
|
37 |
+
|
38 |
+
Attributes
|
39 |
+
==========
|
40 |
+
|
41 |
+
p1
|
42 |
+
normal_vector
|
43 |
+
|
44 |
+
Examples
|
45 |
+
========
|
46 |
+
|
47 |
+
>>> from sympy import Plane, Point3D
|
48 |
+
>>> Plane(Point3D(1, 1, 1), Point3D(2, 3, 4), Point3D(2, 2, 2))
|
49 |
+
Plane(Point3D(1, 1, 1), (-1, 2, -1))
|
50 |
+
>>> Plane((1, 1, 1), (2, 3, 4), (2, 2, 2))
|
51 |
+
Plane(Point3D(1, 1, 1), (-1, 2, -1))
|
52 |
+
>>> Plane(Point3D(1, 1, 1), normal_vector=(1,4,7))
|
53 |
+
Plane(Point3D(1, 1, 1), (1, 4, 7))
|
54 |
+
|
55 |
+
"""
|
56 |
+
def __new__(cls, p1, a=None, b=None, **kwargs):
|
57 |
+
p1 = Point3D(p1, dim=3)
|
58 |
+
if a and b:
|
59 |
+
p2 = Point(a, dim=3)
|
60 |
+
p3 = Point(b, dim=3)
|
61 |
+
if Point3D.are_collinear(p1, p2, p3):
|
62 |
+
raise ValueError('Enter three non-collinear points')
|
63 |
+
a = p1.direction_ratio(p2)
|
64 |
+
b = p1.direction_ratio(p3)
|
65 |
+
normal_vector = tuple(Matrix(a).cross(Matrix(b)))
|
66 |
+
else:
|
67 |
+
a = kwargs.pop('normal_vector', a)
|
68 |
+
evaluate = kwargs.get('evaluate', True)
|
69 |
+
if is_sequence(a) and len(a) == 3:
|
70 |
+
normal_vector = Point3D(a).args if evaluate else a
|
71 |
+
else:
|
72 |
+
raise ValueError(filldedent('''
|
73 |
+
Either provide 3 3D points or a point with a
|
74 |
+
normal vector expressed as a sequence of length 3'''))
|
75 |
+
if all(coord.is_zero for coord in normal_vector):
|
76 |
+
raise ValueError('Normal vector cannot be zero vector')
|
77 |
+
return GeometryEntity.__new__(cls, p1, normal_vector, **kwargs)
|
78 |
+
|
79 |
+
def __contains__(self, o):
|
80 |
+
k = self.equation(x, y, z)
|
81 |
+
if isinstance(o, (LinearEntity, LinearEntity3D)):
|
82 |
+
d = Point3D(o.arbitrary_point(t))
|
83 |
+
e = k.subs([(x, d.x), (y, d.y), (z, d.z)])
|
84 |
+
return e.equals(0)
|
85 |
+
try:
|
86 |
+
o = Point(o, dim=3, strict=True)
|
87 |
+
d = k.xreplace(dict(zip((x, y, z), o.args)))
|
88 |
+
return d.equals(0)
|
89 |
+
except TypeError:
|
90 |
+
return False
|
91 |
+
|
92 |
+
def _eval_evalf(self, prec=15, **options):
|
93 |
+
pt, tup = self.args
|
94 |
+
dps = prec_to_dps(prec)
|
95 |
+
pt = pt.evalf(n=dps, **options)
|
96 |
+
tup = tuple([i.evalf(n=dps, **options) for i in tup])
|
97 |
+
return self.func(pt, normal_vector=tup, evaluate=False)
|
98 |
+
|
99 |
+
def angle_between(self, o):
|
100 |
+
"""Angle between the plane and other geometric entity.
|
101 |
+
|
102 |
+
Parameters
|
103 |
+
==========
|
104 |
+
|
105 |
+
LinearEntity3D, Plane.
|
106 |
+
|
107 |
+
Returns
|
108 |
+
=======
|
109 |
+
|
110 |
+
angle : angle in radians
|
111 |
+
|
112 |
+
Notes
|
113 |
+
=====
|
114 |
+
|
115 |
+
This method accepts only 3D entities as it's parameter, but if you want
|
116 |
+
to calculate the angle between a 2D entity and a plane you should
|
117 |
+
first convert to a 3D entity by projecting onto a desired plane and
|
118 |
+
then proceed to calculate the angle.
|
119 |
+
|
120 |
+
Examples
|
121 |
+
========
|
122 |
+
|
123 |
+
>>> from sympy import Point3D, Line3D, Plane
|
124 |
+
>>> a = Plane(Point3D(1, 2, 2), normal_vector=(1, 2, 3))
|
125 |
+
>>> b = Line3D(Point3D(1, 3, 4), Point3D(2, 2, 2))
|
126 |
+
>>> a.angle_between(b)
|
127 |
+
-asin(sqrt(21)/6)
|
128 |
+
|
129 |
+
"""
|
130 |
+
if isinstance(o, LinearEntity3D):
|
131 |
+
a = Matrix(self.normal_vector)
|
132 |
+
b = Matrix(o.direction_ratio)
|
133 |
+
c = a.dot(b)
|
134 |
+
d = sqrt(sum([i**2 for i in self.normal_vector]))
|
135 |
+
e = sqrt(sum([i**2 for i in o.direction_ratio]))
|
136 |
+
return asin(c/(d*e))
|
137 |
+
if isinstance(o, Plane):
|
138 |
+
a = Matrix(self.normal_vector)
|
139 |
+
b = Matrix(o.normal_vector)
|
140 |
+
c = a.dot(b)
|
141 |
+
d = sqrt(sum([i**2 for i in self.normal_vector]))
|
142 |
+
e = sqrt(sum([i**2 for i in o.normal_vector]))
|
143 |
+
return acos(c/(d*e))
|
144 |
+
|
145 |
+
|
146 |
+
def arbitrary_point(self, u=None, v=None):
|
147 |
+
""" Returns an arbitrary point on the Plane. If given two
|
148 |
+
parameters, the point ranges over the entire plane. If given 1
|
149 |
+
or no parameters, returns a point with one parameter which,
|
150 |
+
when varying from 0 to 2*pi, moves the point in a circle of
|
151 |
+
radius 1 about p1 of the Plane.
|
152 |
+
|
153 |
+
Examples
|
154 |
+
========
|
155 |
+
|
156 |
+
>>> from sympy import Plane, Ray
|
157 |
+
>>> from sympy.abc import u, v, t, r
|
158 |
+
>>> p = Plane((1, 1, 1), normal_vector=(1, 0, 0))
|
159 |
+
>>> p.arbitrary_point(u, v)
|
160 |
+
Point3D(1, u + 1, v + 1)
|
161 |
+
>>> p.arbitrary_point(t)
|
162 |
+
Point3D(1, cos(t) + 1, sin(t) + 1)
|
163 |
+
|
164 |
+
While arbitrary values of u and v can move the point anywhere in
|
165 |
+
the plane, the single-parameter point can be used to construct a
|
166 |
+
ray whose arbitrary point can be located at angle t and radius
|
167 |
+
r from p.p1:
|
168 |
+
|
169 |
+
>>> Ray(p.p1, _).arbitrary_point(r)
|
170 |
+
Point3D(1, r*cos(t) + 1, r*sin(t) + 1)
|
171 |
+
|
172 |
+
Returns
|
173 |
+
=======
|
174 |
+
|
175 |
+
Point3D
|
176 |
+
|
177 |
+
"""
|
178 |
+
circle = v is None
|
179 |
+
if circle:
|
180 |
+
u = _symbol(u or 't', real=True)
|
181 |
+
else:
|
182 |
+
u = _symbol(u or 'u', real=True)
|
183 |
+
v = _symbol(v or 'v', real=True)
|
184 |
+
x, y, z = self.normal_vector
|
185 |
+
a, b, c = self.p1.args
|
186 |
+
# x1, y1, z1 is a nonzero vector parallel to the plane
|
187 |
+
if x.is_zero and y.is_zero:
|
188 |
+
x1, y1, z1 = S.One, S.Zero, S.Zero
|
189 |
+
else:
|
190 |
+
x1, y1, z1 = -y, x, S.Zero
|
191 |
+
# x2, y2, z2 is also parallel to the plane, and orthogonal to x1, y1, z1
|
192 |
+
x2, y2, z2 = tuple(Matrix((x, y, z)).cross(Matrix((x1, y1, z1))))
|
193 |
+
if circle:
|
194 |
+
x1, y1, z1 = (w/sqrt(x1**2 + y1**2 + z1**2) for w in (x1, y1, z1))
|
195 |
+
x2, y2, z2 = (w/sqrt(x2**2 + y2**2 + z2**2) for w in (x2, y2, z2))
|
196 |
+
p = Point3D(a + x1*cos(u) + x2*sin(u), \
|
197 |
+
b + y1*cos(u) + y2*sin(u), \
|
198 |
+
c + z1*cos(u) + z2*sin(u))
|
199 |
+
else:
|
200 |
+
p = Point3D(a + x1*u + x2*v, b + y1*u + y2*v, c + z1*u + z2*v)
|
201 |
+
return p
|
202 |
+
|
203 |
+
|
204 |
+
@staticmethod
|
205 |
+
def are_concurrent(*planes):
|
206 |
+
"""Is a sequence of Planes concurrent?
|
207 |
+
|
208 |
+
Two or more Planes are concurrent if their intersections
|
209 |
+
are a common line.
|
210 |
+
|
211 |
+
Parameters
|
212 |
+
==========
|
213 |
+
|
214 |
+
planes: list
|
215 |
+
|
216 |
+
Returns
|
217 |
+
=======
|
218 |
+
|
219 |
+
Boolean
|
220 |
+
|
221 |
+
Examples
|
222 |
+
========
|
223 |
+
|
224 |
+
>>> from sympy import Plane, Point3D
|
225 |
+
>>> a = Plane(Point3D(5, 0, 0), normal_vector=(1, -1, 1))
|
226 |
+
>>> b = Plane(Point3D(0, -2, 0), normal_vector=(3, 1, 1))
|
227 |
+
>>> c = Plane(Point3D(0, -1, 0), normal_vector=(5, -1, 9))
|
228 |
+
>>> Plane.are_concurrent(a, b)
|
229 |
+
True
|
230 |
+
>>> Plane.are_concurrent(a, b, c)
|
231 |
+
False
|
232 |
+
|
233 |
+
"""
|
234 |
+
planes = list(uniq(planes))
|
235 |
+
for i in planes:
|
236 |
+
if not isinstance(i, Plane):
|
237 |
+
raise ValueError('All objects should be Planes but got %s' % i.func)
|
238 |
+
if len(planes) < 2:
|
239 |
+
return False
|
240 |
+
planes = list(planes)
|
241 |
+
first = planes.pop(0)
|
242 |
+
sol = first.intersection(planes[0])
|
243 |
+
if sol == []:
|
244 |
+
return False
|
245 |
+
else:
|
246 |
+
line = sol[0]
|
247 |
+
for i in planes[1:]:
|
248 |
+
l = first.intersection(i)
|
249 |
+
if not l or l[0] not in line:
|
250 |
+
return False
|
251 |
+
return True
|
252 |
+
|
253 |
+
|
254 |
+
def distance(self, o):
|
255 |
+
"""Distance between the plane and another geometric entity.
|
256 |
+
|
257 |
+
Parameters
|
258 |
+
==========
|
259 |
+
|
260 |
+
Point3D, LinearEntity3D, Plane.
|
261 |
+
|
262 |
+
Returns
|
263 |
+
=======
|
264 |
+
|
265 |
+
distance
|
266 |
+
|
267 |
+
Notes
|
268 |
+
=====
|
269 |
+
|
270 |
+
This method accepts only 3D entities as it's parameter, but if you want
|
271 |
+
to calculate the distance between a 2D entity and a plane you should
|
272 |
+
first convert to a 3D entity by projecting onto a desired plane and
|
273 |
+
then proceed to calculate the distance.
|
274 |
+
|
275 |
+
Examples
|
276 |
+
========
|
277 |
+
|
278 |
+
>>> from sympy import Point3D, Line3D, Plane
|
279 |
+
>>> a = Plane(Point3D(1, 1, 1), normal_vector=(1, 1, 1))
|
280 |
+
>>> b = Point3D(1, 2, 3)
|
281 |
+
>>> a.distance(b)
|
282 |
+
sqrt(3)
|
283 |
+
>>> c = Line3D(Point3D(2, 3, 1), Point3D(1, 2, 2))
|
284 |
+
>>> a.distance(c)
|
285 |
+
0
|
286 |
+
|
287 |
+
"""
|
288 |
+
if self.intersection(o) != []:
|
289 |
+
return S.Zero
|
290 |
+
|
291 |
+
if isinstance(o, (Segment3D, Ray3D)):
|
292 |
+
a, b = o.p1, o.p2
|
293 |
+
pi, = self.intersection(Line3D(a, b))
|
294 |
+
if pi in o:
|
295 |
+
return self.distance(pi)
|
296 |
+
elif a in Segment3D(pi, b):
|
297 |
+
return self.distance(a)
|
298 |
+
else:
|
299 |
+
assert isinstance(o, Segment3D) is True
|
300 |
+
return self.distance(b)
|
301 |
+
|
302 |
+
# following code handles `Point3D`, `LinearEntity3D`, `Plane`
|
303 |
+
a = o if isinstance(o, Point3D) else o.p1
|
304 |
+
n = Point3D(self.normal_vector).unit
|
305 |
+
d = (a - self.p1).dot(n)
|
306 |
+
return abs(d)
|
307 |
+
|
308 |
+
|
309 |
+
def equals(self, o):
|
310 |
+
"""
|
311 |
+
Returns True if self and o are the same mathematical entities.
|
312 |
+
|
313 |
+
Examples
|
314 |
+
========
|
315 |
+
|
316 |
+
>>> from sympy import Plane, Point3D
|
317 |
+
>>> a = Plane(Point3D(1, 2, 3), normal_vector=(1, 1, 1))
|
318 |
+
>>> b = Plane(Point3D(1, 2, 3), normal_vector=(2, 2, 2))
|
319 |
+
>>> c = Plane(Point3D(1, 2, 3), normal_vector=(-1, 4, 6))
|
320 |
+
>>> a.equals(a)
|
321 |
+
True
|
322 |
+
>>> a.equals(b)
|
323 |
+
True
|
324 |
+
>>> a.equals(c)
|
325 |
+
False
|
326 |
+
"""
|
327 |
+
if isinstance(o, Plane):
|
328 |
+
a = self.equation()
|
329 |
+
b = o.equation()
|
330 |
+
return cancel(a/b).is_constant()
|
331 |
+
else:
|
332 |
+
return False
|
333 |
+
|
334 |
+
|
335 |
+
def equation(self, x=None, y=None, z=None):
|
336 |
+
"""The equation of the Plane.
|
337 |
+
|
338 |
+
Examples
|
339 |
+
========
|
340 |
+
|
341 |
+
>>> from sympy import Point3D, Plane
|
342 |
+
>>> a = Plane(Point3D(1, 1, 2), Point3D(2, 4, 7), Point3D(3, 5, 1))
|
343 |
+
>>> a.equation()
|
344 |
+
-23*x + 11*y - 2*z + 16
|
345 |
+
>>> a = Plane(Point3D(1, 4, 2), normal_vector=(6, 6, 6))
|
346 |
+
>>> a.equation()
|
347 |
+
6*x + 6*y + 6*z - 42
|
348 |
+
|
349 |
+
"""
|
350 |
+
x, y, z = [i if i else Symbol(j, real=True) for i, j in zip((x, y, z), 'xyz')]
|
351 |
+
a = Point3D(x, y, z)
|
352 |
+
b = self.p1.direction_ratio(a)
|
353 |
+
c = self.normal_vector
|
354 |
+
return (sum(i*j for i, j in zip(b, c)))
|
355 |
+
|
356 |
+
|
357 |
+
def intersection(self, o):
|
358 |
+
""" The intersection with other geometrical entity.
|
359 |
+
|
360 |
+
Parameters
|
361 |
+
==========
|
362 |
+
|
363 |
+
Point, Point3D, LinearEntity, LinearEntity3D, Plane
|
364 |
+
|
365 |
+
Returns
|
366 |
+
=======
|
367 |
+
|
368 |
+
List
|
369 |
+
|
370 |
+
Examples
|
371 |
+
========
|
372 |
+
|
373 |
+
>>> from sympy import Point3D, Line3D, Plane
|
374 |
+
>>> a = Plane(Point3D(1, 2, 3), normal_vector=(1, 1, 1))
|
375 |
+
>>> b = Point3D(1, 2, 3)
|
376 |
+
>>> a.intersection(b)
|
377 |
+
[Point3D(1, 2, 3)]
|
378 |
+
>>> c = Line3D(Point3D(1, 4, 7), Point3D(2, 2, 2))
|
379 |
+
>>> a.intersection(c)
|
380 |
+
[Point3D(2, 2, 2)]
|
381 |
+
>>> d = Plane(Point3D(6, 0, 0), normal_vector=(2, -5, 3))
|
382 |
+
>>> e = Plane(Point3D(2, 0, 0), normal_vector=(3, 4, -3))
|
383 |
+
>>> d.intersection(e)
|
384 |
+
[Line3D(Point3D(78/23, -24/23, 0), Point3D(147/23, 321/23, 23))]
|
385 |
+
|
386 |
+
"""
|
387 |
+
if not isinstance(o, GeometryEntity):
|
388 |
+
o = Point(o, dim=3)
|
389 |
+
if isinstance(o, Point):
|
390 |
+
if o in self:
|
391 |
+
return [o]
|
392 |
+
else:
|
393 |
+
return []
|
394 |
+
if isinstance(o, (LinearEntity, LinearEntity3D)):
|
395 |
+
# recast to 3D
|
396 |
+
p1, p2 = o.p1, o.p2
|
397 |
+
if isinstance(o, Segment):
|
398 |
+
o = Segment3D(p1, p2)
|
399 |
+
elif isinstance(o, Ray):
|
400 |
+
o = Ray3D(p1, p2)
|
401 |
+
elif isinstance(o, Line):
|
402 |
+
o = Line3D(p1, p2)
|
403 |
+
else:
|
404 |
+
raise ValueError('unhandled linear entity: %s' % o.func)
|
405 |
+
if o in self:
|
406 |
+
return [o]
|
407 |
+
else:
|
408 |
+
a = Point3D(o.arbitrary_point(t))
|
409 |
+
p1, n = self.p1, Point3D(self.normal_vector)
|
410 |
+
|
411 |
+
# TODO: Replace solve with solveset, when this line is tested
|
412 |
+
c = solve((a - p1).dot(n), t)
|
413 |
+
if not c:
|
414 |
+
return []
|
415 |
+
else:
|
416 |
+
c = [i for i in c if i.is_real is not False]
|
417 |
+
if len(c) > 1:
|
418 |
+
c = [i for i in c if i.is_real]
|
419 |
+
if len(c) != 1:
|
420 |
+
raise Undecidable("not sure which point is real")
|
421 |
+
p = a.subs(t, c[0])
|
422 |
+
if p not in o:
|
423 |
+
return [] # e.g. a segment might not intersect a plane
|
424 |
+
return [p]
|
425 |
+
if isinstance(o, Plane):
|
426 |
+
if self.equals(o):
|
427 |
+
return [self]
|
428 |
+
if self.is_parallel(o):
|
429 |
+
return []
|
430 |
+
else:
|
431 |
+
x, y, z = map(Dummy, 'xyz')
|
432 |
+
a, b = Matrix([self.normal_vector]), Matrix([o.normal_vector])
|
433 |
+
c = list(a.cross(b))
|
434 |
+
d = self.equation(x, y, z)
|
435 |
+
e = o.equation(x, y, z)
|
436 |
+
result = list(linsolve([d, e], x, y, z))[0]
|
437 |
+
for i in (x, y, z): result = result.subs(i, 0)
|
438 |
+
return [Line3D(Point3D(result), direction_ratio=c)]
|
439 |
+
|
440 |
+
|
441 |
+
def is_coplanar(self, o):
|
442 |
+
""" Returns True if `o` is coplanar with self, else False.
|
443 |
+
|
444 |
+
Examples
|
445 |
+
========
|
446 |
+
|
447 |
+
>>> from sympy import Plane
|
448 |
+
>>> o = (0, 0, 0)
|
449 |
+
>>> p = Plane(o, (1, 1, 1))
|
450 |
+
>>> p2 = Plane(o, (2, 2, 2))
|
451 |
+
>>> p == p2
|
452 |
+
False
|
453 |
+
>>> p.is_coplanar(p2)
|
454 |
+
True
|
455 |
+
"""
|
456 |
+
if isinstance(o, Plane):
|
457 |
+
return not cancel(self.equation(x, y, z)/o.equation(x, y, z)).has(x, y, z)
|
458 |
+
if isinstance(o, Point3D):
|
459 |
+
return o in self
|
460 |
+
elif isinstance(o, LinearEntity3D):
|
461 |
+
return all(i in self for i in self)
|
462 |
+
elif isinstance(o, GeometryEntity): # XXX should only be handling 2D objects now
|
463 |
+
return all(i == 0 for i in self.normal_vector[:2])
|
464 |
+
|
465 |
+
|
466 |
+
def is_parallel(self, l):
|
467 |
+
"""Is the given geometric entity parallel to the plane?
|
468 |
+
|
469 |
+
Parameters
|
470 |
+
==========
|
471 |
+
|
472 |
+
LinearEntity3D or Plane
|
473 |
+
|
474 |
+
Returns
|
475 |
+
=======
|
476 |
+
|
477 |
+
Boolean
|
478 |
+
|
479 |
+
Examples
|
480 |
+
========
|
481 |
+
|
482 |
+
>>> from sympy import Plane, Point3D
|
483 |
+
>>> a = Plane(Point3D(1,4,6), normal_vector=(2, 4, 6))
|
484 |
+
>>> b = Plane(Point3D(3,1,3), normal_vector=(4, 8, 12))
|
485 |
+
>>> a.is_parallel(b)
|
486 |
+
True
|
487 |
+
|
488 |
+
"""
|
489 |
+
if isinstance(l, LinearEntity3D):
|
490 |
+
a = l.direction_ratio
|
491 |
+
b = self.normal_vector
|
492 |
+
c = sum([i*j for i, j in zip(a, b)])
|
493 |
+
if c == 0:
|
494 |
+
return True
|
495 |
+
else:
|
496 |
+
return False
|
497 |
+
elif isinstance(l, Plane):
|
498 |
+
a = Matrix(l.normal_vector)
|
499 |
+
b = Matrix(self.normal_vector)
|
500 |
+
if a.cross(b).is_zero_matrix:
|
501 |
+
return True
|
502 |
+
else:
|
503 |
+
return False
|
504 |
+
|
505 |
+
|
506 |
+
def is_perpendicular(self, l):
|
507 |
+
"""Is the given geometric entity perpendicualar to the given plane?
|
508 |
+
|
509 |
+
Parameters
|
510 |
+
==========
|
511 |
+
|
512 |
+
LinearEntity3D or Plane
|
513 |
+
|
514 |
+
Returns
|
515 |
+
=======
|
516 |
+
|
517 |
+
Boolean
|
518 |
+
|
519 |
+
Examples
|
520 |
+
========
|
521 |
+
|
522 |
+
>>> from sympy import Plane, Point3D
|
523 |
+
>>> a = Plane(Point3D(1,4,6), normal_vector=(2, 4, 6))
|
524 |
+
>>> b = Plane(Point3D(2, 2, 2), normal_vector=(-1, 2, -1))
|
525 |
+
>>> a.is_perpendicular(b)
|
526 |
+
True
|
527 |
+
|
528 |
+
"""
|
529 |
+
if isinstance(l, LinearEntity3D):
|
530 |
+
a = Matrix(l.direction_ratio)
|
531 |
+
b = Matrix(self.normal_vector)
|
532 |
+
if a.cross(b).is_zero_matrix:
|
533 |
+
return True
|
534 |
+
else:
|
535 |
+
return False
|
536 |
+
elif isinstance(l, Plane):
|
537 |
+
a = Matrix(l.normal_vector)
|
538 |
+
b = Matrix(self.normal_vector)
|
539 |
+
if a.dot(b) == 0:
|
540 |
+
return True
|
541 |
+
else:
|
542 |
+
return False
|
543 |
+
else:
|
544 |
+
return False
|
545 |
+
|
546 |
+
@property
|
547 |
+
def normal_vector(self):
|
548 |
+
"""Normal vector of the given plane.
|
549 |
+
|
550 |
+
Examples
|
551 |
+
========
|
552 |
+
|
553 |
+
>>> from sympy import Point3D, Plane
|
554 |
+
>>> a = Plane(Point3D(1, 1, 1), Point3D(2, 3, 4), Point3D(2, 2, 2))
|
555 |
+
>>> a.normal_vector
|
556 |
+
(-1, 2, -1)
|
557 |
+
>>> a = Plane(Point3D(1, 1, 1), normal_vector=(1, 4, 7))
|
558 |
+
>>> a.normal_vector
|
559 |
+
(1, 4, 7)
|
560 |
+
|
561 |
+
"""
|
562 |
+
return self.args[1]
|
563 |
+
|
564 |
+
@property
|
565 |
+
def p1(self):
|
566 |
+
"""The only defining point of the plane. Others can be obtained from the
|
567 |
+
arbitrary_point method.
|
568 |
+
|
569 |
+
See Also
|
570 |
+
========
|
571 |
+
|
572 |
+
sympy.geometry.point.Point3D
|
573 |
+
|
574 |
+
Examples
|
575 |
+
========
|
576 |
+
|
577 |
+
>>> from sympy import Point3D, Plane
|
578 |
+
>>> a = Plane(Point3D(1, 1, 1), Point3D(2, 3, 4), Point3D(2, 2, 2))
|
579 |
+
>>> a.p1
|
580 |
+
Point3D(1, 1, 1)
|
581 |
+
|
582 |
+
"""
|
583 |
+
return self.args[0]
|
584 |
+
|
585 |
+
def parallel_plane(self, pt):
|
586 |
+
"""
|
587 |
+
Plane parallel to the given plane and passing through the point pt.
|
588 |
+
|
589 |
+
Parameters
|
590 |
+
==========
|
591 |
+
|
592 |
+
pt: Point3D
|
593 |
+
|
594 |
+
Returns
|
595 |
+
=======
|
596 |
+
|
597 |
+
Plane
|
598 |
+
|
599 |
+
Examples
|
600 |
+
========
|
601 |
+
|
602 |
+
>>> from sympy import Plane, Point3D
|
603 |
+
>>> a = Plane(Point3D(1, 4, 6), normal_vector=(2, 4, 6))
|
604 |
+
>>> a.parallel_plane(Point3D(2, 3, 5))
|
605 |
+
Plane(Point3D(2, 3, 5), (2, 4, 6))
|
606 |
+
|
607 |
+
"""
|
608 |
+
a = self.normal_vector
|
609 |
+
return Plane(pt, normal_vector=a)
|
610 |
+
|
611 |
+
def perpendicular_line(self, pt):
|
612 |
+
"""A line perpendicular to the given plane.
|
613 |
+
|
614 |
+
Parameters
|
615 |
+
==========
|
616 |
+
|
617 |
+
pt: Point3D
|
618 |
+
|
619 |
+
Returns
|
620 |
+
=======
|
621 |
+
|
622 |
+
Line3D
|
623 |
+
|
624 |
+
Examples
|
625 |
+
========
|
626 |
+
|
627 |
+
>>> from sympy import Plane, Point3D
|
628 |
+
>>> a = Plane(Point3D(1,4,6), normal_vector=(2, 4, 6))
|
629 |
+
>>> a.perpendicular_line(Point3D(9, 8, 7))
|
630 |
+
Line3D(Point3D(9, 8, 7), Point3D(11, 12, 13))
|
631 |
+
|
632 |
+
"""
|
633 |
+
a = self.normal_vector
|
634 |
+
return Line3D(pt, direction_ratio=a)
|
635 |
+
|
636 |
+
def perpendicular_plane(self, *pts):
|
637 |
+
"""
|
638 |
+
Return a perpendicular passing through the given points. If the
|
639 |
+
direction ratio between the points is the same as the Plane's normal
|
640 |
+
vector then, to select from the infinite number of possible planes,
|
641 |
+
a third point will be chosen on the z-axis (or the y-axis
|
642 |
+
if the normal vector is already parallel to the z-axis). If less than
|
643 |
+
two points are given they will be supplied as follows: if no point is
|
644 |
+
given then pt1 will be self.p1; if a second point is not given it will
|
645 |
+
be a point through pt1 on a line parallel to the z-axis (if the normal
|
646 |
+
is not already the z-axis, otherwise on the line parallel to the
|
647 |
+
y-axis).
|
648 |
+
|
649 |
+
Parameters
|
650 |
+
==========
|
651 |
+
|
652 |
+
pts: 0, 1 or 2 Point3D
|
653 |
+
|
654 |
+
Returns
|
655 |
+
=======
|
656 |
+
|
657 |
+
Plane
|
658 |
+
|
659 |
+
Examples
|
660 |
+
========
|
661 |
+
|
662 |
+
>>> from sympy import Plane, Point3D
|
663 |
+
>>> a, b = Point3D(0, 0, 0), Point3D(0, 1, 0)
|
664 |
+
>>> Z = (0, 0, 1)
|
665 |
+
>>> p = Plane(a, normal_vector=Z)
|
666 |
+
>>> p.perpendicular_plane(a, b)
|
667 |
+
Plane(Point3D(0, 0, 0), (1, 0, 0))
|
668 |
+
"""
|
669 |
+
if len(pts) > 2:
|
670 |
+
raise ValueError('No more than 2 pts should be provided.')
|
671 |
+
|
672 |
+
pts = list(pts)
|
673 |
+
if len(pts) == 0:
|
674 |
+
pts.append(self.p1)
|
675 |
+
if len(pts) == 1:
|
676 |
+
x, y, z = self.normal_vector
|
677 |
+
if x == y == 0:
|
678 |
+
dir = (0, 1, 0)
|
679 |
+
else:
|
680 |
+
dir = (0, 0, 1)
|
681 |
+
pts.append(pts[0] + Point3D(*dir))
|
682 |
+
|
683 |
+
p1, p2 = [Point(i, dim=3) for i in pts]
|
684 |
+
l = Line3D(p1, p2)
|
685 |
+
n = Line3D(p1, direction_ratio=self.normal_vector)
|
686 |
+
if l in n: # XXX should an error be raised instead?
|
687 |
+
# there are infinitely many perpendicular planes;
|
688 |
+
x, y, z = self.normal_vector
|
689 |
+
if x == y == 0:
|
690 |
+
# the z axis is the normal so pick a pt on the y-axis
|
691 |
+
p3 = Point3D(0, 1, 0) # case 1
|
692 |
+
else:
|
693 |
+
# else pick a pt on the z axis
|
694 |
+
p3 = Point3D(0, 0, 1) # case 2
|
695 |
+
# in case that point is already given, move it a bit
|
696 |
+
if p3 in l:
|
697 |
+
p3 *= 2 # case 3
|
698 |
+
else:
|
699 |
+
p3 = p1 + Point3D(*self.normal_vector) # case 4
|
700 |
+
return Plane(p1, p2, p3)
|
701 |
+
|
702 |
+
def projection_line(self, line):
|
703 |
+
"""Project the given line onto the plane through the normal plane
|
704 |
+
containing the line.
|
705 |
+
|
706 |
+
Parameters
|
707 |
+
==========
|
708 |
+
|
709 |
+
LinearEntity or LinearEntity3D
|
710 |
+
|
711 |
+
Returns
|
712 |
+
=======
|
713 |
+
|
714 |
+
Point3D, Line3D, Ray3D or Segment3D
|
715 |
+
|
716 |
+
Notes
|
717 |
+
=====
|
718 |
+
|
719 |
+
For the interaction between 2D and 3D lines(segments, rays), you should
|
720 |
+
convert the line to 3D by using this method. For example for finding the
|
721 |
+
intersection between a 2D and a 3D line, convert the 2D line to a 3D line
|
722 |
+
by projecting it on a required plane and then proceed to find the
|
723 |
+
intersection between those lines.
|
724 |
+
|
725 |
+
Examples
|
726 |
+
========
|
727 |
+
|
728 |
+
>>> from sympy import Plane, Line, Line3D, Point3D
|
729 |
+
>>> a = Plane(Point3D(1, 1, 1), normal_vector=(1, 1, 1))
|
730 |
+
>>> b = Line(Point3D(1, 1), Point3D(2, 2))
|
731 |
+
>>> a.projection_line(b)
|
732 |
+
Line3D(Point3D(4/3, 4/3, 1/3), Point3D(5/3, 5/3, -1/3))
|
733 |
+
>>> c = Line3D(Point3D(1, 1, 1), Point3D(2, 2, 2))
|
734 |
+
>>> a.projection_line(c)
|
735 |
+
Point3D(1, 1, 1)
|
736 |
+
|
737 |
+
"""
|
738 |
+
if not isinstance(line, (LinearEntity, LinearEntity3D)):
|
739 |
+
raise NotImplementedError('Enter a linear entity only')
|
740 |
+
a, b = self.projection(line.p1), self.projection(line.p2)
|
741 |
+
if a == b:
|
742 |
+
# projection does not imply intersection so for
|
743 |
+
# this case (line parallel to plane's normal) we
|
744 |
+
# return the projection point
|
745 |
+
return a
|
746 |
+
if isinstance(line, (Line, Line3D)):
|
747 |
+
return Line3D(a, b)
|
748 |
+
if isinstance(line, (Ray, Ray3D)):
|
749 |
+
return Ray3D(a, b)
|
750 |
+
if isinstance(line, (Segment, Segment3D)):
|
751 |
+
return Segment3D(a, b)
|
752 |
+
|
753 |
+
def projection(self, pt):
|
754 |
+
"""Project the given point onto the plane along the plane normal.
|
755 |
+
|
756 |
+
Parameters
|
757 |
+
==========
|
758 |
+
|
759 |
+
Point or Point3D
|
760 |
+
|
761 |
+
Returns
|
762 |
+
=======
|
763 |
+
|
764 |
+
Point3D
|
765 |
+
|
766 |
+
Examples
|
767 |
+
========
|
768 |
+
|
769 |
+
>>> from sympy import Plane, Point3D
|
770 |
+
>>> A = Plane(Point3D(1, 1, 2), normal_vector=(1, 1, 1))
|
771 |
+
|
772 |
+
The projection is along the normal vector direction, not the z
|
773 |
+
axis, so (1, 1) does not project to (1, 1, 2) on the plane A:
|
774 |
+
|
775 |
+
>>> b = Point3D(1, 1)
|
776 |
+
>>> A.projection(b)
|
777 |
+
Point3D(5/3, 5/3, 2/3)
|
778 |
+
>>> _ in A
|
779 |
+
True
|
780 |
+
|
781 |
+
But the point (1, 1, 2) projects to (1, 1) on the XY-plane:
|
782 |
+
|
783 |
+
>>> XY = Plane((0, 0, 0), (0, 0, 1))
|
784 |
+
>>> XY.projection((1, 1, 2))
|
785 |
+
Point3D(1, 1, 0)
|
786 |
+
"""
|
787 |
+
rv = Point(pt, dim=3)
|
788 |
+
if rv in self:
|
789 |
+
return rv
|
790 |
+
return self.intersection(Line3D(rv, rv + Point3D(self.normal_vector)))[0]
|
791 |
+
|
792 |
+
def random_point(self, seed=None):
|
793 |
+
""" Returns a random point on the Plane.
|
794 |
+
|
795 |
+
Returns
|
796 |
+
=======
|
797 |
+
|
798 |
+
Point3D
|
799 |
+
|
800 |
+
Examples
|
801 |
+
========
|
802 |
+
|
803 |
+
>>> from sympy import Plane
|
804 |
+
>>> p = Plane((1, 0, 0), normal_vector=(0, 1, 0))
|
805 |
+
>>> r = p.random_point(seed=42) # seed value is optional
|
806 |
+
>>> r.n(3)
|
807 |
+
Point3D(2.29, 0, -1.35)
|
808 |
+
|
809 |
+
The random point can be moved to lie on the circle of radius
|
810 |
+
1 centered on p1:
|
811 |
+
|
812 |
+
>>> c = p.p1 + (r - p.p1).unit
|
813 |
+
>>> c.distance(p.p1).equals(1)
|
814 |
+
True
|
815 |
+
"""
|
816 |
+
if seed is not None:
|
817 |
+
rng = random.Random(seed)
|
818 |
+
else:
|
819 |
+
rng = random
|
820 |
+
params = {
|
821 |
+
x: 2*Rational(rng.gauss(0, 1)) - 1,
|
822 |
+
y: 2*Rational(rng.gauss(0, 1)) - 1}
|
823 |
+
return self.arbitrary_point(x, y).subs(params)
|
824 |
+
|
825 |
+
def parameter_value(self, other, u, v=None):
|
826 |
+
"""Return the parameter(s) corresponding to the given point.
|
827 |
+
|
828 |
+
Examples
|
829 |
+
========
|
830 |
+
|
831 |
+
>>> from sympy import pi, Plane
|
832 |
+
>>> from sympy.abc import t, u, v
|
833 |
+
>>> p = Plane((2, 0, 0), (0, 0, 1), (0, 1, 0))
|
834 |
+
|
835 |
+
By default, the parameter value returned defines a point
|
836 |
+
that is a distance of 1 from the Plane's p1 value and
|
837 |
+
in line with the given point:
|
838 |
+
|
839 |
+
>>> on_circle = p.arbitrary_point(t).subs(t, pi/4)
|
840 |
+
>>> on_circle.distance(p.p1)
|
841 |
+
1
|
842 |
+
>>> p.parameter_value(on_circle, t)
|
843 |
+
{t: pi/4}
|
844 |
+
|
845 |
+
Moving the point twice as far from p1 does not change
|
846 |
+
the parameter value:
|
847 |
+
|
848 |
+
>>> off_circle = p.p1 + (on_circle - p.p1)*2
|
849 |
+
>>> off_circle.distance(p.p1)
|
850 |
+
2
|
851 |
+
>>> p.parameter_value(off_circle, t)
|
852 |
+
{t: pi/4}
|
853 |
+
|
854 |
+
If the 2-value parameter is desired, supply the two
|
855 |
+
parameter symbols and a replacement dictionary will
|
856 |
+
be returned:
|
857 |
+
|
858 |
+
>>> p.parameter_value(on_circle, u, v)
|
859 |
+
{u: sqrt(10)/10, v: sqrt(10)/30}
|
860 |
+
>>> p.parameter_value(off_circle, u, v)
|
861 |
+
{u: sqrt(10)/5, v: sqrt(10)/15}
|
862 |
+
"""
|
863 |
+
if not isinstance(other, GeometryEntity):
|
864 |
+
other = Point(other, dim=self.ambient_dimension)
|
865 |
+
if not isinstance(other, Point):
|
866 |
+
raise ValueError("other must be a point")
|
867 |
+
if other == self.p1:
|
868 |
+
return other
|
869 |
+
if isinstance(u, Symbol) and v is None:
|
870 |
+
delta = self.arbitrary_point(u) - self.p1
|
871 |
+
eq = delta - (other - self.p1).unit
|
872 |
+
sol = solve(eq, u, dict=True)
|
873 |
+
elif isinstance(u, Symbol) and isinstance(v, Symbol):
|
874 |
+
pt = self.arbitrary_point(u, v)
|
875 |
+
sol = solve(pt - other, (u, v), dict=True)
|
876 |
+
else:
|
877 |
+
raise ValueError('expecting 1 or 2 symbols')
|
878 |
+
if not sol:
|
879 |
+
raise ValueError("Given point is not on %s" % func_name(self))
|
880 |
+
return sol[0] # {t: tval} or {u: uval, v: vval}
|
881 |
+
|
882 |
+
@property
|
883 |
+
def ambient_dimension(self):
|
884 |
+
return self.p1.ambient_dimension
|
env-llmeval/lib/python3.10/site-packages/sympy/geometry/point.py
ADDED
@@ -0,0 +1,1378 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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]
|
env-llmeval/lib/python3.10/site-packages/sympy/printing/pretty/__init__.py
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""ASCII-ART 2D pretty-printer"""
|
2 |
+
|
3 |
+
from .pretty import (pretty, pretty_print, pprint, pprint_use_unicode,
|
4 |
+
pprint_try_use_unicode, pager_print)
|
5 |
+
|
6 |
+
# if unicode output is available -- let's use it
|
7 |
+
pprint_try_use_unicode()
|
8 |
+
|
9 |
+
__all__ = [
|
10 |
+
'pretty', 'pretty_print', 'pprint', 'pprint_use_unicode',
|
11 |
+
'pprint_try_use_unicode', 'pager_print',
|
12 |
+
]
|
env-llmeval/lib/python3.10/site-packages/sympy/printing/pretty/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (410 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/printing/pretty/__pycache__/pretty.cpython-310.pyc
ADDED
Binary file (84.1 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/printing/pretty/__pycache__/pretty_symbology.cpython-310.pyc
ADDED
Binary file (17.3 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/printing/pretty/__pycache__/stringpict.cpython-310.pyc
ADDED
Binary file (15.8 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/printing/pretty/pretty.py
ADDED
The diff for this file is too large to render.
See raw diff
|
|
env-llmeval/lib/python3.10/site-packages/sympy/printing/pretty/pretty_symbology.py
ADDED
@@ -0,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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Symbolic primitives + unicode/ASCII abstraction for pretty.py"""
|
2 |
+
|
3 |
+
import sys
|
4 |
+
import warnings
|
5 |
+
from string import ascii_lowercase, ascii_uppercase
|
6 |
+
import unicodedata
|
7 |
+
|
8 |
+
unicode_warnings = ''
|
9 |
+
|
10 |
+
def U(name):
|
11 |
+
"""
|
12 |
+
Get a unicode character by name or, None if not found.
|
13 |
+
|
14 |
+
This exists because older versions of Python use older unicode databases.
|
15 |
+
"""
|
16 |
+
try:
|
17 |
+
return unicodedata.lookup(name)
|
18 |
+
except KeyError:
|
19 |
+
global unicode_warnings
|
20 |
+
unicode_warnings += 'No \'%s\' in unicodedata\n' % name
|
21 |
+
return None
|
22 |
+
|
23 |
+
from sympy.printing.conventions import split_super_sub
|
24 |
+
from sympy.core.alphabets import greeks
|
25 |
+
from sympy.utilities.exceptions import sympy_deprecation_warning
|
26 |
+
|
27 |
+
# prefix conventions when constructing tables
|
28 |
+
# L - LATIN i
|
29 |
+
# G - GREEK beta
|
30 |
+
# D - DIGIT 0
|
31 |
+
# S - SYMBOL +
|
32 |
+
|
33 |
+
|
34 |
+
__all__ = ['greek_unicode', 'sub', 'sup', 'xsym', 'vobj', 'hobj', 'pretty_symbol',
|
35 |
+
'annotated']
|
36 |
+
|
37 |
+
|
38 |
+
_use_unicode = False
|
39 |
+
|
40 |
+
|
41 |
+
def pretty_use_unicode(flag=None):
|
42 |
+
"""Set whether pretty-printer should use unicode by default"""
|
43 |
+
global _use_unicode
|
44 |
+
global unicode_warnings
|
45 |
+
if flag is None:
|
46 |
+
return _use_unicode
|
47 |
+
|
48 |
+
if flag and unicode_warnings:
|
49 |
+
# print warnings (if any) on first unicode usage
|
50 |
+
warnings.warn(unicode_warnings)
|
51 |
+
unicode_warnings = ''
|
52 |
+
|
53 |
+
use_unicode_prev = _use_unicode
|
54 |
+
_use_unicode = flag
|
55 |
+
return use_unicode_prev
|
56 |
+
|
57 |
+
|
58 |
+
def pretty_try_use_unicode():
|
59 |
+
"""See if unicode output is available and leverage it if possible"""
|
60 |
+
|
61 |
+
encoding = getattr(sys.stdout, 'encoding', None)
|
62 |
+
|
63 |
+
# this happens when e.g. stdout is redirected through a pipe, or is
|
64 |
+
# e.g. a cStringIO.StringO
|
65 |
+
if encoding is None:
|
66 |
+
return # sys.stdout has no encoding
|
67 |
+
|
68 |
+
symbols = []
|
69 |
+
|
70 |
+
# see if we can represent greek alphabet
|
71 |
+
symbols += greek_unicode.values()
|
72 |
+
|
73 |
+
# and atoms
|
74 |
+
symbols += atoms_table.values()
|
75 |
+
|
76 |
+
for s in symbols:
|
77 |
+
if s is None:
|
78 |
+
return # common symbols not present!
|
79 |
+
|
80 |
+
try:
|
81 |
+
s.encode(encoding)
|
82 |
+
except UnicodeEncodeError:
|
83 |
+
return
|
84 |
+
|
85 |
+
# all the characters were present and encodable
|
86 |
+
pretty_use_unicode(True)
|
87 |
+
|
88 |
+
|
89 |
+
def xstr(*args):
|
90 |
+
sympy_deprecation_warning(
|
91 |
+
"""
|
92 |
+
The sympy.printing.pretty.pretty_symbology.xstr() function is
|
93 |
+
deprecated. Use str() instead.
|
94 |
+
""",
|
95 |
+
deprecated_since_version="1.7",
|
96 |
+
active_deprecations_target="deprecated-pretty-printing-functions"
|
97 |
+
)
|
98 |
+
return str(*args)
|
99 |
+
|
100 |
+
# GREEK
|
101 |
+
g = lambda l: U('GREEK SMALL LETTER %s' % l.upper())
|
102 |
+
G = lambda l: U('GREEK CAPITAL LETTER %s' % l.upper())
|
103 |
+
|
104 |
+
greek_letters = list(greeks) # make a copy
|
105 |
+
# deal with Unicode's funny spelling of lambda
|
106 |
+
greek_letters[greek_letters.index('lambda')] = 'lamda'
|
107 |
+
|
108 |
+
# {} greek letter -> (g,G)
|
109 |
+
greek_unicode = {L: g(L) for L in greek_letters}
|
110 |
+
greek_unicode.update((L[0].upper() + L[1:], G(L)) for L in greek_letters)
|
111 |
+
|
112 |
+
# aliases
|
113 |
+
greek_unicode['lambda'] = greek_unicode['lamda']
|
114 |
+
greek_unicode['Lambda'] = greek_unicode['Lamda']
|
115 |
+
greek_unicode['varsigma'] = '\N{GREEK SMALL LETTER FINAL SIGMA}'
|
116 |
+
|
117 |
+
# BOLD
|
118 |
+
b = lambda l: U('MATHEMATICAL BOLD SMALL %s' % l.upper())
|
119 |
+
B = lambda l: U('MATHEMATICAL BOLD CAPITAL %s' % l.upper())
|
120 |
+
|
121 |
+
bold_unicode = {l: b(l) for l in ascii_lowercase}
|
122 |
+
bold_unicode.update((L, B(L)) for L in ascii_uppercase)
|
123 |
+
|
124 |
+
# GREEK BOLD
|
125 |
+
gb = lambda l: U('MATHEMATICAL BOLD SMALL %s' % l.upper())
|
126 |
+
GB = lambda l: U('MATHEMATICAL BOLD CAPITAL %s' % l.upper())
|
127 |
+
|
128 |
+
greek_bold_letters = list(greeks) # make a copy, not strictly required here
|
129 |
+
# deal with Unicode's funny spelling of lambda
|
130 |
+
greek_bold_letters[greek_bold_letters.index('lambda')] = 'lamda'
|
131 |
+
|
132 |
+
# {} greek letter -> (g,G)
|
133 |
+
greek_bold_unicode = {L: g(L) for L in greek_bold_letters}
|
134 |
+
greek_bold_unicode.update((L[0].upper() + L[1:], G(L)) for L in greek_bold_letters)
|
135 |
+
greek_bold_unicode['lambda'] = greek_unicode['lamda']
|
136 |
+
greek_bold_unicode['Lambda'] = greek_unicode['Lamda']
|
137 |
+
greek_bold_unicode['varsigma'] = '\N{MATHEMATICAL BOLD SMALL FINAL SIGMA}'
|
138 |
+
|
139 |
+
digit_2txt = {
|
140 |
+
'0': 'ZERO',
|
141 |
+
'1': 'ONE',
|
142 |
+
'2': 'TWO',
|
143 |
+
'3': 'THREE',
|
144 |
+
'4': 'FOUR',
|
145 |
+
'5': 'FIVE',
|
146 |
+
'6': 'SIX',
|
147 |
+
'7': 'SEVEN',
|
148 |
+
'8': 'EIGHT',
|
149 |
+
'9': 'NINE',
|
150 |
+
}
|
151 |
+
|
152 |
+
symb_2txt = {
|
153 |
+
'+': 'PLUS SIGN',
|
154 |
+
'-': 'MINUS',
|
155 |
+
'=': 'EQUALS SIGN',
|
156 |
+
'(': 'LEFT PARENTHESIS',
|
157 |
+
')': 'RIGHT PARENTHESIS',
|
158 |
+
'[': 'LEFT SQUARE BRACKET',
|
159 |
+
']': 'RIGHT SQUARE BRACKET',
|
160 |
+
'{': 'LEFT CURLY BRACKET',
|
161 |
+
'}': 'RIGHT CURLY BRACKET',
|
162 |
+
|
163 |
+
# non-std
|
164 |
+
'{}': 'CURLY BRACKET',
|
165 |
+
'sum': 'SUMMATION',
|
166 |
+
'int': 'INTEGRAL',
|
167 |
+
}
|
168 |
+
|
169 |
+
# SUBSCRIPT & SUPERSCRIPT
|
170 |
+
LSUB = lambda letter: U('LATIN SUBSCRIPT SMALL LETTER %s' % letter.upper())
|
171 |
+
GSUB = lambda letter: U('GREEK SUBSCRIPT SMALL LETTER %s' % letter.upper())
|
172 |
+
DSUB = lambda digit: U('SUBSCRIPT %s' % digit_2txt[digit])
|
173 |
+
SSUB = lambda symb: U('SUBSCRIPT %s' % symb_2txt[symb])
|
174 |
+
|
175 |
+
LSUP = lambda letter: U('SUPERSCRIPT LATIN SMALL LETTER %s' % letter.upper())
|
176 |
+
DSUP = lambda digit: U('SUPERSCRIPT %s' % digit_2txt[digit])
|
177 |
+
SSUP = lambda symb: U('SUPERSCRIPT %s' % symb_2txt[symb])
|
178 |
+
|
179 |
+
sub = {} # symb -> subscript symbol
|
180 |
+
sup = {} # symb -> superscript symbol
|
181 |
+
|
182 |
+
# latin subscripts
|
183 |
+
for l in 'aeioruvxhklmnpst':
|
184 |
+
sub[l] = LSUB(l)
|
185 |
+
|
186 |
+
for l in 'in':
|
187 |
+
sup[l] = LSUP(l)
|
188 |
+
|
189 |
+
for gl in ['beta', 'gamma', 'rho', 'phi', 'chi']:
|
190 |
+
sub[gl] = GSUB(gl)
|
191 |
+
|
192 |
+
for d in [str(i) for i in range(10)]:
|
193 |
+
sub[d] = DSUB(d)
|
194 |
+
sup[d] = DSUP(d)
|
195 |
+
|
196 |
+
for s in '+-=()':
|
197 |
+
sub[s] = SSUB(s)
|
198 |
+
sup[s] = SSUP(s)
|
199 |
+
|
200 |
+
# Variable modifiers
|
201 |
+
# TODO: Make brackets adjust to height of contents
|
202 |
+
modifier_dict = {
|
203 |
+
# Accents
|
204 |
+
'mathring': lambda s: center_accent(s, '\N{COMBINING RING ABOVE}'),
|
205 |
+
'ddddot': lambda s: center_accent(s, '\N{COMBINING FOUR DOTS ABOVE}'),
|
206 |
+
'dddot': lambda s: center_accent(s, '\N{COMBINING THREE DOTS ABOVE}'),
|
207 |
+
'ddot': lambda s: center_accent(s, '\N{COMBINING DIAERESIS}'),
|
208 |
+
'dot': lambda s: center_accent(s, '\N{COMBINING DOT ABOVE}'),
|
209 |
+
'check': lambda s: center_accent(s, '\N{COMBINING CARON}'),
|
210 |
+
'breve': lambda s: center_accent(s, '\N{COMBINING BREVE}'),
|
211 |
+
'acute': lambda s: center_accent(s, '\N{COMBINING ACUTE ACCENT}'),
|
212 |
+
'grave': lambda s: center_accent(s, '\N{COMBINING GRAVE ACCENT}'),
|
213 |
+
'tilde': lambda s: center_accent(s, '\N{COMBINING TILDE}'),
|
214 |
+
'hat': lambda s: center_accent(s, '\N{COMBINING CIRCUMFLEX ACCENT}'),
|
215 |
+
'bar': lambda s: center_accent(s, '\N{COMBINING OVERLINE}'),
|
216 |
+
'vec': lambda s: center_accent(s, '\N{COMBINING RIGHT ARROW ABOVE}'),
|
217 |
+
'prime': lambda s: s+'\N{PRIME}',
|
218 |
+
'prm': lambda s: s+'\N{PRIME}',
|
219 |
+
# # Faces -- these are here for some compatibility with latex printing
|
220 |
+
# 'bold': lambda s: s,
|
221 |
+
# 'bm': lambda s: s,
|
222 |
+
# 'cal': lambda s: s,
|
223 |
+
# 'scr': lambda s: s,
|
224 |
+
# 'frak': lambda s: s,
|
225 |
+
# Brackets
|
226 |
+
'norm': lambda s: '\N{DOUBLE VERTICAL LINE}'+s+'\N{DOUBLE VERTICAL LINE}',
|
227 |
+
'avg': lambda s: '\N{MATHEMATICAL LEFT ANGLE BRACKET}'+s+'\N{MATHEMATICAL RIGHT ANGLE BRACKET}',
|
228 |
+
'abs': lambda s: '\N{VERTICAL LINE}'+s+'\N{VERTICAL LINE}',
|
229 |
+
'mag': lambda s: '\N{VERTICAL LINE}'+s+'\N{VERTICAL LINE}',
|
230 |
+
}
|
231 |
+
|
232 |
+
# VERTICAL OBJECTS
|
233 |
+
HUP = lambda symb: U('%s UPPER HOOK' % symb_2txt[symb])
|
234 |
+
CUP = lambda symb: U('%s UPPER CORNER' % symb_2txt[symb])
|
235 |
+
MID = lambda symb: U('%s MIDDLE PIECE' % symb_2txt[symb])
|
236 |
+
EXT = lambda symb: U('%s EXTENSION' % symb_2txt[symb])
|
237 |
+
HLO = lambda symb: U('%s LOWER HOOK' % symb_2txt[symb])
|
238 |
+
CLO = lambda symb: U('%s LOWER CORNER' % symb_2txt[symb])
|
239 |
+
TOP = lambda symb: U('%s TOP' % symb_2txt[symb])
|
240 |
+
BOT = lambda symb: U('%s BOTTOM' % symb_2txt[symb])
|
241 |
+
|
242 |
+
# {} '(' -> (extension, start, end, middle) 1-character
|
243 |
+
_xobj_unicode = {
|
244 |
+
|
245 |
+
# vertical symbols
|
246 |
+
# (( ext, top, bot, mid ), c1)
|
247 |
+
'(': (( EXT('('), HUP('('), HLO('(') ), '('),
|
248 |
+
')': (( EXT(')'), HUP(')'), HLO(')') ), ')'),
|
249 |
+
'[': (( EXT('['), CUP('['), CLO('[') ), '['),
|
250 |
+
']': (( EXT(']'), CUP(']'), CLO(']') ), ']'),
|
251 |
+
'{': (( EXT('{}'), HUP('{'), HLO('{'), MID('{') ), '{'),
|
252 |
+
'}': (( EXT('{}'), HUP('}'), HLO('}'), MID('}') ), '}'),
|
253 |
+
'|': U('BOX DRAWINGS LIGHT VERTICAL'),
|
254 |
+
|
255 |
+
'<': ((U('BOX DRAWINGS LIGHT VERTICAL'),
|
256 |
+
U('BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT'),
|
257 |
+
U('BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT')), '<'),
|
258 |
+
|
259 |
+
'>': ((U('BOX DRAWINGS LIGHT VERTICAL'),
|
260 |
+
U('BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT'),
|
261 |
+
U('BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT')), '>'),
|
262 |
+
|
263 |
+
'lfloor': (( EXT('['), EXT('['), CLO('[') ), U('LEFT FLOOR')),
|
264 |
+
'rfloor': (( EXT(']'), EXT(']'), CLO(']') ), U('RIGHT FLOOR')),
|
265 |
+
'lceil': (( EXT('['), CUP('['), EXT('[') ), U('LEFT CEILING')),
|
266 |
+
'rceil': (( EXT(']'), CUP(']'), EXT(']') ), U('RIGHT CEILING')),
|
267 |
+
|
268 |
+
'int': (( EXT('int'), U('TOP HALF INTEGRAL'), U('BOTTOM HALF INTEGRAL') ), U('INTEGRAL')),
|
269 |
+
'sum': (( U('BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT'), '_', U('OVERLINE'), U('BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT')), U('N-ARY SUMMATION')),
|
270 |
+
|
271 |
+
# horizontal objects
|
272 |
+
#'-': '-',
|
273 |
+
'-': U('BOX DRAWINGS LIGHT HORIZONTAL'),
|
274 |
+
'_': U('LOW LINE'),
|
275 |
+
# We used to use this, but LOW LINE looks better for roots, as it's a
|
276 |
+
# little lower (i.e., it lines up with the / perfectly. But perhaps this
|
277 |
+
# one would still be wanted for some cases?
|
278 |
+
# '_': U('HORIZONTAL SCAN LINE-9'),
|
279 |
+
|
280 |
+
# diagonal objects '\' & '/' ?
|
281 |
+
'/': U('BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT'),
|
282 |
+
'\\': U('BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT'),
|
283 |
+
}
|
284 |
+
|
285 |
+
_xobj_ascii = {
|
286 |
+
# vertical symbols
|
287 |
+
# (( ext, top, bot, mid ), c1)
|
288 |
+
'(': (( '|', '/', '\\' ), '('),
|
289 |
+
')': (( '|', '\\', '/' ), ')'),
|
290 |
+
|
291 |
+
# XXX this looks ugly
|
292 |
+
# '[': (( '|', '-', '-' ), '['),
|
293 |
+
# ']': (( '|', '-', '-' ), ']'),
|
294 |
+
# XXX not so ugly :(
|
295 |
+
'[': (( '[', '[', '[' ), '['),
|
296 |
+
']': (( ']', ']', ']' ), ']'),
|
297 |
+
|
298 |
+
'{': (( '|', '/', '\\', '<' ), '{'),
|
299 |
+
'}': (( '|', '\\', '/', '>' ), '}'),
|
300 |
+
'|': '|',
|
301 |
+
|
302 |
+
'<': (( '|', '/', '\\' ), '<'),
|
303 |
+
'>': (( '|', '\\', '/' ), '>'),
|
304 |
+
|
305 |
+
'int': ( ' | ', ' /', '/ ' ),
|
306 |
+
|
307 |
+
# horizontal objects
|
308 |
+
'-': '-',
|
309 |
+
'_': '_',
|
310 |
+
|
311 |
+
# diagonal objects '\' & '/' ?
|
312 |
+
'/': '/',
|
313 |
+
'\\': '\\',
|
314 |
+
}
|
315 |
+
|
316 |
+
|
317 |
+
def xobj(symb, length):
|
318 |
+
"""Construct spatial object of given length.
|
319 |
+
|
320 |
+
return: [] of equal-length strings
|
321 |
+
"""
|
322 |
+
|
323 |
+
if length <= 0:
|
324 |
+
raise ValueError("Length should be greater than 0")
|
325 |
+
|
326 |
+
# TODO robustify when no unicodedat available
|
327 |
+
if _use_unicode:
|
328 |
+
_xobj = _xobj_unicode
|
329 |
+
else:
|
330 |
+
_xobj = _xobj_ascii
|
331 |
+
|
332 |
+
vinfo = _xobj[symb]
|
333 |
+
|
334 |
+
c1 = top = bot = mid = None
|
335 |
+
|
336 |
+
if not isinstance(vinfo, tuple): # 1 entry
|
337 |
+
ext = vinfo
|
338 |
+
else:
|
339 |
+
if isinstance(vinfo[0], tuple): # (vlong), c1
|
340 |
+
vlong = vinfo[0]
|
341 |
+
c1 = vinfo[1]
|
342 |
+
else: # (vlong), c1
|
343 |
+
vlong = vinfo
|
344 |
+
|
345 |
+
ext = vlong[0]
|
346 |
+
|
347 |
+
try:
|
348 |
+
top = vlong[1]
|
349 |
+
bot = vlong[2]
|
350 |
+
mid = vlong[3]
|
351 |
+
except IndexError:
|
352 |
+
pass
|
353 |
+
|
354 |
+
if c1 is None:
|
355 |
+
c1 = ext
|
356 |
+
if top is None:
|
357 |
+
top = ext
|
358 |
+
if bot is None:
|
359 |
+
bot = ext
|
360 |
+
if mid is not None:
|
361 |
+
if (length % 2) == 0:
|
362 |
+
# even height, but we have to print it somehow anyway...
|
363 |
+
# XXX is it ok?
|
364 |
+
length += 1
|
365 |
+
|
366 |
+
else:
|
367 |
+
mid = ext
|
368 |
+
|
369 |
+
if length == 1:
|
370 |
+
return c1
|
371 |
+
|
372 |
+
res = []
|
373 |
+
next = (length - 2)//2
|
374 |
+
nmid = (length - 2) - next*2
|
375 |
+
|
376 |
+
res += [top]
|
377 |
+
res += [ext]*next
|
378 |
+
res += [mid]*nmid
|
379 |
+
res += [ext]*next
|
380 |
+
res += [bot]
|
381 |
+
|
382 |
+
return res
|
383 |
+
|
384 |
+
|
385 |
+
def vobj(symb, height):
|
386 |
+
"""Construct vertical object of a given height
|
387 |
+
|
388 |
+
see: xobj
|
389 |
+
"""
|
390 |
+
return '\n'.join( xobj(symb, height) )
|
391 |
+
|
392 |
+
|
393 |
+
def hobj(symb, width):
|
394 |
+
"""Construct horizontal object of a given width
|
395 |
+
|
396 |
+
see: xobj
|
397 |
+
"""
|
398 |
+
return ''.join( xobj(symb, width) )
|
399 |
+
|
400 |
+
# RADICAL
|
401 |
+
# n -> symbol
|
402 |
+
root = {
|
403 |
+
2: U('SQUARE ROOT'), # U('RADICAL SYMBOL BOTTOM')
|
404 |
+
3: U('CUBE ROOT'),
|
405 |
+
4: U('FOURTH ROOT'),
|
406 |
+
}
|
407 |
+
|
408 |
+
|
409 |
+
# RATIONAL
|
410 |
+
VF = lambda txt: U('VULGAR FRACTION %s' % txt)
|
411 |
+
|
412 |
+
# (p,q) -> symbol
|
413 |
+
frac = {
|
414 |
+
(1, 2): VF('ONE HALF'),
|
415 |
+
(1, 3): VF('ONE THIRD'),
|
416 |
+
(2, 3): VF('TWO THIRDS'),
|
417 |
+
(1, 4): VF('ONE QUARTER'),
|
418 |
+
(3, 4): VF('THREE QUARTERS'),
|
419 |
+
(1, 5): VF('ONE FIFTH'),
|
420 |
+
(2, 5): VF('TWO FIFTHS'),
|
421 |
+
(3, 5): VF('THREE FIFTHS'),
|
422 |
+
(4, 5): VF('FOUR FIFTHS'),
|
423 |
+
(1, 6): VF('ONE SIXTH'),
|
424 |
+
(5, 6): VF('FIVE SIXTHS'),
|
425 |
+
(1, 8): VF('ONE EIGHTH'),
|
426 |
+
(3, 8): VF('THREE EIGHTHS'),
|
427 |
+
(5, 8): VF('FIVE EIGHTHS'),
|
428 |
+
(7, 8): VF('SEVEN EIGHTHS'),
|
429 |
+
}
|
430 |
+
|
431 |
+
|
432 |
+
# atom symbols
|
433 |
+
_xsym = {
|
434 |
+
'==': ('=', '='),
|
435 |
+
'<': ('<', '<'),
|
436 |
+
'>': ('>', '>'),
|
437 |
+
'<=': ('<=', U('LESS-THAN OR EQUAL TO')),
|
438 |
+
'>=': ('>=', U('GREATER-THAN OR EQUAL TO')),
|
439 |
+
'!=': ('!=', U('NOT EQUAL TO')),
|
440 |
+
':=': (':=', ':='),
|
441 |
+
'+=': ('+=', '+='),
|
442 |
+
'-=': ('-=', '-='),
|
443 |
+
'*=': ('*=', '*='),
|
444 |
+
'/=': ('/=', '/='),
|
445 |
+
'%=': ('%=', '%='),
|
446 |
+
'*': ('*', U('DOT OPERATOR')),
|
447 |
+
'-->': ('-->', U('EM DASH') + U('EM DASH') +
|
448 |
+
U('BLACK RIGHT-POINTING TRIANGLE') if U('EM DASH')
|
449 |
+
and U('BLACK RIGHT-POINTING TRIANGLE') else None),
|
450 |
+
'==>': ('==>', U('BOX DRAWINGS DOUBLE HORIZONTAL') +
|
451 |
+
U('BOX DRAWINGS DOUBLE HORIZONTAL') +
|
452 |
+
U('BLACK RIGHT-POINTING TRIANGLE') if
|
453 |
+
U('BOX DRAWINGS DOUBLE HORIZONTAL') and
|
454 |
+
U('BOX DRAWINGS DOUBLE HORIZONTAL') and
|
455 |
+
U('BLACK RIGHT-POINTING TRIANGLE') else None),
|
456 |
+
'.': ('*', U('RING OPERATOR')),
|
457 |
+
}
|
458 |
+
|
459 |
+
|
460 |
+
def xsym(sym):
|
461 |
+
"""get symbology for a 'character'"""
|
462 |
+
op = _xsym[sym]
|
463 |
+
|
464 |
+
if _use_unicode:
|
465 |
+
return op[1]
|
466 |
+
else:
|
467 |
+
return op[0]
|
468 |
+
|
469 |
+
|
470 |
+
# SYMBOLS
|
471 |
+
|
472 |
+
atoms_table = {
|
473 |
+
# class how-to-display
|
474 |
+
'Exp1': U('SCRIPT SMALL E'),
|
475 |
+
'Pi': U('GREEK SMALL LETTER PI'),
|
476 |
+
'Infinity': U('INFINITY'),
|
477 |
+
'NegativeInfinity': U('INFINITY') and ('-' + U('INFINITY')), # XXX what to do here
|
478 |
+
#'ImaginaryUnit': U('GREEK SMALL LETTER IOTA'),
|
479 |
+
#'ImaginaryUnit': U('MATHEMATICAL ITALIC SMALL I'),
|
480 |
+
'ImaginaryUnit': U('DOUBLE-STRUCK ITALIC SMALL I'),
|
481 |
+
'EmptySet': U('EMPTY SET'),
|
482 |
+
'Naturals': U('DOUBLE-STRUCK CAPITAL N'),
|
483 |
+
'Naturals0': (U('DOUBLE-STRUCK CAPITAL N') and
|
484 |
+
(U('DOUBLE-STRUCK CAPITAL N') +
|
485 |
+
U('SUBSCRIPT ZERO'))),
|
486 |
+
'Integers': U('DOUBLE-STRUCK CAPITAL Z'),
|
487 |
+
'Rationals': U('DOUBLE-STRUCK CAPITAL Q'),
|
488 |
+
'Reals': U('DOUBLE-STRUCK CAPITAL R'),
|
489 |
+
'Complexes': U('DOUBLE-STRUCK CAPITAL C'),
|
490 |
+
'Union': U('UNION'),
|
491 |
+
'SymmetricDifference': U('INCREMENT'),
|
492 |
+
'Intersection': U('INTERSECTION'),
|
493 |
+
'Ring': U('RING OPERATOR'),
|
494 |
+
'Modifier Letter Low Ring':U('Modifier Letter Low Ring'),
|
495 |
+
'EmptySequence': 'EmptySequence',
|
496 |
+
}
|
497 |
+
|
498 |
+
|
499 |
+
def pretty_atom(atom_name, default=None, printer=None):
|
500 |
+
"""return pretty representation of an atom"""
|
501 |
+
if _use_unicode:
|
502 |
+
if printer is not None and atom_name == 'ImaginaryUnit' and printer._settings['imaginary_unit'] == 'j':
|
503 |
+
return U('DOUBLE-STRUCK ITALIC SMALL J')
|
504 |
+
else:
|
505 |
+
return atoms_table[atom_name]
|
506 |
+
else:
|
507 |
+
if default is not None:
|
508 |
+
return default
|
509 |
+
|
510 |
+
raise KeyError('only unicode') # send it default printer
|
511 |
+
|
512 |
+
|
513 |
+
def pretty_symbol(symb_name, bold_name=False):
|
514 |
+
"""return pretty representation of a symbol"""
|
515 |
+
# let's split symb_name into symbol + index
|
516 |
+
# UC: beta1
|
517 |
+
# UC: f_beta
|
518 |
+
|
519 |
+
if not _use_unicode:
|
520 |
+
return symb_name
|
521 |
+
|
522 |
+
name, sups, subs = split_super_sub(symb_name)
|
523 |
+
|
524 |
+
def translate(s, bold_name) :
|
525 |
+
if bold_name:
|
526 |
+
gG = greek_bold_unicode.get(s)
|
527 |
+
else:
|
528 |
+
gG = greek_unicode.get(s)
|
529 |
+
if gG is not None:
|
530 |
+
return gG
|
531 |
+
for key in sorted(modifier_dict.keys(), key=lambda k:len(k), reverse=True) :
|
532 |
+
if s.lower().endswith(key) and len(s)>len(key):
|
533 |
+
return modifier_dict[key](translate(s[:-len(key)], bold_name))
|
534 |
+
if bold_name:
|
535 |
+
return ''.join([bold_unicode[c] for c in s])
|
536 |
+
return s
|
537 |
+
|
538 |
+
name = translate(name, bold_name)
|
539 |
+
|
540 |
+
# Let's prettify sups/subs. If it fails at one of them, pretty sups/subs are
|
541 |
+
# not used at all.
|
542 |
+
def pretty_list(l, mapping):
|
543 |
+
result = []
|
544 |
+
for s in l:
|
545 |
+
pretty = mapping.get(s)
|
546 |
+
if pretty is None:
|
547 |
+
try: # match by separate characters
|
548 |
+
pretty = ''.join([mapping[c] for c in s])
|
549 |
+
except (TypeError, KeyError):
|
550 |
+
return None
|
551 |
+
result.append(pretty)
|
552 |
+
return result
|
553 |
+
|
554 |
+
pretty_sups = pretty_list(sups, sup)
|
555 |
+
if pretty_sups is not None:
|
556 |
+
pretty_subs = pretty_list(subs, sub)
|
557 |
+
else:
|
558 |
+
pretty_subs = None
|
559 |
+
|
560 |
+
# glue the results into one string
|
561 |
+
if pretty_subs is None: # nice formatting of sups/subs did not work
|
562 |
+
if subs:
|
563 |
+
name += '_'+'_'.join([translate(s, bold_name) for s in subs])
|
564 |
+
if sups:
|
565 |
+
name += '__'+'__'.join([translate(s, bold_name) for s in sups])
|
566 |
+
return name
|
567 |
+
else:
|
568 |
+
sups_result = ' '.join(pretty_sups)
|
569 |
+
subs_result = ' '.join(pretty_subs)
|
570 |
+
|
571 |
+
return ''.join([name, sups_result, subs_result])
|
572 |
+
|
573 |
+
|
574 |
+
def annotated(letter):
|
575 |
+
"""
|
576 |
+
Return a stylised drawing of the letter ``letter``, together with
|
577 |
+
information on how to put annotations (super- and subscripts to the
|
578 |
+
left and to the right) on it.
|
579 |
+
|
580 |
+
See pretty.py functions _print_meijerg, _print_hyper on how to use this
|
581 |
+
information.
|
582 |
+
"""
|
583 |
+
ucode_pics = {
|
584 |
+
'F': (2, 0, 2, 0, '\N{BOX DRAWINGS LIGHT DOWN AND RIGHT}\N{BOX DRAWINGS LIGHT HORIZONTAL}\n'
|
585 |
+
'\N{BOX DRAWINGS LIGHT VERTICAL AND RIGHT}\N{BOX DRAWINGS LIGHT HORIZONTAL}\n'
|
586 |
+
'\N{BOX DRAWINGS LIGHT UP}'),
|
587 |
+
'G': (3, 0, 3, 1, '\N{BOX DRAWINGS LIGHT ARC DOWN AND RIGHT}\N{BOX DRAWINGS LIGHT HORIZONTAL}\N{BOX DRAWINGS LIGHT ARC DOWN AND LEFT}\n'
|
588 |
+
'\N{BOX DRAWINGS LIGHT VERTICAL}\N{BOX DRAWINGS LIGHT RIGHT}\N{BOX DRAWINGS LIGHT DOWN AND LEFT}\n'
|
589 |
+
'\N{BOX DRAWINGS LIGHT ARC UP AND RIGHT}\N{BOX DRAWINGS LIGHT HORIZONTAL}\N{BOX DRAWINGS LIGHT ARC UP AND LEFT}')
|
590 |
+
}
|
591 |
+
ascii_pics = {
|
592 |
+
'F': (3, 0, 3, 0, ' _\n|_\n|\n'),
|
593 |
+
'G': (3, 0, 3, 1, ' __\n/__\n\\_|')
|
594 |
+
}
|
595 |
+
|
596 |
+
if _use_unicode:
|
597 |
+
return ucode_pics[letter]
|
598 |
+
else:
|
599 |
+
return ascii_pics[letter]
|
600 |
+
|
601 |
+
_remove_combining = dict.fromkeys(list(range(ord('\N{COMBINING GRAVE ACCENT}'), ord('\N{COMBINING LATIN SMALL LETTER X}')))
|
602 |
+
+ list(range(ord('\N{COMBINING LEFT HARPOON ABOVE}'), ord('\N{COMBINING ASTERISK ABOVE}'))))
|
603 |
+
|
604 |
+
def is_combining(sym):
|
605 |
+
"""Check whether symbol is a unicode modifier. """
|
606 |
+
|
607 |
+
return ord(sym) in _remove_combining
|
608 |
+
|
609 |
+
|
610 |
+
def center_accent(string, accent):
|
611 |
+
"""
|
612 |
+
Returns a string with accent inserted on the middle character. Useful to
|
613 |
+
put combining accents on symbol names, including multi-character names.
|
614 |
+
|
615 |
+
Parameters
|
616 |
+
==========
|
617 |
+
|
618 |
+
string : string
|
619 |
+
The string to place the accent in.
|
620 |
+
accent : string
|
621 |
+
The combining accent to insert
|
622 |
+
|
623 |
+
References
|
624 |
+
==========
|
625 |
+
|
626 |
+
.. [1] https://en.wikipedia.org/wiki/Combining_character
|
627 |
+
.. [2] https://en.wikipedia.org/wiki/Combining_Diacritical_Marks
|
628 |
+
|
629 |
+
"""
|
630 |
+
|
631 |
+
# Accent is placed on the previous character, although it may not always look
|
632 |
+
# like that depending on console
|
633 |
+
midpoint = len(string) // 2 + 1
|
634 |
+
firstpart = string[:midpoint]
|
635 |
+
secondpart = string[midpoint:]
|
636 |
+
return firstpart + accent + secondpart
|
637 |
+
|
638 |
+
|
639 |
+
def line_width(line):
|
640 |
+
"""Unicode combining symbols (modifiers) are not ever displayed as
|
641 |
+
separate symbols and thus should not be counted
|
642 |
+
"""
|
643 |
+
return len(line.translate(_remove_combining))
|
env-llmeval/lib/python3.10/site-packages/sympy/printing/pretty/stringpict.py
ADDED
@@ -0,0 +1,538 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Prettyprinter by Jurjen Bos.
|
2 |
+
(I hate spammers: mail me at pietjepuk314 at the reverse of ku.oc.oohay).
|
3 |
+
All objects have a method that create a "stringPict",
|
4 |
+
that can be used in the str method for pretty printing.
|
5 |
+
|
6 |
+
Updates by Jason Gedge (email <my last name> at cs mun ca)
|
7 |
+
- terminal_string() method
|
8 |
+
- minor fixes and changes (mostly to prettyForm)
|
9 |
+
|
10 |
+
TODO:
|
11 |
+
- Allow left/center/right alignment options for above/below and
|
12 |
+
top/center/bottom alignment options for left/right
|
13 |
+
"""
|
14 |
+
|
15 |
+
from .pretty_symbology import hobj, vobj, xsym, xobj, pretty_use_unicode, line_width
|
16 |
+
from sympy.utilities.exceptions import sympy_deprecation_warning
|
17 |
+
|
18 |
+
class stringPict:
|
19 |
+
"""An ASCII picture.
|
20 |
+
The pictures are represented as a list of equal length strings.
|
21 |
+
"""
|
22 |
+
#special value for stringPict.below
|
23 |
+
LINE = 'line'
|
24 |
+
|
25 |
+
def __init__(self, s, baseline=0):
|
26 |
+
"""Initialize from string.
|
27 |
+
Multiline strings are centered.
|
28 |
+
"""
|
29 |
+
self.s = s
|
30 |
+
#picture is a string that just can be printed
|
31 |
+
self.picture = stringPict.equalLengths(s.splitlines())
|
32 |
+
#baseline is the line number of the "base line"
|
33 |
+
self.baseline = baseline
|
34 |
+
self.binding = None
|
35 |
+
|
36 |
+
@staticmethod
|
37 |
+
def equalLengths(lines):
|
38 |
+
# empty lines
|
39 |
+
if not lines:
|
40 |
+
return ['']
|
41 |
+
|
42 |
+
width = max(line_width(line) for line in lines)
|
43 |
+
return [line.center(width) for line in lines]
|
44 |
+
|
45 |
+
def height(self):
|
46 |
+
"""The height of the picture in characters."""
|
47 |
+
return len(self.picture)
|
48 |
+
|
49 |
+
def width(self):
|
50 |
+
"""The width of the picture in characters."""
|
51 |
+
return line_width(self.picture[0])
|
52 |
+
|
53 |
+
@staticmethod
|
54 |
+
def next(*args):
|
55 |
+
"""Put a string of stringPicts next to each other.
|
56 |
+
Returns string, baseline arguments for stringPict.
|
57 |
+
"""
|
58 |
+
#convert everything to stringPicts
|
59 |
+
objects = []
|
60 |
+
for arg in args:
|
61 |
+
if isinstance(arg, str):
|
62 |
+
arg = stringPict(arg)
|
63 |
+
objects.append(arg)
|
64 |
+
|
65 |
+
#make a list of pictures, with equal height and baseline
|
66 |
+
newBaseline = max(obj.baseline for obj in objects)
|
67 |
+
newHeightBelowBaseline = max(
|
68 |
+
obj.height() - obj.baseline
|
69 |
+
for obj in objects)
|
70 |
+
newHeight = newBaseline + newHeightBelowBaseline
|
71 |
+
|
72 |
+
pictures = []
|
73 |
+
for obj in objects:
|
74 |
+
oneEmptyLine = [' '*obj.width()]
|
75 |
+
basePadding = newBaseline - obj.baseline
|
76 |
+
totalPadding = newHeight - obj.height()
|
77 |
+
pictures.append(
|
78 |
+
oneEmptyLine * basePadding +
|
79 |
+
obj.picture +
|
80 |
+
oneEmptyLine * (totalPadding - basePadding))
|
81 |
+
|
82 |
+
result = [''.join(lines) for lines in zip(*pictures)]
|
83 |
+
return '\n'.join(result), newBaseline
|
84 |
+
|
85 |
+
def right(self, *args):
|
86 |
+
r"""Put pictures next to this one.
|
87 |
+
Returns string, baseline arguments for stringPict.
|
88 |
+
(Multiline) strings are allowed, and are given a baseline of 0.
|
89 |
+
|
90 |
+
Examples
|
91 |
+
========
|
92 |
+
|
93 |
+
>>> from sympy.printing.pretty.stringpict import stringPict
|
94 |
+
>>> print(stringPict("10").right(" + ",stringPict("1\r-\r2",1))[0])
|
95 |
+
1
|
96 |
+
10 + -
|
97 |
+
2
|
98 |
+
|
99 |
+
"""
|
100 |
+
return stringPict.next(self, *args)
|
101 |
+
|
102 |
+
def left(self, *args):
|
103 |
+
"""Put pictures (left to right) at left.
|
104 |
+
Returns string, baseline arguments for stringPict.
|
105 |
+
"""
|
106 |
+
return stringPict.next(*(args + (self,)))
|
107 |
+
|
108 |
+
@staticmethod
|
109 |
+
def stack(*args):
|
110 |
+
"""Put pictures on top of each other,
|
111 |
+
from top to bottom.
|
112 |
+
Returns string, baseline arguments for stringPict.
|
113 |
+
The baseline is the baseline of the second picture.
|
114 |
+
Everything is centered.
|
115 |
+
Baseline is the baseline of the second picture.
|
116 |
+
Strings are allowed.
|
117 |
+
The special value stringPict.LINE is a row of '-' extended to the width.
|
118 |
+
"""
|
119 |
+
#convert everything to stringPicts; keep LINE
|
120 |
+
objects = []
|
121 |
+
for arg in args:
|
122 |
+
if arg is not stringPict.LINE and isinstance(arg, str):
|
123 |
+
arg = stringPict(arg)
|
124 |
+
objects.append(arg)
|
125 |
+
|
126 |
+
#compute new width
|
127 |
+
newWidth = max(
|
128 |
+
obj.width()
|
129 |
+
for obj in objects
|
130 |
+
if obj is not stringPict.LINE)
|
131 |
+
|
132 |
+
lineObj = stringPict(hobj('-', newWidth))
|
133 |
+
|
134 |
+
#replace LINE with proper lines
|
135 |
+
for i, obj in enumerate(objects):
|
136 |
+
if obj is stringPict.LINE:
|
137 |
+
objects[i] = lineObj
|
138 |
+
|
139 |
+
#stack the pictures, and center the result
|
140 |
+
newPicture = []
|
141 |
+
for obj in objects:
|
142 |
+
newPicture.extend(obj.picture)
|
143 |
+
newPicture = [line.center(newWidth) for line in newPicture]
|
144 |
+
newBaseline = objects[0].height() + objects[1].baseline
|
145 |
+
return '\n'.join(newPicture), newBaseline
|
146 |
+
|
147 |
+
def below(self, *args):
|
148 |
+
"""Put pictures under this picture.
|
149 |
+
Returns string, baseline arguments for stringPict.
|
150 |
+
Baseline is baseline of top picture
|
151 |
+
|
152 |
+
Examples
|
153 |
+
========
|
154 |
+
|
155 |
+
>>> from sympy.printing.pretty.stringpict import stringPict
|
156 |
+
>>> print(stringPict("x+3").below(
|
157 |
+
... stringPict.LINE, '3')[0]) #doctest: +NORMALIZE_WHITESPACE
|
158 |
+
x+3
|
159 |
+
---
|
160 |
+
3
|
161 |
+
|
162 |
+
"""
|
163 |
+
s, baseline = stringPict.stack(self, *args)
|
164 |
+
return s, self.baseline
|
165 |
+
|
166 |
+
def above(self, *args):
|
167 |
+
"""Put pictures above this picture.
|
168 |
+
Returns string, baseline arguments for stringPict.
|
169 |
+
Baseline is baseline of bottom picture.
|
170 |
+
"""
|
171 |
+
string, baseline = stringPict.stack(*(args + (self,)))
|
172 |
+
baseline = len(string.splitlines()) - self.height() + self.baseline
|
173 |
+
return string, baseline
|
174 |
+
|
175 |
+
def parens(self, left='(', right=')', ifascii_nougly=False):
|
176 |
+
"""Put parentheses around self.
|
177 |
+
Returns string, baseline arguments for stringPict.
|
178 |
+
|
179 |
+
left or right can be None or empty string which means 'no paren from
|
180 |
+
that side'
|
181 |
+
"""
|
182 |
+
h = self.height()
|
183 |
+
b = self.baseline
|
184 |
+
|
185 |
+
# XXX this is a hack -- ascii parens are ugly!
|
186 |
+
if ifascii_nougly and not pretty_use_unicode():
|
187 |
+
h = 1
|
188 |
+
b = 0
|
189 |
+
|
190 |
+
res = self
|
191 |
+
|
192 |
+
if left:
|
193 |
+
lparen = stringPict(vobj(left, h), baseline=b)
|
194 |
+
res = stringPict(*lparen.right(self))
|
195 |
+
if right:
|
196 |
+
rparen = stringPict(vobj(right, h), baseline=b)
|
197 |
+
res = stringPict(*res.right(rparen))
|
198 |
+
|
199 |
+
return ('\n'.join(res.picture), res.baseline)
|
200 |
+
|
201 |
+
def leftslash(self):
|
202 |
+
"""Precede object by a slash of the proper size.
|
203 |
+
"""
|
204 |
+
# XXX not used anywhere ?
|
205 |
+
height = max(
|
206 |
+
self.baseline,
|
207 |
+
self.height() - 1 - self.baseline)*2 + 1
|
208 |
+
slash = '\n'.join(
|
209 |
+
' '*(height - i - 1) + xobj('/', 1) + ' '*i
|
210 |
+
for i in range(height)
|
211 |
+
)
|
212 |
+
return self.left(stringPict(slash, height//2))
|
213 |
+
|
214 |
+
def root(self, n=None):
|
215 |
+
"""Produce a nice root symbol.
|
216 |
+
Produces ugly results for big n inserts.
|
217 |
+
"""
|
218 |
+
# XXX not used anywhere
|
219 |
+
# XXX duplicate of root drawing in pretty.py
|
220 |
+
#put line over expression
|
221 |
+
result = self.above('_'*self.width())
|
222 |
+
#construct right half of root symbol
|
223 |
+
height = self.height()
|
224 |
+
slash = '\n'.join(
|
225 |
+
' ' * (height - i - 1) + '/' + ' ' * i
|
226 |
+
for i in range(height)
|
227 |
+
)
|
228 |
+
slash = stringPict(slash, height - 1)
|
229 |
+
#left half of root symbol
|
230 |
+
if height > 2:
|
231 |
+
downline = stringPict('\\ \n \\', 1)
|
232 |
+
else:
|
233 |
+
downline = stringPict('\\')
|
234 |
+
#put n on top, as low as possible
|
235 |
+
if n is not None and n.width() > downline.width():
|
236 |
+
downline = downline.left(' '*(n.width() - downline.width()))
|
237 |
+
downline = downline.above(n)
|
238 |
+
#build root symbol
|
239 |
+
root = downline.right(slash)
|
240 |
+
#glue it on at the proper height
|
241 |
+
#normally, the root symbel is as high as self
|
242 |
+
#which is one less than result
|
243 |
+
#this moves the root symbol one down
|
244 |
+
#if the root became higher, the baseline has to grow too
|
245 |
+
root.baseline = result.baseline - result.height() + root.height()
|
246 |
+
return result.left(root)
|
247 |
+
|
248 |
+
def render(self, * args, **kwargs):
|
249 |
+
"""Return the string form of self.
|
250 |
+
|
251 |
+
Unless the argument line_break is set to False, it will
|
252 |
+
break the expression in a form that can be printed
|
253 |
+
on the terminal without being broken up.
|
254 |
+
"""
|
255 |
+
if kwargs["wrap_line"] is False:
|
256 |
+
return "\n".join(self.picture)
|
257 |
+
|
258 |
+
if kwargs["num_columns"] is not None:
|
259 |
+
# Read the argument num_columns if it is not None
|
260 |
+
ncols = kwargs["num_columns"]
|
261 |
+
else:
|
262 |
+
# Attempt to get a terminal width
|
263 |
+
ncols = self.terminal_width()
|
264 |
+
|
265 |
+
ncols -= 2
|
266 |
+
if ncols <= 0:
|
267 |
+
ncols = 78
|
268 |
+
|
269 |
+
# If smaller than the terminal width, no need to correct
|
270 |
+
if self.width() <= ncols:
|
271 |
+
return type(self.picture[0])(self)
|
272 |
+
|
273 |
+
# for one-line pictures we don't need v-spacers. on the other hand, for
|
274 |
+
# multiline-pictures, we need v-spacers between blocks, compare:
|
275 |
+
#
|
276 |
+
# 2 2 3 | a*c*e + a*c*f + a*d | a*c*e + a*c*f + a*d | 3.14159265358979323
|
277 |
+
# 6*x *y + 4*x*y + | | *e + a*d*f + b*c*e | 84626433832795
|
278 |
+
# | *e + a*d*f + b*c*e | + b*c*f + b*d*e + b |
|
279 |
+
# 3 4 4 | | *d*f |
|
280 |
+
# 4*y*x + x + y | + b*c*f + b*d*e + b | |
|
281 |
+
# | | |
|
282 |
+
# | *d*f
|
283 |
+
|
284 |
+
i = 0
|
285 |
+
svals = []
|
286 |
+
do_vspacers = (self.height() > 1)
|
287 |
+
while i < self.width():
|
288 |
+
svals.extend([ sval[i:i + ncols] for sval in self.picture ])
|
289 |
+
if do_vspacers:
|
290 |
+
svals.append("") # a vertical spacer
|
291 |
+
i += ncols
|
292 |
+
|
293 |
+
if svals[-1] == '':
|
294 |
+
del svals[-1] # Get rid of the last spacer
|
295 |
+
|
296 |
+
return "\n".join(svals)
|
297 |
+
|
298 |
+
def terminal_width(self):
|
299 |
+
"""Return the terminal width if possible, otherwise return 0.
|
300 |
+
"""
|
301 |
+
ncols = 0
|
302 |
+
try:
|
303 |
+
import curses
|
304 |
+
import io
|
305 |
+
try:
|
306 |
+
curses.setupterm()
|
307 |
+
ncols = curses.tigetnum('cols')
|
308 |
+
except AttributeError:
|
309 |
+
# windows curses doesn't implement setupterm or tigetnum
|
310 |
+
# code below from
|
311 |
+
# https://code.activestate.com/recipes/440694/
|
312 |
+
from ctypes import windll, create_string_buffer
|
313 |
+
# stdin handle is -10
|
314 |
+
# stdout handle is -11
|
315 |
+
# stderr handle is -12
|
316 |
+
h = windll.kernel32.GetStdHandle(-12)
|
317 |
+
csbi = create_string_buffer(22)
|
318 |
+
res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
|
319 |
+
if res:
|
320 |
+
import struct
|
321 |
+
(bufx, bufy, curx, cury, wattr,
|
322 |
+
left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
|
323 |
+
ncols = right - left + 1
|
324 |
+
except curses.error:
|
325 |
+
pass
|
326 |
+
except io.UnsupportedOperation:
|
327 |
+
pass
|
328 |
+
except (ImportError, TypeError):
|
329 |
+
pass
|
330 |
+
return ncols
|
331 |
+
|
332 |
+
def __eq__(self, o):
|
333 |
+
if isinstance(o, str):
|
334 |
+
return '\n'.join(self.picture) == o
|
335 |
+
elif isinstance(o, stringPict):
|
336 |
+
return o.picture == self.picture
|
337 |
+
return False
|
338 |
+
|
339 |
+
def __hash__(self):
|
340 |
+
return super().__hash__()
|
341 |
+
|
342 |
+
def __str__(self):
|
343 |
+
return '\n'.join(self.picture)
|
344 |
+
|
345 |
+
def __repr__(self):
|
346 |
+
return "stringPict(%r,%d)" % ('\n'.join(self.picture), self.baseline)
|
347 |
+
|
348 |
+
def __getitem__(self, index):
|
349 |
+
return self.picture[index]
|
350 |
+
|
351 |
+
def __len__(self):
|
352 |
+
return len(self.s)
|
353 |
+
|
354 |
+
|
355 |
+
class prettyForm(stringPict):
|
356 |
+
"""
|
357 |
+
Extension of the stringPict class that knows about basic math applications,
|
358 |
+
optimizing double minus signs.
|
359 |
+
|
360 |
+
"Binding" is interpreted as follows::
|
361 |
+
|
362 |
+
ATOM this is an atom: never needs to be parenthesized
|
363 |
+
FUNC this is a function application: parenthesize if added (?)
|
364 |
+
DIV this is a division: make wider division if divided
|
365 |
+
POW this is a power: only parenthesize if exponent
|
366 |
+
MUL this is a multiplication: parenthesize if powered
|
367 |
+
ADD this is an addition: parenthesize if multiplied or powered
|
368 |
+
NEG this is a negative number: optimize if added, parenthesize if
|
369 |
+
multiplied or powered
|
370 |
+
OPEN this is an open object: parenthesize if added, multiplied, or
|
371 |
+
powered (example: Piecewise)
|
372 |
+
"""
|
373 |
+
ATOM, FUNC, DIV, POW, MUL, ADD, NEG, OPEN = range(8)
|
374 |
+
|
375 |
+
def __init__(self, s, baseline=0, binding=0, unicode=None):
|
376 |
+
"""Initialize from stringPict and binding power."""
|
377 |
+
stringPict.__init__(self, s, baseline)
|
378 |
+
self.binding = binding
|
379 |
+
if unicode is not None:
|
380 |
+
sympy_deprecation_warning(
|
381 |
+
"""
|
382 |
+
The unicode argument to prettyForm is deprecated. Only the s
|
383 |
+
argument (the first positional argument) should be passed.
|
384 |
+
""",
|
385 |
+
deprecated_since_version="1.7",
|
386 |
+
active_deprecations_target="deprecated-pretty-printing-functions")
|
387 |
+
self._unicode = unicode or s
|
388 |
+
|
389 |
+
@property
|
390 |
+
def unicode(self):
|
391 |
+
sympy_deprecation_warning(
|
392 |
+
"""
|
393 |
+
The prettyForm.unicode attribute is deprecated. Use the
|
394 |
+
prettyForm.s attribute instead.
|
395 |
+
""",
|
396 |
+
deprecated_since_version="1.7",
|
397 |
+
active_deprecations_target="deprecated-pretty-printing-functions")
|
398 |
+
return self._unicode
|
399 |
+
|
400 |
+
# Note: code to handle subtraction is in _print_Add
|
401 |
+
|
402 |
+
def __add__(self, *others):
|
403 |
+
"""Make a pretty addition.
|
404 |
+
Addition of negative numbers is simplified.
|
405 |
+
"""
|
406 |
+
arg = self
|
407 |
+
if arg.binding > prettyForm.NEG:
|
408 |
+
arg = stringPict(*arg.parens())
|
409 |
+
result = [arg]
|
410 |
+
for arg in others:
|
411 |
+
#add parentheses for weak binders
|
412 |
+
if arg.binding > prettyForm.NEG:
|
413 |
+
arg = stringPict(*arg.parens())
|
414 |
+
#use existing minus sign if available
|
415 |
+
if arg.binding != prettyForm.NEG:
|
416 |
+
result.append(' + ')
|
417 |
+
result.append(arg)
|
418 |
+
return prettyForm(binding=prettyForm.ADD, *stringPict.next(*result))
|
419 |
+
|
420 |
+
def __truediv__(self, den, slashed=False):
|
421 |
+
"""Make a pretty division; stacked or slashed.
|
422 |
+
"""
|
423 |
+
if slashed:
|
424 |
+
raise NotImplementedError("Can't do slashed fraction yet")
|
425 |
+
num = self
|
426 |
+
if num.binding == prettyForm.DIV:
|
427 |
+
num = stringPict(*num.parens())
|
428 |
+
if den.binding == prettyForm.DIV:
|
429 |
+
den = stringPict(*den.parens())
|
430 |
+
|
431 |
+
if num.binding==prettyForm.NEG:
|
432 |
+
num = num.right(" ")[0]
|
433 |
+
|
434 |
+
return prettyForm(binding=prettyForm.DIV, *stringPict.stack(
|
435 |
+
num,
|
436 |
+
stringPict.LINE,
|
437 |
+
den))
|
438 |
+
|
439 |
+
def __mul__(self, *others):
|
440 |
+
"""Make a pretty multiplication.
|
441 |
+
Parentheses are needed around +, - and neg.
|
442 |
+
"""
|
443 |
+
quantity = {
|
444 |
+
'degree': "\N{DEGREE SIGN}"
|
445 |
+
}
|
446 |
+
|
447 |
+
if len(others) == 0:
|
448 |
+
return self # We aren't actually multiplying... So nothing to do here.
|
449 |
+
|
450 |
+
# add parens on args that need them
|
451 |
+
arg = self
|
452 |
+
if arg.binding > prettyForm.MUL and arg.binding != prettyForm.NEG:
|
453 |
+
arg = stringPict(*arg.parens())
|
454 |
+
result = [arg]
|
455 |
+
for arg in others:
|
456 |
+
if arg.picture[0] not in quantity.values():
|
457 |
+
result.append(xsym('*'))
|
458 |
+
#add parentheses for weak binders
|
459 |
+
if arg.binding > prettyForm.MUL and arg.binding != prettyForm.NEG:
|
460 |
+
arg = stringPict(*arg.parens())
|
461 |
+
result.append(arg)
|
462 |
+
|
463 |
+
len_res = len(result)
|
464 |
+
for i in range(len_res):
|
465 |
+
if i < len_res - 1 and result[i] == '-1' and result[i + 1] == xsym('*'):
|
466 |
+
# substitute -1 by -, like in -1*x -> -x
|
467 |
+
result.pop(i)
|
468 |
+
result.pop(i)
|
469 |
+
result.insert(i, '-')
|
470 |
+
if result[0][0] == '-':
|
471 |
+
# if there is a - sign in front of all
|
472 |
+
# This test was failing to catch a prettyForm.__mul__(prettyForm("-1", 0, 6)) being negative
|
473 |
+
bin = prettyForm.NEG
|
474 |
+
if result[0] == '-':
|
475 |
+
right = result[1]
|
476 |
+
if right.picture[right.baseline][0] == '-':
|
477 |
+
result[0] = '- '
|
478 |
+
else:
|
479 |
+
bin = prettyForm.MUL
|
480 |
+
return prettyForm(binding=bin, *stringPict.next(*result))
|
481 |
+
|
482 |
+
def __repr__(self):
|
483 |
+
return "prettyForm(%r,%d,%d)" % (
|
484 |
+
'\n'.join(self.picture),
|
485 |
+
self.baseline,
|
486 |
+
self.binding)
|
487 |
+
|
488 |
+
def __pow__(self, b):
|
489 |
+
"""Make a pretty power.
|
490 |
+
"""
|
491 |
+
a = self
|
492 |
+
use_inline_func_form = False
|
493 |
+
if b.binding == prettyForm.POW:
|
494 |
+
b = stringPict(*b.parens())
|
495 |
+
if a.binding > prettyForm.FUNC:
|
496 |
+
a = stringPict(*a.parens())
|
497 |
+
elif a.binding == prettyForm.FUNC:
|
498 |
+
# heuristic for when to use inline power
|
499 |
+
if b.height() > 1:
|
500 |
+
a = stringPict(*a.parens())
|
501 |
+
else:
|
502 |
+
use_inline_func_form = True
|
503 |
+
|
504 |
+
if use_inline_func_form:
|
505 |
+
# 2
|
506 |
+
# sin + + (x)
|
507 |
+
b.baseline = a.prettyFunc.baseline + b.height()
|
508 |
+
func = stringPict(*a.prettyFunc.right(b))
|
509 |
+
return prettyForm(*func.right(a.prettyArgs))
|
510 |
+
else:
|
511 |
+
# 2 <-- top
|
512 |
+
# (x+y) <-- bot
|
513 |
+
top = stringPict(*b.left(' '*a.width()))
|
514 |
+
bot = stringPict(*a.right(' '*b.width()))
|
515 |
+
|
516 |
+
return prettyForm(binding=prettyForm.POW, *bot.above(top))
|
517 |
+
|
518 |
+
simpleFunctions = ["sin", "cos", "tan"]
|
519 |
+
|
520 |
+
@staticmethod
|
521 |
+
def apply(function, *args):
|
522 |
+
"""Functions of one or more variables.
|
523 |
+
"""
|
524 |
+
if function in prettyForm.simpleFunctions:
|
525 |
+
#simple function: use only space if possible
|
526 |
+
assert len(
|
527 |
+
args) == 1, "Simple function %s must have 1 argument" % function
|
528 |
+
arg = args[0].__pretty__()
|
529 |
+
if arg.binding <= prettyForm.DIV:
|
530 |
+
#optimization: no parentheses necessary
|
531 |
+
return prettyForm(binding=prettyForm.FUNC, *arg.left(function + ' '))
|
532 |
+
argumentList = []
|
533 |
+
for arg in args:
|
534 |
+
argumentList.append(',')
|
535 |
+
argumentList.append(arg.__pretty__())
|
536 |
+
argumentList = stringPict(*stringPict.next(*argumentList[1:]))
|
537 |
+
argumentList = stringPict(*argumentList.parens())
|
538 |
+
return prettyForm(binding=prettyForm.ATOM, *argumentList.left(function))
|
env-llmeval/lib/python3.10/site-packages/sympy/printing/pretty/tests/__init__.py
ADDED
File without changes
|
env-llmeval/lib/python3.10/site-packages/sympy/printing/pretty/tests/test_pretty.py
ADDED
The diff for this file is too large to render.
See raw diff
|
|
env-llmeval/lib/python3.10/site-packages/sympy/sets/__init__.py
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from .sets import (Set, Interval, Union, FiniteSet, ProductSet,
|
2 |
+
Intersection, imageset, Complement, SymmetricDifference,
|
3 |
+
DisjointUnion)
|
4 |
+
|
5 |
+
from .fancysets import ImageSet, Range, ComplexRegion
|
6 |
+
from .contains import Contains
|
7 |
+
from .conditionset import ConditionSet
|
8 |
+
from .ordinals import Ordinal, OmegaPower, ord0
|
9 |
+
from .powerset import PowerSet
|
10 |
+
from ..core.singleton import S
|
11 |
+
from .handlers.comparison import _eval_is_eq # noqa:F401
|
12 |
+
Complexes = S.Complexes
|
13 |
+
EmptySet = S.EmptySet
|
14 |
+
Integers = S.Integers
|
15 |
+
Naturals = S.Naturals
|
16 |
+
Naturals0 = S.Naturals0
|
17 |
+
Rationals = S.Rationals
|
18 |
+
Reals = S.Reals
|
19 |
+
UniversalSet = S.UniversalSet
|
20 |
+
|
21 |
+
__all__ = [
|
22 |
+
'Set', 'Interval', 'Union', 'EmptySet', 'FiniteSet', 'ProductSet',
|
23 |
+
'Intersection', 'imageset', 'Complement', 'SymmetricDifference', 'DisjointUnion',
|
24 |
+
|
25 |
+
'ImageSet', 'Range', 'ComplexRegion', 'Reals',
|
26 |
+
|
27 |
+
'Contains',
|
28 |
+
|
29 |
+
'ConditionSet',
|
30 |
+
|
31 |
+
'Ordinal', 'OmegaPower', 'ord0',
|
32 |
+
|
33 |
+
'PowerSet',
|
34 |
+
|
35 |
+
'Reals', 'Naturals', 'Naturals0', 'UniversalSet', 'Integers', 'Rationals',
|
36 |
+
]
|
env-llmeval/lib/python3.10/site-packages/sympy/sets/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (1.09 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/sets/__pycache__/conditionset.cpython-310.pyc
ADDED
Binary file (7.62 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/sets/__pycache__/contains.cpython-310.pyc
ADDED
Binary file (1.91 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/sets/__pycache__/ordinals.cpython-310.pyc
ADDED
Binary file (8.44 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/sets/conditionset.py
ADDED
@@ -0,0 +1,246 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.singleton import S
|
2 |
+
from sympy.core.basic import Basic
|
3 |
+
from sympy.core.containers import Tuple
|
4 |
+
from sympy.core.function import Lambda, BadSignatureError
|
5 |
+
from sympy.core.logic import fuzzy_bool
|
6 |
+
from sympy.core.relational import Eq
|
7 |
+
from sympy.core.symbol import Dummy
|
8 |
+
from sympy.core.sympify import _sympify
|
9 |
+
from sympy.logic.boolalg import And, as_Boolean
|
10 |
+
from sympy.utilities.iterables import sift, flatten, has_dups
|
11 |
+
from sympy.utilities.exceptions import sympy_deprecation_warning
|
12 |
+
from .contains import Contains
|
13 |
+
from .sets import Set, Union, FiniteSet, SetKind
|
14 |
+
|
15 |
+
|
16 |
+
adummy = Dummy('conditionset')
|
17 |
+
|
18 |
+
|
19 |
+
class ConditionSet(Set):
|
20 |
+
r"""
|
21 |
+
Set of elements which satisfies a given condition.
|
22 |
+
|
23 |
+
.. math:: \{x \mid \textrm{condition}(x) = \texttt{True}, x \in S\}
|
24 |
+
|
25 |
+
Examples
|
26 |
+
========
|
27 |
+
|
28 |
+
>>> from sympy import Symbol, S, ConditionSet, pi, Eq, sin, Interval
|
29 |
+
>>> from sympy.abc import x, y, z
|
30 |
+
|
31 |
+
>>> sin_sols = ConditionSet(x, Eq(sin(x), 0), Interval(0, 2*pi))
|
32 |
+
>>> 2*pi in sin_sols
|
33 |
+
True
|
34 |
+
>>> pi/2 in sin_sols
|
35 |
+
False
|
36 |
+
>>> 3*pi in sin_sols
|
37 |
+
False
|
38 |
+
>>> 5 in ConditionSet(x, x**2 > 4, S.Reals)
|
39 |
+
True
|
40 |
+
|
41 |
+
If the value is not in the base set, the result is false:
|
42 |
+
|
43 |
+
>>> 5 in ConditionSet(x, x**2 > 4, Interval(2, 4))
|
44 |
+
False
|
45 |
+
|
46 |
+
Notes
|
47 |
+
=====
|
48 |
+
|
49 |
+
Symbols with assumptions should be avoided or else the
|
50 |
+
condition may evaluate without consideration of the set:
|
51 |
+
|
52 |
+
>>> n = Symbol('n', negative=True)
|
53 |
+
>>> cond = (n > 0); cond
|
54 |
+
False
|
55 |
+
>>> ConditionSet(n, cond, S.Integers)
|
56 |
+
EmptySet
|
57 |
+
|
58 |
+
Only free symbols can be changed by using `subs`:
|
59 |
+
|
60 |
+
>>> c = ConditionSet(x, x < 1, {x, z})
|
61 |
+
>>> c.subs(x, y)
|
62 |
+
ConditionSet(x, x < 1, {y, z})
|
63 |
+
|
64 |
+
To check if ``pi`` is in ``c`` use:
|
65 |
+
|
66 |
+
>>> pi in c
|
67 |
+
False
|
68 |
+
|
69 |
+
If no base set is specified, the universal set is implied:
|
70 |
+
|
71 |
+
>>> ConditionSet(x, x < 1).base_set
|
72 |
+
UniversalSet
|
73 |
+
|
74 |
+
Only symbols or symbol-like expressions can be used:
|
75 |
+
|
76 |
+
>>> ConditionSet(x + 1, x + 1 < 1, S.Integers)
|
77 |
+
Traceback (most recent call last):
|
78 |
+
...
|
79 |
+
ValueError: non-symbol dummy not recognized in condition
|
80 |
+
|
81 |
+
When the base set is a ConditionSet, the symbols will be
|
82 |
+
unified if possible with preference for the outermost symbols:
|
83 |
+
|
84 |
+
>>> ConditionSet(x, x < y, ConditionSet(z, z + y < 2, S.Integers))
|
85 |
+
ConditionSet(x, (x < y) & (x + y < 2), Integers)
|
86 |
+
|
87 |
+
"""
|
88 |
+
def __new__(cls, sym, condition, base_set=S.UniversalSet):
|
89 |
+
sym = _sympify(sym)
|
90 |
+
flat = flatten([sym])
|
91 |
+
if has_dups(flat):
|
92 |
+
raise BadSignatureError("Duplicate symbols detected")
|
93 |
+
base_set = _sympify(base_set)
|
94 |
+
if not isinstance(base_set, Set):
|
95 |
+
raise TypeError(
|
96 |
+
'base set should be a Set object, not %s' % base_set)
|
97 |
+
condition = _sympify(condition)
|
98 |
+
|
99 |
+
if isinstance(condition, FiniteSet):
|
100 |
+
condition_orig = condition
|
101 |
+
temp = (Eq(lhs, 0) for lhs in condition)
|
102 |
+
condition = And(*temp)
|
103 |
+
sympy_deprecation_warning(
|
104 |
+
f"""
|
105 |
+
Using a set for the condition in ConditionSet is deprecated. Use a boolean
|
106 |
+
instead.
|
107 |
+
|
108 |
+
In this case, replace
|
109 |
+
|
110 |
+
{condition_orig}
|
111 |
+
|
112 |
+
with
|
113 |
+
|
114 |
+
{condition}
|
115 |
+
""",
|
116 |
+
deprecated_since_version='1.5',
|
117 |
+
active_deprecations_target="deprecated-conditionset-set",
|
118 |
+
)
|
119 |
+
|
120 |
+
condition = as_Boolean(condition)
|
121 |
+
|
122 |
+
if condition is S.true:
|
123 |
+
return base_set
|
124 |
+
|
125 |
+
if condition is S.false:
|
126 |
+
return S.EmptySet
|
127 |
+
|
128 |
+
if base_set is S.EmptySet:
|
129 |
+
return S.EmptySet
|
130 |
+
|
131 |
+
# no simple answers, so now check syms
|
132 |
+
for i in flat:
|
133 |
+
if not getattr(i, '_diff_wrt', False):
|
134 |
+
raise ValueError('`%s` is not symbol-like' % i)
|
135 |
+
|
136 |
+
if base_set.contains(sym) is S.false:
|
137 |
+
raise TypeError('sym `%s` is not in base_set `%s`' % (sym, base_set))
|
138 |
+
|
139 |
+
know = None
|
140 |
+
if isinstance(base_set, FiniteSet):
|
141 |
+
sifted = sift(
|
142 |
+
base_set, lambda _: fuzzy_bool(condition.subs(sym, _)))
|
143 |
+
if sifted[None]:
|
144 |
+
know = FiniteSet(*sifted[True])
|
145 |
+
base_set = FiniteSet(*sifted[None])
|
146 |
+
else:
|
147 |
+
return FiniteSet(*sifted[True])
|
148 |
+
|
149 |
+
if isinstance(base_set, cls):
|
150 |
+
s, c, b = base_set.args
|
151 |
+
def sig(s):
|
152 |
+
return cls(s, Eq(adummy, 0)).as_dummy().sym
|
153 |
+
sa, sb = map(sig, (sym, s))
|
154 |
+
if sa != sb:
|
155 |
+
raise BadSignatureError('sym does not match sym of base set')
|
156 |
+
reps = dict(zip(flatten([sym]), flatten([s])))
|
157 |
+
if s == sym:
|
158 |
+
condition = And(condition, c)
|
159 |
+
base_set = b
|
160 |
+
elif not c.free_symbols & sym.free_symbols:
|
161 |
+
reps = {v: k for k, v in reps.items()}
|
162 |
+
condition = And(condition, c.xreplace(reps))
|
163 |
+
base_set = b
|
164 |
+
elif not condition.free_symbols & s.free_symbols:
|
165 |
+
sym = sym.xreplace(reps)
|
166 |
+
condition = And(condition.xreplace(reps), c)
|
167 |
+
base_set = b
|
168 |
+
|
169 |
+
# flatten ConditionSet(Contains(ConditionSet())) expressions
|
170 |
+
if isinstance(condition, Contains) and (sym == condition.args[0]):
|
171 |
+
if isinstance(condition.args[1], Set):
|
172 |
+
return condition.args[1].intersect(base_set)
|
173 |
+
|
174 |
+
rv = Basic.__new__(cls, sym, condition, base_set)
|
175 |
+
return rv if know is None else Union(know, rv)
|
176 |
+
|
177 |
+
sym = property(lambda self: self.args[0])
|
178 |
+
condition = property(lambda self: self.args[1])
|
179 |
+
base_set = property(lambda self: self.args[2])
|
180 |
+
|
181 |
+
@property
|
182 |
+
def free_symbols(self):
|
183 |
+
cond_syms = self.condition.free_symbols - self.sym.free_symbols
|
184 |
+
return cond_syms | self.base_set.free_symbols
|
185 |
+
|
186 |
+
@property
|
187 |
+
def bound_symbols(self):
|
188 |
+
return flatten([self.sym])
|
189 |
+
|
190 |
+
def _contains(self, other):
|
191 |
+
def ok_sig(a, b):
|
192 |
+
tuples = [isinstance(i, Tuple) for i in (a, b)]
|
193 |
+
c = tuples.count(True)
|
194 |
+
if c == 1:
|
195 |
+
return False
|
196 |
+
if c == 0:
|
197 |
+
return True
|
198 |
+
return len(a) == len(b) and all(
|
199 |
+
ok_sig(i, j) for i, j in zip(a, b))
|
200 |
+
if not ok_sig(self.sym, other):
|
201 |
+
return S.false
|
202 |
+
|
203 |
+
# try doing base_cond first and return
|
204 |
+
# False immediately if it is False
|
205 |
+
base_cond = Contains(other, self.base_set)
|
206 |
+
if base_cond is S.false:
|
207 |
+
return S.false
|
208 |
+
|
209 |
+
# Substitute other into condition. This could raise e.g. for
|
210 |
+
# ConditionSet(x, 1/x >= 0, Reals).contains(0)
|
211 |
+
lamda = Lambda((self.sym,), self.condition)
|
212 |
+
try:
|
213 |
+
lambda_cond = lamda(other)
|
214 |
+
except TypeError:
|
215 |
+
return Contains(other, self, evaluate=False)
|
216 |
+
else:
|
217 |
+
return And(base_cond, lambda_cond)
|
218 |
+
|
219 |
+
def as_relational(self, other):
|
220 |
+
f = Lambda(self.sym, self.condition)
|
221 |
+
if isinstance(self.sym, Tuple):
|
222 |
+
f = f(*other)
|
223 |
+
else:
|
224 |
+
f = f(other)
|
225 |
+
return And(f, self.base_set.contains(other))
|
226 |
+
|
227 |
+
def _eval_subs(self, old, new):
|
228 |
+
sym, cond, base = self.args
|
229 |
+
dsym = sym.subs(old, adummy)
|
230 |
+
insym = dsym.has(adummy)
|
231 |
+
# prioritize changing a symbol in the base
|
232 |
+
newbase = base.subs(old, new)
|
233 |
+
if newbase != base:
|
234 |
+
if not insym:
|
235 |
+
cond = cond.subs(old, new)
|
236 |
+
return self.func(sym, cond, newbase)
|
237 |
+
if insym:
|
238 |
+
pass # no change of bound symbols via subs
|
239 |
+
elif getattr(new, '_diff_wrt', False):
|
240 |
+
cond = cond.subs(old, new)
|
241 |
+
else:
|
242 |
+
pass # let error about the symbol raise from __new__
|
243 |
+
return self.func(sym, cond, base)
|
244 |
+
|
245 |
+
def _kind(self):
|
246 |
+
return SetKind(self.sym.kind)
|
env-llmeval/lib/python3.10/site-packages/sympy/sets/contains.py
ADDED
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core import S
|
2 |
+
from sympy.core.relational import Eq, Ne
|
3 |
+
from sympy.logic.boolalg import BooleanFunction
|
4 |
+
from sympy.utilities.misc import func_name
|
5 |
+
from .sets import Set
|
6 |
+
|
7 |
+
|
8 |
+
class Contains(BooleanFunction):
|
9 |
+
"""
|
10 |
+
Asserts that x is an element of the set S.
|
11 |
+
|
12 |
+
Examples
|
13 |
+
========
|
14 |
+
|
15 |
+
>>> from sympy import Symbol, Integer, S, Contains
|
16 |
+
>>> Contains(Integer(2), S.Integers)
|
17 |
+
True
|
18 |
+
>>> Contains(Integer(-2), S.Naturals)
|
19 |
+
False
|
20 |
+
>>> i = Symbol('i', integer=True)
|
21 |
+
>>> Contains(i, S.Naturals)
|
22 |
+
Contains(i, Naturals)
|
23 |
+
|
24 |
+
References
|
25 |
+
==========
|
26 |
+
|
27 |
+
.. [1] https://en.wikipedia.org/wiki/Element_%28mathematics%29
|
28 |
+
"""
|
29 |
+
@classmethod
|
30 |
+
def eval(cls, x, s):
|
31 |
+
|
32 |
+
if not isinstance(s, Set):
|
33 |
+
raise TypeError('expecting Set, not %s' % func_name(s))
|
34 |
+
|
35 |
+
ret = s.contains(x)
|
36 |
+
if not isinstance(ret, Contains) and (
|
37 |
+
ret in (S.true, S.false) or isinstance(ret, Set)):
|
38 |
+
return ret
|
39 |
+
|
40 |
+
@property
|
41 |
+
def binary_symbols(self):
|
42 |
+
return set().union(*[i.binary_symbols
|
43 |
+
for i in self.args[1].args
|
44 |
+
if i.is_Boolean or i.is_Symbol or
|
45 |
+
isinstance(i, (Eq, Ne))])
|
46 |
+
|
47 |
+
def as_set(self):
|
48 |
+
return self.args[1]
|
env-llmeval/lib/python3.10/site-packages/sympy/sets/fancysets.py
ADDED
@@ -0,0 +1,1521 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from functools import reduce
|
2 |
+
from itertools import product
|
3 |
+
|
4 |
+
from sympy.core.basic import Basic
|
5 |
+
from sympy.core.containers import Tuple
|
6 |
+
from sympy.core.expr import Expr
|
7 |
+
from sympy.core.function import Lambda
|
8 |
+
from sympy.core.logic import fuzzy_not, fuzzy_or, fuzzy_and
|
9 |
+
from sympy.core.mod import Mod
|
10 |
+
from sympy.core.numbers import oo, igcd, Rational
|
11 |
+
from sympy.core.relational import Eq, is_eq
|
12 |
+
from sympy.core.kind import NumberKind
|
13 |
+
from sympy.core.singleton import Singleton, S
|
14 |
+
from sympy.core.symbol import Dummy, symbols, Symbol
|
15 |
+
from sympy.core.sympify import _sympify, sympify, _sympy_converter
|
16 |
+
from sympy.functions.elementary.integers import ceiling, floor
|
17 |
+
from sympy.functions.elementary.trigonometric import sin, cos
|
18 |
+
from sympy.logic.boolalg import And, Or
|
19 |
+
from .sets import Set, Interval, Union, FiniteSet, ProductSet, SetKind
|
20 |
+
from sympy.utilities.misc import filldedent
|
21 |
+
|
22 |
+
|
23 |
+
class Rationals(Set, metaclass=Singleton):
|
24 |
+
"""
|
25 |
+
Represents the rational numbers. This set is also available as
|
26 |
+
the singleton ``S.Rationals``.
|
27 |
+
|
28 |
+
Examples
|
29 |
+
========
|
30 |
+
|
31 |
+
>>> from sympy import S
|
32 |
+
>>> S.Half in S.Rationals
|
33 |
+
True
|
34 |
+
>>> iterable = iter(S.Rationals)
|
35 |
+
>>> [next(iterable) for i in range(12)]
|
36 |
+
[0, 1, -1, 1/2, 2, -1/2, -2, 1/3, 3, -1/3, -3, 2/3]
|
37 |
+
"""
|
38 |
+
|
39 |
+
is_iterable = True
|
40 |
+
_inf = S.NegativeInfinity
|
41 |
+
_sup = S.Infinity
|
42 |
+
is_empty = False
|
43 |
+
is_finite_set = False
|
44 |
+
|
45 |
+
def _contains(self, other):
|
46 |
+
if not isinstance(other, Expr):
|
47 |
+
return False
|
48 |
+
return other.is_rational
|
49 |
+
|
50 |
+
def __iter__(self):
|
51 |
+
yield S.Zero
|
52 |
+
yield S.One
|
53 |
+
yield S.NegativeOne
|
54 |
+
d = 2
|
55 |
+
while True:
|
56 |
+
for n in range(d):
|
57 |
+
if igcd(n, d) == 1:
|
58 |
+
yield Rational(n, d)
|
59 |
+
yield Rational(d, n)
|
60 |
+
yield Rational(-n, d)
|
61 |
+
yield Rational(-d, n)
|
62 |
+
d += 1
|
63 |
+
|
64 |
+
@property
|
65 |
+
def _boundary(self):
|
66 |
+
return S.Reals
|
67 |
+
|
68 |
+
def _kind(self):
|
69 |
+
return SetKind(NumberKind)
|
70 |
+
|
71 |
+
|
72 |
+
class Naturals(Set, metaclass=Singleton):
|
73 |
+
"""
|
74 |
+
Represents the natural numbers (or counting numbers) which are all
|
75 |
+
positive integers starting from 1. This set is also available as
|
76 |
+
the singleton ``S.Naturals``.
|
77 |
+
|
78 |
+
Examples
|
79 |
+
========
|
80 |
+
|
81 |
+
>>> from sympy import S, Interval, pprint
|
82 |
+
>>> 5 in S.Naturals
|
83 |
+
True
|
84 |
+
>>> iterable = iter(S.Naturals)
|
85 |
+
>>> next(iterable)
|
86 |
+
1
|
87 |
+
>>> next(iterable)
|
88 |
+
2
|
89 |
+
>>> next(iterable)
|
90 |
+
3
|
91 |
+
>>> pprint(S.Naturals.intersect(Interval(0, 10)))
|
92 |
+
{1, 2, ..., 10}
|
93 |
+
|
94 |
+
See Also
|
95 |
+
========
|
96 |
+
|
97 |
+
Naturals0 : non-negative integers (i.e. includes 0, too)
|
98 |
+
Integers : also includes negative integers
|
99 |
+
"""
|
100 |
+
|
101 |
+
is_iterable = True
|
102 |
+
_inf = S.One
|
103 |
+
_sup = S.Infinity
|
104 |
+
is_empty = False
|
105 |
+
is_finite_set = False
|
106 |
+
|
107 |
+
def _contains(self, other):
|
108 |
+
if not isinstance(other, Expr):
|
109 |
+
return False
|
110 |
+
elif other.is_positive and other.is_integer:
|
111 |
+
return True
|
112 |
+
elif other.is_integer is False or other.is_positive is False:
|
113 |
+
return False
|
114 |
+
|
115 |
+
def _eval_is_subset(self, other):
|
116 |
+
return Range(1, oo).is_subset(other)
|
117 |
+
|
118 |
+
def _eval_is_superset(self, other):
|
119 |
+
return Range(1, oo).is_superset(other)
|
120 |
+
|
121 |
+
def __iter__(self):
|
122 |
+
i = self._inf
|
123 |
+
while True:
|
124 |
+
yield i
|
125 |
+
i = i + 1
|
126 |
+
|
127 |
+
@property
|
128 |
+
def _boundary(self):
|
129 |
+
return self
|
130 |
+
|
131 |
+
def as_relational(self, x):
|
132 |
+
return And(Eq(floor(x), x), x >= self.inf, x < oo)
|
133 |
+
|
134 |
+
def _kind(self):
|
135 |
+
return SetKind(NumberKind)
|
136 |
+
|
137 |
+
|
138 |
+
class Naturals0(Naturals):
|
139 |
+
"""Represents the whole numbers which are all the non-negative integers,
|
140 |
+
inclusive of zero.
|
141 |
+
|
142 |
+
See Also
|
143 |
+
========
|
144 |
+
|
145 |
+
Naturals : positive integers; does not include 0
|
146 |
+
Integers : also includes the negative integers
|
147 |
+
"""
|
148 |
+
_inf = S.Zero
|
149 |
+
|
150 |
+
def _contains(self, other):
|
151 |
+
if not isinstance(other, Expr):
|
152 |
+
return S.false
|
153 |
+
elif other.is_integer and other.is_nonnegative:
|
154 |
+
return S.true
|
155 |
+
elif other.is_integer is False or other.is_nonnegative is False:
|
156 |
+
return S.false
|
157 |
+
|
158 |
+
def _eval_is_subset(self, other):
|
159 |
+
return Range(oo).is_subset(other)
|
160 |
+
|
161 |
+
def _eval_is_superset(self, other):
|
162 |
+
return Range(oo).is_superset(other)
|
163 |
+
|
164 |
+
|
165 |
+
class Integers(Set, metaclass=Singleton):
|
166 |
+
"""
|
167 |
+
Represents all integers: positive, negative and zero. This set is also
|
168 |
+
available as the singleton ``S.Integers``.
|
169 |
+
|
170 |
+
Examples
|
171 |
+
========
|
172 |
+
|
173 |
+
>>> from sympy import S, Interval, pprint
|
174 |
+
>>> 5 in S.Naturals
|
175 |
+
True
|
176 |
+
>>> iterable = iter(S.Integers)
|
177 |
+
>>> next(iterable)
|
178 |
+
0
|
179 |
+
>>> next(iterable)
|
180 |
+
1
|
181 |
+
>>> next(iterable)
|
182 |
+
-1
|
183 |
+
>>> next(iterable)
|
184 |
+
2
|
185 |
+
|
186 |
+
>>> pprint(S.Integers.intersect(Interval(-4, 4)))
|
187 |
+
{-4, -3, ..., 4}
|
188 |
+
|
189 |
+
See Also
|
190 |
+
========
|
191 |
+
|
192 |
+
Naturals0 : non-negative integers
|
193 |
+
Integers : positive and negative integers and zero
|
194 |
+
"""
|
195 |
+
|
196 |
+
is_iterable = True
|
197 |
+
is_empty = False
|
198 |
+
is_finite_set = False
|
199 |
+
|
200 |
+
def _contains(self, other):
|
201 |
+
if not isinstance(other, Expr):
|
202 |
+
return S.false
|
203 |
+
return other.is_integer
|
204 |
+
|
205 |
+
def __iter__(self):
|
206 |
+
yield S.Zero
|
207 |
+
i = S.One
|
208 |
+
while True:
|
209 |
+
yield i
|
210 |
+
yield -i
|
211 |
+
i = i + 1
|
212 |
+
|
213 |
+
@property
|
214 |
+
def _inf(self):
|
215 |
+
return S.NegativeInfinity
|
216 |
+
|
217 |
+
@property
|
218 |
+
def _sup(self):
|
219 |
+
return S.Infinity
|
220 |
+
|
221 |
+
@property
|
222 |
+
def _boundary(self):
|
223 |
+
return self
|
224 |
+
|
225 |
+
def _kind(self):
|
226 |
+
return SetKind(NumberKind)
|
227 |
+
|
228 |
+
def as_relational(self, x):
|
229 |
+
return And(Eq(floor(x), x), -oo < x, x < oo)
|
230 |
+
|
231 |
+
def _eval_is_subset(self, other):
|
232 |
+
return Range(-oo, oo).is_subset(other)
|
233 |
+
|
234 |
+
def _eval_is_superset(self, other):
|
235 |
+
return Range(-oo, oo).is_superset(other)
|
236 |
+
|
237 |
+
|
238 |
+
class Reals(Interval, metaclass=Singleton):
|
239 |
+
"""
|
240 |
+
Represents all real numbers
|
241 |
+
from negative infinity to positive infinity,
|
242 |
+
including all integer, rational and irrational numbers.
|
243 |
+
This set is also available as the singleton ``S.Reals``.
|
244 |
+
|
245 |
+
|
246 |
+
Examples
|
247 |
+
========
|
248 |
+
|
249 |
+
>>> from sympy import S, Rational, pi, I
|
250 |
+
>>> 5 in S.Reals
|
251 |
+
True
|
252 |
+
>>> Rational(-1, 2) in S.Reals
|
253 |
+
True
|
254 |
+
>>> pi in S.Reals
|
255 |
+
True
|
256 |
+
>>> 3*I in S.Reals
|
257 |
+
False
|
258 |
+
>>> S.Reals.contains(pi)
|
259 |
+
True
|
260 |
+
|
261 |
+
|
262 |
+
See Also
|
263 |
+
========
|
264 |
+
|
265 |
+
ComplexRegion
|
266 |
+
"""
|
267 |
+
@property
|
268 |
+
def start(self):
|
269 |
+
return S.NegativeInfinity
|
270 |
+
|
271 |
+
@property
|
272 |
+
def end(self):
|
273 |
+
return S.Infinity
|
274 |
+
|
275 |
+
@property
|
276 |
+
def left_open(self):
|
277 |
+
return True
|
278 |
+
|
279 |
+
@property
|
280 |
+
def right_open(self):
|
281 |
+
return True
|
282 |
+
|
283 |
+
def __eq__(self, other):
|
284 |
+
return other == Interval(S.NegativeInfinity, S.Infinity)
|
285 |
+
|
286 |
+
def __hash__(self):
|
287 |
+
return hash(Interval(S.NegativeInfinity, S.Infinity))
|
288 |
+
|
289 |
+
|
290 |
+
class ImageSet(Set):
|
291 |
+
"""
|
292 |
+
Image of a set under a mathematical function. The transformation
|
293 |
+
must be given as a Lambda function which has as many arguments
|
294 |
+
as the elements of the set upon which it operates, e.g. 1 argument
|
295 |
+
when acting on the set of integers or 2 arguments when acting on
|
296 |
+
a complex region.
|
297 |
+
|
298 |
+
This function is not normally called directly, but is called
|
299 |
+
from ``imageset``.
|
300 |
+
|
301 |
+
|
302 |
+
Examples
|
303 |
+
========
|
304 |
+
|
305 |
+
>>> from sympy import Symbol, S, pi, Dummy, Lambda
|
306 |
+
>>> from sympy import FiniteSet, ImageSet, Interval
|
307 |
+
|
308 |
+
>>> x = Symbol('x')
|
309 |
+
>>> N = S.Naturals
|
310 |
+
>>> squares = ImageSet(Lambda(x, x**2), N) # {x**2 for x in N}
|
311 |
+
>>> 4 in squares
|
312 |
+
True
|
313 |
+
>>> 5 in squares
|
314 |
+
False
|
315 |
+
|
316 |
+
>>> FiniteSet(0, 1, 2, 3, 4, 5, 6, 7, 9, 10).intersect(squares)
|
317 |
+
{1, 4, 9}
|
318 |
+
|
319 |
+
>>> square_iterable = iter(squares)
|
320 |
+
>>> for i in range(4):
|
321 |
+
... next(square_iterable)
|
322 |
+
1
|
323 |
+
4
|
324 |
+
9
|
325 |
+
16
|
326 |
+
|
327 |
+
If you want to get value for `x` = 2, 1/2 etc. (Please check whether the
|
328 |
+
`x` value is in ``base_set`` or not before passing it as args)
|
329 |
+
|
330 |
+
>>> squares.lamda(2)
|
331 |
+
4
|
332 |
+
>>> squares.lamda(S(1)/2)
|
333 |
+
1/4
|
334 |
+
|
335 |
+
>>> n = Dummy('n')
|
336 |
+
>>> solutions = ImageSet(Lambda(n, n*pi), S.Integers) # solutions of sin(x) = 0
|
337 |
+
>>> dom = Interval(-1, 1)
|
338 |
+
>>> dom.intersect(solutions)
|
339 |
+
{0}
|
340 |
+
|
341 |
+
See Also
|
342 |
+
========
|
343 |
+
|
344 |
+
sympy.sets.sets.imageset
|
345 |
+
"""
|
346 |
+
def __new__(cls, flambda, *sets):
|
347 |
+
if not isinstance(flambda, Lambda):
|
348 |
+
raise ValueError('First argument must be a Lambda')
|
349 |
+
|
350 |
+
signature = flambda.signature
|
351 |
+
|
352 |
+
if len(signature) != len(sets):
|
353 |
+
raise ValueError('Incompatible signature')
|
354 |
+
|
355 |
+
sets = [_sympify(s) for s in sets]
|
356 |
+
|
357 |
+
if not all(isinstance(s, Set) for s in sets):
|
358 |
+
raise TypeError("Set arguments to ImageSet should of type Set")
|
359 |
+
|
360 |
+
if not all(cls._check_sig(sg, st) for sg, st in zip(signature, sets)):
|
361 |
+
raise ValueError("Signature %s does not match sets %s" % (signature, sets))
|
362 |
+
|
363 |
+
if flambda is S.IdentityFunction and len(sets) == 1:
|
364 |
+
return sets[0]
|
365 |
+
|
366 |
+
if not set(flambda.variables) & flambda.expr.free_symbols:
|
367 |
+
is_empty = fuzzy_or(s.is_empty for s in sets)
|
368 |
+
if is_empty == True:
|
369 |
+
return S.EmptySet
|
370 |
+
elif is_empty == False:
|
371 |
+
return FiniteSet(flambda.expr)
|
372 |
+
|
373 |
+
return Basic.__new__(cls, flambda, *sets)
|
374 |
+
|
375 |
+
lamda = property(lambda self: self.args[0])
|
376 |
+
base_sets = property(lambda self: self.args[1:])
|
377 |
+
|
378 |
+
@property
|
379 |
+
def base_set(self):
|
380 |
+
# XXX: Maybe deprecate this? It is poorly defined in handling
|
381 |
+
# the multivariate case...
|
382 |
+
sets = self.base_sets
|
383 |
+
if len(sets) == 1:
|
384 |
+
return sets[0]
|
385 |
+
else:
|
386 |
+
return ProductSet(*sets).flatten()
|
387 |
+
|
388 |
+
@property
|
389 |
+
def base_pset(self):
|
390 |
+
return ProductSet(*self.base_sets)
|
391 |
+
|
392 |
+
@classmethod
|
393 |
+
def _check_sig(cls, sig_i, set_i):
|
394 |
+
if sig_i.is_symbol:
|
395 |
+
return True
|
396 |
+
elif isinstance(set_i, ProductSet):
|
397 |
+
sets = set_i.sets
|
398 |
+
if len(sig_i) != len(sets):
|
399 |
+
return False
|
400 |
+
# Recurse through the signature for nested tuples:
|
401 |
+
return all(cls._check_sig(ts, ps) for ts, ps in zip(sig_i, sets))
|
402 |
+
else:
|
403 |
+
# XXX: Need a better way of checking whether a set is a set of
|
404 |
+
# Tuples or not. For example a FiniteSet can contain Tuples
|
405 |
+
# but so can an ImageSet or a ConditionSet. Others like
|
406 |
+
# Integers, Reals etc can not contain Tuples. We could just
|
407 |
+
# list the possibilities here... Current code for e.g.
|
408 |
+
# _contains probably only works for ProductSet.
|
409 |
+
return True # Give the benefit of the doubt
|
410 |
+
|
411 |
+
def __iter__(self):
|
412 |
+
already_seen = set()
|
413 |
+
for i in self.base_pset:
|
414 |
+
val = self.lamda(*i)
|
415 |
+
if val in already_seen:
|
416 |
+
continue
|
417 |
+
else:
|
418 |
+
already_seen.add(val)
|
419 |
+
yield val
|
420 |
+
|
421 |
+
def _is_multivariate(self):
|
422 |
+
return len(self.lamda.variables) > 1
|
423 |
+
|
424 |
+
def _contains(self, other):
|
425 |
+
from sympy.solvers.solveset import _solveset_multi
|
426 |
+
|
427 |
+
def get_symsetmap(signature, base_sets):
|
428 |
+
'''Attempt to get a map of symbols to base_sets'''
|
429 |
+
queue = list(zip(signature, base_sets))
|
430 |
+
symsetmap = {}
|
431 |
+
for sig, base_set in queue:
|
432 |
+
if sig.is_symbol:
|
433 |
+
symsetmap[sig] = base_set
|
434 |
+
elif base_set.is_ProductSet:
|
435 |
+
sets = base_set.sets
|
436 |
+
if len(sig) != len(sets):
|
437 |
+
raise ValueError("Incompatible signature")
|
438 |
+
# Recurse
|
439 |
+
queue.extend(zip(sig, sets))
|
440 |
+
else:
|
441 |
+
# If we get here then we have something like sig = (x, y) and
|
442 |
+
# base_set = {(1, 2), (3, 4)}. For now we give up.
|
443 |
+
return None
|
444 |
+
|
445 |
+
return symsetmap
|
446 |
+
|
447 |
+
def get_equations(expr, candidate):
|
448 |
+
'''Find the equations relating symbols in expr and candidate.'''
|
449 |
+
queue = [(expr, candidate)]
|
450 |
+
for e, c in queue:
|
451 |
+
if not isinstance(e, Tuple):
|
452 |
+
yield Eq(e, c)
|
453 |
+
elif not isinstance(c, Tuple) or len(e) != len(c):
|
454 |
+
yield False
|
455 |
+
return
|
456 |
+
else:
|
457 |
+
queue.extend(zip(e, c))
|
458 |
+
|
459 |
+
# Get the basic objects together:
|
460 |
+
other = _sympify(other)
|
461 |
+
expr = self.lamda.expr
|
462 |
+
sig = self.lamda.signature
|
463 |
+
variables = self.lamda.variables
|
464 |
+
base_sets = self.base_sets
|
465 |
+
|
466 |
+
# Use dummy symbols for ImageSet parameters so they don't match
|
467 |
+
# anything in other
|
468 |
+
rep = {v: Dummy(v.name) for v in variables}
|
469 |
+
variables = [v.subs(rep) for v in variables]
|
470 |
+
sig = sig.subs(rep)
|
471 |
+
expr = expr.subs(rep)
|
472 |
+
|
473 |
+
# Map the parts of other to those in the Lambda expr
|
474 |
+
equations = []
|
475 |
+
for eq in get_equations(expr, other):
|
476 |
+
# Unsatisfiable equation?
|
477 |
+
if eq is False:
|
478 |
+
return False
|
479 |
+
equations.append(eq)
|
480 |
+
|
481 |
+
# Map the symbols in the signature to the corresponding domains
|
482 |
+
symsetmap = get_symsetmap(sig, base_sets)
|
483 |
+
if symsetmap is None:
|
484 |
+
# Can't factor the base sets to a ProductSet
|
485 |
+
return None
|
486 |
+
|
487 |
+
# Which of the variables in the Lambda signature need to be solved for?
|
488 |
+
symss = (eq.free_symbols for eq in equations)
|
489 |
+
variables = set(variables) & reduce(set.union, symss, set())
|
490 |
+
|
491 |
+
# Use internal multivariate solveset
|
492 |
+
variables = tuple(variables)
|
493 |
+
base_sets = [symsetmap[v] for v in variables]
|
494 |
+
solnset = _solveset_multi(equations, variables, base_sets)
|
495 |
+
if solnset is None:
|
496 |
+
return None
|
497 |
+
return fuzzy_not(solnset.is_empty)
|
498 |
+
|
499 |
+
@property
|
500 |
+
def is_iterable(self):
|
501 |
+
return all(s.is_iterable for s in self.base_sets)
|
502 |
+
|
503 |
+
def doit(self, **hints):
|
504 |
+
from sympy.sets.setexpr import SetExpr
|
505 |
+
f = self.lamda
|
506 |
+
sig = f.signature
|
507 |
+
if len(sig) == 1 and sig[0].is_symbol and isinstance(f.expr, Expr):
|
508 |
+
base_set = self.base_sets[0]
|
509 |
+
return SetExpr(base_set)._eval_func(f).set
|
510 |
+
if all(s.is_FiniteSet for s in self.base_sets):
|
511 |
+
return FiniteSet(*(f(*a) for a in product(*self.base_sets)))
|
512 |
+
return self
|
513 |
+
|
514 |
+
def _kind(self):
|
515 |
+
return SetKind(self.lamda.expr.kind)
|
516 |
+
|
517 |
+
|
518 |
+
class Range(Set):
|
519 |
+
"""
|
520 |
+
Represents a range of integers. Can be called as ``Range(stop)``,
|
521 |
+
``Range(start, stop)``, or ``Range(start, stop, step)``; when ``step`` is
|
522 |
+
not given it defaults to 1.
|
523 |
+
|
524 |
+
``Range(stop)`` is the same as ``Range(0, stop, 1)`` and the stop value
|
525 |
+
(just as for Python ranges) is not included in the Range values.
|
526 |
+
|
527 |
+
>>> from sympy import Range
|
528 |
+
>>> list(Range(3))
|
529 |
+
[0, 1, 2]
|
530 |
+
|
531 |
+
The step can also be negative:
|
532 |
+
|
533 |
+
>>> list(Range(10, 0, -2))
|
534 |
+
[10, 8, 6, 4, 2]
|
535 |
+
|
536 |
+
The stop value is made canonical so equivalent ranges always
|
537 |
+
have the same args:
|
538 |
+
|
539 |
+
>>> Range(0, 10, 3)
|
540 |
+
Range(0, 12, 3)
|
541 |
+
|
542 |
+
Infinite ranges are allowed. ``oo`` and ``-oo`` are never included in the
|
543 |
+
set (``Range`` is always a subset of ``Integers``). If the starting point
|
544 |
+
is infinite, then the final value is ``stop - step``. To iterate such a
|
545 |
+
range, it needs to be reversed:
|
546 |
+
|
547 |
+
>>> from sympy import oo
|
548 |
+
>>> r = Range(-oo, 1)
|
549 |
+
>>> r[-1]
|
550 |
+
0
|
551 |
+
>>> next(iter(r))
|
552 |
+
Traceback (most recent call last):
|
553 |
+
...
|
554 |
+
TypeError: Cannot iterate over Range with infinite start
|
555 |
+
>>> next(iter(r.reversed))
|
556 |
+
0
|
557 |
+
|
558 |
+
Although ``Range`` is a :class:`Set` (and supports the normal set
|
559 |
+
operations) it maintains the order of the elements and can
|
560 |
+
be used in contexts where ``range`` would be used.
|
561 |
+
|
562 |
+
>>> from sympy import Interval
|
563 |
+
>>> Range(0, 10, 2).intersect(Interval(3, 7))
|
564 |
+
Range(4, 8, 2)
|
565 |
+
>>> list(_)
|
566 |
+
[4, 6]
|
567 |
+
|
568 |
+
Although slicing of a Range will always return a Range -- possibly
|
569 |
+
empty -- an empty set will be returned from any intersection that
|
570 |
+
is empty:
|
571 |
+
|
572 |
+
>>> Range(3)[:0]
|
573 |
+
Range(0, 0, 1)
|
574 |
+
>>> Range(3).intersect(Interval(4, oo))
|
575 |
+
EmptySet
|
576 |
+
>>> Range(3).intersect(Range(4, oo))
|
577 |
+
EmptySet
|
578 |
+
|
579 |
+
Range will accept symbolic arguments but has very limited support
|
580 |
+
for doing anything other than displaying the Range:
|
581 |
+
|
582 |
+
>>> from sympy import Symbol, pprint
|
583 |
+
>>> from sympy.abc import i, j, k
|
584 |
+
>>> Range(i, j, k).start
|
585 |
+
i
|
586 |
+
>>> Range(i, j, k).inf
|
587 |
+
Traceback (most recent call last):
|
588 |
+
...
|
589 |
+
ValueError: invalid method for symbolic range
|
590 |
+
|
591 |
+
Better success will be had when using integer symbols:
|
592 |
+
|
593 |
+
>>> n = Symbol('n', integer=True)
|
594 |
+
>>> r = Range(n, n + 20, 3)
|
595 |
+
>>> r.inf
|
596 |
+
n
|
597 |
+
>>> pprint(r)
|
598 |
+
{n, n + 3, ..., n + 18}
|
599 |
+
"""
|
600 |
+
|
601 |
+
def __new__(cls, *args):
|
602 |
+
if len(args) == 1:
|
603 |
+
if isinstance(args[0], range):
|
604 |
+
raise TypeError(
|
605 |
+
'use sympify(%s) to convert range to Range' % args[0])
|
606 |
+
|
607 |
+
# expand range
|
608 |
+
slc = slice(*args)
|
609 |
+
|
610 |
+
if slc.step == 0:
|
611 |
+
raise ValueError("step cannot be 0")
|
612 |
+
|
613 |
+
start, stop, step = slc.start or 0, slc.stop, slc.step or 1
|
614 |
+
try:
|
615 |
+
ok = []
|
616 |
+
for w in (start, stop, step):
|
617 |
+
w = sympify(w)
|
618 |
+
if w in [S.NegativeInfinity, S.Infinity] or (
|
619 |
+
w.has(Symbol) and w.is_integer != False):
|
620 |
+
ok.append(w)
|
621 |
+
elif not w.is_Integer:
|
622 |
+
if w.is_infinite:
|
623 |
+
raise ValueError('infinite symbols not allowed')
|
624 |
+
raise ValueError
|
625 |
+
else:
|
626 |
+
ok.append(w)
|
627 |
+
except ValueError:
|
628 |
+
raise ValueError(filldedent('''
|
629 |
+
Finite arguments to Range must be integers; `imageset` can define
|
630 |
+
other cases, e.g. use `imageset(i, i/10, Range(3))` to give
|
631 |
+
[0, 1/10, 1/5].'''))
|
632 |
+
start, stop, step = ok
|
633 |
+
|
634 |
+
null = False
|
635 |
+
if any(i.has(Symbol) for i in (start, stop, step)):
|
636 |
+
dif = stop - start
|
637 |
+
n = dif/step
|
638 |
+
if n.is_Rational:
|
639 |
+
if dif == 0:
|
640 |
+
null = True
|
641 |
+
else: # (x, x + 5, 2) or (x, 3*x, x)
|
642 |
+
n = floor(n)
|
643 |
+
end = start + n*step
|
644 |
+
if dif.is_Rational: # (x, x + 5, 2)
|
645 |
+
if (end - stop).is_negative:
|
646 |
+
end += step
|
647 |
+
else: # (x, 3*x, x)
|
648 |
+
if (end/stop - 1).is_negative:
|
649 |
+
end += step
|
650 |
+
elif n.is_extended_negative:
|
651 |
+
null = True
|
652 |
+
else:
|
653 |
+
end = stop # other methods like sup and reversed must fail
|
654 |
+
elif start.is_infinite:
|
655 |
+
span = step*(stop - start)
|
656 |
+
if span is S.NaN or span <= 0:
|
657 |
+
null = True
|
658 |
+
elif step.is_Integer and stop.is_infinite and abs(step) != 1:
|
659 |
+
raise ValueError(filldedent('''
|
660 |
+
Step size must be %s in this case.''' % (1 if step > 0 else -1)))
|
661 |
+
else:
|
662 |
+
end = stop
|
663 |
+
else:
|
664 |
+
oostep = step.is_infinite
|
665 |
+
if oostep:
|
666 |
+
step = S.One if step > 0 else S.NegativeOne
|
667 |
+
n = ceiling((stop - start)/step)
|
668 |
+
if n <= 0:
|
669 |
+
null = True
|
670 |
+
elif oostep:
|
671 |
+
step = S.One # make it canonical
|
672 |
+
end = start + step
|
673 |
+
else:
|
674 |
+
end = start + n*step
|
675 |
+
if null:
|
676 |
+
start = end = S.Zero
|
677 |
+
step = S.One
|
678 |
+
return Basic.__new__(cls, start, end, step)
|
679 |
+
|
680 |
+
start = property(lambda self: self.args[0])
|
681 |
+
stop = property(lambda self: self.args[1])
|
682 |
+
step = property(lambda self: self.args[2])
|
683 |
+
|
684 |
+
@property
|
685 |
+
def reversed(self):
|
686 |
+
"""Return an equivalent Range in the opposite order.
|
687 |
+
|
688 |
+
Examples
|
689 |
+
========
|
690 |
+
|
691 |
+
>>> from sympy import Range
|
692 |
+
>>> Range(10).reversed
|
693 |
+
Range(9, -1, -1)
|
694 |
+
"""
|
695 |
+
if self.has(Symbol):
|
696 |
+
n = (self.stop - self.start)/self.step
|
697 |
+
if not n.is_extended_positive or not all(
|
698 |
+
i.is_integer or i.is_infinite for i in self.args):
|
699 |
+
raise ValueError('invalid method for symbolic range')
|
700 |
+
if self.start == self.stop:
|
701 |
+
return self
|
702 |
+
return self.func(
|
703 |
+
self.stop - self.step, self.start - self.step, -self.step)
|
704 |
+
|
705 |
+
def _kind(self):
|
706 |
+
return SetKind(NumberKind)
|
707 |
+
|
708 |
+
def _contains(self, other):
|
709 |
+
if self.start == self.stop:
|
710 |
+
return S.false
|
711 |
+
if other.is_infinite:
|
712 |
+
return S.false
|
713 |
+
if not other.is_integer:
|
714 |
+
return other.is_integer
|
715 |
+
if self.has(Symbol):
|
716 |
+
n = (self.stop - self.start)/self.step
|
717 |
+
if not n.is_extended_positive or not all(
|
718 |
+
i.is_integer or i.is_infinite for i in self.args):
|
719 |
+
return
|
720 |
+
else:
|
721 |
+
n = self.size
|
722 |
+
if self.start.is_finite:
|
723 |
+
ref = self.start
|
724 |
+
elif self.stop.is_finite:
|
725 |
+
ref = self.stop
|
726 |
+
else: # both infinite; step is +/- 1 (enforced by __new__)
|
727 |
+
return S.true
|
728 |
+
if n == 1:
|
729 |
+
return Eq(other, self[0])
|
730 |
+
res = (ref - other) % self.step
|
731 |
+
if res == S.Zero:
|
732 |
+
if self.has(Symbol):
|
733 |
+
d = Dummy('i')
|
734 |
+
return self.as_relational(d).subs(d, other)
|
735 |
+
return And(other >= self.inf, other <= self.sup)
|
736 |
+
elif res.is_Integer: # off sequence
|
737 |
+
return S.false
|
738 |
+
else: # symbolic/unsimplified residue modulo step
|
739 |
+
return None
|
740 |
+
|
741 |
+
def __iter__(self):
|
742 |
+
n = self.size # validate
|
743 |
+
if not (n.has(S.Infinity) or n.has(S.NegativeInfinity) or n.is_Integer):
|
744 |
+
raise TypeError("Cannot iterate over symbolic Range")
|
745 |
+
if self.start in [S.NegativeInfinity, S.Infinity]:
|
746 |
+
raise TypeError("Cannot iterate over Range with infinite start")
|
747 |
+
elif self.start != self.stop:
|
748 |
+
i = self.start
|
749 |
+
if n.is_infinite:
|
750 |
+
while True:
|
751 |
+
yield i
|
752 |
+
i += self.step
|
753 |
+
else:
|
754 |
+
for _ in range(n):
|
755 |
+
yield i
|
756 |
+
i += self.step
|
757 |
+
|
758 |
+
@property
|
759 |
+
def is_iterable(self):
|
760 |
+
# Check that size can be determined, used by __iter__
|
761 |
+
dif = self.stop - self.start
|
762 |
+
n = dif/self.step
|
763 |
+
if not (n.has(S.Infinity) or n.has(S.NegativeInfinity) or n.is_Integer):
|
764 |
+
return False
|
765 |
+
if self.start in [S.NegativeInfinity, S.Infinity]:
|
766 |
+
return False
|
767 |
+
if not (n.is_extended_nonnegative and all(i.is_integer for i in self.args)):
|
768 |
+
return False
|
769 |
+
return True
|
770 |
+
|
771 |
+
def __len__(self):
|
772 |
+
rv = self.size
|
773 |
+
if rv is S.Infinity:
|
774 |
+
raise ValueError('Use .size to get the length of an infinite Range')
|
775 |
+
return int(rv)
|
776 |
+
|
777 |
+
@property
|
778 |
+
def size(self):
|
779 |
+
if self.start == self.stop:
|
780 |
+
return S.Zero
|
781 |
+
dif = self.stop - self.start
|
782 |
+
n = dif/self.step
|
783 |
+
if n.is_infinite:
|
784 |
+
return S.Infinity
|
785 |
+
if n.is_extended_nonnegative and all(i.is_integer for i in self.args):
|
786 |
+
return abs(floor(n))
|
787 |
+
raise ValueError('Invalid method for symbolic Range')
|
788 |
+
|
789 |
+
@property
|
790 |
+
def is_finite_set(self):
|
791 |
+
if self.start.is_integer and self.stop.is_integer:
|
792 |
+
return True
|
793 |
+
return self.size.is_finite
|
794 |
+
|
795 |
+
@property
|
796 |
+
def is_empty(self):
|
797 |
+
try:
|
798 |
+
return self.size.is_zero
|
799 |
+
except ValueError:
|
800 |
+
return None
|
801 |
+
|
802 |
+
def __bool__(self):
|
803 |
+
# this only distinguishes between definite null range
|
804 |
+
# and non-null/unknown null; getting True doesn't mean
|
805 |
+
# that it actually is not null
|
806 |
+
b = is_eq(self.start, self.stop)
|
807 |
+
if b is None:
|
808 |
+
raise ValueError('cannot tell if Range is null or not')
|
809 |
+
return not bool(b)
|
810 |
+
|
811 |
+
def __getitem__(self, i):
|
812 |
+
ooslice = "cannot slice from the end with an infinite value"
|
813 |
+
zerostep = "slice step cannot be zero"
|
814 |
+
infinite = "slicing not possible on range with infinite start"
|
815 |
+
# if we had to take every other element in the following
|
816 |
+
# oo, ..., 6, 4, 2, 0
|
817 |
+
# we might get oo, ..., 4, 0 or oo, ..., 6, 2
|
818 |
+
ambiguous = "cannot unambiguously re-stride from the end " + \
|
819 |
+
"with an infinite value"
|
820 |
+
if isinstance(i, slice):
|
821 |
+
if self.size.is_finite: # validates, too
|
822 |
+
if self.start == self.stop:
|
823 |
+
return Range(0)
|
824 |
+
start, stop, step = i.indices(self.size)
|
825 |
+
n = ceiling((stop - start)/step)
|
826 |
+
if n <= 0:
|
827 |
+
return Range(0)
|
828 |
+
canonical_stop = start + n*step
|
829 |
+
end = canonical_stop - step
|
830 |
+
ss = step*self.step
|
831 |
+
return Range(self[start], self[end] + ss, ss)
|
832 |
+
else: # infinite Range
|
833 |
+
start = i.start
|
834 |
+
stop = i.stop
|
835 |
+
if i.step == 0:
|
836 |
+
raise ValueError(zerostep)
|
837 |
+
step = i.step or 1
|
838 |
+
ss = step*self.step
|
839 |
+
#---------------------
|
840 |
+
# handle infinite Range
|
841 |
+
# i.e. Range(-oo, oo) or Range(oo, -oo, -1)
|
842 |
+
# --------------------
|
843 |
+
if self.start.is_infinite and self.stop.is_infinite:
|
844 |
+
raise ValueError(infinite)
|
845 |
+
#---------------------
|
846 |
+
# handle infinite on right
|
847 |
+
# e.g. Range(0, oo) or Range(0, -oo, -1)
|
848 |
+
# --------------------
|
849 |
+
if self.stop.is_infinite:
|
850 |
+
# start and stop are not interdependent --
|
851 |
+
# they only depend on step --so we use the
|
852 |
+
# equivalent reversed values
|
853 |
+
return self.reversed[
|
854 |
+
stop if stop is None else -stop + 1:
|
855 |
+
start if start is None else -start:
|
856 |
+
step].reversed
|
857 |
+
#---------------------
|
858 |
+
# handle infinite on the left
|
859 |
+
# e.g. Range(oo, 0, -1) or Range(-oo, 0)
|
860 |
+
# --------------------
|
861 |
+
# consider combinations of
|
862 |
+
# start/stop {== None, < 0, == 0, > 0} and
|
863 |
+
# step {< 0, > 0}
|
864 |
+
if start is None:
|
865 |
+
if stop is None:
|
866 |
+
if step < 0:
|
867 |
+
return Range(self[-1], self.start, ss)
|
868 |
+
elif step > 1:
|
869 |
+
raise ValueError(ambiguous)
|
870 |
+
else: # == 1
|
871 |
+
return self
|
872 |
+
elif stop < 0:
|
873 |
+
if step < 0:
|
874 |
+
return Range(self[-1], self[stop], ss)
|
875 |
+
else: # > 0
|
876 |
+
return Range(self.start, self[stop], ss)
|
877 |
+
elif stop == 0:
|
878 |
+
if step > 0:
|
879 |
+
return Range(0)
|
880 |
+
else: # < 0
|
881 |
+
raise ValueError(ooslice)
|
882 |
+
elif stop == 1:
|
883 |
+
if step > 0:
|
884 |
+
raise ValueError(ooslice) # infinite singleton
|
885 |
+
else: # < 0
|
886 |
+
raise ValueError(ooslice)
|
887 |
+
else: # > 1
|
888 |
+
raise ValueError(ooslice)
|
889 |
+
elif start < 0:
|
890 |
+
if stop is None:
|
891 |
+
if step < 0:
|
892 |
+
return Range(self[start], self.start, ss)
|
893 |
+
else: # > 0
|
894 |
+
return Range(self[start], self.stop, ss)
|
895 |
+
elif stop < 0:
|
896 |
+
return Range(self[start], self[stop], ss)
|
897 |
+
elif stop == 0:
|
898 |
+
if step < 0:
|
899 |
+
raise ValueError(ooslice)
|
900 |
+
else: # > 0
|
901 |
+
return Range(0)
|
902 |
+
elif stop > 0:
|
903 |
+
raise ValueError(ooslice)
|
904 |
+
elif start == 0:
|
905 |
+
if stop is None:
|
906 |
+
if step < 0:
|
907 |
+
raise ValueError(ooslice) # infinite singleton
|
908 |
+
elif step > 1:
|
909 |
+
raise ValueError(ambiguous)
|
910 |
+
else: # == 1
|
911 |
+
return self
|
912 |
+
elif stop < 0:
|
913 |
+
if step > 1:
|
914 |
+
raise ValueError(ambiguous)
|
915 |
+
elif step == 1:
|
916 |
+
return Range(self.start, self[stop], ss)
|
917 |
+
else: # < 0
|
918 |
+
return Range(0)
|
919 |
+
else: # >= 0
|
920 |
+
raise ValueError(ooslice)
|
921 |
+
elif start > 0:
|
922 |
+
raise ValueError(ooslice)
|
923 |
+
else:
|
924 |
+
if self.start == self.stop:
|
925 |
+
raise IndexError('Range index out of range')
|
926 |
+
if not (all(i.is_integer or i.is_infinite
|
927 |
+
for i in self.args) and ((self.stop - self.start)/
|
928 |
+
self.step).is_extended_positive):
|
929 |
+
raise ValueError('Invalid method for symbolic Range')
|
930 |
+
if i == 0:
|
931 |
+
if self.start.is_infinite:
|
932 |
+
raise ValueError(ooslice)
|
933 |
+
return self.start
|
934 |
+
if i == -1:
|
935 |
+
if self.stop.is_infinite:
|
936 |
+
raise ValueError(ooslice)
|
937 |
+
return self.stop - self.step
|
938 |
+
n = self.size # must be known for any other index
|
939 |
+
rv = (self.stop if i < 0 else self.start) + i*self.step
|
940 |
+
if rv.is_infinite:
|
941 |
+
raise ValueError(ooslice)
|
942 |
+
val = (rv - self.start)/self.step
|
943 |
+
rel = fuzzy_or([val.is_infinite,
|
944 |
+
fuzzy_and([val.is_nonnegative, (n-val).is_nonnegative])])
|
945 |
+
if rel:
|
946 |
+
return rv
|
947 |
+
if rel is None:
|
948 |
+
raise ValueError('Invalid method for symbolic Range')
|
949 |
+
raise IndexError("Range index out of range")
|
950 |
+
|
951 |
+
@property
|
952 |
+
def _inf(self):
|
953 |
+
if not self:
|
954 |
+
return S.EmptySet.inf
|
955 |
+
if self.has(Symbol):
|
956 |
+
if all(i.is_integer or i.is_infinite for i in self.args):
|
957 |
+
dif = self.stop - self.start
|
958 |
+
if self.step.is_positive and dif.is_positive:
|
959 |
+
return self.start
|
960 |
+
elif self.step.is_negative and dif.is_negative:
|
961 |
+
return self.stop - self.step
|
962 |
+
raise ValueError('invalid method for symbolic range')
|
963 |
+
if self.step > 0:
|
964 |
+
return self.start
|
965 |
+
else:
|
966 |
+
return self.stop - self.step
|
967 |
+
|
968 |
+
@property
|
969 |
+
def _sup(self):
|
970 |
+
if not self:
|
971 |
+
return S.EmptySet.sup
|
972 |
+
if self.has(Symbol):
|
973 |
+
if all(i.is_integer or i.is_infinite for i in self.args):
|
974 |
+
dif = self.stop - self.start
|
975 |
+
if self.step.is_positive and dif.is_positive:
|
976 |
+
return self.stop - self.step
|
977 |
+
elif self.step.is_negative and dif.is_negative:
|
978 |
+
return self.start
|
979 |
+
raise ValueError('invalid method for symbolic range')
|
980 |
+
if self.step > 0:
|
981 |
+
return self.stop - self.step
|
982 |
+
else:
|
983 |
+
return self.start
|
984 |
+
|
985 |
+
@property
|
986 |
+
def _boundary(self):
|
987 |
+
return self
|
988 |
+
|
989 |
+
def as_relational(self, x):
|
990 |
+
"""Rewrite a Range in terms of equalities and logic operators. """
|
991 |
+
if self.start.is_infinite:
|
992 |
+
assert not self.stop.is_infinite # by instantiation
|
993 |
+
a = self.reversed.start
|
994 |
+
else:
|
995 |
+
a = self.start
|
996 |
+
step = self.step
|
997 |
+
in_seq = Eq(Mod(x - a, step), 0)
|
998 |
+
ints = And(Eq(Mod(a, 1), 0), Eq(Mod(step, 1), 0))
|
999 |
+
n = (self.stop - self.start)/self.step
|
1000 |
+
if n == 0:
|
1001 |
+
return S.EmptySet.as_relational(x)
|
1002 |
+
if n == 1:
|
1003 |
+
return And(Eq(x, a), ints)
|
1004 |
+
try:
|
1005 |
+
a, b = self.inf, self.sup
|
1006 |
+
except ValueError:
|
1007 |
+
a = None
|
1008 |
+
if a is not None:
|
1009 |
+
range_cond = And(
|
1010 |
+
x > a if a.is_infinite else x >= a,
|
1011 |
+
x < b if b.is_infinite else x <= b)
|
1012 |
+
else:
|
1013 |
+
a, b = self.start, self.stop - self.step
|
1014 |
+
range_cond = Or(
|
1015 |
+
And(self.step >= 1, x > a if a.is_infinite else x >= a,
|
1016 |
+
x < b if b.is_infinite else x <= b),
|
1017 |
+
And(self.step <= -1, x < a if a.is_infinite else x <= a,
|
1018 |
+
x > b if b.is_infinite else x >= b))
|
1019 |
+
return And(in_seq, ints, range_cond)
|
1020 |
+
|
1021 |
+
|
1022 |
+
_sympy_converter[range] = lambda r: Range(r.start, r.stop, r.step)
|
1023 |
+
|
1024 |
+
def normalize_theta_set(theta):
|
1025 |
+
r"""
|
1026 |
+
Normalize a Real Set `theta` in the interval `[0, 2\pi)`. It returns
|
1027 |
+
a normalized value of theta in the Set. For Interval, a maximum of
|
1028 |
+
one cycle $[0, 2\pi]$, is returned i.e. for theta equal to $[0, 10\pi]$,
|
1029 |
+
returned normalized value would be $[0, 2\pi)$. As of now intervals
|
1030 |
+
with end points as non-multiples of ``pi`` is not supported.
|
1031 |
+
|
1032 |
+
Raises
|
1033 |
+
======
|
1034 |
+
|
1035 |
+
NotImplementedError
|
1036 |
+
The algorithms for Normalizing theta Set are not yet
|
1037 |
+
implemented.
|
1038 |
+
ValueError
|
1039 |
+
The input is not valid, i.e. the input is not a real set.
|
1040 |
+
RuntimeError
|
1041 |
+
It is a bug, please report to the github issue tracker.
|
1042 |
+
|
1043 |
+
Examples
|
1044 |
+
========
|
1045 |
+
|
1046 |
+
>>> from sympy.sets.fancysets import normalize_theta_set
|
1047 |
+
>>> from sympy import Interval, FiniteSet, pi
|
1048 |
+
>>> normalize_theta_set(Interval(9*pi/2, 5*pi))
|
1049 |
+
Interval(pi/2, pi)
|
1050 |
+
>>> normalize_theta_set(Interval(-3*pi/2, pi/2))
|
1051 |
+
Interval.Ropen(0, 2*pi)
|
1052 |
+
>>> normalize_theta_set(Interval(-pi/2, pi/2))
|
1053 |
+
Union(Interval(0, pi/2), Interval.Ropen(3*pi/2, 2*pi))
|
1054 |
+
>>> normalize_theta_set(Interval(-4*pi, 3*pi))
|
1055 |
+
Interval.Ropen(0, 2*pi)
|
1056 |
+
>>> normalize_theta_set(Interval(-3*pi/2, -pi/2))
|
1057 |
+
Interval(pi/2, 3*pi/2)
|
1058 |
+
>>> normalize_theta_set(FiniteSet(0, pi, 3*pi))
|
1059 |
+
{0, pi}
|
1060 |
+
|
1061 |
+
"""
|
1062 |
+
from sympy.functions.elementary.trigonometric import _pi_coeff
|
1063 |
+
|
1064 |
+
if theta.is_Interval:
|
1065 |
+
interval_len = theta.measure
|
1066 |
+
# one complete circle
|
1067 |
+
if interval_len >= 2*S.Pi:
|
1068 |
+
if interval_len == 2*S.Pi and theta.left_open and theta.right_open:
|
1069 |
+
k = _pi_coeff(theta.start)
|
1070 |
+
return Union(Interval(0, k*S.Pi, False, True),
|
1071 |
+
Interval(k*S.Pi, 2*S.Pi, True, True))
|
1072 |
+
return Interval(0, 2*S.Pi, False, True)
|
1073 |
+
|
1074 |
+
k_start, k_end = _pi_coeff(theta.start), _pi_coeff(theta.end)
|
1075 |
+
|
1076 |
+
if k_start is None or k_end is None:
|
1077 |
+
raise NotImplementedError("Normalizing theta without pi as coefficient is "
|
1078 |
+
"not yet implemented")
|
1079 |
+
new_start = k_start*S.Pi
|
1080 |
+
new_end = k_end*S.Pi
|
1081 |
+
|
1082 |
+
if new_start > new_end:
|
1083 |
+
return Union(Interval(S.Zero, new_end, False, theta.right_open),
|
1084 |
+
Interval(new_start, 2*S.Pi, theta.left_open, True))
|
1085 |
+
else:
|
1086 |
+
return Interval(new_start, new_end, theta.left_open, theta.right_open)
|
1087 |
+
|
1088 |
+
elif theta.is_FiniteSet:
|
1089 |
+
new_theta = []
|
1090 |
+
for element in theta:
|
1091 |
+
k = _pi_coeff(element)
|
1092 |
+
if k is None:
|
1093 |
+
raise NotImplementedError('Normalizing theta without pi as '
|
1094 |
+
'coefficient, is not Implemented.')
|
1095 |
+
else:
|
1096 |
+
new_theta.append(k*S.Pi)
|
1097 |
+
return FiniteSet(*new_theta)
|
1098 |
+
|
1099 |
+
elif theta.is_Union:
|
1100 |
+
return Union(*[normalize_theta_set(interval) for interval in theta.args])
|
1101 |
+
|
1102 |
+
elif theta.is_subset(S.Reals):
|
1103 |
+
raise NotImplementedError("Normalizing theta when, it is of type %s is not "
|
1104 |
+
"implemented" % type(theta))
|
1105 |
+
else:
|
1106 |
+
raise ValueError(" %s is not a real set" % (theta))
|
1107 |
+
|
1108 |
+
|
1109 |
+
class ComplexRegion(Set):
|
1110 |
+
r"""
|
1111 |
+
Represents the Set of all Complex Numbers. It can represent a
|
1112 |
+
region of Complex Plane in both the standard forms Polar and
|
1113 |
+
Rectangular coordinates.
|
1114 |
+
|
1115 |
+
* Polar Form
|
1116 |
+
Input is in the form of the ProductSet or Union of ProductSets
|
1117 |
+
of the intervals of ``r`` and ``theta``, and use the flag ``polar=True``.
|
1118 |
+
|
1119 |
+
.. math:: Z = \{z \in \mathbb{C} \mid z = r\times (\cos(\theta) + I\sin(\theta)), r \in [\texttt{r}], \theta \in [\texttt{theta}]\}
|
1120 |
+
|
1121 |
+
* Rectangular Form
|
1122 |
+
Input is in the form of the ProductSet or Union of ProductSets
|
1123 |
+
of interval of x and y, the real and imaginary parts of the Complex numbers in a plane.
|
1124 |
+
Default input type is in rectangular form.
|
1125 |
+
|
1126 |
+
.. math:: Z = \{z \in \mathbb{C} \mid z = x + Iy, x \in [\operatorname{re}(z)], y \in [\operatorname{im}(z)]\}
|
1127 |
+
|
1128 |
+
Examples
|
1129 |
+
========
|
1130 |
+
|
1131 |
+
>>> from sympy import ComplexRegion, Interval, S, I, Union
|
1132 |
+
>>> a = Interval(2, 3)
|
1133 |
+
>>> b = Interval(4, 6)
|
1134 |
+
>>> c1 = ComplexRegion(a*b) # Rectangular Form
|
1135 |
+
>>> c1
|
1136 |
+
CartesianComplexRegion(ProductSet(Interval(2, 3), Interval(4, 6)))
|
1137 |
+
|
1138 |
+
* c1 represents the rectangular region in complex plane
|
1139 |
+
surrounded by the coordinates (2, 4), (3, 4), (3, 6) and
|
1140 |
+
(2, 6), of the four vertices.
|
1141 |
+
|
1142 |
+
>>> c = Interval(1, 8)
|
1143 |
+
>>> c2 = ComplexRegion(Union(a*b, b*c))
|
1144 |
+
>>> c2
|
1145 |
+
CartesianComplexRegion(Union(ProductSet(Interval(2, 3), Interval(4, 6)), ProductSet(Interval(4, 6), Interval(1, 8))))
|
1146 |
+
|
1147 |
+
* c2 represents the Union of two rectangular regions in complex
|
1148 |
+
plane. One of them surrounded by the coordinates of c1 and
|
1149 |
+
other surrounded by the coordinates (4, 1), (6, 1), (6, 8) and
|
1150 |
+
(4, 8).
|
1151 |
+
|
1152 |
+
>>> 2.5 + 4.5*I in c1
|
1153 |
+
True
|
1154 |
+
>>> 2.5 + 6.5*I in c1
|
1155 |
+
False
|
1156 |
+
|
1157 |
+
>>> r = Interval(0, 1)
|
1158 |
+
>>> theta = Interval(0, 2*S.Pi)
|
1159 |
+
>>> c2 = ComplexRegion(r*theta, polar=True) # Polar Form
|
1160 |
+
>>> c2 # unit Disk
|
1161 |
+
PolarComplexRegion(ProductSet(Interval(0, 1), Interval.Ropen(0, 2*pi)))
|
1162 |
+
|
1163 |
+
* c2 represents the region in complex plane inside the
|
1164 |
+
Unit Disk centered at the origin.
|
1165 |
+
|
1166 |
+
>>> 0.5 + 0.5*I in c2
|
1167 |
+
True
|
1168 |
+
>>> 1 + 2*I in c2
|
1169 |
+
False
|
1170 |
+
|
1171 |
+
>>> unit_disk = ComplexRegion(Interval(0, 1)*Interval(0, 2*S.Pi), polar=True)
|
1172 |
+
>>> upper_half_unit_disk = ComplexRegion(Interval(0, 1)*Interval(0, S.Pi), polar=True)
|
1173 |
+
>>> intersection = unit_disk.intersect(upper_half_unit_disk)
|
1174 |
+
>>> intersection
|
1175 |
+
PolarComplexRegion(ProductSet(Interval(0, 1), Interval(0, pi)))
|
1176 |
+
>>> intersection == upper_half_unit_disk
|
1177 |
+
True
|
1178 |
+
|
1179 |
+
See Also
|
1180 |
+
========
|
1181 |
+
|
1182 |
+
CartesianComplexRegion
|
1183 |
+
PolarComplexRegion
|
1184 |
+
Complexes
|
1185 |
+
|
1186 |
+
"""
|
1187 |
+
is_ComplexRegion = True
|
1188 |
+
|
1189 |
+
def __new__(cls, sets, polar=False):
|
1190 |
+
if polar is False:
|
1191 |
+
return CartesianComplexRegion(sets)
|
1192 |
+
elif polar is True:
|
1193 |
+
return PolarComplexRegion(sets)
|
1194 |
+
else:
|
1195 |
+
raise ValueError("polar should be either True or False")
|
1196 |
+
|
1197 |
+
@property
|
1198 |
+
def sets(self):
|
1199 |
+
"""
|
1200 |
+
Return raw input sets to the self.
|
1201 |
+
|
1202 |
+
Examples
|
1203 |
+
========
|
1204 |
+
|
1205 |
+
>>> from sympy import Interval, ComplexRegion, Union
|
1206 |
+
>>> a = Interval(2, 3)
|
1207 |
+
>>> b = Interval(4, 5)
|
1208 |
+
>>> c = Interval(1, 7)
|
1209 |
+
>>> C1 = ComplexRegion(a*b)
|
1210 |
+
>>> C1.sets
|
1211 |
+
ProductSet(Interval(2, 3), Interval(4, 5))
|
1212 |
+
>>> C2 = ComplexRegion(Union(a*b, b*c))
|
1213 |
+
>>> C2.sets
|
1214 |
+
Union(ProductSet(Interval(2, 3), Interval(4, 5)), ProductSet(Interval(4, 5), Interval(1, 7)))
|
1215 |
+
|
1216 |
+
"""
|
1217 |
+
return self.args[0]
|
1218 |
+
|
1219 |
+
@property
|
1220 |
+
def psets(self):
|
1221 |
+
"""
|
1222 |
+
Return a tuple of sets (ProductSets) input of the self.
|
1223 |
+
|
1224 |
+
Examples
|
1225 |
+
========
|
1226 |
+
|
1227 |
+
>>> from sympy import Interval, ComplexRegion, Union
|
1228 |
+
>>> a = Interval(2, 3)
|
1229 |
+
>>> b = Interval(4, 5)
|
1230 |
+
>>> c = Interval(1, 7)
|
1231 |
+
>>> C1 = ComplexRegion(a*b)
|
1232 |
+
>>> C1.psets
|
1233 |
+
(ProductSet(Interval(2, 3), Interval(4, 5)),)
|
1234 |
+
>>> C2 = ComplexRegion(Union(a*b, b*c))
|
1235 |
+
>>> C2.psets
|
1236 |
+
(ProductSet(Interval(2, 3), Interval(4, 5)), ProductSet(Interval(4, 5), Interval(1, 7)))
|
1237 |
+
|
1238 |
+
"""
|
1239 |
+
if self.sets.is_ProductSet:
|
1240 |
+
psets = ()
|
1241 |
+
psets = psets + (self.sets, )
|
1242 |
+
else:
|
1243 |
+
psets = self.sets.args
|
1244 |
+
return psets
|
1245 |
+
|
1246 |
+
@property
|
1247 |
+
def a_interval(self):
|
1248 |
+
"""
|
1249 |
+
Return the union of intervals of `x` when, self is in
|
1250 |
+
rectangular form, or the union of intervals of `r` when
|
1251 |
+
self is in polar form.
|
1252 |
+
|
1253 |
+
Examples
|
1254 |
+
========
|
1255 |
+
|
1256 |
+
>>> from sympy import Interval, ComplexRegion, Union
|
1257 |
+
>>> a = Interval(2, 3)
|
1258 |
+
>>> b = Interval(4, 5)
|
1259 |
+
>>> c = Interval(1, 7)
|
1260 |
+
>>> C1 = ComplexRegion(a*b)
|
1261 |
+
>>> C1.a_interval
|
1262 |
+
Interval(2, 3)
|
1263 |
+
>>> C2 = ComplexRegion(Union(a*b, b*c))
|
1264 |
+
>>> C2.a_interval
|
1265 |
+
Union(Interval(2, 3), Interval(4, 5))
|
1266 |
+
|
1267 |
+
"""
|
1268 |
+
a_interval = []
|
1269 |
+
for element in self.psets:
|
1270 |
+
a_interval.append(element.args[0])
|
1271 |
+
|
1272 |
+
a_interval = Union(*a_interval)
|
1273 |
+
return a_interval
|
1274 |
+
|
1275 |
+
@property
|
1276 |
+
def b_interval(self):
|
1277 |
+
"""
|
1278 |
+
Return the union of intervals of `y` when, self is in
|
1279 |
+
rectangular form, or the union of intervals of `theta`
|
1280 |
+
when self is in polar form.
|
1281 |
+
|
1282 |
+
Examples
|
1283 |
+
========
|
1284 |
+
|
1285 |
+
>>> from sympy import Interval, ComplexRegion, Union
|
1286 |
+
>>> a = Interval(2, 3)
|
1287 |
+
>>> b = Interval(4, 5)
|
1288 |
+
>>> c = Interval(1, 7)
|
1289 |
+
>>> C1 = ComplexRegion(a*b)
|
1290 |
+
>>> C1.b_interval
|
1291 |
+
Interval(4, 5)
|
1292 |
+
>>> C2 = ComplexRegion(Union(a*b, b*c))
|
1293 |
+
>>> C2.b_interval
|
1294 |
+
Interval(1, 7)
|
1295 |
+
|
1296 |
+
"""
|
1297 |
+
b_interval = []
|
1298 |
+
for element in self.psets:
|
1299 |
+
b_interval.append(element.args[1])
|
1300 |
+
|
1301 |
+
b_interval = Union(*b_interval)
|
1302 |
+
return b_interval
|
1303 |
+
|
1304 |
+
@property
|
1305 |
+
def _measure(self):
|
1306 |
+
"""
|
1307 |
+
The measure of self.sets.
|
1308 |
+
|
1309 |
+
Examples
|
1310 |
+
========
|
1311 |
+
|
1312 |
+
>>> from sympy import Interval, ComplexRegion, S
|
1313 |
+
>>> a, b = Interval(2, 5), Interval(4, 8)
|
1314 |
+
>>> c = Interval(0, 2*S.Pi)
|
1315 |
+
>>> c1 = ComplexRegion(a*b)
|
1316 |
+
>>> c1.measure
|
1317 |
+
12
|
1318 |
+
>>> c2 = ComplexRegion(a*c, polar=True)
|
1319 |
+
>>> c2.measure
|
1320 |
+
6*pi
|
1321 |
+
|
1322 |
+
"""
|
1323 |
+
return self.sets._measure
|
1324 |
+
|
1325 |
+
def _kind(self):
|
1326 |
+
return self.args[0].kind
|
1327 |
+
|
1328 |
+
@classmethod
|
1329 |
+
def from_real(cls, sets):
|
1330 |
+
"""
|
1331 |
+
Converts given subset of real numbers to a complex region.
|
1332 |
+
|
1333 |
+
Examples
|
1334 |
+
========
|
1335 |
+
|
1336 |
+
>>> from sympy import Interval, ComplexRegion
|
1337 |
+
>>> unit = Interval(0,1)
|
1338 |
+
>>> ComplexRegion.from_real(unit)
|
1339 |
+
CartesianComplexRegion(ProductSet(Interval(0, 1), {0}))
|
1340 |
+
|
1341 |
+
"""
|
1342 |
+
if not sets.is_subset(S.Reals):
|
1343 |
+
raise ValueError("sets must be a subset of the real line")
|
1344 |
+
|
1345 |
+
return CartesianComplexRegion(sets * FiniteSet(0))
|
1346 |
+
|
1347 |
+
def _contains(self, other):
|
1348 |
+
from sympy.functions import arg, Abs
|
1349 |
+
other = sympify(other)
|
1350 |
+
isTuple = isinstance(other, Tuple)
|
1351 |
+
if isTuple and len(other) != 2:
|
1352 |
+
raise ValueError('expecting Tuple of length 2')
|
1353 |
+
|
1354 |
+
# If the other is not an Expression, and neither a Tuple
|
1355 |
+
if not isinstance(other, (Expr, Tuple)):
|
1356 |
+
return S.false
|
1357 |
+
# self in rectangular form
|
1358 |
+
if not self.polar:
|
1359 |
+
re, im = other if isTuple else other.as_real_imag()
|
1360 |
+
return fuzzy_or(fuzzy_and([
|
1361 |
+
pset.args[0]._contains(re),
|
1362 |
+
pset.args[1]._contains(im)])
|
1363 |
+
for pset in self.psets)
|
1364 |
+
|
1365 |
+
# self in polar form
|
1366 |
+
elif self.polar:
|
1367 |
+
if other.is_zero:
|
1368 |
+
# ignore undefined complex argument
|
1369 |
+
return fuzzy_or(pset.args[0]._contains(S.Zero)
|
1370 |
+
for pset in self.psets)
|
1371 |
+
if isTuple:
|
1372 |
+
r, theta = other
|
1373 |
+
else:
|
1374 |
+
r, theta = Abs(other), arg(other)
|
1375 |
+
if theta.is_real and theta.is_number:
|
1376 |
+
# angles in psets are normalized to [0, 2pi)
|
1377 |
+
theta %= 2*S.Pi
|
1378 |
+
return fuzzy_or(fuzzy_and([
|
1379 |
+
pset.args[0]._contains(r),
|
1380 |
+
pset.args[1]._contains(theta)])
|
1381 |
+
for pset in self.psets)
|
1382 |
+
|
1383 |
+
|
1384 |
+
class CartesianComplexRegion(ComplexRegion):
|
1385 |
+
r"""
|
1386 |
+
Set representing a square region of the complex plane.
|
1387 |
+
|
1388 |
+
.. math:: Z = \{z \in \mathbb{C} \mid z = x + Iy, x \in [\operatorname{re}(z)], y \in [\operatorname{im}(z)]\}
|
1389 |
+
|
1390 |
+
Examples
|
1391 |
+
========
|
1392 |
+
|
1393 |
+
>>> from sympy import ComplexRegion, I, Interval
|
1394 |
+
>>> region = ComplexRegion(Interval(1, 3) * Interval(4, 6))
|
1395 |
+
>>> 2 + 5*I in region
|
1396 |
+
True
|
1397 |
+
>>> 5*I in region
|
1398 |
+
False
|
1399 |
+
|
1400 |
+
See also
|
1401 |
+
========
|
1402 |
+
|
1403 |
+
ComplexRegion
|
1404 |
+
PolarComplexRegion
|
1405 |
+
Complexes
|
1406 |
+
"""
|
1407 |
+
|
1408 |
+
polar = False
|
1409 |
+
variables = symbols('x, y', cls=Dummy)
|
1410 |
+
|
1411 |
+
def __new__(cls, sets):
|
1412 |
+
|
1413 |
+
if sets == S.Reals*S.Reals:
|
1414 |
+
return S.Complexes
|
1415 |
+
|
1416 |
+
if all(_a.is_FiniteSet for _a in sets.args) and (len(sets.args) == 2):
|
1417 |
+
|
1418 |
+
# ** ProductSet of FiniteSets in the Complex Plane. **
|
1419 |
+
# For Cases like ComplexRegion({2, 4}*{3}), It
|
1420 |
+
# would return {2 + 3*I, 4 + 3*I}
|
1421 |
+
|
1422 |
+
# FIXME: This should probably be handled with something like:
|
1423 |
+
# return ImageSet(Lambda((x, y), x+I*y), sets).rewrite(FiniteSet)
|
1424 |
+
complex_num = []
|
1425 |
+
for x in sets.args[0]:
|
1426 |
+
for y in sets.args[1]:
|
1427 |
+
complex_num.append(x + S.ImaginaryUnit*y)
|
1428 |
+
return FiniteSet(*complex_num)
|
1429 |
+
else:
|
1430 |
+
return Set.__new__(cls, sets)
|
1431 |
+
|
1432 |
+
@property
|
1433 |
+
def expr(self):
|
1434 |
+
x, y = self.variables
|
1435 |
+
return x + S.ImaginaryUnit*y
|
1436 |
+
|
1437 |
+
|
1438 |
+
class PolarComplexRegion(ComplexRegion):
|
1439 |
+
r"""
|
1440 |
+
Set representing a polar region of the complex plane.
|
1441 |
+
|
1442 |
+
.. math:: Z = \{z \in \mathbb{C} \mid z = r\times (\cos(\theta) + I\sin(\theta)), r \in [\texttt{r}], \theta \in [\texttt{theta}]\}
|
1443 |
+
|
1444 |
+
Examples
|
1445 |
+
========
|
1446 |
+
|
1447 |
+
>>> from sympy import ComplexRegion, Interval, oo, pi, I
|
1448 |
+
>>> rset = Interval(0, oo)
|
1449 |
+
>>> thetaset = Interval(0, pi)
|
1450 |
+
>>> upper_half_plane = ComplexRegion(rset * thetaset, polar=True)
|
1451 |
+
>>> 1 + I in upper_half_plane
|
1452 |
+
True
|
1453 |
+
>>> 1 - I in upper_half_plane
|
1454 |
+
False
|
1455 |
+
|
1456 |
+
See also
|
1457 |
+
========
|
1458 |
+
|
1459 |
+
ComplexRegion
|
1460 |
+
CartesianComplexRegion
|
1461 |
+
Complexes
|
1462 |
+
|
1463 |
+
"""
|
1464 |
+
|
1465 |
+
polar = True
|
1466 |
+
variables = symbols('r, theta', cls=Dummy)
|
1467 |
+
|
1468 |
+
def __new__(cls, sets):
|
1469 |
+
|
1470 |
+
new_sets = []
|
1471 |
+
# sets is Union of ProductSets
|
1472 |
+
if not sets.is_ProductSet:
|
1473 |
+
for k in sets.args:
|
1474 |
+
new_sets.append(k)
|
1475 |
+
# sets is ProductSets
|
1476 |
+
else:
|
1477 |
+
new_sets.append(sets)
|
1478 |
+
# Normalize input theta
|
1479 |
+
for k, v in enumerate(new_sets):
|
1480 |
+
new_sets[k] = ProductSet(v.args[0],
|
1481 |
+
normalize_theta_set(v.args[1]))
|
1482 |
+
sets = Union(*new_sets)
|
1483 |
+
return Set.__new__(cls, sets)
|
1484 |
+
|
1485 |
+
@property
|
1486 |
+
def expr(self):
|
1487 |
+
r, theta = self.variables
|
1488 |
+
return r*(cos(theta) + S.ImaginaryUnit*sin(theta))
|
1489 |
+
|
1490 |
+
|
1491 |
+
class Complexes(CartesianComplexRegion, metaclass=Singleton):
|
1492 |
+
"""
|
1493 |
+
The :class:`Set` of all complex numbers
|
1494 |
+
|
1495 |
+
Examples
|
1496 |
+
========
|
1497 |
+
|
1498 |
+
>>> from sympy import S, I
|
1499 |
+
>>> S.Complexes
|
1500 |
+
Complexes
|
1501 |
+
>>> 1 + I in S.Complexes
|
1502 |
+
True
|
1503 |
+
|
1504 |
+
See also
|
1505 |
+
========
|
1506 |
+
|
1507 |
+
Reals
|
1508 |
+
ComplexRegion
|
1509 |
+
|
1510 |
+
"""
|
1511 |
+
|
1512 |
+
is_empty = False
|
1513 |
+
is_finite_set = False
|
1514 |
+
|
1515 |
+
# Override property from superclass since Complexes has no args
|
1516 |
+
@property
|
1517 |
+
def sets(self):
|
1518 |
+
return ProductSet(S.Reals, S.Reals)
|
1519 |
+
|
1520 |
+
def __new__(cls):
|
1521 |
+
return Set.__new__(cls)
|
env-llmeval/lib/python3.10/site-packages/sympy/sets/handlers/__init__.py
ADDED
File without changes
|
env-llmeval/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/comparison.cpython-310.pyc
ADDED
Binary file (2.35 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/functions.cpython-310.pyc
ADDED
Binary file (6.87 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/mul.cpython-310.pyc
ADDED
Binary file (2.06 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/sets/handlers/add.py
ADDED
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.numbers import oo, Infinity, NegativeInfinity
|
2 |
+
from sympy.core.singleton import S
|
3 |
+
from sympy.core import Basic, Expr
|
4 |
+
from sympy.multipledispatch import Dispatcher
|
5 |
+
from sympy.sets import Interval, FiniteSet
|
6 |
+
|
7 |
+
|
8 |
+
|
9 |
+
# XXX: The functions in this module are clearly not tested and are broken in a
|
10 |
+
# number of ways.
|
11 |
+
|
12 |
+
_set_add = Dispatcher('_set_add')
|
13 |
+
_set_sub = Dispatcher('_set_sub')
|
14 |
+
|
15 |
+
|
16 |
+
@_set_add.register(Basic, Basic)
|
17 |
+
def _(x, y):
|
18 |
+
return None
|
19 |
+
|
20 |
+
|
21 |
+
@_set_add.register(Expr, Expr)
|
22 |
+
def _(x, y):
|
23 |
+
return x+y
|
24 |
+
|
25 |
+
|
26 |
+
@_set_add.register(Interval, Interval)
|
27 |
+
def _(x, y):
|
28 |
+
"""
|
29 |
+
Additions in interval arithmetic
|
30 |
+
https://en.wikipedia.org/wiki/Interval_arithmetic
|
31 |
+
"""
|
32 |
+
return Interval(x.start + y.start, x.end + y.end,
|
33 |
+
x.left_open or y.left_open, x.right_open or y.right_open)
|
34 |
+
|
35 |
+
|
36 |
+
@_set_add.register(Interval, Infinity)
|
37 |
+
def _(x, y):
|
38 |
+
if x.start is S.NegativeInfinity:
|
39 |
+
return Interval(-oo, oo)
|
40 |
+
return FiniteSet({S.Infinity})
|
41 |
+
|
42 |
+
@_set_add.register(Interval, NegativeInfinity)
|
43 |
+
def _(x, y):
|
44 |
+
if x.end is S.Infinity:
|
45 |
+
return Interval(-oo, oo)
|
46 |
+
return FiniteSet({S.NegativeInfinity})
|
47 |
+
|
48 |
+
|
49 |
+
@_set_sub.register(Basic, Basic)
|
50 |
+
def _(x, y):
|
51 |
+
return None
|
52 |
+
|
53 |
+
|
54 |
+
@_set_sub.register(Expr, Expr)
|
55 |
+
def _(x, y):
|
56 |
+
return x-y
|
57 |
+
|
58 |
+
|
59 |
+
@_set_sub.register(Interval, Interval)
|
60 |
+
def _(x, y):
|
61 |
+
"""
|
62 |
+
Subtractions in interval arithmetic
|
63 |
+
https://en.wikipedia.org/wiki/Interval_arithmetic
|
64 |
+
"""
|
65 |
+
return Interval(x.start - y.end, x.end - y.start,
|
66 |
+
x.left_open or y.right_open, x.right_open or y.left_open)
|
67 |
+
|
68 |
+
|
69 |
+
@_set_sub.register(Interval, Infinity)
|
70 |
+
def _(x, y):
|
71 |
+
if x.start is S.NegativeInfinity:
|
72 |
+
return Interval(-oo, oo)
|
73 |
+
return FiniteSet(-oo)
|
74 |
+
|
75 |
+
@_set_sub.register(Interval, NegativeInfinity)
|
76 |
+
def _(x, y):
|
77 |
+
if x.start is S.NegativeInfinity:
|
78 |
+
return Interval(-oo, oo)
|
79 |
+
return FiniteSet(-oo)
|
env-llmeval/lib/python3.10/site-packages/sympy/sets/handlers/comparison.py
ADDED
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.relational import Eq, is_eq
|
2 |
+
from sympy.core.basic import Basic
|
3 |
+
from sympy.core.logic import fuzzy_and, fuzzy_bool
|
4 |
+
from sympy.logic.boolalg import And
|
5 |
+
from sympy.multipledispatch import dispatch
|
6 |
+
from sympy.sets.sets import tfn, ProductSet, Interval, FiniteSet, Set
|
7 |
+
|
8 |
+
|
9 |
+
@dispatch(Interval, FiniteSet) # type:ignore
|
10 |
+
def _eval_is_eq(lhs, rhs): # noqa: F811
|
11 |
+
return False
|
12 |
+
|
13 |
+
|
14 |
+
@dispatch(FiniteSet, Interval) # type:ignore
|
15 |
+
def _eval_is_eq(lhs, rhs): # noqa: F811
|
16 |
+
return False
|
17 |
+
|
18 |
+
|
19 |
+
@dispatch(Interval, Interval) # type:ignore
|
20 |
+
def _eval_is_eq(lhs, rhs): # noqa: F811
|
21 |
+
return And(Eq(lhs.left, rhs.left),
|
22 |
+
Eq(lhs.right, rhs.right),
|
23 |
+
lhs.left_open == rhs.left_open,
|
24 |
+
lhs.right_open == rhs.right_open)
|
25 |
+
|
26 |
+
@dispatch(FiniteSet, FiniteSet) # type:ignore
|
27 |
+
def _eval_is_eq(lhs, rhs): # noqa: F811
|
28 |
+
def all_in_both():
|
29 |
+
s_set = set(lhs.args)
|
30 |
+
o_set = set(rhs.args)
|
31 |
+
yield fuzzy_and(lhs._contains(e) for e in o_set - s_set)
|
32 |
+
yield fuzzy_and(rhs._contains(e) for e in s_set - o_set)
|
33 |
+
|
34 |
+
return tfn[fuzzy_and(all_in_both())]
|
35 |
+
|
36 |
+
|
37 |
+
@dispatch(ProductSet, ProductSet) # type:ignore
|
38 |
+
def _eval_is_eq(lhs, rhs): # noqa: F811
|
39 |
+
if len(lhs.sets) != len(rhs.sets):
|
40 |
+
return False
|
41 |
+
|
42 |
+
eqs = (is_eq(x, y) for x, y in zip(lhs.sets, rhs.sets))
|
43 |
+
return tfn[fuzzy_and(map(fuzzy_bool, eqs))]
|
44 |
+
|
45 |
+
|
46 |
+
@dispatch(Set, Basic) # type:ignore
|
47 |
+
def _eval_is_eq(lhs, rhs): # noqa: F811
|
48 |
+
return False
|
49 |
+
|
50 |
+
|
51 |
+
@dispatch(Set, Set) # type:ignore
|
52 |
+
def _eval_is_eq(lhs, rhs): # noqa: F811
|
53 |
+
return tfn[fuzzy_and(a.is_subset(b) for a, b in [(lhs, rhs), (rhs, lhs)])]
|
env-llmeval/lib/python3.10/site-packages/sympy/sets/handlers/functions.py
ADDED
@@ -0,0 +1,262 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.singleton import S
|
2 |
+
from sympy.sets.sets import Set
|
3 |
+
from sympy.calculus.singularities import singularities
|
4 |
+
from sympy.core import Expr, Add
|
5 |
+
from sympy.core.function import Lambda, FunctionClass, diff, expand_mul
|
6 |
+
from sympy.core.numbers import Float, oo
|
7 |
+
from sympy.core.symbol import Dummy, symbols, Wild
|
8 |
+
from sympy.functions.elementary.exponential import exp, log
|
9 |
+
from sympy.functions.elementary.miscellaneous import Min, Max
|
10 |
+
from sympy.logic.boolalg import true
|
11 |
+
from sympy.multipledispatch import Dispatcher
|
12 |
+
from sympy.sets import (imageset, Interval, FiniteSet, Union, ImageSet,
|
13 |
+
Intersection, Range, Complement)
|
14 |
+
from sympy.sets.sets import EmptySet, is_function_invertible_in_set
|
15 |
+
from sympy.sets.fancysets import Integers, Naturals, Reals
|
16 |
+
from sympy.functions.elementary.exponential import match_real_imag
|
17 |
+
|
18 |
+
|
19 |
+
_x, _y = symbols("x y")
|
20 |
+
|
21 |
+
FunctionUnion = (FunctionClass, Lambda)
|
22 |
+
|
23 |
+
_set_function = Dispatcher('_set_function')
|
24 |
+
|
25 |
+
|
26 |
+
@_set_function.register(FunctionClass, Set)
|
27 |
+
def _(f, x):
|
28 |
+
return None
|
29 |
+
|
30 |
+
@_set_function.register(FunctionUnion, FiniteSet)
|
31 |
+
def _(f, x):
|
32 |
+
return FiniteSet(*map(f, x))
|
33 |
+
|
34 |
+
@_set_function.register(Lambda, Interval)
|
35 |
+
def _(f, x):
|
36 |
+
from sympy.solvers.solveset import solveset
|
37 |
+
from sympy.series import limit
|
38 |
+
# TODO: handle functions with infinitely many solutions (eg, sin, tan)
|
39 |
+
# TODO: handle multivariate functions
|
40 |
+
|
41 |
+
expr = f.expr
|
42 |
+
if len(expr.free_symbols) > 1 or len(f.variables) != 1:
|
43 |
+
return
|
44 |
+
var = f.variables[0]
|
45 |
+
if not var.is_real:
|
46 |
+
if expr.subs(var, Dummy(real=True)).is_real is False:
|
47 |
+
return
|
48 |
+
|
49 |
+
if expr.is_Piecewise:
|
50 |
+
result = S.EmptySet
|
51 |
+
domain_set = x
|
52 |
+
for (p_expr, p_cond) in expr.args:
|
53 |
+
if p_cond is true:
|
54 |
+
intrvl = domain_set
|
55 |
+
else:
|
56 |
+
intrvl = p_cond.as_set()
|
57 |
+
intrvl = Intersection(domain_set, intrvl)
|
58 |
+
|
59 |
+
if p_expr.is_Number:
|
60 |
+
image = FiniteSet(p_expr)
|
61 |
+
else:
|
62 |
+
image = imageset(Lambda(var, p_expr), intrvl)
|
63 |
+
result = Union(result, image)
|
64 |
+
|
65 |
+
# remove the part which has been `imaged`
|
66 |
+
domain_set = Complement(domain_set, intrvl)
|
67 |
+
if domain_set is S.EmptySet:
|
68 |
+
break
|
69 |
+
return result
|
70 |
+
|
71 |
+
if not x.start.is_comparable or not x.end.is_comparable:
|
72 |
+
return
|
73 |
+
|
74 |
+
try:
|
75 |
+
from sympy.polys.polyutils import _nsort
|
76 |
+
sing = list(singularities(expr, var, x))
|
77 |
+
if len(sing) > 1:
|
78 |
+
sing = _nsort(sing)
|
79 |
+
except NotImplementedError:
|
80 |
+
return
|
81 |
+
|
82 |
+
if x.left_open:
|
83 |
+
_start = limit(expr, var, x.start, dir="+")
|
84 |
+
elif x.start not in sing:
|
85 |
+
_start = f(x.start)
|
86 |
+
if x.right_open:
|
87 |
+
_end = limit(expr, var, x.end, dir="-")
|
88 |
+
elif x.end not in sing:
|
89 |
+
_end = f(x.end)
|
90 |
+
|
91 |
+
if len(sing) == 0:
|
92 |
+
soln_expr = solveset(diff(expr, var), var)
|
93 |
+
if not (isinstance(soln_expr, FiniteSet)
|
94 |
+
or soln_expr is S.EmptySet):
|
95 |
+
return
|
96 |
+
solns = list(soln_expr)
|
97 |
+
|
98 |
+
extr = [_start, _end] + [f(i) for i in solns
|
99 |
+
if i.is_real and i in x]
|
100 |
+
start, end = Min(*extr), Max(*extr)
|
101 |
+
|
102 |
+
left_open, right_open = False, False
|
103 |
+
if _start <= _end:
|
104 |
+
# the minimum or maximum value can occur simultaneously
|
105 |
+
# on both the edge of the interval and in some interior
|
106 |
+
# point
|
107 |
+
if start == _start and start not in solns:
|
108 |
+
left_open = x.left_open
|
109 |
+
if end == _end and end not in solns:
|
110 |
+
right_open = x.right_open
|
111 |
+
else:
|
112 |
+
if start == _end and start not in solns:
|
113 |
+
left_open = x.right_open
|
114 |
+
if end == _start and end not in solns:
|
115 |
+
right_open = x.left_open
|
116 |
+
|
117 |
+
return Interval(start, end, left_open, right_open)
|
118 |
+
else:
|
119 |
+
return imageset(f, Interval(x.start, sing[0],
|
120 |
+
x.left_open, True)) + \
|
121 |
+
Union(*[imageset(f, Interval(sing[i], sing[i + 1], True, True))
|
122 |
+
for i in range(0, len(sing) - 1)]) + \
|
123 |
+
imageset(f, Interval(sing[-1], x.end, True, x.right_open))
|
124 |
+
|
125 |
+
@_set_function.register(FunctionClass, Interval)
|
126 |
+
def _(f, x):
|
127 |
+
if f == exp:
|
128 |
+
return Interval(exp(x.start), exp(x.end), x.left_open, x.right_open)
|
129 |
+
elif f == log:
|
130 |
+
return Interval(log(x.start), log(x.end), x.left_open, x.right_open)
|
131 |
+
return ImageSet(Lambda(_x, f(_x)), x)
|
132 |
+
|
133 |
+
@_set_function.register(FunctionUnion, Union)
|
134 |
+
def _(f, x):
|
135 |
+
return Union(*(imageset(f, arg) for arg in x.args))
|
136 |
+
|
137 |
+
@_set_function.register(FunctionUnion, Intersection)
|
138 |
+
def _(f, x):
|
139 |
+
# If the function is invertible, intersect the maps of the sets.
|
140 |
+
if is_function_invertible_in_set(f, x):
|
141 |
+
return Intersection(*(imageset(f, arg) for arg in x.args))
|
142 |
+
else:
|
143 |
+
return ImageSet(Lambda(_x, f(_x)), x)
|
144 |
+
|
145 |
+
@_set_function.register(FunctionUnion, EmptySet)
|
146 |
+
def _(f, x):
|
147 |
+
return x
|
148 |
+
|
149 |
+
@_set_function.register(FunctionUnion, Set)
|
150 |
+
def _(f, x):
|
151 |
+
return ImageSet(Lambda(_x, f(_x)), x)
|
152 |
+
|
153 |
+
@_set_function.register(FunctionUnion, Range)
|
154 |
+
def _(f, self):
|
155 |
+
if not self:
|
156 |
+
return S.EmptySet
|
157 |
+
if not isinstance(f.expr, Expr):
|
158 |
+
return
|
159 |
+
if self.size == 1:
|
160 |
+
return FiniteSet(f(self[0]))
|
161 |
+
if f is S.IdentityFunction:
|
162 |
+
return self
|
163 |
+
|
164 |
+
x = f.variables[0]
|
165 |
+
expr = f.expr
|
166 |
+
# handle f that is linear in f's variable
|
167 |
+
if x not in expr.free_symbols or x in expr.diff(x).free_symbols:
|
168 |
+
return
|
169 |
+
if self.start.is_finite:
|
170 |
+
F = f(self.step*x + self.start) # for i in range(len(self))
|
171 |
+
else:
|
172 |
+
F = f(-self.step*x + self[-1])
|
173 |
+
F = expand_mul(F)
|
174 |
+
if F != expr:
|
175 |
+
return imageset(x, F, Range(self.size))
|
176 |
+
|
177 |
+
@_set_function.register(FunctionUnion, Integers)
|
178 |
+
def _(f, self):
|
179 |
+
expr = f.expr
|
180 |
+
if not isinstance(expr, Expr):
|
181 |
+
return
|
182 |
+
|
183 |
+
n = f.variables[0]
|
184 |
+
if expr == abs(n):
|
185 |
+
return S.Naturals0
|
186 |
+
|
187 |
+
# f(x) + c and f(-x) + c cover the same integers
|
188 |
+
# so choose the form that has the fewest negatives
|
189 |
+
c = f(0)
|
190 |
+
fx = f(n) - c
|
191 |
+
f_x = f(-n) - c
|
192 |
+
neg_count = lambda e: sum(_.could_extract_minus_sign()
|
193 |
+
for _ in Add.make_args(e))
|
194 |
+
if neg_count(f_x) < neg_count(fx):
|
195 |
+
expr = f_x + c
|
196 |
+
|
197 |
+
a = Wild('a', exclude=[n])
|
198 |
+
b = Wild('b', exclude=[n])
|
199 |
+
match = expr.match(a*n + b)
|
200 |
+
if match and match[a] and (
|
201 |
+
not match[a].atoms(Float) and
|
202 |
+
not match[b].atoms(Float)):
|
203 |
+
# canonical shift
|
204 |
+
a, b = match[a], match[b]
|
205 |
+
if a in [1, -1]:
|
206 |
+
# drop integer addends in b
|
207 |
+
nonint = []
|
208 |
+
for bi in Add.make_args(b):
|
209 |
+
if not bi.is_integer:
|
210 |
+
nonint.append(bi)
|
211 |
+
b = Add(*nonint)
|
212 |
+
if b.is_number and a.is_real:
|
213 |
+
# avoid Mod for complex numbers, #11391
|
214 |
+
br, bi = match_real_imag(b)
|
215 |
+
if br and br.is_comparable and a.is_comparable:
|
216 |
+
br %= a
|
217 |
+
b = br + S.ImaginaryUnit*bi
|
218 |
+
elif b.is_number and a.is_imaginary:
|
219 |
+
br, bi = match_real_imag(b)
|
220 |
+
ai = a/S.ImaginaryUnit
|
221 |
+
if bi and bi.is_comparable and ai.is_comparable:
|
222 |
+
bi %= ai
|
223 |
+
b = br + S.ImaginaryUnit*bi
|
224 |
+
expr = a*n + b
|
225 |
+
|
226 |
+
if expr != f.expr:
|
227 |
+
return ImageSet(Lambda(n, expr), S.Integers)
|
228 |
+
|
229 |
+
|
230 |
+
@_set_function.register(FunctionUnion, Naturals)
|
231 |
+
def _(f, self):
|
232 |
+
expr = f.expr
|
233 |
+
if not isinstance(expr, Expr):
|
234 |
+
return
|
235 |
+
|
236 |
+
x = f.variables[0]
|
237 |
+
if not expr.free_symbols - {x}:
|
238 |
+
if expr == abs(x):
|
239 |
+
if self is S.Naturals:
|
240 |
+
return self
|
241 |
+
return S.Naturals0
|
242 |
+
step = expr.coeff(x)
|
243 |
+
c = expr.subs(x, 0)
|
244 |
+
if c.is_Integer and step.is_Integer and expr == step*x + c:
|
245 |
+
if self is S.Naturals:
|
246 |
+
c += step
|
247 |
+
if step > 0:
|
248 |
+
if step == 1:
|
249 |
+
if c == 0:
|
250 |
+
return S.Naturals0
|
251 |
+
elif c == 1:
|
252 |
+
return S.Naturals
|
253 |
+
return Range(c, oo, step)
|
254 |
+
return Range(c, -oo, step)
|
255 |
+
|
256 |
+
|
257 |
+
@_set_function.register(FunctionUnion, Reals)
|
258 |
+
def _(f, self):
|
259 |
+
expr = f.expr
|
260 |
+
if not isinstance(expr, Expr):
|
261 |
+
return
|
262 |
+
return _set_function(f, Interval(-oo, oo))
|
env-llmeval/lib/python3.10/site-packages/sympy/sets/handlers/intersection.py
ADDED
@@ -0,0 +1,514 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.function import Lambda, expand_complex
|
2 |
+
from sympy.core.mul import Mul
|
3 |
+
from sympy.core.numbers import ilcm
|
4 |
+
from sympy.core.relational import Eq
|
5 |
+
from sympy.core.singleton import S
|
6 |
+
from sympy.core.symbol import (Dummy, symbols)
|
7 |
+
from sympy.core.sorting import ordered
|
8 |
+
from sympy.functions.elementary.complexes import sign
|
9 |
+
from sympy.functions.elementary.integers import floor, ceiling
|
10 |
+
from sympy.sets.fancysets import ComplexRegion
|
11 |
+
from sympy.sets.sets import (FiniteSet, Intersection, Interval, Set, Union)
|
12 |
+
from sympy.multipledispatch import Dispatcher
|
13 |
+
from sympy.sets.conditionset import ConditionSet
|
14 |
+
from sympy.sets.fancysets import (Integers, Naturals, Reals, Range,
|
15 |
+
ImageSet, Rationals)
|
16 |
+
from sympy.sets.sets import EmptySet, UniversalSet, imageset, ProductSet
|
17 |
+
from sympy.simplify.radsimp import numer
|
18 |
+
|
19 |
+
|
20 |
+
intersection_sets = Dispatcher('intersection_sets')
|
21 |
+
|
22 |
+
|
23 |
+
@intersection_sets.register(ConditionSet, ConditionSet)
|
24 |
+
def _(a, b):
|
25 |
+
return None
|
26 |
+
|
27 |
+
@intersection_sets.register(ConditionSet, Set)
|
28 |
+
def _(a, b):
|
29 |
+
return ConditionSet(a.sym, a.condition, Intersection(a.base_set, b))
|
30 |
+
|
31 |
+
@intersection_sets.register(Naturals, Integers)
|
32 |
+
def _(a, b):
|
33 |
+
return a
|
34 |
+
|
35 |
+
@intersection_sets.register(Naturals, Naturals)
|
36 |
+
def _(a, b):
|
37 |
+
return a if a is S.Naturals else b
|
38 |
+
|
39 |
+
@intersection_sets.register(Interval, Naturals)
|
40 |
+
def _(a, b):
|
41 |
+
return intersection_sets(b, a)
|
42 |
+
|
43 |
+
@intersection_sets.register(ComplexRegion, Set)
|
44 |
+
def _(self, other):
|
45 |
+
if other.is_ComplexRegion:
|
46 |
+
# self in rectangular form
|
47 |
+
if (not self.polar) and (not other.polar):
|
48 |
+
return ComplexRegion(Intersection(self.sets, other.sets))
|
49 |
+
|
50 |
+
# self in polar form
|
51 |
+
elif self.polar and other.polar:
|
52 |
+
r1, theta1 = self.a_interval, self.b_interval
|
53 |
+
r2, theta2 = other.a_interval, other.b_interval
|
54 |
+
new_r_interval = Intersection(r1, r2)
|
55 |
+
new_theta_interval = Intersection(theta1, theta2)
|
56 |
+
|
57 |
+
# 0 and 2*Pi means the same
|
58 |
+
if ((2*S.Pi in theta1 and S.Zero in theta2) or
|
59 |
+
(2*S.Pi in theta2 and S.Zero in theta1)):
|
60 |
+
new_theta_interval = Union(new_theta_interval,
|
61 |
+
FiniteSet(0))
|
62 |
+
return ComplexRegion(new_r_interval*new_theta_interval,
|
63 |
+
polar=True)
|
64 |
+
|
65 |
+
|
66 |
+
if other.is_subset(S.Reals):
|
67 |
+
new_interval = []
|
68 |
+
x = symbols("x", cls=Dummy, real=True)
|
69 |
+
|
70 |
+
# self in rectangular form
|
71 |
+
if not self.polar:
|
72 |
+
for element in self.psets:
|
73 |
+
if S.Zero in element.args[1]:
|
74 |
+
new_interval.append(element.args[0])
|
75 |
+
new_interval = Union(*new_interval)
|
76 |
+
return Intersection(new_interval, other)
|
77 |
+
|
78 |
+
# self in polar form
|
79 |
+
elif self.polar:
|
80 |
+
for element in self.psets:
|
81 |
+
if S.Zero in element.args[1]:
|
82 |
+
new_interval.append(element.args[0])
|
83 |
+
if S.Pi in element.args[1]:
|
84 |
+
new_interval.append(ImageSet(Lambda(x, -x), element.args[0]))
|
85 |
+
if S.Zero in element.args[0]:
|
86 |
+
new_interval.append(FiniteSet(0))
|
87 |
+
new_interval = Union(*new_interval)
|
88 |
+
return Intersection(new_interval, other)
|
89 |
+
|
90 |
+
@intersection_sets.register(Integers, Reals)
|
91 |
+
def _(a, b):
|
92 |
+
return a
|
93 |
+
|
94 |
+
@intersection_sets.register(Range, Interval)
|
95 |
+
def _(a, b):
|
96 |
+
# Check that there are no symbolic arguments
|
97 |
+
if not all(i.is_number for i in a.args + b.args[:2]):
|
98 |
+
return
|
99 |
+
|
100 |
+
# In case of null Range, return an EmptySet.
|
101 |
+
if a.size == 0:
|
102 |
+
return S.EmptySet
|
103 |
+
|
104 |
+
# trim down to self's size, and represent
|
105 |
+
# as a Range with step 1.
|
106 |
+
start = ceiling(max(b.inf, a.inf))
|
107 |
+
if start not in b:
|
108 |
+
start += 1
|
109 |
+
end = floor(min(b.sup, a.sup))
|
110 |
+
if end not in b:
|
111 |
+
end -= 1
|
112 |
+
return intersection_sets(a, Range(start, end + 1))
|
113 |
+
|
114 |
+
@intersection_sets.register(Range, Naturals)
|
115 |
+
def _(a, b):
|
116 |
+
return intersection_sets(a, Interval(b.inf, S.Infinity))
|
117 |
+
|
118 |
+
@intersection_sets.register(Range, Range)
|
119 |
+
def _(a, b):
|
120 |
+
# Check that there are no symbolic range arguments
|
121 |
+
if not all(all(v.is_number for v in r.args) for r in [a, b]):
|
122 |
+
return None
|
123 |
+
|
124 |
+
# non-overlap quick exits
|
125 |
+
if not b:
|
126 |
+
return S.EmptySet
|
127 |
+
if not a:
|
128 |
+
return S.EmptySet
|
129 |
+
if b.sup < a.inf:
|
130 |
+
return S.EmptySet
|
131 |
+
if b.inf > a.sup:
|
132 |
+
return S.EmptySet
|
133 |
+
|
134 |
+
# work with finite end at the start
|
135 |
+
r1 = a
|
136 |
+
if r1.start.is_infinite:
|
137 |
+
r1 = r1.reversed
|
138 |
+
r2 = b
|
139 |
+
if r2.start.is_infinite:
|
140 |
+
r2 = r2.reversed
|
141 |
+
|
142 |
+
# If both ends are infinite then it means that one Range is just the set
|
143 |
+
# of all integers (the step must be 1).
|
144 |
+
if r1.start.is_infinite:
|
145 |
+
return b
|
146 |
+
if r2.start.is_infinite:
|
147 |
+
return a
|
148 |
+
|
149 |
+
from sympy.solvers.diophantine.diophantine import diop_linear
|
150 |
+
|
151 |
+
# this equation represents the values of the Range;
|
152 |
+
# it's a linear equation
|
153 |
+
eq = lambda r, i: r.start + i*r.step
|
154 |
+
|
155 |
+
# we want to know when the two equations might
|
156 |
+
# have integer solutions so we use the diophantine
|
157 |
+
# solver
|
158 |
+
va, vb = diop_linear(eq(r1, Dummy('a')) - eq(r2, Dummy('b')))
|
159 |
+
|
160 |
+
# check for no solution
|
161 |
+
no_solution = va is None and vb is None
|
162 |
+
if no_solution:
|
163 |
+
return S.EmptySet
|
164 |
+
|
165 |
+
# there is a solution
|
166 |
+
# -------------------
|
167 |
+
|
168 |
+
# find the coincident point, c
|
169 |
+
a0 = va.as_coeff_Add()[0]
|
170 |
+
c = eq(r1, a0)
|
171 |
+
|
172 |
+
# find the first point, if possible, in each range
|
173 |
+
# since c may not be that point
|
174 |
+
def _first_finite_point(r1, c):
|
175 |
+
if c == r1.start:
|
176 |
+
return c
|
177 |
+
# st is the signed step we need to take to
|
178 |
+
# get from c to r1.start
|
179 |
+
st = sign(r1.start - c)*step
|
180 |
+
# use Range to calculate the first point:
|
181 |
+
# we want to get as close as possible to
|
182 |
+
# r1.start; the Range will not be null since
|
183 |
+
# it will at least contain c
|
184 |
+
s1 = Range(c, r1.start + st, st)[-1]
|
185 |
+
if s1 == r1.start:
|
186 |
+
pass
|
187 |
+
else:
|
188 |
+
# if we didn't hit r1.start then, if the
|
189 |
+
# sign of st didn't match the sign of r1.step
|
190 |
+
# we are off by one and s1 is not in r1
|
191 |
+
if sign(r1.step) != sign(st):
|
192 |
+
s1 -= st
|
193 |
+
if s1 not in r1:
|
194 |
+
return
|
195 |
+
return s1
|
196 |
+
|
197 |
+
# calculate the step size of the new Range
|
198 |
+
step = abs(ilcm(r1.step, r2.step))
|
199 |
+
s1 = _first_finite_point(r1, c)
|
200 |
+
if s1 is None:
|
201 |
+
return S.EmptySet
|
202 |
+
s2 = _first_finite_point(r2, c)
|
203 |
+
if s2 is None:
|
204 |
+
return S.EmptySet
|
205 |
+
|
206 |
+
# replace the corresponding start or stop in
|
207 |
+
# the original Ranges with these points; the
|
208 |
+
# result must have at least one point since
|
209 |
+
# we know that s1 and s2 are in the Ranges
|
210 |
+
def _updated_range(r, first):
|
211 |
+
st = sign(r.step)*step
|
212 |
+
if r.start.is_finite:
|
213 |
+
rv = Range(first, r.stop, st)
|
214 |
+
else:
|
215 |
+
rv = Range(r.start, first + st, st)
|
216 |
+
return rv
|
217 |
+
r1 = _updated_range(a, s1)
|
218 |
+
r2 = _updated_range(b, s2)
|
219 |
+
|
220 |
+
# work with them both in the increasing direction
|
221 |
+
if sign(r1.step) < 0:
|
222 |
+
r1 = r1.reversed
|
223 |
+
if sign(r2.step) < 0:
|
224 |
+
r2 = r2.reversed
|
225 |
+
|
226 |
+
# return clipped Range with positive step; it
|
227 |
+
# can't be empty at this point
|
228 |
+
start = max(r1.start, r2.start)
|
229 |
+
stop = min(r1.stop, r2.stop)
|
230 |
+
return Range(start, stop, step)
|
231 |
+
|
232 |
+
|
233 |
+
@intersection_sets.register(Range, Integers)
|
234 |
+
def _(a, b):
|
235 |
+
return a
|
236 |
+
|
237 |
+
|
238 |
+
@intersection_sets.register(Range, Rationals)
|
239 |
+
def _(a, b):
|
240 |
+
return a
|
241 |
+
|
242 |
+
|
243 |
+
@intersection_sets.register(ImageSet, Set)
|
244 |
+
def _(self, other):
|
245 |
+
from sympy.solvers.diophantine import diophantine
|
246 |
+
|
247 |
+
# Only handle the straight-forward univariate case
|
248 |
+
if (len(self.lamda.variables) > 1
|
249 |
+
or self.lamda.signature != self.lamda.variables):
|
250 |
+
return None
|
251 |
+
base_set = self.base_sets[0]
|
252 |
+
|
253 |
+
# Intersection between ImageSets with Integers as base set
|
254 |
+
# For {f(n) : n in Integers} & {g(m) : m in Integers} we solve the
|
255 |
+
# diophantine equations f(n)=g(m).
|
256 |
+
# If the solutions for n are {h(t) : t in Integers} then we return
|
257 |
+
# {f(h(t)) : t in integers}.
|
258 |
+
# If the solutions for n are {n_1, n_2, ..., n_k} then we return
|
259 |
+
# {f(n_i) : 1 <= i <= k}.
|
260 |
+
if base_set is S.Integers:
|
261 |
+
gm = None
|
262 |
+
if isinstance(other, ImageSet) and other.base_sets == (S.Integers,):
|
263 |
+
gm = other.lamda.expr
|
264 |
+
var = other.lamda.variables[0]
|
265 |
+
# Symbol of second ImageSet lambda must be distinct from first
|
266 |
+
m = Dummy('m')
|
267 |
+
gm = gm.subs(var, m)
|
268 |
+
elif other is S.Integers:
|
269 |
+
m = gm = Dummy('m')
|
270 |
+
if gm is not None:
|
271 |
+
fn = self.lamda.expr
|
272 |
+
n = self.lamda.variables[0]
|
273 |
+
try:
|
274 |
+
solns = list(diophantine(fn - gm, syms=(n, m), permute=True))
|
275 |
+
except (TypeError, NotImplementedError):
|
276 |
+
# TypeError if equation not polynomial with rational coeff.
|
277 |
+
# NotImplementedError if correct format but no solver.
|
278 |
+
return
|
279 |
+
# 3 cases are possible for solns:
|
280 |
+
# - empty set,
|
281 |
+
# - one or more parametric (infinite) solutions,
|
282 |
+
# - a finite number of (non-parametric) solution couples.
|
283 |
+
# Among those, there is one type of solution set that is
|
284 |
+
# not helpful here: multiple parametric solutions.
|
285 |
+
if len(solns) == 0:
|
286 |
+
return S.EmptySet
|
287 |
+
elif any(s.free_symbols for tupl in solns for s in tupl):
|
288 |
+
if len(solns) == 1:
|
289 |
+
soln, solm = solns[0]
|
290 |
+
(t,) = soln.free_symbols
|
291 |
+
expr = fn.subs(n, soln.subs(t, n)).expand()
|
292 |
+
return imageset(Lambda(n, expr), S.Integers)
|
293 |
+
else:
|
294 |
+
return
|
295 |
+
else:
|
296 |
+
return FiniteSet(*(fn.subs(n, s[0]) for s in solns))
|
297 |
+
|
298 |
+
if other == S.Reals:
|
299 |
+
from sympy.solvers.solvers import denoms, solve_linear
|
300 |
+
|
301 |
+
def _solution_union(exprs, sym):
|
302 |
+
# return a union of linear solutions to i in expr;
|
303 |
+
# if i cannot be solved, use a ConditionSet for solution
|
304 |
+
sols = []
|
305 |
+
for i in exprs:
|
306 |
+
x, xis = solve_linear(i, 0, [sym])
|
307 |
+
if x == sym:
|
308 |
+
sols.append(FiniteSet(xis))
|
309 |
+
else:
|
310 |
+
sols.append(ConditionSet(sym, Eq(i, 0)))
|
311 |
+
return Union(*sols)
|
312 |
+
|
313 |
+
f = self.lamda.expr
|
314 |
+
n = self.lamda.variables[0]
|
315 |
+
|
316 |
+
n_ = Dummy(n.name, real=True)
|
317 |
+
f_ = f.subs(n, n_)
|
318 |
+
|
319 |
+
re, im = f_.as_real_imag()
|
320 |
+
im = expand_complex(im)
|
321 |
+
|
322 |
+
re = re.subs(n_, n)
|
323 |
+
im = im.subs(n_, n)
|
324 |
+
ifree = im.free_symbols
|
325 |
+
lam = Lambda(n, re)
|
326 |
+
if im.is_zero:
|
327 |
+
# allow re-evaluation
|
328 |
+
# of self in this case to make
|
329 |
+
# the result canonical
|
330 |
+
pass
|
331 |
+
elif im.is_zero is False:
|
332 |
+
return S.EmptySet
|
333 |
+
elif ifree != {n}:
|
334 |
+
return None
|
335 |
+
else:
|
336 |
+
# univarite imaginary part in same variable;
|
337 |
+
# use numer instead of as_numer_denom to keep
|
338 |
+
# this as fast as possible while still handling
|
339 |
+
# simple cases
|
340 |
+
base_set &= _solution_union(
|
341 |
+
Mul.make_args(numer(im)), n)
|
342 |
+
# exclude values that make denominators 0
|
343 |
+
base_set -= _solution_union(denoms(f), n)
|
344 |
+
return imageset(lam, base_set)
|
345 |
+
|
346 |
+
elif isinstance(other, Interval):
|
347 |
+
from sympy.solvers.solveset import (invert_real, invert_complex,
|
348 |
+
solveset)
|
349 |
+
|
350 |
+
f = self.lamda.expr
|
351 |
+
n = self.lamda.variables[0]
|
352 |
+
new_inf, new_sup = None, None
|
353 |
+
new_lopen, new_ropen = other.left_open, other.right_open
|
354 |
+
|
355 |
+
if f.is_real:
|
356 |
+
inverter = invert_real
|
357 |
+
else:
|
358 |
+
inverter = invert_complex
|
359 |
+
|
360 |
+
g1, h1 = inverter(f, other.inf, n)
|
361 |
+
g2, h2 = inverter(f, other.sup, n)
|
362 |
+
|
363 |
+
if all(isinstance(i, FiniteSet) for i in (h1, h2)):
|
364 |
+
if g1 == n:
|
365 |
+
if len(h1) == 1:
|
366 |
+
new_inf = h1.args[0]
|
367 |
+
if g2 == n:
|
368 |
+
if len(h2) == 1:
|
369 |
+
new_sup = h2.args[0]
|
370 |
+
# TODO: Design a technique to handle multiple-inverse
|
371 |
+
# functions
|
372 |
+
|
373 |
+
# Any of the new boundary values cannot be determined
|
374 |
+
if any(i is None for i in (new_sup, new_inf)):
|
375 |
+
return
|
376 |
+
|
377 |
+
|
378 |
+
range_set = S.EmptySet
|
379 |
+
|
380 |
+
if all(i.is_real for i in (new_sup, new_inf)):
|
381 |
+
# this assumes continuity of underlying function
|
382 |
+
# however fixes the case when it is decreasing
|
383 |
+
if new_inf > new_sup:
|
384 |
+
new_inf, new_sup = new_sup, new_inf
|
385 |
+
new_interval = Interval(new_inf, new_sup, new_lopen, new_ropen)
|
386 |
+
range_set = base_set.intersect(new_interval)
|
387 |
+
else:
|
388 |
+
if other.is_subset(S.Reals):
|
389 |
+
solutions = solveset(f, n, S.Reals)
|
390 |
+
if not isinstance(range_set, (ImageSet, ConditionSet)):
|
391 |
+
range_set = solutions.intersect(other)
|
392 |
+
else:
|
393 |
+
return
|
394 |
+
|
395 |
+
if range_set is S.EmptySet:
|
396 |
+
return S.EmptySet
|
397 |
+
elif isinstance(range_set, Range) and range_set.size is not S.Infinity:
|
398 |
+
range_set = FiniteSet(*list(range_set))
|
399 |
+
|
400 |
+
if range_set is not None:
|
401 |
+
return imageset(Lambda(n, f), range_set)
|
402 |
+
return
|
403 |
+
else:
|
404 |
+
return
|
405 |
+
|
406 |
+
|
407 |
+
@intersection_sets.register(ProductSet, ProductSet)
|
408 |
+
def _(a, b):
|
409 |
+
if len(b.args) != len(a.args):
|
410 |
+
return S.EmptySet
|
411 |
+
return ProductSet(*(i.intersect(j) for i, j in zip(a.sets, b.sets)))
|
412 |
+
|
413 |
+
|
414 |
+
@intersection_sets.register(Interval, Interval)
|
415 |
+
def _(a, b):
|
416 |
+
# handle (-oo, oo)
|
417 |
+
infty = S.NegativeInfinity, S.Infinity
|
418 |
+
if a == Interval(*infty):
|
419 |
+
l, r = a.left, a.right
|
420 |
+
if l.is_real or l in infty or r.is_real or r in infty:
|
421 |
+
return b
|
422 |
+
|
423 |
+
# We can't intersect [0,3] with [x,6] -- we don't know if x>0 or x<0
|
424 |
+
if not a._is_comparable(b):
|
425 |
+
return None
|
426 |
+
|
427 |
+
empty = False
|
428 |
+
|
429 |
+
if a.start <= b.end and b.start <= a.end:
|
430 |
+
# Get topology right.
|
431 |
+
if a.start < b.start:
|
432 |
+
start = b.start
|
433 |
+
left_open = b.left_open
|
434 |
+
elif a.start > b.start:
|
435 |
+
start = a.start
|
436 |
+
left_open = a.left_open
|
437 |
+
else:
|
438 |
+
#this is to ensure that if Eq(a.start,b.start) but
|
439 |
+
#type(a.start) != type(b.start) the order of a and b
|
440 |
+
#does not matter for the result
|
441 |
+
start = list(ordered([a,b]))[0].start
|
442 |
+
left_open = a.left_open or b.left_open
|
443 |
+
|
444 |
+
if a.end < b.end:
|
445 |
+
end = a.end
|
446 |
+
right_open = a.right_open
|
447 |
+
elif a.end > b.end:
|
448 |
+
end = b.end
|
449 |
+
right_open = b.right_open
|
450 |
+
else:
|
451 |
+
end = list(ordered([a,b]))[0].end
|
452 |
+
right_open = a.right_open or b.right_open
|
453 |
+
|
454 |
+
if end - start == 0 and (left_open or right_open):
|
455 |
+
empty = True
|
456 |
+
else:
|
457 |
+
empty = True
|
458 |
+
|
459 |
+
if empty:
|
460 |
+
return S.EmptySet
|
461 |
+
|
462 |
+
return Interval(start, end, left_open, right_open)
|
463 |
+
|
464 |
+
@intersection_sets.register(EmptySet, Set)
|
465 |
+
def _(a, b):
|
466 |
+
return S.EmptySet
|
467 |
+
|
468 |
+
@intersection_sets.register(UniversalSet, Set)
|
469 |
+
def _(a, b):
|
470 |
+
return b
|
471 |
+
|
472 |
+
@intersection_sets.register(FiniteSet, FiniteSet)
|
473 |
+
def _(a, b):
|
474 |
+
return FiniteSet(*(a._elements & b._elements))
|
475 |
+
|
476 |
+
@intersection_sets.register(FiniteSet, Set)
|
477 |
+
def _(a, b):
|
478 |
+
try:
|
479 |
+
return FiniteSet(*[el for el in a if el in b])
|
480 |
+
except TypeError:
|
481 |
+
return None # could not evaluate `el in b` due to symbolic ranges.
|
482 |
+
|
483 |
+
@intersection_sets.register(Set, Set)
|
484 |
+
def _(a, b):
|
485 |
+
return None
|
486 |
+
|
487 |
+
@intersection_sets.register(Integers, Rationals)
|
488 |
+
def _(a, b):
|
489 |
+
return a
|
490 |
+
|
491 |
+
@intersection_sets.register(Naturals, Rationals)
|
492 |
+
def _(a, b):
|
493 |
+
return a
|
494 |
+
|
495 |
+
@intersection_sets.register(Rationals, Reals)
|
496 |
+
def _(a, b):
|
497 |
+
return a
|
498 |
+
|
499 |
+
def _intlike_interval(a, b):
|
500 |
+
try:
|
501 |
+
if b._inf is S.NegativeInfinity and b._sup is S.Infinity:
|
502 |
+
return a
|
503 |
+
s = Range(max(a.inf, ceiling(b.left)), floor(b.right) + 1)
|
504 |
+
return intersection_sets(s, b) # take out endpoints if open interval
|
505 |
+
except ValueError:
|
506 |
+
return None
|
507 |
+
|
508 |
+
@intersection_sets.register(Integers, Interval)
|
509 |
+
def _(a, b):
|
510 |
+
return _intlike_interval(a, b)
|
511 |
+
|
512 |
+
@intersection_sets.register(Naturals, Interval)
|
513 |
+
def _(a, b):
|
514 |
+
return _intlike_interval(a, b)
|
env-llmeval/lib/python3.10/site-packages/sympy/sets/handlers/issubset.py
ADDED
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.singleton import S
|
2 |
+
from sympy.core.symbol import Symbol
|
3 |
+
from sympy.core.logic import fuzzy_and, fuzzy_bool, fuzzy_not, fuzzy_or
|
4 |
+
from sympy.core.relational import Eq
|
5 |
+
from sympy.sets.sets import FiniteSet, Interval, Set, Union, ProductSet
|
6 |
+
from sympy.sets.fancysets import Complexes, Reals, Range, Rationals
|
7 |
+
from sympy.multipledispatch import Dispatcher
|
8 |
+
|
9 |
+
|
10 |
+
_inf_sets = [S.Naturals, S.Naturals0, S.Integers, S.Rationals, S.Reals, S.Complexes]
|
11 |
+
|
12 |
+
|
13 |
+
is_subset_sets = Dispatcher('is_subset_sets')
|
14 |
+
|
15 |
+
|
16 |
+
@is_subset_sets.register(Set, Set)
|
17 |
+
def _(a, b):
|
18 |
+
return None
|
19 |
+
|
20 |
+
@is_subset_sets.register(Interval, Interval)
|
21 |
+
def _(a, b):
|
22 |
+
# This is correct but can be made more comprehensive...
|
23 |
+
if fuzzy_bool(a.start < b.start):
|
24 |
+
return False
|
25 |
+
if fuzzy_bool(a.end > b.end):
|
26 |
+
return False
|
27 |
+
if (b.left_open and not a.left_open and fuzzy_bool(Eq(a.start, b.start))):
|
28 |
+
return False
|
29 |
+
if (b.right_open and not a.right_open and fuzzy_bool(Eq(a.end, b.end))):
|
30 |
+
return False
|
31 |
+
|
32 |
+
@is_subset_sets.register(Interval, FiniteSet)
|
33 |
+
def _(a_interval, b_fs):
|
34 |
+
# An Interval can only be a subset of a finite set if it is finite
|
35 |
+
# which can only happen if it has zero measure.
|
36 |
+
if fuzzy_not(a_interval.measure.is_zero):
|
37 |
+
return False
|
38 |
+
|
39 |
+
@is_subset_sets.register(Interval, Union)
|
40 |
+
def _(a_interval, b_u):
|
41 |
+
if all(isinstance(s, (Interval, FiniteSet)) for s in b_u.args):
|
42 |
+
intervals = [s for s in b_u.args if isinstance(s, Interval)]
|
43 |
+
if all(fuzzy_bool(a_interval.start < s.start) for s in intervals):
|
44 |
+
return False
|
45 |
+
if all(fuzzy_bool(a_interval.end > s.end) for s in intervals):
|
46 |
+
return False
|
47 |
+
if a_interval.measure.is_nonzero:
|
48 |
+
no_overlap = lambda s1, s2: fuzzy_or([
|
49 |
+
fuzzy_bool(s1.end <= s2.start),
|
50 |
+
fuzzy_bool(s1.start >= s2.end),
|
51 |
+
])
|
52 |
+
if all(no_overlap(s, a_interval) for s in intervals):
|
53 |
+
return False
|
54 |
+
|
55 |
+
@is_subset_sets.register(Range, Range)
|
56 |
+
def _(a, b):
|
57 |
+
if a.step == b.step == 1:
|
58 |
+
return fuzzy_and([fuzzy_bool(a.start >= b.start),
|
59 |
+
fuzzy_bool(a.stop <= b.stop)])
|
60 |
+
|
61 |
+
@is_subset_sets.register(Range, Interval)
|
62 |
+
def _(a_range, b_interval):
|
63 |
+
if a_range.step.is_positive:
|
64 |
+
if b_interval.left_open and a_range.inf.is_finite:
|
65 |
+
cond_left = a_range.inf > b_interval.left
|
66 |
+
else:
|
67 |
+
cond_left = a_range.inf >= b_interval.left
|
68 |
+
if b_interval.right_open and a_range.sup.is_finite:
|
69 |
+
cond_right = a_range.sup < b_interval.right
|
70 |
+
else:
|
71 |
+
cond_right = a_range.sup <= b_interval.right
|
72 |
+
return fuzzy_and([cond_left, cond_right])
|
73 |
+
|
74 |
+
@is_subset_sets.register(Range, FiniteSet)
|
75 |
+
def _(a_range, b_finiteset):
|
76 |
+
try:
|
77 |
+
a_size = a_range.size
|
78 |
+
except ValueError:
|
79 |
+
# symbolic Range of unknown size
|
80 |
+
return None
|
81 |
+
if a_size > len(b_finiteset):
|
82 |
+
return False
|
83 |
+
elif any(arg.has(Symbol) for arg in a_range.args):
|
84 |
+
return fuzzy_and(b_finiteset.contains(x) for x in a_range)
|
85 |
+
else:
|
86 |
+
# Checking A \ B == EmptySet is more efficient than repeated naive
|
87 |
+
# membership checks on an arbitrary FiniteSet.
|
88 |
+
a_set = set(a_range)
|
89 |
+
b_remaining = len(b_finiteset)
|
90 |
+
# Symbolic expressions and numbers of unknown type (integer or not) are
|
91 |
+
# all counted as "candidates", i.e. *potentially* matching some a in
|
92 |
+
# a_range.
|
93 |
+
cnt_candidate = 0
|
94 |
+
for b in b_finiteset:
|
95 |
+
if b.is_Integer:
|
96 |
+
a_set.discard(b)
|
97 |
+
elif fuzzy_not(b.is_integer):
|
98 |
+
pass
|
99 |
+
else:
|
100 |
+
cnt_candidate += 1
|
101 |
+
b_remaining -= 1
|
102 |
+
if len(a_set) > b_remaining + cnt_candidate:
|
103 |
+
return False
|
104 |
+
if len(a_set) == 0:
|
105 |
+
return True
|
106 |
+
return None
|
107 |
+
|
108 |
+
@is_subset_sets.register(Interval, Range)
|
109 |
+
def _(a_interval, b_range):
|
110 |
+
if a_interval.measure.is_extended_nonzero:
|
111 |
+
return False
|
112 |
+
|
113 |
+
@is_subset_sets.register(Interval, Rationals)
|
114 |
+
def _(a_interval, b_rationals):
|
115 |
+
if a_interval.measure.is_extended_nonzero:
|
116 |
+
return False
|
117 |
+
|
118 |
+
@is_subset_sets.register(Range, Complexes)
|
119 |
+
def _(a, b):
|
120 |
+
return True
|
121 |
+
|
122 |
+
@is_subset_sets.register(Complexes, Interval)
|
123 |
+
def _(a, b):
|
124 |
+
return False
|
125 |
+
|
126 |
+
@is_subset_sets.register(Complexes, Range)
|
127 |
+
def _(a, b):
|
128 |
+
return False
|
129 |
+
|
130 |
+
@is_subset_sets.register(Complexes, Rationals)
|
131 |
+
def _(a, b):
|
132 |
+
return False
|
133 |
+
|
134 |
+
@is_subset_sets.register(Rationals, Reals)
|
135 |
+
def _(a, b):
|
136 |
+
return True
|
137 |
+
|
138 |
+
@is_subset_sets.register(Rationals, Range)
|
139 |
+
def _(a, b):
|
140 |
+
return False
|
141 |
+
|
142 |
+
@is_subset_sets.register(ProductSet, FiniteSet)
|
143 |
+
def _(a_ps, b_fs):
|
144 |
+
return fuzzy_and(b_fs.contains(x) for x in a_ps)
|
env-llmeval/lib/python3.10/site-packages/sympy/sets/handlers/mul.py
ADDED
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core import Basic, Expr
|
2 |
+
from sympy.core.numbers import oo
|
3 |
+
from sympy.core.symbol import symbols
|
4 |
+
from sympy.multipledispatch import Dispatcher
|
5 |
+
from sympy.sets.setexpr import set_mul
|
6 |
+
from sympy.sets.sets import Interval, Set
|
7 |
+
|
8 |
+
|
9 |
+
_x, _y = symbols("x y")
|
10 |
+
|
11 |
+
|
12 |
+
_set_mul = Dispatcher('_set_mul')
|
13 |
+
_set_div = Dispatcher('_set_div')
|
14 |
+
|
15 |
+
|
16 |
+
@_set_mul.register(Basic, Basic)
|
17 |
+
def _(x, y):
|
18 |
+
return None
|
19 |
+
|
20 |
+
@_set_mul.register(Set, Set)
|
21 |
+
def _(x, y):
|
22 |
+
return None
|
23 |
+
|
24 |
+
@_set_mul.register(Expr, Expr)
|
25 |
+
def _(x, y):
|
26 |
+
return x*y
|
27 |
+
|
28 |
+
@_set_mul.register(Interval, Interval)
|
29 |
+
def _(x, y):
|
30 |
+
"""
|
31 |
+
Multiplications in interval arithmetic
|
32 |
+
https://en.wikipedia.org/wiki/Interval_arithmetic
|
33 |
+
"""
|
34 |
+
# TODO: some intervals containing 0 and oo will fail as 0*oo returns nan.
|
35 |
+
comvals = (
|
36 |
+
(x.start * y.start, bool(x.left_open or y.left_open)),
|
37 |
+
(x.start * y.end, bool(x.left_open or y.right_open)),
|
38 |
+
(x.end * y.start, bool(x.right_open or y.left_open)),
|
39 |
+
(x.end * y.end, bool(x.right_open or y.right_open)),
|
40 |
+
)
|
41 |
+
# TODO: handle symbolic intervals
|
42 |
+
minval, minopen = min(comvals)
|
43 |
+
maxval, maxopen = max(comvals)
|
44 |
+
return Interval(
|
45 |
+
minval,
|
46 |
+
maxval,
|
47 |
+
minopen,
|
48 |
+
maxopen
|
49 |
+
)
|
50 |
+
|
51 |
+
@_set_div.register(Basic, Basic)
|
52 |
+
def _(x, y):
|
53 |
+
return None
|
54 |
+
|
55 |
+
@_set_div.register(Expr, Expr)
|
56 |
+
def _(x, y):
|
57 |
+
return x/y
|
58 |
+
|
59 |
+
@_set_div.register(Set, Set)
|
60 |
+
def _(x, y):
|
61 |
+
return None
|
62 |
+
|
63 |
+
@_set_div.register(Interval, Interval)
|
64 |
+
def _(x, y):
|
65 |
+
"""
|
66 |
+
Divisions in interval arithmetic
|
67 |
+
https://en.wikipedia.org/wiki/Interval_arithmetic
|
68 |
+
"""
|
69 |
+
if (y.start*y.end).is_negative:
|
70 |
+
return Interval(-oo, oo)
|
71 |
+
if y.start == 0:
|
72 |
+
s2 = oo
|
73 |
+
else:
|
74 |
+
s2 = 1/y.start
|
75 |
+
if y.end == 0:
|
76 |
+
s1 = -oo
|
77 |
+
else:
|
78 |
+
s1 = 1/y.end
|
79 |
+
return set_mul(x, Interval(s1, s2, y.right_open, y.left_open))
|
env-llmeval/lib/python3.10/site-packages/sympy/sets/handlers/power.py
ADDED
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core import Basic, Expr
|
2 |
+
from sympy.core.function import Lambda
|
3 |
+
from sympy.core.numbers import oo, Infinity, NegativeInfinity, Zero, Integer
|
4 |
+
from sympy.core.singleton import S
|
5 |
+
from sympy.core.symbol import symbols
|
6 |
+
from sympy.functions.elementary.miscellaneous import (Max, Min)
|
7 |
+
from sympy.sets.fancysets import ImageSet
|
8 |
+
from sympy.sets.setexpr import set_div
|
9 |
+
from sympy.sets.sets import Set, Interval, FiniteSet, Union
|
10 |
+
from sympy.multipledispatch import Dispatcher
|
11 |
+
|
12 |
+
|
13 |
+
_x, _y = symbols("x y")
|
14 |
+
|
15 |
+
|
16 |
+
_set_pow = Dispatcher('_set_pow')
|
17 |
+
|
18 |
+
|
19 |
+
@_set_pow.register(Basic, Basic)
|
20 |
+
def _(x, y):
|
21 |
+
return None
|
22 |
+
|
23 |
+
@_set_pow.register(Set, Set)
|
24 |
+
def _(x, y):
|
25 |
+
return ImageSet(Lambda((_x, _y), (_x ** _y)), x, y)
|
26 |
+
|
27 |
+
@_set_pow.register(Expr, Expr)
|
28 |
+
def _(x, y):
|
29 |
+
return x**y
|
30 |
+
|
31 |
+
@_set_pow.register(Interval, Zero)
|
32 |
+
def _(x, z):
|
33 |
+
return FiniteSet(S.One)
|
34 |
+
|
35 |
+
@_set_pow.register(Interval, Integer)
|
36 |
+
def _(x, exponent):
|
37 |
+
"""
|
38 |
+
Powers in interval arithmetic
|
39 |
+
https://en.wikipedia.org/wiki/Interval_arithmetic
|
40 |
+
"""
|
41 |
+
s1 = x.start**exponent
|
42 |
+
s2 = x.end**exponent
|
43 |
+
if ((s2 > s1) if exponent > 0 else (x.end > -x.start)) == True:
|
44 |
+
left_open = x.left_open
|
45 |
+
right_open = x.right_open
|
46 |
+
# TODO: handle unevaluated condition.
|
47 |
+
sleft = s2
|
48 |
+
else:
|
49 |
+
# TODO: `s2 > s1` could be unevaluated.
|
50 |
+
left_open = x.right_open
|
51 |
+
right_open = x.left_open
|
52 |
+
sleft = s1
|
53 |
+
|
54 |
+
if x.start.is_positive:
|
55 |
+
return Interval(
|
56 |
+
Min(s1, s2),
|
57 |
+
Max(s1, s2), left_open, right_open)
|
58 |
+
elif x.end.is_negative:
|
59 |
+
return Interval(
|
60 |
+
Min(s1, s2),
|
61 |
+
Max(s1, s2), left_open, right_open)
|
62 |
+
|
63 |
+
# Case where x.start < 0 and x.end > 0:
|
64 |
+
if exponent.is_odd:
|
65 |
+
if exponent.is_negative:
|
66 |
+
if x.start.is_zero:
|
67 |
+
return Interval(s2, oo, x.right_open)
|
68 |
+
if x.end.is_zero:
|
69 |
+
return Interval(-oo, s1, True, x.left_open)
|
70 |
+
return Union(Interval(-oo, s1, True, x.left_open), Interval(s2, oo, x.right_open))
|
71 |
+
else:
|
72 |
+
return Interval(s1, s2, x.left_open, x.right_open)
|
73 |
+
elif exponent.is_even:
|
74 |
+
if exponent.is_negative:
|
75 |
+
if x.start.is_zero:
|
76 |
+
return Interval(s2, oo, x.right_open)
|
77 |
+
if x.end.is_zero:
|
78 |
+
return Interval(s1, oo, x.left_open)
|
79 |
+
return Interval(0, oo)
|
80 |
+
else:
|
81 |
+
return Interval(S.Zero, sleft, S.Zero not in x, left_open)
|
82 |
+
|
83 |
+
@_set_pow.register(Interval, Infinity)
|
84 |
+
def _(b, e):
|
85 |
+
# TODO: add logic for open intervals?
|
86 |
+
if b.start.is_nonnegative:
|
87 |
+
if b.end < 1:
|
88 |
+
return FiniteSet(S.Zero)
|
89 |
+
if b.start > 1:
|
90 |
+
return FiniteSet(S.Infinity)
|
91 |
+
return Interval(0, oo)
|
92 |
+
elif b.end.is_negative:
|
93 |
+
if b.start > -1:
|
94 |
+
return FiniteSet(S.Zero)
|
95 |
+
if b.end < -1:
|
96 |
+
return FiniteSet(-oo, oo)
|
97 |
+
return Interval(-oo, oo)
|
98 |
+
else:
|
99 |
+
if b.start > -1:
|
100 |
+
if b.end < 1:
|
101 |
+
return FiniteSet(S.Zero)
|
102 |
+
return Interval(0, oo)
|
103 |
+
return Interval(-oo, oo)
|
104 |
+
|
105 |
+
@_set_pow.register(Interval, NegativeInfinity)
|
106 |
+
def _(b, e):
|
107 |
+
return _set_pow(set_div(S.One, b), oo)
|
env-llmeval/lib/python3.10/site-packages/sympy/sets/handlers/union.py
ADDED
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.singleton import S
|
2 |
+
from sympy.core.sympify import sympify
|
3 |
+
from sympy.functions.elementary.miscellaneous import Min, Max
|
4 |
+
from sympy.sets.sets import (EmptySet, FiniteSet, Intersection,
|
5 |
+
Interval, ProductSet, Set, Union, UniversalSet)
|
6 |
+
from sympy.sets.fancysets import (ComplexRegion, Naturals, Naturals0,
|
7 |
+
Integers, Rationals, Reals)
|
8 |
+
from sympy.multipledispatch import Dispatcher
|
9 |
+
|
10 |
+
|
11 |
+
union_sets = Dispatcher('union_sets')
|
12 |
+
|
13 |
+
|
14 |
+
@union_sets.register(Naturals0, Naturals)
|
15 |
+
def _(a, b):
|
16 |
+
return a
|
17 |
+
|
18 |
+
@union_sets.register(Rationals, Naturals)
|
19 |
+
def _(a, b):
|
20 |
+
return a
|
21 |
+
|
22 |
+
@union_sets.register(Rationals, Naturals0)
|
23 |
+
def _(a, b):
|
24 |
+
return a
|
25 |
+
|
26 |
+
@union_sets.register(Reals, Naturals)
|
27 |
+
def _(a, b):
|
28 |
+
return a
|
29 |
+
|
30 |
+
@union_sets.register(Reals, Naturals0)
|
31 |
+
def _(a, b):
|
32 |
+
return a
|
33 |
+
|
34 |
+
@union_sets.register(Reals, Rationals)
|
35 |
+
def _(a, b):
|
36 |
+
return a
|
37 |
+
|
38 |
+
@union_sets.register(Integers, Set)
|
39 |
+
def _(a, b):
|
40 |
+
intersect = Intersection(a, b)
|
41 |
+
if intersect == a:
|
42 |
+
return b
|
43 |
+
elif intersect == b:
|
44 |
+
return a
|
45 |
+
|
46 |
+
@union_sets.register(ComplexRegion, Set)
|
47 |
+
def _(a, b):
|
48 |
+
if b.is_subset(S.Reals):
|
49 |
+
# treat a subset of reals as a complex region
|
50 |
+
b = ComplexRegion.from_real(b)
|
51 |
+
|
52 |
+
if b.is_ComplexRegion:
|
53 |
+
# a in rectangular form
|
54 |
+
if (not a.polar) and (not b.polar):
|
55 |
+
return ComplexRegion(Union(a.sets, b.sets))
|
56 |
+
# a in polar form
|
57 |
+
elif a.polar and b.polar:
|
58 |
+
return ComplexRegion(Union(a.sets, b.sets), polar=True)
|
59 |
+
return None
|
60 |
+
|
61 |
+
@union_sets.register(EmptySet, Set)
|
62 |
+
def _(a, b):
|
63 |
+
return b
|
64 |
+
|
65 |
+
|
66 |
+
@union_sets.register(UniversalSet, Set)
|
67 |
+
def _(a, b):
|
68 |
+
return a
|
69 |
+
|
70 |
+
@union_sets.register(ProductSet, ProductSet)
|
71 |
+
def _(a, b):
|
72 |
+
if b.is_subset(a):
|
73 |
+
return a
|
74 |
+
if len(b.sets) != len(a.sets):
|
75 |
+
return None
|
76 |
+
if len(a.sets) == 2:
|
77 |
+
a1, a2 = a.sets
|
78 |
+
b1, b2 = b.sets
|
79 |
+
if a1 == b1:
|
80 |
+
return a1 * Union(a2, b2)
|
81 |
+
if a2 == b2:
|
82 |
+
return Union(a1, b1) * a2
|
83 |
+
return None
|
84 |
+
|
85 |
+
@union_sets.register(ProductSet, Set)
|
86 |
+
def _(a, b):
|
87 |
+
if b.is_subset(a):
|
88 |
+
return a
|
89 |
+
return None
|
90 |
+
|
91 |
+
@union_sets.register(Interval, Interval)
|
92 |
+
def _(a, b):
|
93 |
+
if a._is_comparable(b):
|
94 |
+
# Non-overlapping intervals
|
95 |
+
end = Min(a.end, b.end)
|
96 |
+
start = Max(a.start, b.start)
|
97 |
+
if (end < start or
|
98 |
+
(end == start and (end not in a and end not in b))):
|
99 |
+
return None
|
100 |
+
else:
|
101 |
+
start = Min(a.start, b.start)
|
102 |
+
end = Max(a.end, b.end)
|
103 |
+
|
104 |
+
left_open = ((a.start != start or a.left_open) and
|
105 |
+
(b.start != start or b.left_open))
|
106 |
+
right_open = ((a.end != end or a.right_open) and
|
107 |
+
(b.end != end or b.right_open))
|
108 |
+
return Interval(start, end, left_open, right_open)
|
109 |
+
|
110 |
+
@union_sets.register(Interval, UniversalSet)
|
111 |
+
def _(a, b):
|
112 |
+
return S.UniversalSet
|
113 |
+
|
114 |
+
@union_sets.register(Interval, Set)
|
115 |
+
def _(a, b):
|
116 |
+
# If I have open end points and these endpoints are contained in b
|
117 |
+
# But only in case, when endpoints are finite. Because
|
118 |
+
# interval does not contain oo or -oo.
|
119 |
+
open_left_in_b_and_finite = (a.left_open and
|
120 |
+
sympify(b.contains(a.start)) is S.true and
|
121 |
+
a.start.is_finite)
|
122 |
+
open_right_in_b_and_finite = (a.right_open and
|
123 |
+
sympify(b.contains(a.end)) is S.true and
|
124 |
+
a.end.is_finite)
|
125 |
+
if open_left_in_b_and_finite or open_right_in_b_and_finite:
|
126 |
+
# Fill in my end points and return
|
127 |
+
open_left = a.left_open and a.start not in b
|
128 |
+
open_right = a.right_open and a.end not in b
|
129 |
+
new_a = Interval(a.start, a.end, open_left, open_right)
|
130 |
+
return {new_a, b}
|
131 |
+
return None
|
132 |
+
|
133 |
+
@union_sets.register(FiniteSet, FiniteSet)
|
134 |
+
def _(a, b):
|
135 |
+
return FiniteSet(*(a._elements | b._elements))
|
136 |
+
|
137 |
+
@union_sets.register(FiniteSet, Set)
|
138 |
+
def _(a, b):
|
139 |
+
# If `b` set contains one of my elements, remove it from `a`
|
140 |
+
if any(b.contains(x) == True for x in a):
|
141 |
+
return {
|
142 |
+
FiniteSet(*[x for x in a if b.contains(x) != True]), b}
|
143 |
+
return None
|
144 |
+
|
145 |
+
@union_sets.register(Set, Set)
|
146 |
+
def _(a, b):
|
147 |
+
return None
|
env-llmeval/lib/python3.10/site-packages/sympy/sets/ordinals.py
ADDED
@@ -0,0 +1,282 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
+
"""
|
7 |
+
Represents ordinal exponential and multiplication terms one of the
|
8 |
+
building blocks of the :class:`Ordinal` class.
|
9 |
+
In ``OmegaPower(a, b)``, ``a`` represents exponent and ``b`` represents multiplicity.
|
10 |
+
"""
|
11 |
+
def __new__(cls, a, b):
|
12 |
+
if isinstance(b, int):
|
13 |
+
b = Integer(b)
|
14 |
+
if not isinstance(b, Integer) or b <= 0:
|
15 |
+
raise TypeError("multiplicity must be a positive integer")
|
16 |
+
|
17 |
+
if not isinstance(a, Ordinal):
|
18 |
+
a = Ordinal.convert(a)
|
19 |
+
|
20 |
+
return Basic.__new__(cls, a, b)
|
21 |
+
|
22 |
+
@property
|
23 |
+
def exp(self):
|
24 |
+
return self.args[0]
|
25 |
+
|
26 |
+
@property
|
27 |
+
def mult(self):
|
28 |
+
return self.args[1]
|
29 |
+
|
30 |
+
def _compare_term(self, other, op):
|
31 |
+
if self.exp == other.exp:
|
32 |
+
return op(self.mult, other.mult)
|
33 |
+
else:
|
34 |
+
return op(self.exp, other.exp)
|
35 |
+
|
36 |
+
def __eq__(self, other):
|
37 |
+
if not isinstance(other, OmegaPower):
|
38 |
+
try:
|
39 |
+
other = OmegaPower(0, other)
|
40 |
+
except TypeError:
|
41 |
+
return NotImplemented
|
42 |
+
return self.args == other.args
|
43 |
+
|
44 |
+
def __hash__(self):
|
45 |
+
return Basic.__hash__(self)
|
46 |
+
|
47 |
+
def __lt__(self, other):
|
48 |
+
if not isinstance(other, OmegaPower):
|
49 |
+
try:
|
50 |
+
other = OmegaPower(0, other)
|
51 |
+
except TypeError:
|
52 |
+
return NotImplemented
|
53 |
+
return self._compare_term(other, operator.lt)
|
54 |
+
|
55 |
+
|
56 |
+
class Ordinal(Basic):
|
57 |
+
"""
|
58 |
+
Represents ordinals in Cantor normal form.
|
59 |
+
|
60 |
+
Internally, this class is just a list of instances of OmegaPower.
|
61 |
+
|
62 |
+
Examples
|
63 |
+
========
|
64 |
+
>>> from sympy import Ordinal, OmegaPower
|
65 |
+
>>> from sympy.sets.ordinals import omega
|
66 |
+
>>> w = omega
|
67 |
+
>>> w.is_limit_ordinal
|
68 |
+
True
|
69 |
+
>>> Ordinal(OmegaPower(w + 1, 1), OmegaPower(3, 2))
|
70 |
+
w**(w + 1) + w**3*2
|
71 |
+
>>> 3 + w
|
72 |
+
w
|
73 |
+
>>> (w + 1) * w
|
74 |
+
w**2
|
75 |
+
|
76 |
+
References
|
77 |
+
==========
|
78 |
+
|
79 |
+
.. [1] https://en.wikipedia.org/wiki/Ordinal_arithmetic
|
80 |
+
"""
|
81 |
+
def __new__(cls, *terms):
|
82 |
+
obj = super().__new__(cls, *terms)
|
83 |
+
powers = [i.exp for i in obj.args]
|
84 |
+
if not all(powers[i] >= powers[i+1] for i in range(len(powers) - 1)):
|
85 |
+
raise ValueError("powers must be in decreasing order")
|
86 |
+
return obj
|
87 |
+
|
88 |
+
@property
|
89 |
+
def terms(self):
|
90 |
+
return self.args
|
91 |
+
|
92 |
+
@property
|
93 |
+
def leading_term(self):
|
94 |
+
if self == ord0:
|
95 |
+
raise ValueError("ordinal zero has no leading term")
|
96 |
+
return self.terms[0]
|
97 |
+
|
98 |
+
@property
|
99 |
+
def trailing_term(self):
|
100 |
+
if self == ord0:
|
101 |
+
raise ValueError("ordinal zero has no trailing term")
|
102 |
+
return self.terms[-1]
|
103 |
+
|
104 |
+
@property
|
105 |
+
def is_successor_ordinal(self):
|
106 |
+
try:
|
107 |
+
return self.trailing_term.exp == ord0
|
108 |
+
except ValueError:
|
109 |
+
return False
|
110 |
+
|
111 |
+
@property
|
112 |
+
def is_limit_ordinal(self):
|
113 |
+
try:
|
114 |
+
return not self.trailing_term.exp == ord0
|
115 |
+
except ValueError:
|
116 |
+
return False
|
117 |
+
|
118 |
+
@property
|
119 |
+
def degree(self):
|
120 |
+
return self.leading_term.exp
|
121 |
+
|
122 |
+
@classmethod
|
123 |
+
def convert(cls, integer_value):
|
124 |
+
if integer_value == 0:
|
125 |
+
return ord0
|
126 |
+
return Ordinal(OmegaPower(0, integer_value))
|
127 |
+
|
128 |
+
def __eq__(self, other):
|
129 |
+
if not isinstance(other, Ordinal):
|
130 |
+
try:
|
131 |
+
other = Ordinal.convert(other)
|
132 |
+
except TypeError:
|
133 |
+
return NotImplemented
|
134 |
+
return self.terms == other.terms
|
135 |
+
|
136 |
+
def __hash__(self):
|
137 |
+
return hash(self.args)
|
138 |
+
|
139 |
+
def __lt__(self, other):
|
140 |
+
if not isinstance(other, Ordinal):
|
141 |
+
try:
|
142 |
+
other = Ordinal.convert(other)
|
143 |
+
except TypeError:
|
144 |
+
return NotImplemented
|
145 |
+
for term_self, term_other in zip(self.terms, other.terms):
|
146 |
+
if term_self != term_other:
|
147 |
+
return term_self < term_other
|
148 |
+
return len(self.terms) < len(other.terms)
|
149 |
+
|
150 |
+
def __le__(self, other):
|
151 |
+
return (self == other or self < other)
|
152 |
+
|
153 |
+
def __gt__(self, other):
|
154 |
+
return not self <= other
|
155 |
+
|
156 |
+
def __ge__(self, other):
|
157 |
+
return not self < other
|
158 |
+
|
159 |
+
def __str__(self):
|
160 |
+
net_str = ""
|
161 |
+
plus_count = 0
|
162 |
+
if self == ord0:
|
163 |
+
return 'ord0'
|
164 |
+
for i in self.terms:
|
165 |
+
if plus_count:
|
166 |
+
net_str += " + "
|
167 |
+
|
168 |
+
if i.exp == ord0:
|
169 |
+
net_str += str(i.mult)
|
170 |
+
elif i.exp == 1:
|
171 |
+
net_str += 'w'
|
172 |
+
elif len(i.exp.terms) > 1 or i.exp.is_limit_ordinal:
|
173 |
+
net_str += 'w**(%s)'%i.exp
|
174 |
+
else:
|
175 |
+
net_str += 'w**%s'%i.exp
|
176 |
+
|
177 |
+
if not i.mult == 1 and not i.exp == ord0:
|
178 |
+
net_str += '*%s'%i.mult
|
179 |
+
|
180 |
+
plus_count += 1
|
181 |
+
return(net_str)
|
182 |
+
|
183 |
+
__repr__ = __str__
|
184 |
+
|
185 |
+
def __add__(self, other):
|
186 |
+
if not isinstance(other, Ordinal):
|
187 |
+
try:
|
188 |
+
other = Ordinal.convert(other)
|
189 |
+
except TypeError:
|
190 |
+
return NotImplemented
|
191 |
+
if other == ord0:
|
192 |
+
return self
|
193 |
+
a_terms = list(self.terms)
|
194 |
+
b_terms = list(other.terms)
|
195 |
+
r = len(a_terms) - 1
|
196 |
+
b_exp = other.degree
|
197 |
+
while r >= 0 and a_terms[r].exp < b_exp:
|
198 |
+
r -= 1
|
199 |
+
if r < 0:
|
200 |
+
terms = b_terms
|
201 |
+
elif a_terms[r].exp == b_exp:
|
202 |
+
sum_term = OmegaPower(b_exp, a_terms[r].mult + other.leading_term.mult)
|
203 |
+
terms = a_terms[:r] + [sum_term] + b_terms[1:]
|
204 |
+
else:
|
205 |
+
terms = a_terms[:r+1] + b_terms
|
206 |
+
return Ordinal(*terms)
|
207 |
+
|
208 |
+
def __radd__(self, other):
|
209 |
+
if not isinstance(other, Ordinal):
|
210 |
+
try:
|
211 |
+
other = Ordinal.convert(other)
|
212 |
+
except TypeError:
|
213 |
+
return NotImplemented
|
214 |
+
return other + self
|
215 |
+
|
216 |
+
def __mul__(self, other):
|
217 |
+
if not isinstance(other, Ordinal):
|
218 |
+
try:
|
219 |
+
other = Ordinal.convert(other)
|
220 |
+
except TypeError:
|
221 |
+
return NotImplemented
|
222 |
+
if ord0 in (self, other):
|
223 |
+
return ord0
|
224 |
+
a_exp = self.degree
|
225 |
+
a_mult = self.leading_term.mult
|
226 |
+
summation = []
|
227 |
+
if other.is_limit_ordinal:
|
228 |
+
for arg in other.terms:
|
229 |
+
summation.append(OmegaPower(a_exp + arg.exp, arg.mult))
|
230 |
+
|
231 |
+
else:
|
232 |
+
for arg in other.terms[:-1]:
|
233 |
+
summation.append(OmegaPower(a_exp + arg.exp, arg.mult))
|
234 |
+
b_mult = other.trailing_term.mult
|
235 |
+
summation.append(OmegaPower(a_exp, a_mult*b_mult))
|
236 |
+
summation += list(self.terms[1:])
|
237 |
+
return Ordinal(*summation)
|
238 |
+
|
239 |
+
def __rmul__(self, other):
|
240 |
+
if not isinstance(other, Ordinal):
|
241 |
+
try:
|
242 |
+
other = Ordinal.convert(other)
|
243 |
+
except TypeError:
|
244 |
+
return NotImplemented
|
245 |
+
return other * self
|
246 |
+
|
247 |
+
def __pow__(self, other):
|
248 |
+
if not self == omega:
|
249 |
+
return NotImplemented
|
250 |
+
return Ordinal(OmegaPower(other, 1))
|
251 |
+
|
252 |
+
|
253 |
+
class OrdinalZero(Ordinal):
|
254 |
+
"""The ordinal zero.
|
255 |
+
|
256 |
+
OrdinalZero can be imported as ``ord0``.
|
257 |
+
"""
|
258 |
+
pass
|
259 |
+
|
260 |
+
|
261 |
+
class OrdinalOmega(Ordinal):
|
262 |
+
"""The ordinal omega which forms the base of all ordinals in cantor normal form.
|
263 |
+
|
264 |
+
OrdinalOmega can be imported as ``omega``.
|
265 |
+
|
266 |
+
Examples
|
267 |
+
========
|
268 |
+
|
269 |
+
>>> from sympy.sets.ordinals import omega
|
270 |
+
>>> omega + omega
|
271 |
+
w*2
|
272 |
+
"""
|
273 |
+
def __new__(cls):
|
274 |
+
return Ordinal.__new__(cls)
|
275 |
+
|
276 |
+
@property
|
277 |
+
def terms(self):
|
278 |
+
return (OmegaPower(1, 1),)
|
279 |
+
|
280 |
+
|
281 |
+
ord0 = OrdinalZero()
|
282 |
+
omega = OrdinalOmega()
|
env-llmeval/lib/python3.10/site-packages/sympy/sets/powerset.py
ADDED
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.decorators import _sympifyit
|
2 |
+
from sympy.core.parameters import global_parameters
|
3 |
+
from sympy.core.logic import fuzzy_bool
|
4 |
+
from sympy.core.singleton import S
|
5 |
+
from sympy.core.sympify import _sympify
|
6 |
+
|
7 |
+
from .sets import Set, FiniteSet, SetKind
|
8 |
+
|
9 |
+
|
10 |
+
class PowerSet(Set):
|
11 |
+
r"""A symbolic object representing a power set.
|
12 |
+
|
13 |
+
Parameters
|
14 |
+
==========
|
15 |
+
|
16 |
+
arg : Set
|
17 |
+
The set to take power of.
|
18 |
+
|
19 |
+
evaluate : bool
|
20 |
+
The flag to control evaluation.
|
21 |
+
|
22 |
+
If the evaluation is disabled for finite sets, it can take
|
23 |
+
advantage of using subset test as a membership test.
|
24 |
+
|
25 |
+
Notes
|
26 |
+
=====
|
27 |
+
|
28 |
+
Power set `\mathcal{P}(S)` is defined as a set containing all the
|
29 |
+
subsets of `S`.
|
30 |
+
|
31 |
+
If the set `S` is a finite set, its power set would have
|
32 |
+
`2^{\left| S \right|}` elements, where `\left| S \right|` denotes
|
33 |
+
the cardinality of `S`.
|
34 |
+
|
35 |
+
Examples
|
36 |
+
========
|
37 |
+
|
38 |
+
>>> from sympy import PowerSet, S, FiniteSet
|
39 |
+
|
40 |
+
A power set of a finite set:
|
41 |
+
|
42 |
+
>>> PowerSet(FiniteSet(1, 2, 3))
|
43 |
+
PowerSet({1, 2, 3})
|
44 |
+
|
45 |
+
A power set of an empty set:
|
46 |
+
|
47 |
+
>>> PowerSet(S.EmptySet)
|
48 |
+
PowerSet(EmptySet)
|
49 |
+
>>> PowerSet(PowerSet(S.EmptySet))
|
50 |
+
PowerSet(PowerSet(EmptySet))
|
51 |
+
|
52 |
+
A power set of an infinite set:
|
53 |
+
|
54 |
+
>>> PowerSet(S.Reals)
|
55 |
+
PowerSet(Reals)
|
56 |
+
|
57 |
+
Evaluating the power set of a finite set to its explicit form:
|
58 |
+
|
59 |
+
>>> PowerSet(FiniteSet(1, 2, 3)).rewrite(FiniteSet)
|
60 |
+
FiniteSet(EmptySet, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3})
|
61 |
+
|
62 |
+
References
|
63 |
+
==========
|
64 |
+
|
65 |
+
.. [1] https://en.wikipedia.org/wiki/Power_set
|
66 |
+
|
67 |
+
.. [2] https://en.wikipedia.org/wiki/Axiom_of_power_set
|
68 |
+
"""
|
69 |
+
def __new__(cls, arg, evaluate=None):
|
70 |
+
if evaluate is None:
|
71 |
+
evaluate=global_parameters.evaluate
|
72 |
+
|
73 |
+
arg = _sympify(arg)
|
74 |
+
|
75 |
+
if not isinstance(arg, Set):
|
76 |
+
raise ValueError('{} must be a set.'.format(arg))
|
77 |
+
|
78 |
+
return super().__new__(cls, arg)
|
79 |
+
|
80 |
+
@property
|
81 |
+
def arg(self):
|
82 |
+
return self.args[0]
|
83 |
+
|
84 |
+
def _eval_rewrite_as_FiniteSet(self, *args, **kwargs):
|
85 |
+
arg = self.arg
|
86 |
+
if arg.is_FiniteSet:
|
87 |
+
return arg.powerset()
|
88 |
+
return None
|
89 |
+
|
90 |
+
@_sympifyit('other', NotImplemented)
|
91 |
+
def _contains(self, other):
|
92 |
+
if not isinstance(other, Set):
|
93 |
+
return None
|
94 |
+
|
95 |
+
return fuzzy_bool(self.arg.is_superset(other))
|
96 |
+
|
97 |
+
def _eval_is_subset(self, other):
|
98 |
+
if isinstance(other, PowerSet):
|
99 |
+
return self.arg.is_subset(other.arg)
|
100 |
+
|
101 |
+
def __len__(self):
|
102 |
+
return 2 ** len(self.arg)
|
103 |
+
|
104 |
+
def __iter__(self):
|
105 |
+
found = [S.EmptySet]
|
106 |
+
yield S.EmptySet
|
107 |
+
|
108 |
+
for x in self.arg:
|
109 |
+
temp = []
|
110 |
+
x = FiniteSet(x)
|
111 |
+
for y in found:
|
112 |
+
new = x + y
|
113 |
+
yield new
|
114 |
+
temp.append(new)
|
115 |
+
found.extend(temp)
|
116 |
+
|
117 |
+
@property
|
118 |
+
def kind(self):
|
119 |
+
return SetKind(self.arg.kind)
|
env-llmeval/lib/python3.10/site-packages/sympy/sets/setexpr.py
ADDED
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core import Expr
|
2 |
+
from sympy.core.decorators import call_highest_priority, _sympifyit
|
3 |
+
from .fancysets import ImageSet
|
4 |
+
from .sets import set_add, set_sub, set_mul, set_div, set_pow, set_function
|
5 |
+
|
6 |
+
|
7 |
+
class SetExpr(Expr):
|
8 |
+
"""An expression that can take on values of a set.
|
9 |
+
|
10 |
+
Examples
|
11 |
+
========
|
12 |
+
|
13 |
+
>>> from sympy import Interval, FiniteSet
|
14 |
+
>>> from sympy.sets.setexpr import SetExpr
|
15 |
+
|
16 |
+
>>> a = SetExpr(Interval(0, 5))
|
17 |
+
>>> b = SetExpr(FiniteSet(1, 10))
|
18 |
+
>>> (a + b).set
|
19 |
+
Union(Interval(1, 6), Interval(10, 15))
|
20 |
+
>>> (2*a + b).set
|
21 |
+
Interval(1, 20)
|
22 |
+
"""
|
23 |
+
_op_priority = 11.0
|
24 |
+
|
25 |
+
def __new__(cls, setarg):
|
26 |
+
return Expr.__new__(cls, setarg)
|
27 |
+
|
28 |
+
set = property(lambda self: self.args[0])
|
29 |
+
|
30 |
+
def _latex(self, printer):
|
31 |
+
return r"SetExpr\left({}\right)".format(printer._print(self.set))
|
32 |
+
|
33 |
+
@_sympifyit('other', NotImplemented)
|
34 |
+
@call_highest_priority('__radd__')
|
35 |
+
def __add__(self, other):
|
36 |
+
return _setexpr_apply_operation(set_add, self, other)
|
37 |
+
|
38 |
+
@_sympifyit('other', NotImplemented)
|
39 |
+
@call_highest_priority('__add__')
|
40 |
+
def __radd__(self, other):
|
41 |
+
return _setexpr_apply_operation(set_add, other, self)
|
42 |
+
|
43 |
+
@_sympifyit('other', NotImplemented)
|
44 |
+
@call_highest_priority('__rmul__')
|
45 |
+
def __mul__(self, other):
|
46 |
+
return _setexpr_apply_operation(set_mul, self, other)
|
47 |
+
|
48 |
+
@_sympifyit('other', NotImplemented)
|
49 |
+
@call_highest_priority('__mul__')
|
50 |
+
def __rmul__(self, other):
|
51 |
+
return _setexpr_apply_operation(set_mul, other, self)
|
52 |
+
|
53 |
+
@_sympifyit('other', NotImplemented)
|
54 |
+
@call_highest_priority('__rsub__')
|
55 |
+
def __sub__(self, other):
|
56 |
+
return _setexpr_apply_operation(set_sub, self, other)
|
57 |
+
|
58 |
+
@_sympifyit('other', NotImplemented)
|
59 |
+
@call_highest_priority('__sub__')
|
60 |
+
def __rsub__(self, other):
|
61 |
+
return _setexpr_apply_operation(set_sub, other, self)
|
62 |
+
|
63 |
+
@_sympifyit('other', NotImplemented)
|
64 |
+
@call_highest_priority('__rpow__')
|
65 |
+
def __pow__(self, other):
|
66 |
+
return _setexpr_apply_operation(set_pow, self, other)
|
67 |
+
|
68 |
+
@_sympifyit('other', NotImplemented)
|
69 |
+
@call_highest_priority('__pow__')
|
70 |
+
def __rpow__(self, other):
|
71 |
+
return _setexpr_apply_operation(set_pow, other, self)
|
72 |
+
|
73 |
+
@_sympifyit('other', NotImplemented)
|
74 |
+
@call_highest_priority('__rtruediv__')
|
75 |
+
def __truediv__(self, other):
|
76 |
+
return _setexpr_apply_operation(set_div, self, other)
|
77 |
+
|
78 |
+
@_sympifyit('other', NotImplemented)
|
79 |
+
@call_highest_priority('__truediv__')
|
80 |
+
def __rtruediv__(self, other):
|
81 |
+
return _setexpr_apply_operation(set_div, other, self)
|
82 |
+
|
83 |
+
def _eval_func(self, func):
|
84 |
+
# TODO: this could be implemented straight into `imageset`:
|
85 |
+
res = set_function(func, self.set)
|
86 |
+
if res is None:
|
87 |
+
return SetExpr(ImageSet(func, self.set))
|
88 |
+
return SetExpr(res)
|
89 |
+
|
90 |
+
|
91 |
+
def _setexpr_apply_operation(op, x, y):
|
92 |
+
if isinstance(x, SetExpr):
|
93 |
+
x = x.set
|
94 |
+
if isinstance(y, SetExpr):
|
95 |
+
y = y.set
|
96 |
+
out = op(x, y)
|
97 |
+
return SetExpr(out)
|
env-llmeval/lib/python3.10/site-packages/sympy/sets/sets.py
ADDED
@@ -0,0 +1,2749 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Any, Callable
|
2 |
+
from functools import reduce
|
3 |
+
from collections import defaultdict
|
4 |
+
import inspect
|
5 |
+
|
6 |
+
from sympy.core.kind import Kind, UndefinedKind, NumberKind
|
7 |
+
from sympy.core.basic import Basic
|
8 |
+
from sympy.core.containers import Tuple, TupleKind
|
9 |
+
from sympy.core.decorators import sympify_method_args, sympify_return
|
10 |
+
from sympy.core.evalf import EvalfMixin
|
11 |
+
from sympy.core.expr import Expr
|
12 |
+
from sympy.core.function import Lambda
|
13 |
+
from sympy.core.logic import (FuzzyBool, fuzzy_bool, fuzzy_or, fuzzy_and,
|
14 |
+
fuzzy_not)
|
15 |
+
from sympy.core.numbers import Float, Integer
|
16 |
+
from sympy.core.operations import LatticeOp
|
17 |
+
from sympy.core.parameters import global_parameters
|
18 |
+
from sympy.core.relational import Eq, Ne, is_lt
|
19 |
+
from sympy.core.singleton import Singleton, S
|
20 |
+
from sympy.core.sorting import ordered
|
21 |
+
from sympy.core.symbol import symbols, Symbol, Dummy, uniquely_named_symbol
|
22 |
+
from sympy.core.sympify import _sympify, sympify, _sympy_converter
|
23 |
+
from sympy.functions.elementary.exponential import exp, log
|
24 |
+
from sympy.functions.elementary.miscellaneous import Max, Min
|
25 |
+
from sympy.logic.boolalg import And, Or, Not, Xor, true, false
|
26 |
+
from sympy.utilities.decorator import deprecated
|
27 |
+
from sympy.utilities.exceptions import sympy_deprecation_warning
|
28 |
+
from sympy.utilities.iterables import (iproduct, sift, roundrobin, iterable,
|
29 |
+
subsets)
|
30 |
+
from sympy.utilities.misc import func_name, filldedent
|
31 |
+
|
32 |
+
from mpmath import mpi, mpf
|
33 |
+
|
34 |
+
from mpmath.libmp.libmpf import prec_to_dps
|
35 |
+
|
36 |
+
|
37 |
+
tfn = defaultdict(lambda: None, {
|
38 |
+
True: S.true,
|
39 |
+
S.true: S.true,
|
40 |
+
False: S.false,
|
41 |
+
S.false: S.false})
|
42 |
+
|
43 |
+
|
44 |
+
@sympify_method_args
|
45 |
+
class Set(Basic, EvalfMixin):
|
46 |
+
"""
|
47 |
+
The base class for any kind of set.
|
48 |
+
|
49 |
+
Explanation
|
50 |
+
===========
|
51 |
+
|
52 |
+
This is not meant to be used directly as a container of items. It does not
|
53 |
+
behave like the builtin ``set``; see :class:`FiniteSet` for that.
|
54 |
+
|
55 |
+
Real intervals are represented by the :class:`Interval` class and unions of
|
56 |
+
sets by the :class:`Union` class. The empty set is represented by the
|
57 |
+
:class:`EmptySet` class and available as a singleton as ``S.EmptySet``.
|
58 |
+
"""
|
59 |
+
|
60 |
+
__slots__ = ()
|
61 |
+
|
62 |
+
is_number = False
|
63 |
+
is_iterable = False
|
64 |
+
is_interval = False
|
65 |
+
|
66 |
+
is_FiniteSet = False
|
67 |
+
is_Interval = False
|
68 |
+
is_ProductSet = False
|
69 |
+
is_Union = False
|
70 |
+
is_Intersection: FuzzyBool = None
|
71 |
+
is_UniversalSet: FuzzyBool = None
|
72 |
+
is_Complement: FuzzyBool = None
|
73 |
+
is_ComplexRegion = False
|
74 |
+
|
75 |
+
is_empty: FuzzyBool = None
|
76 |
+
is_finite_set: FuzzyBool = None
|
77 |
+
|
78 |
+
@property # type: ignore
|
79 |
+
@deprecated(
|
80 |
+
"""
|
81 |
+
The is_EmptySet attribute of Set objects is deprecated.
|
82 |
+
Use 's is S.EmptySet" or 's.is_empty' instead.
|
83 |
+
""",
|
84 |
+
deprecated_since_version="1.5",
|
85 |
+
active_deprecations_target="deprecated-is-emptyset",
|
86 |
+
)
|
87 |
+
def is_EmptySet(self):
|
88 |
+
return None
|
89 |
+
|
90 |
+
@staticmethod
|
91 |
+
def _infimum_key(expr):
|
92 |
+
"""
|
93 |
+
Return infimum (if possible) else S.Infinity.
|
94 |
+
"""
|
95 |
+
try:
|
96 |
+
infimum = expr.inf
|
97 |
+
assert infimum.is_comparable
|
98 |
+
infimum = infimum.evalf() # issue #18505
|
99 |
+
except (NotImplementedError,
|
100 |
+
AttributeError, AssertionError, ValueError):
|
101 |
+
infimum = S.Infinity
|
102 |
+
return infimum
|
103 |
+
|
104 |
+
def union(self, other):
|
105 |
+
"""
|
106 |
+
Returns the union of ``self`` and ``other``.
|
107 |
+
|
108 |
+
Examples
|
109 |
+
========
|
110 |
+
|
111 |
+
As a shortcut it is possible to use the ``+`` operator:
|
112 |
+
|
113 |
+
>>> from sympy import Interval, FiniteSet
|
114 |
+
>>> Interval(0, 1).union(Interval(2, 3))
|
115 |
+
Union(Interval(0, 1), Interval(2, 3))
|
116 |
+
>>> Interval(0, 1) + Interval(2, 3)
|
117 |
+
Union(Interval(0, 1), Interval(2, 3))
|
118 |
+
>>> Interval(1, 2, True, True) + FiniteSet(2, 3)
|
119 |
+
Union({3}, Interval.Lopen(1, 2))
|
120 |
+
|
121 |
+
Similarly it is possible to use the ``-`` operator for set differences:
|
122 |
+
|
123 |
+
>>> Interval(0, 2) - Interval(0, 1)
|
124 |
+
Interval.Lopen(1, 2)
|
125 |
+
>>> Interval(1, 3) - FiniteSet(2)
|
126 |
+
Union(Interval.Ropen(1, 2), Interval.Lopen(2, 3))
|
127 |
+
|
128 |
+
"""
|
129 |
+
return Union(self, other)
|
130 |
+
|
131 |
+
def intersect(self, other):
|
132 |
+
"""
|
133 |
+
Returns the intersection of 'self' and 'other'.
|
134 |
+
|
135 |
+
Examples
|
136 |
+
========
|
137 |
+
|
138 |
+
>>> from sympy import Interval
|
139 |
+
|
140 |
+
>>> Interval(1, 3).intersect(Interval(1, 2))
|
141 |
+
Interval(1, 2)
|
142 |
+
|
143 |
+
>>> from sympy import imageset, Lambda, symbols, S
|
144 |
+
>>> n, m = symbols('n m')
|
145 |
+
>>> a = imageset(Lambda(n, 2*n), S.Integers)
|
146 |
+
>>> a.intersect(imageset(Lambda(m, 2*m + 1), S.Integers))
|
147 |
+
EmptySet
|
148 |
+
|
149 |
+
"""
|
150 |
+
return Intersection(self, other)
|
151 |
+
|
152 |
+
def intersection(self, other):
|
153 |
+
"""
|
154 |
+
Alias for :meth:`intersect()`
|
155 |
+
"""
|
156 |
+
return self.intersect(other)
|
157 |
+
|
158 |
+
def is_disjoint(self, other):
|
159 |
+
"""
|
160 |
+
Returns True if ``self`` and ``other`` are disjoint.
|
161 |
+
|
162 |
+
Examples
|
163 |
+
========
|
164 |
+
|
165 |
+
>>> from sympy import Interval
|
166 |
+
>>> Interval(0, 2).is_disjoint(Interval(1, 2))
|
167 |
+
False
|
168 |
+
>>> Interval(0, 2).is_disjoint(Interval(3, 4))
|
169 |
+
True
|
170 |
+
|
171 |
+
References
|
172 |
+
==========
|
173 |
+
|
174 |
+
.. [1] https://en.wikipedia.org/wiki/Disjoint_sets
|
175 |
+
"""
|
176 |
+
return self.intersect(other) == S.EmptySet
|
177 |
+
|
178 |
+
def isdisjoint(self, other):
|
179 |
+
"""
|
180 |
+
Alias for :meth:`is_disjoint()`
|
181 |
+
"""
|
182 |
+
return self.is_disjoint(other)
|
183 |
+
|
184 |
+
def complement(self, universe):
|
185 |
+
r"""
|
186 |
+
The complement of 'self' w.r.t the given universe.
|
187 |
+
|
188 |
+
Examples
|
189 |
+
========
|
190 |
+
|
191 |
+
>>> from sympy import Interval, S
|
192 |
+
>>> Interval(0, 1).complement(S.Reals)
|
193 |
+
Union(Interval.open(-oo, 0), Interval.open(1, oo))
|
194 |
+
|
195 |
+
>>> Interval(0, 1).complement(S.UniversalSet)
|
196 |
+
Complement(UniversalSet, Interval(0, 1))
|
197 |
+
|
198 |
+
"""
|
199 |
+
return Complement(universe, self)
|
200 |
+
|
201 |
+
def _complement(self, other):
|
202 |
+
# this behaves as other - self
|
203 |
+
if isinstance(self, ProductSet) and isinstance(other, ProductSet):
|
204 |
+
# If self and other are disjoint then other - self == self
|
205 |
+
if len(self.sets) != len(other.sets):
|
206 |
+
return other
|
207 |
+
|
208 |
+
# There can be other ways to represent this but this gives:
|
209 |
+
# (A x B) - (C x D) = ((A - C) x B) U (A x (B - D))
|
210 |
+
overlaps = []
|
211 |
+
pairs = list(zip(self.sets, other.sets))
|
212 |
+
for n in range(len(pairs)):
|
213 |
+
sets = (o if i != n else o-s for i, (s, o) in enumerate(pairs))
|
214 |
+
overlaps.append(ProductSet(*sets))
|
215 |
+
return Union(*overlaps)
|
216 |
+
|
217 |
+
elif isinstance(other, Interval):
|
218 |
+
if isinstance(self, (Interval, FiniteSet)):
|
219 |
+
return Intersection(other, self.complement(S.Reals))
|
220 |
+
|
221 |
+
elif isinstance(other, Union):
|
222 |
+
return Union(*(o - self for o in other.args))
|
223 |
+
|
224 |
+
elif isinstance(other, Complement):
|
225 |
+
return Complement(other.args[0], Union(other.args[1], self), evaluate=False)
|
226 |
+
|
227 |
+
elif other is S.EmptySet:
|
228 |
+
return S.EmptySet
|
229 |
+
|
230 |
+
elif isinstance(other, FiniteSet):
|
231 |
+
sifted = sift(other, lambda x: fuzzy_bool(self.contains(x)))
|
232 |
+
# ignore those that are contained in self
|
233 |
+
return Union(FiniteSet(*(sifted[False])),
|
234 |
+
Complement(FiniteSet(*(sifted[None])), self, evaluate=False)
|
235 |
+
if sifted[None] else S.EmptySet)
|
236 |
+
|
237 |
+
def symmetric_difference(self, other):
|
238 |
+
"""
|
239 |
+
Returns symmetric difference of ``self`` and ``other``.
|
240 |
+
|
241 |
+
Examples
|
242 |
+
========
|
243 |
+
|
244 |
+
>>> from sympy import Interval, S
|
245 |
+
>>> Interval(1, 3).symmetric_difference(S.Reals)
|
246 |
+
Union(Interval.open(-oo, 1), Interval.open(3, oo))
|
247 |
+
>>> Interval(1, 10).symmetric_difference(S.Reals)
|
248 |
+
Union(Interval.open(-oo, 1), Interval.open(10, oo))
|
249 |
+
|
250 |
+
>>> from sympy import S, EmptySet
|
251 |
+
>>> S.Reals.symmetric_difference(EmptySet)
|
252 |
+
Reals
|
253 |
+
|
254 |
+
References
|
255 |
+
==========
|
256 |
+
.. [1] https://en.wikipedia.org/wiki/Symmetric_difference
|
257 |
+
|
258 |
+
"""
|
259 |
+
return SymmetricDifference(self, other)
|
260 |
+
|
261 |
+
def _symmetric_difference(self, other):
|
262 |
+
return Union(Complement(self, other), Complement(other, self))
|
263 |
+
|
264 |
+
@property
|
265 |
+
def inf(self):
|
266 |
+
"""
|
267 |
+
The infimum of ``self``.
|
268 |
+
|
269 |
+
Examples
|
270 |
+
========
|
271 |
+
|
272 |
+
>>> from sympy import Interval, Union
|
273 |
+
>>> Interval(0, 1).inf
|
274 |
+
0
|
275 |
+
>>> Union(Interval(0, 1), Interval(2, 3)).inf
|
276 |
+
0
|
277 |
+
|
278 |
+
"""
|
279 |
+
return self._inf
|
280 |
+
|
281 |
+
@property
|
282 |
+
def _inf(self):
|
283 |
+
raise NotImplementedError("(%s)._inf" % self)
|
284 |
+
|
285 |
+
@property
|
286 |
+
def sup(self):
|
287 |
+
"""
|
288 |
+
The supremum of ``self``.
|
289 |
+
|
290 |
+
Examples
|
291 |
+
========
|
292 |
+
|
293 |
+
>>> from sympy import Interval, Union
|
294 |
+
>>> Interval(0, 1).sup
|
295 |
+
1
|
296 |
+
>>> Union(Interval(0, 1), Interval(2, 3)).sup
|
297 |
+
3
|
298 |
+
|
299 |
+
"""
|
300 |
+
return self._sup
|
301 |
+
|
302 |
+
@property
|
303 |
+
def _sup(self):
|
304 |
+
raise NotImplementedError("(%s)._sup" % self)
|
305 |
+
|
306 |
+
def contains(self, other):
|
307 |
+
"""
|
308 |
+
Returns a SymPy value indicating whether ``other`` is contained
|
309 |
+
in ``self``: ``true`` if it is, ``false`` if it is not, else
|
310 |
+
an unevaluated ``Contains`` expression (or, as in the case of
|
311 |
+
ConditionSet and a union of FiniteSet/Intervals, an expression
|
312 |
+
indicating the conditions for containment).
|
313 |
+
|
314 |
+
Examples
|
315 |
+
========
|
316 |
+
|
317 |
+
>>> from sympy import Interval, S
|
318 |
+
>>> from sympy.abc import x
|
319 |
+
|
320 |
+
>>> Interval(0, 1).contains(0.5)
|
321 |
+
True
|
322 |
+
|
323 |
+
As a shortcut it is possible to use the ``in`` operator, but that
|
324 |
+
will raise an error unless an affirmative true or false is not
|
325 |
+
obtained.
|
326 |
+
|
327 |
+
>>> Interval(0, 1).contains(x)
|
328 |
+
(0 <= x) & (x <= 1)
|
329 |
+
>>> x in Interval(0, 1)
|
330 |
+
Traceback (most recent call last):
|
331 |
+
...
|
332 |
+
TypeError: did not evaluate to a bool: None
|
333 |
+
|
334 |
+
The result of 'in' is a bool, not a SymPy value
|
335 |
+
|
336 |
+
>>> 1 in Interval(0, 2)
|
337 |
+
True
|
338 |
+
>>> _ is S.true
|
339 |
+
False
|
340 |
+
"""
|
341 |
+
from .contains import Contains
|
342 |
+
other = sympify(other, strict=True)
|
343 |
+
|
344 |
+
c = self._contains(other)
|
345 |
+
if isinstance(c, Contains):
|
346 |
+
return c
|
347 |
+
if c is None:
|
348 |
+
return Contains(other, self, evaluate=False)
|
349 |
+
b = tfn[c]
|
350 |
+
if b is None:
|
351 |
+
return c
|
352 |
+
return b
|
353 |
+
|
354 |
+
def _contains(self, other):
|
355 |
+
raise NotImplementedError(filldedent('''
|
356 |
+
(%s)._contains(%s) is not defined. This method, when
|
357 |
+
defined, will receive a sympified object. The method
|
358 |
+
should return True, False, None or something that
|
359 |
+
expresses what must be true for the containment of that
|
360 |
+
object in self to be evaluated. If None is returned
|
361 |
+
then a generic Contains object will be returned
|
362 |
+
by the ``contains`` method.''' % (self, other)))
|
363 |
+
|
364 |
+
def is_subset(self, other):
|
365 |
+
"""
|
366 |
+
Returns True if ``self`` is a subset of ``other``.
|
367 |
+
|
368 |
+
Examples
|
369 |
+
========
|
370 |
+
|
371 |
+
>>> from sympy import Interval
|
372 |
+
>>> Interval(0, 0.5).is_subset(Interval(0, 1))
|
373 |
+
True
|
374 |
+
>>> Interval(0, 1).is_subset(Interval(0, 1, left_open=True))
|
375 |
+
False
|
376 |
+
|
377 |
+
"""
|
378 |
+
if not isinstance(other, Set):
|
379 |
+
raise ValueError("Unknown argument '%s'" % other)
|
380 |
+
|
381 |
+
# Handle the trivial cases
|
382 |
+
if self == other:
|
383 |
+
return True
|
384 |
+
is_empty = self.is_empty
|
385 |
+
if is_empty is True:
|
386 |
+
return True
|
387 |
+
elif fuzzy_not(is_empty) and other.is_empty:
|
388 |
+
return False
|
389 |
+
if self.is_finite_set is False and other.is_finite_set:
|
390 |
+
return False
|
391 |
+
|
392 |
+
# Dispatch on subclass rules
|
393 |
+
ret = self._eval_is_subset(other)
|
394 |
+
if ret is not None:
|
395 |
+
return ret
|
396 |
+
ret = other._eval_is_superset(self)
|
397 |
+
if ret is not None:
|
398 |
+
return ret
|
399 |
+
|
400 |
+
# Use pairwise rules from multiple dispatch
|
401 |
+
from sympy.sets.handlers.issubset import is_subset_sets
|
402 |
+
ret = is_subset_sets(self, other)
|
403 |
+
if ret is not None:
|
404 |
+
return ret
|
405 |
+
|
406 |
+
# Fall back on computing the intersection
|
407 |
+
# XXX: We shouldn't do this. A query like this should be handled
|
408 |
+
# without evaluating new Set objects. It should be the other way round
|
409 |
+
# so that the intersect method uses is_subset for evaluation.
|
410 |
+
if self.intersect(other) == self:
|
411 |
+
return True
|
412 |
+
|
413 |
+
def _eval_is_subset(self, other):
|
414 |
+
'''Returns a fuzzy bool for whether self is a subset of other.'''
|
415 |
+
return None
|
416 |
+
|
417 |
+
def _eval_is_superset(self, other):
|
418 |
+
'''Returns a fuzzy bool for whether self is a subset of other.'''
|
419 |
+
return None
|
420 |
+
|
421 |
+
# This should be deprecated:
|
422 |
+
def issubset(self, other):
|
423 |
+
"""
|
424 |
+
Alias for :meth:`is_subset()`
|
425 |
+
"""
|
426 |
+
return self.is_subset(other)
|
427 |
+
|
428 |
+
def is_proper_subset(self, other):
|
429 |
+
"""
|
430 |
+
Returns True if ``self`` is a proper subset of ``other``.
|
431 |
+
|
432 |
+
Examples
|
433 |
+
========
|
434 |
+
|
435 |
+
>>> from sympy import Interval
|
436 |
+
>>> Interval(0, 0.5).is_proper_subset(Interval(0, 1))
|
437 |
+
True
|
438 |
+
>>> Interval(0, 1).is_proper_subset(Interval(0, 1))
|
439 |
+
False
|
440 |
+
|
441 |
+
"""
|
442 |
+
if isinstance(other, Set):
|
443 |
+
return self != other and self.is_subset(other)
|
444 |
+
else:
|
445 |
+
raise ValueError("Unknown argument '%s'" % other)
|
446 |
+
|
447 |
+
def is_superset(self, other):
|
448 |
+
"""
|
449 |
+
Returns True if ``self`` is a superset of ``other``.
|
450 |
+
|
451 |
+
Examples
|
452 |
+
========
|
453 |
+
|
454 |
+
>>> from sympy import Interval
|
455 |
+
>>> Interval(0, 0.5).is_superset(Interval(0, 1))
|
456 |
+
False
|
457 |
+
>>> Interval(0, 1).is_superset(Interval(0, 1, left_open=True))
|
458 |
+
True
|
459 |
+
|
460 |
+
"""
|
461 |
+
if isinstance(other, Set):
|
462 |
+
return other.is_subset(self)
|
463 |
+
else:
|
464 |
+
raise ValueError("Unknown argument '%s'" % other)
|
465 |
+
|
466 |
+
# This should be deprecated:
|
467 |
+
def issuperset(self, other):
|
468 |
+
"""
|
469 |
+
Alias for :meth:`is_superset()`
|
470 |
+
"""
|
471 |
+
return self.is_superset(other)
|
472 |
+
|
473 |
+
def is_proper_superset(self, other):
|
474 |
+
"""
|
475 |
+
Returns True if ``self`` is a proper superset of ``other``.
|
476 |
+
|
477 |
+
Examples
|
478 |
+
========
|
479 |
+
|
480 |
+
>>> from sympy import Interval
|
481 |
+
>>> Interval(0, 1).is_proper_superset(Interval(0, 0.5))
|
482 |
+
True
|
483 |
+
>>> Interval(0, 1).is_proper_superset(Interval(0, 1))
|
484 |
+
False
|
485 |
+
|
486 |
+
"""
|
487 |
+
if isinstance(other, Set):
|
488 |
+
return self != other and self.is_superset(other)
|
489 |
+
else:
|
490 |
+
raise ValueError("Unknown argument '%s'" % other)
|
491 |
+
|
492 |
+
def _eval_powerset(self):
|
493 |
+
from .powerset import PowerSet
|
494 |
+
return PowerSet(self)
|
495 |
+
|
496 |
+
def powerset(self):
|
497 |
+
"""
|
498 |
+
Find the Power set of ``self``.
|
499 |
+
|
500 |
+
Examples
|
501 |
+
========
|
502 |
+
|
503 |
+
>>> from sympy import EmptySet, FiniteSet, Interval
|
504 |
+
|
505 |
+
A power set of an empty set:
|
506 |
+
|
507 |
+
>>> A = EmptySet
|
508 |
+
>>> A.powerset()
|
509 |
+
{EmptySet}
|
510 |
+
|
511 |
+
A power set of a finite set:
|
512 |
+
|
513 |
+
>>> A = FiniteSet(1, 2)
|
514 |
+
>>> a, b, c = FiniteSet(1), FiniteSet(2), FiniteSet(1, 2)
|
515 |
+
>>> A.powerset() == FiniteSet(a, b, c, EmptySet)
|
516 |
+
True
|
517 |
+
|
518 |
+
A power set of an interval:
|
519 |
+
|
520 |
+
>>> Interval(1, 2).powerset()
|
521 |
+
PowerSet(Interval(1, 2))
|
522 |
+
|
523 |
+
References
|
524 |
+
==========
|
525 |
+
|
526 |
+
.. [1] https://en.wikipedia.org/wiki/Power_set
|
527 |
+
|
528 |
+
"""
|
529 |
+
return self._eval_powerset()
|
530 |
+
|
531 |
+
@property
|
532 |
+
def measure(self):
|
533 |
+
"""
|
534 |
+
The (Lebesgue) measure of ``self``.
|
535 |
+
|
536 |
+
Examples
|
537 |
+
========
|
538 |
+
|
539 |
+
>>> from sympy import Interval, Union
|
540 |
+
>>> Interval(0, 1).measure
|
541 |
+
1
|
542 |
+
>>> Union(Interval(0, 1), Interval(2, 3)).measure
|
543 |
+
2
|
544 |
+
|
545 |
+
"""
|
546 |
+
return self._measure
|
547 |
+
|
548 |
+
@property
|
549 |
+
def kind(self):
|
550 |
+
"""
|
551 |
+
The kind of a Set
|
552 |
+
|
553 |
+
Explanation
|
554 |
+
===========
|
555 |
+
|
556 |
+
Any :class:`Set` will have kind :class:`SetKind` which is
|
557 |
+
parametrised by the kind of the elements of the set. For example
|
558 |
+
most sets are sets of numbers and will have kind
|
559 |
+
``SetKind(NumberKind)``. If elements of sets are different in kind than
|
560 |
+
their kind will ``SetKind(UndefinedKind)``. See
|
561 |
+
:class:`sympy.core.kind.Kind` for an explanation of the kind system.
|
562 |
+
|
563 |
+
Examples
|
564 |
+
========
|
565 |
+
|
566 |
+
>>> from sympy import Interval, Matrix, FiniteSet, EmptySet, ProductSet, PowerSet
|
567 |
+
|
568 |
+
>>> FiniteSet(Matrix([1, 2])).kind
|
569 |
+
SetKind(MatrixKind(NumberKind))
|
570 |
+
|
571 |
+
>>> Interval(1, 2).kind
|
572 |
+
SetKind(NumberKind)
|
573 |
+
|
574 |
+
>>> EmptySet.kind
|
575 |
+
SetKind()
|
576 |
+
|
577 |
+
A :class:`sympy.sets.powerset.PowerSet` is a set of sets:
|
578 |
+
|
579 |
+
>>> PowerSet({1, 2, 3}).kind
|
580 |
+
SetKind(SetKind(NumberKind))
|
581 |
+
|
582 |
+
A :class:`ProductSet` represents the set of tuples of elements of
|
583 |
+
other sets. Its kind is :class:`sympy.core.containers.TupleKind`
|
584 |
+
parametrised by the kinds of the elements of those sets:
|
585 |
+
|
586 |
+
>>> p = ProductSet(FiniteSet(1, 2), FiniteSet(3, 4))
|
587 |
+
>>> list(p)
|
588 |
+
[(1, 3), (2, 3), (1, 4), (2, 4)]
|
589 |
+
>>> p.kind
|
590 |
+
SetKind(TupleKind(NumberKind, NumberKind))
|
591 |
+
|
592 |
+
When all elements of the set do not have same kind, the kind
|
593 |
+
will be returned as ``SetKind(UndefinedKind)``:
|
594 |
+
|
595 |
+
>>> FiniteSet(0, Matrix([1, 2])).kind
|
596 |
+
SetKind(UndefinedKind)
|
597 |
+
|
598 |
+
The kind of the elements of a set are given by the ``element_kind``
|
599 |
+
attribute of ``SetKind``:
|
600 |
+
|
601 |
+
>>> Interval(1, 2).kind.element_kind
|
602 |
+
NumberKind
|
603 |
+
|
604 |
+
See Also
|
605 |
+
========
|
606 |
+
|
607 |
+
NumberKind
|
608 |
+
sympy.core.kind.UndefinedKind
|
609 |
+
sympy.core.containers.TupleKind
|
610 |
+
MatrixKind
|
611 |
+
sympy.matrices.expressions.sets.MatrixSet
|
612 |
+
sympy.sets.conditionset.ConditionSet
|
613 |
+
Rationals
|
614 |
+
Naturals
|
615 |
+
Integers
|
616 |
+
sympy.sets.fancysets.ImageSet
|
617 |
+
sympy.sets.fancysets.Range
|
618 |
+
sympy.sets.fancysets.ComplexRegion
|
619 |
+
sympy.sets.powerset.PowerSet
|
620 |
+
sympy.sets.sets.ProductSet
|
621 |
+
sympy.sets.sets.Interval
|
622 |
+
sympy.sets.sets.Union
|
623 |
+
sympy.sets.sets.Intersection
|
624 |
+
sympy.sets.sets.Complement
|
625 |
+
sympy.sets.sets.EmptySet
|
626 |
+
sympy.sets.sets.UniversalSet
|
627 |
+
sympy.sets.sets.FiniteSet
|
628 |
+
sympy.sets.sets.SymmetricDifference
|
629 |
+
sympy.sets.sets.DisjointUnion
|
630 |
+
"""
|
631 |
+
return self._kind()
|
632 |
+
|
633 |
+
@property
|
634 |
+
def boundary(self):
|
635 |
+
"""
|
636 |
+
The boundary or frontier of a set.
|
637 |
+
|
638 |
+
Explanation
|
639 |
+
===========
|
640 |
+
|
641 |
+
A point x is on the boundary of a set S if
|
642 |
+
|
643 |
+
1. x is in the closure of S.
|
644 |
+
I.e. Every neighborhood of x contains a point in S.
|
645 |
+
2. x is not in the interior of S.
|
646 |
+
I.e. There does not exist an open set centered on x contained
|
647 |
+
entirely within S.
|
648 |
+
|
649 |
+
There are the points on the outer rim of S. If S is open then these
|
650 |
+
points need not actually be contained within S.
|
651 |
+
|
652 |
+
For example, the boundary of an interval is its start and end points.
|
653 |
+
This is true regardless of whether or not the interval is open.
|
654 |
+
|
655 |
+
Examples
|
656 |
+
========
|
657 |
+
|
658 |
+
>>> from sympy import Interval
|
659 |
+
>>> Interval(0, 1).boundary
|
660 |
+
{0, 1}
|
661 |
+
>>> Interval(0, 1, True, False).boundary
|
662 |
+
{0, 1}
|
663 |
+
"""
|
664 |
+
return self._boundary
|
665 |
+
|
666 |
+
@property
|
667 |
+
def is_open(self):
|
668 |
+
"""
|
669 |
+
Property method to check whether a set is open.
|
670 |
+
|
671 |
+
Explanation
|
672 |
+
===========
|
673 |
+
|
674 |
+
A set is open if and only if it has an empty intersection with its
|
675 |
+
boundary. In particular, a subset A of the reals is open if and only
|
676 |
+
if each one of its points is contained in an open interval that is a
|
677 |
+
subset of A.
|
678 |
+
|
679 |
+
Examples
|
680 |
+
========
|
681 |
+
>>> from sympy import S
|
682 |
+
>>> S.Reals.is_open
|
683 |
+
True
|
684 |
+
>>> S.Rationals.is_open
|
685 |
+
False
|
686 |
+
"""
|
687 |
+
return Intersection(self, self.boundary).is_empty
|
688 |
+
|
689 |
+
@property
|
690 |
+
def is_closed(self):
|
691 |
+
"""
|
692 |
+
A property method to check whether a set is closed.
|
693 |
+
|
694 |
+
Explanation
|
695 |
+
===========
|
696 |
+
|
697 |
+
A set is closed if its complement is an open set. The closedness of a
|
698 |
+
subset of the reals is determined with respect to R and its standard
|
699 |
+
topology.
|
700 |
+
|
701 |
+
Examples
|
702 |
+
========
|
703 |
+
>>> from sympy import Interval
|
704 |
+
>>> Interval(0, 1).is_closed
|
705 |
+
True
|
706 |
+
"""
|
707 |
+
return self.boundary.is_subset(self)
|
708 |
+
|
709 |
+
@property
|
710 |
+
def closure(self):
|
711 |
+
"""
|
712 |
+
Property method which returns the closure of a set.
|
713 |
+
The closure is defined as the union of the set itself and its
|
714 |
+
boundary.
|
715 |
+
|
716 |
+
Examples
|
717 |
+
========
|
718 |
+
>>> from sympy import S, Interval
|
719 |
+
>>> S.Reals.closure
|
720 |
+
Reals
|
721 |
+
>>> Interval(0, 1).closure
|
722 |
+
Interval(0, 1)
|
723 |
+
"""
|
724 |
+
return self + self.boundary
|
725 |
+
|
726 |
+
@property
|
727 |
+
def interior(self):
|
728 |
+
"""
|
729 |
+
Property method which returns the interior of a set.
|
730 |
+
The interior of a set S consists all points of S that do not
|
731 |
+
belong to the boundary of S.
|
732 |
+
|
733 |
+
Examples
|
734 |
+
========
|
735 |
+
>>> from sympy import Interval
|
736 |
+
>>> Interval(0, 1).interior
|
737 |
+
Interval.open(0, 1)
|
738 |
+
>>> Interval(0, 1).boundary.interior
|
739 |
+
EmptySet
|
740 |
+
"""
|
741 |
+
return self - self.boundary
|
742 |
+
|
743 |
+
@property
|
744 |
+
def _boundary(self):
|
745 |
+
raise NotImplementedError()
|
746 |
+
|
747 |
+
@property
|
748 |
+
def _measure(self):
|
749 |
+
raise NotImplementedError("(%s)._measure" % self)
|
750 |
+
|
751 |
+
def _kind(self):
|
752 |
+
return SetKind(UndefinedKind)
|
753 |
+
|
754 |
+
def _eval_evalf(self, prec):
|
755 |
+
dps = prec_to_dps(prec)
|
756 |
+
return self.func(*[arg.evalf(n=dps) for arg in self.args])
|
757 |
+
|
758 |
+
@sympify_return([('other', 'Set')], NotImplemented)
|
759 |
+
def __add__(self, other):
|
760 |
+
return self.union(other)
|
761 |
+
|
762 |
+
@sympify_return([('other', 'Set')], NotImplemented)
|
763 |
+
def __or__(self, other):
|
764 |
+
return self.union(other)
|
765 |
+
|
766 |
+
@sympify_return([('other', 'Set')], NotImplemented)
|
767 |
+
def __and__(self, other):
|
768 |
+
return self.intersect(other)
|
769 |
+
|
770 |
+
@sympify_return([('other', 'Set')], NotImplemented)
|
771 |
+
def __mul__(self, other):
|
772 |
+
return ProductSet(self, other)
|
773 |
+
|
774 |
+
@sympify_return([('other', 'Set')], NotImplemented)
|
775 |
+
def __xor__(self, other):
|
776 |
+
return SymmetricDifference(self, other)
|
777 |
+
|
778 |
+
@sympify_return([('exp', Expr)], NotImplemented)
|
779 |
+
def __pow__(self, exp):
|
780 |
+
if not (exp.is_Integer and exp >= 0):
|
781 |
+
raise ValueError("%s: Exponent must be a positive Integer" % exp)
|
782 |
+
return ProductSet(*[self]*exp)
|
783 |
+
|
784 |
+
@sympify_return([('other', 'Set')], NotImplemented)
|
785 |
+
def __sub__(self, other):
|
786 |
+
return Complement(self, other)
|
787 |
+
|
788 |
+
def __contains__(self, other):
|
789 |
+
other = _sympify(other)
|
790 |
+
c = self._contains(other)
|
791 |
+
b = tfn[c]
|
792 |
+
if b is None:
|
793 |
+
# x in y must evaluate to T or F; to entertain a None
|
794 |
+
# result with Set use y.contains(x)
|
795 |
+
raise TypeError('did not evaluate to a bool: %r' % c)
|
796 |
+
return b
|
797 |
+
|
798 |
+
|
799 |
+
class ProductSet(Set):
|
800 |
+
"""
|
801 |
+
Represents a Cartesian Product of Sets.
|
802 |
+
|
803 |
+
Explanation
|
804 |
+
===========
|
805 |
+
|
806 |
+
Returns a Cartesian product given several sets as either an iterable
|
807 |
+
or individual arguments.
|
808 |
+
|
809 |
+
Can use ``*`` operator on any sets for convenient shorthand.
|
810 |
+
|
811 |
+
Examples
|
812 |
+
========
|
813 |
+
|
814 |
+
>>> from sympy import Interval, FiniteSet, ProductSet
|
815 |
+
>>> I = Interval(0, 5); S = FiniteSet(1, 2, 3)
|
816 |
+
>>> ProductSet(I, S)
|
817 |
+
ProductSet(Interval(0, 5), {1, 2, 3})
|
818 |
+
|
819 |
+
>>> (2, 2) in ProductSet(I, S)
|
820 |
+
True
|
821 |
+
|
822 |
+
>>> Interval(0, 1) * Interval(0, 1) # The unit square
|
823 |
+
ProductSet(Interval(0, 1), Interval(0, 1))
|
824 |
+
|
825 |
+
>>> coin = FiniteSet('H', 'T')
|
826 |
+
>>> set(coin**2)
|
827 |
+
{(H, H), (H, T), (T, H), (T, T)}
|
828 |
+
|
829 |
+
The Cartesian product is not commutative or associative e.g.:
|
830 |
+
|
831 |
+
>>> I*S == S*I
|
832 |
+
False
|
833 |
+
>>> (I*I)*I == I*(I*I)
|
834 |
+
False
|
835 |
+
|
836 |
+
Notes
|
837 |
+
=====
|
838 |
+
|
839 |
+
- Passes most operations down to the argument sets
|
840 |
+
|
841 |
+
References
|
842 |
+
==========
|
843 |
+
|
844 |
+
.. [1] https://en.wikipedia.org/wiki/Cartesian_product
|
845 |
+
"""
|
846 |
+
is_ProductSet = True
|
847 |
+
|
848 |
+
def __new__(cls, *sets, **assumptions):
|
849 |
+
if len(sets) == 1 and iterable(sets[0]) and not isinstance(sets[0], (Set, set)):
|
850 |
+
sympy_deprecation_warning(
|
851 |
+
"""
|
852 |
+
ProductSet(iterable) is deprecated. Use ProductSet(*iterable) instead.
|
853 |
+
""",
|
854 |
+
deprecated_since_version="1.5",
|
855 |
+
active_deprecations_target="deprecated-productset-iterable",
|
856 |
+
)
|
857 |
+
sets = tuple(sets[0])
|
858 |
+
|
859 |
+
sets = [sympify(s) for s in sets]
|
860 |
+
|
861 |
+
if not all(isinstance(s, Set) for s in sets):
|
862 |
+
raise TypeError("Arguments to ProductSet should be of type Set")
|
863 |
+
|
864 |
+
# Nullary product of sets is *not* the empty set
|
865 |
+
if len(sets) == 0:
|
866 |
+
return FiniteSet(())
|
867 |
+
|
868 |
+
if S.EmptySet in sets:
|
869 |
+
return S.EmptySet
|
870 |
+
|
871 |
+
return Basic.__new__(cls, *sets, **assumptions)
|
872 |
+
|
873 |
+
@property
|
874 |
+
def sets(self):
|
875 |
+
return self.args
|
876 |
+
|
877 |
+
def flatten(self):
|
878 |
+
def _flatten(sets):
|
879 |
+
for s in sets:
|
880 |
+
if s.is_ProductSet:
|
881 |
+
yield from _flatten(s.sets)
|
882 |
+
else:
|
883 |
+
yield s
|
884 |
+
return ProductSet(*_flatten(self.sets))
|
885 |
+
|
886 |
+
|
887 |
+
|
888 |
+
def _contains(self, element):
|
889 |
+
"""
|
890 |
+
``in`` operator for ProductSets.
|
891 |
+
|
892 |
+
Examples
|
893 |
+
========
|
894 |
+
|
895 |
+
>>> from sympy import Interval
|
896 |
+
>>> (2, 3) in Interval(0, 5) * Interval(0, 5)
|
897 |
+
True
|
898 |
+
|
899 |
+
>>> (10, 10) in Interval(0, 5) * Interval(0, 5)
|
900 |
+
False
|
901 |
+
|
902 |
+
Passes operation on to constituent sets
|
903 |
+
"""
|
904 |
+
if element.is_Symbol:
|
905 |
+
return None
|
906 |
+
|
907 |
+
if not isinstance(element, Tuple) or len(element) != len(self.sets):
|
908 |
+
return False
|
909 |
+
|
910 |
+
return fuzzy_and(s._contains(e) for s, e in zip(self.sets, element))
|
911 |
+
|
912 |
+
def as_relational(self, *symbols):
|
913 |
+
symbols = [_sympify(s) for s in symbols]
|
914 |
+
if len(symbols) != len(self.sets) or not all(
|
915 |
+
i.is_Symbol for i in symbols):
|
916 |
+
raise ValueError(
|
917 |
+
'number of symbols must match the number of sets')
|
918 |
+
return And(*[s.as_relational(i) for s, i in zip(self.sets, symbols)])
|
919 |
+
|
920 |
+
@property
|
921 |
+
def _boundary(self):
|
922 |
+
return Union(*(ProductSet(*(b + b.boundary if i != j else b.boundary
|
923 |
+
for j, b in enumerate(self.sets)))
|
924 |
+
for i, a in enumerate(self.sets)))
|
925 |
+
|
926 |
+
@property
|
927 |
+
def is_iterable(self):
|
928 |
+
"""
|
929 |
+
A property method which tests whether a set is iterable or not.
|
930 |
+
Returns True if set is iterable, otherwise returns False.
|
931 |
+
|
932 |
+
Examples
|
933 |
+
========
|
934 |
+
|
935 |
+
>>> from sympy import FiniteSet, Interval
|
936 |
+
>>> I = Interval(0, 1)
|
937 |
+
>>> A = FiniteSet(1, 2, 3, 4, 5)
|
938 |
+
>>> I.is_iterable
|
939 |
+
False
|
940 |
+
>>> A.is_iterable
|
941 |
+
True
|
942 |
+
|
943 |
+
"""
|
944 |
+
return all(set.is_iterable for set in self.sets)
|
945 |
+
|
946 |
+
def __iter__(self):
|
947 |
+
"""
|
948 |
+
A method which implements is_iterable property method.
|
949 |
+
If self.is_iterable returns True (both constituent sets are iterable),
|
950 |
+
then return the Cartesian Product. Otherwise, raise TypeError.
|
951 |
+
"""
|
952 |
+
return iproduct(*self.sets)
|
953 |
+
|
954 |
+
@property
|
955 |
+
def is_empty(self):
|
956 |
+
return fuzzy_or(s.is_empty for s in self.sets)
|
957 |
+
|
958 |
+
@property
|
959 |
+
def is_finite_set(self):
|
960 |
+
all_finite = fuzzy_and(s.is_finite_set for s in self.sets)
|
961 |
+
return fuzzy_or([self.is_empty, all_finite])
|
962 |
+
|
963 |
+
@property
|
964 |
+
def _measure(self):
|
965 |
+
measure = 1
|
966 |
+
for s in self.sets:
|
967 |
+
measure *= s.measure
|
968 |
+
return measure
|
969 |
+
|
970 |
+
def _kind(self):
|
971 |
+
return SetKind(TupleKind(*(i.kind.element_kind for i in self.args)))
|
972 |
+
|
973 |
+
def __len__(self):
|
974 |
+
return reduce(lambda a, b: a*b, (len(s) for s in self.args))
|
975 |
+
|
976 |
+
def __bool__(self):
|
977 |
+
return all(self.sets)
|
978 |
+
|
979 |
+
|
980 |
+
class Interval(Set):
|
981 |
+
"""
|
982 |
+
Represents a real interval as a Set.
|
983 |
+
|
984 |
+
Usage:
|
985 |
+
Returns an interval with end points ``start`` and ``end``.
|
986 |
+
|
987 |
+
For ``left_open=True`` (default ``left_open`` is ``False``) the interval
|
988 |
+
will be open on the left. Similarly, for ``right_open=True`` the interval
|
989 |
+
will be open on the right.
|
990 |
+
|
991 |
+
Examples
|
992 |
+
========
|
993 |
+
|
994 |
+
>>> from sympy import Symbol, Interval
|
995 |
+
>>> Interval(0, 1)
|
996 |
+
Interval(0, 1)
|
997 |
+
>>> Interval.Ropen(0, 1)
|
998 |
+
Interval.Ropen(0, 1)
|
999 |
+
>>> Interval.Ropen(0, 1)
|
1000 |
+
Interval.Ropen(0, 1)
|
1001 |
+
>>> Interval.Lopen(0, 1)
|
1002 |
+
Interval.Lopen(0, 1)
|
1003 |
+
>>> Interval.open(0, 1)
|
1004 |
+
Interval.open(0, 1)
|
1005 |
+
|
1006 |
+
>>> a = Symbol('a', real=True)
|
1007 |
+
>>> Interval(0, a)
|
1008 |
+
Interval(0, a)
|
1009 |
+
|
1010 |
+
Notes
|
1011 |
+
=====
|
1012 |
+
- Only real end points are supported
|
1013 |
+
- ``Interval(a, b)`` with $a > b$ will return the empty set
|
1014 |
+
- Use the ``evalf()`` method to turn an Interval into an mpmath
|
1015 |
+
``mpi`` interval instance
|
1016 |
+
|
1017 |
+
References
|
1018 |
+
==========
|
1019 |
+
|
1020 |
+
.. [1] https://en.wikipedia.org/wiki/Interval_%28mathematics%29
|
1021 |
+
"""
|
1022 |
+
is_Interval = True
|
1023 |
+
|
1024 |
+
def __new__(cls, start, end, left_open=False, right_open=False):
|
1025 |
+
|
1026 |
+
start = _sympify(start)
|
1027 |
+
end = _sympify(end)
|
1028 |
+
left_open = _sympify(left_open)
|
1029 |
+
right_open = _sympify(right_open)
|
1030 |
+
|
1031 |
+
if not all(isinstance(a, (type(true), type(false)))
|
1032 |
+
for a in [left_open, right_open]):
|
1033 |
+
raise NotImplementedError(
|
1034 |
+
"left_open and right_open can have only true/false values, "
|
1035 |
+
"got %s and %s" % (left_open, right_open))
|
1036 |
+
|
1037 |
+
# Only allow real intervals
|
1038 |
+
if fuzzy_not(fuzzy_and(i.is_extended_real for i in (start, end, end-start))):
|
1039 |
+
raise ValueError("Non-real intervals are not supported")
|
1040 |
+
|
1041 |
+
# evaluate if possible
|
1042 |
+
if is_lt(end, start):
|
1043 |
+
return S.EmptySet
|
1044 |
+
elif (end - start).is_negative:
|
1045 |
+
return S.EmptySet
|
1046 |
+
|
1047 |
+
if end == start and (left_open or right_open):
|
1048 |
+
return S.EmptySet
|
1049 |
+
if end == start and not (left_open or right_open):
|
1050 |
+
if start is S.Infinity or start is S.NegativeInfinity:
|
1051 |
+
return S.EmptySet
|
1052 |
+
return FiniteSet(end)
|
1053 |
+
|
1054 |
+
# Make sure infinite interval end points are open.
|
1055 |
+
if start is S.NegativeInfinity:
|
1056 |
+
left_open = true
|
1057 |
+
if end is S.Infinity:
|
1058 |
+
right_open = true
|
1059 |
+
if start == S.Infinity or end == S.NegativeInfinity:
|
1060 |
+
return S.EmptySet
|
1061 |
+
|
1062 |
+
return Basic.__new__(cls, start, end, left_open, right_open)
|
1063 |
+
|
1064 |
+
@property
|
1065 |
+
def start(self):
|
1066 |
+
"""
|
1067 |
+
The left end point of the interval.
|
1068 |
+
|
1069 |
+
This property takes the same value as the ``inf`` property.
|
1070 |
+
|
1071 |
+
Examples
|
1072 |
+
========
|
1073 |
+
|
1074 |
+
>>> from sympy import Interval
|
1075 |
+
>>> Interval(0, 1).start
|
1076 |
+
0
|
1077 |
+
|
1078 |
+
"""
|
1079 |
+
return self._args[0]
|
1080 |
+
|
1081 |
+
@property
|
1082 |
+
def end(self):
|
1083 |
+
"""
|
1084 |
+
The right end point of the interval.
|
1085 |
+
|
1086 |
+
This property takes the same value as the ``sup`` property.
|
1087 |
+
|
1088 |
+
Examples
|
1089 |
+
========
|
1090 |
+
|
1091 |
+
>>> from sympy import Interval
|
1092 |
+
>>> Interval(0, 1).end
|
1093 |
+
1
|
1094 |
+
|
1095 |
+
"""
|
1096 |
+
return self._args[1]
|
1097 |
+
|
1098 |
+
@property
|
1099 |
+
def left_open(self):
|
1100 |
+
"""
|
1101 |
+
True if interval is left-open.
|
1102 |
+
|
1103 |
+
Examples
|
1104 |
+
========
|
1105 |
+
|
1106 |
+
>>> from sympy import Interval
|
1107 |
+
>>> Interval(0, 1, left_open=True).left_open
|
1108 |
+
True
|
1109 |
+
>>> Interval(0, 1, left_open=False).left_open
|
1110 |
+
False
|
1111 |
+
|
1112 |
+
"""
|
1113 |
+
return self._args[2]
|
1114 |
+
|
1115 |
+
@property
|
1116 |
+
def right_open(self):
|
1117 |
+
"""
|
1118 |
+
True if interval is right-open.
|
1119 |
+
|
1120 |
+
Examples
|
1121 |
+
========
|
1122 |
+
|
1123 |
+
>>> from sympy import Interval
|
1124 |
+
>>> Interval(0, 1, right_open=True).right_open
|
1125 |
+
True
|
1126 |
+
>>> Interval(0, 1, right_open=False).right_open
|
1127 |
+
False
|
1128 |
+
|
1129 |
+
"""
|
1130 |
+
return self._args[3]
|
1131 |
+
|
1132 |
+
@classmethod
|
1133 |
+
def open(cls, a, b):
|
1134 |
+
"""Return an interval including neither boundary."""
|
1135 |
+
return cls(a, b, True, True)
|
1136 |
+
|
1137 |
+
@classmethod
|
1138 |
+
def Lopen(cls, a, b):
|
1139 |
+
"""Return an interval not including the left boundary."""
|
1140 |
+
return cls(a, b, True, False)
|
1141 |
+
|
1142 |
+
@classmethod
|
1143 |
+
def Ropen(cls, a, b):
|
1144 |
+
"""Return an interval not including the right boundary."""
|
1145 |
+
return cls(a, b, False, True)
|
1146 |
+
|
1147 |
+
@property
|
1148 |
+
def _inf(self):
|
1149 |
+
return self.start
|
1150 |
+
|
1151 |
+
@property
|
1152 |
+
def _sup(self):
|
1153 |
+
return self.end
|
1154 |
+
|
1155 |
+
@property
|
1156 |
+
def left(self):
|
1157 |
+
return self.start
|
1158 |
+
|
1159 |
+
@property
|
1160 |
+
def right(self):
|
1161 |
+
return self.end
|
1162 |
+
|
1163 |
+
@property
|
1164 |
+
def is_empty(self):
|
1165 |
+
if self.left_open or self.right_open:
|
1166 |
+
cond = self.start >= self.end # One/both bounds open
|
1167 |
+
else:
|
1168 |
+
cond = self.start > self.end # Both bounds closed
|
1169 |
+
return fuzzy_bool(cond)
|
1170 |
+
|
1171 |
+
@property
|
1172 |
+
def is_finite_set(self):
|
1173 |
+
return self.measure.is_zero
|
1174 |
+
|
1175 |
+
def _complement(self, other):
|
1176 |
+
if other == S.Reals:
|
1177 |
+
a = Interval(S.NegativeInfinity, self.start,
|
1178 |
+
True, not self.left_open)
|
1179 |
+
b = Interval(self.end, S.Infinity, not self.right_open, True)
|
1180 |
+
return Union(a, b)
|
1181 |
+
|
1182 |
+
if isinstance(other, FiniteSet):
|
1183 |
+
nums = [m for m in other.args if m.is_number]
|
1184 |
+
if nums == []:
|
1185 |
+
return None
|
1186 |
+
|
1187 |
+
return Set._complement(self, other)
|
1188 |
+
|
1189 |
+
@property
|
1190 |
+
def _boundary(self):
|
1191 |
+
finite_points = [p for p in (self.start, self.end)
|
1192 |
+
if abs(p) != S.Infinity]
|
1193 |
+
return FiniteSet(*finite_points)
|
1194 |
+
|
1195 |
+
def _contains(self, other):
|
1196 |
+
if (not isinstance(other, Expr) or other is S.NaN
|
1197 |
+
or other.is_real is False or other.has(S.ComplexInfinity)):
|
1198 |
+
# if an expression has zoo it will be zoo or nan
|
1199 |
+
# and neither of those is real
|
1200 |
+
return false
|
1201 |
+
|
1202 |
+
if self.start is S.NegativeInfinity and self.end is S.Infinity:
|
1203 |
+
if other.is_real is not None:
|
1204 |
+
return other.is_real
|
1205 |
+
|
1206 |
+
d = Dummy()
|
1207 |
+
return self.as_relational(d).subs(d, other)
|
1208 |
+
|
1209 |
+
def as_relational(self, x):
|
1210 |
+
"""Rewrite an interval in terms of inequalities and logic operators."""
|
1211 |
+
x = sympify(x)
|
1212 |
+
if self.right_open:
|
1213 |
+
right = x < self.end
|
1214 |
+
else:
|
1215 |
+
right = x <= self.end
|
1216 |
+
if self.left_open:
|
1217 |
+
left = self.start < x
|
1218 |
+
else:
|
1219 |
+
left = self.start <= x
|
1220 |
+
return And(left, right)
|
1221 |
+
|
1222 |
+
@property
|
1223 |
+
def _measure(self):
|
1224 |
+
return self.end - self.start
|
1225 |
+
|
1226 |
+
def _kind(self):
|
1227 |
+
return SetKind(NumberKind)
|
1228 |
+
|
1229 |
+
def to_mpi(self, prec=53):
|
1230 |
+
return mpi(mpf(self.start._eval_evalf(prec)),
|
1231 |
+
mpf(self.end._eval_evalf(prec)))
|
1232 |
+
|
1233 |
+
def _eval_evalf(self, prec):
|
1234 |
+
return Interval(self.left._evalf(prec), self.right._evalf(prec),
|
1235 |
+
left_open=self.left_open, right_open=self.right_open)
|
1236 |
+
|
1237 |
+
def _is_comparable(self, other):
|
1238 |
+
is_comparable = self.start.is_comparable
|
1239 |
+
is_comparable &= self.end.is_comparable
|
1240 |
+
is_comparable &= other.start.is_comparable
|
1241 |
+
is_comparable &= other.end.is_comparable
|
1242 |
+
|
1243 |
+
return is_comparable
|
1244 |
+
|
1245 |
+
@property
|
1246 |
+
def is_left_unbounded(self):
|
1247 |
+
"""Return ``True`` if the left endpoint is negative infinity. """
|
1248 |
+
return self.left is S.NegativeInfinity or self.left == Float("-inf")
|
1249 |
+
|
1250 |
+
@property
|
1251 |
+
def is_right_unbounded(self):
|
1252 |
+
"""Return ``True`` if the right endpoint is positive infinity. """
|
1253 |
+
return self.right is S.Infinity or self.right == Float("+inf")
|
1254 |
+
|
1255 |
+
def _eval_Eq(self, other):
|
1256 |
+
if not isinstance(other, Interval):
|
1257 |
+
if isinstance(other, FiniteSet):
|
1258 |
+
return false
|
1259 |
+
elif isinstance(other, Set):
|
1260 |
+
return None
|
1261 |
+
return false
|
1262 |
+
|
1263 |
+
|
1264 |
+
class Union(Set, LatticeOp):
|
1265 |
+
"""
|
1266 |
+
Represents a union of sets as a :class:`Set`.
|
1267 |
+
|
1268 |
+
Examples
|
1269 |
+
========
|
1270 |
+
|
1271 |
+
>>> from sympy import Union, Interval
|
1272 |
+
>>> Union(Interval(1, 2), Interval(3, 4))
|
1273 |
+
Union(Interval(1, 2), Interval(3, 4))
|
1274 |
+
|
1275 |
+
The Union constructor will always try to merge overlapping intervals,
|
1276 |
+
if possible. For example:
|
1277 |
+
|
1278 |
+
>>> Union(Interval(1, 2), Interval(2, 3))
|
1279 |
+
Interval(1, 3)
|
1280 |
+
|
1281 |
+
See Also
|
1282 |
+
========
|
1283 |
+
|
1284 |
+
Intersection
|
1285 |
+
|
1286 |
+
References
|
1287 |
+
==========
|
1288 |
+
|
1289 |
+
.. [1] https://en.wikipedia.org/wiki/Union_%28set_theory%29
|
1290 |
+
"""
|
1291 |
+
is_Union = True
|
1292 |
+
|
1293 |
+
@property
|
1294 |
+
def identity(self):
|
1295 |
+
return S.EmptySet
|
1296 |
+
|
1297 |
+
@property
|
1298 |
+
def zero(self):
|
1299 |
+
return S.UniversalSet
|
1300 |
+
|
1301 |
+
def __new__(cls, *args, **kwargs):
|
1302 |
+
evaluate = kwargs.get('evaluate', global_parameters.evaluate)
|
1303 |
+
|
1304 |
+
# flatten inputs to merge intersections and iterables
|
1305 |
+
args = _sympify(args)
|
1306 |
+
|
1307 |
+
# Reduce sets using known rules
|
1308 |
+
if evaluate:
|
1309 |
+
args = list(cls._new_args_filter(args))
|
1310 |
+
return simplify_union(args)
|
1311 |
+
|
1312 |
+
args = list(ordered(args, Set._infimum_key))
|
1313 |
+
|
1314 |
+
obj = Basic.__new__(cls, *args)
|
1315 |
+
obj._argset = frozenset(args)
|
1316 |
+
return obj
|
1317 |
+
|
1318 |
+
@property
|
1319 |
+
def args(self):
|
1320 |
+
return self._args
|
1321 |
+
|
1322 |
+
def _complement(self, universe):
|
1323 |
+
# DeMorgan's Law
|
1324 |
+
return Intersection(s.complement(universe) for s in self.args)
|
1325 |
+
|
1326 |
+
@property
|
1327 |
+
def _inf(self):
|
1328 |
+
# We use Min so that sup is meaningful in combination with symbolic
|
1329 |
+
# interval end points.
|
1330 |
+
return Min(*[set.inf for set in self.args])
|
1331 |
+
|
1332 |
+
@property
|
1333 |
+
def _sup(self):
|
1334 |
+
# We use Max so that sup is meaningful in combination with symbolic
|
1335 |
+
# end points.
|
1336 |
+
return Max(*[set.sup for set in self.args])
|
1337 |
+
|
1338 |
+
@property
|
1339 |
+
def is_empty(self):
|
1340 |
+
return fuzzy_and(set.is_empty for set in self.args)
|
1341 |
+
|
1342 |
+
@property
|
1343 |
+
def is_finite_set(self):
|
1344 |
+
return fuzzy_and(set.is_finite_set for set in self.args)
|
1345 |
+
|
1346 |
+
@property
|
1347 |
+
def _measure(self):
|
1348 |
+
# Measure of a union is the sum of the measures of the sets minus
|
1349 |
+
# the sum of their pairwise intersections plus the sum of their
|
1350 |
+
# triple-wise intersections minus ... etc...
|
1351 |
+
|
1352 |
+
# Sets is a collection of intersections and a set of elementary
|
1353 |
+
# sets which made up those intersections (called "sos" for set of sets)
|
1354 |
+
# An example element might of this list might be:
|
1355 |
+
# ( {A,B,C}, A.intersect(B).intersect(C) )
|
1356 |
+
|
1357 |
+
# Start with just elementary sets ( ({A}, A), ({B}, B), ... )
|
1358 |
+
# Then get and subtract ( ({A,B}, (A int B), ... ) while non-zero
|
1359 |
+
sets = [(FiniteSet(s), s) for s in self.args]
|
1360 |
+
measure = 0
|
1361 |
+
parity = 1
|
1362 |
+
while sets:
|
1363 |
+
# Add up the measure of these sets and add or subtract it to total
|
1364 |
+
measure += parity * sum(inter.measure for sos, inter in sets)
|
1365 |
+
|
1366 |
+
# For each intersection in sets, compute the intersection with every
|
1367 |
+
# other set not already part of the intersection.
|
1368 |
+
sets = ((sos + FiniteSet(newset), newset.intersect(intersection))
|
1369 |
+
for sos, intersection in sets for newset in self.args
|
1370 |
+
if newset not in sos)
|
1371 |
+
|
1372 |
+
# Clear out sets with no measure
|
1373 |
+
sets = [(sos, inter) for sos, inter in sets if inter.measure != 0]
|
1374 |
+
|
1375 |
+
# Clear out duplicates
|
1376 |
+
sos_list = []
|
1377 |
+
sets_list = []
|
1378 |
+
for _set in sets:
|
1379 |
+
if _set[0] in sos_list:
|
1380 |
+
continue
|
1381 |
+
else:
|
1382 |
+
sos_list.append(_set[0])
|
1383 |
+
sets_list.append(_set)
|
1384 |
+
sets = sets_list
|
1385 |
+
|
1386 |
+
# Flip Parity - next time subtract/add if we added/subtracted here
|
1387 |
+
parity *= -1
|
1388 |
+
return measure
|
1389 |
+
|
1390 |
+
def _kind(self):
|
1391 |
+
kinds = tuple(arg.kind for arg in self.args if arg is not S.EmptySet)
|
1392 |
+
if not kinds:
|
1393 |
+
return SetKind()
|
1394 |
+
elif all(i == kinds[0] for i in kinds):
|
1395 |
+
return kinds[0]
|
1396 |
+
else:
|
1397 |
+
return SetKind(UndefinedKind)
|
1398 |
+
|
1399 |
+
@property
|
1400 |
+
def _boundary(self):
|
1401 |
+
def boundary_of_set(i):
|
1402 |
+
""" The boundary of set i minus interior of all other sets """
|
1403 |
+
b = self.args[i].boundary
|
1404 |
+
for j, a in enumerate(self.args):
|
1405 |
+
if j != i:
|
1406 |
+
b = b - a.interior
|
1407 |
+
return b
|
1408 |
+
return Union(*map(boundary_of_set, range(len(self.args))))
|
1409 |
+
|
1410 |
+
def _contains(self, other):
|
1411 |
+
return Or(*[s.contains(other) for s in self.args])
|
1412 |
+
|
1413 |
+
def is_subset(self, other):
|
1414 |
+
return fuzzy_and(s.is_subset(other) for s in self.args)
|
1415 |
+
|
1416 |
+
def as_relational(self, symbol):
|
1417 |
+
"""Rewrite a Union in terms of equalities and logic operators. """
|
1418 |
+
if (len(self.args) == 2 and
|
1419 |
+
all(isinstance(i, Interval) for i in self.args)):
|
1420 |
+
# optimization to give 3 args as (x > 1) & (x < 5) & Ne(x, 3)
|
1421 |
+
# instead of as 4, ((1 <= x) & (x < 3)) | ((x <= 5) & (3 < x))
|
1422 |
+
# XXX: This should be ideally be improved to handle any number of
|
1423 |
+
# intervals and also not to assume that the intervals are in any
|
1424 |
+
# particular sorted order.
|
1425 |
+
a, b = self.args
|
1426 |
+
if a.sup == b.inf and a.right_open and b.left_open:
|
1427 |
+
mincond = symbol > a.inf if a.left_open else symbol >= a.inf
|
1428 |
+
maxcond = symbol < b.sup if b.right_open else symbol <= b.sup
|
1429 |
+
necond = Ne(symbol, a.sup)
|
1430 |
+
return And(necond, mincond, maxcond)
|
1431 |
+
return Or(*[i.as_relational(symbol) for i in self.args])
|
1432 |
+
|
1433 |
+
@property
|
1434 |
+
def is_iterable(self):
|
1435 |
+
return all(arg.is_iterable for arg in self.args)
|
1436 |
+
|
1437 |
+
def __iter__(self):
|
1438 |
+
return roundrobin(*(iter(arg) for arg in self.args))
|
1439 |
+
|
1440 |
+
|
1441 |
+
class Intersection(Set, LatticeOp):
|
1442 |
+
"""
|
1443 |
+
Represents an intersection of sets as a :class:`Set`.
|
1444 |
+
|
1445 |
+
Examples
|
1446 |
+
========
|
1447 |
+
|
1448 |
+
>>> from sympy import Intersection, Interval
|
1449 |
+
>>> Intersection(Interval(1, 3), Interval(2, 4))
|
1450 |
+
Interval(2, 3)
|
1451 |
+
|
1452 |
+
We often use the .intersect method
|
1453 |
+
|
1454 |
+
>>> Interval(1,3).intersect(Interval(2,4))
|
1455 |
+
Interval(2, 3)
|
1456 |
+
|
1457 |
+
See Also
|
1458 |
+
========
|
1459 |
+
|
1460 |
+
Union
|
1461 |
+
|
1462 |
+
References
|
1463 |
+
==========
|
1464 |
+
|
1465 |
+
.. [1] https://en.wikipedia.org/wiki/Intersection_%28set_theory%29
|
1466 |
+
"""
|
1467 |
+
is_Intersection = True
|
1468 |
+
|
1469 |
+
@property
|
1470 |
+
def identity(self):
|
1471 |
+
return S.UniversalSet
|
1472 |
+
|
1473 |
+
@property
|
1474 |
+
def zero(self):
|
1475 |
+
return S.EmptySet
|
1476 |
+
|
1477 |
+
def __new__(cls, *args, **kwargs):
|
1478 |
+
evaluate = kwargs.get('evaluate', global_parameters.evaluate)
|
1479 |
+
|
1480 |
+
# flatten inputs to merge intersections and iterables
|
1481 |
+
args = list(ordered(set(_sympify(args))))
|
1482 |
+
|
1483 |
+
# Reduce sets using known rules
|
1484 |
+
if evaluate:
|
1485 |
+
args = list(cls._new_args_filter(args))
|
1486 |
+
return simplify_intersection(args)
|
1487 |
+
|
1488 |
+
args = list(ordered(args, Set._infimum_key))
|
1489 |
+
|
1490 |
+
obj = Basic.__new__(cls, *args)
|
1491 |
+
obj._argset = frozenset(args)
|
1492 |
+
return obj
|
1493 |
+
|
1494 |
+
@property
|
1495 |
+
def args(self):
|
1496 |
+
return self._args
|
1497 |
+
|
1498 |
+
@property
|
1499 |
+
def is_iterable(self):
|
1500 |
+
return any(arg.is_iterable for arg in self.args)
|
1501 |
+
|
1502 |
+
@property
|
1503 |
+
def is_finite_set(self):
|
1504 |
+
if fuzzy_or(arg.is_finite_set for arg in self.args):
|
1505 |
+
return True
|
1506 |
+
|
1507 |
+
def _kind(self):
|
1508 |
+
kinds = tuple(arg.kind for arg in self.args if arg is not S.UniversalSet)
|
1509 |
+
if not kinds:
|
1510 |
+
return SetKind(UndefinedKind)
|
1511 |
+
elif all(i == kinds[0] for i in kinds):
|
1512 |
+
return kinds[0]
|
1513 |
+
else:
|
1514 |
+
return SetKind()
|
1515 |
+
|
1516 |
+
@property
|
1517 |
+
def _inf(self):
|
1518 |
+
raise NotImplementedError()
|
1519 |
+
|
1520 |
+
@property
|
1521 |
+
def _sup(self):
|
1522 |
+
raise NotImplementedError()
|
1523 |
+
|
1524 |
+
def _contains(self, other):
|
1525 |
+
return And(*[set.contains(other) for set in self.args])
|
1526 |
+
|
1527 |
+
def __iter__(self):
|
1528 |
+
sets_sift = sift(self.args, lambda x: x.is_iterable)
|
1529 |
+
|
1530 |
+
completed = False
|
1531 |
+
candidates = sets_sift[True] + sets_sift[None]
|
1532 |
+
|
1533 |
+
finite_candidates, others = [], []
|
1534 |
+
for candidate in candidates:
|
1535 |
+
length = None
|
1536 |
+
try:
|
1537 |
+
length = len(candidate)
|
1538 |
+
except TypeError:
|
1539 |
+
others.append(candidate)
|
1540 |
+
|
1541 |
+
if length is not None:
|
1542 |
+
finite_candidates.append(candidate)
|
1543 |
+
finite_candidates.sort(key=len)
|
1544 |
+
|
1545 |
+
for s in finite_candidates + others:
|
1546 |
+
other_sets = set(self.args) - {s}
|
1547 |
+
other = Intersection(*other_sets, evaluate=False)
|
1548 |
+
completed = True
|
1549 |
+
for x in s:
|
1550 |
+
try:
|
1551 |
+
if x in other:
|
1552 |
+
yield x
|
1553 |
+
except TypeError:
|
1554 |
+
completed = False
|
1555 |
+
if completed:
|
1556 |
+
return
|
1557 |
+
|
1558 |
+
if not completed:
|
1559 |
+
if not candidates:
|
1560 |
+
raise TypeError("None of the constituent sets are iterable")
|
1561 |
+
raise TypeError(
|
1562 |
+
"The computation had not completed because of the "
|
1563 |
+
"undecidable set membership is found in every candidates.")
|
1564 |
+
|
1565 |
+
@staticmethod
|
1566 |
+
def _handle_finite_sets(args):
|
1567 |
+
'''Simplify intersection of one or more FiniteSets and other sets'''
|
1568 |
+
|
1569 |
+
# First separate the FiniteSets from the others
|
1570 |
+
fs_args, others = sift(args, lambda x: x.is_FiniteSet, binary=True)
|
1571 |
+
|
1572 |
+
# Let the caller handle intersection of non-FiniteSets
|
1573 |
+
if not fs_args:
|
1574 |
+
return
|
1575 |
+
|
1576 |
+
# Convert to Python sets and build the set of all elements
|
1577 |
+
fs_sets = [set(fs) for fs in fs_args]
|
1578 |
+
all_elements = reduce(lambda a, b: a | b, fs_sets, set())
|
1579 |
+
|
1580 |
+
# Extract elements that are definitely in or definitely not in the
|
1581 |
+
# intersection. Here we check contains for all of args.
|
1582 |
+
definite = set()
|
1583 |
+
for e in all_elements:
|
1584 |
+
inall = fuzzy_and(s.contains(e) for s in args)
|
1585 |
+
if inall is True:
|
1586 |
+
definite.add(e)
|
1587 |
+
if inall is not None:
|
1588 |
+
for s in fs_sets:
|
1589 |
+
s.discard(e)
|
1590 |
+
|
1591 |
+
# At this point all elements in all of fs_sets are possibly in the
|
1592 |
+
# intersection. In some cases this is because they are definitely in
|
1593 |
+
# the intersection of the finite sets but it's not clear if they are
|
1594 |
+
# members of others. We might have {m, n}, {m}, and Reals where we
|
1595 |
+
# don't know if m or n is real. We want to remove n here but it is
|
1596 |
+
# possibly in because it might be equal to m. So what we do now is
|
1597 |
+
# extract the elements that are definitely in the remaining finite
|
1598 |
+
# sets iteratively until we end up with {n}, {}. At that point if we
|
1599 |
+
# get any empty set all remaining elements are discarded.
|
1600 |
+
|
1601 |
+
fs_elements = reduce(lambda a, b: a | b, fs_sets, set())
|
1602 |
+
|
1603 |
+
# Need fuzzy containment testing
|
1604 |
+
fs_symsets = [FiniteSet(*s) for s in fs_sets]
|
1605 |
+
|
1606 |
+
while fs_elements:
|
1607 |
+
for e in fs_elements:
|
1608 |
+
infs = fuzzy_and(s.contains(e) for s in fs_symsets)
|
1609 |
+
if infs is True:
|
1610 |
+
definite.add(e)
|
1611 |
+
if infs is not None:
|
1612 |
+
for n, s in enumerate(fs_sets):
|
1613 |
+
# Update Python set and FiniteSet
|
1614 |
+
if e in s:
|
1615 |
+
s.remove(e)
|
1616 |
+
fs_symsets[n] = FiniteSet(*s)
|
1617 |
+
fs_elements.remove(e)
|
1618 |
+
break
|
1619 |
+
# If we completed the for loop without removing anything we are
|
1620 |
+
# done so quit the outer while loop
|
1621 |
+
else:
|
1622 |
+
break
|
1623 |
+
|
1624 |
+
# If any of the sets of remainder elements is empty then we discard
|
1625 |
+
# all of them for the intersection.
|
1626 |
+
if not all(fs_sets):
|
1627 |
+
fs_sets = [set()]
|
1628 |
+
|
1629 |
+
# Here we fold back the definitely included elements into each fs.
|
1630 |
+
# Since they are definitely included they must have been members of
|
1631 |
+
# each FiniteSet to begin with. We could instead fold these in with a
|
1632 |
+
# Union at the end to get e.g. {3}|({x}&{y}) rather than {3,x}&{3,y}.
|
1633 |
+
if definite:
|
1634 |
+
fs_sets = [fs | definite for fs in fs_sets]
|
1635 |
+
|
1636 |
+
if fs_sets == [set()]:
|
1637 |
+
return S.EmptySet
|
1638 |
+
|
1639 |
+
sets = [FiniteSet(*s) for s in fs_sets]
|
1640 |
+
|
1641 |
+
# Any set in others is redundant if it contains all the elements that
|
1642 |
+
# are in the finite sets so we don't need it in the Intersection
|
1643 |
+
all_elements = reduce(lambda a, b: a | b, fs_sets, set())
|
1644 |
+
is_redundant = lambda o: all(fuzzy_bool(o.contains(e)) for e in all_elements)
|
1645 |
+
others = [o for o in others if not is_redundant(o)]
|
1646 |
+
|
1647 |
+
if others:
|
1648 |
+
rest = Intersection(*others)
|
1649 |
+
# XXX: Maybe this shortcut should be at the beginning. For large
|
1650 |
+
# FiniteSets it could much more efficient to process the other
|
1651 |
+
# sets first...
|
1652 |
+
if rest is S.EmptySet:
|
1653 |
+
return S.EmptySet
|
1654 |
+
# Flatten the Intersection
|
1655 |
+
if rest.is_Intersection:
|
1656 |
+
sets.extend(rest.args)
|
1657 |
+
else:
|
1658 |
+
sets.append(rest)
|
1659 |
+
|
1660 |
+
if len(sets) == 1:
|
1661 |
+
return sets[0]
|
1662 |
+
else:
|
1663 |
+
return Intersection(*sets, evaluate=False)
|
1664 |
+
|
1665 |
+
def as_relational(self, symbol):
|
1666 |
+
"""Rewrite an Intersection in terms of equalities and logic operators"""
|
1667 |
+
return And(*[set.as_relational(symbol) for set in self.args])
|
1668 |
+
|
1669 |
+
|
1670 |
+
class Complement(Set):
|
1671 |
+
r"""Represents the set difference or relative complement of a set with
|
1672 |
+
another set.
|
1673 |
+
|
1674 |
+
$$A - B = \{x \in A \mid x \notin B\}$$
|
1675 |
+
|
1676 |
+
|
1677 |
+
Examples
|
1678 |
+
========
|
1679 |
+
|
1680 |
+
>>> from sympy import Complement, FiniteSet
|
1681 |
+
>>> Complement(FiniteSet(0, 1, 2), FiniteSet(1))
|
1682 |
+
{0, 2}
|
1683 |
+
|
1684 |
+
See Also
|
1685 |
+
=========
|
1686 |
+
|
1687 |
+
Intersection, Union
|
1688 |
+
|
1689 |
+
References
|
1690 |
+
==========
|
1691 |
+
|
1692 |
+
.. [1] https://mathworld.wolfram.com/ComplementSet.html
|
1693 |
+
"""
|
1694 |
+
|
1695 |
+
is_Complement = True
|
1696 |
+
|
1697 |
+
def __new__(cls, a, b, evaluate=True):
|
1698 |
+
a, b = map(_sympify, (a, b))
|
1699 |
+
if evaluate:
|
1700 |
+
return Complement.reduce(a, b)
|
1701 |
+
|
1702 |
+
return Basic.__new__(cls, a, b)
|
1703 |
+
|
1704 |
+
@staticmethod
|
1705 |
+
def reduce(A, B):
|
1706 |
+
"""
|
1707 |
+
Simplify a :class:`Complement`.
|
1708 |
+
|
1709 |
+
"""
|
1710 |
+
if B == S.UniversalSet or A.is_subset(B):
|
1711 |
+
return S.EmptySet
|
1712 |
+
|
1713 |
+
if isinstance(B, Union):
|
1714 |
+
return Intersection(*(s.complement(A) for s in B.args))
|
1715 |
+
|
1716 |
+
result = B._complement(A)
|
1717 |
+
if result is not None:
|
1718 |
+
return result
|
1719 |
+
else:
|
1720 |
+
return Complement(A, B, evaluate=False)
|
1721 |
+
|
1722 |
+
def _contains(self, other):
|
1723 |
+
A = self.args[0]
|
1724 |
+
B = self.args[1]
|
1725 |
+
return And(A.contains(other), Not(B.contains(other)))
|
1726 |
+
|
1727 |
+
def as_relational(self, symbol):
|
1728 |
+
"""Rewrite a complement in terms of equalities and logic
|
1729 |
+
operators"""
|
1730 |
+
A, B = self.args
|
1731 |
+
|
1732 |
+
A_rel = A.as_relational(symbol)
|
1733 |
+
B_rel = Not(B.as_relational(symbol))
|
1734 |
+
|
1735 |
+
return And(A_rel, B_rel)
|
1736 |
+
|
1737 |
+
def _kind(self):
|
1738 |
+
return self.args[0].kind
|
1739 |
+
|
1740 |
+
@property
|
1741 |
+
def is_iterable(self):
|
1742 |
+
if self.args[0].is_iterable:
|
1743 |
+
return True
|
1744 |
+
|
1745 |
+
@property
|
1746 |
+
def is_finite_set(self):
|
1747 |
+
A, B = self.args
|
1748 |
+
a_finite = A.is_finite_set
|
1749 |
+
if a_finite is True:
|
1750 |
+
return True
|
1751 |
+
elif a_finite is False and B.is_finite_set:
|
1752 |
+
return False
|
1753 |
+
|
1754 |
+
def __iter__(self):
|
1755 |
+
A, B = self.args
|
1756 |
+
for a in A:
|
1757 |
+
if a not in B:
|
1758 |
+
yield a
|
1759 |
+
else:
|
1760 |
+
continue
|
1761 |
+
|
1762 |
+
|
1763 |
+
class EmptySet(Set, metaclass=Singleton):
|
1764 |
+
"""
|
1765 |
+
Represents the empty set. The empty set is available as a singleton
|
1766 |
+
as ``S.EmptySet``.
|
1767 |
+
|
1768 |
+
Examples
|
1769 |
+
========
|
1770 |
+
|
1771 |
+
>>> from sympy import S, Interval
|
1772 |
+
>>> S.EmptySet
|
1773 |
+
EmptySet
|
1774 |
+
|
1775 |
+
>>> Interval(1, 2).intersect(S.EmptySet)
|
1776 |
+
EmptySet
|
1777 |
+
|
1778 |
+
See Also
|
1779 |
+
========
|
1780 |
+
|
1781 |
+
UniversalSet
|
1782 |
+
|
1783 |
+
References
|
1784 |
+
==========
|
1785 |
+
|
1786 |
+
.. [1] https://en.wikipedia.org/wiki/Empty_set
|
1787 |
+
"""
|
1788 |
+
is_empty = True
|
1789 |
+
is_finite_set = True
|
1790 |
+
is_FiniteSet = True
|
1791 |
+
|
1792 |
+
@property # type: ignore
|
1793 |
+
@deprecated(
|
1794 |
+
"""
|
1795 |
+
The is_EmptySet attribute of Set objects is deprecated.
|
1796 |
+
Use 's is S.EmptySet" or 's.is_empty' instead.
|
1797 |
+
""",
|
1798 |
+
deprecated_since_version="1.5",
|
1799 |
+
active_deprecations_target="deprecated-is-emptyset",
|
1800 |
+
)
|
1801 |
+
def is_EmptySet(self):
|
1802 |
+
return True
|
1803 |
+
|
1804 |
+
@property
|
1805 |
+
def _measure(self):
|
1806 |
+
return 0
|
1807 |
+
|
1808 |
+
def _contains(self, other):
|
1809 |
+
return false
|
1810 |
+
|
1811 |
+
def as_relational(self, symbol):
|
1812 |
+
return false
|
1813 |
+
|
1814 |
+
def __len__(self):
|
1815 |
+
return 0
|
1816 |
+
|
1817 |
+
def __iter__(self):
|
1818 |
+
return iter([])
|
1819 |
+
|
1820 |
+
def _eval_powerset(self):
|
1821 |
+
return FiniteSet(self)
|
1822 |
+
|
1823 |
+
@property
|
1824 |
+
def _boundary(self):
|
1825 |
+
return self
|
1826 |
+
|
1827 |
+
def _complement(self, other):
|
1828 |
+
return other
|
1829 |
+
|
1830 |
+
def _kind(self):
|
1831 |
+
return SetKind()
|
1832 |
+
|
1833 |
+
def _symmetric_difference(self, other):
|
1834 |
+
return other
|
1835 |
+
|
1836 |
+
|
1837 |
+
class UniversalSet(Set, metaclass=Singleton):
|
1838 |
+
"""
|
1839 |
+
Represents the set of all things.
|
1840 |
+
The universal set is available as a singleton as ``S.UniversalSet``.
|
1841 |
+
|
1842 |
+
Examples
|
1843 |
+
========
|
1844 |
+
|
1845 |
+
>>> from sympy import S, Interval
|
1846 |
+
>>> S.UniversalSet
|
1847 |
+
UniversalSet
|
1848 |
+
|
1849 |
+
>>> Interval(1, 2).intersect(S.UniversalSet)
|
1850 |
+
Interval(1, 2)
|
1851 |
+
|
1852 |
+
See Also
|
1853 |
+
========
|
1854 |
+
|
1855 |
+
EmptySet
|
1856 |
+
|
1857 |
+
References
|
1858 |
+
==========
|
1859 |
+
|
1860 |
+
.. [1] https://en.wikipedia.org/wiki/Universal_set
|
1861 |
+
"""
|
1862 |
+
|
1863 |
+
is_UniversalSet = True
|
1864 |
+
is_empty = False
|
1865 |
+
is_finite_set = False
|
1866 |
+
|
1867 |
+
def _complement(self, other):
|
1868 |
+
return S.EmptySet
|
1869 |
+
|
1870 |
+
def _symmetric_difference(self, other):
|
1871 |
+
return other
|
1872 |
+
|
1873 |
+
@property
|
1874 |
+
def _measure(self):
|
1875 |
+
return S.Infinity
|
1876 |
+
|
1877 |
+
def _kind(self):
|
1878 |
+
return SetKind(UndefinedKind)
|
1879 |
+
|
1880 |
+
def _contains(self, other):
|
1881 |
+
return true
|
1882 |
+
|
1883 |
+
def as_relational(self, symbol):
|
1884 |
+
return true
|
1885 |
+
|
1886 |
+
@property
|
1887 |
+
def _boundary(self):
|
1888 |
+
return S.EmptySet
|
1889 |
+
|
1890 |
+
|
1891 |
+
class FiniteSet(Set):
|
1892 |
+
"""
|
1893 |
+
Represents a finite set of Sympy expressions.
|
1894 |
+
|
1895 |
+
Examples
|
1896 |
+
========
|
1897 |
+
|
1898 |
+
>>> from sympy import FiniteSet, Symbol, Interval, Naturals0
|
1899 |
+
>>> FiniteSet(1, 2, 3, 4)
|
1900 |
+
{1, 2, 3, 4}
|
1901 |
+
>>> 3 in FiniteSet(1, 2, 3, 4)
|
1902 |
+
True
|
1903 |
+
>>> FiniteSet(1, (1, 2), Symbol('x'))
|
1904 |
+
{1, x, (1, 2)}
|
1905 |
+
>>> FiniteSet(Interval(1, 2), Naturals0, {1, 2})
|
1906 |
+
FiniteSet({1, 2}, Interval(1, 2), Naturals0)
|
1907 |
+
>>> members = [1, 2, 3, 4]
|
1908 |
+
>>> f = FiniteSet(*members)
|
1909 |
+
>>> f
|
1910 |
+
{1, 2, 3, 4}
|
1911 |
+
>>> f - FiniteSet(2)
|
1912 |
+
{1, 3, 4}
|
1913 |
+
>>> f + FiniteSet(2, 5)
|
1914 |
+
{1, 2, 3, 4, 5}
|
1915 |
+
|
1916 |
+
References
|
1917 |
+
==========
|
1918 |
+
|
1919 |
+
.. [1] https://en.wikipedia.org/wiki/Finite_set
|
1920 |
+
"""
|
1921 |
+
is_FiniteSet = True
|
1922 |
+
is_iterable = True
|
1923 |
+
is_empty = False
|
1924 |
+
is_finite_set = True
|
1925 |
+
|
1926 |
+
def __new__(cls, *args, **kwargs):
|
1927 |
+
evaluate = kwargs.get('evaluate', global_parameters.evaluate)
|
1928 |
+
if evaluate:
|
1929 |
+
args = list(map(sympify, args))
|
1930 |
+
|
1931 |
+
if len(args) == 0:
|
1932 |
+
return S.EmptySet
|
1933 |
+
else:
|
1934 |
+
args = list(map(sympify, args))
|
1935 |
+
|
1936 |
+
# keep the form of the first canonical arg
|
1937 |
+
dargs = {}
|
1938 |
+
for i in reversed(list(ordered(args))):
|
1939 |
+
if i.is_Symbol:
|
1940 |
+
dargs[i] = i
|
1941 |
+
else:
|
1942 |
+
try:
|
1943 |
+
dargs[i.as_dummy()] = i
|
1944 |
+
except TypeError:
|
1945 |
+
# e.g. i = class without args like `Interval`
|
1946 |
+
dargs[i] = i
|
1947 |
+
_args_set = set(dargs.values())
|
1948 |
+
args = list(ordered(_args_set, Set._infimum_key))
|
1949 |
+
obj = Basic.__new__(cls, *args)
|
1950 |
+
obj._args_set = _args_set
|
1951 |
+
return obj
|
1952 |
+
|
1953 |
+
|
1954 |
+
def __iter__(self):
|
1955 |
+
return iter(self.args)
|
1956 |
+
|
1957 |
+
def _complement(self, other):
|
1958 |
+
if isinstance(other, Interval):
|
1959 |
+
# Splitting in sub-intervals is only done for S.Reals;
|
1960 |
+
# other cases that need splitting will first pass through
|
1961 |
+
# Set._complement().
|
1962 |
+
nums, syms = [], []
|
1963 |
+
for m in self.args:
|
1964 |
+
if m.is_number and m.is_real:
|
1965 |
+
nums.append(m)
|
1966 |
+
elif m.is_real == False:
|
1967 |
+
pass # drop non-reals
|
1968 |
+
else:
|
1969 |
+
syms.append(m) # various symbolic expressions
|
1970 |
+
if other == S.Reals and nums != []:
|
1971 |
+
nums.sort()
|
1972 |
+
intervals = [] # Build up a list of intervals between the elements
|
1973 |
+
intervals += [Interval(S.NegativeInfinity, nums[0], True, True)]
|
1974 |
+
for a, b in zip(nums[:-1], nums[1:]):
|
1975 |
+
intervals.append(Interval(a, b, True, True)) # both open
|
1976 |
+
intervals.append(Interval(nums[-1], S.Infinity, True, True))
|
1977 |
+
if syms != []:
|
1978 |
+
return Complement(Union(*intervals, evaluate=False),
|
1979 |
+
FiniteSet(*syms), evaluate=False)
|
1980 |
+
else:
|
1981 |
+
return Union(*intervals, evaluate=False)
|
1982 |
+
elif nums == []: # no splitting necessary or possible:
|
1983 |
+
if syms:
|
1984 |
+
return Complement(other, FiniteSet(*syms), evaluate=False)
|
1985 |
+
else:
|
1986 |
+
return other
|
1987 |
+
|
1988 |
+
elif isinstance(other, FiniteSet):
|
1989 |
+
unk = []
|
1990 |
+
for i in self:
|
1991 |
+
c = sympify(other.contains(i))
|
1992 |
+
if c is not S.true and c is not S.false:
|
1993 |
+
unk.append(i)
|
1994 |
+
unk = FiniteSet(*unk)
|
1995 |
+
if unk == self:
|
1996 |
+
return
|
1997 |
+
not_true = []
|
1998 |
+
for i in other:
|
1999 |
+
c = sympify(self.contains(i))
|
2000 |
+
if c is not S.true:
|
2001 |
+
not_true.append(i)
|
2002 |
+
return Complement(FiniteSet(*not_true), unk)
|
2003 |
+
|
2004 |
+
return Set._complement(self, other)
|
2005 |
+
|
2006 |
+
def _contains(self, other):
|
2007 |
+
"""
|
2008 |
+
Tests whether an element, other, is in the set.
|
2009 |
+
|
2010 |
+
Explanation
|
2011 |
+
===========
|
2012 |
+
|
2013 |
+
The actual test is for mathematical equality (as opposed to
|
2014 |
+
syntactical equality). In the worst case all elements of the
|
2015 |
+
set must be checked.
|
2016 |
+
|
2017 |
+
Examples
|
2018 |
+
========
|
2019 |
+
|
2020 |
+
>>> from sympy import FiniteSet
|
2021 |
+
>>> 1 in FiniteSet(1, 2)
|
2022 |
+
True
|
2023 |
+
>>> 5 in FiniteSet(1, 2)
|
2024 |
+
False
|
2025 |
+
|
2026 |
+
"""
|
2027 |
+
if other in self._args_set:
|
2028 |
+
return True
|
2029 |
+
else:
|
2030 |
+
# evaluate=True is needed to override evaluate=False context;
|
2031 |
+
# we need Eq to do the evaluation
|
2032 |
+
return fuzzy_or(fuzzy_bool(Eq(e, other, evaluate=True))
|
2033 |
+
for e in self.args)
|
2034 |
+
|
2035 |
+
def _eval_is_subset(self, other):
|
2036 |
+
return fuzzy_and(other._contains(e) for e in self.args)
|
2037 |
+
|
2038 |
+
@property
|
2039 |
+
def _boundary(self):
|
2040 |
+
return self
|
2041 |
+
|
2042 |
+
@property
|
2043 |
+
def _inf(self):
|
2044 |
+
return Min(*self)
|
2045 |
+
|
2046 |
+
@property
|
2047 |
+
def _sup(self):
|
2048 |
+
return Max(*self)
|
2049 |
+
|
2050 |
+
@property
|
2051 |
+
def measure(self):
|
2052 |
+
return 0
|
2053 |
+
|
2054 |
+
def _kind(self):
|
2055 |
+
if not self.args:
|
2056 |
+
return SetKind()
|
2057 |
+
elif all(i.kind == self.args[0].kind for i in self.args):
|
2058 |
+
return SetKind(self.args[0].kind)
|
2059 |
+
else:
|
2060 |
+
return SetKind(UndefinedKind)
|
2061 |
+
|
2062 |
+
def __len__(self):
|
2063 |
+
return len(self.args)
|
2064 |
+
|
2065 |
+
def as_relational(self, symbol):
|
2066 |
+
"""Rewrite a FiniteSet in terms of equalities and logic operators. """
|
2067 |
+
return Or(*[Eq(symbol, elem) for elem in self])
|
2068 |
+
|
2069 |
+
def compare(self, other):
|
2070 |
+
return (hash(self) - hash(other))
|
2071 |
+
|
2072 |
+
def _eval_evalf(self, prec):
|
2073 |
+
dps = prec_to_dps(prec)
|
2074 |
+
return FiniteSet(*[elem.evalf(n=dps) for elem in self])
|
2075 |
+
|
2076 |
+
def _eval_simplify(self, **kwargs):
|
2077 |
+
from sympy.simplify import simplify
|
2078 |
+
return FiniteSet(*[simplify(elem, **kwargs) for elem in self])
|
2079 |
+
|
2080 |
+
@property
|
2081 |
+
def _sorted_args(self):
|
2082 |
+
return self.args
|
2083 |
+
|
2084 |
+
def _eval_powerset(self):
|
2085 |
+
return self.func(*[self.func(*s) for s in subsets(self.args)])
|
2086 |
+
|
2087 |
+
def _eval_rewrite_as_PowerSet(self, *args, **kwargs):
|
2088 |
+
"""Rewriting method for a finite set to a power set."""
|
2089 |
+
from .powerset import PowerSet
|
2090 |
+
|
2091 |
+
is2pow = lambda n: bool(n and not n & (n - 1))
|
2092 |
+
if not is2pow(len(self)):
|
2093 |
+
return None
|
2094 |
+
|
2095 |
+
fs_test = lambda arg: isinstance(arg, Set) and arg.is_FiniteSet
|
2096 |
+
if not all(fs_test(arg) for arg in args):
|
2097 |
+
return None
|
2098 |
+
|
2099 |
+
biggest = max(args, key=len)
|
2100 |
+
for arg in subsets(biggest.args):
|
2101 |
+
arg_set = FiniteSet(*arg)
|
2102 |
+
if arg_set not in args:
|
2103 |
+
return None
|
2104 |
+
return PowerSet(biggest)
|
2105 |
+
|
2106 |
+
def __ge__(self, other):
|
2107 |
+
if not isinstance(other, Set):
|
2108 |
+
raise TypeError("Invalid comparison of set with %s" % func_name(other))
|
2109 |
+
return other.is_subset(self)
|
2110 |
+
|
2111 |
+
def __gt__(self, other):
|
2112 |
+
if not isinstance(other, Set):
|
2113 |
+
raise TypeError("Invalid comparison of set with %s" % func_name(other))
|
2114 |
+
return self.is_proper_superset(other)
|
2115 |
+
|
2116 |
+
def __le__(self, other):
|
2117 |
+
if not isinstance(other, Set):
|
2118 |
+
raise TypeError("Invalid comparison of set with %s" % func_name(other))
|
2119 |
+
return self.is_subset(other)
|
2120 |
+
|
2121 |
+
def __lt__(self, other):
|
2122 |
+
if not isinstance(other, Set):
|
2123 |
+
raise TypeError("Invalid comparison of set with %s" % func_name(other))
|
2124 |
+
return self.is_proper_subset(other)
|
2125 |
+
|
2126 |
+
def __eq__(self, other):
|
2127 |
+
if isinstance(other, (set, frozenset)):
|
2128 |
+
return self._args_set == other
|
2129 |
+
return super().__eq__(other)
|
2130 |
+
|
2131 |
+
__hash__ : Callable[[Basic], Any] = Basic.__hash__
|
2132 |
+
|
2133 |
+
_sympy_converter[set] = lambda x: FiniteSet(*x)
|
2134 |
+
_sympy_converter[frozenset] = lambda x: FiniteSet(*x)
|
2135 |
+
|
2136 |
+
|
2137 |
+
class SymmetricDifference(Set):
|
2138 |
+
"""Represents the set of elements which are in either of the
|
2139 |
+
sets and not in their intersection.
|
2140 |
+
|
2141 |
+
Examples
|
2142 |
+
========
|
2143 |
+
|
2144 |
+
>>> from sympy import SymmetricDifference, FiniteSet
|
2145 |
+
>>> SymmetricDifference(FiniteSet(1, 2, 3), FiniteSet(3, 4, 5))
|
2146 |
+
{1, 2, 4, 5}
|
2147 |
+
|
2148 |
+
See Also
|
2149 |
+
========
|
2150 |
+
|
2151 |
+
Complement, Union
|
2152 |
+
|
2153 |
+
References
|
2154 |
+
==========
|
2155 |
+
|
2156 |
+
.. [1] https://en.wikipedia.org/wiki/Symmetric_difference
|
2157 |
+
"""
|
2158 |
+
|
2159 |
+
is_SymmetricDifference = True
|
2160 |
+
|
2161 |
+
def __new__(cls, a, b, evaluate=True):
|
2162 |
+
if evaluate:
|
2163 |
+
return SymmetricDifference.reduce(a, b)
|
2164 |
+
|
2165 |
+
return Basic.__new__(cls, a, b)
|
2166 |
+
|
2167 |
+
@staticmethod
|
2168 |
+
def reduce(A, B):
|
2169 |
+
result = B._symmetric_difference(A)
|
2170 |
+
if result is not None:
|
2171 |
+
return result
|
2172 |
+
else:
|
2173 |
+
return SymmetricDifference(A, B, evaluate=False)
|
2174 |
+
|
2175 |
+
def as_relational(self, symbol):
|
2176 |
+
"""Rewrite a symmetric_difference in terms of equalities and
|
2177 |
+
logic operators"""
|
2178 |
+
A, B = self.args
|
2179 |
+
|
2180 |
+
A_rel = A.as_relational(symbol)
|
2181 |
+
B_rel = B.as_relational(symbol)
|
2182 |
+
|
2183 |
+
return Xor(A_rel, B_rel)
|
2184 |
+
|
2185 |
+
@property
|
2186 |
+
def is_iterable(self):
|
2187 |
+
if all(arg.is_iterable for arg in self.args):
|
2188 |
+
return True
|
2189 |
+
|
2190 |
+
def __iter__(self):
|
2191 |
+
|
2192 |
+
args = self.args
|
2193 |
+
union = roundrobin(*(iter(arg) for arg in args))
|
2194 |
+
|
2195 |
+
for item in union:
|
2196 |
+
count = 0
|
2197 |
+
for s in args:
|
2198 |
+
if item in s:
|
2199 |
+
count += 1
|
2200 |
+
|
2201 |
+
if count % 2 == 1:
|
2202 |
+
yield item
|
2203 |
+
|
2204 |
+
|
2205 |
+
|
2206 |
+
class DisjointUnion(Set):
|
2207 |
+
""" Represents the disjoint union (also known as the external disjoint union)
|
2208 |
+
of a finite number of sets.
|
2209 |
+
|
2210 |
+
Examples
|
2211 |
+
========
|
2212 |
+
|
2213 |
+
>>> from sympy import DisjointUnion, FiniteSet, Interval, Union, Symbol
|
2214 |
+
>>> A = FiniteSet(1, 2, 3)
|
2215 |
+
>>> B = Interval(0, 5)
|
2216 |
+
>>> DisjointUnion(A, B)
|
2217 |
+
DisjointUnion({1, 2, 3}, Interval(0, 5))
|
2218 |
+
>>> DisjointUnion(A, B).rewrite(Union)
|
2219 |
+
Union(ProductSet({1, 2, 3}, {0}), ProductSet(Interval(0, 5), {1}))
|
2220 |
+
>>> C = FiniteSet(Symbol('x'), Symbol('y'), Symbol('z'))
|
2221 |
+
>>> DisjointUnion(C, C)
|
2222 |
+
DisjointUnion({x, y, z}, {x, y, z})
|
2223 |
+
>>> DisjointUnion(C, C).rewrite(Union)
|
2224 |
+
ProductSet({x, y, z}, {0, 1})
|
2225 |
+
|
2226 |
+
References
|
2227 |
+
==========
|
2228 |
+
|
2229 |
+
https://en.wikipedia.org/wiki/Disjoint_union
|
2230 |
+
"""
|
2231 |
+
|
2232 |
+
def __new__(cls, *sets):
|
2233 |
+
dj_collection = []
|
2234 |
+
for set_i in sets:
|
2235 |
+
if isinstance(set_i, Set):
|
2236 |
+
dj_collection.append(set_i)
|
2237 |
+
else:
|
2238 |
+
raise TypeError("Invalid input: '%s', input args \
|
2239 |
+
to DisjointUnion must be Sets" % set_i)
|
2240 |
+
obj = Basic.__new__(cls, *dj_collection)
|
2241 |
+
return obj
|
2242 |
+
|
2243 |
+
@property
|
2244 |
+
def sets(self):
|
2245 |
+
return self.args
|
2246 |
+
|
2247 |
+
@property
|
2248 |
+
def is_empty(self):
|
2249 |
+
return fuzzy_and(s.is_empty for s in self.sets)
|
2250 |
+
|
2251 |
+
@property
|
2252 |
+
def is_finite_set(self):
|
2253 |
+
all_finite = fuzzy_and(s.is_finite_set for s in self.sets)
|
2254 |
+
return fuzzy_or([self.is_empty, all_finite])
|
2255 |
+
|
2256 |
+
@property
|
2257 |
+
def is_iterable(self):
|
2258 |
+
if self.is_empty:
|
2259 |
+
return False
|
2260 |
+
iter_flag = True
|
2261 |
+
for set_i in self.sets:
|
2262 |
+
if not set_i.is_empty:
|
2263 |
+
iter_flag = iter_flag and set_i.is_iterable
|
2264 |
+
return iter_flag
|
2265 |
+
|
2266 |
+
def _eval_rewrite_as_Union(self, *sets):
|
2267 |
+
"""
|
2268 |
+
Rewrites the disjoint union as the union of (``set`` x {``i``})
|
2269 |
+
where ``set`` is the element in ``sets`` at index = ``i``
|
2270 |
+
"""
|
2271 |
+
|
2272 |
+
dj_union = S.EmptySet
|
2273 |
+
index = 0
|
2274 |
+
for set_i in sets:
|
2275 |
+
if isinstance(set_i, Set):
|
2276 |
+
cross = ProductSet(set_i, FiniteSet(index))
|
2277 |
+
dj_union = Union(dj_union, cross)
|
2278 |
+
index = index + 1
|
2279 |
+
return dj_union
|
2280 |
+
|
2281 |
+
def _contains(self, element):
|
2282 |
+
"""
|
2283 |
+
``in`` operator for DisjointUnion
|
2284 |
+
|
2285 |
+
Examples
|
2286 |
+
========
|
2287 |
+
|
2288 |
+
>>> from sympy import Interval, DisjointUnion
|
2289 |
+
>>> D = DisjointUnion(Interval(0, 1), Interval(0, 2))
|
2290 |
+
>>> (0.5, 0) in D
|
2291 |
+
True
|
2292 |
+
>>> (0.5, 1) in D
|
2293 |
+
True
|
2294 |
+
>>> (1.5, 0) in D
|
2295 |
+
False
|
2296 |
+
>>> (1.5, 1) in D
|
2297 |
+
True
|
2298 |
+
|
2299 |
+
Passes operation on to constituent sets
|
2300 |
+
"""
|
2301 |
+
if not isinstance(element, Tuple) or len(element) != 2:
|
2302 |
+
return False
|
2303 |
+
|
2304 |
+
if not element[1].is_Integer:
|
2305 |
+
return False
|
2306 |
+
|
2307 |
+
if element[1] >= len(self.sets) or element[1] < 0:
|
2308 |
+
return False
|
2309 |
+
|
2310 |
+
return element[0] in self.sets[element[1]]
|
2311 |
+
|
2312 |
+
def _kind(self):
|
2313 |
+
if not self.args:
|
2314 |
+
return SetKind()
|
2315 |
+
elif all(i.kind == self.args[0].kind for i in self.args):
|
2316 |
+
return self.args[0].kind
|
2317 |
+
else:
|
2318 |
+
return SetKind(UndefinedKind)
|
2319 |
+
|
2320 |
+
def __iter__(self):
|
2321 |
+
if self.is_iterable:
|
2322 |
+
|
2323 |
+
iters = []
|
2324 |
+
for i, s in enumerate(self.sets):
|
2325 |
+
iters.append(iproduct(s, {Integer(i)}))
|
2326 |
+
|
2327 |
+
return iter(roundrobin(*iters))
|
2328 |
+
else:
|
2329 |
+
raise ValueError("'%s' is not iterable." % self)
|
2330 |
+
|
2331 |
+
def __len__(self):
|
2332 |
+
"""
|
2333 |
+
Returns the length of the disjoint union, i.e., the number of elements in the set.
|
2334 |
+
|
2335 |
+
Examples
|
2336 |
+
========
|
2337 |
+
|
2338 |
+
>>> from sympy import FiniteSet, DisjointUnion, EmptySet
|
2339 |
+
>>> D1 = DisjointUnion(FiniteSet(1, 2, 3, 4), EmptySet, FiniteSet(3, 4, 5))
|
2340 |
+
>>> len(D1)
|
2341 |
+
7
|
2342 |
+
>>> D2 = DisjointUnion(FiniteSet(3, 5, 7), EmptySet, FiniteSet(3, 5, 7))
|
2343 |
+
>>> len(D2)
|
2344 |
+
6
|
2345 |
+
>>> D3 = DisjointUnion(EmptySet, EmptySet)
|
2346 |
+
>>> len(D3)
|
2347 |
+
0
|
2348 |
+
|
2349 |
+
Adds up the lengths of the constituent sets.
|
2350 |
+
"""
|
2351 |
+
|
2352 |
+
if self.is_finite_set:
|
2353 |
+
size = 0
|
2354 |
+
for set in self.sets:
|
2355 |
+
size += len(set)
|
2356 |
+
return size
|
2357 |
+
else:
|
2358 |
+
raise ValueError("'%s' is not a finite set." % self)
|
2359 |
+
|
2360 |
+
|
2361 |
+
def imageset(*args):
|
2362 |
+
r"""
|
2363 |
+
Return an image of the set under transformation ``f``.
|
2364 |
+
|
2365 |
+
Explanation
|
2366 |
+
===========
|
2367 |
+
|
2368 |
+
If this function cannot compute the image, it returns an
|
2369 |
+
unevaluated ImageSet object.
|
2370 |
+
|
2371 |
+
.. math::
|
2372 |
+
\{ f(x) \mid x \in \mathrm{self} \}
|
2373 |
+
|
2374 |
+
Examples
|
2375 |
+
========
|
2376 |
+
|
2377 |
+
>>> from sympy import S, Interval, imageset, sin, Lambda
|
2378 |
+
>>> from sympy.abc import x
|
2379 |
+
|
2380 |
+
>>> imageset(x, 2*x, Interval(0, 2))
|
2381 |
+
Interval(0, 4)
|
2382 |
+
|
2383 |
+
>>> imageset(lambda x: 2*x, Interval(0, 2))
|
2384 |
+
Interval(0, 4)
|
2385 |
+
|
2386 |
+
>>> imageset(Lambda(x, sin(x)), Interval(-2, 1))
|
2387 |
+
ImageSet(Lambda(x, sin(x)), Interval(-2, 1))
|
2388 |
+
|
2389 |
+
>>> imageset(sin, Interval(-2, 1))
|
2390 |
+
ImageSet(Lambda(x, sin(x)), Interval(-2, 1))
|
2391 |
+
>>> imageset(lambda y: x + y, Interval(-2, 1))
|
2392 |
+
ImageSet(Lambda(y, x + y), Interval(-2, 1))
|
2393 |
+
|
2394 |
+
Expressions applied to the set of Integers are simplified
|
2395 |
+
to show as few negatives as possible and linear expressions
|
2396 |
+
are converted to a canonical form. If this is not desirable
|
2397 |
+
then the unevaluated ImageSet should be used.
|
2398 |
+
|
2399 |
+
>>> imageset(x, -2*x + 5, S.Integers)
|
2400 |
+
ImageSet(Lambda(x, 2*x + 1), Integers)
|
2401 |
+
|
2402 |
+
See Also
|
2403 |
+
========
|
2404 |
+
|
2405 |
+
sympy.sets.fancysets.ImageSet
|
2406 |
+
|
2407 |
+
"""
|
2408 |
+
from .fancysets import ImageSet
|
2409 |
+
from .setexpr import set_function
|
2410 |
+
|
2411 |
+
if len(args) < 2:
|
2412 |
+
raise ValueError('imageset expects at least 2 args, got: %s' % len(args))
|
2413 |
+
|
2414 |
+
if isinstance(args[0], (Symbol, tuple)) and len(args) > 2:
|
2415 |
+
f = Lambda(args[0], args[1])
|
2416 |
+
set_list = args[2:]
|
2417 |
+
else:
|
2418 |
+
f = args[0]
|
2419 |
+
set_list = args[1:]
|
2420 |
+
|
2421 |
+
if isinstance(f, Lambda):
|
2422 |
+
pass
|
2423 |
+
elif callable(f):
|
2424 |
+
nargs = getattr(f, 'nargs', {})
|
2425 |
+
if nargs:
|
2426 |
+
if len(nargs) != 1:
|
2427 |
+
raise NotImplementedError(filldedent('''
|
2428 |
+
This function can take more than 1 arg
|
2429 |
+
but the potentially complicated set input
|
2430 |
+
has not been analyzed at this point to
|
2431 |
+
know its dimensions. TODO
|
2432 |
+
'''))
|
2433 |
+
N = nargs.args[0]
|
2434 |
+
if N == 1:
|
2435 |
+
s = 'x'
|
2436 |
+
else:
|
2437 |
+
s = [Symbol('x%i' % i) for i in range(1, N + 1)]
|
2438 |
+
else:
|
2439 |
+
s = inspect.signature(f).parameters
|
2440 |
+
|
2441 |
+
dexpr = _sympify(f(*[Dummy() for i in s]))
|
2442 |
+
var = tuple(uniquely_named_symbol(
|
2443 |
+
Symbol(i), dexpr) for i in s)
|
2444 |
+
f = Lambda(var, f(*var))
|
2445 |
+
else:
|
2446 |
+
raise TypeError(filldedent('''
|
2447 |
+
expecting lambda, Lambda, or FunctionClass,
|
2448 |
+
not \'%s\'.''' % func_name(f)))
|
2449 |
+
|
2450 |
+
if any(not isinstance(s, Set) for s in set_list):
|
2451 |
+
name = [func_name(s) for s in set_list]
|
2452 |
+
raise ValueError(
|
2453 |
+
'arguments after mapping should be sets, not %s' % name)
|
2454 |
+
|
2455 |
+
if len(set_list) == 1:
|
2456 |
+
set = set_list[0]
|
2457 |
+
try:
|
2458 |
+
# TypeError if arg count != set dimensions
|
2459 |
+
r = set_function(f, set)
|
2460 |
+
if r is None:
|
2461 |
+
raise TypeError
|
2462 |
+
if not r:
|
2463 |
+
return r
|
2464 |
+
except TypeError:
|
2465 |
+
r = ImageSet(f, set)
|
2466 |
+
if isinstance(r, ImageSet):
|
2467 |
+
f, set = r.args
|
2468 |
+
|
2469 |
+
if f.variables[0] == f.expr:
|
2470 |
+
return set
|
2471 |
+
|
2472 |
+
if isinstance(set, ImageSet):
|
2473 |
+
# XXX: Maybe this should just be:
|
2474 |
+
# f2 = set.lambda
|
2475 |
+
# fun = Lambda(f2.signature, f(*f2.expr))
|
2476 |
+
# return imageset(fun, *set.base_sets)
|
2477 |
+
if len(set.lamda.variables) == 1 and len(f.variables) == 1:
|
2478 |
+
x = set.lamda.variables[0]
|
2479 |
+
y = f.variables[0]
|
2480 |
+
return imageset(
|
2481 |
+
Lambda(x, f.expr.subs(y, set.lamda.expr)), *set.base_sets)
|
2482 |
+
|
2483 |
+
if r is not None:
|
2484 |
+
return r
|
2485 |
+
|
2486 |
+
return ImageSet(f, *set_list)
|
2487 |
+
|
2488 |
+
|
2489 |
+
def is_function_invertible_in_set(func, setv):
|
2490 |
+
"""
|
2491 |
+
Checks whether function ``func`` is invertible when the domain is
|
2492 |
+
restricted to set ``setv``.
|
2493 |
+
"""
|
2494 |
+
# Functions known to always be invertible:
|
2495 |
+
if func in (exp, log):
|
2496 |
+
return True
|
2497 |
+
u = Dummy("u")
|
2498 |
+
fdiff = func(u).diff(u)
|
2499 |
+
# monotonous functions:
|
2500 |
+
# TODO: check subsets (`func` in `setv`)
|
2501 |
+
if (fdiff > 0) == True or (fdiff < 0) == True:
|
2502 |
+
return True
|
2503 |
+
# TODO: support more
|
2504 |
+
return None
|
2505 |
+
|
2506 |
+
|
2507 |
+
def simplify_union(args):
|
2508 |
+
"""
|
2509 |
+
Simplify a :class:`Union` using known rules.
|
2510 |
+
|
2511 |
+
Explanation
|
2512 |
+
===========
|
2513 |
+
|
2514 |
+
We first start with global rules like 'Merge all FiniteSets'
|
2515 |
+
|
2516 |
+
Then we iterate through all pairs and ask the constituent sets if they
|
2517 |
+
can simplify themselves with any other constituent. This process depends
|
2518 |
+
on ``union_sets(a, b)`` functions.
|
2519 |
+
"""
|
2520 |
+
from sympy.sets.handlers.union import union_sets
|
2521 |
+
|
2522 |
+
# ===== Global Rules =====
|
2523 |
+
if not args:
|
2524 |
+
return S.EmptySet
|
2525 |
+
|
2526 |
+
for arg in args:
|
2527 |
+
if not isinstance(arg, Set):
|
2528 |
+
raise TypeError("Input args to Union must be Sets")
|
2529 |
+
|
2530 |
+
# Merge all finite sets
|
2531 |
+
finite_sets = [x for x in args if x.is_FiniteSet]
|
2532 |
+
if len(finite_sets) > 1:
|
2533 |
+
a = (x for set in finite_sets for x in set)
|
2534 |
+
finite_set = FiniteSet(*a)
|
2535 |
+
args = [finite_set] + [x for x in args if not x.is_FiniteSet]
|
2536 |
+
|
2537 |
+
# ===== Pair-wise Rules =====
|
2538 |
+
# Here we depend on rules built into the constituent sets
|
2539 |
+
args = set(args)
|
2540 |
+
new_args = True
|
2541 |
+
while new_args:
|
2542 |
+
for s in args:
|
2543 |
+
new_args = False
|
2544 |
+
for t in args - {s}:
|
2545 |
+
new_set = union_sets(s, t)
|
2546 |
+
# This returns None if s does not know how to intersect
|
2547 |
+
# with t. Returns the newly intersected set otherwise
|
2548 |
+
if new_set is not None:
|
2549 |
+
if not isinstance(new_set, set):
|
2550 |
+
new_set = {new_set}
|
2551 |
+
new_args = (args - {s, t}).union(new_set)
|
2552 |
+
break
|
2553 |
+
if new_args:
|
2554 |
+
args = new_args
|
2555 |
+
break
|
2556 |
+
|
2557 |
+
if len(args) == 1:
|
2558 |
+
return args.pop()
|
2559 |
+
else:
|
2560 |
+
return Union(*args, evaluate=False)
|
2561 |
+
|
2562 |
+
|
2563 |
+
def simplify_intersection(args):
|
2564 |
+
"""
|
2565 |
+
Simplify an intersection using known rules.
|
2566 |
+
|
2567 |
+
Explanation
|
2568 |
+
===========
|
2569 |
+
|
2570 |
+
We first start with global rules like
|
2571 |
+
'if any empty sets return empty set' and 'distribute any unions'
|
2572 |
+
|
2573 |
+
Then we iterate through all pairs and ask the constituent sets if they
|
2574 |
+
can simplify themselves with any other constituent
|
2575 |
+
"""
|
2576 |
+
|
2577 |
+
# ===== Global Rules =====
|
2578 |
+
if not args:
|
2579 |
+
return S.UniversalSet
|
2580 |
+
|
2581 |
+
for arg in args:
|
2582 |
+
if not isinstance(arg, Set):
|
2583 |
+
raise TypeError("Input args to Union must be Sets")
|
2584 |
+
|
2585 |
+
# If any EmptySets return EmptySet
|
2586 |
+
if S.EmptySet in args:
|
2587 |
+
return S.EmptySet
|
2588 |
+
|
2589 |
+
# Handle Finite sets
|
2590 |
+
rv = Intersection._handle_finite_sets(args)
|
2591 |
+
|
2592 |
+
if rv is not None:
|
2593 |
+
return rv
|
2594 |
+
|
2595 |
+
# If any of the sets are unions, return a Union of Intersections
|
2596 |
+
for s in args:
|
2597 |
+
if s.is_Union:
|
2598 |
+
other_sets = set(args) - {s}
|
2599 |
+
if len(other_sets) > 0:
|
2600 |
+
other = Intersection(*other_sets)
|
2601 |
+
return Union(*(Intersection(arg, other) for arg in s.args))
|
2602 |
+
else:
|
2603 |
+
return Union(*s.args)
|
2604 |
+
|
2605 |
+
for s in args:
|
2606 |
+
if s.is_Complement:
|
2607 |
+
args.remove(s)
|
2608 |
+
other_sets = args + [s.args[0]]
|
2609 |
+
return Complement(Intersection(*other_sets), s.args[1])
|
2610 |
+
|
2611 |
+
from sympy.sets.handlers.intersection import intersection_sets
|
2612 |
+
|
2613 |
+
# At this stage we are guaranteed not to have any
|
2614 |
+
# EmptySets, FiniteSets, or Unions in the intersection
|
2615 |
+
|
2616 |
+
# ===== Pair-wise Rules =====
|
2617 |
+
# Here we depend on rules built into the constituent sets
|
2618 |
+
args = set(args)
|
2619 |
+
new_args = True
|
2620 |
+
while new_args:
|
2621 |
+
for s in args:
|
2622 |
+
new_args = False
|
2623 |
+
for t in args - {s}:
|
2624 |
+
new_set = intersection_sets(s, t)
|
2625 |
+
# This returns None if s does not know how to intersect
|
2626 |
+
# with t. Returns the newly intersected set otherwise
|
2627 |
+
|
2628 |
+
if new_set is not None:
|
2629 |
+
new_args = (args - {s, t}).union({new_set})
|
2630 |
+
break
|
2631 |
+
if new_args:
|
2632 |
+
args = new_args
|
2633 |
+
break
|
2634 |
+
|
2635 |
+
if len(args) == 1:
|
2636 |
+
return args.pop()
|
2637 |
+
else:
|
2638 |
+
return Intersection(*args, evaluate=False)
|
2639 |
+
|
2640 |
+
|
2641 |
+
def _handle_finite_sets(op, x, y, commutative):
|
2642 |
+
# Handle finite sets:
|
2643 |
+
fs_args, other = sift([x, y], lambda x: isinstance(x, FiniteSet), binary=True)
|
2644 |
+
if len(fs_args) == 2:
|
2645 |
+
return FiniteSet(*[op(i, j) for i in fs_args[0] for j in fs_args[1]])
|
2646 |
+
elif len(fs_args) == 1:
|
2647 |
+
sets = [_apply_operation(op, other[0], i, commutative) for i in fs_args[0]]
|
2648 |
+
return Union(*sets)
|
2649 |
+
else:
|
2650 |
+
return None
|
2651 |
+
|
2652 |
+
|
2653 |
+
def _apply_operation(op, x, y, commutative):
|
2654 |
+
from .fancysets import ImageSet
|
2655 |
+
d = Dummy('d')
|
2656 |
+
|
2657 |
+
out = _handle_finite_sets(op, x, y, commutative)
|
2658 |
+
if out is None:
|
2659 |
+
out = op(x, y)
|
2660 |
+
|
2661 |
+
if out is None and commutative:
|
2662 |
+
out = op(y, x)
|
2663 |
+
if out is None:
|
2664 |
+
_x, _y = symbols("x y")
|
2665 |
+
if isinstance(x, Set) and not isinstance(y, Set):
|
2666 |
+
out = ImageSet(Lambda(d, op(d, y)), x).doit()
|
2667 |
+
elif not isinstance(x, Set) and isinstance(y, Set):
|
2668 |
+
out = ImageSet(Lambda(d, op(x, d)), y).doit()
|
2669 |
+
else:
|
2670 |
+
out = ImageSet(Lambda((_x, _y), op(_x, _y)), x, y)
|
2671 |
+
return out
|
2672 |
+
|
2673 |
+
|
2674 |
+
def set_add(x, y):
|
2675 |
+
from sympy.sets.handlers.add import _set_add
|
2676 |
+
return _apply_operation(_set_add, x, y, commutative=True)
|
2677 |
+
|
2678 |
+
|
2679 |
+
def set_sub(x, y):
|
2680 |
+
from sympy.sets.handlers.add import _set_sub
|
2681 |
+
return _apply_operation(_set_sub, x, y, commutative=False)
|
2682 |
+
|
2683 |
+
|
2684 |
+
def set_mul(x, y):
|
2685 |
+
from sympy.sets.handlers.mul import _set_mul
|
2686 |
+
return _apply_operation(_set_mul, x, y, commutative=True)
|
2687 |
+
|
2688 |
+
|
2689 |
+
def set_div(x, y):
|
2690 |
+
from sympy.sets.handlers.mul import _set_div
|
2691 |
+
return _apply_operation(_set_div, x, y, commutative=False)
|
2692 |
+
|
2693 |
+
|
2694 |
+
def set_pow(x, y):
|
2695 |
+
from sympy.sets.handlers.power import _set_pow
|
2696 |
+
return _apply_operation(_set_pow, x, y, commutative=False)
|
2697 |
+
|
2698 |
+
|
2699 |
+
def set_function(f, x):
|
2700 |
+
from sympy.sets.handlers.functions import _set_function
|
2701 |
+
return _set_function(f, x)
|
2702 |
+
|
2703 |
+
|
2704 |
+
class SetKind(Kind):
|
2705 |
+
"""
|
2706 |
+
SetKind is kind for all Sets
|
2707 |
+
|
2708 |
+
Every instance of Set will have kind ``SetKind`` parametrised by the kind
|
2709 |
+
of the elements of the ``Set``. The kind of the elements might be
|
2710 |
+
``NumberKind``, or ``TupleKind`` or something else. When not all elements
|
2711 |
+
have the same kind then the kind of the elements will be given as
|
2712 |
+
``UndefinedKind``.
|
2713 |
+
|
2714 |
+
Parameters
|
2715 |
+
==========
|
2716 |
+
|
2717 |
+
element_kind: Kind (optional)
|
2718 |
+
The kind of the elements of the set. In a well defined set all elements
|
2719 |
+
will have the same kind. Otherwise the kind should
|
2720 |
+
:class:`sympy.core.kind.UndefinedKind`. The ``element_kind`` argument is optional but
|
2721 |
+
should only be omitted in the case of ``EmptySet`` whose kind is simply
|
2722 |
+
``SetKind()``
|
2723 |
+
|
2724 |
+
Examples
|
2725 |
+
========
|
2726 |
+
|
2727 |
+
>>> from sympy import Interval
|
2728 |
+
>>> Interval(1, 2).kind
|
2729 |
+
SetKind(NumberKind)
|
2730 |
+
>>> Interval(1,2).kind.element_kind
|
2731 |
+
NumberKind
|
2732 |
+
|
2733 |
+
See Also
|
2734 |
+
========
|
2735 |
+
|
2736 |
+
sympy.core.kind.NumberKind
|
2737 |
+
sympy.matrices.common.MatrixKind
|
2738 |
+
sympy.core.containers.TupleKind
|
2739 |
+
"""
|
2740 |
+
def __new__(cls, element_kind=None):
|
2741 |
+
obj = super().__new__(cls, element_kind)
|
2742 |
+
obj.element_kind = element_kind
|
2743 |
+
return obj
|
2744 |
+
|
2745 |
+
def __repr__(self):
|
2746 |
+
if not self.element_kind:
|
2747 |
+
return "SetKind()"
|
2748 |
+
else:
|
2749 |
+
return "SetKind(%s)" % self.element_kind
|
env-llmeval/lib/python3.10/site-packages/sympy/sets/tests/__init__.py
ADDED
File without changes
|
env-llmeval/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (181 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_conditionset.cpython-310.pyc
ADDED
Binary file (10.5 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_contains.cpython-310.pyc
ADDED
Binary file (2.34 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_fancysets.cpython-310.pyc
ADDED
Binary file (49.9 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_ordinals.cpython-310.pyc
ADDED
Binary file (3.08 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_powerset.cpython-310.pyc
ADDED
Binary file (4.2 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_setexpr.cpython-310.pyc
ADDED
Binary file (10 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_sets.cpython-310.pyc
ADDED
Binary file (62.8 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/sets/tests/test_conditionset.py
ADDED
@@ -0,0 +1,294 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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5 |
+
from sympy.core.function import (Function, Lambda)
|
6 |
+
from sympy.core.mod import Mod
|
7 |
+
from sympy.core.kind import NumberKind
|
8 |
+
from sympy.core.numbers import (oo, pi)
|
9 |
+
from sympy.core.relational import (Eq, Ne)
|
10 |
+
from sympy.core.singleton import S
|
11 |
+
from sympy.core.symbol import (Symbol, symbols)
|
12 |
+
from sympy.functions.elementary.complexes import Abs
|
13 |
+
from sympy.functions.elementary.trigonometric import (asin, sin)
|
14 |
+
from sympy.logic.boolalg import And
|
15 |
+
from sympy.matrices.dense import Matrix
|
16 |
+
from sympy.matrices.expressions.matexpr import MatrixSymbol
|
17 |
+
from sympy.sets.sets import Interval
|
18 |
+
from sympy.testing.pytest import raises, warns_deprecated_sympy
|
19 |
+
|
20 |
+
|
21 |
+
w = Symbol('w')
|
22 |
+
x = Symbol('x')
|
23 |
+
y = Symbol('y')
|
24 |
+
z = Symbol('z')
|
25 |
+
f = Function('f')
|
26 |
+
|
27 |
+
|
28 |
+
def test_CondSet():
|
29 |
+
sin_sols_principal = ConditionSet(x, Eq(sin(x), 0),
|
30 |
+
Interval(0, 2*pi, False, True))
|
31 |
+
assert pi in sin_sols_principal
|
32 |
+
assert pi/2 not in sin_sols_principal
|
33 |
+
assert 3*pi not in sin_sols_principal
|
34 |
+
assert oo not in sin_sols_principal
|
35 |
+
assert 5 in ConditionSet(x, x**2 > 4, S.Reals)
|
36 |
+
assert 1 not in ConditionSet(x, x**2 > 4, S.Reals)
|
37 |
+
# in this case, 0 is not part of the base set so
|
38 |
+
# it can't be in any subset selected by the condition
|
39 |
+
assert 0 not in ConditionSet(x, y > 5, Interval(1, 7))
|
40 |
+
# since 'in' requires a true/false, the following raises
|
41 |
+
# an error because the given value provides no information
|
42 |
+
# for the condition to evaluate (since the condition does
|
43 |
+
# not depend on the dummy symbol): the result is `y > 5`.
|
44 |
+
# In this case, ConditionSet is just acting like
|
45 |
+
# Piecewise((Interval(1, 7), y > 5), (S.EmptySet, True)).
|
46 |
+
raises(TypeError, lambda: 6 in ConditionSet(x, y > 5,
|
47 |
+
Interval(1, 7)))
|
48 |
+
|
49 |
+
X = MatrixSymbol('X', 2, 2)
|
50 |
+
matrix_set = ConditionSet(X, Eq(X*Matrix([[1, 1], [1, 1]]), X))
|
51 |
+
Y = Matrix([[0, 0], [0, 0]])
|
52 |
+
assert matrix_set.contains(Y).doit() is S.true
|
53 |
+
Z = Matrix([[1, 2], [3, 4]])
|
54 |
+
assert matrix_set.contains(Z).doit() is S.false
|
55 |
+
|
56 |
+
assert isinstance(ConditionSet(x, x < 1, {x, y}).base_set,
|
57 |
+
FiniteSet)
|
58 |
+
raises(TypeError, lambda: ConditionSet(x, x + 1, {x, y}))
|
59 |
+
raises(TypeError, lambda: ConditionSet(x, x, 1))
|
60 |
+
|
61 |
+
I = S.Integers
|
62 |
+
U = S.UniversalSet
|
63 |
+
C = ConditionSet
|
64 |
+
assert C(x, False, I) is S.EmptySet
|
65 |
+
assert C(x, True, I) is I
|
66 |
+
assert C(x, x < 1, C(x, x < 2, I)
|
67 |
+
) == C(x, (x < 1) & (x < 2), I)
|
68 |
+
assert C(y, y < 1, C(x, y < 2, I)
|
69 |
+
) == C(x, (x < 1) & (y < 2), I), C(y, y < 1, C(x, y < 2, I))
|
70 |
+
assert C(y, y < 1, C(x, x < 2, I)
|
71 |
+
) == C(y, (y < 1) & (y < 2), I)
|
72 |
+
assert C(y, y < 1, C(x, y < x, I)
|
73 |
+
) == C(x, (x < 1) & (y < x), I)
|
74 |
+
assert unchanged(C, y, x < 1, C(x, y < x, I))
|
75 |
+
assert ConditionSet(x, x < 1).base_set is U
|
76 |
+
# arg checking is not done at instantiation but this
|
77 |
+
# will raise an error when containment is tested
|
78 |
+
assert ConditionSet((x,), x < 1).base_set is U
|
79 |
+
|
80 |
+
c = ConditionSet((x, y), x < y, I**2)
|
81 |
+
assert (1, 2) in c
|
82 |
+
assert (1, pi) not in c
|
83 |
+
|
84 |
+
raises(TypeError, lambda: C(x, x > 1, C((x, y), x > 1, I**2)))
|
85 |
+
# signature mismatch since only 3 args are accepted
|
86 |
+
raises(TypeError, lambda: C((x, y), x + y < 2, U, U))
|
87 |
+
|
88 |
+
|
89 |
+
def test_CondSet_intersect():
|
90 |
+
input_conditionset = ConditionSet(x, x**2 > 4, Interval(1, 4, False,
|
91 |
+
False))
|
92 |
+
other_domain = Interval(0, 3, False, False)
|
93 |
+
output_conditionset = ConditionSet(x, x**2 > 4, Interval(
|
94 |
+
1, 3, False, False))
|
95 |
+
assert Intersection(input_conditionset, other_domain
|
96 |
+
) == output_conditionset
|
97 |
+
|
98 |
+
|
99 |
+
def test_issue_9849():
|
100 |
+
assert ConditionSet(x, Eq(x, x), S.Naturals
|
101 |
+
) is S.Naturals
|
102 |
+
assert ConditionSet(x, Eq(Abs(sin(x)), -1), S.Naturals
|
103 |
+
) == S.EmptySet
|
104 |
+
|
105 |
+
|
106 |
+
def test_simplified_FiniteSet_in_CondSet():
|
107 |
+
assert ConditionSet(x, And(x < 1, x > -3), FiniteSet(0, 1, 2)
|
108 |
+
) == FiniteSet(0)
|
109 |
+
assert ConditionSet(x, x < 0, FiniteSet(0, 1, 2)) == EmptySet
|
110 |
+
assert ConditionSet(x, And(x < -3), EmptySet) == EmptySet
|
111 |
+
y = Symbol('y')
|
112 |
+
assert (ConditionSet(x, And(x > 0), FiniteSet(-1, 0, 1, y)) ==
|
113 |
+
Union(FiniteSet(1), ConditionSet(x, And(x > 0), FiniteSet(y))))
|
114 |
+
assert (ConditionSet(x, Eq(Mod(x, 3), 1), FiniteSet(1, 4, 2, y)) ==
|
115 |
+
Union(FiniteSet(1, 4), ConditionSet(x, Eq(Mod(x, 3), 1),
|
116 |
+
FiniteSet(y))))
|
117 |
+
|
118 |
+
|
119 |
+
def test_free_symbols():
|
120 |
+
assert ConditionSet(x, Eq(y, 0), FiniteSet(z)
|
121 |
+
).free_symbols == {y, z}
|
122 |
+
assert ConditionSet(x, Eq(x, 0), FiniteSet(z)
|
123 |
+
).free_symbols == {z}
|
124 |
+
assert ConditionSet(x, Eq(x, 0), FiniteSet(x, z)
|
125 |
+
).free_symbols == {x, z}
|
126 |
+
assert ConditionSet(x, Eq(x, 0), ImageSet(Lambda(y, y**2),
|
127 |
+
S.Integers)).free_symbols == set()
|
128 |
+
|
129 |
+
|
130 |
+
def test_bound_symbols():
|
131 |
+
assert ConditionSet(x, Eq(y, 0), FiniteSet(z)
|
132 |
+
).bound_symbols == [x]
|
133 |
+
assert ConditionSet(x, Eq(x, 0), FiniteSet(x, y)
|
134 |
+
).bound_symbols == [x]
|
135 |
+
assert ConditionSet(x, x < 10, ImageSet(Lambda(y, y**2), S.Integers)
|
136 |
+
).bound_symbols == [x]
|
137 |
+
assert ConditionSet(x, x < 10, ConditionSet(y, y > 1, S.Integers)
|
138 |
+
).bound_symbols == [x]
|
139 |
+
|
140 |
+
|
141 |
+
def test_as_dummy():
|
142 |
+
_0, _1 = symbols('_0 _1')
|
143 |
+
assert ConditionSet(x, x < 1, Interval(y, oo)
|
144 |
+
).as_dummy() == ConditionSet(_0, _0 < 1, Interval(y, oo))
|
145 |
+
assert ConditionSet(x, x < 1, Interval(x, oo)
|
146 |
+
).as_dummy() == ConditionSet(_0, _0 < 1, Interval(x, oo))
|
147 |
+
assert ConditionSet(x, x < 1, ImageSet(Lambda(y, y**2), S.Integers)
|
148 |
+
).as_dummy() == ConditionSet(
|
149 |
+
_0, _0 < 1, ImageSet(Lambda(_0, _0**2), S.Integers))
|
150 |
+
e = ConditionSet((x, y), x <= y, S.Reals**2)
|
151 |
+
assert e.bound_symbols == [x, y]
|
152 |
+
assert e.as_dummy() == ConditionSet((_0, _1), _0 <= _1, S.Reals**2)
|
153 |
+
assert e.as_dummy() == ConditionSet((y, x), y <= x, S.Reals**2
|
154 |
+
).as_dummy()
|
155 |
+
|
156 |
+
|
157 |
+
def test_subs_CondSet():
|
158 |
+
s = FiniteSet(z, y)
|
159 |
+
c = ConditionSet(x, x < 2, s)
|
160 |
+
assert c.subs(x, y) == c
|
161 |
+
assert c.subs(z, y) == ConditionSet(x, x < 2, FiniteSet(y))
|
162 |
+
assert c.xreplace({x: y}) == ConditionSet(y, y < 2, s)
|
163 |
+
|
164 |
+
assert ConditionSet(x, x < y, s
|
165 |
+
).subs(y, w) == ConditionSet(x, x < w, s.subs(y, w))
|
166 |
+
# if the user uses assumptions that cause the condition
|
167 |
+
# to evaluate, that can't be helped from SymPy's end
|
168 |
+
n = Symbol('n', negative=True)
|
169 |
+
assert ConditionSet(n, 0 < n, S.Integers) is S.EmptySet
|
170 |
+
p = Symbol('p', positive=True)
|
171 |
+
assert ConditionSet(n, n < y, S.Integers
|
172 |
+
).subs(n, x) == ConditionSet(n, n < y, S.Integers)
|
173 |
+
raises(ValueError, lambda: ConditionSet(
|
174 |
+
x + 1, x < 1, S.Integers))
|
175 |
+
assert ConditionSet(
|
176 |
+
p, n < x, Interval(-5, 5)).subs(x, p) == Interval(-5, 5), ConditionSet(
|
177 |
+
p, n < x, Interval(-5, 5)).subs(x, p)
|
178 |
+
assert ConditionSet(
|
179 |
+
n, n < x, Interval(-oo, 0)).subs(x, p
|
180 |
+
) == Interval(-oo, 0)
|
181 |
+
|
182 |
+
assert ConditionSet(f(x), f(x) < 1, {w, z}
|
183 |
+
).subs(f(x), y) == ConditionSet(f(x), f(x) < 1, {w, z})
|
184 |
+
|
185 |
+
# issue 17341
|
186 |
+
k = Symbol('k')
|
187 |
+
img1 = ImageSet(Lambda(k, 2*k*pi + asin(y)), S.Integers)
|
188 |
+
img2 = ImageSet(Lambda(k, 2*k*pi + asin(S.One/3)), S.Integers)
|
189 |
+
assert ConditionSet(x, Contains(
|
190 |
+
y, Interval(-1,1)), img1).subs(y, S.One/3).dummy_eq(img2)
|
191 |
+
|
192 |
+
assert (0, 1) in ConditionSet((x, y), x + y < 3, S.Integers**2)
|
193 |
+
|
194 |
+
raises(TypeError, lambda: ConditionSet(n, n < -10, Interval(0, 10)))
|
195 |
+
|
196 |
+
|
197 |
+
def test_subs_CondSet_tebr():
|
198 |
+
with warns_deprecated_sympy():
|
199 |
+
assert ConditionSet((x, y), {x + 1, x + y}, S.Reals**2) == \
|
200 |
+
ConditionSet((x, y), Eq(x + 1, 0) & Eq(x + y, 0), S.Reals**2)
|
201 |
+
|
202 |
+
|
203 |
+
def test_dummy_eq():
|
204 |
+
C = ConditionSet
|
205 |
+
I = S.Integers
|
206 |
+
c = C(x, x < 1, I)
|
207 |
+
assert c.dummy_eq(C(y, y < 1, I))
|
208 |
+
assert c.dummy_eq(1) == False
|
209 |
+
assert c.dummy_eq(C(x, x < 1, S.Reals)) == False
|
210 |
+
|
211 |
+
c1 = ConditionSet((x, y), Eq(x + 1, 0) & Eq(x + y, 0), S.Reals**2)
|
212 |
+
c2 = ConditionSet((x, y), Eq(x + 1, 0) & Eq(x + y, 0), S.Reals**2)
|
213 |
+
c3 = ConditionSet((x, y), Eq(x + 1, 0) & Eq(x + y, 0), S.Complexes**2)
|
214 |
+
assert c1.dummy_eq(c2)
|
215 |
+
assert c1.dummy_eq(c3) is False
|
216 |
+
assert c.dummy_eq(c1) is False
|
217 |
+
assert c1.dummy_eq(c) is False
|
218 |
+
|
219 |
+
# issue 19496
|
220 |
+
m = Symbol('m')
|
221 |
+
n = Symbol('n')
|
222 |
+
a = Symbol('a')
|
223 |
+
d1 = ImageSet(Lambda(m, m*pi), S.Integers)
|
224 |
+
d2 = ImageSet(Lambda(n, n*pi), S.Integers)
|
225 |
+
c1 = ConditionSet(x, Ne(a, 0), d1)
|
226 |
+
c2 = ConditionSet(x, Ne(a, 0), d2)
|
227 |
+
assert c1.dummy_eq(c2)
|
228 |
+
|
229 |
+
|
230 |
+
def test_contains():
|
231 |
+
assert 6 in ConditionSet(x, x > 5, Interval(1, 7))
|
232 |
+
assert (8 in ConditionSet(x, y > 5, Interval(1, 7))) is False
|
233 |
+
# `in` should give True or False; in this case there is not
|
234 |
+
# enough information for that result
|
235 |
+
raises(TypeError,
|
236 |
+
lambda: 6 in ConditionSet(x, y > 5, Interval(1, 7)))
|
237 |
+
# here, there is enough information but the comparison is
|
238 |
+
# not defined
|
239 |
+
raises(TypeError, lambda: 0 in ConditionSet(x, 1/x >= 0, S.Reals))
|
240 |
+
assert ConditionSet(x, y > 5, Interval(1, 7)
|
241 |
+
).contains(6) == (y > 5)
|
242 |
+
assert ConditionSet(x, y > 5, Interval(1, 7)
|
243 |
+
).contains(8) is S.false
|
244 |
+
assert ConditionSet(x, y > 5, Interval(1, 7)
|
245 |
+
).contains(w) == And(Contains(w, Interval(1, 7)), y > 5)
|
246 |
+
# This returns an unevaluated Contains object
|
247 |
+
# because 1/0 should not be defined for 1 and 0 in the context of
|
248 |
+
# reals.
|
249 |
+
assert ConditionSet(x, 1/x >= 0, S.Reals).contains(0) == \
|
250 |
+
Contains(0, ConditionSet(x, 1/x >= 0, S.Reals), evaluate=False)
|
251 |
+
c = ConditionSet((x, y), x + y > 1, S.Integers**2)
|
252 |
+
assert not c.contains(1)
|
253 |
+
assert c.contains((2, 1))
|
254 |
+
assert not c.contains((0, 1))
|
255 |
+
c = ConditionSet((w, (x, y)), w + x + y > 1, S.Integers*S.Integers**2)
|
256 |
+
assert not c.contains(1)
|
257 |
+
assert not c.contains((1, 2))
|
258 |
+
assert not c.contains(((1, 2), 3))
|
259 |
+
assert not c.contains(((1, 2), (3, 4)))
|
260 |
+
assert c.contains((1, (3, 4)))
|
261 |
+
|
262 |
+
|
263 |
+
def test_as_relational():
|
264 |
+
assert ConditionSet((x, y), x > 1, S.Integers**2).as_relational((x, y)
|
265 |
+
) == (x > 1) & Contains((x, y), S.Integers**2)
|
266 |
+
assert ConditionSet(x, x > 1, S.Integers).as_relational(x
|
267 |
+
) == Contains(x, S.Integers) & (x > 1)
|
268 |
+
|
269 |
+
|
270 |
+
def test_flatten():
|
271 |
+
"""Tests whether there is basic denesting functionality"""
|
272 |
+
inner = ConditionSet(x, sin(x) + x > 0)
|
273 |
+
outer = ConditionSet(x, Contains(x, inner), S.Reals)
|
274 |
+
assert outer == ConditionSet(x, sin(x) + x > 0, S.Reals)
|
275 |
+
|
276 |
+
inner = ConditionSet(y, sin(y) + y > 0)
|
277 |
+
outer = ConditionSet(x, Contains(y, inner), S.Reals)
|
278 |
+
assert outer != ConditionSet(x, sin(x) + x > 0, S.Reals)
|
279 |
+
|
280 |
+
inner = ConditionSet(x, sin(x) + x > 0).intersect(Interval(-1, 1))
|
281 |
+
outer = ConditionSet(x, Contains(x, inner), S.Reals)
|
282 |
+
assert outer == ConditionSet(x, sin(x) + x > 0, Interval(-1, 1))
|
283 |
+
|
284 |
+
|
285 |
+
def test_duplicate():
|
286 |
+
from sympy.core.function import BadSignatureError
|
287 |
+
# test coverage for line 95 in conditionset.py, check for duplicates in symbols
|
288 |
+
dup = symbols('a,a')
|
289 |
+
raises(BadSignatureError, lambda: ConditionSet(dup, x < 0))
|
290 |
+
|
291 |
+
|
292 |
+
def test_SetKind_ConditionSet():
|
293 |
+
assert ConditionSet(x, Eq(sin(x), 0), Interval(0, 2*pi)).kind is SetKind(NumberKind)
|
294 |
+
assert ConditionSet(x, x < 0).kind is SetKind(NumberKind)
|
env-llmeval/lib/python3.10/site-packages/sympy/sets/tests/test_contains.py
ADDED
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.expr import unchanged
|
2 |
+
from sympy.core.numbers import oo
|
3 |
+
from sympy.core.relational import Eq
|
4 |
+
from sympy.core.singleton import S
|
5 |
+
from sympy.core.symbol import Symbol
|
6 |
+
from sympy.sets.contains import Contains
|
7 |
+
from sympy.sets.sets import (FiniteSet, Interval)
|
8 |
+
from sympy.testing.pytest import raises
|
9 |
+
|
10 |
+
def test_contains_basic():
|
11 |
+
raises(TypeError, lambda: Contains(S.Integers, 1))
|
12 |
+
assert Contains(2, S.Integers) is S.true
|
13 |
+
assert Contains(-2, S.Naturals) is S.false
|
14 |
+
|
15 |
+
i = Symbol('i', integer=True)
|
16 |
+
assert Contains(i, S.Naturals) == Contains(i, S.Naturals, evaluate=False)
|
17 |
+
|
18 |
+
|
19 |
+
def test_issue_6194():
|
20 |
+
x = Symbol('x')
|
21 |
+
assert unchanged(Contains, x, Interval(0, 1))
|
22 |
+
assert Interval(0, 1).contains(x) == (S.Zero <= x) & (x <= 1)
|
23 |
+
assert Contains(x, FiniteSet(0)) != S.false
|
24 |
+
assert Contains(x, Interval(1, 1)) != S.false
|
25 |
+
assert Contains(x, S.Integers) != S.false
|
26 |
+
|
27 |
+
|
28 |
+
def test_issue_10326():
|
29 |
+
assert Contains(oo, Interval(-oo, oo)) == False
|
30 |
+
assert Contains(-oo, Interval(-oo, oo)) == False
|
31 |
+
|
32 |
+
|
33 |
+
def test_binary_symbols():
|
34 |
+
x = Symbol('x')
|
35 |
+
y = Symbol('y')
|
36 |
+
z = Symbol('z')
|
37 |
+
assert Contains(x, FiniteSet(y, Eq(z, True))
|
38 |
+
).binary_symbols == {y, z}
|
39 |
+
|
40 |
+
|
41 |
+
def test_as_set():
|
42 |
+
x = Symbol('x')
|
43 |
+
y = Symbol('y')
|
44 |
+
assert Contains(x, FiniteSet(y)).as_set() == FiniteSet(y)
|
45 |
+
assert Contains(x, S.Integers).as_set() == S.Integers
|
46 |
+
assert Contains(x, S.Reals).as_set() == S.Reals
|
47 |
+
|
48 |
+
def test_type_error():
|
49 |
+
# Pass in a parameter not of type "set"
|
50 |
+
raises(TypeError, lambda: Contains(2, None))
|