jasonfan commited on
Commit
9dc14d8
·
verified ·
1 Parent(s): 1ac6505

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. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/handlers/calculus.py +273 -0
  2. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/handlers/common.py +164 -0
  3. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/handlers/matrices.py +716 -0
  4. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/handlers/ntheory.py +279 -0
  5. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/handlers/order.py +440 -0
  6. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/handlers/sets.py +816 -0
  7. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/predicates/__init__.py +5 -0
  8. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/predicates/calculus.py +82 -0
  9. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/predicates/common.py +81 -0
  10. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/predicates/matrices.py +511 -0
  11. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/predicates/ntheory.py +126 -0
  12. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/predicates/order.py +390 -0
  13. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/predicates/sets.py +399 -0
  14. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/relation/__init__.py +13 -0
  15. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/relation/binrel.py +212 -0
  16. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/relation/equality.py +302 -0
  17. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/tests/__init__.py +0 -0
  18. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/tests/test_assumptions_2.py +35 -0
  19. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/tests/test_context.py +39 -0
  20. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/tests/test_matrices.py +283 -0
  21. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/tests/test_query.py +0 -0
  22. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/tests/test_refine.py +227 -0
  23. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/tests/test_rel_queries.py +172 -0
  24. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/tests/test_satask.py +378 -0
  25. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/tests/test_sathandlers.py +50 -0
  26. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/tests/test_wrapper.py +39 -0
  27. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/benchmarks/__init__.py +0 -0
  28. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/benchmarks/bench_discrete_log.py +83 -0
  29. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/benchmarks/bench_meijerint.py +261 -0
  30. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/benchmarks/bench_symbench.py +134 -0
  31. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/calculus/__init__.py +25 -0
  32. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/calculus/accumulationbounds.py +804 -0
  33. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/calculus/euler.py +108 -0
  34. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/calculus/finite_diff.py +476 -0
  35. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/calculus/singularities.py +406 -0
  36. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/calculus/tests/__init__.py +0 -0
  37. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/calculus/tests/test_accumulationbounds.py +336 -0
  38. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/calculus/tests/test_euler.py +74 -0
  39. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/calculus/tests/test_finite_diff.py +164 -0
  40. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/calculus/tests/test_singularities.py +122 -0
  41. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/calculus/tests/test_util.py +392 -0
  42. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/calculus/util.py +895 -0
  43. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/categories/__init__.py +33 -0
  44. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/categories/baseclasses.py +978 -0
  45. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/categories/diagram_drawing.py +2580 -0
  46. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/categories/tests/__init__.py +0 -0
  47. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/categories/tests/test_baseclasses.py +209 -0
  48. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/categories/tests/test_drawing.py +919 -0
  49. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/codegen/__init__.py +24 -0
  50. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/codegen/abstract_nodes.py +18 -0
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/handlers/calculus.py ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module contains query handlers responsible for calculus queries:
3
+ infinitesimal, finite, etc.
4
+ """
5
+
6
+ from sympy.assumptions import Q, ask
7
+ from sympy.core import Expr, Add, Mul, Pow, Symbol
8
+ from sympy.core.numbers import (NegativeInfinity, GoldenRatio,
9
+ Infinity, Exp1, ComplexInfinity, ImaginaryUnit, NaN, Number, Pi, E,
10
+ TribonacciConstant)
11
+ from sympy.functions import cos, exp, log, sign, sin
12
+ from sympy.logic.boolalg import conjuncts
13
+
14
+ from ..predicates.calculus import (FinitePredicate, InfinitePredicate,
15
+ PositiveInfinitePredicate, NegativeInfinitePredicate)
16
+
17
+
18
+ # FinitePredicate
19
+
20
+
21
+ @FinitePredicate.register(Symbol)
22
+ def _(expr, assumptions):
23
+ """
24
+ Handles Symbol.
25
+ """
26
+ if expr.is_finite is not None:
27
+ return expr.is_finite
28
+ if Q.finite(expr) in conjuncts(assumptions):
29
+ return True
30
+ return None
31
+
32
+ @FinitePredicate.register(Add)
33
+ def _(expr, assumptions):
34
+ """
35
+ Return True if expr is bounded, False if not and None if unknown.
36
+
37
+ Truth Table:
38
+
39
+ +-------+-----+-----------+-----------+
40
+ | | | | |
41
+ | | B | U | ? |
42
+ | | | | |
43
+ +-------+-----+---+---+---+---+---+---+
44
+ | | | | | | | | |
45
+ | | |'+'|'-'|'x'|'+'|'-'|'x'|
46
+ | | | | | | | | |
47
+ +-------+-----+---+---+---+---+---+---+
48
+ | | | | |
49
+ | B | B | U | ? |
50
+ | | | | |
51
+ +---+---+-----+---+---+---+---+---+---+
52
+ | | | | | | | | | |
53
+ | |'+'| | U | ? | ? | U | ? | ? |
54
+ | | | | | | | | | |
55
+ | +---+-----+---+---+---+---+---+---+
56
+ | | | | | | | | | |
57
+ | U |'-'| | ? | U | ? | ? | U | ? |
58
+ | | | | | | | | | |
59
+ | +---+-----+---+---+---+---+---+---+
60
+ | | | | | |
61
+ | |'x'| | ? | ? |
62
+ | | | | | |
63
+ +---+---+-----+---+---+---+---+---+---+
64
+ | | | | |
65
+ | ? | | | ? |
66
+ | | | | |
67
+ +-------+-----+-----------+---+---+---+
68
+
69
+ * 'B' = Bounded
70
+
71
+ * 'U' = Unbounded
72
+
73
+ * '?' = unknown boundedness
74
+
75
+ * '+' = positive sign
76
+
77
+ * '-' = negative sign
78
+
79
+ * 'x' = sign unknown
80
+
81
+ * All Bounded -> True
82
+
83
+ * 1 Unbounded and the rest Bounded -> False
84
+
85
+ * >1 Unbounded, all with same known sign -> False
86
+
87
+ * Any Unknown and unknown sign -> None
88
+
89
+ * Else -> None
90
+
91
+ When the signs are not the same you can have an undefined
92
+ result as in oo - oo, hence 'bounded' is also undefined.
93
+ """
94
+ sign = -1 # sign of unknown or infinite
95
+ result = True
96
+ for arg in expr.args:
97
+ _bounded = ask(Q.finite(arg), assumptions)
98
+ if _bounded:
99
+ continue
100
+ s = ask(Q.extended_positive(arg), assumptions)
101
+ # if there has been more than one sign or if the sign of this arg
102
+ # is None and Bounded is None or there was already
103
+ # an unknown sign, return None
104
+ if sign != -1 and s != sign or \
105
+ s is None and None in (_bounded, sign):
106
+ return None
107
+ else:
108
+ sign = s
109
+ # once False, do not change
110
+ if result is not False:
111
+ result = _bounded
112
+ return result
113
+
114
+ @FinitePredicate.register(Mul)
115
+ def _(expr, assumptions):
116
+ """
117
+ Return True if expr is bounded, False if not and None if unknown.
118
+
119
+ Truth Table:
120
+
121
+ +---+---+---+--------+
122
+ | | | | |
123
+ | | B | U | ? |
124
+ | | | | |
125
+ +---+---+---+---+----+
126
+ | | | | | |
127
+ | | | | s | /s |
128
+ | | | | | |
129
+ +---+---+---+---+----+
130
+ | | | | |
131
+ | B | B | U | ? |
132
+ | | | | |
133
+ +---+---+---+---+----+
134
+ | | | | | |
135
+ | U | | U | U | ? |
136
+ | | | | | |
137
+ +---+---+---+---+----+
138
+ | | | | |
139
+ | ? | | | ? |
140
+ | | | | |
141
+ +---+---+---+---+----+
142
+
143
+ * B = Bounded
144
+
145
+ * U = Unbounded
146
+
147
+ * ? = unknown boundedness
148
+
149
+ * s = signed (hence nonzero)
150
+
151
+ * /s = not signed
152
+ """
153
+ result = True
154
+ possible_zero = False
155
+ for arg in expr.args:
156
+ _bounded = ask(Q.finite(arg), assumptions)
157
+ if _bounded:
158
+ if ask(Q.zero(arg), assumptions) is not False:
159
+ if result is False:
160
+ return None
161
+ possible_zero = True
162
+ elif _bounded is None:
163
+ if result is None:
164
+ return None
165
+ if ask(Q.extended_nonzero(arg), assumptions) is None:
166
+ return None
167
+ if result is not False:
168
+ result = None
169
+ else:
170
+ if possible_zero:
171
+ return None
172
+ result = False
173
+ return result
174
+
175
+ @FinitePredicate.register(Pow)
176
+ def _(expr, assumptions):
177
+ """
178
+ * Unbounded ** NonZero -> Unbounded
179
+
180
+ * Bounded ** Bounded -> Bounded
181
+
182
+ * Abs()<=1 ** Positive -> Bounded
183
+
184
+ * Abs()>=1 ** Negative -> Bounded
185
+
186
+ * Otherwise unknown
187
+ """
188
+ if expr.base == E:
189
+ return ask(Q.finite(expr.exp), assumptions)
190
+
191
+ base_bounded = ask(Q.finite(expr.base), assumptions)
192
+ exp_bounded = ask(Q.finite(expr.exp), assumptions)
193
+ if base_bounded is None and exp_bounded is None: # Common Case
194
+ return None
195
+ if base_bounded is False and ask(Q.extended_nonzero(expr.exp), assumptions):
196
+ return False
197
+ if base_bounded and exp_bounded:
198
+ is_base_zero = ask(Q.zero(expr.base),assumptions)
199
+ is_exp_negative = ask(Q.negative(expr.exp),assumptions)
200
+ if is_base_zero is True and is_exp_negative is True:
201
+ return False
202
+ if is_base_zero is not False and is_exp_negative is not False:
203
+ return None
204
+ return True
205
+ if (abs(expr.base) <= 1) == True and ask(Q.extended_positive(expr.exp), assumptions):
206
+ return True
207
+ if (abs(expr.base) >= 1) == True and ask(Q.extended_negative(expr.exp), assumptions):
208
+ return True
209
+ if (abs(expr.base) >= 1) == True and exp_bounded is False:
210
+ return False
211
+ return None
212
+
213
+ @FinitePredicate.register(exp)
214
+ def _(expr, assumptions):
215
+ return ask(Q.finite(expr.exp), assumptions)
216
+
217
+ @FinitePredicate.register(log)
218
+ def _(expr, assumptions):
219
+ # After complex -> finite fact is registered to new assumption system,
220
+ # querying Q.infinite may be removed.
221
+ if ask(Q.infinite(expr.args[0]), assumptions):
222
+ return False
223
+ return ask(~Q.zero(expr.args[0]), assumptions)
224
+
225
+ @FinitePredicate.register_many(cos, sin, Number, Pi, Exp1, GoldenRatio,
226
+ TribonacciConstant, ImaginaryUnit, sign)
227
+ def _(expr, assumptions):
228
+ return True
229
+
230
+ @FinitePredicate.register_many(ComplexInfinity, Infinity, NegativeInfinity)
231
+ def _(expr, assumptions):
232
+ return False
233
+
234
+ @FinitePredicate.register(NaN)
235
+ def _(expr, assumptions):
236
+ return None
237
+
238
+
239
+ # InfinitePredicate
240
+
241
+
242
+ @InfinitePredicate.register(Expr)
243
+ def _(expr, assumptions):
244
+ is_finite = Q.finite(expr)._eval_ask(assumptions)
245
+ if is_finite is None:
246
+ return None
247
+ return not is_finite
248
+
249
+
250
+ # PositiveInfinitePredicate
251
+
252
+
253
+ @PositiveInfinitePredicate.register(Infinity)
254
+ def _(expr, assumptions):
255
+ return True
256
+
257
+
258
+ @PositiveInfinitePredicate.register_many(NegativeInfinity, ComplexInfinity)
259
+ def _(expr, assumptions):
260
+ return False
261
+
262
+
263
+ # NegativeInfinitePredicate
264
+
265
+
266
+ @NegativeInfinitePredicate.register(NegativeInfinity)
267
+ def _(expr, assumptions):
268
+ return True
269
+
270
+
271
+ @NegativeInfinitePredicate.register_many(Infinity, ComplexInfinity)
272
+ def _(expr, assumptions):
273
+ return False
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/handlers/common.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module defines base class for handlers and some core handlers:
3
+ ``Q.commutative`` and ``Q.is_true``.
4
+ """
5
+
6
+ from sympy.assumptions import Q, ask, AppliedPredicate
7
+ from sympy.core import Basic, Symbol
8
+ from sympy.core.logic import _fuzzy_group, fuzzy_and, fuzzy_or
9
+ from sympy.core.numbers import NaN, Number
10
+ from sympy.logic.boolalg import (And, BooleanTrue, BooleanFalse, conjuncts,
11
+ Equivalent, Implies, Not, Or)
12
+ from sympy.utilities.exceptions import sympy_deprecation_warning
13
+
14
+ from ..predicates.common import CommutativePredicate, IsTruePredicate
15
+
16
+
17
+ class AskHandler:
18
+ """Base class that all Ask Handlers must inherit."""
19
+ def __new__(cls, *args, **kwargs):
20
+ sympy_deprecation_warning(
21
+ """
22
+ The AskHandler system is deprecated. The AskHandler class should
23
+ be replaced with the multipledispatch handler of Predicate
24
+ """,
25
+ deprecated_since_version="1.8",
26
+ active_deprecations_target='deprecated-askhandler',
27
+ )
28
+ return super().__new__(cls, *args, **kwargs)
29
+
30
+
31
+ class CommonHandler(AskHandler):
32
+ # Deprecated
33
+ """Defines some useful methods common to most Handlers. """
34
+
35
+ @staticmethod
36
+ def AlwaysTrue(expr, assumptions):
37
+ return True
38
+
39
+ @staticmethod
40
+ def AlwaysFalse(expr, assumptions):
41
+ return False
42
+
43
+ @staticmethod
44
+ def AlwaysNone(expr, assumptions):
45
+ return None
46
+
47
+ NaN = AlwaysFalse
48
+
49
+
50
+ # CommutativePredicate
51
+
52
+ @CommutativePredicate.register(Symbol)
53
+ def _(expr, assumptions):
54
+ """Objects are expected to be commutative unless otherwise stated"""
55
+ assumps = conjuncts(assumptions)
56
+ if expr.is_commutative is not None:
57
+ return expr.is_commutative and not ~Q.commutative(expr) in assumps
58
+ if Q.commutative(expr) in assumps:
59
+ return True
60
+ elif ~Q.commutative(expr) in assumps:
61
+ return False
62
+ return True
63
+
64
+ @CommutativePredicate.register(Basic)
65
+ def _(expr, assumptions):
66
+ for arg in expr.args:
67
+ if not ask(Q.commutative(arg), assumptions):
68
+ return False
69
+ return True
70
+
71
+ @CommutativePredicate.register(Number)
72
+ def _(expr, assumptions):
73
+ return True
74
+
75
+ @CommutativePredicate.register(NaN)
76
+ def _(expr, assumptions):
77
+ return True
78
+
79
+
80
+ # IsTruePredicate
81
+
82
+ @IsTruePredicate.register(bool)
83
+ def _(expr, assumptions):
84
+ return expr
85
+
86
+ @IsTruePredicate.register(BooleanTrue)
87
+ def _(expr, assumptions):
88
+ return True
89
+
90
+ @IsTruePredicate.register(BooleanFalse)
91
+ def _(expr, assumptions):
92
+ return False
93
+
94
+ @IsTruePredicate.register(AppliedPredicate)
95
+ def _(expr, assumptions):
96
+ return ask(expr, assumptions)
97
+
98
+ @IsTruePredicate.register(Not)
99
+ def _(expr, assumptions):
100
+ arg = expr.args[0]
101
+ if arg.is_Symbol:
102
+ # symbol used as abstract boolean object
103
+ return None
104
+ value = ask(arg, assumptions=assumptions)
105
+ if value in (True, False):
106
+ return not value
107
+ else:
108
+ return None
109
+
110
+ @IsTruePredicate.register(Or)
111
+ def _(expr, assumptions):
112
+ result = False
113
+ for arg in expr.args:
114
+ p = ask(arg, assumptions=assumptions)
115
+ if p is True:
116
+ return True
117
+ if p is None:
118
+ result = None
119
+ return result
120
+
121
+ @IsTruePredicate.register(And)
122
+ def _(expr, assumptions):
123
+ result = True
124
+ for arg in expr.args:
125
+ p = ask(arg, assumptions=assumptions)
126
+ if p is False:
127
+ return False
128
+ if p is None:
129
+ result = None
130
+ return result
131
+
132
+ @IsTruePredicate.register(Implies)
133
+ def _(expr, assumptions):
134
+ p, q = expr.args
135
+ return ask(~p | q, assumptions=assumptions)
136
+
137
+ @IsTruePredicate.register(Equivalent)
138
+ def _(expr, assumptions):
139
+ p, q = expr.args
140
+ pt = ask(p, assumptions=assumptions)
141
+ if pt is None:
142
+ return None
143
+ qt = ask(q, assumptions=assumptions)
144
+ if qt is None:
145
+ return None
146
+ return pt == qt
147
+
148
+
149
+ #### Helper methods
150
+ def test_closed_group(expr, assumptions, key):
151
+ """
152
+ Test for membership in a group with respect
153
+ to the current operation.
154
+ """
155
+ return _fuzzy_group(
156
+ (ask(key(a), assumptions) for a in expr.args), quick_exit=True)
157
+
158
+ def ask_all(*queries, assumptions):
159
+ return fuzzy_and(
160
+ (ask(query, assumptions) for query in queries))
161
+
162
+ def ask_any(*queries, assumptions):
163
+ return fuzzy_or(
164
+ (ask(query, assumptions) for query in queries))
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/handlers/matrices.py ADDED
@@ -0,0 +1,716 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module contains query handlers responsible for Matrices queries:
3
+ Square, Symmetric, Invertible etc.
4
+ """
5
+
6
+ from sympy.logic.boolalg import conjuncts
7
+ from sympy.assumptions import Q, ask
8
+ from sympy.assumptions.handlers import test_closed_group
9
+ from sympy.matrices import MatrixBase
10
+ from sympy.matrices.expressions import (BlockMatrix, BlockDiagMatrix, Determinant,
11
+ DiagMatrix, DiagonalMatrix, HadamardProduct, Identity, Inverse, MatAdd, MatMul,
12
+ MatPow, MatrixExpr, MatrixSlice, MatrixSymbol, OneMatrix, Trace, Transpose,
13
+ ZeroMatrix)
14
+ from sympy.matrices.expressions.blockmatrix import reblock_2x2
15
+ from sympy.matrices.expressions.factorizations import Factorization
16
+ from sympy.matrices.expressions.fourier import DFT
17
+ from sympy.core.logic import fuzzy_and
18
+ from sympy.utilities.iterables import sift
19
+ from sympy.core import Basic
20
+
21
+ from ..predicates.matrices import (SquarePredicate, SymmetricPredicate,
22
+ InvertiblePredicate, OrthogonalPredicate, UnitaryPredicate,
23
+ FullRankPredicate, PositiveDefinitePredicate, UpperTriangularPredicate,
24
+ LowerTriangularPredicate, DiagonalPredicate, IntegerElementsPredicate,
25
+ RealElementsPredicate, ComplexElementsPredicate)
26
+
27
+
28
+ def _Factorization(predicate, expr, assumptions):
29
+ if predicate in expr.predicates:
30
+ return True
31
+
32
+
33
+ # SquarePredicate
34
+
35
+ @SquarePredicate.register(MatrixExpr)
36
+ def _(expr, assumptions):
37
+ return expr.shape[0] == expr.shape[1]
38
+
39
+
40
+ # SymmetricPredicate
41
+
42
+ @SymmetricPredicate.register(MatMul)
43
+ def _(expr, assumptions):
44
+ factor, mmul = expr.as_coeff_mmul()
45
+ if all(ask(Q.symmetric(arg), assumptions) for arg in mmul.args):
46
+ return True
47
+ # TODO: implement sathandlers system for the matrices.
48
+ # Now it duplicates the general fact: Implies(Q.diagonal, Q.symmetric).
49
+ if ask(Q.diagonal(expr), assumptions):
50
+ return True
51
+ if len(mmul.args) >= 2 and mmul.args[0] == mmul.args[-1].T:
52
+ if len(mmul.args) == 2:
53
+ return True
54
+ return ask(Q.symmetric(MatMul(*mmul.args[1:-1])), assumptions)
55
+
56
+ @SymmetricPredicate.register(MatPow)
57
+ def _(expr, assumptions):
58
+ # only for integer powers
59
+ base, exp = expr.args
60
+ int_exp = ask(Q.integer(exp), assumptions)
61
+ if not int_exp:
62
+ return None
63
+ non_negative = ask(~Q.negative(exp), assumptions)
64
+ if (non_negative or non_negative == False
65
+ and ask(Q.invertible(base), assumptions)):
66
+ return ask(Q.symmetric(base), assumptions)
67
+ return None
68
+
69
+ @SymmetricPredicate.register(MatAdd)
70
+ def _(expr, assumptions):
71
+ return all(ask(Q.symmetric(arg), assumptions) for arg in expr.args)
72
+
73
+ @SymmetricPredicate.register(MatrixSymbol)
74
+ def _(expr, assumptions):
75
+ if not expr.is_square:
76
+ return False
77
+ # TODO: implement sathandlers system for the matrices.
78
+ # Now it duplicates the general fact: Implies(Q.diagonal, Q.symmetric).
79
+ if ask(Q.diagonal(expr), assumptions):
80
+ return True
81
+ if Q.symmetric(expr) in conjuncts(assumptions):
82
+ return True
83
+
84
+ @SymmetricPredicate.register_many(OneMatrix, ZeroMatrix)
85
+ def _(expr, assumptions):
86
+ return ask(Q.square(expr), assumptions)
87
+
88
+ @SymmetricPredicate.register_many(Inverse, Transpose)
89
+ def _(expr, assumptions):
90
+ return ask(Q.symmetric(expr.arg), assumptions)
91
+
92
+ @SymmetricPredicate.register(MatrixSlice)
93
+ def _(expr, assumptions):
94
+ # TODO: implement sathandlers system for the matrices.
95
+ # Now it duplicates the general fact: Implies(Q.diagonal, Q.symmetric).
96
+ if ask(Q.diagonal(expr), assumptions):
97
+ return True
98
+ if not expr.on_diag:
99
+ return None
100
+ else:
101
+ return ask(Q.symmetric(expr.parent), assumptions)
102
+
103
+ @SymmetricPredicate.register(Identity)
104
+ def _(expr, assumptions):
105
+ return True
106
+
107
+
108
+ # InvertiblePredicate
109
+
110
+ @InvertiblePredicate.register(MatMul)
111
+ def _(expr, assumptions):
112
+ factor, mmul = expr.as_coeff_mmul()
113
+ if all(ask(Q.invertible(arg), assumptions) for arg in mmul.args):
114
+ return True
115
+ if any(ask(Q.invertible(arg), assumptions) is False
116
+ for arg in mmul.args):
117
+ return False
118
+
119
+ @InvertiblePredicate.register(MatPow)
120
+ def _(expr, assumptions):
121
+ # only for integer powers
122
+ base, exp = expr.args
123
+ int_exp = ask(Q.integer(exp), assumptions)
124
+ if not int_exp:
125
+ return None
126
+ if exp.is_negative == False:
127
+ return ask(Q.invertible(base), assumptions)
128
+ return None
129
+
130
+ @InvertiblePredicate.register(MatAdd)
131
+ def _(expr, assumptions):
132
+ return None
133
+
134
+ @InvertiblePredicate.register(MatrixSymbol)
135
+ def _(expr, assumptions):
136
+ if not expr.is_square:
137
+ return False
138
+ if Q.invertible(expr) in conjuncts(assumptions):
139
+ return True
140
+
141
+ @InvertiblePredicate.register_many(Identity, Inverse)
142
+ def _(expr, assumptions):
143
+ return True
144
+
145
+ @InvertiblePredicate.register(ZeroMatrix)
146
+ def _(expr, assumptions):
147
+ return False
148
+
149
+ @InvertiblePredicate.register(OneMatrix)
150
+ def _(expr, assumptions):
151
+ return expr.shape[0] == 1 and expr.shape[1] == 1
152
+
153
+ @InvertiblePredicate.register(Transpose)
154
+ def _(expr, assumptions):
155
+ return ask(Q.invertible(expr.arg), assumptions)
156
+
157
+ @InvertiblePredicate.register(MatrixSlice)
158
+ def _(expr, assumptions):
159
+ if not expr.on_diag:
160
+ return None
161
+ else:
162
+ return ask(Q.invertible(expr.parent), assumptions)
163
+
164
+ @InvertiblePredicate.register(MatrixBase)
165
+ def _(expr, assumptions):
166
+ if not expr.is_square:
167
+ return False
168
+ return expr.rank() == expr.rows
169
+
170
+ @InvertiblePredicate.register(MatrixExpr)
171
+ def _(expr, assumptions):
172
+ if not expr.is_square:
173
+ return False
174
+ return None
175
+
176
+ @InvertiblePredicate.register(BlockMatrix)
177
+ def _(expr, assumptions):
178
+ if not expr.is_square:
179
+ return False
180
+ if expr.blockshape == (1, 1):
181
+ return ask(Q.invertible(expr.blocks[0, 0]), assumptions)
182
+ expr = reblock_2x2(expr)
183
+ if expr.blockshape == (2, 2):
184
+ [[A, B], [C, D]] = expr.blocks.tolist()
185
+ if ask(Q.invertible(A), assumptions) == True:
186
+ invertible = ask(Q.invertible(D - C * A.I * B), assumptions)
187
+ if invertible is not None:
188
+ return invertible
189
+ if ask(Q.invertible(B), assumptions) == True:
190
+ invertible = ask(Q.invertible(C - D * B.I * A), assumptions)
191
+ if invertible is not None:
192
+ return invertible
193
+ if ask(Q.invertible(C), assumptions) == True:
194
+ invertible = ask(Q.invertible(B - A * C.I * D), assumptions)
195
+ if invertible is not None:
196
+ return invertible
197
+ if ask(Q.invertible(D), assumptions) == True:
198
+ invertible = ask(Q.invertible(A - B * D.I * C), assumptions)
199
+ if invertible is not None:
200
+ return invertible
201
+ return None
202
+
203
+ @InvertiblePredicate.register(BlockDiagMatrix)
204
+ def _(expr, assumptions):
205
+ if expr.rowblocksizes != expr.colblocksizes:
206
+ return None
207
+ return fuzzy_and([ask(Q.invertible(a), assumptions) for a in expr.diag])
208
+
209
+
210
+ # OrthogonalPredicate
211
+
212
+ @OrthogonalPredicate.register(MatMul)
213
+ def _(expr, assumptions):
214
+ factor, mmul = expr.as_coeff_mmul()
215
+ if (all(ask(Q.orthogonal(arg), assumptions) for arg in mmul.args) and
216
+ factor == 1):
217
+ return True
218
+ if any(ask(Q.invertible(arg), assumptions) is False
219
+ for arg in mmul.args):
220
+ return False
221
+
222
+ @OrthogonalPredicate.register(MatPow)
223
+ def _(expr, assumptions):
224
+ # only for integer powers
225
+ base, exp = expr.args
226
+ int_exp = ask(Q.integer(exp), assumptions)
227
+ if int_exp:
228
+ return ask(Q.orthogonal(base), assumptions)
229
+ return None
230
+
231
+ @OrthogonalPredicate.register(MatAdd)
232
+ def _(expr, assumptions):
233
+ if (len(expr.args) == 1 and
234
+ ask(Q.orthogonal(expr.args[0]), assumptions)):
235
+ return True
236
+
237
+ @OrthogonalPredicate.register(MatrixSymbol)
238
+ def _(expr, assumptions):
239
+ if (not expr.is_square or
240
+ ask(Q.invertible(expr), assumptions) is False):
241
+ return False
242
+ if Q.orthogonal(expr) in conjuncts(assumptions):
243
+ return True
244
+
245
+ @OrthogonalPredicate.register(Identity)
246
+ def _(expr, assumptions):
247
+ return True
248
+
249
+ @OrthogonalPredicate.register(ZeroMatrix)
250
+ def _(expr, assumptions):
251
+ return False
252
+
253
+ @OrthogonalPredicate.register_many(Inverse, Transpose)
254
+ def _(expr, assumptions):
255
+ return ask(Q.orthogonal(expr.arg), assumptions)
256
+
257
+ @OrthogonalPredicate.register(MatrixSlice)
258
+ def _(expr, assumptions):
259
+ if not expr.on_diag:
260
+ return None
261
+ else:
262
+ return ask(Q.orthogonal(expr.parent), assumptions)
263
+
264
+ @OrthogonalPredicate.register(Factorization)
265
+ def _(expr, assumptions):
266
+ return _Factorization(Q.orthogonal, expr, assumptions)
267
+
268
+
269
+ # UnitaryPredicate
270
+
271
+ @UnitaryPredicate.register(MatMul)
272
+ def _(expr, assumptions):
273
+ factor, mmul = expr.as_coeff_mmul()
274
+ if (all(ask(Q.unitary(arg), assumptions) for arg in mmul.args) and
275
+ abs(factor) == 1):
276
+ return True
277
+ if any(ask(Q.invertible(arg), assumptions) is False
278
+ for arg in mmul.args):
279
+ return False
280
+
281
+ @UnitaryPredicate.register(MatPow)
282
+ def _(expr, assumptions):
283
+ # only for integer powers
284
+ base, exp = expr.args
285
+ int_exp = ask(Q.integer(exp), assumptions)
286
+ if int_exp:
287
+ return ask(Q.unitary(base), assumptions)
288
+ return None
289
+
290
+ @UnitaryPredicate.register(MatrixSymbol)
291
+ def _(expr, assumptions):
292
+ if (not expr.is_square or
293
+ ask(Q.invertible(expr), assumptions) is False):
294
+ return False
295
+ if Q.unitary(expr) in conjuncts(assumptions):
296
+ return True
297
+
298
+ @UnitaryPredicate.register_many(Inverse, Transpose)
299
+ def _(expr, assumptions):
300
+ return ask(Q.unitary(expr.arg), assumptions)
301
+
302
+ @UnitaryPredicate.register(MatrixSlice)
303
+ def _(expr, assumptions):
304
+ if not expr.on_diag:
305
+ return None
306
+ else:
307
+ return ask(Q.unitary(expr.parent), assumptions)
308
+
309
+ @UnitaryPredicate.register_many(DFT, Identity)
310
+ def _(expr, assumptions):
311
+ return True
312
+
313
+ @UnitaryPredicate.register(ZeroMatrix)
314
+ def _(expr, assumptions):
315
+ return False
316
+
317
+ @UnitaryPredicate.register(Factorization)
318
+ def _(expr, assumptions):
319
+ return _Factorization(Q.unitary, expr, assumptions)
320
+
321
+
322
+ # FullRankPredicate
323
+
324
+ @FullRankPredicate.register(MatMul)
325
+ def _(expr, assumptions):
326
+ if all(ask(Q.fullrank(arg), assumptions) for arg in expr.args):
327
+ return True
328
+
329
+ @FullRankPredicate.register(MatPow)
330
+ def _(expr, assumptions):
331
+ # only for integer powers
332
+ base, exp = expr.args
333
+ int_exp = ask(Q.integer(exp), assumptions)
334
+ if int_exp and ask(~Q.negative(exp), assumptions):
335
+ return ask(Q.fullrank(base), assumptions)
336
+ return None
337
+
338
+ @FullRankPredicate.register(Identity)
339
+ def _(expr, assumptions):
340
+ return True
341
+
342
+ @FullRankPredicate.register(ZeroMatrix)
343
+ def _(expr, assumptions):
344
+ return False
345
+
346
+ @FullRankPredicate.register(OneMatrix)
347
+ def _(expr, assumptions):
348
+ return expr.shape[0] == 1 and expr.shape[1] == 1
349
+
350
+ @FullRankPredicate.register_many(Inverse, Transpose)
351
+ def _(expr, assumptions):
352
+ return ask(Q.fullrank(expr.arg), assumptions)
353
+
354
+ @FullRankPredicate.register(MatrixSlice)
355
+ def _(expr, assumptions):
356
+ if ask(Q.orthogonal(expr.parent), assumptions):
357
+ return True
358
+
359
+
360
+ # PositiveDefinitePredicate
361
+
362
+ @PositiveDefinitePredicate.register(MatMul)
363
+ def _(expr, assumptions):
364
+ factor, mmul = expr.as_coeff_mmul()
365
+ if (all(ask(Q.positive_definite(arg), assumptions)
366
+ for arg in mmul.args) and factor > 0):
367
+ return True
368
+ if (len(mmul.args) >= 2
369
+ and mmul.args[0] == mmul.args[-1].T
370
+ and ask(Q.fullrank(mmul.args[0]), assumptions)):
371
+ return ask(Q.positive_definite(
372
+ MatMul(*mmul.args[1:-1])), assumptions)
373
+
374
+ @PositiveDefinitePredicate.register(MatPow)
375
+ def _(expr, assumptions):
376
+ # a power of a positive definite matrix is positive definite
377
+ if ask(Q.positive_definite(expr.args[0]), assumptions):
378
+ return True
379
+
380
+ @PositiveDefinitePredicate.register(MatAdd)
381
+ def _(expr, assumptions):
382
+ if all(ask(Q.positive_definite(arg), assumptions)
383
+ for arg in expr.args):
384
+ return True
385
+
386
+ @PositiveDefinitePredicate.register(MatrixSymbol)
387
+ def _(expr, assumptions):
388
+ if not expr.is_square:
389
+ return False
390
+ if Q.positive_definite(expr) in conjuncts(assumptions):
391
+ return True
392
+
393
+ @PositiveDefinitePredicate.register(Identity)
394
+ def _(expr, assumptions):
395
+ return True
396
+
397
+ @PositiveDefinitePredicate.register(ZeroMatrix)
398
+ def _(expr, assumptions):
399
+ return False
400
+
401
+ @PositiveDefinitePredicate.register(OneMatrix)
402
+ def _(expr, assumptions):
403
+ return expr.shape[0] == 1 and expr.shape[1] == 1
404
+
405
+ @PositiveDefinitePredicate.register_many(Inverse, Transpose)
406
+ def _(expr, assumptions):
407
+ return ask(Q.positive_definite(expr.arg), assumptions)
408
+
409
+ @PositiveDefinitePredicate.register(MatrixSlice)
410
+ def _(expr, assumptions):
411
+ if not expr.on_diag:
412
+ return None
413
+ else:
414
+ return ask(Q.positive_definite(expr.parent), assumptions)
415
+
416
+
417
+ # UpperTriangularPredicate
418
+
419
+ @UpperTriangularPredicate.register(MatMul)
420
+ def _(expr, assumptions):
421
+ factor, matrices = expr.as_coeff_matrices()
422
+ if all(ask(Q.upper_triangular(m), assumptions) for m in matrices):
423
+ return True
424
+
425
+ @UpperTriangularPredicate.register(MatAdd)
426
+ def _(expr, assumptions):
427
+ if all(ask(Q.upper_triangular(arg), assumptions) for arg in expr.args):
428
+ return True
429
+
430
+ @UpperTriangularPredicate.register(MatPow)
431
+ def _(expr, assumptions):
432
+ # only for integer powers
433
+ base, exp = expr.args
434
+ int_exp = ask(Q.integer(exp), assumptions)
435
+ if not int_exp:
436
+ return None
437
+ non_negative = ask(~Q.negative(exp), assumptions)
438
+ if (non_negative or non_negative == False
439
+ and ask(Q.invertible(base), assumptions)):
440
+ return ask(Q.upper_triangular(base), assumptions)
441
+ return None
442
+
443
+ @UpperTriangularPredicate.register(MatrixSymbol)
444
+ def _(expr, assumptions):
445
+ if Q.upper_triangular(expr) in conjuncts(assumptions):
446
+ return True
447
+
448
+ @UpperTriangularPredicate.register_many(Identity, ZeroMatrix)
449
+ def _(expr, assumptions):
450
+ return True
451
+
452
+ @UpperTriangularPredicate.register(OneMatrix)
453
+ def _(expr, assumptions):
454
+ return expr.shape[0] == 1 and expr.shape[1] == 1
455
+
456
+ @UpperTriangularPredicate.register(Transpose)
457
+ def _(expr, assumptions):
458
+ return ask(Q.lower_triangular(expr.arg), assumptions)
459
+
460
+ @UpperTriangularPredicate.register(Inverse)
461
+ def _(expr, assumptions):
462
+ return ask(Q.upper_triangular(expr.arg), assumptions)
463
+
464
+ @UpperTriangularPredicate.register(MatrixSlice)
465
+ def _(expr, assumptions):
466
+ if not expr.on_diag:
467
+ return None
468
+ else:
469
+ return ask(Q.upper_triangular(expr.parent), assumptions)
470
+
471
+ @UpperTriangularPredicate.register(Factorization)
472
+ def _(expr, assumptions):
473
+ return _Factorization(Q.upper_triangular, expr, assumptions)
474
+
475
+ # LowerTriangularPredicate
476
+
477
+ @LowerTriangularPredicate.register(MatMul)
478
+ def _(expr, assumptions):
479
+ factor, matrices = expr.as_coeff_matrices()
480
+ if all(ask(Q.lower_triangular(m), assumptions) for m in matrices):
481
+ return True
482
+
483
+ @LowerTriangularPredicate.register(MatAdd)
484
+ def _(expr, assumptions):
485
+ if all(ask(Q.lower_triangular(arg), assumptions) for arg in expr.args):
486
+ return True
487
+
488
+ @LowerTriangularPredicate.register(MatPow)
489
+ def _(expr, assumptions):
490
+ # only for integer powers
491
+ base, exp = expr.args
492
+ int_exp = ask(Q.integer(exp), assumptions)
493
+ if not int_exp:
494
+ return None
495
+ non_negative = ask(~Q.negative(exp), assumptions)
496
+ if (non_negative or non_negative == False
497
+ and ask(Q.invertible(base), assumptions)):
498
+ return ask(Q.lower_triangular(base), assumptions)
499
+ return None
500
+
501
+ @LowerTriangularPredicate.register(MatrixSymbol)
502
+ def _(expr, assumptions):
503
+ if Q.lower_triangular(expr) in conjuncts(assumptions):
504
+ return True
505
+
506
+ @LowerTriangularPredicate.register_many(Identity, ZeroMatrix)
507
+ def _(expr, assumptions):
508
+ return True
509
+
510
+ @LowerTriangularPredicate.register(OneMatrix)
511
+ def _(expr, assumptions):
512
+ return expr.shape[0] == 1 and expr.shape[1] == 1
513
+
514
+ @LowerTriangularPredicate.register(Transpose)
515
+ def _(expr, assumptions):
516
+ return ask(Q.upper_triangular(expr.arg), assumptions)
517
+
518
+ @LowerTriangularPredicate.register(Inverse)
519
+ def _(expr, assumptions):
520
+ return ask(Q.lower_triangular(expr.arg), assumptions)
521
+
522
+ @LowerTriangularPredicate.register(MatrixSlice)
523
+ def _(expr, assumptions):
524
+ if not expr.on_diag:
525
+ return None
526
+ else:
527
+ return ask(Q.lower_triangular(expr.parent), assumptions)
528
+
529
+ @LowerTriangularPredicate.register(Factorization)
530
+ def _(expr, assumptions):
531
+ return _Factorization(Q.lower_triangular, expr, assumptions)
532
+
533
+
534
+ # DiagonalPredicate
535
+
536
+ def _is_empty_or_1x1(expr):
537
+ return expr.shape in ((0, 0), (1, 1))
538
+
539
+ @DiagonalPredicate.register(MatMul)
540
+ def _(expr, assumptions):
541
+ if _is_empty_or_1x1(expr):
542
+ return True
543
+ factor, matrices = expr.as_coeff_matrices()
544
+ if all(ask(Q.diagonal(m), assumptions) for m in matrices):
545
+ return True
546
+
547
+ @DiagonalPredicate.register(MatPow)
548
+ def _(expr, assumptions):
549
+ # only for integer powers
550
+ base, exp = expr.args
551
+ int_exp = ask(Q.integer(exp), assumptions)
552
+ if not int_exp:
553
+ return None
554
+ non_negative = ask(~Q.negative(exp), assumptions)
555
+ if (non_negative or non_negative == False
556
+ and ask(Q.invertible(base), assumptions)):
557
+ return ask(Q.diagonal(base), assumptions)
558
+ return None
559
+
560
+ @DiagonalPredicate.register(MatAdd)
561
+ def _(expr, assumptions):
562
+ if all(ask(Q.diagonal(arg), assumptions) for arg in expr.args):
563
+ return True
564
+
565
+ @DiagonalPredicate.register(MatrixSymbol)
566
+ def _(expr, assumptions):
567
+ if _is_empty_or_1x1(expr):
568
+ return True
569
+ if Q.diagonal(expr) in conjuncts(assumptions):
570
+ return True
571
+
572
+ @DiagonalPredicate.register(OneMatrix)
573
+ def _(expr, assumptions):
574
+ return expr.shape[0] == 1 and expr.shape[1] == 1
575
+
576
+ @DiagonalPredicate.register_many(Inverse, Transpose)
577
+ def _(expr, assumptions):
578
+ return ask(Q.diagonal(expr.arg), assumptions)
579
+
580
+ @DiagonalPredicate.register(MatrixSlice)
581
+ def _(expr, assumptions):
582
+ if _is_empty_or_1x1(expr):
583
+ return True
584
+ if not expr.on_diag:
585
+ return None
586
+ else:
587
+ return ask(Q.diagonal(expr.parent), assumptions)
588
+
589
+ @DiagonalPredicate.register_many(DiagonalMatrix, DiagMatrix, Identity, ZeroMatrix)
590
+ def _(expr, assumptions):
591
+ return True
592
+
593
+ @DiagonalPredicate.register(Factorization)
594
+ def _(expr, assumptions):
595
+ return _Factorization(Q.diagonal, expr, assumptions)
596
+
597
+
598
+ # IntegerElementsPredicate
599
+
600
+ def BM_elements(predicate, expr, assumptions):
601
+ """ Block Matrix elements. """
602
+ return all(ask(predicate(b), assumptions) for b in expr.blocks)
603
+
604
+ def MS_elements(predicate, expr, assumptions):
605
+ """ Matrix Slice elements. """
606
+ return ask(predicate(expr.parent), assumptions)
607
+
608
+ def MatMul_elements(matrix_predicate, scalar_predicate, expr, assumptions):
609
+ d = sift(expr.args, lambda x: isinstance(x, MatrixExpr))
610
+ factors, matrices = d[False], d[True]
611
+ return fuzzy_and([
612
+ test_closed_group(Basic(*factors), assumptions, scalar_predicate),
613
+ test_closed_group(Basic(*matrices), assumptions, matrix_predicate)])
614
+
615
+
616
+ @IntegerElementsPredicate.register_many(Determinant, HadamardProduct, MatAdd,
617
+ Trace, Transpose)
618
+ def _(expr, assumptions):
619
+ return test_closed_group(expr, assumptions, Q.integer_elements)
620
+
621
+ @IntegerElementsPredicate.register(MatPow)
622
+ def _(expr, assumptions):
623
+ # only for integer powers
624
+ base, exp = expr.args
625
+ int_exp = ask(Q.integer(exp), assumptions)
626
+ if not int_exp:
627
+ return None
628
+ if exp.is_negative == False:
629
+ return ask(Q.integer_elements(base), assumptions)
630
+ return None
631
+
632
+ @IntegerElementsPredicate.register_many(Identity, OneMatrix, ZeroMatrix)
633
+ def _(expr, assumptions):
634
+ return True
635
+
636
+ @IntegerElementsPredicate.register(MatMul)
637
+ def _(expr, assumptions):
638
+ return MatMul_elements(Q.integer_elements, Q.integer, expr, assumptions)
639
+
640
+ @IntegerElementsPredicate.register(MatrixSlice)
641
+ def _(expr, assumptions):
642
+ return MS_elements(Q.integer_elements, expr, assumptions)
643
+
644
+ @IntegerElementsPredicate.register(BlockMatrix)
645
+ def _(expr, assumptions):
646
+ return BM_elements(Q.integer_elements, expr, assumptions)
647
+
648
+
649
+ # RealElementsPredicate
650
+
651
+ @RealElementsPredicate.register_many(Determinant, Factorization, HadamardProduct,
652
+ MatAdd, Trace, Transpose)
653
+ def _(expr, assumptions):
654
+ return test_closed_group(expr, assumptions, Q.real_elements)
655
+
656
+ @RealElementsPredicate.register(MatPow)
657
+ def _(expr, assumptions):
658
+ # only for integer powers
659
+ base, exp = expr.args
660
+ int_exp = ask(Q.integer(exp), assumptions)
661
+ if not int_exp:
662
+ return None
663
+ non_negative = ask(~Q.negative(exp), assumptions)
664
+ if (non_negative or non_negative == False
665
+ and ask(Q.invertible(base), assumptions)):
666
+ return ask(Q.real_elements(base), assumptions)
667
+ return None
668
+
669
+ @RealElementsPredicate.register(MatMul)
670
+ def _(expr, assumptions):
671
+ return MatMul_elements(Q.real_elements, Q.real, expr, assumptions)
672
+
673
+ @RealElementsPredicate.register(MatrixSlice)
674
+ def _(expr, assumptions):
675
+ return MS_elements(Q.real_elements, expr, assumptions)
676
+
677
+ @RealElementsPredicate.register(BlockMatrix)
678
+ def _(expr, assumptions):
679
+ return BM_elements(Q.real_elements, expr, assumptions)
680
+
681
+
682
+ # ComplexElementsPredicate
683
+
684
+ @ComplexElementsPredicate.register_many(Determinant, Factorization, HadamardProduct,
685
+ Inverse, MatAdd, Trace, Transpose)
686
+ def _(expr, assumptions):
687
+ return test_closed_group(expr, assumptions, Q.complex_elements)
688
+
689
+ @ComplexElementsPredicate.register(MatPow)
690
+ def _(expr, assumptions):
691
+ # only for integer powers
692
+ base, exp = expr.args
693
+ int_exp = ask(Q.integer(exp), assumptions)
694
+ if not int_exp:
695
+ return None
696
+ non_negative = ask(~Q.negative(exp), assumptions)
697
+ if (non_negative or non_negative == False
698
+ and ask(Q.invertible(base), assumptions)):
699
+ return ask(Q.complex_elements(base), assumptions)
700
+ return None
701
+
702
+ @ComplexElementsPredicate.register(MatMul)
703
+ def _(expr, assumptions):
704
+ return MatMul_elements(Q.complex_elements, Q.complex, expr, assumptions)
705
+
706
+ @ComplexElementsPredicate.register(MatrixSlice)
707
+ def _(expr, assumptions):
708
+ return MS_elements(Q.complex_elements, expr, assumptions)
709
+
710
+ @ComplexElementsPredicate.register(BlockMatrix)
711
+ def _(expr, assumptions):
712
+ return BM_elements(Q.complex_elements, expr, assumptions)
713
+
714
+ @ComplexElementsPredicate.register(DFT)
715
+ def _(expr, assumptions):
716
+ return True
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/handlers/ntheory.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Handlers for keys related to number theory: prime, even, odd, etc.
3
+ """
4
+
5
+ from sympy.assumptions import Q, ask
6
+ from sympy.core import Add, Basic, Expr, Float, Mul, Pow, S
7
+ from sympy.core.numbers import (ImaginaryUnit, Infinity, Integer, NaN,
8
+ NegativeInfinity, NumberSymbol, Rational, int_valued)
9
+ from sympy.functions import Abs, im, re
10
+ from sympy.ntheory import isprime
11
+
12
+ from sympy.multipledispatch import MDNotImplementedError
13
+
14
+ from ..predicates.ntheory import (PrimePredicate, CompositePredicate,
15
+ EvenPredicate, OddPredicate)
16
+
17
+
18
+ # PrimePredicate
19
+
20
+ def _PrimePredicate_number(expr, assumptions):
21
+ # helper method
22
+ exact = not expr.atoms(Float)
23
+ try:
24
+ i = int(expr.round())
25
+ if (expr - i).equals(0) is False:
26
+ raise TypeError
27
+ except TypeError:
28
+ return False
29
+ if exact:
30
+ return isprime(i)
31
+ # when not exact, we won't give a True or False
32
+ # since the number represents an approximate value
33
+
34
+ @PrimePredicate.register(Expr)
35
+ def _(expr, assumptions):
36
+ ret = expr.is_prime
37
+ if ret is None:
38
+ raise MDNotImplementedError
39
+ return ret
40
+
41
+ @PrimePredicate.register(Basic)
42
+ def _(expr, assumptions):
43
+ if expr.is_number:
44
+ return _PrimePredicate_number(expr, assumptions)
45
+
46
+ @PrimePredicate.register(Mul)
47
+ def _(expr, assumptions):
48
+ if expr.is_number:
49
+ return _PrimePredicate_number(expr, assumptions)
50
+ for arg in expr.args:
51
+ if not ask(Q.integer(arg), assumptions):
52
+ return None
53
+ for arg in expr.args:
54
+ if arg.is_number and arg.is_composite:
55
+ return False
56
+
57
+ @PrimePredicate.register(Pow)
58
+ def _(expr, assumptions):
59
+ """
60
+ Integer**Integer -> !Prime
61
+ """
62
+ if expr.is_number:
63
+ return _PrimePredicate_number(expr, assumptions)
64
+ if ask(Q.integer(expr.exp), assumptions) and \
65
+ ask(Q.integer(expr.base), assumptions):
66
+ prime_base = ask(Q.prime(expr.base), assumptions)
67
+ if prime_base is False:
68
+ return False
69
+ is_exp_one = ask(Q.eq(expr.exp, 1), assumptions)
70
+ if is_exp_one is False:
71
+ return False
72
+ if prime_base is True and is_exp_one is True:
73
+ return True
74
+
75
+ @PrimePredicate.register(Integer)
76
+ def _(expr, assumptions):
77
+ return isprime(expr)
78
+
79
+ @PrimePredicate.register_many(Rational, Infinity, NegativeInfinity, ImaginaryUnit)
80
+ def _(expr, assumptions):
81
+ return False
82
+
83
+ @PrimePredicate.register(Float)
84
+ def _(expr, assumptions):
85
+ return _PrimePredicate_number(expr, assumptions)
86
+
87
+ @PrimePredicate.register(NumberSymbol)
88
+ def _(expr, assumptions):
89
+ return _PrimePredicate_number(expr, assumptions)
90
+
91
+ @PrimePredicate.register(NaN)
92
+ def _(expr, assumptions):
93
+ return None
94
+
95
+
96
+ # CompositePredicate
97
+
98
+ @CompositePredicate.register(Expr)
99
+ def _(expr, assumptions):
100
+ ret = expr.is_composite
101
+ if ret is None:
102
+ raise MDNotImplementedError
103
+ return ret
104
+
105
+ @CompositePredicate.register(Basic)
106
+ def _(expr, assumptions):
107
+ _positive = ask(Q.positive(expr), assumptions)
108
+ if _positive:
109
+ _integer = ask(Q.integer(expr), assumptions)
110
+ if _integer:
111
+ _prime = ask(Q.prime(expr), assumptions)
112
+ if _prime is None:
113
+ return
114
+ # Positive integer which is not prime is not
115
+ # necessarily composite
116
+ _is_one = ask(Q.eq(expr, 1), assumptions)
117
+ if _is_one:
118
+ return False
119
+ if _is_one is None:
120
+ return None
121
+ return not _prime
122
+ else:
123
+ return _integer
124
+ else:
125
+ return _positive
126
+
127
+
128
+ # EvenPredicate
129
+
130
+ def _EvenPredicate_number(expr, assumptions):
131
+ # helper method
132
+ if isinstance(expr, (float, Float)):
133
+ if int_valued(expr):
134
+ return None
135
+ return False
136
+ try:
137
+ i = int(expr.round())
138
+ except TypeError:
139
+ return False
140
+ if not (expr - i).equals(0):
141
+ return False
142
+ return i % 2 == 0
143
+
144
+ @EvenPredicate.register(Expr)
145
+ def _(expr, assumptions):
146
+ ret = expr.is_even
147
+ if ret is None:
148
+ raise MDNotImplementedError
149
+ return ret
150
+
151
+ @EvenPredicate.register(Basic)
152
+ def _(expr, assumptions):
153
+ if expr.is_number:
154
+ return _EvenPredicate_number(expr, assumptions)
155
+
156
+ @EvenPredicate.register(Mul)
157
+ def _(expr, assumptions):
158
+ """
159
+ Even * Integer -> Even
160
+ Even * Odd -> Even
161
+ Integer * Odd -> ?
162
+ Odd * Odd -> Odd
163
+ Even * Even -> Even
164
+ Integer * Integer -> Even if Integer + Integer = Odd
165
+ otherwise -> ?
166
+ """
167
+ if expr.is_number:
168
+ return _EvenPredicate_number(expr, assumptions)
169
+ even, odd, irrational, acc = False, 0, False, 1
170
+ for arg in expr.args:
171
+ # check for all integers and at least one even
172
+ if ask(Q.integer(arg), assumptions):
173
+ if ask(Q.even(arg), assumptions):
174
+ even = True
175
+ elif ask(Q.odd(arg), assumptions):
176
+ odd += 1
177
+ elif not even and acc != 1:
178
+ if ask(Q.odd(acc + arg), assumptions):
179
+ even = True
180
+ elif ask(Q.irrational(arg), assumptions):
181
+ # one irrational makes the result False
182
+ # two makes it undefined
183
+ if irrational:
184
+ break
185
+ irrational = True
186
+ else:
187
+ break
188
+ acc = arg
189
+ else:
190
+ if irrational:
191
+ return False
192
+ if even:
193
+ return True
194
+ if odd == len(expr.args):
195
+ return False
196
+
197
+ @EvenPredicate.register(Add)
198
+ def _(expr, assumptions):
199
+ """
200
+ Even + Odd -> Odd
201
+ Even + Even -> Even
202
+ Odd + Odd -> Even
203
+
204
+ """
205
+ if expr.is_number:
206
+ return _EvenPredicate_number(expr, assumptions)
207
+ _result = True
208
+ for arg in expr.args:
209
+ if ask(Q.even(arg), assumptions):
210
+ pass
211
+ elif ask(Q.odd(arg), assumptions):
212
+ _result = not _result
213
+ else:
214
+ break
215
+ else:
216
+ return _result
217
+
218
+ @EvenPredicate.register(Pow)
219
+ def _(expr, assumptions):
220
+ if expr.is_number:
221
+ return _EvenPredicate_number(expr, assumptions)
222
+ if ask(Q.integer(expr.exp), assumptions):
223
+ if ask(Q.positive(expr.exp), assumptions):
224
+ return ask(Q.even(expr.base), assumptions)
225
+ elif ask(~Q.negative(expr.exp) & Q.odd(expr.base), assumptions):
226
+ return False
227
+ elif expr.base is S.NegativeOne:
228
+ return False
229
+
230
+ @EvenPredicate.register(Integer)
231
+ def _(expr, assumptions):
232
+ return not bool(expr.p & 1)
233
+
234
+ @EvenPredicate.register_many(Rational, Infinity, NegativeInfinity, ImaginaryUnit)
235
+ def _(expr, assumptions):
236
+ return False
237
+
238
+ @EvenPredicate.register(NumberSymbol)
239
+ def _(expr, assumptions):
240
+ return _EvenPredicate_number(expr, assumptions)
241
+
242
+ @EvenPredicate.register(Abs)
243
+ def _(expr, assumptions):
244
+ if ask(Q.real(expr.args[0]), assumptions):
245
+ return ask(Q.even(expr.args[0]), assumptions)
246
+
247
+ @EvenPredicate.register(re)
248
+ def _(expr, assumptions):
249
+ if ask(Q.real(expr.args[0]), assumptions):
250
+ return ask(Q.even(expr.args[0]), assumptions)
251
+
252
+ @EvenPredicate.register(im)
253
+ def _(expr, assumptions):
254
+ if ask(Q.real(expr.args[0]), assumptions):
255
+ return True
256
+
257
+ @EvenPredicate.register(NaN)
258
+ def _(expr, assumptions):
259
+ return None
260
+
261
+
262
+ # OddPredicate
263
+
264
+ @OddPredicate.register(Expr)
265
+ def _(expr, assumptions):
266
+ ret = expr.is_odd
267
+ if ret is None:
268
+ raise MDNotImplementedError
269
+ return ret
270
+
271
+ @OddPredicate.register(Basic)
272
+ def _(expr, assumptions):
273
+ _integer = ask(Q.integer(expr), assumptions)
274
+ if _integer:
275
+ _even = ask(Q.even(expr), assumptions)
276
+ if _even is None:
277
+ return None
278
+ return not _even
279
+ return _integer
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/handlers/order.py ADDED
@@ -0,0 +1,440 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Handlers related to order relations: positive, negative, etc.
3
+ """
4
+
5
+ from sympy.assumptions import Q, ask
6
+ from sympy.core import Add, Basic, Expr, Mul, Pow, S
7
+ from sympy.core.logic import fuzzy_not, fuzzy_and, fuzzy_or
8
+ from sympy.core.numbers import E, ImaginaryUnit, NaN, I, pi
9
+ from sympy.functions import Abs, acos, acot, asin, atan, exp, factorial, log
10
+ from sympy.matrices import Determinant, Trace
11
+ from sympy.matrices.expressions.matexpr import MatrixElement
12
+
13
+ from sympy.multipledispatch import MDNotImplementedError
14
+
15
+ from ..predicates.order import (NegativePredicate, NonNegativePredicate,
16
+ NonZeroPredicate, ZeroPredicate, NonPositivePredicate, PositivePredicate,
17
+ ExtendedNegativePredicate, ExtendedNonNegativePredicate,
18
+ ExtendedNonPositivePredicate, ExtendedNonZeroPredicate,
19
+ ExtendedPositivePredicate,)
20
+
21
+
22
+ # NegativePredicate
23
+
24
+ def _NegativePredicate_number(expr, assumptions):
25
+ r, i = expr.as_real_imag()
26
+
27
+ if r == S.NaN or i == S.NaN:
28
+ return None
29
+
30
+ # If the imaginary part can symbolically be shown to be zero then
31
+ # we just evaluate the real part; otherwise we evaluate the imaginary
32
+ # part to see if it actually evaluates to zero and if it does then
33
+ # we make the comparison between the real part and zero.
34
+ if not i:
35
+ r = r.evalf(2)
36
+ if r._prec != 1:
37
+ return r < 0
38
+ else:
39
+ i = i.evalf(2)
40
+ if i._prec != 1:
41
+ if i != 0:
42
+ return False
43
+ r = r.evalf(2)
44
+ if r._prec != 1:
45
+ return r < 0
46
+
47
+ @NegativePredicate.register(Basic)
48
+ def _(expr, assumptions):
49
+ if expr.is_number:
50
+ return _NegativePredicate_number(expr, assumptions)
51
+
52
+ @NegativePredicate.register(Expr)
53
+ def _(expr, assumptions):
54
+ ret = expr.is_negative
55
+ if ret is None:
56
+ raise MDNotImplementedError
57
+ return ret
58
+
59
+ @NegativePredicate.register(Add)
60
+ def _(expr, assumptions):
61
+ """
62
+ Positive + Positive -> Positive,
63
+ Negative + Negative -> Negative
64
+ """
65
+ if expr.is_number:
66
+ return _NegativePredicate_number(expr, assumptions)
67
+
68
+ r = ask(Q.real(expr), assumptions)
69
+ if r is not True:
70
+ return r
71
+
72
+ nonpos = 0
73
+ for arg in expr.args:
74
+ if ask(Q.negative(arg), assumptions) is not True:
75
+ if ask(Q.positive(arg), assumptions) is False:
76
+ nonpos += 1
77
+ else:
78
+ break
79
+ else:
80
+ if nonpos < len(expr.args):
81
+ return True
82
+
83
+ @NegativePredicate.register(Mul)
84
+ def _(expr, assumptions):
85
+ if expr.is_number:
86
+ return _NegativePredicate_number(expr, assumptions)
87
+ result = None
88
+ for arg in expr.args:
89
+ if result is None:
90
+ result = False
91
+ if ask(Q.negative(arg), assumptions):
92
+ result = not result
93
+ elif ask(Q.positive(arg), assumptions):
94
+ pass
95
+ else:
96
+ return
97
+ return result
98
+
99
+ @NegativePredicate.register(Pow)
100
+ def _(expr, assumptions):
101
+ """
102
+ Real ** Even -> NonNegative
103
+ Real ** Odd -> same_as_base
104
+ NonNegative ** Positive -> NonNegative
105
+ """
106
+ if expr.base == E:
107
+ # Exponential is always positive:
108
+ if ask(Q.real(expr.exp), assumptions):
109
+ return False
110
+ return
111
+
112
+ if expr.is_number:
113
+ return _NegativePredicate_number(expr, assumptions)
114
+ if ask(Q.real(expr.base), assumptions):
115
+ if ask(Q.positive(expr.base), assumptions):
116
+ if ask(Q.real(expr.exp), assumptions):
117
+ return False
118
+ if ask(Q.even(expr.exp), assumptions):
119
+ return False
120
+ if ask(Q.odd(expr.exp), assumptions):
121
+ return ask(Q.negative(expr.base), assumptions)
122
+
123
+ @NegativePredicate.register_many(Abs, ImaginaryUnit)
124
+ def _(expr, assumptions):
125
+ return False
126
+
127
+ @NegativePredicate.register(exp)
128
+ def _(expr, assumptions):
129
+ if ask(Q.real(expr.exp), assumptions):
130
+ return False
131
+ raise MDNotImplementedError
132
+
133
+
134
+ # NonNegativePredicate
135
+
136
+ @NonNegativePredicate.register(Basic)
137
+ def _(expr, assumptions):
138
+ if expr.is_number:
139
+ notnegative = fuzzy_not(_NegativePredicate_number(expr, assumptions))
140
+ if notnegative:
141
+ return ask(Q.real(expr), assumptions)
142
+ else:
143
+ return notnegative
144
+
145
+ @NonNegativePredicate.register(Expr)
146
+ def _(expr, assumptions):
147
+ ret = expr.is_nonnegative
148
+ if ret is None:
149
+ raise MDNotImplementedError
150
+ return ret
151
+
152
+
153
+ # NonZeroPredicate
154
+
155
+ @NonZeroPredicate.register(Expr)
156
+ def _(expr, assumptions):
157
+ ret = expr.is_nonzero
158
+ if ret is None:
159
+ raise MDNotImplementedError
160
+ return ret
161
+
162
+ @NonZeroPredicate.register(Basic)
163
+ def _(expr, assumptions):
164
+ if ask(Q.real(expr)) is False:
165
+ return False
166
+ if expr.is_number:
167
+ # if there are no symbols just evalf
168
+ i = expr.evalf(2)
169
+ def nonz(i):
170
+ if i._prec != 1:
171
+ return i != 0
172
+ return fuzzy_or(nonz(i) for i in i.as_real_imag())
173
+
174
+ @NonZeroPredicate.register(Add)
175
+ def _(expr, assumptions):
176
+ if all(ask(Q.positive(x), assumptions) for x in expr.args) \
177
+ or all(ask(Q.negative(x), assumptions) for x in expr.args):
178
+ return True
179
+
180
+ @NonZeroPredicate.register(Mul)
181
+ def _(expr, assumptions):
182
+ for arg in expr.args:
183
+ result = ask(Q.nonzero(arg), assumptions)
184
+ if result:
185
+ continue
186
+ return result
187
+ return True
188
+
189
+ @NonZeroPredicate.register(Pow)
190
+ def _(expr, assumptions):
191
+ return ask(Q.nonzero(expr.base), assumptions)
192
+
193
+ @NonZeroPredicate.register(Abs)
194
+ def _(expr, assumptions):
195
+ return ask(Q.nonzero(expr.args[0]), assumptions)
196
+
197
+ @NonZeroPredicate.register(NaN)
198
+ def _(expr, assumptions):
199
+ return None
200
+
201
+
202
+ # ZeroPredicate
203
+
204
+ @ZeroPredicate.register(Expr)
205
+ def _(expr, assumptions):
206
+ ret = expr.is_zero
207
+ if ret is None:
208
+ raise MDNotImplementedError
209
+ return ret
210
+
211
+ @ZeroPredicate.register(Basic)
212
+ def _(expr, assumptions):
213
+ return fuzzy_and([fuzzy_not(ask(Q.nonzero(expr), assumptions)),
214
+ ask(Q.real(expr), assumptions)])
215
+
216
+ @ZeroPredicate.register(Mul)
217
+ def _(expr, assumptions):
218
+ # TODO: This should be deducible from the nonzero handler
219
+ return fuzzy_or(ask(Q.zero(arg), assumptions) for arg in expr.args)
220
+
221
+
222
+ # NonPositivePredicate
223
+
224
+ @NonPositivePredicate.register(Expr)
225
+ def _(expr, assumptions):
226
+ ret = expr.is_nonpositive
227
+ if ret is None:
228
+ raise MDNotImplementedError
229
+ return ret
230
+
231
+ @NonPositivePredicate.register(Basic)
232
+ def _(expr, assumptions):
233
+ if expr.is_number:
234
+ notpositive = fuzzy_not(_PositivePredicate_number(expr, assumptions))
235
+ if notpositive:
236
+ return ask(Q.real(expr), assumptions)
237
+ else:
238
+ return notpositive
239
+
240
+
241
+ # PositivePredicate
242
+
243
+ def _PositivePredicate_number(expr, assumptions):
244
+ r, i = expr.as_real_imag()
245
+ # If the imaginary part can symbolically be shown to be zero then
246
+ # we just evaluate the real part; otherwise we evaluate the imaginary
247
+ # part to see if it actually evaluates to zero and if it does then
248
+ # we make the comparison between the real part and zero.
249
+ if not i:
250
+ r = r.evalf(2)
251
+ if r._prec != 1:
252
+ return r > 0
253
+ else:
254
+ i = i.evalf(2)
255
+ if i._prec != 1:
256
+ if i != 0:
257
+ return False
258
+ r = r.evalf(2)
259
+ if r._prec != 1:
260
+ return r > 0
261
+
262
+ @PositivePredicate.register(Expr)
263
+ def _(expr, assumptions):
264
+ ret = expr.is_positive
265
+ if ret is None:
266
+ raise MDNotImplementedError
267
+ return ret
268
+
269
+ @PositivePredicate.register(Basic)
270
+ def _(expr, assumptions):
271
+ if expr.is_number:
272
+ return _PositivePredicate_number(expr, assumptions)
273
+
274
+ @PositivePredicate.register(Mul)
275
+ def _(expr, assumptions):
276
+ if expr.is_number:
277
+ return _PositivePredicate_number(expr, assumptions)
278
+ result = True
279
+ for arg in expr.args:
280
+ if ask(Q.positive(arg), assumptions):
281
+ continue
282
+ elif ask(Q.negative(arg), assumptions):
283
+ result = result ^ True
284
+ else:
285
+ return
286
+ return result
287
+
288
+ @PositivePredicate.register(Add)
289
+ def _(expr, assumptions):
290
+ if expr.is_number:
291
+ return _PositivePredicate_number(expr, assumptions)
292
+
293
+ r = ask(Q.real(expr), assumptions)
294
+ if r is not True:
295
+ return r
296
+
297
+ nonneg = 0
298
+ for arg in expr.args:
299
+ if ask(Q.positive(arg), assumptions) is not True:
300
+ if ask(Q.negative(arg), assumptions) is False:
301
+ nonneg += 1
302
+ else:
303
+ break
304
+ else:
305
+ if nonneg < len(expr.args):
306
+ return True
307
+
308
+ @PositivePredicate.register(Pow)
309
+ def _(expr, assumptions):
310
+ if expr.base == E:
311
+ if ask(Q.real(expr.exp), assumptions):
312
+ return True
313
+ if ask(Q.imaginary(expr.exp), assumptions):
314
+ return ask(Q.even(expr.exp/(I*pi)), assumptions)
315
+ return
316
+
317
+ if expr.is_number:
318
+ return _PositivePredicate_number(expr, assumptions)
319
+ if ask(Q.positive(expr.base), assumptions):
320
+ if ask(Q.real(expr.exp), assumptions):
321
+ return True
322
+ if ask(Q.negative(expr.base), assumptions):
323
+ if ask(Q.even(expr.exp), assumptions):
324
+ return True
325
+ if ask(Q.odd(expr.exp), assumptions):
326
+ return False
327
+
328
+ @PositivePredicate.register(exp)
329
+ def _(expr, assumptions):
330
+ if ask(Q.real(expr.exp), assumptions):
331
+ return True
332
+ if ask(Q.imaginary(expr.exp), assumptions):
333
+ return ask(Q.even(expr.exp/(I*pi)), assumptions)
334
+
335
+ @PositivePredicate.register(log)
336
+ def _(expr, assumptions):
337
+ r = ask(Q.real(expr.args[0]), assumptions)
338
+ if r is not True:
339
+ return r
340
+ if ask(Q.positive(expr.args[0] - 1), assumptions):
341
+ return True
342
+ if ask(Q.negative(expr.args[0] - 1), assumptions):
343
+ return False
344
+
345
+ @PositivePredicate.register(factorial)
346
+ def _(expr, assumptions):
347
+ x = expr.args[0]
348
+ if ask(Q.integer(x) & Q.positive(x), assumptions):
349
+ return True
350
+
351
+ @PositivePredicate.register(ImaginaryUnit)
352
+ def _(expr, assumptions):
353
+ return False
354
+
355
+ @PositivePredicate.register(Abs)
356
+ def _(expr, assumptions):
357
+ return ask(Q.nonzero(expr), assumptions)
358
+
359
+ @PositivePredicate.register(Trace)
360
+ def _(expr, assumptions):
361
+ if ask(Q.positive_definite(expr.arg), assumptions):
362
+ return True
363
+
364
+ @PositivePredicate.register(Determinant)
365
+ def _(expr, assumptions):
366
+ if ask(Q.positive_definite(expr.arg), assumptions):
367
+ return True
368
+
369
+ @PositivePredicate.register(MatrixElement)
370
+ def _(expr, assumptions):
371
+ if (expr.i == expr.j
372
+ and ask(Q.positive_definite(expr.parent), assumptions)):
373
+ return True
374
+
375
+ @PositivePredicate.register(atan)
376
+ def _(expr, assumptions):
377
+ return ask(Q.positive(expr.args[0]), assumptions)
378
+
379
+ @PositivePredicate.register(asin)
380
+ def _(expr, assumptions):
381
+ x = expr.args[0]
382
+ if ask(Q.positive(x) & Q.nonpositive(x - 1), assumptions):
383
+ return True
384
+ if ask(Q.negative(x) & Q.nonnegative(x + 1), assumptions):
385
+ return False
386
+
387
+ @PositivePredicate.register(acos)
388
+ def _(expr, assumptions):
389
+ x = expr.args[0]
390
+ if ask(Q.nonpositive(x - 1) & Q.nonnegative(x + 1), assumptions):
391
+ return True
392
+
393
+ @PositivePredicate.register(acot)
394
+ def _(expr, assumptions):
395
+ return ask(Q.real(expr.args[0]), assumptions)
396
+
397
+ @PositivePredicate.register(NaN)
398
+ def _(expr, assumptions):
399
+ return None
400
+
401
+
402
+ # ExtendedNegativePredicate
403
+
404
+ @ExtendedNegativePredicate.register(object)
405
+ def _(expr, assumptions):
406
+ return ask(Q.negative(expr) | Q.negative_infinite(expr), assumptions)
407
+
408
+
409
+ # ExtendedPositivePredicate
410
+
411
+ @ExtendedPositivePredicate.register(object)
412
+ def _(expr, assumptions):
413
+ return ask(Q.positive(expr) | Q.positive_infinite(expr), assumptions)
414
+
415
+
416
+ # ExtendedNonZeroPredicate
417
+
418
+ @ExtendedNonZeroPredicate.register(object)
419
+ def _(expr, assumptions):
420
+ return ask(
421
+ Q.negative_infinite(expr) | Q.negative(expr) | Q.positive(expr) | Q.positive_infinite(expr),
422
+ assumptions)
423
+
424
+
425
+ # ExtendedNonPositivePredicate
426
+
427
+ @ExtendedNonPositivePredicate.register(object)
428
+ def _(expr, assumptions):
429
+ return ask(
430
+ Q.negative_infinite(expr) | Q.negative(expr) | Q.zero(expr),
431
+ assumptions)
432
+
433
+
434
+ # ExtendedNonNegativePredicate
435
+
436
+ @ExtendedNonNegativePredicate.register(object)
437
+ def _(expr, assumptions):
438
+ return ask(
439
+ Q.zero(expr) | Q.positive(expr) | Q.positive_infinite(expr),
440
+ assumptions)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/handlers/sets.py ADDED
@@ -0,0 +1,816 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Handlers for predicates related to set membership: integer, rational, etc.
3
+ """
4
+
5
+ from sympy.assumptions import Q, ask
6
+ from sympy.core import Add, Basic, Expr, Mul, Pow, S
7
+ from sympy.core.numbers import (AlgebraicNumber, ComplexInfinity, Exp1, Float,
8
+ GoldenRatio, ImaginaryUnit, Infinity, Integer, NaN, NegativeInfinity,
9
+ Number, NumberSymbol, Pi, pi, Rational, TribonacciConstant, E)
10
+ from sympy.core.logic import fuzzy_bool
11
+ from sympy.functions import (Abs, acos, acot, asin, atan, cos, cot, exp, im,
12
+ log, re, sin, tan)
13
+ from sympy.core.numbers import I
14
+ from sympy.core.relational import Eq
15
+ from sympy.functions.elementary.complexes import conjugate
16
+ from sympy.matrices import Determinant, MatrixBase, Trace
17
+ from sympy.matrices.expressions.matexpr import MatrixElement
18
+
19
+ from sympy.multipledispatch import MDNotImplementedError
20
+
21
+ from .common import test_closed_group, ask_all, ask_any
22
+ from ..predicates.sets import (IntegerPredicate, RationalPredicate,
23
+ IrrationalPredicate, RealPredicate, ExtendedRealPredicate,
24
+ HermitianPredicate, ComplexPredicate, ImaginaryPredicate,
25
+ AntihermitianPredicate, AlgebraicPredicate)
26
+
27
+
28
+ # IntegerPredicate
29
+
30
+ def _IntegerPredicate_number(expr, assumptions):
31
+ # helper function
32
+ try:
33
+ i = int(expr.round())
34
+ if not (expr - i).equals(0):
35
+ raise TypeError
36
+ return True
37
+ except TypeError:
38
+ return False
39
+
40
+ @IntegerPredicate.register_many(int, Integer) # type:ignore
41
+ def _(expr, assumptions):
42
+ return True
43
+
44
+ @IntegerPredicate.register_many(Exp1, GoldenRatio, ImaginaryUnit, Infinity,
45
+ NegativeInfinity, Pi, Rational, TribonacciConstant)
46
+ def _(expr, assumptions):
47
+ return False
48
+
49
+ @IntegerPredicate.register(Expr)
50
+ def _(expr, assumptions):
51
+ ret = expr.is_integer
52
+ if ret is None:
53
+ raise MDNotImplementedError
54
+ return ret
55
+
56
+ @IntegerPredicate.register(Add)
57
+ def _(expr, assumptions):
58
+ """
59
+ * Integer + Integer -> Integer
60
+ * Integer + !Integer -> !Integer
61
+ * !Integer + !Integer -> ?
62
+ """
63
+ if expr.is_number:
64
+ return _IntegerPredicate_number(expr, assumptions)
65
+ return test_closed_group(expr, assumptions, Q.integer)
66
+
67
+ @IntegerPredicate.register(Pow)
68
+ def _(expr,assumptions):
69
+ if expr.is_number:
70
+ return _IntegerPredicate_number(expr, assumptions)
71
+ if ask_all(~Q.zero(expr.base), Q.finite(expr.base), Q.zero(expr.exp), assumptions=assumptions):
72
+ return True
73
+ if ask_all(Q.integer(expr.base), Q.integer(expr.exp), assumptions=assumptions):
74
+ if ask_any(Q.positive(expr.exp), Q.nonnegative(expr.exp) & ~Q.zero(expr.base), Q.zero(expr.base-1), Q.zero(expr.base+1), assumptions=assumptions):
75
+ return True
76
+
77
+ @IntegerPredicate.register(Mul)
78
+ def _(expr, assumptions):
79
+ """
80
+ * Integer*Integer -> Integer
81
+ * Integer*Irrational -> !Integer
82
+ * Odd/Even -> !Integer
83
+ * Integer*Rational -> ?
84
+ """
85
+ if expr.is_number:
86
+ return _IntegerPredicate_number(expr, assumptions)
87
+ _output = True
88
+ for arg in expr.args:
89
+ if not ask(Q.integer(arg), assumptions):
90
+ if arg.is_Rational:
91
+ if arg.q == 2:
92
+ return ask(Q.even(2*expr), assumptions)
93
+ if ~(arg.q & 1):
94
+ return None
95
+ elif ask(Q.irrational(arg), assumptions):
96
+ if _output:
97
+ _output = False
98
+ else:
99
+ return
100
+ else:
101
+ return
102
+
103
+ return _output
104
+
105
+ @IntegerPredicate.register(Abs)
106
+ def _(expr, assumptions):
107
+ if ask(Q.integer(expr.args[0]), assumptions):
108
+ return True
109
+
110
+ @IntegerPredicate.register_many(Determinant, MatrixElement, Trace)
111
+ def _(expr, assumptions):
112
+ return ask(Q.integer_elements(expr.args[0]), assumptions)
113
+
114
+
115
+ # RationalPredicate
116
+
117
+ @RationalPredicate.register(Rational)
118
+ def _(expr, assumptions):
119
+ return True
120
+
121
+ @RationalPredicate.register(Float)
122
+ def _(expr, assumptions):
123
+ return None
124
+
125
+ @RationalPredicate.register_many(Exp1, GoldenRatio, ImaginaryUnit, Infinity,
126
+ NegativeInfinity, Pi, TribonacciConstant)
127
+ def _(expr, assumptions):
128
+ return False
129
+
130
+ @RationalPredicate.register(Expr)
131
+ def _(expr, assumptions):
132
+ ret = expr.is_rational
133
+ if ret is None:
134
+ raise MDNotImplementedError
135
+ return ret
136
+
137
+ @RationalPredicate.register_many(Add, Mul)
138
+ def _(expr, assumptions):
139
+ """
140
+ * Rational + Rational -> Rational
141
+ * Rational + !Rational -> !Rational
142
+ * !Rational + !Rational -> ?
143
+ """
144
+ if expr.is_number:
145
+ if expr.as_real_imag()[1]:
146
+ return False
147
+ return test_closed_group(expr, assumptions, Q.rational)
148
+
149
+ @RationalPredicate.register(Pow)
150
+ def _(expr, assumptions):
151
+ """
152
+ * Rational ** Integer -> Rational
153
+ * Irrational ** Rational -> Irrational
154
+ * Rational ** Irrational -> ?
155
+ """
156
+ if expr.base == E:
157
+ x = expr.exp
158
+ if ask(Q.rational(x), assumptions):
159
+ return ask(Q.zero(x), assumptions)
160
+ return
161
+
162
+ is_exp_integer = ask(Q.integer(expr.exp), assumptions)
163
+ if is_exp_integer:
164
+ is_base_rational = ask(Q.rational(expr.base),assumptions)
165
+ if is_base_rational:
166
+ is_base_zero = ask(Q.zero(expr.base),assumptions)
167
+ if is_base_zero is False:
168
+ return True
169
+ if is_base_zero and ask(Q.positive(expr.exp)):
170
+ return True
171
+ if ask(Q.algebraic(expr.base),assumptions) is False:
172
+ return ask(Q.zero(expr.exp), assumptions)
173
+ if ask(Q.irrational(expr.base),assumptions) and ask(Q.eq(expr.exp,-1)):
174
+ return False
175
+ return
176
+ elif ask(Q.rational(expr.exp), assumptions):
177
+ if ask(Q.prime(expr.base), assumptions) and is_exp_integer is False:
178
+ return False
179
+ if ask(Q.zero(expr.base)) and ask(Q.positive(expr.exp)):
180
+ return True
181
+ if ask(Q.eq(expr.base,1)):
182
+ return True
183
+
184
+ @RationalPredicate.register_many(asin, atan, cos, sin, tan)
185
+ def _(expr, assumptions):
186
+ x = expr.args[0]
187
+ if ask(Q.rational(x), assumptions):
188
+ return ask(~Q.nonzero(x), assumptions)
189
+
190
+ @RationalPredicate.register(exp)
191
+ def _(expr, assumptions):
192
+ x = expr.exp
193
+ if ask(Q.rational(x), assumptions):
194
+ return ask(~Q.nonzero(x), assumptions)
195
+
196
+ @RationalPredicate.register_many(acot, cot)
197
+ def _(expr, assumptions):
198
+ x = expr.args[0]
199
+ if ask(Q.rational(x), assumptions):
200
+ return False
201
+
202
+ @RationalPredicate.register_many(acos, log)
203
+ def _(expr, assumptions):
204
+ x = expr.args[0]
205
+ if ask(Q.rational(x), assumptions):
206
+ return ask(~Q.nonzero(x - 1), assumptions)
207
+
208
+
209
+ # IrrationalPredicate
210
+
211
+ @IrrationalPredicate.register(Expr)
212
+ def _(expr, assumptions):
213
+ ret = expr.is_irrational
214
+ if ret is None:
215
+ raise MDNotImplementedError
216
+ return ret
217
+
218
+ @IrrationalPredicate.register(Basic)
219
+ def _(expr, assumptions):
220
+ _real = ask(Q.real(expr), assumptions)
221
+ if _real:
222
+ _rational = ask(Q.rational(expr), assumptions)
223
+ if _rational is None:
224
+ return None
225
+ return not _rational
226
+ else:
227
+ return _real
228
+
229
+
230
+ # RealPredicate
231
+
232
+ def _RealPredicate_number(expr, assumptions):
233
+ # let as_real_imag() work first since the expression may
234
+ # be simpler to evaluate
235
+ i = expr.as_real_imag()[1].evalf(2)
236
+ if i._prec != 1:
237
+ return not i
238
+ # allow None to be returned if we couldn't show for sure
239
+ # that i was 0
240
+
241
+ @RealPredicate.register_many(Abs, Exp1, Float, GoldenRatio, im, Pi, Rational,
242
+ re, TribonacciConstant)
243
+ def _(expr, assumptions):
244
+ return True
245
+
246
+ @RealPredicate.register_many(ImaginaryUnit, Infinity, NegativeInfinity)
247
+ def _(expr, assumptions):
248
+ return False
249
+
250
+ @RealPredicate.register(Expr)
251
+ def _(expr, assumptions):
252
+ ret = expr.is_real
253
+ if ret is None:
254
+ raise MDNotImplementedError
255
+ return ret
256
+
257
+ @RealPredicate.register(Add)
258
+ def _(expr, assumptions):
259
+ """
260
+ * Real + Real -> Real
261
+ * Real + (Complex & !Real) -> !Real
262
+ """
263
+ if expr.is_number:
264
+ return _RealPredicate_number(expr, assumptions)
265
+ return test_closed_group(expr, assumptions, Q.real)
266
+
267
+ @RealPredicate.register(Mul)
268
+ def _(expr, assumptions):
269
+ """
270
+ * Real*Real -> Real
271
+ * Real*Imaginary -> !Real
272
+ * Imaginary*Imaginary -> Real
273
+ """
274
+ if expr.is_number:
275
+ return _RealPredicate_number(expr, assumptions)
276
+ result = True
277
+ for arg in expr.args:
278
+ if ask(Q.real(arg), assumptions):
279
+ pass
280
+ elif ask(Q.imaginary(arg), assumptions):
281
+ result = result ^ True
282
+ else:
283
+ break
284
+ else:
285
+ return result
286
+
287
+ @RealPredicate.register(Pow)
288
+ def _(expr, assumptions):
289
+ """
290
+ * Real**Integer -> Real
291
+ * Positive**Real -> Real
292
+ * Negative**Real -> ?
293
+ * Real**(Integer/Even) -> Real if base is nonnegative
294
+ * Real**(Integer/Odd) -> Real
295
+ * Imaginary**(Integer/Even) -> Real
296
+ * Imaginary**(Integer/Odd) -> not Real
297
+ * Imaginary**Real -> ? since Real could be 0 (giving real)
298
+ or 1 (giving imaginary)
299
+ * b**Imaginary -> Real if log(b) is imaginary and b != 0
300
+ and exponent != integer multiple of
301
+ I*pi/log(b)
302
+ * Real**Real -> ? e.g. sqrt(-1) is imaginary and
303
+ sqrt(2) is not
304
+ """
305
+ if expr.is_number:
306
+ return _RealPredicate_number(expr, assumptions)
307
+
308
+ if expr.base == E:
309
+ return ask(
310
+ Q.integer(expr.exp/I/pi) | Q.real(expr.exp), assumptions
311
+ )
312
+
313
+ if expr.base.func == exp or (expr.base.is_Pow and expr.base.base == E):
314
+ if ask(Q.imaginary(expr.base.exp), assumptions):
315
+ if ask(Q.imaginary(expr.exp), assumptions):
316
+ return True
317
+ # If the i = (exp's arg)/(I*pi) is an integer or half-integer
318
+ # multiple of I*pi then 2*i will be an integer. In addition,
319
+ # exp(i*I*pi) = (-1)**i so the overall realness of the expr
320
+ # can be determined by replacing exp(i*I*pi) with (-1)**i.
321
+ i = expr.base.exp/I/pi
322
+ if ask(Q.integer(2*i), assumptions):
323
+ return ask(Q.real((S.NegativeOne**i)**expr.exp), assumptions)
324
+ return
325
+
326
+ if ask(Q.imaginary(expr.base), assumptions):
327
+ if ask(Q.integer(expr.exp), assumptions):
328
+ odd = ask(Q.odd(expr.exp), assumptions)
329
+ if odd is not None:
330
+ return not odd
331
+ return
332
+
333
+ if ask(Q.imaginary(expr.exp), assumptions):
334
+ imlog = ask(Q.imaginary(log(expr.base)), assumptions)
335
+ if imlog is not None:
336
+ # I**i -> real, log(I) is imag;
337
+ # (2*I)**i -> complex, log(2*I) is not imag
338
+ return imlog
339
+
340
+ if ask(Q.real(expr.base), assumptions):
341
+ if ask(Q.real(expr.exp), assumptions):
342
+ if ask(Q.zero(expr.base), assumptions) is not False:
343
+ if ask(Q.positive(expr.exp), assumptions):
344
+ return True
345
+ return
346
+ if expr.exp.is_Rational and \
347
+ ask(Q.even(expr.exp.q), assumptions):
348
+ return ask(Q.positive(expr.base), assumptions)
349
+ elif ask(Q.integer(expr.exp), assumptions):
350
+ return True
351
+ elif ask(Q.positive(expr.base), assumptions):
352
+ return True
353
+
354
+ @RealPredicate.register_many(cos, sin)
355
+ def _(expr, assumptions):
356
+ if ask(Q.real(expr.args[0]), assumptions):
357
+ return True
358
+
359
+ @RealPredicate.register(exp)
360
+ def _(expr, assumptions):
361
+ return ask(
362
+ Q.integer(expr.exp/I/pi) | Q.real(expr.exp), assumptions
363
+ )
364
+
365
+ @RealPredicate.register(log)
366
+ def _(expr, assumptions):
367
+ return ask(Q.positive(expr.args[0]), assumptions)
368
+
369
+ @RealPredicate.register_many(Determinant, MatrixElement, Trace)
370
+ def _(expr, assumptions):
371
+ return ask(Q.real_elements(expr.args[0]), assumptions)
372
+
373
+
374
+ # ExtendedRealPredicate
375
+
376
+ @ExtendedRealPredicate.register(object)
377
+ def _(expr, assumptions):
378
+ return ask(Q.negative_infinite(expr)
379
+ | Q.negative(expr)
380
+ | Q.zero(expr)
381
+ | Q.positive(expr)
382
+ | Q.positive_infinite(expr),
383
+ assumptions)
384
+
385
+ @ExtendedRealPredicate.register_many(Infinity, NegativeInfinity)
386
+ def _(expr, assumptions):
387
+ return True
388
+
389
+ @ExtendedRealPredicate.register_many(Add, Mul, Pow) # type:ignore
390
+ def _(expr, assumptions):
391
+ return test_closed_group(expr, assumptions, Q.extended_real)
392
+
393
+
394
+ # HermitianPredicate
395
+
396
+ @HermitianPredicate.register(object) # type:ignore
397
+ def _(expr, assumptions):
398
+ if isinstance(expr, MatrixBase):
399
+ return None
400
+ return ask(Q.real(expr), assumptions)
401
+
402
+ @HermitianPredicate.register(Add) # type:ignore
403
+ def _(expr, assumptions):
404
+ """
405
+ * Hermitian + Hermitian -> Hermitian
406
+ * Hermitian + !Hermitian -> !Hermitian
407
+ """
408
+ if expr.is_number:
409
+ raise MDNotImplementedError
410
+ return test_closed_group(expr, assumptions, Q.hermitian)
411
+
412
+ @HermitianPredicate.register(Mul) # type:ignore
413
+ def _(expr, assumptions):
414
+ """
415
+ As long as there is at most only one noncommutative term:
416
+
417
+ * Hermitian*Hermitian -> Hermitian
418
+ * Hermitian*Antihermitian -> !Hermitian
419
+ * Antihermitian*Antihermitian -> Hermitian
420
+ """
421
+ if expr.is_number:
422
+ raise MDNotImplementedError
423
+ nccount = 0
424
+ result = True
425
+ for arg in expr.args:
426
+ if ask(Q.antihermitian(arg), assumptions):
427
+ result = result ^ True
428
+ elif not ask(Q.hermitian(arg), assumptions):
429
+ break
430
+ if ask(~Q.commutative(arg), assumptions):
431
+ nccount += 1
432
+ if nccount > 1:
433
+ break
434
+ else:
435
+ return result
436
+
437
+ @HermitianPredicate.register(Pow) # type:ignore
438
+ def _(expr, assumptions):
439
+ """
440
+ * Hermitian**Integer -> Hermitian
441
+ """
442
+ if expr.is_number:
443
+ raise MDNotImplementedError
444
+ if expr.base == E:
445
+ if ask(Q.hermitian(expr.exp), assumptions):
446
+ return True
447
+ raise MDNotImplementedError
448
+ if ask(Q.hermitian(expr.base), assumptions):
449
+ if ask(Q.integer(expr.exp), assumptions):
450
+ return True
451
+ raise MDNotImplementedError
452
+
453
+ @HermitianPredicate.register_many(cos, sin) # type:ignore
454
+ def _(expr, assumptions):
455
+ if ask(Q.hermitian(expr.args[0]), assumptions):
456
+ return True
457
+ raise MDNotImplementedError
458
+
459
+ @HermitianPredicate.register(exp) # type:ignore
460
+ def _(expr, assumptions):
461
+ if ask(Q.hermitian(expr.exp), assumptions):
462
+ return True
463
+ raise MDNotImplementedError
464
+
465
+ @HermitianPredicate.register(MatrixBase) # type:ignore
466
+ def _(mat, assumptions):
467
+ rows, cols = mat.shape
468
+ ret_val = True
469
+ for i in range(rows):
470
+ for j in range(i, cols):
471
+ cond = fuzzy_bool(Eq(mat[i, j], conjugate(mat[j, i])))
472
+ if cond is None:
473
+ ret_val = None
474
+ if cond == False:
475
+ return False
476
+ if ret_val is None:
477
+ raise MDNotImplementedError
478
+ return ret_val
479
+
480
+
481
+ # ComplexPredicate
482
+
483
+ @ComplexPredicate.register_many(Abs, cos, exp, im, ImaginaryUnit, log, Number, # type:ignore
484
+ NumberSymbol, re, sin)
485
+ def _(expr, assumptions):
486
+ return True
487
+
488
+ @ComplexPredicate.register_many(Infinity, NegativeInfinity) # type:ignore
489
+ def _(expr, assumptions):
490
+ return False
491
+
492
+ @ComplexPredicate.register(Expr) # type:ignore
493
+ def _(expr, assumptions):
494
+ ret = expr.is_complex
495
+ if ret is None:
496
+ raise MDNotImplementedError
497
+ return ret
498
+
499
+ @ComplexPredicate.register_many(Add, Mul) # type:ignore
500
+ def _(expr, assumptions):
501
+ return test_closed_group(expr, assumptions, Q.complex)
502
+
503
+ @ComplexPredicate.register(Pow) # type:ignore
504
+ def _(expr, assumptions):
505
+ if expr.base == E:
506
+ return True
507
+ return test_closed_group(expr, assumptions, Q.complex)
508
+
509
+ @ComplexPredicate.register_many(Determinant, MatrixElement, Trace) # type:ignore
510
+ def _(expr, assumptions):
511
+ return ask(Q.complex_elements(expr.args[0]), assumptions)
512
+
513
+ @ComplexPredicate.register(NaN) # type:ignore
514
+ def _(expr, assumptions):
515
+ return None
516
+
517
+
518
+ # ImaginaryPredicate
519
+
520
+ def _Imaginary_number(expr, assumptions):
521
+ # let as_real_imag() work first since the expression may
522
+ # be simpler to evaluate
523
+ r = expr.as_real_imag()[0].evalf(2)
524
+ if r._prec != 1:
525
+ return not r
526
+ # allow None to be returned if we couldn't show for sure
527
+ # that r was 0
528
+
529
+ @ImaginaryPredicate.register(ImaginaryUnit) # type:ignore
530
+ def _(expr, assumptions):
531
+ return True
532
+
533
+ @ImaginaryPredicate.register(Expr) # type:ignore
534
+ def _(expr, assumptions):
535
+ ret = expr.is_imaginary
536
+ if ret is None:
537
+ raise MDNotImplementedError
538
+ return ret
539
+
540
+ @ImaginaryPredicate.register(Add) # type:ignore
541
+ def _(expr, assumptions):
542
+ """
543
+ * Imaginary + Imaginary -> Imaginary
544
+ * Imaginary + Complex -> ?
545
+ * Imaginary + Real -> !Imaginary
546
+ """
547
+ if expr.is_number:
548
+ return _Imaginary_number(expr, assumptions)
549
+
550
+ reals = 0
551
+ for arg in expr.args:
552
+ if ask(Q.imaginary(arg), assumptions):
553
+ pass
554
+ elif ask(Q.real(arg), assumptions):
555
+ reals += 1
556
+ else:
557
+ break
558
+ else:
559
+ if reals == 0:
560
+ return True
561
+ if reals in (1, len(expr.args)):
562
+ # two reals could sum 0 thus giving an imaginary
563
+ return False
564
+
565
+ @ImaginaryPredicate.register(Mul) # type:ignore
566
+ def _(expr, assumptions):
567
+ """
568
+ * Real*Imaginary -> Imaginary
569
+ * Imaginary*Imaginary -> Real
570
+ """
571
+ if expr.is_number:
572
+ return _Imaginary_number(expr, assumptions)
573
+ result = False
574
+ reals = 0
575
+ for arg in expr.args:
576
+ if ask(Q.imaginary(arg), assumptions):
577
+ result = result ^ True
578
+ elif not ask(Q.real(arg), assumptions):
579
+ break
580
+ else:
581
+ if reals == len(expr.args):
582
+ return False
583
+ return result
584
+
585
+ @ImaginaryPredicate.register(Pow) # type:ignore
586
+ def _(expr, assumptions):
587
+ """
588
+ * Imaginary**Odd -> Imaginary
589
+ * Imaginary**Even -> Real
590
+ * b**Imaginary -> !Imaginary if exponent is an integer
591
+ multiple of I*pi/log(b)
592
+ * Imaginary**Real -> ?
593
+ * Positive**Real -> Real
594
+ * Negative**Integer -> Real
595
+ * Negative**(Integer/2) -> Imaginary
596
+ * Negative**Real -> not Imaginary if exponent is not Rational
597
+ """
598
+ if expr.is_number:
599
+ return _Imaginary_number(expr, assumptions)
600
+
601
+ if expr.base == E:
602
+ a = expr.exp/I/pi
603
+ return ask(Q.integer(2*a) & ~Q.integer(a), assumptions)
604
+
605
+ if expr.base.func == exp or (expr.base.is_Pow and expr.base.base == E):
606
+ if ask(Q.imaginary(expr.base.exp), assumptions):
607
+ if ask(Q.imaginary(expr.exp), assumptions):
608
+ return False
609
+ i = expr.base.exp/I/pi
610
+ if ask(Q.integer(2*i), assumptions):
611
+ return ask(Q.imaginary((S.NegativeOne**i)**expr.exp), assumptions)
612
+
613
+ if ask(Q.imaginary(expr.base), assumptions):
614
+ if ask(Q.integer(expr.exp), assumptions):
615
+ odd = ask(Q.odd(expr.exp), assumptions)
616
+ if odd is not None:
617
+ return odd
618
+ return
619
+
620
+ if ask(Q.imaginary(expr.exp), assumptions):
621
+ imlog = ask(Q.imaginary(log(expr.base)), assumptions)
622
+ if imlog is not None:
623
+ # I**i -> real; (2*I)**i -> complex ==> not imaginary
624
+ return False
625
+
626
+ if ask(Q.real(expr.base) & Q.real(expr.exp), assumptions):
627
+ if ask(Q.positive(expr.base), assumptions):
628
+ return False
629
+ else:
630
+ rat = ask(Q.rational(expr.exp), assumptions)
631
+ if not rat:
632
+ return rat
633
+ if ask(Q.integer(expr.exp), assumptions):
634
+ return False
635
+ else:
636
+ half = ask(Q.integer(2*expr.exp), assumptions)
637
+ if half:
638
+ return ask(Q.negative(expr.base), assumptions)
639
+ return half
640
+
641
+ @ImaginaryPredicate.register(log) # type:ignore
642
+ def _(expr, assumptions):
643
+ if ask(Q.real(expr.args[0]), assumptions):
644
+ if ask(Q.positive(expr.args[0]), assumptions):
645
+ return False
646
+ return
647
+ # XXX it should be enough to do
648
+ # return ask(Q.nonpositive(expr.args[0]), assumptions)
649
+ # but ask(Q.nonpositive(exp(x)), Q.imaginary(x)) -> None;
650
+ # it should return True since exp(x) will be either 0 or complex
651
+ if expr.args[0].func == exp or (expr.args[0].is_Pow and expr.args[0].base == E):
652
+ if expr.args[0].exp in [I, -I]:
653
+ return True
654
+ im = ask(Q.imaginary(expr.args[0]), assumptions)
655
+ if im is False:
656
+ return False
657
+
658
+ @ImaginaryPredicate.register(exp) # type:ignore
659
+ def _(expr, assumptions):
660
+ a = expr.exp/I/pi
661
+ return ask(Q.integer(2*a) & ~Q.integer(a), assumptions)
662
+
663
+ @ImaginaryPredicate.register_many(Number, NumberSymbol) # type:ignore
664
+ def _(expr, assumptions):
665
+ return not (expr.as_real_imag()[1] == 0)
666
+
667
+ @ImaginaryPredicate.register(NaN) # type:ignore
668
+ def _(expr, assumptions):
669
+ return None
670
+
671
+
672
+ # AntihermitianPredicate
673
+
674
+ @AntihermitianPredicate.register(object) # type:ignore
675
+ def _(expr, assumptions):
676
+ if isinstance(expr, MatrixBase):
677
+ return None
678
+ if ask(Q.zero(expr), assumptions):
679
+ return True
680
+ return ask(Q.imaginary(expr), assumptions)
681
+
682
+ @AntihermitianPredicate.register(Add) # type:ignore
683
+ def _(expr, assumptions):
684
+ """
685
+ * Antihermitian + Antihermitian -> Antihermitian
686
+ * Antihermitian + !Antihermitian -> !Antihermitian
687
+ """
688
+ if expr.is_number:
689
+ raise MDNotImplementedError
690
+ return test_closed_group(expr, assumptions, Q.antihermitian)
691
+
692
+ @AntihermitianPredicate.register(Mul) # type:ignore
693
+ def _(expr, assumptions):
694
+ """
695
+ As long as there is at most only one noncommutative term:
696
+
697
+ * Hermitian*Hermitian -> !Antihermitian
698
+ * Hermitian*Antihermitian -> Antihermitian
699
+ * Antihermitian*Antihermitian -> !Antihermitian
700
+ """
701
+ if expr.is_number:
702
+ raise MDNotImplementedError
703
+ nccount = 0
704
+ result = False
705
+ for arg in expr.args:
706
+ if ask(Q.antihermitian(arg), assumptions):
707
+ result = result ^ True
708
+ elif not ask(Q.hermitian(arg), assumptions):
709
+ break
710
+ if ask(~Q.commutative(arg), assumptions):
711
+ nccount += 1
712
+ if nccount > 1:
713
+ break
714
+ else:
715
+ return result
716
+
717
+ @AntihermitianPredicate.register(Pow) # type:ignore
718
+ def _(expr, assumptions):
719
+ """
720
+ * Hermitian**Integer -> !Antihermitian
721
+ * Antihermitian**Even -> !Antihermitian
722
+ * Antihermitian**Odd -> Antihermitian
723
+ """
724
+ if expr.is_number:
725
+ raise MDNotImplementedError
726
+ if ask(Q.hermitian(expr.base), assumptions):
727
+ if ask(Q.integer(expr.exp), assumptions):
728
+ return False
729
+ elif ask(Q.antihermitian(expr.base), assumptions):
730
+ if ask(Q.even(expr.exp), assumptions):
731
+ return False
732
+ elif ask(Q.odd(expr.exp), assumptions):
733
+ return True
734
+ raise MDNotImplementedError
735
+
736
+ @AntihermitianPredicate.register(MatrixBase) # type:ignore
737
+ def _(mat, assumptions):
738
+ rows, cols = mat.shape
739
+ ret_val = True
740
+ for i in range(rows):
741
+ for j in range(i, cols):
742
+ cond = fuzzy_bool(Eq(mat[i, j], -conjugate(mat[j, i])))
743
+ if cond is None:
744
+ ret_val = None
745
+ if cond == False:
746
+ return False
747
+ if ret_val is None:
748
+ raise MDNotImplementedError
749
+ return ret_val
750
+
751
+
752
+ # AlgebraicPredicate
753
+
754
+ @AlgebraicPredicate.register_many(AlgebraicNumber, Float, GoldenRatio, # type:ignore
755
+ ImaginaryUnit, TribonacciConstant)
756
+ def _(expr, assumptions):
757
+ return True
758
+
759
+ @AlgebraicPredicate.register_many(ComplexInfinity, Exp1, Infinity, # type:ignore
760
+ NegativeInfinity, Pi)
761
+ def _(expr, assumptions):
762
+ return False
763
+
764
+ @AlgebraicPredicate.register_many(Add, Mul) # type:ignore
765
+ def _(expr, assumptions):
766
+ return test_closed_group(expr, assumptions, Q.algebraic)
767
+
768
+ @AlgebraicPredicate.register(Pow) # type:ignore
769
+ def _(expr, assumptions):
770
+ if expr.base == E:
771
+ if ask(Q.algebraic(expr.exp), assumptions):
772
+ return ask(~Q.nonzero(expr.exp), assumptions)
773
+ return
774
+ if expr.base == pi:
775
+ if ask(Q.integer(expr.exp), assumptions) and ask(Q.positive(expr.exp), assumptions):
776
+ return False
777
+ return
778
+ exp_rational = ask(Q.rational(expr.exp), assumptions)
779
+ base_algebraic = ask(Q.algebraic(expr.base), assumptions)
780
+ exp_algebraic = ask(Q.algebraic(expr.exp),assumptions)
781
+ if base_algebraic and exp_algebraic:
782
+ if exp_rational:
783
+ return True
784
+ # Check based on the Gelfond-Schneider theorem:
785
+ # If the base is algebraic and not equal to 0 or 1, and the exponent
786
+ # is irrational,then the result is transcendental.
787
+ if ask(Q.ne(expr.base,0) & Q.ne(expr.base,1)) and exp_rational is False:
788
+ return False
789
+
790
+ @AlgebraicPredicate.register(Rational) # type:ignore
791
+ def _(expr, assumptions):
792
+ return expr.q != 0
793
+
794
+ @AlgebraicPredicate.register_many(asin, atan, cos, sin, tan) # type:ignore
795
+ def _(expr, assumptions):
796
+ x = expr.args[0]
797
+ if ask(Q.algebraic(x), assumptions):
798
+ return ask(~Q.nonzero(x), assumptions)
799
+
800
+ @AlgebraicPredicate.register(exp) # type:ignore
801
+ def _(expr, assumptions):
802
+ x = expr.exp
803
+ if ask(Q.algebraic(x), assumptions):
804
+ return ask(~Q.nonzero(x), assumptions)
805
+
806
+ @AlgebraicPredicate.register_many(acot, cot) # type:ignore
807
+ def _(expr, assumptions):
808
+ x = expr.args[0]
809
+ if ask(Q.algebraic(x), assumptions):
810
+ return False
811
+
812
+ @AlgebraicPredicate.register_many(acos, log) # type:ignore
813
+ def _(expr, assumptions):
814
+ x = expr.args[0]
815
+ if ask(Q.algebraic(x), assumptions):
816
+ return ask(~Q.nonzero(x - 1), assumptions)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/predicates/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """
2
+ Module to implement predicate classes.
3
+
4
+ Class of every predicate registered to ``Q`` is defined here.
5
+ """
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/predicates/calculus.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.assumptions import Predicate
2
+ from sympy.multipledispatch import Dispatcher
3
+
4
+ class FinitePredicate(Predicate):
5
+ """
6
+ Finite number predicate.
7
+
8
+ Explanation
9
+ ===========
10
+
11
+ ``Q.finite(x)`` is true if ``x`` is a number but neither an infinity
12
+ nor a ``NaN``. In other words, ``ask(Q.finite(x))`` is true for all
13
+ numerical ``x`` having a bounded absolute value.
14
+
15
+ Examples
16
+ ========
17
+
18
+ >>> from sympy import Q, ask, S, oo, I, zoo
19
+ >>> from sympy.abc import x
20
+ >>> ask(Q.finite(oo))
21
+ False
22
+ >>> ask(Q.finite(-oo))
23
+ False
24
+ >>> ask(Q.finite(zoo))
25
+ False
26
+ >>> ask(Q.finite(1))
27
+ True
28
+ >>> ask(Q.finite(2 + 3*I))
29
+ True
30
+ >>> ask(Q.finite(x), Q.positive(x))
31
+ True
32
+ >>> print(ask(Q.finite(S.NaN)))
33
+ None
34
+
35
+ References
36
+ ==========
37
+
38
+ .. [1] https://en.wikipedia.org/wiki/Finite
39
+
40
+ """
41
+ name = 'finite'
42
+ handler = Dispatcher(
43
+ "FiniteHandler",
44
+ doc=("Handler for Q.finite. Test that an expression is bounded respect"
45
+ " to all its variables.")
46
+ )
47
+
48
+
49
+ class InfinitePredicate(Predicate):
50
+ """
51
+ Infinite number predicate.
52
+
53
+ ``Q.infinite(x)`` is true iff the absolute value of ``x`` is
54
+ infinity.
55
+
56
+ """
57
+ # TODO: Add examples
58
+ name = 'infinite'
59
+ handler = Dispatcher(
60
+ "InfiniteHandler",
61
+ doc="""Handler for Q.infinite key."""
62
+ )
63
+
64
+
65
+ class PositiveInfinitePredicate(Predicate):
66
+ """
67
+ Positive infinity predicate.
68
+
69
+ ``Q.positive_infinite(x)`` is true iff ``x`` is positive infinity ``oo``.
70
+ """
71
+ name = 'positive_infinite'
72
+ handler = Dispatcher("PositiveInfiniteHandler")
73
+
74
+
75
+ class NegativeInfinitePredicate(Predicate):
76
+ """
77
+ Negative infinity predicate.
78
+
79
+ ``Q.negative_infinite(x)`` is true iff ``x`` is negative infinity ``-oo``.
80
+ """
81
+ name = 'negative_infinite'
82
+ handler = Dispatcher("NegativeInfiniteHandler")
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/predicates/common.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.assumptions import Predicate, AppliedPredicate, Q
2
+ from sympy.core.relational import Eq, Ne, Gt, Lt, Ge, Le
3
+ from sympy.multipledispatch import Dispatcher
4
+
5
+
6
+ class CommutativePredicate(Predicate):
7
+ """
8
+ Commutative predicate.
9
+
10
+ Explanation
11
+ ===========
12
+
13
+ ``ask(Q.commutative(x))`` is true iff ``x`` commutes with any other
14
+ object with respect to multiplication operation.
15
+
16
+ """
17
+ # TODO: Add examples
18
+ name = 'commutative'
19
+ handler = Dispatcher("CommutativeHandler", doc="Handler for key 'commutative'.")
20
+
21
+
22
+ binrelpreds = {Eq: Q.eq, Ne: Q.ne, Gt: Q.gt, Lt: Q.lt, Ge: Q.ge, Le: Q.le}
23
+
24
+ class IsTruePredicate(Predicate):
25
+ """
26
+ Generic predicate.
27
+
28
+ Explanation
29
+ ===========
30
+
31
+ ``ask(Q.is_true(x))`` is true iff ``x`` is true. This only makes
32
+ sense if ``x`` is a boolean object.
33
+
34
+ Examples
35
+ ========
36
+
37
+ >>> from sympy import ask, Q
38
+ >>> from sympy.abc import x, y
39
+ >>> ask(Q.is_true(True))
40
+ True
41
+
42
+ Wrapping another applied predicate just returns the applied predicate.
43
+
44
+ >>> Q.is_true(Q.even(x))
45
+ Q.even(x)
46
+
47
+ Wrapping binary relation classes in SymPy core returns applied binary
48
+ relational predicates.
49
+
50
+ >>> from sympy import Eq, Gt
51
+ >>> Q.is_true(Eq(x, y))
52
+ Q.eq(x, y)
53
+ >>> Q.is_true(Gt(x, y))
54
+ Q.gt(x, y)
55
+
56
+ Notes
57
+ =====
58
+
59
+ This class is designed to wrap the boolean objects so that they can
60
+ behave as if they are applied predicates. Consequently, wrapping another
61
+ applied predicate is unnecessary and thus it just returns the argument.
62
+ Also, binary relation classes in SymPy core have binary predicates to
63
+ represent themselves and thus wrapping them with ``Q.is_true`` converts them
64
+ to these applied predicates.
65
+
66
+ """
67
+ name = 'is_true'
68
+ handler = Dispatcher(
69
+ "IsTrueHandler",
70
+ doc="Wrapper allowing to query the truth value of a boolean expression."
71
+ )
72
+
73
+ def __call__(self, arg):
74
+ # No need to wrap another predicate
75
+ if isinstance(arg, AppliedPredicate):
76
+ return arg
77
+ # Convert relational predicates instead of wrapping them
78
+ if getattr(arg, "is_Relational", False):
79
+ pred = binrelpreds[type(arg)]
80
+ return pred(*arg.args)
81
+ return super().__call__(arg)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/predicates/matrices.py ADDED
@@ -0,0 +1,511 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.assumptions import Predicate
2
+ from sympy.multipledispatch import Dispatcher
3
+
4
+ class SquarePredicate(Predicate):
5
+ """
6
+ Square matrix predicate.
7
+
8
+ Explanation
9
+ ===========
10
+
11
+ ``Q.square(x)`` is true iff ``x`` is a square matrix. A square matrix
12
+ is a matrix with the same number of rows and columns.
13
+
14
+ Examples
15
+ ========
16
+
17
+ >>> from sympy import Q, ask, MatrixSymbol, ZeroMatrix, Identity
18
+ >>> X = MatrixSymbol('X', 2, 2)
19
+ >>> Y = MatrixSymbol('X', 2, 3)
20
+ >>> ask(Q.square(X))
21
+ True
22
+ >>> ask(Q.square(Y))
23
+ False
24
+ >>> ask(Q.square(ZeroMatrix(3, 3)))
25
+ True
26
+ >>> ask(Q.square(Identity(3)))
27
+ True
28
+
29
+ References
30
+ ==========
31
+
32
+ .. [1] https://en.wikipedia.org/wiki/Square_matrix
33
+
34
+ """
35
+ name = 'square'
36
+ handler = Dispatcher("SquareHandler", doc="Handler for Q.square.")
37
+
38
+
39
+ class SymmetricPredicate(Predicate):
40
+ """
41
+ Symmetric matrix predicate.
42
+
43
+ Explanation
44
+ ===========
45
+
46
+ ``Q.symmetric(x)`` is true iff ``x`` is a square matrix and is equal to
47
+ its transpose. Every square diagonal matrix is a symmetric matrix.
48
+
49
+ Examples
50
+ ========
51
+
52
+ >>> from sympy import Q, ask, MatrixSymbol
53
+ >>> X = MatrixSymbol('X', 2, 2)
54
+ >>> Y = MatrixSymbol('Y', 2, 3)
55
+ >>> Z = MatrixSymbol('Z', 2, 2)
56
+ >>> ask(Q.symmetric(X*Z), Q.symmetric(X) & Q.symmetric(Z))
57
+ True
58
+ >>> ask(Q.symmetric(X + Z), Q.symmetric(X) & Q.symmetric(Z))
59
+ True
60
+ >>> ask(Q.symmetric(Y))
61
+ False
62
+
63
+
64
+ References
65
+ ==========
66
+
67
+ .. [1] https://en.wikipedia.org/wiki/Symmetric_matrix
68
+
69
+ """
70
+ # TODO: Add handlers to make these keys work with
71
+ # actual matrices and add more examples in the docstring.
72
+ name = 'symmetric'
73
+ handler = Dispatcher("SymmetricHandler", doc="Handler for Q.symmetric.")
74
+
75
+
76
+ class InvertiblePredicate(Predicate):
77
+ """
78
+ Invertible matrix predicate.
79
+
80
+ Explanation
81
+ ===========
82
+
83
+ ``Q.invertible(x)`` is true iff ``x`` is an invertible matrix.
84
+ A square matrix is called invertible only if its determinant is 0.
85
+
86
+ Examples
87
+ ========
88
+
89
+ >>> from sympy import Q, ask, MatrixSymbol
90
+ >>> X = MatrixSymbol('X', 2, 2)
91
+ >>> Y = MatrixSymbol('Y', 2, 3)
92
+ >>> Z = MatrixSymbol('Z', 2, 2)
93
+ >>> ask(Q.invertible(X*Y), Q.invertible(X))
94
+ False
95
+ >>> ask(Q.invertible(X*Z), Q.invertible(X) & Q.invertible(Z))
96
+ True
97
+ >>> ask(Q.invertible(X), Q.fullrank(X) & Q.square(X))
98
+ True
99
+
100
+ References
101
+ ==========
102
+
103
+ .. [1] https://en.wikipedia.org/wiki/Invertible_matrix
104
+
105
+ """
106
+ name = 'invertible'
107
+ handler = Dispatcher("InvertibleHandler", doc="Handler for Q.invertible.")
108
+
109
+
110
+ class OrthogonalPredicate(Predicate):
111
+ """
112
+ Orthogonal matrix predicate.
113
+
114
+ Explanation
115
+ ===========
116
+
117
+ ``Q.orthogonal(x)`` is true iff ``x`` is an orthogonal matrix.
118
+ A square matrix ``M`` is an orthogonal matrix if it satisfies
119
+ ``M^TM = MM^T = I`` where ``M^T`` is the transpose matrix of
120
+ ``M`` and ``I`` is an identity matrix. Note that an orthogonal
121
+ matrix is necessarily invertible.
122
+
123
+ Examples
124
+ ========
125
+
126
+ >>> from sympy import Q, ask, MatrixSymbol, Identity
127
+ >>> X = MatrixSymbol('X', 2, 2)
128
+ >>> Y = MatrixSymbol('Y', 2, 3)
129
+ >>> Z = MatrixSymbol('Z', 2, 2)
130
+ >>> ask(Q.orthogonal(Y))
131
+ False
132
+ >>> ask(Q.orthogonal(X*Z*X), Q.orthogonal(X) & Q.orthogonal(Z))
133
+ True
134
+ >>> ask(Q.orthogonal(Identity(3)))
135
+ True
136
+ >>> ask(Q.invertible(X), Q.orthogonal(X))
137
+ True
138
+
139
+ References
140
+ ==========
141
+
142
+ .. [1] https://en.wikipedia.org/wiki/Orthogonal_matrix
143
+
144
+ """
145
+ name = 'orthogonal'
146
+ handler = Dispatcher("OrthogonalHandler", doc="Handler for key 'orthogonal'.")
147
+
148
+
149
+ class UnitaryPredicate(Predicate):
150
+ """
151
+ Unitary matrix predicate.
152
+
153
+ Explanation
154
+ ===========
155
+
156
+ ``Q.unitary(x)`` is true iff ``x`` is a unitary matrix.
157
+ Unitary matrix is an analogue to orthogonal matrix. A square
158
+ matrix ``M`` with complex elements is unitary if :math:``M^TM = MM^T= I``
159
+ where :math:``M^T`` is the conjugate transpose matrix of ``M``.
160
+
161
+ Examples
162
+ ========
163
+
164
+ >>> from sympy import Q, ask, MatrixSymbol, Identity
165
+ >>> X = MatrixSymbol('X', 2, 2)
166
+ >>> Y = MatrixSymbol('Y', 2, 3)
167
+ >>> Z = MatrixSymbol('Z', 2, 2)
168
+ >>> ask(Q.unitary(Y))
169
+ False
170
+ >>> ask(Q.unitary(X*Z*X), Q.unitary(X) & Q.unitary(Z))
171
+ True
172
+ >>> ask(Q.unitary(Identity(3)))
173
+ True
174
+
175
+ References
176
+ ==========
177
+
178
+ .. [1] https://en.wikipedia.org/wiki/Unitary_matrix
179
+
180
+ """
181
+ name = 'unitary'
182
+ handler = Dispatcher("UnitaryHandler", doc="Handler for key 'unitary'.")
183
+
184
+
185
+ class FullRankPredicate(Predicate):
186
+ """
187
+ Fullrank matrix predicate.
188
+
189
+ Explanation
190
+ ===========
191
+
192
+ ``Q.fullrank(x)`` is true iff ``x`` is a full rank matrix.
193
+ A matrix is full rank if all rows and columns of the matrix
194
+ are linearly independent. A square matrix is full rank iff
195
+ its determinant is nonzero.
196
+
197
+ Examples
198
+ ========
199
+
200
+ >>> from sympy import Q, ask, MatrixSymbol, ZeroMatrix, Identity
201
+ >>> X = MatrixSymbol('X', 2, 2)
202
+ >>> ask(Q.fullrank(X.T), Q.fullrank(X))
203
+ True
204
+ >>> ask(Q.fullrank(ZeroMatrix(3, 3)))
205
+ False
206
+ >>> ask(Q.fullrank(Identity(3)))
207
+ True
208
+
209
+ """
210
+ name = 'fullrank'
211
+ handler = Dispatcher("FullRankHandler", doc="Handler for key 'fullrank'.")
212
+
213
+
214
+ class PositiveDefinitePredicate(Predicate):
215
+ r"""
216
+ Positive definite matrix predicate.
217
+
218
+ Explanation
219
+ ===========
220
+
221
+ If $M$ is a :math:`n \times n` symmetric real matrix, it is said
222
+ to be positive definite if :math:`Z^TMZ` is positive for
223
+ every non-zero column vector $Z$ of $n$ real numbers.
224
+
225
+ Examples
226
+ ========
227
+
228
+ >>> from sympy import Q, ask, MatrixSymbol, Identity
229
+ >>> X = MatrixSymbol('X', 2, 2)
230
+ >>> Y = MatrixSymbol('Y', 2, 3)
231
+ >>> Z = MatrixSymbol('Z', 2, 2)
232
+ >>> ask(Q.positive_definite(Y))
233
+ False
234
+ >>> ask(Q.positive_definite(Identity(3)))
235
+ True
236
+ >>> ask(Q.positive_definite(X + Z), Q.positive_definite(X) &
237
+ ... Q.positive_definite(Z))
238
+ True
239
+
240
+ References
241
+ ==========
242
+
243
+ .. [1] https://en.wikipedia.org/wiki/Positive-definite_matrix
244
+
245
+ """
246
+ name = "positive_definite"
247
+ handler = Dispatcher("PositiveDefiniteHandler", doc="Handler for key 'positive_definite'.")
248
+
249
+
250
+ class UpperTriangularPredicate(Predicate):
251
+ """
252
+ Upper triangular matrix predicate.
253
+
254
+ Explanation
255
+ ===========
256
+
257
+ A matrix $M$ is called upper triangular matrix if :math:`M_{ij}=0`
258
+ for :math:`i<j`.
259
+
260
+ Examples
261
+ ========
262
+
263
+ >>> from sympy import Q, ask, ZeroMatrix, Identity
264
+ >>> ask(Q.upper_triangular(Identity(3)))
265
+ True
266
+ >>> ask(Q.upper_triangular(ZeroMatrix(3, 3)))
267
+ True
268
+
269
+ References
270
+ ==========
271
+
272
+ .. [1] https://mathworld.wolfram.com/UpperTriangularMatrix.html
273
+
274
+ """
275
+ name = "upper_triangular"
276
+ handler = Dispatcher("UpperTriangularHandler", doc="Handler for key 'upper_triangular'.")
277
+
278
+
279
+ class LowerTriangularPredicate(Predicate):
280
+ """
281
+ Lower triangular matrix predicate.
282
+
283
+ Explanation
284
+ ===========
285
+
286
+ A matrix $M$ is called lower triangular matrix if :math:`M_{ij}=0`
287
+ for :math:`i>j`.
288
+
289
+ Examples
290
+ ========
291
+
292
+ >>> from sympy import Q, ask, ZeroMatrix, Identity
293
+ >>> ask(Q.lower_triangular(Identity(3)))
294
+ True
295
+ >>> ask(Q.lower_triangular(ZeroMatrix(3, 3)))
296
+ True
297
+
298
+ References
299
+ ==========
300
+
301
+ .. [1] https://mathworld.wolfram.com/LowerTriangularMatrix.html
302
+
303
+ """
304
+ name = "lower_triangular"
305
+ handler = Dispatcher("LowerTriangularHandler", doc="Handler for key 'lower_triangular'.")
306
+
307
+
308
+ class DiagonalPredicate(Predicate):
309
+ """
310
+ Diagonal matrix predicate.
311
+
312
+ Explanation
313
+ ===========
314
+
315
+ ``Q.diagonal(x)`` is true iff ``x`` is a diagonal matrix. A diagonal
316
+ matrix is a matrix in which the entries outside the main diagonal
317
+ are all zero.
318
+
319
+ Examples
320
+ ========
321
+
322
+ >>> from sympy import Q, ask, MatrixSymbol, ZeroMatrix
323
+ >>> X = MatrixSymbol('X', 2, 2)
324
+ >>> ask(Q.diagonal(ZeroMatrix(3, 3)))
325
+ True
326
+ >>> ask(Q.diagonal(X), Q.lower_triangular(X) &
327
+ ... Q.upper_triangular(X))
328
+ True
329
+
330
+ References
331
+ ==========
332
+
333
+ .. [1] https://en.wikipedia.org/wiki/Diagonal_matrix
334
+
335
+ """
336
+ name = "diagonal"
337
+ handler = Dispatcher("DiagonalHandler", doc="Handler for key 'diagonal'.")
338
+
339
+
340
+ class IntegerElementsPredicate(Predicate):
341
+ """
342
+ Integer elements matrix predicate.
343
+
344
+ Explanation
345
+ ===========
346
+
347
+ ``Q.integer_elements(x)`` is true iff all the elements of ``x``
348
+ are integers.
349
+
350
+ Examples
351
+ ========
352
+
353
+ >>> from sympy import Q, ask, MatrixSymbol
354
+ >>> X = MatrixSymbol('X', 4, 4)
355
+ >>> ask(Q.integer(X[1, 2]), Q.integer_elements(X))
356
+ True
357
+
358
+ """
359
+ name = "integer_elements"
360
+ handler = Dispatcher("IntegerElementsHandler", doc="Handler for key 'integer_elements'.")
361
+
362
+
363
+ class RealElementsPredicate(Predicate):
364
+ """
365
+ Real elements matrix predicate.
366
+
367
+ Explanation
368
+ ===========
369
+
370
+ ``Q.real_elements(x)`` is true iff all the elements of ``x``
371
+ are real numbers.
372
+
373
+ Examples
374
+ ========
375
+
376
+ >>> from sympy import Q, ask, MatrixSymbol
377
+ >>> X = MatrixSymbol('X', 4, 4)
378
+ >>> ask(Q.real(X[1, 2]), Q.real_elements(X))
379
+ True
380
+
381
+ """
382
+ name = "real_elements"
383
+ handler = Dispatcher("RealElementsHandler", doc="Handler for key 'real_elements'.")
384
+
385
+
386
+ class ComplexElementsPredicate(Predicate):
387
+ """
388
+ Complex elements matrix predicate.
389
+
390
+ Explanation
391
+ ===========
392
+
393
+ ``Q.complex_elements(x)`` is true iff all the elements of ``x``
394
+ are complex numbers.
395
+
396
+ Examples
397
+ ========
398
+
399
+ >>> from sympy import Q, ask, MatrixSymbol
400
+ >>> X = MatrixSymbol('X', 4, 4)
401
+ >>> ask(Q.complex(X[1, 2]), Q.complex_elements(X))
402
+ True
403
+ >>> ask(Q.complex_elements(X), Q.integer_elements(X))
404
+ True
405
+
406
+ """
407
+ name = "complex_elements"
408
+ handler = Dispatcher("ComplexElementsHandler", doc="Handler for key 'complex_elements'.")
409
+
410
+
411
+ class SingularPredicate(Predicate):
412
+ """
413
+ Singular matrix predicate.
414
+
415
+ A matrix is singular iff the value of its determinant is 0.
416
+
417
+ Examples
418
+ ========
419
+
420
+ >>> from sympy import Q, ask, MatrixSymbol
421
+ >>> X = MatrixSymbol('X', 4, 4)
422
+ >>> ask(Q.singular(X), Q.invertible(X))
423
+ False
424
+ >>> ask(Q.singular(X), ~Q.invertible(X))
425
+ True
426
+
427
+ References
428
+ ==========
429
+
430
+ .. [1] https://mathworld.wolfram.com/SingularMatrix.html
431
+
432
+ """
433
+ name = "singular"
434
+ handler = Dispatcher("SingularHandler", doc="Predicate fore key 'singular'.")
435
+
436
+
437
+ class NormalPredicate(Predicate):
438
+ """
439
+ Normal matrix predicate.
440
+
441
+ A matrix is normal if it commutes with its conjugate transpose.
442
+
443
+ Examples
444
+ ========
445
+
446
+ >>> from sympy import Q, ask, MatrixSymbol
447
+ >>> X = MatrixSymbol('X', 4, 4)
448
+ >>> ask(Q.normal(X), Q.unitary(X))
449
+ True
450
+
451
+ References
452
+ ==========
453
+
454
+ .. [1] https://en.wikipedia.org/wiki/Normal_matrix
455
+
456
+ """
457
+ name = "normal"
458
+ handler = Dispatcher("NormalHandler", doc="Predicate fore key 'normal'.")
459
+
460
+
461
+ class TriangularPredicate(Predicate):
462
+ """
463
+ Triangular matrix predicate.
464
+
465
+ Explanation
466
+ ===========
467
+
468
+ ``Q.triangular(X)`` is true if ``X`` is one that is either lower
469
+ triangular or upper triangular.
470
+
471
+ Examples
472
+ ========
473
+
474
+ >>> from sympy import Q, ask, MatrixSymbol
475
+ >>> X = MatrixSymbol('X', 4, 4)
476
+ >>> ask(Q.triangular(X), Q.upper_triangular(X))
477
+ True
478
+ >>> ask(Q.triangular(X), Q.lower_triangular(X))
479
+ True
480
+
481
+ References
482
+ ==========
483
+
484
+ .. [1] https://en.wikipedia.org/wiki/Triangular_matrix
485
+
486
+ """
487
+ name = "triangular"
488
+ handler = Dispatcher("TriangularHandler", doc="Predicate fore key 'triangular'.")
489
+
490
+
491
+ class UnitTriangularPredicate(Predicate):
492
+ """
493
+ Unit triangular matrix predicate.
494
+
495
+ Explanation
496
+ ===========
497
+
498
+ A unit triangular matrix is a triangular matrix with 1s
499
+ on the diagonal.
500
+
501
+ Examples
502
+ ========
503
+
504
+ >>> from sympy import Q, ask, MatrixSymbol
505
+ >>> X = MatrixSymbol('X', 4, 4)
506
+ >>> ask(Q.triangular(X), Q.unit_triangular(X))
507
+ True
508
+
509
+ """
510
+ name = "unit_triangular"
511
+ handler = Dispatcher("UnitTriangularHandler", doc="Predicate fore key 'unit_triangular'.")
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/predicates/ntheory.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.assumptions import Predicate
2
+ from sympy.multipledispatch import Dispatcher
3
+
4
+
5
+ class PrimePredicate(Predicate):
6
+ """
7
+ Prime number predicate.
8
+
9
+ Explanation
10
+ ===========
11
+
12
+ ``ask(Q.prime(x))`` is true iff ``x`` is a natural number greater
13
+ than 1 that has no positive divisors other than ``1`` and the
14
+ number itself.
15
+
16
+ Examples
17
+ ========
18
+
19
+ >>> from sympy import Q, ask
20
+ >>> ask(Q.prime(0))
21
+ False
22
+ >>> ask(Q.prime(1))
23
+ False
24
+ >>> ask(Q.prime(2))
25
+ True
26
+ >>> ask(Q.prime(20))
27
+ False
28
+ >>> ask(Q.prime(-3))
29
+ False
30
+
31
+ """
32
+ name = 'prime'
33
+ handler = Dispatcher(
34
+ "PrimeHandler",
35
+ doc=("Handler for key 'prime'. Test that an expression represents a prime"
36
+ " number. When the expression is an exact number, the result (when True)"
37
+ " is subject to the limitations of isprime() which is used to return the "
38
+ "result.")
39
+ )
40
+
41
+
42
+ class CompositePredicate(Predicate):
43
+ """
44
+ Composite number predicate.
45
+
46
+ Explanation
47
+ ===========
48
+
49
+ ``ask(Q.composite(x))`` is true iff ``x`` is a positive integer and has
50
+ at least one positive divisor other than ``1`` and the number itself.
51
+
52
+ Examples
53
+ ========
54
+
55
+ >>> from sympy import Q, ask
56
+ >>> ask(Q.composite(0))
57
+ False
58
+ >>> ask(Q.composite(1))
59
+ False
60
+ >>> ask(Q.composite(2))
61
+ False
62
+ >>> ask(Q.composite(20))
63
+ True
64
+
65
+ """
66
+ name = 'composite'
67
+ handler = Dispatcher("CompositeHandler", doc="Handler for key 'composite'.")
68
+
69
+
70
+ class EvenPredicate(Predicate):
71
+ """
72
+ Even number predicate.
73
+
74
+ Explanation
75
+ ===========
76
+
77
+ ``ask(Q.even(x))`` is true iff ``x`` belongs to the set of even
78
+ integers.
79
+
80
+ Examples
81
+ ========
82
+
83
+ >>> from sympy import Q, ask, pi
84
+ >>> ask(Q.even(0))
85
+ True
86
+ >>> ask(Q.even(2))
87
+ True
88
+ >>> ask(Q.even(3))
89
+ False
90
+ >>> ask(Q.even(pi))
91
+ False
92
+
93
+ """
94
+ name = 'even'
95
+ handler = Dispatcher("EvenHandler", doc="Handler for key 'even'.")
96
+
97
+
98
+ class OddPredicate(Predicate):
99
+ """
100
+ Odd number predicate.
101
+
102
+ Explanation
103
+ ===========
104
+
105
+ ``ask(Q.odd(x))`` is true iff ``x`` belongs to the set of odd numbers.
106
+
107
+ Examples
108
+ ========
109
+
110
+ >>> from sympy import Q, ask, pi
111
+ >>> ask(Q.odd(0))
112
+ False
113
+ >>> ask(Q.odd(2))
114
+ False
115
+ >>> ask(Q.odd(3))
116
+ True
117
+ >>> ask(Q.odd(pi))
118
+ False
119
+
120
+ """
121
+ name = 'odd'
122
+ handler = Dispatcher(
123
+ "OddHandler",
124
+ doc=("Handler for key 'odd'. Test that an expression represents an odd"
125
+ " number.")
126
+ )
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/predicates/order.py ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.assumptions import Predicate
2
+ from sympy.multipledispatch import Dispatcher
3
+
4
+
5
+ class NegativePredicate(Predicate):
6
+ r"""
7
+ Negative number predicate.
8
+
9
+ Explanation
10
+ ===========
11
+
12
+ ``Q.negative(x)`` is true iff ``x`` is a real number and :math:`x < 0`, that is,
13
+ it is in the interval :math:`(-\infty, 0)`. Note in particular that negative
14
+ infinity is not negative.
15
+
16
+ A few important facts about negative numbers:
17
+
18
+ - Note that ``Q.nonnegative`` and ``~Q.negative`` are *not* the same
19
+ thing. ``~Q.negative(x)`` simply means that ``x`` is not negative,
20
+ whereas ``Q.nonnegative(x)`` means that ``x`` is real and not
21
+ negative, i.e., ``Q.nonnegative(x)`` is logically equivalent to
22
+ ``Q.zero(x) | Q.positive(x)``. So for example, ``~Q.negative(I)`` is
23
+ true, whereas ``Q.nonnegative(I)`` is false.
24
+
25
+ - See the documentation of ``Q.real`` for more information about
26
+ related facts.
27
+
28
+ Examples
29
+ ========
30
+
31
+ >>> from sympy import Q, ask, symbols, I
32
+ >>> x = symbols('x')
33
+ >>> ask(Q.negative(x), Q.real(x) & ~Q.positive(x) & ~Q.zero(x))
34
+ True
35
+ >>> ask(Q.negative(-1))
36
+ True
37
+ >>> ask(Q.nonnegative(I))
38
+ False
39
+ >>> ask(~Q.negative(I))
40
+ True
41
+
42
+ """
43
+ name = 'negative'
44
+ handler = Dispatcher(
45
+ "NegativeHandler",
46
+ doc=("Handler for Q.negative. Test that an expression is strictly less"
47
+ " than zero.")
48
+ )
49
+
50
+
51
+ class NonNegativePredicate(Predicate):
52
+ """
53
+ Nonnegative real number predicate.
54
+
55
+ Explanation
56
+ ===========
57
+
58
+ ``ask(Q.nonnegative(x))`` is true iff ``x`` belongs to the set of
59
+ positive numbers including zero.
60
+
61
+ - Note that ``Q.nonnegative`` and ``~Q.negative`` are *not* the same
62
+ thing. ``~Q.negative(x)`` simply means that ``x`` is not negative,
63
+ whereas ``Q.nonnegative(x)`` means that ``x`` is real and not
64
+ negative, i.e., ``Q.nonnegative(x)`` is logically equivalent to
65
+ ``Q.zero(x) | Q.positive(x)``. So for example, ``~Q.negative(I)`` is
66
+ true, whereas ``Q.nonnegative(I)`` is false.
67
+
68
+ Examples
69
+ ========
70
+
71
+ >>> from sympy import Q, ask, I
72
+ >>> ask(Q.nonnegative(1))
73
+ True
74
+ >>> ask(Q.nonnegative(0))
75
+ True
76
+ >>> ask(Q.nonnegative(-1))
77
+ False
78
+ >>> ask(Q.nonnegative(I))
79
+ False
80
+ >>> ask(Q.nonnegative(-I))
81
+ False
82
+
83
+ """
84
+ name = 'nonnegative'
85
+ handler = Dispatcher(
86
+ "NonNegativeHandler",
87
+ doc=("Handler for Q.nonnegative.")
88
+ )
89
+
90
+
91
+ class NonZeroPredicate(Predicate):
92
+ """
93
+ Nonzero real number predicate.
94
+
95
+ Explanation
96
+ ===========
97
+
98
+ ``ask(Q.nonzero(x))`` is true iff ``x`` is real and ``x`` is not zero. Note in
99
+ particular that ``Q.nonzero(x)`` is false if ``x`` is not real. Use
100
+ ``~Q.zero(x)`` if you want the negation of being zero without any real
101
+ assumptions.
102
+
103
+ A few important facts about nonzero numbers:
104
+
105
+ - ``Q.nonzero`` is logically equivalent to ``Q.positive | Q.negative``.
106
+
107
+ - See the documentation of ``Q.real`` for more information about
108
+ related facts.
109
+
110
+ Examples
111
+ ========
112
+
113
+ >>> from sympy import Q, ask, symbols, I, oo
114
+ >>> x = symbols('x')
115
+ >>> print(ask(Q.nonzero(x), ~Q.zero(x)))
116
+ None
117
+ >>> ask(Q.nonzero(x), Q.positive(x))
118
+ True
119
+ >>> ask(Q.nonzero(x), Q.zero(x))
120
+ False
121
+ >>> ask(Q.nonzero(0))
122
+ False
123
+ >>> ask(Q.nonzero(I))
124
+ False
125
+ >>> ask(~Q.zero(I))
126
+ True
127
+ >>> ask(Q.nonzero(oo))
128
+ False
129
+
130
+ """
131
+ name = 'nonzero'
132
+ handler = Dispatcher(
133
+ "NonZeroHandler",
134
+ doc=("Handler for key 'nonzero'. Test that an expression is not identically"
135
+ " zero.")
136
+ )
137
+
138
+
139
+ class ZeroPredicate(Predicate):
140
+ """
141
+ Zero number predicate.
142
+
143
+ Explanation
144
+ ===========
145
+
146
+ ``ask(Q.zero(x))`` is true iff the value of ``x`` is zero.
147
+
148
+ Examples
149
+ ========
150
+
151
+ >>> from sympy import ask, Q, oo, symbols
152
+ >>> x, y = symbols('x, y')
153
+ >>> ask(Q.zero(0))
154
+ True
155
+ >>> ask(Q.zero(1/oo))
156
+ True
157
+ >>> print(ask(Q.zero(0*oo)))
158
+ None
159
+ >>> ask(Q.zero(1))
160
+ False
161
+ >>> ask(Q.zero(x*y), Q.zero(x) | Q.zero(y))
162
+ True
163
+
164
+ """
165
+ name = 'zero'
166
+ handler = Dispatcher(
167
+ "ZeroHandler",
168
+ doc="Handler for key 'zero'."
169
+ )
170
+
171
+
172
+ class NonPositivePredicate(Predicate):
173
+ """
174
+ Nonpositive real number predicate.
175
+
176
+ Explanation
177
+ ===========
178
+
179
+ ``ask(Q.nonpositive(x))`` is true iff ``x`` belongs to the set of
180
+ negative numbers including zero.
181
+
182
+ - Note that ``Q.nonpositive`` and ``~Q.positive`` are *not* the same
183
+ thing. ``~Q.positive(x)`` simply means that ``x`` is not positive,
184
+ whereas ``Q.nonpositive(x)`` means that ``x`` is real and not
185
+ positive, i.e., ``Q.nonpositive(x)`` is logically equivalent to
186
+ `Q.negative(x) | Q.zero(x)``. So for example, ``~Q.positive(I)`` is
187
+ true, whereas ``Q.nonpositive(I)`` is false.
188
+
189
+ Examples
190
+ ========
191
+
192
+ >>> from sympy import Q, ask, I
193
+
194
+ >>> ask(Q.nonpositive(-1))
195
+ True
196
+ >>> ask(Q.nonpositive(0))
197
+ True
198
+ >>> ask(Q.nonpositive(1))
199
+ False
200
+ >>> ask(Q.nonpositive(I))
201
+ False
202
+ >>> ask(Q.nonpositive(-I))
203
+ False
204
+
205
+ """
206
+ name = 'nonpositive'
207
+ handler = Dispatcher(
208
+ "NonPositiveHandler",
209
+ doc="Handler for key 'nonpositive'."
210
+ )
211
+
212
+
213
+ class PositivePredicate(Predicate):
214
+ r"""
215
+ Positive real number predicate.
216
+
217
+ Explanation
218
+ ===========
219
+
220
+ ``Q.positive(x)`` is true iff ``x`` is real and `x > 0`, that is if ``x``
221
+ is in the interval `(0, \infty)`. In particular, infinity is not
222
+ positive.
223
+
224
+ A few important facts about positive numbers:
225
+
226
+ - Note that ``Q.nonpositive`` and ``~Q.positive`` are *not* the same
227
+ thing. ``~Q.positive(x)`` simply means that ``x`` is not positive,
228
+ whereas ``Q.nonpositive(x)`` means that ``x`` is real and not
229
+ positive, i.e., ``Q.nonpositive(x)`` is logically equivalent to
230
+ `Q.negative(x) | Q.zero(x)``. So for example, ``~Q.positive(I)`` is
231
+ true, whereas ``Q.nonpositive(I)`` is false.
232
+
233
+ - See the documentation of ``Q.real`` for more information about
234
+ related facts.
235
+
236
+ Examples
237
+ ========
238
+
239
+ >>> from sympy import Q, ask, symbols, I
240
+ >>> x = symbols('x')
241
+ >>> ask(Q.positive(x), Q.real(x) & ~Q.negative(x) & ~Q.zero(x))
242
+ True
243
+ >>> ask(Q.positive(1))
244
+ True
245
+ >>> ask(Q.nonpositive(I))
246
+ False
247
+ >>> ask(~Q.positive(I))
248
+ True
249
+
250
+ """
251
+ name = 'positive'
252
+ handler = Dispatcher(
253
+ "PositiveHandler",
254
+ doc=("Handler for key 'positive'. Test that an expression is strictly"
255
+ " greater than zero.")
256
+ )
257
+
258
+
259
+ class ExtendedPositivePredicate(Predicate):
260
+ r"""
261
+ Positive extended real number predicate.
262
+
263
+ Explanation
264
+ ===========
265
+
266
+ ``Q.extended_positive(x)`` is true iff ``x`` is extended real and
267
+ `x > 0`, that is if ``x`` is in the interval `(0, \infty]`.
268
+
269
+ Examples
270
+ ========
271
+
272
+ >>> from sympy import ask, I, oo, Q
273
+ >>> ask(Q.extended_positive(1))
274
+ True
275
+ >>> ask(Q.extended_positive(oo))
276
+ True
277
+ >>> ask(Q.extended_positive(I))
278
+ False
279
+
280
+ """
281
+ name = 'extended_positive'
282
+ handler = Dispatcher("ExtendedPositiveHandler")
283
+
284
+
285
+ class ExtendedNegativePredicate(Predicate):
286
+ r"""
287
+ Negative extended real number predicate.
288
+
289
+ Explanation
290
+ ===========
291
+
292
+ ``Q.extended_negative(x)`` is true iff ``x`` is extended real and
293
+ `x < 0`, that is if ``x`` is in the interval `[-\infty, 0)`.
294
+
295
+ Examples
296
+ ========
297
+
298
+ >>> from sympy import ask, I, oo, Q
299
+ >>> ask(Q.extended_negative(-1))
300
+ True
301
+ >>> ask(Q.extended_negative(-oo))
302
+ True
303
+ >>> ask(Q.extended_negative(-I))
304
+ False
305
+
306
+ """
307
+ name = 'extended_negative'
308
+ handler = Dispatcher("ExtendedNegativeHandler")
309
+
310
+
311
+ class ExtendedNonZeroPredicate(Predicate):
312
+ """
313
+ Nonzero extended real number predicate.
314
+
315
+ Explanation
316
+ ===========
317
+
318
+ ``ask(Q.extended_nonzero(x))`` is true iff ``x`` is extended real and
319
+ ``x`` is not zero.
320
+
321
+ Examples
322
+ ========
323
+
324
+ >>> from sympy import ask, I, oo, Q
325
+ >>> ask(Q.extended_nonzero(-1))
326
+ True
327
+ >>> ask(Q.extended_nonzero(oo))
328
+ True
329
+ >>> ask(Q.extended_nonzero(I))
330
+ False
331
+
332
+ """
333
+ name = 'extended_nonzero'
334
+ handler = Dispatcher("ExtendedNonZeroHandler")
335
+
336
+
337
+ class ExtendedNonPositivePredicate(Predicate):
338
+ """
339
+ Nonpositive extended real number predicate.
340
+
341
+ Explanation
342
+ ===========
343
+
344
+ ``ask(Q.extended_nonpositive(x))`` is true iff ``x`` is extended real and
345
+ ``x`` is not positive.
346
+
347
+ Examples
348
+ ========
349
+
350
+ >>> from sympy import ask, I, oo, Q
351
+ >>> ask(Q.extended_nonpositive(-1))
352
+ True
353
+ >>> ask(Q.extended_nonpositive(oo))
354
+ False
355
+ >>> ask(Q.extended_nonpositive(0))
356
+ True
357
+ >>> ask(Q.extended_nonpositive(I))
358
+ False
359
+
360
+ """
361
+ name = 'extended_nonpositive'
362
+ handler = Dispatcher("ExtendedNonPositiveHandler")
363
+
364
+
365
+ class ExtendedNonNegativePredicate(Predicate):
366
+ """
367
+ Nonnegative extended real number predicate.
368
+
369
+ Explanation
370
+ ===========
371
+
372
+ ``ask(Q.extended_nonnegative(x))`` is true iff ``x`` is extended real and
373
+ ``x`` is not negative.
374
+
375
+ Examples
376
+ ========
377
+
378
+ >>> from sympy import ask, I, oo, Q
379
+ >>> ask(Q.extended_nonnegative(-1))
380
+ False
381
+ >>> ask(Q.extended_nonnegative(oo))
382
+ True
383
+ >>> ask(Q.extended_nonnegative(0))
384
+ True
385
+ >>> ask(Q.extended_nonnegative(I))
386
+ False
387
+
388
+ """
389
+ name = 'extended_nonnegative'
390
+ handler = Dispatcher("ExtendedNonNegativeHandler")
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/predicates/sets.py ADDED
@@ -0,0 +1,399 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.assumptions import Predicate
2
+ from sympy.multipledispatch import Dispatcher
3
+
4
+
5
+ class IntegerPredicate(Predicate):
6
+ """
7
+ Integer predicate.
8
+
9
+ Explanation
10
+ ===========
11
+
12
+ ``Q.integer(x)`` is true iff ``x`` belongs to the set of integer
13
+ numbers.
14
+
15
+ Examples
16
+ ========
17
+
18
+ >>> from sympy import Q, ask, S
19
+ >>> ask(Q.integer(5))
20
+ True
21
+ >>> ask(Q.integer(S(1)/2))
22
+ False
23
+
24
+ References
25
+ ==========
26
+
27
+ .. [1] https://en.wikipedia.org/wiki/Integer
28
+
29
+ """
30
+ name = 'integer'
31
+ handler = Dispatcher(
32
+ "IntegerHandler",
33
+ doc=("Handler for Q.integer.\n\n"
34
+ "Test that an expression belongs to the field of integer numbers.")
35
+ )
36
+
37
+
38
+ class NonIntegerPredicate(Predicate):
39
+ """
40
+ Non-integer extended real predicate.
41
+ """
42
+ name = 'noninteger'
43
+ handler = Dispatcher(
44
+ "NonIntegerHandler",
45
+ doc=("Handler for Q.noninteger.\n\n"
46
+ "Test that an expression is a non-integer extended real number.")
47
+ )
48
+
49
+
50
+ class RationalPredicate(Predicate):
51
+ """
52
+ Rational number predicate.
53
+
54
+ Explanation
55
+ ===========
56
+
57
+ ``Q.rational(x)`` is true iff ``x`` belongs to the set of
58
+ rational numbers.
59
+
60
+ Examples
61
+ ========
62
+
63
+ >>> from sympy import ask, Q, pi, S
64
+ >>> ask(Q.rational(0))
65
+ True
66
+ >>> ask(Q.rational(S(1)/2))
67
+ True
68
+ >>> ask(Q.rational(pi))
69
+ False
70
+
71
+ References
72
+ ==========
73
+
74
+ .. [1] https://en.wikipedia.org/wiki/Rational_number
75
+
76
+ """
77
+ name = 'rational'
78
+ handler = Dispatcher(
79
+ "RationalHandler",
80
+ doc=("Handler for Q.rational.\n\n"
81
+ "Test that an expression belongs to the field of rational numbers.")
82
+ )
83
+
84
+
85
+ class IrrationalPredicate(Predicate):
86
+ """
87
+ Irrational number predicate.
88
+
89
+ Explanation
90
+ ===========
91
+
92
+ ``Q.irrational(x)`` is true iff ``x`` is any real number that
93
+ cannot be expressed as a ratio of integers.
94
+
95
+ Examples
96
+ ========
97
+
98
+ >>> from sympy import ask, Q, pi, S, I
99
+ >>> ask(Q.irrational(0))
100
+ False
101
+ >>> ask(Q.irrational(S(1)/2))
102
+ False
103
+ >>> ask(Q.irrational(pi))
104
+ True
105
+ >>> ask(Q.irrational(I))
106
+ False
107
+
108
+ References
109
+ ==========
110
+
111
+ .. [1] https://en.wikipedia.org/wiki/Irrational_number
112
+
113
+ """
114
+ name = 'irrational'
115
+ handler = Dispatcher(
116
+ "IrrationalHandler",
117
+ doc=("Handler for Q.irrational.\n\n"
118
+ "Test that an expression is irrational numbers.")
119
+ )
120
+
121
+
122
+ class RealPredicate(Predicate):
123
+ r"""
124
+ Real number predicate.
125
+
126
+ Explanation
127
+ ===========
128
+
129
+ ``Q.real(x)`` is true iff ``x`` is a real number, i.e., it is in the
130
+ interval `(-\infty, \infty)`. Note that, in particular the
131
+ infinities are not real. Use ``Q.extended_real`` if you want to
132
+ consider those as well.
133
+
134
+ A few important facts about reals:
135
+
136
+ - Every real number is positive, negative, or zero. Furthermore,
137
+ because these sets are pairwise disjoint, each real number is
138
+ exactly one of those three.
139
+
140
+ - Every real number is also complex.
141
+
142
+ - Every real number is finite.
143
+
144
+ - Every real number is either rational or irrational.
145
+
146
+ - Every real number is either algebraic or transcendental.
147
+
148
+ - The facts ``Q.negative``, ``Q.zero``, ``Q.positive``,
149
+ ``Q.nonnegative``, ``Q.nonpositive``, ``Q.nonzero``,
150
+ ``Q.integer``, ``Q.rational``, and ``Q.irrational`` all imply
151
+ ``Q.real``, as do all facts that imply those facts.
152
+
153
+ - The facts ``Q.algebraic``, and ``Q.transcendental`` do not imply
154
+ ``Q.real``; they imply ``Q.complex``. An algebraic or
155
+ transcendental number may or may not be real.
156
+
157
+ - The "non" facts (i.e., ``Q.nonnegative``, ``Q.nonzero``,
158
+ ``Q.nonpositive`` and ``Q.noninteger``) are not equivalent to
159
+ not the fact, but rather, not the fact *and* ``Q.real``.
160
+ For example, ``Q.nonnegative`` means ``~Q.negative & Q.real``.
161
+ So for example, ``I`` is not nonnegative, nonzero, or
162
+ nonpositive.
163
+
164
+ Examples
165
+ ========
166
+
167
+ >>> from sympy import Q, ask, symbols
168
+ >>> x = symbols('x')
169
+ >>> ask(Q.real(x), Q.positive(x))
170
+ True
171
+ >>> ask(Q.real(0))
172
+ True
173
+
174
+ References
175
+ ==========
176
+
177
+ .. [1] https://en.wikipedia.org/wiki/Real_number
178
+
179
+ """
180
+ name = 'real'
181
+ handler = Dispatcher(
182
+ "RealHandler",
183
+ doc=("Handler for Q.real.\n\n"
184
+ "Test that an expression belongs to the field of real numbers.")
185
+ )
186
+
187
+
188
+ class ExtendedRealPredicate(Predicate):
189
+ r"""
190
+ Extended real predicate.
191
+
192
+ Explanation
193
+ ===========
194
+
195
+ ``Q.extended_real(x)`` is true iff ``x`` is a real number or
196
+ `\{-\infty, \infty\}`.
197
+
198
+ See documentation of ``Q.real`` for more information about related
199
+ facts.
200
+
201
+ Examples
202
+ ========
203
+
204
+ >>> from sympy import ask, Q, oo, I
205
+ >>> ask(Q.extended_real(1))
206
+ True
207
+ >>> ask(Q.extended_real(I))
208
+ False
209
+ >>> ask(Q.extended_real(oo))
210
+ True
211
+
212
+ """
213
+ name = 'extended_real'
214
+ handler = Dispatcher(
215
+ "ExtendedRealHandler",
216
+ doc=("Handler for Q.extended_real.\n\n"
217
+ "Test that an expression belongs to the field of extended real\n"
218
+ "numbers, that is real numbers union {Infinity, -Infinity}.")
219
+ )
220
+
221
+
222
+ class HermitianPredicate(Predicate):
223
+ """
224
+ Hermitian predicate.
225
+
226
+ Explanation
227
+ ===========
228
+
229
+ ``ask(Q.hermitian(x))`` is true iff ``x`` belongs to the set of
230
+ Hermitian operators.
231
+
232
+ References
233
+ ==========
234
+
235
+ .. [1] https://mathworld.wolfram.com/HermitianOperator.html
236
+
237
+ """
238
+ # TODO: Add examples
239
+ name = 'hermitian'
240
+ handler = Dispatcher(
241
+ "HermitianHandler",
242
+ doc=("Handler for Q.hermitian.\n\n"
243
+ "Test that an expression belongs to the field of Hermitian operators.")
244
+ )
245
+
246
+
247
+ class ComplexPredicate(Predicate):
248
+ """
249
+ Complex number predicate.
250
+
251
+ Explanation
252
+ ===========
253
+
254
+ ``Q.complex(x)`` is true iff ``x`` belongs to the set of complex
255
+ numbers. Note that every complex number is finite.
256
+
257
+ Examples
258
+ ========
259
+
260
+ >>> from sympy import Q, Symbol, ask, I, oo
261
+ >>> x = Symbol('x')
262
+ >>> ask(Q.complex(0))
263
+ True
264
+ >>> ask(Q.complex(2 + 3*I))
265
+ True
266
+ >>> ask(Q.complex(oo))
267
+ False
268
+
269
+ References
270
+ ==========
271
+
272
+ .. [1] https://en.wikipedia.org/wiki/Complex_number
273
+
274
+ """
275
+ name = 'complex'
276
+ handler = Dispatcher(
277
+ "ComplexHandler",
278
+ doc=("Handler for Q.complex.\n\n"
279
+ "Test that an expression belongs to the field of complex numbers.")
280
+ )
281
+
282
+
283
+ class ImaginaryPredicate(Predicate):
284
+ """
285
+ Imaginary number predicate.
286
+
287
+ Explanation
288
+ ===========
289
+
290
+ ``Q.imaginary(x)`` is true iff ``x`` can be written as a real
291
+ number multiplied by the imaginary unit ``I``. Please note that ``0``
292
+ is not considered to be an imaginary number.
293
+
294
+ Examples
295
+ ========
296
+
297
+ >>> from sympy import Q, ask, I
298
+ >>> ask(Q.imaginary(3*I))
299
+ True
300
+ >>> ask(Q.imaginary(2 + 3*I))
301
+ False
302
+ >>> ask(Q.imaginary(0))
303
+ False
304
+
305
+ References
306
+ ==========
307
+
308
+ .. [1] https://en.wikipedia.org/wiki/Imaginary_number
309
+
310
+ """
311
+ name = 'imaginary'
312
+ handler = Dispatcher(
313
+ "ImaginaryHandler",
314
+ doc=("Handler for Q.imaginary.\n\n"
315
+ "Test that an expression belongs to the field of imaginary numbers,\n"
316
+ "that is, numbers in the form x*I, where x is real.")
317
+ )
318
+
319
+
320
+ class AntihermitianPredicate(Predicate):
321
+ """
322
+ Antihermitian predicate.
323
+
324
+ Explanation
325
+ ===========
326
+
327
+ ``Q.antihermitian(x)`` is true iff ``x`` belongs to the field of
328
+ antihermitian operators, i.e., operators in the form ``x*I``, where
329
+ ``x`` is Hermitian.
330
+
331
+ References
332
+ ==========
333
+
334
+ .. [1] https://mathworld.wolfram.com/HermitianOperator.html
335
+
336
+ """
337
+ # TODO: Add examples
338
+ name = 'antihermitian'
339
+ handler = Dispatcher(
340
+ "AntiHermitianHandler",
341
+ doc=("Handler for Q.antihermitian.\n\n"
342
+ "Test that an expression belongs to the field of anti-Hermitian\n"
343
+ "operators, that is, operators in the form x*I, where x is Hermitian.")
344
+ )
345
+
346
+
347
+ class AlgebraicPredicate(Predicate):
348
+ r"""
349
+ Algebraic number predicate.
350
+
351
+ Explanation
352
+ ===========
353
+
354
+ ``Q.algebraic(x)`` is true iff ``x`` belongs to the set of
355
+ algebraic numbers. ``x`` is algebraic if there is some polynomial
356
+ in ``p(x)\in \mathbb\{Q\}[x]`` such that ``p(x) = 0``.
357
+
358
+ Examples
359
+ ========
360
+
361
+ >>> from sympy import ask, Q, sqrt, I, pi
362
+ >>> ask(Q.algebraic(sqrt(2)))
363
+ True
364
+ >>> ask(Q.algebraic(I))
365
+ True
366
+ >>> ask(Q.algebraic(pi))
367
+ False
368
+
369
+ References
370
+ ==========
371
+
372
+ .. [1] https://en.wikipedia.org/wiki/Algebraic_number
373
+
374
+ """
375
+ name = 'algebraic'
376
+ AlgebraicHandler = Dispatcher(
377
+ "AlgebraicHandler",
378
+ doc="""Handler for Q.algebraic key."""
379
+ )
380
+
381
+
382
+ class TranscendentalPredicate(Predicate):
383
+ """
384
+ Transcedental number predicate.
385
+
386
+ Explanation
387
+ ===========
388
+
389
+ ``Q.transcendental(x)`` is true iff ``x`` belongs to the set of
390
+ transcendental numbers. A transcendental number is a real
391
+ or complex number that is not algebraic.
392
+
393
+ """
394
+ # TODO: Add examples
395
+ name = 'transcendental'
396
+ handler = Dispatcher(
397
+ "Transcendental",
398
+ doc="""Handler for Q.transcendental key."""
399
+ )
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/relation/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A module to implement finitary relations [1] as predicate.
3
+
4
+ References
5
+ ==========
6
+
7
+ .. [1] https://en.wikipedia.org/wiki/Finitary_relation
8
+
9
+ """
10
+
11
+ __all__ = ['BinaryRelation', 'AppliedBinaryRelation']
12
+
13
+ from .binrel import BinaryRelation, AppliedBinaryRelation
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/relation/binrel.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ General binary relations.
3
+ """
4
+ from typing import Optional
5
+
6
+ from sympy.core.singleton import S
7
+ from sympy.assumptions import AppliedPredicate, ask, Predicate, Q # type: ignore
8
+ from sympy.core.kind import BooleanKind
9
+ from sympy.core.relational import Eq, Ne, Gt, Lt, Ge, Le
10
+ from sympy.logic.boolalg import conjuncts, Not
11
+
12
+ __all__ = ["BinaryRelation", "AppliedBinaryRelation"]
13
+
14
+
15
+ class BinaryRelation(Predicate):
16
+ """
17
+ Base class for all binary relational predicates.
18
+
19
+ Explanation
20
+ ===========
21
+
22
+ Binary relation takes two arguments and returns ``AppliedBinaryRelation``
23
+ instance. To evaluate it to boolean value, use :obj:`~.ask()` or
24
+ :obj:`~.refine()` function.
25
+
26
+ You can add support for new types by registering the handler to dispatcher.
27
+ See :obj:`~.Predicate()` for more information about predicate dispatching.
28
+
29
+ Examples
30
+ ========
31
+
32
+ Applying and evaluating to boolean value:
33
+
34
+ >>> from sympy import Q, ask, sin, cos
35
+ >>> from sympy.abc import x
36
+ >>> Q.eq(sin(x)**2+cos(x)**2, 1)
37
+ Q.eq(sin(x)**2 + cos(x)**2, 1)
38
+ >>> ask(_)
39
+ True
40
+
41
+ You can define a new binary relation by subclassing and dispatching.
42
+ Here, we define a relation $R$ such that $x R y$ returns true if
43
+ $x = y + 1$.
44
+
45
+ >>> from sympy import ask, Number, Q
46
+ >>> from sympy.assumptions import BinaryRelation
47
+ >>> class MyRel(BinaryRelation):
48
+ ... name = "R"
49
+ ... is_reflexive = False
50
+ >>> Q.R = MyRel()
51
+ >>> @Q.R.register(Number, Number)
52
+ ... def _(n1, n2, assumptions):
53
+ ... return ask(Q.zero(n1 - n2 - 1), assumptions)
54
+ >>> Q.R(2, 1)
55
+ Q.R(2, 1)
56
+
57
+ Now, we can use ``ask()`` to evaluate it to boolean value.
58
+
59
+ >>> ask(Q.R(2, 1))
60
+ True
61
+ >>> ask(Q.R(1, 2))
62
+ False
63
+
64
+ ``Q.R`` returns ``False`` with minimum cost if two arguments have same
65
+ structure because it is antireflexive relation [1] by
66
+ ``is_reflexive = False``.
67
+
68
+ >>> ask(Q.R(x, x))
69
+ False
70
+
71
+ References
72
+ ==========
73
+
74
+ .. [1] https://en.wikipedia.org/wiki/Reflexive_relation
75
+ """
76
+
77
+ is_reflexive: Optional[bool] = None
78
+ is_symmetric: Optional[bool] = None
79
+
80
+ def __call__(self, *args):
81
+ if not len(args) == 2:
82
+ raise ValueError("Binary relation takes two arguments, but got %s." % len(args))
83
+ return AppliedBinaryRelation(self, *args)
84
+
85
+ @property
86
+ def reversed(self):
87
+ if self.is_symmetric:
88
+ return self
89
+ return None
90
+
91
+ @property
92
+ def negated(self):
93
+ return None
94
+
95
+ def _compare_reflexive(self, lhs, rhs):
96
+ # quick exit for structurally same arguments
97
+ # do not check != here because it cannot catch the
98
+ # equivalent arguments with different structures.
99
+
100
+ # reflexivity does not hold to NaN
101
+ if lhs is S.NaN or rhs is S.NaN:
102
+ return None
103
+
104
+ reflexive = self.is_reflexive
105
+ if reflexive is None:
106
+ pass
107
+ elif reflexive and (lhs == rhs):
108
+ return True
109
+ elif not reflexive and (lhs == rhs):
110
+ return False
111
+ return None
112
+
113
+ def eval(self, args, assumptions=True):
114
+ # quick exit for structurally same arguments
115
+ ret = self._compare_reflexive(*args)
116
+ if ret is not None:
117
+ return ret
118
+
119
+ # don't perform simplify on args here. (done by AppliedBinaryRelation._eval_ask)
120
+ # evaluate by multipledispatch
121
+ lhs, rhs = args
122
+ ret = self.handler(lhs, rhs, assumptions=assumptions)
123
+ if ret is not None:
124
+ return ret
125
+
126
+ # check reversed order if the relation is reflexive
127
+ if self.is_reflexive:
128
+ types = (type(lhs), type(rhs))
129
+ if self.handler.dispatch(*types) is not self.handler.dispatch(*reversed(types)):
130
+ ret = self.handler(rhs, lhs, assumptions=assumptions)
131
+
132
+ return ret
133
+
134
+
135
+ class AppliedBinaryRelation(AppliedPredicate):
136
+ """
137
+ The class of expressions resulting from applying ``BinaryRelation``
138
+ to the arguments.
139
+
140
+ """
141
+
142
+ @property
143
+ def lhs(self):
144
+ """The left-hand side of the relation."""
145
+ return self.arguments[0]
146
+
147
+ @property
148
+ def rhs(self):
149
+ """The right-hand side of the relation."""
150
+ return self.arguments[1]
151
+
152
+ @property
153
+ def reversed(self):
154
+ """
155
+ Try to return the relationship with sides reversed.
156
+ """
157
+ revfunc = self.function.reversed
158
+ if revfunc is None:
159
+ return self
160
+ return revfunc(self.rhs, self.lhs)
161
+
162
+ @property
163
+ def reversedsign(self):
164
+ """
165
+ Try to return the relationship with signs reversed.
166
+ """
167
+ revfunc = self.function.reversed
168
+ if revfunc is None:
169
+ return self
170
+ if not any(side.kind is BooleanKind for side in self.arguments):
171
+ return revfunc(-self.lhs, -self.rhs)
172
+ return self
173
+
174
+ @property
175
+ def negated(self):
176
+ neg_rel = self.function.negated
177
+ if neg_rel is None:
178
+ return Not(self, evaluate=False)
179
+ return neg_rel(*self.arguments)
180
+
181
+ def _eval_ask(self, assumptions):
182
+ conj_assumps = set()
183
+ binrelpreds = {Eq: Q.eq, Ne: Q.ne, Gt: Q.gt, Lt: Q.lt, Ge: Q.ge, Le: Q.le}
184
+ for a in conjuncts(assumptions):
185
+ if a.func in binrelpreds:
186
+ conj_assumps.add(binrelpreds[type(a)](*a.args))
187
+ else:
188
+ conj_assumps.add(a)
189
+
190
+ # After CNF in assumptions module is modified to take polyadic
191
+ # predicate, this will be removed
192
+ if any(rel in conj_assumps for rel in (self, self.reversed)):
193
+ return True
194
+ neg_rels = (self.negated, self.reversed.negated, Not(self, evaluate=False),
195
+ Not(self.reversed, evaluate=False))
196
+ if any(rel in conj_assumps for rel in neg_rels):
197
+ return False
198
+
199
+ # evaluation using multipledispatching
200
+ ret = self.function.eval(self.arguments, assumptions)
201
+ if ret is not None:
202
+ return ret
203
+
204
+ # simplify the args and try again
205
+ args = tuple(a.simplify() for a in self.arguments)
206
+ return self.function.eval(args, assumptions)
207
+
208
+ def __bool__(self):
209
+ ret = ask(self)
210
+ if ret is None:
211
+ raise TypeError("Cannot determine truth value of %s" % self)
212
+ return ret
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/relation/equality.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Module for mathematical equality [1] and inequalities [2].
3
+
4
+ The purpose of this module is to provide the instances which represent the
5
+ binary predicates in order to combine the relationals into logical inference
6
+ system. Objects such as ``Q.eq``, ``Q.lt`` should remain internal to
7
+ assumptions module, and user must use the classes such as :obj:`~.Eq()`,
8
+ :obj:`~.Lt()` instead to construct the relational expressions.
9
+
10
+ References
11
+ ==========
12
+
13
+ .. [1] https://en.wikipedia.org/wiki/Equality_(mathematics)
14
+ .. [2] https://en.wikipedia.org/wiki/Inequality_(mathematics)
15
+ """
16
+ from sympy.assumptions import Q
17
+ from sympy.core.relational import is_eq, is_neq, is_gt, is_ge, is_lt, is_le
18
+
19
+ from .binrel import BinaryRelation
20
+
21
+ __all__ = ['EqualityPredicate', 'UnequalityPredicate', 'StrictGreaterThanPredicate',
22
+ 'GreaterThanPredicate', 'StrictLessThanPredicate', 'LessThanPredicate']
23
+
24
+
25
+ class EqualityPredicate(BinaryRelation):
26
+ """
27
+ Binary predicate for $=$.
28
+
29
+ The purpose of this class is to provide the instance which represent
30
+ the equality predicate in order to allow the logical inference.
31
+ This class must remain internal to assumptions module and user must
32
+ use :obj:`~.Eq()` instead to construct the equality expression.
33
+
34
+ Evaluating this predicate to ``True`` or ``False`` is done by
35
+ :func:`~.core.relational.is_eq`
36
+
37
+ Examples
38
+ ========
39
+
40
+ >>> from sympy import ask, Q
41
+ >>> Q.eq(0, 0)
42
+ Q.eq(0, 0)
43
+ >>> ask(_)
44
+ True
45
+
46
+ See Also
47
+ ========
48
+
49
+ sympy.core.relational.Eq
50
+
51
+ """
52
+ is_reflexive = True
53
+ is_symmetric = True
54
+
55
+ name = 'eq'
56
+ handler = None # Do not allow dispatching by this predicate
57
+
58
+ @property
59
+ def negated(self):
60
+ return Q.ne
61
+
62
+ def eval(self, args, assumptions=True):
63
+ if assumptions == True:
64
+ # default assumptions for is_eq is None
65
+ assumptions = None
66
+ return is_eq(*args, assumptions)
67
+
68
+
69
+ class UnequalityPredicate(BinaryRelation):
70
+ r"""
71
+ Binary predicate for $\neq$.
72
+
73
+ The purpose of this class is to provide the instance which represent
74
+ the inequation predicate in order to allow the logical inference.
75
+ This class must remain internal to assumptions module and user must
76
+ use :obj:`~.Ne()` instead to construct the inequation expression.
77
+
78
+ Evaluating this predicate to ``True`` or ``False`` is done by
79
+ :func:`~.core.relational.is_neq`
80
+
81
+ Examples
82
+ ========
83
+
84
+ >>> from sympy import ask, Q
85
+ >>> Q.ne(0, 0)
86
+ Q.ne(0, 0)
87
+ >>> ask(_)
88
+ False
89
+
90
+ See Also
91
+ ========
92
+
93
+ sympy.core.relational.Ne
94
+
95
+ """
96
+ is_reflexive = False
97
+ is_symmetric = True
98
+
99
+ name = 'ne'
100
+ handler = None
101
+
102
+ @property
103
+ def negated(self):
104
+ return Q.eq
105
+
106
+ def eval(self, args, assumptions=True):
107
+ if assumptions == True:
108
+ # default assumptions for is_neq is None
109
+ assumptions = None
110
+ return is_neq(*args, assumptions)
111
+
112
+
113
+ class StrictGreaterThanPredicate(BinaryRelation):
114
+ """
115
+ Binary predicate for $>$.
116
+
117
+ The purpose of this class is to provide the instance which represent
118
+ the ">" predicate in order to allow the logical inference.
119
+ This class must remain internal to assumptions module and user must
120
+ use :obj:`~.Gt()` instead to construct the equality expression.
121
+
122
+ Evaluating this predicate to ``True`` or ``False`` is done by
123
+ :func:`~.core.relational.is_gt`
124
+
125
+ Examples
126
+ ========
127
+
128
+ >>> from sympy import ask, Q
129
+ >>> Q.gt(0, 0)
130
+ Q.gt(0, 0)
131
+ >>> ask(_)
132
+ False
133
+
134
+ See Also
135
+ ========
136
+
137
+ sympy.core.relational.Gt
138
+
139
+ """
140
+ is_reflexive = False
141
+ is_symmetric = False
142
+
143
+ name = 'gt'
144
+ handler = None
145
+
146
+ @property
147
+ def reversed(self):
148
+ return Q.lt
149
+
150
+ @property
151
+ def negated(self):
152
+ return Q.le
153
+
154
+ def eval(self, args, assumptions=True):
155
+ if assumptions == True:
156
+ # default assumptions for is_gt is None
157
+ assumptions = None
158
+ return is_gt(*args, assumptions)
159
+
160
+
161
+ class GreaterThanPredicate(BinaryRelation):
162
+ """
163
+ Binary predicate for $>=$.
164
+
165
+ The purpose of this class is to provide the instance which represent
166
+ the ">=" predicate in order to allow the logical inference.
167
+ This class must remain internal to assumptions module and user must
168
+ use :obj:`~.Ge()` instead to construct the equality expression.
169
+
170
+ Evaluating this predicate to ``True`` or ``False`` is done by
171
+ :func:`~.core.relational.is_ge`
172
+
173
+ Examples
174
+ ========
175
+
176
+ >>> from sympy import ask, Q
177
+ >>> Q.ge(0, 0)
178
+ Q.ge(0, 0)
179
+ >>> ask(_)
180
+ True
181
+
182
+ See Also
183
+ ========
184
+
185
+ sympy.core.relational.Ge
186
+
187
+ """
188
+ is_reflexive = True
189
+ is_symmetric = False
190
+
191
+ name = 'ge'
192
+ handler = None
193
+
194
+ @property
195
+ def reversed(self):
196
+ return Q.le
197
+
198
+ @property
199
+ def negated(self):
200
+ return Q.lt
201
+
202
+ def eval(self, args, assumptions=True):
203
+ if assumptions == True:
204
+ # default assumptions for is_ge is None
205
+ assumptions = None
206
+ return is_ge(*args, assumptions)
207
+
208
+
209
+ class StrictLessThanPredicate(BinaryRelation):
210
+ """
211
+ Binary predicate for $<$.
212
+
213
+ The purpose of this class is to provide the instance which represent
214
+ the "<" predicate in order to allow the logical inference.
215
+ This class must remain internal to assumptions module and user must
216
+ use :obj:`~.Lt()` instead to construct the equality expression.
217
+
218
+ Evaluating this predicate to ``True`` or ``False`` is done by
219
+ :func:`~.core.relational.is_lt`
220
+
221
+ Examples
222
+ ========
223
+
224
+ >>> from sympy import ask, Q
225
+ >>> Q.lt(0, 0)
226
+ Q.lt(0, 0)
227
+ >>> ask(_)
228
+ False
229
+
230
+ See Also
231
+ ========
232
+
233
+ sympy.core.relational.Lt
234
+
235
+ """
236
+ is_reflexive = False
237
+ is_symmetric = False
238
+
239
+ name = 'lt'
240
+ handler = None
241
+
242
+ @property
243
+ def reversed(self):
244
+ return Q.gt
245
+
246
+ @property
247
+ def negated(self):
248
+ return Q.ge
249
+
250
+ def eval(self, args, assumptions=True):
251
+ if assumptions == True:
252
+ # default assumptions for is_lt is None
253
+ assumptions = None
254
+ return is_lt(*args, assumptions)
255
+
256
+
257
+ class LessThanPredicate(BinaryRelation):
258
+ """
259
+ Binary predicate for $<=$.
260
+
261
+ The purpose of this class is to provide the instance which represent
262
+ the "<=" predicate in order to allow the logical inference.
263
+ This class must remain internal to assumptions module and user must
264
+ use :obj:`~.Le()` instead to construct the equality expression.
265
+
266
+ Evaluating this predicate to ``True`` or ``False`` is done by
267
+ :func:`~.core.relational.is_le`
268
+
269
+ Examples
270
+ ========
271
+
272
+ >>> from sympy import ask, Q
273
+ >>> Q.le(0, 0)
274
+ Q.le(0, 0)
275
+ >>> ask(_)
276
+ True
277
+
278
+ See Also
279
+ ========
280
+
281
+ sympy.core.relational.Le
282
+
283
+ """
284
+ is_reflexive = True
285
+ is_symmetric = False
286
+
287
+ name = 'le'
288
+ handler = None
289
+
290
+ @property
291
+ def reversed(self):
292
+ return Q.ge
293
+
294
+ @property
295
+ def negated(self):
296
+ return Q.gt
297
+
298
+ def eval(self, args, assumptions=True):
299
+ if assumptions == True:
300
+ # default assumptions for is_le is None
301
+ assumptions = None
302
+ return is_le(*args, assumptions)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/tests/__init__.py ADDED
File without changes
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/tests/test_assumptions_2.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ rename this to test_assumptions.py when the old assumptions system is deleted
3
+ """
4
+ from sympy.abc import x, y
5
+ from sympy.assumptions.assume import global_assumptions
6
+ from sympy.assumptions.ask import Q
7
+ from sympy.printing import pretty
8
+
9
+
10
+ def test_equal():
11
+ """Test for equality"""
12
+ assert Q.positive(x) == Q.positive(x)
13
+ assert Q.positive(x) != ~Q.positive(x)
14
+ assert ~Q.positive(x) == ~Q.positive(x)
15
+
16
+
17
+ def test_pretty():
18
+ assert pretty(Q.positive(x)) == "Q.positive(x)"
19
+ assert pretty(
20
+ {Q.positive, Q.integer}) == "{Q.integer, Q.positive}"
21
+
22
+
23
+ def test_global():
24
+ """Test for global assumptions"""
25
+ global_assumptions.add(x > 0)
26
+ assert (x > 0) in global_assumptions
27
+ global_assumptions.remove(x > 0)
28
+ assert not (x > 0) in global_assumptions
29
+ # same with multiple of assumptions
30
+ global_assumptions.add(x > 0, y > 0)
31
+ assert (x > 0) in global_assumptions
32
+ assert (y > 0) in global_assumptions
33
+ global_assumptions.clear()
34
+ assert not (x > 0) in global_assumptions
35
+ assert not (y > 0) in global_assumptions
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/tests/test_context.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.assumptions import ask, Q
2
+ from sympy.assumptions.assume import assuming, global_assumptions
3
+ from sympy.abc import x, y
4
+
5
+ def test_assuming():
6
+ with assuming(Q.integer(x)):
7
+ assert ask(Q.integer(x))
8
+ assert not ask(Q.integer(x))
9
+
10
+ def test_assuming_nested():
11
+ assert not ask(Q.integer(x))
12
+ assert not ask(Q.integer(y))
13
+ with assuming(Q.integer(x)):
14
+ assert ask(Q.integer(x))
15
+ assert not ask(Q.integer(y))
16
+ with assuming(Q.integer(y)):
17
+ assert ask(Q.integer(x))
18
+ assert ask(Q.integer(y))
19
+ assert ask(Q.integer(x))
20
+ assert not ask(Q.integer(y))
21
+ assert not ask(Q.integer(x))
22
+ assert not ask(Q.integer(y))
23
+
24
+ def test_finally():
25
+ try:
26
+ with assuming(Q.integer(x)):
27
+ 1/0
28
+ except ZeroDivisionError:
29
+ pass
30
+ assert not ask(Q.integer(x))
31
+
32
+ def test_remove_safe():
33
+ global_assumptions.add(Q.integer(x))
34
+ with assuming():
35
+ assert ask(Q.integer(x))
36
+ global_assumptions.remove(Q.integer(x))
37
+ assert not ask(Q.integer(x))
38
+ assert ask(Q.integer(x))
39
+ global_assumptions.clear() # for the benefit of other tests
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/tests/test_matrices.py ADDED
@@ -0,0 +1,283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.assumptions.ask import (Q, ask)
2
+ from sympy.core.symbol import Symbol
3
+ from sympy.matrices.expressions.diagonal import (DiagMatrix, DiagonalMatrix)
4
+ from sympy.matrices.dense import Matrix
5
+ from sympy.matrices.expressions import (MatrixSymbol, Identity, ZeroMatrix,
6
+ OneMatrix, Trace, MatrixSlice, Determinant, BlockMatrix, BlockDiagMatrix)
7
+ from sympy.matrices.expressions.factorizations import LofLU
8
+ from sympy.testing.pytest import XFAIL
9
+
10
+ X = MatrixSymbol('X', 2, 2)
11
+ Y = MatrixSymbol('Y', 2, 3)
12
+ Z = MatrixSymbol('Z', 2, 2)
13
+ A1x1 = MatrixSymbol('A1x1', 1, 1)
14
+ B1x1 = MatrixSymbol('B1x1', 1, 1)
15
+ C0x0 = MatrixSymbol('C0x0', 0, 0)
16
+ V1 = MatrixSymbol('V1', 2, 1)
17
+ V2 = MatrixSymbol('V2', 2, 1)
18
+
19
+ def test_square():
20
+ assert ask(Q.square(X))
21
+ assert not ask(Q.square(Y))
22
+ assert ask(Q.square(Y*Y.T))
23
+
24
+ def test_invertible():
25
+ assert ask(Q.invertible(X), Q.invertible(X))
26
+ assert ask(Q.invertible(Y)) is False
27
+ assert ask(Q.invertible(X*Y), Q.invertible(X)) is False
28
+ assert ask(Q.invertible(X*Z), Q.invertible(X)) is None
29
+ assert ask(Q.invertible(X*Z), Q.invertible(X) & Q.invertible(Z)) is True
30
+ assert ask(Q.invertible(X.T)) is None
31
+ assert ask(Q.invertible(X.T), Q.invertible(X)) is True
32
+ assert ask(Q.invertible(X.I)) is True
33
+ assert ask(Q.invertible(Identity(3))) is True
34
+ assert ask(Q.invertible(ZeroMatrix(3, 3))) is False
35
+ assert ask(Q.invertible(OneMatrix(1, 1))) is True
36
+ assert ask(Q.invertible(OneMatrix(3, 3))) is False
37
+ assert ask(Q.invertible(X), Q.fullrank(X) & Q.square(X))
38
+
39
+ def test_singular():
40
+ assert ask(Q.singular(X)) is None
41
+ assert ask(Q.singular(X), Q.invertible(X)) is False
42
+ assert ask(Q.singular(X), ~Q.invertible(X)) is True
43
+
44
+ @XFAIL
45
+ def test_invertible_fullrank():
46
+ assert ask(Q.invertible(X), Q.fullrank(X)) is True
47
+
48
+
49
+ def test_invertible_BlockMatrix():
50
+ assert ask(Q.invertible(BlockMatrix([Identity(3)]))) == True
51
+ assert ask(Q.invertible(BlockMatrix([ZeroMatrix(3, 3)]))) == False
52
+
53
+ X = Matrix([[1, 2, 3], [3, 5, 4]])
54
+ Y = Matrix([[4, 2, 7], [2, 3, 5]])
55
+ # non-invertible A block
56
+ assert ask(Q.invertible(BlockMatrix([
57
+ [Matrix.ones(3, 3), Y.T],
58
+ [X, Matrix.eye(2)],
59
+ ]))) == True
60
+ # non-invertible B block
61
+ assert ask(Q.invertible(BlockMatrix([
62
+ [Y.T, Matrix.ones(3, 3)],
63
+ [Matrix.eye(2), X],
64
+ ]))) == True
65
+ # non-invertible C block
66
+ assert ask(Q.invertible(BlockMatrix([
67
+ [X, Matrix.eye(2)],
68
+ [Matrix.ones(3, 3), Y.T],
69
+ ]))) == True
70
+ # non-invertible D block
71
+ assert ask(Q.invertible(BlockMatrix([
72
+ [Matrix.eye(2), X],
73
+ [Y.T, Matrix.ones(3, 3)],
74
+ ]))) == True
75
+
76
+
77
+ def test_invertible_BlockDiagMatrix():
78
+ assert ask(Q.invertible(BlockDiagMatrix(Identity(3), Identity(5)))) == True
79
+ assert ask(Q.invertible(BlockDiagMatrix(ZeroMatrix(3, 3), Identity(5)))) == False
80
+ assert ask(Q.invertible(BlockDiagMatrix(Identity(3), OneMatrix(5, 5)))) == False
81
+
82
+
83
+ def test_symmetric():
84
+ assert ask(Q.symmetric(X), Q.symmetric(X))
85
+ assert ask(Q.symmetric(X*Z), Q.symmetric(X)) is None
86
+ assert ask(Q.symmetric(X*Z), Q.symmetric(X) & Q.symmetric(Z)) is True
87
+ assert ask(Q.symmetric(X + Z), Q.symmetric(X) & Q.symmetric(Z)) is True
88
+ assert ask(Q.symmetric(Y)) is False
89
+ assert ask(Q.symmetric(Y*Y.T)) is True
90
+ assert ask(Q.symmetric(Y.T*X*Y)) is None
91
+ assert ask(Q.symmetric(Y.T*X*Y), Q.symmetric(X)) is True
92
+ assert ask(Q.symmetric(X**10), Q.symmetric(X)) is True
93
+ assert ask(Q.symmetric(A1x1)) is True
94
+ assert ask(Q.symmetric(A1x1 + B1x1)) is True
95
+ assert ask(Q.symmetric(A1x1 * B1x1)) is True
96
+ assert ask(Q.symmetric(V1.T*V1)) is True
97
+ assert ask(Q.symmetric(V1.T*(V1 + V2))) is True
98
+ assert ask(Q.symmetric(V1.T*(V1 + V2) + A1x1)) is True
99
+ assert ask(Q.symmetric(MatrixSlice(Y, (0, 1), (1, 2)))) is True
100
+ assert ask(Q.symmetric(Identity(3))) is True
101
+ assert ask(Q.symmetric(ZeroMatrix(3, 3))) is True
102
+ assert ask(Q.symmetric(OneMatrix(3, 3))) is True
103
+
104
+ def _test_orthogonal_unitary(predicate):
105
+ assert ask(predicate(X), predicate(X))
106
+ assert ask(predicate(X.T), predicate(X)) is True
107
+ assert ask(predicate(X.I), predicate(X)) is True
108
+ assert ask(predicate(X**2), predicate(X))
109
+ assert ask(predicate(Y)) is False
110
+ assert ask(predicate(X)) is None
111
+ assert ask(predicate(X), ~Q.invertible(X)) is False
112
+ assert ask(predicate(X*Z*X), predicate(X) & predicate(Z)) is True
113
+ assert ask(predicate(Identity(3))) is True
114
+ assert ask(predicate(ZeroMatrix(3, 3))) is False
115
+ assert ask(Q.invertible(X), predicate(X))
116
+ assert not ask(predicate(X + Z), predicate(X) & predicate(Z))
117
+
118
+ def test_orthogonal():
119
+ _test_orthogonal_unitary(Q.orthogonal)
120
+
121
+ def test_unitary():
122
+ _test_orthogonal_unitary(Q.unitary)
123
+ assert ask(Q.unitary(X), Q.orthogonal(X))
124
+
125
+ def test_fullrank():
126
+ assert ask(Q.fullrank(X), Q.fullrank(X))
127
+ assert ask(Q.fullrank(X**2), Q.fullrank(X))
128
+ assert ask(Q.fullrank(X.T), Q.fullrank(X)) is True
129
+ assert ask(Q.fullrank(X)) is None
130
+ assert ask(Q.fullrank(Y)) is None
131
+ assert ask(Q.fullrank(X*Z), Q.fullrank(X) & Q.fullrank(Z)) is True
132
+ assert ask(Q.fullrank(Identity(3))) is True
133
+ assert ask(Q.fullrank(ZeroMatrix(3, 3))) is False
134
+ assert ask(Q.fullrank(OneMatrix(1, 1))) is True
135
+ assert ask(Q.fullrank(OneMatrix(3, 3))) is False
136
+ assert ask(Q.invertible(X), ~Q.fullrank(X)) == False
137
+
138
+
139
+ def test_positive_definite():
140
+ assert ask(Q.positive_definite(X), Q.positive_definite(X))
141
+ assert ask(Q.positive_definite(X.T), Q.positive_definite(X)) is True
142
+ assert ask(Q.positive_definite(X.I), Q.positive_definite(X)) is True
143
+ assert ask(Q.positive_definite(Y)) is False
144
+ assert ask(Q.positive_definite(X)) is None
145
+ assert ask(Q.positive_definite(X**3), Q.positive_definite(X))
146
+ assert ask(Q.positive_definite(X*Z*X),
147
+ Q.positive_definite(X) & Q.positive_definite(Z)) is True
148
+ assert ask(Q.positive_definite(X), Q.orthogonal(X))
149
+ assert ask(Q.positive_definite(Y.T*X*Y),
150
+ Q.positive_definite(X) & Q.fullrank(Y)) is True
151
+ assert not ask(Q.positive_definite(Y.T*X*Y), Q.positive_definite(X))
152
+ assert ask(Q.positive_definite(Identity(3))) is True
153
+ assert ask(Q.positive_definite(ZeroMatrix(3, 3))) is False
154
+ assert ask(Q.positive_definite(OneMatrix(1, 1))) is True
155
+ assert ask(Q.positive_definite(OneMatrix(3, 3))) is False
156
+ assert ask(Q.positive_definite(X + Z), Q.positive_definite(X) &
157
+ Q.positive_definite(Z)) is True
158
+ assert not ask(Q.positive_definite(-X), Q.positive_definite(X))
159
+ assert ask(Q.positive(X[1, 1]), Q.positive_definite(X))
160
+
161
+ def test_triangular():
162
+ assert ask(Q.upper_triangular(X + Z.T + Identity(2)), Q.upper_triangular(X) &
163
+ Q.lower_triangular(Z)) is True
164
+ assert ask(Q.upper_triangular(X*Z.T), Q.upper_triangular(X) &
165
+ Q.lower_triangular(Z)) is True
166
+ assert ask(Q.lower_triangular(Identity(3))) is True
167
+ assert ask(Q.lower_triangular(ZeroMatrix(3, 3))) is True
168
+ assert ask(Q.upper_triangular(ZeroMatrix(3, 3))) is True
169
+ assert ask(Q.lower_triangular(OneMatrix(1, 1))) is True
170
+ assert ask(Q.upper_triangular(OneMatrix(1, 1))) is True
171
+ assert ask(Q.lower_triangular(OneMatrix(3, 3))) is False
172
+ assert ask(Q.upper_triangular(OneMatrix(3, 3))) is False
173
+ assert ask(Q.triangular(X), Q.unit_triangular(X))
174
+ assert ask(Q.upper_triangular(X**3), Q.upper_triangular(X))
175
+ assert ask(Q.lower_triangular(X**3), Q.lower_triangular(X))
176
+
177
+
178
+ def test_diagonal():
179
+ assert ask(Q.diagonal(X + Z.T + Identity(2)), Q.diagonal(X) &
180
+ Q.diagonal(Z)) is True
181
+ assert ask(Q.diagonal(ZeroMatrix(3, 3)))
182
+ assert ask(Q.diagonal(OneMatrix(1, 1))) is True
183
+ assert ask(Q.diagonal(OneMatrix(3, 3))) is False
184
+ assert ask(Q.lower_triangular(X) & Q.upper_triangular(X), Q.diagonal(X))
185
+ assert ask(Q.diagonal(X), Q.lower_triangular(X) & Q.upper_triangular(X))
186
+ assert ask(Q.symmetric(X), Q.diagonal(X))
187
+ assert ask(Q.triangular(X), Q.diagonal(X))
188
+ assert ask(Q.diagonal(C0x0))
189
+ assert ask(Q.diagonal(A1x1))
190
+ assert ask(Q.diagonal(A1x1 + B1x1))
191
+ assert ask(Q.diagonal(A1x1*B1x1))
192
+ assert ask(Q.diagonal(V1.T*V2))
193
+ assert ask(Q.diagonal(V1.T*(X + Z)*V1))
194
+ assert ask(Q.diagonal(MatrixSlice(Y, (0, 1), (1, 2)))) is True
195
+ assert ask(Q.diagonal(V1.T*(V1 + V2))) is True
196
+ assert ask(Q.diagonal(X**3), Q.diagonal(X))
197
+ assert ask(Q.diagonal(Identity(3)))
198
+ assert ask(Q.diagonal(DiagMatrix(V1)))
199
+ assert ask(Q.diagonal(DiagonalMatrix(X)))
200
+
201
+
202
+ def test_non_atoms():
203
+ assert ask(Q.real(Trace(X)), Q.positive(Trace(X)))
204
+
205
+ @XFAIL
206
+ def test_non_trivial_implies():
207
+ X = MatrixSymbol('X', 3, 3)
208
+ Y = MatrixSymbol('Y', 3, 3)
209
+ assert ask(Q.lower_triangular(X+Y), Q.lower_triangular(X) &
210
+ Q.lower_triangular(Y)) is True
211
+ assert ask(Q.triangular(X), Q.lower_triangular(X)) is True
212
+ assert ask(Q.triangular(X+Y), Q.lower_triangular(X) &
213
+ Q.lower_triangular(Y)) is True
214
+
215
+ def test_MatrixSlice():
216
+ X = MatrixSymbol('X', 4, 4)
217
+ B = MatrixSlice(X, (1, 3), (1, 3))
218
+ C = MatrixSlice(X, (0, 3), (1, 3))
219
+ assert ask(Q.symmetric(B), Q.symmetric(X))
220
+ assert ask(Q.invertible(B), Q.invertible(X))
221
+ assert ask(Q.diagonal(B), Q.diagonal(X))
222
+ assert ask(Q.orthogonal(B), Q.orthogonal(X))
223
+ assert ask(Q.upper_triangular(B), Q.upper_triangular(X))
224
+
225
+ assert not ask(Q.symmetric(C), Q.symmetric(X))
226
+ assert not ask(Q.invertible(C), Q.invertible(X))
227
+ assert not ask(Q.diagonal(C), Q.diagonal(X))
228
+ assert not ask(Q.orthogonal(C), Q.orthogonal(X))
229
+ assert not ask(Q.upper_triangular(C), Q.upper_triangular(X))
230
+
231
+ def test_det_trace_positive():
232
+ X = MatrixSymbol('X', 4, 4)
233
+ assert ask(Q.positive(Trace(X)), Q.positive_definite(X))
234
+ assert ask(Q.positive(Determinant(X)), Q.positive_definite(X))
235
+
236
+ def test_field_assumptions():
237
+ X = MatrixSymbol('X', 4, 4)
238
+ Y = MatrixSymbol('Y', 4, 4)
239
+ assert ask(Q.real_elements(X), Q.real_elements(X))
240
+ assert not ask(Q.integer_elements(X), Q.real_elements(X))
241
+ assert ask(Q.complex_elements(X), Q.real_elements(X))
242
+ assert ask(Q.complex_elements(X**2), Q.real_elements(X))
243
+ assert ask(Q.real_elements(X**2), Q.integer_elements(X))
244
+ assert ask(Q.real_elements(X+Y), Q.real_elements(X)) is None
245
+ assert ask(Q.real_elements(X+Y), Q.real_elements(X) & Q.real_elements(Y))
246
+ from sympy.matrices.expressions.hadamard import HadamardProduct
247
+ assert ask(Q.real_elements(HadamardProduct(X, Y)),
248
+ Q.real_elements(X) & Q.real_elements(Y))
249
+ assert ask(Q.complex_elements(X+Y), Q.real_elements(X) & Q.complex_elements(Y))
250
+
251
+ assert ask(Q.real_elements(X.T), Q.real_elements(X))
252
+ assert ask(Q.real_elements(X.I), Q.real_elements(X) & Q.invertible(X))
253
+ assert ask(Q.real_elements(Trace(X)), Q.real_elements(X))
254
+ assert ask(Q.integer_elements(Determinant(X)), Q.integer_elements(X))
255
+ assert not ask(Q.integer_elements(X.I), Q.integer_elements(X))
256
+ alpha = Symbol('alpha')
257
+ assert ask(Q.real_elements(alpha*X), Q.real_elements(X) & Q.real(alpha))
258
+ assert ask(Q.real_elements(LofLU(X)), Q.real_elements(X))
259
+ e = Symbol('e', integer=True, negative=True)
260
+ assert ask(Q.real_elements(X**e), Q.real_elements(X) & Q.invertible(X))
261
+ assert ask(Q.real_elements(X**e), Q.real_elements(X)) is None
262
+
263
+ def test_matrix_element_sets():
264
+ X = MatrixSymbol('X', 4, 4)
265
+ assert ask(Q.real(X[1, 2]), Q.real_elements(X))
266
+ assert ask(Q.integer(X[1, 2]), Q.integer_elements(X))
267
+ assert ask(Q.complex(X[1, 2]), Q.complex_elements(X))
268
+ assert ask(Q.integer_elements(Identity(3)))
269
+ assert ask(Q.integer_elements(ZeroMatrix(3, 3)))
270
+ assert ask(Q.integer_elements(OneMatrix(3, 3)))
271
+ from sympy.matrices.expressions.fourier import DFT
272
+ assert ask(Q.complex_elements(DFT(3)))
273
+
274
+
275
+ def test_matrix_element_sets_slices_blocks():
276
+ X = MatrixSymbol('X', 4, 4)
277
+ assert ask(Q.integer_elements(X[:, 3]), Q.integer_elements(X))
278
+ assert ask(Q.integer_elements(BlockMatrix([[X], [X]])),
279
+ Q.integer_elements(X))
280
+
281
+ def test_matrix_element_sets_determinant_trace():
282
+ assert ask(Q.integer(Determinant(X)), Q.integer_elements(X))
283
+ assert ask(Q.integer(Trace(X)), Q.integer_elements(X))
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/tests/test_query.py ADDED
The diff for this file is too large to render. See raw diff
 
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/tests/test_refine.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.assumptions.ask import Q
2
+ from sympy.assumptions.refine import refine
3
+ from sympy.core.expr import Expr
4
+ from sympy.core.numbers import (I, Rational, nan, pi)
5
+ from sympy.core.singleton import S
6
+ from sympy.core.symbol import Symbol
7
+ from sympy.functions.elementary.complexes import (Abs, arg, im, re, sign)
8
+ from sympy.functions.elementary.exponential import exp
9
+ from sympy.functions.elementary.miscellaneous import sqrt
10
+ from sympy.functions.elementary.trigonometric import (atan, atan2)
11
+ from sympy.abc import w, x, y, z
12
+ from sympy.core.relational import Eq, Ne
13
+ from sympy.functions.elementary.piecewise import Piecewise
14
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
15
+
16
+
17
+ def test_Abs():
18
+ assert refine(Abs(x), Q.positive(x)) == x
19
+ assert refine(1 + Abs(x), Q.positive(x)) == 1 + x
20
+ assert refine(Abs(x), Q.negative(x)) == -x
21
+ assert refine(1 + Abs(x), Q.negative(x)) == 1 - x
22
+
23
+ assert refine(Abs(x**2)) != x**2
24
+ assert refine(Abs(x**2), Q.real(x)) == x**2
25
+
26
+
27
+ def test_pow1():
28
+ assert refine((-1)**x, Q.even(x)) == 1
29
+ assert refine((-1)**x, Q.odd(x)) == -1
30
+ assert refine((-2)**x, Q.even(x)) == 2**x
31
+
32
+ # nested powers
33
+ assert refine(sqrt(x**2)) != Abs(x)
34
+ assert refine(sqrt(x**2), Q.complex(x)) != Abs(x)
35
+ assert refine(sqrt(x**2), Q.real(x)) == Abs(x)
36
+ assert refine(sqrt(x**2), Q.positive(x)) == x
37
+ assert refine((x**3)**Rational(1, 3)) != x
38
+
39
+ assert refine((x**3)**Rational(1, 3), Q.real(x)) != x
40
+ assert refine((x**3)**Rational(1, 3), Q.positive(x)) == x
41
+
42
+ assert refine(sqrt(1/x), Q.real(x)) != 1/sqrt(x)
43
+ assert refine(sqrt(1/x), Q.positive(x)) == 1/sqrt(x)
44
+
45
+ # powers of (-1)
46
+ assert refine((-1)**(x + y), Q.even(x)) == (-1)**y
47
+ assert refine((-1)**(x + y + z), Q.odd(x) & Q.odd(z)) == (-1)**y
48
+ assert refine((-1)**(x + y + 1), Q.odd(x)) == (-1)**y
49
+ assert refine((-1)**(x + y + 2), Q.odd(x)) == (-1)**(y + 1)
50
+ assert refine((-1)**(x + 3)) == (-1)**(x + 1)
51
+
52
+ # continuation
53
+ assert refine((-1)**((-1)**x/2 - S.Half), Q.integer(x)) == (-1)**x
54
+ assert refine((-1)**((-1)**x/2 + S.Half), Q.integer(x)) == (-1)**(x + 1)
55
+ assert refine((-1)**((-1)**x/2 + 5*S.Half), Q.integer(x)) == (-1)**(x + 1)
56
+
57
+
58
+ def test_pow2():
59
+ assert refine((-1)**((-1)**x/2 - 7*S.Half), Q.integer(x)) == (-1)**(x + 1)
60
+ assert refine((-1)**((-1)**x/2 - 9*S.Half), Q.integer(x)) == (-1)**x
61
+
62
+ # powers of Abs
63
+ assert refine(Abs(x)**2, Q.real(x)) == x**2
64
+ assert refine(Abs(x)**3, Q.real(x)) == Abs(x)**3
65
+ assert refine(Abs(x)**2) == Abs(x)**2
66
+
67
+
68
+ def test_exp():
69
+ x = Symbol('x', integer=True)
70
+ assert refine(exp(pi*I*2*x)) == 1
71
+ assert refine(exp(pi*I*2*(x + S.Half))) == -1
72
+ assert refine(exp(pi*I*2*(x + Rational(1, 4)))) == I
73
+ assert refine(exp(pi*I*2*(x + Rational(3, 4)))) == -I
74
+
75
+
76
+ def test_Piecewise():
77
+ assert refine(Piecewise((1, x < 0), (3, True)), (x < 0)) == 1
78
+ assert refine(Piecewise((1, x < 0), (3, True)), ~(x < 0)) == 3
79
+ assert refine(Piecewise((1, x < 0), (3, True)), (y < 0)) == \
80
+ Piecewise((1, x < 0), (3, True))
81
+ assert refine(Piecewise((1, x > 0), (3, True)), (x > 0)) == 1
82
+ assert refine(Piecewise((1, x > 0), (3, True)), ~(x > 0)) == 3
83
+ assert refine(Piecewise((1, x > 0), (3, True)), (y > 0)) == \
84
+ Piecewise((1, x > 0), (3, True))
85
+ assert refine(Piecewise((1, x <= 0), (3, True)), (x <= 0)) == 1
86
+ assert refine(Piecewise((1, x <= 0), (3, True)), ~(x <= 0)) == 3
87
+ assert refine(Piecewise((1, x <= 0), (3, True)), (y <= 0)) == \
88
+ Piecewise((1, x <= 0), (3, True))
89
+ assert refine(Piecewise((1, x >= 0), (3, True)), (x >= 0)) == 1
90
+ assert refine(Piecewise((1, x >= 0), (3, True)), ~(x >= 0)) == 3
91
+ assert refine(Piecewise((1, x >= 0), (3, True)), (y >= 0)) == \
92
+ Piecewise((1, x >= 0), (3, True))
93
+ assert refine(Piecewise((1, Eq(x, 0)), (3, True)), (Eq(x, 0)))\
94
+ == 1
95
+ assert refine(Piecewise((1, Eq(x, 0)), (3, True)), (Eq(0, x)))\
96
+ == 1
97
+ assert refine(Piecewise((1, Eq(x, 0)), (3, True)), ~(Eq(x, 0)))\
98
+ == 3
99
+ assert refine(Piecewise((1, Eq(x, 0)), (3, True)), ~(Eq(0, x)))\
100
+ == 3
101
+ assert refine(Piecewise((1, Eq(x, 0)), (3, True)), (Eq(y, 0)))\
102
+ == Piecewise((1, Eq(x, 0)), (3, True))
103
+ assert refine(Piecewise((1, Ne(x, 0)), (3, True)), (Ne(x, 0)))\
104
+ == 1
105
+ assert refine(Piecewise((1, Ne(x, 0)), (3, True)), ~(Ne(x, 0)))\
106
+ == 3
107
+ assert refine(Piecewise((1, Ne(x, 0)), (3, True)), (Ne(y, 0)))\
108
+ == Piecewise((1, Ne(x, 0)), (3, True))
109
+
110
+
111
+ def test_atan2():
112
+ assert refine(atan2(y, x), Q.real(y) & Q.positive(x)) == atan(y/x)
113
+ assert refine(atan2(y, x), Q.negative(y) & Q.positive(x)) == atan(y/x)
114
+ assert refine(atan2(y, x), Q.negative(y) & Q.negative(x)) == atan(y/x) - pi
115
+ assert refine(atan2(y, x), Q.positive(y) & Q.negative(x)) == atan(y/x) + pi
116
+ assert refine(atan2(y, x), Q.zero(y) & Q.negative(x)) == pi
117
+ assert refine(atan2(y, x), Q.positive(y) & Q.zero(x)) == pi/2
118
+ assert refine(atan2(y, x), Q.negative(y) & Q.zero(x)) == -pi/2
119
+ assert refine(atan2(y, x), Q.zero(y) & Q.zero(x)) is nan
120
+
121
+
122
+ def test_re():
123
+ assert refine(re(x), Q.real(x)) == x
124
+ assert refine(re(x), Q.imaginary(x)) is S.Zero
125
+ assert refine(re(x+y), Q.real(x) & Q.real(y)) == x + y
126
+ assert refine(re(x+y), Q.real(x) & Q.imaginary(y)) == x
127
+ assert refine(re(x*y), Q.real(x) & Q.real(y)) == x * y
128
+ assert refine(re(x*y), Q.real(x) & Q.imaginary(y)) == 0
129
+ assert refine(re(x*y*z), Q.real(x) & Q.real(y) & Q.real(z)) == x * y * z
130
+
131
+
132
+ def test_im():
133
+ assert refine(im(x), Q.imaginary(x)) == -I*x
134
+ assert refine(im(x), Q.real(x)) is S.Zero
135
+ assert refine(im(x+y), Q.imaginary(x) & Q.imaginary(y)) == -I*x - I*y
136
+ assert refine(im(x+y), Q.real(x) & Q.imaginary(y)) == -I*y
137
+ assert refine(im(x*y), Q.imaginary(x) & Q.real(y)) == -I*x*y
138
+ assert refine(im(x*y), Q.imaginary(x) & Q.imaginary(y)) == 0
139
+ assert refine(im(1/x), Q.imaginary(x)) == -I/x
140
+ assert refine(im(x*y*z), Q.imaginary(x) & Q.imaginary(y)
141
+ & Q.imaginary(z)) == -I*x*y*z
142
+
143
+
144
+ def test_complex():
145
+ assert refine(re(1/(x + I*y)), Q.real(x) & Q.real(y)) == \
146
+ x/(x**2 + y**2)
147
+ assert refine(im(1/(x + I*y)), Q.real(x) & Q.real(y)) == \
148
+ -y/(x**2 + y**2)
149
+ assert refine(re((w + I*x) * (y + I*z)), Q.real(w) & Q.real(x) & Q.real(y)
150
+ & Q.real(z)) == w*y - x*z
151
+ assert refine(im((w + I*x) * (y + I*z)), Q.real(w) & Q.real(x) & Q.real(y)
152
+ & Q.real(z)) == w*z + x*y
153
+
154
+
155
+ def test_sign():
156
+ x = Symbol('x', real = True)
157
+ assert refine(sign(x), Q.positive(x)) == 1
158
+ assert refine(sign(x), Q.negative(x)) == -1
159
+ assert refine(sign(x), Q.zero(x)) == 0
160
+ assert refine(sign(x), True) == sign(x)
161
+ assert refine(sign(Abs(x)), Q.nonzero(x)) == 1
162
+
163
+ x = Symbol('x', imaginary=True)
164
+ assert refine(sign(x), Q.positive(im(x))) == S.ImaginaryUnit
165
+ assert refine(sign(x), Q.negative(im(x))) == -S.ImaginaryUnit
166
+ assert refine(sign(x), True) == sign(x)
167
+
168
+ x = Symbol('x', complex=True)
169
+ assert refine(sign(x), Q.zero(x)) == 0
170
+
171
+ def test_arg():
172
+ x = Symbol('x', complex = True)
173
+ assert refine(arg(x), Q.positive(x)) == 0
174
+ assert refine(arg(x), Q.negative(x)) == pi
175
+
176
+ def test_func_args():
177
+ class MyClass(Expr):
178
+ # A class with nontrivial .func
179
+
180
+ def __init__(self, *args):
181
+ self.my_member = ""
182
+
183
+ @property
184
+ def func(self):
185
+ def my_func(*args):
186
+ obj = MyClass(*args)
187
+ obj.my_member = self.my_member
188
+ return obj
189
+ return my_func
190
+
191
+ x = MyClass()
192
+ x.my_member = "A very important value"
193
+ assert x.my_member == refine(x).my_member
194
+
195
+ def test_issue_refine_9384():
196
+ assert refine(Piecewise((1, x < 0), (0, True)), Q.positive(x)) == 0
197
+ assert refine(Piecewise((1, x < 0), (0, True)), Q.negative(x)) == 1
198
+ assert refine(Piecewise((1, x > 0), (0, True)), Q.positive(x)) == 1
199
+ assert refine(Piecewise((1, x > 0), (0, True)), Q.negative(x)) == 0
200
+
201
+
202
+ def test_eval_refine():
203
+ class MockExpr(Expr):
204
+ def _eval_refine(self, assumptions):
205
+ return True
206
+
207
+ mock_obj = MockExpr()
208
+ assert refine(mock_obj)
209
+
210
+ def test_refine_issue_12724():
211
+ expr1 = refine(Abs(x * y), Q.positive(x))
212
+ expr2 = refine(Abs(x * y * z), Q.positive(x))
213
+ assert expr1 == x * Abs(y)
214
+ assert expr2 == x * Abs(y * z)
215
+ y1 = Symbol('y1', real = True)
216
+ expr3 = refine(Abs(x * y1**2 * z), Q.positive(x))
217
+ assert expr3 == x * y1**2 * Abs(z)
218
+
219
+
220
+ def test_matrixelement():
221
+ x = MatrixSymbol('x', 3, 3)
222
+ i = Symbol('i', positive = True)
223
+ j = Symbol('j', positive = True)
224
+ assert refine(x[0, 1], Q.symmetric(x)) == x[0, 1]
225
+ assert refine(x[1, 0], Q.symmetric(x)) == x[0, 1]
226
+ assert refine(x[i, j], Q.symmetric(x)) == x[j, i]
227
+ assert refine(x[j, i], Q.symmetric(x)) == x[j, i]
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/tests/test_rel_queries.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.assumptions.lra_satask import lra_satask
2
+ from sympy.logic.algorithms.lra_theory import UnhandledInput
3
+ from sympy.assumptions.ask import Q, ask
4
+
5
+ from sympy.core import symbols, Symbol
6
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
7
+ from sympy.core.numbers import I
8
+
9
+ from sympy.testing.pytest import raises, XFAIL
10
+ x, y, z = symbols("x y z", real=True)
11
+
12
+ def test_lra_satask():
13
+ im = Symbol('im', imaginary=True)
14
+
15
+ # test preprocessing of unequalities is working correctly
16
+ assert lra_satask(Q.eq(x, 1), ~Q.ne(x, 0)) is False
17
+ assert lra_satask(Q.eq(x, 0), ~Q.ne(x, 0)) is True
18
+ assert lra_satask(~Q.ne(x, 0), Q.eq(x, 0)) is True
19
+ assert lra_satask(~Q.eq(x, 0), Q.eq(x, 0)) is False
20
+ assert lra_satask(Q.ne(x, 0), Q.eq(x, 0)) is False
21
+
22
+ # basic tests
23
+ assert lra_satask(Q.ne(x, x)) is False
24
+ assert lra_satask(Q.eq(x, x)) is True
25
+ assert lra_satask(Q.gt(x, 0), Q.gt(x, 1)) is True
26
+
27
+ # check that True/False are handled
28
+ assert lra_satask(Q.gt(x, 0), True) is None
29
+ assert raises(ValueError, lambda: lra_satask(Q.gt(x, 0), False))
30
+
31
+ # check imaginary numbers are correctly handled
32
+ # (im * I).is_real returns True so this is an edge case
33
+ raises(UnhandledInput, lambda: lra_satask(Q.gt(im * I, 0), Q.gt(im * I, 0)))
34
+
35
+ # check matrix inputs
36
+ X = MatrixSymbol("X", 2, 2)
37
+ raises(UnhandledInput, lambda: lra_satask(Q.lt(X, 2) & Q.gt(X, 3)))
38
+
39
+
40
+ def test_old_assumptions():
41
+ # test unhandled old assumptions
42
+ w = symbols("w")
43
+ raises(UnhandledInput, lambda: lra_satask(Q.lt(w, 2) & Q.gt(w, 3)))
44
+ w = symbols("w", rational=False, real=True)
45
+ raises(UnhandledInput, lambda: lra_satask(Q.lt(w, 2) & Q.gt(w, 3)))
46
+ w = symbols("w", odd=True, real=True)
47
+ raises(UnhandledInput, lambda: lra_satask(Q.lt(w, 2) & Q.gt(w, 3)))
48
+ w = symbols("w", even=True, real=True)
49
+ raises(UnhandledInput, lambda: lra_satask(Q.lt(w, 2) & Q.gt(w, 3)))
50
+ w = symbols("w", prime=True, real=True)
51
+ raises(UnhandledInput, lambda: lra_satask(Q.lt(w, 2) & Q.gt(w, 3)))
52
+ w = symbols("w", composite=True, real=True)
53
+ raises(UnhandledInput, lambda: lra_satask(Q.lt(w, 2) & Q.gt(w, 3)))
54
+ w = symbols("w", integer=True, real=True)
55
+ raises(UnhandledInput, lambda: lra_satask(Q.lt(w, 2) & Q.gt(w, 3)))
56
+ w = symbols("w", integer=False, real=True)
57
+ raises(UnhandledInput, lambda: lra_satask(Q.lt(w, 2) & Q.gt(w, 3)))
58
+
59
+ # test handled
60
+ w = symbols("w", positive=True, real=True)
61
+ assert lra_satask(Q.le(w, 0)) is False
62
+ assert lra_satask(Q.gt(w, 0)) is True
63
+ w = symbols("w", negative=True, real=True)
64
+ assert lra_satask(Q.lt(w, 0)) is True
65
+ assert lra_satask(Q.ge(w, 0)) is False
66
+ w = symbols("w", zero=True, real=True)
67
+ assert lra_satask(Q.eq(w, 0)) is True
68
+ assert lra_satask(Q.ne(w, 0)) is False
69
+ w = symbols("w", nonzero=True, real=True)
70
+ assert lra_satask(Q.ne(w, 0)) is True
71
+ assert lra_satask(Q.eq(w, 1)) is None
72
+ w = symbols("w", nonpositive=True, real=True)
73
+ assert lra_satask(Q.le(w, 0)) is True
74
+ assert lra_satask(Q.gt(w, 0)) is False
75
+ w = symbols("w", nonnegative=True, real=True)
76
+ assert lra_satask(Q.ge(w, 0)) is True
77
+ assert lra_satask(Q.lt(w, 0)) is False
78
+
79
+
80
+ def test_rel_queries():
81
+ assert ask(Q.lt(x, 2) & Q.gt(x, 3)) is False
82
+ assert ask(Q.positive(x - z), (x > y) & (y > z)) is True
83
+ assert ask(x + y > 2, (x < 0) & (y <0)) is False
84
+ assert ask(x > z, (x > y) & (y > z)) is True
85
+
86
+
87
+ def test_unhandled_queries():
88
+ X = MatrixSymbol("X", 2, 2)
89
+ assert ask(Q.lt(X, 2) & Q.gt(X, 3)) is None
90
+
91
+
92
+ def test_all_pred():
93
+ # test usable pred
94
+ assert lra_satask(Q.extended_positive(x), (x > 2)) is True
95
+ assert lra_satask(Q.positive_infinite(x)) is False
96
+ assert lra_satask(Q.negative_infinite(x)) is False
97
+
98
+ # test disallowed pred
99
+ raises(UnhandledInput, lambda: lra_satask((x > 0), (x > 2) & Q.prime(x)))
100
+ raises(UnhandledInput, lambda: lra_satask((x > 0), (x > 2) & Q.composite(x)))
101
+ raises(UnhandledInput, lambda: lra_satask((x > 0), (x > 2) & Q.odd(x)))
102
+ raises(UnhandledInput, lambda: lra_satask((x > 0), (x > 2) & Q.even(x)))
103
+ raises(UnhandledInput, lambda: lra_satask((x > 0), (x > 2) & Q.integer(x)))
104
+
105
+
106
+ def test_number_line_properties():
107
+ # From:
108
+ # https://en.wikipedia.org/wiki/Inequality_(mathematics)#Properties_on_the_number_line
109
+
110
+ a, b, c = symbols("a b c", real=True)
111
+
112
+ # Transitivity
113
+ # If a <= b and b <= c, then a <= c.
114
+ assert ask(a <= c, (a <= b) & (b <= c)) is True
115
+ # If a <= b and b < c, then a < c.
116
+ assert ask(a < c, (a <= b) & (b < c)) is True
117
+ # If a < b and b <= c, then a < c.
118
+ assert ask(a < c, (a < b) & (b <= c)) is True
119
+
120
+ # Addition and subtraction
121
+ # If a <= b, then a + c <= b + c and a - c <= b - c.
122
+ assert ask(a + c <= b + c, a <= b) is True
123
+ assert ask(a - c <= b - c, a <= b) is True
124
+
125
+
126
+ @XFAIL
127
+ def test_failing_number_line_properties():
128
+ # From:
129
+ # https://en.wikipedia.org/wiki/Inequality_(mathematics)#Properties_on_the_number_line
130
+
131
+ a, b, c = symbols("a b c", real=True)
132
+
133
+ # Multiplication and division
134
+ # If a <= b and c > 0, then ac <= bc and a/c <= b/c. (True for non-zero c)
135
+ assert ask(a*c <= b*c, (a <= b) & (c > 0) & ~ Q.zero(c)) is True
136
+ assert ask(a/c <= b/c, (a <= b) & (c > 0) & ~ Q.zero(c)) is True
137
+ # If a <= b and c < 0, then ac >= bc and a/c >= b/c. (True for non-zero c)
138
+ assert ask(a*c >= b*c, (a <= b) & (c < 0) & ~ Q.zero(c)) is True
139
+ assert ask(a/c >= b/c, (a <= b) & (c < 0) & ~ Q.zero(c)) is True
140
+
141
+ # Additive inverse
142
+ # If a <= b, then -a >= -b.
143
+ assert ask(-a >= -b, a <= b) is True
144
+
145
+ # Multiplicative inverse
146
+ # For a, b that are both negative or both positive:
147
+ # If a <= b, then 1/a >= 1/b .
148
+ assert ask(1/a >= 1/b, (a <= b) & Q.positive(x) & Q.positive(b)) is True
149
+ assert ask(1/a >= 1/b, (a <= b) & Q.negative(x) & Q.negative(b)) is True
150
+
151
+
152
+ def test_equality():
153
+ # test symmetry and reflexivity
154
+ assert ask(Q.eq(x, x)) is True
155
+ assert ask(Q.eq(y, x), Q.eq(x, y)) is True
156
+ assert ask(Q.eq(y, x), ~Q.eq(z, z) | Q.eq(x, y)) is True
157
+
158
+ # test transitivity
159
+ assert ask(Q.eq(x,z), Q.eq(x,y) & Q.eq(y,z)) is True
160
+
161
+
162
+ @XFAIL
163
+ def test_equality_failing():
164
+ # Note that implementing the substitution property of equality
165
+ # most likely requires a redesign of the new assumptions.
166
+ # See issue #25485 for why this is the case and general ideas
167
+ # about how things could be redesigned.
168
+
169
+ # test substitution property
170
+ assert ask(Q.prime(x), Q.eq(x, y) & Q.prime(y)) is True
171
+ assert ask(Q.real(x), Q.eq(x, y) & Q.real(y)) is True
172
+ assert ask(Q.imaginary(x), Q.eq(x, y) & Q.imaginary(y)) is True
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/tests/test_satask.py ADDED
@@ -0,0 +1,378 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.assumptions.ask import Q
2
+ from sympy.assumptions.assume import assuming
3
+ from sympy.core.numbers import (I, pi)
4
+ from sympy.core.relational import (Eq, Gt)
5
+ from sympy.core.singleton import S
6
+ from sympy.core.symbol import symbols
7
+ from sympy.functions.elementary.complexes import Abs
8
+ from sympy.logic.boolalg import Implies
9
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
10
+ from sympy.assumptions.cnf import CNF, Literal
11
+ from sympy.assumptions.satask import (satask, extract_predargs,
12
+ get_relevant_clsfacts)
13
+
14
+ from sympy.testing.pytest import raises, XFAIL
15
+
16
+
17
+ x, y, z = symbols('x y z')
18
+
19
+
20
+ def test_satask():
21
+ # No relevant facts
22
+ assert satask(Q.real(x), Q.real(x)) is True
23
+ assert satask(Q.real(x), ~Q.real(x)) is False
24
+ assert satask(Q.real(x)) is None
25
+
26
+ assert satask(Q.real(x), Q.positive(x)) is True
27
+ assert satask(Q.positive(x), Q.real(x)) is None
28
+ assert satask(Q.real(x), ~Q.positive(x)) is None
29
+ assert satask(Q.positive(x), ~Q.real(x)) is False
30
+
31
+ raises(ValueError, lambda: satask(Q.real(x), Q.real(x) & ~Q.real(x)))
32
+
33
+ with assuming(Q.positive(x)):
34
+ assert satask(Q.real(x)) is True
35
+ assert satask(~Q.positive(x)) is False
36
+ raises(ValueError, lambda: satask(Q.real(x), ~Q.positive(x)))
37
+
38
+ assert satask(Q.zero(x), Q.nonzero(x)) is False
39
+ assert satask(Q.positive(x), Q.zero(x)) is False
40
+ assert satask(Q.real(x), Q.zero(x)) is True
41
+ assert satask(Q.zero(x), Q.zero(x*y)) is None
42
+ assert satask(Q.zero(x*y), Q.zero(x))
43
+
44
+
45
+ def test_zero():
46
+ """
47
+ Everything in this test doesn't work with the ask handlers, and most
48
+ things would be very difficult or impossible to make work under that
49
+ model.
50
+
51
+ """
52
+ assert satask(Q.zero(x) | Q.zero(y), Q.zero(x*y)) is True
53
+ assert satask(Q.zero(x*y), Q.zero(x) | Q.zero(y)) is True
54
+
55
+ assert satask(Implies(Q.zero(x), Q.zero(x*y))) is True
56
+
57
+ # This one in particular requires computing the fixed-point of the
58
+ # relevant facts, because going from Q.nonzero(x*y) -> ~Q.zero(x*y) and
59
+ # Q.zero(x*y) -> Equivalent(Q.zero(x*y), Q.zero(x) | Q.zero(y)) takes two
60
+ # steps.
61
+ assert satask(Q.zero(x) | Q.zero(y), Q.nonzero(x*y)) is False
62
+
63
+ assert satask(Q.zero(x), Q.zero(x**2)) is True
64
+
65
+
66
+ def test_zero_positive():
67
+ assert satask(Q.zero(x + y), Q.positive(x) & Q.positive(y)) is False
68
+ assert satask(Q.positive(x) & Q.positive(y), Q.zero(x + y)) is False
69
+ assert satask(Q.nonzero(x + y), Q.positive(x) & Q.positive(y)) is True
70
+ assert satask(Q.positive(x) & Q.positive(y), Q.nonzero(x + y)) is None
71
+
72
+ # This one requires several levels of forward chaining
73
+ assert satask(Q.zero(x*(x + y)), Q.positive(x) & Q.positive(y)) is False
74
+
75
+ assert satask(Q.positive(pi*x*y + 1), Q.positive(x) & Q.positive(y)) is True
76
+ assert satask(Q.positive(pi*x*y - 5), Q.positive(x) & Q.positive(y)) is None
77
+
78
+
79
+ def test_zero_pow():
80
+ assert satask(Q.zero(x**y), Q.zero(x) & Q.positive(y)) is True
81
+ assert satask(Q.zero(x**y), Q.nonzero(x) & Q.zero(y)) is False
82
+
83
+ assert satask(Q.zero(x), Q.zero(x**y)) is True
84
+
85
+ assert satask(Q.zero(x**y), Q.zero(x)) is None
86
+
87
+
88
+ @XFAIL
89
+ # Requires correct Q.square calculation first
90
+ def test_invertible():
91
+ A = MatrixSymbol('A', 5, 5)
92
+ B = MatrixSymbol('B', 5, 5)
93
+ assert satask(Q.invertible(A*B), Q.invertible(A) & Q.invertible(B)) is True
94
+ assert satask(Q.invertible(A), Q.invertible(A*B)) is True
95
+ assert satask(Q.invertible(A) & Q.invertible(B), Q.invertible(A*B)) is True
96
+
97
+
98
+ def test_prime():
99
+ assert satask(Q.prime(5)) is True
100
+ assert satask(Q.prime(6)) is False
101
+ assert satask(Q.prime(-5)) is False
102
+
103
+ assert satask(Q.prime(x*y), Q.integer(x) & Q.integer(y)) is None
104
+ assert satask(Q.prime(x*y), Q.prime(x) & Q.prime(y)) is False
105
+
106
+
107
+ def test_old_assump():
108
+ assert satask(Q.positive(1)) is True
109
+ assert satask(Q.positive(-1)) is False
110
+ assert satask(Q.positive(0)) is False
111
+ assert satask(Q.positive(I)) is False
112
+ assert satask(Q.positive(pi)) is True
113
+
114
+ assert satask(Q.negative(1)) is False
115
+ assert satask(Q.negative(-1)) is True
116
+ assert satask(Q.negative(0)) is False
117
+ assert satask(Q.negative(I)) is False
118
+ assert satask(Q.negative(pi)) is False
119
+
120
+ assert satask(Q.zero(1)) is False
121
+ assert satask(Q.zero(-1)) is False
122
+ assert satask(Q.zero(0)) is True
123
+ assert satask(Q.zero(I)) is False
124
+ assert satask(Q.zero(pi)) is False
125
+
126
+ assert satask(Q.nonzero(1)) is True
127
+ assert satask(Q.nonzero(-1)) is True
128
+ assert satask(Q.nonzero(0)) is False
129
+ assert satask(Q.nonzero(I)) is False
130
+ assert satask(Q.nonzero(pi)) is True
131
+
132
+ assert satask(Q.nonpositive(1)) is False
133
+ assert satask(Q.nonpositive(-1)) is True
134
+ assert satask(Q.nonpositive(0)) is True
135
+ assert satask(Q.nonpositive(I)) is False
136
+ assert satask(Q.nonpositive(pi)) is False
137
+
138
+ assert satask(Q.nonnegative(1)) is True
139
+ assert satask(Q.nonnegative(-1)) is False
140
+ assert satask(Q.nonnegative(0)) is True
141
+ assert satask(Q.nonnegative(I)) is False
142
+ assert satask(Q.nonnegative(pi)) is True
143
+
144
+
145
+ def test_rational_irrational():
146
+ assert satask(Q.irrational(2)) is False
147
+ assert satask(Q.rational(2)) is True
148
+ assert satask(Q.irrational(pi)) is True
149
+ assert satask(Q.rational(pi)) is False
150
+ assert satask(Q.irrational(I)) is False
151
+ assert satask(Q.rational(I)) is False
152
+
153
+ assert satask(Q.irrational(x*y*z), Q.irrational(x) & Q.irrational(y) &
154
+ Q.rational(z)) is None
155
+ assert satask(Q.irrational(x*y*z), Q.irrational(x) & Q.rational(y) &
156
+ Q.rational(z)) is True
157
+ assert satask(Q.irrational(pi*x*y), Q.rational(x) & Q.rational(y)) is True
158
+
159
+ assert satask(Q.irrational(x + y + z), Q.irrational(x) & Q.irrational(y) &
160
+ Q.rational(z)) is None
161
+ assert satask(Q.irrational(x + y + z), Q.irrational(x) & Q.rational(y) &
162
+ Q.rational(z)) is True
163
+ assert satask(Q.irrational(pi + x + y), Q.rational(x) & Q.rational(y)) is True
164
+
165
+ assert satask(Q.irrational(x*y*z), Q.rational(x) & Q.rational(y) &
166
+ Q.rational(z)) is False
167
+ assert satask(Q.rational(x*y*z), Q.rational(x) & Q.rational(y) &
168
+ Q.rational(z)) is True
169
+
170
+ assert satask(Q.irrational(x + y + z), Q.rational(x) & Q.rational(y) &
171
+ Q.rational(z)) is False
172
+ assert satask(Q.rational(x + y + z), Q.rational(x) & Q.rational(y) &
173
+ Q.rational(z)) is True
174
+
175
+
176
+ def test_even_satask():
177
+ assert satask(Q.even(2)) is True
178
+ assert satask(Q.even(3)) is False
179
+
180
+ assert satask(Q.even(x*y), Q.even(x) & Q.odd(y)) is True
181
+ assert satask(Q.even(x*y), Q.even(x) & Q.integer(y)) is True
182
+ assert satask(Q.even(x*y), Q.even(x) & Q.even(y)) is True
183
+ assert satask(Q.even(x*y), Q.odd(x) & Q.odd(y)) is False
184
+ assert satask(Q.even(x*y), Q.even(x)) is None
185
+ assert satask(Q.even(x*y), Q.odd(x) & Q.integer(y)) is None
186
+ assert satask(Q.even(x*y), Q.odd(x) & Q.odd(y)) is False
187
+
188
+ assert satask(Q.even(abs(x)), Q.even(x)) is True
189
+ assert satask(Q.even(abs(x)), Q.odd(x)) is False
190
+ assert satask(Q.even(x), Q.even(abs(x))) is None # x could be complex
191
+
192
+
193
+ def test_odd_satask():
194
+ assert satask(Q.odd(2)) is False
195
+ assert satask(Q.odd(3)) is True
196
+
197
+ assert satask(Q.odd(x*y), Q.even(x) & Q.odd(y)) is False
198
+ assert satask(Q.odd(x*y), Q.even(x) & Q.integer(y)) is False
199
+ assert satask(Q.odd(x*y), Q.even(x) & Q.even(y)) is False
200
+ assert satask(Q.odd(x*y), Q.odd(x) & Q.odd(y)) is True
201
+ assert satask(Q.odd(x*y), Q.even(x)) is None
202
+ assert satask(Q.odd(x*y), Q.odd(x) & Q.integer(y)) is None
203
+ assert satask(Q.odd(x*y), Q.odd(x) & Q.odd(y)) is True
204
+
205
+ assert satask(Q.odd(abs(x)), Q.even(x)) is False
206
+ assert satask(Q.odd(abs(x)), Q.odd(x)) is True
207
+ assert satask(Q.odd(x), Q.odd(abs(x))) is None # x could be complex
208
+
209
+
210
+ def test_integer():
211
+ assert satask(Q.integer(1)) is True
212
+ assert satask(Q.integer(S.Half)) is False
213
+
214
+ assert satask(Q.integer(x + y), Q.integer(x) & Q.integer(y)) is True
215
+ assert satask(Q.integer(x + y), Q.integer(x)) is None
216
+
217
+ assert satask(Q.integer(x + y), Q.integer(x) & ~Q.integer(y)) is False
218
+ assert satask(Q.integer(x + y + z), Q.integer(x) & Q.integer(y) &
219
+ ~Q.integer(z)) is False
220
+ assert satask(Q.integer(x + y + z), Q.integer(x) & ~Q.integer(y) &
221
+ ~Q.integer(z)) is None
222
+ assert satask(Q.integer(x + y + z), Q.integer(x) & ~Q.integer(y)) is None
223
+ assert satask(Q.integer(x + y), Q.integer(x) & Q.irrational(y)) is False
224
+
225
+ assert satask(Q.integer(x*y), Q.integer(x) & Q.integer(y)) is True
226
+ assert satask(Q.integer(x*y), Q.integer(x)) is None
227
+
228
+ assert satask(Q.integer(x*y), Q.integer(x) & ~Q.integer(y)) is None
229
+ assert satask(Q.integer(x*y), Q.integer(x) & ~Q.rational(y)) is False
230
+ assert satask(Q.integer(x*y*z), Q.integer(x) & Q.integer(y) &
231
+ ~Q.rational(z)) is False
232
+ assert satask(Q.integer(x*y*z), Q.integer(x) & ~Q.rational(y) &
233
+ ~Q.rational(z)) is None
234
+ assert satask(Q.integer(x*y*z), Q.integer(x) & ~Q.rational(y)) is None
235
+ assert satask(Q.integer(x*y), Q.integer(x) & Q.irrational(y)) is False
236
+
237
+
238
+ def test_abs():
239
+ assert satask(Q.nonnegative(abs(x))) is True
240
+ assert satask(Q.positive(abs(x)), ~Q.zero(x)) is True
241
+ assert satask(Q.zero(x), ~Q.zero(abs(x))) is False
242
+ assert satask(Q.zero(x), Q.zero(abs(x))) is True
243
+ assert satask(Q.nonzero(x), ~Q.zero(abs(x))) is None # x could be complex
244
+ assert satask(Q.zero(abs(x)), Q.zero(x)) is True
245
+
246
+
247
+ def test_imaginary():
248
+ assert satask(Q.imaginary(2*I)) is True
249
+ assert satask(Q.imaginary(x*y), Q.imaginary(x)) is None
250
+ assert satask(Q.imaginary(x*y), Q.imaginary(x) & Q.real(y)) is True
251
+ assert satask(Q.imaginary(x), Q.real(x)) is False
252
+ assert satask(Q.imaginary(1)) is False
253
+ assert satask(Q.imaginary(x*y), Q.real(x) & Q.real(y)) is False
254
+ assert satask(Q.imaginary(x + y), Q.real(x) & Q.real(y)) is False
255
+
256
+
257
+ def test_real():
258
+ assert satask(Q.real(x*y), Q.real(x) & Q.real(y)) is True
259
+ assert satask(Q.real(x + y), Q.real(x) & Q.real(y)) is True
260
+ assert satask(Q.real(x*y*z), Q.real(x) & Q.real(y) & Q.real(z)) is True
261
+ assert satask(Q.real(x*y*z), Q.real(x) & Q.real(y)) is None
262
+ assert satask(Q.real(x*y*z), Q.real(x) & Q.real(y) & Q.imaginary(z)) is False
263
+ assert satask(Q.real(x + y + z), Q.real(x) & Q.real(y) & Q.real(z)) is True
264
+ assert satask(Q.real(x + y + z), Q.real(x) & Q.real(y)) is None
265
+
266
+
267
+ def test_pos_neg():
268
+ assert satask(~Q.positive(x), Q.negative(x)) is True
269
+ assert satask(~Q.negative(x), Q.positive(x)) is True
270
+ assert satask(Q.positive(x + y), Q.positive(x) & Q.positive(y)) is True
271
+ assert satask(Q.negative(x + y), Q.negative(x) & Q.negative(y)) is True
272
+ assert satask(Q.positive(x + y), Q.negative(x) & Q.negative(y)) is False
273
+ assert satask(Q.negative(x + y), Q.positive(x) & Q.positive(y)) is False
274
+
275
+
276
+ def test_pow_pos_neg():
277
+ assert satask(Q.nonnegative(x**2), Q.positive(x)) is True
278
+ assert satask(Q.nonpositive(x**2), Q.positive(x)) is False
279
+ assert satask(Q.positive(x**2), Q.positive(x)) is True
280
+ assert satask(Q.negative(x**2), Q.positive(x)) is False
281
+ assert satask(Q.real(x**2), Q.positive(x)) is True
282
+
283
+ assert satask(Q.nonnegative(x**2), Q.negative(x)) is True
284
+ assert satask(Q.nonpositive(x**2), Q.negative(x)) is False
285
+ assert satask(Q.positive(x**2), Q.negative(x)) is True
286
+ assert satask(Q.negative(x**2), Q.negative(x)) is False
287
+ assert satask(Q.real(x**2), Q.negative(x)) is True
288
+
289
+ assert satask(Q.nonnegative(x**2), Q.nonnegative(x)) is True
290
+ assert satask(Q.nonpositive(x**2), Q.nonnegative(x)) is None
291
+ assert satask(Q.positive(x**2), Q.nonnegative(x)) is None
292
+ assert satask(Q.negative(x**2), Q.nonnegative(x)) is False
293
+ assert satask(Q.real(x**2), Q.nonnegative(x)) is True
294
+
295
+ assert satask(Q.nonnegative(x**2), Q.nonpositive(x)) is True
296
+ assert satask(Q.nonpositive(x**2), Q.nonpositive(x)) is None
297
+ assert satask(Q.positive(x**2), Q.nonpositive(x)) is None
298
+ assert satask(Q.negative(x**2), Q.nonpositive(x)) is False
299
+ assert satask(Q.real(x**2), Q.nonpositive(x)) is True
300
+
301
+ assert satask(Q.nonnegative(x**3), Q.positive(x)) is True
302
+ assert satask(Q.nonpositive(x**3), Q.positive(x)) is False
303
+ assert satask(Q.positive(x**3), Q.positive(x)) is True
304
+ assert satask(Q.negative(x**3), Q.positive(x)) is False
305
+ assert satask(Q.real(x**3), Q.positive(x)) is True
306
+
307
+ assert satask(Q.nonnegative(x**3), Q.negative(x)) is False
308
+ assert satask(Q.nonpositive(x**3), Q.negative(x)) is True
309
+ assert satask(Q.positive(x**3), Q.negative(x)) is False
310
+ assert satask(Q.negative(x**3), Q.negative(x)) is True
311
+ assert satask(Q.real(x**3), Q.negative(x)) is True
312
+
313
+ assert satask(Q.nonnegative(x**3), Q.nonnegative(x)) is True
314
+ assert satask(Q.nonpositive(x**3), Q.nonnegative(x)) is None
315
+ assert satask(Q.positive(x**3), Q.nonnegative(x)) is None
316
+ assert satask(Q.negative(x**3), Q.nonnegative(x)) is False
317
+ assert satask(Q.real(x**3), Q.nonnegative(x)) is True
318
+
319
+ assert satask(Q.nonnegative(x**3), Q.nonpositive(x)) is None
320
+ assert satask(Q.nonpositive(x**3), Q.nonpositive(x)) is True
321
+ assert satask(Q.positive(x**3), Q.nonpositive(x)) is False
322
+ assert satask(Q.negative(x**3), Q.nonpositive(x)) is None
323
+ assert satask(Q.real(x**3), Q.nonpositive(x)) is True
324
+
325
+ # If x is zero, x**negative is not real.
326
+ assert satask(Q.nonnegative(x**-2), Q.nonpositive(x)) is None
327
+ assert satask(Q.nonpositive(x**-2), Q.nonpositive(x)) is None
328
+ assert satask(Q.positive(x**-2), Q.nonpositive(x)) is None
329
+ assert satask(Q.negative(x**-2), Q.nonpositive(x)) is None
330
+ assert satask(Q.real(x**-2), Q.nonpositive(x)) is None
331
+
332
+ # We could deduce things for negative powers if x is nonzero, but it
333
+ # isn't implemented yet.
334
+
335
+
336
+ def test_prime_composite():
337
+ assert satask(Q.prime(x), Q.composite(x)) is False
338
+ assert satask(Q.composite(x), Q.prime(x)) is False
339
+ assert satask(Q.composite(x), ~Q.prime(x)) is None
340
+ assert satask(Q.prime(x), ~Q.composite(x)) is None
341
+ # since 1 is neither prime nor composite the following should hold
342
+ assert satask(Q.prime(x), Q.integer(x) & Q.positive(x) & ~Q.composite(x)) is None
343
+ assert satask(Q.prime(2)) is True
344
+ assert satask(Q.prime(4)) is False
345
+ assert satask(Q.prime(1)) is False
346
+ assert satask(Q.composite(1)) is False
347
+
348
+
349
+ def test_extract_predargs():
350
+ props = CNF.from_prop(Q.zero(Abs(x*y)) & Q.zero(x*y))
351
+ assump = CNF.from_prop(Q.zero(x))
352
+ context = CNF.from_prop(Q.zero(y))
353
+ assert extract_predargs(props) == {Abs(x*y), x*y}
354
+ assert extract_predargs(props, assump) == {Abs(x*y), x*y, x}
355
+ assert extract_predargs(props, assump, context) == {Abs(x*y), x*y, x, y}
356
+
357
+ props = CNF.from_prop(Eq(x, y))
358
+ assump = CNF.from_prop(Gt(y, z))
359
+ assert extract_predargs(props, assump) == {x, y, z}
360
+
361
+
362
+ def test_get_relevant_clsfacts():
363
+ exprs = {Abs(x*y)}
364
+ exprs, facts = get_relevant_clsfacts(exprs)
365
+ assert exprs == {x*y}
366
+ assert facts.clauses == \
367
+ {frozenset({Literal(Q.odd(Abs(x*y)), False), Literal(Q.odd(x*y), True)}),
368
+ frozenset({Literal(Q.zero(Abs(x*y)), False), Literal(Q.zero(x*y), True)}),
369
+ frozenset({Literal(Q.even(Abs(x*y)), False), Literal(Q.even(x*y), True)}),
370
+ frozenset({Literal(Q.zero(Abs(x*y)), True), Literal(Q.zero(x*y), False)}),
371
+ frozenset({Literal(Q.even(Abs(x*y)), False),
372
+ Literal(Q.odd(Abs(x*y)), False),
373
+ Literal(Q.odd(x*y), True)}),
374
+ frozenset({Literal(Q.even(Abs(x*y)), False),
375
+ Literal(Q.even(x*y), True),
376
+ Literal(Q.odd(Abs(x*y)), False)}),
377
+ frozenset({Literal(Q.positive(Abs(x*y)), False),
378
+ Literal(Q.zero(Abs(x*y)), False)})}
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/tests/test_sathandlers.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.assumptions.ask import Q
2
+ from sympy.core.basic import Basic
3
+ from sympy.core.expr import Expr
4
+ from sympy.core.mul import Mul
5
+ from sympy.core.symbol import symbols
6
+ from sympy.logic.boolalg import (And, Or)
7
+
8
+ from sympy.assumptions.sathandlers import (ClassFactRegistry, allargs,
9
+ anyarg, exactlyonearg,)
10
+
11
+ x, y, z = symbols('x y z')
12
+
13
+
14
+ def test_class_handler_registry():
15
+ my_handler_registry = ClassFactRegistry()
16
+
17
+ # The predicate doesn't matter here, so just pass
18
+ @my_handler_registry.register(Mul)
19
+ def fact1(expr):
20
+ pass
21
+ @my_handler_registry.multiregister(Expr)
22
+ def fact2(expr):
23
+ pass
24
+
25
+ assert my_handler_registry[Basic] == (frozenset(), frozenset())
26
+ assert my_handler_registry[Expr] == (frozenset(), frozenset({fact2}))
27
+ assert my_handler_registry[Mul] == (frozenset({fact1}), frozenset({fact2}))
28
+
29
+
30
+ def test_allargs():
31
+ assert allargs(x, Q.zero(x), x*y) == And(Q.zero(x), Q.zero(y))
32
+ assert allargs(x, Q.positive(x) | Q.negative(x), x*y) == And(Q.positive(x) | Q.negative(x), Q.positive(y) | Q.negative(y))
33
+
34
+
35
+ def test_anyarg():
36
+ assert anyarg(x, Q.zero(x), x*y) == Or(Q.zero(x), Q.zero(y))
37
+ assert anyarg(x, Q.positive(x) & Q.negative(x), x*y) == \
38
+ Or(Q.positive(x) & Q.negative(x), Q.positive(y) & Q.negative(y))
39
+
40
+
41
+ def test_exactlyonearg():
42
+ assert exactlyonearg(x, Q.zero(x), x*y) == \
43
+ Or(Q.zero(x) & ~Q.zero(y), Q.zero(y) & ~Q.zero(x))
44
+ assert exactlyonearg(x, Q.zero(x), x*y*z) == \
45
+ Or(Q.zero(x) & ~Q.zero(y) & ~Q.zero(z), Q.zero(y)
46
+ & ~Q.zero(x) & ~Q.zero(z), Q.zero(z) & ~Q.zero(x) & ~Q.zero(y))
47
+ assert exactlyonearg(x, Q.positive(x) | Q.negative(x), x*y) == \
48
+ Or((Q.positive(x) | Q.negative(x)) &
49
+ ~(Q.positive(y) | Q.negative(y)), (Q.positive(y) | Q.negative(y)) &
50
+ ~(Q.positive(x) | Q.negative(x)))
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/assumptions/tests/test_wrapper.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.assumptions.ask import Q
2
+ from sympy.assumptions.wrapper import (AssumptionsWrapper, is_infinite,
3
+ is_extended_real)
4
+ from sympy.core.symbol import Symbol
5
+ from sympy.core.assumptions import _assume_defined
6
+
7
+
8
+ def test_all_predicates():
9
+ for fact in _assume_defined:
10
+ method_name = f'_eval_is_{fact}'
11
+ assert hasattr(AssumptionsWrapper, method_name)
12
+
13
+
14
+ def test_AssumptionsWrapper():
15
+ x = Symbol('x', positive=True)
16
+ y = Symbol('y')
17
+ assert AssumptionsWrapper(x).is_positive
18
+ assert AssumptionsWrapper(y).is_positive is None
19
+ assert AssumptionsWrapper(y, Q.positive(y)).is_positive
20
+
21
+
22
+ def test_is_infinite():
23
+ x = Symbol('x', infinite=True)
24
+ y = Symbol('y', infinite=False)
25
+ z = Symbol('z')
26
+ assert is_infinite(x)
27
+ assert not is_infinite(y)
28
+ assert is_infinite(z) is None
29
+ assert is_infinite(z, Q.infinite(z))
30
+
31
+
32
+ def test_is_extended_real():
33
+ x = Symbol('x', extended_real=True)
34
+ y = Symbol('y', extended_real=False)
35
+ z = Symbol('z')
36
+ assert is_extended_real(x)
37
+ assert not is_extended_real(y)
38
+ assert is_extended_real(z) is None
39
+ assert is_extended_real(z, Q.extended_real(z))
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/benchmarks/__init__.py ADDED
File without changes
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/benchmarks/bench_discrete_log.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from time import time
3
+ from sympy.ntheory.residue_ntheory import (discrete_log,
4
+ _discrete_log_trial_mul, _discrete_log_shanks_steps,
5
+ _discrete_log_pollard_rho, _discrete_log_pohlig_hellman)
6
+
7
+
8
+ # Cyclic group (Z/pZ)* with p prime, order p - 1 and generator g
9
+ data_set_1 = [
10
+ # p, p - 1, g
11
+ [191, 190, 19],
12
+ [46639, 46638, 6],
13
+ [14789363, 14789362, 2],
14
+ [4254225211, 4254225210, 2],
15
+ [432751500361, 432751500360, 7],
16
+ [158505390797053, 158505390797052, 2],
17
+ [6575202655312007, 6575202655312006, 5],
18
+ [8430573471995353769, 8430573471995353768, 3],
19
+ [3938471339744997827267, 3938471339744997827266, 2],
20
+ [875260951364705563393093, 875260951364705563393092, 5],
21
+ ]
22
+
23
+
24
+ # Cyclic sub-groups of (Z/nZ)* with prime order p and generator g
25
+ # (n, p are primes and n = 2 * p + 1)
26
+ data_set_2 = [
27
+ # n, p, g
28
+ [227, 113, 3],
29
+ [2447, 1223, 2],
30
+ [24527, 12263, 2],
31
+ [245639, 122819, 2],
32
+ [2456747, 1228373, 3],
33
+ [24567899, 12283949, 3],
34
+ [245679023, 122839511, 2],
35
+ [2456791307, 1228395653, 3],
36
+ [24567913439, 12283956719, 2],
37
+ [245679135407, 122839567703, 2],
38
+ [2456791354763, 1228395677381, 3],
39
+ [24567913550903, 12283956775451, 2],
40
+ [245679135509519, 122839567754759, 2],
41
+ ]
42
+
43
+
44
+ # Cyclic sub-groups of (Z/nZ)* with smooth order o and generator g
45
+ data_set_3 = [
46
+ # n, o, g
47
+ [2**118, 2**116, 3],
48
+ ]
49
+
50
+
51
+ def bench_discrete_log(data_set, algo=None):
52
+ if algo is None:
53
+ f = discrete_log
54
+ elif algo == 'trial':
55
+ f = _discrete_log_trial_mul
56
+ elif algo == 'shanks':
57
+ f = _discrete_log_shanks_steps
58
+ elif algo == 'rho':
59
+ f = _discrete_log_pollard_rho
60
+ elif algo == 'ph':
61
+ f = _discrete_log_pohlig_hellman
62
+ else:
63
+ raise ValueError("Argument 'algo' should be one"
64
+ " of ('trial', 'shanks', 'rho' or 'ph')")
65
+
66
+ for i, data in enumerate(data_set):
67
+ for j, (n, p, g) in enumerate(data):
68
+ t = time()
69
+ l = f(n, pow(g, p - 1, n), g, p)
70
+ t = time() - t
71
+ print('[%02d-%03d] %15.10f' % (i, j, t))
72
+ assert l == p - 1
73
+
74
+
75
+ if __name__ == '__main__':
76
+ algo = sys.argv[1] \
77
+ if len(sys.argv) > 1 else None
78
+ data_set = [
79
+ data_set_1,
80
+ data_set_2,
81
+ data_set_3,
82
+ ]
83
+ bench_discrete_log(data_set, algo)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/benchmarks/bench_meijerint.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # conceal the implicit import from the code quality tester
2
+ from sympy.core.numbers import (oo, pi)
3
+ from sympy.core.symbol import (Symbol, symbols)
4
+ from sympy.functions.elementary.exponential import exp
5
+ from sympy.functions.elementary.miscellaneous import sqrt
6
+ from sympy.functions.special.bessel import besseli
7
+ from sympy.functions.special.gamma_functions import gamma
8
+ from sympy.integrals.integrals import integrate
9
+ from sympy.integrals.transforms import (mellin_transform,
10
+ inverse_fourier_transform, inverse_mellin_transform,
11
+ laplace_transform, inverse_laplace_transform, fourier_transform)
12
+
13
+ LT = laplace_transform
14
+ FT = fourier_transform
15
+ MT = mellin_transform
16
+ IFT = inverse_fourier_transform
17
+ ILT = inverse_laplace_transform
18
+ IMT = inverse_mellin_transform
19
+
20
+ from sympy.abc import x, y
21
+ nu, beta, rho = symbols('nu beta rho')
22
+
23
+ apos, bpos, cpos, dpos, posk, p = symbols('a b c d k p', positive=True)
24
+ k = Symbol('k', real=True)
25
+ negk = Symbol('k', negative=True)
26
+
27
+ mu1, mu2 = symbols('mu1 mu2', real=True, nonzero=True, finite=True)
28
+ sigma1, sigma2 = symbols('sigma1 sigma2', real=True, nonzero=True,
29
+ finite=True, positive=True)
30
+ rate = Symbol('lambda', positive=True)
31
+
32
+
33
+ def normal(x, mu, sigma):
34
+ return 1/sqrt(2*pi*sigma**2)*exp(-(x - mu)**2/2/sigma**2)
35
+
36
+
37
+ def exponential(x, rate):
38
+ return rate*exp(-rate*x)
39
+ alpha, beta = symbols('alpha beta', positive=True)
40
+ betadist = x**(alpha - 1)*(1 + x)**(-alpha - beta)*gamma(alpha + beta) \
41
+ /gamma(alpha)/gamma(beta)
42
+ kint = Symbol('k', integer=True, positive=True)
43
+ chi = 2**(1 - kint/2)*x**(kint - 1)*exp(-x**2/2)/gamma(kint/2)
44
+ chisquared = 2**(-k/2)/gamma(k/2)*x**(k/2 - 1)*exp(-x/2)
45
+ dagum = apos*p/x*(x/bpos)**(apos*p)/(1 + x**apos/bpos**apos)**(p + 1)
46
+ d1, d2 = symbols('d1 d2', positive=True)
47
+ f = sqrt(((d1*x)**d1 * d2**d2)/(d1*x + d2)**(d1 + d2))/x \
48
+ /gamma(d1/2)/gamma(d2/2)*gamma((d1 + d2)/2)
49
+ nupos, sigmapos = symbols('nu sigma', positive=True)
50
+ rice = x/sigmapos**2*exp(-(x**2 + nupos**2)/2/sigmapos**2)*besseli(0, x*
51
+ nupos/sigmapos**2)
52
+ mu = Symbol('mu', real=True)
53
+ laplace = exp(-abs(x - mu)/bpos)/2/bpos
54
+
55
+ u = Symbol('u', polar=True)
56
+ tpos = Symbol('t', positive=True)
57
+
58
+
59
+ def E(expr):
60
+ integrate(expr*exponential(x, rate)*normal(y, mu1, sigma1),
61
+ (x, 0, oo), (y, -oo, oo), meijerg=True)
62
+ integrate(expr*exponential(x, rate)*normal(y, mu1, sigma1),
63
+ (y, -oo, oo), (x, 0, oo), meijerg=True)
64
+
65
+ bench = [
66
+ 'MT(x**nu*Heaviside(x - 1), x, s)',
67
+ 'MT(x**nu*Heaviside(1 - x), x, s)',
68
+ 'MT((1-x)**(beta - 1)*Heaviside(1-x), x, s)',
69
+ 'MT((x-1)**(beta - 1)*Heaviside(x-1), x, s)',
70
+ 'MT((1+x)**(-rho), x, s)',
71
+ 'MT(abs(1-x)**(-rho), x, s)',
72
+ 'MT((1-x)**(beta-1)*Heaviside(1-x) + a*(x-1)**(beta-1)*Heaviside(x-1), x, s)',
73
+ 'MT((x**a-b**a)/(x-b), x, s)',
74
+ 'MT((x**a-bpos**a)/(x-bpos), x, s)',
75
+ 'MT(exp(-x), x, s)',
76
+ 'MT(exp(-1/x), x, s)',
77
+ 'MT(log(x)**4*Heaviside(1-x), x, s)',
78
+ 'MT(log(x)**3*Heaviside(x-1), x, s)',
79
+ 'MT(log(x + 1), x, s)',
80
+ 'MT(log(1/x + 1), x, s)',
81
+ 'MT(log(abs(1 - x)), x, s)',
82
+ 'MT(log(abs(1 - 1/x)), x, s)',
83
+ 'MT(log(x)/(x+1), x, s)',
84
+ 'MT(log(x)**2/(x+1), x, s)',
85
+ 'MT(log(x)/(x+1)**2, x, s)',
86
+ 'MT(erf(sqrt(x)), x, s)',
87
+
88
+ 'MT(besselj(a, 2*sqrt(x)), x, s)',
89
+ 'MT(sin(sqrt(x))*besselj(a, sqrt(x)), x, s)',
90
+ 'MT(cos(sqrt(x))*besselj(a, sqrt(x)), x, s)',
91
+ 'MT(besselj(a, sqrt(x))**2, x, s)',
92
+ 'MT(besselj(a, sqrt(x))*besselj(-a, sqrt(x)), x, s)',
93
+ 'MT(besselj(a - 1, sqrt(x))*besselj(a, sqrt(x)), x, s)',
94
+ 'MT(besselj(a, sqrt(x))*besselj(b, sqrt(x)), x, s)',
95
+ 'MT(besselj(a, sqrt(x))**2 + besselj(-a, sqrt(x))**2, x, s)',
96
+ 'MT(bessely(a, 2*sqrt(x)), x, s)',
97
+ 'MT(sin(sqrt(x))*bessely(a, sqrt(x)), x, s)',
98
+ 'MT(cos(sqrt(x))*bessely(a, sqrt(x)), x, s)',
99
+ 'MT(besselj(a, sqrt(x))*bessely(a, sqrt(x)), x, s)',
100
+ 'MT(besselj(a, sqrt(x))*bessely(b, sqrt(x)), x, s)',
101
+ 'MT(bessely(a, sqrt(x))**2, x, s)',
102
+
103
+ 'MT(besselk(a, 2*sqrt(x)), x, s)',
104
+ 'MT(besselj(a, 2*sqrt(2*sqrt(x)))*besselk(a, 2*sqrt(2*sqrt(x))), x, s)',
105
+ 'MT(besseli(a, sqrt(x))*besselk(a, sqrt(x)), x, s)',
106
+ 'MT(besseli(b, sqrt(x))*besselk(a, sqrt(x)), x, s)',
107
+ 'MT(exp(-x/2)*besselk(a, x/2), x, s)',
108
+
109
+ # later: ILT, IMT
110
+
111
+ 'LT((t-apos)**bpos*exp(-cpos*(t-apos))*Heaviside(t-apos), t, s)',
112
+ 'LT(t**apos, t, s)',
113
+ 'LT(Heaviside(t), t, s)',
114
+ 'LT(Heaviside(t - apos), t, s)',
115
+ 'LT(1 - exp(-apos*t), t, s)',
116
+ 'LT((exp(2*t)-1)*exp(-bpos - t)*Heaviside(t)/2, t, s, noconds=True)',
117
+ 'LT(exp(t), t, s)',
118
+ 'LT(exp(2*t), t, s)',
119
+ 'LT(exp(apos*t), t, s)',
120
+ 'LT(log(t/apos), t, s)',
121
+ 'LT(erf(t), t, s)',
122
+ 'LT(sin(apos*t), t, s)',
123
+ 'LT(cos(apos*t), t, s)',
124
+ 'LT(exp(-apos*t)*sin(bpos*t), t, s)',
125
+ 'LT(exp(-apos*t)*cos(bpos*t), t, s)',
126
+ 'LT(besselj(0, t), t, s, noconds=True)',
127
+ 'LT(besselj(1, t), t, s, noconds=True)',
128
+
129
+ 'FT(Heaviside(1 - abs(2*apos*x)), x, k)',
130
+ 'FT(Heaviside(1-abs(apos*x))*(1-abs(apos*x)), x, k)',
131
+ 'FT(exp(-apos*x)*Heaviside(x), x, k)',
132
+ 'IFT(1/(apos + 2*pi*I*x), x, posk, noconds=False)',
133
+ 'IFT(1/(apos + 2*pi*I*x), x, -posk, noconds=False)',
134
+ 'IFT(1/(apos + 2*pi*I*x), x, negk)',
135
+ 'FT(x*exp(-apos*x)*Heaviside(x), x, k)',
136
+ 'FT(exp(-apos*x)*sin(bpos*x)*Heaviside(x), x, k)',
137
+ 'FT(exp(-apos*x**2), x, k)',
138
+ 'IFT(sqrt(pi/apos)*exp(-(pi*k)**2/apos), k, x)',
139
+ 'FT(exp(-apos*abs(x)), x, k)',
140
+
141
+ 'integrate(normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True)',
142
+ 'integrate(x*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True)',
143
+ 'integrate(x**2*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True)',
144
+ 'integrate(x**3*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True)',
145
+ 'integrate(normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
146
+ ' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
147
+ 'integrate(x*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
148
+ ' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
149
+ 'integrate(y*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
150
+ ' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
151
+ 'integrate(x*y*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
152
+ ' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
153
+ 'integrate((x+y+1)*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
154
+ ' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
155
+ 'integrate((x+y-1)*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
156
+ ' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
157
+ 'integrate(x**2*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
158
+ ' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
159
+ 'integrate(y**2*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
160
+ ' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
161
+ 'integrate(exponential(x, rate), (x, 0, oo), meijerg=True)',
162
+ 'integrate(x*exponential(x, rate), (x, 0, oo), meijerg=True)',
163
+ 'integrate(x**2*exponential(x, rate), (x, 0, oo), meijerg=True)',
164
+ 'E(1)',
165
+ 'E(x*y)',
166
+ 'E(x*y**2)',
167
+ 'E((x+y+1)**2)',
168
+ 'E(x+y+1)',
169
+ 'E((x+y-1)**2)',
170
+ 'integrate(betadist, (x, 0, oo), meijerg=True)',
171
+ 'integrate(x*betadist, (x, 0, oo), meijerg=True)',
172
+ 'integrate(x**2*betadist, (x, 0, oo), meijerg=True)',
173
+ 'integrate(chi, (x, 0, oo), meijerg=True)',
174
+ 'integrate(x*chi, (x, 0, oo), meijerg=True)',
175
+ 'integrate(x**2*chi, (x, 0, oo), meijerg=True)',
176
+ 'integrate(chisquared, (x, 0, oo), meijerg=True)',
177
+ 'integrate(x*chisquared, (x, 0, oo), meijerg=True)',
178
+ 'integrate(x**2*chisquared, (x, 0, oo), meijerg=True)',
179
+ 'integrate(((x-k)/sqrt(2*k))**3*chisquared, (x, 0, oo), meijerg=True)',
180
+ 'integrate(dagum, (x, 0, oo), meijerg=True)',
181
+ 'integrate(x*dagum, (x, 0, oo), meijerg=True)',
182
+ 'integrate(x**2*dagum, (x, 0, oo), meijerg=True)',
183
+ 'integrate(f, (x, 0, oo), meijerg=True)',
184
+ 'integrate(x*f, (x, 0, oo), meijerg=True)',
185
+ 'integrate(x**2*f, (x, 0, oo), meijerg=True)',
186
+ 'integrate(rice, (x, 0, oo), meijerg=True)',
187
+ 'integrate(laplace, (x, -oo, oo), meijerg=True)',
188
+ 'integrate(x*laplace, (x, -oo, oo), meijerg=True)',
189
+ 'integrate(x**2*laplace, (x, -oo, oo), meijerg=True)',
190
+ 'integrate(log(x) * x**(k-1) * exp(-x) / gamma(k), (x, 0, oo))',
191
+
192
+ 'integrate(sin(z*x)*(x**2-1)**(-(y+S(1)/2)), (x, 1, oo), meijerg=True)',
193
+ 'integrate(besselj(0,x)*besselj(1,x)*exp(-x**2), (x, 0, oo), meijerg=True)',
194
+ 'integrate(besselj(0,x)*besselj(1,x)*besselk(0,x), (x, 0, oo), meijerg=True)',
195
+ 'integrate(besselj(0,x)*besselj(1,x)*exp(-x**2), (x, 0, oo), meijerg=True)',
196
+ 'integrate(besselj(a,x)*besselj(b,x)/x, (x,0,oo), meijerg=True)',
197
+
198
+ 'hyperexpand(meijerg((-s - a/2 + 1, -s + a/2 + 1), (-a/2 - S(1)/2, -s + a/2 + S(3)/2), (a/2, -a/2), (-a/2 - S(1)/2, -s + a/2 + S(3)/2), 1))',
199
+ "gammasimp(S('2**(2*s)*(-pi*gamma(-a + 1)*gamma(a + 1)*gamma(-a - s + 1)*gamma(-a + s - 1/2)*gamma(a - s + 3/2)*gamma(a + s + 1)/(a*(a + s)) - gamma(-a - 1/2)*gamma(-a + 1)*gamma(a + 1)*gamma(a + 3/2)*gamma(-s + 3/2)*gamma(s - 1/2)*gamma(-a + s + 1)*gamma(a - s + 1)/(a*(-a + s)))*gamma(-2*s + 1)*gamma(s + 1)/(pi*s*gamma(-a - 1/2)*gamma(a + 3/2)*gamma(-s + 1)*gamma(-s + 3/2)*gamma(s - 1/2)*gamma(-a - s + 1)*gamma(-a + s - 1/2)*gamma(a - s + 1)*gamma(a - s + 3/2))'))",
200
+
201
+ 'mellin_transform(E1(x), x, s)',
202
+ 'inverse_mellin_transform(gamma(s)/s, s, x, (0, oo))',
203
+ 'mellin_transform(expint(a, x), x, s)',
204
+ 'mellin_transform(Si(x), x, s)',
205
+ 'inverse_mellin_transform(-2**s*sqrt(pi)*gamma((s + 1)/2)/(2*s*gamma(-s/2 + 1)), s, x, (-1, 0))',
206
+ 'mellin_transform(Ci(sqrt(x)), x, s)',
207
+ 'inverse_mellin_transform(-4**s*sqrt(pi)*gamma(s)/(2*s*gamma(-s + S(1)/2)),s, u, (0, 1))',
208
+ 'laplace_transform(Ci(x), x, s)',
209
+ 'laplace_transform(expint(a, x), x, s)',
210
+ 'laplace_transform(expint(1, x), x, s)',
211
+ 'laplace_transform(expint(2, x), x, s)',
212
+ 'inverse_laplace_transform(-log(1 + s**2)/2/s, s, u)',
213
+ 'inverse_laplace_transform(log(s + 1)/s, s, x)',
214
+ 'inverse_laplace_transform((s - log(s + 1))/s**2, s, x)',
215
+ 'laplace_transform(Chi(x), x, s)',
216
+ 'laplace_transform(Shi(x), x, s)',
217
+
218
+ 'integrate(exp(-z*x)/x, (x, 1, oo), meijerg=True, conds="none")',
219
+ 'integrate(exp(-z*x)/x**2, (x, 1, oo), meijerg=True, conds="none")',
220
+ 'integrate(exp(-z*x)/x**3, (x, 1, oo), meijerg=True,conds="none")',
221
+ 'integrate(-cos(x)/x, (x, tpos, oo), meijerg=True)',
222
+ 'integrate(-sin(x)/x, (x, tpos, oo), meijerg=True)',
223
+ 'integrate(sin(x)/x, (x, 0, z), meijerg=True)',
224
+ 'integrate(sinh(x)/x, (x, 0, z), meijerg=True)',
225
+ 'integrate(exp(-x)/x, x, meijerg=True)',
226
+ 'integrate(exp(-x)/x**2, x, meijerg=True)',
227
+ 'integrate(cos(u)/u, u, meijerg=True)',
228
+ 'integrate(cosh(u)/u, u, meijerg=True)',
229
+ 'integrate(expint(1, x), x, meijerg=True)',
230
+ 'integrate(expint(2, x), x, meijerg=True)',
231
+ 'integrate(Si(x), x, meijerg=True)',
232
+ 'integrate(Ci(u), u, meijerg=True)',
233
+ 'integrate(Shi(x), x, meijerg=True)',
234
+ 'integrate(Chi(u), u, meijerg=True)',
235
+ 'integrate(Si(x)*exp(-x), (x, 0, oo), meijerg=True)',
236
+ 'integrate(expint(1, x)*sin(x), (x, 0, oo), meijerg=True)'
237
+ ]
238
+
239
+ from time import time
240
+ from sympy.core.cache import clear_cache
241
+ import sys
242
+
243
+ timings = []
244
+
245
+ if __name__ == '__main__':
246
+ for n, string in enumerate(bench):
247
+ clear_cache()
248
+ _t = time()
249
+ exec(string)
250
+ _t = time() - _t
251
+ timings += [(_t, string)]
252
+ sys.stdout.write('.')
253
+ sys.stdout.flush()
254
+ if n % (len(bench) // 10) == 0:
255
+ sys.stdout.write('%s' % (10*n // len(bench)))
256
+ print()
257
+
258
+ timings.sort(key=lambda x: -x[0])
259
+
260
+ for ti, string in timings:
261
+ print('%.2fs %s' % (ti, string))
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/benchmarks/bench_symbench.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ from sympy.core.random import random
3
+ from sympy.core.numbers import (I, Integer, pi)
4
+ from sympy.core.symbol import Symbol
5
+ from sympy.core.sympify import sympify
6
+ from sympy.functions.elementary.miscellaneous import sqrt
7
+ from sympy.functions.elementary.trigonometric import sin
8
+ from sympy.polys.polytools import factor
9
+ from sympy.simplify.simplify import simplify
10
+ from sympy.abc import x, y, z
11
+ from timeit import default_timer as clock
12
+
13
+
14
+ def bench_R1():
15
+ "real(f(f(f(f(f(f(f(f(f(f(i/2)))))))))))"
16
+ def f(z):
17
+ return sqrt(Integer(1)/3)*z**2 + I/3
18
+ f(f(f(f(f(f(f(f(f(f(I/2)))))))))).as_real_imag()[0]
19
+
20
+
21
+ def bench_R2():
22
+ "Hermite polynomial hermite(15, y)"
23
+ def hermite(n, y):
24
+ if n == 1:
25
+ return 2*y
26
+ if n == 0:
27
+ return 1
28
+ return (2*y*hermite(n - 1, y) - 2*(n - 1)*hermite(n - 2, y)).expand()
29
+
30
+ hermite(15, y)
31
+
32
+
33
+ def bench_R3():
34
+ "a = [bool(f==f) for _ in range(10)]"
35
+ f = x + y + z
36
+ [bool(f == f) for _ in range(10)]
37
+
38
+
39
+ def bench_R4():
40
+ # we don't have Tuples
41
+ pass
42
+
43
+
44
+ def bench_R5():
45
+ "blowup(L, 8); L=uniq(L)"
46
+ def blowup(L, n):
47
+ for i in range(n):
48
+ L.append( (L[i] + L[i + 1]) * L[i + 2] )
49
+
50
+ def uniq(x):
51
+ v = set(x)
52
+ return v
53
+ L = [x, y, z]
54
+ blowup(L, 8)
55
+ L = uniq(L)
56
+
57
+
58
+ def bench_R6():
59
+ "sum(simplify((x+sin(i))/x+(x-sin(i))/x) for i in range(100))"
60
+ sum(simplify((x + sin(i))/x + (x - sin(i))/x) for i in range(100))
61
+
62
+
63
+ def bench_R7():
64
+ "[f.subs(x, random()) for _ in range(10**4)]"
65
+ f = x**24 + 34*x**12 + 45*x**3 + 9*x**18 + 34*x**10 + 32*x**21
66
+ [f.subs(x, random()) for _ in range(10**4)]
67
+
68
+
69
+ def bench_R8():
70
+ "right(x^2,0,5,10^4)"
71
+ def right(f, a, b, n):
72
+ a = sympify(a)
73
+ b = sympify(b)
74
+ n = sympify(n)
75
+ x = f.atoms(Symbol).pop()
76
+ Deltax = (b - a)/n
77
+ c = a
78
+ est = 0
79
+ for i in range(n):
80
+ c += Deltax
81
+ est += f.subs(x, c)
82
+ return est*Deltax
83
+
84
+ right(x**2, 0, 5, 10**4)
85
+
86
+
87
+ def _bench_R9():
88
+ "factor(x^20 - pi^5*y^20)"
89
+ factor(x**20 - pi**5*y**20)
90
+
91
+
92
+ def bench_R10():
93
+ "v = [-pi,-pi+1/10..,pi]"
94
+ def srange(min, max, step):
95
+ v = [min]
96
+ while (max - v[-1]).evalf() > 0:
97
+ v.append(v[-1] + step)
98
+ return v[:-1]
99
+ srange(-pi, pi, sympify(1)/10)
100
+
101
+
102
+ def bench_R11():
103
+ "a = [random() + random()*I for w in [0..1000]]"
104
+ [random() + random()*I for w in range(1000)]
105
+
106
+
107
+ def bench_S1():
108
+ "e=(x+y+z+1)**7;f=e*(e+1);f.expand()"
109
+ e = (x + y + z + 1)**7
110
+ f = e*(e + 1)
111
+ f.expand()
112
+
113
+
114
+ if __name__ == '__main__':
115
+ benchmarks = [
116
+ bench_R1,
117
+ bench_R2,
118
+ bench_R3,
119
+ bench_R5,
120
+ bench_R6,
121
+ bench_R7,
122
+ bench_R8,
123
+ #_bench_R9,
124
+ bench_R10,
125
+ bench_R11,
126
+ #bench_S1,
127
+ ]
128
+
129
+ report = []
130
+ for b in benchmarks:
131
+ t = clock()
132
+ b()
133
+ t = clock() - t
134
+ print("%s%65s: %f" % (b.__name__, b.__doc__, t))
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/calculus/__init__.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Calculus-related methods."""
2
+
3
+ from .euler import euler_equations
4
+ from .singularities import (singularities, is_increasing,
5
+ is_strictly_increasing, is_decreasing,
6
+ is_strictly_decreasing, is_monotonic)
7
+ from .finite_diff import finite_diff_weights, apply_finite_diff, differentiate_finite
8
+ from .util import (periodicity, not_empty_in, is_convex,
9
+ stationary_points, minimum, maximum)
10
+ from .accumulationbounds import AccumBounds
11
+
12
+ __all__ = [
13
+ 'euler_equations',
14
+
15
+ 'singularities', 'is_increasing',
16
+ 'is_strictly_increasing', 'is_decreasing',
17
+ 'is_strictly_decreasing', 'is_monotonic',
18
+
19
+ 'finite_diff_weights', 'apply_finite_diff', 'differentiate_finite',
20
+
21
+ 'periodicity', 'not_empty_in', 'is_convex', 'stationary_points',
22
+ 'minimum', 'maximum',
23
+
24
+ 'AccumBounds'
25
+ ]
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/calculus/accumulationbounds.py ADDED
@@ -0,0 +1,804 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import Add, Mul, Pow, S
2
+ from sympy.core.basic import Basic
3
+ from sympy.core.expr import Expr
4
+ from sympy.core.numbers import _sympifyit, oo, zoo
5
+ from sympy.core.relational import is_le, is_lt, is_ge, is_gt
6
+ from sympy.core.sympify import _sympify
7
+ from sympy.functions.elementary.miscellaneous import Min, Max
8
+ from sympy.logic.boolalg import And
9
+ from sympy.multipledispatch import dispatch
10
+ from sympy.series.order import Order
11
+ from sympy.sets.sets import FiniteSet
12
+
13
+
14
+ class AccumulationBounds(Expr):
15
+ r"""An accumulation bounds.
16
+
17
+ # Note AccumulationBounds has an alias: AccumBounds
18
+
19
+ AccumulationBounds represent an interval `[a, b]`, which is always closed
20
+ at the ends. Here `a` and `b` can be any value from extended real numbers.
21
+
22
+ The intended meaning of AccummulationBounds is to give an approximate
23
+ location of the accumulation points of a real function at a limit point.
24
+
25
+ Let `a` and `b` be reals such that `a \le b`.
26
+
27
+ `\left\langle a, b\right\rangle = \{x \in \mathbb{R} \mid a \le x \le b\}`
28
+
29
+ `\left\langle -\infty, b\right\rangle = \{x \in \mathbb{R} \mid x \le b\} \cup \{-\infty, \infty\}`
30
+
31
+ `\left\langle a, \infty \right\rangle = \{x \in \mathbb{R} \mid a \le x\} \cup \{-\infty, \infty\}`
32
+
33
+ `\left\langle -\infty, \infty \right\rangle = \mathbb{R} \cup \{-\infty, \infty\}`
34
+
35
+ ``oo`` and ``-oo`` are added to the second and third definition respectively,
36
+ since if either ``-oo`` or ``oo`` is an argument, then the other one should
37
+ be included (though not as an end point). This is forced, since we have,
38
+ for example, ``1/AccumBounds(0, 1) = AccumBounds(1, oo)``, and the limit at
39
+ `0` is not one-sided. As `x` tends to `0-`, then `1/x \rightarrow -\infty`, so `-\infty`
40
+ should be interpreted as belonging to ``AccumBounds(1, oo)`` though it need
41
+ not appear explicitly.
42
+
43
+ In many cases it suffices to know that the limit set is bounded.
44
+ However, in some other cases more exact information could be useful.
45
+ For example, all accumulation values of `\cos(x) + 1` are non-negative.
46
+ (``AccumBounds(-1, 1) + 1 = AccumBounds(0, 2)``)
47
+
48
+ A AccumulationBounds object is defined to be real AccumulationBounds,
49
+ if its end points are finite reals.
50
+
51
+ Let `X`, `Y` be real AccumulationBounds, then their sum, difference,
52
+ product are defined to be the following sets:
53
+
54
+ `X + Y = \{ x+y \mid x \in X \cap y \in Y\}`
55
+
56
+ `X - Y = \{ x-y \mid x \in X \cap y \in Y\}`
57
+
58
+ `X \times Y = \{ x \times y \mid x \in X \cap y \in Y\}`
59
+
60
+ When an AccumBounds is raised to a negative power, if 0 is contained
61
+ between the bounds then an infinite range is returned, otherwise if an
62
+ endpoint is 0 then a semi-infinite range with consistent sign will be returned.
63
+
64
+ AccumBounds in expressions behave a lot like Intervals but the
65
+ semantics are not necessarily the same. Division (or exponentiation
66
+ to a negative integer power) could be handled with *intervals* by
67
+ returning a union of the results obtained after splitting the
68
+ bounds between negatives and positives, but that is not done with
69
+ AccumBounds. In addition, bounds are assumed to be independent of
70
+ each other; if the same bound is used in more than one place in an
71
+ expression, the result may not be the supremum or infimum of the
72
+ expression (see below). Finally, when a boundary is ``1``,
73
+ exponentiation to the power of ``oo`` yields ``oo``, neither
74
+ ``1`` nor ``nan``.
75
+
76
+ Examples
77
+ ========
78
+
79
+ >>> from sympy import AccumBounds, sin, exp, log, pi, E, S, oo
80
+ >>> from sympy.abc import x
81
+
82
+ >>> AccumBounds(0, 1) + AccumBounds(1, 2)
83
+ AccumBounds(1, 3)
84
+
85
+ >>> AccumBounds(0, 1) - AccumBounds(0, 2)
86
+ AccumBounds(-2, 1)
87
+
88
+ >>> AccumBounds(-2, 3)*AccumBounds(-1, 1)
89
+ AccumBounds(-3, 3)
90
+
91
+ >>> AccumBounds(1, 2)*AccumBounds(3, 5)
92
+ AccumBounds(3, 10)
93
+
94
+ The exponentiation of AccumulationBounds is defined
95
+ as follows:
96
+
97
+ If 0 does not belong to `X` or `n > 0` then
98
+
99
+ `X^n = \{ x^n \mid x \in X\}`
100
+
101
+ >>> AccumBounds(1, 4)**(S(1)/2)
102
+ AccumBounds(1, 2)
103
+
104
+ otherwise, an infinite or semi-infinite result is obtained:
105
+
106
+ >>> 1/AccumBounds(-1, 1)
107
+ AccumBounds(-oo, oo)
108
+ >>> 1/AccumBounds(0, 2)
109
+ AccumBounds(1/2, oo)
110
+ >>> 1/AccumBounds(-oo, 0)
111
+ AccumBounds(-oo, 0)
112
+
113
+ A boundary of 1 will always generate all nonnegatives:
114
+
115
+ >>> AccumBounds(1, 2)**oo
116
+ AccumBounds(0, oo)
117
+ >>> AccumBounds(0, 1)**oo
118
+ AccumBounds(0, oo)
119
+
120
+ If the exponent is itself an AccumulationBounds or is not an
121
+ integer then unevaluated results will be returned unless the base
122
+ values are positive:
123
+
124
+ >>> AccumBounds(2, 3)**AccumBounds(-1, 2)
125
+ AccumBounds(1/3, 9)
126
+ >>> AccumBounds(-2, 3)**AccumBounds(-1, 2)
127
+ AccumBounds(-2, 3)**AccumBounds(-1, 2)
128
+
129
+ >>> AccumBounds(-2, -1)**(S(1)/2)
130
+ sqrt(AccumBounds(-2, -1))
131
+
132
+ Note: `\left\langle a, b\right\rangle^2` is not same as `\left\langle a, b\right\rangle \times \left\langle a, b\right\rangle`
133
+
134
+ >>> AccumBounds(-1, 1)**2
135
+ AccumBounds(0, 1)
136
+
137
+ >>> AccumBounds(1, 3) < 4
138
+ True
139
+
140
+ >>> AccumBounds(1, 3) < -1
141
+ False
142
+
143
+ Some elementary functions can also take AccumulationBounds as input.
144
+ A function `f` evaluated for some real AccumulationBounds `\left\langle a, b \right\rangle`
145
+ is defined as `f(\left\langle a, b\right\rangle) = \{ f(x) \mid a \le x \le b \}`
146
+
147
+ >>> sin(AccumBounds(pi/6, pi/3))
148
+ AccumBounds(1/2, sqrt(3)/2)
149
+
150
+ >>> exp(AccumBounds(0, 1))
151
+ AccumBounds(1, E)
152
+
153
+ >>> log(AccumBounds(1, E))
154
+ AccumBounds(0, 1)
155
+
156
+ Some symbol in an expression can be substituted for a AccumulationBounds
157
+ object. But it does not necessarily evaluate the AccumulationBounds for
158
+ that expression.
159
+
160
+ The same expression can be evaluated to different values depending upon
161
+ the form it is used for substitution since each instance of an
162
+ AccumulationBounds is considered independent. For example:
163
+
164
+ >>> (x**2 + 2*x + 1).subs(x, AccumBounds(-1, 1))
165
+ AccumBounds(-1, 4)
166
+
167
+ >>> ((x + 1)**2).subs(x, AccumBounds(-1, 1))
168
+ AccumBounds(0, 4)
169
+
170
+ References
171
+ ==========
172
+
173
+ .. [1] https://en.wikipedia.org/wiki/Interval_arithmetic
174
+
175
+ .. [2] https://fab.cba.mit.edu/classes/S62.12/docs/Hickey_interval.pdf
176
+
177
+ Notes
178
+ =====
179
+
180
+ Do not use ``AccumulationBounds`` for floating point interval arithmetic
181
+ calculations, use ``mpmath.iv`` instead.
182
+ """
183
+
184
+ is_extended_real = True
185
+ is_number = False
186
+
187
+ def __new__(cls, min, max) -> Expr: # type: ignore
188
+
189
+ min = _sympify(min)
190
+ max = _sympify(max)
191
+
192
+ # Only allow real intervals (use symbols with 'is_extended_real=True').
193
+ if not min.is_extended_real or not max.is_extended_real:
194
+ raise ValueError("Only real AccumulationBounds are supported")
195
+
196
+ if max == min:
197
+ return max
198
+
199
+ # Make sure that the created AccumBounds object will be valid.
200
+ if max.is_number and min.is_number:
201
+ bad = max.is_comparable and min.is_comparable and max < min
202
+ else:
203
+ bad = (max - min).is_extended_negative
204
+ if bad:
205
+ raise ValueError(
206
+ "Lower limit should be smaller than upper limit")
207
+
208
+ return Basic.__new__(cls, min, max)
209
+
210
+ # setting the operation priority
211
+ _op_priority = 11.0
212
+
213
+ def _eval_is_real(self):
214
+ if self.min.is_real and self.max.is_real:
215
+ return True
216
+
217
+ @property
218
+ def min(self):
219
+ """
220
+ Returns the minimum possible value attained by AccumulationBounds
221
+ object.
222
+
223
+ Examples
224
+ ========
225
+
226
+ >>> from sympy import AccumBounds
227
+ >>> AccumBounds(1, 3).min
228
+ 1
229
+
230
+ """
231
+ return self.args[0]
232
+
233
+ @property
234
+ def max(self):
235
+ """
236
+ Returns the maximum possible value attained by AccumulationBounds
237
+ object.
238
+
239
+ Examples
240
+ ========
241
+
242
+ >>> from sympy import AccumBounds
243
+ >>> AccumBounds(1, 3).max
244
+ 3
245
+
246
+ """
247
+ return self.args[1]
248
+
249
+ @property
250
+ def delta(self):
251
+ """
252
+ Returns the difference of maximum possible value attained by
253
+ AccumulationBounds object and minimum possible value attained
254
+ by AccumulationBounds object.
255
+
256
+ Examples
257
+ ========
258
+
259
+ >>> from sympy import AccumBounds
260
+ >>> AccumBounds(1, 3).delta
261
+ 2
262
+
263
+ """
264
+ return self.max - self.min
265
+
266
+ @property
267
+ def mid(self):
268
+ """
269
+ Returns the mean of maximum possible value attained by
270
+ AccumulationBounds object and minimum possible value
271
+ attained by AccumulationBounds object.
272
+
273
+ Examples
274
+ ========
275
+
276
+ >>> from sympy import AccumBounds
277
+ >>> AccumBounds(1, 3).mid
278
+ 2
279
+
280
+ """
281
+ return (self.min + self.max) / 2
282
+
283
+ @_sympifyit('other', NotImplemented)
284
+ def _eval_power(self, other):
285
+ return self.__pow__(other)
286
+
287
+ @_sympifyit('other', NotImplemented)
288
+ def __add__(self, other):
289
+ if isinstance(other, Expr):
290
+ if isinstance(other, AccumBounds):
291
+ return AccumBounds(
292
+ Add(self.min, other.min),
293
+ Add(self.max, other.max))
294
+ if other is S.Infinity and self.min is S.NegativeInfinity or \
295
+ other is S.NegativeInfinity and self.max is S.Infinity:
296
+ return AccumBounds(-oo, oo)
297
+ elif other.is_extended_real:
298
+ if self.min is S.NegativeInfinity and self.max is S.Infinity:
299
+ return AccumBounds(-oo, oo)
300
+ elif self.min is S.NegativeInfinity:
301
+ return AccumBounds(-oo, self.max + other)
302
+ elif self.max is S.Infinity:
303
+ return AccumBounds(self.min + other, oo)
304
+ else:
305
+ return AccumBounds(Add(self.min, other), Add(self.max, other))
306
+ return Add(self, other, evaluate=False)
307
+ return NotImplemented
308
+
309
+ __radd__ = __add__
310
+
311
+ def __neg__(self):
312
+ return AccumBounds(-self.max, -self.min)
313
+
314
+ @_sympifyit('other', NotImplemented)
315
+ def __sub__(self, other):
316
+ if isinstance(other, Expr):
317
+ if isinstance(other, AccumBounds):
318
+ return AccumBounds(
319
+ Add(self.min, -other.max),
320
+ Add(self.max, -other.min))
321
+ if other is S.NegativeInfinity and self.min is S.NegativeInfinity or \
322
+ other is S.Infinity and self.max is S.Infinity:
323
+ return AccumBounds(-oo, oo)
324
+ elif other.is_extended_real:
325
+ if self.min is S.NegativeInfinity and self.max is S.Infinity:
326
+ return AccumBounds(-oo, oo)
327
+ elif self.min is S.NegativeInfinity:
328
+ return AccumBounds(-oo, self.max - other)
329
+ elif self.max is S.Infinity:
330
+ return AccumBounds(self.min - other, oo)
331
+ else:
332
+ return AccumBounds(
333
+ Add(self.min, -other),
334
+ Add(self.max, -other))
335
+ return Add(self, -other, evaluate=False)
336
+ return NotImplemented
337
+
338
+ @_sympifyit('other', NotImplemented)
339
+ def __rsub__(self, other):
340
+ return self.__neg__() + other
341
+
342
+ @_sympifyit('other', NotImplemented)
343
+ def __mul__(self, other):
344
+ if self.args == (-oo, oo):
345
+ return self
346
+ if isinstance(other, Expr):
347
+ if isinstance(other, AccumBounds):
348
+ if other.args == (-oo, oo):
349
+ return other
350
+ v = set()
351
+ for a in self.args:
352
+ vi = other*a
353
+ v.update(vi.args or (vi,))
354
+ return AccumBounds(Min(*v), Max(*v))
355
+ if other is S.Infinity:
356
+ if self.min.is_zero:
357
+ return AccumBounds(0, oo)
358
+ if self.max.is_zero:
359
+ return AccumBounds(-oo, 0)
360
+ if other is S.NegativeInfinity:
361
+ if self.min.is_zero:
362
+ return AccumBounds(-oo, 0)
363
+ if self.max.is_zero:
364
+ return AccumBounds(0, oo)
365
+ if other.is_extended_real:
366
+ if other.is_zero:
367
+ if self.max is S.Infinity:
368
+ return AccumBounds(0, oo)
369
+ if self.min is S.NegativeInfinity:
370
+ return AccumBounds(-oo, 0)
371
+ return S.Zero
372
+ if other.is_extended_positive:
373
+ return AccumBounds(
374
+ Mul(self.min, other),
375
+ Mul(self.max, other))
376
+ elif other.is_extended_negative:
377
+ return AccumBounds(
378
+ Mul(self.max, other),
379
+ Mul(self.min, other))
380
+ if isinstance(other, Order):
381
+ return other
382
+ return Mul(self, other, evaluate=False)
383
+ return NotImplemented
384
+
385
+ __rmul__ = __mul__
386
+
387
+ @_sympifyit('other', NotImplemented)
388
+ def __truediv__(self, other):
389
+ if isinstance(other, Expr):
390
+ if isinstance(other, AccumBounds):
391
+ if other.min.is_positive or other.max.is_negative:
392
+ return self * AccumBounds(1/other.max, 1/other.min)
393
+
394
+ if (self.min.is_extended_nonpositive and self.max.is_extended_nonnegative and
395
+ other.min.is_extended_nonpositive and other.max.is_extended_nonnegative):
396
+ if self.min.is_zero and other.min.is_zero:
397
+ return AccumBounds(0, oo)
398
+ if self.max.is_zero and other.min.is_zero:
399
+ return AccumBounds(-oo, 0)
400
+ return AccumBounds(-oo, oo)
401
+
402
+ if self.max.is_extended_negative:
403
+ if other.min.is_extended_negative:
404
+ if other.max.is_zero:
405
+ return AccumBounds(self.max / other.min, oo)
406
+ if other.max.is_extended_positive:
407
+ # if we were dealing with intervals we would return
408
+ # Union(Interval(-oo, self.max/other.max),
409
+ # Interval(self.max/other.min, oo))
410
+ return AccumBounds(-oo, oo)
411
+
412
+ if other.min.is_zero and other.max.is_extended_positive:
413
+ return AccumBounds(-oo, self.max / other.max)
414
+
415
+ if self.min.is_extended_positive:
416
+ if other.min.is_extended_negative:
417
+ if other.max.is_zero:
418
+ return AccumBounds(-oo, self.min / other.min)
419
+ if other.max.is_extended_positive:
420
+ # if we were dealing with intervals we would return
421
+ # Union(Interval(-oo, self.min/other.min),
422
+ # Interval(self.min/other.max, oo))
423
+ return AccumBounds(-oo, oo)
424
+
425
+ if other.min.is_zero and other.max.is_extended_positive:
426
+ return AccumBounds(self.min / other.max, oo)
427
+
428
+ elif other.is_extended_real:
429
+ if other in (S.Infinity, S.NegativeInfinity):
430
+ if self == AccumBounds(-oo, oo):
431
+ return AccumBounds(-oo, oo)
432
+ if self.max is S.Infinity:
433
+ return AccumBounds(Min(0, other), Max(0, other))
434
+ if self.min is S.NegativeInfinity:
435
+ return AccumBounds(Min(0, -other), Max(0, -other))
436
+ if other.is_extended_positive:
437
+ return AccumBounds(self.min / other, self.max / other)
438
+ elif other.is_extended_negative:
439
+ return AccumBounds(self.max / other, self.min / other)
440
+ if (1 / other) is S.ComplexInfinity:
441
+ return Mul(self, 1 / other, evaluate=False)
442
+ else:
443
+ return Mul(self, 1 / other)
444
+
445
+ return NotImplemented
446
+
447
+ @_sympifyit('other', NotImplemented)
448
+ def __rtruediv__(self, other):
449
+ if isinstance(other, Expr):
450
+ if other.is_extended_real:
451
+ if other.is_zero:
452
+ return S.Zero
453
+ if (self.min.is_extended_nonpositive and self.max.is_extended_nonnegative):
454
+ if self.min.is_zero:
455
+ if other.is_extended_positive:
456
+ return AccumBounds(Mul(other, 1 / self.max), oo)
457
+ if other.is_extended_negative:
458
+ return AccumBounds(-oo, Mul(other, 1 / self.max))
459
+ if self.max.is_zero:
460
+ if other.is_extended_positive:
461
+ return AccumBounds(-oo, Mul(other, 1 / self.min))
462
+ if other.is_extended_negative:
463
+ return AccumBounds(Mul(other, 1 / self.min), oo)
464
+ return AccumBounds(-oo, oo)
465
+ else:
466
+ return AccumBounds(Min(other / self.min, other / self.max),
467
+ Max(other / self.min, other / self.max))
468
+ return Mul(other, 1 / self, evaluate=False)
469
+ else:
470
+ return NotImplemented
471
+
472
+ @_sympifyit('other', NotImplemented)
473
+ def __pow__(self, other):
474
+ if isinstance(other, Expr):
475
+ if other is S.Infinity:
476
+ if self.min.is_extended_nonnegative:
477
+ if self.max < 1:
478
+ return S.Zero
479
+ if self.min > 1:
480
+ return S.Infinity
481
+ return AccumBounds(0, oo)
482
+ elif self.max.is_extended_negative:
483
+ if self.min > -1:
484
+ return S.Zero
485
+ if self.max < -1:
486
+ return zoo
487
+ return S.NaN
488
+ else:
489
+ if self.min > -1:
490
+ if self.max < 1:
491
+ return S.Zero
492
+ return AccumBounds(0, oo)
493
+ return AccumBounds(-oo, oo)
494
+
495
+ if other is S.NegativeInfinity:
496
+ return (1/self)**oo
497
+
498
+ # generically true
499
+ if (self.max - self.min).is_nonnegative:
500
+ # well defined
501
+ if self.min.is_nonnegative:
502
+ # no 0 to worry about
503
+ if other.is_nonnegative:
504
+ # no infinity to worry about
505
+ return self.func(self.min**other, self.max**other)
506
+
507
+ if other.is_zero:
508
+ return S.One # x**0 = 1
509
+
510
+ if other.is_Integer or other.is_integer:
511
+ if self.min.is_extended_positive:
512
+ return AccumBounds(
513
+ Min(self.min**other, self.max**other),
514
+ Max(self.min**other, self.max**other))
515
+ elif self.max.is_extended_negative:
516
+ return AccumBounds(
517
+ Min(self.max**other, self.min**other),
518
+ Max(self.max**other, self.min**other))
519
+
520
+ if other % 2 == 0:
521
+ if other.is_extended_negative:
522
+ if self.min.is_zero:
523
+ return AccumBounds(self.max**other, oo)
524
+ if self.max.is_zero:
525
+ return AccumBounds(self.min**other, oo)
526
+ return (1/self)**(-other)
527
+ return AccumBounds(
528
+ S.Zero, Max(self.min**other, self.max**other))
529
+ elif other % 2 == 1:
530
+ if other.is_extended_negative:
531
+ if self.min.is_zero:
532
+ return AccumBounds(self.max**other, oo)
533
+ if self.max.is_zero:
534
+ return AccumBounds(-oo, self.min**other)
535
+ return (1/self)**(-other)
536
+ return AccumBounds(self.min**other, self.max**other)
537
+
538
+ # non-integer exponent
539
+ # 0**neg or neg**frac yields complex
540
+ if (other.is_number or other.is_rational) and (
541
+ self.min.is_extended_nonnegative or (
542
+ other.is_extended_nonnegative and
543
+ self.min.is_extended_nonnegative)):
544
+ num, den = other.as_numer_denom()
545
+ if num is S.One:
546
+ return AccumBounds(*[i**(1/den) for i in self.args])
547
+
548
+ elif den is not S.One: # e.g. if other is not Float
549
+ return (self**num)**(1/den) # ok for non-negative base
550
+
551
+ if isinstance(other, AccumBounds):
552
+ if (self.min.is_extended_positive or
553
+ self.min.is_extended_nonnegative and
554
+ other.min.is_extended_nonnegative):
555
+ p = [self**i for i in other.args]
556
+ if not any(i.is_Pow for i in p):
557
+ a = [j for i in p for j in i.args or (i,)]
558
+ try:
559
+ return self.func(min(a), max(a))
560
+ except TypeError: # can't sort
561
+ pass
562
+
563
+ return Pow(self, other, evaluate=False)
564
+
565
+ return NotImplemented
566
+
567
+ @_sympifyit('other', NotImplemented)
568
+ def __rpow__(self, other):
569
+ if other.is_real and other.is_extended_nonnegative and (
570
+ self.max - self.min).is_extended_positive:
571
+ if other is S.One:
572
+ return S.One
573
+ if other.is_extended_positive:
574
+ a, b = [other**i for i in self.args]
575
+ if min(a, b) != a:
576
+ a, b = b, a
577
+ return self.func(a, b)
578
+ if other.is_zero:
579
+ if self.min.is_zero:
580
+ return self.func(0, 1)
581
+ if self.min.is_extended_positive:
582
+ return S.Zero
583
+
584
+ return Pow(other, self, evaluate=False)
585
+
586
+ def __abs__(self):
587
+ if self.max.is_extended_negative:
588
+ return self.__neg__()
589
+ elif self.min.is_extended_negative:
590
+ return AccumBounds(S.Zero, Max(abs(self.min), self.max))
591
+ else:
592
+ return self
593
+
594
+
595
+ def __contains__(self, other):
596
+ """
597
+ Returns ``True`` if other is contained in self, where other
598
+ belongs to extended real numbers, ``False`` if not contained,
599
+ otherwise TypeError is raised.
600
+
601
+ Examples
602
+ ========
603
+
604
+ >>> from sympy import AccumBounds, oo
605
+ >>> 1 in AccumBounds(-1, 3)
606
+ True
607
+
608
+ -oo and oo go together as limits (in AccumulationBounds).
609
+
610
+ >>> -oo in AccumBounds(1, oo)
611
+ True
612
+
613
+ >>> oo in AccumBounds(-oo, 0)
614
+ True
615
+
616
+ """
617
+ other = _sympify(other)
618
+
619
+ if other in (S.Infinity, S.NegativeInfinity):
620
+ if self.min is S.NegativeInfinity or self.max is S.Infinity:
621
+ return True
622
+ return False
623
+
624
+ rv = And(self.min <= other, self.max >= other)
625
+ if rv not in (True, False):
626
+ raise TypeError("input failed to evaluate")
627
+ return rv
628
+
629
+ def intersection(self, other):
630
+ """
631
+ Returns the intersection of 'self' and 'other'.
632
+ Here other can be an instance of :py:class:`~.FiniteSet` or AccumulationBounds.
633
+
634
+ Parameters
635
+ ==========
636
+
637
+ other : AccumulationBounds
638
+ Another AccumulationBounds object with which the intersection
639
+ has to be computed.
640
+
641
+ Returns
642
+ =======
643
+
644
+ AccumulationBounds
645
+ Intersection of ``self`` and ``other``.
646
+
647
+ Examples
648
+ ========
649
+
650
+ >>> from sympy import AccumBounds, FiniteSet
651
+ >>> AccumBounds(1, 3).intersection(AccumBounds(2, 4))
652
+ AccumBounds(2, 3)
653
+
654
+ >>> AccumBounds(1, 3).intersection(AccumBounds(4, 6))
655
+ EmptySet
656
+
657
+ >>> AccumBounds(1, 4).intersection(FiniteSet(1, 2, 5))
658
+ {1, 2}
659
+
660
+ """
661
+ if not isinstance(other, (AccumBounds, FiniteSet)):
662
+ raise TypeError(
663
+ "Input must be AccumulationBounds or FiniteSet object")
664
+
665
+ if isinstance(other, FiniteSet):
666
+ fin_set = S.EmptySet
667
+ for i in other:
668
+ if i in self:
669
+ fin_set = fin_set + FiniteSet(i)
670
+ return fin_set
671
+
672
+ if self.max < other.min or self.min > other.max:
673
+ return S.EmptySet
674
+
675
+ if self.min <= other.min:
676
+ if self.max <= other.max:
677
+ return AccumBounds(other.min, self.max)
678
+ if self.max > other.max:
679
+ return other
680
+
681
+ if other.min <= self.min:
682
+ if other.max < self.max:
683
+ return AccumBounds(self.min, other.max)
684
+ if other.max > self.max:
685
+ return self
686
+
687
+ def union(self, other):
688
+ # TODO : Devise a better method for Union of AccumBounds
689
+ # this method is not actually correct and
690
+ # can be made better
691
+ if not isinstance(other, AccumBounds):
692
+ raise TypeError(
693
+ "Input must be AccumulationBounds or FiniteSet object")
694
+
695
+ if self.min <= other.min and self.max >= other.min:
696
+ return AccumBounds(self.min, Max(self.max, other.max))
697
+
698
+ if other.min <= self.min and other.max >= self.min:
699
+ return AccumBounds(other.min, Max(self.max, other.max))
700
+
701
+
702
+ @dispatch(AccumulationBounds, AccumulationBounds) # type: ignore # noqa:F811
703
+ def _eval_is_le(lhs, rhs): # noqa:F811
704
+ if is_le(lhs.max, rhs.min):
705
+ return True
706
+ if is_gt(lhs.min, rhs.max):
707
+ return False
708
+
709
+
710
+ @dispatch(AccumulationBounds, Basic) # type: ignore # noqa:F811
711
+ def _eval_is_le(lhs, rhs): # noqa: F811
712
+
713
+ """
714
+ Returns ``True `` if range of values attained by ``lhs`` AccumulationBounds
715
+ object is greater than the range of values attained by ``rhs``,
716
+ where ``rhs`` may be any value of type AccumulationBounds object or
717
+ extended real number value, ``False`` if ``rhs`` satisfies
718
+ the same property, else an unevaluated :py:class:`~.Relational`.
719
+
720
+ Examples
721
+ ========
722
+
723
+ >>> from sympy import AccumBounds, oo
724
+ >>> AccumBounds(1, 3) > AccumBounds(4, oo)
725
+ False
726
+ >>> AccumBounds(1, 4) > AccumBounds(3, 4)
727
+ AccumBounds(1, 4) > AccumBounds(3, 4)
728
+ >>> AccumBounds(1, oo) > -1
729
+ True
730
+
731
+ """
732
+ if not rhs.is_extended_real:
733
+ raise TypeError(
734
+ "Invalid comparison of %s %s" %
735
+ (type(rhs), rhs))
736
+ elif rhs.is_comparable:
737
+ if is_le(lhs.max, rhs):
738
+ return True
739
+ if is_gt(lhs.min, rhs):
740
+ return False
741
+
742
+
743
+ @dispatch(AccumulationBounds, AccumulationBounds)
744
+ def _eval_is_ge(lhs, rhs): # noqa:F811
745
+ if is_ge(lhs.min, rhs.max):
746
+ return True
747
+ if is_lt(lhs.max, rhs.min):
748
+ return False
749
+
750
+
751
+ @dispatch(AccumulationBounds, Expr) # type:ignore
752
+ def _eval_is_ge(lhs, rhs): # noqa: F811
753
+ """
754
+ Returns ``True`` if range of values attained by ``lhs`` AccumulationBounds
755
+ object is less that the range of values attained by ``rhs``, where
756
+ other may be any value of type AccumulationBounds object or extended
757
+ real number value, ``False`` if ``rhs`` satisfies the same
758
+ property, else an unevaluated :py:class:`~.Relational`.
759
+
760
+ Examples
761
+ ========
762
+
763
+ >>> from sympy import AccumBounds, oo
764
+ >>> AccumBounds(1, 3) >= AccumBounds(4, oo)
765
+ False
766
+ >>> AccumBounds(1, 4) >= AccumBounds(3, 4)
767
+ AccumBounds(1, 4) >= AccumBounds(3, 4)
768
+ >>> AccumBounds(1, oo) >= 1
769
+ True
770
+ """
771
+
772
+ if not rhs.is_extended_real:
773
+ raise TypeError(
774
+ "Invalid comparison of %s %s" %
775
+ (type(rhs), rhs))
776
+ elif rhs.is_comparable:
777
+ if is_ge(lhs.min, rhs):
778
+ return True
779
+ if is_lt(lhs.max, rhs):
780
+ return False
781
+
782
+
783
+ @dispatch(Expr, AccumulationBounds) # type:ignore
784
+ def _eval_is_ge(lhs, rhs): # noqa:F811
785
+ if not lhs.is_extended_real:
786
+ raise TypeError(
787
+ "Invalid comparison of %s %s" %
788
+ (type(lhs), lhs))
789
+ elif lhs.is_comparable:
790
+ if is_le(rhs.max, lhs):
791
+ return True
792
+ if is_gt(rhs.min, lhs):
793
+ return False
794
+
795
+
796
+ @dispatch(AccumulationBounds, AccumulationBounds) # type:ignore
797
+ def _eval_is_ge(lhs, rhs): # noqa:F811
798
+ if is_ge(lhs.min, rhs.max):
799
+ return True
800
+ if is_lt(lhs.max, rhs.min):
801
+ return False
802
+
803
+ # setting an alias for AccumulationBounds
804
+ AccumBounds = AccumulationBounds
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/calculus/euler.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module implements a method to find
3
+ Euler-Lagrange Equations for given Lagrangian.
4
+ """
5
+ from itertools import combinations_with_replacement
6
+ from sympy.core.function import (Derivative, Function, diff)
7
+ from sympy.core.relational import Eq
8
+ from sympy.core.singleton import S
9
+ from sympy.core.symbol import Symbol
10
+ from sympy.core.sympify import sympify
11
+ from sympy.utilities.iterables import iterable
12
+
13
+
14
+ def euler_equations(L, funcs=(), vars=()):
15
+ r"""
16
+ Find the Euler-Lagrange equations [1]_ for a given Lagrangian.
17
+
18
+ Parameters
19
+ ==========
20
+
21
+ L : Expr
22
+ The Lagrangian that should be a function of the functions listed
23
+ in the second argument and their derivatives.
24
+
25
+ For example, in the case of two functions $f(x,y)$, $g(x,y)$ and
26
+ two independent variables $x$, $y$ the Lagrangian has the form:
27
+
28
+ .. math:: L\left(f(x,y),g(x,y),\frac{\partial f(x,y)}{\partial x},
29
+ \frac{\partial f(x,y)}{\partial y},
30
+ \frac{\partial g(x,y)}{\partial x},
31
+ \frac{\partial g(x,y)}{\partial y},x,y\right)
32
+
33
+ In many cases it is not necessary to provide anything, except the
34
+ Lagrangian, it will be auto-detected (and an error raised if this
35
+ cannot be done).
36
+
37
+ funcs : Function or an iterable of Functions
38
+ The functions that the Lagrangian depends on. The Euler equations
39
+ are differential equations for each of these functions.
40
+
41
+ vars : Symbol or an iterable of Symbols
42
+ The Symbols that are the independent variables of the functions.
43
+
44
+ Returns
45
+ =======
46
+
47
+ eqns : list of Eq
48
+ The list of differential equations, one for each function.
49
+
50
+ Examples
51
+ ========
52
+
53
+ >>> from sympy import euler_equations, Symbol, Function
54
+ >>> x = Function('x')
55
+ >>> t = Symbol('t')
56
+ >>> L = (x(t).diff(t))**2/2 - x(t)**2/2
57
+ >>> euler_equations(L, x(t), t)
58
+ [Eq(-x(t) - Derivative(x(t), (t, 2)), 0)]
59
+ >>> u = Function('u')
60
+ >>> x = Symbol('x')
61
+ >>> L = (u(t, x).diff(t))**2/2 - (u(t, x).diff(x))**2/2
62
+ >>> euler_equations(L, u(t, x), [t, x])
63
+ [Eq(-Derivative(u(t, x), (t, 2)) + Derivative(u(t, x), (x, 2)), 0)]
64
+
65
+ References
66
+ ==========
67
+
68
+ .. [1] https://en.wikipedia.org/wiki/Euler%E2%80%93Lagrange_equation
69
+
70
+ """
71
+
72
+ funcs = tuple(funcs) if iterable(funcs) else (funcs,)
73
+
74
+ if not funcs:
75
+ funcs = tuple(L.atoms(Function))
76
+ else:
77
+ for f in funcs:
78
+ if not isinstance(f, Function):
79
+ raise TypeError('Function expected, got: %s' % f)
80
+
81
+ vars = tuple(vars) if iterable(vars) else (vars,)
82
+
83
+ if not vars:
84
+ vars = funcs[0].args
85
+ else:
86
+ vars = tuple(sympify(var) for var in vars)
87
+
88
+ if not all(isinstance(v, Symbol) for v in vars):
89
+ raise TypeError('Variables are not symbols, got %s' % vars)
90
+
91
+ for f in funcs:
92
+ if not vars == f.args:
93
+ raise ValueError("Variables %s do not match args: %s" % (vars, f))
94
+
95
+ order = max([len(d.variables) for d in L.atoms(Derivative)
96
+ if d.expr in funcs] + [0])
97
+
98
+ eqns = []
99
+ for f in funcs:
100
+ eq = diff(L, f)
101
+ for i in range(1, order + 1):
102
+ for p in combinations_with_replacement(vars, i):
103
+ eq = eq + S.NegativeOne**i*diff(L, diff(f, *p), *p)
104
+ new_eq = Eq(eq, 0)
105
+ if isinstance(new_eq, Eq):
106
+ eqns.append(new_eq)
107
+
108
+ return eqns
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/calculus/finite_diff.py ADDED
@@ -0,0 +1,476 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Finite difference weights
3
+ =========================
4
+
5
+ This module implements an algorithm for efficient generation of finite
6
+ difference weights for ordinary differentials of functions for
7
+ derivatives from 0 (interpolation) up to arbitrary order.
8
+
9
+ The core algorithm is provided in the finite difference weight generating
10
+ function (``finite_diff_weights``), and two convenience functions are provided
11
+ for:
12
+
13
+ - estimating a derivative (or interpolate) directly from a series of points
14
+ is also provided (``apply_finite_diff``).
15
+ - differentiating by using finite difference approximations
16
+ (``differentiate_finite``).
17
+
18
+ """
19
+
20
+ from sympy.core.function import Derivative
21
+ from sympy.core.singleton import S
22
+ from sympy.core.function import Subs
23
+ from sympy.core.traversal import preorder_traversal
24
+ from sympy.utilities.exceptions import sympy_deprecation_warning
25
+ from sympy.utilities.iterables import iterable
26
+
27
+
28
+
29
+ def finite_diff_weights(order, x_list, x0=S.One):
30
+ """
31
+ Calculates the finite difference weights for an arbitrarily spaced
32
+ one-dimensional grid (``x_list``) for derivatives at ``x0`` of order
33
+ 0, 1, ..., up to ``order`` using a recursive formula. Order of accuracy
34
+ is at least ``len(x_list) - order``, if ``x_list`` is defined correctly.
35
+
36
+ Parameters
37
+ ==========
38
+
39
+ order: int
40
+ Up to what derivative order weights should be calculated.
41
+ 0 corresponds to interpolation.
42
+ x_list: sequence
43
+ Sequence of (unique) values for the independent variable.
44
+ It is useful (but not necessary) to order ``x_list`` from
45
+ nearest to furthest from ``x0``; see examples below.
46
+ x0: Number or Symbol
47
+ Root or value of the independent variable for which the finite
48
+ difference weights should be generated. Default is ``S.One``.
49
+
50
+ Returns
51
+ =======
52
+
53
+ list
54
+ A list of sublists, each corresponding to coefficients for
55
+ increasing derivative order, and each containing lists of
56
+ coefficients for increasing subsets of x_list.
57
+
58
+ Examples
59
+ ========
60
+
61
+ >>> from sympy import finite_diff_weights, S
62
+ >>> res = finite_diff_weights(1, [-S(1)/2, S(1)/2, S(3)/2, S(5)/2], 0)
63
+ >>> res
64
+ [[[1, 0, 0, 0],
65
+ [1/2, 1/2, 0, 0],
66
+ [3/8, 3/4, -1/8, 0],
67
+ [5/16, 15/16, -5/16, 1/16]],
68
+ [[0, 0, 0, 0],
69
+ [-1, 1, 0, 0],
70
+ [-1, 1, 0, 0],
71
+ [-23/24, 7/8, 1/8, -1/24]]]
72
+ >>> res[0][-1] # FD weights for 0th derivative, using full x_list
73
+ [5/16, 15/16, -5/16, 1/16]
74
+ >>> res[1][-1] # FD weights for 1st derivative
75
+ [-23/24, 7/8, 1/8, -1/24]
76
+ >>> res[1][-2] # FD weights for 1st derivative, using x_list[:-1]
77
+ [-1, 1, 0, 0]
78
+ >>> res[1][-1][0] # FD weight for 1st deriv. for x_list[0]
79
+ -23/24
80
+ >>> res[1][-1][1] # FD weight for 1st deriv. for x_list[1], etc.
81
+ 7/8
82
+
83
+ Each sublist contains the most accurate formula at the end.
84
+ Note, that in the above example ``res[1][1]`` is the same as ``res[1][2]``.
85
+ Since res[1][2] has an order of accuracy of
86
+ ``len(x_list[:3]) - order = 3 - 1 = 2``, the same is true for ``res[1][1]``!
87
+
88
+ >>> res = finite_diff_weights(1, [S(0), S(1), -S(1), S(2), -S(2)], 0)[1]
89
+ >>> res
90
+ [[0, 0, 0, 0, 0],
91
+ [-1, 1, 0, 0, 0],
92
+ [0, 1/2, -1/2, 0, 0],
93
+ [-1/2, 1, -1/3, -1/6, 0],
94
+ [0, 2/3, -2/3, -1/12, 1/12]]
95
+ >>> res[0] # no approximation possible, using x_list[0] only
96
+ [0, 0, 0, 0, 0]
97
+ >>> res[1] # classic forward step approximation
98
+ [-1, 1, 0, 0, 0]
99
+ >>> res[2] # classic centered approximation
100
+ [0, 1/2, -1/2, 0, 0]
101
+ >>> res[3:] # higher order approximations
102
+ [[-1/2, 1, -1/3, -1/6, 0], [0, 2/3, -2/3, -1/12, 1/12]]
103
+
104
+ Let us compare this to a differently defined ``x_list``. Pay attention to
105
+ ``foo[i][k]`` corresponding to the gridpoint defined by ``x_list[k]``.
106
+
107
+ >>> foo = finite_diff_weights(1, [-S(2), -S(1), S(0), S(1), S(2)], 0)[1]
108
+ >>> foo
109
+ [[0, 0, 0, 0, 0],
110
+ [-1, 1, 0, 0, 0],
111
+ [1/2, -2, 3/2, 0, 0],
112
+ [1/6, -1, 1/2, 1/3, 0],
113
+ [1/12, -2/3, 0, 2/3, -1/12]]
114
+ >>> foo[1] # not the same and of lower accuracy as res[1]!
115
+ [-1, 1, 0, 0, 0]
116
+ >>> foo[2] # classic double backward step approximation
117
+ [1/2, -2, 3/2, 0, 0]
118
+ >>> foo[4] # the same as res[4]
119
+ [1/12, -2/3, 0, 2/3, -1/12]
120
+
121
+ Note that, unless you plan on using approximations based on subsets of
122
+ ``x_list``, the order of gridpoints does not matter.
123
+
124
+ The capability to generate weights at arbitrary points can be
125
+ used e.g. to minimize Runge's phenomenon by using Chebyshev nodes:
126
+
127
+ >>> from sympy import cos, symbols, pi, simplify
128
+ >>> N, (h, x) = 4, symbols('h x')
129
+ >>> x_list = [x+h*cos(i*pi/(N)) for i in range(N,-1,-1)] # chebyshev nodes
130
+ >>> print(x_list)
131
+ [-h + x, -sqrt(2)*h/2 + x, x, sqrt(2)*h/2 + x, h + x]
132
+ >>> mycoeffs = finite_diff_weights(1, x_list, 0)[1][4]
133
+ >>> [simplify(c) for c in mycoeffs] #doctest: +NORMALIZE_WHITESPACE
134
+ [(h**3/2 + h**2*x - 3*h*x**2 - 4*x**3)/h**4,
135
+ (-sqrt(2)*h**3 - 4*h**2*x + 3*sqrt(2)*h*x**2 + 8*x**3)/h**4,
136
+ (6*h**2*x - 8*x**3)/h**4,
137
+ (sqrt(2)*h**3 - 4*h**2*x - 3*sqrt(2)*h*x**2 + 8*x**3)/h**4,
138
+ (-h**3/2 + h**2*x + 3*h*x**2 - 4*x**3)/h**4]
139
+
140
+ Notes
141
+ =====
142
+
143
+ If weights for a finite difference approximation of 3rd order
144
+ derivative is wanted, weights for 0th, 1st and 2nd order are
145
+ calculated "for free", so are formulae using subsets of ``x_list``.
146
+ This is something one can take advantage of to save computational cost.
147
+ Be aware that one should define ``x_list`` from nearest to furthest from
148
+ ``x0``. If not, subsets of ``x_list`` will yield poorer approximations,
149
+ which might not grand an order of accuracy of ``len(x_list) - order``.
150
+
151
+ See also
152
+ ========
153
+
154
+ sympy.calculus.finite_diff.apply_finite_diff
155
+
156
+ References
157
+ ==========
158
+
159
+ .. [1] Generation of Finite Difference Formulas on Arbitrarily Spaced
160
+ Grids, Bengt Fornberg; Mathematics of computation; 51; 184;
161
+ (1988); 699-706; doi:10.1090/S0025-5718-1988-0935077-0
162
+
163
+ """
164
+ # The notation below closely corresponds to the one used in the paper.
165
+ order = S(order)
166
+ if not order.is_number:
167
+ raise ValueError("Cannot handle symbolic order.")
168
+ if order < 0:
169
+ raise ValueError("Negative derivative order illegal.")
170
+ if int(order) != order:
171
+ raise ValueError("Non-integer order illegal")
172
+ M = order
173
+ N = len(x_list) - 1
174
+ delta = [[[0 for nu in range(N+1)] for n in range(N+1)] for
175
+ m in range(M+1)]
176
+ delta[0][0][0] = S.One
177
+ c1 = S.One
178
+ for n in range(1, N+1):
179
+ c2 = S.One
180
+ for nu in range(n):
181
+ c3 = x_list[n] - x_list[nu]
182
+ c2 = c2 * c3
183
+ if n <= M:
184
+ delta[n][n-1][nu] = 0
185
+ for m in range(min(n, M)+1):
186
+ delta[m][n][nu] = (x_list[n]-x0)*delta[m][n-1][nu] -\
187
+ m*delta[m-1][n-1][nu]
188
+ delta[m][n][nu] /= c3
189
+ for m in range(min(n, M)+1):
190
+ delta[m][n][n] = c1/c2*(m*delta[m-1][n-1][n-1] -
191
+ (x_list[n-1]-x0)*delta[m][n-1][n-1])
192
+ c1 = c2
193
+ return delta
194
+
195
+
196
+ def apply_finite_diff(order, x_list, y_list, x0=S.Zero):
197
+ """
198
+ Calculates the finite difference approximation of
199
+ the derivative of requested order at ``x0`` from points
200
+ provided in ``x_list`` and ``y_list``.
201
+
202
+ Parameters
203
+ ==========
204
+
205
+ order: int
206
+ order of derivative to approximate. 0 corresponds to interpolation.
207
+ x_list: sequence
208
+ Sequence of (unique) values for the independent variable.
209
+ y_list: sequence
210
+ The function value at corresponding values for the independent
211
+ variable in x_list.
212
+ x0: Number or Symbol
213
+ At what value of the independent variable the derivative should be
214
+ evaluated. Defaults to 0.
215
+
216
+ Returns
217
+ =======
218
+
219
+ sympy.core.add.Add or sympy.core.numbers.Number
220
+ The finite difference expression approximating the requested
221
+ derivative order at ``x0``.
222
+
223
+ Examples
224
+ ========
225
+
226
+ >>> from sympy import apply_finite_diff
227
+ >>> cube = lambda arg: (1.0*arg)**3
228
+ >>> xlist = range(-3,3+1)
229
+ >>> apply_finite_diff(2, xlist, map(cube, xlist), 2) - 12 # doctest: +SKIP
230
+ -3.55271367880050e-15
231
+
232
+ we see that the example above only contain rounding errors.
233
+ apply_finite_diff can also be used on more abstract objects:
234
+
235
+ >>> from sympy import IndexedBase, Idx
236
+ >>> x, y = map(IndexedBase, 'xy')
237
+ >>> i = Idx('i')
238
+ >>> x_list, y_list = zip(*[(x[i+j], y[i+j]) for j in range(-1,2)])
239
+ >>> apply_finite_diff(1, x_list, y_list, x[i])
240
+ ((x[i + 1] - x[i])/(-x[i - 1] + x[i]) - 1)*y[i]/(x[i + 1] - x[i]) -
241
+ (x[i + 1] - x[i])*y[i - 1]/((x[i + 1] - x[i - 1])*(-x[i - 1] + x[i])) +
242
+ (-x[i - 1] + x[i])*y[i + 1]/((x[i + 1] - x[i - 1])*(x[i + 1] - x[i]))
243
+
244
+ Notes
245
+ =====
246
+
247
+ Order = 0 corresponds to interpolation.
248
+ Only supply so many points you think makes sense
249
+ to around x0 when extracting the derivative (the function
250
+ need to be well behaved within that region). Also beware
251
+ of Runge's phenomenon.
252
+
253
+ See also
254
+ ========
255
+
256
+ sympy.calculus.finite_diff.finite_diff_weights
257
+
258
+ References
259
+ ==========
260
+
261
+ Fortran 90 implementation with Python interface for numerics: finitediff_
262
+
263
+ .. _finitediff: https://github.com/bjodah/finitediff
264
+
265
+ """
266
+
267
+ # In the original paper the following holds for the notation:
268
+ # M = order
269
+ # N = len(x_list) - 1
270
+
271
+ N = len(x_list) - 1
272
+ if len(x_list) != len(y_list):
273
+ raise ValueError("x_list and y_list not equal in length.")
274
+
275
+ delta = finite_diff_weights(order, x_list, x0)
276
+
277
+ derivative = 0
278
+ for nu in range(len(x_list)):
279
+ derivative += delta[order][N][nu]*y_list[nu]
280
+ return derivative
281
+
282
+
283
+ def _as_finite_diff(derivative, points=1, x0=None, wrt=None):
284
+ """
285
+ Returns an approximation of a derivative of a function in
286
+ the form of a finite difference formula. The expression is a
287
+ weighted sum of the function at a number of discrete values of
288
+ (one of) the independent variable(s).
289
+
290
+ Parameters
291
+ ==========
292
+
293
+ derivative: a Derivative instance
294
+
295
+ points: sequence or coefficient, optional
296
+ If sequence: discrete values (length >= order+1) of the
297
+ independent variable used for generating the finite
298
+ difference weights.
299
+ If it is a coefficient, it will be used as the step-size
300
+ for generating an equidistant sequence of length order+1
301
+ centered around ``x0``. default: 1 (step-size 1)
302
+
303
+ x0: number or Symbol, optional
304
+ the value of the independent variable (``wrt``) at which the
305
+ derivative is to be approximated. Default: same as ``wrt``.
306
+
307
+ wrt: Symbol, optional
308
+ "with respect to" the variable for which the (partial)
309
+ derivative is to be approximated for. If not provided it
310
+ is required that the Derivative is ordinary. Default: ``None``.
311
+
312
+ Examples
313
+ ========
314
+
315
+ >>> from sympy import symbols, Function, exp, sqrt, Symbol
316
+ >>> from sympy.calculus.finite_diff import _as_finite_diff
317
+ >>> x, h = symbols('x h')
318
+ >>> f = Function('f')
319
+ >>> _as_finite_diff(f(x).diff(x))
320
+ -f(x - 1/2) + f(x + 1/2)
321
+
322
+ The default step size and number of points are 1 and ``order + 1``
323
+ respectively. We can change the step size by passing a symbol
324
+ as a parameter:
325
+
326
+ >>> _as_finite_diff(f(x).diff(x), h)
327
+ -f(-h/2 + x)/h + f(h/2 + x)/h
328
+
329
+ We can also specify the discretized values to be used in a sequence:
330
+
331
+ >>> _as_finite_diff(f(x).diff(x), [x, x+h, x+2*h])
332
+ -3*f(x)/(2*h) + 2*f(h + x)/h - f(2*h + x)/(2*h)
333
+
334
+ The algorithm is not restricted to use equidistant spacing, nor
335
+ do we need to make the approximation around ``x0``, but we can get
336
+ an expression estimating the derivative at an offset:
337
+
338
+ >>> e, sq2 = exp(1), sqrt(2)
339
+ >>> xl = [x-h, x+h, x+e*h]
340
+ >>> _as_finite_diff(f(x).diff(x, 1), xl, x+h*sq2)
341
+ 2*h*((h + sqrt(2)*h)/(2*h) - (-sqrt(2)*h + h)/(2*h))*f(E*h + x)/((-h + E*h)*(h + E*h)) +
342
+ (-(-sqrt(2)*h + h)/(2*h) - (-sqrt(2)*h + E*h)/(2*h))*f(-h + x)/(h + E*h) +
343
+ (-(h + sqrt(2)*h)/(2*h) + (-sqrt(2)*h + E*h)/(2*h))*f(h + x)/(-h + E*h)
344
+
345
+ Partial derivatives are also supported:
346
+
347
+ >>> y = Symbol('y')
348
+ >>> d2fdxdy=f(x,y).diff(x,y)
349
+ >>> _as_finite_diff(d2fdxdy, wrt=x)
350
+ -Derivative(f(x - 1/2, y), y) + Derivative(f(x + 1/2, y), y)
351
+
352
+ See also
353
+ ========
354
+
355
+ sympy.calculus.finite_diff.apply_finite_diff
356
+ sympy.calculus.finite_diff.finite_diff_weights
357
+
358
+ """
359
+ if derivative.is_Derivative:
360
+ pass
361
+ elif derivative.is_Atom:
362
+ return derivative
363
+ else:
364
+ return derivative.fromiter(
365
+ [_as_finite_diff(ar, points, x0, wrt) for ar
366
+ in derivative.args], **derivative.assumptions0)
367
+
368
+ if wrt is None:
369
+ old = None
370
+ for v in derivative.variables:
371
+ if old is v:
372
+ continue
373
+ derivative = _as_finite_diff(derivative, points, x0, v)
374
+ old = v
375
+ return derivative
376
+
377
+ order = derivative.variables.count(wrt)
378
+
379
+ if x0 is None:
380
+ x0 = wrt
381
+
382
+ if not iterable(points):
383
+ if getattr(points, 'is_Function', False) and wrt in points.args:
384
+ points = points.subs(wrt, x0)
385
+ # points is simply the step-size, let's make it a
386
+ # equidistant sequence centered around x0
387
+ if order % 2 == 0:
388
+ # even order => odd number of points, grid point included
389
+ points = [x0 + points*i for i
390
+ in range(-order//2, order//2 + 1)]
391
+ else:
392
+ # odd order => even number of points, half-way wrt grid point
393
+ points = [x0 + points*S(i)/2 for i
394
+ in range(-order, order + 1, 2)]
395
+ others = [wrt, 0]
396
+ for v in set(derivative.variables):
397
+ if v == wrt:
398
+ continue
399
+ others += [v, derivative.variables.count(v)]
400
+ if len(points) < order+1:
401
+ raise ValueError("Too few points for order %d" % order)
402
+ return apply_finite_diff(order, points, [
403
+ Derivative(derivative.expr.subs({wrt: x}), *others) for
404
+ x in points], x0)
405
+
406
+
407
+ def differentiate_finite(expr, *symbols,
408
+ points=1, x0=None, wrt=None, evaluate=False):
409
+ r""" Differentiate expr and replace Derivatives with finite differences.
410
+
411
+ Parameters
412
+ ==========
413
+
414
+ expr : expression
415
+ \*symbols : differentiate with respect to symbols
416
+ points: sequence, coefficient or undefined function, optional
417
+ see ``Derivative.as_finite_difference``
418
+ x0: number or Symbol, optional
419
+ see ``Derivative.as_finite_difference``
420
+ wrt: Symbol, optional
421
+ see ``Derivative.as_finite_difference``
422
+
423
+ Examples
424
+ ========
425
+
426
+ >>> from sympy import sin, Function, differentiate_finite
427
+ >>> from sympy.abc import x, y, h
428
+ >>> f, g = Function('f'), Function('g')
429
+ >>> differentiate_finite(f(x)*g(x), x, points=[x-h, x+h])
430
+ -f(-h + x)*g(-h + x)/(2*h) + f(h + x)*g(h + x)/(2*h)
431
+
432
+ ``differentiate_finite`` works on any expression, including the expressions
433
+ with embedded derivatives:
434
+
435
+ >>> differentiate_finite(f(x) + sin(x), x, 2)
436
+ -2*f(x) + f(x - 1) + f(x + 1) - 2*sin(x) + sin(x - 1) + sin(x + 1)
437
+ >>> differentiate_finite(f(x, y), x, y)
438
+ f(x - 1/2, y - 1/2) - f(x - 1/2, y + 1/2) - f(x + 1/2, y - 1/2) + f(x + 1/2, y + 1/2)
439
+ >>> differentiate_finite(f(x)*g(x).diff(x), x)
440
+ (-g(x) + g(x + 1))*f(x + 1/2) - (g(x) - g(x - 1))*f(x - 1/2)
441
+
442
+ To make finite difference with non-constant discretization step use
443
+ undefined functions:
444
+
445
+ >>> dx = Function('dx')
446
+ >>> differentiate_finite(f(x)*g(x).diff(x), points=dx(x))
447
+ -(-g(x - dx(x)/2 - dx(x - dx(x)/2)/2)/dx(x - dx(x)/2) +
448
+ g(x - dx(x)/2 + dx(x - dx(x)/2)/2)/dx(x - dx(x)/2))*f(x - dx(x)/2)/dx(x) +
449
+ (-g(x + dx(x)/2 - dx(x + dx(x)/2)/2)/dx(x + dx(x)/2) +
450
+ g(x + dx(x)/2 + dx(x + dx(x)/2)/2)/dx(x + dx(x)/2))*f(x + dx(x)/2)/dx(x)
451
+
452
+ """
453
+ if any(term.is_Derivative for term in list(preorder_traversal(expr))):
454
+ evaluate = False
455
+
456
+ Dexpr = expr.diff(*symbols, evaluate=evaluate)
457
+ if evaluate:
458
+ sympy_deprecation_warning("""
459
+ The evaluate flag to differentiate_finite() is deprecated.
460
+
461
+ evaluate=True expands the intermediate derivatives before computing
462
+ differences, but this usually not what you want, as it does not
463
+ satisfy the product rule.
464
+ """,
465
+ deprecated_since_version="1.5",
466
+ active_deprecations_target="deprecated-differentiate_finite-evaluate",
467
+ )
468
+ return Dexpr.replace(
469
+ lambda arg: arg.is_Derivative,
470
+ lambda arg: arg.as_finite_difference(points=points, x0=x0, wrt=wrt))
471
+ else:
472
+ DFexpr = Dexpr.as_finite_difference(points=points, x0=x0, wrt=wrt)
473
+ return DFexpr.replace(
474
+ lambda arg: isinstance(arg, Subs),
475
+ lambda arg: arg.expr.as_finite_difference(
476
+ points=points, x0=arg.point[0], wrt=arg.variables[0]))
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/calculus/singularities.py ADDED
@@ -0,0 +1,406 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Singularities
3
+ =============
4
+
5
+ This module implements algorithms for finding singularities for a function
6
+ and identifying types of functions.
7
+
8
+ The differential calculus methods in this module include methods to identify
9
+ the following function types in the given ``Interval``:
10
+ - Increasing
11
+ - Strictly Increasing
12
+ - Decreasing
13
+ - Strictly Decreasing
14
+ - Monotonic
15
+
16
+ """
17
+
18
+ from sympy.core.power import Pow
19
+ from sympy.core.singleton import S
20
+ from sympy.core.symbol import Symbol
21
+ from sympy.core.sympify import sympify
22
+ from sympy.functions.elementary.exponential import log
23
+ from sympy.functions.elementary.trigonometric import sec, csc, cot, tan, cos
24
+ from sympy.functions.elementary.hyperbolic import (
25
+ sech, csch, coth, tanh, cosh, asech, acsch, atanh, acoth)
26
+ from sympy.utilities.misc import filldedent
27
+
28
+
29
+ def singularities(expression, symbol, domain=None):
30
+ """
31
+ Find singularities of a given function.
32
+
33
+ Parameters
34
+ ==========
35
+
36
+ expression : Expr
37
+ The target function in which singularities need to be found.
38
+ symbol : Symbol
39
+ The symbol over the values of which the singularity in
40
+ expression in being searched for.
41
+
42
+ Returns
43
+ =======
44
+
45
+ Set
46
+ A set of values for ``symbol`` for which ``expression`` has a
47
+ singularity. An ``EmptySet`` is returned if ``expression`` has no
48
+ singularities for any given value of ``Symbol``.
49
+
50
+ Raises
51
+ ======
52
+
53
+ NotImplementedError
54
+ Methods for determining the singularities of this function have
55
+ not been developed.
56
+
57
+ Notes
58
+ =====
59
+
60
+ This function does not find non-isolated singularities
61
+ nor does it find branch points of the expression.
62
+
63
+ Currently supported functions are:
64
+ - univariate continuous (real or complex) functions
65
+
66
+ References
67
+ ==========
68
+
69
+ .. [1] https://en.wikipedia.org/wiki/Mathematical_singularity
70
+
71
+ Examples
72
+ ========
73
+
74
+ >>> from sympy import singularities, Symbol, log
75
+ >>> x = Symbol('x', real=True)
76
+ >>> y = Symbol('y', real=False)
77
+ >>> singularities(x**2 + x + 1, x)
78
+ EmptySet
79
+ >>> singularities(1/(x + 1), x)
80
+ {-1}
81
+ >>> singularities(1/(y**2 + 1), y)
82
+ {-I, I}
83
+ >>> singularities(1/(y**3 + 1), y)
84
+ {-1, 1/2 - sqrt(3)*I/2, 1/2 + sqrt(3)*I/2}
85
+ >>> singularities(log(x), x)
86
+ {0}
87
+
88
+ """
89
+ from sympy.solvers.solveset import solveset
90
+
91
+ if domain is None:
92
+ domain = S.Reals if symbol.is_real else S.Complexes
93
+ try:
94
+ sings = S.EmptySet
95
+ e = expression.rewrite([sec, csc, cot, tan], cos)
96
+ e = e.rewrite([sech, csch, coth, tanh], cosh)
97
+ for i in e.atoms(Pow):
98
+ if i.exp.is_infinite:
99
+ raise NotImplementedError
100
+ if i.exp.is_negative:
101
+ # XXX: exponent of varying sign not handled
102
+ sings += solveset(i.base, symbol, domain)
103
+ for i in expression.atoms(log, asech, acsch):
104
+ sings += solveset(i.args[0], symbol, domain)
105
+ for i in expression.atoms(atanh, acoth):
106
+ sings += solveset(i.args[0] - 1, symbol, domain)
107
+ sings += solveset(i.args[0] + 1, symbol, domain)
108
+ return sings
109
+ except NotImplementedError:
110
+ raise NotImplementedError(filldedent('''
111
+ Methods for determining the singularities
112
+ of this function have not been developed.'''))
113
+
114
+
115
+ ###########################################################################
116
+ # DIFFERENTIAL CALCULUS METHODS #
117
+ ###########################################################################
118
+
119
+
120
+ def monotonicity_helper(expression, predicate, interval=S.Reals, symbol=None):
121
+ """
122
+ Helper function for functions checking function monotonicity.
123
+
124
+ Parameters
125
+ ==========
126
+
127
+ expression : Expr
128
+ The target function which is being checked
129
+ predicate : function
130
+ The property being tested for. The function takes in an integer
131
+ and returns a boolean. The integer input is the derivative and
132
+ the boolean result should be true if the property is being held,
133
+ and false otherwise.
134
+ interval : Set, optional
135
+ The range of values in which we are testing, defaults to all reals.
136
+ symbol : Symbol, optional
137
+ The symbol present in expression which gets varied over the given range.
138
+
139
+ It returns a boolean indicating whether the interval in which
140
+ the function's derivative satisfies given predicate is a superset
141
+ of the given interval.
142
+
143
+ Returns
144
+ =======
145
+
146
+ Boolean
147
+ True if ``predicate`` is true for all the derivatives when ``symbol``
148
+ is varied in ``range``, False otherwise.
149
+
150
+ """
151
+ from sympy.solvers.solveset import solveset
152
+
153
+ expression = sympify(expression)
154
+ free = expression.free_symbols
155
+
156
+ if symbol is None:
157
+ if len(free) > 1:
158
+ raise NotImplementedError(
159
+ 'The function has not yet been implemented'
160
+ ' for all multivariate expressions.'
161
+ )
162
+
163
+ variable = symbol or (free.pop() if free else Symbol('x'))
164
+ derivative = expression.diff(variable)
165
+ predicate_interval = solveset(predicate(derivative), variable, S.Reals)
166
+ return interval.is_subset(predicate_interval)
167
+
168
+
169
+ def is_increasing(expression, interval=S.Reals, symbol=None):
170
+ """
171
+ Return whether the function is increasing in the given interval.
172
+
173
+ Parameters
174
+ ==========
175
+
176
+ expression : Expr
177
+ The target function which is being checked.
178
+ interval : Set, optional
179
+ The range of values in which we are testing (defaults to set of
180
+ all real numbers).
181
+ symbol : Symbol, optional
182
+ The symbol present in expression which gets varied over the given range.
183
+
184
+ Returns
185
+ =======
186
+
187
+ Boolean
188
+ True if ``expression`` is increasing (either strictly increasing or
189
+ constant) in the given ``interval``, False otherwise.
190
+
191
+ Examples
192
+ ========
193
+
194
+ >>> from sympy import is_increasing
195
+ >>> from sympy.abc import x, y
196
+ >>> from sympy import S, Interval, oo
197
+ >>> is_increasing(x**3 - 3*x**2 + 4*x, S.Reals)
198
+ True
199
+ >>> is_increasing(-x**2, Interval(-oo, 0))
200
+ True
201
+ >>> is_increasing(-x**2, Interval(0, oo))
202
+ False
203
+ >>> is_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval(-2, 3))
204
+ False
205
+ >>> is_increasing(x**2 + y, Interval(1, 2), x)
206
+ True
207
+
208
+ """
209
+ return monotonicity_helper(expression, lambda x: x >= 0, interval, symbol)
210
+
211
+
212
+ def is_strictly_increasing(expression, interval=S.Reals, symbol=None):
213
+ """
214
+ Return whether the function is strictly increasing in the given interval.
215
+
216
+ Parameters
217
+ ==========
218
+
219
+ expression : Expr
220
+ The target function which is being checked.
221
+ interval : Set, optional
222
+ The range of values in which we are testing (defaults to set of
223
+ all real numbers).
224
+ symbol : Symbol, optional
225
+ The symbol present in expression which gets varied over the given range.
226
+
227
+ Returns
228
+ =======
229
+
230
+ Boolean
231
+ True if ``expression`` is strictly increasing in the given ``interval``,
232
+ False otherwise.
233
+
234
+ Examples
235
+ ========
236
+
237
+ >>> from sympy import is_strictly_increasing
238
+ >>> from sympy.abc import x, y
239
+ >>> from sympy import Interval, oo
240
+ >>> is_strictly_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval.Ropen(-oo, -2))
241
+ True
242
+ >>> is_strictly_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval.Lopen(3, oo))
243
+ True
244
+ >>> is_strictly_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval.open(-2, 3))
245
+ False
246
+ >>> is_strictly_increasing(-x**2, Interval(0, oo))
247
+ False
248
+ >>> is_strictly_increasing(-x**2 + y, Interval(-oo, 0), x)
249
+ False
250
+
251
+ """
252
+ return monotonicity_helper(expression, lambda x: x > 0, interval, symbol)
253
+
254
+
255
+ def is_decreasing(expression, interval=S.Reals, symbol=None):
256
+ """
257
+ Return whether the function is decreasing in the given interval.
258
+
259
+ Parameters
260
+ ==========
261
+
262
+ expression : Expr
263
+ The target function which is being checked.
264
+ interval : Set, optional
265
+ The range of values in which we are testing (defaults to set of
266
+ all real numbers).
267
+ symbol : Symbol, optional
268
+ The symbol present in expression which gets varied over the given range.
269
+
270
+ Returns
271
+ =======
272
+
273
+ Boolean
274
+ True if ``expression`` is decreasing (either strictly decreasing or
275
+ constant) in the given ``interval``, False otherwise.
276
+
277
+ Examples
278
+ ========
279
+
280
+ >>> from sympy import is_decreasing
281
+ >>> from sympy.abc import x, y
282
+ >>> from sympy import S, Interval, oo
283
+ >>> is_decreasing(1/(x**2 - 3*x), Interval.open(S(3)/2, 3))
284
+ True
285
+ >>> is_decreasing(1/(x**2 - 3*x), Interval.open(1.5, 3))
286
+ True
287
+ >>> is_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo))
288
+ True
289
+ >>> is_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, S(3)/2))
290
+ False
291
+ >>> is_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, 1.5))
292
+ False
293
+ >>> is_decreasing(-x**2, Interval(-oo, 0))
294
+ False
295
+ >>> is_decreasing(-x**2 + y, Interval(-oo, 0), x)
296
+ False
297
+
298
+ """
299
+ return monotonicity_helper(expression, lambda x: x <= 0, interval, symbol)
300
+
301
+
302
+ def is_strictly_decreasing(expression, interval=S.Reals, symbol=None):
303
+ """
304
+ Return whether the function is strictly decreasing in the given interval.
305
+
306
+ Parameters
307
+ ==========
308
+
309
+ expression : Expr
310
+ The target function which is being checked.
311
+ interval : Set, optional
312
+ The range of values in which we are testing (defaults to set of
313
+ all real numbers).
314
+ symbol : Symbol, optional
315
+ The symbol present in expression which gets varied over the given range.
316
+
317
+ Returns
318
+ =======
319
+
320
+ Boolean
321
+ True if ``expression`` is strictly decreasing in the given ``interval``,
322
+ False otherwise.
323
+
324
+ Examples
325
+ ========
326
+
327
+ >>> from sympy import is_strictly_decreasing
328
+ >>> from sympy.abc import x, y
329
+ >>> from sympy import S, Interval, oo
330
+ >>> is_strictly_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo))
331
+ True
332
+ >>> is_strictly_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, S(3)/2))
333
+ False
334
+ >>> is_strictly_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, 1.5))
335
+ False
336
+ >>> is_strictly_decreasing(-x**2, Interval(-oo, 0))
337
+ False
338
+ >>> is_strictly_decreasing(-x**2 + y, Interval(-oo, 0), x)
339
+ False
340
+
341
+ """
342
+ return monotonicity_helper(expression, lambda x: x < 0, interval, symbol)
343
+
344
+
345
+ def is_monotonic(expression, interval=S.Reals, symbol=None):
346
+ """
347
+ Return whether the function is monotonic in the given interval.
348
+
349
+ Parameters
350
+ ==========
351
+
352
+ expression : Expr
353
+ The target function which is being checked.
354
+ interval : Set, optional
355
+ The range of values in which we are testing (defaults to set of
356
+ all real numbers).
357
+ symbol : Symbol, optional
358
+ The symbol present in expression which gets varied over the given range.
359
+
360
+ Returns
361
+ =======
362
+
363
+ Boolean
364
+ True if ``expression`` is monotonic in the given ``interval``,
365
+ False otherwise.
366
+
367
+ Raises
368
+ ======
369
+
370
+ NotImplementedError
371
+ Monotonicity check has not been implemented for the queried function.
372
+
373
+ Examples
374
+ ========
375
+
376
+ >>> from sympy import is_monotonic
377
+ >>> from sympy.abc import x, y
378
+ >>> from sympy import S, Interval, oo
379
+ >>> is_monotonic(1/(x**2 - 3*x), Interval.open(S(3)/2, 3))
380
+ True
381
+ >>> is_monotonic(1/(x**2 - 3*x), Interval.open(1.5, 3))
382
+ True
383
+ >>> is_monotonic(1/(x**2 - 3*x), Interval.Lopen(3, oo))
384
+ True
385
+ >>> is_monotonic(x**3 - 3*x**2 + 4*x, S.Reals)
386
+ True
387
+ >>> is_monotonic(-x**2, S.Reals)
388
+ False
389
+ >>> is_monotonic(x**2 + y + 1, Interval(1, 2), x)
390
+ True
391
+
392
+ """
393
+ from sympy.solvers.solveset import solveset
394
+
395
+ expression = sympify(expression)
396
+
397
+ free = expression.free_symbols
398
+ if symbol is None and len(free) > 1:
399
+ raise NotImplementedError(
400
+ 'is_monotonic has not yet been implemented'
401
+ ' for all multivariate expressions.'
402
+ )
403
+
404
+ variable = symbol or (free.pop() if free else Symbol('x'))
405
+ turning_points = solveset(expression.diff(variable), variable, interval)
406
+ return interval.intersection(turning_points) is S.EmptySet
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/calculus/tests/__init__.py ADDED
File without changes
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/calculus/tests/test_accumulationbounds.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import (E, Rational, oo, pi, zoo)
2
+ from sympy.core.singleton import S
3
+ from sympy.core.symbol import Symbol
4
+ from sympy.functions.elementary.exponential import (exp, log)
5
+ from sympy.functions.elementary.miscellaneous import (Max, Min, sqrt)
6
+ from sympy.functions.elementary.trigonometric import (cos, sin, tan)
7
+ from sympy.calculus.accumulationbounds import AccumBounds
8
+ from sympy.core import Add, Mul, Pow
9
+ from sympy.core.expr import unchanged
10
+ from sympy.testing.pytest import raises, XFAIL
11
+ from sympy.abc import x
12
+
13
+ a = Symbol('a', real=True)
14
+ B = AccumBounds
15
+
16
+
17
+ def test_AccumBounds():
18
+ assert B(1, 2).args == (1, 2)
19
+ assert B(1, 2).delta is S.One
20
+ assert B(1, 2).mid == Rational(3, 2)
21
+ assert B(1, 3).is_real == True
22
+
23
+ assert B(1, 1) is S.One
24
+
25
+ assert B(1, 2) + 1 == B(2, 3)
26
+ assert 1 + B(1, 2) == B(2, 3)
27
+ assert B(1, 2) + B(2, 3) == B(3, 5)
28
+
29
+ assert -B(1, 2) == B(-2, -1)
30
+
31
+ assert B(1, 2) - 1 == B(0, 1)
32
+ assert 1 - B(1, 2) == B(-1, 0)
33
+ assert B(2, 3) - B(1, 2) == B(0, 2)
34
+
35
+ assert x + B(1, 2) == Add(B(1, 2), x)
36
+ assert a + B(1, 2) == B(1 + a, 2 + a)
37
+ assert B(1, 2) - x == Add(B(1, 2), -x)
38
+
39
+ assert B(-oo, 1) + oo == B(-oo, oo)
40
+ assert B(1, oo) + oo is oo
41
+ assert B(1, oo) - oo == B(-oo, oo)
42
+ assert (-oo - B(-1, oo)) is -oo
43
+ assert B(-oo, 1) - oo is -oo
44
+
45
+ assert B(1, oo) - oo == B(-oo, oo)
46
+ assert B(-oo, 1) - (-oo) == B(-oo, oo)
47
+ assert (oo - B(1, oo)) == B(-oo, oo)
48
+ assert (-oo - B(1, oo)) is -oo
49
+
50
+ assert B(1, 2)/2 == B(S.Half, 1)
51
+ assert 2/B(2, 3) == B(Rational(2, 3), 1)
52
+ assert 1/B(-1, 1) == B(-oo, oo)
53
+
54
+ assert abs(B(1, 2)) == B(1, 2)
55
+ assert abs(B(-2, -1)) == B(1, 2)
56
+ assert abs(B(-2, 1)) == B(0, 2)
57
+ assert abs(B(-1, 2)) == B(0, 2)
58
+ c = Symbol('c')
59
+ raises(ValueError, lambda: B(0, c))
60
+ raises(ValueError, lambda: B(1, -1))
61
+ r = Symbol('r', real=True)
62
+ raises(ValueError, lambda: B(r, r - 1))
63
+
64
+
65
+ def test_AccumBounds_mul():
66
+ assert B(1, 2)*2 == B(2, 4)
67
+ assert 2*B(1, 2) == B(2, 4)
68
+ assert B(1, 2)*B(2, 3) == B(2, 6)
69
+ assert B(0, 2)*B(2, oo) == B(0, oo)
70
+ l, r = B(-oo, oo), B(-a, a)
71
+ assert l*r == B(-oo, oo)
72
+ assert r*l == B(-oo, oo)
73
+ l, r = B(1, oo), B(-3, -2)
74
+ assert l*r == B(-oo, -2)
75
+ assert r*l == B(-oo, -2)
76
+ assert B(1, 2)*0 == 0
77
+ assert B(1, oo)*0 == B(0, oo)
78
+ assert B(-oo, 1)*0 == B(-oo, 0)
79
+ assert B(-oo, oo)*0 == B(-oo, oo)
80
+
81
+ assert B(1, 2)*x == Mul(B(1, 2), x, evaluate=False)
82
+
83
+ assert B(0, 2)*oo == B(0, oo)
84
+ assert B(-2, 0)*oo == B(-oo, 0)
85
+ assert B(0, 2)*(-oo) == B(-oo, 0)
86
+ assert B(-2, 0)*(-oo) == B(0, oo)
87
+ assert B(-1, 1)*oo == B(-oo, oo)
88
+ assert B(-1, 1)*(-oo) == B(-oo, oo)
89
+ assert B(-oo, oo)*oo == B(-oo, oo)
90
+
91
+
92
+ def test_AccumBounds_div():
93
+ assert B(-1, 3)/B(3, 4) == B(Rational(-1, 3), 1)
94
+ assert B(-2, 4)/B(-3, 4) == B(-oo, oo)
95
+ assert B(-3, -2)/B(-4, 0) == B(S.Half, oo)
96
+
97
+ # these two tests can have a better answer
98
+ # after Union of B is improved
99
+ assert B(-3, -2)/B(-2, 1) == B(-oo, oo)
100
+ assert B(2, 3)/B(-2, 2) == B(-oo, oo)
101
+
102
+ assert B(-3, -2)/B(0, 4) == B(-oo, Rational(-1, 2))
103
+ assert B(2, 4)/B(-3, 0) == B(-oo, Rational(-2, 3))
104
+ assert B(2, 4)/B(0, 3) == B(Rational(2, 3), oo)
105
+
106
+ assert B(0, 1)/B(0, 1) == B(0, oo)
107
+ assert B(-1, 0)/B(0, 1) == B(-oo, 0)
108
+ assert B(-1, 2)/B(-2, 2) == B(-oo, oo)
109
+
110
+ assert 1/B(-1, 2) == B(-oo, oo)
111
+ assert 1/B(0, 2) == B(S.Half, oo)
112
+ assert (-1)/B(0, 2) == B(-oo, Rational(-1, 2))
113
+ assert 1/B(-oo, 0) == B(-oo, 0)
114
+ assert 1/B(-1, 0) == B(-oo, -1)
115
+ assert (-2)/B(-oo, 0) == B(0, oo)
116
+ assert 1/B(-oo, -1) == B(-1, 0)
117
+
118
+ assert B(1, 2)/a == Mul(B(1, 2), 1/a, evaluate=False)
119
+
120
+ assert B(1, 2)/0 == B(1, 2)*zoo
121
+ assert B(1, oo)/oo == B(0, oo)
122
+ assert B(1, oo)/(-oo) == B(-oo, 0)
123
+ assert B(-oo, -1)/oo == B(-oo, 0)
124
+ assert B(-oo, -1)/(-oo) == B(0, oo)
125
+ assert B(-oo, oo)/oo == B(-oo, oo)
126
+ assert B(-oo, oo)/(-oo) == B(-oo, oo)
127
+ assert B(-1, oo)/oo == B(0, oo)
128
+ assert B(-1, oo)/(-oo) == B(-oo, 0)
129
+ assert B(-oo, 1)/oo == B(-oo, 0)
130
+ assert B(-oo, 1)/(-oo) == B(0, oo)
131
+
132
+
133
+ def test_issue_18795():
134
+ r = Symbol('r', real=True)
135
+ a = B(-1,1)
136
+ c = B(7, oo)
137
+ b = B(-oo, oo)
138
+ assert c - tan(r) == B(7-tan(r), oo)
139
+ assert b + tan(r) == B(-oo, oo)
140
+ assert (a + r)/a == B(-oo, oo)*B(r - 1, r + 1)
141
+ assert (b + a)/a == B(-oo, oo)
142
+
143
+
144
+ def test_AccumBounds_func():
145
+ assert (x**2 + 2*x + 1).subs(x, B(-1, 1)) == B(-1, 4)
146
+ assert exp(B(0, 1)) == B(1, E)
147
+ assert exp(B(-oo, oo)) == B(0, oo)
148
+ assert log(B(3, 6)) == B(log(3), log(6))
149
+
150
+
151
+ @XFAIL
152
+ def test_AccumBounds_powf():
153
+ nn = Symbol('nn', nonnegative=True)
154
+ assert B(1 + nn, 2 + nn)**B(1, 2) == B(1 + nn, (2 + nn)**2)
155
+ i = Symbol('i', integer=True, negative=True)
156
+ assert B(1, 2)**i == B(2**i, 1)
157
+
158
+
159
+ def test_AccumBounds_pow():
160
+ assert B(0, 2)**2 == B(0, 4)
161
+ assert B(-1, 1)**2 == B(0, 1)
162
+ assert B(1, 2)**2 == B(1, 4)
163
+ assert B(-1, 2)**3 == B(-1, 8)
164
+ assert B(-1, 1)**0 == 1
165
+
166
+ assert B(1, 2)**Rational(5, 2) == B(1, 4*sqrt(2))
167
+ assert B(0, 2)**S.Half == B(0, sqrt(2))
168
+
169
+ neg = Symbol('neg', negative=True)
170
+ assert unchanged(Pow, B(neg, 1), S.Half)
171
+ nn = Symbol('nn', nonnegative=True)
172
+ assert B(nn, nn + 1)**S.Half == B(sqrt(nn), sqrt(nn + 1))
173
+ assert B(nn, nn + 1)**nn == B(nn**nn, (nn + 1)**nn)
174
+ assert unchanged(Pow, B(nn, nn + 1), x)
175
+ i = Symbol('i', integer=True)
176
+ assert B(1, 2)**i == B(Min(1, 2**i), Max(1, 2**i))
177
+ i = Symbol('i', integer=True, nonnegative=True)
178
+ assert B(1, 2)**i == B(1, 2**i)
179
+ assert B(0, 1)**i == B(0**i, 1)
180
+
181
+ assert B(1, 5)**(-2) == B(Rational(1, 25), 1)
182
+ assert B(-1, 3)**(-2) == B(0, oo)
183
+ assert B(0, 2)**(-3) == B(Rational(1, 8), oo)
184
+ assert B(-2, 0)**(-3) == B(-oo, -Rational(1, 8))
185
+ assert B(0, 2)**(-2) == B(Rational(1, 4), oo)
186
+ assert B(-1, 2)**(-3) == B(-oo, oo)
187
+ assert B(-3, -2)**(-3) == B(Rational(-1, 8), Rational(-1, 27))
188
+ assert B(-3, -2)**(-2) == B(Rational(1, 9), Rational(1, 4))
189
+ assert B(0, oo)**S.Half == B(0, oo)
190
+ assert B(-oo, 0)**(-2) == B(0, oo)
191
+ assert B(-2, 0)**(-2) == B(Rational(1, 4), oo)
192
+
193
+ assert B(Rational(1, 3), S.Half)**oo is S.Zero
194
+ assert B(0, S.Half)**oo is S.Zero
195
+ assert B(S.Half, 1)**oo == B(0, oo)
196
+ assert B(0, 1)**oo == B(0, oo)
197
+ assert B(2, 3)**oo is oo
198
+ assert B(1, 2)**oo == B(0, oo)
199
+ assert B(S.Half, 3)**oo == B(0, oo)
200
+ assert B(Rational(-1, 3), Rational(-1, 4))**oo is S.Zero
201
+ assert B(-1, Rational(-1, 2))**oo is S.NaN
202
+ assert B(-3, -2)**oo is zoo
203
+ assert B(-2, -1)**oo is S.NaN
204
+ assert B(-2, Rational(-1, 2))**oo is S.NaN
205
+ assert B(Rational(-1, 2), S.Half)**oo is S.Zero
206
+ assert B(Rational(-1, 2), 1)**oo == B(0, oo)
207
+ assert B(Rational(-2, 3), 2)**oo == B(0, oo)
208
+ assert B(-1, 1)**oo == B(-oo, oo)
209
+ assert B(-1, S.Half)**oo == B(-oo, oo)
210
+ assert B(-1, 2)**oo == B(-oo, oo)
211
+ assert B(-2, S.Half)**oo == B(-oo, oo)
212
+
213
+ assert B(1, 2)**x == Pow(B(1, 2), x, evaluate=False)
214
+
215
+ assert B(2, 3)**(-oo) is S.Zero
216
+ assert B(0, 2)**(-oo) == B(0, oo)
217
+ assert B(-1, 2)**(-oo) == B(-oo, oo)
218
+
219
+ assert (tan(x)**sin(2*x)).subs(x, B(0, pi/2)) == \
220
+ Pow(B(-oo, oo), B(0, 1))
221
+
222
+
223
+ def test_AccumBounds_exponent():
224
+ # base is 0
225
+ z = 0**B(a, a + S.Half)
226
+ assert z.subs(a, 0) == B(0, 1)
227
+ assert z.subs(a, 1) == 0
228
+ p = z.subs(a, -1)
229
+ assert p.is_Pow and p.args == (0, B(-1, -S.Half))
230
+ # base > 0
231
+ # when base is 1 the type of bounds does not matter
232
+ assert 1**B(a, a + 1) == 1
233
+ # otherwise we need to know if 0 is in the bounds
234
+ assert S.Half**B(-2, 2) == B(S(1)/4, 4)
235
+ assert 2**B(-2, 2) == B(S(1)/4, 4)
236
+
237
+ # +eps may introduce +oo
238
+ # if there is a negative integer exponent
239
+ assert B(0, 1)**B(S(1)/2, 1) == B(0, 1)
240
+ assert B(0, 1)**B(0, 1) == B(0, 1)
241
+
242
+ # positive bases have positive bounds
243
+ assert B(2, 3)**B(-3, -2) == B(S(1)/27, S(1)/4)
244
+ assert B(2, 3)**B(-3, 2) == B(S(1)/27, 9)
245
+
246
+ # bounds generating imaginary parts unevaluated
247
+ assert unchanged(Pow, B(-1, 1), B(1, 2))
248
+ assert B(0, S(1)/2)**B(1, oo) == B(0, S(1)/2)
249
+ assert B(0, 1)**B(1, oo) == B(0, oo)
250
+ assert B(0, 2)**B(1, oo) == B(0, oo)
251
+ assert B(0, oo)**B(1, oo) == B(0, oo)
252
+ assert B(S(1)/2, 1)**B(1, oo) == B(0, oo)
253
+ assert B(S(1)/2, 1)**B(-oo, -1) == B(0, oo)
254
+ assert B(S(1)/2, 1)**B(-oo, oo) == B(0, oo)
255
+ assert B(S(1)/2, 2)**B(1, oo) == B(0, oo)
256
+ assert B(S(1)/2, 2)**B(-oo, -1) == B(0, oo)
257
+ assert B(S(1)/2, 2)**B(-oo, oo) == B(0, oo)
258
+ assert B(S(1)/2, oo)**B(1, oo) == B(0, oo)
259
+ assert B(S(1)/2, oo)**B(-oo, -1) == B(0, oo)
260
+ assert B(S(1)/2, oo)**B(-oo, oo) == B(0, oo)
261
+ assert B(1, 2)**B(1, oo) == B(0, oo)
262
+ assert B(1, 2)**B(-oo, -1) == B(0, oo)
263
+ assert B(1, 2)**B(-oo, oo) == B(0, oo)
264
+ assert B(1, oo)**B(1, oo) == B(0, oo)
265
+ assert B(1, oo)**B(-oo, -1) == B(0, oo)
266
+ assert B(1, oo)**B(-oo, oo) == B(0, oo)
267
+ assert B(2, oo)**B(1, oo) == B(2, oo)
268
+ assert B(2, oo)**B(-oo, -1) == B(0, S(1)/2)
269
+ assert B(2, oo)**B(-oo, oo) == B(0, oo)
270
+
271
+
272
+ def test_comparison_AccumBounds():
273
+ assert (B(1, 3) < 4) == S.true
274
+ assert (B(1, 3) < -1) == S.false
275
+ assert (B(1, 3) < 2).rel_op == '<'
276
+ assert (B(1, 3) <= 2).rel_op == '<='
277
+
278
+ assert (B(1, 3) > 4) == S.false
279
+ assert (B(1, 3) > -1) == S.true
280
+ assert (B(1, 3) > 2).rel_op == '>'
281
+ assert (B(1, 3) >= 2).rel_op == '>='
282
+
283
+ assert (B(1, 3) < B(4, 6)) == S.true
284
+ assert (B(1, 3) < B(2, 4)).rel_op == '<'
285
+ assert (B(1, 3) < B(-2, 0)) == S.false
286
+
287
+ assert (B(1, 3) <= B(4, 6)) == S.true
288
+ assert (B(1, 3) <= B(-2, 0)) == S.false
289
+
290
+ assert (B(1, 3) > B(4, 6)) == S.false
291
+ assert (B(1, 3) > B(-2, 0)) == S.true
292
+
293
+ assert (B(1, 3) >= B(4, 6)) == S.false
294
+ assert (B(1, 3) >= B(-2, 0)) == S.true
295
+
296
+ # issue 13499
297
+ assert (cos(x) > 0).subs(x, oo) == (B(-1, 1) > 0)
298
+
299
+ c = Symbol('c')
300
+ raises(TypeError, lambda: (B(0, 1) < c))
301
+ raises(TypeError, lambda: (B(0, 1) <= c))
302
+ raises(TypeError, lambda: (B(0, 1) > c))
303
+ raises(TypeError, lambda: (B(0, 1) >= c))
304
+
305
+
306
+ def test_contains_AccumBounds():
307
+ assert (1 in B(1, 2)) == S.true
308
+ raises(TypeError, lambda: a in B(1, 2))
309
+ assert 0 in B(-1, 0)
310
+ raises(TypeError, lambda:
311
+ (cos(1)**2 + sin(1)**2 - 1) in B(-1, 0))
312
+ assert (-oo in B(1, oo)) == S.true
313
+ assert (oo in B(-oo, 0)) == S.true
314
+
315
+ # issue 13159
316
+ assert Mul(0, B(-1, 1)) == Mul(B(-1, 1), 0) == 0
317
+ import itertools
318
+ for perm in itertools.permutations([0, B(-1, 1), x]):
319
+ assert Mul(*perm) == 0
320
+
321
+
322
+ def test_intersection_AccumBounds():
323
+ assert B(0, 3).intersection(B(1, 2)) == B(1, 2)
324
+ assert B(0, 3).intersection(B(1, 4)) == B(1, 3)
325
+ assert B(0, 3).intersection(B(-1, 2)) == B(0, 2)
326
+ assert B(0, 3).intersection(B(-1, 4)) == B(0, 3)
327
+ assert B(0, 1).intersection(B(2, 3)) == S.EmptySet
328
+ raises(TypeError, lambda: B(0, 3).intersection(1))
329
+
330
+
331
+ def test_union_AccumBounds():
332
+ assert B(0, 3).union(B(1, 2)) == B(0, 3)
333
+ assert B(0, 3).union(B(1, 4)) == B(0, 4)
334
+ assert B(0, 3).union(B(-1, 2)) == B(-1, 3)
335
+ assert B(0, 3).union(B(-1, 4)) == B(-1, 4)
336
+ raises(TypeError, lambda: B(0, 3).union(1))
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/calculus/tests/test_euler.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.function import (Derivative as D, Function)
2
+ from sympy.core.relational import Eq
3
+ from sympy.core.symbol import (Symbol, symbols)
4
+ from sympy.functions.elementary.trigonometric import (cos, sin)
5
+ from sympy.testing.pytest import raises
6
+ from sympy.calculus.euler import euler_equations as euler
7
+
8
+
9
+ def test_euler_interface():
10
+ x = Function('x')
11
+ y = Symbol('y')
12
+ t = Symbol('t')
13
+ raises(TypeError, lambda: euler())
14
+ raises(TypeError, lambda: euler(D(x(t), t)*y(t), [x(t), y]))
15
+ raises(ValueError, lambda: euler(D(x(t), t)*x(y), [x(t), x(y)]))
16
+ raises(TypeError, lambda: euler(D(x(t), t)**2, x(0)))
17
+ raises(TypeError, lambda: euler(D(x(t), t)*y(t), [t]))
18
+ assert euler(D(x(t), t)**2/2, {x(t)}) == [Eq(-D(x(t), t, t), 0)]
19
+ assert euler(D(x(t), t)**2/2, x(t), {t}) == [Eq(-D(x(t), t, t), 0)]
20
+
21
+
22
+ def test_euler_pendulum():
23
+ x = Function('x')
24
+ t = Symbol('t')
25
+ L = D(x(t), t)**2/2 + cos(x(t))
26
+ assert euler(L, x(t), t) == [Eq(-sin(x(t)) - D(x(t), t, t), 0)]
27
+
28
+
29
+ def test_euler_henonheiles():
30
+ x = Function('x')
31
+ y = Function('y')
32
+ t = Symbol('t')
33
+ L = sum(D(z(t), t)**2/2 - z(t)**2/2 for z in [x, y])
34
+ L += -x(t)**2*y(t) + y(t)**3/3
35
+ assert euler(L, [x(t), y(t)], t) == [Eq(-2*x(t)*y(t) - x(t) -
36
+ D(x(t), t, t), 0),
37
+ Eq(-x(t)**2 + y(t)**2 -
38
+ y(t) - D(y(t), t, t), 0)]
39
+
40
+
41
+ def test_euler_sineg():
42
+ psi = Function('psi')
43
+ t = Symbol('t')
44
+ x = Symbol('x')
45
+ L = D(psi(t, x), t)**2/2 - D(psi(t, x), x)**2/2 + cos(psi(t, x))
46
+ assert euler(L, psi(t, x), [t, x]) == [Eq(-sin(psi(t, x)) -
47
+ D(psi(t, x), t, t) +
48
+ D(psi(t, x), x, x), 0)]
49
+
50
+
51
+ def test_euler_high_order():
52
+ # an example from hep-th/0309038
53
+ m = Symbol('m')
54
+ k = Symbol('k')
55
+ x = Function('x')
56
+ y = Function('y')
57
+ t = Symbol('t')
58
+ L = (m*D(x(t), t)**2/2 + m*D(y(t), t)**2/2 -
59
+ k*D(x(t), t)*D(y(t), t, t) + k*D(y(t), t)*D(x(t), t, t))
60
+ assert euler(L, [x(t), y(t)]) == [Eq(2*k*D(y(t), t, t, t) -
61
+ m*D(x(t), t, t), 0),
62
+ Eq(-2*k*D(x(t), t, t, t) -
63
+ m*D(y(t), t, t), 0)]
64
+
65
+ w = Symbol('w')
66
+ L = D(x(t, w), t, w)**2/2
67
+ assert euler(L) == [Eq(D(x(t, w), t, t, w, w), 0)]
68
+
69
+ def test_issue_18653():
70
+ x, y, z = symbols("x y z")
71
+ f, g, h = symbols("f g h", cls=Function, args=(x, y))
72
+ f, g, h = f(), g(), h()
73
+ expr2 = f.diff(x)*h.diff(z)
74
+ assert euler(expr2, (f,), (x, y)) == []
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/calculus/tests/test_finite_diff.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import product
2
+
3
+ from sympy.core.function import (Function, diff)
4
+ from sympy.core.numbers import Rational
5
+ from sympy.core.singleton import S
6
+ from sympy.core.symbol import symbols
7
+ from sympy.functions.elementary.exponential import exp
8
+ from sympy.calculus.finite_diff import (
9
+ apply_finite_diff, differentiate_finite, finite_diff_weights,
10
+ _as_finite_diff
11
+ )
12
+ from sympy.testing.pytest import raises, warns_deprecated_sympy
13
+
14
+
15
+ def test_apply_finite_diff():
16
+ x, h = symbols('x h')
17
+ f = Function('f')
18
+ assert (apply_finite_diff(1, [x-h, x+h], [f(x-h), f(x+h)], x) -
19
+ (f(x+h)-f(x-h))/(2*h)).simplify() == 0
20
+
21
+ assert (apply_finite_diff(1, [5, 6, 7], [f(5), f(6), f(7)], 5) -
22
+ (Rational(-3, 2)*f(5) + 2*f(6) - S.Half*f(7))).simplify() == 0
23
+ raises(ValueError, lambda: apply_finite_diff(1, [x, h], [f(x)]))
24
+
25
+
26
+ def test_finite_diff_weights():
27
+
28
+ d = finite_diff_weights(1, [5, 6, 7], 5)
29
+ assert d[1][2] == [Rational(-3, 2), 2, Rational(-1, 2)]
30
+
31
+ # Table 1, p. 702 in doi:10.1090/S0025-5718-1988-0935077-0
32
+ # --------------------------------------------------------
33
+ xl = [0, 1, -1, 2, -2, 3, -3, 4, -4]
34
+
35
+ # d holds all coefficients
36
+ d = finite_diff_weights(4, xl, S.Zero)
37
+
38
+ # Zeroeth derivative
39
+ for i in range(5):
40
+ assert d[0][i] == [S.One] + [S.Zero]*8
41
+
42
+ # First derivative
43
+ assert d[1][0] == [S.Zero]*9
44
+ assert d[1][2] == [S.Zero, S.Half, Rational(-1, 2)] + [S.Zero]*6
45
+ assert d[1][4] == [S.Zero, Rational(2, 3), Rational(-2, 3), Rational(-1, 12), Rational(1, 12)] + [S.Zero]*4
46
+ assert d[1][6] == [S.Zero, Rational(3, 4), Rational(-3, 4), Rational(-3, 20), Rational(3, 20),
47
+ Rational(1, 60), Rational(-1, 60)] + [S.Zero]*2
48
+ assert d[1][8] == [S.Zero, Rational(4, 5), Rational(-4, 5), Rational(-1, 5), Rational(1, 5),
49
+ Rational(4, 105), Rational(-4, 105), Rational(-1, 280), Rational(1, 280)]
50
+
51
+ # Second derivative
52
+ for i in range(2):
53
+ assert d[2][i] == [S.Zero]*9
54
+ assert d[2][2] == [-S(2), S.One, S.One] + [S.Zero]*6
55
+ assert d[2][4] == [Rational(-5, 2), Rational(4, 3), Rational(4, 3), Rational(-1, 12), Rational(-1, 12)] + [S.Zero]*4
56
+ assert d[2][6] == [Rational(-49, 18), Rational(3, 2), Rational(3, 2), Rational(-3, 20), Rational(-3, 20),
57
+ Rational(1, 90), Rational(1, 90)] + [S.Zero]*2
58
+ assert d[2][8] == [Rational(-205, 72), Rational(8, 5), Rational(8, 5), Rational(-1, 5), Rational(-1, 5),
59
+ Rational(8, 315), Rational(8, 315), Rational(-1, 560), Rational(-1, 560)]
60
+
61
+ # Third derivative
62
+ for i in range(3):
63
+ assert d[3][i] == [S.Zero]*9
64
+ assert d[3][4] == [S.Zero, -S.One, S.One, S.Half, Rational(-1, 2)] + [S.Zero]*4
65
+ assert d[3][6] == [S.Zero, Rational(-13, 8), Rational(13, 8), S.One, -S.One,
66
+ Rational(-1, 8), Rational(1, 8)] + [S.Zero]*2
67
+ assert d[3][8] == [S.Zero, Rational(-61, 30), Rational(61, 30), Rational(169, 120), Rational(-169, 120),
68
+ Rational(-3, 10), Rational(3, 10), Rational(7, 240), Rational(-7, 240)]
69
+
70
+ # Fourth derivative
71
+ for i in range(4):
72
+ assert d[4][i] == [S.Zero]*9
73
+ assert d[4][4] == [S(6), -S(4), -S(4), S.One, S.One] + [S.Zero]*4
74
+ assert d[4][6] == [Rational(28, 3), Rational(-13, 2), Rational(-13, 2), S(2), S(2),
75
+ Rational(-1, 6), Rational(-1, 6)] + [S.Zero]*2
76
+ assert d[4][8] == [Rational(91, 8), Rational(-122, 15), Rational(-122, 15), Rational(169, 60), Rational(169, 60),
77
+ Rational(-2, 5), Rational(-2, 5), Rational(7, 240), Rational(7, 240)]
78
+
79
+ # Table 2, p. 703 in doi:10.1090/S0025-5718-1988-0935077-0
80
+ # --------------------------------------------------------
81
+ xl = [[j/S(2) for j in list(range(-i*2+1, 0, 2))+list(range(1, i*2+1, 2))]
82
+ for i in range(1, 5)]
83
+
84
+ # d holds all coefficients
85
+ d = [finite_diff_weights({0: 1, 1: 2, 2: 4, 3: 4}[i], xl[i], 0) for
86
+ i in range(4)]
87
+
88
+ # Zeroth derivative
89
+ assert d[0][0][1] == [S.Half, S.Half]
90
+ assert d[1][0][3] == [Rational(-1, 16), Rational(9, 16), Rational(9, 16), Rational(-1, 16)]
91
+ assert d[2][0][5] == [Rational(3, 256), Rational(-25, 256), Rational(75, 128), Rational(75, 128),
92
+ Rational(-25, 256), Rational(3, 256)]
93
+ assert d[3][0][7] == [Rational(-5, 2048), Rational(49, 2048), Rational(-245, 2048), Rational(1225, 2048),
94
+ Rational(1225, 2048), Rational(-245, 2048), Rational(49, 2048), Rational(-5, 2048)]
95
+
96
+ # First derivative
97
+ assert d[0][1][1] == [-S.One, S.One]
98
+ assert d[1][1][3] == [Rational(1, 24), Rational(-9, 8), Rational(9, 8), Rational(-1, 24)]
99
+ assert d[2][1][5] == [Rational(-3, 640), Rational(25, 384), Rational(-75, 64),
100
+ Rational(75, 64), Rational(-25, 384), Rational(3, 640)]
101
+ assert d[3][1][7] == [Rational(5, 7168), Rational(-49, 5120),
102
+ Rational(245, 3072), Rational(-1225, 1024),
103
+ Rational(1225, 1024), Rational(-245, 3072),
104
+ Rational(49, 5120), Rational(-5, 7168)]
105
+
106
+ # Reasonably the rest of the table is also correct... (testing of that
107
+ # deemed excessive at the moment)
108
+ raises(ValueError, lambda: finite_diff_weights(-1, [1, 2]))
109
+ raises(ValueError, lambda: finite_diff_weights(1.2, [1, 2]))
110
+ x = symbols('x')
111
+ raises(ValueError, lambda: finite_diff_weights(x, [1, 2]))
112
+
113
+
114
+ def test_as_finite_diff():
115
+ x = symbols('x')
116
+ f = Function('f')
117
+ dx = Function('dx')
118
+
119
+ _as_finite_diff(f(x).diff(x), [x-2, x-1, x, x+1, x+2])
120
+
121
+ # Use of undefined functions in ``points``
122
+ df_true = -f(x+dx(x)/2-dx(x+dx(x)/2)/2) / dx(x+dx(x)/2) \
123
+ + f(x+dx(x)/2+dx(x+dx(x)/2)/2) / dx(x+dx(x)/2)
124
+ df_test = diff(f(x), x).as_finite_difference(points=dx(x), x0=x+dx(x)/2)
125
+ assert (df_test - df_true).simplify() == 0
126
+
127
+
128
+ def test_differentiate_finite():
129
+ x, y, h = symbols('x y h')
130
+ f = Function('f')
131
+ with warns_deprecated_sympy():
132
+ res0 = differentiate_finite(f(x, y) + exp(42), x, y, evaluate=True)
133
+ xm, xp, ym, yp = [v + sign*S.Half for v, sign in product([x, y], [-1, 1])]
134
+ ref0 = f(xm, ym) + f(xp, yp) - f(xm, yp) - f(xp, ym)
135
+ assert (res0 - ref0).simplify() == 0
136
+
137
+ g = Function('g')
138
+ with warns_deprecated_sympy():
139
+ res1 = differentiate_finite(f(x)*g(x) + 42, x, evaluate=True)
140
+ ref1 = (-f(x - S.Half) + f(x + S.Half))*g(x) + \
141
+ (-g(x - S.Half) + g(x + S.Half))*f(x)
142
+ assert (res1 - ref1).simplify() == 0
143
+
144
+ res2 = differentiate_finite(f(x) + x**3 + 42, x, points=[x-1, x+1])
145
+ ref2 = (f(x + 1) + (x + 1)**3 - f(x - 1) - (x - 1)**3)/2
146
+ assert (res2 - ref2).simplify() == 0
147
+ raises(TypeError, lambda: differentiate_finite(f(x)*g(x), x,
148
+ pints=[x-1, x+1]))
149
+
150
+ res3 = differentiate_finite(f(x)*g(x).diff(x), x)
151
+ ref3 = (-g(x) + g(x + 1))*f(x + S.Half) - (g(x) - g(x - 1))*f(x - S.Half)
152
+ assert res3 == ref3
153
+
154
+ res4 = differentiate_finite(f(x)*g(x).diff(x).diff(x), x)
155
+ ref4 = -((g(x - Rational(3, 2)) - 2*g(x - S.Half) + g(x + S.Half))*f(x - S.Half)) \
156
+ + (g(x - S.Half) - 2*g(x + S.Half) + g(x + Rational(3, 2)))*f(x + S.Half)
157
+ assert res4 == ref4
158
+
159
+ res5_expr = f(x).diff(x)*g(x).diff(x)
160
+ res5 = differentiate_finite(res5_expr, points=[x-h, x, x+h])
161
+ ref5 = (-2*f(x)/h + f(-h + x)/(2*h) + 3*f(h + x)/(2*h))*(-2*g(x)/h + g(-h + x)/(2*h) \
162
+ + 3*g(h + x)/(2*h))/(2*h) - (2*f(x)/h - 3*f(-h + x)/(2*h) - \
163
+ f(h + x)/(2*h))*(2*g(x)/h - 3*g(-h + x)/(2*h) - g(h + x)/(2*h))/(2*h)
164
+ assert res5 == ref5
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/calculus/tests/test_singularities.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import (I, Rational, pi, oo)
2
+ from sympy.core.singleton import S
3
+ from sympy.core.symbol import Symbol, Dummy
4
+ from sympy.core.function import Lambda
5
+ from sympy.functions.elementary.exponential import (exp, log)
6
+ from sympy.functions.elementary.trigonometric import sec, csc
7
+ from sympy.functions.elementary.hyperbolic import (coth, sech,
8
+ atanh, asech, acoth, acsch)
9
+ from sympy.functions.elementary.miscellaneous import sqrt
10
+ from sympy.calculus.singularities import (
11
+ singularities,
12
+ is_increasing,
13
+ is_strictly_increasing,
14
+ is_decreasing,
15
+ is_strictly_decreasing,
16
+ is_monotonic
17
+ )
18
+ from sympy.sets import Interval, FiniteSet, Union, ImageSet
19
+ from sympy.testing.pytest import raises
20
+ from sympy.abc import x, y
21
+
22
+
23
+ def test_singularities():
24
+ x = Symbol('x')
25
+ assert singularities(x**2, x) == S.EmptySet
26
+ assert singularities(x/(x**2 + 3*x + 2), x) == FiniteSet(-2, -1)
27
+ assert singularities(1/(x**2 + 1), x) == FiniteSet(I, -I)
28
+ assert singularities(x/(x**3 + 1), x) == \
29
+ FiniteSet(-1, (1 - sqrt(3) * I) / 2, (1 + sqrt(3) * I) / 2)
30
+ assert singularities(1/(y**2 + 2*I*y + 1), y) == \
31
+ FiniteSet(-I + sqrt(2)*I, -I - sqrt(2)*I)
32
+ _n = Dummy('n')
33
+ assert singularities(sech(x), x).dummy_eq(Union(
34
+ ImageSet(Lambda(_n, 2*_n*I*pi + I*pi/2), S.Integers),
35
+ ImageSet(Lambda(_n, 2*_n*I*pi + 3*I*pi/2), S.Integers)))
36
+ assert singularities(coth(x), x).dummy_eq(Union(
37
+ ImageSet(Lambda(_n, 2*_n*I*pi + I*pi), S.Integers),
38
+ ImageSet(Lambda(_n, 2*_n*I*pi), S.Integers)))
39
+ assert singularities(atanh(x), x) == FiniteSet(-1, 1)
40
+ assert singularities(acoth(x), x) == FiniteSet(-1, 1)
41
+ assert singularities(asech(x), x) == FiniteSet(0)
42
+ assert singularities(acsch(x), x) == FiniteSet(0)
43
+
44
+ x = Symbol('x', real=True)
45
+ assert singularities(1/(x**2 + 1), x) == S.EmptySet
46
+ assert singularities(exp(1/x), x, S.Reals) == FiniteSet(0)
47
+ assert singularities(exp(1/x), x, Interval(1, 2)) == S.EmptySet
48
+ assert singularities(log((x - 2)**2), x, Interval(1, 3)) == FiniteSet(2)
49
+ raises(NotImplementedError, lambda: singularities(x**-oo, x))
50
+ assert singularities(sec(x), x, Interval(0, 3*pi)) == FiniteSet(
51
+ pi/2, 3*pi/2, 5*pi/2)
52
+ assert singularities(csc(x), x, Interval(0, 3*pi)) == FiniteSet(
53
+ 0, pi, 2*pi, 3*pi)
54
+
55
+
56
+ def test_is_increasing():
57
+ """Test whether is_increasing returns correct value."""
58
+ a = Symbol('a', negative=True)
59
+
60
+ assert is_increasing(x**3 - 3*x**2 + 4*x, S.Reals)
61
+ assert is_increasing(-x**2, Interval(-oo, 0))
62
+ assert not is_increasing(-x**2, Interval(0, oo))
63
+ assert not is_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval(-2, 3))
64
+ assert is_increasing(x**2 + y, Interval(1, oo), x)
65
+ assert is_increasing(-x**2*a, Interval(1, oo), x)
66
+ assert is_increasing(1)
67
+
68
+ assert is_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval(-2, 3)) is False
69
+
70
+
71
+ def test_is_strictly_increasing():
72
+ """Test whether is_strictly_increasing returns correct value."""
73
+ assert is_strictly_increasing(
74
+ 4*x**3 - 6*x**2 - 72*x + 30, Interval.Ropen(-oo, -2))
75
+ assert is_strictly_increasing(
76
+ 4*x**3 - 6*x**2 - 72*x + 30, Interval.Lopen(3, oo))
77
+ assert not is_strictly_increasing(
78
+ 4*x**3 - 6*x**2 - 72*x + 30, Interval.open(-2, 3))
79
+ assert not is_strictly_increasing(-x**2, Interval(0, oo))
80
+ assert not is_strictly_decreasing(1)
81
+
82
+ assert is_strictly_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval.open(-2, 3)) is False
83
+
84
+
85
+ def test_is_decreasing():
86
+ """Test whether is_decreasing returns correct value."""
87
+ b = Symbol('b', positive=True)
88
+
89
+ assert is_decreasing(1/(x**2 - 3*x), Interval.open(Rational(3,2), 3))
90
+ assert is_decreasing(1/(x**2 - 3*x), Interval.open(1.5, 3))
91
+ assert is_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo))
92
+ assert not is_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, Rational(3, 2)))
93
+ assert not is_decreasing(-x**2, Interval(-oo, 0))
94
+ assert not is_decreasing(-x**2*b, Interval(-oo, 0), x)
95
+
96
+
97
+ def test_is_strictly_decreasing():
98
+ """Test whether is_strictly_decreasing returns correct value."""
99
+ assert is_strictly_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo))
100
+ assert not is_strictly_decreasing(
101
+ 1/(x**2 - 3*x), Interval.Ropen(-oo, Rational(3, 2)))
102
+ assert not is_strictly_decreasing(-x**2, Interval(-oo, 0))
103
+ assert not is_strictly_decreasing(1)
104
+ assert is_strictly_decreasing(1/(x**2 - 3*x), Interval.open(Rational(3,2), 3))
105
+ assert is_strictly_decreasing(1/(x**2 - 3*x), Interval.open(1.5, 3))
106
+
107
+
108
+ def test_is_monotonic():
109
+ """Test whether is_monotonic returns correct value."""
110
+ assert is_monotonic(1/(x**2 - 3*x), Interval.open(Rational(3,2), 3))
111
+ assert is_monotonic(1/(x**2 - 3*x), Interval.open(1.5, 3))
112
+ assert is_monotonic(1/(x**2 - 3*x), Interval.Lopen(3, oo))
113
+ assert is_monotonic(x**3 - 3*x**2 + 4*x, S.Reals)
114
+ assert not is_monotonic(-x**2, S.Reals)
115
+ assert is_monotonic(x**2 + y + 1, Interval(1, 2), x)
116
+ raises(NotImplementedError, lambda: is_monotonic(x**2 + y + 1))
117
+
118
+
119
+ def test_issue_23401():
120
+ x = Symbol('x')
121
+ expr = (x + 1)/(-1.0e-3*x**2 + 0.1*x + 0.1)
122
+ assert is_increasing(expr, Interval(1,2), x)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/calculus/tests/test_util.py ADDED
@@ -0,0 +1,392 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.function import Lambda
2
+ from sympy.core.numbers import (E, I, Rational, oo, pi)
3
+ from sympy.core.relational import Eq
4
+ from sympy.core.singleton import S
5
+ from sympy.core.symbol import (Dummy, Symbol)
6
+ from sympy.functions.elementary.complexes import (Abs, re)
7
+ from sympy.functions.elementary.exponential import (exp, log)
8
+ from sympy.functions.elementary.integers import frac
9
+ from sympy.functions.elementary.miscellaneous import sqrt
10
+ from sympy.functions.elementary.piecewise import Piecewise
11
+ from sympy.functions.elementary.trigonometric import (
12
+ cos, cot, csc, sec, sin, tan, asin, acos, atan, acot, asec, acsc)
13
+ from sympy.functions.elementary.hyperbolic import (sinh, cosh, tanh, coth,
14
+ sech, csch, asinh, acosh, atanh, acoth, asech, acsch)
15
+ from sympy.functions.special.gamma_functions import gamma
16
+ from sympy.functions.special.error_functions import expint
17
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
18
+ from sympy.simplify.simplify import simplify
19
+ from sympy.calculus.util import (function_range, continuous_domain, not_empty_in,
20
+ periodicity, lcim, is_convex,
21
+ stationary_points, minimum, maximum)
22
+ from sympy.sets.sets import (Interval, FiniteSet, Complement, Union)
23
+ from sympy.sets.fancysets import ImageSet
24
+ from sympy.sets.conditionset import ConditionSet
25
+ from sympy.testing.pytest import XFAIL, raises, _both_exp_pow, slow
26
+ from sympy.abc import x, y
27
+
28
+ a = Symbol('a', real=True)
29
+
30
+ def test_function_range():
31
+ assert function_range(sin(x), x, Interval(-pi/2, pi/2)
32
+ ) == Interval(-1, 1)
33
+ assert function_range(sin(x), x, Interval(0, pi)
34
+ ) == Interval(0, 1)
35
+ assert function_range(tan(x), x, Interval(0, pi)
36
+ ) == Interval(-oo, oo)
37
+ assert function_range(tan(x), x, Interval(pi/2, pi)
38
+ ) == Interval(-oo, 0)
39
+ assert function_range((x + 3)/(x - 2), x, Interval(-5, 5)
40
+ ) == Union(Interval(-oo, Rational(2, 7)), Interval(Rational(8, 3), oo))
41
+ assert function_range(1/(x**2), x, Interval(-1, 1)
42
+ ) == Interval(1, oo)
43
+ assert function_range(exp(x), x, Interval(-1, 1)
44
+ ) == Interval(exp(-1), exp(1))
45
+ assert function_range(log(x) - x, x, S.Reals
46
+ ) == Interval(-oo, -1)
47
+ assert function_range(sqrt(3*x - 1), x, Interval(0, 2)
48
+ ) == Interval(0, sqrt(5))
49
+ assert function_range(x*(x - 1) - (x**2 - x), x, S.Reals
50
+ ) == FiniteSet(0)
51
+ assert function_range(x*(x - 1) - (x**2 - x) + y, x, S.Reals
52
+ ) == FiniteSet(y)
53
+ assert function_range(sin(x), x, Union(Interval(-5, -3), FiniteSet(4))
54
+ ) == Union(Interval(-sin(3), 1), FiniteSet(sin(4)))
55
+ assert function_range(cos(x), x, Interval(-oo, -4)
56
+ ) == Interval(-1, 1)
57
+ assert function_range(cos(x), x, S.EmptySet) == S.EmptySet
58
+ assert function_range(x/sqrt(x**2+1), x, S.Reals) == Interval.open(-1,1)
59
+ raises(NotImplementedError, lambda : function_range(
60
+ exp(x)*(sin(x) - cos(x))/2 - x, x, S.Reals))
61
+ raises(NotImplementedError, lambda : function_range(
62
+ sin(x) + x, x, S.Reals)) # issue 13273
63
+ raises(NotImplementedError, lambda : function_range(
64
+ log(x), x, S.Integers))
65
+ raises(NotImplementedError, lambda : function_range(
66
+ sin(x)/2, x, S.Naturals))
67
+
68
+
69
+ @slow
70
+ def test_function_range1():
71
+ assert function_range(tan(x)**2 + tan(3*x)**2 + 1, x, S.Reals) == Interval(1,oo)
72
+
73
+
74
+ def test_continuous_domain():
75
+ assert continuous_domain(sin(x), x, Interval(0, 2*pi)) == Interval(0, 2*pi)
76
+ assert continuous_domain(tan(x), x, Interval(0, 2*pi)) == \
77
+ Union(Interval(0, pi/2, False, True), Interval(pi/2, pi*Rational(3, 2), True, True),
78
+ Interval(pi*Rational(3, 2), 2*pi, True, False))
79
+ assert continuous_domain(cot(x), x, Interval(0, 2*pi)) == Union(
80
+ Interval.open(0, pi), Interval.open(pi, 2*pi))
81
+ assert continuous_domain((x - 1)/((x - 1)**2), x, S.Reals) == \
82
+ Union(Interval(-oo, 1, True, True), Interval(1, oo, True, True))
83
+ assert continuous_domain(log(x) + log(4*x - 1), x, S.Reals) == \
84
+ Interval(Rational(1, 4), oo, True, True)
85
+ assert continuous_domain(1/sqrt(x - 3), x, S.Reals) == Interval(3, oo, True, True)
86
+ assert continuous_domain(1/x - 2, x, S.Reals) == \
87
+ Union(Interval.open(-oo, 0), Interval.open(0, oo))
88
+ assert continuous_domain(1/(x**2 - 4) + 2, x, S.Reals) == \
89
+ Union(Interval.open(-oo, -2), Interval.open(-2, 2), Interval.open(2, oo))
90
+ assert continuous_domain((x+1)**pi, x, S.Reals) == Interval(-1, oo)
91
+ assert continuous_domain((x+1)**(pi/2), x, S.Reals) == Interval(-1, oo)
92
+ assert continuous_domain(x**x, x, S.Reals) == Interval(0, oo)
93
+ assert continuous_domain((x+1)**log(x**2), x, S.Reals) == Union(
94
+ Interval.Ropen(-1, 0), Interval.open(0, oo))
95
+ domain = continuous_domain(log(tan(x)**2 + 1), x, S.Reals)
96
+ assert not domain.contains(3*pi/2)
97
+ assert domain.contains(5)
98
+ d = Symbol('d', even=True, zero=False)
99
+ assert continuous_domain(x**(1/d), x, S.Reals) == Interval(0, oo)
100
+ n = Dummy('n')
101
+ assert continuous_domain(1/sin(x), x, S.Reals).dummy_eq(Complement(
102
+ S.Reals, Union(ImageSet(Lambda(n, 2*n*pi + pi), S.Integers),
103
+ ImageSet(Lambda(n, 2*n*pi), S.Integers))))
104
+ assert continuous_domain(sin(x) + cos(x), x, S.Reals) == S.Reals
105
+ assert continuous_domain(asin(x), x, S.Reals) == Interval(-1, 1) # issue #21786
106
+ assert continuous_domain(1/acos(log(x)), x, S.Reals) == Interval.Ropen(exp(-1), E)
107
+ assert continuous_domain(sinh(x)+cosh(x), x, S.Reals) == S.Reals
108
+ assert continuous_domain(tanh(x)+sech(x), x, S.Reals) == S.Reals
109
+ assert continuous_domain(atan(x)+asinh(x), x, S.Reals) == S.Reals
110
+ assert continuous_domain(acosh(x), x, S.Reals) == Interval(1, oo)
111
+ assert continuous_domain(atanh(x), x, S.Reals) == Interval.open(-1, 1)
112
+ assert continuous_domain(atanh(x)+acosh(x), x, S.Reals) == S.EmptySet
113
+ assert continuous_domain(asech(x), x, S.Reals) == Interval.Lopen(0, 1)
114
+ assert continuous_domain(acoth(x), x, S.Reals) == Union(
115
+ Interval.open(-oo, -1), Interval.open(1, oo))
116
+ assert continuous_domain(asec(x), x, S.Reals) == Union(
117
+ Interval(-oo, -1), Interval(1, oo))
118
+ assert continuous_domain(acsc(x), x, S.Reals) == Union(
119
+ Interval(-oo, -1), Interval(1, oo))
120
+ for f in (coth, acsch, csch):
121
+ assert continuous_domain(f(x), x, S.Reals) == Union(
122
+ Interval.open(-oo, 0), Interval.open(0, oo))
123
+ assert continuous_domain(acot(x), x, S.Reals).contains(0) == False
124
+ assert continuous_domain(1/(exp(x) - x), x, S.Reals) == Complement(
125
+ S.Reals, ConditionSet(x, Eq(-x + exp(x), 0), S.Reals))
126
+ assert continuous_domain(frac(x**2), x, Interval(-2,-1)) == Union(
127
+ Interval.open(-2, -sqrt(3)), Interval.open(-sqrt(2), -1),
128
+ Interval.open(-sqrt(3), -sqrt(2)))
129
+ assert continuous_domain(frac(x), x, S.Reals) == Complement(
130
+ S.Reals, S.Integers)
131
+ raises(NotImplementedError, lambda : continuous_domain(
132
+ 1/(x**2+1), x, S.Complexes))
133
+ raises(NotImplementedError, lambda : continuous_domain(
134
+ gamma(x), x, Interval(-5,0)))
135
+ assert continuous_domain(x + gamma(pi), x, S.Reals) == S.Reals
136
+
137
+
138
+ @XFAIL
139
+ def test_continuous_domain_acot():
140
+ acot_cont = Piecewise((pi+acot(x), x<0), (acot(x), True))
141
+ assert continuous_domain(acot_cont, x, S.Reals) == S.Reals
142
+
143
+ @XFAIL
144
+ def test_continuous_domain_gamma():
145
+ assert continuous_domain(gamma(x), x, S.Reals).contains(-1) == False
146
+
147
+ @XFAIL
148
+ def test_continuous_domain_neg_power():
149
+ assert continuous_domain((x-2)**(1-x), x, S.Reals) == Interval.open(2, oo)
150
+
151
+
152
+ def test_not_empty_in():
153
+ assert not_empty_in(FiniteSet(x, 2*x).intersect(Interval(1, 2, True, False)), x) == \
154
+ Interval(S.Half, 2, True, False)
155
+ assert not_empty_in(FiniteSet(x, x**2).intersect(Interval(1, 2)), x) == \
156
+ Union(Interval(-sqrt(2), -1), Interval(1, 2))
157
+ assert not_empty_in(FiniteSet(x**2 + x, x).intersect(Interval(2, 4)), x) == \
158
+ Union(Interval(-sqrt(17)/2 - S.Half, -2),
159
+ Interval(1, Rational(-1, 2) + sqrt(17)/2), Interval(2, 4))
160
+ assert not_empty_in(FiniteSet(x/(x - 1)).intersect(S.Reals), x) == \
161
+ Complement(S.Reals, FiniteSet(1))
162
+ assert not_empty_in(FiniteSet(a/(a - 1)).intersect(S.Reals), a) == \
163
+ Complement(S.Reals, FiniteSet(1))
164
+ assert not_empty_in(FiniteSet((x**2 - 3*x + 2)/(x - 1)).intersect(S.Reals), x) == \
165
+ Complement(S.Reals, FiniteSet(1))
166
+ assert not_empty_in(FiniteSet(3, 4, x/(x - 1)).intersect(Interval(2, 3)), x) == \
167
+ Interval(-oo, oo)
168
+ assert not_empty_in(FiniteSet(4, x/(x - 1)).intersect(Interval(2, 3)), x) == \
169
+ Interval(S(3)/2, 2)
170
+ assert not_empty_in(FiniteSet(x/(x**2 - 1)).intersect(S.Reals), x) == \
171
+ Complement(S.Reals, FiniteSet(-1, 1))
172
+ assert not_empty_in(FiniteSet(x, x**2).intersect(Union(Interval(1, 3, True, True),
173
+ Interval(4, 5))), x) == \
174
+ Union(Interval(-sqrt(5), -2), Interval(-sqrt(3), -1, True, True),
175
+ Interval(1, 3, True, True), Interval(4, 5))
176
+ assert not_empty_in(FiniteSet(1).intersect(Interval(3, 4)), x) == S.EmptySet
177
+ assert not_empty_in(FiniteSet(x**2/(x + 2)).intersect(Interval(1, oo)), x) == \
178
+ Union(Interval(-2, -1, True, False), Interval(2, oo))
179
+ raises(ValueError, lambda: not_empty_in(x))
180
+ raises(ValueError, lambda: not_empty_in(Interval(0, 1), x))
181
+ raises(NotImplementedError,
182
+ lambda: not_empty_in(FiniteSet(x).intersect(S.Reals), x, a))
183
+
184
+
185
+ @_both_exp_pow
186
+ def test_periodicity():
187
+ assert periodicity(sin(2*x), x) == pi
188
+ assert periodicity((-2)*tan(4*x), x) == pi/4
189
+ assert periodicity(sin(x)**2, x) == 2*pi
190
+ assert periodicity(3**tan(3*x), x) == pi/3
191
+ assert periodicity(tan(x)*cos(x), x) == 2*pi
192
+ assert periodicity(sin(x)**(tan(x)), x) == 2*pi
193
+ assert periodicity(tan(x)*sec(x), x) == 2*pi
194
+ assert periodicity(sin(2*x)*cos(2*x) - y, x) == pi/2
195
+ assert periodicity(tan(x) + cot(x), x) == pi
196
+ assert periodicity(sin(x) - cos(2*x), x) == 2*pi
197
+ assert periodicity(sin(x) - 1, x) == 2*pi
198
+ assert periodicity(sin(4*x) + sin(x)*cos(x), x) == pi
199
+ assert periodicity(exp(sin(x)), x) == 2*pi
200
+ assert periodicity(log(cot(2*x)) - sin(cos(2*x)), x) == pi
201
+ assert periodicity(sin(2*x)*exp(tan(x) - csc(2*x)), x) == pi
202
+ assert periodicity(cos(sec(x) - csc(2*x)), x) == 2*pi
203
+ assert periodicity(tan(sin(2*x)), x) == pi
204
+ assert periodicity(2*tan(x)**2, x) == pi
205
+ assert periodicity(sin(x%4), x) == 4
206
+ assert periodicity(sin(x)%4, x) == 2*pi
207
+ assert periodicity(tan((3*x-2)%4), x) == Rational(4, 3)
208
+ assert periodicity((sqrt(2)*(x+1)+x) % 3, x) == 3 / (sqrt(2)+1)
209
+ assert periodicity((x**2+1) % x, x) is None
210
+ assert periodicity(sin(re(x)), x) == 2*pi
211
+ assert periodicity(sin(x)**2 + cos(x)**2, x) is S.Zero
212
+ assert periodicity(tan(x), y) is S.Zero
213
+ assert periodicity(sin(x) + I*cos(x), x) == 2*pi
214
+ assert periodicity(x - sin(2*y), y) == pi
215
+
216
+ assert periodicity(exp(x), x) is None
217
+ assert periodicity(exp(I*x), x) == 2*pi
218
+ assert periodicity(exp(I*a), a) == 2*pi
219
+ assert periodicity(exp(a), a) is None
220
+ assert periodicity(exp(log(sin(a) + I*cos(2*a)), evaluate=False), a) == 2*pi
221
+ assert periodicity(exp(log(sin(2*a) + I*cos(a)), evaluate=False), a) == 2*pi
222
+ assert periodicity(exp(sin(a)), a) == 2*pi
223
+ assert periodicity(exp(2*I*a), a) == pi
224
+ assert periodicity(exp(a + I*sin(a)), a) is None
225
+ assert periodicity(exp(cos(a/2) + sin(a)), a) == 4*pi
226
+ assert periodicity(log(x), x) is None
227
+ assert periodicity(exp(x)**sin(x), x) is None
228
+ assert periodicity(sin(x)**y, y) is None
229
+
230
+ assert periodicity(Abs(sin(Abs(sin(x)))), x) == pi
231
+ assert all(periodicity(Abs(f(x)), x) == pi for f in (
232
+ cos, sin, sec, csc, tan, cot))
233
+ assert periodicity(Abs(sin(tan(x))), x) == pi
234
+ assert periodicity(Abs(sin(sin(x) + tan(x))), x) == 2*pi
235
+ assert periodicity(sin(x) > S.Half, x) == 2*pi
236
+
237
+ assert periodicity(x > 2, x) is None
238
+ assert periodicity(x**3 - x**2 + 1, x) is None
239
+ assert periodicity(Abs(x), x) is None
240
+ assert periodicity(Abs(x**2 - 1), x) is None
241
+
242
+ assert periodicity((x**2 + 4)%2, x) is None
243
+ assert periodicity((E**x)%3, x) is None
244
+
245
+ assert periodicity(sin(expint(1, x))/expint(1, x), x) is None
246
+ # returning `None` for any Piecewise
247
+ p = Piecewise((0, x < -1), (x**2, x <= 1), (log(x), True))
248
+ assert periodicity(p, x) is None
249
+
250
+ m = MatrixSymbol('m', 3, 3)
251
+ raises(NotImplementedError, lambda: periodicity(sin(m), m))
252
+ raises(NotImplementedError, lambda: periodicity(sin(m[0, 0]), m))
253
+ raises(NotImplementedError, lambda: periodicity(sin(m), m[0, 0]))
254
+ raises(NotImplementedError, lambda: periodicity(sin(m[0, 0]), m[0, 0]))
255
+
256
+
257
+ def test_periodicity_check():
258
+ assert periodicity(tan(x), x, check=True) == pi
259
+ assert periodicity(sin(x) + cos(x), x, check=True) == 2*pi
260
+ assert periodicity(sec(x), x) == 2*pi
261
+ assert periodicity(sin(x*y), x) == 2*pi/abs(y)
262
+ assert periodicity(Abs(sec(sec(x))), x) == pi
263
+
264
+
265
+ def test_lcim():
266
+ assert lcim([S.Half, S(2), S(3)]) == 6
267
+ assert lcim([pi/2, pi/4, pi]) == pi
268
+ assert lcim([2*pi, pi/2]) == 2*pi
269
+ assert lcim([S.One, 2*pi]) is None
270
+ assert lcim([S(2) + 2*E, E/3 + Rational(1, 3), S.One + E]) == S(2) + 2*E
271
+
272
+
273
+ def test_is_convex():
274
+ assert is_convex(1/x, x, domain=Interval.open(0, oo)) == True
275
+ assert is_convex(1/x, x, domain=Interval(-oo, 0)) == False
276
+ assert is_convex(x**2, x, domain=Interval(0, oo)) == True
277
+ assert is_convex(1/x**3, x, domain=Interval.Lopen(0, oo)) == True
278
+ assert is_convex(-1/x**3, x, domain=Interval.Ropen(-oo, 0)) == True
279
+ assert is_convex(log(x) ,x) == False
280
+ assert is_convex(x**2+y**2, x, y) == True
281
+ assert is_convex(cos(x) + cos(y), x) == False
282
+ assert is_convex(8*x**2 - 2*y**2, x, y) == False
283
+
284
+
285
+ def test_stationary_points():
286
+ assert stationary_points(sin(x), x, Interval(-pi/2, pi/2)
287
+ ) == {-pi/2, pi/2}
288
+ assert stationary_points(sin(x), x, Interval.Ropen(0, pi/4)
289
+ ) is S.EmptySet
290
+ assert stationary_points(tan(x), x,
291
+ ) is S.EmptySet
292
+ assert stationary_points(sin(x)*cos(x), x, Interval(0, pi)
293
+ ) == {pi/4, pi*Rational(3, 4)}
294
+ assert stationary_points(sec(x), x, Interval(0, pi)
295
+ ) == {0, pi}
296
+ assert stationary_points((x+3)*(x-2), x
297
+ ) == FiniteSet(Rational(-1, 2))
298
+ assert stationary_points((x + 3)/(x - 2), x, Interval(-5, 5)
299
+ ) is S.EmptySet
300
+ assert stationary_points((x**2+3)/(x-2), x
301
+ ) == {2 - sqrt(7), 2 + sqrt(7)}
302
+ assert stationary_points((x**2+3)/(x-2), x, Interval(0, 5)
303
+ ) == {2 + sqrt(7)}
304
+ assert stationary_points(x**4 + x**3 - 5*x**2, x, S.Reals
305
+ ) == FiniteSet(-2, 0, Rational(5, 4))
306
+ assert stationary_points(exp(x), x
307
+ ) is S.EmptySet
308
+ assert stationary_points(log(x) - x, x, S.Reals
309
+ ) == {1}
310
+ assert stationary_points(cos(x), x, Union(Interval(0, 5), Interval(-6, -3))
311
+ ) == {0, -pi, pi}
312
+ assert stationary_points(y, x, S.Reals
313
+ ) == S.Reals
314
+ assert stationary_points(y, x, S.EmptySet) == S.EmptySet
315
+
316
+
317
+ def test_maximum():
318
+ assert maximum(sin(x), x) is S.One
319
+ assert maximum(sin(x), x, Interval(0, 1)) == sin(1)
320
+ assert maximum(tan(x), x) is oo
321
+ assert maximum(tan(x), x, Interval(-pi/4, pi/4)) is S.One
322
+ assert maximum(sin(x)*cos(x), x, S.Reals) == S.Half
323
+ assert simplify(maximum(sin(x)*cos(x), x, Interval(pi*Rational(3, 8), pi*Rational(5, 8)))
324
+ ) == sqrt(2)/4
325
+ assert maximum((x+3)*(x-2), x) is oo
326
+ assert maximum((x+3)*(x-2), x, Interval(-5, 0)) == S(14)
327
+ assert maximum((x+3)/(x-2), x, Interval(-5, 0)) == Rational(2, 7)
328
+ assert simplify(maximum(-x**4-x**3+x**2+10, x)
329
+ ) == 41*sqrt(41)/512 + Rational(5419, 512)
330
+ assert maximum(exp(x), x, Interval(-oo, 2)) == exp(2)
331
+ assert maximum(log(x) - x, x, S.Reals) is S.NegativeOne
332
+ assert maximum(cos(x), x, Union(Interval(0, 5), Interval(-6, -3))
333
+ ) is S.One
334
+ assert maximum(cos(x)-sin(x), x, S.Reals) == sqrt(2)
335
+ assert maximum(y, x, S.Reals) == y
336
+ assert maximum(abs(a**3 + a), a, Interval(0, 2)) == 10
337
+ assert maximum(abs(60*a**3 + 24*a), a, Interval(0, 2)) == 528
338
+ assert maximum(abs(12*a*(5*a**2 + 2)), a, Interval(0, 2)) == 528
339
+ assert maximum(x/sqrt(x**2+1), x, S.Reals) == 1
340
+
341
+ raises(ValueError, lambda : maximum(sin(x), x, S.EmptySet))
342
+ raises(ValueError, lambda : maximum(log(cos(x)), x, S.EmptySet))
343
+ raises(ValueError, lambda : maximum(1/(x**2 + y**2 + 1), x, S.EmptySet))
344
+ raises(ValueError, lambda : maximum(sin(x), sin(x)))
345
+ raises(ValueError, lambda : maximum(sin(x), x*y, S.EmptySet))
346
+ raises(ValueError, lambda : maximum(sin(x), S.One))
347
+
348
+
349
+ def test_minimum():
350
+ assert minimum(sin(x), x) is S.NegativeOne
351
+ assert minimum(sin(x), x, Interval(1, 4)) == sin(4)
352
+ assert minimum(tan(x), x) is -oo
353
+ assert minimum(tan(x), x, Interval(-pi/4, pi/4)) is S.NegativeOne
354
+ assert minimum(sin(x)*cos(x), x, S.Reals) == Rational(-1, 2)
355
+ assert simplify(minimum(sin(x)*cos(x), x, Interval(pi*Rational(3, 8), pi*Rational(5, 8)))
356
+ ) == -sqrt(2)/4
357
+ assert minimum((x+3)*(x-2), x) == Rational(-25, 4)
358
+ assert minimum((x+3)/(x-2), x, Interval(-5, 0)) == Rational(-3, 2)
359
+ assert minimum(x**4-x**3+x**2+10, x) == S(10)
360
+ assert minimum(exp(x), x, Interval(-2, oo)) == exp(-2)
361
+ assert minimum(log(x) - x, x, S.Reals) is -oo
362
+ assert minimum(cos(x), x, Union(Interval(0, 5), Interval(-6, -3))
363
+ ) is S.NegativeOne
364
+ assert minimum(cos(x)-sin(x), x, S.Reals) == -sqrt(2)
365
+ assert minimum(y, x, S.Reals) == y
366
+ assert minimum(x/sqrt(x**2+1), x, S.Reals) == -1
367
+
368
+ raises(ValueError, lambda : minimum(sin(x), x, S.EmptySet))
369
+ raises(ValueError, lambda : minimum(log(cos(x)), x, S.EmptySet))
370
+ raises(ValueError, lambda : minimum(1/(x**2 + y**2 + 1), x, S.EmptySet))
371
+ raises(ValueError, lambda : minimum(sin(x), sin(x)))
372
+ raises(ValueError, lambda : minimum(sin(x), x*y, S.EmptySet))
373
+ raises(ValueError, lambda : minimum(sin(x), S.One))
374
+
375
+
376
+ def test_issue_19869():
377
+ assert (maximum(sqrt(3)*(x - 1)/(3*sqrt(x**2 + 1)), x)
378
+ ) == sqrt(3)/3
379
+
380
+
381
+ def test_issue_16469():
382
+ f = abs(a)
383
+ assert function_range(f, a, S.Reals) == Interval(0, oo, False, True)
384
+
385
+
386
+ @_both_exp_pow
387
+ def test_issue_18747():
388
+ assert periodicity(exp(pi*I*(x/4 + S.Half/2)), x) == 8
389
+
390
+
391
+ def test_issue_25942():
392
+ assert (acos(x) > pi/3).as_set() == Interval.Ropen(-1, S(1)/2)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/calculus/util.py ADDED
@@ -0,0 +1,895 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .accumulationbounds import AccumBounds, AccumulationBounds # noqa: F401
2
+ from .singularities import singularities
3
+ from sympy.core import Pow, S
4
+ from sympy.core.function import diff, expand_mul, Function
5
+ from sympy.core.kind import NumberKind
6
+ from sympy.core.mod import Mod
7
+ from sympy.core.numbers import equal_valued
8
+ from sympy.core.relational import Relational
9
+ from sympy.core.symbol import Symbol, Dummy
10
+ from sympy.core.sympify import _sympify
11
+ from sympy.functions.elementary.complexes import Abs, im, re
12
+ from sympy.functions.elementary.exponential import exp, log
13
+ from sympy.functions.elementary.integers import frac
14
+ from sympy.functions.elementary.piecewise import Piecewise
15
+ from sympy.functions.elementary.trigonometric import (
16
+ TrigonometricFunction, sin, cos, tan, cot, csc, sec,
17
+ asin, acos, acot, atan, asec, acsc)
18
+ from sympy.functions.elementary.hyperbolic import (sinh, cosh, tanh, coth,
19
+ sech, csch, asinh, acosh, atanh, acoth, asech, acsch)
20
+ from sympy.polys.polytools import degree, lcm_list
21
+ from sympy.sets.sets import (Interval, Intersection, FiniteSet, Union,
22
+ Complement)
23
+ from sympy.sets.fancysets import ImageSet
24
+ from sympy.sets.conditionset import ConditionSet
25
+ from sympy.utilities import filldedent
26
+ from sympy.utilities.iterables import iterable
27
+ from sympy.matrices.dense import hessian
28
+
29
+
30
+ def continuous_domain(f, symbol, domain):
31
+ """
32
+ Returns the domain on which the function expression f is continuous.
33
+
34
+ This function is limited by the ability to determine the various
35
+ singularities and discontinuities of the given function.
36
+ The result is either given as a union of intervals or constructed using
37
+ other set operations.
38
+
39
+ Parameters
40
+ ==========
41
+
42
+ f : :py:class:`~.Expr`
43
+ The concerned function.
44
+ symbol : :py:class:`~.Symbol`
45
+ The variable for which the intervals are to be determined.
46
+ domain : :py:class:`~.Interval`
47
+ The domain over which the continuity of the symbol has to be checked.
48
+
49
+ Examples
50
+ ========
51
+
52
+ >>> from sympy import Interval, Symbol, S, tan, log, pi, sqrt
53
+ >>> from sympy.calculus.util import continuous_domain
54
+ >>> x = Symbol('x')
55
+ >>> continuous_domain(1/x, x, S.Reals)
56
+ Union(Interval.open(-oo, 0), Interval.open(0, oo))
57
+ >>> continuous_domain(tan(x), x, Interval(0, pi))
58
+ Union(Interval.Ropen(0, pi/2), Interval.Lopen(pi/2, pi))
59
+ >>> continuous_domain(sqrt(x - 2), x, Interval(-5, 5))
60
+ Interval(2, 5)
61
+ >>> continuous_domain(log(2*x - 1), x, S.Reals)
62
+ Interval.open(1/2, oo)
63
+
64
+ Returns
65
+ =======
66
+
67
+ :py:class:`~.Interval`
68
+ Union of all intervals where the function is continuous.
69
+
70
+ Raises
71
+ ======
72
+
73
+ NotImplementedError
74
+ If the method to determine continuity of such a function
75
+ has not yet been developed.
76
+
77
+ """
78
+ from sympy.solvers.inequalities import solve_univariate_inequality
79
+
80
+ if not domain.is_subset(S.Reals):
81
+ raise NotImplementedError(filldedent('''
82
+ Domain must be a subset of S.Reals.
83
+ '''))
84
+ implemented = [Pow, exp, log, Abs, frac,
85
+ sin, cos, tan, cot, sec, csc,
86
+ asin, acos, atan, acot, asec, acsc,
87
+ sinh, cosh, tanh, coth, sech, csch,
88
+ asinh, acosh, atanh, acoth, asech, acsch]
89
+ used = [fct.func for fct in f.atoms(Function) if fct.has(symbol)]
90
+ if any(func not in implemented for func in used):
91
+ raise NotImplementedError(filldedent('''
92
+ Unable to determine the domain of the given function.
93
+ '''))
94
+
95
+ x = Symbol('x')
96
+ constraints = {
97
+ log: (x > 0,),
98
+ asin: (x >= -1, x <= 1),
99
+ acos: (x >= -1, x <= 1),
100
+ acosh: (x >= 1,),
101
+ atanh: (x > -1, x < 1),
102
+ asech: (x > 0, x <= 1)
103
+ }
104
+ constraints_union = {
105
+ asec: (x <= -1, x >= 1),
106
+ acsc: (x <= -1, x >= 1),
107
+ acoth: (x < -1, x > 1)
108
+ }
109
+
110
+ cont_domain = domain
111
+ for atom in f.atoms(Pow):
112
+ den = atom.exp.as_numer_denom()[1]
113
+ if atom.exp.is_rational and den.is_odd:
114
+ pass # 0**negative handled by singularities()
115
+ else:
116
+ constraint = solve_univariate_inequality(atom.base >= 0,
117
+ symbol).as_set()
118
+ cont_domain = Intersection(constraint, cont_domain)
119
+
120
+ for atom in f.atoms(Function):
121
+ if atom.func in constraints:
122
+ for c in constraints[atom.func]:
123
+ constraint_relational = c.subs(x, atom.args[0])
124
+ constraint_set = solve_univariate_inequality(
125
+ constraint_relational, symbol).as_set()
126
+ cont_domain = Intersection(constraint_set, cont_domain)
127
+ elif atom.func in constraints_union:
128
+ constraint_set = S.EmptySet
129
+ for c in constraints_union[atom.func]:
130
+ constraint_relational = c.subs(x, atom.args[0])
131
+ constraint_set += solve_univariate_inequality(
132
+ constraint_relational, symbol).as_set()
133
+ cont_domain = Intersection(constraint_set, cont_domain)
134
+ # XXX: the discontinuities below could be factored out in
135
+ # a new "discontinuities()".
136
+ elif atom.func == acot:
137
+ from sympy.solvers.solveset import solveset_real
138
+ # Sympy's acot() has a step discontinuity at 0. Since it's
139
+ # neither an essential singularity nor a pole, singularities()
140
+ # will not report it. But it's still relevant for determining
141
+ # the continuity of the function f.
142
+ cont_domain -= solveset_real(atom.args[0], symbol)
143
+ # Note that the above may introduce spurious discontinuities, e.g.
144
+ # for abs(acot(x)) at 0.
145
+ elif atom.func == frac:
146
+ from sympy.solvers.solveset import solveset_real
147
+ r = function_range(atom.args[0], symbol, domain)
148
+ r = Intersection(r, S.Integers)
149
+ if r.is_finite_set:
150
+ discont = S.EmptySet
151
+ for n in r:
152
+ discont += solveset_real(atom.args[0]-n, symbol)
153
+ else:
154
+ discont = ConditionSet(
155
+ symbol, S.Integers.contains(atom.args[0]), cont_domain)
156
+ cont_domain -= discont
157
+
158
+ return cont_domain - singularities(f, symbol, domain)
159
+
160
+
161
+ def function_range(f, symbol, domain):
162
+ """
163
+ Finds the range of a function in a given domain.
164
+ This method is limited by the ability to determine the singularities and
165
+ determine limits.
166
+
167
+ Parameters
168
+ ==========
169
+
170
+ f : :py:class:`~.Expr`
171
+ The concerned function.
172
+ symbol : :py:class:`~.Symbol`
173
+ The variable for which the range of function is to be determined.
174
+ domain : :py:class:`~.Interval`
175
+ The domain under which the range of the function has to be found.
176
+
177
+ Examples
178
+ ========
179
+
180
+ >>> from sympy import Interval, Symbol, S, exp, log, pi, sqrt, sin, tan
181
+ >>> from sympy.calculus.util import function_range
182
+ >>> x = Symbol('x')
183
+ >>> function_range(sin(x), x, Interval(0, 2*pi))
184
+ Interval(-1, 1)
185
+ >>> function_range(tan(x), x, Interval(-pi/2, pi/2))
186
+ Interval(-oo, oo)
187
+ >>> function_range(1/x, x, S.Reals)
188
+ Union(Interval.open(-oo, 0), Interval.open(0, oo))
189
+ >>> function_range(exp(x), x, S.Reals)
190
+ Interval.open(0, oo)
191
+ >>> function_range(log(x), x, S.Reals)
192
+ Interval(-oo, oo)
193
+ >>> function_range(sqrt(x), x, Interval(-5, 9))
194
+ Interval(0, 3)
195
+
196
+ Returns
197
+ =======
198
+
199
+ :py:class:`~.Interval`
200
+ Union of all ranges for all intervals under domain where function is
201
+ continuous.
202
+
203
+ Raises
204
+ ======
205
+
206
+ NotImplementedError
207
+ If any of the intervals, in the given domain, for which function
208
+ is continuous are not finite or real,
209
+ OR if the critical points of the function on the domain cannot be found.
210
+ """
211
+
212
+ if domain is S.EmptySet:
213
+ return S.EmptySet
214
+
215
+ period = periodicity(f, symbol)
216
+ if period == S.Zero:
217
+ # the expression is constant wrt symbol
218
+ return FiniteSet(f.expand())
219
+
220
+ from sympy.series.limits import limit
221
+ from sympy.solvers.solveset import solveset
222
+
223
+ if period is not None:
224
+ if isinstance(domain, Interval):
225
+ if (domain.inf - domain.sup).is_infinite:
226
+ domain = Interval(0, period)
227
+ elif isinstance(domain, Union):
228
+ for sub_dom in domain.args:
229
+ if isinstance(sub_dom, Interval) and \
230
+ ((sub_dom.inf - sub_dom.sup).is_infinite):
231
+ domain = Interval(0, period)
232
+
233
+ intervals = continuous_domain(f, symbol, domain)
234
+ range_int = S.EmptySet
235
+ if isinstance(intervals,(Interval, FiniteSet)):
236
+ interval_iter = (intervals,)
237
+ elif isinstance(intervals, Union):
238
+ interval_iter = intervals.args
239
+ else:
240
+ raise NotImplementedError("Unable to find range for the given domain.")
241
+
242
+ for interval in interval_iter:
243
+ if isinstance(interval, FiniteSet):
244
+ for singleton in interval:
245
+ if singleton in domain:
246
+ range_int += FiniteSet(f.subs(symbol, singleton))
247
+ elif isinstance(interval, Interval):
248
+ vals = S.EmptySet
249
+ critical_values = S.EmptySet
250
+ bounds = ((interval.left_open, interval.inf, '+'),
251
+ (interval.right_open, interval.sup, '-'))
252
+
253
+ for is_open, limit_point, direction in bounds:
254
+ if is_open:
255
+ critical_values += FiniteSet(limit(f, symbol, limit_point, direction))
256
+ vals += critical_values
257
+ else:
258
+ vals += FiniteSet(f.subs(symbol, limit_point))
259
+
260
+ critical_points = solveset(f.diff(symbol), symbol, interval)
261
+
262
+ if not iterable(critical_points):
263
+ raise NotImplementedError(
264
+ 'Unable to find critical points for {}'.format(f))
265
+ if isinstance(critical_points, ImageSet):
266
+ raise NotImplementedError(
267
+ 'Infinite number of critical points for {}'.format(f))
268
+
269
+ for critical_point in critical_points:
270
+ vals += FiniteSet(f.subs(symbol, critical_point))
271
+
272
+ left_open, right_open = False, False
273
+
274
+ if critical_values is not S.EmptySet:
275
+ if critical_values.inf == vals.inf:
276
+ left_open = True
277
+
278
+ if critical_values.sup == vals.sup:
279
+ right_open = True
280
+
281
+ range_int += Interval(vals.inf, vals.sup, left_open, right_open)
282
+ else:
283
+ raise NotImplementedError("Unable to find range for the given domain.")
284
+
285
+ return range_int
286
+
287
+
288
+ def not_empty_in(finset_intersection, *syms):
289
+ """
290
+ Finds the domain of the functions in ``finset_intersection`` in which the
291
+ ``finite_set`` is not-empty.
292
+
293
+ Parameters
294
+ ==========
295
+
296
+ finset_intersection : Intersection of FiniteSet
297
+ The unevaluated intersection of FiniteSet containing
298
+ real-valued functions with Union of Sets
299
+ syms : Tuple of symbols
300
+ Symbol for which domain is to be found
301
+
302
+ Raises
303
+ ======
304
+
305
+ NotImplementedError
306
+ The algorithms to find the non-emptiness of the given FiniteSet are
307
+ not yet implemented.
308
+ ValueError
309
+ The input is not valid.
310
+ RuntimeError
311
+ It is a bug, please report it to the github issue tracker
312
+ (https://github.com/sympy/sympy/issues).
313
+
314
+ Examples
315
+ ========
316
+
317
+ >>> from sympy import FiniteSet, Interval, not_empty_in, oo
318
+ >>> from sympy.abc import x
319
+ >>> not_empty_in(FiniteSet(x/2).intersect(Interval(0, 1)), x)
320
+ Interval(0, 2)
321
+ >>> not_empty_in(FiniteSet(x, x**2).intersect(Interval(1, 2)), x)
322
+ Union(Interval(1, 2), Interval(-sqrt(2), -1))
323
+ >>> not_empty_in(FiniteSet(x**2/(x + 2)).intersect(Interval(1, oo)), x)
324
+ Union(Interval.Lopen(-2, -1), Interval(2, oo))
325
+ """
326
+
327
+ # TODO: handle piecewise defined functions
328
+ # TODO: handle transcendental functions
329
+ # TODO: handle multivariate functions
330
+ if len(syms) == 0:
331
+ raise ValueError("One or more symbols must be given in syms.")
332
+
333
+ if finset_intersection is S.EmptySet:
334
+ return S.EmptySet
335
+
336
+ if isinstance(finset_intersection, Union):
337
+ elm_in_sets = finset_intersection.args[0]
338
+ return Union(not_empty_in(finset_intersection.args[1], *syms),
339
+ elm_in_sets)
340
+
341
+ if isinstance(finset_intersection, FiniteSet):
342
+ finite_set = finset_intersection
343
+ _sets = S.Reals
344
+ else:
345
+ finite_set = finset_intersection.args[1]
346
+ _sets = finset_intersection.args[0]
347
+
348
+ if not isinstance(finite_set, FiniteSet):
349
+ raise ValueError('A FiniteSet must be given, not %s: %s' %
350
+ (type(finite_set), finite_set))
351
+
352
+ if len(syms) == 1:
353
+ symb = syms[0]
354
+ else:
355
+ raise NotImplementedError('more than one variables %s not handled' %
356
+ (syms,))
357
+
358
+ def elm_domain(expr, intrvl):
359
+ """ Finds the domain of an expression in any given interval """
360
+ from sympy.solvers.solveset import solveset
361
+
362
+ _start = intrvl.start
363
+ _end = intrvl.end
364
+ _singularities = solveset(expr.as_numer_denom()[1], symb,
365
+ domain=S.Reals)
366
+
367
+ if intrvl.right_open:
368
+ if _end is S.Infinity:
369
+ _domain1 = S.Reals
370
+ else:
371
+ _domain1 = solveset(expr < _end, symb, domain=S.Reals)
372
+ else:
373
+ _domain1 = solveset(expr <= _end, symb, domain=S.Reals)
374
+
375
+ if intrvl.left_open:
376
+ if _start is S.NegativeInfinity:
377
+ _domain2 = S.Reals
378
+ else:
379
+ _domain2 = solveset(expr > _start, symb, domain=S.Reals)
380
+ else:
381
+ _domain2 = solveset(expr >= _start, symb, domain=S.Reals)
382
+
383
+ # domain in the interval
384
+ expr_with_sing = Intersection(_domain1, _domain2)
385
+ expr_domain = Complement(expr_with_sing, _singularities)
386
+ return expr_domain
387
+
388
+ if isinstance(_sets, Interval):
389
+ return Union(*[elm_domain(element, _sets) for element in finite_set])
390
+
391
+ if isinstance(_sets, Union):
392
+ _domain = S.EmptySet
393
+ for intrvl in _sets.args:
394
+ _domain_element = Union(*[elm_domain(element, intrvl)
395
+ for element in finite_set])
396
+ _domain = Union(_domain, _domain_element)
397
+ return _domain
398
+
399
+
400
+ def periodicity(f, symbol, check=False):
401
+ """
402
+ Tests the given function for periodicity in the given symbol.
403
+
404
+ Parameters
405
+ ==========
406
+
407
+ f : :py:class:`~.Expr`
408
+ The concerned function.
409
+ symbol : :py:class:`~.Symbol`
410
+ The variable for which the period is to be determined.
411
+ check : bool, optional
412
+ The flag to verify whether the value being returned is a period or not.
413
+
414
+ Returns
415
+ =======
416
+
417
+ period
418
+ The period of the function is returned.
419
+ ``None`` is returned when the function is aperiodic or has a complex period.
420
+ The value of $0$ is returned as the period of a constant function.
421
+
422
+ Raises
423
+ ======
424
+
425
+ NotImplementedError
426
+ The value of the period computed cannot be verified.
427
+
428
+
429
+ Notes
430
+ =====
431
+
432
+ Currently, we do not support functions with a complex period.
433
+ The period of functions having complex periodic values such
434
+ as ``exp``, ``sinh`` is evaluated to ``None``.
435
+
436
+ The value returned might not be the "fundamental" period of the given
437
+ function i.e. it may not be the smallest periodic value of the function.
438
+
439
+ The verification of the period through the ``check`` flag is not reliable
440
+ due to internal simplification of the given expression. Hence, it is set
441
+ to ``False`` by default.
442
+
443
+ Examples
444
+ ========
445
+ >>> from sympy import periodicity, Symbol, sin, cos, tan, exp
446
+ >>> x = Symbol('x')
447
+ >>> f = sin(x) + sin(2*x) + sin(3*x)
448
+ >>> periodicity(f, x)
449
+ 2*pi
450
+ >>> periodicity(sin(x)*cos(x), x)
451
+ pi
452
+ >>> periodicity(exp(tan(2*x) - 1), x)
453
+ pi/2
454
+ >>> periodicity(sin(4*x)**cos(2*x), x)
455
+ pi
456
+ >>> periodicity(exp(x), x)
457
+ """
458
+ if symbol.kind is not NumberKind:
459
+ raise NotImplementedError("Cannot use symbol of kind %s" % symbol.kind)
460
+ temp = Dummy('x', real=True)
461
+ f = f.subs(symbol, temp)
462
+ symbol = temp
463
+
464
+ def _check(orig_f, period):
465
+ '''Return the checked period or raise an error.'''
466
+ new_f = orig_f.subs(symbol, symbol + period)
467
+ if new_f.equals(orig_f):
468
+ return period
469
+ else:
470
+ raise NotImplementedError(filldedent('''
471
+ The period of the given function cannot be verified.
472
+ When `%s` was replaced with `%s + %s` in `%s`, the result
473
+ was `%s` which was not recognized as being the same as
474
+ the original function.
475
+ So either the period was wrong or the two forms were
476
+ not recognized as being equal.
477
+ Set check=False to obtain the value.''' %
478
+ (symbol, symbol, period, orig_f, new_f)))
479
+
480
+ orig_f = f
481
+ period = None
482
+
483
+ if isinstance(f, Relational):
484
+ f = f.lhs - f.rhs
485
+
486
+ f = f.simplify()
487
+
488
+ if symbol not in f.free_symbols:
489
+ return S.Zero
490
+
491
+ if isinstance(f, TrigonometricFunction):
492
+ try:
493
+ period = f.period(symbol)
494
+ except NotImplementedError:
495
+ pass
496
+
497
+ if isinstance(f, Abs):
498
+ arg = f.args[0]
499
+ if isinstance(arg, (sec, csc, cos)):
500
+ # all but tan and cot might have a
501
+ # a period that is half as large
502
+ # so recast as sin
503
+ arg = sin(arg.args[0])
504
+ period = periodicity(arg, symbol)
505
+ if period is not None and isinstance(arg, sin):
506
+ # the argument of Abs was a trigonometric other than
507
+ # cot or tan; test to see if the half-period
508
+ # is valid. Abs(arg) has behaviour equivalent to
509
+ # orig_f, so use that for test:
510
+ orig_f = Abs(arg)
511
+ try:
512
+ return _check(orig_f, period/2)
513
+ except NotImplementedError as err:
514
+ if check:
515
+ raise NotImplementedError(err)
516
+ # else let new orig_f and period be
517
+ # checked below
518
+
519
+ if isinstance(f, exp) or (f.is_Pow and f.base == S.Exp1):
520
+ f = Pow(S.Exp1, expand_mul(f.exp))
521
+ if im(f) != 0:
522
+ period_real = periodicity(re(f), symbol)
523
+ period_imag = periodicity(im(f), symbol)
524
+ if period_real is not None and period_imag is not None:
525
+ period = lcim([period_real, period_imag])
526
+
527
+ if f.is_Pow and f.base != S.Exp1:
528
+ base, expo = f.args
529
+ base_has_sym = base.has(symbol)
530
+ expo_has_sym = expo.has(symbol)
531
+
532
+ if base_has_sym and not expo_has_sym:
533
+ period = periodicity(base, symbol)
534
+
535
+ elif expo_has_sym and not base_has_sym:
536
+ period = periodicity(expo, symbol)
537
+
538
+ else:
539
+ period = _periodicity(f.args, symbol)
540
+
541
+ elif f.is_Mul:
542
+ coeff, g = f.as_independent(symbol, as_Add=False)
543
+ if isinstance(g, TrigonometricFunction) or not equal_valued(coeff, 1):
544
+ period = periodicity(g, symbol)
545
+ else:
546
+ period = _periodicity(g.args, symbol)
547
+
548
+ elif f.is_Add:
549
+ k, g = f.as_independent(symbol)
550
+ if k is not S.Zero:
551
+ return periodicity(g, symbol)
552
+
553
+ period = _periodicity(g.args, symbol)
554
+
555
+ elif isinstance(f, Mod):
556
+ a, n = f.args
557
+
558
+ if a == symbol:
559
+ period = n
560
+ elif isinstance(a, TrigonometricFunction):
561
+ period = periodicity(a, symbol)
562
+ #check if 'f' is linear in 'symbol'
563
+ elif (a.is_polynomial(symbol) and degree(a, symbol) == 1 and
564
+ symbol not in n.free_symbols):
565
+ period = Abs(n / a.diff(symbol))
566
+
567
+ elif isinstance(f, Piecewise):
568
+ pass # not handling Piecewise yet as the return type is not favorable
569
+
570
+ elif period is None:
571
+ from sympy.solvers.decompogen import compogen, decompogen
572
+ g_s = decompogen(f, symbol)
573
+ num_of_gs = len(g_s)
574
+ if num_of_gs > 1:
575
+ for index, g in enumerate(reversed(g_s)):
576
+ start_index = num_of_gs - 1 - index
577
+ g = compogen(g_s[start_index:], symbol)
578
+ if g not in (orig_f, f): # Fix for issue 12620
579
+ period = periodicity(g, symbol)
580
+ if period is not None:
581
+ break
582
+
583
+ if period is not None:
584
+ if check:
585
+ return _check(orig_f, period)
586
+ return period
587
+
588
+ return None
589
+
590
+
591
+ def _periodicity(args, symbol):
592
+ """
593
+ Helper for `periodicity` to find the period of a list of simpler
594
+ functions.
595
+ It uses the `lcim` method to find the least common period of
596
+ all the functions.
597
+
598
+ Parameters
599
+ ==========
600
+
601
+ args : Tuple of :py:class:`~.Symbol`
602
+ All the symbols present in a function.
603
+
604
+ symbol : :py:class:`~.Symbol`
605
+ The symbol over which the function is to be evaluated.
606
+
607
+ Returns
608
+ =======
609
+
610
+ period
611
+ The least common period of the function for all the symbols
612
+ of the function.
613
+ ``None`` if for at least one of the symbols the function is aperiodic.
614
+
615
+ """
616
+ periods = []
617
+ for f in args:
618
+ period = periodicity(f, symbol)
619
+ if period is None:
620
+ return None
621
+
622
+ if period is not S.Zero:
623
+ periods.append(period)
624
+
625
+ if len(periods) > 1:
626
+ return lcim(periods)
627
+
628
+ if periods:
629
+ return periods[0]
630
+
631
+
632
+ def lcim(numbers):
633
+ """Returns the least common integral multiple of a list of numbers.
634
+
635
+ The numbers can be rational or irrational or a mixture of both.
636
+ `None` is returned for incommensurable numbers.
637
+
638
+ Parameters
639
+ ==========
640
+
641
+ numbers : list
642
+ Numbers (rational and/or irrational) for which lcim is to be found.
643
+
644
+ Returns
645
+ =======
646
+
647
+ number
648
+ lcim if it exists, otherwise ``None`` for incommensurable numbers.
649
+
650
+ Examples
651
+ ========
652
+
653
+ >>> from sympy.calculus.util import lcim
654
+ >>> from sympy import S, pi
655
+ >>> lcim([S(1)/2, S(3)/4, S(5)/6])
656
+ 15/2
657
+ >>> lcim([2*pi, 3*pi, pi, pi/2])
658
+ 6*pi
659
+ >>> lcim([S(1), 2*pi])
660
+ """
661
+ result = None
662
+ if all(num.is_irrational for num in numbers):
663
+ factorized_nums = [num.factor() for num in numbers]
664
+ factors_num = [num.as_coeff_Mul() for num in factorized_nums]
665
+ term = factors_num[0][1]
666
+ if all(factor == term for coeff, factor in factors_num):
667
+ common_term = term
668
+ coeffs = [coeff for coeff, factor in factors_num]
669
+ result = lcm_list(coeffs) * common_term
670
+
671
+ elif all(num.is_rational for num in numbers):
672
+ result = lcm_list(numbers)
673
+
674
+ else:
675
+ pass
676
+
677
+ return result
678
+
679
+ def is_convex(f, *syms, domain=S.Reals):
680
+ r"""Determines the convexity of the function passed in the argument.
681
+
682
+ Parameters
683
+ ==========
684
+
685
+ f : :py:class:`~.Expr`
686
+ The concerned function.
687
+ syms : Tuple of :py:class:`~.Symbol`
688
+ The variables with respect to which the convexity is to be determined.
689
+ domain : :py:class:`~.Interval`, optional
690
+ The domain over which the convexity of the function has to be checked.
691
+ If unspecified, S.Reals will be the default domain.
692
+
693
+ Returns
694
+ =======
695
+
696
+ bool
697
+ The method returns ``True`` if the function is convex otherwise it
698
+ returns ``False``.
699
+
700
+ Raises
701
+ ======
702
+
703
+ NotImplementedError
704
+ The check for the convexity of multivariate functions is not implemented yet.
705
+
706
+ Notes
707
+ =====
708
+
709
+ To determine concavity of a function pass `-f` as the concerned function.
710
+ To determine logarithmic convexity of a function pass `\log(f)` as
711
+ concerned function.
712
+ To determine logarithmic concavity of a function pass `-\log(f)` as
713
+ concerned function.
714
+
715
+ Currently, convexity check of multivariate functions is not handled.
716
+
717
+ Examples
718
+ ========
719
+
720
+ >>> from sympy import is_convex, symbols, exp, oo, Interval
721
+ >>> x = symbols('x')
722
+ >>> is_convex(exp(x), x)
723
+ True
724
+ >>> is_convex(x**3, x, domain = Interval(-1, oo))
725
+ False
726
+ >>> is_convex(1/x**2, x, domain=Interval.open(0, oo))
727
+ True
728
+
729
+ References
730
+ ==========
731
+
732
+ .. [1] https://en.wikipedia.org/wiki/Convex_function
733
+ .. [2] http://www.ifp.illinois.edu/~angelia/L3_convfunc.pdf
734
+ .. [3] https://en.wikipedia.org/wiki/Logarithmically_convex_function
735
+ .. [4] https://en.wikipedia.org/wiki/Logarithmically_concave_function
736
+ .. [5] https://en.wikipedia.org/wiki/Concave_function
737
+
738
+ """
739
+ if len(syms) > 1 :
740
+ return hessian(f, syms).is_positive_semidefinite
741
+ from sympy.solvers.inequalities import solve_univariate_inequality
742
+ f = _sympify(f)
743
+ var = syms[0]
744
+ if any(s in domain for s in singularities(f, var)):
745
+ return False
746
+ condition = f.diff(var, 2) < 0
747
+ if solve_univariate_inequality(condition, var, False, domain):
748
+ return False
749
+ return True
750
+
751
+
752
+ def stationary_points(f, symbol, domain=S.Reals):
753
+ """
754
+ Returns the stationary points of a function (where derivative of the
755
+ function is 0) in the given domain.
756
+
757
+ Parameters
758
+ ==========
759
+
760
+ f : :py:class:`~.Expr`
761
+ The concerned function.
762
+ symbol : :py:class:`~.Symbol`
763
+ The variable for which the stationary points are to be determined.
764
+ domain : :py:class:`~.Interval`
765
+ The domain over which the stationary points have to be checked.
766
+ If unspecified, ``S.Reals`` will be the default domain.
767
+
768
+ Returns
769
+ =======
770
+
771
+ Set
772
+ A set of stationary points for the function. If there are no
773
+ stationary point, an :py:class:`~.EmptySet` is returned.
774
+
775
+ Examples
776
+ ========
777
+
778
+ >>> from sympy import Interval, Symbol, S, sin, pi, pprint, stationary_points
779
+ >>> x = Symbol('x')
780
+
781
+ >>> stationary_points(1/x, x, S.Reals)
782
+ EmptySet
783
+
784
+ >>> pprint(stationary_points(sin(x), x), use_unicode=False)
785
+ pi 3*pi
786
+ {2*n*pi + -- | n in Integers} U {2*n*pi + ---- | n in Integers}
787
+ 2 2
788
+
789
+ >>> stationary_points(sin(x),x, Interval(0, 4*pi))
790
+ {pi/2, 3*pi/2, 5*pi/2, 7*pi/2}
791
+
792
+ """
793
+ from sympy.solvers.solveset import solveset
794
+
795
+ if domain is S.EmptySet:
796
+ return S.EmptySet
797
+
798
+ domain = continuous_domain(f, symbol, domain)
799
+ set = solveset(diff(f, symbol), symbol, domain)
800
+
801
+ return set
802
+
803
+
804
+ def maximum(f, symbol, domain=S.Reals):
805
+ """
806
+ Returns the maximum value of a function in the given domain.
807
+
808
+ Parameters
809
+ ==========
810
+
811
+ f : :py:class:`~.Expr`
812
+ The concerned function.
813
+ symbol : :py:class:`~.Symbol`
814
+ The variable for maximum value needs to be determined.
815
+ domain : :py:class:`~.Interval`
816
+ The domain over which the maximum have to be checked.
817
+ If unspecified, then the global maximum is returned.
818
+
819
+ Returns
820
+ =======
821
+
822
+ number
823
+ Maximum value of the function in given domain.
824
+
825
+ Examples
826
+ ========
827
+
828
+ >>> from sympy import Interval, Symbol, S, sin, cos, pi, maximum
829
+ >>> x = Symbol('x')
830
+
831
+ >>> f = -x**2 + 2*x + 5
832
+ >>> maximum(f, x, S.Reals)
833
+ 6
834
+
835
+ >>> maximum(sin(x), x, Interval(-pi, pi/4))
836
+ sqrt(2)/2
837
+
838
+ >>> maximum(sin(x)*cos(x), x)
839
+ 1/2
840
+
841
+ """
842
+ if isinstance(symbol, Symbol):
843
+ if domain is S.EmptySet:
844
+ raise ValueError("Maximum value not defined for empty domain.")
845
+
846
+ return function_range(f, symbol, domain).sup
847
+ else:
848
+ raise ValueError("%s is not a valid symbol." % symbol)
849
+
850
+
851
+ def minimum(f, symbol, domain=S.Reals):
852
+ """
853
+ Returns the minimum value of a function in the given domain.
854
+
855
+ Parameters
856
+ ==========
857
+
858
+ f : :py:class:`~.Expr`
859
+ The concerned function.
860
+ symbol : :py:class:`~.Symbol`
861
+ The variable for minimum value needs to be determined.
862
+ domain : :py:class:`~.Interval`
863
+ The domain over which the minimum have to be checked.
864
+ If unspecified, then the global minimum is returned.
865
+
866
+ Returns
867
+ =======
868
+
869
+ number
870
+ Minimum value of the function in the given domain.
871
+
872
+ Examples
873
+ ========
874
+
875
+ >>> from sympy import Interval, Symbol, S, sin, cos, minimum
876
+ >>> x = Symbol('x')
877
+
878
+ >>> f = x**2 + 2*x + 5
879
+ >>> minimum(f, x, S.Reals)
880
+ 4
881
+
882
+ >>> minimum(sin(x), x, Interval(2, 3))
883
+ sin(3)
884
+
885
+ >>> minimum(sin(x)*cos(x), x)
886
+ -1/2
887
+
888
+ """
889
+ if isinstance(symbol, Symbol):
890
+ if domain is S.EmptySet:
891
+ raise ValueError("Minimum value not defined for empty domain.")
892
+
893
+ return function_range(f, symbol, domain).inf
894
+ else:
895
+ raise ValueError("%s is not a valid symbol." % symbol)
miniconda3/envs/active_proaction/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
+ ]
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/categories/baseclasses.py ADDED
@@ -0,0 +1,978 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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,
613
+ id:C-->C: EmptySet, 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, Dict)):
779
+ # The user has supplied a dictionary of morphisms and
780
+ # their properties.
781
+ for morphism, props in conclusions_arg.items():
782
+ # Check that no new objects appear in conclusions.
783
+ if (morphism.domain in objects) and \
784
+ (morphism.codomain in objects):
785
+ # No need to add identities and recurse
786
+ # composites this time.
787
+ Diagram._add_morphism_closure(
788
+ conclusions, morphism, FiniteSet(*props) if iterable(props) else FiniteSet(props),
789
+ add_identities=False, recurse_composites=False)
790
+
791
+ return Basic.__new__(cls, Dict(premises), Dict(conclusions), objects)
792
+
793
+ @property
794
+ def premises(self):
795
+ """
796
+ Returns the premises of this diagram.
797
+
798
+ Examples
799
+ ========
800
+
801
+ >>> from sympy.categories import Object, NamedMorphism
802
+ >>> from sympy.categories import IdentityMorphism, Diagram
803
+ >>> from sympy import pretty
804
+ >>> A = Object("A")
805
+ >>> B = Object("B")
806
+ >>> f = NamedMorphism(A, B, "f")
807
+ >>> id_A = IdentityMorphism(A)
808
+ >>> id_B = IdentityMorphism(B)
809
+ >>> d = Diagram([f])
810
+ >>> print(pretty(d.premises, use_unicode=False))
811
+ {id:A-->A: EmptySet, id:B-->B: EmptySet, f:A-->B: EmptySet}
812
+
813
+ """
814
+ return self.args[0]
815
+
816
+ @property
817
+ def conclusions(self):
818
+ """
819
+ Returns the conclusions of this diagram.
820
+
821
+ Examples
822
+ ========
823
+
824
+ >>> from sympy.categories import Object, NamedMorphism
825
+ >>> from sympy.categories import IdentityMorphism, Diagram
826
+ >>> from sympy import FiniteSet
827
+ >>> A = Object("A")
828
+ >>> B = Object("B")
829
+ >>> C = Object("C")
830
+ >>> f = NamedMorphism(A, B, "f")
831
+ >>> g = NamedMorphism(B, C, "g")
832
+ >>> d = Diagram([f, g])
833
+ >>> IdentityMorphism(A) in d.premises.keys()
834
+ True
835
+ >>> g * f in d.premises.keys()
836
+ True
837
+ >>> d = Diagram([f, g], {g * f: "unique"})
838
+ >>> d.conclusions[g * f] == FiniteSet("unique")
839
+ True
840
+
841
+ """
842
+ return self.args[1]
843
+
844
+ @property
845
+ def objects(self):
846
+ """
847
+ Returns the :class:`~.FiniteSet` of objects that appear in this
848
+ diagram.
849
+
850
+ Examples
851
+ ========
852
+
853
+ >>> from sympy.categories import Object, NamedMorphism, Diagram
854
+ >>> A = Object("A")
855
+ >>> B = Object("B")
856
+ >>> C = Object("C")
857
+ >>> f = NamedMorphism(A, B, "f")
858
+ >>> g = NamedMorphism(B, C, "g")
859
+ >>> d = Diagram([f, g])
860
+ >>> d.objects
861
+ {Object("A"), Object("B"), Object("C")}
862
+
863
+ """
864
+ return self.args[2]
865
+
866
+ def hom(self, A, B):
867
+ """
868
+ Returns a 2-tuple of sets of morphisms between objects ``A`` and
869
+ ``B``: one set of morphisms listed as premises, and the other set
870
+ of morphisms listed as conclusions.
871
+
872
+ Examples
873
+ ========
874
+
875
+ >>> from sympy.categories import Object, NamedMorphism, Diagram
876
+ >>> from sympy import pretty
877
+ >>> A = Object("A")
878
+ >>> B = Object("B")
879
+ >>> C = Object("C")
880
+ >>> f = NamedMorphism(A, B, "f")
881
+ >>> g = NamedMorphism(B, C, "g")
882
+ >>> d = Diagram([f, g], {g * f: "unique"})
883
+ >>> print(pretty(d.hom(A, C), use_unicode=False))
884
+ ({g*f:A-->C}, {g*f:A-->C})
885
+
886
+ See Also
887
+ ========
888
+ Object, Morphism
889
+ """
890
+ premises = EmptySet
891
+ conclusions = EmptySet
892
+
893
+ for morphism in self.premises.keys():
894
+ if (morphism.domain == A) and (morphism.codomain == B):
895
+ premises |= FiniteSet(morphism)
896
+ for morphism in self.conclusions.keys():
897
+ if (morphism.domain == A) and (morphism.codomain == B):
898
+ conclusions |= FiniteSet(morphism)
899
+
900
+ return (premises, conclusions)
901
+
902
+ def is_subdiagram(self, diagram):
903
+ """
904
+ Checks whether ``diagram`` is a subdiagram of ``self``.
905
+ Diagram `D'` is a subdiagram of `D` if all premises
906
+ (conclusions) of `D'` are contained in the premises
907
+ (conclusions) of `D`. The morphisms contained
908
+ both in `D'` and `D` should have the same properties for `D'`
909
+ to be a subdiagram of `D`.
910
+
911
+ Examples
912
+ ========
913
+
914
+ >>> from sympy.categories import Object, NamedMorphism, Diagram
915
+ >>> A = Object("A")
916
+ >>> B = Object("B")
917
+ >>> C = Object("C")
918
+ >>> f = NamedMorphism(A, B, "f")
919
+ >>> g = NamedMorphism(B, C, "g")
920
+ >>> d = Diagram([f, g], {g * f: "unique"})
921
+ >>> d1 = Diagram([f])
922
+ >>> d.is_subdiagram(d1)
923
+ True
924
+ >>> d1.is_subdiagram(d)
925
+ False
926
+ """
927
+ premises = all((m in self.premises) and
928
+ (diagram.premises[m] == self.premises[m])
929
+ for m in diagram.premises)
930
+ if not premises:
931
+ return False
932
+
933
+ conclusions = all((m in self.conclusions) and
934
+ (diagram.conclusions[m] == self.conclusions[m])
935
+ for m in diagram.conclusions)
936
+
937
+ # Premises is surely ``True`` here.
938
+ return conclusions
939
+
940
+ def subdiagram_from_objects(self, objects):
941
+ """
942
+ If ``objects`` is a subset of the objects of ``self``, returns
943
+ a diagram which has as premises all those premises of ``self``
944
+ which have a domains and codomains in ``objects``, likewise
945
+ for conclusions. Properties are preserved.
946
+
947
+ Examples
948
+ ========
949
+
950
+ >>> from sympy.categories import Object, NamedMorphism, Diagram
951
+ >>> from sympy import FiniteSet
952
+ >>> A = Object("A")
953
+ >>> B = Object("B")
954
+ >>> C = Object("C")
955
+ >>> f = NamedMorphism(A, B, "f")
956
+ >>> g = NamedMorphism(B, C, "g")
957
+ >>> d = Diagram([f, g], {f: "unique", g*f: "veryunique"})
958
+ >>> d1 = d.subdiagram_from_objects(FiniteSet(A, B))
959
+ >>> d1 == Diagram([f], {f: "unique"})
960
+ True
961
+ """
962
+ if not objects.is_subset(self.objects):
963
+ raise ValueError(
964
+ "Supplied objects should all belong to the diagram.")
965
+
966
+ new_premises = {}
967
+ for morphism, props in self.premises.items():
968
+ if ((sympify(objects.contains(morphism.domain)) is S.true) and
969
+ (sympify(objects.contains(morphism.codomain)) is S.true)):
970
+ new_premises[morphism] = props
971
+
972
+ new_conclusions = {}
973
+ for morphism, props in self.conclusions.items():
974
+ if ((sympify(objects.contains(morphism.domain)) is S.true) and
975
+ (sympify(objects.contains(morphism.codomain)) is S.true)):
976
+ new_conclusions[morphism] = props
977
+
978
+ return Diagram(new_premises, new_conclusions)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/categories/diagram_drawing.py ADDED
@@ -0,0 +1,2580 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 = {obj: [] for obj in objects}
1032
+
1033
+ for morphism in merged_morphisms:
1034
+ adjlists[morphism.domain].append(morphism.codomain)
1035
+ adjlists[morphism.codomain].append(morphism.domain)
1036
+
1037
+ # Assure that the objects in the adjacency list are always in
1038
+ # the same order.
1039
+ for obj in adjlists.keys():
1040
+ adjlists[obj].sort(key=default_sort_key)
1041
+
1042
+ return adjlists
1043
+
1044
+ @staticmethod
1045
+ def _sequential_layout(diagram, merged_morphisms):
1046
+ r"""
1047
+ Lays out the diagram in "sequential" layout. This method
1048
+ will attempt to produce a result as close to a line as
1049
+ possible. For linear diagrams, the result will actually be a
1050
+ line.
1051
+ """
1052
+ objects = diagram.objects
1053
+ sorted_objects = sorted(objects, key=default_sort_key)
1054
+
1055
+ # Set up the adjacency lists of the underlying undirected
1056
+ # graph of ``merged_morphisms``.
1057
+ adjlists = DiagramGrid._get_undirected_graph(objects, merged_morphisms)
1058
+
1059
+ root = min(sorted_objects, key=lambda x: len(adjlists[x]))
1060
+ grid = _GrowableGrid(1, 1)
1061
+ grid[0, 0] = root
1062
+
1063
+ placed_objects = {root}
1064
+
1065
+ def place_objects(pt, placed_objects):
1066
+ """
1067
+ Does depth-first search in the underlying graph of the
1068
+ diagram and places the objects en route.
1069
+ """
1070
+ # We will start placing new objects from here.
1071
+ new_pt = (pt[0], pt[1] + 1)
1072
+
1073
+ for adjacent_obj in adjlists[grid[pt]]:
1074
+ if adjacent_obj in placed_objects:
1075
+ # This object has already been placed.
1076
+ continue
1077
+
1078
+ DiagramGrid._put_object(new_pt, adjacent_obj, grid, [])
1079
+ placed_objects.add(adjacent_obj)
1080
+ placed_objects.update(place_objects(new_pt, placed_objects))
1081
+
1082
+ new_pt = (new_pt[0] + 1, new_pt[1])
1083
+
1084
+ return placed_objects
1085
+
1086
+ place_objects((0, 0), placed_objects)
1087
+
1088
+ return grid
1089
+
1090
+ @staticmethod
1091
+ def _drop_inessential_morphisms(merged_morphisms):
1092
+ r"""
1093
+ Removes those morphisms which should appear in the diagram,
1094
+ but which have no relevance to object layout.
1095
+
1096
+ Currently this removes "loop" morphisms: the non-identity
1097
+ morphisms with the same domains and codomains.
1098
+ """
1099
+ morphisms = [m for m in merged_morphisms if m.domain != m.codomain]
1100
+ return morphisms
1101
+
1102
+ @staticmethod
1103
+ def _get_connected_components(objects, merged_morphisms):
1104
+ """
1105
+ Given a container of morphisms, returns a list of connected
1106
+ components formed by these morphisms. A connected component
1107
+ is represented by a diagram consisting of the corresponding
1108
+ morphisms.
1109
+ """
1110
+ component_index = {}
1111
+ for o in objects:
1112
+ component_index[o] = None
1113
+
1114
+ # Get the underlying undirected graph of the diagram.
1115
+ adjlist = DiagramGrid._get_undirected_graph(objects, merged_morphisms)
1116
+
1117
+ def traverse_component(object, current_index):
1118
+ """
1119
+ Does a depth-first search traversal of the component
1120
+ containing ``object``.
1121
+ """
1122
+ component_index[object] = current_index
1123
+ for o in adjlist[object]:
1124
+ if component_index[o] is None:
1125
+ traverse_component(o, current_index)
1126
+
1127
+ # Traverse all components.
1128
+ current_index = 0
1129
+ for o in adjlist:
1130
+ if component_index[o] is None:
1131
+ traverse_component(o, current_index)
1132
+ current_index += 1
1133
+
1134
+ # List the objects of the components.
1135
+ component_objects = [[] for i in range(current_index)]
1136
+ for o, idx in component_index.items():
1137
+ component_objects[idx].append(o)
1138
+
1139
+ # Finally, list the morphisms belonging to each component.
1140
+ #
1141
+ # Note: If some objects are isolated, they will not get any
1142
+ # morphisms at this stage, and since the layout algorithm
1143
+ # relies, we are essentially going to lose this object.
1144
+ # Therefore, check if there are isolated objects and, for each
1145
+ # of them, provide the trivial identity morphism. It will get
1146
+ # discarded later, but the object will be there.
1147
+
1148
+ component_morphisms = []
1149
+ for component in component_objects:
1150
+ current_morphisms = {}
1151
+ for m in merged_morphisms:
1152
+ if (m.domain in component) and (m.codomain in component):
1153
+ current_morphisms[m] = merged_morphisms[m]
1154
+
1155
+ if len(component) == 1:
1156
+ # Let's add an identity morphism, for the sake of
1157
+ # surely having morphisms in this component.
1158
+ current_morphisms[IdentityMorphism(component[0])] = FiniteSet()
1159
+
1160
+ component_morphisms.append(Diagram(current_morphisms))
1161
+
1162
+ return component_morphisms
1163
+
1164
+ def __init__(self, diagram, groups=None, **hints):
1165
+ premises = DiagramGrid._simplify_morphisms(diagram.premises)
1166
+ conclusions = DiagramGrid._simplify_morphisms(diagram.conclusions)
1167
+ all_merged_morphisms = DiagramGrid._merge_premises_conclusions(
1168
+ premises, conclusions)
1169
+ merged_morphisms = DiagramGrid._drop_inessential_morphisms(
1170
+ all_merged_morphisms)
1171
+
1172
+ # Store the merged morphisms for later use.
1173
+ self._morphisms = all_merged_morphisms
1174
+
1175
+ components = DiagramGrid._get_connected_components(
1176
+ diagram.objects, all_merged_morphisms)
1177
+
1178
+ if groups and (groups != diagram.objects):
1179
+ # Lay out the diagram according to the groups.
1180
+ self._grid = DiagramGrid._handle_groups(
1181
+ diagram, groups, merged_morphisms, hints)
1182
+ elif len(components) > 1:
1183
+ # Note that we check for connectedness _before_ checking
1184
+ # the layout hints because the layout strategies don't
1185
+ # know how to deal with disconnected diagrams.
1186
+
1187
+ # The diagram is disconnected. Lay out the components
1188
+ # independently.
1189
+ grids = []
1190
+
1191
+ # Sort the components to eventually get the grids arranged
1192
+ # in a fixed, hash-independent order.
1193
+ components = sorted(components, key=default_sort_key)
1194
+
1195
+ for component in components:
1196
+ grid = DiagramGrid(component, **hints)
1197
+ grids.append(grid)
1198
+
1199
+ # Throw the grids together, in a line.
1200
+ total_width = sum(g.width for g in grids)
1201
+ total_height = max(g.height for g in grids)
1202
+
1203
+ grid = _GrowableGrid(total_width, total_height)
1204
+ start_j = 0
1205
+ for g in grids:
1206
+ for i in range(g.height):
1207
+ for j in range(g.width):
1208
+ grid[i, start_j + j] = g[i, j]
1209
+
1210
+ start_j += g.width
1211
+
1212
+ self._grid = grid
1213
+ elif "layout" in hints:
1214
+ if hints["layout"] == "sequential":
1215
+ self._grid = DiagramGrid._sequential_layout(
1216
+ diagram, merged_morphisms)
1217
+ else:
1218
+ self._grid = DiagramGrid._generic_layout(diagram, merged_morphisms)
1219
+
1220
+ if hints.get("transpose"):
1221
+ # Transpose the resulting grid.
1222
+ grid = _GrowableGrid(self._grid.height, self._grid.width)
1223
+ for i in range(self._grid.height):
1224
+ for j in range(self._grid.width):
1225
+ grid[j, i] = self._grid[i, j]
1226
+ self._grid = grid
1227
+
1228
+ @property
1229
+ def width(self):
1230
+ """
1231
+ Returns the number of columns in this diagram layout.
1232
+
1233
+ Examples
1234
+ ========
1235
+
1236
+ >>> from sympy.categories import Object, NamedMorphism
1237
+ >>> from sympy.categories import Diagram, DiagramGrid
1238
+ >>> A = Object("A")
1239
+ >>> B = Object("B")
1240
+ >>> C = Object("C")
1241
+ >>> f = NamedMorphism(A, B, "f")
1242
+ >>> g = NamedMorphism(B, C, "g")
1243
+ >>> diagram = Diagram([f, g])
1244
+ >>> grid = DiagramGrid(diagram)
1245
+ >>> grid.width
1246
+ 2
1247
+
1248
+ """
1249
+ return self._grid.width
1250
+
1251
+ @property
1252
+ def height(self):
1253
+ """
1254
+ Returns the number of rows in this diagram layout.
1255
+
1256
+ Examples
1257
+ ========
1258
+
1259
+ >>> from sympy.categories import Object, NamedMorphism
1260
+ >>> from sympy.categories import Diagram, DiagramGrid
1261
+ >>> A = Object("A")
1262
+ >>> B = Object("B")
1263
+ >>> C = Object("C")
1264
+ >>> f = NamedMorphism(A, B, "f")
1265
+ >>> g = NamedMorphism(B, C, "g")
1266
+ >>> diagram = Diagram([f, g])
1267
+ >>> grid = DiagramGrid(diagram)
1268
+ >>> grid.height
1269
+ 2
1270
+
1271
+ """
1272
+ return self._grid.height
1273
+
1274
+ def __getitem__(self, i_j):
1275
+ """
1276
+ Returns the object placed in the row ``i`` and column ``j``.
1277
+ The indices are 0-based.
1278
+
1279
+ Examples
1280
+ ========
1281
+
1282
+ >>> from sympy.categories import Object, NamedMorphism
1283
+ >>> from sympy.categories import Diagram, DiagramGrid
1284
+ >>> A = Object("A")
1285
+ >>> B = Object("B")
1286
+ >>> C = Object("C")
1287
+ >>> f = NamedMorphism(A, B, "f")
1288
+ >>> g = NamedMorphism(B, C, "g")
1289
+ >>> diagram = Diagram([f, g])
1290
+ >>> grid = DiagramGrid(diagram)
1291
+ >>> (grid[0, 0], grid[0, 1])
1292
+ (Object("A"), Object("B"))
1293
+ >>> (grid[1, 0], grid[1, 1])
1294
+ (None, Object("C"))
1295
+
1296
+ """
1297
+ i, j = i_j
1298
+ return self._grid[i, j]
1299
+
1300
+ @property
1301
+ def morphisms(self):
1302
+ """
1303
+ Returns those morphisms (and their properties) which are
1304
+ sufficiently meaningful to be drawn.
1305
+
1306
+ Examples
1307
+ ========
1308
+
1309
+ >>> from sympy.categories import Object, NamedMorphism
1310
+ >>> from sympy.categories import Diagram, DiagramGrid
1311
+ >>> A = Object("A")
1312
+ >>> B = Object("B")
1313
+ >>> C = Object("C")
1314
+ >>> f = NamedMorphism(A, B, "f")
1315
+ >>> g = NamedMorphism(B, C, "g")
1316
+ >>> diagram = Diagram([f, g])
1317
+ >>> grid = DiagramGrid(diagram)
1318
+ >>> grid.morphisms
1319
+ {NamedMorphism(Object("A"), Object("B"), "f"): EmptySet,
1320
+ NamedMorphism(Object("B"), Object("C"), "g"): EmptySet}
1321
+
1322
+ """
1323
+ return self._morphisms
1324
+
1325
+ def __str__(self):
1326
+ """
1327
+ Produces a string representation of this class.
1328
+
1329
+ This method returns a string representation of the underlying
1330
+ list of lists of objects.
1331
+
1332
+ Examples
1333
+ ========
1334
+
1335
+ >>> from sympy.categories import Object, NamedMorphism
1336
+ >>> from sympy.categories import Diagram, DiagramGrid
1337
+ >>> A = Object("A")
1338
+ >>> B = Object("B")
1339
+ >>> C = Object("C")
1340
+ >>> f = NamedMorphism(A, B, "f")
1341
+ >>> g = NamedMorphism(B, C, "g")
1342
+ >>> diagram = Diagram([f, g])
1343
+ >>> grid = DiagramGrid(diagram)
1344
+ >>> print(grid)
1345
+ [[Object("A"), Object("B")],
1346
+ [None, Object("C")]]
1347
+
1348
+ """
1349
+ return repr(self._grid._array)
1350
+
1351
+
1352
+ class ArrowStringDescription:
1353
+ r"""
1354
+ Stores the information necessary for producing an Xy-pic
1355
+ description of an arrow.
1356
+
1357
+ The principal goal of this class is to abstract away the string
1358
+ representation of an arrow and to also provide the functionality
1359
+ to produce the actual Xy-pic string.
1360
+
1361
+ ``unit`` sets the unit which will be used to specify the amount of
1362
+ curving and other distances. ``horizontal_direction`` should be a
1363
+ string of ``"r"`` or ``"l"`` specifying the horizontal offset of the
1364
+ target cell of the arrow relatively to the current one.
1365
+ ``vertical_direction`` should specify the vertical offset using a
1366
+ series of either ``"d"`` or ``"u"``. ``label_position`` should be
1367
+ either ``"^"``, ``"_"``, or ``"|"`` to specify that the label should
1368
+ be positioned above the arrow, below the arrow or just over the arrow,
1369
+ in a break. Note that the notions "above" and "below" are relative
1370
+ to arrow direction. ``label`` stores the morphism label.
1371
+
1372
+ This works as follows (disregard the yet unexplained arguments):
1373
+
1374
+ >>> from sympy.categories.diagram_drawing import ArrowStringDescription
1375
+ >>> astr = ArrowStringDescription(
1376
+ ... unit="mm", curving=None, curving_amount=None,
1377
+ ... looping_start=None, looping_end=None, horizontal_direction="d",
1378
+ ... vertical_direction="r", label_position="_", label="f")
1379
+ >>> print(str(astr))
1380
+ \ar[dr]_{f}
1381
+
1382
+ ``curving`` should be one of ``"^"``, ``"_"`` to specify in which
1383
+ direction the arrow is going to curve. ``curving_amount`` is a number
1384
+ describing how many ``unit``'s the morphism is going to curve:
1385
+
1386
+ >>> astr = ArrowStringDescription(
1387
+ ... unit="mm", curving="^", curving_amount=12,
1388
+ ... looping_start=None, looping_end=None, horizontal_direction="d",
1389
+ ... vertical_direction="r", label_position="_", label="f")
1390
+ >>> print(str(astr))
1391
+ \ar@/^12mm/[dr]_{f}
1392
+
1393
+ ``looping_start`` and ``looping_end`` are currently only used for
1394
+ loop morphisms, those which have the same domain and codomain.
1395
+ These two attributes should store a valid Xy-pic direction and
1396
+ specify, correspondingly, the direction the arrow gets out into
1397
+ and the direction the arrow gets back from:
1398
+
1399
+ >>> astr = ArrowStringDescription(
1400
+ ... unit="mm", curving=None, curving_amount=None,
1401
+ ... looping_start="u", looping_end="l", horizontal_direction="",
1402
+ ... vertical_direction="", label_position="_", label="f")
1403
+ >>> print(str(astr))
1404
+ \ar@(u,l)[]_{f}
1405
+
1406
+ ``label_displacement`` controls how far the arrow label is from
1407
+ the ends of the arrow. For example, to position the arrow label
1408
+ near the arrow head, use ">":
1409
+
1410
+ >>> astr = ArrowStringDescription(
1411
+ ... unit="mm", curving="^", curving_amount=12,
1412
+ ... looping_start=None, looping_end=None, horizontal_direction="d",
1413
+ ... vertical_direction="r", label_position="_", label="f")
1414
+ >>> astr.label_displacement = ">"
1415
+ >>> print(str(astr))
1416
+ \ar@/^12mm/[dr]_>{f}
1417
+
1418
+ Finally, ``arrow_style`` is used to specify the arrow style. To
1419
+ get a dashed arrow, for example, use "{-->}" as arrow style:
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.arrow_style = "{-->}"
1426
+ >>> print(str(astr))
1427
+ \ar@/^12mm/@{-->}[dr]_{f}
1428
+
1429
+ Notes
1430
+ =====
1431
+
1432
+ Instances of :class:`ArrowStringDescription` will be constructed
1433
+ by :class:`XypicDiagramDrawer` and provided for further use in
1434
+ formatters. The user is not expected to construct instances of
1435
+ :class:`ArrowStringDescription` themselves.
1436
+
1437
+ To be able to properly utilise this class, the reader is encouraged
1438
+ to checkout the Xy-pic user guide, available at [Xypic].
1439
+
1440
+ See Also
1441
+ ========
1442
+
1443
+ XypicDiagramDrawer
1444
+
1445
+ References
1446
+ ==========
1447
+
1448
+ .. [Xypic] https://xy-pic.sourceforge.net/
1449
+ """
1450
+ def __init__(self, unit, curving, curving_amount, looping_start,
1451
+ looping_end, horizontal_direction, vertical_direction,
1452
+ label_position, label):
1453
+ self.unit = unit
1454
+ self.curving = curving
1455
+ self.curving_amount = curving_amount
1456
+ self.looping_start = looping_start
1457
+ self.looping_end = looping_end
1458
+ self.horizontal_direction = horizontal_direction
1459
+ self.vertical_direction = vertical_direction
1460
+ self.label_position = label_position
1461
+ self.label = label
1462
+
1463
+ self.label_displacement = ""
1464
+ self.arrow_style = ""
1465
+
1466
+ # This flag shows that the position of the label of this
1467
+ # morphism was set while typesetting a curved morphism and
1468
+ # should not be modified later.
1469
+ self.forced_label_position = False
1470
+
1471
+ def __str__(self):
1472
+ if self.curving:
1473
+ curving_str = "@/%s%d%s/" % (self.curving, self.curving_amount,
1474
+ self.unit)
1475
+ else:
1476
+ curving_str = ""
1477
+
1478
+ if self.looping_start and self.looping_end:
1479
+ looping_str = "@(%s,%s)" % (self.looping_start, self.looping_end)
1480
+ else:
1481
+ looping_str = ""
1482
+
1483
+ if self.arrow_style:
1484
+
1485
+ style_str = "@" + self.arrow_style
1486
+ else:
1487
+ style_str = ""
1488
+
1489
+ return "\\ar%s%s%s[%s%s]%s%s{%s}" % \
1490
+ (curving_str, looping_str, style_str, self.horizontal_direction,
1491
+ self.vertical_direction, self.label_position,
1492
+ self.label_displacement, self.label)
1493
+
1494
+
1495
+ class XypicDiagramDrawer:
1496
+ r"""
1497
+ Given a :class:`~.Diagram` and the corresponding
1498
+ :class:`DiagramGrid`, produces the Xy-pic representation of the
1499
+ diagram.
1500
+
1501
+ The most important method in this class is ``draw``. Consider the
1502
+ following triangle diagram:
1503
+
1504
+ >>> from sympy.categories import Object, NamedMorphism, Diagram
1505
+ >>> from sympy.categories import DiagramGrid, XypicDiagramDrawer
1506
+ >>> A = Object("A")
1507
+ >>> B = Object("B")
1508
+ >>> C = Object("C")
1509
+ >>> f = NamedMorphism(A, B, "f")
1510
+ >>> g = NamedMorphism(B, C, "g")
1511
+ >>> diagram = Diagram([f, g], {g * f: "unique"})
1512
+
1513
+ To draw this diagram, its objects need to be laid out with a
1514
+ :class:`DiagramGrid`::
1515
+
1516
+ >>> grid = DiagramGrid(diagram)
1517
+
1518
+ Finally, the drawing:
1519
+
1520
+ >>> drawer = XypicDiagramDrawer()
1521
+ >>> print(drawer.draw(diagram, grid))
1522
+ \xymatrix{
1523
+ A \ar[d]_{g\circ f} \ar[r]^{f} & B \ar[ld]^{g} \\
1524
+ C &
1525
+ }
1526
+
1527
+ For further details see the docstring of this method.
1528
+
1529
+ To control the appearance of the arrows, formatters are used. The
1530
+ dictionary ``arrow_formatters`` maps morphisms to formatter
1531
+ functions. A formatter is accepts an
1532
+ :class:`ArrowStringDescription` and is allowed to modify any of
1533
+ the arrow properties exposed thereby. For example, to have all
1534
+ morphisms with the property ``unique`` appear as dashed arrows,
1535
+ and to have their names prepended with `\exists !`, the following
1536
+ should be done:
1537
+
1538
+ >>> def formatter(astr):
1539
+ ... astr.label = r"\exists !" + astr.label
1540
+ ... astr.arrow_style = "{-->}"
1541
+ >>> drawer.arrow_formatters["unique"] = formatter
1542
+ >>> print(drawer.draw(diagram, grid))
1543
+ \xymatrix{
1544
+ A \ar@{-->}[d]_{\exists !g\circ f} \ar[r]^{f} & B \ar[ld]^{g} \\
1545
+ C &
1546
+ }
1547
+
1548
+ To modify the appearance of all arrows in the diagram, set
1549
+ ``default_arrow_formatter``. For example, to place all morphism
1550
+ labels a little bit farther from the arrow head so that they look
1551
+ more centred, do as follows:
1552
+
1553
+ >>> def default_formatter(astr):
1554
+ ... astr.label_displacement = "(0.45)"
1555
+ >>> drawer.default_arrow_formatter = default_formatter
1556
+ >>> print(drawer.draw(diagram, grid))
1557
+ \xymatrix{
1558
+ A \ar@{-->}[d]_(0.45){\exists !g\circ f} \ar[r]^(0.45){f} & B \ar[ld]^(0.45){g} \\
1559
+ C &
1560
+ }
1561
+
1562
+ In some diagrams some morphisms are drawn as curved arrows.
1563
+ Consider the following diagram:
1564
+
1565
+ >>> D = Object("D")
1566
+ >>> E = Object("E")
1567
+ >>> h = NamedMorphism(D, A, "h")
1568
+ >>> k = NamedMorphism(D, B, "k")
1569
+ >>> diagram = Diagram([f, g, h, k])
1570
+ >>> grid = DiagramGrid(diagram)
1571
+ >>> drawer = XypicDiagramDrawer()
1572
+ >>> print(drawer.draw(diagram, grid))
1573
+ \xymatrix{
1574
+ A \ar[r]_{f} & B \ar[d]^{g} & D \ar[l]^{k} \ar@/_3mm/[ll]_{h} \\
1575
+ & C &
1576
+ }
1577
+
1578
+ To control how far the morphisms are curved by default, one can
1579
+ use the ``unit`` and ``default_curving_amount`` attributes:
1580
+
1581
+ >>> drawer.unit = "cm"
1582
+ >>> drawer.default_curving_amount = 1
1583
+ >>> print(drawer.draw(diagram, grid))
1584
+ \xymatrix{
1585
+ A \ar[r]_{f} & B \ar[d]^{g} & D \ar[l]^{k} \ar@/_1cm/[ll]_{h} \\
1586
+ & C &
1587
+ }
1588
+
1589
+ In some diagrams, there are multiple curved morphisms between the
1590
+ same two objects. To control by how much the curving changes
1591
+ between two such successive morphisms, use
1592
+ ``default_curving_step``:
1593
+
1594
+ >>> drawer.default_curving_step = 1
1595
+ >>> h1 = NamedMorphism(A, D, "h1")
1596
+ >>> diagram = Diagram([f, g, h, k, h1])
1597
+ >>> grid = DiagramGrid(diagram)
1598
+ >>> print(drawer.draw(diagram, grid))
1599
+ \xymatrix{
1600
+ A \ar[r]_{f} \ar@/^1cm/[rr]^{h_{1}} & B \ar[d]^{g} & D \ar[l]^{k} \ar@/_2cm/[ll]_{h} \\
1601
+ & C &
1602
+ }
1603
+
1604
+ The default value of ``default_curving_step`` is 4 units.
1605
+
1606
+ See Also
1607
+ ========
1608
+
1609
+ draw, ArrowStringDescription
1610
+ """
1611
+ def __init__(self):
1612
+ self.unit = "mm"
1613
+ self.default_curving_amount = 3
1614
+ self.default_curving_step = 4
1615
+
1616
+ # This dictionary maps properties to the corresponding arrow
1617
+ # formatters.
1618
+ self.arrow_formatters = {}
1619
+
1620
+ # This is the default arrow formatter which will be applied to
1621
+ # each arrow independently of its properties.
1622
+ self.default_arrow_formatter = None
1623
+
1624
+ @staticmethod
1625
+ def _process_loop_morphism(i, j, grid, morphisms_str_info, object_coords):
1626
+ """
1627
+ Produces the information required for constructing the string
1628
+ representation of a loop morphism. This function is invoked
1629
+ from ``_process_morphism``.
1630
+
1631
+ See Also
1632
+ ========
1633
+
1634
+ _process_morphism
1635
+ """
1636
+ curving = ""
1637
+ label_pos = "^"
1638
+ looping_start = ""
1639
+ looping_end = ""
1640
+
1641
+ # This is a loop morphism. Count how many morphisms stick
1642
+ # in each of the four quadrants. Note that straight
1643
+ # vertical and horizontal morphisms count in two quadrants
1644
+ # at the same time (i.e., a morphism going up counts both
1645
+ # in the first and the second quadrants).
1646
+
1647
+ # The usual numbering (counterclockwise) of quadrants
1648
+ # applies.
1649
+ quadrant = [0, 0, 0, 0]
1650
+
1651
+ obj = grid[i, j]
1652
+
1653
+ for m, m_str_info in morphisms_str_info.items():
1654
+ if (m.domain == obj) and (m.codomain == obj):
1655
+ # That's another loop morphism. Check how it
1656
+ # loops and mark the corresponding quadrants as
1657
+ # busy.
1658
+ (l_s, l_e) = (m_str_info.looping_start, m_str_info.looping_end)
1659
+
1660
+ if (l_s, l_e) == ("r", "u"):
1661
+ quadrant[0] += 1
1662
+ elif (l_s, l_e) == ("u", "l"):
1663
+ quadrant[1] += 1
1664
+ elif (l_s, l_e) == ("l", "d"):
1665
+ quadrant[2] += 1
1666
+ elif (l_s, l_e) == ("d", "r"):
1667
+ quadrant[3] += 1
1668
+
1669
+ continue
1670
+ if m.domain == obj:
1671
+ (end_i, end_j) = object_coords[m.codomain]
1672
+ goes_out = True
1673
+ elif m.codomain == obj:
1674
+ (end_i, end_j) = object_coords[m.domain]
1675
+ goes_out = False
1676
+ else:
1677
+ continue
1678
+
1679
+ d_i = end_i - i
1680
+ d_j = end_j - j
1681
+ m_curving = m_str_info.curving
1682
+
1683
+ if (d_i != 0) and (d_j != 0):
1684
+ # This is really a diagonal morphism. Detect the
1685
+ # quadrant.
1686
+ if (d_i > 0) and (d_j > 0):
1687
+ quadrant[0] += 1
1688
+ elif (d_i > 0) and (d_j < 0):
1689
+ quadrant[1] += 1
1690
+ elif (d_i < 0) and (d_j < 0):
1691
+ quadrant[2] += 1
1692
+ elif (d_i < 0) and (d_j > 0):
1693
+ quadrant[3] += 1
1694
+ elif d_i == 0:
1695
+ # Knowing where the other end of the morphism is
1696
+ # and which way it goes, we now have to decide
1697
+ # which quadrant is now the upper one and which is
1698
+ # the lower one.
1699
+ if d_j > 0:
1700
+ if goes_out:
1701
+ upper_quadrant = 0
1702
+ lower_quadrant = 3
1703
+ else:
1704
+ upper_quadrant = 3
1705
+ lower_quadrant = 0
1706
+ else:
1707
+ if goes_out:
1708
+ upper_quadrant = 2
1709
+ lower_quadrant = 1
1710
+ else:
1711
+ upper_quadrant = 1
1712
+ lower_quadrant = 2
1713
+
1714
+ if m_curving:
1715
+ if m_curving == "^":
1716
+ quadrant[upper_quadrant] += 1
1717
+ elif m_curving == "_":
1718
+ quadrant[lower_quadrant] += 1
1719
+ else:
1720
+ # This morphism counts in both upper and lower
1721
+ # quadrants.
1722
+ quadrant[upper_quadrant] += 1
1723
+ quadrant[lower_quadrant] += 1
1724
+ elif d_j == 0:
1725
+ # Knowing where the other end of the morphism is
1726
+ # and which way it goes, we now have to decide
1727
+ # which quadrant is now the left one and which is
1728
+ # the right one.
1729
+ if d_i < 0:
1730
+ if goes_out:
1731
+ left_quadrant = 1
1732
+ right_quadrant = 0
1733
+ else:
1734
+ left_quadrant = 0
1735
+ right_quadrant = 1
1736
+ else:
1737
+ if goes_out:
1738
+ left_quadrant = 3
1739
+ right_quadrant = 2
1740
+ else:
1741
+ left_quadrant = 2
1742
+ right_quadrant = 3
1743
+
1744
+ if m_curving:
1745
+ if m_curving == "^":
1746
+ quadrant[left_quadrant] += 1
1747
+ elif m_curving == "_":
1748
+ quadrant[right_quadrant] += 1
1749
+ else:
1750
+ # This morphism counts in both upper and lower
1751
+ # quadrants.
1752
+ quadrant[left_quadrant] += 1
1753
+ quadrant[right_quadrant] += 1
1754
+
1755
+ # Pick the freest quadrant to curve our morphism into.
1756
+ freest_quadrant = 0
1757
+ for i in range(4):
1758
+ if quadrant[i] < quadrant[freest_quadrant]:
1759
+ freest_quadrant = i
1760
+
1761
+ # Now set up proper looping.
1762
+ (looping_start, looping_end) = [("r", "u"), ("u", "l"), ("l", "d"),
1763
+ ("d", "r")][freest_quadrant]
1764
+
1765
+ return (curving, label_pos, looping_start, looping_end)
1766
+
1767
+ @staticmethod
1768
+ def _process_horizontal_morphism(i, j, target_j, grid, morphisms_str_info,
1769
+ object_coords):
1770
+ """
1771
+ Produces the information required for constructing the string
1772
+ representation of a horizontal morphism. This function is
1773
+ invoked from ``_process_morphism``.
1774
+
1775
+ See Also
1776
+ ========
1777
+
1778
+ _process_morphism
1779
+ """
1780
+ # The arrow is horizontal. Check if it goes from left to
1781
+ # right (``backwards == False``) or from right to left
1782
+ # (``backwards == True``).
1783
+ backwards = False
1784
+ start = j
1785
+ end = target_j
1786
+ if end < start:
1787
+ (start, end) = (end, start)
1788
+ backwards = True
1789
+
1790
+ # Let's see which objects are there between ``start`` and
1791
+ # ``end``, and then count how many morphisms stick out
1792
+ # upwards, and how many stick out downwards.
1793
+ #
1794
+ # For example, consider the situation:
1795
+ #
1796
+ # B1 C1
1797
+ # | |
1798
+ # A--B--C--D
1799
+ # |
1800
+ # B2
1801
+ #
1802
+ # Between the objects `A` and `D` there are two objects:
1803
+ # `B` and `C`. Further, there are two morphisms which
1804
+ # stick out upward (the ones between `B1` and `B` and
1805
+ # between `C` and `C1`) and one morphism which sticks out
1806
+ # downward (the one between `B and `B2`).
1807
+ #
1808
+ # We need this information to decide how to curve the
1809
+ # arrow between `A` and `D`. First of all, since there
1810
+ # are two objects between `A` and `D``, we must curve the
1811
+ # arrow. Then, we will have it curve downward, because
1812
+ # there is more space (less morphisms stick out downward
1813
+ # than upward).
1814
+ up = []
1815
+ down = []
1816
+ straight_horizontal = []
1817
+ for k in range(start + 1, end):
1818
+ obj = grid[i, k]
1819
+ if not obj:
1820
+ continue
1821
+
1822
+ for m in morphisms_str_info:
1823
+ if m.domain == obj:
1824
+ (end_i, end_j) = object_coords[m.codomain]
1825
+ elif m.codomain == obj:
1826
+ (end_i, end_j) = object_coords[m.domain]
1827
+ else:
1828
+ continue
1829
+
1830
+ if end_i > i:
1831
+ down.append(m)
1832
+ elif end_i < i:
1833
+ up.append(m)
1834
+ elif not morphisms_str_info[m].curving:
1835
+ # This is a straight horizontal morphism,
1836
+ # because it has no curving.
1837
+ straight_horizontal.append(m)
1838
+
1839
+ if len(up) < len(down):
1840
+ # More morphisms stick out downward than upward, let's
1841
+ # curve the morphism up.
1842
+ if backwards:
1843
+ curving = "_"
1844
+ label_pos = "_"
1845
+ else:
1846
+ curving = "^"
1847
+ label_pos = "^"
1848
+
1849
+ # Assure that the straight horizontal morphisms have
1850
+ # their labels on the lower side of the arrow.
1851
+ for m in straight_horizontal:
1852
+ (i1, j1) = object_coords[m.domain]
1853
+ (i2, j2) = object_coords[m.codomain]
1854
+
1855
+ m_str_info = morphisms_str_info[m]
1856
+ if j1 < j2:
1857
+ m_str_info.label_position = "_"
1858
+ else:
1859
+ m_str_info.label_position = "^"
1860
+
1861
+ # Don't allow any further modifications of the
1862
+ # position of this label.
1863
+ m_str_info.forced_label_position = True
1864
+ else:
1865
+ # More morphisms stick out downward than upward, let's
1866
+ # curve the morphism up.
1867
+ if backwards:
1868
+ curving = "^"
1869
+ label_pos = "^"
1870
+ else:
1871
+ curving = "_"
1872
+ label_pos = "_"
1873
+
1874
+ # Assure that the straight horizontal morphisms have
1875
+ # their labels on the upper side of the arrow.
1876
+ for m in straight_horizontal:
1877
+ (i1, j1) = object_coords[m.domain]
1878
+ (i2, j2) = object_coords[m.codomain]
1879
+
1880
+ m_str_info = morphisms_str_info[m]
1881
+ if j1 < j2:
1882
+ m_str_info.label_position = "^"
1883
+ else:
1884
+ m_str_info.label_position = "_"
1885
+
1886
+ # Don't allow any further modifications of the
1887
+ # position of this label.
1888
+ m_str_info.forced_label_position = True
1889
+
1890
+ return (curving, label_pos)
1891
+
1892
+ @staticmethod
1893
+ def _process_vertical_morphism(i, j, target_i, grid, morphisms_str_info,
1894
+ object_coords):
1895
+ """
1896
+ Produces the information required for constructing the string
1897
+ representation of a vertical morphism. This function is
1898
+ invoked from ``_process_morphism``.
1899
+
1900
+ See Also
1901
+ ========
1902
+
1903
+ _process_morphism
1904
+ """
1905
+ # This arrow is vertical. Check if it goes from top to
1906
+ # bottom (``backwards == False``) or from bottom to top
1907
+ # (``backwards == True``).
1908
+ backwards = False
1909
+ start = i
1910
+ end = target_i
1911
+ if end < start:
1912
+ (start, end) = (end, start)
1913
+ backwards = True
1914
+
1915
+ # Let's see which objects are there between ``start`` and
1916
+ # ``end``, and then count how many morphisms stick out to
1917
+ # the left, and how many stick out to the right.
1918
+ #
1919
+ # See the corresponding comment in the previous branch of
1920
+ # this if-statement for more details.
1921
+ left = []
1922
+ right = []
1923
+ straight_vertical = []
1924
+ for k in range(start + 1, end):
1925
+ obj = grid[k, j]
1926
+ if not obj:
1927
+ continue
1928
+
1929
+ for m in morphisms_str_info:
1930
+ if m.domain == obj:
1931
+ (end_i, end_j) = object_coords[m.codomain]
1932
+ elif m.codomain == obj:
1933
+ (end_i, end_j) = object_coords[m.domain]
1934
+ else:
1935
+ continue
1936
+
1937
+ if end_j > j:
1938
+ right.append(m)
1939
+ elif end_j < j:
1940
+ left.append(m)
1941
+ elif not morphisms_str_info[m].curving:
1942
+ # This is a straight vertical morphism,
1943
+ # because it has no curving.
1944
+ straight_vertical.append(m)
1945
+
1946
+ if len(left) < len(right):
1947
+ # More morphisms stick out to the left than to the
1948
+ # right, let's curve the morphism to the right.
1949
+ if backwards:
1950
+ curving = "^"
1951
+ label_pos = "^"
1952
+ else:
1953
+ curving = "_"
1954
+ label_pos = "_"
1955
+
1956
+ # Assure that the straight vertical morphisms have
1957
+ # their labels on the left side of the arrow.
1958
+ for m in straight_vertical:
1959
+ (i1, j1) = object_coords[m.domain]
1960
+ (i2, j2) = object_coords[m.codomain]
1961
+
1962
+ m_str_info = morphisms_str_info[m]
1963
+ if i1 < i2:
1964
+ m_str_info.label_position = "^"
1965
+ else:
1966
+ m_str_info.label_position = "_"
1967
+
1968
+ # Don't allow any further modifications of the
1969
+ # position of this label.
1970
+ m_str_info.forced_label_position = True
1971
+ else:
1972
+ # More morphisms stick out to the right than to the
1973
+ # left, let's curve the morphism to the left.
1974
+ if backwards:
1975
+ curving = "_"
1976
+ label_pos = "_"
1977
+ else:
1978
+ curving = "^"
1979
+ label_pos = "^"
1980
+
1981
+ # Assure that the straight vertical morphisms have
1982
+ # their labels on the right side of the arrow.
1983
+ for m in straight_vertical:
1984
+ (i1, j1) = object_coords[m.domain]
1985
+ (i2, j2) = object_coords[m.codomain]
1986
+
1987
+ m_str_info = morphisms_str_info[m]
1988
+ if i1 < i2:
1989
+ m_str_info.label_position = "_"
1990
+ else:
1991
+ m_str_info.label_position = "^"
1992
+
1993
+ # Don't allow any further modifications of the
1994
+ # position of this label.
1995
+ m_str_info.forced_label_position = True
1996
+
1997
+ return (curving, label_pos)
1998
+
1999
+ def _process_morphism(self, diagram, grid, morphism, object_coords,
2000
+ morphisms, morphisms_str_info):
2001
+ """
2002
+ Given the required information, produces the string
2003
+ representation of ``morphism``.
2004
+ """
2005
+ def repeat_string_cond(times, str_gt, str_lt):
2006
+ """
2007
+ If ``times > 0``, repeats ``str_gt`` ``times`` times.
2008
+ Otherwise, repeats ``str_lt`` ``-times`` times.
2009
+ """
2010
+ if times > 0:
2011
+ return str_gt * times
2012
+ else:
2013
+ return str_lt * (-times)
2014
+
2015
+ def count_morphisms_undirected(A, B):
2016
+ """
2017
+ Counts how many processed morphisms there are between the
2018
+ two supplied objects.
2019
+ """
2020
+ return len([m for m in morphisms_str_info
2021
+ if {m.domain, m.codomain} == {A, B}])
2022
+
2023
+ def count_morphisms_filtered(dom, cod, curving):
2024
+ """
2025
+ Counts the processed morphisms which go out of ``dom``
2026
+ into ``cod`` with curving ``curving``.
2027
+ """
2028
+ return len([m for m, m_str_info in morphisms_str_info.items()
2029
+ if (m.domain, m.codomain) == (dom, cod) and
2030
+ (m_str_info.curving == curving)])
2031
+
2032
+ (i, j) = object_coords[morphism.domain]
2033
+ (target_i, target_j) = object_coords[morphism.codomain]
2034
+
2035
+ # We now need to determine the direction of
2036
+ # the arrow.
2037
+ delta_i = target_i - i
2038
+ delta_j = target_j - j
2039
+ vertical_direction = repeat_string_cond(delta_i,
2040
+ "d", "u")
2041
+ horizontal_direction = repeat_string_cond(delta_j,
2042
+ "r", "l")
2043
+
2044
+ curving = ""
2045
+ label_pos = "^"
2046
+ looping_start = ""
2047
+ looping_end = ""
2048
+
2049
+ if (delta_i == 0) and (delta_j == 0):
2050
+ # This is a loop morphism.
2051
+ (curving, label_pos, looping_start,
2052
+ looping_end) = XypicDiagramDrawer._process_loop_morphism(
2053
+ i, j, grid, morphisms_str_info, object_coords)
2054
+ elif (delta_i == 0) and (abs(j - target_j) > 1):
2055
+ # This is a horizontal morphism.
2056
+ (curving, label_pos) = XypicDiagramDrawer._process_horizontal_morphism(
2057
+ i, j, target_j, grid, morphisms_str_info, object_coords)
2058
+ elif (delta_j == 0) and (abs(i - target_i) > 1):
2059
+ # This is a vertical morphism.
2060
+ (curving, label_pos) = XypicDiagramDrawer._process_vertical_morphism(
2061
+ i, j, target_i, grid, morphisms_str_info, object_coords)
2062
+
2063
+ count = count_morphisms_undirected(morphism.domain, morphism.codomain)
2064
+ curving_amount = ""
2065
+ if curving:
2066
+ # This morphisms should be curved anyway.
2067
+ curving_amount = self.default_curving_amount + count * \
2068
+ self.default_curving_step
2069
+ elif count:
2070
+ # There are no objects between the domain and codomain of
2071
+ # the current morphism, but this is not there already are
2072
+ # some morphisms with the same domain and codomain, so we
2073
+ # have to curve this one.
2074
+ curving = "^"
2075
+ filtered_morphisms = count_morphisms_filtered(
2076
+ morphism.domain, morphism.codomain, curving)
2077
+ curving_amount = self.default_curving_amount + \
2078
+ filtered_morphisms * \
2079
+ self.default_curving_step
2080
+
2081
+ # Let's now get the name of the morphism.
2082
+ morphism_name = ""
2083
+ if isinstance(morphism, IdentityMorphism):
2084
+ morphism_name = "id_{%s}" + latex(grid[i, j])
2085
+ elif isinstance(morphism, CompositeMorphism):
2086
+ component_names = [latex(Symbol(component.name)) for
2087
+ component in morphism.components]
2088
+ component_names.reverse()
2089
+ morphism_name = "\\circ ".join(component_names)
2090
+ elif isinstance(morphism, NamedMorphism):
2091
+ morphism_name = latex(Symbol(morphism.name))
2092
+
2093
+ return ArrowStringDescription(
2094
+ self.unit, curving, curving_amount, looping_start,
2095
+ looping_end, horizontal_direction, vertical_direction,
2096
+ label_pos, morphism_name)
2097
+
2098
+ @staticmethod
2099
+ def _check_free_space_horizontal(dom_i, dom_j, cod_j, grid):
2100
+ """
2101
+ For a horizontal morphism, checks whether there is free space
2102
+ (i.e., space not occupied by any objects) above the morphism
2103
+ or below it.
2104
+ """
2105
+ if dom_j < cod_j:
2106
+ (start, end) = (dom_j, cod_j)
2107
+ backwards = False
2108
+ else:
2109
+ (start, end) = (cod_j, dom_j)
2110
+ backwards = True
2111
+
2112
+ # Check for free space above.
2113
+ if dom_i == 0:
2114
+ free_up = True
2115
+ else:
2116
+ free_up = all(grid[dom_i - 1, j] for j in
2117
+ range(start, end + 1))
2118
+
2119
+ # Check for free space below.
2120
+ if dom_i == grid.height - 1:
2121
+ free_down = True
2122
+ else:
2123
+ free_down = not any(grid[dom_i + 1, j] for j in
2124
+ range(start, end + 1))
2125
+
2126
+ return (free_up, free_down, backwards)
2127
+
2128
+ @staticmethod
2129
+ def _check_free_space_vertical(dom_i, cod_i, dom_j, grid):
2130
+ """
2131
+ For a vertical morphism, checks whether there is free space
2132
+ (i.e., space not occupied by any objects) to the left of the
2133
+ morphism or to the right of it.
2134
+ """
2135
+ if dom_i < cod_i:
2136
+ (start, end) = (dom_i, cod_i)
2137
+ backwards = False
2138
+ else:
2139
+ (start, end) = (cod_i, dom_i)
2140
+ backwards = True
2141
+
2142
+ # Check if there's space to the left.
2143
+ if dom_j == 0:
2144
+ free_left = True
2145
+ else:
2146
+ free_left = not any(grid[i, dom_j - 1] for i in
2147
+ range(start, end + 1))
2148
+
2149
+ if dom_j == grid.width - 1:
2150
+ free_right = True
2151
+ else:
2152
+ free_right = not any(grid[i, dom_j + 1] for i in
2153
+ range(start, end + 1))
2154
+
2155
+ return (free_left, free_right, backwards)
2156
+
2157
+ @staticmethod
2158
+ def _check_free_space_diagonal(dom_i, cod_i, dom_j, cod_j, grid):
2159
+ """
2160
+ For a diagonal morphism, checks whether there is free space
2161
+ (i.e., space not occupied by any objects) above the morphism
2162
+ or below it.
2163
+ """
2164
+ def abs_xrange(start, end):
2165
+ if start < end:
2166
+ return range(start, end + 1)
2167
+ else:
2168
+ return range(end, start + 1)
2169
+
2170
+ if dom_i < cod_i and dom_j < cod_j:
2171
+ # This morphism goes from top-left to
2172
+ # bottom-right.
2173
+ (start_i, start_j) = (dom_i, dom_j)
2174
+ (end_i, end_j) = (cod_i, cod_j)
2175
+ backwards = False
2176
+ elif dom_i > cod_i and dom_j > cod_j:
2177
+ # This morphism goes from bottom-right to
2178
+ # top-left.
2179
+ (start_i, start_j) = (cod_i, cod_j)
2180
+ (end_i, end_j) = (dom_i, dom_j)
2181
+ backwards = True
2182
+ if dom_i < cod_i and dom_j > cod_j:
2183
+ # This morphism goes from top-right to
2184
+ # bottom-left.
2185
+ (start_i, start_j) = (dom_i, dom_j)
2186
+ (end_i, end_j) = (cod_i, cod_j)
2187
+ backwards = True
2188
+ elif dom_i > cod_i and dom_j < cod_j:
2189
+ # This morphism goes from bottom-left to
2190
+ # top-right.
2191
+ (start_i, start_j) = (cod_i, cod_j)
2192
+ (end_i, end_j) = (dom_i, dom_j)
2193
+ backwards = False
2194
+
2195
+ # This is an attempt at a fast and furious strategy to
2196
+ # decide where there is free space on the two sides of
2197
+ # a diagonal morphism. For a diagonal morphism
2198
+ # starting at ``(start_i, start_j)`` and ending at
2199
+ # ``(end_i, end_j)`` the rectangle defined by these
2200
+ # two points is considered. The slope of the diagonal
2201
+ # ``alpha`` is then computed. Then, for every cell
2202
+ # ``(i, j)`` within the rectangle, the slope
2203
+ # ``alpha1`` of the line through ``(start_i,
2204
+ # start_j)`` and ``(i, j)`` is considered. If
2205
+ # ``alpha1`` is between 0 and ``alpha``, the point
2206
+ # ``(i, j)`` is above the diagonal, if ``alpha1`` is
2207
+ # between ``alpha`` and infinity, the point is below
2208
+ # the diagonal. Also note that, with some beforehand
2209
+ # precautions, this trick works for both the main and
2210
+ # the secondary diagonals of the rectangle.
2211
+
2212
+ # I have considered the possibility to only follow the
2213
+ # shorter diagonals immediately above and below the
2214
+ # main (or secondary) diagonal. This, however,
2215
+ # wouldn't have resulted in much performance gain or
2216
+ # better detection of outer edges, because of
2217
+ # relatively small sizes of diagram grids, while the
2218
+ # code would have become harder to understand.
2219
+
2220
+ alpha = float(end_i - start_i)/(end_j - start_j)
2221
+ free_up = True
2222
+ free_down = True
2223
+ for i in abs_xrange(start_i, end_i):
2224
+ if not free_up and not free_down:
2225
+ break
2226
+
2227
+ for j in abs_xrange(start_j, end_j):
2228
+ if not free_up and not free_down:
2229
+ break
2230
+
2231
+ if (i, j) == (start_i, start_j):
2232
+ continue
2233
+
2234
+ if j == start_j:
2235
+ alpha1 = "inf"
2236
+ else:
2237
+ alpha1 = float(i - start_i)/(j - start_j)
2238
+
2239
+ if grid[i, j]:
2240
+ if (alpha1 == "inf") or (abs(alpha1) > abs(alpha)):
2241
+ free_down = False
2242
+ elif abs(alpha1) < abs(alpha):
2243
+ free_up = False
2244
+
2245
+ return (free_up, free_down, backwards)
2246
+
2247
+ def _push_labels_out(self, morphisms_str_info, grid, object_coords):
2248
+ """
2249
+ For all straight morphisms which form the visual boundary of
2250
+ the laid out diagram, puts their labels on their outer sides.
2251
+ """
2252
+ def set_label_position(free1, free2, pos1, pos2, backwards, m_str_info):
2253
+ """
2254
+ Given the information about room available to one side and
2255
+ to the other side of a morphism (``free1`` and ``free2``),
2256
+ sets the position of the morphism label in such a way that
2257
+ it is on the freer side. This latter operations involves
2258
+ choice between ``pos1`` and ``pos2``, taking ``backwards``
2259
+ in consideration.
2260
+
2261
+ Thus this function will do nothing if either both ``free1
2262
+ == True`` and ``free2 == True`` or both ``free1 == False``
2263
+ and ``free2 == False``. In either case, choosing one side
2264
+ over the other presents no advantage.
2265
+ """
2266
+ if backwards:
2267
+ (pos1, pos2) = (pos2, pos1)
2268
+
2269
+ if free1 and not free2:
2270
+ m_str_info.label_position = pos1
2271
+ elif free2 and not free1:
2272
+ m_str_info.label_position = pos2
2273
+
2274
+ for m, m_str_info in morphisms_str_info.items():
2275
+ if m_str_info.curving or m_str_info.forced_label_position:
2276
+ # This is either a curved morphism, and curved
2277
+ # morphisms have other magic, or the position of this
2278
+ # label has already been fixed.
2279
+ continue
2280
+
2281
+ if m.domain == m.codomain:
2282
+ # This is a loop morphism, their labels, again have a
2283
+ # different magic.
2284
+ continue
2285
+
2286
+ (dom_i, dom_j) = object_coords[m.domain]
2287
+ (cod_i, cod_j) = object_coords[m.codomain]
2288
+
2289
+ if dom_i == cod_i:
2290
+ # Horizontal morphism.
2291
+ (free_up, free_down,
2292
+ backwards) = XypicDiagramDrawer._check_free_space_horizontal(
2293
+ dom_i, dom_j, cod_j, grid)
2294
+
2295
+ set_label_position(free_up, free_down, "^", "_",
2296
+ backwards, m_str_info)
2297
+ elif dom_j == cod_j:
2298
+ # Vertical morphism.
2299
+ (free_left, free_right,
2300
+ backwards) = XypicDiagramDrawer._check_free_space_vertical(
2301
+ dom_i, cod_i, dom_j, grid)
2302
+
2303
+ set_label_position(free_left, free_right, "_", "^",
2304
+ backwards, m_str_info)
2305
+ else:
2306
+ # A diagonal morphism.
2307
+ (free_up, free_down,
2308
+ backwards) = XypicDiagramDrawer._check_free_space_diagonal(
2309
+ dom_i, cod_i, dom_j, cod_j, grid)
2310
+
2311
+ set_label_position(free_up, free_down, "^", "_",
2312
+ backwards, m_str_info)
2313
+
2314
+ @staticmethod
2315
+ def _morphism_sort_key(morphism, object_coords):
2316
+ """
2317
+ Provides a morphism sorting key such that horizontal or
2318
+ vertical morphisms between neighbouring objects come
2319
+ first, then horizontal or vertical morphisms between more
2320
+ far away objects, and finally, all other morphisms.
2321
+ """
2322
+ (i, j) = object_coords[morphism.domain]
2323
+ (target_i, target_j) = object_coords[morphism.codomain]
2324
+
2325
+ if morphism.domain == morphism.codomain:
2326
+ # Loop morphisms should get after diagonal morphisms
2327
+ # so that the proper direction in which to curve the
2328
+ # loop can be determined.
2329
+ return (3, 0, default_sort_key(morphism))
2330
+
2331
+ if target_i == i:
2332
+ return (1, abs(target_j - j), default_sort_key(morphism))
2333
+
2334
+ if target_j == j:
2335
+ return (1, abs(target_i - i), default_sort_key(morphism))
2336
+
2337
+ # Diagonal morphism.
2338
+ return (2, 0, default_sort_key(morphism))
2339
+
2340
+ @staticmethod
2341
+ def _build_xypic_string(diagram, grid, morphisms,
2342
+ morphisms_str_info, diagram_format):
2343
+ """
2344
+ Given a collection of :class:`ArrowStringDescription`
2345
+ describing the morphisms of a diagram and the object layout
2346
+ information of a diagram, produces the final Xy-pic picture.
2347
+ """
2348
+ # Build the mapping between objects and morphisms which have
2349
+ # them as domains.
2350
+ object_morphisms = {}
2351
+ for obj in diagram.objects:
2352
+ object_morphisms[obj] = []
2353
+ for morphism in morphisms:
2354
+ object_morphisms[morphism.domain].append(morphism)
2355
+
2356
+ result = "\\xymatrix%s{\n" % diagram_format
2357
+
2358
+ for i in range(grid.height):
2359
+ for j in range(grid.width):
2360
+ obj = grid[i, j]
2361
+ if obj:
2362
+ result += latex(obj) + " "
2363
+
2364
+ morphisms_to_draw = object_morphisms[obj]
2365
+ for morphism in morphisms_to_draw:
2366
+ result += str(morphisms_str_info[morphism]) + " "
2367
+
2368
+ # Don't put the & after the last column.
2369
+ if j < grid.width - 1:
2370
+ result += "& "
2371
+
2372
+ # Don't put the line break after the last row.
2373
+ if i < grid.height - 1:
2374
+ result += "\\\\"
2375
+ result += "\n"
2376
+
2377
+ result += "}\n"
2378
+
2379
+ return result
2380
+
2381
+ def draw(self, diagram, grid, masked=None, diagram_format=""):
2382
+ r"""
2383
+ Returns the Xy-pic representation of ``diagram`` laid out in
2384
+ ``grid``.
2385
+
2386
+ Consider the following simple triangle diagram.
2387
+
2388
+ >>> from sympy.categories import Object, NamedMorphism, Diagram
2389
+ >>> from sympy.categories import DiagramGrid, XypicDiagramDrawer
2390
+ >>> A = Object("A")
2391
+ >>> B = Object("B")
2392
+ >>> C = Object("C")
2393
+ >>> f = NamedMorphism(A, B, "f")
2394
+ >>> g = NamedMorphism(B, C, "g")
2395
+ >>> diagram = Diagram([f, g], {g * f: "unique"})
2396
+
2397
+ To draw this diagram, its objects need to be laid out with a
2398
+ :class:`DiagramGrid`::
2399
+
2400
+ >>> grid = DiagramGrid(diagram)
2401
+
2402
+ Finally, the drawing:
2403
+
2404
+ >>> drawer = XypicDiagramDrawer()
2405
+ >>> print(drawer.draw(diagram, grid))
2406
+ \xymatrix{
2407
+ A \ar[d]_{g\circ f} \ar[r]^{f} & B \ar[ld]^{g} \\
2408
+ C &
2409
+ }
2410
+
2411
+ The argument ``masked`` can be used to skip morphisms in the
2412
+ presentation of the diagram:
2413
+
2414
+ >>> print(drawer.draw(diagram, grid, masked=[g * f]))
2415
+ \xymatrix{
2416
+ A \ar[r]^{f} & B \ar[ld]^{g} \\
2417
+ C &
2418
+ }
2419
+
2420
+ Finally, the ``diagram_format`` argument can be used to
2421
+ specify the format string of the diagram. For example, to
2422
+ increase the spacing by 1 cm, proceeding as follows:
2423
+
2424
+ >>> print(drawer.draw(diagram, grid, diagram_format="@+1cm"))
2425
+ \xymatrix@+1cm{
2426
+ A \ar[d]_{g\circ f} \ar[r]^{f} & B \ar[ld]^{g} \\
2427
+ C &
2428
+ }
2429
+
2430
+ """
2431
+ # This method works in several steps. It starts by removing
2432
+ # the masked morphisms, if necessary, and then maps objects to
2433
+ # their positions in the grid (coordinate tuples). Remember
2434
+ # that objects are unique in ``Diagram`` and in the layout
2435
+ # produced by ``DiagramGrid``, so every object is mapped to a
2436
+ # single coordinate pair.
2437
+ #
2438
+ # The next step is the central step and is concerned with
2439
+ # analysing the morphisms of the diagram and deciding how to
2440
+ # draw them. For example, how to curve the arrows is decided
2441
+ # at this step. The bulk of the analysis is implemented in
2442
+ # ``_process_morphism``, to the result of which the
2443
+ # appropriate formatters are applied.
2444
+ #
2445
+ # The result of the previous step is a list of
2446
+ # ``ArrowStringDescription``. After the analysis and
2447
+ # application of formatters, some extra logic tries to assure
2448
+ # better positioning of morphism labels (for example, an
2449
+ # attempt is made to avoid the situations when arrows cross
2450
+ # labels). This functionality constitutes the next step and
2451
+ # is implemented in ``_push_labels_out``. Note that label
2452
+ # positions which have been set via a formatter are not
2453
+ # affected in this step.
2454
+ #
2455
+ # Finally, at the closing step, the array of
2456
+ # ``ArrowStringDescription`` and the layout information
2457
+ # incorporated in ``DiagramGrid`` are combined to produce the
2458
+ # resulting Xy-pic picture. This part of code lies in
2459
+ # ``_build_xypic_string``.
2460
+
2461
+ if not masked:
2462
+ morphisms_props = grid.morphisms
2463
+ else:
2464
+ morphisms_props = {}
2465
+ for m, props in grid.morphisms.items():
2466
+ if m in masked:
2467
+ continue
2468
+ morphisms_props[m] = props
2469
+
2470
+ # Build the mapping between objects and their position in the
2471
+ # grid.
2472
+ object_coords = {}
2473
+ for i in range(grid.height):
2474
+ for j in range(grid.width):
2475
+ if grid[i, j]:
2476
+ object_coords[grid[i, j]] = (i, j)
2477
+
2478
+ morphisms = sorted(morphisms_props,
2479
+ key=lambda m: XypicDiagramDrawer._morphism_sort_key(
2480
+ m, object_coords))
2481
+
2482
+ # Build the tuples defining the string representations of
2483
+ # morphisms.
2484
+ morphisms_str_info = {}
2485
+ for morphism in morphisms:
2486
+ string_description = self._process_morphism(
2487
+ diagram, grid, morphism, object_coords, morphisms,
2488
+ morphisms_str_info)
2489
+
2490
+ if self.default_arrow_formatter:
2491
+ self.default_arrow_formatter(string_description)
2492
+
2493
+ for prop in morphisms_props[morphism]:
2494
+ # prop is a Symbol. TODO: Find out why.
2495
+ if prop.name in self.arrow_formatters:
2496
+ formatter = self.arrow_formatters[prop.name]
2497
+ formatter(string_description)
2498
+
2499
+ morphisms_str_info[morphism] = string_description
2500
+
2501
+ # Reposition the labels a bit.
2502
+ self._push_labels_out(morphisms_str_info, grid, object_coords)
2503
+
2504
+ return XypicDiagramDrawer._build_xypic_string(
2505
+ diagram, grid, morphisms, morphisms_str_info, diagram_format)
2506
+
2507
+
2508
+ def xypic_draw_diagram(diagram, masked=None, diagram_format="",
2509
+ groups=None, **hints):
2510
+ r"""
2511
+ Provides a shortcut combining :class:`DiagramGrid` and
2512
+ :class:`XypicDiagramDrawer`. Returns an Xy-pic presentation of
2513
+ ``diagram``. The argument ``masked`` is a list of morphisms which
2514
+ will be not be drawn. The argument ``diagram_format`` is the
2515
+ format string inserted after "\xymatrix". ``groups`` should be a
2516
+ set of logical groups. The ``hints`` will be passed directly to
2517
+ the constructor of :class:`DiagramGrid`.
2518
+
2519
+ For more information about the arguments, see the docstrings of
2520
+ :class:`DiagramGrid` and ``XypicDiagramDrawer.draw``.
2521
+
2522
+ Examples
2523
+ ========
2524
+
2525
+ >>> from sympy.categories import Object, NamedMorphism, Diagram
2526
+ >>> from sympy.categories import xypic_draw_diagram
2527
+ >>> A = Object("A")
2528
+ >>> B = Object("B")
2529
+ >>> C = Object("C")
2530
+ >>> f = NamedMorphism(A, B, "f")
2531
+ >>> g = NamedMorphism(B, C, "g")
2532
+ >>> diagram = Diagram([f, g], {g * f: "unique"})
2533
+ >>> print(xypic_draw_diagram(diagram))
2534
+ \xymatrix{
2535
+ A \ar[d]_{g\circ f} \ar[r]^{f} & B \ar[ld]^{g} \\
2536
+ C &
2537
+ }
2538
+
2539
+ See Also
2540
+ ========
2541
+
2542
+ XypicDiagramDrawer, DiagramGrid
2543
+ """
2544
+ grid = DiagramGrid(diagram, groups, **hints)
2545
+ drawer = XypicDiagramDrawer()
2546
+ return drawer.draw(diagram, grid, masked, diagram_format)
2547
+
2548
+
2549
+ @doctest_depends_on(exe=('latex', 'dvipng'), modules=('pyglet',))
2550
+ def preview_diagram(diagram, masked=None, diagram_format="", groups=None,
2551
+ output='png', viewer=None, euler=True, **hints):
2552
+ """
2553
+ Combines the functionality of ``xypic_draw_diagram`` and
2554
+ ``sympy.printing.preview``. The arguments ``masked``,
2555
+ ``diagram_format``, ``groups``, and ``hints`` are passed to
2556
+ ``xypic_draw_diagram``, while ``output``, ``viewer, and ``euler``
2557
+ are passed to ``preview``.
2558
+
2559
+ Examples
2560
+ ========
2561
+
2562
+ >>> from sympy.categories import Object, NamedMorphism, Diagram
2563
+ >>> from sympy.categories import preview_diagram
2564
+ >>> A = Object("A")
2565
+ >>> B = Object("B")
2566
+ >>> C = Object("C")
2567
+ >>> f = NamedMorphism(A, B, "f")
2568
+ >>> g = NamedMorphism(B, C, "g")
2569
+ >>> d = Diagram([f, g], {g * f: "unique"})
2570
+ >>> preview_diagram(d)
2571
+
2572
+ See Also
2573
+ ========
2574
+
2575
+ XypicDiagramDrawer
2576
+ """
2577
+ from sympy.printing import preview
2578
+ latex_output = xypic_draw_diagram(diagram, masked, diagram_format,
2579
+ groups, **hints)
2580
+ preview(latex_output, output, viewer, euler, ("xypic",))
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/categories/tests/__init__.py ADDED
File without changes
miniconda3/envs/active_proaction/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(""))
miniconda3/envs/active_proaction/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")
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/codegen/__init__.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ The ``sympy.codegen`` module contains classes and functions for building
2
+ abstract syntax trees of algorithms. These trees may then be printed by the
3
+ code-printers in ``sympy.printing``.
4
+
5
+ There are several submodules available:
6
+ - ``sympy.codegen.ast``: AST nodes useful across multiple languages.
7
+ - ``sympy.codegen.cnodes``: AST nodes useful for the C family of languages.
8
+ - ``sympy.codegen.fnodes``: AST nodes useful for Fortran.
9
+ - ``sympy.codegen.cfunctions``: functions specific to C (C99 math functions)
10
+ - ``sympy.codegen.ffunctions``: functions specific to Fortran (e.g. ``kind``).
11
+
12
+
13
+
14
+ """
15
+ from .ast import (
16
+ Assignment, aug_assign, CodeBlock, For, Attribute, Variable, Declaration,
17
+ While, Scope, Print, FunctionPrototype, FunctionDefinition, FunctionCall
18
+ )
19
+
20
+ __all__ = [
21
+ 'Assignment', 'aug_assign', 'CodeBlock', 'For', 'Attribute', 'Variable',
22
+ 'Declaration', 'While', 'Scope', 'Print', 'FunctionPrototype',
23
+ 'FunctionDefinition', 'FunctionCall',
24
+ ]
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sympy/codegen/abstract_nodes.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """This module provides containers for python objects that are valid
2
+ printing targets but are not a subclass of SymPy's Printable.
3
+ """
4
+
5
+
6
+ from sympy.core.containers import Tuple
7
+
8
+
9
+ class List(Tuple):
10
+ """Represents a (frozen) (Python) list (for code printing purposes)."""
11
+ def __eq__(self, other):
12
+ if isinstance(other, list):
13
+ return self == List(*other)
14
+ else:
15
+ return self.args == other
16
+
17
+ def __hash__(self):
18
+ return super().__hash__()