applied-ai-018 commited on
Commit
e94ff2e
·
verified ·
1 Parent(s): 1e44f68

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. ckpts/universal/global_step80/zero/13.mlp.dense_h_to_4h_swiglu.weight/exp_avg_sq.pt +3 -0
  2. ckpts/universal/global_step80/zero/14.attention.query_key_value.weight/exp_avg_sq.pt +3 -0
  3. ckpts/universal/global_step80/zero/19.mlp.dense_h_to_4h_swiglu.weight/exp_avg.pt +3 -0
  4. ckpts/universal/global_step80/zero/19.mlp.dense_h_to_4h_swiglu.weight/fp32.pt +3 -0
  5. ckpts/universal/global_step80/zero/22.attention.dense.weight/exp_avg_sq.pt +3 -0
  6. ckpts/universal/global_step80/zero/22.attention.dense.weight/fp32.pt +3 -0
  7. venv/lib/python3.10/site-packages/sympy/plotting/__pycache__/__init__.cpython-310.pyc +0 -0
  8. venv/lib/python3.10/site-packages/sympy/plotting/__pycache__/experimental_lambdify.cpython-310.pyc +0 -0
  9. venv/lib/python3.10/site-packages/sympy/plotting/__pycache__/plot.cpython-310.pyc +0 -0
  10. venv/lib/python3.10/site-packages/sympy/plotting/__pycache__/plot_implicit.cpython-310.pyc +0 -0
  11. venv/lib/python3.10/site-packages/sympy/plotting/__pycache__/textplot.cpython-310.pyc +0 -0
  12. venv/lib/python3.10/site-packages/sympy/plotting/intervalmath/__init__.py +12 -0
  13. venv/lib/python3.10/site-packages/sympy/plotting/intervalmath/__pycache__/__init__.cpython-310.pyc +0 -0
  14. venv/lib/python3.10/site-packages/sympy/plotting/intervalmath/__pycache__/interval_arithmetic.cpython-310.pyc +0 -0
  15. venv/lib/python3.10/site-packages/sympy/plotting/intervalmath/__pycache__/interval_membership.cpython-310.pyc +0 -0
  16. venv/lib/python3.10/site-packages/sympy/plotting/intervalmath/__pycache__/lib_interval.cpython-310.pyc +0 -0
  17. venv/lib/python3.10/site-packages/sympy/plotting/intervalmath/interval_arithmetic.py +412 -0
  18. venv/lib/python3.10/site-packages/sympy/plotting/intervalmath/interval_membership.py +78 -0
  19. venv/lib/python3.10/site-packages/sympy/plotting/intervalmath/lib_interval.py +452 -0
  20. venv/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/__init__.py +0 -0
  21. venv/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  22. venv/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/__pycache__/test_interval_functions.cpython-310.pyc +0 -0
  23. venv/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/__pycache__/test_interval_membership.cpython-310.pyc +0 -0
  24. venv/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/__pycache__/test_intervalmath.cpython-310.pyc +0 -0
  25. venv/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/test_interval_functions.py +415 -0
  26. venv/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/test_interval_membership.py +150 -0
  27. venv/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/test_intervalmath.py +213 -0
  28. venv/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_camera.cpython-310.pyc +0 -0
  29. venv/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_interval.cpython-310.pyc +0 -0
  30. venv/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_mode.cpython-310.pyc +0 -0
  31. venv/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_mode_base.cpython-310.pyc +0 -0
  32. venv/lib/python3.10/site-packages/sympy/plotting/pygletplot/tests/__init__.py +0 -0
  33. venv/lib/python3.10/site-packages/sympy/plotting/pygletplot/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  34. venv/lib/python3.10/site-packages/sympy/plotting/pygletplot/tests/__pycache__/test_plotting.cpython-310.pyc +0 -0
  35. venv/lib/python3.10/site-packages/sympy/plotting/pygletplot/tests/test_plotting.py +88 -0
  36. venv/lib/python3.10/site-packages/sympy/plotting/tests/__init__.py +0 -0
  37. venv/lib/python3.10/site-packages/sympy/plotting/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  38. venv/lib/python3.10/site-packages/sympy/plotting/tests/__pycache__/test_experimental_lambdify.cpython-310.pyc +0 -0
  39. venv/lib/python3.10/site-packages/sympy/plotting/tests/__pycache__/test_plot.cpython-310.pyc +0 -0
  40. venv/lib/python3.10/site-packages/sympy/plotting/tests/__pycache__/test_plot_implicit.cpython-310.pyc +0 -0
  41. venv/lib/python3.10/site-packages/sympy/plotting/tests/__pycache__/test_textplot.cpython-310.pyc +0 -0
  42. venv/lib/python3.10/site-packages/sympy/plotting/tests/test_experimental_lambdify.py +77 -0
  43. venv/lib/python3.10/site-packages/sympy/plotting/tests/test_plot.py +764 -0
  44. venv/lib/python3.10/site-packages/sympy/plotting/tests/test_plot_implicit.py +146 -0
  45. venv/lib/python3.10/site-packages/sympy/plotting/tests/test_textplot.py +203 -0
  46. venv/lib/python3.10/site-packages/sympy/simplify/__init__.py +60 -0
  47. venv/lib/python3.10/site-packages/sympy/simplify/combsimp.py +114 -0
  48. venv/lib/python3.10/site-packages/sympy/simplify/cse_main.py +946 -0
  49. venv/lib/python3.10/site-packages/sympy/simplify/cse_opts.py +52 -0
  50. venv/lib/python3.10/site-packages/sympy/simplify/epathtools.py +356 -0
ckpts/universal/global_step80/zero/13.mlp.dense_h_to_4h_swiglu.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:597cd4541d8f0b2fd37840754602a4c35a420d3ba2fcd24c852a3038086883f0
3
+ size 33555627
ckpts/universal/global_step80/zero/14.attention.query_key_value.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f84d8647db56b1312df1d15e4dbe30b8d1403786ef6997cc55e21634a1cd7118
3
+ size 50332843
ckpts/universal/global_step80/zero/19.mlp.dense_h_to_4h_swiglu.weight/exp_avg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fdde3bab19c22a9cb9cd103b142b49fe149822d2ded10fbf71ac2f5f636e883d
3
+ size 33555612
ckpts/universal/global_step80/zero/19.mlp.dense_h_to_4h_swiglu.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:edb070ba220debda9741d8c92a21e66d6ee18122af47f8b2e925f32cf4fb4450
3
+ size 33555533
ckpts/universal/global_step80/zero/22.attention.dense.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0173e7bb5be6c9557f5ce406ffb207ce505b16c185e49ebf22d4eee93ed4667a
3
+ size 16778411
ckpts/universal/global_step80/zero/22.attention.dense.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9a0c65c4bef6eee42f21ecc0e7dac08c76ba11d8b407103509576b53edcdbfee
3
+ size 16778317
venv/lib/python3.10/site-packages/sympy/plotting/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (599 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/plotting/__pycache__/experimental_lambdify.cpython-310.pyc ADDED
Binary file (14.3 kB). View file
 
venv/lib/python3.10/site-packages/sympy/plotting/__pycache__/plot.cpython-310.pyc ADDED
Binary file (78.9 kB). View file
 
venv/lib/python3.10/site-packages/sympy/plotting/__pycache__/plot_implicit.cpython-310.pyc ADDED
Binary file (12.9 kB). View file
 
venv/lib/python3.10/site-packages/sympy/plotting/__pycache__/textplot.cpython-310.pyc ADDED
Binary file (4.64 kB). View file
 
venv/lib/python3.10/site-packages/sympy/plotting/intervalmath/__init__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .interval_arithmetic import interval
2
+ from .lib_interval import (Abs, exp, log, log10, sin, cos, tan, sqrt,
3
+ imin, imax, sinh, cosh, tanh, acosh, asinh, atanh,
4
+ asin, acos, atan, ceil, floor, And, Or)
5
+
6
+ __all__ = [
7
+ 'interval',
8
+
9
+ 'Abs', 'exp', 'log', 'log10', 'sin', 'cos', 'tan', 'sqrt', 'imin', 'imax',
10
+ 'sinh', 'cosh', 'tanh', 'acosh', 'asinh', 'atanh', 'asin', 'acos', 'atan',
11
+ 'ceil', 'floor', 'And', 'Or',
12
+ ]
venv/lib/python3.10/site-packages/sympy/plotting/intervalmath/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (755 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/plotting/intervalmath/__pycache__/interval_arithmetic.cpython-310.pyc ADDED
Binary file (9.2 kB). View file
 
venv/lib/python3.10/site-packages/sympy/plotting/intervalmath/__pycache__/interval_membership.cpython-310.pyc ADDED
Binary file (3.07 kB). View file
 
venv/lib/python3.10/site-packages/sympy/plotting/intervalmath/__pycache__/lib_interval.cpython-310.pyc ADDED
Binary file (9.6 kB). View file
 
venv/lib/python3.10/site-packages/sympy/plotting/intervalmath/interval_arithmetic.py ADDED
@@ -0,0 +1,412 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Interval Arithmetic for plotting.
3
+ This module does not implement interval arithmetic accurately and
4
+ hence cannot be used for purposes other than plotting. If you want
5
+ to use interval arithmetic, use mpmath's interval arithmetic.
6
+
7
+ The module implements interval arithmetic using numpy and
8
+ python floating points. The rounding up and down is not handled
9
+ and hence this is not an accurate implementation of interval
10
+ arithmetic.
11
+
12
+ The module uses numpy for speed which cannot be achieved with mpmath.
13
+ """
14
+
15
+ # Q: Why use numpy? Why not simply use mpmath's interval arithmetic?
16
+ # A: mpmath's interval arithmetic simulates a floating point unit
17
+ # and hence is slow, while numpy evaluations are orders of magnitude
18
+ # faster.
19
+
20
+ # Q: Why create a separate class for intervals? Why not use SymPy's
21
+ # Interval Sets?
22
+ # A: The functionalities that will be required for plotting is quite
23
+ # different from what Interval Sets implement.
24
+
25
+ # Q: Why is rounding up and down according to IEEE754 not handled?
26
+ # A: It is not possible to do it in both numpy and python. An external
27
+ # library has to used, which defeats the whole purpose i.e., speed. Also
28
+ # rounding is handled for very few functions in those libraries.
29
+
30
+ # Q Will my plots be affected?
31
+ # A It will not affect most of the plots. The interval arithmetic
32
+ # module based suffers the same problems as that of floating point
33
+ # arithmetic.
34
+
35
+ from sympy.core.logic import fuzzy_and
36
+ from sympy.simplify.simplify import nsimplify
37
+
38
+ from .interval_membership import intervalMembership
39
+
40
+
41
+ class interval:
42
+ """ Represents an interval containing floating points as start and
43
+ end of the interval
44
+ The is_valid variable tracks whether the interval obtained as the
45
+ result of the function is in the domain and is continuous.
46
+ - True: Represents the interval result of a function is continuous and
47
+ in the domain of the function.
48
+ - False: The interval argument of the function was not in the domain of
49
+ the function, hence the is_valid of the result interval is False
50
+ - None: The function was not continuous over the interval or
51
+ the function's argument interval is partly in the domain of the
52
+ function
53
+
54
+ A comparison between an interval and a real number, or a
55
+ comparison between two intervals may return ``intervalMembership``
56
+ of two 3-valued logic values.
57
+ """
58
+
59
+ def __init__(self, *args, is_valid=True, **kwargs):
60
+ self.is_valid = is_valid
61
+ if len(args) == 1:
62
+ if isinstance(args[0], interval):
63
+ self.start, self.end = args[0].start, args[0].end
64
+ else:
65
+ self.start = float(args[0])
66
+ self.end = float(args[0])
67
+ elif len(args) == 2:
68
+ if args[0] < args[1]:
69
+ self.start = float(args[0])
70
+ self.end = float(args[1])
71
+ else:
72
+ self.start = float(args[1])
73
+ self.end = float(args[0])
74
+
75
+ else:
76
+ raise ValueError("interval takes a maximum of two float values "
77
+ "as arguments")
78
+
79
+ @property
80
+ def mid(self):
81
+ return (self.start + self.end) / 2.0
82
+
83
+ @property
84
+ def width(self):
85
+ return self.end - self.start
86
+
87
+ def __repr__(self):
88
+ return "interval(%f, %f)" % (self.start, self.end)
89
+
90
+ def __str__(self):
91
+ return "[%f, %f]" % (self.start, self.end)
92
+
93
+ def __lt__(self, other):
94
+ if isinstance(other, (int, float)):
95
+ if self.end < other:
96
+ return intervalMembership(True, self.is_valid)
97
+ elif self.start > other:
98
+ return intervalMembership(False, self.is_valid)
99
+ else:
100
+ return intervalMembership(None, self.is_valid)
101
+
102
+ elif isinstance(other, interval):
103
+ valid = fuzzy_and([self.is_valid, other.is_valid])
104
+ if self.end < other. start:
105
+ return intervalMembership(True, valid)
106
+ if self.start > other.end:
107
+ return intervalMembership(False, valid)
108
+ return intervalMembership(None, valid)
109
+ else:
110
+ return NotImplemented
111
+
112
+ def __gt__(self, other):
113
+ if isinstance(other, (int, float)):
114
+ if self.start > other:
115
+ return intervalMembership(True, self.is_valid)
116
+ elif self.end < other:
117
+ return intervalMembership(False, self.is_valid)
118
+ else:
119
+ return intervalMembership(None, self.is_valid)
120
+ elif isinstance(other, interval):
121
+ return other.__lt__(self)
122
+ else:
123
+ return NotImplemented
124
+
125
+ def __eq__(self, other):
126
+ if isinstance(other, (int, float)):
127
+ if self.start == other and self.end == other:
128
+ return intervalMembership(True, self.is_valid)
129
+ if other in self:
130
+ return intervalMembership(None, self.is_valid)
131
+ else:
132
+ return intervalMembership(False, self.is_valid)
133
+
134
+ if isinstance(other, interval):
135
+ valid = fuzzy_and([self.is_valid, other.is_valid])
136
+ if self.start == other.start and self.end == other.end:
137
+ return intervalMembership(True, valid)
138
+ elif self.__lt__(other)[0] is not None:
139
+ return intervalMembership(False, valid)
140
+ else:
141
+ return intervalMembership(None, valid)
142
+ else:
143
+ return NotImplemented
144
+
145
+ def __ne__(self, other):
146
+ if isinstance(other, (int, float)):
147
+ if self.start == other and self.end == other:
148
+ return intervalMembership(False, self.is_valid)
149
+ if other in self:
150
+ return intervalMembership(None, self.is_valid)
151
+ else:
152
+ return intervalMembership(True, self.is_valid)
153
+
154
+ if isinstance(other, interval):
155
+ valid = fuzzy_and([self.is_valid, other.is_valid])
156
+ if self.start == other.start and self.end == other.end:
157
+ return intervalMembership(False, valid)
158
+ if not self.__lt__(other)[0] is None:
159
+ return intervalMembership(True, valid)
160
+ return intervalMembership(None, valid)
161
+ else:
162
+ return NotImplemented
163
+
164
+ def __le__(self, other):
165
+ if isinstance(other, (int, float)):
166
+ if self.end <= other:
167
+ return intervalMembership(True, self.is_valid)
168
+ if self.start > other:
169
+ return intervalMembership(False, self.is_valid)
170
+ else:
171
+ return intervalMembership(None, self.is_valid)
172
+
173
+ if isinstance(other, interval):
174
+ valid = fuzzy_and([self.is_valid, other.is_valid])
175
+ if self.end <= other.start:
176
+ return intervalMembership(True, valid)
177
+ if self.start > other.end:
178
+ return intervalMembership(False, valid)
179
+ return intervalMembership(None, valid)
180
+ else:
181
+ return NotImplemented
182
+
183
+ def __ge__(self, other):
184
+ if isinstance(other, (int, float)):
185
+ if self.start >= other:
186
+ return intervalMembership(True, self.is_valid)
187
+ elif self.end < other:
188
+ return intervalMembership(False, self.is_valid)
189
+ else:
190
+ return intervalMembership(None, self.is_valid)
191
+ elif isinstance(other, interval):
192
+ return other.__le__(self)
193
+
194
+ def __add__(self, other):
195
+ if isinstance(other, (int, float)):
196
+ if self.is_valid:
197
+ return interval(self.start + other, self.end + other)
198
+ else:
199
+ start = self.start + other
200
+ end = self.end + other
201
+ return interval(start, end, is_valid=self.is_valid)
202
+
203
+ elif isinstance(other, interval):
204
+ start = self.start + other.start
205
+ end = self.end + other.end
206
+ valid = fuzzy_and([self.is_valid, other.is_valid])
207
+ return interval(start, end, is_valid=valid)
208
+ else:
209
+ return NotImplemented
210
+
211
+ __radd__ = __add__
212
+
213
+ def __sub__(self, other):
214
+ if isinstance(other, (int, float)):
215
+ start = self.start - other
216
+ end = self.end - other
217
+ return interval(start, end, is_valid=self.is_valid)
218
+
219
+ elif isinstance(other, interval):
220
+ start = self.start - other.end
221
+ end = self.end - other.start
222
+ valid = fuzzy_and([self.is_valid, other.is_valid])
223
+ return interval(start, end, is_valid=valid)
224
+ else:
225
+ return NotImplemented
226
+
227
+ def __rsub__(self, other):
228
+ if isinstance(other, (int, float)):
229
+ start = other - self.end
230
+ end = other - self.start
231
+ return interval(start, end, is_valid=self.is_valid)
232
+ elif isinstance(other, interval):
233
+ return other.__sub__(self)
234
+ else:
235
+ return NotImplemented
236
+
237
+ def __neg__(self):
238
+ if self.is_valid:
239
+ return interval(-self.end, -self.start)
240
+ else:
241
+ return interval(-self.end, -self.start, is_valid=self.is_valid)
242
+
243
+ def __mul__(self, other):
244
+ if isinstance(other, interval):
245
+ if self.is_valid is False or other.is_valid is False:
246
+ return interval(-float('inf'), float('inf'), is_valid=False)
247
+ elif self.is_valid is None or other.is_valid is None:
248
+ return interval(-float('inf'), float('inf'), is_valid=None)
249
+ else:
250
+ inters = []
251
+ inters.append(self.start * other.start)
252
+ inters.append(self.end * other.start)
253
+ inters.append(self.start * other.end)
254
+ inters.append(self.end * other.end)
255
+ start = min(inters)
256
+ end = max(inters)
257
+ return interval(start, end)
258
+ elif isinstance(other, (int, float)):
259
+ return interval(self.start*other, self.end*other, is_valid=self.is_valid)
260
+ else:
261
+ return NotImplemented
262
+
263
+ __rmul__ = __mul__
264
+
265
+ def __contains__(self, other):
266
+ if isinstance(other, (int, float)):
267
+ return self.start <= other and self.end >= other
268
+ else:
269
+ return self.start <= other.start and other.end <= self.end
270
+
271
+ def __rtruediv__(self, other):
272
+ if isinstance(other, (int, float)):
273
+ other = interval(other)
274
+ return other.__truediv__(self)
275
+ elif isinstance(other, interval):
276
+ return other.__truediv__(self)
277
+ else:
278
+ return NotImplemented
279
+
280
+ def __truediv__(self, other):
281
+ # Both None and False are handled
282
+ if not self.is_valid:
283
+ # Don't divide as the value is not valid
284
+ return interval(-float('inf'), float('inf'), is_valid=self.is_valid)
285
+ if isinstance(other, (int, float)):
286
+ if other == 0:
287
+ # Divide by zero encountered. valid nowhere
288
+ return interval(-float('inf'), float('inf'), is_valid=False)
289
+ else:
290
+ return interval(self.start / other, self.end / other)
291
+
292
+ elif isinstance(other, interval):
293
+ if other.is_valid is False or self.is_valid is False:
294
+ return interval(-float('inf'), float('inf'), is_valid=False)
295
+ elif other.is_valid is None or self.is_valid is None:
296
+ return interval(-float('inf'), float('inf'), is_valid=None)
297
+ else:
298
+ # denominator contains both signs, i.e. being divided by zero
299
+ # return the whole real line with is_valid = None
300
+ if 0 in other:
301
+ return interval(-float('inf'), float('inf'), is_valid=None)
302
+
303
+ # denominator negative
304
+ this = self
305
+ if other.end < 0:
306
+ this = -this
307
+ other = -other
308
+
309
+ # denominator positive
310
+ inters = []
311
+ inters.append(this.start / other.start)
312
+ inters.append(this.end / other.start)
313
+ inters.append(this.start / other.end)
314
+ inters.append(this.end / other.end)
315
+ start = max(inters)
316
+ end = min(inters)
317
+ return interval(start, end)
318
+ else:
319
+ return NotImplemented
320
+
321
+ def __pow__(self, other):
322
+ # Implements only power to an integer.
323
+ from .lib_interval import exp, log
324
+ if not self.is_valid:
325
+ return self
326
+ if isinstance(other, interval):
327
+ return exp(other * log(self))
328
+ elif isinstance(other, (float, int)):
329
+ if other < 0:
330
+ return 1 / self.__pow__(abs(other))
331
+ else:
332
+ if int(other) == other:
333
+ return _pow_int(self, other)
334
+ else:
335
+ return _pow_float(self, other)
336
+ else:
337
+ return NotImplemented
338
+
339
+ def __rpow__(self, other):
340
+ if isinstance(other, (float, int)):
341
+ if not self.is_valid:
342
+ #Don't do anything
343
+ return self
344
+ elif other < 0:
345
+ if self.width > 0:
346
+ return interval(-float('inf'), float('inf'), is_valid=False)
347
+ else:
348
+ power_rational = nsimplify(self.start)
349
+ num, denom = power_rational.as_numer_denom()
350
+ if denom % 2 == 0:
351
+ return interval(-float('inf'), float('inf'),
352
+ is_valid=False)
353
+ else:
354
+ start = -abs(other)**self.start
355
+ end = start
356
+ return interval(start, end)
357
+ else:
358
+ return interval(other**self.start, other**self.end)
359
+ elif isinstance(other, interval):
360
+ return other.__pow__(self)
361
+ else:
362
+ return NotImplemented
363
+
364
+ def __hash__(self):
365
+ return hash((self.is_valid, self.start, self.end))
366
+
367
+
368
+ def _pow_float(inter, power):
369
+ """Evaluates an interval raised to a floating point."""
370
+ power_rational = nsimplify(power)
371
+ num, denom = power_rational.as_numer_denom()
372
+ if num % 2 == 0:
373
+ start = abs(inter.start)**power
374
+ end = abs(inter.end)**power
375
+ if start < 0:
376
+ ret = interval(0, max(start, end))
377
+ else:
378
+ ret = interval(start, end)
379
+ return ret
380
+ elif denom % 2 == 0:
381
+ if inter.end < 0:
382
+ return interval(-float('inf'), float('inf'), is_valid=False)
383
+ elif inter.start < 0:
384
+ return interval(0, inter.end**power, is_valid=None)
385
+ else:
386
+ return interval(inter.start**power, inter.end**power)
387
+ else:
388
+ if inter.start < 0:
389
+ start = -abs(inter.start)**power
390
+ else:
391
+ start = inter.start**power
392
+
393
+ if inter.end < 0:
394
+ end = -abs(inter.end)**power
395
+ else:
396
+ end = inter.end**power
397
+
398
+ return interval(start, end, is_valid=inter.is_valid)
399
+
400
+
401
+ def _pow_int(inter, power):
402
+ """Evaluates an interval raised to an integer power"""
403
+ power = int(power)
404
+ if power & 1:
405
+ return interval(inter.start**power, inter.end**power)
406
+ else:
407
+ if inter.start < 0 and inter.end > 0:
408
+ start = 0
409
+ end = max(inter.start**power, inter.end**power)
410
+ return interval(start, end)
411
+ else:
412
+ return interval(inter.start**power, inter.end**power)
venv/lib/python3.10/site-packages/sympy/plotting/intervalmath/interval_membership.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.logic import fuzzy_and, fuzzy_or, fuzzy_not, fuzzy_xor
2
+
3
+
4
+ class intervalMembership:
5
+ """Represents a boolean expression returned by the comparison of
6
+ the interval object.
7
+
8
+ Parameters
9
+ ==========
10
+
11
+ (a, b) : (bool, bool)
12
+ The first value determines the comparison as follows:
13
+ - True: If the comparison is True throughout the intervals.
14
+ - False: If the comparison is False throughout the intervals.
15
+ - None: If the comparison is True for some part of the intervals.
16
+
17
+ The second value is determined as follows:
18
+ - True: If both the intervals in comparison are valid.
19
+ - False: If at least one of the intervals is False, else
20
+ - None
21
+ """
22
+ def __init__(self, a, b):
23
+ self._wrapped = (a, b)
24
+
25
+ def __getitem__(self, i):
26
+ try:
27
+ return self._wrapped[i]
28
+ except IndexError:
29
+ raise IndexError(
30
+ "{} must be a valid indexing for the 2-tuple."
31
+ .format(i))
32
+
33
+ def __len__(self):
34
+ return 2
35
+
36
+ def __iter__(self):
37
+ return iter(self._wrapped)
38
+
39
+ def __str__(self):
40
+ return "intervalMembership({}, {})".format(*self)
41
+ __repr__ = __str__
42
+
43
+ def __and__(self, other):
44
+ if not isinstance(other, intervalMembership):
45
+ raise ValueError(
46
+ "The comparison is not supported for {}.".format(other))
47
+
48
+ a1, b1 = self
49
+ a2, b2 = other
50
+ return intervalMembership(fuzzy_and([a1, a2]), fuzzy_and([b1, b2]))
51
+
52
+ def __or__(self, other):
53
+ if not isinstance(other, intervalMembership):
54
+ raise ValueError(
55
+ "The comparison is not supported for {}.".format(other))
56
+
57
+ a1, b1 = self
58
+ a2, b2 = other
59
+ return intervalMembership(fuzzy_or([a1, a2]), fuzzy_and([b1, b2]))
60
+
61
+ def __invert__(self):
62
+ a, b = self
63
+ return intervalMembership(fuzzy_not(a), b)
64
+
65
+ def __xor__(self, other):
66
+ if not isinstance(other, intervalMembership):
67
+ raise ValueError(
68
+ "The comparison is not supported for {}.".format(other))
69
+
70
+ a1, b1 = self
71
+ a2, b2 = other
72
+ return intervalMembership(fuzzy_xor([a1, a2]), fuzzy_and([b1, b2]))
73
+
74
+ def __eq__(self, other):
75
+ return self._wrapped == other
76
+
77
+ def __ne__(self, other):
78
+ return self._wrapped != other
venv/lib/python3.10/site-packages/sympy/plotting/intervalmath/lib_interval.py ADDED
@@ -0,0 +1,452 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ The module contains implemented functions for interval arithmetic."""
2
+ from functools import reduce
3
+
4
+ from sympy.plotting.intervalmath import interval
5
+ from sympy.external import import_module
6
+
7
+
8
+ def Abs(x):
9
+ if isinstance(x, (int, float)):
10
+ return interval(abs(x))
11
+ elif isinstance(x, interval):
12
+ if x.start < 0 and x.end > 0:
13
+ return interval(0, max(abs(x.start), abs(x.end)), is_valid=x.is_valid)
14
+ else:
15
+ return interval(abs(x.start), abs(x.end))
16
+ else:
17
+ raise NotImplementedError
18
+
19
+ #Monotonic
20
+
21
+
22
+ def exp(x):
23
+ """evaluates the exponential of an interval"""
24
+ np = import_module('numpy')
25
+ if isinstance(x, (int, float)):
26
+ return interval(np.exp(x), np.exp(x))
27
+ elif isinstance(x, interval):
28
+ return interval(np.exp(x.start), np.exp(x.end), is_valid=x.is_valid)
29
+ else:
30
+ raise NotImplementedError
31
+
32
+
33
+ #Monotonic
34
+ def log(x):
35
+ """evaluates the natural logarithm of an interval"""
36
+ np = import_module('numpy')
37
+ if isinstance(x, (int, float)):
38
+ if x <= 0:
39
+ return interval(-np.inf, np.inf, is_valid=False)
40
+ else:
41
+ return interval(np.log(x))
42
+ elif isinstance(x, interval):
43
+ if not x.is_valid:
44
+ return interval(-np.inf, np.inf, is_valid=x.is_valid)
45
+ elif x.end <= 0:
46
+ return interval(-np.inf, np.inf, is_valid=False)
47
+ elif x.start <= 0:
48
+ return interval(-np.inf, np.inf, is_valid=None)
49
+
50
+ return interval(np.log(x.start), np.log(x.end))
51
+ else:
52
+ raise NotImplementedError
53
+
54
+
55
+ #Monotonic
56
+ def log10(x):
57
+ """evaluates the logarithm to the base 10 of an interval"""
58
+ np = import_module('numpy')
59
+ if isinstance(x, (int, float)):
60
+ if x <= 0:
61
+ return interval(-np.inf, np.inf, is_valid=False)
62
+ else:
63
+ return interval(np.log10(x))
64
+ elif isinstance(x, interval):
65
+ if not x.is_valid:
66
+ return interval(-np.inf, np.inf, is_valid=x.is_valid)
67
+ elif x.end <= 0:
68
+ return interval(-np.inf, np.inf, is_valid=False)
69
+ elif x.start <= 0:
70
+ return interval(-np.inf, np.inf, is_valid=None)
71
+ return interval(np.log10(x.start), np.log10(x.end))
72
+ else:
73
+ raise NotImplementedError
74
+
75
+
76
+ #Monotonic
77
+ def atan(x):
78
+ """evaluates the tan inverse of an interval"""
79
+ np = import_module('numpy')
80
+ if isinstance(x, (int, float)):
81
+ return interval(np.arctan(x))
82
+ elif isinstance(x, interval):
83
+ start = np.arctan(x.start)
84
+ end = np.arctan(x.end)
85
+ return interval(start, end, is_valid=x.is_valid)
86
+ else:
87
+ raise NotImplementedError
88
+
89
+
90
+ #periodic
91
+ def sin(x):
92
+ """evaluates the sine of an interval"""
93
+ np = import_module('numpy')
94
+ if isinstance(x, (int, float)):
95
+ return interval(np.sin(x))
96
+ elif isinstance(x, interval):
97
+ if not x.is_valid:
98
+ return interval(-1, 1, is_valid=x.is_valid)
99
+ na, __ = divmod(x.start, np.pi / 2.0)
100
+ nb, __ = divmod(x.end, np.pi / 2.0)
101
+ start = min(np.sin(x.start), np.sin(x.end))
102
+ end = max(np.sin(x.start), np.sin(x.end))
103
+ if nb - na > 4:
104
+ return interval(-1, 1, is_valid=x.is_valid)
105
+ elif na == nb:
106
+ return interval(start, end, is_valid=x.is_valid)
107
+ else:
108
+ if (na - 1) // 4 != (nb - 1) // 4:
109
+ #sin has max
110
+ end = 1
111
+ if (na - 3) // 4 != (nb - 3) // 4:
112
+ #sin has min
113
+ start = -1
114
+ return interval(start, end)
115
+ else:
116
+ raise NotImplementedError
117
+
118
+
119
+ #periodic
120
+ def cos(x):
121
+ """Evaluates the cos of an interval"""
122
+ np = import_module('numpy')
123
+ if isinstance(x, (int, float)):
124
+ return interval(np.sin(x))
125
+ elif isinstance(x, interval):
126
+ if not (np.isfinite(x.start) and np.isfinite(x.end)):
127
+ return interval(-1, 1, is_valid=x.is_valid)
128
+ na, __ = divmod(x.start, np.pi / 2.0)
129
+ nb, __ = divmod(x.end, np.pi / 2.0)
130
+ start = min(np.cos(x.start), np.cos(x.end))
131
+ end = max(np.cos(x.start), np.cos(x.end))
132
+ if nb - na > 4:
133
+ #differ more than 2*pi
134
+ return interval(-1, 1, is_valid=x.is_valid)
135
+ elif na == nb:
136
+ #in the same quadarant
137
+ return interval(start, end, is_valid=x.is_valid)
138
+ else:
139
+ if (na) // 4 != (nb) // 4:
140
+ #cos has max
141
+ end = 1
142
+ if (na - 2) // 4 != (nb - 2) // 4:
143
+ #cos has min
144
+ start = -1
145
+ return interval(start, end, is_valid=x.is_valid)
146
+ else:
147
+ raise NotImplementedError
148
+
149
+
150
+ def tan(x):
151
+ """Evaluates the tan of an interval"""
152
+ return sin(x) / cos(x)
153
+
154
+
155
+ #Monotonic
156
+ def sqrt(x):
157
+ """Evaluates the square root of an interval"""
158
+ np = import_module('numpy')
159
+ if isinstance(x, (int, float)):
160
+ if x > 0:
161
+ return interval(np.sqrt(x))
162
+ else:
163
+ return interval(-np.inf, np.inf, is_valid=False)
164
+ elif isinstance(x, interval):
165
+ #Outside the domain
166
+ if x.end < 0:
167
+ return interval(-np.inf, np.inf, is_valid=False)
168
+ #Partially outside the domain
169
+ elif x.start < 0:
170
+ return interval(-np.inf, np.inf, is_valid=None)
171
+ else:
172
+ return interval(np.sqrt(x.start), np.sqrt(x.end),
173
+ is_valid=x.is_valid)
174
+ else:
175
+ raise NotImplementedError
176
+
177
+
178
+ def imin(*args):
179
+ """Evaluates the minimum of a list of intervals"""
180
+ np = import_module('numpy')
181
+ if not all(isinstance(arg, (int, float, interval)) for arg in args):
182
+ return NotImplementedError
183
+ else:
184
+ new_args = [a for a in args if isinstance(a, (int, float))
185
+ or a.is_valid]
186
+ if len(new_args) == 0:
187
+ if all(a.is_valid is False for a in args):
188
+ return interval(-np.inf, np.inf, is_valid=False)
189
+ else:
190
+ return interval(-np.inf, np.inf, is_valid=None)
191
+ start_array = [a if isinstance(a, (int, float)) else a.start
192
+ for a in new_args]
193
+
194
+ end_array = [a if isinstance(a, (int, float)) else a.end
195
+ for a in new_args]
196
+ return interval(min(start_array), min(end_array))
197
+
198
+
199
+ def imax(*args):
200
+ """Evaluates the maximum of a list of intervals"""
201
+ np = import_module('numpy')
202
+ if not all(isinstance(arg, (int, float, interval)) for arg in args):
203
+ return NotImplementedError
204
+ else:
205
+ new_args = [a for a in args if isinstance(a, (int, float))
206
+ or a.is_valid]
207
+ if len(new_args) == 0:
208
+ if all(a.is_valid is False for a in args):
209
+ return interval(-np.inf, np.inf, is_valid=False)
210
+ else:
211
+ return interval(-np.inf, np.inf, is_valid=None)
212
+ start_array = [a if isinstance(a, (int, float)) else a.start
213
+ for a in new_args]
214
+
215
+ end_array = [a if isinstance(a, (int, float)) else a.end
216
+ for a in new_args]
217
+
218
+ return interval(max(start_array), max(end_array))
219
+
220
+
221
+ #Monotonic
222
+ def sinh(x):
223
+ """Evaluates the hyperbolic sine of an interval"""
224
+ np = import_module('numpy')
225
+ if isinstance(x, (int, float)):
226
+ return interval(np.sinh(x), np.sinh(x))
227
+ elif isinstance(x, interval):
228
+ return interval(np.sinh(x.start), np.sinh(x.end), is_valid=x.is_valid)
229
+ else:
230
+ raise NotImplementedError
231
+
232
+
233
+ def cosh(x):
234
+ """Evaluates the hyperbolic cos of an interval"""
235
+ np = import_module('numpy')
236
+ if isinstance(x, (int, float)):
237
+ return interval(np.cosh(x), np.cosh(x))
238
+ elif isinstance(x, interval):
239
+ #both signs
240
+ if x.start < 0 and x.end > 0:
241
+ end = max(np.cosh(x.start), np.cosh(x.end))
242
+ return interval(1, end, is_valid=x.is_valid)
243
+ else:
244
+ #Monotonic
245
+ start = np.cosh(x.start)
246
+ end = np.cosh(x.end)
247
+ return interval(start, end, is_valid=x.is_valid)
248
+ else:
249
+ raise NotImplementedError
250
+
251
+
252
+ #Monotonic
253
+ def tanh(x):
254
+ """Evaluates the hyperbolic tan of an interval"""
255
+ np = import_module('numpy')
256
+ if isinstance(x, (int, float)):
257
+ return interval(np.tanh(x), np.tanh(x))
258
+ elif isinstance(x, interval):
259
+ return interval(np.tanh(x.start), np.tanh(x.end), is_valid=x.is_valid)
260
+ else:
261
+ raise NotImplementedError
262
+
263
+
264
+ def asin(x):
265
+ """Evaluates the inverse sine of an interval"""
266
+ np = import_module('numpy')
267
+ if isinstance(x, (int, float)):
268
+ #Outside the domain
269
+ if abs(x) > 1:
270
+ return interval(-np.inf, np.inf, is_valid=False)
271
+ else:
272
+ return interval(np.arcsin(x), np.arcsin(x))
273
+ elif isinstance(x, interval):
274
+ #Outside the domain
275
+ if x.is_valid is False or x.start > 1 or x.end < -1:
276
+ return interval(-np.inf, np.inf, is_valid=False)
277
+ #Partially outside the domain
278
+ elif x.start < -1 or x.end > 1:
279
+ return interval(-np.inf, np.inf, is_valid=None)
280
+ else:
281
+ start = np.arcsin(x.start)
282
+ end = np.arcsin(x.end)
283
+ return interval(start, end, is_valid=x.is_valid)
284
+
285
+
286
+ def acos(x):
287
+ """Evaluates the inverse cos of an interval"""
288
+ np = import_module('numpy')
289
+ if isinstance(x, (int, float)):
290
+ if abs(x) > 1:
291
+ #Outside the domain
292
+ return interval(-np.inf, np.inf, is_valid=False)
293
+ else:
294
+ return interval(np.arccos(x), np.arccos(x))
295
+ elif isinstance(x, interval):
296
+ #Outside the domain
297
+ if x.is_valid is False or x.start > 1 or x.end < -1:
298
+ return interval(-np.inf, np.inf, is_valid=False)
299
+ #Partially outside the domain
300
+ elif x.start < -1 or x.end > 1:
301
+ return interval(-np.inf, np.inf, is_valid=None)
302
+ else:
303
+ start = np.arccos(x.start)
304
+ end = np.arccos(x.end)
305
+ return interval(start, end, is_valid=x.is_valid)
306
+
307
+
308
+ def ceil(x):
309
+ """Evaluates the ceiling of an interval"""
310
+ np = import_module('numpy')
311
+ if isinstance(x, (int, float)):
312
+ return interval(np.ceil(x))
313
+ elif isinstance(x, interval):
314
+ if x.is_valid is False:
315
+ return interval(-np.inf, np.inf, is_valid=False)
316
+ else:
317
+ start = np.ceil(x.start)
318
+ end = np.ceil(x.end)
319
+ #Continuous over the interval
320
+ if start == end:
321
+ return interval(start, end, is_valid=x.is_valid)
322
+ else:
323
+ #Not continuous over the interval
324
+ return interval(start, end, is_valid=None)
325
+ else:
326
+ return NotImplementedError
327
+
328
+
329
+ def floor(x):
330
+ """Evaluates the floor of an interval"""
331
+ np = import_module('numpy')
332
+ if isinstance(x, (int, float)):
333
+ return interval(np.floor(x))
334
+ elif isinstance(x, interval):
335
+ if x.is_valid is False:
336
+ return interval(-np.inf, np.inf, is_valid=False)
337
+ else:
338
+ start = np.floor(x.start)
339
+ end = np.floor(x.end)
340
+ #continuous over the argument
341
+ if start == end:
342
+ return interval(start, end, is_valid=x.is_valid)
343
+ else:
344
+ #not continuous over the interval
345
+ return interval(start, end, is_valid=None)
346
+ else:
347
+ return NotImplementedError
348
+
349
+
350
+ def acosh(x):
351
+ """Evaluates the inverse hyperbolic cosine of an interval"""
352
+ np = import_module('numpy')
353
+ if isinstance(x, (int, float)):
354
+ #Outside the domain
355
+ if x < 1:
356
+ return interval(-np.inf, np.inf, is_valid=False)
357
+ else:
358
+ return interval(np.arccosh(x))
359
+ elif isinstance(x, interval):
360
+ #Outside the domain
361
+ if x.end < 1:
362
+ return interval(-np.inf, np.inf, is_valid=False)
363
+ #Partly outside the domain
364
+ elif x.start < 1:
365
+ return interval(-np.inf, np.inf, is_valid=None)
366
+ else:
367
+ start = np.arccosh(x.start)
368
+ end = np.arccosh(x.end)
369
+ return interval(start, end, is_valid=x.is_valid)
370
+ else:
371
+ return NotImplementedError
372
+
373
+
374
+ #Monotonic
375
+ def asinh(x):
376
+ """Evaluates the inverse hyperbolic sine of an interval"""
377
+ np = import_module('numpy')
378
+ if isinstance(x, (int, float)):
379
+ return interval(np.arcsinh(x))
380
+ elif isinstance(x, interval):
381
+ start = np.arcsinh(x.start)
382
+ end = np.arcsinh(x.end)
383
+ return interval(start, end, is_valid=x.is_valid)
384
+ else:
385
+ return NotImplementedError
386
+
387
+
388
+ def atanh(x):
389
+ """Evaluates the inverse hyperbolic tangent of an interval"""
390
+ np = import_module('numpy')
391
+ if isinstance(x, (int, float)):
392
+ #Outside the domain
393
+ if abs(x) >= 1:
394
+ return interval(-np.inf, np.inf, is_valid=False)
395
+ else:
396
+ return interval(np.arctanh(x))
397
+ elif isinstance(x, interval):
398
+ #outside the domain
399
+ if x.is_valid is False or x.start >= 1 or x.end <= -1:
400
+ return interval(-np.inf, np.inf, is_valid=False)
401
+ #partly outside the domain
402
+ elif x.start <= -1 or x.end >= 1:
403
+ return interval(-np.inf, np.inf, is_valid=None)
404
+ else:
405
+ start = np.arctanh(x.start)
406
+ end = np.arctanh(x.end)
407
+ return interval(start, end, is_valid=x.is_valid)
408
+ else:
409
+ return NotImplementedError
410
+
411
+
412
+ #Three valued logic for interval plotting.
413
+
414
+ def And(*args):
415
+ """Defines the three valued ``And`` behaviour for a 2-tuple of
416
+ three valued logic values"""
417
+ def reduce_and(cmp_intervala, cmp_intervalb):
418
+ if cmp_intervala[0] is False or cmp_intervalb[0] is False:
419
+ first = False
420
+ elif cmp_intervala[0] is None or cmp_intervalb[0] is None:
421
+ first = None
422
+ else:
423
+ first = True
424
+ if cmp_intervala[1] is False or cmp_intervalb[1] is False:
425
+ second = False
426
+ elif cmp_intervala[1] is None or cmp_intervalb[1] is None:
427
+ second = None
428
+ else:
429
+ second = True
430
+ return (first, second)
431
+ return reduce(reduce_and, args)
432
+
433
+
434
+ def Or(*args):
435
+ """Defines the three valued ``Or`` behaviour for a 2-tuple of
436
+ three valued logic values"""
437
+ def reduce_or(cmp_intervala, cmp_intervalb):
438
+ if cmp_intervala[0] is True or cmp_intervalb[0] is True:
439
+ first = True
440
+ elif cmp_intervala[0] is None or cmp_intervalb[0] is None:
441
+ first = None
442
+ else:
443
+ first = False
444
+
445
+ if cmp_intervala[1] is True or cmp_intervalb[1] is True:
446
+ second = True
447
+ elif cmp_intervala[1] is None or cmp_intervalb[1] is None:
448
+ second = None
449
+ else:
450
+ second = False
451
+ return (first, second)
452
+ return reduce(reduce_or, args)
venv/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (201 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/__pycache__/test_interval_functions.cpython-310.pyc ADDED
Binary file (9.3 kB). View file
 
venv/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/__pycache__/test_interval_membership.cpython-310.pyc ADDED
Binary file (3.67 kB). View file
 
venv/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/__pycache__/test_intervalmath.cpython-310.pyc ADDED
Binary file (6.36 kB). View file
 
venv/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/test_interval_functions.py ADDED
@@ -0,0 +1,415 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.external import import_module
2
+ from sympy.plotting.intervalmath import (
3
+ Abs, acos, acosh, And, asin, asinh, atan, atanh, ceil, cos, cosh,
4
+ exp, floor, imax, imin, interval, log, log10, Or, sin, sinh, sqrt,
5
+ tan, tanh,
6
+ )
7
+
8
+ np = import_module('numpy')
9
+ if not np:
10
+ disabled = True
11
+
12
+
13
+ #requires Numpy. Hence included in interval_functions
14
+
15
+
16
+ def test_interval_pow():
17
+ a = 2**interval(1, 2) == interval(2, 4)
18
+ assert a == (True, True)
19
+ a = interval(1, 2)**interval(1, 2) == interval(1, 4)
20
+ assert a == (True, True)
21
+ a = interval(-1, 1)**interval(0.5, 2)
22
+ assert a.is_valid is None
23
+ a = interval(-2, -1) ** interval(1, 2)
24
+ assert a.is_valid is False
25
+ a = interval(-2, -1) ** (1.0 / 2)
26
+ assert a.is_valid is False
27
+ a = interval(-1, 1)**(1.0 / 2)
28
+ assert a.is_valid is None
29
+ a = interval(-1, 1)**(1.0 / 3) == interval(-1, 1)
30
+ assert a == (True, True)
31
+ a = interval(-1, 1)**2 == interval(0, 1)
32
+ assert a == (True, True)
33
+ a = interval(-1, 1) ** (1.0 / 29) == interval(-1, 1)
34
+ assert a == (True, True)
35
+ a = -2**interval(1, 1) == interval(-2, -2)
36
+ assert a == (True, True)
37
+
38
+ a = interval(1, 2, is_valid=False)**2
39
+ assert a.is_valid is False
40
+
41
+ a = (-3)**interval(1, 2)
42
+ assert a.is_valid is False
43
+ a = (-4)**interval(0.5, 0.5)
44
+ assert a.is_valid is False
45
+ assert ((-3)**interval(1, 1) == interval(-3, -3)) == (True, True)
46
+
47
+ a = interval(8, 64)**(2.0 / 3)
48
+ assert abs(a.start - 4) < 1e-10 # eps
49
+ assert abs(a.end - 16) < 1e-10
50
+ a = interval(-8, 64)**(2.0 / 3)
51
+ assert abs(a.start - 4) < 1e-10 # eps
52
+ assert abs(a.end - 16) < 1e-10
53
+
54
+
55
+ def test_exp():
56
+ a = exp(interval(-np.inf, 0))
57
+ assert a.start == np.exp(-np.inf)
58
+ assert a.end == np.exp(0)
59
+ a = exp(interval(1, 2))
60
+ assert a.start == np.exp(1)
61
+ assert a.end == np.exp(2)
62
+ a = exp(1)
63
+ assert a.start == np.exp(1)
64
+ assert a.end == np.exp(1)
65
+
66
+
67
+ def test_log():
68
+ a = log(interval(1, 2))
69
+ assert a.start == 0
70
+ assert a.end == np.log(2)
71
+ a = log(interval(-1, 1))
72
+ assert a.is_valid is None
73
+ a = log(interval(-3, -1))
74
+ assert a.is_valid is False
75
+ a = log(-3)
76
+ assert a.is_valid is False
77
+ a = log(2)
78
+ assert a.start == np.log(2)
79
+ assert a.end == np.log(2)
80
+
81
+
82
+ def test_log10():
83
+ a = log10(interval(1, 2))
84
+ assert a.start == 0
85
+ assert a.end == np.log10(2)
86
+ a = log10(interval(-1, 1))
87
+ assert a.is_valid is None
88
+ a = log10(interval(-3, -1))
89
+ assert a.is_valid is False
90
+ a = log10(-3)
91
+ assert a.is_valid is False
92
+ a = log10(2)
93
+ assert a.start == np.log10(2)
94
+ assert a.end == np.log10(2)
95
+
96
+
97
+ def test_atan():
98
+ a = atan(interval(0, 1))
99
+ assert a.start == np.arctan(0)
100
+ assert a.end == np.arctan(1)
101
+ a = atan(1)
102
+ assert a.start == np.arctan(1)
103
+ assert a.end == np.arctan(1)
104
+
105
+
106
+ def test_sin():
107
+ a = sin(interval(0, np.pi / 4))
108
+ assert a.start == np.sin(0)
109
+ assert a.end == np.sin(np.pi / 4)
110
+
111
+ a = sin(interval(-np.pi / 4, np.pi / 4))
112
+ assert a.start == np.sin(-np.pi / 4)
113
+ assert a.end == np.sin(np.pi / 4)
114
+
115
+ a = sin(interval(np.pi / 4, 3 * np.pi / 4))
116
+ assert a.start == np.sin(np.pi / 4)
117
+ assert a.end == 1
118
+
119
+ a = sin(interval(7 * np.pi / 6, 7 * np.pi / 4))
120
+ assert a.start == -1
121
+ assert a.end == np.sin(7 * np.pi / 6)
122
+
123
+ a = sin(interval(0, 3 * np.pi))
124
+ assert a.start == -1
125
+ assert a.end == 1
126
+
127
+ a = sin(interval(np.pi / 3, 7 * np.pi / 4))
128
+ assert a.start == -1
129
+ assert a.end == 1
130
+
131
+ a = sin(np.pi / 4)
132
+ assert a.start == np.sin(np.pi / 4)
133
+ assert a.end == np.sin(np.pi / 4)
134
+
135
+ a = sin(interval(1, 2, is_valid=False))
136
+ assert a.is_valid is False
137
+
138
+
139
+ def test_cos():
140
+ a = cos(interval(0, np.pi / 4))
141
+ assert a.start == np.cos(np.pi / 4)
142
+ assert a.end == 1
143
+
144
+ a = cos(interval(-np.pi / 4, np.pi / 4))
145
+ assert a.start == np.cos(-np.pi / 4)
146
+ assert a.end == 1
147
+
148
+ a = cos(interval(np.pi / 4, 3 * np.pi / 4))
149
+ assert a.start == np.cos(3 * np.pi / 4)
150
+ assert a.end == np.cos(np.pi / 4)
151
+
152
+ a = cos(interval(3 * np.pi / 4, 5 * np.pi / 4))
153
+ assert a.start == -1
154
+ assert a.end == np.cos(3 * np.pi / 4)
155
+
156
+ a = cos(interval(0, 3 * np.pi))
157
+ assert a.start == -1
158
+ assert a.end == 1
159
+
160
+ a = cos(interval(- np.pi / 3, 5 * np.pi / 4))
161
+ assert a.start == -1
162
+ assert a.end == 1
163
+
164
+ a = cos(interval(1, 2, is_valid=False))
165
+ assert a.is_valid is False
166
+
167
+
168
+ def test_tan():
169
+ a = tan(interval(0, np.pi / 4))
170
+ assert a.start == 0
171
+ # must match lib_interval definition of tan:
172
+ assert a.end == np.sin(np.pi / 4)/np.cos(np.pi / 4)
173
+
174
+ a = tan(interval(np.pi / 4, 3 * np.pi / 4))
175
+ #discontinuity
176
+ assert a.is_valid is None
177
+
178
+
179
+ def test_sqrt():
180
+ a = sqrt(interval(1, 4))
181
+ assert a.start == 1
182
+ assert a.end == 2
183
+
184
+ a = sqrt(interval(0.01, 1))
185
+ assert a.start == np.sqrt(0.01)
186
+ assert a.end == 1
187
+
188
+ a = sqrt(interval(-1, 1))
189
+ assert a.is_valid is None
190
+
191
+ a = sqrt(interval(-3, -1))
192
+ assert a.is_valid is False
193
+
194
+ a = sqrt(4)
195
+ assert (a == interval(2, 2)) == (True, True)
196
+
197
+ a = sqrt(-3)
198
+ assert a.is_valid is False
199
+
200
+
201
+ def test_imin():
202
+ a = imin(interval(1, 3), interval(2, 5), interval(-1, 3))
203
+ assert a.start == -1
204
+ assert a.end == 3
205
+
206
+ a = imin(-2, interval(1, 4))
207
+ assert a.start == -2
208
+ assert a.end == -2
209
+
210
+ a = imin(5, interval(3, 4), interval(-2, 2, is_valid=False))
211
+ assert a.start == 3
212
+ assert a.end == 4
213
+
214
+
215
+ def test_imax():
216
+ a = imax(interval(-2, 2), interval(2, 7), interval(-3, 9))
217
+ assert a.start == 2
218
+ assert a.end == 9
219
+
220
+ a = imax(8, interval(1, 4))
221
+ assert a.start == 8
222
+ assert a.end == 8
223
+
224
+ a = imax(interval(1, 2), interval(3, 4), interval(-2, 2, is_valid=False))
225
+ assert a.start == 3
226
+ assert a.end == 4
227
+
228
+
229
+ def test_sinh():
230
+ a = sinh(interval(-1, 1))
231
+ assert a.start == np.sinh(-1)
232
+ assert a.end == np.sinh(1)
233
+
234
+ a = sinh(1)
235
+ assert a.start == np.sinh(1)
236
+ assert a.end == np.sinh(1)
237
+
238
+
239
+ def test_cosh():
240
+ a = cosh(interval(1, 2))
241
+ assert a.start == np.cosh(1)
242
+ assert a.end == np.cosh(2)
243
+ a = cosh(interval(-2, -1))
244
+ assert a.start == np.cosh(-1)
245
+ assert a.end == np.cosh(-2)
246
+
247
+ a = cosh(interval(-2, 1))
248
+ assert a.start == 1
249
+ assert a.end == np.cosh(-2)
250
+
251
+ a = cosh(1)
252
+ assert a.start == np.cosh(1)
253
+ assert a.end == np.cosh(1)
254
+
255
+
256
+ def test_tanh():
257
+ a = tanh(interval(-3, 3))
258
+ assert a.start == np.tanh(-3)
259
+ assert a.end == np.tanh(3)
260
+
261
+ a = tanh(3)
262
+ assert a.start == np.tanh(3)
263
+ assert a.end == np.tanh(3)
264
+
265
+
266
+ def test_asin():
267
+ a = asin(interval(-0.5, 0.5))
268
+ assert a.start == np.arcsin(-0.5)
269
+ assert a.end == np.arcsin(0.5)
270
+
271
+ a = asin(interval(-1.5, 1.5))
272
+ assert a.is_valid is None
273
+ a = asin(interval(-2, -1.5))
274
+ assert a.is_valid is False
275
+
276
+ a = asin(interval(0, 2))
277
+ assert a.is_valid is None
278
+
279
+ a = asin(interval(2, 5))
280
+ assert a.is_valid is False
281
+
282
+ a = asin(0.5)
283
+ assert a.start == np.arcsin(0.5)
284
+ assert a.end == np.arcsin(0.5)
285
+
286
+ a = asin(1.5)
287
+ assert a.is_valid is False
288
+
289
+
290
+ def test_acos():
291
+ a = acos(interval(-0.5, 0.5))
292
+ assert a.start == np.arccos(0.5)
293
+ assert a.end == np.arccos(-0.5)
294
+
295
+ a = acos(interval(-1.5, 1.5))
296
+ assert a.is_valid is None
297
+ a = acos(interval(-2, -1.5))
298
+ assert a.is_valid is False
299
+
300
+ a = acos(interval(0, 2))
301
+ assert a.is_valid is None
302
+
303
+ a = acos(interval(2, 5))
304
+ assert a.is_valid is False
305
+
306
+ a = acos(0.5)
307
+ assert a.start == np.arccos(0.5)
308
+ assert a.end == np.arccos(0.5)
309
+
310
+ a = acos(1.5)
311
+ assert a.is_valid is False
312
+
313
+
314
+ def test_ceil():
315
+ a = ceil(interval(0.2, 0.5))
316
+ assert a.start == 1
317
+ assert a.end == 1
318
+
319
+ a = ceil(interval(0.5, 1.5))
320
+ assert a.start == 1
321
+ assert a.end == 2
322
+ assert a.is_valid is None
323
+
324
+ a = ceil(interval(-5, 5))
325
+ assert a.is_valid is None
326
+
327
+ a = ceil(5.4)
328
+ assert a.start == 6
329
+ assert a.end == 6
330
+
331
+
332
+ def test_floor():
333
+ a = floor(interval(0.2, 0.5))
334
+ assert a.start == 0
335
+ assert a.end == 0
336
+
337
+ a = floor(interval(0.5, 1.5))
338
+ assert a.start == 0
339
+ assert a.end == 1
340
+ assert a.is_valid is None
341
+
342
+ a = floor(interval(-5, 5))
343
+ assert a.is_valid is None
344
+
345
+ a = floor(5.4)
346
+ assert a.start == 5
347
+ assert a.end == 5
348
+
349
+
350
+ def test_asinh():
351
+ a = asinh(interval(1, 2))
352
+ assert a.start == np.arcsinh(1)
353
+ assert a.end == np.arcsinh(2)
354
+
355
+ a = asinh(0.5)
356
+ assert a.start == np.arcsinh(0.5)
357
+ assert a.end == np.arcsinh(0.5)
358
+
359
+
360
+ def test_acosh():
361
+ a = acosh(interval(3, 5))
362
+ assert a.start == np.arccosh(3)
363
+ assert a.end == np.arccosh(5)
364
+
365
+ a = acosh(interval(0, 3))
366
+ assert a.is_valid is None
367
+ a = acosh(interval(-3, 0.5))
368
+ assert a.is_valid is False
369
+
370
+ a = acosh(0.5)
371
+ assert a.is_valid is False
372
+
373
+ a = acosh(2)
374
+ assert a.start == np.arccosh(2)
375
+ assert a.end == np.arccosh(2)
376
+
377
+
378
+ def test_atanh():
379
+ a = atanh(interval(-0.5, 0.5))
380
+ assert a.start == np.arctanh(-0.5)
381
+ assert a.end == np.arctanh(0.5)
382
+
383
+ a = atanh(interval(0, 3))
384
+ assert a.is_valid is None
385
+
386
+ a = atanh(interval(-3, -2))
387
+ assert a.is_valid is False
388
+
389
+ a = atanh(0.5)
390
+ assert a.start == np.arctanh(0.5)
391
+ assert a.end == np.arctanh(0.5)
392
+
393
+ a = atanh(1.5)
394
+ assert a.is_valid is False
395
+
396
+
397
+ def test_Abs():
398
+ assert (Abs(interval(-0.5, 0.5)) == interval(0, 0.5)) == (True, True)
399
+ assert (Abs(interval(-3, -2)) == interval(2, 3)) == (True, True)
400
+ assert (Abs(-3) == interval(3, 3)) == (True, True)
401
+
402
+
403
+ def test_And():
404
+ args = [(True, True), (True, False), (True, None)]
405
+ assert And(*args) == (True, False)
406
+
407
+ args = [(False, True), (None, None), (True, True)]
408
+ assert And(*args) == (False, None)
409
+
410
+
411
+ def test_Or():
412
+ args = [(True, True), (True, False), (False, None)]
413
+ assert Or(*args) == (True, True)
414
+ args = [(None, None), (False, None), (False, False)]
415
+ assert Or(*args) == (None, None)
venv/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/test_interval_membership.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.symbol import Symbol
2
+ from sympy.plotting.intervalmath import interval
3
+ from sympy.plotting.intervalmath.interval_membership import intervalMembership
4
+ from sympy.plotting.experimental_lambdify import experimental_lambdify
5
+ from sympy.testing.pytest import raises
6
+
7
+
8
+ def test_creation():
9
+ assert intervalMembership(True, True)
10
+ raises(TypeError, lambda: intervalMembership(True))
11
+ raises(TypeError, lambda: intervalMembership(True, True, True))
12
+
13
+
14
+ def test_getitem():
15
+ a = intervalMembership(True, False)
16
+ assert a[0] is True
17
+ assert a[1] is False
18
+ raises(IndexError, lambda: a[2])
19
+
20
+
21
+ def test_str():
22
+ a = intervalMembership(True, False)
23
+ assert str(a) == 'intervalMembership(True, False)'
24
+ assert repr(a) == 'intervalMembership(True, False)'
25
+
26
+
27
+ def test_equivalence():
28
+ a = intervalMembership(True, True)
29
+ b = intervalMembership(True, False)
30
+ assert (a == b) is False
31
+ assert (a != b) is True
32
+
33
+ a = intervalMembership(True, False)
34
+ b = intervalMembership(True, False)
35
+ assert (a == b) is True
36
+ assert (a != b) is False
37
+
38
+
39
+ def test_not():
40
+ x = Symbol('x')
41
+
42
+ r1 = x > -1
43
+ r2 = x <= -1
44
+
45
+ i = interval
46
+
47
+ f1 = experimental_lambdify((x,), r1)
48
+ f2 = experimental_lambdify((x,), r2)
49
+
50
+ tt = i(-0.1, 0.1, is_valid=True)
51
+ tn = i(-0.1, 0.1, is_valid=None)
52
+ tf = i(-0.1, 0.1, is_valid=False)
53
+
54
+ assert f1(tt) == ~f2(tt)
55
+ assert f1(tn) == ~f2(tn)
56
+ assert f1(tf) == ~f2(tf)
57
+
58
+ nt = i(0.9, 1.1, is_valid=True)
59
+ nn = i(0.9, 1.1, is_valid=None)
60
+ nf = i(0.9, 1.1, is_valid=False)
61
+
62
+ assert f1(nt) == ~f2(nt)
63
+ assert f1(nn) == ~f2(nn)
64
+ assert f1(nf) == ~f2(nf)
65
+
66
+ ft = i(1.9, 2.1, is_valid=True)
67
+ fn = i(1.9, 2.1, is_valid=None)
68
+ ff = i(1.9, 2.1, is_valid=False)
69
+
70
+ assert f1(ft) == ~f2(ft)
71
+ assert f1(fn) == ~f2(fn)
72
+ assert f1(ff) == ~f2(ff)
73
+
74
+
75
+ def test_boolean():
76
+ # There can be 9*9 test cases in full mapping of the cartesian product.
77
+ # But we only consider 3*3 cases for simplicity.
78
+ s = [
79
+ intervalMembership(False, False),
80
+ intervalMembership(None, None),
81
+ intervalMembership(True, True)
82
+ ]
83
+
84
+ # Reduced tests for 'And'
85
+ a1 = [
86
+ intervalMembership(False, False),
87
+ intervalMembership(False, False),
88
+ intervalMembership(False, False),
89
+ intervalMembership(False, False),
90
+ intervalMembership(None, None),
91
+ intervalMembership(None, None),
92
+ intervalMembership(False, False),
93
+ intervalMembership(None, None),
94
+ intervalMembership(True, True)
95
+ ]
96
+ a1_iter = iter(a1)
97
+ for i in range(len(s)):
98
+ for j in range(len(s)):
99
+ assert s[i] & s[j] == next(a1_iter)
100
+
101
+ # Reduced tests for 'Or'
102
+ a1 = [
103
+ intervalMembership(False, False),
104
+ intervalMembership(None, False),
105
+ intervalMembership(True, False),
106
+ intervalMembership(None, False),
107
+ intervalMembership(None, None),
108
+ intervalMembership(True, None),
109
+ intervalMembership(True, False),
110
+ intervalMembership(True, None),
111
+ intervalMembership(True, True)
112
+ ]
113
+ a1_iter = iter(a1)
114
+ for i in range(len(s)):
115
+ for j in range(len(s)):
116
+ assert s[i] | s[j] == next(a1_iter)
117
+
118
+ # Reduced tests for 'Xor'
119
+ a1 = [
120
+ intervalMembership(False, False),
121
+ intervalMembership(None, False),
122
+ intervalMembership(True, False),
123
+ intervalMembership(None, False),
124
+ intervalMembership(None, None),
125
+ intervalMembership(None, None),
126
+ intervalMembership(True, False),
127
+ intervalMembership(None, None),
128
+ intervalMembership(False, True)
129
+ ]
130
+ a1_iter = iter(a1)
131
+ for i in range(len(s)):
132
+ for j in range(len(s)):
133
+ assert s[i] ^ s[j] == next(a1_iter)
134
+
135
+ # Reduced tests for 'Not'
136
+ a1 = [
137
+ intervalMembership(True, False),
138
+ intervalMembership(None, None),
139
+ intervalMembership(False, True)
140
+ ]
141
+ a1_iter = iter(a1)
142
+ for i in range(len(s)):
143
+ assert ~s[i] == next(a1_iter)
144
+
145
+
146
+ def test_boolean_errors():
147
+ a = intervalMembership(True, True)
148
+ raises(ValueError, lambda: a & 1)
149
+ raises(ValueError, lambda: a | 1)
150
+ raises(ValueError, lambda: a ^ 1)
venv/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/test_intervalmath.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.plotting.intervalmath import interval
2
+ from sympy.testing.pytest import raises
3
+
4
+
5
+ def test_interval():
6
+ assert (interval(1, 1) == interval(1, 1, is_valid=True)) == (True, True)
7
+ assert (interval(1, 1) == interval(1, 1, is_valid=False)) == (True, False)
8
+ assert (interval(1, 1) == interval(1, 1, is_valid=None)) == (True, None)
9
+ assert (interval(1, 1.5) == interval(1, 2)) == (None, True)
10
+ assert (interval(0, 1) == interval(2, 3)) == (False, True)
11
+ assert (interval(0, 1) == interval(1, 2)) == (None, True)
12
+ assert (interval(1, 2) != interval(1, 2)) == (False, True)
13
+ assert (interval(1, 3) != interval(2, 3)) == (None, True)
14
+ assert (interval(1, 3) != interval(-5, -3)) == (True, True)
15
+ assert (
16
+ interval(1, 3, is_valid=False) != interval(-5, -3)) == (True, False)
17
+ assert (interval(1, 3, is_valid=None) != interval(-5, 3)) == (None, None)
18
+ assert (interval(4, 4) != 4) == (False, True)
19
+ assert (interval(1, 1) == 1) == (True, True)
20
+ assert (interval(1, 3, is_valid=False) == interval(1, 3)) == (True, False)
21
+ assert (interval(1, 3, is_valid=None) == interval(1, 3)) == (True, None)
22
+ inter = interval(-5, 5)
23
+ assert (interval(inter) == interval(-5, 5)) == (True, True)
24
+ assert inter.width == 10
25
+ assert 0 in inter
26
+ assert -5 in inter
27
+ assert 5 in inter
28
+ assert interval(0, 3) in inter
29
+ assert interval(-6, 2) not in inter
30
+ assert -5.05 not in inter
31
+ assert 5.3 not in inter
32
+ interb = interval(-float('inf'), float('inf'))
33
+ assert 0 in inter
34
+ assert inter in interb
35
+ assert interval(0, float('inf')) in interb
36
+ assert interval(-float('inf'), 5) in interb
37
+ assert interval(-1e50, 1e50) in interb
38
+ assert (
39
+ -interval(-1, -2, is_valid=False) == interval(1, 2)) == (True, False)
40
+ raises(ValueError, lambda: interval(1, 2, 3))
41
+
42
+
43
+ def test_interval_add():
44
+ assert (interval(1, 2) + interval(2, 3) == interval(3, 5)) == (True, True)
45
+ assert (1 + interval(1, 2) == interval(2, 3)) == (True, True)
46
+ assert (interval(1, 2) + 1 == interval(2, 3)) == (True, True)
47
+ compare = (1 + interval(0, float('inf')) == interval(1, float('inf')))
48
+ assert compare == (True, True)
49
+ a = 1 + interval(2, 5, is_valid=False)
50
+ assert a.is_valid is False
51
+ a = 1 + interval(2, 5, is_valid=None)
52
+ assert a.is_valid is None
53
+ a = interval(2, 5, is_valid=False) + interval(3, 5, is_valid=None)
54
+ assert a.is_valid is False
55
+ a = interval(3, 5) + interval(-1, 1, is_valid=None)
56
+ assert a.is_valid is None
57
+ a = interval(2, 5, is_valid=False) + 1
58
+ assert a.is_valid is False
59
+
60
+
61
+ def test_interval_sub():
62
+ assert (interval(1, 2) - interval(1, 5) == interval(-4, 1)) == (True, True)
63
+ assert (interval(1, 2) - 1 == interval(0, 1)) == (True, True)
64
+ assert (1 - interval(1, 2) == interval(-1, 0)) == (True, True)
65
+ a = 1 - interval(1, 2, is_valid=False)
66
+ assert a.is_valid is False
67
+ a = interval(1, 4, is_valid=None) - 1
68
+ assert a.is_valid is None
69
+ a = interval(1, 3, is_valid=False) - interval(1, 3)
70
+ assert a.is_valid is False
71
+ a = interval(1, 3, is_valid=None) - interval(1, 3)
72
+ assert a.is_valid is None
73
+
74
+
75
+ def test_interval_inequality():
76
+ assert (interval(1, 2) < interval(3, 4)) == (True, True)
77
+ assert (interval(1, 2) < interval(2, 4)) == (None, True)
78
+ assert (interval(1, 2) < interval(-2, 0)) == (False, True)
79
+ assert (interval(1, 2) <= interval(2, 4)) == (True, True)
80
+ assert (interval(1, 2) <= interval(1.5, 6)) == (None, True)
81
+ assert (interval(2, 3) <= interval(1, 2)) == (None, True)
82
+ assert (interval(2, 3) <= interval(1, 1.5)) == (False, True)
83
+ assert (
84
+ interval(1, 2, is_valid=False) <= interval(-2, 0)) == (False, False)
85
+ assert (interval(1, 2, is_valid=None) <= interval(-2, 0)) == (False, None)
86
+ assert (interval(1, 2) <= 1.5) == (None, True)
87
+ assert (interval(1, 2) <= 3) == (True, True)
88
+ assert (interval(1, 2) <= 0) == (False, True)
89
+ assert (interval(5, 8) > interval(2, 3)) == (True, True)
90
+ assert (interval(2, 5) > interval(1, 3)) == (None, True)
91
+ assert (interval(2, 3) > interval(3.1, 5)) == (False, True)
92
+
93
+ assert (interval(-1, 1) == 0) == (None, True)
94
+ assert (interval(-1, 1) == 2) == (False, True)
95
+ assert (interval(-1, 1) != 0) == (None, True)
96
+ assert (interval(-1, 1) != 2) == (True, True)
97
+
98
+ assert (interval(3, 5) > 2) == (True, True)
99
+ assert (interval(3, 5) < 2) == (False, True)
100
+ assert (interval(1, 5) < 2) == (None, True)
101
+ assert (interval(1, 5) > 2) == (None, True)
102
+ assert (interval(0, 1) > 2) == (False, True)
103
+ assert (interval(1, 2) >= interval(0, 1)) == (True, True)
104
+ assert (interval(1, 2) >= interval(0, 1.5)) == (None, True)
105
+ assert (interval(1, 2) >= interval(3, 4)) == (False, True)
106
+ assert (interval(1, 2) >= 0) == (True, True)
107
+ assert (interval(1, 2) >= 1.2) == (None, True)
108
+ assert (interval(1, 2) >= 3) == (False, True)
109
+ assert (2 > interval(0, 1)) == (True, True)
110
+ a = interval(-1, 1, is_valid=False) < interval(2, 5, is_valid=None)
111
+ assert a == (True, False)
112
+ a = interval(-1, 1, is_valid=None) < interval(2, 5, is_valid=False)
113
+ assert a == (True, False)
114
+ a = interval(-1, 1, is_valid=None) < interval(2, 5, is_valid=None)
115
+ assert a == (True, None)
116
+ a = interval(-1, 1, is_valid=False) > interval(-5, -2, is_valid=None)
117
+ assert a == (True, False)
118
+ a = interval(-1, 1, is_valid=None) > interval(-5, -2, is_valid=False)
119
+ assert a == (True, False)
120
+ a = interval(-1, 1, is_valid=None) > interval(-5, -2, is_valid=None)
121
+ assert a == (True, None)
122
+
123
+
124
+ def test_interval_mul():
125
+ assert (
126
+ interval(1, 5) * interval(2, 10) == interval(2, 50)) == (True, True)
127
+ a = interval(-1, 1) * interval(2, 10) == interval(-10, 10)
128
+ assert a == (True, True)
129
+
130
+ a = interval(-1, 1) * interval(-5, 3) == interval(-5, 5)
131
+ assert a == (True, True)
132
+
133
+ assert (interval(1, 3) * 2 == interval(2, 6)) == (True, True)
134
+ assert (3 * interval(-1, 2) == interval(-3, 6)) == (True, True)
135
+
136
+ a = 3 * interval(1, 2, is_valid=False)
137
+ assert a.is_valid is False
138
+
139
+ a = 3 * interval(1, 2, is_valid=None)
140
+ assert a.is_valid is None
141
+
142
+ a = interval(1, 5, is_valid=False) * interval(1, 2, is_valid=None)
143
+ assert a.is_valid is False
144
+
145
+
146
+ def test_interval_div():
147
+ div = interval(1, 2, is_valid=False) / 3
148
+ assert div == interval(-float('inf'), float('inf'), is_valid=False)
149
+
150
+ div = interval(1, 2, is_valid=None) / 3
151
+ assert div == interval(-float('inf'), float('inf'), is_valid=None)
152
+
153
+ div = 3 / interval(1, 2, is_valid=None)
154
+ assert div == interval(-float('inf'), float('inf'), is_valid=None)
155
+ a = interval(1, 2) / 0
156
+ assert a.is_valid is False
157
+ a = interval(0.5, 1) / interval(-1, 0)
158
+ assert a.is_valid is None
159
+ a = interval(0, 1) / interval(0, 1)
160
+ assert a.is_valid is None
161
+
162
+ a = interval(-1, 1) / interval(-1, 1)
163
+ assert a.is_valid is None
164
+
165
+ a = interval(-1, 2) / interval(0.5, 1) == interval(-2.0, 4.0)
166
+ assert a == (True, True)
167
+ a = interval(0, 1) / interval(0.5, 1) == interval(0.0, 2.0)
168
+ assert a == (True, True)
169
+ a = interval(-1, 0) / interval(0.5, 1) == interval(-2.0, 0.0)
170
+ assert a == (True, True)
171
+ a = interval(-0.5, -0.25) / interval(0.5, 1) == interval(-1.0, -0.25)
172
+ assert a == (True, True)
173
+ a = interval(0.5, 1) / interval(0.5, 1) == interval(0.5, 2.0)
174
+ assert a == (True, True)
175
+ a = interval(0.5, 4) / interval(0.5, 1) == interval(0.5, 8.0)
176
+ assert a == (True, True)
177
+ a = interval(-1, -0.5) / interval(0.5, 1) == interval(-2.0, -0.5)
178
+ assert a == (True, True)
179
+ a = interval(-4, -0.5) / interval(0.5, 1) == interval(-8.0, -0.5)
180
+ assert a == (True, True)
181
+ a = interval(-1, 2) / interval(-2, -0.5) == interval(-4.0, 2.0)
182
+ assert a == (True, True)
183
+ a = interval(0, 1) / interval(-2, -0.5) == interval(-2.0, 0.0)
184
+ assert a == (True, True)
185
+ a = interval(-1, 0) / interval(-2, -0.5) == interval(0.0, 2.0)
186
+ assert a == (True, True)
187
+ a = interval(-0.5, -0.25) / interval(-2, -0.5) == interval(0.125, 1.0)
188
+ assert a == (True, True)
189
+ a = interval(0.5, 1) / interval(-2, -0.5) == interval(-2.0, -0.25)
190
+ assert a == (True, True)
191
+ a = interval(0.5, 4) / interval(-2, -0.5) == interval(-8.0, -0.25)
192
+ assert a == (True, True)
193
+ a = interval(-1, -0.5) / interval(-2, -0.5) == interval(0.25, 2.0)
194
+ assert a == (True, True)
195
+ a = interval(-4, -0.5) / interval(-2, -0.5) == interval(0.25, 8.0)
196
+ assert a == (True, True)
197
+ a = interval(-5, 5, is_valid=False) / 2
198
+ assert a.is_valid is False
199
+
200
+ def test_hashable():
201
+ '''
202
+ test that interval objects are hashable.
203
+ this is required in order to be able to put them into the cache, which
204
+ appears to be necessary for plotting in py3k. For details, see:
205
+
206
+ https://github.com/sympy/sympy/pull/2101
207
+ https://github.com/sympy/sympy/issues/6533
208
+ '''
209
+ hash(interval(1, 1))
210
+ hash(interval(1, 1, is_valid=True))
211
+ hash(interval(-4, -0.5))
212
+ hash(interval(-2, -0.5))
213
+ hash(interval(0.25, 8.0))
venv/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_camera.cpython-310.pyc ADDED
Binary file (4.32 kB). View file
 
venv/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_interval.cpython-310.pyc ADDED
Binary file (5.85 kB). View file
 
venv/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_mode.cpython-310.pyc ADDED
Binary file (9.36 kB). View file
 
venv/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_mode_base.cpython-310.pyc ADDED
Binary file (10.1 kB). View file
 
venv/lib/python3.10/site-packages/sympy/plotting/pygletplot/tests/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/sympy/plotting/pygletplot/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (199 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/plotting/pygletplot/tests/__pycache__/test_plotting.cpython-310.pyc ADDED
Binary file (3.21 kB). View file
 
venv/lib/python3.10/site-packages/sympy/plotting/pygletplot/tests/test_plotting.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.external.importtools import import_module
2
+
3
+ disabled = False
4
+
5
+ # if pyglet.gl fails to import, e.g. opengl is missing, we disable the tests
6
+ pyglet_gl = import_module("pyglet.gl", catch=(OSError,))
7
+ pyglet_window = import_module("pyglet.window", catch=(OSError,))
8
+ if not pyglet_gl or not pyglet_window:
9
+ disabled = True
10
+
11
+
12
+ from sympy.core.symbol import symbols
13
+ from sympy.functions.elementary.exponential import log
14
+ from sympy.functions.elementary.trigonometric import (cos, sin)
15
+ x, y, z = symbols('x, y, z')
16
+
17
+
18
+ def test_plot_2d():
19
+ from sympy.plotting.pygletplot import PygletPlot
20
+ p = PygletPlot(x, [x, -5, 5, 4], visible=False)
21
+ p.wait_for_calculations()
22
+
23
+
24
+ def test_plot_2d_discontinuous():
25
+ from sympy.plotting.pygletplot import PygletPlot
26
+ p = PygletPlot(1/x, [x, -1, 1, 2], visible=False)
27
+ p.wait_for_calculations()
28
+
29
+
30
+ def test_plot_3d():
31
+ from sympy.plotting.pygletplot import PygletPlot
32
+ p = PygletPlot(x*y, [x, -5, 5, 5], [y, -5, 5, 5], visible=False)
33
+ p.wait_for_calculations()
34
+
35
+
36
+ def test_plot_3d_discontinuous():
37
+ from sympy.plotting.pygletplot import PygletPlot
38
+ p = PygletPlot(1/x, [x, -3, 3, 6], [y, -1, 1, 1], visible=False)
39
+ p.wait_for_calculations()
40
+
41
+
42
+ def test_plot_2d_polar():
43
+ from sympy.plotting.pygletplot import PygletPlot
44
+ p = PygletPlot(1/x, [x, -1, 1, 4], 'mode=polar', visible=False)
45
+ p.wait_for_calculations()
46
+
47
+
48
+ def test_plot_3d_cylinder():
49
+ from sympy.plotting.pygletplot import PygletPlot
50
+ p = PygletPlot(
51
+ 1/y, [x, 0, 6.282, 4], [y, -1, 1, 4], 'mode=polar;style=solid',
52
+ visible=False)
53
+ p.wait_for_calculations()
54
+
55
+
56
+ def test_plot_3d_spherical():
57
+ from sympy.plotting.pygletplot import PygletPlot
58
+ p = PygletPlot(
59
+ 1, [x, 0, 6.282, 4], [y, 0, 3.141,
60
+ 4], 'mode=spherical;style=wireframe',
61
+ visible=False)
62
+ p.wait_for_calculations()
63
+
64
+
65
+ def test_plot_2d_parametric():
66
+ from sympy.plotting.pygletplot import PygletPlot
67
+ p = PygletPlot(sin(x), cos(x), [x, 0, 6.282, 4], visible=False)
68
+ p.wait_for_calculations()
69
+
70
+
71
+ def test_plot_3d_parametric():
72
+ from sympy.plotting.pygletplot import PygletPlot
73
+ p = PygletPlot(sin(x), cos(x), x/5.0, [x, 0, 6.282, 4], visible=False)
74
+ p.wait_for_calculations()
75
+
76
+
77
+ def _test_plot_log():
78
+ from sympy.plotting.pygletplot import PygletPlot
79
+ p = PygletPlot(log(x), [x, 0, 6.282, 4], 'mode=polar', visible=False)
80
+ p.wait_for_calculations()
81
+
82
+
83
+ def test_plot_integral():
84
+ # Make sure it doesn't treat x as an independent variable
85
+ from sympy.plotting.pygletplot import PygletPlot
86
+ from sympy.integrals.integrals import Integral
87
+ p = PygletPlot(Integral(z*x, (x, 1, z), (z, 1, y)), visible=False)
88
+ p.wait_for_calculations()
venv/lib/python3.10/site-packages/sympy/plotting/tests/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/sympy/plotting/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (188 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/plotting/tests/__pycache__/test_experimental_lambdify.cpython-310.pyc ADDED
Binary file (2.15 kB). View file
 
venv/lib/python3.10/site-packages/sympy/plotting/tests/__pycache__/test_plot.cpython-310.pyc ADDED
Binary file (21.1 kB). View file
 
venv/lib/python3.10/site-packages/sympy/plotting/tests/__pycache__/test_plot_implicit.cpython-310.pyc ADDED
Binary file (4.77 kB). View file
 
venv/lib/python3.10/site-packages/sympy/plotting/tests/__pycache__/test_textplot.cpython-310.pyc ADDED
Binary file (8.02 kB). View file
 
venv/lib/python3.10/site-packages/sympy/plotting/tests/test_experimental_lambdify.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.symbol import symbols, Symbol
2
+ from sympy.functions import Max
3
+ from sympy.plotting.experimental_lambdify import experimental_lambdify
4
+ from sympy.plotting.intervalmath.interval_arithmetic import \
5
+ interval, intervalMembership
6
+
7
+
8
+ # Tests for exception handling in experimental_lambdify
9
+ def test_experimental_lambify():
10
+ x = Symbol('x')
11
+ f = experimental_lambdify([x], Max(x, 5))
12
+ # XXX should f be tested? If f(2) is attempted, an
13
+ # error is raised because a complex produced during wrapping of the arg
14
+ # is being compared with an int.
15
+ assert Max(2, 5) == 5
16
+ assert Max(5, 7) == 7
17
+
18
+ x = Symbol('x-3')
19
+ f = experimental_lambdify([x], x + 1)
20
+ assert f(1) == 2
21
+
22
+
23
+ def test_composite_boolean_region():
24
+ x, y = symbols('x y')
25
+
26
+ r1 = (x - 1)**2 + y**2 < 2
27
+ r2 = (x + 1)**2 + y**2 < 2
28
+
29
+ f = experimental_lambdify((x, y), r1 & r2)
30
+ a = (interval(-0.1, 0.1), interval(-0.1, 0.1))
31
+ assert f(*a) == intervalMembership(True, True)
32
+ a = (interval(-1.1, -0.9), interval(-0.1, 0.1))
33
+ assert f(*a) == intervalMembership(False, True)
34
+ a = (interval(0.9, 1.1), interval(-0.1, 0.1))
35
+ assert f(*a) == intervalMembership(False, True)
36
+ a = (interval(-0.1, 0.1), interval(1.9, 2.1))
37
+ assert f(*a) == intervalMembership(False, True)
38
+
39
+ f = experimental_lambdify((x, y), r1 | r2)
40
+ a = (interval(-0.1, 0.1), interval(-0.1, 0.1))
41
+ assert f(*a) == intervalMembership(True, True)
42
+ a = (interval(-1.1, -0.9), interval(-0.1, 0.1))
43
+ assert f(*a) == intervalMembership(True, True)
44
+ a = (interval(0.9, 1.1), interval(-0.1, 0.1))
45
+ assert f(*a) == intervalMembership(True, True)
46
+ a = (interval(-0.1, 0.1), interval(1.9, 2.1))
47
+ assert f(*a) == intervalMembership(False, True)
48
+
49
+ f = experimental_lambdify((x, y), r1 & ~r2)
50
+ a = (interval(-0.1, 0.1), interval(-0.1, 0.1))
51
+ assert f(*a) == intervalMembership(False, True)
52
+ a = (interval(-1.1, -0.9), interval(-0.1, 0.1))
53
+ assert f(*a) == intervalMembership(False, True)
54
+ a = (interval(0.9, 1.1), interval(-0.1, 0.1))
55
+ assert f(*a) == intervalMembership(True, True)
56
+ a = (interval(-0.1, 0.1), interval(1.9, 2.1))
57
+ assert f(*a) == intervalMembership(False, True)
58
+
59
+ f = experimental_lambdify((x, y), ~r1 & r2)
60
+ a = (interval(-0.1, 0.1), interval(-0.1, 0.1))
61
+ assert f(*a) == intervalMembership(False, True)
62
+ a = (interval(-1.1, -0.9), interval(-0.1, 0.1))
63
+ assert f(*a) == intervalMembership(True, True)
64
+ a = (interval(0.9, 1.1), interval(-0.1, 0.1))
65
+ assert f(*a) == intervalMembership(False, True)
66
+ a = (interval(-0.1, 0.1), interval(1.9, 2.1))
67
+ assert f(*a) == intervalMembership(False, True)
68
+
69
+ f = experimental_lambdify((x, y), ~r1 & ~r2)
70
+ a = (interval(-0.1, 0.1), interval(-0.1, 0.1))
71
+ assert f(*a) == intervalMembership(False, True)
72
+ a = (interval(-1.1, -0.9), interval(-0.1, 0.1))
73
+ assert f(*a) == intervalMembership(False, True)
74
+ a = (interval(0.9, 1.1), interval(-0.1, 0.1))
75
+ assert f(*a) == intervalMembership(False, True)
76
+ a = (interval(-0.1, 0.1), interval(1.9, 2.1))
77
+ assert f(*a) == intervalMembership(True, True)
venv/lib/python3.10/site-packages/sympy/plotting/tests/test_plot.py ADDED
@@ -0,0 +1,764 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from tempfile import TemporaryDirectory
3
+
4
+ from sympy.concrete.summations import Sum
5
+ from sympy.core.numbers import (I, oo, pi)
6
+ from sympy.core.relational import Ne
7
+ from sympy.core.symbol import Symbol
8
+ from sympy.functions.elementary.exponential import (LambertW, exp, exp_polar, log)
9
+ from sympy.functions.elementary.miscellaneous import (real_root, sqrt)
10
+ from sympy.functions.elementary.piecewise import Piecewise
11
+ from sympy.functions.elementary.trigonometric import (cos, sin)
12
+ from sympy.functions.special.hyper import meijerg
13
+ from sympy.integrals.integrals import Integral
14
+ from sympy.logic.boolalg import And
15
+ from sympy.core.singleton import S
16
+ from sympy.core.sympify import sympify
17
+ from sympy.external import import_module
18
+ from sympy.plotting.plot import (
19
+ Plot, plot, plot_parametric, plot3d_parametric_line, plot3d,
20
+ plot3d_parametric_surface)
21
+ from sympy.plotting.plot import (
22
+ unset_show, plot_contour, PlotGrid, DefaultBackend, MatplotlibBackend,
23
+ TextBackend, BaseBackend)
24
+ from sympy.testing.pytest import skip, raises, warns, warns_deprecated_sympy
25
+ from sympy.utilities import lambdify as lambdify_
26
+ from sympy.utilities.exceptions import ignore_warnings
27
+
28
+
29
+ unset_show()
30
+
31
+
32
+ matplotlib = import_module(
33
+ 'matplotlib', min_module_version='1.1.0', catch=(RuntimeError,))
34
+
35
+
36
+ class DummyBackendNotOk(BaseBackend):
37
+ """ Used to verify if users can create their own backends.
38
+ This backend is meant to raise NotImplementedError for methods `show`,
39
+ `save`, `close`.
40
+ """
41
+ pass
42
+
43
+
44
+ class DummyBackendOk(BaseBackend):
45
+ """ Used to verify if users can create their own backends.
46
+ This backend is meant to pass all tests.
47
+ """
48
+ def show(self):
49
+ pass
50
+
51
+ def save(self):
52
+ pass
53
+
54
+ def close(self):
55
+ pass
56
+
57
+
58
+ def test_plot_and_save_1():
59
+ if not matplotlib:
60
+ skip("Matplotlib not the default backend")
61
+
62
+ x = Symbol('x')
63
+ y = Symbol('y')
64
+
65
+ with TemporaryDirectory(prefix='sympy_') as tmpdir:
66
+ ###
67
+ # Examples from the 'introduction' notebook
68
+ ###
69
+ p = plot(x, legend=True, label='f1')
70
+ p = plot(x*sin(x), x*cos(x), label='f2')
71
+ p.extend(p)
72
+ p[0].line_color = lambda a: a
73
+ p[1].line_color = 'b'
74
+ p.title = 'Big title'
75
+ p.xlabel = 'the x axis'
76
+ p[1].label = 'straight line'
77
+ p.legend = True
78
+ p.aspect_ratio = (1, 1)
79
+ p.xlim = (-15, 20)
80
+ filename = 'test_basic_options_and_colors.png'
81
+ p.save(os.path.join(tmpdir, filename))
82
+ p._backend.close()
83
+
84
+ p.extend(plot(x + 1))
85
+ p.append(plot(x + 3, x**2)[1])
86
+ filename = 'test_plot_extend_append.png'
87
+ p.save(os.path.join(tmpdir, filename))
88
+
89
+ p[2] = plot(x**2, (x, -2, 3))
90
+ filename = 'test_plot_setitem.png'
91
+ p.save(os.path.join(tmpdir, filename))
92
+ p._backend.close()
93
+
94
+ p = plot(sin(x), (x, -2*pi, 4*pi))
95
+ filename = 'test_line_explicit.png'
96
+ p.save(os.path.join(tmpdir, filename))
97
+ p._backend.close()
98
+
99
+ p = plot(sin(x))
100
+ filename = 'test_line_default_range.png'
101
+ p.save(os.path.join(tmpdir, filename))
102
+ p._backend.close()
103
+
104
+ p = plot((x**2, (x, -5, 5)), (x**3, (x, -3, 3)))
105
+ filename = 'test_line_multiple_range.png'
106
+ p.save(os.path.join(tmpdir, filename))
107
+ p._backend.close()
108
+
109
+ raises(ValueError, lambda: plot(x, y))
110
+
111
+ #Piecewise plots
112
+ p = plot(Piecewise((1, x > 0), (0, True)), (x, -1, 1))
113
+ filename = 'test_plot_piecewise.png'
114
+ p.save(os.path.join(tmpdir, filename))
115
+ p._backend.close()
116
+
117
+ p = plot(Piecewise((x, x < 1), (x**2, True)), (x, -3, 3))
118
+ filename = 'test_plot_piecewise_2.png'
119
+ p.save(os.path.join(tmpdir, filename))
120
+ p._backend.close()
121
+
122
+ # test issue 7471
123
+ p1 = plot(x)
124
+ p2 = plot(3)
125
+ p1.extend(p2)
126
+ filename = 'test_horizontal_line.png'
127
+ p.save(os.path.join(tmpdir, filename))
128
+ p._backend.close()
129
+
130
+ # test issue 10925
131
+ f = Piecewise((-1, x < -1), (x, And(-1 <= x, x < 0)), \
132
+ (x**2, And(0 <= x, x < 1)), (x**3, x >= 1))
133
+ p = plot(f, (x, -3, 3))
134
+ filename = 'test_plot_piecewise_3.png'
135
+ p.save(os.path.join(tmpdir, filename))
136
+ p._backend.close()
137
+
138
+
139
+ def test_plot_and_save_2():
140
+ if not matplotlib:
141
+ skip("Matplotlib not the default backend")
142
+
143
+ x = Symbol('x')
144
+ y = Symbol('y')
145
+ z = Symbol('z')
146
+
147
+ with TemporaryDirectory(prefix='sympy_') as tmpdir:
148
+ #parametric 2d plots.
149
+ #Single plot with default range.
150
+ p = plot_parametric(sin(x), cos(x))
151
+ filename = 'test_parametric.png'
152
+ p.save(os.path.join(tmpdir, filename))
153
+ p._backend.close()
154
+
155
+ #Single plot with range.
156
+ p = plot_parametric(
157
+ sin(x), cos(x), (x, -5, 5), legend=True, label='parametric_plot')
158
+ filename = 'test_parametric_range.png'
159
+ p.save(os.path.join(tmpdir, filename))
160
+ p._backend.close()
161
+
162
+ #Multiple plots with same range.
163
+ p = plot_parametric((sin(x), cos(x)), (x, sin(x)))
164
+ filename = 'test_parametric_multiple.png'
165
+ p.save(os.path.join(tmpdir, filename))
166
+ p._backend.close()
167
+
168
+ #Multiple plots with different ranges.
169
+ p = plot_parametric(
170
+ (sin(x), cos(x), (x, -3, 3)), (x, sin(x), (x, -5, 5)))
171
+ filename = 'test_parametric_multiple_ranges.png'
172
+ p.save(os.path.join(tmpdir, filename))
173
+ p._backend.close()
174
+
175
+ #depth of recursion specified.
176
+ p = plot_parametric(x, sin(x), depth=13)
177
+ filename = 'test_recursion_depth.png'
178
+ p.save(os.path.join(tmpdir, filename))
179
+ p._backend.close()
180
+
181
+ #No adaptive sampling.
182
+ p = plot_parametric(cos(x), sin(x), adaptive=False, nb_of_points=500)
183
+ filename = 'test_adaptive.png'
184
+ p.save(os.path.join(tmpdir, filename))
185
+ p._backend.close()
186
+
187
+ #3d parametric plots
188
+ p = plot3d_parametric_line(
189
+ sin(x), cos(x), x, legend=True, label='3d_parametric_plot')
190
+ filename = 'test_3d_line.png'
191
+ p.save(os.path.join(tmpdir, filename))
192
+ p._backend.close()
193
+
194
+ p = plot3d_parametric_line(
195
+ (sin(x), cos(x), x, (x, -5, 5)), (cos(x), sin(x), x, (x, -3, 3)))
196
+ filename = 'test_3d_line_multiple.png'
197
+ p.save(os.path.join(tmpdir, filename))
198
+ p._backend.close()
199
+
200
+ p = plot3d_parametric_line(sin(x), cos(x), x, nb_of_points=30)
201
+ filename = 'test_3d_line_points.png'
202
+ p.save(os.path.join(tmpdir, filename))
203
+ p._backend.close()
204
+
205
+ # 3d surface single plot.
206
+ p = plot3d(x * y)
207
+ filename = 'test_surface.png'
208
+ p.save(os.path.join(tmpdir, filename))
209
+ p._backend.close()
210
+
211
+ # Multiple 3D plots with same range.
212
+ p = plot3d(-x * y, x * y, (x, -5, 5))
213
+ filename = 'test_surface_multiple.png'
214
+ p.save(os.path.join(tmpdir, filename))
215
+ p._backend.close()
216
+
217
+ # Multiple 3D plots with different ranges.
218
+ p = plot3d(
219
+ (x * y, (x, -3, 3), (y, -3, 3)), (-x * y, (x, -3, 3), (y, -3, 3)))
220
+ filename = 'test_surface_multiple_ranges.png'
221
+ p.save(os.path.join(tmpdir, filename))
222
+ p._backend.close()
223
+
224
+ # Single Parametric 3D plot
225
+ p = plot3d_parametric_surface(sin(x + y), cos(x - y), x - y)
226
+ filename = 'test_parametric_surface.png'
227
+ p.save(os.path.join(tmpdir, filename))
228
+ p._backend.close()
229
+
230
+ # Multiple Parametric 3D plots.
231
+ p = plot3d_parametric_surface(
232
+ (x*sin(z), x*cos(z), z, (x, -5, 5), (z, -5, 5)),
233
+ (sin(x + y), cos(x - y), x - y, (x, -5, 5), (y, -5, 5)))
234
+ filename = 'test_parametric_surface.png'
235
+ p.save(os.path.join(tmpdir, filename))
236
+ p._backend.close()
237
+
238
+ # Single Contour plot.
239
+ p = plot_contour(sin(x)*sin(y), (x, -5, 5), (y, -5, 5))
240
+ filename = 'test_contour_plot.png'
241
+ p.save(os.path.join(tmpdir, filename))
242
+ p._backend.close()
243
+
244
+ # Multiple Contour plots with same range.
245
+ p = plot_contour(x**2 + y**2, x**3 + y**3, (x, -5, 5), (y, -5, 5))
246
+ filename = 'test_contour_plot.png'
247
+ p.save(os.path.join(tmpdir, filename))
248
+ p._backend.close()
249
+
250
+ # Multiple Contour plots with different range.
251
+ p = plot_contour(
252
+ (x**2 + y**2, (x, -5, 5), (y, -5, 5)),
253
+ (x**3 + y**3, (x, -3, 3), (y, -3, 3)))
254
+ filename = 'test_contour_plot.png'
255
+ p.save(os.path.join(tmpdir, filename))
256
+ p._backend.close()
257
+
258
+
259
+ def test_plot_and_save_3():
260
+ if not matplotlib:
261
+ skip("Matplotlib not the default backend")
262
+
263
+ x = Symbol('x')
264
+ y = Symbol('y')
265
+ z = Symbol('z')
266
+
267
+ with TemporaryDirectory(prefix='sympy_') as tmpdir:
268
+ ###
269
+ # Examples from the 'colors' notebook
270
+ ###
271
+
272
+ p = plot(sin(x))
273
+ p[0].line_color = lambda a: a
274
+ filename = 'test_colors_line_arity1.png'
275
+ p.save(os.path.join(tmpdir, filename))
276
+
277
+ p[0].line_color = lambda a, b: b
278
+ filename = 'test_colors_line_arity2.png'
279
+ p.save(os.path.join(tmpdir, filename))
280
+ p._backend.close()
281
+
282
+ p = plot(x*sin(x), x*cos(x), (x, 0, 10))
283
+ p[0].line_color = lambda a: a
284
+ filename = 'test_colors_param_line_arity1.png'
285
+ p.save(os.path.join(tmpdir, filename))
286
+
287
+ p[0].line_color = lambda a, b: a
288
+ filename = 'test_colors_param_line_arity1.png'
289
+ p.save(os.path.join(tmpdir, filename))
290
+
291
+ p[0].line_color = lambda a, b: b
292
+ filename = 'test_colors_param_line_arity2b.png'
293
+ p.save(os.path.join(tmpdir, filename))
294
+ p._backend.close()
295
+
296
+ p = plot3d_parametric_line(sin(x) + 0.1*sin(x)*cos(7*x),
297
+ cos(x) + 0.1*cos(x)*cos(7*x),
298
+ 0.1*sin(7*x),
299
+ (x, 0, 2*pi))
300
+ p[0].line_color = lambdify_(x, sin(4*x))
301
+ filename = 'test_colors_3d_line_arity1.png'
302
+ p.save(os.path.join(tmpdir, filename))
303
+ p[0].line_color = lambda a, b: b
304
+ filename = 'test_colors_3d_line_arity2.png'
305
+ p.save(os.path.join(tmpdir, filename))
306
+ p[0].line_color = lambda a, b, c: c
307
+ filename = 'test_colors_3d_line_arity3.png'
308
+ p.save(os.path.join(tmpdir, filename))
309
+ p._backend.close()
310
+
311
+ p = plot3d(sin(x)*y, (x, 0, 6*pi), (y, -5, 5))
312
+ p[0].surface_color = lambda a: a
313
+ filename = 'test_colors_surface_arity1.png'
314
+ p.save(os.path.join(tmpdir, filename))
315
+ p[0].surface_color = lambda a, b: b
316
+ filename = 'test_colors_surface_arity2.png'
317
+ p.save(os.path.join(tmpdir, filename))
318
+ p[0].surface_color = lambda a, b, c: c
319
+ filename = 'test_colors_surface_arity3a.png'
320
+ p.save(os.path.join(tmpdir, filename))
321
+ p[0].surface_color = lambdify_((x, y, z), sqrt((x - 3*pi)**2 + y**2))
322
+ filename = 'test_colors_surface_arity3b.png'
323
+ p.save(os.path.join(tmpdir, filename))
324
+ p._backend.close()
325
+
326
+ p = plot3d_parametric_surface(x * cos(4 * y), x * sin(4 * y), y,
327
+ (x, -1, 1), (y, -1, 1))
328
+ p[0].surface_color = lambda a: a
329
+ filename = 'test_colors_param_surf_arity1.png'
330
+ p.save(os.path.join(tmpdir, filename))
331
+ p[0].surface_color = lambda a, b: a*b
332
+ filename = 'test_colors_param_surf_arity2.png'
333
+ p.save(os.path.join(tmpdir, filename))
334
+ p[0].surface_color = lambdify_((x, y, z), sqrt(x**2 + y**2 + z**2))
335
+ filename = 'test_colors_param_surf_arity3.png'
336
+ p.save(os.path.join(tmpdir, filename))
337
+ p._backend.close()
338
+
339
+
340
+ def test_plot_and_save_4():
341
+ if not matplotlib:
342
+ skip("Matplotlib not the default backend")
343
+
344
+ x = Symbol('x')
345
+ y = Symbol('y')
346
+
347
+ ###
348
+ # Examples from the 'advanced' notebook
349
+ ###
350
+
351
+ # XXX: This raises the warning "The evaluation of the expression is
352
+ # problematic. We are trying a failback method that may still work. Please
353
+ # report this as a bug." It has to use the fallback because using evalf()
354
+ # is the only way to evaluate the integral. We should perhaps just remove
355
+ # that warning.
356
+ with TemporaryDirectory(prefix='sympy_') as tmpdir:
357
+ with warns(
358
+ UserWarning,
359
+ match="The evaluation of the expression is problematic",
360
+ test_stacklevel=False,
361
+ ):
362
+ i = Integral(log((sin(x)**2 + 1)*sqrt(x**2 + 1)), (x, 0, y))
363
+ p = plot(i, (y, 1, 5))
364
+ filename = 'test_advanced_integral.png'
365
+ p.save(os.path.join(tmpdir, filename))
366
+ p._backend.close()
367
+
368
+
369
+ def test_plot_and_save_5():
370
+ if not matplotlib:
371
+ skip("Matplotlib not the default backend")
372
+
373
+ x = Symbol('x')
374
+ y = Symbol('y')
375
+
376
+ with TemporaryDirectory(prefix='sympy_') as tmpdir:
377
+ s = Sum(1/x**y, (x, 1, oo))
378
+ p = plot(s, (y, 2, 10))
379
+ filename = 'test_advanced_inf_sum.png'
380
+ p.save(os.path.join(tmpdir, filename))
381
+ p._backend.close()
382
+
383
+ p = plot(Sum(1/x, (x, 1, y)), (y, 2, 10), show=False)
384
+ p[0].only_integers = True
385
+ p[0].steps = True
386
+ filename = 'test_advanced_fin_sum.png'
387
+
388
+ # XXX: This should be fixed in experimental_lambdify or by using
389
+ # ordinary lambdify so that it doesn't warn. The error results from
390
+ # passing an array of values as the integration limit.
391
+ #
392
+ # UserWarning: The evaluation of the expression is problematic. We are
393
+ # trying a failback method that may still work. Please report this as a
394
+ # bug.
395
+ with ignore_warnings(UserWarning):
396
+ p.save(os.path.join(tmpdir, filename))
397
+
398
+ p._backend.close()
399
+
400
+
401
+ def test_plot_and_save_6():
402
+ if not matplotlib:
403
+ skip("Matplotlib not the default backend")
404
+
405
+ x = Symbol('x')
406
+
407
+ with TemporaryDirectory(prefix='sympy_') as tmpdir:
408
+ filename = 'test.png'
409
+ ###
410
+ # Test expressions that can not be translated to np and generate complex
411
+ # results.
412
+ ###
413
+ p = plot(sin(x) + I*cos(x))
414
+ p.save(os.path.join(tmpdir, filename))
415
+
416
+ with ignore_warnings(RuntimeWarning):
417
+ p = plot(sqrt(sqrt(-x)))
418
+ p.save(os.path.join(tmpdir, filename))
419
+
420
+ p = plot(LambertW(x))
421
+ p.save(os.path.join(tmpdir, filename))
422
+ p = plot(sqrt(LambertW(x)))
423
+ p.save(os.path.join(tmpdir, filename))
424
+
425
+ #Characteristic function of a StudentT distribution with nu=10
426
+ x1 = 5 * x**2 * exp_polar(-I*pi)/2
427
+ m1 = meijerg(((1 / 2,), ()), ((5, 0, 1 / 2), ()), x1)
428
+ x2 = 5*x**2 * exp_polar(I*pi)/2
429
+ m2 = meijerg(((1/2,), ()), ((5, 0, 1/2), ()), x2)
430
+ expr = (m1 + m2) / (48 * pi)
431
+ p = plot(expr, (x, 1e-6, 1e-2))
432
+ p.save(os.path.join(tmpdir, filename))
433
+
434
+
435
+ def test_plotgrid_and_save():
436
+ if not matplotlib:
437
+ skip("Matplotlib not the default backend")
438
+
439
+ x = Symbol('x')
440
+ y = Symbol('y')
441
+
442
+ with TemporaryDirectory(prefix='sympy_') as tmpdir:
443
+ p1 = plot(x)
444
+ p2 = plot_parametric((sin(x), cos(x)), (x, sin(x)), show=False)
445
+ p3 = plot_parametric(
446
+ cos(x), sin(x), adaptive=False, nb_of_points=500, show=False)
447
+ p4 = plot3d_parametric_line(sin(x), cos(x), x, show=False)
448
+ # symmetric grid
449
+ p = PlotGrid(2, 2, p1, p2, p3, p4)
450
+ filename = 'test_grid1.png'
451
+ p.save(os.path.join(tmpdir, filename))
452
+ p._backend.close()
453
+
454
+ # grid size greater than the number of subplots
455
+ p = PlotGrid(3, 4, p1, p2, p3, p4)
456
+ filename = 'test_grid2.png'
457
+ p.save(os.path.join(tmpdir, filename))
458
+ p._backend.close()
459
+
460
+ p5 = plot(cos(x),(x, -pi, pi), show=False)
461
+ p5[0].line_color = lambda a: a
462
+ p6 = plot(Piecewise((1, x > 0), (0, True)), (x, -1, 1), show=False)
463
+ p7 = plot_contour(
464
+ (x**2 + y**2, (x, -5, 5), (y, -5, 5)),
465
+ (x**3 + y**3, (x, -3, 3), (y, -3, 3)), show=False)
466
+ # unsymmetric grid (subplots in one line)
467
+ p = PlotGrid(1, 3, p5, p6, p7)
468
+ filename = 'test_grid3.png'
469
+ p.save(os.path.join(tmpdir, filename))
470
+ p._backend.close()
471
+
472
+
473
+ def test_append_issue_7140():
474
+ if not matplotlib:
475
+ skip("Matplotlib not the default backend")
476
+
477
+ x = Symbol('x')
478
+ p1 = plot(x)
479
+ p2 = plot(x**2)
480
+ plot(x + 2)
481
+
482
+ # append a series
483
+ p2.append(p1[0])
484
+ assert len(p2._series) == 2
485
+
486
+ with raises(TypeError):
487
+ p1.append(p2)
488
+
489
+ with raises(TypeError):
490
+ p1.append(p2._series)
491
+
492
+
493
+ def test_issue_15265():
494
+ if not matplotlib:
495
+ skip("Matplotlib not the default backend")
496
+
497
+ x = Symbol('x')
498
+ eqn = sin(x)
499
+
500
+ p = plot(eqn, xlim=(-S.Pi, S.Pi), ylim=(-1, 1))
501
+ p._backend.close()
502
+
503
+ p = plot(eqn, xlim=(-1, 1), ylim=(-S.Pi, S.Pi))
504
+ p._backend.close()
505
+
506
+ p = plot(eqn, xlim=(-1, 1), ylim=(sympify('-3.14'), sympify('3.14')))
507
+ p._backend.close()
508
+
509
+ p = plot(eqn, xlim=(sympify('-3.14'), sympify('3.14')), ylim=(-1, 1))
510
+ p._backend.close()
511
+
512
+ raises(ValueError,
513
+ lambda: plot(eqn, xlim=(-S.ImaginaryUnit, 1), ylim=(-1, 1)))
514
+
515
+ raises(ValueError,
516
+ lambda: plot(eqn, xlim=(-1, 1), ylim=(-1, S.ImaginaryUnit)))
517
+
518
+ raises(ValueError,
519
+ lambda: plot(eqn, xlim=(S.NegativeInfinity, 1), ylim=(-1, 1)))
520
+
521
+ raises(ValueError,
522
+ lambda: plot(eqn, xlim=(-1, 1), ylim=(-1, S.Infinity)))
523
+
524
+
525
+ def test_empty_Plot():
526
+ if not matplotlib:
527
+ skip("Matplotlib not the default backend")
528
+
529
+ # No exception showing an empty plot
530
+ plot()
531
+ p = Plot()
532
+ p.show()
533
+
534
+
535
+ def test_issue_17405():
536
+ if not matplotlib:
537
+ skip("Matplotlib not the default backend")
538
+
539
+ x = Symbol('x')
540
+ f = x**0.3 - 10*x**3 + x**2
541
+ p = plot(f, (x, -10, 10), show=False)
542
+ # Random number of segments, probably more than 100, but we want to see
543
+ # that there are segments generated, as opposed to when the bug was present
544
+
545
+ # RuntimeWarning: invalid value encountered in double_scalars
546
+ with ignore_warnings(RuntimeWarning):
547
+ assert len(p[0].get_data()[0]) >= 30
548
+
549
+
550
+ def test_logplot_PR_16796():
551
+ if not matplotlib:
552
+ skip("Matplotlib not the default backend")
553
+
554
+ x = Symbol('x')
555
+ p = plot(x, (x, .001, 100), xscale='log', show=False)
556
+ # Random number of segments, probably more than 100, but we want to see
557
+ # that there are segments generated, as opposed to when the bug was present
558
+ assert len(p[0].get_data()[0]) >= 30
559
+ assert p[0].end == 100.0
560
+ assert p[0].start == .001
561
+
562
+
563
+ def test_issue_16572():
564
+ if not matplotlib:
565
+ skip("Matplotlib not the default backend")
566
+
567
+ x = Symbol('x')
568
+ p = plot(LambertW(x), show=False)
569
+ # Random number of segments, probably more than 50, but we want to see
570
+ # that there are segments generated, as opposed to when the bug was present
571
+ assert len(p[0].get_data()[0]) >= 30
572
+
573
+
574
+ def test_issue_11865():
575
+ if not matplotlib:
576
+ skip("Matplotlib not the default backend")
577
+
578
+ k = Symbol('k', integer=True)
579
+ f = Piecewise((-I*exp(I*pi*k)/k + I*exp(-I*pi*k)/k, Ne(k, 0)), (2*pi, True))
580
+ p = plot(f, show=False)
581
+ # Random number of segments, probably more than 100, but we want to see
582
+ # that there are segments generated, as opposed to when the bug was present
583
+ # and that there are no exceptions.
584
+ assert len(p[0].get_data()[0]) >= 30
585
+
586
+
587
+ def test_issue_11461():
588
+ if not matplotlib:
589
+ skip("Matplotlib not the default backend")
590
+
591
+ x = Symbol('x')
592
+ p = plot(real_root((log(x/(x-2))), 3), show=False)
593
+ # Random number of segments, probably more than 100, but we want to see
594
+ # that there are segments generated, as opposed to when the bug was present
595
+ # and that there are no exceptions.
596
+ assert len(p[0].get_data()[0]) >= 30
597
+
598
+
599
+ def test_issue_11764():
600
+ if not matplotlib:
601
+ skip("Matplotlib not the default backend")
602
+
603
+ x = Symbol('x')
604
+ p = plot_parametric(cos(x), sin(x), (x, 0, 2 * pi), aspect_ratio=(1,1), show=False)
605
+ assert p.aspect_ratio == (1, 1)
606
+ # Random number of segments, probably more than 100, but we want to see
607
+ # that there are segments generated, as opposed to when the bug was present
608
+ assert len(p[0].get_data()[0]) >= 30
609
+
610
+
611
+ def test_issue_13516():
612
+ if not matplotlib:
613
+ skip("Matplotlib not the default backend")
614
+
615
+ x = Symbol('x')
616
+
617
+ pm = plot(sin(x), backend="matplotlib", show=False)
618
+ assert pm.backend == MatplotlibBackend
619
+ assert len(pm[0].get_data()[0]) >= 30
620
+
621
+ pt = plot(sin(x), backend="text", show=False)
622
+ assert pt.backend == TextBackend
623
+ assert len(pt[0].get_data()[0]) >= 30
624
+
625
+ pd = plot(sin(x), backend="default", show=False)
626
+ assert pd.backend == DefaultBackend
627
+ assert len(pd[0].get_data()[0]) >= 30
628
+
629
+ p = plot(sin(x), show=False)
630
+ assert p.backend == DefaultBackend
631
+ assert len(p[0].get_data()[0]) >= 30
632
+
633
+
634
+ def test_plot_limits():
635
+ if not matplotlib:
636
+ skip("Matplotlib not the default backend")
637
+
638
+ x = Symbol('x')
639
+ p = plot(x, x**2, (x, -10, 10))
640
+ backend = p._backend
641
+
642
+ xmin, xmax = backend.ax[0].get_xlim()
643
+ assert abs(xmin + 10) < 2
644
+ assert abs(xmax - 10) < 2
645
+ ymin, ymax = backend.ax[0].get_ylim()
646
+ assert abs(ymin + 10) < 10
647
+ assert abs(ymax - 100) < 10
648
+
649
+
650
+ def test_plot3d_parametric_line_limits():
651
+ if not matplotlib:
652
+ skip("Matplotlib not the default backend")
653
+
654
+ x = Symbol('x')
655
+
656
+ v1 = (2*cos(x), 2*sin(x), 2*x, (x, -5, 5))
657
+ v2 = (sin(x), cos(x), x, (x, -5, 5))
658
+ p = plot3d_parametric_line(v1, v2)
659
+ backend = p._backend
660
+
661
+ xmin, xmax = backend.ax[0].get_xlim()
662
+ assert abs(xmin + 2) < 1e-2
663
+ assert abs(xmax - 2) < 1e-2
664
+ ymin, ymax = backend.ax[0].get_ylim()
665
+ assert abs(ymin + 2) < 1e-2
666
+ assert abs(ymax - 2) < 1e-2
667
+ zmin, zmax = backend.ax[0].get_zlim()
668
+ assert abs(zmin + 10) < 1e-2
669
+ assert abs(zmax - 10) < 1e-2
670
+
671
+ p = plot3d_parametric_line(v2, v1)
672
+ backend = p._backend
673
+
674
+ xmin, xmax = backend.ax[0].get_xlim()
675
+ assert abs(xmin + 2) < 1e-2
676
+ assert abs(xmax - 2) < 1e-2
677
+ ymin, ymax = backend.ax[0].get_ylim()
678
+ assert abs(ymin + 2) < 1e-2
679
+ assert abs(ymax - 2) < 1e-2
680
+ zmin, zmax = backend.ax[0].get_zlim()
681
+ assert abs(zmin + 10) < 1e-2
682
+ assert abs(zmax - 10) < 1e-2
683
+
684
+ def test_plot_size():
685
+ if not matplotlib:
686
+ skip("Matplotlib not the default backend")
687
+
688
+ x = Symbol('x')
689
+
690
+ p1 = plot(sin(x), backend="matplotlib", size=(8, 4))
691
+ s1 = p1._backend.fig.get_size_inches()
692
+ assert (s1[0] == 8) and (s1[1] == 4)
693
+ p2 = plot(sin(x), backend="matplotlib", size=(5, 10))
694
+ s2 = p2._backend.fig.get_size_inches()
695
+ assert (s2[0] == 5) and (s2[1] == 10)
696
+ p3 = PlotGrid(2, 1, p1, p2, size=(6, 2))
697
+ s3 = p3._backend.fig.get_size_inches()
698
+ assert (s3[0] == 6) and (s3[1] == 2)
699
+
700
+ with raises(ValueError):
701
+ plot(sin(x), backend="matplotlib", size=(-1, 3))
702
+
703
+ def test_issue_20113():
704
+ if not matplotlib:
705
+ skip("Matplotlib not the default backend")
706
+
707
+ x = Symbol('x')
708
+
709
+ # verify the capability to use custom backends
710
+ with raises(TypeError):
711
+ plot(sin(x), backend=Plot, show=False)
712
+ p2 = plot(sin(x), backend=MatplotlibBackend, show=False)
713
+ assert p2.backend == MatplotlibBackend
714
+ assert len(p2[0].get_data()[0]) >= 30
715
+ p3 = plot(sin(x), backend=DummyBackendOk, show=False)
716
+ assert p3.backend == DummyBackendOk
717
+ assert len(p3[0].get_data()[0]) >= 30
718
+
719
+ # test for an improper coded backend
720
+ p4 = plot(sin(x), backend=DummyBackendNotOk, show=False)
721
+ assert p4.backend == DummyBackendNotOk
722
+ assert len(p4[0].get_data()[0]) >= 30
723
+ with raises(NotImplementedError):
724
+ p4.show()
725
+ with raises(NotImplementedError):
726
+ p4.save("test/path")
727
+ with raises(NotImplementedError):
728
+ p4._backend.close()
729
+
730
+ def test_custom_coloring():
731
+ x = Symbol('x')
732
+ y = Symbol('y')
733
+ plot(cos(x), line_color=lambda a: a)
734
+ plot(cos(x), line_color=1)
735
+ plot(cos(x), line_color="r")
736
+ plot_parametric(cos(x), sin(x), line_color=lambda a: a)
737
+ plot_parametric(cos(x), sin(x), line_color=1)
738
+ plot_parametric(cos(x), sin(x), line_color="r")
739
+ plot3d_parametric_line(cos(x), sin(x), x, line_color=lambda a: a)
740
+ plot3d_parametric_line(cos(x), sin(x), x, line_color=1)
741
+ plot3d_parametric_line(cos(x), sin(x), x, line_color="r")
742
+ plot3d_parametric_surface(cos(x + y), sin(x - y), x - y,
743
+ (x, -5, 5), (y, -5, 5),
744
+ surface_color=lambda a, b: a**2 + b**2)
745
+ plot3d_parametric_surface(cos(x + y), sin(x - y), x - y,
746
+ (x, -5, 5), (y, -5, 5),
747
+ surface_color=1)
748
+ plot3d_parametric_surface(cos(x + y), sin(x - y), x - y,
749
+ (x, -5, 5), (y, -5, 5),
750
+ surface_color="r")
751
+ plot3d(x*y, (x, -5, 5), (y, -5, 5),
752
+ surface_color=lambda a, b: a**2 + b**2)
753
+ plot3d(x*y, (x, -5, 5), (y, -5, 5), surface_color=1)
754
+ plot3d(x*y, (x, -5, 5), (y, -5, 5), surface_color="r")
755
+
756
+ def test_deprecated_get_segments():
757
+ if not matplotlib:
758
+ skip("Matplotlib not the default backend")
759
+
760
+ x = Symbol('x')
761
+ f = sin(x)
762
+ p = plot(f, (x, -10, 10), show=False)
763
+ with warns_deprecated_sympy():
764
+ p[0].get_segments()
venv/lib/python3.10/site-packages/sympy/plotting/tests/test_plot_implicit.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import (I, pi)
2
+ from sympy.core.relational import Eq
3
+ from sympy.core.symbol import (Symbol, symbols)
4
+ from sympy.functions.elementary.complexes import re
5
+ from sympy.functions.elementary.exponential import exp
6
+ from sympy.functions.elementary.trigonometric import (cos, sin, tan)
7
+ from sympy.logic.boolalg import (And, Or)
8
+ from sympy.plotting.plot_implicit import plot_implicit
9
+ from sympy.plotting.plot import unset_show
10
+ from tempfile import NamedTemporaryFile, mkdtemp
11
+ from sympy.testing.pytest import skip, warns, XFAIL
12
+ from sympy.external import import_module
13
+ from sympy.testing.tmpfiles import TmpFileManager
14
+
15
+ import os
16
+
17
+ #Set plots not to show
18
+ unset_show()
19
+
20
+ def tmp_file(dir=None, name=''):
21
+ return NamedTemporaryFile(
22
+ suffix='.png', dir=dir, delete=False).name
23
+
24
+ def plot_and_save(expr, *args, name='', dir=None, **kwargs):
25
+ p = plot_implicit(expr, *args, **kwargs)
26
+ p.save(tmp_file(dir=dir, name=name))
27
+ # Close the plot to avoid a warning from matplotlib
28
+ p._backend.close()
29
+
30
+ def plot_implicit_tests(name):
31
+ temp_dir = mkdtemp()
32
+ TmpFileManager.tmp_folder(temp_dir)
33
+ x = Symbol('x')
34
+ y = Symbol('y')
35
+ #implicit plot tests
36
+ plot_and_save(Eq(y, cos(x)), (x, -5, 5), (y, -2, 2), name=name, dir=temp_dir)
37
+ plot_and_save(Eq(y**2, x**3 - x), (x, -5, 5),
38
+ (y, -4, 4), name=name, dir=temp_dir)
39
+ plot_and_save(y > 1 / x, (x, -5, 5),
40
+ (y, -2, 2), name=name, dir=temp_dir)
41
+ plot_and_save(y < 1 / tan(x), (x, -5, 5),
42
+ (y, -2, 2), name=name, dir=temp_dir)
43
+ plot_and_save(y >= 2 * sin(x) * cos(x), (x, -5, 5),
44
+ (y, -2, 2), name=name, dir=temp_dir)
45
+ plot_and_save(y <= x**2, (x, -3, 3),
46
+ (y, -1, 5), name=name, dir=temp_dir)
47
+
48
+ #Test all input args for plot_implicit
49
+ plot_and_save(Eq(y**2, x**3 - x), dir=temp_dir)
50
+ plot_and_save(Eq(y**2, x**3 - x), adaptive=False, dir=temp_dir)
51
+ plot_and_save(Eq(y**2, x**3 - x), adaptive=False, points=500, dir=temp_dir)
52
+ plot_and_save(y > x, (x, -5, 5), dir=temp_dir)
53
+ plot_and_save(And(y > exp(x), y > x + 2), dir=temp_dir)
54
+ plot_and_save(Or(y > x, y > -x), dir=temp_dir)
55
+ plot_and_save(x**2 - 1, (x, -5, 5), dir=temp_dir)
56
+ plot_and_save(x**2 - 1, dir=temp_dir)
57
+ plot_and_save(y > x, depth=-5, dir=temp_dir)
58
+ plot_and_save(y > x, depth=5, dir=temp_dir)
59
+ plot_and_save(y > cos(x), adaptive=False, dir=temp_dir)
60
+ plot_and_save(y < cos(x), adaptive=False, dir=temp_dir)
61
+ plot_and_save(And(y > cos(x), Or(y > x, Eq(y, x))), dir=temp_dir)
62
+ plot_and_save(y - cos(pi / x), dir=temp_dir)
63
+
64
+ plot_and_save(x**2 - 1, title='An implicit plot', dir=temp_dir)
65
+
66
+ @XFAIL
67
+ def test_no_adaptive_meshing():
68
+ matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,))
69
+ if matplotlib:
70
+ try:
71
+ temp_dir = mkdtemp()
72
+ TmpFileManager.tmp_folder(temp_dir)
73
+ x = Symbol('x')
74
+ y = Symbol('y')
75
+ # Test plots which cannot be rendered using the adaptive algorithm
76
+
77
+ # This works, but it triggers a deprecation warning from sympify(). The
78
+ # code needs to be updated to detect if interval math is supported without
79
+ # relying on random AttributeErrors.
80
+ with warns(UserWarning, match="Adaptive meshing could not be applied"):
81
+ plot_and_save(Eq(y, re(cos(x) + I*sin(x))), name='test', dir=temp_dir)
82
+ finally:
83
+ TmpFileManager.cleanup()
84
+ else:
85
+ skip("Matplotlib not the default backend")
86
+ def test_line_color():
87
+ x, y = symbols('x, y')
88
+ p = plot_implicit(x**2 + y**2 - 1, line_color="green", show=False)
89
+ assert p._series[0].line_color == "green"
90
+ p = plot_implicit(x**2 + y**2 - 1, line_color='r', show=False)
91
+ assert p._series[0].line_color == "r"
92
+
93
+ def test_matplotlib():
94
+ matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,))
95
+ if matplotlib:
96
+ try:
97
+ plot_implicit_tests('test')
98
+ test_line_color()
99
+ finally:
100
+ TmpFileManager.cleanup()
101
+ else:
102
+ skip("Matplotlib not the default backend")
103
+
104
+
105
+ def test_region_and():
106
+ matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,))
107
+ if not matplotlib:
108
+ skip("Matplotlib not the default backend")
109
+
110
+ from matplotlib.testing.compare import compare_images
111
+ test_directory = os.path.dirname(os.path.abspath(__file__))
112
+
113
+ try:
114
+ temp_dir = mkdtemp()
115
+ TmpFileManager.tmp_folder(temp_dir)
116
+
117
+ x, y = symbols('x y')
118
+
119
+ r1 = (x - 1)**2 + y**2 < 2
120
+ r2 = (x + 1)**2 + y**2 < 2
121
+
122
+ test_filename = tmp_file(dir=temp_dir, name="test_region_and")
123
+ cmp_filename = os.path.join(test_directory, "test_region_and.png")
124
+ p = plot_implicit(r1 & r2, x, y)
125
+ p.save(test_filename)
126
+ compare_images(cmp_filename, test_filename, 0.005)
127
+
128
+ test_filename = tmp_file(dir=temp_dir, name="test_region_or")
129
+ cmp_filename = os.path.join(test_directory, "test_region_or.png")
130
+ p = plot_implicit(r1 | r2, x, y)
131
+ p.save(test_filename)
132
+ compare_images(cmp_filename, test_filename, 0.005)
133
+
134
+ test_filename = tmp_file(dir=temp_dir, name="test_region_not")
135
+ cmp_filename = os.path.join(test_directory, "test_region_not.png")
136
+ p = plot_implicit(~r1, x, y)
137
+ p.save(test_filename)
138
+ compare_images(cmp_filename, test_filename, 0.005)
139
+
140
+ test_filename = tmp_file(dir=temp_dir, name="test_region_xor")
141
+ cmp_filename = os.path.join(test_directory, "test_region_xor.png")
142
+ p = plot_implicit(r1 ^ r2, x, y)
143
+ p.save(test_filename)
144
+ compare_images(cmp_filename, test_filename, 0.005)
145
+ finally:
146
+ TmpFileManager.cleanup()
venv/lib/python3.10/site-packages/sympy/plotting/tests/test_textplot.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.singleton import S
2
+ from sympy.core.symbol import Symbol
3
+ from sympy.functions.elementary.exponential import log
4
+ from sympy.functions.elementary.miscellaneous import sqrt
5
+ from sympy.functions.elementary.trigonometric import sin
6
+ from sympy.plotting.textplot import textplot_str
7
+
8
+ from sympy.utilities.exceptions import ignore_warnings
9
+
10
+
11
+ def test_axes_alignment():
12
+ x = Symbol('x')
13
+ lines = [
14
+ ' 1 | ..',
15
+ ' | ... ',
16
+ ' | .. ',
17
+ ' | ... ',
18
+ ' | ... ',
19
+ ' | .. ',
20
+ ' | ... ',
21
+ ' | ... ',
22
+ ' | .. ',
23
+ ' | ... ',
24
+ ' 0 |--------------------------...--------------------------',
25
+ ' | ... ',
26
+ ' | .. ',
27
+ ' | ... ',
28
+ ' | ... ',
29
+ ' | .. ',
30
+ ' | ... ',
31
+ ' | ... ',
32
+ ' | .. ',
33
+ ' | ... ',
34
+ ' -1 |_______________________________________________________',
35
+ ' -1 0 1'
36
+ ]
37
+ assert lines == list(textplot_str(x, -1, 1))
38
+
39
+ lines = [
40
+ ' 1 | ..',
41
+ ' | .... ',
42
+ ' | ... ',
43
+ ' | ... ',
44
+ ' | .... ',
45
+ ' | ... ',
46
+ ' | ... ',
47
+ ' | .... ',
48
+ ' 0 |--------------------------...--------------------------',
49
+ ' | .... ',
50
+ ' | ... ',
51
+ ' | ... ',
52
+ ' | .... ',
53
+ ' | ... ',
54
+ ' | ... ',
55
+ ' | .... ',
56
+ ' -1 |_______________________________________________________',
57
+ ' -1 0 1'
58
+ ]
59
+ assert lines == list(textplot_str(x, -1, 1, H=17))
60
+
61
+
62
+ def test_singularity():
63
+ x = Symbol('x')
64
+ lines = [
65
+ ' 54 | . ',
66
+ ' | ',
67
+ ' | ',
68
+ ' | ',
69
+ ' | ',' | ',
70
+ ' | ',
71
+ ' | ',
72
+ ' | ',
73
+ ' | ',
74
+ ' 27.5 |--.----------------------------------------------------',
75
+ ' | ',
76
+ ' | ',
77
+ ' | ',
78
+ ' | . ',
79
+ ' | \\ ',
80
+ ' | \\ ',
81
+ ' | .. ',
82
+ ' | ... ',
83
+ ' | ............. ',
84
+ ' 1 |_______________________________________________________',
85
+ ' 0 0.5 1'
86
+ ]
87
+ assert lines == list(textplot_str(1/x, 0, 1))
88
+
89
+ lines = [
90
+ ' 0 | ......',
91
+ ' | ........ ',
92
+ ' | ........ ',
93
+ ' | ...... ',
94
+ ' | ..... ',
95
+ ' | .... ',
96
+ ' | ... ',
97
+ ' | .. ',
98
+ ' | ... ',
99
+ ' | / ',
100
+ ' -2 |-------..----------------------------------------------',
101
+ ' | / ',
102
+ ' | / ',
103
+ ' | / ',
104
+ ' | . ',
105
+ ' | ',
106
+ ' | . ',
107
+ ' | ',
108
+ ' | ',
109
+ ' | ',
110
+ ' -4 |_______________________________________________________',
111
+ ' 0 0.5 1'
112
+ ]
113
+ # RuntimeWarning: divide by zero encountered in log
114
+ with ignore_warnings(RuntimeWarning):
115
+ assert lines == list(textplot_str(log(x), 0, 1))
116
+
117
+
118
+ def test_sinc():
119
+ x = Symbol('x')
120
+ lines = [
121
+ ' 1 | . . ',
122
+ ' | . . ',
123
+ ' | ',
124
+ ' | . . ',
125
+ ' | ',
126
+ ' | . . ',
127
+ ' | ',
128
+ ' | ',
129
+ ' | . . ',
130
+ ' | ',
131
+ ' 0.4 |-------------------------------------------------------',
132
+ ' | . . ',
133
+ ' | ',
134
+ ' | . . ',
135
+ ' | ',
136
+ ' | ..... ..... ',
137
+ ' | .. \\ . . / .. ',
138
+ ' | / \\ / \\ ',
139
+ ' |/ \\ . . / \\',
140
+ ' | \\ / \\ / ',
141
+ ' -0.2 |_______________________________________________________',
142
+ ' -10 0 10'
143
+ ]
144
+ # RuntimeWarning: invalid value encountered in double_scalars
145
+ with ignore_warnings(RuntimeWarning):
146
+ assert lines == list(textplot_str(sin(x)/x, -10, 10))
147
+
148
+
149
+ def test_imaginary():
150
+ x = Symbol('x')
151
+ lines = [
152
+ ' 1 | ..',
153
+ ' | .. ',
154
+ ' | ... ',
155
+ ' | .. ',
156
+ ' | .. ',
157
+ ' | .. ',
158
+ ' | .. ',
159
+ ' | .. ',
160
+ ' | .. ',
161
+ ' | / ',
162
+ ' 0.5 |----------------------------------/--------------------',
163
+ ' | .. ',
164
+ ' | / ',
165
+ ' | . ',
166
+ ' | ',
167
+ ' | . ',
168
+ ' | . ',
169
+ ' | ',
170
+ ' | ',
171
+ ' | ',
172
+ ' 0 |_______________________________________________________',
173
+ ' -1 0 1'
174
+ ]
175
+ # RuntimeWarning: invalid value encountered in sqrt
176
+ with ignore_warnings(RuntimeWarning):
177
+ assert list(textplot_str(sqrt(x), -1, 1)) == lines
178
+
179
+ lines = [
180
+ ' 1 | ',
181
+ ' | ',
182
+ ' | ',
183
+ ' | ',
184
+ ' | ',
185
+ ' | ',
186
+ ' | ',
187
+ ' | ',
188
+ ' | ',
189
+ ' | ',
190
+ ' 0 |-------------------------------------------------------',
191
+ ' | ',
192
+ ' | ',
193
+ ' | ',
194
+ ' | ',
195
+ ' | ',
196
+ ' | ',
197
+ ' | ',
198
+ ' | ',
199
+ ' | ',
200
+ ' -1 |_______________________________________________________',
201
+ ' -1 0 1'
202
+ ]
203
+ assert list(textplot_str(S.ImaginaryUnit, -1, 1)) == lines
venv/lib/python3.10/site-packages/sympy/simplify/__init__.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The module helps converting SymPy expressions into shorter forms of them.
2
+
3
+ for example:
4
+ the expression E**(pi*I) will be converted into -1
5
+ the expression (x+x)**2 will be converted into 4*x**2
6
+ """
7
+ from .simplify import (simplify, hypersimp, hypersimilar,
8
+ logcombine, separatevars, posify, besselsimp, kroneckersimp,
9
+ signsimp, nsimplify)
10
+
11
+ from .fu import FU, fu
12
+
13
+ from .sqrtdenest import sqrtdenest
14
+
15
+ from .cse_main import cse
16
+
17
+ from .epathtools import epath, EPath
18
+
19
+ from .hyperexpand import hyperexpand
20
+
21
+ from .radsimp import collect, rcollect, radsimp, collect_const, fraction, numer, denom
22
+
23
+ from .trigsimp import trigsimp, exptrigsimp
24
+
25
+ from .powsimp import powsimp, powdenest
26
+
27
+ from .combsimp import combsimp
28
+
29
+ from .gammasimp import gammasimp
30
+
31
+ from .ratsimp import ratsimp, ratsimpmodprime
32
+
33
+ __all__ = [
34
+ 'simplify', 'hypersimp', 'hypersimilar', 'logcombine', 'separatevars',
35
+ 'posify', 'besselsimp', 'kroneckersimp', 'signsimp',
36
+ 'nsimplify',
37
+
38
+ 'FU', 'fu',
39
+
40
+ 'sqrtdenest',
41
+
42
+ 'cse',
43
+
44
+ 'epath', 'EPath',
45
+
46
+ 'hyperexpand',
47
+
48
+ 'collect', 'rcollect', 'radsimp', 'collect_const', 'fraction', 'numer',
49
+ 'denom',
50
+
51
+ 'trigsimp', 'exptrigsimp',
52
+
53
+ 'powsimp', 'powdenest',
54
+
55
+ 'combsimp',
56
+
57
+ 'gammasimp',
58
+
59
+ 'ratsimp', 'ratsimpmodprime',
60
+ ]
venv/lib/python3.10/site-packages/sympy/simplify/combsimp.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import Mul
2
+ from sympy.core.function import count_ops
3
+ from sympy.core.traversal import preorder_traversal, bottom_up
4
+ from sympy.functions.combinatorial.factorials import binomial, factorial
5
+ from sympy.functions import gamma
6
+ from sympy.simplify.gammasimp import gammasimp, _gammasimp
7
+
8
+ from sympy.utilities.timeutils import timethis
9
+
10
+
11
+ @timethis('combsimp')
12
+ def combsimp(expr):
13
+ r"""
14
+ Simplify combinatorial expressions.
15
+
16
+ Explanation
17
+ ===========
18
+
19
+ This function takes as input an expression containing factorials,
20
+ binomials, Pochhammer symbol and other "combinatorial" functions,
21
+ and tries to minimize the number of those functions and reduce
22
+ the size of their arguments.
23
+
24
+ The algorithm works by rewriting all combinatorial functions as
25
+ gamma functions and applying gammasimp() except simplification
26
+ steps that may make an integer argument non-integer. See docstring
27
+ of gammasimp for more information.
28
+
29
+ Then it rewrites expression in terms of factorials and binomials by
30
+ rewriting gammas as factorials and converting (a+b)!/a!b! into
31
+ binomials.
32
+
33
+ If expression has gamma functions or combinatorial functions
34
+ with non-integer argument, it is automatically passed to gammasimp.
35
+
36
+ Examples
37
+ ========
38
+
39
+ >>> from sympy.simplify import combsimp
40
+ >>> from sympy import factorial, binomial, symbols
41
+ >>> n, k = symbols('n k', integer = True)
42
+
43
+ >>> combsimp(factorial(n)/factorial(n - 3))
44
+ n*(n - 2)*(n - 1)
45
+ >>> combsimp(binomial(n+1, k+1)/binomial(n, k))
46
+ (n + 1)/(k + 1)
47
+
48
+ """
49
+
50
+ expr = expr.rewrite(gamma, piecewise=False)
51
+ if any(isinstance(node, gamma) and not node.args[0].is_integer
52
+ for node in preorder_traversal(expr)):
53
+ return gammasimp(expr);
54
+
55
+ expr = _gammasimp(expr, as_comb = True)
56
+ expr = _gamma_as_comb(expr)
57
+ return expr
58
+
59
+
60
+ def _gamma_as_comb(expr):
61
+ """
62
+ Helper function for combsimp.
63
+
64
+ Rewrites expression in terms of factorials and binomials
65
+ """
66
+
67
+ expr = expr.rewrite(factorial)
68
+
69
+ def f(rv):
70
+ if not rv.is_Mul:
71
+ return rv
72
+ rvd = rv.as_powers_dict()
73
+ nd_fact_args = [[], []] # numerator, denominator
74
+
75
+ for k in rvd:
76
+ if isinstance(k, factorial) and rvd[k].is_Integer:
77
+ if rvd[k].is_positive:
78
+ nd_fact_args[0].extend([k.args[0]]*rvd[k])
79
+ else:
80
+ nd_fact_args[1].extend([k.args[0]]*-rvd[k])
81
+ rvd[k] = 0
82
+ if not nd_fact_args[0] or not nd_fact_args[1]:
83
+ return rv
84
+
85
+ hit = False
86
+ for m in range(2):
87
+ i = 0
88
+ while i < len(nd_fact_args[m]):
89
+ ai = nd_fact_args[m][i]
90
+ for j in range(i + 1, len(nd_fact_args[m])):
91
+ aj = nd_fact_args[m][j]
92
+
93
+ sum = ai + aj
94
+ if sum in nd_fact_args[1 - m]:
95
+ hit = True
96
+
97
+ nd_fact_args[1 - m].remove(sum)
98
+ del nd_fact_args[m][j]
99
+ del nd_fact_args[m][i]
100
+
101
+ rvd[binomial(sum, ai if count_ops(ai) <
102
+ count_ops(aj) else aj)] += (
103
+ -1 if m == 0 else 1)
104
+ break
105
+ else:
106
+ i += 1
107
+
108
+ if hit:
109
+ return Mul(*([k**rvd[k] for k in rvd] + [factorial(k)
110
+ for k in nd_fact_args[0]]))/Mul(*[factorial(k)
111
+ for k in nd_fact_args[1]])
112
+ return rv
113
+
114
+ return bottom_up(expr, f)
venv/lib/python3.10/site-packages/sympy/simplify/cse_main.py ADDED
@@ -0,0 +1,946 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Tools for doing common subexpression elimination.
2
+ """
3
+ from collections import defaultdict
4
+
5
+ from sympy.core import Basic, Mul, Add, Pow, sympify
6
+ from sympy.core.containers import Tuple, OrderedSet
7
+ from sympy.core.exprtools import factor_terms
8
+ from sympy.core.singleton import S
9
+ from sympy.core.sorting import ordered
10
+ from sympy.core.symbol import symbols, Symbol
11
+ from sympy.matrices import (MatrixBase, Matrix, ImmutableMatrix,
12
+ SparseMatrix, ImmutableSparseMatrix)
13
+ from sympy.matrices.expressions import (MatrixExpr, MatrixSymbol, MatMul,
14
+ MatAdd, MatPow, Inverse)
15
+ from sympy.matrices.expressions.matexpr import MatrixElement
16
+ from sympy.polys.rootoftools import RootOf
17
+ from sympy.utilities.iterables import numbered_symbols, sift, \
18
+ topological_sort, iterable
19
+
20
+ from . import cse_opts
21
+
22
+ # (preprocessor, postprocessor) pairs which are commonly useful. They should
23
+ # each take a SymPy expression and return a possibly transformed expression.
24
+ # When used in the function ``cse()``, the target expressions will be transformed
25
+ # by each of the preprocessor functions in order. After the common
26
+ # subexpressions are eliminated, each resulting expression will have the
27
+ # postprocessor functions transform them in *reverse* order in order to undo the
28
+ # transformation if necessary. This allows the algorithm to operate on
29
+ # a representation of the expressions that allows for more optimization
30
+ # opportunities.
31
+ # ``None`` can be used to specify no transformation for either the preprocessor or
32
+ # postprocessor.
33
+
34
+
35
+ basic_optimizations = [(cse_opts.sub_pre, cse_opts.sub_post),
36
+ (factor_terms, None)]
37
+
38
+ # sometimes we want the output in a different format; non-trivial
39
+ # transformations can be put here for users
40
+ # ===============================================================
41
+
42
+
43
+ def reps_toposort(r):
44
+ """Sort replacements ``r`` so (k1, v1) appears before (k2, v2)
45
+ if k2 is in v1's free symbols. This orders items in the
46
+ way that cse returns its results (hence, in order to use the
47
+ replacements in a substitution option it would make sense
48
+ to reverse the order).
49
+
50
+ Examples
51
+ ========
52
+
53
+ >>> from sympy.simplify.cse_main import reps_toposort
54
+ >>> from sympy.abc import x, y
55
+ >>> from sympy import Eq
56
+ >>> for l, r in reps_toposort([(x, y + 1), (y, 2)]):
57
+ ... print(Eq(l, r))
58
+ ...
59
+ Eq(y, 2)
60
+ Eq(x, y + 1)
61
+
62
+ """
63
+ r = sympify(r)
64
+ E = []
65
+ for c1, (k1, v1) in enumerate(r):
66
+ for c2, (k2, v2) in enumerate(r):
67
+ if k1 in v2.free_symbols:
68
+ E.append((c1, c2))
69
+ return [r[i] for i in topological_sort((range(len(r)), E))]
70
+
71
+
72
+ def cse_separate(r, e):
73
+ """Move expressions that are in the form (symbol, expr) out of the
74
+ expressions and sort them into the replacements using the reps_toposort.
75
+
76
+ Examples
77
+ ========
78
+
79
+ >>> from sympy.simplify.cse_main import cse_separate
80
+ >>> from sympy.abc import x, y, z
81
+ >>> from sympy import cos, exp, cse, Eq, symbols
82
+ >>> x0, x1 = symbols('x:2')
83
+ >>> eq = (x + 1 + exp((x + 1)/(y + 1)) + cos(y + 1))
84
+ >>> cse([eq, Eq(x, z + 1), z - 2], postprocess=cse_separate) in [
85
+ ... [[(x0, y + 1), (x, z + 1), (x1, x + 1)],
86
+ ... [x1 + exp(x1/x0) + cos(x0), z - 2]],
87
+ ... [[(x1, y + 1), (x, z + 1), (x0, x + 1)],
88
+ ... [x0 + exp(x0/x1) + cos(x1), z - 2]]]
89
+ ...
90
+ True
91
+ """
92
+ d = sift(e, lambda w: w.is_Equality and w.lhs.is_Symbol)
93
+ r = r + [w.args for w in d[True]]
94
+ e = d[False]
95
+ return [reps_toposort(r), e]
96
+
97
+
98
+ def cse_release_variables(r, e):
99
+ """
100
+ Return tuples giving ``(a, b)`` where ``a`` is a symbol and ``b`` is
101
+ either an expression or None. The value of None is used when a
102
+ symbol is no longer needed for subsequent expressions.
103
+
104
+ Use of such output can reduce the memory footprint of lambdified
105
+ expressions that contain large, repeated subexpressions.
106
+
107
+ Examples
108
+ ========
109
+
110
+ >>> from sympy import cse
111
+ >>> from sympy.simplify.cse_main import cse_release_variables
112
+ >>> from sympy.abc import x, y
113
+ >>> eqs = [(x + y - 1)**2, x, x + y, (x + y)/(2*x + 1) + (x + y - 1)**2, (2*x + 1)**(x + y)]
114
+ >>> defs, rvs = cse_release_variables(*cse(eqs))
115
+ >>> for i in defs:
116
+ ... print(i)
117
+ ...
118
+ (x0, x + y)
119
+ (x1, (x0 - 1)**2)
120
+ (x2, 2*x + 1)
121
+ (_3, x0/x2 + x1)
122
+ (_4, x2**x0)
123
+ (x2, None)
124
+ (_0, x1)
125
+ (x1, None)
126
+ (_2, x0)
127
+ (x0, None)
128
+ (_1, x)
129
+ >>> print(rvs)
130
+ (_0, _1, _2, _3, _4)
131
+ """
132
+ if not r:
133
+ return r, e
134
+
135
+ s, p = zip(*r)
136
+ esyms = symbols('_:%d' % len(e))
137
+ syms = list(esyms)
138
+ s = list(s)
139
+ in_use = set(s)
140
+ p = list(p)
141
+ # sort e so those with most sub-expressions appear first
142
+ e = [(e[i], syms[i]) for i in range(len(e))]
143
+ e, syms = zip(*sorted(e,
144
+ key=lambda x: -sum([p[s.index(i)].count_ops()
145
+ for i in x[0].free_symbols & in_use])))
146
+ syms = list(syms)
147
+ p += e
148
+ rv = []
149
+ i = len(p) - 1
150
+ while i >= 0:
151
+ _p = p.pop()
152
+ c = in_use & _p.free_symbols
153
+ if c: # sorting for canonical results
154
+ rv.extend([(s, None) for s in sorted(c, key=str)])
155
+ if i >= len(r):
156
+ rv.append((syms.pop(), _p))
157
+ else:
158
+ rv.append((s[i], _p))
159
+ in_use -= c
160
+ i -= 1
161
+ rv.reverse()
162
+ return rv, esyms
163
+
164
+
165
+ # ====end of cse postprocess idioms===========================
166
+
167
+
168
+ def preprocess_for_cse(expr, optimizations):
169
+ """ Preprocess an expression to optimize for common subexpression
170
+ elimination.
171
+
172
+ Parameters
173
+ ==========
174
+
175
+ expr : SymPy expression
176
+ The target expression to optimize.
177
+ optimizations : list of (callable, callable) pairs
178
+ The (preprocessor, postprocessor) pairs.
179
+
180
+ Returns
181
+ =======
182
+
183
+ expr : SymPy expression
184
+ The transformed expression.
185
+ """
186
+ for pre, post in optimizations:
187
+ if pre is not None:
188
+ expr = pre(expr)
189
+ return expr
190
+
191
+
192
+ def postprocess_for_cse(expr, optimizations):
193
+ """Postprocess an expression after common subexpression elimination to
194
+ return the expression to canonical SymPy form.
195
+
196
+ Parameters
197
+ ==========
198
+
199
+ expr : SymPy expression
200
+ The target expression to transform.
201
+ optimizations : list of (callable, callable) pairs, optional
202
+ The (preprocessor, postprocessor) pairs. The postprocessors will be
203
+ applied in reversed order to undo the effects of the preprocessors
204
+ correctly.
205
+
206
+ Returns
207
+ =======
208
+
209
+ expr : SymPy expression
210
+ The transformed expression.
211
+ """
212
+ for pre, post in reversed(optimizations):
213
+ if post is not None:
214
+ expr = post(expr)
215
+ return expr
216
+
217
+
218
+ class FuncArgTracker:
219
+ """
220
+ A class which manages a mapping from functions to arguments and an inverse
221
+ mapping from arguments to functions.
222
+ """
223
+
224
+ def __init__(self, funcs):
225
+ # To minimize the number of symbolic comparisons, all function arguments
226
+ # get assigned a value number.
227
+ self.value_numbers = {}
228
+ self.value_number_to_value = []
229
+
230
+ # Both of these maps use integer indices for arguments / functions.
231
+ self.arg_to_funcset = []
232
+ self.func_to_argset = []
233
+
234
+ for func_i, func in enumerate(funcs):
235
+ func_argset = OrderedSet()
236
+
237
+ for func_arg in func.args:
238
+ arg_number = self.get_or_add_value_number(func_arg)
239
+ func_argset.add(arg_number)
240
+ self.arg_to_funcset[arg_number].add(func_i)
241
+
242
+ self.func_to_argset.append(func_argset)
243
+
244
+ def get_args_in_value_order(self, argset):
245
+ """
246
+ Return the list of arguments in sorted order according to their value
247
+ numbers.
248
+ """
249
+ return [self.value_number_to_value[argn] for argn in sorted(argset)]
250
+
251
+ def get_or_add_value_number(self, value):
252
+ """
253
+ Return the value number for the given argument.
254
+ """
255
+ nvalues = len(self.value_numbers)
256
+ value_number = self.value_numbers.setdefault(value, nvalues)
257
+ if value_number == nvalues:
258
+ self.value_number_to_value.append(value)
259
+ self.arg_to_funcset.append(OrderedSet())
260
+ return value_number
261
+
262
+ def stop_arg_tracking(self, func_i):
263
+ """
264
+ Remove the function func_i from the argument to function mapping.
265
+ """
266
+ for arg in self.func_to_argset[func_i]:
267
+ self.arg_to_funcset[arg].remove(func_i)
268
+
269
+
270
+ def get_common_arg_candidates(self, argset, min_func_i=0):
271
+ """Return a dict whose keys are function numbers. The entries of the dict are
272
+ the number of arguments said function has in common with
273
+ ``argset``. Entries have at least 2 items in common. All keys have
274
+ value at least ``min_func_i``.
275
+ """
276
+ count_map = defaultdict(lambda: 0)
277
+ if not argset:
278
+ return count_map
279
+
280
+ funcsets = [self.arg_to_funcset[arg] for arg in argset]
281
+ # As an optimization below, we handle the largest funcset separately from
282
+ # the others.
283
+ largest_funcset = max(funcsets, key=len)
284
+
285
+ for funcset in funcsets:
286
+ if largest_funcset is funcset:
287
+ continue
288
+ for func_i in funcset:
289
+ if func_i >= min_func_i:
290
+ count_map[func_i] += 1
291
+
292
+ # We pick the smaller of the two containers (count_map, largest_funcset)
293
+ # to iterate over to reduce the number of iterations needed.
294
+ (smaller_funcs_container,
295
+ larger_funcs_container) = sorted(
296
+ [largest_funcset, count_map],
297
+ key=len)
298
+
299
+ for func_i in smaller_funcs_container:
300
+ # Not already in count_map? It can't possibly be in the output, so
301
+ # skip it.
302
+ if count_map[func_i] < 1:
303
+ continue
304
+
305
+ if func_i in larger_funcs_container:
306
+ count_map[func_i] += 1
307
+
308
+ return {k: v for k, v in count_map.items() if v >= 2}
309
+
310
+ def get_subset_candidates(self, argset, restrict_to_funcset=None):
311
+ """
312
+ Return a set of functions each of which whose argument list contains
313
+ ``argset``, optionally filtered only to contain functions in
314
+ ``restrict_to_funcset``.
315
+ """
316
+ iarg = iter(argset)
317
+
318
+ indices = OrderedSet(
319
+ fi for fi in self.arg_to_funcset[next(iarg)])
320
+
321
+ if restrict_to_funcset is not None:
322
+ indices &= restrict_to_funcset
323
+
324
+ for arg in iarg:
325
+ indices &= self.arg_to_funcset[arg]
326
+
327
+ return indices
328
+
329
+ def update_func_argset(self, func_i, new_argset):
330
+ """
331
+ Update a function with a new set of arguments.
332
+ """
333
+ new_args = OrderedSet(new_argset)
334
+ old_args = self.func_to_argset[func_i]
335
+
336
+ for deleted_arg in old_args - new_args:
337
+ self.arg_to_funcset[deleted_arg].remove(func_i)
338
+ for added_arg in new_args - old_args:
339
+ self.arg_to_funcset[added_arg].add(func_i)
340
+
341
+ self.func_to_argset[func_i].clear()
342
+ self.func_to_argset[func_i].update(new_args)
343
+
344
+
345
+ class Unevaluated:
346
+
347
+ def __init__(self, func, args):
348
+ self.func = func
349
+ self.args = args
350
+
351
+ def __str__(self):
352
+ return "Uneval<{}>({})".format(
353
+ self.func, ", ".join(str(a) for a in self.args))
354
+
355
+ def as_unevaluated_basic(self):
356
+ return self.func(*self.args, evaluate=False)
357
+
358
+ @property
359
+ def free_symbols(self):
360
+ return set().union(*[a.free_symbols for a in self.args])
361
+
362
+ __repr__ = __str__
363
+
364
+
365
+ def match_common_args(func_class, funcs, opt_subs):
366
+ """
367
+ Recognize and extract common subexpressions of function arguments within a
368
+ set of function calls. For instance, for the following function calls::
369
+
370
+ x + z + y
371
+ sin(x + y)
372
+
373
+ this will extract a common subexpression of `x + y`::
374
+
375
+ w = x + y
376
+ w + z
377
+ sin(w)
378
+
379
+ The function we work with is assumed to be associative and commutative.
380
+
381
+ Parameters
382
+ ==========
383
+
384
+ func_class: class
385
+ The function class (e.g. Add, Mul)
386
+ funcs: list of functions
387
+ A list of function calls.
388
+ opt_subs: dict
389
+ A dictionary of substitutions which this function may update.
390
+ """
391
+
392
+ # Sort to ensure that whole-function subexpressions come before the items
393
+ # that use them.
394
+ funcs = sorted(funcs, key=lambda f: len(f.args))
395
+ arg_tracker = FuncArgTracker(funcs)
396
+
397
+ changed = OrderedSet()
398
+
399
+ for i in range(len(funcs)):
400
+ common_arg_candidates_counts = arg_tracker.get_common_arg_candidates(
401
+ arg_tracker.func_to_argset[i], min_func_i=i + 1)
402
+
403
+ # Sort the candidates in order of match size.
404
+ # This makes us try combining smaller matches first.
405
+ common_arg_candidates = OrderedSet(sorted(
406
+ common_arg_candidates_counts.keys(),
407
+ key=lambda k: (common_arg_candidates_counts[k], k)))
408
+
409
+ while common_arg_candidates:
410
+ j = common_arg_candidates.pop(last=False)
411
+
412
+ com_args = arg_tracker.func_to_argset[i].intersection(
413
+ arg_tracker.func_to_argset[j])
414
+
415
+ if len(com_args) <= 1:
416
+ # This may happen if a set of common arguments was already
417
+ # combined in a previous iteration.
418
+ continue
419
+
420
+ # For all sets, replace the common symbols by the function
421
+ # over them, to allow recursive matches.
422
+
423
+ diff_i = arg_tracker.func_to_argset[i].difference(com_args)
424
+ if diff_i:
425
+ # com_func needs to be unevaluated to allow for recursive matches.
426
+ com_func = Unevaluated(
427
+ func_class, arg_tracker.get_args_in_value_order(com_args))
428
+ com_func_number = arg_tracker.get_or_add_value_number(com_func)
429
+ arg_tracker.update_func_argset(i, diff_i | OrderedSet([com_func_number]))
430
+ changed.add(i)
431
+ else:
432
+ # Treat the whole expression as a CSE.
433
+ #
434
+ # The reason this needs to be done is somewhat subtle. Within
435
+ # tree_cse(), to_eliminate only contains expressions that are
436
+ # seen more than once. The problem is unevaluated expressions
437
+ # do not compare equal to the evaluated equivalent. So
438
+ # tree_cse() won't mark funcs[i] as a CSE if we use an
439
+ # unevaluated version.
440
+ com_func_number = arg_tracker.get_or_add_value_number(funcs[i])
441
+
442
+ diff_j = arg_tracker.func_to_argset[j].difference(com_args)
443
+ arg_tracker.update_func_argset(j, diff_j | OrderedSet([com_func_number]))
444
+ changed.add(j)
445
+
446
+ for k in arg_tracker.get_subset_candidates(
447
+ com_args, common_arg_candidates):
448
+ diff_k = arg_tracker.func_to_argset[k].difference(com_args)
449
+ arg_tracker.update_func_argset(k, diff_k | OrderedSet([com_func_number]))
450
+ changed.add(k)
451
+
452
+ if i in changed:
453
+ opt_subs[funcs[i]] = Unevaluated(func_class,
454
+ arg_tracker.get_args_in_value_order(arg_tracker.func_to_argset[i]))
455
+
456
+ arg_tracker.stop_arg_tracking(i)
457
+
458
+
459
+ def opt_cse(exprs, order='canonical'):
460
+ """Find optimization opportunities in Adds, Muls, Pows and negative
461
+ coefficient Muls.
462
+
463
+ Parameters
464
+ ==========
465
+
466
+ exprs : list of SymPy expressions
467
+ The expressions to optimize.
468
+ order : string, 'none' or 'canonical'
469
+ The order by which Mul and Add arguments are processed. For large
470
+ expressions where speed is a concern, use the setting order='none'.
471
+
472
+ Returns
473
+ =======
474
+
475
+ opt_subs : dictionary of expression substitutions
476
+ The expression substitutions which can be useful to optimize CSE.
477
+
478
+ Examples
479
+ ========
480
+
481
+ >>> from sympy.simplify.cse_main import opt_cse
482
+ >>> from sympy.abc import x
483
+ >>> opt_subs = opt_cse([x**-2])
484
+ >>> k, v = list(opt_subs.keys())[0], list(opt_subs.values())[0]
485
+ >>> print((k, v.as_unevaluated_basic()))
486
+ (x**(-2), 1/(x**2))
487
+ """
488
+ opt_subs = {}
489
+
490
+ adds = OrderedSet()
491
+ muls = OrderedSet()
492
+
493
+ seen_subexp = set()
494
+ collapsible_subexp = set()
495
+
496
+ def _find_opts(expr):
497
+
498
+ if not isinstance(expr, (Basic, Unevaluated)):
499
+ return
500
+
501
+ if expr.is_Atom or expr.is_Order:
502
+ return
503
+
504
+ if iterable(expr):
505
+ list(map(_find_opts, expr))
506
+ return
507
+
508
+ if expr in seen_subexp:
509
+ return expr
510
+ seen_subexp.add(expr)
511
+
512
+ list(map(_find_opts, expr.args))
513
+
514
+ if not isinstance(expr, MatrixExpr) and expr.could_extract_minus_sign():
515
+ # XXX -expr does not always work rigorously for some expressions
516
+ # containing UnevaluatedExpr.
517
+ # https://github.com/sympy/sympy/issues/24818
518
+ if isinstance(expr, Add):
519
+ neg_expr = Add(*(-i for i in expr.args))
520
+ else:
521
+ neg_expr = -expr
522
+
523
+ if not neg_expr.is_Atom:
524
+ opt_subs[expr] = Unevaluated(Mul, (S.NegativeOne, neg_expr))
525
+ seen_subexp.add(neg_expr)
526
+ expr = neg_expr
527
+
528
+ if isinstance(expr, (Mul, MatMul)):
529
+ if len(expr.args) == 1:
530
+ collapsible_subexp.add(expr)
531
+ else:
532
+ muls.add(expr)
533
+
534
+ elif isinstance(expr, (Add, MatAdd)):
535
+ if len(expr.args) == 1:
536
+ collapsible_subexp.add(expr)
537
+ else:
538
+ adds.add(expr)
539
+
540
+ elif isinstance(expr, Inverse):
541
+ # Do not want to treat `Inverse` as a `MatPow`
542
+ pass
543
+
544
+ elif isinstance(expr, (Pow, MatPow)):
545
+ base, exp = expr.base, expr.exp
546
+ if exp.could_extract_minus_sign():
547
+ opt_subs[expr] = Unevaluated(Pow, (Pow(base, -exp), -1))
548
+
549
+ for e in exprs:
550
+ if isinstance(e, (Basic, Unevaluated)):
551
+ _find_opts(e)
552
+
553
+ # Handle collapsing of multinary operations with single arguments
554
+ edges = [(s, s.args[0]) for s in collapsible_subexp
555
+ if s.args[0] in collapsible_subexp]
556
+ for e in reversed(topological_sort((collapsible_subexp, edges))):
557
+ opt_subs[e] = opt_subs.get(e.args[0], e.args[0])
558
+
559
+ # split muls into commutative
560
+ commutative_muls = OrderedSet()
561
+ for m in muls:
562
+ c, nc = m.args_cnc(cset=False)
563
+ if c:
564
+ c_mul = m.func(*c)
565
+ if nc:
566
+ if c_mul == 1:
567
+ new_obj = m.func(*nc)
568
+ else:
569
+ if isinstance(m, MatMul):
570
+ new_obj = m.func(c_mul, *nc, evaluate=False)
571
+ else:
572
+ new_obj = m.func(c_mul, m.func(*nc), evaluate=False)
573
+ opt_subs[m] = new_obj
574
+ if len(c) > 1:
575
+ commutative_muls.add(c_mul)
576
+
577
+ match_common_args(Add, adds, opt_subs)
578
+ match_common_args(Mul, commutative_muls, opt_subs)
579
+
580
+ return opt_subs
581
+
582
+
583
+ def tree_cse(exprs, symbols, opt_subs=None, order='canonical', ignore=()):
584
+ """Perform raw CSE on expression tree, taking opt_subs into account.
585
+
586
+ Parameters
587
+ ==========
588
+
589
+ exprs : list of SymPy expressions
590
+ The expressions to reduce.
591
+ symbols : infinite iterator yielding unique Symbols
592
+ The symbols used to label the common subexpressions which are pulled
593
+ out.
594
+ opt_subs : dictionary of expression substitutions
595
+ The expressions to be substituted before any CSE action is performed.
596
+ order : string, 'none' or 'canonical'
597
+ The order by which Mul and Add arguments are processed. For large
598
+ expressions where speed is a concern, use the setting order='none'.
599
+ ignore : iterable of Symbols
600
+ Substitutions containing any Symbol from ``ignore`` will be ignored.
601
+ """
602
+ if opt_subs is None:
603
+ opt_subs = {}
604
+
605
+ ## Find repeated sub-expressions
606
+
607
+ to_eliminate = set()
608
+
609
+ seen_subexp = set()
610
+ excluded_symbols = set()
611
+
612
+ def _find_repeated(expr):
613
+ if not isinstance(expr, (Basic, Unevaluated)):
614
+ return
615
+
616
+ if isinstance(expr, RootOf):
617
+ return
618
+
619
+ if isinstance(expr, Basic) and (
620
+ expr.is_Atom or
621
+ expr.is_Order or
622
+ isinstance(expr, (MatrixSymbol, MatrixElement))):
623
+ if expr.is_Symbol:
624
+ excluded_symbols.add(expr)
625
+ return
626
+
627
+ if iterable(expr):
628
+ args = expr
629
+
630
+ else:
631
+ if expr in seen_subexp:
632
+ for ign in ignore:
633
+ if ign in expr.free_symbols:
634
+ break
635
+ else:
636
+ to_eliminate.add(expr)
637
+ return
638
+
639
+ seen_subexp.add(expr)
640
+
641
+ if expr in opt_subs:
642
+ expr = opt_subs[expr]
643
+
644
+ args = expr.args
645
+
646
+ list(map(_find_repeated, args))
647
+
648
+ for e in exprs:
649
+ if isinstance(e, Basic):
650
+ _find_repeated(e)
651
+
652
+ ## Rebuild tree
653
+
654
+ # Remove symbols from the generator that conflict with names in the expressions.
655
+ symbols = (symbol for symbol in symbols if symbol not in excluded_symbols)
656
+
657
+ replacements = []
658
+
659
+ subs = {}
660
+
661
+ def _rebuild(expr):
662
+ if not isinstance(expr, (Basic, Unevaluated)):
663
+ return expr
664
+
665
+ if not expr.args:
666
+ return expr
667
+
668
+ if iterable(expr):
669
+ new_args = [_rebuild(arg) for arg in expr.args]
670
+ return expr.func(*new_args)
671
+
672
+ if expr in subs:
673
+ return subs[expr]
674
+
675
+ orig_expr = expr
676
+ if expr in opt_subs:
677
+ expr = opt_subs[expr]
678
+
679
+ # If enabled, parse Muls and Adds arguments by order to ensure
680
+ # replacement order independent from hashes
681
+ if order != 'none':
682
+ if isinstance(expr, (Mul, MatMul)):
683
+ c, nc = expr.args_cnc()
684
+ if c == [1]:
685
+ args = nc
686
+ else:
687
+ args = list(ordered(c)) + nc
688
+ elif isinstance(expr, (Add, MatAdd)):
689
+ args = list(ordered(expr.args))
690
+ else:
691
+ args = expr.args
692
+ else:
693
+ args = expr.args
694
+
695
+ new_args = list(map(_rebuild, args))
696
+ if isinstance(expr, Unevaluated) or new_args != args:
697
+ new_expr = expr.func(*new_args)
698
+ else:
699
+ new_expr = expr
700
+
701
+ if orig_expr in to_eliminate:
702
+ try:
703
+ sym = next(symbols)
704
+ except StopIteration:
705
+ raise ValueError("Symbols iterator ran out of symbols.")
706
+
707
+ if isinstance(orig_expr, MatrixExpr):
708
+ sym = MatrixSymbol(sym.name, orig_expr.rows,
709
+ orig_expr.cols)
710
+
711
+ subs[orig_expr] = sym
712
+ replacements.append((sym, new_expr))
713
+ return sym
714
+
715
+ else:
716
+ return new_expr
717
+
718
+ reduced_exprs = []
719
+ for e in exprs:
720
+ if isinstance(e, Basic):
721
+ reduced_e = _rebuild(e)
722
+ else:
723
+ reduced_e = e
724
+ reduced_exprs.append(reduced_e)
725
+ return replacements, reduced_exprs
726
+
727
+
728
+ def cse(exprs, symbols=None, optimizations=None, postprocess=None,
729
+ order='canonical', ignore=(), list=True):
730
+ """ Perform common subexpression elimination on an expression.
731
+
732
+ Parameters
733
+ ==========
734
+
735
+ exprs : list of SymPy expressions, or a single SymPy expression
736
+ The expressions to reduce.
737
+ symbols : infinite iterator yielding unique Symbols
738
+ The symbols used to label the common subexpressions which are pulled
739
+ out. The ``numbered_symbols`` generator is useful. The default is a
740
+ stream of symbols of the form "x0", "x1", etc. This must be an
741
+ infinite iterator.
742
+ optimizations : list of (callable, callable) pairs
743
+ The (preprocessor, postprocessor) pairs of external optimization
744
+ functions. Optionally 'basic' can be passed for a set of predefined
745
+ basic optimizations. Such 'basic' optimizations were used by default
746
+ in old implementation, however they can be really slow on larger
747
+ expressions. Now, no pre or post optimizations are made by default.
748
+ postprocess : a function which accepts the two return values of cse and
749
+ returns the desired form of output from cse, e.g. if you want the
750
+ replacements reversed the function might be the following lambda:
751
+ lambda r, e: return reversed(r), e
752
+ order : string, 'none' or 'canonical'
753
+ The order by which Mul and Add arguments are processed. If set to
754
+ 'canonical', arguments will be canonically ordered. If set to 'none',
755
+ ordering will be faster but dependent on expressions hashes, thus
756
+ machine dependent and variable. For large expressions where speed is a
757
+ concern, use the setting order='none'.
758
+ ignore : iterable of Symbols
759
+ Substitutions containing any Symbol from ``ignore`` will be ignored.
760
+ list : bool, (default True)
761
+ Returns expression in list or else with same type as input (when False).
762
+
763
+ Returns
764
+ =======
765
+
766
+ replacements : list of (Symbol, expression) pairs
767
+ All of the common subexpressions that were replaced. Subexpressions
768
+ earlier in this list might show up in subexpressions later in this
769
+ list.
770
+ reduced_exprs : list of SymPy expressions
771
+ The reduced expressions with all of the replacements above.
772
+
773
+ Examples
774
+ ========
775
+
776
+ >>> from sympy import cse, SparseMatrix
777
+ >>> from sympy.abc import x, y, z, w
778
+ >>> cse(((w + x + y + z)*(w + y + z))/(w + x)**3)
779
+ ([(x0, y + z), (x1, w + x)], [(w + x0)*(x0 + x1)/x1**3])
780
+
781
+
782
+ List of expressions with recursive substitutions:
783
+
784
+ >>> m = SparseMatrix([x + y, x + y + z])
785
+ >>> cse([(x+y)**2, x + y + z, y + z, x + z + y, m])
786
+ ([(x0, x + y), (x1, x0 + z)], [x0**2, x1, y + z, x1, Matrix([
787
+ [x0],
788
+ [x1]])])
789
+
790
+ Note: the type and mutability of input matrices is retained.
791
+
792
+ >>> isinstance(_[1][-1], SparseMatrix)
793
+ True
794
+
795
+ The user may disallow substitutions containing certain symbols:
796
+
797
+ >>> cse([y**2*(x + 1), 3*y**2*(x + 1)], ignore=(y,))
798
+ ([(x0, x + 1)], [x0*y**2, 3*x0*y**2])
799
+
800
+ The default return value for the reduced expression(s) is a list, even if there is only
801
+ one expression. The `list` flag preserves the type of the input in the output:
802
+
803
+ >>> cse(x)
804
+ ([], [x])
805
+ >>> cse(x, list=False)
806
+ ([], x)
807
+ """
808
+ if not list:
809
+ return _cse_homogeneous(exprs,
810
+ symbols=symbols, optimizations=optimizations,
811
+ postprocess=postprocess, order=order, ignore=ignore)
812
+
813
+ if isinstance(exprs, (int, float)):
814
+ exprs = sympify(exprs)
815
+
816
+ # Handle the case if just one expression was passed.
817
+ if isinstance(exprs, (Basic, MatrixBase)):
818
+ exprs = [exprs]
819
+
820
+ copy = exprs
821
+ temp = []
822
+ for e in exprs:
823
+ if isinstance(e, (Matrix, ImmutableMatrix)):
824
+ temp.append(Tuple(*e.flat()))
825
+ elif isinstance(e, (SparseMatrix, ImmutableSparseMatrix)):
826
+ temp.append(Tuple(*e.todok().items()))
827
+ else:
828
+ temp.append(e)
829
+ exprs = temp
830
+ del temp
831
+
832
+ if optimizations is None:
833
+ optimizations = []
834
+ elif optimizations == 'basic':
835
+ optimizations = basic_optimizations
836
+
837
+ # Preprocess the expressions to give us better optimization opportunities.
838
+ reduced_exprs = [preprocess_for_cse(e, optimizations) for e in exprs]
839
+
840
+ if symbols is None:
841
+ symbols = numbered_symbols(cls=Symbol)
842
+ else:
843
+ # In case we get passed an iterable with an __iter__ method instead of
844
+ # an actual iterator.
845
+ symbols = iter(symbols)
846
+
847
+ # Find other optimization opportunities.
848
+ opt_subs = opt_cse(reduced_exprs, order)
849
+
850
+ # Main CSE algorithm.
851
+ replacements, reduced_exprs = tree_cse(reduced_exprs, symbols, opt_subs,
852
+ order, ignore)
853
+
854
+ # Postprocess the expressions to return the expressions to canonical form.
855
+ exprs = copy
856
+ for i, (sym, subtree) in enumerate(replacements):
857
+ subtree = postprocess_for_cse(subtree, optimizations)
858
+ replacements[i] = (sym, subtree)
859
+ reduced_exprs = [postprocess_for_cse(e, optimizations)
860
+ for e in reduced_exprs]
861
+
862
+ # Get the matrices back
863
+ for i, e in enumerate(exprs):
864
+ if isinstance(e, (Matrix, ImmutableMatrix)):
865
+ reduced_exprs[i] = Matrix(e.rows, e.cols, reduced_exprs[i])
866
+ if isinstance(e, ImmutableMatrix):
867
+ reduced_exprs[i] = reduced_exprs[i].as_immutable()
868
+ elif isinstance(e, (SparseMatrix, ImmutableSparseMatrix)):
869
+ m = SparseMatrix(e.rows, e.cols, {})
870
+ for k, v in reduced_exprs[i]:
871
+ m[k] = v
872
+ if isinstance(e, ImmutableSparseMatrix):
873
+ m = m.as_immutable()
874
+ reduced_exprs[i] = m
875
+
876
+ if postprocess is None:
877
+ return replacements, reduced_exprs
878
+
879
+ return postprocess(replacements, reduced_exprs)
880
+
881
+
882
+ def _cse_homogeneous(exprs, **kwargs):
883
+ """
884
+ Same as ``cse`` but the ``reduced_exprs`` are returned
885
+ with the same type as ``exprs`` or a sympified version of the same.
886
+
887
+ Parameters
888
+ ==========
889
+
890
+ exprs : an Expr, iterable of Expr or dictionary with Expr values
891
+ the expressions in which repeated subexpressions will be identified
892
+ kwargs : additional arguments for the ``cse`` function
893
+
894
+ Returns
895
+ =======
896
+
897
+ replacements : list of (Symbol, expression) pairs
898
+ All of the common subexpressions that were replaced. Subexpressions
899
+ earlier in this list might show up in subexpressions later in this
900
+ list.
901
+ reduced_exprs : list of SymPy expressions
902
+ The reduced expressions with all of the replacements above.
903
+
904
+ Examples
905
+ ========
906
+
907
+ >>> from sympy.simplify.cse_main import cse
908
+ >>> from sympy import cos, Tuple, Matrix
909
+ >>> from sympy.abc import x
910
+ >>> output = lambda x: type(cse(x, list=False)[1])
911
+ >>> output(1)
912
+ <class 'sympy.core.numbers.One'>
913
+ >>> output('cos(x)')
914
+ <class 'str'>
915
+ >>> output(cos(x))
916
+ cos
917
+ >>> output(Tuple(1, x))
918
+ <class 'sympy.core.containers.Tuple'>
919
+ >>> output(Matrix([[1,0], [0,1]]))
920
+ <class 'sympy.matrices.dense.MutableDenseMatrix'>
921
+ >>> output([1, x])
922
+ <class 'list'>
923
+ >>> output((1, x))
924
+ <class 'tuple'>
925
+ >>> output({1, x})
926
+ <class 'set'>
927
+ """
928
+ if isinstance(exprs, str):
929
+ replacements, reduced_exprs = _cse_homogeneous(
930
+ sympify(exprs), **kwargs)
931
+ return replacements, repr(reduced_exprs)
932
+ if isinstance(exprs, (list, tuple, set)):
933
+ replacements, reduced_exprs = cse(exprs, **kwargs)
934
+ return replacements, type(exprs)(reduced_exprs)
935
+ if isinstance(exprs, dict):
936
+ keys = list(exprs.keys()) # In order to guarantee the order of the elements.
937
+ replacements, values = cse([exprs[k] for k in keys], **kwargs)
938
+ reduced_exprs = dict(zip(keys, values))
939
+ return replacements, reduced_exprs
940
+
941
+ try:
942
+ replacements, (reduced_exprs,) = cse(exprs, **kwargs)
943
+ except TypeError: # For example 'mpf' objects
944
+ return [], exprs
945
+ else:
946
+ return replacements, reduced_exprs
venv/lib/python3.10/site-packages/sympy/simplify/cse_opts.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Optimizations of the expression tree representation for better CSE
2
+ opportunities.
3
+ """
4
+ from sympy.core import Add, Basic, Mul
5
+ from sympy.core.singleton import S
6
+ from sympy.core.sorting import default_sort_key
7
+ from sympy.core.traversal import preorder_traversal
8
+
9
+
10
+ def sub_pre(e):
11
+ """ Replace y - x with -(x - y) if -1 can be extracted from y - x.
12
+ """
13
+ # replacing Add, A, from which -1 can be extracted with -1*-A
14
+ adds = [a for a in e.atoms(Add) if a.could_extract_minus_sign()]
15
+ reps = {}
16
+ ignore = set()
17
+ for a in adds:
18
+ na = -a
19
+ if na.is_Mul: # e.g. MatExpr
20
+ ignore.add(a)
21
+ continue
22
+ reps[a] = Mul._from_args([S.NegativeOne, na])
23
+
24
+ e = e.xreplace(reps)
25
+
26
+ # repeat again for persisting Adds but mark these with a leading 1, -1
27
+ # e.g. y - x -> 1*-1*(x - y)
28
+ if isinstance(e, Basic):
29
+ negs = {}
30
+ for a in sorted(e.atoms(Add), key=default_sort_key):
31
+ if a in ignore:
32
+ continue
33
+ if a in reps:
34
+ negs[a] = reps[a]
35
+ elif a.could_extract_minus_sign():
36
+ negs[a] = Mul._from_args([S.One, S.NegativeOne, -a])
37
+ e = e.xreplace(negs)
38
+ return e
39
+
40
+
41
+ def sub_post(e):
42
+ """ Replace 1*-1*x with -x.
43
+ """
44
+ replacements = []
45
+ for node in preorder_traversal(e):
46
+ if isinstance(node, Mul) and \
47
+ node.args[0] is S.One and node.args[1] is S.NegativeOne:
48
+ replacements.append((node, -Mul._from_args(node.args[2:])))
49
+ for node, replacement in replacements:
50
+ e = e.xreplace({node: replacement})
51
+
52
+ return e
venv/lib/python3.10/site-packages/sympy/simplify/epathtools.py ADDED
@@ -0,0 +1,356 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tools for manipulation of expressions using paths. """
2
+
3
+ from sympy.core import Basic
4
+
5
+
6
+ class EPath:
7
+ r"""
8
+ Manipulate expressions using paths.
9
+
10
+ EPath grammar in EBNF notation::
11
+
12
+ literal ::= /[A-Za-z_][A-Za-z_0-9]*/
13
+ number ::= /-?\d+/
14
+ type ::= literal
15
+ attribute ::= literal "?"
16
+ all ::= "*"
17
+ slice ::= "[" number? (":" number? (":" number?)?)? "]"
18
+ range ::= all | slice
19
+ query ::= (type | attribute) ("|" (type | attribute))*
20
+ selector ::= range | query range?
21
+ path ::= "/" selector ("/" selector)*
22
+
23
+ See the docstring of the epath() function.
24
+
25
+ """
26
+
27
+ __slots__ = ("_path", "_epath")
28
+
29
+ def __new__(cls, path):
30
+ """Construct new EPath. """
31
+ if isinstance(path, EPath):
32
+ return path
33
+
34
+ if not path:
35
+ raise ValueError("empty EPath")
36
+
37
+ _path = path
38
+
39
+ if path[0] == '/':
40
+ path = path[1:]
41
+ else:
42
+ raise NotImplementedError("non-root EPath")
43
+
44
+ epath = []
45
+
46
+ for selector in path.split('/'):
47
+ selector = selector.strip()
48
+
49
+ if not selector:
50
+ raise ValueError("empty selector")
51
+
52
+ index = 0
53
+
54
+ for c in selector:
55
+ if c.isalnum() or c in ('_', '|', '?'):
56
+ index += 1
57
+ else:
58
+ break
59
+
60
+ attrs = []
61
+ types = []
62
+
63
+ if index:
64
+ elements = selector[:index]
65
+ selector = selector[index:]
66
+
67
+ for element in elements.split('|'):
68
+ element = element.strip()
69
+
70
+ if not element:
71
+ raise ValueError("empty element")
72
+
73
+ if element.endswith('?'):
74
+ attrs.append(element[:-1])
75
+ else:
76
+ types.append(element)
77
+
78
+ span = None
79
+
80
+ if selector == '*':
81
+ pass
82
+ else:
83
+ if selector.startswith('['):
84
+ try:
85
+ i = selector.index(']')
86
+ except ValueError:
87
+ raise ValueError("expected ']', got EOL")
88
+
89
+ _span, span = selector[1:i], []
90
+
91
+ if ':' not in _span:
92
+ span = int(_span)
93
+ else:
94
+ for elt in _span.split(':', 3):
95
+ if not elt:
96
+ span.append(None)
97
+ else:
98
+ span.append(int(elt))
99
+
100
+ span = slice(*span)
101
+
102
+ selector = selector[i + 1:]
103
+
104
+ if selector:
105
+ raise ValueError("trailing characters in selector")
106
+
107
+ epath.append((attrs, types, span))
108
+
109
+ obj = object.__new__(cls)
110
+
111
+ obj._path = _path
112
+ obj._epath = epath
113
+
114
+ return obj
115
+
116
+ def __repr__(self):
117
+ return "%s(%r)" % (self.__class__.__name__, self._path)
118
+
119
+ def _get_ordered_args(self, expr):
120
+ """Sort ``expr.args`` using printing order. """
121
+ if expr.is_Add:
122
+ return expr.as_ordered_terms()
123
+ elif expr.is_Mul:
124
+ return expr.as_ordered_factors()
125
+ else:
126
+ return expr.args
127
+
128
+ def _hasattrs(self, expr, attrs):
129
+ """Check if ``expr`` has any of ``attrs``. """
130
+ for attr in attrs:
131
+ if not hasattr(expr, attr):
132
+ return False
133
+
134
+ return True
135
+
136
+ def _hastypes(self, expr, types):
137
+ """Check if ``expr`` is any of ``types``. """
138
+ _types = [ cls.__name__ for cls in expr.__class__.mro() ]
139
+ return bool(set(_types).intersection(types))
140
+
141
+ def _has(self, expr, attrs, types):
142
+ """Apply ``_hasattrs`` and ``_hastypes`` to ``expr``. """
143
+ if not (attrs or types):
144
+ return True
145
+
146
+ if attrs and self._hasattrs(expr, attrs):
147
+ return True
148
+
149
+ if types and self._hastypes(expr, types):
150
+ return True
151
+
152
+ return False
153
+
154
+ def apply(self, expr, func, args=None, kwargs=None):
155
+ """
156
+ Modify parts of an expression selected by a path.
157
+
158
+ Examples
159
+ ========
160
+
161
+ >>> from sympy.simplify.epathtools import EPath
162
+ >>> from sympy import sin, cos, E
163
+ >>> from sympy.abc import x, y, z, t
164
+
165
+ >>> path = EPath("/*/[0]/Symbol")
166
+ >>> expr = [((x, 1), 2), ((3, y), z)]
167
+
168
+ >>> path.apply(expr, lambda expr: expr**2)
169
+ [((x**2, 1), 2), ((3, y**2), z)]
170
+
171
+ >>> path = EPath("/*/*/Symbol")
172
+ >>> expr = t + sin(x + 1) + cos(x + y + E)
173
+
174
+ >>> path.apply(expr, lambda expr: 2*expr)
175
+ t + sin(2*x + 1) + cos(2*x + 2*y + E)
176
+
177
+ """
178
+ def _apply(path, expr, func):
179
+ if not path:
180
+ return func(expr)
181
+ else:
182
+ selector, path = path[0], path[1:]
183
+ attrs, types, span = selector
184
+
185
+ if isinstance(expr, Basic):
186
+ if not expr.is_Atom:
187
+ args, basic = self._get_ordered_args(expr), True
188
+ else:
189
+ return expr
190
+ elif hasattr(expr, '__iter__'):
191
+ args, basic = expr, False
192
+ else:
193
+ return expr
194
+
195
+ args = list(args)
196
+
197
+ if span is not None:
198
+ if isinstance(span, slice):
199
+ indices = range(*span.indices(len(args)))
200
+ else:
201
+ indices = [span]
202
+ else:
203
+ indices = range(len(args))
204
+
205
+ for i in indices:
206
+ try:
207
+ arg = args[i]
208
+ except IndexError:
209
+ continue
210
+
211
+ if self._has(arg, attrs, types):
212
+ args[i] = _apply(path, arg, func)
213
+
214
+ if basic:
215
+ return expr.func(*args)
216
+ else:
217
+ return expr.__class__(args)
218
+
219
+ _args, _kwargs = args or (), kwargs or {}
220
+ _func = lambda expr: func(expr, *_args, **_kwargs)
221
+
222
+ return _apply(self._epath, expr, _func)
223
+
224
+ def select(self, expr):
225
+ """
226
+ Retrieve parts of an expression selected by a path.
227
+
228
+ Examples
229
+ ========
230
+
231
+ >>> from sympy.simplify.epathtools import EPath
232
+ >>> from sympy import sin, cos, E
233
+ >>> from sympy.abc import x, y, z, t
234
+
235
+ >>> path = EPath("/*/[0]/Symbol")
236
+ >>> expr = [((x, 1), 2), ((3, y), z)]
237
+
238
+ >>> path.select(expr)
239
+ [x, y]
240
+
241
+ >>> path = EPath("/*/*/Symbol")
242
+ >>> expr = t + sin(x + 1) + cos(x + y + E)
243
+
244
+ >>> path.select(expr)
245
+ [x, x, y]
246
+
247
+ """
248
+ result = []
249
+
250
+ def _select(path, expr):
251
+ if not path:
252
+ result.append(expr)
253
+ else:
254
+ selector, path = path[0], path[1:]
255
+ attrs, types, span = selector
256
+
257
+ if isinstance(expr, Basic):
258
+ args = self._get_ordered_args(expr)
259
+ elif hasattr(expr, '__iter__'):
260
+ args = expr
261
+ else:
262
+ return
263
+
264
+ if span is not None:
265
+ if isinstance(span, slice):
266
+ args = args[span]
267
+ else:
268
+ try:
269
+ args = [args[span]]
270
+ except IndexError:
271
+ return
272
+
273
+ for arg in args:
274
+ if self._has(arg, attrs, types):
275
+ _select(path, arg)
276
+
277
+ _select(self._epath, expr)
278
+ return result
279
+
280
+
281
+ def epath(path, expr=None, func=None, args=None, kwargs=None):
282
+ r"""
283
+ Manipulate parts of an expression selected by a path.
284
+
285
+ Explanation
286
+ ===========
287
+
288
+ This function allows to manipulate large nested expressions in single
289
+ line of code, utilizing techniques to those applied in XML processing
290
+ standards (e.g. XPath).
291
+
292
+ If ``func`` is ``None``, :func:`epath` retrieves elements selected by
293
+ the ``path``. Otherwise it applies ``func`` to each matching element.
294
+
295
+ Note that it is more efficient to create an EPath object and use the select
296
+ and apply methods of that object, since this will compile the path string
297
+ only once. This function should only be used as a convenient shortcut for
298
+ interactive use.
299
+
300
+ This is the supported syntax:
301
+
302
+ * select all: ``/*``
303
+ Equivalent of ``for arg in args:``.
304
+ * select slice: ``/[0]`` or ``/[1:5]`` or ``/[1:5:2]``
305
+ Supports standard Python's slice syntax.
306
+ * select by type: ``/list`` or ``/list|tuple``
307
+ Emulates ``isinstance()``.
308
+ * select by attribute: ``/__iter__?``
309
+ Emulates ``hasattr()``.
310
+
311
+ Parameters
312
+ ==========
313
+
314
+ path : str | EPath
315
+ A path as a string or a compiled EPath.
316
+ expr : Basic | iterable
317
+ An expression or a container of expressions.
318
+ func : callable (optional)
319
+ A callable that will be applied to matching parts.
320
+ args : tuple (optional)
321
+ Additional positional arguments to ``func``.
322
+ kwargs : dict (optional)
323
+ Additional keyword arguments to ``func``.
324
+
325
+ Examples
326
+ ========
327
+
328
+ >>> from sympy.simplify.epathtools import epath
329
+ >>> from sympy import sin, cos, E
330
+ >>> from sympy.abc import x, y, z, t
331
+
332
+ >>> path = "/*/[0]/Symbol"
333
+ >>> expr = [((x, 1), 2), ((3, y), z)]
334
+
335
+ >>> epath(path, expr)
336
+ [x, y]
337
+ >>> epath(path, expr, lambda expr: expr**2)
338
+ [((x**2, 1), 2), ((3, y**2), z)]
339
+
340
+ >>> path = "/*/*/Symbol"
341
+ >>> expr = t + sin(x + 1) + cos(x + y + E)
342
+
343
+ >>> epath(path, expr)
344
+ [x, x, y]
345
+ >>> epath(path, expr, lambda expr: 2*expr)
346
+ t + sin(2*x + 1) + cos(2*x + 2*y + E)
347
+
348
+ """
349
+ _epath = EPath(path)
350
+
351
+ if expr is None:
352
+ return _epath
353
+ if func is None:
354
+ return _epath.select(expr)
355
+ else:
356
+ return _epath.apply(expr, func, args, kwargs)