applied-ai-018 commited on
Commit
c3816c6
·
verified ·
1 Parent(s): 8dd840a

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. env-llmeval/lib/python3.10/site-packages/sympy/diffgeom/__pycache__/__init__.cpython-310.pyc +0 -0
  2. env-llmeval/lib/python3.10/site-packages/sympy/diffgeom/__pycache__/diffgeom.cpython-310.pyc +0 -0
  3. env-llmeval/lib/python3.10/site-packages/sympy/diffgeom/__pycache__/rn.cpython-310.pyc +0 -0
  4. env-llmeval/lib/python3.10/site-packages/sympy/diffgeom/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  5. env-llmeval/lib/python3.10/site-packages/sympy/diffgeom/tests/__pycache__/test_class_structure.cpython-310.pyc +0 -0
  6. env-llmeval/lib/python3.10/site-packages/sympy/diffgeom/tests/__pycache__/test_diffgeom.cpython-310.pyc +0 -0
  7. env-llmeval/lib/python3.10/site-packages/sympy/diffgeom/tests/__pycache__/test_function_diffgeom_book.cpython-310.pyc +0 -0
  8. env-llmeval/lib/python3.10/site-packages/sympy/diffgeom/tests/__pycache__/test_hyperbolic_space.cpython-310.pyc +0 -0
  9. env-llmeval/lib/python3.10/site-packages/sympy/external/__init__.py +20 -0
  10. env-llmeval/lib/python3.10/site-packages/sympy/external/__pycache__/__init__.cpython-310.pyc +0 -0
  11. env-llmeval/lib/python3.10/site-packages/sympy/external/__pycache__/gmpy.cpython-310.pyc +0 -0
  12. env-llmeval/lib/python3.10/site-packages/sympy/external/__pycache__/importtools.cpython-310.pyc +0 -0
  13. env-llmeval/lib/python3.10/site-packages/sympy/external/__pycache__/pythonmpq.cpython-310.pyc +0 -0
  14. env-llmeval/lib/python3.10/site-packages/sympy/external/pythonmpq.py +341 -0
  15. env-llmeval/lib/python3.10/site-packages/sympy/external/tests/__init__.py +0 -0
  16. env-llmeval/lib/python3.10/site-packages/sympy/external/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  17. env-llmeval/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_autowrap.cpython-310.pyc +0 -0
  18. env-llmeval/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_codegen.cpython-310.pyc +0 -0
  19. env-llmeval/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_importtools.cpython-310.pyc +0 -0
  20. env-llmeval/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_numpy.cpython-310.pyc +0 -0
  21. env-llmeval/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_pythonmpq.cpython-310.pyc +0 -0
  22. env-llmeval/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_scipy.cpython-310.pyc +0 -0
  23. env-llmeval/lib/python3.10/site-packages/sympy/external/tests/test_autowrap.py +313 -0
  24. env-llmeval/lib/python3.10/site-packages/sympy/external/tests/test_codegen.py +379 -0
  25. env-llmeval/lib/python3.10/site-packages/sympy/external/tests/test_importtools.py +40 -0
  26. env-llmeval/lib/python3.10/site-packages/sympy/external/tests/test_numpy.py +333 -0
  27. env-llmeval/lib/python3.10/site-packages/sympy/external/tests/test_pythonmpq.py +176 -0
  28. env-llmeval/lib/python3.10/site-packages/sympy/external/tests/test_scipy.py +35 -0
  29. env-llmeval/lib/python3.10/site-packages/sympy/sandbox/__init__.py +8 -0
  30. env-llmeval/lib/python3.10/site-packages/sympy/sandbox/__pycache__/__init__.cpython-310.pyc +0 -0
  31. env-llmeval/lib/python3.10/site-packages/sympy/sandbox/__pycache__/indexed_integrals.cpython-310.pyc +0 -0
  32. env-llmeval/lib/python3.10/site-packages/sympy/sandbox/indexed_integrals.py +72 -0
  33. env-llmeval/lib/python3.10/site-packages/sympy/sandbox/tests/__init__.py +0 -0
  34. env-llmeval/lib/python3.10/site-packages/sympy/sandbox/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  35. env-llmeval/lib/python3.10/site-packages/sympy/sandbox/tests/__pycache__/test_indexed_integrals.cpython-310.pyc +0 -0
  36. env-llmeval/lib/python3.10/site-packages/sympy/sandbox/tests/test_indexed_integrals.py +25 -0
  37. env-llmeval/lib/python3.10/site-packages/sympy/tensor/__init__.py +23 -0
  38. env-llmeval/lib/python3.10/site-packages/sympy/tensor/__pycache__/__init__.cpython-310.pyc +0 -0
  39. env-llmeval/lib/python3.10/site-packages/sympy/tensor/__pycache__/functions.cpython-310.pyc +0 -0
  40. env-llmeval/lib/python3.10/site-packages/sympy/tensor/__pycache__/index_methods.cpython-310.pyc +0 -0
  41. env-llmeval/lib/python3.10/site-packages/sympy/tensor/__pycache__/indexed.cpython-310.pyc +0 -0
  42. env-llmeval/lib/python3.10/site-packages/sympy/tensor/__pycache__/tensor.cpython-310.pyc +0 -0
  43. env-llmeval/lib/python3.10/site-packages/sympy/tensor/__pycache__/toperators.cpython-310.pyc +0 -0
  44. env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/__init__.py +271 -0
  45. env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/array_comprehension.py +399 -0
  46. env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/array_derivatives.py +129 -0
  47. env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/arrayop.py +528 -0
  48. env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/dense_ndim_array.py +206 -0
  49. env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/__init__.py +178 -0
  50. env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/arrayexpr_derivatives.py +194 -0
env-llmeval/lib/python3.10/site-packages/sympy/diffgeom/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (859 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/diffgeom/__pycache__/diffgeom.cpython-310.pyc ADDED
Binary file (76.2 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/diffgeom/__pycache__/rn.cpython-310.pyc ADDED
Binary file (3.65 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/diffgeom/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (185 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/diffgeom/tests/__pycache__/test_class_structure.cpython-310.pyc ADDED
Binary file (1.47 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/diffgeom/tests/__pycache__/test_diffgeom.cpython-310.pyc ADDED
Binary file (13.5 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/diffgeom/tests/__pycache__/test_function_diffgeom_book.cpython-310.pyc ADDED
Binary file (4.97 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/diffgeom/tests/__pycache__/test_hyperbolic_space.cpython-310.pyc ADDED
Binary file (2.74 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/external/__init__.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Unified place for determining if external dependencies are installed or not.
3
+
4
+ You should import all external modules using the import_module() function.
5
+
6
+ For example
7
+
8
+ >>> from sympy.external import import_module
9
+ >>> numpy = import_module('numpy')
10
+
11
+ If the resulting library is not installed, or if the installed version
12
+ is less than a given minimum version, the function will return None.
13
+ Otherwise, it will return the library. See the docstring of
14
+ import_module() for more information.
15
+
16
+ """
17
+
18
+ from sympy.external.importtools import import_module
19
+
20
+ __all__ = ['import_module']
env-llmeval/lib/python3.10/site-packages/sympy/external/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (773 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/external/__pycache__/gmpy.cpython-310.pyc ADDED
Binary file (1.45 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/external/__pycache__/importtools.cpython-310.pyc ADDED
Binary file (5.52 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/external/__pycache__/pythonmpq.cpython-310.pyc ADDED
Binary file (8.8 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/external/pythonmpq.py ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ PythonMPQ: Rational number type based on Python integers.
3
+
4
+ This class is intended as a pure Python fallback for when gmpy2 is not
5
+ installed. If gmpy2 is installed then its mpq type will be used instead. The
6
+ mpq type is around 20x faster. We could just use the stdlib Fraction class
7
+ here but that is slower:
8
+
9
+ from fractions import Fraction
10
+ from sympy.external.pythonmpq import PythonMPQ
11
+ nums = range(1000)
12
+ dens = range(5, 1005)
13
+ rats = [Fraction(n, d) for n, d in zip(nums, dens)]
14
+ sum(rats) # <--- 24 milliseconds
15
+ rats = [PythonMPQ(n, d) for n, d in zip(nums, dens)]
16
+ sum(rats) # <--- 7 milliseconds
17
+
18
+ Both mpq and Fraction have some awkward features like the behaviour of
19
+ division with // and %:
20
+
21
+ >>> from fractions import Fraction
22
+ >>> Fraction(2, 3) % Fraction(1, 4)
23
+ 1/6
24
+
25
+ For the QQ domain we do not want this behaviour because there should be no
26
+ remainder when dividing rational numbers. SymPy does not make use of this
27
+ aspect of mpq when gmpy2 is installed. Since this class is a fallback for that
28
+ case we do not bother implementing e.g. __mod__ so that we can be sure we
29
+ are not using it when gmpy2 is installed either.
30
+ """
31
+
32
+
33
+ import operator
34
+ from math import gcd
35
+ from decimal import Decimal
36
+ from fractions import Fraction
37
+ import sys
38
+ from typing import Tuple as tTuple, Type
39
+
40
+
41
+ # Used for __hash__
42
+ _PyHASH_MODULUS = sys.hash_info.modulus
43
+ _PyHASH_INF = sys.hash_info.inf
44
+
45
+
46
+ class PythonMPQ:
47
+ """Rational number implementation that is intended to be compatible with
48
+ gmpy2's mpq.
49
+
50
+ Also slightly faster than fractions.Fraction.
51
+
52
+ PythonMPQ should be treated as immutable although no effort is made to
53
+ prevent mutation (since that might slow down calculations).
54
+ """
55
+ __slots__ = ('numerator', 'denominator')
56
+
57
+ def __new__(cls, numerator, denominator=None):
58
+ """Construct PythonMPQ with gcd computation and checks"""
59
+ if denominator is not None:
60
+ #
61
+ # PythonMPQ(n, d): require n and d to be int and d != 0
62
+ #
63
+ if isinstance(numerator, int) and isinstance(denominator, int):
64
+ # This is the slow part:
65
+ divisor = gcd(numerator, denominator)
66
+ numerator //= divisor
67
+ denominator //= divisor
68
+ return cls._new_check(numerator, denominator)
69
+ else:
70
+ #
71
+ # PythonMPQ(q)
72
+ #
73
+ # Here q can be PythonMPQ, int, Decimal, float, Fraction or str
74
+ #
75
+ if isinstance(numerator, int):
76
+ return cls._new(numerator, 1)
77
+ elif isinstance(numerator, PythonMPQ):
78
+ return cls._new(numerator.numerator, numerator.denominator)
79
+
80
+ # Let Fraction handle Decimal/float conversion and str parsing
81
+ if isinstance(numerator, (Decimal, float, str)):
82
+ numerator = Fraction(numerator)
83
+ if isinstance(numerator, Fraction):
84
+ return cls._new(numerator.numerator, numerator.denominator)
85
+ #
86
+ # Reject everything else. This is more strict than mpq which allows
87
+ # things like mpq(Fraction, Fraction) or mpq(Decimal, any). The mpq
88
+ # behaviour is somewhat inconsistent so we choose to accept only a
89
+ # more strict subset of what mpq allows.
90
+ #
91
+ raise TypeError("PythonMPQ() requires numeric or string argument")
92
+
93
+ @classmethod
94
+ def _new_check(cls, numerator, denominator):
95
+ """Construct PythonMPQ, check divide by zero and canonicalize signs"""
96
+ if not denominator:
97
+ raise ZeroDivisionError(f'Zero divisor {numerator}/{denominator}')
98
+ elif denominator < 0:
99
+ numerator = -numerator
100
+ denominator = -denominator
101
+ return cls._new(numerator, denominator)
102
+
103
+ @classmethod
104
+ def _new(cls, numerator, denominator):
105
+ """Construct PythonMPQ efficiently (no checks)"""
106
+ obj = super().__new__(cls)
107
+ obj.numerator = numerator
108
+ obj.denominator = denominator
109
+ return obj
110
+
111
+ def __int__(self):
112
+ """Convert to int (truncates towards zero)"""
113
+ p, q = self.numerator, self.denominator
114
+ if p < 0:
115
+ return -(-p//q)
116
+ return p//q
117
+
118
+ def __float__(self):
119
+ """Convert to float (approximately)"""
120
+ return self.numerator / self.denominator
121
+
122
+ def __bool__(self):
123
+ """True/False if nonzero/zero"""
124
+ return bool(self.numerator)
125
+
126
+ def __eq__(self, other):
127
+ """Compare equal with PythonMPQ, int, float, Decimal or Fraction"""
128
+ if isinstance(other, PythonMPQ):
129
+ return (self.numerator == other.numerator
130
+ and self.denominator == other.denominator)
131
+ elif isinstance(other, self._compatible_types):
132
+ return self.__eq__(PythonMPQ(other))
133
+ else:
134
+ return NotImplemented
135
+
136
+ def __hash__(self):
137
+ """hash - same as mpq/Fraction"""
138
+ try:
139
+ dinv = pow(self.denominator, -1, _PyHASH_MODULUS)
140
+ except ValueError:
141
+ hash_ = _PyHASH_INF
142
+ else:
143
+ hash_ = hash(hash(abs(self.numerator)) * dinv)
144
+ result = hash_ if self.numerator >= 0 else -hash_
145
+ return -2 if result == -1 else result
146
+
147
+ def __reduce__(self):
148
+ """Deconstruct for pickling"""
149
+ return type(self), (self.numerator, self.denominator)
150
+
151
+ def __str__(self):
152
+ """Convert to string"""
153
+ if self.denominator != 1:
154
+ return f"{self.numerator}/{self.denominator}"
155
+ else:
156
+ return f"{self.numerator}"
157
+
158
+ def __repr__(self):
159
+ """Convert to string"""
160
+ return f"MPQ({self.numerator},{self.denominator})"
161
+
162
+ def _cmp(self, other, op):
163
+ """Helper for lt/le/gt/ge"""
164
+ if not isinstance(other, self._compatible_types):
165
+ return NotImplemented
166
+ lhs = self.numerator * other.denominator
167
+ rhs = other.numerator * self.denominator
168
+ return op(lhs, rhs)
169
+
170
+ def __lt__(self, other):
171
+ """self < other"""
172
+ return self._cmp(other, operator.lt)
173
+
174
+ def __le__(self, other):
175
+ """self <= other"""
176
+ return self._cmp(other, operator.le)
177
+
178
+ def __gt__(self, other):
179
+ """self > other"""
180
+ return self._cmp(other, operator.gt)
181
+
182
+ def __ge__(self, other):
183
+ """self >= other"""
184
+ return self._cmp(other, operator.ge)
185
+
186
+ def __abs__(self):
187
+ """abs(q)"""
188
+ return self._new(abs(self.numerator), self.denominator)
189
+
190
+ def __pos__(self):
191
+ """+q"""
192
+ return self
193
+
194
+ def __neg__(self):
195
+ """-q"""
196
+ return self._new(-self.numerator, self.denominator)
197
+
198
+ def __add__(self, other):
199
+ """q1 + q2"""
200
+ if isinstance(other, PythonMPQ):
201
+ #
202
+ # This is much faster than the naive method used in the stdlib
203
+ # fractions module. Not sure where this method comes from
204
+ # though...
205
+ #
206
+ # Compare timings for something like:
207
+ # nums = range(1000)
208
+ # rats = [PythonMPQ(n, d) for n, d in zip(nums[:-5], nums[5:])]
209
+ # sum(rats) # <-- time this
210
+ #
211
+ ap, aq = self.numerator, self.denominator
212
+ bp, bq = other.numerator, other.denominator
213
+ g = gcd(aq, bq)
214
+ if g == 1:
215
+ p = ap*bq + aq*bp
216
+ q = bq*aq
217
+ else:
218
+ q1, q2 = aq//g, bq//g
219
+ p, q = ap*q2 + bp*q1, q1*q2
220
+ g2 = gcd(p, g)
221
+ p, q = (p // g2), q * (g // g2)
222
+
223
+ elif isinstance(other, int):
224
+ p = self.numerator + self.denominator * other
225
+ q = self.denominator
226
+ else:
227
+ return NotImplemented
228
+
229
+ return self._new(p, q)
230
+
231
+ def __radd__(self, other):
232
+ """z1 + q2"""
233
+ if isinstance(other, int):
234
+ p = self.numerator + self.denominator * other
235
+ q = self.denominator
236
+ return self._new(p, q)
237
+ else:
238
+ return NotImplemented
239
+
240
+ def __sub__(self ,other):
241
+ """q1 - q2"""
242
+ if isinstance(other, PythonMPQ):
243
+ ap, aq = self.numerator, self.denominator
244
+ bp, bq = other.numerator, other.denominator
245
+ g = gcd(aq, bq)
246
+ if g == 1:
247
+ p = ap*bq - aq*bp
248
+ q = bq*aq
249
+ else:
250
+ q1, q2 = aq//g, bq//g
251
+ p, q = ap*q2 - bp*q1, q1*q2
252
+ g2 = gcd(p, g)
253
+ p, q = (p // g2), q * (g // g2)
254
+ elif isinstance(other, int):
255
+ p = self.numerator - self.denominator*other
256
+ q = self.denominator
257
+ else:
258
+ return NotImplemented
259
+
260
+ return self._new(p, q)
261
+
262
+ def __rsub__(self, other):
263
+ """z1 - q2"""
264
+ if isinstance(other, int):
265
+ p = self.denominator * other - self.numerator
266
+ q = self.denominator
267
+ return self._new(p, q)
268
+ else:
269
+ return NotImplemented
270
+
271
+ def __mul__(self, other):
272
+ """q1 * q2"""
273
+ if isinstance(other, PythonMPQ):
274
+ ap, aq = self.numerator, self.denominator
275
+ bp, bq = other.numerator, other.denominator
276
+ x1 = gcd(ap, bq)
277
+ x2 = gcd(bp, aq)
278
+ p, q = ((ap//x1)*(bp//x2), (aq//x2)*(bq//x1))
279
+ elif isinstance(other, int):
280
+ x = gcd(other, self.denominator)
281
+ p = self.numerator*(other//x)
282
+ q = self.denominator//x
283
+ else:
284
+ return NotImplemented
285
+
286
+ return self._new(p, q)
287
+
288
+ def __rmul__(self, other):
289
+ """z1 * q2"""
290
+ if isinstance(other, int):
291
+ x = gcd(self.denominator, other)
292
+ p = self.numerator*(other//x)
293
+ q = self.denominator//x
294
+ return self._new(p, q)
295
+ else:
296
+ return NotImplemented
297
+
298
+ def __pow__(self, exp):
299
+ """q ** z"""
300
+ p, q = self.numerator, self.denominator
301
+
302
+ if exp < 0:
303
+ p, q, exp = q, p, -exp
304
+
305
+ return self._new_check(p**exp, q**exp)
306
+
307
+ def __truediv__(self, other):
308
+ """q1 / q2"""
309
+ if isinstance(other, PythonMPQ):
310
+ ap, aq = self.numerator, self.denominator
311
+ bp, bq = other.numerator, other.denominator
312
+ x1 = gcd(ap, bp)
313
+ x2 = gcd(bq, aq)
314
+ p, q = ((ap//x1)*(bq//x2), (aq//x2)*(bp//x1))
315
+ elif isinstance(other, int):
316
+ x = gcd(other, self.numerator)
317
+ p = self.numerator//x
318
+ q = self.denominator*(other//x)
319
+ else:
320
+ return NotImplemented
321
+
322
+ return self._new_check(p, q)
323
+
324
+ def __rtruediv__(self, other):
325
+ """z / q"""
326
+ if isinstance(other, int):
327
+ x = gcd(self.numerator, other)
328
+ p = self.denominator*(other//x)
329
+ q = self.numerator//x
330
+ return self._new_check(p, q)
331
+ else:
332
+ return NotImplemented
333
+
334
+ _compatible_types: tTuple[Type, ...] = ()
335
+
336
+ #
337
+ # These are the types that PythonMPQ will interoperate with for operations
338
+ # and comparisons such as ==, + etc. We define this down here so that we can
339
+ # include PythonMPQ in the list as well.
340
+ #
341
+ PythonMPQ._compatible_types = (PythonMPQ, int, Decimal, Fraction)
env-llmeval/lib/python3.10/site-packages/sympy/external/tests/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/sympy/external/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (185 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_autowrap.cpython-310.pyc ADDED
Binary file (9.05 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_codegen.cpython-310.pyc ADDED
Binary file (9.62 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_importtools.cpython-310.pyc ADDED
Binary file (1.47 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_numpy.cpython-310.pyc ADDED
Binary file (10.9 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_pythonmpq.cpython-310.pyc ADDED
Binary file (6.13 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_scipy.cpython-310.pyc ADDED
Binary file (1.05 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/external/tests/test_autowrap.py ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sympy
2
+ import tempfile
3
+ import os
4
+ from sympy.core.mod import Mod
5
+ from sympy.core.relational import Eq
6
+ from sympy.core.symbol import symbols
7
+ from sympy.external import import_module
8
+ from sympy.tensor import IndexedBase, Idx
9
+ from sympy.utilities.autowrap import autowrap, ufuncify, CodeWrapError
10
+ from sympy.testing.pytest import skip
11
+
12
+ numpy = import_module('numpy', min_module_version='1.6.1')
13
+ Cython = import_module('Cython', min_module_version='0.15.1')
14
+ f2py = import_module('numpy.f2py', import_kwargs={'fromlist': ['f2py']})
15
+
16
+ f2pyworks = False
17
+ if f2py:
18
+ try:
19
+ autowrap(symbols('x'), 'f95', 'f2py')
20
+ except (CodeWrapError, ImportError, OSError):
21
+ f2pyworks = False
22
+ else:
23
+ f2pyworks = True
24
+
25
+ a, b, c = symbols('a b c')
26
+ n, m, d = symbols('n m d', integer=True)
27
+ A, B, C = symbols('A B C', cls=IndexedBase)
28
+ i = Idx('i', m)
29
+ j = Idx('j', n)
30
+ k = Idx('k', d)
31
+
32
+
33
+ def has_module(module):
34
+ """
35
+ Return True if module exists, otherwise run skip().
36
+
37
+ module should be a string.
38
+ """
39
+ # To give a string of the module name to skip(), this function takes a
40
+ # string. So we don't waste time running import_module() more than once,
41
+ # just map the three modules tested here in this dict.
42
+ modnames = {'numpy': numpy, 'Cython': Cython, 'f2py': f2py}
43
+
44
+ if modnames[module]:
45
+ if module == 'f2py' and not f2pyworks:
46
+ skip("Couldn't run f2py.")
47
+ return True
48
+ skip("Couldn't import %s." % module)
49
+
50
+ #
51
+ # test runners used by several language-backend combinations
52
+ #
53
+
54
+ def runtest_autowrap_twice(language, backend):
55
+ f = autowrap((((a + b)/c)**5).expand(), language, backend)
56
+ g = autowrap((((a + b)/c)**4).expand(), language, backend)
57
+
58
+ # check that autowrap updates the module name. Else, g gives the same as f
59
+ assert f(1, -2, 1) == -1.0
60
+ assert g(1, -2, 1) == 1.0
61
+
62
+
63
+ def runtest_autowrap_trace(language, backend):
64
+ has_module('numpy')
65
+ trace = autowrap(A[i, i], language, backend)
66
+ assert trace(numpy.eye(100)) == 100
67
+
68
+
69
+ def runtest_autowrap_matrix_vector(language, backend):
70
+ has_module('numpy')
71
+ x, y = symbols('x y', cls=IndexedBase)
72
+ expr = Eq(y[i], A[i, j]*x[j])
73
+ mv = autowrap(expr, language, backend)
74
+
75
+ # compare with numpy's dot product
76
+ M = numpy.random.rand(10, 20)
77
+ x = numpy.random.rand(20)
78
+ y = numpy.dot(M, x)
79
+ assert numpy.sum(numpy.abs(y - mv(M, x))) < 1e-13
80
+
81
+
82
+ def runtest_autowrap_matrix_matrix(language, backend):
83
+ has_module('numpy')
84
+ expr = Eq(C[i, j], A[i, k]*B[k, j])
85
+ matmat = autowrap(expr, language, backend)
86
+
87
+ # compare with numpy's dot product
88
+ M1 = numpy.random.rand(10, 20)
89
+ M2 = numpy.random.rand(20, 15)
90
+ M3 = numpy.dot(M1, M2)
91
+ assert numpy.sum(numpy.abs(M3 - matmat(M1, M2))) < 1e-13
92
+
93
+
94
+ def runtest_ufuncify(language, backend):
95
+ has_module('numpy')
96
+ a, b, c = symbols('a b c')
97
+ fabc = ufuncify([a, b, c], a*b + c, backend=backend)
98
+ facb = ufuncify([a, c, b], a*b + c, backend=backend)
99
+ grid = numpy.linspace(-2, 2, 50)
100
+ b = numpy.linspace(-5, 4, 50)
101
+ c = numpy.linspace(-1, 1, 50)
102
+ expected = grid*b + c
103
+ numpy.testing.assert_allclose(fabc(grid, b, c), expected)
104
+ numpy.testing.assert_allclose(facb(grid, c, b), expected)
105
+
106
+
107
+ def runtest_issue_10274(language, backend):
108
+ expr = (a - b + c)**(13)
109
+ tmp = tempfile.mkdtemp()
110
+ f = autowrap(expr, language, backend, tempdir=tmp,
111
+ helpers=('helper', a - b + c, (a, b, c)))
112
+ assert f(1, 1, 1) == 1
113
+
114
+ for file in os.listdir(tmp):
115
+ if not (file.startswith("wrapped_code_") and file.endswith(".c")):
116
+ continue
117
+
118
+ with open(tmp + '/' + file) as fil:
119
+ lines = fil.readlines()
120
+ assert lines[0] == "/******************************************************************************\n"
121
+ assert "Code generated with SymPy " + sympy.__version__ in lines[1]
122
+ assert lines[2:] == [
123
+ " * *\n",
124
+ " * See http://www.sympy.org/ for more information. *\n",
125
+ " * *\n",
126
+ " * This file is part of 'autowrap' *\n",
127
+ " ******************************************************************************/\n",
128
+ "#include " + '"' + file[:-1]+ 'h"' + "\n",
129
+ "#include <math.h>\n",
130
+ "\n",
131
+ "double helper(double a, double b, double c) {\n",
132
+ "\n",
133
+ " double helper_result;\n",
134
+ " helper_result = a - b + c;\n",
135
+ " return helper_result;\n",
136
+ "\n",
137
+ "}\n",
138
+ "\n",
139
+ "double autofunc(double a, double b, double c) {\n",
140
+ "\n",
141
+ " double autofunc_result;\n",
142
+ " autofunc_result = pow(helper(a, b, c), 13);\n",
143
+ " return autofunc_result;\n",
144
+ "\n",
145
+ "}\n",
146
+ ]
147
+
148
+
149
+ def runtest_issue_15337(language, backend):
150
+ has_module('numpy')
151
+ # NOTE : autowrap was originally designed to only accept an iterable for
152
+ # the kwarg "helpers", but in issue 10274 the user mistakenly thought that
153
+ # if there was only a single helper it did not need to be passed via an
154
+ # iterable that wrapped the helper tuple. There were no tests for this
155
+ # behavior so when the code was changed to accept a single tuple it broke
156
+ # the original behavior. These tests below ensure that both now work.
157
+ a, b, c, d, e = symbols('a, b, c, d, e')
158
+ expr = (a - b + c - d + e)**13
159
+ exp_res = (1. - 2. + 3. - 4. + 5.)**13
160
+
161
+ f = autowrap(expr, language, backend, args=(a, b, c, d, e),
162
+ helpers=('f1', a - b + c, (a, b, c)))
163
+ numpy.testing.assert_allclose(f(1, 2, 3, 4, 5), exp_res)
164
+
165
+ f = autowrap(expr, language, backend, args=(a, b, c, d, e),
166
+ helpers=(('f1', a - b, (a, b)), ('f2', c - d, (c, d))))
167
+ numpy.testing.assert_allclose(f(1, 2, 3, 4, 5), exp_res)
168
+
169
+
170
+ def test_issue_15230():
171
+ has_module('f2py')
172
+
173
+ x, y = symbols('x, y')
174
+ expr = Mod(x, 3.0) - Mod(y, -2.0)
175
+ f = autowrap(expr, args=[x, y], language='F95')
176
+ exp_res = float(expr.xreplace({x: 3.5, y: 2.7}).evalf())
177
+ assert abs(f(3.5, 2.7) - exp_res) < 1e-14
178
+
179
+ x, y = symbols('x, y', integer=True)
180
+ expr = Mod(x, 3) - Mod(y, -2)
181
+ f = autowrap(expr, args=[x, y], language='F95')
182
+ assert f(3, 2) == expr.xreplace({x: 3, y: 2})
183
+
184
+ #
185
+ # tests of language-backend combinations
186
+ #
187
+
188
+ # f2py
189
+
190
+
191
+ def test_wrap_twice_f95_f2py():
192
+ has_module('f2py')
193
+ runtest_autowrap_twice('f95', 'f2py')
194
+
195
+
196
+ def test_autowrap_trace_f95_f2py():
197
+ has_module('f2py')
198
+ runtest_autowrap_trace('f95', 'f2py')
199
+
200
+
201
+ def test_autowrap_matrix_vector_f95_f2py():
202
+ has_module('f2py')
203
+ runtest_autowrap_matrix_vector('f95', 'f2py')
204
+
205
+
206
+ def test_autowrap_matrix_matrix_f95_f2py():
207
+ has_module('f2py')
208
+ runtest_autowrap_matrix_matrix('f95', 'f2py')
209
+
210
+
211
+ def test_ufuncify_f95_f2py():
212
+ has_module('f2py')
213
+ runtest_ufuncify('f95', 'f2py')
214
+
215
+
216
+ def test_issue_15337_f95_f2py():
217
+ has_module('f2py')
218
+ runtest_issue_15337('f95', 'f2py')
219
+
220
+ # Cython
221
+
222
+
223
+ def test_wrap_twice_c_cython():
224
+ has_module('Cython')
225
+ runtest_autowrap_twice('C', 'cython')
226
+
227
+
228
+ def test_autowrap_trace_C_Cython():
229
+ has_module('Cython')
230
+ runtest_autowrap_trace('C99', 'cython')
231
+
232
+
233
+ def test_autowrap_matrix_vector_C_cython():
234
+ has_module('Cython')
235
+ runtest_autowrap_matrix_vector('C99', 'cython')
236
+
237
+
238
+ def test_autowrap_matrix_matrix_C_cython():
239
+ has_module('Cython')
240
+ runtest_autowrap_matrix_matrix('C99', 'cython')
241
+
242
+
243
+ def test_ufuncify_C_Cython():
244
+ has_module('Cython')
245
+ runtest_ufuncify('C99', 'cython')
246
+
247
+
248
+ def test_issue_10274_C_cython():
249
+ has_module('Cython')
250
+ runtest_issue_10274('C89', 'cython')
251
+
252
+
253
+ def test_issue_15337_C_cython():
254
+ has_module('Cython')
255
+ runtest_issue_15337('C89', 'cython')
256
+
257
+
258
+ def test_autowrap_custom_printer():
259
+ has_module('Cython')
260
+
261
+ from sympy.core.numbers import pi
262
+ from sympy.utilities.codegen import C99CodeGen
263
+ from sympy.printing.c import C99CodePrinter
264
+
265
+ class PiPrinter(C99CodePrinter):
266
+ def _print_Pi(self, expr):
267
+ return "S_PI"
268
+
269
+ printer = PiPrinter()
270
+ gen = C99CodeGen(printer=printer)
271
+ gen.preprocessor_statements.append('#include "shortpi.h"')
272
+
273
+ expr = pi * a
274
+
275
+ expected = (
276
+ '#include "%s"\n'
277
+ '#include <math.h>\n'
278
+ '#include "shortpi.h"\n'
279
+ '\n'
280
+ 'double autofunc(double a) {\n'
281
+ '\n'
282
+ ' double autofunc_result;\n'
283
+ ' autofunc_result = S_PI*a;\n'
284
+ ' return autofunc_result;\n'
285
+ '\n'
286
+ '}\n'
287
+ )
288
+
289
+ tmpdir = tempfile.mkdtemp()
290
+ # write a trivial header file to use in the generated code
291
+ with open(os.path.join(tmpdir, 'shortpi.h'), 'w') as f:
292
+ f.write('#define S_PI 3.14')
293
+
294
+ func = autowrap(expr, backend='cython', tempdir=tmpdir, code_gen=gen)
295
+
296
+ assert func(4.2) == 3.14 * 4.2
297
+
298
+ # check that the generated code is correct
299
+ for filename in os.listdir(tmpdir):
300
+ if filename.startswith('wrapped_code') and filename.endswith('.c'):
301
+ with open(os.path.join(tmpdir, filename)) as f:
302
+ lines = f.readlines()
303
+ expected = expected % filename.replace('.c', '.h')
304
+ assert ''.join(lines[7:]) == expected
305
+
306
+
307
+ # Numpy
308
+
309
+ def test_ufuncify_numpy():
310
+ # This test doesn't use Cython, but if Cython works, then there is a valid
311
+ # C compiler, which is needed.
312
+ has_module('Cython')
313
+ runtest_ufuncify('C99', 'numpy')
env-llmeval/lib/python3.10/site-packages/sympy/external/tests/test_codegen.py ADDED
@@ -0,0 +1,379 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This tests the compilation and execution of the source code generated with
2
+ # utilities.codegen. The compilation takes place in a temporary directory that
3
+ # is removed after the test. By default the test directory is always removed,
4
+ # but this behavior can be changed by setting the environment variable
5
+ # SYMPY_TEST_CLEAN_TEMP to:
6
+ # export SYMPY_TEST_CLEAN_TEMP=always : the default behavior.
7
+ # export SYMPY_TEST_CLEAN_TEMP=success : only remove the directories of working tests.
8
+ # export SYMPY_TEST_CLEAN_TEMP=never : never remove the directories with the test code.
9
+ # When a directory is not removed, the necessary information is printed on
10
+ # screen to find the files that belong to the (failed) tests. If a test does
11
+ # not fail, py.test captures all the output and you will not see the directories
12
+ # corresponding to the successful tests. Use the --nocapture option to see all
13
+ # the output.
14
+
15
+ # All tests below have a counterpart in utilities/test/test_codegen.py. In the
16
+ # latter file, the resulting code is compared with predefined strings, without
17
+ # compilation or execution.
18
+
19
+ # All the generated Fortran code should conform with the Fortran 95 standard,
20
+ # and all the generated C code should be ANSI C, which facilitates the
21
+ # incorporation in various projects. The tests below assume that the binary cc
22
+ # is somewhere in the path and that it can compile ANSI C code.
23
+
24
+ from sympy.abc import x, y, z
25
+ from sympy.external import import_module
26
+ from sympy.testing.pytest import skip
27
+ from sympy.utilities.codegen import codegen, make_routine, get_code_generator
28
+ import sys
29
+ import os
30
+ import tempfile
31
+ import subprocess
32
+
33
+
34
+ pyodide_js = import_module('pyodide_js')
35
+
36
+ # templates for the main program that will test the generated code.
37
+
38
+ main_template = {}
39
+ main_template['F95'] = """
40
+ program main
41
+ include "codegen.h"
42
+ integer :: result;
43
+ result = 0
44
+
45
+ %(statements)s
46
+
47
+ call exit(result)
48
+ end program
49
+ """
50
+
51
+ main_template['C89'] = """
52
+ #include "codegen.h"
53
+ #include <stdio.h>
54
+ #include <math.h>
55
+
56
+ int main() {
57
+ int result = 0;
58
+
59
+ %(statements)s
60
+
61
+ return result;
62
+ }
63
+ """
64
+ main_template['C99'] = main_template['C89']
65
+ # templates for the numerical tests
66
+
67
+ numerical_test_template = {}
68
+ numerical_test_template['C89'] = """
69
+ if (fabs(%(call)s)>%(threshold)s) {
70
+ printf("Numerical validation failed: %(call)s=%%e threshold=%(threshold)s\\n", %(call)s);
71
+ result = -1;
72
+ }
73
+ """
74
+ numerical_test_template['C99'] = numerical_test_template['C89']
75
+
76
+ numerical_test_template['F95'] = """
77
+ if (abs(%(call)s)>%(threshold)s) then
78
+ write(6,"('Numerical validation failed:')")
79
+ write(6,"('%(call)s=',e15.5,'threshold=',e15.5)") %(call)s, %(threshold)s
80
+ result = -1;
81
+ end if
82
+ """
83
+ # command sequences for supported compilers
84
+
85
+ compile_commands = {}
86
+ compile_commands['cc'] = [
87
+ "cc -c codegen.c -o codegen.o",
88
+ "cc -c main.c -o main.o",
89
+ "cc main.o codegen.o -lm -o test.exe"
90
+ ]
91
+
92
+ compile_commands['gfortran'] = [
93
+ "gfortran -c codegen.f90 -o codegen.o",
94
+ "gfortran -ffree-line-length-none -c main.f90 -o main.o",
95
+ "gfortran main.o codegen.o -o test.exe"
96
+ ]
97
+
98
+ compile_commands['g95'] = [
99
+ "g95 -c codegen.f90 -o codegen.o",
100
+ "g95 -ffree-line-length-huge -c main.f90 -o main.o",
101
+ "g95 main.o codegen.o -o test.exe"
102
+ ]
103
+
104
+ compile_commands['ifort'] = [
105
+ "ifort -c codegen.f90 -o codegen.o",
106
+ "ifort -c main.f90 -o main.o",
107
+ "ifort main.o codegen.o -o test.exe"
108
+ ]
109
+
110
+ combinations_lang_compiler = [
111
+ ('C89', 'cc'),
112
+ ('C99', 'cc'),
113
+ ('F95', 'ifort'),
114
+ ('F95', 'gfortran'),
115
+ ('F95', 'g95')
116
+ ]
117
+
118
+
119
+ def try_run(commands):
120
+ """Run a series of commands and only return True if all ran fine."""
121
+ if pyodide_js:
122
+ return False
123
+ with open(os.devnull, 'w') as null:
124
+ for command in commands:
125
+ retcode = subprocess.call(command, stdout=null, shell=True,
126
+ stderr=subprocess.STDOUT)
127
+ if retcode != 0:
128
+ return False
129
+ return True
130
+
131
+
132
+ def run_test(label, routines, numerical_tests, language, commands, friendly=True):
133
+ """A driver for the codegen tests.
134
+
135
+ This driver assumes that a compiler ifort is present in the PATH and that
136
+ ifort is (at least) a Fortran 90 compiler. The generated code is written in
137
+ a temporary directory, together with a main program that validates the
138
+ generated code. The test passes when the compilation and the validation
139
+ run correctly.
140
+ """
141
+
142
+ # Check input arguments before touching the file system
143
+ language = language.upper()
144
+ assert language in main_template
145
+ assert language in numerical_test_template
146
+
147
+ # Check that environment variable makes sense
148
+ clean = os.getenv('SYMPY_TEST_CLEAN_TEMP', 'always').lower()
149
+ if clean not in ('always', 'success', 'never'):
150
+ raise ValueError("SYMPY_TEST_CLEAN_TEMP must be one of the following: 'always', 'success' or 'never'.")
151
+
152
+ # Do all the magic to compile, run and validate the test code
153
+ # 1) prepare the temporary working directory, switch to that dir
154
+ work = tempfile.mkdtemp("_sympy_%s_test" % language, "%s_" % label)
155
+ oldwork = os.getcwd()
156
+ os.chdir(work)
157
+
158
+ # 2) write the generated code
159
+ if friendly:
160
+ # interpret the routines as a name_expr list and call the friendly
161
+ # function codegen
162
+ codegen(routines, language, "codegen", to_files=True)
163
+ else:
164
+ code_gen = get_code_generator(language, "codegen")
165
+ code_gen.write(routines, "codegen", to_files=True)
166
+
167
+ # 3) write a simple main program that links to the generated code, and that
168
+ # includes the numerical tests
169
+ test_strings = []
170
+ for fn_name, args, expected, threshold in numerical_tests:
171
+ call_string = "%s(%s)-(%s)" % (
172
+ fn_name, ",".join(str(arg) for arg in args), expected)
173
+ if language == "F95":
174
+ call_string = fortranize_double_constants(call_string)
175
+ threshold = fortranize_double_constants(str(threshold))
176
+ test_strings.append(numerical_test_template[language] % {
177
+ "call": call_string,
178
+ "threshold": threshold,
179
+ })
180
+
181
+ if language == "F95":
182
+ f_name = "main.f90"
183
+ elif language.startswith("C"):
184
+ f_name = "main.c"
185
+ else:
186
+ raise NotImplementedError(
187
+ "FIXME: filename extension unknown for language: %s" % language)
188
+
189
+ with open(f_name, "w") as f:
190
+ f.write(
191
+ main_template[language] % {'statements': "".join(test_strings)})
192
+
193
+ # 4) Compile and link
194
+ compiled = try_run(commands)
195
+
196
+ # 5) Run if compiled
197
+ if compiled:
198
+ executed = try_run(["./test.exe"])
199
+ else:
200
+ executed = False
201
+
202
+ # 6) Clean up stuff
203
+ if clean == 'always' or (clean == 'success' and compiled and executed):
204
+ def safe_remove(filename):
205
+ if os.path.isfile(filename):
206
+ os.remove(filename)
207
+ safe_remove("codegen.f90")
208
+ safe_remove("codegen.c")
209
+ safe_remove("codegen.h")
210
+ safe_remove("codegen.o")
211
+ safe_remove("main.f90")
212
+ safe_remove("main.c")
213
+ safe_remove("main.o")
214
+ safe_remove("test.exe")
215
+ os.chdir(oldwork)
216
+ os.rmdir(work)
217
+ else:
218
+ print("TEST NOT REMOVED: %s" % work, file=sys.stderr)
219
+ os.chdir(oldwork)
220
+
221
+ # 7) Do the assertions in the end
222
+ assert compiled, "failed to compile %s code with:\n%s" % (
223
+ language, "\n".join(commands))
224
+ assert executed, "failed to execute %s code from:\n%s" % (
225
+ language, "\n".join(commands))
226
+
227
+
228
+ def fortranize_double_constants(code_string):
229
+ """
230
+ Replaces every literal float with literal doubles
231
+ """
232
+ import re
233
+ pattern_exp = re.compile(r'\d+(\.)?\d*[eE]-?\d+')
234
+ pattern_float = re.compile(r'\d+\.\d*(?!\d*d)')
235
+
236
+ def subs_exp(matchobj):
237
+ return re.sub('[eE]', 'd', matchobj.group(0))
238
+
239
+ def subs_float(matchobj):
240
+ return "%sd0" % matchobj.group(0)
241
+
242
+ code_string = pattern_exp.sub(subs_exp, code_string)
243
+ code_string = pattern_float.sub(subs_float, code_string)
244
+
245
+ return code_string
246
+
247
+
248
+ def is_feasible(language, commands):
249
+ # This test should always work, otherwise the compiler is not present.
250
+ routine = make_routine("test", x)
251
+ numerical_tests = [
252
+ ("test", ( 1.0,), 1.0, 1e-15),
253
+ ("test", (-1.0,), -1.0, 1e-15),
254
+ ]
255
+ try:
256
+ run_test("is_feasible", [routine], numerical_tests, language, commands,
257
+ friendly=False)
258
+ return True
259
+ except AssertionError:
260
+ return False
261
+
262
+ valid_lang_commands = []
263
+ invalid_lang_compilers = []
264
+ for lang, compiler in combinations_lang_compiler:
265
+ commands = compile_commands[compiler]
266
+ if is_feasible(lang, commands):
267
+ valid_lang_commands.append((lang, commands))
268
+ else:
269
+ invalid_lang_compilers.append((lang, compiler))
270
+
271
+ # We test all language-compiler combinations, just to report what is skipped
272
+
273
+ def test_C89_cc():
274
+ if ("C89", 'cc') in invalid_lang_compilers:
275
+ skip("`cc' command didn't work as expected (C89)")
276
+
277
+
278
+ def test_C99_cc():
279
+ if ("C99", 'cc') in invalid_lang_compilers:
280
+ skip("`cc' command didn't work as expected (C99)")
281
+
282
+
283
+ def test_F95_ifort():
284
+ if ("F95", 'ifort') in invalid_lang_compilers:
285
+ skip("`ifort' command didn't work as expected")
286
+
287
+
288
+ def test_F95_gfortran():
289
+ if ("F95", 'gfortran') in invalid_lang_compilers:
290
+ skip("`gfortran' command didn't work as expected")
291
+
292
+
293
+ def test_F95_g95():
294
+ if ("F95", 'g95') in invalid_lang_compilers:
295
+ skip("`g95' command didn't work as expected")
296
+
297
+ # Here comes the actual tests
298
+
299
+
300
+ def test_basic_codegen():
301
+ numerical_tests = [
302
+ ("test", (1.0, 6.0, 3.0), 21.0, 1e-15),
303
+ ("test", (-1.0, 2.0, -2.5), -2.5, 1e-15),
304
+ ]
305
+ name_expr = [("test", (x + y)*z)]
306
+ for lang, commands in valid_lang_commands:
307
+ run_test("basic_codegen", name_expr, numerical_tests, lang, commands)
308
+
309
+
310
+ def test_intrinsic_math1_codegen():
311
+ # not included: log10
312
+ from sympy.core.evalf import N
313
+ from sympy.functions import ln
314
+ from sympy.functions.elementary.exponential import log
315
+ from sympy.functions.elementary.hyperbolic import (cosh, sinh, tanh)
316
+ from sympy.functions.elementary.integers import (ceiling, floor)
317
+ from sympy.functions.elementary.miscellaneous import sqrt
318
+ from sympy.functions.elementary.trigonometric import (acos, asin, atan, cos, sin, tan)
319
+ name_expr = [
320
+ ("test_fabs", abs(x)),
321
+ ("test_acos", acos(x)),
322
+ ("test_asin", asin(x)),
323
+ ("test_atan", atan(x)),
324
+ ("test_cos", cos(x)),
325
+ ("test_cosh", cosh(x)),
326
+ ("test_log", log(x)),
327
+ ("test_ln", ln(x)),
328
+ ("test_sin", sin(x)),
329
+ ("test_sinh", sinh(x)),
330
+ ("test_sqrt", sqrt(x)),
331
+ ("test_tan", tan(x)),
332
+ ("test_tanh", tanh(x)),
333
+ ]
334
+ numerical_tests = []
335
+ for name, expr in name_expr:
336
+ for xval in 0.2, 0.5, 0.8:
337
+ expected = N(expr.subs(x, xval))
338
+ numerical_tests.append((name, (xval,), expected, 1e-14))
339
+ for lang, commands in valid_lang_commands:
340
+ if lang.startswith("C"):
341
+ name_expr_C = [("test_floor", floor(x)), ("test_ceil", ceiling(x))]
342
+ else:
343
+ name_expr_C = []
344
+ run_test("intrinsic_math1", name_expr + name_expr_C,
345
+ numerical_tests, lang, commands)
346
+
347
+
348
+ def test_instrinsic_math2_codegen():
349
+ # not included: frexp, ldexp, modf, fmod
350
+ from sympy.core.evalf import N
351
+ from sympy.functions.elementary.trigonometric import atan2
352
+ name_expr = [
353
+ ("test_atan2", atan2(x, y)),
354
+ ("test_pow", x**y),
355
+ ]
356
+ numerical_tests = []
357
+ for name, expr in name_expr:
358
+ for xval, yval in (0.2, 1.3), (0.5, -0.2), (0.8, 0.8):
359
+ expected = N(expr.subs(x, xval).subs(y, yval))
360
+ numerical_tests.append((name, (xval, yval), expected, 1e-14))
361
+ for lang, commands in valid_lang_commands:
362
+ run_test("intrinsic_math2", name_expr, numerical_tests, lang, commands)
363
+
364
+
365
+ def test_complicated_codegen():
366
+ from sympy.core.evalf import N
367
+ from sympy.functions.elementary.trigonometric import (cos, sin, tan)
368
+ name_expr = [
369
+ ("test1", ((sin(x) + cos(y) + tan(z))**7).expand()),
370
+ ("test2", cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))),
371
+ ]
372
+ numerical_tests = []
373
+ for name, expr in name_expr:
374
+ for xval, yval, zval in (0.2, 1.3, -0.3), (0.5, -0.2, 0.0), (0.8, 2.1, 0.8):
375
+ expected = N(expr.subs(x, xval).subs(y, yval).subs(z, zval))
376
+ numerical_tests.append((name, (xval, yval, zval), expected, 1e-12))
377
+ for lang, commands in valid_lang_commands:
378
+ run_test(
379
+ "complicated_codegen", name_expr, numerical_tests, lang, commands)
env-llmeval/lib/python3.10/site-packages/sympy/external/tests/test_importtools.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.external import import_module
2
+ from sympy.testing.pytest import warns
3
+
4
+ # fixes issue that arose in addressing issue 6533
5
+ def test_no_stdlib_collections():
6
+ '''
7
+ make sure we get the right collections when it is not part of a
8
+ larger list
9
+ '''
10
+ import collections
11
+ matplotlib = import_module('matplotlib',
12
+ import_kwargs={'fromlist': ['cm', 'collections']},
13
+ min_module_version='1.1.0', catch=(RuntimeError,))
14
+ if matplotlib:
15
+ assert collections != matplotlib.collections
16
+
17
+ def test_no_stdlib_collections2():
18
+ '''
19
+ make sure we get the right collections when it is not part of a
20
+ larger list
21
+ '''
22
+ import collections
23
+ matplotlib = import_module('matplotlib',
24
+ import_kwargs={'fromlist': ['collections']},
25
+ min_module_version='1.1.0', catch=(RuntimeError,))
26
+ if matplotlib:
27
+ assert collections != matplotlib.collections
28
+
29
+ def test_no_stdlib_collections3():
30
+ '''make sure we get the right collections with no catch'''
31
+ import collections
32
+ matplotlib = import_module('matplotlib',
33
+ import_kwargs={'fromlist': ['cm', 'collections']},
34
+ min_module_version='1.1.0')
35
+ if matplotlib:
36
+ assert collections != matplotlib.collections
37
+
38
+ def test_min_module_version_python3_basestring_error():
39
+ with warns(UserWarning):
40
+ import_module('mpmath', min_module_version='1000.0.1')
env-llmeval/lib/python3.10/site-packages/sympy/external/tests/test_numpy.py ADDED
@@ -0,0 +1,333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This testfile tests SymPy <-> NumPy compatibility
2
+
3
+ # Don't test any SymPy features here. Just pure interaction with NumPy.
4
+ # Always write regular SymPy tests for anything, that can be tested in pure
5
+ # Python (without numpy). Here we test everything, that a user may need when
6
+ # using SymPy with NumPy
7
+ from sympy.external.importtools import version_tuple
8
+ from sympy.external import import_module
9
+
10
+ numpy = import_module('numpy')
11
+ if numpy:
12
+ array, matrix, ndarray = numpy.array, numpy.matrix, numpy.ndarray
13
+ else:
14
+ #bin/test will not execute any tests now
15
+ disabled = True
16
+
17
+
18
+ from sympy.core.numbers import (Float, Integer, Rational)
19
+ from sympy.core.symbol import (Symbol, symbols)
20
+ from sympy.functions.elementary.trigonometric import sin
21
+ from sympy.matrices.dense import (Matrix, list2numpy, matrix2numpy, symarray)
22
+ from sympy.utilities.lambdify import lambdify
23
+ import sympy
24
+
25
+ import mpmath
26
+ from sympy.abc import x, y, z
27
+ from sympy.utilities.decorator import conserve_mpmath_dps
28
+ from sympy.utilities.exceptions import ignore_warnings
29
+ from sympy.testing.pytest import raises
30
+
31
+
32
+ # first, systematically check, that all operations are implemented and don't
33
+ # raise an exception
34
+
35
+
36
+ def test_systematic_basic():
37
+ def s(sympy_object, numpy_array):
38
+ _ = [sympy_object + numpy_array,
39
+ numpy_array + sympy_object,
40
+ sympy_object - numpy_array,
41
+ numpy_array - sympy_object,
42
+ sympy_object * numpy_array,
43
+ numpy_array * sympy_object,
44
+ sympy_object / numpy_array,
45
+ numpy_array / sympy_object,
46
+ sympy_object ** numpy_array,
47
+ numpy_array ** sympy_object]
48
+ x = Symbol("x")
49
+ y = Symbol("y")
50
+ sympy_objs = [
51
+ Rational(2, 3),
52
+ Float("1.3"),
53
+ x,
54
+ y,
55
+ pow(x, y)*y,
56
+ Integer(5),
57
+ Float(5.5),
58
+ ]
59
+ numpy_objs = [
60
+ array([1]),
61
+ array([3, 8, -1]),
62
+ array([x, x**2, Rational(5)]),
63
+ array([x/y*sin(y), 5, Rational(5)]),
64
+ ]
65
+ for x in sympy_objs:
66
+ for y in numpy_objs:
67
+ s(x, y)
68
+
69
+
70
+ # now some random tests, that test particular problems and that also
71
+ # check that the results of the operations are correct
72
+
73
+ def test_basics():
74
+ one = Rational(1)
75
+ zero = Rational(0)
76
+ assert array(1) == array(one)
77
+ assert array([one]) == array([one])
78
+ assert array([x]) == array([x])
79
+ assert array(x) == array(Symbol("x"))
80
+ assert array(one + x) == array(1 + x)
81
+
82
+ X = array([one, zero, zero])
83
+ assert (X == array([one, zero, zero])).all()
84
+ assert (X == array([one, 0, 0])).all()
85
+
86
+
87
+ def test_arrays():
88
+ one = Rational(1)
89
+ zero = Rational(0)
90
+ X = array([one, zero, zero])
91
+ Y = one*X
92
+ X = array([Symbol("a") + Rational(1, 2)])
93
+ Y = X + X
94
+ assert Y == array([1 + 2*Symbol("a")])
95
+ Y = Y + 1
96
+ assert Y == array([2 + 2*Symbol("a")])
97
+ Y = X - X
98
+ assert Y == array([0])
99
+
100
+
101
+ def test_conversion1():
102
+ a = list2numpy([x**2, x])
103
+ #looks like an array?
104
+ assert isinstance(a, ndarray)
105
+ assert a[0] == x**2
106
+ assert a[1] == x
107
+ assert len(a) == 2
108
+ #yes, it's the array
109
+
110
+
111
+ def test_conversion2():
112
+ a = 2*list2numpy([x**2, x])
113
+ b = list2numpy([2*x**2, 2*x])
114
+ assert (a == b).all()
115
+
116
+ one = Rational(1)
117
+ zero = Rational(0)
118
+ X = list2numpy([one, zero, zero])
119
+ Y = one*X
120
+ X = list2numpy([Symbol("a") + Rational(1, 2)])
121
+ Y = X + X
122
+ assert Y == array([1 + 2*Symbol("a")])
123
+ Y = Y + 1
124
+ assert Y == array([2 + 2*Symbol("a")])
125
+ Y = X - X
126
+ assert Y == array([0])
127
+
128
+
129
+ def test_list2numpy():
130
+ assert (array([x**2, x]) == list2numpy([x**2, x])).all()
131
+
132
+
133
+ def test_Matrix1():
134
+ m = Matrix([[x, x**2], [5, 2/x]])
135
+ assert (array(m.subs(x, 2)) == array([[2, 4], [5, 1]])).all()
136
+ m = Matrix([[sin(x), x**2], [5, 2/x]])
137
+ assert (array(m.subs(x, 2)) == array([[sin(2), 4], [5, 1]])).all()
138
+
139
+
140
+ def test_Matrix2():
141
+ m = Matrix([[x, x**2], [5, 2/x]])
142
+ with ignore_warnings(PendingDeprecationWarning):
143
+ assert (matrix(m.subs(x, 2)) == matrix([[2, 4], [5, 1]])).all()
144
+ m = Matrix([[sin(x), x**2], [5, 2/x]])
145
+ with ignore_warnings(PendingDeprecationWarning):
146
+ assert (matrix(m.subs(x, 2)) == matrix([[sin(2), 4], [5, 1]])).all()
147
+
148
+
149
+ def test_Matrix3():
150
+ a = array([[2, 4], [5, 1]])
151
+ assert Matrix(a) == Matrix([[2, 4], [5, 1]])
152
+ assert Matrix(a) != Matrix([[2, 4], [5, 2]])
153
+ a = array([[sin(2), 4], [5, 1]])
154
+ assert Matrix(a) == Matrix([[sin(2), 4], [5, 1]])
155
+ assert Matrix(a) != Matrix([[sin(0), 4], [5, 1]])
156
+
157
+
158
+ def test_Matrix4():
159
+ with ignore_warnings(PendingDeprecationWarning):
160
+ a = matrix([[2, 4], [5, 1]])
161
+ assert Matrix(a) == Matrix([[2, 4], [5, 1]])
162
+ assert Matrix(a) != Matrix([[2, 4], [5, 2]])
163
+ with ignore_warnings(PendingDeprecationWarning):
164
+ a = matrix([[sin(2), 4], [5, 1]])
165
+ assert Matrix(a) == Matrix([[sin(2), 4], [5, 1]])
166
+ assert Matrix(a) != Matrix([[sin(0), 4], [5, 1]])
167
+
168
+
169
+ def test_Matrix_sum():
170
+ M = Matrix([[1, 2, 3], [x, y, x], [2*y, -50, z*x]])
171
+ with ignore_warnings(PendingDeprecationWarning):
172
+ m = matrix([[2, 3, 4], [x, 5, 6], [x, y, z**2]])
173
+ assert M + m == Matrix([[3, 5, 7], [2*x, y + 5, x + 6], [2*y + x, y - 50, z*x + z**2]])
174
+ assert m + M == Matrix([[3, 5, 7], [2*x, y + 5, x + 6], [2*y + x, y - 50, z*x + z**2]])
175
+ assert M + m == M.add(m)
176
+
177
+
178
+ def test_Matrix_mul():
179
+ M = Matrix([[1, 2, 3], [x, y, x]])
180
+ with ignore_warnings(PendingDeprecationWarning):
181
+ m = matrix([[2, 4], [x, 6], [x, z**2]])
182
+ assert M*m == Matrix([
183
+ [ 2 + 5*x, 16 + 3*z**2],
184
+ [2*x + x*y + x**2, 4*x + 6*y + x*z**2],
185
+ ])
186
+
187
+ assert m*M == Matrix([
188
+ [ 2 + 4*x, 4 + 4*y, 6 + 4*x],
189
+ [ 7*x, 2*x + 6*y, 9*x],
190
+ [x + x*z**2, 2*x + y*z**2, 3*x + x*z**2],
191
+ ])
192
+ a = array([2])
193
+ assert a[0] * M == 2 * M
194
+ assert M * a[0] == 2 * M
195
+
196
+
197
+ def test_Matrix_array():
198
+ class matarray:
199
+ def __array__(self):
200
+ from numpy import array
201
+ return array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
202
+ matarr = matarray()
203
+ assert Matrix(matarr) == Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
204
+
205
+
206
+ def test_matrix2numpy():
207
+ a = matrix2numpy(Matrix([[1, x**2], [3*sin(x), 0]]))
208
+ assert isinstance(a, ndarray)
209
+ assert a.shape == (2, 2)
210
+ assert a[0, 0] == 1
211
+ assert a[0, 1] == x**2
212
+ assert a[1, 0] == 3*sin(x)
213
+ assert a[1, 1] == 0
214
+
215
+
216
+ def test_matrix2numpy_conversion():
217
+ a = Matrix([[1, 2, sin(x)], [x**2, x, Rational(1, 2)]])
218
+ b = array([[1, 2, sin(x)], [x**2, x, Rational(1, 2)]])
219
+ assert (matrix2numpy(a) == b).all()
220
+ assert matrix2numpy(a).dtype == numpy.dtype('object')
221
+
222
+ c = matrix2numpy(Matrix([[1, 2], [10, 20]]), dtype='int8')
223
+ d = matrix2numpy(Matrix([[1, 2], [10, 20]]), dtype='float64')
224
+ assert c.dtype == numpy.dtype('int8')
225
+ assert d.dtype == numpy.dtype('float64')
226
+
227
+
228
+ def test_issue_3728():
229
+ assert (Rational(1, 2)*array([2*x, 0]) == array([x, 0])).all()
230
+ assert (Rational(1, 2) + array(
231
+ [2*x, 0]) == array([2*x + Rational(1, 2), Rational(1, 2)])).all()
232
+ assert (Float("0.5")*array([2*x, 0]) == array([Float("1.0")*x, 0])).all()
233
+ assert (Float("0.5") + array(
234
+ [2*x, 0]) == array([2*x + Float("0.5"), Float("0.5")])).all()
235
+
236
+
237
+ @conserve_mpmath_dps
238
+ def test_lambdify():
239
+ mpmath.mp.dps = 16
240
+ sin02 = mpmath.mpf("0.198669330795061215459412627")
241
+ f = lambdify(x, sin(x), "numpy")
242
+ prec = 1e-15
243
+ assert -prec < f(0.2) - sin02 < prec
244
+
245
+ # if this succeeds, it can't be a numpy function
246
+
247
+ if version_tuple(numpy.__version__) >= version_tuple('1.17'):
248
+ with raises(TypeError):
249
+ f(x)
250
+ else:
251
+ with raises(AttributeError):
252
+ f(x)
253
+
254
+
255
+ def test_lambdify_matrix():
256
+ f = lambdify(x, Matrix([[x, 2*x], [1, 2]]), [{'ImmutableMatrix': numpy.array}, "numpy"])
257
+ assert (f(1) == array([[1, 2], [1, 2]])).all()
258
+
259
+
260
+ def test_lambdify_matrix_multi_input():
261
+ M = sympy.Matrix([[x**2, x*y, x*z],
262
+ [y*x, y**2, y*z],
263
+ [z*x, z*y, z**2]])
264
+ f = lambdify((x, y, z), M, [{'ImmutableMatrix': numpy.array}, "numpy"])
265
+
266
+ xh, yh, zh = 1.0, 2.0, 3.0
267
+ expected = array([[xh**2, xh*yh, xh*zh],
268
+ [yh*xh, yh**2, yh*zh],
269
+ [zh*xh, zh*yh, zh**2]])
270
+ actual = f(xh, yh, zh)
271
+ assert numpy.allclose(actual, expected)
272
+
273
+
274
+ def test_lambdify_matrix_vec_input():
275
+ X = sympy.DeferredVector('X')
276
+ M = Matrix([
277
+ [X[0]**2, X[0]*X[1], X[0]*X[2]],
278
+ [X[1]*X[0], X[1]**2, X[1]*X[2]],
279
+ [X[2]*X[0], X[2]*X[1], X[2]**2]])
280
+ f = lambdify(X, M, [{'ImmutableMatrix': numpy.array}, "numpy"])
281
+
282
+ Xh = array([1.0, 2.0, 3.0])
283
+ expected = array([[Xh[0]**2, Xh[0]*Xh[1], Xh[0]*Xh[2]],
284
+ [Xh[1]*Xh[0], Xh[1]**2, Xh[1]*Xh[2]],
285
+ [Xh[2]*Xh[0], Xh[2]*Xh[1], Xh[2]**2]])
286
+ actual = f(Xh)
287
+ assert numpy.allclose(actual, expected)
288
+
289
+
290
+ def test_lambdify_transl():
291
+ from sympy.utilities.lambdify import NUMPY_TRANSLATIONS
292
+ for sym, mat in NUMPY_TRANSLATIONS.items():
293
+ assert sym in sympy.__dict__
294
+ assert mat in numpy.__dict__
295
+
296
+
297
+ def test_symarray():
298
+ """Test creation of numpy arrays of SymPy symbols."""
299
+
300
+ import numpy as np
301
+ import numpy.testing as npt
302
+
303
+ syms = symbols('_0,_1,_2')
304
+ s1 = symarray("", 3)
305
+ s2 = symarray("", 3)
306
+ npt.assert_array_equal(s1, np.array(syms, dtype=object))
307
+ assert s1[0] == s2[0]
308
+
309
+ a = symarray('a', 3)
310
+ b = symarray('b', 3)
311
+ assert not(a[0] == b[0])
312
+
313
+ asyms = symbols('a_0,a_1,a_2')
314
+ npt.assert_array_equal(a, np.array(asyms, dtype=object))
315
+
316
+ # Multidimensional checks
317
+ a2d = symarray('a', (2, 3))
318
+ assert a2d.shape == (2, 3)
319
+ a00, a12 = symbols('a_0_0,a_1_2')
320
+ assert a2d[0, 0] == a00
321
+ assert a2d[1, 2] == a12
322
+
323
+ a3d = symarray('a', (2, 3, 2))
324
+ assert a3d.shape == (2, 3, 2)
325
+ a000, a120, a121 = symbols('a_0_0_0,a_1_2_0,a_1_2_1')
326
+ assert a3d[0, 0, 0] == a000
327
+ assert a3d[1, 2, 0] == a120
328
+ assert a3d[1, 2, 1] == a121
329
+
330
+
331
+ def test_vectorize():
332
+ assert (numpy.vectorize(
333
+ sin)([1, 2, 3]) == numpy.array([sin(1), sin(2), sin(3)])).all()
env-llmeval/lib/python3.10/site-packages/sympy/external/tests/test_pythonmpq.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ test_pythonmpq.py
3
+
4
+ Test the PythonMPQ class for consistency with gmpy2's mpq type. If gmpy2 is
5
+ installed run the same tests for both.
6
+ """
7
+ from fractions import Fraction
8
+ from decimal import Decimal
9
+ import pickle
10
+ from typing import Callable, List, Tuple, Type
11
+
12
+ from sympy.testing.pytest import raises
13
+
14
+ from sympy.external.pythonmpq import PythonMPQ
15
+
16
+ #
17
+ # If gmpy2 is installed then run the tests for both mpq and PythonMPQ.
18
+ # That should ensure consistency between the implementation here and mpq.
19
+ #
20
+ rational_types: List[Tuple[Callable, Type, Callable, Type]]
21
+ rational_types = [(PythonMPQ, PythonMPQ, int, int)]
22
+ try:
23
+ from gmpy2 import mpq, mpz
24
+ rational_types.append((mpq, type(mpq(1)), mpz, type(mpz(1))))
25
+ except ImportError:
26
+ pass
27
+
28
+
29
+ def test_PythonMPQ():
30
+ #
31
+ # Test PythonMPQ and also mpq if gmpy/gmpy2 is installed.
32
+ #
33
+ for Q, TQ, Z, TZ in rational_types:
34
+
35
+ def check_Q(q):
36
+ assert isinstance(q, TQ)
37
+ assert isinstance(q.numerator, TZ)
38
+ assert isinstance(q.denominator, TZ)
39
+ return q.numerator, q.denominator
40
+
41
+ # Check construction from different types
42
+ assert check_Q(Q(3)) == (3, 1)
43
+ assert check_Q(Q(3, 5)) == (3, 5)
44
+ assert check_Q(Q(Q(3, 5))) == (3, 5)
45
+ assert check_Q(Q(0.5)) == (1, 2)
46
+ assert check_Q(Q('0.5')) == (1, 2)
47
+ assert check_Q(Q(Fraction(3, 5))) == (3, 5)
48
+
49
+ # https://github.com/aleaxit/gmpy/issues/327
50
+ if Q is PythonMPQ:
51
+ assert check_Q(Q(Decimal('0.6'))) == (3, 5)
52
+
53
+ # Invalid types
54
+ raises(TypeError, lambda: Q([]))
55
+ raises(TypeError, lambda: Q([], []))
56
+
57
+ # Check normalisation of signs
58
+ assert check_Q(Q(2, 3)) == (2, 3)
59
+ assert check_Q(Q(-2, 3)) == (-2, 3)
60
+ assert check_Q(Q(2, -3)) == (-2, 3)
61
+ assert check_Q(Q(-2, -3)) == (2, 3)
62
+
63
+ # Check gcd calculation
64
+ assert check_Q(Q(12, 8)) == (3, 2)
65
+
66
+ # __int__/__float__
67
+ assert int(Q(5, 3)) == 1
68
+ assert int(Q(-5, 3)) == -1
69
+ assert float(Q(5, 2)) == 2.5
70
+ assert float(Q(-5, 2)) == -2.5
71
+
72
+ # __str__/__repr__
73
+ assert str(Q(2, 1)) == "2"
74
+ assert str(Q(1, 2)) == "1/2"
75
+ if Q is PythonMPQ:
76
+ assert repr(Q(2, 1)) == "MPQ(2,1)"
77
+ assert repr(Q(1, 2)) == "MPQ(1,2)"
78
+ else:
79
+ assert repr(Q(2, 1)) == "mpq(2,1)"
80
+ assert repr(Q(1, 2)) == "mpq(1,2)"
81
+
82
+ # __bool__
83
+ assert bool(Q(1, 2)) is True
84
+ assert bool(Q(0)) is False
85
+
86
+ # __eq__/__ne__
87
+ assert (Q(2, 3) == Q(2, 3)) is True
88
+ assert (Q(2, 3) == Q(2, 5)) is False
89
+ assert (Q(2, 3) != Q(2, 3)) is False
90
+ assert (Q(2, 3) != Q(2, 5)) is True
91
+
92
+ # __hash__
93
+ assert hash(Q(3, 5)) == hash(Fraction(3, 5))
94
+
95
+ # __reduce__
96
+ q = Q(2, 3)
97
+ assert pickle.loads(pickle.dumps(q)) == q
98
+
99
+ # __ge__/__gt__/__le__/__lt__
100
+ assert (Q(1, 3) < Q(2, 3)) is True
101
+ assert (Q(2, 3) < Q(2, 3)) is False
102
+ assert (Q(2, 3) < Q(1, 3)) is False
103
+ assert (Q(-2, 3) < Q(1, 3)) is True
104
+ assert (Q(1, 3) < Q(-2, 3)) is False
105
+
106
+ assert (Q(1, 3) <= Q(2, 3)) is True
107
+ assert (Q(2, 3) <= Q(2, 3)) is True
108
+ assert (Q(2, 3) <= Q(1, 3)) is False
109
+ assert (Q(-2, 3) <= Q(1, 3)) is True
110
+ assert (Q(1, 3) <= Q(-2, 3)) is False
111
+
112
+ assert (Q(1, 3) > Q(2, 3)) is False
113
+ assert (Q(2, 3) > Q(2, 3)) is False
114
+ assert (Q(2, 3) > Q(1, 3)) is True
115
+ assert (Q(-2, 3) > Q(1, 3)) is False
116
+ assert (Q(1, 3) > Q(-2, 3)) is True
117
+
118
+ assert (Q(1, 3) >= Q(2, 3)) is False
119
+ assert (Q(2, 3) >= Q(2, 3)) is True
120
+ assert (Q(2, 3) >= Q(1, 3)) is True
121
+ assert (Q(-2, 3) >= Q(1, 3)) is False
122
+ assert (Q(1, 3) >= Q(-2, 3)) is True
123
+
124
+ # __abs__/__pos__/__neg__
125
+ assert abs(Q(2, 3)) == abs(Q(-2, 3)) == Q(2, 3)
126
+ assert +Q(2, 3) == Q(2, 3)
127
+ assert -Q(2, 3) == Q(-2, 3)
128
+
129
+ # __add__/__radd__
130
+ assert Q(2, 3) + Q(5, 7) == Q(29, 21)
131
+ assert Q(2, 3) + 1 == Q(5, 3)
132
+ assert 1 + Q(2, 3) == Q(5, 3)
133
+ raises(TypeError, lambda: [] + Q(1))
134
+ raises(TypeError, lambda: Q(1) + [])
135
+
136
+ # __sub__/__rsub__
137
+ assert Q(2, 3) - Q(5, 7) == Q(-1, 21)
138
+ assert Q(2, 3) - 1 == Q(-1, 3)
139
+ assert 1 - Q(2, 3) == Q(1, 3)
140
+ raises(TypeError, lambda: [] - Q(1))
141
+ raises(TypeError, lambda: Q(1) - [])
142
+
143
+ # __mul__/__rmul__
144
+ assert Q(2, 3) * Q(5, 7) == Q(10, 21)
145
+ assert Q(2, 3) * 1 == Q(2, 3)
146
+ assert 1 * Q(2, 3) == Q(2, 3)
147
+ raises(TypeError, lambda: [] * Q(1))
148
+ raises(TypeError, lambda: Q(1) * [])
149
+
150
+ # __pow__/__rpow__
151
+ assert Q(2, 3) ** 2 == Q(4, 9)
152
+ assert Q(2, 3) ** 1 == Q(2, 3)
153
+ assert Q(-2, 3) ** 2 == Q(4, 9)
154
+ assert Q(-2, 3) ** -1 == Q(-3, 2)
155
+ if Q is PythonMPQ:
156
+ raises(TypeError, lambda: 1 ** Q(2, 3))
157
+ raises(TypeError, lambda: Q(1, 4) ** Q(1, 2))
158
+ raises(TypeError, lambda: [] ** Q(1))
159
+ raises(TypeError, lambda: Q(1) ** [])
160
+
161
+ # __div__/__rdiv__
162
+ assert Q(2, 3) / Q(5, 7) == Q(14, 15)
163
+ assert Q(2, 3) / 1 == Q(2, 3)
164
+ assert 1 / Q(2, 3) == Q(3, 2)
165
+ raises(TypeError, lambda: [] / Q(1))
166
+ raises(TypeError, lambda: Q(1) / [])
167
+ raises(ZeroDivisionError, lambda: Q(1, 2) / Q(0))
168
+
169
+ # __divmod__
170
+ if Q is PythonMPQ:
171
+ raises(TypeError, lambda: Q(2, 3) // Q(1, 3))
172
+ raises(TypeError, lambda: Q(2, 3) % Q(1, 3))
173
+ raises(TypeError, lambda: 1 // Q(1, 3))
174
+ raises(TypeError, lambda: 1 % Q(1, 3))
175
+ raises(TypeError, lambda: Q(2, 3) // 1)
176
+ raises(TypeError, lambda: Q(2, 3) % 1)
env-llmeval/lib/python3.10/site-packages/sympy/external/tests/test_scipy.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This testfile tests SymPy <-> SciPy compatibility
2
+
3
+ # Don't test any SymPy features here. Just pure interaction with SciPy.
4
+ # Always write regular SymPy tests for anything, that can be tested in pure
5
+ # Python (without scipy). Here we test everything, that a user may need when
6
+ # using SymPy with SciPy
7
+
8
+ from sympy.external import import_module
9
+
10
+ scipy = import_module('scipy')
11
+ if not scipy:
12
+ #bin/test will not execute any tests now
13
+ disabled = True
14
+
15
+ from sympy.functions.special.bessel import jn_zeros
16
+
17
+
18
+ def eq(a, b, tol=1e-6):
19
+ for x, y in zip(a, b):
20
+ if not (abs(x - y) < tol):
21
+ return False
22
+ return True
23
+
24
+
25
+ def test_jn_zeros():
26
+ assert eq(jn_zeros(0, 4, method="scipy"),
27
+ [3.141592, 6.283185, 9.424777, 12.566370])
28
+ assert eq(jn_zeros(1, 4, method="scipy"),
29
+ [4.493409, 7.725251, 10.904121, 14.066193])
30
+ assert eq(jn_zeros(2, 4, method="scipy"),
31
+ [5.763459, 9.095011, 12.322940, 15.514603])
32
+ assert eq(jn_zeros(3, 4, method="scipy"),
33
+ [6.987932, 10.417118, 13.698023, 16.923621])
34
+ assert eq(jn_zeros(4, 4, method="scipy"),
35
+ [8.182561, 11.704907, 15.039664, 18.301255])
env-llmeval/lib/python3.10/site-packages/sympy/sandbox/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Sandbox module of SymPy.
3
+
4
+ This module contains experimental code, use at your own risk!
5
+
6
+ There is no warranty that this code will still be located here in future
7
+ versions of SymPy.
8
+ """
env-llmeval/lib/python3.10/site-packages/sympy/sandbox/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (372 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/sandbox/__pycache__/indexed_integrals.cpython-310.pyc ADDED
Binary file (2.56 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/sandbox/indexed_integrals.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.tensor import Indexed
2
+ from sympy.core.containers import Tuple
3
+ from sympy.core.symbol import Dummy
4
+ from sympy.core.sympify import sympify
5
+ from sympy.integrals.integrals import Integral
6
+
7
+
8
+ class IndexedIntegral(Integral):
9
+ """
10
+ Experimental class to test integration by indexed variables.
11
+
12
+ Usage is analogue to ``Integral``, it simply adds awareness of
13
+ integration over indices.
14
+
15
+ Contraction of non-identical index symbols referring to the same
16
+ ``IndexedBase`` is not yet supported.
17
+
18
+ Examples
19
+ ========
20
+
21
+ >>> from sympy.sandbox.indexed_integrals import IndexedIntegral
22
+ >>> from sympy import IndexedBase, symbols
23
+ >>> A = IndexedBase('A')
24
+ >>> i, j = symbols('i j', integer=True)
25
+ >>> ii = IndexedIntegral(A[i], A[i])
26
+ >>> ii
27
+ Integral(_A[i], _A[i])
28
+ >>> ii.doit()
29
+ A[i]**2/2
30
+
31
+ If the indices are different, indexed objects are considered to be
32
+ different variables:
33
+
34
+ >>> i2 = IndexedIntegral(A[j], A[i])
35
+ >>> i2
36
+ Integral(A[j], _A[i])
37
+ >>> i2.doit()
38
+ A[i]*A[j]
39
+ """
40
+
41
+ def __new__(cls, function, *limits, **assumptions):
42
+ repl, limits = IndexedIntegral._indexed_process_limits(limits)
43
+ function = sympify(function)
44
+ function = function.xreplace(repl)
45
+ obj = Integral.__new__(cls, function, *limits, **assumptions)
46
+ obj._indexed_repl = repl
47
+ obj._indexed_reverse_repl = {val: key for key, val in repl.items()}
48
+ return obj
49
+
50
+ def doit(self):
51
+ res = super().doit()
52
+ return res.xreplace(self._indexed_reverse_repl)
53
+
54
+ @staticmethod
55
+ def _indexed_process_limits(limits):
56
+ repl = {}
57
+ newlimits = []
58
+ for i in limits:
59
+ if isinstance(i, (tuple, list, Tuple)):
60
+ v = i[0]
61
+ vrest = i[1:]
62
+ else:
63
+ v = i
64
+ vrest = ()
65
+ if isinstance(v, Indexed):
66
+ if v not in repl:
67
+ r = Dummy(str(v))
68
+ repl[v] = r
69
+ newlimits.append((r,)+vrest)
70
+ else:
71
+ newlimits.append(i)
72
+ return repl, newlimits
env-llmeval/lib/python3.10/site-packages/sympy/sandbox/tests/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/sympy/sandbox/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (184 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/sandbox/tests/__pycache__/test_indexed_integrals.cpython-310.pyc ADDED
Binary file (1.31 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/sandbox/tests/test_indexed_integrals.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.sandbox.indexed_integrals import IndexedIntegral
2
+ from sympy.core.symbol import symbols
3
+ from sympy.functions.elementary.trigonometric import (cos, sin)
4
+ from sympy.tensor.indexed import (Idx, IndexedBase)
5
+
6
+
7
+ def test_indexed_integrals():
8
+ A = IndexedBase('A')
9
+ i, j = symbols('i j', integer=True)
10
+ a1, a2 = symbols('a1:3', cls=Idx)
11
+ assert isinstance(a1, Idx)
12
+
13
+ assert IndexedIntegral(1, A[i]).doit() == A[i]
14
+ assert IndexedIntegral(A[i], A[i]).doit() == A[i] ** 2 / 2
15
+ assert IndexedIntegral(A[j], A[i]).doit() == A[i] * A[j]
16
+ assert IndexedIntegral(A[i] * A[j], A[i]).doit() == A[i] ** 2 * A[j] / 2
17
+ assert IndexedIntegral(sin(A[i]), A[i]).doit() == -cos(A[i])
18
+ assert IndexedIntegral(sin(A[j]), A[i]).doit() == sin(A[j]) * A[i]
19
+
20
+ assert IndexedIntegral(1, A[a1]).doit() == A[a1]
21
+ assert IndexedIntegral(A[a1], A[a1]).doit() == A[a1] ** 2 / 2
22
+ assert IndexedIntegral(A[a2], A[a1]).doit() == A[a1] * A[a2]
23
+ assert IndexedIntegral(A[a1] * A[a2], A[a1]).doit() == A[a1] ** 2 * A[a2] / 2
24
+ assert IndexedIntegral(sin(A[a1]), A[a1]).doit() == -cos(A[a1])
25
+ assert IndexedIntegral(sin(A[a2]), A[a1]).doit() == sin(A[a2]) * A[a1]
env-llmeval/lib/python3.10/site-packages/sympy/tensor/__init__.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A module to manipulate symbolic objects with indices including tensors
2
+
3
+ """
4
+ from .indexed import IndexedBase, Idx, Indexed
5
+ from .index_methods import get_contraction_structure, get_indices
6
+ from .functions import shape
7
+ from .array import (MutableDenseNDimArray, ImmutableDenseNDimArray,
8
+ MutableSparseNDimArray, ImmutableSparseNDimArray, NDimArray, tensorproduct,
9
+ tensorcontraction, tensordiagonal, derive_by_array, permutedims, Array,
10
+ DenseNDimArray, SparseNDimArray,)
11
+
12
+ __all__ = [
13
+ 'IndexedBase', 'Idx', 'Indexed',
14
+
15
+ 'get_contraction_structure', 'get_indices',
16
+
17
+ 'shape',
18
+
19
+ 'MutableDenseNDimArray', 'ImmutableDenseNDimArray',
20
+ 'MutableSparseNDimArray', 'ImmutableSparseNDimArray', 'NDimArray',
21
+ 'tensorproduct', 'tensorcontraction', 'tensordiagonal', 'derive_by_array', 'permutedims',
22
+ 'Array', 'DenseNDimArray', 'SparseNDimArray',
23
+ ]
env-llmeval/lib/python3.10/site-packages/sympy/tensor/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (946 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/tensor/__pycache__/functions.cpython-310.pyc ADDED
Binary file (5.27 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/tensor/__pycache__/index_methods.cpython-310.pyc ADDED
Binary file (13.6 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/tensor/__pycache__/indexed.cpython-310.pyc ADDED
Binary file (23.8 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/tensor/__pycache__/tensor.cpython-310.pyc ADDED
Binary file (151 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/tensor/__pycache__/toperators.cpython-310.pyc ADDED
Binary file (9.19 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/__init__.py ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""
2
+ N-dim array module for SymPy.
3
+
4
+ Four classes are provided to handle N-dim arrays, given by the combinations
5
+ dense/sparse (i.e. whether to store all elements or only the non-zero ones in
6
+ memory) and mutable/immutable (immutable classes are SymPy objects, but cannot
7
+ change after they have been created).
8
+
9
+ Examples
10
+ ========
11
+
12
+ The following examples show the usage of ``Array``. This is an abbreviation for
13
+ ``ImmutableDenseNDimArray``, that is an immutable and dense N-dim array, the
14
+ other classes are analogous. For mutable classes it is also possible to change
15
+ element values after the object has been constructed.
16
+
17
+ Array construction can detect the shape of nested lists and tuples:
18
+
19
+ >>> from sympy import Array
20
+ >>> a1 = Array([[1, 2], [3, 4], [5, 6]])
21
+ >>> a1
22
+ [[1, 2], [3, 4], [5, 6]]
23
+ >>> a1.shape
24
+ (3, 2)
25
+ >>> a1.rank()
26
+ 2
27
+ >>> from sympy.abc import x, y, z
28
+ >>> a2 = Array([[[x, y], [z, x*z]], [[1, x*y], [1/x, x/y]]])
29
+ >>> a2
30
+ [[[x, y], [z, x*z]], [[1, x*y], [1/x, x/y]]]
31
+ >>> a2.shape
32
+ (2, 2, 2)
33
+ >>> a2.rank()
34
+ 3
35
+
36
+ Otherwise one could pass a 1-dim array followed by a shape tuple:
37
+
38
+ >>> m1 = Array(range(12), (3, 4))
39
+ >>> m1
40
+ [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]
41
+ >>> m2 = Array(range(12), (3, 2, 2))
42
+ >>> m2
43
+ [[[0, 1], [2, 3]], [[4, 5], [6, 7]], [[8, 9], [10, 11]]]
44
+ >>> m2[1,1,1]
45
+ 7
46
+ >>> m2.reshape(4, 3)
47
+ [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]
48
+
49
+ Slice support:
50
+
51
+ >>> m2[:, 1, 1]
52
+ [3, 7, 11]
53
+
54
+ Elementwise derivative:
55
+
56
+ >>> from sympy.abc import x, y, z
57
+ >>> m3 = Array([x**3, x*y, z])
58
+ >>> m3.diff(x)
59
+ [3*x**2, y, 0]
60
+ >>> m3.diff(z)
61
+ [0, 0, 1]
62
+
63
+ Multiplication with other SymPy expressions is applied elementwisely:
64
+
65
+ >>> (1+x)*m3
66
+ [x**3*(x + 1), x*y*(x + 1), z*(x + 1)]
67
+
68
+ To apply a function to each element of the N-dim array, use ``applyfunc``:
69
+
70
+ >>> m3.applyfunc(lambda x: x/2)
71
+ [x**3/2, x*y/2, z/2]
72
+
73
+ N-dim arrays can be converted to nested lists by the ``tolist()`` method:
74
+
75
+ >>> m2.tolist()
76
+ [[[0, 1], [2, 3]], [[4, 5], [6, 7]], [[8, 9], [10, 11]]]
77
+ >>> isinstance(m2.tolist(), list)
78
+ True
79
+
80
+ If the rank is 2, it is possible to convert them to matrices with ``tomatrix()``:
81
+
82
+ >>> m1.tomatrix()
83
+ Matrix([
84
+ [0, 1, 2, 3],
85
+ [4, 5, 6, 7],
86
+ [8, 9, 10, 11]])
87
+
88
+ Products and contractions
89
+ -------------------------
90
+
91
+ Tensor product between arrays `A_{i_1,\ldots,i_n}` and `B_{j_1,\ldots,j_m}`
92
+ creates the combined array `P = A \otimes B` defined as
93
+
94
+ `P_{i_1,\ldots,i_n,j_1,\ldots,j_m} := A_{i_1,\ldots,i_n}\cdot B_{j_1,\ldots,j_m}.`
95
+
96
+ It is available through ``tensorproduct(...)``:
97
+
98
+ >>> from sympy import Array, tensorproduct
99
+ >>> from sympy.abc import x,y,z,t
100
+ >>> A = Array([x, y, z, t])
101
+ >>> B = Array([1, 2, 3, 4])
102
+ >>> tensorproduct(A, B)
103
+ [[x, 2*x, 3*x, 4*x], [y, 2*y, 3*y, 4*y], [z, 2*z, 3*z, 4*z], [t, 2*t, 3*t, 4*t]]
104
+
105
+ In case you don't want to evaluate the tensor product immediately, you can use
106
+ ``ArrayTensorProduct``, which creates an unevaluated tensor product expression:
107
+
108
+ >>> from sympy.tensor.array.expressions import ArrayTensorProduct
109
+ >>> ArrayTensorProduct(A, B)
110
+ ArrayTensorProduct([x, y, z, t], [1, 2, 3, 4])
111
+
112
+ Calling ``.as_explicit()`` on ``ArrayTensorProduct`` is equivalent to just calling
113
+ ``tensorproduct(...)``:
114
+
115
+ >>> ArrayTensorProduct(A, B).as_explicit()
116
+ [[x, 2*x, 3*x, 4*x], [y, 2*y, 3*y, 4*y], [z, 2*z, 3*z, 4*z], [t, 2*t, 3*t, 4*t]]
117
+
118
+ Tensor product between a rank-1 array and a matrix creates a rank-3 array:
119
+
120
+ >>> from sympy import eye
121
+ >>> p1 = tensorproduct(A, eye(4))
122
+ >>> p1
123
+ [[[x, 0, 0, 0], [0, x, 0, 0], [0, 0, x, 0], [0, 0, 0, x]], [[y, 0, 0, 0], [0, y, 0, 0], [0, 0, y, 0], [0, 0, 0, y]], [[z, 0, 0, 0], [0, z, 0, 0], [0, 0, z, 0], [0, 0, 0, z]], [[t, 0, 0, 0], [0, t, 0, 0], [0, 0, t, 0], [0, 0, 0, t]]]
124
+
125
+ Now, to get back `A_0 \otimes \mathbf{1}` one can access `p_{0,m,n}` by slicing:
126
+
127
+ >>> p1[0,:,:]
128
+ [[x, 0, 0, 0], [0, x, 0, 0], [0, 0, x, 0], [0, 0, 0, x]]
129
+
130
+ Tensor contraction sums over the specified axes, for example contracting
131
+ positions `a` and `b` means
132
+
133
+ `A_{i_1,\ldots,i_a,\ldots,i_b,\ldots,i_n} \implies \sum_k A_{i_1,\ldots,k,\ldots,k,\ldots,i_n}`
134
+
135
+ Remember that Python indexing is zero starting, to contract the a-th and b-th
136
+ axes it is therefore necessary to specify `a-1` and `b-1`
137
+
138
+ >>> from sympy import tensorcontraction
139
+ >>> C = Array([[x, y], [z, t]])
140
+
141
+ The matrix trace is equivalent to the contraction of a rank-2 array:
142
+
143
+ `A_{m,n} \implies \sum_k A_{k,k}`
144
+
145
+ >>> tensorcontraction(C, (0, 1))
146
+ t + x
147
+
148
+ To create an expression representing a tensor contraction that does not get
149
+ evaluated immediately, use ``ArrayContraction``, which is equivalent to
150
+ ``tensorcontraction(...)`` if it is followed by ``.as_explicit()``:
151
+
152
+ >>> from sympy.tensor.array.expressions import ArrayContraction
153
+ >>> ArrayContraction(C, (0, 1))
154
+ ArrayContraction([[x, y], [z, t]], (0, 1))
155
+ >>> ArrayContraction(C, (0, 1)).as_explicit()
156
+ t + x
157
+
158
+ Matrix product is equivalent to a tensor product of two rank-2 arrays, followed
159
+ by a contraction of the 2nd and 3rd axes (in Python indexing axes number 1, 2).
160
+
161
+ `A_{m,n}\cdot B_{i,j} \implies \sum_k A_{m, k}\cdot B_{k, j}`
162
+
163
+ >>> D = Array([[2, 1], [0, -1]])
164
+ >>> tensorcontraction(tensorproduct(C, D), (1, 2))
165
+ [[2*x, x - y], [2*z, -t + z]]
166
+
167
+ One may verify that the matrix product is equivalent:
168
+
169
+ >>> from sympy import Matrix
170
+ >>> Matrix([[x, y], [z, t]])*Matrix([[2, 1], [0, -1]])
171
+ Matrix([
172
+ [2*x, x - y],
173
+ [2*z, -t + z]])
174
+
175
+ or equivalently
176
+
177
+ >>> C.tomatrix()*D.tomatrix()
178
+ Matrix([
179
+ [2*x, x - y],
180
+ [2*z, -t + z]])
181
+
182
+ Diagonal operator
183
+ -----------------
184
+
185
+ The ``tensordiagonal`` function acts in a similar manner as ``tensorcontraction``,
186
+ but the joined indices are not summed over, for example diagonalizing
187
+ positions `a` and `b` means
188
+
189
+ `A_{i_1,\ldots,i_a,\ldots,i_b,\ldots,i_n} \implies A_{i_1,\ldots,k,\ldots,k,\ldots,i_n}
190
+ \implies \tilde{A}_{i_1,\ldots,i_{a-1},i_{a+1},\ldots,i_{b-1},i_{b+1},\ldots,i_n,k}`
191
+
192
+ where `\tilde{A}` is the array equivalent to the diagonal of `A` at positions
193
+ `a` and `b` moved to the last index slot.
194
+
195
+ Compare the difference between contraction and diagonal operators:
196
+
197
+ >>> from sympy import tensordiagonal
198
+ >>> from sympy.abc import a, b, c, d
199
+ >>> m = Matrix([[a, b], [c, d]])
200
+ >>> tensorcontraction(m, [0, 1])
201
+ a + d
202
+ >>> tensordiagonal(m, [0, 1])
203
+ [a, d]
204
+
205
+ In short, no summation occurs with ``tensordiagonal``.
206
+
207
+
208
+ Derivatives by array
209
+ --------------------
210
+
211
+ The usual derivative operation may be extended to support derivation with
212
+ respect to arrays, provided that all elements in the that array are symbols or
213
+ expressions suitable for derivations.
214
+
215
+ The definition of a derivative by an array is as follows: given the array
216
+ `A_{i_1, \ldots, i_N}` and the array `X_{j_1, \ldots, j_M}`
217
+ the derivative of arrays will return a new array `B` defined by
218
+
219
+ `B_{j_1,\ldots,j_M,i_1,\ldots,i_N} := \frac{\partial A_{i_1,\ldots,i_N}}{\partial X_{j_1,\ldots,j_M}}`
220
+
221
+ The function ``derive_by_array`` performs such an operation:
222
+
223
+ >>> from sympy import derive_by_array
224
+ >>> from sympy.abc import x, y, z, t
225
+ >>> from sympy import sin, exp
226
+
227
+ With scalars, it behaves exactly as the ordinary derivative:
228
+
229
+ >>> derive_by_array(sin(x*y), x)
230
+ y*cos(x*y)
231
+
232
+ Scalar derived by an array basis:
233
+
234
+ >>> derive_by_array(sin(x*y), [x, y, z])
235
+ [y*cos(x*y), x*cos(x*y), 0]
236
+
237
+ Deriving array by an array basis: `B^{nm} := \frac{\partial A^m}{\partial x^n}`
238
+
239
+ >>> basis = [x, y, z]
240
+ >>> ax = derive_by_array([exp(x), sin(y*z), t], basis)
241
+ >>> ax
242
+ [[exp(x), 0, 0], [0, z*cos(y*z), 0], [0, y*cos(y*z), 0]]
243
+
244
+ Contraction of the resulting array: `\sum_m \frac{\partial A^m}{\partial x^m}`
245
+
246
+ >>> tensorcontraction(ax, (0, 1))
247
+ z*cos(y*z) + exp(x)
248
+
249
+ """
250
+
251
+ from .dense_ndim_array import MutableDenseNDimArray, ImmutableDenseNDimArray, DenseNDimArray
252
+ from .sparse_ndim_array import MutableSparseNDimArray, ImmutableSparseNDimArray, SparseNDimArray
253
+ from .ndim_array import NDimArray, ArrayKind
254
+ from .arrayop import tensorproduct, tensorcontraction, tensordiagonal, derive_by_array, permutedims
255
+ from .array_comprehension import ArrayComprehension, ArrayComprehensionMap
256
+
257
+ Array = ImmutableDenseNDimArray
258
+
259
+ __all__ = [
260
+ 'MutableDenseNDimArray', 'ImmutableDenseNDimArray', 'DenseNDimArray',
261
+
262
+ 'MutableSparseNDimArray', 'ImmutableSparseNDimArray', 'SparseNDimArray',
263
+
264
+ 'NDimArray', 'ArrayKind',
265
+
266
+ 'tensorproduct', 'tensorcontraction', 'tensordiagonal', 'derive_by_array',
267
+
268
+ 'permutedims', 'ArrayComprehension', 'ArrayComprehensionMap',
269
+
270
+ 'Array',
271
+ ]
env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/array_comprehension.py ADDED
@@ -0,0 +1,399 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools, itertools
2
+ from sympy.core.sympify import _sympify, sympify
3
+ from sympy.core.expr import Expr
4
+ from sympy.core import Basic, Tuple
5
+ from sympy.tensor.array import ImmutableDenseNDimArray
6
+ from sympy.core.symbol import Symbol
7
+ from sympy.core.numbers import Integer
8
+
9
+
10
+ class ArrayComprehension(Basic):
11
+ """
12
+ Generate a list comprehension.
13
+
14
+ Explanation
15
+ ===========
16
+
17
+ If there is a symbolic dimension, for example, say [i for i in range(1, N)] where
18
+ N is a Symbol, then the expression will not be expanded to an array. Otherwise,
19
+ calling the doit() function will launch the expansion.
20
+
21
+ Examples
22
+ ========
23
+
24
+ >>> from sympy.tensor.array import ArrayComprehension
25
+ >>> from sympy import symbols
26
+ >>> i, j, k = symbols('i j k')
27
+ >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
28
+ >>> a
29
+ ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
30
+ >>> a.doit()
31
+ [[11, 12, 13], [21, 22, 23], [31, 32, 33], [41, 42, 43]]
32
+ >>> b = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, k))
33
+ >>> b.doit()
34
+ ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, k))
35
+ """
36
+ def __new__(cls, function, *symbols, **assumptions):
37
+ if any(len(l) != 3 or None for l in symbols):
38
+ raise ValueError('ArrayComprehension requires values lower and upper bound'
39
+ ' for the expression')
40
+ arglist = [sympify(function)]
41
+ arglist.extend(cls._check_limits_validity(function, symbols))
42
+ obj = Basic.__new__(cls, *arglist, **assumptions)
43
+ obj._limits = obj._args[1:]
44
+ obj._shape = cls._calculate_shape_from_limits(obj._limits)
45
+ obj._rank = len(obj._shape)
46
+ obj._loop_size = cls._calculate_loop_size(obj._shape)
47
+ return obj
48
+
49
+ @property
50
+ def function(self):
51
+ """The function applied across limits.
52
+
53
+ Examples
54
+ ========
55
+
56
+ >>> from sympy.tensor.array import ArrayComprehension
57
+ >>> from sympy import symbols
58
+ >>> i, j = symbols('i j')
59
+ >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
60
+ >>> a.function
61
+ 10*i + j
62
+ """
63
+ return self._args[0]
64
+
65
+ @property
66
+ def limits(self):
67
+ """
68
+ The list of limits that will be applied while expanding the array.
69
+
70
+ Examples
71
+ ========
72
+
73
+ >>> from sympy.tensor.array import ArrayComprehension
74
+ >>> from sympy import symbols
75
+ >>> i, j = symbols('i j')
76
+ >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
77
+ >>> a.limits
78
+ ((i, 1, 4), (j, 1, 3))
79
+ """
80
+ return self._limits
81
+
82
+ @property
83
+ def free_symbols(self):
84
+ """
85
+ The set of the free_symbols in the array.
86
+ Variables appeared in the bounds are supposed to be excluded
87
+ from the free symbol set.
88
+
89
+ Examples
90
+ ========
91
+
92
+ >>> from sympy.tensor.array import ArrayComprehension
93
+ >>> from sympy import symbols
94
+ >>> i, j, k = symbols('i j k')
95
+ >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
96
+ >>> a.free_symbols
97
+ set()
98
+ >>> b = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, k+3))
99
+ >>> b.free_symbols
100
+ {k}
101
+ """
102
+ expr_free_sym = self.function.free_symbols
103
+ for var, inf, sup in self._limits:
104
+ expr_free_sym.discard(var)
105
+ curr_free_syms = inf.free_symbols.union(sup.free_symbols)
106
+ expr_free_sym = expr_free_sym.union(curr_free_syms)
107
+ return expr_free_sym
108
+
109
+ @property
110
+ def variables(self):
111
+ """The tuples of the variables in the limits.
112
+
113
+ Examples
114
+ ========
115
+
116
+ >>> from sympy.tensor.array import ArrayComprehension
117
+ >>> from sympy import symbols
118
+ >>> i, j, k = symbols('i j k')
119
+ >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
120
+ >>> a.variables
121
+ [i, j]
122
+ """
123
+ return [l[0] for l in self._limits]
124
+
125
+ @property
126
+ def bound_symbols(self):
127
+ """The list of dummy variables.
128
+
129
+ Note
130
+ ====
131
+
132
+ Note that all variables are dummy variables since a limit without
133
+ lower bound or upper bound is not accepted.
134
+ """
135
+ return [l[0] for l in self._limits if len(l) != 1]
136
+
137
+ @property
138
+ def shape(self):
139
+ """
140
+ The shape of the expanded array, which may have symbols.
141
+
142
+ Note
143
+ ====
144
+
145
+ Both the lower and the upper bounds are included while
146
+ calculating the shape.
147
+
148
+ Examples
149
+ ========
150
+
151
+ >>> from sympy.tensor.array import ArrayComprehension
152
+ >>> from sympy import symbols
153
+ >>> i, j, k = symbols('i j k')
154
+ >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
155
+ >>> a.shape
156
+ (4, 3)
157
+ >>> b = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, k+3))
158
+ >>> b.shape
159
+ (4, k + 3)
160
+ """
161
+ return self._shape
162
+
163
+ @property
164
+ def is_shape_numeric(self):
165
+ """
166
+ Test if the array is shape-numeric which means there is no symbolic
167
+ dimension.
168
+
169
+ Examples
170
+ ========
171
+
172
+ >>> from sympy.tensor.array import ArrayComprehension
173
+ >>> from sympy import symbols
174
+ >>> i, j, k = symbols('i j k')
175
+ >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
176
+ >>> a.is_shape_numeric
177
+ True
178
+ >>> b = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, k+3))
179
+ >>> b.is_shape_numeric
180
+ False
181
+ """
182
+ for _, inf, sup in self._limits:
183
+ if Basic(inf, sup).atoms(Symbol):
184
+ return False
185
+ return True
186
+
187
+ def rank(self):
188
+ """The rank of the expanded array.
189
+
190
+ Examples
191
+ ========
192
+
193
+ >>> from sympy.tensor.array import ArrayComprehension
194
+ >>> from sympy import symbols
195
+ >>> i, j, k = symbols('i j k')
196
+ >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
197
+ >>> a.rank()
198
+ 2
199
+ """
200
+ return self._rank
201
+
202
+ def __len__(self):
203
+ """
204
+ The length of the expanded array which means the number
205
+ of elements in the array.
206
+
207
+ Raises
208
+ ======
209
+
210
+ ValueError : When the length of the array is symbolic
211
+
212
+ Examples
213
+ ========
214
+
215
+ >>> from sympy.tensor.array import ArrayComprehension
216
+ >>> from sympy import symbols
217
+ >>> i, j = symbols('i j')
218
+ >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
219
+ >>> len(a)
220
+ 12
221
+ """
222
+ if self._loop_size.free_symbols:
223
+ raise ValueError('Symbolic length is not supported')
224
+ return self._loop_size
225
+
226
+ @classmethod
227
+ def _check_limits_validity(cls, function, limits):
228
+ #limits = sympify(limits)
229
+ new_limits = []
230
+ for var, inf, sup in limits:
231
+ var = _sympify(var)
232
+ inf = _sympify(inf)
233
+ #since this is stored as an argument, it should be
234
+ #a Tuple
235
+ if isinstance(sup, list):
236
+ sup = Tuple(*sup)
237
+ else:
238
+ sup = _sympify(sup)
239
+ new_limits.append(Tuple(var, inf, sup))
240
+ if any((not isinstance(i, Expr)) or i.atoms(Symbol, Integer) != i.atoms()
241
+ for i in [inf, sup]):
242
+ raise TypeError('Bounds should be an Expression(combination of Integer and Symbol)')
243
+ if (inf > sup) == True:
244
+ raise ValueError('Lower bound should be inferior to upper bound')
245
+ if var in inf.free_symbols or var in sup.free_symbols:
246
+ raise ValueError('Variable should not be part of its bounds')
247
+ return new_limits
248
+
249
+ @classmethod
250
+ def _calculate_shape_from_limits(cls, limits):
251
+ return tuple([sup - inf + 1 for _, inf, sup in limits])
252
+
253
+ @classmethod
254
+ def _calculate_loop_size(cls, shape):
255
+ if not shape:
256
+ return 0
257
+ loop_size = 1
258
+ for l in shape:
259
+ loop_size = loop_size * l
260
+
261
+ return loop_size
262
+
263
+ def doit(self, **hints):
264
+ if not self.is_shape_numeric:
265
+ return self
266
+
267
+ return self._expand_array()
268
+
269
+ def _expand_array(self):
270
+ res = []
271
+ for values in itertools.product(*[range(inf, sup+1)
272
+ for var, inf, sup
273
+ in self._limits]):
274
+ res.append(self._get_element(values))
275
+
276
+ return ImmutableDenseNDimArray(res, self.shape)
277
+
278
+ def _get_element(self, values):
279
+ temp = self.function
280
+ for var, val in zip(self.variables, values):
281
+ temp = temp.subs(var, val)
282
+ return temp
283
+
284
+ def tolist(self):
285
+ """Transform the expanded array to a list.
286
+
287
+ Raises
288
+ ======
289
+
290
+ ValueError : When there is a symbolic dimension
291
+
292
+ Examples
293
+ ========
294
+
295
+ >>> from sympy.tensor.array import ArrayComprehension
296
+ >>> from sympy import symbols
297
+ >>> i, j = symbols('i j')
298
+ >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
299
+ >>> a.tolist()
300
+ [[11, 12, 13], [21, 22, 23], [31, 32, 33], [41, 42, 43]]
301
+ """
302
+ if self.is_shape_numeric:
303
+ return self._expand_array().tolist()
304
+
305
+ raise ValueError("A symbolic array cannot be expanded to a list")
306
+
307
+ def tomatrix(self):
308
+ """Transform the expanded array to a matrix.
309
+
310
+ Raises
311
+ ======
312
+
313
+ ValueError : When there is a symbolic dimension
314
+ ValueError : When the rank of the expanded array is not equal to 2
315
+
316
+ Examples
317
+ ========
318
+
319
+ >>> from sympy.tensor.array import ArrayComprehension
320
+ >>> from sympy import symbols
321
+ >>> i, j = symbols('i j')
322
+ >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
323
+ >>> a.tomatrix()
324
+ Matrix([
325
+ [11, 12, 13],
326
+ [21, 22, 23],
327
+ [31, 32, 33],
328
+ [41, 42, 43]])
329
+ """
330
+ from sympy.matrices import Matrix
331
+
332
+ if not self.is_shape_numeric:
333
+ raise ValueError("A symbolic array cannot be expanded to a matrix")
334
+ if self._rank != 2:
335
+ raise ValueError('Dimensions must be of size of 2')
336
+
337
+ return Matrix(self._expand_array().tomatrix())
338
+
339
+
340
+ def isLambda(v):
341
+ LAMBDA = lambda: 0
342
+ return isinstance(v, type(LAMBDA)) and v.__name__ == LAMBDA.__name__
343
+
344
+ class ArrayComprehensionMap(ArrayComprehension):
345
+ '''
346
+ A subclass of ArrayComprehension dedicated to map external function lambda.
347
+
348
+ Notes
349
+ =====
350
+
351
+ Only the lambda function is considered.
352
+ At most one argument in lambda function is accepted in order to avoid ambiguity
353
+ in value assignment.
354
+
355
+ Examples
356
+ ========
357
+
358
+ >>> from sympy.tensor.array import ArrayComprehensionMap
359
+ >>> from sympy import symbols
360
+ >>> i, j, k = symbols('i j k')
361
+ >>> a = ArrayComprehensionMap(lambda: 1, (i, 1, 4))
362
+ >>> a.doit()
363
+ [1, 1, 1, 1]
364
+ >>> b = ArrayComprehensionMap(lambda a: a+1, (j, 1, 4))
365
+ >>> b.doit()
366
+ [2, 3, 4, 5]
367
+
368
+ '''
369
+ def __new__(cls, function, *symbols, **assumptions):
370
+ if any(len(l) != 3 or None for l in symbols):
371
+ raise ValueError('ArrayComprehension requires values lower and upper bound'
372
+ ' for the expression')
373
+
374
+ if not isLambda(function):
375
+ raise ValueError('Data type not supported')
376
+
377
+ arglist = cls._check_limits_validity(function, symbols)
378
+ obj = Basic.__new__(cls, *arglist, **assumptions)
379
+ obj._limits = obj._args
380
+ obj._shape = cls._calculate_shape_from_limits(obj._limits)
381
+ obj._rank = len(obj._shape)
382
+ obj._loop_size = cls._calculate_loop_size(obj._shape)
383
+ obj._lambda = function
384
+ return obj
385
+
386
+ @property
387
+ def func(self):
388
+ class _(ArrayComprehensionMap):
389
+ def __new__(cls, *args, **kwargs):
390
+ return ArrayComprehensionMap(self._lambda, *args, **kwargs)
391
+ return _
392
+
393
+ def _get_element(self, values):
394
+ temp = self._lambda
395
+ if self._lambda.__code__.co_argcount == 0:
396
+ temp = temp()
397
+ elif self._lambda.__code__.co_argcount == 1:
398
+ temp = temp(functools.reduce(lambda a, b: a*b, values))
399
+ return temp
env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/array_derivatives.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from sympy.core.expr import Expr
4
+ from sympy.core.function import Derivative
5
+ from sympy.core.numbers import Integer
6
+ from sympy.matrices.common import MatrixCommon
7
+ from .ndim_array import NDimArray
8
+ from .arrayop import derive_by_array
9
+ from sympy.matrices.expressions.matexpr import MatrixExpr
10
+ from sympy.matrices.expressions.special import ZeroMatrix
11
+ from sympy.matrices.expressions.matexpr import _matrix_derivative
12
+
13
+
14
+ class ArrayDerivative(Derivative):
15
+
16
+ is_scalar = False
17
+
18
+ def __new__(cls, expr, *variables, **kwargs):
19
+ obj = super().__new__(cls, expr, *variables, **kwargs)
20
+ if isinstance(obj, ArrayDerivative):
21
+ obj._shape = obj._get_shape()
22
+ return obj
23
+
24
+ def _get_shape(self):
25
+ shape = ()
26
+ for v, count in self.variable_count:
27
+ if hasattr(v, "shape"):
28
+ for i in range(count):
29
+ shape += v.shape
30
+ if hasattr(self.expr, "shape"):
31
+ shape += self.expr.shape
32
+ return shape
33
+
34
+ @property
35
+ def shape(self):
36
+ return self._shape
37
+
38
+ @classmethod
39
+ def _get_zero_with_shape_like(cls, expr):
40
+ if isinstance(expr, (MatrixCommon, NDimArray)):
41
+ return expr.zeros(*expr.shape)
42
+ elif isinstance(expr, MatrixExpr):
43
+ return ZeroMatrix(*expr.shape)
44
+ else:
45
+ raise RuntimeError("Unable to determine shape of array-derivative.")
46
+
47
+ @staticmethod
48
+ def _call_derive_scalar_by_matrix(expr: Expr, v: MatrixCommon) -> Expr:
49
+ return v.applyfunc(lambda x: expr.diff(x))
50
+
51
+ @staticmethod
52
+ def _call_derive_scalar_by_matexpr(expr: Expr, v: MatrixExpr) -> Expr:
53
+ if expr.has(v):
54
+ return _matrix_derivative(expr, v)
55
+ else:
56
+ return ZeroMatrix(*v.shape)
57
+
58
+ @staticmethod
59
+ def _call_derive_scalar_by_array(expr: Expr, v: NDimArray) -> Expr:
60
+ return v.applyfunc(lambda x: expr.diff(x))
61
+
62
+ @staticmethod
63
+ def _call_derive_matrix_by_scalar(expr: MatrixCommon, v: Expr) -> Expr:
64
+ return _matrix_derivative(expr, v)
65
+
66
+ @staticmethod
67
+ def _call_derive_matexpr_by_scalar(expr: MatrixExpr, v: Expr) -> Expr:
68
+ return expr._eval_derivative(v)
69
+
70
+ @staticmethod
71
+ def _call_derive_array_by_scalar(expr: NDimArray, v: Expr) -> Expr:
72
+ return expr.applyfunc(lambda x: x.diff(v))
73
+
74
+ @staticmethod
75
+ def _call_derive_default(expr: Expr, v: Expr) -> Expr | None:
76
+ if expr.has(v):
77
+ return _matrix_derivative(expr, v)
78
+ else:
79
+ return None
80
+
81
+ @classmethod
82
+ def _dispatch_eval_derivative_n_times(cls, expr, v, count):
83
+ # Evaluate the derivative `n` times. If
84
+ # `_eval_derivative_n_times` is not overridden by the current
85
+ # object, the default in `Basic` will call a loop over
86
+ # `_eval_derivative`:
87
+
88
+ if not isinstance(count, (int, Integer)) or ((count <= 0) == True):
89
+ return None
90
+
91
+ # TODO: this could be done with multiple-dispatching:
92
+ if expr.is_scalar:
93
+ if isinstance(v, MatrixCommon):
94
+ result = cls._call_derive_scalar_by_matrix(expr, v)
95
+ elif isinstance(v, MatrixExpr):
96
+ result = cls._call_derive_scalar_by_matexpr(expr, v)
97
+ elif isinstance(v, NDimArray):
98
+ result = cls._call_derive_scalar_by_array(expr, v)
99
+ elif v.is_scalar:
100
+ # scalar by scalar has a special
101
+ return super()._dispatch_eval_derivative_n_times(expr, v, count)
102
+ else:
103
+ return None
104
+ elif v.is_scalar:
105
+ if isinstance(expr, MatrixCommon):
106
+ result = cls._call_derive_matrix_by_scalar(expr, v)
107
+ elif isinstance(expr, MatrixExpr):
108
+ result = cls._call_derive_matexpr_by_scalar(expr, v)
109
+ elif isinstance(expr, NDimArray):
110
+ result = cls._call_derive_array_by_scalar(expr, v)
111
+ else:
112
+ return None
113
+ else:
114
+ # Both `expr` and `v` are some array/matrix type:
115
+ if isinstance(expr, MatrixCommon) or isinstance(expr, MatrixCommon):
116
+ result = derive_by_array(expr, v)
117
+ elif isinstance(expr, MatrixExpr) and isinstance(v, MatrixExpr):
118
+ result = cls._call_derive_default(expr, v)
119
+ elif isinstance(expr, MatrixExpr) or isinstance(v, MatrixExpr):
120
+ # if one expression is a symbolic matrix expression while the other isn't, don't evaluate:
121
+ return None
122
+ else:
123
+ result = derive_by_array(expr, v)
124
+ if result is None:
125
+ return None
126
+ if count == 1:
127
+ return result
128
+ else:
129
+ return cls._dispatch_eval_derivative_n_times(result, v, count - 1)
env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/arrayop.py ADDED
@@ -0,0 +1,528 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools
2
+ from collections.abc import Iterable
3
+
4
+ from sympy.core._print_helpers import Printable
5
+ from sympy.core.containers import Tuple
6
+ from sympy.core.function import diff
7
+ from sympy.core.singleton import S
8
+ from sympy.core.sympify import _sympify
9
+
10
+ from sympy.tensor.array.ndim_array import NDimArray
11
+ from sympy.tensor.array.dense_ndim_array import DenseNDimArray, ImmutableDenseNDimArray
12
+ from sympy.tensor.array.sparse_ndim_array import SparseNDimArray
13
+
14
+
15
+ def _arrayfy(a):
16
+ from sympy.matrices import MatrixBase
17
+
18
+ if isinstance(a, NDimArray):
19
+ return a
20
+ if isinstance(a, (MatrixBase, list, tuple, Tuple)):
21
+ return ImmutableDenseNDimArray(a)
22
+ return a
23
+
24
+
25
+ def tensorproduct(*args):
26
+ """
27
+ Tensor product among scalars or array-like objects.
28
+
29
+ The equivalent operator for array expressions is ``ArrayTensorProduct``,
30
+ which can be used to keep the expression unevaluated.
31
+
32
+ Examples
33
+ ========
34
+
35
+ >>> from sympy.tensor.array import tensorproduct, Array
36
+ >>> from sympy.abc import x, y, z, t
37
+ >>> A = Array([[1, 2], [3, 4]])
38
+ >>> B = Array([x, y])
39
+ >>> tensorproduct(A, B)
40
+ [[[x, y], [2*x, 2*y]], [[3*x, 3*y], [4*x, 4*y]]]
41
+ >>> tensorproduct(A, x)
42
+ [[x, 2*x], [3*x, 4*x]]
43
+ >>> tensorproduct(A, B, B)
44
+ [[[[x**2, x*y], [x*y, y**2]], [[2*x**2, 2*x*y], [2*x*y, 2*y**2]]], [[[3*x**2, 3*x*y], [3*x*y, 3*y**2]], [[4*x**2, 4*x*y], [4*x*y, 4*y**2]]]]
45
+
46
+ Applying this function on two matrices will result in a rank 4 array.
47
+
48
+ >>> from sympy import Matrix, eye
49
+ >>> m = Matrix([[x, y], [z, t]])
50
+ >>> p = tensorproduct(eye(3), m)
51
+ >>> p
52
+ [[[[x, y], [z, t]], [[0, 0], [0, 0]], [[0, 0], [0, 0]]], [[[0, 0], [0, 0]], [[x, y], [z, t]], [[0, 0], [0, 0]]], [[[0, 0], [0, 0]], [[0, 0], [0, 0]], [[x, y], [z, t]]]]
53
+
54
+ See Also
55
+ ========
56
+
57
+ sympy.tensor.array.expressions.array_expressions.ArrayTensorProduct
58
+
59
+ """
60
+ from sympy.tensor.array import SparseNDimArray, ImmutableSparseNDimArray
61
+
62
+ if len(args) == 0:
63
+ return S.One
64
+ if len(args) == 1:
65
+ return _arrayfy(args[0])
66
+ from sympy.tensor.array.expressions.array_expressions import _CodegenArrayAbstract
67
+ from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct
68
+ from sympy.tensor.array.expressions.array_expressions import _ArrayExpr
69
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
70
+ if any(isinstance(arg, (_ArrayExpr, _CodegenArrayAbstract, MatrixSymbol)) for arg in args):
71
+ return ArrayTensorProduct(*args)
72
+ if len(args) > 2:
73
+ return tensorproduct(tensorproduct(args[0], args[1]), *args[2:])
74
+
75
+ # length of args is 2:
76
+ a, b = map(_arrayfy, args)
77
+
78
+ if not isinstance(a, NDimArray) or not isinstance(b, NDimArray):
79
+ return a*b
80
+
81
+ if isinstance(a, SparseNDimArray) and isinstance(b, SparseNDimArray):
82
+ lp = len(b)
83
+ new_array = {k1*lp + k2: v1*v2 for k1, v1 in a._sparse_array.items() for k2, v2 in b._sparse_array.items()}
84
+ return ImmutableSparseNDimArray(new_array, a.shape + b.shape)
85
+
86
+ product_list = [i*j for i in Flatten(a) for j in Flatten(b)]
87
+ return ImmutableDenseNDimArray(product_list, a.shape + b.shape)
88
+
89
+
90
+ def _util_contraction_diagonal(array, *contraction_or_diagonal_axes):
91
+ array = _arrayfy(array)
92
+
93
+ # Verify contraction_axes:
94
+ taken_dims = set()
95
+ for axes_group in contraction_or_diagonal_axes:
96
+ if not isinstance(axes_group, Iterable):
97
+ raise ValueError("collections of contraction/diagonal axes expected")
98
+
99
+ dim = array.shape[axes_group[0]]
100
+
101
+ for d in axes_group:
102
+ if d in taken_dims:
103
+ raise ValueError("dimension specified more than once")
104
+ if dim != array.shape[d]:
105
+ raise ValueError("cannot contract or diagonalize between axes of different dimension")
106
+ taken_dims.add(d)
107
+
108
+ rank = array.rank()
109
+
110
+ remaining_shape = [dim for i, dim in enumerate(array.shape) if i not in taken_dims]
111
+ cum_shape = [0]*rank
112
+ _cumul = 1
113
+ for i in range(rank):
114
+ cum_shape[rank - i - 1] = _cumul
115
+ _cumul *= int(array.shape[rank - i - 1])
116
+
117
+ # DEFINITION: by absolute position it is meant the position along the one
118
+ # dimensional array containing all the tensor components.
119
+
120
+ # Possible future work on this module: move computation of absolute
121
+ # positions to a class method.
122
+
123
+ # Determine absolute positions of the uncontracted indices:
124
+ remaining_indices = [[cum_shape[i]*j for j in range(array.shape[i])]
125
+ for i in range(rank) if i not in taken_dims]
126
+
127
+ # Determine absolute positions of the contracted indices:
128
+ summed_deltas = []
129
+ for axes_group in contraction_or_diagonal_axes:
130
+ lidx = []
131
+ for js in range(array.shape[axes_group[0]]):
132
+ lidx.append(sum([cum_shape[ig] * js for ig in axes_group]))
133
+ summed_deltas.append(lidx)
134
+
135
+ return array, remaining_indices, remaining_shape, summed_deltas
136
+
137
+
138
+ def tensorcontraction(array, *contraction_axes):
139
+ """
140
+ Contraction of an array-like object on the specified axes.
141
+
142
+ The equivalent operator for array expressions is ``ArrayContraction``,
143
+ which can be used to keep the expression unevaluated.
144
+
145
+ Examples
146
+ ========
147
+
148
+ >>> from sympy import Array, tensorcontraction
149
+ >>> from sympy import Matrix, eye
150
+ >>> tensorcontraction(eye(3), (0, 1))
151
+ 3
152
+ >>> A = Array(range(18), (3, 2, 3))
153
+ >>> A
154
+ [[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]], [[12, 13, 14], [15, 16, 17]]]
155
+ >>> tensorcontraction(A, (0, 2))
156
+ [21, 30]
157
+
158
+ Matrix multiplication may be emulated with a proper combination of
159
+ ``tensorcontraction`` and ``tensorproduct``
160
+
161
+ >>> from sympy import tensorproduct
162
+ >>> from sympy.abc import a,b,c,d,e,f,g,h
163
+ >>> m1 = Matrix([[a, b], [c, d]])
164
+ >>> m2 = Matrix([[e, f], [g, h]])
165
+ >>> p = tensorproduct(m1, m2)
166
+ >>> p
167
+ [[[[a*e, a*f], [a*g, a*h]], [[b*e, b*f], [b*g, b*h]]], [[[c*e, c*f], [c*g, c*h]], [[d*e, d*f], [d*g, d*h]]]]
168
+ >>> tensorcontraction(p, (1, 2))
169
+ [[a*e + b*g, a*f + b*h], [c*e + d*g, c*f + d*h]]
170
+ >>> m1*m2
171
+ Matrix([
172
+ [a*e + b*g, a*f + b*h],
173
+ [c*e + d*g, c*f + d*h]])
174
+
175
+ See Also
176
+ ========
177
+
178
+ sympy.tensor.array.expressions.array_expressions.ArrayContraction
179
+
180
+ """
181
+ from sympy.tensor.array.expressions.array_expressions import _array_contraction
182
+ from sympy.tensor.array.expressions.array_expressions import _CodegenArrayAbstract
183
+ from sympy.tensor.array.expressions.array_expressions import _ArrayExpr
184
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
185
+ if isinstance(array, (_ArrayExpr, _CodegenArrayAbstract, MatrixSymbol)):
186
+ return _array_contraction(array, *contraction_axes)
187
+
188
+ array, remaining_indices, remaining_shape, summed_deltas = _util_contraction_diagonal(array, *contraction_axes)
189
+
190
+ # Compute the contracted array:
191
+ #
192
+ # 1. external for loops on all uncontracted indices.
193
+ # Uncontracted indices are determined by the combinatorial product of
194
+ # the absolute positions of the remaining indices.
195
+ # 2. internal loop on all contracted indices.
196
+ # It sums the values of the absolute contracted index and the absolute
197
+ # uncontracted index for the external loop.
198
+ contracted_array = []
199
+ for icontrib in itertools.product(*remaining_indices):
200
+ index_base_position = sum(icontrib)
201
+ isum = S.Zero
202
+ for sum_to_index in itertools.product(*summed_deltas):
203
+ idx = array._get_tuple_index(index_base_position + sum(sum_to_index))
204
+ isum += array[idx]
205
+
206
+ contracted_array.append(isum)
207
+
208
+ if len(remaining_indices) == 0:
209
+ assert len(contracted_array) == 1
210
+ return contracted_array[0]
211
+
212
+ return type(array)(contracted_array, remaining_shape)
213
+
214
+
215
+ def tensordiagonal(array, *diagonal_axes):
216
+ """
217
+ Diagonalization of an array-like object on the specified axes.
218
+
219
+ This is equivalent to multiplying the expression by Kronecker deltas
220
+ uniting the axes.
221
+
222
+ The diagonal indices are put at the end of the axes.
223
+
224
+ The equivalent operator for array expressions is ``ArrayDiagonal``, which
225
+ can be used to keep the expression unevaluated.
226
+
227
+ Examples
228
+ ========
229
+
230
+ ``tensordiagonal`` acting on a 2-dimensional array by axes 0 and 1 is
231
+ equivalent to the diagonal of the matrix:
232
+
233
+ >>> from sympy import Array, tensordiagonal
234
+ >>> from sympy import Matrix, eye
235
+ >>> tensordiagonal(eye(3), (0, 1))
236
+ [1, 1, 1]
237
+
238
+ >>> from sympy.abc import a,b,c,d
239
+ >>> m1 = Matrix([[a, b], [c, d]])
240
+ >>> tensordiagonal(m1, [0, 1])
241
+ [a, d]
242
+
243
+ In case of higher dimensional arrays, the diagonalized out dimensions
244
+ are appended removed and appended as a single dimension at the end:
245
+
246
+ >>> A = Array(range(18), (3, 2, 3))
247
+ >>> A
248
+ [[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]], [[12, 13, 14], [15, 16, 17]]]
249
+ >>> tensordiagonal(A, (0, 2))
250
+ [[0, 7, 14], [3, 10, 17]]
251
+ >>> from sympy import permutedims
252
+ >>> tensordiagonal(A, (0, 2)) == permutedims(Array([A[0, :, 0], A[1, :, 1], A[2, :, 2]]), [1, 0])
253
+ True
254
+
255
+ See Also
256
+ ========
257
+
258
+ sympy.tensor.array.expressions.array_expressions.ArrayDiagonal
259
+
260
+ """
261
+ if any(len(i) <= 1 for i in diagonal_axes):
262
+ raise ValueError("need at least two axes to diagonalize")
263
+
264
+ from sympy.tensor.array.expressions.array_expressions import _ArrayExpr
265
+ from sympy.tensor.array.expressions.array_expressions import _CodegenArrayAbstract
266
+ from sympy.tensor.array.expressions.array_expressions import ArrayDiagonal, _array_diagonal
267
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
268
+ if isinstance(array, (_ArrayExpr, _CodegenArrayAbstract, MatrixSymbol)):
269
+ return _array_diagonal(array, *diagonal_axes)
270
+
271
+ ArrayDiagonal._validate(array, *diagonal_axes)
272
+
273
+ array, remaining_indices, remaining_shape, diagonal_deltas = _util_contraction_diagonal(array, *diagonal_axes)
274
+
275
+ # Compute the diagonalized array:
276
+ #
277
+ # 1. external for loops on all undiagonalized indices.
278
+ # Undiagonalized indices are determined by the combinatorial product of
279
+ # the absolute positions of the remaining indices.
280
+ # 2. internal loop on all diagonal indices.
281
+ # It appends the values of the absolute diagonalized index and the absolute
282
+ # undiagonalized index for the external loop.
283
+ diagonalized_array = []
284
+ diagonal_shape = [len(i) for i in diagonal_deltas]
285
+ for icontrib in itertools.product(*remaining_indices):
286
+ index_base_position = sum(icontrib)
287
+ isum = []
288
+ for sum_to_index in itertools.product(*diagonal_deltas):
289
+ idx = array._get_tuple_index(index_base_position + sum(sum_to_index))
290
+ isum.append(array[idx])
291
+
292
+ isum = type(array)(isum).reshape(*diagonal_shape)
293
+ diagonalized_array.append(isum)
294
+
295
+ return type(array)(diagonalized_array, remaining_shape + diagonal_shape)
296
+
297
+
298
+ def derive_by_array(expr, dx):
299
+ r"""
300
+ Derivative by arrays. Supports both arrays and scalars.
301
+
302
+ The equivalent operator for array expressions is ``array_derive``.
303
+
304
+ Explanation
305
+ ===========
306
+
307
+ Given the array `A_{i_1, \ldots, i_N}` and the array `X_{j_1, \ldots, j_M}`
308
+ this function will return a new array `B` defined by
309
+
310
+ `B_{j_1,\ldots,j_M,i_1,\ldots,i_N} := \frac{\partial A_{i_1,\ldots,i_N}}{\partial X_{j_1,\ldots,j_M}}`
311
+
312
+ Examples
313
+ ========
314
+
315
+ >>> from sympy import derive_by_array
316
+ >>> from sympy.abc import x, y, z, t
317
+ >>> from sympy import cos
318
+ >>> derive_by_array(cos(x*t), x)
319
+ -t*sin(t*x)
320
+ >>> derive_by_array(cos(x*t), [x, y, z, t])
321
+ [-t*sin(t*x), 0, 0, -x*sin(t*x)]
322
+ >>> derive_by_array([x, y**2*z], [[x, y], [z, t]])
323
+ [[[1, 0], [0, 2*y*z]], [[0, y**2], [0, 0]]]
324
+
325
+ """
326
+ from sympy.matrices import MatrixBase
327
+ from sympy.tensor.array import SparseNDimArray
328
+ array_types = (Iterable, MatrixBase, NDimArray)
329
+
330
+ if isinstance(dx, array_types):
331
+ dx = ImmutableDenseNDimArray(dx)
332
+ for i in dx:
333
+ if not i._diff_wrt:
334
+ raise ValueError("cannot derive by this array")
335
+
336
+ if isinstance(expr, array_types):
337
+ if isinstance(expr, NDimArray):
338
+ expr = expr.as_immutable()
339
+ else:
340
+ expr = ImmutableDenseNDimArray(expr)
341
+
342
+ if isinstance(dx, array_types):
343
+ if isinstance(expr, SparseNDimArray):
344
+ lp = len(expr)
345
+ new_array = {k + i*lp: v
346
+ for i, x in enumerate(Flatten(dx))
347
+ for k, v in expr.diff(x)._sparse_array.items()}
348
+ else:
349
+ new_array = [[y.diff(x) for y in Flatten(expr)] for x in Flatten(dx)]
350
+ return type(expr)(new_array, dx.shape + expr.shape)
351
+ else:
352
+ return expr.diff(dx)
353
+ else:
354
+ expr = _sympify(expr)
355
+ if isinstance(dx, array_types):
356
+ return ImmutableDenseNDimArray([expr.diff(i) for i in Flatten(dx)], dx.shape)
357
+ else:
358
+ dx = _sympify(dx)
359
+ return diff(expr, dx)
360
+
361
+
362
+ def permutedims(expr, perm=None, index_order_old=None, index_order_new=None):
363
+ """
364
+ Permutes the indices of an array.
365
+
366
+ Parameter specifies the permutation of the indices.
367
+
368
+ The equivalent operator for array expressions is ``PermuteDims``, which can
369
+ be used to keep the expression unevaluated.
370
+
371
+ Examples
372
+ ========
373
+
374
+ >>> from sympy.abc import x, y, z, t
375
+ >>> from sympy import sin
376
+ >>> from sympy import Array, permutedims
377
+ >>> a = Array([[x, y, z], [t, sin(x), 0]])
378
+ >>> a
379
+ [[x, y, z], [t, sin(x), 0]]
380
+ >>> permutedims(a, (1, 0))
381
+ [[x, t], [y, sin(x)], [z, 0]]
382
+
383
+ If the array is of second order, ``transpose`` can be used:
384
+
385
+ >>> from sympy import transpose
386
+ >>> transpose(a)
387
+ [[x, t], [y, sin(x)], [z, 0]]
388
+
389
+ Examples on higher dimensions:
390
+
391
+ >>> b = Array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
392
+ >>> permutedims(b, (2, 1, 0))
393
+ [[[1, 5], [3, 7]], [[2, 6], [4, 8]]]
394
+ >>> permutedims(b, (1, 2, 0))
395
+ [[[1, 5], [2, 6]], [[3, 7], [4, 8]]]
396
+
397
+ An alternative way to specify the same permutations as in the previous
398
+ lines involves passing the *old* and *new* indices, either as a list or as
399
+ a string:
400
+
401
+ >>> permutedims(b, index_order_old="cba", index_order_new="abc")
402
+ [[[1, 5], [3, 7]], [[2, 6], [4, 8]]]
403
+ >>> permutedims(b, index_order_old="cab", index_order_new="abc")
404
+ [[[1, 5], [2, 6]], [[3, 7], [4, 8]]]
405
+
406
+ ``Permutation`` objects are also allowed:
407
+
408
+ >>> from sympy.combinatorics import Permutation
409
+ >>> permutedims(b, Permutation([1, 2, 0]))
410
+ [[[1, 5], [2, 6]], [[3, 7], [4, 8]]]
411
+
412
+ See Also
413
+ ========
414
+
415
+ sympy.tensor.array.expressions.array_expressions.PermuteDims
416
+
417
+ """
418
+ from sympy.tensor.array import SparseNDimArray
419
+
420
+ from sympy.tensor.array.expressions.array_expressions import _ArrayExpr
421
+ from sympy.tensor.array.expressions.array_expressions import _CodegenArrayAbstract
422
+ from sympy.tensor.array.expressions.array_expressions import _permute_dims
423
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
424
+ from sympy.tensor.array.expressions import PermuteDims
425
+ from sympy.tensor.array.expressions.array_expressions import get_rank
426
+ perm = PermuteDims._get_permutation_from_arguments(perm, index_order_old, index_order_new, get_rank(expr))
427
+ if isinstance(expr, (_ArrayExpr, _CodegenArrayAbstract, MatrixSymbol)):
428
+ return _permute_dims(expr, perm)
429
+
430
+ if not isinstance(expr, NDimArray):
431
+ expr = ImmutableDenseNDimArray(expr)
432
+
433
+ from sympy.combinatorics import Permutation
434
+ if not isinstance(perm, Permutation):
435
+ perm = Permutation(list(perm))
436
+
437
+ if perm.size != expr.rank():
438
+ raise ValueError("wrong permutation size")
439
+
440
+ # Get the inverse permutation:
441
+ iperm = ~perm
442
+ new_shape = perm(expr.shape)
443
+
444
+ if isinstance(expr, SparseNDimArray):
445
+ return type(expr)({tuple(perm(expr._get_tuple_index(k))): v
446
+ for k, v in expr._sparse_array.items()}, new_shape)
447
+
448
+ indices_span = perm([range(i) for i in expr.shape])
449
+
450
+ new_array = [None]*len(expr)
451
+ for i, idx in enumerate(itertools.product(*indices_span)):
452
+ t = iperm(idx)
453
+ new_array[i] = expr[t]
454
+
455
+ return type(expr)(new_array, new_shape)
456
+
457
+
458
+ class Flatten(Printable):
459
+ """
460
+ Flatten an iterable object to a list in a lazy-evaluation way.
461
+
462
+ Notes
463
+ =====
464
+
465
+ This class is an iterator with which the memory cost can be economised.
466
+ Optimisation has been considered to ameliorate the performance for some
467
+ specific data types like DenseNDimArray and SparseNDimArray.
468
+
469
+ Examples
470
+ ========
471
+
472
+ >>> from sympy.tensor.array.arrayop import Flatten
473
+ >>> from sympy.tensor.array import Array
474
+ >>> A = Array(range(6)).reshape(2, 3)
475
+ >>> Flatten(A)
476
+ Flatten([[0, 1, 2], [3, 4, 5]])
477
+ >>> [i for i in Flatten(A)]
478
+ [0, 1, 2, 3, 4, 5]
479
+ """
480
+ def __init__(self, iterable):
481
+ from sympy.matrices.matrices import MatrixBase
482
+ from sympy.tensor.array import NDimArray
483
+
484
+ if not isinstance(iterable, (Iterable, MatrixBase)):
485
+ raise NotImplementedError("Data type not yet supported")
486
+
487
+ if isinstance(iterable, list):
488
+ iterable = NDimArray(iterable)
489
+
490
+ self._iter = iterable
491
+ self._idx = 0
492
+
493
+ def __iter__(self):
494
+ return self
495
+
496
+ def __next__(self):
497
+ from sympy.matrices.matrices import MatrixBase
498
+
499
+ if len(self._iter) > self._idx:
500
+ if isinstance(self._iter, DenseNDimArray):
501
+ result = self._iter._array[self._idx]
502
+
503
+ elif isinstance(self._iter, SparseNDimArray):
504
+ if self._idx in self._iter._sparse_array:
505
+ result = self._iter._sparse_array[self._idx]
506
+ else:
507
+ result = 0
508
+
509
+ elif isinstance(self._iter, MatrixBase):
510
+ result = self._iter[self._idx]
511
+
512
+ elif hasattr(self._iter, '__next__'):
513
+ result = next(self._iter)
514
+
515
+ else:
516
+ result = self._iter[self._idx]
517
+
518
+ else:
519
+ raise StopIteration
520
+
521
+ self._idx += 1
522
+ return result
523
+
524
+ def next(self):
525
+ return self.__next__()
526
+
527
+ def _sympystr(self, printer):
528
+ return type(self).__name__ + '(' + printer._print(self._iter) + ')'
env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/dense_ndim_array.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ from typing import List
3
+
4
+ from sympy.core.basic import Basic
5
+ from sympy.core.containers import Tuple
6
+ from sympy.core.singleton import S
7
+ from sympy.core.sympify import _sympify
8
+ from sympy.tensor.array.mutable_ndim_array import MutableNDimArray
9
+ from sympy.tensor.array.ndim_array import NDimArray, ImmutableNDimArray, ArrayKind
10
+ from sympy.utilities.iterables import flatten
11
+
12
+
13
+ class DenseNDimArray(NDimArray):
14
+
15
+ _array: List[Basic]
16
+
17
+ def __new__(self, *args, **kwargs):
18
+ return ImmutableDenseNDimArray(*args, **kwargs)
19
+
20
+ @property
21
+ def kind(self) -> ArrayKind:
22
+ return ArrayKind._union(self._array)
23
+
24
+ def __getitem__(self, index):
25
+ """
26
+ Allows to get items from N-dim array.
27
+
28
+ Examples
29
+ ========
30
+
31
+ >>> from sympy import MutableDenseNDimArray
32
+ >>> a = MutableDenseNDimArray([0, 1, 2, 3], (2, 2))
33
+ >>> a
34
+ [[0, 1], [2, 3]]
35
+ >>> a[0, 0]
36
+ 0
37
+ >>> a[1, 1]
38
+ 3
39
+ >>> a[0]
40
+ [0, 1]
41
+ >>> a[1]
42
+ [2, 3]
43
+
44
+
45
+ Symbolic index:
46
+
47
+ >>> from sympy.abc import i, j
48
+ >>> a[i, j]
49
+ [[0, 1], [2, 3]][i, j]
50
+
51
+ Replace `i` and `j` to get element `(1, 1)`:
52
+
53
+ >>> a[i, j].subs({i: 1, j: 1})
54
+ 3
55
+
56
+ """
57
+ syindex = self._check_symbolic_index(index)
58
+ if syindex is not None:
59
+ return syindex
60
+
61
+ index = self._check_index_for_getitem(index)
62
+
63
+ if isinstance(index, tuple) and any(isinstance(i, slice) for i in index):
64
+ sl_factors, eindices = self._get_slice_data_for_array_access(index)
65
+ array = [self._array[self._parse_index(i)] for i in eindices]
66
+ nshape = [len(el) for i, el in enumerate(sl_factors) if isinstance(index[i], slice)]
67
+ return type(self)(array, nshape)
68
+ else:
69
+ index = self._parse_index(index)
70
+ return self._array[index]
71
+
72
+ @classmethod
73
+ def zeros(cls, *shape):
74
+ list_length = functools.reduce(lambda x, y: x*y, shape, S.One)
75
+ return cls._new(([0]*list_length,), shape)
76
+
77
+ def tomatrix(self):
78
+ """
79
+ Converts MutableDenseNDimArray to Matrix. Can convert only 2-dim array, else will raise error.
80
+
81
+ Examples
82
+ ========
83
+
84
+ >>> from sympy import MutableDenseNDimArray
85
+ >>> a = MutableDenseNDimArray([1 for i in range(9)], (3, 3))
86
+ >>> b = a.tomatrix()
87
+ >>> b
88
+ Matrix([
89
+ [1, 1, 1],
90
+ [1, 1, 1],
91
+ [1, 1, 1]])
92
+
93
+ """
94
+ from sympy.matrices import Matrix
95
+
96
+ if self.rank() != 2:
97
+ raise ValueError('Dimensions must be of size of 2')
98
+
99
+ return Matrix(self.shape[0], self.shape[1], self._array)
100
+
101
+ def reshape(self, *newshape):
102
+ """
103
+ Returns MutableDenseNDimArray instance with new shape. Elements number
104
+ must be suitable to new shape. The only argument of method sets
105
+ new shape.
106
+
107
+ Examples
108
+ ========
109
+
110
+ >>> from sympy import MutableDenseNDimArray
111
+ >>> a = MutableDenseNDimArray([1, 2, 3, 4, 5, 6], (2, 3))
112
+ >>> a.shape
113
+ (2, 3)
114
+ >>> a
115
+ [[1, 2, 3], [4, 5, 6]]
116
+ >>> b = a.reshape(3, 2)
117
+ >>> b.shape
118
+ (3, 2)
119
+ >>> b
120
+ [[1, 2], [3, 4], [5, 6]]
121
+
122
+ """
123
+ new_total_size = functools.reduce(lambda x,y: x*y, newshape)
124
+ if new_total_size != self._loop_size:
125
+ raise ValueError('Expecting reshape size to %d but got prod(%s) = %d' % (
126
+ self._loop_size, str(newshape), new_total_size))
127
+
128
+ # there is no `.func` as this class does not subtype `Basic`:
129
+ return type(self)(self._array, newshape)
130
+
131
+
132
+ class ImmutableDenseNDimArray(DenseNDimArray, ImmutableNDimArray): # type: ignore
133
+ def __new__(cls, iterable, shape=None, **kwargs):
134
+ return cls._new(iterable, shape, **kwargs)
135
+
136
+ @classmethod
137
+ def _new(cls, iterable, shape, **kwargs):
138
+ shape, flat_list = cls._handle_ndarray_creation_inputs(iterable, shape, **kwargs)
139
+ shape = Tuple(*map(_sympify, shape))
140
+ cls._check_special_bounds(flat_list, shape)
141
+ flat_list = flatten(flat_list)
142
+ flat_list = Tuple(*flat_list)
143
+ self = Basic.__new__(cls, flat_list, shape, **kwargs)
144
+ self._shape = shape
145
+ self._array = list(flat_list)
146
+ self._rank = len(shape)
147
+ self._loop_size = functools.reduce(lambda x,y: x*y, shape, 1)
148
+ return self
149
+
150
+ def __setitem__(self, index, value):
151
+ raise TypeError('immutable N-dim array')
152
+
153
+ def as_mutable(self):
154
+ return MutableDenseNDimArray(self)
155
+
156
+ def _eval_simplify(self, **kwargs):
157
+ from sympy.simplify.simplify import simplify
158
+ return self.applyfunc(simplify)
159
+
160
+ class MutableDenseNDimArray(DenseNDimArray, MutableNDimArray):
161
+
162
+ def __new__(cls, iterable=None, shape=None, **kwargs):
163
+ return cls._new(iterable, shape, **kwargs)
164
+
165
+ @classmethod
166
+ def _new(cls, iterable, shape, **kwargs):
167
+ shape, flat_list = cls._handle_ndarray_creation_inputs(iterable, shape, **kwargs)
168
+ flat_list = flatten(flat_list)
169
+ self = object.__new__(cls)
170
+ self._shape = shape
171
+ self._array = list(flat_list)
172
+ self._rank = len(shape)
173
+ self._loop_size = functools.reduce(lambda x,y: x*y, shape) if shape else len(flat_list)
174
+ return self
175
+
176
+ def __setitem__(self, index, value):
177
+ """Allows to set items to MutableDenseNDimArray.
178
+
179
+ Examples
180
+ ========
181
+
182
+ >>> from sympy import MutableDenseNDimArray
183
+ >>> a = MutableDenseNDimArray.zeros(2, 2)
184
+ >>> a[0,0] = 1
185
+ >>> a[1,1] = 1
186
+ >>> a
187
+ [[1, 0], [0, 1]]
188
+
189
+ """
190
+ if isinstance(index, tuple) and any(isinstance(i, slice) for i in index):
191
+ value, eindices, slice_offsets = self._get_slice_data_for_array_assignment(index, value)
192
+ for i in eindices:
193
+ other_i = [ind - j for ind, j in zip(i, slice_offsets) if j is not None]
194
+ self._array[self._parse_index(i)] = value[other_i]
195
+ else:
196
+ index = self._parse_index(index)
197
+ self._setter_iterable_check(value)
198
+ value = _sympify(value)
199
+ self._array[index] = value
200
+
201
+ def as_immutable(self):
202
+ return ImmutableDenseNDimArray(self)
203
+
204
+ @property
205
+ def free_symbols(self):
206
+ return {i for j in self._array for i in j.free_symbols}
env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/__init__.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""
2
+ Array expressions are expressions representing N-dimensional arrays, without
3
+ evaluating them. These expressions represent in a certain way abstract syntax
4
+ trees of operations on N-dimensional arrays.
5
+
6
+ Every N-dimensional array operator has a corresponding array expression object.
7
+
8
+ Table of correspondences:
9
+
10
+ =============================== =============================
11
+ Array operator Array expression operator
12
+ =============================== =============================
13
+ tensorproduct ArrayTensorProduct
14
+ tensorcontraction ArrayContraction
15
+ tensordiagonal ArrayDiagonal
16
+ permutedims PermuteDims
17
+ =============================== =============================
18
+
19
+ Examples
20
+ ========
21
+
22
+ ``ArraySymbol`` objects are the N-dimensional equivalent of ``MatrixSymbol``
23
+ objects in the matrix module:
24
+
25
+ >>> from sympy.tensor.array.expressions import ArraySymbol
26
+ >>> from sympy.abc import i, j, k
27
+ >>> A = ArraySymbol("A", (3, 2, 4))
28
+ >>> A.shape
29
+ (3, 2, 4)
30
+ >>> A[i, j, k]
31
+ A[i, j, k]
32
+ >>> A.as_explicit()
33
+ [[[A[0, 0, 0], A[0, 0, 1], A[0, 0, 2], A[0, 0, 3]],
34
+ [A[0, 1, 0], A[0, 1, 1], A[0, 1, 2], A[0, 1, 3]]],
35
+ [[A[1, 0, 0], A[1, 0, 1], A[1, 0, 2], A[1, 0, 3]],
36
+ [A[1, 1, 0], A[1, 1, 1], A[1, 1, 2], A[1, 1, 3]]],
37
+ [[A[2, 0, 0], A[2, 0, 1], A[2, 0, 2], A[2, 0, 3]],
38
+ [A[2, 1, 0], A[2, 1, 1], A[2, 1, 2], A[2, 1, 3]]]]
39
+
40
+ Component-explicit arrays can be added inside array expressions:
41
+
42
+ >>> from sympy import Array
43
+ >>> from sympy import tensorproduct
44
+ >>> from sympy.tensor.array.expressions import ArrayTensorProduct
45
+ >>> a = Array([1, 2, 3])
46
+ >>> b = Array([i, j, k])
47
+ >>> expr = ArrayTensorProduct(a, b, b)
48
+ >>> expr
49
+ ArrayTensorProduct([1, 2, 3], [i, j, k], [i, j, k])
50
+ >>> expr.as_explicit() == tensorproduct(a, b, b)
51
+ True
52
+
53
+ Constructing array expressions from index-explicit forms
54
+ --------------------------------------------------------
55
+
56
+ Array expressions are index-implicit. This means they do not use any indices to
57
+ represent array operations. The function ``convert_indexed_to_array( ... )``
58
+ may be used to convert index-explicit expressions to array expressions.
59
+ It takes as input two parameters: the index-explicit expression and the order
60
+ of the indices:
61
+
62
+ >>> from sympy.tensor.array.expressions import convert_indexed_to_array
63
+ >>> from sympy import Sum
64
+ >>> A = ArraySymbol("A", (3, 3))
65
+ >>> B = ArraySymbol("B", (3, 3))
66
+ >>> convert_indexed_to_array(A[i, j], [i, j])
67
+ A
68
+ >>> convert_indexed_to_array(A[i, j], [j, i])
69
+ PermuteDims(A, (0 1))
70
+ >>> convert_indexed_to_array(A[i, j] + B[j, i], [i, j])
71
+ ArrayAdd(A, PermuteDims(B, (0 1)))
72
+ >>> convert_indexed_to_array(Sum(A[i, j]*B[j, k], (j, 0, 2)), [i, k])
73
+ ArrayContraction(ArrayTensorProduct(A, B), (1, 2))
74
+
75
+ The diagonal of a matrix in the array expression form:
76
+
77
+ >>> convert_indexed_to_array(A[i, i], [i])
78
+ ArrayDiagonal(A, (0, 1))
79
+
80
+ The trace of a matrix in the array expression form:
81
+
82
+ >>> convert_indexed_to_array(Sum(A[i, i], (i, 0, 2)), [i])
83
+ ArrayContraction(A, (0, 1))
84
+
85
+ Compatibility with matrices
86
+ ---------------------------
87
+
88
+ Array expressions can be mixed with objects from the matrix module:
89
+
90
+ >>> from sympy import MatrixSymbol
91
+ >>> from sympy.tensor.array.expressions import ArrayContraction
92
+ >>> M = MatrixSymbol("M", 3, 3)
93
+ >>> N = MatrixSymbol("N", 3, 3)
94
+
95
+ Express the matrix product in the array expression form:
96
+
97
+ >>> from sympy.tensor.array.expressions import convert_matrix_to_array
98
+ >>> expr = convert_matrix_to_array(M*N)
99
+ >>> expr
100
+ ArrayContraction(ArrayTensorProduct(M, N), (1, 2))
101
+
102
+ The expression can be converted back to matrix form:
103
+
104
+ >>> from sympy.tensor.array.expressions import convert_array_to_matrix
105
+ >>> convert_array_to_matrix(expr)
106
+ M*N
107
+
108
+ Add a second contraction on the remaining axes in order to get the trace of `M \cdot N`:
109
+
110
+ >>> expr_tr = ArrayContraction(expr, (0, 1))
111
+ >>> expr_tr
112
+ ArrayContraction(ArrayContraction(ArrayTensorProduct(M, N), (1, 2)), (0, 1))
113
+
114
+ Flatten the expression by calling ``.doit()`` and remove the nested array contraction operations:
115
+
116
+ >>> expr_tr.doit()
117
+ ArrayContraction(ArrayTensorProduct(M, N), (0, 3), (1, 2))
118
+
119
+ Get the explicit form of the array expression:
120
+
121
+ >>> expr.as_explicit()
122
+ [[M[0, 0]*N[0, 0] + M[0, 1]*N[1, 0] + M[0, 2]*N[2, 0], M[0, 0]*N[0, 1] + M[0, 1]*N[1, 1] + M[0, 2]*N[2, 1], M[0, 0]*N[0, 2] + M[0, 1]*N[1, 2] + M[0, 2]*N[2, 2]],
123
+ [M[1, 0]*N[0, 0] + M[1, 1]*N[1, 0] + M[1, 2]*N[2, 0], M[1, 0]*N[0, 1] + M[1, 1]*N[1, 1] + M[1, 2]*N[2, 1], M[1, 0]*N[0, 2] + M[1, 1]*N[1, 2] + M[1, 2]*N[2, 2]],
124
+ [M[2, 0]*N[0, 0] + M[2, 1]*N[1, 0] + M[2, 2]*N[2, 0], M[2, 0]*N[0, 1] + M[2, 1]*N[1, 1] + M[2, 2]*N[2, 1], M[2, 0]*N[0, 2] + M[2, 1]*N[1, 2] + M[2, 2]*N[2, 2]]]
125
+
126
+ Express the trace of a matrix:
127
+
128
+ >>> from sympy import Trace
129
+ >>> convert_matrix_to_array(Trace(M))
130
+ ArrayContraction(M, (0, 1))
131
+ >>> convert_matrix_to_array(Trace(M*N))
132
+ ArrayContraction(ArrayTensorProduct(M, N), (0, 3), (1, 2))
133
+
134
+ Express the transposition of a matrix (will be expressed as a permutation of the axes:
135
+
136
+ >>> convert_matrix_to_array(M.T)
137
+ PermuteDims(M, (0 1))
138
+
139
+ Compute the derivative array expressions:
140
+
141
+ >>> from sympy.tensor.array.expressions import array_derive
142
+ >>> d = array_derive(M, M)
143
+ >>> d
144
+ PermuteDims(ArrayTensorProduct(I, I), (3)(1 2))
145
+
146
+ Verify that the derivative corresponds to the form computed with explicit matrices:
147
+
148
+ >>> d.as_explicit()
149
+ [[[[1, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 1, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 1], [0, 0, 0], [0, 0, 0]]], [[[0, 0, 0], [1, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 1, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 1], [0, 0, 0]]], [[[0, 0, 0], [0, 0, 0], [1, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 1, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 1]]]]
150
+ >>> Me = M.as_explicit()
151
+ >>> Me.diff(Me)
152
+ [[[[1, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 1, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 1], [0, 0, 0], [0, 0, 0]]], [[[0, 0, 0], [1, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 1, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 1], [0, 0, 0]]], [[[0, 0, 0], [0, 0, 0], [1, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 1, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 1]]]]
153
+
154
+ """
155
+
156
+ __all__ = [
157
+ "ArraySymbol", "ArrayElement", "ZeroArray", "OneArray",
158
+ "ArrayTensorProduct",
159
+ "ArrayContraction",
160
+ "ArrayDiagonal",
161
+ "PermuteDims",
162
+ "ArrayAdd",
163
+ "ArrayElementwiseApplyFunc",
164
+ "Reshape",
165
+ "convert_array_to_matrix",
166
+ "convert_matrix_to_array",
167
+ "convert_array_to_indexed",
168
+ "convert_indexed_to_array",
169
+ "array_derive",
170
+ ]
171
+
172
+ from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct, ArrayAdd, PermuteDims, ArrayDiagonal, \
173
+ ArrayContraction, Reshape, ArraySymbol, ArrayElement, ZeroArray, OneArray, ArrayElementwiseApplyFunc
174
+ from sympy.tensor.array.expressions.arrayexpr_derivatives import array_derive
175
+ from sympy.tensor.array.expressions.from_array_to_indexed import convert_array_to_indexed
176
+ from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix
177
+ from sympy.tensor.array.expressions.from_indexed_to_array import convert_indexed_to_array
178
+ from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array
env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/arrayexpr_derivatives.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import operator
2
+ from functools import reduce, singledispatch
3
+
4
+ from sympy.core.expr import Expr
5
+ from sympy.core.singleton import S
6
+ from sympy.matrices.expressions.hadamard import HadamardProduct
7
+ from sympy.matrices.expressions.inverse import Inverse
8
+ from sympy.matrices.expressions.matexpr import (MatrixExpr, MatrixSymbol)
9
+ from sympy.matrices.expressions.special import Identity, OneMatrix
10
+ from sympy.matrices.expressions.transpose import Transpose
11
+ from sympy.combinatorics.permutations import _af_invert
12
+ from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction
13
+ from sympy.tensor.array.expressions.array_expressions import (
14
+ _ArrayExpr, ZeroArray, ArraySymbol, ArrayTensorProduct, ArrayAdd,
15
+ PermuteDims, ArrayDiagonal, ArrayElementwiseApplyFunc, get_rank,
16
+ get_shape, ArrayContraction, _array_tensor_product, _array_contraction,
17
+ _array_diagonal, _array_add, _permute_dims, Reshape)
18
+ from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array
19
+
20
+
21
+ @singledispatch
22
+ def array_derive(expr, x):
23
+ """
24
+ Derivatives (gradients) for array expressions.
25
+ """
26
+ raise NotImplementedError(f"not implemented for type {type(expr)}")
27
+
28
+
29
+ @array_derive.register(Expr)
30
+ def _(expr: Expr, x: _ArrayExpr):
31
+ return ZeroArray(*x.shape)
32
+
33
+
34
+ @array_derive.register(ArrayTensorProduct)
35
+ def _(expr: ArrayTensorProduct, x: Expr):
36
+ args = expr.args
37
+ addend_list = []
38
+ for i, arg in enumerate(expr.args):
39
+ darg = array_derive(arg, x)
40
+ if darg == 0:
41
+ continue
42
+ args_prev = args[:i]
43
+ args_succ = args[i+1:]
44
+ shape_prev = reduce(operator.add, map(get_shape, args_prev), ())
45
+ shape_succ = reduce(operator.add, map(get_shape, args_succ), ())
46
+ addend = _array_tensor_product(*args_prev, darg, *args_succ)
47
+ tot1 = len(get_shape(x))
48
+ tot2 = tot1 + len(shape_prev)
49
+ tot3 = tot2 + len(get_shape(arg))
50
+ tot4 = tot3 + len(shape_succ)
51
+ perm = list(range(tot1, tot2)) + \
52
+ list(range(tot1)) + list(range(tot2, tot3)) + \
53
+ list(range(tot3, tot4))
54
+ addend = _permute_dims(addend, _af_invert(perm))
55
+ addend_list.append(addend)
56
+ if len(addend_list) == 1:
57
+ return addend_list[0]
58
+ elif len(addend_list) == 0:
59
+ return S.Zero
60
+ else:
61
+ return _array_add(*addend_list)
62
+
63
+
64
+ @array_derive.register(ArraySymbol)
65
+ def _(expr: ArraySymbol, x: _ArrayExpr):
66
+ if expr == x:
67
+ return _permute_dims(
68
+ ArrayTensorProduct.fromiter(Identity(i) for i in expr.shape),
69
+ [2*i for i in range(len(expr.shape))] + [2*i+1 for i in range(len(expr.shape))]
70
+ )
71
+ return ZeroArray(*(x.shape + expr.shape))
72
+
73
+
74
+ @array_derive.register(MatrixSymbol)
75
+ def _(expr: MatrixSymbol, x: _ArrayExpr):
76
+ m, n = expr.shape
77
+ if expr == x:
78
+ return _permute_dims(
79
+ _array_tensor_product(Identity(m), Identity(n)),
80
+ [0, 2, 1, 3]
81
+ )
82
+ return ZeroArray(*(x.shape + expr.shape))
83
+
84
+
85
+ @array_derive.register(Identity)
86
+ def _(expr: Identity, x: _ArrayExpr):
87
+ return ZeroArray(*(x.shape + expr.shape))
88
+
89
+
90
+ @array_derive.register(OneMatrix)
91
+ def _(expr: OneMatrix, x: _ArrayExpr):
92
+ return ZeroArray(*(x.shape + expr.shape))
93
+
94
+
95
+ @array_derive.register(Transpose)
96
+ def _(expr: Transpose, x: Expr):
97
+ # D(A.T, A) ==> (m,n,i,j) ==> D(A_ji, A_mn) = d_mj d_ni
98
+ # D(B.T, A) ==> (m,n,i,j) ==> D(B_ji, A_mn)
99
+ fd = array_derive(expr.arg, x)
100
+ return _permute_dims(fd, [0, 1, 3, 2])
101
+
102
+
103
+ @array_derive.register(Inverse)
104
+ def _(expr: Inverse, x: Expr):
105
+ mat = expr.I
106
+ dexpr = array_derive(mat, x)
107
+ tp = _array_tensor_product(-expr, dexpr, expr)
108
+ mp = _array_contraction(tp, (1, 4), (5, 6))
109
+ pp = _permute_dims(mp, [1, 2, 0, 3])
110
+ return pp
111
+
112
+
113
+ @array_derive.register(ElementwiseApplyFunction)
114
+ def _(expr: ElementwiseApplyFunction, x: Expr):
115
+ assert get_rank(expr) == 2
116
+ assert get_rank(x) == 2
117
+ fdiff = expr._get_function_fdiff()
118
+ dexpr = array_derive(expr.expr, x)
119
+ tp = _array_tensor_product(
120
+ ElementwiseApplyFunction(fdiff, expr.expr),
121
+ dexpr
122
+ )
123
+ td = _array_diagonal(
124
+ tp, (0, 4), (1, 5)
125
+ )
126
+ return td
127
+
128
+
129
+ @array_derive.register(ArrayElementwiseApplyFunc)
130
+ def _(expr: ArrayElementwiseApplyFunc, x: Expr):
131
+ fdiff = expr._get_function_fdiff()
132
+ subexpr = expr.expr
133
+ dsubexpr = array_derive(subexpr, x)
134
+ tp = _array_tensor_product(
135
+ dsubexpr,
136
+ ArrayElementwiseApplyFunc(fdiff, subexpr)
137
+ )
138
+ b = get_rank(x)
139
+ c = get_rank(expr)
140
+ diag_indices = [(b + i, b + c + i) for i in range(c)]
141
+ return _array_diagonal(tp, *diag_indices)
142
+
143
+
144
+ @array_derive.register(MatrixExpr)
145
+ def _(expr: MatrixExpr, x: Expr):
146
+ cg = convert_matrix_to_array(expr)
147
+ return array_derive(cg, x)
148
+
149
+
150
+ @array_derive.register(HadamardProduct)
151
+ def _(expr: HadamardProduct, x: Expr):
152
+ raise NotImplementedError()
153
+
154
+
155
+ @array_derive.register(ArrayContraction)
156
+ def _(expr: ArrayContraction, x: Expr):
157
+ fd = array_derive(expr.expr, x)
158
+ rank_x = len(get_shape(x))
159
+ contraction_indices = expr.contraction_indices
160
+ new_contraction_indices = [tuple(j + rank_x for j in i) for i in contraction_indices]
161
+ return _array_contraction(fd, *new_contraction_indices)
162
+
163
+
164
+ @array_derive.register(ArrayDiagonal)
165
+ def _(expr: ArrayDiagonal, x: Expr):
166
+ dsubexpr = array_derive(expr.expr, x)
167
+ rank_x = len(get_shape(x))
168
+ diag_indices = [[j + rank_x for j in i] for i in expr.diagonal_indices]
169
+ return _array_diagonal(dsubexpr, *diag_indices)
170
+
171
+
172
+ @array_derive.register(ArrayAdd)
173
+ def _(expr: ArrayAdd, x: Expr):
174
+ return _array_add(*[array_derive(arg, x) for arg in expr.args])
175
+
176
+
177
+ @array_derive.register(PermuteDims)
178
+ def _(expr: PermuteDims, x: Expr):
179
+ de = array_derive(expr.expr, x)
180
+ perm = [0, 1] + [i + 2 for i in expr.permutation.array_form]
181
+ return _permute_dims(de, perm)
182
+
183
+
184
+ @array_derive.register(Reshape)
185
+ def _(expr: Reshape, x: Expr):
186
+ de = array_derive(expr.expr, x)
187
+ return Reshape(de, get_shape(x) + expr.shape)
188
+
189
+
190
+ def matrix_derive(expr, x):
191
+ from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix
192
+ ce = convert_matrix_to_array(expr)
193
+ dce = array_derive(ce, x)
194
+ return convert_array_to_matrix(dce).doit()