def smith_normal_form(m, domain=None): ''' Return the Smith Normal Form of a matrix `m` over the ring `domain`. This will only work if the ring is a principal ideal domain. Examples ======== >>> from sympy.polys.solvers import RawMatrix as Matrix >>> from sympy.polys.domains import ZZ >>> from sympy.matrices.normalforms import smith_normal_form >>> m = Matrix([[12, 6, 4], [3, 9, 6], [2, 16, 14]]) >>> setattr(m, "ring", ZZ) >>> print(smith_normal_form(m)) Matrix([[1, 0, 0], [0, 10, 0], [0, 0, -30]]) ''' invs = invariant_factors(m, domain=domain) smf = diag(*invs) n = len(invs) if m.rows > n: smf = smf.row_insert(m.rows, zeros(m.rows - n, m.cols)) elif m.cols > n: smf = smf.col_insert(m.cols, zeros(m.rows, m.cols - n)) return smf
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 test_function_return_types(): # Lets ensure that decompositions of immutable matrices remain immutable # I.e. do MatrixBase methods return the correct class? X = ImmutableMatrix([[1, 2], [3, 4]]) Y = ImmutableMatrix([[1], [0]]) q, r = X.QRdecomposition() assert (type(q), type(r)) == (ImmutableMatrix, ImmutableMatrix) assert type(X.LUsolve(Y)) == ImmutableMatrix assert type(X.QRsolve(Y)) == ImmutableMatrix X = ImmutableMatrix([[5, 2], [2, 7]]) assert X.T == X assert X.is_symmetric assert type(X.cholesky()) == ImmutableMatrix L, D = X.LDLdecomposition() assert (type(L), type(D)) == (ImmutableMatrix, ImmutableMatrix) X = ImmutableMatrix([[1, 2], [2, 1]]) assert X.is_diagonalizable() assert X.det() == -3 assert X.norm(2) == 3 assert type(X.eigenvects()[0][2][0]) == ImmutableMatrix assert type(zeros(3, 3).as_immutable().nullspace()[0]) == ImmutableMatrix X = ImmutableMatrix([[1, 0], [2, 1]]) assert type(X.lower_triangular_solve(Y)) == ImmutableMatrix assert type(X.T.upper_triangular_solve(Y)) == ImmutableMatrix assert type(X.minor_submatrix(0, 0)) == ImmutableMatrix
def test_dcm(): q1, q2, q3, q4 = dynamicsymbols('q1 q2 q3 q4') N = ReferenceFrame('N') A = N.orientnew('A', 'Axis', [q1, N.z]) B = A.orientnew('B', 'Axis', [q2, A.x]) C = B.orientnew('C', 'Axis', [q3, B.y]) D = N.orientnew('D', 'Axis', [q4, N.y]) E = N.orientnew('E', 'Space', [q1, q2, q3], '123') assert N.dcm(C) == Matrix( [[ -sin(q1) * sin(q2) * sin(q3) + cos(q1) * cos(q3), -sin(q1) * cos(q2), sin(q1) * sin(q2) * cos(q3) + sin(q3) * cos(q1) ], [ sin(q1) * cos(q3) + sin(q2) * sin(q3) * cos(q1), cos(q1) * cos(q2), sin(q1) * sin(q3) - sin(q2) * cos(q1) * cos(q3) ], [-sin(q3) * cos(q2), sin(q2), cos(q2) * cos(q3)]]) # This is a little touchy. Is it ok to use simplify in assert? test_mat = D.dcm(C) - Matrix( [[ cos(q1) * cos(q3) * cos(q4) - sin(q3) * (-sin(q4) * cos(q2) + sin(q1) * sin(q2) * cos(q4)), -sin(q2) * sin(q4) - sin(q1) * cos(q2) * cos(q4), sin(q3) * cos(q1) * cos(q4) + cos(q3) * (-sin(q4) * cos(q2) + sin(q1) * sin(q2) * cos(q4)) ], [ sin(q1) * cos(q3) + sin(q2) * sin(q3) * cos(q1), cos(q1) * cos(q2), sin(q1) * sin(q3) - sin(q2) * cos(q1) * cos(q3) ], [ sin(q4) * cos(q1) * cos(q3) - sin(q3) * (cos(q2) * cos(q4) + sin(q1) * sin(q2) * sin(q4)), sin(q2) * cos(q4) - sin(q1) * sin(q4) * cos(q2), sin(q3) * sin(q4) * cos(q1) + cos(q3) * (cos(q2) * cos(q4) + sin(q1) * sin(q2) * sin(q4)) ]]) assert test_mat.expand() == zeros(3, 3) assert E.dcm(N) == Matrix( [[cos(q2) * cos(q3), sin(q3) * cos(q2), -sin(q2)], [ sin(q1) * sin(q2) * cos(q3) - sin(q3) * cos(q1), sin(q1) * sin(q2) * sin(q3) + cos(q1) * cos(q3), sin(q1) * cos(q2) ], [ sin(q1) * sin(q3) + sin(q2) * cos(q1) * cos(q3), -sin(q1) * cos(q3) + sin(q2) * sin(q3) * cos(q1), cos(q1) * cos(q2) ]])
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 row_proper(A): """ Reduction of a polynomial matrix to row proper polynomial matrix Implementation of the algorithm as shown in page 7 of Vardulakis, A.I.G. (Antonis I.G). Linear Multivariable Control: Algebraic Analysis and Synthesis Methods. Chichester,New York,Brisbane,Toronto,Singapore: John Wiley & Sons, 1991. INPUT: Polynomial Matrix A OUTPUT: T:An equivalent matrix in row proper form TL the unimodular transformation matrix Christos Tsolakis Example: TODO T=Matrix([[1, s**2, 0], [0, s, 1]]) is_row_proper(T) see also Wolovich Linear Multivariable Systems Springer """ T=A.copy() Transfomation_Matrix=eye(T.rows) #initialize transformation matrix while not is_row_proper(T): #for i in range(3): Thr=mc.highest_row_degree_matrix(T,s) #pprint(Thr) x=symbols('x0:%d'%(Thr.rows+1)) Thr=Thr.transpose() Thr0=Thr.col_insert(Thr.cols,zeros(Thr.rows,1)) SOL=solve_linear_system(Thr0,*x) # solve the system a=Matrix(x) D={var:1 for var in x if var not in SOL.keys()} # put free variables equal to 1 D.update({var:SOL[var].subs(D) for var in x if var in SOL.keys()}) a=a.subs(D) r0=mc.find_degree(T,s) row_degrees=mc.row_degrees(T,s) i0=row_degrees.index(max(row_degrees)) ast=Matrix(1,T.rows,[a[i]*s**(r0-row_degrees[i]) for i in range(T.rows)]) #pprint (ast) TL=eye(T.rows) TL[i0*TL.cols]=ast #pprint (TL) T=TL*T T.simplify() Transfomation_Matrix=TL*Transfomation_Matrix Transfomation_Matrix.simplify() #pprint (T) #print('----------------------------') return Transfomation_Matrix,T
def test_Dirac(): gamma0 = mgamma(0) gamma1 = mgamma(1) gamma2 = mgamma(2) gamma3 = mgamma(3) gamma5 = mgamma(5) # gamma*I -> I*gamma (see #354) assert gamma5 == gamma0 * gamma1 * gamma2 * gamma3 * I assert gamma1 * gamma2 + gamma2 * gamma1 == zeros(4) assert gamma0 * gamma0 == eye(4) * minkowski_tensor[0, 0] assert gamma2 * gamma2 != eye(4) * minkowski_tensor[0, 0] assert gamma2 * gamma2 == eye(4) * minkowski_tensor[2, 2] assert mgamma(5, True) == \ mgamma(0, True)*mgamma(1, True)*mgamma(2, True)*mgamma(3, True)*I
def test_MatAdd_postprocessor(): # Some of these are nonsensical, but we do not raise errors for Add # because that breaks algorithms that want to replace matrices with dummy # symbols. z = zeros(2) assert Add(0, z) == Add(z, 0) == z a = Add(S.Infinity, z) assert a == Add(z, S.Infinity) assert isinstance(a, Add) assert a.args == (S.Infinity, z) a = Add(S.ComplexInfinity, z) assert a == Add(z, S.ComplexInfinity) assert isinstance(a, Add) assert a.args == (S.ComplexInfinity, z) a = Add(z, S.NaN) # assert a == Add(S.NaN, z) # See the XFAIL above assert isinstance(a, Add) assert a.args == (S.NaN, z) M = Matrix([[1, 2], [3, 4]]) a = Add(x, M) assert a == Add(M, x) assert isinstance(a, Add) assert a.args == (x, M) A = MatrixSymbol("A", 2, 2) assert Add(A, M) == Add(M, A) == A + M # Scalars should be absorbed into constant matrices (producing an error) a = Add(x, M, A) assert a == Add(M, x, A) == Add(M, A, x) == Add(x, A, M) == Add( A, x, M) == Add(A, M, x) assert isinstance(a, Add) assert a.args == (x, A + M) assert Add(M, M) == 2 * M assert Add(M, A, M) == Add(M, M, A) == Add(A, M, M) == A + 2 * M a = Add(A, x, M, M, x) assert isinstance(a, Add) assert a.args == (2 * x, A + 2 * M)
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 test_banded(): raises(TypeError, lambda: banded()) raises(TypeError, lambda: banded(1)) raises(TypeError, lambda: banded(1, 2)) raises(TypeError, lambda: banded(1, 2, 3)) raises(TypeError, lambda: banded(1, 2, 3, 4)) raises(ValueError, lambda: banded({0: (1, 2)}, rows=1)) raises(ValueError, lambda: banded({0: (1, 2)}, cols=1)) raises(ValueError, lambda: banded(1, {0: (1, 2)})) raises(ValueError, lambda: banded(2, 1, {0: (1, 2)})) raises(ValueError, lambda: banded(1, 2, {0: (1, 2)})) assert isinstance(banded(2, 4, {}), SparseMatrix) assert banded(2, 4, {}) == zeros(2, 4) assert banded({0: 0, 1: 0}) == zeros(0) assert banded({0: Matrix([1, 2])}) == Matrix([1, 2]) assert banded({1: [1, 2, 3, 0], -1: [4, 5, 6]}) == \ banded({1: (1, 2, 3), -1: (4, 5, 6)}) == \ Matrix([ [0, 1, 0, 0], [4, 0, 2, 0], [0, 5, 0, 3], [0, 0, 6, 0]]) assert banded(3, 4, {-1: 1, 0: 2, 1: 3}) == \ Matrix([ [2, 3, 0, 0], [1, 2, 3, 0], [0, 1, 2, 3]]) s = lambda d: (1 + d)**2 assert banded(5, {0: s, 2: s}) == \ Matrix([ [1, 0, 1, 0, 0], [0, 4, 0, 4, 0], [0, 0, 9, 0, 9], [0, 0, 0, 16, 0], [0, 0, 0, 0, 25]]) assert banded(2, {0: 1}) == \ Matrix([ [1, 0], [0, 1]]) assert banded(2, 3, {0: 1}) == \ Matrix([ [1, 0, 0], [0, 1, 0]]) vert = Matrix([1, 2, 3]) assert banded({0: vert}, cols=3) == \ Matrix([ [1, 0, 0], [2, 1, 0], [3, 2, 1], [0, 3, 2], [0, 0, 3]]) assert banded(4, {0: ones(2)}) == \ Matrix([ [1, 1, 0, 0], [1, 1, 0, 0], [0, 0, 1, 1], [0, 0, 1, 1]]) raises(ValueError, lambda: banded({0: 2, 1: ones(2)}, rows=5)) assert banded({0: 2, 2: (ones(2),)*3}) == \ Matrix([ [2, 0, 1, 1, 0, 0, 0, 0], [0, 2, 1, 1, 0, 0, 0, 0], [0, 0, 2, 0, 1, 1, 0, 0], [0, 0, 0, 2, 1, 1, 0, 0], [0, 0, 0, 0, 2, 0, 1, 1], [0, 0, 0, 0, 0, 2, 1, 1]]) raises(ValueError, lambda: banded({0: (2, ) * 5, 1: (ones(2), ) * 3})) u2 = Matrix([[1, 1], [0, 1]]) assert banded({0: (2,)*5, 1: (u2,)*3}) == \ Matrix([ [2, 1, 1, 0, 0, 0, 0], [0, 2, 1, 0, 0, 0, 0], [0, 0, 2, 1, 1, 0, 0], [0, 0, 0, 2, 1, 0, 0], [0, 0, 0, 0, 2, 1, 1], [0, 0, 0, 0, 0, 0, 1]]) assert banded({0:(0, ones(2)), 2: 2}) == \ Matrix([ [0, 0, 2], [0, 1, 1], [0, 1, 1]]) raises(ValueError, lambda: banded({0: (0, ones(2)), 1: 2})) assert banded({0: 1}, cols=3) == banded({0: 1}, rows=3) == eye(3) assert banded({1: 1}, rows=3) == Matrix([[0, 1, 0], [0, 0, 1], [0, 0, 0]])
def wigner_d_small(J, beta): """Return the small Wigner d matrix for angular momentum J. Explanation =========== J : An integer, half-integer, or SymPy symbol for the total angular momentum of the angular momentum space being rotated. beta : A real number representing the Euler angle of rotation about the so-called line of nodes. See [Edmonds74]_. Returns ======= A matrix representing the corresponding Euler angle rotation( in the basis of eigenvectors of `J_z`). .. math :: \\mathcal{d}_{\\beta} = \\exp\\big( \\frac{i\\beta}{\\hbar} J_y\\big) The components are calculated using the general form [Edmonds74]_, equation 4.1.15. Examples ======== >>> from sympy import Integer, symbols, pi, pprint >>> from sympy.physics.wigner import wigner_d_small >>> half = 1/Integer(2) >>> beta = symbols("beta", real=True) >>> pprint(wigner_d_small(half, beta), use_unicode=True) ⎡ ⎛β⎞ ⎛β⎞⎤ ⎢cos⎜─⎟ sin⎜─⎟⎥ ⎢ ⎝2⎠ ⎝2⎠⎥ ⎢ ⎥ ⎢ ⎛β⎞ ⎛β⎞⎥ ⎢-sin⎜─⎟ cos⎜─⎟⎥ ⎣ ⎝2⎠ ⎝2⎠⎦ >>> pprint(wigner_d_small(2*half, beta), use_unicode=True) ⎡ 2⎛β⎞ ⎛β⎞ ⎛β⎞ 2⎛β⎞ ⎤ ⎢ cos ⎜─⎟ √2⋅sin⎜─⎟⋅cos⎜─⎟ sin ⎜─⎟ ⎥ ⎢ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎥ ⎢ ⎥ ⎢ ⎛β⎞ ⎛β⎞ 2⎛β⎞ 2⎛β⎞ ⎛β⎞ ⎛β⎞⎥ ⎢-√2⋅sin⎜─⎟⋅cos⎜─⎟ - sin ⎜─⎟ + cos ⎜─⎟ √2⋅sin⎜─⎟⋅cos⎜─⎟⎥ ⎢ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎝2⎠⎥ ⎢ ⎥ ⎢ 2⎛β⎞ ⎛β⎞ ⎛β⎞ 2⎛β⎞ ⎥ ⎢ sin ⎜─⎟ -√2⋅sin⎜─⎟⋅cos⎜─⎟ cos ⎜─⎟ ⎥ ⎣ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎦ From table 4 in [Edmonds74]_ >>> pprint(wigner_d_small(half, beta).subs({beta:pi/2}), use_unicode=True) ⎡ √2 √2⎤ ⎢ ── ──⎥ ⎢ 2 2 ⎥ ⎢ ⎥ ⎢-√2 √2⎥ ⎢──── ──⎥ ⎣ 2 2 ⎦ >>> pprint(wigner_d_small(2*half, beta).subs({beta:pi/2}), ... use_unicode=True) ⎡ √2 ⎤ ⎢1/2 ── 1/2⎥ ⎢ 2 ⎥ ⎢ ⎥ ⎢-√2 √2 ⎥ ⎢──── 0 ── ⎥ ⎢ 2 2 ⎥ ⎢ ⎥ ⎢ -√2 ⎥ ⎢1/2 ──── 1/2⎥ ⎣ 2 ⎦ >>> pprint(wigner_d_small(3*half, beta).subs({beta:pi/2}), ... use_unicode=True) ⎡ √2 √6 √6 √2⎤ ⎢ ── ── ── ──⎥ ⎢ 4 4 4 4 ⎥ ⎢ ⎥ ⎢-√6 -√2 √2 √6⎥ ⎢──── ──── ── ──⎥ ⎢ 4 4 4 4 ⎥ ⎢ ⎥ ⎢ √6 -√2 -√2 √6⎥ ⎢ ── ──── ──── ──⎥ ⎢ 4 4 4 4 ⎥ ⎢ ⎥ ⎢-√2 √6 -√6 √2⎥ ⎢──── ── ──── ──⎥ ⎣ 4 4 4 4 ⎦ >>> pprint(wigner_d_small(4*half, beta).subs({beta:pi/2}), ... use_unicode=True) ⎡ √6 ⎤ ⎢1/4 1/2 ── 1/2 1/4⎥ ⎢ 4 ⎥ ⎢ ⎥ ⎢-1/2 -1/2 0 1/2 1/2⎥ ⎢ ⎥ ⎢ √6 √6 ⎥ ⎢ ── 0 -1/2 0 ── ⎥ ⎢ 4 4 ⎥ ⎢ ⎥ ⎢-1/2 1/2 0 -1/2 1/2⎥ ⎢ ⎥ ⎢ √6 ⎥ ⎢1/4 -1/2 ── -1/2 1/4⎥ ⎣ 4 ⎦ """ M = [J - i for i in range(2 * J + 1)] d = zeros(2 * J + 1) for i, Mi in enumerate(M): for j, Mj in enumerate(M): # We get the maximum and minimum value of sigma. sigmamax = max([-Mi - Mj, J - Mj]) sigmamin = min([0, J - Mi]) dij = sqrt( factorial(J + Mi) * factorial(J - Mi) / factorial(J + Mj) / factorial(J - Mj)) terms = [(-1)**(J - Mi - s) * binomial(J + Mj, J - Mi - s) * binomial(J - Mj, s) * cos(beta / 2)**(2 * s + Mi + Mj) * sin(beta / 2)**(2 * J - 2 * s - Mj - Mi) for s in range(sigmamin, sigmamax + 1)] d[i, j] = dij * Add(*terms) return ImmutableMatrix(d)
def timeit_Matrix_zeronm(): zeros(100, 100)
def test_matrix_exp(): from sympy.matrices.dense import Matrix, eye, zeros from sympy.solvers.ode.systems import matrix_exp t = Symbol('t') for n in range(1, 6 + 1): assert matrix_exp(zeros(n), t) == eye(n) for n in range(1, 6 + 1): A = eye(n) expAt = exp(t) * eye(n) assert matrix_exp(A, t) == expAt for n in range(1, 6 + 1): A = Matrix(n, n, lambda i, j: i + 1 if i == j else 0) expAt = Matrix(n, n, lambda i, j: exp((i + 1) * t) if i == j else 0) assert matrix_exp(A, t) == expAt A = Matrix([[0, 1], [-1, 0]]) expAt = Matrix([[cos(t), sin(t)], [-sin(t), cos(t)]]) assert matrix_exp(A, t) == expAt A = Matrix([[2, -5], [2, -4]]) expAt = Matrix( [[3 * exp(-t) * sin(t) + exp(-t) * cos(t), -5 * exp(-t) * sin(t)], [2 * exp(-t) * sin(t), -3 * exp(-t) * sin(t) + exp(-t) * cos(t)]]) assert matrix_exp(A, t) == expAt A = Matrix([[21, 17, 6], [-5, -1, -6], [4, 4, 16]]) # TO update this. # expAt = Matrix([ # [(8*t*exp(12*t) + 5*exp(12*t) - 1)*exp(4*t)/4, # (8*t*exp(12*t) + 5*exp(12*t) - 5)*exp(4*t)/4, # (exp(12*t) - 1)*exp(4*t)/2], # [(-8*t*exp(12*t) - exp(12*t) + 1)*exp(4*t)/4, # (-8*t*exp(12*t) - exp(12*t) + 5)*exp(4*t)/4, # (-exp(12*t) + 1)*exp(4*t)/2], # [4*t*exp(16*t), 4*t*exp(16*t), exp(16*t)]]) expAt = Matrix( [[ 2 * t * exp(16 * t) + 5 * exp(16 * t) / 4 - exp(4 * t) / 4, 2 * t * exp(16 * t) + 5 * exp(16 * t) / 4 - 5 * exp(4 * t) / 4, exp(16 * t) / 2 - exp(4 * t) / 2 ], [ -2 * t * exp(16 * t) - exp(16 * t) / 4 + exp(4 * t) / 4, -2 * t * exp(16 * t) - exp(16 * t) / 4 + 5 * exp(4 * t) / 4, -exp(16 * t) / 2 + exp(4 * t) / 2 ], [4 * t * exp(16 * t), 4 * t * exp(16 * t), exp(16 * t)]]) assert matrix_exp(A, t) == expAt A = Matrix([[1, 1, 0, 0], [0, 1, 1, 0], [0, 0, 1, -S(1) / 8], [0, 0, S(1) / 2, S(1) / 2]]) expAt = Matrix( [[ exp(t), t * exp(t), 4 * t * exp(3 * t / 4) + 8 * t * exp(t) + 48 * exp(3 * t / 4) - 48 * exp(t), -2 * t * exp(3 * t / 4) - 2 * t * exp(t) - 16 * exp(3 * t / 4) + 16 * exp(t) ], [ 0, exp(t), -t * exp(3 * t / 4) - 8 * exp(3 * t / 4) + 8 * exp(t), t * exp(3 * t / 4) / 2 + 2 * exp(3 * t / 4) - 2 * exp(t) ], [ 0, 0, t * exp(3 * t / 4) / 4 + exp(3 * t / 4), -t * exp(3 * t / 4) / 8 ], [ 0, 0, t * exp(3 * t / 4) / 2, -t * exp(3 * t / 4) / 4 + exp(3 * t / 4) ]]) assert matrix_exp(A, t) == expAt A = Matrix([[0, 1, 0, 0], [-1, 0, 0, 0], [0, 0, 0, 1], [0, 0, -1, 0]]) expAt = Matrix([[cos(t), sin(t), 0, 0], [-sin(t), cos(t), 0, 0], [0, 0, cos(t), sin(t)], [0, 0, -sin(t), cos(t)]]) assert matrix_exp(A, t) == expAt A = Matrix([[0, 1, 1, 0], [-1, 0, 0, 1], [0, 0, 0, 1], [0, 0, -1, 0]]) expAt = Matrix([[cos(t), sin(t), t * cos(t), t * sin(t)], [-sin(t), cos(t), -t * sin(t), t * cos(t)], [0, 0, cos(t), sin(t)], [0, 0, -sin(t), cos(t)]]) assert matrix_exp(A, t) == expAt # This case is unacceptably slow right now but should be solvable... #a, b, c, d, e, f = symbols('a b c d e f') #A = Matrix([ #[-a, b, c, d], #[ a, -b, e, 0], #[ 0, 0, -c - e - f, 0], #[ 0, 0, f, -d]]) A = Matrix([[0, I], [I, 0]]) expAt = Matrix( [[exp(I * t) / 2 + exp(-I * t) / 2, exp(I * t) / 2 - exp(-I * t) / 2], [exp(I * t) / 2 - exp(-I * t) / 2, exp(I * t) / 2 + exp(-I * t) / 2]]) assert matrix_exp(A, t) == expAt
from sympy.core.symbol import Symbol from sympy.matrices.dense import (eye, zeros) from sympy.solvers.solvers import solve_linear_system N = 8 M = zeros(N, N + 1) M[:, :N] = eye(N) S = [Symbol('A%i' % i) for i in range(N)] def timeit_linsolve_trivial(): solve_linear_system(M, *S)
def test_matrix_tensor_product(): if not np: skip("numpy not installed.") l1 = zeros(4) for i in range(16): l1[i] = 2**i l2 = zeros(4) for i in range(16): l2[i] = i l3 = zeros(2) for i in range(4): l3[i] = i vec = Matrix([1, 2, 3]) #test for Matrix known 4x4 matricies numpyl1 = np.array(l1.tolist()) numpyl2 = np.array(l2.tolist()) numpy_product = np.kron(numpyl1, numpyl2) args = [l1, l2] sympy_product = matrix_tensor_product(*args) assert numpy_product.tolist() == sympy_product.tolist() numpy_product = np.kron(numpyl2, numpyl1) args = [l2, l1] sympy_product = matrix_tensor_product(*args) assert numpy_product.tolist() == sympy_product.tolist() #test for other known matrix of different dimensions numpyl2 = np.array(l3.tolist()) numpy_product = np.kron(numpyl1, numpyl2) args = [l1, l3] sympy_product = matrix_tensor_product(*args) assert numpy_product.tolist() == sympy_product.tolist() numpy_product = np.kron(numpyl2, numpyl1) args = [l3, l1] sympy_product = matrix_tensor_product(*args) assert numpy_product.tolist() == sympy_product.tolist() #test for non square matrix numpyl2 = np.array(vec.tolist()) numpy_product = np.kron(numpyl1, numpyl2) args = [l1, vec] sympy_product = matrix_tensor_product(*args) assert numpy_product.tolist() == sympy_product.tolist() numpy_product = np.kron(numpyl2, numpyl1) args = [vec, l1] sympy_product = matrix_tensor_product(*args) assert numpy_product.tolist() == sympy_product.tolist() #test for random matrix with random values that are floats random_matrix1 = np.random.rand(randint(1, 5), randint(1, 5)) random_matrix2 = np.random.rand(randint(1, 5), randint(1, 5)) numpy_product = np.kron(random_matrix1, random_matrix2) args = [Matrix(random_matrix1.tolist()), Matrix(random_matrix2.tolist())] sympy_product = matrix_tensor_product(*args) assert not (sympy_product - Matrix(numpy_product.tolist())).tolist() > \ (ones(sympy_product.rows, sympy_product.cols)*epsilon).tolist() #test for three matrix kronecker sympy_product = matrix_tensor_product(l1, vec, l2) numpy_product = np.kron(l1, np.kron(vec, l2)) assert numpy_product.tolist() == sympy_product.tolist()
def test_rotation_matrix(): N = CoordSys3D('N') A = N.orient_new_axis('A', q1, N.k) B = A.orient_new_axis('B', q2, A.i) C = B.orient_new_axis('C', q3, B.j) D = N.orient_new_axis('D', q4, N.j) E = N.orient_new_space('E', q1, q2, q3, '123') F = N.orient_new_quaternion('F', q1, q2, q3, q4) G = N.orient_new_body('G', q1, q2, q3, '123') assert N.rotation_matrix(C) == Matrix([ [- sin(q1) * sin(q2) * sin(q3) + cos(q1) * cos(q3), - sin(q1) * cos(q2), sin(q1) * sin(q2) * cos(q3) + sin(q3) * cos(q1)], \ [sin(q1) * cos(q3) + sin(q2) * sin(q3) * cos(q1), \ cos(q1) * cos(q2), sin(q1) * sin(q3) - sin(q2) * cos(q1) * \ cos(q3)], [- sin(q3) * cos(q2), sin(q2), cos(q2) * cos(q3)]]) test_mat = D.rotation_matrix(C) - Matrix( [[cos(q1) * cos(q3) * cos(q4) - sin(q3) * (- sin(q4) * cos(q2) + sin(q1) * sin(q2) * cos(q4)), - sin(q2) * sin(q4) - sin(q1) * cos(q2) * cos(q4), sin(q3) * cos(q1) * cos(q4) + cos(q3) * \ (- sin(q4) * cos(q2) + sin(q1) * sin(q2) * cos(q4))], \ [sin(q1) * cos(q3) + sin(q2) * sin(q3) * cos(q1), cos(q1) * \ cos(q2), sin(q1) * sin(q3) - sin(q2) * cos(q1) * cos(q3)], \ [sin(q4) * cos(q1) * cos(q3) - sin(q3) * (cos(q2) * cos(q4) + \ sin(q1) * sin(q2) * \ sin(q4)), sin(q2) * cos(q4) - sin(q1) * sin(q4) * cos(q2), sin(q3) * \ sin(q4) * cos(q1) + cos(q3) * (cos(q2) * cos(q4) + \ sin(q1) * sin(q2) * sin(q4))]]) assert test_mat.expand() == zeros(3, 3) assert E.rotation_matrix(N) == Matrix( [[cos(q2)*cos(q3), sin(q3)*cos(q2), -sin(q2)], [sin(q1)*sin(q2)*cos(q3) - sin(q3)*cos(q1), \ sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3), sin(q1)*cos(q2)], \ [sin(q1)*sin(q3) + sin(q2)*cos(q1)*cos(q3), - \ sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1), cos(q1)*cos(q2)]]) assert F.rotation_matrix(N) == Matrix([[ q1**2 + q2**2 - q3**2 - q4**2, 2 * q1 * q4 + 2 * q2 * q3, -2 * q1 * q3 + 2 * q2 * q4 ], [ -2 * q1 * q4 + 2 * q2 * q3, q1**2 - q2**2 + q3**2 - q4**2, 2 * q1 * q2 + 2 * q3 * q4 ], [ 2 * q1 * q3 + 2 * q2 * q4, -2 * q1 * q2 + 2 * q3 * q4, q1**2 - q2**2 - q3**2 + q4**2 ]]) assert G.rotation_matrix(N) == Matrix( [[ cos(q2) * cos(q3), sin(q1) * sin(q2) * cos(q3) + sin(q3) * cos(q1), sin(q1) * sin(q3) - sin(q2) * cos(q1) * cos(q3) ], [ -sin(q3) * cos(q2), -sin(q1) * sin(q2) * sin(q3) + cos(q1) * cos(q3), sin(q1) * cos(q3) + sin(q2) * sin(q3) * cos(q1) ], [sin(q2), -sin(q1) * cos(q2), cos(q1) * cos(q2)]])
def test_MatAdd_postprocessor_xfail(): # This is difficult to get working because of the way that Add processes # its args. z = zeros(2) assert Add(z, S.NaN) == Add(S.NaN, z)
num_tests = 400 min_M_cols = 1 min_M_rows = 1 max_M_cols = 15 max_M_rows = 15 min_val = 1 max_val = 100 fs = open(filename, "w") fs.write("{}\n".format(num_tests)) for i in range(num_tests): print("Creating test case: ", i) M_dim = randrange(min_M_cols, max_M_cols) M = zeros(M_dim) for i in range(M_dim): for j in range(i+1): M[i, j] = randrange(min_val, max_val) B = randMatrix(M_dim, 1, min=min_val, max=max_val, percent=100) x = M.lower_triangular_solve(B).applyfunc(N) fs.write("{} {}\n".format(M_dim, M_dim)) fs.write(M.table(StrPrinter(), rowstart="", rowend="", colsep="\t")) fs.write("\n") fs.write("{} {}\n".format(M_dim, 1)) fs.write(B.table(StrPrinter(), rowstart="", rowend="", colsep="\t")) fs.write("\n") fs.write("{} {}\n".format(M_dim, 1)) fs.write(x.table(StrPrinter(), rowstart="", rowend="", colsep="\t")) fs.write("\n")