applied-ai-018 commited on
Commit
2f68de1
·
verified ·
1 Parent(s): 2b2c7fa

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. ckpts/universal/global_step80/zero/10.input_layernorm.weight/exp_avg.pt +3 -0
  2. ckpts/universal/global_step80/zero/10.mlp.dense_4h_to_h.weight/exp_avg.pt +3 -0
  3. ckpts/universal/global_step80/zero/10.mlp.dense_4h_to_h.weight/fp32.pt +3 -0
  4. ckpts/universal/global_step80/zero/4.mlp.dense_h_to_4h.weight/exp_avg.pt +3 -0
  5. ckpts/universal/global_step80/zero/4.mlp.dense_h_to_4h.weight/exp_avg_sq.pt +3 -0
  6. venv/lib/python3.10/site-packages/sympy/categories/__init__.py +33 -0
  7. venv/lib/python3.10/site-packages/sympy/categories/__pycache__/__init__.cpython-310.pyc +0 -0
  8. venv/lib/python3.10/site-packages/sympy/categories/__pycache__/baseclasses.cpython-310.pyc +0 -0
  9. venv/lib/python3.10/site-packages/sympy/categories/__pycache__/diagram_drawing.cpython-310.pyc +0 -0
  10. venv/lib/python3.10/site-packages/sympy/categories/baseclasses.py +979 -0
  11. venv/lib/python3.10/site-packages/sympy/categories/diagram_drawing.py +2591 -0
  12. venv/lib/python3.10/site-packages/sympy/categories/tests/__init__.py +0 -0
  13. venv/lib/python3.10/site-packages/sympy/categories/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  14. venv/lib/python3.10/site-packages/sympy/categories/tests/__pycache__/test_baseclasses.cpython-310.pyc +0 -0
  15. venv/lib/python3.10/site-packages/sympy/categories/tests/__pycache__/test_drawing.cpython-310.pyc +0 -0
  16. venv/lib/python3.10/site-packages/sympy/categories/tests/test_baseclasses.py +209 -0
  17. venv/lib/python3.10/site-packages/sympy/categories/tests/test_drawing.py +919 -0
  18. venv/lib/python3.10/site-packages/sympy/crypto/__init__.py +35 -0
  19. venv/lib/python3.10/site-packages/sympy/crypto/__pycache__/__init__.cpython-310.pyc +0 -0
  20. venv/lib/python3.10/site-packages/sympy/crypto/__pycache__/crypto.cpython-310.pyc +0 -0
  21. venv/lib/python3.10/site-packages/sympy/crypto/crypto.py +3360 -0
  22. venv/lib/python3.10/site-packages/sympy/crypto/tests/__init__.py +0 -0
  23. venv/lib/python3.10/site-packages/sympy/crypto/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  24. venv/lib/python3.10/site-packages/sympy/crypto/tests/__pycache__/test_crypto.cpython-310.pyc +0 -0
  25. venv/lib/python3.10/site-packages/sympy/crypto/tests/test_crypto.py +562 -0
  26. venv/lib/python3.10/site-packages/sympy/sets/__init__.py +36 -0
  27. venv/lib/python3.10/site-packages/sympy/sets/conditionset.py +246 -0
  28. venv/lib/python3.10/site-packages/sympy/sets/contains.py +48 -0
  29. venv/lib/python3.10/site-packages/sympy/sets/fancysets.py +1521 -0
  30. venv/lib/python3.10/site-packages/sympy/sets/ordinals.py +282 -0
  31. venv/lib/python3.10/site-packages/sympy/sets/powerset.py +119 -0
  32. venv/lib/python3.10/site-packages/sympy/sets/setexpr.py +97 -0
  33. venv/lib/python3.10/site-packages/sympy/sets/sets.py +2749 -0
  34. venv/lib/python3.10/site-packages/sympy/sets/tests/__init__.py +0 -0
  35. venv/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  36. venv/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_contains.cpython-310.pyc +0 -0
  37. venv/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_fancysets.cpython-310.pyc +0 -0
  38. venv/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_ordinals.cpython-310.pyc +0 -0
  39. venv/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_powerset.cpython-310.pyc +0 -0
  40. venv/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_setexpr.cpython-310.pyc +0 -0
  41. venv/lib/python3.10/site-packages/sympy/sets/tests/test_conditionset.py +294 -0
  42. venv/lib/python3.10/site-packages/sympy/sets/tests/test_contains.py +50 -0
  43. venv/lib/python3.10/site-packages/sympy/sets/tests/test_fancysets.py +1306 -0
  44. venv/lib/python3.10/site-packages/sympy/sets/tests/test_ordinals.py +67 -0
  45. venv/lib/python3.10/site-packages/sympy/sets/tests/test_powerset.py +141 -0
  46. venv/lib/python3.10/site-packages/sympy/sets/tests/test_setexpr.py +317 -0
  47. venv/lib/python3.10/site-packages/sympy/sets/tests/test_sets.py +1704 -0
  48. venv/lib/python3.10/site-packages/sympy/strategies/__pycache__/__init__.cpython-310.pyc +0 -0
  49. venv/lib/python3.10/site-packages/sympy/strategies/__pycache__/core.cpython-310.pyc +0 -0
  50. venv/lib/python3.10/site-packages/sympy/strategies/__pycache__/rl.cpython-310.pyc +0 -0
ckpts/universal/global_step80/zero/10.input_layernorm.weight/exp_avg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:28b2410b821ecaec32f84fe711b707a5cd6db344a277459a19d5db00e6dabc94
3
+ size 9372
ckpts/universal/global_step80/zero/10.mlp.dense_4h_to_h.weight/exp_avg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:276d5066ec41a8cf779a325cfca46f3cbaad7b8ea51079ea88d11a95d54563ef
3
+ size 33555612
ckpts/universal/global_step80/zero/10.mlp.dense_4h_to_h.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c8ebb79abd1ef3af3975d7e9d97544fc24a1bbb1c14e7814ab7e570a16afdb80
3
+ size 33555533
ckpts/universal/global_step80/zero/4.mlp.dense_h_to_4h.weight/exp_avg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:102228ffa9de4758a8292602e71dd63f6176c68c2f15fb33583d2b9e1c32c24f
3
+ size 33555612
ckpts/universal/global_step80/zero/4.mlp.dense_h_to_4h.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:50a9cf2ec21a0f1a0f0c46a3dd235e09d66fdc1158005ed8a24076d3e7c08abb
3
+ size 33555627
venv/lib/python3.10/site-packages/sympy/categories/__init__.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Category Theory module.
3
+
4
+ Provides some of the fundamental category-theory-related classes,
5
+ including categories, morphisms, diagrams. Functors are not
6
+ implemented yet.
7
+
8
+ The general reference work this module tries to follow is
9
+
10
+ [JoyOfCats] J. Adamek, H. Herrlich. G. E. Strecker: Abstract and
11
+ Concrete Categories. The Joy of Cats.
12
+
13
+ The latest version of this book should be available for free download
14
+ from
15
+
16
+ katmat.math.uni-bremen.de/acc/acc.pdf
17
+
18
+ """
19
+
20
+ from .baseclasses import (Object, Morphism, IdentityMorphism,
21
+ NamedMorphism, CompositeMorphism, Category,
22
+ Diagram)
23
+
24
+ from .diagram_drawing import (DiagramGrid, XypicDiagramDrawer,
25
+ xypic_draw_diagram, preview_diagram)
26
+
27
+ __all__ = [
28
+ 'Object', 'Morphism', 'IdentityMorphism', 'NamedMorphism',
29
+ 'CompositeMorphism', 'Category', 'Diagram',
30
+
31
+ 'DiagramGrid', 'XypicDiagramDrawer', 'xypic_draw_diagram',
32
+ 'preview_diagram',
33
+ ]
venv/lib/python3.10/site-packages/sympy/categories/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.06 kB). View file
 
venv/lib/python3.10/site-packages/sympy/categories/__pycache__/baseclasses.cpython-310.pyc ADDED
Binary file (28.3 kB). View file
 
venv/lib/python3.10/site-packages/sympy/categories/__pycache__/diagram_drawing.cpython-310.pyc ADDED
Binary file (65.4 kB). View file
 
venv/lib/python3.10/site-packages/sympy/categories/baseclasses.py ADDED
@@ -0,0 +1,979 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import S, Basic, Dict, Symbol, Tuple, sympify
2
+ from sympy.core.symbol import Str
3
+ from sympy.sets import Set, FiniteSet, EmptySet
4
+ from sympy.utilities.iterables import iterable
5
+
6
+
7
+ class Class(Set):
8
+ r"""
9
+ The base class for any kind of class in the set-theoretic sense.
10
+
11
+ Explanation
12
+ ===========
13
+
14
+ In axiomatic set theories, everything is a class. A class which
15
+ can be a member of another class is a set. A class which is not a
16
+ member of another class is a proper class. The class `\{1, 2\}`
17
+ is a set; the class of all sets is a proper class.
18
+
19
+ This class is essentially a synonym for :class:`sympy.core.Set`.
20
+ The goal of this class is to assure easier migration to the
21
+ eventual proper implementation of set theory.
22
+ """
23
+ is_proper = False
24
+
25
+
26
+ class Object(Symbol):
27
+ """
28
+ The base class for any kind of object in an abstract category.
29
+
30
+ Explanation
31
+ ===========
32
+
33
+ While technically any instance of :class:`~.Basic` will do, this
34
+ class is the recommended way to create abstract objects in
35
+ abstract categories.
36
+ """
37
+
38
+
39
+ class Morphism(Basic):
40
+ """
41
+ The base class for any morphism in an abstract category.
42
+
43
+ Explanation
44
+ ===========
45
+
46
+ In abstract categories, a morphism is an arrow between two
47
+ category objects. The object where the arrow starts is called the
48
+ domain, while the object where the arrow ends is called the
49
+ codomain.
50
+
51
+ Two morphisms between the same pair of objects are considered to
52
+ be the same morphisms. To distinguish between morphisms between
53
+ the same objects use :class:`NamedMorphism`.
54
+
55
+ It is prohibited to instantiate this class. Use one of the
56
+ derived classes instead.
57
+
58
+ See Also
59
+ ========
60
+
61
+ IdentityMorphism, NamedMorphism, CompositeMorphism
62
+ """
63
+ def __new__(cls, domain, codomain):
64
+ raise(NotImplementedError(
65
+ "Cannot instantiate Morphism. Use derived classes instead."))
66
+
67
+ @property
68
+ def domain(self):
69
+ """
70
+ Returns the domain of the morphism.
71
+
72
+ Examples
73
+ ========
74
+
75
+ >>> from sympy.categories import Object, NamedMorphism
76
+ >>> A = Object("A")
77
+ >>> B = Object("B")
78
+ >>> f = NamedMorphism(A, B, "f")
79
+ >>> f.domain
80
+ Object("A")
81
+
82
+ """
83
+ return self.args[0]
84
+
85
+ @property
86
+ def codomain(self):
87
+ """
88
+ Returns the codomain of the morphism.
89
+
90
+ Examples
91
+ ========
92
+
93
+ >>> from sympy.categories import Object, NamedMorphism
94
+ >>> A = Object("A")
95
+ >>> B = Object("B")
96
+ >>> f = NamedMorphism(A, B, "f")
97
+ >>> f.codomain
98
+ Object("B")
99
+
100
+ """
101
+ return self.args[1]
102
+
103
+ def compose(self, other):
104
+ r"""
105
+ Composes self with the supplied morphism.
106
+
107
+ The order of elements in the composition is the usual order,
108
+ i.e., to construct `g\circ f` use ``g.compose(f)``.
109
+
110
+ Examples
111
+ ========
112
+
113
+ >>> from sympy.categories import Object, NamedMorphism
114
+ >>> A = Object("A")
115
+ >>> B = Object("B")
116
+ >>> C = Object("C")
117
+ >>> f = NamedMorphism(A, B, "f")
118
+ >>> g = NamedMorphism(B, C, "g")
119
+ >>> g * f
120
+ CompositeMorphism((NamedMorphism(Object("A"), Object("B"), "f"),
121
+ NamedMorphism(Object("B"), Object("C"), "g")))
122
+ >>> (g * f).domain
123
+ Object("A")
124
+ >>> (g * f).codomain
125
+ Object("C")
126
+
127
+ """
128
+ return CompositeMorphism(other, self)
129
+
130
+ def __mul__(self, other):
131
+ r"""
132
+ Composes self with the supplied morphism.
133
+
134
+ The semantics of this operation is given by the following
135
+ equation: ``g * f == g.compose(f)`` for composable morphisms
136
+ ``g`` and ``f``.
137
+
138
+ See Also
139
+ ========
140
+
141
+ compose
142
+ """
143
+ return self.compose(other)
144
+
145
+
146
+ class IdentityMorphism(Morphism):
147
+ """
148
+ Represents an identity morphism.
149
+
150
+ Explanation
151
+ ===========
152
+
153
+ An identity morphism is a morphism with equal domain and codomain,
154
+ which acts as an identity with respect to composition.
155
+
156
+ Examples
157
+ ========
158
+
159
+ >>> from sympy.categories import Object, NamedMorphism, IdentityMorphism
160
+ >>> A = Object("A")
161
+ >>> B = Object("B")
162
+ >>> f = NamedMorphism(A, B, "f")
163
+ >>> id_A = IdentityMorphism(A)
164
+ >>> id_B = IdentityMorphism(B)
165
+ >>> f * id_A == f
166
+ True
167
+ >>> id_B * f == f
168
+ True
169
+
170
+ See Also
171
+ ========
172
+
173
+ Morphism
174
+ """
175
+ def __new__(cls, domain):
176
+ return Basic.__new__(cls, domain)
177
+
178
+ @property
179
+ def codomain(self):
180
+ return self.domain
181
+
182
+
183
+ class NamedMorphism(Morphism):
184
+ """
185
+ Represents a morphism which has a name.
186
+
187
+ Explanation
188
+ ===========
189
+
190
+ Names are used to distinguish between morphisms which have the
191
+ same domain and codomain: two named morphisms are equal if they
192
+ have the same domains, codomains, and names.
193
+
194
+ Examples
195
+ ========
196
+
197
+ >>> from sympy.categories import Object, NamedMorphism
198
+ >>> A = Object("A")
199
+ >>> B = Object("B")
200
+ >>> f = NamedMorphism(A, B, "f")
201
+ >>> f
202
+ NamedMorphism(Object("A"), Object("B"), "f")
203
+ >>> f.name
204
+ 'f'
205
+
206
+ See Also
207
+ ========
208
+
209
+ Morphism
210
+ """
211
+ def __new__(cls, domain, codomain, name):
212
+ if not name:
213
+ raise ValueError("Empty morphism names not allowed.")
214
+
215
+ if not isinstance(name, Str):
216
+ name = Str(name)
217
+
218
+ return Basic.__new__(cls, domain, codomain, name)
219
+
220
+ @property
221
+ def name(self):
222
+ """
223
+ Returns the name of the morphism.
224
+
225
+ Examples
226
+ ========
227
+
228
+ >>> from sympy.categories import Object, NamedMorphism
229
+ >>> A = Object("A")
230
+ >>> B = Object("B")
231
+ >>> f = NamedMorphism(A, B, "f")
232
+ >>> f.name
233
+ 'f'
234
+
235
+ """
236
+ return self.args[2].name
237
+
238
+
239
+ class CompositeMorphism(Morphism):
240
+ r"""
241
+ Represents a morphism which is a composition of other morphisms.
242
+
243
+ Explanation
244
+ ===========
245
+
246
+ Two composite morphisms are equal if the morphisms they were
247
+ obtained from (components) are the same and were listed in the
248
+ same order.
249
+
250
+ The arguments to the constructor for this class should be listed
251
+ in diagram order: to obtain the composition `g\circ f` from the
252
+ instances of :class:`Morphism` ``g`` and ``f`` use
253
+ ``CompositeMorphism(f, g)``.
254
+
255
+ Examples
256
+ ========
257
+
258
+ >>> from sympy.categories import Object, NamedMorphism, CompositeMorphism
259
+ >>> A = Object("A")
260
+ >>> B = Object("B")
261
+ >>> C = Object("C")
262
+ >>> f = NamedMorphism(A, B, "f")
263
+ >>> g = NamedMorphism(B, C, "g")
264
+ >>> g * f
265
+ CompositeMorphism((NamedMorphism(Object("A"), Object("B"), "f"),
266
+ NamedMorphism(Object("B"), Object("C"), "g")))
267
+ >>> CompositeMorphism(f, g) == g * f
268
+ True
269
+
270
+ """
271
+ @staticmethod
272
+ def _add_morphism(t, morphism):
273
+ """
274
+ Intelligently adds ``morphism`` to tuple ``t``.
275
+
276
+ Explanation
277
+ ===========
278
+
279
+ If ``morphism`` is a composite morphism, its components are
280
+ added to the tuple. If ``morphism`` is an identity, nothing
281
+ is added to the tuple.
282
+
283
+ No composability checks are performed.
284
+ """
285
+ if isinstance(morphism, CompositeMorphism):
286
+ # ``morphism`` is a composite morphism; we have to
287
+ # denest its components.
288
+ return t + morphism.components
289
+ elif isinstance(morphism, IdentityMorphism):
290
+ # ``morphism`` is an identity. Nothing happens.
291
+ return t
292
+ else:
293
+ return t + Tuple(morphism)
294
+
295
+ def __new__(cls, *components):
296
+ if components and not isinstance(components[0], Morphism):
297
+ # Maybe the user has explicitly supplied a list of
298
+ # morphisms.
299
+ return CompositeMorphism.__new__(cls, *components[0])
300
+
301
+ normalised_components = Tuple()
302
+
303
+ for current, following in zip(components, components[1:]):
304
+ if not isinstance(current, Morphism) or \
305
+ not isinstance(following, Morphism):
306
+ raise TypeError("All components must be morphisms.")
307
+
308
+ if current.codomain != following.domain:
309
+ raise ValueError("Uncomposable morphisms.")
310
+
311
+ normalised_components = CompositeMorphism._add_morphism(
312
+ normalised_components, current)
313
+
314
+ # We haven't added the last morphism to the list of normalised
315
+ # components. Add it now.
316
+ normalised_components = CompositeMorphism._add_morphism(
317
+ normalised_components, components[-1])
318
+
319
+ if not normalised_components:
320
+ # If ``normalised_components`` is empty, only identities
321
+ # were supplied. Since they all were composable, they are
322
+ # all the same identities.
323
+ return components[0]
324
+ elif len(normalised_components) == 1:
325
+ # No sense to construct a whole CompositeMorphism.
326
+ return normalised_components[0]
327
+
328
+ return Basic.__new__(cls, normalised_components)
329
+
330
+ @property
331
+ def components(self):
332
+ """
333
+ Returns the components of this composite morphism.
334
+
335
+ Examples
336
+ ========
337
+
338
+ >>> from sympy.categories import Object, NamedMorphism
339
+ >>> A = Object("A")
340
+ >>> B = Object("B")
341
+ >>> C = Object("C")
342
+ >>> f = NamedMorphism(A, B, "f")
343
+ >>> g = NamedMorphism(B, C, "g")
344
+ >>> (g * f).components
345
+ (NamedMorphism(Object("A"), Object("B"), "f"),
346
+ NamedMorphism(Object("B"), Object("C"), "g"))
347
+
348
+ """
349
+ return self.args[0]
350
+
351
+ @property
352
+ def domain(self):
353
+ """
354
+ Returns the domain of this composite morphism.
355
+
356
+ The domain of the composite morphism is the domain of its
357
+ first component.
358
+
359
+ Examples
360
+ ========
361
+
362
+ >>> from sympy.categories import Object, NamedMorphism
363
+ >>> A = Object("A")
364
+ >>> B = Object("B")
365
+ >>> C = Object("C")
366
+ >>> f = NamedMorphism(A, B, "f")
367
+ >>> g = NamedMorphism(B, C, "g")
368
+ >>> (g * f).domain
369
+ Object("A")
370
+
371
+ """
372
+ return self.components[0].domain
373
+
374
+ @property
375
+ def codomain(self):
376
+ """
377
+ Returns the codomain of this composite morphism.
378
+
379
+ The codomain of the composite morphism is the codomain of its
380
+ last component.
381
+
382
+ Examples
383
+ ========
384
+
385
+ >>> from sympy.categories import Object, NamedMorphism
386
+ >>> A = Object("A")
387
+ >>> B = Object("B")
388
+ >>> C = Object("C")
389
+ >>> f = NamedMorphism(A, B, "f")
390
+ >>> g = NamedMorphism(B, C, "g")
391
+ >>> (g * f).codomain
392
+ Object("C")
393
+
394
+ """
395
+ return self.components[-1].codomain
396
+
397
+ def flatten(self, new_name):
398
+ """
399
+ Forgets the composite structure of this morphism.
400
+
401
+ Explanation
402
+ ===========
403
+
404
+ If ``new_name`` is not empty, returns a :class:`NamedMorphism`
405
+ with the supplied name, otherwise returns a :class:`Morphism`.
406
+ In both cases the domain of the new morphism is the domain of
407
+ this composite morphism and the codomain of the new morphism
408
+ is the codomain of this composite morphism.
409
+
410
+ Examples
411
+ ========
412
+
413
+ >>> from sympy.categories import Object, NamedMorphism
414
+ >>> A = Object("A")
415
+ >>> B = Object("B")
416
+ >>> C = Object("C")
417
+ >>> f = NamedMorphism(A, B, "f")
418
+ >>> g = NamedMorphism(B, C, "g")
419
+ >>> (g * f).flatten("h")
420
+ NamedMorphism(Object("A"), Object("C"), "h")
421
+
422
+ """
423
+ return NamedMorphism(self.domain, self.codomain, new_name)
424
+
425
+
426
+ class Category(Basic):
427
+ r"""
428
+ An (abstract) category.
429
+
430
+ Explanation
431
+ ===========
432
+
433
+ A category [JoyOfCats] is a quadruple `\mbox{K} = (O, \hom, id,
434
+ \circ)` consisting of
435
+
436
+ * a (set-theoretical) class `O`, whose members are called
437
+ `K`-objects,
438
+
439
+ * for each pair `(A, B)` of `K`-objects, a set `\hom(A, B)` whose
440
+ members are called `K`-morphisms from `A` to `B`,
441
+
442
+ * for a each `K`-object `A`, a morphism `id:A\rightarrow A`,
443
+ called the `K`-identity of `A`,
444
+
445
+ * a composition law `\circ` associating with every `K`-morphisms
446
+ `f:A\rightarrow B` and `g:B\rightarrow C` a `K`-morphism `g\circ
447
+ f:A\rightarrow C`, called the composite of `f` and `g`.
448
+
449
+ Composition is associative, `K`-identities are identities with
450
+ respect to composition, and the sets `\hom(A, B)` are pairwise
451
+ disjoint.
452
+
453
+ This class knows nothing about its objects and morphisms.
454
+ Concrete cases of (abstract) categories should be implemented as
455
+ classes derived from this one.
456
+
457
+ Certain instances of :class:`Diagram` can be asserted to be
458
+ commutative in a :class:`Category` by supplying the argument
459
+ ``commutative_diagrams`` in the constructor.
460
+
461
+ Examples
462
+ ========
463
+
464
+ >>> from sympy.categories import Object, NamedMorphism, Diagram, Category
465
+ >>> from sympy import FiniteSet
466
+ >>> A = Object("A")
467
+ >>> B = Object("B")
468
+ >>> C = Object("C")
469
+ >>> f = NamedMorphism(A, B, "f")
470
+ >>> g = NamedMorphism(B, C, "g")
471
+ >>> d = Diagram([f, g])
472
+ >>> K = Category("K", commutative_diagrams=[d])
473
+ >>> K.commutative_diagrams == FiniteSet(d)
474
+ True
475
+
476
+ See Also
477
+ ========
478
+
479
+ Diagram
480
+ """
481
+ def __new__(cls, name, objects=EmptySet, commutative_diagrams=EmptySet):
482
+ if not name:
483
+ raise ValueError("A Category cannot have an empty name.")
484
+
485
+ if not isinstance(name, Str):
486
+ name = Str(name)
487
+
488
+ if not isinstance(objects, Class):
489
+ objects = Class(objects)
490
+
491
+ new_category = Basic.__new__(cls, name, objects,
492
+ FiniteSet(*commutative_diagrams))
493
+ return new_category
494
+
495
+ @property
496
+ def name(self):
497
+ """
498
+ Returns the name of this category.
499
+
500
+ Examples
501
+ ========
502
+
503
+ >>> from sympy.categories import Category
504
+ >>> K = Category("K")
505
+ >>> K.name
506
+ 'K'
507
+
508
+ """
509
+ return self.args[0].name
510
+
511
+ @property
512
+ def objects(self):
513
+ """
514
+ Returns the class of objects of this category.
515
+
516
+ Examples
517
+ ========
518
+
519
+ >>> from sympy.categories import Object, Category
520
+ >>> from sympy import FiniteSet
521
+ >>> A = Object("A")
522
+ >>> B = Object("B")
523
+ >>> K = Category("K", FiniteSet(A, B))
524
+ >>> K.objects
525
+ Class({Object("A"), Object("B")})
526
+
527
+ """
528
+ return self.args[1]
529
+
530
+ @property
531
+ def commutative_diagrams(self):
532
+ """
533
+ Returns the :class:`~.FiniteSet` of diagrams which are known to
534
+ be commutative in this category.
535
+
536
+ Examples
537
+ ========
538
+
539
+ >>> from sympy.categories import Object, NamedMorphism, Diagram, Category
540
+ >>> from sympy import FiniteSet
541
+ >>> A = Object("A")
542
+ >>> B = Object("B")
543
+ >>> C = Object("C")
544
+ >>> f = NamedMorphism(A, B, "f")
545
+ >>> g = NamedMorphism(B, C, "g")
546
+ >>> d = Diagram([f, g])
547
+ >>> K = Category("K", commutative_diagrams=[d])
548
+ >>> K.commutative_diagrams == FiniteSet(d)
549
+ True
550
+
551
+ """
552
+ return self.args[2]
553
+
554
+ def hom(self, A, B):
555
+ raise NotImplementedError(
556
+ "hom-sets are not implemented in Category.")
557
+
558
+ def all_morphisms(self):
559
+ raise NotImplementedError(
560
+ "Obtaining the class of morphisms is not implemented in Category.")
561
+
562
+
563
+ class Diagram(Basic):
564
+ r"""
565
+ Represents a diagram in a certain category.
566
+
567
+ Explanation
568
+ ===========
569
+
570
+ Informally, a diagram is a collection of objects of a category and
571
+ certain morphisms between them. A diagram is still a monoid with
572
+ respect to morphism composition; i.e., identity morphisms, as well
573
+ as all composites of morphisms included in the diagram belong to
574
+ the diagram. For a more formal approach to this notion see
575
+ [Pare1970].
576
+
577
+ The components of composite morphisms are also added to the
578
+ diagram. No properties are assigned to such morphisms by default.
579
+
580
+ A commutative diagram is often accompanied by a statement of the
581
+ following kind: "if such morphisms with such properties exist,
582
+ then such morphisms which such properties exist and the diagram is
583
+ commutative". To represent this, an instance of :class:`Diagram`
584
+ includes a collection of morphisms which are the premises and
585
+ another collection of conclusions. ``premises`` and
586
+ ``conclusions`` associate morphisms belonging to the corresponding
587
+ categories with the :class:`~.FiniteSet`'s of their properties.
588
+
589
+ The set of properties of a composite morphism is the intersection
590
+ of the sets of properties of its components. The domain and
591
+ codomain of a conclusion morphism should be among the domains and
592
+ codomains of the morphisms listed as the premises of a diagram.
593
+
594
+ No checks are carried out of whether the supplied object and
595
+ morphisms do belong to one and the same category.
596
+
597
+ Examples
598
+ ========
599
+
600
+ >>> from sympy.categories import Object, NamedMorphism, Diagram
601
+ >>> from sympy import pprint, default_sort_key
602
+ >>> A = Object("A")
603
+ >>> B = Object("B")
604
+ >>> C = Object("C")
605
+ >>> f = NamedMorphism(A, B, "f")
606
+ >>> g = NamedMorphism(B, C, "g")
607
+ >>> d = Diagram([f, g])
608
+ >>> premises_keys = sorted(d.premises.keys(), key=default_sort_key)
609
+ >>> pprint(premises_keys, use_unicode=False)
610
+ [g*f:A-->C, id:A-->A, id:B-->B, id:C-->C, f:A-->B, g:B-->C]
611
+ >>> pprint(d.premises, use_unicode=False)
612
+ {g*f:A-->C: EmptySet, id:A-->A: EmptySet, id:B-->B: EmptySet, id:C-->C: EmptyS
613
+ et, f:A-->B: EmptySet, g:B-->C: EmptySet}
614
+ >>> d = Diagram([f, g], {g * f: "unique"})
615
+ >>> pprint(d.conclusions,use_unicode=False)
616
+ {g*f:A-->C: {unique}}
617
+
618
+ References
619
+ ==========
620
+
621
+ [Pare1970] B. Pareigis: Categories and functors. Academic Press, 1970.
622
+
623
+ """
624
+ @staticmethod
625
+ def _set_dict_union(dictionary, key, value):
626
+ """
627
+ If ``key`` is in ``dictionary``, set the new value of ``key``
628
+ to be the union between the old value and ``value``.
629
+ Otherwise, set the value of ``key`` to ``value.
630
+
631
+ Returns ``True`` if the key already was in the dictionary and
632
+ ``False`` otherwise.
633
+ """
634
+ if key in dictionary:
635
+ dictionary[key] = dictionary[key] | value
636
+ return True
637
+ else:
638
+ dictionary[key] = value
639
+ return False
640
+
641
+ @staticmethod
642
+ def _add_morphism_closure(morphisms, morphism, props, add_identities=True,
643
+ recurse_composites=True):
644
+ """
645
+ Adds a morphism and its attributes to the supplied dictionary
646
+ ``morphisms``. If ``add_identities`` is True, also adds the
647
+ identity morphisms for the domain and the codomain of
648
+ ``morphism``.
649
+ """
650
+ if not Diagram._set_dict_union(morphisms, morphism, props):
651
+ # We have just added a new morphism.
652
+
653
+ if isinstance(morphism, IdentityMorphism):
654
+ if props:
655
+ # Properties for identity morphisms don't really
656
+ # make sense, because very much is known about
657
+ # identity morphisms already, so much that they
658
+ # are trivial. Having properties for identity
659
+ # morphisms would only be confusing.
660
+ raise ValueError(
661
+ "Instances of IdentityMorphism cannot have properties.")
662
+ return
663
+
664
+ if add_identities:
665
+ empty = EmptySet
666
+
667
+ id_dom = IdentityMorphism(morphism.domain)
668
+ id_cod = IdentityMorphism(morphism.codomain)
669
+
670
+ Diagram._set_dict_union(morphisms, id_dom, empty)
671
+ Diagram._set_dict_union(morphisms, id_cod, empty)
672
+
673
+ for existing_morphism, existing_props in list(morphisms.items()):
674
+ new_props = existing_props & props
675
+ if morphism.domain == existing_morphism.codomain:
676
+ left = morphism * existing_morphism
677
+ Diagram._set_dict_union(morphisms, left, new_props)
678
+ if morphism.codomain == existing_morphism.domain:
679
+ right = existing_morphism * morphism
680
+ Diagram._set_dict_union(morphisms, right, new_props)
681
+
682
+ if isinstance(morphism, CompositeMorphism) and recurse_composites:
683
+ # This is a composite morphism, add its components as
684
+ # well.
685
+ empty = EmptySet
686
+ for component in morphism.components:
687
+ Diagram._add_morphism_closure(morphisms, component, empty,
688
+ add_identities)
689
+
690
+ def __new__(cls, *args):
691
+ """
692
+ Construct a new instance of Diagram.
693
+
694
+ Explanation
695
+ ===========
696
+
697
+ If no arguments are supplied, an empty diagram is created.
698
+
699
+ If at least an argument is supplied, ``args[0]`` is
700
+ interpreted as the premises of the diagram. If ``args[0]`` is
701
+ a list, it is interpreted as a list of :class:`Morphism`'s, in
702
+ which each :class:`Morphism` has an empty set of properties.
703
+ If ``args[0]`` is a Python dictionary or a :class:`Dict`, it
704
+ is interpreted as a dictionary associating to some
705
+ :class:`Morphism`'s some properties.
706
+
707
+ If at least two arguments are supplied ``args[1]`` is
708
+ interpreted as the conclusions of the diagram. The type of
709
+ ``args[1]`` is interpreted in exactly the same way as the type
710
+ of ``args[0]``. If only one argument is supplied, the diagram
711
+ has no conclusions.
712
+
713
+ Examples
714
+ ========
715
+
716
+ >>> from sympy.categories import Object, NamedMorphism
717
+ >>> from sympy.categories import IdentityMorphism, Diagram
718
+ >>> A = Object("A")
719
+ >>> B = Object("B")
720
+ >>> C = Object("C")
721
+ >>> f = NamedMorphism(A, B, "f")
722
+ >>> g = NamedMorphism(B, C, "g")
723
+ >>> d = Diagram([f, g])
724
+ >>> IdentityMorphism(A) in d.premises.keys()
725
+ True
726
+ >>> g * f in d.premises.keys()
727
+ True
728
+ >>> d = Diagram([f, g], {g * f: "unique"})
729
+ >>> d.conclusions[g * f]
730
+ {unique}
731
+
732
+ """
733
+ premises = {}
734
+ conclusions = {}
735
+
736
+ # Here we will keep track of the objects which appear in the
737
+ # premises.
738
+ objects = EmptySet
739
+
740
+ if len(args) >= 1:
741
+ # We've got some premises in the arguments.
742
+ premises_arg = args[0]
743
+
744
+ if isinstance(premises_arg, list):
745
+ # The user has supplied a list of morphisms, none of
746
+ # which have any attributes.
747
+ empty = EmptySet
748
+
749
+ for morphism in premises_arg:
750
+ objects |= FiniteSet(morphism.domain, morphism.codomain)
751
+ Diagram._add_morphism_closure(premises, morphism, empty)
752
+ elif isinstance(premises_arg, (dict, Dict)):
753
+ # The user has supplied a dictionary of morphisms and
754
+ # their properties.
755
+ for morphism, props in premises_arg.items():
756
+ objects |= FiniteSet(morphism.domain, morphism.codomain)
757
+ Diagram._add_morphism_closure(
758
+ premises, morphism, FiniteSet(*props) if iterable(props) else FiniteSet(props))
759
+
760
+ if len(args) >= 2:
761
+ # We also have some conclusions.
762
+ conclusions_arg = args[1]
763
+
764
+ if isinstance(conclusions_arg, list):
765
+ # The user has supplied a list of morphisms, none of
766
+ # which have any attributes.
767
+ empty = EmptySet
768
+
769
+ for morphism in conclusions_arg:
770
+ # Check that no new objects appear in conclusions.
771
+ if ((sympify(objects.contains(morphism.domain)) is S.true) and
772
+ (sympify(objects.contains(morphism.codomain)) is S.true)):
773
+ # No need to add identities and recurse
774
+ # composites this time.
775
+ Diagram._add_morphism_closure(
776
+ conclusions, morphism, empty, add_identities=False,
777
+ recurse_composites=False)
778
+ elif isinstance(conclusions_arg, dict) or \
779
+ isinstance(conclusions_arg, Dict):
780
+ # The user has supplied a dictionary of morphisms and
781
+ # their properties.
782
+ for morphism, props in conclusions_arg.items():
783
+ # Check that no new objects appear in conclusions.
784
+ if (morphism.domain in objects) and \
785
+ (morphism.codomain in objects):
786
+ # No need to add identities and recurse
787
+ # composites this time.
788
+ Diagram._add_morphism_closure(
789
+ conclusions, morphism, FiniteSet(*props) if iterable(props) else FiniteSet(props),
790
+ add_identities=False, recurse_composites=False)
791
+
792
+ return Basic.__new__(cls, Dict(premises), Dict(conclusions), objects)
793
+
794
+ @property
795
+ def premises(self):
796
+ """
797
+ Returns the premises of this diagram.
798
+
799
+ Examples
800
+ ========
801
+
802
+ >>> from sympy.categories import Object, NamedMorphism
803
+ >>> from sympy.categories import IdentityMorphism, Diagram
804
+ >>> from sympy import pretty
805
+ >>> A = Object("A")
806
+ >>> B = Object("B")
807
+ >>> f = NamedMorphism(A, B, "f")
808
+ >>> id_A = IdentityMorphism(A)
809
+ >>> id_B = IdentityMorphism(B)
810
+ >>> d = Diagram([f])
811
+ >>> print(pretty(d.premises, use_unicode=False))
812
+ {id:A-->A: EmptySet, id:B-->B: EmptySet, f:A-->B: EmptySet}
813
+
814
+ """
815
+ return self.args[0]
816
+
817
+ @property
818
+ def conclusions(self):
819
+ """
820
+ Returns the conclusions of this diagram.
821
+
822
+ Examples
823
+ ========
824
+
825
+ >>> from sympy.categories import Object, NamedMorphism
826
+ >>> from sympy.categories import IdentityMorphism, Diagram
827
+ >>> from sympy import FiniteSet
828
+ >>> A = Object("A")
829
+ >>> B = Object("B")
830
+ >>> C = Object("C")
831
+ >>> f = NamedMorphism(A, B, "f")
832
+ >>> g = NamedMorphism(B, C, "g")
833
+ >>> d = Diagram([f, g])
834
+ >>> IdentityMorphism(A) in d.premises.keys()
835
+ True
836
+ >>> g * f in d.premises.keys()
837
+ True
838
+ >>> d = Diagram([f, g], {g * f: "unique"})
839
+ >>> d.conclusions[g * f] == FiniteSet("unique")
840
+ True
841
+
842
+ """
843
+ return self.args[1]
844
+
845
+ @property
846
+ def objects(self):
847
+ """
848
+ Returns the :class:`~.FiniteSet` of objects that appear in this
849
+ diagram.
850
+
851
+ Examples
852
+ ========
853
+
854
+ >>> from sympy.categories import Object, NamedMorphism, Diagram
855
+ >>> A = Object("A")
856
+ >>> B = Object("B")
857
+ >>> C = Object("C")
858
+ >>> f = NamedMorphism(A, B, "f")
859
+ >>> g = NamedMorphism(B, C, "g")
860
+ >>> d = Diagram([f, g])
861
+ >>> d.objects
862
+ {Object("A"), Object("B"), Object("C")}
863
+
864
+ """
865
+ return self.args[2]
866
+
867
+ def hom(self, A, B):
868
+ """
869
+ Returns a 2-tuple of sets of morphisms between objects ``A`` and
870
+ ``B``: one set of morphisms listed as premises, and the other set
871
+ of morphisms listed as conclusions.
872
+
873
+ Examples
874
+ ========
875
+
876
+ >>> from sympy.categories import Object, NamedMorphism, Diagram
877
+ >>> from sympy import pretty
878
+ >>> A = Object("A")
879
+ >>> B = Object("B")
880
+ >>> C = Object("C")
881
+ >>> f = NamedMorphism(A, B, "f")
882
+ >>> g = NamedMorphism(B, C, "g")
883
+ >>> d = Diagram([f, g], {g * f: "unique"})
884
+ >>> print(pretty(d.hom(A, C), use_unicode=False))
885
+ ({g*f:A-->C}, {g*f:A-->C})
886
+
887
+ See Also
888
+ ========
889
+ Object, Morphism
890
+ """
891
+ premises = EmptySet
892
+ conclusions = EmptySet
893
+
894
+ for morphism in self.premises.keys():
895
+ if (morphism.domain == A) and (morphism.codomain == B):
896
+ premises |= FiniteSet(morphism)
897
+ for morphism in self.conclusions.keys():
898
+ if (morphism.domain == A) and (morphism.codomain == B):
899
+ conclusions |= FiniteSet(morphism)
900
+
901
+ return (premises, conclusions)
902
+
903
+ def is_subdiagram(self, diagram):
904
+ """
905
+ Checks whether ``diagram`` is a subdiagram of ``self``.
906
+ Diagram `D'` is a subdiagram of `D` if all premises
907
+ (conclusions) of `D'` are contained in the premises
908
+ (conclusions) of `D`. The morphisms contained
909
+ both in `D'` and `D` should have the same properties for `D'`
910
+ to be a subdiagram of `D`.
911
+
912
+ Examples
913
+ ========
914
+
915
+ >>> from sympy.categories import Object, NamedMorphism, Diagram
916
+ >>> A = Object("A")
917
+ >>> B = Object("B")
918
+ >>> C = Object("C")
919
+ >>> f = NamedMorphism(A, B, "f")
920
+ >>> g = NamedMorphism(B, C, "g")
921
+ >>> d = Diagram([f, g], {g * f: "unique"})
922
+ >>> d1 = Diagram([f])
923
+ >>> d.is_subdiagram(d1)
924
+ True
925
+ >>> d1.is_subdiagram(d)
926
+ False
927
+ """
928
+ premises = all((m in self.premises) and
929
+ (diagram.premises[m] == self.premises[m])
930
+ for m in diagram.premises)
931
+ if not premises:
932
+ return False
933
+
934
+ conclusions = all((m in self.conclusions) and
935
+ (diagram.conclusions[m] == self.conclusions[m])
936
+ for m in diagram.conclusions)
937
+
938
+ # Premises is surely ``True`` here.
939
+ return conclusions
940
+
941
+ def subdiagram_from_objects(self, objects):
942
+ """
943
+ If ``objects`` is a subset of the objects of ``self``, returns
944
+ a diagram which has as premises all those premises of ``self``
945
+ which have a domains and codomains in ``objects``, likewise
946
+ for conclusions. Properties are preserved.
947
+
948
+ Examples
949
+ ========
950
+
951
+ >>> from sympy.categories import Object, NamedMorphism, Diagram
952
+ >>> from sympy import FiniteSet
953
+ >>> A = Object("A")
954
+ >>> B = Object("B")
955
+ >>> C = Object("C")
956
+ >>> f = NamedMorphism(A, B, "f")
957
+ >>> g = NamedMorphism(B, C, "g")
958
+ >>> d = Diagram([f, g], {f: "unique", g*f: "veryunique"})
959
+ >>> d1 = d.subdiagram_from_objects(FiniteSet(A, B))
960
+ >>> d1 == Diagram([f], {f: "unique"})
961
+ True
962
+ """
963
+ if not objects.is_subset(self.objects):
964
+ raise ValueError(
965
+ "Supplied objects should all belong to the diagram.")
966
+
967
+ new_premises = {}
968
+ for morphism, props in self.premises.items():
969
+ if ((sympify(objects.contains(morphism.domain)) is S.true) and
970
+ (sympify(objects.contains(morphism.codomain)) is S.true)):
971
+ new_premises[morphism] = props
972
+
973
+ new_conclusions = {}
974
+ for morphism, props in self.conclusions.items():
975
+ if ((sympify(objects.contains(morphism.domain)) is S.true) and
976
+ (sympify(objects.contains(morphism.codomain)) is S.true)):
977
+ new_conclusions[morphism] = props
978
+
979
+ return Diagram(new_premises, new_conclusions)
venv/lib/python3.10/site-packages/sympy/categories/diagram_drawing.py ADDED
@@ -0,0 +1,2591 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""
2
+ This module contains the functionality to arrange the nodes of a
3
+ diagram on an abstract grid, and then to produce a graphical
4
+ representation of the grid.
5
+
6
+ The currently supported back-ends are Xy-pic [Xypic].
7
+
8
+ Layout Algorithm
9
+ ================
10
+
11
+ This section provides an overview of the algorithms implemented in
12
+ :class:`DiagramGrid` to lay out diagrams.
13
+
14
+ The first step of the algorithm is the removal composite and identity
15
+ morphisms which do not have properties in the supplied diagram. The
16
+ premises and conclusions of the diagram are then merged.
17
+
18
+ The generic layout algorithm begins with the construction of the
19
+ "skeleton" of the diagram. The skeleton is an undirected graph which
20
+ has the objects of the diagram as vertices and has an (undirected)
21
+ edge between each pair of objects between which there exist morphisms.
22
+ The direction of the morphisms does not matter at this stage. The
23
+ skeleton also includes an edge between each pair of vertices `A` and
24
+ `C` such that there exists an object `B` which is connected via
25
+ a morphism to `A`, and via a morphism to `C`.
26
+
27
+ The skeleton constructed in this way has the property that every
28
+ object is a vertex of a triangle formed by three edges of the
29
+ skeleton. This property lies at the base of the generic layout
30
+ algorithm.
31
+
32
+ After the skeleton has been constructed, the algorithm lists all
33
+ triangles which can be formed. Note that some triangles will not have
34
+ all edges corresponding to morphisms which will actually be drawn.
35
+ Triangles which have only one edge or less which will actually be
36
+ drawn are immediately discarded.
37
+
38
+ The list of triangles is sorted according to the number of edges which
39
+ correspond to morphisms, then the triangle with the least number of such
40
+ edges is selected. One of such edges is picked and the corresponding
41
+ objects are placed horizontally, on a grid. This edge is recorded to
42
+ be in the fringe. The algorithm then finds a "welding" of a triangle
43
+ to the fringe. A welding is an edge in the fringe where a triangle
44
+ could be attached. If the algorithm succeeds in finding such a
45
+ welding, it adds to the grid that vertex of the triangle which was not
46
+ yet included in any edge in the fringe and records the two new edges in
47
+ the fringe. This process continues iteratively until all objects of
48
+ the diagram has been placed or until no more weldings can be found.
49
+
50
+ An edge is only removed from the fringe when a welding to this edge
51
+ has been found, and there is no room around this edge to place
52
+ another vertex.
53
+
54
+ When no more weldings can be found, but there are still triangles
55
+ left, the algorithm searches for a possibility of attaching one of the
56
+ remaining triangles to the existing structure by a vertex. If such a
57
+ possibility is found, the corresponding edge of the found triangle is
58
+ placed in the found space and the iterative process of welding
59
+ triangles restarts.
60
+
61
+ When logical groups are supplied, each of these groups is laid out
62
+ independently. Then a diagram is constructed in which groups are
63
+ objects and any two logical groups between which there exist morphisms
64
+ are connected via a morphism. This diagram is laid out. Finally,
65
+ the grid which includes all objects of the initial diagram is
66
+ constructed by replacing the cells which contain logical groups with
67
+ the corresponding laid out grids, and by correspondingly expanding the
68
+ rows and columns.
69
+
70
+ The sequential layout algorithm begins by constructing the
71
+ underlying undirected graph defined by the morphisms obtained after
72
+ simplifying premises and conclusions and merging them (see above).
73
+ The vertex with the minimal degree is then picked up and depth-first
74
+ search is started from it. All objects which are located at distance
75
+ `n` from the root in the depth-first search tree, are positioned in
76
+ the `n`-th column of the resulting grid. The sequential layout will
77
+ therefore attempt to lay the objects out along a line.
78
+
79
+ References
80
+ ==========
81
+
82
+ .. [Xypic] https://xy-pic.sourceforge.net/
83
+
84
+ """
85
+ from sympy.categories import (CompositeMorphism, IdentityMorphism,
86
+ NamedMorphism, Diagram)
87
+ from sympy.core import Dict, Symbol, default_sort_key
88
+ from sympy.printing.latex import latex
89
+ from sympy.sets import FiniteSet
90
+ from sympy.utilities.iterables import iterable
91
+ from sympy.utilities.decorator import doctest_depends_on
92
+
93
+ from itertools import chain
94
+
95
+
96
+ __doctest_requires__ = {('preview_diagram',): 'pyglet'}
97
+
98
+
99
+ class _GrowableGrid:
100
+ """
101
+ Holds a growable grid of objects.
102
+
103
+ Explanation
104
+ ===========
105
+
106
+ It is possible to append or prepend a row or a column to the grid
107
+ using the corresponding methods. Prepending rows or columns has
108
+ the effect of changing the coordinates of the already existing
109
+ elements.
110
+
111
+ This class currently represents a naive implementation of the
112
+ functionality with little attempt at optimisation.
113
+ """
114
+ def __init__(self, width, height):
115
+ self._width = width
116
+ self._height = height
117
+
118
+ self._array = [[None for j in range(width)] for i in range(height)]
119
+
120
+ @property
121
+ def width(self):
122
+ return self._width
123
+
124
+ @property
125
+ def height(self):
126
+ return self._height
127
+
128
+ def __getitem__(self, i_j):
129
+ """
130
+ Returns the element located at in the i-th line and j-th
131
+ column.
132
+ """
133
+ i, j = i_j
134
+ return self._array[i][j]
135
+
136
+ def __setitem__(self, i_j, newvalue):
137
+ """
138
+ Sets the element located at in the i-th line and j-th
139
+ column.
140
+ """
141
+ i, j = i_j
142
+ self._array[i][j] = newvalue
143
+
144
+ def append_row(self):
145
+ """
146
+ Appends an empty row to the grid.
147
+ """
148
+ self._height += 1
149
+ self._array.append([None for j in range(self._width)])
150
+
151
+ def append_column(self):
152
+ """
153
+ Appends an empty column to the grid.
154
+ """
155
+ self._width += 1
156
+ for i in range(self._height):
157
+ self._array[i].append(None)
158
+
159
+ def prepend_row(self):
160
+ """
161
+ Prepends the grid with an empty row.
162
+ """
163
+ self._height += 1
164
+ self._array.insert(0, [None for j in range(self._width)])
165
+
166
+ def prepend_column(self):
167
+ """
168
+ Prepends the grid with an empty column.
169
+ """
170
+ self._width += 1
171
+ for i in range(self._height):
172
+ self._array[i].insert(0, None)
173
+
174
+
175
+ class DiagramGrid:
176
+ r"""
177
+ Constructs and holds the fitting of the diagram into a grid.
178
+
179
+ Explanation
180
+ ===========
181
+
182
+ The mission of this class is to analyse the structure of the
183
+ supplied diagram and to place its objects on a grid such that,
184
+ when the objects and the morphisms are actually drawn, the diagram
185
+ would be "readable", in the sense that there will not be many
186
+ intersections of moprhisms. This class does not perform any
187
+ actual drawing. It does strive nevertheless to offer sufficient
188
+ metadata to draw a diagram.
189
+
190
+ Consider the following simple diagram.
191
+
192
+ >>> from sympy.categories import Object, NamedMorphism
193
+ >>> from sympy.categories import Diagram, DiagramGrid
194
+ >>> from sympy import pprint
195
+ >>> A = Object("A")
196
+ >>> B = Object("B")
197
+ >>> C = Object("C")
198
+ >>> f = NamedMorphism(A, B, "f")
199
+ >>> g = NamedMorphism(B, C, "g")
200
+ >>> diagram = Diagram([f, g])
201
+
202
+ The simplest way to have a diagram laid out is the following:
203
+
204
+ >>> grid = DiagramGrid(diagram)
205
+ >>> (grid.width, grid.height)
206
+ (2, 2)
207
+ >>> pprint(grid)
208
+ A B
209
+ <BLANKLINE>
210
+ C
211
+
212
+ Sometimes one sees the diagram as consisting of logical groups.
213
+ One can advise ``DiagramGrid`` as to such groups by employing the
214
+ ``groups`` keyword argument.
215
+
216
+ Consider the following diagram:
217
+
218
+ >>> D = Object("D")
219
+ >>> f = NamedMorphism(A, B, "f")
220
+ >>> g = NamedMorphism(B, C, "g")
221
+ >>> h = NamedMorphism(D, A, "h")
222
+ >>> k = NamedMorphism(D, B, "k")
223
+ >>> diagram = Diagram([f, g, h, k])
224
+
225
+ Lay it out with generic layout:
226
+
227
+ >>> grid = DiagramGrid(diagram)
228
+ >>> pprint(grid)
229
+ A B D
230
+ <BLANKLINE>
231
+ C
232
+
233
+ Now, we can group the objects `A` and `D` to have them near one
234
+ another:
235
+
236
+ >>> grid = DiagramGrid(diagram, groups=[[A, D], B, C])
237
+ >>> pprint(grid)
238
+ B C
239
+ <BLANKLINE>
240
+ A D
241
+
242
+ Note how the positioning of the other objects changes.
243
+
244
+ Further indications can be supplied to the constructor of
245
+ :class:`DiagramGrid` using keyword arguments. The currently
246
+ supported hints are explained in the following paragraphs.
247
+
248
+ :class:`DiagramGrid` does not automatically guess which layout
249
+ would suit the supplied diagram better. Consider, for example,
250
+ the following linear diagram:
251
+
252
+ >>> E = Object("E")
253
+ >>> f = NamedMorphism(A, B, "f")
254
+ >>> g = NamedMorphism(B, C, "g")
255
+ >>> h = NamedMorphism(C, D, "h")
256
+ >>> i = NamedMorphism(D, E, "i")
257
+ >>> diagram = Diagram([f, g, h, i])
258
+
259
+ When laid out with the generic layout, it does not get to look
260
+ linear:
261
+
262
+ >>> grid = DiagramGrid(diagram)
263
+ >>> pprint(grid)
264
+ A B
265
+ <BLANKLINE>
266
+ C D
267
+ <BLANKLINE>
268
+ E
269
+
270
+ To get it laid out in a line, use ``layout="sequential"``:
271
+
272
+ >>> grid = DiagramGrid(diagram, layout="sequential")
273
+ >>> pprint(grid)
274
+ A B C D E
275
+
276
+ One may sometimes need to transpose the resulting layout. While
277
+ this can always be done by hand, :class:`DiagramGrid` provides a
278
+ hint for that purpose:
279
+
280
+ >>> grid = DiagramGrid(diagram, layout="sequential", transpose=True)
281
+ >>> pprint(grid)
282
+ A
283
+ <BLANKLINE>
284
+ B
285
+ <BLANKLINE>
286
+ C
287
+ <BLANKLINE>
288
+ D
289
+ <BLANKLINE>
290
+ E
291
+
292
+ Separate hints can also be provided for each group. For an
293
+ example, refer to ``tests/test_drawing.py``, and see the different
294
+ ways in which the five lemma [FiveLemma] can be laid out.
295
+
296
+ See Also
297
+ ========
298
+
299
+ Diagram
300
+
301
+ References
302
+ ==========
303
+
304
+ .. [FiveLemma] https://en.wikipedia.org/wiki/Five_lemma
305
+ """
306
+ @staticmethod
307
+ def _simplify_morphisms(morphisms):
308
+ """
309
+ Given a dictionary mapping morphisms to their properties,
310
+ returns a new dictionary in which there are no morphisms which
311
+ do not have properties, and which are compositions of other
312
+ morphisms included in the dictionary. Identities are dropped
313
+ as well.
314
+ """
315
+ newmorphisms = {}
316
+ for morphism, props in morphisms.items():
317
+ if isinstance(morphism, CompositeMorphism) and not props:
318
+ continue
319
+ elif isinstance(morphism, IdentityMorphism):
320
+ continue
321
+ else:
322
+ newmorphisms[morphism] = props
323
+ return newmorphisms
324
+
325
+ @staticmethod
326
+ def _merge_premises_conclusions(premises, conclusions):
327
+ """
328
+ Given two dictionaries of morphisms and their properties,
329
+ produces a single dictionary which includes elements from both
330
+ dictionaries. If a morphism has some properties in premises
331
+ and also in conclusions, the properties in conclusions take
332
+ priority.
333
+ """
334
+ return dict(chain(premises.items(), conclusions.items()))
335
+
336
+ @staticmethod
337
+ def _juxtapose_edges(edge1, edge2):
338
+ """
339
+ If ``edge1`` and ``edge2`` have precisely one common endpoint,
340
+ returns an edge which would form a triangle with ``edge1`` and
341
+ ``edge2``.
342
+
343
+ If ``edge1`` and ``edge2`` do not have a common endpoint,
344
+ returns ``None``.
345
+
346
+ If ``edge1`` and ``edge`` are the same edge, returns ``None``.
347
+ """
348
+ intersection = edge1 & edge2
349
+ if len(intersection) != 1:
350
+ # The edges either have no common points or are equal.
351
+ return None
352
+
353
+ # The edges have a common endpoint. Extract the different
354
+ # endpoints and set up the new edge.
355
+ return (edge1 - intersection) | (edge2 - intersection)
356
+
357
+ @staticmethod
358
+ def _add_edge_append(dictionary, edge, elem):
359
+ """
360
+ If ``edge`` is not in ``dictionary``, adds ``edge`` to the
361
+ dictionary and sets its value to ``[elem]``. Otherwise
362
+ appends ``elem`` to the value of existing entry.
363
+
364
+ Note that edges are undirected, thus `(A, B) = (B, A)`.
365
+ """
366
+ if edge in dictionary:
367
+ dictionary[edge].append(elem)
368
+ else:
369
+ dictionary[edge] = [elem]
370
+
371
+ @staticmethod
372
+ def _build_skeleton(morphisms):
373
+ """
374
+ Creates a dictionary which maps edges to corresponding
375
+ morphisms. Thus for a morphism `f:A\rightarrow B`, the edge
376
+ `(A, B)` will be associated with `f`. This function also adds
377
+ to the list those edges which are formed by juxtaposition of
378
+ two edges already in the list. These new edges are not
379
+ associated with any morphism and are only added to assure that
380
+ the diagram can be decomposed into triangles.
381
+ """
382
+ edges = {}
383
+ # Create edges for morphisms.
384
+ for morphism in morphisms:
385
+ DiagramGrid._add_edge_append(
386
+ edges, frozenset([morphism.domain, morphism.codomain]), morphism)
387
+
388
+ # Create new edges by juxtaposing existing edges.
389
+ edges1 = dict(edges)
390
+ for w in edges1:
391
+ for v in edges1:
392
+ wv = DiagramGrid._juxtapose_edges(w, v)
393
+ if wv and wv not in edges:
394
+ edges[wv] = []
395
+
396
+ return edges
397
+
398
+ @staticmethod
399
+ def _list_triangles(edges):
400
+ """
401
+ Builds the set of triangles formed by the supplied edges. The
402
+ triangles are arbitrary and need not be commutative. A
403
+ triangle is a set that contains all three of its sides.
404
+ """
405
+ triangles = set()
406
+
407
+ for w in edges:
408
+ for v in edges:
409
+ wv = DiagramGrid._juxtapose_edges(w, v)
410
+ if wv and wv in edges:
411
+ triangles.add(frozenset([w, v, wv]))
412
+
413
+ return triangles
414
+
415
+ @staticmethod
416
+ def _drop_redundant_triangles(triangles, skeleton):
417
+ """
418
+ Returns a list which contains only those triangles who have
419
+ morphisms associated with at least two edges.
420
+ """
421
+ return [tri for tri in triangles
422
+ if len([e for e in tri if skeleton[e]]) >= 2]
423
+
424
+ @staticmethod
425
+ def _morphism_length(morphism):
426
+ """
427
+ Returns the length of a morphism. The length of a morphism is
428
+ the number of components it consists of. A non-composite
429
+ morphism is of length 1.
430
+ """
431
+ if isinstance(morphism, CompositeMorphism):
432
+ return len(morphism.components)
433
+ else:
434
+ return 1
435
+
436
+ @staticmethod
437
+ def _compute_triangle_min_sizes(triangles, edges):
438
+ r"""
439
+ Returns a dictionary mapping triangles to their minimal sizes.
440
+ The minimal size of a triangle is the sum of maximal lengths
441
+ of morphisms associated to the sides of the triangle. The
442
+ length of a morphism is the number of components it consists
443
+ of. A non-composite morphism is of length 1.
444
+
445
+ Sorting triangles by this metric attempts to address two
446
+ aspects of layout. For triangles with only simple morphisms
447
+ in the edge, this assures that triangles with all three edges
448
+ visible will get typeset after triangles with less visible
449
+ edges, which sometimes minimizes the necessity in diagonal
450
+ arrows. For triangles with composite morphisms in the edges,
451
+ this assures that objects connected with shorter morphisms
452
+ will be laid out first, resulting the visual proximity of
453
+ those objects which are connected by shorter morphisms.
454
+ """
455
+ triangle_sizes = {}
456
+ for triangle in triangles:
457
+ size = 0
458
+ for e in triangle:
459
+ morphisms = edges[e]
460
+ if morphisms:
461
+ size += max(DiagramGrid._morphism_length(m)
462
+ for m in morphisms)
463
+ triangle_sizes[triangle] = size
464
+ return triangle_sizes
465
+
466
+ @staticmethod
467
+ def _triangle_objects(triangle):
468
+ """
469
+ Given a triangle, returns the objects included in it.
470
+ """
471
+ # A triangle is a frozenset of three two-element frozensets
472
+ # (the edges). This chains the three edges together and
473
+ # creates a frozenset from the iterator, thus producing a
474
+ # frozenset of objects of the triangle.
475
+ return frozenset(chain(*tuple(triangle)))
476
+
477
+ @staticmethod
478
+ def _other_vertex(triangle, edge):
479
+ """
480
+ Given a triangle and an edge of it, returns the vertex which
481
+ opposes the edge.
482
+ """
483
+ # This gets the set of objects of the triangle and then
484
+ # subtracts the set of objects employed in ``edge`` to get the
485
+ # vertex opposite to ``edge``.
486
+ return list(DiagramGrid._triangle_objects(triangle) - set(edge))[0]
487
+
488
+ @staticmethod
489
+ def _empty_point(pt, grid):
490
+ """
491
+ Checks if the cell at coordinates ``pt`` is either empty or
492
+ out of the bounds of the grid.
493
+ """
494
+ if (pt[0] < 0) or (pt[1] < 0) or \
495
+ (pt[0] >= grid.height) or (pt[1] >= grid.width):
496
+ return True
497
+ return grid[pt] is None
498
+
499
+ @staticmethod
500
+ def _put_object(coords, obj, grid, fringe):
501
+ """
502
+ Places an object at the coordinate ``cords`` in ``grid``,
503
+ growing the grid and updating ``fringe``, if necessary.
504
+ Returns (0, 0) if no row or column has been prepended, (1, 0)
505
+ if a row was prepended, (0, 1) if a column was prepended and
506
+ (1, 1) if both a column and a row were prepended.
507
+ """
508
+ (i, j) = coords
509
+ offset = (0, 0)
510
+ if i == -1:
511
+ grid.prepend_row()
512
+ i = 0
513
+ offset = (1, 0)
514
+ for k in range(len(fringe)):
515
+ ((i1, j1), (i2, j2)) = fringe[k]
516
+ fringe[k] = ((i1 + 1, j1), (i2 + 1, j2))
517
+ elif i == grid.height:
518
+ grid.append_row()
519
+
520
+ if j == -1:
521
+ j = 0
522
+ offset = (offset[0], 1)
523
+ grid.prepend_column()
524
+ for k in range(len(fringe)):
525
+ ((i1, j1), (i2, j2)) = fringe[k]
526
+ fringe[k] = ((i1, j1 + 1), (i2, j2 + 1))
527
+ elif j == grid.width:
528
+ grid.append_column()
529
+
530
+ grid[i, j] = obj
531
+ return offset
532
+
533
+ @staticmethod
534
+ def _choose_target_cell(pt1, pt2, edge, obj, skeleton, grid):
535
+ """
536
+ Given two points, ``pt1`` and ``pt2``, and the welding edge
537
+ ``edge``, chooses one of the two points to place the opposing
538
+ vertex ``obj`` of the triangle. If neither of this points
539
+ fits, returns ``None``.
540
+ """
541
+ pt1_empty = DiagramGrid._empty_point(pt1, grid)
542
+ pt2_empty = DiagramGrid._empty_point(pt2, grid)
543
+
544
+ if pt1_empty and pt2_empty:
545
+ # Both cells are empty. Of these two, choose that cell
546
+ # which will assure that a visible edge of the triangle
547
+ # will be drawn perpendicularly to the current welding
548
+ # edge.
549
+
550
+ A = grid[edge[0]]
551
+
552
+ if skeleton.get(frozenset([A, obj])):
553
+ return pt1
554
+ else:
555
+ return pt2
556
+ if pt1_empty:
557
+ return pt1
558
+ elif pt2_empty:
559
+ return pt2
560
+ else:
561
+ return None
562
+
563
+ @staticmethod
564
+ def _find_triangle_to_weld(triangles, fringe, grid):
565
+ """
566
+ Finds, if possible, a triangle and an edge in the ``fringe`` to
567
+ which the triangle could be attached. Returns the tuple
568
+ containing the triangle and the index of the corresponding
569
+ edge in the ``fringe``.
570
+
571
+ This function relies on the fact that objects are unique in
572
+ the diagram.
573
+ """
574
+ for triangle in triangles:
575
+ for (a, b) in fringe:
576
+ if frozenset([grid[a], grid[b]]) in triangle:
577
+ return (triangle, (a, b))
578
+ return None
579
+
580
+ @staticmethod
581
+ def _weld_triangle(tri, welding_edge, fringe, grid, skeleton):
582
+ """
583
+ If possible, welds the triangle ``tri`` to ``fringe`` and
584
+ returns ``False``. If this method encounters a degenerate
585
+ situation in the fringe and corrects it such that a restart of
586
+ the search is required, it returns ``True`` (which means that
587
+ a restart in finding triangle weldings is required).
588
+
589
+ A degenerate situation is a situation when an edge listed in
590
+ the fringe does not belong to the visual boundary of the
591
+ diagram.
592
+ """
593
+ a, b = welding_edge
594
+ target_cell = None
595
+
596
+ obj = DiagramGrid._other_vertex(tri, (grid[a], grid[b]))
597
+
598
+ # We now have a triangle and an edge where it can be welded to
599
+ # the fringe. Decide where to place the other vertex of the
600
+ # triangle and check for degenerate situations en route.
601
+
602
+ if (abs(a[0] - b[0]) == 1) and (abs(a[1] - b[1]) == 1):
603
+ # A diagonal edge.
604
+ target_cell = (a[0], b[1])
605
+ if grid[target_cell]:
606
+ # That cell is already occupied.
607
+ target_cell = (b[0], a[1])
608
+
609
+ if grid[target_cell]:
610
+ # Degenerate situation, this edge is not
611
+ # on the actual fringe. Correct the
612
+ # fringe and go on.
613
+ fringe.remove((a, b))
614
+ return True
615
+ elif a[0] == b[0]:
616
+ # A horizontal edge. We first attempt to build the
617
+ # triangle in the downward direction.
618
+
619
+ down_left = a[0] + 1, a[1]
620
+ down_right = a[0] + 1, b[1]
621
+
622
+ target_cell = DiagramGrid._choose_target_cell(
623
+ down_left, down_right, (a, b), obj, skeleton, grid)
624
+
625
+ if not target_cell:
626
+ # No room below this edge. Check above.
627
+ up_left = a[0] - 1, a[1]
628
+ up_right = a[0] - 1, b[1]
629
+
630
+ target_cell = DiagramGrid._choose_target_cell(
631
+ up_left, up_right, (a, b), obj, skeleton, grid)
632
+
633
+ if not target_cell:
634
+ # This edge is not in the fringe, remove it
635
+ # and restart.
636
+ fringe.remove((a, b))
637
+ return True
638
+ elif a[1] == b[1]:
639
+ # A vertical edge. We will attempt to place the other
640
+ # vertex of the triangle to the right of this edge.
641
+ right_up = a[0], a[1] + 1
642
+ right_down = b[0], a[1] + 1
643
+
644
+ target_cell = DiagramGrid._choose_target_cell(
645
+ right_up, right_down, (a, b), obj, skeleton, grid)
646
+
647
+ if not target_cell:
648
+ # No room to the left. See what's to the right.
649
+ left_up = a[0], a[1] - 1
650
+ left_down = b[0], a[1] - 1
651
+
652
+ target_cell = DiagramGrid._choose_target_cell(
653
+ left_up, left_down, (a, b), obj, skeleton, grid)
654
+
655
+ if not target_cell:
656
+ # This edge is not in the fringe, remove it
657
+ # and restart.
658
+ fringe.remove((a, b))
659
+ return True
660
+
661
+ # We now know where to place the other vertex of the
662
+ # triangle.
663
+ offset = DiagramGrid._put_object(target_cell, obj, grid, fringe)
664
+
665
+ # Take care of the displacement of coordinates if a row or
666
+ # a column was prepended.
667
+ target_cell = (target_cell[0] + offset[0],
668
+ target_cell[1] + offset[1])
669
+ a = (a[0] + offset[0], a[1] + offset[1])
670
+ b = (b[0] + offset[0], b[1] + offset[1])
671
+
672
+ fringe.extend([(a, target_cell), (b, target_cell)])
673
+
674
+ # No restart is required.
675
+ return False
676
+
677
+ @staticmethod
678
+ def _triangle_key(tri, triangle_sizes):
679
+ """
680
+ Returns a key for the supplied triangle. It should be the
681
+ same independently of the hash randomisation.
682
+ """
683
+ objects = sorted(
684
+ DiagramGrid._triangle_objects(tri), key=default_sort_key)
685
+ return (triangle_sizes[tri], default_sort_key(objects))
686
+
687
+ @staticmethod
688
+ def _pick_root_edge(tri, skeleton):
689
+ """
690
+ For a given triangle always picks the same root edge. The
691
+ root edge is the edge that will be placed first on the grid.
692
+ """
693
+ candidates = [sorted(e, key=default_sort_key)
694
+ for e in tri if skeleton[e]]
695
+ sorted_candidates = sorted(candidates, key=default_sort_key)
696
+ # Don't forget to assure the proper ordering of the vertices
697
+ # in this edge.
698
+ return tuple(sorted(sorted_candidates[0], key=default_sort_key))
699
+
700
+ @staticmethod
701
+ def _drop_irrelevant_triangles(triangles, placed_objects):
702
+ """
703
+ Returns only those triangles whose set of objects is not
704
+ completely included in ``placed_objects``.
705
+ """
706
+ return [tri for tri in triangles if not placed_objects.issuperset(
707
+ DiagramGrid._triangle_objects(tri))]
708
+
709
+ @staticmethod
710
+ def _grow_pseudopod(triangles, fringe, grid, skeleton, placed_objects):
711
+ """
712
+ Starting from an object in the existing structure on the ``grid``,
713
+ adds an edge to which a triangle from ``triangles`` could be
714
+ welded. If this method has found a way to do so, it returns
715
+ the object it has just added.
716
+
717
+ This method should be applied when ``_weld_triangle`` cannot
718
+ find weldings any more.
719
+ """
720
+ for i in range(grid.height):
721
+ for j in range(grid.width):
722
+ obj = grid[i, j]
723
+ if not obj:
724
+ continue
725
+
726
+ # Here we need to choose a triangle which has only
727
+ # ``obj`` in common with the existing structure. The
728
+ # situations when this is not possible should be
729
+ # handled elsewhere.
730
+
731
+ def good_triangle(tri):
732
+ objs = DiagramGrid._triangle_objects(tri)
733
+ return obj in objs and \
734
+ placed_objects & (objs - {obj}) == set()
735
+
736
+ tris = [tri for tri in triangles if good_triangle(tri)]
737
+ if not tris:
738
+ # This object is not interesting.
739
+ continue
740
+
741
+ # Pick the "simplest" of the triangles which could be
742
+ # attached. Remember that the list of triangles is
743
+ # sorted according to their "simplicity" (see
744
+ # _compute_triangle_min_sizes for the metric).
745
+ #
746
+ # Note that ``tris`` are sequentially built from
747
+ # ``triangles``, so we don't have to worry about hash
748
+ # randomisation.
749
+ tri = tris[0]
750
+
751
+ # We have found a triangle which could be attached to
752
+ # the existing structure by a vertex.
753
+
754
+ candidates = sorted([e for e in tri if skeleton[e]],
755
+ key=lambda e: FiniteSet(*e).sort_key())
756
+ edges = [e for e in candidates if obj in e]
757
+
758
+ # Note that a meaningful edge (i.e., and edge that is
759
+ # associated with a morphism) containing ``obj``
760
+ # always exists. That's because all triangles are
761
+ # guaranteed to have at least two meaningful edges.
762
+ # See _drop_redundant_triangles.
763
+
764
+ # Get the object at the other end of the edge.
765
+ edge = edges[0]
766
+ other_obj = tuple(edge - frozenset([obj]))[0]
767
+
768
+ # Now check for free directions. When checking for
769
+ # free directions, prefer the horizontal and vertical
770
+ # directions.
771
+ neighbours = [(i - 1, j), (i, j + 1), (i + 1, j), (i, j - 1),
772
+ (i - 1, j - 1), (i - 1, j + 1), (i + 1, j - 1), (i + 1, j + 1)]
773
+
774
+ for pt in neighbours:
775
+ if DiagramGrid._empty_point(pt, grid):
776
+ # We have a found a place to grow the
777
+ # pseudopod into.
778
+ offset = DiagramGrid._put_object(
779
+ pt, other_obj, grid, fringe)
780
+
781
+ i += offset[0]
782
+ j += offset[1]
783
+ pt = (pt[0] + offset[0], pt[1] + offset[1])
784
+ fringe.append(((i, j), pt))
785
+
786
+ return other_obj
787
+
788
+ # This diagram is actually cooler that I can handle. Fail cowardly.
789
+ return None
790
+
791
+ @staticmethod
792
+ def _handle_groups(diagram, groups, merged_morphisms, hints):
793
+ """
794
+ Given the slightly preprocessed morphisms of the diagram,
795
+ produces a grid laid out according to ``groups``.
796
+
797
+ If a group has hints, it is laid out with those hints only,
798
+ without any influence from ``hints``. Otherwise, it is laid
799
+ out with ``hints``.
800
+ """
801
+ def lay_out_group(group, local_hints):
802
+ """
803
+ If ``group`` is a set of objects, uses a ``DiagramGrid``
804
+ to lay it out and returns the grid. Otherwise returns the
805
+ object (i.e., ``group``). If ``local_hints`` is not
806
+ empty, it is supplied to ``DiagramGrid`` as the dictionary
807
+ of hints. Otherwise, the ``hints`` argument of
808
+ ``_handle_groups`` is used.
809
+ """
810
+ if isinstance(group, FiniteSet):
811
+ # Set up the corresponding object-to-group
812
+ # mappings.
813
+ for obj in group:
814
+ obj_groups[obj] = group
815
+
816
+ # Lay out the current group.
817
+ if local_hints:
818
+ groups_grids[group] = DiagramGrid(
819
+ diagram.subdiagram_from_objects(group), **local_hints)
820
+ else:
821
+ groups_grids[group] = DiagramGrid(
822
+ diagram.subdiagram_from_objects(group), **hints)
823
+ else:
824
+ obj_groups[group] = group
825
+
826
+ def group_to_finiteset(group):
827
+ """
828
+ Converts ``group`` to a :class:``FiniteSet`` if it is an
829
+ iterable.
830
+ """
831
+ if iterable(group):
832
+ return FiniteSet(*group)
833
+ else:
834
+ return group
835
+
836
+ obj_groups = {}
837
+ groups_grids = {}
838
+
839
+ # We would like to support various containers to represent
840
+ # groups. To achieve that, before laying each group out, it
841
+ # should be converted to a FiniteSet, because that is what the
842
+ # following code expects.
843
+
844
+ if isinstance(groups, (dict, Dict)):
845
+ finiteset_groups = {}
846
+ for group, local_hints in groups.items():
847
+ finiteset_group = group_to_finiteset(group)
848
+ finiteset_groups[finiteset_group] = local_hints
849
+ lay_out_group(group, local_hints)
850
+ groups = finiteset_groups
851
+ else:
852
+ finiteset_groups = []
853
+ for group in groups:
854
+ finiteset_group = group_to_finiteset(group)
855
+ finiteset_groups.append(finiteset_group)
856
+ lay_out_group(finiteset_group, None)
857
+ groups = finiteset_groups
858
+
859
+ new_morphisms = []
860
+ for morphism in merged_morphisms:
861
+ dom = obj_groups[morphism.domain]
862
+ cod = obj_groups[morphism.codomain]
863
+ # Note that we are not really interested in morphisms
864
+ # which do not employ two different groups, because
865
+ # these do not influence the layout.
866
+ if dom != cod:
867
+ # These are essentially unnamed morphisms; they are
868
+ # not going to mess in the final layout. By giving
869
+ # them the same names, we avoid unnecessary
870
+ # duplicates.
871
+ new_morphisms.append(NamedMorphism(dom, cod, "dummy"))
872
+
873
+ # Lay out the new diagram. Since these are dummy morphisms,
874
+ # properties and conclusions are irrelevant.
875
+ top_grid = DiagramGrid(Diagram(new_morphisms))
876
+
877
+ # We now have to substitute the groups with the corresponding
878
+ # grids, laid out at the beginning of this function. Compute
879
+ # the size of each row and column in the grid, so that all
880
+ # nested grids fit.
881
+
882
+ def group_size(group):
883
+ """
884
+ For the supplied group (or object, eventually), returns
885
+ the size of the cell that will hold this group (object).
886
+ """
887
+ if group in groups_grids:
888
+ grid = groups_grids[group]
889
+ return (grid.height, grid.width)
890
+ else:
891
+ return (1, 1)
892
+
893
+ row_heights = [max(group_size(top_grid[i, j])[0]
894
+ for j in range(top_grid.width))
895
+ for i in range(top_grid.height)]
896
+
897
+ column_widths = [max(group_size(top_grid[i, j])[1]
898
+ for i in range(top_grid.height))
899
+ for j in range(top_grid.width)]
900
+
901
+ grid = _GrowableGrid(sum(column_widths), sum(row_heights))
902
+
903
+ real_row = 0
904
+ real_column = 0
905
+ for logical_row in range(top_grid.height):
906
+ for logical_column in range(top_grid.width):
907
+ obj = top_grid[logical_row, logical_column]
908
+
909
+ if obj in groups_grids:
910
+ # This is a group. Copy the corresponding grid in
911
+ # place.
912
+ local_grid = groups_grids[obj]
913
+ for i in range(local_grid.height):
914
+ for j in range(local_grid.width):
915
+ grid[real_row + i,
916
+ real_column + j] = local_grid[i, j]
917
+ else:
918
+ # This is an object. Just put it there.
919
+ grid[real_row, real_column] = obj
920
+
921
+ real_column += column_widths[logical_column]
922
+ real_column = 0
923
+ real_row += row_heights[logical_row]
924
+
925
+ return grid
926
+
927
+ @staticmethod
928
+ def _generic_layout(diagram, merged_morphisms):
929
+ """
930
+ Produces the generic layout for the supplied diagram.
931
+ """
932
+ all_objects = set(diagram.objects)
933
+ if len(all_objects) == 1:
934
+ # There only one object in the diagram, just put in on 1x1
935
+ # grid.
936
+ grid = _GrowableGrid(1, 1)
937
+ grid[0, 0] = tuple(all_objects)[0]
938
+ return grid
939
+
940
+ skeleton = DiagramGrid._build_skeleton(merged_morphisms)
941
+
942
+ grid = _GrowableGrid(2, 1)
943
+
944
+ if len(skeleton) == 1:
945
+ # This diagram contains only one morphism. Draw it
946
+ # horizontally.
947
+ objects = sorted(all_objects, key=default_sort_key)
948
+ grid[0, 0] = objects[0]
949
+ grid[0, 1] = objects[1]
950
+
951
+ return grid
952
+
953
+ triangles = DiagramGrid._list_triangles(skeleton)
954
+ triangles = DiagramGrid._drop_redundant_triangles(triangles, skeleton)
955
+ triangle_sizes = DiagramGrid._compute_triangle_min_sizes(
956
+ triangles, skeleton)
957
+
958
+ triangles = sorted(triangles, key=lambda tri:
959
+ DiagramGrid._triangle_key(tri, triangle_sizes))
960
+
961
+ # Place the first edge on the grid.
962
+ root_edge = DiagramGrid._pick_root_edge(triangles[0], skeleton)
963
+ grid[0, 0], grid[0, 1] = root_edge
964
+ fringe = [((0, 0), (0, 1))]
965
+
966
+ # Record which objects we now have on the grid.
967
+ placed_objects = set(root_edge)
968
+
969
+ while placed_objects != all_objects:
970
+ welding = DiagramGrid._find_triangle_to_weld(
971
+ triangles, fringe, grid)
972
+
973
+ if welding:
974
+ (triangle, welding_edge) = welding
975
+
976
+ restart_required = DiagramGrid._weld_triangle(
977
+ triangle, welding_edge, fringe, grid, skeleton)
978
+ if restart_required:
979
+ continue
980
+
981
+ placed_objects.update(
982
+ DiagramGrid._triangle_objects(triangle))
983
+ else:
984
+ # No more weldings found. Try to attach triangles by
985
+ # vertices.
986
+ new_obj = DiagramGrid._grow_pseudopod(
987
+ triangles, fringe, grid, skeleton, placed_objects)
988
+
989
+ if not new_obj:
990
+ # No more triangles can be attached, not even by
991
+ # the edge. We will set up a new diagram out of
992
+ # what has been left, laid it out independently,
993
+ # and then attach it to this one.
994
+
995
+ remaining_objects = all_objects - placed_objects
996
+
997
+ remaining_diagram = diagram.subdiagram_from_objects(
998
+ FiniteSet(*remaining_objects))
999
+ remaining_grid = DiagramGrid(remaining_diagram)
1000
+
1001
+ # Now, let's glue ``remaining_grid`` to ``grid``.
1002
+ final_width = grid.width + remaining_grid.width
1003
+ final_height = max(grid.height, remaining_grid.height)
1004
+ final_grid = _GrowableGrid(final_width, final_height)
1005
+
1006
+ for i in range(grid.width):
1007
+ for j in range(grid.height):
1008
+ final_grid[i, j] = grid[i, j]
1009
+
1010
+ start_j = grid.width
1011
+ for i in range(remaining_grid.height):
1012
+ for j in range(remaining_grid.width):
1013
+ final_grid[i, start_j + j] = remaining_grid[i, j]
1014
+
1015
+ return final_grid
1016
+
1017
+ placed_objects.add(new_obj)
1018
+
1019
+ triangles = DiagramGrid._drop_irrelevant_triangles(
1020
+ triangles, placed_objects)
1021
+
1022
+ return grid
1023
+
1024
+ @staticmethod
1025
+ def _get_undirected_graph(objects, merged_morphisms):
1026
+ """
1027
+ Given the objects and the relevant morphisms of a diagram,
1028
+ returns the adjacency lists of the underlying undirected
1029
+ graph.
1030
+ """
1031
+ adjlists = {}
1032
+ for obj in objects:
1033
+ adjlists[obj] = []
1034
+
1035
+ for morphism in merged_morphisms:
1036
+ adjlists[morphism.domain].append(morphism.codomain)
1037
+ adjlists[morphism.codomain].append(morphism.domain)
1038
+
1039
+ # Assure that the objects in the adjacency list are always in
1040
+ # the same order.
1041
+ for obj in adjlists.keys():
1042
+ adjlists[obj].sort(key=default_sort_key)
1043
+
1044
+ return adjlists
1045
+
1046
+ @staticmethod
1047
+ def _sequential_layout(diagram, merged_morphisms):
1048
+ r"""
1049
+ Lays out the diagram in "sequential" layout. This method
1050
+ will attempt to produce a result as close to a line as
1051
+ possible. For linear diagrams, the result will actually be a
1052
+ line.
1053
+ """
1054
+ objects = diagram.objects
1055
+ sorted_objects = sorted(objects, key=default_sort_key)
1056
+
1057
+ # Set up the adjacency lists of the underlying undirected
1058
+ # graph of ``merged_morphisms``.
1059
+ adjlists = DiagramGrid._get_undirected_graph(objects, merged_morphisms)
1060
+
1061
+ # Find an object with the minimal degree. This is going to be
1062
+ # the root.
1063
+ root = sorted_objects[0]
1064
+ mindegree = len(adjlists[root])
1065
+ for obj in sorted_objects:
1066
+ current_degree = len(adjlists[obj])
1067
+ if current_degree < mindegree:
1068
+ root = obj
1069
+ mindegree = current_degree
1070
+
1071
+ grid = _GrowableGrid(1, 1)
1072
+ grid[0, 0] = root
1073
+
1074
+ placed_objects = {root}
1075
+
1076
+ def place_objects(pt, placed_objects):
1077
+ """
1078
+ Does depth-first search in the underlying graph of the
1079
+ diagram and places the objects en route.
1080
+ """
1081
+ # We will start placing new objects from here.
1082
+ new_pt = (pt[0], pt[1] + 1)
1083
+
1084
+ for adjacent_obj in adjlists[grid[pt]]:
1085
+ if adjacent_obj in placed_objects:
1086
+ # This object has already been placed.
1087
+ continue
1088
+
1089
+ DiagramGrid._put_object(new_pt, adjacent_obj, grid, [])
1090
+ placed_objects.add(adjacent_obj)
1091
+ placed_objects.update(place_objects(new_pt, placed_objects))
1092
+
1093
+ new_pt = (new_pt[0] + 1, new_pt[1])
1094
+
1095
+ return placed_objects
1096
+
1097
+ place_objects((0, 0), placed_objects)
1098
+
1099
+ return grid
1100
+
1101
+ @staticmethod
1102
+ def _drop_inessential_morphisms(merged_morphisms):
1103
+ r"""
1104
+ Removes those morphisms which should appear in the diagram,
1105
+ but which have no relevance to object layout.
1106
+
1107
+ Currently this removes "loop" morphisms: the non-identity
1108
+ morphisms with the same domains and codomains.
1109
+ """
1110
+ morphisms = [m for m in merged_morphisms if m.domain != m.codomain]
1111
+ return morphisms
1112
+
1113
+ @staticmethod
1114
+ def _get_connected_components(objects, merged_morphisms):
1115
+ """
1116
+ Given a container of morphisms, returns a list of connected
1117
+ components formed by these morphisms. A connected component
1118
+ is represented by a diagram consisting of the corresponding
1119
+ morphisms.
1120
+ """
1121
+ component_index = {}
1122
+ for o in objects:
1123
+ component_index[o] = None
1124
+
1125
+ # Get the underlying undirected graph of the diagram.
1126
+ adjlist = DiagramGrid._get_undirected_graph(objects, merged_morphisms)
1127
+
1128
+ def traverse_component(object, current_index):
1129
+ """
1130
+ Does a depth-first search traversal of the component
1131
+ containing ``object``.
1132
+ """
1133
+ component_index[object] = current_index
1134
+ for o in adjlist[object]:
1135
+ if component_index[o] is None:
1136
+ traverse_component(o, current_index)
1137
+
1138
+ # Traverse all components.
1139
+ current_index = 0
1140
+ for o in adjlist:
1141
+ if component_index[o] is None:
1142
+ traverse_component(o, current_index)
1143
+ current_index += 1
1144
+
1145
+ # List the objects of the components.
1146
+ component_objects = [[] for i in range(current_index)]
1147
+ for o, idx in component_index.items():
1148
+ component_objects[idx].append(o)
1149
+
1150
+ # Finally, list the morphisms belonging to each component.
1151
+ #
1152
+ # Note: If some objects are isolated, they will not get any
1153
+ # morphisms at this stage, and since the layout algorithm
1154
+ # relies, we are essentially going to lose this object.
1155
+ # Therefore, check if there are isolated objects and, for each
1156
+ # of them, provide the trivial identity morphism. It will get
1157
+ # discarded later, but the object will be there.
1158
+
1159
+ component_morphisms = []
1160
+ for component in component_objects:
1161
+ current_morphisms = {}
1162
+ for m in merged_morphisms:
1163
+ if (m.domain in component) and (m.codomain in component):
1164
+ current_morphisms[m] = merged_morphisms[m]
1165
+
1166
+ if len(component) == 1:
1167
+ # Let's add an identity morphism, for the sake of
1168
+ # surely having morphisms in this component.
1169
+ current_morphisms[IdentityMorphism(component[0])] = FiniteSet()
1170
+
1171
+ component_morphisms.append(Diagram(current_morphisms))
1172
+
1173
+ return component_morphisms
1174
+
1175
+ def __init__(self, diagram, groups=None, **hints):
1176
+ premises = DiagramGrid._simplify_morphisms(diagram.premises)
1177
+ conclusions = DiagramGrid._simplify_morphisms(diagram.conclusions)
1178
+ all_merged_morphisms = DiagramGrid._merge_premises_conclusions(
1179
+ premises, conclusions)
1180
+ merged_morphisms = DiagramGrid._drop_inessential_morphisms(
1181
+ all_merged_morphisms)
1182
+
1183
+ # Store the merged morphisms for later use.
1184
+ self._morphisms = all_merged_morphisms
1185
+
1186
+ components = DiagramGrid._get_connected_components(
1187
+ diagram.objects, all_merged_morphisms)
1188
+
1189
+ if groups and (groups != diagram.objects):
1190
+ # Lay out the diagram according to the groups.
1191
+ self._grid = DiagramGrid._handle_groups(
1192
+ diagram, groups, merged_morphisms, hints)
1193
+ elif len(components) > 1:
1194
+ # Note that we check for connectedness _before_ checking
1195
+ # the layout hints because the layout strategies don't
1196
+ # know how to deal with disconnected diagrams.
1197
+
1198
+ # The diagram is disconnected. Lay out the components
1199
+ # independently.
1200
+ grids = []
1201
+
1202
+ # Sort the components to eventually get the grids arranged
1203
+ # in a fixed, hash-independent order.
1204
+ components = sorted(components, key=default_sort_key)
1205
+
1206
+ for component in components:
1207
+ grid = DiagramGrid(component, **hints)
1208
+ grids.append(grid)
1209
+
1210
+ # Throw the grids together, in a line.
1211
+ total_width = sum(g.width for g in grids)
1212
+ total_height = max(g.height for g in grids)
1213
+
1214
+ grid = _GrowableGrid(total_width, total_height)
1215
+ start_j = 0
1216
+ for g in grids:
1217
+ for i in range(g.height):
1218
+ for j in range(g.width):
1219
+ grid[i, start_j + j] = g[i, j]
1220
+
1221
+ start_j += g.width
1222
+
1223
+ self._grid = grid
1224
+ elif "layout" in hints:
1225
+ if hints["layout"] == "sequential":
1226
+ self._grid = DiagramGrid._sequential_layout(
1227
+ diagram, merged_morphisms)
1228
+ else:
1229
+ self._grid = DiagramGrid._generic_layout(diagram, merged_morphisms)
1230
+
1231
+ if hints.get("transpose"):
1232
+ # Transpose the resulting grid.
1233
+ grid = _GrowableGrid(self._grid.height, self._grid.width)
1234
+ for i in range(self._grid.height):
1235
+ for j in range(self._grid.width):
1236
+ grid[j, i] = self._grid[i, j]
1237
+ self._grid = grid
1238
+
1239
+ @property
1240
+ def width(self):
1241
+ """
1242
+ Returns the number of columns in this diagram layout.
1243
+
1244
+ Examples
1245
+ ========
1246
+
1247
+ >>> from sympy.categories import Object, NamedMorphism
1248
+ >>> from sympy.categories import Diagram, DiagramGrid
1249
+ >>> A = Object("A")
1250
+ >>> B = Object("B")
1251
+ >>> C = Object("C")
1252
+ >>> f = NamedMorphism(A, B, "f")
1253
+ >>> g = NamedMorphism(B, C, "g")
1254
+ >>> diagram = Diagram([f, g])
1255
+ >>> grid = DiagramGrid(diagram)
1256
+ >>> grid.width
1257
+ 2
1258
+
1259
+ """
1260
+ return self._grid.width
1261
+
1262
+ @property
1263
+ def height(self):
1264
+ """
1265
+ Returns the number of rows in this diagram layout.
1266
+
1267
+ Examples
1268
+ ========
1269
+
1270
+ >>> from sympy.categories import Object, NamedMorphism
1271
+ >>> from sympy.categories import Diagram, DiagramGrid
1272
+ >>> A = Object("A")
1273
+ >>> B = Object("B")
1274
+ >>> C = Object("C")
1275
+ >>> f = NamedMorphism(A, B, "f")
1276
+ >>> g = NamedMorphism(B, C, "g")
1277
+ >>> diagram = Diagram([f, g])
1278
+ >>> grid = DiagramGrid(diagram)
1279
+ >>> grid.height
1280
+ 2
1281
+
1282
+ """
1283
+ return self._grid.height
1284
+
1285
+ def __getitem__(self, i_j):
1286
+ """
1287
+ Returns the object placed in the row ``i`` and column ``j``.
1288
+ The indices are 0-based.
1289
+
1290
+ Examples
1291
+ ========
1292
+
1293
+ >>> from sympy.categories import Object, NamedMorphism
1294
+ >>> from sympy.categories import Diagram, DiagramGrid
1295
+ >>> A = Object("A")
1296
+ >>> B = Object("B")
1297
+ >>> C = Object("C")
1298
+ >>> f = NamedMorphism(A, B, "f")
1299
+ >>> g = NamedMorphism(B, C, "g")
1300
+ >>> diagram = Diagram([f, g])
1301
+ >>> grid = DiagramGrid(diagram)
1302
+ >>> (grid[0, 0], grid[0, 1])
1303
+ (Object("A"), Object("B"))
1304
+ >>> (grid[1, 0], grid[1, 1])
1305
+ (None, Object("C"))
1306
+
1307
+ """
1308
+ i, j = i_j
1309
+ return self._grid[i, j]
1310
+
1311
+ @property
1312
+ def morphisms(self):
1313
+ """
1314
+ Returns those morphisms (and their properties) which are
1315
+ sufficiently meaningful to be drawn.
1316
+
1317
+ Examples
1318
+ ========
1319
+
1320
+ >>> from sympy.categories import Object, NamedMorphism
1321
+ >>> from sympy.categories import Diagram, DiagramGrid
1322
+ >>> A = Object("A")
1323
+ >>> B = Object("B")
1324
+ >>> C = Object("C")
1325
+ >>> f = NamedMorphism(A, B, "f")
1326
+ >>> g = NamedMorphism(B, C, "g")
1327
+ >>> diagram = Diagram([f, g])
1328
+ >>> grid = DiagramGrid(diagram)
1329
+ >>> grid.morphisms
1330
+ {NamedMorphism(Object("A"), Object("B"), "f"): EmptySet,
1331
+ NamedMorphism(Object("B"), Object("C"), "g"): EmptySet}
1332
+
1333
+ """
1334
+ return self._morphisms
1335
+
1336
+ def __str__(self):
1337
+ """
1338
+ Produces a string representation of this class.
1339
+
1340
+ This method returns a string representation of the underlying
1341
+ list of lists of objects.
1342
+
1343
+ Examples
1344
+ ========
1345
+
1346
+ >>> from sympy.categories import Object, NamedMorphism
1347
+ >>> from sympy.categories import Diagram, DiagramGrid
1348
+ >>> A = Object("A")
1349
+ >>> B = Object("B")
1350
+ >>> C = Object("C")
1351
+ >>> f = NamedMorphism(A, B, "f")
1352
+ >>> g = NamedMorphism(B, C, "g")
1353
+ >>> diagram = Diagram([f, g])
1354
+ >>> grid = DiagramGrid(diagram)
1355
+ >>> print(grid)
1356
+ [[Object("A"), Object("B")],
1357
+ [None, Object("C")]]
1358
+
1359
+ """
1360
+ return repr(self._grid._array)
1361
+
1362
+
1363
+ class ArrowStringDescription:
1364
+ r"""
1365
+ Stores the information necessary for producing an Xy-pic
1366
+ description of an arrow.
1367
+
1368
+ The principal goal of this class is to abstract away the string
1369
+ representation of an arrow and to also provide the functionality
1370
+ to produce the actual Xy-pic string.
1371
+
1372
+ ``unit`` sets the unit which will be used to specify the amount of
1373
+ curving and other distances. ``horizontal_direction`` should be a
1374
+ string of ``"r"`` or ``"l"`` specifying the horizontal offset of the
1375
+ target cell of the arrow relatively to the current one.
1376
+ ``vertical_direction`` should specify the vertical offset using a
1377
+ series of either ``"d"`` or ``"u"``. ``label_position`` should be
1378
+ either ``"^"``, ``"_"``, or ``"|"`` to specify that the label should
1379
+ be positioned above the arrow, below the arrow or just over the arrow,
1380
+ in a break. Note that the notions "above" and "below" are relative
1381
+ to arrow direction. ``label`` stores the morphism label.
1382
+
1383
+ This works as follows (disregard the yet unexplained arguments):
1384
+
1385
+ >>> from sympy.categories.diagram_drawing import ArrowStringDescription
1386
+ >>> astr = ArrowStringDescription(
1387
+ ... unit="mm", curving=None, curving_amount=None,
1388
+ ... looping_start=None, looping_end=None, horizontal_direction="d",
1389
+ ... vertical_direction="r", label_position="_", label="f")
1390
+ >>> print(str(astr))
1391
+ \ar[dr]_{f}
1392
+
1393
+ ``curving`` should be one of ``"^"``, ``"_"`` to specify in which
1394
+ direction the arrow is going to curve. ``curving_amount`` is a number
1395
+ describing how many ``unit``'s the morphism is going to curve:
1396
+
1397
+ >>> astr = ArrowStringDescription(
1398
+ ... unit="mm", curving="^", curving_amount=12,
1399
+ ... looping_start=None, looping_end=None, horizontal_direction="d",
1400
+ ... vertical_direction="r", label_position="_", label="f")
1401
+ >>> print(str(astr))
1402
+ \ar@/^12mm/[dr]_{f}
1403
+
1404
+ ``looping_start`` and ``looping_end`` are currently only used for
1405
+ loop morphisms, those which have the same domain and codomain.
1406
+ These two attributes should store a valid Xy-pic direction and
1407
+ specify, correspondingly, the direction the arrow gets out into
1408
+ and the direction the arrow gets back from:
1409
+
1410
+ >>> astr = ArrowStringDescription(
1411
+ ... unit="mm", curving=None, curving_amount=None,
1412
+ ... looping_start="u", looping_end="l", horizontal_direction="",
1413
+ ... vertical_direction="", label_position="_", label="f")
1414
+ >>> print(str(astr))
1415
+ \ar@(u,l)[]_{f}
1416
+
1417
+ ``label_displacement`` controls how far the arrow label is from
1418
+ the ends of the arrow. For example, to position the arrow label
1419
+ near the arrow head, use ">":
1420
+
1421
+ >>> astr = ArrowStringDescription(
1422
+ ... unit="mm", curving="^", curving_amount=12,
1423
+ ... looping_start=None, looping_end=None, horizontal_direction="d",
1424
+ ... vertical_direction="r", label_position="_", label="f")
1425
+ >>> astr.label_displacement = ">"
1426
+ >>> print(str(astr))
1427
+ \ar@/^12mm/[dr]_>{f}
1428
+
1429
+ Finally, ``arrow_style`` is used to specify the arrow style. To
1430
+ get a dashed arrow, for example, use "{-->}" as arrow style:
1431
+
1432
+ >>> astr = ArrowStringDescription(
1433
+ ... unit="mm", curving="^", curving_amount=12,
1434
+ ... looping_start=None, looping_end=None, horizontal_direction="d",
1435
+ ... vertical_direction="r", label_position="_", label="f")
1436
+ >>> astr.arrow_style = "{-->}"
1437
+ >>> print(str(astr))
1438
+ \ar@/^12mm/@{-->}[dr]_{f}
1439
+
1440
+ Notes
1441
+ =====
1442
+
1443
+ Instances of :class:`ArrowStringDescription` will be constructed
1444
+ by :class:`XypicDiagramDrawer` and provided for further use in
1445
+ formatters. The user is not expected to construct instances of
1446
+ :class:`ArrowStringDescription` themselves.
1447
+
1448
+ To be able to properly utilise this class, the reader is encouraged
1449
+ to checkout the Xy-pic user guide, available at [Xypic].
1450
+
1451
+ See Also
1452
+ ========
1453
+
1454
+ XypicDiagramDrawer
1455
+
1456
+ References
1457
+ ==========
1458
+
1459
+ .. [Xypic] https://xy-pic.sourceforge.net/
1460
+ """
1461
+ def __init__(self, unit, curving, curving_amount, looping_start,
1462
+ looping_end, horizontal_direction, vertical_direction,
1463
+ label_position, label):
1464
+ self.unit = unit
1465
+ self.curving = curving
1466
+ self.curving_amount = curving_amount
1467
+ self.looping_start = looping_start
1468
+ self.looping_end = looping_end
1469
+ self.horizontal_direction = horizontal_direction
1470
+ self.vertical_direction = vertical_direction
1471
+ self.label_position = label_position
1472
+ self.label = label
1473
+
1474
+ self.label_displacement = ""
1475
+ self.arrow_style = ""
1476
+
1477
+ # This flag shows that the position of the label of this
1478
+ # morphism was set while typesetting a curved morphism and
1479
+ # should not be modified later.
1480
+ self.forced_label_position = False
1481
+
1482
+ def __str__(self):
1483
+ if self.curving:
1484
+ curving_str = "@/%s%d%s/" % (self.curving, self.curving_amount,
1485
+ self.unit)
1486
+ else:
1487
+ curving_str = ""
1488
+
1489
+ if self.looping_start and self.looping_end:
1490
+ looping_str = "@(%s,%s)" % (self.looping_start, self.looping_end)
1491
+ else:
1492
+ looping_str = ""
1493
+
1494
+ if self.arrow_style:
1495
+
1496
+ style_str = "@" + self.arrow_style
1497
+ else:
1498
+ style_str = ""
1499
+
1500
+ return "\\ar%s%s%s[%s%s]%s%s{%s}" % \
1501
+ (curving_str, looping_str, style_str, self.horizontal_direction,
1502
+ self.vertical_direction, self.label_position,
1503
+ self.label_displacement, self.label)
1504
+
1505
+
1506
+ class XypicDiagramDrawer:
1507
+ r"""
1508
+ Given a :class:`~.Diagram` and the corresponding
1509
+ :class:`DiagramGrid`, produces the Xy-pic representation of the
1510
+ diagram.
1511
+
1512
+ The most important method in this class is ``draw``. Consider the
1513
+ following triangle diagram:
1514
+
1515
+ >>> from sympy.categories import Object, NamedMorphism, Diagram
1516
+ >>> from sympy.categories import DiagramGrid, XypicDiagramDrawer
1517
+ >>> A = Object("A")
1518
+ >>> B = Object("B")
1519
+ >>> C = Object("C")
1520
+ >>> f = NamedMorphism(A, B, "f")
1521
+ >>> g = NamedMorphism(B, C, "g")
1522
+ >>> diagram = Diagram([f, g], {g * f: "unique"})
1523
+
1524
+ To draw this diagram, its objects need to be laid out with a
1525
+ :class:`DiagramGrid`::
1526
+
1527
+ >>> grid = DiagramGrid(diagram)
1528
+
1529
+ Finally, the drawing:
1530
+
1531
+ >>> drawer = XypicDiagramDrawer()
1532
+ >>> print(drawer.draw(diagram, grid))
1533
+ \xymatrix{
1534
+ A \ar[d]_{g\circ f} \ar[r]^{f} & B \ar[ld]^{g} \\
1535
+ C &
1536
+ }
1537
+
1538
+ For further details see the docstring of this method.
1539
+
1540
+ To control the appearance of the arrows, formatters are used. The
1541
+ dictionary ``arrow_formatters`` maps morphisms to formatter
1542
+ functions. A formatter is accepts an
1543
+ :class:`ArrowStringDescription` and is allowed to modify any of
1544
+ the arrow properties exposed thereby. For example, to have all
1545
+ morphisms with the property ``unique`` appear as dashed arrows,
1546
+ and to have their names prepended with `\exists !`, the following
1547
+ should be done:
1548
+
1549
+ >>> def formatter(astr):
1550
+ ... astr.label = r"\exists !" + astr.label
1551
+ ... astr.arrow_style = "{-->}"
1552
+ >>> drawer.arrow_formatters["unique"] = formatter
1553
+ >>> print(drawer.draw(diagram, grid))
1554
+ \xymatrix{
1555
+ A \ar@{-->}[d]_{\exists !g\circ f} \ar[r]^{f} & B \ar[ld]^{g} \\
1556
+ C &
1557
+ }
1558
+
1559
+ To modify the appearance of all arrows in the diagram, set
1560
+ ``default_arrow_formatter``. For example, to place all morphism
1561
+ labels a little bit farther from the arrow head so that they look
1562
+ more centred, do as follows:
1563
+
1564
+ >>> def default_formatter(astr):
1565
+ ... astr.label_displacement = "(0.45)"
1566
+ >>> drawer.default_arrow_formatter = default_formatter
1567
+ >>> print(drawer.draw(diagram, grid))
1568
+ \xymatrix{
1569
+ A \ar@{-->}[d]_(0.45){\exists !g\circ f} \ar[r]^(0.45){f} & B \ar[ld]^(0.45){g} \\
1570
+ C &
1571
+ }
1572
+
1573
+ In some diagrams some morphisms are drawn as curved arrows.
1574
+ Consider the following diagram:
1575
+
1576
+ >>> D = Object("D")
1577
+ >>> E = Object("E")
1578
+ >>> h = NamedMorphism(D, A, "h")
1579
+ >>> k = NamedMorphism(D, B, "k")
1580
+ >>> diagram = Diagram([f, g, h, k])
1581
+ >>> grid = DiagramGrid(diagram)
1582
+ >>> drawer = XypicDiagramDrawer()
1583
+ >>> print(drawer.draw(diagram, grid))
1584
+ \xymatrix{
1585
+ A \ar[r]_{f} & B \ar[d]^{g} & D \ar[l]^{k} \ar@/_3mm/[ll]_{h} \\
1586
+ & C &
1587
+ }
1588
+
1589
+ To control how far the morphisms are curved by default, one can
1590
+ use the ``unit`` and ``default_curving_amount`` attributes:
1591
+
1592
+ >>> drawer.unit = "cm"
1593
+ >>> drawer.default_curving_amount = 1
1594
+ >>> print(drawer.draw(diagram, grid))
1595
+ \xymatrix{
1596
+ A \ar[r]_{f} & B \ar[d]^{g} & D \ar[l]^{k} \ar@/_1cm/[ll]_{h} \\
1597
+ & C &
1598
+ }
1599
+
1600
+ In some diagrams, there are multiple curved morphisms between the
1601
+ same two objects. To control by how much the curving changes
1602
+ between two such successive morphisms, use
1603
+ ``default_curving_step``:
1604
+
1605
+ >>> drawer.default_curving_step = 1
1606
+ >>> h1 = NamedMorphism(A, D, "h1")
1607
+ >>> diagram = Diagram([f, g, h, k, h1])
1608
+ >>> grid = DiagramGrid(diagram)
1609
+ >>> print(drawer.draw(diagram, grid))
1610
+ \xymatrix{
1611
+ A \ar[r]_{f} \ar@/^1cm/[rr]^{h_{1}} & B \ar[d]^{g} & D \ar[l]^{k} \ar@/_2cm/[ll]_{h} \\
1612
+ & C &
1613
+ }
1614
+
1615
+ The default value of ``default_curving_step`` is 4 units.
1616
+
1617
+ See Also
1618
+ ========
1619
+
1620
+ draw, ArrowStringDescription
1621
+ """
1622
+ def __init__(self):
1623
+ self.unit = "mm"
1624
+ self.default_curving_amount = 3
1625
+ self.default_curving_step = 4
1626
+
1627
+ # This dictionary maps properties to the corresponding arrow
1628
+ # formatters.
1629
+ self.arrow_formatters = {}
1630
+
1631
+ # This is the default arrow formatter which will be applied to
1632
+ # each arrow independently of its properties.
1633
+ self.default_arrow_formatter = None
1634
+
1635
+ @staticmethod
1636
+ def _process_loop_morphism(i, j, grid, morphisms_str_info, object_coords):
1637
+ """
1638
+ Produces the information required for constructing the string
1639
+ representation of a loop morphism. This function is invoked
1640
+ from ``_process_morphism``.
1641
+
1642
+ See Also
1643
+ ========
1644
+
1645
+ _process_morphism
1646
+ """
1647
+ curving = ""
1648
+ label_pos = "^"
1649
+ looping_start = ""
1650
+ looping_end = ""
1651
+
1652
+ # This is a loop morphism. Count how many morphisms stick
1653
+ # in each of the four quadrants. Note that straight
1654
+ # vertical and horizontal morphisms count in two quadrants
1655
+ # at the same time (i.e., a morphism going up counts both
1656
+ # in the first and the second quadrants).
1657
+
1658
+ # The usual numbering (counterclockwise) of quadrants
1659
+ # applies.
1660
+ quadrant = [0, 0, 0, 0]
1661
+
1662
+ obj = grid[i, j]
1663
+
1664
+ for m, m_str_info in morphisms_str_info.items():
1665
+ if (m.domain == obj) and (m.codomain == obj):
1666
+ # That's another loop morphism. Check how it
1667
+ # loops and mark the corresponding quadrants as
1668
+ # busy.
1669
+ (l_s, l_e) = (m_str_info.looping_start, m_str_info.looping_end)
1670
+
1671
+ if (l_s, l_e) == ("r", "u"):
1672
+ quadrant[0] += 1
1673
+ elif (l_s, l_e) == ("u", "l"):
1674
+ quadrant[1] += 1
1675
+ elif (l_s, l_e) == ("l", "d"):
1676
+ quadrant[2] += 1
1677
+ elif (l_s, l_e) == ("d", "r"):
1678
+ quadrant[3] += 1
1679
+
1680
+ continue
1681
+ if m.domain == obj:
1682
+ (end_i, end_j) = object_coords[m.codomain]
1683
+ goes_out = True
1684
+ elif m.codomain == obj:
1685
+ (end_i, end_j) = object_coords[m.domain]
1686
+ goes_out = False
1687
+ else:
1688
+ continue
1689
+
1690
+ d_i = end_i - i
1691
+ d_j = end_j - j
1692
+ m_curving = m_str_info.curving
1693
+
1694
+ if (d_i != 0) and (d_j != 0):
1695
+ # This is really a diagonal morphism. Detect the
1696
+ # quadrant.
1697
+ if (d_i > 0) and (d_j > 0):
1698
+ quadrant[0] += 1
1699
+ elif (d_i > 0) and (d_j < 0):
1700
+ quadrant[1] += 1
1701
+ elif (d_i < 0) and (d_j < 0):
1702
+ quadrant[2] += 1
1703
+ elif (d_i < 0) and (d_j > 0):
1704
+ quadrant[3] += 1
1705
+ elif d_i == 0:
1706
+ # Knowing where the other end of the morphism is
1707
+ # and which way it goes, we now have to decide
1708
+ # which quadrant is now the upper one and which is
1709
+ # the lower one.
1710
+ if d_j > 0:
1711
+ if goes_out:
1712
+ upper_quadrant = 0
1713
+ lower_quadrant = 3
1714
+ else:
1715
+ upper_quadrant = 3
1716
+ lower_quadrant = 0
1717
+ else:
1718
+ if goes_out:
1719
+ upper_quadrant = 2
1720
+ lower_quadrant = 1
1721
+ else:
1722
+ upper_quadrant = 1
1723
+ lower_quadrant = 2
1724
+
1725
+ if m_curving:
1726
+ if m_curving == "^":
1727
+ quadrant[upper_quadrant] += 1
1728
+ elif m_curving == "_":
1729
+ quadrant[lower_quadrant] += 1
1730
+ else:
1731
+ # This morphism counts in both upper and lower
1732
+ # quadrants.
1733
+ quadrant[upper_quadrant] += 1
1734
+ quadrant[lower_quadrant] += 1
1735
+ elif d_j == 0:
1736
+ # Knowing where the other end of the morphism is
1737
+ # and which way it goes, we now have to decide
1738
+ # which quadrant is now the left one and which is
1739
+ # the right one.
1740
+ if d_i < 0:
1741
+ if goes_out:
1742
+ left_quadrant = 1
1743
+ right_quadrant = 0
1744
+ else:
1745
+ left_quadrant = 0
1746
+ right_quadrant = 1
1747
+ else:
1748
+ if goes_out:
1749
+ left_quadrant = 3
1750
+ right_quadrant = 2
1751
+ else:
1752
+ left_quadrant = 2
1753
+ right_quadrant = 3
1754
+
1755
+ if m_curving:
1756
+ if m_curving == "^":
1757
+ quadrant[left_quadrant] += 1
1758
+ elif m_curving == "_":
1759
+ quadrant[right_quadrant] += 1
1760
+ else:
1761
+ # This morphism counts in both upper and lower
1762
+ # quadrants.
1763
+ quadrant[left_quadrant] += 1
1764
+ quadrant[right_quadrant] += 1
1765
+
1766
+ # Pick the freest quadrant to curve our morphism into.
1767
+ freest_quadrant = 0
1768
+ for i in range(4):
1769
+ if quadrant[i] < quadrant[freest_quadrant]:
1770
+ freest_quadrant = i
1771
+
1772
+ # Now set up proper looping.
1773
+ (looping_start, looping_end) = [("r", "u"), ("u", "l"), ("l", "d"),
1774
+ ("d", "r")][freest_quadrant]
1775
+
1776
+ return (curving, label_pos, looping_start, looping_end)
1777
+
1778
+ @staticmethod
1779
+ def _process_horizontal_morphism(i, j, target_j, grid, morphisms_str_info,
1780
+ object_coords):
1781
+ """
1782
+ Produces the information required for constructing the string
1783
+ representation of a horizontal morphism. This function is
1784
+ invoked from ``_process_morphism``.
1785
+
1786
+ See Also
1787
+ ========
1788
+
1789
+ _process_morphism
1790
+ """
1791
+ # The arrow is horizontal. Check if it goes from left to
1792
+ # right (``backwards == False``) or from right to left
1793
+ # (``backwards == True``).
1794
+ backwards = False
1795
+ start = j
1796
+ end = target_j
1797
+ if end < start:
1798
+ (start, end) = (end, start)
1799
+ backwards = True
1800
+
1801
+ # Let's see which objects are there between ``start`` and
1802
+ # ``end``, and then count how many morphisms stick out
1803
+ # upwards, and how many stick out downwards.
1804
+ #
1805
+ # For example, consider the situation:
1806
+ #
1807
+ # B1 C1
1808
+ # | |
1809
+ # A--B--C--D
1810
+ # |
1811
+ # B2
1812
+ #
1813
+ # Between the objects `A` and `D` there are two objects:
1814
+ # `B` and `C`. Further, there are two morphisms which
1815
+ # stick out upward (the ones between `B1` and `B` and
1816
+ # between `C` and `C1`) and one morphism which sticks out
1817
+ # downward (the one between `B and `B2`).
1818
+ #
1819
+ # We need this information to decide how to curve the
1820
+ # arrow between `A` and `D`. First of all, since there
1821
+ # are two objects between `A` and `D``, we must curve the
1822
+ # arrow. Then, we will have it curve downward, because
1823
+ # there is more space (less morphisms stick out downward
1824
+ # than upward).
1825
+ up = []
1826
+ down = []
1827
+ straight_horizontal = []
1828
+ for k in range(start + 1, end):
1829
+ obj = grid[i, k]
1830
+ if not obj:
1831
+ continue
1832
+
1833
+ for m in morphisms_str_info:
1834
+ if m.domain == obj:
1835
+ (end_i, end_j) = object_coords[m.codomain]
1836
+ elif m.codomain == obj:
1837
+ (end_i, end_j) = object_coords[m.domain]
1838
+ else:
1839
+ continue
1840
+
1841
+ if end_i > i:
1842
+ down.append(m)
1843
+ elif end_i < i:
1844
+ up.append(m)
1845
+ elif not morphisms_str_info[m].curving:
1846
+ # This is a straight horizontal morphism,
1847
+ # because it has no curving.
1848
+ straight_horizontal.append(m)
1849
+
1850
+ if len(up) < len(down):
1851
+ # More morphisms stick out downward than upward, let's
1852
+ # curve the morphism up.
1853
+ if backwards:
1854
+ curving = "_"
1855
+ label_pos = "_"
1856
+ else:
1857
+ curving = "^"
1858
+ label_pos = "^"
1859
+
1860
+ # Assure that the straight horizontal morphisms have
1861
+ # their labels on the lower side of the arrow.
1862
+ for m in straight_horizontal:
1863
+ (i1, j1) = object_coords[m.domain]
1864
+ (i2, j2) = object_coords[m.codomain]
1865
+
1866
+ m_str_info = morphisms_str_info[m]
1867
+ if j1 < j2:
1868
+ m_str_info.label_position = "_"
1869
+ else:
1870
+ m_str_info.label_position = "^"
1871
+
1872
+ # Don't allow any further modifications of the
1873
+ # position of this label.
1874
+ m_str_info.forced_label_position = True
1875
+ else:
1876
+ # More morphisms stick out downward than upward, let's
1877
+ # curve the morphism up.
1878
+ if backwards:
1879
+ curving = "^"
1880
+ label_pos = "^"
1881
+ else:
1882
+ curving = "_"
1883
+ label_pos = "_"
1884
+
1885
+ # Assure that the straight horizontal morphisms have
1886
+ # their labels on the upper side of the arrow.
1887
+ for m in straight_horizontal:
1888
+ (i1, j1) = object_coords[m.domain]
1889
+ (i2, j2) = object_coords[m.codomain]
1890
+
1891
+ m_str_info = morphisms_str_info[m]
1892
+ if j1 < j2:
1893
+ m_str_info.label_position = "^"
1894
+ else:
1895
+ m_str_info.label_position = "_"
1896
+
1897
+ # Don't allow any further modifications of the
1898
+ # position of this label.
1899
+ m_str_info.forced_label_position = True
1900
+
1901
+ return (curving, label_pos)
1902
+
1903
+ @staticmethod
1904
+ def _process_vertical_morphism(i, j, target_i, grid, morphisms_str_info,
1905
+ object_coords):
1906
+ """
1907
+ Produces the information required for constructing the string
1908
+ representation of a vertical morphism. This function is
1909
+ invoked from ``_process_morphism``.
1910
+
1911
+ See Also
1912
+ ========
1913
+
1914
+ _process_morphism
1915
+ """
1916
+ # This arrow is vertical. Check if it goes from top to
1917
+ # bottom (``backwards == False``) or from bottom to top
1918
+ # (``backwards == True``).
1919
+ backwards = False
1920
+ start = i
1921
+ end = target_i
1922
+ if end < start:
1923
+ (start, end) = (end, start)
1924
+ backwards = True
1925
+
1926
+ # Let's see which objects are there between ``start`` and
1927
+ # ``end``, and then count how many morphisms stick out to
1928
+ # the left, and how many stick out to the right.
1929
+ #
1930
+ # See the corresponding comment in the previous branch of
1931
+ # this if-statement for more details.
1932
+ left = []
1933
+ right = []
1934
+ straight_vertical = []
1935
+ for k in range(start + 1, end):
1936
+ obj = grid[k, j]
1937
+ if not obj:
1938
+ continue
1939
+
1940
+ for m in morphisms_str_info:
1941
+ if m.domain == obj:
1942
+ (end_i, end_j) = object_coords[m.codomain]
1943
+ elif m.codomain == obj:
1944
+ (end_i, end_j) = object_coords[m.domain]
1945
+ else:
1946
+ continue
1947
+
1948
+ if end_j > j:
1949
+ right.append(m)
1950
+ elif end_j < j:
1951
+ left.append(m)
1952
+ elif not morphisms_str_info[m].curving:
1953
+ # This is a straight vertical morphism,
1954
+ # because it has no curving.
1955
+ straight_vertical.append(m)
1956
+
1957
+ if len(left) < len(right):
1958
+ # More morphisms stick out to the left than to the
1959
+ # right, let's curve the morphism to the right.
1960
+ if backwards:
1961
+ curving = "^"
1962
+ label_pos = "^"
1963
+ else:
1964
+ curving = "_"
1965
+ label_pos = "_"
1966
+
1967
+ # Assure that the straight vertical morphisms have
1968
+ # their labels on the left side of the arrow.
1969
+ for m in straight_vertical:
1970
+ (i1, j1) = object_coords[m.domain]
1971
+ (i2, j2) = object_coords[m.codomain]
1972
+
1973
+ m_str_info = morphisms_str_info[m]
1974
+ if i1 < i2:
1975
+ m_str_info.label_position = "^"
1976
+ else:
1977
+ m_str_info.label_position = "_"
1978
+
1979
+ # Don't allow any further modifications of the
1980
+ # position of this label.
1981
+ m_str_info.forced_label_position = True
1982
+ else:
1983
+ # More morphisms stick out to the right than to the
1984
+ # left, let's curve the morphism to the left.
1985
+ if backwards:
1986
+ curving = "_"
1987
+ label_pos = "_"
1988
+ else:
1989
+ curving = "^"
1990
+ label_pos = "^"
1991
+
1992
+ # Assure that the straight vertical morphisms have
1993
+ # their labels on the right side of the arrow.
1994
+ for m in straight_vertical:
1995
+ (i1, j1) = object_coords[m.domain]
1996
+ (i2, j2) = object_coords[m.codomain]
1997
+
1998
+ m_str_info = morphisms_str_info[m]
1999
+ if i1 < i2:
2000
+ m_str_info.label_position = "_"
2001
+ else:
2002
+ m_str_info.label_position = "^"
2003
+
2004
+ # Don't allow any further modifications of the
2005
+ # position of this label.
2006
+ m_str_info.forced_label_position = True
2007
+
2008
+ return (curving, label_pos)
2009
+
2010
+ def _process_morphism(self, diagram, grid, morphism, object_coords,
2011
+ morphisms, morphisms_str_info):
2012
+ """
2013
+ Given the required information, produces the string
2014
+ representation of ``morphism``.
2015
+ """
2016
+ def repeat_string_cond(times, str_gt, str_lt):
2017
+ """
2018
+ If ``times > 0``, repeats ``str_gt`` ``times`` times.
2019
+ Otherwise, repeats ``str_lt`` ``-times`` times.
2020
+ """
2021
+ if times > 0:
2022
+ return str_gt * times
2023
+ else:
2024
+ return str_lt * (-times)
2025
+
2026
+ def count_morphisms_undirected(A, B):
2027
+ """
2028
+ Counts how many processed morphisms there are between the
2029
+ two supplied objects.
2030
+ """
2031
+ return len([m for m in morphisms_str_info
2032
+ if {m.domain, m.codomain} == {A, B}])
2033
+
2034
+ def count_morphisms_filtered(dom, cod, curving):
2035
+ """
2036
+ Counts the processed morphisms which go out of ``dom``
2037
+ into ``cod`` with curving ``curving``.
2038
+ """
2039
+ return len([m for m, m_str_info in morphisms_str_info.items()
2040
+ if (m.domain, m.codomain) == (dom, cod) and
2041
+ (m_str_info.curving == curving)])
2042
+
2043
+ (i, j) = object_coords[morphism.domain]
2044
+ (target_i, target_j) = object_coords[morphism.codomain]
2045
+
2046
+ # We now need to determine the direction of
2047
+ # the arrow.
2048
+ delta_i = target_i - i
2049
+ delta_j = target_j - j
2050
+ vertical_direction = repeat_string_cond(delta_i,
2051
+ "d", "u")
2052
+ horizontal_direction = repeat_string_cond(delta_j,
2053
+ "r", "l")
2054
+
2055
+ curving = ""
2056
+ label_pos = "^"
2057
+ looping_start = ""
2058
+ looping_end = ""
2059
+
2060
+ if (delta_i == 0) and (delta_j == 0):
2061
+ # This is a loop morphism.
2062
+ (curving, label_pos, looping_start,
2063
+ looping_end) = XypicDiagramDrawer._process_loop_morphism(
2064
+ i, j, grid, morphisms_str_info, object_coords)
2065
+ elif (delta_i == 0) and (abs(j - target_j) > 1):
2066
+ # This is a horizontal morphism.
2067
+ (curving, label_pos) = XypicDiagramDrawer._process_horizontal_morphism(
2068
+ i, j, target_j, grid, morphisms_str_info, object_coords)
2069
+ elif (delta_j == 0) and (abs(i - target_i) > 1):
2070
+ # This is a vertical morphism.
2071
+ (curving, label_pos) = XypicDiagramDrawer._process_vertical_morphism(
2072
+ i, j, target_i, grid, morphisms_str_info, object_coords)
2073
+
2074
+ count = count_morphisms_undirected(morphism.domain, morphism.codomain)
2075
+ curving_amount = ""
2076
+ if curving:
2077
+ # This morphisms should be curved anyway.
2078
+ curving_amount = self.default_curving_amount + count * \
2079
+ self.default_curving_step
2080
+ elif count:
2081
+ # There are no objects between the domain and codomain of
2082
+ # the current morphism, but this is not there already are
2083
+ # some morphisms with the same domain and codomain, so we
2084
+ # have to curve this one.
2085
+ curving = "^"
2086
+ filtered_morphisms = count_morphisms_filtered(
2087
+ morphism.domain, morphism.codomain, curving)
2088
+ curving_amount = self.default_curving_amount + \
2089
+ filtered_morphisms * \
2090
+ self.default_curving_step
2091
+
2092
+ # Let's now get the name of the morphism.
2093
+ morphism_name = ""
2094
+ if isinstance(morphism, IdentityMorphism):
2095
+ morphism_name = "id_{%s}" + latex(grid[i, j])
2096
+ elif isinstance(morphism, CompositeMorphism):
2097
+ component_names = [latex(Symbol(component.name)) for
2098
+ component in morphism.components]
2099
+ component_names.reverse()
2100
+ morphism_name = "\\circ ".join(component_names)
2101
+ elif isinstance(morphism, NamedMorphism):
2102
+ morphism_name = latex(Symbol(morphism.name))
2103
+
2104
+ return ArrowStringDescription(
2105
+ self.unit, curving, curving_amount, looping_start,
2106
+ looping_end, horizontal_direction, vertical_direction,
2107
+ label_pos, morphism_name)
2108
+
2109
+ @staticmethod
2110
+ def _check_free_space_horizontal(dom_i, dom_j, cod_j, grid):
2111
+ """
2112
+ For a horizontal morphism, checks whether there is free space
2113
+ (i.e., space not occupied by any objects) above the morphism
2114
+ or below it.
2115
+ """
2116
+ if dom_j < cod_j:
2117
+ (start, end) = (dom_j, cod_j)
2118
+ backwards = False
2119
+ else:
2120
+ (start, end) = (cod_j, dom_j)
2121
+ backwards = True
2122
+
2123
+ # Check for free space above.
2124
+ if dom_i == 0:
2125
+ free_up = True
2126
+ else:
2127
+ free_up = all(grid[dom_i - 1, j] for j in
2128
+ range(start, end + 1))
2129
+
2130
+ # Check for free space below.
2131
+ if dom_i == grid.height - 1:
2132
+ free_down = True
2133
+ else:
2134
+ free_down = not any(grid[dom_i + 1, j] for j in
2135
+ range(start, end + 1))
2136
+
2137
+ return (free_up, free_down, backwards)
2138
+
2139
+ @staticmethod
2140
+ def _check_free_space_vertical(dom_i, cod_i, dom_j, grid):
2141
+ """
2142
+ For a vertical morphism, checks whether there is free space
2143
+ (i.e., space not occupied by any objects) to the left of the
2144
+ morphism or to the right of it.
2145
+ """
2146
+ if dom_i < cod_i:
2147
+ (start, end) = (dom_i, cod_i)
2148
+ backwards = False
2149
+ else:
2150
+ (start, end) = (cod_i, dom_i)
2151
+ backwards = True
2152
+
2153
+ # Check if there's space to the left.
2154
+ if dom_j == 0:
2155
+ free_left = True
2156
+ else:
2157
+ free_left = not any(grid[i, dom_j - 1] for i in
2158
+ range(start, end + 1))
2159
+
2160
+ if dom_j == grid.width - 1:
2161
+ free_right = True
2162
+ else:
2163
+ free_right = not any(grid[i, dom_j + 1] for i in
2164
+ range(start, end + 1))
2165
+
2166
+ return (free_left, free_right, backwards)
2167
+
2168
+ @staticmethod
2169
+ def _check_free_space_diagonal(dom_i, cod_i, dom_j, cod_j, grid):
2170
+ """
2171
+ For a diagonal morphism, checks whether there is free space
2172
+ (i.e., space not occupied by any objects) above the morphism
2173
+ or below it.
2174
+ """
2175
+ def abs_xrange(start, end):
2176
+ if start < end:
2177
+ return range(start, end + 1)
2178
+ else:
2179
+ return range(end, start + 1)
2180
+
2181
+ if dom_i < cod_i and dom_j < cod_j:
2182
+ # This morphism goes from top-left to
2183
+ # bottom-right.
2184
+ (start_i, start_j) = (dom_i, dom_j)
2185
+ (end_i, end_j) = (cod_i, cod_j)
2186
+ backwards = False
2187
+ elif dom_i > cod_i and dom_j > cod_j:
2188
+ # This morphism goes from bottom-right to
2189
+ # top-left.
2190
+ (start_i, start_j) = (cod_i, cod_j)
2191
+ (end_i, end_j) = (dom_i, dom_j)
2192
+ backwards = True
2193
+ if dom_i < cod_i and dom_j > cod_j:
2194
+ # This morphism goes from top-right to
2195
+ # bottom-left.
2196
+ (start_i, start_j) = (dom_i, dom_j)
2197
+ (end_i, end_j) = (cod_i, cod_j)
2198
+ backwards = True
2199
+ elif dom_i > cod_i and dom_j < cod_j:
2200
+ # This morphism goes from bottom-left to
2201
+ # top-right.
2202
+ (start_i, start_j) = (cod_i, cod_j)
2203
+ (end_i, end_j) = (dom_i, dom_j)
2204
+ backwards = False
2205
+
2206
+ # This is an attempt at a fast and furious strategy to
2207
+ # decide where there is free space on the two sides of
2208
+ # a diagonal morphism. For a diagonal morphism
2209
+ # starting at ``(start_i, start_j)`` and ending at
2210
+ # ``(end_i, end_j)`` the rectangle defined by these
2211
+ # two points is considered. The slope of the diagonal
2212
+ # ``alpha`` is then computed. Then, for every cell
2213
+ # ``(i, j)`` within the rectangle, the slope
2214
+ # ``alpha1`` of the line through ``(start_i,
2215
+ # start_j)`` and ``(i, j)`` is considered. If
2216
+ # ``alpha1`` is between 0 and ``alpha``, the point
2217
+ # ``(i, j)`` is above the diagonal, if ``alpha1`` is
2218
+ # between ``alpha`` and infinity, the point is below
2219
+ # the diagonal. Also note that, with some beforehand
2220
+ # precautions, this trick works for both the main and
2221
+ # the secondary diagonals of the rectangle.
2222
+
2223
+ # I have considered the possibility to only follow the
2224
+ # shorter diagonals immediately above and below the
2225
+ # main (or secondary) diagonal. This, however,
2226
+ # wouldn't have resulted in much performance gain or
2227
+ # better detection of outer edges, because of
2228
+ # relatively small sizes of diagram grids, while the
2229
+ # code would have become harder to understand.
2230
+
2231
+ alpha = float(end_i - start_i)/(end_j - start_j)
2232
+ free_up = True
2233
+ free_down = True
2234
+ for i in abs_xrange(start_i, end_i):
2235
+ if not free_up and not free_down:
2236
+ break
2237
+
2238
+ for j in abs_xrange(start_j, end_j):
2239
+ if not free_up and not free_down:
2240
+ break
2241
+
2242
+ if (i, j) == (start_i, start_j):
2243
+ continue
2244
+
2245
+ if j == start_j:
2246
+ alpha1 = "inf"
2247
+ else:
2248
+ alpha1 = float(i - start_i)/(j - start_j)
2249
+
2250
+ if grid[i, j]:
2251
+ if (alpha1 == "inf") or (abs(alpha1) > abs(alpha)):
2252
+ free_down = False
2253
+ elif abs(alpha1) < abs(alpha):
2254
+ free_up = False
2255
+
2256
+ return (free_up, free_down, backwards)
2257
+
2258
+ def _push_labels_out(self, morphisms_str_info, grid, object_coords):
2259
+ """
2260
+ For all straight morphisms which form the visual boundary of
2261
+ the laid out diagram, puts their labels on their outer sides.
2262
+ """
2263
+ def set_label_position(free1, free2, pos1, pos2, backwards, m_str_info):
2264
+ """
2265
+ Given the information about room available to one side and
2266
+ to the other side of a morphism (``free1`` and ``free2``),
2267
+ sets the position of the morphism label in such a way that
2268
+ it is on the freer side. This latter operations involves
2269
+ choice between ``pos1`` and ``pos2``, taking ``backwards``
2270
+ in consideration.
2271
+
2272
+ Thus this function will do nothing if either both ``free1
2273
+ == True`` and ``free2 == True`` or both ``free1 == False``
2274
+ and ``free2 == False``. In either case, choosing one side
2275
+ over the other presents no advantage.
2276
+ """
2277
+ if backwards:
2278
+ (pos1, pos2) = (pos2, pos1)
2279
+
2280
+ if free1 and not free2:
2281
+ m_str_info.label_position = pos1
2282
+ elif free2 and not free1:
2283
+ m_str_info.label_position = pos2
2284
+
2285
+ for m, m_str_info in morphisms_str_info.items():
2286
+ if m_str_info.curving or m_str_info.forced_label_position:
2287
+ # This is either a curved morphism, and curved
2288
+ # morphisms have other magic, or the position of this
2289
+ # label has already been fixed.
2290
+ continue
2291
+
2292
+ if m.domain == m.codomain:
2293
+ # This is a loop morphism, their labels, again have a
2294
+ # different magic.
2295
+ continue
2296
+
2297
+ (dom_i, dom_j) = object_coords[m.domain]
2298
+ (cod_i, cod_j) = object_coords[m.codomain]
2299
+
2300
+ if dom_i == cod_i:
2301
+ # Horizontal morphism.
2302
+ (free_up, free_down,
2303
+ backwards) = XypicDiagramDrawer._check_free_space_horizontal(
2304
+ dom_i, dom_j, cod_j, grid)
2305
+
2306
+ set_label_position(free_up, free_down, "^", "_",
2307
+ backwards, m_str_info)
2308
+ elif dom_j == cod_j:
2309
+ # Vertical morphism.
2310
+ (free_left, free_right,
2311
+ backwards) = XypicDiagramDrawer._check_free_space_vertical(
2312
+ dom_i, cod_i, dom_j, grid)
2313
+
2314
+ set_label_position(free_left, free_right, "_", "^",
2315
+ backwards, m_str_info)
2316
+ else:
2317
+ # A diagonal morphism.
2318
+ (free_up, free_down,
2319
+ backwards) = XypicDiagramDrawer._check_free_space_diagonal(
2320
+ dom_i, cod_i, dom_j, cod_j, grid)
2321
+
2322
+ set_label_position(free_up, free_down, "^", "_",
2323
+ backwards, m_str_info)
2324
+
2325
+ @staticmethod
2326
+ def _morphism_sort_key(morphism, object_coords):
2327
+ """
2328
+ Provides a morphism sorting key such that horizontal or
2329
+ vertical morphisms between neighbouring objects come
2330
+ first, then horizontal or vertical morphisms between more
2331
+ far away objects, and finally, all other morphisms.
2332
+ """
2333
+ (i, j) = object_coords[morphism.domain]
2334
+ (target_i, target_j) = object_coords[morphism.codomain]
2335
+
2336
+ if morphism.domain == morphism.codomain:
2337
+ # Loop morphisms should get after diagonal morphisms
2338
+ # so that the proper direction in which to curve the
2339
+ # loop can be determined.
2340
+ return (3, 0, default_sort_key(morphism))
2341
+
2342
+ if target_i == i:
2343
+ return (1, abs(target_j - j), default_sort_key(morphism))
2344
+
2345
+ if target_j == j:
2346
+ return (1, abs(target_i - i), default_sort_key(morphism))
2347
+
2348
+ # Diagonal morphism.
2349
+ return (2, 0, default_sort_key(morphism))
2350
+
2351
+ @staticmethod
2352
+ def _build_xypic_string(diagram, grid, morphisms,
2353
+ morphisms_str_info, diagram_format):
2354
+ """
2355
+ Given a collection of :class:`ArrowStringDescription`
2356
+ describing the morphisms of a diagram and the object layout
2357
+ information of a diagram, produces the final Xy-pic picture.
2358
+ """
2359
+ # Build the mapping between objects and morphisms which have
2360
+ # them as domains.
2361
+ object_morphisms = {}
2362
+ for obj in diagram.objects:
2363
+ object_morphisms[obj] = []
2364
+ for morphism in morphisms:
2365
+ object_morphisms[morphism.domain].append(morphism)
2366
+
2367
+ result = "\\xymatrix%s{\n" % diagram_format
2368
+
2369
+ for i in range(grid.height):
2370
+ for j in range(grid.width):
2371
+ obj = grid[i, j]
2372
+ if obj:
2373
+ result += latex(obj) + " "
2374
+
2375
+ morphisms_to_draw = object_morphisms[obj]
2376
+ for morphism in morphisms_to_draw:
2377
+ result += str(morphisms_str_info[morphism]) + " "
2378
+
2379
+ # Don't put the & after the last column.
2380
+ if j < grid.width - 1:
2381
+ result += "& "
2382
+
2383
+ # Don't put the line break after the last row.
2384
+ if i < grid.height - 1:
2385
+ result += "\\\\"
2386
+ result += "\n"
2387
+
2388
+ result += "}\n"
2389
+
2390
+ return result
2391
+
2392
+ def draw(self, diagram, grid, masked=None, diagram_format=""):
2393
+ r"""
2394
+ Returns the Xy-pic representation of ``diagram`` laid out in
2395
+ ``grid``.
2396
+
2397
+ Consider the following simple triangle diagram.
2398
+
2399
+ >>> from sympy.categories import Object, NamedMorphism, Diagram
2400
+ >>> from sympy.categories import DiagramGrid, XypicDiagramDrawer
2401
+ >>> A = Object("A")
2402
+ >>> B = Object("B")
2403
+ >>> C = Object("C")
2404
+ >>> f = NamedMorphism(A, B, "f")
2405
+ >>> g = NamedMorphism(B, C, "g")
2406
+ >>> diagram = Diagram([f, g], {g * f: "unique"})
2407
+
2408
+ To draw this diagram, its objects need to be laid out with a
2409
+ :class:`DiagramGrid`::
2410
+
2411
+ >>> grid = DiagramGrid(diagram)
2412
+
2413
+ Finally, the drawing:
2414
+
2415
+ >>> drawer = XypicDiagramDrawer()
2416
+ >>> print(drawer.draw(diagram, grid))
2417
+ \xymatrix{
2418
+ A \ar[d]_{g\circ f} \ar[r]^{f} & B \ar[ld]^{g} \\
2419
+ C &
2420
+ }
2421
+
2422
+ The argument ``masked`` can be used to skip morphisms in the
2423
+ presentation of the diagram:
2424
+
2425
+ >>> print(drawer.draw(diagram, grid, masked=[g * f]))
2426
+ \xymatrix{
2427
+ A \ar[r]^{f} & B \ar[ld]^{g} \\
2428
+ C &
2429
+ }
2430
+
2431
+ Finally, the ``diagram_format`` argument can be used to
2432
+ specify the format string of the diagram. For example, to
2433
+ increase the spacing by 1 cm, proceeding as follows:
2434
+
2435
+ >>> print(drawer.draw(diagram, grid, diagram_format="@+1cm"))
2436
+ \xymatrix@+1cm{
2437
+ A \ar[d]_{g\circ f} \ar[r]^{f} & B \ar[ld]^{g} \\
2438
+ C &
2439
+ }
2440
+
2441
+ """
2442
+ # This method works in several steps. It starts by removing
2443
+ # the masked morphisms, if necessary, and then maps objects to
2444
+ # their positions in the grid (coordinate tuples). Remember
2445
+ # that objects are unique in ``Diagram`` and in the layout
2446
+ # produced by ``DiagramGrid``, so every object is mapped to a
2447
+ # single coordinate pair.
2448
+ #
2449
+ # The next step is the central step and is concerned with
2450
+ # analysing the morphisms of the diagram and deciding how to
2451
+ # draw them. For example, how to curve the arrows is decided
2452
+ # at this step. The bulk of the analysis is implemented in
2453
+ # ``_process_morphism``, to the result of which the
2454
+ # appropriate formatters are applied.
2455
+ #
2456
+ # The result of the previous step is a list of
2457
+ # ``ArrowStringDescription``. After the analysis and
2458
+ # application of formatters, some extra logic tries to assure
2459
+ # better positioning of morphism labels (for example, an
2460
+ # attempt is made to avoid the situations when arrows cross
2461
+ # labels). This functionality constitutes the next step and
2462
+ # is implemented in ``_push_labels_out``. Note that label
2463
+ # positions which have been set via a formatter are not
2464
+ # affected in this step.
2465
+ #
2466
+ # Finally, at the closing step, the array of
2467
+ # ``ArrowStringDescription`` and the layout information
2468
+ # incorporated in ``DiagramGrid`` are combined to produce the
2469
+ # resulting Xy-pic picture. This part of code lies in
2470
+ # ``_build_xypic_string``.
2471
+
2472
+ if not masked:
2473
+ morphisms_props = grid.morphisms
2474
+ else:
2475
+ morphisms_props = {}
2476
+ for m, props in grid.morphisms.items():
2477
+ if m in masked:
2478
+ continue
2479
+ morphisms_props[m] = props
2480
+
2481
+ # Build the mapping between objects and their position in the
2482
+ # grid.
2483
+ object_coords = {}
2484
+ for i in range(grid.height):
2485
+ for j in range(grid.width):
2486
+ if grid[i, j]:
2487
+ object_coords[grid[i, j]] = (i, j)
2488
+
2489
+ morphisms = sorted(morphisms_props,
2490
+ key=lambda m: XypicDiagramDrawer._morphism_sort_key(
2491
+ m, object_coords))
2492
+
2493
+ # Build the tuples defining the string representations of
2494
+ # morphisms.
2495
+ morphisms_str_info = {}
2496
+ for morphism in morphisms:
2497
+ string_description = self._process_morphism(
2498
+ diagram, grid, morphism, object_coords, morphisms,
2499
+ morphisms_str_info)
2500
+
2501
+ if self.default_arrow_formatter:
2502
+ self.default_arrow_formatter(string_description)
2503
+
2504
+ for prop in morphisms_props[morphism]:
2505
+ # prop is a Symbol. TODO: Find out why.
2506
+ if prop.name in self.arrow_formatters:
2507
+ formatter = self.arrow_formatters[prop.name]
2508
+ formatter(string_description)
2509
+
2510
+ morphisms_str_info[morphism] = string_description
2511
+
2512
+ # Reposition the labels a bit.
2513
+ self._push_labels_out(morphisms_str_info, grid, object_coords)
2514
+
2515
+ return XypicDiagramDrawer._build_xypic_string(
2516
+ diagram, grid, morphisms, morphisms_str_info, diagram_format)
2517
+
2518
+
2519
+ def xypic_draw_diagram(diagram, masked=None, diagram_format="",
2520
+ groups=None, **hints):
2521
+ r"""
2522
+ Provides a shortcut combining :class:`DiagramGrid` and
2523
+ :class:`XypicDiagramDrawer`. Returns an Xy-pic presentation of
2524
+ ``diagram``. The argument ``masked`` is a list of morphisms which
2525
+ will be not be drawn. The argument ``diagram_format`` is the
2526
+ format string inserted after "\xymatrix". ``groups`` should be a
2527
+ set of logical groups. The ``hints`` will be passed directly to
2528
+ the constructor of :class:`DiagramGrid`.
2529
+
2530
+ For more information about the arguments, see the docstrings of
2531
+ :class:`DiagramGrid` and ``XypicDiagramDrawer.draw``.
2532
+
2533
+ Examples
2534
+ ========
2535
+
2536
+ >>> from sympy.categories import Object, NamedMorphism, Diagram
2537
+ >>> from sympy.categories import xypic_draw_diagram
2538
+ >>> A = Object("A")
2539
+ >>> B = Object("B")
2540
+ >>> C = Object("C")
2541
+ >>> f = NamedMorphism(A, B, "f")
2542
+ >>> g = NamedMorphism(B, C, "g")
2543
+ >>> diagram = Diagram([f, g], {g * f: "unique"})
2544
+ >>> print(xypic_draw_diagram(diagram))
2545
+ \xymatrix{
2546
+ A \ar[d]_{g\circ f} \ar[r]^{f} & B \ar[ld]^{g} \\
2547
+ C &
2548
+ }
2549
+
2550
+ See Also
2551
+ ========
2552
+
2553
+ XypicDiagramDrawer, DiagramGrid
2554
+ """
2555
+ grid = DiagramGrid(diagram, groups, **hints)
2556
+ drawer = XypicDiagramDrawer()
2557
+ return drawer.draw(diagram, grid, masked, diagram_format)
2558
+
2559
+
2560
+ @doctest_depends_on(exe=('latex', 'dvipng'), modules=('pyglet',))
2561
+ def preview_diagram(diagram, masked=None, diagram_format="", groups=None,
2562
+ output='png', viewer=None, euler=True, **hints):
2563
+ """
2564
+ Combines the functionality of ``xypic_draw_diagram`` and
2565
+ ``sympy.printing.preview``. The arguments ``masked``,
2566
+ ``diagram_format``, ``groups``, and ``hints`` are passed to
2567
+ ``xypic_draw_diagram``, while ``output``, ``viewer, and ``euler``
2568
+ are passed to ``preview``.
2569
+
2570
+ Examples
2571
+ ========
2572
+
2573
+ >>> from sympy.categories import Object, NamedMorphism, Diagram
2574
+ >>> from sympy.categories import preview_diagram
2575
+ >>> A = Object("A")
2576
+ >>> B = Object("B")
2577
+ >>> C = Object("C")
2578
+ >>> f = NamedMorphism(A, B, "f")
2579
+ >>> g = NamedMorphism(B, C, "g")
2580
+ >>> d = Diagram([f, g], {g * f: "unique"})
2581
+ >>> preview_diagram(d)
2582
+
2583
+ See Also
2584
+ ========
2585
+
2586
+ XypicDiagramDrawer
2587
+ """
2588
+ from sympy.printing import preview
2589
+ latex_output = xypic_draw_diagram(diagram, masked, diagram_format,
2590
+ groups, **hints)
2591
+ preview(latex_output, output, viewer, euler, ("xypic",))
venv/lib/python3.10/site-packages/sympy/categories/tests/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/sympy/categories/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (190 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/categories/tests/__pycache__/test_baseclasses.cpython-310.pyc ADDED
Binary file (4.99 kB). View file
 
venv/lib/python3.10/site-packages/sympy/categories/tests/__pycache__/test_drawing.cpython-310.pyc ADDED
Binary file (17.5 kB). View file
 
venv/lib/python3.10/site-packages/sympy/categories/tests/test_baseclasses.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.categories import (Object, Morphism, IdentityMorphism,
2
+ NamedMorphism, CompositeMorphism,
3
+ Diagram, Category)
4
+ from sympy.categories.baseclasses import Class
5
+ from sympy.testing.pytest import raises
6
+ from sympy.core.containers import (Dict, Tuple)
7
+ from sympy.sets import EmptySet
8
+ from sympy.sets.sets import FiniteSet
9
+
10
+
11
+ def test_morphisms():
12
+ A = Object("A")
13
+ B = Object("B")
14
+ C = Object("C")
15
+ D = Object("D")
16
+
17
+ # Test the base morphism.
18
+ f = NamedMorphism(A, B, "f")
19
+ assert f.domain == A
20
+ assert f.codomain == B
21
+ assert f == NamedMorphism(A, B, "f")
22
+
23
+ # Test identities.
24
+ id_A = IdentityMorphism(A)
25
+ id_B = IdentityMorphism(B)
26
+ assert id_A.domain == A
27
+ assert id_A.codomain == A
28
+ assert id_A == IdentityMorphism(A)
29
+ assert id_A != id_B
30
+
31
+ # Test named morphisms.
32
+ g = NamedMorphism(B, C, "g")
33
+ assert g.name == "g"
34
+ assert g != f
35
+ assert g == NamedMorphism(B, C, "g")
36
+ assert g != NamedMorphism(B, C, "f")
37
+
38
+ # Test composite morphisms.
39
+ assert f == CompositeMorphism(f)
40
+
41
+ k = g.compose(f)
42
+ assert k.domain == A
43
+ assert k.codomain == C
44
+ assert k.components == Tuple(f, g)
45
+ assert g * f == k
46
+ assert CompositeMorphism(f, g) == k
47
+
48
+ assert CompositeMorphism(g * f) == g * f
49
+
50
+ # Test the associativity of composition.
51
+ h = NamedMorphism(C, D, "h")
52
+
53
+ p = h * g
54
+ u = h * g * f
55
+
56
+ assert h * k == u
57
+ assert p * f == u
58
+ assert CompositeMorphism(f, g, h) == u
59
+
60
+ # Test flattening.
61
+ u2 = u.flatten("u")
62
+ assert isinstance(u2, NamedMorphism)
63
+ assert u2.name == "u"
64
+ assert u2.domain == A
65
+ assert u2.codomain == D
66
+
67
+ # Test identities.
68
+ assert f * id_A == f
69
+ assert id_B * f == f
70
+ assert id_A * id_A == id_A
71
+ assert CompositeMorphism(id_A) == id_A
72
+
73
+ # Test bad compositions.
74
+ raises(ValueError, lambda: f * g)
75
+
76
+ raises(TypeError, lambda: f.compose(None))
77
+ raises(TypeError, lambda: id_A.compose(None))
78
+ raises(TypeError, lambda: f * None)
79
+ raises(TypeError, lambda: id_A * None)
80
+
81
+ raises(TypeError, lambda: CompositeMorphism(f, None, 1))
82
+
83
+ raises(ValueError, lambda: NamedMorphism(A, B, ""))
84
+ raises(NotImplementedError, lambda: Morphism(A, B))
85
+
86
+
87
+ def test_diagram():
88
+ A = Object("A")
89
+ B = Object("B")
90
+ C = Object("C")
91
+
92
+ f = NamedMorphism(A, B, "f")
93
+ g = NamedMorphism(B, C, "g")
94
+ id_A = IdentityMorphism(A)
95
+ id_B = IdentityMorphism(B)
96
+
97
+ empty = EmptySet
98
+
99
+ # Test the addition of identities.
100
+ d1 = Diagram([f])
101
+
102
+ assert d1.objects == FiniteSet(A, B)
103
+ assert d1.hom(A, B) == (FiniteSet(f), empty)
104
+ assert d1.hom(A, A) == (FiniteSet(id_A), empty)
105
+ assert d1.hom(B, B) == (FiniteSet(id_B), empty)
106
+
107
+ assert d1 == Diagram([id_A, f])
108
+ assert d1 == Diagram([f, f])
109
+
110
+ # Test the addition of composites.
111
+ d2 = Diagram([f, g])
112
+ homAC = d2.hom(A, C)[0]
113
+
114
+ assert d2.objects == FiniteSet(A, B, C)
115
+ assert g * f in d2.premises.keys()
116
+ assert homAC == FiniteSet(g * f)
117
+
118
+ # Test equality, inequality and hash.
119
+ d11 = Diagram([f])
120
+
121
+ assert d1 == d11
122
+ assert d1 != d2
123
+ assert hash(d1) == hash(d11)
124
+
125
+ d11 = Diagram({f: "unique"})
126
+ assert d1 != d11
127
+
128
+ # Make sure that (re-)adding composites (with new properties)
129
+ # works as expected.
130
+ d = Diagram([f, g], {g * f: "unique"})
131
+ assert d.conclusions == Dict({g * f: FiniteSet("unique")})
132
+
133
+ # Check the hom-sets when there are premises and conclusions.
134
+ assert d.hom(A, C) == (FiniteSet(g * f), FiniteSet(g * f))
135
+ d = Diagram([f, g], [g * f])
136
+ assert d.hom(A, C) == (FiniteSet(g * f), FiniteSet(g * f))
137
+
138
+ # Check how the properties of composite morphisms are computed.
139
+ d = Diagram({f: ["unique", "isomorphism"], g: "unique"})
140
+ assert d.premises[g * f] == FiniteSet("unique")
141
+
142
+ # Check that conclusion morphisms with new objects are not allowed.
143
+ d = Diagram([f], [g])
144
+ assert d.conclusions == Dict({})
145
+
146
+ # Test an empty diagram.
147
+ d = Diagram()
148
+ assert d.premises == Dict({})
149
+ assert d.conclusions == Dict({})
150
+ assert d.objects == empty
151
+
152
+ # Check a SymPy Dict object.
153
+ d = Diagram(Dict({f: FiniteSet("unique", "isomorphism"), g: "unique"}))
154
+ assert d.premises[g * f] == FiniteSet("unique")
155
+
156
+ # Check the addition of components of composite morphisms.
157
+ d = Diagram([g * f])
158
+ assert f in d.premises
159
+ assert g in d.premises
160
+
161
+ # Check subdiagrams.
162
+ d = Diagram([f, g], {g * f: "unique"})
163
+
164
+ d1 = Diagram([f])
165
+ assert d.is_subdiagram(d1)
166
+ assert not d1.is_subdiagram(d)
167
+
168
+ d = Diagram([NamedMorphism(B, A, "f'")])
169
+ assert not d.is_subdiagram(d1)
170
+ assert not d1.is_subdiagram(d)
171
+
172
+ d1 = Diagram([f, g], {g * f: ["unique", "something"]})
173
+ assert not d.is_subdiagram(d1)
174
+ assert not d1.is_subdiagram(d)
175
+
176
+ d = Diagram({f: "blooh"})
177
+ d1 = Diagram({f: "bleeh"})
178
+ assert not d.is_subdiagram(d1)
179
+ assert not d1.is_subdiagram(d)
180
+
181
+ d = Diagram([f, g], {f: "unique", g * f: "veryunique"})
182
+ d1 = d.subdiagram_from_objects(FiniteSet(A, B))
183
+ assert d1 == Diagram([f], {f: "unique"})
184
+ raises(ValueError, lambda: d.subdiagram_from_objects(FiniteSet(A,
185
+ Object("D"))))
186
+
187
+ raises(ValueError, lambda: Diagram({IdentityMorphism(A): "unique"}))
188
+
189
+
190
+ def test_category():
191
+ A = Object("A")
192
+ B = Object("B")
193
+ C = Object("C")
194
+
195
+ f = NamedMorphism(A, B, "f")
196
+ g = NamedMorphism(B, C, "g")
197
+
198
+ d1 = Diagram([f, g])
199
+ d2 = Diagram([f])
200
+
201
+ objects = d1.objects | d2.objects
202
+
203
+ K = Category("K", objects, commutative_diagrams=[d1, d2])
204
+
205
+ assert K.name == "K"
206
+ assert K.objects == Class(objects)
207
+ assert K.commutative_diagrams == FiniteSet(d1, d2)
208
+
209
+ raises(ValueError, lambda: Category(""))
venv/lib/python3.10/site-packages/sympy/categories/tests/test_drawing.py ADDED
@@ -0,0 +1,919 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.categories.diagram_drawing import _GrowableGrid, ArrowStringDescription
2
+ from sympy.categories import (DiagramGrid, Object, NamedMorphism,
3
+ Diagram, XypicDiagramDrawer, xypic_draw_diagram)
4
+ from sympy.sets.sets import FiniteSet
5
+
6
+
7
+ def test_GrowableGrid():
8
+ grid = _GrowableGrid(1, 2)
9
+
10
+ # Check dimensions.
11
+ assert grid.width == 1
12
+ assert grid.height == 2
13
+
14
+ # Check initialization of elements.
15
+ assert grid[0, 0] is None
16
+ assert grid[1, 0] is None
17
+
18
+ # Check assignment to elements.
19
+ grid[0, 0] = 1
20
+ grid[1, 0] = "two"
21
+
22
+ assert grid[0, 0] == 1
23
+ assert grid[1, 0] == "two"
24
+
25
+ # Check appending a row.
26
+ grid.append_row()
27
+
28
+ assert grid.width == 1
29
+ assert grid.height == 3
30
+
31
+ assert grid[0, 0] == 1
32
+ assert grid[1, 0] == "two"
33
+ assert grid[2, 0] is None
34
+
35
+ # Check appending a column.
36
+ grid.append_column()
37
+ assert grid.width == 2
38
+ assert grid.height == 3
39
+
40
+ assert grid[0, 0] == 1
41
+ assert grid[1, 0] == "two"
42
+ assert grid[2, 0] is None
43
+
44
+ assert grid[0, 1] is None
45
+ assert grid[1, 1] is None
46
+ assert grid[2, 1] is None
47
+
48
+ grid = _GrowableGrid(1, 2)
49
+ grid[0, 0] = 1
50
+ grid[1, 0] = "two"
51
+
52
+ # Check prepending a row.
53
+ grid.prepend_row()
54
+ assert grid.width == 1
55
+ assert grid.height == 3
56
+
57
+ assert grid[0, 0] is None
58
+ assert grid[1, 0] == 1
59
+ assert grid[2, 0] == "two"
60
+
61
+ # Check prepending a column.
62
+ grid.prepend_column()
63
+ assert grid.width == 2
64
+ assert grid.height == 3
65
+
66
+ assert grid[0, 0] is None
67
+ assert grid[1, 0] is None
68
+ assert grid[2, 0] is None
69
+
70
+ assert grid[0, 1] is None
71
+ assert grid[1, 1] == 1
72
+ assert grid[2, 1] == "two"
73
+
74
+
75
+ def test_DiagramGrid():
76
+ # Set up some objects and morphisms.
77
+ A = Object("A")
78
+ B = Object("B")
79
+ C = Object("C")
80
+ D = Object("D")
81
+ E = Object("E")
82
+
83
+ f = NamedMorphism(A, B, "f")
84
+ g = NamedMorphism(B, C, "g")
85
+ h = NamedMorphism(D, A, "h")
86
+ k = NamedMorphism(D, B, "k")
87
+
88
+ # A one-morphism diagram.
89
+ d = Diagram([f])
90
+ grid = DiagramGrid(d)
91
+
92
+ assert grid.width == 2
93
+ assert grid.height == 1
94
+ assert grid[0, 0] == A
95
+ assert grid[0, 1] == B
96
+ assert grid.morphisms == {f: FiniteSet()}
97
+
98
+ # A triangle.
99
+ d = Diagram([f, g], {g * f: "unique"})
100
+ grid = DiagramGrid(d)
101
+
102
+ assert grid.width == 2
103
+ assert grid.height == 2
104
+ assert grid[0, 0] == A
105
+ assert grid[0, 1] == B
106
+ assert grid[1, 0] == C
107
+ assert grid[1, 1] is None
108
+ assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(),
109
+ g * f: FiniteSet("unique")}
110
+
111
+ # A triangle with a "loop" morphism.
112
+ l_A = NamedMorphism(A, A, "l_A")
113
+ d = Diagram([f, g, l_A])
114
+ grid = DiagramGrid(d)
115
+
116
+ assert grid.width == 2
117
+ assert grid.height == 2
118
+ assert grid[0, 0] == A
119
+ assert grid[0, 1] == B
120
+ assert grid[1, 0] is None
121
+ assert grid[1, 1] == C
122
+ assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), l_A: FiniteSet()}
123
+
124
+ # A simple diagram.
125
+ d = Diagram([f, g, h, k])
126
+ grid = DiagramGrid(d)
127
+
128
+ assert grid.width == 3
129
+ assert grid.height == 2
130
+ assert grid[0, 0] == A
131
+ assert grid[0, 1] == B
132
+ assert grid[0, 2] == D
133
+ assert grid[1, 0] is None
134
+ assert grid[1, 1] == C
135
+ assert grid[1, 2] is None
136
+ assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), h: FiniteSet(),
137
+ k: FiniteSet()}
138
+
139
+ assert str(grid) == '[[Object("A"), Object("B"), Object("D")], ' \
140
+ '[None, Object("C"), None]]'
141
+
142
+ # A chain of morphisms.
143
+ f = NamedMorphism(A, B, "f")
144
+ g = NamedMorphism(B, C, "g")
145
+ h = NamedMorphism(C, D, "h")
146
+ k = NamedMorphism(D, E, "k")
147
+ d = Diagram([f, g, h, k])
148
+ grid = DiagramGrid(d)
149
+
150
+ assert grid.width == 3
151
+ assert grid.height == 3
152
+ assert grid[0, 0] == A
153
+ assert grid[0, 1] == B
154
+ assert grid[0, 2] is None
155
+ assert grid[1, 0] is None
156
+ assert grid[1, 1] == C
157
+ assert grid[1, 2] == D
158
+ assert grid[2, 0] is None
159
+ assert grid[2, 1] is None
160
+ assert grid[2, 2] == E
161
+ assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), h: FiniteSet(),
162
+ k: FiniteSet()}
163
+
164
+ # A square.
165
+ f = NamedMorphism(A, B, "f")
166
+ g = NamedMorphism(B, D, "g")
167
+ h = NamedMorphism(A, C, "h")
168
+ k = NamedMorphism(C, D, "k")
169
+ d = Diagram([f, g, h, k])
170
+ grid = DiagramGrid(d)
171
+
172
+ assert grid.width == 2
173
+ assert grid.height == 2
174
+ assert grid[0, 0] == A
175
+ assert grid[0, 1] == B
176
+ assert grid[1, 0] == C
177
+ assert grid[1, 1] == D
178
+ assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), h: FiniteSet(),
179
+ k: FiniteSet()}
180
+
181
+ # A strange diagram which resulted from a typo when creating a
182
+ # test for five lemma, but which allowed to stop one extra problem
183
+ # in the algorithm.
184
+ A = Object("A")
185
+ B = Object("B")
186
+ C = Object("C")
187
+ D = Object("D")
188
+ E = Object("E")
189
+ A_ = Object("A'")
190
+ B_ = Object("B'")
191
+ C_ = Object("C'")
192
+ D_ = Object("D'")
193
+ E_ = Object("E'")
194
+
195
+ f = NamedMorphism(A, B, "f")
196
+ g = NamedMorphism(B, C, "g")
197
+ h = NamedMorphism(C, D, "h")
198
+ i = NamedMorphism(D, E, "i")
199
+
200
+ # These 4 morphisms should be between primed objects.
201
+ j = NamedMorphism(A, B, "j")
202
+ k = NamedMorphism(B, C, "k")
203
+ l = NamedMorphism(C, D, "l")
204
+ m = NamedMorphism(D, E, "m")
205
+
206
+ o = NamedMorphism(A, A_, "o")
207
+ p = NamedMorphism(B, B_, "p")
208
+ q = NamedMorphism(C, C_, "q")
209
+ r = NamedMorphism(D, D_, "r")
210
+ s = NamedMorphism(E, E_, "s")
211
+
212
+ d = Diagram([f, g, h, i, j, k, l, m, o, p, q, r, s])
213
+ grid = DiagramGrid(d)
214
+
215
+ assert grid.width == 3
216
+ assert grid.height == 4
217
+ assert grid[0, 0] is None
218
+ assert grid[0, 1] == A
219
+ assert grid[0, 2] == A_
220
+ assert grid[1, 0] == C
221
+ assert grid[1, 1] == B
222
+ assert grid[1, 2] == B_
223
+ assert grid[2, 0] == C_
224
+ assert grid[2, 1] == D
225
+ assert grid[2, 2] == D_
226
+ assert grid[3, 0] is None
227
+ assert grid[3, 1] == E
228
+ assert grid[3, 2] == E_
229
+
230
+ morphisms = {}
231
+ for m in [f, g, h, i, j, k, l, m, o, p, q, r, s]:
232
+ morphisms[m] = FiniteSet()
233
+ assert grid.morphisms == morphisms
234
+
235
+ # A cube.
236
+ A1 = Object("A1")
237
+ A2 = Object("A2")
238
+ A3 = Object("A3")
239
+ A4 = Object("A4")
240
+ A5 = Object("A5")
241
+ A6 = Object("A6")
242
+ A7 = Object("A7")
243
+ A8 = Object("A8")
244
+
245
+ # The top face of the cube.
246
+ f1 = NamedMorphism(A1, A2, "f1")
247
+ f2 = NamedMorphism(A1, A3, "f2")
248
+ f3 = NamedMorphism(A2, A4, "f3")
249
+ f4 = NamedMorphism(A3, A4, "f3")
250
+
251
+ # The bottom face of the cube.
252
+ f5 = NamedMorphism(A5, A6, "f5")
253
+ f6 = NamedMorphism(A5, A7, "f6")
254
+ f7 = NamedMorphism(A6, A8, "f7")
255
+ f8 = NamedMorphism(A7, A8, "f8")
256
+
257
+ # The remaining morphisms.
258
+ f9 = NamedMorphism(A1, A5, "f9")
259
+ f10 = NamedMorphism(A2, A6, "f10")
260
+ f11 = NamedMorphism(A3, A7, "f11")
261
+ f12 = NamedMorphism(A4, A8, "f11")
262
+
263
+ d = Diagram([f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12])
264
+ grid = DiagramGrid(d)
265
+
266
+ assert grid.width == 4
267
+ assert grid.height == 3
268
+ assert grid[0, 0] is None
269
+ assert grid[0, 1] == A5
270
+ assert grid[0, 2] == A6
271
+ assert grid[0, 3] is None
272
+ assert grid[1, 0] is None
273
+ assert grid[1, 1] == A1
274
+ assert grid[1, 2] == A2
275
+ assert grid[1, 3] is None
276
+ assert grid[2, 0] == A7
277
+ assert grid[2, 1] == A3
278
+ assert grid[2, 2] == A4
279
+ assert grid[2, 3] == A8
280
+
281
+ morphisms = {}
282
+ for m in [f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12]:
283
+ morphisms[m] = FiniteSet()
284
+ assert grid.morphisms == morphisms
285
+
286
+ # A line diagram.
287
+ A = Object("A")
288
+ B = Object("B")
289
+ C = Object("C")
290
+ D = Object("D")
291
+ E = Object("E")
292
+
293
+ f = NamedMorphism(A, B, "f")
294
+ g = NamedMorphism(B, C, "g")
295
+ h = NamedMorphism(C, D, "h")
296
+ i = NamedMorphism(D, E, "i")
297
+ d = Diagram([f, g, h, i])
298
+ grid = DiagramGrid(d, layout="sequential")
299
+
300
+ assert grid.width == 5
301
+ assert grid.height == 1
302
+ assert grid[0, 0] == A
303
+ assert grid[0, 1] == B
304
+ assert grid[0, 2] == C
305
+ assert grid[0, 3] == D
306
+ assert grid[0, 4] == E
307
+ assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), h: FiniteSet(),
308
+ i: FiniteSet()}
309
+
310
+ # Test the transposed version.
311
+ grid = DiagramGrid(d, layout="sequential", transpose=True)
312
+
313
+ assert grid.width == 1
314
+ assert grid.height == 5
315
+ assert grid[0, 0] == A
316
+ assert grid[1, 0] == B
317
+ assert grid[2, 0] == C
318
+ assert grid[3, 0] == D
319
+ assert grid[4, 0] == E
320
+ assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), h: FiniteSet(),
321
+ i: FiniteSet()}
322
+
323
+ # A pullback.
324
+ m1 = NamedMorphism(A, B, "m1")
325
+ m2 = NamedMorphism(A, C, "m2")
326
+ s1 = NamedMorphism(B, D, "s1")
327
+ s2 = NamedMorphism(C, D, "s2")
328
+ f1 = NamedMorphism(E, B, "f1")
329
+ f2 = NamedMorphism(E, C, "f2")
330
+ g = NamedMorphism(E, A, "g")
331
+
332
+ d = Diagram([m1, m2, s1, s2, f1, f2], {g: "unique"})
333
+ grid = DiagramGrid(d)
334
+
335
+ assert grid.width == 3
336
+ assert grid.height == 2
337
+ assert grid[0, 0] == A
338
+ assert grid[0, 1] == B
339
+ assert grid[0, 2] == E
340
+ assert grid[1, 0] == C
341
+ assert grid[1, 1] == D
342
+ assert grid[1, 2] is None
343
+
344
+ morphisms = {g: FiniteSet("unique")}
345
+ for m in [m1, m2, s1, s2, f1, f2]:
346
+ morphisms[m] = FiniteSet()
347
+ assert grid.morphisms == morphisms
348
+
349
+ # Test the pullback with sequential layout, just for stress
350
+ # testing.
351
+ grid = DiagramGrid(d, layout="sequential")
352
+
353
+ assert grid.width == 5
354
+ assert grid.height == 1
355
+ assert grid[0, 0] == D
356
+ assert grid[0, 1] == B
357
+ assert grid[0, 2] == A
358
+ assert grid[0, 3] == C
359
+ assert grid[0, 4] == E
360
+ assert grid.morphisms == morphisms
361
+
362
+ # Test a pullback with object grouping.
363
+ grid = DiagramGrid(d, groups=FiniteSet(E, FiniteSet(A, B, C, D)))
364
+
365
+ assert grid.width == 3
366
+ assert grid.height == 2
367
+ assert grid[0, 0] == E
368
+ assert grid[0, 1] == A
369
+ assert grid[0, 2] == B
370
+ assert grid[1, 0] is None
371
+ assert grid[1, 1] == C
372
+ assert grid[1, 2] == D
373
+ assert grid.morphisms == morphisms
374
+
375
+ # Five lemma, actually.
376
+ A = Object("A")
377
+ B = Object("B")
378
+ C = Object("C")
379
+ D = Object("D")
380
+ E = Object("E")
381
+ A_ = Object("A'")
382
+ B_ = Object("B'")
383
+ C_ = Object("C'")
384
+ D_ = Object("D'")
385
+ E_ = Object("E'")
386
+
387
+ f = NamedMorphism(A, B, "f")
388
+ g = NamedMorphism(B, C, "g")
389
+ h = NamedMorphism(C, D, "h")
390
+ i = NamedMorphism(D, E, "i")
391
+
392
+ j = NamedMorphism(A_, B_, "j")
393
+ k = NamedMorphism(B_, C_, "k")
394
+ l = NamedMorphism(C_, D_, "l")
395
+ m = NamedMorphism(D_, E_, "m")
396
+
397
+ o = NamedMorphism(A, A_, "o")
398
+ p = NamedMorphism(B, B_, "p")
399
+ q = NamedMorphism(C, C_, "q")
400
+ r = NamedMorphism(D, D_, "r")
401
+ s = NamedMorphism(E, E_, "s")
402
+
403
+ d = Diagram([f, g, h, i, j, k, l, m, o, p, q, r, s])
404
+ grid = DiagramGrid(d)
405
+
406
+ assert grid.width == 5
407
+ assert grid.height == 3
408
+ assert grid[0, 0] is None
409
+ assert grid[0, 1] == A
410
+ assert grid[0, 2] == A_
411
+ assert grid[0, 3] is None
412
+ assert grid[0, 4] is None
413
+ assert grid[1, 0] == C
414
+ assert grid[1, 1] == B
415
+ assert grid[1, 2] == B_
416
+ assert grid[1, 3] == C_
417
+ assert grid[1, 4] is None
418
+ assert grid[2, 0] == D
419
+ assert grid[2, 1] == E
420
+ assert grid[2, 2] is None
421
+ assert grid[2, 3] == D_
422
+ assert grid[2, 4] == E_
423
+
424
+ morphisms = {}
425
+ for m in [f, g, h, i, j, k, l, m, o, p, q, r, s]:
426
+ morphisms[m] = FiniteSet()
427
+ assert grid.morphisms == morphisms
428
+
429
+ # Test the five lemma with object grouping.
430
+ grid = DiagramGrid(d, FiniteSet(
431
+ FiniteSet(A, B, C, D, E), FiniteSet(A_, B_, C_, D_, E_)))
432
+
433
+ assert grid.width == 6
434
+ assert grid.height == 3
435
+ assert grid[0, 0] == A
436
+ assert grid[0, 1] == B
437
+ assert grid[0, 2] is None
438
+ assert grid[0, 3] == A_
439
+ assert grid[0, 4] == B_
440
+ assert grid[0, 5] is None
441
+ assert grid[1, 0] is None
442
+ assert grid[1, 1] == C
443
+ assert grid[1, 2] == D
444
+ assert grid[1, 3] is None
445
+ assert grid[1, 4] == C_
446
+ assert grid[1, 5] == D_
447
+ assert grid[2, 0] is None
448
+ assert grid[2, 1] is None
449
+ assert grid[2, 2] == E
450
+ assert grid[2, 3] is None
451
+ assert grid[2, 4] is None
452
+ assert grid[2, 5] == E_
453
+ assert grid.morphisms == morphisms
454
+
455
+ # Test the five lemma with object grouping, but mixing containers
456
+ # to represent groups.
457
+ grid = DiagramGrid(d, [(A, B, C, D, E), {A_, B_, C_, D_, E_}])
458
+
459
+ assert grid.width == 6
460
+ assert grid.height == 3
461
+ assert grid[0, 0] == A
462
+ assert grid[0, 1] == B
463
+ assert grid[0, 2] is None
464
+ assert grid[0, 3] == A_
465
+ assert grid[0, 4] == B_
466
+ assert grid[0, 5] is None
467
+ assert grid[1, 0] is None
468
+ assert grid[1, 1] == C
469
+ assert grid[1, 2] == D
470
+ assert grid[1, 3] is None
471
+ assert grid[1, 4] == C_
472
+ assert grid[1, 5] == D_
473
+ assert grid[2, 0] is None
474
+ assert grid[2, 1] is None
475
+ assert grid[2, 2] == E
476
+ assert grid[2, 3] is None
477
+ assert grid[2, 4] is None
478
+ assert grid[2, 5] == E_
479
+ assert grid.morphisms == morphisms
480
+
481
+ # Test the five lemma with object grouping and hints.
482
+ grid = DiagramGrid(d, {
483
+ FiniteSet(A, B, C, D, E): {"layout": "sequential",
484
+ "transpose": True},
485
+ FiniteSet(A_, B_, C_, D_, E_): {"layout": "sequential",
486
+ "transpose": True}},
487
+ transpose=True)
488
+
489
+ assert grid.width == 5
490
+ assert grid.height == 2
491
+ assert grid[0, 0] == A
492
+ assert grid[0, 1] == B
493
+ assert grid[0, 2] == C
494
+ assert grid[0, 3] == D
495
+ assert grid[0, 4] == E
496
+ assert grid[1, 0] == A_
497
+ assert grid[1, 1] == B_
498
+ assert grid[1, 2] == C_
499
+ assert grid[1, 3] == D_
500
+ assert grid[1, 4] == E_
501
+ assert grid.morphisms == morphisms
502
+
503
+ # A two-triangle disconnected diagram.
504
+ f = NamedMorphism(A, B, "f")
505
+ g = NamedMorphism(B, C, "g")
506
+ f_ = NamedMorphism(A_, B_, "f")
507
+ g_ = NamedMorphism(B_, C_, "g")
508
+ d = Diagram([f, g, f_, g_], {g * f: "unique", g_ * f_: "unique"})
509
+ grid = DiagramGrid(d)
510
+
511
+ assert grid.width == 4
512
+ assert grid.height == 2
513
+ assert grid[0, 0] == A
514
+ assert grid[0, 1] == B
515
+ assert grid[0, 2] == A_
516
+ assert grid[0, 3] == B_
517
+ assert grid[1, 0] == C
518
+ assert grid[1, 1] is None
519
+ assert grid[1, 2] == C_
520
+ assert grid[1, 3] is None
521
+ assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), f_: FiniteSet(),
522
+ g_: FiniteSet(), g * f: FiniteSet("unique"),
523
+ g_ * f_: FiniteSet("unique")}
524
+
525
+ # A two-morphism disconnected diagram.
526
+ f = NamedMorphism(A, B, "f")
527
+ g = NamedMorphism(C, D, "g")
528
+ d = Diagram([f, g])
529
+ grid = DiagramGrid(d)
530
+
531
+ assert grid.width == 4
532
+ assert grid.height == 1
533
+ assert grid[0, 0] == A
534
+ assert grid[0, 1] == B
535
+ assert grid[0, 2] == C
536
+ assert grid[0, 3] == D
537
+ assert grid.morphisms == {f: FiniteSet(), g: FiniteSet()}
538
+
539
+ # Test a one-object diagram.
540
+ f = NamedMorphism(A, A, "f")
541
+ d = Diagram([f])
542
+ grid = DiagramGrid(d)
543
+
544
+ assert grid.width == 1
545
+ assert grid.height == 1
546
+ assert grid[0, 0] == A
547
+
548
+ # Test a two-object disconnected diagram.
549
+ g = NamedMorphism(B, B, "g")
550
+ d = Diagram([f, g])
551
+ grid = DiagramGrid(d)
552
+
553
+ assert grid.width == 2
554
+ assert grid.height == 1
555
+ assert grid[0, 0] == A
556
+ assert grid[0, 1] == B
557
+
558
+
559
+ def test_DiagramGrid_pseudopod():
560
+ # Test a diagram in which even growing a pseudopod does not
561
+ # eventually help.
562
+ A = Object("A")
563
+ B = Object("B")
564
+ C = Object("C")
565
+ D = Object("D")
566
+ E = Object("E")
567
+ F = Object("F")
568
+ A_ = Object("A'")
569
+ B_ = Object("B'")
570
+ C_ = Object("C'")
571
+ D_ = Object("D'")
572
+ E_ = Object("E'")
573
+
574
+ f1 = NamedMorphism(A, B, "f1")
575
+ f2 = NamedMorphism(A, C, "f2")
576
+ f3 = NamedMorphism(A, D, "f3")
577
+ f4 = NamedMorphism(A, E, "f4")
578
+ f5 = NamedMorphism(A, A_, "f5")
579
+ f6 = NamedMorphism(A, B_, "f6")
580
+ f7 = NamedMorphism(A, C_, "f7")
581
+ f8 = NamedMorphism(A, D_, "f8")
582
+ f9 = NamedMorphism(A, E_, "f9")
583
+ f10 = NamedMorphism(A, F, "f10")
584
+ d = Diagram([f1, f2, f3, f4, f5, f6, f7, f8, f9, f10])
585
+ grid = DiagramGrid(d)
586
+
587
+ assert grid.width == 5
588
+ assert grid.height == 3
589
+ assert grid[0, 0] == E
590
+ assert grid[0, 1] == C
591
+ assert grid[0, 2] == C_
592
+ assert grid[0, 3] == E_
593
+ assert grid[0, 4] == F
594
+ assert grid[1, 0] == D
595
+ assert grid[1, 1] == A
596
+ assert grid[1, 2] == A_
597
+ assert grid[1, 3] is None
598
+ assert grid[1, 4] is None
599
+ assert grid[2, 0] == D_
600
+ assert grid[2, 1] == B
601
+ assert grid[2, 2] == B_
602
+ assert grid[2, 3] is None
603
+ assert grid[2, 4] is None
604
+
605
+ morphisms = {}
606
+ for f in [f1, f2, f3, f4, f5, f6, f7, f8, f9, f10]:
607
+ morphisms[f] = FiniteSet()
608
+ assert grid.morphisms == morphisms
609
+
610
+
611
+ def test_ArrowStringDescription():
612
+ astr = ArrowStringDescription("cm", "", None, "", "", "d", "r", "_", "f")
613
+ assert str(astr) == "\\ar[dr]_{f}"
614
+
615
+ astr = ArrowStringDescription("cm", "", 12, "", "", "d", "r", "_", "f")
616
+ assert str(astr) == "\\ar[dr]_{f}"
617
+
618
+ astr = ArrowStringDescription("cm", "^", 12, "", "", "d", "r", "_", "f")
619
+ assert str(astr) == "\\ar@/^12cm/[dr]_{f}"
620
+
621
+ astr = ArrowStringDescription("cm", "", 12, "r", "", "d", "r", "_", "f")
622
+ assert str(astr) == "\\ar[dr]_{f}"
623
+
624
+ astr = ArrowStringDescription("cm", "", 12, "r", "u", "d", "r", "_", "f")
625
+ assert str(astr) == "\\ar@(r,u)[dr]_{f}"
626
+
627
+ astr = ArrowStringDescription("cm", "", 12, "r", "u", "d", "r", "_", "f")
628
+ assert str(astr) == "\\ar@(r,u)[dr]_{f}"
629
+
630
+ astr = ArrowStringDescription("cm", "", 12, "r", "u", "d", "r", "_", "f")
631
+ astr.arrow_style = "{-->}"
632
+ assert str(astr) == "\\ar@(r,u)@{-->}[dr]_{f}"
633
+
634
+ astr = ArrowStringDescription("cm", "_", 12, "", "", "d", "r", "_", "f")
635
+ astr.arrow_style = "{-->}"
636
+ assert str(astr) == "\\ar@/_12cm/@{-->}[dr]_{f}"
637
+
638
+
639
+ def test_XypicDiagramDrawer_line():
640
+ # A linear diagram.
641
+ A = Object("A")
642
+ B = Object("B")
643
+ C = Object("C")
644
+ D = Object("D")
645
+ E = Object("E")
646
+
647
+ f = NamedMorphism(A, B, "f")
648
+ g = NamedMorphism(B, C, "g")
649
+ h = NamedMorphism(C, D, "h")
650
+ i = NamedMorphism(D, E, "i")
651
+ d = Diagram([f, g, h, i])
652
+ grid = DiagramGrid(d, layout="sequential")
653
+ drawer = XypicDiagramDrawer()
654
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
655
+ "A \\ar[r]^{f} & B \\ar[r]^{g} & C \\ar[r]^{h} & D \\ar[r]^{i} & E \n" \
656
+ "}\n"
657
+
658
+ # The same diagram, transposed.
659
+ grid = DiagramGrid(d, layout="sequential", transpose=True)
660
+ drawer = XypicDiagramDrawer()
661
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
662
+ "A \\ar[d]^{f} \\\\\n" \
663
+ "B \\ar[d]^{g} \\\\\n" \
664
+ "C \\ar[d]^{h} \\\\\n" \
665
+ "D \\ar[d]^{i} \\\\\n" \
666
+ "E \n" \
667
+ "}\n"
668
+
669
+
670
+ def test_XypicDiagramDrawer_triangle():
671
+ # A triangle diagram.
672
+ A = Object("A")
673
+ B = Object("B")
674
+ C = Object("C")
675
+ f = NamedMorphism(A, B, "f")
676
+ g = NamedMorphism(B, C, "g")
677
+
678
+ d = Diagram([f, g], {g * f: "unique"})
679
+ grid = DiagramGrid(d)
680
+ drawer = XypicDiagramDrawer()
681
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
682
+ "A \\ar[d]_{g\\circ f} \\ar[r]^{f} & B \\ar[ld]^{g} \\\\\n" \
683
+ "C & \n" \
684
+ "}\n"
685
+
686
+ # The same diagram, transposed.
687
+ grid = DiagramGrid(d, transpose=True)
688
+ drawer = XypicDiagramDrawer()
689
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
690
+ "A \\ar[r]^{g\\circ f} \\ar[d]_{f} & C \\\\\n" \
691
+ "B \\ar[ru]_{g} & \n" \
692
+ "}\n"
693
+
694
+ # The same diagram, with a masked morphism.
695
+ assert drawer.draw(d, grid, masked=[g]) == "\\xymatrix{\n" \
696
+ "A \\ar[r]^{g\\circ f} \\ar[d]_{f} & C \\\\\n" \
697
+ "B & \n" \
698
+ "}\n"
699
+
700
+ # The same diagram with a formatter for "unique".
701
+ def formatter(astr):
702
+ astr.label = "\\exists !" + astr.label
703
+ astr.arrow_style = "{-->}"
704
+
705
+ drawer.arrow_formatters["unique"] = formatter
706
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
707
+ "A \\ar@{-->}[r]^{\\exists !g\\circ f} \\ar[d]_{f} & C \\\\\n" \
708
+ "B \\ar[ru]_{g} & \n" \
709
+ "}\n"
710
+
711
+ # The same diagram with a default formatter.
712
+ def default_formatter(astr):
713
+ astr.label_displacement = "(0.45)"
714
+
715
+ drawer.default_arrow_formatter = default_formatter
716
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
717
+ "A \\ar@{-->}[r]^(0.45){\\exists !g\\circ f} \\ar[d]_(0.45){f} & C \\\\\n" \
718
+ "B \\ar[ru]_(0.45){g} & \n" \
719
+ "}\n"
720
+
721
+ # A triangle diagram with a lot of morphisms between the same
722
+ # objects.
723
+ f1 = NamedMorphism(B, A, "f1")
724
+ f2 = NamedMorphism(A, B, "f2")
725
+ g1 = NamedMorphism(C, B, "g1")
726
+ g2 = NamedMorphism(B, C, "g2")
727
+ d = Diagram([f, f1, f2, g, g1, g2], {f1 * g1: "unique", g2 * f2: "unique"})
728
+
729
+ grid = DiagramGrid(d, transpose=True)
730
+ drawer = XypicDiagramDrawer()
731
+ assert drawer.draw(d, grid, masked=[f1*g1*g2*f2, g2*f2*f1*g1]) == \
732
+ "\\xymatrix{\n" \
733
+ "A \\ar[r]^{g_{2}\\circ f_{2}} \\ar[d]_{f} \\ar@/^3mm/[d]^{f_{2}} " \
734
+ "& C \\ar@/^3mm/[l]^{f_{1}\\circ g_{1}} \\ar@/^3mm/[ld]^{g_{1}} \\\\\n" \
735
+ "B \\ar@/^3mm/[u]^{f_{1}} \\ar[ru]_{g} \\ar@/^3mm/[ru]^{g_{2}} & \n" \
736
+ "}\n"
737
+
738
+
739
+ def test_XypicDiagramDrawer_cube():
740
+ # A cube diagram.
741
+ A1 = Object("A1")
742
+ A2 = Object("A2")
743
+ A3 = Object("A3")
744
+ A4 = Object("A4")
745
+ A5 = Object("A5")
746
+ A6 = Object("A6")
747
+ A7 = Object("A7")
748
+ A8 = Object("A8")
749
+
750
+ # The top face of the cube.
751
+ f1 = NamedMorphism(A1, A2, "f1")
752
+ f2 = NamedMorphism(A1, A3, "f2")
753
+ f3 = NamedMorphism(A2, A4, "f3")
754
+ f4 = NamedMorphism(A3, A4, "f3")
755
+
756
+ # The bottom face of the cube.
757
+ f5 = NamedMorphism(A5, A6, "f5")
758
+ f6 = NamedMorphism(A5, A7, "f6")
759
+ f7 = NamedMorphism(A6, A8, "f7")
760
+ f8 = NamedMorphism(A7, A8, "f8")
761
+
762
+ # The remaining morphisms.
763
+ f9 = NamedMorphism(A1, A5, "f9")
764
+ f10 = NamedMorphism(A2, A6, "f10")
765
+ f11 = NamedMorphism(A3, A7, "f11")
766
+ f12 = NamedMorphism(A4, A8, "f11")
767
+
768
+ d = Diagram([f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12])
769
+ grid = DiagramGrid(d)
770
+ drawer = XypicDiagramDrawer()
771
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
772
+ "& A_{5} \\ar[r]^{f_{5}} \\ar[ldd]_{f_{6}} & A_{6} \\ar[rdd]^{f_{7}} " \
773
+ "& \\\\\n" \
774
+ "& A_{1} \\ar[r]^{f_{1}} \\ar[d]^{f_{2}} \\ar[u]^{f_{9}} & A_{2} " \
775
+ "\\ar[d]^{f_{3}} \\ar[u]_{f_{10}} & \\\\\n" \
776
+ "A_{7} \\ar@/_3mm/[rrr]_{f_{8}} & A_{3} \\ar[r]^{f_{3}} \\ar[l]_{f_{11}} " \
777
+ "& A_{4} \\ar[r]^{f_{11}} & A_{8} \n" \
778
+ "}\n"
779
+
780
+ # The same diagram, transposed.
781
+ grid = DiagramGrid(d, transpose=True)
782
+ drawer = XypicDiagramDrawer()
783
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
784
+ "& & A_{7} \\ar@/^3mm/[ddd]^{f_{8}} \\\\\n" \
785
+ "A_{5} \\ar[d]_{f_{5}} \\ar[rru]^{f_{6}} & A_{1} \\ar[d]^{f_{1}} " \
786
+ "\\ar[r]^{f_{2}} \\ar[l]^{f_{9}} & A_{3} \\ar[d]_{f_{3}} " \
787
+ "\\ar[u]^{f_{11}} \\\\\n" \
788
+ "A_{6} \\ar[rrd]_{f_{7}} & A_{2} \\ar[r]^{f_{3}} \\ar[l]^{f_{10}} " \
789
+ "& A_{4} \\ar[d]_{f_{11}} \\\\\n" \
790
+ "& & A_{8} \n" \
791
+ "}\n"
792
+
793
+
794
+ def test_XypicDiagramDrawer_curved_and_loops():
795
+ # A simple diagram, with a curved arrow.
796
+ A = Object("A")
797
+ B = Object("B")
798
+ C = Object("C")
799
+ D = Object("D")
800
+
801
+ f = NamedMorphism(A, B, "f")
802
+ g = NamedMorphism(B, C, "g")
803
+ h = NamedMorphism(D, A, "h")
804
+ k = NamedMorphism(D, B, "k")
805
+ d = Diagram([f, g, h, k])
806
+ grid = DiagramGrid(d)
807
+ drawer = XypicDiagramDrawer()
808
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
809
+ "A \\ar[r]_{f} & B \\ar[d]^{g} & D \\ar[l]^{k} \\ar@/_3mm/[ll]_{h} \\\\\n" \
810
+ "& C & \n" \
811
+ "}\n"
812
+
813
+ # The same diagram, transposed.
814
+ grid = DiagramGrid(d, transpose=True)
815
+ drawer = XypicDiagramDrawer()
816
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
817
+ "A \\ar[d]^{f} & \\\\\n" \
818
+ "B \\ar[r]^{g} & C \\\\\n" \
819
+ "D \\ar[u]_{k} \\ar@/^3mm/[uu]^{h} & \n" \
820
+ "}\n"
821
+
822
+ # The same diagram, larger and rotated.
823
+ assert drawer.draw(d, grid, diagram_format="@+1cm@dr") == \
824
+ "\\xymatrix@+1cm@dr{\n" \
825
+ "A \\ar[d]^{f} & \\\\\n" \
826
+ "B \\ar[r]^{g} & C \\\\\n" \
827
+ "D \\ar[u]_{k} \\ar@/^3mm/[uu]^{h} & \n" \
828
+ "}\n"
829
+
830
+ # A simple diagram with three curved arrows.
831
+ h1 = NamedMorphism(D, A, "h1")
832
+ h2 = NamedMorphism(A, D, "h2")
833
+ k = NamedMorphism(D, B, "k")
834
+ d = Diagram([f, g, h, k, h1, h2])
835
+ grid = DiagramGrid(d)
836
+ drawer = XypicDiagramDrawer()
837
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
838
+ "A \\ar[r]_{f} \\ar@/^3mm/[rr]^{h_{2}} & B \\ar[d]^{g} & D \\ar[l]^{k} " \
839
+ "\\ar@/_7mm/[ll]_{h} \\ar@/_11mm/[ll]_{h_{1}} \\\\\n" \
840
+ "& C & \n" \
841
+ "}\n"
842
+
843
+ # The same diagram, transposed.
844
+ grid = DiagramGrid(d, transpose=True)
845
+ drawer = XypicDiagramDrawer()
846
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
847
+ "A \\ar[d]^{f} \\ar@/_3mm/[dd]_{h_{2}} & \\\\\n" \
848
+ "B \\ar[r]^{g} & C \\\\\n" \
849
+ "D \\ar[u]_{k} \\ar@/^7mm/[uu]^{h} \\ar@/^11mm/[uu]^{h_{1}} & \n" \
850
+ "}\n"
851
+
852
+ # The same diagram, with "loop" morphisms.
853
+ l_A = NamedMorphism(A, A, "l_A")
854
+ l_D = NamedMorphism(D, D, "l_D")
855
+ l_C = NamedMorphism(C, C, "l_C")
856
+ d = Diagram([f, g, h, k, h1, h2, l_A, l_D, l_C])
857
+ grid = DiagramGrid(d)
858
+ drawer = XypicDiagramDrawer()
859
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
860
+ "A \\ar[r]_{f} \\ar@/^3mm/[rr]^{h_{2}} \\ar@(u,l)[]^{l_{A}} " \
861
+ "& B \\ar[d]^{g} & D \\ar[l]^{k} \\ar@/_7mm/[ll]_{h} " \
862
+ "\\ar@/_11mm/[ll]_{h_{1}} \\ar@(r,u)[]^{l_{D}} \\\\\n" \
863
+ "& C \\ar@(l,d)[]^{l_{C}} & \n" \
864
+ "}\n"
865
+
866
+ # The same diagram with "loop" morphisms, transposed.
867
+ grid = DiagramGrid(d, transpose=True)
868
+ drawer = XypicDiagramDrawer()
869
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
870
+ "A \\ar[d]^{f} \\ar@/_3mm/[dd]_{h_{2}} \\ar@(r,u)[]^{l_{A}} & \\\\\n" \
871
+ "B \\ar[r]^{g} & C \\ar@(r,u)[]^{l_{C}} \\\\\n" \
872
+ "D \\ar[u]_{k} \\ar@/^7mm/[uu]^{h} \\ar@/^11mm/[uu]^{h_{1}} " \
873
+ "\\ar@(l,d)[]^{l_{D}} & \n" \
874
+ "}\n"
875
+
876
+ # The same diagram with two "loop" morphisms per object.
877
+ l_A_ = NamedMorphism(A, A, "n_A")
878
+ l_D_ = NamedMorphism(D, D, "n_D")
879
+ l_C_ = NamedMorphism(C, C, "n_C")
880
+ d = Diagram([f, g, h, k, h1, h2, l_A, l_D, l_C, l_A_, l_D_, l_C_])
881
+ grid = DiagramGrid(d)
882
+ drawer = XypicDiagramDrawer()
883
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
884
+ "A \\ar[r]_{f} \\ar@/^3mm/[rr]^{h_{2}} \\ar@(u,l)[]^{l_{A}} " \
885
+ "\\ar@/^3mm/@(l,d)[]^{n_{A}} & B \\ar[d]^{g} & D \\ar[l]^{k} " \
886
+ "\\ar@/_7mm/[ll]_{h} \\ar@/_11mm/[ll]_{h_{1}} \\ar@(r,u)[]^{l_{D}} " \
887
+ "\\ar@/^3mm/@(d,r)[]^{n_{D}} \\\\\n" \
888
+ "& C \\ar@(l,d)[]^{l_{C}} \\ar@/^3mm/@(d,r)[]^{n_{C}} & \n" \
889
+ "}\n"
890
+
891
+ # The same diagram with two "loop" morphisms per object, transposed.
892
+ grid = DiagramGrid(d, transpose=True)
893
+ drawer = XypicDiagramDrawer()
894
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
895
+ "A \\ar[d]^{f} \\ar@/_3mm/[dd]_{h_{2}} \\ar@(r,u)[]^{l_{A}} " \
896
+ "\\ar@/^3mm/@(u,l)[]^{n_{A}} & \\\\\n" \
897
+ "B \\ar[r]^{g} & C \\ar@(r,u)[]^{l_{C}} \\ar@/^3mm/@(d,r)[]^{n_{C}} \\\\\n" \
898
+ "D \\ar[u]_{k} \\ar@/^7mm/[uu]^{h} \\ar@/^11mm/[uu]^{h_{1}} " \
899
+ "\\ar@(l,d)[]^{l_{D}} \\ar@/^3mm/@(d,r)[]^{n_{D}} & \n" \
900
+ "}\n"
901
+
902
+
903
+ def test_xypic_draw_diagram():
904
+ # A linear diagram.
905
+ A = Object("A")
906
+ B = Object("B")
907
+ C = Object("C")
908
+ D = Object("D")
909
+ E = Object("E")
910
+
911
+ f = NamedMorphism(A, B, "f")
912
+ g = NamedMorphism(B, C, "g")
913
+ h = NamedMorphism(C, D, "h")
914
+ i = NamedMorphism(D, E, "i")
915
+ d = Diagram([f, g, h, i])
916
+
917
+ grid = DiagramGrid(d, layout="sequential")
918
+ drawer = XypicDiagramDrawer()
919
+ assert drawer.draw(d, grid) == xypic_draw_diagram(d, layout="sequential")
venv/lib/python3.10/site-packages/sympy/crypto/__init__.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.crypto.crypto import (cycle_list,
2
+ encipher_shift, encipher_affine, encipher_substitution,
3
+ check_and_join, encipher_vigenere, decipher_vigenere, bifid5_square,
4
+ bifid6_square, encipher_hill, decipher_hill,
5
+ encipher_bifid5, encipher_bifid6, decipher_bifid5,
6
+ decipher_bifid6, encipher_kid_rsa, decipher_kid_rsa,
7
+ kid_rsa_private_key, kid_rsa_public_key, decipher_rsa, rsa_private_key,
8
+ rsa_public_key, encipher_rsa, lfsr_connection_polynomial,
9
+ lfsr_autocorrelation, lfsr_sequence, encode_morse, decode_morse,
10
+ elgamal_private_key, elgamal_public_key, decipher_elgamal,
11
+ encipher_elgamal, dh_private_key, dh_public_key, dh_shared_key,
12
+ padded_key, encipher_bifid, decipher_bifid, bifid_square, bifid5,
13
+ bifid6, bifid10, decipher_gm, encipher_gm, gm_public_key,
14
+ gm_private_key, bg_private_key, bg_public_key, encipher_bg, decipher_bg,
15
+ encipher_rot13, decipher_rot13, encipher_atbash, decipher_atbash,
16
+ encipher_railfence, decipher_railfence)
17
+
18
+ __all__ = [
19
+ 'cycle_list', 'encipher_shift', 'encipher_affine',
20
+ 'encipher_substitution', 'check_and_join', 'encipher_vigenere',
21
+ 'decipher_vigenere', 'bifid5_square', 'bifid6_square', 'encipher_hill',
22
+ 'decipher_hill', 'encipher_bifid5', 'encipher_bifid6', 'decipher_bifid5',
23
+ 'decipher_bifid6', 'encipher_kid_rsa', 'decipher_kid_rsa',
24
+ 'kid_rsa_private_key', 'kid_rsa_public_key', 'decipher_rsa',
25
+ 'rsa_private_key', 'rsa_public_key', 'encipher_rsa',
26
+ 'lfsr_connection_polynomial', 'lfsr_autocorrelation', 'lfsr_sequence',
27
+ 'encode_morse', 'decode_morse', 'elgamal_private_key',
28
+ 'elgamal_public_key', 'decipher_elgamal', 'encipher_elgamal',
29
+ 'dh_private_key', 'dh_public_key', 'dh_shared_key', 'padded_key',
30
+ 'encipher_bifid', 'decipher_bifid', 'bifid_square', 'bifid5', 'bifid6',
31
+ 'bifid10', 'decipher_gm', 'encipher_gm', 'gm_public_key',
32
+ 'gm_private_key', 'bg_private_key', 'bg_public_key', 'encipher_bg',
33
+ 'decipher_bg', 'encipher_rot13', 'decipher_rot13', 'encipher_atbash',
34
+ 'decipher_atbash', 'encipher_railfence', 'decipher_railfence',
35
+ ]
venv/lib/python3.10/site-packages/sympy/crypto/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.64 kB). View file
 
venv/lib/python3.10/site-packages/sympy/crypto/__pycache__/crypto.cpython-310.pyc ADDED
Binary file (93.8 kB). View file
 
venv/lib/python3.10/site-packages/sympy/crypto/crypto.py ADDED
@@ -0,0 +1,3360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This file contains some classical ciphers and routines
3
+ implementing a linear-feedback shift register (LFSR)
4
+ and the Diffie-Hellman key exchange.
5
+
6
+ .. warning::
7
+
8
+ This module is intended for educational purposes only. Do not use the
9
+ functions in this module for real cryptographic applications. If you wish
10
+ to encrypt real data, we recommend using something like the `cryptography
11
+ <https://cryptography.io/en/latest/>`_ module.
12
+
13
+ """
14
+
15
+ from string import whitespace, ascii_uppercase as uppercase, printable
16
+ from functools import reduce
17
+ import warnings
18
+
19
+ from itertools import cycle
20
+
21
+ from sympy.core import Symbol
22
+ from sympy.core.numbers import igcdex, mod_inverse, igcd, Rational
23
+ from sympy.core.random import _randrange, _randint
24
+ from sympy.matrices import Matrix
25
+ from sympy.ntheory import isprime, primitive_root, factorint
26
+ from sympy.ntheory import totient as _euler
27
+ from sympy.ntheory import reduced_totient as _carmichael
28
+ from sympy.ntheory.generate import nextprime
29
+ from sympy.ntheory.modular import crt
30
+ from sympy.polys.domains import FF
31
+ from sympy.polys.polytools import gcd, Poly
32
+ from sympy.utilities.misc import as_int, filldedent, translate
33
+ from sympy.utilities.iterables import uniq, multiset
34
+
35
+
36
+ class NonInvertibleCipherWarning(RuntimeWarning):
37
+ """A warning raised if the cipher is not invertible."""
38
+ def __init__(self, msg):
39
+ self.fullMessage = msg
40
+
41
+ def __str__(self):
42
+ return '\n\t' + self.fullMessage
43
+
44
+ def warn(self, stacklevel=3):
45
+ warnings.warn(self, stacklevel=stacklevel)
46
+
47
+
48
+ def AZ(s=None):
49
+ """Return the letters of ``s`` in uppercase. In case more than
50
+ one string is passed, each of them will be processed and a list
51
+ of upper case strings will be returned.
52
+
53
+ Examples
54
+ ========
55
+
56
+ >>> from sympy.crypto.crypto import AZ
57
+ >>> AZ('Hello, world!')
58
+ 'HELLOWORLD'
59
+ >>> AZ('Hello, world!'.split())
60
+ ['HELLO', 'WORLD']
61
+
62
+ See Also
63
+ ========
64
+
65
+ check_and_join
66
+
67
+ """
68
+ if not s:
69
+ return uppercase
70
+ t = isinstance(s, str)
71
+ if t:
72
+ s = [s]
73
+ rv = [check_and_join(i.upper().split(), uppercase, filter=True)
74
+ for i in s]
75
+ if t:
76
+ return rv[0]
77
+ return rv
78
+
79
+ bifid5 = AZ().replace('J', '')
80
+ bifid6 = AZ() + '0123456789'
81
+ bifid10 = printable
82
+
83
+
84
+ def padded_key(key, symbols):
85
+ """Return a string of the distinct characters of ``symbols`` with
86
+ those of ``key`` appearing first. A ValueError is raised if
87
+ a) there are duplicate characters in ``symbols`` or
88
+ b) there are characters in ``key`` that are not in ``symbols``.
89
+
90
+ Examples
91
+ ========
92
+
93
+ >>> from sympy.crypto.crypto import padded_key
94
+ >>> padded_key('PUPPY', 'OPQRSTUVWXY')
95
+ 'PUYOQRSTVWX'
96
+ >>> padded_key('RSA', 'ARTIST')
97
+ Traceback (most recent call last):
98
+ ...
99
+ ValueError: duplicate characters in symbols: T
100
+
101
+ """
102
+ syms = list(uniq(symbols))
103
+ if len(syms) != len(symbols):
104
+ extra = ''.join(sorted({
105
+ i for i in symbols if symbols.count(i) > 1}))
106
+ raise ValueError('duplicate characters in symbols: %s' % extra)
107
+ extra = set(key) - set(syms)
108
+ if extra:
109
+ raise ValueError(
110
+ 'characters in key but not symbols: %s' % ''.join(
111
+ sorted(extra)))
112
+ key0 = ''.join(list(uniq(key)))
113
+ # remove from syms characters in key0
114
+ return key0 + translate(''.join(syms), None, key0)
115
+
116
+
117
+ def check_and_join(phrase, symbols=None, filter=None):
118
+ """
119
+ Joins characters of ``phrase`` and if ``symbols`` is given, raises
120
+ an error if any character in ``phrase`` is not in ``symbols``.
121
+
122
+ Parameters
123
+ ==========
124
+
125
+ phrase
126
+ String or list of strings to be returned as a string.
127
+
128
+ symbols
129
+ Iterable of characters allowed in ``phrase``.
130
+
131
+ If ``symbols`` is ``None``, no checking is performed.
132
+
133
+ Examples
134
+ ========
135
+
136
+ >>> from sympy.crypto.crypto import check_and_join
137
+ >>> check_and_join('a phrase')
138
+ 'a phrase'
139
+ >>> check_and_join('a phrase'.upper().split())
140
+ 'APHRASE'
141
+ >>> check_and_join('a phrase!'.upper().split(), 'ARE', filter=True)
142
+ 'ARAE'
143
+ >>> check_and_join('a phrase!'.upper().split(), 'ARE')
144
+ Traceback (most recent call last):
145
+ ...
146
+ ValueError: characters in phrase but not symbols: "!HPS"
147
+
148
+ """
149
+ rv = ''.join(''.join(phrase))
150
+ if symbols is not None:
151
+ symbols = check_and_join(symbols)
152
+ missing = ''.join(sorted(set(rv) - set(symbols)))
153
+ if missing:
154
+ if not filter:
155
+ raise ValueError(
156
+ 'characters in phrase but not symbols: "%s"' % missing)
157
+ rv = translate(rv, None, missing)
158
+ return rv
159
+
160
+
161
+ def _prep(msg, key, alp, default=None):
162
+ if not alp:
163
+ if not default:
164
+ alp = AZ()
165
+ msg = AZ(msg)
166
+ key = AZ(key)
167
+ else:
168
+ alp = default
169
+ else:
170
+ alp = ''.join(alp)
171
+ key = check_and_join(key, alp, filter=True)
172
+ msg = check_and_join(msg, alp, filter=True)
173
+ return msg, key, alp
174
+
175
+
176
+ def cycle_list(k, n):
177
+ """
178
+ Returns the elements of the list ``range(n)`` shifted to the
179
+ left by ``k`` (so the list starts with ``k`` (mod ``n``)).
180
+
181
+ Examples
182
+ ========
183
+
184
+ >>> from sympy.crypto.crypto import cycle_list
185
+ >>> cycle_list(3, 10)
186
+ [3, 4, 5, 6, 7, 8, 9, 0, 1, 2]
187
+
188
+ """
189
+ k = k % n
190
+ return list(range(k, n)) + list(range(k))
191
+
192
+
193
+ ######## shift cipher examples ############
194
+
195
+
196
+ def encipher_shift(msg, key, symbols=None):
197
+ """
198
+ Performs shift cipher encryption on plaintext msg, and returns the
199
+ ciphertext.
200
+
201
+ Parameters
202
+ ==========
203
+
204
+ key : int
205
+ The secret key.
206
+
207
+ msg : str
208
+ Plaintext of upper-case letters.
209
+
210
+ Returns
211
+ =======
212
+
213
+ str
214
+ Ciphertext of upper-case letters.
215
+
216
+ Examples
217
+ ========
218
+
219
+ >>> from sympy.crypto.crypto import encipher_shift, decipher_shift
220
+ >>> msg = "GONAVYBEATARMY"
221
+ >>> ct = encipher_shift(msg, 1); ct
222
+ 'HPOBWZCFBUBSNZ'
223
+
224
+ To decipher the shifted text, change the sign of the key:
225
+
226
+ >>> encipher_shift(ct, -1)
227
+ 'GONAVYBEATARMY'
228
+
229
+ There is also a convenience function that does this with the
230
+ original key:
231
+
232
+ >>> decipher_shift(ct, 1)
233
+ 'GONAVYBEATARMY'
234
+
235
+ Notes
236
+ =====
237
+
238
+ ALGORITHM:
239
+
240
+ STEPS:
241
+ 0. Number the letters of the alphabet from 0, ..., N
242
+ 1. Compute from the string ``msg`` a list ``L1`` of
243
+ corresponding integers.
244
+ 2. Compute from the list ``L1`` a new list ``L2``, given by
245
+ adding ``(k mod 26)`` to each element in ``L1``.
246
+ 3. Compute from the list ``L2`` a string ``ct`` of
247
+ corresponding letters.
248
+
249
+ The shift cipher is also called the Caesar cipher, after
250
+ Julius Caesar, who, according to Suetonius, used it with a
251
+ shift of three to protect messages of military significance.
252
+ Caesar's nephew Augustus reportedly used a similar cipher, but
253
+ with a right shift of 1.
254
+
255
+ References
256
+ ==========
257
+
258
+ .. [1] https://en.wikipedia.org/wiki/Caesar_cipher
259
+ .. [2] https://mathworld.wolfram.com/CaesarsMethod.html
260
+
261
+ See Also
262
+ ========
263
+
264
+ decipher_shift
265
+
266
+ """
267
+ msg, _, A = _prep(msg, '', symbols)
268
+ shift = len(A) - key % len(A)
269
+ key = A[shift:] + A[:shift]
270
+ return translate(msg, key, A)
271
+
272
+
273
+ def decipher_shift(msg, key, symbols=None):
274
+ """
275
+ Return the text by shifting the characters of ``msg`` to the
276
+ left by the amount given by ``key``.
277
+
278
+ Examples
279
+ ========
280
+
281
+ >>> from sympy.crypto.crypto import encipher_shift, decipher_shift
282
+ >>> msg = "GONAVYBEATARMY"
283
+ >>> ct = encipher_shift(msg, 1); ct
284
+ 'HPOBWZCFBUBSNZ'
285
+
286
+ To decipher the shifted text, change the sign of the key:
287
+
288
+ >>> encipher_shift(ct, -1)
289
+ 'GONAVYBEATARMY'
290
+
291
+ Or use this function with the original key:
292
+
293
+ >>> decipher_shift(ct, 1)
294
+ 'GONAVYBEATARMY'
295
+
296
+ """
297
+ return encipher_shift(msg, -key, symbols)
298
+
299
+ def encipher_rot13(msg, symbols=None):
300
+ """
301
+ Performs the ROT13 encryption on a given plaintext ``msg``.
302
+
303
+ Explanation
304
+ ===========
305
+
306
+ ROT13 is a substitution cipher which substitutes each letter
307
+ in the plaintext message for the letter furthest away from it
308
+ in the English alphabet.
309
+
310
+ Equivalently, it is just a Caeser (shift) cipher with a shift
311
+ key of 13 (midway point of the alphabet).
312
+
313
+ References
314
+ ==========
315
+
316
+ .. [1] https://en.wikipedia.org/wiki/ROT13
317
+
318
+ See Also
319
+ ========
320
+
321
+ decipher_rot13
322
+ encipher_shift
323
+
324
+ """
325
+ return encipher_shift(msg, 13, symbols)
326
+
327
+ def decipher_rot13(msg, symbols=None):
328
+ """
329
+ Performs the ROT13 decryption on a given plaintext ``msg``.
330
+
331
+ Explanation
332
+ ============
333
+
334
+ ``decipher_rot13`` is equivalent to ``encipher_rot13`` as both
335
+ ``decipher_shift`` with a key of 13 and ``encipher_shift`` key with a
336
+ key of 13 will return the same results. Nonetheless,
337
+ ``decipher_rot13`` has nonetheless been explicitly defined here for
338
+ consistency.
339
+
340
+ Examples
341
+ ========
342
+
343
+ >>> from sympy.crypto.crypto import encipher_rot13, decipher_rot13
344
+ >>> msg = 'GONAVYBEATARMY'
345
+ >>> ciphertext = encipher_rot13(msg);ciphertext
346
+ 'TBANILORNGNEZL'
347
+ >>> decipher_rot13(ciphertext)
348
+ 'GONAVYBEATARMY'
349
+ >>> encipher_rot13(msg) == decipher_rot13(msg)
350
+ True
351
+ >>> msg == decipher_rot13(ciphertext)
352
+ True
353
+
354
+ """
355
+ return decipher_shift(msg, 13, symbols)
356
+
357
+ ######## affine cipher examples ############
358
+
359
+
360
+ def encipher_affine(msg, key, symbols=None, _inverse=False):
361
+ r"""
362
+ Performs the affine cipher encryption on plaintext ``msg``, and
363
+ returns the ciphertext.
364
+
365
+ Explanation
366
+ ===========
367
+
368
+ Encryption is based on the map `x \rightarrow ax+b` (mod `N`)
369
+ where ``N`` is the number of characters in the alphabet.
370
+ Decryption is based on the map `x \rightarrow cx+d` (mod `N`),
371
+ where `c = a^{-1}` (mod `N`) and `d = -a^{-1}b` (mod `N`).
372
+ In particular, for the map to be invertible, we need
373
+ `\mathrm{gcd}(a, N) = 1` and an error will be raised if this is
374
+ not true.
375
+
376
+ Parameters
377
+ ==========
378
+
379
+ msg : str
380
+ Characters that appear in ``symbols``.
381
+
382
+ a, b : int, int
383
+ A pair integers, with ``gcd(a, N) = 1`` (the secret key).
384
+
385
+ symbols
386
+ String of characters (default = uppercase letters).
387
+
388
+ When no symbols are given, ``msg`` is converted to upper case
389
+ letters and all other characters are ignored.
390
+
391
+ Returns
392
+ =======
393
+
394
+ ct
395
+ String of characters (the ciphertext message)
396
+
397
+ Notes
398
+ =====
399
+
400
+ ALGORITHM:
401
+
402
+ STEPS:
403
+ 0. Number the letters of the alphabet from 0, ..., N
404
+ 1. Compute from the string ``msg`` a list ``L1`` of
405
+ corresponding integers.
406
+ 2. Compute from the list ``L1`` a new list ``L2``, given by
407
+ replacing ``x`` by ``a*x + b (mod N)``, for each element
408
+ ``x`` in ``L1``.
409
+ 3. Compute from the list ``L2`` a string ``ct`` of
410
+ corresponding letters.
411
+
412
+ This is a straightforward generalization of the shift cipher with
413
+ the added complexity of requiring 2 characters to be deciphered in
414
+ order to recover the key.
415
+
416
+ References
417
+ ==========
418
+
419
+ .. [1] https://en.wikipedia.org/wiki/Affine_cipher
420
+
421
+ See Also
422
+ ========
423
+
424
+ decipher_affine
425
+
426
+ """
427
+ msg, _, A = _prep(msg, '', symbols)
428
+ N = len(A)
429
+ a, b = key
430
+ assert gcd(a, N) == 1
431
+ if _inverse:
432
+ c = mod_inverse(a, N)
433
+ d = -b*c
434
+ a, b = c, d
435
+ B = ''.join([A[(a*i + b) % N] for i in range(N)])
436
+ return translate(msg, A, B)
437
+
438
+
439
+ def decipher_affine(msg, key, symbols=None):
440
+ r"""
441
+ Return the deciphered text that was made from the mapping,
442
+ `x \rightarrow ax+b` (mod `N`), where ``N`` is the
443
+ number of characters in the alphabet. Deciphering is done by
444
+ reciphering with a new key: `x \rightarrow cx+d` (mod `N`),
445
+ where `c = a^{-1}` (mod `N`) and `d = -a^{-1}b` (mod `N`).
446
+
447
+ Examples
448
+ ========
449
+
450
+ >>> from sympy.crypto.crypto import encipher_affine, decipher_affine
451
+ >>> msg = "GO NAVY BEAT ARMY"
452
+ >>> key = (3, 1)
453
+ >>> encipher_affine(msg, key)
454
+ 'TROBMVENBGBALV'
455
+ >>> decipher_affine(_, key)
456
+ 'GONAVYBEATARMY'
457
+
458
+ See Also
459
+ ========
460
+
461
+ encipher_affine
462
+
463
+ """
464
+ return encipher_affine(msg, key, symbols, _inverse=True)
465
+
466
+
467
+ def encipher_atbash(msg, symbols=None):
468
+ r"""
469
+ Enciphers a given ``msg`` into its Atbash ciphertext and returns it.
470
+
471
+ Explanation
472
+ ===========
473
+
474
+ Atbash is a substitution cipher originally used to encrypt the Hebrew
475
+ alphabet. Atbash works on the principle of mapping each alphabet to its
476
+ reverse / counterpart (i.e. a would map to z, b to y etc.)
477
+
478
+ Atbash is functionally equivalent to the affine cipher with ``a = 25``
479
+ and ``b = 25``
480
+
481
+ See Also
482
+ ========
483
+
484
+ decipher_atbash
485
+
486
+ """
487
+ return encipher_affine(msg, (25, 25), symbols)
488
+
489
+
490
+ def decipher_atbash(msg, symbols=None):
491
+ r"""
492
+ Deciphers a given ``msg`` using Atbash cipher and returns it.
493
+
494
+ Explanation
495
+ ===========
496
+
497
+ ``decipher_atbash`` is functionally equivalent to ``encipher_atbash``.
498
+ However, it has still been added as a separate function to maintain
499
+ consistency.
500
+
501
+ Examples
502
+ ========
503
+
504
+ >>> from sympy.crypto.crypto import encipher_atbash, decipher_atbash
505
+ >>> msg = 'GONAVYBEATARMY'
506
+ >>> encipher_atbash(msg)
507
+ 'TLMZEBYVZGZINB'
508
+ >>> decipher_atbash(msg)
509
+ 'TLMZEBYVZGZINB'
510
+ >>> encipher_atbash(msg) == decipher_atbash(msg)
511
+ True
512
+ >>> msg == encipher_atbash(encipher_atbash(msg))
513
+ True
514
+
515
+ References
516
+ ==========
517
+
518
+ .. [1] https://en.wikipedia.org/wiki/Atbash
519
+
520
+ See Also
521
+ ========
522
+
523
+ encipher_atbash
524
+
525
+ """
526
+ return decipher_affine(msg, (25, 25), symbols)
527
+
528
+ #################### substitution cipher ###########################
529
+
530
+
531
+ def encipher_substitution(msg, old, new=None):
532
+ r"""
533
+ Returns the ciphertext obtained by replacing each character that
534
+ appears in ``old`` with the corresponding character in ``new``.
535
+ If ``old`` is a mapping, then new is ignored and the replacements
536
+ defined by ``old`` are used.
537
+
538
+ Explanation
539
+ ===========
540
+
541
+ This is a more general than the affine cipher in that the key can
542
+ only be recovered by determining the mapping for each symbol.
543
+ Though in practice, once a few symbols are recognized the mappings
544
+ for other characters can be quickly guessed.
545
+
546
+ Examples
547
+ ========
548
+
549
+ >>> from sympy.crypto.crypto import encipher_substitution, AZ
550
+ >>> old = 'OEYAG'
551
+ >>> new = '034^6'
552
+ >>> msg = AZ("go navy! beat army!")
553
+ >>> ct = encipher_substitution(msg, old, new); ct
554
+ '60N^V4B3^T^RM4'
555
+
556
+ To decrypt a substitution, reverse the last two arguments:
557
+
558
+ >>> encipher_substitution(ct, new, old)
559
+ 'GONAVYBEATARMY'
560
+
561
+ In the special case where ``old`` and ``new`` are a permutation of
562
+ order 2 (representing a transposition of characters) their order
563
+ is immaterial:
564
+
565
+ >>> old = 'NAVY'
566
+ >>> new = 'ANYV'
567
+ >>> encipher = lambda x: encipher_substitution(x, old, new)
568
+ >>> encipher('NAVY')
569
+ 'ANYV'
570
+ >>> encipher(_)
571
+ 'NAVY'
572
+
573
+ The substitution cipher, in general, is a method
574
+ whereby "units" (not necessarily single characters) of plaintext
575
+ are replaced with ciphertext according to a regular system.
576
+
577
+ >>> ords = dict(zip('abc', ['\\%i' % ord(i) for i in 'abc']))
578
+ >>> print(encipher_substitution('abc', ords))
579
+ \97\98\99
580
+
581
+ References
582
+ ==========
583
+
584
+ .. [1] https://en.wikipedia.org/wiki/Substitution_cipher
585
+
586
+ """
587
+ return translate(msg, old, new)
588
+
589
+
590
+ ######################################################################
591
+ #################### Vigenere cipher examples ########################
592
+ ######################################################################
593
+
594
+ def encipher_vigenere(msg, key, symbols=None):
595
+ """
596
+ Performs the Vigenere cipher encryption on plaintext ``msg``, and
597
+ returns the ciphertext.
598
+
599
+ Examples
600
+ ========
601
+
602
+ >>> from sympy.crypto.crypto import encipher_vigenere, AZ
603
+ >>> key = "encrypt"
604
+ >>> msg = "meet me on monday"
605
+ >>> encipher_vigenere(msg, key)
606
+ 'QRGKKTHRZQEBPR'
607
+
608
+ Section 1 of the Kryptos sculpture at the CIA headquarters
609
+ uses this cipher and also changes the order of the
610
+ alphabet [2]_. Here is the first line of that section of
611
+ the sculpture:
612
+
613
+ >>> from sympy.crypto.crypto import decipher_vigenere, padded_key
614
+ >>> alp = padded_key('KRYPTOS', AZ())
615
+ >>> key = 'PALIMPSEST'
616
+ >>> msg = 'EMUFPHZLRFAXYUSDJKZLDKRNSHGNFIVJ'
617
+ >>> decipher_vigenere(msg, key, alp)
618
+ 'BETWEENSUBTLESHADINGANDTHEABSENC'
619
+
620
+ Explanation
621
+ ===========
622
+
623
+ The Vigenere cipher is named after Blaise de Vigenere, a sixteenth
624
+ century diplomat and cryptographer, by a historical accident.
625
+ Vigenere actually invented a different and more complicated cipher.
626
+ The so-called *Vigenere cipher* was actually invented
627
+ by Giovan Batista Belaso in 1553.
628
+
629
+ This cipher was used in the 1800's, for example, during the American
630
+ Civil War. The Confederacy used a brass cipher disk to implement the
631
+ Vigenere cipher (now on display in the NSA Museum in Fort
632
+ Meade) [1]_.
633
+
634
+ The Vigenere cipher is a generalization of the shift cipher.
635
+ Whereas the shift cipher shifts each letter by the same amount
636
+ (that amount being the key of the shift cipher) the Vigenere
637
+ cipher shifts a letter by an amount determined by the key (which is
638
+ a word or phrase known only to the sender and receiver).
639
+
640
+ For example, if the key was a single letter, such as "C", then the
641
+ so-called Vigenere cipher is actually a shift cipher with a
642
+ shift of `2` (since "C" is the 2nd letter of the alphabet, if
643
+ you start counting at `0`). If the key was a word with two
644
+ letters, such as "CA", then the so-called Vigenere cipher will
645
+ shift letters in even positions by `2` and letters in odd positions
646
+ are left alone (shifted by `0`, since "A" is the 0th letter, if
647
+ you start counting at `0`).
648
+
649
+
650
+ ALGORITHM:
651
+
652
+ INPUT:
653
+
654
+ ``msg``: string of characters that appear in ``symbols``
655
+ (the plaintext)
656
+
657
+ ``key``: a string of characters that appear in ``symbols``
658
+ (the secret key)
659
+
660
+ ``symbols``: a string of letters defining the alphabet
661
+
662
+
663
+ OUTPUT:
664
+
665
+ ``ct``: string of characters (the ciphertext message)
666
+
667
+ STEPS:
668
+ 0. Number the letters of the alphabet from 0, ..., N
669
+ 1. Compute from the string ``key`` a list ``L1`` of
670
+ corresponding integers. Let ``n1 = len(L1)``.
671
+ 2. Compute from the string ``msg`` a list ``L2`` of
672
+ corresponding integers. Let ``n2 = len(L2)``.
673
+ 3. Break ``L2`` up sequentially into sublists of size
674
+ ``n1``; the last sublist may be smaller than ``n1``
675
+ 4. For each of these sublists ``L`` of ``L2``, compute a
676
+ new list ``C`` given by ``C[i] = L[i] + L1[i] (mod N)``
677
+ to the ``i``-th element in the sublist, for each ``i``.
678
+ 5. Assemble these lists ``C`` by concatenation into a new
679
+ list of length ``n2``.
680
+ 6. Compute from the new list a string ``ct`` of
681
+ corresponding letters.
682
+
683
+ Once it is known that the key is, say, `n` characters long,
684
+ frequency analysis can be applied to every `n`-th letter of
685
+ the ciphertext to determine the plaintext. This method is
686
+ called *Kasiski examination* (although it was first discovered
687
+ by Babbage). If they key is as long as the message and is
688
+ comprised of randomly selected characters -- a one-time pad -- the
689
+ message is theoretically unbreakable.
690
+
691
+ The cipher Vigenere actually discovered is an "auto-key" cipher
692
+ described as follows.
693
+
694
+ ALGORITHM:
695
+
696
+ INPUT:
697
+
698
+ ``key``: a string of letters (the secret key)
699
+
700
+ ``msg``: string of letters (the plaintext message)
701
+
702
+ OUTPUT:
703
+
704
+ ``ct``: string of upper-case letters (the ciphertext message)
705
+
706
+ STEPS:
707
+ 0. Number the letters of the alphabet from 0, ..., N
708
+ 1. Compute from the string ``msg`` a list ``L2`` of
709
+ corresponding integers. Let ``n2 = len(L2)``.
710
+ 2. Let ``n1`` be the length of the key. Append to the
711
+ string ``key`` the first ``n2 - n1`` characters of
712
+ the plaintext message. Compute from this string (also of
713
+ length ``n2``) a list ``L1`` of integers corresponding
714
+ to the letter numbers in the first step.
715
+ 3. Compute a new list ``C`` given by
716
+ ``C[i] = L1[i] + L2[i] (mod N)``.
717
+ 4. Compute from the new list a string ``ct`` of letters
718
+ corresponding to the new integers.
719
+
720
+ To decipher the auto-key ciphertext, the key is used to decipher
721
+ the first ``n1`` characters and then those characters become the
722
+ key to decipher the next ``n1`` characters, etc...:
723
+
724
+ >>> m = AZ('go navy, beat army! yes you can'); m
725
+ 'GONAVYBEATARMYYESYOUCAN'
726
+ >>> key = AZ('gold bug'); n1 = len(key); n2 = len(m)
727
+ >>> auto_key = key + m[:n2 - n1]; auto_key
728
+ 'GOLDBUGGONAVYBEATARMYYE'
729
+ >>> ct = encipher_vigenere(m, auto_key); ct
730
+ 'MCYDWSHKOGAMKZCELYFGAYR'
731
+ >>> n1 = len(key)
732
+ >>> pt = []
733
+ >>> while ct:
734
+ ... part, ct = ct[:n1], ct[n1:]
735
+ ... pt.append(decipher_vigenere(part, key))
736
+ ... key = pt[-1]
737
+ ...
738
+ >>> ''.join(pt) == m
739
+ True
740
+
741
+ References
742
+ ==========
743
+
744
+ .. [1] https://en.wikipedia.org/wiki/Vigenere_cipher
745
+ .. [2] https://web.archive.org/web/20071116100808/https://filebox.vt.edu/users/batman/kryptos.html
746
+ (short URL: https://goo.gl/ijr22d)
747
+
748
+ """
749
+ msg, key, A = _prep(msg, key, symbols)
750
+ map = {c: i for i, c in enumerate(A)}
751
+ key = [map[c] for c in key]
752
+ N = len(map)
753
+ k = len(key)
754
+ rv = []
755
+ for i, m in enumerate(msg):
756
+ rv.append(A[(map[m] + key[i % k]) % N])
757
+ rv = ''.join(rv)
758
+ return rv
759
+
760
+
761
+ def decipher_vigenere(msg, key, symbols=None):
762
+ """
763
+ Decode using the Vigenere cipher.
764
+
765
+ Examples
766
+ ========
767
+
768
+ >>> from sympy.crypto.crypto import decipher_vigenere
769
+ >>> key = "encrypt"
770
+ >>> ct = "QRGK kt HRZQE BPR"
771
+ >>> decipher_vigenere(ct, key)
772
+ 'MEETMEONMONDAY'
773
+
774
+ """
775
+ msg, key, A = _prep(msg, key, symbols)
776
+ map = {c: i for i, c in enumerate(A)}
777
+ N = len(A) # normally, 26
778
+ K = [map[c] for c in key]
779
+ n = len(K)
780
+ C = [map[c] for c in msg]
781
+ rv = ''.join([A[(-K[i % n] + c) % N] for i, c in enumerate(C)])
782
+ return rv
783
+
784
+
785
+ #################### Hill cipher ########################
786
+
787
+
788
+ def encipher_hill(msg, key, symbols=None, pad="Q"):
789
+ r"""
790
+ Return the Hill cipher encryption of ``msg``.
791
+
792
+ Explanation
793
+ ===========
794
+
795
+ The Hill cipher [1]_, invented by Lester S. Hill in the 1920's [2]_,
796
+ was the first polygraphic cipher in which it was practical
797
+ (though barely) to operate on more than three symbols at once.
798
+ The following discussion assumes an elementary knowledge of
799
+ matrices.
800
+
801
+ First, each letter is first encoded as a number starting with 0.
802
+ Suppose your message `msg` consists of `n` capital letters, with no
803
+ spaces. This may be regarded an `n`-tuple M of elements of
804
+ `Z_{26}` (if the letters are those of the English alphabet). A key
805
+ in the Hill cipher is a `k x k` matrix `K`, all of whose entries
806
+ are in `Z_{26}`, such that the matrix `K` is invertible (i.e., the
807
+ linear transformation `K: Z_{N}^k \rightarrow Z_{N}^k`
808
+ is one-to-one).
809
+
810
+
811
+ Parameters
812
+ ==========
813
+
814
+ msg
815
+ Plaintext message of `n` upper-case letters.
816
+
817
+ key
818
+ A `k \times k` invertible matrix `K`, all of whose entries are
819
+ in `Z_{26}` (or whatever number of symbols are being used).
820
+
821
+ pad
822
+ Character (default "Q") to use to make length of text be a
823
+ multiple of ``k``.
824
+
825
+ Returns
826
+ =======
827
+
828
+ ct
829
+ Ciphertext of upper-case letters.
830
+
831
+ Notes
832
+ =====
833
+
834
+ ALGORITHM:
835
+
836
+ STEPS:
837
+ 0. Number the letters of the alphabet from 0, ..., N
838
+ 1. Compute from the string ``msg`` a list ``L`` of
839
+ corresponding integers. Let ``n = len(L)``.
840
+ 2. Break the list ``L`` up into ``t = ceiling(n/k)``
841
+ sublists ``L_1``, ..., ``L_t`` of size ``k`` (with
842
+ the last list "padded" to ensure its size is
843
+ ``k``).
844
+ 3. Compute new list ``C_1``, ..., ``C_t`` given by
845
+ ``C[i] = K*L_i`` (arithmetic is done mod N), for each
846
+ ``i``.
847
+ 4. Concatenate these into a list ``C = C_1 + ... + C_t``.
848
+ 5. Compute from ``C`` a string ``ct`` of corresponding
849
+ letters. This has length ``k*t``.
850
+
851
+ References
852
+ ==========
853
+
854
+ .. [1] https://en.wikipedia.org/wiki/Hill_cipher
855
+ .. [2] Lester S. Hill, Cryptography in an Algebraic Alphabet,
856
+ The American Mathematical Monthly Vol.36, June-July 1929,
857
+ pp.306-312.
858
+
859
+ See Also
860
+ ========
861
+
862
+ decipher_hill
863
+
864
+ """
865
+ assert key.is_square
866
+ assert len(pad) == 1
867
+ msg, pad, A = _prep(msg, pad, symbols)
868
+ map = {c: i for i, c in enumerate(A)}
869
+ P = [map[c] for c in msg]
870
+ N = len(A)
871
+ k = key.cols
872
+ n = len(P)
873
+ m, r = divmod(n, k)
874
+ if r:
875
+ P = P + [map[pad]]*(k - r)
876
+ m += 1
877
+ rv = ''.join([A[c % N] for j in range(m) for c in
878
+ list(key*Matrix(k, 1, [P[i]
879
+ for i in range(k*j, k*(j + 1))]))])
880
+ return rv
881
+
882
+
883
+ def decipher_hill(msg, key, symbols=None):
884
+ """
885
+ Deciphering is the same as enciphering but using the inverse of the
886
+ key matrix.
887
+
888
+ Examples
889
+ ========
890
+
891
+ >>> from sympy.crypto.crypto import encipher_hill, decipher_hill
892
+ >>> from sympy import Matrix
893
+
894
+ >>> key = Matrix([[1, 2], [3, 5]])
895
+ >>> encipher_hill("meet me on monday", key)
896
+ 'UEQDUEODOCTCWQ'
897
+ >>> decipher_hill(_, key)
898
+ 'MEETMEONMONDAY'
899
+
900
+ When the length of the plaintext (stripped of invalid characters)
901
+ is not a multiple of the key dimension, extra characters will
902
+ appear at the end of the enciphered and deciphered text. In order to
903
+ decipher the text, those characters must be included in the text to
904
+ be deciphered. In the following, the key has a dimension of 4 but
905
+ the text is 2 short of being a multiple of 4 so two characters will
906
+ be added.
907
+
908
+ >>> key = Matrix([[1, 1, 1, 2], [0, 1, 1, 0],
909
+ ... [2, 2, 3, 4], [1, 1, 0, 1]])
910
+ >>> msg = "ST"
911
+ >>> encipher_hill(msg, key)
912
+ 'HJEB'
913
+ >>> decipher_hill(_, key)
914
+ 'STQQ'
915
+ >>> encipher_hill(msg, key, pad="Z")
916
+ 'ISPK'
917
+ >>> decipher_hill(_, key)
918
+ 'STZZ'
919
+
920
+ If the last two characters of the ciphertext were ignored in
921
+ either case, the wrong plaintext would be recovered:
922
+
923
+ >>> decipher_hill("HD", key)
924
+ 'ORMV'
925
+ >>> decipher_hill("IS", key)
926
+ 'UIKY'
927
+
928
+ See Also
929
+ ========
930
+
931
+ encipher_hill
932
+
933
+ """
934
+ assert key.is_square
935
+ msg, _, A = _prep(msg, '', symbols)
936
+ map = {c: i for i, c in enumerate(A)}
937
+ C = [map[c] for c in msg]
938
+ N = len(A)
939
+ k = key.cols
940
+ n = len(C)
941
+ m, r = divmod(n, k)
942
+ if r:
943
+ C = C + [0]*(k - r)
944
+ m += 1
945
+ key_inv = key.inv_mod(N)
946
+ rv = ''.join([A[p % N] for j in range(m) for p in
947
+ list(key_inv*Matrix(
948
+ k, 1, [C[i] for i in range(k*j, k*(j + 1))]))])
949
+ return rv
950
+
951
+
952
+ #################### Bifid cipher ########################
953
+
954
+
955
+ def encipher_bifid(msg, key, symbols=None):
956
+ r"""
957
+ Performs the Bifid cipher encryption on plaintext ``msg``, and
958
+ returns the ciphertext.
959
+
960
+ This is the version of the Bifid cipher that uses an `n \times n`
961
+ Polybius square.
962
+
963
+ Parameters
964
+ ==========
965
+
966
+ msg
967
+ Plaintext string.
968
+
969
+ key
970
+ Short string for key.
971
+
972
+ Duplicate characters are ignored and then it is padded with the
973
+ characters in ``symbols`` that were not in the short key.
974
+
975
+ symbols
976
+ `n \times n` characters defining the alphabet.
977
+
978
+ (default is string.printable)
979
+
980
+ Returns
981
+ =======
982
+
983
+ ciphertext
984
+ Ciphertext using Bifid5 cipher without spaces.
985
+
986
+ See Also
987
+ ========
988
+
989
+ decipher_bifid, encipher_bifid5, encipher_bifid6
990
+
991
+ References
992
+ ==========
993
+
994
+ .. [1] https://en.wikipedia.org/wiki/Bifid_cipher
995
+
996
+ """
997
+ msg, key, A = _prep(msg, key, symbols, bifid10)
998
+ long_key = ''.join(uniq(key)) or A
999
+
1000
+ n = len(A)**.5
1001
+ if n != int(n):
1002
+ raise ValueError(
1003
+ 'Length of alphabet (%s) is not a square number.' % len(A))
1004
+ N = int(n)
1005
+ if len(long_key) < N**2:
1006
+ long_key = list(long_key) + [x for x in A if x not in long_key]
1007
+
1008
+ # the fractionalization
1009
+ row_col = {ch: divmod(i, N) for i, ch in enumerate(long_key)}
1010
+ r, c = zip(*[row_col[x] for x in msg])
1011
+ rc = r + c
1012
+ ch = {i: ch for ch, i in row_col.items()}
1013
+ rv = ''.join(ch[i] for i in zip(rc[::2], rc[1::2]))
1014
+ return rv
1015
+
1016
+
1017
+ def decipher_bifid(msg, key, symbols=None):
1018
+ r"""
1019
+ Performs the Bifid cipher decryption on ciphertext ``msg``, and
1020
+ returns the plaintext.
1021
+
1022
+ This is the version of the Bifid cipher that uses the `n \times n`
1023
+ Polybius square.
1024
+
1025
+ Parameters
1026
+ ==========
1027
+
1028
+ msg
1029
+ Ciphertext string.
1030
+
1031
+ key
1032
+ Short string for key.
1033
+
1034
+ Duplicate characters are ignored and then it is padded with the
1035
+ characters in symbols that were not in the short key.
1036
+
1037
+ symbols
1038
+ `n \times n` characters defining the alphabet.
1039
+
1040
+ (default=string.printable, a `10 \times 10` matrix)
1041
+
1042
+ Returns
1043
+ =======
1044
+
1045
+ deciphered
1046
+ Deciphered text.
1047
+
1048
+ Examples
1049
+ ========
1050
+
1051
+ >>> from sympy.crypto.crypto import (
1052
+ ... encipher_bifid, decipher_bifid, AZ)
1053
+
1054
+ Do an encryption using the bifid5 alphabet:
1055
+
1056
+ >>> alp = AZ().replace('J', '')
1057
+ >>> ct = AZ("meet me on monday!")
1058
+ >>> key = AZ("gold bug")
1059
+ >>> encipher_bifid(ct, key, alp)
1060
+ 'IEILHHFSTSFQYE'
1061
+
1062
+ When entering the text or ciphertext, spaces are ignored so it
1063
+ can be formatted as desired. Re-entering the ciphertext from the
1064
+ preceding, putting 4 characters per line and padding with an extra
1065
+ J, does not cause problems for the deciphering:
1066
+
1067
+ >>> decipher_bifid('''
1068
+ ... IEILH
1069
+ ... HFSTS
1070
+ ... FQYEJ''', key, alp)
1071
+ 'MEETMEONMONDAY'
1072
+
1073
+ When no alphabet is given, all 100 printable characters will be
1074
+ used:
1075
+
1076
+ >>> key = ''
1077
+ >>> encipher_bifid('hello world!', key)
1078
+ 'bmtwmg-bIo*w'
1079
+ >>> decipher_bifid(_, key)
1080
+ 'hello world!'
1081
+
1082
+ If the key is changed, a different encryption is obtained:
1083
+
1084
+ >>> key = 'gold bug'
1085
+ >>> encipher_bifid('hello world!', 'gold_bug')
1086
+ 'hg2sfuei7t}w'
1087
+
1088
+ And if the key used to decrypt the message is not exact, the
1089
+ original text will not be perfectly obtained:
1090
+
1091
+ >>> decipher_bifid(_, 'gold pug')
1092
+ 'heldo~wor6d!'
1093
+
1094
+ """
1095
+ msg, _, A = _prep(msg, '', symbols, bifid10)
1096
+ long_key = ''.join(uniq(key)) or A
1097
+
1098
+ n = len(A)**.5
1099
+ if n != int(n):
1100
+ raise ValueError(
1101
+ 'Length of alphabet (%s) is not a square number.' % len(A))
1102
+ N = int(n)
1103
+ if len(long_key) < N**2:
1104
+ long_key = list(long_key) + [x for x in A if x not in long_key]
1105
+
1106
+ # the reverse fractionalization
1107
+ row_col = {
1108
+ ch: divmod(i, N) for i, ch in enumerate(long_key)}
1109
+ rc = [i for c in msg for i in row_col[c]]
1110
+ n = len(msg)
1111
+ rc = zip(*(rc[:n], rc[n:]))
1112
+ ch = {i: ch for ch, i in row_col.items()}
1113
+ rv = ''.join(ch[i] for i in rc)
1114
+ return rv
1115
+
1116
+
1117
+ def bifid_square(key):
1118
+ """Return characters of ``key`` arranged in a square.
1119
+
1120
+ Examples
1121
+ ========
1122
+
1123
+ >>> from sympy.crypto.crypto import (
1124
+ ... bifid_square, AZ, padded_key, bifid5)
1125
+ >>> bifid_square(AZ().replace('J', ''))
1126
+ Matrix([
1127
+ [A, B, C, D, E],
1128
+ [F, G, H, I, K],
1129
+ [L, M, N, O, P],
1130
+ [Q, R, S, T, U],
1131
+ [V, W, X, Y, Z]])
1132
+
1133
+ >>> bifid_square(padded_key(AZ('gold bug!'), bifid5))
1134
+ Matrix([
1135
+ [G, O, L, D, B],
1136
+ [U, A, C, E, F],
1137
+ [H, I, K, M, N],
1138
+ [P, Q, R, S, T],
1139
+ [V, W, X, Y, Z]])
1140
+
1141
+ See Also
1142
+ ========
1143
+
1144
+ padded_key
1145
+
1146
+ """
1147
+ A = ''.join(uniq(''.join(key)))
1148
+ n = len(A)**.5
1149
+ if n != int(n):
1150
+ raise ValueError(
1151
+ 'Length of alphabet (%s) is not a square number.' % len(A))
1152
+ n = int(n)
1153
+ f = lambda i, j: Symbol(A[n*i + j])
1154
+ rv = Matrix(n, n, f)
1155
+ return rv
1156
+
1157
+
1158
+ def encipher_bifid5(msg, key):
1159
+ r"""
1160
+ Performs the Bifid cipher encryption on plaintext ``msg``, and
1161
+ returns the ciphertext.
1162
+
1163
+ Explanation
1164
+ ===========
1165
+
1166
+ This is the version of the Bifid cipher that uses the `5 \times 5`
1167
+ Polybius square. The letter "J" is ignored so it must be replaced
1168
+ with something else (traditionally an "I") before encryption.
1169
+
1170
+ ALGORITHM: (5x5 case)
1171
+
1172
+ STEPS:
1173
+ 0. Create the `5 \times 5` Polybius square ``S`` associated
1174
+ to ``key`` as follows:
1175
+
1176
+ a) moving from left-to-right, top-to-bottom,
1177
+ place the letters of the key into a `5 \times 5`
1178
+ matrix,
1179
+ b) if the key has less than 25 letters, add the
1180
+ letters of the alphabet not in the key until the
1181
+ `5 \times 5` square is filled.
1182
+
1183
+ 1. Create a list ``P`` of pairs of numbers which are the
1184
+ coordinates in the Polybius square of the letters in
1185
+ ``msg``.
1186
+ 2. Let ``L1`` be the list of all first coordinates of ``P``
1187
+ (length of ``L1 = n``), let ``L2`` be the list of all
1188
+ second coordinates of ``P`` (so the length of ``L2``
1189
+ is also ``n``).
1190
+ 3. Let ``L`` be the concatenation of ``L1`` and ``L2``
1191
+ (length ``L = 2*n``), except that consecutive numbers
1192
+ are paired ``(L[2*i], L[2*i + 1])``. You can regard
1193
+ ``L`` as a list of pairs of length ``n``.
1194
+ 4. Let ``C`` be the list of all letters which are of the
1195
+ form ``S[i, j]``, for all ``(i, j)`` in ``L``. As a
1196
+ string, this is the ciphertext of ``msg``.
1197
+
1198
+ Parameters
1199
+ ==========
1200
+
1201
+ msg : str
1202
+ Plaintext string.
1203
+
1204
+ Converted to upper case and filtered of anything but all letters
1205
+ except J.
1206
+
1207
+ key
1208
+ Short string for key; non-alphabetic letters, J and duplicated
1209
+ characters are ignored and then, if the length is less than 25
1210
+ characters, it is padded with other letters of the alphabet
1211
+ (in alphabetical order).
1212
+
1213
+ Returns
1214
+ =======
1215
+
1216
+ ct
1217
+ Ciphertext (all caps, no spaces).
1218
+
1219
+ Examples
1220
+ ========
1221
+
1222
+ >>> from sympy.crypto.crypto import (
1223
+ ... encipher_bifid5, decipher_bifid5)
1224
+
1225
+ "J" will be omitted unless it is replaced with something else:
1226
+
1227
+ >>> round_trip = lambda m, k: \
1228
+ ... decipher_bifid5(encipher_bifid5(m, k), k)
1229
+ >>> key = 'a'
1230
+ >>> msg = "JOSIE"
1231
+ >>> round_trip(msg, key)
1232
+ 'OSIE'
1233
+ >>> round_trip(msg.replace("J", "I"), key)
1234
+ 'IOSIE'
1235
+ >>> j = "QIQ"
1236
+ >>> round_trip(msg.replace("J", j), key).replace(j, "J")
1237
+ 'JOSIE'
1238
+
1239
+
1240
+ Notes
1241
+ =====
1242
+
1243
+ The Bifid cipher was invented around 1901 by Felix Delastelle.
1244
+ It is a *fractional substitution* cipher, where letters are
1245
+ replaced by pairs of symbols from a smaller alphabet. The
1246
+ cipher uses a `5 \times 5` square filled with some ordering of the
1247
+ alphabet, except that "J" is replaced with "I" (this is a so-called
1248
+ Polybius square; there is a `6 \times 6` analog if you add back in
1249
+ "J" and also append onto the usual 26 letter alphabet, the digits
1250
+ 0, 1, ..., 9).
1251
+ According to Helen Gaines' book *Cryptanalysis*, this type of cipher
1252
+ was used in the field by the German Army during World War I.
1253
+
1254
+ See Also
1255
+ ========
1256
+
1257
+ decipher_bifid5, encipher_bifid
1258
+
1259
+ """
1260
+ msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid5)
1261
+ key = padded_key(key, bifid5)
1262
+ return encipher_bifid(msg, '', key)
1263
+
1264
+
1265
+ def decipher_bifid5(msg, key):
1266
+ r"""
1267
+ Return the Bifid cipher decryption of ``msg``.
1268
+
1269
+ Explanation
1270
+ ===========
1271
+
1272
+ This is the version of the Bifid cipher that uses the `5 \times 5`
1273
+ Polybius square; the letter "J" is ignored unless a ``key`` of
1274
+ length 25 is used.
1275
+
1276
+ Parameters
1277
+ ==========
1278
+
1279
+ msg
1280
+ Ciphertext string.
1281
+
1282
+ key
1283
+ Short string for key; duplicated characters are ignored and if
1284
+ the length is less then 25 characters, it will be padded with
1285
+ other letters from the alphabet omitting "J".
1286
+ Non-alphabetic characters are ignored.
1287
+
1288
+ Returns
1289
+ =======
1290
+
1291
+ plaintext
1292
+ Plaintext from Bifid5 cipher (all caps, no spaces).
1293
+
1294
+ Examples
1295
+ ========
1296
+
1297
+ >>> from sympy.crypto.crypto import encipher_bifid5, decipher_bifid5
1298
+ >>> key = "gold bug"
1299
+ >>> encipher_bifid5('meet me on friday', key)
1300
+ 'IEILEHFSTSFXEE'
1301
+ >>> encipher_bifid5('meet me on monday', key)
1302
+ 'IEILHHFSTSFQYE'
1303
+ >>> decipher_bifid5(_, key)
1304
+ 'MEETMEONMONDAY'
1305
+
1306
+ """
1307
+ msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid5)
1308
+ key = padded_key(key, bifid5)
1309
+ return decipher_bifid(msg, '', key)
1310
+
1311
+
1312
+ def bifid5_square(key=None):
1313
+ r"""
1314
+ 5x5 Polybius square.
1315
+
1316
+ Produce the Polybius square for the `5 \times 5` Bifid cipher.
1317
+
1318
+ Examples
1319
+ ========
1320
+
1321
+ >>> from sympy.crypto.crypto import bifid5_square
1322
+ >>> bifid5_square("gold bug")
1323
+ Matrix([
1324
+ [G, O, L, D, B],
1325
+ [U, A, C, E, F],
1326
+ [H, I, K, M, N],
1327
+ [P, Q, R, S, T],
1328
+ [V, W, X, Y, Z]])
1329
+
1330
+ """
1331
+ if not key:
1332
+ key = bifid5
1333
+ else:
1334
+ _, key, _ = _prep('', key.upper(), None, bifid5)
1335
+ key = padded_key(key, bifid5)
1336
+ return bifid_square(key)
1337
+
1338
+
1339
+ def encipher_bifid6(msg, key):
1340
+ r"""
1341
+ Performs the Bifid cipher encryption on plaintext ``msg``, and
1342
+ returns the ciphertext.
1343
+
1344
+ This is the version of the Bifid cipher that uses the `6 \times 6`
1345
+ Polybius square.
1346
+
1347
+ Parameters
1348
+ ==========
1349
+
1350
+ msg
1351
+ Plaintext string (digits okay).
1352
+
1353
+ key
1354
+ Short string for key (digits okay).
1355
+
1356
+ If ``key`` is less than 36 characters long, the square will be
1357
+ filled with letters A through Z and digits 0 through 9.
1358
+
1359
+ Returns
1360
+ =======
1361
+
1362
+ ciphertext
1363
+ Ciphertext from Bifid cipher (all caps, no spaces).
1364
+
1365
+ See Also
1366
+ ========
1367
+
1368
+ decipher_bifid6, encipher_bifid
1369
+
1370
+ """
1371
+ msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid6)
1372
+ key = padded_key(key, bifid6)
1373
+ return encipher_bifid(msg, '', key)
1374
+
1375
+
1376
+ def decipher_bifid6(msg, key):
1377
+ r"""
1378
+ Performs the Bifid cipher decryption on ciphertext ``msg``, and
1379
+ returns the plaintext.
1380
+
1381
+ This is the version of the Bifid cipher that uses the `6 \times 6`
1382
+ Polybius square.
1383
+
1384
+ Parameters
1385
+ ==========
1386
+
1387
+ msg
1388
+ Ciphertext string (digits okay); converted to upper case
1389
+
1390
+ key
1391
+ Short string for key (digits okay).
1392
+
1393
+ If ``key`` is less than 36 characters long, the square will be
1394
+ filled with letters A through Z and digits 0 through 9.
1395
+ All letters are converted to uppercase.
1396
+
1397
+ Returns
1398
+ =======
1399
+
1400
+ plaintext
1401
+ Plaintext from Bifid cipher (all caps, no spaces).
1402
+
1403
+ Examples
1404
+ ========
1405
+
1406
+ >>> from sympy.crypto.crypto import encipher_bifid6, decipher_bifid6
1407
+ >>> key = "gold bug"
1408
+ >>> encipher_bifid6('meet me on monday at 8am', key)
1409
+ 'KFKLJJHF5MMMKTFRGPL'
1410
+ >>> decipher_bifid6(_, key)
1411
+ 'MEETMEONMONDAYAT8AM'
1412
+
1413
+ """
1414
+ msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid6)
1415
+ key = padded_key(key, bifid6)
1416
+ return decipher_bifid(msg, '', key)
1417
+
1418
+
1419
+ def bifid6_square(key=None):
1420
+ r"""
1421
+ 6x6 Polybius square.
1422
+
1423
+ Produces the Polybius square for the `6 \times 6` Bifid cipher.
1424
+ Assumes alphabet of symbols is "A", ..., "Z", "0", ..., "9".
1425
+
1426
+ Examples
1427
+ ========
1428
+
1429
+ >>> from sympy.crypto.crypto import bifid6_square
1430
+ >>> key = "gold bug"
1431
+ >>> bifid6_square(key)
1432
+ Matrix([
1433
+ [G, O, L, D, B, U],
1434
+ [A, C, E, F, H, I],
1435
+ [J, K, M, N, P, Q],
1436
+ [R, S, T, V, W, X],
1437
+ [Y, Z, 0, 1, 2, 3],
1438
+ [4, 5, 6, 7, 8, 9]])
1439
+
1440
+ """
1441
+ if not key:
1442
+ key = bifid6
1443
+ else:
1444
+ _, key, _ = _prep('', key.upper(), None, bifid6)
1445
+ key = padded_key(key, bifid6)
1446
+ return bifid_square(key)
1447
+
1448
+
1449
+ #################### RSA #############################
1450
+
1451
+ def _decipher_rsa_crt(i, d, factors):
1452
+ """Decipher RSA using chinese remainder theorem from the information
1453
+ of the relatively-prime factors of the modulus.
1454
+
1455
+ Parameters
1456
+ ==========
1457
+
1458
+ i : integer
1459
+ Ciphertext
1460
+
1461
+ d : integer
1462
+ The exponent component.
1463
+
1464
+ factors : list of relatively-prime integers
1465
+ The integers given must be coprime and the product must equal
1466
+ the modulus component of the original RSA key.
1467
+
1468
+ Examples
1469
+ ========
1470
+
1471
+ How to decrypt RSA with CRT:
1472
+
1473
+ >>> from sympy.crypto.crypto import rsa_public_key, rsa_private_key
1474
+ >>> primes = [61, 53]
1475
+ >>> e = 17
1476
+ >>> args = primes + [e]
1477
+ >>> puk = rsa_public_key(*args)
1478
+ >>> prk = rsa_private_key(*args)
1479
+
1480
+ >>> from sympy.crypto.crypto import encipher_rsa, _decipher_rsa_crt
1481
+ >>> msg = 65
1482
+ >>> crt_primes = primes
1483
+ >>> encrypted = encipher_rsa(msg, puk)
1484
+ >>> decrypted = _decipher_rsa_crt(encrypted, prk[1], primes)
1485
+ >>> decrypted
1486
+ 65
1487
+ """
1488
+ moduluses = [pow(i, d, p) for p in factors]
1489
+
1490
+ result = crt(factors, moduluses)
1491
+ if not result:
1492
+ raise ValueError("CRT failed")
1493
+ return result[0]
1494
+
1495
+
1496
+ def _rsa_key(*args, public=True, private=True, totient='Euler', index=None, multipower=None):
1497
+ r"""A private subroutine to generate RSA key
1498
+
1499
+ Parameters
1500
+ ==========
1501
+
1502
+ public, private : bool, optional
1503
+ Flag to generate either a public key, a private key.
1504
+
1505
+ totient : 'Euler' or 'Carmichael'
1506
+ Different notation used for totient.
1507
+
1508
+ multipower : bool, optional
1509
+ Flag to bypass warning for multipower RSA.
1510
+ """
1511
+
1512
+ if len(args) < 2:
1513
+ return False
1514
+
1515
+ if totient not in ('Euler', 'Carmichael'):
1516
+ raise ValueError(
1517
+ "The argument totient={} should either be " \
1518
+ "'Euler', 'Carmichalel'." \
1519
+ .format(totient))
1520
+
1521
+ if totient == 'Euler':
1522
+ _totient = _euler
1523
+ else:
1524
+ _totient = _carmichael
1525
+
1526
+ if index is not None:
1527
+ index = as_int(index)
1528
+ if totient != 'Carmichael':
1529
+ raise ValueError(
1530
+ "Setting the 'index' keyword argument requires totient"
1531
+ "notation to be specified as 'Carmichael'.")
1532
+
1533
+ primes, e = args[:-1], args[-1]
1534
+
1535
+ if not all(isprime(p) for p in primes):
1536
+ new_primes = []
1537
+ for i in primes:
1538
+ new_primes.extend(factorint(i, multiple=True))
1539
+ primes = new_primes
1540
+
1541
+ n = reduce(lambda i, j: i*j, primes)
1542
+
1543
+ tally = multiset(primes)
1544
+ if all(v == 1 for v in tally.values()):
1545
+ multiple = list(tally.keys())
1546
+ phi = _totient._from_distinct_primes(*multiple)
1547
+
1548
+ else:
1549
+ if not multipower:
1550
+ NonInvertibleCipherWarning(
1551
+ 'Non-distinctive primes found in the factors {}. '
1552
+ 'The cipher may not be decryptable for some numbers '
1553
+ 'in the complete residue system Z[{}], but the cipher '
1554
+ 'can still be valid if you restrict the domain to be '
1555
+ 'the reduced residue system Z*[{}]. You can pass '
1556
+ 'the flag multipower=True if you want to suppress this '
1557
+ 'warning.'
1558
+ .format(primes, n, n)
1559
+ # stacklevel=4 because most users will call a function that
1560
+ # calls this function
1561
+ ).warn(stacklevel=4)
1562
+ phi = _totient._from_factors(tally)
1563
+
1564
+ if igcd(e, phi) == 1:
1565
+ if public and not private:
1566
+ if isinstance(index, int):
1567
+ e = e % phi
1568
+ e += index * phi
1569
+ return n, e
1570
+
1571
+ if private and not public:
1572
+ d = mod_inverse(e, phi)
1573
+ if isinstance(index, int):
1574
+ d += index * phi
1575
+ return n, d
1576
+
1577
+ return False
1578
+
1579
+
1580
+ def rsa_public_key(*args, **kwargs):
1581
+ r"""Return the RSA *public key* pair, `(n, e)`
1582
+
1583
+ Parameters
1584
+ ==========
1585
+
1586
+ args : naturals
1587
+ If specified as `p, q, e` where `p` and `q` are distinct primes
1588
+ and `e` is a desired public exponent of the RSA, `n = p q` and
1589
+ `e` will be verified against the totient
1590
+ `\phi(n)` (Euler totient) or `\lambda(n)` (Carmichael totient)
1591
+ to be `\gcd(e, \phi(n)) = 1` or `\gcd(e, \lambda(n)) = 1`.
1592
+
1593
+ If specified as `p_1, p_2, \dots, p_n, e` where
1594
+ `p_1, p_2, \dots, p_n` are specified as primes,
1595
+ and `e` is specified as a desired public exponent of the RSA,
1596
+ it will be able to form a multi-prime RSA, which is a more
1597
+ generalized form of the popular 2-prime RSA.
1598
+
1599
+ It can also be possible to form a single-prime RSA by specifying
1600
+ the argument as `p, e`, which can be considered a trivial case
1601
+ of a multiprime RSA.
1602
+
1603
+ Furthermore, it can be possible to form a multi-power RSA by
1604
+ specifying two or more pairs of the primes to be same.
1605
+ However, unlike the two-distinct prime RSA or multi-prime
1606
+ RSA, not every numbers in the complete residue system
1607
+ (`\mathbb{Z}_n`) will be decryptable since the mapping
1608
+ `\mathbb{Z}_{n} \rightarrow \mathbb{Z}_{n}`
1609
+ will not be bijective.
1610
+ (Only except for the trivial case when
1611
+ `e = 1`
1612
+ or more generally,
1613
+
1614
+ .. math::
1615
+ e \in \left \{ 1 + k \lambda(n)
1616
+ \mid k \in \mathbb{Z} \land k \geq 0 \right \}
1617
+
1618
+ when RSA reduces to the identity.)
1619
+ However, the RSA can still be decryptable for the numbers in the
1620
+ reduced residue system (`\mathbb{Z}_n^{\times}`), since the
1621
+ mapping
1622
+ `\mathbb{Z}_{n}^{\times} \rightarrow \mathbb{Z}_{n}^{\times}`
1623
+ can still be bijective.
1624
+
1625
+ If you pass a non-prime integer to the arguments
1626
+ `p_1, p_2, \dots, p_n`, the particular number will be
1627
+ prime-factored and it will become either a multi-prime RSA or a
1628
+ multi-power RSA in its canonical form, depending on whether the
1629
+ product equals its radical or not.
1630
+ `p_1 p_2 \dots p_n = \text{rad}(p_1 p_2 \dots p_n)`
1631
+
1632
+ totient : bool, optional
1633
+ If ``'Euler'``, it uses Euler's totient `\phi(n)` which is
1634
+ :meth:`sympy.ntheory.factor_.totient` in SymPy.
1635
+
1636
+ If ``'Carmichael'``, it uses Carmichael's totient `\lambda(n)`
1637
+ which is :meth:`sympy.ntheory.factor_.reduced_totient` in SymPy.
1638
+
1639
+ Unlike private key generation, this is a trivial keyword for
1640
+ public key generation because
1641
+ `\gcd(e, \phi(n)) = 1 \iff \gcd(e, \lambda(n)) = 1`.
1642
+
1643
+ index : nonnegative integer, optional
1644
+ Returns an arbitrary solution of a RSA public key at the index
1645
+ specified at `0, 1, 2, \dots`. This parameter needs to be
1646
+ specified along with ``totient='Carmichael'``.
1647
+
1648
+ Similarly to the non-uniquenss of a RSA private key as described
1649
+ in the ``index`` parameter documentation in
1650
+ :meth:`rsa_private_key`, RSA public key is also not unique and
1651
+ there is an infinite number of RSA public exponents which
1652
+ can behave in the same manner.
1653
+
1654
+ From any given RSA public exponent `e`, there are can be an
1655
+ another RSA public exponent `e + k \lambda(n)` where `k` is an
1656
+ integer, `\lambda` is a Carmichael's totient function.
1657
+
1658
+ However, considering only the positive cases, there can be
1659
+ a principal solution of a RSA public exponent `e_0` in
1660
+ `0 < e_0 < \lambda(n)`, and all the other solutions
1661
+ can be canonicalzed in a form of `e_0 + k \lambda(n)`.
1662
+
1663
+ ``index`` specifies the `k` notation to yield any possible value
1664
+ an RSA public key can have.
1665
+
1666
+ An example of computing any arbitrary RSA public key:
1667
+
1668
+ >>> from sympy.crypto.crypto import rsa_public_key
1669
+ >>> rsa_public_key(61, 53, 17, totient='Carmichael', index=0)
1670
+ (3233, 17)
1671
+ >>> rsa_public_key(61, 53, 17, totient='Carmichael', index=1)
1672
+ (3233, 797)
1673
+ >>> rsa_public_key(61, 53, 17, totient='Carmichael', index=2)
1674
+ (3233, 1577)
1675
+
1676
+ multipower : bool, optional
1677
+ Any pair of non-distinct primes found in the RSA specification
1678
+ will restrict the domain of the cryptosystem, as noted in the
1679
+ explanation of the parameter ``args``.
1680
+
1681
+ SymPy RSA key generator may give a warning before dispatching it
1682
+ as a multi-power RSA, however, you can disable the warning if
1683
+ you pass ``True`` to this keyword.
1684
+
1685
+ Returns
1686
+ =======
1687
+
1688
+ (n, e) : int, int
1689
+ `n` is a product of any arbitrary number of primes given as
1690
+ the argument.
1691
+
1692
+ `e` is relatively prime (coprime) to the Euler totient
1693
+ `\phi(n)`.
1694
+
1695
+ False
1696
+ Returned if less than two arguments are given, or `e` is
1697
+ not relatively prime to the modulus.
1698
+
1699
+ Examples
1700
+ ========
1701
+
1702
+ >>> from sympy.crypto.crypto import rsa_public_key
1703
+
1704
+ A public key of a two-prime RSA:
1705
+
1706
+ >>> p, q, e = 3, 5, 7
1707
+ >>> rsa_public_key(p, q, e)
1708
+ (15, 7)
1709
+ >>> rsa_public_key(p, q, 30)
1710
+ False
1711
+
1712
+ A public key of a multiprime RSA:
1713
+
1714
+ >>> primes = [2, 3, 5, 7, 11, 13]
1715
+ >>> e = 7
1716
+ >>> args = primes + [e]
1717
+ >>> rsa_public_key(*args)
1718
+ (30030, 7)
1719
+
1720
+ Notes
1721
+ =====
1722
+
1723
+ Although the RSA can be generalized over any modulus `n`, using
1724
+ two large primes had became the most popular specification because a
1725
+ product of two large primes is usually the hardest to factor
1726
+ relatively to the digits of `n` can have.
1727
+
1728
+ However, it may need further understanding of the time complexities
1729
+ of each prime-factoring algorithms to verify the claim.
1730
+
1731
+ See Also
1732
+ ========
1733
+
1734
+ rsa_private_key
1735
+ encipher_rsa
1736
+ decipher_rsa
1737
+
1738
+ References
1739
+ ==========
1740
+
1741
+ .. [1] https://en.wikipedia.org/wiki/RSA_%28cryptosystem%29
1742
+
1743
+ .. [2] https://cacr.uwaterloo.ca/techreports/2006/cacr2006-16.pdf
1744
+
1745
+ .. [3] https://link.springer.com/content/pdf/10.1007/BFb0055738.pdf
1746
+
1747
+ .. [4] https://www.itiis.org/digital-library/manuscript/1381
1748
+ """
1749
+ return _rsa_key(*args, public=True, private=False, **kwargs)
1750
+
1751
+
1752
+ def rsa_private_key(*args, **kwargs):
1753
+ r"""Return the RSA *private key* pair, `(n, d)`
1754
+
1755
+ Parameters
1756
+ ==========
1757
+
1758
+ args : naturals
1759
+ The keyword is identical to the ``args`` in
1760
+ :meth:`rsa_public_key`.
1761
+
1762
+ totient : bool, optional
1763
+ If ``'Euler'``, it uses Euler's totient convention `\phi(n)`
1764
+ which is :meth:`sympy.ntheory.factor_.totient` in SymPy.
1765
+
1766
+ If ``'Carmichael'``, it uses Carmichael's totient convention
1767
+ `\lambda(n)` which is
1768
+ :meth:`sympy.ntheory.factor_.reduced_totient` in SymPy.
1769
+
1770
+ There can be some output differences for private key generation
1771
+ as examples below.
1772
+
1773
+ Example using Euler's totient:
1774
+
1775
+ >>> from sympy.crypto.crypto import rsa_private_key
1776
+ >>> rsa_private_key(61, 53, 17, totient='Euler')
1777
+ (3233, 2753)
1778
+
1779
+ Example using Carmichael's totient:
1780
+
1781
+ >>> from sympy.crypto.crypto import rsa_private_key
1782
+ >>> rsa_private_key(61, 53, 17, totient='Carmichael')
1783
+ (3233, 413)
1784
+
1785
+ index : nonnegative integer, optional
1786
+ Returns an arbitrary solution of a RSA private key at the index
1787
+ specified at `0, 1, 2, \dots`. This parameter needs to be
1788
+ specified along with ``totient='Carmichael'``.
1789
+
1790
+ RSA private exponent is a non-unique solution of
1791
+ `e d \mod \lambda(n) = 1` and it is possible in any form of
1792
+ `d + k \lambda(n)`, where `d` is an another
1793
+ already-computed private exponent, and `\lambda` is a
1794
+ Carmichael's totient function, and `k` is any integer.
1795
+
1796
+ However, considering only the positive cases, there can be
1797
+ a principal solution of a RSA private exponent `d_0` in
1798
+ `0 < d_0 < \lambda(n)`, and all the other solutions
1799
+ can be canonicalzed in a form of `d_0 + k \lambda(n)`.
1800
+
1801
+ ``index`` specifies the `k` notation to yield any possible value
1802
+ an RSA private key can have.
1803
+
1804
+ An example of computing any arbitrary RSA private key:
1805
+
1806
+ >>> from sympy.crypto.crypto import rsa_private_key
1807
+ >>> rsa_private_key(61, 53, 17, totient='Carmichael', index=0)
1808
+ (3233, 413)
1809
+ >>> rsa_private_key(61, 53, 17, totient='Carmichael', index=1)
1810
+ (3233, 1193)
1811
+ >>> rsa_private_key(61, 53, 17, totient='Carmichael', index=2)
1812
+ (3233, 1973)
1813
+
1814
+ multipower : bool, optional
1815
+ The keyword is identical to the ``multipower`` in
1816
+ :meth:`rsa_public_key`.
1817
+
1818
+ Returns
1819
+ =======
1820
+
1821
+ (n, d) : int, int
1822
+ `n` is a product of any arbitrary number of primes given as
1823
+ the argument.
1824
+
1825
+ `d` is the inverse of `e` (mod `\phi(n)`) where `e` is the
1826
+ exponent given, and `\phi` is a Euler totient.
1827
+
1828
+ False
1829
+ Returned if less than two arguments are given, or `e` is
1830
+ not relatively prime to the totient of the modulus.
1831
+
1832
+ Examples
1833
+ ========
1834
+
1835
+ >>> from sympy.crypto.crypto import rsa_private_key
1836
+
1837
+ A private key of a two-prime RSA:
1838
+
1839
+ >>> p, q, e = 3, 5, 7
1840
+ >>> rsa_private_key(p, q, e)
1841
+ (15, 7)
1842
+ >>> rsa_private_key(p, q, 30)
1843
+ False
1844
+
1845
+ A private key of a multiprime RSA:
1846
+
1847
+ >>> primes = [2, 3, 5, 7, 11, 13]
1848
+ >>> e = 7
1849
+ >>> args = primes + [e]
1850
+ >>> rsa_private_key(*args)
1851
+ (30030, 823)
1852
+
1853
+ See Also
1854
+ ========
1855
+
1856
+ rsa_public_key
1857
+ encipher_rsa
1858
+ decipher_rsa
1859
+
1860
+ References
1861
+ ==========
1862
+
1863
+ .. [1] https://en.wikipedia.org/wiki/RSA_%28cryptosystem%29
1864
+
1865
+ .. [2] https://cacr.uwaterloo.ca/techreports/2006/cacr2006-16.pdf
1866
+
1867
+ .. [3] https://link.springer.com/content/pdf/10.1007/BFb0055738.pdf
1868
+
1869
+ .. [4] https://www.itiis.org/digital-library/manuscript/1381
1870
+ """
1871
+ return _rsa_key(*args, public=False, private=True, **kwargs)
1872
+
1873
+
1874
+ def _encipher_decipher_rsa(i, key, factors=None):
1875
+ n, d = key
1876
+ if not factors:
1877
+ return pow(i, d, n)
1878
+
1879
+ def _is_coprime_set(l):
1880
+ is_coprime_set = True
1881
+ for i in range(len(l)):
1882
+ for j in range(i+1, len(l)):
1883
+ if igcd(l[i], l[j]) != 1:
1884
+ is_coprime_set = False
1885
+ break
1886
+ return is_coprime_set
1887
+
1888
+ prod = reduce(lambda i, j: i*j, factors)
1889
+ if prod == n and _is_coprime_set(factors):
1890
+ return _decipher_rsa_crt(i, d, factors)
1891
+ return _encipher_decipher_rsa(i, key, factors=None)
1892
+
1893
+
1894
+ def encipher_rsa(i, key, factors=None):
1895
+ r"""Encrypt the plaintext with RSA.
1896
+
1897
+ Parameters
1898
+ ==========
1899
+
1900
+ i : integer
1901
+ The plaintext to be encrypted for.
1902
+
1903
+ key : (n, e) where n, e are integers
1904
+ `n` is the modulus of the key and `e` is the exponent of the
1905
+ key. The encryption is computed by `i^e \bmod n`.
1906
+
1907
+ The key can either be a public key or a private key, however,
1908
+ the message encrypted by a public key can only be decrypted by
1909
+ a private key, and vice versa, as RSA is an asymmetric
1910
+ cryptography system.
1911
+
1912
+ factors : list of coprime integers
1913
+ This is identical to the keyword ``factors`` in
1914
+ :meth:`decipher_rsa`.
1915
+
1916
+ Notes
1917
+ =====
1918
+
1919
+ Some specifications may make the RSA not cryptographically
1920
+ meaningful.
1921
+
1922
+ For example, `0`, `1` will remain always same after taking any
1923
+ number of exponentiation, thus, should be avoided.
1924
+
1925
+ Furthermore, if `i^e < n`, `i` may easily be figured out by taking
1926
+ `e` th root.
1927
+
1928
+ And also, specifying the exponent as `1` or in more generalized form
1929
+ as `1 + k \lambda(n)` where `k` is an nonnegative integer,
1930
+ `\lambda` is a carmichael totient, the RSA becomes an identity
1931
+ mapping.
1932
+
1933
+ Examples
1934
+ ========
1935
+
1936
+ >>> from sympy.crypto.crypto import encipher_rsa
1937
+ >>> from sympy.crypto.crypto import rsa_public_key, rsa_private_key
1938
+
1939
+ Public Key Encryption:
1940
+
1941
+ >>> p, q, e = 3, 5, 7
1942
+ >>> puk = rsa_public_key(p, q, e)
1943
+ >>> msg = 12
1944
+ >>> encipher_rsa(msg, puk)
1945
+ 3
1946
+
1947
+ Private Key Encryption:
1948
+
1949
+ >>> p, q, e = 3, 5, 7
1950
+ >>> prk = rsa_private_key(p, q, e)
1951
+ >>> msg = 12
1952
+ >>> encipher_rsa(msg, prk)
1953
+ 3
1954
+
1955
+ Encryption using chinese remainder theorem:
1956
+
1957
+ >>> encipher_rsa(msg, prk, factors=[p, q])
1958
+ 3
1959
+ """
1960
+ return _encipher_decipher_rsa(i, key, factors=factors)
1961
+
1962
+
1963
+ def decipher_rsa(i, key, factors=None):
1964
+ r"""Decrypt the ciphertext with RSA.
1965
+
1966
+ Parameters
1967
+ ==========
1968
+
1969
+ i : integer
1970
+ The ciphertext to be decrypted for.
1971
+
1972
+ key : (n, d) where n, d are integers
1973
+ `n` is the modulus of the key and `d` is the exponent of the
1974
+ key. The decryption is computed by `i^d \bmod n`.
1975
+
1976
+ The key can either be a public key or a private key, however,
1977
+ the message encrypted by a public key can only be decrypted by
1978
+ a private key, and vice versa, as RSA is an asymmetric
1979
+ cryptography system.
1980
+
1981
+ factors : list of coprime integers
1982
+ As the modulus `n` created from RSA key generation is composed
1983
+ of arbitrary prime factors
1984
+ `n = {p_1}^{k_1}{p_2}^{k_2}\dots{p_n}^{k_n}` where
1985
+ `p_1, p_2, \dots, p_n` are distinct primes and
1986
+ `k_1, k_2, \dots, k_n` are positive integers, chinese remainder
1987
+ theorem can be used to compute `i^d \bmod n` from the
1988
+ fragmented modulo operations like
1989
+
1990
+ .. math::
1991
+ i^d \bmod {p_1}^{k_1}, i^d \bmod {p_2}^{k_2}, \dots,
1992
+ i^d \bmod {p_n}^{k_n}
1993
+
1994
+ or like
1995
+
1996
+ .. math::
1997
+ i^d \bmod {p_1}^{k_1}{p_2}^{k_2},
1998
+ i^d \bmod {p_3}^{k_3}, \dots ,
1999
+ i^d \bmod {p_n}^{k_n}
2000
+
2001
+ as long as every moduli does not share any common divisor each
2002
+ other.
2003
+
2004
+ The raw primes used in generating the RSA key pair can be a good
2005
+ option.
2006
+
2007
+ Note that the speed advantage of using this is only viable for
2008
+ very large cases (Like 2048-bit RSA keys) since the
2009
+ overhead of using pure Python implementation of
2010
+ :meth:`sympy.ntheory.modular.crt` may overcompensate the
2011
+ theoretical speed advantage.
2012
+
2013
+ Notes
2014
+ =====
2015
+
2016
+ See the ``Notes`` section in the documentation of
2017
+ :meth:`encipher_rsa`
2018
+
2019
+ Examples
2020
+ ========
2021
+
2022
+ >>> from sympy.crypto.crypto import decipher_rsa, encipher_rsa
2023
+ >>> from sympy.crypto.crypto import rsa_public_key, rsa_private_key
2024
+
2025
+ Public Key Encryption and Decryption:
2026
+
2027
+ >>> p, q, e = 3, 5, 7
2028
+ >>> prk = rsa_private_key(p, q, e)
2029
+ >>> puk = rsa_public_key(p, q, e)
2030
+ >>> msg = 12
2031
+ >>> new_msg = encipher_rsa(msg, prk)
2032
+ >>> new_msg
2033
+ 3
2034
+ >>> decipher_rsa(new_msg, puk)
2035
+ 12
2036
+
2037
+ Private Key Encryption and Decryption:
2038
+
2039
+ >>> p, q, e = 3, 5, 7
2040
+ >>> prk = rsa_private_key(p, q, e)
2041
+ >>> puk = rsa_public_key(p, q, e)
2042
+ >>> msg = 12
2043
+ >>> new_msg = encipher_rsa(msg, puk)
2044
+ >>> new_msg
2045
+ 3
2046
+ >>> decipher_rsa(new_msg, prk)
2047
+ 12
2048
+
2049
+ Decryption using chinese remainder theorem:
2050
+
2051
+ >>> decipher_rsa(new_msg, prk, factors=[p, q])
2052
+ 12
2053
+
2054
+ See Also
2055
+ ========
2056
+
2057
+ encipher_rsa
2058
+ """
2059
+ return _encipher_decipher_rsa(i, key, factors=factors)
2060
+
2061
+
2062
+ #################### kid krypto (kid RSA) #############################
2063
+
2064
+
2065
+ def kid_rsa_public_key(a, b, A, B):
2066
+ r"""
2067
+ Kid RSA is a version of RSA useful to teach grade school children
2068
+ since it does not involve exponentiation.
2069
+
2070
+ Explanation
2071
+ ===========
2072
+
2073
+ Alice wants to talk to Bob. Bob generates keys as follows.
2074
+ Key generation:
2075
+
2076
+ * Select positive integers `a, b, A, B` at random.
2077
+ * Compute `M = a b - 1`, `e = A M + a`, `d = B M + b`,
2078
+ `n = (e d - 1)//M`.
2079
+ * The *public key* is `(n, e)`. Bob sends these to Alice.
2080
+ * The *private key* is `(n, d)`, which Bob keeps secret.
2081
+
2082
+ Encryption: If `p` is the plaintext message then the
2083
+ ciphertext is `c = p e \pmod n`.
2084
+
2085
+ Decryption: If `c` is the ciphertext message then the
2086
+ plaintext is `p = c d \pmod n`.
2087
+
2088
+ Examples
2089
+ ========
2090
+
2091
+ >>> from sympy.crypto.crypto import kid_rsa_public_key
2092
+ >>> a, b, A, B = 3, 4, 5, 6
2093
+ >>> kid_rsa_public_key(a, b, A, B)
2094
+ (369, 58)
2095
+
2096
+ """
2097
+ M = a*b - 1
2098
+ e = A*M + a
2099
+ d = B*M + b
2100
+ n = (e*d - 1)//M
2101
+ return n, e
2102
+
2103
+
2104
+ def kid_rsa_private_key(a, b, A, B):
2105
+ """
2106
+ Compute `M = a b - 1`, `e = A M + a`, `d = B M + b`,
2107
+ `n = (e d - 1) / M`. The *private key* is `d`, which Bob
2108
+ keeps secret.
2109
+
2110
+ Examples
2111
+ ========
2112
+
2113
+ >>> from sympy.crypto.crypto import kid_rsa_private_key
2114
+ >>> a, b, A, B = 3, 4, 5, 6
2115
+ >>> kid_rsa_private_key(a, b, A, B)
2116
+ (369, 70)
2117
+
2118
+ """
2119
+ M = a*b - 1
2120
+ e = A*M + a
2121
+ d = B*M + b
2122
+ n = (e*d - 1)//M
2123
+ return n, d
2124
+
2125
+
2126
+ def encipher_kid_rsa(msg, key):
2127
+ """
2128
+ Here ``msg`` is the plaintext and ``key`` is the public key.
2129
+
2130
+ Examples
2131
+ ========
2132
+
2133
+ >>> from sympy.crypto.crypto import (
2134
+ ... encipher_kid_rsa, kid_rsa_public_key)
2135
+ >>> msg = 200
2136
+ >>> a, b, A, B = 3, 4, 5, 6
2137
+ >>> key = kid_rsa_public_key(a, b, A, B)
2138
+ >>> encipher_kid_rsa(msg, key)
2139
+ 161
2140
+
2141
+ """
2142
+ n, e = key
2143
+ return (msg*e) % n
2144
+
2145
+
2146
+ def decipher_kid_rsa(msg, key):
2147
+ """
2148
+ Here ``msg`` is the plaintext and ``key`` is the private key.
2149
+
2150
+ Examples
2151
+ ========
2152
+
2153
+ >>> from sympy.crypto.crypto import (
2154
+ ... kid_rsa_public_key, kid_rsa_private_key,
2155
+ ... decipher_kid_rsa, encipher_kid_rsa)
2156
+ >>> a, b, A, B = 3, 4, 5, 6
2157
+ >>> d = kid_rsa_private_key(a, b, A, B)
2158
+ >>> msg = 200
2159
+ >>> pub = kid_rsa_public_key(a, b, A, B)
2160
+ >>> pri = kid_rsa_private_key(a, b, A, B)
2161
+ >>> ct = encipher_kid_rsa(msg, pub)
2162
+ >>> decipher_kid_rsa(ct, pri)
2163
+ 200
2164
+
2165
+ """
2166
+ n, d = key
2167
+ return (msg*d) % n
2168
+
2169
+
2170
+ #################### Morse Code ######################################
2171
+
2172
+ morse_char = {
2173
+ ".-": "A", "-...": "B",
2174
+ "-.-.": "C", "-..": "D",
2175
+ ".": "E", "..-.": "F",
2176
+ "--.": "G", "....": "H",
2177
+ "..": "I", ".---": "J",
2178
+ "-.-": "K", ".-..": "L",
2179
+ "--": "M", "-.": "N",
2180
+ "---": "O", ".--.": "P",
2181
+ "--.-": "Q", ".-.": "R",
2182
+ "...": "S", "-": "T",
2183
+ "..-": "U", "...-": "V",
2184
+ ".--": "W", "-..-": "X",
2185
+ "-.--": "Y", "--..": "Z",
2186
+ "-----": "0", ".----": "1",
2187
+ "..---": "2", "...--": "3",
2188
+ "....-": "4", ".....": "5",
2189
+ "-....": "6", "--...": "7",
2190
+ "---..": "8", "----.": "9",
2191
+ ".-.-.-": ".", "--..--": ",",
2192
+ "---...": ":", "-.-.-.": ";",
2193
+ "..--..": "?", "-....-": "-",
2194
+ "..--.-": "_", "-.--.": "(",
2195
+ "-.--.-": ")", ".----.": "'",
2196
+ "-...-": "=", ".-.-.": "+",
2197
+ "-..-.": "/", ".--.-.": "@",
2198
+ "...-..-": "$", "-.-.--": "!"}
2199
+ char_morse = {v: k for k, v in morse_char.items()}
2200
+
2201
+
2202
+ def encode_morse(msg, sep='|', mapping=None):
2203
+ """
2204
+ Encodes a plaintext into popular Morse Code with letters
2205
+ separated by ``sep`` and words by a double ``sep``.
2206
+
2207
+ Examples
2208
+ ========
2209
+
2210
+ >>> from sympy.crypto.crypto import encode_morse
2211
+ >>> msg = 'ATTACK RIGHT FLANK'
2212
+ >>> encode_morse(msg)
2213
+ '.-|-|-|.-|-.-.|-.-||.-.|..|--.|....|-||..-.|.-..|.-|-.|-.-'
2214
+
2215
+ References
2216
+ ==========
2217
+
2218
+ .. [1] https://en.wikipedia.org/wiki/Morse_code
2219
+
2220
+ """
2221
+
2222
+ mapping = mapping or char_morse
2223
+ assert sep not in mapping
2224
+ word_sep = 2*sep
2225
+ mapping[" "] = word_sep
2226
+ suffix = msg and msg[-1] in whitespace
2227
+
2228
+ # normalize whitespace
2229
+ msg = (' ' if word_sep else '').join(msg.split())
2230
+ # omit unmapped chars
2231
+ chars = set(''.join(msg.split()))
2232
+ ok = set(mapping.keys())
2233
+ msg = translate(msg, None, ''.join(chars - ok))
2234
+
2235
+ morsestring = []
2236
+ words = msg.split()
2237
+ for word in words:
2238
+ morseword = []
2239
+ for letter in word:
2240
+ morseletter = mapping[letter]
2241
+ morseword.append(morseletter)
2242
+
2243
+ word = sep.join(morseword)
2244
+ morsestring.append(word)
2245
+
2246
+ return word_sep.join(morsestring) + (word_sep if suffix else '')
2247
+
2248
+
2249
+ def decode_morse(msg, sep='|', mapping=None):
2250
+ """
2251
+ Decodes a Morse Code with letters separated by ``sep``
2252
+ (default is '|') and words by `word_sep` (default is '||)
2253
+ into plaintext.
2254
+
2255
+ Examples
2256
+ ========
2257
+
2258
+ >>> from sympy.crypto.crypto import decode_morse
2259
+ >>> mc = '--|---|...-|.||.|.-|...|-'
2260
+ >>> decode_morse(mc)
2261
+ 'MOVE EAST'
2262
+
2263
+ References
2264
+ ==========
2265
+
2266
+ .. [1] https://en.wikipedia.org/wiki/Morse_code
2267
+
2268
+ """
2269
+
2270
+ mapping = mapping or morse_char
2271
+ word_sep = 2*sep
2272
+ characterstring = []
2273
+ words = msg.strip(word_sep).split(word_sep)
2274
+ for word in words:
2275
+ letters = word.split(sep)
2276
+ chars = [mapping[c] for c in letters]
2277
+ word = ''.join(chars)
2278
+ characterstring.append(word)
2279
+ rv = " ".join(characterstring)
2280
+ return rv
2281
+
2282
+
2283
+ #################### LFSRs ##########################################
2284
+
2285
+
2286
+ def lfsr_sequence(key, fill, n):
2287
+ r"""
2288
+ This function creates an LFSR sequence.
2289
+
2290
+ Parameters
2291
+ ==========
2292
+
2293
+ key : list
2294
+ A list of finite field elements, `[c_0, c_1, \ldots, c_k].`
2295
+
2296
+ fill : list
2297
+ The list of the initial terms of the LFSR sequence,
2298
+ `[x_0, x_1, \ldots, x_k].`
2299
+
2300
+ n
2301
+ Number of terms of the sequence that the function returns.
2302
+
2303
+ Returns
2304
+ =======
2305
+
2306
+ L
2307
+ The LFSR sequence defined by
2308
+ `x_{n+1} = c_k x_n + \ldots + c_0 x_{n-k}`, for
2309
+ `n \leq k`.
2310
+
2311
+ Notes
2312
+ =====
2313
+
2314
+ S. Golomb [G]_ gives a list of three statistical properties a
2315
+ sequence of numbers `a = \{a_n\}_{n=1}^\infty`,
2316
+ `a_n \in \{0,1\}`, should display to be considered
2317
+ "random". Define the autocorrelation of `a` to be
2318
+
2319
+ .. math::
2320
+
2321
+ C(k) = C(k,a) = \lim_{N\rightarrow \infty} {1\over N}\sum_{n=1}^N (-1)^{a_n + a_{n+k}}.
2322
+
2323
+ In the case where `a` is periodic with period
2324
+ `P` then this reduces to
2325
+
2326
+ .. math::
2327
+
2328
+ C(k) = {1\over P}\sum_{n=1}^P (-1)^{a_n + a_{n+k}}.
2329
+
2330
+ Assume `a` is periodic with period `P`.
2331
+
2332
+ - balance:
2333
+
2334
+ .. math::
2335
+
2336
+ \left|\sum_{n=1}^P(-1)^{a_n}\right| \leq 1.
2337
+
2338
+ - low autocorrelation:
2339
+
2340
+ .. math::
2341
+
2342
+ C(k) = \left\{ \begin{array}{cc} 1,& k = 0,\\ \epsilon, & k \ne 0. \end{array} \right.
2343
+
2344
+ (For sequences satisfying these first two properties, it is known
2345
+ that `\epsilon = -1/P` must hold.)
2346
+
2347
+ - proportional runs property: In each period, half the runs have
2348
+ length `1`, one-fourth have length `2`, etc.
2349
+ Moreover, there are as many runs of `1`'s as there are of
2350
+ `0`'s.
2351
+
2352
+ Examples
2353
+ ========
2354
+
2355
+ >>> from sympy.crypto.crypto import lfsr_sequence
2356
+ >>> from sympy.polys.domains import FF
2357
+ >>> F = FF(2)
2358
+ >>> fill = [F(1), F(1), F(0), F(1)]
2359
+ >>> key = [F(1), F(0), F(0), F(1)]
2360
+ >>> lfsr_sequence(key, fill, 10)
2361
+ [1 mod 2, 1 mod 2, 0 mod 2, 1 mod 2, 0 mod 2,
2362
+ 1 mod 2, 1 mod 2, 0 mod 2, 0 mod 2, 1 mod 2]
2363
+
2364
+ References
2365
+ ==========
2366
+
2367
+ .. [G] Solomon Golomb, Shift register sequences, Aegean Park Press,
2368
+ Laguna Hills, Ca, 1967
2369
+
2370
+ """
2371
+ if not isinstance(key, list):
2372
+ raise TypeError("key must be a list")
2373
+ if not isinstance(fill, list):
2374
+ raise TypeError("fill must be a list")
2375
+ p = key[0].mod
2376
+ F = FF(p)
2377
+ s = fill
2378
+ k = len(fill)
2379
+ L = []
2380
+ for i in range(n):
2381
+ s0 = s[:]
2382
+ L.append(s[0])
2383
+ s = s[1:k]
2384
+ x = sum([int(key[i]*s0[i]) for i in range(k)])
2385
+ s.append(F(x))
2386
+ return L # use [x.to_int() for x in L] for int version
2387
+
2388
+
2389
+ def lfsr_autocorrelation(L, P, k):
2390
+ """
2391
+ This function computes the LFSR autocorrelation function.
2392
+
2393
+ Parameters
2394
+ ==========
2395
+
2396
+ L
2397
+ A periodic sequence of elements of `GF(2)`.
2398
+ L must have length larger than P.
2399
+
2400
+ P
2401
+ The period of L.
2402
+
2403
+ k : int
2404
+ An integer `k` (`0 < k < P`).
2405
+
2406
+ Returns
2407
+ =======
2408
+
2409
+ autocorrelation
2410
+ The k-th value of the autocorrelation of the LFSR L.
2411
+
2412
+ Examples
2413
+ ========
2414
+
2415
+ >>> from sympy.crypto.crypto import (
2416
+ ... lfsr_sequence, lfsr_autocorrelation)
2417
+ >>> from sympy.polys.domains import FF
2418
+ >>> F = FF(2)
2419
+ >>> fill = [F(1), F(1), F(0), F(1)]
2420
+ >>> key = [F(1), F(0), F(0), F(1)]
2421
+ >>> s = lfsr_sequence(key, fill, 20)
2422
+ >>> lfsr_autocorrelation(s, 15, 7)
2423
+ -1/15
2424
+ >>> lfsr_autocorrelation(s, 15, 0)
2425
+ 1
2426
+
2427
+ """
2428
+ if not isinstance(L, list):
2429
+ raise TypeError("L (=%s) must be a list" % L)
2430
+ P = int(P)
2431
+ k = int(k)
2432
+ L0 = L[:P] # slices makes a copy
2433
+ L1 = L0 + L0[:k]
2434
+ L2 = [(-1)**(L1[i].to_int() + L1[i + k].to_int()) for i in range(P)]
2435
+ tot = sum(L2)
2436
+ return Rational(tot, P)
2437
+
2438
+
2439
+ def lfsr_connection_polynomial(s):
2440
+ """
2441
+ This function computes the LFSR connection polynomial.
2442
+
2443
+ Parameters
2444
+ ==========
2445
+
2446
+ s
2447
+ A sequence of elements of even length, with entries in a finite
2448
+ field.
2449
+
2450
+ Returns
2451
+ =======
2452
+
2453
+ C(x)
2454
+ The connection polynomial of a minimal LFSR yielding s.
2455
+
2456
+ This implements the algorithm in section 3 of J. L. Massey's
2457
+ article [M]_.
2458
+
2459
+ Examples
2460
+ ========
2461
+
2462
+ >>> from sympy.crypto.crypto import (
2463
+ ... lfsr_sequence, lfsr_connection_polynomial)
2464
+ >>> from sympy.polys.domains import FF
2465
+ >>> F = FF(2)
2466
+ >>> fill = [F(1), F(1), F(0), F(1)]
2467
+ >>> key = [F(1), F(0), F(0), F(1)]
2468
+ >>> s = lfsr_sequence(key, fill, 20)
2469
+ >>> lfsr_connection_polynomial(s)
2470
+ x**4 + x + 1
2471
+ >>> fill = [F(1), F(0), F(0), F(1)]
2472
+ >>> key = [F(1), F(1), F(0), F(1)]
2473
+ >>> s = lfsr_sequence(key, fill, 20)
2474
+ >>> lfsr_connection_polynomial(s)
2475
+ x**3 + 1
2476
+ >>> fill = [F(1), F(0), F(1)]
2477
+ >>> key = [F(1), F(1), F(0)]
2478
+ >>> s = lfsr_sequence(key, fill, 20)
2479
+ >>> lfsr_connection_polynomial(s)
2480
+ x**3 + x**2 + 1
2481
+ >>> fill = [F(1), F(0), F(1)]
2482
+ >>> key = [F(1), F(0), F(1)]
2483
+ >>> s = lfsr_sequence(key, fill, 20)
2484
+ >>> lfsr_connection_polynomial(s)
2485
+ x**3 + x + 1
2486
+
2487
+ References
2488
+ ==========
2489
+
2490
+ .. [M] James L. Massey, "Shift-Register Synthesis and BCH Decoding."
2491
+ IEEE Trans. on Information Theory, vol. 15(1), pp. 122-127,
2492
+ Jan 1969.
2493
+
2494
+ """
2495
+ # Initialization:
2496
+ p = s[0].mod
2497
+ x = Symbol("x")
2498
+ C = 1*x**0
2499
+ B = 1*x**0
2500
+ m = 1
2501
+ b = 1*x**0
2502
+ L = 0
2503
+ N = 0
2504
+ while N < len(s):
2505
+ if L > 0:
2506
+ dC = Poly(C).degree()
2507
+ r = min(L + 1, dC + 1)
2508
+ coeffsC = [C.subs(x, 0)] + [C.coeff(x**i)
2509
+ for i in range(1, dC + 1)]
2510
+ d = (s[N].to_int() + sum([coeffsC[i]*s[N - i].to_int()
2511
+ for i in range(1, r)])) % p
2512
+ if L == 0:
2513
+ d = s[N].to_int()*x**0
2514
+ if d == 0:
2515
+ m += 1
2516
+ N += 1
2517
+ if d > 0:
2518
+ if 2*L > N:
2519
+ C = (C - d*((b**(p - 2)) % p)*x**m*B).expand()
2520
+ m += 1
2521
+ N += 1
2522
+ else:
2523
+ T = C
2524
+ C = (C - d*((b**(p - 2)) % p)*x**m*B).expand()
2525
+ L = N + 1 - L
2526
+ m = 1
2527
+ b = d
2528
+ B = T
2529
+ N += 1
2530
+ dC = Poly(C).degree()
2531
+ coeffsC = [C.subs(x, 0)] + [C.coeff(x**i) for i in range(1, dC + 1)]
2532
+ return sum([coeffsC[i] % p*x**i for i in range(dC + 1)
2533
+ if coeffsC[i] is not None])
2534
+
2535
+
2536
+ #################### ElGamal #############################
2537
+
2538
+
2539
+ def elgamal_private_key(digit=10, seed=None):
2540
+ r"""
2541
+ Return three number tuple as private key.
2542
+
2543
+ Explanation
2544
+ ===========
2545
+
2546
+ Elgamal encryption is based on the mathematical problem
2547
+ called the Discrete Logarithm Problem (DLP). For example,
2548
+
2549
+ `a^{b} \equiv c \pmod p`
2550
+
2551
+ In general, if ``a`` and ``b`` are known, ``ct`` is easily
2552
+ calculated. If ``b`` is unknown, it is hard to use
2553
+ ``a`` and ``ct`` to get ``b``.
2554
+
2555
+ Parameters
2556
+ ==========
2557
+
2558
+ digit : int
2559
+ Minimum number of binary digits for key.
2560
+
2561
+ Returns
2562
+ =======
2563
+
2564
+ tuple : (p, r, d)
2565
+ p = prime number.
2566
+
2567
+ r = primitive root.
2568
+
2569
+ d = random number.
2570
+
2571
+ Notes
2572
+ =====
2573
+
2574
+ For testing purposes, the ``seed`` parameter may be set to control
2575
+ the output of this routine. See sympy.core.random._randrange.
2576
+
2577
+ Examples
2578
+ ========
2579
+
2580
+ >>> from sympy.crypto.crypto import elgamal_private_key
2581
+ >>> from sympy.ntheory import is_primitive_root, isprime
2582
+ >>> a, b, _ = elgamal_private_key()
2583
+ >>> isprime(a)
2584
+ True
2585
+ >>> is_primitive_root(b, a)
2586
+ True
2587
+
2588
+ """
2589
+ randrange = _randrange(seed)
2590
+ p = nextprime(2**digit)
2591
+ return p, primitive_root(p), randrange(2, p)
2592
+
2593
+
2594
+ def elgamal_public_key(key):
2595
+ r"""
2596
+ Return three number tuple as public key.
2597
+
2598
+ Parameters
2599
+ ==========
2600
+
2601
+ key : (p, r, e)
2602
+ Tuple generated by ``elgamal_private_key``.
2603
+
2604
+ Returns
2605
+ =======
2606
+
2607
+ tuple : (p, r, e)
2608
+ `e = r**d \bmod p`
2609
+
2610
+ `d` is a random number in private key.
2611
+
2612
+ Examples
2613
+ ========
2614
+
2615
+ >>> from sympy.crypto.crypto import elgamal_public_key
2616
+ >>> elgamal_public_key((1031, 14, 636))
2617
+ (1031, 14, 212)
2618
+
2619
+ """
2620
+ p, r, e = key
2621
+ return p, r, pow(r, e, p)
2622
+
2623
+
2624
+ def encipher_elgamal(i, key, seed=None):
2625
+ r"""
2626
+ Encrypt message with public key.
2627
+
2628
+ Explanation
2629
+ ===========
2630
+
2631
+ ``i`` is a plaintext message expressed as an integer.
2632
+ ``key`` is public key (p, r, e). In order to encrypt
2633
+ a message, a random number ``a`` in ``range(2, p)``
2634
+ is generated and the encryped message is returned as
2635
+ `c_{1}` and `c_{2}` where:
2636
+
2637
+ `c_{1} \equiv r^{a} \pmod p`
2638
+
2639
+ `c_{2} \equiv m e^{a} \pmod p`
2640
+
2641
+ Parameters
2642
+ ==========
2643
+
2644
+ msg
2645
+ int of encoded message.
2646
+
2647
+ key
2648
+ Public key.
2649
+
2650
+ Returns
2651
+ =======
2652
+
2653
+ tuple : (c1, c2)
2654
+ Encipher into two number.
2655
+
2656
+ Notes
2657
+ =====
2658
+
2659
+ For testing purposes, the ``seed`` parameter may be set to control
2660
+ the output of this routine. See sympy.core.random._randrange.
2661
+
2662
+ Examples
2663
+ ========
2664
+
2665
+ >>> from sympy.crypto.crypto import encipher_elgamal, elgamal_private_key, elgamal_public_key
2666
+ >>> pri = elgamal_private_key(5, seed=[3]); pri
2667
+ (37, 2, 3)
2668
+ >>> pub = elgamal_public_key(pri); pub
2669
+ (37, 2, 8)
2670
+ >>> msg = 36
2671
+ >>> encipher_elgamal(msg, pub, seed=[3])
2672
+ (8, 6)
2673
+
2674
+ """
2675
+ p, r, e = key
2676
+ if i < 0 or i >= p:
2677
+ raise ValueError(
2678
+ 'Message (%s) should be in range(%s)' % (i, p))
2679
+ randrange = _randrange(seed)
2680
+ a = randrange(2, p)
2681
+ return pow(r, a, p), i*pow(e, a, p) % p
2682
+
2683
+
2684
+ def decipher_elgamal(msg, key):
2685
+ r"""
2686
+ Decrypt message with private key.
2687
+
2688
+ `msg = (c_{1}, c_{2})`
2689
+
2690
+ `key = (p, r, d)`
2691
+
2692
+ According to extended Eucliden theorem,
2693
+ `u c_{1}^{d} + p n = 1`
2694
+
2695
+ `u \equiv 1/{{c_{1}}^d} \pmod p`
2696
+
2697
+ `u c_{2} \equiv \frac{1}{c_{1}^d} c_{2} \equiv \frac{1}{r^{ad}} c_{2} \pmod p`
2698
+
2699
+ `\frac{1}{r^{ad}} m e^a \equiv \frac{1}{r^{ad}} m {r^{d a}} \equiv m \pmod p`
2700
+
2701
+ Examples
2702
+ ========
2703
+
2704
+ >>> from sympy.crypto.crypto import decipher_elgamal
2705
+ >>> from sympy.crypto.crypto import encipher_elgamal
2706
+ >>> from sympy.crypto.crypto import elgamal_private_key
2707
+ >>> from sympy.crypto.crypto import elgamal_public_key
2708
+
2709
+ >>> pri = elgamal_private_key(5, seed=[3])
2710
+ >>> pub = elgamal_public_key(pri); pub
2711
+ (37, 2, 8)
2712
+ >>> msg = 17
2713
+ >>> decipher_elgamal(encipher_elgamal(msg, pub), pri) == msg
2714
+ True
2715
+
2716
+ """
2717
+ p, _, d = key
2718
+ c1, c2 = msg
2719
+ u = igcdex(c1**d, p)[0]
2720
+ return u * c2 % p
2721
+
2722
+
2723
+ ################ Diffie-Hellman Key Exchange #########################
2724
+
2725
+ def dh_private_key(digit=10, seed=None):
2726
+ r"""
2727
+ Return three integer tuple as private key.
2728
+
2729
+ Explanation
2730
+ ===========
2731
+
2732
+ Diffie-Hellman key exchange is based on the mathematical problem
2733
+ called the Discrete Logarithm Problem (see ElGamal).
2734
+
2735
+ Diffie-Hellman key exchange is divided into the following steps:
2736
+
2737
+ * Alice and Bob agree on a base that consist of a prime ``p``
2738
+ and a primitive root of ``p`` called ``g``
2739
+ * Alice choses a number ``a`` and Bob choses a number ``b`` where
2740
+ ``a`` and ``b`` are random numbers in range `[2, p)`. These are
2741
+ their private keys.
2742
+ * Alice then publicly sends Bob `g^{a} \pmod p` while Bob sends
2743
+ Alice `g^{b} \pmod p`
2744
+ * They both raise the received value to their secretly chosen
2745
+ number (``a`` or ``b``) and now have both as their shared key
2746
+ `g^{ab} \pmod p`
2747
+
2748
+ Parameters
2749
+ ==========
2750
+
2751
+ digit
2752
+ Minimum number of binary digits required in key.
2753
+
2754
+ Returns
2755
+ =======
2756
+
2757
+ tuple : (p, g, a)
2758
+ p = prime number.
2759
+
2760
+ g = primitive root of p.
2761
+
2762
+ a = random number from 2 through p - 1.
2763
+
2764
+ Notes
2765
+ =====
2766
+
2767
+ For testing purposes, the ``seed`` parameter may be set to control
2768
+ the output of this routine. See sympy.core.random._randrange.
2769
+
2770
+ Examples
2771
+ ========
2772
+
2773
+ >>> from sympy.crypto.crypto import dh_private_key
2774
+ >>> from sympy.ntheory import isprime, is_primitive_root
2775
+ >>> p, g, _ = dh_private_key()
2776
+ >>> isprime(p)
2777
+ True
2778
+ >>> is_primitive_root(g, p)
2779
+ True
2780
+ >>> p, g, _ = dh_private_key(5)
2781
+ >>> isprime(p)
2782
+ True
2783
+ >>> is_primitive_root(g, p)
2784
+ True
2785
+
2786
+ """
2787
+ p = nextprime(2**digit)
2788
+ g = primitive_root(p)
2789
+ randrange = _randrange(seed)
2790
+ a = randrange(2, p)
2791
+ return p, g, a
2792
+
2793
+
2794
+ def dh_public_key(key):
2795
+ r"""
2796
+ Return three number tuple as public key.
2797
+
2798
+ This is the tuple that Alice sends to Bob.
2799
+
2800
+ Parameters
2801
+ ==========
2802
+
2803
+ key : (p, g, a)
2804
+ A tuple generated by ``dh_private_key``.
2805
+
2806
+ Returns
2807
+ =======
2808
+
2809
+ tuple : int, int, int
2810
+ A tuple of `(p, g, g^a \mod p)` with `p`, `g` and `a` given as
2811
+ parameters.s
2812
+
2813
+ Examples
2814
+ ========
2815
+
2816
+ >>> from sympy.crypto.crypto import dh_private_key, dh_public_key
2817
+ >>> p, g, a = dh_private_key();
2818
+ >>> _p, _g, x = dh_public_key((p, g, a))
2819
+ >>> p == _p and g == _g
2820
+ True
2821
+ >>> x == pow(g, a, p)
2822
+ True
2823
+
2824
+ """
2825
+ p, g, a = key
2826
+ return p, g, pow(g, a, p)
2827
+
2828
+
2829
+ def dh_shared_key(key, b):
2830
+ """
2831
+ Return an integer that is the shared key.
2832
+
2833
+ This is what Bob and Alice can both calculate using the public
2834
+ keys they received from each other and their private keys.
2835
+
2836
+ Parameters
2837
+ ==========
2838
+
2839
+ key : (p, g, x)
2840
+ Tuple `(p, g, x)` generated by ``dh_public_key``.
2841
+
2842
+ b
2843
+ Random number in the range of `2` to `p - 1`
2844
+ (Chosen by second key exchange member (Bob)).
2845
+
2846
+ Returns
2847
+ =======
2848
+
2849
+ int
2850
+ A shared key.
2851
+
2852
+ Examples
2853
+ ========
2854
+
2855
+ >>> from sympy.crypto.crypto import (
2856
+ ... dh_private_key, dh_public_key, dh_shared_key)
2857
+ >>> prk = dh_private_key();
2858
+ >>> p, g, x = dh_public_key(prk);
2859
+ >>> sk = dh_shared_key((p, g, x), 1000)
2860
+ >>> sk == pow(x, 1000, p)
2861
+ True
2862
+
2863
+ """
2864
+ p, _, x = key
2865
+ if 1 >= b or b >= p:
2866
+ raise ValueError(filldedent('''
2867
+ Value of b should be greater 1 and less
2868
+ than prime %s.''' % p))
2869
+
2870
+ return pow(x, b, p)
2871
+
2872
+
2873
+ ################ Goldwasser-Micali Encryption #########################
2874
+
2875
+
2876
+ def _legendre(a, p):
2877
+ """
2878
+ Returns the legendre symbol of a and p
2879
+ assuming that p is a prime.
2880
+
2881
+ i.e. 1 if a is a quadratic residue mod p
2882
+ -1 if a is not a quadratic residue mod p
2883
+ 0 if a is divisible by p
2884
+
2885
+ Parameters
2886
+ ==========
2887
+
2888
+ a : int
2889
+ The number to test.
2890
+
2891
+ p : prime
2892
+ The prime to test ``a`` against.
2893
+
2894
+ Returns
2895
+ =======
2896
+
2897
+ int
2898
+ Legendre symbol (a / p).
2899
+
2900
+ """
2901
+ sig = pow(a, (p - 1)//2, p)
2902
+ if sig == 1:
2903
+ return 1
2904
+ elif sig == 0:
2905
+ return 0
2906
+ else:
2907
+ return -1
2908
+
2909
+
2910
+ def _random_coprime_stream(n, seed=None):
2911
+ randrange = _randrange(seed)
2912
+ while True:
2913
+ y = randrange(n)
2914
+ if gcd(y, n) == 1:
2915
+ yield y
2916
+
2917
+
2918
+ def gm_private_key(p, q, a=None):
2919
+ r"""
2920
+ Check if ``p`` and ``q`` can be used as private keys for
2921
+ the Goldwasser-Micali encryption. The method works
2922
+ roughly as follows.
2923
+
2924
+ Explanation
2925
+ ===========
2926
+
2927
+ #. Pick two large primes $p$ and $q$.
2928
+ #. Call their product $N$.
2929
+ #. Given a message as an integer $i$, write $i$ in its bit representation $b_0, \dots, b_n$.
2930
+ #. For each $k$,
2931
+
2932
+ if $b_k = 0$:
2933
+ let $a_k$ be a random square
2934
+ (quadratic residue) modulo $p q$
2935
+ such that ``jacobi_symbol(a, p*q) = 1``
2936
+ if $b_k = 1$:
2937
+ let $a_k$ be a random non-square
2938
+ (non-quadratic residue) modulo $p q$
2939
+ such that ``jacobi_symbol(a, p*q) = 1``
2940
+
2941
+ returns $\left[a_1, a_2, \dots\right]$
2942
+
2943
+ $b_k$ can be recovered by checking whether or not
2944
+ $a_k$ is a residue. And from the $b_k$'s, the message
2945
+ can be reconstructed.
2946
+
2947
+ The idea is that, while ``jacobi_symbol(a, p*q)``
2948
+ can be easily computed (and when it is equal to $-1$ will
2949
+ tell you that $a$ is not a square mod $p q$), quadratic
2950
+ residuosity modulo a composite number is hard to compute
2951
+ without knowing its factorization.
2952
+
2953
+ Moreover, approximately half the numbers coprime to $p q$ have
2954
+ :func:`~.jacobi_symbol` equal to $1$ . And among those, approximately half
2955
+ are residues and approximately half are not. This maximizes the
2956
+ entropy of the code.
2957
+
2958
+ Parameters
2959
+ ==========
2960
+
2961
+ p, q, a
2962
+ Initialization variables.
2963
+
2964
+ Returns
2965
+ =======
2966
+
2967
+ tuple : (p, q)
2968
+ The input value ``p`` and ``q``.
2969
+
2970
+ Raises
2971
+ ======
2972
+
2973
+ ValueError
2974
+ If ``p`` and ``q`` are not distinct odd primes.
2975
+
2976
+ """
2977
+ if p == q:
2978
+ raise ValueError("expected distinct primes, "
2979
+ "got two copies of %i" % p)
2980
+ elif not isprime(p) or not isprime(q):
2981
+ raise ValueError("first two arguments must be prime, "
2982
+ "got %i of %i" % (p, q))
2983
+ elif p == 2 or q == 2:
2984
+ raise ValueError("first two arguments must not be even, "
2985
+ "got %i of %i" % (p, q))
2986
+ return p, q
2987
+
2988
+
2989
+ def gm_public_key(p, q, a=None, seed=None):
2990
+ """
2991
+ Compute public keys for ``p`` and ``q``.
2992
+ Note that in Goldwasser-Micali Encryption,
2993
+ public keys are randomly selected.
2994
+
2995
+ Parameters
2996
+ ==========
2997
+
2998
+ p, q, a : int, int, int
2999
+ Initialization variables.
3000
+
3001
+ Returns
3002
+ =======
3003
+
3004
+ tuple : (a, N)
3005
+ ``a`` is the input ``a`` if it is not ``None`` otherwise
3006
+ some random integer coprime to ``p`` and ``q``.
3007
+
3008
+ ``N`` is the product of ``p`` and ``q``.
3009
+
3010
+ """
3011
+
3012
+ p, q = gm_private_key(p, q)
3013
+ N = p * q
3014
+
3015
+ if a is None:
3016
+ randrange = _randrange(seed)
3017
+ while True:
3018
+ a = randrange(N)
3019
+ if _legendre(a, p) == _legendre(a, q) == -1:
3020
+ break
3021
+ else:
3022
+ if _legendre(a, p) != -1 or _legendre(a, q) != -1:
3023
+ return False
3024
+ return (a, N)
3025
+
3026
+
3027
+ def encipher_gm(i, key, seed=None):
3028
+ """
3029
+ Encrypt integer 'i' using public_key 'key'
3030
+ Note that gm uses random encryption.
3031
+
3032
+ Parameters
3033
+ ==========
3034
+
3035
+ i : int
3036
+ The message to encrypt.
3037
+
3038
+ key : (a, N)
3039
+ The public key.
3040
+
3041
+ Returns
3042
+ =======
3043
+
3044
+ list : list of int
3045
+ The randomized encrypted message.
3046
+
3047
+ """
3048
+ if i < 0:
3049
+ raise ValueError(
3050
+ "message must be a non-negative "
3051
+ "integer: got %d instead" % i)
3052
+ a, N = key
3053
+ bits = []
3054
+ while i > 0:
3055
+ bits.append(i % 2)
3056
+ i //= 2
3057
+
3058
+ gen = _random_coprime_stream(N, seed)
3059
+ rev = reversed(bits)
3060
+ encode = lambda b: next(gen)**2*pow(a, b) % N
3061
+ return [ encode(b) for b in rev ]
3062
+
3063
+
3064
+
3065
+ def decipher_gm(message, key):
3066
+ """
3067
+ Decrypt message 'message' using public_key 'key'.
3068
+
3069
+ Parameters
3070
+ ==========
3071
+
3072
+ message : list of int
3073
+ The randomized encrypted message.
3074
+
3075
+ key : (p, q)
3076
+ The private key.
3077
+
3078
+ Returns
3079
+ =======
3080
+
3081
+ int
3082
+ The encrypted message.
3083
+
3084
+ """
3085
+ p, q = key
3086
+ res = lambda m, p: _legendre(m, p) > 0
3087
+ bits = [res(m, p) * res(m, q) for m in message]
3088
+ m = 0
3089
+ for b in bits:
3090
+ m <<= 1
3091
+ m += not b
3092
+ return m
3093
+
3094
+
3095
+
3096
+ ########### RailFence Cipher #############
3097
+
3098
+ def encipher_railfence(message,rails):
3099
+ """
3100
+ Performs Railfence Encryption on plaintext and returns ciphertext
3101
+
3102
+ Examples
3103
+ ========
3104
+
3105
+ >>> from sympy.crypto.crypto import encipher_railfence
3106
+ >>> message = "hello world"
3107
+ >>> encipher_railfence(message,3)
3108
+ 'horel ollwd'
3109
+
3110
+ Parameters
3111
+ ==========
3112
+
3113
+ message : string, the message to encrypt.
3114
+ rails : int, the number of rails.
3115
+
3116
+ Returns
3117
+ =======
3118
+
3119
+ The Encrypted string message.
3120
+
3121
+ References
3122
+ ==========
3123
+ .. [1] https://en.wikipedia.org/wiki/Rail_fence_cipher
3124
+
3125
+ """
3126
+ r = list(range(rails))
3127
+ p = cycle(r + r[-2:0:-1])
3128
+ return ''.join(sorted(message, key=lambda i: next(p)))
3129
+
3130
+
3131
+ def decipher_railfence(ciphertext,rails):
3132
+ """
3133
+ Decrypt the message using the given rails
3134
+
3135
+ Examples
3136
+ ========
3137
+
3138
+ >>> from sympy.crypto.crypto import decipher_railfence
3139
+ >>> decipher_railfence("horel ollwd",3)
3140
+ 'hello world'
3141
+
3142
+ Parameters
3143
+ ==========
3144
+
3145
+ message : string, the message to encrypt.
3146
+ rails : int, the number of rails.
3147
+
3148
+ Returns
3149
+ =======
3150
+
3151
+ The Decrypted string message.
3152
+
3153
+ """
3154
+ r = list(range(rails))
3155
+ p = cycle(r + r[-2:0:-1])
3156
+
3157
+ idx = sorted(range(len(ciphertext)), key=lambda i: next(p))
3158
+ res = [''] * len(ciphertext)
3159
+ for i, c in zip(idx, ciphertext):
3160
+ res[i] = c
3161
+ return ''.join(res)
3162
+
3163
+
3164
+ ################ Blum-Goldwasser cryptosystem #########################
3165
+
3166
+ def bg_private_key(p, q):
3167
+ """
3168
+ Check if p and q can be used as private keys for
3169
+ the Blum-Goldwasser cryptosystem.
3170
+
3171
+ Explanation
3172
+ ===========
3173
+
3174
+ The three necessary checks for p and q to pass
3175
+ so that they can be used as private keys:
3176
+
3177
+ 1. p and q must both be prime
3178
+ 2. p and q must be distinct
3179
+ 3. p and q must be congruent to 3 mod 4
3180
+
3181
+ Parameters
3182
+ ==========
3183
+
3184
+ p, q
3185
+ The keys to be checked.
3186
+
3187
+ Returns
3188
+ =======
3189
+
3190
+ p, q
3191
+ Input values.
3192
+
3193
+ Raises
3194
+ ======
3195
+
3196
+ ValueError
3197
+ If p and q do not pass the above conditions.
3198
+
3199
+ """
3200
+
3201
+ if not isprime(p) or not isprime(q):
3202
+ raise ValueError("the two arguments must be prime, "
3203
+ "got %i and %i" %(p, q))
3204
+ elif p == q:
3205
+ raise ValueError("the two arguments must be distinct, "
3206
+ "got two copies of %i. " %p)
3207
+ elif (p - 3) % 4 != 0 or (q - 3) % 4 != 0:
3208
+ raise ValueError("the two arguments must be congruent to 3 mod 4, "
3209
+ "got %i and %i" %(p, q))
3210
+ return p, q
3211
+
3212
+ def bg_public_key(p, q):
3213
+ """
3214
+ Calculates public keys from private keys.
3215
+
3216
+ Explanation
3217
+ ===========
3218
+
3219
+ The function first checks the validity of
3220
+ private keys passed as arguments and
3221
+ then returns their product.
3222
+
3223
+ Parameters
3224
+ ==========
3225
+
3226
+ p, q
3227
+ The private keys.
3228
+
3229
+ Returns
3230
+ =======
3231
+
3232
+ N
3233
+ The public key.
3234
+
3235
+ """
3236
+ p, q = bg_private_key(p, q)
3237
+ N = p * q
3238
+ return N
3239
+
3240
+ def encipher_bg(i, key, seed=None):
3241
+ """
3242
+ Encrypts the message using public key and seed.
3243
+
3244
+ Explanation
3245
+ ===========
3246
+
3247
+ ALGORITHM:
3248
+ 1. Encodes i as a string of L bits, m.
3249
+ 2. Select a random element r, where 1 < r < key, and computes
3250
+ x = r^2 mod key.
3251
+ 3. Use BBS pseudo-random number generator to generate L random bits, b,
3252
+ using the initial seed as x.
3253
+ 4. Encrypted message, c_i = m_i XOR b_i, 1 <= i <= L.
3254
+ 5. x_L = x^(2^L) mod key.
3255
+ 6. Return (c, x_L)
3256
+
3257
+ Parameters
3258
+ ==========
3259
+
3260
+ i
3261
+ Message, a non-negative integer
3262
+
3263
+ key
3264
+ The public key
3265
+
3266
+ Returns
3267
+ =======
3268
+
3269
+ Tuple
3270
+ (encrypted_message, x_L)
3271
+
3272
+ Raises
3273
+ ======
3274
+
3275
+ ValueError
3276
+ If i is negative.
3277
+
3278
+ """
3279
+
3280
+ if i < 0:
3281
+ raise ValueError(
3282
+ "message must be a non-negative "
3283
+ "integer: got %d instead" % i)
3284
+
3285
+ enc_msg = []
3286
+ while i > 0:
3287
+ enc_msg.append(i % 2)
3288
+ i //= 2
3289
+ enc_msg.reverse()
3290
+ L = len(enc_msg)
3291
+
3292
+ r = _randint(seed)(2, key - 1)
3293
+ x = r**2 % key
3294
+ x_L = pow(int(x), int(2**L), int(key))
3295
+
3296
+ rand_bits = []
3297
+ for _ in range(L):
3298
+ rand_bits.append(x % 2)
3299
+ x = x**2 % key
3300
+
3301
+ encrypt_msg = [m ^ b for (m, b) in zip(enc_msg, rand_bits)]
3302
+
3303
+ return (encrypt_msg, x_L)
3304
+
3305
+ def decipher_bg(message, key):
3306
+ """
3307
+ Decrypts the message using private keys.
3308
+
3309
+ Explanation
3310
+ ===========
3311
+
3312
+ ALGORITHM:
3313
+ 1. Let, c be the encrypted message, y the second number received,
3314
+ and p and q be the private keys.
3315
+ 2. Compute, r_p = y^((p+1)/4 ^ L) mod p and
3316
+ r_q = y^((q+1)/4 ^ L) mod q.
3317
+ 3. Compute x_0 = (q(q^-1 mod p)r_p + p(p^-1 mod q)r_q) mod N.
3318
+ 4. From, recompute the bits using the BBS generator, as in the
3319
+ encryption algorithm.
3320
+ 5. Compute original message by XORing c and b.
3321
+
3322
+ Parameters
3323
+ ==========
3324
+
3325
+ message
3326
+ Tuple of encrypted message and a non-negative integer.
3327
+
3328
+ key
3329
+ Tuple of private keys.
3330
+
3331
+ Returns
3332
+ =======
3333
+
3334
+ orig_msg
3335
+ The original message
3336
+
3337
+ """
3338
+
3339
+ p, q = key
3340
+ encrypt_msg, y = message
3341
+ public_key = p * q
3342
+ L = len(encrypt_msg)
3343
+ p_t = ((p + 1)/4)**L
3344
+ q_t = ((q + 1)/4)**L
3345
+ r_p = pow(int(y), int(p_t), int(p))
3346
+ r_q = pow(int(y), int(q_t), int(q))
3347
+
3348
+ x = (q * mod_inverse(q, p) * r_p + p * mod_inverse(p, q) * r_q) % public_key
3349
+
3350
+ orig_bits = []
3351
+ for _ in range(L):
3352
+ orig_bits.append(x % 2)
3353
+ x = x**2 % public_key
3354
+
3355
+ orig_msg = 0
3356
+ for (m, b) in zip(encrypt_msg, orig_bits):
3357
+ orig_msg = orig_msg * 2
3358
+ orig_msg += (m ^ b)
3359
+
3360
+ return orig_msg
venv/lib/python3.10/site-packages/sympy/crypto/tests/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/sympy/crypto/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (186 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/crypto/tests/__pycache__/test_crypto.cpython-310.pyc ADDED
Binary file (21 kB). View file
 
venv/lib/python3.10/site-packages/sympy/crypto/tests/test_crypto.py ADDED
@@ -0,0 +1,562 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import symbols
2
+ from sympy.crypto.crypto import (cycle_list,
3
+ encipher_shift, encipher_affine, encipher_substitution,
4
+ check_and_join, encipher_vigenere, decipher_vigenere,
5
+ encipher_hill, decipher_hill, encipher_bifid5, encipher_bifid6,
6
+ bifid5_square, bifid6_square, bifid5, bifid6,
7
+ decipher_bifid5, decipher_bifid6, encipher_kid_rsa,
8
+ decipher_kid_rsa, kid_rsa_private_key, kid_rsa_public_key,
9
+ decipher_rsa, rsa_private_key, rsa_public_key, encipher_rsa,
10
+ lfsr_connection_polynomial, lfsr_autocorrelation, lfsr_sequence,
11
+ encode_morse, decode_morse, elgamal_private_key, elgamal_public_key,
12
+ encipher_elgamal, decipher_elgamal, dh_private_key, dh_public_key,
13
+ dh_shared_key, decipher_shift, decipher_affine, encipher_bifid,
14
+ decipher_bifid, bifid_square, padded_key, uniq, decipher_gm,
15
+ encipher_gm, gm_public_key, gm_private_key, encipher_bg, decipher_bg,
16
+ bg_private_key, bg_public_key, encipher_rot13, decipher_rot13,
17
+ encipher_atbash, decipher_atbash, NonInvertibleCipherWarning,
18
+ encipher_railfence, decipher_railfence)
19
+ from sympy.matrices import Matrix
20
+ from sympy.ntheory import isprime, is_primitive_root
21
+ from sympy.polys.domains import FF
22
+
23
+ from sympy.testing.pytest import raises, warns
24
+
25
+ from sympy.core.random import randrange
26
+
27
+ def test_encipher_railfence():
28
+ assert encipher_railfence("hello world",2) == "hlowrdel ol"
29
+ assert encipher_railfence("hello world",3) == "horel ollwd"
30
+ assert encipher_railfence("hello world",4) == "hwe olordll"
31
+
32
+ def test_decipher_railfence():
33
+ assert decipher_railfence("hlowrdel ol",2) == "hello world"
34
+ assert decipher_railfence("horel ollwd",3) == "hello world"
35
+ assert decipher_railfence("hwe olordll",4) == "hello world"
36
+
37
+
38
+ def test_cycle_list():
39
+ assert cycle_list(3, 4) == [3, 0, 1, 2]
40
+ assert cycle_list(-1, 4) == [3, 0, 1, 2]
41
+ assert cycle_list(1, 4) == [1, 2, 3, 0]
42
+
43
+
44
+ def test_encipher_shift():
45
+ assert encipher_shift("ABC", 0) == "ABC"
46
+ assert encipher_shift("ABC", 1) == "BCD"
47
+ assert encipher_shift("ABC", -1) == "ZAB"
48
+ assert decipher_shift("ZAB", -1) == "ABC"
49
+
50
+ def test_encipher_rot13():
51
+ assert encipher_rot13("ABC") == "NOP"
52
+ assert encipher_rot13("NOP") == "ABC"
53
+ assert decipher_rot13("ABC") == "NOP"
54
+ assert decipher_rot13("NOP") == "ABC"
55
+
56
+
57
+ def test_encipher_affine():
58
+ assert encipher_affine("ABC", (1, 0)) == "ABC"
59
+ assert encipher_affine("ABC", (1, 1)) == "BCD"
60
+ assert encipher_affine("ABC", (-1, 0)) == "AZY"
61
+ assert encipher_affine("ABC", (-1, 1), symbols="ABCD") == "BAD"
62
+ assert encipher_affine("123", (-1, 1), symbols="1234") == "214"
63
+ assert encipher_affine("ABC", (3, 16)) == "QTW"
64
+ assert decipher_affine("QTW", (3, 16)) == "ABC"
65
+
66
+ def test_encipher_atbash():
67
+ assert encipher_atbash("ABC") == "ZYX"
68
+ assert encipher_atbash("ZYX") == "ABC"
69
+ assert decipher_atbash("ABC") == "ZYX"
70
+ assert decipher_atbash("ZYX") == "ABC"
71
+
72
+ def test_encipher_substitution():
73
+ assert encipher_substitution("ABC", "BAC", "ABC") == "BAC"
74
+ assert encipher_substitution("123", "1243", "1234") == "124"
75
+
76
+
77
+ def test_check_and_join():
78
+ assert check_and_join("abc") == "abc"
79
+ assert check_and_join(uniq("aaabc")) == "abc"
80
+ assert check_and_join("ab c".split()) == "abc"
81
+ assert check_and_join("abc", "a", filter=True) == "a"
82
+ raises(ValueError, lambda: check_and_join('ab', 'a'))
83
+
84
+
85
+ def test_encipher_vigenere():
86
+ assert encipher_vigenere("ABC", "ABC") == "ACE"
87
+ assert encipher_vigenere("ABC", "ABC", symbols="ABCD") == "ACA"
88
+ assert encipher_vigenere("ABC", "AB", symbols="ABCD") == "ACC"
89
+ assert encipher_vigenere("AB", "ABC", symbols="ABCD") == "AC"
90
+ assert encipher_vigenere("A", "ABC", symbols="ABCD") == "A"
91
+
92
+
93
+ def test_decipher_vigenere():
94
+ assert decipher_vigenere("ABC", "ABC") == "AAA"
95
+ assert decipher_vigenere("ABC", "ABC", symbols="ABCD") == "AAA"
96
+ assert decipher_vigenere("ABC", "AB", symbols="ABCD") == "AAC"
97
+ assert decipher_vigenere("AB", "ABC", symbols="ABCD") == "AA"
98
+ assert decipher_vigenere("A", "ABC", symbols="ABCD") == "A"
99
+
100
+
101
+ def test_encipher_hill():
102
+ A = Matrix(2, 2, [1, 2, 3, 5])
103
+ assert encipher_hill("ABCD", A) == "CFIV"
104
+ A = Matrix(2, 2, [1, 0, 0, 1])
105
+ assert encipher_hill("ABCD", A) == "ABCD"
106
+ assert encipher_hill("ABCD", A, symbols="ABCD") == "ABCD"
107
+ A = Matrix(2, 2, [1, 2, 3, 5])
108
+ assert encipher_hill("ABCD", A, symbols="ABCD") == "CBAB"
109
+ assert encipher_hill("AB", A, symbols="ABCD") == "CB"
110
+ # message length, n, does not need to be a multiple of k;
111
+ # it is padded
112
+ assert encipher_hill("ABA", A) == "CFGC"
113
+ assert encipher_hill("ABA", A, pad="Z") == "CFYV"
114
+
115
+
116
+ def test_decipher_hill():
117
+ A = Matrix(2, 2, [1, 2, 3, 5])
118
+ assert decipher_hill("CFIV", A) == "ABCD"
119
+ A = Matrix(2, 2, [1, 0, 0, 1])
120
+ assert decipher_hill("ABCD", A) == "ABCD"
121
+ assert decipher_hill("ABCD", A, symbols="ABCD") == "ABCD"
122
+ A = Matrix(2, 2, [1, 2, 3, 5])
123
+ assert decipher_hill("CBAB", A, symbols="ABCD") == "ABCD"
124
+ assert decipher_hill("CB", A, symbols="ABCD") == "AB"
125
+ # n does not need to be a multiple of k
126
+ assert decipher_hill("CFA", A) == "ABAA"
127
+
128
+
129
+ def test_encipher_bifid5():
130
+ assert encipher_bifid5("AB", "AB") == "AB"
131
+ assert encipher_bifid5("AB", "CD") == "CO"
132
+ assert encipher_bifid5("ab", "c") == "CH"
133
+ assert encipher_bifid5("a bc", "b") == "BAC"
134
+
135
+
136
+ def test_bifid5_square():
137
+ A = bifid5
138
+ f = lambda i, j: symbols(A[5*i + j])
139
+ M = Matrix(5, 5, f)
140
+ assert bifid5_square("") == M
141
+
142
+
143
+ def test_decipher_bifid5():
144
+ assert decipher_bifid5("AB", "AB") == "AB"
145
+ assert decipher_bifid5("CO", "CD") == "AB"
146
+ assert decipher_bifid5("ch", "c") == "AB"
147
+ assert decipher_bifid5("b ac", "b") == "ABC"
148
+
149
+
150
+ def test_encipher_bifid6():
151
+ assert encipher_bifid6("AB", "AB") == "AB"
152
+ assert encipher_bifid6("AB", "CD") == "CP"
153
+ assert encipher_bifid6("ab", "c") == "CI"
154
+ assert encipher_bifid6("a bc", "b") == "BAC"
155
+
156
+
157
+ def test_decipher_bifid6():
158
+ assert decipher_bifid6("AB", "AB") == "AB"
159
+ assert decipher_bifid6("CP", "CD") == "AB"
160
+ assert decipher_bifid6("ci", "c") == "AB"
161
+ assert decipher_bifid6("b ac", "b") == "ABC"
162
+
163
+
164
+ def test_bifid6_square():
165
+ A = bifid6
166
+ f = lambda i, j: symbols(A[6*i + j])
167
+ M = Matrix(6, 6, f)
168
+ assert bifid6_square("") == M
169
+
170
+
171
+ def test_rsa_public_key():
172
+ assert rsa_public_key(2, 3, 1) == (6, 1)
173
+ assert rsa_public_key(5, 3, 3) == (15, 3)
174
+
175
+ with warns(NonInvertibleCipherWarning):
176
+ assert rsa_public_key(2, 2, 1) == (4, 1)
177
+ assert rsa_public_key(8, 8, 8) is False
178
+
179
+
180
+ def test_rsa_private_key():
181
+ assert rsa_private_key(2, 3, 1) == (6, 1)
182
+ assert rsa_private_key(5, 3, 3) == (15, 3)
183
+ assert rsa_private_key(23,29,5) == (667,493)
184
+
185
+ with warns(NonInvertibleCipherWarning):
186
+ assert rsa_private_key(2, 2, 1) == (4, 1)
187
+ assert rsa_private_key(8, 8, 8) is False
188
+
189
+
190
+ def test_rsa_large_key():
191
+ # Sample from
192
+ # http://www.herongyang.com/Cryptography/JCE-Public-Key-RSA-Private-Public-Key-Pair-Sample.html
193
+ p = int('101565610013301240713207239558950144682174355406589305284428666'\
194
+ '903702505233009')
195
+ q = int('894687191887545488935455605955948413812376003053143521429242133'\
196
+ '12069293984003')
197
+ e = int('65537')
198
+ d = int('893650581832704239530398858744759129594796235440844479456143566'\
199
+ '6999402846577625762582824202269399672579058991442587406384754958587'\
200
+ '400493169361356902030209')
201
+ assert rsa_public_key(p, q, e) == (p*q, e)
202
+ assert rsa_private_key(p, q, e) == (p*q, d)
203
+
204
+
205
+ def test_encipher_rsa():
206
+ puk = rsa_public_key(2, 3, 1)
207
+ assert encipher_rsa(2, puk) == 2
208
+ puk = rsa_public_key(5, 3, 3)
209
+ assert encipher_rsa(2, puk) == 8
210
+
211
+ with warns(NonInvertibleCipherWarning):
212
+ puk = rsa_public_key(2, 2, 1)
213
+ assert encipher_rsa(2, puk) == 2
214
+
215
+
216
+ def test_decipher_rsa():
217
+ prk = rsa_private_key(2, 3, 1)
218
+ assert decipher_rsa(2, prk) == 2
219
+ prk = rsa_private_key(5, 3, 3)
220
+ assert decipher_rsa(8, prk) == 2
221
+
222
+ with warns(NonInvertibleCipherWarning):
223
+ prk = rsa_private_key(2, 2, 1)
224
+ assert decipher_rsa(2, prk) == 2
225
+
226
+
227
+ def test_mutltiprime_rsa_full_example():
228
+ # Test example from
229
+ # https://iopscience.iop.org/article/10.1088/1742-6596/995/1/012030
230
+ puk = rsa_public_key(2, 3, 5, 7, 11, 13, 7)
231
+ prk = rsa_private_key(2, 3, 5, 7, 11, 13, 7)
232
+ assert puk == (30030, 7)
233
+ assert prk == (30030, 823)
234
+
235
+ msg = 10
236
+ encrypted = encipher_rsa(2 * msg - 15, puk)
237
+ assert encrypted == 18065
238
+ decrypted = (decipher_rsa(encrypted, prk) + 15) / 2
239
+ assert decrypted == msg
240
+
241
+ # Test example from
242
+ # https://www.scirp.org/pdf/JCC_2018032215502008.pdf
243
+ puk1 = rsa_public_key(53, 41, 43, 47, 41)
244
+ prk1 = rsa_private_key(53, 41, 43, 47, 41)
245
+ puk2 = rsa_public_key(53, 41, 43, 47, 97)
246
+ prk2 = rsa_private_key(53, 41, 43, 47, 97)
247
+
248
+ assert puk1 == (4391633, 41)
249
+ assert prk1 == (4391633, 294041)
250
+ assert puk2 == (4391633, 97)
251
+ assert prk2 == (4391633, 455713)
252
+
253
+ msg = 12321
254
+ encrypted = encipher_rsa(encipher_rsa(msg, puk1), puk2)
255
+ assert encrypted == 1081588
256
+ decrypted = decipher_rsa(decipher_rsa(encrypted, prk2), prk1)
257
+ assert decrypted == msg
258
+
259
+
260
+ def test_rsa_crt_extreme():
261
+ p = int(
262
+ '10177157607154245068023861503693082120906487143725062283406501' \
263
+ '54082258226204046999838297167140821364638180697194879500245557' \
264
+ '65445186962893346463841419427008800341257468600224049986260471' \
265
+ '92257248163014468841725476918639415726709736077813632961290911' \
266
+ '0256421232977833028677441206049309220354796014376698325101693')
267
+
268
+ q = int(
269
+ '28752342353095132872290181526607275886182793241660805077850801' \
270
+ '75689512797754286972952273553128181861830576836289738668745250' \
271
+ '34028199691128870676414118458442900035778874482624765513861643' \
272
+ '27966696316822188398336199002306588703902894100476186823849595' \
273
+ '103239410527279605442148285816149368667083114802852804976893')
274
+
275
+ r = int(
276
+ '17698229259868825776879500736350186838850961935956310134378261' \
277
+ '89771862186717463067541369694816245225291921138038800171125596' \
278
+ '07315449521981157084370187887650624061033066022458512942411841' \
279
+ '18747893789972315277160085086164119879536041875335384844820566' \
280
+ '0287479617671726408053319619892052000850883994343378882717849')
281
+
282
+ s = int(
283
+ '68925428438585431029269182233502611027091755064643742383515623' \
284
+ '64321310582896893395529367074942808353187138794422745718419645' \
285
+ '28291231865157212604266903677599180789896916456120289112752835' \
286
+ '98502265889669730331688206825220074713977607415178738015831030' \
287
+ '364290585369150502819743827343552098197095520550865360159439'
288
+ )
289
+
290
+ t = int(
291
+ '69035483433453632820551311892368908779778144568711455301541094' \
292
+ '31487047642322695357696860925747923189635033183069823820910521' \
293
+ '71172909106797748883261493224162414050106920442445896819806600' \
294
+ '15448444826108008217972129130625571421904893252804729877353352' \
295
+ '739420480574842850202181462656251626522910618936534699566291'
296
+ )
297
+
298
+ e = 65537
299
+ puk = rsa_public_key(p, q, r, s, t, e)
300
+ prk = rsa_private_key(p, q, r, s, t, e)
301
+
302
+ plaintext = 1000
303
+ ciphertext_1 = encipher_rsa(plaintext, puk)
304
+ ciphertext_2 = encipher_rsa(plaintext, puk, [p, q, r, s, t])
305
+ assert ciphertext_1 == ciphertext_2
306
+ assert decipher_rsa(ciphertext_1, prk) == \
307
+ decipher_rsa(ciphertext_1, prk, [p, q, r, s, t])
308
+
309
+
310
+ def test_rsa_exhaustive():
311
+ p, q = 61, 53
312
+ e = 17
313
+ puk = rsa_public_key(p, q, e, totient='Carmichael')
314
+ prk = rsa_private_key(p, q, e, totient='Carmichael')
315
+
316
+ for msg in range(puk[0]):
317
+ encrypted = encipher_rsa(msg, puk)
318
+ decrypted = decipher_rsa(encrypted, prk)
319
+ try:
320
+ assert decrypted == msg
321
+ except AssertionError:
322
+ raise AssertionError(
323
+ "The RSA is not correctly decrypted " \
324
+ "(Original : {}, Encrypted : {}, Decrypted : {})" \
325
+ .format(msg, encrypted, decrypted)
326
+ )
327
+
328
+
329
+ def test_rsa_multiprime_exhanstive():
330
+ primes = [3, 5, 7, 11]
331
+ e = 7
332
+ args = primes + [e]
333
+ puk = rsa_public_key(*args, totient='Carmichael')
334
+ prk = rsa_private_key(*args, totient='Carmichael')
335
+ n = puk[0]
336
+
337
+ for msg in range(n):
338
+ encrypted = encipher_rsa(msg, puk)
339
+ decrypted = decipher_rsa(encrypted, prk)
340
+ try:
341
+ assert decrypted == msg
342
+ except AssertionError:
343
+ raise AssertionError(
344
+ "The RSA is not correctly decrypted " \
345
+ "(Original : {}, Encrypted : {}, Decrypted : {})" \
346
+ .format(msg, encrypted, decrypted)
347
+ )
348
+
349
+
350
+ def test_rsa_multipower_exhanstive():
351
+ from sympy.core.numbers import igcd
352
+ primes = [5, 5, 7]
353
+ e = 7
354
+ args = primes + [e]
355
+ puk = rsa_public_key(*args, multipower=True)
356
+ prk = rsa_private_key(*args, multipower=True)
357
+ n = puk[0]
358
+
359
+ for msg in range(n):
360
+ if igcd(msg, n) != 1:
361
+ continue
362
+
363
+ encrypted = encipher_rsa(msg, puk)
364
+ decrypted = decipher_rsa(encrypted, prk)
365
+ try:
366
+ assert decrypted == msg
367
+ except AssertionError:
368
+ raise AssertionError(
369
+ "The RSA is not correctly decrypted " \
370
+ "(Original : {}, Encrypted : {}, Decrypted : {})" \
371
+ .format(msg, encrypted, decrypted)
372
+ )
373
+
374
+
375
+ def test_kid_rsa_public_key():
376
+ assert kid_rsa_public_key(1, 2, 1, 1) == (5, 2)
377
+ assert kid_rsa_public_key(1, 2, 2, 1) == (8, 3)
378
+ assert kid_rsa_public_key(1, 2, 1, 2) == (7, 2)
379
+
380
+
381
+ def test_kid_rsa_private_key():
382
+ assert kid_rsa_private_key(1, 2, 1, 1) == (5, 3)
383
+ assert kid_rsa_private_key(1, 2, 2, 1) == (8, 3)
384
+ assert kid_rsa_private_key(1, 2, 1, 2) == (7, 4)
385
+
386
+
387
+ def test_encipher_kid_rsa():
388
+ assert encipher_kid_rsa(1, (5, 2)) == 2
389
+ assert encipher_kid_rsa(1, (8, 3)) == 3
390
+ assert encipher_kid_rsa(1, (7, 2)) == 2
391
+
392
+
393
+ def test_decipher_kid_rsa():
394
+ assert decipher_kid_rsa(2, (5, 3)) == 1
395
+ assert decipher_kid_rsa(3, (8, 3)) == 1
396
+ assert decipher_kid_rsa(2, (7, 4)) == 1
397
+
398
+
399
+ def test_encode_morse():
400
+ assert encode_morse('ABC') == '.-|-...|-.-.'
401
+ assert encode_morse('SMS ') == '...|--|...||'
402
+ assert encode_morse('SMS\n') == '...|--|...||'
403
+ assert encode_morse('') == ''
404
+ assert encode_morse(' ') == '||'
405
+ assert encode_morse(' ', sep='`') == '``'
406
+ assert encode_morse(' ', sep='``') == '````'
407
+ assert encode_morse('!@#$%^&*()_+') == '-.-.--|.--.-.|...-..-|-.--.|-.--.-|..--.-|.-.-.'
408
+ assert encode_morse('12345') == '.----|..---|...--|....-|.....'
409
+ assert encode_morse('67890') == '-....|--...|---..|----.|-----'
410
+
411
+
412
+ def test_decode_morse():
413
+ assert decode_morse('-.-|.|-.--') == 'KEY'
414
+ assert decode_morse('.-.|..-|-.||') == 'RUN'
415
+ raises(KeyError, lambda: decode_morse('.....----'))
416
+
417
+
418
+ def test_lfsr_sequence():
419
+ raises(TypeError, lambda: lfsr_sequence(1, [1], 1))
420
+ raises(TypeError, lambda: lfsr_sequence([1], 1, 1))
421
+ F = FF(2)
422
+ assert lfsr_sequence([F(1)], [F(1)], 2) == [F(1), F(1)]
423
+ assert lfsr_sequence([F(0)], [F(1)], 2) == [F(1), F(0)]
424
+ F = FF(3)
425
+ assert lfsr_sequence([F(1)], [F(1)], 2) == [F(1), F(1)]
426
+ assert lfsr_sequence([F(0)], [F(2)], 2) == [F(2), F(0)]
427
+ assert lfsr_sequence([F(1)], [F(2)], 2) == [F(2), F(2)]
428
+
429
+
430
+ def test_lfsr_autocorrelation():
431
+ raises(TypeError, lambda: lfsr_autocorrelation(1, 2, 3))
432
+ F = FF(2)
433
+ s = lfsr_sequence([F(1), F(0)], [F(0), F(1)], 5)
434
+ assert lfsr_autocorrelation(s, 2, 0) == 1
435
+ assert lfsr_autocorrelation(s, 2, 1) == -1
436
+
437
+
438
+ def test_lfsr_connection_polynomial():
439
+ F = FF(2)
440
+ x = symbols("x")
441
+ s = lfsr_sequence([F(1), F(0)], [F(0), F(1)], 5)
442
+ assert lfsr_connection_polynomial(s) == x**2 + 1
443
+ s = lfsr_sequence([F(1), F(1)], [F(0), F(1)], 5)
444
+ assert lfsr_connection_polynomial(s) == x**2 + x + 1
445
+
446
+
447
+ def test_elgamal_private_key():
448
+ a, b, _ = elgamal_private_key(digit=100)
449
+ assert isprime(a)
450
+ assert is_primitive_root(b, a)
451
+ assert len(bin(a)) >= 102
452
+
453
+
454
+ def test_elgamal():
455
+ dk = elgamal_private_key(5)
456
+ ek = elgamal_public_key(dk)
457
+ P = ek[0]
458
+ assert P - 1 == decipher_elgamal(encipher_elgamal(P - 1, ek), dk)
459
+ raises(ValueError, lambda: encipher_elgamal(P, dk))
460
+ raises(ValueError, lambda: encipher_elgamal(-1, dk))
461
+
462
+
463
+ def test_dh_private_key():
464
+ p, g, _ = dh_private_key(digit = 100)
465
+ assert isprime(p)
466
+ assert is_primitive_root(g, p)
467
+ assert len(bin(p)) >= 102
468
+
469
+
470
+ def test_dh_public_key():
471
+ p1, g1, a = dh_private_key(digit = 100)
472
+ p2, g2, ga = dh_public_key((p1, g1, a))
473
+ assert p1 == p2
474
+ assert g1 == g2
475
+ assert ga == pow(g1, a, p1)
476
+
477
+
478
+ def test_dh_shared_key():
479
+ prk = dh_private_key(digit = 100)
480
+ p, _, ga = dh_public_key(prk)
481
+ b = randrange(2, p)
482
+ sk = dh_shared_key((p, _, ga), b)
483
+ assert sk == pow(ga, b, p)
484
+ raises(ValueError, lambda: dh_shared_key((1031, 14, 565), 2000))
485
+
486
+
487
+ def test_padded_key():
488
+ assert padded_key('b', 'ab') == 'ba'
489
+ raises(ValueError, lambda: padded_key('ab', 'ace'))
490
+ raises(ValueError, lambda: padded_key('ab', 'abba'))
491
+
492
+
493
+ def test_bifid():
494
+ raises(ValueError, lambda: encipher_bifid('abc', 'b', 'abcde'))
495
+ assert encipher_bifid('abc', 'b', 'abcd') == 'bdb'
496
+ raises(ValueError, lambda: decipher_bifid('bdb', 'b', 'abcde'))
497
+ assert encipher_bifid('bdb', 'b', 'abcd') == 'abc'
498
+ raises(ValueError, lambda: bifid_square('abcde'))
499
+ assert bifid5_square("B") == \
500
+ bifid5_square('BACDEFGHIKLMNOPQRSTUVWXYZ')
501
+ assert bifid6_square('B0') == \
502
+ bifid6_square('B0ACDEFGHIJKLMNOPQRSTUVWXYZ123456789')
503
+
504
+
505
+ def test_encipher_decipher_gm():
506
+ ps = [131, 137, 139, 149, 151, 157, 163, 167,
507
+ 173, 179, 181, 191, 193, 197, 199]
508
+ qs = [89, 97, 101, 103, 107, 109, 113, 127,
509
+ 131, 137, 139, 149, 151, 157, 47]
510
+ messages = [
511
+ 0, 32855, 34303, 14805, 1280, 75859, 38368,
512
+ 724, 60356, 51675, 76697, 61854, 18661,
513
+ ]
514
+ for p, q in zip(ps, qs):
515
+ pri = gm_private_key(p, q)
516
+ for msg in messages:
517
+ pub = gm_public_key(p, q)
518
+ enc = encipher_gm(msg, pub)
519
+ dec = decipher_gm(enc, pri)
520
+ assert dec == msg
521
+
522
+
523
+ def test_gm_private_key():
524
+ raises(ValueError, lambda: gm_public_key(13, 15))
525
+ raises(ValueError, lambda: gm_public_key(0, 0))
526
+ raises(ValueError, lambda: gm_public_key(0, 5))
527
+ assert 17, 19 == gm_public_key(17, 19)
528
+
529
+
530
+ def test_gm_public_key():
531
+ assert 323 == gm_public_key(17, 19)[1]
532
+ assert 15 == gm_public_key(3, 5)[1]
533
+ raises(ValueError, lambda: gm_public_key(15, 19))
534
+
535
+ def test_encipher_decipher_bg():
536
+ ps = [67, 7, 71, 103, 11, 43, 107, 47,
537
+ 79, 19, 83, 23, 59, 127, 31]
538
+ qs = qs = [7, 71, 103, 11, 43, 107, 47,
539
+ 79, 19, 83, 23, 59, 127, 31, 67]
540
+ messages = [
541
+ 0, 328, 343, 148, 1280, 758, 383,
542
+ 724, 603, 516, 766, 618, 186,
543
+ ]
544
+
545
+ for p, q in zip(ps, qs):
546
+ pri = bg_private_key(p, q)
547
+ for msg in messages:
548
+ pub = bg_public_key(p, q)
549
+ enc = encipher_bg(msg, pub)
550
+ dec = decipher_bg(enc, pri)
551
+ assert dec == msg
552
+
553
+ def test_bg_private_key():
554
+ raises(ValueError, lambda: bg_private_key(8, 16))
555
+ raises(ValueError, lambda: bg_private_key(8, 8))
556
+ raises(ValueError, lambda: bg_private_key(13, 17))
557
+ assert 23, 31 == bg_private_key(23, 31)
558
+
559
+ def test_bg_public_key():
560
+ assert 5293 == bg_public_key(67, 79)
561
+ assert 713 == bg_public_key(23, 31)
562
+ raises(ValueError, lambda: bg_private_key(13, 17))
venv/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
+ ]
venv/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)
venv/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]
venv/lib/python3.10/site-packages/sympy/sets/fancysets.py ADDED
@@ -0,0 +1,1521 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)
venv/lib/python3.10/site-packages/sympy/sets/ordinals.py ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import Basic, Integer
2
+ import operator
3
+
4
+
5
+ class OmegaPower(Basic):
6
+ """
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()
venv/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)
venv/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)
venv/lib/python3.10/site-packages/sympy/sets/sets.py ADDED
@@ -0,0 +1,2749 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
venv/lib/python3.10/site-packages/sympy/sets/tests/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (184 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_contains.cpython-310.pyc ADDED
Binary file (2.34 kB). View file
 
venv/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_fancysets.cpython-310.pyc ADDED
Binary file (50 kB). View file
 
venv/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_ordinals.cpython-310.pyc ADDED
Binary file (3.09 kB). View file
 
venv/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_powerset.cpython-310.pyc ADDED
Binary file (4.2 kB). View file
 
venv/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_setexpr.cpython-310.pyc ADDED
Binary file (10 kB). View file
 
venv/lib/python3.10/site-packages/sympy/sets/tests/test_conditionset.py ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.expr import unchanged
2
+ from sympy.sets import (ConditionSet, Intersection, FiniteSet,
3
+ EmptySet, Union, Contains, ImageSet)
4
+ from sympy.sets.sets import SetKind
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)
venv/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))
venv/lib/python3.10/site-packages/sympy/sets/tests/test_fancysets.py ADDED
@@ -0,0 +1,1306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from sympy.core.expr import unchanged
3
+ from sympy.sets.contains import Contains
4
+ from sympy.sets.fancysets import (ImageSet, Range, normalize_theta_set,
5
+ ComplexRegion)
6
+ from sympy.sets.sets import (FiniteSet, Interval, Union, imageset,
7
+ Intersection, ProductSet, SetKind)
8
+ from sympy.sets.conditionset import ConditionSet
9
+ from sympy.simplify.simplify import simplify
10
+ from sympy.core.basic import Basic
11
+ from sympy.core.containers import Tuple, TupleKind
12
+ from sympy.core.function import Lambda
13
+ from sympy.core.kind import NumberKind
14
+ from sympy.core.numbers import (I, Rational, oo, pi)
15
+ from sympy.core.relational import Eq
16
+ from sympy.core.singleton import S
17
+ from sympy.core.symbol import (Dummy, Symbol, symbols)
18
+ from sympy.functions.elementary.complexes import Abs
19
+ from sympy.functions.elementary.exponential import (exp, log)
20
+ from sympy.functions.elementary.integers import floor
21
+ from sympy.functions.elementary.miscellaneous import sqrt
22
+ from sympy.functions.elementary.trigonometric import (cos, sin, tan)
23
+ from sympy.logic.boolalg import And
24
+ from sympy.matrices.dense import eye
25
+ from sympy.testing.pytest import XFAIL, raises
26
+ from sympy.abc import x, y, t, z
27
+ from sympy.core.mod import Mod
28
+
29
+ import itertools
30
+
31
+
32
+ def test_naturals():
33
+ N = S.Naturals
34
+ assert 5 in N
35
+ assert -5 not in N
36
+ assert 5.5 not in N
37
+ ni = iter(N)
38
+ a, b, c, d = next(ni), next(ni), next(ni), next(ni)
39
+ assert (a, b, c, d) == (1, 2, 3, 4)
40
+ assert isinstance(a, Basic)
41
+
42
+ assert N.intersect(Interval(-5, 5)) == Range(1, 6)
43
+ assert N.intersect(Interval(-5, 5, True, True)) == Range(1, 5)
44
+
45
+ assert N.boundary == N
46
+ assert N.is_open == False
47
+ assert N.is_closed == True
48
+
49
+ assert N.inf == 1
50
+ assert N.sup is oo
51
+ assert not N.contains(oo)
52
+ for s in (S.Naturals0, S.Naturals):
53
+ assert s.intersection(S.Reals) is s
54
+ assert s.is_subset(S.Reals)
55
+
56
+ assert N.as_relational(x) == And(Eq(floor(x), x), x >= 1, x < oo)
57
+
58
+
59
+ def test_naturals0():
60
+ N = S.Naturals0
61
+ assert 0 in N
62
+ assert -1 not in N
63
+ assert next(iter(N)) == 0
64
+ assert not N.contains(oo)
65
+ assert N.contains(sin(x)) == Contains(sin(x), N)
66
+
67
+
68
+ def test_integers():
69
+ Z = S.Integers
70
+ assert 5 in Z
71
+ assert -5 in Z
72
+ assert 5.5 not in Z
73
+ assert not Z.contains(oo)
74
+ assert not Z.contains(-oo)
75
+
76
+ zi = iter(Z)
77
+ a, b, c, d = next(zi), next(zi), next(zi), next(zi)
78
+ assert (a, b, c, d) == (0, 1, -1, 2)
79
+ assert isinstance(a, Basic)
80
+
81
+ assert Z.intersect(Interval(-5, 5)) == Range(-5, 6)
82
+ assert Z.intersect(Interval(-5, 5, True, True)) == Range(-4, 5)
83
+ assert Z.intersect(Interval(5, S.Infinity)) == Range(5, S.Infinity)
84
+ assert Z.intersect(Interval.Lopen(5, S.Infinity)) == Range(6, S.Infinity)
85
+
86
+ assert Z.inf is -oo
87
+ assert Z.sup is oo
88
+
89
+ assert Z.boundary == Z
90
+ assert Z.is_open == False
91
+ assert Z.is_closed == True
92
+
93
+ assert Z.as_relational(x) == And(Eq(floor(x), x), -oo < x, x < oo)
94
+
95
+
96
+ def test_ImageSet():
97
+ raises(ValueError, lambda: ImageSet(x, S.Integers))
98
+ assert ImageSet(Lambda(x, 1), S.Integers) == FiniteSet(1)
99
+ assert ImageSet(Lambda(x, y), S.Integers) == {y}
100
+ assert ImageSet(Lambda(x, 1), S.EmptySet) == S.EmptySet
101
+ empty = Intersection(FiniteSet(log(2)/pi), S.Integers)
102
+ assert unchanged(ImageSet, Lambda(x, 1), empty) # issue #17471
103
+ squares = ImageSet(Lambda(x, x**2), S.Naturals)
104
+ assert 4 in squares
105
+ assert 5 not in squares
106
+ assert FiniteSet(*range(10)).intersect(squares) == FiniteSet(1, 4, 9)
107
+
108
+ assert 16 not in squares.intersect(Interval(0, 10))
109
+
110
+ si = iter(squares)
111
+ a, b, c, d = next(si), next(si), next(si), next(si)
112
+ assert (a, b, c, d) == (1, 4, 9, 16)
113
+
114
+ harmonics = ImageSet(Lambda(x, 1/x), S.Naturals)
115
+ assert Rational(1, 5) in harmonics
116
+ assert Rational(.25) in harmonics
117
+ assert 0.25 not in harmonics
118
+ assert Rational(.3) not in harmonics
119
+ assert (1, 2) not in harmonics
120
+
121
+ assert harmonics.is_iterable
122
+
123
+ assert imageset(x, -x, Interval(0, 1)) == Interval(-1, 0)
124
+
125
+ assert ImageSet(Lambda(x, x**2), Interval(0, 2)).doit() == Interval(0, 4)
126
+ assert ImageSet(Lambda((x, y), 2*x), {4}, {3}).doit() == FiniteSet(8)
127
+ assert (ImageSet(Lambda((x, y), x+y), {1, 2, 3}, {10, 20, 30}).doit() ==
128
+ FiniteSet(11, 12, 13, 21, 22, 23, 31, 32, 33))
129
+
130
+ c = Interval(1, 3) * Interval(1, 3)
131
+ assert Tuple(2, 6) in ImageSet(Lambda(((x, y),), (x, 2*y)), c)
132
+ assert Tuple(2, S.Half) in ImageSet(Lambda(((x, y),), (x, 1/y)), c)
133
+ assert Tuple(2, -2) not in ImageSet(Lambda(((x, y),), (x, y**2)), c)
134
+ assert Tuple(2, -2) in ImageSet(Lambda(((x, y),), (x, -2)), c)
135
+ c3 = ProductSet(Interval(3, 7), Interval(8, 11), Interval(5, 9))
136
+ assert Tuple(8, 3, 9) in ImageSet(Lambda(((t, y, x),), (y, t, x)), c3)
137
+ assert Tuple(Rational(1, 8), 3, 9) in ImageSet(Lambda(((t, y, x),), (1/y, t, x)), c3)
138
+ assert 2/pi not in ImageSet(Lambda(((x, y),), 2/x), c)
139
+ assert 2/S(100) not in ImageSet(Lambda(((x, y),), 2/x), c)
140
+ assert Rational(2, 3) in ImageSet(Lambda(((x, y),), 2/x), c)
141
+
142
+ S1 = imageset(lambda x, y: x + y, S.Integers, S.Naturals)
143
+ assert S1.base_pset == ProductSet(S.Integers, S.Naturals)
144
+ assert S1.base_sets == (S.Integers, S.Naturals)
145
+
146
+ # Passing a set instead of a FiniteSet shouldn't raise
147
+ assert unchanged(ImageSet, Lambda(x, x**2), {1, 2, 3})
148
+
149
+ S2 = ImageSet(Lambda(((x, y),), x+y), {(1, 2), (3, 4)})
150
+ assert 3 in S2.doit()
151
+ # FIXME: This doesn't yet work:
152
+ #assert 3 in S2
153
+ assert S2._contains(3) is None
154
+
155
+ raises(TypeError, lambda: ImageSet(Lambda(x, x**2), 1))
156
+
157
+
158
+ def test_image_is_ImageSet():
159
+ assert isinstance(imageset(x, sqrt(sin(x)), Range(5)), ImageSet)
160
+
161
+
162
+ def test_halfcircle():
163
+ r, th = symbols('r, theta', real=True)
164
+ L = Lambda(((r, th),), (r*cos(th), r*sin(th)))
165
+ halfcircle = ImageSet(L, Interval(0, 1)*Interval(0, pi))
166
+
167
+ assert (1, 0) in halfcircle
168
+ assert (0, -1) not in halfcircle
169
+ assert (0, 0) in halfcircle
170
+ assert halfcircle._contains((r, 0)) is None
171
+ # This one doesn't work:
172
+ #assert (r, 2*pi) not in halfcircle
173
+
174
+ assert not halfcircle.is_iterable
175
+
176
+
177
+ def test_ImageSet_iterator_not_injective():
178
+ L = Lambda(x, x - x % 2) # produces 0, 2, 2, 4, 4, 6, 6, ...
179
+ evens = ImageSet(L, S.Naturals)
180
+ i = iter(evens)
181
+ # No repeats here
182
+ assert (next(i), next(i), next(i), next(i)) == (0, 2, 4, 6)
183
+
184
+
185
+ def test_inf_Range_len():
186
+ raises(ValueError, lambda: len(Range(0, oo, 2)))
187
+ assert Range(0, oo, 2).size is S.Infinity
188
+ assert Range(0, -oo, -2).size is S.Infinity
189
+ assert Range(oo, 0, -2).size is S.Infinity
190
+ assert Range(-oo, 0, 2).size is S.Infinity
191
+
192
+
193
+ def test_Range_set():
194
+ empty = Range(0)
195
+
196
+ assert Range(5) == Range(0, 5) == Range(0, 5, 1)
197
+
198
+ r = Range(10, 20, 2)
199
+ assert 12 in r
200
+ assert 8 not in r
201
+ assert 11 not in r
202
+ assert 30 not in r
203
+
204
+ assert list(Range(0, 5)) == list(range(5))
205
+ assert list(Range(5, 0, -1)) == list(range(5, 0, -1))
206
+
207
+
208
+ assert Range(5, 15).sup == 14
209
+ assert Range(5, 15).inf == 5
210
+ assert Range(15, 5, -1).sup == 15
211
+ assert Range(15, 5, -1).inf == 6
212
+ assert Range(10, 67, 10).sup == 60
213
+ assert Range(60, 7, -10).inf == 10
214
+
215
+ assert len(Range(10, 38, 10)) == 3
216
+
217
+ assert Range(0, 0, 5) == empty
218
+ assert Range(oo, oo, 1) == empty
219
+ assert Range(oo, 1, 1) == empty
220
+ assert Range(-oo, 1, -1) == empty
221
+ assert Range(1, oo, -1) == empty
222
+ assert Range(1, -oo, 1) == empty
223
+ assert Range(1, -4, oo) == empty
224
+ ip = symbols('ip', positive=True)
225
+ assert Range(0, ip, -1) == empty
226
+ assert Range(0, -ip, 1) == empty
227
+ assert Range(1, -4, -oo) == Range(1, 2)
228
+ assert Range(1, 4, oo) == Range(1, 2)
229
+ assert Range(-oo, oo).size == oo
230
+ assert Range(oo, -oo, -1).size == oo
231
+ raises(ValueError, lambda: Range(-oo, oo, 2))
232
+ raises(ValueError, lambda: Range(x, pi, y))
233
+ raises(ValueError, lambda: Range(x, y, 0))
234
+
235
+ assert 5 in Range(0, oo, 5)
236
+ assert -5 in Range(-oo, 0, 5)
237
+ assert oo not in Range(0, oo)
238
+ ni = symbols('ni', integer=False)
239
+ assert ni not in Range(oo)
240
+ u = symbols('u', integer=None)
241
+ assert Range(oo).contains(u) is not False
242
+ inf = symbols('inf', infinite=True)
243
+ assert inf not in Range(-oo, oo)
244
+ raises(ValueError, lambda: Range(0, oo, 2)[-1])
245
+ raises(ValueError, lambda: Range(0, -oo, -2)[-1])
246
+ assert Range(-oo, 1, 1)[-1] is S.Zero
247
+ assert Range(oo, 1, -1)[-1] == 2
248
+ assert inf not in Range(oo)
249
+ assert Range(1, 10, 1)[-1] == 9
250
+ assert all(i.is_Integer for i in Range(0, -1, 1))
251
+ it = iter(Range(-oo, 0, 2))
252
+ raises(TypeError, lambda: next(it))
253
+
254
+ assert empty.intersect(S.Integers) == empty
255
+ assert Range(-1, 10, 1).intersect(S.Complexes) == Range(-1, 10, 1)
256
+ assert Range(-1, 10, 1).intersect(S.Reals) == Range(-1, 10, 1)
257
+ assert Range(-1, 10, 1).intersect(S.Rationals) == Range(-1, 10, 1)
258
+ assert Range(-1, 10, 1).intersect(S.Integers) == Range(-1, 10, 1)
259
+ assert Range(-1, 10, 1).intersect(S.Naturals) == Range(1, 10, 1)
260
+ assert Range(-1, 10, 1).intersect(S.Naturals0) == Range(0, 10, 1)
261
+
262
+ # test slicing
263
+ assert Range(1, 10, 1)[5] == 6
264
+ assert Range(1, 12, 2)[5] == 11
265
+ assert Range(1, 10, 1)[-1] == 9
266
+ assert Range(1, 10, 3)[-1] == 7
267
+ raises(ValueError, lambda: Range(oo,0,-1)[1:3:0])
268
+ raises(ValueError, lambda: Range(oo,0,-1)[:1])
269
+ raises(ValueError, lambda: Range(1, oo)[-2])
270
+ raises(ValueError, lambda: Range(-oo, 1)[2])
271
+ raises(IndexError, lambda: Range(10)[-20])
272
+ raises(IndexError, lambda: Range(10)[20])
273
+ raises(ValueError, lambda: Range(2, -oo, -2)[2:2:0])
274
+ assert Range(2, -oo, -2)[2:2:2] == empty
275
+ assert Range(2, -oo, -2)[:2:2] == Range(2, -2, -4)
276
+ raises(ValueError, lambda: Range(-oo, 4, 2)[:2:2])
277
+ assert Range(-oo, 4, 2)[::-2] == Range(2, -oo, -4)
278
+ raises(ValueError, lambda: Range(-oo, 4, 2)[::2])
279
+ assert Range(oo, 2, -2)[::] == Range(oo, 2, -2)
280
+ assert Range(-oo, 4, 2)[:-2:-2] == Range(2, 0, -4)
281
+ assert Range(-oo, 4, 2)[:-2:2] == Range(-oo, 0, 4)
282
+ raises(ValueError, lambda: Range(-oo, 4, 2)[:0:-2])
283
+ raises(ValueError, lambda: Range(-oo, 4, 2)[:2:-2])
284
+ assert Range(-oo, 4, 2)[-2::-2] == Range(0, -oo, -4)
285
+ raises(ValueError, lambda: Range(-oo, 4, 2)[-2:0:-2])
286
+ raises(ValueError, lambda: Range(-oo, 4, 2)[0::2])
287
+ assert Range(oo, 2, -2)[0::] == Range(oo, 2, -2)
288
+ raises(ValueError, lambda: Range(-oo, 4, 2)[0:-2:2])
289
+ assert Range(oo, 2, -2)[0:-2:] == Range(oo, 6, -2)
290
+ raises(ValueError, lambda: Range(oo, 2, -2)[0:2:])
291
+ raises(ValueError, lambda: Range(-oo, 4, 2)[2::-1])
292
+ assert Range(-oo, 4, 2)[-2::2] == Range(0, 4, 4)
293
+ assert Range(oo, 0, -2)[-10:0:2] == empty
294
+ raises(ValueError, lambda: Range(oo, 0, -2)[0])
295
+ raises(ValueError, lambda: Range(oo, 0, -2)[-10:10:2])
296
+ raises(ValueError, lambda: Range(oo, 0, -2)[0::-2])
297
+ assert Range(oo, 0, -2)[0:-4:-2] == empty
298
+ assert Range(oo, 0, -2)[:0:2] == empty
299
+ raises(ValueError, lambda: Range(oo, 0, -2)[:1:-1])
300
+
301
+ # test empty Range
302
+ assert Range(x, x, y) == empty
303
+ assert empty.reversed == empty
304
+ assert 0 not in empty
305
+ assert list(empty) == []
306
+ assert len(empty) == 0
307
+ assert empty.size is S.Zero
308
+ assert empty.intersect(FiniteSet(0)) is S.EmptySet
309
+ assert bool(empty) is False
310
+ raises(IndexError, lambda: empty[0])
311
+ assert empty[:0] == empty
312
+ raises(NotImplementedError, lambda: empty.inf)
313
+ raises(NotImplementedError, lambda: empty.sup)
314
+ assert empty.as_relational(x) is S.false
315
+
316
+ AB = [None] + list(range(12))
317
+ for R in [
318
+ Range(1, 10),
319
+ Range(1, 10, 2),
320
+ ]:
321
+ r = list(R)
322
+ for a, b, c in itertools.product(AB, AB, [-3, -1, None, 1, 3]):
323
+ for reverse in range(2):
324
+ r = list(reversed(r))
325
+ R = R.reversed
326
+ result = list(R[a:b:c])
327
+ ans = r[a:b:c]
328
+ txt = ('\n%s[%s:%s:%s] = %s -> %s' % (
329
+ R, a, b, c, result, ans))
330
+ check = ans == result
331
+ assert check, txt
332
+
333
+ assert Range(1, 10, 1).boundary == Range(1, 10, 1)
334
+
335
+ for r in (Range(1, 10, 2), Range(1, oo, 2)):
336
+ rev = r.reversed
337
+ assert r.inf == rev.inf and r.sup == rev.sup
338
+ assert r.step == -rev.step
339
+
340
+ builtin_range = range
341
+
342
+ raises(TypeError, lambda: Range(builtin_range(1)))
343
+ assert S(builtin_range(10)) == Range(10)
344
+ assert S(builtin_range(1000000000000)) == Range(1000000000000)
345
+
346
+ # test Range.as_relational
347
+ assert Range(1, 4).as_relational(x) == (x >= 1) & (x <= 3) & Eq(Mod(x, 1), 0)
348
+ assert Range(oo, 1, -2).as_relational(x) == (x >= 3) & (x < oo) & Eq(Mod(x + 1, -2), 0)
349
+
350
+
351
+ def test_Range_symbolic():
352
+ # symbolic Range
353
+ xr = Range(x, x + 4, 5)
354
+ sr = Range(x, y, t)
355
+ i = Symbol('i', integer=True)
356
+ ip = Symbol('i', integer=True, positive=True)
357
+ ipr = Range(ip)
358
+ inr = Range(0, -ip, -1)
359
+ ir = Range(i, i + 19, 2)
360
+ ir2 = Range(i, i*8, 3*i)
361
+ i = Symbol('i', integer=True)
362
+ inf = symbols('inf', infinite=True)
363
+ raises(ValueError, lambda: Range(inf))
364
+ raises(ValueError, lambda: Range(inf, 0, -1))
365
+ raises(ValueError, lambda: Range(inf, inf, 1))
366
+ raises(ValueError, lambda: Range(1, 1, inf))
367
+ # args
368
+ assert xr.args == (x, x + 5, 5)
369
+ assert sr.args == (x, y, t)
370
+ assert ir.args == (i, i + 20, 2)
371
+ assert ir2.args == (i, 10*i, 3*i)
372
+ # reversed
373
+ raises(ValueError, lambda: xr.reversed)
374
+ raises(ValueError, lambda: sr.reversed)
375
+ assert ipr.reversed.args == (ip - 1, -1, -1)
376
+ assert inr.reversed.args == (-ip + 1, 1, 1)
377
+ assert ir.reversed.args == (i + 18, i - 2, -2)
378
+ assert ir2.reversed.args == (7*i, -2*i, -3*i)
379
+ # contains
380
+ assert inf not in sr
381
+ assert inf not in ir
382
+ assert 0 in ipr
383
+ assert 0 in inr
384
+ raises(TypeError, lambda: 1 in ipr)
385
+ raises(TypeError, lambda: -1 in inr)
386
+ assert .1 not in sr
387
+ assert .1 not in ir
388
+ assert i + 1 not in ir
389
+ assert i + 2 in ir
390
+ raises(TypeError, lambda: x in xr) # XXX is this what contains is supposed to do?
391
+ raises(TypeError, lambda: 1 in sr) # XXX is this what contains is supposed to do?
392
+ # iter
393
+ raises(ValueError, lambda: next(iter(xr)))
394
+ raises(ValueError, lambda: next(iter(sr)))
395
+ assert next(iter(ir)) == i
396
+ assert next(iter(ir2)) == i
397
+ assert sr.intersect(S.Integers) == sr
398
+ assert sr.intersect(FiniteSet(x)) == Intersection({x}, sr)
399
+ raises(ValueError, lambda: sr[:2])
400
+ raises(ValueError, lambda: xr[0])
401
+ raises(ValueError, lambda: sr[0])
402
+ # len
403
+ assert len(ir) == ir.size == 10
404
+ assert len(ir2) == ir2.size == 3
405
+ raises(ValueError, lambda: len(xr))
406
+ raises(ValueError, lambda: xr.size)
407
+ raises(ValueError, lambda: len(sr))
408
+ raises(ValueError, lambda: sr.size)
409
+ # bool
410
+ assert bool(Range(0)) == False
411
+ assert bool(xr)
412
+ assert bool(ir)
413
+ assert bool(ipr)
414
+ assert bool(inr)
415
+ raises(ValueError, lambda: bool(sr))
416
+ raises(ValueError, lambda: bool(ir2))
417
+ # inf
418
+ raises(ValueError, lambda: xr.inf)
419
+ raises(ValueError, lambda: sr.inf)
420
+ assert ipr.inf == 0
421
+ assert inr.inf == -ip + 1
422
+ assert ir.inf == i
423
+ raises(ValueError, lambda: ir2.inf)
424
+ # sup
425
+ raises(ValueError, lambda: xr.sup)
426
+ raises(ValueError, lambda: sr.sup)
427
+ assert ipr.sup == ip - 1
428
+ assert inr.sup == 0
429
+ assert ir.inf == i
430
+ raises(ValueError, lambda: ir2.sup)
431
+ # getitem
432
+ raises(ValueError, lambda: xr[0])
433
+ raises(ValueError, lambda: sr[0])
434
+ raises(ValueError, lambda: sr[-1])
435
+ raises(ValueError, lambda: sr[:2])
436
+ assert ir[:2] == Range(i, i + 4, 2)
437
+ assert ir[0] == i
438
+ assert ir[-2] == i + 16
439
+ assert ir[-1] == i + 18
440
+ assert ir2[:2] == Range(i, 7*i, 3*i)
441
+ assert ir2[0] == i
442
+ assert ir2[-2] == 4*i
443
+ assert ir2[-1] == 7*i
444
+ raises(ValueError, lambda: Range(i)[-1])
445
+ assert ipr[0] == ipr.inf == 0
446
+ assert ipr[-1] == ipr.sup == ip - 1
447
+ assert inr[0] == inr.sup == 0
448
+ assert inr[-1] == inr.inf == -ip + 1
449
+ raises(ValueError, lambda: ipr[-2])
450
+ assert ir.inf == i
451
+ assert ir.sup == i + 18
452
+ raises(ValueError, lambda: Range(i).inf)
453
+ # as_relational
454
+ assert ir.as_relational(x) == ((x >= i) & (x <= i + 18) &
455
+ Eq(Mod(-i + x, 2), 0))
456
+ assert ir2.as_relational(x) == Eq(
457
+ Mod(-i + x, 3*i), 0) & (((x >= i) & (x <= 7*i) & (3*i >= 1)) |
458
+ ((x <= i) & (x >= 7*i) & (3*i <= -1)))
459
+ assert Range(i, i + 1).as_relational(x) == Eq(x, i)
460
+ assert sr.as_relational(z) == Eq(
461
+ Mod(t, 1), 0) & Eq(Mod(x, 1), 0) & Eq(Mod(-x + z, t), 0
462
+ ) & (((z >= x) & (z <= -t + y) & (t >= 1)) |
463
+ ((z <= x) & (z >= -t + y) & (t <= -1)))
464
+ assert xr.as_relational(z) == Eq(z, x) & Eq(Mod(x, 1), 0)
465
+ # symbols can clash if user wants (but it must be integer)
466
+ assert xr.as_relational(x) == Eq(Mod(x, 1), 0)
467
+ # contains() for symbolic values (issue #18146)
468
+ e = Symbol('e', integer=True, even=True)
469
+ o = Symbol('o', integer=True, odd=True)
470
+ assert Range(5).contains(i) == And(i >= 0, i <= 4)
471
+ assert Range(1).contains(i) == Eq(i, 0)
472
+ assert Range(-oo, 5, 1).contains(i) == (i <= 4)
473
+ assert Range(-oo, oo).contains(i) == True
474
+ assert Range(0, 8, 2).contains(i) == Contains(i, Range(0, 8, 2))
475
+ assert Range(0, 8, 2).contains(e) == And(e >= 0, e <= 6)
476
+ assert Range(0, 8, 2).contains(2*i) == And(2*i >= 0, 2*i <= 6)
477
+ assert Range(0, 8, 2).contains(o) == False
478
+ assert Range(1, 9, 2).contains(e) == False
479
+ assert Range(1, 9, 2).contains(o) == And(o >= 1, o <= 7)
480
+ assert Range(8, 0, -2).contains(o) == False
481
+ assert Range(9, 1, -2).contains(o) == And(o >= 3, o <= 9)
482
+ assert Range(-oo, 8, 2).contains(i) == Contains(i, Range(-oo, 8, 2))
483
+
484
+
485
+ def test_range_range_intersection():
486
+ for a, b, r in [
487
+ (Range(0), Range(1), S.EmptySet),
488
+ (Range(3), Range(4, oo), S.EmptySet),
489
+ (Range(3), Range(-3, -1), S.EmptySet),
490
+ (Range(1, 3), Range(0, 3), Range(1, 3)),
491
+ (Range(1, 3), Range(1, 4), Range(1, 3)),
492
+ (Range(1, oo, 2), Range(2, oo, 2), S.EmptySet),
493
+ (Range(0, oo, 2), Range(oo), Range(0, oo, 2)),
494
+ (Range(0, oo, 2), Range(100), Range(0, 100, 2)),
495
+ (Range(2, oo, 2), Range(oo), Range(2, oo, 2)),
496
+ (Range(0, oo, 2), Range(5, 6), S.EmptySet),
497
+ (Range(2, 80, 1), Range(55, 71, 4), Range(55, 71, 4)),
498
+ (Range(0, 6, 3), Range(-oo, 5, 3), S.EmptySet),
499
+ (Range(0, oo, 2), Range(5, oo, 3), Range(8, oo, 6)),
500
+ (Range(4, 6, 2), Range(2, 16, 7), S.EmptySet),]:
501
+ assert a.intersect(b) == r
502
+ assert a.intersect(b.reversed) == r
503
+ assert a.reversed.intersect(b) == r
504
+ assert a.reversed.intersect(b.reversed) == r
505
+ a, b = b, a
506
+ assert a.intersect(b) == r
507
+ assert a.intersect(b.reversed) == r
508
+ assert a.reversed.intersect(b) == r
509
+ assert a.reversed.intersect(b.reversed) == r
510
+
511
+
512
+ def test_range_interval_intersection():
513
+ p = symbols('p', positive=True)
514
+ assert isinstance(Range(3).intersect(Interval(p, p + 2)), Intersection)
515
+ assert Range(4).intersect(Interval(0, 3)) == Range(4)
516
+ assert Range(4).intersect(Interval(-oo, oo)) == Range(4)
517
+ assert Range(4).intersect(Interval(1, oo)) == Range(1, 4)
518
+ assert Range(4).intersect(Interval(1.1, oo)) == Range(2, 4)
519
+ assert Range(4).intersect(Interval(0.1, 3)) == Range(1, 4)
520
+ assert Range(4).intersect(Interval(0.1, 3.1)) == Range(1, 4)
521
+ assert Range(4).intersect(Interval.open(0, 3)) == Range(1, 3)
522
+ assert Range(4).intersect(Interval.open(0.1, 0.5)) is S.EmptySet
523
+ assert Interval(-1, 5).intersect(S.Complexes) == Interval(-1, 5)
524
+ assert Interval(-1, 5).intersect(S.Reals) == Interval(-1, 5)
525
+ assert Interval(-1, 5).intersect(S.Integers) == Range(-1, 6)
526
+ assert Interval(-1, 5).intersect(S.Naturals) == Range(1, 6)
527
+ assert Interval(-1, 5).intersect(S.Naturals0) == Range(0, 6)
528
+
529
+ # Null Range intersections
530
+ assert Range(0).intersect(Interval(0.2, 0.8)) is S.EmptySet
531
+ assert Range(0).intersect(Interval(-oo, oo)) is S.EmptySet
532
+
533
+
534
+ def test_range_is_finite_set():
535
+ assert Range(-100, 100).is_finite_set is True
536
+ assert Range(2, oo).is_finite_set is False
537
+ assert Range(-oo, 50).is_finite_set is False
538
+ assert Range(-oo, oo).is_finite_set is False
539
+ assert Range(oo, -oo).is_finite_set is True
540
+ assert Range(0, 0).is_finite_set is True
541
+ assert Range(oo, oo).is_finite_set is True
542
+ assert Range(-oo, -oo).is_finite_set is True
543
+ n = Symbol('n', integer=True)
544
+ m = Symbol('m', integer=True)
545
+ assert Range(n, n + 49).is_finite_set is True
546
+ assert Range(n, 0).is_finite_set is True
547
+ assert Range(-3, n + 7).is_finite_set is True
548
+ assert Range(n, m).is_finite_set is True
549
+ assert Range(n + m, m - n).is_finite_set is True
550
+ assert Range(n, n + m + n).is_finite_set is True
551
+ assert Range(n, oo).is_finite_set is False
552
+ assert Range(-oo, n).is_finite_set is False
553
+ assert Range(n, -oo).is_finite_set is True
554
+ assert Range(oo, n).is_finite_set is True
555
+
556
+
557
+ def test_Range_is_iterable():
558
+ assert Range(-100, 100).is_iterable is True
559
+ assert Range(2, oo).is_iterable is False
560
+ assert Range(-oo, 50).is_iterable is False
561
+ assert Range(-oo, oo).is_iterable is False
562
+ assert Range(oo, -oo).is_iterable is True
563
+ assert Range(0, 0).is_iterable is True
564
+ assert Range(oo, oo).is_iterable is True
565
+ assert Range(-oo, -oo).is_iterable is True
566
+ n = Symbol('n', integer=True)
567
+ m = Symbol('m', integer=True)
568
+ p = Symbol('p', integer=True, positive=True)
569
+ assert Range(n, n + 49).is_iterable is True
570
+ assert Range(n, 0).is_iterable is False
571
+ assert Range(-3, n + 7).is_iterable is False
572
+ assert Range(-3, p + 7).is_iterable is False # Should work with better __iter__
573
+ assert Range(n, m).is_iterable is False
574
+ assert Range(n + m, m - n).is_iterable is False
575
+ assert Range(n, n + m + n).is_iterable is False
576
+ assert Range(n, oo).is_iterable is False
577
+ assert Range(-oo, n).is_iterable is False
578
+ x = Symbol('x')
579
+ assert Range(x, x + 49).is_iterable is False
580
+ assert Range(x, 0).is_iterable is False
581
+ assert Range(-3, x + 7).is_iterable is False
582
+ assert Range(x, m).is_iterable is False
583
+ assert Range(x + m, m - x).is_iterable is False
584
+ assert Range(x, x + m + x).is_iterable is False
585
+ assert Range(x, oo).is_iterable is False
586
+ assert Range(-oo, x).is_iterable is False
587
+
588
+
589
+ def test_Integers_eval_imageset():
590
+ ans = ImageSet(Lambda(x, 2*x + Rational(3, 7)), S.Integers)
591
+ im = imageset(Lambda(x, -2*x + Rational(3, 7)), S.Integers)
592
+ assert im == ans
593
+ im = imageset(Lambda(x, -2*x - Rational(11, 7)), S.Integers)
594
+ assert im == ans
595
+ y = Symbol('y')
596
+ L = imageset(x, 2*x + y, S.Integers)
597
+ assert y + 4 in L
598
+ a, b, c = 0.092, 0.433, 0.341
599
+ assert a in imageset(x, a + c*x, S.Integers)
600
+ assert b in imageset(x, b + c*x, S.Integers)
601
+
602
+ _x = symbols('x', negative=True)
603
+ eq = _x**2 - _x + 1
604
+ assert imageset(_x, eq, S.Integers).lamda.expr == _x**2 + _x + 1
605
+ eq = 3*_x - 1
606
+ assert imageset(_x, eq, S.Integers).lamda.expr == 3*_x + 2
607
+
608
+ assert imageset(x, (x, 1/x), S.Integers) == \
609
+ ImageSet(Lambda(x, (x, 1/x)), S.Integers)
610
+
611
+
612
+ def test_Range_eval_imageset():
613
+ a, b, c = symbols('a b c')
614
+ assert imageset(x, a*(x + b) + c, Range(3)) == \
615
+ imageset(x, a*x + a*b + c, Range(3))
616
+ eq = (x + 1)**2
617
+ assert imageset(x, eq, Range(3)).lamda.expr == eq
618
+ eq = a*(x + b) + c
619
+ r = Range(3, -3, -2)
620
+ imset = imageset(x, eq, r)
621
+ assert imset.lamda.expr != eq
622
+ assert list(imset) == [eq.subs(x, i).expand() for i in list(r)]
623
+
624
+
625
+ def test_fun():
626
+ assert (FiniteSet(*ImageSet(Lambda(x, sin(pi*x/4)),
627
+ Range(-10, 11))) == FiniteSet(-1, -sqrt(2)/2, 0, sqrt(2)/2, 1))
628
+
629
+
630
+ def test_Range_is_empty():
631
+ i = Symbol('i', integer=True)
632
+ n = Symbol('n', negative=True, integer=True)
633
+ p = Symbol('p', positive=True, integer=True)
634
+
635
+ assert Range(0).is_empty
636
+ assert not Range(1).is_empty
637
+ assert Range(1, 0).is_empty
638
+ assert not Range(-1, 0).is_empty
639
+ assert Range(i).is_empty is None
640
+ assert Range(n).is_empty
641
+ assert Range(p).is_empty is False
642
+ assert Range(n, 0).is_empty is False
643
+ assert Range(n, p).is_empty is False
644
+ assert Range(p, n).is_empty
645
+ assert Range(n, -1).is_empty is None
646
+ assert Range(p, n, -1).is_empty is False
647
+
648
+
649
+ def test_Reals():
650
+ assert 5 in S.Reals
651
+ assert S.Pi in S.Reals
652
+ assert -sqrt(2) in S.Reals
653
+ assert (2, 5) not in S.Reals
654
+ assert sqrt(-1) not in S.Reals
655
+ assert S.Reals == Interval(-oo, oo)
656
+ assert S.Reals != Interval(0, oo)
657
+ assert S.Reals.is_subset(Interval(-oo, oo))
658
+ assert S.Reals.intersect(Range(-oo, oo)) == Range(-oo, oo)
659
+ assert S.ComplexInfinity not in S.Reals
660
+ assert S.NaN not in S.Reals
661
+ assert x + S.ComplexInfinity not in S.Reals
662
+
663
+
664
+ def test_Complex():
665
+ assert 5 in S.Complexes
666
+ assert 5 + 4*I in S.Complexes
667
+ assert S.Pi in S.Complexes
668
+ assert -sqrt(2) in S.Complexes
669
+ assert -I in S.Complexes
670
+ assert sqrt(-1) in S.Complexes
671
+ assert S.Complexes.intersect(S.Reals) == S.Reals
672
+ assert S.Complexes.union(S.Reals) == S.Complexes
673
+ assert S.Complexes == ComplexRegion(S.Reals*S.Reals)
674
+ assert (S.Complexes == ComplexRegion(Interval(1, 2)*Interval(3, 4))) == False
675
+ assert str(S.Complexes) == "Complexes"
676
+ assert repr(S.Complexes) == "Complexes"
677
+
678
+
679
+ def take(n, iterable):
680
+ "Return first n items of the iterable as a list"
681
+ return list(itertools.islice(iterable, n))
682
+
683
+
684
+ def test_intersections():
685
+ assert S.Integers.intersect(S.Reals) == S.Integers
686
+ assert 5 in S.Integers.intersect(S.Reals)
687
+ assert 5 in S.Integers.intersect(S.Reals)
688
+ assert -5 not in S.Naturals.intersect(S.Reals)
689
+ assert 5.5 not in S.Integers.intersect(S.Reals)
690
+ assert 5 in S.Integers.intersect(Interval(3, oo))
691
+ assert -5 in S.Integers.intersect(Interval(-oo, 3))
692
+ assert all(x.is_Integer
693
+ for x in take(10, S.Integers.intersect(Interval(3, oo)) ))
694
+
695
+
696
+ def test_infinitely_indexed_set_1():
697
+ from sympy.abc import n, m
698
+ assert imageset(Lambda(n, n), S.Integers) == imageset(Lambda(m, m), S.Integers)
699
+
700
+ assert imageset(Lambda(n, 2*n), S.Integers).intersect(
701
+ imageset(Lambda(m, 2*m + 1), S.Integers)) is S.EmptySet
702
+
703
+ assert imageset(Lambda(n, 2*n), S.Integers).intersect(
704
+ imageset(Lambda(n, 2*n + 1), S.Integers)) is S.EmptySet
705
+
706
+ assert imageset(Lambda(m, 2*m), S.Integers).intersect(
707
+ imageset(Lambda(n, 3*n), S.Integers)).dummy_eq(
708
+ ImageSet(Lambda(t, 6*t), S.Integers))
709
+
710
+ assert imageset(x, x/2 + Rational(1, 3), S.Integers).intersect(S.Integers) is S.EmptySet
711
+ assert imageset(x, x/2 + S.Half, S.Integers).intersect(S.Integers) is S.Integers
712
+
713
+ # https://github.com/sympy/sympy/issues/17355
714
+ S53 = ImageSet(Lambda(n, 5*n + 3), S.Integers)
715
+ assert S53.intersect(S.Integers) == S53
716
+
717
+
718
+ def test_infinitely_indexed_set_2():
719
+ from sympy.abc import n
720
+ a = Symbol('a', integer=True)
721
+ assert imageset(Lambda(n, n), S.Integers) == \
722
+ imageset(Lambda(n, n + a), S.Integers)
723
+ assert imageset(Lambda(n, n + pi), S.Integers) == \
724
+ imageset(Lambda(n, n + a + pi), S.Integers)
725
+ assert imageset(Lambda(n, n), S.Integers) == \
726
+ imageset(Lambda(n, -n + a), S.Integers)
727
+ assert imageset(Lambda(n, -6*n), S.Integers) == \
728
+ ImageSet(Lambda(n, 6*n), S.Integers)
729
+ assert imageset(Lambda(n, 2*n + pi), S.Integers) == \
730
+ ImageSet(Lambda(n, 2*n + pi - 2), S.Integers)
731
+
732
+
733
+ def test_imageset_intersect_real():
734
+ from sympy.abc import n
735
+ assert imageset(Lambda(n, n + (n - 1)*(n + 1)*I), S.Integers).intersect(S.Reals) == FiniteSet(-1, 1)
736
+ im = (n - 1)*(n + S.Half)
737
+ assert imageset(Lambda(n, n + im*I), S.Integers
738
+ ).intersect(S.Reals) == FiniteSet(1)
739
+ assert imageset(Lambda(n, n + im*(n + 1)*I), S.Naturals0
740
+ ).intersect(S.Reals) == FiniteSet(1)
741
+ assert imageset(Lambda(n, n/2 + im.expand()*I), S.Integers
742
+ ).intersect(S.Reals) == ImageSet(Lambda(x, x/2), ConditionSet(
743
+ n, Eq(n**2 - n/2 - S(1)/2, 0), S.Integers))
744
+ assert imageset(Lambda(n, n/(1/n - 1) + im*(n + 1)*I), S.Integers
745
+ ).intersect(S.Reals) == FiniteSet(S.Half)
746
+ assert imageset(Lambda(n, n/(n - 6) +
747
+ (n - 3)*(n + 1)*I/(2*n + 2)), S.Integers).intersect(
748
+ S.Reals) == FiniteSet(-1)
749
+ assert imageset(Lambda(n, n/(n**2 - 9) +
750
+ (n - 3)*(n + 1)*I/(2*n + 2)), S.Integers).intersect(
751
+ S.Reals) is S.EmptySet
752
+ s = ImageSet(
753
+ Lambda(n, -I*(I*(2*pi*n - pi/4) + log(Abs(sqrt(-I))))),
754
+ S.Integers)
755
+ # s is unevaluated, but after intersection the result
756
+ # should be canonical
757
+ assert s.intersect(S.Reals) == imageset(
758
+ Lambda(n, 2*n*pi - pi/4), S.Integers) == ImageSet(
759
+ Lambda(n, 2*pi*n + pi*Rational(7, 4)), S.Integers)
760
+
761
+
762
+ def test_imageset_intersect_interval():
763
+ from sympy.abc import n
764
+ f1 = ImageSet(Lambda(n, n*pi), S.Integers)
765
+ f2 = ImageSet(Lambda(n, 2*n), Interval(0, pi))
766
+ f3 = ImageSet(Lambda(n, 2*n*pi + pi/2), S.Integers)
767
+ # complex expressions
768
+ f4 = ImageSet(Lambda(n, n*I*pi), S.Integers)
769
+ f5 = ImageSet(Lambda(n, 2*I*n*pi + pi/2), S.Integers)
770
+ # non-linear expressions
771
+ f6 = ImageSet(Lambda(n, log(n)), S.Integers)
772
+ f7 = ImageSet(Lambda(n, n**2), S.Integers)
773
+ f8 = ImageSet(Lambda(n, Abs(n)), S.Integers)
774
+ f9 = ImageSet(Lambda(n, exp(n)), S.Naturals0)
775
+
776
+ assert f1.intersect(Interval(-1, 1)) == FiniteSet(0)
777
+ assert f1.intersect(Interval(0, 2*pi, False, True)) == FiniteSet(0, pi)
778
+ assert f2.intersect(Interval(1, 2)) == Interval(1, 2)
779
+ assert f3.intersect(Interval(-1, 1)) == S.EmptySet
780
+ assert f3.intersect(Interval(-5, 5)) == FiniteSet(pi*Rational(-3, 2), pi/2)
781
+ assert f4.intersect(Interval(-1, 1)) == FiniteSet(0)
782
+ assert f4.intersect(Interval(1, 2)) == S.EmptySet
783
+ assert f5.intersect(Interval(0, 1)) == S.EmptySet
784
+ assert f6.intersect(Interval(0, 1)) == FiniteSet(S.Zero, log(2))
785
+ assert f7.intersect(Interval(0, 10)) == Intersection(f7, Interval(0, 10))
786
+ assert f8.intersect(Interval(0, 2)) == Intersection(f8, Interval(0, 2))
787
+ assert f9.intersect(Interval(1, 2)) == Intersection(f9, Interval(1, 2))
788
+
789
+
790
+ def test_imageset_intersect_diophantine():
791
+ from sympy.abc import m, n
792
+ # Check that same lambda variable for both ImageSets is handled correctly
793
+ img1 = ImageSet(Lambda(n, 2*n + 1), S.Integers)
794
+ img2 = ImageSet(Lambda(n, 4*n + 1), S.Integers)
795
+ assert img1.intersect(img2) == img2
796
+ # Empty solution set returned by diophantine:
797
+ assert ImageSet(Lambda(n, 2*n), S.Integers).intersect(
798
+ ImageSet(Lambda(n, 2*n + 1), S.Integers)) == S.EmptySet
799
+ # Check intersection with S.Integers:
800
+ assert ImageSet(Lambda(n, 9/n + 20*n/3), S.Integers).intersect(
801
+ S.Integers) == FiniteSet(-61, -23, 23, 61)
802
+ # Single solution (2, 3) for diophantine solution:
803
+ assert ImageSet(Lambda(n, (n - 2)**2), S.Integers).intersect(
804
+ ImageSet(Lambda(n, -(n - 3)**2), S.Integers)) == FiniteSet(0)
805
+ # Single parametric solution for diophantine solution:
806
+ assert ImageSet(Lambda(n, n**2 + 5), S.Integers).intersect(
807
+ ImageSet(Lambda(m, 2*m), S.Integers)).dummy_eq(ImageSet(
808
+ Lambda(n, 4*n**2 + 4*n + 6), S.Integers))
809
+ # 4 non-parametric solution couples for dioph. equation:
810
+ assert ImageSet(Lambda(n, n**2 - 9), S.Integers).intersect(
811
+ ImageSet(Lambda(m, -m**2), S.Integers)) == FiniteSet(-9, 0)
812
+ # Double parametric solution for diophantine solution:
813
+ assert ImageSet(Lambda(m, m**2 + 40), S.Integers).intersect(
814
+ ImageSet(Lambda(n, 41*n), S.Integers)).dummy_eq(Intersection(
815
+ ImageSet(Lambda(m, m**2 + 40), S.Integers),
816
+ ImageSet(Lambda(n, 41*n), S.Integers)))
817
+ # Check that diophantine returns *all* (8) solutions (permute=True)
818
+ assert ImageSet(Lambda(n, n**4 - 2**4), S.Integers).intersect(
819
+ ImageSet(Lambda(m, -m**4 + 3**4), S.Integers)) == FiniteSet(0, 65)
820
+ assert ImageSet(Lambda(n, pi/12 + n*5*pi/12), S.Integers).intersect(
821
+ ImageSet(Lambda(n, 7*pi/12 + n*11*pi/12), S.Integers)).dummy_eq(ImageSet(
822
+ Lambda(n, 55*pi*n/12 + 17*pi/4), S.Integers))
823
+ # TypeError raised by diophantine (#18081)
824
+ assert ImageSet(Lambda(n, n*log(2)), S.Integers).intersection(
825
+ S.Integers).dummy_eq(Intersection(ImageSet(
826
+ Lambda(n, n*log(2)), S.Integers), S.Integers))
827
+ # NotImplementedError raised by diophantine (no solver for cubic_thue)
828
+ assert ImageSet(Lambda(n, n**3 + 1), S.Integers).intersect(
829
+ ImageSet(Lambda(n, n**3), S.Integers)).dummy_eq(Intersection(
830
+ ImageSet(Lambda(n, n**3 + 1), S.Integers),
831
+ ImageSet(Lambda(n, n**3), S.Integers)))
832
+
833
+
834
+ def test_infinitely_indexed_set_3():
835
+ from sympy.abc import n, m
836
+ assert imageset(Lambda(m, 2*pi*m), S.Integers).intersect(
837
+ imageset(Lambda(n, 3*pi*n), S.Integers)).dummy_eq(
838
+ ImageSet(Lambda(t, 6*pi*t), S.Integers))
839
+ assert imageset(Lambda(n, 2*n + 1), S.Integers) == \
840
+ imageset(Lambda(n, 2*n - 1), S.Integers)
841
+ assert imageset(Lambda(n, 3*n + 2), S.Integers) == \
842
+ imageset(Lambda(n, 3*n - 1), S.Integers)
843
+
844
+
845
+ def test_ImageSet_simplification():
846
+ from sympy.abc import n, m
847
+ assert imageset(Lambda(n, n), S.Integers) == S.Integers
848
+ assert imageset(Lambda(n, sin(n)),
849
+ imageset(Lambda(m, tan(m)), S.Integers)) == \
850
+ imageset(Lambda(m, sin(tan(m))), S.Integers)
851
+ assert imageset(n, 1 + 2*n, S.Naturals) == Range(3, oo, 2)
852
+ assert imageset(n, 1 + 2*n, S.Naturals0) == Range(1, oo, 2)
853
+ assert imageset(n, 1 - 2*n, S.Naturals) == Range(-1, -oo, -2)
854
+
855
+
856
+ def test_ImageSet_contains():
857
+ assert (2, S.Half) in imageset(x, (x, 1/x), S.Integers)
858
+ assert imageset(x, x + I*3, S.Integers).intersection(S.Reals) is S.EmptySet
859
+ i = Dummy(integer=True)
860
+ q = imageset(x, x + I*y, S.Integers).intersection(S.Reals)
861
+ assert q.subs(y, I*i).intersection(S.Integers) is S.Integers
862
+ q = imageset(x, x + I*y/x, S.Integers).intersection(S.Reals)
863
+ assert q.subs(y, 0) is S.Integers
864
+ assert q.subs(y, I*i*x).intersection(S.Integers) is S.Integers
865
+ z = cos(1)**2 + sin(1)**2 - 1
866
+ q = imageset(x, x + I*z, S.Integers).intersection(S.Reals)
867
+ assert q is not S.EmptySet
868
+
869
+
870
+ def test_ComplexRegion_contains():
871
+ r = Symbol('r', real=True)
872
+ # contains in ComplexRegion
873
+ a = Interval(2, 3)
874
+ b = Interval(4, 6)
875
+ c = Interval(7, 9)
876
+ c1 = ComplexRegion(a*b)
877
+ c2 = ComplexRegion(Union(a*b, c*a))
878
+ assert 2.5 + 4.5*I in c1
879
+ assert 2 + 4*I in c1
880
+ assert 3 + 4*I in c1
881
+ assert 8 + 2.5*I in c2
882
+ assert 2.5 + 6.1*I not in c1
883
+ assert 4.5 + 3.2*I not in c1
884
+ assert c1.contains(x) == Contains(x, c1, evaluate=False)
885
+ assert c1.contains(r) == False
886
+ assert c2.contains(x) == Contains(x, c2, evaluate=False)
887
+ assert c2.contains(r) == False
888
+
889
+ r1 = Interval(0, 1)
890
+ theta1 = Interval(0, 2*S.Pi)
891
+ c3 = ComplexRegion(r1*theta1, polar=True)
892
+ assert (0.5 + I*6/10) in c3
893
+ assert (S.Half + I*6/10) in c3
894
+ assert (S.Half + .6*I) in c3
895
+ assert (0.5 + .6*I) in c3
896
+ assert I in c3
897
+ assert 1 in c3
898
+ assert 0 in c3
899
+ assert 1 + I not in c3
900
+ assert 1 - I not in c3
901
+ assert c3.contains(x) == Contains(x, c3, evaluate=False)
902
+ assert c3.contains(r + 2*I) == Contains(
903
+ r + 2*I, c3, evaluate=False) # is in fact False
904
+ assert c3.contains(1/(1 + r**2)) == Contains(
905
+ 1/(1 + r**2), c3, evaluate=False) # is in fact True
906
+
907
+ r2 = Interval(0, 3)
908
+ theta2 = Interval(pi, 2*pi, left_open=True)
909
+ c4 = ComplexRegion(r2*theta2, polar=True)
910
+ assert c4.contains(0) == True
911
+ assert c4.contains(2 + I) == False
912
+ assert c4.contains(-2 + I) == False
913
+ assert c4.contains(-2 - I) == True
914
+ assert c4.contains(2 - I) == True
915
+ assert c4.contains(-2) == False
916
+ assert c4.contains(2) == True
917
+ assert c4.contains(x) == Contains(x, c4, evaluate=False)
918
+ assert c4.contains(3/(1 + r**2)) == Contains(
919
+ 3/(1 + r**2), c4, evaluate=False) # is in fact True
920
+
921
+ raises(ValueError, lambda: ComplexRegion(r1*theta1, polar=2))
922
+
923
+
924
+ def test_symbolic_Range():
925
+ n = Symbol('n')
926
+ raises(ValueError, lambda: Range(n)[0])
927
+ raises(IndexError, lambda: Range(n, n)[0])
928
+ raises(ValueError, lambda: Range(n, n+1)[0])
929
+ raises(ValueError, lambda: Range(n).size)
930
+
931
+ n = Symbol('n', integer=True)
932
+ raises(ValueError, lambda: Range(n)[0])
933
+ raises(IndexError, lambda: Range(n, n)[0])
934
+ assert Range(n, n+1)[0] == n
935
+ raises(ValueError, lambda: Range(n).size)
936
+ assert Range(n, n+1).size == 1
937
+
938
+ n = Symbol('n', integer=True, nonnegative=True)
939
+ raises(ValueError, lambda: Range(n)[0])
940
+ raises(IndexError, lambda: Range(n, n)[0])
941
+ assert Range(n+1)[0] == 0
942
+ assert Range(n, n+1)[0] == n
943
+ assert Range(n).size == n
944
+ assert Range(n+1).size == n+1
945
+ assert Range(n, n+1).size == 1
946
+
947
+ n = Symbol('n', integer=True, positive=True)
948
+ assert Range(n)[0] == 0
949
+ assert Range(n, n+1)[0] == n
950
+ assert Range(n).size == n
951
+ assert Range(n, n+1).size == 1
952
+
953
+ m = Symbol('m', integer=True, positive=True)
954
+
955
+ assert Range(n, n+m)[0] == n
956
+ assert Range(n, n+m).size == m
957
+ assert Range(n, n+1).size == 1
958
+ assert Range(n, n+m, 2).size == floor(m/2)
959
+
960
+ m = Symbol('m', integer=True, positive=True, even=True)
961
+ assert Range(n, n+m, 2).size == m/2
962
+
963
+
964
+ def test_issue_18400():
965
+ n = Symbol('n', integer=True)
966
+ raises(ValueError, lambda: imageset(lambda x: x*2, Range(n)))
967
+
968
+ n = Symbol('n', integer=True, positive=True)
969
+ # No exception
970
+ assert imageset(lambda x: x*2, Range(n)) == imageset(lambda x: x*2, Range(n))
971
+
972
+
973
+ def test_ComplexRegion_intersect():
974
+ # Polar form
975
+ X_axis = ComplexRegion(Interval(0, oo)*FiniteSet(0, S.Pi), polar=True)
976
+
977
+ unit_disk = ComplexRegion(Interval(0, 1)*Interval(0, 2*S.Pi), polar=True)
978
+ upper_half_unit_disk = ComplexRegion(Interval(0, 1)*Interval(0, S.Pi), polar=True)
979
+ upper_half_disk = ComplexRegion(Interval(0, oo)*Interval(0, S.Pi), polar=True)
980
+ lower_half_disk = ComplexRegion(Interval(0, oo)*Interval(S.Pi, 2*S.Pi), polar=True)
981
+ right_half_disk = ComplexRegion(Interval(0, oo)*Interval(-S.Pi/2, S.Pi/2), polar=True)
982
+ first_quad_disk = ComplexRegion(Interval(0, oo)*Interval(0, S.Pi/2), polar=True)
983
+
984
+ assert upper_half_disk.intersect(unit_disk) == upper_half_unit_disk
985
+ assert right_half_disk.intersect(first_quad_disk) == first_quad_disk
986
+ assert upper_half_disk.intersect(right_half_disk) == first_quad_disk
987
+ assert upper_half_disk.intersect(lower_half_disk) == X_axis
988
+
989
+ c1 = ComplexRegion(Interval(0, 4)*Interval(0, 2*S.Pi), polar=True)
990
+ assert c1.intersect(Interval(1, 5)) == Interval(1, 4)
991
+ assert c1.intersect(Interval(4, 9)) == FiniteSet(4)
992
+ assert c1.intersect(Interval(5, 12)) is S.EmptySet
993
+
994
+ # Rectangular form
995
+ X_axis = ComplexRegion(Interval(-oo, oo)*FiniteSet(0))
996
+
997
+ unit_square = ComplexRegion(Interval(-1, 1)*Interval(-1, 1))
998
+ upper_half_unit_square = ComplexRegion(Interval(-1, 1)*Interval(0, 1))
999
+ upper_half_plane = ComplexRegion(Interval(-oo, oo)*Interval(0, oo))
1000
+ lower_half_plane = ComplexRegion(Interval(-oo, oo)*Interval(-oo, 0))
1001
+ right_half_plane = ComplexRegion(Interval(0, oo)*Interval(-oo, oo))
1002
+ first_quad_plane = ComplexRegion(Interval(0, oo)*Interval(0, oo))
1003
+
1004
+ assert upper_half_plane.intersect(unit_square) == upper_half_unit_square
1005
+ assert right_half_plane.intersect(first_quad_plane) == first_quad_plane
1006
+ assert upper_half_plane.intersect(right_half_plane) == first_quad_plane
1007
+ assert upper_half_plane.intersect(lower_half_plane) == X_axis
1008
+
1009
+ c1 = ComplexRegion(Interval(-5, 5)*Interval(-10, 10))
1010
+ assert c1.intersect(Interval(2, 7)) == Interval(2, 5)
1011
+ assert c1.intersect(Interval(5, 7)) == FiniteSet(5)
1012
+ assert c1.intersect(Interval(6, 9)) is S.EmptySet
1013
+
1014
+ # unevaluated object
1015
+ C1 = ComplexRegion(Interval(0, 1)*Interval(0, 2*S.Pi), polar=True)
1016
+ C2 = ComplexRegion(Interval(-1, 1)*Interval(-1, 1))
1017
+ assert C1.intersect(C2) == Intersection(C1, C2, evaluate=False)
1018
+
1019
+
1020
+ def test_ComplexRegion_union():
1021
+ # Polar form
1022
+ c1 = ComplexRegion(Interval(0, 1)*Interval(0, 2*S.Pi), polar=True)
1023
+ c2 = ComplexRegion(Interval(0, 1)*Interval(0, S.Pi), polar=True)
1024
+ c3 = ComplexRegion(Interval(0, oo)*Interval(0, S.Pi), polar=True)
1025
+ c4 = ComplexRegion(Interval(0, oo)*Interval(S.Pi, 2*S.Pi), polar=True)
1026
+
1027
+ p1 = Union(Interval(0, 1)*Interval(0, 2*S.Pi), Interval(0, 1)*Interval(0, S.Pi))
1028
+ p2 = Union(Interval(0, oo)*Interval(0, S.Pi), Interval(0, oo)*Interval(S.Pi, 2*S.Pi))
1029
+
1030
+ assert c1.union(c2) == ComplexRegion(p1, polar=True)
1031
+ assert c3.union(c4) == ComplexRegion(p2, polar=True)
1032
+
1033
+ # Rectangular form
1034
+ c5 = ComplexRegion(Interval(2, 5)*Interval(6, 9))
1035
+ c6 = ComplexRegion(Interval(4, 6)*Interval(10, 12))
1036
+ c7 = ComplexRegion(Interval(0, 10)*Interval(-10, 0))
1037
+ c8 = ComplexRegion(Interval(12, 16)*Interval(14, 20))
1038
+
1039
+ p3 = Union(Interval(2, 5)*Interval(6, 9), Interval(4, 6)*Interval(10, 12))
1040
+ p4 = Union(Interval(0, 10)*Interval(-10, 0), Interval(12, 16)*Interval(14, 20))
1041
+
1042
+ assert c5.union(c6) == ComplexRegion(p3)
1043
+ assert c7.union(c8) == ComplexRegion(p4)
1044
+
1045
+ assert c1.union(Interval(2, 4)) == Union(c1, Interval(2, 4), evaluate=False)
1046
+ assert c5.union(Interval(2, 4)) == Union(c5, ComplexRegion.from_real(Interval(2, 4)))
1047
+
1048
+
1049
+ def test_ComplexRegion_from_real():
1050
+ c1 = ComplexRegion(Interval(0, 1) * Interval(0, 2 * S.Pi), polar=True)
1051
+
1052
+ raises(ValueError, lambda: c1.from_real(c1))
1053
+ assert c1.from_real(Interval(-1, 1)) == ComplexRegion(Interval(-1, 1) * FiniteSet(0), False)
1054
+
1055
+
1056
+ def test_ComplexRegion_measure():
1057
+ a, b = Interval(2, 5), Interval(4, 8)
1058
+ theta1, theta2 = Interval(0, 2*S.Pi), Interval(0, S.Pi)
1059
+ c1 = ComplexRegion(a*b)
1060
+ c2 = ComplexRegion(Union(a*theta1, b*theta2), polar=True)
1061
+
1062
+ assert c1.measure == 12
1063
+ assert c2.measure == 9*pi
1064
+
1065
+
1066
+ def test_normalize_theta_set():
1067
+ # Interval
1068
+ assert normalize_theta_set(Interval(pi, 2*pi)) == \
1069
+ Union(FiniteSet(0), Interval.Ropen(pi, 2*pi))
1070
+ assert normalize_theta_set(Interval(pi*Rational(9, 2), 5*pi)) == Interval(pi/2, pi)
1071
+ assert normalize_theta_set(Interval(pi*Rational(-3, 2), pi/2)) == Interval.Ropen(0, 2*pi)
1072
+ assert normalize_theta_set(Interval.open(pi*Rational(-3, 2), pi/2)) == \
1073
+ Union(Interval.Ropen(0, pi/2), Interval.open(pi/2, 2*pi))
1074
+ assert normalize_theta_set(Interval.open(pi*Rational(-7, 2), pi*Rational(-3, 2))) == \
1075
+ Union(Interval.Ropen(0, pi/2), Interval.open(pi/2, 2*pi))
1076
+ assert normalize_theta_set(Interval(-pi/2, pi/2)) == \
1077
+ Union(Interval(0, pi/2), Interval.Ropen(pi*Rational(3, 2), 2*pi))
1078
+ assert normalize_theta_set(Interval.open(-pi/2, pi/2)) == \
1079
+ Union(Interval.Ropen(0, pi/2), Interval.open(pi*Rational(3, 2), 2*pi))
1080
+ assert normalize_theta_set(Interval(-4*pi, 3*pi)) == Interval.Ropen(0, 2*pi)
1081
+ assert normalize_theta_set(Interval(pi*Rational(-3, 2), -pi/2)) == Interval(pi/2, pi*Rational(3, 2))
1082
+ assert normalize_theta_set(Interval.open(0, 2*pi)) == Interval.open(0, 2*pi)
1083
+ assert normalize_theta_set(Interval.Ropen(-pi/2, pi/2)) == \
1084
+ Union(Interval.Ropen(0, pi/2), Interval.Ropen(pi*Rational(3, 2), 2*pi))
1085
+ assert normalize_theta_set(Interval.Lopen(-pi/2, pi/2)) == \
1086
+ Union(Interval(0, pi/2), Interval.open(pi*Rational(3, 2), 2*pi))
1087
+ assert normalize_theta_set(Interval(-pi/2, pi/2)) == \
1088
+ Union(Interval(0, pi/2), Interval.Ropen(pi*Rational(3, 2), 2*pi))
1089
+ assert normalize_theta_set(Interval.open(4*pi, pi*Rational(9, 2))) == Interval.open(0, pi/2)
1090
+ assert normalize_theta_set(Interval.Lopen(4*pi, pi*Rational(9, 2))) == Interval.Lopen(0, pi/2)
1091
+ assert normalize_theta_set(Interval.Ropen(4*pi, pi*Rational(9, 2))) == Interval.Ropen(0, pi/2)
1092
+ assert normalize_theta_set(Interval.open(3*pi, 5*pi)) == \
1093
+ Union(Interval.Ropen(0, pi), Interval.open(pi, 2*pi))
1094
+
1095
+ # FiniteSet
1096
+ assert normalize_theta_set(FiniteSet(0, pi, 3*pi)) == FiniteSet(0, pi)
1097
+ assert normalize_theta_set(FiniteSet(0, pi/2, pi, 2*pi)) == FiniteSet(0, pi/2, pi)
1098
+ assert normalize_theta_set(FiniteSet(0, -pi/2, -pi, -2*pi)) == FiniteSet(0, pi, pi*Rational(3, 2))
1099
+ assert normalize_theta_set(FiniteSet(pi*Rational(-3, 2), pi/2)) == \
1100
+ FiniteSet(pi/2)
1101
+ assert normalize_theta_set(FiniteSet(2*pi)) == FiniteSet(0)
1102
+
1103
+ # Unions
1104
+ assert normalize_theta_set(Union(Interval(0, pi/3), Interval(pi/2, pi))) == \
1105
+ Union(Interval(0, pi/3), Interval(pi/2, pi))
1106
+ assert normalize_theta_set(Union(Interval(0, pi), Interval(2*pi, pi*Rational(7, 3)))) == \
1107
+ Interval(0, pi)
1108
+
1109
+ # ValueError for non-real sets
1110
+ raises(ValueError, lambda: normalize_theta_set(S.Complexes))
1111
+
1112
+ # NotImplementedError for subset of reals
1113
+ raises(NotImplementedError, lambda: normalize_theta_set(Interval(0, 1)))
1114
+
1115
+ # NotImplementedError without pi as coefficient
1116
+ raises(NotImplementedError, lambda: normalize_theta_set(Interval(1, 2*pi)))
1117
+ raises(NotImplementedError, lambda: normalize_theta_set(Interval(2*pi, 10)))
1118
+ raises(NotImplementedError, lambda: normalize_theta_set(FiniteSet(0, 3, 3*pi)))
1119
+
1120
+
1121
+ def test_ComplexRegion_FiniteSet():
1122
+ x, y, z, a, b, c = symbols('x y z a b c')
1123
+
1124
+ # Issue #9669
1125
+ assert ComplexRegion(FiniteSet(a, b, c)*FiniteSet(x, y, z)) == \
1126
+ FiniteSet(a + I*x, a + I*y, a + I*z, b + I*x, b + I*y,
1127
+ b + I*z, c + I*x, c + I*y, c + I*z)
1128
+ assert ComplexRegion(FiniteSet(2)*FiniteSet(3)) == FiniteSet(2 + 3*I)
1129
+
1130
+
1131
+ def test_union_RealSubSet():
1132
+ assert (S.Complexes).union(Interval(1, 2)) == S.Complexes
1133
+ assert (S.Complexes).union(S.Integers) == S.Complexes
1134
+
1135
+
1136
+ def test_SetKind_fancySet():
1137
+ G = lambda *args: ImageSet(Lambda(x, x ** 2), *args)
1138
+ assert G(Interval(1, 4)).kind is SetKind(NumberKind)
1139
+ assert G(FiniteSet(1, 4)).kind is SetKind(NumberKind)
1140
+ assert S.Rationals.kind is SetKind(NumberKind)
1141
+ assert S.Naturals.kind is SetKind(NumberKind)
1142
+ assert S.Integers.kind is SetKind(NumberKind)
1143
+ assert Range(3).kind is SetKind(NumberKind)
1144
+ a = Interval(2, 3)
1145
+ b = Interval(4, 6)
1146
+ c1 = ComplexRegion(a*b)
1147
+ assert c1.kind is SetKind(TupleKind(NumberKind, NumberKind))
1148
+
1149
+
1150
+ def test_issue_9980():
1151
+ c1 = ComplexRegion(Interval(1, 2)*Interval(2, 3))
1152
+ c2 = ComplexRegion(Interval(1, 5)*Interval(1, 3))
1153
+ R = Union(c1, c2)
1154
+ assert simplify(R) == ComplexRegion(Union(Interval(1, 2)*Interval(2, 3), \
1155
+ Interval(1, 5)*Interval(1, 3)), False)
1156
+ assert c1.func(*c1.args) == c1
1157
+ assert R.func(*R.args) == R
1158
+
1159
+
1160
+ def test_issue_11732():
1161
+ interval12 = Interval(1, 2)
1162
+ finiteset1234 = FiniteSet(1, 2, 3, 4)
1163
+ pointComplex = Tuple(1, 5)
1164
+
1165
+ assert (interval12 in S.Naturals) == False
1166
+ assert (interval12 in S.Naturals0) == False
1167
+ assert (interval12 in S.Integers) == False
1168
+ assert (interval12 in S.Complexes) == False
1169
+
1170
+ assert (finiteset1234 in S.Naturals) == False
1171
+ assert (finiteset1234 in S.Naturals0) == False
1172
+ assert (finiteset1234 in S.Integers) == False
1173
+ assert (finiteset1234 in S.Complexes) == False
1174
+
1175
+ assert (pointComplex in S.Naturals) == False
1176
+ assert (pointComplex in S.Naturals0) == False
1177
+ assert (pointComplex in S.Integers) == False
1178
+ assert (pointComplex in S.Complexes) == True
1179
+
1180
+
1181
+ def test_issue_11730():
1182
+ unit = Interval(0, 1)
1183
+ square = ComplexRegion(unit ** 2)
1184
+
1185
+ assert Union(S.Complexes, FiniteSet(oo)) != S.Complexes
1186
+ assert Union(S.Complexes, FiniteSet(eye(4))) != S.Complexes
1187
+ assert Union(unit, square) == square
1188
+ assert Intersection(S.Reals, square) == unit
1189
+
1190
+
1191
+ def test_issue_11938():
1192
+ unit = Interval(0, 1)
1193
+ ival = Interval(1, 2)
1194
+ cr1 = ComplexRegion(ival * unit)
1195
+
1196
+ assert Intersection(cr1, S.Reals) == ival
1197
+ assert Intersection(cr1, unit) == FiniteSet(1)
1198
+
1199
+ arg1 = Interval(0, S.Pi)
1200
+ arg2 = FiniteSet(S.Pi)
1201
+ arg3 = Interval(S.Pi / 4, 3 * S.Pi / 4)
1202
+ cp1 = ComplexRegion(unit * arg1, polar=True)
1203
+ cp2 = ComplexRegion(unit * arg2, polar=True)
1204
+ cp3 = ComplexRegion(unit * arg3, polar=True)
1205
+
1206
+ assert Intersection(cp1, S.Reals) == Interval(-1, 1)
1207
+ assert Intersection(cp2, S.Reals) == Interval(-1, 0)
1208
+ assert Intersection(cp3, S.Reals) == FiniteSet(0)
1209
+
1210
+
1211
+ def test_issue_11914():
1212
+ a, b = Interval(0, 1), Interval(0, pi)
1213
+ c, d = Interval(2, 3), Interval(pi, 3 * pi / 2)
1214
+ cp1 = ComplexRegion(a * b, polar=True)
1215
+ cp2 = ComplexRegion(c * d, polar=True)
1216
+
1217
+ assert -3 in cp1.union(cp2)
1218
+ assert -3 in cp2.union(cp1)
1219
+ assert -5 not in cp1.union(cp2)
1220
+
1221
+
1222
+ def test_issue_9543():
1223
+ assert ImageSet(Lambda(x, x**2), S.Naturals).is_subset(S.Reals)
1224
+
1225
+
1226
+ def test_issue_16871():
1227
+ assert ImageSet(Lambda(x, x), FiniteSet(1)) == {1}
1228
+ assert ImageSet(Lambda(x, x - 3), S.Integers
1229
+ ).intersection(S.Integers) is S.Integers
1230
+
1231
+
1232
+ @XFAIL
1233
+ def test_issue_16871b():
1234
+ assert ImageSet(Lambda(x, x - 3), S.Integers).is_subset(S.Integers)
1235
+
1236
+
1237
+ def test_issue_18050():
1238
+ assert imageset(Lambda(x, I*x + 1), S.Integers
1239
+ ) == ImageSet(Lambda(x, I*x + 1), S.Integers)
1240
+ assert imageset(Lambda(x, 3*I*x + 4 + 8*I), S.Integers
1241
+ ) == ImageSet(Lambda(x, 3*I*x + 4 + 2*I), S.Integers)
1242
+ # no 'Mod' for next 2 tests:
1243
+ assert imageset(Lambda(x, 2*x + 3*I), S.Integers
1244
+ ) == ImageSet(Lambda(x, 2*x + 3*I), S.Integers)
1245
+ r = Symbol('r', positive=True)
1246
+ assert imageset(Lambda(x, r*x + 10), S.Integers
1247
+ ) == ImageSet(Lambda(x, r*x + 10), S.Integers)
1248
+ # reduce real part:
1249
+ assert imageset(Lambda(x, 3*x + 8 + 5*I), S.Integers
1250
+ ) == ImageSet(Lambda(x, 3*x + 2 + 5*I), S.Integers)
1251
+
1252
+
1253
+ def test_Rationals():
1254
+ assert S.Integers.is_subset(S.Rationals)
1255
+ assert S.Naturals.is_subset(S.Rationals)
1256
+ assert S.Naturals0.is_subset(S.Rationals)
1257
+ assert S.Rationals.is_subset(S.Reals)
1258
+ assert S.Rationals.inf is -oo
1259
+ assert S.Rationals.sup is oo
1260
+ it = iter(S.Rationals)
1261
+ assert [next(it) for i in range(12)] == [
1262
+ 0, 1, -1, S.Half, 2, Rational(-1, 2), -2,
1263
+ Rational(1, 3), 3, Rational(-1, 3), -3, Rational(2, 3)]
1264
+ assert Basic() not in S.Rationals
1265
+ assert S.Half in S.Rationals
1266
+ assert S.Rationals.contains(0.5) == Contains(0.5, S.Rationals, evaluate=False)
1267
+ assert 2 in S.Rationals
1268
+ r = symbols('r', rational=True)
1269
+ assert r in S.Rationals
1270
+ raises(TypeError, lambda: x in S.Rationals)
1271
+ # issue #18134:
1272
+ assert S.Rationals.boundary == S.Reals
1273
+ assert S.Rationals.closure == S.Reals
1274
+ assert S.Rationals.is_open == False
1275
+ assert S.Rationals.is_closed == False
1276
+
1277
+
1278
+ def test_NZQRC_unions():
1279
+ # check that all trivial number set unions are simplified:
1280
+ nbrsets = (S.Naturals, S.Naturals0, S.Integers, S.Rationals,
1281
+ S.Reals, S.Complexes)
1282
+ unions = (Union(a, b) for a in nbrsets for b in nbrsets)
1283
+ assert all(u.is_Union is False for u in unions)
1284
+
1285
+
1286
+ def test_imageset_intersection():
1287
+ n = Dummy()
1288
+ s = ImageSet(Lambda(n, -I*(I*(2*pi*n - pi/4) +
1289
+ log(Abs(sqrt(-I))))), S.Integers)
1290
+ assert s.intersect(S.Reals) == ImageSet(
1291
+ Lambda(n, 2*pi*n + pi*Rational(7, 4)), S.Integers)
1292
+
1293
+
1294
+ def test_issue_17858():
1295
+ assert 1 in Range(-oo, oo)
1296
+ assert 0 in Range(oo, -oo, -1)
1297
+ assert oo not in Range(-oo, oo)
1298
+ assert -oo not in Range(-oo, oo)
1299
+
1300
+ def test_issue_17859():
1301
+ r = Range(-oo,oo)
1302
+ raises(ValueError,lambda: r[::2])
1303
+ raises(ValueError, lambda: r[::-2])
1304
+ r = Range(oo,-oo,-1)
1305
+ raises(ValueError,lambda: r[::2])
1306
+ raises(ValueError, lambda: r[::-2])
venv/lib/python3.10/site-packages/sympy/sets/tests/test_ordinals.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.sets.ordinals import Ordinal, OmegaPower, ord0, omega
2
+ from sympy.testing.pytest import raises
3
+
4
+ def test_string_ordinals():
5
+ assert str(omega) == 'w'
6
+ assert str(Ordinal(OmegaPower(5, 3), OmegaPower(3, 2))) == 'w**5*3 + w**3*2'
7
+ assert str(Ordinal(OmegaPower(5, 3), OmegaPower(0, 5))) == 'w**5*3 + 5'
8
+ assert str(Ordinal(OmegaPower(1, 3), OmegaPower(0, 5))) == 'w*3 + 5'
9
+ assert str(Ordinal(OmegaPower(omega + 1, 1), OmegaPower(3, 2))) == 'w**(w + 1) + w**3*2'
10
+
11
+ def test_addition_with_integers():
12
+ assert 3 + Ordinal(OmegaPower(5, 3)) == Ordinal(OmegaPower(5, 3))
13
+ assert Ordinal(OmegaPower(5, 3))+3 == Ordinal(OmegaPower(5, 3), OmegaPower(0, 3))
14
+ assert Ordinal(OmegaPower(5, 3), OmegaPower(0, 2))+3 == \
15
+ Ordinal(OmegaPower(5, 3), OmegaPower(0, 5))
16
+
17
+
18
+ def test_addition_with_ordinals():
19
+ assert Ordinal(OmegaPower(5, 3), OmegaPower(3, 2)) + Ordinal(OmegaPower(3, 3)) == \
20
+ Ordinal(OmegaPower(5, 3), OmegaPower(3, 5))
21
+ assert Ordinal(OmegaPower(5, 3), OmegaPower(3, 2)) + Ordinal(OmegaPower(4, 2)) == \
22
+ Ordinal(OmegaPower(5, 3), OmegaPower(4, 2))
23
+ assert Ordinal(OmegaPower(omega, 2), OmegaPower(3, 2)) + Ordinal(OmegaPower(4, 2)) == \
24
+ Ordinal(OmegaPower(omega, 2), OmegaPower(4, 2))
25
+
26
+ def test_comparison():
27
+ assert Ordinal(OmegaPower(5, 3)) > Ordinal(OmegaPower(4, 3), OmegaPower(2, 1))
28
+ assert Ordinal(OmegaPower(5, 3), OmegaPower(3, 2)) < Ordinal(OmegaPower(5, 4))
29
+ assert Ordinal(OmegaPower(5, 4)) < Ordinal(OmegaPower(5, 5), OmegaPower(4, 1))
30
+
31
+ assert Ordinal(OmegaPower(5, 3), OmegaPower(3, 2)) == \
32
+ Ordinal(OmegaPower(5, 3), OmegaPower(3, 2))
33
+ assert not Ordinal(OmegaPower(5, 3), OmegaPower(3, 2)) == Ordinal(OmegaPower(5, 3))
34
+ assert Ordinal(OmegaPower(omega, 3)) > Ordinal(OmegaPower(5, 3))
35
+
36
+ def test_multiplication_with_integers():
37
+ w = omega
38
+ assert 3*w == w
39
+ assert w*9 == Ordinal(OmegaPower(1, 9))
40
+
41
+ def test_multiplication():
42
+ w = omega
43
+ assert w*(w + 1) == w*w + w
44
+ assert (w + 1)*(w + 1) == w*w + w + 1
45
+ assert w*1 == w
46
+ assert 1*w == w
47
+ assert w*ord0 == ord0
48
+ assert ord0*w == ord0
49
+ assert w**w == w * w**w
50
+ assert (w**w)*w*w == w**(w + 2)
51
+
52
+ def test_exponentiation():
53
+ w = omega
54
+ assert w**2 == w*w
55
+ assert w**3 == w*w*w
56
+ assert w**(w + 1) == Ordinal(OmegaPower(omega + 1, 1))
57
+ assert (w**w)*(w**w) == w**(w*2)
58
+
59
+ def test_comapre_not_instance():
60
+ w = OmegaPower(omega + 1, 1)
61
+ assert(not (w == None))
62
+ assert(not (w < 5))
63
+ raises(TypeError, lambda: w < 6.66)
64
+
65
+ def test_is_successort():
66
+ w = Ordinal(OmegaPower(5, 1))
67
+ assert not w.is_successor_ordinal
venv/lib/python3.10/site-packages/sympy/sets/tests/test_powerset.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.expr import unchanged
2
+ from sympy.core.singleton import S
3
+ from sympy.core.symbol import Symbol
4
+ from sympy.sets.contains import Contains
5
+ from sympy.sets.fancysets import Interval
6
+ from sympy.sets.powerset import PowerSet
7
+ from sympy.sets.sets import FiniteSet
8
+ from sympy.testing.pytest import raises, XFAIL
9
+
10
+
11
+ def test_powerset_creation():
12
+ assert unchanged(PowerSet, FiniteSet(1, 2))
13
+ assert unchanged(PowerSet, S.EmptySet)
14
+ raises(ValueError, lambda: PowerSet(123))
15
+ assert unchanged(PowerSet, S.Reals)
16
+ assert unchanged(PowerSet, S.Integers)
17
+
18
+
19
+ def test_powerset_rewrite_FiniteSet():
20
+ assert PowerSet(FiniteSet(1, 2)).rewrite(FiniteSet) == \
21
+ FiniteSet(S.EmptySet, FiniteSet(1), FiniteSet(2), FiniteSet(1, 2))
22
+ assert PowerSet(S.EmptySet).rewrite(FiniteSet) == FiniteSet(S.EmptySet)
23
+ assert PowerSet(S.Naturals).rewrite(FiniteSet) == PowerSet(S.Naturals)
24
+
25
+
26
+ def test_finiteset_rewrite_powerset():
27
+ assert FiniteSet(S.EmptySet).rewrite(PowerSet) == PowerSet(S.EmptySet)
28
+ assert FiniteSet(
29
+ S.EmptySet, FiniteSet(1),
30
+ FiniteSet(2), FiniteSet(1, 2)).rewrite(PowerSet) == \
31
+ PowerSet(FiniteSet(1, 2))
32
+ assert FiniteSet(1, 2, 3).rewrite(PowerSet) == FiniteSet(1, 2, 3)
33
+
34
+
35
+ def test_powerset__contains__():
36
+ subset_series = [
37
+ S.EmptySet,
38
+ FiniteSet(1, 2),
39
+ S.Naturals,
40
+ S.Naturals0,
41
+ S.Integers,
42
+ S.Rationals,
43
+ S.Reals,
44
+ S.Complexes]
45
+
46
+ l = len(subset_series)
47
+ for i in range(l):
48
+ for j in range(l):
49
+ if i <= j:
50
+ assert subset_series[i] in \
51
+ PowerSet(subset_series[j], evaluate=False)
52
+ else:
53
+ assert subset_series[i] not in \
54
+ PowerSet(subset_series[j], evaluate=False)
55
+
56
+
57
+ @XFAIL
58
+ def test_failing_powerset__contains__():
59
+ # XXX These are failing when evaluate=True,
60
+ # but using unevaluated PowerSet works fine.
61
+ assert FiniteSet(1, 2) not in PowerSet(S.EmptySet).rewrite(FiniteSet)
62
+ assert S.Naturals not in PowerSet(S.EmptySet).rewrite(FiniteSet)
63
+ assert S.Naturals not in PowerSet(FiniteSet(1, 2)).rewrite(FiniteSet)
64
+ assert S.Naturals0 not in PowerSet(S.EmptySet).rewrite(FiniteSet)
65
+ assert S.Naturals0 not in PowerSet(FiniteSet(1, 2)).rewrite(FiniteSet)
66
+ assert S.Integers not in PowerSet(S.EmptySet).rewrite(FiniteSet)
67
+ assert S.Integers not in PowerSet(FiniteSet(1, 2)).rewrite(FiniteSet)
68
+ assert S.Rationals not in PowerSet(S.EmptySet).rewrite(FiniteSet)
69
+ assert S.Rationals not in PowerSet(FiniteSet(1, 2)).rewrite(FiniteSet)
70
+ assert S.Reals not in PowerSet(S.EmptySet).rewrite(FiniteSet)
71
+ assert S.Reals not in PowerSet(FiniteSet(1, 2)).rewrite(FiniteSet)
72
+ assert S.Complexes not in PowerSet(S.EmptySet).rewrite(FiniteSet)
73
+ assert S.Complexes not in PowerSet(FiniteSet(1, 2)).rewrite(FiniteSet)
74
+
75
+
76
+ def test_powerset__len__():
77
+ A = PowerSet(S.EmptySet, evaluate=False)
78
+ assert len(A) == 1
79
+ A = PowerSet(A, evaluate=False)
80
+ assert len(A) == 2
81
+ A = PowerSet(A, evaluate=False)
82
+ assert len(A) == 4
83
+ A = PowerSet(A, evaluate=False)
84
+ assert len(A) == 16
85
+
86
+
87
+ def test_powerset__iter__():
88
+ a = PowerSet(FiniteSet(1, 2)).__iter__()
89
+ assert next(a) == S.EmptySet
90
+ assert next(a) == FiniteSet(1)
91
+ assert next(a) == FiniteSet(2)
92
+ assert next(a) == FiniteSet(1, 2)
93
+
94
+ a = PowerSet(S.Naturals).__iter__()
95
+ assert next(a) == S.EmptySet
96
+ assert next(a) == FiniteSet(1)
97
+ assert next(a) == FiniteSet(2)
98
+ assert next(a) == FiniteSet(1, 2)
99
+ assert next(a) == FiniteSet(3)
100
+ assert next(a) == FiniteSet(1, 3)
101
+ assert next(a) == FiniteSet(2, 3)
102
+ assert next(a) == FiniteSet(1, 2, 3)
103
+
104
+
105
+ def test_powerset_contains():
106
+ A = PowerSet(FiniteSet(1), evaluate=False)
107
+ assert A.contains(2) == Contains(2, A)
108
+
109
+ x = Symbol('x')
110
+
111
+ A = PowerSet(FiniteSet(x), evaluate=False)
112
+ assert A.contains(FiniteSet(1)) == Contains(FiniteSet(1), A)
113
+
114
+
115
+ def test_powerset_method():
116
+ # EmptySet
117
+ A = FiniteSet()
118
+ pset = A.powerset()
119
+ assert len(pset) == 1
120
+ assert pset == FiniteSet(S.EmptySet)
121
+
122
+ # FiniteSets
123
+ A = FiniteSet(1, 2)
124
+ pset = A.powerset()
125
+ assert len(pset) == 2**len(A)
126
+ assert pset == FiniteSet(FiniteSet(), FiniteSet(1),
127
+ FiniteSet(2), A)
128
+ # Not finite sets
129
+ A = Interval(0, 1)
130
+ assert A.powerset() == PowerSet(A)
131
+
132
+ def test_is_subset():
133
+ # covers line 101-102
134
+ # initialize powerset(1), which is a subset of powerset(1,2)
135
+ subset = PowerSet(FiniteSet(1))
136
+ pset = PowerSet(FiniteSet(1, 2))
137
+ bad_set = PowerSet(FiniteSet(2, 3))
138
+ # assert "subset" is subset of pset == True
139
+ assert subset.is_subset(pset)
140
+ # assert "bad_set" is subset of pset == False
141
+ assert not pset.is_subset(bad_set)
venv/lib/python3.10/site-packages/sympy/sets/tests/test_setexpr.py ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.sets.setexpr import SetExpr
2
+ from sympy.sets import Interval, FiniteSet, Intersection, ImageSet, Union
3
+
4
+ from sympy.core.expr import Expr
5
+ from sympy.core.function import Lambda
6
+ from sympy.core.numbers import (I, Rational, oo)
7
+ from sympy.core.singleton import S
8
+ from sympy.core.symbol import (Dummy, Symbol, symbols)
9
+ from sympy.functions.elementary.exponential import (exp, log)
10
+ from sympy.functions.elementary.miscellaneous import (Max, Min, sqrt)
11
+ from sympy.functions.elementary.trigonometric import cos
12
+ from sympy.sets.sets import Set
13
+
14
+
15
+ a, x = symbols("a, x")
16
+ _d = Dummy("d")
17
+
18
+
19
+ def test_setexpr():
20
+ se = SetExpr(Interval(0, 1))
21
+ assert isinstance(se.set, Set)
22
+ assert isinstance(se, Expr)
23
+
24
+
25
+ def test_scalar_funcs():
26
+ assert SetExpr(Interval(0, 1)).set == Interval(0, 1)
27
+ a, b = Symbol('a', real=True), Symbol('b', real=True)
28
+ a, b = 1, 2
29
+ # TODO: add support for more functions in the future:
30
+ for f in [exp, log]:
31
+ input_se = f(SetExpr(Interval(a, b)))
32
+ output = input_se.set
33
+ expected = Interval(Min(f(a), f(b)), Max(f(a), f(b)))
34
+ assert output == expected
35
+
36
+
37
+ def test_Add_Mul():
38
+ assert (SetExpr(Interval(0, 1)) + 1).set == Interval(1, 2)
39
+ assert (SetExpr(Interval(0, 1))*2).set == Interval(0, 2)
40
+
41
+
42
+ def test_Pow():
43
+ assert (SetExpr(Interval(0, 2))**2).set == Interval(0, 4)
44
+
45
+
46
+ def test_compound():
47
+ assert (exp(SetExpr(Interval(0, 1))*2 + 1)).set == \
48
+ Interval(exp(1), exp(3))
49
+
50
+
51
+ def test_Interval_Interval():
52
+ assert (SetExpr(Interval(1, 2)) + SetExpr(Interval(10, 20))).set == \
53
+ Interval(11, 22)
54
+ assert (SetExpr(Interval(1, 2))*SetExpr(Interval(10, 20))).set == \
55
+ Interval(10, 40)
56
+
57
+
58
+ def test_FiniteSet_FiniteSet():
59
+ assert (SetExpr(FiniteSet(1, 2, 3)) + SetExpr(FiniteSet(1, 2))).set == \
60
+ FiniteSet(2, 3, 4, 5)
61
+ assert (SetExpr(FiniteSet(1, 2, 3))*SetExpr(FiniteSet(1, 2))).set == \
62
+ FiniteSet(1, 2, 3, 4, 6)
63
+
64
+
65
+ def test_Interval_FiniteSet():
66
+ assert (SetExpr(FiniteSet(1, 2)) + SetExpr(Interval(0, 10))).set == \
67
+ Interval(1, 12)
68
+
69
+
70
+ def test_Many_Sets():
71
+ assert (SetExpr(Interval(0, 1)) +
72
+ SetExpr(Interval(2, 3)) +
73
+ SetExpr(FiniteSet(10, 11, 12))).set == Interval(12, 16)
74
+
75
+
76
+ def test_same_setexprs_are_not_identical():
77
+ a = SetExpr(FiniteSet(0, 1))
78
+ b = SetExpr(FiniteSet(0, 1))
79
+ assert (a + b).set == FiniteSet(0, 1, 2)
80
+
81
+ # Cannot detect the set being the same:
82
+ # assert (a + a).set == FiniteSet(0, 2)
83
+
84
+
85
+ def test_Interval_arithmetic():
86
+ i12cc = SetExpr(Interval(1, 2))
87
+ i12lo = SetExpr(Interval.Lopen(1, 2))
88
+ i12ro = SetExpr(Interval.Ropen(1, 2))
89
+ i12o = SetExpr(Interval.open(1, 2))
90
+
91
+ n23cc = SetExpr(Interval(-2, 3))
92
+ n23lo = SetExpr(Interval.Lopen(-2, 3))
93
+ n23ro = SetExpr(Interval.Ropen(-2, 3))
94
+ n23o = SetExpr(Interval.open(-2, 3))
95
+
96
+ n3n2cc = SetExpr(Interval(-3, -2))
97
+
98
+ assert i12cc + i12cc == SetExpr(Interval(2, 4))
99
+ assert i12cc - i12cc == SetExpr(Interval(-1, 1))
100
+ assert i12cc*i12cc == SetExpr(Interval(1, 4))
101
+ assert i12cc/i12cc == SetExpr(Interval(S.Half, 2))
102
+ assert i12cc**2 == SetExpr(Interval(1, 4))
103
+ assert i12cc**3 == SetExpr(Interval(1, 8))
104
+
105
+ assert i12lo + i12ro == SetExpr(Interval.open(2, 4))
106
+ assert i12lo - i12ro == SetExpr(Interval.Lopen(-1, 1))
107
+ assert i12lo*i12ro == SetExpr(Interval.open(1, 4))
108
+ assert i12lo/i12ro == SetExpr(Interval.Lopen(S.Half, 2))
109
+ assert i12lo + i12lo == SetExpr(Interval.Lopen(2, 4))
110
+ assert i12lo - i12lo == SetExpr(Interval.open(-1, 1))
111
+ assert i12lo*i12lo == SetExpr(Interval.Lopen(1, 4))
112
+ assert i12lo/i12lo == SetExpr(Interval.open(S.Half, 2))
113
+ assert i12lo + i12cc == SetExpr(Interval.Lopen(2, 4))
114
+ assert i12lo - i12cc == SetExpr(Interval.Lopen(-1, 1))
115
+ assert i12lo*i12cc == SetExpr(Interval.Lopen(1, 4))
116
+ assert i12lo/i12cc == SetExpr(Interval.Lopen(S.Half, 2))
117
+ assert i12lo + i12o == SetExpr(Interval.open(2, 4))
118
+ assert i12lo - i12o == SetExpr(Interval.open(-1, 1))
119
+ assert i12lo*i12o == SetExpr(Interval.open(1, 4))
120
+ assert i12lo/i12o == SetExpr(Interval.open(S.Half, 2))
121
+ assert i12lo**2 == SetExpr(Interval.Lopen(1, 4))
122
+ assert i12lo**3 == SetExpr(Interval.Lopen(1, 8))
123
+
124
+ assert i12ro + i12ro == SetExpr(Interval.Ropen(2, 4))
125
+ assert i12ro - i12ro == SetExpr(Interval.open(-1, 1))
126
+ assert i12ro*i12ro == SetExpr(Interval.Ropen(1, 4))
127
+ assert i12ro/i12ro == SetExpr(Interval.open(S.Half, 2))
128
+ assert i12ro + i12cc == SetExpr(Interval.Ropen(2, 4))
129
+ assert i12ro - i12cc == SetExpr(Interval.Ropen(-1, 1))
130
+ assert i12ro*i12cc == SetExpr(Interval.Ropen(1, 4))
131
+ assert i12ro/i12cc == SetExpr(Interval.Ropen(S.Half, 2))
132
+ assert i12ro + i12o == SetExpr(Interval.open(2, 4))
133
+ assert i12ro - i12o == SetExpr(Interval.open(-1, 1))
134
+ assert i12ro*i12o == SetExpr(Interval.open(1, 4))
135
+ assert i12ro/i12o == SetExpr(Interval.open(S.Half, 2))
136
+ assert i12ro**2 == SetExpr(Interval.Ropen(1, 4))
137
+ assert i12ro**3 == SetExpr(Interval.Ropen(1, 8))
138
+
139
+ assert i12o + i12lo == SetExpr(Interval.open(2, 4))
140
+ assert i12o - i12lo == SetExpr(Interval.open(-1, 1))
141
+ assert i12o*i12lo == SetExpr(Interval.open(1, 4))
142
+ assert i12o/i12lo == SetExpr(Interval.open(S.Half, 2))
143
+ assert i12o + i12ro == SetExpr(Interval.open(2, 4))
144
+ assert i12o - i12ro == SetExpr(Interval.open(-1, 1))
145
+ assert i12o*i12ro == SetExpr(Interval.open(1, 4))
146
+ assert i12o/i12ro == SetExpr(Interval.open(S.Half, 2))
147
+ assert i12o + i12cc == SetExpr(Interval.open(2, 4))
148
+ assert i12o - i12cc == SetExpr(Interval.open(-1, 1))
149
+ assert i12o*i12cc == SetExpr(Interval.open(1, 4))
150
+ assert i12o/i12cc == SetExpr(Interval.open(S.Half, 2))
151
+ assert i12o**2 == SetExpr(Interval.open(1, 4))
152
+ assert i12o**3 == SetExpr(Interval.open(1, 8))
153
+
154
+ assert n23cc + n23cc == SetExpr(Interval(-4, 6))
155
+ assert n23cc - n23cc == SetExpr(Interval(-5, 5))
156
+ assert n23cc*n23cc == SetExpr(Interval(-6, 9))
157
+ assert n23cc/n23cc == SetExpr(Interval.open(-oo, oo))
158
+ assert n23cc + n23ro == SetExpr(Interval.Ropen(-4, 6))
159
+ assert n23cc - n23ro == SetExpr(Interval.Lopen(-5, 5))
160
+ assert n23cc*n23ro == SetExpr(Interval.Ropen(-6, 9))
161
+ assert n23cc/n23ro == SetExpr(Interval.Lopen(-oo, oo))
162
+ assert n23cc + n23lo == SetExpr(Interval.Lopen(-4, 6))
163
+ assert n23cc - n23lo == SetExpr(Interval.Ropen(-5, 5))
164
+ assert n23cc*n23lo == SetExpr(Interval(-6, 9))
165
+ assert n23cc/n23lo == SetExpr(Interval.open(-oo, oo))
166
+ assert n23cc + n23o == SetExpr(Interval.open(-4, 6))
167
+ assert n23cc - n23o == SetExpr(Interval.open(-5, 5))
168
+ assert n23cc*n23o == SetExpr(Interval.open(-6, 9))
169
+ assert n23cc/n23o == SetExpr(Interval.open(-oo, oo))
170
+ assert n23cc**2 == SetExpr(Interval(0, 9))
171
+ assert n23cc**3 == SetExpr(Interval(-8, 27))
172
+
173
+ n32cc = SetExpr(Interval(-3, 2))
174
+ n32lo = SetExpr(Interval.Lopen(-3, 2))
175
+ n32ro = SetExpr(Interval.Ropen(-3, 2))
176
+ assert n32cc*n32lo == SetExpr(Interval.Ropen(-6, 9))
177
+ assert n32cc*n32cc == SetExpr(Interval(-6, 9))
178
+ assert n32lo*n32cc == SetExpr(Interval.Ropen(-6, 9))
179
+ assert n32cc*n32ro == SetExpr(Interval(-6, 9))
180
+ assert n32lo*n32ro == SetExpr(Interval.Ropen(-6, 9))
181
+ assert n32cc/n32lo == SetExpr(Interval.Ropen(-oo, oo))
182
+ assert i12cc/n32lo == SetExpr(Interval.Ropen(-oo, oo))
183
+
184
+ assert n3n2cc**2 == SetExpr(Interval(4, 9))
185
+ assert n3n2cc**3 == SetExpr(Interval(-27, -8))
186
+
187
+ assert n23cc + i12cc == SetExpr(Interval(-1, 5))
188
+ assert n23cc - i12cc == SetExpr(Interval(-4, 2))
189
+ assert n23cc*i12cc == SetExpr(Interval(-4, 6))
190
+ assert n23cc/i12cc == SetExpr(Interval(-2, 3))
191
+
192
+
193
+ def test_SetExpr_Intersection():
194
+ x, y, z, w = symbols("x y z w")
195
+ set1 = Interval(x, y)
196
+ set2 = Interval(w, z)
197
+ inter = Intersection(set1, set2)
198
+ se = SetExpr(inter)
199
+ assert exp(se).set == Intersection(
200
+ ImageSet(Lambda(x, exp(x)), set1),
201
+ ImageSet(Lambda(x, exp(x)), set2))
202
+ assert cos(se).set == ImageSet(Lambda(x, cos(x)), inter)
203
+
204
+
205
+ def test_SetExpr_Interval_div():
206
+ # TODO: some expressions cannot be calculated due to bugs (currently
207
+ # commented):
208
+ assert SetExpr(Interval(-3, -2))/SetExpr(Interval(-2, 1)) == SetExpr(Interval(-oo, oo))
209
+ assert SetExpr(Interval(2, 3))/SetExpr(Interval(-2, 2)) == SetExpr(Interval(-oo, oo))
210
+
211
+ assert SetExpr(Interval(-3, -2))/SetExpr(Interval(0, 4)) == SetExpr(Interval(-oo, Rational(-1, 2)))
212
+ assert SetExpr(Interval(2, 4))/SetExpr(Interval(-3, 0)) == SetExpr(Interval(-oo, Rational(-2, 3)))
213
+ assert SetExpr(Interval(2, 4))/SetExpr(Interval(0, 3)) == SetExpr(Interval(Rational(2, 3), oo))
214
+
215
+ # assert SetExpr(Interval(0, 1))/SetExpr(Interval(0, 1)) == SetExpr(Interval(0, oo))
216
+ # assert SetExpr(Interval(-1, 0))/SetExpr(Interval(0, 1)) == SetExpr(Interval(-oo, 0))
217
+ assert SetExpr(Interval(-1, 2))/SetExpr(Interval(-2, 2)) == SetExpr(Interval(-oo, oo))
218
+
219
+ assert 1/SetExpr(Interval(-1, 2)) == SetExpr(Union(Interval(-oo, -1), Interval(S.Half, oo)))
220
+
221
+ assert 1/SetExpr(Interval(0, 2)) == SetExpr(Interval(S.Half, oo))
222
+ assert (-1)/SetExpr(Interval(0, 2)) == SetExpr(Interval(-oo, Rational(-1, 2)))
223
+ assert 1/SetExpr(Interval(-oo, 0)) == SetExpr(Interval.open(-oo, 0))
224
+ assert 1/SetExpr(Interval(-1, 0)) == SetExpr(Interval(-oo, -1))
225
+ # assert (-2)/SetExpr(Interval(-oo, 0)) == SetExpr(Interval(0, oo))
226
+ # assert 1/SetExpr(Interval(-oo, -1)) == SetExpr(Interval(-1, 0))
227
+
228
+ # assert SetExpr(Interval(1, 2))/a == Mul(SetExpr(Interval(1, 2)), 1/a, evaluate=False)
229
+
230
+ # assert SetExpr(Interval(1, 2))/0 == SetExpr(Interval(1, 2))*zoo
231
+ # assert SetExpr(Interval(1, oo))/oo == SetExpr(Interval(0, oo))
232
+ # assert SetExpr(Interval(1, oo))/(-oo) == SetExpr(Interval(-oo, 0))
233
+ # assert SetExpr(Interval(-oo, -1))/oo == SetExpr(Interval(-oo, 0))
234
+ # assert SetExpr(Interval(-oo, -1))/(-oo) == SetExpr(Interval(0, oo))
235
+ # assert SetExpr(Interval(-oo, oo))/oo == SetExpr(Interval(-oo, oo))
236
+ # assert SetExpr(Interval(-oo, oo))/(-oo) == SetExpr(Interval(-oo, oo))
237
+ # assert SetExpr(Interval(-1, oo))/oo == SetExpr(Interval(0, oo))
238
+ # assert SetExpr(Interval(-1, oo))/(-oo) == SetExpr(Interval(-oo, 0))
239
+ # assert SetExpr(Interval(-oo, 1))/oo == SetExpr(Interval(-oo, 0))
240
+ # assert SetExpr(Interval(-oo, 1))/(-oo) == SetExpr(Interval(0, oo))
241
+
242
+
243
+ def test_SetExpr_Interval_pow():
244
+ assert SetExpr(Interval(0, 2))**2 == SetExpr(Interval(0, 4))
245
+ assert SetExpr(Interval(-1, 1))**2 == SetExpr(Interval(0, 1))
246
+ assert SetExpr(Interval(1, 2))**2 == SetExpr(Interval(1, 4))
247
+ assert SetExpr(Interval(-1, 2))**3 == SetExpr(Interval(-1, 8))
248
+ assert SetExpr(Interval(-1, 1))**0 == SetExpr(FiniteSet(1))
249
+
250
+
251
+ assert SetExpr(Interval(1, 2))**Rational(5, 2) == SetExpr(Interval(1, 4*sqrt(2)))
252
+ #assert SetExpr(Interval(-1, 2))**Rational(1, 3) == SetExpr(Interval(-1, 2**Rational(1, 3)))
253
+ #assert SetExpr(Interval(0, 2))**S.Half == SetExpr(Interval(0, sqrt(2)))
254
+
255
+ #assert SetExpr(Interval(-4, 2))**Rational(2, 3) == SetExpr(Interval(0, 2*2**Rational(1, 3)))
256
+
257
+ #assert SetExpr(Interval(-1, 5))**S.Half == SetExpr(Interval(0, sqrt(5)))
258
+ #assert SetExpr(Interval(-oo, 2))**S.Half == SetExpr(Interval(0, sqrt(2)))
259
+ #assert SetExpr(Interval(-2, 3))**(Rational(-1, 4)) == SetExpr(Interval(0, oo))
260
+
261
+ assert SetExpr(Interval(1, 5))**(-2) == SetExpr(Interval(Rational(1, 25), 1))
262
+ assert SetExpr(Interval(-1, 3))**(-2) == SetExpr(Interval(0, oo))
263
+
264
+ assert SetExpr(Interval(0, 2))**(-2) == SetExpr(Interval(Rational(1, 4), oo))
265
+ assert SetExpr(Interval(-1, 2))**(-3) == SetExpr(Union(Interval(-oo, -1), Interval(Rational(1, 8), oo)))
266
+ assert SetExpr(Interval(-3, -2))**(-3) == SetExpr(Interval(Rational(-1, 8), Rational(-1, 27)))
267
+ assert SetExpr(Interval(-3, -2))**(-2) == SetExpr(Interval(Rational(1, 9), Rational(1, 4)))
268
+ #assert SetExpr(Interval(0, oo))**S.Half == SetExpr(Interval(0, oo))
269
+ #assert SetExpr(Interval(-oo, -1))**Rational(1, 3) == SetExpr(Interval(-oo, -1))
270
+ #assert SetExpr(Interval(-2, 3))**(Rational(-1, 3)) == SetExpr(Interval(-oo, oo))
271
+
272
+ assert SetExpr(Interval(-oo, 0))**(-2) == SetExpr(Interval.open(0, oo))
273
+ assert SetExpr(Interval(-2, 0))**(-2) == SetExpr(Interval(Rational(1, 4), oo))
274
+
275
+ assert SetExpr(Interval(Rational(1, 3), S.Half))**oo == SetExpr(FiniteSet(0))
276
+ assert SetExpr(Interval(0, S.Half))**oo == SetExpr(FiniteSet(0))
277
+ assert SetExpr(Interval(S.Half, 1))**oo == SetExpr(Interval(0, oo))
278
+ assert SetExpr(Interval(0, 1))**oo == SetExpr(Interval(0, oo))
279
+ assert SetExpr(Interval(2, 3))**oo == SetExpr(FiniteSet(oo))
280
+ assert SetExpr(Interval(1, 2))**oo == SetExpr(Interval(0, oo))
281
+ assert SetExpr(Interval(S.Half, 3))**oo == SetExpr(Interval(0, oo))
282
+ assert SetExpr(Interval(Rational(-1, 3), Rational(-1, 4)))**oo == SetExpr(FiniteSet(0))
283
+ assert SetExpr(Interval(-1, Rational(-1, 2)))**oo == SetExpr(Interval(-oo, oo))
284
+ assert SetExpr(Interval(-3, -2))**oo == SetExpr(FiniteSet(-oo, oo))
285
+ assert SetExpr(Interval(-2, -1))**oo == SetExpr(Interval(-oo, oo))
286
+ assert SetExpr(Interval(-2, Rational(-1, 2)))**oo == SetExpr(Interval(-oo, oo))
287
+ assert SetExpr(Interval(Rational(-1, 2), S.Half))**oo == SetExpr(FiniteSet(0))
288
+ assert SetExpr(Interval(Rational(-1, 2), 1))**oo == SetExpr(Interval(0, oo))
289
+ assert SetExpr(Interval(Rational(-2, 3), 2))**oo == SetExpr(Interval(0, oo))
290
+ assert SetExpr(Interval(-1, 1))**oo == SetExpr(Interval(-oo, oo))
291
+ assert SetExpr(Interval(-1, S.Half))**oo == SetExpr(Interval(-oo, oo))
292
+ assert SetExpr(Interval(-1, 2))**oo == SetExpr(Interval(-oo, oo))
293
+ assert SetExpr(Interval(-2, S.Half))**oo == SetExpr(Interval(-oo, oo))
294
+
295
+ assert (SetExpr(Interval(1, 2))**x).dummy_eq(SetExpr(ImageSet(Lambda(_d, _d**x), Interval(1, 2))))
296
+
297
+ assert SetExpr(Interval(2, 3))**(-oo) == SetExpr(FiniteSet(0))
298
+ assert SetExpr(Interval(0, 2))**(-oo) == SetExpr(Interval(0, oo))
299
+ assert (SetExpr(Interval(-1, 2))**(-oo)).dummy_eq(SetExpr(ImageSet(Lambda(_d, _d**(-oo)), Interval(-1, 2))))
300
+
301
+
302
+ def test_SetExpr_Integers():
303
+ assert SetExpr(S.Integers) + 1 == SetExpr(S.Integers)
304
+ assert (SetExpr(S.Integers) + I).dummy_eq(
305
+ SetExpr(ImageSet(Lambda(_d, _d + I), S.Integers)))
306
+ assert SetExpr(S.Integers)*(-1) == SetExpr(S.Integers)
307
+ assert (SetExpr(S.Integers)*2).dummy_eq(
308
+ SetExpr(ImageSet(Lambda(_d, 2*_d), S.Integers)))
309
+ assert (SetExpr(S.Integers)*I).dummy_eq(
310
+ SetExpr(ImageSet(Lambda(_d, I*_d), S.Integers)))
311
+ # issue #18050:
312
+ assert SetExpr(S.Integers)._eval_func(Lambda(x, I*x + 1)).dummy_eq(
313
+ SetExpr(ImageSet(Lambda(_d, I*_d + 1), S.Integers)))
314
+ # needs improvement:
315
+ assert (SetExpr(S.Integers)*I + 1).dummy_eq(
316
+ SetExpr(ImageSet(Lambda(x, x + 1),
317
+ ImageSet(Lambda(_d, _d*I), S.Integers))))
venv/lib/python3.10/site-packages/sympy/sets/tests/test_sets.py ADDED
@@ -0,0 +1,1704 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.concrete.summations import Sum
2
+ from sympy.core.add import Add
3
+ from sympy.core.containers import TupleKind
4
+ from sympy.core.function import Lambda
5
+ from sympy.core.kind import NumberKind, UndefinedKind
6
+ from sympy.core.numbers import (Float, I, Rational, nan, oo, pi, zoo)
7
+ from sympy.core.power import Pow
8
+ from sympy.core.singleton import S
9
+ from sympy.core.symbol import (Symbol, symbols)
10
+ from sympy.core.sympify import sympify
11
+ from sympy.functions.elementary.miscellaneous import (Max, Min, sqrt)
12
+ from sympy.functions.elementary.piecewise import Piecewise
13
+ from sympy.functions.elementary.trigonometric import (cos, sin)
14
+ from sympy.logic.boolalg import (false, true)
15
+ from sympy.matrices.common import MatrixKind
16
+ from sympy.matrices.dense import Matrix
17
+ from sympy.polys.rootoftools import rootof
18
+ from sympy.sets.contains import Contains
19
+ from sympy.sets.fancysets import (ImageSet, Range)
20
+ from sympy.sets.sets import (Complement, DisjointUnion, FiniteSet, Intersection, Interval, ProductSet, Set, SymmetricDifference, Union, imageset, SetKind)
21
+ from mpmath import mpi
22
+
23
+ from sympy.core.expr import unchanged
24
+ from sympy.core.relational import Eq, Ne, Le, Lt, LessThan
25
+ from sympy.logic import And, Or, Xor
26
+ from sympy.testing.pytest import raises, XFAIL, warns_deprecated_sympy
27
+
28
+ from sympy.abc import x, y, z, m, n
29
+
30
+ EmptySet = S.EmptySet
31
+
32
+ def test_imageset():
33
+ ints = S.Integers
34
+ assert imageset(x, x - 1, S.Naturals) is S.Naturals0
35
+ assert imageset(x, x + 1, S.Naturals0) is S.Naturals
36
+ assert imageset(x, abs(x), S.Naturals0) is S.Naturals0
37
+ assert imageset(x, abs(x), S.Naturals) is S.Naturals
38
+ assert imageset(x, abs(x), S.Integers) is S.Naturals0
39
+ # issue 16878a
40
+ r = symbols('r', real=True)
41
+ assert imageset(x, (x, x), S.Reals)._contains((1, r)) == None
42
+ assert imageset(x, (x, x), S.Reals)._contains((1, 2)) == False
43
+ assert (r, r) in imageset(x, (x, x), S.Reals)
44
+ assert 1 + I in imageset(x, x + I, S.Reals)
45
+ assert {1} not in imageset(x, (x,), S.Reals)
46
+ assert (1, 1) not in imageset(x, (x,), S.Reals)
47
+ raises(TypeError, lambda: imageset(x, ints))
48
+ raises(ValueError, lambda: imageset(x, y, z, ints))
49
+ raises(ValueError, lambda: imageset(Lambda(x, cos(x)), y))
50
+ assert (1, 2) in imageset(Lambda((x, y), (x, y)), ints, ints)
51
+ raises(ValueError, lambda: imageset(Lambda(x, x), ints, ints))
52
+ assert imageset(cos, ints) == ImageSet(Lambda(x, cos(x)), ints)
53
+ def f(x):
54
+ return cos(x)
55
+ assert imageset(f, ints) == imageset(x, cos(x), ints)
56
+ f = lambda x: cos(x)
57
+ assert imageset(f, ints) == ImageSet(Lambda(x, cos(x)), ints)
58
+ assert imageset(x, 1, ints) == FiniteSet(1)
59
+ assert imageset(x, y, ints) == {y}
60
+ assert imageset((x, y), (1, z), ints, S.Reals) == {(1, z)}
61
+ clash = Symbol('x', integer=true)
62
+ assert (str(imageset(lambda x: x + clash, Interval(-2, 1)).lamda.expr)
63
+ in ('x0 + x', 'x + x0'))
64
+ x1, x2 = symbols("x1, x2")
65
+ assert imageset(lambda x, y:
66
+ Add(x, y), Interval(1, 2), Interval(2, 3)).dummy_eq(
67
+ ImageSet(Lambda((x1, x2), x1 + x2),
68
+ Interval(1, 2), Interval(2, 3)))
69
+
70
+
71
+ def test_is_empty():
72
+ for s in [S.Naturals, S.Naturals0, S.Integers, S.Rationals, S.Reals,
73
+ S.UniversalSet]:
74
+ assert s.is_empty is False
75
+
76
+ assert S.EmptySet.is_empty is True
77
+
78
+
79
+ def test_is_finiteset():
80
+ for s in [S.Naturals, S.Naturals0, S.Integers, S.Rationals, S.Reals,
81
+ S.UniversalSet]:
82
+ assert s.is_finite_set is False
83
+
84
+ assert S.EmptySet.is_finite_set is True
85
+
86
+ assert FiniteSet(1, 2).is_finite_set is True
87
+ assert Interval(1, 2).is_finite_set is False
88
+ assert Interval(x, y).is_finite_set is None
89
+ assert ProductSet(FiniteSet(1), FiniteSet(2)).is_finite_set is True
90
+ assert ProductSet(FiniteSet(1), Interval(1, 2)).is_finite_set is False
91
+ assert ProductSet(FiniteSet(1), Interval(x, y)).is_finite_set is None
92
+ assert Union(Interval(0, 1), Interval(2, 3)).is_finite_set is False
93
+ assert Union(FiniteSet(1), Interval(2, 3)).is_finite_set is False
94
+ assert Union(FiniteSet(1), FiniteSet(2)).is_finite_set is True
95
+ assert Union(FiniteSet(1), Interval(x, y)).is_finite_set is None
96
+ assert Intersection(Interval(x, y), FiniteSet(1)).is_finite_set is True
97
+ assert Intersection(Interval(x, y), Interval(1, 2)).is_finite_set is None
98
+ assert Intersection(FiniteSet(x), FiniteSet(y)).is_finite_set is True
99
+ assert Complement(FiniteSet(1), Interval(x, y)).is_finite_set is True
100
+ assert Complement(Interval(x, y), FiniteSet(1)).is_finite_set is None
101
+ assert Complement(Interval(1, 2), FiniteSet(x)).is_finite_set is False
102
+ assert DisjointUnion(Interval(-5, 3), FiniteSet(x, y)).is_finite_set is False
103
+ assert DisjointUnion(S.EmptySet, FiniteSet(x, y), S.EmptySet).is_finite_set is True
104
+
105
+
106
+ def test_deprecated_is_EmptySet():
107
+ with warns_deprecated_sympy():
108
+ S.EmptySet.is_EmptySet
109
+
110
+ with warns_deprecated_sympy():
111
+ FiniteSet(1).is_EmptySet
112
+
113
+
114
+ def test_interval_arguments():
115
+ assert Interval(0, oo) == Interval(0, oo, False, True)
116
+ assert Interval(0, oo).right_open is true
117
+ assert Interval(-oo, 0) == Interval(-oo, 0, True, False)
118
+ assert Interval(-oo, 0).left_open is true
119
+ assert Interval(oo, -oo) == S.EmptySet
120
+ assert Interval(oo, oo) == S.EmptySet
121
+ assert Interval(-oo, -oo) == S.EmptySet
122
+ assert Interval(oo, x) == S.EmptySet
123
+ assert Interval(oo, oo) == S.EmptySet
124
+ assert Interval(x, -oo) == S.EmptySet
125
+ assert Interval(x, x) == {x}
126
+
127
+ assert isinstance(Interval(1, 1), FiniteSet)
128
+ e = Sum(x, (x, 1, 3))
129
+ assert isinstance(Interval(e, e), FiniteSet)
130
+
131
+ assert Interval(1, 0) == S.EmptySet
132
+ assert Interval(1, 1).measure == 0
133
+
134
+ assert Interval(1, 1, False, True) == S.EmptySet
135
+ assert Interval(1, 1, True, False) == S.EmptySet
136
+ assert Interval(1, 1, True, True) == S.EmptySet
137
+
138
+
139
+ assert isinstance(Interval(0, Symbol('a')), Interval)
140
+ assert Interval(Symbol('a', positive=True), 0) == S.EmptySet
141
+ raises(ValueError, lambda: Interval(0, S.ImaginaryUnit))
142
+ raises(ValueError, lambda: Interval(0, Symbol('z', extended_real=False)))
143
+ raises(ValueError, lambda: Interval(x, x + S.ImaginaryUnit))
144
+
145
+ raises(NotImplementedError, lambda: Interval(0, 1, And(x, y)))
146
+ raises(NotImplementedError, lambda: Interval(0, 1, False, And(x, y)))
147
+ raises(NotImplementedError, lambda: Interval(0, 1, z, And(x, y)))
148
+
149
+
150
+ def test_interval_symbolic_end_points():
151
+ a = Symbol('a', real=True)
152
+
153
+ assert Union(Interval(0, a), Interval(0, 3)).sup == Max(a, 3)
154
+ assert Union(Interval(a, 0), Interval(-3, 0)).inf == Min(-3, a)
155
+
156
+ assert Interval(0, a).contains(1) == LessThan(1, a)
157
+
158
+
159
+ def test_interval_is_empty():
160
+ x, y = symbols('x, y')
161
+ r = Symbol('r', real=True)
162
+ p = Symbol('p', positive=True)
163
+ n = Symbol('n', negative=True)
164
+ nn = Symbol('nn', nonnegative=True)
165
+ assert Interval(1, 2).is_empty == False
166
+ assert Interval(3, 3).is_empty == False # FiniteSet
167
+ assert Interval(r, r).is_empty == False # FiniteSet
168
+ assert Interval(r, r + nn).is_empty == False
169
+ assert Interval(x, x).is_empty == False
170
+ assert Interval(1, oo).is_empty == False
171
+ assert Interval(-oo, oo).is_empty == False
172
+ assert Interval(-oo, 1).is_empty == False
173
+ assert Interval(x, y).is_empty == None
174
+ assert Interval(r, oo).is_empty == False # real implies finite
175
+ assert Interval(n, 0).is_empty == False
176
+ assert Interval(n, 0, left_open=True).is_empty == False
177
+ assert Interval(p, 0).is_empty == True # EmptySet
178
+ assert Interval(nn, 0).is_empty == None
179
+ assert Interval(n, p).is_empty == False
180
+ assert Interval(0, p, left_open=True).is_empty == False
181
+ assert Interval(0, p, right_open=True).is_empty == False
182
+ assert Interval(0, nn, left_open=True).is_empty == None
183
+ assert Interval(0, nn, right_open=True).is_empty == None
184
+
185
+
186
+ def test_union():
187
+ assert Union(Interval(1, 2), Interval(2, 3)) == Interval(1, 3)
188
+ assert Union(Interval(1, 2), Interval(2, 3, True)) == Interval(1, 3)
189
+ assert Union(Interval(1, 3), Interval(2, 4)) == Interval(1, 4)
190
+ assert Union(Interval(1, 2), Interval(1, 3)) == Interval(1, 3)
191
+ assert Union(Interval(1, 3), Interval(1, 2)) == Interval(1, 3)
192
+ assert Union(Interval(1, 3, False, True), Interval(1, 2)) == \
193
+ Interval(1, 3, False, True)
194
+ assert Union(Interval(1, 3), Interval(1, 2, False, True)) == Interval(1, 3)
195
+ assert Union(Interval(1, 2, True), Interval(1, 3)) == Interval(1, 3)
196
+ assert Union(Interval(1, 2, True), Interval(1, 3, True)) == \
197
+ Interval(1, 3, True)
198
+ assert Union(Interval(1, 2, True), Interval(1, 3, True, True)) == \
199
+ Interval(1, 3, True, True)
200
+ assert Union(Interval(1, 2, True, True), Interval(1, 3, True)) == \
201
+ Interval(1, 3, True)
202
+ assert Union(Interval(1, 3), Interval(2, 3)) == Interval(1, 3)
203
+ assert Union(Interval(1, 3, False, True), Interval(2, 3)) == \
204
+ Interval(1, 3)
205
+ assert Union(Interval(1, 2, False, True), Interval(2, 3, True)) != \
206
+ Interval(1, 3)
207
+ assert Union(Interval(1, 2), S.EmptySet) == Interval(1, 2)
208
+ assert Union(S.EmptySet) == S.EmptySet
209
+
210
+ assert Union(Interval(0, 1), *[FiniteSet(1.0/n) for n in range(1, 10)]) == \
211
+ Interval(0, 1)
212
+ # issue #18241:
213
+ x = Symbol('x')
214
+ assert Union(Interval(0, 1), FiniteSet(1, x)) == Union(
215
+ Interval(0, 1), FiniteSet(x))
216
+ assert unchanged(Union, Interval(0, 1), FiniteSet(2, x))
217
+
218
+ assert Interval(1, 2).union(Interval(2, 3)) == \
219
+ Interval(1, 2) + Interval(2, 3)
220
+
221
+ assert Interval(1, 2).union(Interval(2, 3)) == Interval(1, 3)
222
+
223
+ assert Union(Set()) == Set()
224
+
225
+ assert FiniteSet(1) + FiniteSet(2) + FiniteSet(3) == FiniteSet(1, 2, 3)
226
+ assert FiniteSet('ham') + FiniteSet('eggs') == FiniteSet('ham', 'eggs')
227
+ assert FiniteSet(1, 2, 3) + S.EmptySet == FiniteSet(1, 2, 3)
228
+
229
+ assert FiniteSet(1, 2, 3) & FiniteSet(2, 3, 4) == FiniteSet(2, 3)
230
+ assert FiniteSet(1, 2, 3) | FiniteSet(2, 3, 4) == FiniteSet(1, 2, 3, 4)
231
+
232
+ assert FiniteSet(1, 2, 3) & S.EmptySet == S.EmptySet
233
+ assert FiniteSet(1, 2, 3) | S.EmptySet == FiniteSet(1, 2, 3)
234
+
235
+ x = Symbol("x")
236
+ y = Symbol("y")
237
+ z = Symbol("z")
238
+ assert S.EmptySet | FiniteSet(x, FiniteSet(y, z)) == \
239
+ FiniteSet(x, FiniteSet(y, z))
240
+
241
+ # Test that Intervals and FiniteSets play nicely
242
+ assert Interval(1, 3) + FiniteSet(2) == Interval(1, 3)
243
+ assert Interval(1, 3, True, True) + FiniteSet(3) == \
244
+ Interval(1, 3, True, False)
245
+ X = Interval(1, 3) + FiniteSet(5)
246
+ Y = Interval(1, 2) + FiniteSet(3)
247
+ XandY = X.intersect(Y)
248
+ assert 2 in X and 3 in X and 3 in XandY
249
+ assert XandY.is_subset(X) and XandY.is_subset(Y)
250
+
251
+ raises(TypeError, lambda: Union(1, 2, 3))
252
+
253
+ assert X.is_iterable is False
254
+
255
+ # issue 7843
256
+ assert Union(S.EmptySet, FiniteSet(-sqrt(-I), sqrt(-I))) == \
257
+ FiniteSet(-sqrt(-I), sqrt(-I))
258
+
259
+ assert Union(S.Reals, S.Integers) == S.Reals
260
+
261
+
262
+ def test_union_iter():
263
+ # Use Range because it is ordered
264
+ u = Union(Range(3), Range(5), Range(4), evaluate=False)
265
+
266
+ # Round robin
267
+ assert list(u) == [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 4]
268
+
269
+
270
+ def test_union_is_empty():
271
+ assert (Interval(x, y) + FiniteSet(1)).is_empty == False
272
+ assert (Interval(x, y) + Interval(-x, y)).is_empty == None
273
+
274
+
275
+ def test_difference():
276
+ assert Interval(1, 3) - Interval(1, 2) == Interval(2, 3, True)
277
+ assert Interval(1, 3) - Interval(2, 3) == Interval(1, 2, False, True)
278
+ assert Interval(1, 3, True) - Interval(2, 3) == Interval(1, 2, True, True)
279
+ assert Interval(1, 3, True) - Interval(2, 3, True) == \
280
+ Interval(1, 2, True, False)
281
+ assert Interval(0, 2) - FiniteSet(1) == \
282
+ Union(Interval(0, 1, False, True), Interval(1, 2, True, False))
283
+
284
+ # issue #18119
285
+ assert S.Reals - FiniteSet(I) == S.Reals
286
+ assert S.Reals - FiniteSet(-I, I) == S.Reals
287
+ assert Interval(0, 10) - FiniteSet(-I, I) == Interval(0, 10)
288
+ assert Interval(0, 10) - FiniteSet(1, I) == Union(
289
+ Interval.Ropen(0, 1), Interval.Lopen(1, 10))
290
+ assert S.Reals - FiniteSet(1, 2 + I, x, y**2) == Complement(
291
+ Union(Interval.open(-oo, 1), Interval.open(1, oo)), FiniteSet(x, y**2),
292
+ evaluate=False)
293
+
294
+ assert FiniteSet(1, 2, 3) - FiniteSet(2) == FiniteSet(1, 3)
295
+ assert FiniteSet('ham', 'eggs') - FiniteSet('eggs') == FiniteSet('ham')
296
+ assert FiniteSet(1, 2, 3, 4) - Interval(2, 10, True, False) == \
297
+ FiniteSet(1, 2)
298
+ assert FiniteSet(1, 2, 3, 4) - S.EmptySet == FiniteSet(1, 2, 3, 4)
299
+ assert Union(Interval(0, 2), FiniteSet(2, 3, 4)) - Interval(1, 3) == \
300
+ Union(Interval(0, 1, False, True), FiniteSet(4))
301
+
302
+ assert -1 in S.Reals - S.Naturals
303
+
304
+
305
+ def test_Complement():
306
+ A = FiniteSet(1, 3, 4)
307
+ B = FiniteSet(3, 4)
308
+ C = Interval(1, 3)
309
+ D = Interval(1, 2)
310
+
311
+ assert Complement(A, B, evaluate=False).is_iterable is True
312
+ assert Complement(A, C, evaluate=False).is_iterable is True
313
+ assert Complement(C, D, evaluate=False).is_iterable is None
314
+
315
+ assert FiniteSet(*Complement(A, B, evaluate=False)) == FiniteSet(1)
316
+ assert FiniteSet(*Complement(A, C, evaluate=False)) == FiniteSet(4)
317
+ raises(TypeError, lambda: FiniteSet(*Complement(C, A, evaluate=False)))
318
+
319
+ assert Complement(Interval(1, 3), Interval(1, 2)) == Interval(2, 3, True)
320
+ assert Complement(FiniteSet(1, 3, 4), FiniteSet(3, 4)) == FiniteSet(1)
321
+ assert Complement(Union(Interval(0, 2), FiniteSet(2, 3, 4)),
322
+ Interval(1, 3)) == \
323
+ Union(Interval(0, 1, False, True), FiniteSet(4))
324
+
325
+ assert 3 not in Complement(Interval(0, 5), Interval(1, 4), evaluate=False)
326
+ assert -1 in Complement(S.Reals, S.Naturals, evaluate=False)
327
+ assert 1 not in Complement(S.Reals, S.Naturals, evaluate=False)
328
+
329
+ assert Complement(S.Integers, S.UniversalSet) == EmptySet
330
+ assert S.UniversalSet.complement(S.Integers) == EmptySet
331
+
332
+ assert (0 not in S.Reals.intersect(S.Integers - FiniteSet(0)))
333
+
334
+ assert S.EmptySet - S.Integers == S.EmptySet
335
+
336
+ assert (S.Integers - FiniteSet(0)) - FiniteSet(1) == S.Integers - FiniteSet(0, 1)
337
+
338
+ assert S.Reals - Union(S.Naturals, FiniteSet(pi)) == \
339
+ Intersection(S.Reals - S.Naturals, S.Reals - FiniteSet(pi))
340
+ # issue 12712
341
+ assert Complement(FiniteSet(x, y, 2), Interval(-10, 10)) == \
342
+ Complement(FiniteSet(x, y), Interval(-10, 10))
343
+
344
+ A = FiniteSet(*symbols('a:c'))
345
+ B = FiniteSet(*symbols('d:f'))
346
+ assert unchanged(Complement, ProductSet(A, A), B)
347
+
348
+ A2 = ProductSet(A, A)
349
+ B3 = ProductSet(B, B, B)
350
+ assert A2 - B3 == A2
351
+ assert B3 - A2 == B3
352
+
353
+
354
+ def test_set_operations_nonsets():
355
+ '''Tests that e.g. FiniteSet(1) * 2 raises TypeError'''
356
+ ops = [
357
+ lambda a, b: a + b,
358
+ lambda a, b: a - b,
359
+ lambda a, b: a * b,
360
+ lambda a, b: a / b,
361
+ lambda a, b: a // b,
362
+ lambda a, b: a | b,
363
+ lambda a, b: a & b,
364
+ lambda a, b: a ^ b,
365
+ # FiniteSet(1) ** 2 gives a ProductSet
366
+ #lambda a, b: a ** b,
367
+ ]
368
+ Sx = FiniteSet(x)
369
+ Sy = FiniteSet(y)
370
+ sets = [
371
+ {1},
372
+ FiniteSet(1),
373
+ Interval(1, 2),
374
+ Union(Sx, Interval(1, 2)),
375
+ Intersection(Sx, Sy),
376
+ Complement(Sx, Sy),
377
+ ProductSet(Sx, Sy),
378
+ S.EmptySet,
379
+ ]
380
+ nums = [0, 1, 2, S(0), S(1), S(2)]
381
+
382
+ for si in sets:
383
+ for ni in nums:
384
+ for op in ops:
385
+ raises(TypeError, lambda : op(si, ni))
386
+ raises(TypeError, lambda : op(ni, si))
387
+ raises(TypeError, lambda: si ** object())
388
+ raises(TypeError, lambda: si ** {1})
389
+
390
+
391
+ def test_complement():
392
+ assert Complement({1, 2}, {1}) == {2}
393
+ assert Interval(0, 1).complement(S.Reals) == \
394
+ Union(Interval(-oo, 0, True, True), Interval(1, oo, True, True))
395
+ assert Interval(0, 1, True, False).complement(S.Reals) == \
396
+ Union(Interval(-oo, 0, True, False), Interval(1, oo, True, True))
397
+ assert Interval(0, 1, False, True).complement(S.Reals) == \
398
+ Union(Interval(-oo, 0, True, True), Interval(1, oo, False, True))
399
+ assert Interval(0, 1, True, True).complement(S.Reals) == \
400
+ Union(Interval(-oo, 0, True, False), Interval(1, oo, False, True))
401
+
402
+ assert S.UniversalSet.complement(S.EmptySet) == S.EmptySet
403
+ assert S.UniversalSet.complement(S.Reals) == S.EmptySet
404
+ assert S.UniversalSet.complement(S.UniversalSet) == S.EmptySet
405
+
406
+ assert S.EmptySet.complement(S.Reals) == S.Reals
407
+
408
+ assert Union(Interval(0, 1), Interval(2, 3)).complement(S.Reals) == \
409
+ Union(Interval(-oo, 0, True, True), Interval(1, 2, True, True),
410
+ Interval(3, oo, True, True))
411
+
412
+ assert FiniteSet(0).complement(S.Reals) == \
413
+ Union(Interval(-oo, 0, True, True), Interval(0, oo, True, True))
414
+
415
+ assert (FiniteSet(5) + Interval(S.NegativeInfinity,
416
+ 0)).complement(S.Reals) == \
417
+ Interval(0, 5, True, True) + Interval(5, S.Infinity, True, True)
418
+
419
+ assert FiniteSet(1, 2, 3).complement(S.Reals) == \
420
+ Interval(S.NegativeInfinity, 1, True, True) + \
421
+ Interval(1, 2, True, True) + Interval(2, 3, True, True) +\
422
+ Interval(3, S.Infinity, True, True)
423
+
424
+ assert FiniteSet(x).complement(S.Reals) == Complement(S.Reals, FiniteSet(x))
425
+
426
+ assert FiniteSet(0, x).complement(S.Reals) == Complement(Interval(-oo, 0, True, True) +
427
+ Interval(0, oo, True, True)
428
+ , FiniteSet(x), evaluate=False)
429
+
430
+ square = Interval(0, 1) * Interval(0, 1)
431
+ notsquare = square.complement(S.Reals*S.Reals)
432
+
433
+ assert all(pt in square for pt in [(0, 0), (.5, .5), (1, 0), (1, 1)])
434
+ assert not any(
435
+ pt in notsquare for pt in [(0, 0), (.5, .5), (1, 0), (1, 1)])
436
+ assert not any(pt in square for pt in [(-1, 0), (1.5, .5), (10, 10)])
437
+ assert all(pt in notsquare for pt in [(-1, 0), (1.5, .5), (10, 10)])
438
+
439
+
440
+ def test_intersect1():
441
+ assert all(S.Integers.intersection(i) is i for i in
442
+ (S.Naturals, S.Naturals0))
443
+ assert all(i.intersection(S.Integers) is i for i in
444
+ (S.Naturals, S.Naturals0))
445
+ s = S.Naturals0
446
+ assert S.Naturals.intersection(s) is S.Naturals
447
+ assert s.intersection(S.Naturals) is S.Naturals
448
+ x = Symbol('x')
449
+ assert Interval(0, 2).intersect(Interval(1, 2)) == Interval(1, 2)
450
+ assert Interval(0, 2).intersect(Interval(1, 2, True)) == \
451
+ Interval(1, 2, True)
452
+ assert Interval(0, 2, True).intersect(Interval(1, 2)) == \
453
+ Interval(1, 2, False, False)
454
+ assert Interval(0, 2, True, True).intersect(Interval(1, 2)) == \
455
+ Interval(1, 2, False, True)
456
+ assert Interval(0, 2).intersect(Union(Interval(0, 1), Interval(2, 3))) == \
457
+ Union(Interval(0, 1), Interval(2, 2))
458
+
459
+ assert FiniteSet(1, 2).intersect(FiniteSet(1, 2, 3)) == FiniteSet(1, 2)
460
+ assert FiniteSet(1, 2, x).intersect(FiniteSet(x)) == FiniteSet(x)
461
+ assert FiniteSet('ham', 'eggs').intersect(FiniteSet('ham')) == \
462
+ FiniteSet('ham')
463
+ assert FiniteSet(1, 2, 3, 4, 5).intersect(S.EmptySet) == S.EmptySet
464
+
465
+ assert Interval(0, 5).intersect(FiniteSet(1, 3)) == FiniteSet(1, 3)
466
+ assert Interval(0, 1, True, True).intersect(FiniteSet(1)) == S.EmptySet
467
+
468
+ assert Union(Interval(0, 1), Interval(2, 3)).intersect(Interval(1, 2)) == \
469
+ Union(Interval(1, 1), Interval(2, 2))
470
+ assert Union(Interval(0, 1), Interval(2, 3)).intersect(Interval(0, 2)) == \
471
+ Union(Interval(0, 1), Interval(2, 2))
472
+ assert Union(Interval(0, 1), Interval(2, 3)).intersect(Interval(1, 2, True, True)) == \
473
+ S.EmptySet
474
+ assert Union(Interval(0, 1), Interval(2, 3)).intersect(S.EmptySet) == \
475
+ S.EmptySet
476
+ assert Union(Interval(0, 5), FiniteSet('ham')).intersect(FiniteSet(2, 3, 4, 5, 6)) == \
477
+ Intersection(FiniteSet(2, 3, 4, 5, 6), Union(FiniteSet('ham'), Interval(0, 5)))
478
+ assert Intersection(FiniteSet(1, 2, 3), Interval(2, x), Interval(3, y)) == \
479
+ Intersection(FiniteSet(3), Interval(2, x), Interval(3, y), evaluate=False)
480
+ assert Intersection(FiniteSet(1, 2), Interval(0, 3), Interval(x, y)) == \
481
+ Intersection({1, 2}, Interval(x, y), evaluate=False)
482
+ assert Intersection(FiniteSet(1, 2, 4), Interval(0, 3), Interval(x, y)) == \
483
+ Intersection({1, 2}, Interval(x, y), evaluate=False)
484
+ # XXX: Is the real=True necessary here?
485
+ # https://github.com/sympy/sympy/issues/17532
486
+ m, n = symbols('m, n', real=True)
487
+ assert Intersection(FiniteSet(m), FiniteSet(m, n), Interval(m, m+1)) == \
488
+ FiniteSet(m)
489
+
490
+ # issue 8217
491
+ assert Intersection(FiniteSet(x), FiniteSet(y)) == \
492
+ Intersection(FiniteSet(x), FiniteSet(y), evaluate=False)
493
+ assert FiniteSet(x).intersect(S.Reals) == \
494
+ Intersection(S.Reals, FiniteSet(x), evaluate=False)
495
+
496
+ # tests for the intersection alias
497
+ assert Interval(0, 5).intersection(FiniteSet(1, 3)) == FiniteSet(1, 3)
498
+ assert Interval(0, 1, True, True).intersection(FiniteSet(1)) == S.EmptySet
499
+
500
+ assert Union(Interval(0, 1), Interval(2, 3)).intersection(Interval(1, 2)) == \
501
+ Union(Interval(1, 1), Interval(2, 2))
502
+
503
+
504
+ def test_intersection():
505
+ # iterable
506
+ i = Intersection(FiniteSet(1, 2, 3), Interval(2, 5), evaluate=False)
507
+ assert i.is_iterable
508
+ assert set(i) == {S(2), S(3)}
509
+
510
+ # challenging intervals
511
+ x = Symbol('x', real=True)
512
+ i = Intersection(Interval(0, 3), Interval(x, 6))
513
+ assert (5 in i) is False
514
+ raises(TypeError, lambda: 2 in i)
515
+
516
+ # Singleton special cases
517
+ assert Intersection(Interval(0, 1), S.EmptySet) == S.EmptySet
518
+ assert Intersection(Interval(-oo, oo), Interval(-oo, x)) == Interval(-oo, x)
519
+
520
+ # Products
521
+ line = Interval(0, 5)
522
+ i = Intersection(line**2, line**3, evaluate=False)
523
+ assert (2, 2) not in i
524
+ assert (2, 2, 2) not in i
525
+ raises(TypeError, lambda: list(i))
526
+
527
+ a = Intersection(Intersection(S.Integers, S.Naturals, evaluate=False), S.Reals, evaluate=False)
528
+ assert a._argset == frozenset([Intersection(S.Naturals, S.Integers, evaluate=False), S.Reals])
529
+
530
+ assert Intersection(S.Complexes, FiniteSet(S.ComplexInfinity)) == S.EmptySet
531
+
532
+ # issue 12178
533
+ assert Intersection() == S.UniversalSet
534
+
535
+ # issue 16987
536
+ assert Intersection({1}, {1}, {x}) == Intersection({1}, {x})
537
+
538
+
539
+ def test_issue_9623():
540
+ n = Symbol('n')
541
+
542
+ a = S.Reals
543
+ b = Interval(0, oo)
544
+ c = FiniteSet(n)
545
+
546
+ assert Intersection(a, b, c) == Intersection(b, c)
547
+ assert Intersection(Interval(1, 2), Interval(3, 4), FiniteSet(n)) == EmptySet
548
+
549
+
550
+ def test_is_disjoint():
551
+ assert Interval(0, 2).is_disjoint(Interval(1, 2)) == False
552
+ assert Interval(0, 2).is_disjoint(Interval(3, 4)) == True
553
+
554
+
555
+ def test_ProductSet__len__():
556
+ A = FiniteSet(1, 2)
557
+ B = FiniteSet(1, 2, 3)
558
+ assert ProductSet(A).__len__() == 2
559
+ assert ProductSet(A).__len__() is not S(2)
560
+ assert ProductSet(A, B).__len__() == 6
561
+ assert ProductSet(A, B).__len__() is not S(6)
562
+
563
+
564
+ def test_ProductSet():
565
+ # ProductSet is always a set of Tuples
566
+ assert ProductSet(S.Reals) == S.Reals ** 1
567
+ assert ProductSet(S.Reals, S.Reals) == S.Reals ** 2
568
+ assert ProductSet(S.Reals, S.Reals, S.Reals) == S.Reals ** 3
569
+
570
+ assert ProductSet(S.Reals) != S.Reals
571
+ assert ProductSet(S.Reals, S.Reals) == S.Reals * S.Reals
572
+ assert ProductSet(S.Reals, S.Reals, S.Reals) != S.Reals * S.Reals * S.Reals
573
+ assert ProductSet(S.Reals, S.Reals, S.Reals) == (S.Reals * S.Reals * S.Reals).flatten()
574
+
575
+ assert 1 not in ProductSet(S.Reals)
576
+ assert (1,) in ProductSet(S.Reals)
577
+
578
+ assert 1 not in ProductSet(S.Reals, S.Reals)
579
+ assert (1, 2) in ProductSet(S.Reals, S.Reals)
580
+ assert (1, I) not in ProductSet(S.Reals, S.Reals)
581
+
582
+ assert (1, 2, 3) in ProductSet(S.Reals, S.Reals, S.Reals)
583
+ assert (1, 2, 3) in S.Reals ** 3
584
+ assert (1, 2, 3) not in S.Reals * S.Reals * S.Reals
585
+ assert ((1, 2), 3) in S.Reals * S.Reals * S.Reals
586
+ assert (1, (2, 3)) not in S.Reals * S.Reals * S.Reals
587
+ assert (1, (2, 3)) in S.Reals * (S.Reals * S.Reals)
588
+
589
+ assert ProductSet() == FiniteSet(())
590
+ assert ProductSet(S.Reals, S.EmptySet) == S.EmptySet
591
+
592
+ # See GH-17458
593
+
594
+ for ni in range(5):
595
+ Rn = ProductSet(*(S.Reals,) * ni)
596
+ assert (1,) * ni in Rn
597
+ assert 1 not in Rn
598
+
599
+ assert (S.Reals * S.Reals) * S.Reals != S.Reals * (S.Reals * S.Reals)
600
+
601
+ S1 = S.Reals
602
+ S2 = S.Integers
603
+ x1 = pi
604
+ x2 = 3
605
+ assert x1 in S1
606
+ assert x2 in S2
607
+ assert (x1, x2) in S1 * S2
608
+ S3 = S1 * S2
609
+ x3 = (x1, x2)
610
+ assert x3 in S3
611
+ assert (x3, x3) in S3 * S3
612
+ assert x3 + x3 not in S3 * S3
613
+
614
+ raises(ValueError, lambda: S.Reals**-1)
615
+ with warns_deprecated_sympy():
616
+ ProductSet(FiniteSet(s) for s in range(2))
617
+ raises(TypeError, lambda: ProductSet(None))
618
+
619
+ S1 = FiniteSet(1, 2)
620
+ S2 = FiniteSet(3, 4)
621
+ S3 = ProductSet(S1, S2)
622
+ assert (S3.as_relational(x, y)
623
+ == And(S1.as_relational(x), S2.as_relational(y))
624
+ == And(Or(Eq(x, 1), Eq(x, 2)), Or(Eq(y, 3), Eq(y, 4))))
625
+ raises(ValueError, lambda: S3.as_relational(x))
626
+ raises(ValueError, lambda: S3.as_relational(x, 1))
627
+ raises(ValueError, lambda: ProductSet(Interval(0, 1)).as_relational(x, y))
628
+
629
+ Z2 = ProductSet(S.Integers, S.Integers)
630
+ assert Z2.contains((1, 2)) is S.true
631
+ assert Z2.contains((1,)) is S.false
632
+ assert Z2.contains(x) == Contains(x, Z2, evaluate=False)
633
+ assert Z2.contains(x).subs(x, 1) is S.false
634
+ assert Z2.contains((x, 1)).subs(x, 2) is S.true
635
+ assert Z2.contains((x, y)) == Contains((x, y), Z2, evaluate=False)
636
+ assert unchanged(Contains, (x, y), Z2)
637
+ assert Contains((1, 2), Z2) is S.true
638
+
639
+
640
+ def test_ProductSet_of_single_arg_is_not_arg():
641
+ assert unchanged(ProductSet, Interval(0, 1))
642
+ assert unchanged(ProductSet, ProductSet(Interval(0, 1)))
643
+
644
+
645
+ def test_ProductSet_is_empty():
646
+ assert ProductSet(S.Integers, S.Reals).is_empty == False
647
+ assert ProductSet(Interval(x, 1), S.Reals).is_empty == None
648
+
649
+
650
+ def test_interval_subs():
651
+ a = Symbol('a', real=True)
652
+
653
+ assert Interval(0, a).subs(a, 2) == Interval(0, 2)
654
+ assert Interval(a, 0).subs(a, 2) == S.EmptySet
655
+
656
+
657
+ def test_interval_to_mpi():
658
+ assert Interval(0, 1).to_mpi() == mpi(0, 1)
659
+ assert Interval(0, 1, True, False).to_mpi() == mpi(0, 1)
660
+ assert type(Interval(0, 1).to_mpi()) == type(mpi(0, 1))
661
+
662
+
663
+ def test_set_evalf():
664
+ assert Interval(S(11)/64, S.Half).evalf() == Interval(
665
+ Float('0.171875'), Float('0.5'))
666
+ assert Interval(x, S.Half, right_open=True).evalf() == Interval(
667
+ x, Float('0.5'), right_open=True)
668
+ assert Interval(-oo, S.Half).evalf() == Interval(-oo, Float('0.5'))
669
+ assert FiniteSet(2, x).evalf() == FiniteSet(Float('2.0'), x)
670
+
671
+
672
+ def test_measure():
673
+ a = Symbol('a', real=True)
674
+
675
+ assert Interval(1, 3).measure == 2
676
+ assert Interval(0, a).measure == a
677
+ assert Interval(1, a).measure == a - 1
678
+
679
+ assert Union(Interval(1, 2), Interval(3, 4)).measure == 2
680
+ assert Union(Interval(1, 2), Interval(3, 4), FiniteSet(5, 6, 7)).measure \
681
+ == 2
682
+
683
+ assert FiniteSet(1, 2, oo, a, -oo, -5).measure == 0
684
+
685
+ assert S.EmptySet.measure == 0
686
+
687
+ square = Interval(0, 10) * Interval(0, 10)
688
+ offsetsquare = Interval(5, 15) * Interval(5, 15)
689
+ band = Interval(-oo, oo) * Interval(2, 4)
690
+
691
+ assert square.measure == offsetsquare.measure == 100
692
+ assert (square + offsetsquare).measure == 175 # there is some overlap
693
+ assert (square - offsetsquare).measure == 75
694
+ assert (square * FiniteSet(1, 2, 3)).measure == 0
695
+ assert (square.intersect(band)).measure == 20
696
+ assert (square + band).measure is oo
697
+ assert (band * FiniteSet(1, 2, 3)).measure is nan
698
+
699
+
700
+ def test_is_subset():
701
+ assert Interval(0, 1).is_subset(Interval(0, 2)) is True
702
+ assert Interval(0, 3).is_subset(Interval(0, 2)) is False
703
+ assert Interval(0, 1).is_subset(FiniteSet(0, 1)) is False
704
+
705
+ assert FiniteSet(1, 2).is_subset(FiniteSet(1, 2, 3, 4))
706
+ assert FiniteSet(4, 5).is_subset(FiniteSet(1, 2, 3, 4)) is False
707
+ assert FiniteSet(1).is_subset(Interval(0, 2))
708
+ assert FiniteSet(1, 2).is_subset(Interval(0, 2, True, True)) is False
709
+ assert (Interval(1, 2) + FiniteSet(3)).is_subset(
710
+ Interval(0, 2, False, True) + FiniteSet(2, 3))
711
+
712
+ assert Interval(3, 4).is_subset(Union(Interval(0, 1), Interval(2, 5))) is True
713
+ assert Interval(3, 6).is_subset(Union(Interval(0, 1), Interval(2, 5))) is False
714
+
715
+ assert FiniteSet(1, 2, 3, 4).is_subset(Interval(0, 5)) is True
716
+ assert S.EmptySet.is_subset(FiniteSet(1, 2, 3)) is True
717
+
718
+ assert Interval(0, 1).is_subset(S.EmptySet) is False
719
+ assert S.EmptySet.is_subset(S.EmptySet) is True
720
+
721
+ raises(ValueError, lambda: S.EmptySet.is_subset(1))
722
+
723
+ # tests for the issubset alias
724
+ assert FiniteSet(1, 2, 3, 4).issubset(Interval(0, 5)) is True
725
+ assert S.EmptySet.issubset(FiniteSet(1, 2, 3)) is True
726
+
727
+ assert S.Naturals.is_subset(S.Integers)
728
+ assert S.Naturals0.is_subset(S.Integers)
729
+
730
+ assert FiniteSet(x).is_subset(FiniteSet(y)) is None
731
+ assert FiniteSet(x).is_subset(FiniteSet(y).subs(y, x)) is True
732
+ assert FiniteSet(x).is_subset(FiniteSet(y).subs(y, x+1)) is False
733
+
734
+ assert Interval(0, 1).is_subset(Interval(0, 1, left_open=True)) is False
735
+ assert Interval(-2, 3).is_subset(Union(Interval(-oo, -2), Interval(3, oo))) is False
736
+
737
+ n = Symbol('n', integer=True)
738
+ assert Range(-3, 4, 1).is_subset(FiniteSet(-10, 10)) is False
739
+ assert Range(S(10)**100).is_subset(FiniteSet(0, 1, 2)) is False
740
+ assert Range(6, 0, -2).is_subset(FiniteSet(2, 4, 6)) is True
741
+ assert Range(1, oo).is_subset(FiniteSet(1, 2)) is False
742
+ assert Range(-oo, 1).is_subset(FiniteSet(1)) is False
743
+ assert Range(3).is_subset(FiniteSet(0, 1, n)) is None
744
+ assert Range(n, n + 2).is_subset(FiniteSet(n, n + 1)) is True
745
+ assert Range(5).is_subset(Interval(0, 4, right_open=True)) is False
746
+ #issue 19513
747
+ assert imageset(Lambda(n, 1/n), S.Integers).is_subset(S.Reals) is None
748
+
749
+ def test_is_proper_subset():
750
+ assert Interval(0, 1).is_proper_subset(Interval(0, 2)) is True
751
+ assert Interval(0, 3).is_proper_subset(Interval(0, 2)) is False
752
+ assert S.EmptySet.is_proper_subset(FiniteSet(1, 2, 3)) is True
753
+
754
+ raises(ValueError, lambda: Interval(0, 1).is_proper_subset(0))
755
+
756
+
757
+ def test_is_superset():
758
+ assert Interval(0, 1).is_superset(Interval(0, 2)) == False
759
+ assert Interval(0, 3).is_superset(Interval(0, 2))
760
+
761
+ assert FiniteSet(1, 2).is_superset(FiniteSet(1, 2, 3, 4)) == False
762
+ assert FiniteSet(4, 5).is_superset(FiniteSet(1, 2, 3, 4)) == False
763
+ assert FiniteSet(1).is_superset(Interval(0, 2)) == False
764
+ assert FiniteSet(1, 2).is_superset(Interval(0, 2, True, True)) == False
765
+ assert (Interval(1, 2) + FiniteSet(3)).is_superset(
766
+ Interval(0, 2, False, True) + FiniteSet(2, 3)) == False
767
+
768
+ assert Interval(3, 4).is_superset(Union(Interval(0, 1), Interval(2, 5))) == False
769
+
770
+ assert FiniteSet(1, 2, 3, 4).is_superset(Interval(0, 5)) == False
771
+ assert S.EmptySet.is_superset(FiniteSet(1, 2, 3)) == False
772
+
773
+ assert Interval(0, 1).is_superset(S.EmptySet) == True
774
+ assert S.EmptySet.is_superset(S.EmptySet) == True
775
+
776
+ raises(ValueError, lambda: S.EmptySet.is_superset(1))
777
+
778
+ # tests for the issuperset alias
779
+ assert Interval(0, 1).issuperset(S.EmptySet) == True
780
+ assert S.EmptySet.issuperset(S.EmptySet) == True
781
+
782
+
783
+ def test_is_proper_superset():
784
+ assert Interval(0, 1).is_proper_superset(Interval(0, 2)) is False
785
+ assert Interval(0, 3).is_proper_superset(Interval(0, 2)) is True
786
+ assert FiniteSet(1, 2, 3).is_proper_superset(S.EmptySet) is True
787
+
788
+ raises(ValueError, lambda: Interval(0, 1).is_proper_superset(0))
789
+
790
+
791
+ def test_contains():
792
+ assert Interval(0, 2).contains(1) is S.true
793
+ assert Interval(0, 2).contains(3) is S.false
794
+ assert Interval(0, 2, True, False).contains(0) is S.false
795
+ assert Interval(0, 2, True, False).contains(2) is S.true
796
+ assert Interval(0, 2, False, True).contains(0) is S.true
797
+ assert Interval(0, 2, False, True).contains(2) is S.false
798
+ assert Interval(0, 2, True, True).contains(0) is S.false
799
+ assert Interval(0, 2, True, True).contains(2) is S.false
800
+
801
+ assert (Interval(0, 2) in Interval(0, 2)) is False
802
+
803
+ assert FiniteSet(1, 2, 3).contains(2) is S.true
804
+ assert FiniteSet(1, 2, Symbol('x')).contains(Symbol('x')) is S.true
805
+
806
+ assert FiniteSet(y)._contains(x) is None
807
+ raises(TypeError, lambda: x in FiniteSet(y))
808
+ assert FiniteSet({x, y})._contains({x}) is None
809
+ assert FiniteSet({x, y}).subs(y, x)._contains({x}) is True
810
+ assert FiniteSet({x, y}).subs(y, x+1)._contains({x}) is False
811
+
812
+ # issue 8197
813
+ from sympy.abc import a, b
814
+ assert isinstance(FiniteSet(b).contains(-a), Contains)
815
+ assert isinstance(FiniteSet(b).contains(a), Contains)
816
+ assert isinstance(FiniteSet(a).contains(1), Contains)
817
+ raises(TypeError, lambda: 1 in FiniteSet(a))
818
+
819
+ # issue 8209
820
+ rad1 = Pow(Pow(2, Rational(1, 3)) - 1, Rational(1, 3))
821
+ rad2 = Pow(Rational(1, 9), Rational(1, 3)) - Pow(Rational(2, 9), Rational(1, 3)) + Pow(Rational(4, 9), Rational(1, 3))
822
+ s1 = FiniteSet(rad1)
823
+ s2 = FiniteSet(rad2)
824
+ assert s1 - s2 == S.EmptySet
825
+
826
+ items = [1, 2, S.Infinity, S('ham'), -1.1]
827
+ fset = FiniteSet(*items)
828
+ assert all(item in fset for item in items)
829
+ assert all(fset.contains(item) is S.true for item in items)
830
+
831
+ assert Union(Interval(0, 1), Interval(2, 5)).contains(3) is S.true
832
+ assert Union(Interval(0, 1), Interval(2, 5)).contains(6) is S.false
833
+ assert Union(Interval(0, 1), FiniteSet(2, 5)).contains(3) is S.false
834
+
835
+ assert S.EmptySet.contains(1) is S.false
836
+ assert FiniteSet(rootof(x**3 + x - 1, 0)).contains(S.Infinity) is S.false
837
+
838
+ assert rootof(x**5 + x**3 + 1, 0) in S.Reals
839
+ assert not rootof(x**5 + x**3 + 1, 1) in S.Reals
840
+
841
+ # non-bool results
842
+ assert Union(Interval(1, 2), Interval(3, 4)).contains(x) == \
843
+ Or(And(S.One <= x, x <= 2), And(S(3) <= x, x <= 4))
844
+ assert Intersection(Interval(1, x), Interval(2, 3)).contains(y) == \
845
+ And(y <= 3, y <= x, S.One <= y, S(2) <= y)
846
+
847
+ assert (S.Complexes).contains(S.ComplexInfinity) == S.false
848
+
849
+
850
+ def test_interval_symbolic():
851
+ x = Symbol('x')
852
+ e = Interval(0, 1)
853
+ assert e.contains(x) == And(S.Zero <= x, x <= 1)
854
+ raises(TypeError, lambda: x in e)
855
+ e = Interval(0, 1, True, True)
856
+ assert e.contains(x) == And(S.Zero < x, x < 1)
857
+ c = Symbol('c', real=False)
858
+ assert Interval(x, x + 1).contains(c) == False
859
+ e = Symbol('e', extended_real=True)
860
+ assert Interval(-oo, oo).contains(e) == And(
861
+ S.NegativeInfinity < e, e < S.Infinity)
862
+
863
+
864
+ def test_union_contains():
865
+ x = Symbol('x')
866
+ i1 = Interval(0, 1)
867
+ i2 = Interval(2, 3)
868
+ i3 = Union(i1, i2)
869
+ assert i3.as_relational(x) == Or(And(S.Zero <= x, x <= 1), And(S(2) <= x, x <= 3))
870
+ raises(TypeError, lambda: x in i3)
871
+ e = i3.contains(x)
872
+ assert e == i3.as_relational(x)
873
+ assert e.subs(x, -0.5) is false
874
+ assert e.subs(x, 0.5) is true
875
+ assert e.subs(x, 1.5) is false
876
+ assert e.subs(x, 2.5) is true
877
+ assert e.subs(x, 3.5) is false
878
+
879
+ U = Interval(0, 2, True, True) + Interval(10, oo) + FiniteSet(-1, 2, 5, 6)
880
+ assert all(el not in U for el in [0, 4, -oo])
881
+ assert all(el in U for el in [2, 5, 10])
882
+
883
+
884
+ def test_is_number():
885
+ assert Interval(0, 1).is_number is False
886
+ assert Set().is_number is False
887
+
888
+
889
+ def test_Interval_is_left_unbounded():
890
+ assert Interval(3, 4).is_left_unbounded is False
891
+ assert Interval(-oo, 3).is_left_unbounded is True
892
+ assert Interval(Float("-inf"), 3).is_left_unbounded is True
893
+
894
+
895
+ def test_Interval_is_right_unbounded():
896
+ assert Interval(3, 4).is_right_unbounded is False
897
+ assert Interval(3, oo).is_right_unbounded is True
898
+ assert Interval(3, Float("+inf")).is_right_unbounded is True
899
+
900
+
901
+ def test_Interval_as_relational():
902
+ x = Symbol('x')
903
+
904
+ assert Interval(-1, 2, False, False).as_relational(x) == \
905
+ And(Le(-1, x), Le(x, 2))
906
+ assert Interval(-1, 2, True, False).as_relational(x) == \
907
+ And(Lt(-1, x), Le(x, 2))
908
+ assert Interval(-1, 2, False, True).as_relational(x) == \
909
+ And(Le(-1, x), Lt(x, 2))
910
+ assert Interval(-1, 2, True, True).as_relational(x) == \
911
+ And(Lt(-1, x), Lt(x, 2))
912
+
913
+ assert Interval(-oo, 2, right_open=False).as_relational(x) == And(Lt(-oo, x), Le(x, 2))
914
+ assert Interval(-oo, 2, right_open=True).as_relational(x) == And(Lt(-oo, x), Lt(x, 2))
915
+
916
+ assert Interval(-2, oo, left_open=False).as_relational(x) == And(Le(-2, x), Lt(x, oo))
917
+ assert Interval(-2, oo, left_open=True).as_relational(x) == And(Lt(-2, x), Lt(x, oo))
918
+
919
+ assert Interval(-oo, oo).as_relational(x) == And(Lt(-oo, x), Lt(x, oo))
920
+ x = Symbol('x', real=True)
921
+ y = Symbol('y', real=True)
922
+ assert Interval(x, y).as_relational(x) == (x <= y)
923
+ assert Interval(y, x).as_relational(x) == (y <= x)
924
+
925
+
926
+ def test_Finite_as_relational():
927
+ x = Symbol('x')
928
+ y = Symbol('y')
929
+
930
+ assert FiniteSet(1, 2).as_relational(x) == Or(Eq(x, 1), Eq(x, 2))
931
+ assert FiniteSet(y, -5).as_relational(x) == Or(Eq(x, y), Eq(x, -5))
932
+
933
+
934
+ def test_Union_as_relational():
935
+ x = Symbol('x')
936
+ assert (Interval(0, 1) + FiniteSet(2)).as_relational(x) == \
937
+ Or(And(Le(0, x), Le(x, 1)), Eq(x, 2))
938
+ assert (Interval(0, 1, True, True) + FiniteSet(1)).as_relational(x) == \
939
+ And(Lt(0, x), Le(x, 1))
940
+ assert Or(x < 0, x > 0).as_set().as_relational(x) == \
941
+ And((x > -oo), (x < oo), Ne(x, 0))
942
+ assert (Interval.Ropen(1, 3) + Interval.Lopen(3, 5)
943
+ ).as_relational(x) == And(Ne(x,3),(x>=1),(x<=5))
944
+
945
+
946
+ def test_Intersection_as_relational():
947
+ x = Symbol('x')
948
+ assert (Intersection(Interval(0, 1), FiniteSet(2),
949
+ evaluate=False).as_relational(x)
950
+ == And(And(Le(0, x), Le(x, 1)), Eq(x, 2)))
951
+
952
+
953
+ def test_Complement_as_relational():
954
+ x = Symbol('x')
955
+ expr = Complement(Interval(0, 1), FiniteSet(2), evaluate=False)
956
+ assert expr.as_relational(x) == \
957
+ And(Le(0, x), Le(x, 1), Ne(x, 2))
958
+
959
+
960
+ @XFAIL
961
+ def test_Complement_as_relational_fail():
962
+ x = Symbol('x')
963
+ expr = Complement(Interval(0, 1), FiniteSet(2), evaluate=False)
964
+ # XXX This example fails because 0 <= x changes to x >= 0
965
+ # during the evaluation.
966
+ assert expr.as_relational(x) == \
967
+ (0 <= x) & (x <= 1) & Ne(x, 2)
968
+
969
+
970
+ def test_SymmetricDifference_as_relational():
971
+ x = Symbol('x')
972
+ expr = SymmetricDifference(Interval(0, 1), FiniteSet(2), evaluate=False)
973
+ assert expr.as_relational(x) == Xor(Eq(x, 2), Le(0, x) & Le(x, 1))
974
+
975
+
976
+ def test_EmptySet():
977
+ assert S.EmptySet.as_relational(Symbol('x')) is S.false
978
+ assert S.EmptySet.intersect(S.UniversalSet) == S.EmptySet
979
+ assert S.EmptySet.boundary == S.EmptySet
980
+
981
+
982
+ def test_finite_basic():
983
+ x = Symbol('x')
984
+ A = FiniteSet(1, 2, 3)
985
+ B = FiniteSet(3, 4, 5)
986
+ AorB = Union(A, B)
987
+ AandB = A.intersect(B)
988
+ assert A.is_subset(AorB) and B.is_subset(AorB)
989
+ assert AandB.is_subset(A)
990
+ assert AandB == FiniteSet(3)
991
+
992
+ assert A.inf == 1 and A.sup == 3
993
+ assert AorB.inf == 1 and AorB.sup == 5
994
+ assert FiniteSet(x, 1, 5).sup == Max(x, 5)
995
+ assert FiniteSet(x, 1, 5).inf == Min(x, 1)
996
+
997
+ # issue 7335
998
+ assert FiniteSet(S.EmptySet) != S.EmptySet
999
+ assert FiniteSet(FiniteSet(1, 2, 3)) != FiniteSet(1, 2, 3)
1000
+ assert FiniteSet((1, 2, 3)) != FiniteSet(1, 2, 3)
1001
+
1002
+ # Ensure a variety of types can exist in a FiniteSet
1003
+ assert FiniteSet((1, 2), A, -5, x, 'eggs', x**2)
1004
+
1005
+ assert (A > B) is False
1006
+ assert (A >= B) is False
1007
+ assert (A < B) is False
1008
+ assert (A <= B) is False
1009
+ assert AorB > A and AorB > B
1010
+ assert AorB >= A and AorB >= B
1011
+ assert A >= A and A <= A
1012
+ assert A >= AandB and B >= AandB
1013
+ assert A > AandB and B > AandB
1014
+
1015
+
1016
+ def test_product_basic():
1017
+ H, T = 'H', 'T'
1018
+ unit_line = Interval(0, 1)
1019
+ d6 = FiniteSet(1, 2, 3, 4, 5, 6)
1020
+ d4 = FiniteSet(1, 2, 3, 4)
1021
+ coin = FiniteSet(H, T)
1022
+
1023
+ square = unit_line * unit_line
1024
+
1025
+ assert (0, 0) in square
1026
+ assert 0 not in square
1027
+ assert (H, T) in coin ** 2
1028
+ assert (.5, .5, .5) in (square * unit_line).flatten()
1029
+ assert ((.5, .5), .5) in square * unit_line
1030
+ assert (H, 3, 3) in (coin * d6 * d6).flatten()
1031
+ assert ((H, 3), 3) in coin * d6 * d6
1032
+ HH, TT = sympify(H), sympify(T)
1033
+ assert set(coin**2) == {(HH, HH), (HH, TT), (TT, HH), (TT, TT)}
1034
+
1035
+ assert (d4*d4).is_subset(d6*d6)
1036
+
1037
+ assert square.complement(Interval(-oo, oo)*Interval(-oo, oo)) == Union(
1038
+ (Interval(-oo, 0, True, True) +
1039
+ Interval(1, oo, True, True))*Interval(-oo, oo),
1040
+ Interval(-oo, oo)*(Interval(-oo, 0, True, True) +
1041
+ Interval(1, oo, True, True)))
1042
+
1043
+ assert (Interval(-5, 5)**3).is_subset(Interval(-10, 10)**3)
1044
+ assert not (Interval(-10, 10)**3).is_subset(Interval(-5, 5)**3)
1045
+ assert not (Interval(-5, 5)**2).is_subset(Interval(-10, 10)**3)
1046
+
1047
+ assert (Interval(.2, .5)*FiniteSet(.5)).is_subset(square) # segment in square
1048
+
1049
+ assert len(coin*coin*coin) == 8
1050
+ assert len(S.EmptySet*S.EmptySet) == 0
1051
+ assert len(S.EmptySet*coin) == 0
1052
+ raises(TypeError, lambda: len(coin*Interval(0, 2)))
1053
+
1054
+
1055
+ def test_real():
1056
+ x = Symbol('x', real=True)
1057
+
1058
+ I = Interval(0, 5)
1059
+ J = Interval(10, 20)
1060
+ A = FiniteSet(1, 2, 30, x, S.Pi)
1061
+ B = FiniteSet(-4, 0)
1062
+ C = FiniteSet(100)
1063
+ D = FiniteSet('Ham', 'Eggs')
1064
+
1065
+ assert all(s.is_subset(S.Reals) for s in [I, J, A, B, C])
1066
+ assert not D.is_subset(S.Reals)
1067
+ assert all((a + b).is_subset(S.Reals) for a in [I, J, A, B, C] for b in [I, J, A, B, C])
1068
+ assert not any((a + D).is_subset(S.Reals) for a in [I, J, A, B, C, D])
1069
+
1070
+ assert not (I + A + D).is_subset(S.Reals)
1071
+
1072
+
1073
+ def test_supinf():
1074
+ x = Symbol('x', real=True)
1075
+ y = Symbol('y', real=True)
1076
+
1077
+ assert (Interval(0, 1) + FiniteSet(2)).sup == 2
1078
+ assert (Interval(0, 1) + FiniteSet(2)).inf == 0
1079
+ assert (Interval(0, 1) + FiniteSet(x)).sup == Max(1, x)
1080
+ assert (Interval(0, 1) + FiniteSet(x)).inf == Min(0, x)
1081
+ assert FiniteSet(5, 1, x).sup == Max(5, x)
1082
+ assert FiniteSet(5, 1, x).inf == Min(1, x)
1083
+ assert FiniteSet(5, 1, x, y).sup == Max(5, x, y)
1084
+ assert FiniteSet(5, 1, x, y).inf == Min(1, x, y)
1085
+ assert FiniteSet(5, 1, x, y, S.Infinity, S.NegativeInfinity).sup == \
1086
+ S.Infinity
1087
+ assert FiniteSet(5, 1, x, y, S.Infinity, S.NegativeInfinity).inf == \
1088
+ S.NegativeInfinity
1089
+ assert FiniteSet('Ham', 'Eggs').sup == Max('Ham', 'Eggs')
1090
+
1091
+
1092
+ def test_universalset():
1093
+ U = S.UniversalSet
1094
+ x = Symbol('x')
1095
+ assert U.as_relational(x) is S.true
1096
+ assert U.union(Interval(2, 4)) == U
1097
+
1098
+ assert U.intersect(Interval(2, 4)) == Interval(2, 4)
1099
+ assert U.measure is S.Infinity
1100
+ assert U.boundary == S.EmptySet
1101
+ assert U.contains(0) is S.true
1102
+
1103
+
1104
+ def test_Union_of_ProductSets_shares():
1105
+ line = Interval(0, 2)
1106
+ points = FiniteSet(0, 1, 2)
1107
+ assert Union(line * line, line * points) == line * line
1108
+
1109
+
1110
+ def test_Interval_free_symbols():
1111
+ # issue 6211
1112
+ assert Interval(0, 1).free_symbols == set()
1113
+ x = Symbol('x', real=True)
1114
+ assert Interval(0, x).free_symbols == {x}
1115
+
1116
+
1117
+ def test_image_interval():
1118
+ x = Symbol('x', real=True)
1119
+ a = Symbol('a', real=True)
1120
+ assert imageset(x, 2*x, Interval(-2, 1)) == Interval(-4, 2)
1121
+ assert imageset(x, 2*x, Interval(-2, 1, True, False)) == \
1122
+ Interval(-4, 2, True, False)
1123
+ assert imageset(x, x**2, Interval(-2, 1, True, False)) == \
1124
+ Interval(0, 4, False, True)
1125
+ assert imageset(x, x**2, Interval(-2, 1)) == Interval(0, 4)
1126
+ assert imageset(x, x**2, Interval(-2, 1, True, False)) == \
1127
+ Interval(0, 4, False, True)
1128
+ assert imageset(x, x**2, Interval(-2, 1, True, True)) == \
1129
+ Interval(0, 4, False, True)
1130
+ assert imageset(x, (x - 2)**2, Interval(1, 3)) == Interval(0, 1)
1131
+ assert imageset(x, 3*x**4 - 26*x**3 + 78*x**2 - 90*x, Interval(0, 4)) == \
1132
+ Interval(-35, 0) # Multiple Maxima
1133
+ assert imageset(x, x + 1/x, Interval(-oo, oo)) == Interval(-oo, -2) \
1134
+ + Interval(2, oo) # Single Infinite discontinuity
1135
+ assert imageset(x, 1/x + 1/(x-1)**2, Interval(0, 2, True, False)) == \
1136
+ Interval(Rational(3, 2), oo, False) # Multiple Infinite discontinuities
1137
+
1138
+ # Test for Python lambda
1139
+ assert imageset(lambda x: 2*x, Interval(-2, 1)) == Interval(-4, 2)
1140
+
1141
+ assert imageset(Lambda(x, a*x), Interval(0, 1)) == \
1142
+ ImageSet(Lambda(x, a*x), Interval(0, 1))
1143
+
1144
+ assert imageset(Lambda(x, sin(cos(x))), Interval(0, 1)) == \
1145
+ ImageSet(Lambda(x, sin(cos(x))), Interval(0, 1))
1146
+
1147
+
1148
+ def test_image_piecewise():
1149
+ f = Piecewise((x, x <= -1), (1/x**2, x <= 5), (x**3, True))
1150
+ f1 = Piecewise((0, x <= 1), (1, x <= 2), (2, True))
1151
+ assert imageset(x, f, Interval(-5, 5)) == Union(Interval(-5, -1), Interval(Rational(1, 25), oo))
1152
+ assert imageset(x, f1, Interval(1, 2)) == FiniteSet(0, 1)
1153
+
1154
+
1155
+ @XFAIL # See: https://github.com/sympy/sympy/pull/2723#discussion_r8659826
1156
+ def test_image_Intersection():
1157
+ x = Symbol('x', real=True)
1158
+ y = Symbol('y', real=True)
1159
+ assert imageset(x, x**2, Interval(-2, 0).intersect(Interval(x, y))) == \
1160
+ Interval(0, 4).intersect(Interval(Min(x**2, y**2), Max(x**2, y**2)))
1161
+
1162
+
1163
+ def test_image_FiniteSet():
1164
+ x = Symbol('x', real=True)
1165
+ assert imageset(x, 2*x, FiniteSet(1, 2, 3)) == FiniteSet(2, 4, 6)
1166
+
1167
+
1168
+ def test_image_Union():
1169
+ x = Symbol('x', real=True)
1170
+ assert imageset(x, x**2, Interval(-2, 0) + FiniteSet(1, 2, 3)) == \
1171
+ (Interval(0, 4) + FiniteSet(9))
1172
+
1173
+
1174
+ def test_image_EmptySet():
1175
+ x = Symbol('x', real=True)
1176
+ assert imageset(x, 2*x, S.EmptySet) == S.EmptySet
1177
+
1178
+
1179
+ def test_issue_5724_7680():
1180
+ assert I not in S.Reals # issue 7680
1181
+ assert Interval(-oo, oo).contains(I) is S.false
1182
+
1183
+
1184
+ def test_boundary():
1185
+ assert FiniteSet(1).boundary == FiniteSet(1)
1186
+ assert all(Interval(0, 1, left_open, right_open).boundary == FiniteSet(0, 1)
1187
+ for left_open in (true, false) for right_open in (true, false))
1188
+
1189
+
1190
+ def test_boundary_Union():
1191
+ assert (Interval(0, 1) + Interval(2, 3)).boundary == FiniteSet(0, 1, 2, 3)
1192
+ assert ((Interval(0, 1, False, True)
1193
+ + Interval(1, 2, True, False)).boundary == FiniteSet(0, 1, 2))
1194
+
1195
+ assert (Interval(0, 1) + FiniteSet(2)).boundary == FiniteSet(0, 1, 2)
1196
+ assert Union(Interval(0, 10), Interval(5, 15), evaluate=False).boundary \
1197
+ == FiniteSet(0, 15)
1198
+
1199
+ assert Union(Interval(0, 10), Interval(0, 1), evaluate=False).boundary \
1200
+ == FiniteSet(0, 10)
1201
+ assert Union(Interval(0, 10, True, True),
1202
+ Interval(10, 15, True, True), evaluate=False).boundary \
1203
+ == FiniteSet(0, 10, 15)
1204
+
1205
+
1206
+ @XFAIL
1207
+ def test_union_boundary_of_joining_sets():
1208
+ """ Testing the boundary of unions is a hard problem """
1209
+ assert Union(Interval(0, 10), Interval(10, 15), evaluate=False).boundary \
1210
+ == FiniteSet(0, 15)
1211
+
1212
+
1213
+ def test_boundary_ProductSet():
1214
+ open_square = Interval(0, 1, True, True) ** 2
1215
+ assert open_square.boundary == (FiniteSet(0, 1) * Interval(0, 1)
1216
+ + Interval(0, 1) * FiniteSet(0, 1))
1217
+
1218
+ second_square = Interval(1, 2, True, True) * Interval(0, 1, True, True)
1219
+ assert (open_square + second_square).boundary == (
1220
+ FiniteSet(0, 1) * Interval(0, 1)
1221
+ + FiniteSet(1, 2) * Interval(0, 1)
1222
+ + Interval(0, 1) * FiniteSet(0, 1)
1223
+ + Interval(1, 2) * FiniteSet(0, 1))
1224
+
1225
+
1226
+ def test_boundary_ProductSet_line():
1227
+ line_in_r2 = Interval(0, 1) * FiniteSet(0)
1228
+ assert line_in_r2.boundary == line_in_r2
1229
+
1230
+
1231
+ def test_is_open():
1232
+ assert Interval(0, 1, False, False).is_open is False
1233
+ assert Interval(0, 1, True, False).is_open is False
1234
+ assert Interval(0, 1, True, True).is_open is True
1235
+ assert FiniteSet(1, 2, 3).is_open is False
1236
+
1237
+
1238
+ def test_is_closed():
1239
+ assert Interval(0, 1, False, False).is_closed is True
1240
+ assert Interval(0, 1, True, False).is_closed is False
1241
+ assert FiniteSet(1, 2, 3).is_closed is True
1242
+
1243
+
1244
+ def test_closure():
1245
+ assert Interval(0, 1, False, True).closure == Interval(0, 1, False, False)
1246
+
1247
+
1248
+ def test_interior():
1249
+ assert Interval(0, 1, False, True).interior == Interval(0, 1, True, True)
1250
+
1251
+
1252
+ def test_issue_7841():
1253
+ raises(TypeError, lambda: x in S.Reals)
1254
+
1255
+
1256
+ def test_Eq():
1257
+ assert Eq(Interval(0, 1), Interval(0, 1))
1258
+ assert Eq(Interval(0, 1), Interval(0, 2)) == False
1259
+
1260
+ s1 = FiniteSet(0, 1)
1261
+ s2 = FiniteSet(1, 2)
1262
+
1263
+ assert Eq(s1, s1)
1264
+ assert Eq(s1, s2) == False
1265
+
1266
+ assert Eq(s1*s2, s1*s2)
1267
+ assert Eq(s1*s2, s2*s1) == False
1268
+
1269
+ assert unchanged(Eq, FiniteSet({x, y}), FiniteSet({x}))
1270
+ assert Eq(FiniteSet({x, y}).subs(y, x), FiniteSet({x})) is S.true
1271
+ assert Eq(FiniteSet({x, y}), FiniteSet({x})).subs(y, x) is S.true
1272
+ assert Eq(FiniteSet({x, y}).subs(y, x+1), FiniteSet({x})) is S.false
1273
+ assert Eq(FiniteSet({x, y}), FiniteSet({x})).subs(y, x+1) is S.false
1274
+
1275
+ assert Eq(ProductSet({1}, {2}), Interval(1, 2)) is S.false
1276
+ assert Eq(ProductSet({1}), ProductSet({1}, {2})) is S.false
1277
+
1278
+ assert Eq(FiniteSet(()), FiniteSet(1)) is S.false
1279
+ assert Eq(ProductSet(), FiniteSet(1)) is S.false
1280
+
1281
+ i1 = Interval(0, 1)
1282
+ i2 = Interval(x, y)
1283
+ assert unchanged(Eq, ProductSet(i1, i1), ProductSet(i2, i2))
1284
+
1285
+
1286
+ def test_SymmetricDifference():
1287
+ A = FiniteSet(0, 1, 2, 3, 4, 5)
1288
+ B = FiniteSet(2, 4, 6, 8, 10)
1289
+ C = Interval(8, 10)
1290
+
1291
+ assert SymmetricDifference(A, B, evaluate=False).is_iterable is True
1292
+ assert SymmetricDifference(A, C, evaluate=False).is_iterable is None
1293
+ assert FiniteSet(*SymmetricDifference(A, B, evaluate=False)) == \
1294
+ FiniteSet(0, 1, 3, 5, 6, 8, 10)
1295
+ raises(TypeError,
1296
+ lambda: FiniteSet(*SymmetricDifference(A, C, evaluate=False)))
1297
+
1298
+ assert SymmetricDifference(FiniteSet(0, 1, 2, 3, 4, 5), \
1299
+ FiniteSet(2, 4, 6, 8, 10)) == FiniteSet(0, 1, 3, 5, 6, 8, 10)
1300
+ assert SymmetricDifference(FiniteSet(2, 3, 4), FiniteSet(2, 3, 4 ,5)) \
1301
+ == FiniteSet(5)
1302
+ assert FiniteSet(1, 2, 3, 4, 5) ^ FiniteSet(1, 2, 5, 6) == \
1303
+ FiniteSet(3, 4, 6)
1304
+ assert Set(S(1), S(2), S(3)) ^ Set(S(2), S(3), S(4)) == Union(Set(S(1), S(2), S(3)) - Set(S(2), S(3), S(4)), \
1305
+ Set(S(2), S(3), S(4)) - Set(S(1), S(2), S(3)))
1306
+ assert Interval(0, 4) ^ Interval(2, 5) == Union(Interval(0, 4) - \
1307
+ Interval(2, 5), Interval(2, 5) - Interval(0, 4))
1308
+
1309
+
1310
+ def test_issue_9536():
1311
+ from sympy.functions.elementary.exponential import log
1312
+ a = Symbol('a', real=True)
1313
+ assert FiniteSet(log(a)).intersect(S.Reals) == Intersection(S.Reals, FiniteSet(log(a)))
1314
+
1315
+
1316
+ def test_issue_9637():
1317
+ n = Symbol('n')
1318
+ a = FiniteSet(n)
1319
+ b = FiniteSet(2, n)
1320
+ assert Complement(S.Reals, a) == Complement(S.Reals, a, evaluate=False)
1321
+ assert Complement(Interval(1, 3), a) == Complement(Interval(1, 3), a, evaluate=False)
1322
+ assert Complement(Interval(1, 3), b) == \
1323
+ Complement(Union(Interval(1, 2, False, True), Interval(2, 3, True, False)), a)
1324
+ assert Complement(a, S.Reals) == Complement(a, S.Reals, evaluate=False)
1325
+ assert Complement(a, Interval(1, 3)) == Complement(a, Interval(1, 3), evaluate=False)
1326
+
1327
+
1328
+ def test_issue_9808():
1329
+ # See https://github.com/sympy/sympy/issues/16342
1330
+ assert Complement(FiniteSet(y), FiniteSet(1)) == Complement(FiniteSet(y), FiniteSet(1), evaluate=False)
1331
+ assert Complement(FiniteSet(1, 2, x), FiniteSet(x, y, 2, 3)) == \
1332
+ Complement(FiniteSet(1), FiniteSet(y), evaluate=False)
1333
+
1334
+
1335
+ def test_issue_9956():
1336
+ assert Union(Interval(-oo, oo), FiniteSet(1)) == Interval(-oo, oo)
1337
+ assert Interval(-oo, oo).contains(1) is S.true
1338
+
1339
+
1340
+ def test_issue_Symbol_inter():
1341
+ i = Interval(0, oo)
1342
+ r = S.Reals
1343
+ mat = Matrix([0, 0, 0])
1344
+ assert Intersection(r, i, FiniteSet(m), FiniteSet(m, n)) == \
1345
+ Intersection(i, FiniteSet(m))
1346
+ assert Intersection(FiniteSet(1, m, n), FiniteSet(m, n, 2), i) == \
1347
+ Intersection(i, FiniteSet(m, n))
1348
+ assert Intersection(FiniteSet(m, n, x), FiniteSet(m, z), r) == \
1349
+ Intersection(Intersection({m, z}, {m, n, x}), r)
1350
+ assert Intersection(FiniteSet(m, n, 3), FiniteSet(m, n, x), r) == \
1351
+ Intersection(FiniteSet(3, m, n), FiniteSet(m, n, x), r, evaluate=False)
1352
+ assert Intersection(FiniteSet(m, n, 3), FiniteSet(m, n, 2, 3), r) == \
1353
+ Intersection(FiniteSet(3, m, n), r)
1354
+ assert Intersection(r, FiniteSet(mat, 2, n), FiniteSet(0, mat, n)) == \
1355
+ Intersection(r, FiniteSet(n))
1356
+ assert Intersection(FiniteSet(sin(x), cos(x)), FiniteSet(sin(x), cos(x), 1), r) == \
1357
+ Intersection(r, FiniteSet(sin(x), cos(x)))
1358
+ assert Intersection(FiniteSet(x**2, 1, sin(x)), FiniteSet(x**2, 2, sin(x)), r) == \
1359
+ Intersection(r, FiniteSet(x**2, sin(x)))
1360
+
1361
+
1362
+ def test_issue_11827():
1363
+ assert S.Naturals0**4
1364
+
1365
+
1366
+ def test_issue_10113():
1367
+ f = x**2/(x**2 - 4)
1368
+ assert imageset(x, f, S.Reals) == Union(Interval(-oo, 0), Interval(1, oo, True, True))
1369
+ assert imageset(x, f, Interval(-2, 2)) == Interval(-oo, 0)
1370
+ assert imageset(x, f, Interval(-2, 3)) == Union(Interval(-oo, 0), Interval(Rational(9, 5), oo))
1371
+
1372
+
1373
+ def test_issue_10248():
1374
+ raises(
1375
+ TypeError, lambda: list(Intersection(S.Reals, FiniteSet(x)))
1376
+ )
1377
+ A = Symbol('A', real=True)
1378
+ assert list(Intersection(S.Reals, FiniteSet(A))) == [A]
1379
+
1380
+
1381
+ def test_issue_9447():
1382
+ a = Interval(0, 1) + Interval(2, 3)
1383
+ assert Complement(S.UniversalSet, a) == Complement(
1384
+ S.UniversalSet, Union(Interval(0, 1), Interval(2, 3)), evaluate=False)
1385
+ assert Complement(S.Naturals, a) == Complement(
1386
+ S.Naturals, Union(Interval(0, 1), Interval(2, 3)), evaluate=False)
1387
+
1388
+
1389
+ def test_issue_10337():
1390
+ assert (FiniteSet(2) == 3) is False
1391
+ assert (FiniteSet(2) != 3) is True
1392
+ raises(TypeError, lambda: FiniteSet(2) < 3)
1393
+ raises(TypeError, lambda: FiniteSet(2) <= 3)
1394
+ raises(TypeError, lambda: FiniteSet(2) > 3)
1395
+ raises(TypeError, lambda: FiniteSet(2) >= 3)
1396
+
1397
+
1398
+ def test_issue_10326():
1399
+ bad = [
1400
+ EmptySet,
1401
+ FiniteSet(1),
1402
+ Interval(1, 2),
1403
+ S.ComplexInfinity,
1404
+ S.ImaginaryUnit,
1405
+ S.Infinity,
1406
+ S.NaN,
1407
+ S.NegativeInfinity,
1408
+ ]
1409
+ interval = Interval(0, 5)
1410
+ for i in bad:
1411
+ assert i not in interval
1412
+
1413
+ x = Symbol('x', real=True)
1414
+ nr = Symbol('nr', extended_real=False)
1415
+ assert x + 1 in Interval(x, x + 4)
1416
+ assert nr not in Interval(x, x + 4)
1417
+ assert Interval(1, 2) in FiniteSet(Interval(0, 5), Interval(1, 2))
1418
+ assert Interval(-oo, oo).contains(oo) is S.false
1419
+ assert Interval(-oo, oo).contains(-oo) is S.false
1420
+
1421
+
1422
+ def test_issue_2799():
1423
+ U = S.UniversalSet
1424
+ a = Symbol('a', real=True)
1425
+ inf_interval = Interval(a, oo)
1426
+ R = S.Reals
1427
+
1428
+ assert U + inf_interval == inf_interval + U
1429
+ assert U + R == R + U
1430
+ assert R + inf_interval == inf_interval + R
1431
+
1432
+
1433
+ def test_issue_9706():
1434
+ assert Interval(-oo, 0).closure == Interval(-oo, 0, True, False)
1435
+ assert Interval(0, oo).closure == Interval(0, oo, False, True)
1436
+ assert Interval(-oo, oo).closure == Interval(-oo, oo)
1437
+
1438
+
1439
+ def test_issue_8257():
1440
+ reals_plus_infinity = Union(Interval(-oo, oo), FiniteSet(oo))
1441
+ reals_plus_negativeinfinity = Union(Interval(-oo, oo), FiniteSet(-oo))
1442
+ assert Interval(-oo, oo) + FiniteSet(oo) == reals_plus_infinity
1443
+ assert FiniteSet(oo) + Interval(-oo, oo) == reals_plus_infinity
1444
+ assert Interval(-oo, oo) + FiniteSet(-oo) == reals_plus_negativeinfinity
1445
+ assert FiniteSet(-oo) + Interval(-oo, oo) == reals_plus_negativeinfinity
1446
+
1447
+
1448
+ def test_issue_10931():
1449
+ assert S.Integers - S.Integers == EmptySet
1450
+ assert S.Integers - S.Reals == EmptySet
1451
+
1452
+
1453
+ def test_issue_11174():
1454
+ soln = Intersection(Interval(-oo, oo), FiniteSet(-x), evaluate=False)
1455
+ assert Intersection(FiniteSet(-x), S.Reals) == soln
1456
+
1457
+ soln = Intersection(S.Reals, FiniteSet(x), evaluate=False)
1458
+ assert Intersection(FiniteSet(x), S.Reals) == soln
1459
+
1460
+
1461
+ def test_issue_18505():
1462
+ assert ImageSet(Lambda(n, sqrt(pi*n/2 - 1 + pi/2)), S.Integers).contains(0) == \
1463
+ Contains(0, ImageSet(Lambda(n, sqrt(pi*n/2 - 1 + pi/2)), S.Integers))
1464
+
1465
+
1466
+ def test_finite_set_intersection():
1467
+ # The following should not produce recursion errors
1468
+ # Note: some of these are not completely correct. See
1469
+ # https://github.com/sympy/sympy/issues/16342.
1470
+ assert Intersection(FiniteSet(-oo, x), FiniteSet(x)) == FiniteSet(x)
1471
+ assert Intersection._handle_finite_sets([FiniteSet(-oo, x), FiniteSet(0, x)]) == FiniteSet(x)
1472
+
1473
+ assert Intersection._handle_finite_sets([FiniteSet(-oo, x), FiniteSet(x)]) == FiniteSet(x)
1474
+ assert Intersection._handle_finite_sets([FiniteSet(2, 3, x, y), FiniteSet(1, 2, x)]) == \
1475
+ Intersection._handle_finite_sets([FiniteSet(1, 2, x), FiniteSet(2, 3, x, y)]) == \
1476
+ Intersection(FiniteSet(1, 2, x), FiniteSet(2, 3, x, y)) == \
1477
+ Intersection(FiniteSet(1, 2, x), FiniteSet(2, x, y))
1478
+
1479
+ assert FiniteSet(1+x-y) & FiniteSet(1) == \
1480
+ FiniteSet(1) & FiniteSet(1+x-y) == \
1481
+ Intersection(FiniteSet(1+x-y), FiniteSet(1), evaluate=False)
1482
+
1483
+ assert FiniteSet(1) & FiniteSet(x) == FiniteSet(x) & FiniteSet(1) == \
1484
+ Intersection(FiniteSet(1), FiniteSet(x), evaluate=False)
1485
+
1486
+ assert FiniteSet({x}) & FiniteSet({x, y}) == \
1487
+ Intersection(FiniteSet({x}), FiniteSet({x, y}), evaluate=False)
1488
+
1489
+
1490
+ def test_union_intersection_constructor():
1491
+ # The actual exception does not matter here, so long as these fail
1492
+ sets = [FiniteSet(1), FiniteSet(2)]
1493
+ raises(Exception, lambda: Union(sets))
1494
+ raises(Exception, lambda: Intersection(sets))
1495
+ raises(Exception, lambda: Union(tuple(sets)))
1496
+ raises(Exception, lambda: Intersection(tuple(sets)))
1497
+ raises(Exception, lambda: Union(i for i in sets))
1498
+ raises(Exception, lambda: Intersection(i for i in sets))
1499
+
1500
+ # Python sets are treated the same as FiniteSet
1501
+ # The union of a single set (of sets) is the set (of sets) itself
1502
+ assert Union(set(sets)) == FiniteSet(*sets)
1503
+ assert Intersection(set(sets)) == FiniteSet(*sets)
1504
+
1505
+ assert Union({1}, {2}) == FiniteSet(1, 2)
1506
+ assert Intersection({1, 2}, {2, 3}) == FiniteSet(2)
1507
+
1508
+
1509
+ def test_Union_contains():
1510
+ assert zoo not in Union(
1511
+ Interval.open(-oo, 0), Interval.open(0, oo))
1512
+
1513
+
1514
+ @XFAIL
1515
+ def test_issue_16878b():
1516
+ # in intersection_sets for (ImageSet, Set) there is no code
1517
+ # that handles the base_set of S.Reals like there is
1518
+ # for Integers
1519
+ assert imageset(x, (x, x), S.Reals).is_subset(S.Reals**2) is True
1520
+
1521
+ def test_DisjointUnion():
1522
+ assert DisjointUnion(FiniteSet(1, 2, 3), FiniteSet(1, 2, 3), FiniteSet(1, 2, 3)).rewrite(Union) == (FiniteSet(1, 2, 3) * FiniteSet(0, 1, 2))
1523
+ assert DisjointUnion(Interval(1, 3), Interval(2, 4)).rewrite(Union) == Union(Interval(1, 3) * FiniteSet(0), Interval(2, 4) * FiniteSet(1))
1524
+ assert DisjointUnion(Interval(0, 5), Interval(0, 5)).rewrite(Union) == Union(Interval(0, 5) * FiniteSet(0), Interval(0, 5) * FiniteSet(1))
1525
+ assert DisjointUnion(Interval(-1, 2), S.EmptySet, S.EmptySet).rewrite(Union) == Interval(-1, 2) * FiniteSet(0)
1526
+ assert DisjointUnion(Interval(-1, 2)).rewrite(Union) == Interval(-1, 2) * FiniteSet(0)
1527
+ assert DisjointUnion(S.EmptySet, Interval(-1, 2), S.EmptySet).rewrite(Union) == Interval(-1, 2) * FiniteSet(1)
1528
+ assert DisjointUnion(Interval(-oo, oo)).rewrite(Union) == Interval(-oo, oo) * FiniteSet(0)
1529
+ assert DisjointUnion(S.EmptySet).rewrite(Union) == S.EmptySet
1530
+ assert DisjointUnion().rewrite(Union) == S.EmptySet
1531
+ raises(TypeError, lambda: DisjointUnion(Symbol('n')))
1532
+
1533
+ x = Symbol("x")
1534
+ y = Symbol("y")
1535
+ z = Symbol("z")
1536
+ assert DisjointUnion(FiniteSet(x), FiniteSet(y, z)).rewrite(Union) == (FiniteSet(x) * FiniteSet(0)) + (FiniteSet(y, z) * FiniteSet(1))
1537
+
1538
+ def test_DisjointUnion_is_empty():
1539
+ assert DisjointUnion(S.EmptySet).is_empty is True
1540
+ assert DisjointUnion(S.EmptySet, S.EmptySet).is_empty is True
1541
+ assert DisjointUnion(S.EmptySet, FiniteSet(1, 2, 3)).is_empty is False
1542
+
1543
+ def test_DisjointUnion_is_iterable():
1544
+ assert DisjointUnion(S.Integers, S.Naturals, S.Rationals).is_iterable is True
1545
+ assert DisjointUnion(S.EmptySet, S.Reals).is_iterable is False
1546
+ assert DisjointUnion(FiniteSet(1, 2, 3), S.EmptySet, FiniteSet(x, y)).is_iterable is True
1547
+ assert DisjointUnion(S.EmptySet, S.EmptySet).is_iterable is False
1548
+
1549
+ def test_DisjointUnion_contains():
1550
+ assert (0, 0) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
1551
+ assert (0, 1) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
1552
+ assert (0, 2) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
1553
+ assert (1, 0) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
1554
+ assert (1, 1) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
1555
+ assert (1, 2) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
1556
+ assert (2, 0) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
1557
+ assert (2, 1) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
1558
+ assert (2, 2) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
1559
+ assert (0, 1, 2) not in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
1560
+ assert (0, 0.5) not in DisjointUnion(FiniteSet(0.5))
1561
+ assert (0, 5) not in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
1562
+ assert (x, 0) in DisjointUnion(FiniteSet(x, y, z), S.EmptySet, FiniteSet(y))
1563
+ assert (y, 0) in DisjointUnion(FiniteSet(x, y, z), S.EmptySet, FiniteSet(y))
1564
+ assert (z, 0) in DisjointUnion(FiniteSet(x, y, z), S.EmptySet, FiniteSet(y))
1565
+ assert (y, 2) in DisjointUnion(FiniteSet(x, y, z), S.EmptySet, FiniteSet(y))
1566
+ assert (0.5, 0) in DisjointUnion(Interval(0, 1), Interval(0, 2))
1567
+ assert (0.5, 1) in DisjointUnion(Interval(0, 1), Interval(0, 2))
1568
+ assert (1.5, 0) not in DisjointUnion(Interval(0, 1), Interval(0, 2))
1569
+ assert (1.5, 1) in DisjointUnion(Interval(0, 1), Interval(0, 2))
1570
+
1571
+ def test_DisjointUnion_iter():
1572
+ D = DisjointUnion(FiniteSet(3, 5, 7, 9), FiniteSet(x, y, z))
1573
+ it = iter(D)
1574
+ L1 = [(x, 1), (y, 1), (z, 1)]
1575
+ L2 = [(3, 0), (5, 0), (7, 0), (9, 0)]
1576
+ nxt = next(it)
1577
+ assert nxt in L2
1578
+ L2.remove(nxt)
1579
+ nxt = next(it)
1580
+ assert nxt in L1
1581
+ L1.remove(nxt)
1582
+ nxt = next(it)
1583
+ assert nxt in L2
1584
+ L2.remove(nxt)
1585
+ nxt = next(it)
1586
+ assert nxt in L1
1587
+ L1.remove(nxt)
1588
+ nxt = next(it)
1589
+ assert nxt in L2
1590
+ L2.remove(nxt)
1591
+ nxt = next(it)
1592
+ assert nxt in L1
1593
+ L1.remove(nxt)
1594
+ nxt = next(it)
1595
+ assert nxt in L2
1596
+ L2.remove(nxt)
1597
+ raises(StopIteration, lambda: next(it))
1598
+
1599
+ raises(ValueError, lambda: iter(DisjointUnion(Interval(0, 1), S.EmptySet)))
1600
+
1601
+ def test_DisjointUnion_len():
1602
+ assert len(DisjointUnion(FiniteSet(3, 5, 7, 9), FiniteSet(x, y, z))) == 7
1603
+ assert len(DisjointUnion(S.EmptySet, S.EmptySet, FiniteSet(x, y, z), S.EmptySet)) == 3
1604
+ raises(ValueError, lambda: len(DisjointUnion(Interval(0, 1), S.EmptySet)))
1605
+
1606
+ def test_SetKind_ProductSet():
1607
+ p = ProductSet(FiniteSet(Matrix([1, 2])), FiniteSet(Matrix([1, 2])))
1608
+ mk = MatrixKind(NumberKind)
1609
+ k = SetKind(TupleKind(mk, mk))
1610
+ assert p.kind is k
1611
+ assert ProductSet(Interval(1, 2), FiniteSet(Matrix([1, 2]))).kind is SetKind(TupleKind(NumberKind, mk))
1612
+
1613
+ def test_SetKind_Interval():
1614
+ assert Interval(1, 2).kind is SetKind(NumberKind)
1615
+
1616
+ def test_SetKind_EmptySet_UniversalSet():
1617
+ assert S.UniversalSet.kind is SetKind(UndefinedKind)
1618
+ assert EmptySet.kind is SetKind()
1619
+
1620
+ def test_SetKind_FiniteSet():
1621
+ assert FiniteSet(1, Matrix([1, 2])).kind is SetKind(UndefinedKind)
1622
+ assert FiniteSet(1, 2).kind is SetKind(NumberKind)
1623
+
1624
+ def test_SetKind_Unions():
1625
+ assert Union(FiniteSet(Matrix([1, 2])), Interval(1, 2)).kind is SetKind(UndefinedKind)
1626
+ assert Union(Interval(1, 2), Interval(1, 7)).kind is SetKind(NumberKind)
1627
+
1628
+ def test_SetKind_DisjointUnion():
1629
+ A = FiniteSet(1, 2, 3)
1630
+ B = Interval(0, 5)
1631
+ assert DisjointUnion(A, B).kind is SetKind(NumberKind)
1632
+
1633
+ def test_SetKind_evaluate_False():
1634
+ U = lambda *args: Union(*args, evaluate=False)
1635
+ assert U({1}, EmptySet).kind is SetKind(NumberKind)
1636
+ assert U(Interval(1, 2), EmptySet).kind is SetKind(NumberKind)
1637
+ assert U({1}, S.UniversalSet).kind is SetKind(UndefinedKind)
1638
+ assert U(Interval(1, 2), Interval(4, 5),
1639
+ FiniteSet(1)).kind is SetKind(NumberKind)
1640
+ I = lambda *args: Intersection(*args, evaluate=False)
1641
+ assert I({1}, S.UniversalSet).kind is SetKind(NumberKind)
1642
+ assert I({1}, EmptySet).kind is SetKind()
1643
+ C = lambda *args: Complement(*args, evaluate=False)
1644
+ assert C(S.UniversalSet, {1, 2, 4, 5}).kind is SetKind(UndefinedKind)
1645
+ assert C({1, 2, 3, 4, 5}, EmptySet).kind is SetKind(NumberKind)
1646
+ assert C(EmptySet, {1, 2, 3, 4, 5}).kind is SetKind()
1647
+
1648
+ def test_SetKind_ImageSet_Special():
1649
+ f = ImageSet(Lambda(n, n ** 2), Interval(1, 4))
1650
+ assert (f - FiniteSet(3)).kind is SetKind(NumberKind)
1651
+ assert (f + Interval(16, 17)).kind is SetKind(NumberKind)
1652
+ assert (f + FiniteSet(17)).kind is SetKind(NumberKind)
1653
+
1654
+ def test_issue_20089():
1655
+ B = FiniteSet(FiniteSet(1, 2), FiniteSet(1))
1656
+ assert 1 not in B
1657
+ assert 1.0 not in B
1658
+ assert not Eq(1, FiniteSet(1, 2))
1659
+ assert FiniteSet(1) in B
1660
+ A = FiniteSet(1, 2)
1661
+ assert A in B
1662
+ assert B.issubset(B)
1663
+ assert not A.issubset(B)
1664
+ assert 1 in A
1665
+ C = FiniteSet(FiniteSet(1, 2), FiniteSet(1), 1, 2)
1666
+ assert A.issubset(C)
1667
+ assert B.issubset(C)
1668
+
1669
+ def test_issue_19378():
1670
+ a = FiniteSet(1, 2)
1671
+ b = ProductSet(a, a)
1672
+ c = FiniteSet((1, 1), (1, 2), (2, 1), (2, 2))
1673
+ assert b.is_subset(c) is True
1674
+ d = FiniteSet(1)
1675
+ assert b.is_subset(d) is False
1676
+ assert Eq(c, b).simplify() is S.true
1677
+ assert Eq(a, c).simplify() is S.false
1678
+ assert Eq({1}, {x}).simplify() == Eq({1}, {x})
1679
+
1680
+ def test_intersection_symbolic():
1681
+ n = Symbol('n')
1682
+ # These should not throw an error
1683
+ assert isinstance(Intersection(Range(n), Range(100)), Intersection)
1684
+ assert isinstance(Intersection(Range(n), Interval(1, 100)), Intersection)
1685
+ assert isinstance(Intersection(Range(100), Interval(1, n)), Intersection)
1686
+
1687
+
1688
+ @XFAIL
1689
+ def test_intersection_symbolic_failing():
1690
+ n = Symbol('n', integer=True, positive=True)
1691
+ assert Intersection(Range(10, n), Range(4, 500, 5)) == Intersection(
1692
+ Range(14, n), Range(14, 500, 5))
1693
+ assert Intersection(Interval(10, n), Range(4, 500, 5)) == Intersection(
1694
+ Interval(14, n), Range(14, 500, 5))
1695
+
1696
+
1697
+ def test_issue_20379():
1698
+ #https://github.com/sympy/sympy/issues/20379
1699
+ x = pi - 3.14159265358979
1700
+ assert FiniteSet(x).evalf(2) == FiniteSet(Float('3.23108914886517e-15', 2))
1701
+
1702
+ def test_finiteset_simplify():
1703
+ S = FiniteSet(1, cos(1)**2 + sin(1)**2)
1704
+ assert S.simplify() == {1}
venv/lib/python3.10/site-packages/sympy/strategies/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.64 kB). View file
 
venv/lib/python3.10/site-packages/sympy/strategies/__pycache__/core.cpython-310.pyc ADDED
Binary file (5.36 kB). View file
 
venv/lib/python3.10/site-packages/sympy/strategies/__pycache__/rl.cpython-310.pyc ADDED
Binary file (5.52 kB). View file