def inverse(M): return Matrix([[1 / M[i, j] for j in range(M.shape[1])] for i in range(M.shape[0])])
from sympy import Matrix import string # Define variables dimension = 3 # Your N key = np.matrix([[6, 24, 1], [13, 16, 10], [20, 17, 15]]) # Your key message = 'LRZBHPDOG' # You message # Generate the alphabet alphabet = string.ascii_uppercase # Encrypted message decryptedMessage = "" # Get the decrypt key key = Matrix(key) key = key.inv_mod(26) key = key.tolist() # Group message in vectors and generate crypted message for index, i in enumerate(message): values = [] # Create the N blocs if index % dimension == 0: for j in range(0, dimension): values.append([alphabet.index(message[index + j])]) # Create the vectors and work with them vector = np.matrix(values) vector = key * vector vector %= 26 for j in range(0, dimension):
def Lx(a, n): x = symbols('x') return Matrix( n, 1, lambda i, j: Poly( (reduce(mul, ((x - a[k] if k != i else 1) for k in range(0, n)), 1)).expand(basic=True), x))
def test_trace(): M = Matrix([[1, 0, 0], [0, 5, 0], [0, 0, 8]]) assert M.trace() == 14
def test_evalf(): a = Matrix([sqrt(5), 6]) assert abs(a.evalf()[0] - a[0].evalf()) < 1e-10 assert abs(a.evalf()[1] - a[1].evalf()) < 1e-10
def test_sum(): x, y, z = symbols('xyz') m = Matrix([[1, 2, 3], [x, y, x], [2 * y, -50, z * x]]) assert m + m == Matrix([[2, 4, 6], [2 * x, 2 * y, 2 * x], [4 * y, -100, 2 * z * x]])
def test_eigen(): x, y = symbols('xy') R = Rational assert eye(3).charpoly(x) == Poly((x - 1)**3, x) assert eye(3).charpoly(y) == Poly((y - 1)**3, y) M = Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) assert M.eigenvals() == {S.One: 3} assert canonicalize(M.eigenvects()) == canonicalize([ (1, 3, [Matrix([1, 0, 0]), Matrix([0, 1, 0]), Matrix([0, 0, 1])]) ]) M = Matrix([[0, 1, 1], [1, 0, 0], [1, 1, 1]]) assert M.eigenvals() == {2 * S.One: 1, -S.One: 1, S.Zero: 1} assert canonicalize(M.eigenvects()) == canonicalize([ (2, 1, [Matrix([R(2, 3), R(1, 3), 1])]), (-1, 1, [Matrix([-1, 1, 0])]), (0, 1, [Matrix([0, -1, 1])]) ]) M = Matrix([[1, -1], [1, 3]]) assert canonicalize(M.eigenvects()) == canonicalize( [[2, 2, [Matrix(1, 2, [-1, 1])]]]) M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) a = R(15, 2) b = 3 * 33**R(1, 2) c = R(13, 2) d = (R(33, 8) + 3 * b / 8) e = (R(33, 8) - 3 * b / 8) def NS(e, n): return str(N(e, n)) r = [ (a - b / 2, 1, [ Matrix([ (12 + 24 / (c - b / 2)) / ((c - b / 2) * e) + 3 / (c - b / 2), (6 + 12 / (c - b / 2)) / e, 1 ]) ]), (0, 1, [Matrix([1, -2, 1])]), (a + b / 2, 1, [ Matrix([ (12 + 24 / (c + b / 2)) / ((c + b / 2) * d) + 3 / (c + b / 2), (6 + 12 / (c + b / 2)) / d, 1 ]) ]), ] r1 = [(NS(r[i][0], 2), NS(r[i][1], 2), [NS(j, 2) for j in r[i][2][0]]) for i in range(len(r))] r = M.eigenvects() r2 = [(NS(r[i][0], 2), NS(r[i][1], 2), [NS(j, 2) for j in r[i][2][0]]) for i in range(len(r))] assert sorted(r1) == sorted(r2) eps = Symbol('eps', real=True) M = Matrix([[abs(eps), I * eps], [-I * eps, abs(eps)]]) assert canonicalize(M.eigenvects()) == canonicalize([ (2 * abs(eps), 1, [Matrix([[I * eps / abs(eps)], [1]])]), (0, 1, [Matrix([[-I * eps / abs(eps)], [1]])]) ])
def test_issue_3441_3453(): assert S('[[1/3,2], (2/5,)]') == [[Rational(1, 3), 2], (Rational(2, 5), )] assert S('[[2/6,2], (2/4,)]') == [[Rational(1, 3), 2], (Rational(1, 2), )] assert S('[[[2*(1)]]]') == [[[2]]] assert S('Matrix([2*(1)])') == Matrix([2])
return A_, b_, c, cone_dict if __name__ == '__main__': import sympy from sympy import Matrix import scs import ecos a = np.random.normal(size=(100, 3)) S = np.cov(a, rowvar=False) A, b, c, cone_dict = write_glasso_cone_program(S, 1.) x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]) print(_vec2symmetric((A @ x)[1:22], 6)) x = Matrix(sympy.symbols([ "theta11", "theta21", "theta31", "theta22", "theta32", "theta33", "z11", "z22", "z33", "z21", "z31", "z32", "t1", "t2", "t3", "t" ])) print(Matrix(b) - Matrix(A.toarray()) @ x) print(Matrix(c).T @ x) sol = diffcp.solve_and_derivative(A, b, c, cone_dict) K = np.linalg.inv(S) sol = scs.solve(dict(A=A, b=b, c=c), cone_dict, eps=1e-15, max_iters=10000, verbose=True, acceleration_lookback=1) x = sol["x"] p = S.shape[0] # d = int(S.shape[0]*(S.shape[0]+1)/2) # theta = _vec2symmetric(x[:d], p) # print(theta[:3, :3]) # print(np.linalg.inv(S)[:3, :3]) # print(np.linalg.norm(theta - np.linalg.inv(S), "fro"))
def test_represent(): assert represent(Jz) == hbar * Matrix([[1, 0], [0, -1]]) / 2 assert represent(Jz, j=1) == hbar * Matrix([[1, 0, 0], [0, 0, 0], [0, 0, -1]])
# Primary State Rates x_dot = v * cos(theta) y_dot = v * sin(theta) theta_dot = u_max * sin(w) writeList = [x_dot, y_dot, theta_dot] # Covariance Calculations p11, p12, \ p22, \ = symbols('p11 p12 \ p22' ) P = Matrix([[p11, p12], [p12, p22]]) F = Matrix([[diff(x_dot, x), diff(x_dot, y)], [diff(y_dot, x), diff(y_dot, y)]]) G = Matrix([[cos(theta)], [sin(theta)]]) h = sqrt((x - xb)**2 + (y - yb)**2) H = Matrix([[diff(h, x), diff(h, y)]]) Q = Dt * diag(sigv**2) R = Dt * diag(sigr**2) P_dot = (F * P + P * F.T - P * H.T * (R**-1) * H * P + G * Q * G.T)
def test_python_matrix(): p = python(Matrix([[x**2 + 1, 1], [y, x + y]])) s = "x = Symbol('x')\ny = Symbol('y')\ne = MutableDenseMatrix([[x**2 + 1, 1], [y, x + y]])" assert p == s
def run_circuit(self, circuit): """Run a circuit and return the results. Args: circuit (dict): JSON that describes the circuit Returns: dict: A dictionary of results which looks something like:: {'data': {'unitary': array([[sqrt(2)/2, sqrt(2)/2, 0, 0], [0, 0, sqrt(2)/2, -sqrt(2)/2], [0, 0, sqrt(2)/2, sqrt(2)/2], [sqrt(2)/2, -sqrt(2)/2, 0, 0]], dtype=object) }, 'status': 'DONE'} Raises: SimulatorError: if unsupported operations passed """ ccircuit = circuit['compiled_circuit'] self._number_of_qubits = ccircuit['header']['number_of_qubits'] result = {} result['data'] = {} self._unitary_state = eye(2**self._number_of_qubits) for operation in ccircuit['operations']: if 'conditional' in operation: raise SimulatorError( 'conditional operations not supported in unitary simulator' ) if operation['name'] == 'measure' or operation['name'] == 'reset': raise SimulatorError('operation {} not supported by ' 'sympy unitary simulator.'.format( operation['name'])) if operation['name'] in ['U', 'u1', 'u2', 'u3']: if 'params' in operation: params = operation['params'] else: params = None qubit = operation['qubits'][0] gate = SympyUnitarySimulator.compute_ugate_matrix_wrap(params) self._add_unitary_single(gate, qubit) elif operation['name'] in ['id']: logger.info( 'Identity gate is ignored by sympy-based unitary simulator.' ) elif operation['name'] in ['barrier']: logger.info( 'Barrier is ignored by sympy-based unitary simulator.') elif operation['name'] in ['CX', 'cx']: qubit0 = operation['qubits'][0] qubit1 = operation['qubits'][1] gate = Matrix([[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]]) self._add_unitary_two(gate, qubit0, qubit1) else: result['status'] = 'ERROR' return result result['data']['unitary'] = np.array(self._unitary_state) result['status'] = 'DONE' result['name'] = circuit['name'] return result
def rot_mat(a, q): T = Matrix([[cos(q), -sin(q), 0], [sin(q) * cos(a), cos(q) * cos(a), -sin(a)], [sin(q) * sin(a), cos(q) * sin(a), cos(a)]]) return T
def test_diagonalization(): x, y, z = symbols('x', 'y', 'z') m = Matrix(3, 2, [-3, 1, -3, 20, 3, 10]) assert not m.is_diagonalizable() assert not m.is_symmetric() raises(NonSquareMatrixException, 'm.diagonalize()') # diagonalizable m = diag(1, 2, 3) (P, D) = m.diagonalize() assert P == eye(3) assert D == m m = Matrix(2, 2, [0, 1, 1, 0]) assert m.is_symmetric() assert m.is_diagonalizable() (P, D) = m.diagonalize() assert P.inv() * m * P == D m = Matrix(2, 2, [1, 0, 0, 3]) assert m.is_symmetric() assert m.is_diagonalizable() (P, D) = m.diagonalize() assert P.inv() * m * P == D assert P == eye(2) assert D == m m = Matrix(2, 2, [1, 1, 0, 0]) assert m.is_diagonalizable() (P, D) = m.diagonalize() assert P.inv() * m * P == D m = Matrix(3, 3, [1, 2, 0, 0, 3, 0, 2, -4, 2]) assert m.is_diagonalizable() (P, D) = m.diagonalize() assert P.inv() * m * P == D m = Matrix(2, 2, [1, 0, 0, 0]) assert m.is_diagonal() assert m.is_diagonalizable() (P, D) = m.diagonalize() assert P.inv() * m * P == D assert P == eye(2) # diagonalizable, complex only m = Matrix(2, 2, [0, 1, -1, 0]) assert not m.is_diagonalizable(True) raises(MatrixError, '(D, P) = m.diagonalize(True)') assert m.is_diagonalizable() (P, D) = m.diagonalize() assert P.inv() * m * P == D m = Matrix(2, 2, [1, 0, 0, I]) raises(NotImplementedError, 'm.is_diagonalizable(True)') # !!! bug because of eigenvects() or roots(x**2 + (-1 - I)*x + I, x) # see issue 2193 # assert not m.is_diagonalizable(True) # raises(MatrixError, '(P, D) = m.diagonalize(True)') # (P, D) = m.diagonalize(True) # not diagonalizable m = Matrix(2, 2, [0, 1, 0, 0]) assert not m.is_diagonalizable() raises(MatrixError, '(D, P) = m.diagonalize()') m = Matrix(3, 3, [-3, 1, -3, 20, 3, 10, 2, -2, 4]) assert not m.is_diagonalizable() raises(MatrixError, '(D, P) = m.diagonalize()') # symbolic a, b, c, d = symbols('a', 'b', 'c', 'd') m = Matrix(2, 2, [a, c, c, b]) assert m.is_symmetric() assert m.is_diagonalizable()
def advection(self): """ returns a sympy matrix containing (v \cdot \nabla)v """ gradv = self.gradient() v = Matrix(self.v) adv = v.T * gradv return adv.T
def test_jordan_form(): m = Matrix(3, 2, [-3, 1, -3, 20, 3, 10]) raises(NonSquareMatrixException, 'm.jordan_form()') # diagonalizable m = Matrix(3, 3, [7, -12, 6, 10, -19, 10, 12, -24, 13]) Jmust = Matrix(3, 3, [1, 0, 0, 0, 1, 0, 0, 0, -1]) (P, J) = m.jordan_form() assert Jmust == J assert Jmust == m.diagonalize()[1] #m = Matrix(3, 3, [0, 6, 3, 1, 3, 1, -2, 2, 1]) #m.jordan_form() # very long # m.jordan_form() # # diagonalizable, complex only # Jordan cells # complexity: one of eigenvalues is zero m = Matrix(3, 3, [0, 1, 0, -4, 4, 0, -2, 1, 2]) Jmust = Matrix(3, 3, [2, 0, 0, 0, 2, 1, 0, 0, 2]) assert Jmust == m.jordan_form()[1] (P, Jcells) = m.jordan_cells() assert Jcells[0] == Matrix(1, 1, [2]) assert Jcells[1] == Matrix(2, 2, [2, 1, 0, 2]) #complexity: all of eigenvalues are equal m = Matrix(3, 3, [2, 6, -15, 1, 1, -5, 1, 2, -6]) Jmust = Matrix(3, 3, [-1, 0, 0, 0, -1, 1, 0, 0, -1]) (P, J) = m.jordan_form() assert Jmust == J #complexity: two of eigenvalues are zero m = Matrix(3, 3, [4, -5, 2, 5, -7, 3, 6, -9, 4]) Jmust = Matrix(3, 3, [1, 0, 0, 0, 0, 1, 0, 0, 0]) (P, J) = m.jordan_form() assert Jmust == J m = Matrix(4, 4, [6, 5, -2, -3, -3, -1, 3, 3, 2, 1, -2, -3, -1, 1, 5, 5]) Jmust = Matrix(4, 4, [2, 1, 0, 0, 0, 2, 0, 0, 0, 0, 2, 1, 0, 0, 0, 2]) (P, J) = m.jordan_form() assert Jmust == J m = Matrix(4, 4, [6, 2, -8, -6, -3, 2, 9, 6, 2, -2, -8, -6, -1, 0, 3, 4]) Jmust = Matrix(4, 4, [2, 0, 0, 0, 0, 2, 1, 0, 0, 0, 2, 0, 0, 0, 0, -2]) (P, J) = m.jordan_form() assert Jmust == J m = Matrix(4, 4, [5, 4, 2, 1, 0, 1, -1, -1, -1, -1, 3, 0, 1, 1, -1, 2]) assert not m.is_diagonalizable() Jmust = Matrix(4, 4, [1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 4, 1, 0, 0, 0, 4]) (P, J) = m.jordan_form() assert Jmust == J
def time_derivative(self): """ returns a sympy Matrix (col vector) of the time derivative of self.v """ time_derivative = list() for component in self.v: time_derivative.append(diff(component, Symbol('t'))) return Matrix(time_derivative)
def test_nullspace(): # first test reduced row-ech form R = Rational M = Matrix([[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 = Matrix([[-5, -1, 4, -3, -1], [1, -1, -1, 1, 0], [-1, 0, 0, 0, 0], [4, 1, -4, 3, 1], [-2, 0, 2, -2, -1]]) assert M * M.nullspace()[0] == Matrix(5, 1, [0] * 5) M = Matrix([[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]) # issue 1698; just see that we can do it when rows > cols M = Matrix([[1, 2], [2, 4], [3, 6]]) assert M.nullspace()
def test_division(): x, y, z = symbols('x', 'y', 'z') v = Matrix(1, 2, [x, y]) assert v.__div__(z) == Matrix(1, 2, [x / z, y / z]) assert v.__truediv__(z) == Matrix(1, 2, [x / z, y / z]) assert v / z == Matrix(1, 2, [x / z, y / z])
def test_sparse_matrix(): return def eye(n): tmp = SMatrix(n, n, lambda i, j: 0) for i in range(tmp.rows): tmp[i, i] = 1 return tmp def zeros(n): return SMatrix(n, n, lambda i, j: 0) # test_multiplication a = SMatrix(( (1, 2), (3, 1), (0, 6), )) b = SMatrix(( (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 x = Symbol("x") c = b * Symbol("x") assert isinstance(c, SMatrix) 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, SMatrix) 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 = SMatrix([[2, 3], [4, 5]]) assert (A**5)[:] == [6140, 8097, 10796, 14237] A = SMatrix([[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 = SMatrix([x, 0], [0, 0]) m = a assert m.cols == m.rows assert m.cols == 2 assert m[:] == [x, 0, 0, 0] b = SMatrix(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 # test_determinant x, y = Symbol('x'), Symbol('y') assert SMatrix([[1]]).det() == 1 assert SMatrix(((-3, 2), (8, -5))).det() == -1 assert SMatrix(((x, 1), (y, 2 * y))).det() == 2 * x * y - y assert SMatrix(((1, 1, 1), (1, 2, 3), (1, 3, 6))).det() == 1 assert SMatrix(((3, -2, 0, 5), (-2, 1, -2, 2), (0, -2, 5, 0), (5, 0, 3, 4))).det() == -289 assert SMatrix(((1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16))).det() == 0 assert SMatrix(((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 SMatrix(((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 SMatrix(((-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 SMatrix(((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_submatrix m0 = eye(4) assert m0[0:3, 0:3] == eye(3) assert m0[2:4, 0:2] == zeros(2) m1 = SMatrix(3, 3, lambda i, j: i + j) assert m1[0, :] == SMatrix(1, 3, (0, 1, 2)) assert m1[1:3, 1] == SMatrix(2, 1, (2, 3)) m2 = SMatrix([0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]) assert m2[:, -1] == SMatrix(4, 1, [3, 7, 11, 15]) assert m2[-2:, :] == SMatrix([[8, 9, 10, 11], [12, 13, 14, 15]]) # test_submatrix_assignment m = zeros(4) m[2:4, 2:4] = eye(2) assert m == SMatrix((0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1)) m[0:2, 0:2] = eye(2) assert m == eye(4) m[:, 0] = SMatrix(4, 1, (1, 2, 3, 4)) assert m == SMatrix((1, 0, 0, 0), (2, 1, 0, 0), (3, 0, 1, 0), (4, 0, 0, 1)) m[:, :] = zeros(4) assert m == zeros(4) m[:, :] = ((1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16)) assert m == SMatrix( ((1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16))) m[0:2, 0] = [0, 0] assert m == SMatrix( ((0, 2, 3, 4), (0, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16))) # test_reshape m0 = eye(3) assert m0.reshape(1, 9) == SMatrix(1, 9, (1, 0, 0, 0, 1, 0, 0, 0, 1)) m1 = SMatrix(3, 4, lambda i, j: i + j) assert m1.reshape(4, 3) == SMatrix((0, 1, 2), (3, 1, 2), (3, 4, 2), (3, 4, 5)) assert m1.reshape(2, 6) == SMatrix((0, 1, 2, 3, 1, 2), (3, 4, 2, 3, 4, 5)) # test_applyfunc m0 = eye(3) assert m0.applyfunc(lambda x: 2 * x) == eye(3) * 2 assert m0.applyfunc(lambda x: 0) == zeros(3) # test_LUdecomp testmat = SMatrix([[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).permuteBkwd(p) - testmat == zeros(4) testmat = SMatrix([[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).permuteBkwd(p) - testmat == 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).permuteBkwd(p) - M == zeros(3) # test_LUsolve A = SMatrix([[2, 3, 5], [3, 6, 2], [8, 3, 6]]) x = SMatrix(3, 1, [3, 7, 5]) b = A * x soln = A.LUsolve(b) assert soln == x A = SMatrix([[0, -1, 2], [5, 10, 7], [8, 3, 4]]) x = SMatrix(3, 1, [-1, 2, 5]) b = A * x soln = A.LUsolve(b) assert soln == x # test_inverse A = eye(4) assert A.inv() == eye(4) assert A.inv("LU") == eye(4) assert A.inv("ADJ") == eye(4) A = SMatrix([[2, 3, 5], [3, 6, 2], [8, 3, 6]]) Ainv = A.inv() assert A * Ainv == eye(3) assert A.inv("LU") == Ainv assert A.inv("ADJ") == 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(v1) == 14 # test_cofactor assert eye(3) == eye(3).cofactorMatrix() test = SMatrix([[1, 3, 2], [2, 6, 3], [2, 3, 6]]) assert test.cofactorMatrix() == SMatrix([[27, -6, -6], [-12, 2, 3], [-3, 1, 0]]) test = SMatrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) assert test.cofactorMatrix() == SMatrix([[-3, 6, -3], [6, -12, 6], [-3, 6, -3]]) # test_jacobian x = Symbol('x') y = Symbol('y') L = SMatrix(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 = SMatrix(1, 2, [x, x**2 * y**3]) assert L.jacobian(syms) == SMatrix([[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 == eye(2) # test nullspace # first test reduced row-ech form R = Rational M = Matrix([[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 = Matrix([[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') eye3 = eye(3) assert eye3.charpoly(x) == (1 - x)**3 assert eye3.charpoly(y) == (1 - y)**3 # test values M = Matrix([(0, 1, -1), (1, 1, 0), (-1, 0, 1)]) vals = M.eigenvals() vals.sort() assert vals == [-1, 1, 2] R = Rational M = Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) assert M.eigenvects() == [[ 1, 3, [ Matrix(1, 3, [1, 0, 0]), Matrix(1, 3, [0, 1, 0]), Matrix(1, 3, [0, 0, 1]) ] ]] M = Matrix([[5, 0, 2], [3, 2, 0], [0, 0, 1]]) assert M.eigenvects() == [[1, 1, [Matrix(1, 3, [R(-1) / 2, R(3) / 2, 1])]], [2, 1, [Matrix(1, 3, [0, 1, 0])]], [5, 1, [Matrix(1, 3, [1, 1, 0])]]] assert M.zeros((3, 5)) == SMatrix(3, 5, {})
def test_vec(): m = Matrix([[1, 3], [2, 4]]) m_vec = m.vec() assert m_vec.cols == 1 for i in xrange(4): assert m_vec[i] == i + 1
def test_shape(): x, y = symbols("xy") M = Matrix([[x, 0, 0], [0, y, 0]]) assert M.shape == (2, 3)
def test_vech_errors(): m = Matrix([[1, 3]]) raises(TypeError, 'm.vech()') m = Matrix([[1, 3], [2, 4]]) raises(ValueError, 'm.vech()')
def test_is_lower(): a = Matrix([[1, 2, 3]]) assert a.is_lower() == False a = Matrix([[1], [2], [3]]) assert a.is_lower() == True
def test_tolist(): x, y, z = symbols('xyz') lst = [[S.One, S.Half, x * y, S.Zero], [x, y, z, x**2], [y, -S.One, z * x, 3]] m = Matrix(lst) assert m.tolist() == lst
def T(a, n): return Matrix( Matrix.eye(n).col_insert(n, Matrix(n, 1, lambda i, j: -a[i]**n)))
def test_determinant(): x, y, z = Symbol('x'), Symbol('y'), Symbol('z') M = Matrix((1, )) assert M.det(method="bareis") == 1 assert M.det(method="berkowitz") == 1 M = Matrix(((-3, 2), (8, -5))) assert M.det(method="bareis") == -1 assert M.det(method="berkowitz") == -1 M = Matrix(((x, 1), (y, 2 * y))) assert M.det(method="bareis") == 2 * x * y - y assert M.det(method="berkowitz") == 2 * x * y - y M = Matrix(((1, 1, 1), (1, 2, 3), (1, 3, 6))) assert M.det(method="bareis") == 1 assert M.det(method="berkowitz") == 1 M = Matrix(((3, -2, 0, 5), (-2, 1, -2, 2), (0, -2, 5, 0), (5, 0, 3, 4))) assert M.det(method="bareis") == -289 assert M.det(method="berkowitz") == -289 M = Matrix(((1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16))) assert M.det(method="bareis") == 0 assert M.det(method="berkowitz") == 0 M = Matrix(((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))) assert M.det(method="bareis") == 275 assert M.det(method="berkowitz") == 275 M = Matrix(((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))) assert M.det(method="bareis") == -55 assert M.det(method="berkowitz") == -55 M = Matrix(((-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))) assert M.det(method="bareis") == 11664 assert M.det(method="berkowitz") == 11664 M = Matrix(((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))) assert M.det(method="bareis") == 123 assert M.det(method="berkowitz") == 123 M = Matrix(((x, y, z), (1, 0, 0), (y, z, x))) assert M.det(method="bareis") == z**2 - x * y assert M.det(method="berkowitz") == z**2 - x * y
def F(a, n): return Matrix( n, 1, lambda i, j: reduce(mul, ( (a[i] - a[k] if k != i else 1) for k in range(0, n)), 1))
for p in product([0, 1], repeat=N**2): v = Matrix(p).reshape(N, N) if hasMatching(v): print("\r", v, end="", flush=True) MP = v.multiply_elementwise(P) MQ = v.multiply_elementwise(Q) pr = getVal(MP, MQ) assert (pr != 0) m = MP.multiply_elementwise(MP.inv().T) result += pr * (-1)**(N + int(sum(p))) * m print("\r", end="") return result if __name__ == "__main__": N = 4 random.seed(42) P = Matrix([[random.randint(1, 1000) for j in range(N)] for i in range(N)]) Q = Matrix([[random.randint(1, 1000) for j in range(N)] for i in range(N)]) from run import solve, proba_match res1 = Matrix(proba_match(N, N, solve(P, Q))) print(res1) res2 = compute(N, P, Q) print(res2) print(np.array(res1, dtype=float)) print(np.array(res2, dtype=float)) print(res1 == res2)