applied-ai-018 commited on
Commit
5975f57
·
verified ·
1 Parent(s): 0f7fe19

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. llmeval-env/lib/python3.10/site-packages/sympy/categories/__init__.py +33 -0
  2. llmeval-env/lib/python3.10/site-packages/sympy/categories/__pycache__/__init__.cpython-310.pyc +0 -0
  3. llmeval-env/lib/python3.10/site-packages/sympy/categories/__pycache__/baseclasses.cpython-310.pyc +0 -0
  4. llmeval-env/lib/python3.10/site-packages/sympy/categories/__pycache__/diagram_drawing.cpython-310.pyc +0 -0
  5. llmeval-env/lib/python3.10/site-packages/sympy/categories/baseclasses.py +979 -0
  6. llmeval-env/lib/python3.10/site-packages/sympy/categories/diagram_drawing.py +2591 -0
  7. llmeval-env/lib/python3.10/site-packages/sympy/categories/tests/__init__.py +0 -0
  8. llmeval-env/lib/python3.10/site-packages/sympy/categories/tests/test_baseclasses.py +209 -0
  9. llmeval-env/lib/python3.10/site-packages/sympy/functions/special/__pycache__/__init__.cpython-310.pyc +0 -0
  10. llmeval-env/lib/python3.10/site-packages/sympy/functions/special/__pycache__/bessel.cpython-310.pyc +0 -0
  11. llmeval-env/lib/python3.10/site-packages/sympy/functions/special/__pycache__/beta_functions.cpython-310.pyc +0 -0
  12. llmeval-env/lib/python3.10/site-packages/sympy/functions/special/__pycache__/bsplines.cpython-310.pyc +0 -0
  13. llmeval-env/lib/python3.10/site-packages/sympy/functions/special/__pycache__/delta_functions.cpython-310.pyc +0 -0
  14. llmeval-env/lib/python3.10/site-packages/sympy/functions/special/__pycache__/elliptic_integrals.cpython-310.pyc +0 -0
  15. llmeval-env/lib/python3.10/site-packages/sympy/functions/special/__pycache__/error_functions.cpython-310.pyc +0 -0
  16. llmeval-env/lib/python3.10/site-packages/sympy/functions/special/__pycache__/gamma_functions.cpython-310.pyc +0 -0
  17. llmeval-env/lib/python3.10/site-packages/sympy/functions/special/__pycache__/hyper.cpython-310.pyc +0 -0
  18. llmeval-env/lib/python3.10/site-packages/sympy/functions/special/__pycache__/mathieu_functions.cpython-310.pyc +0 -0
  19. llmeval-env/lib/python3.10/site-packages/sympy/functions/special/__pycache__/polynomials.cpython-310.pyc +0 -0
  20. llmeval-env/lib/python3.10/site-packages/sympy/functions/special/__pycache__/singularity_functions.cpython-310.pyc +0 -0
  21. llmeval-env/lib/python3.10/site-packages/sympy/functions/special/__pycache__/spherical_harmonics.cpython-310.pyc +0 -0
  22. llmeval-env/lib/python3.10/site-packages/sympy/functions/special/__pycache__/tensor_functions.cpython-310.pyc +0 -0
  23. llmeval-env/lib/python3.10/site-packages/sympy/functions/special/__pycache__/zeta_functions.cpython-310.pyc +0 -0
  24. llmeval-env/lib/python3.10/site-packages/sympy/functions/special/benchmarks/__init__.py +0 -0
  25. llmeval-env/lib/python3.10/site-packages/sympy/functions/special/benchmarks/__pycache__/__init__.cpython-310.pyc +0 -0
  26. llmeval-env/lib/python3.10/site-packages/sympy/functions/special/benchmarks/__pycache__/bench_special.cpython-310.pyc +0 -0
  27. llmeval-env/lib/python3.10/site-packages/sympy/functions/special/benchmarks/bench_special.py +8 -0
  28. llmeval-env/lib/python3.10/site-packages/sympy/functions/special/tests/__pycache__/test_beta_functions.cpython-310.pyc +0 -0
  29. llmeval-env/lib/python3.10/site-packages/sympy/functions/special/tests/__pycache__/test_delta_functions.cpython-310.pyc +0 -0
  30. llmeval-env/lib/python3.10/site-packages/sympy/functions/special/tests/__pycache__/test_hyper.cpython-310.pyc +0 -0
  31. llmeval-env/lib/python3.10/site-packages/sympy/functions/special/tests/__pycache__/test_mathieu.cpython-310.pyc +0 -0
  32. llmeval-env/lib/python3.10/site-packages/sympy/functions/special/tests/__pycache__/test_singularity_functions.cpython-310.pyc +0 -0
  33. llmeval-env/lib/python3.10/site-packages/sympy/functions/special/tests/__pycache__/test_spec_polynomials.cpython-310.pyc +0 -0
  34. llmeval-env/lib/python3.10/site-packages/sympy/functions/special/tests/__pycache__/test_spherical_harmonics.cpython-310.pyc +0 -0
  35. llmeval-env/lib/python3.10/site-packages/sympy/functions/special/tests/__pycache__/test_tensor_functions.cpython-310.pyc +0 -0
  36. llmeval-env/lib/python3.10/site-packages/sympy/sets/__init__.py +36 -0
  37. llmeval-env/lib/python3.10/site-packages/sympy/sets/__pycache__/__init__.cpython-310.pyc +0 -0
  38. llmeval-env/lib/python3.10/site-packages/sympy/sets/__pycache__/conditionset.cpython-310.pyc +0 -0
  39. llmeval-env/lib/python3.10/site-packages/sympy/sets/__pycache__/contains.cpython-310.pyc +0 -0
  40. llmeval-env/lib/python3.10/site-packages/sympy/sets/__pycache__/fancysets.cpython-310.pyc +0 -0
  41. llmeval-env/lib/python3.10/site-packages/sympy/sets/__pycache__/ordinals.cpython-310.pyc +0 -0
  42. llmeval-env/lib/python3.10/site-packages/sympy/sets/__pycache__/sets.cpython-310.pyc +0 -0
  43. llmeval-env/lib/python3.10/site-packages/sympy/sets/conditionset.py +246 -0
  44. llmeval-env/lib/python3.10/site-packages/sympy/sets/contains.py +48 -0
  45. llmeval-env/lib/python3.10/site-packages/sympy/sets/fancysets.py +1521 -0
  46. llmeval-env/lib/python3.10/site-packages/sympy/sets/handlers/__init__.py +0 -0
  47. llmeval-env/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/__init__.cpython-310.pyc +0 -0
  48. llmeval-env/lib/python3.10/site-packages/sympy/sets/handlers/add.py +79 -0
  49. llmeval-env/lib/python3.10/site-packages/sympy/sets/handlers/comparison.py +53 -0
  50. llmeval-env/lib/python3.10/site-packages/sympy/sets/handlers/functions.py +262 -0
llmeval-env/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
+ ]
llmeval-env/lib/python3.10/site-packages/sympy/categories/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.07 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/categories/__pycache__/baseclasses.cpython-310.pyc ADDED
Binary file (28.3 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/categories/__pycache__/diagram_drawing.cpython-310.pyc ADDED
Binary file (65.4 kB). View file
 
llmeval-env/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)
llmeval-env/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",))
llmeval-env/lib/python3.10/site-packages/sympy/categories/tests/__init__.py ADDED
File without changes
llmeval-env/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(""))
llmeval-env/lib/python3.10/site-packages/sympy/functions/special/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (196 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/special/__pycache__/bessel.cpython-310.pyc ADDED
Binary file (58.7 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/special/__pycache__/beta_functions.cpython-310.pyc ADDED
Binary file (13.2 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/special/__pycache__/bsplines.cpython-310.pyc ADDED
Binary file (10.5 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/special/__pycache__/delta_functions.cpython-310.pyc ADDED
Binary file (18.6 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/special/__pycache__/elliptic_integrals.cpython-310.pyc ADDED
Binary file (14.5 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/special/__pycache__/error_functions.cpython-310.pyc ADDED
Binary file (78.9 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/special/__pycache__/gamma_functions.cpython-310.pyc ADDED
Binary file (41.3 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/special/__pycache__/hyper.cpython-310.pyc ADDED
Binary file (40.3 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/special/__pycache__/mathieu_functions.cpython-310.pyc ADDED
Binary file (7.08 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/special/__pycache__/polynomials.cpython-310.pyc ADDED
Binary file (39.4 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/special/__pycache__/singularity_functions.cpython-310.pyc ADDED
Binary file (7.96 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/special/__pycache__/spherical_harmonics.cpython-310.pyc ADDED
Binary file (10.9 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/special/__pycache__/tensor_functions.cpython-310.pyc ADDED
Binary file (12.4 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/special/__pycache__/zeta_functions.cpython-310.pyc ADDED
Binary file (23.1 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/special/benchmarks/__init__.py ADDED
File without changes
llmeval-env/lib/python3.10/site-packages/sympy/functions/special/benchmarks/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (207 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/special/benchmarks/__pycache__/bench_special.cpython-310.pyc ADDED
Binary file (496 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/special/benchmarks/bench_special.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.symbol import symbols
2
+ from sympy.functions.special.spherical_harmonics import Ynm
3
+
4
+ x, y = symbols('x,y')
5
+
6
+
7
+ def timeit_Ynm_xy():
8
+ Ynm(1, 1, x, y)
llmeval-env/lib/python3.10/site-packages/sympy/functions/special/tests/__pycache__/test_beta_functions.cpython-310.pyc ADDED
Binary file (3.86 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/special/tests/__pycache__/test_delta_functions.cpython-310.pyc ADDED
Binary file (5.96 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/special/tests/__pycache__/test_hyper.cpython-310.pyc ADDED
Binary file (15.1 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/special/tests/__pycache__/test_mathieu.cpython-310.pyc ADDED
Binary file (1.81 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/special/tests/__pycache__/test_singularity_functions.cpython-310.pyc ADDED
Binary file (4.77 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/special/tests/__pycache__/test_spec_polynomials.cpython-310.pyc ADDED
Binary file (18.5 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/special/tests/__pycache__/test_spherical_harmonics.cpython-310.pyc ADDED
Binary file (3.69 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/special/tests/__pycache__/test_tensor_functions.cpython-310.pyc ADDED
Binary file (4.59 kB). View file
 
llmeval-env/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
+ ]
llmeval-env/lib/python3.10/site-packages/sympy/sets/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.1 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/sets/__pycache__/conditionset.cpython-310.pyc ADDED
Binary file (7.63 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/sets/__pycache__/contains.cpython-310.pyc ADDED
Binary file (1.91 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/sets/__pycache__/fancysets.cpython-310.pyc ADDED
Binary file (42.4 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/sets/__pycache__/ordinals.cpython-310.pyc ADDED
Binary file (8.45 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/sets/__pycache__/sets.cpython-310.pyc ADDED
Binary file (81.4 kB). View file
 
llmeval-env/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)
llmeval-env/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]
llmeval-env/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)
llmeval-env/lib/python3.10/site-packages/sympy/sets/handlers/__init__.py ADDED
File without changes
llmeval-env/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (192 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/sets/handlers/add.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import oo, Infinity, NegativeInfinity
2
+ from sympy.core.singleton import S
3
+ from sympy.core import Basic, Expr
4
+ from sympy.multipledispatch import Dispatcher
5
+ from sympy.sets import Interval, FiniteSet
6
+
7
+
8
+
9
+ # XXX: The functions in this module are clearly not tested and are broken in a
10
+ # number of ways.
11
+
12
+ _set_add = Dispatcher('_set_add')
13
+ _set_sub = Dispatcher('_set_sub')
14
+
15
+
16
+ @_set_add.register(Basic, Basic)
17
+ def _(x, y):
18
+ return None
19
+
20
+
21
+ @_set_add.register(Expr, Expr)
22
+ def _(x, y):
23
+ return x+y
24
+
25
+
26
+ @_set_add.register(Interval, Interval)
27
+ def _(x, y):
28
+ """
29
+ Additions in interval arithmetic
30
+ https://en.wikipedia.org/wiki/Interval_arithmetic
31
+ """
32
+ return Interval(x.start + y.start, x.end + y.end,
33
+ x.left_open or y.left_open, x.right_open or y.right_open)
34
+
35
+
36
+ @_set_add.register(Interval, Infinity)
37
+ def _(x, y):
38
+ if x.start is S.NegativeInfinity:
39
+ return Interval(-oo, oo)
40
+ return FiniteSet({S.Infinity})
41
+
42
+ @_set_add.register(Interval, NegativeInfinity)
43
+ def _(x, y):
44
+ if x.end is S.Infinity:
45
+ return Interval(-oo, oo)
46
+ return FiniteSet({S.NegativeInfinity})
47
+
48
+
49
+ @_set_sub.register(Basic, Basic)
50
+ def _(x, y):
51
+ return None
52
+
53
+
54
+ @_set_sub.register(Expr, Expr)
55
+ def _(x, y):
56
+ return x-y
57
+
58
+
59
+ @_set_sub.register(Interval, Interval)
60
+ def _(x, y):
61
+ """
62
+ Subtractions in interval arithmetic
63
+ https://en.wikipedia.org/wiki/Interval_arithmetic
64
+ """
65
+ return Interval(x.start - y.end, x.end - y.start,
66
+ x.left_open or y.right_open, x.right_open or y.left_open)
67
+
68
+
69
+ @_set_sub.register(Interval, Infinity)
70
+ def _(x, y):
71
+ if x.start is S.NegativeInfinity:
72
+ return Interval(-oo, oo)
73
+ return FiniteSet(-oo)
74
+
75
+ @_set_sub.register(Interval, NegativeInfinity)
76
+ def _(x, y):
77
+ if x.start is S.NegativeInfinity:
78
+ return Interval(-oo, oo)
79
+ return FiniteSet(-oo)
llmeval-env/lib/python3.10/site-packages/sympy/sets/handlers/comparison.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.relational import Eq, is_eq
2
+ from sympy.core.basic import Basic
3
+ from sympy.core.logic import fuzzy_and, fuzzy_bool
4
+ from sympy.logic.boolalg import And
5
+ from sympy.multipledispatch import dispatch
6
+ from sympy.sets.sets import tfn, ProductSet, Interval, FiniteSet, Set
7
+
8
+
9
+ @dispatch(Interval, FiniteSet) # type:ignore
10
+ def _eval_is_eq(lhs, rhs): # noqa: F811
11
+ return False
12
+
13
+
14
+ @dispatch(FiniteSet, Interval) # type:ignore
15
+ def _eval_is_eq(lhs, rhs): # noqa: F811
16
+ return False
17
+
18
+
19
+ @dispatch(Interval, Interval) # type:ignore
20
+ def _eval_is_eq(lhs, rhs): # noqa: F811
21
+ return And(Eq(lhs.left, rhs.left),
22
+ Eq(lhs.right, rhs.right),
23
+ lhs.left_open == rhs.left_open,
24
+ lhs.right_open == rhs.right_open)
25
+
26
+ @dispatch(FiniteSet, FiniteSet) # type:ignore
27
+ def _eval_is_eq(lhs, rhs): # noqa: F811
28
+ def all_in_both():
29
+ s_set = set(lhs.args)
30
+ o_set = set(rhs.args)
31
+ yield fuzzy_and(lhs._contains(e) for e in o_set - s_set)
32
+ yield fuzzy_and(rhs._contains(e) for e in s_set - o_set)
33
+
34
+ return tfn[fuzzy_and(all_in_both())]
35
+
36
+
37
+ @dispatch(ProductSet, ProductSet) # type:ignore
38
+ def _eval_is_eq(lhs, rhs): # noqa: F811
39
+ if len(lhs.sets) != len(rhs.sets):
40
+ return False
41
+
42
+ eqs = (is_eq(x, y) for x, y in zip(lhs.sets, rhs.sets))
43
+ return tfn[fuzzy_and(map(fuzzy_bool, eqs))]
44
+
45
+
46
+ @dispatch(Set, Basic) # type:ignore
47
+ def _eval_is_eq(lhs, rhs): # noqa: F811
48
+ return False
49
+
50
+
51
+ @dispatch(Set, Set) # type:ignore
52
+ def _eval_is_eq(lhs, rhs): # noqa: F811
53
+ return tfn[fuzzy_and(a.is_subset(b) for a, b in [(lhs, rhs), (rhs, lhs)])]
llmeval-env/lib/python3.10/site-packages/sympy/sets/handlers/functions.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.singleton import S
2
+ from sympy.sets.sets import Set
3
+ from sympy.calculus.singularities import singularities
4
+ from sympy.core import Expr, Add
5
+ from sympy.core.function import Lambda, FunctionClass, diff, expand_mul
6
+ from sympy.core.numbers import Float, oo
7
+ from sympy.core.symbol import Dummy, symbols, Wild
8
+ from sympy.functions.elementary.exponential import exp, log
9
+ from sympy.functions.elementary.miscellaneous import Min, Max
10
+ from sympy.logic.boolalg import true
11
+ from sympy.multipledispatch import Dispatcher
12
+ from sympy.sets import (imageset, Interval, FiniteSet, Union, ImageSet,
13
+ Intersection, Range, Complement)
14
+ from sympy.sets.sets import EmptySet, is_function_invertible_in_set
15
+ from sympy.sets.fancysets import Integers, Naturals, Reals
16
+ from sympy.functions.elementary.exponential import match_real_imag
17
+
18
+
19
+ _x, _y = symbols("x y")
20
+
21
+ FunctionUnion = (FunctionClass, Lambda)
22
+
23
+ _set_function = Dispatcher('_set_function')
24
+
25
+
26
+ @_set_function.register(FunctionClass, Set)
27
+ def _(f, x):
28
+ return None
29
+
30
+ @_set_function.register(FunctionUnion, FiniteSet)
31
+ def _(f, x):
32
+ return FiniteSet(*map(f, x))
33
+
34
+ @_set_function.register(Lambda, Interval)
35
+ def _(f, x):
36
+ from sympy.solvers.solveset import solveset
37
+ from sympy.series import limit
38
+ # TODO: handle functions with infinitely many solutions (eg, sin, tan)
39
+ # TODO: handle multivariate functions
40
+
41
+ expr = f.expr
42
+ if len(expr.free_symbols) > 1 or len(f.variables) != 1:
43
+ return
44
+ var = f.variables[0]
45
+ if not var.is_real:
46
+ if expr.subs(var, Dummy(real=True)).is_real is False:
47
+ return
48
+
49
+ if expr.is_Piecewise:
50
+ result = S.EmptySet
51
+ domain_set = x
52
+ for (p_expr, p_cond) in expr.args:
53
+ if p_cond is true:
54
+ intrvl = domain_set
55
+ else:
56
+ intrvl = p_cond.as_set()
57
+ intrvl = Intersection(domain_set, intrvl)
58
+
59
+ if p_expr.is_Number:
60
+ image = FiniteSet(p_expr)
61
+ else:
62
+ image = imageset(Lambda(var, p_expr), intrvl)
63
+ result = Union(result, image)
64
+
65
+ # remove the part which has been `imaged`
66
+ domain_set = Complement(domain_set, intrvl)
67
+ if domain_set is S.EmptySet:
68
+ break
69
+ return result
70
+
71
+ if not x.start.is_comparable or not x.end.is_comparable:
72
+ return
73
+
74
+ try:
75
+ from sympy.polys.polyutils import _nsort
76
+ sing = list(singularities(expr, var, x))
77
+ if len(sing) > 1:
78
+ sing = _nsort(sing)
79
+ except NotImplementedError:
80
+ return
81
+
82
+ if x.left_open:
83
+ _start = limit(expr, var, x.start, dir="+")
84
+ elif x.start not in sing:
85
+ _start = f(x.start)
86
+ if x.right_open:
87
+ _end = limit(expr, var, x.end, dir="-")
88
+ elif x.end not in sing:
89
+ _end = f(x.end)
90
+
91
+ if len(sing) == 0:
92
+ soln_expr = solveset(diff(expr, var), var)
93
+ if not (isinstance(soln_expr, FiniteSet)
94
+ or soln_expr is S.EmptySet):
95
+ return
96
+ solns = list(soln_expr)
97
+
98
+ extr = [_start, _end] + [f(i) for i in solns
99
+ if i.is_real and i in x]
100
+ start, end = Min(*extr), Max(*extr)
101
+
102
+ left_open, right_open = False, False
103
+ if _start <= _end:
104
+ # the minimum or maximum value can occur simultaneously
105
+ # on both the edge of the interval and in some interior
106
+ # point
107
+ if start == _start and start not in solns:
108
+ left_open = x.left_open
109
+ if end == _end and end not in solns:
110
+ right_open = x.right_open
111
+ else:
112
+ if start == _end and start not in solns:
113
+ left_open = x.right_open
114
+ if end == _start and end not in solns:
115
+ right_open = x.left_open
116
+
117
+ return Interval(start, end, left_open, right_open)
118
+ else:
119
+ return imageset(f, Interval(x.start, sing[0],
120
+ x.left_open, True)) + \
121
+ Union(*[imageset(f, Interval(sing[i], sing[i + 1], True, True))
122
+ for i in range(0, len(sing) - 1)]) + \
123
+ imageset(f, Interval(sing[-1], x.end, True, x.right_open))
124
+
125
+ @_set_function.register(FunctionClass, Interval)
126
+ def _(f, x):
127
+ if f == exp:
128
+ return Interval(exp(x.start), exp(x.end), x.left_open, x.right_open)
129
+ elif f == log:
130
+ return Interval(log(x.start), log(x.end), x.left_open, x.right_open)
131
+ return ImageSet(Lambda(_x, f(_x)), x)
132
+
133
+ @_set_function.register(FunctionUnion, Union)
134
+ def _(f, x):
135
+ return Union(*(imageset(f, arg) for arg in x.args))
136
+
137
+ @_set_function.register(FunctionUnion, Intersection)
138
+ def _(f, x):
139
+ # If the function is invertible, intersect the maps of the sets.
140
+ if is_function_invertible_in_set(f, x):
141
+ return Intersection(*(imageset(f, arg) for arg in x.args))
142
+ else:
143
+ return ImageSet(Lambda(_x, f(_x)), x)
144
+
145
+ @_set_function.register(FunctionUnion, EmptySet)
146
+ def _(f, x):
147
+ return x
148
+
149
+ @_set_function.register(FunctionUnion, Set)
150
+ def _(f, x):
151
+ return ImageSet(Lambda(_x, f(_x)), x)
152
+
153
+ @_set_function.register(FunctionUnion, Range)
154
+ def _(f, self):
155
+ if not self:
156
+ return S.EmptySet
157
+ if not isinstance(f.expr, Expr):
158
+ return
159
+ if self.size == 1:
160
+ return FiniteSet(f(self[0]))
161
+ if f is S.IdentityFunction:
162
+ return self
163
+
164
+ x = f.variables[0]
165
+ expr = f.expr
166
+ # handle f that is linear in f's variable
167
+ if x not in expr.free_symbols or x in expr.diff(x).free_symbols:
168
+ return
169
+ if self.start.is_finite:
170
+ F = f(self.step*x + self.start) # for i in range(len(self))
171
+ else:
172
+ F = f(-self.step*x + self[-1])
173
+ F = expand_mul(F)
174
+ if F != expr:
175
+ return imageset(x, F, Range(self.size))
176
+
177
+ @_set_function.register(FunctionUnion, Integers)
178
+ def _(f, self):
179
+ expr = f.expr
180
+ if not isinstance(expr, Expr):
181
+ return
182
+
183
+ n = f.variables[0]
184
+ if expr == abs(n):
185
+ return S.Naturals0
186
+
187
+ # f(x) + c and f(-x) + c cover the same integers
188
+ # so choose the form that has the fewest negatives
189
+ c = f(0)
190
+ fx = f(n) - c
191
+ f_x = f(-n) - c
192
+ neg_count = lambda e: sum(_.could_extract_minus_sign()
193
+ for _ in Add.make_args(e))
194
+ if neg_count(f_x) < neg_count(fx):
195
+ expr = f_x + c
196
+
197
+ a = Wild('a', exclude=[n])
198
+ b = Wild('b', exclude=[n])
199
+ match = expr.match(a*n + b)
200
+ if match and match[a] and (
201
+ not match[a].atoms(Float) and
202
+ not match[b].atoms(Float)):
203
+ # canonical shift
204
+ a, b = match[a], match[b]
205
+ if a in [1, -1]:
206
+ # drop integer addends in b
207
+ nonint = []
208
+ for bi in Add.make_args(b):
209
+ if not bi.is_integer:
210
+ nonint.append(bi)
211
+ b = Add(*nonint)
212
+ if b.is_number and a.is_real:
213
+ # avoid Mod for complex numbers, #11391
214
+ br, bi = match_real_imag(b)
215
+ if br and br.is_comparable and a.is_comparable:
216
+ br %= a
217
+ b = br + S.ImaginaryUnit*bi
218
+ elif b.is_number and a.is_imaginary:
219
+ br, bi = match_real_imag(b)
220
+ ai = a/S.ImaginaryUnit
221
+ if bi and bi.is_comparable and ai.is_comparable:
222
+ bi %= ai
223
+ b = br + S.ImaginaryUnit*bi
224
+ expr = a*n + b
225
+
226
+ if expr != f.expr:
227
+ return ImageSet(Lambda(n, expr), S.Integers)
228
+
229
+
230
+ @_set_function.register(FunctionUnion, Naturals)
231
+ def _(f, self):
232
+ expr = f.expr
233
+ if not isinstance(expr, Expr):
234
+ return
235
+
236
+ x = f.variables[0]
237
+ if not expr.free_symbols - {x}:
238
+ if expr == abs(x):
239
+ if self is S.Naturals:
240
+ return self
241
+ return S.Naturals0
242
+ step = expr.coeff(x)
243
+ c = expr.subs(x, 0)
244
+ if c.is_Integer and step.is_Integer and expr == step*x + c:
245
+ if self is S.Naturals:
246
+ c += step
247
+ if step > 0:
248
+ if step == 1:
249
+ if c == 0:
250
+ return S.Naturals0
251
+ elif c == 1:
252
+ return S.Naturals
253
+ return Range(c, oo, step)
254
+ return Range(c, -oo, step)
255
+
256
+
257
+ @_set_function.register(FunctionUnion, Reals)
258
+ def _(f, self):
259
+ expr = f.expr
260
+ if not isinstance(expr, Expr):
261
+ return
262
+ return _set_function(f, Interval(-oo, oo))