applied-ai-018 commited on
Commit
3297406
·
verified ·
1 Parent(s): b99c033

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. llmeval-env/lib/python3.10/site-packages/sympy/polys/agca/tests/__pycache__/test_homomorphisms.cpython-310.pyc +0 -0
  2. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/__init__.py +15 -0
  3. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/__init__.cpython-310.pyc +0 -0
  4. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/_typing.cpython-310.pyc +0 -0
  5. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/ddm.cpython-310.pyc +0 -0
  6. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/dense.cpython-310.pyc +0 -0
  7. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/domainmatrix.cpython-310.pyc +0 -0
  8. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/domainscalar.cpython-310.pyc +0 -0
  9. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/eigen.cpython-310.pyc +0 -0
  10. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/exceptions.cpython-310.pyc +0 -0
  11. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/linsolve.cpython-310.pyc +0 -0
  12. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/lll.cpython-310.pyc +0 -0
  13. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/normalforms.cpython-310.pyc +0 -0
  14. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/sdm.cpython-310.pyc +0 -0
  15. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/_typing.py +12 -0
  16. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/ddm.py +496 -0
  17. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/dense.py +348 -0
  18. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/domainmatrix.py +1791 -0
  19. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/domainscalar.py +116 -0
  20. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/eigen.py +90 -0
  21. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/exceptions.py +67 -0
  22. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/linsolve.py +230 -0
  23. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/lll.py +94 -0
  24. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/normalforms.py +406 -0
  25. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/sdm.py +1241 -0
  26. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/__init__.py +0 -0
  27. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  28. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/__pycache__/test_ddm.cpython-310.pyc +0 -0
  29. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/__pycache__/test_dense.cpython-310.pyc +0 -0
  30. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/__pycache__/test_domainmatrix.cpython-310.pyc +0 -0
  31. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/__pycache__/test_domainscalar.cpython-310.pyc +0 -0
  32. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/__pycache__/test_eigen.cpython-310.pyc +0 -0
  33. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/__pycache__/test_linsolve.cpython-310.pyc +0 -0
  34. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/__pycache__/test_lll.cpython-310.pyc +0 -0
  35. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/__pycache__/test_normalforms.cpython-310.pyc +0 -0
  36. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/__pycache__/test_sdm.cpython-310.pyc +0 -0
  37. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_ddm.py +557 -0
  38. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_dense.py +345 -0
  39. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_domainmatrix.py +910 -0
  40. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_domainscalar.py +147 -0
  41. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_eigen.py +90 -0
  42. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_linsolve.py +111 -0
  43. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_lll.py +145 -0
  44. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_normalforms.py +75 -0
  45. llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_sdm.py +444 -0
  46. llmeval-env/lib/python3.10/site-packages/sympy/polys/numberfields/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  47. llmeval-env/lib/python3.10/site-packages/sympy/polys/numberfields/tests/__pycache__/test_basis.cpython-310.pyc +0 -0
  48. llmeval-env/lib/python3.10/site-packages/sympy/polys/numberfields/tests/__pycache__/test_galoisgroups.cpython-310.pyc +0 -0
  49. llmeval-env/lib/python3.10/site-packages/sympy/polys/numberfields/tests/__pycache__/test_minpoly.cpython-310.pyc +0 -0
  50. llmeval-env/lib/python3.10/site-packages/sympy/polys/numberfields/tests/__pycache__/test_modules.cpython-310.pyc +0 -0
llmeval-env/lib/python3.10/site-packages/sympy/polys/agca/tests/__pycache__/test_homomorphisms.cpython-310.pyc ADDED
Binary file (5.63 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+
3
+ sympy.polys.matrices package.
4
+
5
+ The main export from this package is the DomainMatrix class which is a
6
+ lower-level implementation of matrices based on the polys Domains. This
7
+ implementation is typically a lot faster than SymPy's standard Matrix class
8
+ but is a work in progress and is still experimental.
9
+
10
+ """
11
+ from .domainmatrix import DomainMatrix, DM
12
+
13
+ __all__ = [
14
+ 'DomainMatrix', 'DM',
15
+ ]
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (612 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/_typing.cpython-310.pyc ADDED
Binary file (1.11 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/ddm.cpython-310.pyc ADDED
Binary file (17.8 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/dense.cpython-310.pyc ADDED
Binary file (8.92 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/domainmatrix.cpython-310.pyc ADDED
Binary file (51.8 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/domainscalar.cpython-310.pyc ADDED
Binary file (4.38 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/eigen.cpython-310.pyc ADDED
Binary file (3.79 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/exceptions.cpython-310.pyc ADDED
Binary file (2.12 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/linsolve.cpython-310.pyc ADDED
Binary file (5.46 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/lll.cpython-310.pyc ADDED
Binary file (4.89 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/normalforms.cpython-310.pyc ADDED
Binary file (11 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/sdm.cpython-310.pyc ADDED
Binary file (34.2 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/_typing.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import TypeVar, Protocol
2
+
3
+
4
+ T = TypeVar('T')
5
+
6
+
7
+ class RingElement(Protocol):
8
+ def __add__(self: T, other: T, /) -> T: ...
9
+ def __sub__(self: T, other: T, /) -> T: ...
10
+ def __mul__(self: T, other: T, /) -> T: ...
11
+ def __pow__(self: T, other: int, /) -> T: ...
12
+ def __neg__(self: T, /) -> T: ...
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/ddm.py ADDED
@@ -0,0 +1,496 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+
3
+ Module for the DDM class.
4
+
5
+ The DDM class is an internal representation used by DomainMatrix. The letters
6
+ DDM stand for Dense Domain Matrix. A DDM instance represents a matrix using
7
+ elements from a polynomial Domain (e.g. ZZ, QQ, ...) in a dense-matrix
8
+ representation.
9
+
10
+ Basic usage:
11
+
12
+ >>> from sympy import ZZ, QQ
13
+ >>> from sympy.polys.matrices.ddm import DDM
14
+ >>> A = DDM([[ZZ(0), ZZ(1)], [ZZ(-1), ZZ(0)]], (2, 2), ZZ)
15
+ >>> A.shape
16
+ (2, 2)
17
+ >>> A
18
+ [[0, 1], [-1, 0]]
19
+ >>> type(A)
20
+ <class 'sympy.polys.matrices.ddm.DDM'>
21
+ >>> A @ A
22
+ [[-1, 0], [0, -1]]
23
+
24
+ The ddm_* functions are designed to operate on DDM as well as on an ordinary
25
+ list of lists:
26
+
27
+ >>> from sympy.polys.matrices.dense import ddm_idet
28
+ >>> ddm_idet(A, QQ)
29
+ 1
30
+ >>> ddm_idet([[0, 1], [-1, 0]], QQ)
31
+ 1
32
+ >>> A
33
+ [[-1, 0], [0, -1]]
34
+
35
+ Note that ddm_idet modifies the input matrix in-place. It is recommended to
36
+ use the DDM.det method as a friendlier interface to this instead which takes
37
+ care of copying the matrix:
38
+
39
+ >>> B = DDM([[ZZ(0), ZZ(1)], [ZZ(-1), ZZ(0)]], (2, 2), ZZ)
40
+ >>> B.det()
41
+ 1
42
+
43
+ Normally DDM would not be used directly and is just part of the internal
44
+ representation of DomainMatrix which adds further functionality including e.g.
45
+ unifying domains.
46
+
47
+ The dense format used by DDM is a list of lists of elements e.g. the 2x2
48
+ identity matrix is like [[1, 0], [0, 1]]. The DDM class itself is a subclass
49
+ of list and its list items are plain lists. Elements are accessed as e.g.
50
+ ddm[i][j] where ddm[i] gives the ith row and ddm[i][j] gets the element in the
51
+ jth column of that row. Subclassing list makes e.g. iteration and indexing
52
+ very efficient. We do not override __getitem__ because it would lose that
53
+ benefit.
54
+
55
+ The core routines are implemented by the ddm_* functions defined in dense.py.
56
+ Those functions are intended to be able to operate on a raw list-of-lists
57
+ representation of matrices with most functions operating in-place. The DDM
58
+ class takes care of copying etc and also stores a Domain object associated
59
+ with its elements. This makes it possible to implement things like A + B with
60
+ domain checking and also shape checking so that the list of lists
61
+ representation is friendlier.
62
+
63
+ """
64
+ from itertools import chain
65
+
66
+ from .exceptions import DMBadInputError, DMShapeError, DMDomainError
67
+
68
+ from .dense import (
69
+ ddm_transpose,
70
+ ddm_iadd,
71
+ ddm_isub,
72
+ ddm_ineg,
73
+ ddm_imul,
74
+ ddm_irmul,
75
+ ddm_imatmul,
76
+ ddm_irref,
77
+ ddm_idet,
78
+ ddm_iinv,
79
+ ddm_ilu_split,
80
+ ddm_ilu_solve,
81
+ ddm_berk,
82
+ )
83
+
84
+ from sympy.polys.domains import QQ
85
+ from .lll import ddm_lll, ddm_lll_transform
86
+
87
+
88
+ class DDM(list):
89
+ """Dense matrix based on polys domain elements
90
+
91
+ This is a list subclass and is a wrapper for a list of lists that supports
92
+ basic matrix arithmetic +, -, *, **.
93
+ """
94
+
95
+ fmt = 'dense'
96
+
97
+ def __init__(self, rowslist, shape, domain):
98
+ super().__init__(rowslist)
99
+ self.shape = self.rows, self.cols = m, n = shape
100
+ self.domain = domain
101
+
102
+ if not (len(self) == m and all(len(row) == n for row in self)):
103
+ raise DMBadInputError("Inconsistent row-list/shape")
104
+
105
+ def getitem(self, i, j):
106
+ return self[i][j]
107
+
108
+ def setitem(self, i, j, value):
109
+ self[i][j] = value
110
+
111
+ def extract_slice(self, slice1, slice2):
112
+ ddm = [row[slice2] for row in self[slice1]]
113
+ rows = len(ddm)
114
+ cols = len(ddm[0]) if ddm else len(range(self.shape[1])[slice2])
115
+ return DDM(ddm, (rows, cols), self.domain)
116
+
117
+ def extract(self, rows, cols):
118
+ ddm = []
119
+ for i in rows:
120
+ rowi = self[i]
121
+ ddm.append([rowi[j] for j in cols])
122
+ return DDM(ddm, (len(rows), len(cols)), self.domain)
123
+
124
+ def to_list(self):
125
+ return list(self)
126
+
127
+ def to_list_flat(self):
128
+ flat = []
129
+ for row in self:
130
+ flat.extend(row)
131
+ return flat
132
+
133
+ def flatiter(self):
134
+ return chain.from_iterable(self)
135
+
136
+ def flat(self):
137
+ items = []
138
+ for row in self:
139
+ items.extend(row)
140
+ return items
141
+
142
+ def to_dok(self):
143
+ return {(i, j): e for i, row in enumerate(self) for j, e in enumerate(row)}
144
+
145
+ def to_ddm(self):
146
+ return self
147
+
148
+ def to_sdm(self):
149
+ return SDM.from_list(self, self.shape, self.domain)
150
+
151
+ def convert_to(self, K):
152
+ Kold = self.domain
153
+ if K == Kold:
154
+ return self.copy()
155
+ rows = ([K.convert_from(e, Kold) for e in row] for row in self)
156
+ return DDM(rows, self.shape, K)
157
+
158
+ def __str__(self):
159
+ rowsstr = ['[%s]' % ', '.join(map(str, row)) for row in self]
160
+ return '[%s]' % ', '.join(rowsstr)
161
+
162
+ def __repr__(self):
163
+ cls = type(self).__name__
164
+ rows = list.__repr__(self)
165
+ return '%s(%s, %s, %s)' % (cls, rows, self.shape, self.domain)
166
+
167
+ def __eq__(self, other):
168
+ if not isinstance(other, DDM):
169
+ return False
170
+ return (super().__eq__(other) and self.domain == other.domain)
171
+
172
+ def __ne__(self, other):
173
+ return not self.__eq__(other)
174
+
175
+ @classmethod
176
+ def zeros(cls, shape, domain):
177
+ z = domain.zero
178
+ m, n = shape
179
+ rowslist = ([z] * n for _ in range(m))
180
+ return DDM(rowslist, shape, domain)
181
+
182
+ @classmethod
183
+ def ones(cls, shape, domain):
184
+ one = domain.one
185
+ m, n = shape
186
+ rowlist = ([one] * n for _ in range(m))
187
+ return DDM(rowlist, shape, domain)
188
+
189
+ @classmethod
190
+ def eye(cls, size, domain):
191
+ one = domain.one
192
+ ddm = cls.zeros((size, size), domain)
193
+ for i in range(size):
194
+ ddm[i][i] = one
195
+ return ddm
196
+
197
+ def copy(self):
198
+ copyrows = (row[:] for row in self)
199
+ return DDM(copyrows, self.shape, self.domain)
200
+
201
+ def transpose(self):
202
+ rows, cols = self.shape
203
+ if rows:
204
+ ddmT = ddm_transpose(self)
205
+ else:
206
+ ddmT = [[]] * cols
207
+ return DDM(ddmT, (cols, rows), self.domain)
208
+
209
+ def __add__(a, b):
210
+ if not isinstance(b, DDM):
211
+ return NotImplemented
212
+ return a.add(b)
213
+
214
+ def __sub__(a, b):
215
+ if not isinstance(b, DDM):
216
+ return NotImplemented
217
+ return a.sub(b)
218
+
219
+ def __neg__(a):
220
+ return a.neg()
221
+
222
+ def __mul__(a, b):
223
+ if b in a.domain:
224
+ return a.mul(b)
225
+ else:
226
+ return NotImplemented
227
+
228
+ def __rmul__(a, b):
229
+ if b in a.domain:
230
+ return a.mul(b)
231
+ else:
232
+ return NotImplemented
233
+
234
+ def __matmul__(a, b):
235
+ if isinstance(b, DDM):
236
+ return a.matmul(b)
237
+ else:
238
+ return NotImplemented
239
+
240
+ @classmethod
241
+ def _check(cls, a, op, b, ashape, bshape):
242
+ if a.domain != b.domain:
243
+ msg = "Domain mismatch: %s %s %s" % (a.domain, op, b.domain)
244
+ raise DMDomainError(msg)
245
+ if ashape != bshape:
246
+ msg = "Shape mismatch: %s %s %s" % (a.shape, op, b.shape)
247
+ raise DMShapeError(msg)
248
+
249
+ def add(a, b):
250
+ """a + b"""
251
+ a._check(a, '+', b, a.shape, b.shape)
252
+ c = a.copy()
253
+ ddm_iadd(c, b)
254
+ return c
255
+
256
+ def sub(a, b):
257
+ """a - b"""
258
+ a._check(a, '-', b, a.shape, b.shape)
259
+ c = a.copy()
260
+ ddm_isub(c, b)
261
+ return c
262
+
263
+ def neg(a):
264
+ """-a"""
265
+ b = a.copy()
266
+ ddm_ineg(b)
267
+ return b
268
+
269
+ def mul(a, b):
270
+ c = a.copy()
271
+ ddm_imul(c, b)
272
+ return c
273
+
274
+ def rmul(a, b):
275
+ c = a.copy()
276
+ ddm_irmul(c, b)
277
+ return c
278
+
279
+ def matmul(a, b):
280
+ """a @ b (matrix product)"""
281
+ m, o = a.shape
282
+ o2, n = b.shape
283
+ a._check(a, '*', b, o, o2)
284
+ c = a.zeros((m, n), a.domain)
285
+ ddm_imatmul(c, a, b)
286
+ return c
287
+
288
+ def mul_elementwise(a, b):
289
+ assert a.shape == b.shape
290
+ assert a.domain == b.domain
291
+ c = [[aij * bij for aij, bij in zip(ai, bi)] for ai, bi in zip(a, b)]
292
+ return DDM(c, a.shape, a.domain)
293
+
294
+ def hstack(A, *B):
295
+ """Horizontally stacks :py:class:`~.DDM` matrices.
296
+
297
+ Examples
298
+ ========
299
+
300
+ >>> from sympy import ZZ
301
+ >>> from sympy.polys.matrices.sdm import DDM
302
+
303
+ >>> A = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
304
+ >>> B = DDM([[ZZ(5), ZZ(6)], [ZZ(7), ZZ(8)]], (2, 2), ZZ)
305
+ >>> A.hstack(B)
306
+ [[1, 2, 5, 6], [3, 4, 7, 8]]
307
+
308
+ >>> C = DDM([[ZZ(9), ZZ(10)], [ZZ(11), ZZ(12)]], (2, 2), ZZ)
309
+ >>> A.hstack(B, C)
310
+ [[1, 2, 5, 6, 9, 10], [3, 4, 7, 8, 11, 12]]
311
+ """
312
+ Anew = list(A.copy())
313
+ rows, cols = A.shape
314
+ domain = A.domain
315
+
316
+ for Bk in B:
317
+ Bkrows, Bkcols = Bk.shape
318
+ assert Bkrows == rows
319
+ assert Bk.domain == domain
320
+
321
+ cols += Bkcols
322
+
323
+ for i, Bki in enumerate(Bk):
324
+ Anew[i].extend(Bki)
325
+
326
+ return DDM(Anew, (rows, cols), A.domain)
327
+
328
+ def vstack(A, *B):
329
+ """Vertically stacks :py:class:`~.DDM` matrices.
330
+
331
+ Examples
332
+ ========
333
+
334
+ >>> from sympy import ZZ
335
+ >>> from sympy.polys.matrices.sdm import DDM
336
+
337
+ >>> A = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
338
+ >>> B = DDM([[ZZ(5), ZZ(6)], [ZZ(7), ZZ(8)]], (2, 2), ZZ)
339
+ >>> A.vstack(B)
340
+ [[1, 2], [3, 4], [5, 6], [7, 8]]
341
+
342
+ >>> C = DDM([[ZZ(9), ZZ(10)], [ZZ(11), ZZ(12)]], (2, 2), ZZ)
343
+ >>> A.vstack(B, C)
344
+ [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]]
345
+ """
346
+ Anew = list(A.copy())
347
+ rows, cols = A.shape
348
+ domain = A.domain
349
+
350
+ for Bk in B:
351
+ Bkrows, Bkcols = Bk.shape
352
+ assert Bkcols == cols
353
+ assert Bk.domain == domain
354
+
355
+ rows += Bkrows
356
+
357
+ Anew.extend(Bk.copy())
358
+
359
+ return DDM(Anew, (rows, cols), A.domain)
360
+
361
+ def applyfunc(self, func, domain):
362
+ elements = (list(map(func, row)) for row in self)
363
+ return DDM(elements, self.shape, domain)
364
+
365
+ def scc(a):
366
+ """Strongly connected components of a square matrix *a*.
367
+
368
+ Examples
369
+ ========
370
+
371
+ >>> from sympy import ZZ
372
+ >>> from sympy.polys.matrices.sdm import DDM
373
+ >>> A = DDM([[ZZ(1), ZZ(0)], [ZZ(0), ZZ(1)]], (2, 2), ZZ)
374
+ >>> A.scc()
375
+ [[0], [1]]
376
+
377
+ See also
378
+ ========
379
+
380
+ sympy.polys.matrices.domainmatrix.DomainMatrix.scc
381
+
382
+ """
383
+ return a.to_sdm().scc()
384
+
385
+ def rref(a):
386
+ """Reduced-row echelon form of a and list of pivots"""
387
+ b = a.copy()
388
+ K = a.domain
389
+ partial_pivot = K.is_RealField or K.is_ComplexField
390
+ pivots = ddm_irref(b, _partial_pivot=partial_pivot)
391
+ return b, pivots
392
+
393
+ def nullspace(a):
394
+ rref, pivots = a.rref()
395
+ rows, cols = a.shape
396
+ domain = a.domain
397
+
398
+ basis = []
399
+ nonpivots = []
400
+ for i in range(cols):
401
+ if i in pivots:
402
+ continue
403
+ nonpivots.append(i)
404
+ vec = [domain.one if i == j else domain.zero for j in range(cols)]
405
+ for ii, jj in enumerate(pivots):
406
+ vec[jj] -= rref[ii][i]
407
+ basis.append(vec)
408
+
409
+ return DDM(basis, (len(basis), cols), domain), nonpivots
410
+
411
+ def particular(a):
412
+ return a.to_sdm().particular().to_ddm()
413
+
414
+ def det(a):
415
+ """Determinant of a"""
416
+ m, n = a.shape
417
+ if m != n:
418
+ raise DMShapeError("Determinant of non-square matrix")
419
+ b = a.copy()
420
+ K = b.domain
421
+ deta = ddm_idet(b, K)
422
+ return deta
423
+
424
+ def inv(a):
425
+ """Inverse of a"""
426
+ m, n = a.shape
427
+ if m != n:
428
+ raise DMShapeError("Determinant of non-square matrix")
429
+ ainv = a.copy()
430
+ K = a.domain
431
+ ddm_iinv(ainv, a, K)
432
+ return ainv
433
+
434
+ def lu(a):
435
+ """L, U decomposition of a"""
436
+ m, n = a.shape
437
+ K = a.domain
438
+
439
+ U = a.copy()
440
+ L = a.eye(m, K)
441
+ swaps = ddm_ilu_split(L, U, K)
442
+
443
+ return L, U, swaps
444
+
445
+ def lu_solve(a, b):
446
+ """x where a*x = b"""
447
+ m, n = a.shape
448
+ m2, o = b.shape
449
+ a._check(a, 'lu_solve', b, m, m2)
450
+
451
+ L, U, swaps = a.lu()
452
+ x = a.zeros((n, o), a.domain)
453
+ ddm_ilu_solve(x, L, U, swaps, b)
454
+ return x
455
+
456
+ def charpoly(a):
457
+ """Coefficients of characteristic polynomial of a"""
458
+ K = a.domain
459
+ m, n = a.shape
460
+ if m != n:
461
+ raise DMShapeError("Charpoly of non-square matrix")
462
+ vec = ddm_berk(a, K)
463
+ coeffs = [vec[i][0] for i in range(n+1)]
464
+ return coeffs
465
+
466
+ def is_zero_matrix(self):
467
+ """
468
+ Says whether this matrix has all zero entries.
469
+ """
470
+ zero = self.domain.zero
471
+ return all(Mij == zero for Mij in self.flatiter())
472
+
473
+ def is_upper(self):
474
+ """
475
+ Says whether this matrix is upper-triangular. True can be returned
476
+ even if the matrix is not square.
477
+ """
478
+ zero = self.domain.zero
479
+ return all(Mij == zero for i, Mi in enumerate(self) for Mij in Mi[:i])
480
+
481
+ def is_lower(self):
482
+ """
483
+ Says whether this matrix is lower-triangular. True can be returned
484
+ even if the matrix is not square.
485
+ """
486
+ zero = self.domain.zero
487
+ return all(Mij == zero for i, Mi in enumerate(self) for Mij in Mi[i+1:])
488
+
489
+ def lll(A, delta=QQ(3, 4)):
490
+ return ddm_lll(A, delta=delta)
491
+
492
+ def lll_transform(A, delta=QQ(3, 4)):
493
+ return ddm_lll_transform(A, delta=delta)
494
+
495
+
496
+ from .sdm import SDM
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/dense.py ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+
3
+ Module for the ddm_* routines for operating on a matrix in list of lists
4
+ matrix representation.
5
+
6
+ These routines are used internally by the DDM class which also provides a
7
+ friendlier interface for them. The idea here is to implement core matrix
8
+ routines in a way that can be applied to any simple list representation
9
+ without the need to use any particular matrix class. For example we can
10
+ compute the RREF of a matrix like:
11
+
12
+ >>> from sympy.polys.matrices.dense import ddm_irref
13
+ >>> M = [[1, 2, 3], [4, 5, 6]]
14
+ >>> pivots = ddm_irref(M)
15
+ >>> M
16
+ [[1.0, 0.0, -1.0], [0, 1.0, 2.0]]
17
+
18
+ These are lower-level routines that work mostly in place.The routines at this
19
+ level should not need to know what the domain of the elements is but should
20
+ ideally document what operations they will use and what functions they need to
21
+ be provided with.
22
+
23
+ The next-level up is the DDM class which uses these routines but wraps them up
24
+ with an interface that handles copying etc and keeps track of the Domain of
25
+ the elements of the matrix:
26
+
27
+ >>> from sympy.polys.domains import QQ
28
+ >>> from sympy.polys.matrices.ddm import DDM
29
+ >>> M = DDM([[QQ(1), QQ(2), QQ(3)], [QQ(4), QQ(5), QQ(6)]], (2, 3), QQ)
30
+ >>> M
31
+ [[1, 2, 3], [4, 5, 6]]
32
+ >>> Mrref, pivots = M.rref()
33
+ >>> Mrref
34
+ [[1, 0, -1], [0, 1, 2]]
35
+
36
+ """
37
+ from __future__ import annotations
38
+ from operator import mul
39
+ from .exceptions import (
40
+ DMShapeError,
41
+ DMNonInvertibleMatrixError,
42
+ DMNonSquareMatrixError,
43
+ )
44
+ from typing import Sequence, TypeVar
45
+ from sympy.polys.matrices._typing import RingElement
46
+
47
+
48
+ T = TypeVar('T')
49
+ R = TypeVar('R', bound=RingElement)
50
+
51
+
52
+ def ddm_transpose(matrix: Sequence[Sequence[T]]) -> list[list[T]]:
53
+ """matrix transpose"""
54
+ return list(map(list, zip(*matrix)))
55
+
56
+
57
+ def ddm_iadd(a: list[list[R]], b: Sequence[Sequence[R]]) -> None:
58
+ """a += b"""
59
+ for ai, bi in zip(a, b):
60
+ for j, bij in enumerate(bi):
61
+ ai[j] += bij
62
+
63
+
64
+ def ddm_isub(a: list[list[R]], b: Sequence[Sequence[R]]) -> None:
65
+ """a -= b"""
66
+ for ai, bi in zip(a, b):
67
+ for j, bij in enumerate(bi):
68
+ ai[j] -= bij
69
+
70
+
71
+ def ddm_ineg(a: list[list[R]]) -> None:
72
+ """a <-- -a"""
73
+ for ai in a:
74
+ for j, aij in enumerate(ai):
75
+ ai[j] = -aij
76
+
77
+
78
+ def ddm_imul(a: list[list[R]], b: R) -> None:
79
+ for ai in a:
80
+ for j, aij in enumerate(ai):
81
+ ai[j] = aij * b
82
+
83
+
84
+ def ddm_irmul(a: list[list[R]], b: R) -> None:
85
+ for ai in a:
86
+ for j, aij in enumerate(ai):
87
+ ai[j] = b * aij
88
+
89
+
90
+ def ddm_imatmul(
91
+ a: list[list[R]], b: Sequence[Sequence[R]], c: Sequence[Sequence[R]]
92
+ ) -> None:
93
+ """a += b @ c"""
94
+ cT = list(zip(*c))
95
+
96
+ for bi, ai in zip(b, a):
97
+ for j, cTj in enumerate(cT):
98
+ ai[j] = sum(map(mul, bi, cTj), ai[j])
99
+
100
+
101
+ def ddm_irref(a, _partial_pivot=False):
102
+ """a <-- rref(a)"""
103
+ # a is (m x n)
104
+ m = len(a)
105
+ if not m:
106
+ return []
107
+ n = len(a[0])
108
+
109
+ i = 0
110
+ pivots = []
111
+
112
+ for j in range(n):
113
+ # Proper pivoting should be used for all domains for performance
114
+ # reasons but it is only strictly needed for RR and CC (and possibly
115
+ # other domains like RR(x)). This path is used by DDM.rref() if the
116
+ # domain is RR or CC. It uses partial (row) pivoting based on the
117
+ # absolute value of the pivot candidates.
118
+ if _partial_pivot:
119
+ ip = max(range(i, m), key=lambda ip: abs(a[ip][j]))
120
+ a[i], a[ip] = a[ip], a[i]
121
+
122
+ # pivot
123
+ aij = a[i][j]
124
+
125
+ # zero-pivot
126
+ if not aij:
127
+ for ip in range(i+1, m):
128
+ aij = a[ip][j]
129
+ # row-swap
130
+ if aij:
131
+ a[i], a[ip] = a[ip], a[i]
132
+ break
133
+ else:
134
+ # next column
135
+ continue
136
+
137
+ # normalise row
138
+ ai = a[i]
139
+ aijinv = aij**-1
140
+ for l in range(j, n):
141
+ ai[l] *= aijinv # ai[j] = one
142
+
143
+ # eliminate above and below to the right
144
+ for k, ak in enumerate(a):
145
+ if k == i or not ak[j]:
146
+ continue
147
+ akj = ak[j]
148
+ ak[j] -= akj # ak[j] = zero
149
+ for l in range(j+1, n):
150
+ ak[l] -= akj * ai[l]
151
+
152
+ # next row
153
+ pivots.append(j)
154
+ i += 1
155
+
156
+ # no more rows?
157
+ if i >= m:
158
+ break
159
+
160
+ return pivots
161
+
162
+
163
+ def ddm_idet(a, K):
164
+ """a <-- echelon(a); return det"""
165
+ # Bareiss algorithm
166
+ # https://www.math.usm.edu/perry/Research/Thesis_DRL.pdf
167
+
168
+ # a is (m x n)
169
+ m = len(a)
170
+ if not m:
171
+ return K.one
172
+ n = len(a[0])
173
+
174
+ exquo = K.exquo
175
+ # uf keeps track of the sign change from row swaps
176
+ uf = K.one
177
+
178
+ for k in range(n-1):
179
+ if not a[k][k]:
180
+ for i in range(k+1, n):
181
+ if a[i][k]:
182
+ a[k], a[i] = a[i], a[k]
183
+ uf = -uf
184
+ break
185
+ else:
186
+ return K.zero
187
+
188
+ akkm1 = a[k-1][k-1] if k else K.one
189
+
190
+ for i in range(k+1, n):
191
+ for j in range(k+1, n):
192
+ a[i][j] = exquo(a[i][j]*a[k][k] - a[i][k]*a[k][j], akkm1)
193
+
194
+ return uf * a[-1][-1]
195
+
196
+
197
+ def ddm_iinv(ainv, a, K):
198
+ if not K.is_Field:
199
+ raise ValueError('Not a field')
200
+
201
+ # a is (m x n)
202
+ m = len(a)
203
+ if not m:
204
+ return
205
+ n = len(a[0])
206
+ if m != n:
207
+ raise DMNonSquareMatrixError
208
+
209
+ eye = [[K.one if i==j else K.zero for j in range(n)] for i in range(n)]
210
+ Aaug = [row + eyerow for row, eyerow in zip(a, eye)]
211
+ pivots = ddm_irref(Aaug)
212
+ if pivots != list(range(n)):
213
+ raise DMNonInvertibleMatrixError('Matrix det == 0; not invertible.')
214
+ ainv[:] = [row[n:] for row in Aaug]
215
+
216
+
217
+ def ddm_ilu_split(L, U, K):
218
+ """L, U <-- LU(U)"""
219
+ m = len(U)
220
+ if not m:
221
+ return []
222
+ n = len(U[0])
223
+
224
+ swaps = ddm_ilu(U)
225
+
226
+ zeros = [K.zero] * min(m, n)
227
+ for i in range(1, m):
228
+ j = min(i, n)
229
+ L[i][:j] = U[i][:j]
230
+ U[i][:j] = zeros[:j]
231
+
232
+ return swaps
233
+
234
+
235
+ def ddm_ilu(a):
236
+ """a <-- LU(a)"""
237
+ m = len(a)
238
+ if not m:
239
+ return []
240
+ n = len(a[0])
241
+
242
+ swaps = []
243
+
244
+ for i in range(min(m, n)):
245
+ if not a[i][i]:
246
+ for ip in range(i+1, m):
247
+ if a[ip][i]:
248
+ swaps.append((i, ip))
249
+ a[i], a[ip] = a[ip], a[i]
250
+ break
251
+ else:
252
+ # M = Matrix([[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 1], [0, 0, 1, 2]])
253
+ continue
254
+ for j in range(i+1, m):
255
+ l_ji = a[j][i] / a[i][i]
256
+ a[j][i] = l_ji
257
+ for k in range(i+1, n):
258
+ a[j][k] -= l_ji * a[i][k]
259
+
260
+ return swaps
261
+
262
+
263
+ def ddm_ilu_solve(x, L, U, swaps, b):
264
+ """x <-- solve(L*U*x = swaps(b))"""
265
+ m = len(U)
266
+ if not m:
267
+ return
268
+ n = len(U[0])
269
+
270
+ m2 = len(b)
271
+ if not m2:
272
+ raise DMShapeError("Shape mismtch")
273
+ o = len(b[0])
274
+
275
+ if m != m2:
276
+ raise DMShapeError("Shape mismtch")
277
+ if m < n:
278
+ raise NotImplementedError("Underdetermined")
279
+
280
+ if swaps:
281
+ b = [row[:] for row in b]
282
+ for i1, i2 in swaps:
283
+ b[i1], b[i2] = b[i2], b[i1]
284
+
285
+ # solve Ly = b
286
+ y = [[None] * o for _ in range(m)]
287
+ for k in range(o):
288
+ for i in range(m):
289
+ rhs = b[i][k]
290
+ for j in range(i):
291
+ rhs -= L[i][j] * y[j][k]
292
+ y[i][k] = rhs
293
+
294
+ if m > n:
295
+ for i in range(n, m):
296
+ for j in range(o):
297
+ if y[i][j]:
298
+ raise DMNonInvertibleMatrixError
299
+
300
+ # Solve Ux = y
301
+ for k in range(o):
302
+ for i in reversed(range(n)):
303
+ if not U[i][i]:
304
+ raise DMNonInvertibleMatrixError
305
+ rhs = y[i][k]
306
+ for j in range(i+1, n):
307
+ rhs -= U[i][j] * x[j][k]
308
+ x[i][k] = rhs / U[i][i]
309
+
310
+
311
+ def ddm_berk(M, K):
312
+ m = len(M)
313
+ if not m:
314
+ return [[K.one]]
315
+ n = len(M[0])
316
+
317
+ if m != n:
318
+ raise DMShapeError("Not square")
319
+
320
+ if n == 1:
321
+ return [[K.one], [-M[0][0]]]
322
+
323
+ a = M[0][0]
324
+ R = [M[0][1:]]
325
+ C = [[row[0]] for row in M[1:]]
326
+ A = [row[1:] for row in M[1:]]
327
+
328
+ q = ddm_berk(A, K)
329
+
330
+ T = [[K.zero] * n for _ in range(n+1)]
331
+ for i in range(n):
332
+ T[i][i] = K.one
333
+ T[i+1][i] = -a
334
+ for i in range(2, n+1):
335
+ if i == 2:
336
+ AnC = C
337
+ else:
338
+ C = AnC
339
+ AnC = [[K.zero] for row in C]
340
+ ddm_imatmul(AnC, A, C)
341
+ RAnC = [[K.zero]]
342
+ ddm_imatmul(RAnC, R, AnC)
343
+ for j in range(0, n+1-i):
344
+ T[i+j][j] = -RAnC[0][0]
345
+
346
+ qout = [[K.zero] for _ in range(n+1)]
347
+ ddm_imatmul(qout, T, q)
348
+ return qout
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/domainmatrix.py ADDED
@@ -0,0 +1,1791 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+
3
+ Module for the DomainMatrix class.
4
+
5
+ A DomainMatrix represents a matrix with elements that are in a particular
6
+ Domain. Each DomainMatrix internally wraps a DDM which is used for the
7
+ lower-level operations. The idea is that the DomainMatrix class provides the
8
+ convenience routines for converting between Expr and the poly domains as well
9
+ as unifying matrices with different domains.
10
+
11
+ """
12
+ from functools import reduce
13
+ from typing import Union as tUnion, Tuple as tTuple
14
+
15
+ from sympy.core.sympify import _sympify
16
+
17
+ from ..domains import Domain
18
+
19
+ from ..constructor import construct_domain
20
+
21
+ from .exceptions import (DMNonSquareMatrixError, DMShapeError,
22
+ DMDomainError, DMFormatError, DMBadInputError,
23
+ DMNotAField)
24
+
25
+ from .ddm import DDM
26
+
27
+ from .sdm import SDM
28
+
29
+ from .domainscalar import DomainScalar
30
+
31
+ from sympy.polys.domains import ZZ, EXRAW, QQ
32
+
33
+
34
+ def DM(rows, domain):
35
+ """Convenient alias for DomainMatrix.from_list
36
+
37
+ Examples
38
+ =======
39
+
40
+ >>> from sympy import ZZ
41
+ >>> from sympy.polys.matrices import DM
42
+ >>> DM([[1, 2], [3, 4]], ZZ)
43
+ DomainMatrix([[1, 2], [3, 4]], (2, 2), ZZ)
44
+
45
+ See also
46
+ =======
47
+
48
+ DomainMatrix.from_list
49
+ """
50
+ return DomainMatrix.from_list(rows, domain)
51
+
52
+
53
+ class DomainMatrix:
54
+ r"""
55
+ Associate Matrix with :py:class:`~.Domain`
56
+
57
+ Explanation
58
+ ===========
59
+
60
+ DomainMatrix uses :py:class:`~.Domain` for its internal representation
61
+ which makes it faster than the SymPy Matrix class (currently) for many
62
+ common operations, but this advantage makes it not entirely compatible
63
+ with Matrix. DomainMatrix are analogous to numpy arrays with "dtype".
64
+ In the DomainMatrix, each element has a domain such as :ref:`ZZ`
65
+ or :ref:`QQ(a)`.
66
+
67
+
68
+ Examples
69
+ ========
70
+
71
+ Creating a DomainMatrix from the existing Matrix class:
72
+
73
+ >>> from sympy import Matrix
74
+ >>> from sympy.polys.matrices import DomainMatrix
75
+ >>> Matrix1 = Matrix([
76
+ ... [1, 2],
77
+ ... [3, 4]])
78
+ >>> A = DomainMatrix.from_Matrix(Matrix1)
79
+ >>> A
80
+ DomainMatrix({0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}}, (2, 2), ZZ)
81
+
82
+ Directly forming a DomainMatrix:
83
+
84
+ >>> from sympy import ZZ
85
+ >>> from sympy.polys.matrices import DomainMatrix
86
+ >>> A = DomainMatrix([
87
+ ... [ZZ(1), ZZ(2)],
88
+ ... [ZZ(3), ZZ(4)]], (2, 2), ZZ)
89
+ >>> A
90
+ DomainMatrix([[1, 2], [3, 4]], (2, 2), ZZ)
91
+
92
+ See Also
93
+ ========
94
+
95
+ DDM
96
+ SDM
97
+ Domain
98
+ Poly
99
+
100
+ """
101
+ rep: tUnion[SDM, DDM]
102
+ shape: tTuple[int, int]
103
+ domain: Domain
104
+
105
+ def __new__(cls, rows, shape, domain, *, fmt=None):
106
+ """
107
+ Creates a :py:class:`~.DomainMatrix`.
108
+
109
+ Parameters
110
+ ==========
111
+
112
+ rows : Represents elements of DomainMatrix as list of lists
113
+ shape : Represents dimension of DomainMatrix
114
+ domain : Represents :py:class:`~.Domain` of DomainMatrix
115
+
116
+ Raises
117
+ ======
118
+
119
+ TypeError
120
+ If any of rows, shape and domain are not provided
121
+
122
+ """
123
+ if isinstance(rows, (DDM, SDM)):
124
+ raise TypeError("Use from_rep to initialise from SDM/DDM")
125
+ elif isinstance(rows, list):
126
+ rep = DDM(rows, shape, domain)
127
+ elif isinstance(rows, dict):
128
+ rep = SDM(rows, shape, domain)
129
+ else:
130
+ msg = "Input should be list-of-lists or dict-of-dicts"
131
+ raise TypeError(msg)
132
+
133
+ if fmt is not None:
134
+ if fmt == 'sparse':
135
+ rep = rep.to_sdm()
136
+ elif fmt == 'dense':
137
+ rep = rep.to_ddm()
138
+ else:
139
+ raise ValueError("fmt should be 'sparse' or 'dense'")
140
+
141
+ return cls.from_rep(rep)
142
+
143
+ def __getnewargs__(self):
144
+ rep = self.rep
145
+ if isinstance(rep, DDM):
146
+ arg = list(rep)
147
+ elif isinstance(rep, SDM):
148
+ arg = dict(rep)
149
+ else:
150
+ raise RuntimeError # pragma: no cover
151
+ return arg, self.shape, self.domain
152
+
153
+ def __getitem__(self, key):
154
+ i, j = key
155
+ m, n = self.shape
156
+ if not (isinstance(i, slice) or isinstance(j, slice)):
157
+ return DomainScalar(self.rep.getitem(i, j), self.domain)
158
+
159
+ if not isinstance(i, slice):
160
+ if not -m <= i < m:
161
+ raise IndexError("Row index out of range")
162
+ i = i % m
163
+ i = slice(i, i+1)
164
+ if not isinstance(j, slice):
165
+ if not -n <= j < n:
166
+ raise IndexError("Column index out of range")
167
+ j = j % n
168
+ j = slice(j, j+1)
169
+
170
+ return self.from_rep(self.rep.extract_slice(i, j))
171
+
172
+ def getitem_sympy(self, i, j):
173
+ return self.domain.to_sympy(self.rep.getitem(i, j))
174
+
175
+ def extract(self, rowslist, colslist):
176
+ return self.from_rep(self.rep.extract(rowslist, colslist))
177
+
178
+ def __setitem__(self, key, value):
179
+ i, j = key
180
+ if not self.domain.of_type(value):
181
+ raise TypeError
182
+ if isinstance(i, int) and isinstance(j, int):
183
+ self.rep.setitem(i, j, value)
184
+ else:
185
+ raise NotImplementedError
186
+
187
+ @classmethod
188
+ def from_rep(cls, rep):
189
+ """Create a new DomainMatrix efficiently from DDM/SDM.
190
+
191
+ Examples
192
+ ========
193
+
194
+ Create a :py:class:`~.DomainMatrix` with an dense internal
195
+ representation as :py:class:`~.DDM`:
196
+
197
+ >>> from sympy.polys.domains import ZZ
198
+ >>> from sympy.polys.matrices import DomainMatrix
199
+ >>> from sympy.polys.matrices.ddm import DDM
200
+ >>> drep = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
201
+ >>> dM = DomainMatrix.from_rep(drep)
202
+ >>> dM
203
+ DomainMatrix([[1, 2], [3, 4]], (2, 2), ZZ)
204
+
205
+ Create a :py:class:`~.DomainMatrix` with a sparse internal
206
+ representation as :py:class:`~.SDM`:
207
+
208
+ >>> from sympy.polys.matrices import DomainMatrix
209
+ >>> from sympy.polys.matrices.sdm import SDM
210
+ >>> from sympy import ZZ
211
+ >>> drep = SDM({0:{1:ZZ(1)},1:{0:ZZ(2)}}, (2, 2), ZZ)
212
+ >>> dM = DomainMatrix.from_rep(drep)
213
+ >>> dM
214
+ DomainMatrix({0: {1: 1}, 1: {0: 2}}, (2, 2), ZZ)
215
+
216
+ Parameters
217
+ ==========
218
+
219
+ rep: SDM or DDM
220
+ The internal sparse or dense representation of the matrix.
221
+
222
+ Returns
223
+ =======
224
+
225
+ DomainMatrix
226
+ A :py:class:`~.DomainMatrix` wrapping *rep*.
227
+
228
+ Notes
229
+ =====
230
+
231
+ This takes ownership of rep as its internal representation. If rep is
232
+ being mutated elsewhere then a copy should be provided to
233
+ ``from_rep``. Only minimal verification or checking is done on *rep*
234
+ as this is supposed to be an efficient internal routine.
235
+
236
+ """
237
+ if not isinstance(rep, (DDM, SDM)):
238
+ raise TypeError("rep should be of type DDM or SDM")
239
+ self = super().__new__(cls)
240
+ self.rep = rep
241
+ self.shape = rep.shape
242
+ self.domain = rep.domain
243
+ return self
244
+
245
+
246
+ @classmethod
247
+ def from_list(cls, rows, domain):
248
+ r"""
249
+ Convert a list of lists into a DomainMatrix
250
+
251
+ Parameters
252
+ ==========
253
+
254
+ rows: list of lists
255
+ Each element of the inner lists should be either the single arg,
256
+ or tuple of args, that would be passed to the domain constructor
257
+ in order to form an element of the domain. See examples.
258
+
259
+ Returns
260
+ =======
261
+
262
+ DomainMatrix containing elements defined in rows
263
+
264
+ Examples
265
+ ========
266
+
267
+ >>> from sympy.polys.matrices import DomainMatrix
268
+ >>> from sympy import FF, QQ, ZZ
269
+ >>> A = DomainMatrix.from_list([[1, 0, 1], [0, 0, 1]], ZZ)
270
+ >>> A
271
+ DomainMatrix([[1, 0, 1], [0, 0, 1]], (2, 3), ZZ)
272
+ >>> B = DomainMatrix.from_list([[1, 0, 1], [0, 0, 1]], FF(7))
273
+ >>> B
274
+ DomainMatrix([[1 mod 7, 0 mod 7, 1 mod 7], [0 mod 7, 0 mod 7, 1 mod 7]], (2, 3), GF(7))
275
+ >>> C = DomainMatrix.from_list([[(1, 2), (3, 1)], [(1, 4), (5, 1)]], QQ)
276
+ >>> C
277
+ DomainMatrix([[1/2, 3], [1/4, 5]], (2, 2), QQ)
278
+
279
+ See Also
280
+ ========
281
+
282
+ from_list_sympy
283
+
284
+ """
285
+ nrows = len(rows)
286
+ ncols = 0 if not nrows else len(rows[0])
287
+ conv = lambda e: domain(*e) if isinstance(e, tuple) else domain(e)
288
+ domain_rows = [[conv(e) for e in row] for row in rows]
289
+ return DomainMatrix(domain_rows, (nrows, ncols), domain)
290
+
291
+
292
+ @classmethod
293
+ def from_list_sympy(cls, nrows, ncols, rows, **kwargs):
294
+ r"""
295
+ Convert a list of lists of Expr into a DomainMatrix using construct_domain
296
+
297
+ Parameters
298
+ ==========
299
+
300
+ nrows: number of rows
301
+ ncols: number of columns
302
+ rows: list of lists
303
+
304
+ Returns
305
+ =======
306
+
307
+ DomainMatrix containing elements of rows
308
+
309
+ Examples
310
+ ========
311
+
312
+ >>> from sympy.polys.matrices import DomainMatrix
313
+ >>> from sympy.abc import x, y, z
314
+ >>> A = DomainMatrix.from_list_sympy(1, 3, [[x, y, z]])
315
+ >>> A
316
+ DomainMatrix([[x, y, z]], (1, 3), ZZ[x,y,z])
317
+
318
+ See Also
319
+ ========
320
+
321
+ sympy.polys.constructor.construct_domain, from_dict_sympy
322
+
323
+ """
324
+ assert len(rows) == nrows
325
+ assert all(len(row) == ncols for row in rows)
326
+
327
+ items_sympy = [_sympify(item) for row in rows for item in row]
328
+
329
+ domain, items_domain = cls.get_domain(items_sympy, **kwargs)
330
+
331
+ domain_rows = [[items_domain[ncols*r + c] for c in range(ncols)] for r in range(nrows)]
332
+
333
+ return DomainMatrix(domain_rows, (nrows, ncols), domain)
334
+
335
+ @classmethod
336
+ def from_dict_sympy(cls, nrows, ncols, elemsdict, **kwargs):
337
+ """
338
+
339
+ Parameters
340
+ ==========
341
+
342
+ nrows: number of rows
343
+ ncols: number of cols
344
+ elemsdict: dict of dicts containing non-zero elements of the DomainMatrix
345
+
346
+ Returns
347
+ =======
348
+
349
+ DomainMatrix containing elements of elemsdict
350
+
351
+ Examples
352
+ ========
353
+
354
+ >>> from sympy.polys.matrices import DomainMatrix
355
+ >>> from sympy.abc import x,y,z
356
+ >>> elemsdict = {0: {0:x}, 1:{1: y}, 2: {2: z}}
357
+ >>> A = DomainMatrix.from_dict_sympy(3, 3, elemsdict)
358
+ >>> A
359
+ DomainMatrix({0: {0: x}, 1: {1: y}, 2: {2: z}}, (3, 3), ZZ[x,y,z])
360
+
361
+ See Also
362
+ ========
363
+
364
+ from_list_sympy
365
+
366
+ """
367
+ if not all(0 <= r < nrows for r in elemsdict):
368
+ raise DMBadInputError("Row out of range")
369
+ if not all(0 <= c < ncols for row in elemsdict.values() for c in row):
370
+ raise DMBadInputError("Column out of range")
371
+
372
+ items_sympy = [_sympify(item) for row in elemsdict.values() for item in row.values()]
373
+ domain, items_domain = cls.get_domain(items_sympy, **kwargs)
374
+
375
+ idx = 0
376
+ items_dict = {}
377
+ for i, row in elemsdict.items():
378
+ items_dict[i] = {}
379
+ for j in row:
380
+ items_dict[i][j] = items_domain[idx]
381
+ idx += 1
382
+
383
+ return DomainMatrix(items_dict, (nrows, ncols), domain)
384
+
385
+ @classmethod
386
+ def from_Matrix(cls, M, fmt='sparse',**kwargs):
387
+ r"""
388
+ Convert Matrix to DomainMatrix
389
+
390
+ Parameters
391
+ ==========
392
+
393
+ M: Matrix
394
+
395
+ Returns
396
+ =======
397
+
398
+ Returns DomainMatrix with identical elements as M
399
+
400
+ Examples
401
+ ========
402
+
403
+ >>> from sympy import Matrix
404
+ >>> from sympy.polys.matrices import DomainMatrix
405
+ >>> M = Matrix([
406
+ ... [1.0, 3.4],
407
+ ... [2.4, 1]])
408
+ >>> A = DomainMatrix.from_Matrix(M)
409
+ >>> A
410
+ DomainMatrix({0: {0: 1.0, 1: 3.4}, 1: {0: 2.4, 1: 1.0}}, (2, 2), RR)
411
+
412
+ We can keep internal representation as ddm using fmt='dense'
413
+ >>> from sympy import Matrix, QQ
414
+ >>> from sympy.polys.matrices import DomainMatrix
415
+ >>> A = DomainMatrix.from_Matrix(Matrix([[QQ(1, 2), QQ(3, 4)], [QQ(0, 1), QQ(0, 1)]]), fmt='dense')
416
+ >>> A.rep
417
+ [[1/2, 3/4], [0, 0]]
418
+
419
+ See Also
420
+ ========
421
+
422
+ Matrix
423
+
424
+ """
425
+ if fmt == 'dense':
426
+ return cls.from_list_sympy(*M.shape, M.tolist(), **kwargs)
427
+
428
+ return cls.from_dict_sympy(*M.shape, M.todod(), **kwargs)
429
+
430
+ @classmethod
431
+ def get_domain(cls, items_sympy, **kwargs):
432
+ K, items_K = construct_domain(items_sympy, **kwargs)
433
+ return K, items_K
434
+
435
+ def copy(self):
436
+ return self.from_rep(self.rep.copy())
437
+
438
+ def convert_to(self, K):
439
+ r"""
440
+ Change the domain of DomainMatrix to desired domain or field
441
+
442
+ Parameters
443
+ ==========
444
+
445
+ K : Represents the desired domain or field.
446
+ Alternatively, ``None`` may be passed, in which case this method
447
+ just returns a copy of this DomainMatrix.
448
+
449
+ Returns
450
+ =======
451
+
452
+ DomainMatrix
453
+ DomainMatrix with the desired domain or field
454
+
455
+ Examples
456
+ ========
457
+
458
+ >>> from sympy import ZZ, ZZ_I
459
+ >>> from sympy.polys.matrices import DomainMatrix
460
+ >>> A = DomainMatrix([
461
+ ... [ZZ(1), ZZ(2)],
462
+ ... [ZZ(3), ZZ(4)]], (2, 2), ZZ)
463
+
464
+ >>> A.convert_to(ZZ_I)
465
+ DomainMatrix([[1, 2], [3, 4]], (2, 2), ZZ_I)
466
+
467
+ """
468
+ if K is None:
469
+ return self.copy()
470
+ return self.from_rep(self.rep.convert_to(K))
471
+
472
+ def to_sympy(self):
473
+ return self.convert_to(EXRAW)
474
+
475
+ def to_field(self):
476
+ r"""
477
+ Returns a DomainMatrix with the appropriate field
478
+
479
+ Returns
480
+ =======
481
+
482
+ DomainMatrix
483
+ DomainMatrix with the appropriate field
484
+
485
+ Examples
486
+ ========
487
+
488
+ >>> from sympy import ZZ
489
+ >>> from sympy.polys.matrices import DomainMatrix
490
+ >>> A = DomainMatrix([
491
+ ... [ZZ(1), ZZ(2)],
492
+ ... [ZZ(3), ZZ(4)]], (2, 2), ZZ)
493
+
494
+ >>> A.to_field()
495
+ DomainMatrix([[1, 2], [3, 4]], (2, 2), QQ)
496
+
497
+ """
498
+ K = self.domain.get_field()
499
+ return self.convert_to(K)
500
+
501
+ def to_sparse(self):
502
+ """
503
+ Return a sparse DomainMatrix representation of *self*.
504
+
505
+ Examples
506
+ ========
507
+
508
+ >>> from sympy.polys.matrices import DomainMatrix
509
+ >>> from sympy import QQ
510
+ >>> A = DomainMatrix([[1, 0],[0, 2]], (2, 2), QQ)
511
+ >>> A.rep
512
+ [[1, 0], [0, 2]]
513
+ >>> B = A.to_sparse()
514
+ >>> B.rep
515
+ {0: {0: 1}, 1: {1: 2}}
516
+ """
517
+ if self.rep.fmt == 'sparse':
518
+ return self
519
+
520
+ return self.from_rep(SDM.from_ddm(self.rep))
521
+
522
+ def to_dense(self):
523
+ """
524
+ Return a dense DomainMatrix representation of *self*.
525
+
526
+ Examples
527
+ ========
528
+
529
+ >>> from sympy.polys.matrices import DomainMatrix
530
+ >>> from sympy import QQ
531
+ >>> A = DomainMatrix({0: {0: 1}, 1: {1: 2}}, (2, 2), QQ)
532
+ >>> A.rep
533
+ {0: {0: 1}, 1: {1: 2}}
534
+ >>> B = A.to_dense()
535
+ >>> B.rep
536
+ [[1, 0], [0, 2]]
537
+
538
+ """
539
+ if self.rep.fmt == 'dense':
540
+ return self
541
+
542
+ return self.from_rep(SDM.to_ddm(self.rep))
543
+
544
+ @classmethod
545
+ def _unify_domain(cls, *matrices):
546
+ """Convert matrices to a common domain"""
547
+ domains = {matrix.domain for matrix in matrices}
548
+ if len(domains) == 1:
549
+ return matrices
550
+ domain = reduce(lambda x, y: x.unify(y), domains)
551
+ return tuple(matrix.convert_to(domain) for matrix in matrices)
552
+
553
+ @classmethod
554
+ def _unify_fmt(cls, *matrices, fmt=None):
555
+ """Convert matrices to the same format.
556
+
557
+ If all matrices have the same format, then return unmodified.
558
+ Otherwise convert both to the preferred format given as *fmt* which
559
+ should be 'dense' or 'sparse'.
560
+ """
561
+ formats = {matrix.rep.fmt for matrix in matrices}
562
+ if len(formats) == 1:
563
+ return matrices
564
+ if fmt == 'sparse':
565
+ return tuple(matrix.to_sparse() for matrix in matrices)
566
+ elif fmt == 'dense':
567
+ return tuple(matrix.to_dense() for matrix in matrices)
568
+ else:
569
+ raise ValueError("fmt should be 'sparse' or 'dense'")
570
+
571
+ def unify(self, *others, fmt=None):
572
+ """
573
+ Unifies the domains and the format of self and other
574
+ matrices.
575
+
576
+ Parameters
577
+ ==========
578
+
579
+ others : DomainMatrix
580
+
581
+ fmt: string 'dense', 'sparse' or `None` (default)
582
+ The preferred format to convert to if self and other are not
583
+ already in the same format. If `None` or not specified then no
584
+ conversion if performed.
585
+
586
+ Returns
587
+ =======
588
+
589
+ Tuple[DomainMatrix]
590
+ Matrices with unified domain and format
591
+
592
+ Examples
593
+ ========
594
+
595
+ Unify the domain of DomainMatrix that have different domains:
596
+
597
+ >>> from sympy import ZZ, QQ
598
+ >>> from sympy.polys.matrices import DomainMatrix
599
+ >>> A = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ)
600
+ >>> B = DomainMatrix([[QQ(1, 2), QQ(2)]], (1, 2), QQ)
601
+ >>> Aq, Bq = A.unify(B)
602
+ >>> Aq
603
+ DomainMatrix([[1, 2]], (1, 2), QQ)
604
+ >>> Bq
605
+ DomainMatrix([[1/2, 2]], (1, 2), QQ)
606
+
607
+ Unify the format (dense or sparse):
608
+
609
+ >>> A = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ)
610
+ >>> B = DomainMatrix({0:{0: ZZ(1)}}, (2, 2), ZZ)
611
+ >>> B.rep
612
+ {0: {0: 1}}
613
+
614
+ >>> A2, B2 = A.unify(B, fmt='dense')
615
+ >>> B2.rep
616
+ [[1, 0], [0, 0]]
617
+
618
+ See Also
619
+ ========
620
+
621
+ convert_to, to_dense, to_sparse
622
+
623
+ """
624
+ matrices = (self,) + others
625
+ matrices = DomainMatrix._unify_domain(*matrices)
626
+ if fmt is not None:
627
+ matrices = DomainMatrix._unify_fmt(*matrices, fmt=fmt)
628
+ return matrices
629
+
630
+ def to_Matrix(self):
631
+ r"""
632
+ Convert DomainMatrix to Matrix
633
+
634
+ Returns
635
+ =======
636
+
637
+ Matrix
638
+ MutableDenseMatrix for the DomainMatrix
639
+
640
+ Examples
641
+ ========
642
+
643
+ >>> from sympy import ZZ
644
+ >>> from sympy.polys.matrices import DomainMatrix
645
+ >>> A = DomainMatrix([
646
+ ... [ZZ(1), ZZ(2)],
647
+ ... [ZZ(3), ZZ(4)]], (2, 2), ZZ)
648
+
649
+ >>> A.to_Matrix()
650
+ Matrix([
651
+ [1, 2],
652
+ [3, 4]])
653
+
654
+ See Also
655
+ ========
656
+
657
+ from_Matrix
658
+
659
+ """
660
+ from sympy.matrices.dense import MutableDenseMatrix
661
+ elemlist = self.rep.to_list()
662
+ elements_sympy = [self.domain.to_sympy(e) for row in elemlist for e in row]
663
+ return MutableDenseMatrix(*self.shape, elements_sympy)
664
+
665
+ def to_list(self):
666
+ return self.rep.to_list()
667
+
668
+ def to_list_flat(self):
669
+ return self.rep.to_list_flat()
670
+
671
+ def to_dok(self):
672
+ return self.rep.to_dok()
673
+
674
+ def __repr__(self):
675
+ return 'DomainMatrix(%s, %r, %r)' % (str(self.rep), self.shape, self.domain)
676
+
677
+ def transpose(self):
678
+ """Matrix transpose of ``self``"""
679
+ return self.from_rep(self.rep.transpose())
680
+
681
+ def flat(self):
682
+ rows, cols = self.shape
683
+ return [self[i,j].element for i in range(rows) for j in range(cols)]
684
+
685
+ @property
686
+ def is_zero_matrix(self):
687
+ return self.rep.is_zero_matrix()
688
+
689
+ @property
690
+ def is_upper(self):
691
+ """
692
+ Says whether this matrix is upper-triangular. True can be returned
693
+ even if the matrix is not square.
694
+ """
695
+ return self.rep.is_upper()
696
+
697
+ @property
698
+ def is_lower(self):
699
+ """
700
+ Says whether this matrix is lower-triangular. True can be returned
701
+ even if the matrix is not square.
702
+ """
703
+ return self.rep.is_lower()
704
+
705
+ @property
706
+ def is_square(self):
707
+ return self.shape[0] == self.shape[1]
708
+
709
+ def rank(self):
710
+ rref, pivots = self.rref()
711
+ return len(pivots)
712
+
713
+ def hstack(A, *B):
714
+ r"""Horizontally stack the given matrices.
715
+
716
+ Parameters
717
+ ==========
718
+
719
+ B: DomainMatrix
720
+ Matrices to stack horizontally.
721
+
722
+ Returns
723
+ =======
724
+
725
+ DomainMatrix
726
+ DomainMatrix by stacking horizontally.
727
+
728
+ Examples
729
+ ========
730
+
731
+ >>> from sympy import ZZ
732
+ >>> from sympy.polys.matrices import DomainMatrix
733
+
734
+ >>> A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
735
+ >>> B = DomainMatrix([[ZZ(5), ZZ(6)], [ZZ(7), ZZ(8)]], (2, 2), ZZ)
736
+ >>> A.hstack(B)
737
+ DomainMatrix([[1, 2, 5, 6], [3, 4, 7, 8]], (2, 4), ZZ)
738
+
739
+ >>> C = DomainMatrix([[ZZ(9), ZZ(10)], [ZZ(11), ZZ(12)]], (2, 2), ZZ)
740
+ >>> A.hstack(B, C)
741
+ DomainMatrix([[1, 2, 5, 6, 9, 10], [3, 4, 7, 8, 11, 12]], (2, 6), ZZ)
742
+
743
+ See Also
744
+ ========
745
+
746
+ unify
747
+ """
748
+ A, *B = A.unify(*B, fmt='dense')
749
+ return DomainMatrix.from_rep(A.rep.hstack(*(Bk.rep for Bk in B)))
750
+
751
+ def vstack(A, *B):
752
+ r"""Vertically stack the given matrices.
753
+
754
+ Parameters
755
+ ==========
756
+
757
+ B: DomainMatrix
758
+ Matrices to stack vertically.
759
+
760
+ Returns
761
+ =======
762
+
763
+ DomainMatrix
764
+ DomainMatrix by stacking vertically.
765
+
766
+ Examples
767
+ ========
768
+
769
+ >>> from sympy import ZZ
770
+ >>> from sympy.polys.matrices import DomainMatrix
771
+
772
+ >>> A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
773
+ >>> B = DomainMatrix([[ZZ(5), ZZ(6)], [ZZ(7), ZZ(8)]], (2, 2), ZZ)
774
+ >>> A.vstack(B)
775
+ DomainMatrix([[1, 2], [3, 4], [5, 6], [7, 8]], (4, 2), ZZ)
776
+
777
+ >>> C = DomainMatrix([[ZZ(9), ZZ(10)], [ZZ(11), ZZ(12)]], (2, 2), ZZ)
778
+ >>> A.vstack(B, C)
779
+ DomainMatrix([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]], (6, 2), ZZ)
780
+
781
+ See Also
782
+ ========
783
+
784
+ unify
785
+ """
786
+ A, *B = A.unify(*B, fmt='dense')
787
+ return DomainMatrix.from_rep(A.rep.vstack(*(Bk.rep for Bk in B)))
788
+
789
+ def applyfunc(self, func, domain=None):
790
+ if domain is None:
791
+ domain = self.domain
792
+ return self.from_rep(self.rep.applyfunc(func, domain))
793
+
794
+ def __add__(A, B):
795
+ if not isinstance(B, DomainMatrix):
796
+ return NotImplemented
797
+ A, B = A.unify(B, fmt='dense')
798
+ return A.add(B)
799
+
800
+ def __sub__(A, B):
801
+ if not isinstance(B, DomainMatrix):
802
+ return NotImplemented
803
+ A, B = A.unify(B, fmt='dense')
804
+ return A.sub(B)
805
+
806
+ def __neg__(A):
807
+ return A.neg()
808
+
809
+ def __mul__(A, B):
810
+ """A * B"""
811
+ if isinstance(B, DomainMatrix):
812
+ A, B = A.unify(B, fmt='dense')
813
+ return A.matmul(B)
814
+ elif B in A.domain:
815
+ return A.scalarmul(B)
816
+ elif isinstance(B, DomainScalar):
817
+ A, B = A.unify(B)
818
+ return A.scalarmul(B.element)
819
+ else:
820
+ return NotImplemented
821
+
822
+ def __rmul__(A, B):
823
+ if B in A.domain:
824
+ return A.rscalarmul(B)
825
+ elif isinstance(B, DomainScalar):
826
+ A, B = A.unify(B)
827
+ return A.rscalarmul(B.element)
828
+ else:
829
+ return NotImplemented
830
+
831
+ def __pow__(A, n):
832
+ """A ** n"""
833
+ if not isinstance(n, int):
834
+ return NotImplemented
835
+ return A.pow(n)
836
+
837
+ def _check(a, op, b, ashape, bshape):
838
+ if a.domain != b.domain:
839
+ msg = "Domain mismatch: %s %s %s" % (a.domain, op, b.domain)
840
+ raise DMDomainError(msg)
841
+ if ashape != bshape:
842
+ msg = "Shape mismatch: %s %s %s" % (a.shape, op, b.shape)
843
+ raise DMShapeError(msg)
844
+ if a.rep.fmt != b.rep.fmt:
845
+ msg = "Format mismatch: %s %s %s" % (a.rep.fmt, op, b.rep.fmt)
846
+ raise DMFormatError(msg)
847
+
848
+ def add(A, B):
849
+ r"""
850
+ Adds two DomainMatrix matrices of the same Domain
851
+
852
+ Parameters
853
+ ==========
854
+
855
+ A, B: DomainMatrix
856
+ matrices to add
857
+
858
+ Returns
859
+ =======
860
+
861
+ DomainMatrix
862
+ DomainMatrix after Addition
863
+
864
+ Raises
865
+ ======
866
+
867
+ DMShapeError
868
+ If the dimensions of the two DomainMatrix are not equal
869
+
870
+ ValueError
871
+ If the domain of the two DomainMatrix are not same
872
+
873
+ Examples
874
+ ========
875
+
876
+ >>> from sympy import ZZ
877
+ >>> from sympy.polys.matrices import DomainMatrix
878
+ >>> A = DomainMatrix([
879
+ ... [ZZ(1), ZZ(2)],
880
+ ... [ZZ(3), ZZ(4)]], (2, 2), ZZ)
881
+ >>> B = DomainMatrix([
882
+ ... [ZZ(4), ZZ(3)],
883
+ ... [ZZ(2), ZZ(1)]], (2, 2), ZZ)
884
+
885
+ >>> A.add(B)
886
+ DomainMatrix([[5, 5], [5, 5]], (2, 2), ZZ)
887
+
888
+ See Also
889
+ ========
890
+
891
+ sub, matmul
892
+
893
+ """
894
+ A._check('+', B, A.shape, B.shape)
895
+ return A.from_rep(A.rep.add(B.rep))
896
+
897
+
898
+ def sub(A, B):
899
+ r"""
900
+ Subtracts two DomainMatrix matrices of the same Domain
901
+
902
+ Parameters
903
+ ==========
904
+
905
+ A, B: DomainMatrix
906
+ matrices to subtract
907
+
908
+ Returns
909
+ =======
910
+
911
+ DomainMatrix
912
+ DomainMatrix after Subtraction
913
+
914
+ Raises
915
+ ======
916
+
917
+ DMShapeError
918
+ If the dimensions of the two DomainMatrix are not equal
919
+
920
+ ValueError
921
+ If the domain of the two DomainMatrix are not same
922
+
923
+ Examples
924
+ ========
925
+
926
+ >>> from sympy import ZZ
927
+ >>> from sympy.polys.matrices import DomainMatrix
928
+ >>> A = DomainMatrix([
929
+ ... [ZZ(1), ZZ(2)],
930
+ ... [ZZ(3), ZZ(4)]], (2, 2), ZZ)
931
+ >>> B = DomainMatrix([
932
+ ... [ZZ(4), ZZ(3)],
933
+ ... [ZZ(2), ZZ(1)]], (2, 2), ZZ)
934
+
935
+ >>> A.sub(B)
936
+ DomainMatrix([[-3, -1], [1, 3]], (2, 2), ZZ)
937
+
938
+ See Also
939
+ ========
940
+
941
+ add, matmul
942
+
943
+ """
944
+ A._check('-', B, A.shape, B.shape)
945
+ return A.from_rep(A.rep.sub(B.rep))
946
+
947
+ def neg(A):
948
+ r"""
949
+ Returns the negative of DomainMatrix
950
+
951
+ Parameters
952
+ ==========
953
+
954
+ A : Represents a DomainMatrix
955
+
956
+ Returns
957
+ =======
958
+
959
+ DomainMatrix
960
+ DomainMatrix after Negation
961
+
962
+ Examples
963
+ ========
964
+
965
+ >>> from sympy import ZZ
966
+ >>> from sympy.polys.matrices import DomainMatrix
967
+ >>> A = DomainMatrix([
968
+ ... [ZZ(1), ZZ(2)],
969
+ ... [ZZ(3), ZZ(4)]], (2, 2), ZZ)
970
+
971
+ >>> A.neg()
972
+ DomainMatrix([[-1, -2], [-3, -4]], (2, 2), ZZ)
973
+
974
+ """
975
+ return A.from_rep(A.rep.neg())
976
+
977
+ def mul(A, b):
978
+ r"""
979
+ Performs term by term multiplication for the second DomainMatrix
980
+ w.r.t first DomainMatrix. Returns a DomainMatrix whose rows are
981
+ list of DomainMatrix matrices created after term by term multiplication.
982
+
983
+ Parameters
984
+ ==========
985
+
986
+ A, B: DomainMatrix
987
+ matrices to multiply term-wise
988
+
989
+ Returns
990
+ =======
991
+
992
+ DomainMatrix
993
+ DomainMatrix after term by term multiplication
994
+
995
+ Examples
996
+ ========
997
+
998
+ >>> from sympy import ZZ
999
+ >>> from sympy.polys.matrices import DomainMatrix
1000
+ >>> A = DomainMatrix([
1001
+ ... [ZZ(1), ZZ(2)],
1002
+ ... [ZZ(3), ZZ(4)]], (2, 2), ZZ)
1003
+ >>> B = DomainMatrix([
1004
+ ... [ZZ(1), ZZ(1)],
1005
+ ... [ZZ(0), ZZ(1)]], (2, 2), ZZ)
1006
+
1007
+ >>> A.mul(B)
1008
+ DomainMatrix([[DomainMatrix([[1, 1], [0, 1]], (2, 2), ZZ),
1009
+ DomainMatrix([[2, 2], [0, 2]], (2, 2), ZZ)],
1010
+ [DomainMatrix([[3, 3], [0, 3]], (2, 2), ZZ),
1011
+ DomainMatrix([[4, 4], [0, 4]], (2, 2), ZZ)]], (2, 2), ZZ)
1012
+
1013
+ See Also
1014
+ ========
1015
+
1016
+ matmul
1017
+
1018
+ """
1019
+ return A.from_rep(A.rep.mul(b))
1020
+
1021
+ def rmul(A, b):
1022
+ return A.from_rep(A.rep.rmul(b))
1023
+
1024
+ def matmul(A, B):
1025
+ r"""
1026
+ Performs matrix multiplication of two DomainMatrix matrices
1027
+
1028
+ Parameters
1029
+ ==========
1030
+
1031
+ A, B: DomainMatrix
1032
+ to multiply
1033
+
1034
+ Returns
1035
+ =======
1036
+
1037
+ DomainMatrix
1038
+ DomainMatrix after multiplication
1039
+
1040
+ Examples
1041
+ ========
1042
+
1043
+ >>> from sympy import ZZ
1044
+ >>> from sympy.polys.matrices import DomainMatrix
1045
+ >>> A = DomainMatrix([
1046
+ ... [ZZ(1), ZZ(2)],
1047
+ ... [ZZ(3), ZZ(4)]], (2, 2), ZZ)
1048
+ >>> B = DomainMatrix([
1049
+ ... [ZZ(1), ZZ(1)],
1050
+ ... [ZZ(0), ZZ(1)]], (2, 2), ZZ)
1051
+
1052
+ >>> A.matmul(B)
1053
+ DomainMatrix([[1, 3], [3, 7]], (2, 2), ZZ)
1054
+
1055
+ See Also
1056
+ ========
1057
+
1058
+ mul, pow, add, sub
1059
+
1060
+ """
1061
+
1062
+ A._check('*', B, A.shape[1], B.shape[0])
1063
+ return A.from_rep(A.rep.matmul(B.rep))
1064
+
1065
+ def _scalarmul(A, lamda, reverse):
1066
+ if lamda == A.domain.zero:
1067
+ return DomainMatrix.zeros(A.shape, A.domain)
1068
+ elif lamda == A.domain.one:
1069
+ return A.copy()
1070
+ elif reverse:
1071
+ return A.rmul(lamda)
1072
+ else:
1073
+ return A.mul(lamda)
1074
+
1075
+ def scalarmul(A, lamda):
1076
+ return A._scalarmul(lamda, reverse=False)
1077
+
1078
+ def rscalarmul(A, lamda):
1079
+ return A._scalarmul(lamda, reverse=True)
1080
+
1081
+ def mul_elementwise(A, B):
1082
+ assert A.domain == B.domain
1083
+ return A.from_rep(A.rep.mul_elementwise(B.rep))
1084
+
1085
+ def __truediv__(A, lamda):
1086
+ """ Method for Scalar Division"""
1087
+ if isinstance(lamda, int) or ZZ.of_type(lamda):
1088
+ lamda = DomainScalar(ZZ(lamda), ZZ)
1089
+
1090
+ if not isinstance(lamda, DomainScalar):
1091
+ return NotImplemented
1092
+
1093
+ A, lamda = A.to_field().unify(lamda)
1094
+ if lamda.element == lamda.domain.zero:
1095
+ raise ZeroDivisionError
1096
+ if lamda.element == lamda.domain.one:
1097
+ return A.to_field()
1098
+
1099
+ return A.mul(1 / lamda.element)
1100
+
1101
+ def pow(A, n):
1102
+ r"""
1103
+ Computes A**n
1104
+
1105
+ Parameters
1106
+ ==========
1107
+
1108
+ A : DomainMatrix
1109
+
1110
+ n : exponent for A
1111
+
1112
+ Returns
1113
+ =======
1114
+
1115
+ DomainMatrix
1116
+ DomainMatrix on computing A**n
1117
+
1118
+ Raises
1119
+ ======
1120
+
1121
+ NotImplementedError
1122
+ if n is negative.
1123
+
1124
+ Examples
1125
+ ========
1126
+
1127
+ >>> from sympy import ZZ
1128
+ >>> from sympy.polys.matrices import DomainMatrix
1129
+ >>> A = DomainMatrix([
1130
+ ... [ZZ(1), ZZ(1)],
1131
+ ... [ZZ(0), ZZ(1)]], (2, 2), ZZ)
1132
+
1133
+ >>> A.pow(2)
1134
+ DomainMatrix([[1, 2], [0, 1]], (2, 2), ZZ)
1135
+
1136
+ See Also
1137
+ ========
1138
+
1139
+ matmul
1140
+
1141
+ """
1142
+ nrows, ncols = A.shape
1143
+ if nrows != ncols:
1144
+ raise DMNonSquareMatrixError('Power of a nonsquare matrix')
1145
+ if n < 0:
1146
+ raise NotImplementedError('Negative powers')
1147
+ elif n == 0:
1148
+ return A.eye(nrows, A.domain)
1149
+ elif n == 1:
1150
+ return A
1151
+ elif n % 2 == 1:
1152
+ return A * A**(n - 1)
1153
+ else:
1154
+ sqrtAn = A ** (n // 2)
1155
+ return sqrtAn * sqrtAn
1156
+
1157
+ def scc(self):
1158
+ """Compute the strongly connected components of a DomainMatrix
1159
+
1160
+ Explanation
1161
+ ===========
1162
+
1163
+ A square matrix can be considered as the adjacency matrix for a
1164
+ directed graph where the row and column indices are the vertices. In
1165
+ this graph if there is an edge from vertex ``i`` to vertex ``j`` if
1166
+ ``M[i, j]`` is nonzero. This routine computes the strongly connected
1167
+ components of that graph which are subsets of the rows and columns that
1168
+ are connected by some nonzero element of the matrix. The strongly
1169
+ connected components are useful because many operations such as the
1170
+ determinant can be computed by working with the submatrices
1171
+ corresponding to each component.
1172
+
1173
+ Examples
1174
+ ========
1175
+
1176
+ Find the strongly connected components of a matrix:
1177
+
1178
+ >>> from sympy import ZZ
1179
+ >>> from sympy.polys.matrices import DomainMatrix
1180
+ >>> M = DomainMatrix([[ZZ(1), ZZ(0), ZZ(2)],
1181
+ ... [ZZ(0), ZZ(3), ZZ(0)],
1182
+ ... [ZZ(4), ZZ(6), ZZ(5)]], (3, 3), ZZ)
1183
+ >>> M.scc()
1184
+ [[1], [0, 2]]
1185
+
1186
+ Compute the determinant from the components:
1187
+
1188
+ >>> MM = M.to_Matrix()
1189
+ >>> MM
1190
+ Matrix([
1191
+ [1, 0, 2],
1192
+ [0, 3, 0],
1193
+ [4, 6, 5]])
1194
+ >>> MM[[1], [1]]
1195
+ Matrix([[3]])
1196
+ >>> MM[[0, 2], [0, 2]]
1197
+ Matrix([
1198
+ [1, 2],
1199
+ [4, 5]])
1200
+ >>> MM.det()
1201
+ -9
1202
+ >>> MM[[1], [1]].det() * MM[[0, 2], [0, 2]].det()
1203
+ -9
1204
+
1205
+ The components are given in reverse topological order and represent a
1206
+ permutation of the rows and columns that will bring the matrix into
1207
+ block lower-triangular form:
1208
+
1209
+ >>> MM[[1, 0, 2], [1, 0, 2]]
1210
+ Matrix([
1211
+ [3, 0, 0],
1212
+ [0, 1, 2],
1213
+ [6, 4, 5]])
1214
+
1215
+ Returns
1216
+ =======
1217
+
1218
+ List of lists of integers
1219
+ Each list represents a strongly connected component.
1220
+
1221
+ See also
1222
+ ========
1223
+
1224
+ sympy.matrices.matrices.MatrixBase.strongly_connected_components
1225
+ sympy.utilities.iterables.strongly_connected_components
1226
+
1227
+ """
1228
+ rows, cols = self.shape
1229
+ assert rows == cols
1230
+ return self.rep.scc()
1231
+
1232
+ def rref(self):
1233
+ r"""
1234
+ Returns reduced-row echelon form and list of pivots for the DomainMatrix
1235
+
1236
+ Returns
1237
+ =======
1238
+
1239
+ (DomainMatrix, list)
1240
+ reduced-row echelon form and list of pivots for the DomainMatrix
1241
+
1242
+ Raises
1243
+ ======
1244
+
1245
+ ValueError
1246
+ If the domain of DomainMatrix not a Field
1247
+
1248
+ Examples
1249
+ ========
1250
+
1251
+ >>> from sympy import QQ
1252
+ >>> from sympy.polys.matrices import DomainMatrix
1253
+ >>> A = DomainMatrix([
1254
+ ... [QQ(2), QQ(-1), QQ(0)],
1255
+ ... [QQ(-1), QQ(2), QQ(-1)],
1256
+ ... [QQ(0), QQ(0), QQ(2)]], (3, 3), QQ)
1257
+
1258
+ >>> rref_matrix, rref_pivots = A.rref()
1259
+ >>> rref_matrix
1260
+ DomainMatrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]], (3, 3), QQ)
1261
+ >>> rref_pivots
1262
+ (0, 1, 2)
1263
+
1264
+ See Also
1265
+ ========
1266
+
1267
+ convert_to, lu
1268
+
1269
+ """
1270
+ if not self.domain.is_Field:
1271
+ raise DMNotAField('Not a field')
1272
+ rref_ddm, pivots = self.rep.rref()
1273
+ return self.from_rep(rref_ddm), tuple(pivots)
1274
+
1275
+ def columnspace(self):
1276
+ r"""
1277
+ Returns the columnspace for the DomainMatrix
1278
+
1279
+ Returns
1280
+ =======
1281
+
1282
+ DomainMatrix
1283
+ The columns of this matrix form a basis for the columnspace.
1284
+
1285
+ Examples
1286
+ ========
1287
+
1288
+ >>> from sympy import QQ
1289
+ >>> from sympy.polys.matrices import DomainMatrix
1290
+ >>> A = DomainMatrix([
1291
+ ... [QQ(1), QQ(-1)],
1292
+ ... [QQ(2), QQ(-2)]], (2, 2), QQ)
1293
+ >>> A.columnspace()
1294
+ DomainMatrix([[1], [2]], (2, 1), QQ)
1295
+
1296
+ """
1297
+ if not self.domain.is_Field:
1298
+ raise DMNotAField('Not a field')
1299
+ rref, pivots = self.rref()
1300
+ rows, cols = self.shape
1301
+ return self.extract(range(rows), pivots)
1302
+
1303
+ def rowspace(self):
1304
+ r"""
1305
+ Returns the rowspace for the DomainMatrix
1306
+
1307
+ Returns
1308
+ =======
1309
+
1310
+ DomainMatrix
1311
+ The rows of this matrix form a basis for the rowspace.
1312
+
1313
+ Examples
1314
+ ========
1315
+
1316
+ >>> from sympy import QQ
1317
+ >>> from sympy.polys.matrices import DomainMatrix
1318
+ >>> A = DomainMatrix([
1319
+ ... [QQ(1), QQ(-1)],
1320
+ ... [QQ(2), QQ(-2)]], (2, 2), QQ)
1321
+ >>> A.rowspace()
1322
+ DomainMatrix([[1, -1]], (1, 2), QQ)
1323
+
1324
+ """
1325
+ if not self.domain.is_Field:
1326
+ raise DMNotAField('Not a field')
1327
+ rref, pivots = self.rref()
1328
+ rows, cols = self.shape
1329
+ return self.extract(range(len(pivots)), range(cols))
1330
+
1331
+ def nullspace(self):
1332
+ r"""
1333
+ Returns the nullspace for the DomainMatrix
1334
+
1335
+ Returns
1336
+ =======
1337
+
1338
+ DomainMatrix
1339
+ The rows of this matrix form a basis for the nullspace.
1340
+
1341
+ Examples
1342
+ ========
1343
+
1344
+ >>> from sympy import QQ
1345
+ >>> from sympy.polys.matrices import DomainMatrix
1346
+ >>> A = DomainMatrix([
1347
+ ... [QQ(1), QQ(-1)],
1348
+ ... [QQ(2), QQ(-2)]], (2, 2), QQ)
1349
+ >>> A.nullspace()
1350
+ DomainMatrix([[1, 1]], (1, 2), QQ)
1351
+
1352
+ """
1353
+ if not self.domain.is_Field:
1354
+ raise DMNotAField('Not a field')
1355
+ return self.from_rep(self.rep.nullspace()[0])
1356
+
1357
+ def inv(self):
1358
+ r"""
1359
+ Finds the inverse of the DomainMatrix if exists
1360
+
1361
+ Returns
1362
+ =======
1363
+
1364
+ DomainMatrix
1365
+ DomainMatrix after inverse
1366
+
1367
+ Raises
1368
+ ======
1369
+
1370
+ ValueError
1371
+ If the domain of DomainMatrix not a Field
1372
+
1373
+ DMNonSquareMatrixError
1374
+ If the DomainMatrix is not a not Square DomainMatrix
1375
+
1376
+ Examples
1377
+ ========
1378
+
1379
+ >>> from sympy import QQ
1380
+ >>> from sympy.polys.matrices import DomainMatrix
1381
+ >>> A = DomainMatrix([
1382
+ ... [QQ(2), QQ(-1), QQ(0)],
1383
+ ... [QQ(-1), QQ(2), QQ(-1)],
1384
+ ... [QQ(0), QQ(0), QQ(2)]], (3, 3), QQ)
1385
+ >>> A.inv()
1386
+ DomainMatrix([[2/3, 1/3, 1/6], [1/3, 2/3, 1/3], [0, 0, 1/2]], (3, 3), QQ)
1387
+
1388
+ See Also
1389
+ ========
1390
+
1391
+ neg
1392
+
1393
+ """
1394
+ if not self.domain.is_Field:
1395
+ raise DMNotAField('Not a field')
1396
+ m, n = self.shape
1397
+ if m != n:
1398
+ raise DMNonSquareMatrixError
1399
+ inv = self.rep.inv()
1400
+ return self.from_rep(inv)
1401
+
1402
+ def det(self):
1403
+ r"""
1404
+ Returns the determinant of a Square DomainMatrix
1405
+
1406
+ Returns
1407
+ =======
1408
+
1409
+ S.Complexes
1410
+ determinant of Square DomainMatrix
1411
+
1412
+ Raises
1413
+ ======
1414
+
1415
+ ValueError
1416
+ If the domain of DomainMatrix not a Field
1417
+
1418
+ Examples
1419
+ ========
1420
+
1421
+ >>> from sympy import ZZ
1422
+ >>> from sympy.polys.matrices import DomainMatrix
1423
+ >>> A = DomainMatrix([
1424
+ ... [ZZ(1), ZZ(2)],
1425
+ ... [ZZ(3), ZZ(4)]], (2, 2), ZZ)
1426
+
1427
+ >>> A.det()
1428
+ -2
1429
+
1430
+ """
1431
+ m, n = self.shape
1432
+ if m != n:
1433
+ raise DMNonSquareMatrixError
1434
+ return self.rep.det()
1435
+
1436
+ def lu(self):
1437
+ r"""
1438
+ Returns Lower and Upper decomposition of the DomainMatrix
1439
+
1440
+ Returns
1441
+ =======
1442
+
1443
+ (L, U, exchange)
1444
+ L, U are Lower and Upper decomposition of the DomainMatrix,
1445
+ exchange is the list of indices of rows exchanged in the decomposition.
1446
+
1447
+ Raises
1448
+ ======
1449
+
1450
+ ValueError
1451
+ If the domain of DomainMatrix not a Field
1452
+
1453
+ Examples
1454
+ ========
1455
+
1456
+ >>> from sympy import QQ
1457
+ >>> from sympy.polys.matrices import DomainMatrix
1458
+ >>> A = DomainMatrix([
1459
+ ... [QQ(1), QQ(-1)],
1460
+ ... [QQ(2), QQ(-2)]], (2, 2), QQ)
1461
+ >>> A.lu()
1462
+ (DomainMatrix([[1, 0], [2, 1]], (2, 2), QQ), DomainMatrix([[1, -1], [0, 0]], (2, 2), QQ), [])
1463
+
1464
+ See Also
1465
+ ========
1466
+
1467
+ lu_solve
1468
+
1469
+ """
1470
+ if not self.domain.is_Field:
1471
+ raise DMNotAField('Not a field')
1472
+ L, U, swaps = self.rep.lu()
1473
+ return self.from_rep(L), self.from_rep(U), swaps
1474
+
1475
+ def lu_solve(self, rhs):
1476
+ r"""
1477
+ Solver for DomainMatrix x in the A*x = B
1478
+
1479
+ Parameters
1480
+ ==========
1481
+
1482
+ rhs : DomainMatrix B
1483
+
1484
+ Returns
1485
+ =======
1486
+
1487
+ DomainMatrix
1488
+ x in A*x = B
1489
+
1490
+ Raises
1491
+ ======
1492
+
1493
+ DMShapeError
1494
+ If the DomainMatrix A and rhs have different number of rows
1495
+
1496
+ ValueError
1497
+ If the domain of DomainMatrix A not a Field
1498
+
1499
+ Examples
1500
+ ========
1501
+
1502
+ >>> from sympy import QQ
1503
+ >>> from sympy.polys.matrices import DomainMatrix
1504
+ >>> A = DomainMatrix([
1505
+ ... [QQ(1), QQ(2)],
1506
+ ... [QQ(3), QQ(4)]], (2, 2), QQ)
1507
+ >>> B = DomainMatrix([
1508
+ ... [QQ(1), QQ(1)],
1509
+ ... [QQ(0), QQ(1)]], (2, 2), QQ)
1510
+
1511
+ >>> A.lu_solve(B)
1512
+ DomainMatrix([[-2, -1], [3/2, 1]], (2, 2), QQ)
1513
+
1514
+ See Also
1515
+ ========
1516
+
1517
+ lu
1518
+
1519
+ """
1520
+ if self.shape[0] != rhs.shape[0]:
1521
+ raise DMShapeError("Shape")
1522
+ if not self.domain.is_Field:
1523
+ raise DMNotAField('Not a field')
1524
+ sol = self.rep.lu_solve(rhs.rep)
1525
+ return self.from_rep(sol)
1526
+
1527
+ def _solve(A, b):
1528
+ # XXX: Not sure about this method or its signature. It is just created
1529
+ # because it is needed by the holonomic module.
1530
+ if A.shape[0] != b.shape[0]:
1531
+ raise DMShapeError("Shape")
1532
+ if A.domain != b.domain or not A.domain.is_Field:
1533
+ raise DMNotAField('Not a field')
1534
+ Aaug = A.hstack(b)
1535
+ Arref, pivots = Aaug.rref()
1536
+ particular = Arref.from_rep(Arref.rep.particular())
1537
+ nullspace_rep, nonpivots = Arref[:,:-1].rep.nullspace()
1538
+ nullspace = Arref.from_rep(nullspace_rep)
1539
+ return particular, nullspace
1540
+
1541
+ def charpoly(self):
1542
+ r"""
1543
+ Returns the coefficients of the characteristic polynomial
1544
+ of the DomainMatrix. These elements will be domain elements.
1545
+ The domain of the elements will be same as domain of the DomainMatrix.
1546
+
1547
+ Returns
1548
+ =======
1549
+
1550
+ list
1551
+ coefficients of the characteristic polynomial
1552
+
1553
+ Raises
1554
+ ======
1555
+
1556
+ DMNonSquareMatrixError
1557
+ If the DomainMatrix is not a not Square DomainMatrix
1558
+
1559
+ Examples
1560
+ ========
1561
+
1562
+ >>> from sympy import ZZ
1563
+ >>> from sympy.polys.matrices import DomainMatrix
1564
+ >>> A = DomainMatrix([
1565
+ ... [ZZ(1), ZZ(2)],
1566
+ ... [ZZ(3), ZZ(4)]], (2, 2), ZZ)
1567
+
1568
+ >>> A.charpoly()
1569
+ [1, -5, -2]
1570
+
1571
+ """
1572
+ m, n = self.shape
1573
+ if m != n:
1574
+ raise DMNonSquareMatrixError("not square")
1575
+ return self.rep.charpoly()
1576
+
1577
+ @classmethod
1578
+ def eye(cls, shape, domain):
1579
+ r"""
1580
+ Return identity matrix of size n
1581
+
1582
+ Examples
1583
+ ========
1584
+
1585
+ >>> from sympy.polys.matrices import DomainMatrix
1586
+ >>> from sympy import QQ
1587
+ >>> DomainMatrix.eye(3, QQ)
1588
+ DomainMatrix({0: {0: 1}, 1: {1: 1}, 2: {2: 1}}, (3, 3), QQ)
1589
+
1590
+ """
1591
+ if isinstance(shape, int):
1592
+ shape = (shape, shape)
1593
+ return cls.from_rep(SDM.eye(shape, domain))
1594
+
1595
+ @classmethod
1596
+ def diag(cls, diagonal, domain, shape=None):
1597
+ r"""
1598
+ Return diagonal matrix with entries from ``diagonal``.
1599
+
1600
+ Examples
1601
+ ========
1602
+
1603
+ >>> from sympy.polys.matrices import DomainMatrix
1604
+ >>> from sympy import ZZ
1605
+ >>> DomainMatrix.diag([ZZ(5), ZZ(6)], ZZ)
1606
+ DomainMatrix({0: {0: 5}, 1: {1: 6}}, (2, 2), ZZ)
1607
+
1608
+ """
1609
+ if shape is None:
1610
+ N = len(diagonal)
1611
+ shape = (N, N)
1612
+ return cls.from_rep(SDM.diag(diagonal, domain, shape))
1613
+
1614
+ @classmethod
1615
+ def zeros(cls, shape, domain, *, fmt='sparse'):
1616
+ """Returns a zero DomainMatrix of size shape, belonging to the specified domain
1617
+
1618
+ Examples
1619
+ ========
1620
+
1621
+ >>> from sympy.polys.matrices import DomainMatrix
1622
+ >>> from sympy import QQ
1623
+ >>> DomainMatrix.zeros((2, 3), QQ)
1624
+ DomainMatrix({}, (2, 3), QQ)
1625
+
1626
+ """
1627
+ return cls.from_rep(SDM.zeros(shape, domain))
1628
+
1629
+ @classmethod
1630
+ def ones(cls, shape, domain):
1631
+ """Returns a DomainMatrix of 1s, of size shape, belonging to the specified domain
1632
+
1633
+ Examples
1634
+ ========
1635
+
1636
+ >>> from sympy.polys.matrices import DomainMatrix
1637
+ >>> from sympy import QQ
1638
+ >>> DomainMatrix.ones((2,3), QQ)
1639
+ DomainMatrix([[1, 1, 1], [1, 1, 1]], (2, 3), QQ)
1640
+
1641
+ """
1642
+ return cls.from_rep(DDM.ones(shape, domain))
1643
+
1644
+ def __eq__(A, B):
1645
+ r"""
1646
+ Checks for two DomainMatrix matrices to be equal or not
1647
+
1648
+ Parameters
1649
+ ==========
1650
+
1651
+ A, B: DomainMatrix
1652
+ to check equality
1653
+
1654
+ Returns
1655
+ =======
1656
+
1657
+ Boolean
1658
+ True for equal, else False
1659
+
1660
+ Raises
1661
+ ======
1662
+
1663
+ NotImplementedError
1664
+ If B is not a DomainMatrix
1665
+
1666
+ Examples
1667
+ ========
1668
+
1669
+ >>> from sympy import ZZ
1670
+ >>> from sympy.polys.matrices import DomainMatrix
1671
+ >>> A = DomainMatrix([
1672
+ ... [ZZ(1), ZZ(2)],
1673
+ ... [ZZ(3), ZZ(4)]], (2, 2), ZZ)
1674
+ >>> B = DomainMatrix([
1675
+ ... [ZZ(1), ZZ(1)],
1676
+ ... [ZZ(0), ZZ(1)]], (2, 2), ZZ)
1677
+ >>> A.__eq__(A)
1678
+ True
1679
+ >>> A.__eq__(B)
1680
+ False
1681
+
1682
+ """
1683
+ if not isinstance(A, type(B)):
1684
+ return NotImplemented
1685
+ return A.domain == B.domain and A.rep == B.rep
1686
+
1687
+ def unify_eq(A, B):
1688
+ if A.shape != B.shape:
1689
+ return False
1690
+ if A.domain != B.domain:
1691
+ A, B = A.unify(B)
1692
+ return A == B
1693
+
1694
+ def lll(A, delta=QQ(3, 4)):
1695
+ """
1696
+ Performs the Lenstra–Lenstra–Lovász (LLL) basis reduction algorithm.
1697
+ See [1]_ and [2]_.
1698
+
1699
+ Parameters
1700
+ ==========
1701
+
1702
+ delta : QQ, optional
1703
+ The Lovász parameter. Must be in the interval (0.25, 1), with larger
1704
+ values producing a more reduced basis. The default is 0.75 for
1705
+ historical reasons.
1706
+
1707
+ Returns
1708
+ =======
1709
+
1710
+ The reduced basis as a DomainMatrix over ZZ.
1711
+
1712
+ Throws
1713
+ ======
1714
+
1715
+ DMValueError: if delta is not in the range (0.25, 1)
1716
+ DMShapeError: if the matrix is not of shape (m, n) with m <= n
1717
+ DMDomainError: if the matrix domain is not ZZ
1718
+ DMRankError: if the matrix contains linearly dependent rows
1719
+
1720
+ Examples
1721
+ ========
1722
+
1723
+ >>> from sympy.polys.domains import ZZ, QQ
1724
+ >>> from sympy.polys.matrices import DM
1725
+ >>> x = DM([[1, 0, 0, 0, -20160],
1726
+ ... [0, 1, 0, 0, 33768],
1727
+ ... [0, 0, 1, 0, 39578],
1728
+ ... [0, 0, 0, 1, 47757]], ZZ)
1729
+ >>> y = DM([[10, -3, -2, 8, -4],
1730
+ ... [3, -9, 8, 1, -11],
1731
+ ... [-3, 13, -9, -3, -9],
1732
+ ... [-12, -7, -11, 9, -1]], ZZ)
1733
+ >>> assert x.lll(delta=QQ(5, 6)) == y
1734
+
1735
+ Notes
1736
+ =====
1737
+
1738
+ The implementation is derived from the Maple code given in Figures 4.3
1739
+ and 4.4 of [3]_ (pp.68-69). It uses the efficient method of only calculating
1740
+ state updates as they are required.
1741
+
1742
+ See also
1743
+ ========
1744
+
1745
+ lll_transform
1746
+
1747
+ References
1748
+ ==========
1749
+
1750
+ .. [1] https://en.wikipedia.org/wiki/Lenstra–Lenstra–Lovász_lattice_basis_reduction_algorithm
1751
+ .. [2] https://web.archive.org/web/20221029115428/https://web.cs.elte.hu/~lovasz/scans/lll.pdf
1752
+ .. [3] Murray R. Bremner, "Lattice Basis Reduction: An Introduction to the LLL Algorithm and Its Applications"
1753
+
1754
+ """
1755
+ return DomainMatrix.from_rep(A.rep.lll(delta=delta))
1756
+
1757
+ def lll_transform(A, delta=QQ(3, 4)):
1758
+ """
1759
+ Performs the Lenstra–Lenstra–Lovász (LLL) basis reduction algorithm
1760
+ and returns the reduced basis and transformation matrix.
1761
+
1762
+ Explanation
1763
+ ===========
1764
+
1765
+ Parameters, algorithm and basis are the same as for :meth:`lll` except that
1766
+ the return value is a tuple `(B, T)` with `B` the reduced basis and
1767
+ `T` a transformation matrix. The original basis `A` is transformed to
1768
+ `B` with `T*A == B`. If only `B` is needed then :meth:`lll` should be
1769
+ used as it is a little faster.
1770
+
1771
+ Examples
1772
+ ========
1773
+
1774
+ >>> from sympy.polys.domains import ZZ, QQ
1775
+ >>> from sympy.polys.matrices import DM
1776
+ >>> X = DM([[1, 0, 0, 0, -20160],
1777
+ ... [0, 1, 0, 0, 33768],
1778
+ ... [0, 0, 1, 0, 39578],
1779
+ ... [0, 0, 0, 1, 47757]], ZZ)
1780
+ >>> B, T = X.lll_transform(delta=QQ(5, 6))
1781
+ >>> T * X == B
1782
+ True
1783
+
1784
+ See also
1785
+ ========
1786
+
1787
+ lll
1788
+
1789
+ """
1790
+ reduced, transform = A.rep.lll_transform(delta=delta)
1791
+ return DomainMatrix.from_rep(reduced), DomainMatrix.from_rep(transform)
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/domainscalar.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+
3
+ Module for the DomainScalar class.
4
+
5
+ A DomainScalar represents an element which is in a particular
6
+ Domain. The idea is that the DomainScalar class provides the
7
+ convenience routines for unifying elements with different domains.
8
+
9
+ It assists in Scalar Multiplication and getitem for DomainMatrix.
10
+
11
+ """
12
+ from ..constructor import construct_domain
13
+
14
+ from sympy.polys.domains import Domain, ZZ
15
+
16
+
17
+ class DomainScalar:
18
+ r"""
19
+ docstring
20
+ """
21
+
22
+ def __new__(cls, element, domain):
23
+ if not isinstance(domain, Domain):
24
+ raise TypeError("domain should be of type Domain")
25
+ if not domain.of_type(element):
26
+ raise TypeError("element %s should be in domain %s" % (element, domain))
27
+ return cls.new(element, domain)
28
+
29
+ @classmethod
30
+ def new(cls, element, domain):
31
+ obj = super().__new__(cls)
32
+ obj.element = element
33
+ obj.domain = domain
34
+ return obj
35
+
36
+ def __repr__(self):
37
+ return repr(self.element)
38
+
39
+ @classmethod
40
+ def from_sympy(cls, expr):
41
+ [domain, [element]] = construct_domain([expr])
42
+ return cls.new(element, domain)
43
+
44
+ def to_sympy(self):
45
+ return self.domain.to_sympy(self.element)
46
+
47
+ def to_domain(self, domain):
48
+ element = domain.convert_from(self.element, self.domain)
49
+ return self.new(element, domain)
50
+
51
+ def convert_to(self, domain):
52
+ return self.to_domain(domain)
53
+
54
+ def unify(self, other):
55
+ domain = self.domain.unify(other.domain)
56
+ return self.to_domain(domain), other.to_domain(domain)
57
+
58
+ def __add__(self, other):
59
+ if not isinstance(other, DomainScalar):
60
+ return NotImplemented
61
+ self, other = self.unify(other)
62
+ return self.new(self.element + other.element, self.domain)
63
+
64
+ def __sub__(self, other):
65
+ if not isinstance(other, DomainScalar):
66
+ return NotImplemented
67
+ self, other = self.unify(other)
68
+ return self.new(self.element - other.element, self.domain)
69
+
70
+ def __mul__(self, other):
71
+ if not isinstance(other, DomainScalar):
72
+ if isinstance(other, int):
73
+ other = DomainScalar(ZZ(other), ZZ)
74
+ else:
75
+ return NotImplemented
76
+
77
+ self, other = self.unify(other)
78
+ return self.new(self.element * other.element, self.domain)
79
+
80
+ def __floordiv__(self, other):
81
+ if not isinstance(other, DomainScalar):
82
+ return NotImplemented
83
+ self, other = self.unify(other)
84
+ return self.new(self.domain.quo(self.element, other.element), self.domain)
85
+
86
+ def __mod__(self, other):
87
+ if not isinstance(other, DomainScalar):
88
+ return NotImplemented
89
+ self, other = self.unify(other)
90
+ return self.new(self.domain.rem(self.element, other.element), self.domain)
91
+
92
+ def __divmod__(self, other):
93
+ if not isinstance(other, DomainScalar):
94
+ return NotImplemented
95
+ self, other = self.unify(other)
96
+ q, r = self.domain.div(self.element, other.element)
97
+ return (self.new(q, self.domain), self.new(r, self.domain))
98
+
99
+ def __pow__(self, n):
100
+ if not isinstance(n, int):
101
+ return NotImplemented
102
+ return self.new(self.element**n, self.domain)
103
+
104
+ def __pos__(self):
105
+ return self.new(+self.element, self.domain)
106
+
107
+ def __eq__(self, other):
108
+ if not isinstance(other, DomainScalar):
109
+ return NotImplemented
110
+ return self.element == other.element and self.domain == other.domain
111
+
112
+ def is_zero(self):
113
+ return self.element == self.domain.zero
114
+
115
+ def is_one(self):
116
+ return self.element == self.domain.one
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/eigen.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+
3
+ Routines for computing eigenvectors with DomainMatrix.
4
+
5
+ """
6
+ from sympy.core.symbol import Dummy
7
+
8
+ from ..agca.extensions import FiniteExtension
9
+ from ..factortools import dup_factor_list
10
+ from ..polyroots import roots
11
+ from ..polytools import Poly
12
+ from ..rootoftools import CRootOf
13
+
14
+ from .domainmatrix import DomainMatrix
15
+
16
+
17
+ def dom_eigenvects(A, l=Dummy('lambda')):
18
+ charpoly = A.charpoly()
19
+ rows, cols = A.shape
20
+ domain = A.domain
21
+ _, factors = dup_factor_list(charpoly, domain)
22
+
23
+ rational_eigenvects = []
24
+ algebraic_eigenvects = []
25
+ for base, exp in factors:
26
+ if len(base) == 2:
27
+ field = domain
28
+ eigenval = -base[1] / base[0]
29
+
30
+ EE_items = [
31
+ [eigenval if i == j else field.zero for j in range(cols)]
32
+ for i in range(rows)]
33
+ EE = DomainMatrix(EE_items, (rows, cols), field)
34
+
35
+ basis = (A - EE).nullspace()
36
+ rational_eigenvects.append((field, eigenval, exp, basis))
37
+ else:
38
+ minpoly = Poly.from_list(base, l, domain=domain)
39
+ field = FiniteExtension(minpoly)
40
+ eigenval = field(l)
41
+
42
+ AA_items = [
43
+ [Poly.from_list([item], l, domain=domain).rep for item in row]
44
+ for row in A.rep.to_ddm()]
45
+ AA_items = [[field(item) for item in row] for row in AA_items]
46
+ AA = DomainMatrix(AA_items, (rows, cols), field)
47
+ EE_items = [
48
+ [eigenval if i == j else field.zero for j in range(cols)]
49
+ for i in range(rows)]
50
+ EE = DomainMatrix(EE_items, (rows, cols), field)
51
+
52
+ basis = (AA - EE).nullspace()
53
+ algebraic_eigenvects.append((field, minpoly, exp, basis))
54
+
55
+ return rational_eigenvects, algebraic_eigenvects
56
+
57
+
58
+ def dom_eigenvects_to_sympy(
59
+ rational_eigenvects, algebraic_eigenvects,
60
+ Matrix, **kwargs
61
+ ):
62
+ result = []
63
+
64
+ for field, eigenvalue, multiplicity, eigenvects in rational_eigenvects:
65
+ eigenvects = eigenvects.rep.to_ddm()
66
+ eigenvalue = field.to_sympy(eigenvalue)
67
+ new_eigenvects = [
68
+ Matrix([field.to_sympy(x) for x in vect])
69
+ for vect in eigenvects]
70
+ result.append((eigenvalue, multiplicity, new_eigenvects))
71
+
72
+ for field, minpoly, multiplicity, eigenvects in algebraic_eigenvects:
73
+ eigenvects = eigenvects.rep.to_ddm()
74
+ l = minpoly.gens[0]
75
+
76
+ eigenvects = [[field.to_sympy(x) for x in vect] for vect in eigenvects]
77
+
78
+ degree = minpoly.degree()
79
+ minpoly = minpoly.as_expr()
80
+ eigenvals = roots(minpoly, l, **kwargs)
81
+ if len(eigenvals) != degree:
82
+ eigenvals = [CRootOf(minpoly, l, idx) for idx in range(degree)]
83
+
84
+ for eigenvalue in eigenvals:
85
+ new_eigenvects = [
86
+ Matrix([x.subs(l, eigenvalue) for x in vect])
87
+ for vect in eigenvects]
88
+ result.append((eigenvalue, multiplicity, new_eigenvects))
89
+
90
+ return result
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/exceptions.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+
3
+ Module to define exceptions to be used in sympy.polys.matrices modules and
4
+ classes.
5
+
6
+ Ideally all exceptions raised in these modules would be defined and documented
7
+ here and not e.g. imported from matrices. Also ideally generic exceptions like
8
+ ValueError/TypeError would not be raised anywhere.
9
+
10
+ """
11
+
12
+
13
+ class DMError(Exception):
14
+ """Base class for errors raised by DomainMatrix"""
15
+ pass
16
+
17
+
18
+ class DMBadInputError(DMError):
19
+ """list of lists is inconsistent with shape"""
20
+ pass
21
+
22
+
23
+ class DMDomainError(DMError):
24
+ """domains do not match"""
25
+ pass
26
+
27
+
28
+ class DMNotAField(DMDomainError):
29
+ """domain is not a field"""
30
+ pass
31
+
32
+
33
+ class DMFormatError(DMError):
34
+ """mixed dense/sparse not supported"""
35
+ pass
36
+
37
+
38
+ class DMNonInvertibleMatrixError(DMError):
39
+ """The matrix in not invertible"""
40
+ pass
41
+
42
+
43
+ class DMRankError(DMError):
44
+ """matrix does not have expected rank"""
45
+ pass
46
+
47
+
48
+ class DMShapeError(DMError):
49
+ """shapes are inconsistent"""
50
+ pass
51
+
52
+
53
+ class DMNonSquareMatrixError(DMShapeError):
54
+ """The matrix is not square"""
55
+ pass
56
+
57
+
58
+ class DMValueError(DMError):
59
+ """The value passed is invalid"""
60
+ pass
61
+
62
+
63
+ __all__ = [
64
+ 'DMError', 'DMBadInputError', 'DMDomainError', 'DMFormatError',
65
+ 'DMRankError', 'DMShapeError', 'DMNotAField',
66
+ 'DMNonInvertibleMatrixError', 'DMNonSquareMatrixError', 'DMValueError'
67
+ ]
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/linsolve.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # sympy.polys.matrices.linsolve module
3
+ #
4
+ # This module defines the _linsolve function which is the internal workhorse
5
+ # used by linsolve. This computes the solution of a system of linear equations
6
+ # using the SDM sparse matrix implementation in sympy.polys.matrices.sdm. This
7
+ # is a replacement for solve_lin_sys in sympy.polys.solvers which is
8
+ # inefficient for large sparse systems due to the use of a PolyRing with many
9
+ # generators:
10
+ #
11
+ # https://github.com/sympy/sympy/issues/20857
12
+ #
13
+ # The implementation of _linsolve here handles:
14
+ #
15
+ # - Extracting the coefficients from the Expr/Eq input equations.
16
+ # - Constructing a domain and converting the coefficients to
17
+ # that domain.
18
+ # - Using the SDM.rref, SDM.nullspace etc methods to generate the full
19
+ # solution working with arithmetic only in the domain of the coefficients.
20
+ #
21
+ # The routines here are particularly designed to be efficient for large sparse
22
+ # systems of linear equations although as well as dense systems. It is
23
+ # possible that for some small dense systems solve_lin_sys which uses the
24
+ # dense matrix implementation DDM will be more efficient. With smaller systems
25
+ # though the bulk of the time is spent just preprocessing the inputs and the
26
+ # relative time spent in rref is too small to be noticeable.
27
+ #
28
+
29
+ from collections import defaultdict
30
+
31
+ from sympy.core.add import Add
32
+ from sympy.core.mul import Mul
33
+ from sympy.core.singleton import S
34
+
35
+ from sympy.polys.constructor import construct_domain
36
+ from sympy.polys.solvers import PolyNonlinearError
37
+
38
+ from .sdm import (
39
+ SDM,
40
+ sdm_irref,
41
+ sdm_particular_from_rref,
42
+ sdm_nullspace_from_rref
43
+ )
44
+
45
+ from sympy.utilities.misc import filldedent
46
+
47
+
48
+ def _linsolve(eqs, syms):
49
+
50
+ """Solve a linear system of equations.
51
+
52
+ Examples
53
+ ========
54
+
55
+ Solve a linear system with a unique solution:
56
+
57
+ >>> from sympy import symbols, Eq
58
+ >>> from sympy.polys.matrices.linsolve import _linsolve
59
+ >>> x, y = symbols('x, y')
60
+ >>> eqs = [Eq(x + y, 1), Eq(x - y, 2)]
61
+ >>> _linsolve(eqs, [x, y])
62
+ {x: 3/2, y: -1/2}
63
+
64
+ In the case of underdetermined systems the solution will be expressed in
65
+ terms of the unknown symbols that are unconstrained:
66
+
67
+ >>> _linsolve([Eq(x + y, 0)], [x, y])
68
+ {x: -y, y: y}
69
+
70
+ """
71
+ # Number of unknowns (columns in the non-augmented matrix)
72
+ nsyms = len(syms)
73
+
74
+ # Convert to sparse augmented matrix (len(eqs) x (nsyms+1))
75
+ eqsdict, const = _linear_eq_to_dict(eqs, syms)
76
+ Aaug = sympy_dict_to_dm(eqsdict, const, syms)
77
+ K = Aaug.domain
78
+
79
+ # sdm_irref has issues with float matrices. This uses the ddm_rref()
80
+ # function. When sdm_rref() can handle float matrices reasonably this
81
+ # should be removed...
82
+ if K.is_RealField or K.is_ComplexField:
83
+ Aaug = Aaug.to_ddm().rref()[0].to_sdm()
84
+
85
+ # Compute reduced-row echelon form (RREF)
86
+ Arref, pivots, nzcols = sdm_irref(Aaug)
87
+
88
+ # No solution:
89
+ if pivots and pivots[-1] == nsyms:
90
+ return None
91
+
92
+ # Particular solution for non-homogeneous system:
93
+ P = sdm_particular_from_rref(Arref, nsyms+1, pivots)
94
+
95
+ # Nullspace - general solution to homogeneous system
96
+ # Note: using nsyms not nsyms+1 to ignore last column
97
+ V, nonpivots = sdm_nullspace_from_rref(Arref, K.one, nsyms, pivots, nzcols)
98
+
99
+ # Collect together terms from particular and nullspace:
100
+ sol = defaultdict(list)
101
+ for i, v in P.items():
102
+ sol[syms[i]].append(K.to_sympy(v))
103
+ for npi, Vi in zip(nonpivots, V):
104
+ sym = syms[npi]
105
+ for i, v in Vi.items():
106
+ sol[syms[i]].append(sym * K.to_sympy(v))
107
+
108
+ # Use a single call to Add for each term:
109
+ sol = {s: Add(*terms) for s, terms in sol.items()}
110
+
111
+ # Fill in the zeros:
112
+ zero = S.Zero
113
+ for s in set(syms) - set(sol):
114
+ sol[s] = zero
115
+
116
+ # All done!
117
+ return sol
118
+
119
+
120
+ def sympy_dict_to_dm(eqs_coeffs, eqs_rhs, syms):
121
+ """Convert a system of dict equations to a sparse augmented matrix"""
122
+ elems = set(eqs_rhs).union(*(e.values() for e in eqs_coeffs))
123
+ K, elems_K = construct_domain(elems, field=True, extension=True)
124
+ elem_map = dict(zip(elems, elems_K))
125
+ neqs = len(eqs_coeffs)
126
+ nsyms = len(syms)
127
+ sym2index = dict(zip(syms, range(nsyms)))
128
+ eqsdict = []
129
+ for eq, rhs in zip(eqs_coeffs, eqs_rhs):
130
+ eqdict = {sym2index[s]: elem_map[c] for s, c in eq.items()}
131
+ if rhs:
132
+ eqdict[nsyms] = -elem_map[rhs]
133
+ if eqdict:
134
+ eqsdict.append(eqdict)
135
+ sdm_aug = SDM(enumerate(eqsdict), (neqs, nsyms + 1), K)
136
+ return sdm_aug
137
+
138
+
139
+ def _linear_eq_to_dict(eqs, syms):
140
+ """Convert a system Expr/Eq equations into dict form, returning
141
+ the coefficient dictionaries and a list of syms-independent terms
142
+ from each expression in ``eqs```.
143
+
144
+ Examples
145
+ ========
146
+
147
+ >>> from sympy.polys.matrices.linsolve import _linear_eq_to_dict
148
+ >>> from sympy.abc import x
149
+ >>> _linear_eq_to_dict([2*x + 3], {x})
150
+ ([{x: 2}], [3])
151
+ """
152
+ coeffs = []
153
+ ind = []
154
+ symset = set(syms)
155
+ for i, e in enumerate(eqs):
156
+ if e.is_Equality:
157
+ coeff, terms = _lin_eq2dict(e.lhs, symset)
158
+ cR, tR = _lin_eq2dict(e.rhs, symset)
159
+ # there were no nonlinear errors so now
160
+ # cancellation is allowed
161
+ coeff -= cR
162
+ for k, v in tR.items():
163
+ if k in terms:
164
+ terms[k] -= v
165
+ else:
166
+ terms[k] = -v
167
+ # don't store coefficients of 0, however
168
+ terms = {k: v for k, v in terms.items() if v}
169
+ c, d = coeff, terms
170
+ else:
171
+ c, d = _lin_eq2dict(e, symset)
172
+ coeffs.append(d)
173
+ ind.append(c)
174
+ return coeffs, ind
175
+
176
+
177
+ def _lin_eq2dict(a, symset):
178
+ """return (c, d) where c is the sym-independent part of ``a`` and
179
+ ``d`` is an efficiently calculated dictionary mapping symbols to
180
+ their coefficients. A PolyNonlinearError is raised if non-linearity
181
+ is detected.
182
+
183
+ The values in the dictionary will be non-zero.
184
+
185
+ Examples
186
+ ========
187
+
188
+ >>> from sympy.polys.matrices.linsolve import _lin_eq2dict
189
+ >>> from sympy.abc import x, y
190
+ >>> _lin_eq2dict(x + 2*y + 3, {x, y})
191
+ (3, {x: 1, y: 2})
192
+ """
193
+ if a in symset:
194
+ return S.Zero, {a: S.One}
195
+ elif a.is_Add:
196
+ terms_list = defaultdict(list)
197
+ coeff_list = []
198
+ for ai in a.args:
199
+ ci, ti = _lin_eq2dict(ai, symset)
200
+ coeff_list.append(ci)
201
+ for mij, cij in ti.items():
202
+ terms_list[mij].append(cij)
203
+ coeff = Add(*coeff_list)
204
+ terms = {sym: Add(*coeffs) for sym, coeffs in terms_list.items()}
205
+ return coeff, terms
206
+ elif a.is_Mul:
207
+ terms = terms_coeff = None
208
+ coeff_list = []
209
+ for ai in a.args:
210
+ ci, ti = _lin_eq2dict(ai, symset)
211
+ if not ti:
212
+ coeff_list.append(ci)
213
+ elif terms is None:
214
+ terms = ti
215
+ terms_coeff = ci
216
+ else:
217
+ # since ti is not null and we already have
218
+ # a term, this is a cross term
219
+ raise PolyNonlinearError(filldedent('''
220
+ nonlinear cross-term: %s''' % a))
221
+ coeff = Mul._from_args(coeff_list)
222
+ if terms is None:
223
+ return coeff, {}
224
+ else:
225
+ terms = {sym: coeff * c for sym, c in terms.items()}
226
+ return coeff * terms_coeff, terms
227
+ elif not a.has_xfree(symset):
228
+ return a, {}
229
+ else:
230
+ raise PolyNonlinearError('nonlinear term: %s' % a)
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/lll.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from math import floor as mfloor
4
+
5
+ from sympy.polys.domains import ZZ, QQ
6
+ from sympy.polys.matrices.exceptions import DMRankError, DMShapeError, DMValueError, DMDomainError
7
+
8
+
9
+ def _ddm_lll(x, delta=QQ(3, 4), return_transform=False):
10
+ if QQ(1, 4) >= delta or delta >= QQ(1, 1):
11
+ raise DMValueError("delta must lie in range (0.25, 1)")
12
+ if x.shape[0] > x.shape[1]:
13
+ raise DMShapeError("input matrix must have shape (m, n) with m <= n")
14
+ if x.domain != ZZ:
15
+ raise DMDomainError("input matrix domain must be ZZ")
16
+ m = x.shape[0]
17
+ n = x.shape[1]
18
+ k = 1
19
+ y = x.copy()
20
+ y_star = x.zeros((m, n), QQ)
21
+ mu = x.zeros((m, m), QQ)
22
+ g_star = [QQ(0, 1) for _ in range(m)]
23
+ half = QQ(1, 2)
24
+ T = x.eye(m, ZZ) if return_transform else None
25
+ linear_dependent_error = "input matrix contains linearly dependent rows"
26
+
27
+ def closest_integer(x):
28
+ return ZZ(mfloor(x + half))
29
+
30
+ def lovasz_condition(k: int) -> bool:
31
+ return g_star[k] >= ((delta - mu[k][k - 1] ** 2) * g_star[k - 1])
32
+
33
+ def mu_small(k: int, j: int) -> bool:
34
+ return abs(mu[k][j]) <= half
35
+
36
+ def dot_rows(x, y, rows: tuple[int, int]):
37
+ return sum([x[rows[0]][z] * y[rows[1]][z] for z in range(x.shape[1])])
38
+
39
+ def reduce_row(T, mu, y, rows: tuple[int, int]):
40
+ r = closest_integer(mu[rows[0]][rows[1]])
41
+ y[rows[0]] = [y[rows[0]][z] - r * y[rows[1]][z] for z in range(n)]
42
+ mu[rows[0]][:rows[1]] = [mu[rows[0]][z] - r * mu[rows[1]][z] for z in range(rows[1])]
43
+ mu[rows[0]][rows[1]] -= r
44
+ if return_transform:
45
+ T[rows[0]] = [T[rows[0]][z] - r * T[rows[1]][z] for z in range(m)]
46
+
47
+ for i in range(m):
48
+ y_star[i] = [QQ.convert_from(z, ZZ) for z in y[i]]
49
+ for j in range(i):
50
+ row_dot = dot_rows(y, y_star, (i, j))
51
+ try:
52
+ mu[i][j] = row_dot / g_star[j]
53
+ except ZeroDivisionError:
54
+ raise DMRankError(linear_dependent_error)
55
+ y_star[i] = [y_star[i][z] - mu[i][j] * y_star[j][z] for z in range(n)]
56
+ g_star[i] = dot_rows(y_star, y_star, (i, i))
57
+ while k < m:
58
+ if not mu_small(k, k - 1):
59
+ reduce_row(T, mu, y, (k, k - 1))
60
+ if lovasz_condition(k):
61
+ for l in range(k - 2, -1, -1):
62
+ if not mu_small(k, l):
63
+ reduce_row(T, mu, y, (k, l))
64
+ k += 1
65
+ else:
66
+ nu = mu[k][k - 1]
67
+ alpha = g_star[k] + nu ** 2 * g_star[k - 1]
68
+ try:
69
+ beta = g_star[k - 1] / alpha
70
+ except ZeroDivisionError:
71
+ raise DMRankError(linear_dependent_error)
72
+ mu[k][k - 1] = nu * beta
73
+ g_star[k] = g_star[k] * beta
74
+ g_star[k - 1] = alpha
75
+ y[k], y[k - 1] = y[k - 1], y[k]
76
+ mu[k][:k - 1], mu[k - 1][:k - 1] = mu[k - 1][:k - 1], mu[k][:k - 1]
77
+ for i in range(k + 1, m):
78
+ xi = mu[i][k]
79
+ mu[i][k] = mu[i][k - 1] - nu * xi
80
+ mu[i][k - 1] = mu[k][k - 1] * mu[i][k] + xi
81
+ if return_transform:
82
+ T[k], T[k - 1] = T[k - 1], T[k]
83
+ k = max(k - 1, 1)
84
+ assert all([lovasz_condition(i) for i in range(1, m)])
85
+ assert all([mu_small(i, j) for i in range(m) for j in range(i)])
86
+ return y, T
87
+
88
+
89
+ def ddm_lll(x, delta=QQ(3, 4)):
90
+ return _ddm_lll(x, delta=delta, return_transform=False)[0]
91
+
92
+
93
+ def ddm_lll_transform(x, delta=QQ(3, 4)):
94
+ return _ddm_lll(x, delta=delta, return_transform=True)
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/normalforms.py ADDED
@@ -0,0 +1,406 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''Functions returning normal forms of matrices'''
2
+
3
+ from collections import defaultdict
4
+
5
+ from .domainmatrix import DomainMatrix
6
+ from .exceptions import DMDomainError, DMShapeError
7
+ from sympy.ntheory.modular import symmetric_residue
8
+ from sympy.polys.domains import QQ, ZZ
9
+
10
+
11
+ # TODO (future work):
12
+ # There are faster algorithms for Smith and Hermite normal forms, which
13
+ # we should implement. See e.g. the Kannan-Bachem algorithm:
14
+ # <https://www.researchgate.net/publication/220617516_Polynomial_Algorithms_for_Computing_the_Smith_and_Hermite_Normal_Forms_of_an_Integer_Matrix>
15
+
16
+
17
+ def smith_normal_form(m):
18
+ '''
19
+ Return the Smith Normal Form of a matrix `m` over the ring `domain`.
20
+ This will only work if the ring is a principal ideal domain.
21
+
22
+ Examples
23
+ ========
24
+
25
+ >>> from sympy import ZZ
26
+ >>> from sympy.polys.matrices import DomainMatrix
27
+ >>> from sympy.polys.matrices.normalforms import smith_normal_form
28
+ >>> m = DomainMatrix([[ZZ(12), ZZ(6), ZZ(4)],
29
+ ... [ZZ(3), ZZ(9), ZZ(6)],
30
+ ... [ZZ(2), ZZ(16), ZZ(14)]], (3, 3), ZZ)
31
+ >>> print(smith_normal_form(m).to_Matrix())
32
+ Matrix([[1, 0, 0], [0, 10, 0], [0, 0, -30]])
33
+
34
+ '''
35
+ invs = invariant_factors(m)
36
+ smf = DomainMatrix.diag(invs, m.domain, m.shape)
37
+ return smf
38
+
39
+
40
+ def add_columns(m, i, j, a, b, c, d):
41
+ # replace m[:, i] by a*m[:, i] + b*m[:, j]
42
+ # and m[:, j] by c*m[:, i] + d*m[:, j]
43
+ for k in range(len(m)):
44
+ e = m[k][i]
45
+ m[k][i] = a*e + b*m[k][j]
46
+ m[k][j] = c*e + d*m[k][j]
47
+
48
+
49
+ def invariant_factors(m):
50
+ '''
51
+ Return the tuple of abelian invariants for a matrix `m`
52
+ (as in the Smith-Normal form)
53
+
54
+ References
55
+ ==========
56
+
57
+ [1] https://en.wikipedia.org/wiki/Smith_normal_form#Algorithm
58
+ [2] https://web.archive.org/web/20200331143852/https://sierra.nmsu.edu/morandi/notes/SmithNormalForm.pdf
59
+
60
+ '''
61
+ domain = m.domain
62
+ if not domain.is_PID:
63
+ msg = "The matrix entries must be over a principal ideal domain"
64
+ raise ValueError(msg)
65
+
66
+ if 0 in m.shape:
67
+ return ()
68
+
69
+ rows, cols = shape = m.shape
70
+ m = list(m.to_dense().rep)
71
+
72
+ def add_rows(m, i, j, a, b, c, d):
73
+ # replace m[i, :] by a*m[i, :] + b*m[j, :]
74
+ # and m[j, :] by c*m[i, :] + d*m[j, :]
75
+ for k in range(cols):
76
+ e = m[i][k]
77
+ m[i][k] = a*e + b*m[j][k]
78
+ m[j][k] = c*e + d*m[j][k]
79
+
80
+ def clear_column(m):
81
+ # make m[1:, 0] zero by row and column operations
82
+ if m[0][0] == 0:
83
+ return m # pragma: nocover
84
+ pivot = m[0][0]
85
+ for j in range(1, rows):
86
+ if m[j][0] == 0:
87
+ continue
88
+ d, r = domain.div(m[j][0], pivot)
89
+ if r == 0:
90
+ add_rows(m, 0, j, 1, 0, -d, 1)
91
+ else:
92
+ a, b, g = domain.gcdex(pivot, m[j][0])
93
+ d_0 = domain.div(m[j][0], g)[0]
94
+ d_j = domain.div(pivot, g)[0]
95
+ add_rows(m, 0, j, a, b, d_0, -d_j)
96
+ pivot = g
97
+ return m
98
+
99
+ def clear_row(m):
100
+ # make m[0, 1:] zero by row and column operations
101
+ if m[0][0] == 0:
102
+ return m # pragma: nocover
103
+ pivot = m[0][0]
104
+ for j in range(1, cols):
105
+ if m[0][j] == 0:
106
+ continue
107
+ d, r = domain.div(m[0][j], pivot)
108
+ if r == 0:
109
+ add_columns(m, 0, j, 1, 0, -d, 1)
110
+ else:
111
+ a, b, g = domain.gcdex(pivot, m[0][j])
112
+ d_0 = domain.div(m[0][j], g)[0]
113
+ d_j = domain.div(pivot, g)[0]
114
+ add_columns(m, 0, j, a, b, d_0, -d_j)
115
+ pivot = g
116
+ return m
117
+
118
+ # permute the rows and columns until m[0,0] is non-zero if possible
119
+ ind = [i for i in range(rows) if m[i][0] != 0]
120
+ if ind and ind[0] != 0:
121
+ m[0], m[ind[0]] = m[ind[0]], m[0]
122
+ else:
123
+ ind = [j for j in range(cols) if m[0][j] != 0]
124
+ if ind and ind[0] != 0:
125
+ for row in m:
126
+ row[0], row[ind[0]] = row[ind[0]], row[0]
127
+
128
+ # make the first row and column except m[0,0] zero
129
+ while (any(m[0][i] != 0 for i in range(1,cols)) or
130
+ any(m[i][0] != 0 for i in range(1,rows))):
131
+ m = clear_column(m)
132
+ m = clear_row(m)
133
+
134
+ if 1 in shape:
135
+ invs = ()
136
+ else:
137
+ lower_right = DomainMatrix([r[1:] for r in m[1:]], (rows-1, cols-1), domain)
138
+ invs = invariant_factors(lower_right)
139
+
140
+ if m[0][0]:
141
+ result = [m[0][0]]
142
+ result.extend(invs)
143
+ # in case m[0] doesn't divide the invariants of the rest of the matrix
144
+ for i in range(len(result)-1):
145
+ if result[i] and domain.div(result[i+1], result[i])[1] != 0:
146
+ g = domain.gcd(result[i+1], result[i])
147
+ result[i+1] = domain.div(result[i], g)[0]*result[i+1]
148
+ result[i] = g
149
+ else:
150
+ break
151
+ else:
152
+ result = invs + (m[0][0],)
153
+ return tuple(result)
154
+
155
+
156
+ def _gcdex(a, b):
157
+ r"""
158
+ This supports the functions that compute Hermite Normal Form.
159
+
160
+ Explanation
161
+ ===========
162
+
163
+ Let x, y be the coefficients returned by the extended Euclidean
164
+ Algorithm, so that x*a + y*b = g. In the algorithms for computing HNF,
165
+ it is critical that x, y not only satisfy the condition of being small
166
+ in magnitude -- namely that |x| <= |b|/g, |y| <- |a|/g -- but also that
167
+ y == 0 when a | b.
168
+
169
+ """
170
+ x, y, g = ZZ.gcdex(a, b)
171
+ if a != 0 and b % a == 0:
172
+ y = 0
173
+ x = -1 if a < 0 else 1
174
+ return x, y, g
175
+
176
+
177
+ def _hermite_normal_form(A):
178
+ r"""
179
+ Compute the Hermite Normal Form of DomainMatrix *A* over :ref:`ZZ`.
180
+
181
+ Parameters
182
+ ==========
183
+
184
+ A : :py:class:`~.DomainMatrix` over domain :ref:`ZZ`.
185
+
186
+ Returns
187
+ =======
188
+
189
+ :py:class:`~.DomainMatrix`
190
+ The HNF of matrix *A*.
191
+
192
+ Raises
193
+ ======
194
+
195
+ DMDomainError
196
+ If the domain of the matrix is not :ref:`ZZ`.
197
+
198
+ References
199
+ ==========
200
+
201
+ .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.*
202
+ (See Algorithm 2.4.5.)
203
+
204
+ """
205
+ if not A.domain.is_ZZ:
206
+ raise DMDomainError('Matrix must be over domain ZZ.')
207
+ # We work one row at a time, starting from the bottom row, and working our
208
+ # way up.
209
+ m, n = A.shape
210
+ A = A.to_dense().rep.copy()
211
+ # Our goal is to put pivot entries in the rightmost columns.
212
+ # Invariant: Before processing each row, k should be the index of the
213
+ # leftmost column in which we have so far put a pivot.
214
+ k = n
215
+ for i in range(m - 1, -1, -1):
216
+ if k == 0:
217
+ # This case can arise when n < m and we've already found n pivots.
218
+ # We don't need to consider any more rows, because this is already
219
+ # the maximum possible number of pivots.
220
+ break
221
+ k -= 1
222
+ # k now points to the column in which we want to put a pivot.
223
+ # We want zeros in all entries to the left of the pivot column.
224
+ for j in range(k - 1, -1, -1):
225
+ if A[i][j] != 0:
226
+ # Replace cols j, k by lin combs of these cols such that, in row i,
227
+ # col j has 0, while col k has the gcd of their row i entries. Note
228
+ # that this ensures a nonzero entry in col k.
229
+ u, v, d = _gcdex(A[i][k], A[i][j])
230
+ r, s = A[i][k] // d, A[i][j] // d
231
+ add_columns(A, k, j, u, v, -s, r)
232
+ b = A[i][k]
233
+ # Do not want the pivot entry to be negative.
234
+ if b < 0:
235
+ add_columns(A, k, k, -1, 0, -1, 0)
236
+ b = -b
237
+ # The pivot entry will be 0 iff the row was 0 from the pivot col all the
238
+ # way to the left. In this case, we are still working on the same pivot
239
+ # col for the next row. Therefore:
240
+ if b == 0:
241
+ k += 1
242
+ # If the pivot entry is nonzero, then we want to reduce all entries to its
243
+ # right in the sense of the division algorithm, i.e. make them all remainders
244
+ # w.r.t. the pivot as divisor.
245
+ else:
246
+ for j in range(k + 1, n):
247
+ q = A[i][j] // b
248
+ add_columns(A, j, k, 1, -q, 0, 1)
249
+ # Finally, the HNF consists of those columns of A in which we succeeded in making
250
+ # a nonzero pivot.
251
+ return DomainMatrix.from_rep(A)[:, k:]
252
+
253
+
254
+ def _hermite_normal_form_modulo_D(A, D):
255
+ r"""
256
+ Perform the mod *D* Hermite Normal Form reduction algorithm on
257
+ :py:class:`~.DomainMatrix` *A*.
258
+
259
+ Explanation
260
+ ===========
261
+
262
+ If *A* is an $m \times n$ matrix of rank $m$, having Hermite Normal Form
263
+ $W$, and if *D* is any positive integer known in advance to be a multiple
264
+ of $\det(W)$, then the HNF of *A* can be computed by an algorithm that
265
+ works mod *D* in order to prevent coefficient explosion.
266
+
267
+ Parameters
268
+ ==========
269
+
270
+ A : :py:class:`~.DomainMatrix` over :ref:`ZZ`
271
+ $m \times n$ matrix, having rank $m$.
272
+ D : :ref:`ZZ`
273
+ Positive integer, known to be a multiple of the determinant of the
274
+ HNF of *A*.
275
+
276
+ Returns
277
+ =======
278
+
279
+ :py:class:`~.DomainMatrix`
280
+ The HNF of matrix *A*.
281
+
282
+ Raises
283
+ ======
284
+
285
+ DMDomainError
286
+ If the domain of the matrix is not :ref:`ZZ`, or
287
+ if *D* is given but is not in :ref:`ZZ`.
288
+
289
+ DMShapeError
290
+ If the matrix has more rows than columns.
291
+
292
+ References
293
+ ==========
294
+
295
+ .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.*
296
+ (See Algorithm 2.4.8.)
297
+
298
+ """
299
+ if not A.domain.is_ZZ:
300
+ raise DMDomainError('Matrix must be over domain ZZ.')
301
+ if not ZZ.of_type(D) or D < 1:
302
+ raise DMDomainError('Modulus D must be positive element of domain ZZ.')
303
+
304
+ def add_columns_mod_R(m, R, i, j, a, b, c, d):
305
+ # replace m[:, i] by (a*m[:, i] + b*m[:, j]) % R
306
+ # and m[:, j] by (c*m[:, i] + d*m[:, j]) % R
307
+ for k in range(len(m)):
308
+ e = m[k][i]
309
+ m[k][i] = symmetric_residue((a * e + b * m[k][j]) % R, R)
310
+ m[k][j] = symmetric_residue((c * e + d * m[k][j]) % R, R)
311
+
312
+ W = defaultdict(dict)
313
+
314
+ m, n = A.shape
315
+ if n < m:
316
+ raise DMShapeError('Matrix must have at least as many columns as rows.')
317
+ A = A.to_dense().rep.copy()
318
+ k = n
319
+ R = D
320
+ for i in range(m - 1, -1, -1):
321
+ k -= 1
322
+ for j in range(k - 1, -1, -1):
323
+ if A[i][j] != 0:
324
+ u, v, d = _gcdex(A[i][k], A[i][j])
325
+ r, s = A[i][k] // d, A[i][j] // d
326
+ add_columns_mod_R(A, R, k, j, u, v, -s, r)
327
+ b = A[i][k]
328
+ if b == 0:
329
+ A[i][k] = b = R
330
+ u, v, d = _gcdex(b, R)
331
+ for ii in range(m):
332
+ W[ii][i] = u*A[ii][k] % R
333
+ if W[i][i] == 0:
334
+ W[i][i] = R
335
+ for j in range(i + 1, m):
336
+ q = W[i][j] // W[i][i]
337
+ add_columns(W, j, i, 1, -q, 0, 1)
338
+ R //= d
339
+ return DomainMatrix(W, (m, m), ZZ).to_dense()
340
+
341
+
342
+ def hermite_normal_form(A, *, D=None, check_rank=False):
343
+ r"""
344
+ Compute the Hermite Normal Form of :py:class:`~.DomainMatrix` *A* over
345
+ :ref:`ZZ`.
346
+
347
+ Examples
348
+ ========
349
+
350
+ >>> from sympy import ZZ
351
+ >>> from sympy.polys.matrices import DomainMatrix
352
+ >>> from sympy.polys.matrices.normalforms import hermite_normal_form
353
+ >>> m = DomainMatrix([[ZZ(12), ZZ(6), ZZ(4)],
354
+ ... [ZZ(3), ZZ(9), ZZ(6)],
355
+ ... [ZZ(2), ZZ(16), ZZ(14)]], (3, 3), ZZ)
356
+ >>> print(hermite_normal_form(m).to_Matrix())
357
+ Matrix([[10, 0, 2], [0, 15, 3], [0, 0, 2]])
358
+
359
+ Parameters
360
+ ==========
361
+
362
+ A : $m \times n$ ``DomainMatrix`` over :ref:`ZZ`.
363
+
364
+ D : :ref:`ZZ`, optional
365
+ Let $W$ be the HNF of *A*. If known in advance, a positive integer *D*
366
+ being any multiple of $\det(W)$ may be provided. In this case, if *A*
367
+ also has rank $m$, then we may use an alternative algorithm that works
368
+ mod *D* in order to prevent coefficient explosion.
369
+
370
+ check_rank : boolean, optional (default=False)
371
+ The basic assumption is that, if you pass a value for *D*, then
372
+ you already believe that *A* has rank $m$, so we do not waste time
373
+ checking it for you. If you do want this to be checked (and the
374
+ ordinary, non-modulo *D* algorithm to be used if the check fails), then
375
+ set *check_rank* to ``True``.
376
+
377
+ Returns
378
+ =======
379
+
380
+ :py:class:`~.DomainMatrix`
381
+ The HNF of matrix *A*.
382
+
383
+ Raises
384
+ ======
385
+
386
+ DMDomainError
387
+ If the domain of the matrix is not :ref:`ZZ`, or
388
+ if *D* is given but is not in :ref:`ZZ`.
389
+
390
+ DMShapeError
391
+ If the mod *D* algorithm is used but the matrix has more rows than
392
+ columns.
393
+
394
+ References
395
+ ==========
396
+
397
+ .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.*
398
+ (See Algorithms 2.4.5 and 2.4.8.)
399
+
400
+ """
401
+ if not A.domain.is_ZZ:
402
+ raise DMDomainError('Matrix must be over domain ZZ.')
403
+ if D is not None and (not check_rank or A.convert_to(QQ).rank() == A.shape[0]):
404
+ return _hermite_normal_form_modulo_D(A, D)
405
+ else:
406
+ return _hermite_normal_form(A)
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/sdm.py ADDED
@@ -0,0 +1,1241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+
3
+ Module for the SDM class.
4
+
5
+ """
6
+
7
+ from operator import add, neg, pos, sub, mul
8
+ from collections import defaultdict
9
+
10
+ from sympy.utilities.iterables import _strongly_connected_components
11
+
12
+ from .exceptions import DMBadInputError, DMDomainError, DMShapeError
13
+
14
+ from .ddm import DDM
15
+ from .lll import ddm_lll, ddm_lll_transform
16
+ from sympy.polys.domains import QQ
17
+
18
+
19
+ class SDM(dict):
20
+ r"""Sparse matrix based on polys domain elements
21
+
22
+ This is a dict subclass and is a wrapper for a dict of dicts that supports
23
+ basic matrix arithmetic +, -, *, **.
24
+
25
+
26
+ In order to create a new :py:class:`~.SDM`, a dict
27
+ of dicts mapping non-zero elements to their
28
+ corresponding row and column in the matrix is needed.
29
+
30
+ We also need to specify the shape and :py:class:`~.Domain`
31
+ of our :py:class:`~.SDM` object.
32
+
33
+ We declare a 2x2 :py:class:`~.SDM` matrix belonging
34
+ to QQ domain as shown below.
35
+ The 2x2 Matrix in the example is
36
+
37
+ .. math::
38
+ A = \left[\begin{array}{ccc}
39
+ 0 & \frac{1}{2} \\
40
+ 0 & 0 \end{array} \right]
41
+
42
+
43
+ >>> from sympy.polys.matrices.sdm import SDM
44
+ >>> from sympy import QQ
45
+ >>> elemsdict = {0:{1:QQ(1, 2)}}
46
+ >>> A = SDM(elemsdict, (2, 2), QQ)
47
+ >>> A
48
+ {0: {1: 1/2}}
49
+
50
+ We can manipulate :py:class:`~.SDM` the same way
51
+ as a Matrix class
52
+
53
+ >>> from sympy import ZZ
54
+ >>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ)
55
+ >>> B = SDM({0:{0: ZZ(3)}, 1:{1:ZZ(4)}}, (2, 2), ZZ)
56
+ >>> A + B
57
+ {0: {0: 3, 1: 2}, 1: {0: 1, 1: 4}}
58
+
59
+ Multiplication
60
+
61
+ >>> A*B
62
+ {0: {1: 8}, 1: {0: 3}}
63
+ >>> A*ZZ(2)
64
+ {0: {1: 4}, 1: {0: 2}}
65
+
66
+ """
67
+
68
+ fmt = 'sparse'
69
+
70
+ def __init__(self, elemsdict, shape, domain):
71
+ super().__init__(elemsdict)
72
+ self.shape = self.rows, self.cols = m, n = shape
73
+ self.domain = domain
74
+
75
+ if not all(0 <= r < m for r in self):
76
+ raise DMBadInputError("Row out of range")
77
+ if not all(0 <= c < n for row in self.values() for c in row):
78
+ raise DMBadInputError("Column out of range")
79
+
80
+ def getitem(self, i, j):
81
+ try:
82
+ return self[i][j]
83
+ except KeyError:
84
+ m, n = self.shape
85
+ if -m <= i < m and -n <= j < n:
86
+ try:
87
+ return self[i % m][j % n]
88
+ except KeyError:
89
+ return self.domain.zero
90
+ else:
91
+ raise IndexError("index out of range")
92
+
93
+ def setitem(self, i, j, value):
94
+ m, n = self.shape
95
+ if not (-m <= i < m and -n <= j < n):
96
+ raise IndexError("index out of range")
97
+ i, j = i % m, j % n
98
+ if value:
99
+ try:
100
+ self[i][j] = value
101
+ except KeyError:
102
+ self[i] = {j: value}
103
+ else:
104
+ rowi = self.get(i, None)
105
+ if rowi is not None:
106
+ try:
107
+ del rowi[j]
108
+ except KeyError:
109
+ pass
110
+ else:
111
+ if not rowi:
112
+ del self[i]
113
+
114
+ def extract_slice(self, slice1, slice2):
115
+ m, n = self.shape
116
+ ri = range(m)[slice1]
117
+ ci = range(n)[slice2]
118
+
119
+ sdm = {}
120
+ for i, row in self.items():
121
+ if i in ri:
122
+ row = {ci.index(j): e for j, e in row.items() if j in ci}
123
+ if row:
124
+ sdm[ri.index(i)] = row
125
+
126
+ return self.new(sdm, (len(ri), len(ci)), self.domain)
127
+
128
+ def extract(self, rows, cols):
129
+ if not (self and rows and cols):
130
+ return self.zeros((len(rows), len(cols)), self.domain)
131
+
132
+ m, n = self.shape
133
+ if not (-m <= min(rows) <= max(rows) < m):
134
+ raise IndexError('Row index out of range')
135
+ if not (-n <= min(cols) <= max(cols) < n):
136
+ raise IndexError('Column index out of range')
137
+
138
+ # rows and cols can contain duplicates e.g. M[[1, 2, 2], [0, 1]]
139
+ # Build a map from row/col in self to list of rows/cols in output
140
+ rowmap = defaultdict(list)
141
+ colmap = defaultdict(list)
142
+ for i2, i1 in enumerate(rows):
143
+ rowmap[i1 % m].append(i2)
144
+ for j2, j1 in enumerate(cols):
145
+ colmap[j1 % n].append(j2)
146
+
147
+ # Used to efficiently skip zero rows/cols
148
+ rowset = set(rowmap)
149
+ colset = set(colmap)
150
+
151
+ sdm1 = self
152
+ sdm2 = {}
153
+ for i1 in rowset & set(sdm1):
154
+ row1 = sdm1[i1]
155
+ row2 = {}
156
+ for j1 in colset & set(row1):
157
+ row1_j1 = row1[j1]
158
+ for j2 in colmap[j1]:
159
+ row2[j2] = row1_j1
160
+ if row2:
161
+ for i2 in rowmap[i1]:
162
+ sdm2[i2] = row2.copy()
163
+
164
+ return self.new(sdm2, (len(rows), len(cols)), self.domain)
165
+
166
+ def __str__(self):
167
+ rowsstr = []
168
+ for i, row in self.items():
169
+ elemsstr = ', '.join('%s: %s' % (j, elem) for j, elem in row.items())
170
+ rowsstr.append('%s: {%s}' % (i, elemsstr))
171
+ return '{%s}' % ', '.join(rowsstr)
172
+
173
+ def __repr__(self):
174
+ cls = type(self).__name__
175
+ rows = dict.__repr__(self)
176
+ return '%s(%s, %s, %s)' % (cls, rows, self.shape, self.domain)
177
+
178
+ @classmethod
179
+ def new(cls, sdm, shape, domain):
180
+ """
181
+
182
+ Parameters
183
+ ==========
184
+
185
+ sdm: A dict of dicts for non-zero elements in SDM
186
+ shape: tuple representing dimension of SDM
187
+ domain: Represents :py:class:`~.Domain` of SDM
188
+
189
+ Returns
190
+ =======
191
+
192
+ An :py:class:`~.SDM` object
193
+
194
+ Examples
195
+ ========
196
+
197
+ >>> from sympy.polys.matrices.sdm import SDM
198
+ >>> from sympy import QQ
199
+ >>> elemsdict = {0:{1: QQ(2)}}
200
+ >>> A = SDM.new(elemsdict, (2, 2), QQ)
201
+ >>> A
202
+ {0: {1: 2}}
203
+
204
+ """
205
+ return cls(sdm, shape, domain)
206
+
207
+ def copy(A):
208
+ """
209
+ Returns the copy of a :py:class:`~.SDM` object
210
+
211
+ Examples
212
+ ========
213
+
214
+ >>> from sympy.polys.matrices.sdm import SDM
215
+ >>> from sympy import QQ
216
+ >>> elemsdict = {0:{1:QQ(2)}, 1:{}}
217
+ >>> A = SDM(elemsdict, (2, 2), QQ)
218
+ >>> B = A.copy()
219
+ >>> B
220
+ {0: {1: 2}, 1: {}}
221
+
222
+ """
223
+ Ac = {i: Ai.copy() for i, Ai in A.items()}
224
+ return A.new(Ac, A.shape, A.domain)
225
+
226
+ @classmethod
227
+ def from_list(cls, ddm, shape, domain):
228
+ """
229
+
230
+ Parameters
231
+ ==========
232
+
233
+ ddm:
234
+ list of lists containing domain elements
235
+ shape:
236
+ Dimensions of :py:class:`~.SDM` matrix
237
+ domain:
238
+ Represents :py:class:`~.Domain` of :py:class:`~.SDM` object
239
+
240
+ Returns
241
+ =======
242
+
243
+ :py:class:`~.SDM` containing elements of ddm
244
+
245
+ Examples
246
+ ========
247
+
248
+ >>> from sympy.polys.matrices.sdm import SDM
249
+ >>> from sympy import QQ
250
+ >>> ddm = [[QQ(1, 2), QQ(0)], [QQ(0), QQ(3, 4)]]
251
+ >>> A = SDM.from_list(ddm, (2, 2), QQ)
252
+ >>> A
253
+ {0: {0: 1/2}, 1: {1: 3/4}}
254
+
255
+ """
256
+
257
+ m, n = shape
258
+ if not (len(ddm) == m and all(len(row) == n for row in ddm)):
259
+ raise DMBadInputError("Inconsistent row-list/shape")
260
+ getrow = lambda i: {j:ddm[i][j] for j in range(n) if ddm[i][j]}
261
+ irows = ((i, getrow(i)) for i in range(m))
262
+ sdm = {i: row for i, row in irows if row}
263
+ return cls(sdm, shape, domain)
264
+
265
+ @classmethod
266
+ def from_ddm(cls, ddm):
267
+ """
268
+ converts object of :py:class:`~.DDM` to
269
+ :py:class:`~.SDM`
270
+
271
+ Examples
272
+ ========
273
+
274
+ >>> from sympy.polys.matrices.ddm import DDM
275
+ >>> from sympy.polys.matrices.sdm import SDM
276
+ >>> from sympy import QQ
277
+ >>> ddm = DDM( [[QQ(1, 2), 0], [0, QQ(3, 4)]], (2, 2), QQ)
278
+ >>> A = SDM.from_ddm(ddm)
279
+ >>> A
280
+ {0: {0: 1/2}, 1: {1: 3/4}}
281
+
282
+ """
283
+ return cls.from_list(ddm, ddm.shape, ddm.domain)
284
+
285
+ def to_list(M):
286
+ """
287
+
288
+ Converts a :py:class:`~.SDM` object to a list
289
+
290
+ Examples
291
+ ========
292
+
293
+ >>> from sympy.polys.matrices.sdm import SDM
294
+ >>> from sympy import QQ
295
+ >>> elemsdict = {0:{1:QQ(2)}, 1:{}}
296
+ >>> A = SDM(elemsdict, (2, 2), QQ)
297
+ >>> A.to_list()
298
+ [[0, 2], [0, 0]]
299
+
300
+ """
301
+ m, n = M.shape
302
+ zero = M.domain.zero
303
+ ddm = [[zero] * n for _ in range(m)]
304
+ for i, row in M.items():
305
+ for j, e in row.items():
306
+ ddm[i][j] = e
307
+ return ddm
308
+
309
+ def to_list_flat(M):
310
+ m, n = M.shape
311
+ zero = M.domain.zero
312
+ flat = [zero] * (m * n)
313
+ for i, row in M.items():
314
+ for j, e in row.items():
315
+ flat[i*n + j] = e
316
+ return flat
317
+
318
+ def to_dok(M):
319
+ return {(i, j): e for i, row in M.items() for j, e in row.items()}
320
+
321
+ def to_ddm(M):
322
+ """
323
+ Convert a :py:class:`~.SDM` object to a :py:class:`~.DDM` object
324
+
325
+ Examples
326
+ ========
327
+
328
+ >>> from sympy.polys.matrices.sdm import SDM
329
+ >>> from sympy import QQ
330
+ >>> A = SDM({0:{1:QQ(2)}, 1:{}}, (2, 2), QQ)
331
+ >>> A.to_ddm()
332
+ [[0, 2], [0, 0]]
333
+
334
+ """
335
+ return DDM(M.to_list(), M.shape, M.domain)
336
+
337
+ def to_sdm(M):
338
+ return M
339
+
340
+ @classmethod
341
+ def zeros(cls, shape, domain):
342
+ r"""
343
+
344
+ Returns a :py:class:`~.SDM` of size shape,
345
+ belonging to the specified domain
346
+
347
+ In the example below we declare a matrix A where,
348
+
349
+ .. math::
350
+ A := \left[\begin{array}{ccc}
351
+ 0 & 0 & 0 \\
352
+ 0 & 0 & 0 \end{array} \right]
353
+
354
+ >>> from sympy.polys.matrices.sdm import SDM
355
+ >>> from sympy import QQ
356
+ >>> A = SDM.zeros((2, 3), QQ)
357
+ >>> A
358
+ {}
359
+
360
+ """
361
+ return cls({}, shape, domain)
362
+
363
+ @classmethod
364
+ def ones(cls, shape, domain):
365
+ one = domain.one
366
+ m, n = shape
367
+ row = dict(zip(range(n), [one]*n))
368
+ sdm = {i: row.copy() for i in range(m)}
369
+ return cls(sdm, shape, domain)
370
+
371
+ @classmethod
372
+ def eye(cls, shape, domain):
373
+ """
374
+
375
+ Returns a identity :py:class:`~.SDM` matrix of dimensions
376
+ size x size, belonging to the specified domain
377
+
378
+ Examples
379
+ ========
380
+
381
+ >>> from sympy.polys.matrices.sdm import SDM
382
+ >>> from sympy import QQ
383
+ >>> I = SDM.eye((2, 2), QQ)
384
+ >>> I
385
+ {0: {0: 1}, 1: {1: 1}}
386
+
387
+ """
388
+ rows, cols = shape
389
+ one = domain.one
390
+ sdm = {i: {i: one} for i in range(min(rows, cols))}
391
+ return cls(sdm, shape, domain)
392
+
393
+ @classmethod
394
+ def diag(cls, diagonal, domain, shape):
395
+ sdm = {i: {i: v} for i, v in enumerate(diagonal) if v}
396
+ return cls(sdm, shape, domain)
397
+
398
+ def transpose(M):
399
+ """
400
+
401
+ Returns the transpose of a :py:class:`~.SDM` matrix
402
+
403
+ Examples
404
+ ========
405
+
406
+ >>> from sympy.polys.matrices.sdm import SDM
407
+ >>> from sympy import QQ
408
+ >>> A = SDM({0:{1:QQ(2)}, 1:{}}, (2, 2), QQ)
409
+ >>> A.transpose()
410
+ {1: {0: 2}}
411
+
412
+ """
413
+ MT = sdm_transpose(M)
414
+ return M.new(MT, M.shape[::-1], M.domain)
415
+
416
+ def __add__(A, B):
417
+ if not isinstance(B, SDM):
418
+ return NotImplemented
419
+ return A.add(B)
420
+
421
+ def __sub__(A, B):
422
+ if not isinstance(B, SDM):
423
+ return NotImplemented
424
+ return A.sub(B)
425
+
426
+ def __neg__(A):
427
+ return A.neg()
428
+
429
+ def __mul__(A, B):
430
+ """A * B"""
431
+ if isinstance(B, SDM):
432
+ return A.matmul(B)
433
+ elif B in A.domain:
434
+ return A.mul(B)
435
+ else:
436
+ return NotImplemented
437
+
438
+ def __rmul__(a, b):
439
+ if b in a.domain:
440
+ return a.rmul(b)
441
+ else:
442
+ return NotImplemented
443
+
444
+ def matmul(A, B):
445
+ """
446
+ Performs matrix multiplication of two SDM matrices
447
+
448
+ Parameters
449
+ ==========
450
+
451
+ A, B: SDM to multiply
452
+
453
+ Returns
454
+ =======
455
+
456
+ SDM
457
+ SDM after multiplication
458
+
459
+ Raises
460
+ ======
461
+
462
+ DomainError
463
+ If domain of A does not match
464
+ with that of B
465
+
466
+ Examples
467
+ ========
468
+
469
+ >>> from sympy import ZZ
470
+ >>> from sympy.polys.matrices.sdm import SDM
471
+ >>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ)
472
+ >>> B = SDM({0:{0:ZZ(2), 1:ZZ(3)}, 1:{0:ZZ(4)}}, (2, 2), ZZ)
473
+ >>> A.matmul(B)
474
+ {0: {0: 8}, 1: {0: 2, 1: 3}}
475
+
476
+ """
477
+ if A.domain != B.domain:
478
+ raise DMDomainError
479
+ m, n = A.shape
480
+ n2, o = B.shape
481
+ if n != n2:
482
+ raise DMShapeError
483
+ C = sdm_matmul(A, B, A.domain, m, o)
484
+ return A.new(C, (m, o), A.domain)
485
+
486
+ def mul(A, b):
487
+ """
488
+ Multiplies each element of A with a scalar b
489
+
490
+ Examples
491
+ ========
492
+
493
+ >>> from sympy import ZZ
494
+ >>> from sympy.polys.matrices.sdm import SDM
495
+ >>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ)
496
+ >>> A.mul(ZZ(3))
497
+ {0: {1: 6}, 1: {0: 3}}
498
+
499
+ """
500
+ Csdm = unop_dict(A, lambda aij: aij*b)
501
+ return A.new(Csdm, A.shape, A.domain)
502
+
503
+ def rmul(A, b):
504
+ Csdm = unop_dict(A, lambda aij: b*aij)
505
+ return A.new(Csdm, A.shape, A.domain)
506
+
507
+ def mul_elementwise(A, B):
508
+ if A.domain != B.domain:
509
+ raise DMDomainError
510
+ if A.shape != B.shape:
511
+ raise DMShapeError
512
+ zero = A.domain.zero
513
+ fzero = lambda e: zero
514
+ Csdm = binop_dict(A, B, mul, fzero, fzero)
515
+ return A.new(Csdm, A.shape, A.domain)
516
+
517
+ def add(A, B):
518
+ """
519
+
520
+ Adds two :py:class:`~.SDM` matrices
521
+
522
+ Examples
523
+ ========
524
+
525
+ >>> from sympy import ZZ
526
+ >>> from sympy.polys.matrices.sdm import SDM
527
+ >>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ)
528
+ >>> B = SDM({0:{0: ZZ(3)}, 1:{1:ZZ(4)}}, (2, 2), ZZ)
529
+ >>> A.add(B)
530
+ {0: {0: 3, 1: 2}, 1: {0: 1, 1: 4}}
531
+
532
+ """
533
+
534
+ Csdm = binop_dict(A, B, add, pos, pos)
535
+ return A.new(Csdm, A.shape, A.domain)
536
+
537
+ def sub(A, B):
538
+ """
539
+
540
+ Subtracts two :py:class:`~.SDM` matrices
541
+
542
+ Examples
543
+ ========
544
+
545
+ >>> from sympy import ZZ
546
+ >>> from sympy.polys.matrices.sdm import SDM
547
+ >>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ)
548
+ >>> B = SDM({0:{0: ZZ(3)}, 1:{1:ZZ(4)}}, (2, 2), ZZ)
549
+ >>> A.sub(B)
550
+ {0: {0: -3, 1: 2}, 1: {0: 1, 1: -4}}
551
+
552
+ """
553
+ Csdm = binop_dict(A, B, sub, pos, neg)
554
+ return A.new(Csdm, A.shape, A.domain)
555
+
556
+ def neg(A):
557
+ """
558
+
559
+ Returns the negative of a :py:class:`~.SDM` matrix
560
+
561
+ Examples
562
+ ========
563
+
564
+ >>> from sympy import ZZ
565
+ >>> from sympy.polys.matrices.sdm import SDM
566
+ >>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ)
567
+ >>> A.neg()
568
+ {0: {1: -2}, 1: {0: -1}}
569
+
570
+ """
571
+ Csdm = unop_dict(A, neg)
572
+ return A.new(Csdm, A.shape, A.domain)
573
+
574
+ def convert_to(A, K):
575
+ """
576
+
577
+ Converts the :py:class:`~.Domain` of a :py:class:`~.SDM` matrix to K
578
+
579
+ Examples
580
+ ========
581
+
582
+ >>> from sympy import ZZ, QQ
583
+ >>> from sympy.polys.matrices.sdm import SDM
584
+ >>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ)
585
+ >>> A.convert_to(QQ)
586
+ {0: {1: 2}, 1: {0: 1}}
587
+
588
+ """
589
+ Kold = A.domain
590
+ if K == Kold:
591
+ return A.copy()
592
+ Ak = unop_dict(A, lambda e: K.convert_from(e, Kold))
593
+ return A.new(Ak, A.shape, K)
594
+
595
+ def scc(A):
596
+ """Strongly connected components of a square matrix *A*.
597
+
598
+ Examples
599
+ ========
600
+
601
+ >>> from sympy import ZZ
602
+ >>> from sympy.polys.matrices.sdm import SDM
603
+ >>> A = SDM({0:{0: ZZ(2)}, 1:{1:ZZ(1)}}, (2, 2), ZZ)
604
+ >>> A.scc()
605
+ [[0], [1]]
606
+
607
+ See also
608
+ ========
609
+
610
+ sympy.polys.matrices.domainmatrix.DomainMatrix.scc
611
+ """
612
+ rows, cols = A.shape
613
+ assert rows == cols
614
+ V = range(rows)
615
+ Emap = {v: list(A.get(v, [])) for v in V}
616
+ return _strongly_connected_components(V, Emap)
617
+
618
+ def rref(A):
619
+ """
620
+
621
+ Returns reduced-row echelon form and list of pivots for the :py:class:`~.SDM`
622
+
623
+ Examples
624
+ ========
625
+
626
+ >>> from sympy import QQ
627
+ >>> from sympy.polys.matrices.sdm import SDM
628
+ >>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(2), 1:QQ(4)}}, (2, 2), QQ)
629
+ >>> A.rref()
630
+ ({0: {0: 1, 1: 2}}, [0])
631
+
632
+ """
633
+ B, pivots, _ = sdm_irref(A)
634
+ return A.new(B, A.shape, A.domain), pivots
635
+
636
+ def inv(A):
637
+ """
638
+
639
+ Returns inverse of a matrix A
640
+
641
+ Examples
642
+ ========
643
+
644
+ >>> from sympy import QQ
645
+ >>> from sympy.polys.matrices.sdm import SDM
646
+ >>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ)
647
+ >>> A.inv()
648
+ {0: {0: -2, 1: 1}, 1: {0: 3/2, 1: -1/2}}
649
+
650
+ """
651
+ return A.from_ddm(A.to_ddm().inv())
652
+
653
+ def det(A):
654
+ """
655
+ Returns determinant of A
656
+
657
+ Examples
658
+ ========
659
+
660
+ >>> from sympy import QQ
661
+ >>> from sympy.polys.matrices.sdm import SDM
662
+ >>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ)
663
+ >>> A.det()
664
+ -2
665
+
666
+ """
667
+ return A.to_ddm().det()
668
+
669
+ def lu(A):
670
+ """
671
+
672
+ Returns LU decomposition for a matrix A
673
+
674
+ Examples
675
+ ========
676
+
677
+ >>> from sympy import QQ
678
+ >>> from sympy.polys.matrices.sdm import SDM
679
+ >>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ)
680
+ >>> A.lu()
681
+ ({0: {0: 1}, 1: {0: 3, 1: 1}}, {0: {0: 1, 1: 2}, 1: {1: -2}}, [])
682
+
683
+ """
684
+ L, U, swaps = A.to_ddm().lu()
685
+ return A.from_ddm(L), A.from_ddm(U), swaps
686
+
687
+ def lu_solve(A, b):
688
+ """
689
+
690
+ Uses LU decomposition to solve Ax = b,
691
+
692
+ Examples
693
+ ========
694
+
695
+ >>> from sympy import QQ
696
+ >>> from sympy.polys.matrices.sdm import SDM
697
+ >>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ)
698
+ >>> b = SDM({0:{0:QQ(1)}, 1:{0:QQ(2)}}, (2, 1), QQ)
699
+ >>> A.lu_solve(b)
700
+ {1: {0: 1/2}}
701
+
702
+ """
703
+ return A.from_ddm(A.to_ddm().lu_solve(b.to_ddm()))
704
+
705
+ def nullspace(A):
706
+ """
707
+
708
+ Returns nullspace for a :py:class:`~.SDM` matrix A
709
+
710
+ Examples
711
+ ========
712
+
713
+ >>> from sympy import QQ
714
+ >>> from sympy.polys.matrices.sdm import SDM
715
+ >>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0: QQ(2), 1: QQ(4)}}, (2, 2), QQ)
716
+ >>> A.nullspace()
717
+ ({0: {0: -2, 1: 1}}, [1])
718
+
719
+ """
720
+ ncols = A.shape[1]
721
+ one = A.domain.one
722
+ B, pivots, nzcols = sdm_irref(A)
723
+ K, nonpivots = sdm_nullspace_from_rref(B, one, ncols, pivots, nzcols)
724
+ K = dict(enumerate(K))
725
+ shape = (len(K), ncols)
726
+ return A.new(K, shape, A.domain), nonpivots
727
+
728
+ def particular(A):
729
+ ncols = A.shape[1]
730
+ B, pivots, nzcols = sdm_irref(A)
731
+ P = sdm_particular_from_rref(B, ncols, pivots)
732
+ rep = {0:P} if P else {}
733
+ return A.new(rep, (1, ncols-1), A.domain)
734
+
735
+ def hstack(A, *B):
736
+ """Horizontally stacks :py:class:`~.SDM` matrices.
737
+
738
+ Examples
739
+ ========
740
+
741
+ >>> from sympy import ZZ
742
+ >>> from sympy.polys.matrices.sdm import SDM
743
+
744
+ >>> A = SDM({0: {0: ZZ(1), 1: ZZ(2)}, 1: {0: ZZ(3), 1: ZZ(4)}}, (2, 2), ZZ)
745
+ >>> B = SDM({0: {0: ZZ(5), 1: ZZ(6)}, 1: {0: ZZ(7), 1: ZZ(8)}}, (2, 2), ZZ)
746
+ >>> A.hstack(B)
747
+ {0: {0: 1, 1: 2, 2: 5, 3: 6}, 1: {0: 3, 1: 4, 2: 7, 3: 8}}
748
+
749
+ >>> C = SDM({0: {0: ZZ(9), 1: ZZ(10)}, 1: {0: ZZ(11), 1: ZZ(12)}}, (2, 2), ZZ)
750
+ >>> A.hstack(B, C)
751
+ {0: {0: 1, 1: 2, 2: 5, 3: 6, 4: 9, 5: 10}, 1: {0: 3, 1: 4, 2: 7, 3: 8, 4: 11, 5: 12}}
752
+ """
753
+ Anew = dict(A.copy())
754
+ rows, cols = A.shape
755
+ domain = A.domain
756
+
757
+ for Bk in B:
758
+ Bkrows, Bkcols = Bk.shape
759
+ assert Bkrows == rows
760
+ assert Bk.domain == domain
761
+
762
+ for i, Bki in Bk.items():
763
+ Ai = Anew.get(i, None)
764
+ if Ai is None:
765
+ Anew[i] = Ai = {}
766
+ for j, Bkij in Bki.items():
767
+ Ai[j + cols] = Bkij
768
+ cols += Bkcols
769
+
770
+ return A.new(Anew, (rows, cols), A.domain)
771
+
772
+ def vstack(A, *B):
773
+ """Vertically stacks :py:class:`~.SDM` matrices.
774
+
775
+ Examples
776
+ ========
777
+
778
+ >>> from sympy import ZZ
779
+ >>> from sympy.polys.matrices.sdm import SDM
780
+
781
+ >>> A = SDM({0: {0: ZZ(1), 1: ZZ(2)}, 1: {0: ZZ(3), 1: ZZ(4)}}, (2, 2), ZZ)
782
+ >>> B = SDM({0: {0: ZZ(5), 1: ZZ(6)}, 1: {0: ZZ(7), 1: ZZ(8)}}, (2, 2), ZZ)
783
+ >>> A.vstack(B)
784
+ {0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}, 2: {0: 5, 1: 6}, 3: {0: 7, 1: 8}}
785
+
786
+ >>> C = SDM({0: {0: ZZ(9), 1: ZZ(10)}, 1: {0: ZZ(11), 1: ZZ(12)}}, (2, 2), ZZ)
787
+ >>> A.vstack(B, C)
788
+ {0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}, 2: {0: 5, 1: 6}, 3: {0: 7, 1: 8}, 4: {0: 9, 1: 10}, 5: {0: 11, 1: 12}}
789
+ """
790
+ Anew = dict(A.copy())
791
+ rows, cols = A.shape
792
+ domain = A.domain
793
+
794
+ for Bk in B:
795
+ Bkrows, Bkcols = Bk.shape
796
+ assert Bkcols == cols
797
+ assert Bk.domain == domain
798
+
799
+ for i, Bki in Bk.items():
800
+ Anew[i + rows] = Bki
801
+ rows += Bkrows
802
+
803
+ return A.new(Anew, (rows, cols), A.domain)
804
+
805
+ def applyfunc(self, func, domain):
806
+ sdm = {i: {j: func(e) for j, e in row.items()} for i, row in self.items()}
807
+ return self.new(sdm, self.shape, domain)
808
+
809
+ def charpoly(A):
810
+ """
811
+ Returns the coefficients of the characteristic polynomial
812
+ of the :py:class:`~.SDM` matrix. These elements will be domain elements.
813
+ The domain of the elements will be same as domain of the :py:class:`~.SDM`.
814
+
815
+ Examples
816
+ ========
817
+
818
+ >>> from sympy import QQ, Symbol
819
+ >>> from sympy.polys.matrices.sdm import SDM
820
+ >>> from sympy.polys import Poly
821
+ >>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ)
822
+ >>> A.charpoly()
823
+ [1, -5, -2]
824
+
825
+ We can create a polynomial using the
826
+ coefficients using :py:class:`~.Poly`
827
+
828
+ >>> x = Symbol('x')
829
+ >>> p = Poly(A.charpoly(), x, domain=A.domain)
830
+ >>> p
831
+ Poly(x**2 - 5*x - 2, x, domain='QQ')
832
+
833
+ """
834
+ return A.to_ddm().charpoly()
835
+
836
+ def is_zero_matrix(self):
837
+ """
838
+ Says whether this matrix has all zero entries.
839
+ """
840
+ return not self
841
+
842
+ def is_upper(self):
843
+ """
844
+ Says whether this matrix is upper-triangular. True can be returned
845
+ even if the matrix is not square.
846
+ """
847
+ return all(i <= j for i, row in self.items() for j in row)
848
+
849
+ def is_lower(self):
850
+ """
851
+ Says whether this matrix is lower-triangular. True can be returned
852
+ even if the matrix is not square.
853
+ """
854
+ return all(i >= j for i, row in self.items() for j in row)
855
+
856
+ def lll(A, delta=QQ(3, 4)):
857
+ return A.from_ddm(ddm_lll(A.to_ddm(), delta=delta))
858
+
859
+ def lll_transform(A, delta=QQ(3, 4)):
860
+ reduced, transform = ddm_lll_transform(A.to_ddm(), delta=delta)
861
+ return A.from_ddm(reduced), A.from_ddm(transform)
862
+
863
+
864
+ def binop_dict(A, B, fab, fa, fb):
865
+ Anz, Bnz = set(A), set(B)
866
+ C = {}
867
+
868
+ for i in Anz & Bnz:
869
+ Ai, Bi = A[i], B[i]
870
+ Ci = {}
871
+ Anzi, Bnzi = set(Ai), set(Bi)
872
+ for j in Anzi & Bnzi:
873
+ Cij = fab(Ai[j], Bi[j])
874
+ if Cij:
875
+ Ci[j] = Cij
876
+ for j in Anzi - Bnzi:
877
+ Cij = fa(Ai[j])
878
+ if Cij:
879
+ Ci[j] = Cij
880
+ for j in Bnzi - Anzi:
881
+ Cij = fb(Bi[j])
882
+ if Cij:
883
+ Ci[j] = Cij
884
+ if Ci:
885
+ C[i] = Ci
886
+
887
+ for i in Anz - Bnz:
888
+ Ai = A[i]
889
+ Ci = {}
890
+ for j, Aij in Ai.items():
891
+ Cij = fa(Aij)
892
+ if Cij:
893
+ Ci[j] = Cij
894
+ if Ci:
895
+ C[i] = Ci
896
+
897
+ for i in Bnz - Anz:
898
+ Bi = B[i]
899
+ Ci = {}
900
+ for j, Bij in Bi.items():
901
+ Cij = fb(Bij)
902
+ if Cij:
903
+ Ci[j] = Cij
904
+ if Ci:
905
+ C[i] = Ci
906
+
907
+ return C
908
+
909
+
910
+ def unop_dict(A, f):
911
+ B = {}
912
+ for i, Ai in A.items():
913
+ Bi = {}
914
+ for j, Aij in Ai.items():
915
+ Bij = f(Aij)
916
+ if Bij:
917
+ Bi[j] = Bij
918
+ if Bi:
919
+ B[i] = Bi
920
+ return B
921
+
922
+
923
+ def sdm_transpose(M):
924
+ MT = {}
925
+ for i, Mi in M.items():
926
+ for j, Mij in Mi.items():
927
+ try:
928
+ MT[j][i] = Mij
929
+ except KeyError:
930
+ MT[j] = {i: Mij}
931
+ return MT
932
+
933
+
934
+ def sdm_matmul(A, B, K, m, o):
935
+ #
936
+ # Should be fast if A and B are very sparse.
937
+ # Consider e.g. A = B = eye(1000).
938
+ #
939
+ # The idea here is that we compute C = A*B in terms of the rows of C and
940
+ # B since the dict of dicts representation naturally stores the matrix as
941
+ # rows. The ith row of C (Ci) is equal to the sum of Aik * Bk where Bk is
942
+ # the kth row of B. The algorithm below loops over each nonzero element
943
+ # Aik of A and if the corresponding row Bj is nonzero then we do
944
+ # Ci += Aik * Bk.
945
+ # To make this more efficient we don't need to loop over all elements Aik.
946
+ # Instead for each row Ai we compute the intersection of the nonzero
947
+ # columns in Ai with the nonzero rows in B. That gives the k such that
948
+ # Aik and Bk are both nonzero. In Python the intersection of two sets
949
+ # of int can be computed very efficiently.
950
+ #
951
+ if K.is_EXRAW:
952
+ return sdm_matmul_exraw(A, B, K, m, o)
953
+
954
+ C = {}
955
+ B_knz = set(B)
956
+ for i, Ai in A.items():
957
+ Ci = {}
958
+ Ai_knz = set(Ai)
959
+ for k in Ai_knz & B_knz:
960
+ Aik = Ai[k]
961
+ for j, Bkj in B[k].items():
962
+ Cij = Ci.get(j, None)
963
+ if Cij is not None:
964
+ Cij = Cij + Aik * Bkj
965
+ if Cij:
966
+ Ci[j] = Cij
967
+ else:
968
+ Ci.pop(j)
969
+ else:
970
+ Cij = Aik * Bkj
971
+ if Cij:
972
+ Ci[j] = Cij
973
+ if Ci:
974
+ C[i] = Ci
975
+ return C
976
+
977
+
978
+ def sdm_matmul_exraw(A, B, K, m, o):
979
+ #
980
+ # Like sdm_matmul above except that:
981
+ #
982
+ # - Handles cases like 0*oo -> nan (sdm_matmul skips multipication by zero)
983
+ # - Uses K.sum (Add(*items)) for efficient addition of Expr
984
+ #
985
+ zero = K.zero
986
+ C = {}
987
+ B_knz = set(B)
988
+ for i, Ai in A.items():
989
+ Ci_list = defaultdict(list)
990
+ Ai_knz = set(Ai)
991
+
992
+ # Nonzero row/column pair
993
+ for k in Ai_knz & B_knz:
994
+ Aik = Ai[k]
995
+ if zero * Aik == zero:
996
+ # This is the main inner loop:
997
+ for j, Bkj in B[k].items():
998
+ Ci_list[j].append(Aik * Bkj)
999
+ else:
1000
+ for j in range(o):
1001
+ Ci_list[j].append(Aik * B[k].get(j, zero))
1002
+
1003
+ # Zero row in B, check for infinities in A
1004
+ for k in Ai_knz - B_knz:
1005
+ zAik = zero * Ai[k]
1006
+ if zAik != zero:
1007
+ for j in range(o):
1008
+ Ci_list[j].append(zAik)
1009
+
1010
+ # Add terms using K.sum (Add(*terms)) for efficiency
1011
+ Ci = {}
1012
+ for j, Cij_list in Ci_list.items():
1013
+ Cij = K.sum(Cij_list)
1014
+ if Cij:
1015
+ Ci[j] = Cij
1016
+ if Ci:
1017
+ C[i] = Ci
1018
+
1019
+ # Find all infinities in B
1020
+ for k, Bk in B.items():
1021
+ for j, Bkj in Bk.items():
1022
+ if zero * Bkj != zero:
1023
+ for i in range(m):
1024
+ Aik = A.get(i, {}).get(k, zero)
1025
+ # If Aik is not zero then this was handled above
1026
+ if Aik == zero:
1027
+ Ci = C.get(i, {})
1028
+ Cij = Ci.get(j, zero) + Aik * Bkj
1029
+ if Cij != zero:
1030
+ Ci[j] = Cij
1031
+ else: # pragma: no cover
1032
+ # Not sure how we could get here but let's raise an
1033
+ # exception just in case.
1034
+ raise RuntimeError
1035
+ C[i] = Ci
1036
+
1037
+ return C
1038
+
1039
+
1040
+ def sdm_irref(A):
1041
+ """RREF and pivots of a sparse matrix *A*.
1042
+
1043
+ Compute the reduced row echelon form (RREF) of the matrix *A* and return a
1044
+ list of the pivot columns. This routine does not work in place and leaves
1045
+ the original matrix *A* unmodified.
1046
+
1047
+ Examples
1048
+ ========
1049
+
1050
+ This routine works with a dict of dicts sparse representation of a matrix:
1051
+
1052
+ >>> from sympy import QQ
1053
+ >>> from sympy.polys.matrices.sdm import sdm_irref
1054
+ >>> A = {0: {0: QQ(1), 1: QQ(2)}, 1: {0: QQ(3), 1: QQ(4)}}
1055
+ >>> Arref, pivots, _ = sdm_irref(A)
1056
+ >>> Arref
1057
+ {0: {0: 1}, 1: {1: 1}}
1058
+ >>> pivots
1059
+ [0, 1]
1060
+
1061
+ The analogous calculation with :py:class:`~.Matrix` would be
1062
+
1063
+ >>> from sympy import Matrix
1064
+ >>> M = Matrix([[1, 2], [3, 4]])
1065
+ >>> Mrref, pivots = M.rref()
1066
+ >>> Mrref
1067
+ Matrix([
1068
+ [1, 0],
1069
+ [0, 1]])
1070
+ >>> pivots
1071
+ (0, 1)
1072
+
1073
+ Notes
1074
+ =====
1075
+
1076
+ The cost of this algorithm is determined purely by the nonzero elements of
1077
+ the matrix. No part of the cost of any step in this algorithm depends on
1078
+ the number of rows or columns in the matrix. No step depends even on the
1079
+ number of nonzero rows apart from the primary loop over those rows. The
1080
+ implementation is much faster than ddm_rref for sparse matrices. In fact
1081
+ at the time of writing it is also (slightly) faster than the dense
1082
+ implementation even if the input is a fully dense matrix so it seems to be
1083
+ faster in all cases.
1084
+
1085
+ The elements of the matrix should support exact division with ``/``. For
1086
+ example elements of any domain that is a field (e.g. ``QQ``) should be
1087
+ fine. No attempt is made to handle inexact arithmetic.
1088
+
1089
+ """
1090
+ #
1091
+ # Any zeros in the matrix are not stored at all so an element is zero if
1092
+ # its row dict has no index at that key. A row is entirely zero if its
1093
+ # row index is not in the outer dict. Since rref reorders the rows and
1094
+ # removes zero rows we can completely discard the row indices. The first
1095
+ # step then copies the row dicts into a list sorted by the index of the
1096
+ # first nonzero column in each row.
1097
+ #
1098
+ # The algorithm then processes each row Ai one at a time. Previously seen
1099
+ # rows are used to cancel their pivot columns from Ai. Then a pivot from
1100
+ # Ai is chosen and is cancelled from all previously seen rows. At this
1101
+ # point Ai joins the previously seen rows. Once all rows are seen all
1102
+ # elimination has occurred and the rows are sorted by pivot column index.
1103
+ #
1104
+ # The previously seen rows are stored in two separate groups. The reduced
1105
+ # group consists of all rows that have been reduced to a single nonzero
1106
+ # element (the pivot). There is no need to attempt any further reduction
1107
+ # with these. Rows that still have other nonzeros need to be considered
1108
+ # when Ai is cancelled from the previously seen rows.
1109
+ #
1110
+ # A dict nonzerocolumns is used to map from a column index to a set of
1111
+ # previously seen rows that still have a nonzero element in that column.
1112
+ # This means that we can cancel the pivot from Ai into the previously seen
1113
+ # rows without needing to loop over each row that might have a zero in
1114
+ # that column.
1115
+ #
1116
+
1117
+ # Row dicts sorted by index of first nonzero column
1118
+ # (Maybe sorting is not needed/useful.)
1119
+ Arows = sorted((Ai.copy() for Ai in A.values()), key=min)
1120
+
1121
+ # Each processed row has an associated pivot column.
1122
+ # pivot_row_map maps from the pivot column index to the row dict.
1123
+ # This means that we can represent a set of rows purely as a set of their
1124
+ # pivot indices.
1125
+ pivot_row_map = {}
1126
+
1127
+ # Set of pivot indices for rows that are fully reduced to a single nonzero.
1128
+ reduced_pivots = set()
1129
+
1130
+ # Set of pivot indices for rows not fully reduced
1131
+ nonreduced_pivots = set()
1132
+
1133
+ # Map from column index to a set of pivot indices representing the rows
1134
+ # that have a nonzero at that column.
1135
+ nonzero_columns = defaultdict(set)
1136
+
1137
+ while Arows:
1138
+ # Select pivot element and row
1139
+ Ai = Arows.pop()
1140
+
1141
+ # Nonzero columns from fully reduced pivot rows can be removed
1142
+ Ai = {j: Aij for j, Aij in Ai.items() if j not in reduced_pivots}
1143
+
1144
+ # Others require full row cancellation
1145
+ for j in nonreduced_pivots & set(Ai):
1146
+ Aj = pivot_row_map[j]
1147
+ Aij = Ai[j]
1148
+ Ainz = set(Ai)
1149
+ Ajnz = set(Aj)
1150
+ for k in Ajnz - Ainz:
1151
+ Ai[k] = - Aij * Aj[k]
1152
+ Ai.pop(j)
1153
+ Ainz.remove(j)
1154
+ for k in Ajnz & Ainz:
1155
+ Aik = Ai[k] - Aij * Aj[k]
1156
+ if Aik:
1157
+ Ai[k] = Aik
1158
+ else:
1159
+ Ai.pop(k)
1160
+
1161
+ # We have now cancelled previously seen pivots from Ai.
1162
+ # If it is zero then discard it.
1163
+ if not Ai:
1164
+ continue
1165
+
1166
+ # Choose a pivot from Ai:
1167
+ j = min(Ai)
1168
+ Aij = Ai[j]
1169
+ pivot_row_map[j] = Ai
1170
+ Ainz = set(Ai)
1171
+
1172
+ # Normalise the pivot row to make the pivot 1.
1173
+ #
1174
+ # This approach is slow for some domains. Cross cancellation might be
1175
+ # better for e.g. QQ(x) with division delayed to the final steps.
1176
+ Aijinv = Aij**-1
1177
+ for l in Ai:
1178
+ Ai[l] *= Aijinv
1179
+
1180
+ # Use Aij to cancel column j from all previously seen rows
1181
+ for k in nonzero_columns.pop(j, ()):
1182
+ Ak = pivot_row_map[k]
1183
+ Akj = Ak[j]
1184
+ Aknz = set(Ak)
1185
+ for l in Ainz - Aknz:
1186
+ Ak[l] = - Akj * Ai[l]
1187
+ nonzero_columns[l].add(k)
1188
+ Ak.pop(j)
1189
+ Aknz.remove(j)
1190
+ for l in Ainz & Aknz:
1191
+ Akl = Ak[l] - Akj * Ai[l]
1192
+ if Akl:
1193
+ Ak[l] = Akl
1194
+ else:
1195
+ # Drop nonzero elements
1196
+ Ak.pop(l)
1197
+ if l != j:
1198
+ nonzero_columns[l].remove(k)
1199
+ if len(Ak) == 1:
1200
+ reduced_pivots.add(k)
1201
+ nonreduced_pivots.remove(k)
1202
+
1203
+ if len(Ai) == 1:
1204
+ reduced_pivots.add(j)
1205
+ else:
1206
+ nonreduced_pivots.add(j)
1207
+ for l in Ai:
1208
+ if l != j:
1209
+ nonzero_columns[l].add(j)
1210
+
1211
+ # All done!
1212
+ pivots = sorted(reduced_pivots | nonreduced_pivots)
1213
+ pivot2row = {p: n for n, p in enumerate(pivots)}
1214
+ nonzero_columns = {c: {pivot2row[p] for p in s} for c, s in nonzero_columns.items()}
1215
+ rows = [pivot_row_map[i] for i in pivots]
1216
+ rref = dict(enumerate(rows))
1217
+ return rref, pivots, nonzero_columns
1218
+
1219
+
1220
+ def sdm_nullspace_from_rref(A, one, ncols, pivots, nonzero_cols):
1221
+ """Get nullspace from A which is in RREF"""
1222
+ nonpivots = sorted(set(range(ncols)) - set(pivots))
1223
+
1224
+ K = []
1225
+ for j in nonpivots:
1226
+ Kj = {j:one}
1227
+ for i in nonzero_cols.get(j, ()):
1228
+ Kj[pivots[i]] = -A[i][j]
1229
+ K.append(Kj)
1230
+
1231
+ return K, nonpivots
1232
+
1233
+
1234
+ def sdm_particular_from_rref(A, ncols, pivots):
1235
+ """Get a particular solution from A which is in RREF"""
1236
+ P = {}
1237
+ for i, j in enumerate(pivots):
1238
+ Ain = A[i].get(ncols-1, None)
1239
+ if Ain is not None:
1240
+ P[j] = Ain / A[i][j]
1241
+ return P
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/__init__.py ADDED
File without changes
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (199 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/__pycache__/test_ddm.cpython-310.pyc ADDED
Binary file (21.8 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/__pycache__/test_dense.cpython-310.pyc ADDED
Binary file (9.49 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/__pycache__/test_domainmatrix.cpython-310.pyc ADDED
Binary file (37.3 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/__pycache__/test_domainscalar.cpython-310.pyc ADDED
Binary file (5.79 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/__pycache__/test_eigen.cpython-310.pyc ADDED
Binary file (3.05 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/__pycache__/test_linsolve.cpython-310.pyc ADDED
Binary file (3.38 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/__pycache__/test_lll.cpython-310.pyc ADDED
Binary file (7.29 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/__pycache__/test_normalforms.cpython-310.pyc ADDED
Binary file (3.6 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/__pycache__/test_sdm.cpython-310.pyc ADDED
Binary file (18.1 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_ddm.py ADDED
@@ -0,0 +1,557 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.testing.pytest import raises
2
+ from sympy.external.gmpy import HAS_GMPY
3
+
4
+ from sympy.polys import ZZ, QQ
5
+
6
+ from sympy.polys.matrices.ddm import DDM
7
+ from sympy.polys.matrices.exceptions import (
8
+ DMShapeError, DMNonInvertibleMatrixError, DMDomainError,
9
+ DMBadInputError)
10
+
11
+
12
+ def test_DDM_init():
13
+ items = [[ZZ(0), ZZ(1), ZZ(2)], [ZZ(3), ZZ(4), ZZ(5)]]
14
+ shape = (2, 3)
15
+ ddm = DDM(items, shape, ZZ)
16
+ assert ddm.shape == shape
17
+ assert ddm.rows == 2
18
+ assert ddm.cols == 3
19
+ assert ddm.domain == ZZ
20
+
21
+ raises(DMBadInputError, lambda: DDM([[ZZ(2), ZZ(3)]], (2, 2), ZZ))
22
+ raises(DMBadInputError, lambda: DDM([[ZZ(1)], [ZZ(2), ZZ(3)]], (2, 2), ZZ))
23
+
24
+
25
+ def test_DDM_getsetitem():
26
+ ddm = DDM([[ZZ(2), ZZ(3)], [ZZ(4), ZZ(5)]], (2, 2), ZZ)
27
+
28
+ assert ddm[0][0] == ZZ(2)
29
+ assert ddm[0][1] == ZZ(3)
30
+ assert ddm[1][0] == ZZ(4)
31
+ assert ddm[1][1] == ZZ(5)
32
+
33
+ raises(IndexError, lambda: ddm[2][0])
34
+ raises(IndexError, lambda: ddm[0][2])
35
+
36
+ ddm[0][0] = ZZ(-1)
37
+ assert ddm[0][0] == ZZ(-1)
38
+
39
+
40
+ def test_DDM_str():
41
+ ddm = DDM([[ZZ(0), ZZ(1)], [ZZ(2), ZZ(3)]], (2, 2), ZZ)
42
+ if HAS_GMPY: # pragma: no cover
43
+ assert str(ddm) == '[[0, 1], [2, 3]]'
44
+ assert repr(ddm) == 'DDM([[mpz(0), mpz(1)], [mpz(2), mpz(3)]], (2, 2), ZZ)'
45
+ else: # pragma: no cover
46
+ assert repr(ddm) == 'DDM([[0, 1], [2, 3]], (2, 2), ZZ)'
47
+ assert str(ddm) == '[[0, 1], [2, 3]]'
48
+
49
+
50
+ def test_DDM_eq():
51
+ items = [[ZZ(0), ZZ(1)], [ZZ(2), ZZ(3)]]
52
+ ddm1 = DDM(items, (2, 2), ZZ)
53
+ ddm2 = DDM(items, (2, 2), ZZ)
54
+
55
+ assert (ddm1 == ddm1) is True
56
+ assert (ddm1 == items) is False
57
+ assert (items == ddm1) is False
58
+ assert (ddm1 == ddm2) is True
59
+ assert (ddm2 == ddm1) is True
60
+
61
+ assert (ddm1 != ddm1) is False
62
+ assert (ddm1 != items) is True
63
+ assert (items != ddm1) is True
64
+ assert (ddm1 != ddm2) is False
65
+ assert (ddm2 != ddm1) is False
66
+
67
+ ddm3 = DDM([[ZZ(0), ZZ(1)], [ZZ(3), ZZ(3)]], (2, 2), ZZ)
68
+ ddm3 = DDM(items, (2, 2), QQ)
69
+
70
+ assert (ddm1 == ddm3) is False
71
+ assert (ddm3 == ddm1) is False
72
+ assert (ddm1 != ddm3) is True
73
+ assert (ddm3 != ddm1) is True
74
+
75
+
76
+ def test_DDM_convert_to():
77
+ ddm = DDM([[ZZ(1), ZZ(2)]], (1, 2), ZZ)
78
+ assert ddm.convert_to(ZZ) == ddm
79
+ ddmq = ddm.convert_to(QQ)
80
+ assert ddmq.domain == QQ
81
+
82
+
83
+ def test_DDM_zeros():
84
+ ddmz = DDM.zeros((3, 4), QQ)
85
+ assert list(ddmz) == [[QQ(0)] * 4] * 3
86
+ assert ddmz.shape == (3, 4)
87
+ assert ddmz.domain == QQ
88
+
89
+ def test_DDM_ones():
90
+ ddmone = DDM.ones((2, 3), QQ)
91
+ assert list(ddmone) == [[QQ(1)] * 3] * 2
92
+ assert ddmone.shape == (2, 3)
93
+ assert ddmone.domain == QQ
94
+
95
+ def test_DDM_eye():
96
+ ddmz = DDM.eye(3, QQ)
97
+ f = lambda i, j: QQ(1) if i == j else QQ(0)
98
+ assert list(ddmz) == [[f(i, j) for i in range(3)] for j in range(3)]
99
+ assert ddmz.shape == (3, 3)
100
+ assert ddmz.domain == QQ
101
+
102
+
103
+ def test_DDM_copy():
104
+ ddm1 = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ)
105
+ ddm2 = ddm1.copy()
106
+ assert (ddm1 == ddm2) is True
107
+ ddm1[0][0] = QQ(-1)
108
+ assert (ddm1 == ddm2) is False
109
+ ddm2[0][0] = QQ(-1)
110
+ assert (ddm1 == ddm2) is True
111
+
112
+
113
+ def test_DDM_transpose():
114
+ ddm = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ)
115
+ ddmT = DDM([[QQ(1), QQ(2)]], (1, 2), QQ)
116
+ assert ddm.transpose() == ddmT
117
+ ddm02 = DDM([], (0, 2), QQ)
118
+ ddm02T = DDM([[], []], (2, 0), QQ)
119
+ assert ddm02.transpose() == ddm02T
120
+ assert ddm02T.transpose() == ddm02
121
+ ddm0 = DDM([], (0, 0), QQ)
122
+ assert ddm0.transpose() == ddm0
123
+
124
+
125
+ def test_DDM_add():
126
+ A = DDM([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ)
127
+ B = DDM([[ZZ(3)], [ZZ(4)]], (2, 1), ZZ)
128
+ C = DDM([[ZZ(4)], [ZZ(6)]], (2, 1), ZZ)
129
+ AQ = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ)
130
+ assert A + B == A.add(B) == C
131
+
132
+ raises(DMShapeError, lambda: A + DDM([[ZZ(5)]], (1, 1), ZZ))
133
+ raises(TypeError, lambda: A + ZZ(1))
134
+ raises(TypeError, lambda: ZZ(1) + A)
135
+ raises(DMDomainError, lambda: A + AQ)
136
+ raises(DMDomainError, lambda: AQ + A)
137
+
138
+
139
+ def test_DDM_sub():
140
+ A = DDM([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ)
141
+ B = DDM([[ZZ(3)], [ZZ(4)]], (2, 1), ZZ)
142
+ C = DDM([[ZZ(-2)], [ZZ(-2)]], (2, 1), ZZ)
143
+ AQ = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ)
144
+ D = DDM([[ZZ(5)]], (1, 1), ZZ)
145
+ assert A - B == A.sub(B) == C
146
+
147
+ raises(TypeError, lambda: A - ZZ(1))
148
+ raises(TypeError, lambda: ZZ(1) - A)
149
+ raises(DMShapeError, lambda: A - D)
150
+ raises(DMShapeError, lambda: D - A)
151
+ raises(DMShapeError, lambda: A.sub(D))
152
+ raises(DMShapeError, lambda: D.sub(A))
153
+ raises(DMDomainError, lambda: A - AQ)
154
+ raises(DMDomainError, lambda: AQ - A)
155
+ raises(DMDomainError, lambda: A.sub(AQ))
156
+ raises(DMDomainError, lambda: AQ.sub(A))
157
+
158
+
159
+ def test_DDM_neg():
160
+ A = DDM([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ)
161
+ An = DDM([[ZZ(-1)], [ZZ(-2)]], (2, 1), ZZ)
162
+ assert -A == A.neg() == An
163
+ assert -An == An.neg() == A
164
+
165
+
166
+ def test_DDM_mul():
167
+ A = DDM([[ZZ(1)]], (1, 1), ZZ)
168
+ A2 = DDM([[ZZ(2)]], (1, 1), ZZ)
169
+ assert A * ZZ(2) == A2
170
+ assert ZZ(2) * A == A2
171
+ raises(TypeError, lambda: [[1]] * A)
172
+ raises(TypeError, lambda: A * [[1]])
173
+
174
+
175
+ def test_DDM_matmul():
176
+ A = DDM([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ)
177
+ B = DDM([[ZZ(3), ZZ(4)]], (1, 2), ZZ)
178
+ AB = DDM([[ZZ(3), ZZ(4)], [ZZ(6), ZZ(8)]], (2, 2), ZZ)
179
+ BA = DDM([[ZZ(11)]], (1, 1), ZZ)
180
+
181
+ assert A @ B == A.matmul(B) == AB
182
+ assert B @ A == B.matmul(A) == BA
183
+
184
+ raises(TypeError, lambda: A @ 1)
185
+ raises(TypeError, lambda: A @ [[3, 4]])
186
+
187
+ Bq = DDM([[QQ(3), QQ(4)]], (1, 2), QQ)
188
+
189
+ raises(DMDomainError, lambda: A @ Bq)
190
+ raises(DMDomainError, lambda: Bq @ A)
191
+
192
+ C = DDM([[ZZ(1)]], (1, 1), ZZ)
193
+
194
+ assert A @ C == A.matmul(C) == A
195
+
196
+ raises(DMShapeError, lambda: C @ A)
197
+ raises(DMShapeError, lambda: C.matmul(A))
198
+
199
+ Z04 = DDM([], (0, 4), ZZ)
200
+ Z40 = DDM([[]]*4, (4, 0), ZZ)
201
+ Z50 = DDM([[]]*5, (5, 0), ZZ)
202
+ Z05 = DDM([], (0, 5), ZZ)
203
+ Z45 = DDM([[0] * 5] * 4, (4, 5), ZZ)
204
+ Z54 = DDM([[0] * 4] * 5, (5, 4), ZZ)
205
+ Z00 = DDM([], (0, 0), ZZ)
206
+
207
+ assert Z04 @ Z45 == Z04.matmul(Z45) == Z05
208
+ assert Z45 @ Z50 == Z45.matmul(Z50) == Z40
209
+ assert Z00 @ Z04 == Z00.matmul(Z04) == Z04
210
+ assert Z50 @ Z00 == Z50.matmul(Z00) == Z50
211
+ assert Z00 @ Z00 == Z00.matmul(Z00) == Z00
212
+ assert Z50 @ Z04 == Z50.matmul(Z04) == Z54
213
+
214
+ raises(DMShapeError, lambda: Z05 @ Z40)
215
+ raises(DMShapeError, lambda: Z05.matmul(Z40))
216
+
217
+
218
+ def test_DDM_hstack():
219
+ A = DDM([[ZZ(1), ZZ(2), ZZ(3)]], (1, 3), ZZ)
220
+ B = DDM([[ZZ(4), ZZ(5)]], (1, 2), ZZ)
221
+ C = DDM([[ZZ(6)]], (1, 1), ZZ)
222
+
223
+ Ah = A.hstack(B)
224
+ assert Ah.shape == (1, 5)
225
+ assert Ah.domain == ZZ
226
+ assert Ah == DDM([[ZZ(1), ZZ(2), ZZ(3), ZZ(4), ZZ(5)]], (1, 5), ZZ)
227
+
228
+ Ah = A.hstack(B, C)
229
+ assert Ah.shape == (1, 6)
230
+ assert Ah.domain == ZZ
231
+ assert Ah == DDM([[ZZ(1), ZZ(2), ZZ(3), ZZ(4), ZZ(5), ZZ(6)]], (1, 6), ZZ)
232
+
233
+
234
+ def test_DDM_vstack():
235
+ A = DDM([[ZZ(1)], [ZZ(2)], [ZZ(3)]], (3, 1), ZZ)
236
+ B = DDM([[ZZ(4)], [ZZ(5)]], (2, 1), ZZ)
237
+ C = DDM([[ZZ(6)]], (1, 1), ZZ)
238
+
239
+ Ah = A.vstack(B)
240
+ assert Ah.shape == (5, 1)
241
+ assert Ah.domain == ZZ
242
+ assert Ah == DDM([[ZZ(1)], [ZZ(2)], [ZZ(3)], [ZZ(4)], [ZZ(5)]], (5, 1), ZZ)
243
+
244
+ Ah = A.vstack(B, C)
245
+ assert Ah.shape == (6, 1)
246
+ assert Ah.domain == ZZ
247
+ assert Ah == DDM([[ZZ(1)], [ZZ(2)], [ZZ(3)], [ZZ(4)], [ZZ(5)], [ZZ(6)]], (6, 1), ZZ)
248
+
249
+
250
+ def test_DDM_applyfunc():
251
+ A = DDM([[ZZ(1), ZZ(2), ZZ(3)]], (1, 3), ZZ)
252
+ B = DDM([[ZZ(2), ZZ(4), ZZ(6)]], (1, 3), ZZ)
253
+ assert A.applyfunc(lambda x: 2*x, ZZ) == B
254
+
255
+ def test_DDM_rref():
256
+
257
+ A = DDM([], (0, 4), QQ)
258
+ assert A.rref() == (A, [])
259
+
260
+ A = DDM([[QQ(0), QQ(1)], [QQ(1), QQ(1)]], (2, 2), QQ)
261
+ Ar = DDM([[QQ(1), QQ(0)], [QQ(0), QQ(1)]], (2, 2), QQ)
262
+ pivots = [0, 1]
263
+ assert A.rref() == (Ar, pivots)
264
+
265
+ A = DDM([[QQ(1), QQ(2), QQ(1)], [QQ(3), QQ(4), QQ(1)]], (2, 3), QQ)
266
+ Ar = DDM([[QQ(1), QQ(0), QQ(-1)], [QQ(0), QQ(1), QQ(1)]], (2, 3), QQ)
267
+ pivots = [0, 1]
268
+ assert A.rref() == (Ar, pivots)
269
+
270
+ A = DDM([[QQ(3), QQ(4), QQ(1)], [QQ(1), QQ(2), QQ(1)]], (2, 3), QQ)
271
+ Ar = DDM([[QQ(1), QQ(0), QQ(-1)], [QQ(0), QQ(1), QQ(1)]], (2, 3), QQ)
272
+ pivots = [0, 1]
273
+ assert A.rref() == (Ar, pivots)
274
+
275
+ A = DDM([[QQ(1), QQ(0)], [QQ(1), QQ(3)], [QQ(0), QQ(1)]], (3, 2), QQ)
276
+ Ar = DDM([[QQ(1), QQ(0)], [QQ(0), QQ(1)], [QQ(0), QQ(0)]], (3, 2), QQ)
277
+ pivots = [0, 1]
278
+ assert A.rref() == (Ar, pivots)
279
+
280
+ A = DDM([[QQ(1), QQ(0), QQ(1)], [QQ(3), QQ(0), QQ(1)]], (2, 3), QQ)
281
+ Ar = DDM([[QQ(1), QQ(0), QQ(0)], [QQ(0), QQ(0), QQ(1)]], (2, 3), QQ)
282
+ pivots = [0, 2]
283
+ assert A.rref() == (Ar, pivots)
284
+
285
+
286
+ def test_DDM_nullspace():
287
+ A = DDM([[QQ(1), QQ(1)], [QQ(1), QQ(1)]], (2, 2), QQ)
288
+ Anull = DDM([[QQ(-1), QQ(1)]], (1, 2), QQ)
289
+ nonpivots = [1]
290
+ assert A.nullspace() == (Anull, nonpivots)
291
+
292
+
293
+ def test_DDM_particular():
294
+ A = DDM([[QQ(1), QQ(0)]], (1, 2), QQ)
295
+ assert A.particular() == DDM.zeros((1, 1), QQ)
296
+
297
+
298
+ def test_DDM_det():
299
+ # 0x0 case
300
+ A = DDM([], (0, 0), ZZ)
301
+ assert A.det() == ZZ(1)
302
+
303
+ # 1x1 case
304
+ A = DDM([[ZZ(2)]], (1, 1), ZZ)
305
+ assert A.det() == ZZ(2)
306
+
307
+ # 2x2 case
308
+ A = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
309
+ assert A.det() == ZZ(-2)
310
+
311
+ # 3x3 with swap
312
+ A = DDM([[ZZ(1), ZZ(2), ZZ(3)], [ZZ(1), ZZ(2), ZZ(4)], [ZZ(1), ZZ(2), ZZ(5)]], (3, 3), ZZ)
313
+ assert A.det() == ZZ(0)
314
+
315
+ # 2x2 QQ case
316
+ A = DDM([[QQ(1, 2), QQ(1, 2)], [QQ(1, 3), QQ(1, 4)]], (2, 2), QQ)
317
+ assert A.det() == QQ(-1, 24)
318
+
319
+ # Nonsquare error
320
+ A = DDM([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ)
321
+ raises(DMShapeError, lambda: A.det())
322
+
323
+ # Nonsquare error with empty matrix
324
+ A = DDM([], (0, 1), ZZ)
325
+ raises(DMShapeError, lambda: A.det())
326
+
327
+
328
+ def test_DDM_inv():
329
+ A = DDM([[QQ(1, 1), QQ(2, 1)], [QQ(3, 1), QQ(4, 1)]], (2, 2), QQ)
330
+ Ainv = DDM([[QQ(-2, 1), QQ(1, 1)], [QQ(3, 2), QQ(-1, 2)]], (2, 2), QQ)
331
+ assert A.inv() == Ainv
332
+
333
+ A = DDM([[QQ(1), QQ(2)]], (1, 2), QQ)
334
+ raises(DMShapeError, lambda: A.inv())
335
+
336
+ A = DDM([[ZZ(2)]], (1, 1), ZZ)
337
+ raises(ValueError, lambda: A.inv())
338
+
339
+ A = DDM([], (0, 0), QQ)
340
+ assert A.inv() == A
341
+
342
+ A = DDM([[QQ(1), QQ(2)], [QQ(2), QQ(4)]], (2, 2), QQ)
343
+ raises(DMNonInvertibleMatrixError, lambda: A.inv())
344
+
345
+
346
+ def test_DDM_lu():
347
+ A = DDM([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
348
+ L, U, swaps = A.lu()
349
+ assert L == DDM([[QQ(1), QQ(0)], [QQ(3), QQ(1)]], (2, 2), QQ)
350
+ assert U == DDM([[QQ(1), QQ(2)], [QQ(0), QQ(-2)]], (2, 2), QQ)
351
+ assert swaps == []
352
+
353
+ A = [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 1], [0, 0, 1, 2]]
354
+ Lexp = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 1, 1]]
355
+ Uexp = [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 1], [0, 0, 0, 1]]
356
+ to_dom = lambda rows, dom: [[dom(e) for e in row] for row in rows]
357
+ A = DDM(to_dom(A, QQ), (4, 4), QQ)
358
+ Lexp = DDM(to_dom(Lexp, QQ), (4, 4), QQ)
359
+ Uexp = DDM(to_dom(Uexp, QQ), (4, 4), QQ)
360
+ L, U, swaps = A.lu()
361
+ assert L == Lexp
362
+ assert U == Uexp
363
+ assert swaps == []
364
+
365
+
366
+ def test_DDM_lu_solve():
367
+ # Basic example
368
+ A = DDM([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
369
+ b = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ)
370
+ x = DDM([[QQ(0)], [QQ(1, 2)]], (2, 1), QQ)
371
+ assert A.lu_solve(b) == x
372
+
373
+ # Example with swaps
374
+ A = DDM([[QQ(0), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
375
+ assert A.lu_solve(b) == x
376
+
377
+ # Overdetermined, consistent
378
+ A = DDM([[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]], (3, 2), QQ)
379
+ b = DDM([[QQ(1)], [QQ(2)], [QQ(3)]], (3, 1), QQ)
380
+ assert A.lu_solve(b) == x
381
+
382
+ # Overdetermined, inconsistent
383
+ b = DDM([[QQ(1)], [QQ(2)], [QQ(4)]], (3, 1), QQ)
384
+ raises(DMNonInvertibleMatrixError, lambda: A.lu_solve(b))
385
+
386
+ # Square, noninvertible
387
+ A = DDM([[QQ(1), QQ(2)], [QQ(1), QQ(2)]], (2, 2), QQ)
388
+ b = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ)
389
+ raises(DMNonInvertibleMatrixError, lambda: A.lu_solve(b))
390
+
391
+ # Underdetermined
392
+ A = DDM([[QQ(1), QQ(2)]], (1, 2), QQ)
393
+ b = DDM([[QQ(3)]], (1, 1), QQ)
394
+ raises(NotImplementedError, lambda: A.lu_solve(b))
395
+
396
+ # Domain mismatch
397
+ bz = DDM([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ)
398
+ raises(DMDomainError, lambda: A.lu_solve(bz))
399
+
400
+ # Shape mismatch
401
+ b3 = DDM([[QQ(1)], [QQ(2)], [QQ(3)]], (3, 1), QQ)
402
+ raises(DMShapeError, lambda: A.lu_solve(b3))
403
+
404
+
405
+ def test_DDM_charpoly():
406
+ A = DDM([], (0, 0), ZZ)
407
+ assert A.charpoly() == [ZZ(1)]
408
+
409
+ A = DDM([
410
+ [ZZ(1), ZZ(2), ZZ(3)],
411
+ [ZZ(4), ZZ(5), ZZ(6)],
412
+ [ZZ(7), ZZ(8), ZZ(9)]], (3, 3), ZZ)
413
+ Avec = [ZZ(1), ZZ(-15), ZZ(-18), ZZ(0)]
414
+ assert A.charpoly() == Avec
415
+
416
+ A = DDM([[ZZ(1), ZZ(2)]], (1, 2), ZZ)
417
+ raises(DMShapeError, lambda: A.charpoly())
418
+
419
+
420
+ def test_DDM_getitem():
421
+ dm = DDM([
422
+ [ZZ(1), ZZ(2), ZZ(3)],
423
+ [ZZ(4), ZZ(5), ZZ(6)],
424
+ [ZZ(7), ZZ(8), ZZ(9)]], (3, 3), ZZ)
425
+
426
+ assert dm.getitem(1, 1) == ZZ(5)
427
+ assert dm.getitem(1, -2) == ZZ(5)
428
+ assert dm.getitem(-1, -3) == ZZ(7)
429
+
430
+ raises(IndexError, lambda: dm.getitem(3, 3))
431
+
432
+
433
+ def test_DDM_setitem():
434
+ dm = DDM.zeros((3, 3), ZZ)
435
+ dm.setitem(0, 0, 1)
436
+ dm.setitem(1, -2, 1)
437
+ dm.setitem(-1, -1, 1)
438
+ assert dm == DDM.eye(3, ZZ)
439
+
440
+ raises(IndexError, lambda: dm.setitem(3, 3, 0))
441
+
442
+
443
+ def test_DDM_extract_slice():
444
+ dm = DDM([
445
+ [ZZ(1), ZZ(2), ZZ(3)],
446
+ [ZZ(4), ZZ(5), ZZ(6)],
447
+ [ZZ(7), ZZ(8), ZZ(9)]], (3, 3), ZZ)
448
+
449
+ assert dm.extract_slice(slice(0, 3), slice(0, 3)) == dm
450
+ assert dm.extract_slice(slice(1, 3), slice(-2)) == DDM([[4], [7]], (2, 1), ZZ)
451
+ assert dm.extract_slice(slice(1, 3), slice(-2)) == DDM([[4], [7]], (2, 1), ZZ)
452
+ assert dm.extract_slice(slice(2, 3), slice(-2)) == DDM([[ZZ(7)]], (1, 1), ZZ)
453
+ assert dm.extract_slice(slice(0, 2), slice(-2)) == DDM([[1], [4]], (2, 1), ZZ)
454
+ assert dm.extract_slice(slice(-1), slice(-1)) == DDM([[1, 2], [4, 5]], (2, 2), ZZ)
455
+
456
+ assert dm.extract_slice(slice(2), slice(3, 4)) == DDM([[], []], (2, 0), ZZ)
457
+ assert dm.extract_slice(slice(3, 4), slice(2)) == DDM([], (0, 2), ZZ)
458
+ assert dm.extract_slice(slice(3, 4), slice(3, 4)) == DDM([], (0, 0), ZZ)
459
+
460
+
461
+ def test_DDM_extract():
462
+ dm1 = DDM([
463
+ [ZZ(1), ZZ(2), ZZ(3)],
464
+ [ZZ(4), ZZ(5), ZZ(6)],
465
+ [ZZ(7), ZZ(8), ZZ(9)]], (3, 3), ZZ)
466
+ dm2 = DDM([
467
+ [ZZ(6), ZZ(4)],
468
+ [ZZ(3), ZZ(1)]], (2, 2), ZZ)
469
+ assert dm1.extract([1, 0], [2, 0]) == dm2
470
+ assert dm1.extract([-2, 0], [-1, 0]) == dm2
471
+
472
+ assert dm1.extract([], []) == DDM.zeros((0, 0), ZZ)
473
+ assert dm1.extract([1], []) == DDM.zeros((1, 0), ZZ)
474
+ assert dm1.extract([], [1]) == DDM.zeros((0, 1), ZZ)
475
+
476
+ raises(IndexError, lambda: dm2.extract([2], [0]))
477
+ raises(IndexError, lambda: dm2.extract([0], [2]))
478
+ raises(IndexError, lambda: dm2.extract([-3], [0]))
479
+ raises(IndexError, lambda: dm2.extract([0], [-3]))
480
+
481
+
482
+ def test_DDM_flat():
483
+ dm = DDM([
484
+ [ZZ(6), ZZ(4)],
485
+ [ZZ(3), ZZ(1)]], (2, 2), ZZ)
486
+ assert dm.flat() == [ZZ(6), ZZ(4), ZZ(3), ZZ(1)]
487
+
488
+
489
+ def test_DDM_is_zero_matrix():
490
+ A = DDM([[QQ(1), QQ(0)], [QQ(0), QQ(0)]], (2, 2), QQ)
491
+ Azero = DDM.zeros((1, 2), QQ)
492
+ assert A.is_zero_matrix() is False
493
+ assert Azero.is_zero_matrix() is True
494
+
495
+
496
+ def test_DDM_is_upper():
497
+ # Wide matrices:
498
+ A = DDM([
499
+ [QQ(1), QQ(2), QQ(3), QQ(4)],
500
+ [QQ(0), QQ(5), QQ(6), QQ(7)],
501
+ [QQ(0), QQ(0), QQ(8), QQ(9)]
502
+ ], (3, 4), QQ)
503
+ B = DDM([
504
+ [QQ(1), QQ(2), QQ(3), QQ(4)],
505
+ [QQ(0), QQ(5), QQ(6), QQ(7)],
506
+ [QQ(0), QQ(7), QQ(8), QQ(9)]
507
+ ], (3, 4), QQ)
508
+ assert A.is_upper() is True
509
+ assert B.is_upper() is False
510
+
511
+ # Tall matrices:
512
+ A = DDM([
513
+ [QQ(1), QQ(2), QQ(3)],
514
+ [QQ(0), QQ(5), QQ(6)],
515
+ [QQ(0), QQ(0), QQ(8)],
516
+ [QQ(0), QQ(0), QQ(0)]
517
+ ], (4, 3), QQ)
518
+ B = DDM([
519
+ [QQ(1), QQ(2), QQ(3)],
520
+ [QQ(0), QQ(5), QQ(6)],
521
+ [QQ(0), QQ(0), QQ(8)],
522
+ [QQ(0), QQ(0), QQ(10)]
523
+ ], (4, 3), QQ)
524
+ assert A.is_upper() is True
525
+ assert B.is_upper() is False
526
+
527
+
528
+ def test_DDM_is_lower():
529
+ # Tall matrices:
530
+ A = DDM([
531
+ [QQ(1), QQ(2), QQ(3), QQ(4)],
532
+ [QQ(0), QQ(5), QQ(6), QQ(7)],
533
+ [QQ(0), QQ(0), QQ(8), QQ(9)]
534
+ ], (3, 4), QQ).transpose()
535
+ B = DDM([
536
+ [QQ(1), QQ(2), QQ(3), QQ(4)],
537
+ [QQ(0), QQ(5), QQ(6), QQ(7)],
538
+ [QQ(0), QQ(7), QQ(8), QQ(9)]
539
+ ], (3, 4), QQ).transpose()
540
+ assert A.is_lower() is True
541
+ assert B.is_lower() is False
542
+
543
+ # Wide matrices:
544
+ A = DDM([
545
+ [QQ(1), QQ(2), QQ(3)],
546
+ [QQ(0), QQ(5), QQ(6)],
547
+ [QQ(0), QQ(0), QQ(8)],
548
+ [QQ(0), QQ(0), QQ(0)]
549
+ ], (4, 3), QQ).transpose()
550
+ B = DDM([
551
+ [QQ(1), QQ(2), QQ(3)],
552
+ [QQ(0), QQ(5), QQ(6)],
553
+ [QQ(0), QQ(0), QQ(8)],
554
+ [QQ(0), QQ(0), QQ(10)]
555
+ ], (4, 3), QQ).transpose()
556
+ assert A.is_lower() is True
557
+ assert B.is_lower() is False
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_dense.py ADDED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.testing.pytest import raises
2
+
3
+ from sympy.polys import ZZ, QQ
4
+
5
+ from sympy.polys.matrices.ddm import DDM
6
+ from sympy.polys.matrices.dense import (
7
+ ddm_transpose,
8
+ ddm_iadd, ddm_isub, ddm_ineg, ddm_imatmul, ddm_imul, ddm_irref,
9
+ ddm_idet, ddm_iinv, ddm_ilu, ddm_ilu_split, ddm_ilu_solve, ddm_berk)
10
+ from sympy.polys.matrices.exceptions import (
11
+ DMShapeError, DMNonInvertibleMatrixError, DMNonSquareMatrixError)
12
+
13
+
14
+ def test_ddm_transpose():
15
+ a = [[1, 2], [3, 4]]
16
+ assert ddm_transpose(a) == [[1, 3], [2, 4]]
17
+
18
+
19
+ def test_ddm_iadd():
20
+ a = [[1, 2], [3, 4]]
21
+ b = [[5, 6], [7, 8]]
22
+ ddm_iadd(a, b)
23
+ assert a == [[6, 8], [10, 12]]
24
+
25
+
26
+ def test_ddm_isub():
27
+ a = [[1, 2], [3, 4]]
28
+ b = [[5, 6], [7, 8]]
29
+ ddm_isub(a, b)
30
+ assert a == [[-4, -4], [-4, -4]]
31
+
32
+
33
+ def test_ddm_ineg():
34
+ a = [[1, 2], [3, 4]]
35
+ ddm_ineg(a)
36
+ assert a == [[-1, -2], [-3, -4]]
37
+
38
+
39
+ def test_ddm_matmul():
40
+ a = [[1, 2], [3, 4]]
41
+ ddm_imul(a, 2)
42
+ assert a == [[2, 4], [6, 8]]
43
+
44
+ a = [[1, 2], [3, 4]]
45
+ ddm_imul(a, 0)
46
+ assert a == [[0, 0], [0, 0]]
47
+
48
+
49
+ def test_ddm_imatmul():
50
+ a = [[1, 2, 3], [4, 5, 6]]
51
+ b = [[1, 2], [3, 4], [5, 6]]
52
+
53
+ c1 = [[0, 0], [0, 0]]
54
+ ddm_imatmul(c1, a, b)
55
+ assert c1 == [[22, 28], [49, 64]]
56
+
57
+ c2 = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
58
+ ddm_imatmul(c2, b, a)
59
+ assert c2 == [[9, 12, 15], [19, 26, 33], [29, 40, 51]]
60
+
61
+ b3 = [[1], [2], [3]]
62
+ c3 = [[0], [0]]
63
+ ddm_imatmul(c3, a, b3)
64
+ assert c3 == [[14], [32]]
65
+
66
+
67
+ def test_ddm_irref():
68
+ # Empty matrix
69
+ A = []
70
+ Ar = []
71
+ pivots = []
72
+ assert ddm_irref(A) == pivots
73
+ assert A == Ar
74
+
75
+ # Standard square case
76
+ A = [[QQ(0), QQ(1)], [QQ(1), QQ(1)]]
77
+ Ar = [[QQ(1), QQ(0)], [QQ(0), QQ(1)]]
78
+ pivots = [0, 1]
79
+ assert ddm_irref(A) == pivots
80
+ assert A == Ar
81
+
82
+ # m < n case
83
+ A = [[QQ(1), QQ(2), QQ(1)], [QQ(3), QQ(4), QQ(1)]]
84
+ Ar = [[QQ(1), QQ(0), QQ(-1)], [QQ(0), QQ(1), QQ(1)]]
85
+ pivots = [0, 1]
86
+ assert ddm_irref(A) == pivots
87
+ assert A == Ar
88
+
89
+ # same m < n but reversed
90
+ A = [[QQ(3), QQ(4), QQ(1)], [QQ(1), QQ(2), QQ(1)]]
91
+ Ar = [[QQ(1), QQ(0), QQ(-1)], [QQ(0), QQ(1), QQ(1)]]
92
+ pivots = [0, 1]
93
+ assert ddm_irref(A) == pivots
94
+ assert A == Ar
95
+
96
+ # m > n case
97
+ A = [[QQ(1), QQ(0)], [QQ(1), QQ(3)], [QQ(0), QQ(1)]]
98
+ Ar = [[QQ(1), QQ(0)], [QQ(0), QQ(1)], [QQ(0), QQ(0)]]
99
+ pivots = [0, 1]
100
+ assert ddm_irref(A) == pivots
101
+ assert A == Ar
102
+
103
+ # Example with missing pivot
104
+ A = [[QQ(1), QQ(0), QQ(1)], [QQ(3), QQ(0), QQ(1)]]
105
+ Ar = [[QQ(1), QQ(0), QQ(0)], [QQ(0), QQ(0), QQ(1)]]
106
+ pivots = [0, 2]
107
+ assert ddm_irref(A) == pivots
108
+ assert A == Ar
109
+
110
+ # Example with missing pivot and no replacement
111
+ A = [[QQ(0), QQ(1)], [QQ(0), QQ(2)], [QQ(1), QQ(0)]]
112
+ Ar = [[QQ(1), QQ(0)], [QQ(0), QQ(1)], [QQ(0), QQ(0)]]
113
+ pivots = [0, 1]
114
+ assert ddm_irref(A) == pivots
115
+ assert A == Ar
116
+
117
+
118
+ def test_ddm_idet():
119
+ A = []
120
+ assert ddm_idet(A, ZZ) == ZZ(1)
121
+
122
+ A = [[ZZ(2)]]
123
+ assert ddm_idet(A, ZZ) == ZZ(2)
124
+
125
+ A = [[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]]
126
+ assert ddm_idet(A, ZZ) == ZZ(-2)
127
+
128
+ A = [[ZZ(1), ZZ(2), ZZ(3)], [ZZ(1), ZZ(2), ZZ(4)], [ZZ(1), ZZ(3), ZZ(5)]]
129
+ assert ddm_idet(A, ZZ) == ZZ(-1)
130
+
131
+ A = [[ZZ(1), ZZ(2), ZZ(3)], [ZZ(1), ZZ(2), ZZ(4)], [ZZ(1), ZZ(2), ZZ(5)]]
132
+ assert ddm_idet(A, ZZ) == ZZ(0)
133
+
134
+ A = [[QQ(1, 2), QQ(1, 2)], [QQ(1, 3), QQ(1, 4)]]
135
+ assert ddm_idet(A, QQ) == QQ(-1, 24)
136
+
137
+
138
+ def test_ddm_inv():
139
+ A = []
140
+ Ainv = []
141
+ ddm_iinv(Ainv, A, QQ)
142
+ assert Ainv == A
143
+
144
+ A = []
145
+ Ainv = []
146
+ raises(ValueError, lambda: ddm_iinv(Ainv, A, ZZ))
147
+
148
+ A = [[QQ(1), QQ(2)]]
149
+ Ainv = [[QQ(0), QQ(0)]]
150
+ raises(DMNonSquareMatrixError, lambda: ddm_iinv(Ainv, A, QQ))
151
+
152
+ A = [[QQ(1, 1), QQ(2, 1)], [QQ(3, 1), QQ(4, 1)]]
153
+ Ainv = [[QQ(0), QQ(0)], [QQ(0), QQ(0)]]
154
+ Ainv_expected = [[QQ(-2, 1), QQ(1, 1)], [QQ(3, 2), QQ(-1, 2)]]
155
+ ddm_iinv(Ainv, A, QQ)
156
+ assert Ainv == Ainv_expected
157
+
158
+ A = [[QQ(1, 1), QQ(2, 1)], [QQ(2, 1), QQ(4, 1)]]
159
+ Ainv = [[QQ(0), QQ(0)], [QQ(0), QQ(0)]]
160
+ raises(DMNonInvertibleMatrixError, lambda: ddm_iinv(Ainv, A, QQ))
161
+
162
+
163
+ def test_ddm_ilu():
164
+ A = []
165
+ Alu = []
166
+ swaps = ddm_ilu(A)
167
+ assert A == Alu
168
+ assert swaps == []
169
+
170
+ A = [[]]
171
+ Alu = [[]]
172
+ swaps = ddm_ilu(A)
173
+ assert A == Alu
174
+ assert swaps == []
175
+
176
+ A = [[QQ(1), QQ(2)], [QQ(3), QQ(4)]]
177
+ Alu = [[QQ(1), QQ(2)], [QQ(3), QQ(-2)]]
178
+ swaps = ddm_ilu(A)
179
+ assert A == Alu
180
+ assert swaps == []
181
+
182
+ A = [[QQ(0), QQ(2)], [QQ(3), QQ(4)]]
183
+ Alu = [[QQ(3), QQ(4)], [QQ(0), QQ(2)]]
184
+ swaps = ddm_ilu(A)
185
+ assert A == Alu
186
+ assert swaps == [(0, 1)]
187
+
188
+ A = [[QQ(1), QQ(2), QQ(3)], [QQ(4), QQ(5), QQ(6)], [QQ(7), QQ(8), QQ(9)]]
189
+ Alu = [[QQ(1), QQ(2), QQ(3)], [QQ(4), QQ(-3), QQ(-6)], [QQ(7), QQ(2), QQ(0)]]
190
+ swaps = ddm_ilu(A)
191
+ assert A == Alu
192
+ assert swaps == []
193
+
194
+ A = [[QQ(0), QQ(1), QQ(2)], [QQ(0), QQ(1), QQ(3)], [QQ(1), QQ(1), QQ(2)]]
195
+ Alu = [[QQ(1), QQ(1), QQ(2)], [QQ(0), QQ(1), QQ(3)], [QQ(0), QQ(1), QQ(-1)]]
196
+ swaps = ddm_ilu(A)
197
+ assert A == Alu
198
+ assert swaps == [(0, 2)]
199
+
200
+ A = [[QQ(1), QQ(2), QQ(3)], [QQ(4), QQ(5), QQ(6)]]
201
+ Alu = [[QQ(1), QQ(2), QQ(3)], [QQ(4), QQ(-3), QQ(-6)]]
202
+ swaps = ddm_ilu(A)
203
+ assert A == Alu
204
+ assert swaps == []
205
+
206
+ A = [[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]]
207
+ Alu = [[QQ(1), QQ(2)], [QQ(3), QQ(-2)], [QQ(5), QQ(2)]]
208
+ swaps = ddm_ilu(A)
209
+ assert A == Alu
210
+ assert swaps == []
211
+
212
+
213
+ def test_ddm_ilu_split():
214
+ U = []
215
+ L = []
216
+ Uexp = []
217
+ Lexp = []
218
+ swaps = ddm_ilu_split(L, U, QQ)
219
+ assert U == Uexp
220
+ assert L == Lexp
221
+ assert swaps == []
222
+
223
+ U = [[]]
224
+ L = [[QQ(1)]]
225
+ Uexp = [[]]
226
+ Lexp = [[QQ(1)]]
227
+ swaps = ddm_ilu_split(L, U, QQ)
228
+ assert U == Uexp
229
+ assert L == Lexp
230
+ assert swaps == []
231
+
232
+ U = [[QQ(1), QQ(2)], [QQ(3), QQ(4)]]
233
+ L = [[QQ(1), QQ(0)], [QQ(0), QQ(1)]]
234
+ Uexp = [[QQ(1), QQ(2)], [QQ(0), QQ(-2)]]
235
+ Lexp = [[QQ(1), QQ(0)], [QQ(3), QQ(1)]]
236
+ swaps = ddm_ilu_split(L, U, QQ)
237
+ assert U == Uexp
238
+ assert L == Lexp
239
+ assert swaps == []
240
+
241
+ U = [[QQ(1), QQ(2), QQ(3)], [QQ(4), QQ(5), QQ(6)]]
242
+ L = [[QQ(1), QQ(0)], [QQ(0), QQ(1)]]
243
+ Uexp = [[QQ(1), QQ(2), QQ(3)], [QQ(0), QQ(-3), QQ(-6)]]
244
+ Lexp = [[QQ(1), QQ(0)], [QQ(4), QQ(1)]]
245
+ swaps = ddm_ilu_split(L, U, QQ)
246
+ assert U == Uexp
247
+ assert L == Lexp
248
+ assert swaps == []
249
+
250
+ U = [[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]]
251
+ L = [[QQ(1), QQ(0), QQ(0)], [QQ(0), QQ(1), QQ(0)], [QQ(0), QQ(0), QQ(1)]]
252
+ Uexp = [[QQ(1), QQ(2)], [QQ(0), QQ(-2)], [QQ(0), QQ(0)]]
253
+ Lexp = [[QQ(1), QQ(0), QQ(0)], [QQ(3), QQ(1), QQ(0)], [QQ(5), QQ(2), QQ(1)]]
254
+ swaps = ddm_ilu_split(L, U, QQ)
255
+ assert U == Uexp
256
+ assert L == Lexp
257
+ assert swaps == []
258
+
259
+
260
+ def test_ddm_ilu_solve():
261
+ # Basic example
262
+ # A = [[QQ(1), QQ(2)], [QQ(3), QQ(4)]]
263
+ U = [[QQ(1), QQ(2)], [QQ(0), QQ(-2)]]
264
+ L = [[QQ(1), QQ(0)], [QQ(3), QQ(1)]]
265
+ swaps = []
266
+ b = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ)
267
+ x = DDM([[QQ(0)], [QQ(0)]], (2, 1), QQ)
268
+ xexp = DDM([[QQ(0)], [QQ(1, 2)]], (2, 1), QQ)
269
+ ddm_ilu_solve(x, L, U, swaps, b)
270
+ assert x == xexp
271
+
272
+ # Example with swaps
273
+ # A = [[QQ(0), QQ(2)], [QQ(3), QQ(4)]]
274
+ U = [[QQ(3), QQ(4)], [QQ(0), QQ(2)]]
275
+ L = [[QQ(1), QQ(0)], [QQ(0), QQ(1)]]
276
+ swaps = [(0, 1)]
277
+ b = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ)
278
+ x = DDM([[QQ(0)], [QQ(0)]], (2, 1), QQ)
279
+ xexp = DDM([[QQ(0)], [QQ(1, 2)]], (2, 1), QQ)
280
+ ddm_ilu_solve(x, L, U, swaps, b)
281
+ assert x == xexp
282
+
283
+ # Overdetermined, consistent
284
+ # A = DDM([[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]], (3, 2), QQ)
285
+ U = [[QQ(1), QQ(2)], [QQ(0), QQ(-2)], [QQ(0), QQ(0)]]
286
+ L = [[QQ(1), QQ(0), QQ(0)], [QQ(3), QQ(1), QQ(0)], [QQ(5), QQ(2), QQ(1)]]
287
+ swaps = []
288
+ b = DDM([[QQ(1)], [QQ(2)], [QQ(3)]], (3, 1), QQ)
289
+ x = DDM([[QQ(0)], [QQ(0)]], (2, 1), QQ)
290
+ xexp = DDM([[QQ(0)], [QQ(1, 2)]], (2, 1), QQ)
291
+ ddm_ilu_solve(x, L, U, swaps, b)
292
+ assert x == xexp
293
+
294
+ # Overdetermined, inconsistent
295
+ b = DDM([[QQ(1)], [QQ(2)], [QQ(4)]], (3, 1), QQ)
296
+ raises(DMNonInvertibleMatrixError, lambda: ddm_ilu_solve(x, L, U, swaps, b))
297
+
298
+ # Square, noninvertible
299
+ # A = DDM([[QQ(1), QQ(2)], [QQ(1), QQ(2)]], (2, 2), QQ)
300
+ U = [[QQ(1), QQ(2)], [QQ(0), QQ(0)]]
301
+ L = [[QQ(1), QQ(0)], [QQ(1), QQ(1)]]
302
+ swaps = []
303
+ b = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ)
304
+ raises(DMNonInvertibleMatrixError, lambda: ddm_ilu_solve(x, L, U, swaps, b))
305
+
306
+ # Underdetermined
307
+ # A = DDM([[QQ(1), QQ(2)]], (1, 2), QQ)
308
+ U = [[QQ(1), QQ(2)]]
309
+ L = [[QQ(1)]]
310
+ swaps = []
311
+ b = DDM([[QQ(3)]], (1, 1), QQ)
312
+ raises(NotImplementedError, lambda: ddm_ilu_solve(x, L, U, swaps, b))
313
+
314
+ # Shape mismatch
315
+ b3 = DDM([[QQ(1)], [QQ(2)], [QQ(3)]], (3, 1), QQ)
316
+ raises(DMShapeError, lambda: ddm_ilu_solve(x, L, U, swaps, b3))
317
+
318
+ # Empty shape mismatch
319
+ U = [[QQ(1)]]
320
+ L = [[QQ(1)]]
321
+ swaps = []
322
+ x = [[QQ(1)]]
323
+ b = []
324
+ raises(DMShapeError, lambda: ddm_ilu_solve(x, L, U, swaps, b))
325
+
326
+ # Empty system
327
+ U = []
328
+ L = []
329
+ swaps = []
330
+ b = []
331
+ x = []
332
+ ddm_ilu_solve(x, L, U, swaps, b)
333
+ assert x == []
334
+
335
+
336
+ def test_ddm_charpoly():
337
+ A = []
338
+ assert ddm_berk(A, ZZ) == [[ZZ(1)]]
339
+
340
+ A = [[ZZ(1), ZZ(2), ZZ(3)], [ZZ(4), ZZ(5), ZZ(6)], [ZZ(7), ZZ(8), ZZ(9)]]
341
+ Avec = [[ZZ(1)], [ZZ(-15)], [ZZ(-18)], [ZZ(0)]]
342
+ assert ddm_berk(A, ZZ) == Avec
343
+
344
+ A = DDM([[ZZ(1), ZZ(2)]], (1, 2), ZZ)
345
+ raises(DMShapeError, lambda: ddm_berk(A, ZZ))
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_domainmatrix.py ADDED
@@ -0,0 +1,910 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.testing.pytest import raises
2
+
3
+ from sympy.core.numbers import Integer, Rational
4
+ from sympy.core.singleton import S
5
+ from sympy.functions import sqrt
6
+
7
+ from sympy.matrices.dense import Matrix
8
+ from sympy.polys.domains import FF, ZZ, QQ, EXRAW
9
+
10
+ from sympy.polys.matrices.domainmatrix import DomainMatrix, DomainScalar, DM
11
+ from sympy.polys.matrices.exceptions import (
12
+ DMBadInputError, DMDomainError, DMShapeError, DMFormatError, DMNotAField,
13
+ DMNonSquareMatrixError, DMNonInvertibleMatrixError,
14
+ )
15
+ from sympy.polys.matrices.ddm import DDM
16
+ from sympy.polys.matrices.sdm import SDM
17
+
18
+
19
+ def test_DM():
20
+ ddm = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
21
+ A = DM([[1, 2], [3, 4]], ZZ)
22
+ assert A.rep == ddm
23
+ assert A.shape == (2, 2)
24
+ assert A.domain == ZZ
25
+
26
+
27
+ def test_DomainMatrix_init():
28
+ lol = [[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]]
29
+ dod = {0: {0: ZZ(1), 1:ZZ(2)}, 1: {0:ZZ(3), 1:ZZ(4)}}
30
+ ddm = DDM(lol, (2, 2), ZZ)
31
+ sdm = SDM(dod, (2, 2), ZZ)
32
+
33
+ A = DomainMatrix(lol, (2, 2), ZZ)
34
+ assert A.rep == ddm
35
+ assert A.shape == (2, 2)
36
+ assert A.domain == ZZ
37
+
38
+ A = DomainMatrix(dod, (2, 2), ZZ)
39
+ assert A.rep == sdm
40
+ assert A.shape == (2, 2)
41
+ assert A.domain == ZZ
42
+
43
+ raises(TypeError, lambda: DomainMatrix(ddm, (2, 2), ZZ))
44
+ raises(TypeError, lambda: DomainMatrix(sdm, (2, 2), ZZ))
45
+ raises(TypeError, lambda: DomainMatrix(Matrix([[1]]), (1, 1), ZZ))
46
+
47
+ for fmt, rep in [('sparse', sdm), ('dense', ddm)]:
48
+ A = DomainMatrix(lol, (2, 2), ZZ, fmt=fmt)
49
+ assert A.rep == rep
50
+ A = DomainMatrix(dod, (2, 2), ZZ, fmt=fmt)
51
+ assert A.rep == rep
52
+
53
+ raises(ValueError, lambda: DomainMatrix(lol, (2, 2), ZZ, fmt='invalid'))
54
+
55
+ raises(DMBadInputError, lambda: DomainMatrix([[ZZ(1), ZZ(2)]], (2, 2), ZZ))
56
+
57
+
58
+ def test_DomainMatrix_from_rep():
59
+ ddm = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
60
+ A = DomainMatrix.from_rep(ddm)
61
+ assert A.rep == ddm
62
+ assert A.shape == (2, 2)
63
+ assert A.domain == ZZ
64
+
65
+ sdm = SDM({0: {0: ZZ(1), 1:ZZ(2)}, 1: {0:ZZ(3), 1:ZZ(4)}}, (2, 2), ZZ)
66
+ A = DomainMatrix.from_rep(sdm)
67
+ assert A.rep == sdm
68
+ assert A.shape == (2, 2)
69
+ assert A.domain == ZZ
70
+
71
+ A = DomainMatrix([[ZZ(1)]], (1, 1), ZZ)
72
+ raises(TypeError, lambda: DomainMatrix.from_rep(A))
73
+
74
+
75
+ def test_DomainMatrix_from_list():
76
+ ddm = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
77
+ A = DomainMatrix.from_list([[1, 2], [3, 4]], ZZ)
78
+ assert A.rep == ddm
79
+ assert A.shape == (2, 2)
80
+ assert A.domain == ZZ
81
+
82
+ dom = FF(7)
83
+ ddm = DDM([[dom(1), dom(2)], [dom(3), dom(4)]], (2, 2), dom)
84
+ A = DomainMatrix.from_list([[1, 2], [3, 4]], dom)
85
+ assert A.rep == ddm
86
+ assert A.shape == (2, 2)
87
+ assert A.domain == dom
88
+
89
+ ddm = DDM([[QQ(1, 2), QQ(3, 1)], [QQ(1, 4), QQ(5, 1)]], (2, 2), QQ)
90
+ A = DomainMatrix.from_list([[(1, 2), (3, 1)], [(1, 4), (5, 1)]], QQ)
91
+ assert A.rep == ddm
92
+ assert A.shape == (2, 2)
93
+ assert A.domain == QQ
94
+
95
+
96
+ def test_DomainMatrix_from_list_sympy():
97
+ ddm = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
98
+ A = DomainMatrix.from_list_sympy(2, 2, [[1, 2], [3, 4]])
99
+ assert A.rep == ddm
100
+ assert A.shape == (2, 2)
101
+ assert A.domain == ZZ
102
+
103
+ K = QQ.algebraic_field(sqrt(2))
104
+ ddm = DDM(
105
+ [[K.convert(1 + sqrt(2)), K.convert(2 + sqrt(2))],
106
+ [K.convert(3 + sqrt(2)), K.convert(4 + sqrt(2))]],
107
+ (2, 2),
108
+ K
109
+ )
110
+ A = DomainMatrix.from_list_sympy(
111
+ 2, 2, [[1 + sqrt(2), 2 + sqrt(2)], [3 + sqrt(2), 4 + sqrt(2)]],
112
+ extension=True)
113
+ assert A.rep == ddm
114
+ assert A.shape == (2, 2)
115
+ assert A.domain == K
116
+
117
+
118
+ def test_DomainMatrix_from_dict_sympy():
119
+ sdm = SDM({0: {0: QQ(1, 2)}, 1: {1: QQ(2, 3)}}, (2, 2), QQ)
120
+ sympy_dict = {0: {0: Rational(1, 2)}, 1: {1: Rational(2, 3)}}
121
+ A = DomainMatrix.from_dict_sympy(2, 2, sympy_dict)
122
+ assert A.rep == sdm
123
+ assert A.shape == (2, 2)
124
+ assert A.domain == QQ
125
+
126
+ fds = DomainMatrix.from_dict_sympy
127
+ raises(DMBadInputError, lambda: fds(2, 2, {3: {0: Rational(1, 2)}}))
128
+ raises(DMBadInputError, lambda: fds(2, 2, {0: {3: Rational(1, 2)}}))
129
+
130
+
131
+ def test_DomainMatrix_from_Matrix():
132
+ sdm = SDM({0: {0: ZZ(1), 1: ZZ(2)}, 1: {0: ZZ(3), 1: ZZ(4)}}, (2, 2), ZZ)
133
+ A = DomainMatrix.from_Matrix(Matrix([[1, 2], [3, 4]]))
134
+ assert A.rep == sdm
135
+ assert A.shape == (2, 2)
136
+ assert A.domain == ZZ
137
+
138
+ K = QQ.algebraic_field(sqrt(2))
139
+ sdm = SDM(
140
+ {0: {0: K.convert(1 + sqrt(2)), 1: K.convert(2 + sqrt(2))},
141
+ 1: {0: K.convert(3 + sqrt(2)), 1: K.convert(4 + sqrt(2))}},
142
+ (2, 2),
143
+ K
144
+ )
145
+ A = DomainMatrix.from_Matrix(
146
+ Matrix([[1 + sqrt(2), 2 + sqrt(2)], [3 + sqrt(2), 4 + sqrt(2)]]),
147
+ extension=True)
148
+ assert A.rep == sdm
149
+ assert A.shape == (2, 2)
150
+ assert A.domain == K
151
+
152
+ A = DomainMatrix.from_Matrix(Matrix([[QQ(1, 2), QQ(3, 4)], [QQ(0, 1), QQ(0, 1)]]), fmt='dense')
153
+ ddm = DDM([[QQ(1, 2), QQ(3, 4)], [QQ(0, 1), QQ(0, 1)]], (2, 2), QQ)
154
+
155
+ assert A.rep == ddm
156
+ assert A.shape == (2, 2)
157
+ assert A.domain == QQ
158
+
159
+
160
+ def test_DomainMatrix_eq():
161
+ A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
162
+ assert A == A
163
+ B = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(1)]], (2, 2), ZZ)
164
+ assert A != B
165
+ C = [[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]]
166
+ assert A != C
167
+
168
+
169
+ def test_DomainMatrix_unify_eq():
170
+ A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
171
+ B1 = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
172
+ B2 = DomainMatrix([[QQ(1), QQ(3)], [QQ(3), QQ(4)]], (2, 2), QQ)
173
+ B3 = DomainMatrix([[ZZ(1)]], (1, 1), ZZ)
174
+ assert A.unify_eq(B1) is True
175
+ assert A.unify_eq(B2) is False
176
+ assert A.unify_eq(B3) is False
177
+
178
+
179
+ def test_DomainMatrix_get_domain():
180
+ K, items = DomainMatrix.get_domain([1, 2, 3, 4])
181
+ assert items == [ZZ(1), ZZ(2), ZZ(3), ZZ(4)]
182
+ assert K == ZZ
183
+
184
+ K, items = DomainMatrix.get_domain([1, 2, 3, Rational(1, 2)])
185
+ assert items == [QQ(1), QQ(2), QQ(3), QQ(1, 2)]
186
+ assert K == QQ
187
+
188
+
189
+ def test_DomainMatrix_convert_to():
190
+ A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
191
+ Aq = A.convert_to(QQ)
192
+ assert Aq == DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
193
+ Acopy = A.convert_to(None)
194
+ assert Acopy == A and Acopy is not A
195
+
196
+
197
+ def test_DomainMatrix_to_sympy():
198
+ A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
199
+ assert A.to_sympy() == A.convert_to(EXRAW)
200
+
201
+
202
+ def test_DomainMatrix_to_field():
203
+ A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
204
+ Aq = A.to_field()
205
+ assert Aq == DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
206
+
207
+
208
+ def test_DomainMatrix_to_sparse():
209
+ A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
210
+ A_sparse = A.to_sparse()
211
+ assert A_sparse.rep == {0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}}
212
+
213
+
214
+ def test_DomainMatrix_to_dense():
215
+ A = DomainMatrix({0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}}, (2, 2), ZZ)
216
+ A_dense = A.to_dense()
217
+ assert A_dense.rep == DDM([[1, 2], [3, 4]], (2, 2), ZZ)
218
+
219
+
220
+ def test_DomainMatrix_unify():
221
+ Az = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
222
+ Aq = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
223
+ assert Az.unify(Az) == (Az, Az)
224
+ assert Az.unify(Aq) == (Aq, Aq)
225
+ assert Aq.unify(Az) == (Aq, Aq)
226
+ assert Aq.unify(Aq) == (Aq, Aq)
227
+
228
+ As = DomainMatrix({0: {1: ZZ(1)}, 1:{0:ZZ(2)}}, (2, 2), ZZ)
229
+ Ad = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
230
+
231
+ assert As.unify(As) == (As, As)
232
+ assert Ad.unify(Ad) == (Ad, Ad)
233
+
234
+ Bs, Bd = As.unify(Ad, fmt='dense')
235
+ assert Bs.rep == DDM([[0, 1], [2, 0]], (2, 2), ZZ)
236
+ assert Bd.rep == DDM([[1, 2],[3, 4]], (2, 2), ZZ)
237
+
238
+ Bs, Bd = As.unify(Ad, fmt='sparse')
239
+ assert Bs.rep == SDM({0: {1: 1}, 1: {0: 2}}, (2, 2), ZZ)
240
+ assert Bd.rep == SDM({0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}}, (2, 2), ZZ)
241
+
242
+ raises(ValueError, lambda: As.unify(Ad, fmt='invalid'))
243
+
244
+
245
+ def test_DomainMatrix_to_Matrix():
246
+ A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
247
+ assert A.to_Matrix() == Matrix([[1, 2], [3, 4]])
248
+
249
+
250
+ def test_DomainMatrix_to_list():
251
+ A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
252
+ assert A.to_list() == [[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]]
253
+
254
+
255
+ def test_DomainMatrix_to_list_flat():
256
+ A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
257
+ assert A.to_list_flat() == [ZZ(1), ZZ(2), ZZ(3), ZZ(4)]
258
+
259
+
260
+ def test_DomainMatrix_to_dok():
261
+ A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
262
+ assert A.to_dok() == {(0, 0):ZZ(1), (0, 1):ZZ(2), (1, 0):ZZ(3), (1, 1):ZZ(4)}
263
+
264
+
265
+ def test_DomainMatrix_repr():
266
+ A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
267
+ assert repr(A) == 'DomainMatrix([[1, 2], [3, 4]], (2, 2), ZZ)'
268
+
269
+
270
+ def test_DomainMatrix_transpose():
271
+ A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
272
+ AT = DomainMatrix([[ZZ(1), ZZ(3)], [ZZ(2), ZZ(4)]], (2, 2), ZZ)
273
+ assert A.transpose() == AT
274
+
275
+
276
+ def test_DomainMatrix_flat():
277
+ A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
278
+ assert A.flat() == [ZZ(1), ZZ(2), ZZ(3), ZZ(4)]
279
+
280
+
281
+ def test_DomainMatrix_is_zero_matrix():
282
+ A = DomainMatrix([[ZZ(1)]], (1, 1), ZZ)
283
+ B = DomainMatrix([[ZZ(0)]], (1, 1), ZZ)
284
+ assert A.is_zero_matrix is False
285
+ assert B.is_zero_matrix is True
286
+
287
+
288
+ def test_DomainMatrix_is_upper():
289
+ A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(0), ZZ(4)]], (2, 2), ZZ)
290
+ B = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
291
+ assert A.is_upper is True
292
+ assert B.is_upper is False
293
+
294
+
295
+ def test_DomainMatrix_is_lower():
296
+ A = DomainMatrix([[ZZ(1), ZZ(0)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
297
+ B = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
298
+ assert A.is_lower is True
299
+ assert B.is_lower is False
300
+
301
+
302
+ def test_DomainMatrix_is_square():
303
+ A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
304
+ B = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)], [ZZ(5), ZZ(6)]], (3, 2), ZZ)
305
+ assert A.is_square is True
306
+ assert B.is_square is False
307
+
308
+
309
+ def test_DomainMatrix_rank():
310
+ A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(6), QQ(8)]], (3, 2), QQ)
311
+ assert A.rank() == 2
312
+
313
+
314
+ def test_DomainMatrix_add():
315
+ A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
316
+ B = DomainMatrix([[ZZ(2), ZZ(4)], [ZZ(6), ZZ(8)]], (2, 2), ZZ)
317
+ assert A + A == A.add(A) == B
318
+
319
+ A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
320
+ L = [[2, 3], [3, 4]]
321
+ raises(TypeError, lambda: A + L)
322
+ raises(TypeError, lambda: L + A)
323
+
324
+ A1 = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
325
+ A2 = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ)
326
+ raises(DMShapeError, lambda: A1 + A2)
327
+ raises(DMShapeError, lambda: A2 + A1)
328
+ raises(DMShapeError, lambda: A1.add(A2))
329
+ raises(DMShapeError, lambda: A2.add(A1))
330
+
331
+ Az = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
332
+ Aq = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
333
+ Asum = DomainMatrix([[QQ(2), QQ(4)], [QQ(6), QQ(8)]], (2, 2), QQ)
334
+ assert Az + Aq == Asum
335
+ assert Aq + Az == Asum
336
+ raises(DMDomainError, lambda: Az.add(Aq))
337
+ raises(DMDomainError, lambda: Aq.add(Az))
338
+
339
+ As = DomainMatrix({0: {1: ZZ(1)}, 1: {0: ZZ(2)}}, (2, 2), ZZ)
340
+ Ad = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
341
+
342
+ Asd = As + Ad
343
+ Ads = Ad + As
344
+ assert Asd == DomainMatrix([[1, 3], [5, 4]], (2, 2), ZZ)
345
+ assert Asd.rep == DDM([[1, 3], [5, 4]], (2, 2), ZZ)
346
+ assert Ads == DomainMatrix([[1, 3], [5, 4]], (2, 2), ZZ)
347
+ assert Ads.rep == DDM([[1, 3], [5, 4]], (2, 2), ZZ)
348
+ raises(DMFormatError, lambda: As.add(Ad))
349
+
350
+
351
+ def test_DomainMatrix_sub():
352
+ A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
353
+ B = DomainMatrix([[ZZ(0), ZZ(0)], [ZZ(0), ZZ(0)]], (2, 2), ZZ)
354
+ assert A - A == A.sub(A) == B
355
+
356
+ A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
357
+ L = [[2, 3], [3, 4]]
358
+ raises(TypeError, lambda: A - L)
359
+ raises(TypeError, lambda: L - A)
360
+
361
+ A1 = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
362
+ A2 = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ)
363
+ raises(DMShapeError, lambda: A1 - A2)
364
+ raises(DMShapeError, lambda: A2 - A1)
365
+ raises(DMShapeError, lambda: A1.sub(A2))
366
+ raises(DMShapeError, lambda: A2.sub(A1))
367
+
368
+ Az = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
369
+ Aq = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
370
+ Adiff = DomainMatrix([[QQ(0), QQ(0)], [QQ(0), QQ(0)]], (2, 2), QQ)
371
+ assert Az - Aq == Adiff
372
+ assert Aq - Az == Adiff
373
+ raises(DMDomainError, lambda: Az.sub(Aq))
374
+ raises(DMDomainError, lambda: Aq.sub(Az))
375
+
376
+ As = DomainMatrix({0: {1: ZZ(1)}, 1: {0: ZZ(2)}}, (2, 2), ZZ)
377
+ Ad = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
378
+
379
+ Asd = As - Ad
380
+ Ads = Ad - As
381
+ assert Asd == DomainMatrix([[-1, -1], [-1, -4]], (2, 2), ZZ)
382
+ assert Asd.rep == DDM([[-1, -1], [-1, -4]], (2, 2), ZZ)
383
+ assert Asd == -Ads
384
+ assert Asd.rep == -Ads.rep
385
+
386
+
387
+ def test_DomainMatrix_neg():
388
+ A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
389
+ Aneg = DomainMatrix([[ZZ(-1), ZZ(-2)], [ZZ(-3), ZZ(-4)]], (2, 2), ZZ)
390
+ assert -A == A.neg() == Aneg
391
+
392
+
393
+ def test_DomainMatrix_mul():
394
+ A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
395
+ A2 = DomainMatrix([[ZZ(7), ZZ(10)], [ZZ(15), ZZ(22)]], (2, 2), ZZ)
396
+ assert A*A == A.matmul(A) == A2
397
+
398
+ A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
399
+ L = [[1, 2], [3, 4]]
400
+ raises(TypeError, lambda: A * L)
401
+ raises(TypeError, lambda: L * A)
402
+
403
+ Az = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
404
+ Aq = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
405
+ Aprod = DomainMatrix([[QQ(7), QQ(10)], [QQ(15), QQ(22)]], (2, 2), QQ)
406
+ assert Az * Aq == Aprod
407
+ assert Aq * Az == Aprod
408
+ raises(DMDomainError, lambda: Az.matmul(Aq))
409
+ raises(DMDomainError, lambda: Aq.matmul(Az))
410
+
411
+ A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
412
+ AA = DomainMatrix([[ZZ(2), ZZ(4)], [ZZ(6), ZZ(8)]], (2, 2), ZZ)
413
+ x = ZZ(2)
414
+ assert A * x == x * A == A.mul(x) == AA
415
+
416
+ A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
417
+ AA = DomainMatrix.zeros((2, 2), ZZ)
418
+ x = ZZ(0)
419
+ assert A * x == x * A == A.mul(x).to_sparse() == AA
420
+
421
+ As = DomainMatrix({0: {1: ZZ(1)}, 1: {0: ZZ(2)}}, (2, 2), ZZ)
422
+ Ad = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
423
+
424
+ Asd = As * Ad
425
+ Ads = Ad * As
426
+ assert Asd == DomainMatrix([[3, 4], [2, 4]], (2, 2), ZZ)
427
+ assert Asd.rep == DDM([[3, 4], [2, 4]], (2, 2), ZZ)
428
+ assert Ads == DomainMatrix([[4, 1], [8, 3]], (2, 2), ZZ)
429
+ assert Ads.rep == DDM([[4, 1], [8, 3]], (2, 2), ZZ)
430
+
431
+
432
+ def test_DomainMatrix_mul_elementwise():
433
+ A = DomainMatrix([[ZZ(2), ZZ(2)], [ZZ(0), ZZ(0)]], (2, 2), ZZ)
434
+ B = DomainMatrix([[ZZ(4), ZZ(0)], [ZZ(3), ZZ(0)]], (2, 2), ZZ)
435
+ C = DomainMatrix([[ZZ(8), ZZ(0)], [ZZ(0), ZZ(0)]], (2, 2), ZZ)
436
+ assert A.mul_elementwise(B) == C
437
+ assert B.mul_elementwise(A) == C
438
+
439
+
440
+ def test_DomainMatrix_pow():
441
+ eye = DomainMatrix.eye(2, ZZ)
442
+ A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
443
+ A2 = DomainMatrix([[ZZ(7), ZZ(10)], [ZZ(15), ZZ(22)]], (2, 2), ZZ)
444
+ A3 = DomainMatrix([[ZZ(37), ZZ(54)], [ZZ(81), ZZ(118)]], (2, 2), ZZ)
445
+ assert A**0 == A.pow(0) == eye
446
+ assert A**1 == A.pow(1) == A
447
+ assert A**2 == A.pow(2) == A2
448
+ assert A**3 == A.pow(3) == A3
449
+
450
+ raises(TypeError, lambda: A ** Rational(1, 2))
451
+ raises(NotImplementedError, lambda: A ** -1)
452
+ raises(NotImplementedError, lambda: A.pow(-1))
453
+
454
+ A = DomainMatrix.zeros((2, 1), ZZ)
455
+ raises(DMNonSquareMatrixError, lambda: A ** 1)
456
+
457
+
458
+ def test_DomainMatrix_scc():
459
+ Ad = DomainMatrix([[ZZ(1), ZZ(2), ZZ(3)],
460
+ [ZZ(0), ZZ(1), ZZ(0)],
461
+ [ZZ(2), ZZ(0), ZZ(4)]], (3, 3), ZZ)
462
+ As = Ad.to_sparse()
463
+ Addm = Ad.rep
464
+ Asdm = As.rep
465
+ for A in [Ad, As, Addm, Asdm]:
466
+ assert Ad.scc() == [[1], [0, 2]]
467
+
468
+
469
+ def test_DomainMatrix_rref():
470
+ A = DomainMatrix([], (0, 1), QQ)
471
+ assert A.rref() == (A, ())
472
+
473
+ A = DomainMatrix([[QQ(1)]], (1, 1), QQ)
474
+ assert A.rref() == (A, (0,))
475
+
476
+ A = DomainMatrix([[QQ(0)]], (1, 1), QQ)
477
+ assert A.rref() == (A, ())
478
+
479
+ A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
480
+ Ar, pivots = A.rref()
481
+ assert Ar == DomainMatrix([[QQ(1), QQ(0)], [QQ(0), QQ(1)]], (2, 2), QQ)
482
+ assert pivots == (0, 1)
483
+
484
+ A = DomainMatrix([[QQ(0), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
485
+ Ar, pivots = A.rref()
486
+ assert Ar == DomainMatrix([[QQ(1), QQ(0)], [QQ(0), QQ(1)]], (2, 2), QQ)
487
+ assert pivots == (0, 1)
488
+
489
+ A = DomainMatrix([[QQ(0), QQ(2)], [QQ(0), QQ(4)]], (2, 2), QQ)
490
+ Ar, pivots = A.rref()
491
+ assert Ar == DomainMatrix([[QQ(0), QQ(1)], [QQ(0), QQ(0)]], (2, 2), QQ)
492
+ assert pivots == (1,)
493
+
494
+ Az = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
495
+ raises(DMNotAField, lambda: Az.rref())
496
+
497
+
498
+ def test_DomainMatrix_columnspace():
499
+ A = DomainMatrix([[QQ(1), QQ(-1), QQ(1)], [QQ(2), QQ(-2), QQ(3)]], (2, 3), QQ)
500
+ Acol = DomainMatrix([[QQ(1), QQ(1)], [QQ(2), QQ(3)]], (2, 2), QQ)
501
+ assert A.columnspace() == Acol
502
+
503
+ Az = DomainMatrix([[ZZ(1), ZZ(-1), ZZ(1)], [ZZ(2), ZZ(-2), ZZ(3)]], (2, 3), ZZ)
504
+ raises(DMNotAField, lambda: Az.columnspace())
505
+
506
+ A = DomainMatrix([[QQ(1), QQ(-1), QQ(1)], [QQ(2), QQ(-2), QQ(3)]], (2, 3), QQ, fmt='sparse')
507
+ Acol = DomainMatrix({0: {0: QQ(1), 1: QQ(1)}, 1: {0: QQ(2), 1: QQ(3)}}, (2, 2), QQ)
508
+ assert A.columnspace() == Acol
509
+
510
+
511
+ def test_DomainMatrix_rowspace():
512
+ A = DomainMatrix([[QQ(1), QQ(-1), QQ(1)], [QQ(2), QQ(-2), QQ(3)]], (2, 3), QQ)
513
+ assert A.rowspace() == A
514
+
515
+ Az = DomainMatrix([[ZZ(1), ZZ(-1), ZZ(1)], [ZZ(2), ZZ(-2), ZZ(3)]], (2, 3), ZZ)
516
+ raises(DMNotAField, lambda: Az.rowspace())
517
+
518
+ A = DomainMatrix([[QQ(1), QQ(-1), QQ(1)], [QQ(2), QQ(-2), QQ(3)]], (2, 3), QQ, fmt='sparse')
519
+ assert A.rowspace() == A
520
+
521
+
522
+ def test_DomainMatrix_nullspace():
523
+ A = DomainMatrix([[QQ(1), QQ(1)], [QQ(1), QQ(1)]], (2, 2), QQ)
524
+ Anull = DomainMatrix([[QQ(-1), QQ(1)]], (1, 2), QQ)
525
+ assert A.nullspace() == Anull
526
+
527
+ Az = DomainMatrix([[ZZ(1), ZZ(1)], [ZZ(1), ZZ(1)]], (2, 2), ZZ)
528
+ raises(DMNotAField, lambda: Az.nullspace())
529
+
530
+
531
+ def test_DomainMatrix_solve():
532
+ # XXX: Maybe the _solve method should be changed...
533
+ A = DomainMatrix([[QQ(1), QQ(2)], [QQ(2), QQ(4)]], (2, 2), QQ)
534
+ b = DomainMatrix([[QQ(1)], [QQ(2)]], (2, 1), QQ)
535
+ particular = DomainMatrix([[1, 0]], (1, 2), QQ)
536
+ nullspace = DomainMatrix([[-2, 1]], (1, 2), QQ)
537
+ assert A._solve(b) == (particular, nullspace)
538
+
539
+ b3 = DomainMatrix([[QQ(1)], [QQ(1)], [QQ(1)]], (3, 1), QQ)
540
+ raises(DMShapeError, lambda: A._solve(b3))
541
+
542
+ bz = DomainMatrix([[ZZ(1)], [ZZ(1)]], (2, 1), ZZ)
543
+ raises(DMNotAField, lambda: A._solve(bz))
544
+
545
+
546
+ def test_DomainMatrix_inv():
547
+ A = DomainMatrix([], (0, 0), QQ)
548
+ assert A.inv() == A
549
+
550
+ A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
551
+ Ainv = DomainMatrix([[QQ(-2), QQ(1)], [QQ(3, 2), QQ(-1, 2)]], (2, 2), QQ)
552
+ assert A.inv() == Ainv
553
+
554
+ Az = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
555
+ raises(DMNotAField, lambda: Az.inv())
556
+
557
+ Ans = DomainMatrix([[QQ(1), QQ(2)]], (1, 2), QQ)
558
+ raises(DMNonSquareMatrixError, lambda: Ans.inv())
559
+
560
+ Aninv = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(6)]], (2, 2), QQ)
561
+ raises(DMNonInvertibleMatrixError, lambda: Aninv.inv())
562
+
563
+
564
+ def test_DomainMatrix_det():
565
+ A = DomainMatrix([], (0, 0), ZZ)
566
+ assert A.det() == 1
567
+
568
+ A = DomainMatrix([[1]], (1, 1), ZZ)
569
+ assert A.det() == 1
570
+
571
+ A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
572
+ assert A.det() == ZZ(-2)
573
+
574
+ A = DomainMatrix([[ZZ(1), ZZ(2), ZZ(3)], [ZZ(1), ZZ(2), ZZ(4)], [ZZ(1), ZZ(3), ZZ(5)]], (3, 3), ZZ)
575
+ assert A.det() == ZZ(-1)
576
+
577
+ A = DomainMatrix([[ZZ(1), ZZ(2), ZZ(3)], [ZZ(1), ZZ(2), ZZ(4)], [ZZ(1), ZZ(2), ZZ(5)]], (3, 3), ZZ)
578
+ assert A.det() == ZZ(0)
579
+
580
+ Ans = DomainMatrix([[QQ(1), QQ(2)]], (1, 2), QQ)
581
+ raises(DMNonSquareMatrixError, lambda: Ans.det())
582
+
583
+ A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
584
+ assert A.det() == QQ(-2)
585
+
586
+
587
+ def test_DomainMatrix_lu():
588
+ A = DomainMatrix([], (0, 0), QQ)
589
+ assert A.lu() == (A, A, [])
590
+
591
+ A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
592
+ L = DomainMatrix([[QQ(1), QQ(0)], [QQ(3), QQ(1)]], (2, 2), QQ)
593
+ U = DomainMatrix([[QQ(1), QQ(2)], [QQ(0), QQ(-2)]], (2, 2), QQ)
594
+ swaps = []
595
+ assert A.lu() == (L, U, swaps)
596
+
597
+ A = DomainMatrix([[QQ(0), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
598
+ L = DomainMatrix([[QQ(1), QQ(0)], [QQ(0), QQ(1)]], (2, 2), QQ)
599
+ U = DomainMatrix([[QQ(3), QQ(4)], [QQ(0), QQ(2)]], (2, 2), QQ)
600
+ swaps = [(0, 1)]
601
+ assert A.lu() == (L, U, swaps)
602
+
603
+ A = DomainMatrix([[QQ(1), QQ(2)], [QQ(2), QQ(4)]], (2, 2), QQ)
604
+ L = DomainMatrix([[QQ(1), QQ(0)], [QQ(2), QQ(1)]], (2, 2), QQ)
605
+ U = DomainMatrix([[QQ(1), QQ(2)], [QQ(0), QQ(0)]], (2, 2), QQ)
606
+ swaps = []
607
+ assert A.lu() == (L, U, swaps)
608
+
609
+ A = DomainMatrix([[QQ(0), QQ(2)], [QQ(0), QQ(4)]], (2, 2), QQ)
610
+ L = DomainMatrix([[QQ(1), QQ(0)], [QQ(0), QQ(1)]], (2, 2), QQ)
611
+ U = DomainMatrix([[QQ(0), QQ(2)], [QQ(0), QQ(4)]], (2, 2), QQ)
612
+ swaps = []
613
+ assert A.lu() == (L, U, swaps)
614
+
615
+ A = DomainMatrix([[QQ(1), QQ(2), QQ(3)], [QQ(4), QQ(5), QQ(6)]], (2, 3), QQ)
616
+ L = DomainMatrix([[QQ(1), QQ(0)], [QQ(4), QQ(1)]], (2, 2), QQ)
617
+ U = DomainMatrix([[QQ(1), QQ(2), QQ(3)], [QQ(0), QQ(-3), QQ(-6)]], (2, 3), QQ)
618
+ swaps = []
619
+ assert A.lu() == (L, U, swaps)
620
+
621
+ A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]], (3, 2), QQ)
622
+ L = DomainMatrix([
623
+ [QQ(1), QQ(0), QQ(0)],
624
+ [QQ(3), QQ(1), QQ(0)],
625
+ [QQ(5), QQ(2), QQ(1)]], (3, 3), QQ)
626
+ U = DomainMatrix([[QQ(1), QQ(2)], [QQ(0), QQ(-2)], [QQ(0), QQ(0)]], (3, 2), QQ)
627
+ swaps = []
628
+ assert A.lu() == (L, U, swaps)
629
+
630
+ A = [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 1], [0, 0, 1, 2]]
631
+ L = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 1, 1]]
632
+ U = [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 1], [0, 0, 0, 1]]
633
+ to_dom = lambda rows, dom: [[dom(e) for e in row] for row in rows]
634
+ A = DomainMatrix(to_dom(A, QQ), (4, 4), QQ)
635
+ L = DomainMatrix(to_dom(L, QQ), (4, 4), QQ)
636
+ U = DomainMatrix(to_dom(U, QQ), (4, 4), QQ)
637
+ assert A.lu() == (L, U, [])
638
+
639
+ A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
640
+ raises(DMNotAField, lambda: A.lu())
641
+
642
+
643
+ def test_DomainMatrix_lu_solve():
644
+ # Base case
645
+ A = b = x = DomainMatrix([], (0, 0), QQ)
646
+ assert A.lu_solve(b) == x
647
+
648
+ # Basic example
649
+ A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
650
+ b = DomainMatrix([[QQ(1)], [QQ(2)]], (2, 1), QQ)
651
+ x = DomainMatrix([[QQ(0)], [QQ(1, 2)]], (2, 1), QQ)
652
+ assert A.lu_solve(b) == x
653
+
654
+ # Example with swaps
655
+ A = DomainMatrix([[QQ(0), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
656
+ b = DomainMatrix([[QQ(1)], [QQ(2)]], (2, 1), QQ)
657
+ x = DomainMatrix([[QQ(0)], [QQ(1, 2)]], (2, 1), QQ)
658
+ assert A.lu_solve(b) == x
659
+
660
+ # Non-invertible
661
+ A = DomainMatrix([[QQ(1), QQ(2)], [QQ(2), QQ(4)]], (2, 2), QQ)
662
+ b = DomainMatrix([[QQ(1)], [QQ(2)]], (2, 1), QQ)
663
+ raises(DMNonInvertibleMatrixError, lambda: A.lu_solve(b))
664
+
665
+ # Overdetermined, consistent
666
+ A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]], (3, 2), QQ)
667
+ b = DomainMatrix([[QQ(1)], [QQ(2)], [QQ(3)]], (3, 1), QQ)
668
+ x = DomainMatrix([[QQ(0)], [QQ(1, 2)]], (2, 1), QQ)
669
+ assert A.lu_solve(b) == x
670
+
671
+ # Overdetermined, inconsistent
672
+ A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]], (3, 2), QQ)
673
+ b = DomainMatrix([[QQ(1)], [QQ(2)], [QQ(4)]], (3, 1), QQ)
674
+ raises(DMNonInvertibleMatrixError, lambda: A.lu_solve(b))
675
+
676
+ # Underdetermined
677
+ A = DomainMatrix([[QQ(1), QQ(2)]], (1, 2), QQ)
678
+ b = DomainMatrix([[QQ(1)]], (1, 1), QQ)
679
+ raises(NotImplementedError, lambda: A.lu_solve(b))
680
+
681
+ # Non-field
682
+ A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
683
+ b = DomainMatrix([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ)
684
+ raises(DMNotAField, lambda: A.lu_solve(b))
685
+
686
+ # Shape mismatch
687
+ A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
688
+ b = DomainMatrix([[QQ(1), QQ(2)]], (1, 2), QQ)
689
+ raises(DMShapeError, lambda: A.lu_solve(b))
690
+
691
+
692
+ def test_DomainMatrix_charpoly():
693
+ A = DomainMatrix([], (0, 0), ZZ)
694
+ assert A.charpoly() == [ZZ(1)]
695
+
696
+ A = DomainMatrix([[1]], (1, 1), ZZ)
697
+ assert A.charpoly() == [ZZ(1), ZZ(-1)]
698
+
699
+ A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
700
+ assert A.charpoly() == [ZZ(1), ZZ(-5), ZZ(-2)]
701
+
702
+ A = DomainMatrix([[ZZ(1), ZZ(2), ZZ(3)], [ZZ(4), ZZ(5), ZZ(6)], [ZZ(7), ZZ(8), ZZ(9)]], (3, 3), ZZ)
703
+ assert A.charpoly() == [ZZ(1), ZZ(-15), ZZ(-18), ZZ(0)]
704
+
705
+ Ans = DomainMatrix([[QQ(1), QQ(2)]], (1, 2), QQ)
706
+ raises(DMNonSquareMatrixError, lambda: Ans.charpoly())
707
+
708
+
709
+ def test_DomainMatrix_eye():
710
+ A = DomainMatrix.eye(3, QQ)
711
+ assert A.rep == SDM.eye((3, 3), QQ)
712
+ assert A.shape == (3, 3)
713
+ assert A.domain == QQ
714
+
715
+
716
+ def test_DomainMatrix_zeros():
717
+ A = DomainMatrix.zeros((1, 2), QQ)
718
+ assert A.rep == SDM.zeros((1, 2), QQ)
719
+ assert A.shape == (1, 2)
720
+ assert A.domain == QQ
721
+
722
+
723
+ def test_DomainMatrix_ones():
724
+ A = DomainMatrix.ones((2, 3), QQ)
725
+ assert A.rep == DDM.ones((2, 3), QQ)
726
+ assert A.shape == (2, 3)
727
+ assert A.domain == QQ
728
+
729
+
730
+ def test_DomainMatrix_diag():
731
+ A = DomainMatrix({0:{0:ZZ(2)}, 1:{1:ZZ(3)}}, (2, 2), ZZ)
732
+ assert DomainMatrix.diag([ZZ(2), ZZ(3)], ZZ) == A
733
+
734
+ A = DomainMatrix({0:{0:ZZ(2)}, 1:{1:ZZ(3)}}, (3, 4), ZZ)
735
+ assert DomainMatrix.diag([ZZ(2), ZZ(3)], ZZ, (3, 4)) == A
736
+
737
+
738
+ def test_DomainMatrix_hstack():
739
+ A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
740
+ B = DomainMatrix([[ZZ(5), ZZ(6)], [ZZ(7), ZZ(8)]], (2, 2), ZZ)
741
+ C = DomainMatrix([[ZZ(9), ZZ(10)], [ZZ(11), ZZ(12)]], (2, 2), ZZ)
742
+
743
+ AB = DomainMatrix([
744
+ [ZZ(1), ZZ(2), ZZ(5), ZZ(6)],
745
+ [ZZ(3), ZZ(4), ZZ(7), ZZ(8)]], (2, 4), ZZ)
746
+ ABC = DomainMatrix([
747
+ [ZZ(1), ZZ(2), ZZ(5), ZZ(6), ZZ(9), ZZ(10)],
748
+ [ZZ(3), ZZ(4), ZZ(7), ZZ(8), ZZ(11), ZZ(12)]], (2, 6), ZZ)
749
+ assert A.hstack(B) == AB
750
+ assert A.hstack(B, C) == ABC
751
+
752
+
753
+ def test_DomainMatrix_vstack():
754
+ A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
755
+ B = DomainMatrix([[ZZ(5), ZZ(6)], [ZZ(7), ZZ(8)]], (2, 2), ZZ)
756
+ C = DomainMatrix([[ZZ(9), ZZ(10)], [ZZ(11), ZZ(12)]], (2, 2), ZZ)
757
+
758
+ AB = DomainMatrix([
759
+ [ZZ(1), ZZ(2)],
760
+ [ZZ(3), ZZ(4)],
761
+ [ZZ(5), ZZ(6)],
762
+ [ZZ(7), ZZ(8)]], (4, 2), ZZ)
763
+ ABC = DomainMatrix([
764
+ [ZZ(1), ZZ(2)],
765
+ [ZZ(3), ZZ(4)],
766
+ [ZZ(5), ZZ(6)],
767
+ [ZZ(7), ZZ(8)],
768
+ [ZZ(9), ZZ(10)],
769
+ [ZZ(11), ZZ(12)]], (6, 2), ZZ)
770
+ assert A.vstack(B) == AB
771
+ assert A.vstack(B, C) == ABC
772
+
773
+
774
+ def test_DomainMatrix_applyfunc():
775
+ A = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ)
776
+ B = DomainMatrix([[ZZ(2), ZZ(4)]], (1, 2), ZZ)
777
+ assert A.applyfunc(lambda x: 2*x) == B
778
+
779
+
780
+ def test_DomainMatrix_scalarmul():
781
+ A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
782
+ lamda = DomainScalar(QQ(3)/QQ(2), QQ)
783
+ assert A * lamda == DomainMatrix([[QQ(3, 2), QQ(3)], [QQ(9, 2), QQ(6)]], (2, 2), QQ)
784
+ assert A * 2 == DomainMatrix([[ZZ(2), ZZ(4)], [ZZ(6), ZZ(8)]], (2, 2), ZZ)
785
+ assert 2 * A == DomainMatrix([[ZZ(2), ZZ(4)], [ZZ(6), ZZ(8)]], (2, 2), ZZ)
786
+ assert A * DomainScalar(ZZ(0), ZZ) == DomainMatrix({}, (2, 2), ZZ)
787
+ assert A * DomainScalar(ZZ(1), ZZ) == A
788
+
789
+ raises(TypeError, lambda: A * 1.5)
790
+
791
+
792
+ def test_DomainMatrix_truediv():
793
+ A = DomainMatrix.from_Matrix(Matrix([[1, 2], [3, 4]]))
794
+ lamda = DomainScalar(QQ(3)/QQ(2), QQ)
795
+ assert A / lamda == DomainMatrix({0: {0: QQ(2, 3), 1: QQ(4, 3)}, 1: {0: QQ(2), 1: QQ(8, 3)}}, (2, 2), QQ)
796
+ b = DomainScalar(ZZ(1), ZZ)
797
+ assert A / b == DomainMatrix({0: {0: QQ(1), 1: QQ(2)}, 1: {0: QQ(3), 1: QQ(4)}}, (2, 2), QQ)
798
+
799
+ assert A / 1 == DomainMatrix({0: {0: QQ(1), 1: QQ(2)}, 1: {0: QQ(3), 1: QQ(4)}}, (2, 2), QQ)
800
+ assert A / 2 == DomainMatrix({0: {0: QQ(1, 2), 1: QQ(1)}, 1: {0: QQ(3, 2), 1: QQ(2)}}, (2, 2), QQ)
801
+
802
+ raises(ZeroDivisionError, lambda: A / 0)
803
+ raises(TypeError, lambda: A / 1.5)
804
+ raises(ZeroDivisionError, lambda: A / DomainScalar(ZZ(0), ZZ))
805
+
806
+
807
+ def test_DomainMatrix_getitem():
808
+ dM = DomainMatrix([
809
+ [ZZ(1), ZZ(2), ZZ(3)],
810
+ [ZZ(4), ZZ(5), ZZ(6)],
811
+ [ZZ(7), ZZ(8), ZZ(9)]], (3, 3), ZZ)
812
+
813
+ assert dM[1:,:-2] == DomainMatrix([[ZZ(4)], [ZZ(7)]], (2, 1), ZZ)
814
+ assert dM[2,:-2] == DomainMatrix([[ZZ(7)]], (1, 1), ZZ)
815
+ assert dM[:-2,:-2] == DomainMatrix([[ZZ(1)]], (1, 1), ZZ)
816
+ assert dM[:-1,0:2] == DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(4), ZZ(5)]], (2, 2), ZZ)
817
+ assert dM[:, -1] == DomainMatrix([[ZZ(3)], [ZZ(6)], [ZZ(9)]], (3, 1), ZZ)
818
+ assert dM[-1, :] == DomainMatrix([[ZZ(7), ZZ(8), ZZ(9)]], (1, 3), ZZ)
819
+ assert dM[::-1, :] == DomainMatrix([
820
+ [ZZ(7), ZZ(8), ZZ(9)],
821
+ [ZZ(4), ZZ(5), ZZ(6)],
822
+ [ZZ(1), ZZ(2), ZZ(3)]], (3, 3), ZZ)
823
+
824
+ raises(IndexError, lambda: dM[4, :-2])
825
+ raises(IndexError, lambda: dM[:-2, 4])
826
+
827
+ assert dM[1, 2] == DomainScalar(ZZ(6), ZZ)
828
+ assert dM[-2, 2] == DomainScalar(ZZ(6), ZZ)
829
+ assert dM[1, -2] == DomainScalar(ZZ(5), ZZ)
830
+ assert dM[-1, -3] == DomainScalar(ZZ(7), ZZ)
831
+
832
+ raises(IndexError, lambda: dM[3, 3])
833
+ raises(IndexError, lambda: dM[1, 4])
834
+ raises(IndexError, lambda: dM[-1, -4])
835
+
836
+ dM = DomainMatrix({0: {0: ZZ(1)}}, (10, 10), ZZ)
837
+ assert dM[5, 5] == DomainScalar(ZZ(0), ZZ)
838
+ assert dM[0, 0] == DomainScalar(ZZ(1), ZZ)
839
+
840
+ dM = DomainMatrix({1: {0: 1}}, (2,1), ZZ)
841
+ assert dM[0:, 0] == DomainMatrix({1: {0: 1}}, (2, 1), ZZ)
842
+ raises(IndexError, lambda: dM[3, 0])
843
+
844
+ dM = DomainMatrix({2: {2: ZZ(1)}, 4: {4: ZZ(1)}}, (5, 5), ZZ)
845
+ assert dM[:2,:2] == DomainMatrix({}, (2, 2), ZZ)
846
+ assert dM[2:,2:] == DomainMatrix({0: {0: 1}, 2: {2: 1}}, (3, 3), ZZ)
847
+ assert dM[3:,3:] == DomainMatrix({1: {1: 1}}, (2, 2), ZZ)
848
+ assert dM[2:, 6:] == DomainMatrix({}, (3, 0), ZZ)
849
+
850
+
851
+ def test_DomainMatrix_getitem_sympy():
852
+ dM = DomainMatrix({2: {2: ZZ(2)}, 4: {4: ZZ(1)}}, (5, 5), ZZ)
853
+ val1 = dM.getitem_sympy(0, 0)
854
+ assert val1 is S.Zero
855
+ val2 = dM.getitem_sympy(2, 2)
856
+ assert val2 == 2 and isinstance(val2, Integer)
857
+
858
+
859
+ def test_DomainMatrix_extract():
860
+ dM1 = DomainMatrix([
861
+ [ZZ(1), ZZ(2), ZZ(3)],
862
+ [ZZ(4), ZZ(5), ZZ(6)],
863
+ [ZZ(7), ZZ(8), ZZ(9)]], (3, 3), ZZ)
864
+ dM2 = DomainMatrix([
865
+ [ZZ(1), ZZ(3)],
866
+ [ZZ(7), ZZ(9)]], (2, 2), ZZ)
867
+ assert dM1.extract([0, 2], [0, 2]) == dM2
868
+ assert dM1.to_sparse().extract([0, 2], [0, 2]) == dM2.to_sparse()
869
+ assert dM1.extract([0, -1], [0, -1]) == dM2
870
+ assert dM1.to_sparse().extract([0, -1], [0, -1]) == dM2.to_sparse()
871
+
872
+ dM3 = DomainMatrix([
873
+ [ZZ(1), ZZ(2), ZZ(2)],
874
+ [ZZ(4), ZZ(5), ZZ(5)],
875
+ [ZZ(4), ZZ(5), ZZ(5)]], (3, 3), ZZ)
876
+ assert dM1.extract([0, 1, 1], [0, 1, 1]) == dM3
877
+ assert dM1.to_sparse().extract([0, 1, 1], [0, 1, 1]) == dM3.to_sparse()
878
+
879
+ empty = [
880
+ ([], [], (0, 0)),
881
+ ([1], [], (1, 0)),
882
+ ([], [1], (0, 1)),
883
+ ]
884
+ for rows, cols, size in empty:
885
+ assert dM1.extract(rows, cols) == DomainMatrix.zeros(size, ZZ).to_dense()
886
+ assert dM1.to_sparse().extract(rows, cols) == DomainMatrix.zeros(size, ZZ)
887
+
888
+ dM = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
889
+ bad_indices = [([2], [0]), ([0], [2]), ([-3], [0]), ([0], [-3])]
890
+ for rows, cols in bad_indices:
891
+ raises(IndexError, lambda: dM.extract(rows, cols))
892
+ raises(IndexError, lambda: dM.to_sparse().extract(rows, cols))
893
+
894
+
895
+ def test_DomainMatrix_setitem():
896
+ dM = DomainMatrix({2: {2: ZZ(1)}, 4: {4: ZZ(1)}}, (5, 5), ZZ)
897
+ dM[2, 2] = ZZ(2)
898
+ assert dM == DomainMatrix({2: {2: ZZ(2)}, 4: {4: ZZ(1)}}, (5, 5), ZZ)
899
+ def setitem(i, j, val):
900
+ dM[i, j] = val
901
+ raises(TypeError, lambda: setitem(2, 2, QQ(1, 2)))
902
+ raises(NotImplementedError, lambda: setitem(slice(1, 2), 2, ZZ(1)))
903
+
904
+
905
+ def test_DomainMatrix_pickling():
906
+ import pickle
907
+ dM = DomainMatrix({2: {2: ZZ(1)}, 4: {4: ZZ(1)}}, (5, 5), ZZ)
908
+ assert pickle.loads(pickle.dumps(dM)) == dM
909
+ dM = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
910
+ assert pickle.loads(pickle.dumps(dM)) == dM
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_domainscalar.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.testing.pytest import raises
2
+
3
+ from sympy.core.symbol import S
4
+ from sympy.polys import ZZ, QQ
5
+ from sympy.polys.matrices.domainscalar import DomainScalar
6
+ from sympy.polys.matrices.domainmatrix import DomainMatrix
7
+
8
+
9
+ def test_DomainScalar___new__():
10
+ raises(TypeError, lambda: DomainScalar(ZZ(1), QQ))
11
+ raises(TypeError, lambda: DomainScalar(ZZ(1), 1))
12
+
13
+
14
+ def test_DomainScalar_new():
15
+ A = DomainScalar(ZZ(1), ZZ)
16
+ B = A.new(ZZ(4), ZZ)
17
+ assert B == DomainScalar(ZZ(4), ZZ)
18
+
19
+
20
+ def test_DomainScalar_repr():
21
+ A = DomainScalar(ZZ(1), ZZ)
22
+ assert repr(A) in {'1', 'mpz(1)'}
23
+
24
+
25
+ def test_DomainScalar_from_sympy():
26
+ expr = S(1)
27
+ B = DomainScalar.from_sympy(expr)
28
+ assert B == DomainScalar(ZZ(1), ZZ)
29
+
30
+
31
+ def test_DomainScalar_to_sympy():
32
+ B = DomainScalar(ZZ(1), ZZ)
33
+ expr = B.to_sympy()
34
+ assert expr.is_Integer and expr == 1
35
+
36
+
37
+ def test_DomainScalar_to_domain():
38
+ A = DomainScalar(ZZ(1), ZZ)
39
+ B = A.to_domain(QQ)
40
+ assert B == DomainScalar(QQ(1), QQ)
41
+
42
+
43
+ def test_DomainScalar_convert_to():
44
+ A = DomainScalar(ZZ(1), ZZ)
45
+ B = A.convert_to(QQ)
46
+ assert B == DomainScalar(QQ(1), QQ)
47
+
48
+
49
+ def test_DomainScalar_unify():
50
+ A = DomainScalar(ZZ(1), ZZ)
51
+ B = DomainScalar(QQ(2), QQ)
52
+ A, B = A.unify(B)
53
+ assert A.domain == B.domain == QQ
54
+
55
+
56
+ def test_DomainScalar_add():
57
+ A = DomainScalar(ZZ(1), ZZ)
58
+ B = DomainScalar(QQ(2), QQ)
59
+ assert A + B == DomainScalar(QQ(3), QQ)
60
+
61
+ raises(TypeError, lambda: A + 1.5)
62
+
63
+ def test_DomainScalar_sub():
64
+ A = DomainScalar(ZZ(1), ZZ)
65
+ B = DomainScalar(QQ(2), QQ)
66
+ assert A - B == DomainScalar(QQ(-1), QQ)
67
+
68
+ raises(TypeError, lambda: A - 1.5)
69
+
70
+ def test_DomainScalar_mul():
71
+ A = DomainScalar(ZZ(1), ZZ)
72
+ B = DomainScalar(QQ(2), QQ)
73
+ dm = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
74
+ assert A * B == DomainScalar(QQ(2), QQ)
75
+ assert A * dm == dm
76
+ assert B * 2 == DomainScalar(QQ(4), QQ)
77
+
78
+ raises(TypeError, lambda: A * 1.5)
79
+
80
+
81
+ def test_DomainScalar_floordiv():
82
+ A = DomainScalar(ZZ(-5), ZZ)
83
+ B = DomainScalar(QQ(2), QQ)
84
+ assert A // B == DomainScalar(QQ(-5, 2), QQ)
85
+ C = DomainScalar(ZZ(2), ZZ)
86
+ assert A // C == DomainScalar(ZZ(-3), ZZ)
87
+
88
+ raises(TypeError, lambda: A // 1.5)
89
+
90
+
91
+ def test_DomainScalar_mod():
92
+ A = DomainScalar(ZZ(5), ZZ)
93
+ B = DomainScalar(QQ(2), QQ)
94
+ assert A % B == DomainScalar(QQ(0), QQ)
95
+ C = DomainScalar(ZZ(2), ZZ)
96
+ assert A % C == DomainScalar(ZZ(1), ZZ)
97
+
98
+ raises(TypeError, lambda: A % 1.5)
99
+
100
+
101
+ def test_DomainScalar_divmod():
102
+ A = DomainScalar(ZZ(5), ZZ)
103
+ B = DomainScalar(QQ(2), QQ)
104
+ assert divmod(A, B) == (DomainScalar(QQ(5, 2), QQ), DomainScalar(QQ(0), QQ))
105
+ C = DomainScalar(ZZ(2), ZZ)
106
+ assert divmod(A, C) == (DomainScalar(ZZ(2), ZZ), DomainScalar(ZZ(1), ZZ))
107
+
108
+ raises(TypeError, lambda: divmod(A, 1.5))
109
+
110
+
111
+ def test_DomainScalar_pow():
112
+ A = DomainScalar(ZZ(-5), ZZ)
113
+ B = A**(2)
114
+ assert B == DomainScalar(ZZ(25), ZZ)
115
+
116
+ raises(TypeError, lambda: A**(1.5))
117
+
118
+
119
+ def test_DomainScalar_pos():
120
+ A = DomainScalar(QQ(2), QQ)
121
+ B = DomainScalar(QQ(2), QQ)
122
+ assert +A == B
123
+
124
+
125
+ def test_DomainScalar_eq():
126
+ A = DomainScalar(QQ(2), QQ)
127
+ assert A == A
128
+ B = DomainScalar(ZZ(-5), ZZ)
129
+ assert A != B
130
+ C = DomainScalar(ZZ(2), ZZ)
131
+ assert A != C
132
+ D = [1]
133
+ assert A != D
134
+
135
+
136
+ def test_DomainScalar_isZero():
137
+ A = DomainScalar(ZZ(0), ZZ)
138
+ assert A.is_zero() == True
139
+ B = DomainScalar(ZZ(1), ZZ)
140
+ assert B.is_zero() == False
141
+
142
+
143
+ def test_DomainScalar_isOne():
144
+ A = DomainScalar(ZZ(1), ZZ)
145
+ assert A.is_one() == True
146
+ B = DomainScalar(ZZ(0), ZZ)
147
+ assert B.is_one() == False
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_eigen.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Tests for the sympy.polys.matrices.eigen module
3
+ """
4
+
5
+ from sympy.core.singleton import S
6
+ from sympy.functions.elementary.miscellaneous import sqrt
7
+ from sympy.matrices.dense import Matrix
8
+
9
+ from sympy.polys.agca.extensions import FiniteExtension
10
+ from sympy.polys.domains import QQ
11
+ from sympy.polys.polytools import Poly
12
+ from sympy.polys.rootoftools import CRootOf
13
+ from sympy.polys.matrices.domainmatrix import DomainMatrix
14
+
15
+ from sympy.polys.matrices.eigen import dom_eigenvects, dom_eigenvects_to_sympy
16
+
17
+
18
+ def test_dom_eigenvects_rational():
19
+ # Rational eigenvalues
20
+ A = DomainMatrix([[QQ(1), QQ(2)], [QQ(1), QQ(2)]], (2, 2), QQ)
21
+ rational_eigenvects = [
22
+ (QQ, QQ(3), 1, DomainMatrix([[QQ(1), QQ(1)]], (1, 2), QQ)),
23
+ (QQ, QQ(0), 1, DomainMatrix([[QQ(-2), QQ(1)]], (1, 2), QQ)),
24
+ ]
25
+ assert dom_eigenvects(A) == (rational_eigenvects, [])
26
+
27
+ # Test converting to Expr:
28
+ sympy_eigenvects = [
29
+ (S(3), 1, [Matrix([1, 1])]),
30
+ (S(0), 1, [Matrix([-2, 1])]),
31
+ ]
32
+ assert dom_eigenvects_to_sympy(rational_eigenvects, [], Matrix) == sympy_eigenvects
33
+
34
+
35
+ def test_dom_eigenvects_algebraic():
36
+ # Algebraic eigenvalues
37
+ A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
38
+ Avects = dom_eigenvects(A)
39
+
40
+ # Extract the dummy to build the expected result:
41
+ lamda = Avects[1][0][1].gens[0]
42
+ irreducible = Poly(lamda**2 - 5*lamda - 2, lamda, domain=QQ)
43
+ K = FiniteExtension(irreducible)
44
+ KK = K.from_sympy
45
+ algebraic_eigenvects = [
46
+ (K, irreducible, 1, DomainMatrix([[KK((lamda-4)/3), KK(1)]], (1, 2), K)),
47
+ ]
48
+ assert Avects == ([], algebraic_eigenvects)
49
+
50
+ # Test converting to Expr:
51
+ sympy_eigenvects = [
52
+ (S(5)/2 - sqrt(33)/2, 1, [Matrix([[-sqrt(33)/6 - S(1)/2], [1]])]),
53
+ (S(5)/2 + sqrt(33)/2, 1, [Matrix([[-S(1)/2 + sqrt(33)/6], [1]])]),
54
+ ]
55
+ assert dom_eigenvects_to_sympy([], algebraic_eigenvects, Matrix) == sympy_eigenvects
56
+
57
+
58
+ def test_dom_eigenvects_rootof():
59
+ # Algebraic eigenvalues
60
+ A = DomainMatrix([
61
+ [0, 0, 0, 0, -1],
62
+ [1, 0, 0, 0, 1],
63
+ [0, 1, 0, 0, 0],
64
+ [0, 0, 1, 0, 0],
65
+ [0, 0, 0, 1, 0]], (5, 5), QQ)
66
+ Avects = dom_eigenvects(A)
67
+
68
+ # Extract the dummy to build the expected result:
69
+ lamda = Avects[1][0][1].gens[0]
70
+ irreducible = Poly(lamda**5 - lamda + 1, lamda, domain=QQ)
71
+ K = FiniteExtension(irreducible)
72
+ KK = K.from_sympy
73
+ algebraic_eigenvects = [
74
+ (K, irreducible, 1,
75
+ DomainMatrix([
76
+ [KK(lamda**4-1), KK(lamda**3), KK(lamda**2), KK(lamda), KK(1)]
77
+ ], (1, 5), K)),
78
+ ]
79
+ assert Avects == ([], algebraic_eigenvects)
80
+
81
+ # Test converting to Expr (slow):
82
+ l0, l1, l2, l3, l4 = [CRootOf(lamda**5 - lamda + 1, i) for i in range(5)]
83
+ sympy_eigenvects = [
84
+ (l0, 1, [Matrix([-1 + l0**4, l0**3, l0**2, l0, 1])]),
85
+ (l1, 1, [Matrix([-1 + l1**4, l1**3, l1**2, l1, 1])]),
86
+ (l2, 1, [Matrix([-1 + l2**4, l2**3, l2**2, l2, 1])]),
87
+ (l3, 1, [Matrix([-1 + l3**4, l3**3, l3**2, l3, 1])]),
88
+ (l4, 1, [Matrix([-1 + l4**4, l4**3, l4**2, l4, 1])]),
89
+ ]
90
+ assert dom_eigenvects_to_sympy([], algebraic_eigenvects, Matrix) == sympy_eigenvects
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_linsolve.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # test_linsolve.py
3
+ #
4
+ # Test the internal implementation of linsolve.
5
+ #
6
+
7
+ from sympy.testing.pytest import raises
8
+
9
+ from sympy.core.numbers import I
10
+ from sympy.core.relational import Eq
11
+ from sympy.core.singleton import S
12
+ from sympy.abc import x, y, z
13
+
14
+ from sympy.polys.matrices.linsolve import _linsolve
15
+ from sympy.polys.solvers import PolyNonlinearError
16
+
17
+
18
+ def test__linsolve():
19
+ assert _linsolve([], [x]) == {x:x}
20
+ assert _linsolve([S.Zero], [x]) == {x:x}
21
+ assert _linsolve([x-1,x-2], [x]) is None
22
+ assert _linsolve([x-1], [x]) == {x:1}
23
+ assert _linsolve([x-1, y], [x, y]) == {x:1, y:S.Zero}
24
+ assert _linsolve([2*I], [x]) is None
25
+ raises(PolyNonlinearError, lambda: _linsolve([x*(1 + x)], [x]))
26
+
27
+
28
+ def test__linsolve_float():
29
+
30
+ # This should give the exact answer:
31
+ eqs = [
32
+ y - x,
33
+ y - 0.0216 * x
34
+ ]
35
+ sol = {x:0.0, y:0.0}
36
+ assert _linsolve(eqs, (x, y)) == sol
37
+
38
+ # Other cases should be close to eps
39
+
40
+ def all_close(sol1, sol2, eps=1e-15):
41
+ close = lambda a, b: abs(a - b) < eps
42
+ assert sol1.keys() == sol2.keys()
43
+ return all(close(sol1[s], sol2[s]) for s in sol1)
44
+
45
+ eqs = [
46
+ 0.8*x + 0.8*z + 0.2,
47
+ 0.9*x + 0.7*y + 0.2*z + 0.9,
48
+ 0.7*x + 0.2*y + 0.2*z + 0.5
49
+ ]
50
+ sol_exact = {x:-29/42, y:-11/21, z:37/84}
51
+ sol_linsolve = _linsolve(eqs, [x,y,z])
52
+ assert all_close(sol_exact, sol_linsolve)
53
+
54
+ eqs = [
55
+ 0.9*x + 0.3*y + 0.4*z + 0.6,
56
+ 0.6*x + 0.9*y + 0.1*z + 0.7,
57
+ 0.4*x + 0.6*y + 0.9*z + 0.5
58
+ ]
59
+ sol_exact = {x:-88/175, y:-46/105, z:-1/25}
60
+ sol_linsolve = _linsolve(eqs, [x,y,z])
61
+ assert all_close(sol_exact, sol_linsolve)
62
+
63
+ eqs = [
64
+ 0.4*x + 0.3*y + 0.6*z + 0.7,
65
+ 0.4*x + 0.3*y + 0.9*z + 0.9,
66
+ 0.7*x + 0.9*y,
67
+ ]
68
+ sol_exact = {x:-9/5, y:7/5, z:-2/3}
69
+ sol_linsolve = _linsolve(eqs, [x,y,z])
70
+ assert all_close(sol_exact, sol_linsolve)
71
+
72
+ eqs = [
73
+ x*(0.7 + 0.6*I) + y*(0.4 + 0.7*I) + z*(0.9 + 0.1*I) + 0.5,
74
+ 0.2*I*x + 0.2*I*y + z*(0.9 + 0.2*I) + 0.1,
75
+ x*(0.9 + 0.7*I) + y*(0.9 + 0.7*I) + z*(0.9 + 0.4*I) + 0.4,
76
+ ]
77
+ sol_exact = {
78
+ x:-6157/7995 - 411/5330*I,
79
+ y:8519/15990 + 1784/7995*I,
80
+ z:-34/533 + 107/1599*I,
81
+ }
82
+ sol_linsolve = _linsolve(eqs, [x,y,z])
83
+ assert all_close(sol_exact, sol_linsolve)
84
+
85
+ # XXX: This system for x and y over RR(z) is problematic.
86
+ #
87
+ # eqs = [
88
+ # x*(0.2*z + 0.9) + y*(0.5*z + 0.8) + 0.6,
89
+ # 0.1*x*z + y*(0.1*z + 0.6) + 0.9,
90
+ # ]
91
+ #
92
+ # linsolve(eqs, [x, y])
93
+ # The solution for x comes out as
94
+ #
95
+ # -3.9e-5*z**2 - 3.6e-5*z - 8.67361737988404e-20
96
+ # x = ----------------------------------------------
97
+ # 3.0e-6*z**3 - 1.3e-5*z**2 - 5.4e-5*z
98
+ #
99
+ # The 8e-20 in the numerator should be zero which would allow z to cancel
100
+ # from top and bottom. It should be possible to avoid this somehow because
101
+ # the inverse of the matrix only has a quadratic factor (the determinant)
102
+ # in the denominator.
103
+
104
+
105
+ def test__linsolve_deprecated():
106
+ raises(PolyNonlinearError, lambda:
107
+ _linsolve([Eq(x**2, x**2 + y)], [x, y]))
108
+ raises(PolyNonlinearError, lambda:
109
+ _linsolve([(x + y)**2 - x**2], [x]))
110
+ raises(PolyNonlinearError, lambda:
111
+ _linsolve([Eq((x + y)**2, x**2)], [x]))
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_lll.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.polys.domains import ZZ, QQ
2
+ from sympy.polys.matrices import DM
3
+ from sympy.polys.matrices.domainmatrix import DomainMatrix
4
+ from sympy.polys.matrices.exceptions import DMRankError, DMValueError, DMShapeError, DMDomainError
5
+ from sympy.polys.matrices.lll import _ddm_lll, ddm_lll, ddm_lll_transform
6
+ from sympy.testing.pytest import raises
7
+
8
+
9
+ def test_lll():
10
+ normal_test_data = [
11
+ (
12
+ DM([[1, 0, 0, 0, -20160],
13
+ [0, 1, 0, 0, 33768],
14
+ [0, 0, 1, 0, 39578],
15
+ [0, 0, 0, 1, 47757]], ZZ),
16
+ DM([[10, -3, -2, 8, -4],
17
+ [3, -9, 8, 1, -11],
18
+ [-3, 13, -9, -3, -9],
19
+ [-12, -7, -11, 9, -1]], ZZ)
20
+ ),
21
+ (
22
+ DM([[20, 52, 3456],
23
+ [14, 31, -1],
24
+ [34, -442, 0]], ZZ),
25
+ DM([[14, 31, -1],
26
+ [188, -101, -11],
27
+ [236, 13, 3443]], ZZ)
28
+ ),
29
+ (
30
+ DM([[34, -1, -86, 12],
31
+ [-54, 34, 55, 678],
32
+ [23, 3498, 234, 6783],
33
+ [87, 49, 665, 11]], ZZ),
34
+ DM([[34, -1, -86, 12],
35
+ [291, 43, 149, 83],
36
+ [-54, 34, 55, 678],
37
+ [-189, 3077, -184, -223]], ZZ)
38
+ )
39
+ ]
40
+ delta = QQ(5, 6)
41
+ for basis_dm, reduced_dm in normal_test_data:
42
+ reduced = _ddm_lll(basis_dm.rep, delta=delta)[0]
43
+ assert reduced == reduced_dm.rep
44
+
45
+ reduced = ddm_lll(basis_dm.rep, delta=delta)
46
+ assert reduced == reduced_dm.rep
47
+
48
+ reduced, transform = _ddm_lll(basis_dm.rep, delta=delta, return_transform=True)
49
+ assert reduced == reduced_dm.rep
50
+ assert transform.matmul(basis_dm.rep) == reduced_dm.rep
51
+
52
+ reduced, transform = ddm_lll_transform(basis_dm.rep, delta=delta)
53
+ assert reduced == reduced_dm.rep
54
+ assert transform.matmul(basis_dm.rep) == reduced_dm.rep
55
+
56
+ reduced = basis_dm.rep.lll(delta=delta)
57
+ assert reduced == reduced_dm.rep
58
+
59
+ reduced, transform = basis_dm.rep.lll_transform(delta=delta)
60
+ assert reduced == reduced_dm.rep
61
+ assert transform.matmul(basis_dm.rep) == reduced_dm.rep
62
+
63
+ reduced = basis_dm.rep.to_sdm().lll(delta=delta)
64
+ assert reduced == reduced_dm.rep.to_sdm()
65
+
66
+ reduced, transform = basis_dm.rep.to_sdm().lll_transform(delta=delta)
67
+ assert reduced == reduced_dm.rep.to_sdm()
68
+ assert transform.matmul(basis_dm.rep.to_sdm()) == reduced_dm.rep.to_sdm()
69
+
70
+ reduced = basis_dm.lll(delta=delta)
71
+ assert reduced == reduced_dm
72
+
73
+ reduced, transform = basis_dm.lll_transform(delta=delta)
74
+ assert reduced == reduced_dm
75
+ assert transform.matmul(basis_dm) == reduced_dm
76
+
77
+
78
+ def test_lll_linear_dependent():
79
+ linear_dependent_test_data = [
80
+ DM([[0, -1, -2, -3],
81
+ [1, 0, -1, -2],
82
+ [2, 1, 0, -1],
83
+ [3, 2, 1, 0]], ZZ),
84
+ DM([[1, 0, 0, 1],
85
+ [0, 1, 0, 1],
86
+ [0, 0, 1, 1],
87
+ [1, 2, 3, 6]], ZZ),
88
+ DM([[3, -5, 1],
89
+ [4, 6, 0],
90
+ [10, -4, 2]], ZZ)
91
+ ]
92
+ for not_basis in linear_dependent_test_data:
93
+ raises(DMRankError, lambda: _ddm_lll(not_basis.rep))
94
+ raises(DMRankError, lambda: ddm_lll(not_basis.rep))
95
+ raises(DMRankError, lambda: not_basis.rep.lll())
96
+ raises(DMRankError, lambda: not_basis.rep.to_sdm().lll())
97
+ raises(DMRankError, lambda: not_basis.lll())
98
+ raises(DMRankError, lambda: _ddm_lll(not_basis.rep, return_transform=True))
99
+ raises(DMRankError, lambda: ddm_lll_transform(not_basis.rep))
100
+ raises(DMRankError, lambda: not_basis.rep.lll_transform())
101
+ raises(DMRankError, lambda: not_basis.rep.to_sdm().lll_transform())
102
+ raises(DMRankError, lambda: not_basis.lll_transform())
103
+
104
+
105
+ def test_lll_wrong_delta():
106
+ dummy_matrix = DomainMatrix.ones((3, 3), ZZ)
107
+ for wrong_delta in [QQ(-1, 4), QQ(0, 1), QQ(1, 4), QQ(1, 1), QQ(100, 1)]:
108
+ raises(DMValueError, lambda: _ddm_lll(dummy_matrix.rep, delta=wrong_delta))
109
+ raises(DMValueError, lambda: ddm_lll(dummy_matrix.rep, delta=wrong_delta))
110
+ raises(DMValueError, lambda: dummy_matrix.rep.lll(delta=wrong_delta))
111
+ raises(DMValueError, lambda: dummy_matrix.rep.to_sdm().lll(delta=wrong_delta))
112
+ raises(DMValueError, lambda: dummy_matrix.lll(delta=wrong_delta))
113
+ raises(DMValueError, lambda: _ddm_lll(dummy_matrix.rep, delta=wrong_delta, return_transform=True))
114
+ raises(DMValueError, lambda: ddm_lll_transform(dummy_matrix.rep, delta=wrong_delta))
115
+ raises(DMValueError, lambda: dummy_matrix.rep.lll_transform(delta=wrong_delta))
116
+ raises(DMValueError, lambda: dummy_matrix.rep.to_sdm().lll_transform(delta=wrong_delta))
117
+ raises(DMValueError, lambda: dummy_matrix.lll_transform(delta=wrong_delta))
118
+
119
+
120
+ def test_lll_wrong_shape():
121
+ wrong_shape_matrix = DomainMatrix.ones((4, 3), ZZ)
122
+ raises(DMShapeError, lambda: _ddm_lll(wrong_shape_matrix.rep))
123
+ raises(DMShapeError, lambda: ddm_lll(wrong_shape_matrix.rep))
124
+ raises(DMShapeError, lambda: wrong_shape_matrix.rep.lll())
125
+ raises(DMShapeError, lambda: wrong_shape_matrix.rep.to_sdm().lll())
126
+ raises(DMShapeError, lambda: wrong_shape_matrix.lll())
127
+ raises(DMShapeError, lambda: _ddm_lll(wrong_shape_matrix.rep, return_transform=True))
128
+ raises(DMShapeError, lambda: ddm_lll_transform(wrong_shape_matrix.rep))
129
+ raises(DMShapeError, lambda: wrong_shape_matrix.rep.lll_transform())
130
+ raises(DMShapeError, lambda: wrong_shape_matrix.rep.to_sdm().lll_transform())
131
+ raises(DMShapeError, lambda: wrong_shape_matrix.lll_transform())
132
+
133
+
134
+ def test_lll_wrong_domain():
135
+ wrong_domain_matrix = DomainMatrix.ones((3, 3), QQ)
136
+ raises(DMDomainError, lambda: _ddm_lll(wrong_domain_matrix.rep))
137
+ raises(DMDomainError, lambda: ddm_lll(wrong_domain_matrix.rep))
138
+ raises(DMDomainError, lambda: wrong_domain_matrix.rep.lll())
139
+ raises(DMDomainError, lambda: wrong_domain_matrix.rep.to_sdm().lll())
140
+ raises(DMDomainError, lambda: wrong_domain_matrix.lll())
141
+ raises(DMDomainError, lambda: _ddm_lll(wrong_domain_matrix.rep, return_transform=True))
142
+ raises(DMDomainError, lambda: ddm_lll_transform(wrong_domain_matrix.rep))
143
+ raises(DMDomainError, lambda: wrong_domain_matrix.rep.lll_transform())
144
+ raises(DMDomainError, lambda: wrong_domain_matrix.rep.to_sdm().lll_transform())
145
+ raises(DMDomainError, lambda: wrong_domain_matrix.lll_transform())
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_normalforms.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.testing.pytest import raises
2
+
3
+ from sympy.core.symbol import Symbol
4
+ from sympy.polys.matrices.normalforms import (
5
+ invariant_factors, smith_normal_form,
6
+ hermite_normal_form, _hermite_normal_form, _hermite_normal_form_modulo_D)
7
+ from sympy.polys.domains import ZZ, QQ
8
+ from sympy.polys.matrices import DomainMatrix, DM
9
+ from sympy.polys.matrices.exceptions import DMDomainError, DMShapeError
10
+
11
+
12
+ def test_smith_normal():
13
+
14
+ m = DM([[12, 6, 4, 8], [3, 9, 6, 12], [2, 16, 14, 28], [20, 10, 10, 20]], ZZ)
15
+ smf = DM([[1, 0, 0, 0], [0, 10, 0, 0], [0, 0, -30, 0], [0, 0, 0, 0]], ZZ)
16
+ assert smith_normal_form(m).to_dense() == smf
17
+
18
+ x = Symbol('x')
19
+ m = DM([[x-1, 1, -1],
20
+ [ 0, x, -1],
21
+ [ 0, -1, x]], QQ[x])
22
+ dx = m.domain.gens[0]
23
+ assert invariant_factors(m) == (1, dx-1, dx**2-1)
24
+
25
+ zr = DomainMatrix([], (0, 2), ZZ)
26
+ zc = DomainMatrix([[], []], (2, 0), ZZ)
27
+ assert smith_normal_form(zr).to_dense() == zr
28
+ assert smith_normal_form(zc).to_dense() == zc
29
+
30
+ assert smith_normal_form(DM([[2, 4]], ZZ)).to_dense() == DM([[2, 0]], ZZ)
31
+ assert smith_normal_form(DM([[0, -2]], ZZ)).to_dense() == DM([[-2, 0]], ZZ)
32
+ assert smith_normal_form(DM([[0], [-2]], ZZ)).to_dense() == DM([[-2], [0]], ZZ)
33
+
34
+ m = DM([[3, 0, 0, 0], [0, 0, 0, 0], [0, 0, 2, 0]], ZZ)
35
+ snf = DM([[1, 0, 0, 0], [0, 6, 0, 0], [0, 0, 0, 0]], ZZ)
36
+ assert smith_normal_form(m).to_dense() == snf
37
+
38
+ raises(ValueError, lambda: smith_normal_form(DM([[1]], ZZ[x])))
39
+
40
+
41
+ def test_hermite_normal():
42
+ m = DM([[2, 7, 17, 29, 41], [3, 11, 19, 31, 43], [5, 13, 23, 37, 47]], ZZ)
43
+ hnf = DM([[1, 0, 0], [0, 2, 1], [0, 0, 1]], ZZ)
44
+ assert hermite_normal_form(m) == hnf
45
+ assert hermite_normal_form(m, D=ZZ(2)) == hnf
46
+ assert hermite_normal_form(m, D=ZZ(2), check_rank=True) == hnf
47
+
48
+ m = m.transpose()
49
+ hnf = DM([[37, 0, 19], [222, -6, 113], [48, 0, 25], [0, 2, 1], [0, 0, 1]], ZZ)
50
+ assert hermite_normal_form(m) == hnf
51
+ raises(DMShapeError, lambda: _hermite_normal_form_modulo_D(m, ZZ(96)))
52
+ raises(DMDomainError, lambda: _hermite_normal_form_modulo_D(m, QQ(96)))
53
+
54
+ m = DM([[8, 28, 68, 116, 164], [3, 11, 19, 31, 43], [5, 13, 23, 37, 47]], ZZ)
55
+ hnf = DM([[4, 0, 0], [0, 2, 1], [0, 0, 1]], ZZ)
56
+ assert hermite_normal_form(m) == hnf
57
+ assert hermite_normal_form(m, D=ZZ(8)) == hnf
58
+ assert hermite_normal_form(m, D=ZZ(8), check_rank=True) == hnf
59
+
60
+ m = DM([[10, 8, 6, 30, 2], [45, 36, 27, 18, 9], [5, 4, 3, 2, 1]], ZZ)
61
+ hnf = DM([[26, 2], [0, 9], [0, 1]], ZZ)
62
+ assert hermite_normal_form(m) == hnf
63
+
64
+ m = DM([[2, 7], [0, 0], [0, 0]], ZZ)
65
+ hnf = DM([[1], [0], [0]], ZZ)
66
+ assert hermite_normal_form(m) == hnf
67
+
68
+ m = DM([[-2, 1], [0, 1]], ZZ)
69
+ hnf = DM([[2, 1], [0, 1]], ZZ)
70
+ assert hermite_normal_form(m) == hnf
71
+
72
+ m = DomainMatrix([[QQ(1)]], (1, 1), QQ)
73
+ raises(DMDomainError, lambda: hermite_normal_form(m))
74
+ raises(DMDomainError, lambda: _hermite_normal_form(m))
75
+ raises(DMDomainError, lambda: _hermite_normal_form_modulo_D(m, ZZ(1)))
llmeval-env/lib/python3.10/site-packages/sympy/polys/matrices/tests/test_sdm.py ADDED
@@ -0,0 +1,444 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Tests for the basic functionality of the SDM class.
3
+ """
4
+
5
+ from itertools import product
6
+
7
+ from sympy.core.singleton import S
8
+ from sympy.external.gmpy import HAS_GMPY
9
+ from sympy.testing.pytest import raises
10
+
11
+ from sympy.polys.domains import QQ, ZZ, EXRAW
12
+ from sympy.polys.matrices.sdm import SDM
13
+ from sympy.polys.matrices.ddm import DDM
14
+ from sympy.polys.matrices.exceptions import (DMBadInputError, DMDomainError,
15
+ DMShapeError)
16
+
17
+
18
+ def test_SDM():
19
+ A = SDM({0:{0:ZZ(1)}}, (2, 2), ZZ)
20
+ assert A.domain == ZZ
21
+ assert A.shape == (2, 2)
22
+ assert dict(A) == {0:{0:ZZ(1)}}
23
+
24
+ raises(DMBadInputError, lambda: SDM({5:{1:ZZ(0)}}, (2, 2), ZZ))
25
+ raises(DMBadInputError, lambda: SDM({0:{5:ZZ(0)}}, (2, 2), ZZ))
26
+
27
+
28
+ def test_DDM_str():
29
+ sdm = SDM({0:{0:ZZ(1)}, 1:{1:ZZ(1)}}, (2, 2), ZZ)
30
+ assert str(sdm) == '{0: {0: 1}, 1: {1: 1}}'
31
+ if HAS_GMPY: # pragma: no cover
32
+ assert repr(sdm) == 'SDM({0: {0: mpz(1)}, 1: {1: mpz(1)}}, (2, 2), ZZ)'
33
+ else: # pragma: no cover
34
+ assert repr(sdm) == 'SDM({0: {0: 1}, 1: {1: 1}}, (2, 2), ZZ)'
35
+
36
+
37
+ def test_SDM_new():
38
+ A = SDM({0:{0:ZZ(1)}}, (2, 2), ZZ)
39
+ B = A.new({}, (2, 2), ZZ)
40
+ assert B == SDM({}, (2, 2), ZZ)
41
+
42
+
43
+ def test_SDM_copy():
44
+ A = SDM({0:{0:ZZ(1)}}, (2, 2), ZZ)
45
+ B = A.copy()
46
+ assert A == B
47
+ A[0][0] = ZZ(2)
48
+ assert A != B
49
+
50
+
51
+ def test_SDM_from_list():
52
+ A = SDM.from_list([[ZZ(0), ZZ(1)], [ZZ(1), ZZ(0)]], (2, 2), ZZ)
53
+ assert A == SDM({0:{1:ZZ(1)}, 1:{0:ZZ(1)}}, (2, 2), ZZ)
54
+
55
+ raises(DMBadInputError, lambda: SDM.from_list([[ZZ(0)], [ZZ(0), ZZ(1)]], (2, 2), ZZ))
56
+ raises(DMBadInputError, lambda: SDM.from_list([[ZZ(0), ZZ(1)]], (2, 2), ZZ))
57
+
58
+
59
+ def test_SDM_to_list():
60
+ A = SDM({0:{1: ZZ(1)}}, (2, 2), ZZ)
61
+ assert A.to_list() == [[ZZ(0), ZZ(1)], [ZZ(0), ZZ(0)]]
62
+
63
+ A = SDM({}, (0, 2), ZZ)
64
+ assert A.to_list() == []
65
+
66
+ A = SDM({}, (2, 0), ZZ)
67
+ assert A.to_list() == [[], []]
68
+
69
+
70
+ def test_SDM_to_list_flat():
71
+ A = SDM({0:{1: ZZ(1)}}, (2, 2), ZZ)
72
+ assert A.to_list_flat() == [ZZ(0), ZZ(1), ZZ(0), ZZ(0)]
73
+
74
+
75
+ def test_SDM_to_dok():
76
+ A = SDM({0:{1: ZZ(1)}}, (2, 2), ZZ)
77
+ assert A.to_dok() == {(0, 1): ZZ(1)}
78
+
79
+
80
+ def test_SDM_from_ddm():
81
+ A = DDM([[ZZ(1), ZZ(0)], [ZZ(1), ZZ(0)]], (2, 2), ZZ)
82
+ B = SDM.from_ddm(A)
83
+ assert B.domain == ZZ
84
+ assert B.shape == (2, 2)
85
+ assert dict(B) == {0:{0:ZZ(1)}, 1:{0:ZZ(1)}}
86
+
87
+
88
+ def test_SDM_to_ddm():
89
+ A = SDM({0:{1: ZZ(1)}}, (2, 2), ZZ)
90
+ B = DDM([[ZZ(0), ZZ(1)], [ZZ(0), ZZ(0)]], (2, 2), ZZ)
91
+ assert A.to_ddm() == B
92
+
93
+
94
+ def test_SDM_to_sdm():
95
+ A = SDM({0:{1: ZZ(1)}}, (2, 2), ZZ)
96
+ assert A.to_sdm() == A
97
+
98
+
99
+ def test_SDM_getitem():
100
+ A = SDM({0:{1:ZZ(1)}}, (2, 2), ZZ)
101
+ assert A.getitem(0, 0) == ZZ.zero
102
+ assert A.getitem(0, 1) == ZZ.one
103
+ assert A.getitem(1, 0) == ZZ.zero
104
+ assert A.getitem(-2, -2) == ZZ.zero
105
+ assert A.getitem(-2, -1) == ZZ.one
106
+ assert A.getitem(-1, -2) == ZZ.zero
107
+ raises(IndexError, lambda: A.getitem(2, 0))
108
+ raises(IndexError, lambda: A.getitem(0, 2))
109
+
110
+
111
+ def test_SDM_setitem():
112
+ A = SDM({0:{1:ZZ(1)}}, (2, 2), ZZ)
113
+ A.setitem(0, 0, ZZ(1))
114
+ assert A == SDM({0:{0:ZZ(1), 1:ZZ(1)}}, (2, 2), ZZ)
115
+ A.setitem(1, 0, ZZ(1))
116
+ assert A == SDM({0:{0:ZZ(1), 1:ZZ(1)}, 1:{0:ZZ(1)}}, (2, 2), ZZ)
117
+ A.setitem(1, 0, ZZ(0))
118
+ assert A == SDM({0:{0:ZZ(1), 1:ZZ(1)}}, (2, 2), ZZ)
119
+ # Repeat the above test so that this time the row is empty
120
+ A.setitem(1, 0, ZZ(0))
121
+ assert A == SDM({0:{0:ZZ(1), 1:ZZ(1)}}, (2, 2), ZZ)
122
+ A.setitem(0, 0, ZZ(0))
123
+ assert A == SDM({0:{1:ZZ(1)}}, (2, 2), ZZ)
124
+ # This time the row is there but column is empty
125
+ A.setitem(0, 0, ZZ(0))
126
+ assert A == SDM({0:{1:ZZ(1)}}, (2, 2), ZZ)
127
+ raises(IndexError, lambda: A.setitem(2, 0, ZZ(1)))
128
+ raises(IndexError, lambda: A.setitem(0, 2, ZZ(1)))
129
+
130
+
131
+ def test_SDM_extract_slice():
132
+ A = SDM({0:{0:ZZ(1), 1:ZZ(2)}, 1:{0:ZZ(3), 1:ZZ(4)}}, (2, 2), ZZ)
133
+ B = A.extract_slice(slice(1, 2), slice(1, 2))
134
+ assert B == SDM({0:{0:ZZ(4)}}, (1, 1), ZZ)
135
+
136
+
137
+ def test_SDM_extract():
138
+ A = SDM({0:{0:ZZ(1), 1:ZZ(2)}, 1:{0:ZZ(3), 1:ZZ(4)}}, (2, 2), ZZ)
139
+ B = A.extract([1], [1])
140
+ assert B == SDM({0:{0:ZZ(4)}}, (1, 1), ZZ)
141
+ B = A.extract([1, 0], [1, 0])
142
+ assert B == SDM({0:{0:ZZ(4), 1:ZZ(3)}, 1:{0:ZZ(2), 1:ZZ(1)}}, (2, 2), ZZ)
143
+ B = A.extract([1, 1], [1, 1])
144
+ assert B == SDM({0:{0:ZZ(4), 1:ZZ(4)}, 1:{0:ZZ(4), 1:ZZ(4)}}, (2, 2), ZZ)
145
+ B = A.extract([-1], [-1])
146
+ assert B == SDM({0:{0:ZZ(4)}}, (1, 1), ZZ)
147
+
148
+ A = SDM({}, (2, 2), ZZ)
149
+ B = A.extract([0, 1, 0], [0, 0])
150
+ assert B == SDM({}, (3, 2), ZZ)
151
+
152
+ A = SDM({0:{0:ZZ(1), 1:ZZ(2)}, 1:{0:ZZ(3), 1:ZZ(4)}}, (2, 2), ZZ)
153
+ assert A.extract([], []) == SDM.zeros((0, 0), ZZ)
154
+ assert A.extract([1], []) == SDM.zeros((1, 0), ZZ)
155
+ assert A.extract([], [1]) == SDM.zeros((0, 1), ZZ)
156
+
157
+ raises(IndexError, lambda: A.extract([2], [0]))
158
+ raises(IndexError, lambda: A.extract([0], [2]))
159
+ raises(IndexError, lambda: A.extract([-3], [0]))
160
+ raises(IndexError, lambda: A.extract([0], [-3]))
161
+
162
+
163
+ def test_SDM_zeros():
164
+ A = SDM.zeros((2, 2), ZZ)
165
+ assert A.domain == ZZ
166
+ assert A.shape == (2, 2)
167
+ assert dict(A) == {}
168
+
169
+ def test_SDM_ones():
170
+ A = SDM.ones((1, 2), QQ)
171
+ assert A.domain == QQ
172
+ assert A.shape == (1, 2)
173
+ assert dict(A) == {0:{0:QQ(1), 1:QQ(1)}}
174
+
175
+ def test_SDM_eye():
176
+ A = SDM.eye((2, 2), ZZ)
177
+ assert A.domain == ZZ
178
+ assert A.shape == (2, 2)
179
+ assert dict(A) == {0:{0:ZZ(1)}, 1:{1:ZZ(1)}}
180
+
181
+
182
+ def test_SDM_diag():
183
+ A = SDM.diag([ZZ(1), ZZ(2)], ZZ, (2, 3))
184
+ assert A == SDM({0:{0:ZZ(1)}, 1:{1:ZZ(2)}}, (2, 3), ZZ)
185
+
186
+
187
+ def test_SDM_transpose():
188
+ A = SDM({0:{0:ZZ(1), 1:ZZ(2)}, 1:{0:ZZ(3), 1:ZZ(4)}}, (2, 2), ZZ)
189
+ B = SDM({0:{0:ZZ(1), 1:ZZ(3)}, 1:{0:ZZ(2), 1:ZZ(4)}}, (2, 2), ZZ)
190
+ assert A.transpose() == B
191
+
192
+ A = SDM({0:{1:ZZ(2)}}, (2, 2), ZZ)
193
+ B = SDM({1:{0:ZZ(2)}}, (2, 2), ZZ)
194
+ assert A.transpose() == B
195
+
196
+ A = SDM({0:{1:ZZ(2)}}, (1, 2), ZZ)
197
+ B = SDM({1:{0:ZZ(2)}}, (2, 1), ZZ)
198
+ assert A.transpose() == B
199
+
200
+
201
+ def test_SDM_mul():
202
+ A = SDM({0:{0:ZZ(2)}}, (2, 2), ZZ)
203
+ B = SDM({0:{0:ZZ(4)}}, (2, 2), ZZ)
204
+ assert A*ZZ(2) == B
205
+ assert ZZ(2)*A == B
206
+
207
+ raises(TypeError, lambda: A*QQ(1, 2))
208
+ raises(TypeError, lambda: QQ(1, 2)*A)
209
+
210
+
211
+ def test_SDM_mul_elementwise():
212
+ A = SDM({0:{0:ZZ(2), 1:ZZ(2)}}, (2, 2), ZZ)
213
+ B = SDM({0:{0:ZZ(4)}, 1:{0:ZZ(3)}}, (2, 2), ZZ)
214
+ C = SDM({0:{0:ZZ(8)}}, (2, 2), ZZ)
215
+ assert A.mul_elementwise(B) == C
216
+ assert B.mul_elementwise(A) == C
217
+
218
+ Aq = A.convert_to(QQ)
219
+ A1 = SDM({0:{0:ZZ(1)}}, (1, 1), ZZ)
220
+
221
+ raises(DMDomainError, lambda: Aq.mul_elementwise(B))
222
+ raises(DMShapeError, lambda: A1.mul_elementwise(B))
223
+
224
+
225
+ def test_SDM_matmul():
226
+ A = SDM({0:{0:ZZ(2)}}, (2, 2), ZZ)
227
+ B = SDM({0:{0:ZZ(4)}}, (2, 2), ZZ)
228
+ assert A.matmul(A) == A*A == B
229
+
230
+ C = SDM({0:{0:ZZ(2)}}, (2, 2), QQ)
231
+ raises(DMDomainError, lambda: A.matmul(C))
232
+
233
+ A = SDM({0:{0:ZZ(1), 1:ZZ(2)}, 1:{0:ZZ(3), 1:ZZ(4)}}, (2, 2), ZZ)
234
+ B = SDM({0:{0:ZZ(7), 1:ZZ(10)}, 1:{0:ZZ(15), 1:ZZ(22)}}, (2, 2), ZZ)
235
+ assert A.matmul(A) == A*A == B
236
+
237
+ A22 = SDM({0:{0:ZZ(4)}}, (2, 2), ZZ)
238
+ A32 = SDM({0:{0:ZZ(2)}}, (3, 2), ZZ)
239
+ A23 = SDM({0:{0:ZZ(4)}}, (2, 3), ZZ)
240
+ A33 = SDM({0:{0:ZZ(8)}}, (3, 3), ZZ)
241
+ A22 = SDM({0:{0:ZZ(8)}}, (2, 2), ZZ)
242
+ assert A32.matmul(A23) == A33
243
+ assert A23.matmul(A32) == A22
244
+ # XXX: @ not supported by SDM...
245
+ #assert A32.matmul(A23) == A32 @ A23 == A33
246
+ #assert A23.matmul(A32) == A23 @ A32 == A22
247
+ #raises(DMShapeError, lambda: A23 @ A22)
248
+ raises(DMShapeError, lambda: A23.matmul(A22))
249
+
250
+ A = SDM({0: {0: ZZ(-1), 1: ZZ(1)}}, (1, 2), ZZ)
251
+ B = SDM({0: {0: ZZ(-1)}, 1: {0: ZZ(-1)}}, (2, 1), ZZ)
252
+ assert A.matmul(B) == A*B == SDM({}, (1, 1), ZZ)
253
+
254
+
255
+ def test_matmul_exraw():
256
+
257
+ def dm(d):
258
+ result = {}
259
+ for i, row in d.items():
260
+ row = {j:val for j, val in row.items() if val}
261
+ if row:
262
+ result[i] = row
263
+ return SDM(result, (2, 2), EXRAW)
264
+
265
+ values = [S.NegativeInfinity, S.NegativeOne, S.Zero, S.One, S.Infinity]
266
+ for a, b, c, d in product(*[values]*4):
267
+ Ad = dm({0: {0:a, 1:b}, 1: {0:c, 1:d}})
268
+ Ad2 = dm({0: {0:a*a + b*c, 1:a*b + b*d}, 1:{0:c*a + d*c, 1: c*b + d*d}})
269
+ assert Ad * Ad == Ad2
270
+
271
+
272
+ def test_SDM_add():
273
+ A = SDM({0:{1:ZZ(1)}, 1:{0:ZZ(2), 1:ZZ(3)}}, (2, 2), ZZ)
274
+ B = SDM({0:{0:ZZ(1)}, 1:{0:ZZ(-2), 1:ZZ(3)}}, (2, 2), ZZ)
275
+ C = SDM({0:{0:ZZ(1), 1:ZZ(1)}, 1:{1:ZZ(6)}}, (2, 2), ZZ)
276
+ assert A.add(B) == B.add(A) == A + B == B + A == C
277
+
278
+ A = SDM({0:{1:ZZ(1)}}, (2, 2), ZZ)
279
+ B = SDM({0:{0:ZZ(1)}, 1:{0:ZZ(-2), 1:ZZ(3)}}, (2, 2), ZZ)
280
+ C = SDM({0:{0:ZZ(1), 1:ZZ(1)}, 1:{0:ZZ(-2), 1:ZZ(3)}}, (2, 2), ZZ)
281
+ assert A.add(B) == B.add(A) == A + B == B + A == C
282
+
283
+ raises(TypeError, lambda: A + [])
284
+
285
+
286
+ def test_SDM_sub():
287
+ A = SDM({0:{1:ZZ(1)}, 1:{0:ZZ(2), 1:ZZ(3)}}, (2, 2), ZZ)
288
+ B = SDM({0:{0:ZZ(1)}, 1:{0:ZZ(-2), 1:ZZ(3)}}, (2, 2), ZZ)
289
+ C = SDM({0:{0:ZZ(-1), 1:ZZ(1)}, 1:{0:ZZ(4)}}, (2, 2), ZZ)
290
+ assert A.sub(B) == A - B == C
291
+
292
+ raises(TypeError, lambda: A - [])
293
+
294
+
295
+ def test_SDM_neg():
296
+ A = SDM({0:{1:ZZ(1)}, 1:{0:ZZ(2), 1:ZZ(3)}}, (2, 2), ZZ)
297
+ B = SDM({0:{1:ZZ(-1)}, 1:{0:ZZ(-2), 1:ZZ(-3)}}, (2, 2), ZZ)
298
+ assert A.neg() == -A == B
299
+
300
+
301
+ def test_SDM_convert_to():
302
+ A = SDM({0:{1:ZZ(1)}, 1:{0:ZZ(2), 1:ZZ(3)}}, (2, 2), ZZ)
303
+ B = SDM({0:{1:QQ(1)}, 1:{0:QQ(2), 1:QQ(3)}}, (2, 2), QQ)
304
+ C = A.convert_to(QQ)
305
+ assert C == B
306
+ assert C.domain == QQ
307
+
308
+ D = A.convert_to(ZZ)
309
+ assert D == A
310
+ assert D.domain == ZZ
311
+
312
+
313
+ def test_SDM_hstack():
314
+ A = SDM({0:{1:ZZ(1)}}, (2, 2), ZZ)
315
+ B = SDM({1:{1:ZZ(1)}}, (2, 2), ZZ)
316
+ AA = SDM({0:{1:ZZ(1), 3:ZZ(1)}}, (2, 4), ZZ)
317
+ AB = SDM({0:{1:ZZ(1)}, 1:{3:ZZ(1)}}, (2, 4), ZZ)
318
+ assert SDM.hstack(A) == A
319
+ assert SDM.hstack(A, A) == AA
320
+ assert SDM.hstack(A, B) == AB
321
+
322
+
323
+ def test_SDM_vstack():
324
+ A = SDM({0:{1:ZZ(1)}}, (2, 2), ZZ)
325
+ B = SDM({1:{1:ZZ(1)}}, (2, 2), ZZ)
326
+ AA = SDM({0:{1:ZZ(1)}, 2:{1:ZZ(1)}}, (4, 2), ZZ)
327
+ AB = SDM({0:{1:ZZ(1)}, 3:{1:ZZ(1)}}, (4, 2), ZZ)
328
+ assert SDM.vstack(A) == A
329
+ assert SDM.vstack(A, A) == AA
330
+ assert SDM.vstack(A, B) == AB
331
+
332
+
333
+ def test_SDM_applyfunc():
334
+ A = SDM({0:{1:ZZ(1)}}, (2, 2), ZZ)
335
+ B = SDM({0:{1:ZZ(2)}}, (2, 2), ZZ)
336
+ assert A.applyfunc(lambda x: 2*x, ZZ) == B
337
+
338
+
339
+ def test_SDM_inv():
340
+ A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ)
341
+ B = SDM({0:{0:QQ(-2), 1:QQ(1)}, 1:{0:QQ(3, 2), 1:QQ(-1, 2)}}, (2, 2), QQ)
342
+ assert A.inv() == B
343
+
344
+
345
+ def test_SDM_det():
346
+ A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ)
347
+ assert A.det() == QQ(-2)
348
+
349
+
350
+ def test_SDM_lu():
351
+ A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ)
352
+ L = SDM({0:{0:QQ(1)}, 1:{0:QQ(3), 1:QQ(1)}}, (2, 2), QQ)
353
+ #U = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(-2)}}, (2, 2), QQ)
354
+ #swaps = []
355
+ # This doesn't quite work. U has some nonzero elements in the lower part.
356
+ #assert A.lu() == (L, U, swaps)
357
+ assert A.lu()[0] == L
358
+
359
+
360
+ def test_SDM_lu_solve():
361
+ A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ)
362
+ b = SDM({0:{0:QQ(1)}, 1:{0:QQ(2)}}, (2, 1), QQ)
363
+ x = SDM({1:{0:QQ(1, 2)}}, (2, 1), QQ)
364
+ assert A.matmul(x) == b
365
+ assert A.lu_solve(b) == x
366
+
367
+
368
+ def test_SDM_charpoly():
369
+ A = SDM({0:{0:ZZ(1), 1:ZZ(2)}, 1:{0:ZZ(3), 1:ZZ(4)}}, (2, 2), ZZ)
370
+ assert A.charpoly() == [ZZ(1), ZZ(-5), ZZ(-2)]
371
+
372
+
373
+ def test_SDM_nullspace():
374
+ A = SDM({0:{0:QQ(1), 1:QQ(1)}}, (2, 2), QQ)
375
+ assert A.nullspace()[0] == SDM({0:{0:QQ(-1), 1:QQ(1)}}, (1, 2), QQ)
376
+
377
+
378
+ def test_SDM_rref():
379
+ eye2 = SDM({0:{0:QQ(1)}, 1:{1:QQ(1)}}, (2, 2), QQ)
380
+
381
+ A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ)
382
+ assert A.rref() == (eye2, [0, 1])
383
+
384
+ A = SDM({0:{0:QQ(1)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ)
385
+ assert A.rref() == (eye2, [0, 1])
386
+
387
+ A = SDM({0:{1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ)
388
+ assert A.rref() == (eye2, [0, 1])
389
+
390
+ A = SDM({0:{0:QQ(1), 1:QQ(2), 2:QQ(3)},
391
+ 1:{0:QQ(4), 1:QQ(5), 2:QQ(6)},
392
+ 2:{0:QQ(7), 1:QQ(8), 2:QQ(9)} }, (3, 3), QQ)
393
+ Arref = SDM({0:{0:QQ(1), 2:QQ(-1)}, 1:{1:QQ(1), 2:QQ(2)}}, (3, 3), QQ)
394
+ assert A.rref() == (Arref, [0, 1])
395
+
396
+ A = SDM({0:{0:QQ(1), 1:QQ(2), 3:QQ(1)},
397
+ 1:{0:QQ(1), 1:QQ(1), 2:QQ(9)}}, (2, 4), QQ)
398
+ Arref = SDM({0:{0:QQ(1), 2:QQ(18), 3:QQ(-1)},
399
+ 1:{1:QQ(1), 2:QQ(-9), 3:QQ(1)}}, (2, 4), QQ)
400
+ assert A.rref() == (Arref, [0, 1])
401
+
402
+ A = SDM({0:{0:QQ(1), 1:QQ(1), 2:QQ(1)},
403
+ 1:{0:QQ(1), 1:QQ(2), 2:QQ(2)}}, (2, 3), QQ)
404
+ Arref = SDM(
405
+ {0: {0: QQ(1,1)}, 1: {1: QQ(1,1), 2: QQ(1,1)}},
406
+ (2, 3), QQ)
407
+ assert A.rref() == (Arref, [0, 1])
408
+
409
+
410
+ def test_SDM_particular():
411
+ A = SDM({0:{0:QQ(1)}}, (2, 2), QQ)
412
+ Apart = SDM.zeros((1, 2), QQ)
413
+ assert A.particular() == Apart
414
+
415
+
416
+ def test_SDM_is_zero_matrix():
417
+ A = SDM({0: {0: QQ(1)}}, (2, 2), QQ)
418
+ Azero = SDM.zeros((1, 2), QQ)
419
+ assert A.is_zero_matrix() is False
420
+ assert Azero.is_zero_matrix() is True
421
+
422
+
423
+ def test_SDM_is_upper():
424
+ A = SDM({0: {0: QQ(1), 1: QQ(2), 2: QQ(3), 3: QQ(4)},
425
+ 1: {1: QQ(5), 2: QQ(6), 3: QQ(7)},
426
+ 2: {2: QQ(8), 3: QQ(9)}}, (3, 4), QQ)
427
+ B = SDM({0: {0: QQ(1), 1: QQ(2), 2: QQ(3), 3: QQ(4)},
428
+ 1: {1: QQ(5), 2: QQ(6), 3: QQ(7)},
429
+ 2: {1: QQ(7), 2: QQ(8), 3: QQ(9)}}, (3, 4), QQ)
430
+ assert A.is_upper() is True
431
+ assert B.is_upper() is False
432
+
433
+
434
+ def test_SDM_is_lower():
435
+ A = SDM({0: {0: QQ(1), 1: QQ(2), 2: QQ(3), 3: QQ(4)},
436
+ 1: {1: QQ(5), 2: QQ(6), 3: QQ(7)},
437
+ 2: {2: QQ(8), 3: QQ(9)}}, (3, 4), QQ
438
+ ).transpose()
439
+ B = SDM({0: {0: QQ(1), 1: QQ(2), 2: QQ(3), 3: QQ(4)},
440
+ 1: {1: QQ(5), 2: QQ(6), 3: QQ(7)},
441
+ 2: {1: QQ(7), 2: QQ(8), 3: QQ(9)}}, (3, 4), QQ
442
+ ).transpose()
443
+ assert A.is_lower() is True
444
+ assert B.is_lower() is False
llmeval-env/lib/python3.10/site-packages/sympy/polys/numberfields/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (203 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/polys/numberfields/tests/__pycache__/test_basis.cpython-310.pyc ADDED
Binary file (3.59 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/polys/numberfields/tests/__pycache__/test_galoisgroups.cpython-310.pyc ADDED
Binary file (4.99 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/polys/numberfields/tests/__pycache__/test_minpoly.cpython-310.pyc ADDED
Binary file (21.8 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/polys/numberfields/tests/__pycache__/test_modules.cpython-310.pyc ADDED
Binary file (28.1 kB). View file