def test_multiplication(): A = MatrixSymbol('A', n, m) B = MatrixSymbol('B', m, l) C = MatrixSymbol('C', n, n) assert (2 * A * B).shape == (n, l) assert (A * 0 * B) == ZeroMatrix(n, l) raises(ShapeError, lambda: B * A) assert (2 * A).shape == A.shape assert A * ZeroMatrix(m, m) * B == ZeroMatrix(n, l) assert C * Identity(n) * C.I == Identity(n) assert B / 2 == S.Half * B raises(NotImplementedError, lambda: 2 / B) A = MatrixSymbol('A', n, n) B = MatrixSymbol('B', n, n) assert Identity(n) * (A + B) == A + B assert A**2 * A == A**3 assert A**2 * (A.I)**3 == A.I assert A**3 * (A.I)**2 == A
def test_arrayexpr_array_expr_zero_array(): za1 = ZeroArray(k, l, m, n) zm1 = ZeroMatrix(m, n) za2 = ZeroArray(k, m, m, n) zm2 = ZeroMatrix(m, m) zm3 = ZeroMatrix(k, k) assert _array_tensor_product(M, N, za1) == ZeroArray(k, k, k, k, k, l, m, n) assert _array_tensor_product(M, N, zm1) == ZeroArray(k, k, k, k, m, n) assert _array_contraction(za1, (3,)) == ZeroArray(k, l, m) assert _array_contraction(zm1, (1,)) == ZeroArray(m) assert _array_contraction(za2, (1, 2)) == ZeroArray(k, n) assert _array_contraction(zm2, (0, 1)) == 0 assert _array_diagonal(za2, (1, 2)) == ZeroArray(k, n, m) assert _array_diagonal(zm2, (0, 1)) == ZeroArray(m) assert _permute_dims(za1, [2, 1, 3, 0]) == ZeroArray(m, l, n, k) assert _permute_dims(zm1, [1, 0]) == ZeroArray(n, m) assert _array_add(za1) == za1 assert _array_add(zm1) == ZeroArray(m, n) tp1 = _array_tensor_product(MatrixSymbol("A", k, l), MatrixSymbol("B", m, n)) assert _array_add(tp1, za1) == tp1 tp2 = _array_tensor_product(MatrixSymbol("C", k, l), MatrixSymbol("D", m, n)) assert _array_add(tp1, za1, tp2) == _array_add(tp1, tp2) assert _array_add(M, zm3) == M assert _array_add(M, N, zm3) == _array_add(M, N)
def test_issue_7842(): A = MatrixSymbol('A', 3, 1) B = MatrixSymbol('B', 2, 1) assert Eq(A, B) == False assert Eq(A[1, 0], B[1, 0]).func is Eq A = ZeroMatrix(2, 3) B = ZeroMatrix(2, 3) assert Eq(A, B) == True
def test_Zero_power(): z1 = ZeroMatrix(n, n) assert z1**4 == z1 raises(ValueError, lambda: z1**-2) assert z1**0 == Identity(n) assert MatPow(z1, 2).doit() == z1**2 raises(ValueError, lambda: MatPow(z1, -2).doit()) z2 = ZeroMatrix(3, 3) assert MatPow(z2, 4).doit() == z2**4 raises(ValueError, lambda: z2**-3) assert z2**3 == MatPow(z2, 3).doit() assert z2**0 == Identity(3) raises(ValueError, lambda: MatPow(z2, -1).doit())
def blocks(self): from sympy.matrices.immutable import ImmutableDenseMatrix mats = self.args data = [[mats[i] if i == j else ZeroMatrix(mats[i].rows, mats[j].cols) for j in range(len(mats))] for i in range(len(mats))] return ImmutableDenseMatrix(data, evaluate=False)
def test_MatrixSet(): n, m = symbols('n m', integer=True) A = MatrixSymbol('A', n, m) C = MatrixSymbol('C', n, n) M = MatrixSet(2, 2, set=S.Reals) assert M.shape == (2, 2) assert M.set == S.Reals X = Matrix([[1, 2], [3, 4]]) assert X in M X = ZeroMatrix(2, 2) assert X in M raises(TypeError, lambda: A in M) raises(TypeError, lambda: 1 in M) M = MatrixSet(n, m, set=S.Reals) assert A in M raises(TypeError, lambda: C in M) raises(TypeError, lambda: X in M) M = MatrixSet(2, 2, set={1, 2, 3}) X = Matrix([[1, 2], [3, 4]]) Y = Matrix([[1, 2]]) assert (X in M) == S.false assert (Y in M) == S.false raises(ValueError, lambda: MatrixSet(2, -2, S.Reals)) raises(ValueError, lambda: MatrixSet(2.4, -1, S.Reals)) raises(TypeError, lambda: MatrixSet(2, 2, (1, 2, 3)))
def test_MatrixPermute_doit(): p = Permutation(0, 1, 2) A = MatrixSymbol('A', 3, 3) assert MatrixPermute(A, p).doit() == MatrixPermute(A, p) p = Permutation(0, size=3) A = MatrixSymbol('A', 3, 3) assert MatrixPermute(A, p).doit().as_explicit() == \ MatrixPermute(A, p).as_explicit() p = Permutation(0, 1, 2) A = Identity(3) assert MatrixPermute(A, p, 0).doit().as_explicit() == \ MatrixPermute(A, p, 0).as_explicit() assert MatrixPermute(A, p, 1).doit().as_explicit() == \ MatrixPermute(A, p, 1).as_explicit() A = ZeroMatrix(3, 3) assert MatrixPermute(A, p).doit() == A A = OneMatrix(3, 3) assert MatrixPermute(A, p).doit() == A A = MatrixSymbol('A', 4, 4) p1 = Permutation(0, 1, 2, 3) p2 = Permutation(0, 2, 3, 1) expr = MatrixPermute(MatrixPermute(A, p1, 0), p2, 0) assert expr.as_explicit() == expr.doit().as_explicit() expr = MatrixPermute(MatrixPermute(A, p1, 1), p2, 1) assert expr.as_explicit() == expr.doit().as_explicit()
def test_addition(): A = MatrixSymbol('A', n, m) B = MatrixSymbol('B', n, m) assert isinstance(A + B, MatAdd) assert (A + B).shape == A.shape assert isinstance(A - A + 2 * B, MatMul) raises(ShapeError, lambda: A + B.T) raises(TypeError, lambda: A + 1) raises(TypeError, lambda: 5 + A) raises(TypeError, lambda: 5 - A) assert A + ZeroMatrix(n, m) - A == ZeroMatrix(n, m) with raises(TypeError): ZeroMatrix(n, m) + S.Zero
def test_mixed_deriv_mixed_expressions(): expr = 3 * Trace(A) assert expr.diff(A) == 3 * Identity(k) expr = k deriv = expr.diff(A) assert isinstance(deriv, ZeroMatrix) assert deriv == ZeroMatrix(k, k) expr = Trace(A)**2 assert expr.diff(A) == (2 * Trace(A)) * Identity(k) expr = Trace(A) * A I = Identity(k) assert expr.diff(A) == ArrayAdd( ArrayTensorProduct(I, A), PermuteDims(ArrayTensorProduct(Trace(A) * I, I), Permutation(3)(1, 2))) expr = Trace(Trace(A) * A) assert expr.diff(A) == (2 * Trace(A)) * Identity(k) expr = Trace(Trace(Trace(A) * A) * A) assert expr.diff(A) == (3 * Trace(A)**2) * Identity(k)
def test_MatMul_postprocessor(): z = zeros(2) z1 = ZeroMatrix(2, 2) assert Mul(0, z) == Mul(z, 0) in [z, z1] M = Matrix([[1, 2], [3, 4]]) Mx = Matrix([[x, 2 * x], [3 * x, 4 * x]]) assert Mul(x, M) == Mul(M, x) == Mx A = MatrixSymbol("A", 2, 2) assert Mul(A, M) == MatMul(A, M) assert Mul(M, A) == MatMul(M, A) # Scalars should be absorbed into constant matrices a = Mul(x, M, A) b = Mul(M, x, A) c = Mul(M, A, x) assert a == b == c == MatMul(Mx, A) a = Mul(x, A, M) b = Mul(A, x, M) c = Mul(A, M, x) assert a == b == c == MatMul(A, Mx) assert Mul(M, M) == M**2 assert Mul(A, M, M) == MatMul(A, M**2) assert Mul(M, M, A) == MatMul(M**2, A) assert Mul(M, A, M) == MatMul(M, A, M) assert Mul(A, x, M, M, x) == MatMul(A, Mx**2)
def _get_zero_with_shape_like(cls, expr): if isinstance(expr, (MatrixCommon, NDimArray)): return expr.zeros(*expr.shape) elif isinstance(expr, MatrixExpr): return ZeroMatrix(*expr.shape) else: raise RuntimeError("Unable to determine shape of array-derivative.")
def UDLdecomposition(self): """Returns the Block UDL decomposition of a 2x2 Block Matrix Returns ======= (U, D, L) : Matrices U : Upper Diagonal Matrix D : Diagonal Matrix L : Lower Diagonal Matrix Examples ======== >>> from sympy import symbols, MatrixSymbol, BlockMatrix, block_collapse >>> m, n = symbols('m n') >>> A = MatrixSymbol('A', n, n) >>> B = MatrixSymbol('B', n, m) >>> C = MatrixSymbol('C', m, n) >>> D = MatrixSymbol('D', m, m) >>> X = BlockMatrix([[A, B], [C, D]]) >>> U, D, L = X.UDLdecomposition() >>> block_collapse(U*D*L) Matrix([ [A, B], [C, D]]) Raises ====== ShapeError If the block matrix is not a 2x2 matrix NonInvertibleMatrixError If the matrix "D" is non-invertible See Also ======== sympy.matrices.expressions.blockmatrix.BlockMatrix.LDUdecomposition sympy.matrices.expressions.blockmatrix.BlockMatrix.LUdecomposition """ if self.blockshape == (2,2): [[A, B], [C, D]] = self.blocks.tolist() try: DI = D.I except NonInvertibleMatrixError: raise NonInvertibleMatrixError('Block UDL decomposition cannot be calculated when\ "D" is singular') Ip = Identity(A.shape[0]) Iq = Identity(B.shape[1]) Z = ZeroMatrix(*B.shape) U = BlockMatrix([[Ip, B*DI], [Z.T, Iq]]) D = BlockDiagMatrix(self.schur('D'), D) L = BlockMatrix([[Ip, Z],[DI*C, Iq]]) return U, D, L else: raise ShapeError("Block UDL decomposition is supported only for 2x2 block matrices")
def LUdecomposition(self): """Returns the Block LU decomposition of a 2x2 Block Matrix Returns ======= (L, U) : Matrices L : Lower Diagonal Matrix U : Upper Diagonal Matrix Examples ======== >>> from sympy import symbols, MatrixSymbol, BlockMatrix, block_collapse >>> m, n = symbols('m n') >>> A = MatrixSymbol('A', n, n) >>> B = MatrixSymbol('B', n, m) >>> C = MatrixSymbol('C', m, n) >>> D = MatrixSymbol('D', m, m) >>> X = BlockMatrix([[A, B], [C, D]]) >>> L, U = X.LUdecomposition() >>> block_collapse(L*U) Matrix([ [A, B], [C, D]]) Raises ====== ShapeError If the block matrix is not a 2x2 matrix NonInvertibleMatrixError If the matrix "A" is non-invertible See Also ======== sympy.matrices.expressions.blockmatrix.BlockMatrix.UDLdecomposition sympy.matrices.expressions.blockmatrix.BlockMatrix.LDUdecomposition """ if self.blockshape == (2, 2): [[A, B], [C, D]] = self.blocks.tolist() try: A = A**0.5 AI = A.I except NonInvertibleMatrixError: raise NonInvertibleMatrixError( 'Block LU decomposition cannot be calculated when\ "A" is singular') Z = ZeroMatrix(*B.shape) Q = self.schur()**0.5 L = BlockMatrix([[A, Z], [C * AI, Q]]) U = BlockMatrix([[A, AI * B], [Z.T, Q]]) return L, U else: raise ShapeError( "Block LU decomposition is supported only for 2x2 block matrices" )
def test_arrayexpr_convert_array_to_matrix(): cg = _array_contraction(_array_tensor_product(M), (0, 1)) assert convert_array_to_matrix(cg) == Trace(M) cg = _array_contraction(_array_tensor_product(M, N), (0, 1), (2, 3)) assert convert_array_to_matrix(cg) == Trace(M) * Trace(N) cg = _array_contraction(_array_tensor_product(M, N), (0, 3), (1, 2)) assert convert_array_to_matrix(cg) == Trace(M * N) cg = _array_contraction(_array_tensor_product(M, N), (0, 2), (1, 3)) assert convert_array_to_matrix(cg) == Trace(M * N.T) cg = convert_matrix_to_array(M * N * P) assert convert_array_to_matrix(cg) == M * N * P cg = convert_matrix_to_array(M * N.T * P) assert convert_array_to_matrix(cg) == M * N.T * P cg = _array_contraction(_array_tensor_product(M,N,P,Q), (1, 2), (5, 6)) assert convert_array_to_matrix(cg) == _array_tensor_product(M * N, P * Q) cg = _array_contraction(_array_tensor_product(-2, M, N), (1, 2)) assert convert_array_to_matrix(cg) == -2 * M * N a = MatrixSymbol("a", k, 1) b = MatrixSymbol("b", k, 1) c = MatrixSymbol("c", k, 1) cg = PermuteDims( _array_contraction( _array_tensor_product( a, ArrayAdd( _array_tensor_product(b, c), _array_tensor_product(c, b), ) ), (2, 4)), [0, 1, 3, 2]) assert convert_array_to_matrix(cg) == a * (b.T * c + c.T * b) za = ZeroArray(m, n) assert convert_array_to_matrix(za) == ZeroMatrix(m, n) cg = _array_tensor_product(3, M) assert convert_array_to_matrix(cg) == 3 * M # Partial conversion to matrix multiplication: expr = _array_contraction(_array_tensor_product(M, N, P, Q), (0, 2), (1, 4, 6)) assert convert_array_to_matrix(expr) == _array_contraction(_array_tensor_product(M.T*N, P, Q), (0, 2, 4)) x = MatrixSymbol("x", k, 1) cg = PermuteDims( _array_contraction(_array_tensor_product(OneArray(1), x, OneArray(1), DiagMatrix(Identity(1))), (0, 5)), Permutation(1, 2, 3)) assert convert_array_to_matrix(cg) == x expr = ArrayAdd(M, PermuteDims(M, [1, 0])) assert convert_array_to_matrix(expr) == M + Transpose(M)
def test_matrixsymbol_solving(): A = MatrixSymbol('A', 2, 2) B = MatrixSymbol('B', 2, 2) Z = ZeroMatrix(2, 2) assert -(-A + B) - A + B == Z assert (-(-A + B) - A + B).simplify() == Z assert (-(-A + B) - A + B).expand() == Z assert (-(-A + B) - A + B - Z).simplify() == Z assert (-(-A + B) - A + B - Z).expand() == Z
def test_invariants(): A = MatrixSymbol('A', n, m) B = MatrixSymbol('B', m, l) X = MatrixSymbol('X', n, n) objs = [Identity(n), ZeroMatrix(m, n), A, MatMul(A, B), MatAdd(A, A), Transpose(A), Adjoint(A), Inverse(X), MatPow(X, 2), MatPow(X, -1), MatPow(X, 0)] for obj in objs: assert obj == obj.__class__(*obj.args)
def expand(self, **hints): arg = self.args[0] condition = self._condition if not is_random(arg): return ZeroMatrix(*self.shape) if isinstance(arg, RandomSymbol): return self elif isinstance(arg, Add): rv = [] for a in arg.args: if is_random(a): rv.append(a) variances = Add( *map(lambda xv: Variance(xv, condition).expand(), rv)) map_to_covar = lambda x: 2 * Covariance(*x, condition=condition ).expand() covariances = Add( *map(map_to_covar, itertools.combinations(rv, 2))) return variances + covariances elif isinstance(arg, (Mul, MatMul)): nonrv = [] rv = [] for a in arg.args: if is_random(a): rv.append(a) else: nonrv.append(a) if len(rv) == 0: return ZeroMatrix(*self.shape) # Avoid possible infinite loops with MatMul: if len(nonrv) == 0: return self # Variance of many multiple matrix products is not implemented: if len(rv) > 1: return self return Mul.fromiter(nonrv) * Variance( Mul.fromiter(rv), condition) * (Mul.fromiter(nonrv)).transpose() # this expression contains a RandomSymbol somehow: return self
def test_subs_Matrix(): z = zeros(2) z1 = ZeroMatrix(2, 2) assert (x * y).subs({x: z, y: 0}) in [z, z1] assert (x * y).subs({y: z, x: 0}) == 0 assert (x * y).subs({y: z, x: 0}, simultaneous=True) in [z, z1] assert (x + y).subs({x: z, y: z}, simultaneous=True) in [z, z1] assert (x + y).subs({x: z, y: z}) in [z, z1] # Issue #15528 assert Mul(Matrix([[3]]), x).subs(x, 2.0) == Matrix([[6.0]]) # Does not raise a TypeError, see comment on the MatAdd postprocessor assert Add(Matrix([[3]]), x).subs(x, 2.0) == Add(Matrix([[3]]), 2.0)
def test_canonicalize(): X = MatrixSymbol('X', 2, 2) Y = MatrixSymbol('Y', 2, 2) expr = HadamardProduct(X, check=False) assert isinstance(expr, HadamardProduct) expr2 = expr.doit() # unpack is called assert isinstance(expr2, MatrixSymbol) Z = ZeroMatrix(2, 2) U = OneMatrix(2, 2) assert HadamardProduct(Z, X).doit() == Z assert HadamardProduct(U, X, X, U).doit() == HadamardPower(X, 2) assert HadamardProduct(X, U, Y).doit() == HadamardProduct(X, Y) assert HadamardProduct(X, Z, U, Y).doit() == Z
def test_NumPyPrinter(): from sympy.core.function import Lambda from sympy.matrices.expressions.adjoint import Adjoint from sympy.matrices.expressions.diagonal import (DiagMatrix, DiagonalMatrix, DiagonalOf) from sympy.matrices.expressions.funcmatrix import FunctionMatrix from sympy.matrices.expressions.hadamard import HadamardProduct from sympy.matrices.expressions.kronecker import KroneckerProduct from sympy.matrices.expressions.special import (OneMatrix, ZeroMatrix) from sympy.abc import a, b p = NumPyPrinter() assert p.doprint(sign(x)) == 'numpy.sign(x)' A = MatrixSymbol("A", 2, 2) B = MatrixSymbol("B", 2, 2) C = MatrixSymbol("C", 1, 5) D = MatrixSymbol("D", 3, 4) assert p.doprint(A**(-1)) == "numpy.linalg.inv(A)" assert p.doprint(A**5) == "numpy.linalg.matrix_power(A, 5)" assert p.doprint(Identity(3)) == "numpy.eye(3)" u = MatrixSymbol('x', 2, 1) v = MatrixSymbol('y', 2, 1) assert p.doprint(MatrixSolve(A, u)) == 'numpy.linalg.solve(A, x)' assert p.doprint(MatrixSolve(A, u) + v) == 'numpy.linalg.solve(A, x) + y' assert p.doprint(ZeroMatrix(2, 3)) == "numpy.zeros((2, 3))" assert p.doprint(OneMatrix(2, 3)) == "numpy.ones((2, 3))" assert p.doprint(FunctionMatrix(4, 5, Lambda((a, b), a + b))) == \ "numpy.fromfunction(lambda a, b: a + b, (4, 5))" assert p.doprint(HadamardProduct(A, B)) == "numpy.multiply(A, B)" assert p.doprint(KroneckerProduct(A, B)) == "numpy.kron(A, B)" assert p.doprint(Adjoint(A)) == "numpy.conjugate(numpy.transpose(A))" assert p.doprint(DiagonalOf(A)) == "numpy.reshape(numpy.diag(A), (-1, 1))" assert p.doprint(DiagMatrix(C)) == "numpy.diagflat(C)" assert p.doprint(DiagonalMatrix(D)) == "numpy.multiply(D, numpy.eye(3, 4))" # Workaround for numpy negative integer power errors assert p.doprint(x**-1) == 'x**(-1.0)' assert p.doprint(x**-2) == 'x**(-2.0)' expr = Pow(2, -1, evaluate=False) assert p.doprint(expr) == "2**(-1.0)" assert p.doprint(S.Exp1) == 'numpy.e' assert p.doprint(S.Pi) == 'numpy.pi' assert p.doprint(S.EulerGamma) == 'numpy.euler_gamma' assert p.doprint(S.NaN) == 'numpy.nan' assert p.doprint(S.Infinity) == 'numpy.PINF' assert p.doprint(S.NegativeInfinity) == 'numpy.NINF'
def test_zero_matrix_creation(): assert unchanged(ZeroMatrix, 2, 2) assert unchanged(ZeroMatrix, 0, 0) raises(ValueError, lambda: ZeroMatrix(-1, 2)) raises(ValueError, lambda: ZeroMatrix(2.0, 2)) raises(ValueError, lambda: ZeroMatrix(2j, 2)) raises(ValueError, lambda: ZeroMatrix(2, -1)) raises(ValueError, lambda: ZeroMatrix(2, 2.0)) raises(ValueError, lambda: ZeroMatrix(2, 2j)) n = symbols('n') assert unchanged(ZeroMatrix, n, n) n = symbols('n', integer=False) raises(ValueError, lambda: ZeroMatrix(n, n)) n = symbols('n', negative=True) raises(ValueError, lambda: ZeroMatrix(n, n))
def test_matrix_derivative_by_scalar(): assert A.diff(i) == ZeroMatrix(k, k) assert (A*(X + B)*c).diff(i) == ZeroMatrix(k, 1) assert x.diff(i) == ZeroMatrix(k, 1) assert (x.T*y).diff(i) == ZeroMatrix(1, 1) assert (x*x.T).diff(i) == ZeroMatrix(k, k) assert (x + y).diff(i) == ZeroMatrix(k, 1) assert hadamard_power(x, 2).diff(i) == ZeroMatrix(k, 1) assert hadamard_power(x, i).diff(i).dummy_eq( HadamardProduct(x.applyfunc(log), HadamardPower(x, i))) assert hadamard_product(x, y).diff(i) == ZeroMatrix(k, 1) assert hadamard_product(i*OneMatrix(k, 1), x, y).diff(i) == hadamard_product(x, y) assert (i*x).diff(i) == x assert (sin(i)*A*B*x).diff(i) == cos(i)*A*B*x assert x.applyfunc(sin).diff(i) == ZeroMatrix(k, 1) assert Trace(i**2*X).diff(i) == 2*i*Trace(X) mu = symbols("mu") expr = (2*mu*x) assert expr.diff(x) == 2*mu*Identity(k)
def test_ZeroMatrix(): n, m = symbols('n m', integer=True) A = MatrixSymbol('A', n, m) Z = ZeroMatrix(n, m) assert A + Z == A assert A * Z.T == ZeroMatrix(n, n) assert Z * A.T == ZeroMatrix(n, n) assert A - A == ZeroMatrix(*A.shape) assert Z assert Z.transpose() == ZeroMatrix(m, n) assert Z.conjugate() == Z assert ZeroMatrix(n, n)**0 == Identity(n) with raises(NonSquareMatrixError): Z**0 with raises(NonSquareMatrixError): Z**1 with raises(NonSquareMatrixError): Z**2 assert ZeroMatrix(3, 3).as_explicit() == ImmutableDenseMatrix.zeros(3, 3)
def test_block_index(): I = Identity(3) Z = ZeroMatrix(3, 3) B = BlockMatrix([[I, I], [I, I]]) e3 = ImmutableMatrix(eye(3)) BB = BlockMatrix([[e3, e3], [e3, e3]]) assert B[0, 0] == B[3, 0] == B[0, 3] == B[3, 3] == 1 assert B[4, 3] == B[5, 1] == 0 BB = BlockMatrix([[e3, e3], [e3, e3]]) assert B.as_explicit() == BB.as_explicit() BI = BlockMatrix([[I, Z], [Z, I]]) assert BI.as_explicit().equals(eye(6))
def test_MatrixSet(): M = MatrixSet(2, 2, set=S.Reals) assert M.shape == (2, 2) assert M.set == S.Reals X = Matrix([[1, 2], [3, 4]]) assert X in M X = ZeroMatrix(2, 2) assert X in M raises(TypeError, lambda: A in M) raises(TypeError, lambda: 1 in M) M = MatrixSet(n, m, set=S.Reals) assert A in M raises(TypeError, lambda: C in M) raises(TypeError, lambda: X in M) M = MatrixSet(2, 2, set={1, 2, 3}) X = Matrix([[1, 2], [3, 4]]) Y = Matrix([[1, 2]]) assert (X in M) == S.false assert (Y in M) == S.false raises(ValueError, lambda: MatrixSet(2, -2, S.Reals)) raises(ValueError, lambda: MatrixSet(2.4, -1, S.Reals)) raises(TypeError, lambda: MatrixSet(2, 2, (1, 2, 3)))
def test_hadamard(): m, n, p = symbols('m, n, p', integer=True) A = MatrixSymbol('A', m, n) B = MatrixSymbol('B', m, n) C = MatrixSymbol('C', m, p) X = MatrixSymbol('X', m, m) I = Identity(m) with raises(TypeError): hadamard_product() assert hadamard_product(A) == A assert isinstance(hadamard_product(A, B), HadamardProduct) assert hadamard_product(A, B).doit() == hadamard_product(A, B) with raises(ShapeError): hadamard_product(A, C) hadamard_product(A, I) assert hadamard_product(X, I) == X assert isinstance(hadamard_product(X, I), MatrixSymbol) a = MatrixSymbol("a", k, 1) expr = MatAdd(ZeroMatrix(k, 1), OneMatrix(k, 1)) expr = HadamardProduct(expr, a) assert expr.doit() == a
def expand(self, **hints): arg1 = self.args[0] arg2 = self.args[1] condition = self._condition if arg1 == arg2: return VarianceMatrix(arg1, condition).expand() if not is_random(arg1) or not is_random(arg2): return ZeroMatrix(*self.shape) if isinstance(arg1, RandomSymbol) and isinstance(arg2, RandomSymbol): return CrossCovarianceMatrix(arg1, arg2, condition) coeff_rv_list1 = self._expand_single_argument(arg1.expand()) coeff_rv_list2 = self._expand_single_argument(arg2.expand()) addends = [ a * CrossCovarianceMatrix(r1, r2, condition=condition) * b.transpose() for (a, r1) in coeff_rv_list1 for (b, r2) in coeff_rv_list2 ] return Add.fromiter(addends)
def absorb(x): if any(isinstance(c, ZeroMatrix) for c in x.args): return ZeroMatrix(*x.shape) else: return x
def test_ZeroMatrix_doit(): n = symbols('n', integer=True) Znn = ZeroMatrix(Add(n, n, evaluate=False), n) assert isinstance(Znn.rows, Add) assert Znn.doit() == ZeroMatrix(2 * n, n) assert isinstance(Znn.doit().rows, Mul)
def test_matrix_add_with_scalar(): raises(TypeError, lambda: Add(0, ZeroMatrix(2, 2)))