def symchol(M): # symbolic Cholesky B = SparseMatrix(M) t = B.row_structure_symbolic_cholesky() B = np.asarray(B)*0 for i in range(B.shape[0]): B[i, t[i]] = 1 return B
def test_lower_triangular_solve(): a, b, c, d = symbols('a:d') u, v, w, x = symbols('u:x') A = SparseMatrix([[a, 0], [c, d]]) B = MutableSparseMatrix([[u, v], [w, x]]) C = ImmutableSparseMatrix([[u, v], [w, x]]) sol = Matrix([[u / a, v / a], [(w - c * u / a) / d, (x - c * v / a) / d]]) assert A.lower_triangular_solve(B) == sol assert A.lower_triangular_solve(C) == sol
def test_diagonal_solve(): a, d = symbols('a d') u, v, w, x = symbols('u:x') A = SparseMatrix([[a, 0], [0, d]]) B = MutableSparseMatrix([[u, v], [w, x]]) C = ImmutableSparseMatrix([[u, v], [w, x]]) sol = Matrix([[u / a, v / a], [w / d, x / d]]) assert A.diagonal_solve(B) == sol assert A.diagonal_solve(C) == sol
def test_upper_triangular_solve(): a, b, c, d = symbols('a:d') u, v, w, x = symbols('u:x') A = SparseMatrix([[a, b], [0, d]]) B = MutableSparseMatrix([[u, v], [w, x]]) C = ImmutableSparseMatrix([[u, v], [w, x]]) sol = Matrix([[(u - b * w / d) / a, (v - b * x / d) / a], [w / d, x / d]]) assert A.upper_triangular_solve(B) == sol assert A.upper_triangular_solve(C) == sol
def test_hermitian(): x = Symbol('x') a = SparseMatrix([[0, I], [-I, 0]]) assert a.is_hermitian a = SparseMatrix([[1, I], [-I, 1]]) assert a.is_hermitian a[0, 0] = 2 * I assert a.is_hermitian is False a[0, 0] = x assert a.is_hermitian is None a[0, 1] = a[1, 0] * I assert a.is_hermitian is False
def test_CL_RL(): assert SparseMatrix(((1, 2), (3, 4))).row_list() == [ (0, 0, 1), (0, 1, 2), (1, 0, 3), (1, 1, 4), ] assert SparseMatrix(((1, 2), (3, 4))).col_list() == [ (0, 0, 1), (1, 0, 3), (0, 1, 2), (1, 1, 4), ]
def PartialTrace(expr, n): ##calculate the partial trace of the n_th photon dictadd = collect(expr, [HH[l1, l2, l3, l4, l5, l6]], evaluate=False) TermsCoeff = list(dictadd.items()) ParticleOne = [] ParticleTwo = [] ## get the size of the matrix for ii in range(len(TermsCoeff)): HHList = TermsCoeff[ii][0] if HHList.indices[n - 1] == HHList.indices[n + 2]: ll = [ HHList.indices[0], HHList.indices[1], HHList.indices[2], HHList.indices[3], HHList.indices[4], HHList.indices[5] ] del ( ll[n - 1], ll[n + 1] ) ## because cannot del all at the same time, thus do it one by one, the index is not n+2 ParticleOne.append(ll[0]) ParticleTwo.append(ll[1]) # start from 0 Upperone = max(ParticleOne) + 1 Lowerone = min(min(ParticleOne), 0) Uppertwo = max(ParticleTwo) + 1 Lowertwo = min(min(ParticleTwo), 0) rangeP1 = Upperone - Lowerone rangeP2 = Uppertwo - Lowertwo Msize = (rangeP1 * rangeP2) SMatrix = SparseMatrix(Msize, Msize, {(0, 0): 0}) for ii in range(len(TermsCoeff)): HHList = TermsCoeff[ii][0] if HHList.indices[n - 1] == HHList.indices[n + 2]: ll = [ HHList.indices[0], HHList.indices[1], HHList.indices[2], HHList.indices[3], HHList.indices[4], HHList.indices[5] ] del ( ll[n - 1], ll[n + 1] ) ## because cannot del all at the same time, thus do it one by one, the index is not n+2 # print('rest: ',ll) # print('rest: ',ll[0]-Lowerone,'',ll[1]-Lowertwo, '',ll[2]-Lowerone,'',ll[3]-Lowertwo) Dimrow = (ll[0] - Lowerone) * rangeP2 + (ll[1] - Lowertwo) Dimcol = (ll[2] - Lowerone) * rangeP2 + (ll[3] - Lowertwo) SMatrix = SparseMatrix( Msize, Msize, {(Dimrow, Dimcol): TermsCoeff[ii][1]}) + SMatrix return SMatrix.rank()
def test_scipy_sparse_matrix(): if not scipy: skip("scipy not installed.") A = SparseMatrix([[x, 0], [0, y]]) f = lambdify((x, y), A, modules="scipy") B = f(1, 2) assert isinstance(B, scipy.sparse.coo_matrix)
def tomatrix(self): """ Converts MutableDenseNDimArray to Matrix. Can convert only 2-dim array, else will raise error. Examples ======== >>> from sympy import MutableSparseNDimArray >>> a = MutableSparseNDimArray([1 for i in range(9)], (3, 3)) >>> b = a.tomatrix() >>> b Matrix([ [1, 1, 1], [1, 1, 1], [1, 1, 1]]) """ from sympy.matrices import SparseMatrix if self.rank() != 2: raise ValueError('Dimensions must be of size of 2') mat_sparse = {} for key, value in self._sparse_array.items(): mat_sparse[self._get_tuple_index(key)] = value return SparseMatrix(self.shape[0], self.shape[1], mat_sparse)
def test_MatrixElement_with_values(): x, y, z, w = symbols("x y z w") M = Matrix([[x, y], [z, w]]) i, j = symbols("i, j") Mij = M[i, j] assert isinstance(Mij, MatrixElement) Ms = SparseMatrix([[2, 3], [4, 5]]) msij = Ms[i, j] assert isinstance(msij, MatrixElement) for oi, oj in [(0, 0), (0, 1), (1, 0), (1, 1)]: assert Mij.subs({i: oi, j: oj}) == M[oi, oj] assert msij.subs({i: oi, j: oj}) == Ms[oi, oj] A = MatrixSymbol("A", 2, 2) assert A[0, 0].subs(A, M) == x assert A[i, j].subs(A, M) == M[i, j] assert M[i, j].subs(M, A) == A[i, j] assert isinstance(M[3 * i - 2, j], MatrixElement) assert M[3 * i - 2, j].subs({i: 1, j: 0}) == M[1, 0] assert isinstance(M[i, 0], MatrixElement) assert M[i, 0].subs(i, 0) == M[0, 0] assert M[0, i].subs(i, 1) == M[0, 1] assert M[i, j].diff(x) == Matrix([[1, 0], [0, 0]])[i, j] raises(ValueError, lambda: M[i, 2]) raises(ValueError, lambda: M[i, -1]) raises(ValueError, lambda: M[2, i]) raises(ValueError, lambda: M[-1, i])
def test_eq(): A = Matrix([[1]]) B = ImmutableMatrix([[1]]) C = SparseMatrix([[1]]) assert A != object() assert A != "Matrix([[1]])" assert A == B assert A == C
def test_as_immutable(): data = [[1, 2], [3, 4]] X = Matrix(data) assert sympify(X) == X.as_immutable() == ImmutableMatrix(data) data = {(0, 0): 1, (0, 1): 2, (1, 0): 3, (1, 1): 4} X = SparseMatrix(2, 2, data) assert sympify(X) == X.as_immutable() == ImmutableSparseMatrix(2, 2, data)
def test_sparse(): M = SparseMatrix(5, 6, {}) M[2, 2] = 10 M[1, 2] = 20 M[1, 3] = 22 M[0, 3] = 30 M[3, 0] = x * y assert mcode(M) == ( "sparse([4 2 3 1 2], [1 3 3 4 4], [x.*y 20 10 30 22], 5, 6)")
def test_diagonal(): m = Matrix(3, 3, range(9)) d = m.diagonal() assert d == m.diagonal(0) assert tuple(d) == (0, 4, 8) assert tuple(m.diagonal(1)) == (1, 5) assert tuple(m.diagonal(-1)) == (3, 7) assert tuple(m.diagonal(2)) == (2, ) assert type(m.diagonal()) == type(m) s = SparseMatrix(3, 3, {(1, 1): 1}) assert type(s.diagonal()) == type(s) assert type(m) != type(s) raises(ValueError, lambda: m.diagonal(3)) raises(ValueError, lambda: m.diagonal(-3)) raises(ValueError, lambda: m.diagonal(pi)) M = ones(2, 3) assert banded({i: list(M.diagonal(i)) for i in range(1 - M.rows, M.cols)}) == M
def test_LDLdecomposition(): raises(NonSquareMatrixError, lambda: Matrix((1, 2)).LDLdecomposition()) raises(ValueError, lambda: Matrix(((1, 2), (3, 4))).LDLdecomposition()) raises(ValueError, lambda: Matrix(((5 + I, 0), (0, 1))).LDLdecomposition()) raises(ValueError, lambda: Matrix(((1, 5), (5, 1))).LDLdecomposition()) raises(ValueError, lambda: Matrix( ((1, 2), (3, 4))).LDLdecomposition(hermitian=False)) A = Matrix(((1, 5), (5, 1))) L, D = A.LDLdecomposition(hermitian=False) assert L * D * L.T == A A = Matrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11))) L, D = A.LDLdecomposition() assert L * D * L.T == A assert L.is_lower assert L == Matrix([[1, 0, 0], [Rational(3, 5), 1, 0], [Rational(-1, 5), Rational(1, 3), 1]]) assert D.is_diagonal() assert D == Matrix([[25, 0, 0], [0, 9, 0], [0, 0, 9]]) A = Matrix( ((4, -2 * I, 2 + 2 * I), (2 * I, 2, -1 + I), (2 - 2 * I, -1 - I, 11))) L, D = A.LDLdecomposition() assert expand_mul(L * D * L.H) == A assert L.expand() == Matrix([[1, 0, 0], [I / 2, 1, 0], [S.Half - I / 2, 0, 1]]) assert D.expand() == Matrix(((4, 0, 0), (0, 1, 0), (0, 0, 9))) raises(NonSquareMatrixError, lambda: SparseMatrix( (1, 2)).LDLdecomposition()) raises(ValueError, lambda: SparseMatrix(((1, 2), (3, 4))).LDLdecomposition()) raises(ValueError, lambda: SparseMatrix(((5 + I, 0), (0, 1))).LDLdecomposition()) raises(ValueError, lambda: SparseMatrix(((1, 5), (5, 1))).LDLdecomposition()) raises( ValueError, lambda: SparseMatrix( ((1, 2), (3, 4))).LDLdecomposition(hermitian=False)) A = SparseMatrix(((1, 5), (5, 1))) L, D = A.LDLdecomposition(hermitian=False) assert L * D * L.T == A A = SparseMatrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11))) L, D = A.LDLdecomposition() assert L * D * L.T == A assert L.is_lower assert L == Matrix([[1, 0, 0], [Rational(3, 5), 1, 0], [Rational(-1, 5), Rational(1, 3), 1]]) assert D.is_diagonal() assert D == Matrix([[25, 0, 0], [0, 9, 0], [0, 0, 9]]) A = SparseMatrix( ((4, -2 * I, 2 + 2 * I), (2 * I, 2, -1 + I), (2 - 2 * I, -1 - I, 11))) L, D = A.LDLdecomposition() assert expand_mul(L * D * L.H) == A assert L == Matrix(((1, 0, 0), (I / 2, 1, 0), (S.Half - I / 2, 0, 1))) assert D == Matrix(((4, 0, 0), (0, 1, 0), (0, 0, 9)))
def test_sparse(): M = SparseMatrix(5, 6, {}) M[2, 2] = 10 M[1, 2] = 20 M[1, 3] = 22 M[0, 3] = 30 M[3, 0] = x * y assert julia_code(M) == ( "sparse([4, 2, 3, 1, 2], [1, 3, 3, 4, 4], [x.*y, 20, 10, 30, 22], 5, 6)" )
def test_SciPyPrinter(): p = SciPyPrinter() expr = acos(x) assert 'numpy' not in p.module_imports assert p.doprint(expr) == 'numpy.arccos(x)' assert 'numpy' in p.module_imports assert not any(m.startswith('scipy') for m in p.module_imports) smat = SparseMatrix(2, 5, {(0, 1): 3}) assert p.doprint(smat) == 'scipy.sparse.coo_matrix([3], ([0], [1]), shape=(2, 5))' assert 'scipy.sparse' in p.module_imports
def test_matrix_sum(): A = Matrix([[0, 1], [n, 0]]) result = Sum(A, (n, 0, 3)).doit() assert result == Matrix([[0, 4], [6, 0]]) assert result.__class__ == ImmutableDenseMatrix A = SparseMatrix([[0, 1], [n, 0]]) result = Sum(A, (n, 0, 3)).doit() assert result.__class__ == ImmutableSparseMatrix
def test_copyin(): s = SparseMatrix(3, 3, {}) s[1, 0] = 1 assert s[:, 0] == SparseMatrix(Matrix([0, 1, 0])) assert s[3] == 1 assert s[3:4] == [1] s[1, 1] = 42 assert s[1, 1] == 42 assert s[1, 1:] == SparseMatrix([[42, 0]]) s[1, 1:] = Matrix([[5, 6]]) assert s[1, :] == SparseMatrix([[1, 5, 6]]) s[1, 1:] = [[42, 43]] assert s[1, :] == SparseMatrix([[1, 42, 43]]) s[0, 0] = 17 assert s[:, :1] == SparseMatrix([17, 1, 0]) s[0, 0] = [1, 1, 1] assert s[:, 0] == SparseMatrix([1, 1, 1]) s[0, 0] = Matrix([1, 1, 1]) assert s[:, 0] == SparseMatrix([1, 1, 1]) s[0, 0] = SparseMatrix([1, 1, 1]) assert s[:, 0] == SparseMatrix([1, 1, 1])
def test_sparse_creation(): a = SparseMatrix(2, 2, {(0, 0): [[1, 2], [3, 4]]}) assert a == SparseMatrix([[1, 2], [3, 4]]) a = SparseMatrix(2, 2, {(0, 0): [[1, 2]]}) assert a == SparseMatrix([[1, 2], [0, 0]]) a = SparseMatrix(2, 2, {(0, 0): [1, 2]}) assert a == SparseMatrix([[1, 0], [2, 0]])
def sparse_sympy_matrix(self, triqs_operator_expression): Hsp = self.sparse_matrix(triqs_operator_expression) from sympy.matrices import SparseMatrix from sympy.simplify.simplify import nsimplify d = dict([((i, j), nsimplify(val)) for (i, j), val in Hsp.todok().items()]) H = SparseMatrix(Hsp.shape[0], Hsp.shape[1], d) return H
def test_csrtodok(): h = [[5, 7, 5], [2, 1, 3], [0, 1, 1, 3], [3, 4]] g = [[12, 5, 4], [2, 4, 2], [0, 1, 2, 3], [3, 7]] i = [[1, 3, 12], [0, 2, 4], [0, 2, 3], [2, 5]] j = [[11, 15, 12, 15], [2, 4, 1, 2], [0, 1, 1, 2, 3, 4], [5, 8]] k = [[1, 3], [2, 1], [0, 1, 1, 2], [3, 3]] m = _csrtodok(h) assert isinstance(m, SparseMatrix) assert m == SparseMatrix(3, 4, {(0, 2): 5, (2, 1): 7, (2, 3): 5}) assert _csrtodok(g) == SparseMatrix(3, 7, { (0, 2): 12, (1, 4): 5, (2, 2): 4 }) assert _csrtodok(i) == SparseMatrix([[1, 0, 3, 0, 0], [0, 0, 0, 0, 12]]) assert _csrtodok(j) == SparseMatrix(5, 8, { (0, 2): 11, (2, 4): 15, (3, 1): 12, (4, 2): 15 }) assert _csrtodok(k) == SparseMatrix(3, 3, {(0, 2): 1, (2, 1): 3})
def test_sparse(): M = SparseMatrix(5, 6, {}) M[2, 2] = 10 M[1, 2] = 20 M[1, 3] = 22 M[0, 3] = 30 M[3, 0] = x * y assert (maple_code(M) == "Matrix([[0, 0, 0, 30, 0, 0]," " [0, 0, 20, 22, 0, 0]," " [0, 0, 10, 0, 0, 0]," " [x*y, 0, 0, 0, 0, 0]," " [0, 0, 0, 0, 0, 0]], " "storage = sparse)")
def test_subs(): A = MatrixSymbol('A', n, m) B = MatrixSymbol('B', m, l) C = MatrixSymbol('C', m, l) assert A.subs(n, m).shape == (m, m) assert (A * B).subs(B, C) == A * C assert (A * B).subs(l, n).is_square A = SparseMatrix([[1, 2], [3, 4]]) B = Matrix([[1, 2], [3, 4]]) C, D = MatrixSymbol('C', 2, 2), MatrixSymbol('D', 2, 2) assert (C * D).subs({C: A, D: B}) == MatMul(A, B)
def test_SciPyPrinter(): p = SciPyPrinter() expr = acos(x) assert "numpy" not in p.module_imports assert p.doprint(expr) == "numpy.arccos(x)" assert "numpy" in p.module_imports assert not any(m.startswith("scipy") for m in p.module_imports) smat = SparseMatrix(2, 5, {(0, 1): 3}) assert p.doprint( smat) == "scipy.sparse.coo_matrix([3], ([0], [1]), shape=(2, 5))" assert "scipy.sparse" in p.module_imports assert p.doprint(S.GoldenRatio) == "scipy.constants.golden_ratio" assert p.doprint(S.Pi) == "scipy.constants.pi" assert p.doprint(S.Exp1) == "numpy.e"
def test_SciPyPrinter(): p = SciPyPrinter() expr = acos(x) assert 'numpy' not in p.module_imports assert p.doprint(expr) == 'numpy.arccos(x)' assert 'numpy' in p.module_imports assert not any(m.startswith('scipy') for m in p.module_imports) smat = SparseMatrix(2, 5, {(0, 1): 3}) assert p.doprint(smat) == \ 'scipy.sparse.coo_matrix(([3], ([0], [1])), shape=(2, 5))' assert 'scipy.sparse' in p.module_imports assert p.doprint(S.GoldenRatio) == 'scipy.constants.golden_ratio' assert p.doprint(S.Pi) == 'scipy.constants.pi' assert p.doprint(S.Exp1) == 'numpy.e'
def test_matexpr_subs(): A = MatrixSymbol('A', n, m) B = MatrixSymbol('B', m, l) C = MatrixSymbol('C', m, l) assert A.subs(n, m).shape == (m, m) assert (A * B).subs(B, C) == A * C assert (A * B).subs(l, n).is_square W = MatrixSymbol("W", 3, 3) X = MatrixSymbol("X", 2, 2) Y = MatrixSymbol("Y", 1, 2) Z = MatrixSymbol("Z", n, 2) # no restrictions on Symbol replacement assert X.subs(X, Y) == Y # it might be better to just change the name y = Str('y') assert X.subs(Str("X"), y).args == (y, 2, 2) # it's ok to introduce a wider matrix assert X[1, 1].subs(X, W) == W[1, 1] # but for a given MatrixExpression, only change # name if indexing on the new shape is valid. # Here, X is 2,2; Y is 1,2 and Y[1, 1] is out # of range so an error is raised raises(IndexError, lambda: X[1, 1].subs(X, Y)) # here, [0, 1] is in range so the subs succeeds assert X[0, 1].subs(X, Y) == Y[0, 1] # and here the size of n will accept any index # in the first position assert W[2, 1].subs(W, Z) == Z[2, 1] # but not in the second position raises(IndexError, lambda: W[2, 2].subs(W, Z)) # any matrix should raise if invalid raises(IndexError, lambda: W[2, 2].subs(W, zeros(2))) A = SparseMatrix([[1, 2], [3, 4]]) B = Matrix([[1, 2], [3, 4]]) C, D = MatrixSymbol('C', 2, 2), MatrixSymbol('D', 2, 2) assert (C * D).subs({C: A, D: B}) == MatMul(A, B)
def internal_loop_analysis(S_df, logger=None): """ Identifies the "rational" basis for the null space of S_df matrix, and convert them to internal loops. This is an alternative to the Matlab function null(S_df, 'r') (which is significantly faster). Warning: This is extremely time consuming. Please use the MATLAB version. M = Matrix([[16, 2, 3,13], [5,11,10, 8], [9, 7, 6,12], [4,14,15, 1]]) print(nsimplify(M, rational=True).nullspace()) """ if logger is None: logger = create_logger( name="optstoicpy.script.database_preprocessing.internal_loop_analysis") raise NotImplementedError("Use the Matlab version as this is too slow.") reactions = S_df_no_cofactor.columns.tolist() metabolites = S_df_no_cofactor.index.tolist() Sint = S_df_no_cofactor.as_matrix() # Sint_mat = Matrix(Sint) # too slow Smat = SparseMatrix(Sint.astype(int)) # Get the rational basis of the null space of Sint Nint_mat = nsimplify(Smat, rational=True).nullspace() # Convert back to numpy array Nint = np.array(Nint_mat).astype(np.float64) eps = 1e-9 Nint[Nint < eps] = 0
def LDL(mat): """ Algorithm for numeric LDL factization, exploiting sparse structure. This function is a modification of scipy.sparse.SparseMatrix._LDL_sparse, allowing mpmath.mpi interval arithmetic objects as entries. L, D are SparseMatrix objects. However we assign values through _smat member to avoid type conversions to Rational. """ Lrowstruc = mat.row_structure_symbolic_cholesky() print 'Number of entries in L: ', np.sum(map(len, Lrowstruc)) L = SparseMatrix(mat.rows, mat.rows, dict([((i, i), mpi(0)) for i in range(mat.rows)])) D = SparseMatrix(mat.rows, mat.cols, {}) for i in range(len(Lrowstruc)): for j in Lrowstruc[i]: if i != j: L._smat[(i, j)] = mat._smat.get((i, j), mpi(0)) summ = 0 for p1 in Lrowstruc[i]: if p1 < j: for p2 in Lrowstruc[j]: if p2 < j: if p1 == p2: summ += L[i, p1]*L[j, p1]*D[p1, p1] else: break else: break L._smat[(i, j)] = L[i, j] - summ L._smat[(i, j)] = L[i, j] / D[j, j] elif i == j: D._smat[(i, i)] = mat._smat.get((i, i), mpi(0)) summ = 0 for k in Lrowstruc[i]: if k < i: summ += L[i, k]**2*D[k, k] else: break D._smat[(i, i)] -= summ return L, D
def test_doktocsr(): a = SparseMatrix([[1, 2, 0, 0], [0, 3, 9, 0], [0, 1, 4, 0]]) b = SparseMatrix(4, 6, [ 10, 20, 0, 0, 0, 0, 0, 30, 0, 40, 0, 0, 0, 0, 50, 60, 70, 0, 0, 0, 0, 0, 0, 80 ]) c = SparseMatrix(4, 4, [0, 0, 0, 0, 0, 12, 0, 2, 15, 0, 12, 0, 0, 0, 0, 4]) d = SparseMatrix(10, 10, {(1, 1): 12, (3, 5): 7, (7, 8): 12}) e = SparseMatrix([[0, 0, 0], [1, 0, 2], [3, 0, 0]]) f = SparseMatrix(7, 8, {(2, 3): 5, (4, 5): 12}) assert _doktocsr(a) == [[1, 2, 3, 9, 1, 4], [0, 1, 1, 2, 1, 2], [0, 2, 4, 6], [3, 4]] assert _doktocsr(b) == [[10, 20, 30, 40, 50, 60, 70, 80], [0, 1, 1, 3, 2, 3, 4, 5], [0, 2, 4, 7, 8], [4, 6]] assert _doktocsr(c) == [[12, 2, 15, 12, 4], [1, 3, 0, 2, 3], [0, 0, 2, 4, 5], [4, 4]] assert _doktocsr(d) == [[12, 7, 12], [1, 5, 8], [0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3], [10, 10]] assert _doktocsr(e) == [[1, 2, 3], [0, 2, 0], [0, 0, 2, 3], [3, 3]] assert _doktocsr(f) == [[5, 12], [3, 5], [0, 0, 0, 1, 1, 2, 2, 2], [7, 8]]
def test_upper_triangular_solve(): raises( NonSquareMatrixError, lambda: SparseMatrix([[1, 2]]). upper_triangular_solve(Matrix([[1, 2]]))) raises( ShapeError, lambda: SparseMatrix([[1, 2], [0, 4]]).upper_triangular_solve( Matrix([1]))) raises( TypeError, lambda: SparseMatrix([[1, 2], [3, 4]]).upper_triangular_solve( Matrix([[1, 2], [3, 4]]))) a, b, c, d = symbols('a:d') u, v, w, x = symbols('u:x') A = SparseMatrix([[a, b], [0, d]]) B = MutableSparseMatrix([[u, v], [w, x]]) C = ImmutableSparseMatrix([[u, v], [w, x]]) sol = Matrix([[(u - b * w / d) / a, (v - b * x / d) / a], [w / d, x / d]]) assert A.upper_triangular_solve(B) == sol assert A.upper_triangular_solve(C) == sol
def test_lower_triangular_solve(): raises( NonSquareMatrixError, lambda: SparseMatrix([[1, 2]]). lower_triangular_solve(Matrix([[1, 2]]))) raises( ShapeError, lambda: SparseMatrix([[1, 2], [0, 4]]).lower_triangular_solve( Matrix([1]))) raises( ValueError, lambda: SparseMatrix([[1, 2], [3, 4]]).lower_triangular_solve( Matrix([[1, 2], [3, 4]]))) a, b, c, d = symbols('a:d') u, v, w, x = symbols('u:x') A = SparseMatrix([[a, 0], [c, d]]) B = MutableSparseMatrix([[u, v], [w, x]]) C = ImmutableSparseMatrix([[u, v], [w, x]]) sol = Matrix([[u / a, v / a], [(w - c * u / a) / d, (x - c * v / a) / d]]) assert A.lower_triangular_solve(B) == sol assert A.lower_triangular_solve(C) == sol
def test_sparse_matrix(): def sparse_eye(n): return SparseMatrix.eye(n) def sparse_zeros(n): return SparseMatrix.zeros(n) # creation args raises(TypeError, lambda: SparseMatrix(1, 2)) a = SparseMatrix(( (1, 0), (0, 1) )) assert SparseMatrix(a) == a from sympy.matrices import MutableSparseMatrix, MutableDenseMatrix a = MutableSparseMatrix([]) b = MutableDenseMatrix([1, 2]) assert a.row_join(b) == b assert a.col_join(b) == b assert type(a.row_join(b)) == type(a) assert type(a.col_join(b)) == type(a) # make sure 0 x n matrices get stacked correctly sparse_matrices = [SparseMatrix.zeros(0, n) for n in range(4)] assert SparseMatrix.hstack(*sparse_matrices) == Matrix(0, 6, []) sparse_matrices = [SparseMatrix.zeros(n, 0) for n in range(4)] assert SparseMatrix.vstack(*sparse_matrices) == Matrix(6, 0, []) # test element assignment a = SparseMatrix(( (1, 0), (0, 1) )) a[3] = 4 assert a[1, 1] == 4 a[3] = 1 a[0, 0] = 2 assert a == SparseMatrix(( (2, 0), (0, 1) )) a[1, 0] = 5 assert a == SparseMatrix(( (2, 0), (5, 1) )) a[1, 1] = 0 assert a == SparseMatrix(( (2, 0), (5, 0) )) assert a._smat == {(0, 0): 2, (1, 0): 5} # test_multiplication a = SparseMatrix(( (1, 2), (3, 1), (0, 6), )) b = SparseMatrix(( (1, 2), (3, 0), )) c = a*b assert c[0, 0] == 7 assert c[0, 1] == 2 assert c[1, 0] == 6 assert c[1, 1] == 6 assert c[2, 0] == 18 assert c[2, 1] == 0 try: eval('c = a @ b') except SyntaxError: pass else: assert c[0, 0] == 7 assert c[0, 1] == 2 assert c[1, 0] == 6 assert c[1, 1] == 6 assert c[2, 0] == 18 assert c[2, 1] == 0 x = Symbol("x") c = b * Symbol("x") assert isinstance(c, SparseMatrix) assert c[0, 0] == x assert c[0, 1] == 2*x assert c[1, 0] == 3*x assert c[1, 1] == 0 c = 5 * b assert isinstance(c, SparseMatrix) assert c[0, 0] == 5 assert c[0, 1] == 2*5 assert c[1, 0] == 3*5 assert c[1, 1] == 0 #test_power A = SparseMatrix([[2, 3], [4, 5]]) assert (A**5)[:] == [6140, 8097, 10796, 14237] A = SparseMatrix([[2, 1, 3], [4, 2, 4], [6, 12, 1]]) assert (A**3)[:] == [290, 262, 251, 448, 440, 368, 702, 954, 433] # test_creation x = Symbol("x") a = SparseMatrix([[x, 0], [0, 0]]) m = a assert m.cols == m.rows assert m.cols == 2 assert m[:] == [x, 0, 0, 0] b = SparseMatrix(2, 2, [x, 0, 0, 0]) m = b assert m.cols == m.rows assert m.cols == 2 assert m[:] == [x, 0, 0, 0] assert a == b S = sparse_eye(3) S.row_del(1) assert S == SparseMatrix([ [1, 0, 0], [0, 0, 1]]) S = sparse_eye(3) S.col_del(1) assert S == SparseMatrix([ [1, 0], [0, 0], [0, 1]]) S = SparseMatrix.eye(3) S[2, 1] = 2 S.col_swap(1, 0) assert S == SparseMatrix([ [0, 1, 0], [1, 0, 0], [2, 0, 1]]) a = SparseMatrix(1, 2, [1, 2]) b = a.copy() c = a.copy() assert a[0] == 1 a.row_del(0) assert a == SparseMatrix(0, 2, []) b.col_del(1) assert b == SparseMatrix(1, 1, [1]) # test_determinant x, y = Symbol('x'), Symbol('y') assert SparseMatrix(1, 1, [0]).det() == 0 assert SparseMatrix([[1]]).det() == 1 assert SparseMatrix(((-3, 2), (8, -5))).det() == -1 assert SparseMatrix(((x, 1), (y, 2*y))).det() == 2*x*y - y assert SparseMatrix(( (1, 1, 1), (1, 2, 3), (1, 3, 6) )).det() == 1 assert SparseMatrix(( ( 3, -2, 0, 5), (-2, 1, -2, 2), ( 0, -2, 5, 0), ( 5, 0, 3, 4) )).det() == -289 assert SparseMatrix(( ( 1, 2, 3, 4), ( 5, 6, 7, 8), ( 9, 10, 11, 12), (13, 14, 15, 16) )).det() == 0 assert SparseMatrix(( (3, 2, 0, 0, 0), (0, 3, 2, 0, 0), (0, 0, 3, 2, 0), (0, 0, 0, 3, 2), (2, 0, 0, 0, 3) )).det() == 275 assert SparseMatrix(( (1, 0, 1, 2, 12), (2, 0, 1, 1, 4), (2, 1, 1, -1, 3), (3, 2, -1, 1, 8), (1, 1, 1, 0, 6) )).det() == -55 assert SparseMatrix(( (-5, 2, 3, 4, 5), ( 1, -4, 3, 4, 5), ( 1, 2, -3, 4, 5), ( 1, 2, 3, -2, 5), ( 1, 2, 3, 4, -1) )).det() == 11664 assert SparseMatrix(( ( 2, 7, -1, 3, 2), ( 0, 0, 1, 0, 1), (-2, 0, 7, 0, 2), (-3, -2, 4, 5, 3), ( 1, 0, 0, 0, 1) )).det() == 123 # test_slicing m0 = sparse_eye(4) assert m0[:3, :3] == sparse_eye(3) assert m0[2:4, 0:2] == sparse_zeros(2) m1 = SparseMatrix(3, 3, lambda i, j: i + j) assert m1[0, :] == SparseMatrix(1, 3, (0, 1, 2)) assert m1[1:3, 1] == SparseMatrix(2, 1, (2, 3)) m2 = SparseMatrix( [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]]) assert m2[:, -1] == SparseMatrix(4, 1, [3, 7, 11, 15]) assert m2[-2:, :] == SparseMatrix([[8, 9, 10, 11], [12, 13, 14, 15]]) assert SparseMatrix([[1, 2], [3, 4]])[[1], [1]] == Matrix([[4]]) # test_submatrix_assignment m = sparse_zeros(4) m[2:4, 2:4] = sparse_eye(2) assert m == SparseMatrix([(0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1)]) assert len(m._smat) == 2 m[:2, :2] = sparse_eye(2) assert m == sparse_eye(4) m[:, 0] = SparseMatrix(4, 1, (1, 2, 3, 4)) assert m == SparseMatrix([(1, 0, 0, 0), (2, 1, 0, 0), (3, 0, 1, 0), (4, 0, 0, 1)]) m[:, :] = sparse_zeros(4) assert m == sparse_zeros(4) m[:, :] = ((1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16)) assert m == SparseMatrix((( 1, 2, 3, 4), ( 5, 6, 7, 8), ( 9, 10, 11, 12), (13, 14, 15, 16))) m[:2, 0] = [0, 0] assert m == SparseMatrix((( 0, 2, 3, 4), ( 0, 6, 7, 8), ( 9, 10, 11, 12), (13, 14, 15, 16))) # test_reshape m0 = sparse_eye(3) assert m0.reshape(1, 9) == SparseMatrix(1, 9, (1, 0, 0, 0, 1, 0, 0, 0, 1)) m1 = SparseMatrix(3, 4, lambda i, j: i + j) assert m1.reshape(4, 3) == \ SparseMatrix([(0, 1, 2), (3, 1, 2), (3, 4, 2), (3, 4, 5)]) assert m1.reshape(2, 6) == \ SparseMatrix([(0, 1, 2, 3, 1, 2), (3, 4, 2, 3, 4, 5)]) # test_applyfunc m0 = sparse_eye(3) assert m0.applyfunc(lambda x: 2*x) == sparse_eye(3)*2 assert m0.applyfunc(lambda x: 0 ) == sparse_zeros(3) # test__eval_Abs assert abs(SparseMatrix(((x, 1), (y, 2*y)))) == SparseMatrix(((Abs(x), 1), (Abs(y), 2*Abs(y)))) # test_LUdecomp testmat = SparseMatrix([[ 0, 2, 5, 3], [ 3, 3, 7, 4], [ 8, 4, 0, 2], [-2, 6, 3, 4]]) L, U, p = testmat.LUdecomposition() assert L.is_lower assert U.is_upper assert (L*U).permute_rows(p, 'backward') - testmat == sparse_zeros(4) testmat = SparseMatrix([[ 6, -2, 7, 4], [ 0, 3, 6, 7], [ 1, -2, 7, 4], [-9, 2, 6, 3]]) L, U, p = testmat.LUdecomposition() assert L.is_lower assert U.is_upper assert (L*U).permute_rows(p, 'backward') - testmat == sparse_zeros(4) x, y, z = Symbol('x'), Symbol('y'), Symbol('z') M = Matrix(((1, x, 1), (2, y, 0), (y, 0, z))) L, U, p = M.LUdecomposition() assert L.is_lower assert U.is_upper assert (L*U).permute_rows(p, 'backward') - M == sparse_zeros(3) # test_LUsolve A = SparseMatrix([[2, 3, 5], [3, 6, 2], [8, 3, 6]]) x = SparseMatrix(3, 1, [3, 7, 5]) b = A*x soln = A.LUsolve(b) assert soln == x A = SparseMatrix([[0, -1, 2], [5, 10, 7], [8, 3, 4]]) x = SparseMatrix(3, 1, [-1, 2, 5]) b = A*x soln = A.LUsolve(b) assert soln == x # test_inverse A = sparse_eye(4) assert A.inv() == sparse_eye(4) assert A.inv(method="CH") == sparse_eye(4) assert A.inv(method="LDL") == sparse_eye(4) A = SparseMatrix([[2, 3, 5], [3, 6, 2], [7, 2, 6]]) Ainv = SparseMatrix(Matrix(A).inv()) assert A*Ainv == sparse_eye(3) assert A.inv(method="CH") == Ainv assert A.inv(method="LDL") == Ainv A = SparseMatrix([[2, 3, 5], [3, 6, 2], [5, 2, 6]]) Ainv = SparseMatrix(Matrix(A).inv()) assert A*Ainv == sparse_eye(3) assert A.inv(method="CH") == Ainv assert A.inv(method="LDL") == Ainv # test_cross v1 = Matrix(1, 3, [1, 2, 3]) v2 = Matrix(1, 3, [3, 4, 5]) assert v1.cross(v2) == Matrix(1, 3, [-2, 4, -2]) assert v1.norm(2)**2 == 14 # conjugate a = SparseMatrix(((1, 2 + I), (3, 4))) assert a.C == SparseMatrix([ [1, 2 - I], [3, 4] ]) # mul assert a*Matrix(2, 2, [1, 0, 0, 1]) == a assert a + Matrix(2, 2, [1, 1, 1, 1]) == SparseMatrix([ [2, 3 + I], [4, 5] ]) # col join assert a.col_join(sparse_eye(2)) == SparseMatrix([ [1, 2 + I], [3, 4], [1, 0], [0, 1] ]) # symmetric assert not a.is_symmetric(simplify=False) # test_cofactor assert sparse_eye(3) == sparse_eye(3).cofactor_matrix() test = SparseMatrix([[1, 3, 2], [2, 6, 3], [2, 3, 6]]) assert test.cofactor_matrix() == \ SparseMatrix([[27, -6, -6], [-12, 2, 3], [-3, 1, 0]]) test = SparseMatrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) assert test.cofactor_matrix() == \ SparseMatrix([[-3, 6, -3], [6, -12, 6], [-3, 6, -3]]) # test_jacobian x = Symbol('x') y = Symbol('y') L = SparseMatrix(1, 2, [x**2*y, 2*y**2 + x*y]) syms = [x, y] assert L.jacobian(syms) == Matrix([[2*x*y, x**2], [y, 4*y + x]]) L = SparseMatrix(1, 2, [x, x**2*y**3]) assert L.jacobian(syms) == SparseMatrix([[1, 0], [2*x*y**3, x**2*3*y**2]]) # test_QR A = Matrix([[1, 2], [2, 3]]) Q, S = A.QRdecomposition() R = Rational assert Q == Matrix([ [ 5**R(-1, 2), (R(2)/5)*(R(1)/5)**R(-1, 2)], [2*5**R(-1, 2), (-R(1)/5)*(R(1)/5)**R(-1, 2)]]) assert S == Matrix([ [5**R(1, 2), 8*5**R(-1, 2)], [ 0, (R(1)/5)**R(1, 2)]]) assert Q*S == A assert Q.T * Q == sparse_eye(2) R = Rational # test nullspace # first test reduced row-ech form M = SparseMatrix([[5, 7, 2, 1], [1, 6, 2, -1]]) out, tmp = M.rref() assert out == Matrix([[1, 0, -R(2)/23, R(13)/23], [0, 1, R(8)/23, R(-6)/23]]) M = SparseMatrix([[ 1, 3, 0, 2, 6, 3, 1], [-2, -6, 0, -2, -8, 3, 1], [ 3, 9, 0, 0, 6, 6, 2], [-1, -3, 0, 1, 0, 9, 3]]) out, tmp = M.rref() assert out == Matrix([[1, 3, 0, 0, 2, 0, 0], [0, 0, 0, 1, 2, 0, 0], [0, 0, 0, 0, 0, 1, R(1)/3], [0, 0, 0, 0, 0, 0, 0]]) # now check the vectors basis = M.nullspace() assert basis[0] == Matrix([-3, 1, 0, 0, 0, 0, 0]) assert basis[1] == Matrix([0, 0, 1, 0, 0, 0, 0]) assert basis[2] == Matrix([-2, 0, 0, -2, 1, 0, 0]) assert basis[3] == Matrix([0, 0, 0, 0, 0, R(-1)/3, 1]) # test eigen x = Symbol('x') y = Symbol('y') sparse_eye3 = sparse_eye(3) assert sparse_eye3.charpoly(x) == PurePoly(((x - 1)**3)) assert sparse_eye3.charpoly(y) == PurePoly(((y - 1)**3)) # test values M = Matrix([( 0, 1, -1), ( 1, 1, 0), (-1, 0, 1)]) vals = M.eigenvals() assert sorted(vals.keys()) == [-1, 1, 2] R = Rational M = Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) assert M.eigenvects() == [(1, 3, [ Matrix([1, 0, 0]), Matrix([0, 1, 0]), Matrix([0, 0, 1])])] M = Matrix([[5, 0, 2], [3, 2, 0], [0, 0, 1]]) assert M.eigenvects() == [(1, 1, [Matrix([R(-1)/2, R(3)/2, 1])]), (2, 1, [Matrix([0, 1, 0])]), (5, 1, [Matrix([1, 1, 0])])] assert M.zeros(3, 5) == SparseMatrix(3, 5, {}) A = SparseMatrix(10, 10, {(0, 0): 18, (0, 9): 12, (1, 4): 18, (2, 7): 16, (3, 9): 12, (4, 2): 19, (5, 7): 16, (6, 2): 12, (9, 7): 18}) assert A.row_list() == [(0, 0, 18), (0, 9, 12), (1, 4, 18), (2, 7, 16), (3, 9, 12), (4, 2, 19), (5, 7, 16), (6, 2, 12), (9, 7, 18)] assert A.col_list() == [(0, 0, 18), (4, 2, 19), (6, 2, 12), (1, 4, 18), (2, 7, 16), (5, 7, 16), (9, 7, 18), (0, 9, 12), (3, 9, 12)] assert SparseMatrix.eye(2).nnz() == 2
def cse(exprs, symbols=None, optimizations=None, postprocess=None, order='canonical', ignore=()): """ Perform common subexpression elimination on an expression. Parameters ========== exprs : list of sympy expressions, or a single sympy expression The expressions to reduce. symbols : infinite iterator yielding unique Symbols The symbols used to label the common subexpressions which are pulled out. The ``numbered_symbols`` generator is useful. The default is a stream of symbols of the form "x0", "x1", etc. This must be an infinite iterator. optimizations : list of (callable, callable) pairs The (preprocessor, postprocessor) pairs of external optimization functions. Optionally 'basic' can be passed for a set of predefined basic optimizations. Such 'basic' optimizations were used by default in old implementation, however they can be really slow on larger expressions. Now, no pre or post optimizations are made by default. postprocess : a function which accepts the two return values of cse and returns the desired form of output from cse, e.g. if you want the replacements reversed the function might be the following lambda: lambda r, e: return reversed(r), e order : string, 'none' or 'canonical' The order by which Mul and Add arguments are processed. If set to 'canonical', arguments will be canonically ordered. If set to 'none', ordering will be faster but dependent on expressions hashes, thus machine dependent and variable. For large expressions where speed is a concern, use the setting order='none'. ignore : iterable of Symbols Substitutions containing any Symbol from ``ignore`` will be ignored. Returns ======= replacements : list of (Symbol, expression) pairs All of the common subexpressions that were replaced. Subexpressions earlier in this list might show up in subexpressions later in this list. reduced_exprs : list of sympy expressions The reduced expressions with all of the replacements above. Examples ======== >>> from sympy import cse, SparseMatrix >>> from sympy.abc import x, y, z, w >>> cse(((w + x + y + z)*(w + y + z))/(w + x)**3) ([(x0, w + y + z)], [x0*(x + x0)/(w + x)**3]) Note that currently, y + z will not get substituted if -y - z is used. >>> cse(((w + x + y + z)*(w - y - z))/(w + x)**3) ([(x0, w + x)], [(w - y - z)*(x0 + y + z)/x0**3]) List of expressions with recursive substitutions: >>> m = SparseMatrix([x + y, x + y + z]) >>> cse([(x+y)**2, x + y + z, y + z, x + z + y, m]) ([(x0, x + y), (x1, x0 + z)], [x0**2, x1, y + z, x1, Matrix([ [x0], [x1]])]) Note: the type and mutability of input matrices is retained. >>> isinstance(_[1][-1], SparseMatrix) True The user may disallow substitutions containing certain symbols: >>> cse([y**2*(x + 1), 3*y**2*(x + 1)], ignore=(y,)) ([(x0, x + 1)], [x0*y**2, 3*x0*y**2]) """ from sympy.matrices import (MatrixBase, Matrix, ImmutableMatrix, SparseMatrix, ImmutableSparseMatrix) # Handle the case if just one expression was passed. if isinstance(exprs, (Basic, MatrixBase)): exprs = [exprs] copy = exprs temp = [] for e in exprs: if isinstance(e, (Matrix, ImmutableMatrix)): temp.append(Tuple(*e._mat)) elif isinstance(e, (SparseMatrix, ImmutableSparseMatrix)): temp.append(Tuple(*e._smat.items())) else: temp.append(e) exprs = temp del temp if optimizations is None: optimizations = list() elif optimizations == 'basic': optimizations = basic_optimizations # Preprocess the expressions to give us better optimization opportunities. reduced_exprs = [preprocess_for_cse(e, optimizations) for e in exprs] excluded_symbols = set().union(*[expr.atoms(Symbol) for expr in reduced_exprs]) if symbols is None: symbols = numbered_symbols() else: # In case we get passed an iterable with an __iter__ method instead of # an actual iterator. symbols = iter(symbols) symbols = filter_symbols(symbols, excluded_symbols) # Find other optimization opportunities. opt_subs = opt_cse(reduced_exprs, order) # Main CSE algorithm. replacements, reduced_exprs = tree_cse(reduced_exprs, symbols, opt_subs, order, ignore) # Postprocess the expressions to return the expressions to canonical form. exprs = copy for i, (sym, subtree) in enumerate(replacements): subtree = postprocess_for_cse(subtree, optimizations) replacements[i] = (sym, subtree) reduced_exprs = [postprocess_for_cse(e, optimizations) for e in reduced_exprs] # Get the matrices back for i, e in enumerate(exprs): if isinstance(e, (Matrix, ImmutableMatrix)): reduced_exprs[i] = Matrix(e.rows, e.cols, reduced_exprs[i]) if isinstance(e, ImmutableMatrix): reduced_exprs[i] = reduced_exprs[i].as_immutable() elif isinstance(e, (SparseMatrix, ImmutableSparseMatrix)): m = SparseMatrix(e.rows, e.cols, {}) for k, v in reduced_exprs[i]: m[k] = v if isinstance(e, ImmutableSparseMatrix): m = m.as_immutable() reduced_exprs[i] = m if postprocess is None: return replacements, reduced_exprs return postprocess(replacements, reduced_exprs)
def sparse_eye(n): return SparseMatrix.eye(n)
def test_sparse_zeros_sparse_eye(): assert SparseMatrix.eye(3) == eye(3, cls=SparseMatrix) assert len(SparseMatrix.eye(3)._smat) == 3 assert SparseMatrix.zeros(3) == zeros(3, cls=SparseMatrix) assert len(SparseMatrix.zeros(3)._smat) == 0
def sparse_zeros(n): return SparseMatrix.zeros(n)
def test_sparse_solve(): from sympy.matrices import SparseMatrix A = SparseMatrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11))) assert A.cholesky() == Matrix([ [ 5, 0, 0], [ 3, 3, 0], [-1, 1, 3]]) assert A.cholesky() * A.cholesky().T == Matrix([ [25, 15, -5], [15, 18, 0], [-5, 0, 11]]) A = SparseMatrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11))) L, D = A.LDLdecomposition() assert 15*L == Matrix([ [15, 0, 0], [ 9, 15, 0], [-3, 5, 15]]) assert D == Matrix([ [25, 0, 0], [ 0, 9, 0], [ 0, 0, 9]]) assert L * D * L.T == A A = SparseMatrix(((3, 0, 2), (0, 0, 1), (1, 2, 0))) assert A.inv() * A == SparseMatrix(eye(3)) A = SparseMatrix([ [ 2, -1, 0], [-1, 2, -1], [ 0, 0, 2]]) ans = SparseMatrix([ [S(2)/3, S(1)/3, S(1)/6], [S(1)/3, S(2)/3, S(1)/3], [ 0, 0, S(1)/2]]) assert A.inv(method='CH') == ans assert A.inv(method='LDL') == ans assert A * ans == SparseMatrix(eye(3)) s = A.solve(A[:, 0], 'LDL') assert A*s == A[:, 0] s = A.solve(A[:, 0], 'CH') assert A*s == A[:, 0] A = A.col_join(A) s = A.solve_least_squares(A[:, 0], 'CH') assert A*s == A[:, 0] s = A.solve_least_squares(A[:, 0], 'LDL') assert A*s == A[:, 0]