applied-ai-018 commited on
Commit
94dca98
·
verified ·
1 Parent(s): a01c0fd

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. env-llmeval/lib/python3.10/site-packages/sympy/categories/__init__.py +33 -0
  2. env-llmeval/lib/python3.10/site-packages/sympy/categories/baseclasses.py +979 -0
  3. env-llmeval/lib/python3.10/site-packages/sympy/categories/diagram_drawing.py +2591 -0
  4. env-llmeval/lib/python3.10/site-packages/sympy/categories/tests/__init__.py +0 -0
  5. env-llmeval/lib/python3.10/site-packages/sympy/categories/tests/test_baseclasses.py +209 -0
  6. env-llmeval/lib/python3.10/site-packages/sympy/categories/tests/test_drawing.py +919 -0
  7. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/__init__.py +1 -0
  8. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/__init__.cpython-310.pyc +0 -0
  9. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/_trigonometric_special.cpython-310.pyc +0 -0
  10. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/complexes.cpython-310.pyc +0 -0
  11. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/exponential.cpython-310.pyc +0 -0
  12. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/hyperbolic.cpython-310.pyc +0 -0
  13. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/integers.cpython-310.pyc +0 -0
  14. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/miscellaneous.cpython-310.pyc +0 -0
  15. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/piecewise.cpython-310.pyc +0 -0
  16. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/trigonometric.cpython-310.pyc +0 -0
  17. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/_trigonometric_special.py +260 -0
  18. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/benchmarks/__init__.py +0 -0
  19. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/benchmarks/__pycache__/__init__.cpython-310.pyc +0 -0
  20. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/benchmarks/__pycache__/bench_exp.cpython-310.pyc +0 -0
  21. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/benchmarks/bench_exp.py +11 -0
  22. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/complexes.py +1465 -0
  23. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/exponential.py +1291 -0
  24. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/integers.py +625 -0
  25. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/tests/__init__.py +0 -0
  26. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  27. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_complexes.cpython-310.pyc +0 -0
  28. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_exponential.cpython-310.pyc +0 -0
  29. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_hyperbolic.cpython-310.pyc +0 -0
  30. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_integers.cpython-310.pyc +0 -0
  31. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_interface.cpython-310.pyc +0 -0
  32. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_miscellaneous.cpython-310.pyc +0 -0
  33. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_piecewise.cpython-310.pyc +0 -0
  34. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_trigonometric.cpython-310.pyc +0 -0
  35. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_complexes.py +1018 -0
  36. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_exponential.py +806 -0
  37. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_hyperbolic.py +1460 -0
  38. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_integers.py +632 -0
  39. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_interface.py +72 -0
  40. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_miscellaneous.py +504 -0
  41. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_piecewise.py +1606 -0
  42. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_trigonometric.py +2162 -0
  43. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/trigonometric.py +0 -0
  44. env-llmeval/lib/python3.10/site-packages/sympy/functions/special/__init__.py +1 -0
  45. env-llmeval/lib/python3.10/site-packages/sympy/functions/special/__pycache__/__init__.cpython-310.pyc +0 -0
  46. env-llmeval/lib/python3.10/site-packages/sympy/functions/special/__pycache__/bessel.cpython-310.pyc +0 -0
  47. env-llmeval/lib/python3.10/site-packages/sympy/functions/special/__pycache__/beta_functions.cpython-310.pyc +0 -0
  48. env-llmeval/lib/python3.10/site-packages/sympy/functions/special/__pycache__/elliptic_integrals.cpython-310.pyc +0 -0
  49. env-llmeval/lib/python3.10/site-packages/sympy/functions/special/__pycache__/gamma_functions.cpython-310.pyc +0 -0
  50. env-llmeval/lib/python3.10/site-packages/sympy/functions/special/__pycache__/mathieu_functions.cpython-310.pyc +0 -0
env-llmeval/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
+ ]
env-llmeval/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)
env-llmeval/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",))
env-llmeval/lib/python3.10/site-packages/sympy/categories/tests/__init__.py ADDED
File without changes
env-llmeval/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(""))
env-llmeval/lib/python3.10/site-packages/sympy/categories/tests/test_drawing.py ADDED
@@ -0,0 +1,919 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.categories.diagram_drawing import _GrowableGrid, ArrowStringDescription
2
+ from sympy.categories import (DiagramGrid, Object, NamedMorphism,
3
+ Diagram, XypicDiagramDrawer, xypic_draw_diagram)
4
+ from sympy.sets.sets import FiniteSet
5
+
6
+
7
+ def test_GrowableGrid():
8
+ grid = _GrowableGrid(1, 2)
9
+
10
+ # Check dimensions.
11
+ assert grid.width == 1
12
+ assert grid.height == 2
13
+
14
+ # Check initialization of elements.
15
+ assert grid[0, 0] is None
16
+ assert grid[1, 0] is None
17
+
18
+ # Check assignment to elements.
19
+ grid[0, 0] = 1
20
+ grid[1, 0] = "two"
21
+
22
+ assert grid[0, 0] == 1
23
+ assert grid[1, 0] == "two"
24
+
25
+ # Check appending a row.
26
+ grid.append_row()
27
+
28
+ assert grid.width == 1
29
+ assert grid.height == 3
30
+
31
+ assert grid[0, 0] == 1
32
+ assert grid[1, 0] == "two"
33
+ assert grid[2, 0] is None
34
+
35
+ # Check appending a column.
36
+ grid.append_column()
37
+ assert grid.width == 2
38
+ assert grid.height == 3
39
+
40
+ assert grid[0, 0] == 1
41
+ assert grid[1, 0] == "two"
42
+ assert grid[2, 0] is None
43
+
44
+ assert grid[0, 1] is None
45
+ assert grid[1, 1] is None
46
+ assert grid[2, 1] is None
47
+
48
+ grid = _GrowableGrid(1, 2)
49
+ grid[0, 0] = 1
50
+ grid[1, 0] = "two"
51
+
52
+ # Check prepending a row.
53
+ grid.prepend_row()
54
+ assert grid.width == 1
55
+ assert grid.height == 3
56
+
57
+ assert grid[0, 0] is None
58
+ assert grid[1, 0] == 1
59
+ assert grid[2, 0] == "two"
60
+
61
+ # Check prepending a column.
62
+ grid.prepend_column()
63
+ assert grid.width == 2
64
+ assert grid.height == 3
65
+
66
+ assert grid[0, 0] is None
67
+ assert grid[1, 0] is None
68
+ assert grid[2, 0] is None
69
+
70
+ assert grid[0, 1] is None
71
+ assert grid[1, 1] == 1
72
+ assert grid[2, 1] == "two"
73
+
74
+
75
+ def test_DiagramGrid():
76
+ # Set up some objects and morphisms.
77
+ A = Object("A")
78
+ B = Object("B")
79
+ C = Object("C")
80
+ D = Object("D")
81
+ E = Object("E")
82
+
83
+ f = NamedMorphism(A, B, "f")
84
+ g = NamedMorphism(B, C, "g")
85
+ h = NamedMorphism(D, A, "h")
86
+ k = NamedMorphism(D, B, "k")
87
+
88
+ # A one-morphism diagram.
89
+ d = Diagram([f])
90
+ grid = DiagramGrid(d)
91
+
92
+ assert grid.width == 2
93
+ assert grid.height == 1
94
+ assert grid[0, 0] == A
95
+ assert grid[0, 1] == B
96
+ assert grid.morphisms == {f: FiniteSet()}
97
+
98
+ # A triangle.
99
+ d = Diagram([f, g], {g * f: "unique"})
100
+ grid = DiagramGrid(d)
101
+
102
+ assert grid.width == 2
103
+ assert grid.height == 2
104
+ assert grid[0, 0] == A
105
+ assert grid[0, 1] == B
106
+ assert grid[1, 0] == C
107
+ assert grid[1, 1] is None
108
+ assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(),
109
+ g * f: FiniteSet("unique")}
110
+
111
+ # A triangle with a "loop" morphism.
112
+ l_A = NamedMorphism(A, A, "l_A")
113
+ d = Diagram([f, g, l_A])
114
+ grid = DiagramGrid(d)
115
+
116
+ assert grid.width == 2
117
+ assert grid.height == 2
118
+ assert grid[0, 0] == A
119
+ assert grid[0, 1] == B
120
+ assert grid[1, 0] is None
121
+ assert grid[1, 1] == C
122
+ assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), l_A: FiniteSet()}
123
+
124
+ # A simple diagram.
125
+ d = Diagram([f, g, h, k])
126
+ grid = DiagramGrid(d)
127
+
128
+ assert grid.width == 3
129
+ assert grid.height == 2
130
+ assert grid[0, 0] == A
131
+ assert grid[0, 1] == B
132
+ assert grid[0, 2] == D
133
+ assert grid[1, 0] is None
134
+ assert grid[1, 1] == C
135
+ assert grid[1, 2] is None
136
+ assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), h: FiniteSet(),
137
+ k: FiniteSet()}
138
+
139
+ assert str(grid) == '[[Object("A"), Object("B"), Object("D")], ' \
140
+ '[None, Object("C"), None]]'
141
+
142
+ # A chain of morphisms.
143
+ f = NamedMorphism(A, B, "f")
144
+ g = NamedMorphism(B, C, "g")
145
+ h = NamedMorphism(C, D, "h")
146
+ k = NamedMorphism(D, E, "k")
147
+ d = Diagram([f, g, h, k])
148
+ grid = DiagramGrid(d)
149
+
150
+ assert grid.width == 3
151
+ assert grid.height == 3
152
+ assert grid[0, 0] == A
153
+ assert grid[0, 1] == B
154
+ assert grid[0, 2] is None
155
+ assert grid[1, 0] is None
156
+ assert grid[1, 1] == C
157
+ assert grid[1, 2] == D
158
+ assert grid[2, 0] is None
159
+ assert grid[2, 1] is None
160
+ assert grid[2, 2] == E
161
+ assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), h: FiniteSet(),
162
+ k: FiniteSet()}
163
+
164
+ # A square.
165
+ f = NamedMorphism(A, B, "f")
166
+ g = NamedMorphism(B, D, "g")
167
+ h = NamedMorphism(A, C, "h")
168
+ k = NamedMorphism(C, D, "k")
169
+ d = Diagram([f, g, h, k])
170
+ grid = DiagramGrid(d)
171
+
172
+ assert grid.width == 2
173
+ assert grid.height == 2
174
+ assert grid[0, 0] == A
175
+ assert grid[0, 1] == B
176
+ assert grid[1, 0] == C
177
+ assert grid[1, 1] == D
178
+ assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), h: FiniteSet(),
179
+ k: FiniteSet()}
180
+
181
+ # A strange diagram which resulted from a typo when creating a
182
+ # test for five lemma, but which allowed to stop one extra problem
183
+ # in the algorithm.
184
+ A = Object("A")
185
+ B = Object("B")
186
+ C = Object("C")
187
+ D = Object("D")
188
+ E = Object("E")
189
+ A_ = Object("A'")
190
+ B_ = Object("B'")
191
+ C_ = Object("C'")
192
+ D_ = Object("D'")
193
+ E_ = Object("E'")
194
+
195
+ f = NamedMorphism(A, B, "f")
196
+ g = NamedMorphism(B, C, "g")
197
+ h = NamedMorphism(C, D, "h")
198
+ i = NamedMorphism(D, E, "i")
199
+
200
+ # These 4 morphisms should be between primed objects.
201
+ j = NamedMorphism(A, B, "j")
202
+ k = NamedMorphism(B, C, "k")
203
+ l = NamedMorphism(C, D, "l")
204
+ m = NamedMorphism(D, E, "m")
205
+
206
+ o = NamedMorphism(A, A_, "o")
207
+ p = NamedMorphism(B, B_, "p")
208
+ q = NamedMorphism(C, C_, "q")
209
+ r = NamedMorphism(D, D_, "r")
210
+ s = NamedMorphism(E, E_, "s")
211
+
212
+ d = Diagram([f, g, h, i, j, k, l, m, o, p, q, r, s])
213
+ grid = DiagramGrid(d)
214
+
215
+ assert grid.width == 3
216
+ assert grid.height == 4
217
+ assert grid[0, 0] is None
218
+ assert grid[0, 1] == A
219
+ assert grid[0, 2] == A_
220
+ assert grid[1, 0] == C
221
+ assert grid[1, 1] == B
222
+ assert grid[1, 2] == B_
223
+ assert grid[2, 0] == C_
224
+ assert grid[2, 1] == D
225
+ assert grid[2, 2] == D_
226
+ assert grid[3, 0] is None
227
+ assert grid[3, 1] == E
228
+ assert grid[3, 2] == E_
229
+
230
+ morphisms = {}
231
+ for m in [f, g, h, i, j, k, l, m, o, p, q, r, s]:
232
+ morphisms[m] = FiniteSet()
233
+ assert grid.morphisms == morphisms
234
+
235
+ # A cube.
236
+ A1 = Object("A1")
237
+ A2 = Object("A2")
238
+ A3 = Object("A3")
239
+ A4 = Object("A4")
240
+ A5 = Object("A5")
241
+ A6 = Object("A6")
242
+ A7 = Object("A7")
243
+ A8 = Object("A8")
244
+
245
+ # The top face of the cube.
246
+ f1 = NamedMorphism(A1, A2, "f1")
247
+ f2 = NamedMorphism(A1, A3, "f2")
248
+ f3 = NamedMorphism(A2, A4, "f3")
249
+ f4 = NamedMorphism(A3, A4, "f3")
250
+
251
+ # The bottom face of the cube.
252
+ f5 = NamedMorphism(A5, A6, "f5")
253
+ f6 = NamedMorphism(A5, A7, "f6")
254
+ f7 = NamedMorphism(A6, A8, "f7")
255
+ f8 = NamedMorphism(A7, A8, "f8")
256
+
257
+ # The remaining morphisms.
258
+ f9 = NamedMorphism(A1, A5, "f9")
259
+ f10 = NamedMorphism(A2, A6, "f10")
260
+ f11 = NamedMorphism(A3, A7, "f11")
261
+ f12 = NamedMorphism(A4, A8, "f11")
262
+
263
+ d = Diagram([f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12])
264
+ grid = DiagramGrid(d)
265
+
266
+ assert grid.width == 4
267
+ assert grid.height == 3
268
+ assert grid[0, 0] is None
269
+ assert grid[0, 1] == A5
270
+ assert grid[0, 2] == A6
271
+ assert grid[0, 3] is None
272
+ assert grid[1, 0] is None
273
+ assert grid[1, 1] == A1
274
+ assert grid[1, 2] == A2
275
+ assert grid[1, 3] is None
276
+ assert grid[2, 0] == A7
277
+ assert grid[2, 1] == A3
278
+ assert grid[2, 2] == A4
279
+ assert grid[2, 3] == A8
280
+
281
+ morphisms = {}
282
+ for m in [f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12]:
283
+ morphisms[m] = FiniteSet()
284
+ assert grid.morphisms == morphisms
285
+
286
+ # A line diagram.
287
+ A = Object("A")
288
+ B = Object("B")
289
+ C = Object("C")
290
+ D = Object("D")
291
+ E = Object("E")
292
+
293
+ f = NamedMorphism(A, B, "f")
294
+ g = NamedMorphism(B, C, "g")
295
+ h = NamedMorphism(C, D, "h")
296
+ i = NamedMorphism(D, E, "i")
297
+ d = Diagram([f, g, h, i])
298
+ grid = DiagramGrid(d, layout="sequential")
299
+
300
+ assert grid.width == 5
301
+ assert grid.height == 1
302
+ assert grid[0, 0] == A
303
+ assert grid[0, 1] == B
304
+ assert grid[0, 2] == C
305
+ assert grid[0, 3] == D
306
+ assert grid[0, 4] == E
307
+ assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), h: FiniteSet(),
308
+ i: FiniteSet()}
309
+
310
+ # Test the transposed version.
311
+ grid = DiagramGrid(d, layout="sequential", transpose=True)
312
+
313
+ assert grid.width == 1
314
+ assert grid.height == 5
315
+ assert grid[0, 0] == A
316
+ assert grid[1, 0] == B
317
+ assert grid[2, 0] == C
318
+ assert grid[3, 0] == D
319
+ assert grid[4, 0] == E
320
+ assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), h: FiniteSet(),
321
+ i: FiniteSet()}
322
+
323
+ # A pullback.
324
+ m1 = NamedMorphism(A, B, "m1")
325
+ m2 = NamedMorphism(A, C, "m2")
326
+ s1 = NamedMorphism(B, D, "s1")
327
+ s2 = NamedMorphism(C, D, "s2")
328
+ f1 = NamedMorphism(E, B, "f1")
329
+ f2 = NamedMorphism(E, C, "f2")
330
+ g = NamedMorphism(E, A, "g")
331
+
332
+ d = Diagram([m1, m2, s1, s2, f1, f2], {g: "unique"})
333
+ grid = DiagramGrid(d)
334
+
335
+ assert grid.width == 3
336
+ assert grid.height == 2
337
+ assert grid[0, 0] == A
338
+ assert grid[0, 1] == B
339
+ assert grid[0, 2] == E
340
+ assert grid[1, 0] == C
341
+ assert grid[1, 1] == D
342
+ assert grid[1, 2] is None
343
+
344
+ morphisms = {g: FiniteSet("unique")}
345
+ for m in [m1, m2, s1, s2, f1, f2]:
346
+ morphisms[m] = FiniteSet()
347
+ assert grid.morphisms == morphisms
348
+
349
+ # Test the pullback with sequential layout, just for stress
350
+ # testing.
351
+ grid = DiagramGrid(d, layout="sequential")
352
+
353
+ assert grid.width == 5
354
+ assert grid.height == 1
355
+ assert grid[0, 0] == D
356
+ assert grid[0, 1] == B
357
+ assert grid[0, 2] == A
358
+ assert grid[0, 3] == C
359
+ assert grid[0, 4] == E
360
+ assert grid.morphisms == morphisms
361
+
362
+ # Test a pullback with object grouping.
363
+ grid = DiagramGrid(d, groups=FiniteSet(E, FiniteSet(A, B, C, D)))
364
+
365
+ assert grid.width == 3
366
+ assert grid.height == 2
367
+ assert grid[0, 0] == E
368
+ assert grid[0, 1] == A
369
+ assert grid[0, 2] == B
370
+ assert grid[1, 0] is None
371
+ assert grid[1, 1] == C
372
+ assert grid[1, 2] == D
373
+ assert grid.morphisms == morphisms
374
+
375
+ # Five lemma, actually.
376
+ A = Object("A")
377
+ B = Object("B")
378
+ C = Object("C")
379
+ D = Object("D")
380
+ E = Object("E")
381
+ A_ = Object("A'")
382
+ B_ = Object("B'")
383
+ C_ = Object("C'")
384
+ D_ = Object("D'")
385
+ E_ = Object("E'")
386
+
387
+ f = NamedMorphism(A, B, "f")
388
+ g = NamedMorphism(B, C, "g")
389
+ h = NamedMorphism(C, D, "h")
390
+ i = NamedMorphism(D, E, "i")
391
+
392
+ j = NamedMorphism(A_, B_, "j")
393
+ k = NamedMorphism(B_, C_, "k")
394
+ l = NamedMorphism(C_, D_, "l")
395
+ m = NamedMorphism(D_, E_, "m")
396
+
397
+ o = NamedMorphism(A, A_, "o")
398
+ p = NamedMorphism(B, B_, "p")
399
+ q = NamedMorphism(C, C_, "q")
400
+ r = NamedMorphism(D, D_, "r")
401
+ s = NamedMorphism(E, E_, "s")
402
+
403
+ d = Diagram([f, g, h, i, j, k, l, m, o, p, q, r, s])
404
+ grid = DiagramGrid(d)
405
+
406
+ assert grid.width == 5
407
+ assert grid.height == 3
408
+ assert grid[0, 0] is None
409
+ assert grid[0, 1] == A
410
+ assert grid[0, 2] == A_
411
+ assert grid[0, 3] is None
412
+ assert grid[0, 4] is None
413
+ assert grid[1, 0] == C
414
+ assert grid[1, 1] == B
415
+ assert grid[1, 2] == B_
416
+ assert grid[1, 3] == C_
417
+ assert grid[1, 4] is None
418
+ assert grid[2, 0] == D
419
+ assert grid[2, 1] == E
420
+ assert grid[2, 2] is None
421
+ assert grid[2, 3] == D_
422
+ assert grid[2, 4] == E_
423
+
424
+ morphisms = {}
425
+ for m in [f, g, h, i, j, k, l, m, o, p, q, r, s]:
426
+ morphisms[m] = FiniteSet()
427
+ assert grid.morphisms == morphisms
428
+
429
+ # Test the five lemma with object grouping.
430
+ grid = DiagramGrid(d, FiniteSet(
431
+ FiniteSet(A, B, C, D, E), FiniteSet(A_, B_, C_, D_, E_)))
432
+
433
+ assert grid.width == 6
434
+ assert grid.height == 3
435
+ assert grid[0, 0] == A
436
+ assert grid[0, 1] == B
437
+ assert grid[0, 2] is None
438
+ assert grid[0, 3] == A_
439
+ assert grid[0, 4] == B_
440
+ assert grid[0, 5] is None
441
+ assert grid[1, 0] is None
442
+ assert grid[1, 1] == C
443
+ assert grid[1, 2] == D
444
+ assert grid[1, 3] is None
445
+ assert grid[1, 4] == C_
446
+ assert grid[1, 5] == D_
447
+ assert grid[2, 0] is None
448
+ assert grid[2, 1] is None
449
+ assert grid[2, 2] == E
450
+ assert grid[2, 3] is None
451
+ assert grid[2, 4] is None
452
+ assert grid[2, 5] == E_
453
+ assert grid.morphisms == morphisms
454
+
455
+ # Test the five lemma with object grouping, but mixing containers
456
+ # to represent groups.
457
+ grid = DiagramGrid(d, [(A, B, C, D, E), {A_, B_, C_, D_, E_}])
458
+
459
+ assert grid.width == 6
460
+ assert grid.height == 3
461
+ assert grid[0, 0] == A
462
+ assert grid[0, 1] == B
463
+ assert grid[0, 2] is None
464
+ assert grid[0, 3] == A_
465
+ assert grid[0, 4] == B_
466
+ assert grid[0, 5] is None
467
+ assert grid[1, 0] is None
468
+ assert grid[1, 1] == C
469
+ assert grid[1, 2] == D
470
+ assert grid[1, 3] is None
471
+ assert grid[1, 4] == C_
472
+ assert grid[1, 5] == D_
473
+ assert grid[2, 0] is None
474
+ assert grid[2, 1] is None
475
+ assert grid[2, 2] == E
476
+ assert grid[2, 3] is None
477
+ assert grid[2, 4] is None
478
+ assert grid[2, 5] == E_
479
+ assert grid.morphisms == morphisms
480
+
481
+ # Test the five lemma with object grouping and hints.
482
+ grid = DiagramGrid(d, {
483
+ FiniteSet(A, B, C, D, E): {"layout": "sequential",
484
+ "transpose": True},
485
+ FiniteSet(A_, B_, C_, D_, E_): {"layout": "sequential",
486
+ "transpose": True}},
487
+ transpose=True)
488
+
489
+ assert grid.width == 5
490
+ assert grid.height == 2
491
+ assert grid[0, 0] == A
492
+ assert grid[0, 1] == B
493
+ assert grid[0, 2] == C
494
+ assert grid[0, 3] == D
495
+ assert grid[0, 4] == E
496
+ assert grid[1, 0] == A_
497
+ assert grid[1, 1] == B_
498
+ assert grid[1, 2] == C_
499
+ assert grid[1, 3] == D_
500
+ assert grid[1, 4] == E_
501
+ assert grid.morphisms == morphisms
502
+
503
+ # A two-triangle disconnected diagram.
504
+ f = NamedMorphism(A, B, "f")
505
+ g = NamedMorphism(B, C, "g")
506
+ f_ = NamedMorphism(A_, B_, "f")
507
+ g_ = NamedMorphism(B_, C_, "g")
508
+ d = Diagram([f, g, f_, g_], {g * f: "unique", g_ * f_: "unique"})
509
+ grid = DiagramGrid(d)
510
+
511
+ assert grid.width == 4
512
+ assert grid.height == 2
513
+ assert grid[0, 0] == A
514
+ assert grid[0, 1] == B
515
+ assert grid[0, 2] == A_
516
+ assert grid[0, 3] == B_
517
+ assert grid[1, 0] == C
518
+ assert grid[1, 1] is None
519
+ assert grid[1, 2] == C_
520
+ assert grid[1, 3] is None
521
+ assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), f_: FiniteSet(),
522
+ g_: FiniteSet(), g * f: FiniteSet("unique"),
523
+ g_ * f_: FiniteSet("unique")}
524
+
525
+ # A two-morphism disconnected diagram.
526
+ f = NamedMorphism(A, B, "f")
527
+ g = NamedMorphism(C, D, "g")
528
+ d = Diagram([f, g])
529
+ grid = DiagramGrid(d)
530
+
531
+ assert grid.width == 4
532
+ assert grid.height == 1
533
+ assert grid[0, 0] == A
534
+ assert grid[0, 1] == B
535
+ assert grid[0, 2] == C
536
+ assert grid[0, 3] == D
537
+ assert grid.morphisms == {f: FiniteSet(), g: FiniteSet()}
538
+
539
+ # Test a one-object diagram.
540
+ f = NamedMorphism(A, A, "f")
541
+ d = Diagram([f])
542
+ grid = DiagramGrid(d)
543
+
544
+ assert grid.width == 1
545
+ assert grid.height == 1
546
+ assert grid[0, 0] == A
547
+
548
+ # Test a two-object disconnected diagram.
549
+ g = NamedMorphism(B, B, "g")
550
+ d = Diagram([f, g])
551
+ grid = DiagramGrid(d)
552
+
553
+ assert grid.width == 2
554
+ assert grid.height == 1
555
+ assert grid[0, 0] == A
556
+ assert grid[0, 1] == B
557
+
558
+
559
+ def test_DiagramGrid_pseudopod():
560
+ # Test a diagram in which even growing a pseudopod does not
561
+ # eventually help.
562
+ A = Object("A")
563
+ B = Object("B")
564
+ C = Object("C")
565
+ D = Object("D")
566
+ E = Object("E")
567
+ F = Object("F")
568
+ A_ = Object("A'")
569
+ B_ = Object("B'")
570
+ C_ = Object("C'")
571
+ D_ = Object("D'")
572
+ E_ = Object("E'")
573
+
574
+ f1 = NamedMorphism(A, B, "f1")
575
+ f2 = NamedMorphism(A, C, "f2")
576
+ f3 = NamedMorphism(A, D, "f3")
577
+ f4 = NamedMorphism(A, E, "f4")
578
+ f5 = NamedMorphism(A, A_, "f5")
579
+ f6 = NamedMorphism(A, B_, "f6")
580
+ f7 = NamedMorphism(A, C_, "f7")
581
+ f8 = NamedMorphism(A, D_, "f8")
582
+ f9 = NamedMorphism(A, E_, "f9")
583
+ f10 = NamedMorphism(A, F, "f10")
584
+ d = Diagram([f1, f2, f3, f4, f5, f6, f7, f8, f9, f10])
585
+ grid = DiagramGrid(d)
586
+
587
+ assert grid.width == 5
588
+ assert grid.height == 3
589
+ assert grid[0, 0] == E
590
+ assert grid[0, 1] == C
591
+ assert grid[0, 2] == C_
592
+ assert grid[0, 3] == E_
593
+ assert grid[0, 4] == F
594
+ assert grid[1, 0] == D
595
+ assert grid[1, 1] == A
596
+ assert grid[1, 2] == A_
597
+ assert grid[1, 3] is None
598
+ assert grid[1, 4] is None
599
+ assert grid[2, 0] == D_
600
+ assert grid[2, 1] == B
601
+ assert grid[2, 2] == B_
602
+ assert grid[2, 3] is None
603
+ assert grid[2, 4] is None
604
+
605
+ morphisms = {}
606
+ for f in [f1, f2, f3, f4, f5, f6, f7, f8, f9, f10]:
607
+ morphisms[f] = FiniteSet()
608
+ assert grid.morphisms == morphisms
609
+
610
+
611
+ def test_ArrowStringDescription():
612
+ astr = ArrowStringDescription("cm", "", None, "", "", "d", "r", "_", "f")
613
+ assert str(astr) == "\\ar[dr]_{f}"
614
+
615
+ astr = ArrowStringDescription("cm", "", 12, "", "", "d", "r", "_", "f")
616
+ assert str(astr) == "\\ar[dr]_{f}"
617
+
618
+ astr = ArrowStringDescription("cm", "^", 12, "", "", "d", "r", "_", "f")
619
+ assert str(astr) == "\\ar@/^12cm/[dr]_{f}"
620
+
621
+ astr = ArrowStringDescription("cm", "", 12, "r", "", "d", "r", "_", "f")
622
+ assert str(astr) == "\\ar[dr]_{f}"
623
+
624
+ astr = ArrowStringDescription("cm", "", 12, "r", "u", "d", "r", "_", "f")
625
+ assert str(astr) == "\\ar@(r,u)[dr]_{f}"
626
+
627
+ astr = ArrowStringDescription("cm", "", 12, "r", "u", "d", "r", "_", "f")
628
+ assert str(astr) == "\\ar@(r,u)[dr]_{f}"
629
+
630
+ astr = ArrowStringDescription("cm", "", 12, "r", "u", "d", "r", "_", "f")
631
+ astr.arrow_style = "{-->}"
632
+ assert str(astr) == "\\ar@(r,u)@{-->}[dr]_{f}"
633
+
634
+ astr = ArrowStringDescription("cm", "_", 12, "", "", "d", "r", "_", "f")
635
+ astr.arrow_style = "{-->}"
636
+ assert str(astr) == "\\ar@/_12cm/@{-->}[dr]_{f}"
637
+
638
+
639
+ def test_XypicDiagramDrawer_line():
640
+ # A linear diagram.
641
+ A = Object("A")
642
+ B = Object("B")
643
+ C = Object("C")
644
+ D = Object("D")
645
+ E = Object("E")
646
+
647
+ f = NamedMorphism(A, B, "f")
648
+ g = NamedMorphism(B, C, "g")
649
+ h = NamedMorphism(C, D, "h")
650
+ i = NamedMorphism(D, E, "i")
651
+ d = Diagram([f, g, h, i])
652
+ grid = DiagramGrid(d, layout="sequential")
653
+ drawer = XypicDiagramDrawer()
654
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
655
+ "A \\ar[r]^{f} & B \\ar[r]^{g} & C \\ar[r]^{h} & D \\ar[r]^{i} & E \n" \
656
+ "}\n"
657
+
658
+ # The same diagram, transposed.
659
+ grid = DiagramGrid(d, layout="sequential", transpose=True)
660
+ drawer = XypicDiagramDrawer()
661
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
662
+ "A \\ar[d]^{f} \\\\\n" \
663
+ "B \\ar[d]^{g} \\\\\n" \
664
+ "C \\ar[d]^{h} \\\\\n" \
665
+ "D \\ar[d]^{i} \\\\\n" \
666
+ "E \n" \
667
+ "}\n"
668
+
669
+
670
+ def test_XypicDiagramDrawer_triangle():
671
+ # A triangle diagram.
672
+ A = Object("A")
673
+ B = Object("B")
674
+ C = Object("C")
675
+ f = NamedMorphism(A, B, "f")
676
+ g = NamedMorphism(B, C, "g")
677
+
678
+ d = Diagram([f, g], {g * f: "unique"})
679
+ grid = DiagramGrid(d)
680
+ drawer = XypicDiagramDrawer()
681
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
682
+ "A \\ar[d]_{g\\circ f} \\ar[r]^{f} & B \\ar[ld]^{g} \\\\\n" \
683
+ "C & \n" \
684
+ "}\n"
685
+
686
+ # The same diagram, transposed.
687
+ grid = DiagramGrid(d, transpose=True)
688
+ drawer = XypicDiagramDrawer()
689
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
690
+ "A \\ar[r]^{g\\circ f} \\ar[d]_{f} & C \\\\\n" \
691
+ "B \\ar[ru]_{g} & \n" \
692
+ "}\n"
693
+
694
+ # The same diagram, with a masked morphism.
695
+ assert drawer.draw(d, grid, masked=[g]) == "\\xymatrix{\n" \
696
+ "A \\ar[r]^{g\\circ f} \\ar[d]_{f} & C \\\\\n" \
697
+ "B & \n" \
698
+ "}\n"
699
+
700
+ # The same diagram with a formatter for "unique".
701
+ def formatter(astr):
702
+ astr.label = "\\exists !" + astr.label
703
+ astr.arrow_style = "{-->}"
704
+
705
+ drawer.arrow_formatters["unique"] = formatter
706
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
707
+ "A \\ar@{-->}[r]^{\\exists !g\\circ f} \\ar[d]_{f} & C \\\\\n" \
708
+ "B \\ar[ru]_{g} & \n" \
709
+ "}\n"
710
+
711
+ # The same diagram with a default formatter.
712
+ def default_formatter(astr):
713
+ astr.label_displacement = "(0.45)"
714
+
715
+ drawer.default_arrow_formatter = default_formatter
716
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
717
+ "A \\ar@{-->}[r]^(0.45){\\exists !g\\circ f} \\ar[d]_(0.45){f} & C \\\\\n" \
718
+ "B \\ar[ru]_(0.45){g} & \n" \
719
+ "}\n"
720
+
721
+ # A triangle diagram with a lot of morphisms between the same
722
+ # objects.
723
+ f1 = NamedMorphism(B, A, "f1")
724
+ f2 = NamedMorphism(A, B, "f2")
725
+ g1 = NamedMorphism(C, B, "g1")
726
+ g2 = NamedMorphism(B, C, "g2")
727
+ d = Diagram([f, f1, f2, g, g1, g2], {f1 * g1: "unique", g2 * f2: "unique"})
728
+
729
+ grid = DiagramGrid(d, transpose=True)
730
+ drawer = XypicDiagramDrawer()
731
+ assert drawer.draw(d, grid, masked=[f1*g1*g2*f2, g2*f2*f1*g1]) == \
732
+ "\\xymatrix{\n" \
733
+ "A \\ar[r]^{g_{2}\\circ f_{2}} \\ar[d]_{f} \\ar@/^3mm/[d]^{f_{2}} " \
734
+ "& C \\ar@/^3mm/[l]^{f_{1}\\circ g_{1}} \\ar@/^3mm/[ld]^{g_{1}} \\\\\n" \
735
+ "B \\ar@/^3mm/[u]^{f_{1}} \\ar[ru]_{g} \\ar@/^3mm/[ru]^{g_{2}} & \n" \
736
+ "}\n"
737
+
738
+
739
+ def test_XypicDiagramDrawer_cube():
740
+ # A cube diagram.
741
+ A1 = Object("A1")
742
+ A2 = Object("A2")
743
+ A3 = Object("A3")
744
+ A4 = Object("A4")
745
+ A5 = Object("A5")
746
+ A6 = Object("A6")
747
+ A7 = Object("A7")
748
+ A8 = Object("A8")
749
+
750
+ # The top face of the cube.
751
+ f1 = NamedMorphism(A1, A2, "f1")
752
+ f2 = NamedMorphism(A1, A3, "f2")
753
+ f3 = NamedMorphism(A2, A4, "f3")
754
+ f4 = NamedMorphism(A3, A4, "f3")
755
+
756
+ # The bottom face of the cube.
757
+ f5 = NamedMorphism(A5, A6, "f5")
758
+ f6 = NamedMorphism(A5, A7, "f6")
759
+ f7 = NamedMorphism(A6, A8, "f7")
760
+ f8 = NamedMorphism(A7, A8, "f8")
761
+
762
+ # The remaining morphisms.
763
+ f9 = NamedMorphism(A1, A5, "f9")
764
+ f10 = NamedMorphism(A2, A6, "f10")
765
+ f11 = NamedMorphism(A3, A7, "f11")
766
+ f12 = NamedMorphism(A4, A8, "f11")
767
+
768
+ d = Diagram([f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12])
769
+ grid = DiagramGrid(d)
770
+ drawer = XypicDiagramDrawer()
771
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
772
+ "& A_{5} \\ar[r]^{f_{5}} \\ar[ldd]_{f_{6}} & A_{6} \\ar[rdd]^{f_{7}} " \
773
+ "& \\\\\n" \
774
+ "& A_{1} \\ar[r]^{f_{1}} \\ar[d]^{f_{2}} \\ar[u]^{f_{9}} & A_{2} " \
775
+ "\\ar[d]^{f_{3}} \\ar[u]_{f_{10}} & \\\\\n" \
776
+ "A_{7} \\ar@/_3mm/[rrr]_{f_{8}} & A_{3} \\ar[r]^{f_{3}} \\ar[l]_{f_{11}} " \
777
+ "& A_{4} \\ar[r]^{f_{11}} & A_{8} \n" \
778
+ "}\n"
779
+
780
+ # The same diagram, transposed.
781
+ grid = DiagramGrid(d, transpose=True)
782
+ drawer = XypicDiagramDrawer()
783
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
784
+ "& & A_{7} \\ar@/^3mm/[ddd]^{f_{8}} \\\\\n" \
785
+ "A_{5} \\ar[d]_{f_{5}} \\ar[rru]^{f_{6}} & A_{1} \\ar[d]^{f_{1}} " \
786
+ "\\ar[r]^{f_{2}} \\ar[l]^{f_{9}} & A_{3} \\ar[d]_{f_{3}} " \
787
+ "\\ar[u]^{f_{11}} \\\\\n" \
788
+ "A_{6} \\ar[rrd]_{f_{7}} & A_{2} \\ar[r]^{f_{3}} \\ar[l]^{f_{10}} " \
789
+ "& A_{4} \\ar[d]_{f_{11}} \\\\\n" \
790
+ "& & A_{8} \n" \
791
+ "}\n"
792
+
793
+
794
+ def test_XypicDiagramDrawer_curved_and_loops():
795
+ # A simple diagram, with a curved arrow.
796
+ A = Object("A")
797
+ B = Object("B")
798
+ C = Object("C")
799
+ D = Object("D")
800
+
801
+ f = NamedMorphism(A, B, "f")
802
+ g = NamedMorphism(B, C, "g")
803
+ h = NamedMorphism(D, A, "h")
804
+ k = NamedMorphism(D, B, "k")
805
+ d = Diagram([f, g, h, k])
806
+ grid = DiagramGrid(d)
807
+ drawer = XypicDiagramDrawer()
808
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
809
+ "A \\ar[r]_{f} & B \\ar[d]^{g} & D \\ar[l]^{k} \\ar@/_3mm/[ll]_{h} \\\\\n" \
810
+ "& C & \n" \
811
+ "}\n"
812
+
813
+ # The same diagram, transposed.
814
+ grid = DiagramGrid(d, transpose=True)
815
+ drawer = XypicDiagramDrawer()
816
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
817
+ "A \\ar[d]^{f} & \\\\\n" \
818
+ "B \\ar[r]^{g} & C \\\\\n" \
819
+ "D \\ar[u]_{k} \\ar@/^3mm/[uu]^{h} & \n" \
820
+ "}\n"
821
+
822
+ # The same diagram, larger and rotated.
823
+ assert drawer.draw(d, grid, diagram_format="@+1cm@dr") == \
824
+ "\\xymatrix@+1cm@dr{\n" \
825
+ "A \\ar[d]^{f} & \\\\\n" \
826
+ "B \\ar[r]^{g} & C \\\\\n" \
827
+ "D \\ar[u]_{k} \\ar@/^3mm/[uu]^{h} & \n" \
828
+ "}\n"
829
+
830
+ # A simple diagram with three curved arrows.
831
+ h1 = NamedMorphism(D, A, "h1")
832
+ h2 = NamedMorphism(A, D, "h2")
833
+ k = NamedMorphism(D, B, "k")
834
+ d = Diagram([f, g, h, k, h1, h2])
835
+ grid = DiagramGrid(d)
836
+ drawer = XypicDiagramDrawer()
837
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
838
+ "A \\ar[r]_{f} \\ar@/^3mm/[rr]^{h_{2}} & B \\ar[d]^{g} & D \\ar[l]^{k} " \
839
+ "\\ar@/_7mm/[ll]_{h} \\ar@/_11mm/[ll]_{h_{1}} \\\\\n" \
840
+ "& C & \n" \
841
+ "}\n"
842
+
843
+ # The same diagram, transposed.
844
+ grid = DiagramGrid(d, transpose=True)
845
+ drawer = XypicDiagramDrawer()
846
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
847
+ "A \\ar[d]^{f} \\ar@/_3mm/[dd]_{h_{2}} & \\\\\n" \
848
+ "B \\ar[r]^{g} & C \\\\\n" \
849
+ "D \\ar[u]_{k} \\ar@/^7mm/[uu]^{h} \\ar@/^11mm/[uu]^{h_{1}} & \n" \
850
+ "}\n"
851
+
852
+ # The same diagram, with "loop" morphisms.
853
+ l_A = NamedMorphism(A, A, "l_A")
854
+ l_D = NamedMorphism(D, D, "l_D")
855
+ l_C = NamedMorphism(C, C, "l_C")
856
+ d = Diagram([f, g, h, k, h1, h2, l_A, l_D, l_C])
857
+ grid = DiagramGrid(d)
858
+ drawer = XypicDiagramDrawer()
859
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
860
+ "A \\ar[r]_{f} \\ar@/^3mm/[rr]^{h_{2}} \\ar@(u,l)[]^{l_{A}} " \
861
+ "& B \\ar[d]^{g} & D \\ar[l]^{k} \\ar@/_7mm/[ll]_{h} " \
862
+ "\\ar@/_11mm/[ll]_{h_{1}} \\ar@(r,u)[]^{l_{D}} \\\\\n" \
863
+ "& C \\ar@(l,d)[]^{l_{C}} & \n" \
864
+ "}\n"
865
+
866
+ # The same diagram with "loop" morphisms, transposed.
867
+ grid = DiagramGrid(d, transpose=True)
868
+ drawer = XypicDiagramDrawer()
869
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
870
+ "A \\ar[d]^{f} \\ar@/_3mm/[dd]_{h_{2}} \\ar@(r,u)[]^{l_{A}} & \\\\\n" \
871
+ "B \\ar[r]^{g} & C \\ar@(r,u)[]^{l_{C}} \\\\\n" \
872
+ "D \\ar[u]_{k} \\ar@/^7mm/[uu]^{h} \\ar@/^11mm/[uu]^{h_{1}} " \
873
+ "\\ar@(l,d)[]^{l_{D}} & \n" \
874
+ "}\n"
875
+
876
+ # The same diagram with two "loop" morphisms per object.
877
+ l_A_ = NamedMorphism(A, A, "n_A")
878
+ l_D_ = NamedMorphism(D, D, "n_D")
879
+ l_C_ = NamedMorphism(C, C, "n_C")
880
+ d = Diagram([f, g, h, k, h1, h2, l_A, l_D, l_C, l_A_, l_D_, l_C_])
881
+ grid = DiagramGrid(d)
882
+ drawer = XypicDiagramDrawer()
883
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
884
+ "A \\ar[r]_{f} \\ar@/^3mm/[rr]^{h_{2}} \\ar@(u,l)[]^{l_{A}} " \
885
+ "\\ar@/^3mm/@(l,d)[]^{n_{A}} & B \\ar[d]^{g} & D \\ar[l]^{k} " \
886
+ "\\ar@/_7mm/[ll]_{h} \\ar@/_11mm/[ll]_{h_{1}} \\ar@(r,u)[]^{l_{D}} " \
887
+ "\\ar@/^3mm/@(d,r)[]^{n_{D}} \\\\\n" \
888
+ "& C \\ar@(l,d)[]^{l_{C}} \\ar@/^3mm/@(d,r)[]^{n_{C}} & \n" \
889
+ "}\n"
890
+
891
+ # The same diagram with two "loop" morphisms per object, transposed.
892
+ grid = DiagramGrid(d, transpose=True)
893
+ drawer = XypicDiagramDrawer()
894
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
895
+ "A \\ar[d]^{f} \\ar@/_3mm/[dd]_{h_{2}} \\ar@(r,u)[]^{l_{A}} " \
896
+ "\\ar@/^3mm/@(u,l)[]^{n_{A}} & \\\\\n" \
897
+ "B \\ar[r]^{g} & C \\ar@(r,u)[]^{l_{C}} \\ar@/^3mm/@(d,r)[]^{n_{C}} \\\\\n" \
898
+ "D \\ar[u]_{k} \\ar@/^7mm/[uu]^{h} \\ar@/^11mm/[uu]^{h_{1}} " \
899
+ "\\ar@(l,d)[]^{l_{D}} \\ar@/^3mm/@(d,r)[]^{n_{D}} & \n" \
900
+ "}\n"
901
+
902
+
903
+ def test_xypic_draw_diagram():
904
+ # A linear diagram.
905
+ A = Object("A")
906
+ B = Object("B")
907
+ C = Object("C")
908
+ D = Object("D")
909
+ E = Object("E")
910
+
911
+ f = NamedMorphism(A, B, "f")
912
+ g = NamedMorphism(B, C, "g")
913
+ h = NamedMorphism(C, D, "h")
914
+ i = NamedMorphism(D, E, "i")
915
+ d = Diagram([f, g, h, i])
916
+
917
+ grid = DiagramGrid(d, layout="sequential")
918
+ drawer = XypicDiagramDrawer()
919
+ assert drawer.draw(d, grid) == xypic_draw_diagram(d, layout="sequential")
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Stub __init__.py for sympy.functions.elementary
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (191 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/_trigonometric_special.cpython-310.pyc ADDED
Binary file (8.55 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/complexes.cpython-310.pyc ADDED
Binary file (39 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/exponential.cpython-310.pyc ADDED
Binary file (34.8 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/hyperbolic.cpython-310.pyc ADDED
Binary file (55.8 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/integers.cpython-310.pyc ADDED
Binary file (16 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/miscellaneous.cpython-310.pyc ADDED
Binary file (30.8 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/piecewise.cpython-310.pyc ADDED
Binary file (44.7 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/trigonometric.cpython-310.pyc ADDED
Binary file (91.6 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/_trigonometric_special.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""A module for special angle forumlas for trigonometric functions
2
+
3
+ TODO
4
+ ====
5
+
6
+ This module should be developed in the future to contain direct squrae root
7
+ representation of
8
+
9
+ .. math
10
+ F(\frac{n}{m} \pi)
11
+
12
+ for every
13
+
14
+ - $m \in \{ 3, 5, 17, 257, 65537 \}$
15
+ - $n \in \mathbb{N}$, $0 \le n < m$
16
+ - $F \in \{\sin, \cos, \tan, \csc, \sec, \cot\}$
17
+
18
+ Without multi-step rewrites
19
+ (e.g. $\tan \to \cos/\sin \to \cos/\sqrt \to \ sqrt$)
20
+ or using chebyshev identities
21
+ (e.g. $\cos \to \cos + \cos^2 + \cdots \to \sqrt{} + \sqrt{}^2 + \cdots $),
22
+ which are trivial to implement in sympy,
23
+ and had used to give overly complicated expressions.
24
+
25
+ The reference can be found below, if anyone may need help implementing them.
26
+
27
+ References
28
+ ==========
29
+
30
+ .. [*] Gottlieb, Christian. (1999). The Simple and straightforward construction
31
+ of the regular 257-gon. The Mathematical Intelligencer. 21. 31-37.
32
+ 10.1007/BF03024829.
33
+ .. [*] https://resources.wolframcloud.com/FunctionRepository/resources/Cos2PiOverFermatPrime
34
+ """
35
+ from __future__ import annotations
36
+ from typing import Callable
37
+ from functools import reduce
38
+ from sympy.core.expr import Expr
39
+ from sympy.core.singleton import S
40
+ from sympy.core.numbers import igcdex, Integer
41
+ from sympy.functions.elementary.miscellaneous import sqrt
42
+ from sympy.core.cache import cacheit
43
+
44
+
45
+ def migcdex(*x: int) -> tuple[tuple[int, ...], int]:
46
+ r"""Compute extended gcd for multiple integers.
47
+
48
+ Explanation
49
+ ===========
50
+
51
+ Given the integers $x_1, \cdots, x_n$ and
52
+ an extended gcd for multiple arguments are defined as a solution
53
+ $(y_1, \cdots, y_n), g$ for the diophantine equation
54
+ $x_1 y_1 + \cdots + x_n y_n = g$ such that
55
+ $g = \gcd(x_1, \cdots, x_n)$.
56
+
57
+ Examples
58
+ ========
59
+
60
+ >>> from sympy.functions.elementary._trigonometric_special import migcdex
61
+ >>> migcdex()
62
+ ((), 0)
63
+ >>> migcdex(4)
64
+ ((1,), 4)
65
+ >>> migcdex(4, 6)
66
+ ((-1, 1), 2)
67
+ >>> migcdex(6, 10, 15)
68
+ ((1, 1, -1), 1)
69
+ """
70
+ if not x:
71
+ return (), 0
72
+
73
+ if len(x) == 1:
74
+ return (1,), x[0]
75
+
76
+ if len(x) == 2:
77
+ u, v, h = igcdex(x[0], x[1])
78
+ return (u, v), h
79
+
80
+ y, g = migcdex(*x[1:])
81
+ u, v, h = igcdex(x[0], g)
82
+ return (u, *(v * i for i in y)), h
83
+
84
+
85
+ def ipartfrac(*denoms: int) -> tuple[int, ...]:
86
+ r"""Compute the the partial fraction decomposition.
87
+
88
+ Explanation
89
+ ===========
90
+
91
+ Given a rational number $\frac{1}{q_1 \cdots q_n}$ where all
92
+ $q_1, \cdots, q_n$ are pairwise coprime,
93
+
94
+ A partial fraction decomposition is defined as
95
+
96
+ .. math::
97
+ \frac{1}{q_1 \cdots q_n} = \frac{p_1}{q_1} + \cdots + \frac{p_n}{q_n}
98
+
99
+ And it can be derived from solving the following diophantine equation for
100
+ the $p_1, \cdots, p_n$
101
+
102
+ .. math::
103
+ 1 = p_1 \prod_{i \ne 1}q_i + \cdots + p_n \prod_{i \ne n}q_i
104
+
105
+ Where $q_1, \cdots, q_n$ being pairwise coprime implies
106
+ $\gcd(\prod_{i \ne 1}q_i, \cdots, \prod_{i \ne n}q_i) = 1$,
107
+ which guarantees the existance of the solution.
108
+
109
+ It is sufficient to compute partial fraction decomposition only
110
+ for numerator $1$ because partial fraction decomposition for any
111
+ $\frac{n}{q_1 \cdots q_n}$ can be easily computed by multiplying
112
+ the result by $n$ afterwards.
113
+
114
+ Parameters
115
+ ==========
116
+
117
+ denoms : int
118
+ The pairwise coprime integer denominators $q_i$ which defines the
119
+ rational number $\frac{1}{q_1 \cdots q_n}$
120
+
121
+ Returns
122
+ =======
123
+
124
+ tuple[int, ...]
125
+ The list of numerators which semantically corresponds to $p_i$ of the
126
+ partial fraction decomposition
127
+ $\frac{1}{q_1 \cdots q_n} = \frac{p_1}{q_1} + \cdots + \frac{p_n}{q_n}$
128
+
129
+ Examples
130
+ ========
131
+
132
+ >>> from sympy import Rational, Mul
133
+ >>> from sympy.functions.elementary._trigonometric_special import ipartfrac
134
+
135
+ >>> denoms = 2, 3, 5
136
+ >>> numers = ipartfrac(2, 3, 5)
137
+ >>> numers
138
+ (1, 7, -14)
139
+
140
+ >>> Rational(1, Mul(*denoms))
141
+ 1/30
142
+ >>> out = 0
143
+ >>> for n, d in zip(numers, denoms):
144
+ ... out += Rational(n, d)
145
+ >>> out
146
+ 1/30
147
+ """
148
+ if not denoms:
149
+ return ()
150
+
151
+ def mul(x: int, y: int) -> int:
152
+ return x * y
153
+
154
+ denom = reduce(mul, denoms)
155
+ a = [denom // x for x in denoms]
156
+ h, _ = migcdex(*a)
157
+ return h
158
+
159
+
160
+ def fermat_coords(n: int) -> list[int] | None:
161
+ """If n can be factored in terms of Fermat primes with
162
+ multiplicity of each being 1, return those primes, else
163
+ None
164
+ """
165
+ primes = []
166
+ for p in [3, 5, 17, 257, 65537]:
167
+ quotient, remainder = divmod(n, p)
168
+ if remainder == 0:
169
+ n = quotient
170
+ primes.append(p)
171
+ if n == 1:
172
+ return primes
173
+ return None
174
+
175
+
176
+ @cacheit
177
+ def cos_3() -> Expr:
178
+ r"""Computes $\cos \frac{\pi}{3}$ in square roots"""
179
+ return S.Half
180
+
181
+
182
+ @cacheit
183
+ def cos_5() -> Expr:
184
+ r"""Computes $\cos \frac{\pi}{5}$ in square roots"""
185
+ return (sqrt(5) + 1) / 4
186
+
187
+
188
+ @cacheit
189
+ def cos_17() -> Expr:
190
+ r"""Computes $\cos \frac{\pi}{17}$ in square roots"""
191
+ return sqrt(
192
+ (15 + sqrt(17)) / 32 + sqrt(2) * (sqrt(17 - sqrt(17)) +
193
+ sqrt(sqrt(2) * (-8 * sqrt(17 + sqrt(17)) - (1 - sqrt(17))
194
+ * sqrt(17 - sqrt(17))) + 6 * sqrt(17) + 34)) / 32)
195
+
196
+
197
+ @cacheit
198
+ def cos_257() -> Expr:
199
+ r"""Computes $\cos \frac{\pi}{257}$ in square roots
200
+
201
+ References
202
+ ==========
203
+
204
+ .. [*] https://math.stackexchange.com/questions/516142/how-does-cos2-pi-257-look-like-in-real-radicals
205
+ .. [*] https://r-knott.surrey.ac.uk/Fibonacci/simpleTrig.html
206
+ """
207
+ def f1(a: Expr, b: Expr) -> tuple[Expr, Expr]:
208
+ return (a + sqrt(a**2 + b)) / 2, (a - sqrt(a**2 + b)) / 2
209
+
210
+ def f2(a: Expr, b: Expr) -> Expr:
211
+ return (a - sqrt(a**2 + b))/2
212
+
213
+ t1, t2 = f1(S.NegativeOne, Integer(256))
214
+ z1, z3 = f1(t1, Integer(64))
215
+ z2, z4 = f1(t2, Integer(64))
216
+ y1, y5 = f1(z1, 4*(5 + t1 + 2*z1))
217
+ y6, y2 = f1(z2, 4*(5 + t2 + 2*z2))
218
+ y3, y7 = f1(z3, 4*(5 + t1 + 2*z3))
219
+ y8, y4 = f1(z4, 4*(5 + t2 + 2*z4))
220
+ x1, x9 = f1(y1, -4*(t1 + y1 + y3 + 2*y6))
221
+ x2, x10 = f1(y2, -4*(t2 + y2 + y4 + 2*y7))
222
+ x3, x11 = f1(y3, -4*(t1 + y3 + y5 + 2*y8))
223
+ x4, x12 = f1(y4, -4*(t2 + y4 + y6 + 2*y1))
224
+ x5, x13 = f1(y5, -4*(t1 + y5 + y7 + 2*y2))
225
+ x6, x14 = f1(y6, -4*(t2 + y6 + y8 + 2*y3))
226
+ x15, x7 = f1(y7, -4*(t1 + y7 + y1 + 2*y4))
227
+ x8, x16 = f1(y8, -4*(t2 + y8 + y2 + 2*y5))
228
+ v1 = f2(x1, -4*(x1 + x2 + x3 + x6))
229
+ v2 = f2(x2, -4*(x2 + x3 + x4 + x7))
230
+ v3 = f2(x8, -4*(x8 + x9 + x10 + x13))
231
+ v4 = f2(x9, -4*(x9 + x10 + x11 + x14))
232
+ v5 = f2(x10, -4*(x10 + x11 + x12 + x15))
233
+ v6 = f2(x16, -4*(x16 + x1 + x2 + x5))
234
+ u1 = -f2(-v1, -4*(v2 + v3))
235
+ u2 = -f2(-v4, -4*(v5 + v6))
236
+ w1 = -2*f2(-u1, -4*u2)
237
+ return sqrt(sqrt(2)*sqrt(w1 + 4)/8 + S.Half)
238
+
239
+
240
+ def cos_table() -> dict[int, Callable[[], Expr]]:
241
+ r"""Lazily evaluated table for $\cos \frac{\pi}{n}$ in square roots for
242
+ $n \in \{3, 5, 17, 257, 65537\}$.
243
+
244
+ Notes
245
+ =====
246
+
247
+ 65537 is the only other known Fermat prime and it is nearly impossible to
248
+ build in the current SymPy due to performance issues.
249
+
250
+ References
251
+ ==========
252
+
253
+ https://r-knott.surrey.ac.uk/Fibonacci/simpleTrig.html
254
+ """
255
+ return {
256
+ 3: cos_3,
257
+ 5: cos_5,
258
+ 17: cos_17,
259
+ 257: cos_257
260
+ }
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/benchmarks/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/benchmarks/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (202 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/benchmarks/__pycache__/bench_exp.cpython-310.pyc ADDED
Binary file (527 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/benchmarks/bench_exp.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.symbol import symbols
2
+ from sympy.functions.elementary.exponential import exp
3
+
4
+ x, y = symbols('x,y')
5
+
6
+ e = exp(2*x)
7
+ q = exp(3*x)
8
+
9
+
10
+ def timeit_exp_subs():
11
+ e.subs(q, y)
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/complexes.py ADDED
@@ -0,0 +1,1465 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Tuple as tTuple
2
+
3
+ from sympy.core import S, Add, Mul, sympify, Symbol, Dummy, Basic
4
+ from sympy.core.expr import Expr
5
+ from sympy.core.exprtools import factor_terms
6
+ from sympy.core.function import (Function, Derivative, ArgumentIndexError,
7
+ AppliedUndef, expand_mul)
8
+ from sympy.core.logic import fuzzy_not, fuzzy_or
9
+ from sympy.core.numbers import pi, I, oo
10
+ from sympy.core.power import Pow
11
+ from sympy.core.relational import Eq
12
+ from sympy.functions.elementary.miscellaneous import sqrt
13
+ from sympy.functions.elementary.piecewise import Piecewise
14
+
15
+ ###############################################################################
16
+ ######################### REAL and IMAGINARY PARTS ############################
17
+ ###############################################################################
18
+
19
+
20
+ class re(Function):
21
+ """
22
+ Returns real part of expression. This function performs only
23
+ elementary analysis and so it will fail to decompose properly
24
+ more complicated expressions. If completely simplified result
25
+ is needed then use ``Basic.as_real_imag()`` or perform complex
26
+ expansion on instance of this function.
27
+
28
+ Examples
29
+ ========
30
+
31
+ >>> from sympy import re, im, I, E, symbols
32
+ >>> x, y = symbols('x y', real=True)
33
+ >>> re(2*E)
34
+ 2*E
35
+ >>> re(2*I + 17)
36
+ 17
37
+ >>> re(2*I)
38
+ 0
39
+ >>> re(im(x) + x*I + 2)
40
+ 2
41
+ >>> re(5 + I + 2)
42
+ 7
43
+
44
+ Parameters
45
+ ==========
46
+
47
+ arg : Expr
48
+ Real or complex expression.
49
+
50
+ Returns
51
+ =======
52
+
53
+ expr : Expr
54
+ Real part of expression.
55
+
56
+ See Also
57
+ ========
58
+
59
+ im
60
+ """
61
+
62
+ args: tTuple[Expr]
63
+
64
+ is_extended_real = True
65
+ unbranched = True # implicitly works on the projection to C
66
+ _singularities = True # non-holomorphic
67
+
68
+ @classmethod
69
+ def eval(cls, arg):
70
+ if arg is S.NaN:
71
+ return S.NaN
72
+ elif arg is S.ComplexInfinity:
73
+ return S.NaN
74
+ elif arg.is_extended_real:
75
+ return arg
76
+ elif arg.is_imaginary or (I*arg).is_extended_real:
77
+ return S.Zero
78
+ elif arg.is_Matrix:
79
+ return arg.as_real_imag()[0]
80
+ elif arg.is_Function and isinstance(arg, conjugate):
81
+ return re(arg.args[0])
82
+ else:
83
+
84
+ included, reverted, excluded = [], [], []
85
+ args = Add.make_args(arg)
86
+ for term in args:
87
+ coeff = term.as_coefficient(I)
88
+
89
+ if coeff is not None:
90
+ if not coeff.is_extended_real:
91
+ reverted.append(coeff)
92
+ elif not term.has(I) and term.is_extended_real:
93
+ excluded.append(term)
94
+ else:
95
+ # Try to do some advanced expansion. If
96
+ # impossible, don't try to do re(arg) again
97
+ # (because this is what we are trying to do now).
98
+ real_imag = term.as_real_imag(ignore=arg)
99
+ if real_imag:
100
+ excluded.append(real_imag[0])
101
+ else:
102
+ included.append(term)
103
+
104
+ if len(args) != len(included):
105
+ a, b, c = (Add(*xs) for xs in [included, reverted, excluded])
106
+
107
+ return cls(a) - im(b) + c
108
+
109
+ def as_real_imag(self, deep=True, **hints):
110
+ """
111
+ Returns the real number with a zero imaginary part.
112
+
113
+ """
114
+ return (self, S.Zero)
115
+
116
+ def _eval_derivative(self, x):
117
+ if x.is_extended_real or self.args[0].is_extended_real:
118
+ return re(Derivative(self.args[0], x, evaluate=True))
119
+ if x.is_imaginary or self.args[0].is_imaginary:
120
+ return -I \
121
+ * im(Derivative(self.args[0], x, evaluate=True))
122
+
123
+ def _eval_rewrite_as_im(self, arg, **kwargs):
124
+ return self.args[0] - I*im(self.args[0])
125
+
126
+ def _eval_is_algebraic(self):
127
+ return self.args[0].is_algebraic
128
+
129
+ def _eval_is_zero(self):
130
+ # is_imaginary implies nonzero
131
+ return fuzzy_or([self.args[0].is_imaginary, self.args[0].is_zero])
132
+
133
+ def _eval_is_finite(self):
134
+ if self.args[0].is_finite:
135
+ return True
136
+
137
+ def _eval_is_complex(self):
138
+ if self.args[0].is_finite:
139
+ return True
140
+
141
+
142
+ class im(Function):
143
+ """
144
+ Returns imaginary part of expression. This function performs only
145
+ elementary analysis and so it will fail to decompose properly more
146
+ complicated expressions. If completely simplified result is needed then
147
+ use ``Basic.as_real_imag()`` or perform complex expansion on instance of
148
+ this function.
149
+
150
+ Examples
151
+ ========
152
+
153
+ >>> from sympy import re, im, E, I
154
+ >>> from sympy.abc import x, y
155
+ >>> im(2*E)
156
+ 0
157
+ >>> im(2*I + 17)
158
+ 2
159
+ >>> im(x*I)
160
+ re(x)
161
+ >>> im(re(x) + y)
162
+ im(y)
163
+ >>> im(2 + 3*I)
164
+ 3
165
+
166
+ Parameters
167
+ ==========
168
+
169
+ arg : Expr
170
+ Real or complex expression.
171
+
172
+ Returns
173
+ =======
174
+
175
+ expr : Expr
176
+ Imaginary part of expression.
177
+
178
+ See Also
179
+ ========
180
+
181
+ re
182
+ """
183
+
184
+ args: tTuple[Expr]
185
+
186
+ is_extended_real = True
187
+ unbranched = True # implicitly works on the projection to C
188
+ _singularities = True # non-holomorphic
189
+
190
+ @classmethod
191
+ def eval(cls, arg):
192
+ if arg is S.NaN:
193
+ return S.NaN
194
+ elif arg is S.ComplexInfinity:
195
+ return S.NaN
196
+ elif arg.is_extended_real:
197
+ return S.Zero
198
+ elif arg.is_imaginary or (I*arg).is_extended_real:
199
+ return -I * arg
200
+ elif arg.is_Matrix:
201
+ return arg.as_real_imag()[1]
202
+ elif arg.is_Function and isinstance(arg, conjugate):
203
+ return -im(arg.args[0])
204
+ else:
205
+ included, reverted, excluded = [], [], []
206
+ args = Add.make_args(arg)
207
+ for term in args:
208
+ coeff = term.as_coefficient(I)
209
+
210
+ if coeff is not None:
211
+ if not coeff.is_extended_real:
212
+ reverted.append(coeff)
213
+ else:
214
+ excluded.append(coeff)
215
+ elif term.has(I) or not term.is_extended_real:
216
+ # Try to do some advanced expansion. If
217
+ # impossible, don't try to do im(arg) again
218
+ # (because this is what we are trying to do now).
219
+ real_imag = term.as_real_imag(ignore=arg)
220
+ if real_imag:
221
+ excluded.append(real_imag[1])
222
+ else:
223
+ included.append(term)
224
+
225
+ if len(args) != len(included):
226
+ a, b, c = (Add(*xs) for xs in [included, reverted, excluded])
227
+
228
+ return cls(a) + re(b) + c
229
+
230
+ def as_real_imag(self, deep=True, **hints):
231
+ """
232
+ Return the imaginary part with a zero real part.
233
+
234
+ """
235
+ return (self, S.Zero)
236
+
237
+ def _eval_derivative(self, x):
238
+ if x.is_extended_real or self.args[0].is_extended_real:
239
+ return im(Derivative(self.args[0], x, evaluate=True))
240
+ if x.is_imaginary or self.args[0].is_imaginary:
241
+ return -I \
242
+ * re(Derivative(self.args[0], x, evaluate=True))
243
+
244
+ def _eval_rewrite_as_re(self, arg, **kwargs):
245
+ return -I*(self.args[0] - re(self.args[0]))
246
+
247
+ def _eval_is_algebraic(self):
248
+ return self.args[0].is_algebraic
249
+
250
+ def _eval_is_zero(self):
251
+ return self.args[0].is_extended_real
252
+
253
+ def _eval_is_finite(self):
254
+ if self.args[0].is_finite:
255
+ return True
256
+
257
+ def _eval_is_complex(self):
258
+ if self.args[0].is_finite:
259
+ return True
260
+
261
+ ###############################################################################
262
+ ############### SIGN, ABSOLUTE VALUE, ARGUMENT and CONJUGATION ################
263
+ ###############################################################################
264
+
265
+ class sign(Function):
266
+ """
267
+ Returns the complex sign of an expression:
268
+
269
+ Explanation
270
+ ===========
271
+
272
+ If the expression is real the sign will be:
273
+
274
+ * $1$ if expression is positive
275
+ * $0$ if expression is equal to zero
276
+ * $-1$ if expression is negative
277
+
278
+ If the expression is imaginary the sign will be:
279
+
280
+ * $I$ if im(expression) is positive
281
+ * $-I$ if im(expression) is negative
282
+
283
+ Otherwise an unevaluated expression will be returned. When evaluated, the
284
+ result (in general) will be ``cos(arg(expr)) + I*sin(arg(expr))``.
285
+
286
+ Examples
287
+ ========
288
+
289
+ >>> from sympy import sign, I
290
+
291
+ >>> sign(-1)
292
+ -1
293
+ >>> sign(0)
294
+ 0
295
+ >>> sign(-3*I)
296
+ -I
297
+ >>> sign(1 + I)
298
+ sign(1 + I)
299
+ >>> _.evalf()
300
+ 0.707106781186548 + 0.707106781186548*I
301
+
302
+ Parameters
303
+ ==========
304
+
305
+ arg : Expr
306
+ Real or imaginary expression.
307
+
308
+ Returns
309
+ =======
310
+
311
+ expr : Expr
312
+ Complex sign of expression.
313
+
314
+ See Also
315
+ ========
316
+
317
+ Abs, conjugate
318
+ """
319
+
320
+ is_complex = True
321
+ _singularities = True
322
+
323
+ def doit(self, **hints):
324
+ s = super().doit()
325
+ if s == self and self.args[0].is_zero is False:
326
+ return self.args[0] / Abs(self.args[0])
327
+ return s
328
+
329
+ @classmethod
330
+ def eval(cls, arg):
331
+ # handle what we can
332
+ if arg.is_Mul:
333
+ c, args = arg.as_coeff_mul()
334
+ unk = []
335
+ s = sign(c)
336
+ for a in args:
337
+ if a.is_extended_negative:
338
+ s = -s
339
+ elif a.is_extended_positive:
340
+ pass
341
+ else:
342
+ if a.is_imaginary:
343
+ ai = im(a)
344
+ if ai.is_comparable: # i.e. a = I*real
345
+ s *= I
346
+ if ai.is_extended_negative:
347
+ # can't use sign(ai) here since ai might not be
348
+ # a Number
349
+ s = -s
350
+ else:
351
+ unk.append(a)
352
+ else:
353
+ unk.append(a)
354
+ if c is S.One and len(unk) == len(args):
355
+ return None
356
+ return s * cls(arg._new_rawargs(*unk))
357
+ if arg is S.NaN:
358
+ return S.NaN
359
+ if arg.is_zero: # it may be an Expr that is zero
360
+ return S.Zero
361
+ if arg.is_extended_positive:
362
+ return S.One
363
+ if arg.is_extended_negative:
364
+ return S.NegativeOne
365
+ if arg.is_Function:
366
+ if isinstance(arg, sign):
367
+ return arg
368
+ if arg.is_imaginary:
369
+ if arg.is_Pow and arg.exp is S.Half:
370
+ # we catch this because non-trivial sqrt args are not expanded
371
+ # e.g. sqrt(1-sqrt(2)) --x--> to I*sqrt(sqrt(2) - 1)
372
+ return I
373
+ arg2 = -I * arg
374
+ if arg2.is_extended_positive:
375
+ return I
376
+ if arg2.is_extended_negative:
377
+ return -I
378
+
379
+ def _eval_Abs(self):
380
+ if fuzzy_not(self.args[0].is_zero):
381
+ return S.One
382
+
383
+ def _eval_conjugate(self):
384
+ return sign(conjugate(self.args[0]))
385
+
386
+ def _eval_derivative(self, x):
387
+ if self.args[0].is_extended_real:
388
+ from sympy.functions.special.delta_functions import DiracDelta
389
+ return 2 * Derivative(self.args[0], x, evaluate=True) \
390
+ * DiracDelta(self.args[0])
391
+ elif self.args[0].is_imaginary:
392
+ from sympy.functions.special.delta_functions import DiracDelta
393
+ return 2 * Derivative(self.args[0], x, evaluate=True) \
394
+ * DiracDelta(-I * self.args[0])
395
+
396
+ def _eval_is_nonnegative(self):
397
+ if self.args[0].is_nonnegative:
398
+ return True
399
+
400
+ def _eval_is_nonpositive(self):
401
+ if self.args[0].is_nonpositive:
402
+ return True
403
+
404
+ def _eval_is_imaginary(self):
405
+ return self.args[0].is_imaginary
406
+
407
+ def _eval_is_integer(self):
408
+ return self.args[0].is_extended_real
409
+
410
+ def _eval_is_zero(self):
411
+ return self.args[0].is_zero
412
+
413
+ def _eval_power(self, other):
414
+ if (
415
+ fuzzy_not(self.args[0].is_zero) and
416
+ other.is_integer and
417
+ other.is_even
418
+ ):
419
+ return S.One
420
+
421
+ def _eval_nseries(self, x, n, logx, cdir=0):
422
+ arg0 = self.args[0]
423
+ x0 = arg0.subs(x, 0)
424
+ if x0 != 0:
425
+ return self.func(x0)
426
+ if cdir != 0:
427
+ cdir = arg0.dir(x, cdir)
428
+ return -S.One if re(cdir) < 0 else S.One
429
+
430
+ def _eval_rewrite_as_Piecewise(self, arg, **kwargs):
431
+ if arg.is_extended_real:
432
+ return Piecewise((1, arg > 0), (-1, arg < 0), (0, True))
433
+
434
+ def _eval_rewrite_as_Heaviside(self, arg, **kwargs):
435
+ from sympy.functions.special.delta_functions import Heaviside
436
+ if arg.is_extended_real:
437
+ return Heaviside(arg) * 2 - 1
438
+
439
+ def _eval_rewrite_as_Abs(self, arg, **kwargs):
440
+ return Piecewise((0, Eq(arg, 0)), (arg / Abs(arg), True))
441
+
442
+ def _eval_simplify(self, **kwargs):
443
+ return self.func(factor_terms(self.args[0])) # XXX include doit?
444
+
445
+
446
+ class Abs(Function):
447
+ """
448
+ Return the absolute value of the argument.
449
+
450
+ Explanation
451
+ ===========
452
+
453
+ This is an extension of the built-in function ``abs()`` to accept symbolic
454
+ values. If you pass a SymPy expression to the built-in ``abs()``, it will
455
+ pass it automatically to ``Abs()``.
456
+
457
+ Examples
458
+ ========
459
+
460
+ >>> from sympy import Abs, Symbol, S, I
461
+ >>> Abs(-1)
462
+ 1
463
+ >>> x = Symbol('x', real=True)
464
+ >>> Abs(-x)
465
+ Abs(x)
466
+ >>> Abs(x**2)
467
+ x**2
468
+ >>> abs(-x) # The Python built-in
469
+ Abs(x)
470
+ >>> Abs(3*x + 2*I)
471
+ sqrt(9*x**2 + 4)
472
+ >>> Abs(8*I)
473
+ 8
474
+
475
+ Note that the Python built-in will return either an Expr or int depending on
476
+ the argument::
477
+
478
+ >>> type(abs(-1))
479
+ <... 'int'>
480
+ >>> type(abs(S.NegativeOne))
481
+ <class 'sympy.core.numbers.One'>
482
+
483
+ Abs will always return a SymPy object.
484
+
485
+ Parameters
486
+ ==========
487
+
488
+ arg : Expr
489
+ Real or complex expression.
490
+
491
+ Returns
492
+ =======
493
+
494
+ expr : Expr
495
+ Absolute value returned can be an expression or integer depending on
496
+ input arg.
497
+
498
+ See Also
499
+ ========
500
+
501
+ sign, conjugate
502
+ """
503
+
504
+ args: tTuple[Expr]
505
+
506
+ is_extended_real = True
507
+ is_extended_negative = False
508
+ is_extended_nonnegative = True
509
+ unbranched = True
510
+ _singularities = True # non-holomorphic
511
+
512
+ def fdiff(self, argindex=1):
513
+ """
514
+ Get the first derivative of the argument to Abs().
515
+
516
+ """
517
+ if argindex == 1:
518
+ return sign(self.args[0])
519
+ else:
520
+ raise ArgumentIndexError(self, argindex)
521
+
522
+ @classmethod
523
+ def eval(cls, arg):
524
+ from sympy.simplify.simplify import signsimp
525
+
526
+ if hasattr(arg, '_eval_Abs'):
527
+ obj = arg._eval_Abs()
528
+ if obj is not None:
529
+ return obj
530
+ if not isinstance(arg, Expr):
531
+ raise TypeError("Bad argument type for Abs(): %s" % type(arg))
532
+
533
+ # handle what we can
534
+ arg = signsimp(arg, evaluate=False)
535
+ n, d = arg.as_numer_denom()
536
+ if d.free_symbols and not n.free_symbols:
537
+ return cls(n)/cls(d)
538
+
539
+ if arg.is_Mul:
540
+ known = []
541
+ unk = []
542
+ for t in arg.args:
543
+ if t.is_Pow and t.exp.is_integer and t.exp.is_negative:
544
+ bnew = cls(t.base)
545
+ if isinstance(bnew, cls):
546
+ unk.append(t)
547
+ else:
548
+ known.append(Pow(bnew, t.exp))
549
+ else:
550
+ tnew = cls(t)
551
+ if isinstance(tnew, cls):
552
+ unk.append(t)
553
+ else:
554
+ known.append(tnew)
555
+ known = Mul(*known)
556
+ unk = cls(Mul(*unk), evaluate=False) if unk else S.One
557
+ return known*unk
558
+ if arg is S.NaN:
559
+ return S.NaN
560
+ if arg is S.ComplexInfinity:
561
+ return oo
562
+ from sympy.functions.elementary.exponential import exp, log
563
+
564
+ if arg.is_Pow:
565
+ base, exponent = arg.as_base_exp()
566
+ if base.is_extended_real:
567
+ if exponent.is_integer:
568
+ if exponent.is_even:
569
+ return arg
570
+ if base is S.NegativeOne:
571
+ return S.One
572
+ return Abs(base)**exponent
573
+ if base.is_extended_nonnegative:
574
+ return base**re(exponent)
575
+ if base.is_extended_negative:
576
+ return (-base)**re(exponent)*exp(-pi*im(exponent))
577
+ return
578
+ elif not base.has(Symbol): # complex base
579
+ # express base**exponent as exp(exponent*log(base))
580
+ a, b = log(base).as_real_imag()
581
+ z = a + I*b
582
+ return exp(re(exponent*z))
583
+ if isinstance(arg, exp):
584
+ return exp(re(arg.args[0]))
585
+ if isinstance(arg, AppliedUndef):
586
+ if arg.is_positive:
587
+ return arg
588
+ elif arg.is_negative:
589
+ return -arg
590
+ return
591
+ if arg.is_Add and arg.has(oo, S.NegativeInfinity):
592
+ if any(a.is_infinite for a in arg.as_real_imag()):
593
+ return oo
594
+ if arg.is_zero:
595
+ return S.Zero
596
+ if arg.is_extended_nonnegative:
597
+ return arg
598
+ if arg.is_extended_nonpositive:
599
+ return -arg
600
+ if arg.is_imaginary:
601
+ arg2 = -I * arg
602
+ if arg2.is_extended_nonnegative:
603
+ return arg2
604
+ if arg.is_extended_real:
605
+ return
606
+ # reject result if all new conjugates are just wrappers around
607
+ # an expression that was already in the arg
608
+ conj = signsimp(arg.conjugate(), evaluate=False)
609
+ new_conj = conj.atoms(conjugate) - arg.atoms(conjugate)
610
+ if new_conj and all(arg.has(i.args[0]) for i in new_conj):
611
+ return
612
+ if arg != conj and arg != -conj:
613
+ ignore = arg.atoms(Abs)
614
+ abs_free_arg = arg.xreplace({i: Dummy(real=True) for i in ignore})
615
+ unk = [a for a in abs_free_arg.free_symbols if a.is_extended_real is None]
616
+ if not unk or not all(conj.has(conjugate(u)) for u in unk):
617
+ return sqrt(expand_mul(arg*conj))
618
+
619
+ def _eval_is_real(self):
620
+ if self.args[0].is_finite:
621
+ return True
622
+
623
+ def _eval_is_integer(self):
624
+ if self.args[0].is_extended_real:
625
+ return self.args[0].is_integer
626
+
627
+ def _eval_is_extended_nonzero(self):
628
+ return fuzzy_not(self._args[0].is_zero)
629
+
630
+ def _eval_is_zero(self):
631
+ return self._args[0].is_zero
632
+
633
+ def _eval_is_extended_positive(self):
634
+ return fuzzy_not(self._args[0].is_zero)
635
+
636
+ def _eval_is_rational(self):
637
+ if self.args[0].is_extended_real:
638
+ return self.args[0].is_rational
639
+
640
+ def _eval_is_even(self):
641
+ if self.args[0].is_extended_real:
642
+ return self.args[0].is_even
643
+
644
+ def _eval_is_odd(self):
645
+ if self.args[0].is_extended_real:
646
+ return self.args[0].is_odd
647
+
648
+ def _eval_is_algebraic(self):
649
+ return self.args[0].is_algebraic
650
+
651
+ def _eval_power(self, exponent):
652
+ if self.args[0].is_extended_real and exponent.is_integer:
653
+ if exponent.is_even:
654
+ return self.args[0]**exponent
655
+ elif exponent is not S.NegativeOne and exponent.is_Integer:
656
+ return self.args[0]**(exponent - 1)*self
657
+ return
658
+
659
+ def _eval_nseries(self, x, n, logx, cdir=0):
660
+ from sympy.functions.elementary.exponential import log
661
+ direction = self.args[0].leadterm(x)[0]
662
+ if direction.has(log(x)):
663
+ direction = direction.subs(log(x), logx)
664
+ s = self.args[0]._eval_nseries(x, n=n, logx=logx)
665
+ return (sign(direction)*s).expand()
666
+
667
+ def _eval_derivative(self, x):
668
+ if self.args[0].is_extended_real or self.args[0].is_imaginary:
669
+ return Derivative(self.args[0], x, evaluate=True) \
670
+ * sign(conjugate(self.args[0]))
671
+ rv = (re(self.args[0]) * Derivative(re(self.args[0]), x,
672
+ evaluate=True) + im(self.args[0]) * Derivative(im(self.args[0]),
673
+ x, evaluate=True)) / Abs(self.args[0])
674
+ return rv.rewrite(sign)
675
+
676
+ def _eval_rewrite_as_Heaviside(self, arg, **kwargs):
677
+ # Note this only holds for real arg (since Heaviside is not defined
678
+ # for complex arguments).
679
+ from sympy.functions.special.delta_functions import Heaviside
680
+ if arg.is_extended_real:
681
+ return arg*(Heaviside(arg) - Heaviside(-arg))
682
+
683
+ def _eval_rewrite_as_Piecewise(self, arg, **kwargs):
684
+ if arg.is_extended_real:
685
+ return Piecewise((arg, arg >= 0), (-arg, True))
686
+ elif arg.is_imaginary:
687
+ return Piecewise((I*arg, I*arg >= 0), (-I*arg, True))
688
+
689
+ def _eval_rewrite_as_sign(self, arg, **kwargs):
690
+ return arg/sign(arg)
691
+
692
+ def _eval_rewrite_as_conjugate(self, arg, **kwargs):
693
+ return sqrt(arg*conjugate(arg))
694
+
695
+
696
+ class arg(Function):
697
+ r"""
698
+ Returns the argument (in radians) of a complex number. The argument is
699
+ evaluated in consistent convention with ``atan2`` where the branch-cut is
700
+ taken along the negative real axis and ``arg(z)`` is in the interval
701
+ $(-\pi,\pi]$. For a positive number, the argument is always 0; the
702
+ argument of a negative number is $\pi$; and the argument of 0
703
+ is undefined and returns ``nan``. So the ``arg`` function will never nest
704
+ greater than 3 levels since at the 4th application, the result must be
705
+ nan; for a real number, nan is returned on the 3rd application.
706
+
707
+ Examples
708
+ ========
709
+
710
+ >>> from sympy import arg, I, sqrt, Dummy
711
+ >>> from sympy.abc import x
712
+ >>> arg(2.0)
713
+ 0
714
+ >>> arg(I)
715
+ pi/2
716
+ >>> arg(sqrt(2) + I*sqrt(2))
717
+ pi/4
718
+ >>> arg(sqrt(3)/2 + I/2)
719
+ pi/6
720
+ >>> arg(4 + 3*I)
721
+ atan(3/4)
722
+ >>> arg(0.8 + 0.6*I)
723
+ 0.643501108793284
724
+ >>> arg(arg(arg(arg(x))))
725
+ nan
726
+ >>> real = Dummy(real=True)
727
+ >>> arg(arg(arg(real)))
728
+ nan
729
+
730
+ Parameters
731
+ ==========
732
+
733
+ arg : Expr
734
+ Real or complex expression.
735
+
736
+ Returns
737
+ =======
738
+
739
+ value : Expr
740
+ Returns arc tangent of arg measured in radians.
741
+
742
+ """
743
+
744
+ is_extended_real = True
745
+ is_real = True
746
+ is_finite = True
747
+ _singularities = True # non-holomorphic
748
+
749
+ @classmethod
750
+ def eval(cls, arg):
751
+ a = arg
752
+ for i in range(3):
753
+ if isinstance(a, cls):
754
+ a = a.args[0]
755
+ else:
756
+ if i == 2 and a.is_extended_real:
757
+ return S.NaN
758
+ break
759
+ else:
760
+ return S.NaN
761
+ from sympy.functions.elementary.exponential import exp_polar
762
+ if isinstance(arg, exp_polar):
763
+ return periodic_argument(arg, oo)
764
+ if not arg.is_Atom:
765
+ c, arg_ = factor_terms(arg).as_coeff_Mul()
766
+ if arg_.is_Mul:
767
+ arg_ = Mul(*[a if (sign(a) not in (-1, 1)) else
768
+ sign(a) for a in arg_.args])
769
+ arg_ = sign(c)*arg_
770
+ else:
771
+ arg_ = arg
772
+ if any(i.is_extended_positive is None for i in arg_.atoms(AppliedUndef)):
773
+ return
774
+ from sympy.functions.elementary.trigonometric import atan2
775
+ x, y = arg_.as_real_imag()
776
+ rv = atan2(y, x)
777
+ if rv.is_number:
778
+ return rv
779
+ if arg_ != arg:
780
+ return cls(arg_, evaluate=False)
781
+
782
+ def _eval_derivative(self, t):
783
+ x, y = self.args[0].as_real_imag()
784
+ return (x * Derivative(y, t, evaluate=True) - y *
785
+ Derivative(x, t, evaluate=True)) / (x**2 + y**2)
786
+
787
+ def _eval_rewrite_as_atan2(self, arg, **kwargs):
788
+ from sympy.functions.elementary.trigonometric import atan2
789
+ x, y = self.args[0].as_real_imag()
790
+ return atan2(y, x)
791
+
792
+
793
+ class conjugate(Function):
794
+ """
795
+ Returns the *complex conjugate* [1]_ of an argument.
796
+ In mathematics, the complex conjugate of a complex number
797
+ is given by changing the sign of the imaginary part.
798
+
799
+ Thus, the conjugate of the complex number
800
+ :math:`a + ib` (where $a$ and $b$ are real numbers) is :math:`a - ib`
801
+
802
+ Examples
803
+ ========
804
+
805
+ >>> from sympy import conjugate, I
806
+ >>> conjugate(2)
807
+ 2
808
+ >>> conjugate(I)
809
+ -I
810
+ >>> conjugate(3 + 2*I)
811
+ 3 - 2*I
812
+ >>> conjugate(5 - I)
813
+ 5 + I
814
+
815
+ Parameters
816
+ ==========
817
+
818
+ arg : Expr
819
+ Real or complex expression.
820
+
821
+ Returns
822
+ =======
823
+
824
+ arg : Expr
825
+ Complex conjugate of arg as real, imaginary or mixed expression.
826
+
827
+ See Also
828
+ ========
829
+
830
+ sign, Abs
831
+
832
+ References
833
+ ==========
834
+
835
+ .. [1] https://en.wikipedia.org/wiki/Complex_conjugation
836
+ """
837
+ _singularities = True # non-holomorphic
838
+
839
+ @classmethod
840
+ def eval(cls, arg):
841
+ obj = arg._eval_conjugate()
842
+ if obj is not None:
843
+ return obj
844
+
845
+ def inverse(self):
846
+ return conjugate
847
+
848
+ def _eval_Abs(self):
849
+ return Abs(self.args[0], evaluate=True)
850
+
851
+ def _eval_adjoint(self):
852
+ return transpose(self.args[0])
853
+
854
+ def _eval_conjugate(self):
855
+ return self.args[0]
856
+
857
+ def _eval_derivative(self, x):
858
+ if x.is_real:
859
+ return conjugate(Derivative(self.args[0], x, evaluate=True))
860
+ elif x.is_imaginary:
861
+ return -conjugate(Derivative(self.args[0], x, evaluate=True))
862
+
863
+ def _eval_transpose(self):
864
+ return adjoint(self.args[0])
865
+
866
+ def _eval_is_algebraic(self):
867
+ return self.args[0].is_algebraic
868
+
869
+
870
+ class transpose(Function):
871
+ """
872
+ Linear map transposition.
873
+
874
+ Examples
875
+ ========
876
+
877
+ >>> from sympy import transpose, Matrix, MatrixSymbol
878
+ >>> A = MatrixSymbol('A', 25, 9)
879
+ >>> transpose(A)
880
+ A.T
881
+ >>> B = MatrixSymbol('B', 9, 22)
882
+ >>> transpose(B)
883
+ B.T
884
+ >>> transpose(A*B)
885
+ B.T*A.T
886
+ >>> M = Matrix([[4, 5], [2, 1], [90, 12]])
887
+ >>> M
888
+ Matrix([
889
+ [ 4, 5],
890
+ [ 2, 1],
891
+ [90, 12]])
892
+ >>> transpose(M)
893
+ Matrix([
894
+ [4, 2, 90],
895
+ [5, 1, 12]])
896
+
897
+ Parameters
898
+ ==========
899
+
900
+ arg : Matrix
901
+ Matrix or matrix expression to take the transpose of.
902
+
903
+ Returns
904
+ =======
905
+
906
+ value : Matrix
907
+ Transpose of arg.
908
+
909
+ """
910
+
911
+ @classmethod
912
+ def eval(cls, arg):
913
+ obj = arg._eval_transpose()
914
+ if obj is not None:
915
+ return obj
916
+
917
+ def _eval_adjoint(self):
918
+ return conjugate(self.args[0])
919
+
920
+ def _eval_conjugate(self):
921
+ return adjoint(self.args[0])
922
+
923
+ def _eval_transpose(self):
924
+ return self.args[0]
925
+
926
+
927
+ class adjoint(Function):
928
+ """
929
+ Conjugate transpose or Hermite conjugation.
930
+
931
+ Examples
932
+ ========
933
+
934
+ >>> from sympy import adjoint, MatrixSymbol
935
+ >>> A = MatrixSymbol('A', 10, 5)
936
+ >>> adjoint(A)
937
+ Adjoint(A)
938
+
939
+ Parameters
940
+ ==========
941
+
942
+ arg : Matrix
943
+ Matrix or matrix expression to take the adjoint of.
944
+
945
+ Returns
946
+ =======
947
+
948
+ value : Matrix
949
+ Represents the conjugate transpose or Hermite
950
+ conjugation of arg.
951
+
952
+ """
953
+
954
+ @classmethod
955
+ def eval(cls, arg):
956
+ obj = arg._eval_adjoint()
957
+ if obj is not None:
958
+ return obj
959
+ obj = arg._eval_transpose()
960
+ if obj is not None:
961
+ return conjugate(obj)
962
+
963
+ def _eval_adjoint(self):
964
+ return self.args[0]
965
+
966
+ def _eval_conjugate(self):
967
+ return transpose(self.args[0])
968
+
969
+ def _eval_transpose(self):
970
+ return conjugate(self.args[0])
971
+
972
+ def _latex(self, printer, exp=None, *args):
973
+ arg = printer._print(self.args[0])
974
+ tex = r'%s^{\dagger}' % arg
975
+ if exp:
976
+ tex = r'\left(%s\right)^{%s}' % (tex, exp)
977
+ return tex
978
+
979
+ def _pretty(self, printer, *args):
980
+ from sympy.printing.pretty.stringpict import prettyForm
981
+ pform = printer._print(self.args[0], *args)
982
+ if printer._use_unicode:
983
+ pform = pform**prettyForm('\N{DAGGER}')
984
+ else:
985
+ pform = pform**prettyForm('+')
986
+ return pform
987
+
988
+ ###############################################################################
989
+ ############### HANDLING OF POLAR NUMBERS #####################################
990
+ ###############################################################################
991
+
992
+
993
+ class polar_lift(Function):
994
+ """
995
+ Lift argument to the Riemann surface of the logarithm, using the
996
+ standard branch.
997
+
998
+ Examples
999
+ ========
1000
+
1001
+ >>> from sympy import Symbol, polar_lift, I
1002
+ >>> p = Symbol('p', polar=True)
1003
+ >>> x = Symbol('x')
1004
+ >>> polar_lift(4)
1005
+ 4*exp_polar(0)
1006
+ >>> polar_lift(-4)
1007
+ 4*exp_polar(I*pi)
1008
+ >>> polar_lift(-I)
1009
+ exp_polar(-I*pi/2)
1010
+ >>> polar_lift(I + 2)
1011
+ polar_lift(2 + I)
1012
+
1013
+ >>> polar_lift(4*x)
1014
+ 4*polar_lift(x)
1015
+ >>> polar_lift(4*p)
1016
+ 4*p
1017
+
1018
+ Parameters
1019
+ ==========
1020
+
1021
+ arg : Expr
1022
+ Real or complex expression.
1023
+
1024
+ See Also
1025
+ ========
1026
+
1027
+ sympy.functions.elementary.exponential.exp_polar
1028
+ periodic_argument
1029
+ """
1030
+
1031
+ is_polar = True
1032
+ is_comparable = False # Cannot be evalf'd.
1033
+
1034
+ @classmethod
1035
+ def eval(cls, arg):
1036
+ from sympy.functions.elementary.complexes import arg as argument
1037
+ if arg.is_number:
1038
+ ar = argument(arg)
1039
+ # In general we want to affirm that something is known,
1040
+ # e.g. `not ar.has(argument) and not ar.has(atan)`
1041
+ # but for now we will just be more restrictive and
1042
+ # see that it has evaluated to one of the known values.
1043
+ if ar in (0, pi/2, -pi/2, pi):
1044
+ from sympy.functions.elementary.exponential import exp_polar
1045
+ return exp_polar(I*ar)*abs(arg)
1046
+
1047
+ if arg.is_Mul:
1048
+ args = arg.args
1049
+ else:
1050
+ args = [arg]
1051
+ included = []
1052
+ excluded = []
1053
+ positive = []
1054
+ for arg in args:
1055
+ if arg.is_polar:
1056
+ included += [arg]
1057
+ elif arg.is_positive:
1058
+ positive += [arg]
1059
+ else:
1060
+ excluded += [arg]
1061
+ if len(excluded) < len(args):
1062
+ if excluded:
1063
+ return Mul(*(included + positive))*polar_lift(Mul(*excluded))
1064
+ elif included:
1065
+ return Mul(*(included + positive))
1066
+ else:
1067
+ from sympy.functions.elementary.exponential import exp_polar
1068
+ return Mul(*positive)*exp_polar(0)
1069
+
1070
+ def _eval_evalf(self, prec):
1071
+ """ Careful! any evalf of polar numbers is flaky """
1072
+ return self.args[0]._eval_evalf(prec)
1073
+
1074
+ def _eval_Abs(self):
1075
+ return Abs(self.args[0], evaluate=True)
1076
+
1077
+
1078
+ class periodic_argument(Function):
1079
+ r"""
1080
+ Represent the argument on a quotient of the Riemann surface of the
1081
+ logarithm. That is, given a period $P$, always return a value in
1082
+ $(-P/2, P/2]$, by using $\exp(PI) = 1$.
1083
+
1084
+ Examples
1085
+ ========
1086
+
1087
+ >>> from sympy import exp_polar, periodic_argument
1088
+ >>> from sympy import I, pi
1089
+ >>> periodic_argument(exp_polar(10*I*pi), 2*pi)
1090
+ 0
1091
+ >>> periodic_argument(exp_polar(5*I*pi), 4*pi)
1092
+ pi
1093
+ >>> from sympy import exp_polar, periodic_argument
1094
+ >>> from sympy import I, pi
1095
+ >>> periodic_argument(exp_polar(5*I*pi), 2*pi)
1096
+ pi
1097
+ >>> periodic_argument(exp_polar(5*I*pi), 3*pi)
1098
+ -pi
1099
+ >>> periodic_argument(exp_polar(5*I*pi), pi)
1100
+ 0
1101
+
1102
+ Parameters
1103
+ ==========
1104
+
1105
+ ar : Expr
1106
+ A polar number.
1107
+
1108
+ period : Expr
1109
+ The period $P$.
1110
+
1111
+ See Also
1112
+ ========
1113
+
1114
+ sympy.functions.elementary.exponential.exp_polar
1115
+ polar_lift : Lift argument to the Riemann surface of the logarithm
1116
+ principal_branch
1117
+ """
1118
+
1119
+ @classmethod
1120
+ def _getunbranched(cls, ar):
1121
+ from sympy.functions.elementary.exponential import exp_polar, log
1122
+ if ar.is_Mul:
1123
+ args = ar.args
1124
+ else:
1125
+ args = [ar]
1126
+ unbranched = 0
1127
+ for a in args:
1128
+ if not a.is_polar:
1129
+ unbranched += arg(a)
1130
+ elif isinstance(a, exp_polar):
1131
+ unbranched += a.exp.as_real_imag()[1]
1132
+ elif a.is_Pow:
1133
+ re, im = a.exp.as_real_imag()
1134
+ unbranched += re*unbranched_argument(
1135
+ a.base) + im*log(abs(a.base))
1136
+ elif isinstance(a, polar_lift):
1137
+ unbranched += arg(a.args[0])
1138
+ else:
1139
+ return None
1140
+ return unbranched
1141
+
1142
+ @classmethod
1143
+ def eval(cls, ar, period):
1144
+ # Our strategy is to evaluate the argument on the Riemann surface of the
1145
+ # logarithm, and then reduce.
1146
+ # NOTE evidently this means it is a rather bad idea to use this with
1147
+ # period != 2*pi and non-polar numbers.
1148
+ if not period.is_extended_positive:
1149
+ return None
1150
+ if period == oo and isinstance(ar, principal_branch):
1151
+ return periodic_argument(*ar.args)
1152
+ if isinstance(ar, polar_lift) and period >= 2*pi:
1153
+ return periodic_argument(ar.args[0], period)
1154
+ if ar.is_Mul:
1155
+ newargs = [x for x in ar.args if not x.is_positive]
1156
+ if len(newargs) != len(ar.args):
1157
+ return periodic_argument(Mul(*newargs), period)
1158
+ unbranched = cls._getunbranched(ar)
1159
+ if unbranched is None:
1160
+ return None
1161
+ from sympy.functions.elementary.trigonometric import atan, atan2
1162
+ if unbranched.has(periodic_argument, atan2, atan):
1163
+ return None
1164
+ if period == oo:
1165
+ return unbranched
1166
+ if period != oo:
1167
+ from sympy.functions.elementary.integers import ceiling
1168
+ n = ceiling(unbranched/period - S.Half)*period
1169
+ if not n.has(ceiling):
1170
+ return unbranched - n
1171
+
1172
+ def _eval_evalf(self, prec):
1173
+ z, period = self.args
1174
+ if period == oo:
1175
+ unbranched = periodic_argument._getunbranched(z)
1176
+ if unbranched is None:
1177
+ return self
1178
+ return unbranched._eval_evalf(prec)
1179
+ ub = periodic_argument(z, oo)._eval_evalf(prec)
1180
+ from sympy.functions.elementary.integers import ceiling
1181
+ return (ub - ceiling(ub/period - S.Half)*period)._eval_evalf(prec)
1182
+
1183
+
1184
+ def unbranched_argument(arg):
1185
+ '''
1186
+ Returns periodic argument of arg with period as infinity.
1187
+
1188
+ Examples
1189
+ ========
1190
+
1191
+ >>> from sympy import exp_polar, unbranched_argument
1192
+ >>> from sympy import I, pi
1193
+ >>> unbranched_argument(exp_polar(15*I*pi))
1194
+ 15*pi
1195
+ >>> unbranched_argument(exp_polar(7*I*pi))
1196
+ 7*pi
1197
+
1198
+ See also
1199
+ ========
1200
+
1201
+ periodic_argument
1202
+ '''
1203
+ return periodic_argument(arg, oo)
1204
+
1205
+
1206
+ class principal_branch(Function):
1207
+ """
1208
+ Represent a polar number reduced to its principal branch on a quotient
1209
+ of the Riemann surface of the logarithm.
1210
+
1211
+ Explanation
1212
+ ===========
1213
+
1214
+ This is a function of two arguments. The first argument is a polar
1215
+ number `z`, and the second one a positive real number or infinity, `p`.
1216
+ The result is ``z mod exp_polar(I*p)``.
1217
+
1218
+ Examples
1219
+ ========
1220
+
1221
+ >>> from sympy import exp_polar, principal_branch, oo, I, pi
1222
+ >>> from sympy.abc import z
1223
+ >>> principal_branch(z, oo)
1224
+ z
1225
+ >>> principal_branch(exp_polar(2*pi*I)*3, 2*pi)
1226
+ 3*exp_polar(0)
1227
+ >>> principal_branch(exp_polar(2*pi*I)*3*z, 2*pi)
1228
+ 3*principal_branch(z, 2*pi)
1229
+
1230
+ Parameters
1231
+ ==========
1232
+
1233
+ x : Expr
1234
+ A polar number.
1235
+
1236
+ period : Expr
1237
+ Positive real number or infinity.
1238
+
1239
+ See Also
1240
+ ========
1241
+
1242
+ sympy.functions.elementary.exponential.exp_polar
1243
+ polar_lift : Lift argument to the Riemann surface of the logarithm
1244
+ periodic_argument
1245
+ """
1246
+
1247
+ is_polar = True
1248
+ is_comparable = False # cannot always be evalf'd
1249
+
1250
+ @classmethod
1251
+ def eval(self, x, period):
1252
+ from sympy.functions.elementary.exponential import exp_polar
1253
+ if isinstance(x, polar_lift):
1254
+ return principal_branch(x.args[0], period)
1255
+ if period == oo:
1256
+ return x
1257
+ ub = periodic_argument(x, oo)
1258
+ barg = periodic_argument(x, period)
1259
+ if ub != barg and not ub.has(periodic_argument) \
1260
+ and not barg.has(periodic_argument):
1261
+ pl = polar_lift(x)
1262
+
1263
+ def mr(expr):
1264
+ if not isinstance(expr, Symbol):
1265
+ return polar_lift(expr)
1266
+ return expr
1267
+ pl = pl.replace(polar_lift, mr)
1268
+ # Recompute unbranched argument
1269
+ ub = periodic_argument(pl, oo)
1270
+ if not pl.has(polar_lift):
1271
+ if ub != barg:
1272
+ res = exp_polar(I*(barg - ub))*pl
1273
+ else:
1274
+ res = pl
1275
+ if not res.is_polar and not res.has(exp_polar):
1276
+ res *= exp_polar(0)
1277
+ return res
1278
+
1279
+ if not x.free_symbols:
1280
+ c, m = x, ()
1281
+ else:
1282
+ c, m = x.as_coeff_mul(*x.free_symbols)
1283
+ others = []
1284
+ for y in m:
1285
+ if y.is_positive:
1286
+ c *= y
1287
+ else:
1288
+ others += [y]
1289
+ m = tuple(others)
1290
+ arg = periodic_argument(c, period)
1291
+ if arg.has(periodic_argument):
1292
+ return None
1293
+ if arg.is_number and (unbranched_argument(c) != arg or
1294
+ (arg == 0 and m != () and c != 1)):
1295
+ if arg == 0:
1296
+ return abs(c)*principal_branch(Mul(*m), period)
1297
+ return principal_branch(exp_polar(I*arg)*Mul(*m), period)*abs(c)
1298
+ if arg.is_number and ((abs(arg) < period/2) == True or arg == period/2) \
1299
+ and m == ():
1300
+ return exp_polar(arg*I)*abs(c)
1301
+
1302
+ def _eval_evalf(self, prec):
1303
+ z, period = self.args
1304
+ p = periodic_argument(z, period)._eval_evalf(prec)
1305
+ if abs(p) > pi or p == -pi:
1306
+ return self # Cannot evalf for this argument.
1307
+ from sympy.functions.elementary.exponential import exp
1308
+ return (abs(z)*exp(I*p))._eval_evalf(prec)
1309
+
1310
+
1311
+ def _polarify(eq, lift, pause=False):
1312
+ from sympy.integrals.integrals import Integral
1313
+ if eq.is_polar:
1314
+ return eq
1315
+ if eq.is_number and not pause:
1316
+ return polar_lift(eq)
1317
+ if isinstance(eq, Symbol) and not pause and lift:
1318
+ return polar_lift(eq)
1319
+ elif eq.is_Atom:
1320
+ return eq
1321
+ elif eq.is_Add:
1322
+ r = eq.func(*[_polarify(arg, lift, pause=True) for arg in eq.args])
1323
+ if lift:
1324
+ return polar_lift(r)
1325
+ return r
1326
+ elif eq.is_Pow and eq.base == S.Exp1:
1327
+ return eq.func(S.Exp1, _polarify(eq.exp, lift, pause=False))
1328
+ elif eq.is_Function:
1329
+ return eq.func(*[_polarify(arg, lift, pause=False) for arg in eq.args])
1330
+ elif isinstance(eq, Integral):
1331
+ # Don't lift the integration variable
1332
+ func = _polarify(eq.function, lift, pause=pause)
1333
+ limits = []
1334
+ for limit in eq.args[1:]:
1335
+ var = _polarify(limit[0], lift=False, pause=pause)
1336
+ rest = _polarify(limit[1:], lift=lift, pause=pause)
1337
+ limits.append((var,) + rest)
1338
+ return Integral(*((func,) + tuple(limits)))
1339
+ else:
1340
+ return eq.func(*[_polarify(arg, lift, pause=pause)
1341
+ if isinstance(arg, Expr) else arg for arg in eq.args])
1342
+
1343
+
1344
+ def polarify(eq, subs=True, lift=False):
1345
+ """
1346
+ Turn all numbers in eq into their polar equivalents (under the standard
1347
+ choice of argument).
1348
+
1349
+ Note that no attempt is made to guess a formal convention of adding
1350
+ polar numbers, expressions like $1 + x$ will generally not be altered.
1351
+
1352
+ Note also that this function does not promote ``exp(x)`` to ``exp_polar(x)``.
1353
+
1354
+ If ``subs`` is ``True``, all symbols which are not already polar will be
1355
+ substituted for polar dummies; in this case the function behaves much
1356
+ like :func:`~.posify`.
1357
+
1358
+ If ``lift`` is ``True``, both addition statements and non-polar symbols are
1359
+ changed to their ``polar_lift()``ed versions.
1360
+ Note that ``lift=True`` implies ``subs=False``.
1361
+
1362
+ Examples
1363
+ ========
1364
+
1365
+ >>> from sympy import polarify, sin, I
1366
+ >>> from sympy.abc import x, y
1367
+ >>> expr = (-x)**y
1368
+ >>> expr.expand()
1369
+ (-x)**y
1370
+ >>> polarify(expr)
1371
+ ((_x*exp_polar(I*pi))**_y, {_x: x, _y: y})
1372
+ >>> polarify(expr)[0].expand()
1373
+ _x**_y*exp_polar(_y*I*pi)
1374
+ >>> polarify(x, lift=True)
1375
+ polar_lift(x)
1376
+ >>> polarify(x*(1+y), lift=True)
1377
+ polar_lift(x)*polar_lift(y + 1)
1378
+
1379
+ Adds are treated carefully:
1380
+
1381
+ >>> polarify(1 + sin((1 + I)*x))
1382
+ (sin(_x*polar_lift(1 + I)) + 1, {_x: x})
1383
+ """
1384
+ if lift:
1385
+ subs = False
1386
+ eq = _polarify(sympify(eq), lift)
1387
+ if not subs:
1388
+ return eq
1389
+ reps = {s: Dummy(s.name, polar=True) for s in eq.free_symbols}
1390
+ eq = eq.subs(reps)
1391
+ return eq, {r: s for s, r in reps.items()}
1392
+
1393
+
1394
+ def _unpolarify(eq, exponents_only, pause=False):
1395
+ if not isinstance(eq, Basic) or eq.is_Atom:
1396
+ return eq
1397
+
1398
+ if not pause:
1399
+ from sympy.functions.elementary.exponential import exp, exp_polar
1400
+ if isinstance(eq, exp_polar):
1401
+ return exp(_unpolarify(eq.exp, exponents_only))
1402
+ if isinstance(eq, principal_branch) and eq.args[1] == 2*pi:
1403
+ return _unpolarify(eq.args[0], exponents_only)
1404
+ if (
1405
+ eq.is_Add or eq.is_Mul or eq.is_Boolean or
1406
+ eq.is_Relational and (
1407
+ eq.rel_op in ('==', '!=') and 0 in eq.args or
1408
+ eq.rel_op not in ('==', '!='))
1409
+ ):
1410
+ return eq.func(*[_unpolarify(x, exponents_only) for x in eq.args])
1411
+ if isinstance(eq, polar_lift):
1412
+ return _unpolarify(eq.args[0], exponents_only)
1413
+
1414
+ if eq.is_Pow:
1415
+ expo = _unpolarify(eq.exp, exponents_only)
1416
+ base = _unpolarify(eq.base, exponents_only,
1417
+ not (expo.is_integer and not pause))
1418
+ return base**expo
1419
+
1420
+ if eq.is_Function and getattr(eq.func, 'unbranched', False):
1421
+ return eq.func(*[_unpolarify(x, exponents_only, exponents_only)
1422
+ for x in eq.args])
1423
+
1424
+ return eq.func(*[_unpolarify(x, exponents_only, True) for x in eq.args])
1425
+
1426
+
1427
+ def unpolarify(eq, subs=None, exponents_only=False):
1428
+ """
1429
+ If `p` denotes the projection from the Riemann surface of the logarithm to
1430
+ the complex line, return a simplified version `eq'` of `eq` such that
1431
+ `p(eq') = p(eq)`.
1432
+ Also apply the substitution subs in the end. (This is a convenience, since
1433
+ ``unpolarify``, in a certain sense, undoes :func:`polarify`.)
1434
+
1435
+ Examples
1436
+ ========
1437
+
1438
+ >>> from sympy import unpolarify, polar_lift, sin, I
1439
+ >>> unpolarify(polar_lift(I + 2))
1440
+ 2 + I
1441
+ >>> unpolarify(sin(polar_lift(I + 7)))
1442
+ sin(7 + I)
1443
+ """
1444
+ if isinstance(eq, bool):
1445
+ return eq
1446
+
1447
+ eq = sympify(eq)
1448
+ if subs is not None:
1449
+ return unpolarify(eq.subs(subs))
1450
+ changed = True
1451
+ pause = False
1452
+ if exponents_only:
1453
+ pause = True
1454
+ while changed:
1455
+ changed = False
1456
+ res = _unpolarify(eq, exponents_only, pause)
1457
+ if res != eq:
1458
+ changed = True
1459
+ eq = res
1460
+ if isinstance(res, bool):
1461
+ return res
1462
+ # Finally, replacing Exp(0) by 1 is always correct.
1463
+ # So is polar_lift(0) -> 0.
1464
+ from sympy.functions.elementary.exponential import exp_polar
1465
+ return res.subs({exp_polar(0): 1, polar_lift(0): 0})
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/exponential.py ADDED
@@ -0,0 +1,1291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import product
2
+ from typing import Tuple as tTuple
3
+
4
+ from sympy.core.add import Add
5
+ from sympy.core.cache import cacheit
6
+ from sympy.core.expr import Expr
7
+ from sympy.core.function import (Function, ArgumentIndexError, expand_log,
8
+ expand_mul, FunctionClass, PoleError, expand_multinomial, expand_complex)
9
+ from sympy.core.logic import fuzzy_and, fuzzy_not, fuzzy_or
10
+ from sympy.core.mul import Mul
11
+ from sympy.core.numbers import Integer, Rational, pi, I, ImaginaryUnit
12
+ from sympy.core.parameters import global_parameters
13
+ from sympy.core.power import Pow
14
+ from sympy.core.singleton import S
15
+ from sympy.core.symbol import Wild, Dummy
16
+ from sympy.core.sympify import sympify
17
+ from sympy.functions.combinatorial.factorials import factorial
18
+ from sympy.functions.elementary.complexes import arg, unpolarify, im, re, Abs
19
+ from sympy.functions.elementary.miscellaneous import sqrt
20
+ from sympy.ntheory import multiplicity, perfect_power
21
+ from sympy.ntheory.factor_ import factorint
22
+
23
+ # NOTE IMPORTANT
24
+ # The series expansion code in this file is an important part of the gruntz
25
+ # algorithm for determining limits. _eval_nseries has to return a generalized
26
+ # power series with coefficients in C(log(x), log).
27
+ # In more detail, the result of _eval_nseries(self, x, n) must be
28
+ # c_0*x**e_0 + ... (finitely many terms)
29
+ # where e_i are numbers (not necessarily integers) and c_i involve only
30
+ # numbers, the function log, and log(x). [This also means it must not contain
31
+ # log(x(1+p)), this *has* to be expanded to log(x)+log(1+p) if x.is_positive and
32
+ # p.is_positive.]
33
+
34
+
35
+ class ExpBase(Function):
36
+
37
+ unbranched = True
38
+ _singularities = (S.ComplexInfinity,)
39
+
40
+ @property
41
+ def kind(self):
42
+ return self.exp.kind
43
+
44
+ def inverse(self, argindex=1):
45
+ """
46
+ Returns the inverse function of ``exp(x)``.
47
+ """
48
+ return log
49
+
50
+ def as_numer_denom(self):
51
+ """
52
+ Returns this with a positive exponent as a 2-tuple (a fraction).
53
+
54
+ Examples
55
+ ========
56
+
57
+ >>> from sympy import exp
58
+ >>> from sympy.abc import x
59
+ >>> exp(-x).as_numer_denom()
60
+ (1, exp(x))
61
+ >>> exp(x).as_numer_denom()
62
+ (exp(x), 1)
63
+ """
64
+ # this should be the same as Pow.as_numer_denom wrt
65
+ # exponent handling
66
+ exp = self.exp
67
+ neg_exp = exp.is_negative
68
+ if not neg_exp and not (-exp).is_negative:
69
+ neg_exp = exp.could_extract_minus_sign()
70
+ if neg_exp:
71
+ return S.One, self.func(-exp)
72
+ return self, S.One
73
+
74
+ @property
75
+ def exp(self):
76
+ """
77
+ Returns the exponent of the function.
78
+ """
79
+ return self.args[0]
80
+
81
+ def as_base_exp(self):
82
+ """
83
+ Returns the 2-tuple (base, exponent).
84
+ """
85
+ return self.func(1), Mul(*self.args)
86
+
87
+ def _eval_adjoint(self):
88
+ return self.func(self.exp.adjoint())
89
+
90
+ def _eval_conjugate(self):
91
+ return self.func(self.exp.conjugate())
92
+
93
+ def _eval_transpose(self):
94
+ return self.func(self.exp.transpose())
95
+
96
+ def _eval_is_finite(self):
97
+ arg = self.exp
98
+ if arg.is_infinite:
99
+ if arg.is_extended_negative:
100
+ return True
101
+ if arg.is_extended_positive:
102
+ return False
103
+ if arg.is_finite:
104
+ return True
105
+
106
+ def _eval_is_rational(self):
107
+ s = self.func(*self.args)
108
+ if s.func == self.func:
109
+ z = s.exp.is_zero
110
+ if z:
111
+ return True
112
+ elif s.exp.is_rational and fuzzy_not(z):
113
+ return False
114
+ else:
115
+ return s.is_rational
116
+
117
+ def _eval_is_zero(self):
118
+ return self.exp is S.NegativeInfinity
119
+
120
+ def _eval_power(self, other):
121
+ """exp(arg)**e -> exp(arg*e) if assumptions allow it.
122
+ """
123
+ b, e = self.as_base_exp()
124
+ return Pow._eval_power(Pow(b, e, evaluate=False), other)
125
+
126
+ def _eval_expand_power_exp(self, **hints):
127
+ from sympy.concrete.products import Product
128
+ from sympy.concrete.summations import Sum
129
+ arg = self.args[0]
130
+ if arg.is_Add and arg.is_commutative:
131
+ return Mul.fromiter(self.func(x) for x in arg.args)
132
+ elif isinstance(arg, Sum) and arg.is_commutative:
133
+ return Product(self.func(arg.function), *arg.limits)
134
+ return self.func(arg)
135
+
136
+
137
+ class exp_polar(ExpBase):
138
+ r"""
139
+ Represent a *polar number* (see g-function Sphinx documentation).
140
+
141
+ Explanation
142
+ ===========
143
+
144
+ ``exp_polar`` represents the function
145
+ `Exp: \mathbb{C} \rightarrow \mathcal{S}`, sending the complex number
146
+ `z = a + bi` to the polar number `r = exp(a), \theta = b`. It is one of
147
+ the main functions to construct polar numbers.
148
+
149
+ Examples
150
+ ========
151
+
152
+ >>> from sympy import exp_polar, pi, I, exp
153
+
154
+ The main difference is that polar numbers do not "wrap around" at `2 \pi`:
155
+
156
+ >>> exp(2*pi*I)
157
+ 1
158
+ >>> exp_polar(2*pi*I)
159
+ exp_polar(2*I*pi)
160
+
161
+ apart from that they behave mostly like classical complex numbers:
162
+
163
+ >>> exp_polar(2)*exp_polar(3)
164
+ exp_polar(5)
165
+
166
+ See Also
167
+ ========
168
+
169
+ sympy.simplify.powsimp.powsimp
170
+ polar_lift
171
+ periodic_argument
172
+ principal_branch
173
+ """
174
+
175
+ is_polar = True
176
+ is_comparable = False # cannot be evalf'd
177
+
178
+ def _eval_Abs(self): # Abs is never a polar number
179
+ return exp(re(self.args[0]))
180
+
181
+ def _eval_evalf(self, prec):
182
+ """ Careful! any evalf of polar numbers is flaky """
183
+ i = im(self.args[0])
184
+ try:
185
+ bad = (i <= -pi or i > pi)
186
+ except TypeError:
187
+ bad = True
188
+ if bad:
189
+ return self # cannot evalf for this argument
190
+ res = exp(self.args[0])._eval_evalf(prec)
191
+ if i > 0 and im(res) < 0:
192
+ # i ~ pi, but exp(I*i) evaluated to argument slightly bigger than pi
193
+ return re(res)
194
+ return res
195
+
196
+ def _eval_power(self, other):
197
+ return self.func(self.args[0]*other)
198
+
199
+ def _eval_is_extended_real(self):
200
+ if self.args[0].is_extended_real:
201
+ return True
202
+
203
+ def as_base_exp(self):
204
+ # XXX exp_polar(0) is special!
205
+ if self.args[0] == 0:
206
+ return self, S.One
207
+ return ExpBase.as_base_exp(self)
208
+
209
+
210
+ class ExpMeta(FunctionClass):
211
+ def __instancecheck__(cls, instance):
212
+ if exp in instance.__class__.__mro__:
213
+ return True
214
+ return isinstance(instance, Pow) and instance.base is S.Exp1
215
+
216
+
217
+ class exp(ExpBase, metaclass=ExpMeta):
218
+ """
219
+ The exponential function, :math:`e^x`.
220
+
221
+ Examples
222
+ ========
223
+
224
+ >>> from sympy import exp, I, pi
225
+ >>> from sympy.abc import x
226
+ >>> exp(x)
227
+ exp(x)
228
+ >>> exp(x).diff(x)
229
+ exp(x)
230
+ >>> exp(I*pi)
231
+ -1
232
+
233
+ Parameters
234
+ ==========
235
+
236
+ arg : Expr
237
+
238
+ See Also
239
+ ========
240
+
241
+ log
242
+ """
243
+
244
+ def fdiff(self, argindex=1):
245
+ """
246
+ Returns the first derivative of this function.
247
+ """
248
+ if argindex == 1:
249
+ return self
250
+ else:
251
+ raise ArgumentIndexError(self, argindex)
252
+
253
+ def _eval_refine(self, assumptions):
254
+ from sympy.assumptions import ask, Q
255
+ arg = self.args[0]
256
+ if arg.is_Mul:
257
+ Ioo = I*S.Infinity
258
+ if arg in [Ioo, -Ioo]:
259
+ return S.NaN
260
+
261
+ coeff = arg.as_coefficient(pi*I)
262
+ if coeff:
263
+ if ask(Q.integer(2*coeff)):
264
+ if ask(Q.even(coeff)):
265
+ return S.One
266
+ elif ask(Q.odd(coeff)):
267
+ return S.NegativeOne
268
+ elif ask(Q.even(coeff + S.Half)):
269
+ return -I
270
+ elif ask(Q.odd(coeff + S.Half)):
271
+ return I
272
+
273
+ @classmethod
274
+ def eval(cls, arg):
275
+ from sympy.calculus import AccumBounds
276
+ from sympy.matrices.matrices import MatrixBase
277
+ from sympy.sets.setexpr import SetExpr
278
+ from sympy.simplify.simplify import logcombine
279
+ if isinstance(arg, MatrixBase):
280
+ return arg.exp()
281
+ elif global_parameters.exp_is_pow:
282
+ return Pow(S.Exp1, arg)
283
+ elif arg.is_Number:
284
+ if arg is S.NaN:
285
+ return S.NaN
286
+ elif arg.is_zero:
287
+ return S.One
288
+ elif arg is S.One:
289
+ return S.Exp1
290
+ elif arg is S.Infinity:
291
+ return S.Infinity
292
+ elif arg is S.NegativeInfinity:
293
+ return S.Zero
294
+ elif arg is S.ComplexInfinity:
295
+ return S.NaN
296
+ elif isinstance(arg, log):
297
+ return arg.args[0]
298
+ elif isinstance(arg, AccumBounds):
299
+ return AccumBounds(exp(arg.min), exp(arg.max))
300
+ elif isinstance(arg, SetExpr):
301
+ return arg._eval_func(cls)
302
+ elif arg.is_Mul:
303
+ coeff = arg.as_coefficient(pi*I)
304
+ if coeff:
305
+ if (2*coeff).is_integer:
306
+ if coeff.is_even:
307
+ return S.One
308
+ elif coeff.is_odd:
309
+ return S.NegativeOne
310
+ elif (coeff + S.Half).is_even:
311
+ return -I
312
+ elif (coeff + S.Half).is_odd:
313
+ return I
314
+ elif coeff.is_Rational:
315
+ ncoeff = coeff % 2 # restrict to [0, 2pi)
316
+ if ncoeff > 1: # restrict to (-pi, pi]
317
+ ncoeff -= 2
318
+ if ncoeff != coeff:
319
+ return cls(ncoeff*pi*I)
320
+
321
+ # Warning: code in risch.py will be very sensitive to changes
322
+ # in this (see DifferentialExtension).
323
+
324
+ # look for a single log factor
325
+
326
+ coeff, terms = arg.as_coeff_Mul()
327
+
328
+ # but it can't be multiplied by oo
329
+ if coeff in [S.NegativeInfinity, S.Infinity]:
330
+ if terms.is_number:
331
+ if coeff is S.NegativeInfinity:
332
+ terms = -terms
333
+ if re(terms).is_zero and terms is not S.Zero:
334
+ return S.NaN
335
+ if re(terms).is_positive and im(terms) is not S.Zero:
336
+ return S.ComplexInfinity
337
+ if re(terms).is_negative:
338
+ return S.Zero
339
+ return None
340
+
341
+ coeffs, log_term = [coeff], None
342
+ for term in Mul.make_args(terms):
343
+ term_ = logcombine(term)
344
+ if isinstance(term_, log):
345
+ if log_term is None:
346
+ log_term = term_.args[0]
347
+ else:
348
+ return None
349
+ elif term.is_comparable:
350
+ coeffs.append(term)
351
+ else:
352
+ return None
353
+
354
+ return log_term**Mul(*coeffs) if log_term else None
355
+
356
+ elif arg.is_Add:
357
+ out = []
358
+ add = []
359
+ argchanged = False
360
+ for a in arg.args:
361
+ if a is S.One:
362
+ add.append(a)
363
+ continue
364
+ newa = cls(a)
365
+ if isinstance(newa, cls):
366
+ if newa.args[0] != a:
367
+ add.append(newa.args[0])
368
+ argchanged = True
369
+ else:
370
+ add.append(a)
371
+ else:
372
+ out.append(newa)
373
+ if out or argchanged:
374
+ return Mul(*out)*cls(Add(*add), evaluate=False)
375
+
376
+ if arg.is_zero:
377
+ return S.One
378
+
379
+ @property
380
+ def base(self):
381
+ """
382
+ Returns the base of the exponential function.
383
+ """
384
+ return S.Exp1
385
+
386
+ @staticmethod
387
+ @cacheit
388
+ def taylor_term(n, x, *previous_terms):
389
+ """
390
+ Calculates the next term in the Taylor series expansion.
391
+ """
392
+ if n < 0:
393
+ return S.Zero
394
+ if n == 0:
395
+ return S.One
396
+ x = sympify(x)
397
+ if previous_terms:
398
+ p = previous_terms[-1]
399
+ if p is not None:
400
+ return p * x / n
401
+ return x**n/factorial(n)
402
+
403
+ def as_real_imag(self, deep=True, **hints):
404
+ """
405
+ Returns this function as a 2-tuple representing a complex number.
406
+
407
+ Examples
408
+ ========
409
+
410
+ >>> from sympy import exp, I
411
+ >>> from sympy.abc import x
412
+ >>> exp(x).as_real_imag()
413
+ (exp(re(x))*cos(im(x)), exp(re(x))*sin(im(x)))
414
+ >>> exp(1).as_real_imag()
415
+ (E, 0)
416
+ >>> exp(I).as_real_imag()
417
+ (cos(1), sin(1))
418
+ >>> exp(1+I).as_real_imag()
419
+ (E*cos(1), E*sin(1))
420
+
421
+ See Also
422
+ ========
423
+
424
+ sympy.functions.elementary.complexes.re
425
+ sympy.functions.elementary.complexes.im
426
+ """
427
+ from sympy.functions.elementary.trigonometric import cos, sin
428
+ re, im = self.args[0].as_real_imag()
429
+ if deep:
430
+ re = re.expand(deep, **hints)
431
+ im = im.expand(deep, **hints)
432
+ cos, sin = cos(im), sin(im)
433
+ return (exp(re)*cos, exp(re)*sin)
434
+
435
+ def _eval_subs(self, old, new):
436
+ # keep processing of power-like args centralized in Pow
437
+ if old.is_Pow: # handle (exp(3*log(x))).subs(x**2, z) -> z**(3/2)
438
+ old = exp(old.exp*log(old.base))
439
+ elif old is S.Exp1 and new.is_Function:
440
+ old = exp
441
+ if isinstance(old, exp) or old is S.Exp1:
442
+ f = lambda a: Pow(*a.as_base_exp(), evaluate=False) if (
443
+ a.is_Pow or isinstance(a, exp)) else a
444
+ return Pow._eval_subs(f(self), f(old), new)
445
+
446
+ if old is exp and not new.is_Function:
447
+ return new**self.exp._subs(old, new)
448
+ return Function._eval_subs(self, old, new)
449
+
450
+ def _eval_is_extended_real(self):
451
+ if self.args[0].is_extended_real:
452
+ return True
453
+ elif self.args[0].is_imaginary:
454
+ arg2 = -S(2) * I * self.args[0] / pi
455
+ return arg2.is_even
456
+
457
+ def _eval_is_complex(self):
458
+ def complex_extended_negative(arg):
459
+ yield arg.is_complex
460
+ yield arg.is_extended_negative
461
+ return fuzzy_or(complex_extended_negative(self.args[0]))
462
+
463
+ def _eval_is_algebraic(self):
464
+ if (self.exp / pi / I).is_rational:
465
+ return True
466
+ if fuzzy_not(self.exp.is_zero):
467
+ if self.exp.is_algebraic:
468
+ return False
469
+ elif (self.exp / pi).is_rational:
470
+ return False
471
+
472
+ def _eval_is_extended_positive(self):
473
+ if self.exp.is_extended_real:
474
+ return self.args[0] is not S.NegativeInfinity
475
+ elif self.exp.is_imaginary:
476
+ arg2 = -I * self.args[0] / pi
477
+ return arg2.is_even
478
+
479
+ def _eval_nseries(self, x, n, logx, cdir=0):
480
+ # NOTE Please see the comment at the beginning of this file, labelled
481
+ # IMPORTANT.
482
+ from sympy.functions.elementary.complexes import sign
483
+ from sympy.functions.elementary.integers import ceiling
484
+ from sympy.series.limits import limit
485
+ from sympy.series.order import Order
486
+ from sympy.simplify.powsimp import powsimp
487
+ arg = self.exp
488
+ arg_series = arg._eval_nseries(x, n=n, logx=logx)
489
+ if arg_series.is_Order:
490
+ return 1 + arg_series
491
+ arg0 = limit(arg_series.removeO(), x, 0)
492
+ if arg0 is S.NegativeInfinity:
493
+ return Order(x**n, x)
494
+ if arg0 is S.Infinity:
495
+ return self
496
+ # checking for indecisiveness/ sign terms in arg0
497
+ if any(isinstance(arg, (sign, ImaginaryUnit)) for arg in arg0.args):
498
+ return self
499
+ t = Dummy("t")
500
+ nterms = n
501
+ try:
502
+ cf = Order(arg.as_leading_term(x, logx=logx), x).getn()
503
+ except (NotImplementedError, PoleError):
504
+ cf = 0
505
+ if cf and cf > 0:
506
+ nterms = ceiling(n/cf)
507
+ exp_series = exp(t)._taylor(t, nterms)
508
+ r = exp(arg0)*exp_series.subs(t, arg_series - arg0)
509
+ rep = {logx: log(x)} if logx is not None else {}
510
+ if r.subs(rep) == self:
511
+ return r
512
+ if cf and cf > 1:
513
+ r += Order((arg_series - arg0)**n, x)/x**((cf-1)*n)
514
+ else:
515
+ r += Order((arg_series - arg0)**n, x)
516
+ r = r.expand()
517
+ r = powsimp(r, deep=True, combine='exp')
518
+ # powsimp may introduce unexpanded (-1)**Rational; see PR #17201
519
+ simplerat = lambda x: x.is_Rational and x.q in [3, 4, 6]
520
+ w = Wild('w', properties=[simplerat])
521
+ r = r.replace(S.NegativeOne**w, expand_complex(S.NegativeOne**w))
522
+ return r
523
+
524
+ def _taylor(self, x, n):
525
+ l = []
526
+ g = None
527
+ for i in range(n):
528
+ g = self.taylor_term(i, self.args[0], g)
529
+ g = g.nseries(x, n=n)
530
+ l.append(g.removeO())
531
+ return Add(*l)
532
+
533
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
534
+ from sympy.calculus.util import AccumBounds
535
+ arg = self.args[0].cancel().as_leading_term(x, logx=logx)
536
+ arg0 = arg.subs(x, 0)
537
+ if arg is S.NaN:
538
+ return S.NaN
539
+ if isinstance(arg0, AccumBounds):
540
+ # This check addresses a corner case involving AccumBounds.
541
+ # if isinstance(arg, AccumBounds) is True, then arg0 can either be 0,
542
+ # AccumBounds(-oo, 0) or AccumBounds(-oo, oo).
543
+ # Check out function: test_issue_18473() in test_exponential.py and
544
+ # test_limits.py for more information.
545
+ if re(cdir) < S.Zero:
546
+ return exp(-arg0)
547
+ return exp(arg0)
548
+ if arg0 is S.NaN:
549
+ arg0 = arg.limit(x, 0)
550
+ if arg0.is_infinite is False:
551
+ return exp(arg0)
552
+ raise PoleError("Cannot expand %s around 0" % (self))
553
+
554
+ def _eval_rewrite_as_sin(self, arg, **kwargs):
555
+ from sympy.functions.elementary.trigonometric import sin
556
+ return sin(I*arg + pi/2) - I*sin(I*arg)
557
+
558
+ def _eval_rewrite_as_cos(self, arg, **kwargs):
559
+ from sympy.functions.elementary.trigonometric import cos
560
+ return cos(I*arg) + I*cos(I*arg + pi/2)
561
+
562
+ def _eval_rewrite_as_tanh(self, arg, **kwargs):
563
+ from sympy.functions.elementary.hyperbolic import tanh
564
+ return (1 + tanh(arg/2))/(1 - tanh(arg/2))
565
+
566
+ def _eval_rewrite_as_sqrt(self, arg, **kwargs):
567
+ from sympy.functions.elementary.trigonometric import sin, cos
568
+ if arg.is_Mul:
569
+ coeff = arg.coeff(pi*I)
570
+ if coeff and coeff.is_number:
571
+ cosine, sine = cos(pi*coeff), sin(pi*coeff)
572
+ if not isinstance(cosine, cos) and not isinstance (sine, sin):
573
+ return cosine + I*sine
574
+
575
+ def _eval_rewrite_as_Pow(self, arg, **kwargs):
576
+ if arg.is_Mul:
577
+ logs = [a for a in arg.args if isinstance(a, log) and len(a.args) == 1]
578
+ if logs:
579
+ return Pow(logs[0].args[0], arg.coeff(logs[0]))
580
+
581
+
582
+ def match_real_imag(expr):
583
+ r"""
584
+ Try to match expr with $a + Ib$ for real $a$ and $b$.
585
+
586
+ ``match_real_imag`` returns a tuple containing the real and imaginary
587
+ parts of expr or ``(None, None)`` if direct matching is not possible. Contrary
588
+ to :func:`~.re()`, :func:`~.im()``, and ``as_real_imag()``, this helper will not force things
589
+ by returning expressions themselves containing ``re()`` or ``im()`` and it
590
+ does not expand its argument either.
591
+
592
+ """
593
+ r_, i_ = expr.as_independent(I, as_Add=True)
594
+ if i_ == 0 and r_.is_real:
595
+ return (r_, i_)
596
+ i_ = i_.as_coefficient(I)
597
+ if i_ and i_.is_real and r_.is_real:
598
+ return (r_, i_)
599
+ else:
600
+ return (None, None) # simpler to check for than None
601
+
602
+
603
+ class log(Function):
604
+ r"""
605
+ The natural logarithm function `\ln(x)` or `\log(x)`.
606
+
607
+ Explanation
608
+ ===========
609
+
610
+ Logarithms are taken with the natural base, `e`. To get
611
+ a logarithm of a different base ``b``, use ``log(x, b)``,
612
+ which is essentially short-hand for ``log(x)/log(b)``.
613
+
614
+ ``log`` represents the principal branch of the natural
615
+ logarithm. As such it has a branch cut along the negative
616
+ real axis and returns values having a complex argument in
617
+ `(-\pi, \pi]`.
618
+
619
+ Examples
620
+ ========
621
+
622
+ >>> from sympy import log, sqrt, S, I
623
+ >>> log(8, 2)
624
+ 3
625
+ >>> log(S(8)/3, 2)
626
+ -log(3)/log(2) + 3
627
+ >>> log(-1 + I*sqrt(3))
628
+ log(2) + 2*I*pi/3
629
+
630
+ See Also
631
+ ========
632
+
633
+ exp
634
+
635
+ """
636
+
637
+ args: tTuple[Expr]
638
+
639
+ _singularities = (S.Zero, S.ComplexInfinity)
640
+
641
+ def fdiff(self, argindex=1):
642
+ """
643
+ Returns the first derivative of the function.
644
+ """
645
+ if argindex == 1:
646
+ return 1/self.args[0]
647
+ else:
648
+ raise ArgumentIndexError(self, argindex)
649
+
650
+ def inverse(self, argindex=1):
651
+ r"""
652
+ Returns `e^x`, the inverse function of `\log(x)`.
653
+ """
654
+ return exp
655
+
656
+ @classmethod
657
+ def eval(cls, arg, base=None):
658
+ from sympy.calculus import AccumBounds
659
+ from sympy.sets.setexpr import SetExpr
660
+
661
+ arg = sympify(arg)
662
+
663
+ if base is not None:
664
+ base = sympify(base)
665
+ if base == 1:
666
+ if arg == 1:
667
+ return S.NaN
668
+ else:
669
+ return S.ComplexInfinity
670
+ try:
671
+ # handle extraction of powers of the base now
672
+ # or else expand_log in Mul would have to handle this
673
+ n = multiplicity(base, arg)
674
+ if n:
675
+ return n + log(arg / base**n) / log(base)
676
+ else:
677
+ return log(arg)/log(base)
678
+ except ValueError:
679
+ pass
680
+ if base is not S.Exp1:
681
+ return cls(arg)/cls(base)
682
+ else:
683
+ return cls(arg)
684
+
685
+ if arg.is_Number:
686
+ if arg.is_zero:
687
+ return S.ComplexInfinity
688
+ elif arg is S.One:
689
+ return S.Zero
690
+ elif arg is S.Infinity:
691
+ return S.Infinity
692
+ elif arg is S.NegativeInfinity:
693
+ return S.Infinity
694
+ elif arg is S.NaN:
695
+ return S.NaN
696
+ elif arg.is_Rational and arg.p == 1:
697
+ return -cls(arg.q)
698
+
699
+ if arg.is_Pow and arg.base is S.Exp1 and arg.exp.is_extended_real:
700
+ return arg.exp
701
+ if isinstance(arg, exp) and arg.exp.is_extended_real:
702
+ return arg.exp
703
+ elif isinstance(arg, exp) and arg.exp.is_number:
704
+ r_, i_ = match_real_imag(arg.exp)
705
+ if i_ and i_.is_comparable:
706
+ i_ %= 2*pi
707
+ if i_ > pi:
708
+ i_ -= 2*pi
709
+ return r_ + expand_mul(i_ * I, deep=False)
710
+ elif isinstance(arg, exp_polar):
711
+ return unpolarify(arg.exp)
712
+ elif isinstance(arg, AccumBounds):
713
+ if arg.min.is_positive:
714
+ return AccumBounds(log(arg.min), log(arg.max))
715
+ elif arg.min.is_zero:
716
+ return AccumBounds(S.NegativeInfinity, log(arg.max))
717
+ else:
718
+ return S.NaN
719
+ elif isinstance(arg, SetExpr):
720
+ return arg._eval_func(cls)
721
+
722
+ if arg.is_number:
723
+ if arg.is_negative:
724
+ return pi * I + cls(-arg)
725
+ elif arg is S.ComplexInfinity:
726
+ return S.ComplexInfinity
727
+ elif arg is S.Exp1:
728
+ return S.One
729
+
730
+ if arg.is_zero:
731
+ return S.ComplexInfinity
732
+
733
+ # don't autoexpand Pow or Mul (see the issue 3351):
734
+ if not arg.is_Add:
735
+ coeff = arg.as_coefficient(I)
736
+
737
+ if coeff is not None:
738
+ if coeff is S.Infinity:
739
+ return S.Infinity
740
+ elif coeff is S.NegativeInfinity:
741
+ return S.Infinity
742
+ elif coeff.is_Rational:
743
+ if coeff.is_nonnegative:
744
+ return pi * I * S.Half + cls(coeff)
745
+ else:
746
+ return -pi * I * S.Half + cls(-coeff)
747
+
748
+ if arg.is_number and arg.is_algebraic:
749
+ # Match arg = coeff*(r_ + i_*I) with coeff>0, r_ and i_ real.
750
+ coeff, arg_ = arg.as_independent(I, as_Add=False)
751
+ if coeff.is_negative:
752
+ coeff *= -1
753
+ arg_ *= -1
754
+ arg_ = expand_mul(arg_, deep=False)
755
+ r_, i_ = arg_.as_independent(I, as_Add=True)
756
+ i_ = i_.as_coefficient(I)
757
+ if coeff.is_real and i_ and i_.is_real and r_.is_real:
758
+ if r_.is_zero:
759
+ if i_.is_positive:
760
+ return pi * I * S.Half + cls(coeff * i_)
761
+ elif i_.is_negative:
762
+ return -pi * I * S.Half + cls(coeff * -i_)
763
+ else:
764
+ from sympy.simplify import ratsimp
765
+ # Check for arguments involving rational multiples of pi
766
+ t = (i_/r_).cancel()
767
+ t1 = (-t).cancel()
768
+ atan_table = _log_atan_table()
769
+ if t in atan_table:
770
+ modulus = ratsimp(coeff * Abs(arg_))
771
+ if r_.is_positive:
772
+ return cls(modulus) + I * atan_table[t]
773
+ else:
774
+ return cls(modulus) + I * (atan_table[t] - pi)
775
+ elif t1 in atan_table:
776
+ modulus = ratsimp(coeff * Abs(arg_))
777
+ if r_.is_positive:
778
+ return cls(modulus) + I * (-atan_table[t1])
779
+ else:
780
+ return cls(modulus) + I * (pi - atan_table[t1])
781
+
782
+ def as_base_exp(self):
783
+ """
784
+ Returns this function in the form (base, exponent).
785
+ """
786
+ return self, S.One
787
+
788
+ @staticmethod
789
+ @cacheit
790
+ def taylor_term(n, x, *previous_terms): # of log(1+x)
791
+ r"""
792
+ Returns the next term in the Taylor series expansion of `\log(1+x)`.
793
+ """
794
+ from sympy.simplify.powsimp import powsimp
795
+ if n < 0:
796
+ return S.Zero
797
+ x = sympify(x)
798
+ if n == 0:
799
+ return x
800
+ if previous_terms:
801
+ p = previous_terms[-1]
802
+ if p is not None:
803
+ return powsimp((-n) * p * x / (n + 1), deep=True, combine='exp')
804
+ return (1 - 2*(n % 2)) * x**(n + 1)/(n + 1)
805
+
806
+ def _eval_expand_log(self, deep=True, **hints):
807
+ from sympy.concrete import Sum, Product
808
+ force = hints.get('force', False)
809
+ factor = hints.get('factor', False)
810
+ if (len(self.args) == 2):
811
+ return expand_log(self.func(*self.args), deep=deep, force=force)
812
+ arg = self.args[0]
813
+ if arg.is_Integer:
814
+ # remove perfect powers
815
+ p = perfect_power(arg)
816
+ logarg = None
817
+ coeff = 1
818
+ if p is not False:
819
+ arg, coeff = p
820
+ logarg = self.func(arg)
821
+ # expand as product of its prime factors if factor=True
822
+ if factor:
823
+ p = factorint(arg)
824
+ if arg not in p.keys():
825
+ logarg = sum(n*log(val) for val, n in p.items())
826
+ if logarg is not None:
827
+ return coeff*logarg
828
+ elif arg.is_Rational:
829
+ return log(arg.p) - log(arg.q)
830
+ elif arg.is_Mul:
831
+ expr = []
832
+ nonpos = []
833
+ for x in arg.args:
834
+ if force or x.is_positive or x.is_polar:
835
+ a = self.func(x)
836
+ if isinstance(a, log):
837
+ expr.append(self.func(x)._eval_expand_log(**hints))
838
+ else:
839
+ expr.append(a)
840
+ elif x.is_negative:
841
+ a = self.func(-x)
842
+ expr.append(a)
843
+ nonpos.append(S.NegativeOne)
844
+ else:
845
+ nonpos.append(x)
846
+ return Add(*expr) + log(Mul(*nonpos))
847
+ elif arg.is_Pow or isinstance(arg, exp):
848
+ if force or (arg.exp.is_extended_real and (arg.base.is_positive or ((arg.exp+1)
849
+ .is_positive and (arg.exp-1).is_nonpositive))) or arg.base.is_polar:
850
+ b = arg.base
851
+ e = arg.exp
852
+ a = self.func(b)
853
+ if isinstance(a, log):
854
+ return unpolarify(e) * a._eval_expand_log(**hints)
855
+ else:
856
+ return unpolarify(e) * a
857
+ elif isinstance(arg, Product):
858
+ if force or arg.function.is_positive:
859
+ return Sum(log(arg.function), *arg.limits)
860
+
861
+ return self.func(arg)
862
+
863
+ def _eval_simplify(self, **kwargs):
864
+ from sympy.simplify.simplify import expand_log, simplify, inversecombine
865
+ if len(self.args) == 2: # it's unevaluated
866
+ return simplify(self.func(*self.args), **kwargs)
867
+
868
+ expr = self.func(simplify(self.args[0], **kwargs))
869
+ if kwargs['inverse']:
870
+ expr = inversecombine(expr)
871
+ expr = expand_log(expr, deep=True)
872
+ return min([expr, self], key=kwargs['measure'])
873
+
874
+ def as_real_imag(self, deep=True, **hints):
875
+ """
876
+ Returns this function as a complex coordinate.
877
+
878
+ Examples
879
+ ========
880
+
881
+ >>> from sympy import I, log
882
+ >>> from sympy.abc import x
883
+ >>> log(x).as_real_imag()
884
+ (log(Abs(x)), arg(x))
885
+ >>> log(I).as_real_imag()
886
+ (0, pi/2)
887
+ >>> log(1 + I).as_real_imag()
888
+ (log(sqrt(2)), pi/4)
889
+ >>> log(I*x).as_real_imag()
890
+ (log(Abs(x)), arg(I*x))
891
+
892
+ """
893
+ sarg = self.args[0]
894
+ if deep:
895
+ sarg = self.args[0].expand(deep, **hints)
896
+ sarg_abs = Abs(sarg)
897
+ if sarg_abs == sarg:
898
+ return self, S.Zero
899
+ sarg_arg = arg(sarg)
900
+ if hints.get('log', False): # Expand the log
901
+ hints['complex'] = False
902
+ return (log(sarg_abs).expand(deep, **hints), sarg_arg)
903
+ else:
904
+ return log(sarg_abs), sarg_arg
905
+
906
+ def _eval_is_rational(self):
907
+ s = self.func(*self.args)
908
+ if s.func == self.func:
909
+ if (self.args[0] - 1).is_zero:
910
+ return True
911
+ if s.args[0].is_rational and fuzzy_not((self.args[0] - 1).is_zero):
912
+ return False
913
+ else:
914
+ return s.is_rational
915
+
916
+ def _eval_is_algebraic(self):
917
+ s = self.func(*self.args)
918
+ if s.func == self.func:
919
+ if (self.args[0] - 1).is_zero:
920
+ return True
921
+ elif fuzzy_not((self.args[0] - 1).is_zero):
922
+ if self.args[0].is_algebraic:
923
+ return False
924
+ else:
925
+ return s.is_algebraic
926
+
927
+ def _eval_is_extended_real(self):
928
+ return self.args[0].is_extended_positive
929
+
930
+ def _eval_is_complex(self):
931
+ z = self.args[0]
932
+ return fuzzy_and([z.is_complex, fuzzy_not(z.is_zero)])
933
+
934
+ def _eval_is_finite(self):
935
+ arg = self.args[0]
936
+ if arg.is_zero:
937
+ return False
938
+ return arg.is_finite
939
+
940
+ def _eval_is_extended_positive(self):
941
+ return (self.args[0] - 1).is_extended_positive
942
+
943
+ def _eval_is_zero(self):
944
+ return (self.args[0] - 1).is_zero
945
+
946
+ def _eval_is_extended_nonnegative(self):
947
+ return (self.args[0] - 1).is_extended_nonnegative
948
+
949
+ def _eval_nseries(self, x, n, logx, cdir=0):
950
+ # NOTE Please see the comment at the beginning of this file, labelled
951
+ # IMPORTANT.
952
+ from sympy.series.order import Order
953
+ from sympy.simplify.simplify import logcombine
954
+ from sympy.core.symbol import Dummy
955
+
956
+ if self.args[0] == x:
957
+ return log(x) if logx is None else logx
958
+ arg = self.args[0]
959
+ t = Dummy('t', positive=True)
960
+ if cdir == 0:
961
+ cdir = 1
962
+ z = arg.subs(x, cdir*t)
963
+
964
+ k, l = Wild("k"), Wild("l")
965
+ r = z.match(k*t**l)
966
+ if r is not None:
967
+ k, l = r[k], r[l]
968
+ if l != 0 and not l.has(t) and not k.has(t):
969
+ r = l*log(x) if logx is None else l*logx
970
+ r += log(k) - l*log(cdir) # XXX true regardless of assumptions?
971
+ return r
972
+
973
+ def coeff_exp(term, x):
974
+ coeff, exp = S.One, S.Zero
975
+ for factor in Mul.make_args(term):
976
+ if factor.has(x):
977
+ base, exp = factor.as_base_exp()
978
+ if base != x:
979
+ try:
980
+ return term.leadterm(x)
981
+ except ValueError:
982
+ return term, S.Zero
983
+ else:
984
+ coeff *= factor
985
+ return coeff, exp
986
+
987
+ # TODO new and probably slow
988
+ try:
989
+ a, b = z.leadterm(t, logx=logx, cdir=1)
990
+ except (ValueError, NotImplementedError, PoleError):
991
+ s = z._eval_nseries(t, n=n, logx=logx, cdir=1)
992
+ while s.is_Order:
993
+ n += 1
994
+ s = z._eval_nseries(t, n=n, logx=logx, cdir=1)
995
+ try:
996
+ a, b = s.removeO().leadterm(t, cdir=1)
997
+ except ValueError:
998
+ a, b = s.removeO().as_leading_term(t, cdir=1), S.Zero
999
+
1000
+ p = (z/(a*t**b) - 1)._eval_nseries(t, n=n, logx=logx, cdir=1)
1001
+ if p.has(exp):
1002
+ p = logcombine(p)
1003
+ if isinstance(p, Order):
1004
+ n = p.getn()
1005
+ _, d = coeff_exp(p, t)
1006
+ logx = log(x) if logx is None else logx
1007
+
1008
+ if not d.is_positive:
1009
+ res = log(a) - b*log(cdir) + b*logx
1010
+ _res = res
1011
+ logflags = {"deep": True, "log": True, "mul": False, "power_exp": False,
1012
+ "power_base": False, "multinomial": False, "basic": False, "force": True,
1013
+ "factor": False}
1014
+ expr = self.expand(**logflags)
1015
+ if (not a.could_extract_minus_sign() and
1016
+ logx.could_extract_minus_sign()):
1017
+ _res = _res.subs(-logx, -log(x)).expand(**logflags)
1018
+ else:
1019
+ _res = _res.subs(logx, log(x)).expand(**logflags)
1020
+ if _res == expr:
1021
+ return res
1022
+ return res + Order(x**n, x)
1023
+
1024
+ def mul(d1, d2):
1025
+ res = {}
1026
+ for e1, e2 in product(d1, d2):
1027
+ ex = e1 + e2
1028
+ if ex < n:
1029
+ res[ex] = res.get(ex, S.Zero) + d1[e1]*d2[e2]
1030
+ return res
1031
+
1032
+ pterms = {}
1033
+
1034
+ for term in Add.make_args(p.removeO()):
1035
+ co1, e1 = coeff_exp(term, t)
1036
+ pterms[e1] = pterms.get(e1, S.Zero) + co1
1037
+
1038
+ k = S.One
1039
+ terms = {}
1040
+ pk = pterms
1041
+
1042
+ while k*d < n:
1043
+ coeff = -S.NegativeOne**k/k
1044
+ for ex in pk:
1045
+ _ = terms.get(ex, S.Zero) + coeff*pk[ex]
1046
+ terms[ex] = _.nsimplify()
1047
+ pk = mul(pk, pterms)
1048
+ k += S.One
1049
+
1050
+ res = log(a) - b*log(cdir) + b*logx
1051
+ for ex in terms:
1052
+ res += terms[ex]*t**(ex)
1053
+
1054
+ if a.is_negative and im(z) != 0:
1055
+ from sympy.functions.special.delta_functions import Heaviside
1056
+ for i, term in enumerate(z.lseries(t)):
1057
+ if not term.is_real or i == 5:
1058
+ break
1059
+ if i < 5:
1060
+ coeff, _ = term.as_coeff_exponent(t)
1061
+ res += -2*I*pi*Heaviside(-im(coeff), 0)
1062
+
1063
+ res = res.subs(t, x/cdir)
1064
+ return res + Order(x**n, x)
1065
+
1066
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
1067
+ # NOTE
1068
+ # Refer https://github.com/sympy/sympy/pull/23592 for more information
1069
+ # on each of the following steps involved in this method.
1070
+ arg0 = self.args[0].together()
1071
+
1072
+ # STEP 1
1073
+ t = Dummy('t', positive=True)
1074
+ if cdir == 0:
1075
+ cdir = 1
1076
+ z = arg0.subs(x, cdir*t)
1077
+
1078
+ # STEP 2
1079
+ try:
1080
+ c, e = z.leadterm(t, logx=logx, cdir=1)
1081
+ except ValueError:
1082
+ arg = arg0.as_leading_term(x, logx=logx, cdir=cdir)
1083
+ return log(arg)
1084
+ if c.has(t):
1085
+ c = c.subs(t, x/cdir)
1086
+ if e != 0:
1087
+ raise PoleError("Cannot expand %s around 0" % (self))
1088
+ return log(c)
1089
+
1090
+ # STEP 3
1091
+ if c == S.One and e == S.Zero:
1092
+ return (arg0 - S.One).as_leading_term(x, logx=logx)
1093
+
1094
+ # STEP 4
1095
+ res = log(c) - e*log(cdir)
1096
+ logx = log(x) if logx is None else logx
1097
+ res += e*logx
1098
+
1099
+ # STEP 5
1100
+ if c.is_negative and im(z) != 0:
1101
+ from sympy.functions.special.delta_functions import Heaviside
1102
+ for i, term in enumerate(z.lseries(t)):
1103
+ if not term.is_real or i == 5:
1104
+ break
1105
+ if i < 5:
1106
+ coeff, _ = term.as_coeff_exponent(t)
1107
+ res += -2*I*pi*Heaviside(-im(coeff), 0)
1108
+ return res
1109
+
1110
+
1111
+ class LambertW(Function):
1112
+ r"""
1113
+ The Lambert W function $W(z)$ is defined as the inverse
1114
+ function of $w \exp(w)$ [1]_.
1115
+
1116
+ Explanation
1117
+ ===========
1118
+
1119
+ In other words, the value of $W(z)$ is such that $z = W(z) \exp(W(z))$
1120
+ for any complex number $z$. The Lambert W function is a multivalued
1121
+ function with infinitely many branches $W_k(z)$, indexed by
1122
+ $k \in \mathbb{Z}$. Each branch gives a different solution $w$
1123
+ of the equation $z = w \exp(w)$.
1124
+
1125
+ The Lambert W function has two partially real branches: the
1126
+ principal branch ($k = 0$) is real for real $z > -1/e$, and the
1127
+ $k = -1$ branch is real for $-1/e < z < 0$. All branches except
1128
+ $k = 0$ have a logarithmic singularity at $z = 0$.
1129
+
1130
+ Examples
1131
+ ========
1132
+
1133
+ >>> from sympy import LambertW
1134
+ >>> LambertW(1.2)
1135
+ 0.635564016364870
1136
+ >>> LambertW(1.2, -1).n()
1137
+ -1.34747534407696 - 4.41624341514535*I
1138
+ >>> LambertW(-1).is_real
1139
+ False
1140
+
1141
+ References
1142
+ ==========
1143
+
1144
+ .. [1] https://en.wikipedia.org/wiki/Lambert_W_function
1145
+ """
1146
+ _singularities = (-Pow(S.Exp1, -1, evaluate=False), S.ComplexInfinity)
1147
+
1148
+ @classmethod
1149
+ def eval(cls, x, k=None):
1150
+ if k == S.Zero:
1151
+ return cls(x)
1152
+ elif k is None:
1153
+ k = S.Zero
1154
+
1155
+ if k.is_zero:
1156
+ if x.is_zero:
1157
+ return S.Zero
1158
+ if x is S.Exp1:
1159
+ return S.One
1160
+ if x == -1/S.Exp1:
1161
+ return S.NegativeOne
1162
+ if x == -log(2)/2:
1163
+ return -log(2)
1164
+ if x == 2*log(2):
1165
+ return log(2)
1166
+ if x == -pi/2:
1167
+ return I*pi/2
1168
+ if x == exp(1 + S.Exp1):
1169
+ return S.Exp1
1170
+ if x is S.Infinity:
1171
+ return S.Infinity
1172
+ if x.is_zero:
1173
+ return S.Zero
1174
+
1175
+ if fuzzy_not(k.is_zero):
1176
+ if x.is_zero:
1177
+ return S.NegativeInfinity
1178
+ if k is S.NegativeOne:
1179
+ if x == -pi/2:
1180
+ return -I*pi/2
1181
+ elif x == -1/S.Exp1:
1182
+ return S.NegativeOne
1183
+ elif x == -2*exp(-2):
1184
+ return -Integer(2)
1185
+
1186
+ def fdiff(self, argindex=1):
1187
+ """
1188
+ Return the first derivative of this function.
1189
+ """
1190
+ x = self.args[0]
1191
+
1192
+ if len(self.args) == 1:
1193
+ if argindex == 1:
1194
+ return LambertW(x)/(x*(1 + LambertW(x)))
1195
+ else:
1196
+ k = self.args[1]
1197
+ if argindex == 1:
1198
+ return LambertW(x, k)/(x*(1 + LambertW(x, k)))
1199
+
1200
+ raise ArgumentIndexError(self, argindex)
1201
+
1202
+ def _eval_is_extended_real(self):
1203
+ x = self.args[0]
1204
+ if len(self.args) == 1:
1205
+ k = S.Zero
1206
+ else:
1207
+ k = self.args[1]
1208
+ if k.is_zero:
1209
+ if (x + 1/S.Exp1).is_positive:
1210
+ return True
1211
+ elif (x + 1/S.Exp1).is_nonpositive:
1212
+ return False
1213
+ elif (k + 1).is_zero:
1214
+ if x.is_negative and (x + 1/S.Exp1).is_positive:
1215
+ return True
1216
+ elif x.is_nonpositive or (x + 1/S.Exp1).is_nonnegative:
1217
+ return False
1218
+ elif fuzzy_not(k.is_zero) and fuzzy_not((k + 1).is_zero):
1219
+ if x.is_extended_real:
1220
+ return False
1221
+
1222
+ def _eval_is_finite(self):
1223
+ return self.args[0].is_finite
1224
+
1225
+ def _eval_is_algebraic(self):
1226
+ s = self.func(*self.args)
1227
+ if s.func == self.func:
1228
+ if fuzzy_not(self.args[0].is_zero) and self.args[0].is_algebraic:
1229
+ return False
1230
+ else:
1231
+ return s.is_algebraic
1232
+
1233
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
1234
+ if len(self.args) == 1:
1235
+ arg = self.args[0]
1236
+ arg0 = arg.subs(x, 0).cancel()
1237
+ if not arg0.is_zero:
1238
+ return self.func(arg0)
1239
+ return arg.as_leading_term(x)
1240
+
1241
+ def _eval_nseries(self, x, n, logx, cdir=0):
1242
+ if len(self.args) == 1:
1243
+ from sympy.functions.elementary.integers import ceiling
1244
+ from sympy.series.order import Order
1245
+ arg = self.args[0].nseries(x, n=n, logx=logx)
1246
+ lt = arg.as_leading_term(x, logx=logx)
1247
+ lte = 1
1248
+ if lt.is_Pow:
1249
+ lte = lt.exp
1250
+ if ceiling(n/lte) >= 1:
1251
+ s = Add(*[(-S.One)**(k - 1)*Integer(k)**(k - 2)/
1252
+ factorial(k - 1)*arg**k for k in range(1, ceiling(n/lte))])
1253
+ s = expand_multinomial(s)
1254
+ else:
1255
+ s = S.Zero
1256
+
1257
+ return s + Order(x**n, x)
1258
+ return super()._eval_nseries(x, n, logx)
1259
+
1260
+ def _eval_is_zero(self):
1261
+ x = self.args[0]
1262
+ if len(self.args) == 1:
1263
+ return x.is_zero
1264
+ else:
1265
+ return fuzzy_and([x.is_zero, self.args[1].is_zero])
1266
+
1267
+
1268
+ @cacheit
1269
+ def _log_atan_table():
1270
+ return {
1271
+ # first quadrant only
1272
+ sqrt(3): pi / 3,
1273
+ 1: pi / 4,
1274
+ sqrt(5 - 2 * sqrt(5)): pi / 5,
1275
+ sqrt(2) * sqrt(5 - sqrt(5)) / (1 + sqrt(5)): pi / 5,
1276
+ sqrt(5 + 2 * sqrt(5)): pi * Rational(2, 5),
1277
+ sqrt(2) * sqrt(sqrt(5) + 5) / (-1 + sqrt(5)): pi * Rational(2, 5),
1278
+ sqrt(3) / 3: pi / 6,
1279
+ sqrt(2) - 1: pi / 8,
1280
+ sqrt(2 - sqrt(2)) / sqrt(sqrt(2) + 2): pi / 8,
1281
+ sqrt(2) + 1: pi * Rational(3, 8),
1282
+ sqrt(sqrt(2) + 2) / sqrt(2 - sqrt(2)): pi * Rational(3, 8),
1283
+ sqrt(1 - 2 * sqrt(5) / 5): pi / 10,
1284
+ (-sqrt(2) + sqrt(10)) / (2 * sqrt(sqrt(5) + 5)): pi / 10,
1285
+ sqrt(1 + 2 * sqrt(5) / 5): pi * Rational(3, 10),
1286
+ (sqrt(2) + sqrt(10)) / (2 * sqrt(5 - sqrt(5))): pi * Rational(3, 10),
1287
+ 2 - sqrt(3): pi / 12,
1288
+ (-1 + sqrt(3)) / (1 + sqrt(3)): pi / 12,
1289
+ 2 + sqrt(3): pi * Rational(5, 12),
1290
+ (1 + sqrt(3)) / (-1 + sqrt(3)): pi * Rational(5, 12)
1291
+ }
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/integers.py ADDED
@@ -0,0 +1,625 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Tuple as tTuple
2
+
3
+ from sympy.core.basic import Basic
4
+ from sympy.core.expr import Expr
5
+
6
+ from sympy.core import Add, S
7
+ from sympy.core.evalf import get_integer_part, PrecisionExhausted
8
+ from sympy.core.function import Function
9
+ from sympy.core.logic import fuzzy_or
10
+ from sympy.core.numbers import Integer
11
+ from sympy.core.relational import Gt, Lt, Ge, Le, Relational, is_eq
12
+ from sympy.core.symbol import Symbol
13
+ from sympy.core.sympify import _sympify
14
+ from sympy.functions.elementary.complexes import im, re
15
+ from sympy.multipledispatch import dispatch
16
+
17
+ ###############################################################################
18
+ ######################### FLOOR and CEILING FUNCTIONS #########################
19
+ ###############################################################################
20
+
21
+
22
+ class RoundFunction(Function):
23
+ """Abstract base class for rounding functions."""
24
+
25
+ args: tTuple[Expr]
26
+
27
+ @classmethod
28
+ def eval(cls, arg):
29
+ v = cls._eval_number(arg)
30
+ if v is not None:
31
+ return v
32
+
33
+ if arg.is_integer or arg.is_finite is False:
34
+ return arg
35
+ if arg.is_imaginary or (S.ImaginaryUnit*arg).is_real:
36
+ i = im(arg)
37
+ if not i.has(S.ImaginaryUnit):
38
+ return cls(i)*S.ImaginaryUnit
39
+ return cls(arg, evaluate=False)
40
+
41
+ # Integral, numerical, symbolic part
42
+ ipart = npart = spart = S.Zero
43
+
44
+ # Extract integral (or complex integral) terms
45
+ terms = Add.make_args(arg)
46
+
47
+ for t in terms:
48
+ if t.is_integer or (t.is_imaginary and im(t).is_integer):
49
+ ipart += t
50
+ elif t.has(Symbol):
51
+ spart += t
52
+ else:
53
+ npart += t
54
+
55
+ if not (npart or spart):
56
+ return ipart
57
+
58
+ # Evaluate npart numerically if independent of spart
59
+ if npart and (
60
+ not spart or
61
+ npart.is_real and (spart.is_imaginary or (S.ImaginaryUnit*spart).is_real) or
62
+ npart.is_imaginary and spart.is_real):
63
+ try:
64
+ r, i = get_integer_part(
65
+ npart, cls._dir, {}, return_ints=True)
66
+ ipart += Integer(r) + Integer(i)*S.ImaginaryUnit
67
+ npart = S.Zero
68
+ except (PrecisionExhausted, NotImplementedError):
69
+ pass
70
+
71
+ spart += npart
72
+ if not spart:
73
+ return ipart
74
+ elif spart.is_imaginary or (S.ImaginaryUnit*spart).is_real:
75
+ return ipart + cls(im(spart), evaluate=False)*S.ImaginaryUnit
76
+ elif isinstance(spart, (floor, ceiling)):
77
+ return ipart + spart
78
+ else:
79
+ return ipart + cls(spart, evaluate=False)
80
+
81
+ @classmethod
82
+ def _eval_number(cls, arg):
83
+ raise NotImplementedError()
84
+
85
+ def _eval_is_finite(self):
86
+ return self.args[0].is_finite
87
+
88
+ def _eval_is_real(self):
89
+ return self.args[0].is_real
90
+
91
+ def _eval_is_integer(self):
92
+ return self.args[0].is_real
93
+
94
+
95
+ class floor(RoundFunction):
96
+ """
97
+ Floor is a univariate function which returns the largest integer
98
+ value not greater than its argument. This implementation
99
+ generalizes floor to complex numbers by taking the floor of the
100
+ real and imaginary parts separately.
101
+
102
+ Examples
103
+ ========
104
+
105
+ >>> from sympy import floor, E, I, S, Float, Rational
106
+ >>> floor(17)
107
+ 17
108
+ >>> floor(Rational(23, 10))
109
+ 2
110
+ >>> floor(2*E)
111
+ 5
112
+ >>> floor(-Float(0.567))
113
+ -1
114
+ >>> floor(-I/2)
115
+ -I
116
+ >>> floor(S(5)/2 + 5*I/2)
117
+ 2 + 2*I
118
+
119
+ See Also
120
+ ========
121
+
122
+ sympy.functions.elementary.integers.ceiling
123
+
124
+ References
125
+ ==========
126
+
127
+ .. [1] "Concrete mathematics" by Graham, pp. 87
128
+ .. [2] https://mathworld.wolfram.com/FloorFunction.html
129
+
130
+ """
131
+ _dir = -1
132
+
133
+ @classmethod
134
+ def _eval_number(cls, arg):
135
+ if arg.is_Number:
136
+ return arg.floor()
137
+ elif any(isinstance(i, j)
138
+ for i in (arg, -arg) for j in (floor, ceiling)):
139
+ return arg
140
+ if arg.is_NumberSymbol:
141
+ return arg.approximation_interval(Integer)[0]
142
+
143
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
144
+ from sympy.calculus.accumulationbounds import AccumBounds
145
+ arg = self.args[0]
146
+ arg0 = arg.subs(x, 0)
147
+ r = self.subs(x, 0)
148
+ if arg0 is S.NaN or isinstance(arg0, AccumBounds):
149
+ arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+')
150
+ r = floor(arg0)
151
+ if arg0.is_finite:
152
+ if arg0 == r:
153
+ ndir = arg.dir(x, cdir=cdir)
154
+ return r - 1 if ndir.is_negative else r
155
+ else:
156
+ return r
157
+ return arg.as_leading_term(x, logx=logx, cdir=cdir)
158
+
159
+ def _eval_nseries(self, x, n, logx, cdir=0):
160
+ arg = self.args[0]
161
+ arg0 = arg.subs(x, 0)
162
+ r = self.subs(x, 0)
163
+ if arg0 is S.NaN:
164
+ arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+')
165
+ r = floor(arg0)
166
+ if arg0.is_infinite:
167
+ from sympy.calculus.accumulationbounds import AccumBounds
168
+ from sympy.series.order import Order
169
+ s = arg._eval_nseries(x, n, logx, cdir)
170
+ o = Order(1, (x, 0)) if n <= 0 else AccumBounds(-1, 0)
171
+ return s + o
172
+ if arg0 == r:
173
+ ndir = arg.dir(x, cdir=cdir if cdir != 0 else 1)
174
+ return r - 1 if ndir.is_negative else r
175
+ else:
176
+ return r
177
+
178
+ def _eval_is_negative(self):
179
+ return self.args[0].is_negative
180
+
181
+ def _eval_is_nonnegative(self):
182
+ return self.args[0].is_nonnegative
183
+
184
+ def _eval_rewrite_as_ceiling(self, arg, **kwargs):
185
+ return -ceiling(-arg)
186
+
187
+ def _eval_rewrite_as_frac(self, arg, **kwargs):
188
+ return arg - frac(arg)
189
+
190
+ def __le__(self, other):
191
+ other = S(other)
192
+ if self.args[0].is_real:
193
+ if other.is_integer:
194
+ return self.args[0] < other + 1
195
+ if other.is_number and other.is_real:
196
+ return self.args[0] < ceiling(other)
197
+ if self.args[0] == other and other.is_real:
198
+ return S.true
199
+ if other is S.Infinity and self.is_finite:
200
+ return S.true
201
+
202
+ return Le(self, other, evaluate=False)
203
+
204
+ def __ge__(self, other):
205
+ other = S(other)
206
+ if self.args[0].is_real:
207
+ if other.is_integer:
208
+ return self.args[0] >= other
209
+ if other.is_number and other.is_real:
210
+ return self.args[0] >= ceiling(other)
211
+ if self.args[0] == other and other.is_real:
212
+ return S.false
213
+ if other is S.NegativeInfinity and self.is_finite:
214
+ return S.true
215
+
216
+ return Ge(self, other, evaluate=False)
217
+
218
+ def __gt__(self, other):
219
+ other = S(other)
220
+ if self.args[0].is_real:
221
+ if other.is_integer:
222
+ return self.args[0] >= other + 1
223
+ if other.is_number and other.is_real:
224
+ return self.args[0] >= ceiling(other)
225
+ if self.args[0] == other and other.is_real:
226
+ return S.false
227
+ if other is S.NegativeInfinity and self.is_finite:
228
+ return S.true
229
+
230
+ return Gt(self, other, evaluate=False)
231
+
232
+ def __lt__(self, other):
233
+ other = S(other)
234
+ if self.args[0].is_real:
235
+ if other.is_integer:
236
+ return self.args[0] < other
237
+ if other.is_number and other.is_real:
238
+ return self.args[0] < ceiling(other)
239
+ if self.args[0] == other and other.is_real:
240
+ return S.false
241
+ if other is S.Infinity and self.is_finite:
242
+ return S.true
243
+
244
+ return Lt(self, other, evaluate=False)
245
+
246
+
247
+ @dispatch(floor, Expr)
248
+ def _eval_is_eq(lhs, rhs): # noqa:F811
249
+ return is_eq(lhs.rewrite(ceiling), rhs) or \
250
+ is_eq(lhs.rewrite(frac),rhs)
251
+
252
+
253
+ class ceiling(RoundFunction):
254
+ """
255
+ Ceiling is a univariate function which returns the smallest integer
256
+ value not less than its argument. This implementation
257
+ generalizes ceiling to complex numbers by taking the ceiling of the
258
+ real and imaginary parts separately.
259
+
260
+ Examples
261
+ ========
262
+
263
+ >>> from sympy import ceiling, E, I, S, Float, Rational
264
+ >>> ceiling(17)
265
+ 17
266
+ >>> ceiling(Rational(23, 10))
267
+ 3
268
+ >>> ceiling(2*E)
269
+ 6
270
+ >>> ceiling(-Float(0.567))
271
+ 0
272
+ >>> ceiling(I/2)
273
+ I
274
+ >>> ceiling(S(5)/2 + 5*I/2)
275
+ 3 + 3*I
276
+
277
+ See Also
278
+ ========
279
+
280
+ sympy.functions.elementary.integers.floor
281
+
282
+ References
283
+ ==========
284
+
285
+ .. [1] "Concrete mathematics" by Graham, pp. 87
286
+ .. [2] https://mathworld.wolfram.com/CeilingFunction.html
287
+
288
+ """
289
+ _dir = 1
290
+
291
+ @classmethod
292
+ def _eval_number(cls, arg):
293
+ if arg.is_Number:
294
+ return arg.ceiling()
295
+ elif any(isinstance(i, j)
296
+ for i in (arg, -arg) for j in (floor, ceiling)):
297
+ return arg
298
+ if arg.is_NumberSymbol:
299
+ return arg.approximation_interval(Integer)[1]
300
+
301
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
302
+ from sympy.calculus.accumulationbounds import AccumBounds
303
+ arg = self.args[0]
304
+ arg0 = arg.subs(x, 0)
305
+ r = self.subs(x, 0)
306
+ if arg0 is S.NaN or isinstance(arg0, AccumBounds):
307
+ arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+')
308
+ r = ceiling(arg0)
309
+ if arg0.is_finite:
310
+ if arg0 == r:
311
+ ndir = arg.dir(x, cdir=cdir)
312
+ return r if ndir.is_negative else r + 1
313
+ else:
314
+ return r
315
+ return arg.as_leading_term(x, logx=logx, cdir=cdir)
316
+
317
+ def _eval_nseries(self, x, n, logx, cdir=0):
318
+ arg = self.args[0]
319
+ arg0 = arg.subs(x, 0)
320
+ r = self.subs(x, 0)
321
+ if arg0 is S.NaN:
322
+ arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+')
323
+ r = ceiling(arg0)
324
+ if arg0.is_infinite:
325
+ from sympy.calculus.accumulationbounds import AccumBounds
326
+ from sympy.series.order import Order
327
+ s = arg._eval_nseries(x, n, logx, cdir)
328
+ o = Order(1, (x, 0)) if n <= 0 else AccumBounds(0, 1)
329
+ return s + o
330
+ if arg0 == r:
331
+ ndir = arg.dir(x, cdir=cdir if cdir != 0 else 1)
332
+ return r if ndir.is_negative else r + 1
333
+ else:
334
+ return r
335
+
336
+ def _eval_rewrite_as_floor(self, arg, **kwargs):
337
+ return -floor(-arg)
338
+
339
+ def _eval_rewrite_as_frac(self, arg, **kwargs):
340
+ return arg + frac(-arg)
341
+
342
+ def _eval_is_positive(self):
343
+ return self.args[0].is_positive
344
+
345
+ def _eval_is_nonpositive(self):
346
+ return self.args[0].is_nonpositive
347
+
348
+ def __lt__(self, other):
349
+ other = S(other)
350
+ if self.args[0].is_real:
351
+ if other.is_integer:
352
+ return self.args[0] <= other - 1
353
+ if other.is_number and other.is_real:
354
+ return self.args[0] <= floor(other)
355
+ if self.args[0] == other and other.is_real:
356
+ return S.false
357
+ if other is S.Infinity and self.is_finite:
358
+ return S.true
359
+
360
+ return Lt(self, other, evaluate=False)
361
+
362
+ def __gt__(self, other):
363
+ other = S(other)
364
+ if self.args[0].is_real:
365
+ if other.is_integer:
366
+ return self.args[0] > other
367
+ if other.is_number and other.is_real:
368
+ return self.args[0] > floor(other)
369
+ if self.args[0] == other and other.is_real:
370
+ return S.false
371
+ if other is S.NegativeInfinity and self.is_finite:
372
+ return S.true
373
+
374
+ return Gt(self, other, evaluate=False)
375
+
376
+ def __ge__(self, other):
377
+ other = S(other)
378
+ if self.args[0].is_real:
379
+ if other.is_integer:
380
+ return self.args[0] > other - 1
381
+ if other.is_number and other.is_real:
382
+ return self.args[0] > floor(other)
383
+ if self.args[0] == other and other.is_real:
384
+ return S.true
385
+ if other is S.NegativeInfinity and self.is_finite:
386
+ return S.true
387
+
388
+ return Ge(self, other, evaluate=False)
389
+
390
+ def __le__(self, other):
391
+ other = S(other)
392
+ if self.args[0].is_real:
393
+ if other.is_integer:
394
+ return self.args[0] <= other
395
+ if other.is_number and other.is_real:
396
+ return self.args[0] <= floor(other)
397
+ if self.args[0] == other and other.is_real:
398
+ return S.false
399
+ if other is S.Infinity and self.is_finite:
400
+ return S.true
401
+
402
+ return Le(self, other, evaluate=False)
403
+
404
+
405
+ @dispatch(ceiling, Basic) # type:ignore
406
+ def _eval_is_eq(lhs, rhs): # noqa:F811
407
+ return is_eq(lhs.rewrite(floor), rhs) or is_eq(lhs.rewrite(frac),rhs)
408
+
409
+
410
+ class frac(Function):
411
+ r"""Represents the fractional part of x
412
+
413
+ For real numbers it is defined [1]_ as
414
+
415
+ .. math::
416
+ x - \left\lfloor{x}\right\rfloor
417
+
418
+ Examples
419
+ ========
420
+
421
+ >>> from sympy import Symbol, frac, Rational, floor, I
422
+ >>> frac(Rational(4, 3))
423
+ 1/3
424
+ >>> frac(-Rational(4, 3))
425
+ 2/3
426
+
427
+ returns zero for integer arguments
428
+
429
+ >>> n = Symbol('n', integer=True)
430
+ >>> frac(n)
431
+ 0
432
+
433
+ rewrite as floor
434
+
435
+ >>> x = Symbol('x')
436
+ >>> frac(x).rewrite(floor)
437
+ x - floor(x)
438
+
439
+ for complex arguments
440
+
441
+ >>> r = Symbol('r', real=True)
442
+ >>> t = Symbol('t', real=True)
443
+ >>> frac(t + I*r)
444
+ I*frac(r) + frac(t)
445
+
446
+ See Also
447
+ ========
448
+
449
+ sympy.functions.elementary.integers.floor
450
+ sympy.functions.elementary.integers.ceiling
451
+
452
+ References
453
+ ===========
454
+
455
+ .. [1] https://en.wikipedia.org/wiki/Fractional_part
456
+ .. [2] https://mathworld.wolfram.com/FractionalPart.html
457
+
458
+ """
459
+ @classmethod
460
+ def eval(cls, arg):
461
+ from sympy.calculus.accumulationbounds import AccumBounds
462
+
463
+ def _eval(arg):
464
+ if arg in (S.Infinity, S.NegativeInfinity):
465
+ return AccumBounds(0, 1)
466
+ if arg.is_integer:
467
+ return S.Zero
468
+ if arg.is_number:
469
+ if arg is S.NaN:
470
+ return S.NaN
471
+ elif arg is S.ComplexInfinity:
472
+ return S.NaN
473
+ else:
474
+ return arg - floor(arg)
475
+ return cls(arg, evaluate=False)
476
+
477
+ terms = Add.make_args(arg)
478
+ real, imag = S.Zero, S.Zero
479
+ for t in terms:
480
+ # Two checks are needed for complex arguments
481
+ # see issue-7649 for details
482
+ if t.is_imaginary or (S.ImaginaryUnit*t).is_real:
483
+ i = im(t)
484
+ if not i.has(S.ImaginaryUnit):
485
+ imag += i
486
+ else:
487
+ real += t
488
+ else:
489
+ real += t
490
+
491
+ real = _eval(real)
492
+ imag = _eval(imag)
493
+ return real + S.ImaginaryUnit*imag
494
+
495
+ def _eval_rewrite_as_floor(self, arg, **kwargs):
496
+ return arg - floor(arg)
497
+
498
+ def _eval_rewrite_as_ceiling(self, arg, **kwargs):
499
+ return arg + ceiling(-arg)
500
+
501
+ def _eval_is_finite(self):
502
+ return True
503
+
504
+ def _eval_is_real(self):
505
+ return self.args[0].is_extended_real
506
+
507
+ def _eval_is_imaginary(self):
508
+ return self.args[0].is_imaginary
509
+
510
+ def _eval_is_integer(self):
511
+ return self.args[0].is_integer
512
+
513
+ def _eval_is_zero(self):
514
+ return fuzzy_or([self.args[0].is_zero, self.args[0].is_integer])
515
+
516
+ def _eval_is_negative(self):
517
+ return False
518
+
519
+ def __ge__(self, other):
520
+ if self.is_extended_real:
521
+ other = _sympify(other)
522
+ # Check if other <= 0
523
+ if other.is_extended_nonpositive:
524
+ return S.true
525
+ # Check if other >= 1
526
+ res = self._value_one_or_more(other)
527
+ if res is not None:
528
+ return not(res)
529
+ return Ge(self, other, evaluate=False)
530
+
531
+ def __gt__(self, other):
532
+ if self.is_extended_real:
533
+ other = _sympify(other)
534
+ # Check if other < 0
535
+ res = self._value_one_or_more(other)
536
+ if res is not None:
537
+ return not(res)
538
+ # Check if other >= 1
539
+ if other.is_extended_negative:
540
+ return S.true
541
+ return Gt(self, other, evaluate=False)
542
+
543
+ def __le__(self, other):
544
+ if self.is_extended_real:
545
+ other = _sympify(other)
546
+ # Check if other < 0
547
+ if other.is_extended_negative:
548
+ return S.false
549
+ # Check if other >= 1
550
+ res = self._value_one_or_more(other)
551
+ if res is not None:
552
+ return res
553
+ return Le(self, other, evaluate=False)
554
+
555
+ def __lt__(self, other):
556
+ if self.is_extended_real:
557
+ other = _sympify(other)
558
+ # Check if other <= 0
559
+ if other.is_extended_nonpositive:
560
+ return S.false
561
+ # Check if other >= 1
562
+ res = self._value_one_or_more(other)
563
+ if res is not None:
564
+ return res
565
+ return Lt(self, other, evaluate=False)
566
+
567
+ def _value_one_or_more(self, other):
568
+ if other.is_extended_real:
569
+ if other.is_number:
570
+ res = other >= 1
571
+ if res and not isinstance(res, Relational):
572
+ return S.true
573
+ if other.is_integer and other.is_positive:
574
+ return S.true
575
+
576
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
577
+ from sympy.calculus.accumulationbounds import AccumBounds
578
+ arg = self.args[0]
579
+ arg0 = arg.subs(x, 0)
580
+ r = self.subs(x, 0)
581
+
582
+ if arg0.is_finite:
583
+ if r.is_zero:
584
+ ndir = arg.dir(x, cdir=cdir)
585
+ if ndir.is_negative:
586
+ return S.One
587
+ return (arg - arg0).as_leading_term(x, logx=logx, cdir=cdir)
588
+ else:
589
+ return r
590
+ elif arg0 in (S.ComplexInfinity, S.Infinity, S.NegativeInfinity):
591
+ return AccumBounds(0, 1)
592
+ return arg.as_leading_term(x, logx=logx, cdir=cdir)
593
+
594
+ def _eval_nseries(self, x, n, logx, cdir=0):
595
+ from sympy.series.order import Order
596
+ arg = self.args[0]
597
+ arg0 = arg.subs(x, 0)
598
+ r = self.subs(x, 0)
599
+
600
+ if arg0.is_infinite:
601
+ from sympy.calculus.accumulationbounds import AccumBounds
602
+ o = Order(1, (x, 0)) if n <= 0 else AccumBounds(0, 1) + Order(x**n, (x, 0))
603
+ return o
604
+ else:
605
+ res = (arg - arg0)._eval_nseries(x, n, logx=logx, cdir=cdir)
606
+ if r.is_zero:
607
+ ndir = arg.dir(x, cdir=cdir)
608
+ res += S.One if ndir.is_negative else S.Zero
609
+ else:
610
+ res += r
611
+ return res
612
+
613
+
614
+ @dispatch(frac, Basic) # type:ignore
615
+ def _eval_is_eq(lhs, rhs): # noqa:F811
616
+ if (lhs.rewrite(floor) == rhs) or \
617
+ (lhs.rewrite(ceiling) == rhs):
618
+ return True
619
+ # Check if other < 0
620
+ if rhs.is_extended_negative:
621
+ return False
622
+ # Check if other >= 1
623
+ res = lhs._value_one_or_more(rhs)
624
+ if res is not None:
625
+ return False
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/tests/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (197 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_complexes.cpython-310.pyc ADDED
Binary file (30.5 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_exponential.cpython-310.pyc ADDED
Binary file (29.6 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_hyperbolic.cpython-310.pyc ADDED
Binary file (54.9 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_integers.cpython-310.pyc ADDED
Binary file (16.9 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_interface.cpython-310.pyc ADDED
Binary file (3.1 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_miscellaneous.cpython-310.pyc ADDED
Binary file (15.6 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_piecewise.cpython-310.pyc ADDED
Binary file (54.4 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_trigonometric.cpython-310.pyc ADDED
Binary file (85.4 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_complexes.py ADDED
@@ -0,0 +1,1018 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.expr import Expr
2
+ from sympy.core.function import (Derivative, Function, Lambda, expand)
3
+ from sympy.core.numbers import (E, I, Rational, comp, nan, oo, pi, zoo)
4
+ from sympy.core.relational import Eq
5
+ from sympy.core.singleton import S
6
+ from sympy.core.symbol import (Symbol, symbols)
7
+ from sympy.functions.elementary.complexes import (Abs, adjoint, arg, conjugate, im, re, sign, transpose)
8
+ from sympy.functions.elementary.exponential import (exp, exp_polar, log)
9
+ from sympy.functions.elementary.miscellaneous import sqrt
10
+ from sympy.functions.elementary.piecewise import Piecewise
11
+ from sympy.functions.elementary.trigonometric import (acos, atan, atan2, cos, sin)
12
+ from sympy.functions.special.delta_functions import (DiracDelta, Heaviside)
13
+ from sympy.integrals.integrals import Integral
14
+ from sympy.matrices.dense import Matrix
15
+ from sympy.matrices.expressions.funcmatrix import FunctionMatrix
16
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
17
+ from sympy.matrices.immutable import (ImmutableMatrix, ImmutableSparseMatrix)
18
+ from sympy.matrices import SparseMatrix
19
+ from sympy.sets.sets import Interval
20
+ from sympy.core.expr import unchanged
21
+ from sympy.core.function import ArgumentIndexError
22
+ from sympy.testing.pytest import XFAIL, raises, _both_exp_pow
23
+
24
+
25
+ def N_equals(a, b):
26
+ """Check whether two complex numbers are numerically close"""
27
+ return comp(a.n(), b.n(), 1.e-6)
28
+
29
+
30
+ def test_re():
31
+ x, y = symbols('x,y')
32
+ a, b = symbols('a,b', real=True)
33
+
34
+ r = Symbol('r', real=True)
35
+ i = Symbol('i', imaginary=True)
36
+
37
+ assert re(nan) is nan
38
+
39
+ assert re(oo) is oo
40
+ assert re(-oo) is -oo
41
+
42
+ assert re(0) == 0
43
+
44
+ assert re(1) == 1
45
+ assert re(-1) == -1
46
+
47
+ assert re(E) == E
48
+ assert re(-E) == -E
49
+
50
+ assert unchanged(re, x)
51
+ assert re(x*I) == -im(x)
52
+ assert re(r*I) == 0
53
+ assert re(r) == r
54
+ assert re(i*I) == I * i
55
+ assert re(i) == 0
56
+
57
+ assert re(x + y) == re(x) + re(y)
58
+ assert re(x + r) == re(x) + r
59
+
60
+ assert re(re(x)) == re(x)
61
+
62
+ assert re(2 + I) == 2
63
+ assert re(x + I) == re(x)
64
+
65
+ assert re(x + y*I) == re(x) - im(y)
66
+ assert re(x + r*I) == re(x)
67
+
68
+ assert re(log(2*I)) == log(2)
69
+
70
+ assert re((2 + I)**2).expand(complex=True) == 3
71
+
72
+ assert re(conjugate(x)) == re(x)
73
+ assert conjugate(re(x)) == re(x)
74
+
75
+ assert re(x).as_real_imag() == (re(x), 0)
76
+
77
+ assert re(i*r*x).diff(r) == re(i*x)
78
+ assert re(i*r*x).diff(i) == I*r*im(x)
79
+
80
+ assert re(
81
+ sqrt(a + b*I)) == (a**2 + b**2)**Rational(1, 4)*cos(atan2(b, a)/2)
82
+ assert re(a * (2 + b*I)) == 2*a
83
+
84
+ assert re((1 + sqrt(a + b*I))/2) == \
85
+ (a**2 + b**2)**Rational(1, 4)*cos(atan2(b, a)/2)/2 + S.Half
86
+
87
+ assert re(x).rewrite(im) == x - S.ImaginaryUnit*im(x)
88
+ assert (x + re(y)).rewrite(re, im) == x + y - S.ImaginaryUnit*im(y)
89
+
90
+ a = Symbol('a', algebraic=True)
91
+ t = Symbol('t', transcendental=True)
92
+ x = Symbol('x')
93
+ assert re(a).is_algebraic
94
+ assert re(x).is_algebraic is None
95
+ assert re(t).is_algebraic is False
96
+
97
+ assert re(S.ComplexInfinity) is S.NaN
98
+
99
+ n, m, l = symbols('n m l')
100
+ A = MatrixSymbol('A',n,m)
101
+ assert re(A) == (S.Half) * (A + conjugate(A))
102
+
103
+ A = Matrix([[1 + 4*I,2],[0, -3*I]])
104
+ assert re(A) == Matrix([[1, 2],[0, 0]])
105
+
106
+ A = ImmutableMatrix([[1 + 3*I, 3-2*I],[0, 2*I]])
107
+ assert re(A) == ImmutableMatrix([[1, 3],[0, 0]])
108
+
109
+ X = SparseMatrix([[2*j + i*I for i in range(5)] for j in range(5)])
110
+ assert re(X) - Matrix([[0, 0, 0, 0, 0],
111
+ [2, 2, 2, 2, 2],
112
+ [4, 4, 4, 4, 4],
113
+ [6, 6, 6, 6, 6],
114
+ [8, 8, 8, 8, 8]]) == Matrix.zeros(5)
115
+
116
+ assert im(X) - Matrix([[0, 1, 2, 3, 4],
117
+ [0, 1, 2, 3, 4],
118
+ [0, 1, 2, 3, 4],
119
+ [0, 1, 2, 3, 4],
120
+ [0, 1, 2, 3, 4]]) == Matrix.zeros(5)
121
+
122
+ X = FunctionMatrix(3, 3, Lambda((n, m), n + m*I))
123
+ assert re(X) == Matrix([[0, 0, 0], [1, 1, 1], [2, 2, 2]])
124
+
125
+
126
+ def test_im():
127
+ x, y = symbols('x,y')
128
+ a, b = symbols('a,b', real=True)
129
+
130
+ r = Symbol('r', real=True)
131
+ i = Symbol('i', imaginary=True)
132
+
133
+ assert im(nan) is nan
134
+
135
+ assert im(oo*I) is oo
136
+ assert im(-oo*I) is -oo
137
+
138
+ assert im(0) == 0
139
+
140
+ assert im(1) == 0
141
+ assert im(-1) == 0
142
+
143
+ assert im(E*I) == E
144
+ assert im(-E*I) == -E
145
+
146
+ assert unchanged(im, x)
147
+ assert im(x*I) == re(x)
148
+ assert im(r*I) == r
149
+ assert im(r) == 0
150
+ assert im(i*I) == 0
151
+ assert im(i) == -I * i
152
+
153
+ assert im(x + y) == im(x) + im(y)
154
+ assert im(x + r) == im(x)
155
+ assert im(x + r*I) == im(x) + r
156
+
157
+ assert im(im(x)*I) == im(x)
158
+
159
+ assert im(2 + I) == 1
160
+ assert im(x + I) == im(x) + 1
161
+
162
+ assert im(x + y*I) == im(x) + re(y)
163
+ assert im(x + r*I) == im(x) + r
164
+
165
+ assert im(log(2*I)) == pi/2
166
+
167
+ assert im((2 + I)**2).expand(complex=True) == 4
168
+
169
+ assert im(conjugate(x)) == -im(x)
170
+ assert conjugate(im(x)) == im(x)
171
+
172
+ assert im(x).as_real_imag() == (im(x), 0)
173
+
174
+ assert im(i*r*x).diff(r) == im(i*x)
175
+ assert im(i*r*x).diff(i) == -I * re(r*x)
176
+
177
+ assert im(
178
+ sqrt(a + b*I)) == (a**2 + b**2)**Rational(1, 4)*sin(atan2(b, a)/2)
179
+ assert im(a * (2 + b*I)) == a*b
180
+
181
+ assert im((1 + sqrt(a + b*I))/2) == \
182
+ (a**2 + b**2)**Rational(1, 4)*sin(atan2(b, a)/2)/2
183
+
184
+ assert im(x).rewrite(re) == -S.ImaginaryUnit * (x - re(x))
185
+ assert (x + im(y)).rewrite(im, re) == x - S.ImaginaryUnit * (y - re(y))
186
+
187
+ a = Symbol('a', algebraic=True)
188
+ t = Symbol('t', transcendental=True)
189
+ x = Symbol('x')
190
+ assert re(a).is_algebraic
191
+ assert re(x).is_algebraic is None
192
+ assert re(t).is_algebraic is False
193
+
194
+ assert im(S.ComplexInfinity) is S.NaN
195
+
196
+ n, m, l = symbols('n m l')
197
+ A = MatrixSymbol('A',n,m)
198
+
199
+ assert im(A) == (S.One/(2*I)) * (A - conjugate(A))
200
+
201
+ A = Matrix([[1 + 4*I, 2],[0, -3*I]])
202
+ assert im(A) == Matrix([[4, 0],[0, -3]])
203
+
204
+ A = ImmutableMatrix([[1 + 3*I, 3-2*I],[0, 2*I]])
205
+ assert im(A) == ImmutableMatrix([[3, -2],[0, 2]])
206
+
207
+ X = ImmutableSparseMatrix(
208
+ [[i*I + i for i in range(5)] for i in range(5)])
209
+ Y = SparseMatrix([list(range(5)) for i in range(5)])
210
+ assert im(X).as_immutable() == Y
211
+
212
+ X = FunctionMatrix(3, 3, Lambda((n, m), n + m*I))
213
+ assert im(X) == Matrix([[0, 1, 2], [0, 1, 2], [0, 1, 2]])
214
+
215
+ def test_sign():
216
+ assert sign(1.2) == 1
217
+ assert sign(-1.2) == -1
218
+ assert sign(3*I) == I
219
+ assert sign(-3*I) == -I
220
+ assert sign(0) == 0
221
+ assert sign(0, evaluate=False).doit() == 0
222
+ assert sign(oo, evaluate=False).doit() == 1
223
+ assert sign(nan) is nan
224
+ assert sign(2 + 2*I).doit() == sqrt(2)*(2 + 2*I)/4
225
+ assert sign(2 + 3*I).simplify() == sign(2 + 3*I)
226
+ assert sign(2 + 2*I).simplify() == sign(1 + I)
227
+ assert sign(im(sqrt(1 - sqrt(3)))) == 1
228
+ assert sign(sqrt(1 - sqrt(3))) == I
229
+
230
+ x = Symbol('x')
231
+ assert sign(x).is_finite is True
232
+ assert sign(x).is_complex is True
233
+ assert sign(x).is_imaginary is None
234
+ assert sign(x).is_integer is None
235
+ assert sign(x).is_real is None
236
+ assert sign(x).is_zero is None
237
+ assert sign(x).doit() == sign(x)
238
+ assert sign(1.2*x) == sign(x)
239
+ assert sign(2*x) == sign(x)
240
+ assert sign(I*x) == I*sign(x)
241
+ assert sign(-2*I*x) == -I*sign(x)
242
+ assert sign(conjugate(x)) == conjugate(sign(x))
243
+
244
+ p = Symbol('p', positive=True)
245
+ n = Symbol('n', negative=True)
246
+ m = Symbol('m', negative=True)
247
+ assert sign(2*p*x) == sign(x)
248
+ assert sign(n*x) == -sign(x)
249
+ assert sign(n*m*x) == sign(x)
250
+
251
+ x = Symbol('x', imaginary=True)
252
+ assert sign(x).is_imaginary is True
253
+ assert sign(x).is_integer is False
254
+ assert sign(x).is_real is False
255
+ assert sign(x).is_zero is False
256
+ assert sign(x).diff(x) == 2*DiracDelta(-I*x)
257
+ assert sign(x).doit() == x / Abs(x)
258
+ assert conjugate(sign(x)) == -sign(x)
259
+
260
+ x = Symbol('x', real=True)
261
+ assert sign(x).is_imaginary is False
262
+ assert sign(x).is_integer is True
263
+ assert sign(x).is_real is True
264
+ assert sign(x).is_zero is None
265
+ assert sign(x).diff(x) == 2*DiracDelta(x)
266
+ assert sign(x).doit() == sign(x)
267
+ assert conjugate(sign(x)) == sign(x)
268
+
269
+ x = Symbol('x', nonzero=True)
270
+ assert sign(x).is_imaginary is False
271
+ assert sign(x).is_integer is True
272
+ assert sign(x).is_real is True
273
+ assert sign(x).is_zero is False
274
+ assert sign(x).doit() == x / Abs(x)
275
+ assert sign(Abs(x)) == 1
276
+ assert Abs(sign(x)) == 1
277
+
278
+ x = Symbol('x', positive=True)
279
+ assert sign(x).is_imaginary is False
280
+ assert sign(x).is_integer is True
281
+ assert sign(x).is_real is True
282
+ assert sign(x).is_zero is False
283
+ assert sign(x).doit() == x / Abs(x)
284
+ assert sign(Abs(x)) == 1
285
+ assert Abs(sign(x)) == 1
286
+
287
+ x = 0
288
+ assert sign(x).is_imaginary is False
289
+ assert sign(x).is_integer is True
290
+ assert sign(x).is_real is True
291
+ assert sign(x).is_zero is True
292
+ assert sign(x).doit() == 0
293
+ assert sign(Abs(x)) == 0
294
+ assert Abs(sign(x)) == 0
295
+
296
+ nz = Symbol('nz', nonzero=True, integer=True)
297
+ assert sign(nz).is_imaginary is False
298
+ assert sign(nz).is_integer is True
299
+ assert sign(nz).is_real is True
300
+ assert sign(nz).is_zero is False
301
+ assert sign(nz)**2 == 1
302
+ assert (sign(nz)**3).args == (sign(nz), 3)
303
+
304
+ assert sign(Symbol('x', nonnegative=True)).is_nonnegative
305
+ assert sign(Symbol('x', nonnegative=True)).is_nonpositive is None
306
+ assert sign(Symbol('x', nonpositive=True)).is_nonnegative is None
307
+ assert sign(Symbol('x', nonpositive=True)).is_nonpositive
308
+ assert sign(Symbol('x', real=True)).is_nonnegative is None
309
+ assert sign(Symbol('x', real=True)).is_nonpositive is None
310
+ assert sign(Symbol('x', real=True, zero=False)).is_nonpositive is None
311
+
312
+ x, y = Symbol('x', real=True), Symbol('y')
313
+ f = Function('f')
314
+ assert sign(x).rewrite(Piecewise) == \
315
+ Piecewise((1, x > 0), (-1, x < 0), (0, True))
316
+ assert sign(y).rewrite(Piecewise) == sign(y)
317
+ assert sign(x).rewrite(Heaviside) == 2*Heaviside(x, H0=S(1)/2) - 1
318
+ assert sign(y).rewrite(Heaviside) == sign(y)
319
+ assert sign(y).rewrite(Abs) == Piecewise((0, Eq(y, 0)), (y/Abs(y), True))
320
+ assert sign(f(y)).rewrite(Abs) == Piecewise((0, Eq(f(y), 0)), (f(y)/Abs(f(y)), True))
321
+
322
+ # evaluate what can be evaluated
323
+ assert sign(exp_polar(I*pi)*pi) is S.NegativeOne
324
+
325
+ eq = -sqrt(10 + 6*sqrt(3)) + sqrt(1 + sqrt(3)) + sqrt(3 + 3*sqrt(3))
326
+ # if there is a fast way to know when and when you cannot prove an
327
+ # expression like this is zero then the equality to zero is ok
328
+ assert sign(eq).func is sign or sign(eq) == 0
329
+ # but sometimes it's hard to do this so it's better not to load
330
+ # abs down with tests that will be very slow
331
+ q = 1 + sqrt(2) - 2*sqrt(3) + 1331*sqrt(6)
332
+ p = expand(q**3)**Rational(1, 3)
333
+ d = p - q
334
+ assert sign(d).func is sign or sign(d) == 0
335
+
336
+
337
+ def test_as_real_imag():
338
+ n = pi**1000
339
+ # the special code for working out the real
340
+ # and complex parts of a power with Integer exponent
341
+ # should not run if there is no imaginary part, hence
342
+ # this should not hang
343
+ assert n.as_real_imag() == (n, 0)
344
+
345
+ # issue 6261
346
+ x = Symbol('x')
347
+ assert sqrt(x).as_real_imag() == \
348
+ ((re(x)**2 + im(x)**2)**Rational(1, 4)*cos(atan2(im(x), re(x))/2),
349
+ (re(x)**2 + im(x)**2)**Rational(1, 4)*sin(atan2(im(x), re(x))/2))
350
+
351
+ # issue 3853
352
+ a, b = symbols('a,b', real=True)
353
+ assert ((1 + sqrt(a + b*I))/2).as_real_imag() == \
354
+ (
355
+ (a**2 + b**2)**Rational(
356
+ 1, 4)*cos(atan2(b, a)/2)/2 + S.Half,
357
+ (a**2 + b**2)**Rational(1, 4)*sin(atan2(b, a)/2)/2)
358
+
359
+ assert sqrt(a**2).as_real_imag() == (sqrt(a**2), 0)
360
+ i = symbols('i', imaginary=True)
361
+ assert sqrt(i**2).as_real_imag() == (0, abs(i))
362
+
363
+ assert ((1 + I)/(1 - I)).as_real_imag() == (0, 1)
364
+ assert ((1 + I)**3/(1 - I)).as_real_imag() == (-2, 0)
365
+
366
+
367
+ @XFAIL
368
+ def test_sign_issue_3068():
369
+ n = pi**1000
370
+ i = int(n)
371
+ x = Symbol('x')
372
+ assert (n - i).round() == 1 # doesn't hang
373
+ assert sign(n - i) == 1
374
+ # perhaps it's not possible to get the sign right when
375
+ # only 1 digit is being requested for this situation;
376
+ # 2 digits works
377
+ assert (n - x).n(1, subs={x: i}) > 0
378
+ assert (n - x).n(2, subs={x: i}) > 0
379
+
380
+
381
+ def test_Abs():
382
+ raises(TypeError, lambda: Abs(Interval(2, 3))) # issue 8717
383
+
384
+ x, y = symbols('x,y')
385
+ assert sign(sign(x)) == sign(x)
386
+ assert sign(x*y).func is sign
387
+ assert Abs(0) == 0
388
+ assert Abs(1) == 1
389
+ assert Abs(-1) == 1
390
+ assert Abs(I) == 1
391
+ assert Abs(-I) == 1
392
+ assert Abs(nan) is nan
393
+ assert Abs(zoo) is oo
394
+ assert Abs(I * pi) == pi
395
+ assert Abs(-I * pi) == pi
396
+ assert Abs(I * x) == Abs(x)
397
+ assert Abs(-I * x) == Abs(x)
398
+ assert Abs(-2*x) == 2*Abs(x)
399
+ assert Abs(-2.0*x) == 2.0*Abs(x)
400
+ assert Abs(2*pi*x*y) == 2*pi*Abs(x*y)
401
+ assert Abs(conjugate(x)) == Abs(x)
402
+ assert conjugate(Abs(x)) == Abs(x)
403
+ assert Abs(x).expand(complex=True) == sqrt(re(x)**2 + im(x)**2)
404
+
405
+ a = Symbol('a', positive=True)
406
+ assert Abs(2*pi*x*a) == 2*pi*a*Abs(x)
407
+ assert Abs(2*pi*I*x*a) == 2*pi*a*Abs(x)
408
+
409
+ x = Symbol('x', real=True)
410
+ n = Symbol('n', integer=True)
411
+ assert Abs((-1)**n) == 1
412
+ assert x**(2*n) == Abs(x)**(2*n)
413
+ assert Abs(x).diff(x) == sign(x)
414
+ assert abs(x) == Abs(x) # Python built-in
415
+ assert Abs(x)**3 == x**2*Abs(x)
416
+ assert Abs(x)**4 == x**4
417
+ assert (
418
+ Abs(x)**(3*n)).args == (Abs(x), 3*n) # leave symbolic odd unchanged
419
+ assert (1/Abs(x)).args == (Abs(x), -1)
420
+ assert 1/Abs(x)**3 == 1/(x**2*Abs(x))
421
+ assert Abs(x)**-3 == Abs(x)/(x**4)
422
+ assert Abs(x**3) == x**2*Abs(x)
423
+ assert Abs(I**I) == exp(-pi/2)
424
+ assert Abs((4 + 5*I)**(6 + 7*I)) == 68921*exp(-7*atan(Rational(5, 4)))
425
+ y = Symbol('y', real=True)
426
+ assert Abs(I**y) == 1
427
+ y = Symbol('y')
428
+ assert Abs(I**y) == exp(-pi*im(y)/2)
429
+
430
+ x = Symbol('x', imaginary=True)
431
+ assert Abs(x).diff(x) == -sign(x)
432
+
433
+ eq = -sqrt(10 + 6*sqrt(3)) + sqrt(1 + sqrt(3)) + sqrt(3 + 3*sqrt(3))
434
+ # if there is a fast way to know when you can and when you cannot prove an
435
+ # expression like this is zero then the equality to zero is ok
436
+ assert abs(eq).func is Abs or abs(eq) == 0
437
+ # but sometimes it's hard to do this so it's better not to load
438
+ # abs down with tests that will be very slow
439
+ q = 1 + sqrt(2) - 2*sqrt(3) + 1331*sqrt(6)
440
+ p = expand(q**3)**Rational(1, 3)
441
+ d = p - q
442
+ assert abs(d).func is Abs or abs(d) == 0
443
+
444
+ assert Abs(4*exp(pi*I/4)) == 4
445
+ assert Abs(3**(2 + I)) == 9
446
+ assert Abs((-3)**(1 - I)) == 3*exp(pi)
447
+
448
+ assert Abs(oo) is oo
449
+ assert Abs(-oo) is oo
450
+ assert Abs(oo + I) is oo
451
+ assert Abs(oo + I*oo) is oo
452
+
453
+ a = Symbol('a', algebraic=True)
454
+ t = Symbol('t', transcendental=True)
455
+ x = Symbol('x')
456
+ assert re(a).is_algebraic
457
+ assert re(x).is_algebraic is None
458
+ assert re(t).is_algebraic is False
459
+ assert Abs(x).fdiff() == sign(x)
460
+ raises(ArgumentIndexError, lambda: Abs(x).fdiff(2))
461
+
462
+ # doesn't have recursion error
463
+ arg = sqrt(acos(1 - I)*acos(1 + I))
464
+ assert abs(arg) == arg
465
+
466
+ # special handling to put Abs in denom
467
+ assert abs(1/x) == 1/Abs(x)
468
+ e = abs(2/x**2)
469
+ assert e.is_Mul and e == 2/Abs(x**2)
470
+ assert unchanged(Abs, y/x)
471
+ assert unchanged(Abs, x/(x + 1))
472
+ assert unchanged(Abs, x*y)
473
+ p = Symbol('p', positive=True)
474
+ assert abs(x/p) == abs(x)/p
475
+
476
+ # coverage
477
+ assert unchanged(Abs, Symbol('x', real=True)**y)
478
+ # issue 19627
479
+ f = Function('f', positive=True)
480
+ assert sqrt(f(x)**2) == f(x)
481
+ # issue 21625
482
+ assert unchanged(Abs, S("im(acos(-i + acosh(-g + i)))"))
483
+
484
+
485
+ def test_Abs_rewrite():
486
+ x = Symbol('x', real=True)
487
+ a = Abs(x).rewrite(Heaviside).expand()
488
+ assert a == x*Heaviside(x) - x*Heaviside(-x)
489
+ for i in [-2, -1, 0, 1, 2]:
490
+ assert a.subs(x, i) == abs(i)
491
+ y = Symbol('y')
492
+ assert Abs(y).rewrite(Heaviside) == Abs(y)
493
+
494
+ x, y = Symbol('x', real=True), Symbol('y')
495
+ assert Abs(x).rewrite(Piecewise) == Piecewise((x, x >= 0), (-x, True))
496
+ assert Abs(y).rewrite(Piecewise) == Abs(y)
497
+ assert Abs(y).rewrite(sign) == y/sign(y)
498
+
499
+ i = Symbol('i', imaginary=True)
500
+ assert abs(i).rewrite(Piecewise) == Piecewise((I*i, I*i >= 0), (-I*i, True))
501
+
502
+
503
+ assert Abs(y).rewrite(conjugate) == sqrt(y*conjugate(y))
504
+ assert Abs(i).rewrite(conjugate) == sqrt(-i**2) # == -I*i
505
+
506
+ y = Symbol('y', extended_real=True)
507
+ assert (Abs(exp(-I*x)-exp(-I*y))**2).rewrite(conjugate) == \
508
+ -exp(I*x)*exp(-I*y) + 2 - exp(-I*x)*exp(I*y)
509
+
510
+
511
+ def test_Abs_real():
512
+ # test some properties of abs that only apply
513
+ # to real numbers
514
+ x = Symbol('x', complex=True)
515
+ assert sqrt(x**2) != Abs(x)
516
+ assert Abs(x**2) != x**2
517
+
518
+ x = Symbol('x', real=True)
519
+ assert sqrt(x**2) == Abs(x)
520
+ assert Abs(x**2) == x**2
521
+
522
+ # if the symbol is zero, the following will still apply
523
+ nn = Symbol('nn', nonnegative=True, real=True)
524
+ np = Symbol('np', nonpositive=True, real=True)
525
+ assert Abs(nn) == nn
526
+ assert Abs(np) == -np
527
+
528
+
529
+ def test_Abs_properties():
530
+ x = Symbol('x')
531
+ assert Abs(x).is_real is None
532
+ assert Abs(x).is_extended_real is True
533
+ assert Abs(x).is_rational is None
534
+ assert Abs(x).is_positive is None
535
+ assert Abs(x).is_nonnegative is None
536
+ assert Abs(x).is_extended_positive is None
537
+ assert Abs(x).is_extended_nonnegative is True
538
+
539
+ f = Symbol('x', finite=True)
540
+ assert Abs(f).is_real is True
541
+ assert Abs(f).is_extended_real is True
542
+ assert Abs(f).is_rational is None
543
+ assert Abs(f).is_positive is None
544
+ assert Abs(f).is_nonnegative is True
545
+ assert Abs(f).is_extended_positive is None
546
+ assert Abs(f).is_extended_nonnegative is True
547
+
548
+ z = Symbol('z', complex=True, zero=False)
549
+ assert Abs(z).is_real is True # since complex implies finite
550
+ assert Abs(z).is_extended_real is True
551
+ assert Abs(z).is_rational is None
552
+ assert Abs(z).is_positive is True
553
+ assert Abs(z).is_extended_positive is True
554
+ assert Abs(z).is_zero is False
555
+
556
+ p = Symbol('p', positive=True)
557
+ assert Abs(p).is_real is True
558
+ assert Abs(p).is_extended_real is True
559
+ assert Abs(p).is_rational is None
560
+ assert Abs(p).is_positive is True
561
+ assert Abs(p).is_zero is False
562
+
563
+ q = Symbol('q', rational=True)
564
+ assert Abs(q).is_real is True
565
+ assert Abs(q).is_rational is True
566
+ assert Abs(q).is_integer is None
567
+ assert Abs(q).is_positive is None
568
+ assert Abs(q).is_nonnegative is True
569
+
570
+ i = Symbol('i', integer=True)
571
+ assert Abs(i).is_real is True
572
+ assert Abs(i).is_integer is True
573
+ assert Abs(i).is_positive is None
574
+ assert Abs(i).is_nonnegative is True
575
+
576
+ e = Symbol('n', even=True)
577
+ ne = Symbol('ne', real=True, even=False)
578
+ assert Abs(e).is_even is True
579
+ assert Abs(ne).is_even is False
580
+ assert Abs(i).is_even is None
581
+
582
+ o = Symbol('n', odd=True)
583
+ no = Symbol('no', real=True, odd=False)
584
+ assert Abs(o).is_odd is True
585
+ assert Abs(no).is_odd is False
586
+ assert Abs(i).is_odd is None
587
+
588
+
589
+ def test_abs():
590
+ # this tests that abs calls Abs; don't rename to
591
+ # test_Abs since that test is already above
592
+ a = Symbol('a', positive=True)
593
+ assert abs(I*(1 + a)**2) == (1 + a)**2
594
+
595
+
596
+ def test_arg():
597
+ assert arg(0) is nan
598
+ assert arg(1) == 0
599
+ assert arg(-1) == pi
600
+ assert arg(I) == pi/2
601
+ assert arg(-I) == -pi/2
602
+ assert arg(1 + I) == pi/4
603
+ assert arg(-1 + I) == pi*Rational(3, 4)
604
+ assert arg(1 - I) == -pi/4
605
+ assert arg(exp_polar(4*pi*I)) == 4*pi
606
+ assert arg(exp_polar(-7*pi*I)) == -7*pi
607
+ assert arg(exp_polar(5 - 3*pi*I/4)) == pi*Rational(-3, 4)
608
+ f = Function('f')
609
+ assert not arg(f(0) + I*f(1)).atoms(re)
610
+
611
+ # check nesting
612
+ x = Symbol('x')
613
+ assert arg(arg(arg(x))) is not S.NaN
614
+ assert arg(arg(arg(arg(x)))) is S.NaN
615
+ r = Symbol('r', extended_real=True)
616
+ assert arg(arg(r)) is not S.NaN
617
+ assert arg(arg(arg(r))) is S.NaN
618
+
619
+ p = Function('p', extended_positive=True)
620
+ assert arg(p(x)) == 0
621
+ assert arg((3 + I)*p(x)) == arg(3 + I)
622
+
623
+ p = Symbol('p', positive=True)
624
+ assert arg(p) == 0
625
+ assert arg(p*I) == pi/2
626
+
627
+ n = Symbol('n', negative=True)
628
+ assert arg(n) == pi
629
+ assert arg(n*I) == -pi/2
630
+
631
+ x = Symbol('x')
632
+ assert conjugate(arg(x)) == arg(x)
633
+
634
+ e = p + I*p**2
635
+ assert arg(e) == arg(1 + p*I)
636
+ # make sure sign doesn't swap
637
+ e = -2*p + 4*I*p**2
638
+ assert arg(e) == arg(-1 + 2*p*I)
639
+ # make sure sign isn't lost
640
+ x = symbols('x', real=True) # could be zero
641
+ e = x + I*x
642
+ assert arg(e) == arg(x*(1 + I))
643
+ assert arg(e/p) == arg(x*(1 + I))
644
+ e = p*cos(p) + I*log(p)*exp(p)
645
+ assert arg(e).args[0] == e
646
+ # keep it simple -- let the user do more advanced cancellation
647
+ e = (p + 1) + I*(p**2 - 1)
648
+ assert arg(e).args[0] == e
649
+
650
+ f = Function('f')
651
+ e = 2*x*(f(0) - 1) - 2*x*f(0)
652
+ assert arg(e) == arg(-2*x)
653
+ assert arg(f(0)).func == arg and arg(f(0)).args == (f(0),)
654
+
655
+
656
+ def test_arg_rewrite():
657
+ assert arg(1 + I) == atan2(1, 1)
658
+
659
+ x = Symbol('x', real=True)
660
+ y = Symbol('y', real=True)
661
+ assert arg(x + I*y).rewrite(atan2) == atan2(y, x)
662
+
663
+
664
+ def test_adjoint():
665
+ a = Symbol('a', antihermitian=True)
666
+ b = Symbol('b', hermitian=True)
667
+ assert adjoint(a) == -a
668
+ assert adjoint(I*a) == I*a
669
+ assert adjoint(b) == b
670
+ assert adjoint(I*b) == -I*b
671
+ assert adjoint(a*b) == -b*a
672
+ assert adjoint(I*a*b) == I*b*a
673
+
674
+ x, y = symbols('x y')
675
+ assert adjoint(adjoint(x)) == x
676
+ assert adjoint(x + y) == adjoint(x) + adjoint(y)
677
+ assert adjoint(x - y) == adjoint(x) - adjoint(y)
678
+ assert adjoint(x * y) == adjoint(x) * adjoint(y)
679
+ assert adjoint(x / y) == adjoint(x) / adjoint(y)
680
+ assert adjoint(-x) == -adjoint(x)
681
+
682
+ x, y = symbols('x y', commutative=False)
683
+ assert adjoint(adjoint(x)) == x
684
+ assert adjoint(x + y) == adjoint(x) + adjoint(y)
685
+ assert adjoint(x - y) == adjoint(x) - adjoint(y)
686
+ assert adjoint(x * y) == adjoint(y) * adjoint(x)
687
+ assert adjoint(x / y) == 1 / adjoint(y) * adjoint(x)
688
+ assert adjoint(-x) == -adjoint(x)
689
+
690
+
691
+ def test_conjugate():
692
+ a = Symbol('a', real=True)
693
+ b = Symbol('b', imaginary=True)
694
+ assert conjugate(a) == a
695
+ assert conjugate(I*a) == -I*a
696
+ assert conjugate(b) == -b
697
+ assert conjugate(I*b) == I*b
698
+ assert conjugate(a*b) == -a*b
699
+ assert conjugate(I*a*b) == I*a*b
700
+
701
+ x, y = symbols('x y')
702
+ assert conjugate(conjugate(x)) == x
703
+ assert conjugate(x).inverse() == conjugate
704
+ assert conjugate(x + y) == conjugate(x) + conjugate(y)
705
+ assert conjugate(x - y) == conjugate(x) - conjugate(y)
706
+ assert conjugate(x * y) == conjugate(x) * conjugate(y)
707
+ assert conjugate(x / y) == conjugate(x) / conjugate(y)
708
+ assert conjugate(-x) == -conjugate(x)
709
+
710
+ a = Symbol('a', algebraic=True)
711
+ t = Symbol('t', transcendental=True)
712
+ assert re(a).is_algebraic
713
+ assert re(x).is_algebraic is None
714
+ assert re(t).is_algebraic is False
715
+
716
+
717
+ def test_conjugate_transpose():
718
+ x = Symbol('x')
719
+ assert conjugate(transpose(x)) == adjoint(x)
720
+ assert transpose(conjugate(x)) == adjoint(x)
721
+ assert adjoint(transpose(x)) == conjugate(x)
722
+ assert transpose(adjoint(x)) == conjugate(x)
723
+ assert adjoint(conjugate(x)) == transpose(x)
724
+ assert conjugate(adjoint(x)) == transpose(x)
725
+
726
+ class Symmetric(Expr):
727
+ def _eval_adjoint(self):
728
+ return None
729
+
730
+ def _eval_conjugate(self):
731
+ return None
732
+
733
+ def _eval_transpose(self):
734
+ return self
735
+ x = Symmetric()
736
+ assert conjugate(x) == adjoint(x)
737
+ assert transpose(x) == x
738
+
739
+
740
+ def test_transpose():
741
+ a = Symbol('a', complex=True)
742
+ assert transpose(a) == a
743
+ assert transpose(I*a) == I*a
744
+
745
+ x, y = symbols('x y')
746
+ assert transpose(transpose(x)) == x
747
+ assert transpose(x + y) == transpose(x) + transpose(y)
748
+ assert transpose(x - y) == transpose(x) - transpose(y)
749
+ assert transpose(x * y) == transpose(x) * transpose(y)
750
+ assert transpose(x / y) == transpose(x) / transpose(y)
751
+ assert transpose(-x) == -transpose(x)
752
+
753
+ x, y = symbols('x y', commutative=False)
754
+ assert transpose(transpose(x)) == x
755
+ assert transpose(x + y) == transpose(x) + transpose(y)
756
+ assert transpose(x - y) == transpose(x) - transpose(y)
757
+ assert transpose(x * y) == transpose(y) * transpose(x)
758
+ assert transpose(x / y) == 1 / transpose(y) * transpose(x)
759
+ assert transpose(-x) == -transpose(x)
760
+
761
+
762
+ @_both_exp_pow
763
+ def test_polarify():
764
+ from sympy.functions.elementary.complexes import (polar_lift, polarify)
765
+ x = Symbol('x')
766
+ z = Symbol('z', polar=True)
767
+ f = Function('f')
768
+ ES = {}
769
+
770
+ assert polarify(-1) == (polar_lift(-1), ES)
771
+ assert polarify(1 + I) == (polar_lift(1 + I), ES)
772
+
773
+ assert polarify(exp(x), subs=False) == exp(x)
774
+ assert polarify(1 + x, subs=False) == 1 + x
775
+ assert polarify(f(I) + x, subs=False) == f(polar_lift(I)) + x
776
+
777
+ assert polarify(x, lift=True) == polar_lift(x)
778
+ assert polarify(z, lift=True) == z
779
+ assert polarify(f(x), lift=True) == f(polar_lift(x))
780
+ assert polarify(1 + x, lift=True) == polar_lift(1 + x)
781
+ assert polarify(1 + f(x), lift=True) == polar_lift(1 + f(polar_lift(x)))
782
+
783
+ newex, subs = polarify(f(x) + z)
784
+ assert newex.subs(subs) == f(x) + z
785
+
786
+ mu = Symbol("mu")
787
+ sigma = Symbol("sigma", positive=True)
788
+
789
+ # Make sure polarify(lift=True) doesn't try to lift the integration
790
+ # variable
791
+ assert polarify(
792
+ Integral(sqrt(2)*x*exp(-(-mu + x)**2/(2*sigma**2))/(2*sqrt(pi)*sigma),
793
+ (x, -oo, oo)), lift=True) == Integral(sqrt(2)*(sigma*exp_polar(0))**exp_polar(I*pi)*
794
+ exp((sigma*exp_polar(0))**(2*exp_polar(I*pi))*exp_polar(I*pi)*polar_lift(-mu + x)**
795
+ (2*exp_polar(0))/2)*exp_polar(0)*polar_lift(x)/(2*sqrt(pi)), (x, -oo, oo))
796
+
797
+
798
+ def test_unpolarify():
799
+ from sympy.functions.elementary.complexes import (polar_lift, principal_branch, unpolarify)
800
+ from sympy.core.relational import Ne
801
+ from sympy.functions.elementary.hyperbolic import tanh
802
+ from sympy.functions.special.error_functions import erf
803
+ from sympy.functions.special.gamma_functions import (gamma, uppergamma)
804
+ from sympy.abc import x
805
+ p = exp_polar(7*I) + 1
806
+ u = exp(7*I) + 1
807
+
808
+ assert unpolarify(1) == 1
809
+ assert unpolarify(p) == u
810
+ assert unpolarify(p**2) == u**2
811
+ assert unpolarify(p**x) == p**x
812
+ assert unpolarify(p*x) == u*x
813
+ assert unpolarify(p + x) == u + x
814
+ assert unpolarify(sqrt(sin(p))) == sqrt(sin(u))
815
+
816
+ # Test reduction to principal branch 2*pi.
817
+ t = principal_branch(x, 2*pi)
818
+ assert unpolarify(t) == x
819
+ assert unpolarify(sqrt(t)) == sqrt(t)
820
+
821
+ # Test exponents_only.
822
+ assert unpolarify(p**p, exponents_only=True) == p**u
823
+ assert unpolarify(uppergamma(x, p**p)) == uppergamma(x, p**u)
824
+
825
+ # Test functions.
826
+ assert unpolarify(sin(p)) == sin(u)
827
+ assert unpolarify(tanh(p)) == tanh(u)
828
+ assert unpolarify(gamma(p)) == gamma(u)
829
+ assert unpolarify(erf(p)) == erf(u)
830
+ assert unpolarify(uppergamma(x, p)) == uppergamma(x, p)
831
+
832
+ assert unpolarify(uppergamma(sin(p), sin(p + exp_polar(0)))) == \
833
+ uppergamma(sin(u), sin(u + 1))
834
+ assert unpolarify(uppergamma(polar_lift(0), 2*exp_polar(0))) == \
835
+ uppergamma(0, 2)
836
+
837
+ assert unpolarify(Eq(p, 0)) == Eq(u, 0)
838
+ assert unpolarify(Ne(p, 0)) == Ne(u, 0)
839
+ assert unpolarify(polar_lift(x) > 0) == (x > 0)
840
+
841
+ # Test bools
842
+ assert unpolarify(True) is True
843
+
844
+
845
+ def test_issue_4035():
846
+ x = Symbol('x')
847
+ assert Abs(x).expand(trig=True) == Abs(x)
848
+ assert sign(x).expand(trig=True) == sign(x)
849
+ assert arg(x).expand(trig=True) == arg(x)
850
+
851
+
852
+ def test_issue_3206():
853
+ x = Symbol('x')
854
+ assert Abs(Abs(x)) == Abs(x)
855
+
856
+
857
+ def test_issue_4754_derivative_conjugate():
858
+ x = Symbol('x', real=True)
859
+ y = Symbol('y', imaginary=True)
860
+ f = Function('f')
861
+ assert (f(x).conjugate()).diff(x) == (f(x).diff(x)).conjugate()
862
+ assert (f(y).conjugate()).diff(y) == -(f(y).diff(y)).conjugate()
863
+
864
+
865
+ def test_derivatives_issue_4757():
866
+ x = Symbol('x', real=True)
867
+ y = Symbol('y', imaginary=True)
868
+ f = Function('f')
869
+ assert re(f(x)).diff(x) == re(f(x).diff(x))
870
+ assert im(f(x)).diff(x) == im(f(x).diff(x))
871
+ assert re(f(y)).diff(y) == -I*im(f(y).diff(y))
872
+ assert im(f(y)).diff(y) == -I*re(f(y).diff(y))
873
+ assert Abs(f(x)).diff(x).subs(f(x), 1 + I*x).doit() == x/sqrt(1 + x**2)
874
+ assert arg(f(x)).diff(x).subs(f(x), 1 + I*x**2).doit() == 2*x/(1 + x**4)
875
+ assert Abs(f(y)).diff(y).subs(f(y), 1 + y).doit() == -y/sqrt(1 - y**2)
876
+ assert arg(f(y)).diff(y).subs(f(y), I + y**2).doit() == 2*y/(1 + y**4)
877
+
878
+
879
+ def test_issue_11413():
880
+ from sympy.simplify.simplify import simplify
881
+ v0 = Symbol('v0')
882
+ v1 = Symbol('v1')
883
+ v2 = Symbol('v2')
884
+ V = Matrix([[v0],[v1],[v2]])
885
+ U = V.normalized()
886
+ assert U == Matrix([
887
+ [v0/sqrt(Abs(v0)**2 + Abs(v1)**2 + Abs(v2)**2)],
888
+ [v1/sqrt(Abs(v0)**2 + Abs(v1)**2 + Abs(v2)**2)],
889
+ [v2/sqrt(Abs(v0)**2 + Abs(v1)**2 + Abs(v2)**2)]])
890
+ U.norm = sqrt(v0**2/(v0**2 + v1**2 + v2**2) + v1**2/(v0**2 + v1**2 + v2**2) + v2**2/(v0**2 + v1**2 + v2**2))
891
+ assert simplify(U.norm) == 1
892
+
893
+
894
+ def test_periodic_argument():
895
+ from sympy.functions.elementary.complexes import (periodic_argument, polar_lift, principal_branch, unbranched_argument)
896
+ x = Symbol('x')
897
+ p = Symbol('p', positive=True)
898
+
899
+ assert unbranched_argument(2 + I) == periodic_argument(2 + I, oo)
900
+ assert unbranched_argument(1 + x) == periodic_argument(1 + x, oo)
901
+ assert N_equals(unbranched_argument((1 + I)**2), pi/2)
902
+ assert N_equals(unbranched_argument((1 - I)**2), -pi/2)
903
+ assert N_equals(periodic_argument((1 + I)**2, 3*pi), pi/2)
904
+ assert N_equals(periodic_argument((1 - I)**2, 3*pi), -pi/2)
905
+
906
+ assert unbranched_argument(principal_branch(x, pi)) == \
907
+ periodic_argument(x, pi)
908
+
909
+ assert unbranched_argument(polar_lift(2 + I)) == unbranched_argument(2 + I)
910
+ assert periodic_argument(polar_lift(2 + I), 2*pi) == \
911
+ periodic_argument(2 + I, 2*pi)
912
+ assert periodic_argument(polar_lift(2 + I), 3*pi) == \
913
+ periodic_argument(2 + I, 3*pi)
914
+ assert periodic_argument(polar_lift(2 + I), pi) == \
915
+ periodic_argument(polar_lift(2 + I), pi)
916
+
917
+ assert unbranched_argument(polar_lift(1 + I)) == pi/4
918
+ assert periodic_argument(2*p, p) == periodic_argument(p, p)
919
+ assert periodic_argument(pi*p, p) == periodic_argument(p, p)
920
+
921
+ assert Abs(polar_lift(1 + I)) == Abs(1 + I)
922
+
923
+
924
+ @XFAIL
925
+ def test_principal_branch_fail():
926
+ # TODO XXX why does abs(x)._eval_evalf() not fall back to global evalf?
927
+ from sympy.functions.elementary.complexes import principal_branch
928
+ assert N_equals(principal_branch((1 + I)**2, pi/2), 0)
929
+
930
+
931
+ def test_principal_branch():
932
+ from sympy.functions.elementary.complexes import (polar_lift, principal_branch)
933
+ p = Symbol('p', positive=True)
934
+ x = Symbol('x')
935
+ neg = Symbol('x', negative=True)
936
+
937
+ assert principal_branch(polar_lift(x), p) == principal_branch(x, p)
938
+ assert principal_branch(polar_lift(2 + I), p) == principal_branch(2 + I, p)
939
+ assert principal_branch(2*x, p) == 2*principal_branch(x, p)
940
+ assert principal_branch(1, pi) == exp_polar(0)
941
+ assert principal_branch(-1, 2*pi) == exp_polar(I*pi)
942
+ assert principal_branch(-1, pi) == exp_polar(0)
943
+ assert principal_branch(exp_polar(3*pi*I)*x, 2*pi) == \
944
+ principal_branch(exp_polar(I*pi)*x, 2*pi)
945
+ assert principal_branch(neg*exp_polar(pi*I), 2*pi) == neg*exp_polar(-I*pi)
946
+ # related to issue #14692
947
+ assert principal_branch(exp_polar(-I*pi/2)/polar_lift(neg), 2*pi) == \
948
+ exp_polar(-I*pi/2)/neg
949
+
950
+ assert N_equals(principal_branch((1 + I)**2, 2*pi), 2*I)
951
+ assert N_equals(principal_branch((1 + I)**2, 3*pi), 2*I)
952
+ assert N_equals(principal_branch((1 + I)**2, 1*pi), 2*I)
953
+
954
+ # test argument sanitization
955
+ assert principal_branch(x, I).func is principal_branch
956
+ assert principal_branch(x, -4).func is principal_branch
957
+ assert principal_branch(x, -oo).func is principal_branch
958
+ assert principal_branch(x, zoo).func is principal_branch
959
+
960
+
961
+ @XFAIL
962
+ def test_issue_6167_6151():
963
+ n = pi**1000
964
+ i = int(n)
965
+ assert sign(n - i) == 1
966
+ assert abs(n - i) == n - i
967
+ x = Symbol('x')
968
+ eps = pi**-1500
969
+ big = pi**1000
970
+ one = cos(x)**2 + sin(x)**2
971
+ e = big*one - big + eps
972
+ from sympy.simplify.simplify import simplify
973
+ assert sign(simplify(e)) == 1
974
+ for xi in (111, 11, 1, Rational(1, 10)):
975
+ assert sign(e.subs(x, xi)) == 1
976
+
977
+
978
+ def test_issue_14216():
979
+ from sympy.functions.elementary.complexes import unpolarify
980
+ A = MatrixSymbol("A", 2, 2)
981
+ assert unpolarify(A[0, 0]) == A[0, 0]
982
+ assert unpolarify(A[0, 0]*A[1, 0]) == A[0, 0]*A[1, 0]
983
+
984
+
985
+ def test_issue_14238():
986
+ # doesn't cause recursion error
987
+ r = Symbol('r', real=True)
988
+ assert Abs(r + Piecewise((0, r > 0), (1 - r, True)))
989
+
990
+
991
+ def test_issue_22189():
992
+ x = Symbol('x')
993
+ for a in (sqrt(7 - 2*x) - 2, 1 - x):
994
+ assert Abs(a) - Abs(-a) == 0, a
995
+
996
+
997
+ def test_zero_assumptions():
998
+ nr = Symbol('nonreal', real=False, finite=True)
999
+ ni = Symbol('nonimaginary', imaginary=False)
1000
+ # imaginary implies not zero
1001
+ nzni = Symbol('nonzerononimaginary', zero=False, imaginary=False)
1002
+
1003
+ assert re(nr).is_zero is None
1004
+ assert im(nr).is_zero is False
1005
+
1006
+ assert re(ni).is_zero is None
1007
+ assert im(ni).is_zero is None
1008
+
1009
+ assert re(nzni).is_zero is False
1010
+ assert im(nzni).is_zero is None
1011
+
1012
+
1013
+ @_both_exp_pow
1014
+ def test_issue_15893():
1015
+ f = Function('f', real=True)
1016
+ x = Symbol('x', real=True)
1017
+ eq = Derivative(Abs(f(x)), f(x))
1018
+ assert eq.doit() == sign(f(x))
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_exponential.py ADDED
@@ -0,0 +1,806 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.assumptions.refine import refine
2
+ from sympy.calculus.accumulationbounds import AccumBounds
3
+ from sympy.concrete.products import Product
4
+ from sympy.concrete.summations import Sum
5
+ from sympy.core.function import expand_log
6
+ from sympy.core.numbers import (E, Float, I, Rational, nan, oo, pi, zoo)
7
+ from sympy.core.power import Pow
8
+ from sympy.core.singleton import S
9
+ from sympy.core.symbol import (Symbol, symbols)
10
+ from sympy.functions.elementary.complexes import (adjoint, conjugate, re, sign, transpose)
11
+ from sympy.functions.elementary.exponential import (LambertW, exp, exp_polar, log)
12
+ from sympy.functions.elementary.hyperbolic import (cosh, sinh, tanh)
13
+ from sympy.functions.elementary.miscellaneous import sqrt
14
+ from sympy.functions.elementary.trigonometric import (cos, sin, tan)
15
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
16
+ from sympy.polys.polytools import gcd
17
+ from sympy.series.order import O
18
+ from sympy.simplify.simplify import simplify
19
+ from sympy.core.parameters import global_parameters
20
+ from sympy.functions.elementary.exponential import match_real_imag
21
+ from sympy.abc import x, y, z
22
+ from sympy.core.expr import unchanged
23
+ from sympy.core.function import ArgumentIndexError
24
+ from sympy.testing.pytest import raises, XFAIL, _both_exp_pow
25
+
26
+
27
+ @_both_exp_pow
28
+ def test_exp_values():
29
+ if global_parameters.exp_is_pow:
30
+ assert type(exp(x)) is Pow
31
+ else:
32
+ assert type(exp(x)) is exp
33
+
34
+ k = Symbol('k', integer=True)
35
+
36
+ assert exp(nan) is nan
37
+
38
+ assert exp(oo) is oo
39
+ assert exp(-oo) == 0
40
+
41
+ assert exp(0) == 1
42
+ assert exp(1) == E
43
+ assert exp(-1 + x).as_base_exp() == (S.Exp1, x - 1)
44
+ assert exp(1 + x).as_base_exp() == (S.Exp1, x + 1)
45
+
46
+ assert exp(pi*I/2) == I
47
+ assert exp(pi*I) == -1
48
+ assert exp(pi*I*Rational(3, 2)) == -I
49
+ assert exp(2*pi*I) == 1
50
+
51
+ assert refine(exp(pi*I*2*k)) == 1
52
+ assert refine(exp(pi*I*2*(k + S.Half))) == -1
53
+ assert refine(exp(pi*I*2*(k + Rational(1, 4)))) == I
54
+ assert refine(exp(pi*I*2*(k + Rational(3, 4)))) == -I
55
+
56
+ assert exp(log(x)) == x
57
+ assert exp(2*log(x)) == x**2
58
+ assert exp(pi*log(x)) == x**pi
59
+
60
+ assert exp(17*log(x) + E*log(y)) == x**17 * y**E
61
+
62
+ assert exp(x*log(x)) != x**x
63
+ assert exp(sin(x)*log(x)) != x
64
+
65
+ assert exp(3*log(x) + oo*x) == exp(oo*x) * x**3
66
+ assert exp(4*log(x)*log(y) + 3*log(x)) == x**3 * exp(4*log(x)*log(y))
67
+
68
+ assert exp(-oo, evaluate=False).is_finite is True
69
+ assert exp(oo, evaluate=False).is_finite is False
70
+
71
+
72
+ @_both_exp_pow
73
+ def test_exp_period():
74
+ assert exp(I*pi*Rational(9, 4)) == exp(I*pi/4)
75
+ assert exp(I*pi*Rational(46, 18)) == exp(I*pi*Rational(5, 9))
76
+ assert exp(I*pi*Rational(25, 7)) == exp(I*pi*Rational(-3, 7))
77
+ assert exp(I*pi*Rational(-19, 3)) == exp(-I*pi/3)
78
+ assert exp(I*pi*Rational(37, 8)) - exp(I*pi*Rational(-11, 8)) == 0
79
+ assert exp(I*pi*Rational(-5, 3)) / exp(I*pi*Rational(11, 5)) * exp(I*pi*Rational(148, 15)) == 1
80
+
81
+ assert exp(2 - I*pi*Rational(17, 5)) == exp(2 + I*pi*Rational(3, 5))
82
+ assert exp(log(3) + I*pi*Rational(29, 9)) == 3 * exp(I*pi*Rational(-7, 9))
83
+
84
+ n = Symbol('n', integer=True)
85
+ e = Symbol('e', even=True)
86
+ assert exp(e*I*pi) == 1
87
+ assert exp((e + 1)*I*pi) == -1
88
+ assert exp((1 + 4*n)*I*pi/2) == I
89
+ assert exp((-1 + 4*n)*I*pi/2) == -I
90
+
91
+
92
+ @_both_exp_pow
93
+ def test_exp_log():
94
+ x = Symbol("x", real=True)
95
+ assert log(exp(x)) == x
96
+ assert exp(log(x)) == x
97
+
98
+ if not global_parameters.exp_is_pow:
99
+ assert log(x).inverse() == exp
100
+ assert exp(x).inverse() == log
101
+
102
+ y = Symbol("y", polar=True)
103
+ assert log(exp_polar(z)) == z
104
+ assert exp(log(y)) == y
105
+
106
+
107
+ @_both_exp_pow
108
+ def test_exp_expand():
109
+ e = exp(log(Rational(2))*(1 + x) - log(Rational(2))*x)
110
+ assert e.expand() == 2
111
+ assert exp(x + y) != exp(x)*exp(y)
112
+ assert exp(x + y).expand() == exp(x)*exp(y)
113
+
114
+
115
+ @_both_exp_pow
116
+ def test_exp__as_base_exp():
117
+ assert exp(x).as_base_exp() == (E, x)
118
+ assert exp(2*x).as_base_exp() == (E, 2*x)
119
+ assert exp(x*y).as_base_exp() == (E, x*y)
120
+ assert exp(-x).as_base_exp() == (E, -x)
121
+
122
+ # Pow( *expr.as_base_exp() ) == expr invariant should hold
123
+ assert E**x == exp(x)
124
+ assert E**(2*x) == exp(2*x)
125
+ assert E**(x*y) == exp(x*y)
126
+
127
+ assert exp(x).base is S.Exp1
128
+ assert exp(x).exp == x
129
+
130
+
131
+ @_both_exp_pow
132
+ def test_exp_infinity():
133
+ assert exp(I*y) != nan
134
+ assert refine(exp(I*oo)) is nan
135
+ assert refine(exp(-I*oo)) is nan
136
+ assert exp(y*I*oo) != nan
137
+ assert exp(zoo) is nan
138
+ x = Symbol('x', extended_real=True, finite=False)
139
+ assert exp(x).is_complex is None
140
+
141
+
142
+ @_both_exp_pow
143
+ def test_exp_subs():
144
+ x = Symbol('x')
145
+ e = (exp(3*log(x), evaluate=False)) # evaluates to x**3
146
+ assert e.subs(x**3, y**3) == e
147
+ assert e.subs(x**2, 5) == e
148
+ assert (x**3).subs(x**2, y) != y**Rational(3, 2)
149
+ assert exp(exp(x) + exp(x**2)).subs(exp(exp(x)), y) == y * exp(exp(x**2))
150
+ assert exp(x).subs(E, y) == y**x
151
+ x = symbols('x', real=True)
152
+ assert exp(5*x).subs(exp(7*x), y) == y**Rational(5, 7)
153
+ assert exp(2*x + 7).subs(exp(3*x), y) == y**Rational(2, 3) * exp(7)
154
+ x = symbols('x', positive=True)
155
+ assert exp(3*log(x)).subs(x**2, y) == y**Rational(3, 2)
156
+ # differentiate between E and exp
157
+ assert exp(exp(x + E)).subs(exp, 3) == 3**(3**(x + E))
158
+ assert exp(exp(x + E)).subs(exp, sin) == sin(sin(x + E))
159
+ assert exp(exp(x + E)).subs(E, 3) == 3**(3**(x + 3))
160
+ assert exp(3).subs(E, sin) == sin(3)
161
+
162
+
163
+ def test_exp_adjoint():
164
+ assert adjoint(exp(x)) == exp(adjoint(x))
165
+
166
+
167
+ def test_exp_conjugate():
168
+ assert conjugate(exp(x)) == exp(conjugate(x))
169
+
170
+
171
+ @_both_exp_pow
172
+ def test_exp_transpose():
173
+ assert transpose(exp(x)) == exp(transpose(x))
174
+
175
+
176
+ @_both_exp_pow
177
+ def test_exp_rewrite():
178
+ assert exp(x).rewrite(sin) == sinh(x) + cosh(x)
179
+ assert exp(x*I).rewrite(cos) == cos(x) + I*sin(x)
180
+ assert exp(1).rewrite(cos) == sinh(1) + cosh(1)
181
+ assert exp(1).rewrite(sin) == sinh(1) + cosh(1)
182
+ assert exp(1).rewrite(sin) == sinh(1) + cosh(1)
183
+ assert exp(x).rewrite(tanh) == (1 + tanh(x/2))/(1 - tanh(x/2))
184
+ assert exp(pi*I/4).rewrite(sqrt) == sqrt(2)/2 + sqrt(2)*I/2
185
+ assert exp(pi*I/3).rewrite(sqrt) == S.Half + sqrt(3)*I/2
186
+ if not global_parameters.exp_is_pow:
187
+ assert exp(x*log(y)).rewrite(Pow) == y**x
188
+ assert exp(log(x)*log(y)).rewrite(Pow) in [x**log(y), y**log(x)]
189
+ assert exp(log(log(x))*y).rewrite(Pow) == log(x)**y
190
+
191
+ n = Symbol('n', integer=True)
192
+
193
+ assert Sum((exp(pi*I/2)/2)**n, (n, 0, oo)).rewrite(sqrt).doit() == Rational(4, 5) + I*2/5
194
+ assert Sum((exp(pi*I/4)/2)**n, (n, 0, oo)).rewrite(sqrt).doit() == 1/(1 - sqrt(2)*(1 + I)/4)
195
+ assert (Sum((exp(pi*I/3)/2)**n, (n, 0, oo)).rewrite(sqrt).doit().cancel()
196
+ == 4*I/(sqrt(3) + 3*I))
197
+
198
+
199
+ @_both_exp_pow
200
+ def test_exp_leading_term():
201
+ assert exp(x).as_leading_term(x) == 1
202
+ assert exp(2 + x).as_leading_term(x) == exp(2)
203
+ assert exp((2*x + 3) / (x+1)).as_leading_term(x) == exp(3)
204
+
205
+ # The following tests are commented, since now SymPy returns the
206
+ # original function when the leading term in the series expansion does
207
+ # not exist.
208
+ # raises(NotImplementedError, lambda: exp(1/x).as_leading_term(x))
209
+ # raises(NotImplementedError, lambda: exp((x + 1) / x**2).as_leading_term(x))
210
+ # raises(NotImplementedError, lambda: exp(x + 1/x).as_leading_term(x))
211
+
212
+
213
+ @_both_exp_pow
214
+ def test_exp_taylor_term():
215
+ x = symbols('x')
216
+ assert exp(x).taylor_term(1, x) == x
217
+ assert exp(x).taylor_term(3, x) == x**3/6
218
+ assert exp(x).taylor_term(4, x) == x**4/24
219
+ assert exp(x).taylor_term(-1, x) is S.Zero
220
+
221
+
222
+ def test_exp_MatrixSymbol():
223
+ A = MatrixSymbol("A", 2, 2)
224
+ assert exp(A).has(exp)
225
+
226
+
227
+ def test_exp_fdiff():
228
+ x = Symbol('x')
229
+ raises(ArgumentIndexError, lambda: exp(x).fdiff(2))
230
+
231
+
232
+ def test_log_values():
233
+ assert log(nan) is nan
234
+
235
+ assert log(oo) is oo
236
+ assert log(-oo) is oo
237
+
238
+ assert log(zoo) is zoo
239
+ assert log(-zoo) is zoo
240
+
241
+ assert log(0) is zoo
242
+
243
+ assert log(1) == 0
244
+ assert log(-1) == I*pi
245
+
246
+ assert log(E) == 1
247
+ assert log(-E).expand() == 1 + I*pi
248
+
249
+ assert unchanged(log, pi)
250
+ assert log(-pi).expand() == log(pi) + I*pi
251
+
252
+ assert unchanged(log, 17)
253
+ assert log(-17) == log(17) + I*pi
254
+
255
+ assert log(I) == I*pi/2
256
+ assert log(-I) == -I*pi/2
257
+
258
+ assert log(17*I) == I*pi/2 + log(17)
259
+ assert log(-17*I).expand() == -I*pi/2 + log(17)
260
+
261
+ assert log(oo*I) is oo
262
+ assert log(-oo*I) is oo
263
+ assert log(0, 2) is zoo
264
+ assert log(0, 5) is zoo
265
+
266
+ assert exp(-log(3))**(-1) == 3
267
+
268
+ assert log(S.Half) == -log(2)
269
+ assert log(2*3).func is log
270
+ assert log(2*3**2).func is log
271
+
272
+
273
+ def test_match_real_imag():
274
+ x, y = symbols('x,y', real=True)
275
+ i = Symbol('i', imaginary=True)
276
+ assert match_real_imag(S.One) == (1, 0)
277
+ assert match_real_imag(I) == (0, 1)
278
+ assert match_real_imag(3 - 5*I) == (3, -5)
279
+ assert match_real_imag(-sqrt(3) + S.Half*I) == (-sqrt(3), S.Half)
280
+ assert match_real_imag(x + y*I) == (x, y)
281
+ assert match_real_imag(x*I + y*I) == (0, x + y)
282
+ assert match_real_imag((x + y)*I) == (0, x + y)
283
+ assert match_real_imag(Rational(-2, 3)*i*I) == (None, None)
284
+ assert match_real_imag(1 - 2*i) == (None, None)
285
+ assert match_real_imag(sqrt(2)*(3 - 5*I)) == (None, None)
286
+
287
+
288
+ def test_log_exact():
289
+ # check for pi/2, pi/3, pi/4, pi/6, pi/8, pi/12; pi/5, pi/10:
290
+ for n in range(-23, 24):
291
+ if gcd(n, 24) != 1:
292
+ assert log(exp(n*I*pi/24).rewrite(sqrt)) == n*I*pi/24
293
+ for n in range(-9, 10):
294
+ assert log(exp(n*I*pi/10).rewrite(sqrt)) == n*I*pi/10
295
+
296
+ assert log(S.Half - I*sqrt(3)/2) == -I*pi/3
297
+ assert log(Rational(-1, 2) + I*sqrt(3)/2) == I*pi*Rational(2, 3)
298
+ assert log(-sqrt(2)/2 - I*sqrt(2)/2) == -I*pi*Rational(3, 4)
299
+ assert log(-sqrt(3)/2 - I*S.Half) == -I*pi*Rational(5, 6)
300
+
301
+ assert log(Rational(-1, 4) + sqrt(5)/4 - I*sqrt(sqrt(5)/8 + Rational(5, 8))) == -I*pi*Rational(2, 5)
302
+ assert log(sqrt(Rational(5, 8) - sqrt(5)/8) + I*(Rational(1, 4) + sqrt(5)/4)) == I*pi*Rational(3, 10)
303
+ assert log(-sqrt(sqrt(2)/4 + S.Half) + I*sqrt(S.Half - sqrt(2)/4)) == I*pi*Rational(7, 8)
304
+ assert log(-sqrt(6)/4 - sqrt(2)/4 + I*(-sqrt(6)/4 + sqrt(2)/4)) == -I*pi*Rational(11, 12)
305
+
306
+ assert log(-1 + I*sqrt(3)) == log(2) + I*pi*Rational(2, 3)
307
+ assert log(5 + 5*I) == log(5*sqrt(2)) + I*pi/4
308
+ assert log(sqrt(-12)) == log(2*sqrt(3)) + I*pi/2
309
+ assert log(-sqrt(6) + sqrt(2) - I*sqrt(6) - I*sqrt(2)) == log(4) - I*pi*Rational(7, 12)
310
+ assert log(-sqrt(6-3*sqrt(2)) - I*sqrt(6+3*sqrt(2))) == log(2*sqrt(3)) - I*pi*Rational(5, 8)
311
+ assert log(1 + I*sqrt(2-sqrt(2))/sqrt(2+sqrt(2))) == log(2/sqrt(sqrt(2) + 2)) + I*pi/8
312
+ assert log(cos(pi*Rational(7, 12)) + I*sin(pi*Rational(7, 12))) == I*pi*Rational(7, 12)
313
+ assert log(cos(pi*Rational(6, 5)) + I*sin(pi*Rational(6, 5))) == I*pi*Rational(-4, 5)
314
+
315
+ assert log(5*(1 + I)/sqrt(2)) == log(5) + I*pi/4
316
+ assert log(sqrt(2)*(-sqrt(3) + 1 - sqrt(3)*I - I)) == log(4) - I*pi*Rational(7, 12)
317
+ assert log(-sqrt(2)*(1 - I*sqrt(3))) == log(2*sqrt(2)) + I*pi*Rational(2, 3)
318
+ assert log(sqrt(3)*I*(-sqrt(6 - 3*sqrt(2)) - I*sqrt(3*sqrt(2) + 6))) == log(6) - I*pi/8
319
+
320
+ zero = (1 + sqrt(2))**2 - 3 - 2*sqrt(2)
321
+ assert log(zero - I*sqrt(3)) == log(sqrt(3)) - I*pi/2
322
+ assert unchanged(log, zero + I*zero) or log(zero + zero*I) is zoo
323
+
324
+ # bail quickly if no obvious simplification is possible:
325
+ assert unchanged(log, (sqrt(2)-1/sqrt(sqrt(3)+I))**1000)
326
+ # beware of non-real coefficients
327
+ assert unchanged(log, sqrt(2-sqrt(5))*(1 + I))
328
+
329
+
330
+ def test_log_base():
331
+ assert log(1, 2) == 0
332
+ assert log(2, 2) == 1
333
+ assert log(3, 2) == log(3)/log(2)
334
+ assert log(6, 2) == 1 + log(3)/log(2)
335
+ assert log(6, 3) == 1 + log(2)/log(3)
336
+ assert log(2**3, 2) == 3
337
+ assert log(3**3, 3) == 3
338
+ assert log(5, 1) is zoo
339
+ assert log(1, 1) is nan
340
+ assert log(Rational(2, 3), 10) == log(Rational(2, 3))/log(10)
341
+ assert log(Rational(2, 3), Rational(1, 3)) == -log(2)/log(3) + 1
342
+ assert log(Rational(2, 3), Rational(2, 5)) == \
343
+ log(Rational(2, 3))/log(Rational(2, 5))
344
+ # issue 17148
345
+ assert log(Rational(8, 3), 2) == -log(3)/log(2) + 3
346
+
347
+
348
+ def test_log_symbolic():
349
+ assert log(x, exp(1)) == log(x)
350
+ assert log(exp(x)) != x
351
+
352
+ assert log(x, exp(1)) == log(x)
353
+ assert log(x*y) != log(x) + log(y)
354
+ assert log(x/y).expand() != log(x) - log(y)
355
+ assert log(x/y).expand(force=True) == log(x) - log(y)
356
+ assert log(x**y).expand() != y*log(x)
357
+ assert log(x**y).expand(force=True) == y*log(x)
358
+
359
+ assert log(x, 2) == log(x)/log(2)
360
+ assert log(E, 2) == 1/log(2)
361
+
362
+ p, q = symbols('p,q', positive=True)
363
+ r = Symbol('r', real=True)
364
+
365
+ assert log(p**2) != 2*log(p)
366
+ assert log(p**2).expand() == 2*log(p)
367
+ assert log(x**2).expand() != 2*log(x)
368
+ assert log(p**q) != q*log(p)
369
+ assert log(exp(p)) == p
370
+ assert log(p*q) != log(p) + log(q)
371
+ assert log(p*q).expand() == log(p) + log(q)
372
+
373
+ assert log(-sqrt(3)) == log(sqrt(3)) + I*pi
374
+ assert log(-exp(p)) != p + I*pi
375
+ assert log(-exp(x)).expand() != x + I*pi
376
+ assert log(-exp(r)).expand() == r + I*pi
377
+
378
+ assert log(x**y) != y*log(x)
379
+
380
+ assert (log(x**-5)**-1).expand() != -1/log(x)/5
381
+ assert (log(p**-5)**-1).expand() == -1/log(p)/5
382
+ assert log(-x).func is log and log(-x).args[0] == -x
383
+ assert log(-p).func is log and log(-p).args[0] == -p
384
+
385
+
386
+ def test_log_exp():
387
+ assert log(exp(4*I*pi)) == 0 # exp evaluates
388
+ assert log(exp(-5*I*pi)) == I*pi # exp evaluates
389
+ assert log(exp(I*pi*Rational(19, 4))) == I*pi*Rational(3, 4)
390
+ assert log(exp(I*pi*Rational(25, 7))) == I*pi*Rational(-3, 7)
391
+ assert log(exp(-5*I)) == -5*I + 2*I*pi
392
+
393
+
394
+ @_both_exp_pow
395
+ def test_exp_assumptions():
396
+ r = Symbol('r', real=True)
397
+ i = Symbol('i', imaginary=True)
398
+ for e in exp, exp_polar:
399
+ assert e(x).is_real is None
400
+ assert e(x).is_imaginary is None
401
+ assert e(i).is_real is None
402
+ assert e(i).is_imaginary is None
403
+ assert e(r).is_real is True
404
+ assert e(r).is_imaginary is False
405
+ assert e(re(x)).is_extended_real is True
406
+ assert e(re(x)).is_imaginary is False
407
+
408
+ assert Pow(E, I*pi, evaluate=False).is_imaginary == False
409
+ assert Pow(E, 2*I*pi, evaluate=False).is_imaginary == False
410
+ assert Pow(E, I*pi/2, evaluate=False).is_imaginary == True
411
+ assert Pow(E, I*pi/3, evaluate=False).is_imaginary is None
412
+
413
+ assert exp(0, evaluate=False).is_algebraic
414
+
415
+ a = Symbol('a', algebraic=True)
416
+ an = Symbol('an', algebraic=True, nonzero=True)
417
+ r = Symbol('r', rational=True)
418
+ rn = Symbol('rn', rational=True, nonzero=True)
419
+ assert exp(a).is_algebraic is None
420
+ assert exp(an).is_algebraic is False
421
+ assert exp(pi*r).is_algebraic is None
422
+ assert exp(pi*rn).is_algebraic is False
423
+
424
+ assert exp(0, evaluate=False).is_algebraic is True
425
+ assert exp(I*pi/3, evaluate=False).is_algebraic is True
426
+ assert exp(I*pi*r, evaluate=False).is_algebraic is True
427
+
428
+
429
+ @_both_exp_pow
430
+ def test_exp_AccumBounds():
431
+ assert exp(AccumBounds(1, 2)) == AccumBounds(E, E**2)
432
+
433
+
434
+ def test_log_assumptions():
435
+ p = symbols('p', positive=True)
436
+ n = symbols('n', negative=True)
437
+ z = symbols('z', zero=True)
438
+ x = symbols('x', infinite=True, extended_positive=True)
439
+
440
+ assert log(z).is_positive is False
441
+ assert log(x).is_extended_positive is True
442
+ assert log(2) > 0
443
+ assert log(1, evaluate=False).is_zero
444
+ assert log(1 + z).is_zero
445
+ assert log(p).is_zero is None
446
+ assert log(n).is_zero is False
447
+ assert log(0.5).is_negative is True
448
+ assert log(exp(p) + 1).is_positive
449
+
450
+ assert log(1, evaluate=False).is_algebraic
451
+ assert log(42, evaluate=False).is_algebraic is False
452
+
453
+ assert log(1 + z).is_rational
454
+
455
+
456
+ def test_log_hashing():
457
+ assert x != log(log(x))
458
+ assert hash(x) != hash(log(log(x)))
459
+ assert log(x) != log(log(log(x)))
460
+
461
+ e = 1/log(log(x) + log(log(x)))
462
+ assert e.base.func is log
463
+ e = 1/log(log(x) + log(log(log(x))))
464
+ assert e.base.func is log
465
+
466
+ e = log(log(x))
467
+ assert e.func is log
468
+ assert x.func is not log
469
+ assert hash(log(log(x))) != hash(x)
470
+ assert e != x
471
+
472
+
473
+ def test_log_sign():
474
+ assert sign(log(2)) == 1
475
+
476
+
477
+ def test_log_expand_complex():
478
+ assert log(1 + I).expand(complex=True) == log(2)/2 + I*pi/4
479
+ assert log(1 - sqrt(2)).expand(complex=True) == log(sqrt(2) - 1) + I*pi
480
+
481
+
482
+ def test_log_apply_evalf():
483
+ value = (log(3)/log(2) - 1).evalf()
484
+ assert value.epsilon_eq(Float("0.58496250072115618145373"))
485
+
486
+
487
+ def test_log_leading_term():
488
+ p = Symbol('p')
489
+
490
+ # Test for STEP 3
491
+ assert log(1 + x + x**2).as_leading_term(x, cdir=1) == x
492
+ # Test for STEP 4
493
+ assert log(2*x).as_leading_term(x, cdir=1) == log(x) + log(2)
494
+ assert log(2*x).as_leading_term(x, cdir=-1) == log(x) + log(2)
495
+ assert log(-2*x).as_leading_term(x, cdir=1, logx=p) == p + log(2) + I*pi
496
+ assert log(-2*x).as_leading_term(x, cdir=-1, logx=p) == p + log(2) - I*pi
497
+ # Test for STEP 5
498
+ assert log(-2*x + (3 - I)*x**2).as_leading_term(x, cdir=1) == log(x) + log(2) - I*pi
499
+ assert log(-2*x + (3 - I)*x**2).as_leading_term(x, cdir=-1) == log(x) + log(2) - I*pi
500
+ assert log(2*x + (3 - I)*x**2).as_leading_term(x, cdir=1) == log(x) + log(2)
501
+ assert log(2*x + (3 - I)*x**2).as_leading_term(x, cdir=-1) == log(x) + log(2) - 2*I*pi
502
+ assert log(-1 + x - I*x**2 + I*x**3).as_leading_term(x, cdir=1) == -I*pi
503
+ assert log(-1 + x - I*x**2 + I*x**3).as_leading_term(x, cdir=-1) == -I*pi
504
+ assert log(-1/(1 - x)).as_leading_term(x, cdir=1) == I*pi
505
+ assert log(-1/(1 - x)).as_leading_term(x, cdir=-1) == I*pi
506
+
507
+
508
+ def test_log_nseries():
509
+ p = Symbol('p')
510
+ assert log(1/x)._eval_nseries(x, 4, logx=-p, cdir=1) == p
511
+ assert log(1/x)._eval_nseries(x, 4, logx=-p, cdir=-1) == p + 2*I*pi
512
+ assert log(x - 1)._eval_nseries(x, 4, None, I) == I*pi - x - x**2/2 - x**3/3 + O(x**4)
513
+ assert log(x - 1)._eval_nseries(x, 4, None, -I) == -I*pi - x - x**2/2 - x**3/3 + O(x**4)
514
+ assert log(I*x + I*x**3 - 1)._eval_nseries(x, 3, None, 1) == I*pi - I*x + x**2/2 + O(x**3)
515
+ assert log(I*x + I*x**3 - 1)._eval_nseries(x, 3, None, -1) == -I*pi - I*x + x**2/2 + O(x**3)
516
+ assert log(I*x**2 + I*x**3 - 1)._eval_nseries(x, 3, None, 1) == I*pi - I*x**2 + O(x**3)
517
+ assert log(I*x**2 + I*x**3 - 1)._eval_nseries(x, 3, None, -1) == I*pi - I*x**2 + O(x**3)
518
+ assert log(2*x + (3 - I)*x**2)._eval_nseries(x, 3, None, 1) == log(2) + log(x) + \
519
+ x*(S(3)/2 - I/2) + x**2*(-1 + 3*I/4) + O(x**3)
520
+ assert log(2*x + (3 - I)*x**2)._eval_nseries(x, 3, None, -1) == -2*I*pi + log(2) + \
521
+ log(x) - x*(-S(3)/2 + I/2) + x**2*(-1 + 3*I/4) + O(x**3)
522
+ assert log(-2*x + (3 - I)*x**2)._eval_nseries(x, 3, None, 1) == -I*pi + log(2) + log(x) + \
523
+ x*(-S(3)/2 + I/2) + x**2*(-1 + 3*I/4) + O(x**3)
524
+ assert log(-2*x + (3 - I)*x**2)._eval_nseries(x, 3, None, -1) == -I*pi + log(2) + log(x) - \
525
+ x*(S(3)/2 - I/2) + x**2*(-1 + 3*I/4) + O(x**3)
526
+ assert log(sqrt(-I*x**2 - 3)*sqrt(-I*x**2 - 1) - 2)._eval_nseries(x, 3, None, 1) == -I*pi + \
527
+ log(sqrt(3) + 2) + I*x**2*(-2 + 4*sqrt(3)/3) + O(x**3)
528
+ assert log(-1/(1 - x))._eval_nseries(x, 3, None, 1) == I*pi + x + x**2/2 + O(x**3)
529
+ assert log(-1/(1 - x))._eval_nseries(x, 3, None, -1) == I*pi + x + x**2/2 + O(x**3)
530
+
531
+
532
+ def test_log_series():
533
+ # Note Series at infinities other than oo/-oo were introduced as a part of
534
+ # pull request 23798. Refer https://github.com/sympy/sympy/pull/23798 for
535
+ # more information.
536
+ expr1 = log(1 + x)
537
+ expr2 = log(x + sqrt(x**2 + 1))
538
+
539
+ assert expr1.series(x, x0=I*oo, n=4) == 1/(3*x**3) - 1/(2*x**2) + 1/x + \
540
+ I*pi/2 - log(I/x) + O(x**(-4), (x, oo*I))
541
+ assert expr1.series(x, x0=-I*oo, n=4) == 1/(3*x**3) - 1/(2*x**2) + 1/x - \
542
+ I*pi/2 - log(-I/x) + O(x**(-4), (x, -oo*I))
543
+ assert expr2.series(x, x0=I*oo, n=4) == 1/(4*x**2) + I*pi/2 + log(2) - \
544
+ log(I/x) + O(x**(-4), (x, oo*I))
545
+ assert expr2.series(x, x0=-I*oo, n=4) == -1/(4*x**2) - I*pi/2 - log(2) + \
546
+ log(-I/x) + O(x**(-4), (x, -oo*I))
547
+
548
+
549
+ def test_log_expand():
550
+ w = Symbol("w", positive=True)
551
+ e = log(w**(log(5)/log(3)))
552
+ assert e.expand() == log(5)/log(3) * log(w)
553
+ x, y, z = symbols('x,y,z', positive=True)
554
+ assert log(x*(y + z)).expand(mul=False) == log(x) + log(y + z)
555
+ assert log(log(x**2)*log(y*z)).expand() in [log(2*log(x)*log(y) +
556
+ 2*log(x)*log(z)), log(log(x)*log(z) + log(y)*log(x)) + log(2),
557
+ log((log(y) + log(z))*log(x)) + log(2)]
558
+ assert log(x**log(x**2)).expand(deep=False) == log(x)*log(x**2)
559
+ assert log(x**log(x**2)).expand() == 2*log(x)**2
560
+ x, y = symbols('x,y')
561
+ assert log(x*y).expand(force=True) == log(x) + log(y)
562
+ assert log(x**y).expand(force=True) == y*log(x)
563
+ assert log(exp(x)).expand(force=True) == x
564
+
565
+ # there's generally no need to expand out logs since this requires
566
+ # factoring and if simplification is sought, it's cheaper to put
567
+ # logs together than it is to take them apart.
568
+ assert log(2*3**2).expand() != 2*log(3) + log(2)
569
+
570
+
571
+ @XFAIL
572
+ def test_log_expand_fail():
573
+ x, y, z = symbols('x,y,z', positive=True)
574
+ assert (log(x*(y + z))*(x + y)).expand(mul=True, log=True) == y*log(
575
+ x) + y*log(y + z) + z*log(x) + z*log(y + z)
576
+
577
+
578
+ def test_log_simplify():
579
+ x = Symbol("x", positive=True)
580
+ assert log(x**2).expand() == 2*log(x)
581
+ assert expand_log(log(x**(2 + log(2)))) == (2 + log(2))*log(x)
582
+
583
+ z = Symbol('z')
584
+ assert log(sqrt(z)).expand() == log(z)/2
585
+ assert expand_log(log(z**(log(2) - 1))) == (log(2) - 1)*log(z)
586
+ assert log(z**(-1)).expand() != -log(z)
587
+ assert log(z**(x/(x+1))).expand() == x*log(z)/(x + 1)
588
+
589
+
590
+ def test_log_AccumBounds():
591
+ assert log(AccumBounds(1, E)) == AccumBounds(0, 1)
592
+ assert log(AccumBounds(0, E)) == AccumBounds(-oo, 1)
593
+ assert log(AccumBounds(-1, E)) == S.NaN
594
+ assert log(AccumBounds(0, oo)) == AccumBounds(-oo, oo)
595
+ assert log(AccumBounds(-oo, 0)) == S.NaN
596
+ assert log(AccumBounds(-oo, oo)) == S.NaN
597
+
598
+
599
+ @_both_exp_pow
600
+ def test_lambertw():
601
+ k = Symbol('k')
602
+
603
+ assert LambertW(x, 0) == LambertW(x)
604
+ assert LambertW(x, 0, evaluate=False) != LambertW(x)
605
+ assert LambertW(0) == 0
606
+ assert LambertW(E) == 1
607
+ assert LambertW(-1/E) == -1
608
+ assert LambertW(-log(2)/2) == -log(2)
609
+ assert LambertW(oo) is oo
610
+ assert LambertW(0, 1) is -oo
611
+ assert LambertW(0, 42) is -oo
612
+ assert LambertW(-pi/2, -1) == -I*pi/2
613
+ assert LambertW(-1/E, -1) == -1
614
+ assert LambertW(-2*exp(-2), -1) == -2
615
+ assert LambertW(2*log(2)) == log(2)
616
+ assert LambertW(-pi/2) == I*pi/2
617
+ assert LambertW(exp(1 + E)) == E
618
+
619
+ assert LambertW(x**2).diff(x) == 2*LambertW(x**2)/x/(1 + LambertW(x**2))
620
+ assert LambertW(x, k).diff(x) == LambertW(x, k)/x/(1 + LambertW(x, k))
621
+
622
+ assert LambertW(sqrt(2)).evalf(30).epsilon_eq(
623
+ Float("0.701338383413663009202120278965", 30), 1e-29)
624
+ assert re(LambertW(2, -1)).evalf().epsilon_eq(Float("-0.834310366631110"))
625
+
626
+ assert LambertW(-1).is_real is False # issue 5215
627
+ assert LambertW(2, evaluate=False).is_real
628
+ p = Symbol('p', positive=True)
629
+ assert LambertW(p, evaluate=False).is_real
630
+ assert LambertW(p - 1, evaluate=False).is_real is None
631
+ assert LambertW(-p - 2/S.Exp1, evaluate=False).is_real is False
632
+ assert LambertW(S.Half, -1, evaluate=False).is_real is False
633
+ assert LambertW(Rational(-1, 10), -1, evaluate=False).is_real
634
+ assert LambertW(-10, -1, evaluate=False).is_real is False
635
+ assert LambertW(-2, 2, evaluate=False).is_real is False
636
+
637
+ assert LambertW(0, evaluate=False).is_algebraic
638
+ na = Symbol('na', nonzero=True, algebraic=True)
639
+ assert LambertW(na).is_algebraic is False
640
+ assert LambertW(p).is_zero is False
641
+ n = Symbol('n', negative=True)
642
+ assert LambertW(n).is_zero is False
643
+
644
+
645
+ def test_issue_5673():
646
+ e = LambertW(-1)
647
+ assert e.is_comparable is False
648
+ assert e.is_positive is not True
649
+ e2 = 1 - 1/(1 - exp(-1000))
650
+ assert e2.is_positive is not True
651
+ e3 = -2 + exp(exp(LambertW(log(2)))*LambertW(log(2)))
652
+ assert e3.is_nonzero is not True
653
+
654
+
655
+ def test_log_fdiff():
656
+ x = Symbol('x')
657
+ raises(ArgumentIndexError, lambda: log(x).fdiff(2))
658
+
659
+
660
+ def test_log_taylor_term():
661
+ x = symbols('x')
662
+ assert log(x).taylor_term(0, x) == x
663
+ assert log(x).taylor_term(1, x) == -x**2/2
664
+ assert log(x).taylor_term(4, x) == x**5/5
665
+ assert log(x).taylor_term(-1, x) is S.Zero
666
+
667
+
668
+ def test_exp_expand_NC():
669
+ A, B, C = symbols('A,B,C', commutative=False)
670
+
671
+ assert exp(A + B).expand() == exp(A + B)
672
+ assert exp(A + B + C).expand() == exp(A + B + C)
673
+ assert exp(x + y).expand() == exp(x)*exp(y)
674
+ assert exp(x + y + z).expand() == exp(x)*exp(y)*exp(z)
675
+
676
+
677
+ @_both_exp_pow
678
+ def test_as_numer_denom():
679
+ n = symbols('n', negative=True)
680
+ assert exp(x).as_numer_denom() == (exp(x), 1)
681
+ assert exp(-x).as_numer_denom() == (1, exp(x))
682
+ assert exp(-2*x).as_numer_denom() == (1, exp(2*x))
683
+ assert exp(-2).as_numer_denom() == (1, exp(2))
684
+ assert exp(n).as_numer_denom() == (1, exp(-n))
685
+ assert exp(-n).as_numer_denom() == (exp(-n), 1)
686
+ assert exp(-I*x).as_numer_denom() == (1, exp(I*x))
687
+ assert exp(-I*n).as_numer_denom() == (1, exp(I*n))
688
+ assert exp(-n).as_numer_denom() == (exp(-n), 1)
689
+
690
+
691
+ @_both_exp_pow
692
+ def test_polar():
693
+ x, y = symbols('x y', polar=True)
694
+
695
+ assert abs(exp_polar(I*4)) == 1
696
+ assert abs(exp_polar(0)) == 1
697
+ assert abs(exp_polar(2 + 3*I)) == exp(2)
698
+ assert exp_polar(I*10).n() == exp_polar(I*10)
699
+
700
+ assert log(exp_polar(z)) == z
701
+ assert log(x*y).expand() == log(x) + log(y)
702
+ assert log(x**z).expand() == z*log(x)
703
+
704
+ assert exp_polar(3).exp == 3
705
+
706
+ # Compare exp(1.0*pi*I).
707
+ assert (exp_polar(1.0*pi*I).n(n=5)).as_real_imag()[1] >= 0
708
+
709
+ assert exp_polar(0).is_rational is True # issue 8008
710
+
711
+
712
+ def test_exp_summation():
713
+ w = symbols("w")
714
+ m, n, i, j = symbols("m n i j")
715
+ expr = exp(Sum(w*i, (i, 0, n), (j, 0, m)))
716
+ assert expr.expand() == Product(exp(w*i), (i, 0, n), (j, 0, m))
717
+
718
+
719
+ def test_log_product():
720
+ from sympy.abc import n, m
721
+
722
+ i, j = symbols('i,j', positive=True, integer=True)
723
+ x, y = symbols('x,y', positive=True)
724
+ z = symbols('z', real=True)
725
+ w = symbols('w')
726
+
727
+ expr = log(Product(x**i, (i, 1, n)))
728
+ assert simplify(expr) == expr
729
+ assert expr.expand() == Sum(i*log(x), (i, 1, n))
730
+ expr = log(Product(x**i*y**j, (i, 1, n), (j, 1, m)))
731
+ assert simplify(expr) == expr
732
+ assert expr.expand() == Sum(i*log(x) + j*log(y), (i, 1, n), (j, 1, m))
733
+
734
+ expr = log(Product(-2, (n, 0, 4)))
735
+ assert simplify(expr) == expr
736
+ assert expr.expand() == expr
737
+ assert expr.expand(force=True) == Sum(log(-2), (n, 0, 4))
738
+
739
+ expr = log(Product(exp(z*i), (i, 0, n)))
740
+ assert expr.expand() == Sum(z*i, (i, 0, n))
741
+
742
+ expr = log(Product(exp(w*i), (i, 0, n)))
743
+ assert expr.expand() == expr
744
+ assert expr.expand(force=True) == Sum(w*i, (i, 0, n))
745
+
746
+ expr = log(Product(i**2*abs(j), (i, 1, n), (j, 1, m)))
747
+ assert expr.expand() == Sum(2*log(i) + log(j), (i, 1, n), (j, 1, m))
748
+
749
+
750
+ @XFAIL
751
+ def test_log_product_simplify_to_sum():
752
+ from sympy.abc import n, m
753
+ i, j = symbols('i,j', positive=True, integer=True)
754
+ x, y = symbols('x,y', positive=True)
755
+ assert simplify(log(Product(x**i, (i, 1, n)))) == Sum(i*log(x), (i, 1, n))
756
+ assert simplify(log(Product(x**i*y**j, (i, 1, n), (j, 1, m)))) == \
757
+ Sum(i*log(x) + j*log(y), (i, 1, n), (j, 1, m))
758
+
759
+
760
+ def test_issue_8866():
761
+ assert simplify(log(x, 10, evaluate=False)) == simplify(log(x, 10))
762
+ assert expand_log(log(x, 10, evaluate=False)) == expand_log(log(x, 10))
763
+
764
+ y = Symbol('y', positive=True)
765
+ l1 = log(exp(y), exp(10))
766
+ b1 = log(exp(y), exp(5))
767
+ l2 = log(exp(y), exp(10), evaluate=False)
768
+ b2 = log(exp(y), exp(5), evaluate=False)
769
+ assert simplify(log(l1, b1)) == simplify(log(l2, b2))
770
+ assert expand_log(log(l1, b1)) == expand_log(log(l2, b2))
771
+
772
+
773
+ def test_log_expand_factor():
774
+ assert (log(18)/log(3) - 2).expand(factor=True) == log(2)/log(3)
775
+ assert (log(12)/log(2)).expand(factor=True) == log(3)/log(2) + 2
776
+ assert (log(15)/log(3)).expand(factor=True) == 1 + log(5)/log(3)
777
+ assert (log(2)/(-log(12) + log(24))).expand(factor=True) == 1
778
+
779
+ assert expand_log(log(12), factor=True) == log(3) + 2*log(2)
780
+ assert expand_log(log(21)/log(7), factor=False) == log(3)/log(7) + 1
781
+ assert expand_log(log(45)/log(5) + log(20), factor=False) == \
782
+ 1 + 2*log(3)/log(5) + log(20)
783
+ assert expand_log(log(45)/log(5) + log(26), factor=True) == \
784
+ log(2) + log(13) + (log(5) + 2*log(3))/log(5)
785
+
786
+
787
+ def test_issue_9116():
788
+ n = Symbol('n', positive=True, integer=True)
789
+ assert log(n).is_nonnegative is True
790
+
791
+
792
+ def test_issue_18473():
793
+ assert exp(x*log(cos(1/x))).as_leading_term(x) == S.NaN
794
+ assert exp(x*log(tan(1/x))).as_leading_term(x) == S.NaN
795
+ assert log(cos(1/x)).as_leading_term(x) == S.NaN
796
+ assert log(tan(1/x)).as_leading_term(x) == S.NaN
797
+ assert log(cos(1/x) + 2).as_leading_term(x) == AccumBounds(0, log(3))
798
+ assert exp(x*log(cos(1/x) + 2)).as_leading_term(x) == 1
799
+ assert log(cos(1/x) - 2).as_leading_term(x) == S.NaN
800
+ assert exp(x*log(cos(1/x) - 2)).as_leading_term(x) == S.NaN
801
+ assert log(cos(1/x) + 1).as_leading_term(x) == AccumBounds(-oo, log(2))
802
+ assert exp(x*log(cos(1/x) + 1)).as_leading_term(x) == AccumBounds(0, 1)
803
+ assert log(sin(1/x)**2).as_leading_term(x) == AccumBounds(-oo, 0)
804
+ assert exp(x*log(sin(1/x)**2)).as_leading_term(x) == AccumBounds(0, 1)
805
+ assert log(tan(1/x)**2).as_leading_term(x) == AccumBounds(-oo, oo)
806
+ assert exp(2*x*(log(tan(1/x)**2))).as_leading_term(x) == AccumBounds(0, oo)
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_hyperbolic.py ADDED
@@ -0,0 +1,1460 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.calculus.accumulationbounds import AccumBounds
2
+ from sympy.core.function import (expand_mul, expand_trig)
3
+ from sympy.core.numbers import (E, I, Integer, Rational, nan, oo, pi, zoo)
4
+ from sympy.core.singleton import S
5
+ from sympy.core.symbol import (Symbol, symbols)
6
+ from sympy.functions.elementary.complexes import (im, re)
7
+ from sympy.functions.elementary.exponential import (exp, log)
8
+ from sympy.functions.elementary.hyperbolic import (acosh, acoth, acsch, asech, asinh, atanh, cosh, coth, csch, sech, sinh, tanh)
9
+ from sympy.functions.elementary.miscellaneous import sqrt
10
+ from sympy.functions.elementary.trigonometric import (acos, asin, cos, cot, sec, sin, tan)
11
+ from sympy.series.order import O
12
+
13
+ from sympy.core.expr import unchanged
14
+ from sympy.core.function import ArgumentIndexError
15
+ from sympy.testing.pytest import raises
16
+
17
+
18
+ def test_sinh():
19
+ x, y = symbols('x,y')
20
+
21
+ k = Symbol('k', integer=True)
22
+
23
+ assert sinh(nan) is nan
24
+ assert sinh(zoo) is nan
25
+
26
+ assert sinh(oo) is oo
27
+ assert sinh(-oo) is -oo
28
+
29
+ assert sinh(0) == 0
30
+
31
+ assert unchanged(sinh, 1)
32
+ assert sinh(-1) == -sinh(1)
33
+
34
+ assert unchanged(sinh, x)
35
+ assert sinh(-x) == -sinh(x)
36
+
37
+ assert unchanged(sinh, pi)
38
+ assert sinh(-pi) == -sinh(pi)
39
+
40
+ assert unchanged(sinh, 2**1024 * E)
41
+ assert sinh(-2**1024 * E) == -sinh(2**1024 * E)
42
+
43
+ assert sinh(pi*I) == 0
44
+ assert sinh(-pi*I) == 0
45
+ assert sinh(2*pi*I) == 0
46
+ assert sinh(-2*pi*I) == 0
47
+ assert sinh(-3*10**73*pi*I) == 0
48
+ assert sinh(7*10**103*pi*I) == 0
49
+
50
+ assert sinh(pi*I/2) == I
51
+ assert sinh(-pi*I/2) == -I
52
+ assert sinh(pi*I*Rational(5, 2)) == I
53
+ assert sinh(pi*I*Rational(7, 2)) == -I
54
+
55
+ assert sinh(pi*I/3) == S.Half*sqrt(3)*I
56
+ assert sinh(pi*I*Rational(-2, 3)) == Rational(-1, 2)*sqrt(3)*I
57
+
58
+ assert sinh(pi*I/4) == S.Half*sqrt(2)*I
59
+ assert sinh(-pi*I/4) == Rational(-1, 2)*sqrt(2)*I
60
+ assert sinh(pi*I*Rational(17, 4)) == S.Half*sqrt(2)*I
61
+ assert sinh(pi*I*Rational(-3, 4)) == Rational(-1, 2)*sqrt(2)*I
62
+
63
+ assert sinh(pi*I/6) == S.Half*I
64
+ assert sinh(-pi*I/6) == Rational(-1, 2)*I
65
+ assert sinh(pi*I*Rational(7, 6)) == Rational(-1, 2)*I
66
+ assert sinh(pi*I*Rational(-5, 6)) == Rational(-1, 2)*I
67
+
68
+ assert sinh(pi*I/105) == sin(pi/105)*I
69
+ assert sinh(-pi*I/105) == -sin(pi/105)*I
70
+
71
+ assert unchanged(sinh, 2 + 3*I)
72
+
73
+ assert sinh(x*I) == sin(x)*I
74
+
75
+ assert sinh(k*pi*I) == 0
76
+ assert sinh(17*k*pi*I) == 0
77
+
78
+ assert sinh(k*pi*I/2) == sin(k*pi/2)*I
79
+
80
+ assert sinh(x).as_real_imag(deep=False) == (cos(im(x))*sinh(re(x)),
81
+ sin(im(x))*cosh(re(x)))
82
+ x = Symbol('x', extended_real=True)
83
+ assert sinh(x).as_real_imag(deep=False) == (sinh(x), 0)
84
+
85
+ x = Symbol('x', real=True)
86
+ assert sinh(I*x).is_finite is True
87
+ assert sinh(x).is_real is True
88
+ assert sinh(I).is_real is False
89
+ p = Symbol('p', positive=True)
90
+ assert sinh(p).is_zero is False
91
+ assert sinh(0, evaluate=False).is_zero is True
92
+ assert sinh(2*pi*I, evaluate=False).is_zero is True
93
+
94
+
95
+ def test_sinh_series():
96
+ x = Symbol('x')
97
+ assert sinh(x).series(x, 0, 10) == \
98
+ x + x**3/6 + x**5/120 + x**7/5040 + x**9/362880 + O(x**10)
99
+
100
+
101
+ def test_sinh_fdiff():
102
+ x = Symbol('x')
103
+ raises(ArgumentIndexError, lambda: sinh(x).fdiff(2))
104
+
105
+
106
+ def test_cosh():
107
+ x, y = symbols('x,y')
108
+
109
+ k = Symbol('k', integer=True)
110
+
111
+ assert cosh(nan) is nan
112
+ assert cosh(zoo) is nan
113
+
114
+ assert cosh(oo) is oo
115
+ assert cosh(-oo) is oo
116
+
117
+ assert cosh(0) == 1
118
+
119
+ assert unchanged(cosh, 1)
120
+ assert cosh(-1) == cosh(1)
121
+
122
+ assert unchanged(cosh, x)
123
+ assert cosh(-x) == cosh(x)
124
+
125
+ assert cosh(pi*I) == cos(pi)
126
+ assert cosh(-pi*I) == cos(pi)
127
+
128
+ assert unchanged(cosh, 2**1024 * E)
129
+ assert cosh(-2**1024 * E) == cosh(2**1024 * E)
130
+
131
+ assert cosh(pi*I/2) == 0
132
+ assert cosh(-pi*I/2) == 0
133
+ assert cosh((-3*10**73 + 1)*pi*I/2) == 0
134
+ assert cosh((7*10**103 + 1)*pi*I/2) == 0
135
+
136
+ assert cosh(pi*I) == -1
137
+ assert cosh(-pi*I) == -1
138
+ assert cosh(5*pi*I) == -1
139
+ assert cosh(8*pi*I) == 1
140
+
141
+ assert cosh(pi*I/3) == S.Half
142
+ assert cosh(pi*I*Rational(-2, 3)) == Rational(-1, 2)
143
+
144
+ assert cosh(pi*I/4) == S.Half*sqrt(2)
145
+ assert cosh(-pi*I/4) == S.Half*sqrt(2)
146
+ assert cosh(pi*I*Rational(11, 4)) == Rational(-1, 2)*sqrt(2)
147
+ assert cosh(pi*I*Rational(-3, 4)) == Rational(-1, 2)*sqrt(2)
148
+
149
+ assert cosh(pi*I/6) == S.Half*sqrt(3)
150
+ assert cosh(-pi*I/6) == S.Half*sqrt(3)
151
+ assert cosh(pi*I*Rational(7, 6)) == Rational(-1, 2)*sqrt(3)
152
+ assert cosh(pi*I*Rational(-5, 6)) == Rational(-1, 2)*sqrt(3)
153
+
154
+ assert cosh(pi*I/105) == cos(pi/105)
155
+ assert cosh(-pi*I/105) == cos(pi/105)
156
+
157
+ assert unchanged(cosh, 2 + 3*I)
158
+
159
+ assert cosh(x*I) == cos(x)
160
+
161
+ assert cosh(k*pi*I) == cos(k*pi)
162
+ assert cosh(17*k*pi*I) == cos(17*k*pi)
163
+
164
+ assert unchanged(cosh, k*pi)
165
+
166
+ assert cosh(x).as_real_imag(deep=False) == (cos(im(x))*cosh(re(x)),
167
+ sin(im(x))*sinh(re(x)))
168
+ x = Symbol('x', extended_real=True)
169
+ assert cosh(x).as_real_imag(deep=False) == (cosh(x), 0)
170
+
171
+ x = Symbol('x', real=True)
172
+ assert cosh(I*x).is_finite is True
173
+ assert cosh(I*x).is_real is True
174
+ assert cosh(I*2 + 1).is_real is False
175
+ assert cosh(5*I*S.Pi/2, evaluate=False).is_zero is True
176
+ assert cosh(x).is_zero is False
177
+
178
+
179
+ def test_cosh_series():
180
+ x = Symbol('x')
181
+ assert cosh(x).series(x, 0, 10) == \
182
+ 1 + x**2/2 + x**4/24 + x**6/720 + x**8/40320 + O(x**10)
183
+
184
+
185
+ def test_cosh_fdiff():
186
+ x = Symbol('x')
187
+ raises(ArgumentIndexError, lambda: cosh(x).fdiff(2))
188
+
189
+
190
+ def test_tanh():
191
+ x, y = symbols('x,y')
192
+
193
+ k = Symbol('k', integer=True)
194
+
195
+ assert tanh(nan) is nan
196
+ assert tanh(zoo) is nan
197
+
198
+ assert tanh(oo) == 1
199
+ assert tanh(-oo) == -1
200
+
201
+ assert tanh(0) == 0
202
+
203
+ assert unchanged(tanh, 1)
204
+ assert tanh(-1) == -tanh(1)
205
+
206
+ assert unchanged(tanh, x)
207
+ assert tanh(-x) == -tanh(x)
208
+
209
+ assert unchanged(tanh, pi)
210
+ assert tanh(-pi) == -tanh(pi)
211
+
212
+ assert unchanged(tanh, 2**1024 * E)
213
+ assert tanh(-2**1024 * E) == -tanh(2**1024 * E)
214
+
215
+ assert tanh(pi*I) == 0
216
+ assert tanh(-pi*I) == 0
217
+ assert tanh(2*pi*I) == 0
218
+ assert tanh(-2*pi*I) == 0
219
+ assert tanh(-3*10**73*pi*I) == 0
220
+ assert tanh(7*10**103*pi*I) == 0
221
+
222
+ assert tanh(pi*I/2) is zoo
223
+ assert tanh(-pi*I/2) is zoo
224
+ assert tanh(pi*I*Rational(5, 2)) is zoo
225
+ assert tanh(pi*I*Rational(7, 2)) is zoo
226
+
227
+ assert tanh(pi*I/3) == sqrt(3)*I
228
+ assert tanh(pi*I*Rational(-2, 3)) == sqrt(3)*I
229
+
230
+ assert tanh(pi*I/4) == I
231
+ assert tanh(-pi*I/4) == -I
232
+ assert tanh(pi*I*Rational(17, 4)) == I
233
+ assert tanh(pi*I*Rational(-3, 4)) == I
234
+
235
+ assert tanh(pi*I/6) == I/sqrt(3)
236
+ assert tanh(-pi*I/6) == -I/sqrt(3)
237
+ assert tanh(pi*I*Rational(7, 6)) == I/sqrt(3)
238
+ assert tanh(pi*I*Rational(-5, 6)) == I/sqrt(3)
239
+
240
+ assert tanh(pi*I/105) == tan(pi/105)*I
241
+ assert tanh(-pi*I/105) == -tan(pi/105)*I
242
+
243
+ assert unchanged(tanh, 2 + 3*I)
244
+
245
+ assert tanh(x*I) == tan(x)*I
246
+
247
+ assert tanh(k*pi*I) == 0
248
+ assert tanh(17*k*pi*I) == 0
249
+
250
+ assert tanh(k*pi*I/2) == tan(k*pi/2)*I
251
+
252
+ assert tanh(x).as_real_imag(deep=False) == (sinh(re(x))*cosh(re(x))/(cos(im(x))**2
253
+ + sinh(re(x))**2),
254
+ sin(im(x))*cos(im(x))/(cos(im(x))**2 + sinh(re(x))**2))
255
+ x = Symbol('x', extended_real=True)
256
+ assert tanh(x).as_real_imag(deep=False) == (tanh(x), 0)
257
+ assert tanh(I*pi/3 + 1).is_real is False
258
+ assert tanh(x).is_real is True
259
+ assert tanh(I*pi*x/2).is_real is None
260
+
261
+
262
+ def test_tanh_series():
263
+ x = Symbol('x')
264
+ assert tanh(x).series(x, 0, 10) == \
265
+ x - x**3/3 + 2*x**5/15 - 17*x**7/315 + 62*x**9/2835 + O(x**10)
266
+
267
+
268
+ def test_tanh_fdiff():
269
+ x = Symbol('x')
270
+ raises(ArgumentIndexError, lambda: tanh(x).fdiff(2))
271
+
272
+
273
+ def test_coth():
274
+ x, y = symbols('x,y')
275
+
276
+ k = Symbol('k', integer=True)
277
+
278
+ assert coth(nan) is nan
279
+ assert coth(zoo) is nan
280
+
281
+ assert coth(oo) == 1
282
+ assert coth(-oo) == -1
283
+
284
+ assert coth(0) is zoo
285
+ assert unchanged(coth, 1)
286
+ assert coth(-1) == -coth(1)
287
+
288
+ assert unchanged(coth, x)
289
+ assert coth(-x) == -coth(x)
290
+
291
+ assert coth(pi*I) == -I*cot(pi)
292
+ assert coth(-pi*I) == cot(pi)*I
293
+
294
+ assert unchanged(coth, 2**1024 * E)
295
+ assert coth(-2**1024 * E) == -coth(2**1024 * E)
296
+
297
+ assert coth(pi*I) == -I*cot(pi)
298
+ assert coth(-pi*I) == I*cot(pi)
299
+ assert coth(2*pi*I) == -I*cot(2*pi)
300
+ assert coth(-2*pi*I) == I*cot(2*pi)
301
+ assert coth(-3*10**73*pi*I) == I*cot(3*10**73*pi)
302
+ assert coth(7*10**103*pi*I) == -I*cot(7*10**103*pi)
303
+
304
+ assert coth(pi*I/2) == 0
305
+ assert coth(-pi*I/2) == 0
306
+ assert coth(pi*I*Rational(5, 2)) == 0
307
+ assert coth(pi*I*Rational(7, 2)) == 0
308
+
309
+ assert coth(pi*I/3) == -I/sqrt(3)
310
+ assert coth(pi*I*Rational(-2, 3)) == -I/sqrt(3)
311
+
312
+ assert coth(pi*I/4) == -I
313
+ assert coth(-pi*I/4) == I
314
+ assert coth(pi*I*Rational(17, 4)) == -I
315
+ assert coth(pi*I*Rational(-3, 4)) == -I
316
+
317
+ assert coth(pi*I/6) == -sqrt(3)*I
318
+ assert coth(-pi*I/6) == sqrt(3)*I
319
+ assert coth(pi*I*Rational(7, 6)) == -sqrt(3)*I
320
+ assert coth(pi*I*Rational(-5, 6)) == -sqrt(3)*I
321
+
322
+ assert coth(pi*I/105) == -cot(pi/105)*I
323
+ assert coth(-pi*I/105) == cot(pi/105)*I
324
+
325
+ assert unchanged(coth, 2 + 3*I)
326
+
327
+ assert coth(x*I) == -cot(x)*I
328
+
329
+ assert coth(k*pi*I) == -cot(k*pi)*I
330
+ assert coth(17*k*pi*I) == -cot(17*k*pi)*I
331
+
332
+ assert coth(k*pi*I) == -cot(k*pi)*I
333
+
334
+ assert coth(log(tan(2))) == coth(log(-tan(2)))
335
+ assert coth(1 + I*pi/2) == tanh(1)
336
+
337
+ assert coth(x).as_real_imag(deep=False) == (sinh(re(x))*cosh(re(x))/(sin(im(x))**2
338
+ + sinh(re(x))**2),
339
+ -sin(im(x))*cos(im(x))/(sin(im(x))**2 + sinh(re(x))**2))
340
+ x = Symbol('x', extended_real=True)
341
+ assert coth(x).as_real_imag(deep=False) == (coth(x), 0)
342
+
343
+ assert expand_trig(coth(2*x)) == (coth(x)**2 + 1)/(2*coth(x))
344
+ assert expand_trig(coth(3*x)) == (coth(x)**3 + 3*coth(x))/(1 + 3*coth(x)**2)
345
+
346
+ assert expand_trig(coth(x + y)) == (1 + coth(x)*coth(y))/(coth(x) + coth(y))
347
+
348
+
349
+ def test_coth_series():
350
+ x = Symbol('x')
351
+ assert coth(x).series(x, 0, 8) == \
352
+ 1/x + x/3 - x**3/45 + 2*x**5/945 - x**7/4725 + O(x**8)
353
+
354
+
355
+ def test_coth_fdiff():
356
+ x = Symbol('x')
357
+ raises(ArgumentIndexError, lambda: coth(x).fdiff(2))
358
+
359
+
360
+ def test_csch():
361
+ x, y = symbols('x,y')
362
+
363
+ k = Symbol('k', integer=True)
364
+ n = Symbol('n', positive=True)
365
+
366
+ assert csch(nan) is nan
367
+ assert csch(zoo) is nan
368
+
369
+ assert csch(oo) == 0
370
+ assert csch(-oo) == 0
371
+
372
+ assert csch(0) is zoo
373
+
374
+ assert csch(-1) == -csch(1)
375
+
376
+ assert csch(-x) == -csch(x)
377
+ assert csch(-pi) == -csch(pi)
378
+ assert csch(-2**1024 * E) == -csch(2**1024 * E)
379
+
380
+ assert csch(pi*I) is zoo
381
+ assert csch(-pi*I) is zoo
382
+ assert csch(2*pi*I) is zoo
383
+ assert csch(-2*pi*I) is zoo
384
+ assert csch(-3*10**73*pi*I) is zoo
385
+ assert csch(7*10**103*pi*I) is zoo
386
+
387
+ assert csch(pi*I/2) == -I
388
+ assert csch(-pi*I/2) == I
389
+ assert csch(pi*I*Rational(5, 2)) == -I
390
+ assert csch(pi*I*Rational(7, 2)) == I
391
+
392
+ assert csch(pi*I/3) == -2/sqrt(3)*I
393
+ assert csch(pi*I*Rational(-2, 3)) == 2/sqrt(3)*I
394
+
395
+ assert csch(pi*I/4) == -sqrt(2)*I
396
+ assert csch(-pi*I/4) == sqrt(2)*I
397
+ assert csch(pi*I*Rational(7, 4)) == sqrt(2)*I
398
+ assert csch(pi*I*Rational(-3, 4)) == sqrt(2)*I
399
+
400
+ assert csch(pi*I/6) == -2*I
401
+ assert csch(-pi*I/6) == 2*I
402
+ assert csch(pi*I*Rational(7, 6)) == 2*I
403
+ assert csch(pi*I*Rational(-7, 6)) == -2*I
404
+ assert csch(pi*I*Rational(-5, 6)) == 2*I
405
+
406
+ assert csch(pi*I/105) == -1/sin(pi/105)*I
407
+ assert csch(-pi*I/105) == 1/sin(pi/105)*I
408
+
409
+ assert csch(x*I) == -1/sin(x)*I
410
+
411
+ assert csch(k*pi*I) is zoo
412
+ assert csch(17*k*pi*I) is zoo
413
+
414
+ assert csch(k*pi*I/2) == -1/sin(k*pi/2)*I
415
+
416
+ assert csch(n).is_real is True
417
+
418
+ assert expand_trig(csch(x + y)) == 1/(sinh(x)*cosh(y) + cosh(x)*sinh(y))
419
+
420
+
421
+ def test_csch_series():
422
+ x = Symbol('x')
423
+ assert csch(x).series(x, 0, 10) == \
424
+ 1/ x - x/6 + 7*x**3/360 - 31*x**5/15120 + 127*x**7/604800 \
425
+ - 73*x**9/3421440 + O(x**10)
426
+
427
+
428
+ def test_csch_fdiff():
429
+ x = Symbol('x')
430
+ raises(ArgumentIndexError, lambda: csch(x).fdiff(2))
431
+
432
+
433
+ def test_sech():
434
+ x, y = symbols('x, y')
435
+
436
+ k = Symbol('k', integer=True)
437
+ n = Symbol('n', positive=True)
438
+
439
+ assert sech(nan) is nan
440
+ assert sech(zoo) is nan
441
+
442
+ assert sech(oo) == 0
443
+ assert sech(-oo) == 0
444
+
445
+ assert sech(0) == 1
446
+
447
+ assert sech(-1) == sech(1)
448
+ assert sech(-x) == sech(x)
449
+
450
+ assert sech(pi*I) == sec(pi)
451
+
452
+ assert sech(-pi*I) == sec(pi)
453
+ assert sech(-2**1024 * E) == sech(2**1024 * E)
454
+
455
+ assert sech(pi*I/2) is zoo
456
+ assert sech(-pi*I/2) is zoo
457
+ assert sech((-3*10**73 + 1)*pi*I/2) is zoo
458
+ assert sech((7*10**103 + 1)*pi*I/2) is zoo
459
+
460
+ assert sech(pi*I) == -1
461
+ assert sech(-pi*I) == -1
462
+ assert sech(5*pi*I) == -1
463
+ assert sech(8*pi*I) == 1
464
+
465
+ assert sech(pi*I/3) == 2
466
+ assert sech(pi*I*Rational(-2, 3)) == -2
467
+
468
+ assert sech(pi*I/4) == sqrt(2)
469
+ assert sech(-pi*I/4) == sqrt(2)
470
+ assert sech(pi*I*Rational(5, 4)) == -sqrt(2)
471
+ assert sech(pi*I*Rational(-5, 4)) == -sqrt(2)
472
+
473
+ assert sech(pi*I/6) == 2/sqrt(3)
474
+ assert sech(-pi*I/6) == 2/sqrt(3)
475
+ assert sech(pi*I*Rational(7, 6)) == -2/sqrt(3)
476
+ assert sech(pi*I*Rational(-5, 6)) == -2/sqrt(3)
477
+
478
+ assert sech(pi*I/105) == 1/cos(pi/105)
479
+ assert sech(-pi*I/105) == 1/cos(pi/105)
480
+
481
+ assert sech(x*I) == 1/cos(x)
482
+
483
+ assert sech(k*pi*I) == 1/cos(k*pi)
484
+ assert sech(17*k*pi*I) == 1/cos(17*k*pi)
485
+
486
+ assert sech(n).is_real is True
487
+
488
+ assert expand_trig(sech(x + y)) == 1/(cosh(x)*cosh(y) + sinh(x)*sinh(y))
489
+
490
+
491
+ def test_sech_series():
492
+ x = Symbol('x')
493
+ assert sech(x).series(x, 0, 10) == \
494
+ 1 - x**2/2 + 5*x**4/24 - 61*x**6/720 + 277*x**8/8064 + O(x**10)
495
+
496
+
497
+ def test_sech_fdiff():
498
+ x = Symbol('x')
499
+ raises(ArgumentIndexError, lambda: sech(x).fdiff(2))
500
+
501
+
502
+ def test_asinh():
503
+ x, y = symbols('x,y')
504
+ assert unchanged(asinh, x)
505
+ assert asinh(-x) == -asinh(x)
506
+
507
+ #at specific points
508
+ assert asinh(nan) is nan
509
+ assert asinh( 0) == 0
510
+ assert asinh(+1) == log(sqrt(2) + 1)
511
+
512
+ assert asinh(-1) == log(sqrt(2) - 1)
513
+ assert asinh(I) == pi*I/2
514
+ assert asinh(-I) == -pi*I/2
515
+ assert asinh(I/2) == pi*I/6
516
+ assert asinh(-I/2) == -pi*I/6
517
+
518
+ # at infinites
519
+ assert asinh(oo) is oo
520
+ assert asinh(-oo) is -oo
521
+
522
+ assert asinh(I*oo) is oo
523
+ assert asinh(-I *oo) is -oo
524
+
525
+ assert asinh(zoo) is zoo
526
+
527
+ #properties
528
+ assert asinh(I *(sqrt(3) - 1)/(2**Rational(3, 2))) == pi*I/12
529
+ assert asinh(-I *(sqrt(3) - 1)/(2**Rational(3, 2))) == -pi*I/12
530
+
531
+ assert asinh(I*(sqrt(5) - 1)/4) == pi*I/10
532
+ assert asinh(-I*(sqrt(5) - 1)/4) == -pi*I/10
533
+
534
+ assert asinh(I*(sqrt(5) + 1)/4) == pi*I*Rational(3, 10)
535
+ assert asinh(-I*(sqrt(5) + 1)/4) == pi*I*Rational(-3, 10)
536
+
537
+ # Symmetry
538
+ assert asinh(Rational(-1, 2)) == -asinh(S.Half)
539
+
540
+ # inverse composition
541
+ assert unchanged(asinh, sinh(Symbol('v1')))
542
+
543
+ assert asinh(sinh(0, evaluate=False)) == 0
544
+ assert asinh(sinh(-3, evaluate=False)) == -3
545
+ assert asinh(sinh(2, evaluate=False)) == 2
546
+ assert asinh(sinh(I, evaluate=False)) == I
547
+ assert asinh(sinh(-I, evaluate=False)) == -I
548
+ assert asinh(sinh(5*I, evaluate=False)) == -2*I*pi + 5*I
549
+ assert asinh(sinh(15 + 11*I)) == 15 - 4*I*pi + 11*I
550
+ assert asinh(sinh(-73 + 97*I)) == 73 - 97*I + 31*I*pi
551
+ assert asinh(sinh(-7 - 23*I)) == 7 - 7*I*pi + 23*I
552
+ assert asinh(sinh(13 - 3*I)) == -13 - I*pi + 3*I
553
+ p = Symbol('p', positive=True)
554
+ assert asinh(p).is_zero is False
555
+ assert asinh(sinh(0, evaluate=False), evaluate=False).is_zero is True
556
+
557
+
558
+ def test_asinh_rewrite():
559
+ x = Symbol('x')
560
+ assert asinh(x).rewrite(log) == log(x + sqrt(x**2 + 1))
561
+ assert asinh(x).rewrite(atanh) == atanh(x/sqrt(1 + x**2))
562
+ assert asinh(x).rewrite(asin) == asinh(x)
563
+ assert asinh(x*(1 + I)).rewrite(asin) == -I*asin(I*x*(1+I))
564
+ assert asinh(x).rewrite(acos) == I*(-I*asinh(x) + pi/2) - I*pi/2
565
+
566
+
567
+ def test_asinh_leading_term():
568
+ x = Symbol('x')
569
+ assert asinh(x).as_leading_term(x, cdir=1) == x
570
+ # Tests concerning branch points
571
+ assert asinh(x + I).as_leading_term(x, cdir=1) == I*pi/2
572
+ assert asinh(x - I).as_leading_term(x, cdir=1) == -I*pi/2
573
+ assert asinh(1/x).as_leading_term(x, cdir=1) == -log(x) + log(2)
574
+ assert asinh(1/x).as_leading_term(x, cdir=-1) == log(x) - log(2) - I*pi
575
+ # Tests concerning points lying on branch cuts
576
+ assert asinh(x + 2*I).as_leading_term(x, cdir=1) == I*asin(2)
577
+ assert asinh(x + 2*I).as_leading_term(x, cdir=-1) == -I*asin(2) + I*pi
578
+ assert asinh(x - 2*I).as_leading_term(x, cdir=1) == -I*pi + I*asin(2)
579
+ assert asinh(x - 2*I).as_leading_term(x, cdir=-1) == -I*asin(2)
580
+ # Tests concerning re(ndir) == 0
581
+ assert asinh(2*I + I*x - x**2).as_leading_term(x, cdir=1) == log(2 - sqrt(3)) + I*pi/2
582
+ assert asinh(2*I + I*x - x**2).as_leading_term(x, cdir=-1) == log(2 - sqrt(3)) + I*pi/2
583
+
584
+
585
+ def test_asinh_series():
586
+ x = Symbol('x')
587
+ assert asinh(x).series(x, 0, 8) == \
588
+ x - x**3/6 + 3*x**5/40 - 5*x**7/112 + O(x**8)
589
+ t5 = asinh(x).taylor_term(5, x)
590
+ assert t5 == 3*x**5/40
591
+ assert asinh(x).taylor_term(7, x, t5, 0) == -5*x**7/112
592
+
593
+
594
+ def test_asinh_nseries():
595
+ x = Symbol('x')
596
+ # Tests concerning branch points
597
+ assert asinh(x + I)._eval_nseries(x, 4, None) == I*pi/2 + \
598
+ sqrt(x)*(1 - I) + x**(S(3)/2)*(S(1)/12 + I/12) + x**(S(5)/2)*(-S(3)/160 + 3*I/160) + \
599
+ x**(S(7)/2)*(-S(5)/896 - 5*I/896) + O(x**4)
600
+ assert asinh(x - I)._eval_nseries(x, 4, None) == -I*pi/2 + \
601
+ sqrt(x)*(1 + I) + x**(S(3)/2)*(S(1)/12 - I/12) + x**(S(5)/2)*(-S(3)/160 - 3*I/160) + \
602
+ x**(S(7)/2)*(-S(5)/896 + 5*I/896) + O(x**4)
603
+ # Tests concerning points lying on branch cuts
604
+ assert asinh(x + 2*I)._eval_nseries(x, 4, None, cdir=1) == I*asin(2) - \
605
+ sqrt(3)*I*x/3 + sqrt(3)*x**2/9 + sqrt(3)*I*x**3/18 + O(x**4)
606
+ assert asinh(x + 2*I)._eval_nseries(x, 4, None, cdir=-1) == I*pi - I*asin(2) + \
607
+ sqrt(3)*I*x/3 - sqrt(3)*x**2/9 - sqrt(3)*I*x**3/18 + O(x**4)
608
+ assert asinh(x - 2*I)._eval_nseries(x, 4, None, cdir=1) == I*asin(2) - I*pi + \
609
+ sqrt(3)*I*x/3 + sqrt(3)*x**2/9 - sqrt(3)*I*x**3/18 + O(x**4)
610
+ assert asinh(x - 2*I)._eval_nseries(x, 4, None, cdir=-1) == -I*asin(2) - \
611
+ sqrt(3)*I*x/3 - sqrt(3)*x**2/9 + sqrt(3)*I*x**3/18 + O(x**4)
612
+ # Tests concerning re(ndir) == 0
613
+ assert asinh(2*I + I*x - x**2)._eval_nseries(x, 4, None) == I*pi/2 + log(2 - sqrt(3)) - \
614
+ sqrt(3)*x/3 + x**2*(sqrt(3)/9 - sqrt(3)*I/3) + x**3*(-sqrt(3)/18 + 2*sqrt(3)*I/9) + O(x**4)
615
+
616
+
617
+ def test_asinh_fdiff():
618
+ x = Symbol('x')
619
+ raises(ArgumentIndexError, lambda: asinh(x).fdiff(2))
620
+
621
+
622
+ def test_acosh():
623
+ x = Symbol('x')
624
+
625
+ assert unchanged(acosh, -x)
626
+
627
+ #at specific points
628
+ assert acosh(1) == 0
629
+ assert acosh(-1) == pi*I
630
+ assert acosh(0) == I*pi/2
631
+ assert acosh(S.Half) == I*pi/3
632
+ assert acosh(Rational(-1, 2)) == pi*I*Rational(2, 3)
633
+ assert acosh(nan) is nan
634
+
635
+ # at infinites
636
+ assert acosh(oo) is oo
637
+ assert acosh(-oo) is oo
638
+
639
+ assert acosh(I*oo) == oo + I*pi/2
640
+ assert acosh(-I*oo) == oo - I*pi/2
641
+
642
+ assert acosh(zoo) is zoo
643
+
644
+ assert acosh(I) == log(I*(1 + sqrt(2)))
645
+ assert acosh(-I) == log(-I*(1 + sqrt(2)))
646
+ assert acosh((sqrt(3) - 1)/(2*sqrt(2))) == pi*I*Rational(5, 12)
647
+ assert acosh(-(sqrt(3) - 1)/(2*sqrt(2))) == pi*I*Rational(7, 12)
648
+ assert acosh(sqrt(2)/2) == I*pi/4
649
+ assert acosh(-sqrt(2)/2) == I*pi*Rational(3, 4)
650
+ assert acosh(sqrt(3)/2) == I*pi/6
651
+ assert acosh(-sqrt(3)/2) == I*pi*Rational(5, 6)
652
+ assert acosh(sqrt(2 + sqrt(2))/2) == I*pi/8
653
+ assert acosh(-sqrt(2 + sqrt(2))/2) == I*pi*Rational(7, 8)
654
+ assert acosh(sqrt(2 - sqrt(2))/2) == I*pi*Rational(3, 8)
655
+ assert acosh(-sqrt(2 - sqrt(2))/2) == I*pi*Rational(5, 8)
656
+ assert acosh((1 + sqrt(3))/(2*sqrt(2))) == I*pi/12
657
+ assert acosh(-(1 + sqrt(3))/(2*sqrt(2))) == I*pi*Rational(11, 12)
658
+ assert acosh((sqrt(5) + 1)/4) == I*pi/5
659
+ assert acosh(-(sqrt(5) + 1)/4) == I*pi*Rational(4, 5)
660
+
661
+ assert str(acosh(5*I).n(6)) == '2.31244 + 1.5708*I'
662
+ assert str(acosh(-5*I).n(6)) == '2.31244 - 1.5708*I'
663
+
664
+ # inverse composition
665
+ assert unchanged(acosh, Symbol('v1'))
666
+
667
+ assert acosh(cosh(-3, evaluate=False)) == 3
668
+ assert acosh(cosh(3, evaluate=False)) == 3
669
+ assert acosh(cosh(0, evaluate=False)) == 0
670
+ assert acosh(cosh(I, evaluate=False)) == I
671
+ assert acosh(cosh(-I, evaluate=False)) == I
672
+ assert acosh(cosh(7*I, evaluate=False)) == -2*I*pi + 7*I
673
+ assert acosh(cosh(1 + I)) == 1 + I
674
+ assert acosh(cosh(3 - 3*I)) == 3 - 3*I
675
+ assert acosh(cosh(-3 + 2*I)) == 3 - 2*I
676
+ assert acosh(cosh(-5 - 17*I)) == 5 - 6*I*pi + 17*I
677
+ assert acosh(cosh(-21 + 11*I)) == 21 - 11*I + 4*I*pi
678
+ assert acosh(cosh(cosh(1) + I)) == cosh(1) + I
679
+ assert acosh(1, evaluate=False).is_zero is True
680
+
681
+
682
+ def test_acosh_rewrite():
683
+ x = Symbol('x')
684
+ assert acosh(x).rewrite(log) == log(x + sqrt(x - 1)*sqrt(x + 1))
685
+ assert acosh(x).rewrite(asin) == sqrt(x - 1)*(-asin(x) + pi/2)/sqrt(1 - x)
686
+ assert acosh(x).rewrite(asinh) == sqrt(x - 1)*(-asin(x) + pi/2)/sqrt(1 - x)
687
+ assert acosh(x).rewrite(atanh) == \
688
+ (sqrt(x - 1)*sqrt(x + 1)*atanh(sqrt(x**2 - 1)/x)/sqrt(x**2 - 1) +
689
+ pi*sqrt(x - 1)*(-x*sqrt(x**(-2)) + 1)/(2*sqrt(1 - x)))
690
+ x = Symbol('x', positive=True)
691
+ assert acosh(x).rewrite(atanh) == \
692
+ sqrt(x - 1)*sqrt(x + 1)*atanh(sqrt(x**2 - 1)/x)/sqrt(x**2 - 1)
693
+
694
+
695
+ def test_acosh_leading_term():
696
+ x = Symbol('x')
697
+ # Tests concerning branch points
698
+ assert acosh(x).as_leading_term(x) == I*pi/2
699
+ assert acosh(x + 1).as_leading_term(x) == sqrt(2)*sqrt(x)
700
+ assert acosh(x - 1).as_leading_term(x) == I*pi
701
+ assert acosh(1/x).as_leading_term(x, cdir=1) == -log(x) + log(2)
702
+ assert acosh(1/x).as_leading_term(x, cdir=-1) == -log(x) + log(2) + 2*I*pi
703
+ # Tests concerning points lying on branch cuts
704
+ assert acosh(I*x - 2).as_leading_term(x, cdir=1) == acosh(-2)
705
+ assert acosh(-I*x - 2).as_leading_term(x, cdir=1) == -2*I*pi + acosh(-2)
706
+ assert acosh(x**2 - I*x + S(1)/3).as_leading_term(x, cdir=1) == -acosh(S(1)/3)
707
+ assert acosh(x**2 - I*x + S(1)/3).as_leading_term(x, cdir=-1) == acosh(S(1)/3)
708
+ assert acosh(1/(I*x - 3)).as_leading_term(x, cdir=1) == -acosh(-S(1)/3)
709
+ assert acosh(1/(I*x - 3)).as_leading_term(x, cdir=-1) == acosh(-S(1)/3)
710
+ # Tests concerning im(ndir) == 0
711
+ assert acosh(-I*x**2 + x - 2).as_leading_term(x, cdir=1) == log(sqrt(3) + 2) - I*pi
712
+ assert acosh(-I*x**2 + x - 2).as_leading_term(x, cdir=-1) == log(sqrt(3) + 2) - I*pi
713
+
714
+
715
+ def test_acosh_series():
716
+ x = Symbol('x')
717
+ assert acosh(x).series(x, 0, 8) == \
718
+ -I*x + pi*I/2 - I*x**3/6 - 3*I*x**5/40 - 5*I*x**7/112 + O(x**8)
719
+ t5 = acosh(x).taylor_term(5, x)
720
+ assert t5 == - 3*I*x**5/40
721
+ assert acosh(x).taylor_term(7, x, t5, 0) == - 5*I*x**7/112
722
+
723
+
724
+ def test_acosh_nseries():
725
+ x = Symbol('x')
726
+ # Tests concerning branch points
727
+ assert acosh(x + 1)._eval_nseries(x, 4, None) == sqrt(2)*sqrt(x) - \
728
+ sqrt(2)*x**(S(3)/2)/12 + 3*sqrt(2)*x**(S(5)/2)/160 - 5*sqrt(2)*x**(S(7)/2)/896 + O(x**4)
729
+ # Tests concerning points lying on branch cuts
730
+ assert acosh(x - 1)._eval_nseries(x, 4, None) == I*pi - \
731
+ sqrt(2)*I*sqrt(x) - sqrt(2)*I*x**(S(3)/2)/12 - 3*sqrt(2)*I*x**(S(5)/2)/160 - \
732
+ 5*sqrt(2)*I*x**(S(7)/2)/896 + O(x**4)
733
+ assert acosh(I*x - 2)._eval_nseries(x, 4, None, cdir=1) == acosh(-2) - \
734
+ sqrt(3)*I*x/3 + sqrt(3)*x**2/9 + sqrt(3)*I*x**3/18 + O(x**4)
735
+ assert acosh(-I*x - 2)._eval_nseries(x, 4, None, cdir=1) == acosh(-2) - \
736
+ 2*I*pi + sqrt(3)*I*x/3 + sqrt(3)*x**2/9 - sqrt(3)*I*x**3/18 + O(x**4)
737
+ assert acosh(1/(I*x - 3))._eval_nseries(x, 4, None, cdir=1) == -acosh(-S(1)/3) + \
738
+ sqrt(2)*x/12 + 17*sqrt(2)*I*x**2/576 - 443*sqrt(2)*x**3/41472 + O(x**4)
739
+ assert acosh(1/(I*x - 3))._eval_nseries(x, 4, None, cdir=-1) == acosh(-S(1)/3) - \
740
+ sqrt(2)*x/12 - 17*sqrt(2)*I*x**2/576 + 443*sqrt(2)*x**3/41472 + O(x**4)
741
+ # Tests concerning im(ndir) == 0
742
+ assert acosh(-I*x**2 + x - 2)._eval_nseries(x, 4, None) == -I*pi + log(sqrt(3) + 2) - \
743
+ sqrt(3)*x/3 + x**2*(-sqrt(3)/9 + sqrt(3)*I/3) + x**3*(-sqrt(3)/18 + 2*sqrt(3)*I/9) + O(x**4)
744
+
745
+
746
+ def test_acosh_fdiff():
747
+ x = Symbol('x')
748
+ raises(ArgumentIndexError, lambda: acosh(x).fdiff(2))
749
+
750
+
751
+ def test_asech():
752
+ x = Symbol('x')
753
+
754
+ assert unchanged(asech, -x)
755
+
756
+ # values at fixed points
757
+ assert asech(1) == 0
758
+ assert asech(-1) == pi*I
759
+ assert asech(0) is oo
760
+ assert asech(2) == I*pi/3
761
+ assert asech(-2) == 2*I*pi / 3
762
+ assert asech(nan) is nan
763
+
764
+ # at infinites
765
+ assert asech(oo) == I*pi/2
766
+ assert asech(-oo) == I*pi/2
767
+ assert asech(zoo) == I*AccumBounds(-pi/2, pi/2)
768
+
769
+ assert asech(I) == log(1 + sqrt(2)) - I*pi/2
770
+ assert asech(-I) == log(1 + sqrt(2)) + I*pi/2
771
+ assert asech(sqrt(2) - sqrt(6)) == 11*I*pi / 12
772
+ assert asech(sqrt(2 - 2/sqrt(5))) == I*pi / 10
773
+ assert asech(-sqrt(2 - 2/sqrt(5))) == 9*I*pi / 10
774
+ assert asech(2 / sqrt(2 + sqrt(2))) == I*pi / 8
775
+ assert asech(-2 / sqrt(2 + sqrt(2))) == 7*I*pi / 8
776
+ assert asech(sqrt(5) - 1) == I*pi / 5
777
+ assert asech(1 - sqrt(5)) == 4*I*pi / 5
778
+ assert asech(-sqrt(2*(2 + sqrt(2)))) == 5*I*pi / 8
779
+
780
+ # properties
781
+ # asech(x) == acosh(1/x)
782
+ assert asech(sqrt(2)) == acosh(1/sqrt(2))
783
+ assert asech(2/sqrt(3)) == acosh(sqrt(3)/2)
784
+ assert asech(2/sqrt(2 + sqrt(2))) == acosh(sqrt(2 + sqrt(2))/2)
785
+ assert asech(2) == acosh(S.Half)
786
+
787
+ # asech(x) == I*acos(1/x)
788
+ # (Note: the exact formula is asech(x) == +/- I*acos(1/x))
789
+ assert asech(-sqrt(2)) == I*acos(-1/sqrt(2))
790
+ assert asech(-2/sqrt(3)) == I*acos(-sqrt(3)/2)
791
+ assert asech(-S(2)) == I*acos(Rational(-1, 2))
792
+ assert asech(-2/sqrt(2)) == I*acos(-sqrt(2)/2)
793
+
794
+ # sech(asech(x)) / x == 1
795
+ assert expand_mul(sech(asech(sqrt(6) - sqrt(2))) / (sqrt(6) - sqrt(2))) == 1
796
+ assert expand_mul(sech(asech(sqrt(6) + sqrt(2))) / (sqrt(6) + sqrt(2))) == 1
797
+ assert (sech(asech(sqrt(2 + 2/sqrt(5)))) / (sqrt(2 + 2/sqrt(5)))).simplify() == 1
798
+ assert (sech(asech(-sqrt(2 + 2/sqrt(5)))) / (-sqrt(2 + 2/sqrt(5)))).simplify() == 1
799
+ assert (sech(asech(sqrt(2*(2 + sqrt(2))))) / (sqrt(2*(2 + sqrt(2))))).simplify() == 1
800
+ assert expand_mul(sech(asech(1 + sqrt(5))) / (1 + sqrt(5))) == 1
801
+ assert expand_mul(sech(asech(-1 - sqrt(5))) / (-1 - sqrt(5))) == 1
802
+ assert expand_mul(sech(asech(-sqrt(6) - sqrt(2))) / (-sqrt(6) - sqrt(2))) == 1
803
+
804
+ # numerical evaluation
805
+ assert str(asech(5*I).n(6)) == '0.19869 - 1.5708*I'
806
+ assert str(asech(-5*I).n(6)) == '0.19869 + 1.5708*I'
807
+
808
+
809
+ def test_asech_leading_term():
810
+ x = Symbol('x')
811
+ # Tests concerning branch points
812
+ assert asech(x).as_leading_term(x, cdir=1) == -log(x) + log(2)
813
+ assert asech(x).as_leading_term(x, cdir=-1) == -log(x) + log(2) + 2*I*pi
814
+ assert asech(x + 1).as_leading_term(x, cdir=1) == sqrt(2)*I*sqrt(x)
815
+ assert asech(1/x).as_leading_term(x, cdir=1) == I*pi/2
816
+ # Tests concerning points lying on branch cuts
817
+ assert asech(x - 1).as_leading_term(x, cdir=1) == I*pi
818
+ assert asech(I*x + 3).as_leading_term(x, cdir=1) == -asech(3)
819
+ assert asech(-I*x + 3).as_leading_term(x, cdir=1) == asech(3)
820
+ assert asech(I*x - 3).as_leading_term(x, cdir=1) == -asech(-3)
821
+ assert asech(-I*x - 3).as_leading_term(x, cdir=1) == asech(-3)
822
+ assert asech(I*x - S(1)/3).as_leading_term(x, cdir=1) == -2*I*pi + asech(-S(1)/3)
823
+ assert asech(I*x - S(1)/3).as_leading_term(x, cdir=-1) == asech(-S(1)/3)
824
+ # Tests concerning im(ndir) == 0
825
+ assert asech(-I*x**2 + x - 3).as_leading_term(x, cdir=1) == log(-S(1)/3 + 2*sqrt(2)*I/3)
826
+ assert asech(-I*x**2 + x - 3).as_leading_term(x, cdir=-1) == log(-S(1)/3 + 2*sqrt(2)*I/3)
827
+
828
+
829
+ def test_asech_series():
830
+ x = Symbol('x')
831
+ assert asech(x).series(x, 0, 9, cdir=1) == log(2) - log(x) - x**2/4 - 3*x**4/32 \
832
+ - 5*x**6/96 - 35*x**8/1024 + O(x**9)
833
+ assert asech(x).series(x, 0, 9, cdir=-1) == I*pi + log(2) - log(-x) - x**2/4 - \
834
+ 3*x**4/32 - 5*x**6/96 - 35*x**8/1024 + O(x**9)
835
+ t6 = asech(x).taylor_term(6, x)
836
+ assert t6 == -5*x**6/96
837
+ assert asech(x).taylor_term(8, x, t6, 0) == -35*x**8/1024
838
+
839
+
840
+ def test_asech_nseries():
841
+ x = Symbol('x')
842
+ # Tests concerning branch points
843
+ assert asech(x + 1)._eval_nseries(x, 4, None) == sqrt(2)*sqrt(-x) + 5*sqrt(2)*(-x)**(S(3)/2)/12 + \
844
+ 43*sqrt(2)*(-x)**(S(5)/2)/160 + 177*sqrt(2)*(-x)**(S(7)/2)/896 + O(x**4)
845
+ # Tests concerning points lying on branch cuts
846
+ assert asech(x - 1)._eval_nseries(x, 4, None) == I*pi + sqrt(2)*sqrt(x) + \
847
+ 5*sqrt(2)*x**(S(3)/2)/12 + 43*sqrt(2)*x**(S(5)/2)/160 + 177*sqrt(2)*x**(S(7)/2)/896 + O(x**4)
848
+ assert asech(I*x + 3)._eval_nseries(x, 4, None) == -asech(3) + sqrt(2)*x/12 - \
849
+ 17*sqrt(2)*I*x**2/576 - 443*sqrt(2)*x**3/41472 + O(x**4)
850
+ assert asech(-I*x + 3)._eval_nseries(x, 4, None) == asech(3) + sqrt(2)*x/12 + \
851
+ 17*sqrt(2)*I*x**2/576 - 443*sqrt(2)*x**3/41472 + O(x**4)
852
+ assert asech(I*x - 3)._eval_nseries(x, 4, None) == -asech(-3) - sqrt(2)*x/12 - \
853
+ 17*sqrt(2)*I*x**2/576 + 443*sqrt(2)*x**3/41472 + O(x**4)
854
+ assert asech(-I*x - 3)._eval_nseries(x, 4, None) == asech(-3) - sqrt(2)*x/12 + \
855
+ 17*sqrt(2)*I*x**2/576 + 443*sqrt(2)*x**3/41472 + O(x**4)
856
+ # Tests concerning im(ndir) == 0
857
+ assert asech(-I*x**2 + x - 2)._eval_nseries(x, 3, None) == 2*I*pi/3 + sqrt(3)*I*x/6 + \
858
+ x**2*(sqrt(3)/6 + 7*sqrt(3)*I/72) + O(x**3)
859
+
860
+
861
+ def test_asech_rewrite():
862
+ x = Symbol('x')
863
+ assert asech(x).rewrite(log) == log(1/x + sqrt(1/x - 1) * sqrt(1/x + 1))
864
+ assert asech(x).rewrite(acosh) == acosh(1/x)
865
+ assert asech(x).rewrite(asinh) == sqrt(-1 + 1/x)*(-asin(1/x) + pi/2)/sqrt(1 - 1/x)
866
+ assert asech(x).rewrite(atanh) == \
867
+ sqrt(x + 1)*sqrt(1/(x + 1))*atanh(sqrt(1 - x**2)) + I*pi*(-sqrt(x)*sqrt(1/x) + 1 - I*sqrt(x**2)/(2*sqrt(-x**2)) - I*sqrt(-x)/(2*sqrt(x)))
868
+
869
+
870
+ def test_asech_fdiff():
871
+ x = Symbol('x')
872
+ raises(ArgumentIndexError, lambda: asech(x).fdiff(2))
873
+
874
+
875
+ def test_acsch():
876
+ x = Symbol('x')
877
+
878
+ assert unchanged(acsch, x)
879
+ assert acsch(-x) == -acsch(x)
880
+
881
+ # values at fixed points
882
+ assert acsch(1) == log(1 + sqrt(2))
883
+ assert acsch(-1) == - log(1 + sqrt(2))
884
+ assert acsch(0) is zoo
885
+ assert acsch(2) == log((1+sqrt(5))/2)
886
+ assert acsch(-2) == - log((1+sqrt(5))/2)
887
+
888
+ assert acsch(I) == - I*pi/2
889
+ assert acsch(-I) == I*pi/2
890
+ assert acsch(-I*(sqrt(6) + sqrt(2))) == I*pi / 12
891
+ assert acsch(I*(sqrt(2) + sqrt(6))) == -I*pi / 12
892
+ assert acsch(-I*(1 + sqrt(5))) == I*pi / 10
893
+ assert acsch(I*(1 + sqrt(5))) == -I*pi / 10
894
+ assert acsch(-I*2 / sqrt(2 - sqrt(2))) == I*pi / 8
895
+ assert acsch(I*2 / sqrt(2 - sqrt(2))) == -I*pi / 8
896
+ assert acsch(-I*2) == I*pi / 6
897
+ assert acsch(I*2) == -I*pi / 6
898
+ assert acsch(-I*sqrt(2 + 2/sqrt(5))) == I*pi / 5
899
+ assert acsch(I*sqrt(2 + 2/sqrt(5))) == -I*pi / 5
900
+ assert acsch(-I*sqrt(2)) == I*pi / 4
901
+ assert acsch(I*sqrt(2)) == -I*pi / 4
902
+ assert acsch(-I*(sqrt(5)-1)) == 3*I*pi / 10
903
+ assert acsch(I*(sqrt(5)-1)) == -3*I*pi / 10
904
+ assert acsch(-I*2 / sqrt(3)) == I*pi / 3
905
+ assert acsch(I*2 / sqrt(3)) == -I*pi / 3
906
+ assert acsch(-I*2 / sqrt(2 + sqrt(2))) == 3*I*pi / 8
907
+ assert acsch(I*2 / sqrt(2 + sqrt(2))) == -3*I*pi / 8
908
+ assert acsch(-I*sqrt(2 - 2/sqrt(5))) == 2*I*pi / 5
909
+ assert acsch(I*sqrt(2 - 2/sqrt(5))) == -2*I*pi / 5
910
+ assert acsch(-I*(sqrt(6) - sqrt(2))) == 5*I*pi / 12
911
+ assert acsch(I*(sqrt(6) - sqrt(2))) == -5*I*pi / 12
912
+ assert acsch(nan) is nan
913
+
914
+ # properties
915
+ # acsch(x) == asinh(1/x)
916
+ assert acsch(-I*sqrt(2)) == asinh(I/sqrt(2))
917
+ assert acsch(-I*2 / sqrt(3)) == asinh(I*sqrt(3) / 2)
918
+
919
+ # acsch(x) == -I*asin(I/x)
920
+ assert acsch(-I*sqrt(2)) == -I*asin(-1/sqrt(2))
921
+ assert acsch(-I*2 / sqrt(3)) == -I*asin(-sqrt(3)/2)
922
+
923
+ # csch(acsch(x)) / x == 1
924
+ assert expand_mul(csch(acsch(-I*(sqrt(6) + sqrt(2)))) / (-I*(sqrt(6) + sqrt(2)))) == 1
925
+ assert expand_mul(csch(acsch(I*(1 + sqrt(5)))) / (I*(1 + sqrt(5)))) == 1
926
+ assert (csch(acsch(I*sqrt(2 - 2/sqrt(5)))) / (I*sqrt(2 - 2/sqrt(5)))).simplify() == 1
927
+ assert (csch(acsch(-I*sqrt(2 - 2/sqrt(5)))) / (-I*sqrt(2 - 2/sqrt(5)))).simplify() == 1
928
+
929
+ # numerical evaluation
930
+ assert str(acsch(5*I+1).n(6)) == '0.0391819 - 0.193363*I'
931
+ assert str(acsch(-5*I+1).n(6)) == '0.0391819 + 0.193363*I'
932
+
933
+
934
+ def test_acsch_infinities():
935
+ assert acsch(oo) == 0
936
+ assert acsch(-oo) == 0
937
+ assert acsch(zoo) == 0
938
+
939
+
940
+ def test_acsch_leading_term():
941
+ x = Symbol('x')
942
+ assert acsch(1/x).as_leading_term(x) == x
943
+ # Tests concerning branch points
944
+ assert acsch(x + I).as_leading_term(x) == -I*pi/2
945
+ assert acsch(x - I).as_leading_term(x) == I*pi/2
946
+ # Tests concerning points lying on branch cuts
947
+ assert acsch(x).as_leading_term(x, cdir=1) == -log(x) + log(2)
948
+ assert acsch(x).as_leading_term(x, cdir=-1) == log(x) - log(2) - I*pi
949
+ assert acsch(x + I/2).as_leading_term(x, cdir=1) == -I*pi - acsch(I/2)
950
+ assert acsch(x + I/2).as_leading_term(x, cdir=-1) == acsch(I/2)
951
+ assert acsch(x - I/2).as_leading_term(x, cdir=1) == -acsch(I/2)
952
+ assert acsch(x - I/2).as_leading_term(x, cdir=-1) == acsch(I/2) + I*pi
953
+ # Tests concerning re(ndir) == 0
954
+ assert acsch(I/2 + I*x - x**2).as_leading_term(x, cdir=1) == log(2 - sqrt(3)) - I*pi/2
955
+ assert acsch(I/2 + I*x - x**2).as_leading_term(x, cdir=-1) == log(2 - sqrt(3)) - I*pi/2
956
+
957
+
958
+ def test_acsch_series():
959
+ x = Symbol('x')
960
+ assert acsch(x).series(x, 0, 9) == log(2) - log(x) + x**2/4 - 3*x**4/32 \
961
+ + 5*x**6/96 - 35*x**8/1024 + O(x**9)
962
+ t4 = acsch(x).taylor_term(4, x)
963
+ assert t4 == -3*x**4/32
964
+ assert acsch(x).taylor_term(6, x, t4, 0) == 5*x**6/96
965
+
966
+
967
+ def test_acsch_nseries():
968
+ x = Symbol('x')
969
+ # Tests concerning branch points
970
+ assert acsch(x + I)._eval_nseries(x, 4, None) == -I*pi/2 + I*sqrt(x) + \
971
+ sqrt(x) + 5*I*x**(S(3)/2)/12 - 5*x**(S(3)/2)/12 - 43*I*x**(S(5)/2)/160 - \
972
+ 43*x**(S(5)/2)/160 - 177*I*x**(S(7)/2)/896 + 177*x**(S(7)/2)/896 + O(x**4)
973
+ assert acsch(x - I)._eval_nseries(x, 4, None) == I*pi/2 - I*sqrt(x) + \
974
+ sqrt(x) - 5*I*x**(S(3)/2)/12 - 5*x**(S(3)/2)/12 + 43*I*x**(S(5)/2)/160 - \
975
+ 43*x**(S(5)/2)/160 + 177*I*x**(S(7)/2)/896 + 177*x**(S(7)/2)/896 + O(x**4)
976
+ # Tests concerning points lying on branch cuts
977
+ assert acsch(x + I/2)._eval_nseries(x, 4, None, cdir=1) == -acsch(I/2) - \
978
+ I*pi + 4*sqrt(3)*I*x/3 - 8*sqrt(3)*x**2/9 - 16*sqrt(3)*I*x**3/9 + O(x**4)
979
+ assert acsch(x + I/2)._eval_nseries(x, 4, None, cdir=-1) == acsch(I/2) - \
980
+ 4*sqrt(3)*I*x/3 + 8*sqrt(3)*x**2/9 + 16*sqrt(3)*I*x**3/9 + O(x**4)
981
+ assert acsch(x - I/2)._eval_nseries(x, 4, None, cdir=1) == -acsch(I/2) - \
982
+ 4*sqrt(3)*I*x/3 - 8*sqrt(3)*x**2/9 + 16*sqrt(3)*I*x**3/9 + O(x**4)
983
+ assert acsch(x - I/2)._eval_nseries(x, 4, None, cdir=-1) == I*pi + \
984
+ acsch(I/2) + 4*sqrt(3)*I*x/3 + 8*sqrt(3)*x**2/9 - 16*sqrt(3)*I*x**3/9 + O(x**4)
985
+ # TODO: Tests concerning re(ndir) == 0
986
+ assert acsch(I/2 + I*x - x**2)._eval_nseries(x, 4, None) == -I*pi/2 + \
987
+ log(2 - sqrt(3)) + 4*sqrt(3)*x/3 + x**2*(-8*sqrt(3)/9 + 4*sqrt(3)*I/3) + \
988
+ x**3*(16*sqrt(3)/9 - 16*sqrt(3)*I/9) + O(x**4)
989
+
990
+
991
+ def test_acsch_rewrite():
992
+ x = Symbol('x')
993
+ assert acsch(x).rewrite(log) == log(1/x + sqrt(1/x**2 + 1))
994
+ assert acsch(x).rewrite(asinh) == asinh(1/x)
995
+ assert acsch(x).rewrite(atanh) == (sqrt(-x**2)*(-sqrt(-(x**2 + 1)**2)
996
+ *atanh(sqrt(x**2 + 1))/(x**2 + 1)
997
+ + pi/2)/x)
998
+
999
+
1000
+ def test_acsch_fdiff():
1001
+ x = Symbol('x')
1002
+ raises(ArgumentIndexError, lambda: acsch(x).fdiff(2))
1003
+
1004
+
1005
+ def test_atanh():
1006
+ x = Symbol('x')
1007
+
1008
+ #at specific points
1009
+ assert atanh(0) == 0
1010
+ assert atanh(I) == I*pi/4
1011
+ assert atanh(-I) == -I*pi/4
1012
+ assert atanh(1) is oo
1013
+ assert atanh(-1) is -oo
1014
+ assert atanh(nan) is nan
1015
+
1016
+ # at infinites
1017
+ assert atanh(oo) == -I*pi/2
1018
+ assert atanh(-oo) == I*pi/2
1019
+
1020
+ assert atanh(I*oo) == I*pi/2
1021
+ assert atanh(-I*oo) == -I*pi/2
1022
+
1023
+ assert atanh(zoo) == I*AccumBounds(-pi/2, pi/2)
1024
+
1025
+ #properties
1026
+ assert atanh(-x) == -atanh(x)
1027
+
1028
+ assert atanh(I/sqrt(3)) == I*pi/6
1029
+ assert atanh(-I/sqrt(3)) == -I*pi/6
1030
+ assert atanh(I*sqrt(3)) == I*pi/3
1031
+ assert atanh(-I*sqrt(3)) == -I*pi/3
1032
+ assert atanh(I*(1 + sqrt(2))) == pi*I*Rational(3, 8)
1033
+ assert atanh(I*(sqrt(2) - 1)) == pi*I/8
1034
+ assert atanh(I*(1 - sqrt(2))) == -pi*I/8
1035
+ assert atanh(-I*(1 + sqrt(2))) == pi*I*Rational(-3, 8)
1036
+ assert atanh(I*sqrt(5 + 2*sqrt(5))) == I*pi*Rational(2, 5)
1037
+ assert atanh(-I*sqrt(5 + 2*sqrt(5))) == I*pi*Rational(-2, 5)
1038
+ assert atanh(I*(2 - sqrt(3))) == pi*I/12
1039
+ assert atanh(I*(sqrt(3) - 2)) == -pi*I/12
1040
+ assert atanh(oo) == -I*pi/2
1041
+
1042
+ # Symmetry
1043
+ assert atanh(Rational(-1, 2)) == -atanh(S.Half)
1044
+
1045
+ # inverse composition
1046
+ assert unchanged(atanh, tanh(Symbol('v1')))
1047
+
1048
+ assert atanh(tanh(-5, evaluate=False)) == -5
1049
+ assert atanh(tanh(0, evaluate=False)) == 0
1050
+ assert atanh(tanh(7, evaluate=False)) == 7
1051
+ assert atanh(tanh(I, evaluate=False)) == I
1052
+ assert atanh(tanh(-I, evaluate=False)) == -I
1053
+ assert atanh(tanh(-11*I, evaluate=False)) == -11*I + 4*I*pi
1054
+ assert atanh(tanh(3 + I)) == 3 + I
1055
+ assert atanh(tanh(4 + 5*I)) == 4 - 2*I*pi + 5*I
1056
+ assert atanh(tanh(pi/2)) == pi/2
1057
+ assert atanh(tanh(pi)) == pi
1058
+ assert atanh(tanh(-3 + 7*I)) == -3 - 2*I*pi + 7*I
1059
+ assert atanh(tanh(9 - I*2/3)) == 9 - I*2/3
1060
+ assert atanh(tanh(-32 - 123*I)) == -32 - 123*I + 39*I*pi
1061
+
1062
+
1063
+ def test_atanh_rewrite():
1064
+ x = Symbol('x')
1065
+ assert atanh(x).rewrite(log) == (log(1 + x) - log(1 - x)) / 2
1066
+ assert atanh(x).rewrite(asinh) == \
1067
+ pi*x/(2*sqrt(-x**2)) - sqrt(-x)*sqrt(1 - x**2)*sqrt(1/(x**2 - 1))*asinh(sqrt(1/(x**2 - 1)))/sqrt(x)
1068
+
1069
+
1070
+ def test_atanh_leading_term():
1071
+ x = Symbol('x')
1072
+ assert atanh(x).as_leading_term(x) == x
1073
+ # Tests concerning branch points
1074
+ assert atanh(x + 1).as_leading_term(x, cdir=1) == -log(x)/2 + log(2)/2 - I*pi/2
1075
+ assert atanh(x + 1).as_leading_term(x, cdir=-1) == -log(x)/2 + log(2)/2 + I*pi/2
1076
+ assert atanh(x - 1).as_leading_term(x, cdir=1) == log(x)/2 - log(2)/2
1077
+ assert atanh(x - 1).as_leading_term(x, cdir=-1) == log(x)/2 - log(2)/2
1078
+ assert atanh(1/x).as_leading_term(x, cdir=1) == -I*pi/2
1079
+ assert atanh(1/x).as_leading_term(x, cdir=-1) == I*pi/2
1080
+ # Tests concerning points lying on branch cuts
1081
+ assert atanh(I*x + 2).as_leading_term(x, cdir=1) == atanh(2) + I*pi
1082
+ assert atanh(-I*x + 2).as_leading_term(x, cdir=1) == atanh(2)
1083
+ assert atanh(I*x - 2).as_leading_term(x, cdir=1) == -atanh(2)
1084
+ assert atanh(-I*x - 2).as_leading_term(x, cdir=1) == -I*pi - atanh(2)
1085
+ # Tests concerning im(ndir) == 0
1086
+ assert atanh(-I*x**2 + x - 2).as_leading_term(x, cdir=1) == -log(3)/2 - I*pi/2
1087
+ assert atanh(-I*x**2 + x - 2).as_leading_term(x, cdir=-1) == -log(3)/2 - I*pi/2
1088
+
1089
+
1090
+ def test_atanh_series():
1091
+ x = Symbol('x')
1092
+ assert atanh(x).series(x, 0, 10) == \
1093
+ x + x**3/3 + x**5/5 + x**7/7 + x**9/9 + O(x**10)
1094
+
1095
+
1096
+ def test_atanh_nseries():
1097
+ x = Symbol('x')
1098
+ # Tests concerning branch points
1099
+ assert atanh(x + 1)._eval_nseries(x, 4, None, cdir=1) == -I*pi/2 + log(2)/2 - \
1100
+ log(x)/2 + x/4 - x**2/16 + x**3/48 + O(x**4)
1101
+ assert atanh(x + 1)._eval_nseries(x, 4, None, cdir=-1) == I*pi/2 + log(2)/2 - \
1102
+ log(x)/2 + x/4 - x**2/16 + x**3/48 + O(x**4)
1103
+ assert atanh(x - 1)._eval_nseries(x, 4, None, cdir=1) == -log(2)/2 + log(x)/2 + \
1104
+ x/4 + x**2/16 + x**3/48 + O(x**4)
1105
+ assert atanh(x - 1)._eval_nseries(x, 4, None, cdir=-1) == -log(2)/2 + log(x)/2 + \
1106
+ x/4 + x**2/16 + x**3/48 + O(x**4)
1107
+ # Tests concerning points lying on branch cuts
1108
+ assert atanh(I*x + 2)._eval_nseries(x, 4, None, cdir=1) == I*pi + atanh(2) - \
1109
+ I*x/3 - 2*x**2/9 + 13*I*x**3/81 + O(x**4)
1110
+ assert atanh(I*x + 2)._eval_nseries(x, 4, None, cdir=-1) == atanh(2) - I*x/3 - \
1111
+ 2*x**2/9 + 13*I*x**3/81 + O(x**4)
1112
+ assert atanh(I*x - 2)._eval_nseries(x, 4, None, cdir=1) == -atanh(2) - I*x/3 + \
1113
+ 2*x**2/9 + 13*I*x**3/81 + O(x**4)
1114
+ assert atanh(I*x - 2)._eval_nseries(x, 4, None, cdir=-1) == -atanh(2) - I*pi - \
1115
+ I*x/3 + 2*x**2/9 + 13*I*x**3/81 + O(x**4)
1116
+ # Tests concerning im(ndir) == 0
1117
+ assert atanh(-I*x**2 + x - 2)._eval_nseries(x, 4, None) == -I*pi/2 - log(3)/2 - x/3 + \
1118
+ x**2*(-S(1)/4 + I/2) + x**2*(S(1)/36 - I/6) + x**3*(-S(1)/6 + I/2) + x**3*(S(1)/162 - I/18) + O(x**4)
1119
+
1120
+
1121
+ def test_atanh_fdiff():
1122
+ x = Symbol('x')
1123
+ raises(ArgumentIndexError, lambda: atanh(x).fdiff(2))
1124
+
1125
+
1126
+ def test_acoth():
1127
+ x = Symbol('x')
1128
+
1129
+ #at specific points
1130
+ assert acoth(0) == I*pi/2
1131
+ assert acoth(I) == -I*pi/4
1132
+ assert acoth(-I) == I*pi/4
1133
+ assert acoth(1) is oo
1134
+ assert acoth(-1) is -oo
1135
+ assert acoth(nan) is nan
1136
+
1137
+ # at infinites
1138
+ assert acoth(oo) == 0
1139
+ assert acoth(-oo) == 0
1140
+ assert acoth(I*oo) == 0
1141
+ assert acoth(-I*oo) == 0
1142
+ assert acoth(zoo) == 0
1143
+
1144
+ #properties
1145
+ assert acoth(-x) == -acoth(x)
1146
+
1147
+ assert acoth(I/sqrt(3)) == -I*pi/3
1148
+ assert acoth(-I/sqrt(3)) == I*pi/3
1149
+ assert acoth(I*sqrt(3)) == -I*pi/6
1150
+ assert acoth(-I*sqrt(3)) == I*pi/6
1151
+ assert acoth(I*(1 + sqrt(2))) == -pi*I/8
1152
+ assert acoth(-I*(sqrt(2) + 1)) == pi*I/8
1153
+ assert acoth(I*(1 - sqrt(2))) == pi*I*Rational(3, 8)
1154
+ assert acoth(I*(sqrt(2) - 1)) == pi*I*Rational(-3, 8)
1155
+ assert acoth(I*sqrt(5 + 2*sqrt(5))) == -I*pi/10
1156
+ assert acoth(-I*sqrt(5 + 2*sqrt(5))) == I*pi/10
1157
+ assert acoth(I*(2 + sqrt(3))) == -pi*I/12
1158
+ assert acoth(-I*(2 + sqrt(3))) == pi*I/12
1159
+ assert acoth(I*(2 - sqrt(3))) == pi*I*Rational(-5, 12)
1160
+ assert acoth(I*(sqrt(3) - 2)) == pi*I*Rational(5, 12)
1161
+
1162
+ # Symmetry
1163
+ assert acoth(Rational(-1, 2)) == -acoth(S.Half)
1164
+
1165
+
1166
+ def test_acoth_rewrite():
1167
+ x = Symbol('x')
1168
+ assert acoth(x).rewrite(log) == (log(1 + 1/x) - log(1 - 1/x)) / 2
1169
+ assert acoth(x).rewrite(atanh) == atanh(1/x)
1170
+ assert acoth(x).rewrite(asinh) == \
1171
+ x*sqrt(x**(-2))*asinh(sqrt(1/(x**2 - 1))) + I*pi*(sqrt((x - 1)/x)*sqrt(x/(x - 1)) - sqrt(x/(x + 1))*sqrt(1 + 1/x))/2
1172
+
1173
+
1174
+ def test_acoth_leading_term():
1175
+ x = Symbol('x')
1176
+ # Tests concerning branch points
1177
+ assert acoth(x + 1).as_leading_term(x, cdir=1) == -log(x)/2 + log(2)/2
1178
+ assert acoth(x + 1).as_leading_term(x, cdir=-1) == -log(x)/2 + log(2)/2
1179
+ assert acoth(x - 1).as_leading_term(x, cdir=1) == log(x)/2 - log(2)/2 + I*pi/2
1180
+ assert acoth(x - 1).as_leading_term(x, cdir=-1) == log(x)/2 - log(2)/2 - I*pi/2
1181
+ # Tests concerning points lying on branch cuts
1182
+ assert acoth(x).as_leading_term(x, cdir=-1) == I*pi/2
1183
+ assert acoth(x).as_leading_term(x, cdir=1) == -I*pi/2
1184
+ assert acoth(I*x + 1/2).as_leading_term(x, cdir=1) == acoth(1/2)
1185
+ assert acoth(-I*x + 1/2).as_leading_term(x, cdir=1) == acoth(1/2) + I*pi
1186
+ assert acoth(I*x - 1/2).as_leading_term(x, cdir=1) == -I*pi - acoth(1/2)
1187
+ assert acoth(-I*x - 1/2).as_leading_term(x, cdir=1) == -acoth(1/2)
1188
+ # Tests concerning im(ndir) == 0
1189
+ assert acoth(-I*x**2 - x - S(1)/2).as_leading_term(x, cdir=1) == -log(3)/2 + I*pi/2
1190
+ assert acoth(-I*x**2 - x - S(1)/2).as_leading_term(x, cdir=-1) == -log(3)/2 + I*pi/2
1191
+
1192
+
1193
+ def test_acoth_series():
1194
+ x = Symbol('x')
1195
+ assert acoth(x).series(x, 0, 10) == \
1196
+ -I*pi/2 + x + x**3/3 + x**5/5 + x**7/7 + x**9/9 + O(x**10)
1197
+
1198
+
1199
+ def test_acoth_nseries():
1200
+ x = Symbol('x')
1201
+ # Tests concerning branch points
1202
+ assert acoth(x + 1)._eval_nseries(x, 4, None) == log(2)/2 - log(x)/2 + x/4 - \
1203
+ x**2/16 + x**3/48 + O(x**4)
1204
+ assert acoth(x - 1)._eval_nseries(x, 4, None, cdir=1) == I*pi/2 - log(2)/2 + \
1205
+ log(x)/2 + x/4 + x**2/16 + x**3/48 + O(x**4)
1206
+ assert acoth(x - 1)._eval_nseries(x, 4, None, cdir=-1) == -I*pi/2 - log(2)/2 + \
1207
+ log(x)/2 + x/4 + x**2/16 + x**3/48 + O(x**4)
1208
+ # Tests concerning points lying on branch cuts
1209
+ assert acoth(I*x + S(1)/2)._eval_nseries(x, 4, None, cdir=1) == acoth(S(1)/2) + \
1210
+ 4*I*x/3 - 8*x**2/9 - 112*I*x**3/81 + O(x**4)
1211
+ assert acoth(I*x + S(1)/2)._eval_nseries(x, 4, None, cdir=-1) == I*pi + \
1212
+ acoth(S(1)/2) + 4*I*x/3 - 8*x**2/9 - 112*I*x**3/81 + O(x**4)
1213
+ assert acoth(I*x - S(1)/2)._eval_nseries(x, 4, None, cdir=1) == -acoth(S(1)/2) - \
1214
+ I*pi + 4*I*x/3 + 8*x**2/9 - 112*I*x**3/81 + O(x**4)
1215
+ assert acoth(I*x - S(1)/2)._eval_nseries(x, 4, None, cdir=-1) == -acoth(S(1)/2) + \
1216
+ 4*I*x/3 + 8*x**2/9 - 112*I*x**3/81 + O(x**4)
1217
+ # Tests concerning im(ndir) == 0
1218
+ assert acoth(-I*x**2 - x - S(1)/2)._eval_nseries(x, 4, None) == I*pi/2 - log(3)/2 - \
1219
+ 4*x/3 + x**2*(-S(8)/9 + 2*I/3) - 2*I*x**2 + x**3*(S(104)/81 - 16*I/9) - 8*x**3/3 + O(x**4)
1220
+
1221
+
1222
+ def test_acoth_fdiff():
1223
+ x = Symbol('x')
1224
+ raises(ArgumentIndexError, lambda: acoth(x).fdiff(2))
1225
+
1226
+
1227
+ def test_inverses():
1228
+ x = Symbol('x')
1229
+ assert sinh(x).inverse() == asinh
1230
+ raises(AttributeError, lambda: cosh(x).inverse())
1231
+ assert tanh(x).inverse() == atanh
1232
+ assert coth(x).inverse() == acoth
1233
+ assert asinh(x).inverse() == sinh
1234
+ assert acosh(x).inverse() == cosh
1235
+ assert atanh(x).inverse() == tanh
1236
+ assert acoth(x).inverse() == coth
1237
+ assert asech(x).inverse() == sech
1238
+ assert acsch(x).inverse() == csch
1239
+
1240
+
1241
+ def test_leading_term():
1242
+ x = Symbol('x')
1243
+ assert cosh(x).as_leading_term(x) == 1
1244
+ assert coth(x).as_leading_term(x) == 1/x
1245
+ for func in [sinh, tanh]:
1246
+ assert func(x).as_leading_term(x) == x
1247
+ for func in [sinh, cosh, tanh, coth]:
1248
+ for ar in (1/x, S.Half):
1249
+ eq = func(ar)
1250
+ assert eq.as_leading_term(x) == eq
1251
+ for func in [csch, sech]:
1252
+ eq = func(S.Half)
1253
+ assert eq.as_leading_term(x) == eq
1254
+
1255
+
1256
+ def test_complex():
1257
+ a, b = symbols('a,b', real=True)
1258
+ z = a + b*I
1259
+ for func in [sinh, cosh, tanh, coth, sech, csch]:
1260
+ assert func(z).conjugate() == func(a - b*I)
1261
+ for deep in [True, False]:
1262
+ assert sinh(z).expand(
1263
+ complex=True, deep=deep) == sinh(a)*cos(b) + I*cosh(a)*sin(b)
1264
+ assert cosh(z).expand(
1265
+ complex=True, deep=deep) == cosh(a)*cos(b) + I*sinh(a)*sin(b)
1266
+ assert tanh(z).expand(complex=True, deep=deep) == sinh(a)*cosh(
1267
+ a)/(cos(b)**2 + sinh(a)**2) + I*sin(b)*cos(b)/(cos(b)**2 + sinh(a)**2)
1268
+ assert coth(z).expand(complex=True, deep=deep) == sinh(a)*cosh(
1269
+ a)/(sin(b)**2 + sinh(a)**2) - I*sin(b)*cos(b)/(sin(b)**2 + sinh(a)**2)
1270
+ assert csch(z).expand(complex=True, deep=deep) == cos(b) * sinh(a) / (sin(b)**2\
1271
+ *cosh(a)**2 + cos(b)**2 * sinh(a)**2) - I*sin(b) * cosh(a) / (sin(b)**2\
1272
+ *cosh(a)**2 + cos(b)**2 * sinh(a)**2)
1273
+ assert sech(z).expand(complex=True, deep=deep) == cos(b) * cosh(a) / (sin(b)**2\
1274
+ *sinh(a)**2 + cos(b)**2 * cosh(a)**2) - I*sin(b) * sinh(a) / (sin(b)**2\
1275
+ *sinh(a)**2 + cos(b)**2 * cosh(a)**2)
1276
+
1277
+
1278
+ def test_complex_2899():
1279
+ a, b = symbols('a,b', real=True)
1280
+ for deep in [True, False]:
1281
+ for func in [sinh, cosh, tanh, coth]:
1282
+ assert func(a).expand(complex=True, deep=deep) == func(a)
1283
+
1284
+
1285
+ def test_simplifications():
1286
+ x = Symbol('x')
1287
+ assert sinh(asinh(x)) == x
1288
+ assert sinh(acosh(x)) == sqrt(x - 1) * sqrt(x + 1)
1289
+ assert sinh(atanh(x)) == x/sqrt(1 - x**2)
1290
+ assert sinh(acoth(x)) == 1/(sqrt(x - 1) * sqrt(x + 1))
1291
+
1292
+ assert cosh(asinh(x)) == sqrt(1 + x**2)
1293
+ assert cosh(acosh(x)) == x
1294
+ assert cosh(atanh(x)) == 1/sqrt(1 - x**2)
1295
+ assert cosh(acoth(x)) == x/(sqrt(x - 1) * sqrt(x + 1))
1296
+
1297
+ assert tanh(asinh(x)) == x/sqrt(1 + x**2)
1298
+ assert tanh(acosh(x)) == sqrt(x - 1) * sqrt(x + 1) / x
1299
+ assert tanh(atanh(x)) == x
1300
+ assert tanh(acoth(x)) == 1/x
1301
+
1302
+ assert coth(asinh(x)) == sqrt(1 + x**2)/x
1303
+ assert coth(acosh(x)) == x/(sqrt(x - 1) * sqrt(x + 1))
1304
+ assert coth(atanh(x)) == 1/x
1305
+ assert coth(acoth(x)) == x
1306
+
1307
+ assert csch(asinh(x)) == 1/x
1308
+ assert csch(acosh(x)) == 1/(sqrt(x - 1) * sqrt(x + 1))
1309
+ assert csch(atanh(x)) == sqrt(1 - x**2)/x
1310
+ assert csch(acoth(x)) == sqrt(x - 1) * sqrt(x + 1)
1311
+
1312
+ assert sech(asinh(x)) == 1/sqrt(1 + x**2)
1313
+ assert sech(acosh(x)) == 1/x
1314
+ assert sech(atanh(x)) == sqrt(1 - x**2)
1315
+ assert sech(acoth(x)) == sqrt(x - 1) * sqrt(x + 1)/x
1316
+
1317
+
1318
+ def test_issue_4136():
1319
+ assert cosh(asinh(Integer(3)/2)) == sqrt(Integer(13)/4)
1320
+
1321
+
1322
+ def test_sinh_rewrite():
1323
+ x = Symbol('x')
1324
+ assert sinh(x).rewrite(exp) == (exp(x) - exp(-x))/2 \
1325
+ == sinh(x).rewrite('tractable')
1326
+ assert sinh(x).rewrite(cosh) == -I*cosh(x + I*pi/2)
1327
+ tanh_half = tanh(S.Half*x)
1328
+ assert sinh(x).rewrite(tanh) == 2*tanh_half/(1 - tanh_half**2)
1329
+ coth_half = coth(S.Half*x)
1330
+ assert sinh(x).rewrite(coth) == 2*coth_half/(coth_half**2 - 1)
1331
+
1332
+
1333
+ def test_cosh_rewrite():
1334
+ x = Symbol('x')
1335
+ assert cosh(x).rewrite(exp) == (exp(x) + exp(-x))/2 \
1336
+ == cosh(x).rewrite('tractable')
1337
+ assert cosh(x).rewrite(sinh) == -I*sinh(x + I*pi/2)
1338
+ tanh_half = tanh(S.Half*x)**2
1339
+ assert cosh(x).rewrite(tanh) == (1 + tanh_half)/(1 - tanh_half)
1340
+ coth_half = coth(S.Half*x)**2
1341
+ assert cosh(x).rewrite(coth) == (coth_half + 1)/(coth_half - 1)
1342
+
1343
+
1344
+ def test_tanh_rewrite():
1345
+ x = Symbol('x')
1346
+ assert tanh(x).rewrite(exp) == (exp(x) - exp(-x))/(exp(x) + exp(-x)) \
1347
+ == tanh(x).rewrite('tractable')
1348
+ assert tanh(x).rewrite(sinh) == I*sinh(x)/sinh(I*pi/2 - x)
1349
+ assert tanh(x).rewrite(cosh) == I*cosh(I*pi/2 - x)/cosh(x)
1350
+ assert tanh(x).rewrite(coth) == 1/coth(x)
1351
+
1352
+
1353
+ def test_coth_rewrite():
1354
+ x = Symbol('x')
1355
+ assert coth(x).rewrite(exp) == (exp(x) + exp(-x))/(exp(x) - exp(-x)) \
1356
+ == coth(x).rewrite('tractable')
1357
+ assert coth(x).rewrite(sinh) == -I*sinh(I*pi/2 - x)/sinh(x)
1358
+ assert coth(x).rewrite(cosh) == -I*cosh(x)/cosh(I*pi/2 - x)
1359
+ assert coth(x).rewrite(tanh) == 1/tanh(x)
1360
+
1361
+
1362
+ def test_csch_rewrite():
1363
+ x = Symbol('x')
1364
+ assert csch(x).rewrite(exp) == 1 / (exp(x)/2 - exp(-x)/2) \
1365
+ == csch(x).rewrite('tractable')
1366
+ assert csch(x).rewrite(cosh) == I/cosh(x + I*pi/2)
1367
+ tanh_half = tanh(S.Half*x)
1368
+ assert csch(x).rewrite(tanh) == (1 - tanh_half**2)/(2*tanh_half)
1369
+ coth_half = coth(S.Half*x)
1370
+ assert csch(x).rewrite(coth) == (coth_half**2 - 1)/(2*coth_half)
1371
+
1372
+
1373
+ def test_sech_rewrite():
1374
+ x = Symbol('x')
1375
+ assert sech(x).rewrite(exp) == 1 / (exp(x)/2 + exp(-x)/2) \
1376
+ == sech(x).rewrite('tractable')
1377
+ assert sech(x).rewrite(sinh) == I/sinh(x + I*pi/2)
1378
+ tanh_half = tanh(S.Half*x)**2
1379
+ assert sech(x).rewrite(tanh) == (1 - tanh_half)/(1 + tanh_half)
1380
+ coth_half = coth(S.Half*x)**2
1381
+ assert sech(x).rewrite(coth) == (coth_half - 1)/(coth_half + 1)
1382
+
1383
+
1384
+ def test_derivs():
1385
+ x = Symbol('x')
1386
+ assert coth(x).diff(x) == -sinh(x)**(-2)
1387
+ assert sinh(x).diff(x) == cosh(x)
1388
+ assert cosh(x).diff(x) == sinh(x)
1389
+ assert tanh(x).diff(x) == -tanh(x)**2 + 1
1390
+ assert csch(x).diff(x) == -coth(x)*csch(x)
1391
+ assert sech(x).diff(x) == -tanh(x)*sech(x)
1392
+ assert acoth(x).diff(x) == 1/(-x**2 + 1)
1393
+ assert asinh(x).diff(x) == 1/sqrt(x**2 + 1)
1394
+ assert acosh(x).diff(x) == 1/(sqrt(x - 1)*sqrt(x + 1))
1395
+ assert acosh(x).diff(x) == acosh(x).rewrite(log).diff(x).together()
1396
+ assert atanh(x).diff(x) == 1/(-x**2 + 1)
1397
+ assert asech(x).diff(x) == -1/(x*sqrt(1 - x**2))
1398
+ assert acsch(x).diff(x) == -1/(x**2*sqrt(1 + x**(-2)))
1399
+
1400
+
1401
+ def test_sinh_expansion():
1402
+ x, y = symbols('x,y')
1403
+ assert sinh(x+y).expand(trig=True) == sinh(x)*cosh(y) + cosh(x)*sinh(y)
1404
+ assert sinh(2*x).expand(trig=True) == 2*sinh(x)*cosh(x)
1405
+ assert sinh(3*x).expand(trig=True).expand() == \
1406
+ sinh(x)**3 + 3*sinh(x)*cosh(x)**2
1407
+
1408
+
1409
+ def test_cosh_expansion():
1410
+ x, y = symbols('x,y')
1411
+ assert cosh(x+y).expand(trig=True) == cosh(x)*cosh(y) + sinh(x)*sinh(y)
1412
+ assert cosh(2*x).expand(trig=True) == cosh(x)**2 + sinh(x)**2
1413
+ assert cosh(3*x).expand(trig=True).expand() == \
1414
+ 3*sinh(x)**2*cosh(x) + cosh(x)**3
1415
+
1416
+ def test_cosh_positive():
1417
+ # See issue 11721
1418
+ # cosh(x) is positive for real values of x
1419
+ k = symbols('k', real=True)
1420
+ n = symbols('n', integer=True)
1421
+
1422
+ assert cosh(k, evaluate=False).is_positive is True
1423
+ assert cosh(k + 2*n*pi*I, evaluate=False).is_positive is True
1424
+ assert cosh(I*pi/4, evaluate=False).is_positive is True
1425
+ assert cosh(3*I*pi/4, evaluate=False).is_positive is False
1426
+
1427
+ def test_cosh_nonnegative():
1428
+ k = symbols('k', real=True)
1429
+ n = symbols('n', integer=True)
1430
+
1431
+ assert cosh(k, evaluate=False).is_nonnegative is True
1432
+ assert cosh(k + 2*n*pi*I, evaluate=False).is_nonnegative is True
1433
+ assert cosh(I*pi/4, evaluate=False).is_nonnegative is True
1434
+ assert cosh(3*I*pi/4, evaluate=False).is_nonnegative is False
1435
+ assert cosh(S.Zero, evaluate=False).is_nonnegative is True
1436
+
1437
+ def test_real_assumptions():
1438
+ z = Symbol('z', real=False)
1439
+ assert sinh(z).is_real is None
1440
+ assert cosh(z).is_real is None
1441
+ assert tanh(z).is_real is None
1442
+ assert sech(z).is_real is None
1443
+ assert csch(z).is_real is None
1444
+ assert coth(z).is_real is None
1445
+
1446
+ def test_sign_assumptions():
1447
+ p = Symbol('p', positive=True)
1448
+ n = Symbol('n', negative=True)
1449
+ assert sinh(n).is_negative is True
1450
+ assert sinh(p).is_positive is True
1451
+ assert cosh(n).is_positive is True
1452
+ assert cosh(p).is_positive is True
1453
+ assert tanh(n).is_negative is True
1454
+ assert tanh(p).is_positive is True
1455
+ assert csch(n).is_negative is True
1456
+ assert csch(p).is_positive is True
1457
+ assert sech(n).is_positive is True
1458
+ assert sech(p).is_positive is True
1459
+ assert coth(n).is_negative is True
1460
+ assert coth(p).is_positive is True
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_integers.py ADDED
@@ -0,0 +1,632 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.calculus.accumulationbounds import AccumBounds
2
+ from sympy.core.numbers import (E, Float, I, Rational, nan, oo, pi, zoo)
3
+ from sympy.core.relational import (Eq, Ge, Gt, Le, Lt, Ne)
4
+ from sympy.core.singleton import S
5
+ from sympy.core.symbol import (Symbol, symbols)
6
+ from sympy.functions.combinatorial.factorials import factorial
7
+ from sympy.functions.elementary.exponential import (exp, log)
8
+ from sympy.functions.elementary.integers import (ceiling, floor, frac)
9
+ from sympy.functions.elementary.miscellaneous import sqrt
10
+ from sympy.functions.elementary.trigonometric import sin, cos, tan
11
+
12
+ from sympy.core.expr import unchanged
13
+ from sympy.testing.pytest import XFAIL
14
+
15
+ x = Symbol('x')
16
+ i = Symbol('i', imaginary=True)
17
+ y = Symbol('y', real=True)
18
+ k, n = symbols('k,n', integer=True)
19
+
20
+
21
+ def test_floor():
22
+
23
+ assert floor(nan) is nan
24
+
25
+ assert floor(oo) is oo
26
+ assert floor(-oo) is -oo
27
+ assert floor(zoo) is zoo
28
+
29
+ assert floor(0) == 0
30
+
31
+ assert floor(1) == 1
32
+ assert floor(-1) == -1
33
+
34
+ assert floor(E) == 2
35
+ assert floor(-E) == -3
36
+
37
+ assert floor(2*E) == 5
38
+ assert floor(-2*E) == -6
39
+
40
+ assert floor(pi) == 3
41
+ assert floor(-pi) == -4
42
+
43
+ assert floor(S.Half) == 0
44
+ assert floor(Rational(-1, 2)) == -1
45
+
46
+ assert floor(Rational(7, 3)) == 2
47
+ assert floor(Rational(-7, 3)) == -3
48
+ assert floor(-Rational(7, 3)) == -3
49
+
50
+ assert floor(Float(17.0)) == 17
51
+ assert floor(-Float(17.0)) == -17
52
+
53
+ assert floor(Float(7.69)) == 7
54
+ assert floor(-Float(7.69)) == -8
55
+
56
+ assert floor(I) == I
57
+ assert floor(-I) == -I
58
+ e = floor(i)
59
+ assert e.func is floor and e.args[0] == i
60
+
61
+ assert floor(oo*I) == oo*I
62
+ assert floor(-oo*I) == -oo*I
63
+ assert floor(exp(I*pi/4)*oo) == exp(I*pi/4)*oo
64
+
65
+ assert floor(2*I) == 2*I
66
+ assert floor(-2*I) == -2*I
67
+
68
+ assert floor(I/2) == 0
69
+ assert floor(-I/2) == -I
70
+
71
+ assert floor(E + 17) == 19
72
+ assert floor(pi + 2) == 5
73
+
74
+ assert floor(E + pi) == 5
75
+ assert floor(I + pi) == 3 + I
76
+
77
+ assert floor(floor(pi)) == 3
78
+ assert floor(floor(y)) == floor(y)
79
+ assert floor(floor(x)) == floor(x)
80
+
81
+ assert unchanged(floor, x)
82
+ assert unchanged(floor, 2*x)
83
+ assert unchanged(floor, k*x)
84
+
85
+ assert floor(k) == k
86
+ assert floor(2*k) == 2*k
87
+ assert floor(k*n) == k*n
88
+
89
+ assert unchanged(floor, k/2)
90
+
91
+ assert unchanged(floor, x + y)
92
+
93
+ assert floor(x + 3) == floor(x) + 3
94
+ assert floor(x + k) == floor(x) + k
95
+
96
+ assert floor(y + 3) == floor(y) + 3
97
+ assert floor(y + k) == floor(y) + k
98
+
99
+ assert floor(3 + I*y + pi) == 6 + floor(y)*I
100
+
101
+ assert floor(k + n) == k + n
102
+
103
+ assert unchanged(floor, x*I)
104
+ assert floor(k*I) == k*I
105
+
106
+ assert floor(Rational(23, 10) - E*I) == 2 - 3*I
107
+
108
+ assert floor(sin(1)) == 0
109
+ assert floor(sin(-1)) == -1
110
+
111
+ assert floor(exp(2)) == 7
112
+
113
+ assert floor(log(8)/log(2)) != 2
114
+ assert int(floor(log(8)/log(2)).evalf(chop=True)) == 3
115
+
116
+ assert floor(factorial(50)/exp(1)) == \
117
+ 11188719610782480504630258070757734324011354208865721592720336800
118
+
119
+ assert (floor(y) < y) == False
120
+ assert (floor(y) <= y) == True
121
+ assert (floor(y) > y) == False
122
+ assert (floor(y) >= y) == False
123
+ assert (floor(x) <= x).is_Relational # x could be non-real
124
+ assert (floor(x) > x).is_Relational
125
+ assert (floor(x) <= y).is_Relational # arg is not same as rhs
126
+ assert (floor(x) > y).is_Relational
127
+ assert (floor(y) <= oo) == True
128
+ assert (floor(y) < oo) == True
129
+ assert (floor(y) >= -oo) == True
130
+ assert (floor(y) > -oo) == True
131
+
132
+ assert floor(y).rewrite(frac) == y - frac(y)
133
+ assert floor(y).rewrite(ceiling) == -ceiling(-y)
134
+ assert floor(y).rewrite(frac).subs(y, -pi) == floor(-pi)
135
+ assert floor(y).rewrite(frac).subs(y, E) == floor(E)
136
+ assert floor(y).rewrite(ceiling).subs(y, E) == -ceiling(-E)
137
+ assert floor(y).rewrite(ceiling).subs(y, -pi) == -ceiling(pi)
138
+
139
+ assert Eq(floor(y), y - frac(y))
140
+ assert Eq(floor(y), -ceiling(-y))
141
+
142
+ neg = Symbol('neg', negative=True)
143
+ nn = Symbol('nn', nonnegative=True)
144
+ pos = Symbol('pos', positive=True)
145
+ np = Symbol('np', nonpositive=True)
146
+
147
+ assert (floor(neg) < 0) == True
148
+ assert (floor(neg) <= 0) == True
149
+ assert (floor(neg) > 0) == False
150
+ assert (floor(neg) >= 0) == False
151
+ assert (floor(neg) <= -1) == True
152
+ assert (floor(neg) >= -3) == (neg >= -3)
153
+ assert (floor(neg) < 5) == (neg < 5)
154
+
155
+ assert (floor(nn) < 0) == False
156
+ assert (floor(nn) >= 0) == True
157
+
158
+ assert (floor(pos) < 0) == False
159
+ assert (floor(pos) <= 0) == (pos < 1)
160
+ assert (floor(pos) > 0) == (pos >= 1)
161
+ assert (floor(pos) >= 0) == True
162
+ assert (floor(pos) >= 3) == (pos >= 3)
163
+
164
+ assert (floor(np) <= 0) == True
165
+ assert (floor(np) > 0) == False
166
+
167
+ assert floor(neg).is_negative == True
168
+ assert floor(neg).is_nonnegative == False
169
+ assert floor(nn).is_negative == False
170
+ assert floor(nn).is_nonnegative == True
171
+ assert floor(pos).is_negative == False
172
+ assert floor(pos).is_nonnegative == True
173
+ assert floor(np).is_negative is None
174
+ assert floor(np).is_nonnegative is None
175
+
176
+ assert (floor(7, evaluate=False) >= 7) == True
177
+ assert (floor(7, evaluate=False) > 7) == False
178
+ assert (floor(7, evaluate=False) <= 7) == True
179
+ assert (floor(7, evaluate=False) < 7) == False
180
+
181
+ assert (floor(7, evaluate=False) >= 6) == True
182
+ assert (floor(7, evaluate=False) > 6) == True
183
+ assert (floor(7, evaluate=False) <= 6) == False
184
+ assert (floor(7, evaluate=False) < 6) == False
185
+
186
+ assert (floor(7, evaluate=False) >= 8) == False
187
+ assert (floor(7, evaluate=False) > 8) == False
188
+ assert (floor(7, evaluate=False) <= 8) == True
189
+ assert (floor(7, evaluate=False) < 8) == True
190
+
191
+ assert (floor(x) <= 5.5) == Le(floor(x), 5.5, evaluate=False)
192
+ assert (floor(x) >= -3.2) == Ge(floor(x), -3.2, evaluate=False)
193
+ assert (floor(x) < 2.9) == Lt(floor(x), 2.9, evaluate=False)
194
+ assert (floor(x) > -1.7) == Gt(floor(x), -1.7, evaluate=False)
195
+
196
+ assert (floor(y) <= 5.5) == (y < 6)
197
+ assert (floor(y) >= -3.2) == (y >= -3)
198
+ assert (floor(y) < 2.9) == (y < 3)
199
+ assert (floor(y) > -1.7) == (y >= -1)
200
+
201
+ assert (floor(y) <= n) == (y < n + 1)
202
+ assert (floor(y) >= n) == (y >= n)
203
+ assert (floor(y) < n) == (y < n)
204
+ assert (floor(y) > n) == (y >= n + 1)
205
+
206
+
207
+ def test_ceiling():
208
+
209
+ assert ceiling(nan) is nan
210
+
211
+ assert ceiling(oo) is oo
212
+ assert ceiling(-oo) is -oo
213
+ assert ceiling(zoo) is zoo
214
+
215
+ assert ceiling(0) == 0
216
+
217
+ assert ceiling(1) == 1
218
+ assert ceiling(-1) == -1
219
+
220
+ assert ceiling(E) == 3
221
+ assert ceiling(-E) == -2
222
+
223
+ assert ceiling(2*E) == 6
224
+ assert ceiling(-2*E) == -5
225
+
226
+ assert ceiling(pi) == 4
227
+ assert ceiling(-pi) == -3
228
+
229
+ assert ceiling(S.Half) == 1
230
+ assert ceiling(Rational(-1, 2)) == 0
231
+
232
+ assert ceiling(Rational(7, 3)) == 3
233
+ assert ceiling(-Rational(7, 3)) == -2
234
+
235
+ assert ceiling(Float(17.0)) == 17
236
+ assert ceiling(-Float(17.0)) == -17
237
+
238
+ assert ceiling(Float(7.69)) == 8
239
+ assert ceiling(-Float(7.69)) == -7
240
+
241
+ assert ceiling(I) == I
242
+ assert ceiling(-I) == -I
243
+ e = ceiling(i)
244
+ assert e.func is ceiling and e.args[0] == i
245
+
246
+ assert ceiling(oo*I) == oo*I
247
+ assert ceiling(-oo*I) == -oo*I
248
+ assert ceiling(exp(I*pi/4)*oo) == exp(I*pi/4)*oo
249
+
250
+ assert ceiling(2*I) == 2*I
251
+ assert ceiling(-2*I) == -2*I
252
+
253
+ assert ceiling(I/2) == I
254
+ assert ceiling(-I/2) == 0
255
+
256
+ assert ceiling(E + 17) == 20
257
+ assert ceiling(pi + 2) == 6
258
+
259
+ assert ceiling(E + pi) == 6
260
+ assert ceiling(I + pi) == I + 4
261
+
262
+ assert ceiling(ceiling(pi)) == 4
263
+ assert ceiling(ceiling(y)) == ceiling(y)
264
+ assert ceiling(ceiling(x)) == ceiling(x)
265
+
266
+ assert unchanged(ceiling, x)
267
+ assert unchanged(ceiling, 2*x)
268
+ assert unchanged(ceiling, k*x)
269
+
270
+ assert ceiling(k) == k
271
+ assert ceiling(2*k) == 2*k
272
+ assert ceiling(k*n) == k*n
273
+
274
+ assert unchanged(ceiling, k/2)
275
+
276
+ assert unchanged(ceiling, x + y)
277
+
278
+ assert ceiling(x + 3) == ceiling(x) + 3
279
+ assert ceiling(x + k) == ceiling(x) + k
280
+
281
+ assert ceiling(y + 3) == ceiling(y) + 3
282
+ assert ceiling(y + k) == ceiling(y) + k
283
+
284
+ assert ceiling(3 + pi + y*I) == 7 + ceiling(y)*I
285
+
286
+ assert ceiling(k + n) == k + n
287
+
288
+ assert unchanged(ceiling, x*I)
289
+ assert ceiling(k*I) == k*I
290
+
291
+ assert ceiling(Rational(23, 10) - E*I) == 3 - 2*I
292
+
293
+ assert ceiling(sin(1)) == 1
294
+ assert ceiling(sin(-1)) == 0
295
+
296
+ assert ceiling(exp(2)) == 8
297
+
298
+ assert ceiling(-log(8)/log(2)) != -2
299
+ assert int(ceiling(-log(8)/log(2)).evalf(chop=True)) == -3
300
+
301
+ assert ceiling(factorial(50)/exp(1)) == \
302
+ 11188719610782480504630258070757734324011354208865721592720336801
303
+
304
+ assert (ceiling(y) >= y) == True
305
+ assert (ceiling(y) > y) == False
306
+ assert (ceiling(y) < y) == False
307
+ assert (ceiling(y) <= y) == False
308
+ assert (ceiling(x) >= x).is_Relational # x could be non-real
309
+ assert (ceiling(x) < x).is_Relational
310
+ assert (ceiling(x) >= y).is_Relational # arg is not same as rhs
311
+ assert (ceiling(x) < y).is_Relational
312
+ assert (ceiling(y) >= -oo) == True
313
+ assert (ceiling(y) > -oo) == True
314
+ assert (ceiling(y) <= oo) == True
315
+ assert (ceiling(y) < oo) == True
316
+
317
+ assert ceiling(y).rewrite(floor) == -floor(-y)
318
+ assert ceiling(y).rewrite(frac) == y + frac(-y)
319
+ assert ceiling(y).rewrite(floor).subs(y, -pi) == -floor(pi)
320
+ assert ceiling(y).rewrite(floor).subs(y, E) == -floor(-E)
321
+ assert ceiling(y).rewrite(frac).subs(y, pi) == ceiling(pi)
322
+ assert ceiling(y).rewrite(frac).subs(y, -E) == ceiling(-E)
323
+
324
+ assert Eq(ceiling(y), y + frac(-y))
325
+ assert Eq(ceiling(y), -floor(-y))
326
+
327
+ neg = Symbol('neg', negative=True)
328
+ nn = Symbol('nn', nonnegative=True)
329
+ pos = Symbol('pos', positive=True)
330
+ np = Symbol('np', nonpositive=True)
331
+
332
+ assert (ceiling(neg) <= 0) == True
333
+ assert (ceiling(neg) < 0) == (neg <= -1)
334
+ assert (ceiling(neg) > 0) == False
335
+ assert (ceiling(neg) >= 0) == (neg > -1)
336
+ assert (ceiling(neg) > -3) == (neg > -3)
337
+ assert (ceiling(neg) <= 10) == (neg <= 10)
338
+
339
+ assert (ceiling(nn) < 0) == False
340
+ assert (ceiling(nn) >= 0) == True
341
+
342
+ assert (ceiling(pos) < 0) == False
343
+ assert (ceiling(pos) <= 0) == False
344
+ assert (ceiling(pos) > 0) == True
345
+ assert (ceiling(pos) >= 0) == True
346
+ assert (ceiling(pos) >= 1) == True
347
+ assert (ceiling(pos) > 5) == (pos > 5)
348
+
349
+ assert (ceiling(np) <= 0) == True
350
+ assert (ceiling(np) > 0) == False
351
+
352
+ assert ceiling(neg).is_positive == False
353
+ assert ceiling(neg).is_nonpositive == True
354
+ assert ceiling(nn).is_positive is None
355
+ assert ceiling(nn).is_nonpositive is None
356
+ assert ceiling(pos).is_positive == True
357
+ assert ceiling(pos).is_nonpositive == False
358
+ assert ceiling(np).is_positive == False
359
+ assert ceiling(np).is_nonpositive == True
360
+
361
+ assert (ceiling(7, evaluate=False) >= 7) == True
362
+ assert (ceiling(7, evaluate=False) > 7) == False
363
+ assert (ceiling(7, evaluate=False) <= 7) == True
364
+ assert (ceiling(7, evaluate=False) < 7) == False
365
+
366
+ assert (ceiling(7, evaluate=False) >= 6) == True
367
+ assert (ceiling(7, evaluate=False) > 6) == True
368
+ assert (ceiling(7, evaluate=False) <= 6) == False
369
+ assert (ceiling(7, evaluate=False) < 6) == False
370
+
371
+ assert (ceiling(7, evaluate=False) >= 8) == False
372
+ assert (ceiling(7, evaluate=False) > 8) == False
373
+ assert (ceiling(7, evaluate=False) <= 8) == True
374
+ assert (ceiling(7, evaluate=False) < 8) == True
375
+
376
+ assert (ceiling(x) <= 5.5) == Le(ceiling(x), 5.5, evaluate=False)
377
+ assert (ceiling(x) >= -3.2) == Ge(ceiling(x), -3.2, evaluate=False)
378
+ assert (ceiling(x) < 2.9) == Lt(ceiling(x), 2.9, evaluate=False)
379
+ assert (ceiling(x) > -1.7) == Gt(ceiling(x), -1.7, evaluate=False)
380
+
381
+ assert (ceiling(y) <= 5.5) == (y <= 5)
382
+ assert (ceiling(y) >= -3.2) == (y > -4)
383
+ assert (ceiling(y) < 2.9) == (y <= 2)
384
+ assert (ceiling(y) > -1.7) == (y > -2)
385
+
386
+ assert (ceiling(y) <= n) == (y <= n)
387
+ assert (ceiling(y) >= n) == (y > n - 1)
388
+ assert (ceiling(y) < n) == (y <= n - 1)
389
+ assert (ceiling(y) > n) == (y > n)
390
+
391
+
392
+ def test_frac():
393
+ assert isinstance(frac(x), frac)
394
+ assert frac(oo) == AccumBounds(0, 1)
395
+ assert frac(-oo) == AccumBounds(0, 1)
396
+ assert frac(zoo) is nan
397
+
398
+ assert frac(n) == 0
399
+ assert frac(nan) is nan
400
+ assert frac(Rational(4, 3)) == Rational(1, 3)
401
+ assert frac(-Rational(4, 3)) == Rational(2, 3)
402
+ assert frac(Rational(-4, 3)) == Rational(2, 3)
403
+
404
+ r = Symbol('r', real=True)
405
+ assert frac(I*r) == I*frac(r)
406
+ assert frac(1 + I*r) == I*frac(r)
407
+ assert frac(0.5 + I*r) == 0.5 + I*frac(r)
408
+ assert frac(n + I*r) == I*frac(r)
409
+ assert frac(n + I*k) == 0
410
+ assert unchanged(frac, x + I*x)
411
+ assert frac(x + I*n) == frac(x)
412
+
413
+ assert frac(x).rewrite(floor) == x - floor(x)
414
+ assert frac(x).rewrite(ceiling) == x + ceiling(-x)
415
+ assert frac(y).rewrite(floor).subs(y, pi) == frac(pi)
416
+ assert frac(y).rewrite(floor).subs(y, -E) == frac(-E)
417
+ assert frac(y).rewrite(ceiling).subs(y, -pi) == frac(-pi)
418
+ assert frac(y).rewrite(ceiling).subs(y, E) == frac(E)
419
+
420
+ assert Eq(frac(y), y - floor(y))
421
+ assert Eq(frac(y), y + ceiling(-y))
422
+
423
+ r = Symbol('r', real=True)
424
+ p_i = Symbol('p_i', integer=True, positive=True)
425
+ n_i = Symbol('p_i', integer=True, negative=True)
426
+ np_i = Symbol('np_i', integer=True, nonpositive=True)
427
+ nn_i = Symbol('nn_i', integer=True, nonnegative=True)
428
+ p_r = Symbol('p_r', positive=True)
429
+ n_r = Symbol('n_r', negative=True)
430
+ np_r = Symbol('np_r', real=True, nonpositive=True)
431
+ nn_r = Symbol('nn_r', real=True, nonnegative=True)
432
+
433
+ # Real frac argument, integer rhs
434
+ assert frac(r) <= p_i
435
+ assert not frac(r) <= n_i
436
+ assert (frac(r) <= np_i).has(Le)
437
+ assert (frac(r) <= nn_i).has(Le)
438
+ assert frac(r) < p_i
439
+ assert not frac(r) < n_i
440
+ assert not frac(r) < np_i
441
+ assert (frac(r) < nn_i).has(Lt)
442
+ assert not frac(r) >= p_i
443
+ assert frac(r) >= n_i
444
+ assert frac(r) >= np_i
445
+ assert (frac(r) >= nn_i).has(Ge)
446
+ assert not frac(r) > p_i
447
+ assert frac(r) > n_i
448
+ assert (frac(r) > np_i).has(Gt)
449
+ assert (frac(r) > nn_i).has(Gt)
450
+
451
+ assert not Eq(frac(r), p_i)
452
+ assert not Eq(frac(r), n_i)
453
+ assert Eq(frac(r), np_i).has(Eq)
454
+ assert Eq(frac(r), nn_i).has(Eq)
455
+
456
+ assert Ne(frac(r), p_i)
457
+ assert Ne(frac(r), n_i)
458
+ assert Ne(frac(r), np_i).has(Ne)
459
+ assert Ne(frac(r), nn_i).has(Ne)
460
+
461
+
462
+ # Real frac argument, real rhs
463
+ assert (frac(r) <= p_r).has(Le)
464
+ assert not frac(r) <= n_r
465
+ assert (frac(r) <= np_r).has(Le)
466
+ assert (frac(r) <= nn_r).has(Le)
467
+ assert (frac(r) < p_r).has(Lt)
468
+ assert not frac(r) < n_r
469
+ assert not frac(r) < np_r
470
+ assert (frac(r) < nn_r).has(Lt)
471
+ assert (frac(r) >= p_r).has(Ge)
472
+ assert frac(r) >= n_r
473
+ assert frac(r) >= np_r
474
+ assert (frac(r) >= nn_r).has(Ge)
475
+ assert (frac(r) > p_r).has(Gt)
476
+ assert frac(r) > n_r
477
+ assert (frac(r) > np_r).has(Gt)
478
+ assert (frac(r) > nn_r).has(Gt)
479
+
480
+ assert not Eq(frac(r), n_r)
481
+ assert Eq(frac(r), p_r).has(Eq)
482
+ assert Eq(frac(r), np_r).has(Eq)
483
+ assert Eq(frac(r), nn_r).has(Eq)
484
+
485
+ assert Ne(frac(r), p_r).has(Ne)
486
+ assert Ne(frac(r), n_r)
487
+ assert Ne(frac(r), np_r).has(Ne)
488
+ assert Ne(frac(r), nn_r).has(Ne)
489
+
490
+ # Real frac argument, +/- oo rhs
491
+ assert frac(r) < oo
492
+ assert frac(r) <= oo
493
+ assert not frac(r) > oo
494
+ assert not frac(r) >= oo
495
+
496
+ assert not frac(r) < -oo
497
+ assert not frac(r) <= -oo
498
+ assert frac(r) > -oo
499
+ assert frac(r) >= -oo
500
+
501
+ assert frac(r) < 1
502
+ assert frac(r) <= 1
503
+ assert not frac(r) > 1
504
+ assert not frac(r) >= 1
505
+
506
+ assert not frac(r) < 0
507
+ assert (frac(r) <= 0).has(Le)
508
+ assert (frac(r) > 0).has(Gt)
509
+ assert frac(r) >= 0
510
+
511
+ # Some test for numbers
512
+ assert frac(r) <= sqrt(2)
513
+ assert (frac(r) <= sqrt(3) - sqrt(2)).has(Le)
514
+ assert not frac(r) <= sqrt(2) - sqrt(3)
515
+ assert not frac(r) >= sqrt(2)
516
+ assert (frac(r) >= sqrt(3) - sqrt(2)).has(Ge)
517
+ assert frac(r) >= sqrt(2) - sqrt(3)
518
+
519
+ assert not Eq(frac(r), sqrt(2))
520
+ assert Eq(frac(r), sqrt(3) - sqrt(2)).has(Eq)
521
+ assert not Eq(frac(r), sqrt(2) - sqrt(3))
522
+ assert Ne(frac(r), sqrt(2))
523
+ assert Ne(frac(r), sqrt(3) - sqrt(2)).has(Ne)
524
+ assert Ne(frac(r), sqrt(2) - sqrt(3))
525
+
526
+ assert frac(p_i, evaluate=False).is_zero
527
+ assert frac(p_i, evaluate=False).is_finite
528
+ assert frac(p_i, evaluate=False).is_integer
529
+ assert frac(p_i, evaluate=False).is_real
530
+ assert frac(r).is_finite
531
+ assert frac(r).is_real
532
+ assert frac(r).is_zero is None
533
+ assert frac(r).is_integer is None
534
+
535
+ assert frac(oo).is_finite
536
+ assert frac(oo).is_real
537
+
538
+
539
+ def test_series():
540
+ x, y = symbols('x,y')
541
+ assert floor(x).nseries(x, y, 100) == floor(y)
542
+ assert ceiling(x).nseries(x, y, 100) == ceiling(y)
543
+ assert floor(x).nseries(x, pi, 100) == 3
544
+ assert ceiling(x).nseries(x, pi, 100) == 4
545
+ assert floor(x).nseries(x, 0, 100) == 0
546
+ assert ceiling(x).nseries(x, 0, 100) == 1
547
+ assert floor(-x).nseries(x, 0, 100) == -1
548
+ assert ceiling(-x).nseries(x, 0, 100) == 0
549
+
550
+
551
+ def test_issue_14355():
552
+ # This test checks the leading term and series for the floor and ceil
553
+ # function when arg0 evaluates to S.NaN.
554
+ assert floor((x**3 + x)/(x**2 - x)).as_leading_term(x, cdir = 1) == -2
555
+ assert floor((x**3 + x)/(x**2 - x)).as_leading_term(x, cdir = -1) == -1
556
+ assert floor((cos(x) - 1)/x).as_leading_term(x, cdir = 1) == -1
557
+ assert floor((cos(x) - 1)/x).as_leading_term(x, cdir = -1) == 0
558
+ assert floor(sin(x)/x).as_leading_term(x, cdir = 1) == 0
559
+ assert floor(sin(x)/x).as_leading_term(x, cdir = -1) == 0
560
+ assert floor(-tan(x)/x).as_leading_term(x, cdir = 1) == -2
561
+ assert floor(-tan(x)/x).as_leading_term(x, cdir = -1) == -2
562
+ assert floor(sin(x)/x/3).as_leading_term(x, cdir = 1) == 0
563
+ assert floor(sin(x)/x/3).as_leading_term(x, cdir = -1) == 0
564
+ assert ceiling((x**3 + x)/(x**2 - x)).as_leading_term(x, cdir = 1) == -1
565
+ assert ceiling((x**3 + x)/(x**2 - x)).as_leading_term(x, cdir = -1) == 0
566
+ assert ceiling((cos(x) - 1)/x).as_leading_term(x, cdir = 1) == 0
567
+ assert ceiling((cos(x) - 1)/x).as_leading_term(x, cdir = -1) == 1
568
+ assert ceiling(sin(x)/x).as_leading_term(x, cdir = 1) == 1
569
+ assert ceiling(sin(x)/x).as_leading_term(x, cdir = -1) == 1
570
+ assert ceiling(-tan(x)/x).as_leading_term(x, cdir = 1) == -1
571
+ assert ceiling(-tan(x)/x).as_leading_term(x, cdir = 1) == -1
572
+ assert ceiling(sin(x)/x/3).as_leading_term(x, cdir = 1) == 1
573
+ assert ceiling(sin(x)/x/3).as_leading_term(x, cdir = -1) == 1
574
+ # test for series
575
+ assert floor(sin(x)/x).series(x, 0, 100, cdir = 1) == 0
576
+ assert floor(sin(x)/x).series(x, 0, 100, cdir = 1) == 0
577
+ assert floor((x**3 + x)/(x**2 - x)).series(x, 0, 100, cdir = 1) == -2
578
+ assert floor((x**3 + x)/(x**2 - x)).series(x, 0, 100, cdir = -1) == -1
579
+ assert ceiling(sin(x)/x).series(x, 0, 100, cdir = 1) == 1
580
+ assert ceiling(sin(x)/x).series(x, 0, 100, cdir = -1) == 1
581
+ assert ceiling((x**3 + x)/(x**2 - x)).series(x, 0, 100, cdir = 1) == -1
582
+ assert ceiling((x**3 + x)/(x**2 - x)).series(x, 0, 100, cdir = -1) == 0
583
+
584
+
585
+ def test_frac_leading_term():
586
+ assert frac(x).as_leading_term(x) == x
587
+ assert frac(x).as_leading_term(x, cdir = 1) == x
588
+ assert frac(x).as_leading_term(x, cdir = -1) == 1
589
+ assert frac(x + S.Half).as_leading_term(x, cdir = 1) == S.Half
590
+ assert frac(x + S.Half).as_leading_term(x, cdir = -1) == S.Half
591
+ assert frac(-2*x + 1).as_leading_term(x, cdir = 1) == S.One
592
+ assert frac(-2*x + 1).as_leading_term(x, cdir = -1) == -2*x
593
+ assert frac(sin(x) + 5).as_leading_term(x, cdir = 1) == x
594
+ assert frac(sin(x) + 5).as_leading_term(x, cdir = -1) == S.One
595
+ assert frac(sin(x**2) + 5).as_leading_term(x, cdir = 1) == x**2
596
+ assert frac(sin(x**2) + 5).as_leading_term(x, cdir = -1) == x**2
597
+
598
+
599
+ @XFAIL
600
+ def test_issue_4149():
601
+ assert floor(3 + pi*I + y*I) == 3 + floor(pi + y)*I
602
+ assert floor(3*I + pi*I + y*I) == floor(3 + pi + y)*I
603
+ assert floor(3 + E + pi*I + y*I) == 5 + floor(pi + y)*I
604
+
605
+
606
+ def test_issue_21651():
607
+ k = Symbol('k', positive=True, integer=True)
608
+ exp = 2*2**(-k)
609
+ assert isinstance(floor(exp), floor)
610
+
611
+
612
+ def test_issue_11207():
613
+ assert floor(floor(x)) == floor(x)
614
+ assert floor(ceiling(x)) == ceiling(x)
615
+ assert ceiling(floor(x)) == floor(x)
616
+ assert ceiling(ceiling(x)) == ceiling(x)
617
+
618
+
619
+ def test_nested_floor_ceiling():
620
+ assert floor(-floor(ceiling(x**3)/y)) == -floor(ceiling(x**3)/y)
621
+ assert ceiling(-floor(ceiling(x**3)/y)) == -floor(ceiling(x**3)/y)
622
+ assert floor(ceiling(-floor(x**Rational(7, 2)/y))) == -floor(x**Rational(7, 2)/y)
623
+ assert -ceiling(-ceiling(floor(x)/y)) == ceiling(floor(x)/y)
624
+
625
+ def test_issue_18689():
626
+ assert floor(floor(floor(x)) + 3) == floor(x) + 3
627
+ assert ceiling(ceiling(ceiling(x)) + 1) == ceiling(x) + 1
628
+ assert ceiling(ceiling(floor(x)) + 3) == floor(x) + 3
629
+
630
+ def test_issue_18421():
631
+ assert floor(float(0)) is S.Zero
632
+ assert ceiling(float(0)) is S.Zero
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_interface.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This test file tests the SymPy function interface, that people use to create
2
+ # their own new functions. It should be as easy as possible.
3
+ from sympy.core.function import Function
4
+ from sympy.core.sympify import sympify
5
+ from sympy.functions.elementary.hyperbolic import tanh
6
+ from sympy.functions.elementary.trigonometric import (cos, sin)
7
+ from sympy.series.limits import limit
8
+ from sympy.abc import x
9
+
10
+
11
+ def test_function_series1():
12
+ """Create our new "sin" function."""
13
+
14
+ class my_function(Function):
15
+
16
+ def fdiff(self, argindex=1):
17
+ return cos(self.args[0])
18
+
19
+ @classmethod
20
+ def eval(cls, arg):
21
+ arg = sympify(arg)
22
+ if arg == 0:
23
+ return sympify(0)
24
+
25
+ #Test that the taylor series is correct
26
+ assert my_function(x).series(x, 0, 10) == sin(x).series(x, 0, 10)
27
+ assert limit(my_function(x)/x, x, 0) == 1
28
+
29
+
30
+ def test_function_series2():
31
+ """Create our new "cos" function."""
32
+
33
+ class my_function2(Function):
34
+
35
+ def fdiff(self, argindex=1):
36
+ return -sin(self.args[0])
37
+
38
+ @classmethod
39
+ def eval(cls, arg):
40
+ arg = sympify(arg)
41
+ if arg == 0:
42
+ return sympify(1)
43
+
44
+ #Test that the taylor series is correct
45
+ assert my_function2(x).series(x, 0, 10) == cos(x).series(x, 0, 10)
46
+
47
+
48
+ def test_function_series3():
49
+ """
50
+ Test our easy "tanh" function.
51
+
52
+ This test tests two things:
53
+ * that the Function interface works as expected and it's easy to use
54
+ * that the general algorithm for the series expansion works even when the
55
+ derivative is defined recursively in terms of the original function,
56
+ since tanh(x).diff(x) == 1-tanh(x)**2
57
+ """
58
+
59
+ class mytanh(Function):
60
+
61
+ def fdiff(self, argindex=1):
62
+ return 1 - mytanh(self.args[0])**2
63
+
64
+ @classmethod
65
+ def eval(cls, arg):
66
+ arg = sympify(arg)
67
+ if arg == 0:
68
+ return sympify(0)
69
+
70
+ e = tanh(x)
71
+ f = mytanh(x)
72
+ assert e.series(x, 0, 6) == f.series(x, 0, 6)
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_miscellaneous.py ADDED
@@ -0,0 +1,504 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools as it
2
+
3
+ from sympy.core.expr import unchanged
4
+ from sympy.core.function import Function
5
+ from sympy.core.numbers import I, oo, Rational
6
+ from sympy.core.power import Pow
7
+ from sympy.core.singleton import S
8
+ from sympy.core.symbol import Symbol
9
+ from sympy.external import import_module
10
+ from sympy.functions.elementary.exponential import log
11
+ from sympy.functions.elementary.integers import floor, ceiling
12
+ from sympy.functions.elementary.miscellaneous import (sqrt, cbrt, root, Min,
13
+ Max, real_root, Rem)
14
+ from sympy.functions.elementary.trigonometric import cos, sin
15
+ from sympy.functions.special.delta_functions import Heaviside
16
+
17
+ from sympy.utilities.lambdify import lambdify
18
+ from sympy.testing.pytest import raises, skip, ignore_warnings
19
+
20
+ def test_Min():
21
+ from sympy.abc import x, y, z
22
+ n = Symbol('n', negative=True)
23
+ n_ = Symbol('n_', negative=True)
24
+ nn = Symbol('nn', nonnegative=True)
25
+ nn_ = Symbol('nn_', nonnegative=True)
26
+ p = Symbol('p', positive=True)
27
+ p_ = Symbol('p_', positive=True)
28
+ np = Symbol('np', nonpositive=True)
29
+ np_ = Symbol('np_', nonpositive=True)
30
+ r = Symbol('r', real=True)
31
+
32
+ assert Min(5, 4) == 4
33
+ assert Min(-oo, -oo) is -oo
34
+ assert Min(-oo, n) is -oo
35
+ assert Min(n, -oo) is -oo
36
+ assert Min(-oo, np) is -oo
37
+ assert Min(np, -oo) is -oo
38
+ assert Min(-oo, 0) is -oo
39
+ assert Min(0, -oo) is -oo
40
+ assert Min(-oo, nn) is -oo
41
+ assert Min(nn, -oo) is -oo
42
+ assert Min(-oo, p) is -oo
43
+ assert Min(p, -oo) is -oo
44
+ assert Min(-oo, oo) is -oo
45
+ assert Min(oo, -oo) is -oo
46
+ assert Min(n, n) == n
47
+ assert unchanged(Min, n, np)
48
+ assert Min(np, n) == Min(n, np)
49
+ assert Min(n, 0) == n
50
+ assert Min(0, n) == n
51
+ assert Min(n, nn) == n
52
+ assert Min(nn, n) == n
53
+ assert Min(n, p) == n
54
+ assert Min(p, n) == n
55
+ assert Min(n, oo) == n
56
+ assert Min(oo, n) == n
57
+ assert Min(np, np) == np
58
+ assert Min(np, 0) == np
59
+ assert Min(0, np) == np
60
+ assert Min(np, nn) == np
61
+ assert Min(nn, np) == np
62
+ assert Min(np, p) == np
63
+ assert Min(p, np) == np
64
+ assert Min(np, oo) == np
65
+ assert Min(oo, np) == np
66
+ assert Min(0, 0) == 0
67
+ assert Min(0, nn) == 0
68
+ assert Min(nn, 0) == 0
69
+ assert Min(0, p) == 0
70
+ assert Min(p, 0) == 0
71
+ assert Min(0, oo) == 0
72
+ assert Min(oo, 0) == 0
73
+ assert Min(nn, nn) == nn
74
+ assert unchanged(Min, nn, p)
75
+ assert Min(p, nn) == Min(nn, p)
76
+ assert Min(nn, oo) == nn
77
+ assert Min(oo, nn) == nn
78
+ assert Min(p, p) == p
79
+ assert Min(p, oo) == p
80
+ assert Min(oo, p) == p
81
+ assert Min(oo, oo) is oo
82
+
83
+ assert Min(n, n_).func is Min
84
+ assert Min(nn, nn_).func is Min
85
+ assert Min(np, np_).func is Min
86
+ assert Min(p, p_).func is Min
87
+
88
+ # lists
89
+ assert Min() is S.Infinity
90
+ assert Min(x) == x
91
+ assert Min(x, y) == Min(y, x)
92
+ assert Min(x, y, z) == Min(z, y, x)
93
+ assert Min(x, Min(y, z)) == Min(z, y, x)
94
+ assert Min(x, Max(y, -oo)) == Min(x, y)
95
+ assert Min(p, oo, n, p, p, p_) == n
96
+ assert Min(p_, n_, p) == n_
97
+ assert Min(n, oo, -7, p, p, 2) == Min(n, -7)
98
+ assert Min(2, x, p, n, oo, n_, p, 2, -2, -2) == Min(-2, x, n, n_)
99
+ assert Min(0, x, 1, y) == Min(0, x, y)
100
+ assert Min(1000, 100, -100, x, p, n) == Min(n, x, -100)
101
+ assert unchanged(Min, sin(x), cos(x))
102
+ assert Min(sin(x), cos(x)) == Min(cos(x), sin(x))
103
+ assert Min(cos(x), sin(x)).subs(x, 1) == cos(1)
104
+ assert Min(cos(x), sin(x)).subs(x, S.Half) == sin(S.Half)
105
+ raises(ValueError, lambda: Min(cos(x), sin(x)).subs(x, I))
106
+ raises(ValueError, lambda: Min(I))
107
+ raises(ValueError, lambda: Min(I, x))
108
+ raises(ValueError, lambda: Min(S.ComplexInfinity, x))
109
+
110
+ assert Min(1, x).diff(x) == Heaviside(1 - x)
111
+ assert Min(x, 1).diff(x) == Heaviside(1 - x)
112
+ assert Min(0, -x, 1 - 2*x).diff(x) == -Heaviside(x + Min(0, -2*x + 1)) \
113
+ - 2*Heaviside(2*x + Min(0, -x) - 1)
114
+
115
+ # issue 7619
116
+ f = Function('f')
117
+ assert Min(1, 2*Min(f(1), 2)) # doesn't fail
118
+
119
+ # issue 7233
120
+ e = Min(0, x)
121
+ assert e.n().args == (0, x)
122
+
123
+ # issue 8643
124
+ m = Min(n, p_, n_, r)
125
+ assert m.is_positive is False
126
+ assert m.is_nonnegative is False
127
+ assert m.is_negative is True
128
+
129
+ m = Min(p, p_)
130
+ assert m.is_positive is True
131
+ assert m.is_nonnegative is True
132
+ assert m.is_negative is False
133
+
134
+ m = Min(p, nn_, p_)
135
+ assert m.is_positive is None
136
+ assert m.is_nonnegative is True
137
+ assert m.is_negative is False
138
+
139
+ m = Min(nn, p, r)
140
+ assert m.is_positive is None
141
+ assert m.is_nonnegative is None
142
+ assert m.is_negative is None
143
+
144
+
145
+ def test_Max():
146
+ from sympy.abc import x, y, z
147
+ n = Symbol('n', negative=True)
148
+ n_ = Symbol('n_', negative=True)
149
+ nn = Symbol('nn', nonnegative=True)
150
+ p = Symbol('p', positive=True)
151
+ p_ = Symbol('p_', positive=True)
152
+ r = Symbol('r', real=True)
153
+
154
+ assert Max(5, 4) == 5
155
+
156
+ # lists
157
+
158
+ assert Max() is S.NegativeInfinity
159
+ assert Max(x) == x
160
+ assert Max(x, y) == Max(y, x)
161
+ assert Max(x, y, z) == Max(z, y, x)
162
+ assert Max(x, Max(y, z)) == Max(z, y, x)
163
+ assert Max(x, Min(y, oo)) == Max(x, y)
164
+ assert Max(n, -oo, n_, p, 2) == Max(p, 2)
165
+ assert Max(n, -oo, n_, p) == p
166
+ assert Max(2, x, p, n, -oo, S.NegativeInfinity, n_, p, 2) == Max(2, x, p)
167
+ assert Max(0, x, 1, y) == Max(1, x, y)
168
+ assert Max(r, r + 1, r - 1) == 1 + r
169
+ assert Max(1000, 100, -100, x, p, n) == Max(p, x, 1000)
170
+ assert Max(cos(x), sin(x)) == Max(sin(x), cos(x))
171
+ assert Max(cos(x), sin(x)).subs(x, 1) == sin(1)
172
+ assert Max(cos(x), sin(x)).subs(x, S.Half) == cos(S.Half)
173
+ raises(ValueError, lambda: Max(cos(x), sin(x)).subs(x, I))
174
+ raises(ValueError, lambda: Max(I))
175
+ raises(ValueError, lambda: Max(I, x))
176
+ raises(ValueError, lambda: Max(S.ComplexInfinity, 1))
177
+ assert Max(n, -oo, n_, p, 2) == Max(p, 2)
178
+ assert Max(n, -oo, n_, p, 1000) == Max(p, 1000)
179
+
180
+ assert Max(1, x).diff(x) == Heaviside(x - 1)
181
+ assert Max(x, 1).diff(x) == Heaviside(x - 1)
182
+ assert Max(x**2, 1 + x, 1).diff(x) == \
183
+ 2*x*Heaviside(x**2 - Max(1, x + 1)) \
184
+ + Heaviside(x - Max(1, x**2) + 1)
185
+
186
+ e = Max(0, x)
187
+ assert e.n().args == (0, x)
188
+
189
+ # issue 8643
190
+ m = Max(p, p_, n, r)
191
+ assert m.is_positive is True
192
+ assert m.is_nonnegative is True
193
+ assert m.is_negative is False
194
+
195
+ m = Max(n, n_)
196
+ assert m.is_positive is False
197
+ assert m.is_nonnegative is False
198
+ assert m.is_negative is True
199
+
200
+ m = Max(n, n_, r)
201
+ assert m.is_positive is None
202
+ assert m.is_nonnegative is None
203
+ assert m.is_negative is None
204
+
205
+ m = Max(n, nn, r)
206
+ assert m.is_positive is None
207
+ assert m.is_nonnegative is True
208
+ assert m.is_negative is False
209
+
210
+
211
+ def test_minmax_assumptions():
212
+ r = Symbol('r', real=True)
213
+ a = Symbol('a', real=True, algebraic=True)
214
+ t = Symbol('t', real=True, transcendental=True)
215
+ q = Symbol('q', rational=True)
216
+ p = Symbol('p', irrational=True)
217
+ n = Symbol('n', rational=True, integer=False)
218
+ i = Symbol('i', integer=True)
219
+ o = Symbol('o', odd=True)
220
+ e = Symbol('e', even=True)
221
+ k = Symbol('k', prime=True)
222
+ reals = [r, a, t, q, p, n, i, o, e, k]
223
+
224
+ for ext in (Max, Min):
225
+ for x, y in it.product(reals, repeat=2):
226
+
227
+ # Must be real
228
+ assert ext(x, y).is_real
229
+
230
+ # Algebraic?
231
+ if x.is_algebraic and y.is_algebraic:
232
+ assert ext(x, y).is_algebraic
233
+ elif x.is_transcendental and y.is_transcendental:
234
+ assert ext(x, y).is_transcendental
235
+ else:
236
+ assert ext(x, y).is_algebraic is None
237
+
238
+ # Rational?
239
+ if x.is_rational and y.is_rational:
240
+ assert ext(x, y).is_rational
241
+ elif x.is_irrational and y.is_irrational:
242
+ assert ext(x, y).is_irrational
243
+ else:
244
+ assert ext(x, y).is_rational is None
245
+
246
+ # Integer?
247
+ if x.is_integer and y.is_integer:
248
+ assert ext(x, y).is_integer
249
+ elif x.is_noninteger and y.is_noninteger:
250
+ assert ext(x, y).is_noninteger
251
+ else:
252
+ assert ext(x, y).is_integer is None
253
+
254
+ # Odd?
255
+ if x.is_odd and y.is_odd:
256
+ assert ext(x, y).is_odd
257
+ elif x.is_odd is False and y.is_odd is False:
258
+ assert ext(x, y).is_odd is False
259
+ else:
260
+ assert ext(x, y).is_odd is None
261
+
262
+ # Even?
263
+ if x.is_even and y.is_even:
264
+ assert ext(x, y).is_even
265
+ elif x.is_even is False and y.is_even is False:
266
+ assert ext(x, y).is_even is False
267
+ else:
268
+ assert ext(x, y).is_even is None
269
+
270
+ # Prime?
271
+ if x.is_prime and y.is_prime:
272
+ assert ext(x, y).is_prime
273
+ elif x.is_prime is False and y.is_prime is False:
274
+ assert ext(x, y).is_prime is False
275
+ else:
276
+ assert ext(x, y).is_prime is None
277
+
278
+
279
+ def test_issue_8413():
280
+ x = Symbol('x', real=True)
281
+ # we can't evaluate in general because non-reals are not
282
+ # comparable: Min(floor(3.2 + I), 3.2 + I) -> ValueError
283
+ assert Min(floor(x), x) == floor(x)
284
+ assert Min(ceiling(x), x) == x
285
+ assert Max(floor(x), x) == x
286
+ assert Max(ceiling(x), x) == ceiling(x)
287
+
288
+
289
+ def test_root():
290
+ from sympy.abc import x
291
+ n = Symbol('n', integer=True)
292
+ k = Symbol('k', integer=True)
293
+
294
+ assert root(2, 2) == sqrt(2)
295
+ assert root(2, 1) == 2
296
+ assert root(2, 3) == 2**Rational(1, 3)
297
+ assert root(2, 3) == cbrt(2)
298
+ assert root(2, -5) == 2**Rational(4, 5)/2
299
+
300
+ assert root(-2, 1) == -2
301
+
302
+ assert root(-2, 2) == sqrt(2)*I
303
+ assert root(-2, 1) == -2
304
+
305
+ assert root(x, 2) == sqrt(x)
306
+ assert root(x, 1) == x
307
+ assert root(x, 3) == x**Rational(1, 3)
308
+ assert root(x, 3) == cbrt(x)
309
+ assert root(x, -5) == x**Rational(-1, 5)
310
+
311
+ assert root(x, n) == x**(1/n)
312
+ assert root(x, -n) == x**(-1/n)
313
+
314
+ assert root(x, n, k) == (-1)**(2*k/n)*x**(1/n)
315
+
316
+
317
+ def test_real_root():
318
+ assert real_root(-8, 3) == -2
319
+ assert real_root(-16, 4) == root(-16, 4)
320
+ r = root(-7, 4)
321
+ assert real_root(r) == r
322
+ r1 = root(-1, 3)
323
+ r2 = r1**2
324
+ r3 = root(-1, 4)
325
+ assert real_root(r1 + r2 + r3) == -1 + r2 + r3
326
+ assert real_root(root(-2, 3)) == -root(2, 3)
327
+ assert real_root(-8., 3) == -2.0
328
+ x = Symbol('x')
329
+ n = Symbol('n')
330
+ g = real_root(x, n)
331
+ assert g.subs({"x": -8, "n": 3}) == -2
332
+ assert g.subs({"x": 8, "n": 3}) == 2
333
+ # give principle root if there is no real root -- if this is not desired
334
+ # then maybe a Root class is needed to raise an error instead
335
+ assert g.subs({"x": I, "n": 3}) == cbrt(I)
336
+ assert g.subs({"x": -8, "n": 2}) == sqrt(-8)
337
+ assert g.subs({"x": I, "n": 2}) == sqrt(I)
338
+
339
+
340
+ def test_issue_11463():
341
+ numpy = import_module('numpy')
342
+ if not numpy:
343
+ skip("numpy not installed.")
344
+ x = Symbol('x')
345
+ f = lambdify(x, real_root((log(x/(x-2))), 3), 'numpy')
346
+ # numpy.select evaluates all options before considering conditions,
347
+ # so it raises a warning about root of negative number which does
348
+ # not affect the outcome. This warning is suppressed here
349
+ with ignore_warnings(RuntimeWarning):
350
+ assert f(numpy.array(-1)) < -1
351
+
352
+
353
+ def test_rewrite_MaxMin_as_Heaviside():
354
+ from sympy.abc import x
355
+ assert Max(0, x).rewrite(Heaviside) == x*Heaviside(x)
356
+ assert Max(3, x).rewrite(Heaviside) == x*Heaviside(x - 3) + \
357
+ 3*Heaviside(-x + 3)
358
+ assert Max(0, x+2, 2*x).rewrite(Heaviside) == \
359
+ 2*x*Heaviside(2*x)*Heaviside(x - 2) + \
360
+ (x + 2)*Heaviside(-x + 2)*Heaviside(x + 2)
361
+
362
+ assert Min(0, x).rewrite(Heaviside) == x*Heaviside(-x)
363
+ assert Min(3, x).rewrite(Heaviside) == x*Heaviside(-x + 3) + \
364
+ 3*Heaviside(x - 3)
365
+ assert Min(x, -x, -2).rewrite(Heaviside) == \
366
+ x*Heaviside(-2*x)*Heaviside(-x - 2) - \
367
+ x*Heaviside(2*x)*Heaviside(x - 2) \
368
+ - 2*Heaviside(-x + 2)*Heaviside(x + 2)
369
+
370
+
371
+ def test_rewrite_MaxMin_as_Piecewise():
372
+ from sympy.core.symbol import symbols
373
+ from sympy.functions.elementary.piecewise import Piecewise
374
+ x, y, z, a, b = symbols('x y z a b', real=True)
375
+ vx, vy, va = symbols('vx vy va')
376
+ assert Max(a, b).rewrite(Piecewise) == Piecewise((a, a >= b), (b, True))
377
+ assert Max(x, y, z).rewrite(Piecewise) == Piecewise((x, (x >= y) & (x >= z)), (y, y >= z), (z, True))
378
+ assert Max(x, y, a, b).rewrite(Piecewise) == Piecewise((a, (a >= b) & (a >= x) & (a >= y)),
379
+ (b, (b >= x) & (b >= y)), (x, x >= y), (y, True))
380
+ assert Min(a, b).rewrite(Piecewise) == Piecewise((a, a <= b), (b, True))
381
+ assert Min(x, y, z).rewrite(Piecewise) == Piecewise((x, (x <= y) & (x <= z)), (y, y <= z), (z, True))
382
+ assert Min(x, y, a, b).rewrite(Piecewise) == Piecewise((a, (a <= b) & (a <= x) & (a <= y)),
383
+ (b, (b <= x) & (b <= y)), (x, x <= y), (y, True))
384
+
385
+ # Piecewise rewriting of Min/Max does also takes place for not explicitly real arguments
386
+ assert Max(vx, vy).rewrite(Piecewise) == Piecewise((vx, vx >= vy), (vy, True))
387
+ assert Min(va, vx, vy).rewrite(Piecewise) == Piecewise((va, (va <= vx) & (va <= vy)), (vx, vx <= vy), (vy, True))
388
+
389
+
390
+ def test_issue_11099():
391
+ from sympy.abc import x, y
392
+ # some fixed value tests
393
+ fixed_test_data = {x: -2, y: 3}
394
+ assert Min(x, y).evalf(subs=fixed_test_data) == \
395
+ Min(x, y).subs(fixed_test_data).evalf()
396
+ assert Max(x, y).evalf(subs=fixed_test_data) == \
397
+ Max(x, y).subs(fixed_test_data).evalf()
398
+ # randomly generate some test data
399
+ from sympy.core.random import randint
400
+ for i in range(20):
401
+ random_test_data = {x: randint(-100, 100), y: randint(-100, 100)}
402
+ assert Min(x, y).evalf(subs=random_test_data) == \
403
+ Min(x, y).subs(random_test_data).evalf()
404
+ assert Max(x, y).evalf(subs=random_test_data) == \
405
+ Max(x, y).subs(random_test_data).evalf()
406
+
407
+
408
+ def test_issue_12638():
409
+ from sympy.abc import a, b, c
410
+ assert Min(a, b, c, Max(a, b)) == Min(a, b, c)
411
+ assert Min(a, b, Max(a, b, c)) == Min(a, b)
412
+ assert Min(a, b, Max(a, c)) == Min(a, b)
413
+
414
+ def test_issue_21399():
415
+ from sympy.abc import a, b, c
416
+ assert Max(Min(a, b), Min(a, b, c)) == Min(a, b)
417
+
418
+
419
+ def test_instantiation_evaluation():
420
+ from sympy.abc import v, w, x, y, z
421
+ assert Min(1, Max(2, x)) == 1
422
+ assert Max(3, Min(2, x)) == 3
423
+ assert Min(Max(x, y), Max(x, z)) == Max(x, Min(y, z))
424
+ assert set(Min(Max(w, x), Max(y, z)).args) == {
425
+ Max(w, x), Max(y, z)}
426
+ assert Min(Max(x, y), Max(x, z), w) == Min(
427
+ w, Max(x, Min(y, z)))
428
+ A, B = Min, Max
429
+ for i in range(2):
430
+ assert A(x, B(x, y)) == x
431
+ assert A(x, B(y, A(x, w, z))) == A(x, B(y, A(w, z)))
432
+ A, B = B, A
433
+ assert Min(w, Max(x, y), Max(v, x, z)) == Min(
434
+ w, Max(x, Min(y, Max(v, z))))
435
+
436
+ def test_rewrite_as_Abs():
437
+ from itertools import permutations
438
+ from sympy.functions.elementary.complexes import Abs
439
+ from sympy.abc import x, y, z, w
440
+ def test(e):
441
+ free = e.free_symbols
442
+ a = e.rewrite(Abs)
443
+ assert not a.has(Min, Max)
444
+ for i in permutations(range(len(free))):
445
+ reps = dict(zip(free, i))
446
+ assert a.xreplace(reps) == e.xreplace(reps)
447
+ test(Min(x, y))
448
+ test(Max(x, y))
449
+ test(Min(x, y, z))
450
+ test(Min(Max(w, x), Max(y, z)))
451
+
452
+ def test_issue_14000():
453
+ assert isinstance(sqrt(4, evaluate=False), Pow) == True
454
+ assert isinstance(cbrt(3.5, evaluate=False), Pow) == True
455
+ assert isinstance(root(16, 4, evaluate=False), Pow) == True
456
+
457
+ assert sqrt(4, evaluate=False) == Pow(4, S.Half, evaluate=False)
458
+ assert cbrt(3.5, evaluate=False) == Pow(3.5, Rational(1, 3), evaluate=False)
459
+ assert root(4, 2, evaluate=False) == Pow(4, S.Half, evaluate=False)
460
+
461
+ assert root(16, 4, 2, evaluate=False).has(Pow) == True
462
+ assert real_root(-8, 3, evaluate=False).has(Pow) == True
463
+
464
+ def test_issue_6899():
465
+ from sympy.core.function import Lambda
466
+ x = Symbol('x')
467
+ eqn = Lambda(x, x)
468
+ assert eqn.func(*eqn.args) == eqn
469
+
470
+ def test_Rem():
471
+ from sympy.abc import x, y
472
+ assert Rem(5, 3) == 2
473
+ assert Rem(-5, 3) == -2
474
+ assert Rem(5, -3) == 2
475
+ assert Rem(-5, -3) == -2
476
+ assert Rem(x**3, y) == Rem(x**3, y)
477
+ assert Rem(Rem(-5, 3) + 3, 3) == 1
478
+
479
+
480
+ def test_minmax_no_evaluate():
481
+ from sympy import evaluate
482
+ p = Symbol('p', positive=True)
483
+
484
+ assert Max(1, 3) == 3
485
+ assert Max(1, 3).args == ()
486
+ assert Max(0, p) == p
487
+ assert Max(0, p).args == ()
488
+ assert Min(0, p) == 0
489
+ assert Min(0, p).args == ()
490
+
491
+ assert Max(1, 3, evaluate=False) != 3
492
+ assert Max(1, 3, evaluate=False).args == (1, 3)
493
+ assert Max(0, p, evaluate=False) != p
494
+ assert Max(0, p, evaluate=False).args == (0, p)
495
+ assert Min(0, p, evaluate=False) != 0
496
+ assert Min(0, p, evaluate=False).args == (0, p)
497
+
498
+ with evaluate(False):
499
+ assert Max(1, 3) != 3
500
+ assert Max(1, 3).args == (1, 3)
501
+ assert Max(0, p) != p
502
+ assert Max(0, p).args == (0, p)
503
+ assert Min(0, p) != 0
504
+ assert Min(0, p).args == (0, p)
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_piecewise.py ADDED
@@ -0,0 +1,1606 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.concrete.summations import Sum
2
+ from sympy.core.add import Add
3
+ from sympy.core.basic import Basic
4
+ from sympy.core.containers import Tuple
5
+ from sympy.core.expr import unchanged
6
+ from sympy.core.function import (Function, diff, expand)
7
+ from sympy.core.mul import Mul
8
+ from sympy.core.mod import Mod
9
+ from sympy.core.numbers import (Float, I, Rational, oo, pi, zoo)
10
+ from sympy.core.relational import (Eq, Ge, Gt, Ne)
11
+ from sympy.core.singleton import S
12
+ from sympy.core.symbol import (Symbol, symbols)
13
+ from sympy.functions.combinatorial.factorials import factorial
14
+ from sympy.functions.elementary.complexes import (Abs, adjoint, arg, conjugate, im, re, transpose)
15
+ from sympy.functions.elementary.exponential import (exp, log)
16
+ from sympy.functions.elementary.miscellaneous import (Max, Min, sqrt)
17
+ from sympy.functions.elementary.piecewise import (Piecewise,
18
+ piecewise_fold, piecewise_exclusive, Undefined, ExprCondPair)
19
+ from sympy.functions.elementary.trigonometric import (cos, sin)
20
+ from sympy.functions.special.delta_functions import (DiracDelta, Heaviside)
21
+ from sympy.functions.special.tensor_functions import KroneckerDelta
22
+ from sympy.integrals.integrals import (Integral, integrate)
23
+ from sympy.logic.boolalg import (And, ITE, Not, Or)
24
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
25
+ from sympy.printing import srepr
26
+ from sympy.sets.contains import Contains
27
+ from sympy.sets.sets import Interval
28
+ from sympy.solvers.solvers import solve
29
+ from sympy.testing.pytest import raises, slow
30
+ from sympy.utilities.lambdify import lambdify
31
+
32
+ a, b, c, d, x, y = symbols('a:d, x, y')
33
+ z = symbols('z', nonzero=True)
34
+
35
+
36
+ def test_piecewise1():
37
+
38
+ # Test canonicalization
39
+ assert unchanged(Piecewise, ExprCondPair(x, x < 1), ExprCondPair(0, True))
40
+ assert Piecewise((x, x < 1), (0, True)) == Piecewise(ExprCondPair(x, x < 1),
41
+ ExprCondPair(0, True))
42
+ assert Piecewise((x, x < 1), (0, True), (1, True)) == \
43
+ Piecewise((x, x < 1), (0, True))
44
+ assert Piecewise((x, x < 1), (0, False), (-1, 1 > 2)) == \
45
+ Piecewise((x, x < 1))
46
+ assert Piecewise((x, x < 1), (0, x < 1), (0, True)) == \
47
+ Piecewise((x, x < 1), (0, True))
48
+ assert Piecewise((x, x < 1), (0, x < 2), (0, True)) == \
49
+ Piecewise((x, x < 1), (0, True))
50
+ assert Piecewise((x, x < 1), (x, x < 2), (0, True)) == \
51
+ Piecewise((x, Or(x < 1, x < 2)), (0, True))
52
+ assert Piecewise((x, x < 1), (x, x < 2), (x, True)) == x
53
+ assert Piecewise((x, True)) == x
54
+ # Explicitly constructed empty Piecewise not accepted
55
+ raises(TypeError, lambda: Piecewise())
56
+ # False condition is never retained
57
+ assert Piecewise((2*x, x < 0), (x, False)) == \
58
+ Piecewise((2*x, x < 0), (x, False), evaluate=False) == \
59
+ Piecewise((2*x, x < 0))
60
+ assert Piecewise((x, False)) == Undefined
61
+ raises(TypeError, lambda: Piecewise(x))
62
+ assert Piecewise((x, 1)) == x # 1 and 0 are accepted as True/False
63
+ raises(TypeError, lambda: Piecewise((x, 2)))
64
+ raises(TypeError, lambda: Piecewise((x, x**2)))
65
+ raises(TypeError, lambda: Piecewise(([1], True)))
66
+ assert Piecewise(((1, 2), True)) == Tuple(1, 2)
67
+ cond = (Piecewise((1, x < 0), (2, True)) < y)
68
+ assert Piecewise((1, cond)
69
+ ) == Piecewise((1, ITE(x < 0, y > 1, y > 2)))
70
+
71
+ assert Piecewise((1, x > 0), (2, And(x <= 0, x > -1))
72
+ ) == Piecewise((1, x > 0), (2, x > -1))
73
+ assert Piecewise((1, x <= 0), (2, (x < 0) & (x > -1))
74
+ ) == Piecewise((1, x <= 0))
75
+
76
+ # test for supporting Contains in Piecewise
77
+ pwise = Piecewise(
78
+ (1, And(x <= 6, x > 1, Contains(x, S.Integers))),
79
+ (0, True))
80
+ assert pwise.subs(x, pi) == 0
81
+ assert pwise.subs(x, 2) == 1
82
+ assert pwise.subs(x, 7) == 0
83
+
84
+ # Test subs
85
+ p = Piecewise((-1, x < -1), (x**2, x < 0), (log(x), x >= 0))
86
+ p_x2 = Piecewise((-1, x**2 < -1), (x**4, x**2 < 0), (log(x**2), x**2 >= 0))
87
+ assert p.subs(x, x**2) == p_x2
88
+ assert p.subs(x, -5) == -1
89
+ assert p.subs(x, -1) == 1
90
+ assert p.subs(x, 1) == log(1)
91
+
92
+ # More subs tests
93
+ p2 = Piecewise((1, x < pi), (-1, x < 2*pi), (0, x > 2*pi))
94
+ p3 = Piecewise((1, Eq(x, 0)), (1/x, True))
95
+ p4 = Piecewise((1, Eq(x, 0)), (2, 1/x>2))
96
+ assert p2.subs(x, 2) == 1
97
+ assert p2.subs(x, 4) == -1
98
+ assert p2.subs(x, 10) == 0
99
+ assert p3.subs(x, 0.0) == 1
100
+ assert p4.subs(x, 0.0) == 1
101
+
102
+
103
+ f, g, h = symbols('f,g,h', cls=Function)
104
+ pf = Piecewise((f(x), x < -1), (f(x) + h(x) + 2, x <= 1))
105
+ pg = Piecewise((g(x), x < -1), (g(x) + h(x) + 2, x <= 1))
106
+ assert pg.subs(g, f) == pf
107
+
108
+ assert Piecewise((1, Eq(x, 0)), (0, True)).subs(x, 0) == 1
109
+ assert Piecewise((1, Eq(x, 0)), (0, True)).subs(x, 1) == 0
110
+ assert Piecewise((1, Eq(x, y)), (0, True)).subs(x, y) == 1
111
+ assert Piecewise((1, Eq(x, z)), (0, True)).subs(x, z) == 1
112
+ assert Piecewise((1, Eq(exp(x), cos(z))), (0, True)).subs(x, z) == \
113
+ Piecewise((1, Eq(exp(z), cos(z))), (0, True))
114
+
115
+ p5 = Piecewise( (0, Eq(cos(x) + y, 0)), (1, True))
116
+ assert p5.subs(y, 0) == Piecewise( (0, Eq(cos(x), 0)), (1, True))
117
+
118
+ assert Piecewise((-1, y < 1), (0, x < 0), (1, Eq(x, 0)), (2, True)
119
+ ).subs(x, 1) == Piecewise((-1, y < 1), (2, True))
120
+ assert Piecewise((1, Eq(x**2, -1)), (2, x < 0)).subs(x, I) == 1
121
+
122
+ p6 = Piecewise((x, x > 0))
123
+ n = symbols('n', negative=True)
124
+ assert p6.subs(x, n) == Undefined
125
+
126
+ # Test evalf
127
+ assert p.evalf() == Piecewise((-1.0, x < -1), (x**2, x < 0), (log(x), True))
128
+ assert p.evalf(subs={x: -2}) == -1.0
129
+ assert p.evalf(subs={x: -1}) == 1.0
130
+ assert p.evalf(subs={x: 1}) == log(1)
131
+ assert p6.evalf(subs={x: -5}) == Undefined
132
+
133
+ # Test doit
134
+ f_int = Piecewise((Integral(x, (x, 0, 1)), x < 1))
135
+ assert f_int.doit() == Piecewise( (S.Half, x < 1) )
136
+
137
+ # Test differentiation
138
+ f = x
139
+ fp = x*p
140
+ dp = Piecewise((0, x < -1), (2*x, x < 0), (1/x, x >= 0))
141
+ fp_dx = x*dp + p
142
+ assert diff(p, x) == dp
143
+ assert diff(f*p, x) == fp_dx
144
+
145
+ # Test simple arithmetic
146
+ assert x*p == fp
147
+ assert x*p + p == p + x*p
148
+ assert p + f == f + p
149
+ assert p + dp == dp + p
150
+ assert p - dp == -(dp - p)
151
+
152
+ # Test power
153
+ dp2 = Piecewise((0, x < -1), (4*x**2, x < 0), (1/x**2, x >= 0))
154
+ assert dp**2 == dp2
155
+
156
+ # Test _eval_interval
157
+ f1 = x*y + 2
158
+ f2 = x*y**2 + 3
159
+ peval = Piecewise((f1, x < 0), (f2, x > 0))
160
+ peval_interval = f1.subs(
161
+ x, 0) - f1.subs(x, -1) + f2.subs(x, 1) - f2.subs(x, 0)
162
+ assert peval._eval_interval(x, 0, 0) == 0
163
+ assert peval._eval_interval(x, -1, 1) == peval_interval
164
+ peval2 = Piecewise((f1, x < 0), (f2, True))
165
+ assert peval2._eval_interval(x, 0, 0) == 0
166
+ assert peval2._eval_interval(x, 1, -1) == -peval_interval
167
+ assert peval2._eval_interval(x, -1, -2) == f1.subs(x, -2) - f1.subs(x, -1)
168
+ assert peval2._eval_interval(x, -1, 1) == peval_interval
169
+ assert peval2._eval_interval(x, None, 0) == peval2.subs(x, 0)
170
+ assert peval2._eval_interval(x, -1, None) == -peval2.subs(x, -1)
171
+
172
+ # Test integration
173
+ assert p.integrate() == Piecewise(
174
+ (-x, x < -1),
175
+ (x**3/3 + Rational(4, 3), x < 0),
176
+ (x*log(x) - x + Rational(4, 3), True))
177
+ p = Piecewise((x, x < 1), (x**2, -1 <= x), (x, 3 < x))
178
+ assert integrate(p, (x, -2, 2)) == Rational(5, 6)
179
+ assert integrate(p, (x, 2, -2)) == Rational(-5, 6)
180
+ p = Piecewise((0, x < 0), (1, x < 1), (0, x < 2), (1, x < 3), (0, True))
181
+ assert integrate(p, (x, -oo, oo)) == 2
182
+ p = Piecewise((x, x < -10), (x**2, x <= -1), (x, 1 < x))
183
+ assert integrate(p, (x, -2, 2)) == Undefined
184
+
185
+ # Test commutativity
186
+ assert isinstance(p, Piecewise) and p.is_commutative is True
187
+
188
+
189
+ def test_piecewise_free_symbols():
190
+ f = Piecewise((x, a < 0), (y, True))
191
+ assert f.free_symbols == {x, y, a}
192
+
193
+
194
+ def test_piecewise_integrate1():
195
+ x, y = symbols('x y', real=True)
196
+
197
+ f = Piecewise(((x - 2)**2, x >= 0), (1, True))
198
+ assert integrate(f, (x, -2, 2)) == Rational(14, 3)
199
+
200
+ g = Piecewise(((x - 5)**5, x >= 4), (f, True))
201
+ assert integrate(g, (x, -2, 2)) == Rational(14, 3)
202
+ assert integrate(g, (x, -2, 5)) == Rational(43, 6)
203
+
204
+ assert g == Piecewise(((x - 5)**5, x >= 4), (f, x < 4))
205
+
206
+ g = Piecewise(((x - 5)**5, 2 <= x), (f, x < 2))
207
+ assert integrate(g, (x, -2, 2)) == Rational(14, 3)
208
+ assert integrate(g, (x, -2, 5)) == Rational(-701, 6)
209
+
210
+ assert g == Piecewise(((x - 5)**5, 2 <= x), (f, True))
211
+
212
+ g = Piecewise(((x - 5)**5, 2 <= x), (2*f, True))
213
+ assert integrate(g, (x, -2, 2)) == Rational(28, 3)
214
+ assert integrate(g, (x, -2, 5)) == Rational(-673, 6)
215
+
216
+
217
+ def test_piecewise_integrate1b():
218
+ g = Piecewise((1, x > 0), (0, Eq(x, 0)), (-1, x < 0))
219
+ assert integrate(g, (x, -1, 1)) == 0
220
+
221
+ g = Piecewise((1, x - y < 0), (0, True))
222
+ assert integrate(g, (y, -oo, 0)) == -Min(0, x)
223
+ assert g.subs(x, -3).integrate((y, -oo, 0)) == 3
224
+ assert integrate(g, (y, 0, -oo)) == Min(0, x)
225
+ assert integrate(g, (y, 0, oo)) == -Max(0, x) + oo
226
+ assert integrate(g, (y, -oo, 42)) == -Min(42, x) + 42
227
+ assert integrate(g, (y, -oo, oo)) == -x + oo
228
+
229
+ g = Piecewise((0, x < 0), (x, x <= 1), (1, True))
230
+ gy1 = g.integrate((x, y, 1))
231
+ g1y = g.integrate((x, 1, y))
232
+ for yy in (-1, S.Half, 2):
233
+ assert g.integrate((x, yy, 1)) == gy1.subs(y, yy)
234
+ assert g.integrate((x, 1, yy)) == g1y.subs(y, yy)
235
+ assert gy1 == Piecewise(
236
+ (-Min(1, Max(0, y))**2/2 + S.Half, y < 1),
237
+ (-y + 1, True))
238
+ assert g1y == Piecewise(
239
+ (Min(1, Max(0, y))**2/2 - S.Half, y < 1),
240
+ (y - 1, True))
241
+
242
+
243
+ @slow
244
+ def test_piecewise_integrate1ca():
245
+ y = symbols('y', real=True)
246
+ g = Piecewise(
247
+ (1 - x, Interval(0, 1).contains(x)),
248
+ (1 + x, Interval(-1, 0).contains(x)),
249
+ (0, True)
250
+ )
251
+ gy1 = g.integrate((x, y, 1))
252
+ g1y = g.integrate((x, 1, y))
253
+
254
+ assert g.integrate((x, -2, 1)) == gy1.subs(y, -2)
255
+ assert g.integrate((x, 1, -2)) == g1y.subs(y, -2)
256
+ assert g.integrate((x, 0, 1)) == gy1.subs(y, 0)
257
+ assert g.integrate((x, 1, 0)) == g1y.subs(y, 0)
258
+ assert g.integrate((x, 2, 1)) == gy1.subs(y, 2)
259
+ assert g.integrate((x, 1, 2)) == g1y.subs(y, 2)
260
+ assert piecewise_fold(gy1.rewrite(Piecewise)
261
+ ).simplify() == Piecewise(
262
+ (1, y <= -1),
263
+ (-y**2/2 - y + S.Half, y <= 0),
264
+ (y**2/2 - y + S.Half, y < 1),
265
+ (0, True))
266
+ assert piecewise_fold(g1y.rewrite(Piecewise)
267
+ ).simplify() == Piecewise(
268
+ (-1, y <= -1),
269
+ (y**2/2 + y - S.Half, y <= 0),
270
+ (-y**2/2 + y - S.Half, y < 1),
271
+ (0, True))
272
+ assert gy1 == Piecewise(
273
+ (
274
+ -Min(1, Max(-1, y))**2/2 - Min(1, Max(-1, y)) +
275
+ Min(1, Max(0, y))**2 + S.Half, y < 1),
276
+ (0, True)
277
+ )
278
+ assert g1y == Piecewise(
279
+ (
280
+ Min(1, Max(-1, y))**2/2 + Min(1, Max(-1, y)) -
281
+ Min(1, Max(0, y))**2 - S.Half, y < 1),
282
+ (0, True))
283
+
284
+
285
+ @slow
286
+ def test_piecewise_integrate1cb():
287
+ y = symbols('y', real=True)
288
+ g = Piecewise(
289
+ (0, Or(x <= -1, x >= 1)),
290
+ (1 - x, x > 0),
291
+ (1 + x, True)
292
+ )
293
+ gy1 = g.integrate((x, y, 1))
294
+ g1y = g.integrate((x, 1, y))
295
+
296
+ assert g.integrate((x, -2, 1)) == gy1.subs(y, -2)
297
+ assert g.integrate((x, 1, -2)) == g1y.subs(y, -2)
298
+ assert g.integrate((x, 0, 1)) == gy1.subs(y, 0)
299
+ assert g.integrate((x, 1, 0)) == g1y.subs(y, 0)
300
+ assert g.integrate((x, 2, 1)) == gy1.subs(y, 2)
301
+ assert g.integrate((x, 1, 2)) == g1y.subs(y, 2)
302
+
303
+ assert piecewise_fold(gy1.rewrite(Piecewise)
304
+ ).simplify() == Piecewise(
305
+ (1, y <= -1),
306
+ (-y**2/2 - y + S.Half, y <= 0),
307
+ (y**2/2 - y + S.Half, y < 1),
308
+ (0, True))
309
+ assert piecewise_fold(g1y.rewrite(Piecewise)
310
+ ).simplify() == Piecewise(
311
+ (-1, y <= -1),
312
+ (y**2/2 + y - S.Half, y <= 0),
313
+ (-y**2/2 + y - S.Half, y < 1),
314
+ (0, True))
315
+
316
+ # g1y and gy1 should simplify if the condition that y < 1
317
+ # is applied, e.g. Min(1, Max(-1, y)) --> Max(-1, y)
318
+ assert gy1 == Piecewise(
319
+ (
320
+ -Min(1, Max(-1, y))**2/2 - Min(1, Max(-1, y)) +
321
+ Min(1, Max(0, y))**2 + S.Half, y < 1),
322
+ (0, True)
323
+ )
324
+ assert g1y == Piecewise(
325
+ (
326
+ Min(1, Max(-1, y))**2/2 + Min(1, Max(-1, y)) -
327
+ Min(1, Max(0, y))**2 - S.Half, y < 1),
328
+ (0, True))
329
+
330
+
331
+ def test_piecewise_integrate2():
332
+ from itertools import permutations
333
+ lim = Tuple(x, c, d)
334
+ p = Piecewise((1, x < a), (2, x > b), (3, True))
335
+ q = p.integrate(lim)
336
+ assert q == Piecewise(
337
+ (-c + 2*d - 2*Min(d, Max(a, c)) + Min(d, Max(a, b, c)), c < d),
338
+ (-2*c + d + 2*Min(c, Max(a, d)) - Min(c, Max(a, b, d)), True))
339
+ for v in permutations((1, 2, 3, 4)):
340
+ r = dict(zip((a, b, c, d), v))
341
+ assert p.subs(r).integrate(lim.subs(r)) == q.subs(r)
342
+
343
+
344
+ def test_meijer_bypass():
345
+ # totally bypass meijerg machinery when dealing
346
+ # with Piecewise in integrate
347
+ assert Piecewise((1, x < 4), (0, True)).integrate((x, oo, 1)) == -3
348
+
349
+
350
+ def test_piecewise_integrate3_inequality_conditions():
351
+ from sympy.utilities.iterables import cartes
352
+ lim = (x, 0, 5)
353
+ # set below includes two pts below range, 2 pts in range,
354
+ # 2 pts above range, and the boundaries
355
+ N = (-2, -1, 0, 1, 2, 5, 6, 7)
356
+
357
+ p = Piecewise((1, x > a), (2, x > b), (0, True))
358
+ ans = p.integrate(lim)
359
+ for i, j in cartes(N, repeat=2):
360
+ reps = dict(zip((a, b), (i, j)))
361
+ assert ans.subs(reps) == p.subs(reps).integrate(lim)
362
+ assert ans.subs(a, 4).subs(b, 1) == 0 + 2*3 + 1
363
+
364
+ p = Piecewise((1, x > a), (2, x < b), (0, True))
365
+ ans = p.integrate(lim)
366
+ for i, j in cartes(N, repeat=2):
367
+ reps = dict(zip((a, b), (i, j)))
368
+ assert ans.subs(reps) == p.subs(reps).integrate(lim)
369
+
370
+ # delete old tests that involved c1 and c2 since those
371
+ # reduce to the above except that a value of 0 was used
372
+ # for two expressions whereas the above uses 3 different
373
+ # values
374
+
375
+
376
+ @slow
377
+ def test_piecewise_integrate4_symbolic_conditions():
378
+ a = Symbol('a', real=True)
379
+ b = Symbol('b', real=True)
380
+ x = Symbol('x', real=True)
381
+ y = Symbol('y', real=True)
382
+ p0 = Piecewise((0, Or(x < a, x > b)), (1, True))
383
+ p1 = Piecewise((0, x < a), (0, x > b), (1, True))
384
+ p2 = Piecewise((0, x > b), (0, x < a), (1, True))
385
+ p3 = Piecewise((0, x < a), (1, x < b), (0, True))
386
+ p4 = Piecewise((0, x > b), (1, x > a), (0, True))
387
+ p5 = Piecewise((1, And(a < x, x < b)), (0, True))
388
+
389
+ # check values of a=1, b=3 (and reversed) with values
390
+ # of y of 0, 1, 2, 3, 4
391
+ lim = Tuple(x, -oo, y)
392
+ for p in (p0, p1, p2, p3, p4, p5):
393
+ ans = p.integrate(lim)
394
+ for i in range(5):
395
+ reps = {a:1, b:3, y:i}
396
+ assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps))
397
+ reps = {a: 3, b:1, y:i}
398
+ assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps))
399
+ lim = Tuple(x, y, oo)
400
+ for p in (p0, p1, p2, p3, p4, p5):
401
+ ans = p.integrate(lim)
402
+ for i in range(5):
403
+ reps = {a:1, b:3, y:i}
404
+ assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps))
405
+ reps = {a:3, b:1, y:i}
406
+ assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps))
407
+
408
+ ans = Piecewise(
409
+ (0, x <= Min(a, b)),
410
+ (x - Min(a, b), x <= b),
411
+ (b - Min(a, b), True))
412
+ for i in (p0, p1, p2, p4):
413
+ assert i.integrate(x) == ans
414
+ assert p3.integrate(x) == Piecewise(
415
+ (0, x < a),
416
+ (-a + x, x <= Max(a, b)),
417
+ (-a + Max(a, b), True))
418
+ assert p5.integrate(x) == Piecewise(
419
+ (0, x <= a),
420
+ (-a + x, x <= Max(a, b)),
421
+ (-a + Max(a, b), True))
422
+
423
+ p1 = Piecewise((0, x < a), (S.Half, x > b), (1, True))
424
+ p2 = Piecewise((S.Half, x > b), (0, x < a), (1, True))
425
+ p3 = Piecewise((0, x < a), (1, x < b), (S.Half, True))
426
+ p4 = Piecewise((S.Half, x > b), (1, x > a), (0, True))
427
+ p5 = Piecewise((1, And(a < x, x < b)), (S.Half, x > b), (0, True))
428
+
429
+ # check values of a=1, b=3 (and reversed) with values
430
+ # of y of 0, 1, 2, 3, 4
431
+ lim = Tuple(x, -oo, y)
432
+ for p in (p1, p2, p3, p4, p5):
433
+ ans = p.integrate(lim)
434
+ for i in range(5):
435
+ reps = {a:1, b:3, y:i}
436
+ assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps))
437
+ reps = {a: 3, b:1, y:i}
438
+ assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps))
439
+
440
+
441
+ def test_piecewise_integrate5_independent_conditions():
442
+ p = Piecewise((0, Eq(y, 0)), (x*y, True))
443
+ assert integrate(p, (x, 1, 3)) == Piecewise((0, Eq(y, 0)), (4*y, True))
444
+
445
+
446
+ def test_issue_22917():
447
+ p = (Piecewise((0, ITE((x - y > 1) | (2 * x - 2 * y > 1), False,
448
+ ITE(x - y > 1, 2 * y - 2 < -1, 2 * x - 2 * y > 1))),
449
+ (Piecewise((0, ITE(x - y > 1, True, 2 * x - 2 * y > 1)),
450
+ (2 * Piecewise((0, x - y > 1), (y, True)), True)), True))
451
+ + 2 * Piecewise((1, ITE((x - y > 1) | (2 * x - 2 * y > 1), False,
452
+ ITE(x - y > 1, 2 * y - 2 < -1, 2 * x - 2 * y > 1))),
453
+ (Piecewise((1, ITE(x - y > 1, True, 2 * x - 2 * y > 1)),
454
+ (2 * Piecewise((1, x - y > 1), (x, True)), True)), True)))
455
+ assert piecewise_fold(p) == Piecewise((2, (x - y > S.Half) | (x - y > 1)),
456
+ (2*y + 4, x - y > 1),
457
+ (4*x + 2*y, True))
458
+ assert piecewise_fold(p > 1).rewrite(ITE) == ITE((x - y > S.Half) | (x - y > 1), True,
459
+ ITE(x - y > 1, 2*y + 4 > 1, 4*x + 2*y > 1))
460
+
461
+
462
+ def test_piecewise_simplify():
463
+ p = Piecewise(((x**2 + 1)/x**2, Eq(x*(1 + x) - x**2, 0)),
464
+ ((-1)**x*(-1), True))
465
+ assert p.simplify() == \
466
+ Piecewise((zoo, Eq(x, 0)), ((-1)**(x + 1), True))
467
+ # simplify when there are Eq in conditions
468
+ assert Piecewise(
469
+ (a, And(Eq(a, 0), Eq(a + b, 0))), (1, True)).simplify(
470
+ ) == Piecewise(
471
+ (0, And(Eq(a, 0), Eq(b, 0))), (1, True))
472
+ assert Piecewise((2*x*factorial(a)/(factorial(y)*factorial(-y + a)),
473
+ Eq(y, 0) & Eq(-y + a, 0)), (2*factorial(a)/(factorial(y)*factorial(-y
474
+ + a)), Eq(y, 0) & Eq(-y + a, 1)), (0, True)).simplify(
475
+ ) == Piecewise(
476
+ (2*x, And(Eq(a, 0), Eq(y, 0))),
477
+ (2, And(Eq(a, 1), Eq(y, 0))),
478
+ (0, True))
479
+ args = (2, And(Eq(x, 2), Ge(y, 0))), (x, True)
480
+ assert Piecewise(*args).simplify() == Piecewise(*args)
481
+ args = (1, Eq(x, 0)), (sin(x)/x, True)
482
+ assert Piecewise(*args).simplify() == Piecewise(*args)
483
+ assert Piecewise((2 + y, And(Eq(x, 2), Eq(y, 0))), (x, True)
484
+ ).simplify() == x
485
+ # check that x or f(x) are recognized as being Symbol-like for lhs
486
+ args = Tuple((1, Eq(x, 0)), (sin(x) + 1 + x, True))
487
+ ans = x + sin(x) + 1
488
+ f = Function('f')
489
+ assert Piecewise(*args).simplify() == ans
490
+ assert Piecewise(*args.subs(x, f(x))).simplify() == ans.subs(x, f(x))
491
+
492
+ # issue 18634
493
+ d = Symbol("d", integer=True)
494
+ n = Symbol("n", integer=True)
495
+ t = Symbol("t", positive=True)
496
+ expr = Piecewise((-d + 2*n, Eq(1/t, 1)), (t**(1 - 4*n)*t**(4*n - 1)*(-d + 2*n), True))
497
+ assert expr.simplify() == -d + 2*n
498
+
499
+ # issue 22747
500
+ p = Piecewise((0, (t < -2) & (t < -1) & (t < 0)), ((t/2 + 1)*(t +
501
+ 1)*(t + 2), (t < -1) & (t < 0)), ((S.Half - t/2)*(1 - t)*(t + 1),
502
+ (t < -2) & (t < -1) & (t < 1)), ((t + 1)*(-t*(t/2 + 1) + (S.Half
503
+ - t/2)*(1 - t)), (t < -2) & (t < -1) & (t < 0) & (t < 1)), ((t +
504
+ 1)*((S.Half - t/2)*(1 - t) + (t/2 + 1)*(t + 2)), (t < -1) & (t <
505
+ 1)), ((t + 1)*(-t*(t/2 + 1) + (S.Half - t/2)*(1 - t)), (t < -1) &
506
+ (t < 0) & (t < 1)), (0, (t < -2) & (t < -1)), ((t/2 + 1)*(t +
507
+ 1)*(t + 2), t < -1), ((t + 1)*(-t*(t/2 + 1) + (S.Half - t/2)*(t +
508
+ 1)), (t < 0) & ((t < -2) | (t < 0))), ((S.Half - t/2)*(1 - t)*(t
509
+ + 1), (t < 1) & ((t < -2) | (t < 1))), (0, True)) + Piecewise((0,
510
+ (t < -1) & (t < 0) & (t < 1)), ((1 - t)*(t/2 + S.Half)*(t + 1),
511
+ (t < 0) & (t < 1)), ((1 - t)*(1 - t/2)*(2 - t), (t < -1) & (t <
512
+ 0) & (t < 2)), ((1 - t)*((1 - t)*(t/2 + S.Half) + (1 - t/2)*(2 -
513
+ t)), (t < -1) & (t < 0) & (t < 1) & (t < 2)), ((1 - t)*((1 -
514
+ t/2)*(2 - t) + (t/2 + S.Half)*(t + 1)), (t < 0) & (t < 2)), ((1 -
515
+ t)*((1 - t)*(t/2 + S.Half) + (1 - t/2)*(2 - t)), (t < 0) & (t <
516
+ 1) & (t < 2)), (0, (t < -1) & (t < 0)), ((1 - t)*(t/2 +
517
+ S.Half)*(t + 1), t < 0), ((1 - t)*(t*(1 - t/2) + (1 - t)*(t/2 +
518
+ S.Half)), (t < 1) & ((t < -1) | (t < 1))), ((1 - t)*(1 - t/2)*(2
519
+ - t), (t < 2) & ((t < -1) | (t < 2))), (0, True))
520
+ assert p.simplify() == Piecewise(
521
+ (0, t < -2), ((t + 1)*(t + 2)**2/2, t < -1), (-3*t**3/2
522
+ - 5*t**2/2 + 1, t < 0), (3*t**3/2 - 5*t**2/2 + 1, t < 1), ((1 -
523
+ t)*(t - 2)**2/2, t < 2), (0, True))
524
+
525
+ # coverage
526
+ nan = Undefined
527
+ covered = Piecewise((1, x > 3), (2, x < 2), (3, x > 1))
528
+ assert covered.simplify().args == covered.args
529
+ assert Piecewise((1, x < 2), (2, x < 1), (3, True)).simplify(
530
+ ) == Piecewise((1, x < 2), (3, True))
531
+ assert Piecewise((1, x > 2)).simplify() == Piecewise((1, x > 2),
532
+ (nan, True))
533
+ assert Piecewise((1, (x >= 2) & (x < oo))
534
+ ).simplify() == Piecewise((1, (x >= 2) & (x < oo)), (nan, True))
535
+ assert Piecewise((1, x < 2), (2, (x > 1) & (x < 3)), (3, True)
536
+ ). simplify() == Piecewise((1, x < 2), (2, x < 3), (3, True))
537
+ assert Piecewise((1, x < 2), (2, (x <= 3) & (x > 1)), (3, True)
538
+ ).simplify() == Piecewise((1, x < 2), (2, x <= 3), (3, True))
539
+ assert Piecewise((1, x < 2), (2, (x > 2) & (x < 3)), (3, True)
540
+ ).simplify() == Piecewise((1, x < 2), (2, (x > 2) & (x < 3)),
541
+ (3, True))
542
+ assert Piecewise((1, x < 2), (2, (x >= 1) & (x <= 3)), (3, True)
543
+ ).simplify() == Piecewise((1, x < 2), (2, x <= 3), (3, True))
544
+ assert Piecewise((1, x < 1), (2, (x >= 2) & (x <= 3)), (3, True)
545
+ ).simplify() == Piecewise((1, x < 1), (2, (x >= 2) & (x <= 3)),
546
+ (3, True))
547
+
548
+
549
+ def test_piecewise_solve():
550
+ abs2 = Piecewise((-x, x <= 0), (x, x > 0))
551
+ f = abs2.subs(x, x - 2)
552
+ assert solve(f, x) == [2]
553
+ assert solve(f - 1, x) == [1, 3]
554
+
555
+ f = Piecewise(((x - 2)**2, x >= 0), (1, True))
556
+ assert solve(f, x) == [2]
557
+
558
+ g = Piecewise(((x - 5)**5, x >= 4), (f, True))
559
+ assert solve(g, x) == [2, 5]
560
+
561
+ g = Piecewise(((x - 5)**5, x >= 4), (f, x < 4))
562
+ assert solve(g, x) == [2, 5]
563
+
564
+ g = Piecewise(((x - 5)**5, x >= 2), (f, x < 2))
565
+ assert solve(g, x) == [5]
566
+
567
+ g = Piecewise(((x - 5)**5, x >= 2), (f, True))
568
+ assert solve(g, x) == [5]
569
+
570
+ g = Piecewise(((x - 5)**5, x >= 2), (f, True), (10, False))
571
+ assert solve(g, x) == [5]
572
+
573
+ g = Piecewise(((x - 5)**5, x >= 2),
574
+ (-x + 2, x - 2 <= 0), (x - 2, x - 2 > 0))
575
+ assert solve(g, x) == [5]
576
+
577
+ # if no symbol is given the piecewise detection must still work
578
+ assert solve(Piecewise((x - 2, x > 2), (2 - x, True)) - 3) == [-1, 5]
579
+
580
+ f = Piecewise(((x - 2)**2, x >= 0), (0, True))
581
+ raises(NotImplementedError, lambda: solve(f, x))
582
+
583
+ def nona(ans):
584
+ return list(filter(lambda x: x is not S.NaN, ans))
585
+ p = Piecewise((x**2 - 4, x < y), (x - 2, True))
586
+ ans = solve(p, x)
587
+ assert nona([i.subs(y, -2) for i in ans]) == [2]
588
+ assert nona([i.subs(y, 2) for i in ans]) == [-2, 2]
589
+ assert nona([i.subs(y, 3) for i in ans]) == [-2, 2]
590
+ assert ans == [
591
+ Piecewise((-2, y > -2), (S.NaN, True)),
592
+ Piecewise((2, y <= 2), (S.NaN, True)),
593
+ Piecewise((2, y > 2), (S.NaN, True))]
594
+
595
+ # issue 6060
596
+ absxm3 = Piecewise(
597
+ (x - 3, 0 <= x - 3),
598
+ (3 - x, 0 > x - 3)
599
+ )
600
+ assert solve(absxm3 - y, x) == [
601
+ Piecewise((-y + 3, -y < 0), (S.NaN, True)),
602
+ Piecewise((y + 3, y >= 0), (S.NaN, True))]
603
+ p = Symbol('p', positive=True)
604
+ assert solve(absxm3 - p, x) == [-p + 3, p + 3]
605
+
606
+ # issue 6989
607
+ f = Function('f')
608
+ assert solve(Eq(-f(x), Piecewise((1, x > 0), (0, True))), f(x)) == \
609
+ [Piecewise((-1, x > 0), (0, True))]
610
+
611
+ # issue 8587
612
+ f = Piecewise((2*x**2, And(0 < x, x < 1)), (2, True))
613
+ assert solve(f - 1) == [1/sqrt(2)]
614
+
615
+
616
+ def test_piecewise_fold():
617
+ p = Piecewise((x, x < 1), (1, 1 <= x))
618
+
619
+ assert piecewise_fold(x*p) == Piecewise((x**2, x < 1), (x, 1 <= x))
620
+ assert piecewise_fold(p + p) == Piecewise((2*x, x < 1), (2, 1 <= x))
621
+ assert piecewise_fold(Piecewise((1, x < 0), (2, True))
622
+ + Piecewise((10, x < 0), (-10, True))) == \
623
+ Piecewise((11, x < 0), (-8, True))
624
+
625
+ p1 = Piecewise((0, x < 0), (x, x <= 1), (0, True))
626
+ p2 = Piecewise((0, x < 0), (1 - x, x <= 1), (0, True))
627
+
628
+ p = 4*p1 + 2*p2
629
+ assert integrate(
630
+ piecewise_fold(p), (x, -oo, oo)) == integrate(2*x + 2, (x, 0, 1))
631
+
632
+ assert piecewise_fold(
633
+ Piecewise((1, y <= 0), (-Piecewise((2, y >= 0)), True)
634
+ )) == Piecewise((1, y <= 0), (-2, y >= 0))
635
+
636
+ assert piecewise_fold(Piecewise((x, ITE(x > 0, y < 1, y > 1)))
637
+ ) == Piecewise((x, ((x <= 0) | (y < 1)) & ((x > 0) | (y > 1))))
638
+
639
+ a, b = (Piecewise((2, Eq(x, 0)), (0, True)),
640
+ Piecewise((x, Eq(-x + y, 0)), (1, Eq(-x + y, 1)), (0, True)))
641
+ assert piecewise_fold(Mul(a, b, evaluate=False)
642
+ ) == piecewise_fold(Mul(b, a, evaluate=False))
643
+
644
+
645
+ def test_piecewise_fold_piecewise_in_cond():
646
+ p1 = Piecewise((cos(x), x < 0), (0, True))
647
+ p2 = Piecewise((0, Eq(p1, 0)), (p1 / Abs(p1), True))
648
+ assert p2.subs(x, -pi/2) == 0
649
+ assert p2.subs(x, 1) == 0
650
+ assert p2.subs(x, -pi/4) == 1
651
+ p4 = Piecewise((0, Eq(p1, 0)), (1,True))
652
+ ans = piecewise_fold(p4)
653
+ for i in range(-1, 1):
654
+ assert ans.subs(x, i) == p4.subs(x, i)
655
+
656
+ r1 = 1 < Piecewise((1, x < 1), (3, True))
657
+ ans = piecewise_fold(r1)
658
+ for i in range(2):
659
+ assert ans.subs(x, i) == r1.subs(x, i)
660
+
661
+ p5 = Piecewise((1, x < 0), (3, True))
662
+ p6 = Piecewise((1, x < 1), (3, True))
663
+ p7 = Piecewise((1, p5 < p6), (0, True))
664
+ ans = piecewise_fold(p7)
665
+ for i in range(-1, 2):
666
+ assert ans.subs(x, i) == p7.subs(x, i)
667
+
668
+
669
+ def test_piecewise_fold_piecewise_in_cond_2():
670
+ p1 = Piecewise((cos(x), x < 0), (0, True))
671
+ p2 = Piecewise((0, Eq(p1, 0)), (1 / p1, True))
672
+ p3 = Piecewise(
673
+ (0, (x >= 0) | Eq(cos(x), 0)),
674
+ (1/cos(x), x < 0),
675
+ (zoo, True)) # redundant b/c all x are already covered
676
+ assert(piecewise_fold(p2) == p3)
677
+
678
+
679
+ def test_piecewise_fold_expand():
680
+ p1 = Piecewise((1, Interval(0, 1, False, True).contains(x)), (0, True))
681
+
682
+ p2 = piecewise_fold(expand((1 - x)*p1))
683
+ cond = ((x >= 0) & (x < 1))
684
+ assert piecewise_fold(expand((1 - x)*p1), evaluate=False
685
+ ) == Piecewise((1 - x, cond), (-x, cond), (1, cond), (0, True), evaluate=False)
686
+ assert piecewise_fold(expand((1 - x)*p1), evaluate=None
687
+ ) == Piecewise((1 - x, cond), (0, True))
688
+ assert p2 == Piecewise((1 - x, cond), (0, True))
689
+ assert p2 == expand(piecewise_fold((1 - x)*p1))
690
+
691
+
692
+ def test_piecewise_duplicate():
693
+ p = Piecewise((x, x < -10), (x**2, x <= -1), (x, 1 < x))
694
+ assert p == Piecewise(*p.args)
695
+
696
+
697
+ def test_doit():
698
+ p1 = Piecewise((x, x < 1), (x**2, -1 <= x), (x, 3 < x))
699
+ p2 = Piecewise((x, x < 1), (Integral(2 * x), -1 <= x), (x, 3 < x))
700
+ assert p2.doit() == p1
701
+ assert p2.doit(deep=False) == p2
702
+ # issue 17165
703
+ p1 = Sum(y**x, (x, -1, oo)).doit()
704
+ assert p1.doit() == p1
705
+
706
+
707
+ def test_piecewise_interval():
708
+ p1 = Piecewise((x, Interval(0, 1).contains(x)), (0, True))
709
+ assert p1.subs(x, -0.5) == 0
710
+ assert p1.subs(x, 0.5) == 0.5
711
+ assert p1.diff(x) == Piecewise((1, Interval(0, 1).contains(x)), (0, True))
712
+ assert integrate(p1, x) == Piecewise(
713
+ (0, x <= 0),
714
+ (x**2/2, x <= 1),
715
+ (S.Half, True))
716
+
717
+
718
+ def test_piecewise_exclusive():
719
+ p = Piecewise((0, x < 0), (S.Half, x <= 0), (1, True))
720
+ assert piecewise_exclusive(p) == Piecewise((0, x < 0), (S.Half, Eq(x, 0)),
721
+ (1, x > 0), evaluate=False)
722
+ assert piecewise_exclusive(p + 2) == Piecewise((0, x < 0), (S.Half, Eq(x, 0)),
723
+ (1, x > 0), evaluate=False) + 2
724
+ assert piecewise_exclusive(Piecewise((1, y <= 0),
725
+ (-Piecewise((2, y >= 0)), True))) == \
726
+ Piecewise((1, y <= 0),
727
+ (-Piecewise((2, y >= 0),
728
+ (S.NaN, y < 0), evaluate=False), y > 0), evaluate=False)
729
+ assert piecewise_exclusive(Piecewise((1, x > y))) == Piecewise((1, x > y),
730
+ (S.NaN, x <= y),
731
+ evaluate=False)
732
+ assert piecewise_exclusive(Piecewise((1, x > y)),
733
+ skip_nan=True) == Piecewise((1, x > y))
734
+
735
+ xr, yr = symbols('xr, yr', real=True)
736
+
737
+ p1 = Piecewise((1, xr < 0), (2, True), evaluate=False)
738
+ p1x = Piecewise((1, xr < 0), (2, xr >= 0), evaluate=False)
739
+
740
+ p2 = Piecewise((p1, yr < 0), (3, True), evaluate=False)
741
+ p2x = Piecewise((p1, yr < 0), (3, yr >= 0), evaluate=False)
742
+ p2xx = Piecewise((p1x, yr < 0), (3, yr >= 0), evaluate=False)
743
+
744
+ assert piecewise_exclusive(p2) == p2xx
745
+ assert piecewise_exclusive(p2, deep=False) == p2x
746
+
747
+
748
+ def test_piecewise_collapse():
749
+ assert Piecewise((x, True)) == x
750
+ a = x < 1
751
+ assert Piecewise((x, a), (x + 1, a)) == Piecewise((x, a))
752
+ assert Piecewise((x, a), (x + 1, a.reversed)) == Piecewise((x, a))
753
+ b = x < 5
754
+ def canonical(i):
755
+ if isinstance(i, Piecewise):
756
+ return Piecewise(*i.args)
757
+ return i
758
+ for args in [
759
+ ((1, a), (Piecewise((2, a), (3, b)), b)),
760
+ ((1, a), (Piecewise((2, a), (3, b.reversed)), b)),
761
+ ((1, a), (Piecewise((2, a), (3, b)), b), (4, True)),
762
+ ((1, a), (Piecewise((2, a), (3, b), (4, True)), b)),
763
+ ((1, a), (Piecewise((2, a), (3, b), (4, True)), b), (5, True))]:
764
+ for i in (0, 2, 10):
765
+ assert canonical(
766
+ Piecewise(*args, evaluate=False).subs(x, i)
767
+ ) == canonical(Piecewise(*args).subs(x, i))
768
+ r1, r2, r3, r4 = symbols('r1:5')
769
+ a = x < r1
770
+ b = x < r2
771
+ c = x < r3
772
+ d = x < r4
773
+ assert Piecewise((1, a), (Piecewise(
774
+ (2, a), (3, b), (4, c)), b), (5, c)
775
+ ) == Piecewise((1, a), (3, b), (5, c))
776
+ assert Piecewise((1, a), (Piecewise(
777
+ (2, a), (3, b), (4, c), (6, True)), c), (5, d)
778
+ ) == Piecewise((1, a), (Piecewise(
779
+ (3, b), (4, c)), c), (5, d))
780
+ assert Piecewise((1, Or(a, d)), (Piecewise(
781
+ (2, d), (3, b), (4, c)), b), (5, c)
782
+ ) == Piecewise((1, Or(a, d)), (Piecewise(
783
+ (2, d), (3, b)), b), (5, c))
784
+ assert Piecewise((1, c), (2, ~c), (3, S.true)
785
+ ) == Piecewise((1, c), (2, S.true))
786
+ assert Piecewise((1, c), (2, And(~c, b)), (3,True)
787
+ ) == Piecewise((1, c), (2, b), (3, True))
788
+ assert Piecewise((1, c), (2, Or(~c, b)), (3,True)
789
+ ).subs(dict(zip((r1, r2, r3, r4, x), (1, 2, 3, 4, 3.5)))) == 2
790
+ assert Piecewise((1, c), (2, ~c)) == Piecewise((1, c), (2, True))
791
+
792
+
793
+ def test_piecewise_lambdify():
794
+ p = Piecewise(
795
+ (x**2, x < 0),
796
+ (x, Interval(0, 1, False, True).contains(x)),
797
+ (2 - x, x >= 1),
798
+ (0, True)
799
+ )
800
+
801
+ f = lambdify(x, p)
802
+ assert f(-2.0) == 4.0
803
+ assert f(0.0) == 0.0
804
+ assert f(0.5) == 0.5
805
+ assert f(2.0) == 0.0
806
+
807
+
808
+ def test_piecewise_series():
809
+ from sympy.series.order import O
810
+ p1 = Piecewise((sin(x), x < 0), (cos(x), x > 0))
811
+ p2 = Piecewise((x + O(x**2), x < 0), (1 + O(x**2), x > 0))
812
+ assert p1.nseries(x, n=2) == p2
813
+
814
+
815
+ def test_piecewise_as_leading_term():
816
+ p1 = Piecewise((1/x, x > 1), (0, True))
817
+ p2 = Piecewise((x, x > 1), (0, True))
818
+ p3 = Piecewise((1/x, x > 1), (x, True))
819
+ p4 = Piecewise((x, x > 1), (1/x, True))
820
+ p5 = Piecewise((1/x, x > 1), (x, True))
821
+ p6 = Piecewise((1/x, x < 1), (x, True))
822
+ p7 = Piecewise((x, x < 1), (1/x, True))
823
+ p8 = Piecewise((x, x > 1), (1/x, True))
824
+ assert p1.as_leading_term(x) == 0
825
+ assert p2.as_leading_term(x) == 0
826
+ assert p3.as_leading_term(x) == x
827
+ assert p4.as_leading_term(x) == 1/x
828
+ assert p5.as_leading_term(x) == x
829
+ assert p6.as_leading_term(x) == 1/x
830
+ assert p7.as_leading_term(x) == x
831
+ assert p8.as_leading_term(x) == 1/x
832
+
833
+
834
+ def test_piecewise_complex():
835
+ p1 = Piecewise((2, x < 0), (1, 0 <= x))
836
+ p2 = Piecewise((2*I, x < 0), (I, 0 <= x))
837
+ p3 = Piecewise((I*x, x > 1), (1 + I, True))
838
+ p4 = Piecewise((-I*conjugate(x), x > 1), (1 - I, True))
839
+
840
+ assert conjugate(p1) == p1
841
+ assert conjugate(p2) == piecewise_fold(-p2)
842
+ assert conjugate(p3) == p4
843
+
844
+ assert p1.is_imaginary is False
845
+ assert p1.is_real is True
846
+ assert p2.is_imaginary is True
847
+ assert p2.is_real is False
848
+ assert p3.is_imaginary is None
849
+ assert p3.is_real is None
850
+
851
+ assert p1.as_real_imag() == (p1, 0)
852
+ assert p2.as_real_imag() == (0, -I*p2)
853
+
854
+
855
+ def test_conjugate_transpose():
856
+ A, B = symbols("A B", commutative=False)
857
+ p = Piecewise((A*B**2, x > 0), (A**2*B, True))
858
+ assert p.adjoint() == \
859
+ Piecewise((adjoint(A*B**2), x > 0), (adjoint(A**2*B), True))
860
+ assert p.conjugate() == \
861
+ Piecewise((conjugate(A*B**2), x > 0), (conjugate(A**2*B), True))
862
+ assert p.transpose() == \
863
+ Piecewise((transpose(A*B**2), x > 0), (transpose(A**2*B), True))
864
+
865
+
866
+ def test_piecewise_evaluate():
867
+ assert Piecewise((x, True)) == x
868
+ assert Piecewise((x, True), evaluate=True) == x
869
+ assert Piecewise((1, Eq(1, x))).args == ((1, Eq(x, 1)),)
870
+ assert Piecewise((1, Eq(1, x)), evaluate=False).args == (
871
+ (1, Eq(1, x)),)
872
+ # like the additive and multiplicative identities that
873
+ # cannot be kept in Add/Mul, we also do not keep a single True
874
+ p = Piecewise((x, True), evaluate=False)
875
+ assert p == x
876
+
877
+
878
+ def test_as_expr_set_pairs():
879
+ assert Piecewise((x, x > 0), (-x, x <= 0)).as_expr_set_pairs() == \
880
+ [(x, Interval(0, oo, True, True)), (-x, Interval(-oo, 0))]
881
+
882
+ assert Piecewise(((x - 2)**2, x >= 0), (0, True)).as_expr_set_pairs() == \
883
+ [((x - 2)**2, Interval(0, oo)), (0, Interval(-oo, 0, True, True))]
884
+
885
+
886
+ def test_S_srepr_is_identity():
887
+ p = Piecewise((10, Eq(x, 0)), (12, True))
888
+ q = S(srepr(p))
889
+ assert p == q
890
+
891
+
892
+ def test_issue_12587():
893
+ # sort holes into intervals
894
+ p = Piecewise((1, x > 4), (2, Not((x <= 3) & (x > -1))), (3, True))
895
+ assert p.integrate((x, -5, 5)) == 23
896
+ p = Piecewise((1, x > 1), (2, x < y), (3, True))
897
+ lim = x, -3, 3
898
+ ans = p.integrate(lim)
899
+ for i in range(-1, 3):
900
+ assert ans.subs(y, i) == p.subs(y, i).integrate(lim)
901
+
902
+
903
+ def test_issue_11045():
904
+ assert integrate(1/(x*sqrt(x**2 - 1)), (x, 1, 2)) == pi/3
905
+
906
+ # handle And with Or arguments
907
+ assert Piecewise((1, And(Or(x < 1, x > 3), x < 2)), (0, True)
908
+ ).integrate((x, 0, 3)) == 1
909
+
910
+ # hidden false
911
+ assert Piecewise((1, x > 1), (2, x > x + 1), (3, True)
912
+ ).integrate((x, 0, 3)) == 5
913
+ # targetcond is Eq
914
+ assert Piecewise((1, x > 1), (2, Eq(1, x)), (3, True)
915
+ ).integrate((x, 0, 4)) == 6
916
+ # And has Relational needing to be solved
917
+ assert Piecewise((1, And(2*x > x + 1, x < 2)), (0, True)
918
+ ).integrate((x, 0, 3)) == 1
919
+ # Or has Relational needing to be solved
920
+ assert Piecewise((1, Or(2*x > x + 2, x < 1)), (0, True)
921
+ ).integrate((x, 0, 3)) == 2
922
+ # ignore hidden false (handled in canonicalization)
923
+ assert Piecewise((1, x > 1), (2, x > x + 1), (3, True)
924
+ ).integrate((x, 0, 3)) == 5
925
+ # watch for hidden True Piecewise
926
+ assert Piecewise((2, Eq(1 - x, x*(1/x - 1))), (0, True)
927
+ ).integrate((x, 0, 3)) == 6
928
+
929
+ # overlapping conditions of targetcond are recognized and ignored;
930
+ # the condition x > 3 will be pre-empted by the first condition
931
+ assert Piecewise((1, Or(x < 1, x > 2)), (2, x > 3), (3, True)
932
+ ).integrate((x, 0, 4)) == 6
933
+
934
+ # convert Ne to Or
935
+ assert Piecewise((1, Ne(x, 0)), (2, True)
936
+ ).integrate((x, -1, 1)) == 2
937
+
938
+ # no default but well defined
939
+ assert Piecewise((x, (x > 1) & (x < 3)), (1, (x < 4))
940
+ ).integrate((x, 1, 4)) == 5
941
+
942
+ p = Piecewise((x, (x > 1) & (x < 3)), (1, (x < 4)))
943
+ nan = Undefined
944
+ i = p.integrate((x, 1, y))
945
+ assert i == Piecewise(
946
+ (y - 1, y < 1),
947
+ (Min(3, y)**2/2 - Min(3, y) + Min(4, y) - S.Half,
948
+ y <= Min(4, y)),
949
+ (nan, True))
950
+ assert p.integrate((x, 1, -1)) == i.subs(y, -1)
951
+ assert p.integrate((x, 1, 4)) == 5
952
+ assert p.integrate((x, 1, 5)) is nan
953
+
954
+ # handle Not
955
+ p = Piecewise((1, x > 1), (2, Not(And(x > 1, x< 3))), (3, True))
956
+ assert p.integrate((x, 0, 3)) == 4
957
+
958
+ # handle updating of int_expr when there is overlap
959
+ p = Piecewise(
960
+ (1, And(5 > x, x > 1)),
961
+ (2, Or(x < 3, x > 7)),
962
+ (4, x < 8))
963
+ assert p.integrate((x, 0, 10)) == 20
964
+
965
+ # And with Eq arg handling
966
+ assert Piecewise((1, x < 1), (2, And(Eq(x, 3), x > 1))
967
+ ).integrate((x, 0, 3)) is S.NaN
968
+ assert Piecewise((1, x < 1), (2, And(Eq(x, 3), x > 1)), (3, True)
969
+ ).integrate((x, 0, 3)) == 7
970
+ assert Piecewise((1, x < 0), (2, And(Eq(x, 3), x < 1)), (3, True)
971
+ ).integrate((x, -1, 1)) == 4
972
+ # middle condition doesn't matter: it's a zero width interval
973
+ assert Piecewise((1, x < 1), (2, Eq(x, 3) & (y < x)), (3, True)
974
+ ).integrate((x, 0, 3)) == 7
975
+
976
+
977
+ def test_holes():
978
+ nan = Undefined
979
+ assert Piecewise((1, x < 2)).integrate(x) == Piecewise(
980
+ (x, x < 2), (nan, True))
981
+ assert Piecewise((1, And(x > 1, x < 2))).integrate(x) == Piecewise(
982
+ (nan, x < 1), (x, x < 2), (nan, True))
983
+ assert Piecewise((1, And(x > 1, x < 2))).integrate((x, 0, 3)) is nan
984
+ assert Piecewise((1, And(x > 0, x < 4))).integrate((x, 1, 3)) == 2
985
+
986
+ # this also tests that the integrate method is used on non-Piecwise
987
+ # arguments in _eval_integral
988
+ A, B = symbols("A B")
989
+ a, b = symbols('a b', real=True)
990
+ assert Piecewise((A, And(x < 0, a < 1)), (B, Or(x < 1, a > 2))
991
+ ).integrate(x) == Piecewise(
992
+ (B*x, (a > 2)),
993
+ (Piecewise((A*x, x < 0), (B*x, x < 1), (nan, True)), a < 1),
994
+ (Piecewise((B*x, x < 1), (nan, True)), True))
995
+
996
+
997
+ def test_issue_11922():
998
+ def f(x):
999
+ return Piecewise((0, x < -1), (1 - x**2, x < 1), (0, True))
1000
+ autocorr = lambda k: (
1001
+ f(x) * f(x + k)).integrate((x, -1, 1))
1002
+ assert autocorr(1.9) > 0
1003
+ k = symbols('k')
1004
+ good_autocorr = lambda k: (
1005
+ (1 - x**2) * f(x + k)).integrate((x, -1, 1))
1006
+ a = good_autocorr(k)
1007
+ assert a.subs(k, 3) == 0
1008
+ k = symbols('k', positive=True)
1009
+ a = good_autocorr(k)
1010
+ assert a.subs(k, 3) == 0
1011
+ assert Piecewise((0, x < 1), (10, (x >= 1))
1012
+ ).integrate() == Piecewise((0, x < 1), (10*x - 10, True))
1013
+
1014
+
1015
+ def test_issue_5227():
1016
+ f = 0.0032513612725229*Piecewise((0, x < -80.8461538461539),
1017
+ (-0.0160799238820171*x + 1.33215984776403, x < 2),
1018
+ (Piecewise((0.3, x > 123), (0.7, True)) +
1019
+ Piecewise((0.4, x > 2), (0.6, True)), x <=
1020
+ 123), (-0.00817409766454352*x + 2.10541401273885, x <
1021
+ 380.571428571429), (0, True))
1022
+ i = integrate(f, (x, -oo, oo))
1023
+ assert i == Integral(f, (x, -oo, oo)).doit()
1024
+ assert str(i) == '1.00195081676351'
1025
+ assert Piecewise((1, x - y < 0), (0, True)
1026
+ ).integrate(y) == Piecewise((0, y <= x), (-x + y, True))
1027
+
1028
+
1029
+ def test_issue_10137():
1030
+ a = Symbol('a', real=True)
1031
+ b = Symbol('b', real=True)
1032
+ x = Symbol('x', real=True)
1033
+ y = Symbol('y', real=True)
1034
+ p0 = Piecewise((0, Or(x < a, x > b)), (1, True))
1035
+ p1 = Piecewise((0, Or(a > x, b < x)), (1, True))
1036
+ assert integrate(p0, (x, y, oo)) == integrate(p1, (x, y, oo))
1037
+ p3 = Piecewise((1, And(0 < x, x < a)), (0, True))
1038
+ p4 = Piecewise((1, And(a > x, x > 0)), (0, True))
1039
+ ip3 = integrate(p3, x)
1040
+ assert ip3 == Piecewise(
1041
+ (0, x <= 0),
1042
+ (x, x <= Max(0, a)),
1043
+ (Max(0, a), True))
1044
+ ip4 = integrate(p4, x)
1045
+ assert ip4 == ip3
1046
+ assert p3.integrate((x, 2, 4)) == Min(4, Max(2, a)) - 2
1047
+ assert p4.integrate((x, 2, 4)) == Min(4, Max(2, a)) - 2
1048
+
1049
+
1050
+ def test_stackoverflow_43852159():
1051
+ f = lambda x: Piecewise((1, (x >= -1) & (x <= 1)), (0, True))
1052
+ Conv = lambda x: integrate(f(x - y)*f(y), (y, -oo, +oo))
1053
+ cx = Conv(x)
1054
+ assert cx.subs(x, -1.5) == cx.subs(x, 1.5)
1055
+ assert cx.subs(x, 3) == 0
1056
+ assert piecewise_fold(f(x - y)*f(y)) == Piecewise(
1057
+ (1, (y >= -1) & (y <= 1) & (x - y >= -1) & (x - y <= 1)),
1058
+ (0, True))
1059
+
1060
+
1061
+ def test_issue_12557():
1062
+ '''
1063
+ # 3200 seconds to compute the fourier part of issue
1064
+ import sympy as sym
1065
+ x,y,z,t = sym.symbols('x y z t')
1066
+ k = sym.symbols("k", integer=True)
1067
+ fourier = sym.fourier_series(sym.cos(k*x)*sym.sqrt(x**2),
1068
+ (x, -sym.pi, sym.pi))
1069
+ assert fourier == FourierSeries(
1070
+ sqrt(x**2)*cos(k*x), (x, -pi, pi), (Piecewise((pi**2,
1071
+ Eq(k, 0)), (2*(-1)**k/k**2 - 2/k**2, True))/(2*pi),
1072
+ SeqFormula(Piecewise((pi**2, (Eq(_n, 0) & Eq(k, 0)) | (Eq(_n, 0) &
1073
+ Eq(_n, k) & Eq(k, 0)) | (Eq(_n, 0) & Eq(k, 0) & Eq(_n, -k)) | (Eq(_n,
1074
+ 0) & Eq(_n, k) & Eq(k, 0) & Eq(_n, -k))), (pi**2/2, Eq(_n, k) | Eq(_n,
1075
+ -k) | (Eq(_n, 0) & Eq(_n, k)) | (Eq(_n, k) & Eq(k, 0)) | (Eq(_n, 0) &
1076
+ Eq(_n, -k)) | (Eq(_n, k) & Eq(_n, -k)) | (Eq(k, 0) & Eq(_n, -k)) |
1077
+ (Eq(_n, 0) & Eq(_n, k) & Eq(_n, -k)) | (Eq(_n, k) & Eq(k, 0) & Eq(_n,
1078
+ -k))), ((-1)**k*pi**2*_n**3*sin(pi*_n)/(pi*_n**4 - 2*pi*_n**2*k**2 +
1079
+ pi*k**4) - (-1)**k*pi**2*_n**3*sin(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2
1080
+ - pi*k**4) + (-1)**k*pi*_n**2*cos(pi*_n)/(pi*_n**4 - 2*pi*_n**2*k**2 +
1081
+ pi*k**4) - (-1)**k*pi*_n**2*cos(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2 -
1082
+ pi*k**4) - (-1)**k*pi**2*_n*k**2*sin(pi*_n)/(pi*_n**4 -
1083
+ 2*pi*_n**2*k**2 + pi*k**4) +
1084
+ (-1)**k*pi**2*_n*k**2*sin(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2 -
1085
+ pi*k**4) + (-1)**k*pi*k**2*cos(pi*_n)/(pi*_n**4 - 2*pi*_n**2*k**2 +
1086
+ pi*k**4) - (-1)**k*pi*k**2*cos(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2 -
1087
+ pi*k**4) - (2*_n**2 + 2*k**2)/(_n**4 - 2*_n**2*k**2 + k**4),
1088
+ True))*cos(_n*x)/pi, (_n, 1, oo)), SeqFormula(0, (_k, 1, oo))))
1089
+ '''
1090
+ x = symbols("x", real=True)
1091
+ k = symbols('k', integer=True, finite=True)
1092
+ abs2 = lambda x: Piecewise((-x, x <= 0), (x, x > 0))
1093
+ assert integrate(abs2(x), (x, -pi, pi)) == pi**2
1094
+ func = cos(k*x)*sqrt(x**2)
1095
+ assert integrate(func, (x, -pi, pi)) == Piecewise(
1096
+ (2*(-1)**k/k**2 - 2/k**2, Ne(k, 0)), (pi**2, True))
1097
+
1098
+ def test_issue_6900():
1099
+ from itertools import permutations
1100
+ t0, t1, T, t = symbols('t0, t1 T t')
1101
+ f = Piecewise((0, t < t0), (x, And(t0 <= t, t < t1)), (0, t >= t1))
1102
+ g = f.integrate(t)
1103
+ assert g == Piecewise(
1104
+ (0, t <= t0),
1105
+ (t*x - t0*x, t <= Max(t0, t1)),
1106
+ (-t0*x + x*Max(t0, t1), True))
1107
+ for i in permutations(range(2)):
1108
+ reps = dict(zip((t0,t1), i))
1109
+ for tt in range(-1,3):
1110
+ assert (g.xreplace(reps).subs(t,tt) ==
1111
+ f.xreplace(reps).integrate(t).subs(t,tt))
1112
+ lim = Tuple(t, t0, T)
1113
+ g = f.integrate(lim)
1114
+ ans = Piecewise(
1115
+ (-t0*x + x*Min(T, Max(t0, t1)), T > t0),
1116
+ (0, True))
1117
+ for i in permutations(range(3)):
1118
+ reps = dict(zip((t0,t1,T), i))
1119
+ tru = f.xreplace(reps).integrate(lim.xreplace(reps))
1120
+ assert tru == ans.xreplace(reps)
1121
+ assert g == ans
1122
+
1123
+
1124
+ def test_issue_10122():
1125
+ assert solve(abs(x) + abs(x - 1) - 1 > 0, x
1126
+ ) == Or(And(-oo < x, x < S.Zero), And(S.One < x, x < oo))
1127
+
1128
+
1129
+ def test_issue_4313():
1130
+ u = Piecewise((0, x <= 0), (1, x >= a), (x/a, True))
1131
+ e = (u - u.subs(x, y))**2/(x - y)**2
1132
+ M = Max(0, a)
1133
+ assert integrate(e, x).expand() == Piecewise(
1134
+ (Piecewise(
1135
+ (0, x <= 0),
1136
+ (-y**2/(a**2*x - a**2*y) + x/a**2 - 2*y*log(-y)/a**2 +
1137
+ 2*y*log(x - y)/a**2 - y/a**2, x <= M),
1138
+ (-y**2/(-a**2*y + a**2*M) + 1/(-y + M) -
1139
+ 1/(x - y) - 2*y*log(-y)/a**2 + 2*y*log(-y +
1140
+ M)/a**2 - y/a**2 + M/a**2, True)),
1141
+ ((a <= y) & (y <= 0)) | ((y <= 0) & (y > -oo))),
1142
+ (Piecewise(
1143
+ (-1/(x - y), x <= 0),
1144
+ (-a**2/(a**2*x - a**2*y) + 2*a*y/(a**2*x - a**2*y) -
1145
+ y**2/(a**2*x - a**2*y) + 2*log(-y)/a - 2*log(x - y)/a +
1146
+ 2/a + x/a**2 - 2*y*log(-y)/a**2 + 2*y*log(x - y)/a**2 -
1147
+ y/a**2, x <= M),
1148
+ (-a**2/(-a**2*y + a**2*M) + 2*a*y/(-a**2*y +
1149
+ a**2*M) - y**2/(-a**2*y + a**2*M) +
1150
+ 2*log(-y)/a - 2*log(-y + M)/a + 2/a -
1151
+ 2*y*log(-y)/a**2 + 2*y*log(-y + M)/a**2 -
1152
+ y/a**2 + M/a**2, True)),
1153
+ a <= y),
1154
+ (Piecewise(
1155
+ (-y**2/(a**2*x - a**2*y), x <= 0),
1156
+ (x/a**2 + y/a**2, x <= M),
1157
+ (a**2/(-a**2*y + a**2*M) -
1158
+ a**2/(a**2*x - a**2*y) - 2*a*y/(-a**2*y + a**2*M) +
1159
+ 2*a*y/(a**2*x - a**2*y) + y**2/(-a**2*y + a**2*M) -
1160
+ y**2/(a**2*x - a**2*y) + y/a**2 + M/a**2, True)),
1161
+ True))
1162
+
1163
+
1164
+ def test__intervals():
1165
+ assert Piecewise((x + 2, Eq(x, 3)))._intervals(x) == (True, [])
1166
+ assert Piecewise(
1167
+ (1, x > x + 1),
1168
+ (Piecewise((1, x < x + 1)), 2*x < 2*x + 1),
1169
+ (1, True))._intervals(x) == (True, [(-oo, oo, 1, 1)])
1170
+ assert Piecewise((1, Ne(x, I)), (0, True))._intervals(x) == (True,
1171
+ [(-oo, oo, 1, 0)])
1172
+ assert Piecewise((-cos(x), sin(x) >= 0), (cos(x), True)
1173
+ )._intervals(x) == (True,
1174
+ [(0, pi, -cos(x), 0), (-oo, oo, cos(x), 1)])
1175
+ # the following tests that duplicates are removed and that non-Eq
1176
+ # generated zero-width intervals are removed
1177
+ assert Piecewise((1, Abs(x**(-2)) > 1), (0, True)
1178
+ )._intervals(x) == (True,
1179
+ [(-1, 0, 1, 0), (0, 1, 1, 0), (-oo, oo, 0, 1)])
1180
+
1181
+
1182
+ def test_containment():
1183
+ a, b, c, d, e = [1, 2, 3, 4, 5]
1184
+ p = (Piecewise((d, x > 1), (e, True))*
1185
+ Piecewise((a, Abs(x - 1) < 1), (b, Abs(x - 2) < 2), (c, True)))
1186
+ assert p.integrate(x).diff(x) == Piecewise(
1187
+ (c*e, x <= 0),
1188
+ (a*e, x <= 1),
1189
+ (a*d, x < 2), # this is what we want to get right
1190
+ (b*d, x < 4),
1191
+ (c*d, True))
1192
+
1193
+
1194
+ def test_piecewise_with_DiracDelta():
1195
+ d1 = DiracDelta(x - 1)
1196
+ assert integrate(d1, (x, -oo, oo)) == 1
1197
+ assert integrate(d1, (x, 0, 2)) == 1
1198
+ assert Piecewise((d1, Eq(x, 2)), (0, True)).integrate(x) == 0
1199
+ assert Piecewise((d1, x < 2), (0, True)).integrate(x) == Piecewise(
1200
+ (Heaviside(x - 1), x < 2), (1, True))
1201
+ # TODO raise error if function is discontinuous at limit of
1202
+ # integration, e.g. integrate(d1, (x, -2, 1)) or Piecewise(
1203
+ # (d1, Eq(x, 1)
1204
+
1205
+
1206
+ def test_issue_10258():
1207
+ assert Piecewise((0, x < 1), (1, True)).is_zero is None
1208
+ assert Piecewise((-1, x < 1), (1, True)).is_zero is False
1209
+ a = Symbol('a', zero=True)
1210
+ assert Piecewise((0, x < 1), (a, True)).is_zero
1211
+ assert Piecewise((1, x < 1), (a, x < 3)).is_zero is None
1212
+ a = Symbol('a')
1213
+ assert Piecewise((0, x < 1), (a, True)).is_zero is None
1214
+ assert Piecewise((0, x < 1), (1, True)).is_nonzero is None
1215
+ assert Piecewise((1, x < 1), (2, True)).is_nonzero
1216
+ assert Piecewise((0, x < 1), (oo, True)).is_finite is None
1217
+ assert Piecewise((0, x < 1), (1, True)).is_finite
1218
+ b = Basic()
1219
+ assert Piecewise((b, x < 1)).is_finite is None
1220
+
1221
+ # 10258
1222
+ c = Piecewise((1, x < 0), (2, True)) < 3
1223
+ assert c != True
1224
+ assert piecewise_fold(c) == True
1225
+
1226
+
1227
+ def test_issue_10087():
1228
+ a, b = Piecewise((x, x > 1), (2, True)), Piecewise((x, x > 3), (3, True))
1229
+ m = a*b
1230
+ f = piecewise_fold(m)
1231
+ for i in (0, 2, 4):
1232
+ assert m.subs(x, i) == f.subs(x, i)
1233
+ m = a + b
1234
+ f = piecewise_fold(m)
1235
+ for i in (0, 2, 4):
1236
+ assert m.subs(x, i) == f.subs(x, i)
1237
+
1238
+
1239
+ def test_issue_8919():
1240
+ c = symbols('c:5')
1241
+ x = symbols("x")
1242
+ f1 = Piecewise((c[1], x < 1), (c[2], True))
1243
+ f2 = Piecewise((c[3], x < Rational(1, 3)), (c[4], True))
1244
+ assert integrate(f1*f2, (x, 0, 2)
1245
+ ) == c[1]*c[3]/3 + 2*c[1]*c[4]/3 + c[2]*c[4]
1246
+ f1 = Piecewise((0, x < 1), (2, True))
1247
+ f2 = Piecewise((3, x < 2), (0, True))
1248
+ assert integrate(f1*f2, (x, 0, 3)) == 6
1249
+
1250
+ y = symbols("y", positive=True)
1251
+ a, b, c, x, z = symbols("a,b,c,x,z", real=True)
1252
+ I = Integral(Piecewise(
1253
+ (0, (x >= y) | (x < 0) | (b > c)),
1254
+ (a, True)), (x, 0, z))
1255
+ ans = I.doit()
1256
+ assert ans == Piecewise((0, b > c), (a*Min(y, z) - a*Min(0, z), True))
1257
+ for cond in (True, False):
1258
+ for yy in range(1, 3):
1259
+ for zz in range(-yy, 0, yy):
1260
+ reps = [(b > c, cond), (y, yy), (z, zz)]
1261
+ assert ans.subs(reps) == I.subs(reps).doit()
1262
+
1263
+
1264
+ def test_unevaluated_integrals():
1265
+ f = Function('f')
1266
+ p = Piecewise((1, Eq(f(x) - 1, 0)), (2, x - 10 < 0), (0, True))
1267
+ assert p.integrate(x) == Integral(p, x)
1268
+ assert p.integrate((x, 0, 5)) == Integral(p, (x, 0, 5))
1269
+ # test it by replacing f(x) with x%2 which will not
1270
+ # affect the answer: the integrand is essentially 2 over
1271
+ # the domain of integration
1272
+ assert Integral(p, (x, 0, 5)).subs(f(x), x%2).n() == 10.0
1273
+
1274
+ # this is a test of using _solve_inequality when
1275
+ # solve_univariate_inequality fails
1276
+ assert p.integrate(y) == Piecewise(
1277
+ (y, Eq(f(x), 1) | ((x < 10) & Eq(f(x), 1))),
1278
+ (2*y, (x > -oo) & (x < 10)), (0, True))
1279
+
1280
+
1281
+ def test_conditions_as_alternate_booleans():
1282
+ a, b, c = symbols('a:c')
1283
+ assert Piecewise((x, Piecewise((y < 1, x > 0), (y > 1, True)))
1284
+ ) == Piecewise((x, ITE(x > 0, y < 1, y > 1)))
1285
+
1286
+
1287
+ def test_Piecewise_rewrite_as_ITE():
1288
+ a, b, c, d = symbols('a:d')
1289
+
1290
+ def _ITE(*args):
1291
+ return Piecewise(*args).rewrite(ITE)
1292
+
1293
+ assert _ITE((a, x < 1), (b, x >= 1)) == ITE(x < 1, a, b)
1294
+ assert _ITE((a, x < 1), (b, x < oo)) == ITE(x < 1, a, b)
1295
+ assert _ITE((a, x < 1), (b, Or(y < 1, x < oo)), (c, y > 0)
1296
+ ) == ITE(x < 1, a, b)
1297
+ assert _ITE((a, x < 1), (b, True)) == ITE(x < 1, a, b)
1298
+ assert _ITE((a, x < 1), (b, x < 2), (c, True)
1299
+ ) == ITE(x < 1, a, ITE(x < 2, b, c))
1300
+ assert _ITE((a, x < 1), (b, y < 2), (c, True)
1301
+ ) == ITE(x < 1, a, ITE(y < 2, b, c))
1302
+ assert _ITE((a, x < 1), (b, x < oo), (c, y < 1)
1303
+ ) == ITE(x < 1, a, b)
1304
+ assert _ITE((a, x < 1), (c, y < 1), (b, x < oo), (d, True)
1305
+ ) == ITE(x < 1, a, ITE(y < 1, c, b))
1306
+ assert _ITE((a, x < 0), (b, Or(x < oo, y < 1))
1307
+ ) == ITE(x < 0, a, b)
1308
+ raises(TypeError, lambda: _ITE((x + 1, x < 1), (x, True)))
1309
+ # if `a` in the following were replaced with y then the coverage
1310
+ # is complete but something other than as_set would need to be
1311
+ # used to detect this
1312
+ raises(NotImplementedError, lambda: _ITE((x, x < y), (y, x >= a)))
1313
+ raises(ValueError, lambda: _ITE((a, x < 2), (b, x > 3)))
1314
+
1315
+
1316
+ def test_issue_14052():
1317
+ assert integrate(abs(sin(x)), (x, 0, 2*pi)) == 4
1318
+
1319
+
1320
+ def test_issue_14240():
1321
+ assert piecewise_fold(
1322
+ Piecewise((1, a), (2, b), (4, True)) +
1323
+ Piecewise((8, a), (16, True))
1324
+ ) == Piecewise((9, a), (18, b), (20, True))
1325
+ assert piecewise_fold(
1326
+ Piecewise((2, a), (3, b), (5, True)) *
1327
+ Piecewise((7, a), (11, True))
1328
+ ) == Piecewise((14, a), (33, b), (55, True))
1329
+ # these will hang if naive folding is used
1330
+ assert piecewise_fold(Add(*[
1331
+ Piecewise((i, a), (0, True)) for i in range(40)])
1332
+ ) == Piecewise((780, a), (0, True))
1333
+ assert piecewise_fold(Mul(*[
1334
+ Piecewise((i, a), (0, True)) for i in range(1, 41)])
1335
+ ) == Piecewise((factorial(40), a), (0, True))
1336
+
1337
+
1338
+ def test_issue_14787():
1339
+ x = Symbol('x')
1340
+ f = Piecewise((x, x < 1), ((S(58) / 7), True))
1341
+ assert str(f.evalf()) == "Piecewise((x, x < 1), (8.28571428571429, True))"
1342
+
1343
+ def test_issue_21481():
1344
+ b, e = symbols('b e')
1345
+ C = Piecewise(
1346
+ (2,
1347
+ ((b > 1) & (e > 0)) |
1348
+ ((b > 0) & (b < 1) & (e < 0)) |
1349
+ ((e >= 2) & (b < -1) & Eq(Mod(e, 2), 0)) |
1350
+ ((e <= -2) & (b > -1) & (b < 0) & Eq(Mod(e, 2), 0))),
1351
+ (S.Half,
1352
+ ((b > 1) & (e < 0)) |
1353
+ ((b > 0) & (e > 0) & (b < 1)) |
1354
+ ((e <= -2) & (b < -1) & Eq(Mod(e, 2), 0)) |
1355
+ ((e >= 2) & (b > -1) & (b < 0) & Eq(Mod(e, 2), 0))),
1356
+ (-S.Half,
1357
+ Eq(Mod(e, 2), 1) &
1358
+ (((e <= -1) & (b < -1)) | ((e >= 1) & (b > -1) & (b < 0)))),
1359
+ (-2,
1360
+ ((e >= 1) & (b < -1) & Eq(Mod(e, 2), 1)) |
1361
+ ((e <= -1) & (b > -1) & (b < 0) & Eq(Mod(e, 2), 1)))
1362
+ )
1363
+ A = Piecewise(
1364
+ (1, Eq(b, 1) | Eq(e, 0) | (Eq(b, -1) & Eq(Mod(e, 2), 0))),
1365
+ (0, Eq(b, 0) & (e > 0)),
1366
+ (-1, Eq(b, -1) & Eq(Mod(e, 2), 1)),
1367
+ (C, Eq(im(b), 0) & Eq(im(e), 0))
1368
+ )
1369
+
1370
+ B = piecewise_fold(A)
1371
+ sa = A.simplify()
1372
+ sb = B.simplify()
1373
+ v = (-2, -1, -S.Half, 0, S.Half, 1, 2)
1374
+ for i in v:
1375
+ for j in v:
1376
+ r = {b:i, e:j}
1377
+ ok = [k.xreplace(r) for k in (A, B, sa, sb)]
1378
+ assert len(set(ok)) == 1
1379
+
1380
+
1381
+ def test_issue_8458():
1382
+ x, y = symbols('x y')
1383
+ # Original issue
1384
+ p1 = Piecewise((0, Eq(x, 0)), (sin(x), True))
1385
+ assert p1.simplify() == sin(x)
1386
+ # Slightly larger variant
1387
+ p2 = Piecewise((x, Eq(x, 0)), (4*x + (y-2)**4, Eq(x, 0) & Eq(x+y, 2)), (sin(x), True))
1388
+ assert p2.simplify() == sin(x)
1389
+ # Test for problem highlighted during review
1390
+ p3 = Piecewise((x+1, Eq(x, -1)), (4*x + (y-2)**4, Eq(x, 0) & Eq(x+y, 2)), (sin(x), True))
1391
+ assert p3.simplify() == Piecewise((0, Eq(x, -1)), (sin(x), True))
1392
+
1393
+
1394
+ def test_issue_16417():
1395
+ z = Symbol('z')
1396
+ assert unchanged(Piecewise, (1, Or(Eq(im(z), 0), Gt(re(z), 0))), (2, True))
1397
+
1398
+ x = Symbol('x')
1399
+ assert unchanged(Piecewise, (S.Pi, re(x) < 0),
1400
+ (0, Or(re(x) > 0, Ne(im(x), 0))),
1401
+ (S.NaN, True))
1402
+ r = Symbol('r', real=True)
1403
+ p = Piecewise((S.Pi, re(r) < 0),
1404
+ (0, Or(re(r) > 0, Ne(im(r), 0))),
1405
+ (S.NaN, True))
1406
+ assert p == Piecewise((S.Pi, r < 0),
1407
+ (0, r > 0),
1408
+ (S.NaN, True), evaluate=False)
1409
+ # Does not work since imaginary != 0...
1410
+ #i = Symbol('i', imaginary=True)
1411
+ #p = Piecewise((S.Pi, re(i) < 0),
1412
+ # (0, Or(re(i) > 0, Ne(im(i), 0))),
1413
+ # (S.NaN, True))
1414
+ #assert p == Piecewise((0, Ne(im(i), 0)),
1415
+ # (S.NaN, True), evaluate=False)
1416
+ i = I*r
1417
+ p = Piecewise((S.Pi, re(i) < 0),
1418
+ (0, Or(re(i) > 0, Ne(im(i), 0))),
1419
+ (S.NaN, True))
1420
+ assert p == Piecewise((0, Ne(im(i), 0)),
1421
+ (S.NaN, True), evaluate=False)
1422
+ assert p == Piecewise((0, Ne(r, 0)),
1423
+ (S.NaN, True), evaluate=False)
1424
+
1425
+
1426
+ def test_eval_rewrite_as_KroneckerDelta():
1427
+ x, y, z, n, t, m = symbols('x y z n t m')
1428
+ K = KroneckerDelta
1429
+ f = lambda p: expand(p.rewrite(K))
1430
+
1431
+ p1 = Piecewise((0, Eq(x, y)), (1, True))
1432
+ assert f(p1) == 1 - K(x, y)
1433
+
1434
+ p2 = Piecewise((x, Eq(y,0)), (z, Eq(t,0)), (n, True))
1435
+ assert f(p2) == n*K(0, t)*K(0, y) - n*K(0, t) - n*K(0, y) + n + \
1436
+ x*K(0, y) - z*K(0, t)*K(0, y) + z*K(0, t)
1437
+
1438
+ p3 = Piecewise((1, Ne(x, y)), (0, True))
1439
+ assert f(p3) == 1 - K(x, y)
1440
+
1441
+ p4 = Piecewise((1, Eq(x, 3)), (4, True), (5, True))
1442
+ assert f(p4) == 4 - 3*K(3, x)
1443
+
1444
+ p5 = Piecewise((3, Ne(x, 2)), (4, Eq(y, 2)), (5, True))
1445
+ assert f(p5) == -K(2, x)*K(2, y) + 2*K(2, x) + 3
1446
+
1447
+ p6 = Piecewise((0, Ne(x, 1) & Ne(y, 4)), (1, True))
1448
+ assert f(p6) == -K(1, x)*K(4, y) + K(1, x) + K(4, y)
1449
+
1450
+ p7 = Piecewise((2, Eq(y, 3) & Ne(x, 2)), (1, True))
1451
+ assert f(p7) == -K(2, x)*K(3, y) + K(3, y) + 1
1452
+
1453
+ p8 = Piecewise((4, Eq(x, 3) & Ne(y, 2)), (1, True))
1454
+ assert f(p8) == -3*K(2, y)*K(3, x) + 3*K(3, x) + 1
1455
+
1456
+ p9 = Piecewise((6, Eq(x, 4) & Eq(y, 1)), (1, True))
1457
+ assert f(p9) == 5 * K(1, y) * K(4, x) + 1
1458
+
1459
+ p10 = Piecewise((4, Ne(x, -4) | Ne(y, 1)), (1, True))
1460
+ assert f(p10) == -3 * K(-4, x) * K(1, y) + 4
1461
+
1462
+ p11 = Piecewise((1, Eq(y, 2) | Ne(x, -3)), (2, True))
1463
+ assert f(p11) == -K(-3, x)*K(2, y) + K(-3, x) + 1
1464
+
1465
+ p12 = Piecewise((-1, Eq(x, 1) | Ne(y, 3)), (1, True))
1466
+ assert f(p12) == -2*K(1, x)*K(3, y) + 2*K(3, y) - 1
1467
+
1468
+ p13 = Piecewise((3, Eq(x, 2) | Eq(y, 4)), (1, True))
1469
+ assert f(p13) == -2*K(2, x)*K(4, y) + 2*K(2, x) + 2*K(4, y) + 1
1470
+
1471
+ p14 = Piecewise((1, Ne(x, 0) | Ne(y, 1)), (3, True))
1472
+ assert f(p14) == 2 * K(0, x) * K(1, y) + 1
1473
+
1474
+ p15 = Piecewise((2, Eq(x, 3) | Ne(y, 2)), (3, Eq(x, 4) & Eq(y, 5)), (1, True))
1475
+ assert f(p15) == -2*K(2, y)*K(3, x)*K(4, x)*K(5, y) + K(2, y)*K(3, x) + \
1476
+ 2*K(2, y)*K(4, x)*K(5, y) - K(2, y) + 2
1477
+
1478
+ p16 = Piecewise((0, Ne(m, n)), (1, True))*Piecewise((0, Ne(n, t)), (1, True))\
1479
+ *Piecewise((0, Ne(n, x)), (1, True)) - Piecewise((0, Ne(t, x)), (1, True))
1480
+ assert f(p16) == K(m, n)*K(n, t)*K(n, x) - K(t, x)
1481
+
1482
+ p17 = Piecewise((0, Ne(t, x) & (Ne(m, n) | Ne(n, t) | Ne(n, x))),
1483
+ (1, Ne(t, x)), (-1, Ne(m, n) | Ne(n, t) | Ne(n, x)), (0, True))
1484
+ assert f(p17) == K(m, n)*K(n, t)*K(n, x) - K(t, x)
1485
+
1486
+ p18 = Piecewise((-4, Eq(y, 1) | (Eq(x, -5) & Eq(x, z))), (4, True))
1487
+ assert f(p18) == 8*K(-5, x)*K(1, y)*K(x, z) - 8*K(-5, x)*K(x, z) - 8*K(1, y) + 4
1488
+
1489
+ p19 = Piecewise((0, x > 2), (1, True))
1490
+ assert f(p19) == p19
1491
+
1492
+ p20 = Piecewise((0, And(x < 2, x > -5)), (1, True))
1493
+ assert f(p20) == p20
1494
+
1495
+ p21 = Piecewise((0, Or(x > 1, x < 0)), (1, True))
1496
+ assert f(p21) == p21
1497
+
1498
+ p22 = Piecewise((0, ~((Eq(y, -1) | Ne(x, 0)) & (Ne(x, 1) | Ne(y, -1)))), (1, True))
1499
+ assert f(p22) == K(-1, y)*K(0, x) - K(-1, y)*K(1, x) - K(0, x) + 1
1500
+
1501
+
1502
+ @slow
1503
+ def test_identical_conds_issue():
1504
+ from sympy.stats import Uniform, density
1505
+ u1 = Uniform('u1', 0, 1)
1506
+ u2 = Uniform('u2', 0, 1)
1507
+ # Result is quite big, so not really important here (and should ideally be
1508
+ # simpler). Should not give an exception though.
1509
+ density(u1 + u2)
1510
+
1511
+
1512
+ def test_issue_7370():
1513
+ f = Piecewise((1, x <= 2400))
1514
+ v = integrate(f, (x, 0, Float("252.4", 30)))
1515
+ assert str(v) == '252.400000000000000000000000000'
1516
+
1517
+
1518
+ def test_issue_14933():
1519
+ x = Symbol('x')
1520
+ y = Symbol('y')
1521
+
1522
+ inp = MatrixSymbol('inp', 1, 1)
1523
+ rep_dict = {y: inp[0, 0], x: inp[0, 0]}
1524
+
1525
+ p = Piecewise((1, ITE(y > 0, x < 0, True)))
1526
+ assert p.xreplace(rep_dict) == Piecewise((1, ITE(inp[0, 0] > 0, inp[0, 0] < 0, True)))
1527
+
1528
+
1529
+ def test_issue_16715():
1530
+ raises(NotImplementedError, lambda: Piecewise((x, x<0), (0, y>1)).as_expr_set_pairs())
1531
+
1532
+
1533
+ def test_issue_20360():
1534
+ t, tau = symbols("t tau", real=True)
1535
+ n = symbols("n", integer=True)
1536
+ lam = pi * (n - S.Half)
1537
+ eq = integrate(exp(lam * tau), (tau, 0, t))
1538
+ assert eq.simplify() == (2*exp(pi*t*(2*n - 1)/2) - 2)/(pi*(2*n - 1))
1539
+
1540
+
1541
+ def test_piecewise_eval():
1542
+ # XXX these tests might need modification if this
1543
+ # simplification is moved out of eval and into
1544
+ # boolalg or Piecewise simplification functions
1545
+ f = lambda x: x.args[0].cond
1546
+ # unsimplified
1547
+ assert f(Piecewise((x, (x > -oo) & (x < 3)))
1548
+ ) == ((x > -oo) & (x < 3))
1549
+ assert f(Piecewise((x, (x > -oo) & (x < oo)))
1550
+ ) == ((x > -oo) & (x < oo))
1551
+ assert f(Piecewise((x, (x > -3) & (x < 3)))
1552
+ ) == ((x > -3) & (x < 3))
1553
+ assert f(Piecewise((x, (x > -3) & (x < oo)))
1554
+ ) == ((x > -3) & (x < oo))
1555
+ assert f(Piecewise((x, (x <= 3) & (x > -oo)))
1556
+ ) == ((x <= 3) & (x > -oo))
1557
+ assert f(Piecewise((x, (x <= 3) & (x > -3)))
1558
+ ) == ((x <= 3) & (x > -3))
1559
+ assert f(Piecewise((x, (x >= -3) & (x < 3)))
1560
+ ) == ((x >= -3) & (x < 3))
1561
+ assert f(Piecewise((x, (x >= -3) & (x < oo)))
1562
+ ) == ((x >= -3) & (x < oo))
1563
+ assert f(Piecewise((x, (x >= -3) & (x <= 3)))
1564
+ ) == ((x >= -3) & (x <= 3))
1565
+ # could simplify by keeping only the first
1566
+ # arg of result
1567
+ assert f(Piecewise((x, (x <= oo) & (x > -oo)))
1568
+ ) == (x > -oo) & (x <= oo)
1569
+ assert f(Piecewise((x, (x <= oo) & (x > -3)))
1570
+ ) == (x > -3) & (x <= oo)
1571
+ assert f(Piecewise((x, (x >= -oo) & (x < 3)))
1572
+ ) == (x < 3) & (x >= -oo)
1573
+ assert f(Piecewise((x, (x >= -oo) & (x < oo)))
1574
+ ) == (x < oo) & (x >= -oo)
1575
+ assert f(Piecewise((x, (x >= -oo) & (x <= 3)))
1576
+ ) == (x <= 3) & (x >= -oo)
1577
+ assert f(Piecewise((x, (x >= -oo) & (x <= oo)))
1578
+ ) == (x <= oo) & (x >= -oo) # but cannot be True unless x is real
1579
+ assert f(Piecewise((x, (x >= -3) & (x <= oo)))
1580
+ ) == (x >= -3) & (x <= oo)
1581
+ assert f(Piecewise((x, (Abs(arg(a)) <= 1) | (Abs(arg(a)) < 1)))
1582
+ ) == (Abs(arg(a)) <= 1) | (Abs(arg(a)) < 1)
1583
+
1584
+
1585
+ def test_issue_22533():
1586
+ x = Symbol('x', real=True)
1587
+ f = Piecewise((-1 / x, x <= 0), (1 / x, True))
1588
+ assert integrate(f, x) == Piecewise((-log(x), x <= 0), (log(x), True))
1589
+
1590
+
1591
+ def test_issue_24072():
1592
+ assert Piecewise((1, x > 1), (2, x <= 1), (3, x <= 1)
1593
+ ) == Piecewise((1, x > 1), (2, True))
1594
+
1595
+
1596
+ def test_piecewise__eval_is_meromorphic():
1597
+ """ Issue 24127: Tests eval_is_meromorphic auxiliary method """
1598
+ x = symbols('x', real=True)
1599
+ f = Piecewise((1, x < 0), (sqrt(1 - x), True))
1600
+ assert f.is_meromorphic(x, I) is None
1601
+ assert f.is_meromorphic(x, -1) == True
1602
+ assert f.is_meromorphic(x, 0) == None
1603
+ assert f.is_meromorphic(x, 1) == False
1604
+ assert f.is_meromorphic(x, 2) == True
1605
+ assert f.is_meromorphic(x, Symbol('a')) == None
1606
+ assert f.is_meromorphic(x, Symbol('a', real=True)) == None
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_trigonometric.py ADDED
@@ -0,0 +1,2162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.calculus.accumulationbounds import AccumBounds
2
+ from sympy.core.add import Add
3
+ from sympy.core.function import (Lambda, diff)
4
+ from sympy.core.mod import Mod
5
+ from sympy.core.mul import Mul
6
+ from sympy.core.numbers import (E, Float, I, Rational, nan, oo, pi, zoo)
7
+ from sympy.core.power import Pow
8
+ from sympy.core.singleton import S
9
+ from sympy.core.symbol import (Symbol, symbols)
10
+ from sympy.functions.elementary.complexes import (arg, conjugate, im, re)
11
+ from sympy.functions.elementary.exponential import (exp, log)
12
+ from sympy.functions.elementary.hyperbolic import (acoth, asinh, atanh, cosh, coth, sinh, tanh)
13
+ from sympy.functions.elementary.miscellaneous import sqrt
14
+ from sympy.functions.elementary.trigonometric import (acos, acot, acsc, asec, asin, atan, atan2,
15
+ cos, cot, csc, sec, sin, sinc, tan)
16
+ from sympy.functions.special.bessel import (besselj, jn)
17
+ from sympy.functions.special.delta_functions import Heaviside
18
+ from sympy.matrices.dense import Matrix
19
+ from sympy.polys.polytools import (cancel, gcd)
20
+ from sympy.series.limits import limit
21
+ from sympy.series.order import O
22
+ from sympy.series.series import series
23
+ from sympy.sets.fancysets import ImageSet
24
+ from sympy.sets.sets import (FiniteSet, Interval)
25
+ from sympy.simplify.simplify import simplify
26
+ from sympy.core.expr import unchanged
27
+ from sympy.core.function import ArgumentIndexError
28
+ from sympy.core.relational import Ne, Eq
29
+ from sympy.functions.elementary.piecewise import Piecewise
30
+ from sympy.sets.setexpr import SetExpr
31
+ from sympy.testing.pytest import XFAIL, slow, raises
32
+
33
+
34
+ x, y, z = symbols('x y z')
35
+ r = Symbol('r', real=True)
36
+ k, m = symbols('k m', integer=True)
37
+ p = Symbol('p', positive=True)
38
+ n = Symbol('n', negative=True)
39
+ np = Symbol('p', nonpositive=True)
40
+ nn = Symbol('n', nonnegative=True)
41
+ nz = Symbol('nz', nonzero=True)
42
+ ep = Symbol('ep', extended_positive=True)
43
+ en = Symbol('en', extended_negative=True)
44
+ enp = Symbol('ep', extended_nonpositive=True)
45
+ enn = Symbol('en', extended_nonnegative=True)
46
+ enz = Symbol('enz', extended_nonzero=True)
47
+ a = Symbol('a', algebraic=True)
48
+ na = Symbol('na', nonzero=True, algebraic=True)
49
+
50
+
51
+ def test_sin():
52
+ x, y = symbols('x y')
53
+ z = symbols('z', imaginary=True)
54
+
55
+ assert sin.nargs == FiniteSet(1)
56
+ assert sin(nan) is nan
57
+ assert sin(zoo) is nan
58
+
59
+ assert sin(oo) == AccumBounds(-1, 1)
60
+ assert sin(oo) - sin(oo) == AccumBounds(-2, 2)
61
+ assert sin(oo*I) == oo*I
62
+ assert sin(-oo*I) == -oo*I
63
+ assert 0*sin(oo) is S.Zero
64
+ assert 0/sin(oo) is S.Zero
65
+ assert 0 + sin(oo) == AccumBounds(-1, 1)
66
+ assert 5 + sin(oo) == AccumBounds(4, 6)
67
+
68
+ assert sin(0) == 0
69
+
70
+ assert sin(z*I) == I*sinh(z)
71
+ assert sin(asin(x)) == x
72
+ assert sin(atan(x)) == x / sqrt(1 + x**2)
73
+ assert sin(acos(x)) == sqrt(1 - x**2)
74
+ assert sin(acot(x)) == 1 / (sqrt(1 + 1 / x**2) * x)
75
+ assert sin(acsc(x)) == 1 / x
76
+ assert sin(asec(x)) == sqrt(1 - 1 / x**2)
77
+ assert sin(atan2(y, x)) == y / sqrt(x**2 + y**2)
78
+
79
+ assert sin(pi*I) == sinh(pi)*I
80
+ assert sin(-pi*I) == -sinh(pi)*I
81
+ assert sin(-2*I) == -sinh(2)*I
82
+
83
+ assert sin(pi) == 0
84
+ assert sin(-pi) == 0
85
+ assert sin(2*pi) == 0
86
+ assert sin(-2*pi) == 0
87
+ assert sin(-3*10**73*pi) == 0
88
+ assert sin(7*10**103*pi) == 0
89
+
90
+ assert sin(pi/2) == 1
91
+ assert sin(-pi/2) == -1
92
+ assert sin(pi*Rational(5, 2)) == 1
93
+ assert sin(pi*Rational(7, 2)) == -1
94
+
95
+ ne = symbols('ne', integer=True, even=False)
96
+ e = symbols('e', even=True)
97
+ assert sin(pi*ne/2) == (-1)**(ne/2 - S.Half)
98
+ assert sin(pi*k/2).func == sin
99
+ assert sin(pi*e/2) == 0
100
+ assert sin(pi*k) == 0
101
+ assert sin(pi*k).subs(k, 3) == sin(pi*k/2).subs(k, 6) # issue 8298
102
+
103
+ assert sin(pi/3) == S.Half*sqrt(3)
104
+ assert sin(pi*Rational(-2, 3)) == Rational(-1, 2)*sqrt(3)
105
+
106
+ assert sin(pi/4) == S.Half*sqrt(2)
107
+ assert sin(-pi/4) == Rational(-1, 2)*sqrt(2)
108
+ assert sin(pi*Rational(17, 4)) == S.Half*sqrt(2)
109
+ assert sin(pi*Rational(-3, 4)) == Rational(-1, 2)*sqrt(2)
110
+
111
+ assert sin(pi/6) == S.Half
112
+ assert sin(-pi/6) == Rational(-1, 2)
113
+ assert sin(pi*Rational(7, 6)) == Rational(-1, 2)
114
+ assert sin(pi*Rational(-5, 6)) == Rational(-1, 2)
115
+
116
+ assert sin(pi*Rational(1, 5)) == sqrt((5 - sqrt(5)) / 8)
117
+ assert sin(pi*Rational(2, 5)) == sqrt((5 + sqrt(5)) / 8)
118
+ assert sin(pi*Rational(3, 5)) == sin(pi*Rational(2, 5))
119
+ assert sin(pi*Rational(4, 5)) == sin(pi*Rational(1, 5))
120
+ assert sin(pi*Rational(6, 5)) == -sin(pi*Rational(1, 5))
121
+ assert sin(pi*Rational(8, 5)) == -sin(pi*Rational(2, 5))
122
+
123
+ assert sin(pi*Rational(-1273, 5)) == -sin(pi*Rational(2, 5))
124
+
125
+ assert sin(pi/8) == sqrt((2 - sqrt(2))/4)
126
+
127
+ assert sin(pi/10) == Rational(-1, 4) + sqrt(5)/4
128
+
129
+ assert sin(pi/12) == -sqrt(2)/4 + sqrt(6)/4
130
+ assert sin(pi*Rational(5, 12)) == sqrt(2)/4 + sqrt(6)/4
131
+ assert sin(pi*Rational(-7, 12)) == -sqrt(2)/4 - sqrt(6)/4
132
+ assert sin(pi*Rational(-11, 12)) == sqrt(2)/4 - sqrt(6)/4
133
+
134
+ assert sin(pi*Rational(104, 105)) == sin(pi/105)
135
+ assert sin(pi*Rational(106, 105)) == -sin(pi/105)
136
+
137
+ assert sin(pi*Rational(-104, 105)) == -sin(pi/105)
138
+ assert sin(pi*Rational(-106, 105)) == sin(pi/105)
139
+
140
+ assert sin(x*I) == sinh(x)*I
141
+
142
+ assert sin(k*pi) == 0
143
+ assert sin(17*k*pi) == 0
144
+ assert sin(2*k*pi + 4) == sin(4)
145
+ assert sin(2*k*pi + m*pi + 1) == (-1)**(m + 2*k)*sin(1)
146
+
147
+ assert sin(k*pi*I) == sinh(k*pi)*I
148
+
149
+ assert sin(r).is_real is True
150
+
151
+ assert sin(0, evaluate=False).is_algebraic
152
+ assert sin(a).is_algebraic is None
153
+ assert sin(na).is_algebraic is False
154
+ q = Symbol('q', rational=True)
155
+ assert sin(pi*q).is_algebraic
156
+ qn = Symbol('qn', rational=True, nonzero=True)
157
+ assert sin(qn).is_rational is False
158
+ assert sin(q).is_rational is None # issue 8653
159
+
160
+ assert isinstance(sin( re(x) - im(y)), sin) is True
161
+ assert isinstance(sin(-re(x) + im(y)), sin) is False
162
+
163
+ assert sin(SetExpr(Interval(0, 1))) == SetExpr(ImageSet(Lambda(x, sin(x)),
164
+ Interval(0, 1)))
165
+
166
+ for d in list(range(1, 22)) + [60, 85]:
167
+ for n in range(d*2 + 1):
168
+ x = n*pi/d
169
+ e = abs( float(sin(x)) - sin(float(x)) )
170
+ assert e < 1e-12
171
+
172
+ assert sin(0, evaluate=False).is_zero is True
173
+ assert sin(k*pi, evaluate=False).is_zero is True
174
+
175
+ assert sin(Add(1, -1, evaluate=False), evaluate=False).is_zero is True
176
+
177
+
178
+ def test_sin_cos():
179
+ for d in [1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 24, 30, 40, 60, 120]: # list is not exhaustive...
180
+ for n in range(-2*d, d*2):
181
+ x = n*pi/d
182
+ assert sin(x + pi/2) == cos(x), "fails for %d*pi/%d" % (n, d)
183
+ assert sin(x - pi/2) == -cos(x), "fails for %d*pi/%d" % (n, d)
184
+ assert sin(x) == cos(x - pi/2), "fails for %d*pi/%d" % (n, d)
185
+ assert -sin(x) == cos(x + pi/2), "fails for %d*pi/%d" % (n, d)
186
+
187
+
188
+ def test_sin_series():
189
+ assert sin(x).series(x, 0, 9) == \
190
+ x - x**3/6 + x**5/120 - x**7/5040 + O(x**9)
191
+
192
+
193
+ def test_sin_rewrite():
194
+ assert sin(x).rewrite(exp) == -I*(exp(I*x) - exp(-I*x))/2
195
+ assert sin(x).rewrite(tan) == 2*tan(x/2)/(1 + tan(x/2)**2)
196
+ assert sin(x).rewrite(cot) == \
197
+ Piecewise((0, Eq(im(x), 0) & Eq(Mod(x, pi), 0)),
198
+ (2*cot(x/2)/(cot(x/2)**2 + 1), True))
199
+ assert sin(sinh(x)).rewrite(
200
+ exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, sinh(3)).n()
201
+ assert sin(cosh(x)).rewrite(
202
+ exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, cosh(3)).n()
203
+ assert sin(tanh(x)).rewrite(
204
+ exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, tanh(3)).n()
205
+ assert sin(coth(x)).rewrite(
206
+ exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, coth(3)).n()
207
+ assert sin(sin(x)).rewrite(
208
+ exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, sin(3)).n()
209
+ assert sin(cos(x)).rewrite(
210
+ exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, cos(3)).n()
211
+ assert sin(tan(x)).rewrite(
212
+ exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, tan(3)).n()
213
+ assert sin(cot(x)).rewrite(
214
+ exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, cot(3)).n()
215
+ assert sin(log(x)).rewrite(Pow) == I*x**-I / 2 - I*x**I /2
216
+ assert sin(x).rewrite(csc) == 1/csc(x)
217
+ assert sin(x).rewrite(cos) == cos(x - pi / 2, evaluate=False)
218
+ assert sin(x).rewrite(sec) == 1 / sec(x - pi / 2, evaluate=False)
219
+ assert sin(cos(x)).rewrite(Pow) == sin(cos(x))
220
+
221
+
222
+ def _test_extrig(f, i, e):
223
+ from sympy.core.function import expand_trig
224
+ assert unchanged(f, i)
225
+ assert expand_trig(f(i)) == f(i)
226
+ # testing directly instead of with .expand(trig=True)
227
+ # because the other expansions undo the unevaluated Mul
228
+ assert expand_trig(f(Mul(i, 1, evaluate=False))) == e
229
+ assert abs(f(i) - e).n() < 1e-10
230
+
231
+
232
+ def test_sin_expansion():
233
+ # Note: these formulas are not unique. The ones here come from the
234
+ # Chebyshev formulas.
235
+ assert sin(x + y).expand(trig=True) == sin(x)*cos(y) + cos(x)*sin(y)
236
+ assert sin(x - y).expand(trig=True) == sin(x)*cos(y) - cos(x)*sin(y)
237
+ assert sin(y - x).expand(trig=True) == cos(x)*sin(y) - sin(x)*cos(y)
238
+ assert sin(2*x).expand(trig=True) == 2*sin(x)*cos(x)
239
+ assert sin(3*x).expand(trig=True) == -4*sin(x)**3 + 3*sin(x)
240
+ assert sin(4*x).expand(trig=True) == -8*sin(x)**3*cos(x) + 4*sin(x)*cos(x)
241
+ _test_extrig(sin, 2, 2*sin(1)*cos(1))
242
+ _test_extrig(sin, 3, -4*sin(1)**3 + 3*sin(1))
243
+
244
+
245
+ def test_sin_AccumBounds():
246
+ assert sin(AccumBounds(-oo, oo)) == AccumBounds(-1, 1)
247
+ assert sin(AccumBounds(0, oo)) == AccumBounds(-1, 1)
248
+ assert sin(AccumBounds(-oo, 0)) == AccumBounds(-1, 1)
249
+ assert sin(AccumBounds(0, 2*S.Pi)) == AccumBounds(-1, 1)
250
+ assert sin(AccumBounds(0, S.Pi*Rational(3, 4))) == AccumBounds(0, 1)
251
+ assert sin(AccumBounds(S.Pi*Rational(3, 4), S.Pi*Rational(7, 4))) == AccumBounds(-1, sin(S.Pi*Rational(3, 4)))
252
+ assert sin(AccumBounds(S.Pi/4, S.Pi/3)) == AccumBounds(sin(S.Pi/4), sin(S.Pi/3))
253
+ assert sin(AccumBounds(S.Pi*Rational(3, 4), S.Pi*Rational(5, 6))) == AccumBounds(sin(S.Pi*Rational(5, 6)), sin(S.Pi*Rational(3, 4)))
254
+
255
+
256
+ def test_sin_fdiff():
257
+ assert sin(x).fdiff() == cos(x)
258
+ raises(ArgumentIndexError, lambda: sin(x).fdiff(2))
259
+
260
+
261
+ def test_trig_symmetry():
262
+ assert sin(-x) == -sin(x)
263
+ assert cos(-x) == cos(x)
264
+ assert tan(-x) == -tan(x)
265
+ assert cot(-x) == -cot(x)
266
+ assert sin(x + pi) == -sin(x)
267
+ assert sin(x + 2*pi) == sin(x)
268
+ assert sin(x + 3*pi) == -sin(x)
269
+ assert sin(x + 4*pi) == sin(x)
270
+ assert sin(x - 5*pi) == -sin(x)
271
+ assert cos(x + pi) == -cos(x)
272
+ assert cos(x + 2*pi) == cos(x)
273
+ assert cos(x + 3*pi) == -cos(x)
274
+ assert cos(x + 4*pi) == cos(x)
275
+ assert cos(x - 5*pi) == -cos(x)
276
+ assert tan(x + pi) == tan(x)
277
+ assert tan(x - 3*pi) == tan(x)
278
+ assert cot(x + pi) == cot(x)
279
+ assert cot(x - 3*pi) == cot(x)
280
+ assert sin(pi/2 - x) == cos(x)
281
+ assert sin(pi*Rational(3, 2) - x) == -cos(x)
282
+ assert sin(pi*Rational(5, 2) - x) == cos(x)
283
+ assert cos(pi/2 - x) == sin(x)
284
+ assert cos(pi*Rational(3, 2) - x) == -sin(x)
285
+ assert cos(pi*Rational(5, 2) - x) == sin(x)
286
+ assert tan(pi/2 - x) == cot(x)
287
+ assert tan(pi*Rational(3, 2) - x) == cot(x)
288
+ assert tan(pi*Rational(5, 2) - x) == cot(x)
289
+ assert cot(pi/2 - x) == tan(x)
290
+ assert cot(pi*Rational(3, 2) - x) == tan(x)
291
+ assert cot(pi*Rational(5, 2) - x) == tan(x)
292
+ assert sin(pi/2 + x) == cos(x)
293
+ assert cos(pi/2 + x) == -sin(x)
294
+ assert tan(pi/2 + x) == -cot(x)
295
+ assert cot(pi/2 + x) == -tan(x)
296
+
297
+
298
+ def test_cos():
299
+ x, y = symbols('x y')
300
+
301
+ assert cos.nargs == FiniteSet(1)
302
+ assert cos(nan) is nan
303
+
304
+ assert cos(oo) == AccumBounds(-1, 1)
305
+ assert cos(oo) - cos(oo) == AccumBounds(-2, 2)
306
+ assert cos(oo*I) is oo
307
+ assert cos(-oo*I) is oo
308
+ assert cos(zoo) is nan
309
+
310
+ assert cos(0) == 1
311
+
312
+ assert cos(acos(x)) == x
313
+ assert cos(atan(x)) == 1 / sqrt(1 + x**2)
314
+ assert cos(asin(x)) == sqrt(1 - x**2)
315
+ assert cos(acot(x)) == 1 / sqrt(1 + 1 / x**2)
316
+ assert cos(acsc(x)) == sqrt(1 - 1 / x**2)
317
+ assert cos(asec(x)) == 1 / x
318
+ assert cos(atan2(y, x)) == x / sqrt(x**2 + y**2)
319
+
320
+ assert cos(pi*I) == cosh(pi)
321
+ assert cos(-pi*I) == cosh(pi)
322
+ assert cos(-2*I) == cosh(2)
323
+
324
+ assert cos(pi/2) == 0
325
+ assert cos(-pi/2) == 0
326
+ assert cos(pi/2) == 0
327
+ assert cos(-pi/2) == 0
328
+ assert cos((-3*10**73 + 1)*pi/2) == 0
329
+ assert cos((7*10**103 + 1)*pi/2) == 0
330
+
331
+ n = symbols('n', integer=True, even=False)
332
+ e = symbols('e', even=True)
333
+ assert cos(pi*n/2) == 0
334
+ assert cos(pi*e/2) == (-1)**(e/2)
335
+
336
+ assert cos(pi) == -1
337
+ assert cos(-pi) == -1
338
+ assert cos(2*pi) == 1
339
+ assert cos(5*pi) == -1
340
+ assert cos(8*pi) == 1
341
+
342
+ assert cos(pi/3) == S.Half
343
+ assert cos(pi*Rational(-2, 3)) == Rational(-1, 2)
344
+
345
+ assert cos(pi/4) == S.Half*sqrt(2)
346
+ assert cos(-pi/4) == S.Half*sqrt(2)
347
+ assert cos(pi*Rational(11, 4)) == Rational(-1, 2)*sqrt(2)
348
+ assert cos(pi*Rational(-3, 4)) == Rational(-1, 2)*sqrt(2)
349
+
350
+ assert cos(pi/6) == S.Half*sqrt(3)
351
+ assert cos(-pi/6) == S.Half*sqrt(3)
352
+ assert cos(pi*Rational(7, 6)) == Rational(-1, 2)*sqrt(3)
353
+ assert cos(pi*Rational(-5, 6)) == Rational(-1, 2)*sqrt(3)
354
+
355
+ assert cos(pi*Rational(1, 5)) == (sqrt(5) + 1)/4
356
+ assert cos(pi*Rational(2, 5)) == (sqrt(5) - 1)/4
357
+ assert cos(pi*Rational(3, 5)) == -cos(pi*Rational(2, 5))
358
+ assert cos(pi*Rational(4, 5)) == -cos(pi*Rational(1, 5))
359
+ assert cos(pi*Rational(6, 5)) == -cos(pi*Rational(1, 5))
360
+ assert cos(pi*Rational(8, 5)) == cos(pi*Rational(2, 5))
361
+
362
+ assert cos(pi*Rational(-1273, 5)) == -cos(pi*Rational(2, 5))
363
+
364
+ assert cos(pi/8) == sqrt((2 + sqrt(2))/4)
365
+
366
+ assert cos(pi/12) == sqrt(2)/4 + sqrt(6)/4
367
+ assert cos(pi*Rational(5, 12)) == -sqrt(2)/4 + sqrt(6)/4
368
+ assert cos(pi*Rational(7, 12)) == sqrt(2)/4 - sqrt(6)/4
369
+ assert cos(pi*Rational(11, 12)) == -sqrt(2)/4 - sqrt(6)/4
370
+
371
+ assert cos(pi*Rational(104, 105)) == -cos(pi/105)
372
+ assert cos(pi*Rational(106, 105)) == -cos(pi/105)
373
+
374
+ assert cos(pi*Rational(-104, 105)) == -cos(pi/105)
375
+ assert cos(pi*Rational(-106, 105)) == -cos(pi/105)
376
+
377
+ assert cos(x*I) == cosh(x)
378
+ assert cos(k*pi*I) == cosh(k*pi)
379
+
380
+ assert cos(r).is_real is True
381
+
382
+ assert cos(0, evaluate=False).is_algebraic
383
+ assert cos(a).is_algebraic is None
384
+ assert cos(na).is_algebraic is False
385
+ q = Symbol('q', rational=True)
386
+ assert cos(pi*q).is_algebraic
387
+ assert cos(pi*Rational(2, 7)).is_algebraic
388
+
389
+ assert cos(k*pi) == (-1)**k
390
+ assert cos(2*k*pi) == 1
391
+ assert cos(0, evaluate=False).is_zero is False
392
+ assert cos(Rational(1, 2)).is_zero is False
393
+ # The following test will return None as the result, but really it should
394
+ # be True even if it is not always possible to resolve an assumptions query.
395
+ assert cos(asin(-1, evaluate=False), evaluate=False).is_zero is None
396
+ for d in list(range(1, 22)) + [60, 85]:
397
+ for n in range(2*d + 1):
398
+ x = n*pi/d
399
+ e = abs( float(cos(x)) - cos(float(x)) )
400
+ assert e < 1e-12
401
+
402
+
403
+ def test_issue_6190():
404
+ c = Float('123456789012345678901234567890.25', '')
405
+ for cls in [sin, cos, tan, cot]:
406
+ assert cls(c*pi) == cls(pi/4)
407
+ assert cls(4.125*pi) == cls(pi/8)
408
+ assert cls(4.7*pi) == cls((4.7 % 2)*pi)
409
+
410
+
411
+ def test_cos_series():
412
+ assert cos(x).series(x, 0, 9) == \
413
+ 1 - x**2/2 + x**4/24 - x**6/720 + x**8/40320 + O(x**9)
414
+
415
+
416
+ def test_cos_rewrite():
417
+ assert cos(x).rewrite(exp) == exp(I*x)/2 + exp(-I*x)/2
418
+ assert cos(x).rewrite(tan) == (1 - tan(x/2)**2)/(1 + tan(x/2)**2)
419
+ assert cos(x).rewrite(cot) == \
420
+ Piecewise((1, Eq(im(x), 0) & Eq(Mod(x, 2*pi), 0)),
421
+ ((cot(x/2)**2 - 1)/(cot(x/2)**2 + 1), True))
422
+ assert cos(sinh(x)).rewrite(
423
+ exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, sinh(3)).n()
424
+ assert cos(cosh(x)).rewrite(
425
+ exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, cosh(3)).n()
426
+ assert cos(tanh(x)).rewrite(
427
+ exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, tanh(3)).n()
428
+ assert cos(coth(x)).rewrite(
429
+ exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, coth(3)).n()
430
+ assert cos(sin(x)).rewrite(
431
+ exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, sin(3)).n()
432
+ assert cos(cos(x)).rewrite(
433
+ exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, cos(3)).n()
434
+ assert cos(tan(x)).rewrite(
435
+ exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, tan(3)).n()
436
+ assert cos(cot(x)).rewrite(
437
+ exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, cot(3)).n()
438
+ assert cos(log(x)).rewrite(Pow) == x**I/2 + x**-I/2
439
+ assert cos(x).rewrite(sec) == 1/sec(x)
440
+ assert cos(x).rewrite(sin) == sin(x + pi/2, evaluate=False)
441
+ assert cos(x).rewrite(csc) == 1/csc(-x + pi/2, evaluate=False)
442
+ assert cos(sin(x)).rewrite(Pow) == cos(sin(x))
443
+
444
+
445
+ def test_cos_expansion():
446
+ assert cos(x + y).expand(trig=True) == cos(x)*cos(y) - sin(x)*sin(y)
447
+ assert cos(x - y).expand(trig=True) == cos(x)*cos(y) + sin(x)*sin(y)
448
+ assert cos(y - x).expand(trig=True) == cos(x)*cos(y) + sin(x)*sin(y)
449
+ assert cos(2*x).expand(trig=True) == 2*cos(x)**2 - 1
450
+ assert cos(3*x).expand(trig=True) == 4*cos(x)**3 - 3*cos(x)
451
+ assert cos(4*x).expand(trig=True) == 8*cos(x)**4 - 8*cos(x)**2 + 1
452
+ _test_extrig(cos, 2, 2*cos(1)**2 - 1)
453
+ _test_extrig(cos, 3, 4*cos(1)**3 - 3*cos(1))
454
+
455
+
456
+ def test_cos_AccumBounds():
457
+ assert cos(AccumBounds(-oo, oo)) == AccumBounds(-1, 1)
458
+ assert cos(AccumBounds(0, oo)) == AccumBounds(-1, 1)
459
+ assert cos(AccumBounds(-oo, 0)) == AccumBounds(-1, 1)
460
+ assert cos(AccumBounds(0, 2*S.Pi)) == AccumBounds(-1, 1)
461
+ assert cos(AccumBounds(-S.Pi/3, S.Pi/4)) == AccumBounds(cos(-S.Pi/3), 1)
462
+ assert cos(AccumBounds(S.Pi*Rational(3, 4), S.Pi*Rational(5, 4))) == AccumBounds(-1, cos(S.Pi*Rational(3, 4)))
463
+ assert cos(AccumBounds(S.Pi*Rational(5, 4), S.Pi*Rational(4, 3))) == AccumBounds(cos(S.Pi*Rational(5, 4)), cos(S.Pi*Rational(4, 3)))
464
+ assert cos(AccumBounds(S.Pi/4, S.Pi/3)) == AccumBounds(cos(S.Pi/3), cos(S.Pi/4))
465
+
466
+
467
+ def test_cos_fdiff():
468
+ assert cos(x).fdiff() == -sin(x)
469
+ raises(ArgumentIndexError, lambda: cos(x).fdiff(2))
470
+
471
+
472
+ def test_tan():
473
+ assert tan(nan) is nan
474
+
475
+ assert tan(zoo) is nan
476
+ assert tan(oo) == AccumBounds(-oo, oo)
477
+ assert tan(oo) - tan(oo) == AccumBounds(-oo, oo)
478
+ assert tan.nargs == FiniteSet(1)
479
+ assert tan(oo*I) == I
480
+ assert tan(-oo*I) == -I
481
+
482
+ assert tan(0) == 0
483
+
484
+ assert tan(atan(x)) == x
485
+ assert tan(asin(x)) == x / sqrt(1 - x**2)
486
+ assert tan(acos(x)) == sqrt(1 - x**2) / x
487
+ assert tan(acot(x)) == 1 / x
488
+ assert tan(acsc(x)) == 1 / (sqrt(1 - 1 / x**2) * x)
489
+ assert tan(asec(x)) == sqrt(1 - 1 / x**2) * x
490
+ assert tan(atan2(y, x)) == y/x
491
+
492
+ assert tan(pi*I) == tanh(pi)*I
493
+ assert tan(-pi*I) == -tanh(pi)*I
494
+ assert tan(-2*I) == -tanh(2)*I
495
+
496
+ assert tan(pi) == 0
497
+ assert tan(-pi) == 0
498
+ assert tan(2*pi) == 0
499
+ assert tan(-2*pi) == 0
500
+ assert tan(-3*10**73*pi) == 0
501
+
502
+ assert tan(pi/2) is zoo
503
+ assert tan(pi*Rational(3, 2)) is zoo
504
+
505
+ assert tan(pi/3) == sqrt(3)
506
+ assert tan(pi*Rational(-2, 3)) == sqrt(3)
507
+
508
+ assert tan(pi/4) is S.One
509
+ assert tan(-pi/4) is S.NegativeOne
510
+ assert tan(pi*Rational(17, 4)) is S.One
511
+ assert tan(pi*Rational(-3, 4)) is S.One
512
+
513
+ assert tan(pi/5) == sqrt(5 - 2*sqrt(5))
514
+ assert tan(pi*Rational(2, 5)) == sqrt(5 + 2*sqrt(5))
515
+ assert tan(pi*Rational(18, 5)) == -sqrt(5 + 2*sqrt(5))
516
+ assert tan(pi*Rational(-16, 5)) == -sqrt(5 - 2*sqrt(5))
517
+
518
+ assert tan(pi/6) == 1/sqrt(3)
519
+ assert tan(-pi/6) == -1/sqrt(3)
520
+ assert tan(pi*Rational(7, 6)) == 1/sqrt(3)
521
+ assert tan(pi*Rational(-5, 6)) == 1/sqrt(3)
522
+
523
+ assert tan(pi/8) == -1 + sqrt(2)
524
+ assert tan(pi*Rational(3, 8)) == 1 + sqrt(2) # issue 15959
525
+ assert tan(pi*Rational(5, 8)) == -1 - sqrt(2)
526
+ assert tan(pi*Rational(7, 8)) == 1 - sqrt(2)
527
+
528
+ assert tan(pi/10) == sqrt(1 - 2*sqrt(5)/5)
529
+ assert tan(pi*Rational(3, 10)) == sqrt(1 + 2*sqrt(5)/5)
530
+ assert tan(pi*Rational(17, 10)) == -sqrt(1 + 2*sqrt(5)/5)
531
+ assert tan(pi*Rational(-31, 10)) == -sqrt(1 - 2*sqrt(5)/5)
532
+
533
+ assert tan(pi/12) == -sqrt(3) + 2
534
+ assert tan(pi*Rational(5, 12)) == sqrt(3) + 2
535
+ assert tan(pi*Rational(7, 12)) == -sqrt(3) - 2
536
+ assert tan(pi*Rational(11, 12)) == sqrt(3) - 2
537
+
538
+ assert tan(pi/24).radsimp() == -2 - sqrt(3) + sqrt(2) + sqrt(6)
539
+ assert tan(pi*Rational(5, 24)).radsimp() == -2 + sqrt(3) - sqrt(2) + sqrt(6)
540
+ assert tan(pi*Rational(7, 24)).radsimp() == 2 - sqrt(3) - sqrt(2) + sqrt(6)
541
+ assert tan(pi*Rational(11, 24)).radsimp() == 2 + sqrt(3) + sqrt(2) + sqrt(6)
542
+ assert tan(pi*Rational(13, 24)).radsimp() == -2 - sqrt(3) - sqrt(2) - sqrt(6)
543
+ assert tan(pi*Rational(17, 24)).radsimp() == -2 + sqrt(3) + sqrt(2) - sqrt(6)
544
+ assert tan(pi*Rational(19, 24)).radsimp() == 2 - sqrt(3) + sqrt(2) - sqrt(6)
545
+ assert tan(pi*Rational(23, 24)).radsimp() == 2 + sqrt(3) - sqrt(2) - sqrt(6)
546
+
547
+ assert tan(x*I) == tanh(x)*I
548
+
549
+ assert tan(k*pi) == 0
550
+ assert tan(17*k*pi) == 0
551
+
552
+ assert tan(k*pi*I) == tanh(k*pi)*I
553
+
554
+ assert tan(r).is_real is None
555
+ assert tan(r).is_extended_real is True
556
+
557
+ assert tan(0, evaluate=False).is_algebraic
558
+ assert tan(a).is_algebraic is None
559
+ assert tan(na).is_algebraic is False
560
+
561
+ assert tan(pi*Rational(10, 7)) == tan(pi*Rational(3, 7))
562
+ assert tan(pi*Rational(11, 7)) == -tan(pi*Rational(3, 7))
563
+ assert tan(pi*Rational(-11, 7)) == tan(pi*Rational(3, 7))
564
+
565
+ assert tan(pi*Rational(15, 14)) == tan(pi/14)
566
+ assert tan(pi*Rational(-15, 14)) == -tan(pi/14)
567
+
568
+ assert tan(r).is_finite is None
569
+ assert tan(I*r).is_finite is True
570
+
571
+ # https://github.com/sympy/sympy/issues/21177
572
+ f = tan(pi*(x + S(3)/2))/(3*x)
573
+ assert f.as_leading_term(x) == -1/(3*pi*x**2)
574
+
575
+
576
+ def test_tan_series():
577
+ assert tan(x).series(x, 0, 9) == \
578
+ x + x**3/3 + 2*x**5/15 + 17*x**7/315 + O(x**9)
579
+
580
+
581
+ def test_tan_rewrite():
582
+ neg_exp, pos_exp = exp(-x*I), exp(x*I)
583
+ assert tan(x).rewrite(exp) == I*(neg_exp - pos_exp)/(neg_exp + pos_exp)
584
+ assert tan(x).rewrite(sin) == 2*sin(x)**2/sin(2*x)
585
+ assert tan(x).rewrite(cos) == cos(x - S.Pi/2, evaluate=False)/cos(x)
586
+ assert tan(x).rewrite(cot) == 1/cot(x)
587
+ assert tan(sinh(x)).rewrite(exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, sinh(3)).n()
588
+ assert tan(cosh(x)).rewrite(exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, cosh(3)).n()
589
+ assert tan(tanh(x)).rewrite(exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, tanh(3)).n()
590
+ assert tan(coth(x)).rewrite(exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, coth(3)).n()
591
+ assert tan(sin(x)).rewrite(exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, sin(3)).n()
592
+ assert tan(cos(x)).rewrite(exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, cos(3)).n()
593
+ assert tan(tan(x)).rewrite(exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, tan(3)).n()
594
+ assert tan(cot(x)).rewrite(exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, cot(3)).n()
595
+ assert tan(log(x)).rewrite(Pow) == I*(x**-I - x**I)/(x**-I + x**I)
596
+ assert tan(x).rewrite(sec) == sec(x)/sec(x - pi/2, evaluate=False)
597
+ assert tan(x).rewrite(csc) == csc(-x + pi/2, evaluate=False)/csc(x)
598
+ assert tan(sin(x)).rewrite(Pow) == tan(sin(x))
599
+
600
+
601
+ @slow
602
+ def test_tan_rewrite_slow():
603
+ assert 0 == (cos(pi/34)*tan(pi/34) - sin(pi/34)).rewrite(pow)
604
+ assert 0 == (cos(pi/17)*tan(pi/17) - sin(pi/17)).rewrite(pow)
605
+ assert tan(pi/19).rewrite(pow) == tan(pi/19)
606
+ assert tan(pi*Rational(8, 19)).rewrite(sqrt) == tan(pi*Rational(8, 19))
607
+ assert tan(pi*Rational(2, 5), evaluate=False).rewrite(sqrt) == sqrt(sqrt(5)/8 +
608
+ Rational(5, 8))/(Rational(-1, 4) + sqrt(5)/4)
609
+
610
+
611
+ def test_tan_subs():
612
+ assert tan(x).subs(tan(x), y) == y
613
+ assert tan(x).subs(x, y) == tan(y)
614
+ assert tan(x).subs(x, S.Pi/2) is zoo
615
+ assert tan(x).subs(x, S.Pi*Rational(3, 2)) is zoo
616
+
617
+
618
+ def test_tan_expansion():
619
+ assert tan(x + y).expand(trig=True) == ((tan(x) + tan(y))/(1 - tan(x)*tan(y))).expand()
620
+ assert tan(x - y).expand(trig=True) == ((tan(x) - tan(y))/(1 + tan(x)*tan(y))).expand()
621
+ assert tan(x + y + z).expand(trig=True) == (
622
+ (tan(x) + tan(y) + tan(z) - tan(x)*tan(y)*tan(z))/
623
+ (1 - tan(x)*tan(y) - tan(x)*tan(z) - tan(y)*tan(z))).expand()
624
+ assert 0 == tan(2*x).expand(trig=True).rewrite(tan).subs([(tan(x), Rational(1, 7))])*24 - 7
625
+ assert 0 == tan(3*x).expand(trig=True).rewrite(tan).subs([(tan(x), Rational(1, 5))])*55 - 37
626
+ assert 0 == tan(4*x - pi/4).expand(trig=True).rewrite(tan).subs([(tan(x), Rational(1, 5))])*239 - 1
627
+ _test_extrig(tan, 2, 2*tan(1)/(1 - tan(1)**2))
628
+ _test_extrig(tan, 3, (-tan(1)**3 + 3*tan(1))/(1 - 3*tan(1)**2))
629
+
630
+
631
+ def test_tan_AccumBounds():
632
+ assert tan(AccumBounds(-oo, oo)) == AccumBounds(-oo, oo)
633
+ assert tan(AccumBounds(S.Pi/3, S.Pi*Rational(2, 3))) == AccumBounds(-oo, oo)
634
+ assert tan(AccumBounds(S.Pi/6, S.Pi/3)) == AccumBounds(tan(S.Pi/6), tan(S.Pi/3))
635
+
636
+
637
+ def test_tan_fdiff():
638
+ assert tan(x).fdiff() == tan(x)**2 + 1
639
+ raises(ArgumentIndexError, lambda: tan(x).fdiff(2))
640
+
641
+
642
+ def test_cot():
643
+ assert cot(nan) is nan
644
+
645
+ assert cot.nargs == FiniteSet(1)
646
+ assert cot(oo*I) == -I
647
+ assert cot(-oo*I) == I
648
+ assert cot(zoo) is nan
649
+
650
+ assert cot(0) is zoo
651
+ assert cot(2*pi) is zoo
652
+
653
+ assert cot(acot(x)) == x
654
+ assert cot(atan(x)) == 1 / x
655
+ assert cot(asin(x)) == sqrt(1 - x**2) / x
656
+ assert cot(acos(x)) == x / sqrt(1 - x**2)
657
+ assert cot(acsc(x)) == sqrt(1 - 1 / x**2) * x
658
+ assert cot(asec(x)) == 1 / (sqrt(1 - 1 / x**2) * x)
659
+ assert cot(atan2(y, x)) == x/y
660
+
661
+ assert cot(pi*I) == -coth(pi)*I
662
+ assert cot(-pi*I) == coth(pi)*I
663
+ assert cot(-2*I) == coth(2)*I
664
+
665
+ assert cot(pi) == cot(2*pi) == cot(3*pi)
666
+ assert cot(-pi) == cot(-2*pi) == cot(-3*pi)
667
+
668
+ assert cot(pi/2) == 0
669
+ assert cot(-pi/2) == 0
670
+ assert cot(pi*Rational(5, 2)) == 0
671
+ assert cot(pi*Rational(7, 2)) == 0
672
+
673
+ assert cot(pi/3) == 1/sqrt(3)
674
+ assert cot(pi*Rational(-2, 3)) == 1/sqrt(3)
675
+
676
+ assert cot(pi/4) is S.One
677
+ assert cot(-pi/4) is S.NegativeOne
678
+ assert cot(pi*Rational(17, 4)) is S.One
679
+ assert cot(pi*Rational(-3, 4)) is S.One
680
+
681
+ assert cot(pi/6) == sqrt(3)
682
+ assert cot(-pi/6) == -sqrt(3)
683
+ assert cot(pi*Rational(7, 6)) == sqrt(3)
684
+ assert cot(pi*Rational(-5, 6)) == sqrt(3)
685
+
686
+ assert cot(pi/8) == 1 + sqrt(2)
687
+ assert cot(pi*Rational(3, 8)) == -1 + sqrt(2)
688
+ assert cot(pi*Rational(5, 8)) == 1 - sqrt(2)
689
+ assert cot(pi*Rational(7, 8)) == -1 - sqrt(2)
690
+
691
+ assert cot(pi/12) == sqrt(3) + 2
692
+ assert cot(pi*Rational(5, 12)) == -sqrt(3) + 2
693
+ assert cot(pi*Rational(7, 12)) == sqrt(3) - 2
694
+ assert cot(pi*Rational(11, 12)) == -sqrt(3) - 2
695
+
696
+ assert cot(pi/24).radsimp() == sqrt(2) + sqrt(3) + 2 + sqrt(6)
697
+ assert cot(pi*Rational(5, 24)).radsimp() == -sqrt(2) - sqrt(3) + 2 + sqrt(6)
698
+ assert cot(pi*Rational(7, 24)).radsimp() == -sqrt(2) + sqrt(3) - 2 + sqrt(6)
699
+ assert cot(pi*Rational(11, 24)).radsimp() == sqrt(2) - sqrt(3) - 2 + sqrt(6)
700
+ assert cot(pi*Rational(13, 24)).radsimp() == -sqrt(2) + sqrt(3) + 2 - sqrt(6)
701
+ assert cot(pi*Rational(17, 24)).radsimp() == sqrt(2) - sqrt(3) + 2 - sqrt(6)
702
+ assert cot(pi*Rational(19, 24)).radsimp() == sqrt(2) + sqrt(3) - 2 - sqrt(6)
703
+ assert cot(pi*Rational(23, 24)).radsimp() == -sqrt(2) - sqrt(3) - 2 - sqrt(6)
704
+
705
+ assert cot(x*I) == -coth(x)*I
706
+ assert cot(k*pi*I) == -coth(k*pi)*I
707
+
708
+ assert cot(r).is_real is None
709
+ assert cot(r).is_extended_real is True
710
+
711
+ assert cot(a).is_algebraic is None
712
+ assert cot(na).is_algebraic is False
713
+
714
+ assert cot(pi*Rational(10, 7)) == cot(pi*Rational(3, 7))
715
+ assert cot(pi*Rational(11, 7)) == -cot(pi*Rational(3, 7))
716
+ assert cot(pi*Rational(-11, 7)) == cot(pi*Rational(3, 7))
717
+
718
+ assert cot(pi*Rational(39, 34)) == cot(pi*Rational(5, 34))
719
+ assert cot(pi*Rational(-41, 34)) == -cot(pi*Rational(7, 34))
720
+
721
+ assert cot(x).is_finite is None
722
+ assert cot(r).is_finite is None
723
+ i = Symbol('i', imaginary=True)
724
+ assert cot(i).is_finite is True
725
+
726
+ assert cot(x).subs(x, 3*pi) is zoo
727
+
728
+ # https://github.com/sympy/sympy/issues/21177
729
+ f = cot(pi*(x + 4))/(3*x)
730
+ assert f.as_leading_term(x) == 1/(3*pi*x**2)
731
+
732
+
733
+ def test_tan_cot_sin_cos_evalf():
734
+ assert abs((tan(pi*Rational(8, 15))*cos(pi*Rational(8, 15))/sin(pi*Rational(8, 15)) - 1).evalf()) < 1e-14
735
+ assert abs((cot(pi*Rational(4, 15))*sin(pi*Rational(4, 15))/cos(pi*Rational(4, 15)) - 1).evalf()) < 1e-14
736
+
737
+ @XFAIL
738
+ def test_tan_cot_sin_cos_ratsimp():
739
+ assert 1 == (tan(pi*Rational(8, 15))*cos(pi*Rational(8, 15))/sin(pi*Rational(8, 15))).ratsimp()
740
+ assert 1 == (cot(pi*Rational(4, 15))*sin(pi*Rational(4, 15))/cos(pi*Rational(4, 15))).ratsimp()
741
+
742
+
743
+ def test_cot_series():
744
+ assert cot(x).series(x, 0, 9) == \
745
+ 1/x - x/3 - x**3/45 - 2*x**5/945 - x**7/4725 + O(x**9)
746
+ # issue 6210
747
+ assert cot(x**4 + x**5).series(x, 0, 1) == \
748
+ x**(-4) - 1/x**3 + x**(-2) - 1/x + 1 + O(x)
749
+ assert cot(pi*(1-x)).series(x, 0, 3) == -1/(pi*x) + pi*x/3 + O(x**3)
750
+ assert cot(x).taylor_term(0, x) == 1/x
751
+ assert cot(x).taylor_term(2, x) is S.Zero
752
+ assert cot(x).taylor_term(3, x) == -x**3/45
753
+
754
+
755
+ def test_cot_rewrite():
756
+ neg_exp, pos_exp = exp(-x*I), exp(x*I)
757
+ assert cot(x).rewrite(exp) == I*(pos_exp + neg_exp)/(pos_exp - neg_exp)
758
+ assert cot(x).rewrite(sin) == sin(2*x)/(2*(sin(x)**2))
759
+ assert cot(x).rewrite(cos) == cos(x)/cos(x - pi/2, evaluate=False)
760
+ assert cot(x).rewrite(tan) == 1/tan(x)
761
+ def check(func):
762
+ z = cot(func(x)).rewrite(exp) - cot(x).rewrite(exp).subs(x, func(x))
763
+ assert z.rewrite(exp).expand() == 0
764
+ check(sinh)
765
+ check(cosh)
766
+ check(tanh)
767
+ check(coth)
768
+ check(sin)
769
+ check(cos)
770
+ check(tan)
771
+ assert cot(log(x)).rewrite(Pow) == -I*(x**-I + x**I)/(x**-I - x**I)
772
+ assert cot(x).rewrite(sec) == sec(x - pi / 2, evaluate=False) / sec(x)
773
+ assert cot(x).rewrite(csc) == csc(x) / csc(- x + pi / 2, evaluate=False)
774
+ assert cot(sin(x)).rewrite(Pow) == cot(sin(x))
775
+
776
+
777
+ @slow
778
+ def test_cot_rewrite_slow():
779
+ assert cot(pi*Rational(4, 34)).rewrite(pow).ratsimp() == \
780
+ (cos(pi*Rational(4, 34))/sin(pi*Rational(4, 34))).rewrite(pow).ratsimp()
781
+ assert cot(pi*Rational(4, 17)).rewrite(pow) == \
782
+ (cos(pi*Rational(4, 17))/sin(pi*Rational(4, 17))).rewrite(pow)
783
+ assert cot(pi/19).rewrite(pow) == cot(pi/19)
784
+ assert cot(pi/19).rewrite(sqrt) == cot(pi/19)
785
+ assert cot(pi*Rational(2, 5), evaluate=False).rewrite(sqrt) == \
786
+ (Rational(-1, 4) + sqrt(5)/4) / sqrt(sqrt(5)/8 + Rational(5, 8))
787
+
788
+
789
+ def test_cot_subs():
790
+ assert cot(x).subs(cot(x), y) == y
791
+ assert cot(x).subs(x, y) == cot(y)
792
+ assert cot(x).subs(x, 0) is zoo
793
+ assert cot(x).subs(x, S.Pi) is zoo
794
+
795
+
796
+ def test_cot_expansion():
797
+ assert cot(x + y).expand(trig=True).together() == (
798
+ (cot(x)*cot(y) - 1)/(cot(x) + cot(y)))
799
+ assert cot(x - y).expand(trig=True).together() == (
800
+ cot(x)*cot(-y) - 1)/(cot(x) + cot(-y))
801
+ assert cot(x + y + z).expand(trig=True).together() == (
802
+ (cot(x)*cot(y)*cot(z) - cot(x) - cot(y) - cot(z))/
803
+ (-1 + cot(x)*cot(y) + cot(x)*cot(z) + cot(y)*cot(z)))
804
+ assert cot(3*x).expand(trig=True).together() == (
805
+ (cot(x)**2 - 3)*cot(x)/(3*cot(x)**2 - 1))
806
+ assert cot(2*x).expand(trig=True) == cot(x)/2 - 1/(2*cot(x))
807
+ assert cot(3*x).expand(trig=True).together() == (
808
+ cot(x)**2 - 3)*cot(x)/(3*cot(x)**2 - 1)
809
+ assert cot(4*x - pi/4).expand(trig=True).cancel() == (
810
+ -tan(x)**4 + 4*tan(x)**3 + 6*tan(x)**2 - 4*tan(x) - 1
811
+ )/(tan(x)**4 + 4*tan(x)**3 - 6*tan(x)**2 - 4*tan(x) + 1)
812
+ _test_extrig(cot, 2, (-1 + cot(1)**2)/(2*cot(1)))
813
+ _test_extrig(cot, 3, (-3*cot(1) + cot(1)**3)/(-1 + 3*cot(1)**2))
814
+
815
+
816
+ def test_cot_AccumBounds():
817
+ assert cot(AccumBounds(-oo, oo)) == AccumBounds(-oo, oo)
818
+ assert cot(AccumBounds(-S.Pi/3, S.Pi/3)) == AccumBounds(-oo, oo)
819
+ assert cot(AccumBounds(S.Pi/6, S.Pi/3)) == AccumBounds(cot(S.Pi/3), cot(S.Pi/6))
820
+
821
+
822
+ def test_cot_fdiff():
823
+ assert cot(x).fdiff() == -cot(x)**2 - 1
824
+ raises(ArgumentIndexError, lambda: cot(x).fdiff(2))
825
+
826
+
827
+ def test_sinc():
828
+ assert isinstance(sinc(x), sinc)
829
+
830
+ s = Symbol('s', zero=True)
831
+ assert sinc(s) is S.One
832
+ assert sinc(S.Infinity) is S.Zero
833
+ assert sinc(S.NegativeInfinity) is S.Zero
834
+ assert sinc(S.NaN) is S.NaN
835
+ assert sinc(S.ComplexInfinity) is S.NaN
836
+
837
+ n = Symbol('n', integer=True, nonzero=True)
838
+ assert sinc(n*pi) is S.Zero
839
+ assert sinc(-n*pi) is S.Zero
840
+ assert sinc(pi/2) == 2 / pi
841
+ assert sinc(-pi/2) == 2 / pi
842
+ assert sinc(pi*Rational(5, 2)) == 2 / (5*pi)
843
+ assert sinc(pi*Rational(7, 2)) == -2 / (7*pi)
844
+
845
+ assert sinc(-x) == sinc(x)
846
+
847
+ assert sinc(x).diff(x) == cos(x)/x - sin(x)/x**2
848
+ assert sinc(x).diff(x) == (sin(x)/x).diff(x)
849
+ assert sinc(x).diff(x, x) == (-sin(x) - 2*cos(x)/x + 2*sin(x)/x**2)/x
850
+ assert sinc(x).diff(x, x) == (sin(x)/x).diff(x, x)
851
+ assert limit(sinc(x).diff(x), x, 0) == 0
852
+ assert limit(sinc(x).diff(x, x), x, 0) == -S(1)/3
853
+
854
+ # https://github.com/sympy/sympy/issues/11402
855
+ #
856
+ # assert sinc(x).diff(x) == Piecewise(((x*cos(x) - sin(x)) / x**2, Ne(x, 0)), (0, True))
857
+ #
858
+ # assert sinc(x).diff(x).equals(sinc(x).rewrite(sin).diff(x))
859
+ #
860
+ # assert sinc(x).diff(x).subs(x, 0) is S.Zero
861
+
862
+ assert sinc(x).series() == 1 - x**2/6 + x**4/120 + O(x**6)
863
+
864
+ assert sinc(x).rewrite(jn) == jn(0, x)
865
+ assert sinc(x).rewrite(sin) == Piecewise((sin(x)/x, Ne(x, 0)), (1, True))
866
+ assert sinc(pi, evaluate=False).is_zero is True
867
+ assert sinc(0, evaluate=False).is_zero is False
868
+ assert sinc(n*pi, evaluate=False).is_zero is True
869
+ assert sinc(x).is_zero is None
870
+ xr = Symbol('xr', real=True, nonzero=True)
871
+ assert sinc(x).is_real is None
872
+ assert sinc(xr).is_real is True
873
+ assert sinc(I*xr).is_real is True
874
+ assert sinc(I*100).is_real is True
875
+ assert sinc(x).is_finite is None
876
+ assert sinc(xr).is_finite is True
877
+
878
+
879
+ def test_asin():
880
+ assert asin(nan) is nan
881
+
882
+ assert asin.nargs == FiniteSet(1)
883
+ assert asin(oo) == -I*oo
884
+ assert asin(-oo) == I*oo
885
+ assert asin(zoo) is zoo
886
+
887
+ # Note: asin(-x) = - asin(x)
888
+ assert asin(0) == 0
889
+ assert asin(1) == pi/2
890
+ assert asin(-1) == -pi/2
891
+ assert asin(sqrt(3)/2) == pi/3
892
+ assert asin(-sqrt(3)/2) == -pi/3
893
+ assert asin(sqrt(2)/2) == pi/4
894
+ assert asin(-sqrt(2)/2) == -pi/4
895
+ assert asin(sqrt((5 - sqrt(5))/8)) == pi/5
896
+ assert asin(-sqrt((5 - sqrt(5))/8)) == -pi/5
897
+ assert asin(S.Half) == pi/6
898
+ assert asin(Rational(-1, 2)) == -pi/6
899
+ assert asin((sqrt(2 - sqrt(2)))/2) == pi/8
900
+ assert asin(-(sqrt(2 - sqrt(2)))/2) == -pi/8
901
+ assert asin((sqrt(5) - 1)/4) == pi/10
902
+ assert asin(-(sqrt(5) - 1)/4) == -pi/10
903
+ assert asin((sqrt(3) - 1)/sqrt(2**3)) == pi/12
904
+ assert asin(-(sqrt(3) - 1)/sqrt(2**3)) == -pi/12
905
+
906
+ # check round-trip for exact values:
907
+ for d in [5, 6, 8, 10, 12]:
908
+ for n in range(-(d//2), d//2 + 1):
909
+ if gcd(n, d) == 1:
910
+ assert asin(sin(n*pi/d)) == n*pi/d
911
+
912
+ assert asin(x).diff(x) == 1/sqrt(1 - x**2)
913
+
914
+ assert asin(0.2, evaluate=False).is_real is True
915
+ assert asin(-2).is_real is False
916
+ assert asin(r).is_real is None
917
+
918
+ assert asin(-2*I) == -I*asinh(2)
919
+
920
+ assert asin(Rational(1, 7), evaluate=False).is_positive is True
921
+ assert asin(Rational(-1, 7), evaluate=False).is_positive is False
922
+ assert asin(p).is_positive is None
923
+ assert asin(sin(Rational(7, 2))) == Rational(-7, 2) + pi
924
+ assert asin(sin(Rational(-7, 4))) == Rational(7, 4) - pi
925
+ assert unchanged(asin, cos(x))
926
+
927
+
928
+ def test_asin_series():
929
+ assert asin(x).series(x, 0, 9) == \
930
+ x + x**3/6 + 3*x**5/40 + 5*x**7/112 + O(x**9)
931
+ t5 = asin(x).taylor_term(5, x)
932
+ assert t5 == 3*x**5/40
933
+ assert asin(x).taylor_term(7, x, t5, 0) == 5*x**7/112
934
+
935
+
936
+ def test_asin_leading_term():
937
+ assert asin(x).as_leading_term(x) == x
938
+ # Tests concerning branch points
939
+ assert asin(x + 1).as_leading_term(x) == pi/2
940
+ assert asin(x - 1).as_leading_term(x) == -pi/2
941
+ assert asin(1/x).as_leading_term(x, cdir=1) == I*log(x) + pi/2 - I*log(2)
942
+ assert asin(1/x).as_leading_term(x, cdir=-1) == -I*log(x) - 3*pi/2 + I*log(2)
943
+ # Tests concerning points lying on branch cuts
944
+ assert asin(I*x + 2).as_leading_term(x, cdir=1) == pi - asin(2)
945
+ assert asin(-I*x + 2).as_leading_term(x, cdir=1) == asin(2)
946
+ assert asin(I*x - 2).as_leading_term(x, cdir=1) == -asin(2)
947
+ assert asin(-I*x - 2).as_leading_term(x, cdir=1) == -pi + asin(2)
948
+ # Tests concerning im(ndir) == 0
949
+ assert asin(-I*x**2 + x - 2).as_leading_term(x, cdir=1) == -pi/2 + I*log(2 - sqrt(3))
950
+ assert asin(-I*x**2 + x - 2).as_leading_term(x, cdir=-1) == -pi/2 + I*log(2 - sqrt(3))
951
+
952
+
953
+ def test_asin_rewrite():
954
+ assert asin(x).rewrite(log) == -I*log(I*x + sqrt(1 - x**2))
955
+ assert asin(x).rewrite(atan) == 2*atan(x/(1 + sqrt(1 - x**2)))
956
+ assert asin(x).rewrite(acos) == S.Pi/2 - acos(x)
957
+ assert asin(x).rewrite(acot) == 2*acot((sqrt(-x**2 + 1) + 1)/x)
958
+ assert asin(x).rewrite(asec) == -asec(1/x) + pi/2
959
+ assert asin(x).rewrite(acsc) == acsc(1/x)
960
+
961
+
962
+ def test_asin_fdiff():
963
+ assert asin(x).fdiff() == 1/sqrt(1 - x**2)
964
+ raises(ArgumentIndexError, lambda: asin(x).fdiff(2))
965
+
966
+
967
+ def test_acos():
968
+ assert acos(nan) is nan
969
+ assert acos(zoo) is zoo
970
+
971
+ assert acos.nargs == FiniteSet(1)
972
+ assert acos(oo) == I*oo
973
+ assert acos(-oo) == -I*oo
974
+
975
+ # Note: acos(-x) = pi - acos(x)
976
+ assert acos(0) == pi/2
977
+ assert acos(S.Half) == pi/3
978
+ assert acos(Rational(-1, 2)) == pi*Rational(2, 3)
979
+ assert acos(1) == 0
980
+ assert acos(-1) == pi
981
+ assert acos(sqrt(2)/2) == pi/4
982
+ assert acos(-sqrt(2)/2) == pi*Rational(3, 4)
983
+
984
+ # check round-trip for exact values:
985
+ for d in [5, 6, 8, 10, 12]:
986
+ for num in range(d):
987
+ if gcd(num, d) == 1:
988
+ assert acos(cos(num*pi/d)) == num*pi/d
989
+
990
+ assert acos(2*I) == pi/2 - asin(2*I)
991
+
992
+ assert acos(x).diff(x) == -1/sqrt(1 - x**2)
993
+
994
+ assert acos(0.2).is_real is True
995
+ assert acos(-2).is_real is False
996
+ assert acos(r).is_real is None
997
+
998
+ assert acos(Rational(1, 7), evaluate=False).is_positive is True
999
+ assert acos(Rational(-1, 7), evaluate=False).is_positive is True
1000
+ assert acos(Rational(3, 2), evaluate=False).is_positive is False
1001
+ assert acos(p).is_positive is None
1002
+
1003
+ assert acos(2 + p).conjugate() != acos(10 + p)
1004
+ assert acos(-3 + n).conjugate() != acos(-3 + n)
1005
+ assert acos(Rational(1, 3)).conjugate() == acos(Rational(1, 3))
1006
+ assert acos(Rational(-1, 3)).conjugate() == acos(Rational(-1, 3))
1007
+ assert acos(p + n*I).conjugate() == acos(p - n*I)
1008
+ assert acos(z).conjugate() != acos(conjugate(z))
1009
+
1010
+
1011
+ def test_acos_leading_term():
1012
+ assert acos(x).as_leading_term(x) == pi/2
1013
+ # Tests concerning branch points
1014
+ assert acos(x + 1).as_leading_term(x) == sqrt(2)*sqrt(-x)
1015
+ assert acos(x - 1).as_leading_term(x) == pi
1016
+ assert acos(1/x).as_leading_term(x, cdir=1) == -I*log(x) + I*log(2)
1017
+ assert acos(1/x).as_leading_term(x, cdir=-1) == I*log(x) + 2*pi - I*log(2)
1018
+ # Tests concerning points lying on branch cuts
1019
+ assert acos(I*x + 2).as_leading_term(x, cdir=1) == -acos(2)
1020
+ assert acos(-I*x + 2).as_leading_term(x, cdir=1) == acos(2)
1021
+ assert acos(I*x - 2).as_leading_term(x, cdir=1) == acos(-2)
1022
+ assert acos(-I*x - 2).as_leading_term(x, cdir=1) == 2*pi - acos(-2)
1023
+ # Tests concerning im(ndir) == 0
1024
+ assert acos(-I*x**2 + x - 2).as_leading_term(x, cdir=1) == pi + I*log(sqrt(3) + 2)
1025
+ assert acos(-I*x**2 + x - 2).as_leading_term(x, cdir=-1) == pi + I*log(sqrt(3) + 2)
1026
+
1027
+
1028
+ def test_acos_series():
1029
+ assert acos(x).series(x, 0, 8) == \
1030
+ pi/2 - x - x**3/6 - 3*x**5/40 - 5*x**7/112 + O(x**8)
1031
+ assert acos(x).series(x, 0, 8) == pi/2 - asin(x).series(x, 0, 8)
1032
+ t5 = acos(x).taylor_term(5, x)
1033
+ assert t5 == -3*x**5/40
1034
+ assert acos(x).taylor_term(7, x, t5, 0) == -5*x**7/112
1035
+ assert acos(x).taylor_term(0, x) == pi/2
1036
+ assert acos(x).taylor_term(2, x) is S.Zero
1037
+
1038
+
1039
+ def test_acos_rewrite():
1040
+ assert acos(x).rewrite(log) == pi/2 + I*log(I*x + sqrt(1 - x**2))
1041
+ assert acos(x).rewrite(atan) == pi*(-x*sqrt(x**(-2)) + 1)/2 + atan(sqrt(1 - x**2)/x)
1042
+ assert acos(0).rewrite(atan) == S.Pi/2
1043
+ assert acos(0.5).rewrite(atan) == acos(0.5).rewrite(log)
1044
+ assert acos(x).rewrite(asin) == S.Pi/2 - asin(x)
1045
+ assert acos(x).rewrite(acot) == -2*acot((sqrt(-x**2 + 1) + 1)/x) + pi/2
1046
+ assert acos(x).rewrite(asec) == asec(1/x)
1047
+ assert acos(x).rewrite(acsc) == -acsc(1/x) + pi/2
1048
+
1049
+
1050
+ def test_acos_fdiff():
1051
+ assert acos(x).fdiff() == -1/sqrt(1 - x**2)
1052
+ raises(ArgumentIndexError, lambda: acos(x).fdiff(2))
1053
+
1054
+
1055
+ def test_atan():
1056
+ assert atan(nan) is nan
1057
+
1058
+ assert atan.nargs == FiniteSet(1)
1059
+ assert atan(oo) == pi/2
1060
+ assert atan(-oo) == -pi/2
1061
+ assert atan(zoo) == AccumBounds(-pi/2, pi/2)
1062
+
1063
+ assert atan(0) == 0
1064
+ assert atan(1) == pi/4
1065
+ assert atan(sqrt(3)) == pi/3
1066
+ assert atan(-(1 + sqrt(2))) == pi*Rational(-3, 8)
1067
+ assert atan(sqrt(5 - 2 * sqrt(5))) == pi/5
1068
+ assert atan(-sqrt(1 - 2 * sqrt(5)/ 5)) == -pi/10
1069
+ assert atan(sqrt(1 + 2 * sqrt(5) / 5)) == pi*Rational(3, 10)
1070
+ assert atan(-2 + sqrt(3)) == -pi/12
1071
+ assert atan(2 + sqrt(3)) == pi*Rational(5, 12)
1072
+ assert atan(-2 - sqrt(3)) == pi*Rational(-5, 12)
1073
+
1074
+ # check round-trip for exact values:
1075
+ for d in [5, 6, 8, 10, 12]:
1076
+ for num in range(-(d//2), d//2 + 1):
1077
+ if gcd(num, d) == 1:
1078
+ assert atan(tan(num*pi/d)) == num*pi/d
1079
+
1080
+ assert atan(oo) == pi/2
1081
+ assert atan(x).diff(x) == 1/(1 + x**2)
1082
+
1083
+ assert atan(r).is_real is True
1084
+
1085
+ assert atan(-2*I) == -I*atanh(2)
1086
+ assert unchanged(atan, cot(x))
1087
+ assert atan(cot(Rational(1, 4))) == Rational(-1, 4) + pi/2
1088
+ assert acot(Rational(1, 4)).is_rational is False
1089
+
1090
+ for s in (x, p, n, np, nn, nz, ep, en, enp, enn, enz):
1091
+ if s.is_real or s.is_extended_real is None:
1092
+ assert s.is_nonzero is atan(s).is_nonzero
1093
+ assert s.is_positive is atan(s).is_positive
1094
+ assert s.is_negative is atan(s).is_negative
1095
+ assert s.is_nonpositive is atan(s).is_nonpositive
1096
+ assert s.is_nonnegative is atan(s).is_nonnegative
1097
+ else:
1098
+ assert s.is_extended_nonzero is atan(s).is_nonzero
1099
+ assert s.is_extended_positive is atan(s).is_positive
1100
+ assert s.is_extended_negative is atan(s).is_negative
1101
+ assert s.is_extended_nonpositive is atan(s).is_nonpositive
1102
+ assert s.is_extended_nonnegative is atan(s).is_nonnegative
1103
+ assert s.is_extended_nonzero is atan(s).is_extended_nonzero
1104
+ assert s.is_extended_positive is atan(s).is_extended_positive
1105
+ assert s.is_extended_negative is atan(s).is_extended_negative
1106
+ assert s.is_extended_nonpositive is atan(s).is_extended_nonpositive
1107
+ assert s.is_extended_nonnegative is atan(s).is_extended_nonnegative
1108
+
1109
+
1110
+ def test_atan_rewrite():
1111
+ assert atan(x).rewrite(log) == I*(log(1 - I*x)-log(1 + I*x))/2
1112
+ assert atan(x).rewrite(asin) == (-asin(1/sqrt(x**2 + 1)) + pi/2)*sqrt(x**2)/x
1113
+ assert atan(x).rewrite(acos) == sqrt(x**2)*acos(1/sqrt(x**2 + 1))/x
1114
+ assert atan(x).rewrite(acot) == acot(1/x)
1115
+ assert atan(x).rewrite(asec) == sqrt(x**2)*asec(sqrt(x**2 + 1))/x
1116
+ assert atan(x).rewrite(acsc) == (-acsc(sqrt(x**2 + 1)) + pi/2)*sqrt(x**2)/x
1117
+
1118
+ assert atan(-5*I).evalf() == atan(x).rewrite(log).evalf(subs={x:-5*I})
1119
+ assert atan(5*I).evalf() == atan(x).rewrite(log).evalf(subs={x:5*I})
1120
+
1121
+
1122
+ def test_atan_fdiff():
1123
+ assert atan(x).fdiff() == 1/(x**2 + 1)
1124
+ raises(ArgumentIndexError, lambda: atan(x).fdiff(2))
1125
+
1126
+
1127
+ def test_atan_leading_term():
1128
+ assert atan(x).as_leading_term(x) == x
1129
+ assert atan(1/x).as_leading_term(x, cdir=1) == pi/2
1130
+ assert atan(1/x).as_leading_term(x, cdir=-1) == -pi/2
1131
+ # Tests concerning branch points
1132
+ assert atan(x + I).as_leading_term(x, cdir=1) == -I*log(x)/2 + pi/4 + I*log(2)/2
1133
+ assert atan(x + I).as_leading_term(x, cdir=-1) == -I*log(x)/2 - 3*pi/4 + I*log(2)/2
1134
+ assert atan(x - I).as_leading_term(x, cdir=1) == I*log(x)/2 + pi/4 - I*log(2)/2
1135
+ assert atan(x - I).as_leading_term(x, cdir=-1) == I*log(x)/2 + pi/4 - I*log(2)/2
1136
+ # Tests concerning points lying on branch cuts
1137
+ assert atan(x + 2*I).as_leading_term(x, cdir=1) == I*atanh(2)
1138
+ assert atan(x + 2*I).as_leading_term(x, cdir=-1) == -pi + I*atanh(2)
1139
+ assert atan(x - 2*I).as_leading_term(x, cdir=1) == pi - I*atanh(2)
1140
+ assert atan(x - 2*I).as_leading_term(x, cdir=-1) == -I*atanh(2)
1141
+ # Tests concerning re(ndir) == 0
1142
+ assert atan(2*I - I*x - x**2).as_leading_term(x, cdir=1) == -pi/2 + I*log(3)/2
1143
+ assert atan(2*I - I*x - x**2).as_leading_term(x, cdir=-1) == -pi/2 + I*log(3)/2
1144
+
1145
+
1146
+ def test_atan2():
1147
+ assert atan2.nargs == FiniteSet(2)
1148
+ assert atan2(0, 0) is S.NaN
1149
+ assert atan2(0, 1) == 0
1150
+ assert atan2(1, 1) == pi/4
1151
+ assert atan2(1, 0) == pi/2
1152
+ assert atan2(1, -1) == pi*Rational(3, 4)
1153
+ assert atan2(0, -1) == pi
1154
+ assert atan2(-1, -1) == pi*Rational(-3, 4)
1155
+ assert atan2(-1, 0) == -pi/2
1156
+ assert atan2(-1, 1) == -pi/4
1157
+ i = symbols('i', imaginary=True)
1158
+ r = symbols('r', real=True)
1159
+ eq = atan2(r, i)
1160
+ ans = -I*log((i + I*r)/sqrt(i**2 + r**2))
1161
+ reps = ((r, 2), (i, I))
1162
+ assert eq.subs(reps) == ans.subs(reps)
1163
+
1164
+ x = Symbol('x', negative=True)
1165
+ y = Symbol('y', negative=True)
1166
+ assert atan2(y, x) == atan(y/x) - pi
1167
+ y = Symbol('y', nonnegative=True)
1168
+ assert atan2(y, x) == atan(y/x) + pi
1169
+ y = Symbol('y')
1170
+ assert atan2(y, x) == atan2(y, x, evaluate=False)
1171
+
1172
+ u = Symbol("u", positive=True)
1173
+ assert atan2(0, u) == 0
1174
+ u = Symbol("u", negative=True)
1175
+ assert atan2(0, u) == pi
1176
+
1177
+ assert atan2(y, oo) == 0
1178
+ assert atan2(y, -oo)== 2*pi*Heaviside(re(y), S.Half) - pi
1179
+
1180
+ assert atan2(y, x).rewrite(log) == -I*log((x + I*y)/sqrt(x**2 + y**2))
1181
+ assert atan2(0, 0) is S.NaN
1182
+
1183
+ ex = atan2(y, x) - arg(x + I*y)
1184
+ assert ex.subs({x:2, y:3}).rewrite(arg) == 0
1185
+ assert ex.subs({x:2, y:3*I}).rewrite(arg) == -pi - I*log(sqrt(5)*I/5)
1186
+ assert ex.subs({x:2*I, y:3}).rewrite(arg) == -pi/2 - I*log(sqrt(5)*I)
1187
+ assert ex.subs({x:2*I, y:3*I}).rewrite(arg) == -pi + atan(Rational(2, 3)) + atan(Rational(3, 2))
1188
+ i = symbols('i', imaginary=True)
1189
+ r = symbols('r', real=True)
1190
+ e = atan2(i, r)
1191
+ rewrite = e.rewrite(arg)
1192
+ reps = {i: I, r: -2}
1193
+ assert rewrite == -I*log(abs(I*i + r)/sqrt(abs(i**2 + r**2))) + arg((I*i + r)/sqrt(i**2 + r**2))
1194
+ assert (e - rewrite).subs(reps).equals(0)
1195
+
1196
+ assert atan2(0, x).rewrite(atan) == Piecewise((pi, re(x) < 0),
1197
+ (0, Ne(x, 0)),
1198
+ (nan, True))
1199
+ assert atan2(0, r).rewrite(atan) == Piecewise((pi, r < 0), (0, Ne(r, 0)), (S.NaN, True))
1200
+ assert atan2(0, i),rewrite(atan) == 0
1201
+ assert atan2(0, r + i).rewrite(atan) == Piecewise((pi, r < 0), (0, True))
1202
+
1203
+ assert atan2(y, x).rewrite(atan) == Piecewise(
1204
+ (2*atan(y/(x + sqrt(x**2 + y**2))), Ne(y, 0)),
1205
+ (pi, re(x) < 0),
1206
+ (0, (re(x) > 0) | Ne(im(x), 0)),
1207
+ (nan, True))
1208
+ assert conjugate(atan2(x, y)) == atan2(conjugate(x), conjugate(y))
1209
+
1210
+ assert diff(atan2(y, x), x) == -y/(x**2 + y**2)
1211
+ assert diff(atan2(y, x), y) == x/(x**2 + y**2)
1212
+
1213
+ assert simplify(diff(atan2(y, x).rewrite(log), x)) == -y/(x**2 + y**2)
1214
+ assert simplify(diff(atan2(y, x).rewrite(log), y)) == x/(x**2 + y**2)
1215
+
1216
+ assert str(atan2(1, 2).evalf(5)) == '0.46365'
1217
+ raises(ArgumentIndexError, lambda: atan2(x, y).fdiff(3))
1218
+
1219
+ def test_issue_17461():
1220
+ class A(Symbol):
1221
+ is_extended_real = True
1222
+
1223
+ def _eval_evalf(self, prec):
1224
+ return Float(5.0)
1225
+
1226
+ x = A('X')
1227
+ y = A('Y')
1228
+ assert abs(atan2(x, y).evalf() - 0.785398163397448) <= 1e-10
1229
+
1230
+ def test_acot():
1231
+ assert acot(nan) is nan
1232
+
1233
+ assert acot.nargs == FiniteSet(1)
1234
+ assert acot(-oo) == 0
1235
+ assert acot(oo) == 0
1236
+ assert acot(zoo) == 0
1237
+ assert acot(1) == pi/4
1238
+ assert acot(0) == pi/2
1239
+ assert acot(sqrt(3)/3) == pi/3
1240
+ assert acot(1/sqrt(3)) == pi/3
1241
+ assert acot(-1/sqrt(3)) == -pi/3
1242
+ assert acot(x).diff(x) == -1/(1 + x**2)
1243
+
1244
+ assert acot(r).is_extended_real is True
1245
+
1246
+ assert acot(I*pi) == -I*acoth(pi)
1247
+ assert acot(-2*I) == I*acoth(2)
1248
+ assert acot(x).is_positive is None
1249
+ assert acot(n).is_positive is False
1250
+ assert acot(p).is_positive is True
1251
+ assert acot(I).is_positive is False
1252
+ assert acot(Rational(1, 4)).is_rational is False
1253
+ assert unchanged(acot, cot(x))
1254
+ assert unchanged(acot, tan(x))
1255
+ assert acot(cot(Rational(1, 4))) == Rational(1, 4)
1256
+ assert acot(tan(Rational(-1, 4))) == Rational(1, 4) - pi/2
1257
+
1258
+
1259
+ def test_acot_rewrite():
1260
+ assert acot(x).rewrite(log) == I*(log(1 - I/x)-log(1 + I/x))/2
1261
+ assert acot(x).rewrite(asin) == x*(-asin(sqrt(-x**2)/sqrt(-x**2 - 1)) + pi/2)*sqrt(x**(-2))
1262
+ assert acot(x).rewrite(acos) == x*sqrt(x**(-2))*acos(sqrt(-x**2)/sqrt(-x**2 - 1))
1263
+ assert acot(x).rewrite(atan) == atan(1/x)
1264
+ assert acot(x).rewrite(asec) == x*sqrt(x**(-2))*asec(sqrt((x**2 + 1)/x**2))
1265
+ assert acot(x).rewrite(acsc) == x*(-acsc(sqrt((x**2 + 1)/x**2)) + pi/2)*sqrt(x**(-2))
1266
+
1267
+ assert acot(-I/5).evalf() == acot(x).rewrite(log).evalf(subs={x:-I/5})
1268
+ assert acot(I/5).evalf() == acot(x).rewrite(log).evalf(subs={x:I/5})
1269
+
1270
+
1271
+ def test_acot_fdiff():
1272
+ assert acot(x).fdiff() == -1/(x**2 + 1)
1273
+ raises(ArgumentIndexError, lambda: acot(x).fdiff(2))
1274
+
1275
+ def test_acot_leading_term():
1276
+ assert acot(1/x).as_leading_term(x) == x
1277
+ # Tests concerning branch points
1278
+ assert acot(x + I).as_leading_term(x, cdir=1) == I*log(x)/2 + pi/4 - I*log(2)/2
1279
+ assert acot(x + I).as_leading_term(x, cdir=-1) == I*log(x)/2 + pi/4 - I*log(2)/2
1280
+ assert acot(x - I).as_leading_term(x, cdir=1) == -I*log(x)/2 + pi/4 + I*log(2)/2
1281
+ assert acot(x - I).as_leading_term(x, cdir=-1) == -I*log(x)/2 - 3*pi/4 + I*log(2)/2
1282
+ # Tests concerning points lying on branch cuts
1283
+ assert acot(x).as_leading_term(x, cdir=1) == pi/2
1284
+ assert acot(x).as_leading_term(x, cdir=-1) == -pi/2
1285
+ assert acot(x + I/2).as_leading_term(x, cdir=1) == pi - I*acoth(S(1)/2)
1286
+ assert acot(x + I/2).as_leading_term(x, cdir=-1) == -I*acoth(S(1)/2)
1287
+ assert acot(x - I/2).as_leading_term(x, cdir=1) == I*acoth(S(1)/2)
1288
+ assert acot(x - I/2).as_leading_term(x, cdir=-1) == -pi + I*acoth(S(1)/2)
1289
+ # Tests concerning re(ndir) == 0
1290
+ assert acot(I/2 - I*x - x**2).as_leading_term(x, cdir=1) == -pi/2 - I*log(3)/2
1291
+ assert acot(I/2 - I*x - x**2).as_leading_term(x, cdir=-1) == -pi/2 - I*log(3)/2
1292
+
1293
+
1294
+ def test_attributes():
1295
+ assert sin(x).args == (x,)
1296
+
1297
+
1298
+ def test_sincos_rewrite():
1299
+ assert sin(pi/2 - x) == cos(x)
1300
+ assert sin(pi - x) == sin(x)
1301
+ assert cos(pi/2 - x) == sin(x)
1302
+ assert cos(pi - x) == -cos(x)
1303
+
1304
+
1305
+ def _check_even_rewrite(func, arg):
1306
+ """Checks that the expr has been rewritten using f(-x) -> f(x)
1307
+ arg : -x
1308
+ """
1309
+ return func(arg).args[0] == -arg
1310
+
1311
+
1312
+ def _check_odd_rewrite(func, arg):
1313
+ """Checks that the expr has been rewritten using f(-x) -> -f(x)
1314
+ arg : -x
1315
+ """
1316
+ return func(arg).func.is_Mul
1317
+
1318
+
1319
+ def _check_no_rewrite(func, arg):
1320
+ """Checks that the expr is not rewritten"""
1321
+ return func(arg).args[0] == arg
1322
+
1323
+
1324
+ def test_evenodd_rewrite():
1325
+ a = cos(2) # negative
1326
+ b = sin(1) # positive
1327
+ even = [cos]
1328
+ odd = [sin, tan, cot, asin, atan, acot]
1329
+ with_minus = [-1, -2**1024 * E, -pi/105, -x*y, -x - y]
1330
+ for func in even:
1331
+ for expr in with_minus:
1332
+ assert _check_even_rewrite(func, expr)
1333
+ assert _check_no_rewrite(func, a*b)
1334
+ assert func(
1335
+ x - y) == func(y - x) # it doesn't matter which form is canonical
1336
+ for func in odd:
1337
+ for expr in with_minus:
1338
+ assert _check_odd_rewrite(func, expr)
1339
+ assert _check_no_rewrite(func, a*b)
1340
+ assert func(
1341
+ x - y) == -func(y - x) # it doesn't matter which form is canonical
1342
+
1343
+
1344
+ def test_as_leading_term_issue_5272():
1345
+ assert sin(x).as_leading_term(x) == x
1346
+ assert cos(x).as_leading_term(x) == 1
1347
+ assert tan(x).as_leading_term(x) == x
1348
+ assert cot(x).as_leading_term(x) == 1/x
1349
+
1350
+
1351
+ def test_leading_terms():
1352
+ assert sin(1/x).as_leading_term(x) == AccumBounds(-1, 1)
1353
+ assert sin(S.Half).as_leading_term(x) == sin(S.Half)
1354
+ assert cos(1/x).as_leading_term(x) == AccumBounds(-1, 1)
1355
+ assert cos(S.Half).as_leading_term(x) == cos(S.Half)
1356
+ assert sec(1/x).as_leading_term(x) == AccumBounds(S.NegativeInfinity, S.Infinity)
1357
+ assert csc(1/x).as_leading_term(x) == AccumBounds(S.NegativeInfinity, S.Infinity)
1358
+ assert tan(1/x).as_leading_term(x) == AccumBounds(S.NegativeInfinity, S.Infinity)
1359
+ assert cot(1/x).as_leading_term(x) == AccumBounds(S.NegativeInfinity, S.Infinity)
1360
+
1361
+ # https://github.com/sympy/sympy/issues/21038
1362
+ f = sin(pi*(x + 4))/(3*x)
1363
+ assert f.as_leading_term(x) == pi/3
1364
+
1365
+
1366
+ def test_atan2_expansion():
1367
+ assert cancel(atan2(x**2, x + 1).diff(x) - atan(x**2/(x + 1)).diff(x)) == 0
1368
+ assert cancel(atan(y/x).series(y, 0, 5) - atan2(y, x).series(y, 0, 5)
1369
+ + atan2(0, x) - atan(0)) == O(y**5)
1370
+ assert cancel(atan(y/x).series(x, 1, 4) - atan2(y, x).series(x, 1, 4)
1371
+ + atan2(y, 1) - atan(y)) == O((x - 1)**4, (x, 1))
1372
+ assert cancel(atan((y + x)/x).series(x, 1, 3) - atan2(y + x, x).series(x, 1, 3)
1373
+ + atan2(1 + y, 1) - atan(1 + y)) == O((x - 1)**3, (x, 1))
1374
+ assert Matrix([atan2(y, x)]).jacobian([y, x]) == \
1375
+ Matrix([[x/(y**2 + x**2), -y/(y**2 + x**2)]])
1376
+
1377
+
1378
+ def test_aseries():
1379
+ def t(n, v, d, e):
1380
+ assert abs(
1381
+ n(1/v).evalf() - n(1/x).series(x, dir=d).removeO().subs(x, v)) < e
1382
+ t(atan, 0.1, '+', 1e-5)
1383
+ t(atan, -0.1, '-', 1e-5)
1384
+ t(acot, 0.1, '+', 1e-5)
1385
+ t(acot, -0.1, '-', 1e-5)
1386
+
1387
+
1388
+ def test_issue_4420():
1389
+ i = Symbol('i', integer=True)
1390
+ e = Symbol('e', even=True)
1391
+ o = Symbol('o', odd=True)
1392
+
1393
+ # unknown parity for variable
1394
+ assert cos(4*i*pi) == 1
1395
+ assert sin(4*i*pi) == 0
1396
+ assert tan(4*i*pi) == 0
1397
+ assert cot(4*i*pi) is zoo
1398
+
1399
+ assert cos(3*i*pi) == cos(pi*i) # +/-1
1400
+ assert sin(3*i*pi) == 0
1401
+ assert tan(3*i*pi) == 0
1402
+ assert cot(3*i*pi) is zoo
1403
+
1404
+ assert cos(4.0*i*pi) == 1
1405
+ assert sin(4.0*i*pi) == 0
1406
+ assert tan(4.0*i*pi) == 0
1407
+ assert cot(4.0*i*pi) is zoo
1408
+
1409
+ assert cos(3.0*i*pi) == cos(pi*i) # +/-1
1410
+ assert sin(3.0*i*pi) == 0
1411
+ assert tan(3.0*i*pi) == 0
1412
+ assert cot(3.0*i*pi) is zoo
1413
+
1414
+ assert cos(4.5*i*pi) == cos(0.5*pi*i)
1415
+ assert sin(4.5*i*pi) == sin(0.5*pi*i)
1416
+ assert tan(4.5*i*pi) == tan(0.5*pi*i)
1417
+ assert cot(4.5*i*pi) == cot(0.5*pi*i)
1418
+
1419
+ # parity of variable is known
1420
+ assert cos(4*e*pi) == 1
1421
+ assert sin(4*e*pi) == 0
1422
+ assert tan(4*e*pi) == 0
1423
+ assert cot(4*e*pi) is zoo
1424
+
1425
+ assert cos(3*e*pi) == 1
1426
+ assert sin(3*e*pi) == 0
1427
+ assert tan(3*e*pi) == 0
1428
+ assert cot(3*e*pi) is zoo
1429
+
1430
+ assert cos(4.0*e*pi) == 1
1431
+ assert sin(4.0*e*pi) == 0
1432
+ assert tan(4.0*e*pi) == 0
1433
+ assert cot(4.0*e*pi) is zoo
1434
+
1435
+ assert cos(3.0*e*pi) == 1
1436
+ assert sin(3.0*e*pi) == 0
1437
+ assert tan(3.0*e*pi) == 0
1438
+ assert cot(3.0*e*pi) is zoo
1439
+
1440
+ assert cos(4.5*e*pi) == cos(0.5*pi*e)
1441
+ assert sin(4.5*e*pi) == sin(0.5*pi*e)
1442
+ assert tan(4.5*e*pi) == tan(0.5*pi*e)
1443
+ assert cot(4.5*e*pi) == cot(0.5*pi*e)
1444
+
1445
+ assert cos(4*o*pi) == 1
1446
+ assert sin(4*o*pi) == 0
1447
+ assert tan(4*o*pi) == 0
1448
+ assert cot(4*o*pi) is zoo
1449
+
1450
+ assert cos(3*o*pi) == -1
1451
+ assert sin(3*o*pi) == 0
1452
+ assert tan(3*o*pi) == 0
1453
+ assert cot(3*o*pi) is zoo
1454
+
1455
+ assert cos(4.0*o*pi) == 1
1456
+ assert sin(4.0*o*pi) == 0
1457
+ assert tan(4.0*o*pi) == 0
1458
+ assert cot(4.0*o*pi) is zoo
1459
+
1460
+ assert cos(3.0*o*pi) == -1
1461
+ assert sin(3.0*o*pi) == 0
1462
+ assert tan(3.0*o*pi) == 0
1463
+ assert cot(3.0*o*pi) is zoo
1464
+
1465
+ assert cos(4.5*o*pi) == cos(0.5*pi*o)
1466
+ assert sin(4.5*o*pi) == sin(0.5*pi*o)
1467
+ assert tan(4.5*o*pi) == tan(0.5*pi*o)
1468
+ assert cot(4.5*o*pi) == cot(0.5*pi*o)
1469
+
1470
+ # x could be imaginary
1471
+ assert cos(4*x*pi) == cos(4*pi*x)
1472
+ assert sin(4*x*pi) == sin(4*pi*x)
1473
+ assert tan(4*x*pi) == tan(4*pi*x)
1474
+ assert cot(4*x*pi) == cot(4*pi*x)
1475
+
1476
+ assert cos(3*x*pi) == cos(3*pi*x)
1477
+ assert sin(3*x*pi) == sin(3*pi*x)
1478
+ assert tan(3*x*pi) == tan(3*pi*x)
1479
+ assert cot(3*x*pi) == cot(3*pi*x)
1480
+
1481
+ assert cos(4.0*x*pi) == cos(4.0*pi*x)
1482
+ assert sin(4.0*x*pi) == sin(4.0*pi*x)
1483
+ assert tan(4.0*x*pi) == tan(4.0*pi*x)
1484
+ assert cot(4.0*x*pi) == cot(4.0*pi*x)
1485
+
1486
+ assert cos(3.0*x*pi) == cos(3.0*pi*x)
1487
+ assert sin(3.0*x*pi) == sin(3.0*pi*x)
1488
+ assert tan(3.0*x*pi) == tan(3.0*pi*x)
1489
+ assert cot(3.0*x*pi) == cot(3.0*pi*x)
1490
+
1491
+ assert cos(4.5*x*pi) == cos(4.5*pi*x)
1492
+ assert sin(4.5*x*pi) == sin(4.5*pi*x)
1493
+ assert tan(4.5*x*pi) == tan(4.5*pi*x)
1494
+ assert cot(4.5*x*pi) == cot(4.5*pi*x)
1495
+
1496
+
1497
+ def test_inverses():
1498
+ raises(AttributeError, lambda: sin(x).inverse())
1499
+ raises(AttributeError, lambda: cos(x).inverse())
1500
+ assert tan(x).inverse() == atan
1501
+ assert cot(x).inverse() == acot
1502
+ raises(AttributeError, lambda: csc(x).inverse())
1503
+ raises(AttributeError, lambda: sec(x).inverse())
1504
+ assert asin(x).inverse() == sin
1505
+ assert acos(x).inverse() == cos
1506
+ assert atan(x).inverse() == tan
1507
+ assert acot(x).inverse() == cot
1508
+
1509
+
1510
+ def test_real_imag():
1511
+ a, b = symbols('a b', real=True)
1512
+ z = a + b*I
1513
+ for deep in [True, False]:
1514
+ assert sin(
1515
+ z).as_real_imag(deep=deep) == (sin(a)*cosh(b), cos(a)*sinh(b))
1516
+ assert cos(
1517
+ z).as_real_imag(deep=deep) == (cos(a)*cosh(b), -sin(a)*sinh(b))
1518
+ assert tan(z).as_real_imag(deep=deep) == (sin(2*a)/(cos(2*a) +
1519
+ cosh(2*b)), sinh(2*b)/(cos(2*a) + cosh(2*b)))
1520
+ assert cot(z).as_real_imag(deep=deep) == (-sin(2*a)/(cos(2*a) -
1521
+ cosh(2*b)), sinh(2*b)/(cos(2*a) - cosh(2*b)))
1522
+ assert sin(a).as_real_imag(deep=deep) == (sin(a), 0)
1523
+ assert cos(a).as_real_imag(deep=deep) == (cos(a), 0)
1524
+ assert tan(a).as_real_imag(deep=deep) == (tan(a), 0)
1525
+ assert cot(a).as_real_imag(deep=deep) == (cot(a), 0)
1526
+
1527
+
1528
+ @XFAIL
1529
+ def test_sin_cos_with_infinity():
1530
+ # Test for issue 5196
1531
+ # https://github.com/sympy/sympy/issues/5196
1532
+ assert sin(oo) is S.NaN
1533
+ assert cos(oo) is S.NaN
1534
+
1535
+
1536
+ @slow
1537
+ def test_sincos_rewrite_sqrt():
1538
+ # equivalent to testing rewrite(pow)
1539
+ for p in [1, 3, 5, 17]:
1540
+ for t in [1, 8]:
1541
+ n = t*p
1542
+ # The vertices `exp(i*pi/n)` of a regular `n`-gon can
1543
+ # be expressed by means of nested square roots if and
1544
+ # only if `n` is a product of Fermat primes, `p`, and
1545
+ # powers of 2, `t'. The code aims to check all vertices
1546
+ # not belonging to an `m`-gon for `m < n`(`gcd(i, n) == 1`).
1547
+ # For large `n` this makes the test too slow, therefore
1548
+ # the vertices are limited to those of index `i < 10`.
1549
+ for i in range(1, min((n + 1)//2 + 1, 10)):
1550
+ if 1 == gcd(i, n):
1551
+ x = i*pi/n
1552
+ s1 = sin(x).rewrite(sqrt)
1553
+ c1 = cos(x).rewrite(sqrt)
1554
+ assert not s1.has(cos, sin), "fails for %d*pi/%d" % (i, n)
1555
+ assert not c1.has(cos, sin), "fails for %d*pi/%d" % (i, n)
1556
+ assert 1e-3 > abs(sin(x.evalf(5)) - s1.evalf(2)), "fails for %d*pi/%d" % (i, n)
1557
+ assert 1e-3 > abs(cos(x.evalf(5)) - c1.evalf(2)), "fails for %d*pi/%d" % (i, n)
1558
+ assert cos(pi/14).rewrite(sqrt) == sqrt(cos(pi/7)/2 + S.Half)
1559
+ assert cos(pi*Rational(-15, 2)/11, evaluate=False).rewrite(
1560
+ sqrt) == -sqrt(-cos(pi*Rational(4, 11))/2 + S.Half)
1561
+ assert cos(Mul(2, pi, S.Half, evaluate=False), evaluate=False).rewrite(
1562
+ sqrt) == -1
1563
+ e = cos(pi/3/17) # don't use pi/15 since that is caught at instantiation
1564
+ a = (
1565
+ -3*sqrt(-sqrt(17) + 17)*sqrt(sqrt(17) + 17)/64 -
1566
+ 3*sqrt(34)*sqrt(sqrt(17) + 17)/128 - sqrt(sqrt(17) +
1567
+ 17)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17)
1568
+ + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/64 - sqrt(-sqrt(17)
1569
+ + 17)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
1570
+ 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/128 - Rational(1, 32) +
1571
+ sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
1572
+ 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/64 +
1573
+ 3*sqrt(2)*sqrt(sqrt(17) + 17)/128 + sqrt(34)*sqrt(-sqrt(17) + 17)/128
1574
+ + 13*sqrt(2)*sqrt(-sqrt(17) + 17)/128 + sqrt(17)*sqrt(-sqrt(17) +
1575
+ 17)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17)
1576
+ + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/128 + 5*sqrt(17)/32
1577
+ + sqrt(3)*sqrt(-sqrt(2)*sqrt(sqrt(17) + 17)*sqrt(sqrt(17)/32 +
1578
+ sqrt(2)*sqrt(-sqrt(17) + 17)/32 +
1579
+ sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
1580
+ 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + Rational(15, 32))/8 -
1581
+ 5*sqrt(2)*sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) + 17)/32 +
1582
+ sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
1583
+ 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 +
1584
+ Rational(15, 32))*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
1585
+ 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/64 -
1586
+ 3*sqrt(2)*sqrt(-sqrt(17) + 17)*sqrt(sqrt(17)/32 +
1587
+ sqrt(2)*sqrt(-sqrt(17) + 17)/32 +
1588
+ sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
1589
+ 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + Rational(15, 32))/32
1590
+ + sqrt(34)*sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) + 17)/32 +
1591
+ sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
1592
+ 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 +
1593
+ Rational(15, 32))*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
1594
+ 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/64 +
1595
+ sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) + 17)/32 +
1596
+ sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
1597
+ 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + Rational(15, 32))/2 +
1598
+ S.Half + sqrt(-sqrt(17) + 17)*sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) +
1599
+ 17)/32 + sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) -
1600
+ sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) +
1601
+ 6*sqrt(17) + 34)/32 + Rational(15, 32))*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) -
1602
+ sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) +
1603
+ 6*sqrt(17) + 34)/32 + sqrt(34)*sqrt(-sqrt(17) + 17)*sqrt(sqrt(17)/32 +
1604
+ sqrt(2)*sqrt(-sqrt(17) + 17)/32 +
1605
+ sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
1606
+ 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 +
1607
+ Rational(15, 32))/32)/2)
1608
+ assert e.rewrite(sqrt) == a
1609
+ assert e.n() == a.n()
1610
+ # coverage of fermatCoords: multiplicity > 1; the following could be
1611
+ # different but that portion of the code should be tested in some way
1612
+ assert cos(pi/9/17).rewrite(sqrt) == \
1613
+ sin(pi/9)*sin(pi*Rational(2, 17)) + cos(pi/9)*cos(pi*Rational(2, 17))
1614
+
1615
+
1616
+ @slow
1617
+ def test_sincos_rewrite_sqrt_257():
1618
+ assert cos(pi/257).rewrite(sqrt).evalf(64) == cos(pi/257).evalf(64)
1619
+
1620
+
1621
+ @slow
1622
+ def test_tancot_rewrite_sqrt():
1623
+ # equivalent to testing rewrite(pow)
1624
+ for p in [1, 3, 5, 17]:
1625
+ for t in [1, 8]:
1626
+ n = t*p
1627
+ for i in range(1, min((n + 1)//2 + 1, 10)):
1628
+ if 1 == gcd(i, n):
1629
+ x = i*pi/n
1630
+ if 2*i != n and 3*i != 2*n:
1631
+ t1 = tan(x).rewrite(sqrt)
1632
+ assert not t1.has(cot, tan), "fails for %d*pi/%d" % (i, n)
1633
+ assert 1e-3 > abs( tan(x.evalf(7)) - t1.evalf(4) ), "fails for %d*pi/%d" % (i, n)
1634
+ if i != 0 and i != n:
1635
+ c1 = cot(x).rewrite(sqrt)
1636
+ assert not c1.has(cot, tan), "fails for %d*pi/%d" % (i, n)
1637
+ assert 1e-3 > abs( cot(x.evalf(7)) - c1.evalf(4) ), "fails for %d*pi/%d" % (i, n)
1638
+
1639
+
1640
+ def test_sec():
1641
+ x = symbols('x', real=True)
1642
+ z = symbols('z')
1643
+
1644
+ assert sec.nargs == FiniteSet(1)
1645
+
1646
+ assert sec(zoo) is nan
1647
+ assert sec(0) == 1
1648
+ assert sec(pi) == -1
1649
+ assert sec(pi/2) is zoo
1650
+ assert sec(-pi/2) is zoo
1651
+ assert sec(pi/6) == 2*sqrt(3)/3
1652
+ assert sec(pi/3) == 2
1653
+ assert sec(pi*Rational(5, 2)) is zoo
1654
+ assert sec(pi*Rational(9, 7)) == -sec(pi*Rational(2, 7))
1655
+ assert sec(pi*Rational(3, 4)) == -sqrt(2) # issue 8421
1656
+ assert sec(I) == 1/cosh(1)
1657
+ assert sec(x*I) == 1/cosh(x)
1658
+ assert sec(-x) == sec(x)
1659
+
1660
+ assert sec(asec(x)) == x
1661
+
1662
+ assert sec(z).conjugate() == sec(conjugate(z))
1663
+
1664
+ assert (sec(z).as_real_imag() ==
1665
+ (cos(re(z))*cosh(im(z))/(sin(re(z))**2*sinh(im(z))**2 +
1666
+ cos(re(z))**2*cosh(im(z))**2),
1667
+ sin(re(z))*sinh(im(z))/(sin(re(z))**2*sinh(im(z))**2 +
1668
+ cos(re(z))**2*cosh(im(z))**2)))
1669
+
1670
+ assert sec(x).expand(trig=True) == 1/cos(x)
1671
+ assert sec(2*x).expand(trig=True) == 1/(2*cos(x)**2 - 1)
1672
+
1673
+ assert sec(x).is_extended_real == True
1674
+ assert sec(z).is_real == None
1675
+
1676
+ assert sec(a).is_algebraic is None
1677
+ assert sec(na).is_algebraic is False
1678
+
1679
+ assert sec(x).as_leading_term() == sec(x)
1680
+
1681
+ assert sec(0, evaluate=False).is_finite == True
1682
+ assert sec(x).is_finite == None
1683
+ assert sec(pi/2, evaluate=False).is_finite == False
1684
+
1685
+ assert series(sec(x), x, x0=0, n=6) == 1 + x**2/2 + 5*x**4/24 + O(x**6)
1686
+
1687
+ # https://github.com/sympy/sympy/issues/7166
1688
+ assert series(sqrt(sec(x))) == 1 + x**2/4 + 7*x**4/96 + O(x**6)
1689
+
1690
+ # https://github.com/sympy/sympy/issues/7167
1691
+ assert (series(sqrt(sec(x)), x, x0=pi*3/2, n=4) ==
1692
+ 1/sqrt(x - pi*Rational(3, 2)) + (x - pi*Rational(3, 2))**Rational(3, 2)/12 +
1693
+ (x - pi*Rational(3, 2))**Rational(7, 2)/160 + O((x - pi*Rational(3, 2))**4, (x, pi*Rational(3, 2))))
1694
+
1695
+ assert sec(x).diff(x) == tan(x)*sec(x)
1696
+
1697
+ # Taylor Term checks
1698
+ assert sec(z).taylor_term(4, z) == 5*z**4/24
1699
+ assert sec(z).taylor_term(6, z) == 61*z**6/720
1700
+ assert sec(z).taylor_term(5, z) == 0
1701
+
1702
+
1703
+ def test_sec_rewrite():
1704
+ assert sec(x).rewrite(exp) == 1/(exp(I*x)/2 + exp(-I*x)/2)
1705
+ assert sec(x).rewrite(cos) == 1/cos(x)
1706
+ assert sec(x).rewrite(tan) == (tan(x/2)**2 + 1)/(-tan(x/2)**2 + 1)
1707
+ assert sec(x).rewrite(pow) == sec(x)
1708
+ assert sec(x).rewrite(sqrt) == sec(x)
1709
+ assert sec(z).rewrite(cot) == (cot(z/2)**2 + 1)/(cot(z/2)**2 - 1)
1710
+ assert sec(x).rewrite(sin) == 1 / sin(x + pi / 2, evaluate=False)
1711
+ assert sec(x).rewrite(tan) == (tan(x / 2)**2 + 1) / (-tan(x / 2)**2 + 1)
1712
+ assert sec(x).rewrite(csc) == csc(-x + pi/2, evaluate=False)
1713
+
1714
+
1715
+ def test_sec_fdiff():
1716
+ assert sec(x).fdiff() == tan(x)*sec(x)
1717
+ raises(ArgumentIndexError, lambda: sec(x).fdiff(2))
1718
+
1719
+
1720
+ def test_csc():
1721
+ x = symbols('x', real=True)
1722
+ z = symbols('z')
1723
+
1724
+ # https://github.com/sympy/sympy/issues/6707
1725
+ cosecant = csc('x')
1726
+ alternate = 1/sin('x')
1727
+ assert cosecant.equals(alternate) == True
1728
+ assert alternate.equals(cosecant) == True
1729
+
1730
+ assert csc.nargs == FiniteSet(1)
1731
+
1732
+ assert csc(0) is zoo
1733
+ assert csc(pi) is zoo
1734
+ assert csc(zoo) is nan
1735
+
1736
+ assert csc(pi/2) == 1
1737
+ assert csc(-pi/2) == -1
1738
+ assert csc(pi/6) == 2
1739
+ assert csc(pi/3) == 2*sqrt(3)/3
1740
+ assert csc(pi*Rational(5, 2)) == 1
1741
+ assert csc(pi*Rational(9, 7)) == -csc(pi*Rational(2, 7))
1742
+ assert csc(pi*Rational(3, 4)) == sqrt(2) # issue 8421
1743
+ assert csc(I) == -I/sinh(1)
1744
+ assert csc(x*I) == -I/sinh(x)
1745
+ assert csc(-x) == -csc(x)
1746
+
1747
+ assert csc(acsc(x)) == x
1748
+
1749
+ assert csc(z).conjugate() == csc(conjugate(z))
1750
+
1751
+ assert (csc(z).as_real_imag() ==
1752
+ (sin(re(z))*cosh(im(z))/(sin(re(z))**2*cosh(im(z))**2 +
1753
+ cos(re(z))**2*sinh(im(z))**2),
1754
+ -cos(re(z))*sinh(im(z))/(sin(re(z))**2*cosh(im(z))**2 +
1755
+ cos(re(z))**2*sinh(im(z))**2)))
1756
+
1757
+ assert csc(x).expand(trig=True) == 1/sin(x)
1758
+ assert csc(2*x).expand(trig=True) == 1/(2*sin(x)*cos(x))
1759
+
1760
+ assert csc(x).is_extended_real == True
1761
+ assert csc(z).is_real == None
1762
+
1763
+ assert csc(a).is_algebraic is None
1764
+ assert csc(na).is_algebraic is False
1765
+
1766
+ assert csc(x).as_leading_term() == csc(x)
1767
+
1768
+ assert csc(0, evaluate=False).is_finite == False
1769
+ assert csc(x).is_finite == None
1770
+ assert csc(pi/2, evaluate=False).is_finite == True
1771
+
1772
+ assert series(csc(x), x, x0=pi/2, n=6) == \
1773
+ 1 + (x - pi/2)**2/2 + 5*(x - pi/2)**4/24 + O((x - pi/2)**6, (x, pi/2))
1774
+ assert series(csc(x), x, x0=0, n=6) == \
1775
+ 1/x + x/6 + 7*x**3/360 + 31*x**5/15120 + O(x**6)
1776
+
1777
+ assert csc(x).diff(x) == -cot(x)*csc(x)
1778
+
1779
+ assert csc(x).taylor_term(2, x) == 0
1780
+ assert csc(x).taylor_term(3, x) == 7*x**3/360
1781
+ assert csc(x).taylor_term(5, x) == 31*x**5/15120
1782
+ raises(ArgumentIndexError, lambda: csc(x).fdiff(2))
1783
+
1784
+
1785
+ def test_asec():
1786
+ z = Symbol('z', zero=True)
1787
+ assert asec(z) is zoo
1788
+ assert asec(nan) is nan
1789
+ assert asec(1) == 0
1790
+ assert asec(-1) == pi
1791
+ assert asec(oo) == pi/2
1792
+ assert asec(-oo) == pi/2
1793
+ assert asec(zoo) == pi/2
1794
+
1795
+ assert asec(sec(pi*Rational(13, 4))) == pi*Rational(3, 4)
1796
+ assert asec(1 + sqrt(5)) == pi*Rational(2, 5)
1797
+ assert asec(2/sqrt(3)) == pi/6
1798
+ assert asec(sqrt(4 - 2*sqrt(2))) == pi/8
1799
+ assert asec(-sqrt(4 + 2*sqrt(2))) == pi*Rational(5, 8)
1800
+ assert asec(sqrt(2 + 2*sqrt(5)/5)) == pi*Rational(3, 10)
1801
+ assert asec(-sqrt(2 + 2*sqrt(5)/5)) == pi*Rational(7, 10)
1802
+ assert asec(sqrt(2) - sqrt(6)) == pi*Rational(11, 12)
1803
+
1804
+ assert asec(x).diff(x) == 1/(x**2*sqrt(1 - 1/x**2))
1805
+
1806
+ assert asec(x).rewrite(log) == I*log(sqrt(1 - 1/x**2) + I/x) + pi/2
1807
+ assert asec(x).rewrite(asin) == -asin(1/x) + pi/2
1808
+ assert asec(x).rewrite(acos) == acos(1/x)
1809
+ assert asec(x).rewrite(atan) == \
1810
+ pi*(1 - sqrt(x**2)/x)/2 + sqrt(x**2)*atan(sqrt(x**2 - 1))/x
1811
+ assert asec(x).rewrite(acot) == \
1812
+ pi*(1 - sqrt(x**2)/x)/2 + sqrt(x**2)*acot(1/sqrt(x**2 - 1))/x
1813
+ assert asec(x).rewrite(acsc) == -acsc(x) + pi/2
1814
+ raises(ArgumentIndexError, lambda: asec(x).fdiff(2))
1815
+
1816
+
1817
+ def test_asec_is_real():
1818
+ assert asec(S.Half).is_real is False
1819
+ n = Symbol('n', positive=True, integer=True)
1820
+ assert asec(n).is_extended_real is True
1821
+ assert asec(x).is_real is None
1822
+ assert asec(r).is_real is None
1823
+ t = Symbol('t', real=False, finite=True)
1824
+ assert asec(t).is_real is False
1825
+
1826
+
1827
+ def test_asec_leading_term():
1828
+ assert asec(1/x).as_leading_term(x) == pi/2
1829
+ # Tests concerning branch points
1830
+ assert asec(x + 1).as_leading_term(x) == sqrt(2)*sqrt(x)
1831
+ assert asec(x - 1).as_leading_term(x) == pi
1832
+ # Tests concerning points lying on branch cuts
1833
+ assert asec(x).as_leading_term(x, cdir=1) == -I*log(x) + I*log(2)
1834
+ assert asec(x).as_leading_term(x, cdir=-1) == I*log(x) + 2*pi - I*log(2)
1835
+ assert asec(I*x + 1/2).as_leading_term(x, cdir=1) == asec(1/2)
1836
+ assert asec(-I*x + 1/2).as_leading_term(x, cdir=1) == -asec(1/2)
1837
+ assert asec(I*x - 1/2).as_leading_term(x, cdir=1) == 2*pi - asec(-1/2)
1838
+ assert asec(-I*x - 1/2).as_leading_term(x, cdir=1) == asec(-1/2)
1839
+ # Tests concerning im(ndir) == 0
1840
+ assert asec(-I*x**2 + x - S(1)/2).as_leading_term(x, cdir=1) == pi + I*log(2 - sqrt(3))
1841
+ assert asec(-I*x**2 + x - S(1)/2).as_leading_term(x, cdir=-1) == pi + I*log(2 - sqrt(3))
1842
+
1843
+
1844
+ def test_asec_series():
1845
+ assert asec(x).series(x, 0, 9) == \
1846
+ I*log(2) - I*log(x) - I*x**2/4 - 3*I*x**4/32 \
1847
+ - 5*I*x**6/96 - 35*I*x**8/1024 + O(x**9)
1848
+ t4 = asec(x).taylor_term(4, x)
1849
+ assert t4 == -3*I*x**4/32
1850
+ assert asec(x).taylor_term(6, x, t4, 0) == -5*I*x**6/96
1851
+
1852
+
1853
+ def test_acsc():
1854
+ assert acsc(nan) is nan
1855
+ assert acsc(1) == pi/2
1856
+ assert acsc(-1) == -pi/2
1857
+ assert acsc(oo) == 0
1858
+ assert acsc(-oo) == 0
1859
+ assert acsc(zoo) == 0
1860
+ assert acsc(0) is zoo
1861
+
1862
+ assert acsc(csc(3)) == -3 + pi
1863
+ assert acsc(csc(4)) == -4 + pi
1864
+ assert acsc(csc(6)) == 6 - 2*pi
1865
+ assert unchanged(acsc, csc(x))
1866
+ assert unchanged(acsc, sec(x))
1867
+
1868
+ assert acsc(2/sqrt(3)) == pi/3
1869
+ assert acsc(csc(pi*Rational(13, 4))) == -pi/4
1870
+ assert acsc(sqrt(2 + 2*sqrt(5)/5)) == pi/5
1871
+ assert acsc(-sqrt(2 + 2*sqrt(5)/5)) == -pi/5
1872
+ assert acsc(-2) == -pi/6
1873
+ assert acsc(-sqrt(4 + 2*sqrt(2))) == -pi/8
1874
+ assert acsc(sqrt(4 - 2*sqrt(2))) == pi*Rational(3, 8)
1875
+ assert acsc(1 + sqrt(5)) == pi/10
1876
+ assert acsc(sqrt(2) - sqrt(6)) == pi*Rational(-5, 12)
1877
+
1878
+ assert acsc(x).diff(x) == -1/(x**2*sqrt(1 - 1/x**2))
1879
+
1880
+ assert acsc(x).rewrite(log) == -I*log(sqrt(1 - 1/x**2) + I/x)
1881
+ assert acsc(x).rewrite(asin) == asin(1/x)
1882
+ assert acsc(x).rewrite(acos) == -acos(1/x) + pi/2
1883
+ assert acsc(x).rewrite(atan) == \
1884
+ (-atan(sqrt(x**2 - 1)) + pi/2)*sqrt(x**2)/x
1885
+ assert acsc(x).rewrite(acot) == (-acot(1/sqrt(x**2 - 1)) + pi/2)*sqrt(x**2)/x
1886
+ assert acsc(x).rewrite(asec) == -asec(x) + pi/2
1887
+ raises(ArgumentIndexError, lambda: acsc(x).fdiff(2))
1888
+
1889
+
1890
+ def test_csc_rewrite():
1891
+ assert csc(x).rewrite(pow) == csc(x)
1892
+ assert csc(x).rewrite(sqrt) == csc(x)
1893
+
1894
+ assert csc(x).rewrite(exp) == 2*I/(exp(I*x) - exp(-I*x))
1895
+ assert csc(x).rewrite(sin) == 1/sin(x)
1896
+ assert csc(x).rewrite(tan) == (tan(x/2)**2 + 1)/(2*tan(x/2))
1897
+ assert csc(x).rewrite(cot) == (cot(x/2)**2 + 1)/(2*cot(x/2))
1898
+ assert csc(x).rewrite(cos) == 1/cos(x - pi/2, evaluate=False)
1899
+ assert csc(x).rewrite(sec) == sec(-x + pi/2, evaluate=False)
1900
+
1901
+ # issue 17349
1902
+ assert csc(1 - exp(-besselj(I, I))).rewrite(cos) == \
1903
+ -1/cos(-pi/2 - 1 + cos(I*besselj(I, I)) +
1904
+ I*cos(-pi/2 + I*besselj(I, I), evaluate=False), evaluate=False)
1905
+
1906
+
1907
+ def test_acsc_leading_term():
1908
+ assert acsc(1/x).as_leading_term(x) == x
1909
+ # Tests concerning branch points
1910
+ assert acsc(x + 1).as_leading_term(x) == pi/2
1911
+ assert acsc(x - 1).as_leading_term(x) == -pi/2
1912
+ # Tests concerning points lying on branch cuts
1913
+ assert acsc(x).as_leading_term(x, cdir=1) == I*log(x) + pi/2 - I*log(2)
1914
+ assert acsc(x).as_leading_term(x, cdir=-1) == -I*log(x) - 3*pi/2 + I*log(2)
1915
+ assert acsc(I*x + 1/2).as_leading_term(x, cdir=1) == acsc(1/2)
1916
+ assert acsc(-I*x + 1/2).as_leading_term(x, cdir=1) == pi - acsc(1/2)
1917
+ assert acsc(I*x - 1/2).as_leading_term(x, cdir=1) == -pi - acsc(-1/2)
1918
+ assert acsc(-I*x - 1/2).as_leading_term(x, cdir=1) == -acsc(1/2)
1919
+ # Tests concerning im(ndir) == 0
1920
+ assert acsc(-I*x**2 + x - S(1)/2).as_leading_term(x, cdir=1) == -pi/2 + I*log(sqrt(3) + 2)
1921
+ assert acsc(-I*x**2 + x - S(1)/2).as_leading_term(x, cdir=-1) == -pi/2 + I*log(sqrt(3) + 2)
1922
+
1923
+
1924
+ def test_acsc_series():
1925
+ assert acsc(x).series(x, 0, 9) == \
1926
+ -I*log(2) + pi/2 + I*log(x) + I*x**2/4 \
1927
+ + 3*I*x**4/32 + 5*I*x**6/96 + 35*I*x**8/1024 + O(x**9)
1928
+ t6 = acsc(x).taylor_term(6, x)
1929
+ assert t6 == 5*I*x**6/96
1930
+ assert acsc(x).taylor_term(8, x, t6, 0) == 35*I*x**8/1024
1931
+
1932
+
1933
+ def test_asin_nseries():
1934
+ assert asin(x + 2)._eval_nseries(x, 4, None, I) == -asin(2) + pi + \
1935
+ sqrt(3)*I*x/3 - sqrt(3)*I*x**2/9 + sqrt(3)*I*x**3/18 + O(x**4)
1936
+ assert asin(x + 2)._eval_nseries(x, 4, None, -I) == asin(2) - \
1937
+ sqrt(3)*I*x/3 + sqrt(3)*I*x**2/9 - sqrt(3)*I*x**3/18 + O(x**4)
1938
+ assert asin(x - 2)._eval_nseries(x, 4, None, I) == -asin(2) - \
1939
+ sqrt(3)*I*x/3 - sqrt(3)*I*x**2/9 - sqrt(3)*I*x**3/18 + O(x**4)
1940
+ assert asin(x - 2)._eval_nseries(x, 4, None, -I) == asin(2) - pi + \
1941
+ sqrt(3)*I*x/3 + sqrt(3)*I*x**2/9 + sqrt(3)*I*x**3/18 + O(x**4)
1942
+ # testing nseries for asin at branch points
1943
+ assert asin(1 + x)._eval_nseries(x, 3, None) == pi/2 - sqrt(2)*sqrt(-x) - \
1944
+ sqrt(2)*(-x)**(S(3)/2)/12 - 3*sqrt(2)*(-x)**(S(5)/2)/160 + O(x**3)
1945
+ assert asin(-1 + x)._eval_nseries(x, 3, None) == -pi/2 + sqrt(2)*sqrt(x) + \
1946
+ sqrt(2)*x**(S(3)/2)/12 + 3*sqrt(2)*x**(S(5)/2)/160 + O(x**3)
1947
+ assert asin(exp(x))._eval_nseries(x, 3, None) == pi/2 - sqrt(2)*sqrt(-x) + \
1948
+ sqrt(2)*(-x)**(S(3)/2)/6 - sqrt(2)*(-x)**(S(5)/2)/120 + O(x**3)
1949
+ assert asin(-exp(x))._eval_nseries(x, 3, None) == -pi/2 + sqrt(2)*sqrt(-x) - \
1950
+ sqrt(2)*(-x)**(S(3)/2)/6 + sqrt(2)*(-x)**(S(5)/2)/120 + O(x**3)
1951
+
1952
+
1953
+ def test_acos_nseries():
1954
+ assert acos(x + 2)._eval_nseries(x, 4, None, I) == -acos(2) - sqrt(3)*I*x/3 + \
1955
+ sqrt(3)*I*x**2/9 - sqrt(3)*I*x**3/18 + O(x**4)
1956
+ assert acos(x + 2)._eval_nseries(x, 4, None, -I) == acos(2) + sqrt(3)*I*x/3 - \
1957
+ sqrt(3)*I*x**2/9 + sqrt(3)*I*x**3/18 + O(x**4)
1958
+ assert acos(x - 2)._eval_nseries(x, 4, None, I) == acos(-2) + sqrt(3)*I*x/3 + \
1959
+ sqrt(3)*I*x**2/9 + sqrt(3)*I*x**3/18 + O(x**4)
1960
+ assert acos(x - 2)._eval_nseries(x, 4, None, -I) == -acos(-2) + 2*pi - \
1961
+ sqrt(3)*I*x/3 - sqrt(3)*I*x**2/9 - sqrt(3)*I*x**3/18 + O(x**4)
1962
+ # testing nseries for acos at branch points
1963
+ assert acos(1 + x)._eval_nseries(x, 3, None) == sqrt(2)*sqrt(-x) + \
1964
+ sqrt(2)*(-x)**(S(3)/2)/12 + 3*sqrt(2)*(-x)**(S(5)/2)/160 + O(x**3)
1965
+ assert acos(-1 + x)._eval_nseries(x, 3, None) == pi - sqrt(2)*sqrt(x) - \
1966
+ sqrt(2)*x**(S(3)/2)/12 - 3*sqrt(2)*x**(S(5)/2)/160 + O(x**3)
1967
+ assert acos(exp(x))._eval_nseries(x, 3, None) == sqrt(2)*sqrt(-x) - \
1968
+ sqrt(2)*(-x)**(S(3)/2)/6 + sqrt(2)*(-x)**(S(5)/2)/120 + O(x**3)
1969
+ assert acos(-exp(x))._eval_nseries(x, 3, None) == pi - sqrt(2)*sqrt(-x) + \
1970
+ sqrt(2)*(-x)**(S(3)/2)/6 - sqrt(2)*(-x)**(S(5)/2)/120 + O(x**3)
1971
+
1972
+
1973
+ def test_atan_nseries():
1974
+ assert atan(x + 2*I)._eval_nseries(x, 4, None, 1) == I*atanh(2) - x/3 - \
1975
+ 2*I*x**2/9 + 13*x**3/81 + O(x**4)
1976
+ assert atan(x + 2*I)._eval_nseries(x, 4, None, -1) == I*atanh(2) - pi - \
1977
+ x/3 - 2*I*x**2/9 + 13*x**3/81 + O(x**4)
1978
+ assert atan(x - 2*I)._eval_nseries(x, 4, None, 1) == -I*atanh(2) + pi - \
1979
+ x/3 + 2*I*x**2/9 + 13*x**3/81 + O(x**4)
1980
+ assert atan(x - 2*I)._eval_nseries(x, 4, None, -1) == -I*atanh(2) - x/3 + \
1981
+ 2*I*x**2/9 + 13*x**3/81 + O(x**4)
1982
+ assert atan(1/x)._eval_nseries(x, 2, None, 1) == pi/2 - x + O(x**2)
1983
+ assert atan(1/x)._eval_nseries(x, 2, None, -1) == -pi/2 - x + O(x**2)
1984
+ # testing nseries for atan at branch points
1985
+ assert atan(x + I)._eval_nseries(x, 4, None) == I*log(2)/2 + pi/4 - \
1986
+ I*log(x)/2 + x/4 + I*x**2/16 - x**3/48 + O(x**4)
1987
+ assert atan(x - I)._eval_nseries(x, 4, None) == -I*log(2)/2 + pi/4 + \
1988
+ I*log(x)/2 + x/4 - I*x**2/16 - x**3/48 + O(x**4)
1989
+
1990
+
1991
+ def test_acot_nseries():
1992
+ assert acot(x + S(1)/2*I)._eval_nseries(x, 4, None, 1) == -I*acoth(S(1)/2) + \
1993
+ pi - 4*x/3 + 8*I*x**2/9 + 112*x**3/81 + O(x**4)
1994
+ assert acot(x + S(1)/2*I)._eval_nseries(x, 4, None, -1) == -I*acoth(S(1)/2) - \
1995
+ 4*x/3 + 8*I*x**2/9 + 112*x**3/81 + O(x**4)
1996
+ assert acot(x - S(1)/2*I)._eval_nseries(x, 4, None, 1) == I*acoth(S(1)/2) - \
1997
+ 4*x/3 - 8*I*x**2/9 + 112*x**3/81 + O(x**4)
1998
+ assert acot(x - S(1)/2*I)._eval_nseries(x, 4, None, -1) == I*acoth(S(1)/2) - \
1999
+ pi - 4*x/3 - 8*I*x**2/9 + 112*x**3/81 + O(x**4)
2000
+ assert acot(x)._eval_nseries(x, 2, None, 1) == pi/2 - x + O(x**2)
2001
+ assert acot(x)._eval_nseries(x, 2, None, -1) == -pi/2 - x + O(x**2)
2002
+ # testing nseries for acot at branch points
2003
+ assert acot(x + I)._eval_nseries(x, 4, None) == -I*log(2)/2 + pi/4 + \
2004
+ I*log(x)/2 - x/4 - I*x**2/16 + x**3/48 + O(x**4)
2005
+ assert acot(x - I)._eval_nseries(x, 4, None) == I*log(2)/2 + pi/4 - \
2006
+ I*log(x)/2 - x/4 + I*x**2/16 + x**3/48 + O(x**4)
2007
+
2008
+
2009
+ def test_asec_nseries():
2010
+ assert asec(x + S(1)/2)._eval_nseries(x, 4, None, I) == asec(S(1)/2) - \
2011
+ 4*sqrt(3)*I*x/3 + 8*sqrt(3)*I*x**2/9 - 16*sqrt(3)*I*x**3/9 + O(x**4)
2012
+ assert asec(x + S(1)/2)._eval_nseries(x, 4, None, -I) == -asec(S(1)/2) + \
2013
+ 4*sqrt(3)*I*x/3 - 8*sqrt(3)*I*x**2/9 + 16*sqrt(3)*I*x**3/9 + O(x**4)
2014
+ assert asec(x - S(1)/2)._eval_nseries(x, 4, None, I) == -asec(-S(1)/2) + \
2015
+ 2*pi + 4*sqrt(3)*I*x/3 + 8*sqrt(3)*I*x**2/9 + 16*sqrt(3)*I*x**3/9 + O(x**4)
2016
+ assert asec(x - S(1)/2)._eval_nseries(x, 4, None, -I) == asec(-S(1)/2) - \
2017
+ 4*sqrt(3)*I*x/3 - 8*sqrt(3)*I*x**2/9 - 16*sqrt(3)*I*x**3/9 + O(x**4)
2018
+ # testing nseries for asec at branch points
2019
+ assert asec(1 + x)._eval_nseries(x, 3, None) == sqrt(2)*sqrt(x) - \
2020
+ 5*sqrt(2)*x**(S(3)/2)/12 + 43*sqrt(2)*x**(S(5)/2)/160 + O(x**3)
2021
+ assert asec(-1 + x)._eval_nseries(x, 3, None) == pi - sqrt(2)*sqrt(-x) + \
2022
+ 5*sqrt(2)*(-x)**(S(3)/2)/12 - 43*sqrt(2)*(-x)**(S(5)/2)/160 + O(x**3)
2023
+ assert asec(exp(x))._eval_nseries(x, 3, None) == sqrt(2)*sqrt(x) - \
2024
+ sqrt(2)*x**(S(3)/2)/6 + sqrt(2)*x**(S(5)/2)/120 + O(x**3)
2025
+ assert asec(-exp(x))._eval_nseries(x, 3, None) == pi - sqrt(2)*sqrt(x) + \
2026
+ sqrt(2)*x**(S(3)/2)/6 - sqrt(2)*x**(S(5)/2)/120 + O(x**3)
2027
+
2028
+
2029
+ def test_acsc_nseries():
2030
+ assert acsc(x + S(1)/2)._eval_nseries(x, 4, None, I) == acsc(S(1)/2) + \
2031
+ 4*sqrt(3)*I*x/3 - 8*sqrt(3)*I*x**2/9 + 16*sqrt(3)*I*x**3/9 + O(x**4)
2032
+ assert acsc(x + S(1)/2)._eval_nseries(x, 4, None, -I) == -acsc(S(1)/2) + \
2033
+ pi - 4*sqrt(3)*I*x/3 + 8*sqrt(3)*I*x**2/9 - 16*sqrt(3)*I*x**3/9 + O(x**4)
2034
+ assert acsc(x - S(1)/2)._eval_nseries(x, 4, None, I) == acsc(S(1)/2) - pi -\
2035
+ 4*sqrt(3)*I*x/3 - 8*sqrt(3)*I*x**2/9 - 16*sqrt(3)*I*x**3/9 + O(x**4)
2036
+ assert acsc(x - S(1)/2)._eval_nseries(x, 4, None, -I) == -acsc(S(1)/2) + \
2037
+ 4*sqrt(3)*I*x/3 + 8*sqrt(3)*I*x**2/9 + 16*sqrt(3)*I*x**3/9 + O(x**4)
2038
+ # testing nseries for acsc at branch points
2039
+ assert acsc(1 + x)._eval_nseries(x, 3, None) == pi/2 - sqrt(2)*sqrt(x) + \
2040
+ 5*sqrt(2)*x**(S(3)/2)/12 - 43*sqrt(2)*x**(S(5)/2)/160 + O(x**3)
2041
+ assert acsc(-1 + x)._eval_nseries(x, 3, None) == -pi/2 + sqrt(2)*sqrt(-x) - \
2042
+ 5*sqrt(2)*(-x)**(S(3)/2)/12 + 43*sqrt(2)*(-x)**(S(5)/2)/160 + O(x**3)
2043
+ assert acsc(exp(x))._eval_nseries(x, 3, None) == pi/2 - sqrt(2)*sqrt(x) + \
2044
+ sqrt(2)*x**(S(3)/2)/6 - sqrt(2)*x**(S(5)/2)/120 + O(x**3)
2045
+ assert acsc(-exp(x))._eval_nseries(x, 3, None) == -pi/2 + sqrt(2)*sqrt(x) - \
2046
+ sqrt(2)*x**(S(3)/2)/6 + sqrt(2)*x**(S(5)/2)/120 + O(x**3)
2047
+
2048
+
2049
+ def test_issue_8653():
2050
+ n = Symbol('n', integer=True)
2051
+ assert sin(n).is_irrational is None
2052
+ assert cos(n).is_irrational is None
2053
+ assert tan(n).is_irrational is None
2054
+
2055
+
2056
+ def test_issue_9157():
2057
+ n = Symbol('n', integer=True, positive=True)
2058
+ assert atan(n - 1).is_nonnegative is True
2059
+
2060
+
2061
+ def test_trig_period():
2062
+ x, y = symbols('x, y')
2063
+
2064
+ assert sin(x).period() == 2*pi
2065
+ assert cos(x).period() == 2*pi
2066
+ assert tan(x).period() == pi
2067
+ assert cot(x).period() == pi
2068
+ assert sec(x).period() == 2*pi
2069
+ assert csc(x).period() == 2*pi
2070
+ assert sin(2*x).period() == pi
2071
+ assert cot(4*x - 6).period() == pi/4
2072
+ assert cos((-3)*x).period() == pi*Rational(2, 3)
2073
+ assert cos(x*y).period(x) == 2*pi/abs(y)
2074
+ assert sin(3*x*y + 2*pi).period(y) == 2*pi/abs(3*x)
2075
+ assert tan(3*x).period(y) is S.Zero
2076
+ raises(NotImplementedError, lambda: sin(x**2).period(x))
2077
+
2078
+
2079
+ def test_issue_7171():
2080
+ assert sin(x).rewrite(sqrt) == sin(x)
2081
+ assert sin(x).rewrite(pow) == sin(x)
2082
+
2083
+
2084
+ def test_issue_11864():
2085
+ w, k = symbols('w, k', real=True)
2086
+ F = Piecewise((1, Eq(2*pi*k, 0)), (sin(pi*k)/(pi*k), True))
2087
+ soln = Piecewise((1, Eq(2*pi*k, 0)), (sinc(pi*k), True))
2088
+ assert F.rewrite(sinc) == soln
2089
+
2090
+ def test_real_assumptions():
2091
+ z = Symbol('z', real=False, finite=True)
2092
+ assert sin(z).is_real is None
2093
+ assert cos(z).is_real is None
2094
+ assert tan(z).is_real is False
2095
+ assert sec(z).is_real is None
2096
+ assert csc(z).is_real is None
2097
+ assert cot(z).is_real is False
2098
+ assert asin(p).is_real is None
2099
+ assert asin(n).is_real is None
2100
+ assert asec(p).is_real is None
2101
+ assert asec(n).is_real is None
2102
+ assert acos(p).is_real is None
2103
+ assert acos(n).is_real is None
2104
+ assert acsc(p).is_real is None
2105
+ assert acsc(n).is_real is None
2106
+ assert atan(p).is_positive is True
2107
+ assert atan(n).is_negative is True
2108
+ assert acot(p).is_positive is True
2109
+ assert acot(n).is_negative is True
2110
+
2111
+ def test_issue_14320():
2112
+ assert asin(sin(2)) == -2 + pi and (-pi/2 <= -2 + pi <= pi/2) and sin(2) == sin(-2 + pi)
2113
+ assert asin(cos(2)) == -2 + pi/2 and (-pi/2 <= -2 + pi/2 <= pi/2) and cos(2) == sin(-2 + pi/2)
2114
+ assert acos(sin(2)) == -pi/2 + 2 and (0 <= -pi/2 + 2 <= pi) and sin(2) == cos(-pi/2 + 2)
2115
+ assert acos(cos(20)) == -6*pi + 20 and (0 <= -6*pi + 20 <= pi) and cos(20) == cos(-6*pi + 20)
2116
+ assert acos(cos(30)) == -30 + 10*pi and (0 <= -30 + 10*pi <= pi) and cos(30) == cos(-30 + 10*pi)
2117
+
2118
+ assert atan(tan(17)) == -5*pi + 17 and (-pi/2 < -5*pi + 17 < pi/2) and tan(17) == tan(-5*pi + 17)
2119
+ assert atan(tan(15)) == -5*pi + 15 and (-pi/2 < -5*pi + 15 < pi/2) and tan(15) == tan(-5*pi + 15)
2120
+ assert atan(cot(12)) == -12 + pi*Rational(7, 2) and (-pi/2 < -12 + pi*Rational(7, 2) < pi/2) and cot(12) == tan(-12 + pi*Rational(7, 2))
2121
+ assert acot(cot(15)) == -5*pi + 15 and (-pi/2 < -5*pi + 15 <= pi/2) and cot(15) == cot(-5*pi + 15)
2122
+ assert acot(tan(19)) == -19 + pi*Rational(13, 2) and (-pi/2 < -19 + pi*Rational(13, 2) <= pi/2) and tan(19) == cot(-19 + pi*Rational(13, 2))
2123
+
2124
+ assert asec(sec(11)) == -11 + 4*pi and (0 <= -11 + 4*pi <= pi) and cos(11) == cos(-11 + 4*pi)
2125
+ assert asec(csc(13)) == -13 + pi*Rational(9, 2) and (0 <= -13 + pi*Rational(9, 2) <= pi) and sin(13) == cos(-13 + pi*Rational(9, 2))
2126
+ assert acsc(csc(14)) == -4*pi + 14 and (-pi/2 <= -4*pi + 14 <= pi/2) and sin(14) == sin(-4*pi + 14)
2127
+ assert acsc(sec(10)) == pi*Rational(-7, 2) + 10 and (-pi/2 <= pi*Rational(-7, 2) + 10 <= pi/2) and cos(10) == sin(pi*Rational(-7, 2) + 10)
2128
+
2129
+ def test_issue_14543():
2130
+ assert sec(2*pi + 11) == sec(11)
2131
+ assert sec(2*pi - 11) == sec(11)
2132
+ assert sec(pi + 11) == -sec(11)
2133
+ assert sec(pi - 11) == -sec(11)
2134
+
2135
+ assert csc(2*pi + 17) == csc(17)
2136
+ assert csc(2*pi - 17) == -csc(17)
2137
+ assert csc(pi + 17) == -csc(17)
2138
+ assert csc(pi - 17) == csc(17)
2139
+
2140
+ x = Symbol('x')
2141
+ assert csc(pi/2 + x) == sec(x)
2142
+ assert csc(pi/2 - x) == sec(x)
2143
+ assert csc(pi*Rational(3, 2) + x) == -sec(x)
2144
+ assert csc(pi*Rational(3, 2) - x) == -sec(x)
2145
+
2146
+ assert sec(pi/2 - x) == csc(x)
2147
+ assert sec(pi/2 + x) == -csc(x)
2148
+ assert sec(pi*Rational(3, 2) + x) == csc(x)
2149
+ assert sec(pi*Rational(3, 2) - x) == -csc(x)
2150
+
2151
+
2152
+ def test_as_real_imag():
2153
+ # This is for https://github.com/sympy/sympy/issues/17142
2154
+ # If it start failing again in irrelevant builds or in the master
2155
+ # please open up the issue again.
2156
+ expr = atan(I/(I + I*tan(1)))
2157
+ assert expr.as_real_imag() == (expr, 0)
2158
+
2159
+
2160
+ def test_issue_18746():
2161
+ e3 = cos(S.Pi*(x/4 + 1/4))
2162
+ assert e3.period() == 8
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/trigonometric.py ADDED
The diff for this file is too large to render. See raw diff
 
env-llmeval/lib/python3.10/site-packages/sympy/functions/special/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Stub __init__.py for the sympy.functions.special package
env-llmeval/lib/python3.10/site-packages/sympy/functions/special/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (188 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/functions/special/__pycache__/bessel.cpython-310.pyc ADDED
Binary file (58.7 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/functions/special/__pycache__/beta_functions.cpython-310.pyc ADDED
Binary file (13.2 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/functions/special/__pycache__/elliptic_integrals.cpython-310.pyc ADDED
Binary file (14.5 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/functions/special/__pycache__/gamma_functions.cpython-310.pyc ADDED
Binary file (41.3 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/functions/special/__pycache__/mathieu_functions.cpython-310.pyc ADDED
Binary file (7.07 kB). View file