hash
stringlengths 64
64
| content
stringlengths 0
1.51M
|
---|---|
2819983c8178f52ab7e256f36c5099458592c887619d1dc02b7abe55b53a82b5 | from sympy.core.numbers import Float
from sympy.physics.quantum.constants import hbar
def test_hbar():
assert hbar.is_commutative is True
assert hbar.is_real is True
assert hbar.is_positive is True
assert hbar.is_negative is False
assert hbar.is_irrational is True
assert hbar.evalf() == Float(1.05457162e-34)
|
45ad3127f32f6746ec8209da25dc7aceed423967979d1aece6868ffb51b274aa | from random import randint
from sympy.core.numbers import Integer
from sympy.matrices.dense import (Matrix, ones, zeros)
from sympy.physics.quantum.matrixutils import (
to_sympy, to_numpy, to_scipy_sparse, matrix_tensor_product,
matrix_to_zero, matrix_zeros, numpy_ndarray, scipy_sparse_matrix
)
from sympy.external import import_module
from sympy.testing.pytest import skip
m = Matrix([[1, 2], [3, 4]])
def test_sympy_to_sympy():
assert to_sympy(m) == m
def test_matrix_to_zero():
assert matrix_to_zero(m) == m
assert matrix_to_zero(Matrix([[0, 0], [0, 0]])) == Integer(0)
np = import_module('numpy')
def test_to_numpy():
if not np:
skip("numpy not installed.")
result = np.matrix([[1, 2], [3, 4]], dtype='complex')
assert (to_numpy(m) == result).all()
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.matrix(l1.tolist())
numpyl2 = np.matrix(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.matrix(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.matrix(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()
scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']})
def test_to_scipy_sparse():
if not np:
skip("numpy not installed.")
if not scipy:
skip("scipy not installed.")
else:
sparse = scipy.sparse
result = sparse.csr_matrix([[1, 2], [3, 4]], dtype='complex')
assert np.linalg.norm((to_scipy_sparse(m) - result).todense()) == 0.0
epsilon = .000001
def test_matrix_zeros_sympy():
sym = matrix_zeros(4, 4, format='sympy')
assert isinstance(sym, Matrix)
def test_matrix_zeros_numpy():
if not np:
skip("numpy not installed.")
num = matrix_zeros(4, 4, format='numpy')
assert isinstance(num, numpy_ndarray)
def test_matrix_zeros_scipy():
if not np:
skip("numpy not installed.")
if not scipy:
skip("scipy not installed.")
sci = matrix_zeros(4, 4, format='scipy.sparse')
assert isinstance(sci, scipy_sparse_matrix)
|
dfbb53f29e8c8478c061ea1acb5672bfb802b3e0de6508b855dc141f621f7c31 | from sympy.core.numbers import (I, Integer)
from sympy.physics.quantum.innerproduct import InnerProduct
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum.state import Bra, Ket, StateBase
def test_innerproduct():
k = Ket('k')
b = Bra('b')
ip = InnerProduct(b, k)
assert isinstance(ip, InnerProduct)
assert ip.bra == b
assert ip.ket == k
assert b*k == InnerProduct(b, k)
assert k*(b*k)*b == k*InnerProduct(b, k)*b
assert InnerProduct(b, k).subs(b, Dagger(k)) == Dagger(k)*k
def test_innerproduct_dagger():
k = Ket('k')
b = Bra('b')
ip = b*k
assert Dagger(ip) == Dagger(k)*Dagger(b)
class FooState(StateBase):
pass
class FooKet(Ket, FooState):
@classmethod
def dual_class(self):
return FooBra
def _eval_innerproduct_FooBra(self, bra):
return Integer(1)
def _eval_innerproduct_BarBra(self, bra):
return I
class FooBra(Bra, FooState):
@classmethod
def dual_class(self):
return FooKet
class BarState(StateBase):
pass
class BarKet(Ket, BarState):
@classmethod
def dual_class(self):
return BarBra
class BarBra(Bra, BarState):
@classmethod
def dual_class(self):
return BarKet
def test_doit():
f = FooKet('foo')
b = BarBra('bar')
assert InnerProduct(b, f).doit() == I
assert InnerProduct(Dagger(f), Dagger(b)).doit() == -I
assert InnerProduct(Dagger(f), f).doit() == Integer(1)
|
70e883dacff2749e1d437dc9ab3c5d8598bc263f72e20b2bdefd47c5bf67fdcd | from sympy.core.containers import Tuple
from sympy.core.symbol import symbols
from sympy.matrices.dense import Matrix
from sympy.physics.quantum.trace import Tr
from sympy.testing.pytest import raises
def test_trace_new():
a, b, c, d, Y = symbols('a b c d Y')
A, B, C, D = symbols('A B C D', commutative=False)
assert Tr(a + b) == a + b
assert Tr(A + B) == Tr(A) + Tr(B)
#check trace args not implicitly permuted
assert Tr(C*D*A*B).args[0].args == (C, D, A, B)
# check for mul and adds
assert Tr((a*b) + ( c*d)) == (a*b) + (c*d)
# Tr(scalar*A) = scalar*Tr(A)
assert Tr(a*A) == a*Tr(A)
assert Tr(a*A*B*b) == a*b*Tr(A*B)
# since A is symbol and not commutative
assert isinstance(Tr(A), Tr)
#POW
assert Tr(pow(a, b)) == a**b
assert isinstance(Tr(pow(A, a)), Tr)
#Matrix
M = Matrix([[1, 1], [2, 2]])
assert Tr(M) == 3
##test indices in different forms
#no index
t = Tr(A)
assert t.args[1] == Tuple()
#single index
t = Tr(A, 0)
assert t.args[1] == Tuple(0)
#index in a list
t = Tr(A, [0])
assert t.args[1] == Tuple(0)
t = Tr(A, [0, 1, 2])
assert t.args[1] == Tuple(0, 1, 2)
#index is tuple
t = Tr(A, (0))
assert t.args[1] == Tuple(0)
t = Tr(A, (1, 2))
assert t.args[1] == Tuple(1, 2)
#trace indices test
t = Tr((A + B), [2])
assert t.args[0].args[1] == Tuple(2) and t.args[1].args[1] == Tuple(2)
t = Tr(a*A, [2, 3])
assert t.args[1].args[1] == Tuple(2, 3)
#class with trace method defined
#to simulate numpy objects
class Foo:
def trace(self):
return 1
assert Tr(Foo()) == 1
#argument test
# check for value error, when either/both arguments are not provided
raises(ValueError, lambda: Tr())
raises(ValueError, lambda: Tr(A, 1, 2))
def test_trace_doit():
a, b, c, d = symbols('a b c d')
A, B, C, D = symbols('A B C D', commutative=False)
#TODO: needed while testing reduced density operations, etc.
def test_permute():
A, B, C, D, E, F, G = symbols('A B C D E F G', commutative=False)
t = Tr(A*B*C*D*E*F*G)
assert t.permute(0).args[0].args == (A, B, C, D, E, F, G)
assert t.permute(2).args[0].args == (F, G, A, B, C, D, E)
assert t.permute(4).args[0].args == (D, E, F, G, A, B, C)
assert t.permute(6).args[0].args == (B, C, D, E, F, G, A)
assert t.permute(8).args[0].args == t.permute(1).args[0].args
assert t.permute(-1).args[0].args == (B, C, D, E, F, G, A)
assert t.permute(-3).args[0].args == (D, E, F, G, A, B, C)
assert t.permute(-5).args[0].args == (F, G, A, B, C, D, E)
assert t.permute(-8).args[0].args == t.permute(-1).args[0].args
t = Tr((A + B)*(B*B)*C*D)
assert t.permute(2).args[0].args == (C, D, (A + B), (B**2))
t1 = Tr(A*B)
t2 = t1.permute(1)
assert id(t1) != id(t2) and t1 == t2
|
a70d78410e9705390adf9d36d44fe70ea72f5dd3a2e1b2e23e591d77213ceb9b | from sympy.concrete.summations import Sum
from sympy.core.numbers import Rational
from sympy.core.singleton import S
from sympy.core.symbol import symbols
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.physics.quantum.cg import Wigner3j, Wigner6j, Wigner9j, CG, cg_simp
from sympy.functions.special.tensor_functions import KroneckerDelta
def test_cg_simp_add():
j, m1, m1p, m2, m2p = symbols('j m1 m1p m2 m2p')
# Test Varshalovich 8.7.1 Eq 1
a = CG(S.Half, S.Half, 0, 0, S.Half, S.Half)
b = CG(S.Half, Rational(-1, 2), 0, 0, S.Half, Rational(-1, 2))
c = CG(1, 1, 0, 0, 1, 1)
d = CG(1, 0, 0, 0, 1, 0)
e = CG(1, -1, 0, 0, 1, -1)
assert cg_simp(a + b) == 2
assert cg_simp(c + d + e) == 3
assert cg_simp(a + b + c + d + e) == 5
assert cg_simp(a + b + c) == 2 + c
assert cg_simp(2*a + b) == 2 + a
assert cg_simp(2*c + d + e) == 3 + c
assert cg_simp(5*a + 5*b) == 10
assert cg_simp(5*c + 5*d + 5*e) == 15
assert cg_simp(-a - b) == -2
assert cg_simp(-c - d - e) == -3
assert cg_simp(-6*a - 6*b) == -12
assert cg_simp(-4*c - 4*d - 4*e) == -12
a = CG(S.Half, S.Half, j, 0, S.Half, S.Half)
b = CG(S.Half, Rational(-1, 2), j, 0, S.Half, Rational(-1, 2))
c = CG(1, 1, j, 0, 1, 1)
d = CG(1, 0, j, 0, 1, 0)
e = CG(1, -1, j, 0, 1, -1)
assert cg_simp(a + b) == 2*KroneckerDelta(j, 0)
assert cg_simp(c + d + e) == 3*KroneckerDelta(j, 0)
assert cg_simp(a + b + c + d + e) == 5*KroneckerDelta(j, 0)
assert cg_simp(a + b + c) == 2*KroneckerDelta(j, 0) + c
assert cg_simp(2*a + b) == 2*KroneckerDelta(j, 0) + a
assert cg_simp(2*c + d + e) == 3*KroneckerDelta(j, 0) + c
assert cg_simp(5*a + 5*b) == 10*KroneckerDelta(j, 0)
assert cg_simp(5*c + 5*d + 5*e) == 15*KroneckerDelta(j, 0)
assert cg_simp(-a - b) == -2*KroneckerDelta(j, 0)
assert cg_simp(-c - d - e) == -3*KroneckerDelta(j, 0)
assert cg_simp(-6*a - 6*b) == -12*KroneckerDelta(j, 0)
assert cg_simp(-4*c - 4*d - 4*e) == -12*KroneckerDelta(j, 0)
# Test Varshalovich 8.7.1 Eq 2
a = CG(S.Half, S.Half, S.Half, Rational(-1, 2), 0, 0)
b = CG(S.Half, Rational(-1, 2), S.Half, S.Half, 0, 0)
c = CG(1, 1, 1, -1, 0, 0)
d = CG(1, 0, 1, 0, 0, 0)
e = CG(1, -1, 1, 1, 0, 0)
assert cg_simp(a - b) == sqrt(2)
assert cg_simp(c - d + e) == sqrt(3)
assert cg_simp(a - b + c - d + e) == sqrt(2) + sqrt(3)
assert cg_simp(a - b + c) == sqrt(2) + c
assert cg_simp(2*a - b) == sqrt(2) + a
assert cg_simp(2*c - d + e) == sqrt(3) + c
assert cg_simp(5*a - 5*b) == 5*sqrt(2)
assert cg_simp(5*c - 5*d + 5*e) == 5*sqrt(3)
assert cg_simp(-a + b) == -sqrt(2)
assert cg_simp(-c + d - e) == -sqrt(3)
assert cg_simp(-6*a + 6*b) == -6*sqrt(2)
assert cg_simp(-4*c + 4*d - 4*e) == -4*sqrt(3)
a = CG(S.Half, S.Half, S.Half, Rational(-1, 2), j, 0)
b = CG(S.Half, Rational(-1, 2), S.Half, S.Half, j, 0)
c = CG(1, 1, 1, -1, j, 0)
d = CG(1, 0, 1, 0, j, 0)
e = CG(1, -1, 1, 1, j, 0)
assert cg_simp(a - b) == sqrt(2)*KroneckerDelta(j, 0)
assert cg_simp(c - d + e) == sqrt(3)*KroneckerDelta(j, 0)
assert cg_simp(a - b + c - d + e) == sqrt(
2)*KroneckerDelta(j, 0) + sqrt(3)*KroneckerDelta(j, 0)
assert cg_simp(a - b + c) == sqrt(2)*KroneckerDelta(j, 0) + c
assert cg_simp(2*a - b) == sqrt(2)*KroneckerDelta(j, 0) + a
assert cg_simp(2*c - d + e) == sqrt(3)*KroneckerDelta(j, 0) + c
assert cg_simp(5*a - 5*b) == 5*sqrt(2)*KroneckerDelta(j, 0)
assert cg_simp(5*c - 5*d + 5*e) == 5*sqrt(3)*KroneckerDelta(j, 0)
assert cg_simp(-a + b) == -sqrt(2)*KroneckerDelta(j, 0)
assert cg_simp(-c + d - e) == -sqrt(3)*KroneckerDelta(j, 0)
assert cg_simp(-6*a + 6*b) == -6*sqrt(2)*KroneckerDelta(j, 0)
assert cg_simp(-4*c + 4*d - 4*e) == -4*sqrt(3)*KroneckerDelta(j, 0)
# Test Varshalovich 8.7.2 Eq 9
# alpha=alphap,beta=betap case
# numerical
a = CG(S.Half, S.Half, S.Half, Rational(-1, 2), 1, 0)**2
b = CG(S.Half, S.Half, S.Half, Rational(-1, 2), 0, 0)**2
c = CG(1, 0, 1, 1, 1, 1)**2
d = CG(1, 0, 1, 1, 2, 1)**2
assert cg_simp(a + b) == 1
assert cg_simp(c + d) == 1
assert cg_simp(a + b + c + d) == 2
assert cg_simp(4*a + 4*b) == 4
assert cg_simp(4*c + 4*d) == 4
assert cg_simp(5*a + 3*b) == 3 + 2*a
assert cg_simp(5*c + 3*d) == 3 + 2*c
assert cg_simp(-a - b) == -1
assert cg_simp(-c - d) == -1
# symbolic
a = CG(S.Half, m1, S.Half, m2, 1, 1)**2
b = CG(S.Half, m1, S.Half, m2, 1, 0)**2
c = CG(S.Half, m1, S.Half, m2, 1, -1)**2
d = CG(S.Half, m1, S.Half, m2, 0, 0)**2
assert cg_simp(a + b + c + d) == 1
assert cg_simp(4*a + 4*b + 4*c + 4*d) == 4
assert cg_simp(3*a + 5*b + 3*c + 4*d) == 3 + 2*b + d
assert cg_simp(-a - b - c - d) == -1
a = CG(1, m1, 1, m2, 2, 2)**2
b = CG(1, m1, 1, m2, 2, 1)**2
c = CG(1, m1, 1, m2, 2, 0)**2
d = CG(1, m1, 1, m2, 2, -1)**2
e = CG(1, m1, 1, m2, 2, -2)**2
f = CG(1, m1, 1, m2, 1, 1)**2
g = CG(1, m1, 1, m2, 1, 0)**2
h = CG(1, m1, 1, m2, 1, -1)**2
i = CG(1, m1, 1, m2, 0, 0)**2
assert cg_simp(a + b + c + d + e + f + g + h + i) == 1
assert cg_simp(4*(a + b + c + d + e + f + g + h + i)) == 4
assert cg_simp(a + b + 2*c + d + 4*e + f + g + h + i) == 1 + c + 3*e
assert cg_simp(-a - b - c - d - e - f - g - h - i) == -1
# alpha!=alphap or beta!=betap case
# numerical
a = CG(S.Half, S(
1)/2, S.Half, Rational(-1, 2), 1, 0)*CG(S.Half, Rational(-1, 2), S.Half, S.Half, 1, 0)
b = CG(S.Half, S(
1)/2, S.Half, Rational(-1, 2), 0, 0)*CG(S.Half, Rational(-1, 2), S.Half, S.Half, 0, 0)
c = CG(1, 1, 1, 0, 2, 1)*CG(1, 0, 1, 1, 2, 1)
d = CG(1, 1, 1, 0, 1, 1)*CG(1, 0, 1, 1, 1, 1)
assert cg_simp(a + b) == 0
assert cg_simp(c + d) == 0
# symbolic
a = CG(S.Half, m1, S.Half, m2, 1, 1)*CG(S.Half, m1p, S.Half, m2p, 1, 1)
b = CG(S.Half, m1, S.Half, m2, 1, 0)*CG(S.Half, m1p, S.Half, m2p, 1, 0)
c = CG(S.Half, m1, S.Half, m2, 1, -1)*CG(S.Half, m1p, S.Half, m2p, 1, -1)
d = CG(S.Half, m1, S.Half, m2, 0, 0)*CG(S.Half, m1p, S.Half, m2p, 0, 0)
assert cg_simp(a + b + c + d) == KroneckerDelta(m1, m1p)*KroneckerDelta(m2, m2p)
a = CG(1, m1, 1, m2, 2, 2)*CG(1, m1p, 1, m2p, 2, 2)
b = CG(1, m1, 1, m2, 2, 1)*CG(1, m1p, 1, m2p, 2, 1)
c = CG(1, m1, 1, m2, 2, 0)*CG(1, m1p, 1, m2p, 2, 0)
d = CG(1, m1, 1, m2, 2, -1)*CG(1, m1p, 1, m2p, 2, -1)
e = CG(1, m1, 1, m2, 2, -2)*CG(1, m1p, 1, m2p, 2, -2)
f = CG(1, m1, 1, m2, 1, 1)*CG(1, m1p, 1, m2p, 1, 1)
g = CG(1, m1, 1, m2, 1, 0)*CG(1, m1p, 1, m2p, 1, 0)
h = CG(1, m1, 1, m2, 1, -1)*CG(1, m1p, 1, m2p, 1, -1)
i = CG(1, m1, 1, m2, 0, 0)*CG(1, m1p, 1, m2p, 0, 0)
assert cg_simp(
a + b + c + d + e + f + g + h + i) == KroneckerDelta(m1, m1p)*KroneckerDelta(m2, m2p)
def test_cg_simp_sum():
x, a, b, c, cp, alpha, beta, gamma, gammap = symbols(
'x a b c cp alpha beta gamma gammap')
# Varshalovich 8.7.1 Eq 1
assert cg_simp(x * Sum(CG(a, alpha, b, 0, a, alpha), (alpha, -a, a)
)) == x*(2*a + 1)*KroneckerDelta(b, 0)
assert cg_simp(x * Sum(CG(a, alpha, b, 0, a, alpha), (alpha, -a, a)) + CG(1, 0, 1, 0, 1, 0)) == x*(2*a + 1)*KroneckerDelta(b, 0) + CG(1, 0, 1, 0, 1, 0)
assert cg_simp(2 * Sum(CG(1, alpha, 0, 0, 1, alpha), (alpha, -1, 1))) == 6
# Varshalovich 8.7.1 Eq 2
assert cg_simp(x*Sum((-1)**(a - alpha) * CG(a, alpha, a, -alpha, c,
0), (alpha, -a, a))) == x*sqrt(2*a + 1)*KroneckerDelta(c, 0)
assert cg_simp(3*Sum((-1)**(2 - alpha) * CG(
2, alpha, 2, -alpha, 0, 0), (alpha, -2, 2))) == 3*sqrt(5)
# Varshalovich 8.7.2 Eq 4
assert cg_simp(Sum(CG(a, alpha, b, beta, c, gamma)*CG(a, alpha, b, beta, cp, gammap), (alpha, -a, a), (beta, -b, b))) == KroneckerDelta(c, cp)*KroneckerDelta(gamma, gammap)
assert cg_simp(Sum(CG(a, alpha, b, beta, c, gamma)*CG(a, alpha, b, beta, c, gammap), (alpha, -a, a), (beta, -b, b))) == KroneckerDelta(gamma, gammap)
assert cg_simp(Sum(CG(a, alpha, b, beta, c, gamma)*CG(a, alpha, b, beta, cp, gamma), (alpha, -a, a), (beta, -b, b))) == KroneckerDelta(c, cp)
assert cg_simp(Sum(CG(
a, alpha, b, beta, c, gamma)**2, (alpha, -a, a), (beta, -b, b))) == 1
assert cg_simp(Sum(CG(2, alpha, 1, beta, 2, gamma)*CG(2, alpha, 1, beta, 2, gammap), (alpha, -2, 2), (beta, -1, 1))) == KroneckerDelta(gamma, gammap)
def test_doit():
assert Wigner3j(S.Half, Rational(-1, 2), S.Half, S.Half, 0, 0).doit() == -sqrt(2)/2
assert Wigner6j(1, 2, 3, 2, 1, 2).doit() == sqrt(21)/105
assert Wigner6j(3, 1, 2, 2, 2, 1).doit() == sqrt(21) / 105
assert Wigner9j(
2, 1, 1, Rational(3, 2), S.Half, 1, S.Half, S.Half, 0).doit() == sqrt(2)/12
assert CG(S.Half, S.Half, S.Half, Rational(-1, 2), 1, 0).doit() == sqrt(2)/2
|
d77431eabbf45df27ef20a0cc16c3dc4a869d9733b6133c606eddb7ceda0784f | # -*- encoding: utf-8 -*-
"""
TODO:
* Address Issue 2251, printing of spin states
"""
from typing import Dict as tDict, Any
from sympy.physics.quantum.anticommutator import AntiCommutator
from sympy.physics.quantum.cg import CG, Wigner3j, Wigner6j, Wigner9j
from sympy.physics.quantum.commutator import Commutator
from sympy.physics.quantum.constants import hbar
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum.gate import CGate, CNotGate, IdentityGate, UGate, XGate
from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace, HilbertSpace, L2
from sympy.physics.quantum.innerproduct import InnerProduct
from sympy.physics.quantum.operator import Operator, OuterProduct, DifferentialOperator
from sympy.physics.quantum.qexpr import QExpr
from sympy.physics.quantum.qubit import Qubit, IntQubit
from sympy.physics.quantum.spin import Jz, J2, JzBra, JzBraCoupled, JzKet, JzKetCoupled, Rotation, WignerD
from sympy.physics.quantum.state import Bra, Ket, TimeDepBra, TimeDepKet
from sympy.physics.quantum.tensorproduct import TensorProduct
from sympy.physics.quantum.sho1d import RaisingOp
from sympy.core.function import (Derivative, Function)
from sympy.core.numbers import oo
from sympy.core.power import Pow
from sympy.core.singleton import S
from sympy.core.symbol import (Symbol, symbols)
from sympy.matrices.dense import Matrix
from sympy.sets.sets import Interval
from sympy.testing.pytest import XFAIL
# Imports used in srepr strings
from sympy.physics.quantum.spin import JzOp
from sympy.printing import srepr
from sympy.printing.pretty import pretty as xpretty
from sympy.printing.latex import latex
MutableDenseMatrix = Matrix
ENV = {} # type: tDict[str, Any]
exec('from sympy import *', ENV)
exec('from sympy.physics.quantum import *', ENV)
exec('from sympy.physics.quantum.cg import *', ENV)
exec('from sympy.physics.quantum.spin import *', ENV)
exec('from sympy.physics.quantum.hilbert import *', ENV)
exec('from sympy.physics.quantum.qubit import *', ENV)
exec('from sympy.physics.quantum.qexpr import *', ENV)
exec('from sympy.physics.quantum.gate import *', ENV)
exec('from sympy.physics.quantum.constants import *', ENV)
def sT(expr, string):
"""
sT := sreprTest
from sympy/printing/tests/test_repr.py
"""
assert srepr(expr) == string
assert eval(string, ENV) == expr
def pretty(expr):
"""ASCII pretty-printing"""
return xpretty(expr, use_unicode=False, wrap_line=False)
def upretty(expr):
"""Unicode pretty-printing"""
return xpretty(expr, use_unicode=True, wrap_line=False)
def test_anticommutator():
A = Operator('A')
B = Operator('B')
ac = AntiCommutator(A, B)
ac_tall = AntiCommutator(A**2, B)
assert str(ac) == '{A,B}'
assert pretty(ac) == '{A,B}'
assert upretty(ac) == '{A,B}'
assert latex(ac) == r'\left\{A,B\right\}'
sT(ac, "AntiCommutator(Operator(Symbol('A')),Operator(Symbol('B')))")
assert str(ac_tall) == '{A**2,B}'
ascii_str = \
"""\
/ 2 \\\n\
<A ,B>\n\
\\ /\
"""
ucode_str = \
"""\
⎧ 2 ⎫\n\
⎨A ,B⎬\n\
⎩ ⎭\
"""
assert pretty(ac_tall) == ascii_str
assert upretty(ac_tall) == ucode_str
assert latex(ac_tall) == r'\left\{A^{2},B\right\}'
sT(ac_tall, "AntiCommutator(Pow(Operator(Symbol('A')), Integer(2)),Operator(Symbol('B')))")
def test_cg():
cg = CG(1, 2, 3, 4, 5, 6)
wigner3j = Wigner3j(1, 2, 3, 4, 5, 6)
wigner6j = Wigner6j(1, 2, 3, 4, 5, 6)
wigner9j = Wigner9j(1, 2, 3, 4, 5, 6, 7, 8, 9)
assert str(cg) == 'CG(1, 2, 3, 4, 5, 6)'
ascii_str = \
"""\
5,6 \n\
C \n\
1,2,3,4\
"""
ucode_str = \
"""\
5,6 \n\
C \n\
1,2,3,4\
"""
assert pretty(cg) == ascii_str
assert upretty(cg) == ucode_str
assert latex(cg) == 'C^{5,6}_{1,2,3,4}'
assert latex(cg ** 2) == R'\left(C^{5,6}_{1,2,3,4}\right)^{2}'
sT(cg, "CG(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5), Integer(6))")
assert str(wigner3j) == 'Wigner3j(1, 2, 3, 4, 5, 6)'
ascii_str = \
"""\
/1 3 5\\\n\
| |\n\
\\2 4 6/\
"""
ucode_str = \
"""\
⎛1 3 5⎞\n\
⎜ ⎟\n\
⎝2 4 6⎠\
"""
assert pretty(wigner3j) == ascii_str
assert upretty(wigner3j) == ucode_str
assert latex(wigner3j) == \
r'\left(\begin{array}{ccc} 1 & 3 & 5 \\ 2 & 4 & 6 \end{array}\right)'
sT(wigner3j, "Wigner3j(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5), Integer(6))")
assert str(wigner6j) == 'Wigner6j(1, 2, 3, 4, 5, 6)'
ascii_str = \
"""\
/1 2 3\\\n\
< >\n\
\\4 5 6/\
"""
ucode_str = \
"""\
⎧1 2 3⎫\n\
⎨ ⎬\n\
⎩4 5 6⎭\
"""
assert pretty(wigner6j) == ascii_str
assert upretty(wigner6j) == ucode_str
assert latex(wigner6j) == \
r'\left\{\begin{array}{ccc} 1 & 2 & 3 \\ 4 & 5 & 6 \end{array}\right\}'
sT(wigner6j, "Wigner6j(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5), Integer(6))")
assert str(wigner9j) == 'Wigner9j(1, 2, 3, 4, 5, 6, 7, 8, 9)'
ascii_str = \
"""\
/1 2 3\\\n\
| |\n\
<4 5 6>\n\
| |\n\
\\7 8 9/\
"""
ucode_str = \
"""\
⎧1 2 3⎫\n\
⎪ ⎪\n\
⎨4 5 6⎬\n\
⎪ ⎪\n\
⎩7 8 9⎭\
"""
assert pretty(wigner9j) == ascii_str
assert upretty(wigner9j) == ucode_str
assert latex(wigner9j) == \
r'\left\{\begin{array}{ccc} 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \end{array}\right\}'
sT(wigner9j, "Wigner9j(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5), Integer(6), Integer(7), Integer(8), Integer(9))")
def test_commutator():
A = Operator('A')
B = Operator('B')
c = Commutator(A, B)
c_tall = Commutator(A**2, B)
assert str(c) == '[A,B]'
assert pretty(c) == '[A,B]'
assert upretty(c) == '[A,B]'
assert latex(c) == r'\left[A,B\right]'
sT(c, "Commutator(Operator(Symbol('A')),Operator(Symbol('B')))")
assert str(c_tall) == '[A**2,B]'
ascii_str = \
"""\
[ 2 ]\n\
[A ,B]\
"""
ucode_str = \
"""\
⎡ 2 ⎤\n\
⎣A ,B⎦\
"""
assert pretty(c_tall) == ascii_str
assert upretty(c_tall) == ucode_str
assert latex(c_tall) == r'\left[A^{2},B\right]'
sT(c_tall, "Commutator(Pow(Operator(Symbol('A')), Integer(2)),Operator(Symbol('B')))")
def test_constants():
assert str(hbar) == 'hbar'
assert pretty(hbar) == 'hbar'
assert upretty(hbar) == 'ℏ'
assert latex(hbar) == r'\hbar'
sT(hbar, "HBar()")
def test_dagger():
x = symbols('x')
expr = Dagger(x)
assert str(expr) == 'Dagger(x)'
ascii_str = \
"""\
+\n\
x \
"""
ucode_str = \
"""\
†\n\
x \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
assert latex(expr) == r'x^{\dagger}'
sT(expr, "Dagger(Symbol('x'))")
@XFAIL
def test_gate_failing():
a, b, c, d = symbols('a,b,c,d')
uMat = Matrix([[a, b], [c, d]])
g = UGate((0,), uMat)
assert str(g) == 'U(0)'
def test_gate():
a, b, c, d = symbols('a,b,c,d')
uMat = Matrix([[a, b], [c, d]])
q = Qubit(1, 0, 1, 0, 1)
g1 = IdentityGate(2)
g2 = CGate((3, 0), XGate(1))
g3 = CNotGate(1, 0)
g4 = UGate((0,), uMat)
assert str(g1) == '1(2)'
assert pretty(g1) == '1 \n 2'
assert upretty(g1) == '1 \n 2'
assert latex(g1) == r'1_{2}'
sT(g1, "IdentityGate(Integer(2))")
assert str(g1*q) == '1(2)*|10101>'
ascii_str = \
"""\
1 *|10101>\n\
2 \
"""
ucode_str = \
"""\
1 ⋅❘10101⟩\n\
2 \
"""
assert pretty(g1*q) == ascii_str
assert upretty(g1*q) == ucode_str
assert latex(g1*q) == r'1_{2} {\left|10101\right\rangle }'
sT(g1*q, "Mul(IdentityGate(Integer(2)), Qubit(Integer(1),Integer(0),Integer(1),Integer(0),Integer(1)))")
assert str(g2) == 'C((3,0),X(1))'
ascii_str = \
"""\
C /X \\\n\
3,0\\ 1/\
"""
ucode_str = \
"""\
C ⎛X ⎞\n\
3,0⎝ 1⎠\
"""
assert pretty(g2) == ascii_str
assert upretty(g2) == ucode_str
assert latex(g2) == r'C_{3,0}{\left(X_{1}\right)}'
sT(g2, "CGate(Tuple(Integer(3), Integer(0)),XGate(Integer(1)))")
assert str(g3) == 'CNOT(1,0)'
ascii_str = \
"""\
CNOT \n\
1,0\
"""
ucode_str = \
"""\
CNOT \n\
1,0\
"""
assert pretty(g3) == ascii_str
assert upretty(g3) == ucode_str
assert latex(g3) == r'CNOT_{1,0}'
sT(g3, "CNotGate(Integer(1),Integer(0))")
ascii_str = \
"""\
U \n\
0\
"""
ucode_str = \
"""\
U \n\
0\
"""
assert str(g4) == \
"""\
U((0,),Matrix([\n\
[a, b],\n\
[c, d]]))\
"""
assert pretty(g4) == ascii_str
assert upretty(g4) == ucode_str
assert latex(g4) == r'U_{0}'
sT(g4, "UGate(Tuple(Integer(0)),MutableDenseMatrix([[Symbol('a'), Symbol('b')], [Symbol('c'), Symbol('d')]]))")
def test_hilbert():
h1 = HilbertSpace()
h2 = ComplexSpace(2)
h3 = FockSpace()
h4 = L2(Interval(0, oo))
assert str(h1) == 'H'
assert pretty(h1) == 'H'
assert upretty(h1) == 'H'
assert latex(h1) == r'\mathcal{H}'
sT(h1, "HilbertSpace()")
assert str(h2) == 'C(2)'
ascii_str = \
"""\
2\n\
C \
"""
ucode_str = \
"""\
2\n\
C \
"""
assert pretty(h2) == ascii_str
assert upretty(h2) == ucode_str
assert latex(h2) == r'\mathcal{C}^{2}'
sT(h2, "ComplexSpace(Integer(2))")
assert str(h3) == 'F'
assert pretty(h3) == 'F'
assert upretty(h3) == 'F'
assert latex(h3) == r'\mathcal{F}'
sT(h3, "FockSpace()")
assert str(h4) == 'L2(Interval(0, oo))'
ascii_str = \
"""\
2\n\
L \
"""
ucode_str = \
"""\
2\n\
L \
"""
assert pretty(h4) == ascii_str
assert upretty(h4) == ucode_str
assert latex(h4) == r'{\mathcal{L}^2}\left( \left[0, \infty\right) \right)'
sT(h4, "L2(Interval(Integer(0), oo, false, true))")
assert str(h1 + h2) == 'H+C(2)'
ascii_str = \
"""\
2\n\
H + C \
"""
ucode_str = \
"""\
2\n\
H ⊕ C \
"""
assert pretty(h1 + h2) == ascii_str
assert upretty(h1 + h2) == ucode_str
assert latex(h1 + h2)
sT(h1 + h2, "DirectSumHilbertSpace(HilbertSpace(),ComplexSpace(Integer(2)))")
assert str(h1*h2) == "H*C(2)"
ascii_str = \
"""\
2\n\
H x C \
"""
ucode_str = \
"""\
2\n\
H ⨂ C \
"""
assert pretty(h1*h2) == ascii_str
assert upretty(h1*h2) == ucode_str
assert latex(h1*h2)
sT(h1*h2,
"TensorProductHilbertSpace(HilbertSpace(),ComplexSpace(Integer(2)))")
assert str(h1**2) == 'H**2'
ascii_str = \
"""\
x2\n\
H \
"""
ucode_str = \
"""\
⨂2\n\
H \
"""
assert pretty(h1**2) == ascii_str
assert upretty(h1**2) == ucode_str
assert latex(h1**2) == r'{\mathcal{H}}^{\otimes 2}'
sT(h1**2, "TensorPowerHilbertSpace(HilbertSpace(),Integer(2))")
def test_innerproduct():
x = symbols('x')
ip1 = InnerProduct(Bra(), Ket())
ip2 = InnerProduct(TimeDepBra(), TimeDepKet())
ip3 = InnerProduct(JzBra(1, 1), JzKet(1, 1))
ip4 = InnerProduct(JzBraCoupled(1, 1, (1, 1)), JzKetCoupled(1, 1, (1, 1)))
ip_tall1 = InnerProduct(Bra(x/2), Ket(x/2))
ip_tall2 = InnerProduct(Bra(x), Ket(x/2))
ip_tall3 = InnerProduct(Bra(x/2), Ket(x))
assert str(ip1) == '<psi|psi>'
assert pretty(ip1) == '<psi|psi>'
assert upretty(ip1) == '⟨ψ❘ψ⟩'
assert latex(
ip1) == r'\left\langle \psi \right. {\left|\psi\right\rangle }'
sT(ip1, "InnerProduct(Bra(Symbol('psi')),Ket(Symbol('psi')))")
assert str(ip2) == '<psi;t|psi;t>'
assert pretty(ip2) == '<psi;t|psi;t>'
assert upretty(ip2) == '⟨ψ;t❘ψ;t⟩'
assert latex(ip2) == \
r'\left\langle \psi;t \right. {\left|\psi;t\right\rangle }'
sT(ip2, "InnerProduct(TimeDepBra(Symbol('psi'),Symbol('t')),TimeDepKet(Symbol('psi'),Symbol('t')))")
assert str(ip3) == "<1,1|1,1>"
assert pretty(ip3) == '<1,1|1,1>'
assert upretty(ip3) == '⟨1,1❘1,1⟩'
assert latex(ip3) == r'\left\langle 1,1 \right. {\left|1,1\right\rangle }'
sT(ip3, "InnerProduct(JzBra(Integer(1),Integer(1)),JzKet(Integer(1),Integer(1)))")
assert str(ip4) == "<1,1,j1=1,j2=1|1,1,j1=1,j2=1>"
assert pretty(ip4) == '<1,1,j1=1,j2=1|1,1,j1=1,j2=1>'
assert upretty(ip4) == '⟨1,1,j₁=1,j₂=1❘1,1,j₁=1,j₂=1⟩'
assert latex(ip4) == \
r'\left\langle 1,1,j_{1}=1,j_{2}=1 \right. {\left|1,1,j_{1}=1,j_{2}=1\right\rangle }'
sT(ip4, "InnerProduct(JzBraCoupled(Integer(1),Integer(1),Tuple(Integer(1), Integer(1)),Tuple(Tuple(Integer(1), Integer(2), Integer(1)))),JzKetCoupled(Integer(1),Integer(1),Tuple(Integer(1), Integer(1)),Tuple(Tuple(Integer(1), Integer(2), Integer(1)))))")
assert str(ip_tall1) == '<x/2|x/2>'
ascii_str = \
"""\
/ | \\ \n\
/ x|x \\\n\
\\ -|- /\n\
\\2|2/ \
"""
ucode_str = \
"""\
╱ │ ╲ \n\
╱ x│x ╲\n\
╲ ─│─ ╱\n\
╲2│2╱ \
"""
assert pretty(ip_tall1) == ascii_str
assert upretty(ip_tall1) == ucode_str
assert latex(ip_tall1) == \
r'\left\langle \frac{x}{2} \right. {\left|\frac{x}{2}\right\rangle }'
sT(ip_tall1, "InnerProduct(Bra(Mul(Rational(1, 2), Symbol('x'))),Ket(Mul(Rational(1, 2), Symbol('x'))))")
assert str(ip_tall2) == '<x|x/2>'
ascii_str = \
"""\
/ | \\ \n\
/ |x \\\n\
\\ x|- /\n\
\\ |2/ \
"""
ucode_str = \
"""\
╱ │ ╲ \n\
╱ │x ╲\n\
╲ x│─ ╱\n\
╲ │2╱ \
"""
assert pretty(ip_tall2) == ascii_str
assert upretty(ip_tall2) == ucode_str
assert latex(ip_tall2) == \
r'\left\langle x \right. {\left|\frac{x}{2}\right\rangle }'
sT(ip_tall2,
"InnerProduct(Bra(Symbol('x')),Ket(Mul(Rational(1, 2), Symbol('x'))))")
assert str(ip_tall3) == '<x/2|x>'
ascii_str = \
"""\
/ | \\ \n\
/ x| \\\n\
\\ -|x /\n\
\\2| / \
"""
ucode_str = \
"""\
╱ │ ╲ \n\
╱ x│ ╲\n\
╲ ─│x ╱\n\
╲2│ ╱ \
"""
assert pretty(ip_tall3) == ascii_str
assert upretty(ip_tall3) == ucode_str
assert latex(ip_tall3) == \
r'\left\langle \frac{x}{2} \right. {\left|x\right\rangle }'
sT(ip_tall3,
"InnerProduct(Bra(Mul(Rational(1, 2), Symbol('x'))),Ket(Symbol('x')))")
def test_operator():
a = Operator('A')
b = Operator('B', Symbol('t'), S.Half)
inv = a.inv()
f = Function('f')
x = symbols('x')
d = DifferentialOperator(Derivative(f(x), x), f(x))
op = OuterProduct(Ket(), Bra())
assert str(a) == 'A'
assert pretty(a) == 'A'
assert upretty(a) == 'A'
assert latex(a) == 'A'
sT(a, "Operator(Symbol('A'))")
assert str(inv) == 'A**(-1)'
ascii_str = \
"""\
-1\n\
A \
"""
ucode_str = \
"""\
-1\n\
A \
"""
assert pretty(inv) == ascii_str
assert upretty(inv) == ucode_str
assert latex(inv) == r'A^{-1}'
sT(inv, "Pow(Operator(Symbol('A')), Integer(-1))")
assert str(d) == 'DifferentialOperator(Derivative(f(x), x),f(x))'
ascii_str = \
"""\
/d \\\n\
DifferentialOperator|--(f(x)),f(x)|\n\
\\dx /\
"""
ucode_str = \
"""\
⎛d ⎞\n\
DifferentialOperator⎜──(f(x)),f(x)⎟\n\
⎝dx ⎠\
"""
assert pretty(d) == ascii_str
assert upretty(d) == ucode_str
assert latex(d) == \
r'DifferentialOperator\left(\frac{d}{d x} f{\left(x \right)},f{\left(x \right)}\right)'
sT(d, "DifferentialOperator(Derivative(Function('f')(Symbol('x')), Tuple(Symbol('x'), Integer(1))),Function('f')(Symbol('x')))")
assert str(b) == 'Operator(B,t,1/2)'
assert pretty(b) == 'Operator(B,t,1/2)'
assert upretty(b) == 'Operator(B,t,1/2)'
assert latex(b) == r'Operator\left(B,t,\frac{1}{2}\right)'
sT(b, "Operator(Symbol('B'),Symbol('t'),Rational(1, 2))")
assert str(op) == '|psi><psi|'
assert pretty(op) == '|psi><psi|'
assert upretty(op) == '❘ψ⟩⟨ψ❘'
assert latex(op) == r'{\left|\psi\right\rangle }{\left\langle \psi\right|}'
sT(op, "OuterProduct(Ket(Symbol('psi')),Bra(Symbol('psi')))")
def test_qexpr():
q = QExpr('q')
assert str(q) == 'q'
assert pretty(q) == 'q'
assert upretty(q) == 'q'
assert latex(q) == r'q'
sT(q, "QExpr(Symbol('q'))")
def test_qubit():
q1 = Qubit('0101')
q2 = IntQubit(8)
assert str(q1) == '|0101>'
assert pretty(q1) == '|0101>'
assert upretty(q1) == '❘0101⟩'
assert latex(q1) == r'{\left|0101\right\rangle }'
sT(q1, "Qubit(Integer(0),Integer(1),Integer(0),Integer(1))")
assert str(q2) == '|8>'
assert pretty(q2) == '|8>'
assert upretty(q2) == '❘8⟩'
assert latex(q2) == r'{\left|8\right\rangle }'
sT(q2, "IntQubit(8)")
def test_spin():
lz = JzOp('L')
ket = JzKet(1, 0)
bra = JzBra(1, 0)
cket = JzKetCoupled(1, 0, (1, 2))
cbra = JzBraCoupled(1, 0, (1, 2))
cket_big = JzKetCoupled(1, 0, (1, 2, 3))
cbra_big = JzBraCoupled(1, 0, (1, 2, 3))
rot = Rotation(1, 2, 3)
bigd = WignerD(1, 2, 3, 4, 5, 6)
smalld = WignerD(1, 2, 3, 0, 4, 0)
assert str(lz) == 'Lz'
ascii_str = \
"""\
L \n\
z\
"""
ucode_str = \
"""\
L \n\
z\
"""
assert pretty(lz) == ascii_str
assert upretty(lz) == ucode_str
assert latex(lz) == 'L_z'
sT(lz, "JzOp(Symbol('L'))")
assert str(J2) == 'J2'
ascii_str = \
"""\
2\n\
J \
"""
ucode_str = \
"""\
2\n\
J \
"""
assert pretty(J2) == ascii_str
assert upretty(J2) == ucode_str
assert latex(J2) == r'J^2'
sT(J2, "J2Op(Symbol('J'))")
assert str(Jz) == 'Jz'
ascii_str = \
"""\
J \n\
z\
"""
ucode_str = \
"""\
J \n\
z\
"""
assert pretty(Jz) == ascii_str
assert upretty(Jz) == ucode_str
assert latex(Jz) == 'J_z'
sT(Jz, "JzOp(Symbol('J'))")
assert str(ket) == '|1,0>'
assert pretty(ket) == '|1,0>'
assert upretty(ket) == '❘1,0⟩'
assert latex(ket) == r'{\left|1,0\right\rangle }'
sT(ket, "JzKet(Integer(1),Integer(0))")
assert str(bra) == '<1,0|'
assert pretty(bra) == '<1,0|'
assert upretty(bra) == '⟨1,0❘'
assert latex(bra) == r'{\left\langle 1,0\right|}'
sT(bra, "JzBra(Integer(1),Integer(0))")
assert str(cket) == '|1,0,j1=1,j2=2>'
assert pretty(cket) == '|1,0,j1=1,j2=2>'
assert upretty(cket) == '❘1,0,j₁=1,j₂=2⟩'
assert latex(cket) == r'{\left|1,0,j_{1}=1,j_{2}=2\right\rangle }'
sT(cket, "JzKetCoupled(Integer(1),Integer(0),Tuple(Integer(1), Integer(2)),Tuple(Tuple(Integer(1), Integer(2), Integer(1))))")
assert str(cbra) == '<1,0,j1=1,j2=2|'
assert pretty(cbra) == '<1,0,j1=1,j2=2|'
assert upretty(cbra) == '⟨1,0,j₁=1,j₂=2❘'
assert latex(cbra) == r'{\left\langle 1,0,j_{1}=1,j_{2}=2\right|}'
sT(cbra, "JzBraCoupled(Integer(1),Integer(0),Tuple(Integer(1), Integer(2)),Tuple(Tuple(Integer(1), Integer(2), Integer(1))))")
assert str(cket_big) == '|1,0,j1=1,j2=2,j3=3,j(1,2)=3>'
# TODO: Fix non-unicode pretty printing
# i.e. j1,2 -> j(1,2)
assert pretty(cket_big) == '|1,0,j1=1,j2=2,j3=3,j1,2=3>'
assert upretty(cket_big) == '❘1,0,j₁=1,j₂=2,j₃=3,j₁,₂=3⟩'
assert latex(cket_big) == \
r'{\left|1,0,j_{1}=1,j_{2}=2,j_{3}=3,j_{1,2}=3\right\rangle }'
sT(cket_big, "JzKetCoupled(Integer(1),Integer(0),Tuple(Integer(1), Integer(2), Integer(3)),Tuple(Tuple(Integer(1), Integer(2), Integer(3)), Tuple(Integer(1), Integer(3), Integer(1))))")
assert str(cbra_big) == '<1,0,j1=1,j2=2,j3=3,j(1,2)=3|'
assert pretty(cbra_big) == '<1,0,j1=1,j2=2,j3=3,j1,2=3|'
assert upretty(cbra_big) == '⟨1,0,j₁=1,j₂=2,j₃=3,j₁,₂=3❘'
assert latex(cbra_big) == \
r'{\left\langle 1,0,j_{1}=1,j_{2}=2,j_{3}=3,j_{1,2}=3\right|}'
sT(cbra_big, "JzBraCoupled(Integer(1),Integer(0),Tuple(Integer(1), Integer(2), Integer(3)),Tuple(Tuple(Integer(1), Integer(2), Integer(3)), Tuple(Integer(1), Integer(3), Integer(1))))")
assert str(rot) == 'R(1,2,3)'
assert pretty(rot) == 'R (1,2,3)'
assert upretty(rot) == 'ℛ (1,2,3)'
assert latex(rot) == r'\mathcal{R}\left(1,2,3\right)'
sT(rot, "Rotation(Integer(1),Integer(2),Integer(3))")
assert str(bigd) == 'WignerD(1, 2, 3, 4, 5, 6)'
ascii_str = \
"""\
1 \n\
D (4,5,6)\n\
2,3 \
"""
ucode_str = \
"""\
1 \n\
D (4,5,6)\n\
2,3 \
"""
assert pretty(bigd) == ascii_str
assert upretty(bigd) == ucode_str
assert latex(bigd) == r'D^{1}_{2,3}\left(4,5,6\right)'
sT(bigd, "WignerD(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5), Integer(6))")
assert str(smalld) == 'WignerD(1, 2, 3, 0, 4, 0)'
ascii_str = \
"""\
1 \n\
d (4)\n\
2,3 \
"""
ucode_str = \
"""\
1 \n\
d (4)\n\
2,3 \
"""
assert pretty(smalld) == ascii_str
assert upretty(smalld) == ucode_str
assert latex(smalld) == r'd^{1}_{2,3}\left(4\right)'
sT(smalld, "WignerD(Integer(1), Integer(2), Integer(3), Integer(0), Integer(4), Integer(0))")
def test_state():
x = symbols('x')
bra = Bra()
ket = Ket()
bra_tall = Bra(x/2)
ket_tall = Ket(x/2)
tbra = TimeDepBra()
tket = TimeDepKet()
assert str(bra) == '<psi|'
assert pretty(bra) == '<psi|'
assert upretty(bra) == '⟨ψ❘'
assert latex(bra) == r'{\left\langle \psi\right|}'
sT(bra, "Bra(Symbol('psi'))")
assert str(ket) == '|psi>'
assert pretty(ket) == '|psi>'
assert upretty(ket) == '❘ψ⟩'
assert latex(ket) == r'{\left|\psi\right\rangle }'
sT(ket, "Ket(Symbol('psi'))")
assert str(bra_tall) == '<x/2|'
ascii_str = \
"""\
/ |\n\
/ x|\n\
\\ -|\n\
\\2|\
"""
ucode_str = \
"""\
╱ │\n\
╱ x│\n\
╲ ─│\n\
╲2│\
"""
assert pretty(bra_tall) == ascii_str
assert upretty(bra_tall) == ucode_str
assert latex(bra_tall) == r'{\left\langle \frac{x}{2}\right|}'
sT(bra_tall, "Bra(Mul(Rational(1, 2), Symbol('x')))")
assert str(ket_tall) == '|x/2>'
ascii_str = \
"""\
| \\ \n\
|x \\\n\
|- /\n\
|2/ \
"""
ucode_str = \
"""\
│ ╲ \n\
│x ╲\n\
│─ ╱\n\
│2╱ \
"""
assert pretty(ket_tall) == ascii_str
assert upretty(ket_tall) == ucode_str
assert latex(ket_tall) == r'{\left|\frac{x}{2}\right\rangle }'
sT(ket_tall, "Ket(Mul(Rational(1, 2), Symbol('x')))")
assert str(tbra) == '<psi;t|'
assert pretty(tbra) == '<psi;t|'
assert upretty(tbra) == '⟨ψ;t❘'
assert latex(tbra) == r'{\left\langle \psi;t\right|}'
sT(tbra, "TimeDepBra(Symbol('psi'),Symbol('t'))")
assert str(tket) == '|psi;t>'
assert pretty(tket) == '|psi;t>'
assert upretty(tket) == '❘ψ;t⟩'
assert latex(tket) == r'{\left|\psi;t\right\rangle }'
sT(tket, "TimeDepKet(Symbol('psi'),Symbol('t'))")
def test_tensorproduct():
tp = TensorProduct(JzKet(1, 1), JzKet(1, 0))
assert str(tp) == '|1,1>x|1,0>'
assert pretty(tp) == '|1,1>x |1,0>'
assert upretty(tp) == '❘1,1⟩⨂ ❘1,0⟩'
assert latex(tp) == \
r'{{\left|1,1\right\rangle }}\otimes {{\left|1,0\right\rangle }}'
sT(tp, "TensorProduct(JzKet(Integer(1),Integer(1)), JzKet(Integer(1),Integer(0)))")
def test_big_expr():
f = Function('f')
x = symbols('x')
e1 = Dagger(AntiCommutator(Operator('A') + Operator('B'), Pow(DifferentialOperator(Derivative(f(x), x), f(x)), 3))*TensorProduct(Jz**2, Operator('A') + Operator('B')))*(JzBra(1, 0) + JzBra(1, 1))*(JzKet(0, 0) + JzKet(1, -1))
e2 = Commutator(Jz**2, Operator('A') + Operator('B'))*AntiCommutator(Dagger(Operator('C')*Operator('D')), Operator('E').inv()**2)*Dagger(Commutator(Jz, J2))
e3 = Wigner3j(1, 2, 3, 4, 5, 6)*TensorProduct(Commutator(Operator('A') + Dagger(Operator('B')), Operator('C') + Operator('D')), Jz - J2)*Dagger(OuterProduct(Dagger(JzBra(1, 1)), JzBra(1, 0)))*TensorProduct(JzKetCoupled(1, 1, (1, 1)) + JzKetCoupled(1, 0, (1, 1)), JzKetCoupled(1, -1, (1, 1)))
e4 = (ComplexSpace(1)*ComplexSpace(2) + FockSpace()**2)*(L2(Interval(
0, oo)) + HilbertSpace())
assert str(e1) == '(Jz**2)x(Dagger(A) + Dagger(B))*{Dagger(DifferentialOperator(Derivative(f(x), x),f(x)))**3,Dagger(A) + Dagger(B)}*(<1,0| + <1,1|)*(|0,0> + |1,-1>)'
ascii_str = \
"""\
/ 3 \\ \n\
|/ +\\ | \n\
2 / + +\\ <| /d \\ | + +> \n\
/J \\ x \\A + B /*||DifferentialOperator|--(f(x)),f(x)| | ,A + B |*(<1,0| + <1,1|)*(|0,0> + |1,-1>)\n\
\\ z/ \\\\ \\dx / / / \
"""
ucode_str = \
"""\
⎧ 3 ⎫ \n\
⎪⎛ †⎞ ⎪ \n\
2 ⎛ † †⎞ ⎨⎜ ⎛d ⎞ ⎟ † †⎬ \n\
⎛J ⎞ ⨂ ⎝A + B ⎠⋅⎪⎜DifferentialOperator⎜──(f(x)),f(x)⎟ ⎟ ,A + B ⎪⋅(⟨1,0❘ + ⟨1,1❘)⋅(❘0,0⟩ + ❘1,-1⟩)\n\
⎝ z⎠ ⎩⎝ ⎝dx ⎠ ⎠ ⎭ \
"""
assert pretty(e1) == ascii_str
assert upretty(e1) == ucode_str
assert latex(e1) == \
r'{J_z^{2}}\otimes \left({A^{\dagger} + B^{\dagger}}\right) \left\{\left(DifferentialOperator\left(\frac{d}{d x} f{\left(x \right)},f{\left(x \right)}\right)^{\dagger}\right)^{3},A^{\dagger} + B^{\dagger}\right\} \left({\left\langle 1,0\right|} + {\left\langle 1,1\right|}\right) \left({\left|0,0\right\rangle } + {\left|1,-1\right\rangle }\right)'
sT(e1, "Mul(TensorProduct(Pow(JzOp(Symbol('J')), Integer(2)), Add(Dagger(Operator(Symbol('A'))), Dagger(Operator(Symbol('B'))))), AntiCommutator(Pow(Dagger(DifferentialOperator(Derivative(Function('f')(Symbol('x')), Tuple(Symbol('x'), Integer(1))),Function('f')(Symbol('x')))), Integer(3)),Add(Dagger(Operator(Symbol('A'))), Dagger(Operator(Symbol('B'))))), Add(JzBra(Integer(1),Integer(0)), JzBra(Integer(1),Integer(1))), Add(JzKet(Integer(0),Integer(0)), JzKet(Integer(1),Integer(-1))))")
assert str(e2) == '[Jz**2,A + B]*{E**(-2),Dagger(D)*Dagger(C)}*[J2,Jz]'
ascii_str = \
"""\
[ 2 ] / -2 + +\\ [ 2 ]\n\
[/J \\ ,A + B]*<E ,D *C >*[J ,J ]\n\
[\\ z/ ] \\ / [ z]\
"""
ucode_str = \
"""\
⎡ 2 ⎤ ⎧ -2 † †⎫ ⎡ 2 ⎤\n\
⎢⎛J ⎞ ,A + B⎥⋅⎨E ,D ⋅C ⎬⋅⎢J ,J ⎥\n\
⎣⎝ z⎠ ⎦ ⎩ ⎭ ⎣ z⎦\
"""
assert pretty(e2) == ascii_str
assert upretty(e2) == ucode_str
assert latex(e2) == \
r'\left[J_z^{2},A + B\right] \left\{E^{-2},D^{\dagger} C^{\dagger}\right\} \left[J^2,J_z\right]'
sT(e2, "Mul(Commutator(Pow(JzOp(Symbol('J')), Integer(2)),Add(Operator(Symbol('A')), Operator(Symbol('B')))), AntiCommutator(Pow(Operator(Symbol('E')), Integer(-2)),Mul(Dagger(Operator(Symbol('D'))), Dagger(Operator(Symbol('C'))))), Commutator(J2Op(Symbol('J')),JzOp(Symbol('J'))))")
assert str(e3) == \
"Wigner3j(1, 2, 3, 4, 5, 6)*[Dagger(B) + A,C + D]x(-J2 + Jz)*|1,0><1,1|*(|1,0,j1=1,j2=1> + |1,1,j1=1,j2=1>)x|1,-1,j1=1,j2=1>"
ascii_str = \
"""\
[ + ] / 2 \\ \n\
/1 3 5\\*[B + A,C + D]x |- J + J |*|1,0><1,1|*(|1,0,j1=1,j2=1> + |1,1,j1=1,j2=1>)x |1,-1,j1=1,j2=1>\n\
| | \\ z/ \n\
\\2 4 6/ \
"""
ucode_str = \
"""\
⎡ † ⎤ ⎛ 2 ⎞ \n\
⎛1 3 5⎞⋅⎣B + A,C + D⎦⨂ ⎜- J + J ⎟⋅❘1,0⟩⟨1,1❘⋅(❘1,0,j₁=1,j₂=1⟩ + ❘1,1,j₁=1,j₂=1⟩)⨂ ❘1,-1,j₁=1,j₂=1⟩\n\
⎜ ⎟ ⎝ z⎠ \n\
⎝2 4 6⎠ \
"""
assert pretty(e3) == ascii_str
assert upretty(e3) == ucode_str
assert latex(e3) == \
r'\left(\begin{array}{ccc} 1 & 3 & 5 \\ 2 & 4 & 6 \end{array}\right) {\left[B^{\dagger} + A,C + D\right]}\otimes \left({- J^2 + J_z}\right) {\left|1,0\right\rangle }{\left\langle 1,1\right|} \left({{\left|1,0,j_{1}=1,j_{2}=1\right\rangle } + {\left|1,1,j_{1}=1,j_{2}=1\right\rangle }}\right)\otimes {{\left|1,-1,j_{1}=1,j_{2}=1\right\rangle }}'
sT(e3, "Mul(Wigner3j(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5), Integer(6)), TensorProduct(Commutator(Add(Dagger(Operator(Symbol('B'))), Operator(Symbol('A'))),Add(Operator(Symbol('C')), Operator(Symbol('D')))), Add(Mul(Integer(-1), J2Op(Symbol('J'))), JzOp(Symbol('J')))), OuterProduct(JzKet(Integer(1),Integer(0)),JzBra(Integer(1),Integer(1))), TensorProduct(Add(JzKetCoupled(Integer(1),Integer(0),Tuple(Integer(1), Integer(1)),Tuple(Tuple(Integer(1), Integer(2), Integer(1)))), JzKetCoupled(Integer(1),Integer(1),Tuple(Integer(1), Integer(1)),Tuple(Tuple(Integer(1), Integer(2), Integer(1))))), JzKetCoupled(Integer(1),Integer(-1),Tuple(Integer(1), Integer(1)),Tuple(Tuple(Integer(1), Integer(2), Integer(1))))))")
assert str(e4) == '(C(1)*C(2)+F**2)*(L2(Interval(0, oo))+H)'
ascii_str = \
"""\
// 1 2\\ x2\\ / 2 \\\n\
\\\\C x C / + F / x \\L + H/\
"""
ucode_str = \
"""\
⎛⎛ 1 2⎞ ⨂2⎞ ⎛ 2 ⎞\n\
⎝⎝C ⨂ C ⎠ ⊕ F ⎠ ⨂ ⎝L ⊕ H⎠\
"""
assert pretty(e4) == ascii_str
assert upretty(e4) == ucode_str
assert latex(e4) == \
r'\left(\left(\mathcal{C}^{1}\otimes \mathcal{C}^{2}\right)\oplus {\mathcal{F}}^{\otimes 2}\right)\otimes \left({\mathcal{L}^2}\left( \left[0, \infty\right) \right)\oplus \mathcal{H}\right)'
sT(e4, "TensorProductHilbertSpace((DirectSumHilbertSpace(TensorProductHilbertSpace(ComplexSpace(Integer(1)),ComplexSpace(Integer(2))),TensorPowerHilbertSpace(FockSpace(),Integer(2)))),(DirectSumHilbertSpace(L2(Interval(Integer(0), oo, false, true)),HilbertSpace())))")
def _test_sho1d():
ad = RaisingOp('a')
assert pretty(ad) == ' \N{DAGGER}\na '
assert latex(ad) == 'a^{\\dagger}'
|
9dcef9644e575edadcf3c39c7c1e66006874d56a5fddde116ecbbcbcb24f4c2f | """Tests for sho1d.py"""
from sympy.core.numbers import (I, Integer)
from sympy.core.singleton import S
from sympy.core.symbol import Symbol
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.physics.quantum import Dagger
from sympy.physics.quantum.constants import hbar
from sympy.physics.quantum import Commutator
from sympy.physics.quantum.qapply import qapply
from sympy.physics.quantum.innerproduct import InnerProduct
from sympy.physics.quantum.cartesian import X, Px
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.physics.quantum.hilbert import ComplexSpace
from sympy.physics.quantum.represent import represent
from sympy.external import import_module
from sympy.testing.pytest import skip
from sympy.physics.quantum.sho1d import (RaisingOp, LoweringOp,
SHOKet, SHOBra,
Hamiltonian, NumberOp)
ad = RaisingOp('a')
a = LoweringOp('a')
k = SHOKet('k')
kz = SHOKet(0)
kf = SHOKet(1)
k3 = SHOKet(3)
b = SHOBra('b')
b3 = SHOBra(3)
H = Hamiltonian('H')
N = NumberOp('N')
omega = Symbol('omega')
m = Symbol('m')
ndim = Integer(4)
np = import_module('numpy')
scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']})
ad_rep_sympy = represent(ad, basis=N, ndim=4, format='sympy')
a_rep = represent(a, basis=N, ndim=4, format='sympy')
N_rep = represent(N, basis=N, ndim=4, format='sympy')
H_rep = represent(H, basis=N, ndim=4, format='sympy')
k3_rep = represent(k3, basis=N, ndim=4, format='sympy')
b3_rep = represent(b3, basis=N, ndim=4, format='sympy')
def test_RaisingOp():
assert Dagger(ad) == a
assert Commutator(ad, a).doit() == Integer(-1)
assert Commutator(ad, N).doit() == Integer(-1)*ad
assert qapply(ad*k) == (sqrt(k.n + 1)*SHOKet(k.n + 1)).expand()
assert qapply(ad*kz) == (sqrt(kz.n + 1)*SHOKet(kz.n + 1)).expand()
assert qapply(ad*kf) == (sqrt(kf.n + 1)*SHOKet(kf.n + 1)).expand()
assert ad.rewrite('xp').doit() == \
(Integer(1)/sqrt(Integer(2)*hbar*m*omega))*(Integer(-1)*I*Px + m*omega*X)
assert ad.hilbert_space == ComplexSpace(S.Infinity)
for i in range(ndim - 1):
assert ad_rep_sympy[i + 1,i] == sqrt(i + 1)
if not np:
skip("numpy not installed.")
ad_rep_numpy = represent(ad, basis=N, ndim=4, format='numpy')
for i in range(ndim - 1):
assert ad_rep_numpy[i + 1,i] == float(sqrt(i + 1))
if not np:
skip("numpy not installed.")
if not scipy:
skip("scipy not installed.")
ad_rep_scipy = represent(ad, basis=N, ndim=4, format='scipy.sparse', spmatrix='lil')
for i in range(ndim - 1):
assert ad_rep_scipy[i + 1,i] == float(sqrt(i + 1))
assert ad_rep_numpy.dtype == 'float64'
assert ad_rep_scipy.dtype == 'float64'
def test_LoweringOp():
assert Dagger(a) == ad
assert Commutator(a, ad).doit() == Integer(1)
assert Commutator(a, N).doit() == a
assert qapply(a*k) == (sqrt(k.n)*SHOKet(k.n-Integer(1))).expand()
assert qapply(a*kz) == Integer(0)
assert qapply(a*kf) == (sqrt(kf.n)*SHOKet(kf.n-Integer(1))).expand()
assert a.rewrite('xp').doit() == \
(Integer(1)/sqrt(Integer(2)*hbar*m*omega))*(I*Px + m*omega*X)
for i in range(ndim - 1):
assert a_rep[i,i + 1] == sqrt(i + 1)
def test_NumberOp():
assert Commutator(N, ad).doit() == ad
assert Commutator(N, a).doit() == Integer(-1)*a
assert Commutator(N, H).doit() == Integer(0)
assert qapply(N*k) == (k.n*k).expand()
assert N.rewrite('a').doit() == ad*a
assert N.rewrite('xp').doit() == (Integer(1)/(Integer(2)*m*hbar*omega))*(
Px**2 + (m*omega*X)**2) - Integer(1)/Integer(2)
assert N.rewrite('H').doit() == H/(hbar*omega) - Integer(1)/Integer(2)
for i in range(ndim):
assert N_rep[i,i] == i
assert N_rep == ad_rep_sympy*a_rep
def test_Hamiltonian():
assert Commutator(H, N).doit() == Integer(0)
assert qapply(H*k) == ((hbar*omega*(k.n + Integer(1)/Integer(2)))*k).expand()
assert H.rewrite('a').doit() == hbar*omega*(ad*a + Integer(1)/Integer(2))
assert H.rewrite('xp').doit() == \
(Integer(1)/(Integer(2)*m))*(Px**2 + (m*omega*X)**2)
assert H.rewrite('N').doit() == hbar*omega*(N + Integer(1)/Integer(2))
for i in range(ndim):
assert H_rep[i,i] == hbar*omega*(i + Integer(1)/Integer(2))
def test_SHOKet():
assert SHOKet('k').dual_class() == SHOBra
assert SHOBra('b').dual_class() == SHOKet
assert InnerProduct(b,k).doit() == KroneckerDelta(k.n, b.n)
assert k.hilbert_space == ComplexSpace(S.Infinity)
assert k3_rep[k3.n, 0] == Integer(1)
assert b3_rep[0, b3.n] == Integer(1)
|
1ab2405914151ff97c1081eb8f5bdeda3b71b247bbd88ae2437968f787eaad54 | from sympy.core.mul import Mul
from sympy.core.numbers import Integer
from sympy.core.symbol import Symbol
from sympy.utilities import numbered_symbols
from sympy.physics.quantum.gate import X, Y, Z, H, CNOT, CGate
from sympy.physics.quantum.identitysearch import bfs_identity_search
from sympy.physics.quantum.circuitutils import (kmp_table, find_subcircuit,
replace_subcircuit, convert_to_symbolic_indices,
convert_to_real_indices, random_reduce, random_insert,
flatten_ids)
from sympy.testing.pytest import slow
def create_gate_sequence(qubit=0):
gates = (X(qubit), Y(qubit), Z(qubit), H(qubit))
return gates
def test_kmp_table():
word = ('a', 'b', 'c', 'd', 'a', 'b', 'd')
expected_table = [-1, 0, 0, 0, 0, 1, 2]
assert expected_table == kmp_table(word)
word = ('P', 'A', 'R', 'T', 'I', 'C', 'I', 'P', 'A', 'T', 'E', ' ',
'I', 'N', ' ', 'P', 'A', 'R', 'A', 'C', 'H', 'U', 'T', 'E')
expected_table = [-1, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0,
0, 0, 0, 0, 1, 2, 3, 0, 0, 0, 0, 0]
assert expected_table == kmp_table(word)
x = X(0)
y = Y(0)
z = Z(0)
h = H(0)
word = (x, y, y, x, z)
expected_table = [-1, 0, 0, 0, 1]
assert expected_table == kmp_table(word)
word = (x, x, y, h, z)
expected_table = [-1, 0, 1, 0, 0]
assert expected_table == kmp_table(word)
def test_find_subcircuit():
x = X(0)
y = Y(0)
z = Z(0)
h = H(0)
x1 = X(1)
y1 = Y(1)
i0 = Symbol('i0')
x_i0 = X(i0)
y_i0 = Y(i0)
z_i0 = Z(i0)
h_i0 = H(i0)
circuit = (x, y, z)
assert find_subcircuit(circuit, (x,)) == 0
assert find_subcircuit(circuit, (x1,)) == -1
assert find_subcircuit(circuit, (y,)) == 1
assert find_subcircuit(circuit, (h,)) == -1
assert find_subcircuit(circuit, Mul(x, h)) == -1
assert find_subcircuit(circuit, Mul(x, y, z)) == 0
assert find_subcircuit(circuit, Mul(y, z)) == 1
assert find_subcircuit(Mul(*circuit), (x, y, z, h)) == -1
assert find_subcircuit(Mul(*circuit), (z, y, x)) == -1
assert find_subcircuit(circuit, (x,), start=2, end=1) == -1
circuit = (x, y, x, y, z)
assert find_subcircuit(Mul(*circuit), Mul(x, y, z)) == 2
assert find_subcircuit(circuit, (x,), start=1) == 2
assert find_subcircuit(circuit, (x, y), start=1, end=2) == -1
assert find_subcircuit(Mul(*circuit), (x, y), start=1, end=3) == -1
assert find_subcircuit(circuit, (x, y), start=1, end=4) == 2
assert find_subcircuit(circuit, (x, y), start=2, end=4) == 2
circuit = (x, y, z, x1, x, y, z, h, x, y, x1,
x, y, z, h, y1, h)
assert find_subcircuit(circuit, (x, y, z, h, y1)) == 11
circuit = (x, y, x_i0, y_i0, z_i0, z)
assert find_subcircuit(circuit, (x_i0, y_i0, z_i0)) == 2
circuit = (x_i0, y_i0, z_i0, x_i0, y_i0, h_i0)
subcircuit = (x_i0, y_i0, z_i0)
result = find_subcircuit(circuit, subcircuit)
assert result == 0
def test_replace_subcircuit():
x = X(0)
y = Y(0)
z = Z(0)
h = H(0)
cnot = CNOT(1, 0)
cgate_z = CGate((0,), Z(1))
# Standard cases
circuit = (z, y, x, x)
remove = (z, y, x)
assert replace_subcircuit(circuit, Mul(*remove)) == (x,)
assert replace_subcircuit(circuit, remove + (x,)) == ()
assert replace_subcircuit(circuit, remove, pos=1) == circuit
assert replace_subcircuit(circuit, remove, pos=0) == (x,)
assert replace_subcircuit(circuit, (x, x), pos=2) == (z, y)
assert replace_subcircuit(circuit, (h,)) == circuit
circuit = (x, y, x, y, z)
remove = (x, y, z)
assert replace_subcircuit(Mul(*circuit), Mul(*remove)) == (x, y)
remove = (x, y, x, y)
assert replace_subcircuit(circuit, remove) == (z,)
circuit = (x, h, cgate_z, h, cnot)
remove = (x, h, cgate_z)
assert replace_subcircuit(circuit, Mul(*remove), pos=-1) == (h, cnot)
assert replace_subcircuit(circuit, remove, pos=1) == circuit
remove = (h, h)
assert replace_subcircuit(circuit, remove) == circuit
remove = (h, cgate_z, h, cnot)
assert replace_subcircuit(circuit, remove) == (x,)
replace = (h, x)
actual = replace_subcircuit(circuit, remove,
replace=replace)
assert actual == (x, h, x)
circuit = (x, y, h, x, y, z)
remove = (x, y)
replace = (cnot, cgate_z)
actual = replace_subcircuit(circuit, remove,
replace=Mul(*replace))
assert actual == (cnot, cgate_z, h, x, y, z)
actual = replace_subcircuit(circuit, remove,
replace=replace, pos=1)
assert actual == (x, y, h, cnot, cgate_z, z)
def test_convert_to_symbolic_indices():
(x, y, z, h) = create_gate_sequence()
i0 = Symbol('i0')
exp_map = {i0: Integer(0)}
actual, act_map, sndx, gen = convert_to_symbolic_indices((x,))
assert actual == (X(i0),)
assert act_map == exp_map
expected = (X(i0), Y(i0), Z(i0), H(i0))
exp_map = {i0: Integer(0)}
actual, act_map, sndx, gen = convert_to_symbolic_indices((x, y, z, h))
assert actual == expected
assert exp_map == act_map
(x1, y1, z1, h1) = create_gate_sequence(1)
i1 = Symbol('i1')
expected = (X(i0), Y(i0), Z(i0), H(i0))
exp_map = {i0: Integer(1)}
actual, act_map, sndx, gen = convert_to_symbolic_indices((x1, y1, z1, h1))
assert actual == expected
assert act_map == exp_map
expected = (X(i0), Y(i0), Z(i0), H(i0), X(i1), Y(i1), Z(i1), H(i1))
exp_map = {i0: Integer(0), i1: Integer(1)}
actual, act_map, sndx, gen = convert_to_symbolic_indices((x, y, z, h,
x1, y1, z1, h1))
assert actual == expected
assert act_map == exp_map
exp_map = {i0: Integer(1), i1: Integer(0)}
actual, act_map, sndx, gen = convert_to_symbolic_indices(Mul(x1, y1,
z1, h1, x, y, z, h))
assert actual == expected
assert act_map == exp_map
expected = (X(i0), X(i1), Y(i0), Y(i1), Z(i0), Z(i1), H(i0), H(i1))
exp_map = {i0: Integer(0), i1: Integer(1)}
actual, act_map, sndx, gen = convert_to_symbolic_indices(Mul(x, x1,
y, y1, z, z1, h, h1))
assert actual == expected
assert act_map == exp_map
exp_map = {i0: Integer(1), i1: Integer(0)}
actual, act_map, sndx, gen = convert_to_symbolic_indices((x1, x, y1, y,
z1, z, h1, h))
assert actual == expected
assert act_map == exp_map
cnot_10 = CNOT(1, 0)
cnot_01 = CNOT(0, 1)
cgate_z_10 = CGate(1, Z(0))
cgate_z_01 = CGate(0, Z(1))
expected = (X(i0), X(i1), Y(i0), Y(i1), Z(i0), Z(i1),
H(i0), H(i1), CNOT(i1, i0), CNOT(i0, i1),
CGate(i1, Z(i0)), CGate(i0, Z(i1)))
exp_map = {i0: Integer(0), i1: Integer(1)}
args = (x, x1, y, y1, z, z1, h, h1, cnot_10, cnot_01,
cgate_z_10, cgate_z_01)
actual, act_map, sndx, gen = convert_to_symbolic_indices(args)
assert actual == expected
assert act_map == exp_map
args = (x1, x, y1, y, z1, z, h1, h, cnot_10, cnot_01,
cgate_z_10, cgate_z_01)
expected = (X(i0), X(i1), Y(i0), Y(i1), Z(i0), Z(i1),
H(i0), H(i1), CNOT(i0, i1), CNOT(i1, i0),
CGate(i0, Z(i1)), CGate(i1, Z(i0)))
exp_map = {i0: Integer(1), i1: Integer(0)}
actual, act_map, sndx, gen = convert_to_symbolic_indices(args)
assert actual == expected
assert act_map == exp_map
args = (cnot_10, h, cgate_z_01, h)
expected = (CNOT(i0, i1), H(i1), CGate(i1, Z(i0)), H(i1))
exp_map = {i0: Integer(1), i1: Integer(0)}
actual, act_map, sndx, gen = convert_to_symbolic_indices(args)
assert actual == expected
assert act_map == exp_map
args = (cnot_01, h1, cgate_z_10, h1)
exp_map = {i0: Integer(0), i1: Integer(1)}
actual, act_map, sndx, gen = convert_to_symbolic_indices(args)
assert actual == expected
assert act_map == exp_map
args = (cnot_10, h1, cgate_z_01, h1)
expected = (CNOT(i0, i1), H(i0), CGate(i1, Z(i0)), H(i0))
exp_map = {i0: Integer(1), i1: Integer(0)}
actual, act_map, sndx, gen = convert_to_symbolic_indices(args)
assert actual == expected
assert act_map == exp_map
i2 = Symbol('i2')
ccgate_z = CGate(0, CGate(1, Z(2)))
ccgate_x = CGate(1, CGate(2, X(0)))
args = (ccgate_z, ccgate_x)
expected = (CGate(i0, CGate(i1, Z(i2))), CGate(i1, CGate(i2, X(i0))))
exp_map = {i0: Integer(0), i1: Integer(1), i2: Integer(2)}
actual, act_map, sndx, gen = convert_to_symbolic_indices(args)
assert actual == expected
assert act_map == exp_map
ndx_map = {i0: Integer(0)}
index_gen = numbered_symbols(prefix='i', start=1)
actual, act_map, sndx, gen = convert_to_symbolic_indices(args,
qubit_map=ndx_map,
start=i0,
gen=index_gen)
assert actual == expected
assert act_map == exp_map
i3 = Symbol('i3')
cgate_x0_c321 = CGate((3, 2, 1), X(0))
exp_map = {i0: Integer(3), i1: Integer(2),
i2: Integer(1), i3: Integer(0)}
expected = (CGate((i0, i1, i2), X(i3)),)
args = (cgate_x0_c321,)
actual, act_map, sndx, gen = convert_to_symbolic_indices(args)
assert actual == expected
assert act_map == exp_map
def test_convert_to_real_indices():
i0 = Symbol('i0')
i1 = Symbol('i1')
(x, y, z, h) = create_gate_sequence()
x_i0 = X(i0)
y_i0 = Y(i0)
z_i0 = Z(i0)
qubit_map = {i0: 0}
args = (z_i0, y_i0, x_i0)
expected = (z, y, x)
actual = convert_to_real_indices(args, qubit_map)
assert actual == expected
cnot_10 = CNOT(1, 0)
cnot_01 = CNOT(0, 1)
cgate_z_10 = CGate(1, Z(0))
cgate_z_01 = CGate(0, Z(1))
cnot_i1_i0 = CNOT(i1, i0)
cnot_i0_i1 = CNOT(i0, i1)
cgate_z_i1_i0 = CGate(i1, Z(i0))
qubit_map = {i0: 0, i1: 1}
args = (cnot_i1_i0,)
expected = (cnot_10,)
actual = convert_to_real_indices(args, qubit_map)
assert actual == expected
args = (cgate_z_i1_i0,)
expected = (cgate_z_10,)
actual = convert_to_real_indices(args, qubit_map)
assert actual == expected
args = (cnot_i0_i1,)
expected = (cnot_01,)
actual = convert_to_real_indices(args, qubit_map)
assert actual == expected
qubit_map = {i0: 1, i1: 0}
args = (cgate_z_i1_i0,)
expected = (cgate_z_01,)
actual = convert_to_real_indices(args, qubit_map)
assert actual == expected
i2 = Symbol('i2')
ccgate_z = CGate(i0, CGate(i1, Z(i2)))
ccgate_x = CGate(i1, CGate(i2, X(i0)))
qubit_map = {i0: 0, i1: 1, i2: 2}
args = (ccgate_z, ccgate_x)
expected = (CGate(0, CGate(1, Z(2))), CGate(1, CGate(2, X(0))))
actual = convert_to_real_indices(Mul(*args), qubit_map)
assert actual == expected
qubit_map = {i0: 1, i2: 0, i1: 2}
args = (ccgate_x, ccgate_z)
expected = (CGate(2, CGate(0, X(1))), CGate(1, CGate(2, Z(0))))
actual = convert_to_real_indices(args, qubit_map)
assert actual == expected
@slow
def test_random_reduce():
x = X(0)
y = Y(0)
z = Z(0)
h = H(0)
cnot = CNOT(1, 0)
cgate_z = CGate((0,), Z(1))
gate_list = [x, y, z]
ids = list(bfs_identity_search(gate_list, 1, max_depth=4))
circuit = (x, y, h, z, cnot)
assert random_reduce(circuit, []) == circuit
assert random_reduce(circuit, ids) == circuit
seq = [2, 11, 9, 3, 5]
circuit = (x, y, z, x, y, h)
assert random_reduce(circuit, ids, seed=seq) == (x, y, h)
circuit = (x, x, y, y, z, z)
assert random_reduce(circuit, ids, seed=seq) == (x, x, y, y)
seq = [14, 13, 0]
assert random_reduce(circuit, ids, seed=seq) == (y, y, z, z)
gate_list = [x, y, z, h, cnot, cgate_z]
ids = list(bfs_identity_search(gate_list, 2, max_depth=4))
seq = [25]
circuit = (x, y, z, y, h, y, h, cgate_z, h, cnot)
expected = (x, y, z, cgate_z, h, cnot)
assert random_reduce(circuit, ids, seed=seq) == expected
circuit = Mul(*circuit)
assert random_reduce(circuit, ids, seed=seq) == expected
@slow
def test_random_insert():
x = X(0)
y = Y(0)
z = Z(0)
h = H(0)
cnot = CNOT(1, 0)
cgate_z = CGate((0,), Z(1))
choices = [(x, x)]
circuit = (y, y)
loc, choice = 0, 0
actual = random_insert(circuit, choices, seed=[loc, choice])
assert actual == (x, x, y, y)
circuit = (x, y, z, h)
choices = [(h, h), (x, y, z)]
expected = (x, x, y, z, y, z, h)
loc, choice = 1, 1
actual = random_insert(circuit, choices, seed=[loc, choice])
assert actual == expected
gate_list = [x, y, z, h, cnot, cgate_z]
ids = list(bfs_identity_search(gate_list, 2, max_depth=4))
eq_ids = flatten_ids(ids)
circuit = (x, y, h, cnot, cgate_z)
expected = (x, z, x, z, x, y, h, cnot, cgate_z)
loc, choice = 1, 30
actual = random_insert(circuit, eq_ids, seed=[loc, choice])
assert actual == expected
circuit = Mul(*circuit)
actual = random_insert(circuit, eq_ids, seed=[loc, choice])
assert actual == expected
|
5237ce7704733571cad0032111a238df578c3635542bb825aa21b13972440b9d | from sympy.core.add import Add
from sympy.core.function import diff
from sympy.core.mul import Mul
from sympy.core.numbers import (I, Integer, Rational, oo, pi)
from sympy.core.power import Pow
from sympy.core.singleton import S
from sympy.core.symbol import (Symbol, symbols)
from sympy.core.sympify import sympify
from sympy.functions.elementary.complexes import conjugate
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import sin
from sympy.testing.pytest import raises
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum.qexpr import QExpr
from sympy.physics.quantum.state import (
Ket, Bra, TimeDepKet, TimeDepBra,
KetBase, BraBase, StateBase, Wavefunction,
OrthogonalKet, OrthogonalBra
)
from sympy.physics.quantum.hilbert import HilbertSpace
x, y, t = symbols('x,y,t')
class CustomKet(Ket):
@classmethod
def default_args(self):
return ("test",)
class CustomKetMultipleLabels(Ket):
@classmethod
def default_args(self):
return ("r", "theta", "phi")
class CustomTimeDepKet(TimeDepKet):
@classmethod
def default_args(self):
return ("test", "t")
class CustomTimeDepKetMultipleLabels(TimeDepKet):
@classmethod
def default_args(self):
return ("r", "theta", "phi", "t")
def test_ket():
k = Ket('0')
assert isinstance(k, Ket)
assert isinstance(k, KetBase)
assert isinstance(k, StateBase)
assert isinstance(k, QExpr)
assert k.label == (Symbol('0'),)
assert k.hilbert_space == HilbertSpace()
assert k.is_commutative is False
# Make sure this doesn't get converted to the number pi.
k = Ket('pi')
assert k.label == (Symbol('pi'),)
k = Ket(x, y)
assert k.label == (x, y)
assert k.hilbert_space == HilbertSpace()
assert k.is_commutative is False
assert k.dual_class() == Bra
assert k.dual == Bra(x, y)
assert k.subs(x, y) == Ket(y, y)
k = CustomKet()
assert k == CustomKet("test")
k = CustomKetMultipleLabels()
assert k == CustomKetMultipleLabels("r", "theta", "phi")
assert Ket() == Ket('psi')
def test_bra():
b = Bra('0')
assert isinstance(b, Bra)
assert isinstance(b, BraBase)
assert isinstance(b, StateBase)
assert isinstance(b, QExpr)
assert b.label == (Symbol('0'),)
assert b.hilbert_space == HilbertSpace()
assert b.is_commutative is False
# Make sure this doesn't get converted to the number pi.
b = Bra('pi')
assert b.label == (Symbol('pi'),)
b = Bra(x, y)
assert b.label == (x, y)
assert b.hilbert_space == HilbertSpace()
assert b.is_commutative is False
assert b.dual_class() == Ket
assert b.dual == Ket(x, y)
assert b.subs(x, y) == Bra(y, y)
assert Bra() == Bra('psi')
def test_ops():
k0 = Ket(0)
k1 = Ket(1)
k = 2*I*k0 - (x/sqrt(2))*k1
assert k == Add(Mul(2, I, k0),
Mul(Rational(-1, 2), x, Pow(2, S.Half), k1))
def test_time_dep_ket():
k = TimeDepKet(0, t)
assert isinstance(k, TimeDepKet)
assert isinstance(k, KetBase)
assert isinstance(k, StateBase)
assert isinstance(k, QExpr)
assert k.label == (Integer(0),)
assert k.args == (Integer(0), t)
assert k.time == t
assert k.dual_class() == TimeDepBra
assert k.dual == TimeDepBra(0, t)
assert k.subs(t, 2) == TimeDepKet(0, 2)
k = TimeDepKet(x, 0.5)
assert k.label == (x,)
assert k.args == (x, sympify(0.5))
k = CustomTimeDepKet()
assert k.label == (Symbol("test"),)
assert k.time == Symbol("t")
assert k == CustomTimeDepKet("test", "t")
k = CustomTimeDepKetMultipleLabels()
assert k.label == (Symbol("r"), Symbol("theta"), Symbol("phi"))
assert k.time == Symbol("t")
assert k == CustomTimeDepKetMultipleLabels("r", "theta", "phi", "t")
assert TimeDepKet() == TimeDepKet("psi", "t")
def test_time_dep_bra():
b = TimeDepBra(0, t)
assert isinstance(b, TimeDepBra)
assert isinstance(b, BraBase)
assert isinstance(b, StateBase)
assert isinstance(b, QExpr)
assert b.label == (Integer(0),)
assert b.args == (Integer(0), t)
assert b.time == t
assert b.dual_class() == TimeDepKet
assert b.dual == TimeDepKet(0, t)
k = TimeDepBra(x, 0.5)
assert k.label == (x,)
assert k.args == (x, sympify(0.5))
assert TimeDepBra() == TimeDepBra("psi", "t")
def test_bra_ket_dagger():
x = symbols('x', complex=True)
k = Ket('k')
b = Bra('b')
assert Dagger(k) == Bra('k')
assert Dagger(b) == Ket('b')
assert Dagger(k).is_commutative is False
k2 = Ket('k2')
e = 2*I*k + x*k2
assert Dagger(e) == conjugate(x)*Dagger(k2) - 2*I*Dagger(k)
def test_wavefunction():
x, y = symbols('x y', real=True)
L = symbols('L', positive=True)
n = symbols('n', integer=True, positive=True)
f = Wavefunction(x**2, x)
p = f.prob()
lims = f.limits
assert f.is_normalized is False
assert f.norm is oo
assert f(10) == 100
assert p(10) == 10000
assert lims[x] == (-oo, oo)
assert diff(f, x) == Wavefunction(2*x, x)
raises(NotImplementedError, lambda: f.normalize())
assert conjugate(f) == Wavefunction(conjugate(f.expr), x)
assert conjugate(f) == Dagger(f)
g = Wavefunction(x**2*y + y**2*x, (x, 0, 1), (y, 0, 2))
lims_g = g.limits
assert lims_g[x] == (0, 1)
assert lims_g[y] == (0, 2)
assert g.is_normalized is False
assert g.norm == sqrt(42)/3
assert g(2, 4) == 0
assert g(1, 1) == 2
assert diff(diff(g, x), y) == Wavefunction(2*x + 2*y, (x, 0, 1), (y, 0, 2))
assert conjugate(g) == Wavefunction(conjugate(g.expr), *g.args[1:])
assert conjugate(g) == Dagger(g)
h = Wavefunction(sqrt(5)*x**2, (x, 0, 1))
assert h.is_normalized is True
assert h.normalize() == h
assert conjugate(h) == Wavefunction(conjugate(h.expr), (x, 0, 1))
assert conjugate(h) == Dagger(h)
piab = Wavefunction(sin(n*pi*x/L), (x, 0, L))
assert piab.norm == sqrt(L/2)
assert piab(L + 1) == 0
assert piab(0.5) == sin(0.5*n*pi/L)
assert piab(0.5, n=1, L=1) == sin(0.5*pi)
assert piab.normalize() == \
Wavefunction(sqrt(2)/sqrt(L)*sin(n*pi*x/L), (x, 0, L))
assert conjugate(piab) == Wavefunction(conjugate(piab.expr), (x, 0, L))
assert conjugate(piab) == Dagger(piab)
k = Wavefunction(x**2, 'x')
assert type(k.variables[0]) == Symbol
def test_orthogonal_states():
braket = OrthogonalBra(x) * OrthogonalKet(x)
assert braket.doit() == 1
braket = OrthogonalBra(x) * OrthogonalKet(x+1)
assert braket.doit() == 0
braket = OrthogonalBra(x) * OrthogonalKet(y)
assert braket.doit() == braket
|
cd6997a22d5c3c54365ce75a02f6ea4cde047b13df7c6dd97a0d21d690d14ad4 | from sympy.core.function import expand_mul
from sympy.core.numbers import pi
from sympy.core.singleton import S
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.matrices.dense import Matrix
from sympy.core.backend import _simplify_matrix
from sympy.core.symbol import symbols
from sympy.physics.mechanics import dynamicsymbols, Body, PinJoint, PrismaticJoint
from sympy.physics.mechanics.joint import Joint
from sympy.physics.vector import Vector, ReferenceFrame
from sympy.testing.pytest import raises
t = dynamicsymbols._t # type: ignore
def _generate_body():
N = ReferenceFrame('N')
A = ReferenceFrame('A')
P = Body('P', frame=N)
C = Body('C', frame=A)
return N, A, P, C
def test_Joint():
parent = Body('parent')
child = Body('child')
raises(TypeError, lambda: Joint('J', parent, child))
def test_pinjoint():
P = Body('P')
C = Body('C')
l, m = symbols('l m')
theta, omega = dynamicsymbols('theta_J, omega_J')
Pj = PinJoint('J', P, C)
assert Pj.name == 'J'
assert Pj.parent == P
assert Pj.child == C
assert Pj.coordinates == [theta]
assert Pj.speeds == [omega]
assert Pj.kdes == [omega - theta.diff(t)]
assert Pj.parent_axis == P.frame.x
assert Pj.child_point.pos_from(C.masscenter) == Vector(0)
assert Pj.parent_point.pos_from(P.masscenter) == Vector(0)
assert Pj.parent_point.pos_from(Pj._child_point) == Vector(0)
assert C.masscenter.pos_from(P.masscenter) == Vector(0)
assert Pj.__str__() == 'PinJoint: J parent: P child: C'
P1 = Body('P1')
C1 = Body('C1')
J1 = PinJoint('J1', P1, C1, parent_joint_pos=l*P1.frame.x,
child_joint_pos=m*C1.frame.y, parent_axis=P1.frame.z)
assert J1._parent_axis == P1.frame.z
assert J1._child_point.pos_from(C1.masscenter) == m * C1.frame.y
assert J1._parent_point.pos_from(P1.masscenter) == l * P1.frame.x
assert J1._parent_point.pos_from(J1._child_point) == Vector(0)
assert (P1.masscenter.pos_from(C1.masscenter) ==
-l*P1.frame.x + m*C1.frame.y)
def test_pin_joint_double_pendulum():
q1, q2 = dynamicsymbols('q1 q2')
u1, u2 = dynamicsymbols('u1 u2')
m, l = symbols('m l')
N = ReferenceFrame('N')
A = ReferenceFrame('A')
B = ReferenceFrame('B')
C = Body('C', frame=N) # ceiling
PartP = Body('P', frame=A, mass=m)
PartR = Body('R', frame=B, mass=m)
J1 = PinJoint('J1', C, PartP, speeds=u1, coordinates=q1,
child_joint_pos=-l*A.x, parent_axis=C.frame.z,
child_axis=PartP.frame.z)
J2 = PinJoint('J2', PartP, PartR, speeds=u2, coordinates=q2,
child_joint_pos=-l*B.x, parent_axis=PartP.frame.z,
child_axis=PartR.frame.z)
# Check orientation
assert N.dcm(A) == Matrix([[cos(q1), -sin(q1), 0],
[sin(q1), cos(q1), 0], [0, 0, 1]])
assert A.dcm(B) == Matrix([[cos(q2), -sin(q2), 0],
[sin(q2), cos(q2), 0], [0, 0, 1]])
assert _simplify_matrix(N.dcm(B)) == Matrix([[cos(q1 + q2), -sin(q1 + q2), 0],
[sin(q1 + q2), cos(q1 + q2), 0],
[0, 0, 1]])
# Check Angular Velocity
assert A.ang_vel_in(N) == u1 * N.z
assert B.ang_vel_in(A) == u2 * A.z
assert B.ang_vel_in(N) == u1 * N.z + u2 * A.z
# Check kde
assert J1.kdes == [u1 - q1.diff(t)]
assert J2.kdes == [u2 - q2.diff(t)]
# Check Linear Velocity
assert PartP.masscenter.vel(N) == l*u1*A.y
assert PartR.masscenter.vel(A) == l*u2*B.y
assert PartR.masscenter.vel(N) == l*u1*A.y + l*(u1 + u2)*B.y
def test_pin_joint_chaos_pendulum():
mA, mB, lA, lB, h = symbols('mA, mB, lA, lB, h')
theta, phi, omega, alpha = dynamicsymbols('theta phi omega alpha')
N = ReferenceFrame('N')
A = ReferenceFrame('A')
B = ReferenceFrame('B')
lA = (lB - h / 2) / 2
lC = (lB/2 + h/4)
rod = Body('rod', frame=A, mass=mA)
plate = Body('plate', mass=mB, frame=B)
C = Body('C', frame=N)
J1 = PinJoint('J1', C, rod, coordinates=theta, speeds=omega,
child_joint_pos=lA*A.z, parent_axis=N.y, child_axis=A.y)
J2 = PinJoint('J2', rod, plate, coordinates=phi, speeds=alpha,
parent_joint_pos=lC*A.z, parent_axis=A.z, child_axis=B.z)
# Check orientation
assert A.dcm(N) == Matrix([[cos(theta), 0, -sin(theta)],
[0, 1, 0],
[sin(theta), 0, cos(theta)]])
assert A.dcm(B) == Matrix([[cos(phi), -sin(phi), 0],
[sin(phi), cos(phi), 0],
[0, 0, 1]])
assert B.dcm(N) == Matrix([
[cos(phi)*cos(theta), sin(phi), -sin(theta)*cos(phi)],
[-sin(phi)*cos(theta), cos(phi), sin(phi)*sin(theta)],
[sin(theta), 0, cos(theta)]])
# Check Angular Velocity
assert A.ang_vel_in(N) == omega*N.y
assert A.ang_vel_in(B) == -alpha*A.z
assert N.ang_vel_in(B) == -omega*N.y - alpha*A.z
# Check kde
assert J1.kdes == [omega - theta.diff(t)]
assert J2.kdes == [alpha - phi.diff(t)]
# Check pos of masscenters
assert C.masscenter.pos_from(rod.masscenter) == lA*A.z
assert rod.masscenter.pos_from(plate.masscenter) == - lC * A.z
# Check Linear Velocities
assert rod.masscenter.vel(N) == (h/4 - lB/2)*omega*A.x
assert plate.masscenter.vel(N) == ((h/4 - lB/2)*omega +
(h/4 + lB/2)*omega)*A.x
def test_pinjoint_arbitrary_axis():
theta, omega = dynamicsymbols('theta_J, omega_J')
# When the bodies are attached though masscenters but axess are opposite.
N, A, P, C = _generate_body()
PinJoint('J', P, C, child_axis=-A.x)
assert (-A.x).angle_between(N.x) == 0
assert -A.x.express(N) == N.x
assert A.dcm(N) == Matrix([[-1, 0, 0],
[0, -cos(theta), -sin(theta)],
[0, -sin(theta), cos(theta)]])
assert A.ang_vel_in(N) == omega*N.x
assert A.ang_vel_in(N).magnitude() == sqrt(omega**2)
assert C.masscenter.pos_from(P.masscenter) == 0
assert C.masscenter.pos_from(P.masscenter).express(N).simplify() == 0
assert C.masscenter.vel(N) == 0
# When axes are different and parent joint is at masscenter but child joint
# is at a unit vector from child masscenter.
N, A, P, C = _generate_body()
PinJoint('J', P, C, child_axis=A.y, child_joint_pos=A.x)
assert A.y.angle_between(N.x) == 0 # Axis are aligned
assert A.y.express(N) == N.x
assert A.dcm(N) == Matrix([[0, -cos(theta), -sin(theta)],
[1, 0, 0],
[0, -sin(theta), cos(theta)]])
assert A.ang_vel_in(N) == omega*N.x
assert A.ang_vel_in(N).express(A) == omega * A.y
assert A.ang_vel_in(N).magnitude() == sqrt(omega**2)
angle = A.ang_vel_in(N).angle_between(A.y)
assert angle.xreplace({omega: 1}) == 0
assert C.masscenter.vel(N) == omega*A.z
assert C.masscenter.pos_from(P.masscenter) == -A.x
assert (C.masscenter.pos_from(P.masscenter).express(N).simplify() ==
cos(theta)*N.y + sin(theta)*N.z)
assert C.masscenter.vel(N).angle_between(A.x) == pi/2
# Similar to previous case but wrt parent body
N, A, P, C = _generate_body()
PinJoint('J', P, C, parent_axis=N.y, parent_joint_pos=N.x)
assert N.y.angle_between(A.x) == 0 # Axis are aligned
assert N.y.express(A) == A.x
assert A.dcm(N) == Matrix([[0, 1, 0],
[-cos(theta), 0, sin(theta)],
[sin(theta), 0, cos(theta)]])
assert A.ang_vel_in(N) == omega*N.y
assert A.ang_vel_in(N).express(A) == omega*A.x
assert A.ang_vel_in(N).magnitude() == sqrt(omega**2)
angle = A.ang_vel_in(N).angle_between(A.x)
assert angle.xreplace({omega: 1}) == 0
assert C.masscenter.vel(N).simplify() == - omega*N.z
assert C.masscenter.pos_from(P.masscenter) == N.x
# Both joint pos id defined but different axes
N, A, P, C = _generate_body()
PinJoint('J', P, C, parent_joint_pos=N.x, child_joint_pos=A.x,
child_axis=A.x+A.y)
assert expand_mul(N.x.angle_between(A.x + A.y)) == 0 # Axis are aligned
assert (A.x + A.y).express(N).simplify() == sqrt(2)*N.x
assert _simplify_matrix(A.dcm(N)) == Matrix([
[sqrt(2)/2, -sqrt(2)*cos(theta)/2, -sqrt(2)*sin(theta)/2],
[sqrt(2)/2, sqrt(2)*cos(theta)/2, sqrt(2)*sin(theta)/2],
[0, -sin(theta), cos(theta)]])
assert A.ang_vel_in(N) == omega*N.x
assert (A.ang_vel_in(N).express(A).simplify() ==
(omega*A.x + omega*A.y)/sqrt(2))
assert A.ang_vel_in(N).magnitude() == sqrt(omega**2)
angle = A.ang_vel_in(N).angle_between(A.x + A.y)
assert angle.xreplace({omega: 1}) == 0
assert C.masscenter.vel(N).simplify() == (omega * A.z)/sqrt(2)
assert C.masscenter.pos_from(P.masscenter) == N.x - A.x
assert (C.masscenter.pos_from(P.masscenter).express(N).simplify() ==
(1 - sqrt(2)/2)*N.x + sqrt(2)*cos(theta)/2*N.y +
sqrt(2)*sin(theta)/2*N.z)
assert (C.masscenter.vel(N).express(N).simplify() ==
-sqrt(2)*omega*sin(theta)/2*N.y + sqrt(2)*omega*cos(theta)/2*N.z)
assert C.masscenter.vel(N).angle_between(A.x) == pi/2
N, A, P, C = _generate_body()
PinJoint('J', P, C, parent_joint_pos=N.x, child_joint_pos=A.x,
child_axis=A.x+A.y-A.z)
assert expand_mul(N.x.angle_between(A.x + A.y - A.z)) == 0 # Axis aligned
assert (A.x + A.y - A.z).express(N).simplify() == sqrt(3)*N.x
assert _simplify_matrix(A.dcm(N)) == Matrix([
[sqrt(3)/3, -sqrt(6)*sin(theta + pi/4)/3,
sqrt(6)*cos(theta + pi/4)/3],
[sqrt(3)/3, sqrt(6)*cos(theta + pi/12)/3,
sqrt(6)*sin(theta + pi/12)/3],
[-sqrt(3)/3, sqrt(6)*cos(theta + 5*pi/12)/3,
sqrt(6)*sin(theta + 5*pi/12)/3]])
assert A.ang_vel_in(N) == omega*N.x
assert A.ang_vel_in(N).express(A).simplify() == (omega*A.x + omega*A.y -
omega*A.z)/sqrt(3)
assert A.ang_vel_in(N).magnitude() == sqrt(omega**2)
angle = A.ang_vel_in(N).angle_between(A.x + A.y-A.z)
assert angle.xreplace({omega: 1}) == 0
assert C.masscenter.vel(N).simplify() == (omega*A.y + omega*A.z)/sqrt(3)
assert C.masscenter.pos_from(P.masscenter) == N.x - A.x
assert (C.masscenter.pos_from(P.masscenter).express(N).simplify() ==
(1 - sqrt(3)/3)*N.x + sqrt(6)*sin(theta + pi/4)/3*N.y -
sqrt(6)*cos(theta + pi/4)/3*N.z)
assert (C.masscenter.vel(N).express(N).simplify() ==
sqrt(6)*omega*cos(theta + pi/4)/3*N.y +
sqrt(6)*omega*sin(theta + pi/4)/3*N.z)
assert C.masscenter.vel(N).angle_between(A.x) == pi/2
N, A, P, C = _generate_body()
m, n = symbols('m n')
PinJoint('J', P, C, parent_joint_pos=m*N.x, child_joint_pos=n*A.x,
child_axis=A.x+A.y-A.z, parent_axis=N.x-N.y+N.z)
angle = (N.x-N.y+N.z).angle_between(A.x+A.y-A.z)
assert expand_mul(angle) == 0 # Axis are aligned
assert ((A.x-A.y+A.z).express(N).simplify() ==
(-4*cos(theta)/3 - S(1)/3)*N.x + (S(1)/3 - 4*sin(theta + pi/6)/3)*N.y +
(4*cos(theta + pi/3)/3 - S(1)/3)*N.z)
assert _simplify_matrix(A.dcm(N)) == Matrix([
[S(1)/3 - 2*cos(theta)/3, -2*sin(theta + pi/6)/3 - S(1)/3,
2*cos(theta + pi/3)/3 + S(1)/3],
[2*cos(theta + pi/3)/3 + S(1)/3, 2*cos(theta)/3 - S(1)/3,
2*sin(theta + pi/6)/3 + S(1)/3],
[-2*sin(theta + pi/6)/3 - S(1)/3, 2*cos(theta + pi/3)/3 + S(1)/3,
2*cos(theta)/3 - S(1)/3]])
assert A.ang_vel_in(N) == (omega*N.x - omega*N.y + omega*N.z)/sqrt(3)
assert A.ang_vel_in(N).express(A).simplify() == (omega*A.x + omega*A.y -
omega*A.z)/sqrt(3)
assert A.ang_vel_in(N).magnitude() == sqrt(omega**2)
angle = A.ang_vel_in(N).angle_between(A.x+A.y-A.z)
assert angle.xreplace({omega: 1}) == 0
assert (C.masscenter.vel(N).simplify() ==
(m*omega*N.y + m*omega*N.z + n*omega*A.y + n*omega*A.z)/sqrt(3))
assert C.masscenter.pos_from(P.masscenter) == m*N.x - n*A.x
assert (C.masscenter.pos_from(P.masscenter).express(N).simplify() ==
(m + n*(2*cos(theta) - 1)/3)*N.x + n*(2*sin(theta + pi/6) +
1)/3*N.y - n*(2*cos(theta + pi/3) + 1)/3*N.z)
assert (C.masscenter.vel(N).express(N).simplify() ==
-2*n*omega*sin(theta)/3*N.x + (sqrt(3)*m +
2*n*cos(theta + pi/6))*omega/3*N.y
+ (sqrt(3)*m + 2*n*sin(theta + pi/3))*omega/3*N.z)
assert expand_mul(C.masscenter.vel(N).angle_between(m*N.x - n*A.x)) == pi/2
def test_pinjoint_pi():
_, _, P, C = _generate_body()
J = PinJoint('J', P, C, child_axis=-C.frame.x)
assert J._generate_vector() == P.frame.z
_, _, P, C = _generate_body()
J = PinJoint('J', P, C, parent_axis=P.frame.y, child_axis=-C.frame.y)
assert J._generate_vector() == P.frame.x
_, _, P, C = _generate_body()
J = PinJoint('J', P, C, parent_axis=P.frame.z, child_axis=-C.frame.z)
assert J._generate_vector() == P.frame.y
_, _, P, C = _generate_body()
J = PinJoint('J', P, C, parent_axis=P.frame.x+P.frame.y, child_axis=-C.frame.y-C.frame.x)
assert J._generate_vector() == P.frame.z
_, _, P, C = _generate_body()
J = PinJoint('J', P, C, parent_axis=P.frame.y+P.frame.z, child_axis=-C.frame.y-C.frame.z)
assert J._generate_vector() == P.frame.x
_, _, P, C = _generate_body()
J = PinJoint('J', P, C, parent_axis=P.frame.x+P.frame.z, child_axis=-C.frame.z-C.frame.x)
assert J._generate_vector() == P.frame.y
_, _, P, C = _generate_body()
J = PinJoint('J', P, C, parent_axis=P.frame.x+P.frame.y+P.frame.z,
child_axis=-C.frame.x-C.frame.y-C.frame.z)
assert J._generate_vector() == P.frame.y - P.frame.z
def test_slidingjoint():
_, _, P, C = _generate_body()
x, v = dynamicsymbols('x_S, v_S')
S = PrismaticJoint('S', P, C)
assert S.name == 'S'
assert S.parent == P
assert S.child == C
assert S.coordinates == [x]
assert S.speeds == [v]
assert S.kdes == [v - x.diff(t)]
assert S.parent_axis == P.frame.x
assert S.child_axis == C.frame.x
assert S.child_point.pos_from(C.masscenter) == Vector(0)
assert S.parent_point.pos_from(P.masscenter) == Vector(0)
assert S.parent_point.pos_from(S.child_point) == - x * P.frame.x
assert P.masscenter.pos_from(C.masscenter) == - x * P.frame.x
assert C.masscenter.vel(P.frame) == v * P.frame.x
assert P.ang_vel_in(C) == 0
assert C.ang_vel_in(P) == 0
assert S.__str__() == 'PrismaticJoint: S parent: P child: C'
N, A, P, C = _generate_body()
l, m = symbols('l m')
S = PrismaticJoint('S', P, C, parent_joint_pos= l * P.frame.x,
child_joint_pos= m * C.frame.y, parent_axis = P.frame.z)
assert S.parent_axis == P.frame.z
assert S.child_point.pos_from(C.masscenter) == m * C.frame.y
assert S.parent_point.pos_from(P.masscenter) == l * P.frame.x
assert S.parent_point.pos_from(S.child_point) == - x * P.frame.z
assert P.masscenter.pos_from(C.masscenter) == - l*N.x - x*N.z + m*A.y
assert C.masscenter.vel(P.frame) == v * P.frame.z
assert C.ang_vel_in(P) == 0
assert P.ang_vel_in(C) == 0
_, _, P, C = _generate_body()
S = PrismaticJoint('S', P, C, parent_joint_pos= l * P.frame.z,
child_joint_pos= m * C.frame.x, parent_axis = P.frame.z)
assert S.parent_axis == P.frame.z
assert S.child_point.pos_from(C.masscenter) == m * C.frame.x
assert S.parent_point.pos_from(P.masscenter) == l * P.frame.z
assert S.parent_point.pos_from(S.child_point) == - x * P.frame.z
assert P.masscenter.pos_from(C.masscenter) == (-l - x)*P.frame.z + m*C.frame.x
assert C.masscenter.vel(P.frame) == v * P.frame.z
assert C.ang_vel_in(P) == 0
assert P.ang_vel_in(C) == 0
def test_slidingjoint_arbitrary_axis():
x, v = dynamicsymbols('x_S, v_S')
N, A, P, C = _generate_body()
PrismaticJoint('S', P, C, child_axis=-A.x)
assert (-A.x).angle_between(N.x) == 0
assert -A.x.express(N) == N.x
assert A.dcm(N) == Matrix([[-1, 0, 0], [0, -1, 0], [0, 0, 1]])
assert C.masscenter.pos_from(P.masscenter) == x * N.x
assert C.masscenter.pos_from(P.masscenter).express(A).simplify() == -x * A.x
assert C.masscenter.vel(N) == v * N.x
assert C.masscenter.vel(N).express(A) == -v * A.x
assert A.ang_vel_in(N) == 0
assert N.ang_vel_in(A) == 0
#When axes are different and parent joint is at masscenter but child joint is at a unit vector from
#child masscenter.
N, A, P, C = _generate_body()
PrismaticJoint('S', P, C, child_axis=A.y, child_joint_pos=A.x)
assert A.y.angle_between(N.x) == 0 #Axis are aligned
assert A.y.express(N) == N.x
assert A.dcm(N) == Matrix([[0, -1, 0], [1, 0, 0], [0, 0, 1]])
assert C.masscenter.vel(N) == v * N.x
assert C.masscenter.vel(N).express(A) == v * A.y
assert C.masscenter.pos_from(P.masscenter) == x*N.x - A.x
assert C.masscenter.pos_from(P.masscenter).express(N).simplify() == x*N.x + N.y
assert A.ang_vel_in(N) == 0
assert N.ang_vel_in(A) == 0
#Similar to previous case but wrt parent body
N, A, P, C = _generate_body()
PrismaticJoint('S', P, C, parent_axis=N.y, parent_joint_pos=N.x)
assert N.y.angle_between(A.x) == 0 #Axis are aligned
assert N.y.express(A) == A.x
assert A.dcm(N) == Matrix([[0, 1, 0], [-1, 0, 0], [0, 0, 1]])
assert C.masscenter.vel(N) == v * N.y
assert C.masscenter.vel(N).express(A) == v * A.x
assert C.masscenter.pos_from(P.masscenter) == N.x + x*N.y
assert A.ang_vel_in(N) == 0
assert N.ang_vel_in(A) == 0
#Both joint pos is defined but different axes
N, A, P, C = _generate_body()
PrismaticJoint('S', P, C, parent_joint_pos=N.x, child_joint_pos=A.x, child_axis=A.x+A.y)
assert N.x.angle_between(A.x + A.y) == 0 #Axis are aligned
assert (A.x + A.y).express(N) == sqrt(2)*N.x
assert A.dcm(N) == Matrix([[sqrt(2)/2, -sqrt(2)/2, 0], [sqrt(2)/2, sqrt(2)/2, 0], [0, 0, 1]])
assert C.masscenter.pos_from(P.masscenter) == (x + 1)*N.x - A.x
assert C.masscenter.pos_from(P.masscenter).express(N) == (x - sqrt(2)/2 + 1)*N.x + sqrt(2)/2*N.y
assert C.masscenter.vel(N).express(A) == v * (A.x + A.y)/sqrt(2)
assert C.masscenter.vel(N) == v*N.x
assert A.ang_vel_in(N) == 0
assert N.ang_vel_in(A) == 0
N, A, P, C = _generate_body()
PrismaticJoint('S', P, C, parent_joint_pos=N.x, child_joint_pos=A.x, child_axis=A.x+A.y-A.z)
assert N.x.angle_between(A.x + A.y - A.z) == 0 #Axis are aligned
assert (A.x + A.y - A.z).express(N) == sqrt(3)*N.x
assert _simplify_matrix(A.dcm(N)) == Matrix([[sqrt(3)/3, -sqrt(3)/3, sqrt(3)/3],
[sqrt(3)/3, sqrt(3)/6 + S(1)/2, S(1)/2 - sqrt(3)/6],
[-sqrt(3)/3, S(1)/2 - sqrt(3)/6, sqrt(3)/6 + S(1)/2]])
assert C.masscenter.pos_from(P.masscenter) == (x + 1)*N.x - A.x
assert C.masscenter.pos_from(P.masscenter).express(N) == \
(x - sqrt(3)/3 + 1)*N.x + sqrt(3)/3*N.y - sqrt(3)/3*N.z
assert C.masscenter.vel(N) == v*N.x
assert C.masscenter.vel(N).express(A) == sqrt(3)*v/3*A.x + sqrt(3)*v/3*A.y - sqrt(3)*v/3*A.z
assert A.ang_vel_in(N) == 0
assert N.ang_vel_in(A) == 0
N, A, P, C = _generate_body()
m, n = symbols('m n')
PrismaticJoint('S', P, C, parent_joint_pos=m*N.x, child_joint_pos=n*A.x,
child_axis=A.x+A.y-A.z, parent_axis=N.x-N.y+N.z)
assert (N.x-N.y+N.z).angle_between(A.x+A.y-A.z) == 0 #Axis are aligned
assert (A.x+A.y-A.z).express(N) == N.x - N.y + N.z
assert _simplify_matrix(A.dcm(N)) == Matrix([[-S(1)/3, -S(2)/3, S(2)/3],
[S(2)/3, S(1)/3, S(2)/3],
[-S(2)/3, S(2)/3, S(1)/3]])
assert C.masscenter.pos_from(P.masscenter) == \
(m + sqrt(3)*x/3)*N.x - sqrt(3)*x/3*N.y + sqrt(3)*x/3*N.z - n*A.x
assert C.masscenter.pos_from(P.masscenter).express(N) == \
(m + n/3 + sqrt(3)*x/3)*N.x + (2*n/3 - sqrt(3)*x/3)*N.y + (-2*n/3 + sqrt(3)*x/3)*N.z
assert C.masscenter.vel(N) == sqrt(3)*v/3*N.x - sqrt(3)*v/3*N.y + sqrt(3)*v/3*N.z
assert C.masscenter.vel(N).express(A) == sqrt(3)*v/3*A.x + sqrt(3)*v/3*A.y - sqrt(3)*v/3*A.z
assert A.ang_vel_in(N) == 0
assert N.ang_vel_in(A) == 0
|
658e647a922ced763a4ebfab3ada6235fff9211a50ea2657f6fe69b35ff2aa3d | from sympy.core.symbol import symbols
from sympy.physics.mechanics import Point, Particle, ReferenceFrame, inertia
from sympy.testing.pytest import raises
def test_particle():
m, m2, v1, v2, v3, r, g, h = symbols('m m2 v1 v2 v3 r g h')
P = Point('P')
P2 = Point('P2')
p = Particle('pa', P, m)
assert p.__str__() == 'pa'
assert p.mass == m
assert p.point == P
# Test the mass setter
p.mass = m2
assert p.mass == m2
# Test the point setter
p.point = P2
assert p.point == P2
# Test the linear momentum function
N = ReferenceFrame('N')
O = Point('O')
P2.set_pos(O, r * N.y)
P2.set_vel(N, v1 * N.x)
raises(TypeError, lambda: Particle(P, P, m))
raises(TypeError, lambda: Particle('pa', m, m))
assert p.linear_momentum(N) == m2 * v1 * N.x
assert p.angular_momentum(O, N) == -m2 * r *v1 * N.z
P2.set_vel(N, v2 * N.y)
assert p.linear_momentum(N) == m2 * v2 * N.y
assert p.angular_momentum(O, N) == 0
P2.set_vel(N, v3 * N.z)
assert p.linear_momentum(N) == m2 * v3 * N.z
assert p.angular_momentum(O, N) == m2 * r * v3 * N.x
P2.set_vel(N, v1 * N.x + v2 * N.y + v3 * N.z)
assert p.linear_momentum(N) == m2 * (v1 * N.x + v2 * N.y + v3 * N.z)
assert p.angular_momentum(O, N) == m2 * r * (v3 * N.x - v1 * N.z)
p.potential_energy = m * g * h
assert p.potential_energy == m * g * h
# TODO make the result not be system-dependent
assert p.kinetic_energy(
N) in [m2*(v1**2 + v2**2 + v3**2)/2,
m2 * v1**2 / 2 + m2 * v2**2 / 2 + m2 * v3**2 / 2]
def test_parallel_axis():
N = ReferenceFrame('N')
m, a, b = symbols('m, a, b')
o = Point('o')
p = o.locatenew('p', a * N.x + b * N.y)
P = Particle('P', o, m)
Ip = P.parallel_axis(p, N)
Ip_expected = inertia(N, m * b**2, m * a**2, m * (a**2 + b**2),
ixy=-m * a * b)
assert Ip == Ip_expected
|
b60744abfd8712aeb32cf0ed5d695e9492d48f98c59b3bb061d16ed1c1d161d8 | from sympy.physics.mechanics import (dynamicsymbols, ReferenceFrame, Point,
RigidBody, LagrangesMethod, Particle,
inertia, Lagrangian)
from sympy.core.function import (Derivative, Function)
from sympy.core.numbers import pi
from sympy.core.symbol import symbols
from sympy.functions.elementary.trigonometric import (cos, sin, tan)
from sympy.matrices.dense import Matrix
from sympy.simplify.simplify import simplify
def test_disc_on_an_incline_plane():
# Disc rolling on an inclined plane
# First the generalized coordinates are created. The mass center of the
# disc is located from top vertex of the inclined plane by the generalized
# coordinate 'y'. The orientation of the disc is defined by the angle
# 'theta'. The mass of the disc is 'm' and its radius is 'R'. The length of
# the inclined path is 'l', the angle of inclination is 'alpha'. 'g' is the
# gravitational constant.
y, theta = dynamicsymbols('y theta')
yd, thetad = dynamicsymbols('y theta', 1)
m, g, R, l, alpha = symbols('m g R l alpha')
# Next, we create the inertial reference frame 'N'. A reference frame 'A'
# is attached to the inclined plane. Finally a frame is created which is attached to the disk.
N = ReferenceFrame('N')
A = N.orientnew('A', 'Axis', [pi/2 - alpha, N.z])
B = A.orientnew('B', 'Axis', [-theta, A.z])
# Creating the disc 'D'; we create the point that represents the mass
# center of the disc and set its velocity. The inertia dyadic of the disc
# is created. Finally, we create the disc.
Do = Point('Do')
Do.set_vel(N, yd * A.x)
I = m * R**2/2 * B.z | B.z
D = RigidBody('D', Do, B, m, (I, Do))
# To construct the Lagrangian, 'L', of the disc, we determine its kinetic
# and potential energies, T and U, respectively. L is defined as the
# difference between T and U.
D.potential_energy = m * g * (l - y) * sin(alpha)
L = Lagrangian(N, D)
# We then create the list of generalized coordinates and constraint
# equations. The constraint arises due to the disc rolling without slip on
# on the inclined path. We then invoke the 'LagrangesMethod' class and
# supply it the necessary arguments and generate the equations of motion.
# The'rhs' method solves for the q_double_dots (i.e. the second derivative
# with respect to time of the generalized coordinates and the lagrange
# multipliers.
q = [y, theta]
hol_coneqs = [y - R * theta]
m = LagrangesMethod(L, q, hol_coneqs=hol_coneqs)
m.form_lagranges_equations()
rhs = m.rhs()
rhs.simplify()
assert rhs[2] == 2*g*sin(alpha)/3
def test_simp_pen():
# This tests that the equations generated by LagrangesMethod are identical
# to those obtained by hand calculations. The system under consideration is
# the simple pendulum.
# We begin by creating the generalized coordinates as per the requirements
# of LagrangesMethod. Also we created the associate symbols
# that characterize the system: 'm' is the mass of the bob, l is the length
# of the massless rigid rod connecting the bob to a point O fixed in the
# inertial frame.
q, u = dynamicsymbols('q u')
qd, ud = dynamicsymbols('q u ', 1)
l, m, g = symbols('l m g')
# We then create the inertial frame and a frame attached to the massless
# string following which we define the inertial angular velocity of the
# string.
N = ReferenceFrame('N')
A = N.orientnew('A', 'Axis', [q, N.z])
A.set_ang_vel(N, qd * N.z)
# Next, we create the point O and fix it in the inertial frame. We then
# locate the point P to which the bob is attached. Its corresponding
# velocity is then determined by the 'two point formula'.
O = Point('O')
O.set_vel(N, 0)
P = O.locatenew('P', l * A.x)
P.v2pt_theory(O, N, A)
# The 'Particle' which represents the bob is then created and its
# Lagrangian generated.
Pa = Particle('Pa', P, m)
Pa.potential_energy = - m * g * l * cos(q)
L = Lagrangian(N, Pa)
# The 'LagrangesMethod' class is invoked to obtain equations of motion.
lm = LagrangesMethod(L, [q])
lm.form_lagranges_equations()
RHS = lm.rhs()
assert RHS[1] == -g*sin(q)/l
def test_nonminimal_pendulum():
q1, q2 = dynamicsymbols('q1:3')
q1d, q2d = dynamicsymbols('q1:3', level=1)
L, m, t = symbols('L, m, t')
g = 9.8
# Compose World Frame
N = ReferenceFrame('N')
pN = Point('N*')
pN.set_vel(N, 0)
# Create point P, the pendulum mass
P = pN.locatenew('P1', q1*N.x + q2*N.y)
P.set_vel(N, P.pos_from(pN).dt(N))
pP = Particle('pP', P, m)
# Constraint Equations
f_c = Matrix([q1**2 + q2**2 - L**2])
# Calculate the lagrangian, and form the equations of motion
Lag = Lagrangian(N, pP)
LM = LagrangesMethod(Lag, [q1, q2], hol_coneqs=f_c,
forcelist=[(P, m*g*N.x)], frame=N)
LM.form_lagranges_equations()
# Check solution
lam1 = LM.lam_vec[0, 0]
eom_sol = Matrix([[m*Derivative(q1, t, t) - 9.8*m + 2*lam1*q1],
[m*Derivative(q2, t, t) + 2*lam1*q2]])
assert LM.eom == eom_sol
# Check multiplier solution
lam_sol = Matrix([(19.6*q1 + 2*q1d**2 + 2*q2d**2)/(4*q1**2/m + 4*q2**2/m)])
assert simplify(LM.solve_multipliers(sol_type='Matrix')) == simplify(lam_sol)
def test_dub_pen():
# The system considered is the double pendulum. Like in the
# test of the simple pendulum above, we begin by creating the generalized
# coordinates and the simple generalized speeds and accelerations which
# will be used later. Following this we create frames and points necessary
# for the kinematics. The procedure isn't explicitly explained as this is
# similar to the simple pendulum. Also this is documented on the pydy.org
# website.
q1, q2 = dynamicsymbols('q1 q2')
q1d, q2d = dynamicsymbols('q1 q2', 1)
q1dd, q2dd = dynamicsymbols('q1 q2', 2)
u1, u2 = dynamicsymbols('u1 u2')
u1d, u2d = dynamicsymbols('u1 u2', 1)
l, m, g = symbols('l m g')
N = ReferenceFrame('N')
A = N.orientnew('A', 'Axis', [q1, N.z])
B = N.orientnew('B', 'Axis', [q2, N.z])
A.set_ang_vel(N, q1d * A.z)
B.set_ang_vel(N, q2d * A.z)
O = Point('O')
P = O.locatenew('P', l * A.x)
R = P.locatenew('R', l * B.x)
O.set_vel(N, 0)
P.v2pt_theory(O, N, A)
R.v2pt_theory(P, N, B)
ParP = Particle('ParP', P, m)
ParR = Particle('ParR', R, m)
ParP.potential_energy = - m * g * l * cos(q1)
ParR.potential_energy = - m * g * l * cos(q1) - m * g * l * cos(q2)
L = Lagrangian(N, ParP, ParR)
lm = LagrangesMethod(L, [q1, q2], bodies=[ParP, ParR])
lm.form_lagranges_equations()
assert simplify(l*m*(2*g*sin(q1) + l*sin(q1)*sin(q2)*q2dd
+ l*sin(q1)*cos(q2)*q2d**2 - l*sin(q2)*cos(q1)*q2d**2
+ l*cos(q1)*cos(q2)*q2dd + 2*l*q1dd) - lm.eom[0]) == 0
assert simplify(l*m*(g*sin(q2) + l*sin(q1)*sin(q2)*q1dd
- l*sin(q1)*cos(q2)*q1d**2 + l*sin(q2)*cos(q1)*q1d**2
+ l*cos(q1)*cos(q2)*q1dd + l*q2dd) - lm.eom[1]) == 0
assert lm.bodies == [ParP, ParR]
def test_rolling_disc():
# Rolling Disc Example
# Here the rolling disc is formed from the contact point up, removing the
# need to introduce generalized speeds. Only 3 configuration and 3
# speed variables are need to describe this system, along with the
# disc's mass and radius, and the local gravity.
q1, q2, q3 = dynamicsymbols('q1 q2 q3')
q1d, q2d, q3d = dynamicsymbols('q1 q2 q3', 1)
r, m, g = symbols('r m g')
# The kinematics are formed by a series of simple rotations. Each simple
# rotation creates a new frame, and the next rotation is defined by the new
# frame's basis vectors. This example uses a 3-1-2 series of rotations, or
# Z, X, Y series of rotations. Angular velocity for this is defined using
# the second frame's basis (the lean frame).
N = ReferenceFrame('N')
Y = N.orientnew('Y', 'Axis', [q1, N.z])
L = Y.orientnew('L', 'Axis', [q2, Y.x])
R = L.orientnew('R', 'Axis', [q3, L.y])
# This is the translational kinematics. We create a point with no velocity
# in N; this is the contact point between the disc and ground. Next we form
# the position vector from the contact point to the disc's center of mass.
# Finally we form the velocity and acceleration of the disc.
C = Point('C')
C.set_vel(N, 0)
Dmc = C.locatenew('Dmc', r * L.z)
Dmc.v2pt_theory(C, N, R)
# Forming the inertia dyadic.
I = inertia(L, m/4 * r**2, m/2 * r**2, m/4 * r**2)
BodyD = RigidBody('BodyD', Dmc, R, m, (I, Dmc))
# Finally we form the equations of motion, using the same steps we did
# before. Supply the Lagrangian, the generalized speeds.
BodyD.potential_energy = - m * g * r * cos(q2)
Lag = Lagrangian(N, BodyD)
q = [q1, q2, q3]
q1 = Function('q1')
q2 = Function('q2')
q3 = Function('q3')
l = LagrangesMethod(Lag, q)
l.form_lagranges_equations()
RHS = l.rhs()
RHS.simplify()
t = symbols('t')
assert (l.mass_matrix[3:6] == [0, 5*m*r**2/4, 0])
assert RHS[4].simplify() == (
(-8*g*sin(q2(t)) + r*(5*sin(2*q2(t))*Derivative(q1(t), t) +
12*cos(q2(t))*Derivative(q3(t), t))*Derivative(q1(t), t))/(10*r))
assert RHS[5] == (-5*cos(q2(t))*Derivative(q1(t), t) + 6*tan(q2(t)
)*Derivative(q3(t), t) + 4*Derivative(q1(t), t)/cos(q2(t))
)*Derivative(q2(t), t)
|
5fb96bc53216b933fb1a0a58c86566386e3ccc6e140d657df450025c53b954c0 | import sympy.physics.mechanics.models as models
from sympy.core.backend import (cos, sin, Matrix, symbols, zeros)
from sympy.simplify.simplify import simplify
from sympy.physics.mechanics import (dynamicsymbols)
def test_multi_mass_spring_damper_inputs():
c0, k0, m0 = symbols("c0 k0 m0")
g = symbols("g")
v0, x0, f0 = dynamicsymbols("v0 x0 f0")
kane1 = models.multi_mass_spring_damper(1)
massmatrix1 = Matrix([[m0]])
forcing1 = Matrix([[-c0*v0 - k0*x0]])
assert simplify(massmatrix1 - kane1.mass_matrix) == Matrix([0])
assert simplify(forcing1 - kane1.forcing) == Matrix([0])
kane2 = models.multi_mass_spring_damper(1, True)
massmatrix2 = Matrix([[m0]])
forcing2 = Matrix([[-c0*v0 + g*m0 - k0*x0]])
assert simplify(massmatrix2 - kane2.mass_matrix) == Matrix([0])
assert simplify(forcing2 - kane2.forcing) == Matrix([0])
kane3 = models.multi_mass_spring_damper(1, True, True)
massmatrix3 = Matrix([[m0]])
forcing3 = Matrix([[-c0*v0 + g*m0 - k0*x0 + f0]])
assert simplify(massmatrix3 - kane3.mass_matrix) == Matrix([0])
assert simplify(forcing3 - kane3.forcing) == Matrix([0])
kane4 = models.multi_mass_spring_damper(1, False, True)
massmatrix4 = Matrix([[m0]])
forcing4 = Matrix([[-c0*v0 - k0*x0 + f0]])
assert simplify(massmatrix4 - kane4.mass_matrix) == Matrix([0])
assert simplify(forcing4 - kane4.forcing) == Matrix([0])
def test_multi_mass_spring_damper_higher_order():
c0, k0, m0 = symbols("c0 k0 m0")
c1, k1, m1 = symbols("c1 k1 m1")
c2, k2, m2 = symbols("c2 k2 m2")
v0, x0 = dynamicsymbols("v0 x0")
v1, x1 = dynamicsymbols("v1 x1")
v2, x2 = dynamicsymbols("v2 x2")
kane1 = models.multi_mass_spring_damper(3)
massmatrix1 = Matrix([[m0 + m1 + m2, m1 + m2, m2],
[m1 + m2, m1 + m2, m2],
[m2, m2, m2]])
forcing1 = Matrix([[-c0*v0 - k0*x0],
[-c1*v1 - k1*x1],
[-c2*v2 - k2*x2]])
assert simplify(massmatrix1 - kane1.mass_matrix) == zeros(3)
assert simplify(forcing1 - kane1.forcing) == Matrix([0, 0, 0])
def test_n_link_pendulum_on_cart_inputs():
l0, m0 = symbols("l0 m0")
m1 = symbols("m1")
g = symbols("g")
q0, q1, F, T1 = dynamicsymbols("q0 q1 F T1")
u0, u1 = dynamicsymbols("u0 u1")
kane1 = models.n_link_pendulum_on_cart(1)
massmatrix1 = Matrix([[m0 + m1, -l0*m1*cos(q1)],
[-l0*m1*cos(q1), l0**2*m1]])
forcing1 = Matrix([[-l0*m1*u1**2*sin(q1) + F], [g*l0*m1*sin(q1)]])
assert simplify(massmatrix1 - kane1.mass_matrix) == zeros(2)
assert simplify(forcing1 - kane1.forcing) == Matrix([0, 0])
kane2 = models.n_link_pendulum_on_cart(1, False)
massmatrix2 = Matrix([[m0 + m1, -l0*m1*cos(q1)],
[-l0*m1*cos(q1), l0**2*m1]])
forcing2 = Matrix([[-l0*m1*u1**2*sin(q1)], [g*l0*m1*sin(q1)]])
assert simplify(massmatrix2 - kane2.mass_matrix) == zeros(2)
assert simplify(forcing2 - kane2.forcing) == Matrix([0, 0])
kane3 = models.n_link_pendulum_on_cart(1, False, True)
massmatrix3 = Matrix([[m0 + m1, -l0*m1*cos(q1)],
[-l0*m1*cos(q1), l0**2*m1]])
forcing3 = Matrix([[-l0*m1*u1**2*sin(q1)], [g*l0*m1*sin(q1) + T1]])
assert simplify(massmatrix3 - kane3.mass_matrix) == zeros(2)
assert simplify(forcing3 - kane3.forcing) == Matrix([0, 0])
kane4 = models.n_link_pendulum_on_cart(1, True, False)
massmatrix4 = Matrix([[m0 + m1, -l0*m1*cos(q1)],
[-l0*m1*cos(q1), l0**2*m1]])
forcing4 = Matrix([[-l0*m1*u1**2*sin(q1) + F], [g*l0*m1*sin(q1)]])
assert simplify(massmatrix4 - kane4.mass_matrix) == zeros(2)
assert simplify(forcing4 - kane4.forcing) == Matrix([0, 0])
def test_n_link_pendulum_on_cart_higher_order():
l0, m0 = symbols("l0 m0")
l1, m1 = symbols("l1 m1")
m2 = symbols("m2")
g = symbols("g")
q0, q1, q2 = dynamicsymbols("q0 q1 q2")
u0, u1, u2 = dynamicsymbols("u0 u1 u2")
F, T1 = dynamicsymbols("F T1")
kane1 = models.n_link_pendulum_on_cart(2)
massmatrix1 = Matrix([[m0 + m1 + m2, -l0*m1*cos(q1) - l0*m2*cos(q1),
-l1*m2*cos(q2)],
[-l0*m1*cos(q1) - l0*m2*cos(q1), l0**2*m1 + l0**2*m2,
l0*l1*m2*(sin(q1)*sin(q2) + cos(q1)*cos(q2))],
[-l1*m2*cos(q2),
l0*l1*m2*(sin(q1)*sin(q2) + cos(q1)*cos(q2)),
l1**2*m2]])
forcing1 = Matrix([[-l0*m1*u1**2*sin(q1) - l0*m2*u1**2*sin(q1) -
l1*m2*u2**2*sin(q2) + F],
[g*l0*m1*sin(q1) + g*l0*m2*sin(q1) -
l0*l1*m2*(sin(q1)*cos(q2) - sin(q2)*cos(q1))*u2**2],
[g*l1*m2*sin(q2) - l0*l1*m2*(-sin(q1)*cos(q2) +
sin(q2)*cos(q1))*u1**2]])
assert simplify(massmatrix1 - kane1.mass_matrix) == zeros(3)
assert simplify(forcing1 - kane1.forcing) == Matrix([0, 0, 0])
|
43ea9143dcce156df163f1eaca5555c9c7f1dd35da7eb3f1f15a6955d1b79099 | from sympy.core.backend import (cos, expand, Matrix, sin, symbols, tan, sqrt, S,
zeros)
from sympy.simplify.simplify import simplify
from sympy.physics.mechanics import (dynamicsymbols, ReferenceFrame, Point,
RigidBody, KanesMethod, inertia, Particle,
dot)
def test_one_dof():
# This is for a 1 dof spring-mass-damper case.
# It is described in more detail in the KanesMethod docstring.
q, u = dynamicsymbols('q u')
qd, ud = dynamicsymbols('q u', 1)
m, c, k = symbols('m c k')
N = ReferenceFrame('N')
P = Point('P')
P.set_vel(N, u * N.x)
kd = [qd - u]
FL = [(P, (-k * q - c * u) * N.x)]
pa = Particle('pa', P, m)
BL = [pa]
KM = KanesMethod(N, [q], [u], kd)
KM.kanes_equations(BL, FL)
assert KM.bodies == BL
assert KM.loads == FL
MM = KM.mass_matrix
forcing = KM.forcing
rhs = MM.inv() * forcing
assert expand(rhs[0]) == expand(-(q * k + u * c) / m)
assert simplify(KM.rhs() -
KM.mass_matrix_full.LUsolve(KM.forcing_full)) == zeros(2, 1)
assert (KM.linearize(A_and_B=True, )[0] == Matrix([[0, 1], [-k/m, -c/m]]))
def test_two_dof():
# This is for a 2 d.o.f., 2 particle spring-mass-damper.
# The first coordinate is the displacement of the first particle, and the
# second is the relative displacement between the first and second
# particles. Speeds are defined as the time derivatives of the particles.
q1, q2, u1, u2 = dynamicsymbols('q1 q2 u1 u2')
q1d, q2d, u1d, u2d = dynamicsymbols('q1 q2 u1 u2', 1)
m, c1, c2, k1, k2 = symbols('m c1 c2 k1 k2')
N = ReferenceFrame('N')
P1 = Point('P1')
P2 = Point('P2')
P1.set_vel(N, u1 * N.x)
P2.set_vel(N, (u1 + u2) * N.x)
kd = [q1d - u1, q2d - u2]
# Now we create the list of forces, then assign properties to each
# particle, then create a list of all particles.
FL = [(P1, (-k1 * q1 - c1 * u1 + k2 * q2 + c2 * u2) * N.x), (P2, (-k2 *
q2 - c2 * u2) * N.x)]
pa1 = Particle('pa1', P1, m)
pa2 = Particle('pa2', P2, m)
BL = [pa1, pa2]
# Finally we create the KanesMethod object, specify the inertial frame,
# pass relevant information, and form Fr & Fr*. Then we calculate the mass
# matrix and forcing terms, and finally solve for the udots.
KM = KanesMethod(N, q_ind=[q1, q2], u_ind=[u1, u2], kd_eqs=kd)
KM.kanes_equations(BL, FL)
MM = KM.mass_matrix
forcing = KM.forcing
rhs = MM.inv() * forcing
assert expand(rhs[0]) == expand((-k1 * q1 - c1 * u1 + k2 * q2 + c2 * u2)/m)
assert expand(rhs[1]) == expand((k1 * q1 + c1 * u1 - 2 * k2 * q2 - 2 *
c2 * u2) / m)
assert simplify(KM.rhs() -
KM.mass_matrix_full.LUsolve(KM.forcing_full)) == zeros(4, 1)
def test_pend():
q, u = dynamicsymbols('q u')
qd, ud = dynamicsymbols('q u', 1)
m, l, g = symbols('m l g')
N = ReferenceFrame('N')
P = Point('P')
P.set_vel(N, -l * u * sin(q) * N.x + l * u * cos(q) * N.y)
kd = [qd - u]
FL = [(P, m * g * N.x)]
pa = Particle('pa', P, m)
BL = [pa]
KM = KanesMethod(N, [q], [u], kd)
KM.kanes_equations(BL, FL)
MM = KM.mass_matrix
forcing = KM.forcing
rhs = MM.inv() * forcing
rhs.simplify()
assert expand(rhs[0]) == expand(-g / l * sin(q))
assert simplify(KM.rhs() -
KM.mass_matrix_full.LUsolve(KM.forcing_full)) == zeros(2, 1)
def test_rolling_disc():
# Rolling Disc Example
# Here the rolling disc is formed from the contact point up, removing the
# need to introduce generalized speeds. Only 3 configuration and three
# speed variables are need to describe this system, along with the disc's
# mass and radius, and the local gravity (note that mass will drop out).
q1, q2, q3, u1, u2, u3 = dynamicsymbols('q1 q2 q3 u1 u2 u3')
q1d, q2d, q3d, u1d, u2d, u3d = dynamicsymbols('q1 q2 q3 u1 u2 u3', 1)
r, m, g = symbols('r m g')
# The kinematics are formed by a series of simple rotations. Each simple
# rotation creates a new frame, and the next rotation is defined by the new
# frame's basis vectors. This example uses a 3-1-2 series of rotations, or
# Z, X, Y series of rotations. Angular velocity for this is defined using
# the second frame's basis (the lean frame).
N = ReferenceFrame('N')
Y = N.orientnew('Y', 'Axis', [q1, N.z])
L = Y.orientnew('L', 'Axis', [q2, Y.x])
R = L.orientnew('R', 'Axis', [q3, L.y])
w_R_N_qd = R.ang_vel_in(N)
R.set_ang_vel(N, u1 * L.x + u2 * L.y + u3 * L.z)
# This is the translational kinematics. We create a point with no velocity
# in N; this is the contact point between the disc and ground. Next we form
# the position vector from the contact point to the disc's center of mass.
# Finally we form the velocity and acceleration of the disc.
C = Point('C')
C.set_vel(N, 0)
Dmc = C.locatenew('Dmc', r * L.z)
Dmc.v2pt_theory(C, N, R)
# This is a simple way to form the inertia dyadic.
I = inertia(L, m / 4 * r**2, m / 2 * r**2, m / 4 * r**2)
# Kinematic differential equations; how the generalized coordinate time
# derivatives relate to generalized speeds.
kd = [dot(R.ang_vel_in(N) - w_R_N_qd, uv) for uv in L]
# Creation of the force list; it is the gravitational force at the mass
# center of the disc. Then we create the disc by assigning a Point to the
# center of mass attribute, a ReferenceFrame to the frame attribute, and mass
# and inertia. Then we form the body list.
ForceList = [(Dmc, - m * g * Y.z)]
BodyD = RigidBody('BodyD', Dmc, R, m, (I, Dmc))
BodyList = [BodyD]
# Finally we form the equations of motion, using the same steps we did
# before. Specify inertial frame, supply generalized speeds, supply
# kinematic differential equation dictionary, compute Fr from the force
# list and Fr* from the body list, compute the mass matrix and forcing
# terms, then solve for the u dots (time derivatives of the generalized
# speeds).
KM = KanesMethod(N, q_ind=[q1, q2, q3], u_ind=[u1, u2, u3], kd_eqs=kd)
KM.kanes_equations(BodyList, ForceList)
MM = KM.mass_matrix
forcing = KM.forcing
rhs = MM.inv() * forcing
kdd = KM.kindiffdict()
rhs = rhs.subs(kdd)
rhs.simplify()
assert rhs.expand() == Matrix([(6*u2*u3*r - u3**2*r*tan(q2) +
4*g*sin(q2))/(5*r), -2*u1*u3/3, u1*(-2*u2 + u3*tan(q2))]).expand()
assert simplify(KM.rhs() -
KM.mass_matrix_full.LUsolve(KM.forcing_full)) == zeros(6, 1)
# This code tests our output vs. benchmark values. When r=g=m=1, the
# critical speed (where all eigenvalues of the linearized equations are 0)
# is 1 / sqrt(3) for the upright case.
A = KM.linearize(A_and_B=True)[0]
A_upright = A.subs({r: 1, g: 1, m: 1}).subs({q1: 0, q2: 0, q3: 0, u1: 0, u3: 0})
import sympy
assert sympy.sympify(A_upright.subs({u2: 1 / sqrt(3)})).eigenvals() == {S.Zero: 6}
def test_aux():
# Same as above, except we have 2 auxiliary speeds for the ground contact
# point, which is known to be zero. In one case, we go through then
# substitute the aux. speeds in at the end (they are zero, as well as their
# derivative), in the other case, we use the built-in auxiliary speed part
# of KanesMethod. The equations from each should be the same.
q1, q2, q3, u1, u2, u3 = dynamicsymbols('q1 q2 q3 u1 u2 u3')
q1d, q2d, q3d, u1d, u2d, u3d = dynamicsymbols('q1 q2 q3 u1 u2 u3', 1)
u4, u5, f1, f2 = dynamicsymbols('u4, u5, f1, f2')
u4d, u5d = dynamicsymbols('u4, u5', 1)
r, m, g = symbols('r m g')
N = ReferenceFrame('N')
Y = N.orientnew('Y', 'Axis', [q1, N.z])
L = Y.orientnew('L', 'Axis', [q2, Y.x])
R = L.orientnew('R', 'Axis', [q3, L.y])
w_R_N_qd = R.ang_vel_in(N)
R.set_ang_vel(N, u1 * L.x + u2 * L.y + u3 * L.z)
C = Point('C')
C.set_vel(N, u4 * L.x + u5 * (Y.z ^ L.x))
Dmc = C.locatenew('Dmc', r * L.z)
Dmc.v2pt_theory(C, N, R)
Dmc.a2pt_theory(C, N, R)
I = inertia(L, m / 4 * r**2, m / 2 * r**2, m / 4 * r**2)
kd = [dot(R.ang_vel_in(N) - w_R_N_qd, uv) for uv in L]
ForceList = [(Dmc, - m * g * Y.z), (C, f1 * L.x + f2 * (Y.z ^ L.x))]
BodyD = RigidBody('BodyD', Dmc, R, m, (I, Dmc))
BodyList = [BodyD]
KM = KanesMethod(N, q_ind=[q1, q2, q3], u_ind=[u1, u2, u3, u4, u5],
kd_eqs=kd)
(fr, frstar) = KM.kanes_equations(BodyList, ForceList)
fr = fr.subs({u4d: 0, u5d: 0}).subs({u4: 0, u5: 0})
frstar = frstar.subs({u4d: 0, u5d: 0}).subs({u4: 0, u5: 0})
KM2 = KanesMethod(N, q_ind=[q1, q2, q3], u_ind=[u1, u2, u3], kd_eqs=kd,
u_auxiliary=[u4, u5])
(fr2, frstar2) = KM2.kanes_equations(BodyList, ForceList)
fr2 = fr2.subs({u4d: 0, u5d: 0}).subs({u4: 0, u5: 0})
frstar2 = frstar2.subs({u4d: 0, u5d: 0}).subs({u4: 0, u5: 0})
frstar.simplify()
frstar2.simplify()
assert (fr - fr2).expand() == Matrix([0, 0, 0, 0, 0])
assert (frstar - frstar2).expand() == Matrix([0, 0, 0, 0, 0])
def test_parallel_axis():
# This is for a 2 dof inverted pendulum on a cart.
# This tests the parallel axis code in KanesMethod. The inertia of the
# pendulum is defined about the hinge, not about the center of mass.
# Defining the constants and knowns of the system
gravity = symbols('g')
k, ls = symbols('k ls')
a, mA, mC = symbols('a mA mC')
F = dynamicsymbols('F')
Ix, Iy, Iz = symbols('Ix Iy Iz')
# Declaring the Generalized coordinates and speeds
q1, q2 = dynamicsymbols('q1 q2')
q1d, q2d = dynamicsymbols('q1 q2', 1)
u1, u2 = dynamicsymbols('u1 u2')
u1d, u2d = dynamicsymbols('u1 u2', 1)
# Creating reference frames
N = ReferenceFrame('N')
A = ReferenceFrame('A')
A.orient(N, 'Axis', [-q2, N.z])
A.set_ang_vel(N, -u2 * N.z)
# Origin of Newtonian reference frame
O = Point('O')
# Creating and Locating the positions of the cart, C, and the
# center of mass of the pendulum, A
C = O.locatenew('C', q1 * N.x)
Ao = C.locatenew('Ao', a * A.y)
# Defining velocities of the points
O.set_vel(N, 0)
C.set_vel(N, u1 * N.x)
Ao.v2pt_theory(C, N, A)
Cart = Particle('Cart', C, mC)
Pendulum = RigidBody('Pendulum', Ao, A, mA, (inertia(A, Ix, Iy, Iz), C))
# kinematical differential equations
kindiffs = [q1d - u1, q2d - u2]
bodyList = [Cart, Pendulum]
forceList = [(Ao, -N.y * gravity * mA),
(C, -N.y * gravity * mC),
(C, -N.x * k * (q1 - ls)),
(C, N.x * F)]
km = KanesMethod(N, [q1, q2], [u1, u2], kindiffs)
(fr, frstar) = km.kanes_equations(bodyList, forceList)
mm = km.mass_matrix_full
assert mm[3, 3] == Iz
def test_input_format():
# 1 dof problem from test_one_dof
q, u = dynamicsymbols('q u')
qd, ud = dynamicsymbols('q u', 1)
m, c, k = symbols('m c k')
N = ReferenceFrame('N')
P = Point('P')
P.set_vel(N, u * N.x)
kd = [qd - u]
FL = [(P, (-k * q - c * u) * N.x)]
pa = Particle('pa', P, m)
BL = [pa]
KM = KanesMethod(N, [q], [u], kd)
# test for input format kane.kanes_equations((body1, body2, particle1))
assert KM.kanes_equations(BL)[0] == Matrix([0])
# test for input format kane.kanes_equations(bodies=(body1, body 2), loads=(load1,load2))
assert KM.kanes_equations(bodies=BL, loads=None)[0] == Matrix([0])
# test for input format kane.kanes_equations(bodies=(body1, body 2), loads=None)
assert KM.kanes_equations(BL, loads=None)[0] == Matrix([0])
# test for input format kane.kanes_equations(bodies=(body1, body 2))
assert KM.kanes_equations(BL)[0] == Matrix([0])
# test for input format kane.kanes_equations(bodies=(body1, body2), loads=[])
assert KM.kanes_equations(BL, [])[0] == Matrix([0])
# test for error raised when a wrong force list (in this case a string) is provided
from sympy.testing.pytest import raises
raises(ValueError, lambda: KM._form_fr('bad input'))
# 1 dof problem from test_one_dof with FL & BL in instance
KM = KanesMethod(N, [q], [u], kd, bodies=BL, forcelist=FL)
assert KM.kanes_equations()[0] == Matrix([-c*u - k*q])
# 2 dof problem from test_two_dof
q1, q2, u1, u2 = dynamicsymbols('q1 q2 u1 u2')
q1d, q2d, u1d, u2d = dynamicsymbols('q1 q2 u1 u2', 1)
m, c1, c2, k1, k2 = symbols('m c1 c2 k1 k2')
N = ReferenceFrame('N')
P1 = Point('P1')
P2 = Point('P2')
P1.set_vel(N, u1 * N.x)
P2.set_vel(N, (u1 + u2) * N.x)
kd = [q1d - u1, q2d - u2]
FL = ((P1, (-k1 * q1 - c1 * u1 + k2 * q2 + c2 * u2) * N.x), (P2, (-k2 *
q2 - c2 * u2) * N.x))
pa1 = Particle('pa1', P1, m)
pa2 = Particle('pa2', P2, m)
BL = (pa1, pa2)
KM = KanesMethod(N, q_ind=[q1, q2], u_ind=[u1, u2], kd_eqs=kd)
# test for input format
# kane.kanes_equations((body1, body2), (load1, load2))
KM.kanes_equations(BL, FL)
MM = KM.mass_matrix
forcing = KM.forcing
rhs = MM.inv() * forcing
assert expand(rhs[0]) == expand((-k1 * q1 - c1 * u1 + k2 * q2 + c2 * u2)/m)
assert expand(rhs[1]) == expand((k1 * q1 + c1 * u1 - 2 * k2 * q2 - 2 *
c2 * u2) / m)
|
1b85dd185a7a948530349eaa9bbed7db864f2a019ccb1601b82bfad567913973 | from sympy.core.backend import (symbols, Matrix, cos, sin, atan, sqrt,
Rational, _simplify_matrix)
from sympy.core.sympify import sympify
from sympy.simplify.simplify import simplify
from sympy.solvers.solvers import solve
from sympy.physics.mechanics import dynamicsymbols, ReferenceFrame, Point,\
dot, cross, inertia, KanesMethod, Particle, RigidBody, Lagrangian,\
LagrangesMethod
from sympy.testing.pytest import slow
@slow
def test_linearize_rolling_disc_kane():
# Symbols for time and constant parameters
t, r, m, g, v = symbols('t r m g v')
# Configuration variables and their time derivatives
q1, q2, q3, q4, q5, q6 = q = dynamicsymbols('q1:7')
q1d, q2d, q3d, q4d, q5d, q6d = qd = [qi.diff(t) for qi in q]
# Generalized speeds and their time derivatives
u = dynamicsymbols('u:6')
u1, u2, u3, u4, u5, u6 = u = dynamicsymbols('u1:7')
u1d, u2d, u3d, u4d, u5d, u6d = [ui.diff(t) for ui in u]
# Reference frames
N = ReferenceFrame('N') # Inertial frame
NO = Point('NO') # Inertial origin
A = N.orientnew('A', 'Axis', [q1, N.z]) # Yaw intermediate frame
B = A.orientnew('B', 'Axis', [q2, A.x]) # Lean intermediate frame
C = B.orientnew('C', 'Axis', [q3, B.y]) # Disc fixed frame
CO = NO.locatenew('CO', q4*N.x + q5*N.y + q6*N.z) # Disc center
# Disc angular velocity in N expressed using time derivatives of coordinates
w_c_n_qd = C.ang_vel_in(N)
w_b_n_qd = B.ang_vel_in(N)
# Inertial angular velocity and angular acceleration of disc fixed frame
C.set_ang_vel(N, u1*B.x + u2*B.y + u3*B.z)
# Disc center velocity in N expressed using time derivatives of coordinates
v_co_n_qd = CO.pos_from(NO).dt(N)
# Disc center velocity in N expressed using generalized speeds
CO.set_vel(N, u4*C.x + u5*C.y + u6*C.z)
# Disc Ground Contact Point
P = CO.locatenew('P', r*B.z)
P.v2pt_theory(CO, N, C)
# Configuration constraint
f_c = Matrix([q6 - dot(CO.pos_from(P), N.z)])
# Velocity level constraints
f_v = Matrix([dot(P.vel(N), uv) for uv in C])
# Kinematic differential equations
kindiffs = Matrix([dot(w_c_n_qd - C.ang_vel_in(N), uv) for uv in B] +
[dot(v_co_n_qd - CO.vel(N), uv) for uv in N])
qdots = solve(kindiffs, qd)
# Set angular velocity of remaining frames
B.set_ang_vel(N, w_b_n_qd.subs(qdots))
C.set_ang_acc(N, C.ang_vel_in(N).dt(B) + cross(B.ang_vel_in(N), C.ang_vel_in(N)))
# Active forces
F_CO = m*g*A.z
# Create inertia dyadic of disc C about point CO
I = (m * r**2) / 4
J = (m * r**2) / 2
I_C_CO = inertia(C, I, J, I)
Disc = RigidBody('Disc', CO, C, m, (I_C_CO, CO))
BL = [Disc]
FL = [(CO, F_CO)]
KM = KanesMethod(N, [q1, q2, q3, q4, q5], [u1, u2, u3], kd_eqs=kindiffs,
q_dependent=[q6], configuration_constraints=f_c,
u_dependent=[u4, u5, u6], velocity_constraints=f_v)
(fr, fr_star) = KM.kanes_equations(BL, FL)
# Test generalized form equations
linearizer = KM.to_linearizer()
assert linearizer.f_c == f_c
assert linearizer.f_v == f_v
assert linearizer.f_a == f_v.diff(t).subs(KM.kindiffdict())
sol = solve(linearizer.f_0 + linearizer.f_1, qd)
for qi in qdots.keys():
assert sol[qi] == qdots[qi]
assert simplify(linearizer.f_2 + linearizer.f_3 - fr - fr_star) == Matrix([0, 0, 0])
# Perform the linearization
# Precomputed operating point
q_op = {q6: -r*cos(q2)}
u_op = {u1: 0,
u2: sin(q2)*q1d + q3d,
u3: cos(q2)*q1d,
u4: -r*(sin(q2)*q1d + q3d)*cos(q3),
u5: 0,
u6: -r*(sin(q2)*q1d + q3d)*sin(q3)}
qd_op = {q2d: 0,
q4d: -r*(sin(q2)*q1d + q3d)*cos(q1),
q5d: -r*(sin(q2)*q1d + q3d)*sin(q1),
q6d: 0}
ud_op = {u1d: 4*g*sin(q2)/(5*r) + sin(2*q2)*q1d**2/2 + 6*cos(q2)*q1d*q3d/5,
u2d: 0,
u3d: 0,
u4d: r*(sin(q2)*sin(q3)*q1d*q3d + sin(q3)*q3d**2),
u5d: r*(4*g*sin(q2)/(5*r) + sin(2*q2)*q1d**2/2 + 6*cos(q2)*q1d*q3d/5),
u6d: -r*(sin(q2)*cos(q3)*q1d*q3d + cos(q3)*q3d**2)}
A, B = linearizer.linearize(op_point=[q_op, u_op, qd_op, ud_op], A_and_B=True, simplify=True)
upright_nominal = {q1d: 0, q2: 0, m: 1, r: 1, g: 1}
# Precomputed solution
A_sol = Matrix([[0, 0, 0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0],
[sin(q1)*q3d, 0, 0, 0, 0, -sin(q1), -cos(q1), 0],
[-cos(q1)*q3d, 0, 0, 0, 0, cos(q1), -sin(q1), 0],
[0, Rational(4, 5), 0, 0, 0, 0, 0, 6*q3d/5],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, -2*q3d, 0, 0]])
B_sol = Matrix([])
# Check that linearization is correct
assert A.subs(upright_nominal) == A_sol
assert B.subs(upright_nominal) == B_sol
# Check eigenvalues at critical speed are all zero:
assert sympify(A.subs(upright_nominal).subs(q3d, 1/sqrt(3))).eigenvals() == {0: 8}
def test_linearize_pendulum_kane_minimal():
q1 = dynamicsymbols('q1') # angle of pendulum
u1 = dynamicsymbols('u1') # Angular velocity
q1d = dynamicsymbols('q1', 1) # Angular velocity
L, m, t = symbols('L, m, t')
g = 9.8
# Compose world frame
N = ReferenceFrame('N')
pN = Point('N*')
pN.set_vel(N, 0)
# A.x is along the pendulum
A = N.orientnew('A', 'axis', [q1, N.z])
A.set_ang_vel(N, u1*N.z)
# Locate point P relative to the origin N*
P = pN.locatenew('P', L*A.x)
P.v2pt_theory(pN, N, A)
pP = Particle('pP', P, m)
# Create Kinematic Differential Equations
kde = Matrix([q1d - u1])
# Input the force resultant at P
R = m*g*N.x
# Solve for eom with kanes method
KM = KanesMethod(N, q_ind=[q1], u_ind=[u1], kd_eqs=kde)
(fr, frstar) = KM.kanes_equations([pP], [(P, R)])
# Linearize
A, B, inp_vec = KM.linearize(A_and_B=True, simplify=True)
assert A == Matrix([[0, 1], [-9.8*cos(q1)/L, 0]])
assert B == Matrix([])
def test_linearize_pendulum_kane_nonminimal():
# Create generalized coordinates and speeds for this non-minimal realization
# q1, q2 = N.x and N.y coordinates of pendulum
# u1, u2 = N.x and N.y velocities of pendulum
q1, q2 = dynamicsymbols('q1:3')
q1d, q2d = dynamicsymbols('q1:3', level=1)
u1, u2 = dynamicsymbols('u1:3')
u1d, u2d = dynamicsymbols('u1:3', level=1)
L, m, t = symbols('L, m, t')
g = 9.8
# Compose world frame
N = ReferenceFrame('N')
pN = Point('N*')
pN.set_vel(N, 0)
# A.x is along the pendulum
theta1 = atan(q2/q1)
A = N.orientnew('A', 'axis', [theta1, N.z])
# Locate the pendulum mass
P = pN.locatenew('P1', q1*N.x + q2*N.y)
pP = Particle('pP', P, m)
# Calculate the kinematic differential equations
kde = Matrix([q1d - u1,
q2d - u2])
dq_dict = solve(kde, [q1d, q2d])
# Set velocity of point P
P.set_vel(N, P.pos_from(pN).dt(N).subs(dq_dict))
# Configuration constraint is length of pendulum
f_c = Matrix([P.pos_from(pN).magnitude() - L])
# Velocity constraint is that the velocity in the A.x direction is
# always zero (the pendulum is never getting longer).
f_v = Matrix([P.vel(N).express(A).dot(A.x)])
f_v.simplify()
# Acceleration constraints is the time derivative of the velocity constraint
f_a = f_v.diff(t)
f_a.simplify()
# Input the force resultant at P
R = m*g*N.x
# Derive the equations of motion using the KanesMethod class.
KM = KanesMethod(N, q_ind=[q2], u_ind=[u2], q_dependent=[q1],
u_dependent=[u1], configuration_constraints=f_c,
velocity_constraints=f_v, acceleration_constraints=f_a, kd_eqs=kde)
(fr, frstar) = KM.kanes_equations([pP], [(P, R)])
# Set the operating point to be straight down, and non-moving
q_op = {q1: L, q2: 0}
u_op = {u1: 0, u2: 0}
ud_op = {u1d: 0, u2d: 0}
A, B, inp_vec = KM.linearize(op_point=[q_op, u_op, ud_op], A_and_B=True,
simplify=True)
assert A.expand() == Matrix([[0, 1], [-9.8/L, 0]])
assert B == Matrix([])
def test_linearize_pendulum_lagrange_minimal():
q1 = dynamicsymbols('q1') # angle of pendulum
q1d = dynamicsymbols('q1', 1) # Angular velocity
L, m, t = symbols('L, m, t')
g = 9.8
# Compose world frame
N = ReferenceFrame('N')
pN = Point('N*')
pN.set_vel(N, 0)
# A.x is along the pendulum
A = N.orientnew('A', 'axis', [q1, N.z])
A.set_ang_vel(N, q1d*N.z)
# Locate point P relative to the origin N*
P = pN.locatenew('P', L*A.x)
P.v2pt_theory(pN, N, A)
pP = Particle('pP', P, m)
# Solve for eom with Lagranges method
Lag = Lagrangian(N, pP)
LM = LagrangesMethod(Lag, [q1], forcelist=[(P, m*g*N.x)], frame=N)
LM.form_lagranges_equations()
# Linearize
A, B, inp_vec = LM.linearize([q1], [q1d], A_and_B=True)
assert _simplify_matrix(A) == Matrix([[0, 1], [-9.8*cos(q1)/L, 0]])
assert B == Matrix([])
def test_linearize_pendulum_lagrange_nonminimal():
q1, q2 = dynamicsymbols('q1:3')
q1d, q2d = dynamicsymbols('q1:3', level=1)
L, m, t = symbols('L, m, t')
g = 9.8
# Compose World Frame
N = ReferenceFrame('N')
pN = Point('N*')
pN.set_vel(N, 0)
# A.x is along the pendulum
theta1 = atan(q2/q1)
A = N.orientnew('A', 'axis', [theta1, N.z])
# Create point P, the pendulum mass
P = pN.locatenew('P1', q1*N.x + q2*N.y)
P.set_vel(N, P.pos_from(pN).dt(N))
pP = Particle('pP', P, m)
# Constraint Equations
f_c = Matrix([q1**2 + q2**2 - L**2])
# Calculate the lagrangian, and form the equations of motion
Lag = Lagrangian(N, pP)
LM = LagrangesMethod(Lag, [q1, q2], hol_coneqs=f_c, forcelist=[(P, m*g*N.x)], frame=N)
LM.form_lagranges_equations()
# Compose operating point
op_point = {q1: L, q2: 0, q1d: 0, q2d: 0, q1d.diff(t): 0, q2d.diff(t): 0}
# Solve for multiplier operating point
lam_op = LM.solve_multipliers(op_point=op_point)
op_point.update(lam_op)
# Perform the Linearization
A, B, inp_vec = LM.linearize([q2], [q2d], [q1], [q1d],
op_point=op_point, A_and_B=True)
assert _simplify_matrix(A) == Matrix([[0, 1], [-9.8/L, 0]])
assert B == Matrix([])
def test_linearize_rolling_disc_lagrange():
q1, q2, q3 = q = dynamicsymbols('q1 q2 q3')
q1d, q2d, q3d = qd = dynamicsymbols('q1 q2 q3', 1)
r, m, g = symbols('r m g')
N = ReferenceFrame('N')
Y = N.orientnew('Y', 'Axis', [q1, N.z])
L = Y.orientnew('L', 'Axis', [q2, Y.x])
R = L.orientnew('R', 'Axis', [q3, L.y])
C = Point('C')
C.set_vel(N, 0)
Dmc = C.locatenew('Dmc', r * L.z)
Dmc.v2pt_theory(C, N, R)
I = inertia(L, m / 4 * r**2, m / 2 * r**2, m / 4 * r**2)
BodyD = RigidBody('BodyD', Dmc, R, m, (I, Dmc))
BodyD.potential_energy = - m * g * r * cos(q2)
Lag = Lagrangian(N, BodyD)
l = LagrangesMethod(Lag, q)
l.form_lagranges_equations()
# Linearize about steady-state upright rolling
op_point = {q1: 0, q2: 0, q3: 0,
q1d: 0, q2d: 0,
q1d.diff(): 0, q2d.diff(): 0, q3d.diff(): 0}
A = l.linearize(q_ind=q, qd_ind=qd, op_point=op_point, A_and_B=True)[0]
sol = Matrix([[0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, -6*q3d, 0],
[0, -4*g/(5*r), 0, 6*q3d/5, 0, 0],
[0, 0, 0, 0, 0, 0]])
assert A == sol
|
542b4a3e7ee5148e5da6598a8c3724d8f77235b2fff5b7b7e4649bc3058082b4 | from sympy.core.symbol import symbols
from sympy.physics.mechanics import Point, ReferenceFrame, Dyadic, RigidBody
from sympy.physics.mechanics import dynamicsymbols, outer, inertia
from sympy.physics.mechanics import inertia_of_point_mass
from sympy.core.backend import expand
from sympy.testing.pytest import raises
def test_rigidbody():
m, m2, v1, v2, v3, omega = symbols('m m2 v1 v2 v3 omega')
A = ReferenceFrame('A')
A2 = ReferenceFrame('A2')
P = Point('P')
P2 = Point('P2')
I = Dyadic(0)
I2 = Dyadic(0)
B = RigidBody('B', P, A, m, (I, P))
assert B.mass == m
assert B.frame == A
assert B.masscenter == P
assert B.inertia == (I, B.masscenter)
B.mass = m2
B.frame = A2
B.masscenter = P2
B.inertia = (I2, B.masscenter)
raises(TypeError, lambda: RigidBody(P, P, A, m, (I, P)))
raises(TypeError, lambda: RigidBody('B', P, P, m, (I, P)))
raises(TypeError, lambda: RigidBody('B', P, A, m, (P, P)))
raises(TypeError, lambda: RigidBody('B', P, A, m, (I, I)))
assert B.__str__() == 'B'
assert B.mass == m2
assert B.frame == A2
assert B.masscenter == P2
assert B.inertia == (I2, B.masscenter)
assert B.masscenter == P2
assert B.inertia == (I2, B.masscenter)
# Testing linear momentum function assuming A2 is the inertial frame
N = ReferenceFrame('N')
P2.set_vel(N, v1 * N.x + v2 * N.y + v3 * N.z)
assert B.linear_momentum(N) == m2 * (v1 * N.x + v2 * N.y + v3 * N.z)
def test_rigidbody2():
M, v, r, omega, g, h = dynamicsymbols('M v r omega g h')
N = ReferenceFrame('N')
b = ReferenceFrame('b')
b.set_ang_vel(N, omega * b.x)
P = Point('P')
I = outer(b.x, b.x)
Inertia_tuple = (I, P)
B = RigidBody('B', P, b, M, Inertia_tuple)
P.set_vel(N, v * b.x)
assert B.angular_momentum(P, N) == omega * b.x
O = Point('O')
O.set_vel(N, v * b.x)
P.set_pos(O, r * b.y)
assert B.angular_momentum(O, N) == omega * b.x - M*v*r*b.z
B.potential_energy = M * g * h
assert B.potential_energy == M * g * h
assert expand(2 * B.kinetic_energy(N)) == omega**2 + M * v**2
def test_rigidbody3():
q1, q2, q3, q4 = dynamicsymbols('q1:5')
p1, p2, p3 = symbols('p1:4')
m = symbols('m')
A = ReferenceFrame('A')
B = A.orientnew('B', 'axis', [q1, A.x])
O = Point('O')
O.set_vel(A, q2*A.x + q3*A.y + q4*A.z)
P = O.locatenew('P', p1*B.x + p2*B.y + p3*B.z)
P.v2pt_theory(O, A, B)
I = outer(B.x, B.x)
rb1 = RigidBody('rb1', P, B, m, (I, P))
# I_S/O = I_S/S* + I_S*/O
rb2 = RigidBody('rb2', P, B, m,
(I + inertia_of_point_mass(m, P.pos_from(O), B), O))
assert rb1.central_inertia == rb2.central_inertia
assert rb1.angular_momentum(O, A) == rb2.angular_momentum(O, A)
def test_pendulum_angular_momentum():
"""Consider a pendulum of length OA = 2a, of mass m as a rigid body of
center of mass G (OG = a) which turn around (O,z). The angle between the
reference frame R and the rod is q. The inertia of the body is I =
(G,0,ma^2/3,ma^2/3). """
m, a = symbols('m, a')
q = dynamicsymbols('q')
R = ReferenceFrame('R')
R1 = R.orientnew('R1', 'Axis', [q, R.z])
R1.set_ang_vel(R, q.diff() * R.z)
I = inertia(R1, 0, m * a**2 / 3, m * a**2 / 3)
O = Point('O')
A = O.locatenew('A', 2*a * R1.x)
G = O.locatenew('G', a * R1.x)
S = RigidBody('S', G, R1, m, (I, G))
O.set_vel(R, 0)
A.v2pt_theory(O, R, R1)
G.v2pt_theory(O, R, R1)
assert (4 * m * a**2 / 3 * q.diff() * R.z -
S.angular_momentum(O, R).express(R)) == 0
def test_parallel_axis():
N = ReferenceFrame('N')
m, Ix, Iy, Iz, a, b = symbols('m, I_x, I_y, I_z, a, b')
Io = inertia(N, Ix, Iy, Iz)
o = Point('o')
p = o.locatenew('p', a * N.x + b * N.y)
R = RigidBody('R', o, N, m, (Io, o))
Ip = R.parallel_axis(p)
Ip_expected = inertia(N, Ix + m * b**2, Iy + m * a**2,
Iz + m * (a**2 + b**2), ixy=-m * a * b)
assert Ip == Ip_expected
|
bd1c6f387e7ac2e5914f28264dc249640941e81c3656585cafdaba039dbafd60 | from sympy.core.backend import symbols, Matrix, atan, zeros
from sympy.simplify.simplify import simplify
from sympy.physics.mechanics import (dynamicsymbols, Particle, Point,
ReferenceFrame, SymbolicSystem)
from sympy.testing.pytest import raises
# This class is going to be tested using a simple pendulum set up in x and y
# coordinates
x, y, u, v, lam = dynamicsymbols('x y u v lambda')
m, l, g = symbols('m l g')
# Set up the different forms the equations can take
# [1] Explicit form where the kinematics and dynamics are combined
# x' = F(x, t, r, p)
#
# [2] Implicit form where the kinematics and dynamics are combined
# M(x, p) x' = F(x, t, r, p)
#
# [3] Implicit form where the kinematics and dynamics are separate
# M(q, p) u' = F(q, u, t, r, p)
# q' = G(q, u, t, r, p)
dyn_implicit_mat = Matrix([[1, 0, -x/m],
[0, 1, -y/m],
[0, 0, l**2/m]])
dyn_implicit_rhs = Matrix([0, 0, u**2 + v**2 - g*y])
comb_implicit_mat = Matrix([[1, 0, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 0, 1, 0, -x/m],
[0, 0, 0, 1, -y/m],
[0, 0, 0, 0, l**2/m]])
comb_implicit_rhs = Matrix([u, v, 0, 0, u**2 + v**2 - g*y])
kin_explicit_rhs = Matrix([u, v])
comb_explicit_rhs = comb_implicit_mat.LUsolve(comb_implicit_rhs)
# Set up a body and load to pass into the system
theta = atan(x/y)
N = ReferenceFrame('N')
A = N.orientnew('A', 'Axis', [theta, N.z])
O = Point('O')
P = O.locatenew('P', l * A.x)
Pa = Particle('Pa', P, m)
bodies = [Pa]
loads = [(P, g * m * N.x)]
# Set up some output equations to be given to SymbolicSystem
# Change to make these fit the pendulum
PE = symbols("PE")
out_eqns = {PE: m*g*(l+y)}
# Set up remaining arguments that can be passed to SymbolicSystem
alg_con = [2]
alg_con_full = [4]
coordinates = (x, y, lam)
speeds = (u, v)
states = (x, y, u, v, lam)
coord_idxs = (0, 1)
speed_idxs = (2, 3)
def test_form_1():
symsystem1 = SymbolicSystem(states, comb_explicit_rhs,
alg_con=alg_con_full, output_eqns=out_eqns,
coord_idxs=coord_idxs, speed_idxs=speed_idxs,
bodies=bodies, loads=loads)
assert symsystem1.coordinates == Matrix([x, y])
assert symsystem1.speeds == Matrix([u, v])
assert symsystem1.states == Matrix([x, y, u, v, lam])
assert symsystem1.alg_con == [4]
inter = comb_explicit_rhs
assert simplify(symsystem1.comb_explicit_rhs - inter) == zeros(5, 1)
assert set(symsystem1.dynamic_symbols()) == {y, v, lam, u, x}
assert type(symsystem1.dynamic_symbols()) == tuple
assert set(symsystem1.constant_symbols()) == {l, g, m}
assert type(symsystem1.constant_symbols()) == tuple
assert symsystem1.output_eqns == out_eqns
assert symsystem1.bodies == (Pa,)
assert symsystem1.loads == ((P, g * m * N.x),)
def test_form_2():
symsystem2 = SymbolicSystem(coordinates, comb_implicit_rhs, speeds=speeds,
mass_matrix=comb_implicit_mat,
alg_con=alg_con_full, output_eqns=out_eqns,
bodies=bodies, loads=loads)
assert symsystem2.coordinates == Matrix([x, y, lam])
assert symsystem2.speeds == Matrix([u, v])
assert symsystem2.states == Matrix([x, y, lam, u, v])
assert symsystem2.alg_con == [4]
inter = comb_implicit_rhs
assert simplify(symsystem2.comb_implicit_rhs - inter) == zeros(5, 1)
assert simplify(symsystem2.comb_implicit_mat-comb_implicit_mat) == zeros(5)
assert set(symsystem2.dynamic_symbols()) == {y, v, lam, u, x}
assert type(symsystem2.dynamic_symbols()) == tuple
assert set(symsystem2.constant_symbols()) == {l, g, m}
assert type(symsystem2.constant_symbols()) == tuple
inter = comb_explicit_rhs
symsystem2.compute_explicit_form()
assert simplify(symsystem2.comb_explicit_rhs - inter) == zeros(5, 1)
assert symsystem2.output_eqns == out_eqns
assert symsystem2.bodies == (Pa,)
assert symsystem2.loads == ((P, g * m * N.x),)
def test_form_3():
symsystem3 = SymbolicSystem(states, dyn_implicit_rhs,
mass_matrix=dyn_implicit_mat,
coordinate_derivatives=kin_explicit_rhs,
alg_con=alg_con, coord_idxs=coord_idxs,
speed_idxs=speed_idxs, bodies=bodies,
loads=loads)
assert symsystem3.coordinates == Matrix([x, y])
assert symsystem3.speeds == Matrix([u, v])
assert symsystem3.states == Matrix([x, y, u, v, lam])
assert symsystem3.alg_con == [4]
inter1 = kin_explicit_rhs
inter2 = dyn_implicit_rhs
assert simplify(symsystem3.kin_explicit_rhs - inter1) == zeros(2, 1)
assert simplify(symsystem3.dyn_implicit_mat - dyn_implicit_mat) == zeros(3)
assert simplify(symsystem3.dyn_implicit_rhs - inter2) == zeros(3, 1)
inter = comb_implicit_rhs
assert simplify(symsystem3.comb_implicit_rhs - inter) == zeros(5, 1)
assert simplify(symsystem3.comb_implicit_mat-comb_implicit_mat) == zeros(5)
inter = comb_explicit_rhs
symsystem3.compute_explicit_form()
assert simplify(symsystem3.comb_explicit_rhs - inter) == zeros(5, 1)
assert set(symsystem3.dynamic_symbols()) == {y, v, lam, u, x}
assert type(symsystem3.dynamic_symbols()) == tuple
assert set(symsystem3.constant_symbols()) == {l, g, m}
assert type(symsystem3.constant_symbols()) == tuple
assert symsystem3.output_eqns == {}
assert symsystem3.bodies == (Pa,)
assert symsystem3.loads == ((P, g * m * N.x),)
def test_property_attributes():
symsystem = SymbolicSystem(states, comb_explicit_rhs,
alg_con=alg_con_full, output_eqns=out_eqns,
coord_idxs=coord_idxs, speed_idxs=speed_idxs,
bodies=bodies, loads=loads)
with raises(AttributeError):
symsystem.bodies = 42
with raises(AttributeError):
symsystem.coordinates = 42
with raises(AttributeError):
symsystem.dyn_implicit_rhs = 42
with raises(AttributeError):
symsystem.comb_implicit_rhs = 42
with raises(AttributeError):
symsystem.loads = 42
with raises(AttributeError):
symsystem.dyn_implicit_mat = 42
with raises(AttributeError):
symsystem.comb_implicit_mat = 42
with raises(AttributeError):
symsystem.kin_explicit_rhs = 42
with raises(AttributeError):
symsystem.comb_explicit_rhs = 42
with raises(AttributeError):
symsystem.speeds = 42
with raises(AttributeError):
symsystem.states = 42
with raises(AttributeError):
symsystem.alg_con = 42
def test_not_specified_errors():
"""This test will cover errors that arise from trying to access attributes
that were not specified upon object creation or were specified on creation
and the user tries to recalculate them."""
# Trying to access form 2 when form 1 given
# Trying to access form 3 when form 2 given
symsystem1 = SymbolicSystem(states, comb_explicit_rhs)
with raises(AttributeError):
symsystem1.comb_implicit_mat
with raises(AttributeError):
symsystem1.comb_implicit_rhs
with raises(AttributeError):
symsystem1.dyn_implicit_mat
with raises(AttributeError):
symsystem1.dyn_implicit_rhs
with raises(AttributeError):
symsystem1.kin_explicit_rhs
with raises(AttributeError):
symsystem1.compute_explicit_form()
symsystem2 = SymbolicSystem(coordinates, comb_implicit_rhs, speeds=speeds,
mass_matrix=comb_implicit_mat)
with raises(AttributeError):
symsystem2.dyn_implicit_mat
with raises(AttributeError):
symsystem2.dyn_implicit_rhs
with raises(AttributeError):
symsystem2.kin_explicit_rhs
# Attribute error when trying to access coordinates and speeds when only the
# states were given.
with raises(AttributeError):
symsystem1.coordinates
with raises(AttributeError):
symsystem1.speeds
# Attribute error when trying to access bodies and loads when they are not
# given
with raises(AttributeError):
symsystem1.bodies
with raises(AttributeError):
symsystem1.loads
# Attribute error when trying to access comb_explicit_rhs before it was
# calculated
with raises(AttributeError):
symsystem2.comb_explicit_rhs
|
c8d380861e2750cbd5d1b0eb5efa850953aa8e0105e97b5ebdbc046662637f82 | from sympy.core.function import expand
from sympy.core.symbol import symbols
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.matrices.dense import Matrix
from sympy.simplify.trigsimp import trigsimp
from sympy.physics.mechanics import (PinJoint, JointsMethod, Body, KanesMethod,
PrismaticJoint, LagrangesMethod, inertia)
from sympy.physics.vector import dynamicsymbols, ReferenceFrame
from sympy.testing.pytest import raises
t = dynamicsymbols._t # type: ignore
def test_jointsmethod():
P = Body('P')
C = Body('C')
Pin = PinJoint('P1', P, C)
C_ixx, g = symbols('C_ixx g')
theta, omega = dynamicsymbols('theta_P1, omega_P1')
P.apply_force(g*P.y)
method = JointsMethod(P, Pin)
assert method.frame == P.frame
assert method.bodies == [C, P]
assert method.loads == [(P.masscenter, g*P.frame.y)]
assert method.q == [theta]
assert method.u == [omega]
assert method.kdes == [omega - theta.diff()]
soln = method.form_eoms()
assert soln == Matrix([[-C_ixx*omega.diff()]])
assert method.forcing_full == Matrix([[omega], [0]])
assert method.mass_matrix_full == Matrix([[1, 0], [0, C_ixx]])
assert isinstance(method.method, KanesMethod)
def test_jointmethod_duplicate_coordinates_speeds():
P = Body('P')
C = Body('C')
T = Body('T')
q, u = dynamicsymbols('q u')
P1 = PinJoint('P1', P, C, q)
P2 = PrismaticJoint('P2', C, T, q)
raises(ValueError, lambda: JointsMethod(P, P1, P2))
P1 = PinJoint('P1', P, C, speeds=u)
P2 = PrismaticJoint('P2', C, T, speeds=u)
raises(ValueError, lambda: JointsMethod(P, P1, P2))
P1 = PinJoint('P1', P, C, q, u)
P2 = PrismaticJoint('P2', C, T, q, u)
raises(ValueError, lambda: JointsMethod(P, P1, P2))
def test_complete_simple_double_pendulum():
q1, q2 = dynamicsymbols('q1 q2')
u1, u2 = dynamicsymbols('u1 u2')
m, l, g = symbols('m l g')
C = Body('C') # ceiling
PartP = Body('P', mass=m)
PartR = Body('R', mass=m)
J1 = PinJoint('J1', C, PartP, speeds=u1, coordinates=q1,
child_joint_pos=-l*PartP.x, parent_axis=C.z,
child_axis=PartP.z)
J2 = PinJoint('J2', PartP, PartR, speeds=u2, coordinates=q2,
child_joint_pos=-l*PartR.x, parent_axis=PartP.z,
child_axis=PartR.z)
PartP.apply_force(m*g*C.x)
PartR.apply_force(m*g*C.x)
method = JointsMethod(C, J1, J2)
method.form_eoms()
assert expand(method.mass_matrix_full) == Matrix([[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 2*l**2*m*cos(q2) + 3*l**2*m, l**2*m*cos(q2) + l**2*m],
[0, 0, l**2*m*cos(q2) + l**2*m, l**2*m]])
assert trigsimp(method.forcing_full) == trigsimp(Matrix([[u1], [u2], [-g*l*m*(sin(q1 + q2) + sin(q1)) -
g*l*m*sin(q1) + l**2*m*(2*u1 + u2)*u2*sin(q2)],
[-g*l*m*sin(q1 + q2) - l**2*m*u1**2*sin(q2)]]))
def test_two_dof_joints():
q1, q2, u1, u2 = dynamicsymbols('q1 q2 u1 u2')
m, c1, c2, k1, k2 = symbols('m c1 c2 k1 k2')
W = Body('W')
B1 = Body('B1', mass=m)
B2 = Body('B2', mass=m)
J1 = PrismaticJoint('J1', W, B1, coordinates=q1, speeds=u1)
J2 = PrismaticJoint('J2', B1, B2, coordinates=q2, speeds=u2)
W.apply_force(k1*q1*W.x, reaction_body=B1)
W.apply_force(c1*u1*W.x, reaction_body=B1)
B1.apply_force(k2*q2*W.x, reaction_body=B2)
B1.apply_force(c2*u2*W.x, reaction_body=B2)
method = JointsMethod(W, J1, J2)
method.form_eoms()
MM = method.mass_matrix
forcing = method.forcing
rhs = MM.LUsolve(forcing)
assert expand(rhs[0]) == expand((-k1 * q1 - c1 * u1 + k2 * q2 + c2 * u2)/m)
assert expand(rhs[1]) == expand((k1 * q1 + c1 * u1 - 2 * k2 * q2 - 2 *
c2 * u2) / m)
def test_simple_pedulum():
l, m, g = symbols('l m g')
C = Body('C')
b = Body('b', mass=m)
q = dynamicsymbols('q')
P = PinJoint('P', C, b, speeds=q.diff(t), coordinates=q, child_joint_pos = -l*b.x,
parent_axis=C.z, child_axis=b.z)
b.potential_energy = - m * g * l * cos(q)
method = JointsMethod(C, P)
method.form_eoms(LagrangesMethod)
rhs = method.rhs()
assert rhs[1] == -g*sin(q)/l
def test_chaos_pendulum():
#https://www.pydy.org/examples/chaos_pendulum.html
mA, mB, lA, lB, IAxx, IBxx, IByy, IBzz, g = symbols('mA, mB, lA, lB, IAxx, IBxx, IByy, IBzz, g')
theta, phi, omega, alpha = dynamicsymbols('theta phi omega alpha')
A = ReferenceFrame('A')
B = ReferenceFrame('B')
rod = Body('rod', mass=mA, frame=A, central_inertia=inertia(A, IAxx, IAxx, 0))
plate = Body('plate', mass=mB, frame=B, central_inertia=inertia(B, IBxx, IByy, IBzz))
C = Body('C')
J1 = PinJoint('J1', C, rod, coordinates=theta, speeds=omega,
child_joint_pos=-lA*rod.z, parent_axis=C.y, child_axis=rod.y)
J2 = PinJoint('J2', rod, plate, coordinates=phi, speeds=alpha,
parent_joint_pos=(lB-lA)*rod.z, parent_axis=rod.z, child_axis=plate.z)
rod.apply_force(mA*g*C.z)
plate.apply_force(mB*g*C.z)
method = JointsMethod(C, J1, J2)
method.form_eoms()
MM = method.mass_matrix
forcing = method.forcing
rhs = MM.LUsolve(forcing)
xd = (-2 * IBxx * alpha * omega * sin(phi) * cos(phi) + 2 * IByy * alpha * omega * sin(phi) *
cos(phi) - g * lA * mA * sin(theta) - g * lB * mB * sin(theta)) / (IAxx + IBxx *
sin(phi)**2 + IByy * cos(phi)**2 + lA**2 * mA + lB**2 * mB)
assert (rhs[0] - xd).simplify() == 0
xd = (IBxx - IByy) * omega**2 * sin(phi) * cos(phi) / IBzz
assert (rhs[1] - xd).simplify() == 0
|
828ee9f513be2b2c73ac79c37b2045bb8938a87afc5fc26cf17b4634f4ad08b6 | from sympy.core.evalf import evalf
from sympy.core.numbers import pi
from sympy.core.symbol import symbols
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import acos, sin, cos
from sympy.matrices.dense import Matrix
from sympy.physics.mechanics import (ReferenceFrame, dynamicsymbols,
KanesMethod, inertia, msubs, Point, RigidBody, dot)
from sympy.testing.pytest import slow, ON_TRAVIS, skip
@slow
def test_bicycle():
if ON_TRAVIS:
skip("Too slow for travis.")
# Code to get equations of motion for a bicycle modeled as in:
# J.P Meijaard, Jim M Papadopoulos, Andy Ruina and A.L Schwab. Linearized
# dynamics equations for the balance and steer of a bicycle: a benchmark
# and review. Proceedings of The Royal Society (2007) 463, 1955-1982
# doi: 10.1098/rspa.2007.1857
# Note that this code has been crudely ported from Autolev, which is the
# reason for some of the unusual naming conventions. It was purposefully as
# similar as possible in order to aide debugging.
# Declare Coordinates & Speeds
# Simple definitions for qdots - qd = u
# Speeds are: yaw frame ang. rate, roll frame ang. rate, rear wheel frame
# ang. rate (spinning motion), frame ang. rate (pitching motion), steering
# frame ang. rate, and front wheel ang. rate (spinning motion).
# Wheel positions are ignorable coordinates, so they are not introduced.
q1, q2, q4, q5 = dynamicsymbols('q1 q2 q4 q5')
q1d, q2d, q4d, q5d = dynamicsymbols('q1 q2 q4 q5', 1)
u1, u2, u3, u4, u5, u6 = dynamicsymbols('u1 u2 u3 u4 u5 u6')
u1d, u2d, u3d, u4d, u5d, u6d = dynamicsymbols('u1 u2 u3 u4 u5 u6', 1)
# Declare System's Parameters
WFrad, WRrad, htangle, forkoffset = symbols('WFrad WRrad htangle forkoffset')
forklength, framelength, forkcg1 = symbols('forklength framelength forkcg1')
forkcg3, framecg1, framecg3, Iwr11 = symbols('forkcg3 framecg1 framecg3 Iwr11')
Iwr22, Iwf11, Iwf22, Iframe11 = symbols('Iwr22 Iwf11 Iwf22 Iframe11')
Iframe22, Iframe33, Iframe31, Ifork11 = symbols('Iframe22 Iframe33 Iframe31 Ifork11')
Ifork22, Ifork33, Ifork31, g = symbols('Ifork22 Ifork33 Ifork31 g')
mframe, mfork, mwf, mwr = symbols('mframe mfork mwf mwr')
# Set up reference frames for the system
# N - inertial
# Y - yaw
# R - roll
# WR - rear wheel, rotation angle is ignorable coordinate so not oriented
# Frame - bicycle frame
# TempFrame - statically rotated frame for easier reference inertia definition
# Fork - bicycle fork
# TempFork - statically rotated frame for easier reference inertia definition
# WF - front wheel, again posses a ignorable coordinate
N = ReferenceFrame('N')
Y = N.orientnew('Y', 'Axis', [q1, N.z])
R = Y.orientnew('R', 'Axis', [q2, Y.x])
Frame = R.orientnew('Frame', 'Axis', [q4 + htangle, R.y])
WR = ReferenceFrame('WR')
TempFrame = Frame.orientnew('TempFrame', 'Axis', [-htangle, Frame.y])
Fork = Frame.orientnew('Fork', 'Axis', [q5, Frame.x])
TempFork = Fork.orientnew('TempFork', 'Axis', [-htangle, Fork.y])
WF = ReferenceFrame('WF')
# Kinematics of the Bicycle First block of code is forming the positions of
# the relevant points
# rear wheel contact -> rear wheel mass center -> frame mass center +
# frame/fork connection -> fork mass center + front wheel mass center ->
# front wheel contact point
WR_cont = Point('WR_cont')
WR_mc = WR_cont.locatenew('WR_mc', WRrad * R.z)
Steer = WR_mc.locatenew('Steer', framelength * Frame.z)
Frame_mc = WR_mc.locatenew('Frame_mc', - framecg1 * Frame.x
+ framecg3 * Frame.z)
Fork_mc = Steer.locatenew('Fork_mc', - forkcg1 * Fork.x
+ forkcg3 * Fork.z)
WF_mc = Steer.locatenew('WF_mc', forklength * Fork.x + forkoffset * Fork.z)
WF_cont = WF_mc.locatenew('WF_cont', WFrad * (dot(Fork.y, Y.z) * Fork.y -
Y.z).normalize())
# Set the angular velocity of each frame.
# Angular accelerations end up being calculated automatically by
# differentiating the angular velocities when first needed.
# u1 is yaw rate
# u2 is roll rate
# u3 is rear wheel rate
# u4 is frame pitch rate
# u5 is fork steer rate
# u6 is front wheel rate
Y.set_ang_vel(N, u1 * Y.z)
R.set_ang_vel(Y, u2 * R.x)
WR.set_ang_vel(Frame, u3 * Frame.y)
Frame.set_ang_vel(R, u4 * Frame.y)
Fork.set_ang_vel(Frame, u5 * Fork.x)
WF.set_ang_vel(Fork, u6 * Fork.y)
# Form the velocities of the previously defined points, using the 2 - point
# theorem (written out by hand here). Accelerations again are calculated
# automatically when first needed.
WR_cont.set_vel(N, 0)
WR_mc.v2pt_theory(WR_cont, N, WR)
Steer.v2pt_theory(WR_mc, N, Frame)
Frame_mc.v2pt_theory(WR_mc, N, Frame)
Fork_mc.v2pt_theory(Steer, N, Fork)
WF_mc.v2pt_theory(Steer, N, Fork)
WF_cont.v2pt_theory(WF_mc, N, WF)
# Sets the inertias of each body. Uses the inertia frame to construct the
# inertia dyadics. Wheel inertias are only defined by principle moments of
# inertia, and are in fact constant in the frame and fork reference frames;
# it is for this reason that the orientations of the wheels does not need
# to be defined. The frame and fork inertias are defined in the 'Temp'
# frames which are fixed to the appropriate body frames; this is to allow
# easier input of the reference values of the benchmark paper. Note that
# due to slightly different orientations, the products of inertia need to
# have their signs flipped; this is done later when entering the numerical
# value.
Frame_I = (inertia(TempFrame, Iframe11, Iframe22, Iframe33, 0, 0, Iframe31), Frame_mc)
Fork_I = (inertia(TempFork, Ifork11, Ifork22, Ifork33, 0, 0, Ifork31), Fork_mc)
WR_I = (inertia(Frame, Iwr11, Iwr22, Iwr11), WR_mc)
WF_I = (inertia(Fork, Iwf11, Iwf22, Iwf11), WF_mc)
# Declaration of the RigidBody containers. ::
BodyFrame = RigidBody('BodyFrame', Frame_mc, Frame, mframe, Frame_I)
BodyFork = RigidBody('BodyFork', Fork_mc, Fork, mfork, Fork_I)
BodyWR = RigidBody('BodyWR', WR_mc, WR, mwr, WR_I)
BodyWF = RigidBody('BodyWF', WF_mc, WF, mwf, WF_I)
# The kinematic differential equations; they are defined quite simply. Each
# entry in this list is equal to zero.
kd = [q1d - u1, q2d - u2, q4d - u4, q5d - u5]
# The nonholonomic constraints are the velocity of the front wheel contact
# point dotted into the X, Y, and Z directions; the yaw frame is used as it
# is "closer" to the front wheel (1 less DCM connecting them). These
# constraints force the velocity of the front wheel contact point to be 0
# in the inertial frame; the X and Y direction constraints enforce a
# "no-slip" condition, and the Z direction constraint forces the front
# wheel contact point to not move away from the ground frame, essentially
# replicating the holonomic constraint which does not allow the frame pitch
# to change in an invalid fashion.
conlist_speed = [WF_cont.vel(N) & Y.x, WF_cont.vel(N) & Y.y, WF_cont.vel(N) & Y.z]
# The holonomic constraint is that the position from the rear wheel contact
# point to the front wheel contact point when dotted into the
# normal-to-ground plane direction must be zero; effectively that the front
# and rear wheel contact points are always touching the ground plane. This
# is actually not part of the dynamic equations, but instead is necessary
# for the lineraization process.
conlist_coord = [WF_cont.pos_from(WR_cont) & Y.z]
# The force list; each body has the appropriate gravitational force applied
# at its mass center.
FL = [(Frame_mc, -mframe * g * Y.z),
(Fork_mc, -mfork * g * Y.z),
(WF_mc, -mwf * g * Y.z),
(WR_mc, -mwr * g * Y.z)]
BL = [BodyFrame, BodyFork, BodyWR, BodyWF]
# The N frame is the inertial frame, coordinates are supplied in the order
# of independent, dependent coordinates, as are the speeds. The kinematic
# differential equation are also entered here. Here the dependent speeds
# are specified, in the same order they were provided in earlier, along
# with the non-holonomic constraints. The dependent coordinate is also
# provided, with the holonomic constraint. Again, this is only provided
# for the linearization process.
KM = KanesMethod(N, q_ind=[q1, q2, q5],
q_dependent=[q4], configuration_constraints=conlist_coord,
u_ind=[u2, u3, u5],
u_dependent=[u1, u4, u6], velocity_constraints=conlist_speed,
kd_eqs=kd)
(fr, frstar) = KM.kanes_equations(BL, FL)
# This is the start of entering in the numerical values from the benchmark
# paper to validate the eigen values of the linearized equations from this
# model to the reference eigen values. Look at the aforementioned paper for
# more information. Some of these are intermediate values, used to
# transform values from the paper into the coordinate systems used in this
# model.
PaperRadRear = 0.3
PaperRadFront = 0.35
HTA = evalf.N(pi / 2 - pi / 10)
TrailPaper = 0.08
rake = evalf.N(-(TrailPaper*sin(HTA)-(PaperRadFront*cos(HTA))))
PaperWb = 1.02
PaperFrameCgX = 0.3
PaperFrameCgZ = 0.9
PaperForkCgX = 0.9
PaperForkCgZ = 0.7
FrameLength = evalf.N(PaperWb*sin(HTA)-(rake-(PaperRadFront-PaperRadRear)*cos(HTA)))
FrameCGNorm = evalf.N((PaperFrameCgZ - PaperRadRear-(PaperFrameCgX/sin(HTA))*cos(HTA))*sin(HTA))
FrameCGPar = evalf.N(PaperFrameCgX / sin(HTA) + (PaperFrameCgZ - PaperRadRear - PaperFrameCgX / sin(HTA) * cos(HTA)) * cos(HTA))
tempa = evalf.N(PaperForkCgZ - PaperRadFront)
tempb = evalf.N(PaperWb-PaperForkCgX)
tempc = evalf.N(sqrt(tempa**2+tempb**2))
PaperForkL = evalf.N(PaperWb*cos(HTA)-(PaperRadFront-PaperRadRear)*sin(HTA))
ForkCGNorm = evalf.N(rake+(tempc * sin(pi/2-HTA-acos(tempa/tempc))))
ForkCGPar = evalf.N(tempc * cos((pi/2-HTA)-acos(tempa/tempc))-PaperForkL)
# Here is the final assembly of the numerical values. The symbol 'v' is the
# forward speed of the bicycle (a concept which only makes sense in the
# upright, static equilibrium case?). These are in a dictionary which will
# later be substituted in. Again the sign on the *product* of inertia
# values is flipped here, due to different orientations of coordinate
# systems.
v = symbols('v')
val_dict = {WFrad: PaperRadFront,
WRrad: PaperRadRear,
htangle: HTA,
forkoffset: rake,
forklength: PaperForkL,
framelength: FrameLength,
forkcg1: ForkCGPar,
forkcg3: ForkCGNorm,
framecg1: FrameCGNorm,
framecg3: FrameCGPar,
Iwr11: 0.0603,
Iwr22: 0.12,
Iwf11: 0.1405,
Iwf22: 0.28,
Ifork11: 0.05892,
Ifork22: 0.06,
Ifork33: 0.00708,
Ifork31: 0.00756,
Iframe11: 9.2,
Iframe22: 11,
Iframe33: 2.8,
Iframe31: -2.4,
mfork: 4,
mframe: 85,
mwf: 3,
mwr: 2,
g: 9.81,
q1: 0,
q2: 0,
q4: 0,
q5: 0,
u1: 0,
u2: 0,
u3: v / PaperRadRear,
u4: 0,
u5: 0,
u6: v / PaperRadFront}
# Linearizes the forcing vector; the equations are set up as MM udot =
# forcing, where MM is the mass matrix, udot is the vector representing the
# time derivatives of the generalized speeds, and forcing is a vector which
# contains both external forcing terms and internal forcing terms, such as
# centripital or coriolis forces. This actually returns a matrix with as
# many rows as *total* coordinates and speeds, but only as many columns as
# independent coordinates and speeds.
forcing_lin = KM.linearize()[0]
# As mentioned above, the size of the linearized forcing terms is expanded
# to include both q's and u's, so the mass matrix must have this done as
# well. This will likely be changed to be part of the linearized process,
# for future reference.
MM_full = KM.mass_matrix_full
MM_full_s = msubs(MM_full, val_dict)
forcing_lin_s = msubs(forcing_lin, KM.kindiffdict(), val_dict)
MM_full_s = MM_full_s.evalf()
forcing_lin_s = forcing_lin_s.evalf()
# Finally, we construct an "A" matrix for the form xdot = A x (x being the
# state vector, although in this case, the sizes are a little off). The
# following line extracts only the minimum entries required for eigenvalue
# analysis, which correspond to rows and columns for lean, steer, lean
# rate, and steer rate.
Amat = MM_full_s.inv() * forcing_lin_s
A = Amat.extract([1, 2, 4, 6], [1, 2, 3, 5])
# Precomputed for comparison
Res = Matrix([[ 0, 0, 1.0, 0],
[ 0, 0, 0, 1.0],
[9.48977444677355, -0.891197738059089*v**2 - 0.571523173729245, -0.105522449805691*v, -0.330515398992311*v],
[11.7194768719633, -1.97171508499972*v**2 + 30.9087533932407, 3.67680523332152*v, -3.08486552743311*v]])
# Actual eigenvalue comparison
eps = 1.e-12
for i in range(6):
error = Res.subs(v, i) - A.subs(v, i)
assert all(abs(x) < eps for x in error)
|
dccc1e43fa9f6f273c5aa712bef8fb88a40b45d325922f52eae37277c6480cdd | from sympy.core.backend import cos, Matrix, sin, zeros, tan, pi, symbols
from sympy.simplify.simplify import simplify
from sympy.simplify.trigsimp import trigsimp
from sympy.solvers.solvers import solve
from sympy.physics.mechanics import (cross, dot, dynamicsymbols,
find_dynamicsymbols, KanesMethod, inertia,
inertia_of_point_mass, Point,
ReferenceFrame, RigidBody)
def test_aux_dep():
# This test is about rolling disc dynamics, comparing the results found
# with KanesMethod to those found when deriving the equations "manually"
# with SymPy.
# The terms Fr, Fr*, and Fr*_steady are all compared between the two
# methods. Here, Fr*_steady refers to the generalized inertia forces for an
# equilibrium configuration.
# Note: comparing to the test of test_rolling_disc() in test_kane.py, this
# test also tests auxiliary speeds and configuration and motion constraints
#, seen in the generalized dependent coordinates q[3], and depend speeds
# u[3], u[4] and u[5].
# First, manual derivation of Fr, Fr_star, Fr_star_steady.
# Symbols for time and constant parameters.
# Symbols for contact forces: Fx, Fy, Fz.
t, r, m, g, I, J = symbols('t r m g I J')
Fx, Fy, Fz = symbols('Fx Fy Fz')
# Configuration variables and their time derivatives:
# q[0] -- yaw
# q[1] -- lean
# q[2] -- spin
# q[3] -- dot(-r*B.z, A.z) -- distance from ground plane to disc center in
# A.z direction
# Generalized speeds and their time derivatives:
# u[0] -- disc angular velocity component, disc fixed x direction
# u[1] -- disc angular velocity component, disc fixed y direction
# u[2] -- disc angular velocity component, disc fixed z direction
# u[3] -- disc velocity component, A.x direction
# u[4] -- disc velocity component, A.y direction
# u[5] -- disc velocity component, A.z direction
# Auxiliary generalized speeds:
# ua[0] -- contact point auxiliary generalized speed, A.x direction
# ua[1] -- contact point auxiliary generalized speed, A.y direction
# ua[2] -- contact point auxiliary generalized speed, A.z direction
q = dynamicsymbols('q:4')
qd = [qi.diff(t) for qi in q]
u = dynamicsymbols('u:6')
ud = [ui.diff(t) for ui in u]
ud_zero = dict(zip(ud, [0.]*len(ud)))
ua = dynamicsymbols('ua:3')
ua_zero = dict(zip(ua, [0.]*len(ua))) # noqa:F841
# Reference frames:
# Yaw intermediate frame: A.
# Lean intermediate frame: B.
# Disc fixed frame: C.
N = ReferenceFrame('N')
A = N.orientnew('A', 'Axis', [q[0], N.z])
B = A.orientnew('B', 'Axis', [q[1], A.x])
C = B.orientnew('C', 'Axis', [q[2], B.y])
# Angular velocity and angular acceleration of disc fixed frame
# u[0], u[1] and u[2] are generalized independent speeds.
C.set_ang_vel(N, u[0]*B.x + u[1]*B.y + u[2]*B.z)
C.set_ang_acc(N, C.ang_vel_in(N).diff(t, B)
+ cross(B.ang_vel_in(N), C.ang_vel_in(N)))
# Velocity and acceleration of points:
# Disc-ground contact point: P.
# Center of disc: O, defined from point P with depend coordinate: q[3]
# u[3], u[4] and u[5] are generalized dependent speeds.
P = Point('P')
P.set_vel(N, ua[0]*A.x + ua[1]*A.y + ua[2]*A.z)
O = P.locatenew('O', q[3]*A.z + r*sin(q[1])*A.y)
O.set_vel(N, u[3]*A.x + u[4]*A.y + u[5]*A.z)
O.set_acc(N, O.vel(N).diff(t, A) + cross(A.ang_vel_in(N), O.vel(N)))
# Kinematic differential equations:
# Two equalities: one is w_c_n_qd = C.ang_vel_in(N) in three coordinates
# directions of B, for qd0, qd1 and qd2.
# the other is v_o_n_qd = O.vel(N) in A.z direction for qd3.
# Then, solve for dq/dt's in terms of u's: qd_kd.
w_c_n_qd = qd[0]*A.z + qd[1]*B.x + qd[2]*B.y
v_o_n_qd = O.pos_from(P).diff(t, A) + cross(A.ang_vel_in(N), O.pos_from(P))
kindiffs = Matrix([dot(w_c_n_qd - C.ang_vel_in(N), uv) for uv in B] +
[dot(v_o_n_qd - O.vel(N), A.z)])
qd_kd = solve(kindiffs, qd) # noqa:F841
# Values of generalized speeds during a steady turn for later substitution
# into the Fr_star_steady.
steady_conditions = solve(kindiffs.subs({qd[1] : 0, qd[3] : 0}), u)
steady_conditions.update({qd[1] : 0, qd[3] : 0})
# Partial angular velocities and velocities.
partial_w_C = [C.ang_vel_in(N).diff(ui, N) for ui in u + ua]
partial_v_O = [O.vel(N).diff(ui, N) for ui in u + ua]
partial_v_P = [P.vel(N).diff(ui, N) for ui in u + ua]
# Configuration constraint: f_c, the projection of radius r in A.z direction
# is q[3].
# Velocity constraints: f_v, for u3, u4 and u5.
# Acceleration constraints: f_a.
f_c = Matrix([dot(-r*B.z, A.z) - q[3]])
f_v = Matrix([dot(O.vel(N) - (P.vel(N) + cross(C.ang_vel_in(N),
O.pos_from(P))), ai).expand() for ai in A])
v_o_n = cross(C.ang_vel_in(N), O.pos_from(P))
a_o_n = v_o_n.diff(t, A) + cross(A.ang_vel_in(N), v_o_n)
f_a = Matrix([dot(O.acc(N) - a_o_n, ai) for ai in A]) # noqa:F841
# Solve for constraint equations in the form of
# u_dependent = A_rs * [u_i; u_aux].
# First, obtain constraint coefficient matrix: M_v * [u; ua] = 0;
# Second, taking u[0], u[1], u[2] as independent,
# taking u[3], u[4], u[5] as dependent,
# rearranging the matrix of M_v to be A_rs for u_dependent.
# Third, u_aux ==0 for u_dep, and resulting dictionary of u_dep_dict.
M_v = zeros(3, 9)
for i in range(3):
for j, ui in enumerate(u + ua):
M_v[i, j] = f_v[i].diff(ui)
M_v_i = M_v[:, :3]
M_v_d = M_v[:, 3:6]
M_v_aux = M_v[:, 6:]
M_v_i_aux = M_v_i.row_join(M_v_aux)
A_rs = - M_v_d.inv() * M_v_i_aux
u_dep = A_rs[:, :3] * Matrix(u[:3])
u_dep_dict = dict(zip(u[3:], u_dep))
# Active forces: F_O acting on point O; F_P acting on point P.
# Generalized active forces (unconstrained): Fr_u = F_point * pv_point.
F_O = m*g*A.z
F_P = Fx * A.x + Fy * A.y + Fz * A.z
Fr_u = Matrix([dot(F_O, pv_o) + dot(F_P, pv_p) for pv_o, pv_p in
zip(partial_v_O, partial_v_P)])
# Inertia force: R_star_O.
# Inertia of disc: I_C_O, where J is a inertia component about principal axis.
# Inertia torque: T_star_C.
# Generalized inertia forces (unconstrained): Fr_star_u.
R_star_O = -m*O.acc(N)
I_C_O = inertia(B, I, J, I)
T_star_C = -(dot(I_C_O, C.ang_acc_in(N)) \
+ cross(C.ang_vel_in(N), dot(I_C_O, C.ang_vel_in(N))))
Fr_star_u = Matrix([dot(R_star_O, pv) + dot(T_star_C, pav) for pv, pav in
zip(partial_v_O, partial_w_C)])
# Form nonholonomic Fr: Fr_c, and nonholonomic Fr_star: Fr_star_c.
# Also, nonholonomic Fr_star in steady turning condition: Fr_star_steady.
Fr_c = Fr_u[:3, :].col_join(Fr_u[6:, :]) + A_rs.T * Fr_u[3:6, :]
Fr_star_c = Fr_star_u[:3, :].col_join(Fr_star_u[6:, :])\
+ A_rs.T * Fr_star_u[3:6, :]
Fr_star_steady = Fr_star_c.subs(ud_zero).subs(u_dep_dict)\
.subs(steady_conditions).subs({q[3]: -r*cos(q[1])}).expand()
# Second, using KaneMethod in mechanics for fr, frstar and frstar_steady.
# Rigid Bodies: disc, with inertia I_C_O.
iner_tuple = (I_C_O, O)
disc = RigidBody('disc', O, C, m, iner_tuple)
bodyList = [disc]
# Generalized forces: Gravity: F_o; Auxiliary forces: F_p.
F_o = (O, F_O)
F_p = (P, F_P)
forceList = [F_o, F_p]
# KanesMethod.
kane = KanesMethod(
N, q_ind= q[:3], u_ind= u[:3], kd_eqs=kindiffs,
q_dependent=q[3:], configuration_constraints = f_c,
u_dependent=u[3:], velocity_constraints= f_v,
u_auxiliary=ua
)
# fr, frstar, frstar_steady and kdd(kinematic differential equations).
(fr, frstar)= kane.kanes_equations(bodyList, forceList)
frstar_steady = frstar.subs(ud_zero).subs(u_dep_dict).subs(steady_conditions)\
.subs({q[3]: -r*cos(q[1])}).expand()
kdd = kane.kindiffdict()
assert Matrix(Fr_c).expand() == fr.expand()
assert Matrix(Fr_star_c.subs(kdd)).expand() == frstar.expand()
assert (simplify(Matrix(Fr_star_steady).expand()) ==
simplify(frstar_steady.expand()))
syms_in_forcing = find_dynamicsymbols(kane.forcing)
for qdi in qd:
assert qdi not in syms_in_forcing
def test_non_central_inertia():
# This tests that the calculation of Fr* does not depend the point
# about which the inertia of a rigid body is defined. This test solves
# exercises 8.12, 8.17 from Kane 1985.
# Declare symbols
q1, q2, q3 = dynamicsymbols('q1:4')
q1d, q2d, q3d = dynamicsymbols('q1:4', level=1)
u1, u2, u3, u4, u5 = dynamicsymbols('u1:6')
u_prime, R, M, g, e, f, theta = symbols('u\' R, M, g, e, f, theta')
a, b, mA, mB, IA, J, K, t = symbols('a b mA mB IA J K t')
Q1, Q2, Q3 = symbols('Q1, Q2 Q3')
IA22, IA23, IA33 = symbols('IA22 IA23 IA33')
# Reference Frames
F = ReferenceFrame('F')
P = F.orientnew('P', 'axis', [-theta, F.y])
A = P.orientnew('A', 'axis', [q1, P.x])
A.set_ang_vel(F, u1*A.x + u3*A.z)
# define frames for wheels
B = A.orientnew('B', 'axis', [q2, A.z])
C = A.orientnew('C', 'axis', [q3, A.z])
B.set_ang_vel(A, u4 * A.z)
C.set_ang_vel(A, u5 * A.z)
# define points D, S*, Q on frame A and their velocities
pD = Point('D')
pD.set_vel(A, 0)
# u3 will not change v_D_F since wheels are still assumed to roll without slip.
pD.set_vel(F, u2 * A.y)
pS_star = pD.locatenew('S*', e*A.y)
pQ = pD.locatenew('Q', f*A.y - R*A.x)
for p in [pS_star, pQ]:
p.v2pt_theory(pD, F, A)
# masscenters of bodies A, B, C
pA_star = pD.locatenew('A*', a*A.y)
pB_star = pD.locatenew('B*', b*A.z)
pC_star = pD.locatenew('C*', -b*A.z)
for p in [pA_star, pB_star, pC_star]:
p.v2pt_theory(pD, F, A)
# points of B, C touching the plane P
pB_hat = pB_star.locatenew('B^', -R*A.x)
pC_hat = pC_star.locatenew('C^', -R*A.x)
pB_hat.v2pt_theory(pB_star, F, B)
pC_hat.v2pt_theory(pC_star, F, C)
# the velocities of B^, C^ are zero since B, C are assumed to roll without slip
kde = [q1d - u1, q2d - u4, q3d - u5]
vc = [dot(p.vel(F), A.y) for p in [pB_hat, pC_hat]]
# inertias of bodies A, B, C
# IA22, IA23, IA33 are not specified in the problem statement, but are
# necessary to define an inertia object. Although the values of
# IA22, IA23, IA33 are not known in terms of the variables given in the
# problem statement, they do not appear in the general inertia terms.
inertia_A = inertia(A, IA, IA22, IA33, 0, IA23, 0)
inertia_B = inertia(B, K, K, J)
inertia_C = inertia(C, K, K, J)
# define the rigid bodies A, B, C
rbA = RigidBody('rbA', pA_star, A, mA, (inertia_A, pA_star))
rbB = RigidBody('rbB', pB_star, B, mB, (inertia_B, pB_star))
rbC = RigidBody('rbC', pC_star, C, mB, (inertia_C, pC_star))
km = KanesMethod(F, q_ind=[q1, q2, q3], u_ind=[u1, u2], kd_eqs=kde,
u_dependent=[u4, u5], velocity_constraints=vc,
u_auxiliary=[u3])
forces = [(pS_star, -M*g*F.x), (pQ, Q1*A.x + Q2*A.y + Q3*A.z)]
bodies = [rbA, rbB, rbC]
fr, fr_star = km.kanes_equations(bodies, forces)
vc_map = solve(vc, [u4, u5])
# KanesMethod returns the negative of Fr, Fr* as defined in Kane1985.
fr_star_expected = Matrix([
-(IA + 2*J*b**2/R**2 + 2*K +
mA*a**2 + 2*mB*b**2) * u1.diff(t) - mA*a*u1*u2,
-(mA + 2*mB +2*J/R**2) * u2.diff(t) + mA*a*u1**2,
0])
t = trigsimp(fr_star.subs(vc_map).subs({u3: 0})).doit().expand()
assert ((fr_star_expected - t).expand() == zeros(3, 1))
# define inertias of rigid bodies A, B, C about point D
# I_S/O = I_S/S* + I_S*/O
bodies2 = []
for rb, I_star in zip([rbA, rbB, rbC], [inertia_A, inertia_B, inertia_C]):
I = I_star + inertia_of_point_mass(rb.mass,
rb.masscenter.pos_from(pD),
rb.frame)
bodies2.append(RigidBody('', rb.masscenter, rb.frame, rb.mass,
(I, pD)))
fr2, fr_star2 = km.kanes_equations(bodies2, forces)
t = trigsimp(fr_star2.subs(vc_map).subs({u3: 0})).doit()
assert (fr_star_expected - t).expand() == zeros(3, 1)
def test_sub_qdot():
# This test solves exercises 8.12, 8.17 from Kane 1985 and defines
# some velocities in terms of q, qdot.
## --- Declare symbols ---
q1, q2, q3 = dynamicsymbols('q1:4')
q1d, q2d, q3d = dynamicsymbols('q1:4', level=1)
u1, u2, u3 = dynamicsymbols('u1:4')
u_prime, R, M, g, e, f, theta = symbols('u\' R, M, g, e, f, theta')
a, b, mA, mB, IA, J, K, t = symbols('a b mA mB IA J K t')
IA22, IA23, IA33 = symbols('IA22 IA23 IA33')
Q1, Q2, Q3 = symbols('Q1 Q2 Q3')
# --- Reference Frames ---
F = ReferenceFrame('F')
P = F.orientnew('P', 'axis', [-theta, F.y])
A = P.orientnew('A', 'axis', [q1, P.x])
A.set_ang_vel(F, u1*A.x + u3*A.z)
# define frames for wheels
B = A.orientnew('B', 'axis', [q2, A.z])
C = A.orientnew('C', 'axis', [q3, A.z])
## --- define points D, S*, Q on frame A and their velocities ---
pD = Point('D')
pD.set_vel(A, 0)
# u3 will not change v_D_F since wheels are still assumed to roll w/o slip
pD.set_vel(F, u2 * A.y)
pS_star = pD.locatenew('S*', e*A.y)
pQ = pD.locatenew('Q', f*A.y - R*A.x)
# masscenters of bodies A, B, C
pA_star = pD.locatenew('A*', a*A.y)
pB_star = pD.locatenew('B*', b*A.z)
pC_star = pD.locatenew('C*', -b*A.z)
for p in [pS_star, pQ, pA_star, pB_star, pC_star]:
p.v2pt_theory(pD, F, A)
# points of B, C touching the plane P
pB_hat = pB_star.locatenew('B^', -R*A.x)
pC_hat = pC_star.locatenew('C^', -R*A.x)
pB_hat.v2pt_theory(pB_star, F, B)
pC_hat.v2pt_theory(pC_star, F, C)
# --- relate qdot, u ---
# the velocities of B^, C^ are zero since B, C are assumed to roll w/o slip
kde = [dot(p.vel(F), A.y) for p in [pB_hat, pC_hat]]
kde += [u1 - q1d]
kde_map = solve(kde, [q1d, q2d, q3d])
for k, v in list(kde_map.items()):
kde_map[k.diff(t)] = v.diff(t)
# inertias of bodies A, B, C
# IA22, IA23, IA33 are not specified in the problem statement, but are
# necessary to define an inertia object. Although the values of
# IA22, IA23, IA33 are not known in terms of the variables given in the
# problem statement, they do not appear in the general inertia terms.
inertia_A = inertia(A, IA, IA22, IA33, 0, IA23, 0)
inertia_B = inertia(B, K, K, J)
inertia_C = inertia(C, K, K, J)
# define the rigid bodies A, B, C
rbA = RigidBody('rbA', pA_star, A, mA, (inertia_A, pA_star))
rbB = RigidBody('rbB', pB_star, B, mB, (inertia_B, pB_star))
rbC = RigidBody('rbC', pC_star, C, mB, (inertia_C, pC_star))
## --- use kanes method ---
km = KanesMethod(F, [q1, q2, q3], [u1, u2], kd_eqs=kde, u_auxiliary=[u3])
forces = [(pS_star, -M*g*F.x), (pQ, Q1*A.x + Q2*A.y + Q3*A.z)]
bodies = [rbA, rbB, rbC]
# Q2 = -u_prime * u2 * Q1 / sqrt(u2**2 + f**2 * u1**2)
# -u_prime * R * u2 / sqrt(u2**2 + f**2 * u1**2) = R / Q1 * Q2
fr_expected = Matrix([
f*Q3 + M*g*e*sin(theta)*cos(q1),
Q2 + M*g*sin(theta)*sin(q1),
e*M*g*cos(theta) - Q1*f - Q2*R])
#Q1 * (f - u_prime * R * u2 / sqrt(u2**2 + f**2 * u1**2)))])
fr_star_expected = Matrix([
-(IA + 2*J*b**2/R**2 + 2*K +
mA*a**2 + 2*mB*b**2) * u1.diff(t) - mA*a*u1*u2,
-(mA + 2*mB +2*J/R**2) * u2.diff(t) + mA*a*u1**2,
0])
fr, fr_star = km.kanes_equations(bodies, forces)
assert (fr.expand() == fr_expected.expand())
assert ((fr_star_expected - trigsimp(fr_star)).expand() == zeros(3, 1))
def test_sub_qdot2():
# This test solves exercises 8.3 from Kane 1985 and defines
# all velocities in terms of q, qdot. We check that the generalized active
# forces are correctly computed if u terms are only defined in the
# kinematic differential equations.
#
# This functionality was added in PR 8948. Without qdot/u substitution, the
# KanesMethod constructor will fail during the constraint initialization as
# the B matrix will be poorly formed and inversion of the dependent part
# will fail.
g, m, Px, Py, Pz, R, t = symbols('g m Px Py Pz R t')
q = dynamicsymbols('q:5')
qd = dynamicsymbols('q:5', level=1)
u = dynamicsymbols('u:5')
## Define inertial, intermediate, and rigid body reference frames
A = ReferenceFrame('A')
B_prime = A.orientnew('B_prime', 'Axis', [q[0], A.z])
B = B_prime.orientnew('B', 'Axis', [pi/2 - q[1], B_prime.x])
C = B.orientnew('C', 'Axis', [q[2], B.z])
## Define points of interest and their velocities
pO = Point('O')
pO.set_vel(A, 0)
# R is the point in plane H that comes into contact with disk C.
pR = pO.locatenew('R', q[3]*A.x + q[4]*A.y)
pR.set_vel(A, pR.pos_from(pO).diff(t, A))
pR.set_vel(B, 0)
# C^ is the point in disk C that comes into contact with plane H.
pC_hat = pR.locatenew('C^', 0)
pC_hat.set_vel(C, 0)
# C* is the point at the center of disk C.
pCs = pC_hat.locatenew('C*', R*B.y)
pCs.set_vel(C, 0)
pCs.set_vel(B, 0)
# calculate velocites of points C* and C^ in frame A
pCs.v2pt_theory(pR, A, B) # points C* and R are fixed in frame B
pC_hat.v2pt_theory(pCs, A, C) # points C* and C^ are fixed in frame C
## Define forces on each point of the system
R_C_hat = Px*A.x + Py*A.y + Pz*A.z
R_Cs = -m*g*A.z
forces = [(pC_hat, R_C_hat), (pCs, R_Cs)]
## Define kinematic differential equations
# let ui = omega_C_A & bi (i = 1, 2, 3)
# u4 = qd4, u5 = qd5
u_expr = [C.ang_vel_in(A) & uv for uv in B]
u_expr += qd[3:]
kde = [ui - e for ui, e in zip(u, u_expr)]
km1 = KanesMethod(A, q, u, kde)
fr1, _ = km1.kanes_equations([], forces)
## Calculate generalized active forces if we impose the condition that the
# disk C is rolling without slipping
u_indep = u[:3]
u_dep = list(set(u) - set(u_indep))
vc = [pC_hat.vel(A) & uv for uv in [A.x, A.y]]
km2 = KanesMethod(A, q, u_indep, kde,
u_dependent=u_dep, velocity_constraints=vc)
fr2, _ = km2.kanes_equations([], forces)
fr1_expected = Matrix([
-R*g*m*sin(q[1]),
-R*(Px*cos(q[0]) + Py*sin(q[0]))*tan(q[1]),
R*(Px*cos(q[0]) + Py*sin(q[0])),
Px,
Py])
fr2_expected = Matrix([
-R*g*m*sin(q[1]),
0,
0])
assert (trigsimp(fr1.expand()) == trigsimp(fr1_expected.expand()))
assert (trigsimp(fr2.expand()) == trigsimp(fr2_expected.expand()))
|
5ca48058f7b336057e28d6fcb555654ed3e5cb4f5295ee4f2537a2d2df2106b2 | from sympy.physics.units.definitions.dimension_definitions import current, temperature, amount_of_substance, \
luminous_intensity, angle, charge, voltage, impedance, conductance, capacitance, inductance, magnetic_density, \
magnetic_flux, information
from sympy.core.numbers import (Rational, pi)
from sympy.core.singleton import S as S_singleton
from sympy.physics.units.prefixes import kilo, milli, micro, deci, centi, nano, pico, kibi, mebi, gibi, tebi, pebi, exbi
from sympy.physics.units.quantities import Quantity
One = S_singleton.One
#### UNITS ####
# Dimensionless:
percent = percents = Quantity("percent", latex_repr=r"\%")
percent.set_global_relative_scale_factor(Rational(1, 100), One)
permille = Quantity("permille")
permille.set_global_relative_scale_factor(Rational(1, 1000), One)
# Angular units (dimensionless)
rad = radian = radians = Quantity("radian", abbrev="rad")
radian.set_global_dimension(angle)
deg = degree = degrees = Quantity("degree", abbrev="deg", latex_repr=r"^\circ")
degree.set_global_relative_scale_factor(pi/180, radian)
sr = steradian = steradians = Quantity("steradian", abbrev="sr")
mil = angular_mil = angular_mils = Quantity("angular_mil", abbrev="mil")
# Base units:
m = meter = meters = Quantity("meter", abbrev="m")
# gram; used to define its prefixed units
g = gram = grams = Quantity("gram", abbrev="g")
# NOTE: the `kilogram` has scale factor 1000. In SI, kg is a base unit, but
# nonetheless we are trying to be compatible with the `kilo` prefix. In a
# similar manner, people using CGS or gaussian units could argue that the
# `centimeter` rather than `meter` is the fundamental unit for length, but the
# scale factor of `centimeter` will be kept as 1/100 to be compatible with the
# `centi` prefix. The current state of the code assumes SI unit dimensions, in
# the future this module will be modified in order to be unit system-neutral
# (that is, support all kinds of unit systems).
kg = kilogram = kilograms = Quantity("kilogram", abbrev="kg")
kg.set_global_relative_scale_factor(kilo, gram)
s = second = seconds = Quantity("second", abbrev="s")
A = ampere = amperes = Quantity("ampere", abbrev='A')
ampere.set_global_dimension(current)
K = kelvin = kelvins = Quantity("kelvin", abbrev='K')
kelvin.set_global_dimension(temperature)
mol = mole = moles = Quantity("mole", abbrev="mol")
mole.set_global_dimension(amount_of_substance)
cd = candela = candelas = Quantity("candela", abbrev="cd")
candela.set_global_dimension(luminous_intensity)
mg = milligram = milligrams = Quantity("milligram", abbrev="mg")
mg.set_global_relative_scale_factor(milli, gram)
ug = microgram = micrograms = Quantity("microgram", abbrev="ug", latex_repr=r"\mu\text{g}")
ug.set_global_relative_scale_factor(micro, gram)
# derived units
newton = newtons = N = Quantity("newton", abbrev="N")
joule = joules = J = Quantity("joule", abbrev="J")
watt = watts = W = Quantity("watt", abbrev="W")
pascal = pascals = Pa = pa = Quantity("pascal", abbrev="Pa")
hertz = hz = Hz = Quantity("hertz", abbrev="Hz")
# CGS derived units:
dyne = Quantity("dyne")
dyne.set_global_relative_scale_factor(One/10**5, newton)
erg = Quantity("erg")
erg.set_global_relative_scale_factor(One/10**7, joule)
# MKSA extension to MKS: derived units
coulomb = coulombs = C = Quantity("coulomb", abbrev='C')
coulomb.set_global_dimension(charge)
volt = volts = v = V = Quantity("volt", abbrev='V')
volt.set_global_dimension(voltage)
ohm = ohms = Quantity("ohm", abbrev='ohm', latex_repr=r"\Omega")
ohm.set_global_dimension(impedance)
siemens = S = mho = mhos = Quantity("siemens", abbrev='S')
siemens.set_global_dimension(conductance)
farad = farads = F = Quantity("farad", abbrev='F')
farad.set_global_dimension(capacitance)
henry = henrys = H = Quantity("henry", abbrev='H')
henry.set_global_dimension(inductance)
tesla = teslas = T = Quantity("tesla", abbrev='T')
tesla.set_global_dimension(magnetic_density)
weber = webers = Wb = wb = Quantity("weber", abbrev='Wb')
weber.set_global_dimension(magnetic_flux)
# CGS units for electromagnetic quantities:
statampere = Quantity("statampere")
statcoulomb = statC = franklin = Quantity("statcoulomb", abbrev="statC")
statvolt = Quantity("statvolt")
gauss = Quantity("gauss")
maxwell = Quantity("maxwell")
debye = Quantity("debye")
oersted = Quantity("oersted")
# Other derived units:
optical_power = dioptre = diopter = D = Quantity("dioptre")
lux = lx = Quantity("lux", abbrev="lx")
# katal is the SI unit of catalytic activity
katal = kat = Quantity("katal", abbrev="kat")
# gray is the SI unit of absorbed dose
gray = Gy = Quantity("gray")
# becquerel is the SI unit of radioactivity
becquerel = Bq = Quantity("becquerel", abbrev="Bq")
# Common length units
km = kilometer = kilometers = Quantity("kilometer", abbrev="km")
km.set_global_relative_scale_factor(kilo, meter)
dm = decimeter = decimeters = Quantity("decimeter", abbrev="dm")
dm.set_global_relative_scale_factor(deci, meter)
cm = centimeter = centimeters = Quantity("centimeter", abbrev="cm")
cm.set_global_relative_scale_factor(centi, meter)
mm = millimeter = millimeters = Quantity("millimeter", abbrev="mm")
mm.set_global_relative_scale_factor(milli, meter)
um = micrometer = micrometers = micron = microns = \
Quantity("micrometer", abbrev="um", latex_repr=r'\mu\text{m}')
um.set_global_relative_scale_factor(micro, meter)
nm = nanometer = nanometers = Quantity("nanometer", abbrev="nm")
nm.set_global_relative_scale_factor(nano, meter)
pm = picometer = picometers = Quantity("picometer", abbrev="pm")
pm.set_global_relative_scale_factor(pico, meter)
ft = foot = feet = Quantity("foot", abbrev="ft")
ft.set_global_relative_scale_factor(Rational(3048, 10000), meter)
inch = inches = Quantity("inch")
inch.set_global_relative_scale_factor(Rational(1, 12), foot)
yd = yard = yards = Quantity("yard", abbrev="yd")
yd.set_global_relative_scale_factor(3, feet)
mi = mile = miles = Quantity("mile")
mi.set_global_relative_scale_factor(5280, feet)
nmi = nautical_mile = nautical_miles = Quantity("nautical_mile")
nmi.set_global_relative_scale_factor(6076, feet)
# Common volume and area units
l = liter = liters = Quantity("liter")
dl = deciliter = deciliters = Quantity("deciliter")
dl.set_global_relative_scale_factor(Rational(1, 10), liter)
cl = centiliter = centiliters = Quantity("centiliter")
cl.set_global_relative_scale_factor(Rational(1, 100), liter)
ml = milliliter = milliliters = Quantity("milliliter")
ml.set_global_relative_scale_factor(Rational(1, 1000), liter)
# Common time units
ms = millisecond = milliseconds = Quantity("millisecond", abbrev="ms")
millisecond.set_global_relative_scale_factor(milli, second)
us = microsecond = microseconds = Quantity("microsecond", abbrev="us", latex_repr=r'\mu\text{s}')
microsecond.set_global_relative_scale_factor(micro, second)
ns = nanosecond = nanoseconds = Quantity("nanosecond", abbrev="ns")
nanosecond.set_global_relative_scale_factor(nano, second)
ps = picosecond = picoseconds = Quantity("picosecond", abbrev="ps")
picosecond.set_global_relative_scale_factor(pico, second)
minute = minutes = Quantity("minute")
minute.set_global_relative_scale_factor(60, second)
h = hour = hours = Quantity("hour")
hour.set_global_relative_scale_factor(60, minute)
day = days = Quantity("day")
day.set_global_relative_scale_factor(24, hour)
anomalistic_year = anomalistic_years = Quantity("anomalistic_year")
anomalistic_year.set_global_relative_scale_factor(365.259636, day)
sidereal_year = sidereal_years = Quantity("sidereal_year")
sidereal_year.set_global_relative_scale_factor(31558149.540, seconds)
tropical_year = tropical_years = Quantity("tropical_year")
tropical_year.set_global_relative_scale_factor(365.24219, day)
common_year = common_years = Quantity("common_year")
common_year.set_global_relative_scale_factor(365, day)
julian_year = julian_years = Quantity("julian_year")
julian_year.set_global_relative_scale_factor((365 + One/4), day)
draconic_year = draconic_years = Quantity("draconic_year")
draconic_year.set_global_relative_scale_factor(346.62, day)
gaussian_year = gaussian_years = Quantity("gaussian_year")
gaussian_year.set_global_relative_scale_factor(365.2568983, day)
full_moon_cycle = full_moon_cycles = Quantity("full_moon_cycle")
full_moon_cycle.set_global_relative_scale_factor(411.78443029, day)
year = years = tropical_year
#### CONSTANTS ####
# Newton constant
G = gravitational_constant = Quantity("gravitational_constant", abbrev="G")
# speed of light
c = speed_of_light = Quantity("speed_of_light", abbrev="c")
# elementary charge
elementary_charge = Quantity("elementary_charge", abbrev="e")
# Planck constant
planck = Quantity("planck", abbrev="h")
# Reduced Planck constant
hbar = Quantity("hbar", abbrev="hbar")
# Electronvolt
eV = electronvolt = electronvolts = Quantity("electronvolt", abbrev="eV")
# Avogadro number
avogadro_number = Quantity("avogadro_number")
# Avogadro constant
avogadro = avogadro_constant = Quantity("avogadro_constant")
# Boltzmann constant
boltzmann = boltzmann_constant = Quantity("boltzmann_constant")
# Stefan-Boltzmann constant
stefan = stefan_boltzmann_constant = Quantity("stefan_boltzmann_constant")
# Atomic mass
amu = amus = atomic_mass_unit = atomic_mass_constant = Quantity("atomic_mass_constant")
# Molar gas constant
R = molar_gas_constant = Quantity("molar_gas_constant", abbrev="R")
# Faraday constant
faraday_constant = Quantity("faraday_constant")
# Josephson constant
josephson_constant = Quantity("josephson_constant", abbrev="K_j")
# Von Klitzing constant
von_klitzing_constant = Quantity("von_klitzing_constant", abbrev="R_k")
# Acceleration due to gravity (on the Earth surface)
gee = gees = acceleration_due_to_gravity = Quantity("acceleration_due_to_gravity", abbrev="g")
# magnetic constant:
u0 = magnetic_constant = vacuum_permeability = Quantity("magnetic_constant")
# electric constat:
e0 = electric_constant = vacuum_permittivity = Quantity("vacuum_permittivity")
# vacuum impedance:
Z0 = vacuum_impedance = Quantity("vacuum_impedance", abbrev='Z_0', latex_repr=r'Z_{0}')
# Coulomb's constant:
coulomb_constant = coulombs_constant = electric_force_constant = \
Quantity("coulomb_constant", abbrev="k_e")
atmosphere = atmospheres = atm = Quantity("atmosphere", abbrev="atm")
kPa = kilopascal = Quantity("kilopascal", abbrev="kPa")
kilopascal.set_global_relative_scale_factor(kilo, Pa)
bar = bars = Quantity("bar", abbrev="bar")
pound = pounds = Quantity("pound") # exact
psi = Quantity("psi")
dHg0 = 13.5951 # approx value at 0 C
mmHg = torr = Quantity("mmHg")
atmosphere.set_global_relative_scale_factor(101325, pascal)
bar.set_global_relative_scale_factor(100, kPa)
pound.set_global_relative_scale_factor(Rational(45359237, 100000000), kg)
mmu = mmus = milli_mass_unit = Quantity("milli_mass_unit")
quart = quarts = Quantity("quart")
# Other convenient units and magnitudes
ly = lightyear = lightyears = Quantity("lightyear", abbrev="ly")
au = astronomical_unit = astronomical_units = Quantity("astronomical_unit", abbrev="AU")
# Fundamental Planck units:
planck_mass = Quantity("planck_mass", abbrev="m_P", latex_repr=r'm_\text{P}')
planck_time = Quantity("planck_time", abbrev="t_P", latex_repr=r't_\text{P}')
planck_temperature = Quantity("planck_temperature", abbrev="T_P",
latex_repr=r'T_\text{P}')
planck_length = Quantity("planck_length", abbrev="l_P", latex_repr=r'l_\text{P}')
planck_charge = Quantity("planck_charge", abbrev="q_P", latex_repr=r'q_\text{P}')
# Derived Planck units:
planck_area = Quantity("planck_area")
planck_volume = Quantity("planck_volume")
planck_momentum = Quantity("planck_momentum")
planck_energy = Quantity("planck_energy", abbrev="E_P", latex_repr=r'E_\text{P}')
planck_force = Quantity("planck_force", abbrev="F_P", latex_repr=r'F_\text{P}')
planck_power = Quantity("planck_power", abbrev="P_P", latex_repr=r'P_\text{P}')
planck_density = Quantity("planck_density", abbrev="rho_P", latex_repr=r'\rho_\text{P}')
planck_energy_density = Quantity("planck_energy_density", abbrev="rho^E_P")
planck_intensity = Quantity("planck_intensity", abbrev="I_P", latex_repr=r'I_\text{P}')
planck_angular_frequency = Quantity("planck_angular_frequency", abbrev="omega_P",
latex_repr=r'\omega_\text{P}')
planck_pressure = Quantity("planck_pressure", abbrev="p_P", latex_repr=r'p_\text{P}')
planck_current = Quantity("planck_current", abbrev="I_P", latex_repr=r'I_\text{P}')
planck_voltage = Quantity("planck_voltage", abbrev="V_P", latex_repr=r'V_\text{P}')
planck_impedance = Quantity("planck_impedance", abbrev="Z_P", latex_repr=r'Z_\text{P}')
planck_acceleration = Quantity("planck_acceleration", abbrev="a_P",
latex_repr=r'a_\text{P}')
# Information theory units:
bit = bits = Quantity("bit")
bit.set_global_dimension(information)
byte = bytes = Quantity("byte")
kibibyte = kibibytes = Quantity("kibibyte")
mebibyte = mebibytes = Quantity("mebibyte")
gibibyte = gibibytes = Quantity("gibibyte")
tebibyte = tebibytes = Quantity("tebibyte")
pebibyte = pebibytes = Quantity("pebibyte")
exbibyte = exbibytes = Quantity("exbibyte")
byte.set_global_relative_scale_factor(8, bit)
kibibyte.set_global_relative_scale_factor(kibi, byte)
mebibyte.set_global_relative_scale_factor(mebi, byte)
gibibyte.set_global_relative_scale_factor(gibi, byte)
tebibyte.set_global_relative_scale_factor(tebi, byte)
pebibyte.set_global_relative_scale_factor(pebi, byte)
exbibyte.set_global_relative_scale_factor(exbi, byte)
# Older units for radioactivity
curie = Ci = Quantity("curie", abbrev="Ci")
rutherford = Rd = Quantity("rutherford", abbrev="Rd")
|
073976c43e4120a5b3c6c83dbb5b9102bfb38372442e7cf6363cee86ff71d439 | from sympy.core.singleton import S
from sympy.core.numbers import pi
from sympy.physics.units import DimensionSystem, hertz, kilogram
from sympy.physics.units.definitions import (
G, Hz, J, N, Pa, W, c, g, kg, m, s, meter, gram, second, newton,
joule, watt, pascal)
from sympy.physics.units.definitions.dimension_definitions import (
acceleration, action, energy, force, frequency, momentum,
power, pressure, velocity, length, mass, time)
from sympy.physics.units.prefixes import PREFIXES, prefix_unit
from sympy.physics.units.prefixes import (
kibi, mebi, gibi, tebi, pebi, exbi
)
from sympy.physics.units.definitions import (
cd, K, coulomb, volt, ohm, siemens, farad, henry, tesla, weber, dioptre,
lux, katal, gray, becquerel, inch, liter, julian_year,
gravitational_constant, speed_of_light, elementary_charge, planck, hbar,
electronvolt, avogadro_number, avogadro_constant, boltzmann_constant,
stefan_boltzmann_constant, atomic_mass_constant, molar_gas_constant,
faraday_constant, josephson_constant, von_klitzing_constant,
acceleration_due_to_gravity, magnetic_constant, vacuum_permittivity,
vacuum_impedance, coulomb_constant, atmosphere, bar, pound, psi, mmHg,
milli_mass_unit, quart, lightyear, astronomical_unit, planck_mass,
planck_time, planck_temperature, planck_length, planck_charge,
planck_area, planck_volume, planck_momentum, planck_energy, planck_force,
planck_power, planck_density, planck_energy_density, planck_intensity,
planck_angular_frequency, planck_pressure, planck_current, planck_voltage,
planck_impedance, planck_acceleration, bit, byte, kibibyte, mebibyte,
gibibyte, tebibyte, pebibyte, exbibyte, curie, rutherford, radian, degree,
steradian, angular_mil, atomic_mass_unit, gee, kPa, ampere, u0, kelvin,
mol, mole, candela, electric_constant, boltzmann
)
dimsys_length_weight_time = DimensionSystem([
# Dimensional dependencies for MKS base dimensions
length,
mass,
time,
], dimensional_dependencies=dict(
# Dimensional dependencies for derived dimensions
velocity=dict(length=1, time=-1),
acceleration=dict(length=1, time=-2),
momentum=dict(mass=1, length=1, time=-1),
force=dict(mass=1, length=1, time=-2),
energy=dict(mass=1, length=2, time=-2),
power=dict(length=2, mass=1, time=-3),
pressure=dict(mass=1, length=-1, time=-2),
frequency=dict(time=-1),
action=dict(length=2, mass=1, time=-1),
volume=dict(length=3),
))
One = S.One
# Base units:
dimsys_length_weight_time.set_quantity_dimension(meter, length)
dimsys_length_weight_time.set_quantity_scale_factor(meter, One)
# gram; used to define its prefixed units
dimsys_length_weight_time.set_quantity_dimension(gram, mass)
dimsys_length_weight_time.set_quantity_scale_factor(gram, One)
dimsys_length_weight_time.set_quantity_dimension(second, time)
dimsys_length_weight_time.set_quantity_scale_factor(second, One)
# derived units
dimsys_length_weight_time.set_quantity_dimension(newton, force)
dimsys_length_weight_time.set_quantity_scale_factor(newton, kilogram*meter/second**2)
dimsys_length_weight_time.set_quantity_dimension(joule, energy)
dimsys_length_weight_time.set_quantity_scale_factor(joule, newton*meter)
dimsys_length_weight_time.set_quantity_dimension(watt, power)
dimsys_length_weight_time.set_quantity_scale_factor(watt, joule/second)
dimsys_length_weight_time.set_quantity_dimension(pascal, pressure)
dimsys_length_weight_time.set_quantity_scale_factor(pascal, newton/meter**2)
dimsys_length_weight_time.set_quantity_dimension(hertz, frequency)
dimsys_length_weight_time.set_quantity_scale_factor(hertz, One)
# Other derived units:
dimsys_length_weight_time.set_quantity_dimension(dioptre, 1 / length)
dimsys_length_weight_time.set_quantity_scale_factor(dioptre, 1/meter)
# Common volume and area units
dimsys_length_weight_time.set_quantity_dimension(liter, length ** 3)
dimsys_length_weight_time.set_quantity_scale_factor(liter, meter**3 / 1000)
# Newton constant
# REF: NIST SP 959 (June 2019)
dimsys_length_weight_time.set_quantity_dimension(gravitational_constant, length ** 3 * mass ** -1 * time ** -2)
dimsys_length_weight_time.set_quantity_scale_factor(gravitational_constant, 6.67430e-11*m**3/(kg*s**2))
# speed of light
dimsys_length_weight_time.set_quantity_dimension(speed_of_light, velocity)
dimsys_length_weight_time.set_quantity_scale_factor(speed_of_light, 299792458*meter/second)
# Planck constant
# REF: NIST SP 959 (June 2019)
dimsys_length_weight_time.set_quantity_dimension(planck, action)
dimsys_length_weight_time.set_quantity_scale_factor(planck, 6.62607015e-34*joule*second)
# Reduced Planck constant
# REF: NIST SP 959 (June 2019)
dimsys_length_weight_time.set_quantity_dimension(hbar, action)
dimsys_length_weight_time.set_quantity_scale_factor(hbar, planck / (2 * pi))
__all__ = [
'mmHg', 'atmosphere', 'newton', 'meter', 'vacuum_permittivity', 'pascal',
'magnetic_constant', 'angular_mil', 'julian_year', 'weber', 'exbibyte',
'liter', 'molar_gas_constant', 'faraday_constant', 'avogadro_constant',
'planck_momentum', 'planck_density', 'gee', 'mol', 'bit', 'gray', 'kibi',
'bar', 'curie', 'prefix_unit', 'PREFIXES', 'planck_time', 'gram',
'candela', 'force', 'planck_intensity', 'energy', 'becquerel',
'planck_acceleration', 'speed_of_light', 'dioptre', 'second', 'frequency',
'Hz', 'power', 'lux', 'planck_current', 'momentum', 'tebibyte',
'planck_power', 'degree', 'mebi', 'K', 'planck_volume',
'quart', 'pressure', 'W', 'joule', 'boltzmann_constant', 'c', 'g',
'planck_force', 'exbi', 's', 'watt', 'action', 'hbar', 'gibibyte',
'DimensionSystem', 'cd', 'volt', 'planck_charge',
'dimsys_length_weight_time', 'pebi', 'vacuum_impedance', 'planck',
'farad', 'gravitational_constant', 'u0', 'hertz', 'tesla', 'steradian',
'josephson_constant', 'planck_area', 'stefan_boltzmann_constant',
'astronomical_unit', 'J', 'N', 'planck_voltage', 'planck_energy',
'atomic_mass_constant', 'rutherford', 'elementary_charge', 'Pa',
'planck_mass', 'henry', 'planck_angular_frequency', 'ohm', 'pound',
'planck_pressure', 'G', 'avogadro_number', 'psi', 'von_klitzing_constant',
'planck_length', 'radian', 'mole', 'acceleration',
'planck_energy_density', 'mebibyte', 'length',
'acceleration_due_to_gravity', 'planck_temperature', 'tebi', 'inch',
'electronvolt', 'coulomb_constant', 'kelvin', 'kPa', 'boltzmann',
'milli_mass_unit', 'gibi', 'planck_impedance', 'electric_constant', 'kg',
'coulomb', 'siemens', 'byte', 'atomic_mass_unit', 'm', 'kibibyte',
'kilogram', 'lightyear', 'mass', 'time', 'pebibyte', 'velocity',
'ampere', 'katal',
]
|
2eb1627234208843f65d056620fc13e808561410d527b9a97cfe248bd01f8540 | from sympy.core.singleton import S
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.physics.units import UnitSystem, centimeter, gram, second, coulomb, charge, speed_of_light, current, mass, \
length, voltage, magnetic_density, magnetic_flux
from sympy.physics.units.definitions import coulombs_constant
from sympy.physics.units.definitions.unit_definitions import statcoulomb, statampere, statvolt, volt, tesla, gauss, \
weber, maxwell, debye, oersted, ohm, farad, henry, erg, ampere, coulomb_constant
from sympy.physics.units.systems.mks import dimsys_length_weight_time
One = S.One
dimsys_cgs = dimsys_length_weight_time.extend(
[],
new_dim_deps=dict(
# Dimensional dependencies for derived dimensions
impedance=dict(time=1, length=-1),
conductance=dict(time=-1, length=1),
capacitance=dict(length=1),
inductance=dict(time=2, length=-1),
charge=dict(mass=S.Half, length=S(3)/2, time=-1),
current=dict(mass=One/2, length=3*One/2, time=-2),
voltage=dict(length=-One/2, mass=One/2, time=-1),
magnetic_density=dict(length=-One/2, mass=One/2, time=-1),
magnetic_flux=dict(length=3*One/2, mass=One/2, time=-1),
)
)
cgs_gauss = UnitSystem(
base_units=[centimeter, gram, second],
units=[],
name="cgs_gauss",
dimension_system=dimsys_cgs)
cgs_gauss.set_quantity_scale_factor(coulombs_constant, 1)
cgs_gauss.set_quantity_dimension(statcoulomb, charge)
cgs_gauss.set_quantity_scale_factor(statcoulomb, centimeter**(S(3)/2)*gram**(S.Half)/second)
cgs_gauss.set_quantity_dimension(coulomb, charge)
cgs_gauss.set_quantity_dimension(statampere, current)
cgs_gauss.set_quantity_scale_factor(statampere, statcoulomb/second)
cgs_gauss.set_quantity_dimension(statvolt, voltage)
cgs_gauss.set_quantity_scale_factor(statvolt, erg/statcoulomb)
cgs_gauss.set_quantity_dimension(volt, voltage)
cgs_gauss.set_quantity_dimension(gauss, magnetic_density)
cgs_gauss.set_quantity_scale_factor(gauss, sqrt(gram/centimeter)/second)
cgs_gauss.set_quantity_dimension(tesla, magnetic_density)
cgs_gauss.set_quantity_dimension(maxwell, magnetic_flux)
cgs_gauss.set_quantity_scale_factor(maxwell, sqrt(centimeter**3*gram)/second)
# SI units expressed in CGS-gaussian units:
cgs_gauss.set_quantity_scale_factor(coulomb, speed_of_light*statcoulomb/10)
cgs_gauss.set_quantity_scale_factor(ampere, speed_of_light*statcoulomb/second/10)
cgs_gauss.set_quantity_scale_factor(volt, speed_of_light*statvolt/10**6)
cgs_gauss.set_quantity_scale_factor(weber, 10**8*maxwell)
cgs_gauss.set_quantity_scale_factor(tesla, 10**4*gauss)
cgs_gauss.set_quantity_scale_factor(debye, One/10**18*statcoulomb*centimeter)
cgs_gauss.set_quantity_scale_factor(oersted, sqrt(gram/centimeter)/second)
cgs_gauss.set_quantity_scale_factor(ohm, 10**9/speed_of_light**2*second/centimeter)
cgs_gauss.set_quantity_scale_factor(farad, One/10**9*speed_of_light**2*centimeter)
cgs_gauss.set_quantity_scale_factor(henry, 10**9/speed_of_light**2/centimeter*second**2)
# Coulomb's constant:
cgs_gauss.set_quantity_dimension(coulomb_constant, 1)
cgs_gauss.set_quantity_scale_factor(coulomb_constant, 1)
__all__ = [
'ohm', 'tesla', 'maxwell', 'speed_of_light', 'volt', 'second', 'voltage',
'debye', 'dimsys_length_weight_time', 'centimeter', 'coulomb_constant',
'farad', 'sqrt', 'UnitSystem', 'current', 'charge', 'weber', 'gram',
'statcoulomb', 'gauss', 'S', 'statvolt', 'oersted', 'statampere',
'dimsys_cgs', 'coulomb', 'magnetic_density', 'magnetic_flux', 'One',
'length', 'erg', 'mass', 'coulombs_constant', 'henry', 'ampere',
'cgs_gauss',
]
|
fb3a4a67d614e9be6f501272a177cca742d2f10b160be08a73e5541f67c38b53 | """
SI unit system.
Based on MKSA, which stands for "meter, kilogram, second, ampere".
Added kelvin, candela and mole.
"""
from typing import List
from sympy.physics.units import DimensionSystem, Dimension, dHg0
from sympy.physics.units.quantities import Quantity
from sympy.core.numbers import (Rational, pi)
from sympy.core.singleton import S
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.physics.units.definitions.dimension_definitions import (
acceleration, action, current, impedance, length, mass, time, velocity,
amount_of_substance, temperature, information, frequency, force, pressure,
energy, power, charge, voltage, capacitance, conductance, magnetic_flux,
magnetic_density, inductance, luminous_intensity
)
from sympy.physics.units.definitions import (
kilogram, newton, second, meter, gram, cd, K, joule, watt, pascal, hertz,
coulomb, volt, ohm, siemens, farad, henry, tesla, weber, dioptre, lux,
katal, gray, becquerel, inch, liter, julian_year, gravitational_constant,
speed_of_light, elementary_charge, planck, hbar, electronvolt,
avogadro_number, avogadro_constant, boltzmann_constant,
stefan_boltzmann_constant, atomic_mass_constant, molar_gas_constant,
faraday_constant, josephson_constant, von_klitzing_constant,
acceleration_due_to_gravity, magnetic_constant, vacuum_permittivity,
vacuum_impedance, coulomb_constant, atmosphere, bar, pound, psi, mmHg,
milli_mass_unit, quart, lightyear, astronomical_unit, planck_mass,
planck_time, planck_temperature, planck_length, planck_charge, planck_area,
planck_volume, planck_momentum, planck_energy, planck_force, planck_power,
planck_density, planck_energy_density, planck_intensity,
planck_angular_frequency, planck_pressure, planck_current, planck_voltage,
planck_impedance, planck_acceleration, bit, byte, kibibyte, mebibyte,
gibibyte, tebibyte, pebibyte, exbibyte, curie, rutherford, radian, degree,
steradian, angular_mil, atomic_mass_unit, gee, kPa, ampere, u0, c, kelvin,
mol, mole, candela, m, kg, s, electric_constant, G, boltzmann
)
from sympy.physics.units.prefixes import PREFIXES, prefix_unit
from sympy.physics.units.systems.mksa import MKSA, dimsys_MKSA
derived_dims = (frequency, force, pressure, energy, power, charge, voltage,
capacitance, conductance, magnetic_flux,
magnetic_density, inductance, luminous_intensity)
base_dims = (amount_of_substance, luminous_intensity, temperature)
units = [mol, cd, K, lux, hertz, newton, pascal, joule, watt, coulomb, volt,
farad, ohm, siemens, weber, tesla, henry, candela, lux, becquerel,
gray, katal]
all_units = [] # type: List[Quantity]
for u in units:
all_units.extend(prefix_unit(u, PREFIXES))
all_units.extend([mol, cd, K, lux])
dimsys_SI = dimsys_MKSA.extend(
[
# Dimensional dependencies for other base dimensions:
temperature,
amount_of_substance,
luminous_intensity,
])
dimsys_default = dimsys_SI.extend(
[information],
)
SI = MKSA.extend(base=(mol, cd, K), units=all_units, name='SI', dimension_system=dimsys_SI)
One = S.One
SI.set_quantity_dimension(radian, One)
SI.set_quantity_scale_factor(ampere, One)
SI.set_quantity_scale_factor(kelvin, One)
SI.set_quantity_scale_factor(mole, One)
SI.set_quantity_scale_factor(candela, One)
# MKSA extension to MKS: derived units
SI.set_quantity_scale_factor(coulomb, One)
SI.set_quantity_scale_factor(volt, joule/coulomb)
SI.set_quantity_scale_factor(ohm, volt/ampere)
SI.set_quantity_scale_factor(siemens, ampere/volt)
SI.set_quantity_scale_factor(farad, coulomb/volt)
SI.set_quantity_scale_factor(henry, volt*second/ampere)
SI.set_quantity_scale_factor(tesla, volt*second/meter**2)
SI.set_quantity_scale_factor(weber, joule/ampere)
SI.set_quantity_dimension(lux, luminous_intensity / length ** 2)
SI.set_quantity_scale_factor(lux, steradian*candela/meter**2)
# katal is the SI unit of catalytic activity
SI.set_quantity_dimension(katal, amount_of_substance / time)
SI.set_quantity_scale_factor(katal, mol/second)
# gray is the SI unit of absorbed dose
SI.set_quantity_dimension(gray, energy / mass)
SI.set_quantity_scale_factor(gray, meter**2/second**2)
# becquerel is the SI unit of radioactivity
SI.set_quantity_dimension(becquerel, 1 / time)
SI.set_quantity_scale_factor(becquerel, 1/second)
#### CONSTANTS ####
# elementary charge
# REF: NIST SP 959 (June 2019)
SI.set_quantity_dimension(elementary_charge, charge)
SI.set_quantity_scale_factor(elementary_charge, 1.602176634e-19*coulomb)
# Electronvolt
# REF: NIST SP 959 (June 2019)
SI.set_quantity_dimension(electronvolt, energy)
SI.set_quantity_scale_factor(electronvolt, 1.602176634e-19*joule)
# Avogadro number
# REF: NIST SP 959 (June 2019)
SI.set_quantity_dimension(avogadro_number, One)
SI.set_quantity_scale_factor(avogadro_number, 6.02214076e23)
# Avogadro constant
SI.set_quantity_dimension(avogadro_constant, amount_of_substance ** -1)
SI.set_quantity_scale_factor(avogadro_constant, avogadro_number / mol)
# Boltzmann constant
# REF: NIST SP 959 (June 2019)
SI.set_quantity_dimension(boltzmann_constant, energy / temperature)
SI.set_quantity_scale_factor(boltzmann_constant, 1.380649e-23*joule/kelvin)
# Stefan-Boltzmann constant
# REF: NIST SP 959 (June 2019)
SI.set_quantity_dimension(stefan_boltzmann_constant, energy * time ** -1 * length ** -2 * temperature ** -4)
SI.set_quantity_scale_factor(stefan_boltzmann_constant, pi**2 * boltzmann_constant**4 / (60 * hbar**3 * speed_of_light ** 2))
# Atomic mass
# REF: NIST SP 959 (June 2019)
SI.set_quantity_dimension(atomic_mass_constant, mass)
SI.set_quantity_scale_factor(atomic_mass_constant, 1.66053906660e-24*gram)
# Molar gas constant
# REF: NIST SP 959 (June 2019)
SI.set_quantity_dimension(molar_gas_constant, energy / (temperature * amount_of_substance))
SI.set_quantity_scale_factor(molar_gas_constant, boltzmann_constant * avogadro_constant)
# Faraday constant
SI.set_quantity_dimension(faraday_constant, charge / amount_of_substance)
SI.set_quantity_scale_factor(faraday_constant, elementary_charge * avogadro_constant)
# Josephson constant
SI.set_quantity_dimension(josephson_constant, frequency / voltage)
SI.set_quantity_scale_factor(josephson_constant, 0.5 * planck / elementary_charge)
# Von Klitzing constant
SI.set_quantity_dimension(von_klitzing_constant, voltage / current)
SI.set_quantity_scale_factor(von_klitzing_constant, hbar / elementary_charge ** 2)
# Acceleration due to gravity (on the Earth surface)
SI.set_quantity_dimension(acceleration_due_to_gravity, acceleration)
SI.set_quantity_scale_factor(acceleration_due_to_gravity, 9.80665*meter/second**2)
# magnetic constant:
SI.set_quantity_dimension(magnetic_constant, force / current ** 2)
SI.set_quantity_scale_factor(magnetic_constant, 4*pi/10**7 * newton/ampere**2)
# electric constant:
SI.set_quantity_dimension(vacuum_permittivity, capacitance / length)
SI.set_quantity_scale_factor(vacuum_permittivity, 1/(u0 * c**2))
# vacuum impedance:
SI.set_quantity_dimension(vacuum_impedance, impedance)
SI.set_quantity_scale_factor(vacuum_impedance, u0 * c)
# Coulomb's constant:
SI.set_quantity_dimension(coulomb_constant, force * length ** 2 / charge ** 2)
SI.set_quantity_scale_factor(coulomb_constant, 1/(4*pi*vacuum_permittivity))
SI.set_quantity_dimension(psi, pressure)
SI.set_quantity_scale_factor(psi, pound * gee / inch ** 2)
SI.set_quantity_dimension(mmHg, pressure)
SI.set_quantity_scale_factor(mmHg, dHg0 * acceleration_due_to_gravity * kilogram / meter**2)
SI.set_quantity_dimension(milli_mass_unit, mass)
SI.set_quantity_scale_factor(milli_mass_unit, atomic_mass_unit/1000)
SI.set_quantity_dimension(quart, length ** 3)
SI.set_quantity_scale_factor(quart, Rational(231, 4) * inch**3)
# Other convenient units and magnitudes
SI.set_quantity_dimension(lightyear, length)
SI.set_quantity_scale_factor(lightyear, speed_of_light*julian_year)
SI.set_quantity_dimension(astronomical_unit, length)
SI.set_quantity_scale_factor(astronomical_unit, 149597870691*meter)
# Fundamental Planck units:
SI.set_quantity_dimension(planck_mass, mass)
SI.set_quantity_scale_factor(planck_mass, sqrt(hbar*speed_of_light/G))
SI.set_quantity_dimension(planck_time, time)
SI.set_quantity_scale_factor(planck_time, sqrt(hbar*G/speed_of_light**5))
SI.set_quantity_dimension(planck_temperature, temperature)
SI.set_quantity_scale_factor(planck_temperature, sqrt(hbar*speed_of_light**5/G/boltzmann**2))
SI.set_quantity_dimension(planck_length, length)
SI.set_quantity_scale_factor(planck_length, sqrt(hbar*G/speed_of_light**3))
SI.set_quantity_dimension(planck_charge, charge)
SI.set_quantity_scale_factor(planck_charge, sqrt(4*pi*electric_constant*hbar*speed_of_light))
# Derived Planck units:
SI.set_quantity_dimension(planck_area, length ** 2)
SI.set_quantity_scale_factor(planck_area, planck_length**2)
SI.set_quantity_dimension(planck_volume, length ** 3)
SI.set_quantity_scale_factor(planck_volume, planck_length**3)
SI.set_quantity_dimension(planck_momentum, mass * velocity)
SI.set_quantity_scale_factor(planck_momentum, planck_mass * speed_of_light)
SI.set_quantity_dimension(planck_energy, energy)
SI.set_quantity_scale_factor(planck_energy, planck_mass * speed_of_light**2)
SI.set_quantity_dimension(planck_force, force)
SI.set_quantity_scale_factor(planck_force, planck_energy / planck_length)
SI.set_quantity_dimension(planck_power, power)
SI.set_quantity_scale_factor(planck_power, planck_energy / planck_time)
SI.set_quantity_dimension(planck_density, mass / length ** 3)
SI.set_quantity_scale_factor(planck_density, planck_mass / planck_length**3)
SI.set_quantity_dimension(planck_energy_density, energy / length ** 3)
SI.set_quantity_scale_factor(planck_energy_density, planck_energy / planck_length**3)
SI.set_quantity_dimension(planck_intensity, mass * time ** (-3))
SI.set_quantity_scale_factor(planck_intensity, planck_energy_density * speed_of_light)
SI.set_quantity_dimension(planck_angular_frequency, 1 / time)
SI.set_quantity_scale_factor(planck_angular_frequency, 1 / planck_time)
SI.set_quantity_dimension(planck_pressure, pressure)
SI.set_quantity_scale_factor(planck_pressure, planck_force / planck_length**2)
SI.set_quantity_dimension(planck_current, current)
SI.set_quantity_scale_factor(planck_current, planck_charge / planck_time)
SI.set_quantity_dimension(planck_voltage, voltage)
SI.set_quantity_scale_factor(planck_voltage, planck_energy / planck_charge)
SI.set_quantity_dimension(planck_impedance, impedance)
SI.set_quantity_scale_factor(planck_impedance, planck_voltage / planck_current)
SI.set_quantity_dimension(planck_acceleration, acceleration)
SI.set_quantity_scale_factor(planck_acceleration, speed_of_light / planck_time)
# Older units for radioactivity
SI.set_quantity_dimension(curie, 1 / time)
SI.set_quantity_scale_factor(curie, 37000000000*becquerel)
SI.set_quantity_dimension(rutherford, 1 / time)
SI.set_quantity_scale_factor(rutherford, 1000000*becquerel)
# check that scale factors are the right SI dimensions:
for _scale_factor, _dimension in zip(
SI._quantity_scale_factors.values(),
SI._quantity_dimension_map.values()
):
dimex = SI.get_dimensional_expr(_scale_factor)
if dimex != 1:
# XXX: equivalent_dims is an instance method taking two arguments in
# addition to self so this can not work:
if not DimensionSystem.equivalent_dims(_dimension, Dimension(dimex)): # type: ignore
raise ValueError("quantity value and dimension mismatch")
del _scale_factor, _dimension
__all__ = [
'mmHg', 'atmosphere', 'inductance', 'newton', 'meter',
'vacuum_permittivity', 'pascal', 'magnetic_constant', 'voltage',
'angular_mil', 'luminous_intensity', 'all_units',
'julian_year', 'weber', 'exbibyte', 'liter',
'molar_gas_constant', 'faraday_constant', 'avogadro_constant',
'lightyear', 'planck_density', 'gee', 'mol', 'bit', 'gray',
'planck_momentum', 'bar', 'magnetic_density', 'prefix_unit', 'PREFIXES',
'planck_time', 'dimex', 'gram', 'candela', 'force', 'planck_intensity',
'energy', 'becquerel', 'planck_acceleration', 'speed_of_light',
'conductance', 'frequency', 'coulomb_constant', 'degree', 'lux', 'planck',
'current', 'planck_current', 'tebibyte', 'planck_power', 'MKSA', 'power',
'K', 'planck_volume', 'quart', 'pressure', 'amount_of_substance',
'joule', 'boltzmann_constant', 'Dimension', 'c', 'planck_force', 'length',
'watt', 'action', 'hbar', 'gibibyte', 'DimensionSystem', 'cd', 'volt',
'planck_charge', 'dioptre', 'vacuum_impedance', 'dimsys_default', 'farad',
'charge', 'gravitational_constant', 'temperature', 'u0', 'hertz',
'capacitance', 'tesla', 'steradian', 'planck_mass', 'josephson_constant',
'planck_area', 'stefan_boltzmann_constant', 'base_dims',
'astronomical_unit', 'radian', 'planck_voltage', 'impedance',
'planck_energy', 'atomic_mass_constant', 'rutherford', 'second', 'inch',
'elementary_charge', 'SI', 'electronvolt', 'dimsys_SI', 'henry',
'planck_angular_frequency', 'ohm', 'pound', 'planck_pressure', 'G', 'psi',
'dHg0', 'von_klitzing_constant', 'planck_length', 'avogadro_number',
'mole', 'acceleration', 'information', 'planck_energy_density',
'mebibyte', 's', 'acceleration_due_to_gravity',
'planck_temperature', 'units', 'mass', 'dimsys_MKSA', 'kelvin', 'kPa',
'boltzmann', 'milli_mass_unit', 'planck_impedance', 'electric_constant',
'derived_dims', 'kg', 'coulomb', 'siemens', 'byte', 'magnetic_flux',
'atomic_mass_unit', 'm', 'kibibyte', 'kilogram', 'One', 'curie', 'u',
'time', 'pebibyte', 'velocity', 'ampere', 'katal',
]
|
0d0415f12fcc240b59c4d6e1feaa518684e5f41377a9a33304e772be8e6c7e26 | import warnings
from sympy.core.add import Add
from sympy.core.function import (Function, diff)
from sympy.core.numbers import (Number, Rational)
from sympy.core.singleton import S
from sympy.core.symbol import (Symbol, symbols)
from sympy.functions.elementary.complexes import Abs
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import sin
from sympy.integrals.integrals import integrate
from sympy.physics.units import (amount_of_substance, convert_to, find_unit,
volume, kilometer, joule)
from sympy.physics.units.definitions import (amu, au, centimeter, coulomb,
day, foot, grams, hour, inch, kg, km, m, meter, millimeter,
minute, quart, s, second, speed_of_light, bit,
byte, kibibyte, mebibyte, gibibyte, tebibyte, pebibyte, exbibyte,
kilogram, gravitational_constant)
from sympy.physics.units.definitions.dimension_definitions import (
Dimension, charge, length, time, temperature, pressure,
energy
)
from sympy.physics.units.prefixes import PREFIXES, kilo
from sympy.physics.units.quantities import Quantity
from sympy.physics.units.systems import SI
from sympy.testing.pytest import XFAIL, raises, warns_deprecated_sympy
k = PREFIXES["k"]
def test_str_repr():
assert str(kg) == "kilogram"
def test_eq():
# simple test
assert 10*m == 10*m
assert 10*m != 10*s
def test_convert_to():
q = Quantity("q1")
q.set_global_relative_scale_factor(S(5000), meter)
assert q.convert_to(m) == 5000*m
assert speed_of_light.convert_to(m / s) == 299792458 * m / s
# TODO: eventually support this kind of conversion:
# assert (2*speed_of_light).convert_to(m / s) == 2 * 299792458 * m / s
assert day.convert_to(s) == 86400*s
# Wrong dimension to convert:
assert q.convert_to(s) == q
assert speed_of_light.convert_to(m) == speed_of_light
expr = joule*second
conv = convert_to(expr, joule)
assert conv == joule*second
def test_Quantity_definition():
q = Quantity("s10", abbrev="sabbr")
q.set_global_relative_scale_factor(10, second)
u = Quantity("u", abbrev="dam")
u.set_global_relative_scale_factor(10, meter)
km = Quantity("km")
km.set_global_relative_scale_factor(kilo, meter)
v = Quantity("u")
v.set_global_relative_scale_factor(5*kilo, meter)
assert q.scale_factor == 10
assert q.dimension == time
assert q.abbrev == Symbol("sabbr")
assert u.dimension == length
assert u.scale_factor == 10
assert u.abbrev == Symbol("dam")
assert km.scale_factor == 1000
assert km.func(*km.args) == km
assert km.func(*km.args).args == km.args
assert v.dimension == length
assert v.scale_factor == 5000
with warns_deprecated_sympy():
Quantity('invalid', 'dimension', 1)
with warns_deprecated_sympy():
Quantity('mismatch', dimension=length, scale_factor=kg)
def test_abbrev():
u = Quantity("u")
u.set_global_relative_scale_factor(S.One, meter)
assert u.name == Symbol("u")
assert u.abbrev == Symbol("u")
u = Quantity("u", abbrev="om")
u.set_global_relative_scale_factor(S(2), meter)
assert u.name == Symbol("u")
assert u.abbrev == Symbol("om")
assert u.scale_factor == 2
assert isinstance(u.scale_factor, Number)
u = Quantity("u", abbrev="ikm")
u.set_global_relative_scale_factor(3*kilo, meter)
assert u.abbrev == Symbol("ikm")
assert u.scale_factor == 3000
def test_print():
u = Quantity("unitname", abbrev="dam")
assert repr(u) == "unitname"
assert str(u) == "unitname"
def test_Quantity_eq():
u = Quantity("u", abbrev="dam")
v = Quantity("v1")
assert u != v
v = Quantity("v2", abbrev="ds")
assert u != v
v = Quantity("v3", abbrev="dm")
assert u != v
def test_add_sub():
u = Quantity("u")
v = Quantity("v")
w = Quantity("w")
u.set_global_relative_scale_factor(S(10), meter)
v.set_global_relative_scale_factor(S(5), meter)
w.set_global_relative_scale_factor(S(2), second)
assert isinstance(u + v, Add)
assert (u + v.convert_to(u)) == (1 + S.Half)*u
# TODO: eventually add this:
# assert (u + v).convert_to(u) == (1 + S.Half)*u
assert isinstance(u - v, Add)
assert (u - v.convert_to(u)) == S.Half*u
# TODO: eventually add this:
# assert (u - v).convert_to(u) == S.Half*u
def test_quantity_abs():
v_w1 = Quantity('v_w1')
v_w2 = Quantity('v_w2')
v_w3 = Quantity('v_w3')
v_w1.set_global_relative_scale_factor(1, meter/second)
v_w2.set_global_relative_scale_factor(1, meter/second)
v_w3.set_global_relative_scale_factor(1, meter/second)
expr = v_w3 - Abs(v_w1 - v_w2)
assert SI.get_dimensional_expr(v_w1) == (length/time).name
Dq = Dimension(SI.get_dimensional_expr(expr))
with warns_deprecated_sympy():
Dq1 = Dimension(Quantity.get_dimensional_expr(expr))
assert Dq == Dq1
assert SI.get_dimension_system().get_dimensional_dependencies(Dq) == {
'length': 1,
'time': -1,
}
assert meter == sqrt(meter**2)
def test_check_unit_consistency():
u = Quantity("u")
v = Quantity("v")
w = Quantity("w")
u.set_global_relative_scale_factor(S(10), meter)
v.set_global_relative_scale_factor(S(5), meter)
w.set_global_relative_scale_factor(S(2), second)
def check_unit_consistency(expr):
SI._collect_factor_and_dimension(expr)
raises(ValueError, lambda: check_unit_consistency(u + w))
raises(ValueError, lambda: check_unit_consistency(u - w))
raises(ValueError, lambda: check_unit_consistency(u + 1))
raises(ValueError, lambda: check_unit_consistency(u - 1))
raises(ValueError, lambda: check_unit_consistency(1 - exp(u / w)))
def test_mul_div():
u = Quantity("u")
v = Quantity("v")
t = Quantity("t")
ut = Quantity("ut")
v2 = Quantity("v")
u.set_global_relative_scale_factor(S(10), meter)
v.set_global_relative_scale_factor(S(5), meter)
t.set_global_relative_scale_factor(S(2), second)
ut.set_global_relative_scale_factor(S(20), meter*second)
v2.set_global_relative_scale_factor(S(5), meter/second)
assert 1 / u == u**(-1)
assert u / 1 == u
v1 = u / t
v2 = v
# Pow only supports structural equality:
assert v1 != v2
assert v1 == v2.convert_to(v1)
# TODO: decide whether to allow such expression in the future
# (requires somehow manipulating the core).
# assert u / Quantity('l2', dimension=length, scale_factor=2) == 5
assert u * 1 == u
ut1 = u * t
ut2 = ut
# Mul only supports structural equality:
assert ut1 != ut2
assert ut1 == ut2.convert_to(ut1)
# Mul only supports structural equality:
lp1 = Quantity("lp1")
lp1.set_global_relative_scale_factor(S(2), 1/meter)
assert u * lp1 != 20
assert u**0 == 1
assert u**1 == u
# TODO: Pow only support structural equality:
u2 = Quantity("u2")
u3 = Quantity("u3")
u2.set_global_relative_scale_factor(S(100), meter**2)
u3.set_global_relative_scale_factor(Rational(1, 10), 1/meter)
assert u ** 2 != u2
assert u ** -1 != u3
assert u ** 2 == u2.convert_to(u)
assert u ** -1 == u3.convert_to(u)
def test_units():
assert convert_to((5*m/s * day) / km, 1) == 432
assert convert_to(foot / meter, meter) == Rational(3048, 10000)
# amu is a pure mass so mass/mass gives a number, not an amount (mol)
# TODO: need better simplification routine:
assert str(convert_to(grams/amu, grams).n(2)) == '6.0e+23'
# Light from the sun needs about 8.3 minutes to reach earth
t = (1*au / speed_of_light) / minute
# TODO: need a better way to simplify expressions containing units:
t = convert_to(convert_to(t, meter / minute), meter)
assert t.simplify() == Rational(49865956897, 5995849160)
# TODO: fix this, it should give `m` without `Abs`
assert sqrt(m**2) == m
assert (sqrt(m))**2 == m
t = Symbol('t')
assert integrate(t*m/s, (t, 1*s, 5*s)) == 12*m*s
assert (t * m/s).integrate((t, 1*s, 5*s)) == 12*m*s
def test_issue_quart():
assert convert_to(4 * quart / inch ** 3, meter) == 231
assert convert_to(4 * quart / inch ** 3, millimeter) == 231
def test_issue_5565():
assert (m < s).is_Relational
def test_find_unit():
assert find_unit('coulomb') == ['coulomb', 'coulombs', 'coulomb_constant']
assert find_unit(coulomb) == ['C', 'coulomb', 'coulombs', 'planck_charge', 'elementary_charge']
assert find_unit(charge) == ['C', 'coulomb', 'coulombs', 'planck_charge', 'elementary_charge']
assert find_unit(inch) == [
'm', 'au', 'cm', 'dm', 'ft', 'km', 'ly', 'mi', 'mm', 'nm', 'pm', 'um',
'yd', 'nmi', 'feet', 'foot', 'inch', 'mile', 'yard', 'meter', 'miles',
'yards', 'inches', 'meters', 'micron', 'microns', 'decimeter',
'kilometer', 'lightyear', 'nanometer', 'picometer', 'centimeter',
'decimeters', 'kilometers', 'lightyears', 'micrometer', 'millimeter',
'nanometers', 'picometers', 'centimeters', 'micrometers',
'millimeters', 'nautical_mile', 'planck_length', 'nautical_miles', 'astronomical_unit',
'astronomical_units']
assert find_unit(inch**-1) == ['D', 'dioptre', 'optical_power']
assert find_unit(length**-1) == ['D', 'dioptre', 'optical_power']
assert find_unit(inch ** 3) == [
'l', 'cl', 'dl', 'ml', 'liter', 'quart', 'liters', 'quarts',
'deciliter', 'centiliter', 'deciliters', 'milliliter',
'centiliters', 'milliliters', 'planck_volume']
assert find_unit('voltage') == ['V', 'v', 'volt', 'volts', 'planck_voltage']
def test_Quantity_derivative():
x = symbols("x")
assert diff(x*meter, x) == meter
assert diff(x**3*meter**2, x) == 3*x**2*meter**2
assert diff(meter, meter) == 1
assert diff(meter**2, meter) == 2*meter
def test_quantity_postprocessing():
q1 = Quantity('q1')
q2 = Quantity('q2')
SI.set_quantity_dimension(q1, length*pressure**2*temperature/time)
SI.set_quantity_dimension(q2, energy*pressure*temperature/(length**2*time))
assert q1 + q2
q = q1 + q2
Dq = Dimension(SI.get_dimensional_expr(q))
assert SI.get_dimension_system().get_dimensional_dependencies(Dq) == {
'length': -1,
'mass': 2,
'temperature': 1,
'time': -5,
}
def test_factor_and_dimension():
assert (3000, Dimension(1)) == SI._collect_factor_and_dimension(3000)
assert (1001, length) == SI._collect_factor_and_dimension(meter + km)
assert (2, length/time) == SI._collect_factor_and_dimension(
meter/second + 36*km/(10*hour))
x, y = symbols('x y')
assert (x + y/100, length) == SI._collect_factor_and_dimension(
x*m + y*centimeter)
cH = Quantity('cH')
SI.set_quantity_dimension(cH, amount_of_substance/volume)
pH = -log(cH)
assert (1, volume/amount_of_substance) == SI._collect_factor_and_dimension(
exp(pH))
v_w1 = Quantity('v_w1')
v_w2 = Quantity('v_w2')
v_w1.set_global_relative_scale_factor(Rational(3, 2), meter/second)
v_w2.set_global_relative_scale_factor(2, meter/second)
expr = Abs(v_w1/2 - v_w2)
assert (Rational(5, 4), length/time) == \
SI._collect_factor_and_dimension(expr)
expr = Rational(5, 2)*second/meter*v_w1 - 3000
assert (-(2996 + Rational(1, 4)), Dimension(1)) == \
SI._collect_factor_and_dimension(expr)
expr = v_w1**(v_w2/v_w1)
assert ((Rational(3, 2))**Rational(4, 3), (length/time)**Rational(4, 3)) == \
SI._collect_factor_and_dimension(expr)
with warns_deprecated_sympy():
assert (3000, Dimension(1)) == Quantity._collect_factor_and_dimension(3000)
@XFAIL
def test_factor_and_dimension_with_Abs():
with warns_deprecated_sympy():
v_w1 = Quantity('v_w1', length/time, Rational(3, 2)*meter/second)
v_w1.set_global_relative_scale_factor(Rational(3, 2), meter/second)
expr = v_w1 - Abs(v_w1)
assert (0, length/time) == Quantity._collect_factor_and_dimension(expr)
def test_dimensional_expr_of_derivative():
l = Quantity('l')
t = Quantity('t')
t1 = Quantity('t1')
l.set_global_relative_scale_factor(36, km)
t.set_global_relative_scale_factor(1, hour)
t1.set_global_relative_scale_factor(1, second)
x = Symbol('x')
y = Symbol('y')
f = Function('f')
dfdx = f(x, y).diff(x, y)
dl_dt = dfdx.subs({f(x, y): l, x: t, y: t1})
assert SI.get_dimensional_expr(dl_dt) ==\
SI.get_dimensional_expr(l / t / t1) ==\
Symbol("length")/Symbol("time")**2
assert SI._collect_factor_and_dimension(dl_dt) ==\
SI._collect_factor_and_dimension(l / t / t1) ==\
(10, length/time**2)
def test_get_dimensional_expr_with_function():
v_w1 = Quantity('v_w1')
v_w2 = Quantity('v_w2')
v_w1.set_global_relative_scale_factor(1, meter/second)
v_w2.set_global_relative_scale_factor(1, meter/second)
assert SI.get_dimensional_expr(sin(v_w1)) == \
sin(SI.get_dimensional_expr(v_w1))
assert SI.get_dimensional_expr(sin(v_w1/v_w2)) == 1
def test_binary_information():
assert convert_to(kibibyte, byte) == 1024*byte
assert convert_to(mebibyte, byte) == 1024**2*byte
assert convert_to(gibibyte, byte) == 1024**3*byte
assert convert_to(tebibyte, byte) == 1024**4*byte
assert convert_to(pebibyte, byte) == 1024**5*byte
assert convert_to(exbibyte, byte) == 1024**6*byte
assert kibibyte.convert_to(bit) == 8*1024*bit
assert byte.convert_to(bit) == 8*bit
a = 10*kibibyte*hour
assert convert_to(a, byte) == 10240*byte*hour
assert convert_to(a, minute) == 600*kibibyte*minute
assert convert_to(a, [byte, minute]) == 614400*byte*minute
def test_conversion_with_2_nonstandard_dimensions():
good_grade = Quantity("good_grade")
kilo_good_grade = Quantity("kilo_good_grade")
centi_good_grade = Quantity("centi_good_grade")
kilo_good_grade.set_global_relative_scale_factor(1000, good_grade)
centi_good_grade.set_global_relative_scale_factor(S.One/10**5, kilo_good_grade)
charity_points = Quantity("charity_points")
milli_charity_points = Quantity("milli_charity_points")
missions = Quantity("missions")
milli_charity_points.set_global_relative_scale_factor(S.One/1000, charity_points)
missions.set_global_relative_scale_factor(251, charity_points)
assert convert_to(
kilo_good_grade*milli_charity_points*millimeter,
[centi_good_grade, missions, centimeter]
) == S.One * 10**5 / (251*1000) / 10 * centi_good_grade*missions*centimeter
def test_eval_subs():
energy, mass, force = symbols('energy mass force')
expr1 = energy/mass
units = {energy: kilogram*meter**2/second**2, mass: kilogram}
assert expr1.subs(units) == meter**2/second**2
expr2 = force/mass
units = {force:gravitational_constant*kilogram**2/meter**2, mass:kilogram}
assert expr2.subs(units) == gravitational_constant*kilogram/meter**2
def test_issue_14932():
assert (log(inch) - log(2)).simplify() == log(inch/2)
assert (log(inch) - log(foot)).simplify() == -log(12)
p = symbols('p', positive=True)
assert (log(inch) - log(p)).simplify() == log(inch/p)
def test_issue_14547():
# the root issue is that an argument with dimensions should
# not raise an error when the `arg - 1` calculation is
# performed in the assumptions system
from sympy.physics.units import foot, inch
from sympy.core.relational import Eq
assert log(foot).is_zero is None
assert log(foot).is_positive is None
assert log(foot).is_nonnegative is None
assert log(foot).is_negative is None
assert log(foot).is_algebraic is None
assert log(foot).is_rational is None
# doesn't raise error
assert Eq(log(foot), log(inch)) is not None # might be False or unevaluated
x = Symbol('x')
e = foot + x
assert e.is_Add and set(e.args) == {foot, x}
e = foot + 1
assert e.is_Add and set(e.args) == {foot, 1}
def test_deprecated_quantity_methods():
step = Quantity("step")
with warns_deprecated_sympy():
step.set_dimension(length)
step.set_scale_factor(2*meter)
assert convert_to(step, centimeter) == 200*centimeter
assert convert_to(1000*step/second, kilometer/second) == 2*kilometer/second
def test_issue_22164():
warnings.simplefilter("error")
dm = Quantity("dm")
SI.set_quantity_dimension(dm, length)
SI.set_quantity_scale_factor(dm, 1)
bad_exp = Quantity("bad_exp")
SI.set_quantity_dimension(bad_exp, length)
SI.set_quantity_scale_factor(bad_exp, 1)
expr = dm ** bad_exp
# deprecation warning is not expected here
SI._collect_factor_and_dimension(expr)
|
8c9fef1b107db99530cd80b7856bfa1ff9d0f325da7ec9243f16cc5729444c7e | from sympy.physics.units import DimensionSystem, joule, second, ampere
from sympy.testing.pytest import warns_deprecated_sympy
from sympy.core.numbers import Rational
from sympy.core.singleton import S
from sympy.physics.units.definitions import c, kg, m, s
from sympy.physics.units.definitions.dimension_definitions import length, time
from sympy.physics.units.quantities import Quantity
from sympy.physics.units.unitsystem import UnitSystem
def test_definition():
# want to test if the system can have several units of the same dimension
dm = Quantity("dm")
base = (m, s)
# base_dim = (m.dimension, s.dimension)
ms = UnitSystem(base, (c, dm), "MS", "MS system")
ms.set_quantity_dimension(dm, length)
ms.set_quantity_scale_factor(dm, Rational(1, 10))
assert set(ms._base_units) == set(base)
assert set(ms._units) == {m, s, c, dm}
# assert ms._units == DimensionSystem._sort_dims(base + (velocity,))
assert ms.name == "MS"
assert ms.descr == "MS system"
def test_str_repr():
assert str(UnitSystem((m, s), name="MS")) == "MS"
assert str(UnitSystem((m, s))) == "UnitSystem((meter, second))"
assert repr(UnitSystem((m, s))) == "<UnitSystem: (%s, %s)>" % (m, s)
def test_print_unit_base():
A = Quantity("A")
A.set_global_relative_scale_factor(S.One, ampere)
Js = Quantity("Js")
Js.set_global_relative_scale_factor(S.One, joule*second)
mksa = UnitSystem((m, kg, s, A), (Js,))
with warns_deprecated_sympy():
assert mksa.print_unit_base(Js) == m**2*kg*s**-1/1000
def test_extend():
ms = UnitSystem((m, s), (c,))
Js = Quantity("Js")
Js.set_global_relative_scale_factor(1, joule*second)
mks = ms.extend((kg,), (Js,))
res = UnitSystem((m, s, kg), (c, Js))
assert set(mks._base_units) == set(res._base_units)
assert set(mks._units) == set(res._units)
def test_dim():
dimsys = UnitSystem((m, kg, s), (c,))
assert dimsys.dim == 3
def test_is_consistent():
dimension_system = DimensionSystem([length, time])
us = UnitSystem([m, s], dimension_system=dimension_system)
assert us.is_consistent == True
|
0cda342e068a9834a746ea073a581da33e17f07727d279dd22fa1c0cdd310059 | from sympy.physics.units.systems.si import dimsys_SI
from sympy.core.numbers import pi
from sympy.core.singleton import S
from sympy.core.symbol import Symbol
from sympy.functions.elementary.complexes import Abs
from sympy.functions.elementary.exponential import log
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import (acos, atan2, cos)
from sympy.physics.units.dimensions import Dimension
from sympy.physics.units.definitions.dimension_definitions import (
length, time, mass, force, pressure, angle
)
from sympy.physics.units import foot
from sympy.testing.pytest import raises
def test_Dimension_definition():
assert dimsys_SI.get_dimensional_dependencies(length) == {"length": 1}
assert length.name == Symbol("length")
assert length.symbol == Symbol("L")
halflength = sqrt(length)
assert dimsys_SI.get_dimensional_dependencies(halflength) == {"length": S.Half}
def test_Dimension_error_definition():
# tuple with more or less than two entries
raises(TypeError, lambda: Dimension(("length", 1, 2)))
raises(TypeError, lambda: Dimension(["length"]))
# non-number power
raises(TypeError, lambda: Dimension({"length": "a"}))
# non-number with named argument
raises(TypeError, lambda: Dimension({"length": (1, 2)}))
# symbol should by Symbol or str
raises(AssertionError, lambda: Dimension("length", symbol=1))
def test_str():
assert str(Dimension("length")) == "Dimension(length)"
assert str(Dimension("length", "L")) == "Dimension(length, L)"
def test_Dimension_properties():
assert dimsys_SI.is_dimensionless(length) is False
assert dimsys_SI.is_dimensionless(length/length) is True
assert dimsys_SI.is_dimensionless(Dimension("undefined")) is False
assert length.has_integer_powers(dimsys_SI) is True
assert (length**(-1)).has_integer_powers(dimsys_SI) is True
assert (length**1.5).has_integer_powers(dimsys_SI) is False
def test_Dimension_add_sub():
assert length + length == length
assert length - length == length
assert -length == length
raises(TypeError, lambda: length + foot)
raises(TypeError, lambda: foot + length)
raises(TypeError, lambda: length - foot)
raises(TypeError, lambda: foot - length)
# issue 14547 - only raise error for dimensional args; allow
# others to pass
x = Symbol('x')
e = length + x
assert e == x + length and e.is_Add and set(e.args) == {length, x}
e = length + 1
assert e == 1 + length == 1 - length and e.is_Add and set(e.args) == {length, 1}
assert dimsys_SI.get_dimensional_dependencies(mass * length / time**2 + force) == \
{'length': 1, 'mass': 1, 'time': -2}
assert dimsys_SI.get_dimensional_dependencies(mass * length / time**2 + force -
pressure * length**2) == \
{'length': 1, 'mass': 1, 'time': -2}
raises(TypeError, lambda: dimsys_SI.get_dimensional_dependencies(mass * length / time**2 + pressure))
def test_Dimension_mul_div_exp():
assert 2*length == length*2 == length/2 == length
assert 2/length == 1/length
x = Symbol('x')
m = x*length
assert m == length*x and m.is_Mul and set(m.args) == {x, length}
d = x/length
assert d == x*length**-1 and d.is_Mul and set(d.args) == {x, 1/length}
d = length/x
assert d == length*x**-1 and d.is_Mul and set(d.args) == {1/x, length}
velo = length / time
assert (length * length) == length ** 2
assert dimsys_SI.get_dimensional_dependencies(length * length) == {"length": 2}
assert dimsys_SI.get_dimensional_dependencies(length ** 2) == {"length": 2}
assert dimsys_SI.get_dimensional_dependencies(length * time) == { "length": 1, "time": 1}
assert dimsys_SI.get_dimensional_dependencies(velo) == { "length": 1, "time": -1}
assert dimsys_SI.get_dimensional_dependencies(velo ** 2) == {"length": 2, "time": -2}
assert dimsys_SI.get_dimensional_dependencies(length / length) == {}
assert dimsys_SI.get_dimensional_dependencies(velo / length * time) == {}
assert dimsys_SI.get_dimensional_dependencies(length ** -1) == {"length": -1}
assert dimsys_SI.get_dimensional_dependencies(velo ** -1.5) == {"length": -1.5, "time": 1.5}
length_a = length**"a"
assert dimsys_SI.get_dimensional_dependencies(length_a) == {"length": Symbol("a")}
assert dimsys_SI.get_dimensional_dependencies(length**pi) == {"length": pi}
assert dimsys_SI.get_dimensional_dependencies(length**(length/length)) == {"length": Dimension(1)}
raises(TypeError, lambda: dimsys_SI.get_dimensional_dependencies(length**length))
assert length != 1
assert length / length != 1
length_0 = length ** 0
assert dimsys_SI.get_dimensional_dependencies(length_0) == {}
# issue 18738
a = Symbol('a')
b = Symbol('b')
c = sqrt(a**2 + b**2)
c_dim = c.subs({a: length, b: length})
assert dimsys_SI.equivalent_dims(c_dim, length)
def test_Dimension_functions():
raises(TypeError, lambda: dimsys_SI.get_dimensional_dependencies(cos(length)))
raises(TypeError, lambda: dimsys_SI.get_dimensional_dependencies(acos(angle)))
raises(TypeError, lambda: dimsys_SI.get_dimensional_dependencies(atan2(length, time)))
raises(TypeError, lambda: dimsys_SI.get_dimensional_dependencies(log(length)))
raises(TypeError, lambda: dimsys_SI.get_dimensional_dependencies(log(100, length)))
raises(TypeError, lambda: dimsys_SI.get_dimensional_dependencies(log(length, 10)))
assert dimsys_SI.get_dimensional_dependencies(pi) == {}
assert dimsys_SI.get_dimensional_dependencies(cos(1)) == {}
assert dimsys_SI.get_dimensional_dependencies(cos(angle)) == {}
assert dimsys_SI.get_dimensional_dependencies(atan2(length, length)) == {}
assert dimsys_SI.get_dimensional_dependencies(log(length / length, length / length)) == {}
assert dimsys_SI.get_dimensional_dependencies(Abs(length)) == {"length": 1}
assert dimsys_SI.get_dimensional_dependencies(Abs(length / length)) == {}
assert dimsys_SI.get_dimensional_dependencies(sqrt(-1)) == {}
|
c1b6fea13975bf91f4b1b9e9f618aa201a01886a76635710d2806d23aa77fe3c | from sympy.core.mul import Mul
from sympy.core.numbers import Rational
from sympy.core.singleton import S
from sympy.core.symbol import (Symbol, symbols)
from sympy.physics.units import Quantity, length, meter
from sympy.physics.units.prefixes import PREFIXES, Prefix, prefix_unit, kilo, \
kibi
from sympy.physics.units.systems import SI
x = Symbol('x')
def test_prefix_operations():
m = PREFIXES['m']
k = PREFIXES['k']
M = PREFIXES['M']
dodeca = Prefix('dodeca', 'dd', 1, base=12)
assert m * k == 1
assert k * k == M
assert 1 / m == k
assert k / m == M
assert dodeca * dodeca == 144
assert 1 / dodeca == S.One / 12
assert k / dodeca == S(1000) / 12
assert dodeca / dodeca == 1
m = Quantity("fake_meter")
SI.set_quantity_dimension(m, S.One)
SI.set_quantity_scale_factor(m, S.One)
assert dodeca * m == 12 * m
assert dodeca / m == 12 / m
expr1 = kilo * 3
assert isinstance(expr1, Mul)
assert expr1.args == (3, kilo)
expr2 = kilo * x
assert isinstance(expr2, Mul)
assert expr2.args == (x, kilo)
expr3 = kilo / 3
assert isinstance(expr3, Mul)
assert expr3.args == (Rational(1, 3), kilo)
assert expr3.args == (S.One/3, kilo)
expr4 = kilo / x
assert isinstance(expr4, Mul)
assert expr4.args == (1/x, kilo)
def test_prefix_unit():
m = Quantity("fake_meter", abbrev="m")
m.set_global_relative_scale_factor(1, meter)
pref = {"m": PREFIXES["m"], "c": PREFIXES["c"], "d": PREFIXES["d"]}
q1 = Quantity("millifake_meter", abbrev="mm")
q2 = Quantity("centifake_meter", abbrev="cm")
q3 = Quantity("decifake_meter", abbrev="dm")
SI.set_quantity_dimension(q1, length)
SI.set_quantity_scale_factor(q1, PREFIXES["m"])
SI.set_quantity_scale_factor(q1, PREFIXES["c"])
SI.set_quantity_scale_factor(q1, PREFIXES["d"])
res = [q1, q2, q3]
prefs = prefix_unit(m, pref)
assert set(prefs) == set(res)
assert set(map(lambda v: v.abbrev, prefs)) == set(symbols("mm,cm,dm"))
def test_bases():
assert kilo.base == 10
assert kibi.base == 2
def test_repr():
assert eval(repr(kilo)) == kilo
assert eval(repr(kibi)) == kibi
|
55b657e73d7823fbf5c56993dbf0a731c88772f3759acf64c36a0024d3a58ae9 | from sympy.core.containers import Tuple
from sympy.core.numbers import pi
from sympy.core.power import Pow
from sympy.core.symbol import symbols
from sympy.core.sympify import sympify
from sympy.printing.str import sstr
from sympy.physics.units import (
G, centimeter, coulomb, day, degree, gram, hbar, hour, inch, joule, kelvin,
kilogram, kilometer, length, meter, mile, minute, newton, planck,
planck_length, planck_mass, planck_temperature, planck_time, radians,
second, speed_of_light, steradian, time, km)
from sympy.physics.units.util import convert_to, check_dimensions
from sympy.testing.pytest import raises
def NS(e, n=15, **options):
return sstr(sympify(e).evalf(n, **options), full_prec=True)
L = length
T = time
def test_dim_simplify_add():
# assert Add(L, L) == L
assert L + L == L
def test_dim_simplify_mul():
# assert Mul(L, T) == L*T
assert L*T == L*T
def test_dim_simplify_pow():
assert Pow(L, 2) == L**2
def test_dim_simplify_rec():
# assert Mul(Add(L, L), T) == L*T
assert (L + L) * T == L*T
def test_convert_to_quantities():
assert convert_to(3, meter) == 3
assert convert_to(mile, kilometer) == 25146*kilometer/15625
assert convert_to(meter/second, speed_of_light) == speed_of_light/299792458
assert convert_to(299792458*meter/second, speed_of_light) == speed_of_light
assert convert_to(2*299792458*meter/second, speed_of_light) == 2*speed_of_light
assert convert_to(speed_of_light, meter/second) == 299792458*meter/second
assert convert_to(2*speed_of_light, meter/second) == 599584916*meter/second
assert convert_to(day, second) == 86400*second
assert convert_to(2*hour, minute) == 120*minute
assert convert_to(mile, meter) == 201168*meter/125
assert convert_to(mile/hour, kilometer/hour) == 25146*kilometer/(15625*hour)
assert convert_to(3*newton, meter/second) == 3*newton
assert convert_to(3*newton, kilogram*meter/second**2) == 3*meter*kilogram/second**2
assert convert_to(kilometer + mile, meter) == 326168*meter/125
assert convert_to(2*kilometer + 3*mile, meter) == 853504*meter/125
assert convert_to(inch**2, meter**2) == 16129*meter**2/25000000
assert convert_to(3*inch**2, meter) == 48387*meter**2/25000000
assert convert_to(2*kilometer/hour + 3*mile/hour, meter/second) == 53344*meter/(28125*second)
assert convert_to(2*kilometer/hour + 3*mile/hour, centimeter/second) == 213376*centimeter/(1125*second)
assert convert_to(kilometer * (mile + kilometer), meter) == 2609344 * meter ** 2
assert convert_to(steradian, coulomb) == steradian
assert convert_to(radians, degree) == 180*degree/pi
assert convert_to(radians, [meter, degree]) == 180*degree/pi
assert convert_to(pi*radians, degree) == 180*degree
assert convert_to(pi, degree) == 180*degree
def test_convert_to_tuples_of_quantities():
assert convert_to(speed_of_light, [meter, second]) == 299792458 * meter / second
assert convert_to(speed_of_light, (meter, second)) == 299792458 * meter / second
assert convert_to(speed_of_light, Tuple(meter, second)) == 299792458 * meter / second
assert convert_to(joule, [meter, kilogram, second]) == kilogram*meter**2/second**2
assert convert_to(joule, [centimeter, gram, second]) == 10000000*centimeter**2*gram/second**2
assert convert_to(299792458*meter/second, [speed_of_light]) == speed_of_light
assert convert_to(speed_of_light / 2, [meter, second, kilogram]) == meter/second*299792458 / 2
# This doesn't make physically sense, but let's keep it as a conversion test:
assert convert_to(2 * speed_of_light, [meter, second, kilogram]) == 2 * 299792458 * meter / second
assert convert_to(G, [G, speed_of_light, planck]) == 1.0*G
assert NS(convert_to(meter, [G, speed_of_light, hbar]), n=7) == '6.187142e+34*gravitational_constant**0.5000000*hbar**0.5000000/speed_of_light**1.500000'
assert NS(convert_to(planck_mass, kilogram), n=7) == '2.176434e-8*kilogram'
assert NS(convert_to(planck_length, meter), n=7) == '1.616255e-35*meter'
assert NS(convert_to(planck_time, second), n=6) == '5.39125e-44*second'
assert NS(convert_to(planck_temperature, kelvin), n=7) == '1.416784e+32*kelvin'
assert NS(convert_to(convert_to(meter, [G, speed_of_light, planck]), meter), n=10) == '1.000000000*meter'
def test_eval_simplify():
from sympy.physics.units import cm, mm, km, m, K, kilo
from sympy.core.symbol import symbols
x, y = symbols('x y')
assert (cm/mm).simplify() == 10
assert (km/m).simplify() == 1000
assert (km/cm).simplify() == 100000
assert (10*x*K*km**2/m/cm).simplify() == 1000000000*x*kelvin
assert (cm/km/m).simplify() == 1/(10000000*centimeter)
assert (3*kilo*meter).simplify() == 3000*meter
assert (4*kilo*meter/(2*kilometer)).simplify() == 2
assert (4*kilometer**2/(kilo*meter)**2).simplify() == 4
def test_quantity_simplify():
from sympy.physics.units.util import quantity_simplify
from sympy.physics.units import kilo, foot
from sympy.core.symbol import symbols
x, y = symbols('x y')
assert quantity_simplify(x*(8*kilo*newton*meter + y)) == x*(8000*meter*newton + y)
assert quantity_simplify(foot*inch*(foot + inch)) == foot**2*(foot + foot/12)/12
assert quantity_simplify(foot*inch*(foot*foot + inch*(foot + inch))) == foot**2*(foot**2 + foot/12*(foot + foot/12))/12
assert quantity_simplify(2**(foot/inch*kilo/1000)*inch) == 4096*foot/12
assert quantity_simplify(foot**2*inch + inch**2*foot) == 13*foot**3/144
def test_check_dimensions():
x = symbols('x')
assert check_dimensions(inch + x) == inch + x
assert check_dimensions(length + x) == length + x
# after subs we get 2*length; check will clear the constant
assert check_dimensions((length + x).subs(x, length)) == length
assert check_dimensions(newton*meter + joule) == joule + meter*newton
raises(ValueError, lambda: check_dimensions(inch + 1))
raises(ValueError, lambda: check_dimensions(length + 1))
raises(ValueError, lambda: check_dimensions(length + time))
raises(ValueError, lambda: check_dimensions(meter + second))
raises(ValueError, lambda: check_dimensions(2 * meter + second))
raises(ValueError, lambda: check_dimensions(2 * meter + 3 * second))
raises(ValueError, lambda: check_dimensions(1 / second + 1 / meter))
raises(ValueError, lambda: check_dimensions(2 * meter*(mile + centimeter) + km))
|
53e47c27f8941f10e7c461a4971818708a31ecb65bdc022deb12fee9eaccca40 | from sympy.testing.pytest import warns_deprecated_sympy
from sympy.core.symbol import symbols
from sympy.matrices.dense import (Matrix, eye)
from sympy.physics.units.definitions.dimension_definitions import (
action, current, length, mass, time,
velocity)
from sympy.physics.units.dimensions import DimensionSystem
def test_call():
mksa = DimensionSystem((length, time, mass, current), (action,))
with warns_deprecated_sympy():
assert mksa(action) == mksa.print_dim_base(action)
def test_extend():
ms = DimensionSystem((length, time), (velocity,))
mks = ms.extend((mass,), (action,))
res = DimensionSystem((length, time, mass), (velocity, action))
assert mks.base_dims == res.base_dims
assert mks.derived_dims == res.derived_dims
def test_sort_dims():
with warns_deprecated_sympy():
assert (DimensionSystem.sort_dims((length, velocity, time))
== (length, time, velocity))
def test_list_dims():
dimsys = DimensionSystem((length, time, mass))
assert dimsys.list_can_dims == ("length", "mass", "time")
def test_dim_can_vector():
dimsys = DimensionSystem(
[length, mass, time],
[velocity, action],
{
velocity: {length: 1, time: -1}
}
)
assert dimsys.dim_can_vector(length) == Matrix([1, 0, 0])
assert dimsys.dim_can_vector(velocity) == Matrix([1, 0, -1])
dimsys = DimensionSystem(
(length, velocity, action),
(mass, time),
{
time: {length: 1, velocity: -1}
}
)
assert dimsys.dim_can_vector(length) == Matrix([0, 1, 0])
assert dimsys.dim_can_vector(velocity) == Matrix([0, 0, 1])
assert dimsys.dim_can_vector(time) == Matrix([0, 1, -1])
dimsys = DimensionSystem(
(length, mass, time),
(velocity, action),
{velocity: {length: 1, time: -1},
action: {mass: 1, length: 2, time: -1}})
assert dimsys.dim_vector(length) == Matrix([1, 0, 0])
assert dimsys.dim_vector(velocity) == Matrix([1, 0, -1])
def test_inv_can_transf_matrix():
dimsys = DimensionSystem((length, mass, time))
assert dimsys.inv_can_transf_matrix == eye(3)
def test_can_transf_matrix():
dimsys = DimensionSystem((length, mass, time))
assert dimsys.can_transf_matrix == eye(3)
dimsys = DimensionSystem((length, velocity, action))
assert dimsys.can_transf_matrix == eye(3)
dimsys = DimensionSystem((length, time), (velocity,), {velocity: {length: 1, time: -1}})
assert dimsys.can_transf_matrix == eye(2)
def test_is_consistent():
assert DimensionSystem((length, time)).is_consistent is True
def test_print_dim_base():
mksa = DimensionSystem(
(length, time, mass, current),
(action,),
{action: {mass: 1, length: 2, time: -1}})
L, M, T = symbols("L M T")
assert mksa.print_dim_base(action) == L**2*M/T
def test_dim():
dimsys = DimensionSystem(
(length, mass, time),
(velocity, action),
{velocity: {length: 1, time: -1},
action: {mass: 1, length: 2, time: -1}}
)
assert dimsys.dim == 3
|
00738f757633d6a027f755398220720420b0cb3d7a28194a0f8b9fa8430d6e63 | from sympy.concrete.tests.test_sums_products import NS
from sympy.core.singleton import S
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.physics.units import convert_to, coulomb_constant, elementary_charge, gravitational_constant, planck
from sympy.physics.units.definitions.unit_definitions import statcoulomb, coulomb, second, gram, centimeter, erg, \
newton, joule, dyne, speed_of_light, meter
from sympy.physics.units.systems import SI
from sympy.physics.units.systems.cgs import cgs_gauss
def test_conversion_to_from_si():
assert convert_to(statcoulomb, coulomb, cgs_gauss) == 5*coulomb/149896229
assert convert_to(coulomb, statcoulomb, cgs_gauss) == 149896229*statcoulomb/5
assert convert_to(statcoulomb, sqrt(gram*centimeter**3)/second, cgs_gauss) == centimeter**(S(3)/2)*sqrt(gram)/second
assert convert_to(coulomb, sqrt(gram*centimeter**3)/second, cgs_gauss) == 149896229*centimeter**(S(3)/2)*sqrt(gram)/(5*second)
# SI units have an additional base unit, no conversion in case of electromagnetism:
assert convert_to(coulomb, statcoulomb, SI) == coulomb
assert convert_to(statcoulomb, coulomb, SI) == statcoulomb
# SI without electromagnetism:
assert convert_to(erg, joule, SI) == joule/10**7
assert convert_to(erg, joule, cgs_gauss) == joule/10**7
assert convert_to(joule, erg, SI) == 10**7*erg
assert convert_to(joule, erg, cgs_gauss) == 10**7*erg
assert convert_to(dyne, newton, SI) == newton/10**5
assert convert_to(dyne, newton, cgs_gauss) == newton/10**5
assert convert_to(newton, dyne, SI) == 10**5*dyne
assert convert_to(newton, dyne, cgs_gauss) == 10**5*dyne
def test_cgs_gauss_convert_constants():
assert convert_to(speed_of_light, centimeter/second, cgs_gauss) == 29979245800*centimeter/second
assert convert_to(coulomb_constant, 1, cgs_gauss) == 1
assert convert_to(coulomb_constant, newton*meter**2/coulomb**2, cgs_gauss) == 22468879468420441*meter**2*newton/(25000000000*coulomb**2)
assert convert_to(coulomb_constant, newton*meter**2/coulomb**2, SI) == 22468879468420441*meter**2*newton/(2500000*coulomb**2)
assert convert_to(coulomb_constant, dyne*centimeter**2/statcoulomb**2, cgs_gauss) == centimeter**2*dyne/statcoulomb**2
assert convert_to(coulomb_constant, 1, SI) == coulomb_constant
assert NS(convert_to(coulomb_constant, newton*meter**2/coulomb**2, SI)) == '8987551787.36818*meter**2*newton/coulomb**2'
assert convert_to(elementary_charge, statcoulomb, cgs_gauss)
assert convert_to(gravitational_constant, dyne*centimeter**2/gram**2, cgs_gauss)
assert NS(convert_to(planck, erg*second, cgs_gauss)) == '6.62607015e-27*erg*second'
|
ebc177e9e23d0d0a086874299946350b310c7ced91b2a828e9634ebf8c7bbc3c | from sympy.matrices.dense import eye, Matrix
from sympy.tensor.tensor import tensor_indices, TensorHead, tensor_heads, \
TensExpr, canon_bp
from sympy.physics.hep.gamma_matrices import GammaMatrix as G, LorentzIndex, \
kahane_simplify, gamma_trace, _simplify_single_line, simplify_gamma_expression
def _is_tensor_eq(arg1, arg2):
arg1 = canon_bp(arg1)
arg2 = canon_bp(arg2)
if isinstance(arg1, TensExpr):
return arg1.equals(arg2)
elif isinstance(arg2, TensExpr):
return arg2.equals(arg1)
return arg1 == arg2
def execute_gamma_simplify_tests_for_function(tfunc, D):
"""
Perform tests to check if sfunc is able to simplify gamma matrix expressions.
Parameters
==========
`sfunc` a function to simplify a `TIDS`, shall return the simplified `TIDS`.
`D` the number of dimension (in most cases `D=4`).
"""
mu, nu, rho, sigma = tensor_indices("mu, nu, rho, sigma", LorentzIndex)
a1, a2, a3, a4, a5, a6 = tensor_indices("a1:7", LorentzIndex)
mu11, mu12, mu21, mu31, mu32, mu41, mu51, mu52 = tensor_indices("mu11, mu12, mu21, mu31, mu32, mu41, mu51, mu52", LorentzIndex)
mu61, mu71, mu72 = tensor_indices("mu61, mu71, mu72", LorentzIndex)
m0, m1, m2, m3, m4, m5, m6 = tensor_indices("m0:7", LorentzIndex)
def g(xx, yy):
return (G(xx)*G(yy) + G(yy)*G(xx))/2
# Some examples taken from Kahane's paper, 4 dim only:
if D == 4:
t = (G(a1)*G(mu11)*G(a2)*G(mu21)*G(-a1)*G(mu31)*G(-a2))
assert _is_tensor_eq(tfunc(t), -4*G(mu11)*G(mu31)*G(mu21) - 4*G(mu31)*G(mu11)*G(mu21))
t = (G(a1)*G(mu11)*G(mu12)*\
G(a2)*G(mu21)*\
G(a3)*G(mu31)*G(mu32)*\
G(a4)*G(mu41)*\
G(-a2)*G(mu51)*G(mu52)*\
G(-a1)*G(mu61)*\
G(-a3)*G(mu71)*G(mu72)*\
G(-a4))
assert _is_tensor_eq(tfunc(t), \
16*G(mu31)*G(mu32)*G(mu72)*G(mu71)*G(mu11)*G(mu52)*G(mu51)*G(mu12)*G(mu61)*G(mu21)*G(mu41) + 16*G(mu31)*G(mu32)*G(mu72)*G(mu71)*G(mu12)*G(mu51)*G(mu52)*G(mu11)*G(mu61)*G(mu21)*G(mu41) + 16*G(mu71)*G(mu72)*G(mu32)*G(mu31)*G(mu11)*G(mu52)*G(mu51)*G(mu12)*G(mu61)*G(mu21)*G(mu41) + 16*G(mu71)*G(mu72)*G(mu32)*G(mu31)*G(mu12)*G(mu51)*G(mu52)*G(mu11)*G(mu61)*G(mu21)*G(mu41))
# Fully Lorentz-contracted expressions, these return scalars:
def add_delta(ne):
return ne * eye(4) # DiracSpinorIndex.delta(DiracSpinorIndex.auto_left, -DiracSpinorIndex.auto_right)
t = (G(mu)*G(-mu))
ts = add_delta(D)
assert _is_tensor_eq(tfunc(t), ts)
t = (G(mu)*G(nu)*G(-mu)*G(-nu))
ts = add_delta(2*D - D**2) # -8
assert _is_tensor_eq(tfunc(t), ts)
t = (G(mu)*G(nu)*G(-nu)*G(-mu))
ts = add_delta(D**2) # 16
assert _is_tensor_eq(tfunc(t), ts)
t = (G(mu)*G(nu)*G(-rho)*G(-nu)*G(-mu)*G(rho))
ts = add_delta(4*D - 4*D**2 + D**3) # 16
assert _is_tensor_eq(tfunc(t), ts)
t = (G(mu)*G(nu)*G(rho)*G(-rho)*G(-nu)*G(-mu))
ts = add_delta(D**3) # 64
assert _is_tensor_eq(tfunc(t), ts)
t = (G(a1)*G(a2)*G(a3)*G(a4)*G(-a3)*G(-a1)*G(-a2)*G(-a4))
ts = add_delta(-8*D + 16*D**2 - 8*D**3 + D**4) # -32
assert _is_tensor_eq(tfunc(t), ts)
t = (G(-mu)*G(-nu)*G(-rho)*G(-sigma)*G(nu)*G(mu)*G(sigma)*G(rho))
ts = add_delta(-16*D + 24*D**2 - 8*D**3 + D**4) # 64
assert _is_tensor_eq(tfunc(t), ts)
t = (G(-mu)*G(nu)*G(-rho)*G(sigma)*G(rho)*G(-nu)*G(mu)*G(-sigma))
ts = add_delta(8*D - 12*D**2 + 6*D**3 - D**4) # -32
assert _is_tensor_eq(tfunc(t), ts)
t = (G(a1)*G(a2)*G(a3)*G(a4)*G(a5)*G(-a3)*G(-a2)*G(-a1)*G(-a5)*G(-a4))
ts = add_delta(64*D - 112*D**2 + 60*D**3 - 12*D**4 + D**5) # 256
assert _is_tensor_eq(tfunc(t), ts)
t = (G(a1)*G(a2)*G(a3)*G(a4)*G(a5)*G(-a3)*G(-a1)*G(-a2)*G(-a4)*G(-a5))
ts = add_delta(64*D - 120*D**2 + 72*D**3 - 16*D**4 + D**5) # -128
assert _is_tensor_eq(tfunc(t), ts)
t = (G(a1)*G(a2)*G(a3)*G(a4)*G(a5)*G(a6)*G(-a3)*G(-a2)*G(-a1)*G(-a6)*G(-a5)*G(-a4))
ts = add_delta(416*D - 816*D**2 + 528*D**3 - 144*D**4 + 18*D**5 - D**6) # -128
assert _is_tensor_eq(tfunc(t), ts)
t = (G(a1)*G(a2)*G(a3)*G(a4)*G(a5)*G(a6)*G(-a2)*G(-a3)*G(-a1)*G(-a6)*G(-a4)*G(-a5))
ts = add_delta(416*D - 848*D**2 + 584*D**3 - 172*D**4 + 22*D**5 - D**6) # -128
assert _is_tensor_eq(tfunc(t), ts)
# Expressions with free indices:
t = (G(mu)*G(nu)*G(rho)*G(sigma)*G(-mu))
assert _is_tensor_eq(tfunc(t), (-2*G(sigma)*G(rho)*G(nu) + (4-D)*G(nu)*G(rho)*G(sigma)))
t = (G(mu)*G(nu)*G(-mu))
assert _is_tensor_eq(tfunc(t), (2-D)*G(nu))
t = (G(mu)*G(nu)*G(rho)*G(-mu))
assert _is_tensor_eq(tfunc(t), 2*G(nu)*G(rho) + 2*G(rho)*G(nu) - (4-D)*G(nu)*G(rho))
t = 2*G(m2)*G(m0)*G(m1)*G(-m0)*G(-m1)
st = tfunc(t)
assert _is_tensor_eq(st, (D*(-2*D + 4))*G(m2))
t = G(m2)*G(m0)*G(m1)*G(-m0)*G(-m2)
st = tfunc(t)
assert _is_tensor_eq(st, ((-D + 2)**2)*G(m1))
t = G(m0)*G(m1)*G(m2)*G(m3)*G(-m1)
st = tfunc(t)
assert _is_tensor_eq(st, (D - 4)*G(m0)*G(m2)*G(m3) + 4*G(m0)*g(m2, m3))
t = G(m0)*G(m1)*G(m2)*G(m3)*G(-m1)*G(-m0)
st = tfunc(t)
assert _is_tensor_eq(st, ((D - 4)**2)*G(m2)*G(m3) + (8*D - 16)*g(m2, m3))
t = G(m2)*G(m0)*G(m1)*G(-m2)*G(-m0)
st = tfunc(t)
assert _is_tensor_eq(st, ((-D + 2)*(D - 4) + 4)*G(m1))
t = G(m3)*G(m1)*G(m0)*G(m2)*G(-m3)*G(-m0)*G(-m2)
st = tfunc(t)
assert _is_tensor_eq(st, (-4*D + (-D + 2)**2*(D - 4) + 8)*G(m1))
t = 2*G(m0)*G(m1)*G(m2)*G(m3)*G(-m0)
st = tfunc(t)
assert _is_tensor_eq(st, ((-2*D + 8)*G(m1)*G(m2)*G(m3) - 4*G(m3)*G(m2)*G(m1)))
t = G(m5)*G(m0)*G(m1)*G(m4)*G(m2)*G(-m4)*G(m3)*G(-m0)
st = tfunc(t)
assert _is_tensor_eq(st, (((-D + 2)*(-D + 4))*G(m5)*G(m1)*G(m2)*G(m3) + (2*D - 4)*G(m5)*G(m3)*G(m2)*G(m1)))
t = -G(m0)*G(m1)*G(m2)*G(m3)*G(-m0)*G(m4)
st = tfunc(t)
assert _is_tensor_eq(st, ((D - 4)*G(m1)*G(m2)*G(m3)*G(m4) + 2*G(m3)*G(m2)*G(m1)*G(m4)))
t = G(-m5)*G(m0)*G(m1)*G(m2)*G(m3)*G(m4)*G(-m0)*G(m5)
st = tfunc(t)
result1 = ((-D + 4)**2 + 4)*G(m1)*G(m2)*G(m3)*G(m4) +\
(4*D - 16)*G(m3)*G(m2)*G(m1)*G(m4) + (4*D - 16)*G(m4)*G(m1)*G(m2)*G(m3)\
+ 4*G(m2)*G(m1)*G(m4)*G(m3) + 4*G(m3)*G(m4)*G(m1)*G(m2) +\
4*G(m4)*G(m3)*G(m2)*G(m1)
# Kahane's algorithm yields this result, which is equivalent to `result1`
# in four dimensions, but is not automatically recognized as equal:
result2 = 8*G(m1)*G(m2)*G(m3)*G(m4) + 8*G(m4)*G(m3)*G(m2)*G(m1)
if D == 4:
assert _is_tensor_eq(st, (result1)) or _is_tensor_eq(st, (result2))
else:
assert _is_tensor_eq(st, (result1))
# and a few very simple cases, with no contracted indices:
t = G(m0)
st = tfunc(t)
assert _is_tensor_eq(st, t)
t = -7*G(m0)
st = tfunc(t)
assert _is_tensor_eq(st, t)
t = 224*G(m0)*G(m1)*G(-m2)*G(m3)
st = tfunc(t)
assert _is_tensor_eq(st, t)
def test_kahane_algorithm():
# Wrap this function to convert to and from TIDS:
def tfunc(e):
return _simplify_single_line(e)
execute_gamma_simplify_tests_for_function(tfunc, D=4)
def test_kahane_simplify1():
i0,i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,i11,i12,i13,i14,i15 = tensor_indices('i0:16', LorentzIndex)
mu, nu, rho, sigma = tensor_indices("mu, nu, rho, sigma", LorentzIndex)
D = 4
t = G(i0)*G(i1)
r = kahane_simplify(t)
assert r.equals(t)
t = G(i0)*G(i1)*G(-i0)
r = kahane_simplify(t)
assert r.equals(-2*G(i1))
t = G(i0)*G(i1)*G(-i0)
r = kahane_simplify(t)
assert r.equals(-2*G(i1))
t = G(i0)*G(i1)
r = kahane_simplify(t)
assert r.equals(t)
t = G(i0)*G(i1)
r = kahane_simplify(t)
assert r.equals(t)
t = G(i0)*G(-i0)
r = kahane_simplify(t)
assert r.equals(4*eye(4))
t = G(i0)*G(-i0)
r = kahane_simplify(t)
assert r.equals(4*eye(4))
t = G(i0)*G(-i0)
r = kahane_simplify(t)
assert r.equals(4*eye(4))
t = G(i0)*G(i1)*G(-i0)
r = kahane_simplify(t)
assert r.equals(-2*G(i1))
t = G(i0)*G(i1)*G(-i0)*G(-i1)
r = kahane_simplify(t)
assert r.equals((2*D - D**2)*eye(4))
t = G(i0)*G(i1)*G(-i0)*G(-i1)
r = kahane_simplify(t)
assert r.equals((2*D - D**2)*eye(4))
t = G(i0)*G(-i0)*G(i1)*G(-i1)
r = kahane_simplify(t)
assert r.equals(16*eye(4))
t = (G(mu)*G(nu)*G(-nu)*G(-mu))
r = kahane_simplify(t)
assert r.equals(D**2*eye(4))
t = (G(mu)*G(nu)*G(-nu)*G(-mu))
r = kahane_simplify(t)
assert r.equals(D**2*eye(4))
t = (G(mu)*G(nu)*G(-nu)*G(-mu))
r = kahane_simplify(t)
assert r.equals(D**2*eye(4))
t = (G(mu)*G(nu)*G(-rho)*G(-nu)*G(-mu)*G(rho))
r = kahane_simplify(t)
assert r.equals((4*D - 4*D**2 + D**3)*eye(4))
t = (G(-mu)*G(-nu)*G(-rho)*G(-sigma)*G(nu)*G(mu)*G(sigma)*G(rho))
r = kahane_simplify(t)
assert r.equals((-16*D + 24*D**2 - 8*D**3 + D**4)*eye(4))
t = (G(-mu)*G(nu)*G(-rho)*G(sigma)*G(rho)*G(-nu)*G(mu)*G(-sigma))
r = kahane_simplify(t)
assert r.equals((8*D - 12*D**2 + 6*D**3 - D**4)*eye(4))
# Expressions with free indices:
t = (G(mu)*G(nu)*G(rho)*G(sigma)*G(-mu))
r = kahane_simplify(t)
assert r.equals(-2*G(sigma)*G(rho)*G(nu))
t = (G(mu)*G(nu)*G(rho)*G(sigma)*G(-mu))
r = kahane_simplify(t)
assert r.equals(-2*G(sigma)*G(rho)*G(nu))
def test_gamma_matrix_class():
i, j, k = tensor_indices('i,j,k', LorentzIndex)
# define another type of TensorHead to see if exprs are correctly handled:
A = TensorHead('A', [LorentzIndex])
t = A(k)*G(i)*G(-i)
ts = simplify_gamma_expression(t)
assert _is_tensor_eq(ts, Matrix([
[4, 0, 0, 0],
[0, 4, 0, 0],
[0, 0, 4, 0],
[0, 0, 0, 4]])*A(k))
t = G(i)*A(k)*G(j)
ts = simplify_gamma_expression(t)
assert _is_tensor_eq(ts, A(k)*G(i)*G(j))
execute_gamma_simplify_tests_for_function(simplify_gamma_expression, D=4)
def test_gamma_matrix_trace():
g = LorentzIndex.metric
m0, m1, m2, m3, m4, m5, m6 = tensor_indices('m0:7', LorentzIndex)
n0, n1, n2, n3, n4, n5 = tensor_indices('n0:6', LorentzIndex)
# working in D=4 dimensions
D = 4
# traces of odd number of gamma matrices are zero:
t = G(m0)
t1 = gamma_trace(t)
assert t1.equals(0)
t = G(m0)*G(m1)*G(m2)
t1 = gamma_trace(t)
assert t1.equals(0)
t = G(m0)*G(m1)*G(-m0)
t1 = gamma_trace(t)
assert t1.equals(0)
t = G(m0)*G(m1)*G(m2)*G(m3)*G(m4)
t1 = gamma_trace(t)
assert t1.equals(0)
# traces without internal contractions:
t = G(m0)*G(m1)
t1 = gamma_trace(t)
assert _is_tensor_eq(t1, 4*g(m0, m1))
t = G(m0)*G(m1)*G(m2)*G(m3)
t1 = gamma_trace(t)
t2 = -4*g(m0, m2)*g(m1, m3) + 4*g(m0, m1)*g(m2, m3) + 4*g(m0, m3)*g(m1, m2)
assert _is_tensor_eq(t1, t2)
t = G(m0)*G(m1)*G(m2)*G(m3)*G(m4)*G(m5)
t1 = gamma_trace(t)
t2 = t1*g(-m0, -m5)
t2 = t2.contract_metric(g)
assert _is_tensor_eq(t2, D*gamma_trace(G(m1)*G(m2)*G(m3)*G(m4)))
# traces of expressions with internal contractions:
t = G(m0)*G(-m0)
t1 = gamma_trace(t)
assert t1.equals(4*D)
t = G(m0)*G(m1)*G(-m0)*G(-m1)
t1 = gamma_trace(t)
assert t1.equals(8*D - 4*D**2)
t = G(m0)*G(m1)*G(m2)*G(m3)*G(m4)*G(-m0)
t1 = gamma_trace(t)
t2 = (-4*D)*g(m1, m3)*g(m2, m4) + (4*D)*g(m1, m2)*g(m3, m4) + \
(4*D)*g(m1, m4)*g(m2, m3)
assert _is_tensor_eq(t1, t2)
t = G(-m5)*G(m0)*G(m1)*G(m2)*G(m3)*G(m4)*G(-m0)*G(m5)
t1 = gamma_trace(t)
t2 = (32*D + 4*(-D + 4)**2 - 64)*(g(m1, m2)*g(m3, m4) - \
g(m1, m3)*g(m2, m4) + g(m1, m4)*g(m2, m3))
assert _is_tensor_eq(t1, t2)
t = G(m0)*G(m1)*G(-m0)*G(m3)
t1 = gamma_trace(t)
assert t1.equals((-4*D + 8)*g(m1, m3))
# p, q = S1('p,q')
# ps = p(m0)*G(-m0)
# qs = q(m0)*G(-m0)
# t = ps*qs*ps*qs
# t1 = gamma_trace(t)
# assert t1 == 8*p(m0)*q(-m0)*p(m1)*q(-m1) - 4*p(m0)*p(-m0)*q(m1)*q(-m1)
t = G(m0)*G(m1)*G(m2)*G(m3)*G(m4)*G(m5)*G(-m0)*G(-m1)*G(-m2)*G(-m3)*G(-m4)*G(-m5)
t1 = gamma_trace(t)
assert t1.equals(-4*D**6 + 120*D**5 - 1040*D**4 + 3360*D**3 - 4480*D**2 + 2048*D)
t = G(m0)*G(m1)*G(n1)*G(m2)*G(n2)*G(m3)*G(m4)*G(-n2)*G(-n1)*G(-m0)*G(-m1)*G(-m2)*G(-m3)*G(-m4)
t1 = gamma_trace(t)
tresu = -7168*D + 16768*D**2 - 14400*D**3 + 5920*D**4 - 1232*D**5 + 120*D**6 - 4*D**7
assert t1.equals(tresu)
# checked with Mathematica
# In[1]:= <<Tracer.m
# In[2]:= Spur[l];
# In[3]:= GammaTrace[l, {m0},{m1},{n1},{m2},{n2},{m3},{m4},{n3},{n4},{m0},{m1},{m2},{m3},{m4}]
t = G(m0)*G(m1)*G(n1)*G(m2)*G(n2)*G(m3)*G(m4)*G(n3)*G(n4)*G(-m0)*G(-m1)*G(-m2)*G(-m3)*G(-m4)
t1 = gamma_trace(t)
# t1 = t1.expand_coeff()
c1 = -4*D**5 + 120*D**4 - 1200*D**3 + 5280*D**2 - 10560*D + 7808
c2 = -4*D**5 + 88*D**4 - 560*D**3 + 1440*D**2 - 1600*D + 640
assert _is_tensor_eq(t1, c1*g(n1, n4)*g(n2, n3) + c2*g(n1, n2)*g(n3, n4) + \
(-c1)*g(n1, n3)*g(n2, n4))
p, q = tensor_heads('p,q', [LorentzIndex])
ps = p(m0)*G(-m0)
qs = q(m0)*G(-m0)
p2 = p(m0)*p(-m0)
q2 = q(m0)*q(-m0)
pq = p(m0)*q(-m0)
t = ps*qs*ps*qs
r = gamma_trace(t)
assert _is_tensor_eq(r, 8*pq*pq - 4*p2*q2)
t = ps*qs*ps*qs*ps*qs
r = gamma_trace(t)
assert _is_tensor_eq(r, -12*p2*pq*q2 + 16*pq*pq*pq)
t = ps*qs*ps*qs*ps*qs*ps*qs
r = gamma_trace(t)
assert _is_tensor_eq(r, -32*pq*pq*p2*q2 + 32*pq*pq*pq*pq + 4*p2*p2*q2*q2)
t = 4*p(m1)*p(m0)*p(-m0)*q(-m1)*q(m2)*q(-m2)
assert _is_tensor_eq(gamma_trace(t), t)
t = ps*ps*ps*ps*ps*ps*ps*ps
r = gamma_trace(t)
assert r.equals(4*p2*p2*p2*p2)
|
e60474d71f4796a33f0d589296eed87f59b9350588da8a817b56b77519017087 | from sympy.core.numbers import pi
from sympy.core.singleton import S
from sympy.core.symbol import symbols
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.integrals.integrals import Integral
from sympy.physics.vector import Dyadic, Point, ReferenceFrame, Vector
from sympy.physics.vector.functions import (cross, dot, express,
time_derivative,
kinematic_equations, outer,
partial_velocity,
get_motion_params, dynamicsymbols)
from sympy.testing.pytest import raises
Vector.simp = True
q1, q2, q3, q4, q5 = symbols('q1 q2 q3 q4 q5')
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])
def test_dot():
assert dot(A.x, A.x) == 1
assert dot(A.x, A.y) == 0
assert dot(A.x, A.z) == 0
assert dot(A.y, A.x) == 0
assert dot(A.y, A.y) == 1
assert dot(A.y, A.z) == 0
assert dot(A.z, A.x) == 0
assert dot(A.z, A.y) == 0
assert dot(A.z, A.z) == 1
def test_dot_different_frames():
assert dot(N.x, A.x) == cos(q1)
assert dot(N.x, A.y) == -sin(q1)
assert dot(N.x, A.z) == 0
assert dot(N.y, A.x) == sin(q1)
assert dot(N.y, A.y) == cos(q1)
assert dot(N.y, A.z) == 0
assert dot(N.z, A.x) == 0
assert dot(N.z, A.y) == 0
assert dot(N.z, A.z) == 1
assert dot(N.x, A.x + A.y) == sqrt(2)*cos(q1 + pi/4) == dot(A.x + A.y, N.x)
assert dot(A.x, C.x) == cos(q3)
assert dot(A.x, C.y) == 0
assert dot(A.x, C.z) == sin(q3)
assert dot(A.y, C.x) == sin(q2)*sin(q3)
assert dot(A.y, C.y) == cos(q2)
assert dot(A.y, C.z) == -sin(q2)*cos(q3)
assert dot(A.z, C.x) == -cos(q2)*sin(q3)
assert dot(A.z, C.y) == sin(q2)
assert dot(A.z, C.z) == cos(q2)*cos(q3)
def test_cross():
assert cross(A.x, A.x) == 0
assert cross(A.x, A.y) == A.z
assert cross(A.x, A.z) == -A.y
assert cross(A.y, A.x) == -A.z
assert cross(A.y, A.y) == 0
assert cross(A.y, A.z) == A.x
assert cross(A.z, A.x) == A.y
assert cross(A.z, A.y) == -A.x
assert cross(A.z, A.z) == 0
def test_cross_different_frames():
assert cross(N.x, A.x) == sin(q1)*A.z
assert cross(N.x, A.y) == cos(q1)*A.z
assert cross(N.x, A.z) == -sin(q1)*A.x - cos(q1)*A.y
assert cross(N.y, A.x) == -cos(q1)*A.z
assert cross(N.y, A.y) == sin(q1)*A.z
assert cross(N.y, A.z) == cos(q1)*A.x - sin(q1)*A.y
assert cross(N.z, A.x) == A.y
assert cross(N.z, A.y) == -A.x
assert cross(N.z, A.z) == 0
assert cross(N.x, A.x) == sin(q1)*A.z
assert cross(N.x, A.y) == cos(q1)*A.z
assert cross(N.x, A.x + A.y) == sin(q1)*A.z + cos(q1)*A.z
assert cross(A.x + A.y, N.x) == -sin(q1)*A.z - cos(q1)*A.z
assert cross(A.x, C.x) == sin(q3)*C.y
assert cross(A.x, C.y) == -sin(q3)*C.x + cos(q3)*C.z
assert cross(A.x, C.z) == -cos(q3)*C.y
assert cross(C.x, A.x) == -sin(q3)*C.y
assert cross(C.y, A.x) == sin(q3)*C.x - cos(q3)*C.z
assert cross(C.z, A.x) == cos(q3)*C.y
def test_operator_match():
"""Test that the output of dot, cross, outer functions match
operator behavior.
"""
A = ReferenceFrame('A')
v = A.x + A.y
d = v | v
zerov = Vector(0)
zerod = Dyadic(0)
# dot products
assert d & d == dot(d, d)
assert d & zerod == dot(d, zerod)
assert zerod & d == dot(zerod, d)
assert d & v == dot(d, v)
assert v & d == dot(v, d)
assert d & zerov == dot(d, zerov)
assert zerov & d == dot(zerov, d)
raises(TypeError, lambda: dot(d, S.Zero))
raises(TypeError, lambda: dot(S.Zero, d))
raises(TypeError, lambda: dot(d, 0))
raises(TypeError, lambda: dot(0, d))
assert v & v == dot(v, v)
assert v & zerov == dot(v, zerov)
assert zerov & v == dot(zerov, v)
raises(TypeError, lambda: dot(v, S.Zero))
raises(TypeError, lambda: dot(S.Zero, v))
raises(TypeError, lambda: dot(v, 0))
raises(TypeError, lambda: dot(0, v))
# cross products
raises(TypeError, lambda: cross(d, d))
raises(TypeError, lambda: cross(d, zerod))
raises(TypeError, lambda: cross(zerod, d))
assert d ^ v == cross(d, v)
assert v ^ d == cross(v, d)
assert d ^ zerov == cross(d, zerov)
assert zerov ^ d == cross(zerov, d)
assert zerov ^ d == cross(zerov, d)
raises(TypeError, lambda: cross(d, S.Zero))
raises(TypeError, lambda: cross(S.Zero, d))
raises(TypeError, lambda: cross(d, 0))
raises(TypeError, lambda: cross(0, d))
assert v ^ v == cross(v, v)
assert v ^ zerov == cross(v, zerov)
assert zerov ^ v == cross(zerov, v)
raises(TypeError, lambda: cross(v, S.Zero))
raises(TypeError, lambda: cross(S.Zero, v))
raises(TypeError, lambda: cross(v, 0))
raises(TypeError, lambda: cross(0, v))
# outer products
raises(TypeError, lambda: outer(d, d))
raises(TypeError, lambda: outer(d, zerod))
raises(TypeError, lambda: outer(zerod, d))
raises(TypeError, lambda: outer(d, v))
raises(TypeError, lambda: outer(v, d))
raises(TypeError, lambda: outer(d, zerov))
raises(TypeError, lambda: outer(zerov, d))
raises(TypeError, lambda: outer(zerov, d))
raises(TypeError, lambda: outer(d, S.Zero))
raises(TypeError, lambda: outer(S.Zero, d))
raises(TypeError, lambda: outer(d, 0))
raises(TypeError, lambda: outer(0, d))
assert v | v == outer(v, v)
assert v | zerov == outer(v, zerov)
assert zerov | v == outer(zerov, v)
raises(TypeError, lambda: outer(v, S.Zero))
raises(TypeError, lambda: outer(S.Zero, v))
raises(TypeError, lambda: outer(v, 0))
raises(TypeError, lambda: outer(0, v))
def test_express():
assert express(Vector(0), N) == Vector(0)
assert express(S.Zero, N) is S.Zero
assert express(A.x, C) == cos(q3)*C.x + sin(q3)*C.z
assert express(A.y, C) == sin(q2)*sin(q3)*C.x + cos(q2)*C.y - \
sin(q2)*cos(q3)*C.z
assert express(A.z, C) == -sin(q3)*cos(q2)*C.x + sin(q2)*C.y + \
cos(q2)*cos(q3)*C.z
assert express(A.x, N) == cos(q1)*N.x + sin(q1)*N.y
assert express(A.y, N) == -sin(q1)*N.x + cos(q1)*N.y
assert express(A.z, N) == N.z
assert express(A.x, A) == A.x
assert express(A.y, A) == A.y
assert express(A.z, A) == A.z
assert express(A.x, B) == B.x
assert express(A.y, B) == cos(q2)*B.y - sin(q2)*B.z
assert express(A.z, B) == sin(q2)*B.y + cos(q2)*B.z
assert express(A.x, C) == cos(q3)*C.x + sin(q3)*C.z
assert express(A.y, C) == sin(q2)*sin(q3)*C.x + cos(q2)*C.y - \
sin(q2)*cos(q3)*C.z
assert express(A.z, C) == -sin(q3)*cos(q2)*C.x + sin(q2)*C.y + \
cos(q2)*cos(q3)*C.z
# Check to make sure UnitVectors get converted properly
assert express(N.x, N) == N.x
assert express(N.y, N) == N.y
assert express(N.z, N) == N.z
assert express(N.x, A) == (cos(q1)*A.x - sin(q1)*A.y)
assert express(N.y, A) == (sin(q1)*A.x + cos(q1)*A.y)
assert express(N.z, A) == A.z
assert express(N.x, B) == (cos(q1)*B.x - sin(q1)*cos(q2)*B.y +
sin(q1)*sin(q2)*B.z)
assert express(N.y, B) == (sin(q1)*B.x + cos(q1)*cos(q2)*B.y -
sin(q2)*cos(q1)*B.z)
assert express(N.z, B) == (sin(q2)*B.y + cos(q2)*B.z)
assert express(N.x, C) == (
(cos(q1)*cos(q3) - sin(q1)*sin(q2)*sin(q3))*C.x -
sin(q1)*cos(q2)*C.y +
(sin(q3)*cos(q1) + sin(q1)*sin(q2)*cos(q3))*C.z)
assert express(N.y, C) == (
(sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1))*C.x +
cos(q1)*cos(q2)*C.y +
(sin(q1)*sin(q3) - sin(q2)*cos(q1)*cos(q3))*C.z)
assert express(N.z, C) == (-sin(q3)*cos(q2)*C.x + sin(q2)*C.y +
cos(q2)*cos(q3)*C.z)
assert express(A.x, N) == (cos(q1)*N.x + sin(q1)*N.y)
assert express(A.y, N) == (-sin(q1)*N.x + cos(q1)*N.y)
assert express(A.z, N) == N.z
assert express(A.x, A) == A.x
assert express(A.y, A) == A.y
assert express(A.z, A) == A.z
assert express(A.x, B) == B.x
assert express(A.y, B) == (cos(q2)*B.y - sin(q2)*B.z)
assert express(A.z, B) == (sin(q2)*B.y + cos(q2)*B.z)
assert express(A.x, C) == (cos(q3)*C.x + sin(q3)*C.z)
assert express(A.y, C) == (sin(q2)*sin(q3)*C.x + cos(q2)*C.y -
sin(q2)*cos(q3)*C.z)
assert express(A.z, C) == (-sin(q3)*cos(q2)*C.x + sin(q2)*C.y +
cos(q2)*cos(q3)*C.z)
assert express(B.x, N) == (cos(q1)*N.x + sin(q1)*N.y)
assert express(B.y, N) == (-sin(q1)*cos(q2)*N.x +
cos(q1)*cos(q2)*N.y + sin(q2)*N.z)
assert express(B.z, N) == (sin(q1)*sin(q2)*N.x -
sin(q2)*cos(q1)*N.y + cos(q2)*N.z)
assert express(B.x, A) == A.x
assert express(B.y, A) == (cos(q2)*A.y + sin(q2)*A.z)
assert express(B.z, A) == (-sin(q2)*A.y + cos(q2)*A.z)
assert express(B.x, B) == B.x
assert express(B.y, B) == B.y
assert express(B.z, B) == B.z
assert express(B.x, C) == (cos(q3)*C.x + sin(q3)*C.z)
assert express(B.y, C) == C.y
assert express(B.z, C) == (-sin(q3)*C.x + cos(q3)*C.z)
assert express(C.x, N) == (
(cos(q1)*cos(q3) - sin(q1)*sin(q2)*sin(q3))*N.x +
(sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1))*N.y -
sin(q3)*cos(q2)*N.z)
assert express(C.y, N) == (
-sin(q1)*cos(q2)*N.x + cos(q1)*cos(q2)*N.y + sin(q2)*N.z)
assert express(C.z, N) == (
(sin(q3)*cos(q1) + sin(q1)*sin(q2)*cos(q3))*N.x +
(sin(q1)*sin(q3) - sin(q2)*cos(q1)*cos(q3))*N.y +
cos(q2)*cos(q3)*N.z)
assert express(C.x, A) == (cos(q3)*A.x + sin(q2)*sin(q3)*A.y -
sin(q3)*cos(q2)*A.z)
assert express(C.y, A) == (cos(q2)*A.y + sin(q2)*A.z)
assert express(C.z, A) == (sin(q3)*A.x - sin(q2)*cos(q3)*A.y +
cos(q2)*cos(q3)*A.z)
assert express(C.x, B) == (cos(q3)*B.x - sin(q3)*B.z)
assert express(C.y, B) == B.y
assert express(C.z, B) == (sin(q3)*B.x + cos(q3)*B.z)
assert express(C.x, C) == C.x
assert express(C.y, C) == C.y
assert express(C.z, C) == C.z == (C.z)
# Check to make sure Vectors get converted back to UnitVectors
assert N.x == express((cos(q1)*A.x - sin(q1)*A.y), N)
assert N.y == express((sin(q1)*A.x + cos(q1)*A.y), N)
assert N.x == express((cos(q1)*B.x - sin(q1)*cos(q2)*B.y +
sin(q1)*sin(q2)*B.z), N)
assert N.y == express((sin(q1)*B.x + cos(q1)*cos(q2)*B.y -
sin(q2)*cos(q1)*B.z), N)
assert N.z == express((sin(q2)*B.y + cos(q2)*B.z), N)
"""
These don't really test our code, they instead test the auto simplification
(or lack thereof) of SymPy.
assert N.x == express((
(cos(q1)*cos(q3)-sin(q1)*sin(q2)*sin(q3))*C.x -
sin(q1)*cos(q2)*C.y +
(sin(q3)*cos(q1)+sin(q1)*sin(q2)*cos(q3))*C.z), N)
assert N.y == express((
(sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1))*C.x +
cos(q1)*cos(q2)*C.y +
(sin(q1)*sin(q3) - sin(q2)*cos(q1)*cos(q3))*C.z), N)
assert N.z == express((-sin(q3)*cos(q2)*C.x + sin(q2)*C.y +
cos(q2)*cos(q3)*C.z), N)
"""
assert A.x == express((cos(q1)*N.x + sin(q1)*N.y), A)
assert A.y == express((-sin(q1)*N.x + cos(q1)*N.y), A)
assert A.y == express((cos(q2)*B.y - sin(q2)*B.z), A)
assert A.z == express((sin(q2)*B.y + cos(q2)*B.z), A)
assert A.x == express((cos(q3)*C.x + sin(q3)*C.z), A)
# Tripsimp messes up here too.
#print express((sin(q2)*sin(q3)*C.x + cos(q2)*C.y -
# sin(q2)*cos(q3)*C.z), A)
assert A.y == express((sin(q2)*sin(q3)*C.x + cos(q2)*C.y -
sin(q2)*cos(q3)*C.z), A)
assert A.z == express((-sin(q3)*cos(q2)*C.x + sin(q2)*C.y +
cos(q2)*cos(q3)*C.z), A)
assert B.x == express((cos(q1)*N.x + sin(q1)*N.y), B)
assert B.y == express((-sin(q1)*cos(q2)*N.x +
cos(q1)*cos(q2)*N.y + sin(q2)*N.z), B)
assert B.z == express((sin(q1)*sin(q2)*N.x -
sin(q2)*cos(q1)*N.y + cos(q2)*N.z), B)
assert B.y == express((cos(q2)*A.y + sin(q2)*A.z), B)
assert B.z == express((-sin(q2)*A.y + cos(q2)*A.z), B)
assert B.x == express((cos(q3)*C.x + sin(q3)*C.z), B)
assert B.z == express((-sin(q3)*C.x + cos(q3)*C.z), B)
"""
assert C.x == express((
(cos(q1)*cos(q3)-sin(q1)*sin(q2)*sin(q3))*N.x +
(sin(q1)*cos(q3)+sin(q2)*sin(q3)*cos(q1))*N.y -
sin(q3)*cos(q2)*N.z), C)
assert C.y == express((
-sin(q1)*cos(q2)*N.x + cos(q1)*cos(q2)*N.y + sin(q2)*N.z), C)
assert C.z == express((
(sin(q3)*cos(q1)+sin(q1)*sin(q2)*cos(q3))*N.x +
(sin(q1)*sin(q3)-sin(q2)*cos(q1)*cos(q3))*N.y +
cos(q2)*cos(q3)*N.z), C)
"""
assert C.x == express((cos(q3)*A.x + sin(q2)*sin(q3)*A.y -
sin(q3)*cos(q2)*A.z), C)
assert C.y == express((cos(q2)*A.y + sin(q2)*A.z), C)
assert C.z == express((sin(q3)*A.x - sin(q2)*cos(q3)*A.y +
cos(q2)*cos(q3)*A.z), C)
assert C.x == express((cos(q3)*B.x - sin(q3)*B.z), C)
assert C.z == express((sin(q3)*B.x + cos(q3)*B.z), C)
def test_time_derivative():
#The use of time_derivative for calculations pertaining to scalar
#fields has been tested in test_coordinate_vars in test_essential.py
A = ReferenceFrame('A')
q = dynamicsymbols('q')
qd = dynamicsymbols('q', 1)
B = A.orientnew('B', 'Axis', [q, A.z])
d = A.x | A.x
assert time_derivative(d, B) == (-qd) * (A.y | A.x) + \
(-qd) * (A.x | A.y)
d1 = A.x | B.y
assert time_derivative(d1, A) == - qd*(A.x|B.x)
assert time_derivative(d1, B) == - qd*(A.y|B.y)
d2 = A.x | B.x
assert time_derivative(d2, A) == qd*(A.x|B.y)
assert time_derivative(d2, B) == - qd*(A.y|B.x)
d3 = A.x | B.z
assert time_derivative(d3, A) == 0
assert time_derivative(d3, B) == - qd*(A.y|B.z)
q1, q2, q3, q4 = dynamicsymbols('q1 q2 q3 q4')
q1d, q2d, q3d, q4d = dynamicsymbols('q1 q2 q3 q4', 1)
q1dd, q2dd, q3dd, q4dd = dynamicsymbols('q1 q2 q3 q4', 2)
C = B.orientnew('C', 'Axis', [q4, B.x])
v1 = q1 * A.z
v2 = q2*A.x + q3*B.y
v3 = q1*A.x + q2*A.y + q3*A.z
assert time_derivative(B.x, C) == 0
assert time_derivative(B.y, C) == - q4d*B.z
assert time_derivative(B.z, C) == q4d*B.y
assert time_derivative(v1, B) == q1d*A.z
assert time_derivative(v1, C) == - q1*sin(q)*q4d*A.x + \
q1*cos(q)*q4d*A.y + q1d*A.z
assert time_derivative(v2, A) == q2d*A.x - q3*qd*B.x + q3d*B.y
assert time_derivative(v2, C) == q2d*A.x - q2*qd*A.y + \
q2*sin(q)*q4d*A.z + q3d*B.y - q3*q4d*B.z
assert time_derivative(v3, B) == (q2*qd + q1d)*A.x + \
(-q1*qd + q2d)*A.y + q3d*A.z
assert time_derivative(d, C) == - qd*(A.y|A.x) + \
sin(q)*q4d*(A.z|A.x) - qd*(A.x|A.y) + sin(q)*q4d*(A.x|A.z)
raises(ValueError, lambda: time_derivative(B.x, C, order=0.5))
raises(ValueError, lambda: time_derivative(B.x, C, order=-1))
def test_get_motion_methods():
#Initialization
t = dynamicsymbols._t
s1, s2, s3 = symbols('s1 s2 s3')
S1, S2, S3 = symbols('S1 S2 S3')
S4, S5, S6 = symbols('S4 S5 S6')
t1, t2 = symbols('t1 t2')
a, b, c = dynamicsymbols('a b c')
ad, bd, cd = dynamicsymbols('a b c', 1)
a2d, b2d, c2d = dynamicsymbols('a b c', 2)
v0 = S1*N.x + S2*N.y + S3*N.z
v01 = S4*N.x + S5*N.y + S6*N.z
v1 = s1*N.x + s2*N.y + s3*N.z
v2 = a*N.x + b*N.y + c*N.z
v2d = ad*N.x + bd*N.y + cd*N.z
v2dd = a2d*N.x + b2d*N.y + c2d*N.z
#Test position parameter
assert get_motion_params(frame = N) == (0, 0, 0)
assert get_motion_params(N, position=v1) == (0, 0, v1)
assert get_motion_params(N, position=v2) == (v2dd, v2d, v2)
#Test velocity parameter
assert get_motion_params(N, velocity=v1) == (0, v1, v1 * t)
assert get_motion_params(N, velocity=v1, position=v0, timevalue1=t1) == \
(0, v1, v0 + v1*(t - t1))
answer = get_motion_params(N, velocity=v1, position=v2, timevalue1=t1)
answer_expected = (0, v1, v1*t - v1*t1 + v2.subs(t, t1))
assert answer == answer_expected
answer = get_motion_params(N, velocity=v2, position=v0, timevalue1=t1)
integral_vector = Integral(a, (t, t1, t))*N.x + Integral(b, (t, t1, t))*N.y \
+ Integral(c, (t, t1, t))*N.z
answer_expected = (v2d, v2, v0 + integral_vector)
assert answer == answer_expected
#Test acceleration parameter
assert get_motion_params(N, acceleration=v1) == \
(v1, v1 * t, v1 * t**2/2)
assert get_motion_params(N, acceleration=v1, velocity=v0,
position=v2, timevalue1=t1, timevalue2=t2) == \
(v1, (v0 + v1*t - v1*t2),
-v0*t1 + v1*t**2/2 + v1*t2*t1 - \
v1*t1**2/2 + t*(v0 - v1*t2) + \
v2.subs(t, t1))
assert get_motion_params(N, acceleration=v1, velocity=v0,
position=v01, timevalue1=t1, timevalue2=t2) == \
(v1, v0 + v1*t - v1*t2,
-v0*t1 + v01 + v1*t**2/2 + \
v1*t2*t1 - v1*t1**2/2 + \
t*(v0 - v1*t2))
answer = get_motion_params(N, acceleration=a*N.x, velocity=S1*N.x,
position=S2*N.x, timevalue1=t1, timevalue2=t2)
i1 = Integral(a, (t, t2, t))
answer_expected = (a*N.x, (S1 + i1)*N.x, \
(S2 + Integral(S1 + i1, (t, t1, t)))*N.x)
assert answer == answer_expected
def test_kin_eqs():
q0, q1, q2, q3 = dynamicsymbols('q0 q1 q2 q3')
q0d, q1d, q2d, q3d = dynamicsymbols('q0 q1 q2 q3', 1)
u1, u2, u3 = dynamicsymbols('u1 u2 u3')
ke = kinematic_equations([u1,u2,u3], [q1,q2,q3], 'body', 313)
assert ke == kinematic_equations([u1,u2,u3], [q1,q2,q3], 'body', '313')
kds = kinematic_equations([u1, u2, u3], [q0, q1, q2, q3], 'quaternion')
assert kds == [-0.5 * q0 * u1 - 0.5 * q2 * u3 + 0.5 * q3 * u2 + q1d,
-0.5 * q0 * u2 + 0.5 * q1 * u3 - 0.5 * q3 * u1 + q2d,
-0.5 * q0 * u3 - 0.5 * q1 * u2 + 0.5 * q2 * u1 + q3d,
0.5 * q1 * u1 + 0.5 * q2 * u2 + 0.5 * q3 * u3 + q0d]
raises(ValueError, lambda: kinematic_equations([u1, u2, u3], [q0, q1, q2], 'quaternion'))
raises(ValueError, lambda: kinematic_equations([u1, u2, u3], [q0, q1, q2, q3], 'quaternion', '123'))
raises(ValueError, lambda: kinematic_equations([u1, u2, u3], [q0, q1, q2, q3], 'foo'))
raises(TypeError, lambda: kinematic_equations(u1, [q0, q1, q2, q3], 'quaternion'))
raises(TypeError, lambda: kinematic_equations([u1], [q0, q1, q2, q3], 'quaternion'))
raises(TypeError, lambda: kinematic_equations([u1, u2, u3], q0, 'quaternion'))
raises(ValueError, lambda: kinematic_equations([u1, u2, u3], [q0, q1, q2, q3], 'body'))
raises(ValueError, lambda: kinematic_equations([u1, u2, u3], [q0, q1, q2, q3], 'space'))
raises(ValueError, lambda: kinematic_equations([u1, u2, u3], [q0, q1, q2], 'body', '222'))
assert kinematic_equations([0, 0, 0], [q0, q1, q2], 'space') == [S.Zero, S.Zero, S.Zero]
def test_partial_velocity():
q1, q2, q3, u1, u2, u3 = dynamicsymbols('q1 q2 q3 u1 u2 u3')
u4, u5 = dynamicsymbols('u4, u5')
r = symbols('r')
N = ReferenceFrame('N')
Y = N.orientnew('Y', 'Axis', [q1, N.z])
L = Y.orientnew('L', 'Axis', [q2, Y.x])
R = L.orientnew('R', 'Axis', [q3, L.y])
R.set_ang_vel(N, u1 * L.x + u2 * L.y + u3 * L.z)
C = Point('C')
C.set_vel(N, u4 * L.x + u5 * (Y.z ^ L.x))
Dmc = C.locatenew('Dmc', r * L.z)
Dmc.v2pt_theory(C, N, R)
vel_list = [Dmc.vel(N), C.vel(N), R.ang_vel_in(N)]
u_list = [u1, u2, u3, u4, u5]
assert (partial_velocity(vel_list, u_list, N) ==
[[- r*L.y, r*L.x, 0, L.x, cos(q2)*L.y - sin(q2)*L.z],
[0, 0, 0, L.x, cos(q2)*L.y - sin(q2)*L.z],
[L.x, L.y, L.z, 0, 0]])
# Make sure that partial velocities can be computed regardless if the
# orientation between frames is defined or not.
A = ReferenceFrame('A')
B = ReferenceFrame('B')
v = u4 * A.x + u5 * B.y
assert partial_velocity((v, ), (u4, u5), A) == [[A.x, B.y]]
raises(TypeError, lambda: partial_velocity(Dmc.vel(N), u_list, N))
raises(TypeError, lambda: partial_velocity(vel_list, u1, N))
def test_dynamicsymbols():
#Tests to check the assumptions applied to dynamicsymbols
f1 = dynamicsymbols('f1')
f2 = dynamicsymbols('f2', real=True)
f3 = dynamicsymbols('f3', positive=True)
f4, f5 = dynamicsymbols('f4,f5', commutative=False)
f6 = dynamicsymbols('f6', integer=True)
assert f1.is_real is None
assert f2.is_real
assert f3.is_positive
assert f4*f5 != f5*f4
assert f6.is_integer
|
05d01f935a183ba6f153837a0d9f6e1078b7b68402afbf0fe6fc73d83d7c3a55 | from sympy.core.numbers import (Float, pi)
from sympy.core.symbol import symbols
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.matrices.immutable import ImmutableDenseMatrix as Matrix
from sympy.physics.vector import ReferenceFrame, Vector, dynamicsymbols, dot
from sympy.abc import x, y, z
from sympy.testing.pytest import raises
Vector.simp = True
A = ReferenceFrame('A')
def test_Vector():
assert A.x != A.y
assert A.y != A.z
assert A.z != A.x
assert A.x + 0 == A.x
v1 = x*A.x + y*A.y + z*A.z
v2 = x**2*A.x + y**2*A.y + z**2*A.z
v3 = v1 + v2
v4 = v1 - v2
assert isinstance(v1, Vector)
assert dot(v1, A.x) == x
assert dot(v1, A.y) == y
assert dot(v1, A.z) == z
assert isinstance(v2, Vector)
assert dot(v2, A.x) == x**2
assert dot(v2, A.y) == y**2
assert dot(v2, A.z) == z**2
assert isinstance(v3, Vector)
# We probably shouldn't be using simplify in dot...
assert dot(v3, A.x) == x**2 + x
assert dot(v3, A.y) == y**2 + y
assert dot(v3, A.z) == z**2 + z
assert isinstance(v4, Vector)
# We probably shouldn't be using simplify in dot...
assert dot(v4, A.x) == x - x**2
assert dot(v4, A.y) == y - y**2
assert dot(v4, A.z) == z - z**2
assert v1.to_matrix(A) == Matrix([[x], [y], [z]])
q = symbols('q')
B = A.orientnew('B', 'Axis', (q, A.x))
assert v1.to_matrix(B) == Matrix([[x],
[ y * cos(q) + z * sin(q)],
[-y * sin(q) + z * cos(q)]])
#Test the separate method
B = ReferenceFrame('B')
v5 = x*A.x + y*A.y + z*B.z
assert Vector(0).separate() == {}
assert v1.separate() == {A: v1}
assert v5.separate() == {A: x*A.x + y*A.y, B: z*B.z}
#Test the free_symbols property
v6 = x*A.x + y*A.y + z*A.z
assert v6.free_symbols(A) == {x,y,z}
raises(TypeError, lambda: v3.applyfunc(v1))
def test_Vector_diffs():
q1, q2, q3, q4 = dynamicsymbols('q1 q2 q3 q4')
q1d, q2d, q3d, q4d = dynamicsymbols('q1 q2 q3 q4', 1)
q1dd, q2dd, q3dd, q4dd = dynamicsymbols('q1 q2 q3 q4', 2)
N = ReferenceFrame('N')
A = N.orientnew('A', 'Axis', [q3, N.z])
B = A.orientnew('B', 'Axis', [q2, A.x])
v1 = q2 * A.x + q3 * N.y
v2 = q3 * B.x + v1
v3 = v1.dt(B)
v4 = v2.dt(B)
v5 = q1*A.x + q2*A.y + q3*A.z
assert v1.dt(N) == q2d * A.x + q2 * q3d * A.y + q3d * N.y
assert v1.dt(A) == q2d * A.x + q3 * q3d * N.x + q3d * N.y
assert v1.dt(B) == (q2d * A.x + q3 * q3d * N.x + q3d *\
N.y - q3 * cos(q3) * q2d * N.z)
assert v2.dt(N) == (q2d * A.x + (q2 + q3) * q3d * A.y + q3d * B.x + q3d *
N.y)
assert v2.dt(A) == q2d * A.x + q3d * B.x + q3 * q3d * N.x + q3d * N.y
assert v2.dt(B) == (q2d * A.x + q3d * B.x + q3 * q3d * N.x + q3d * N.y -
q3 * cos(q3) * q2d * N.z)
assert v3.dt(N) == (q2dd * A.x + q2d * q3d * A.y + (q3d**2 + q3 * q3dd) *
N.x + q3dd * N.y + (q3 * sin(q3) * q2d * q3d -
cos(q3) * q2d * q3d - q3 * cos(q3) * q2dd) * N.z)
assert v3.dt(A) == (q2dd * A.x + (2 * q3d**2 + q3 * q3dd) * N.x + (q3dd -
q3 * q3d**2) * N.y + (q3 * sin(q3) * q2d * q3d -
cos(q3) * q2d * q3d - q3 * cos(q3) * q2dd) * N.z)
assert v3.dt(B) == (q2dd * A.x - q3 * cos(q3) * q2d**2 * A.y + (2 *
q3d**2 + q3 * q3dd) * N.x + (q3dd - q3 * q3d**2) *
N.y + (2 * q3 * sin(q3) * q2d * q3d - 2 * cos(q3) *
q2d * q3d - q3 * cos(q3) * q2dd) * N.z)
assert v4.dt(N) == (q2dd * A.x + q3d * (q2d + q3d) * A.y + q3dd * B.x +
(q3d**2 + q3 * q3dd) * N.x + q3dd * N.y + (q3 *
sin(q3) * q2d * q3d - cos(q3) * q2d * q3d - q3 *
cos(q3) * q2dd) * N.z)
assert v4.dt(A) == (q2dd * A.x + q3dd * B.x + (2 * q3d**2 + q3 * q3dd) *
N.x + (q3dd - q3 * q3d**2) * N.y + (q3 * sin(q3) *
q2d * q3d - cos(q3) * q2d * q3d - q3 * cos(q3) *
q2dd) * N.z)
assert v4.dt(B) == (q2dd * A.x - q3 * cos(q3) * q2d**2 * A.y + q3dd * B.x +
(2 * q3d**2 + q3 * q3dd) * N.x + (q3dd - q3 * q3d**2) *
N.y + (2 * q3 * sin(q3) * q2d * q3d - 2 * cos(q3) *
q2d * q3d - q3 * cos(q3) * q2dd) * N.z)
assert v5.dt(B) == q1d*A.x + (q3*q2d + q2d)*A.y + (-q2*q2d + q3d)*A.z
assert v5.dt(A) == q1d*A.x + q2d*A.y + q3d*A.z
assert v5.dt(N) == (-q2*q3d + q1d)*A.x + (q1*q3d + q2d)*A.y + q3d*A.z
assert v3.diff(q1d, N) == 0
assert v3.diff(q2d, N) == A.x - q3 * cos(q3) * N.z
assert v3.diff(q3d, N) == q3 * N.x + N.y
assert v3.diff(q1d, A) == 0
assert v3.diff(q2d, A) == A.x - q3 * cos(q3) * N.z
assert v3.diff(q3d, A) == q3 * N.x + N.y
assert v3.diff(q1d, B) == 0
assert v3.diff(q2d, B) == A.x - q3 * cos(q3) * N.z
assert v3.diff(q3d, B) == q3 * N.x + N.y
assert v4.diff(q1d, N) == 0
assert v4.diff(q2d, N) == A.x - q3 * cos(q3) * N.z
assert v4.diff(q3d, N) == B.x + q3 * N.x + N.y
assert v4.diff(q1d, A) == 0
assert v4.diff(q2d, A) == A.x - q3 * cos(q3) * N.z
assert v4.diff(q3d, A) == B.x + q3 * N.x + N.y
assert v4.diff(q1d, B) == 0
assert v4.diff(q2d, B) == A.x - q3 * cos(q3) * N.z
assert v4.diff(q3d, B) == B.x + q3 * N.x + N.y
def test_vector_var_in_dcm():
N = ReferenceFrame('N')
A = ReferenceFrame('A')
B = ReferenceFrame('B')
u1, u2, u3, u4 = dynamicsymbols('u1 u2 u3 u4')
v = u1 * u2 * A.x + u3 * N.y + u4**2 * N.z
assert v.diff(u1, N, var_in_dcm=False) == u2 * A.x
assert v.diff(u1, A, var_in_dcm=False) == u2 * A.x
assert v.diff(u3, N, var_in_dcm=False) == N.y
assert v.diff(u3, A, var_in_dcm=False) == N.y
assert v.diff(u3, B, var_in_dcm=False) == N.y
assert v.diff(u4, N, var_in_dcm=False) == 2 * u4 * N.z
raises(ValueError, lambda: v.diff(u1, N))
def test_vector_simplify():
x, y, z, k, n, m, w, f, s, A = symbols('x, y, z, k, n, m, w, f, s, A')
N = ReferenceFrame('N')
test1 = (1 / x + 1 / y) * N.x
assert (test1 & N.x) != (x + y) / (x * y)
test1 = test1.simplify()
assert (test1 & N.x) == (x + y) / (x * y)
test2 = (A**2 * s**4 / (4 * pi * k * m**3)) * N.x
test2 = test2.simplify()
assert (test2 & N.x) == (A**2 * s**4 / (4 * pi * k * m**3))
test3 = ((4 + 4 * x - 2 * (2 + 2 * x)) / (2 + 2 * x)) * N.x
test3 = test3.simplify()
assert (test3 & N.x) == 0
test4 = ((-4 * x * y**2 - 2 * y**3 - 2 * x**2 * y) / (x + y)**2) * N.x
test4 = test4.simplify()
assert (test4 & N.x) == -2 * y
def test_vector_evalf():
a, b = symbols('a b')
v = pi * A.x
assert v.evalf(2) == Float('3.1416', 2) * A.x
v = pi * A.x + 5 * a * A.y - b * A.z
assert v.evalf(3) == Float('3.1416', 3) * A.x + Float('5', 3) * a * A.y - b * A.z
assert v.evalf(5, subs={a: 1.234, b:5.8973}) == Float('3.1415926536', 5) * A.x + Float('6.17', 5) * A.y - Float('5.8973', 5) * A.z
def test_vector_angle():
A = ReferenceFrame('A')
v1 = A.x + A.y
v2 = A.z
assert v1.angle_between(v2) == pi/2
B = ReferenceFrame('B')
B.orient_axis(A, A.x, pi)
v3 = A.x
v4 = B.x
assert v3.angle_between(v4) == 0
def test_vector_xreplace():
x, y, z = symbols('x y z')
v = x**2 * A.x + x*y * A.y + x*y*z * A.z
assert v.xreplace({x : cos(x)}) == cos(x)**2 * A.x + y*cos(x) * A.y + y*z*cos(x) * A.z
assert v.xreplace({x*y : pi}) == x**2 * A.x + pi * A.y + x*y*z * A.z
assert v.xreplace({x*y*z : 1}) == x**2*A.x + x*y*A.y + A.z
assert v.xreplace({x:1, z:0}) == A.x + y * A.y
raises(TypeError, lambda: v.xreplace())
raises(TypeError, lambda: v.xreplace([x, y]))
|
30b1c556d5d69a9ba04297e27b849a4b0c1a76f87c2a03037f13a686f1ad665f | from sympy.core.numbers import pi
from sympy.core.symbol import symbols
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.matrices.dense import (eye, zeros)
from sympy.matrices.immutable import ImmutableDenseMatrix as Matrix
from sympy.simplify.simplify import simplify
from sympy.physics.vector import (ReferenceFrame, Vector, CoordinateSym,
dynamicsymbols, time_derivative, express,
dot)
from sympy.physics.vector.frame import _check_frame
from sympy.physics.vector.vector import VectorTypeError
from sympy.testing.pytest import raises
import warnings
Vector.simp = True
def test_dict_list():
A = ReferenceFrame('A')
B = ReferenceFrame('B')
C = ReferenceFrame('C')
D = ReferenceFrame('D')
E = ReferenceFrame('E')
F = ReferenceFrame('F')
B.orient_axis(A, A.x, 1.0)
C.orient_axis(B, B.x, 1.0)
D.orient_axis(C, C.x, 1.0)
assert D._dict_list(A, 0) == [D, C, B, A]
E.orient_axis(D, D.x, 1.0)
assert C._dict_list(A, 0) == [C, B, A]
assert C._dict_list(E, 0) == [C, D, E]
# only 0, 1, 2 permitted for second argument
raises(ValueError, lambda: C._dict_list(E, 5))
# no connecting path
raises(ValueError, lambda: F._dict_list(A, 0))
def test_coordinate_vars():
"""Tests the coordinate variables functionality"""
A = ReferenceFrame('A')
assert CoordinateSym('Ax', A, 0) == A[0]
assert CoordinateSym('Ax', A, 1) == A[1]
assert CoordinateSym('Ax', A, 2) == A[2]
raises(ValueError, lambda: CoordinateSym('Ax', A, 3))
q = dynamicsymbols('q')
qd = dynamicsymbols('q', 1)
assert isinstance(A[0], CoordinateSym) and \
isinstance(A[0], CoordinateSym) and \
isinstance(A[0], CoordinateSym)
assert A.variable_map(A) == {A[0]:A[0], A[1]:A[1], A[2]:A[2]}
assert A[0].frame == A
B = A.orientnew('B', 'Axis', [q, A.z])
assert B.variable_map(A) == {B[2]: A[2], B[1]: -A[0]*sin(q) + A[1]*cos(q),
B[0]: A[0]*cos(q) + A[1]*sin(q)}
assert A.variable_map(B) == {A[0]: B[0]*cos(q) - B[1]*sin(q),
A[1]: B[0]*sin(q) + B[1]*cos(q), A[2]: B[2]}
assert time_derivative(B[0], A) == -A[0]*sin(q)*qd + A[1]*cos(q)*qd
assert time_derivative(B[1], A) == -A[0]*cos(q)*qd - A[1]*sin(q)*qd
assert time_derivative(B[2], A) == 0
assert express(B[0], A, variables=True) == A[0]*cos(q) + A[1]*sin(q)
assert express(B[1], A, variables=True) == -A[0]*sin(q) + A[1]*cos(q)
assert express(B[2], A, variables=True) == A[2]
assert time_derivative(A[0]*A.x + A[1]*A.y + A[2]*A.z, B) == A[1]*qd*A.x - A[0]*qd*A.y
assert time_derivative(B[0]*B.x + B[1]*B.y + B[2]*B.z, A) == - B[1]*qd*B.x + B[0]*qd*B.y
assert express(B[0]*B[1]*B[2], A, variables=True) == \
A[2]*(-A[0]*sin(q) + A[1]*cos(q))*(A[0]*cos(q) + A[1]*sin(q))
assert (time_derivative(B[0]*B[1]*B[2], A) -
(A[2]*(-A[0]**2*cos(2*q) -
2*A[0]*A[1]*sin(2*q) +
A[1]**2*cos(2*q))*qd)).trigsimp() == 0
assert express(B[0]*B.x + B[1]*B.y + B[2]*B.z, A) == \
(B[0]*cos(q) - B[1]*sin(q))*A.x + (B[0]*sin(q) + \
B[1]*cos(q))*A.y + B[2]*A.z
assert express(B[0]*B.x + B[1]*B.y + B[2]*B.z, A, variables=True) == \
A[0]*A.x + A[1]*A.y + A[2]*A.z
assert express(A[0]*A.x + A[1]*A.y + A[2]*A.z, B) == \
(A[0]*cos(q) + A[1]*sin(q))*B.x + \
(-A[0]*sin(q) + A[1]*cos(q))*B.y + A[2]*B.z
assert express(A[0]*A.x + A[1]*A.y + A[2]*A.z, B, variables=True) == \
B[0]*B.x + B[1]*B.y + B[2]*B.z
N = B.orientnew('N', 'Axis', [-q, B.z])
assert N.variable_map(A) == {N[0]: A[0], N[2]: A[2], N[1]: A[1]}
C = A.orientnew('C', 'Axis', [q, A.x + A.y + A.z])
mapping = A.variable_map(C)
assert mapping[A[0]] == 2*C[0]*cos(q)/3 + C[0]/3 - 2*C[1]*sin(q + pi/6)/3 +\
C[1]/3 - 2*C[2]*cos(q + pi/3)/3 + C[2]/3
assert mapping[A[1]] == -2*C[0]*cos(q + pi/3)/3 + \
C[0]/3 + 2*C[1]*cos(q)/3 + C[1]/3 - 2*C[2]*sin(q + pi/6)/3 + C[2]/3
assert mapping[A[2]] == -2*C[0]*sin(q + pi/6)/3 + C[0]/3 - \
2*C[1]*cos(q + pi/3)/3 + C[1]/3 + 2*C[2]*cos(q)/3 + C[2]/3
def test_ang_vel():
q1, q2, q3, q4 = dynamicsymbols('q1 q2 q3 q4')
q1d, q2d, q3d, q4d = dynamicsymbols('q1 q2 q3 q4', 1)
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])
u1, u2, u3 = dynamicsymbols('u1 u2 u3')
assert A.ang_vel_in(N) == (q1d)*A.z
assert B.ang_vel_in(N) == (q2d)*B.x + (q1d)*A.z
assert C.ang_vel_in(N) == (q3d)*C.y + (q2d)*B.x + (q1d)*A.z
A2 = N.orientnew('A2', 'Axis', [q4, N.y])
assert N.ang_vel_in(N) == 0
assert N.ang_vel_in(A) == -q1d*N.z
assert N.ang_vel_in(B) == -q1d*A.z - q2d*B.x
assert N.ang_vel_in(C) == -q1d*A.z - q2d*B.x - q3d*B.y
assert N.ang_vel_in(A2) == -q4d*N.y
assert A.ang_vel_in(N) == q1d*N.z
assert A.ang_vel_in(A) == 0
assert A.ang_vel_in(B) == - q2d*B.x
assert A.ang_vel_in(C) == - q2d*B.x - q3d*B.y
assert A.ang_vel_in(A2) == q1d*N.z - q4d*N.y
assert B.ang_vel_in(N) == q1d*A.z + q2d*A.x
assert B.ang_vel_in(A) == q2d*A.x
assert B.ang_vel_in(B) == 0
assert B.ang_vel_in(C) == -q3d*B.y
assert B.ang_vel_in(A2) == q1d*A.z + q2d*A.x - q4d*N.y
assert C.ang_vel_in(N) == q1d*A.z + q2d*A.x + q3d*B.y
assert C.ang_vel_in(A) == q2d*A.x + q3d*C.y
assert C.ang_vel_in(B) == q3d*B.y
assert C.ang_vel_in(C) == 0
assert C.ang_vel_in(A2) == q1d*A.z + q2d*A.x + q3d*B.y - q4d*N.y
assert A2.ang_vel_in(N) == q4d*A2.y
assert A2.ang_vel_in(A) == q4d*A2.y - q1d*N.z
assert A2.ang_vel_in(B) == q4d*N.y - q1d*A.z - q2d*A.x
assert A2.ang_vel_in(C) == q4d*N.y - q1d*A.z - q2d*A.x - q3d*B.y
assert A2.ang_vel_in(A2) == 0
C.set_ang_vel(N, u1*C.x + u2*C.y + u3*C.z)
assert C.ang_vel_in(N) == (u1)*C.x + (u2)*C.y + (u3)*C.z
assert N.ang_vel_in(C) == (-u1)*C.x + (-u2)*C.y + (-u3)*C.z
assert C.ang_vel_in(D) == (u1)*C.x + (u2)*C.y + (u3)*C.z + (-q4d)*D.y
assert D.ang_vel_in(C) == (-u1)*C.x + (-u2)*C.y + (-u3)*C.z + (q4d)*D.y
q0 = dynamicsymbols('q0')
q0d = dynamicsymbols('q0', 1)
E = N.orientnew('E', 'Quaternion', (q0, q1, q2, q3))
assert E.ang_vel_in(N) == (
2 * (q1d * q0 + q2d * q3 - q3d * q2 - q0d * q1) * E.x +
2 * (q2d * q0 + q3d * q1 - q1d * q3 - q0d * q2) * E.y +
2 * (q3d * q0 + q1d * q2 - q2d * q1 - q0d * q3) * E.z)
F = N.orientnew('F', 'Body', (q1, q2, q3), 313)
assert F.ang_vel_in(N) == ((sin(q2)*sin(q3)*q1d + cos(q3)*q2d)*F.x +
(sin(q2)*cos(q3)*q1d - sin(q3)*q2d)*F.y + (cos(q2)*q1d + q3d)*F.z)
G = N.orientnew('G', 'Axis', (q1, N.x + N.y))
assert G.ang_vel_in(N) == q1d * (N.x + N.y).normalize()
assert N.ang_vel_in(G) == -q1d * (N.x + N.y).normalize()
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_w_diff_dcm1():
# Ref:
# Dynamics Theory and Applications, Kane 1985
# Sec. 2.1 ANGULAR VELOCITY
A = ReferenceFrame('A')
B = ReferenceFrame('B')
c11, c12, c13 = dynamicsymbols('C11 C12 C13')
c21, c22, c23 = dynamicsymbols('C21 C22 C23')
c31, c32, c33 = dynamicsymbols('C31 C32 C33')
c11d, c12d, c13d = dynamicsymbols('C11 C12 C13', level=1)
c21d, c22d, c23d = dynamicsymbols('C21 C22 C23', level=1)
c31d, c32d, c33d = dynamicsymbols('C31 C32 C33', level=1)
DCM = Matrix([
[c11, c12, c13],
[c21, c22, c23],
[c31, c32, c33]
])
B.orient(A, 'DCM', DCM)
b1a = (B.x).express(A)
b2a = (B.y).express(A)
b3a = (B.z).express(A)
# Equation (2.1.1)
B.set_ang_vel(A, B.x*(dot((b3a).dt(A), B.y))
+ B.y*(dot((b1a).dt(A), B.z))
+ B.z*(dot((b2a).dt(A), B.x)))
# Equation (2.1.21)
expr = ( (c12*c13d + c22*c23d + c32*c33d)*B.x
+ (c13*c11d + c23*c21d + c33*c31d)*B.y
+ (c11*c12d + c21*c22d + c31*c32d)*B.z)
assert B.ang_vel_in(A) - expr == 0
def test_w_diff_dcm2():
q1, q2, q3 = dynamicsymbols('q1:4')
N = ReferenceFrame('N')
A = N.orientnew('A', 'axis', [q1, N.x])
B = A.orientnew('B', 'axis', [q2, A.y])
C = B.orientnew('C', 'axis', [q3, B.z])
DCM = C.dcm(N).T
D = N.orientnew('D', 'DCM', DCM)
# Frames D and C are the same ReferenceFrame,
# since they have equal DCM respect to frame N.
# Therefore, D and C should have same angle velocity in N.
assert D.dcm(N) == C.dcm(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)]])
assert (D.ang_vel_in(N) - C.ang_vel_in(N)).express(N).simplify() == 0
def test_orientnew_respects_parent_class():
class MyReferenceFrame(ReferenceFrame):
pass
B = MyReferenceFrame('B')
C = B.orientnew('C', 'Axis', [0, B.x])
assert isinstance(C, MyReferenceFrame)
def test_orientnew_respects_input_indices():
N = ReferenceFrame('N')
q1 = dynamicsymbols('q1')
A = N.orientnew('a', 'Axis', [q1, N.z])
#modify default indices:
minds = [x+'1' for x in N.indices]
B = N.orientnew('b', 'Axis', [q1, N.z], indices=minds)
assert N.indices == A.indices
assert B.indices == minds
def test_orientnew_respects_input_latexs():
N = ReferenceFrame('N')
q1 = dynamicsymbols('q1')
A = N.orientnew('a', 'Axis', [q1, N.z])
#build default and alternate latex_vecs:
def_latex_vecs = [(r"\mathbf{\hat{%s}_%s}" % (A.name.lower(),
A.indices[0])), (r"\mathbf{\hat{%s}_%s}" %
(A.name.lower(), A.indices[1])),
(r"\mathbf{\hat{%s}_%s}" % (A.name.lower(),
A.indices[2]))]
name = 'b'
indices = [x+'1' for x in N.indices]
new_latex_vecs = [(r"\mathbf{\hat{%s}_{%s}}" % (name.lower(),
indices[0])), (r"\mathbf{\hat{%s}_{%s}}" %
(name.lower(), indices[1])),
(r"\mathbf{\hat{%s}_{%s}}" % (name.lower(),
indices[2]))]
B = N.orientnew(name, 'Axis', [q1, N.z], latexs=new_latex_vecs)
assert A.latex_vecs == def_latex_vecs
assert B.latex_vecs == new_latex_vecs
assert B.indices != indices
def test_orientnew_respects_input_variables():
N = ReferenceFrame('N')
q1 = dynamicsymbols('q1')
A = N.orientnew('a', 'Axis', [q1, N.z])
#build non-standard variable names
name = 'b'
new_variables = ['notb_'+x+'1' for x in N.indices]
B = N.orientnew(name, 'Axis', [q1, N.z], variables=new_variables)
for j,var in enumerate(A.varlist):
assert var.name == A.name + '_' + A.indices[j]
for j,var in enumerate(B.varlist):
assert var.name == new_variables[j]
def test_issue_10348():
u = dynamicsymbols('u:3')
I = ReferenceFrame('I')
I.orientnew('A', 'space', u, 'XYZ')
def test_issue_11503():
A = ReferenceFrame("A")
A.orientnew("B", "Axis", [35, A.y])
C = ReferenceFrame("C")
A.orient(C, "Axis", [70, C.z])
def test_partial_velocity():
N = ReferenceFrame('N')
A = ReferenceFrame('A')
u1, u2 = dynamicsymbols('u1, u2')
A.set_ang_vel(N, u1 * A.x + u2 * N.y)
assert N.partial_velocity(A, u1) == -A.x
assert N.partial_velocity(A, u1, u2) == (-A.x, -N.y)
assert A.partial_velocity(N, u1) == A.x
assert A.partial_velocity(N, u1, u2) == (A.x, N.y)
assert N.partial_velocity(N, u1) == 0
assert A.partial_velocity(A, u1) == 0
def test_issue_11498():
A = ReferenceFrame('A')
B = ReferenceFrame('B')
# Identity transformation
A.orient(B, 'DCM', eye(3))
assert A.dcm(B) == Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
assert B.dcm(A) == Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
# x -> y
# y -> -z
# z -> -x
A.orient(B, 'DCM', Matrix([[0, 1, 0], [0, 0, -1], [-1, 0, 0]]))
assert B.dcm(A) == Matrix([[0, 1, 0], [0, 0, -1], [-1, 0, 0]])
assert A.dcm(B) == Matrix([[0, 0, -1], [1, 0, 0], [0, -1, 0]])
assert B.dcm(A).T == A.dcm(B)
def test_reference_frame():
raises(TypeError, lambda: ReferenceFrame(0))
raises(TypeError, lambda: ReferenceFrame('N', 0))
raises(ValueError, lambda: ReferenceFrame('N', [0, 1]))
raises(TypeError, lambda: ReferenceFrame('N', [0, 1, 2]))
raises(TypeError, lambda: ReferenceFrame('N', ['a', 'b', 'c'], 0))
raises(ValueError, lambda: ReferenceFrame('N', ['a', 'b', 'c'], [0, 1]))
raises(TypeError, lambda: ReferenceFrame('N', ['a', 'b', 'c'], [0, 1, 2]))
raises(TypeError, lambda: ReferenceFrame('N', ['a', 'b', 'c'],
['a', 'b', 'c'], 0))
raises(ValueError, lambda: ReferenceFrame('N', ['a', 'b', 'c'],
['a', 'b', 'c'], [0, 1]))
raises(TypeError, lambda: ReferenceFrame('N', ['a', 'b', 'c'],
['a', 'b', 'c'], [0, 1, 2]))
N = ReferenceFrame('N')
assert N[0] == CoordinateSym('N_x', N, 0)
assert N[1] == CoordinateSym('N_y', N, 1)
assert N[2] == CoordinateSym('N_z', N, 2)
raises(ValueError, lambda: N[3])
N = ReferenceFrame('N', ['a', 'b', 'c'])
assert N['a'] == N.x
assert N['b'] == N.y
assert N['c'] == N.z
raises(ValueError, lambda: N['d'])
assert str(N) == 'N'
A = ReferenceFrame('A')
B = ReferenceFrame('B')
q0, q1, q2, q3 = symbols('q0 q1 q2 q3')
raises(TypeError, lambda: A.orient(B, 'DCM', 0))
raises(TypeError, lambda: B.orient(N, 'Space', [q1, q2, q3], '222'))
raises(TypeError, lambda: B.orient(N, 'Axis', [q1, N.x + 2 * N.y], '222'))
raises(TypeError, lambda: B.orient(N, 'Axis', q1))
raises(IndexError, lambda: B.orient(N, 'Axis', [q1]))
raises(TypeError, lambda: B.orient(N, 'Quaternion', [q0, q1, q2, q3], '222'))
raises(TypeError, lambda: B.orient(N, 'Quaternion', q0))
raises(TypeError, lambda: B.orient(N, 'Quaternion', [q0, q1, q2]))
raises(NotImplementedError, lambda: B.orient(N, 'Foo', [q0, q1, q2]))
raises(TypeError, lambda: B.orient(N, 'Body', [q1, q2], '232'))
raises(TypeError, lambda: B.orient(N, 'Space', [q1, q2], '232'))
N.set_ang_acc(B, 0)
assert N.ang_acc_in(B) == Vector(0)
N.set_ang_vel(B, 0)
assert N.ang_vel_in(B) == Vector(0)
def test_check_frame():
raises(VectorTypeError, lambda: _check_frame(0))
def test_dcm_diff_16824():
# NOTE : This is a regression test for the bug introduced in PR 14758,
# identified in 16824, and solved by PR 16828.
# This is the solution to Problem 2.2 on page 264 in Kane & Lenvinson's
# 1985 book.
q1, q2, q3 = dynamicsymbols('q1:4')
s1 = sin(q1)
c1 = cos(q1)
s2 = sin(q2)
c2 = cos(q2)
s3 = sin(q3)
c3 = cos(q3)
dcm = Matrix([[c2*c3, s1*s2*c3 - s3*c1, c1*s2*c3 + s3*s1],
[c2*s3, s1*s2*s3 + c3*c1, c1*s2*s3 - c3*s1],
[-s2, s1*c2, c1*c2]])
A = ReferenceFrame('A')
B = ReferenceFrame('B')
B.orient(A, 'DCM', dcm)
AwB = B.ang_vel_in(A)
alpha2 = s3*c2*q1.diff() + c3*q2.diff()
beta2 = s1*c2*q3.diff() + c1*q2.diff()
assert simplify(AwB.dot(A.y) - alpha2) == 0
assert simplify(AwB.dot(B.y) - beta2) == 0
def test_orient_explicit():
A = ReferenceFrame('A')
B = ReferenceFrame('B')
A.orient_explicit(B, eye(3))
assert A.dcm(B) == Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
def test_orient_axis():
A = ReferenceFrame('A')
B = ReferenceFrame('B')
A.orient_axis(B,-B.x, 1)
A1 = A.dcm(B)
A.orient_axis(B, B.x, -1)
A2 = A.dcm(B)
A.orient_axis(B, 1, -B.x)
A3 = A.dcm(B)
assert A1 == A2
assert A2 == A3
raises(TypeError, lambda: A.orient_axis(B, 1, 1))
def test_orient_body():
A = ReferenceFrame('A')
B = ReferenceFrame('B')
B.orient_body_fixed(A, (1,1,0), 'XYX')
assert B.dcm(A) == Matrix([[cos(1), sin(1)**2, -sin(1)*cos(1)], [0, cos(1), sin(1)], [sin(1), -sin(1)*cos(1), cos(1)**2]])
def test_orient_space():
A = ReferenceFrame('A')
B = ReferenceFrame('B')
B.orient_space_fixed(A, (0,0,0), '123')
assert B.dcm(A) == Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
def test_orient_quaternion():
A = ReferenceFrame('A')
B = ReferenceFrame('B')
B.orient_quaternion(A, (0,0,0,0))
assert B.dcm(A) == Matrix([[0, 0, 0], [0, 0, 0], [0, 0, 0]])
def test_looped_frame_warning():
A = ReferenceFrame('A')
B = ReferenceFrame('B')
C = ReferenceFrame('C')
a, b, c = symbols('a b c')
B.orient_axis(A, A.x, a)
C.orient_axis(B, B.x, b)
with warnings.catch_warnings(record = True) as w:
warnings.simplefilter("always")
A.orient_axis(C, C.x, c)
assert issubclass(w[-1].category, UserWarning)
assert 'Loops are defined among the orientation of frames. ' + \
'This is likely not desired and may cause errors in your calculations.' in str(w[-1].message)
def test_frame_dict():
A = ReferenceFrame('A')
B = ReferenceFrame('B')
C = ReferenceFrame('C')
a, b, c = symbols('a b c')
B.orient_axis(A, A.x, a)
assert A._dcm_dict == {B: Matrix([[1, 0, 0],[0, cos(a), -sin(a)],[0, sin(a), cos(a)]])}
assert B._dcm_dict == {A: Matrix([[1, 0, 0],[0, cos(a), sin(a)],[0, -sin(a), cos(a)]])}
assert C._dcm_dict == {}
B.orient_axis(C, C.x, b)
# Previous relation is not wiped
assert A._dcm_dict == {B: Matrix([[1, 0, 0],[0, cos(a), -sin(a)],[0, sin(a), cos(a)]])}
assert B._dcm_dict == {A: Matrix([[1, 0, 0],[0, cos(a), sin(a)],[0, -sin(a), cos(a)]]), \
C: Matrix([[1, 0, 0],[0, cos(b), sin(b)],[0, -sin(b), cos(b)]])}
assert C._dcm_dict == {B: Matrix([[1, 0, 0],[0, cos(b), -sin(b)],[0, sin(b), cos(b)]])}
A.orient_axis(B, B.x, c)
# Previous relation is updated
assert B._dcm_dict == {C: Matrix([[1, 0, 0],[0, cos(b), sin(b)],[0, -sin(b), cos(b)]]),\
A: Matrix([[1, 0, 0],[0, cos(c), -sin(c)],[0, sin(c), cos(c)]])}
assert A._dcm_dict == {B: Matrix([[1, 0, 0],[0, cos(c), sin(c)],[0, -sin(c), cos(c)]])}
assert C._dcm_dict == {B: Matrix([[1, 0, 0],[0, cos(b), -sin(b)],[0, sin(b), cos(b)]])}
def test_dcm_cache_dict():
A = ReferenceFrame('A')
B = ReferenceFrame('B')
C = ReferenceFrame('C')
D = ReferenceFrame('D')
a, b, c = symbols('a b c')
B.orient_axis(A, A.x, a)
C.orient_axis(B, B.x, b)
D.orient_axis(C, C.x, c)
assert D._dcm_dict == {C: Matrix([[1, 0, 0],[0, cos(c), sin(c)],[0, -sin(c), cos(c)]])}
assert C._dcm_dict == {B: Matrix([[1, 0, 0],[0, cos(b), sin(b)],[0, -sin(b), cos(b)]]), \
D: Matrix([[1, 0, 0],[0, cos(c), -sin(c)],[0, sin(c), cos(c)]])}
assert B._dcm_dict == {A: Matrix([[1, 0, 0],[0, cos(a), sin(a)],[0, -sin(a), cos(a)]]), \
C: Matrix([[1, 0, 0],[0, cos(b), -sin(b)],[0, sin(b), cos(b)]])}
assert A._dcm_dict == {B: Matrix([[1, 0, 0],[0, cos(a), -sin(a)],[0, sin(a), cos(a)]])}
assert D._dcm_dict == D._dcm_cache
D.dcm(A) # Check calculated dcm relation is stored in _dcm_cache and not in _dcm_dict
assert list(A._dcm_cache.keys()) == [A, B, D]
assert list(D._dcm_cache.keys()) == [C, A]
assert list(A._dcm_dict.keys()) == [B]
assert list(D._dcm_dict.keys()) == [C]
assert A._dcm_dict != A._dcm_cache
A.orient_axis(B, B.x, b) # _dcm_cache of A is wiped out and new relation is stored.
assert A._dcm_dict == {B: Matrix([[1, 0, 0],[0, cos(b), sin(b)],[0, -sin(b), cos(b)]])}
assert A._dcm_dict == A._dcm_cache
assert B._dcm_dict == {C: Matrix([[1, 0, 0],[0, cos(b), -sin(b)],[0, sin(b), cos(b)]]), \
A: Matrix([[1, 0, 0],[0, cos(b), -sin(b)],[0, sin(b), cos(b)]])}
|
1548e1d7c43307a75749abbd887bad6f7ea8dbc7da49aed3f6c07489ca636be3 | from sympy.core.singleton import S
from sympy.core.symbol import Symbol
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.physics.vector import ReferenceFrame, Vector, Point, \
dynamicsymbols
from sympy.physics.vector.fieldfunctions import divergence, \
gradient, curl, is_conservative, is_solenoidal, \
scalar_potential, scalar_potential_difference
from sympy.testing.pytest import raises
R = ReferenceFrame('R')
q = dynamicsymbols('q')
P = R.orientnew('P', 'Axis', [q, R.z])
def test_curl():
assert curl(Vector(0), R) == Vector(0)
assert curl(R.x, R) == Vector(0)
assert curl(2*R[1]**2*R.y, R) == Vector(0)
assert curl(R[0]*R[1]*R.z, R) == R[0]*R.x - R[1]*R.y
assert curl(R[0]*R[1]*R[2] * (R.x+R.y+R.z), R) == \
(-R[0]*R[1] + R[0]*R[2])*R.x + (R[0]*R[1] - R[1]*R[2])*R.y + \
(-R[0]*R[2] + R[1]*R[2])*R.z
assert curl(2*R[0]**2*R.y, R) == 4*R[0]*R.z
assert curl(P[0]**2*R.x + P.y, R) == \
- 2*(R[0]*cos(q) + R[1]*sin(q))*sin(q)*R.z
assert curl(P[0]*R.y, P) == cos(q)*P.z
def test_divergence():
assert divergence(Vector(0), R) is S.Zero
assert divergence(R.x, R) is S.Zero
assert divergence(R[0]**2*R.x, R) == 2*R[0]
assert divergence(R[0]*R[1]*R[2] * (R.x+R.y+R.z), R) == \
R[0]*R[1] + R[0]*R[2] + R[1]*R[2]
assert divergence((1/(R[0]*R[1]*R[2])) * (R.x+R.y+R.z), R) == \
-1/(R[0]*R[1]*R[2]**2) - 1/(R[0]*R[1]**2*R[2]) - \
1/(R[0]**2*R[1]*R[2])
v = P[0]*P.x + P[1]*P.y + P[2]*P.z
assert divergence(v, P) == 3
assert divergence(v, R).simplify() == 3
assert divergence(P[0]*R.x + R[0]*P.x, R) == 2*cos(q)
def test_gradient():
a = Symbol('a')
assert gradient(0, R) == Vector(0)
assert gradient(R[0], R) == R.x
assert gradient(R[0]*R[1]*R[2], R) == \
R[1]*R[2]*R.x + R[0]*R[2]*R.y + R[0]*R[1]*R.z
assert gradient(2*R[0]**2, R) == 4*R[0]*R.x
assert gradient(a*sin(R[1])/R[0], R) == \
- a*sin(R[1])/R[0]**2*R.x + a*cos(R[1])/R[0]*R.y
assert gradient(P[0]*P[1], R) == \
((-R[0]*sin(q) + R[1]*cos(q))*cos(q) - (R[0]*cos(q) + R[1]*sin(q))*sin(q))*R.x + \
((-R[0]*sin(q) + R[1]*cos(q))*sin(q) + (R[0]*cos(q) + R[1]*sin(q))*cos(q))*R.y
assert gradient(P[0]*R[2], P) == P[2]*P.x + P[0]*P.z
scalar_field = 2*R[0]**2*R[1]*R[2]
grad_field = gradient(scalar_field, R)
vector_field = R[1]**2*R.x + 3*R[0]*R.y + 5*R[1]*R[2]*R.z
curl_field = curl(vector_field, R)
def test_conservative():
assert is_conservative(0) is True
assert is_conservative(R.x) is True
assert is_conservative(2 * R.x + 3 * R.y + 4 * R.z) is True
assert is_conservative(R[1]*R[2]*R.x + R[0]*R[2]*R.y + R[0]*R[1]*R.z) is \
True
assert is_conservative(R[0] * R.y) is False
assert is_conservative(grad_field) is True
assert is_conservative(curl_field) is False
assert is_conservative(4*R[0]*R[1]*R[2]*R.x + 2*R[0]**2*R[2]*R.y) is \
False
assert is_conservative(R[2]*P.x + P[0]*R.z) is True
def test_solenoidal():
assert is_solenoidal(0) is True
assert is_solenoidal(R.x) is True
assert is_solenoidal(2 * R.x + 3 * R.y + 4 * R.z) is True
assert is_solenoidal(R[1]*R[2]*R.x + R[0]*R[2]*R.y + R[0]*R[1]*R.z) is \
True
assert is_solenoidal(R[1] * R.y) is False
assert is_solenoidal(grad_field) is False
assert is_solenoidal(curl_field) is True
assert is_solenoidal((-2*R[1] + 3)*R.z) is True
assert is_solenoidal(cos(q)*R.x + sin(q)*R.y + cos(q)*P.z) is True
assert is_solenoidal(R[2]*P.x + P[0]*R.z) is True
def test_scalar_potential():
assert scalar_potential(0, R) == 0
assert scalar_potential(R.x, R) == R[0]
assert scalar_potential(R.y, R) == R[1]
assert scalar_potential(R.z, R) == R[2]
assert scalar_potential(R[1]*R[2]*R.x + R[0]*R[2]*R.y + \
R[0]*R[1]*R.z, R) == R[0]*R[1]*R[2]
assert scalar_potential(grad_field, R) == scalar_field
assert scalar_potential(R[2]*P.x + P[0]*R.z, R) == \
R[0]*R[2]*cos(q) + R[1]*R[2]*sin(q)
assert scalar_potential(R[2]*P.x + P[0]*R.z, P) == P[0]*P[2]
raises(ValueError, lambda: scalar_potential(R[0] * R.y, R))
def test_scalar_potential_difference():
origin = Point('O')
point1 = origin.locatenew('P1', 1*R.x + 2*R.y + 3*R.z)
point2 = origin.locatenew('P2', 4*R.x + 5*R.y + 6*R.z)
genericpointR = origin.locatenew('RP', R[0]*R.x + R[1]*R.y + R[2]*R.z)
genericpointP = origin.locatenew('PP', P[0]*P.x + P[1]*P.y + P[2]*P.z)
assert scalar_potential_difference(S.Zero, R, point1, point2, \
origin) == 0
assert scalar_potential_difference(scalar_field, R, origin, \
genericpointR, origin) == \
scalar_field
assert scalar_potential_difference(grad_field, R, origin, \
genericpointR, origin) == \
scalar_field
assert scalar_potential_difference(grad_field, R, point1, point2,
origin) == 948
assert scalar_potential_difference(R[1]*R[2]*R.x + R[0]*R[2]*R.y + \
R[0]*R[1]*R.z, R, point1,
genericpointR, origin) == \
R[0]*R[1]*R[2] - 6
potential_diff_P = 2*P[2]*(P[0]*sin(q) + P[1]*cos(q))*\
(P[0]*cos(q) - P[1]*sin(q))**2
assert scalar_potential_difference(grad_field, P, origin, \
genericpointP, \
origin).simplify() == \
potential_diff_P
|
d3d54a3ffb926a2267cb92f136591233053f2dd42167ac86aa80f5186e1d7365 | from sympy.core.numbers import (Float, pi)
from sympy.core.symbol import symbols
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.matrices.immutable import ImmutableDenseMatrix as Matrix
from sympy.physics.vector import ReferenceFrame, Vector, dynamicsymbols, outer
from sympy.physics.vector.dyadic import _check_dyadic
from sympy.testing.pytest import raises
Vector.simp = True
A = ReferenceFrame('A')
def test_dyadic():
d1 = A.x | A.x
d2 = A.y | A.y
d3 = A.x | A.y
assert d1 * 0 == 0
assert d1 != 0
assert d1 * 2 == 2 * A.x | A.x
assert d1 / 2. == 0.5 * d1
assert d1 & (0 * d1) == 0
assert d1 & d2 == 0
assert d1 & A.x == A.x
assert d1 ^ A.x == 0
assert d1 ^ A.y == A.x | A.z
assert d1 ^ A.z == - A.x | A.y
assert d2 ^ A.x == - A.y | A.z
assert A.x ^ d1 == 0
assert A.y ^ d1 == - A.z | A.x
assert A.z ^ d1 == A.y | A.x
assert A.x & d1 == A.x
assert A.y & d1 == 0
assert A.y & d2 == A.y
assert d1 & d3 == A.x | A.y
assert d3 & d1 == 0
assert d1.dt(A) == 0
q = dynamicsymbols('q')
qd = dynamicsymbols('q', 1)
B = A.orientnew('B', 'Axis', [q, A.z])
assert d1.express(B) == d1.express(B, B)
assert d1.express(B) == ((cos(q)**2) * (B.x | B.x) + (-sin(q) * cos(q)) *
(B.x | B.y) + (-sin(q) * cos(q)) * (B.y | B.x) + (sin(q)**2) *
(B.y | B.y))
assert d1.express(B, A) == (cos(q)) * (B.x | A.x) + (-sin(q)) * (B.y | A.x)
assert d1.express(A, B) == (cos(q)) * (A.x | B.x) + (-sin(q)) * (A.x | B.y)
assert d1.dt(B) == (-qd) * (A.y | A.x) + (-qd) * (A.x | A.y)
assert d1.to_matrix(A) == Matrix([[1, 0, 0], [0, 0, 0], [0, 0, 0]])
assert d1.to_matrix(A, B) == Matrix([[cos(q), -sin(q), 0],
[0, 0, 0],
[0, 0, 0]])
assert d3.to_matrix(A) == Matrix([[0, 1, 0], [0, 0, 0], [0, 0, 0]])
a, b, c, d, e, f = symbols('a, b, c, d, e, f')
v1 = a * A.x + b * A.y + c * A.z
v2 = d * A.x + e * A.y + f * A.z
d4 = v1.outer(v2)
assert d4.to_matrix(A) == Matrix([[a * d, a * e, a * f],
[b * d, b * e, b * f],
[c * d, c * e, c * f]])
d5 = v1.outer(v1)
C = A.orientnew('C', 'Axis', [q, A.x])
for expected, actual in zip(C.dcm(A) * d5.to_matrix(A) * C.dcm(A).T,
d5.to_matrix(C)):
assert (expected - actual).simplify() == 0
raises(TypeError, lambda: d1.applyfunc(0))
def test_dyadic_simplify():
x, y, z, k, n, m, w, f, s, A = symbols('x, y, z, k, n, m, w, f, s, A')
N = ReferenceFrame('N')
dy = N.x | N.x
test1 = (1 / x + 1 / y) * dy
assert (N.x & test1 & N.x) != (x + y) / (x * y)
test1 = test1.simplify()
assert (N.x & test1 & N.x) == (x + y) / (x * y)
test2 = (A**2 * s**4 / (4 * pi * k * m**3)) * dy
test2 = test2.simplify()
assert (N.x & test2 & N.x) == (A**2 * s**4 / (4 * pi * k * m**3))
test3 = ((4 + 4 * x - 2 * (2 + 2 * x)) / (2 + 2 * x)) * dy
test3 = test3.simplify()
assert (N.x & test3 & N.x) == 0
test4 = ((-4 * x * y**2 - 2 * y**3 - 2 * x**2 * y) / (x + y)**2) * dy
test4 = test4.simplify()
assert (N.x & test4 & N.x) == -2 * y
def test_dyadic_subs():
N = ReferenceFrame('N')
s = symbols('s')
a = s*(N.x | N.x)
assert a.subs({s: 2}) == 2*(N.x | N.x)
def test_check_dyadic():
raises(TypeError, lambda: _check_dyadic(0))
def test_dyadic_evalf():
N = ReferenceFrame('N')
a = pi * (N.x | N.x)
assert a.evalf(3) == Float('3.1416', 3) * (N.x | N.x)
s = symbols('s')
a = 5 * s * pi* (N.x | N.x)
assert a.evalf(2) == Float('5', 2) * Float('3.1416', 2) * s * (N.x | N.x)
assert a.evalf(9, subs={s: 5.124}) == Float('80.48760378', 9) * (N.x | N.x)
def test_dyadic_xreplace():
x, y, z = symbols('x y z')
N = ReferenceFrame('N')
D = outer(N.x, N.x)
v = x*y * D
assert v.xreplace({x : cos(x)}) == cos(x)*y * D
assert v.xreplace({x*y : pi}) == pi * D
v = (x*y)**z * D
assert v.xreplace({(x*y)**z : 1}) == D
assert v.xreplace({x:1, z:0}) == D
raises(TypeError, lambda: v.xreplace())
raises(TypeError, lambda: v.xreplace([x, y]))
|
4c5aaca366146f9cf0e285fa1f6d3a5aed174f025914a3d8f7681debc92d30de | from sympy.core.singleton import S
from sympy.physics.vector import Vector, ReferenceFrame, Dyadic
from sympy.testing.pytest import raises
Vector.simp = True
A = ReferenceFrame('A')
def test_output_type():
A = ReferenceFrame('A')
v = A.x + A.y
d = v | v
zerov = Vector(0)
zerod = Dyadic(0)
# dot products
assert isinstance(d & d, Dyadic)
assert isinstance(d & zerod, Dyadic)
assert isinstance(zerod & d, Dyadic)
assert isinstance(d & v, Vector)
assert isinstance(v & d, Vector)
assert isinstance(d & zerov, Vector)
assert isinstance(zerov & d, Vector)
raises(TypeError, lambda: d & S.Zero)
raises(TypeError, lambda: S.Zero & d)
raises(TypeError, lambda: d & 0)
raises(TypeError, lambda: 0 & d)
assert not isinstance(v & v, (Vector, Dyadic))
assert not isinstance(v & zerov, (Vector, Dyadic))
assert not isinstance(zerov & v, (Vector, Dyadic))
raises(TypeError, lambda: v & S.Zero)
raises(TypeError, lambda: S.Zero & v)
raises(TypeError, lambda: v & 0)
raises(TypeError, lambda: 0 & v)
# cross products
raises(TypeError, lambda: d ^ d)
raises(TypeError, lambda: d ^ zerod)
raises(TypeError, lambda: zerod ^ d)
assert isinstance(d ^ v, Dyadic)
assert isinstance(v ^ d, Dyadic)
assert isinstance(d ^ zerov, Dyadic)
assert isinstance(zerov ^ d, Dyadic)
assert isinstance(zerov ^ d, Dyadic)
raises(TypeError, lambda: d ^ S.Zero)
raises(TypeError, lambda: S.Zero ^ d)
raises(TypeError, lambda: d ^ 0)
raises(TypeError, lambda: 0 ^ d)
assert isinstance(v ^ v, Vector)
assert isinstance(v ^ zerov, Vector)
assert isinstance(zerov ^ v, Vector)
raises(TypeError, lambda: v ^ S.Zero)
raises(TypeError, lambda: S.Zero ^ v)
raises(TypeError, lambda: v ^ 0)
raises(TypeError, lambda: 0 ^ v)
# outer products
raises(TypeError, lambda: d | d)
raises(TypeError, lambda: d | zerod)
raises(TypeError, lambda: zerod | d)
raises(TypeError, lambda: d | v)
raises(TypeError, lambda: v | d)
raises(TypeError, lambda: d | zerov)
raises(TypeError, lambda: zerov | d)
raises(TypeError, lambda: zerov | d)
raises(TypeError, lambda: d | S.Zero)
raises(TypeError, lambda: S.Zero | d)
raises(TypeError, lambda: d | 0)
raises(TypeError, lambda: 0 | d)
assert isinstance(v | v, Dyadic)
assert isinstance(v | zerov, Dyadic)
assert isinstance(zerov | v, Dyadic)
raises(TypeError, lambda: v | S.Zero)
raises(TypeError, lambda: S.Zero | v)
raises(TypeError, lambda: v | 0)
raises(TypeError, lambda: 0 | v)
|
929b625f7c72ff13d2ca0f1fe316768c99e8af29cfbdf4de9ce06d9edb185da6 | # -*- coding: utf-8 -*-
from sympy.core.function import Function
from sympy.core.symbol import symbols
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import (asin, cos, sin)
from sympy.physics.vector import ReferenceFrame, dynamicsymbols, Dyadic
from sympy.physics.vector.printing import (VectorLatexPrinter, vpprint,
vsprint, vsstrrepr, vlatex)
a, b, c = symbols('a, b, c')
alpha, omega, beta = dynamicsymbols('alpha, omega, beta')
A = ReferenceFrame('A')
N = ReferenceFrame('N')
v = a ** 2 * N.x + b * N.y + c * sin(alpha) * N.z
w = alpha * N.x + sin(omega) * N.y + alpha * beta * N.z
ww = alpha * N.x + asin(omega) * N.y - alpha.diff() * beta * N.z
o = a/b * N.x + (c+b)/a * N.y + c**2/b * N.z
y = a ** 2 * (N.x | N.y) + b * (N.y | N.y) + c * sin(alpha) * (N.z | N.y)
x = alpha * (N.x | N.x) + sin(omega) * (N.y | N.z) + alpha * beta * (N.z | N.x)
xx = N.x | (-N.y - N.z)
xx2 = N.x | (N.y + N.z)
def ascii_vpretty(expr):
return vpprint(expr, use_unicode=False, wrap_line=False)
def unicode_vpretty(expr):
return vpprint(expr, use_unicode=True, wrap_line=False)
def test_latex_printer():
r = Function('r')('t')
assert VectorLatexPrinter().doprint(r ** 2) == "r^{2}"
r2 = Function('r^2')('t')
assert VectorLatexPrinter().doprint(r2.diff()) == r'\dot{r^{2}}'
ra = Function('r__a')('t')
assert VectorLatexPrinter().doprint(ra.diff().diff()) == r'\ddot{r^{a}}'
def test_vector_pretty_print():
# TODO : The unit vectors should print with subscripts but they just
# print as `n_x` instead of making `x` a subscript with unicode.
# TODO : The pretty print division does not print correctly here:
# w = alpha * N.x + sin(omega) * N.y + alpha / beta * N.z
expected = """\
2
a n_x + b n_y + c*sin(alpha) n_z\
"""
uexpected = """\
2
a n_x + b n_y + c⋅sin(α) n_z\
"""
assert ascii_vpretty(v) == expected
assert unicode_vpretty(v) == uexpected
expected = 'alpha n_x + sin(omega) n_y + alpha*beta n_z'
uexpected = 'α n_x + sin(ω) n_y + α⋅β n_z'
assert ascii_vpretty(w) == expected
assert unicode_vpretty(w) == uexpected
expected = """\
2
a b + c c
- n_x + ----- n_y + -- n_z
b a b\
"""
uexpected = """\
2
a b + c c
─ n_x + ───── n_y + ── n_z
b a b\
"""
assert ascii_vpretty(o) == expected
assert unicode_vpretty(o) == uexpected
def test_vector_latex():
a, b, c, d, omega = symbols('a, b, c, d, omega')
v = (a ** 2 + b / c) * A.x + sqrt(d) * A.y + cos(omega) * A.z
assert vlatex(v) == (r'(a^{2} + \frac{b}{c})\mathbf{\hat{a}_x} + '
r'\sqrt{d}\mathbf{\hat{a}_y} + '
r'\cos{\left(\omega \right)}'
r'\mathbf{\hat{a}_z}')
theta, omega, alpha, q = dynamicsymbols('theta, omega, alpha, q')
v = theta * A.x + omega * omega * A.y + (q * alpha) * A.z
assert vlatex(v) == (r'\theta\mathbf{\hat{a}_x} + '
r'\omega^{2}\mathbf{\hat{a}_y} + '
r'\alpha q\mathbf{\hat{a}_z}')
phi1, phi2, phi3 = dynamicsymbols('phi1, phi2, phi3')
theta1, theta2, theta3 = symbols('theta1, theta2, theta3')
v = (sin(theta1) * A.x +
cos(phi1) * cos(phi2) * A.y +
cos(theta1 + phi3) * A.z)
assert vlatex(v) == (r'\sin{\left(\theta_{1} \right)}'
r'\mathbf{\hat{a}_x} + \cos{'
r'\left(\phi_{1} \right)} \cos{'
r'\left(\phi_{2} \right)}\mathbf{\hat{a}_y} + '
r'\cos{\left(\theta_{1} + '
r'\phi_{3} \right)}\mathbf{\hat{a}_z}')
N = ReferenceFrame('N')
a, b, c, d, omega = symbols('a, b, c, d, omega')
v = (a ** 2 + b / c) * N.x + sqrt(d) * N.y + cos(omega) * N.z
expected = (r'(a^{2} + \frac{b}{c})\mathbf{\hat{n}_x} + '
r'\sqrt{d}\mathbf{\hat{n}_y} + '
r'\cos{\left(\omega \right)}'
r'\mathbf{\hat{n}_z}')
assert vlatex(v) == expected
# Try custom unit vectors.
N = ReferenceFrame('N', latexs=(r'\hat{i}', r'\hat{j}', r'\hat{k}'))
v = (a ** 2 + b / c) * N.x + sqrt(d) * N.y + cos(omega) * N.z
expected = (r'(a^{2} + \frac{b}{c})\hat{i} + '
r'\sqrt{d}\hat{j} + '
r'\cos{\left(\omega \right)}\hat{k}')
assert vlatex(v) == expected
expected = r'\alpha\mathbf{\hat{n}_x} + \operatorname{asin}{\left(\omega ' \
r'\right)}\mathbf{\hat{n}_y} - \beta \dot{\alpha}\mathbf{\hat{n}_z}'
assert vlatex(ww) == expected
expected = r'- \mathbf{\hat{n}_x}\otimes \mathbf{\hat{n}_y} - ' \
r'\mathbf{\hat{n}_x}\otimes \mathbf{\hat{n}_z}'
assert vlatex(xx) == expected
expected = r'\mathbf{\hat{n}_x}\otimes \mathbf{\hat{n}_y} + ' \
r'\mathbf{\hat{n}_x}\otimes \mathbf{\hat{n}_z}'
assert vlatex(xx2) == expected
def test_vector_latex_arguments():
assert vlatex(N.x * 3.0, full_prec=False) == r'3.0\mathbf{\hat{n}_x}'
assert vlatex(N.x * 3.0, full_prec=True) == r'3.00000000000000\mathbf{\hat{n}_x}'
def test_vector_latex_with_functions():
N = ReferenceFrame('N')
omega, alpha = dynamicsymbols('omega, alpha')
v = omega.diff() * N.x
assert vlatex(v) == r'\dot{\omega}\mathbf{\hat{n}_x}'
v = omega.diff() ** alpha * N.x
assert vlatex(v) == (r'\dot{\omega}^{\alpha}'
r'\mathbf{\hat{n}_x}')
def test_dyadic_pretty_print():
expected = """\
2
a n_x|n_y + b n_y|n_y + c*sin(alpha) n_z|n_y\
"""
uexpected = """\
2
a n_x⊗n_y + b n_y⊗n_y + c⋅sin(α) n_z⊗n_y\
"""
assert ascii_vpretty(y) == expected
assert unicode_vpretty(y) == uexpected
expected = 'alpha n_x|n_x + sin(omega) n_y|n_z + alpha*beta n_z|n_x'
uexpected = 'α n_x⊗n_x + sin(ω) n_y⊗n_z + α⋅β n_z⊗n_x'
assert ascii_vpretty(x) == expected
assert unicode_vpretty(x) == uexpected
assert ascii_vpretty(Dyadic([])) == '0'
assert unicode_vpretty(Dyadic([])) == '0'
assert ascii_vpretty(xx) == '- n_x|n_y - n_x|n_z'
assert unicode_vpretty(xx) == '- n_x⊗n_y - n_x⊗n_z'
assert ascii_vpretty(xx2) == 'n_x|n_y + n_x|n_z'
assert unicode_vpretty(xx2) == 'n_x⊗n_y + n_x⊗n_z'
def test_dyadic_latex():
expected = (r'a^{2}\mathbf{\hat{n}_x}\otimes \mathbf{\hat{n}_y} + '
r'b\mathbf{\hat{n}_y}\otimes \mathbf{\hat{n}_y} + '
r'c \sin{\left(\alpha \right)}'
r'\mathbf{\hat{n}_z}\otimes \mathbf{\hat{n}_y}')
assert vlatex(y) == expected
expected = (r'\alpha\mathbf{\hat{n}_x}\otimes \mathbf{\hat{n}_x} + '
r'\sin{\left(\omega \right)}\mathbf{\hat{n}_y}'
r'\otimes \mathbf{\hat{n}_z} + '
r'\alpha \beta\mathbf{\hat{n}_z}\otimes \mathbf{\hat{n}_x}')
assert vlatex(x) == expected
assert vlatex(Dyadic([])) == '0'
def test_dyadic_str():
assert vsprint(Dyadic([])) == '0'
assert vsprint(y) == 'a**2*(N.x|N.y) + b*(N.y|N.y) + c*sin(alpha)*(N.z|N.y)'
assert vsprint(x) == 'alpha*(N.x|N.x) + sin(omega)*(N.y|N.z) + alpha*beta*(N.z|N.x)'
assert vsprint(ww) == "alpha*N.x + asin(omega)*N.y - beta*alpha'*N.z"
assert vsprint(xx) == '- (N.x|N.y) - (N.x|N.z)'
assert vsprint(xx2) == '(N.x|N.y) + (N.x|N.z)'
def test_vlatex(): # vlatex is broken #12078
from sympy.physics.vector import vlatex
x = symbols('x')
J = symbols('J')
f = Function('f')
g = Function('g')
h = Function('h')
expected = r'J \left(\frac{d}{d x} g{\left(x \right)} - \frac{d}{d x} h{\left(x \right)}\right)'
expr = J*f(x).diff(x).subs(f(x), g(x)-h(x))
assert vlatex(expr) == expected
def test_issue_13354():
"""
Test for proper pretty printing of physics vectors with ADD
instances in arguments.
Test is exactly the one suggested in the original bug report by
@moorepants.
"""
a, b, c = symbols('a, b, c')
A = ReferenceFrame('A')
v = a * A.x + b * A.y + c * A.z
w = b * A.x + c * A.y + a * A.z
z = w + v
expected = """(a + b) a_x + (b + c) a_y + (a + c) a_z"""
assert ascii_vpretty(z) == expected
def test_vector_derivative_printing():
# First order
v = omega.diff() * N.x
assert unicode_vpretty(v) == 'ω̇ n_x'
assert ascii_vpretty(v) == "omega'(t) n_x"
# Second order
v = omega.diff().diff() * N.x
assert vlatex(v) == r'\ddot{\omega}\mathbf{\hat{n}_x}'
assert unicode_vpretty(v) == 'ω̈ n_x'
assert ascii_vpretty(v) == "omega''(t) n_x"
# Third order
v = omega.diff().diff().diff() * N.x
assert vlatex(v) == r'\dddot{\omega}\mathbf{\hat{n}_x}'
assert unicode_vpretty(v) == 'ω⃛ n_x'
assert ascii_vpretty(v) == "omega'''(t) n_x"
# Fourth order
v = omega.diff().diff().diff().diff() * N.x
assert vlatex(v) == r'\ddddot{\omega}\mathbf{\hat{n}_x}'
assert unicode_vpretty(v) == 'ω⃜ n_x'
assert ascii_vpretty(v) == "omega''''(t) n_x"
# Fifth order
v = omega.diff().diff().diff().diff().diff() * N.x
assert vlatex(v) == r'\frac{d^{5}}{d t^{5}} \omega\mathbf{\hat{n}_x}'
assert unicode_vpretty(v) == ' 5\n d\n───(ω) n_x\n 5\ndt'
assert ascii_vpretty(v) == ' 5\n d\n---(omega) n_x\n 5\ndt'
def test_vector_str_printing():
assert vsprint(w) == 'alpha*N.x + sin(omega)*N.y + alpha*beta*N.z'
assert vsprint(omega.diff() * N.x) == "omega'*N.x"
assert vsstrrepr(w) == 'alpha*N.x + sin(omega)*N.y + alpha*beta*N.z'
def test_vector_str_arguments():
assert vsprint(N.x * 3.0, full_prec=False) == '3.0*N.x'
assert vsprint(N.x * 3.0, full_prec=True) == '3.00000000000000*N.x'
def test_issue_14041():
import sympy.physics.mechanics as me
A_frame = me.ReferenceFrame('A')
thetad, phid = me.dynamicsymbols('theta, phi', 1)
L = symbols('L')
assert vlatex(L*(phid + thetad)**2*A_frame.x) == \
r"L \left(\dot{\phi} + \dot{\theta}\right)^{2}\mathbf{\hat{a}_x}"
assert vlatex((phid + thetad)**2*A_frame.x) == \
r"\left(\dot{\phi} + \dot{\theta}\right)^{2}\mathbf{\hat{a}_x}"
assert vlatex((phid*thetad)**a*A_frame.x) == \
r"\left(\dot{\phi} \dot{\theta}\right)^{a}\mathbf{\hat{a}_x}"
|
d9168c3b967a4ba8025966ac1f316c6d8b76a479b768d3543be7c7ffb3a904ce | from sympy.core.function import expand
from sympy.core.numbers import (Rational, pi)
from sympy.core.singleton import S
from sympy.core.symbol import (Symbol, symbols)
from sympy.sets.sets import Interval
from sympy.simplify.simplify import simplify
from sympy.physics.continuum_mechanics.beam import Beam
from sympy.functions import SingularityFunction, Piecewise, meijerg, Abs, log
from sympy.testing.pytest import raises
from sympy.physics.units import meter, newton, kilo, giga, milli
from sympy.physics.continuum_mechanics.beam import Beam3D
from sympy.geometry import Circle, Polygon, Point2D, Triangle
from sympy.core.sympify import sympify
x = Symbol('x')
y = Symbol('y')
R1, R2 = symbols('R1, R2')
def test_Beam():
E = Symbol('E')
E_1 = Symbol('E_1')
I = Symbol('I')
I_1 = Symbol('I_1')
A = Symbol('A')
b = Beam(1, E, I)
assert b.length == 1
assert b.elastic_modulus == E
assert b.second_moment == I
assert b.variable == x
# Test the length setter
b.length = 4
assert b.length == 4
# Test the E setter
b.elastic_modulus = E_1
assert b.elastic_modulus == E_1
# Test the I setter
b.second_moment = I_1
assert b.second_moment is I_1
# Test the variable setter
b.variable = y
assert b.variable is y
# Test for all boundary conditions.
b.bc_deflection = [(0, 2)]
b.bc_slope = [(0, 1)]
assert b.boundary_conditions == {'deflection': [(0, 2)], 'slope': [(0, 1)]}
# Test for slope boundary condition method
b.bc_slope.extend([(4, 3), (5, 0)])
s_bcs = b.bc_slope
assert s_bcs == [(0, 1), (4, 3), (5, 0)]
# Test for deflection boundary condition method
b.bc_deflection.extend([(4, 3), (5, 0)])
d_bcs = b.bc_deflection
assert d_bcs == [(0, 2), (4, 3), (5, 0)]
# Test for updated boundary conditions
bcs_new = b.boundary_conditions
assert bcs_new == {
'deflection': [(0, 2), (4, 3), (5, 0)],
'slope': [(0, 1), (4, 3), (5, 0)]}
b1 = Beam(30, E, I)
b1.apply_load(-8, 0, -1)
b1.apply_load(R1, 10, -1)
b1.apply_load(R2, 30, -1)
b1.apply_load(120, 30, -2)
b1.bc_deflection = [(10, 0), (30, 0)]
b1.solve_for_reaction_loads(R1, R2)
# Test for finding reaction forces
p = b1.reaction_loads
q = {R1: 6, R2: 2}
assert p == q
# Test for load distribution function.
p = b1.load
q = -8*SingularityFunction(x, 0, -1) + 6*SingularityFunction(x, 10, -1) \
+ 120*SingularityFunction(x, 30, -2) + 2*SingularityFunction(x, 30, -1)
assert p == q
# Test for shear force distribution function
p = b1.shear_force()
q = 8*SingularityFunction(x, 0, 0) - 6*SingularityFunction(x, 10, 0) \
- 120*SingularityFunction(x, 30, -1) - 2*SingularityFunction(x, 30, 0)
assert p == q
# Test for shear stress distribution function
p = b1.shear_stress()
q = (8*SingularityFunction(x, 0, 0) - 6*SingularityFunction(x, 10, 0) \
- 120*SingularityFunction(x, 30, -1) \
- 2*SingularityFunction(x, 30, 0))/A
assert p==q
# Test for bending moment distribution function
p = b1.bending_moment()
q = 8*SingularityFunction(x, 0, 1) - 6*SingularityFunction(x, 10, 1) \
- 120*SingularityFunction(x, 30, 0) - 2*SingularityFunction(x, 30, 1)
assert p == q
# Test for slope distribution function
p = b1.slope()
q = -4*SingularityFunction(x, 0, 2) + 3*SingularityFunction(x, 10, 2) \
+ 120*SingularityFunction(x, 30, 1) + SingularityFunction(x, 30, 2) \
+ Rational(4000, 3)
assert p == q/(E*I)
# Test for deflection distribution function
p = b1.deflection()
q = x*Rational(4000, 3) - 4*SingularityFunction(x, 0, 3)/3 \
+ SingularityFunction(x, 10, 3) + 60*SingularityFunction(x, 30, 2) \
+ SingularityFunction(x, 30, 3)/3 - 12000
assert p == q/(E*I)
# Test using symbols
l = Symbol('l')
w0 = Symbol('w0')
w2 = Symbol('w2')
a1 = Symbol('a1')
c = Symbol('c')
c1 = Symbol('c1')
d = Symbol('d')
e = Symbol('e')
f = Symbol('f')
b2 = Beam(l, E, I)
b2.apply_load(w0, a1, 1)
b2.apply_load(w2, c1, -1)
b2.bc_deflection = [(c, d)]
b2.bc_slope = [(e, f)]
# Test for load distribution function.
p = b2.load
q = w0*SingularityFunction(x, a1, 1) + w2*SingularityFunction(x, c1, -1)
assert p == q
# Test for shear force distribution function
p = b2.shear_force()
q = -w0*SingularityFunction(x, a1, 2)/2 \
- w2*SingularityFunction(x, c1, 0)
assert p == q
# Test for shear stress distribution function
p = b2.shear_stress()
q = (-w0*SingularityFunction(x, a1, 2)/2 \
- w2*SingularityFunction(x, c1, 0))/A
assert p == q
# Test for bending moment distribution function
p = b2.bending_moment()
q = -w0*SingularityFunction(x, a1, 3)/6 - w2*SingularityFunction(x, c1, 1)
assert p == q
# Test for slope distribution function
p = b2.slope()
q = (w0*SingularityFunction(x, a1, 4)/24 + w2*SingularityFunction(x, c1, 2)/2)/(E*I) + (E*I*f - w0*SingularityFunction(e, a1, 4)/24 - w2*SingularityFunction(e, c1, 2)/2)/(E*I)
assert expand(p) == expand(q)
# Test for deflection distribution function
p = b2.deflection()
q = x*(E*I*f - w0*SingularityFunction(e, a1, 4)/24 \
- w2*SingularityFunction(e, c1, 2)/2)/(E*I) \
+ (w0*SingularityFunction(x, a1, 5)/120 \
+ w2*SingularityFunction(x, c1, 3)/6)/(E*I) \
+ (E*I*(-c*f + d) + c*w0*SingularityFunction(e, a1, 4)/24 \
+ c*w2*SingularityFunction(e, c1, 2)/2 \
- w0*SingularityFunction(c, a1, 5)/120 \
- w2*SingularityFunction(c, c1, 3)/6)/(E*I)
assert simplify(p - q) == 0
b3 = Beam(9, E, I, 2)
b3.apply_load(value=-2, start=2, order=2, end=3)
b3.bc_slope.append((0, 2))
C3 = symbols('C3')
C4 = symbols('C4')
p = b3.load
q = -2*SingularityFunction(x, 2, 2) + 2*SingularityFunction(x, 3, 0) \
+ 4*SingularityFunction(x, 3, 1) + 2*SingularityFunction(x, 3, 2)
assert p == q
p = b3.shear_force()
q = 2*SingularityFunction(x, 2, 3)/3 - 2*SingularityFunction(x, 3, 1) \
- 2*SingularityFunction(x, 3, 2) - 2*SingularityFunction(x, 3, 3)/3
assert p == q
p = b3.shear_stress()
q = SingularityFunction(x, 2, 3)/3 - 1*SingularityFunction(x, 3, 1) \
- 1*SingularityFunction(x, 3, 2) - 1*SingularityFunction(x, 3, 3)/3
assert p == q
p = b3.slope()
q = 2 - (SingularityFunction(x, 2, 5)/30 - SingularityFunction(x, 3, 3)/3 \
- SingularityFunction(x, 3, 4)/6 - SingularityFunction(x, 3, 5)/30)/(E*I)
assert p == q
p = b3.deflection()
q = 2*x - (SingularityFunction(x, 2, 6)/180 \
- SingularityFunction(x, 3, 4)/12 - SingularityFunction(x, 3, 5)/30 \
- SingularityFunction(x, 3, 6)/180)/(E*I)
assert p == q + C4
b4 = Beam(4, E, I, 3)
b4.apply_load(-3, 0, 0, end=3)
p = b4.load
q = -3*SingularityFunction(x, 0, 0) + 3*SingularityFunction(x, 3, 0)
assert p == q
p = b4.shear_force()
q = 3*SingularityFunction(x, 0, 1) \
- 3*SingularityFunction(x, 3, 1)
assert p == q
p = b4.shear_stress()
q = SingularityFunction(x, 0, 1) - SingularityFunction(x, 3, 1)
assert p == q
p = b4.slope()
q = -3*SingularityFunction(x, 0, 3)/6 + 3*SingularityFunction(x, 3, 3)/6
assert p == q/(E*I) + C3
p = b4.deflection()
q = -3*SingularityFunction(x, 0, 4)/24 + 3*SingularityFunction(x, 3, 4)/24
assert p == q/(E*I) + C3*x + C4
# can't use end with point loads
raises(ValueError, lambda: b4.apply_load(-3, 0, -1, end=3))
with raises(TypeError):
b4.variable = 1
def test_insufficient_bconditions():
# Test cases when required number of boundary conditions
# are not provided to solve the integration constants.
L = symbols('L', positive=True)
E, I, P, a3, a4 = symbols('E I P a3 a4')
b = Beam(L, E, I, base_char='a')
b.apply_load(R2, L, -1)
b.apply_load(R1, 0, -1)
b.apply_load(-P, L/2, -1)
b.solve_for_reaction_loads(R1, R2)
p = b.slope()
q = P*SingularityFunction(x, 0, 2)/4 - P*SingularityFunction(x, L/2, 2)/2 + P*SingularityFunction(x, L, 2)/4
assert p == q/(E*I) + a3
p = b.deflection()
q = P*SingularityFunction(x, 0, 3)/12 - P*SingularityFunction(x, L/2, 3)/6 + P*SingularityFunction(x, L, 3)/12
assert p == q/(E*I) + a3*x + a4
b.bc_deflection = [(0, 0)]
p = b.deflection()
q = a3*x + P*SingularityFunction(x, 0, 3)/12 - P*SingularityFunction(x, L/2, 3)/6 + P*SingularityFunction(x, L, 3)/12
assert p == q/(E*I)
b.bc_deflection = [(0, 0), (L, 0)]
p = b.deflection()
q = -L**2*P*x/16 + P*SingularityFunction(x, 0, 3)/12 - P*SingularityFunction(x, L/2, 3)/6 + P*SingularityFunction(x, L, 3)/12
assert p == q/(E*I)
def test_statically_indeterminate():
E = Symbol('E')
I = Symbol('I')
M1, M2 = symbols('M1, M2')
F = Symbol('F')
l = Symbol('l', positive=True)
b5 = Beam(l, E, I)
b5.bc_deflection = [(0, 0),(l, 0)]
b5.bc_slope = [(0, 0),(l, 0)]
b5.apply_load(R1, 0, -1)
b5.apply_load(M1, 0, -2)
b5.apply_load(R2, l, -1)
b5.apply_load(M2, l, -2)
b5.apply_load(-F, l/2, -1)
b5.solve_for_reaction_loads(R1, R2, M1, M2)
p = b5.reaction_loads
q = {R1: F/2, R2: F/2, M1: -F*l/8, M2: F*l/8}
assert p == q
def test_beam_units():
E = Symbol('E')
I = Symbol('I')
R1, R2 = symbols('R1, R2')
kN = kilo*newton
gN = giga*newton
b = Beam(8*meter, 200*gN/meter**2, 400*1000000*(milli*meter)**4)
b.apply_load(5*kN, 2*meter, -1)
b.apply_load(R1, 0*meter, -1)
b.apply_load(R2, 8*meter, -1)
b.apply_load(10*kN/meter, 4*meter, 0, end=8*meter)
b.bc_deflection = [(0*meter, 0*meter), (8*meter, 0*meter)]
b.solve_for_reaction_loads(R1, R2)
assert b.reaction_loads == {R1: -13750*newton, R2: -31250*newton}
b = Beam(3*meter, E*newton/meter**2, I*meter**4)
b.apply_load(8*kN, 1*meter, -1)
b.apply_load(R1, 0*meter, -1)
b.apply_load(R2, 3*meter, -1)
b.apply_load(12*kN*meter, 2*meter, -2)
b.bc_deflection = [(0*meter, 0*meter), (3*meter, 0*meter)]
b.solve_for_reaction_loads(R1, R2)
assert b.reaction_loads == {R1: newton*Rational(-28000, 3), R2: newton*Rational(4000, 3)}
assert b.deflection().subs(x, 1*meter) == 62000*meter/(9*E*I)
def test_variable_moment():
E = Symbol('E')
I = Symbol('I')
b = Beam(4, E, 2*(4 - x))
b.apply_load(20, 4, -1)
R, M = symbols('R, M')
b.apply_load(R, 0, -1)
b.apply_load(M, 0, -2)
b.bc_deflection = [(0, 0)]
b.bc_slope = [(0, 0)]
b.solve_for_reaction_loads(R, M)
assert b.slope().expand() == ((10*x*SingularityFunction(x, 0, 0)
- 10*(x - 4)*SingularityFunction(x, 4, 0))/E).expand()
assert b.deflection().expand() == ((5*x**2*SingularityFunction(x, 0, 0)
- 10*Piecewise((0, Abs(x)/4 < 1), (16*meijerg(((3, 1), ()), ((), (2, 0)), x/4), True))
+ 40*SingularityFunction(x, 4, 1))/E).expand()
b = Beam(4, E - x, I)
b.apply_load(20, 4, -1)
R, M = symbols('R, M')
b.apply_load(R, 0, -1)
b.apply_load(M, 0, -2)
b.bc_deflection = [(0, 0)]
b.bc_slope = [(0, 0)]
b.solve_for_reaction_loads(R, M)
assert b.slope().expand() == ((-80*(-log(-E) + log(-E + x))*SingularityFunction(x, 0, 0)
+ 80*(-log(-E + 4) + log(-E + x))*SingularityFunction(x, 4, 0) + 20*(-E*log(-E)
+ E*log(-E + x) + x)*SingularityFunction(x, 0, 0) - 20*(-E*log(-E + 4) + E*log(-E + x)
+ x - 4)*SingularityFunction(x, 4, 0))/I).expand()
def test_composite_beam():
E = Symbol('E')
I = Symbol('I')
b1 = Beam(2, E, 1.5*I)
b2 = Beam(2, E, I)
b = b1.join(b2, "fixed")
b.apply_load(-20, 0, -1)
b.apply_load(80, 0, -2)
b.apply_load(20, 4, -1)
b.bc_slope = [(0, 0)]
b.bc_deflection = [(0, 0)]
assert b.length == 4
assert b.second_moment == Piecewise((1.5*I, x <= 2), (I, x <= 4))
assert b.slope().subs(x, 4) == 120.0/(E*I)
assert b.slope().subs(x, 2) == 80.0/(E*I)
assert int(b.deflection().subs(x, 4).args[0]) == -302 # Coefficient of 1/(E*I)
l = symbols('l', positive=True)
R1, M1, R2, R3, P = symbols('R1 M1 R2 R3 P')
b1 = Beam(2*l, E, I)
b2 = Beam(2*l, E, I)
b = b1.join(b2,"hinge")
b.apply_load(M1, 0, -2)
b.apply_load(R1, 0, -1)
b.apply_load(R2, l, -1)
b.apply_load(R3, 4*l, -1)
b.apply_load(P, 3*l, -1)
b.bc_slope = [(0, 0)]
b.bc_deflection = [(0, 0), (l, 0), (4*l, 0)]
b.solve_for_reaction_loads(M1, R1, R2, R3)
assert b.reaction_loads == {R3: -P/2, R2: P*Rational(-5, 4), M1: -P*l/4, R1: P*Rational(3, 4)}
assert b.slope().subs(x, 3*l) == -7*P*l**2/(48*E*I)
assert b.deflection().subs(x, 2*l) == 7*P*l**3/(24*E*I)
assert b.deflection().subs(x, 3*l) == 5*P*l**3/(16*E*I)
# When beams having same second moment are joined.
b1 = Beam(2, 500, 10)
b2 = Beam(2, 500, 10)
b = b1.join(b2, "fixed")
b.apply_load(M1, 0, -2)
b.apply_load(R1, 0, -1)
b.apply_load(R2, 1, -1)
b.apply_load(R3, 4, -1)
b.apply_load(10, 3, -1)
b.bc_slope = [(0, 0)]
b.bc_deflection = [(0, 0), (1, 0), (4, 0)]
b.solve_for_reaction_loads(M1, R1, R2, R3)
assert b.slope() == -2*SingularityFunction(x, 0, 1)/5625 + SingularityFunction(x, 0, 2)/1875\
- 133*SingularityFunction(x, 1, 2)/135000 + SingularityFunction(x, 3, 2)/1000\
- 37*SingularityFunction(x, 4, 2)/67500
assert b.deflection() == -SingularityFunction(x, 0, 2)/5625 + SingularityFunction(x, 0, 3)/5625\
- 133*SingularityFunction(x, 1, 3)/405000 + SingularityFunction(x, 3, 3)/3000\
- 37*SingularityFunction(x, 4, 3)/202500
def test_point_cflexure():
E = Symbol('E')
I = Symbol('I')
b = Beam(10, E, I)
b.apply_load(-4, 0, -1)
b.apply_load(-46, 6, -1)
b.apply_load(10, 2, -1)
b.apply_load(20, 4, -1)
b.apply_load(3, 6, 0)
assert b.point_cflexure() == [Rational(10, 3)]
def test_remove_load():
E = Symbol('E')
I = Symbol('I')
b = Beam(4, E, I)
try:
b.remove_load(2, 1, -1)
# As no load is applied on beam, ValueError should be returned.
except ValueError:
assert True
else:
assert False
b.apply_load(-3, 0, -2)
b.apply_load(4, 2, -1)
b.apply_load(-2, 2, 2, end = 3)
b.remove_load(-2, 2, 2, end = 3)
assert b.load == -3*SingularityFunction(x, 0, -2) + 4*SingularityFunction(x, 2, -1)
assert b.applied_loads == [(-3, 0, -2, None), (4, 2, -1, None)]
try:
b.remove_load(1, 2, -1)
# As load of this magnitude was never applied at
# this position, method should return a ValueError.
except ValueError:
assert True
else:
assert False
b.remove_load(-3, 0, -2)
b.remove_load(4, 2, -1)
assert b.load == 0
assert b.applied_loads == []
def test_apply_support():
E = Symbol('E')
I = Symbol('I')
b = Beam(4, E, I)
b.apply_support(0, "cantilever")
b.apply_load(20, 4, -1)
M_0, R_0 = symbols('M_0, R_0')
b.solve_for_reaction_loads(R_0, M_0)
assert simplify(b.slope()) == simplify((80*SingularityFunction(x, 0, 1) - 10*SingularityFunction(x, 0, 2)
+ 10*SingularityFunction(x, 4, 2))/(E*I))
assert simplify(b.deflection()) == simplify((40*SingularityFunction(x, 0, 2) - 10*SingularityFunction(x, 0, 3)/3
+ 10*SingularityFunction(x, 4, 3)/3)/(E*I))
b = Beam(30, E, I)
b.apply_support(10, "pin")
b.apply_support(30, "roller")
b.apply_load(-8, 0, -1)
b.apply_load(120, 30, -2)
R_10, R_30 = symbols('R_10, R_30')
b.solve_for_reaction_loads(R_10, R_30)
assert b.slope() == (-4*SingularityFunction(x, 0, 2) + 3*SingularityFunction(x, 10, 2)
+ 120*SingularityFunction(x, 30, 1) + SingularityFunction(x, 30, 2) + Rational(4000, 3))/(E*I)
assert b.deflection() == (x*Rational(4000, 3) - 4*SingularityFunction(x, 0, 3)/3 + SingularityFunction(x, 10, 3)
+ 60*SingularityFunction(x, 30, 2) + SingularityFunction(x, 30, 3)/3 - 12000)/(E*I)
P = Symbol('P', positive=True)
L = Symbol('L', positive=True)
b = Beam(L, E, I)
b.apply_support(0, type='fixed')
b.apply_support(L, type='fixed')
b.apply_load(-P, L/2, -1)
R_0, R_L, M_0, M_L = symbols('R_0, R_L, M_0, M_L')
b.solve_for_reaction_loads(R_0, R_L, M_0, M_L)
assert b.reaction_loads == {R_0: P/2, R_L: P/2, M_0: -L*P/8, M_L: L*P/8}
def test_max_shear_force():
E = Symbol('E')
I = Symbol('I')
b = Beam(3, E, I)
R, M = symbols('R, M')
b.apply_load(R, 0, -1)
b.apply_load(M, 0, -2)
b.apply_load(2, 3, -1)
b.apply_load(4, 2, -1)
b.apply_load(2, 2, 0, end=3)
b.solve_for_reaction_loads(R, M)
assert b.max_shear_force() == (Interval(0, 2), 8)
l = symbols('l', positive=True)
P = Symbol('P')
b = Beam(l, E, I)
R1, R2 = symbols('R1, R2')
b.apply_load(R1, 0, -1)
b.apply_load(R2, l, -1)
b.apply_load(P, 0, 0, end=l)
b.solve_for_reaction_loads(R1, R2)
assert b.max_shear_force() == (0, l*Abs(P)/2)
def test_max_bmoment():
E = Symbol('E')
I = Symbol('I')
l, P = symbols('l, P', positive=True)
b = Beam(l, E, I)
R1, R2 = symbols('R1, R2')
b.apply_load(R1, 0, -1)
b.apply_load(R2, l, -1)
b.apply_load(P, l/2, -1)
b.solve_for_reaction_loads(R1, R2)
b.reaction_loads
assert b.max_bmoment() == (l/2, P*l/4)
b = Beam(l, E, I)
R1, R2 = symbols('R1, R2')
b.apply_load(R1, 0, -1)
b.apply_load(R2, l, -1)
b.apply_load(P, 0, 0, end=l)
b.solve_for_reaction_loads(R1, R2)
assert b.max_bmoment() == (l/2, P*l**2/8)
def test_max_deflection():
E, I, l, F = symbols('E, I, l, F', positive=True)
b = Beam(l, E, I)
b.bc_deflection = [(0, 0),(l, 0)]
b.bc_slope = [(0, 0),(l, 0)]
b.apply_load(F/2, 0, -1)
b.apply_load(-F*l/8, 0, -2)
b.apply_load(F/2, l, -1)
b.apply_load(F*l/8, l, -2)
b.apply_load(-F, l/2, -1)
assert b.max_deflection() == (l/2, F*l**3/(192*E*I))
def test_Beam3D():
l, E, G, I, A = symbols('l, E, G, I, A')
R1, R2, R3, R4 = symbols('R1, R2, R3, R4')
b = Beam3D(l, E, G, I, A)
m, q = symbols('m, q')
b.apply_load(q, 0, 0, dir="y")
b.apply_moment_load(m, 0, 0, dir="z")
b.bc_slope = [(0, [0, 0, 0]), (l, [0, 0, 0])]
b.bc_deflection = [(0, [0, 0, 0]), (l, [0, 0, 0])]
b.solve_slope_deflection()
assert b.polar_moment() == 2*I
assert b.shear_force() == [0, -q*x, 0]
assert b.shear_stress() == [0, -q*x/A, 0]
assert b.axial_stress() == 0
assert b.bending_moment() == [0, 0, -m*x + q*x**2/2]
expected_deflection = (x*(A*G*q*x**3/4 + A*G*x**2*(-l*(A*G*l*(l*q - 2*m) +
12*E*I*q)/(A*G*l**2 + 12*E*I)/2 - m) + 3*E*I*l*(A*G*l*(l*q - 2*m) +
12*E*I*q)/(A*G*l**2 + 12*E*I) + x*(-A*G*l**2*q/2 +
3*A*G*l**2*(A*G*l*(l*q - 2*m) + 12*E*I*q)/(A*G*l**2 + 12*E*I)/4 +
A*G*l*m*Rational(3, 2) - 3*E*I*q))/(6*A*E*G*I))
dx, dy, dz = b.deflection()
assert dx == dz == 0
assert simplify(dy - expected_deflection) == 0
b2 = Beam3D(30, E, G, I, A, x)
b2.apply_load(50, start=0, order=0, dir="y")
b2.bc_deflection = [(0, [0, 0, 0]), (30, [0, 0, 0])]
b2.apply_load(R1, start=0, order=-1, dir="y")
b2.apply_load(R2, start=30, order=-1, dir="y")
b2.solve_for_reaction_loads(R1, R2)
assert b2.reaction_loads == {R1: -750, R2: -750}
b2.solve_slope_deflection()
assert b2.slope() == [0, 0, 25*x**3/(3*E*I) - 375*x**2/(E*I) + 3750*x/(E*I)]
expected_deflection = 25*x**4/(12*E*I) - 125*x**3/(E*I) + 1875*x**2/(E*I) - \
25*x**2/(A*G) + 750*x/(A*G)
dx, dy, dz = b2.deflection()
assert dx == dz == 0
assert dy == expected_deflection
# Test for solve_for_reaction_loads
b3 = Beam3D(30, E, G, I, A, x)
b3.apply_load(8, start=0, order=0, dir="y")
b3.apply_load(9*x, start=0, order=0, dir="z")
b3.apply_load(R1, start=0, order=-1, dir="y")
b3.apply_load(R2, start=30, order=-1, dir="y")
b3.apply_load(R3, start=0, order=-1, dir="z")
b3.apply_load(R4, start=30, order=-1, dir="z")
b3.solve_for_reaction_loads(R1, R2, R3, R4)
assert b3.reaction_loads == {R1: -120, R2: -120, R3: -1350, R4: -2700}
def test_polar_moment_Beam3D():
l, E, G, A, I1, I2 = symbols('l, E, G, A, I1, I2')
I = [I1, I2]
b = Beam3D(l, E, G, I, A)
assert b.polar_moment() == I1 + I2
def test_parabolic_loads():
E, I, L = symbols('E, I, L', positive=True, real=True)
R, M, P = symbols('R, M, P', real=True)
# cantilever beam fixed at x=0 and parabolic distributed loading across
# length of beam
beam = Beam(L, E, I)
beam.bc_deflection.append((0, 0))
beam.bc_slope.append((0, 0))
beam.apply_load(R, 0, -1)
beam.apply_load(M, 0, -2)
# parabolic load
beam.apply_load(1, 0, 2)
beam.solve_for_reaction_loads(R, M)
assert beam.reaction_loads[R] == -L**3/3
# cantilever beam fixed at x=0 and parabolic distributed loading across
# first half of beam
beam = Beam(2*L, E, I)
beam.bc_deflection.append((0, 0))
beam.bc_slope.append((0, 0))
beam.apply_load(R, 0, -1)
beam.apply_load(M, 0, -2)
# parabolic load from x=0 to x=L
beam.apply_load(1, 0, 2, end=L)
beam.solve_for_reaction_loads(R, M)
# result should be the same as the prior example
assert beam.reaction_loads[R] == -L**3/3
# check constant load
beam = Beam(2*L, E, I)
beam.apply_load(P, 0, 0, end=L)
loading = beam.load.xreplace({L: 10, E: 20, I: 30, P: 40})
assert loading.xreplace({x: 5}) == 40
assert loading.xreplace({x: 15}) == 0
# check ramp load
beam = Beam(2*L, E, I)
beam.apply_load(P, 0, 1, end=L)
assert beam.load == (P*SingularityFunction(x, 0, 1) -
P*SingularityFunction(x, L, 1) -
P*L*SingularityFunction(x, L, 0))
# check higher order load: x**8 load from x=0 to x=L
beam = Beam(2*L, E, I)
beam.apply_load(P, 0, 8, end=L)
loading = beam.load.xreplace({L: 10, E: 20, I: 30, P: 40})
assert loading.xreplace({x: 5}) == 40*5**8
assert loading.xreplace({x: 15}) == 0
def test_cross_section():
I = Symbol('I')
l = Symbol('l')
E = Symbol('E')
C3, C4 = symbols('C3, C4')
a, c, g, h, r, n = symbols('a, c, g, h, r, n')
# test for second_moment and cross_section setter
b0 = Beam(l, E, I)
assert b0.second_moment == I
assert b0.cross_section == None
b0.cross_section = Circle((0, 0), 5)
assert b0.second_moment == pi*Rational(625, 4)
assert b0.cross_section == Circle((0, 0), 5)
b0.second_moment = 2*n - 6
assert b0.second_moment == 2*n-6
assert b0.cross_section == None
with raises(ValueError):
b0.second_moment = Circle((0, 0), 5)
# beam with a circular cross-section
b1 = Beam(50, E, Circle((0, 0), r))
assert b1.cross_section == Circle((0, 0), r)
assert b1.second_moment == pi*r*Abs(r)**3/4
b1.apply_load(-10, 0, -1)
b1.apply_load(R1, 5, -1)
b1.apply_load(R2, 50, -1)
b1.apply_load(90, 45, -2)
b1.solve_for_reaction_loads(R1, R2)
assert b1.load == (-10*SingularityFunction(x, 0, -1) + 82*SingularityFunction(x, 5, -1)/S(9)
+ 90*SingularityFunction(x, 45, -2) + 8*SingularityFunction(x, 50, -1)/9)
assert b1.bending_moment() == (10*SingularityFunction(x, 0, 1) - 82*SingularityFunction(x, 5, 1)/9
- 90*SingularityFunction(x, 45, 0) - 8*SingularityFunction(x, 50, 1)/9)
q = (-5*SingularityFunction(x, 0, 2) + 41*SingularityFunction(x, 5, 2)/S(9)
+ 90*SingularityFunction(x, 45, 1) + 4*SingularityFunction(x, 50, 2)/S(9))/(pi*E*r*Abs(r)**3)
assert b1.slope() == C3 + 4*q
q = (-5*SingularityFunction(x, 0, 3)/3 + 41*SingularityFunction(x, 5, 3)/27 + 45*SingularityFunction(x, 45, 2)
+ 4*SingularityFunction(x, 50, 3)/27)/(pi*E*r*Abs(r)**3)
assert b1.deflection() == C3*x + C4 + 4*q
# beam with a recatangular cross-section
b2 = Beam(20, E, Polygon((0, 0), (a, 0), (a, c), (0, c)))
assert b2.cross_section == Polygon((0, 0), (a, 0), (a, c), (0, c))
assert b2.second_moment == a*c**3/12
# beam with a triangular cross-section
b3 = Beam(15, E, Triangle((0, 0), (g, 0), (g/2, h)))
assert b3.cross_section == Triangle(Point2D(0, 0), Point2D(g, 0), Point2D(g/2, h))
assert b3.second_moment == g*h**3/36
# composite beam
b = b2.join(b3, "fixed")
b.apply_load(-30, 0, -1)
b.apply_load(65, 0, -2)
b.apply_load(40, 0, -1)
b.bc_slope = [(0, 0)]
b.bc_deflection = [(0, 0)]
assert b.second_moment == Piecewise((a*c**3/12, x <= 20), (g*h**3/36, x <= 35))
assert b.cross_section == None
assert b.length == 35
assert b.slope().subs(x, 7) == 8400/(E*a*c**3)
assert b.slope().subs(x, 25) == 52200/(E*g*h**3) + 39600/(E*a*c**3)
assert b.deflection().subs(x, 30) == -537000/(E*g*h**3) - 712000/(E*a*c**3)
def test_max_shear_force_Beam3D():
x = symbols('x')
b = Beam3D(20, 40, 21, 100, 25)
b.apply_load(15, start=0, order=0, dir="z")
b.apply_load(12*x, start=0, order=0, dir="y")
b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])]
assert b.max_shear_force() == [(0, 0), (20, 2400), (20, 300)]
def test_max_bending_moment_Beam3D():
x = symbols('x')
b = Beam3D(20, 40, 21, 100, 25)
b.apply_load(15, start=0, order=0, dir="z")
b.apply_load(12*x, start=0, order=0, dir="y")
b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])]
assert b.max_bmoment() == [(0, 0), (20, 3000), (20, 16000)]
def test_max_deflection_Beam3D():
x = symbols('x')
b = Beam3D(20, 40, 21, 100, 25)
b.apply_load(15, start=0, order=0, dir="z")
b.apply_load(12*x, start=0, order=0, dir="y")
b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])]
b.solve_slope_deflection()
c = sympify("495/14")
p = sympify("-10 + 10*sqrt(10793)/43")
q = sympify("(10 - 10*sqrt(10793)/43)**3/160 - 20/7 + (10 - 10*sqrt(10793)/43)**4/6400 + 20*sqrt(10793)/301 + 27*(10 - 10*sqrt(10793)/43)**2/560")
assert b.max_deflection() == [(0, 0), (10, c), (p, q)]
|
3de15fae5ecc0645811dd73bf7ab030d80ee8467a96addc3424ecf9b24d7567c | from sympy.core.function import (Derivative, Function)
from sympy.core.numbers import (I, pi)
from sympy.core.symbol import (Symbol, symbols)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import (atan2, cos, sin)
from sympy.simplify.simplify import simplify
from sympy.abc import epsilon, mu
from sympy.functions.elementary.exponential import exp
from sympy.physics.units import speed_of_light, m, s
from sympy.physics.optics import TWave
from sympy.testing.pytest import raises
c = speed_of_light.convert_to(m/s)
def test_twave():
A1, phi1, A2, phi2, f = symbols('A1, phi1, A2, phi2, f')
n = Symbol('n') # Refractive index
t = Symbol('t') # Time
x = Symbol('x') # Spatial variable
E = Function('E')
w1 = TWave(A1, f, phi1)
w2 = TWave(A2, f, phi2)
assert w1.amplitude == A1
assert w1.frequency == f
assert w1.phase == phi1
assert w1.wavelength == c/(f*n)
assert w1.time_period == 1/f
assert w1.angular_velocity == 2*pi*f
assert w1.wavenumber == 2*pi*f*n/c
assert w1.speed == c/n
w3 = w1 + w2
assert w3.amplitude == sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2) + A2**2)
assert w3.frequency == f
assert w3.phase == atan2(A1*sin(phi1) + A2*sin(phi2), A1*cos(phi1) + A2*cos(phi2))
assert w3.wavelength == c/(f*n)
assert w3.time_period == 1/f
assert w3.angular_velocity == 2*pi*f
assert w3.wavenumber == 2*pi*f*n/c
assert w3.speed == c/n
assert simplify(w3.rewrite(sin) - w2.rewrite(sin) - w1.rewrite(sin)) == 0
assert w3.rewrite('pde') == epsilon*mu*Derivative(E(x, t), t, t) + Derivative(E(x, t), x, x)
assert w3.rewrite(cos) == sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2)
+ A2**2)*cos(pi*f*n*x*s/(149896229*m) - 2*pi*f*t + atan2(A1*sin(phi1)
+ A2*sin(phi2), A1*cos(phi1) + A2*cos(phi2)))
assert w3.rewrite(exp) == sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2)
+ A2**2)*exp(I*(-2*pi*f*t + atan2(A1*sin(phi1) + A2*sin(phi2), A1*cos(phi1)
+ A2*cos(phi2)) + pi*s*f*n*x/(149896229*m)))
w4 = TWave(A1, None, 0, 1/f)
assert w4.frequency == f
w5 = w1 - w2
assert w5.amplitude == sqrt(A1**2 - 2*A1*A2*cos(phi1 - phi2) + A2**2)
assert w5.frequency == f
assert w5.phase == atan2(A1*sin(phi1) - A2*sin(phi2), A1*cos(phi1) - A2*cos(phi2))
assert w5.wavelength == c/(f*n)
assert w5.time_period == 1/f
assert w5.angular_velocity == 2*pi*f
assert w5.wavenumber == 2*pi*f*n/c
assert w5.speed == c/n
assert simplify(w5.rewrite(sin) - w1.rewrite(sin) + w2.rewrite(sin)) == 0
assert w5.rewrite('pde') == epsilon*mu*Derivative(E(x, t), t, t) + Derivative(E(x, t), x, x)
assert w5.rewrite(cos) == sqrt(A1**2 - 2*A1*A2*cos(phi1 - phi2)
+ A2**2)*cos(-2*pi*f*t + atan2(A1*sin(phi1) - A2*sin(phi2), A1*cos(phi1)
- A2*cos(phi2)) + pi*s*f*n*x/(149896229*m))
assert w5.rewrite(exp) == sqrt(A1**2 - 2*A1*A2*cos(phi1 - phi2)
+ A2**2)*exp(I*(-2*pi*f*t + atan2(A1*sin(phi1) - A2*sin(phi2), A1*cos(phi1)
- A2*cos(phi2)) + pi*s*f*n*x/(149896229*m)))
w6 = 2*w1
assert w6.amplitude == 2*A1
assert w6.frequency == f
assert w6.phase == phi1
w7 = -w6
assert w7.amplitude == -2*A1
assert w7.frequency == f
assert w7.phase == phi1
raises(ValueError, lambda:TWave(A1))
raises(ValueError, lambda:TWave(A1, f, phi1, t))
|
c3c04973b59eafdce69e0645a466dd33211ac0583923c3699910e0fedc8dd63c | from sympy.functions.elementary.miscellaneous import sqrt
from sympy.physics.optics import Medium
from sympy.abc import epsilon, mu, n
from sympy.physics.units import speed_of_light, u0, e0, m, kg, s, A
from sympy.testing.pytest import raises
c = speed_of_light.convert_to(m/s)
e0 = e0.convert_to(A**2*s**4/(kg*m**3))
u0 = u0.convert_to(m*kg/(A**2*s**2))
def test_medium():
m1 = Medium('m1')
assert m1.intrinsic_impedance == sqrt(u0/e0)
assert m1.speed == 1/sqrt(e0*u0)
assert m1.refractive_index == c*sqrt(e0*u0)
assert m1.permittivity == e0
assert m1.permeability == u0
m2 = Medium('m2', epsilon, mu)
assert m2.intrinsic_impedance == sqrt(mu/epsilon)
assert m2.speed == 1/sqrt(epsilon*mu)
assert m2.refractive_index == c*sqrt(epsilon*mu)
assert m2.permittivity == epsilon
assert m2.permeability == mu
# Increasing electric permittivity and magnetic permeability
# by small amount from its value in vacuum.
m3 = Medium('m3', 9.0*10**(-12)*s**4*A**2/(m**3*kg), 1.45*10**(-6)*kg*m/(A**2*s**2))
assert m3.refractive_index > m1.refractive_index
assert m3 > m1
assert m3 != m1
# Decreasing electric permittivity and magnetic permeability
# by small amount from its value in vacuum.
m4 = Medium('m4', 7.0*10**(-12)*s**4*A**2/(m**3*kg), 1.15*10**(-6)*kg*m/(A**2*s**2))
assert m4.refractive_index < m1.refractive_index
assert m4 < m1
m5 = Medium('m5', permittivity=710*10**(-12)*s**4*A**2/(m**3*kg), n=1.33)
assert abs(m5.intrinsic_impedance - 6.24845417765552*kg*m**2/(A**2*s**3)) \
< 1e-12*kg*m**2/(A**2*s**3)
assert abs(m5.speed - 225407863.157895*m/s) < 1e-6*m/s
assert abs(m5.refractive_index - 1.33000000000000) < 1e-12
assert abs(m5.permittivity - 7.1e-10*A**2*s**4/(kg*m**3)) \
< 1e-20*A**2*s**4/(kg*m**3)
assert abs(m5.permeability - 2.77206575232851e-8*kg*m/(A**2*s**2)) \
< 1e-20*kg*m/(A**2*s**2)
m6 = Medium('m6', None, mu, n)
assert m6.permittivity == n**2/(c**2*mu)
assert Medium('m7') == Medium('m8', e0, u0) # test for equality
raises(ValueError, lambda:Medium('m9', e0, u0, 2))
|
4a389c8c0a6d7191b0b97fa26ff2eaecf94638da2dbe8d97278a77240f623552 | from sympy.core.numbers import comp, Rational
from sympy.physics.optics.utils import (refraction_angle, fresnel_coefficients,
deviation, brewster_angle, critical_angle, lens_makers_formula,
mirror_formula, lens_formula, hyperfocal_distance,
transverse_magnification)
from sympy.physics.optics.medium import Medium
from sympy.physics.units import e0
from sympy.core.numbers import oo
from sympy.core.symbol import symbols
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.matrices.dense import Matrix
from sympy.geometry.point import Point3D
from sympy.geometry.line import Ray3D
from sympy.geometry.plane import Plane
from sympy.testing.pytest import raises
ae = lambda a, b, n: comp(a, b, 10**-n)
def test_refraction_angle():
n1, n2 = symbols('n1, n2')
m1 = Medium('m1')
m2 = Medium('m2')
r1 = Ray3D(Point3D(-1, -1, 1), Point3D(0, 0, 0))
i = Matrix([1, 1, 1])
n = Matrix([0, 0, 1])
normal_ray = Ray3D(Point3D(0, 0, 0), Point3D(0, 0, 1))
P = Plane(Point3D(0, 0, 0), normal_vector=[0, 0, 1])
assert refraction_angle(r1, 1, 1, n) == Matrix([
[ 1],
[ 1],
[-1]])
assert refraction_angle([1, 1, 1], 1, 1, n) == Matrix([
[ 1],
[ 1],
[-1]])
assert refraction_angle((1, 1, 1), 1, 1, n) == Matrix([
[ 1],
[ 1],
[-1]])
assert refraction_angle(i, 1, 1, [0, 0, 1]) == Matrix([
[ 1],
[ 1],
[-1]])
assert refraction_angle(i, 1, 1, (0, 0, 1)) == Matrix([
[ 1],
[ 1],
[-1]])
assert refraction_angle(i, 1, 1, normal_ray) == Matrix([
[ 1],
[ 1],
[-1]])
assert refraction_angle(i, 1, 1, plane=P) == Matrix([
[ 1],
[ 1],
[-1]])
assert refraction_angle(r1, 1, 1, plane=P) == \
Ray3D(Point3D(0, 0, 0), Point3D(1, 1, -1))
assert refraction_angle(r1, m1, 1.33, plane=P) == \
Ray3D(Point3D(0, 0, 0), Point3D(Rational(100, 133), Rational(100, 133), -789378201649271*sqrt(3)/1000000000000000))
assert refraction_angle(r1, 1, m2, plane=P) == \
Ray3D(Point3D(0, 0, 0), Point3D(1, 1, -1))
assert refraction_angle(r1, n1, n2, plane=P) == \
Ray3D(Point3D(0, 0, 0), Point3D(n1/n2, n1/n2, -sqrt(3)*sqrt(-2*n1**2/(3*n2**2) + 1)))
assert refraction_angle(r1, 1.33, 1, plane=P) == 0 # TIR
assert refraction_angle(r1, 1, 1, normal_ray) == \
Ray3D(Point3D(0, 0, 0), direction_ratio=[1, 1, -1])
assert ae(refraction_angle(0.5, 1, 2), 0.24207, 5)
assert ae(refraction_angle(0.5, 2, 1), 1.28293, 5)
raises(ValueError, lambda: refraction_angle(r1, m1, m2, normal_ray, P))
raises(TypeError, lambda: refraction_angle(m1, m1, m2)) # can add other values for arg[0]
raises(TypeError, lambda: refraction_angle(r1, m1, m2, None, i))
raises(TypeError, lambda: refraction_angle(r1, m1, m2, m2))
def test_fresnel_coefficients():
assert all(ae(i, j, 5) for i, j in zip(
fresnel_coefficients(0.5, 1, 1.33),
[0.11163, -0.17138, 0.83581, 0.82862]))
assert all(ae(i, j, 5) for i, j in zip(
fresnel_coefficients(0.5, 1.33, 1),
[-0.07726, 0.20482, 1.22724, 1.20482]))
m1 = Medium('m1')
m2 = Medium('m2', n=2)
assert all(ae(i, j, 5) for i, j in zip(
fresnel_coefficients(0.3, m1, m2),
[0.31784, -0.34865, 0.65892, 0.65135]))
ans = [[-0.23563, -0.97184], [0.81648, -0.57738]]
got = fresnel_coefficients(0.6, m2, m1)
for i, j in zip(got, ans):
for a, b in zip(i.as_real_imag(), j):
assert ae(a, b, 5)
def test_deviation():
n1, n2 = symbols('n1, n2')
r1 = Ray3D(Point3D(-1, -1, 1), Point3D(0, 0, 0))
n = Matrix([0, 0, 1])
i = Matrix([-1, -1, -1])
normal_ray = Ray3D(Point3D(0, 0, 0), Point3D(0, 0, 1))
P = Plane(Point3D(0, 0, 0), normal_vector=[0, 0, 1])
assert deviation(r1, 1, 1, normal=n) == 0
assert deviation(r1, 1, 1, plane=P) == 0
assert deviation(r1, 1, 1.1, plane=P).evalf(3) + 0.119 < 1e-3
assert deviation(i, 1, 1.1, normal=normal_ray).evalf(3) + 0.119 < 1e-3
assert deviation(r1, 1.33, 1, plane=P) is None # TIR
assert deviation(r1, 1, 1, normal=[0, 0, 1]) == 0
assert deviation([-1, -1, -1], 1, 1, normal=[0, 0, 1]) == 0
assert ae(deviation(0.5, 1, 2), -0.25793, 5)
assert ae(deviation(0.5, 2, 1), 0.78293, 5)
def test_brewster_angle():
m1 = Medium('m1', n=1)
m2 = Medium('m2', n=1.33)
assert ae(brewster_angle(m1, m2), 0.93, 2)
m1 = Medium('m1', permittivity=e0, n=1)
m2 = Medium('m2', permittivity=e0, n=1.33)
assert ae(brewster_angle(m1, m2), 0.93, 2)
assert ae(brewster_angle(1, 1.33), 0.93, 2)
def test_critical_angle():
m1 = Medium('m1', n=1)
m2 = Medium('m2', n=1.33)
assert ae(critical_angle(m2, m1), 0.85, 2)
def test_lens_makers_formula():
n1, n2 = symbols('n1, n2')
m1 = Medium('m1', permittivity=e0, n=1)
m2 = Medium('m2', permittivity=e0, n=1.33)
assert lens_makers_formula(n1, n2, 10, -10) == 5.0*n2/(n1 - n2)
assert ae(lens_makers_formula(m1, m2, 10, -10), -20.15, 2)
assert ae(lens_makers_formula(1.33, 1, 10, -10), 15.15, 2)
def test_mirror_formula():
u, v, f = symbols('u, v, f')
assert mirror_formula(focal_length=f, u=u) == f*u/(-f + u)
assert mirror_formula(focal_length=f, v=v) == f*v/(-f + v)
assert mirror_formula(u=u, v=v) == u*v/(u + v)
assert mirror_formula(u=oo, v=v) == v
assert mirror_formula(u=oo, v=oo) is oo
assert mirror_formula(focal_length=oo, u=u) == -u
assert mirror_formula(u=u, v=oo) == u
assert mirror_formula(focal_length=oo, v=oo) is oo
assert mirror_formula(focal_length=f, v=oo) == f
assert mirror_formula(focal_length=oo, v=v) == -v
assert mirror_formula(focal_length=oo, u=oo) is oo
assert mirror_formula(focal_length=f, u=oo) == f
assert mirror_formula(focal_length=oo, u=u) == -u
raises(ValueError, lambda: mirror_formula(focal_length=f, u=u, v=v))
def test_lens_formula():
u, v, f = symbols('u, v, f')
assert lens_formula(focal_length=f, u=u) == f*u/(f + u)
assert lens_formula(focal_length=f, v=v) == f*v/(f - v)
assert lens_formula(u=u, v=v) == u*v/(u - v)
assert lens_formula(u=oo, v=v) == v
assert lens_formula(u=oo, v=oo) is oo
assert lens_formula(focal_length=oo, u=u) == u
assert lens_formula(u=u, v=oo) == -u
assert lens_formula(focal_length=oo, v=oo) is -oo
assert lens_formula(focal_length=oo, v=v) == v
assert lens_formula(focal_length=f, v=oo) == -f
assert lens_formula(focal_length=oo, u=oo) is oo
assert lens_formula(focal_length=oo, u=u) == u
assert lens_formula(focal_length=f, u=oo) == f
raises(ValueError, lambda: lens_formula(focal_length=f, u=u, v=v))
def test_hyperfocal_distance():
f, N, c = symbols('f, N, c')
assert hyperfocal_distance(f=f, N=N, c=c) == f**2/(N*c)
assert ae(hyperfocal_distance(f=0.5, N=8, c=0.0033), 9.47, 2)
def test_transverse_magnification():
si, so = symbols('si, so')
assert transverse_magnification(si, so) == -si/so
assert transverse_magnification(30, 15) == -2
def test_lens_makers_formula_thick_lens():
n1, n2 = symbols('n1, n2')
m1 = Medium('m1', permittivity=e0, n=1)
m2 = Medium('m2', permittivity=e0, n=1.33)
assert ae(lens_makers_formula(m1, m2, 10, -10, d=1), -19.82, 2)
assert lens_makers_formula(n1, n2, 1, -1, d=0.1) == n2/((2.0 - (0.1*n1 - 0.1*n2)/n1)*(n1 - n2))
def test_lens_makers_formula_plano_lens():
n1, n2 = symbols('n1, n2')
m1 = Medium('m1', permittivity=e0, n=1)
m2 = Medium('m2', permittivity=e0, n=1.33)
assert ae(lens_makers_formula(m1, m2, 10, oo), -40.30, 2)
assert lens_makers_formula(n1, n2, 10, oo) == 10.0*n2/(n1 - n2)
|
f35333c80dbd1d972483f4acfbcf3ee68d20f5aba00ea0abfcbc1c248897b80d | from sympy.physics.optics.polarization import (jones_vector, stokes_vector,
jones_2_stokes, linear_polarizer, phase_retarder, half_wave_retarder,
quarter_wave_retarder, transmissive_filter, reflective_filter,
mueller_matrix, polarizing_beam_splitter)
from sympy.core.numbers import (I, pi)
from sympy.core.singleton import S
from sympy.core.symbol import symbols
from sympy.functions.elementary.exponential import exp
from sympy.matrices.dense import Matrix
def test_polarization():
assert jones_vector(0, 0) == Matrix([1, 0])
assert jones_vector(pi/2, 0) == Matrix([0, 1])
#################################################################
assert stokes_vector(0, 0) == Matrix([1, 1, 0, 0])
assert stokes_vector(pi/2, 0) == Matrix([1, -1, 0, 0])
#################################################################
H = jones_vector(0, 0)
V = jones_vector(pi/2, 0)
D = jones_vector(pi/4, 0)
A = jones_vector(-pi/4, 0)
R = jones_vector(0, pi/4)
L = jones_vector(0, -pi/4)
res = [Matrix([1, 1, 0, 0]),
Matrix([1, -1, 0, 0]),
Matrix([1, 0, 1, 0]),
Matrix([1, 0, -1, 0]),
Matrix([1, 0, 0, 1]),
Matrix([1, 0, 0, -1])]
assert [jones_2_stokes(e) for e in [H, V, D, A, R, L]] == res
#################################################################
assert linear_polarizer(0) == Matrix([[1, 0], [0, 0]])
#################################################################
delta = symbols("delta", real=True)
res = Matrix([[exp(-I*delta/2), 0], [0, exp(I*delta/2)]])
assert phase_retarder(0, delta) == res
#################################################################
assert half_wave_retarder(0) == Matrix([[-I, 0], [0, I]])
#################################################################
res = Matrix([[exp(-I*pi/4), 0], [0, I*exp(-I*pi/4)]])
assert quarter_wave_retarder(0) == res
#################################################################
assert transmissive_filter(1) == Matrix([[1, 0], [0, 1]])
#################################################################
assert reflective_filter(1) == Matrix([[1, 0], [0, -1]])
res = Matrix([[S(1)/2, S(1)/2, 0, 0],
[S(1)/2, S(1)/2, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]])
assert mueller_matrix(linear_polarizer(0)) == res
#################################################################
res = Matrix([[1, 0, 0, 0], [0, 0, 0, -I], [0, 0, 1, 0], [0, -I, 0, 0]])
assert polarizing_beam_splitter() == res
|
a5152fc5fd2bc728afdd9e9f2938c6305b9997cdf2e2bf42195030283c0806fb | from sympy.core.evalf import N
from sympy.core.numbers import (Float, I, oo, pi)
from sympy.core.symbol import symbols
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import atan2
from sympy.matrices.dense import Matrix
from sympy.polys.polytools import factor
from sympy.physics.optics import (BeamParameter, CurvedMirror,
CurvedRefraction, FlatMirror, FlatRefraction, FreeSpace, GeometricRay,
RayTransferMatrix, ThinLens, conjugate_gauss_beams,
gaussian_conj, geometric_conj_ab, geometric_conj_af, geometric_conj_bf,
rayleigh2waist, waist2rayleigh)
def streq(a, b):
return str(a) == str(b)
def test_gauss_opt():
mat = RayTransferMatrix(1, 2, 3, 4)
assert mat == Matrix([[1, 2], [3, 4]])
assert mat == RayTransferMatrix( Matrix([[1, 2], [3, 4]]) )
assert [mat.A, mat.B, mat.C, mat.D] == [1, 2, 3, 4]
d, f, h, n1, n2, R = symbols('d f h n1 n2 R')
lens = ThinLens(f)
assert lens == Matrix([[ 1, 0], [-1/f, 1]])
assert lens.C == -1/f
assert FreeSpace(d) == Matrix([[ 1, d], [0, 1]])
assert FlatRefraction(n1, n2) == Matrix([[1, 0], [0, n1/n2]])
assert CurvedRefraction(
R, n1, n2) == Matrix([[1, 0], [(n1 - n2)/(R*n2), n1/n2]])
assert FlatMirror() == Matrix([[1, 0], [0, 1]])
assert CurvedMirror(R) == Matrix([[ 1, 0], [-2/R, 1]])
assert ThinLens(f) == Matrix([[ 1, 0], [-1/f, 1]])
mul = CurvedMirror(R)*FreeSpace(d)
mul_mat = Matrix([[ 1, 0], [-2/R, 1]])*Matrix([[ 1, d], [0, 1]])
assert mul.A == mul_mat[0, 0]
assert mul.B == mul_mat[0, 1]
assert mul.C == mul_mat[1, 0]
assert mul.D == mul_mat[1, 1]
angle = symbols('angle')
assert GeometricRay(h, angle) == Matrix([[ h], [angle]])
assert FreeSpace(
d)*GeometricRay(h, angle) == Matrix([[angle*d + h], [angle]])
assert GeometricRay( Matrix( ((h,), (angle,)) ) ) == Matrix([[h], [angle]])
assert (FreeSpace(d)*GeometricRay(h, angle)).height == angle*d + h
assert (FreeSpace(d)*GeometricRay(h, angle)).angle == angle
p = BeamParameter(530e-9, 1, w=1e-3)
assert streq(p.q, 1 + 1.88679245283019*I*pi)
assert streq(N(p.q), 1.0 + 5.92753330865999*I)
assert streq(N(p.w_0), Float(0.00100000000000000))
assert streq(N(p.z_r), Float(5.92753330865999))
fs = FreeSpace(10)
p1 = fs*p
assert streq(N(p.w), Float(0.00101413072159615))
assert streq(N(p1.w), Float(0.00210803120913829))
w, wavelen = symbols('w wavelen')
assert waist2rayleigh(w, wavelen) == pi*w**2/wavelen
z_r, wavelen = symbols('z_r wavelen')
assert rayleigh2waist(z_r, wavelen) == sqrt(wavelen*z_r)/sqrt(pi)
a, b, f = symbols('a b f')
assert geometric_conj_ab(a, b) == a*b/(a + b)
assert geometric_conj_af(a, f) == a*f/(a - f)
assert geometric_conj_bf(b, f) == b*f/(b - f)
assert geometric_conj_ab(oo, b) == b
assert geometric_conj_ab(a, oo) == a
s_in, z_r_in, f = symbols('s_in z_r_in f')
assert gaussian_conj(
s_in, z_r_in, f)[0] == 1/(-1/(s_in + z_r_in**2/(-f + s_in)) + 1/f)
assert gaussian_conj(
s_in, z_r_in, f)[1] == z_r_in/(1 - s_in**2/f**2 + z_r_in**2/f**2)
assert gaussian_conj(
s_in, z_r_in, f)[2] == 1/sqrt(1 - s_in**2/f**2 + z_r_in**2/f**2)
l, w_i, w_o, f = symbols('l w_i w_o f')
assert conjugate_gauss_beams(l, w_i, w_o, f=f)[0] == f*(
-sqrt(w_i**2/w_o**2 - pi**2*w_i**4/(f**2*l**2)) + 1)
assert factor(conjugate_gauss_beams(l, w_i, w_o, f=f)[1]) == f*w_o**2*(
w_i**2/w_o**2 - sqrt(w_i**2/w_o**2 - pi**2*w_i**4/(f**2*l**2)))/w_i**2
assert conjugate_gauss_beams(l, w_i, w_o, f=f)[2] == f
z, l, w = symbols('z l r', positive=True)
p = BeamParameter(l, z, w=w)
assert p.radius == z*(pi**2*w**4/(l**2*z**2) + 1)
assert p.w == w*sqrt(l**2*z**2/(pi**2*w**4) + 1)
assert p.w_0 == w
assert p.divergence == l/(pi*w)
assert p.gouy == atan2(z, pi*w**2/l)
assert p.waist_approximation_limit == 2*l/pi
|
88249c9c01cf20129b562041ed81f26bc1f2684337010adcb6a0055c73701e69 | from typing import Optional
from sympy.core.expr import Expr
from sympy.core.function import Derivative
from sympy.core.numbers import Integer
from sympy.matrices.common import MatrixCommon
from .ndim_array import NDimArray
from .arrayop import derive_by_array
from sympy.matrices.expressions.matexpr import MatrixExpr
from sympy.matrices.expressions.special import ZeroMatrix
from sympy.matrices.expressions.matexpr import _matrix_derivative
class ArrayDerivative(Derivative):
is_scalar = False
def __new__(cls, expr, *variables, **kwargs):
obj = super().__new__(cls, expr, *variables, **kwargs)
if isinstance(obj, ArrayDerivative):
obj._shape = obj._get_shape()
return obj
def _get_shape(self):
shape = ()
for v, count in self.variable_count:
if hasattr(v, "shape"):
for i in range(count):
shape += v.shape
if hasattr(self.expr, "shape"):
shape += self.expr.shape
return shape
@property
def shape(self):
return self._shape
@classmethod
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.")
@staticmethod
def _call_derive_scalar_by_matrix(expr, v): # type: (Expr, MatrixCommon) -> Expr
return v.applyfunc(lambda x: expr.diff(x))
@staticmethod
def _call_derive_scalar_by_matexpr(expr, v): # type: (Expr, MatrixExpr) -> Expr
if expr.has(v):
return _matrix_derivative(expr, v)
else:
return ZeroMatrix(*v.shape)
@staticmethod
def _call_derive_scalar_by_array(expr, v): # type: (Expr, NDimArray) -> Expr
return v.applyfunc(lambda x: expr.diff(x))
@staticmethod
def _call_derive_matrix_by_scalar(expr, v): # type: (MatrixCommon, Expr) -> Expr
return _matrix_derivative(expr, v)
@staticmethod
def _call_derive_matexpr_by_scalar(expr, v): # type: (MatrixExpr, Expr) -> Expr
return expr._eval_derivative(v)
@staticmethod
def _call_derive_array_by_scalar(expr, v): # type: (NDimArray, Expr) -> Expr
return expr.applyfunc(lambda x: x.diff(v))
@staticmethod
def _call_derive_default(expr, v): # type: (Expr, Expr) -> Optional[Expr]
if expr.has(v):
return _matrix_derivative(expr, v)
else:
return None
@classmethod
def _dispatch_eval_derivative_n_times(cls, expr, v, count):
# Evaluate the derivative `n` times. If
# `_eval_derivative_n_times` is not overridden by the current
# object, the default in `Basic` will call a loop over
# `_eval_derivative`:
if not isinstance(count, (int, Integer)) or ((count <= 0) == True):
return None
# TODO: this could be done with multiple-dispatching:
if expr.is_scalar:
if isinstance(v, MatrixCommon):
result = cls._call_derive_scalar_by_matrix(expr, v)
elif isinstance(v, MatrixExpr):
result = cls._call_derive_scalar_by_matexpr(expr, v)
elif isinstance(v, NDimArray):
result = cls._call_derive_scalar_by_array(expr, v)
elif v.is_scalar:
# scalar by scalar has a special
return super()._dispatch_eval_derivative_n_times(expr, v, count)
else:
return None
elif v.is_scalar:
if isinstance(expr, MatrixCommon):
result = cls._call_derive_matrix_by_scalar(expr, v)
elif isinstance(expr, MatrixExpr):
result = cls._call_derive_matexpr_by_scalar(expr, v)
elif isinstance(expr, NDimArray):
result = cls._call_derive_array_by_scalar(expr, v)
else:
return None
else:
# Both `expr` and `v` are some array/matrix type:
if isinstance(expr, MatrixCommon) or isinstance(expr, MatrixCommon):
result = derive_by_array(expr, v)
elif isinstance(expr, MatrixExpr) and isinstance(v, MatrixExpr):
result = cls._call_derive_default(expr, v)
elif isinstance(expr, MatrixExpr) or isinstance(v, MatrixExpr):
# if one expression is a symbolic matrix expression while the other isn't, don't evaluate:
return None
else:
result = derive_by_array(expr, v)
if result is None:
return None
if count == 1:
return result
else:
return cls._dispatch_eval_derivative_n_times(result, v, count - 1)
|
16cfbd378610d1220858ad6d6bd8799fc7fd510fe48a07e5608bb306ca4eda8e | import functools, itertools
from sympy.core.sympify import sympify
from sympy.core.expr import Expr
from sympy.core import Basic
from sympy.tensor.array import ImmutableDenseNDimArray
from sympy.core.symbol import Symbol
from sympy.core.numbers import Integer
class ArrayComprehension(Basic):
"""
Generate a list comprehension.
Explanation
===========
If there is a symbolic dimension, for example, say [i for i in range(1, N)] where
N is a Symbol, then the expression will not be expanded to an array. Otherwise,
calling the doit() function will launch the expansion.
Examples
========
>>> from sympy.tensor.array import ArrayComprehension
>>> from sympy import symbols
>>> i, j, k = symbols('i j k')
>>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
>>> a
ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
>>> a.doit()
[[11, 12, 13], [21, 22, 23], [31, 32, 33], [41, 42, 43]]
>>> b = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, k))
>>> b.doit()
ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, k))
"""
def __new__(cls, function, *symbols, **assumptions):
if any(len(l) != 3 or None for l in symbols):
raise ValueError('ArrayComprehension requires values lower and upper bound'
' for the expression')
arglist = [sympify(function)]
arglist.extend(cls._check_limits_validity(function, symbols))
obj = Basic.__new__(cls, *arglist, **assumptions)
obj._limits = obj._args[1:]
obj._shape = cls._calculate_shape_from_limits(obj._limits)
obj._rank = len(obj._shape)
obj._loop_size = cls._calculate_loop_size(obj._shape)
return obj
@property
def function(self):
"""The function applied across limits.
Examples
========
>>> from sympy.tensor.array import ArrayComprehension
>>> from sympy import symbols
>>> i, j = symbols('i j')
>>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
>>> a.function
10*i + j
"""
return self._args[0]
@property
def limits(self):
"""
The list of limits that will be applied while expanding the array.
Examples
========
>>> from sympy.tensor.array import ArrayComprehension
>>> from sympy import symbols
>>> i, j = symbols('i j')
>>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
>>> a.limits
((i, 1, 4), (j, 1, 3))
"""
return self._limits
@property
def free_symbols(self):
"""
The set of the free_symbols in the array.
Variables appeared in the bounds are supposed to be excluded
from the free symbol set.
Examples
========
>>> from sympy.tensor.array import ArrayComprehension
>>> from sympy import symbols
>>> i, j, k = symbols('i j k')
>>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
>>> a.free_symbols
set()
>>> b = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, k+3))
>>> b.free_symbols
{k}
"""
expr_free_sym = self.function.free_symbols
for var, inf, sup in self._limits:
expr_free_sym.discard(var)
curr_free_syms = inf.free_symbols.union(sup.free_symbols)
expr_free_sym = expr_free_sym.union(curr_free_syms)
return expr_free_sym
@property
def variables(self):
"""The tuples of the variables in the limits.
Examples
========
>>> from sympy.tensor.array import ArrayComprehension
>>> from sympy import symbols
>>> i, j, k = symbols('i j k')
>>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
>>> a.variables
[i, j]
"""
return [l[0] for l in self._limits]
@property
def bound_symbols(self):
"""The list of dummy variables.
Note
====
Note that all variables are dummy variables since a limit without
lower bound or upper bound is not accepted.
"""
return [l[0] for l in self._limits if len(l) != 1]
@property
def shape(self):
"""
The shape of the expanded array, which may have symbols.
Note
====
Both the lower and the upper bounds are included while
calculating the shape.
Examples
========
>>> from sympy.tensor.array import ArrayComprehension
>>> from sympy import symbols
>>> i, j, k = symbols('i j k')
>>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
>>> a.shape
(4, 3)
>>> b = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, k+3))
>>> b.shape
(4, k + 3)
"""
return self._shape
@property
def is_shape_numeric(self):
"""
Test if the array is shape-numeric which means there is no symbolic
dimension.
Examples
========
>>> from sympy.tensor.array import ArrayComprehension
>>> from sympy import symbols
>>> i, j, k = symbols('i j k')
>>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
>>> a.is_shape_numeric
True
>>> b = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, k+3))
>>> b.is_shape_numeric
False
"""
for _, inf, sup in self._limits:
if Basic(inf, sup).atoms(Symbol):
return False
return True
def rank(self):
"""The rank of the expanded array.
Examples
========
>>> from sympy.tensor.array import ArrayComprehension
>>> from sympy import symbols
>>> i, j, k = symbols('i j k')
>>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
>>> a.rank()
2
"""
return self._rank
def __len__(self):
"""
The length of the expanded array which means the number
of elements in the array.
Raises
======
ValueError : When the length of the array is symbolic
Examples
========
>>> from sympy.tensor.array import ArrayComprehension
>>> from sympy import symbols
>>> i, j = symbols('i j')
>>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
>>> len(a)
12
"""
if self._loop_size.free_symbols:
raise ValueError('Symbolic length is not supported')
return self._loop_size
@classmethod
def _check_limits_validity(cls, function, limits):
limits = sympify(limits)
for var, inf, sup in limits:
if any((not isinstance(i, Expr)) or i.atoms(Symbol, Integer) != i.atoms()
for i in [inf, sup]):
raise TypeError('Bounds should be an Expression(combination of Integer and Symbol)')
if (inf > sup) == True:
raise ValueError('Lower bound should be inferior to upper bound')
if var in inf.free_symbols or var in sup.free_symbols:
raise ValueError('Variable should not be part of its bounds')
return limits
@classmethod
def _calculate_shape_from_limits(cls, limits):
return tuple([sup - inf + 1 for _, inf, sup in limits])
@classmethod
def _calculate_loop_size(cls, shape):
if not shape:
return 0
loop_size = 1
for l in shape:
loop_size = loop_size * l
return loop_size
def doit(self):
if not self.is_shape_numeric:
return self
return self._expand_array()
def _expand_array(self):
res = []
for values in itertools.product(*[range(inf, sup+1)
for var, inf, sup
in self._limits]):
res.append(self._get_element(values))
return ImmutableDenseNDimArray(res, self.shape)
def _get_element(self, values):
temp = self.function
for var, val in zip(self.variables, values):
temp = temp.subs(var, val)
return temp
def tolist(self):
"""Transform the expanded array to a list.
Raises
======
ValueError : When there is a symbolic dimension
Examples
========
>>> from sympy.tensor.array import ArrayComprehension
>>> from sympy import symbols
>>> i, j = symbols('i j')
>>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
>>> a.tolist()
[[11, 12, 13], [21, 22, 23], [31, 32, 33], [41, 42, 43]]
"""
if self.is_shape_numeric:
return self._expand_array().tolist()
raise ValueError("A symbolic array cannot be expanded to a list")
def tomatrix(self):
"""Transform the expanded array to a matrix.
Raises
======
ValueError : When there is a symbolic dimension
ValueError : When the rank of the expanded array is not equal to 2
Examples
========
>>> from sympy.tensor.array import ArrayComprehension
>>> from sympy import symbols
>>> i, j = symbols('i j')
>>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
>>> a.tomatrix()
Matrix([
[11, 12, 13],
[21, 22, 23],
[31, 32, 33],
[41, 42, 43]])
"""
from sympy.matrices import Matrix
if not self.is_shape_numeric:
raise ValueError("A symbolic array cannot be expanded to a matrix")
if self._rank != 2:
raise ValueError('Dimensions must be of size of 2')
return Matrix(self._expand_array().tomatrix())
def isLambda(v):
LAMBDA = lambda: 0
return isinstance(v, type(LAMBDA)) and v.__name__ == LAMBDA.__name__
class ArrayComprehensionMap(ArrayComprehension):
'''
A subclass of ArrayComprehension dedicated to map external function lambda.
Notes
=====
Only the lambda function is considered.
At most one argument in lambda function is accepted in order to avoid ambiguity
in value assignment.
Examples
========
>>> from sympy.tensor.array import ArrayComprehensionMap
>>> from sympy import symbols
>>> i, j, k = symbols('i j k')
>>> a = ArrayComprehensionMap(lambda: 1, (i, 1, 4))
>>> a.doit()
[1, 1, 1, 1]
>>> b = ArrayComprehensionMap(lambda a: a+1, (j, 1, 4))
>>> b.doit()
[2, 3, 4, 5]
'''
def __new__(cls, function, *symbols, **assumptions):
if any(len(l) != 3 or None for l in symbols):
raise ValueError('ArrayComprehension requires values lower and upper bound'
' for the expression')
if not isLambda(function):
raise ValueError('Data type not supported')
arglist = cls._check_limits_validity(function, symbols)
obj = Basic.__new__(cls, *arglist, **assumptions)
obj._limits = obj._args
obj._shape = cls._calculate_shape_from_limits(obj._limits)
obj._rank = len(obj._shape)
obj._loop_size = cls._calculate_loop_size(obj._shape)
obj._lambda = function
return obj
@property
def func(self):
class _(ArrayComprehensionMap):
def __new__(cls, *args, **kwargs):
return ArrayComprehensionMap(self._lambda, *args, **kwargs)
return _
def _get_element(self, values):
temp = self._lambda
if self._lambda.__code__.co_argcount == 0:
temp = temp()
elif self._lambda.__code__.co_argcount == 1:
temp = temp(functools.reduce(lambda a, b: a*b, values))
return temp
|
95a16b78dcc0bc663c30833f6e61a9d4eee98bcba05da532b4e188bcf2e458b6 | import itertools
from collections.abc import Iterable
from sympy.core.basic import Basic
from sympy.core.containers import Tuple
from sympy.core.function import diff
from sympy.core.singleton import S
from sympy.core.sympify import _sympify
from sympy.tensor.array.ndim_array import NDimArray
from sympy.tensor.array.dense_ndim_array import DenseNDimArray, ImmutableDenseNDimArray
from sympy.tensor.array.sparse_ndim_array import SparseNDimArray
def _arrayfy(a):
from sympy.matrices import MatrixBase
if isinstance(a, NDimArray):
return a
if isinstance(a, (MatrixBase, list, tuple, Tuple)):
return ImmutableDenseNDimArray(a)
return a
def tensorproduct(*args):
"""
Tensor product among scalars or array-like objects.
Examples
========
>>> from sympy.tensor.array import tensorproduct, Array
>>> from sympy.abc import x, y, z, t
>>> A = Array([[1, 2], [3, 4]])
>>> B = Array([x, y])
>>> tensorproduct(A, B)
[[[x, y], [2*x, 2*y]], [[3*x, 3*y], [4*x, 4*y]]]
>>> tensorproduct(A, x)
[[x, 2*x], [3*x, 4*x]]
>>> tensorproduct(A, B, B)
[[[[x**2, x*y], [x*y, y**2]], [[2*x**2, 2*x*y], [2*x*y, 2*y**2]]], [[[3*x**2, 3*x*y], [3*x*y, 3*y**2]], [[4*x**2, 4*x*y], [4*x*y, 4*y**2]]]]
Applying this function on two matrices will result in a rank 4 array.
>>> from sympy import Matrix, eye
>>> m = Matrix([[x, y], [z, t]])
>>> p = tensorproduct(eye(3), m)
>>> p
[[[[x, y], [z, t]], [[0, 0], [0, 0]], [[0, 0], [0, 0]]], [[[0, 0], [0, 0]], [[x, y], [z, t]], [[0, 0], [0, 0]]], [[[0, 0], [0, 0]], [[0, 0], [0, 0]], [[x, y], [z, t]]]]
"""
from sympy.tensor.array import SparseNDimArray, ImmutableSparseNDimArray
if len(args) == 0:
return S.One
if len(args) == 1:
return _arrayfy(args[0])
from sympy.tensor.array.expressions.array_expressions import _CodegenArrayAbstract
from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct
from sympy.tensor.array.expressions.array_expressions import _ArrayExpr
from sympy.matrices.expressions.matexpr import MatrixSymbol
if any(isinstance(arg, (_ArrayExpr, _CodegenArrayAbstract, MatrixSymbol)) for arg in args):
return ArrayTensorProduct(*args)
if len(args) > 2:
return tensorproduct(tensorproduct(args[0], args[1]), *args[2:])
# length of args is 2:
a, b = map(_arrayfy, args)
if not isinstance(a, NDimArray) or not isinstance(b, NDimArray):
return a*b
if isinstance(a, SparseNDimArray) and isinstance(b, SparseNDimArray):
lp = len(b)
new_array = {k1*lp + k2: v1*v2 for k1, v1 in a._sparse_array.items() for k2, v2 in b._sparse_array.items()}
return ImmutableSparseNDimArray(new_array, a.shape + b.shape)
product_list = [i*j for i in Flatten(a) for j in Flatten(b)]
return ImmutableDenseNDimArray(product_list, a.shape + b.shape)
def _util_contraction_diagonal(array, *contraction_or_diagonal_axes):
array = _arrayfy(array)
# Verify contraction_axes:
taken_dims = set()
for axes_group in contraction_or_diagonal_axes:
if not isinstance(axes_group, Iterable):
raise ValueError("collections of contraction/diagonal axes expected")
dim = array.shape[axes_group[0]]
for d in axes_group:
if d in taken_dims:
raise ValueError("dimension specified more than once")
if dim != array.shape[d]:
raise ValueError("cannot contract or diagonalize between axes of different dimension")
taken_dims.add(d)
rank = array.rank()
remaining_shape = [dim for i, dim in enumerate(array.shape) if i not in taken_dims]
cum_shape = [0]*rank
_cumul = 1
for i in range(rank):
cum_shape[rank - i - 1] = _cumul
_cumul *= int(array.shape[rank - i - 1])
# DEFINITION: by absolute position it is meant the position along the one
# dimensional array containing all the tensor components.
# Possible future work on this module: move computation of absolute
# positions to a class method.
# Determine absolute positions of the uncontracted indices:
remaining_indices = [[cum_shape[i]*j for j in range(array.shape[i])]
for i in range(rank) if i not in taken_dims]
# Determine absolute positions of the contracted indices:
summed_deltas = []
for axes_group in contraction_or_diagonal_axes:
lidx = []
for js in range(array.shape[axes_group[0]]):
lidx.append(sum([cum_shape[ig] * js for ig in axes_group]))
summed_deltas.append(lidx)
return array, remaining_indices, remaining_shape, summed_deltas
def tensorcontraction(array, *contraction_axes):
"""
Contraction of an array-like object on the specified axes.
Examples
========
>>> from sympy import Array, tensorcontraction
>>> from sympy import Matrix, eye
>>> tensorcontraction(eye(3), (0, 1))
3
>>> A = Array(range(18), (3, 2, 3))
>>> A
[[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]], [[12, 13, 14], [15, 16, 17]]]
>>> tensorcontraction(A, (0, 2))
[21, 30]
Matrix multiplication may be emulated with a proper combination of
``tensorcontraction`` and ``tensorproduct``
>>> from sympy import tensorproduct
>>> from sympy.abc import a,b,c,d,e,f,g,h
>>> m1 = Matrix([[a, b], [c, d]])
>>> m2 = Matrix([[e, f], [g, h]])
>>> p = tensorproduct(m1, m2)
>>> p
[[[[a*e, a*f], [a*g, a*h]], [[b*e, b*f], [b*g, b*h]]], [[[c*e, c*f], [c*g, c*h]], [[d*e, d*f], [d*g, d*h]]]]
>>> tensorcontraction(p, (1, 2))
[[a*e + b*g, a*f + b*h], [c*e + d*g, c*f + d*h]]
>>> m1*m2
Matrix([
[a*e + b*g, a*f + b*h],
[c*e + d*g, c*f + d*h]])
"""
from sympy.tensor.array.expressions.array_expressions import ArrayContraction
from sympy.tensor.array.expressions.array_expressions import _CodegenArrayAbstract
from sympy.tensor.array.expressions.array_expressions import _ArrayExpr
from sympy.matrices.expressions.matexpr import MatrixSymbol
if isinstance(array, (_ArrayExpr, _CodegenArrayAbstract, MatrixSymbol)):
return ArrayContraction(array, *contraction_axes)
array, remaining_indices, remaining_shape, summed_deltas = _util_contraction_diagonal(array, *contraction_axes)
# Compute the contracted array:
#
# 1. external for loops on all uncontracted indices.
# Uncontracted indices are determined by the combinatorial product of
# the absolute positions of the remaining indices.
# 2. internal loop on all contracted indices.
# It sums the values of the absolute contracted index and the absolute
# uncontracted index for the external loop.
contracted_array = []
for icontrib in itertools.product(*remaining_indices):
index_base_position = sum(icontrib)
isum = S.Zero
for sum_to_index in itertools.product(*summed_deltas):
idx = array._get_tuple_index(index_base_position + sum(sum_to_index))
isum += array[idx]
contracted_array.append(isum)
if len(remaining_indices) == 0:
assert len(contracted_array) == 1
return contracted_array[0]
return type(array)(contracted_array, remaining_shape)
def tensordiagonal(array, *diagonal_axes):
"""
Diagonalization of an array-like object on the specified axes.
This is equivalent to multiplying the expression by Kronecker deltas
uniting the axes.
The diagonal indices are put at the end of the axes.
Examples
========
``tensordiagonal`` acting on a 2-dimensional array by axes 0 and 1 is
equivalent to the diagonal of the matrix:
>>> from sympy import Array, tensordiagonal
>>> from sympy import Matrix, eye
>>> tensordiagonal(eye(3), (0, 1))
[1, 1, 1]
>>> from sympy.abc import a,b,c,d
>>> m1 = Matrix([[a, b], [c, d]])
>>> tensordiagonal(m1, [0, 1])
[a, d]
In case of higher dimensional arrays, the diagonalized out dimensions
are appended removed and appended as a single dimension at the end:
>>> A = Array(range(18), (3, 2, 3))
>>> A
[[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]], [[12, 13, 14], [15, 16, 17]]]
>>> tensordiagonal(A, (0, 2))
[[0, 7, 14], [3, 10, 17]]
>>> from sympy import permutedims
>>> tensordiagonal(A, (0, 2)) == permutedims(Array([A[0, :, 0], A[1, :, 1], A[2, :, 2]]), [1, 0])
True
"""
if any(len(i) <= 1 for i in diagonal_axes):
raise ValueError("need at least two axes to diagonalize")
from sympy.tensor.array.expressions.array_expressions import _ArrayExpr
from sympy.tensor.array.expressions.array_expressions import _CodegenArrayAbstract
from sympy.tensor.array.expressions.array_expressions import ArrayDiagonal
from sympy.matrices.expressions.matexpr import MatrixSymbol
if isinstance(array, (_ArrayExpr, _CodegenArrayAbstract, MatrixSymbol)):
return ArrayDiagonal(array, *diagonal_axes)
ArrayDiagonal._validate(array, *diagonal_axes)
array, remaining_indices, remaining_shape, diagonal_deltas = _util_contraction_diagonal(array, *diagonal_axes)
# Compute the diagonalized array:
#
# 1. external for loops on all undiagonalized indices.
# Undiagonalized indices are determined by the combinatorial product of
# the absolute positions of the remaining indices.
# 2. internal loop on all diagonal indices.
# It appends the values of the absolute diagonalized index and the absolute
# undiagonalized index for the external loop.
diagonalized_array = []
diagonal_shape = [len(i) for i in diagonal_deltas]
for icontrib in itertools.product(*remaining_indices):
index_base_position = sum(icontrib)
isum = []
for sum_to_index in itertools.product(*diagonal_deltas):
idx = array._get_tuple_index(index_base_position + sum(sum_to_index))
isum.append(array[idx])
isum = type(array)(isum).reshape(*diagonal_shape)
diagonalized_array.append(isum)
return type(array)(diagonalized_array, remaining_shape + diagonal_shape)
def derive_by_array(expr, dx):
r"""
Derivative by arrays. Supports both arrays and scalars.
Explanation
===========
Given the array `A_{i_1, \ldots, i_N}` and the array `X_{j_1, \ldots, j_M}`
this function will return a new array `B` defined by
`B_{j_1,\ldots,j_M,i_1,\ldots,i_N} := \frac{\partial A_{i_1,\ldots,i_N}}{\partial X_{j_1,\ldots,j_M}}`
Examples
========
>>> from sympy import derive_by_array
>>> from sympy.abc import x, y, z, t
>>> from sympy import cos
>>> derive_by_array(cos(x*t), x)
-t*sin(t*x)
>>> derive_by_array(cos(x*t), [x, y, z, t])
[-t*sin(t*x), 0, 0, -x*sin(t*x)]
>>> derive_by_array([x, y**2*z], [[x, y], [z, t]])
[[[1, 0], [0, 2*y*z]], [[0, y**2], [0, 0]]]
"""
from sympy.matrices import MatrixBase
from sympy.tensor.array import SparseNDimArray
array_types = (Iterable, MatrixBase, NDimArray)
if isinstance(dx, array_types):
dx = ImmutableDenseNDimArray(dx)
for i in dx:
if not i._diff_wrt:
raise ValueError("cannot derive by this array")
if isinstance(expr, array_types):
if isinstance(expr, NDimArray):
expr = expr.as_immutable()
else:
expr = ImmutableDenseNDimArray(expr)
if isinstance(dx, array_types):
if isinstance(expr, SparseNDimArray):
lp = len(expr)
new_array = {k + i*lp: v
for i, x in enumerate(Flatten(dx))
for k, v in expr.diff(x)._sparse_array.items()}
else:
new_array = [[y.diff(x) for y in Flatten(expr)] for x in Flatten(dx)]
return type(expr)(new_array, dx.shape + expr.shape)
else:
return expr.diff(dx)
else:
expr = _sympify(expr)
if isinstance(dx, array_types):
return ImmutableDenseNDimArray([expr.diff(i) for i in Flatten(dx)], dx.shape)
else:
dx = _sympify(dx)
return diff(expr, dx)
def permutedims(expr, perm):
"""
Permutes the indices of an array.
Parameter specifies the permutation of the indices.
Examples
========
>>> from sympy.abc import x, y, z, t
>>> from sympy import sin
>>> from sympy import Array, permutedims
>>> a = Array([[x, y, z], [t, sin(x), 0]])
>>> a
[[x, y, z], [t, sin(x), 0]]
>>> permutedims(a, (1, 0))
[[x, t], [y, sin(x)], [z, 0]]
If the array is of second order, ``transpose`` can be used:
>>> from sympy import transpose
>>> transpose(a)
[[x, t], [y, sin(x)], [z, 0]]
Examples on higher dimensions:
>>> b = Array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
>>> permutedims(b, (2, 1, 0))
[[[1, 5], [3, 7]], [[2, 6], [4, 8]]]
>>> permutedims(b, (1, 2, 0))
[[[1, 5], [2, 6]], [[3, 7], [4, 8]]]
``Permutation`` objects are also allowed:
>>> from sympy.combinatorics import Permutation
>>> permutedims(b, Permutation([1, 2, 0]))
[[[1, 5], [2, 6]], [[3, 7], [4, 8]]]
"""
from sympy.tensor.array import SparseNDimArray
from sympy.tensor.array.expressions.array_expressions import _ArrayExpr
from sympy.tensor.array.expressions.array_expressions import _CodegenArrayAbstract
from sympy.tensor.array.expressions.array_expressions import PermuteDims
from sympy.matrices.expressions.matexpr import MatrixSymbol
if isinstance(expr, (_ArrayExpr, _CodegenArrayAbstract, MatrixSymbol)):
return PermuteDims(expr, perm)
if not isinstance(expr, NDimArray):
expr = ImmutableDenseNDimArray(expr)
from sympy.combinatorics import Permutation
if not isinstance(perm, Permutation):
perm = Permutation(list(perm))
if perm.size != expr.rank():
raise ValueError("wrong permutation size")
# Get the inverse permutation:
iperm = ~perm
new_shape = perm(expr.shape)
if isinstance(expr, SparseNDimArray):
return type(expr)({tuple(perm(expr._get_tuple_index(k))): v
for k, v in expr._sparse_array.items()}, new_shape)
indices_span = perm([range(i) for i in expr.shape])
new_array = [None]*len(expr)
for i, idx in enumerate(itertools.product(*indices_span)):
t = iperm(idx)
new_array[i] = expr[t]
return type(expr)(new_array, new_shape)
class Flatten(Basic):
'''
Flatten an iterable object to a list in a lazy-evaluation way.
Notes
=====
This class is an iterator with which the memory cost can be economised.
Optimisation has been considered to ameliorate the performance for some
specific data types like DenseNDimArray and SparseNDimArray.
Examples
========
>>> from sympy.tensor.array.arrayop import Flatten
>>> from sympy.tensor.array import Array
>>> A = Array(range(6)).reshape(2, 3)
>>> Flatten(A)
Flatten([[0, 1, 2], [3, 4, 5]])
>>> [i for i in Flatten(A)]
[0, 1, 2, 3, 4, 5]
'''
def __init__(self, iterable):
from sympy.matrices.matrices import MatrixBase
from sympy.tensor.array import NDimArray
if not isinstance(iterable, (Iterable, MatrixBase)):
raise NotImplementedError("Data type not yet supported")
if isinstance(iterable, list):
iterable = NDimArray(iterable)
self._iter = iterable
self._idx = 0
def __iter__(self):
return self
def __next__(self):
from sympy.matrices.matrices import MatrixBase
if len(self._iter) > self._idx:
if isinstance(self._iter, DenseNDimArray):
result = self._iter._array[self._idx]
elif isinstance(self._iter, SparseNDimArray):
if self._idx in self._iter._sparse_array:
result = self._iter._sparse_array[self._idx]
else:
result = 0
elif isinstance(self._iter, MatrixBase):
result = self._iter[self._idx]
elif hasattr(self._iter, '__next__'):
result = next(self._iter)
else:
result = self._iter[self._idx]
else:
raise StopIteration
self._idx += 1
return result
def next(self):
return self.__next__()
|
e270ff1e0f89742ff5998413a2198a15f2f933552076ad1fa670d420b913b6af | from sympy.core.basic import Basic
from sympy.core.containers import (Dict, Tuple)
from sympy.core.singleton import S
from sympy.core.sympify import _sympify
from sympy.tensor.array.mutable_ndim_array import MutableNDimArray
from sympy.tensor.array.ndim_array import NDimArray, ImmutableNDimArray
from sympy.utilities.iterables import flatten
import functools
class SparseNDimArray(NDimArray):
def __new__(self, *args, **kwargs):
return ImmutableSparseNDimArray(*args, **kwargs)
def __getitem__(self, index):
"""
Get an element from a sparse N-dim array.
Examples
========
>>> from sympy import MutableSparseNDimArray
>>> a = MutableSparseNDimArray(range(4), (2, 2))
>>> a
[[0, 1], [2, 3]]
>>> a[0, 0]
0
>>> a[1, 1]
3
>>> a[0]
[0, 1]
>>> a[1]
[2, 3]
Symbolic indexing:
>>> from sympy.abc import i, j
>>> a[i, j]
[[0, 1], [2, 3]][i, j]
Replace `i` and `j` to get element `(0, 0)`:
>>> a[i, j].subs({i: 0, j: 0})
0
"""
syindex = self._check_symbolic_index(index)
if syindex is not None:
return syindex
index = self._check_index_for_getitem(index)
# `index` is a tuple with one or more slices:
if isinstance(index, tuple) and any(isinstance(i, slice) for i in index):
sl_factors, eindices = self._get_slice_data_for_array_access(index)
array = [self._sparse_array.get(self._parse_index(i), S.Zero) for i in eindices]
nshape = [len(el) for i, el in enumerate(sl_factors) if isinstance(index[i], slice)]
return type(self)(array, nshape)
else:
index = self._parse_index(index)
return self._sparse_array.get(index, S.Zero)
@classmethod
def zeros(cls, *shape):
"""
Return a sparse N-dim array of zeros.
"""
return cls({}, shape)
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 reshape(self, *newshape):
new_total_size = functools.reduce(lambda x,y: x*y, newshape)
if new_total_size != self._loop_size:
raise ValueError("Invalid reshape parameters " + newshape)
return type(self)(self._sparse_array, newshape)
class ImmutableSparseNDimArray(SparseNDimArray, ImmutableNDimArray): # type: ignore
def __new__(cls, iterable=None, shape=None, **kwargs):
shape, flat_list = cls._handle_ndarray_creation_inputs(iterable, shape, **kwargs)
shape = Tuple(*map(_sympify, shape))
cls._check_special_bounds(flat_list, shape)
loop_size = functools.reduce(lambda x,y: x*y, shape) if shape else len(flat_list)
# Sparse array:
if isinstance(flat_list, (dict, Dict)):
sparse_array = Dict(flat_list)
else:
sparse_array = {}
for i, el in enumerate(flatten(flat_list)):
if el != 0:
sparse_array[i] = _sympify(el)
sparse_array = Dict(sparse_array)
self = Basic.__new__(cls, sparse_array, shape, **kwargs)
self._shape = shape
self._rank = len(shape)
self._loop_size = loop_size
self._sparse_array = sparse_array
return self
def __setitem__(self, index, value):
raise TypeError("immutable N-dim array")
def as_mutable(self):
return MutableSparseNDimArray(self)
class MutableSparseNDimArray(MutableNDimArray, SparseNDimArray):
def __new__(cls, iterable=None, shape=None, **kwargs):
shape, flat_list = cls._handle_ndarray_creation_inputs(iterable, shape, **kwargs)
self = object.__new__(cls)
self._shape = shape
self._rank = len(shape)
self._loop_size = functools.reduce(lambda x,y: x*y, shape) if shape else len(flat_list)
# Sparse array:
if isinstance(flat_list, (dict, Dict)):
self._sparse_array = dict(flat_list)
return self
self._sparse_array = {}
for i, el in enumerate(flatten(flat_list)):
if el != 0:
self._sparse_array[i] = _sympify(el)
return self
def __setitem__(self, index, value):
"""Allows to set items to MutableDenseNDimArray.
Examples
========
>>> from sympy import MutableSparseNDimArray
>>> a = MutableSparseNDimArray.zeros(2, 2)
>>> a[0, 0] = 1
>>> a[1, 1] = 1
>>> a
[[1, 0], [0, 1]]
"""
if isinstance(index, tuple) and any(isinstance(i, slice) for i in index):
value, eindices, slice_offsets = self._get_slice_data_for_array_assignment(index, value)
for i in eindices:
other_i = [ind - j for ind, j in zip(i, slice_offsets) if j is not None]
other_value = value[other_i]
complete_index = self._parse_index(i)
if other_value != 0:
self._sparse_array[complete_index] = other_value
elif complete_index in self._sparse_array:
self._sparse_array.pop(complete_index)
else:
index = self._parse_index(index)
value = _sympify(value)
if value == 0 and index in self._sparse_array:
self._sparse_array.pop(index)
else:
self._sparse_array[index] = value
def as_immutable(self):
return ImmutableSparseNDimArray(self)
@property
def free_symbols(self):
return {i for j in self._sparse_array.values() for i in j.free_symbols}
|
7ce3c9cb0bd24472a70a4dff40dcd7bca11646177baf25f8bf35eac65341f32b | from sympy.core.basic import Basic
from sympy.core.containers import (Dict, Tuple)
from sympy.core.expr import Expr
from sympy.core.kind import Kind, NumberKind, UndefinedKind
from sympy.core.numbers import Integer
from sympy.core.singleton import S
from sympy.core.sympify import sympify
from sympy.external.gmpy import SYMPY_INTS
from sympy.printing.defaults import Printable
import itertools
from collections.abc import Iterable
class ArrayKind(Kind):
"""
Kind for N-dimensional array in SymPy.
This kind represents the multidimensional array that algebraic
operations are defined. Basic class for this kind is ``NDimArray``,
but any expression representing the array can have this.
Parameters
==========
element_kind : Kind
Kind of the element. Default is :obj:NumberKind `<sympy.core.kind.NumberKind>`,
which means that the array contains only numbers.
Examples
========
Any instance of array class has ``ArrayKind``.
>>> from sympy import NDimArray
>>> NDimArray([1,2,3]).kind
ArrayKind(NumberKind)
Although expressions representing an array may be not instance of
array class, it will have ``ArrayKind`` as well.
>>> from sympy import Integral
>>> from sympy.tensor.array import NDimArray
>>> from sympy.abc import x
>>> intA = Integral(NDimArray([1,2,3]), x)
>>> isinstance(intA, NDimArray)
False
>>> intA.kind
ArrayKind(NumberKind)
Use ``isinstance()`` to check for ``ArrayKind` without specifying
the element kind. Use ``is`` with specifying the element kind.
>>> from sympy.tensor.array import ArrayKind
>>> from sympy.core import NumberKind
>>> boolA = NDimArray([True, False])
>>> isinstance(boolA.kind, ArrayKind)
True
>>> boolA.kind is ArrayKind(NumberKind)
False
See Also
========
shape : Function to return the shape of objects with ``MatrixKind``.
"""
def __new__(cls, element_kind=NumberKind):
obj = super().__new__(cls, element_kind)
obj.element_kind = element_kind
return obj
def __repr__(self):
return "ArrayKind(%s)" % self.element_kind
@classmethod
def _union(cls, kinds) -> 'ArrayKind':
elem_kinds = set(e.kind for e in kinds)
if len(elem_kinds) == 1:
elemkind, = elem_kinds
else:
elemkind = UndefinedKind
return ArrayKind(elemkind)
class NDimArray(Printable):
"""
Examples
========
Create an N-dim array of zeros:
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray.zeros(2, 3, 4)
>>> a
[[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]]
Create an N-dim array from a list;
>>> a = MutableDenseNDimArray([[2, 3], [4, 5]])
>>> a
[[2, 3], [4, 5]]
>>> b = MutableDenseNDimArray([[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]]])
>>> b
[[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]]]
Create an N-dim array from a flat list with dimension shape:
>>> a = MutableDenseNDimArray([1, 2, 3, 4, 5, 6], (2, 3))
>>> a
[[1, 2, 3], [4, 5, 6]]
Create an N-dim array from a matrix:
>>> from sympy import Matrix
>>> a = Matrix([[1,2],[3,4]])
>>> a
Matrix([
[1, 2],
[3, 4]])
>>> b = MutableDenseNDimArray(a)
>>> b
[[1, 2], [3, 4]]
Arithmetic operations on N-dim arrays
>>> a = MutableDenseNDimArray([1, 1, 1, 1], (2, 2))
>>> b = MutableDenseNDimArray([4, 4, 4, 4], (2, 2))
>>> c = a + b
>>> c
[[5, 5], [5, 5]]
>>> a - b
[[-3, -3], [-3, -3]]
"""
_diff_wrt = True
is_scalar = False
def __new__(cls, iterable, shape=None, **kwargs):
from sympy.tensor.array import ImmutableDenseNDimArray
return ImmutableDenseNDimArray(iterable, shape, **kwargs)
def _parse_index(self, index):
if isinstance(index, (SYMPY_INTS, Integer)):
raise ValueError("Only a tuple index is accepted")
if self._loop_size == 0:
raise ValueError("Index not valide with an empty array")
if len(index) != self._rank:
raise ValueError('Wrong number of array axes')
real_index = 0
# check if input index can exist in current indexing
for i in range(self._rank):
if (index[i] >= self.shape[i]) or (index[i] < -self.shape[i]):
raise ValueError('Index ' + str(index) + ' out of border')
if index[i] < 0:
real_index += 1
real_index = real_index*self.shape[i] + index[i]
return real_index
def _get_tuple_index(self, integer_index):
index = []
for i, sh in enumerate(reversed(self.shape)):
index.append(integer_index % sh)
integer_index //= sh
index.reverse()
return tuple(index)
def _check_symbolic_index(self, index):
# Check if any index is symbolic:
tuple_index = (index if isinstance(index, tuple) else (index,))
if any((isinstance(i, Expr) and (not i.is_number)) for i in tuple_index):
for i, nth_dim in zip(tuple_index, self.shape):
if ((i < 0) == True) or ((i >= nth_dim) == True):
raise ValueError("index out of range")
from sympy.tensor import Indexed
return Indexed(self, *tuple_index)
return None
def _setter_iterable_check(self, value):
from sympy.matrices.matrices import MatrixBase
if isinstance(value, (Iterable, MatrixBase, NDimArray)):
raise NotImplementedError
@classmethod
def _scan_iterable_shape(cls, iterable):
def f(pointer):
if not isinstance(pointer, Iterable):
return [pointer], ()
result = []
elems, shapes = zip(*[f(i) for i in pointer])
if len(set(shapes)) != 1:
raise ValueError("could not determine shape unambiguously")
for i in elems:
result.extend(i)
return result, (len(shapes),)+shapes[0]
return f(iterable)
@classmethod
def _handle_ndarray_creation_inputs(cls, iterable=None, shape=None, **kwargs):
from sympy.matrices.matrices import MatrixBase
from sympy.tensor.array import SparseNDimArray
if shape is None:
if iterable is None:
shape = ()
iterable = ()
# Construction of a sparse array from a sparse array
elif isinstance(iterable, SparseNDimArray):
return iterable._shape, iterable._sparse_array
# Construct N-dim array from another N-dim array:
elif isinstance(iterable, NDimArray):
shape = iterable.shape
# Construct N-dim array from an iterable (numpy arrays included):
elif isinstance(iterable, Iterable):
iterable, shape = cls._scan_iterable_shape(iterable)
# Construct N-dim array from a Matrix:
elif isinstance(iterable, MatrixBase):
shape = iterable.shape
else:
shape = ()
iterable = (iterable,)
if isinstance(iterable, (Dict, dict)) and shape is not None:
new_dict = iterable.copy()
for k, v in new_dict.items():
if isinstance(k, (tuple, Tuple)):
new_key = 0
for i, idx in enumerate(k):
new_key = new_key * shape[i] + idx
iterable[new_key] = iterable[k]
del iterable[k]
if isinstance(shape, (SYMPY_INTS, Integer)):
shape = (shape,)
if not all(isinstance(dim, (SYMPY_INTS, Integer)) for dim in shape):
raise TypeError("Shape should contain integers only.")
return tuple(shape), iterable
def __len__(self):
"""Overload common function len(). Returns number of elements in array.
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray.zeros(3, 3)
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> len(a)
9
"""
return self._loop_size
@property
def shape(self):
"""
Returns array shape (dimension).
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray.zeros(3, 3)
>>> a.shape
(3, 3)
"""
return self._shape
def rank(self):
"""
Returns rank of array.
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray.zeros(3,4,5,6,3)
>>> a.rank()
5
"""
return self._rank
def diff(self, *args, **kwargs):
"""
Calculate the derivative of each element in the array.
Examples
========
>>> from sympy import ImmutableDenseNDimArray
>>> from sympy.abc import x, y
>>> M = ImmutableDenseNDimArray([[x, y], [1, x*y]])
>>> M.diff(x)
[[1, 0], [0, y]]
"""
from sympy.tensor.array.array_derivatives import ArrayDerivative
kwargs.setdefault('evaluate', True)
return ArrayDerivative(self.as_immutable(), *args, **kwargs)
def _eval_derivative(self, base):
# Types are (base: scalar, self: array)
return self.applyfunc(lambda x: base.diff(x))
def _eval_derivative_n_times(self, s, n):
return Basic._eval_derivative_n_times(self, s, n)
def applyfunc(self, f):
"""Apply a function to each element of the N-dim array.
Examples
========
>>> from sympy import ImmutableDenseNDimArray
>>> m = ImmutableDenseNDimArray([i*2+j for i in range(2) for j in range(2)], (2, 2))
>>> m
[[0, 1], [2, 3]]
>>> m.applyfunc(lambda i: 2*i)
[[0, 2], [4, 6]]
"""
from sympy.tensor.array import SparseNDimArray
from sympy.tensor.array.arrayop import Flatten
if isinstance(self, SparseNDimArray) and f(S.Zero) == 0:
return type(self)({k: f(v) for k, v in self._sparse_array.items() if f(v) != 0}, self.shape)
return type(self)(map(f, Flatten(self)), self.shape)
def _sympystr(self, printer):
def f(sh, shape_left, i, j):
if len(shape_left) == 1:
return "["+", ".join([printer._print(self[self._get_tuple_index(e)]) for e in range(i, j)])+"]"
sh //= shape_left[0]
return "[" + ", ".join([f(sh, shape_left[1:], i+e*sh, i+(e+1)*sh) for e in range(shape_left[0])]) + "]" # + "\n"*len(shape_left)
if self.rank() == 0:
return printer._print(self[()])
return f(self._loop_size, self.shape, 0, self._loop_size)
def tolist(self):
"""
Converting MutableDenseNDimArray to one-dim list
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray([1, 2, 3, 4], (2, 2))
>>> a
[[1, 2], [3, 4]]
>>> b = a.tolist()
>>> b
[[1, 2], [3, 4]]
"""
def f(sh, shape_left, i, j):
if len(shape_left) == 1:
return [self[self._get_tuple_index(e)] for e in range(i, j)]
result = []
sh //= shape_left[0]
for e in range(shape_left[0]):
result.append(f(sh, shape_left[1:], i+e*sh, i+(e+1)*sh))
return result
return f(self._loop_size, self.shape, 0, self._loop_size)
def __add__(self, other):
from sympy.tensor.array.arrayop import Flatten
if not isinstance(other, NDimArray):
return NotImplemented
if self.shape != other.shape:
raise ValueError("array shape mismatch")
result_list = [i+j for i,j in zip(Flatten(self), Flatten(other))]
return type(self)(result_list, self.shape)
def __sub__(self, other):
from sympy.tensor.array.arrayop import Flatten
if not isinstance(other, NDimArray):
return NotImplemented
if self.shape != other.shape:
raise ValueError("array shape mismatch")
result_list = [i-j for i,j in zip(Flatten(self), Flatten(other))]
return type(self)(result_list, self.shape)
def __mul__(self, other):
from sympy.matrices.matrices import MatrixBase
from sympy.tensor.array import SparseNDimArray
from sympy.tensor.array.arrayop import Flatten
if isinstance(other, (Iterable, NDimArray, MatrixBase)):
raise ValueError("scalar expected, use tensorproduct(...) for tensorial product")
other = sympify(other)
if isinstance(self, SparseNDimArray):
if other.is_zero:
return type(self)({}, self.shape)
return type(self)({k: other*v for (k, v) in self._sparse_array.items()}, self.shape)
result_list = [i*other for i in Flatten(self)]
return type(self)(result_list, self.shape)
def __rmul__(self, other):
from sympy.matrices.matrices import MatrixBase
from sympy.tensor.array import SparseNDimArray
from sympy.tensor.array.arrayop import Flatten
if isinstance(other, (Iterable, NDimArray, MatrixBase)):
raise ValueError("scalar expected, use tensorproduct(...) for tensorial product")
other = sympify(other)
if isinstance(self, SparseNDimArray):
if other.is_zero:
return type(self)({}, self.shape)
return type(self)({k: other*v for (k, v) in self._sparse_array.items()}, self.shape)
result_list = [other*i for i in Flatten(self)]
return type(self)(result_list, self.shape)
def __truediv__(self, other):
from sympy.matrices.matrices import MatrixBase
from sympy.tensor.array import SparseNDimArray
from sympy.tensor.array.arrayop import Flatten
if isinstance(other, (Iterable, NDimArray, MatrixBase)):
raise ValueError("scalar expected")
other = sympify(other)
if isinstance(self, SparseNDimArray) and other != S.Zero:
return type(self)({k: v/other for (k, v) in self._sparse_array.items()}, self.shape)
result_list = [i/other for i in Flatten(self)]
return type(self)(result_list, self.shape)
def __rtruediv__(self, other):
raise NotImplementedError('unsupported operation on NDimArray')
def __neg__(self):
from sympy.tensor.array import SparseNDimArray
from sympy.tensor.array.arrayop import Flatten
if isinstance(self, SparseNDimArray):
return type(self)({k: -v for (k, v) in self._sparse_array.items()}, self.shape)
result_list = [-i for i in Flatten(self)]
return type(self)(result_list, self.shape)
def __iter__(self):
def iterator():
if self._shape:
for i in range(self._shape[0]):
yield self[i]
else:
yield self[()]
return iterator()
def __eq__(self, other):
"""
NDimArray instances can be compared to each other.
Instances equal if they have same shape and data.
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray.zeros(2, 3)
>>> b = MutableDenseNDimArray.zeros(2, 3)
>>> a == b
True
>>> c = a.reshape(3, 2)
>>> c == b
False
>>> a[0,0] = 1
>>> b[0,0] = 2
>>> a == b
False
"""
from sympy.tensor.array import SparseNDimArray
if not isinstance(other, NDimArray):
return False
if not self.shape == other.shape:
return False
if isinstance(self, SparseNDimArray) and isinstance(other, SparseNDimArray):
return dict(self._sparse_array) == dict(other._sparse_array)
return list(self) == list(other)
def __ne__(self, other):
return not self == other
def _eval_transpose(self):
if self.rank() != 2:
raise ValueError("array rank not 2")
from .arrayop import permutedims
return permutedims(self, (1, 0))
def transpose(self):
return self._eval_transpose()
def _eval_conjugate(self):
from sympy.tensor.array.arrayop import Flatten
return self.func([i.conjugate() for i in Flatten(self)], self.shape)
def conjugate(self):
return self._eval_conjugate()
def _eval_adjoint(self):
return self.transpose().conjugate()
def adjoint(self):
return self._eval_adjoint()
def _slice_expand(self, s, dim):
if not isinstance(s, slice):
return (s,)
start, stop, step = s.indices(dim)
return [start + i*step for i in range((stop-start)//step)]
def _get_slice_data_for_array_access(self, index):
sl_factors = [self._slice_expand(i, dim) for (i, dim) in zip(index, self.shape)]
eindices = itertools.product(*sl_factors)
return sl_factors, eindices
def _get_slice_data_for_array_assignment(self, index, value):
if not isinstance(value, NDimArray):
value = type(self)(value)
sl_factors, eindices = self._get_slice_data_for_array_access(index)
slice_offsets = [min(i) if isinstance(i, list) else None for i in sl_factors]
# TODO: add checks for dimensions for `value`?
return value, eindices, slice_offsets
@classmethod
def _check_special_bounds(cls, flat_list, shape):
if shape == () and len(flat_list) != 1:
raise ValueError("arrays without shape need one scalar value")
if shape == (0,) and len(flat_list) > 0:
raise ValueError("if array shape is (0,) there cannot be elements")
def _check_index_for_getitem(self, index):
if isinstance(index, (SYMPY_INTS, Integer, slice)):
index = (index, )
if len(index) < self.rank():
index = tuple([i for i in index] + \
[slice(None) for i in range(len(index), self.rank())])
if len(index) > self.rank():
raise ValueError('Dimension of index greater than rank of array')
return index
class ImmutableNDimArray(NDimArray, Basic):
_op_priority = 11.0
def __hash__(self):
return Basic.__hash__(self)
def as_immutable(self):
return self
def as_mutable(self):
raise NotImplementedError("abstract method")
|
8b489ed80b9d527d5ddea1e38ebdff4976d901f40e444e12eb46d9404b3f53f1 | import functools
from typing import List
from sympy.core.basic import Basic
from sympy.core.containers import Tuple
from sympy.core.singleton import S
from sympy.core.sympify import _sympify
from sympy.simplify.simplify import simplify
from sympy.tensor.array.mutable_ndim_array import MutableNDimArray
from sympy.tensor.array.ndim_array import NDimArray, ImmutableNDimArray, ArrayKind
from sympy.utilities.iterables import flatten
class DenseNDimArray(NDimArray):
_array: List[Basic]
def __new__(self, *args, **kwargs):
return ImmutableDenseNDimArray(*args, **kwargs)
@property
def kind(self) -> ArrayKind:
return ArrayKind._union(self._array)
def __getitem__(self, index):
"""
Allows to get items from N-dim array.
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray([0, 1, 2, 3], (2, 2))
>>> a
[[0, 1], [2, 3]]
>>> a[0, 0]
0
>>> a[1, 1]
3
>>> a[0]
[0, 1]
>>> a[1]
[2, 3]
Symbolic index:
>>> from sympy.abc import i, j
>>> a[i, j]
[[0, 1], [2, 3]][i, j]
Replace `i` and `j` to get element `(1, 1)`:
>>> a[i, j].subs({i: 1, j: 1})
3
"""
syindex = self._check_symbolic_index(index)
if syindex is not None:
return syindex
index = self._check_index_for_getitem(index)
if isinstance(index, tuple) and any(isinstance(i, slice) for i in index):
sl_factors, eindices = self._get_slice_data_for_array_access(index)
array = [self._array[self._parse_index(i)] for i in eindices]
nshape = [len(el) for i, el in enumerate(sl_factors) if isinstance(index[i], slice)]
return type(self)(array, nshape)
else:
index = self._parse_index(index)
return self._array[index]
@classmethod
def zeros(cls, *shape):
list_length = functools.reduce(lambda x, y: x*y, shape, S.One)
return cls._new(([0]*list_length,), shape)
def tomatrix(self):
"""
Converts MutableDenseNDimArray to Matrix. Can convert only 2-dim array, else will raise error.
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray([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 Matrix
if self.rank() != 2:
raise ValueError('Dimensions must be of size of 2')
return Matrix(self.shape[0], self.shape[1], self._array)
def reshape(self, *newshape):
"""
Returns MutableDenseNDimArray instance with new shape. Elements number
must be suitable to new shape. The only argument of method sets
new shape.
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray([1, 2, 3, 4, 5, 6], (2, 3))
>>> a.shape
(2, 3)
>>> a
[[1, 2, 3], [4, 5, 6]]
>>> b = a.reshape(3, 2)
>>> b.shape
(3, 2)
>>> b
[[1, 2], [3, 4], [5, 6]]
"""
new_total_size = functools.reduce(lambda x,y: x*y, newshape)
if new_total_size != self._loop_size:
raise ValueError("Invalid reshape parameters " + newshape)
# there is no `.func` as this class does not subtype `Basic`:
return type(self)(self._array, newshape)
class ImmutableDenseNDimArray(DenseNDimArray, ImmutableNDimArray): # type: ignore
"""
"""
def __new__(cls, iterable, shape=None, **kwargs):
return cls._new(iterable, shape, **kwargs)
@classmethod
def _new(cls, iterable, shape, **kwargs):
shape, flat_list = cls._handle_ndarray_creation_inputs(iterable, shape, **kwargs)
shape = Tuple(*map(_sympify, shape))
cls._check_special_bounds(flat_list, shape)
flat_list = flatten(flat_list)
flat_list = Tuple(*flat_list)
self = Basic.__new__(cls, flat_list, shape, **kwargs)
self._shape = shape
self._array = list(flat_list)
self._rank = len(shape)
self._loop_size = functools.reduce(lambda x,y: x*y, shape, 1)
return self
def __setitem__(self, index, value):
raise TypeError('immutable N-dim array')
def as_mutable(self):
return MutableDenseNDimArray(self)
def _eval_simplify(self, **kwargs):
return self.applyfunc(simplify)
class MutableDenseNDimArray(DenseNDimArray, MutableNDimArray):
def __new__(cls, iterable=None, shape=None, **kwargs):
return cls._new(iterable, shape, **kwargs)
@classmethod
def _new(cls, iterable, shape, **kwargs):
shape, flat_list = cls._handle_ndarray_creation_inputs(iterable, shape, **kwargs)
flat_list = flatten(flat_list)
self = object.__new__(cls)
self._shape = shape
self._array = list(flat_list)
self._rank = len(shape)
self._loop_size = functools.reduce(lambda x,y: x*y, shape) if shape else len(flat_list)
return self
def __setitem__(self, index, value):
"""Allows to set items to MutableDenseNDimArray.
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray.zeros(2, 2)
>>> a[0,0] = 1
>>> a[1,1] = 1
>>> a
[[1, 0], [0, 1]]
"""
if isinstance(index, tuple) and any(isinstance(i, slice) for i in index):
value, eindices, slice_offsets = self._get_slice_data_for_array_assignment(index, value)
for i in eindices:
other_i = [ind - j for ind, j in zip(i, slice_offsets) if j is not None]
self._array[self._parse_index(i)] = value[other_i]
else:
index = self._parse_index(index)
self._setter_iterable_check(value)
value = _sympify(value)
self._array[index] = value
def as_immutable(self):
return ImmutableDenseNDimArray(self)
@property
def free_symbols(self):
return {i for j in self._array for i in j.free_symbols}
|
e5aab7e13327224ffc4ec4b4b530411c5de39f07d0941e0ce09501cd29eb8fba | from sympy.tensor.functions import TensorProduct
from sympy.matrices.dense import Matrix
from sympy.matrices.expressions.matexpr import MatrixSymbol
from sympy.tensor.array import Array
from sympy.abc import x, y, z
from sympy.abc import i, j, k, l
A = MatrixSymbol("A", 3, 3)
B = MatrixSymbol("B", 3, 3)
C = MatrixSymbol("C", 3, 3)
def test_TensorProduct_construction():
assert TensorProduct(3, 4) == 12
assert isinstance(TensorProduct(A, A), TensorProduct)
expr = TensorProduct(TensorProduct(x, y), z)
assert expr == x*y*z
expr = TensorProduct(TensorProduct(A, B), C)
assert expr == TensorProduct(A, B, C)
expr = TensorProduct(Matrix.eye(2), [[0, -1], [1, 0]])
assert expr == Array([
[
[[0, -1], [1, 0]],
[[0, 0], [0, 0]]
],
[
[[0, 0], [0, 0]],
[[0, -1], [1, 0]]
]
])
def test_TensorProduct_shape():
expr = TensorProduct(3, 4, evaluate=False)
assert expr.shape == ()
assert expr.rank() == 0
expr = TensorProduct([1, 2], [x, y], evaluate=False)
assert expr.shape == (2, 2)
assert expr.rank() == 2
expr = TensorProduct(expr, expr, evaluate=False)
assert expr.shape == (2, 2, 2, 2)
assert expr.rank() == 4
expr = TensorProduct(Matrix.eye(2), [[0, -1], [1, 0]], evaluate=False)
assert expr.shape == (2, 2, 2, 2)
assert expr.rank() == 4
def test_TensorProduct_getitem():
expr = TensorProduct(A, B)
assert expr[i, j, k, l] == A[i, j]*B[k, l]
|
1b7abbd10c3d6a327ceee90ae9e206db704994a89b390f92c0f2aa721ca39d7e | from sympy.testing.pytest import raises
from sympy.tensor.toperators import PartialDerivative
from sympy.tensor.tensor import (TensorIndexType,
tensor_indices,
TensorHead, tensor_heads)
from sympy.core.numbers import Rational
from sympy.core.symbol import symbols
from sympy.matrices.dense import diag
from sympy.tensor.array import Array
from random import randint
L = TensorIndexType("L")
i, j, k, m, m1, m2, m3, m4 = tensor_indices("i j k m m1 m2 m3 m4", L)
i0 = tensor_indices("i0", L)
L_0, L_1 = tensor_indices("L_0 L_1", L)
A, B, C, D = tensor_heads("A B C D", [L])
H = TensorHead("H", [L, L])
def test_invalid_partial_derivative_valence():
raises(ValueError, lambda: PartialDerivative(C(j), D(-j)))
raises(ValueError, lambda: PartialDerivative(C(-j), D(j)))
def test_tensor_partial_deriv():
# Test flatten:
expr = PartialDerivative(PartialDerivative(A(i), A(j)), A(i))
assert expr.expr == A(L_0)
assert expr.variables == (A(j), A(L_0))
expr1 = PartialDerivative(A(i), A(j))
assert expr1.expr == A(i)
assert expr1.variables == (A(j),)
expr2 = A(i)*PartialDerivative(H(k, -i), A(j))
assert expr2.get_indices() == [L_0, k, -L_0, -j]
expr2b = A(i)*PartialDerivative(H(k, -i), A(-j))
assert expr2b.get_indices() == [L_0, k, -L_0, j]
expr3 = A(i)*PartialDerivative(B(k)*C(-i) + 3*H(k, -i), A(j))
assert expr3.get_indices() == [L_0, k, -L_0, -j]
expr4 = (A(i) + B(i))*PartialDerivative(C(j), D(j))
assert expr4.get_indices() == [i, L_0, -L_0]
expr4b = (A(i) + B(i))*PartialDerivative(C(-j), D(-j))
assert expr4b.get_indices() == [i, -L_0, L_0]
expr5 = (A(i) + B(i))*PartialDerivative(C(-i), D(j))
assert expr5.get_indices() == [L_0, -L_0, -j]
def test_replace_arrays_partial_derivative():
x, y, z, t = symbols("x y z t")
# d(A^i)/d(A_j) = d(g^ik A_k)/d(A_j) = g^ik delta_jk
expr = PartialDerivative(A(i), A(-j))
assert expr.get_free_indices() == [i, j]
assert expr.get_indices() == [i, j]
assert expr.replace_with_arrays({A(i): [x, y], L: diag(1, 1)}, [i, j]) == Array([[1, 0], [0, 1]])
assert expr.replace_with_arrays({A(i): [x, y], L: diag(1, -1)}, [i, j]) == Array([[1, 0], [0, -1]])
assert expr.replace_with_arrays({A(-i): [x, y], L: diag(1, 1)}, [i, j]) == Array([[1, 0], [0, 1]])
assert expr.replace_with_arrays({A(-i): [x, y], L: diag(1, -1)}, [i, j]) == Array([[1, 0], [0, -1]])
expr = PartialDerivative(A(i), A(j))
assert expr.get_free_indices() == [i, -j]
assert expr.get_indices() == [i, -j]
assert expr.replace_with_arrays({A(i): [x, y]}, [i, -j]) == Array([[1, 0], [0, 1]])
assert expr.replace_with_arrays({A(i): [x, y], L: diag(1, 1)}, [i, -j]) == Array([[1, 0], [0, 1]])
assert expr.replace_with_arrays({A(i): [x, y], L: diag(1, -1)}, [i, -j]) == Array([[1, 0], [0, 1]])
assert expr.replace_with_arrays({A(-i): [x, y], L: diag(1, 1)}, [i, -j]) == Array([[1, 0], [0, 1]])
assert expr.replace_with_arrays({A(-i): [x, y], L: diag(1, -1)}, [i, -j]) == Array([[1, 0], [0, 1]])
expr = PartialDerivative(A(-i), A(-j))
expr.get_free_indices() == [-i, j]
expr.get_indices() == [-i, j]
assert expr.replace_with_arrays({A(-i): [x, y]}, [-i, j]) == Array([[1, 0], [0, 1]])
assert expr.replace_with_arrays({A(-i): [x, y], L: diag(1, 1)}, [-i, j]) == Array([[1, 0], [0, 1]])
assert expr.replace_with_arrays({A(-i): [x, y], L: diag(1, -1)}, [-i, j]) == Array([[1, 0], [0, 1]])
assert expr.replace_with_arrays({A(i): [x, y], L: diag(1, 1)}, [-i, j]) == Array([[1, 0], [0, 1]])
assert expr.replace_with_arrays({A(i): [x, y], L: diag(1, -1)}, [-i, j]) == Array([[1, 0], [0, 1]])
expr = PartialDerivative(A(i), A(i))
assert expr.get_free_indices() == []
assert expr.get_indices() == [L_0, -L_0]
assert expr.replace_with_arrays({A(i): [x, y], L: diag(1, 1)}, []) == 2
assert expr.replace_with_arrays({A(i): [x, y], L: diag(1, -1)}, []) == 2
expr = PartialDerivative(A(-i), A(-i))
assert expr.get_free_indices() == []
assert expr.get_indices() == [-L_0, L_0]
assert expr.replace_with_arrays({A(i): [x, y], L: diag(1, 1)}, []) == 2
assert expr.replace_with_arrays({A(i): [x, y], L: diag(1, -1)}, []) == 2
expr = PartialDerivative(H(i, j) + H(j, i), A(i))
assert expr.get_indices() == [L_0, j, -L_0]
assert expr.get_free_indices() == [j]
expr = PartialDerivative(H(i, j) + H(j, i), A(k))*B(-i)
assert expr.get_indices() == [L_0, j, -k, -L_0]
assert expr.get_free_indices() == [j, -k]
expr = PartialDerivative(A(i)*(H(-i, j) + H(j, -i)), A(j))
assert expr.get_indices() == [L_0, -L_0, L_1, -L_1]
assert expr.get_free_indices() == []
expr = A(j)*A(-j) + expr
assert expr.get_indices() == [L_0, -L_0, L_1, -L_1]
assert expr.get_free_indices() == []
expr = A(i)*(B(j)*PartialDerivative(C(-j), D(i)) + C(j)*PartialDerivative(D(-j), B(i)))
assert expr.get_indices() == [L_0, L_1, -L_1, -L_0]
assert expr.get_free_indices() == []
expr = A(i)*PartialDerivative(C(-j), D(i))
assert expr.get_indices() == [L_0, -j, -L_0]
assert expr.get_free_indices() == [-j]
def test_expand_partial_derivative_sum_rule():
tau = symbols("tau")
# check sum rule for D(tensor, symbol)
expr1aa = PartialDerivative(A(i), tau)
assert expr1aa._expand_partial_derivative() == PartialDerivative(A(i), tau)
expr1ab = PartialDerivative(A(i) + B(i), tau)
assert (expr1ab._expand_partial_derivative() ==
PartialDerivative(A(i), tau) +
PartialDerivative(B(i), tau))
expr1ac = PartialDerivative(A(i) + B(i) + C(i), tau)
assert (expr1ac._expand_partial_derivative() ==
PartialDerivative(A(i), tau) +
PartialDerivative(B(i), tau) +
PartialDerivative(C(i), tau))
# check sum rule for D(tensor, D(j))
expr1ba = PartialDerivative(A(i), D(j))
assert expr1ba._expand_partial_derivative() ==\
PartialDerivative(A(i), D(j))
expr1bb = PartialDerivative(A(i) + B(i), D(j))
assert (expr1bb._expand_partial_derivative() ==
PartialDerivative(A(i), D(j)) +
PartialDerivative(B(i), D(j)))
expr1bc = PartialDerivative(A(i) + B(i) + C(i), D(j))
assert expr1bc._expand_partial_derivative() ==\
PartialDerivative(A(i), D(j))\
+ PartialDerivative(B(i), D(j))\
+ PartialDerivative(C(i), D(j))
# check sum rule for D(tensor, H(j, k))
expr1ca = PartialDerivative(A(i), H(j, k))
assert expr1ca._expand_partial_derivative() ==\
PartialDerivative(A(i), H(j, k))
expr1cb = PartialDerivative(A(i) + B(i), H(j, k))
assert (expr1cb._expand_partial_derivative() ==
PartialDerivative(A(i), H(j, k))
+ PartialDerivative(B(i), H(j, k)))
expr1cc = PartialDerivative(A(i) + B(i) + C(i), H(j, k))
assert (expr1cc._expand_partial_derivative() ==
PartialDerivative(A(i), H(j, k))
+ PartialDerivative(B(i), H(j, k))
+ PartialDerivative(C(i), H(j, k)))
# check sum rule for D(D(tensor, D(j)), H(k, m))
expr1da = PartialDerivative(A(i), (D(j), H(k, m)))
assert expr1da._expand_partial_derivative() ==\
PartialDerivative(A(i), (D(j), H(k, m)))
expr1db = PartialDerivative(A(i) + B(i), (D(j), H(k, m)))
assert expr1db._expand_partial_derivative() ==\
PartialDerivative(A(i), (D(j), H(k, m)))\
+ PartialDerivative(B(i), (D(j), H(k, m)))
expr1dc = PartialDerivative(A(i) + B(i) + C(i), (D(j), H(k, m)))
assert expr1dc._expand_partial_derivative() ==\
PartialDerivative(A(i), (D(j), H(k, m)))\
+ PartialDerivative(B(i), (D(j), H(k, m)))\
+ PartialDerivative(C(i), (D(j), H(k, m)))
def test_expand_partial_derivative_constant_factor_rule():
nneg = randint(0, 1000)
pos = randint(1, 1000)
neg = -randint(1, 1000)
c1 = Rational(nneg, pos)
c2 = Rational(neg, pos)
c3 = Rational(nneg, neg)
expr2a = PartialDerivative(nneg*A(i), D(j))
assert expr2a._expand_partial_derivative() ==\
nneg*PartialDerivative(A(i), D(j))
expr2b = PartialDerivative(neg*A(i), D(j))
assert expr2b._expand_partial_derivative() ==\
neg*PartialDerivative(A(i), D(j))
expr2ca = PartialDerivative(c1*A(i), D(j))
assert expr2ca._expand_partial_derivative() ==\
c1*PartialDerivative(A(i), D(j))
expr2cb = PartialDerivative(c2*A(i), D(j))
assert expr2cb._expand_partial_derivative() ==\
c2*PartialDerivative(A(i), D(j))
expr2cc = PartialDerivative(c3*A(i), D(j))
assert expr2cc._expand_partial_derivative() ==\
c3*PartialDerivative(A(i), D(j))
def test_expand_partial_derivative_full_linearity():
nneg = randint(0, 1000)
pos = randint(1, 1000)
neg = -randint(1, 1000)
c1 = Rational(nneg, pos)
c2 = Rational(neg, pos)
c3 = Rational(nneg, neg)
# check full linearity
p = PartialDerivative(42, D(j))
assert p and not p._expand_partial_derivative()
expr3a = PartialDerivative(nneg*A(i) + pos*B(i), D(j))
assert expr3a._expand_partial_derivative() ==\
nneg*PartialDerivative(A(i), D(j))\
+ pos*PartialDerivative(B(i), D(j))
expr3b = PartialDerivative(nneg*A(i) + neg*B(i), D(j))
assert expr3b._expand_partial_derivative() ==\
nneg*PartialDerivative(A(i), D(j))\
+ neg*PartialDerivative(B(i), D(j))
expr3c = PartialDerivative(neg*A(i) + pos*B(i), D(j))
assert expr3c._expand_partial_derivative() ==\
neg*PartialDerivative(A(i), D(j))\
+ pos*PartialDerivative(B(i), D(j))
expr3d = PartialDerivative(c1*A(i) + c2*B(i), D(j))
assert expr3d._expand_partial_derivative() ==\
c1*PartialDerivative(A(i), D(j))\
+ c2*PartialDerivative(B(i), D(j))
expr3e = PartialDerivative(c2*A(i) + c1*B(i), D(j))
assert expr3e._expand_partial_derivative() ==\
c2*PartialDerivative(A(i), D(j))\
+ c1*PartialDerivative(B(i), D(j))
expr3f = PartialDerivative(c2*A(i) + c3*B(i), D(j))
assert expr3f._expand_partial_derivative() ==\
c2*PartialDerivative(A(i), D(j))\
+ c3*PartialDerivative(B(i), D(j))
expr3g = PartialDerivative(c3*A(i) + c2*B(i), D(j))
assert expr3g._expand_partial_derivative() ==\
c3*PartialDerivative(A(i), D(j))\
+ c2*PartialDerivative(B(i), D(j))
expr3h = PartialDerivative(c3*A(i) + c1*B(i), D(j))
assert expr3h._expand_partial_derivative() ==\
c3*PartialDerivative(A(i), D(j))\
+ c1*PartialDerivative(B(i), D(j))
expr3i = PartialDerivative(c1*A(i) + c3*B(i), D(j))
assert expr3i._expand_partial_derivative() ==\
c1*PartialDerivative(A(i), D(j))\
+ c3*PartialDerivative(B(i), D(j))
def test_expand_partial_derivative_product_rule():
# check product rule
expr4a = PartialDerivative(A(i)*B(j), D(k))
assert expr4a._expand_partial_derivative() == \
PartialDerivative(A(i), D(k))*B(j)\
+ A(i)*PartialDerivative(B(j), D(k))
expr4b = PartialDerivative(A(i)*B(j)*C(k), D(m))
assert expr4b._expand_partial_derivative() ==\
PartialDerivative(A(i), D(m))*B(j)*C(k)\
+ A(i)*PartialDerivative(B(j), D(m))*C(k)\
+ A(i)*B(j)*PartialDerivative(C(k), D(m))
expr4c = PartialDerivative(A(i)*B(j), C(k), D(m))
assert expr4c._expand_partial_derivative() ==\
PartialDerivative(A(i), C(k), D(m))*B(j) \
+ PartialDerivative(A(i), C(k))*PartialDerivative(B(j), D(m))\
+ PartialDerivative(A(i), D(m))*PartialDerivative(B(j), C(k))\
+ A(i)*PartialDerivative(B(j), C(k), D(m))
def test_eval_partial_derivative_expr_by_symbol():
tau, alpha = symbols("tau alpha")
expr1 = PartialDerivative(tau**alpha, tau)
assert expr1._perform_derivative() == alpha * 1 / tau * tau ** alpha
expr2 = PartialDerivative(2*tau + 3*tau**4, tau)
assert expr2._perform_derivative() == 2 + 12 * tau ** 3
expr3 = PartialDerivative(2*tau + 3*tau**4, alpha)
assert expr3._perform_derivative() == 0
def test_eval_partial_derivative_single_tensors_by_scalar():
tau, mu = symbols("tau mu")
expr = PartialDerivative(tau**mu, tau)
assert expr._perform_derivative() == mu*tau**mu/tau
expr1a = PartialDerivative(A(i), tau)
assert expr1a._perform_derivative() == 0
expr1b = PartialDerivative(A(-i), tau)
assert expr1b._perform_derivative() == 0
expr2a = PartialDerivative(H(i, j), tau)
assert expr2a._perform_derivative() == 0
expr2b = PartialDerivative(H(i, -j), tau)
assert expr2b._perform_derivative() == 0
expr2c = PartialDerivative(H(-i, j), tau)
assert expr2c._perform_derivative() == 0
expr2d = PartialDerivative(H(-i, -j), tau)
assert expr2d._perform_derivative() == 0
def test_eval_partial_derivative_single_1st_rank_tensors_by_tensor():
expr1 = PartialDerivative(A(i), A(j))
assert expr1._perform_derivative() - L.delta(i, -j) == 0
expr2 = PartialDerivative(A(i), A(-j))
assert expr2._perform_derivative() - L.metric(i, L_0) * L.delta(-L_0, j) == 0
expr3 = PartialDerivative(A(-i), A(-j))
assert expr3._perform_derivative() - L.delta(-i, j) == 0
expr4 = PartialDerivative(A(-i), A(j))
assert expr4._perform_derivative() - L.metric(-i, -L_0) * L.delta(L_0, -j) == 0
expr5 = PartialDerivative(A(i), B(j))
expr6 = PartialDerivative(A(i), C(j))
expr7 = PartialDerivative(A(i), D(j))
expr8 = PartialDerivative(A(i), H(j, k))
assert expr5._perform_derivative() == 0
assert expr6._perform_derivative() == 0
assert expr7._perform_derivative() == 0
assert expr8._perform_derivative() == 0
expr9 = PartialDerivative(A(i), A(i))
assert expr9._perform_derivative() - L.delta(L_0, -L_0) == 0
expr10 = PartialDerivative(A(-i), A(-i))
assert expr10._perform_derivative() - L.delta(-L_0, L_0) == 0
def test_eval_partial_derivative_single_2nd_rank_tensors_by_tensor():
expr1 = PartialDerivative(H(i, j), H(m, m1))
assert expr1._perform_derivative() - L.delta(i, -m) * L.delta(j, -m1) == 0
expr2 = PartialDerivative(H(i, j), H(-m, m1))
assert expr2._perform_derivative() - L.metric(i, L_0) * L.delta(-L_0, m) * L.delta(j, -m1) == 0
expr3 = PartialDerivative(H(i, j), H(m, -m1))
assert expr3._perform_derivative() - L.delta(i, -m) * L.metric(j, L_0) * L.delta(-L_0, m1) == 0
expr4 = PartialDerivative(H(i, j), H(-m, -m1))
assert expr4._perform_derivative() - L.metric(i, L_0) * L.delta(-L_0, m) * L.metric(j, L_1) * L.delta(-L_1, m1) == 0
def test_eval_partial_derivative_divergence_type():
expr1a = PartialDerivative(A(i), A(i))
expr1b = PartialDerivative(A(i), A(k))
expr1c = PartialDerivative(L.delta(-i, k) * A(i), A(k))
assert (expr1a._perform_derivative()
- (L.delta(-i, k) * expr1b._perform_derivative())).contract_delta(L.delta) == 0
assert (expr1a._perform_derivative()
- expr1c._perform_derivative()).contract_delta(L.delta) == 0
expr2a = PartialDerivative(H(i, j), H(i, j))
expr2b = PartialDerivative(H(i, j), H(k, m))
expr2c = PartialDerivative(L.delta(-i, k) * L.delta(-j, m) * H(i, j), H(k, m))
assert (expr2a._perform_derivative()
- (L.delta(-i, k) * L.delta(-j, m) * expr2b._perform_derivative())).contract_delta(L.delta) == 0
assert (expr2a._perform_derivative()
- expr2c._perform_derivative()).contract_delta(L.delta) == 0
def test_eval_partial_derivative_expr1():
tau, alpha = symbols("tau alpha")
# this is only some special expression
# tested: vector derivative
# tested: scalar derivative
# tested: tensor derivative
base_expr1 = A(i)*H(-i, j) + A(i)*A(-i)*A(j) + tau**alpha*A(j)
tensor_derivative = PartialDerivative(base_expr1, H(k, m))._perform_derivative()
vector_derivative = PartialDerivative(base_expr1, A(k))._perform_derivative()
scalar_derivative = PartialDerivative(base_expr1, tau)._perform_derivative()
assert (tensor_derivative - A(L_0)*L.metric(-L_0, -L_1)*L.delta(L_1, -k)*L.delta(j, -m)) == 0
assert (vector_derivative - (tau**alpha*L.delta(j, -k) +
L.delta(L_0, -k)*A(-L_0)*A(j) +
A(L_0)*L.metric(-L_0, -L_1)*L.delta(L_1, -k)*A(j) +
A(L_0)*A(-L_0)*L.delta(j, -k) +
L.delta(L_0, -k)*H(-L_0, j))).expand() == 0
assert (vector_derivative.contract_metric(L.metric).contract_delta(L.delta) -
(tau**alpha*L.delta(j, -k) + A(L_0)*A(-L_0)*L.delta(j, -k) + H(-k, j) + 2*A(j)*A(-k))).expand() == 0
assert scalar_derivative - alpha*1/tau*tau**alpha*A(j) == 0
def test_eval_partial_derivative_mixed_scalar_tensor_expr2():
tau, alpha = symbols("tau alpha")
base_expr2 = A(i)*A(-i) + tau**2
vector_expression = PartialDerivative(base_expr2, A(k))._perform_derivative()
assert (vector_expression -
(L.delta(L_0, -k)*A(-L_0) + A(L_0)*L.metric(-L_0, -L_1)*L.delta(L_1, -k))).expand() == 0
scalar_expression = PartialDerivative(base_expr2, tau)._perform_derivative()
assert scalar_expression == 2*tau
|
c37fa68cbcc463e9be615d6ac1a75ce5d89f585c9074c63aad3f9a52c6d7c3ff | from functools import wraps
from sympy.concrete.summations import Sum
from sympy.core.function import expand
from sympy.core.numbers import Integer
from sympy.matrices.dense import (Matrix, eye)
from sympy.tensor.indexed import Indexed
from sympy.combinatorics import Permutation
from sympy.core import S, Rational, Symbol, Basic, Add
from sympy.core.containers import Tuple
from sympy.core.symbol import symbols
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.tensor.array import Array
from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorSymmetry, \
get_symmetric_group_sgs, TensorIndex, tensor_mul, TensAdd, \
riemann_cyclic_replace, riemann_cyclic, TensMul, tensor_heads, \
TensorManager, TensExpr, TensorHead, canon_bp, \
tensorhead, tensorsymmetry, TensorType, substitute_indices
from sympy.testing.pytest import raises, XFAIL, warns_deprecated_sympy, ignore_warnings
from sympy.utilities.exceptions import SymPyDeprecationWarning
from sympy.matrices import diag
def filter_warnings_decorator(f):
@wraps(f)
def wrapper():
with ignore_warnings(SymPyDeprecationWarning):
f()
return wrapper
def _is_equal(arg1, arg2):
if isinstance(arg1, TensExpr):
return arg1.equals(arg2)
elif isinstance(arg2, TensExpr):
return arg2.equals(arg1)
return arg1 == arg2
#################### Tests from tensor_can.py #######################
def test_canonicalize_no_slot_sym():
# A_d0 * B^d0; T_c = A^d0*B_d0
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b, d0, d1 = tensor_indices('a,b,d0,d1', Lorentz)
A, B = tensor_heads('A,B', [Lorentz], TensorSymmetry.no_symmetry(1))
t = A(-d0)*B(d0)
tc = t.canon_bp()
assert str(tc) == 'A(L_0)*B(-L_0)'
# A^a * B^b; T_c = T
t = A(a)*B(b)
tc = t.canon_bp()
assert tc == t
# B^b * A^a
t1 = B(b)*A(a)
tc = t1.canon_bp()
assert str(tc) == 'A(a)*B(b)'
# A symmetric
# A^{b}_{d0}*A^{d0, a}; T_c = A^{a d0}*A{b}_{d0}
A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = A(b, -d0)*A(d0, a)
tc = t.canon_bp()
assert str(tc) == 'A(a, L_0)*A(b, -L_0)'
# A^{d1}_{d0}*B^d0*C_d1
# T_c = A^{d0 d1}*B_d0*C_d1
B, C = tensor_heads('B,C', [Lorentz], TensorSymmetry.no_symmetry(1))
t = A(d1, -d0)*B(d0)*C(-d1)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, L_1)*B(-L_0)*C(-L_1)'
# A without symmetry
# A^{d1}_{d0}*B^d0*C_d1 ord=[d0,-d0,d1,-d1]; g = [2,1,0,3,4,5]
# T_c = A^{d0 d1}*B_d1*C_d0; can = [0,2,3,1,4,5]
A = TensorHead('A', [Lorentz]*2, TensorSymmetry.no_symmetry(2))
t = A(d1, -d0)*B(d0)*C(-d1)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, L_1)*B(-L_1)*C(-L_0)'
# A, B without symmetry
# A^{d1}_{d0}*B_{d1}^{d0}
# T_c = A^{d0 d1}*B_{d0 d1}
B = TensorHead('B', [Lorentz]*2, TensorSymmetry.no_symmetry(2))
t = A(d1, -d0)*B(-d1, d0)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, L_1)*B(-L_0, -L_1)'
# A_{d0}^{d1}*B_{d1}^{d0}
# T_c = A^{d0 d1}*B_{d1 d0}
t = A(-d0, d1)*B(-d1, d0)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, L_1)*B(-L_1, -L_0)'
# A, B, C without symmetry
# A^{d1 d0}*B_{a d0}*C_{d1 b}
# T_c=A^{d0 d1}*B_{a d1}*C_{d0 b}
C = TensorHead('C', [Lorentz]*2, TensorSymmetry.no_symmetry(2))
t = A(d1, d0)*B(-a, -d0)*C(-d1, -b)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, L_1)*B(-a, -L_1)*C(-L_0, -b)'
# A symmetric, B and C without symmetry
# A^{d1 d0}*B_{a d0}*C_{d1 b}
# T_c = A^{d0 d1}*B_{a d0}*C_{d1 b}
A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = A(d1, d0)*B(-a, -d0)*C(-d1, -b)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, L_1)*B(-a, -L_0)*C(-L_1, -b)'
# A and C symmetric, B without symmetry
# A^{d1 d0}*B_{a d0}*C_{d1 b} ord=[a,b,d0,-d0,d1,-d1]
# T_c = A^{d0 d1}*B_{a d0}*C_{b d1}
C = TensorHead('C', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = A(d1, d0)*B(-a, -d0)*C(-d1, -b)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, L_1)*B(-a, -L_0)*C(-b, -L_1)'
def test_canonicalize_no_dummies():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b, c, d = tensor_indices('a, b, c, d', Lorentz)
# A commuting
# A^c A^b A^a
# T_c = A^a A^b A^c
A = TensorHead('A', [Lorentz], TensorSymmetry.no_symmetry(1))
t = A(c)*A(b)*A(a)
tc = t.canon_bp()
assert str(tc) == 'A(a)*A(b)*A(c)'
# A anticommuting
# A^c A^b A^a
# T_c = -A^a A^b A^c
A = TensorHead('A', [Lorentz], TensorSymmetry.no_symmetry(1), 1)
t = A(c)*A(b)*A(a)
tc = t.canon_bp()
assert str(tc) == '-A(a)*A(b)*A(c)'
# A commuting and symmetric
# A^{b,d}*A^{c,a}
# T_c = A^{a c}*A^{b d}
A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = A(b, d)*A(c, a)
tc = t.canon_bp()
assert str(tc) == 'A(a, c)*A(b, d)'
# A anticommuting and symmetric
# A^{b,d}*A^{c,a}
# T_c = -A^{a c}*A^{b d}
A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2), 1)
t = A(b, d)*A(c, a)
tc = t.canon_bp()
assert str(tc) == '-A(a, c)*A(b, d)'
# A^{c,a}*A^{b,d}
# T_c = A^{a c}*A^{b d}
t = A(c, a)*A(b, d)
tc = t.canon_bp()
assert str(tc) == 'A(a, c)*A(b, d)'
def test_tensorhead_construction_without_symmetry():
L = TensorIndexType('Lorentz')
A1 = TensorHead('A', [L, L])
A2 = TensorHead('A', [L, L], TensorSymmetry.no_symmetry(2))
assert A1 == A2
A3 = TensorHead('A', [L, L], TensorSymmetry.fully_symmetric(2)) # Symmetric
assert A1 != A3
def test_no_metric_symmetry():
# no metric symmetry; A no symmetry
# A^d1_d0 * A^d0_d1
# T_c = A^d0_d1 * A^d1_d0
Lorentz = TensorIndexType('Lorentz', dummy_name='L', metric_symmetry=0)
d0, d1, d2, d3 = tensor_indices('d:4', Lorentz)
A = TensorHead('A', [Lorentz]*2, TensorSymmetry.no_symmetry(2))
t = A(d1, -d0)*A(d0, -d1)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, -L_1)*A(L_1, -L_0)'
# A^d1_d2 * A^d0_d3 * A^d2_d1 * A^d3_d0
# T_c = A^d0_d1 * A^d1_d0 * A^d2_d3 * A^d3_d2
t = A(d1, -d2)*A(d0, -d3)*A(d2, -d1)*A(d3, -d0)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, -L_1)*A(L_1, -L_0)*A(L_2, -L_3)*A(L_3, -L_2)'
# A^d0_d2 * A^d1_d3 * A^d3_d0 * A^d2_d1
# T_c = A^d0_d1 * A^d1_d2 * A^d2_d3 * A^d3_d0
t = A(d0, -d1)*A(d1, -d2)*A(d2, -d3)*A(d3, -d0)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, -L_1)*A(L_1, -L_2)*A(L_2, -L_3)*A(L_3, -L_0)'
def test_canonicalize1():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, a0, a1, a2, a3, b, d0, d1, d2, d3 = \
tensor_indices('a,a0,a1,a2,a3,b,d0,d1,d2,d3', Lorentz)
# A_d0*A^d0; ord = [d0,-d0]
# T_c = A^d0*A_d0
A = TensorHead('A', [Lorentz], TensorSymmetry.no_symmetry(1))
t = A(-d0)*A(d0)
tc = t.canon_bp()
assert str(tc) == 'A(L_0)*A(-L_0)'
# A commuting
# A_d0*A_d1*A_d2*A^d2*A^d1*A^d0
# T_c = A^d0*A_d0*A^d1*A_d1*A^d2*A_d2
t = A(-d0)*A(-d1)*A(-d2)*A(d2)*A(d1)*A(d0)
tc = t.canon_bp()
assert str(tc) == 'A(L_0)*A(-L_0)*A(L_1)*A(-L_1)*A(L_2)*A(-L_2)'
# A anticommuting
# A_d0*A_d1*A_d2*A^d2*A^d1*A^d0
# T_c 0
A = TensorHead('A', [Lorentz], TensorSymmetry.no_symmetry(1), 1)
t = A(-d0)*A(-d1)*A(-d2)*A(d2)*A(d1)*A(d0)
tc = t.canon_bp()
assert tc == 0
# A commuting symmetric
# A^{d0 b}*A^a_d1*A^d1_d0
# T_c = A^{a d0}*A^{b d1}*A_{d0 d1}
A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = A(d0, b)*A(a, -d1)*A(d1, -d0)
tc = t.canon_bp()
assert str(tc) == 'A(a, L_0)*A(b, L_1)*A(-L_0, -L_1)'
# A, B commuting symmetric
# A^{d0 b}*A^d1_d0*B^a_d1
# T_c = A^{b d0}*A_d0^d1*B^a_d1
B = TensorHead('B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = A(d0, b)*A(d1, -d0)*B(a, -d1)
tc = t.canon_bp()
assert str(tc) == 'A(b, L_0)*A(-L_0, L_1)*B(a, -L_1)'
# A commuting symmetric
# A^{d1 d0 b}*A^{a}_{d1 d0}; ord=[a,b, d0,-d0,d1,-d1]
# T_c = A^{a d0 d1}*A^{b}_{d0 d1}
A = TensorHead('A', [Lorentz]*3, TensorSymmetry.fully_symmetric(3))
t = A(d1, d0, b)*A(a, -d1, -d0)
tc = t.canon_bp()
assert str(tc) == 'A(a, L_0, L_1)*A(b, -L_0, -L_1)'
# A^{d3 d0 d2}*A^a0_{d1 d2}*A^d1_d3^a1*A^{a2 a3}_d0
# T_c = A^{a0 d0 d1}*A^a1_d0^d2*A^{a2 a3 d3}*A_{d1 d2 d3}
t = A(d3, d0, d2)*A(a0, -d1, -d2)*A(d1, -d3, a1)*A(a2, a3, -d0)
tc = t.canon_bp()
assert str(tc) == 'A(a0, L_0, L_1)*A(a1, -L_0, L_2)*A(a2, a3, L_3)*A(-L_1, -L_2, -L_3)'
# A commuting symmetric, B antisymmetric
# A^{d0 d1 d2} * A_{d2 d3 d1} * B_d0^d3
# in this esxample and in the next three,
# renaming dummy indices and using symmetry of A,
# T = A^{d0 d1 d2} * A_{d0 d1 d3} * B_d2^d3
# can = 0
A = TensorHead('A', [Lorentz]*3, TensorSymmetry.fully_symmetric(3))
B = TensorHead('B', [Lorentz]*2, TensorSymmetry.fully_symmetric(-2))
t = A(d0, d1, d2)*A(-d2, -d3, -d1)*B(-d0, d3)
tc = t.canon_bp()
assert tc == 0
# A anticommuting symmetric, B antisymmetric
# A^{d0 d1 d2} * A_{d2 d3 d1} * B_d0^d3
# T_c = A^{d0 d1 d2} * A_{d0 d1}^d3 * B_{d2 d3}
A = TensorHead('A', [Lorentz]*3, TensorSymmetry.fully_symmetric(3), 1)
B = TensorHead('B', [Lorentz]*2, TensorSymmetry.fully_symmetric(-2))
t = A(d0, d1, d2)*A(-d2, -d3, -d1)*B(-d0, d3)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, L_1, L_2)*A(-L_0, -L_1, L_3)*B(-L_2, -L_3)'
# A anticommuting symmetric, B antisymmetric commuting, antisymmetric metric
# A^{d0 d1 d2} * A_{d2 d3 d1} * B_d0^d3
# T_c = -A^{d0 d1 d2} * A_{d0 d1}^d3 * B_{d2 d3}
Spinor = TensorIndexType('Spinor', dummy_name='S', metric_symmetry=-1)
a, a0, a1, a2, a3, b, d0, d1, d2, d3 = \
tensor_indices('a,a0,a1,a2,a3,b,d0,d1,d2,d3', Spinor)
A = TensorHead('A', [Spinor]*3, TensorSymmetry.fully_symmetric(3), 1)
B = TensorHead('B', [Spinor]*2, TensorSymmetry.fully_symmetric(-2))
t = A(d0, d1, d2)*A(-d2, -d3, -d1)*B(-d0, d3)
tc = t.canon_bp()
assert str(tc) == '-A(S_0, S_1, S_2)*A(-S_0, -S_1, S_3)*B(-S_2, -S_3)'
# A anticommuting symmetric, B antisymmetric anticommuting,
# no metric symmetry
# A^{d0 d1 d2} * A_{d2 d3 d1} * B_d0^d3
# T_c = A^{d0 d1 d2} * A_{d0 d1 d3} * B_d2^d3
Mat = TensorIndexType('Mat', metric_symmetry=0, dummy_name='M')
a, a0, a1, a2, a3, b, d0, d1, d2, d3 = \
tensor_indices('a,a0,a1,a2,a3,b,d0,d1,d2,d3', Mat)
A = TensorHead('A', [Mat]*3, TensorSymmetry.fully_symmetric(3), 1)
B = TensorHead('B', [Mat]*2, TensorSymmetry.fully_symmetric(-2))
t = A(d0, d1, d2)*A(-d2, -d3, -d1)*B(-d0, d3)
tc = t.canon_bp()
assert str(tc) == 'A(M_0, M_1, M_2)*A(-M_0, -M_1, -M_3)*B(-M_2, M_3)'
# Gamma anticommuting
# Gamma_{mu nu} * gamma^rho * Gamma^{nu mu alpha}
# T_c = -Gamma^{mu nu} * gamma^rho * Gamma_{alpha mu nu}
alpha, beta, gamma, mu, nu, rho = \
tensor_indices('alpha,beta,gamma,mu,nu,rho', Lorentz)
Gamma = TensorHead('Gamma', [Lorentz],
TensorSymmetry.fully_symmetric(1), 2)
Gamma2 = TensorHead('Gamma', [Lorentz]*2,
TensorSymmetry.fully_symmetric(-2), 2)
Gamma3 = TensorHead('Gamma', [Lorentz]*3,
TensorSymmetry.fully_symmetric(-3), 2)
t = Gamma2(-mu, -nu)*Gamma(rho)*Gamma3(nu, mu, alpha)
tc = t.canon_bp()
assert str(tc) == '-Gamma(L_0, L_1)*Gamma(rho)*Gamma(alpha, -L_0, -L_1)'
# Gamma_{mu nu} * Gamma^{gamma beta} * gamma_rho * Gamma^{nu mu alpha}
# T_c = Gamma^{mu nu} * Gamma^{beta gamma} * gamma_rho * Gamma^alpha_{mu nu}
t = Gamma2(mu, nu)*Gamma2(beta, gamma)*Gamma(-rho)*Gamma3(alpha, -mu, -nu)
tc = t.canon_bp()
assert str(tc) == 'Gamma(L_0, L_1)*Gamma(beta, gamma)*Gamma(-rho)*Gamma(alpha, -L_0, -L_1)'
# f^a_{b,c} antisymmetric in b,c; A_mu^a no symmetry
# f^c_{d a} * f_{c e b} * A_mu^d * A_nu^a * A^{nu e} * A^{mu b}
# g = [8,11,5, 9,13,7, 1,10, 3,4, 2,12, 0,6, 14,15]
# T_c = -f^{a b c} * f_a^{d e} * A^mu_b * A_{mu d} * A^nu_c * A_{nu e}
Flavor = TensorIndexType('Flavor', dummy_name='F')
a, b, c, d, e, ff = tensor_indices('a,b,c,d,e,f', Flavor)
mu, nu = tensor_indices('mu,nu', Lorentz)
f = TensorHead('f', [Flavor]*3, TensorSymmetry.direct_product(1, -2))
A = TensorHead('A', [Lorentz, Flavor], TensorSymmetry.no_symmetry(2))
t = f(c, -d, -a)*f(-c, -e, -b)*A(-mu, d)*A(-nu, a)*A(nu, e)*A(mu, b)
tc = t.canon_bp()
assert str(tc) == '-f(F_0, F_1, F_2)*f(-F_0, F_3, F_4)*A(L_0, -F_1)*A(-L_0, -F_3)*A(L_1, -F_2)*A(-L_1, -F_4)'
def test_bug_correction_tensor_indices():
# to make sure that tensor_indices does not return a list if creating
# only one index:
A = TensorIndexType("A")
i = tensor_indices('i', A)
assert not isinstance(i, (tuple, list))
assert isinstance(i, TensorIndex)
def test_riemann_invariants():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11 = \
tensor_indices('d0:12', Lorentz)
# R^{d0 d1}_{d1 d0}; ord = [d0,-d0,d1,-d1]
# T_c = -R^{d0 d1}_{d0 d1}
R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann())
t = R(d0, d1, -d1, -d0)
tc = t.canon_bp()
assert str(tc) == '-R(L_0, L_1, -L_0, -L_1)'
# R_d11^d1_d0^d5 * R^{d6 d4 d0}_d5 * R_{d7 d2 d8 d9} *
# R_{d10 d3 d6 d4} * R^{d2 d7 d11}_d1 * R^{d8 d9 d3 d10}
# can = [0,2,4,6, 1,3,8,10, 5,7,12,14, 9,11,16,18, 13,15,20,22,
# 17,19,21<F10,23, 24,25]
# T_c = R^{d0 d1 d2 d3} * R_{d0 d1}^{d4 d5} * R_{d2 d3}^{d6 d7} *
# R_{d4 d5}^{d8 d9} * R_{d6 d7}^{d10 d11} * R_{d8 d9 d10 d11}
t = R(-d11,d1,-d0,d5)*R(d6,d4,d0,-d5)*R(-d7,-d2,-d8,-d9)* \
R(-d10,-d3,-d6,-d4)*R(d2,d7,d11,-d1)*R(d8,d9,d3,d10)
tc = t.canon_bp()
assert str(tc) == 'R(L_0, L_1, L_2, L_3)*R(-L_0, -L_1, L_4, L_5)*R(-L_2, -L_3, L_6, L_7)*R(-L_4, -L_5, L_8, L_9)*R(-L_6, -L_7, L_10, L_11)*R(-L_8, -L_9, -L_10, -L_11)'
def test_riemann_products():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
d0, d1, d2, d3, d4, d5, d6 = tensor_indices('d0:7', Lorentz)
a0, a1, a2, a3, a4, a5 = tensor_indices('a0:6', Lorentz)
a, b = tensor_indices('a,b', Lorentz)
R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann())
# R^{a b d0}_d0 = 0
t = R(a, b, d0, -d0)
tc = t.canon_bp()
assert tc == 0
# R^{d0 b a}_d0
# T_c = -R^{a d0 b}_d0
t = R(d0, b, a, -d0)
tc = t.canon_bp()
assert str(tc) == '-R(a, L_0, b, -L_0)'
# R^d1_d2^b_d0 * R^{d0 a}_d1^d2; ord=[a,b,d0,-d0,d1,-d1,d2,-d2]
# T_c = -R^{a d0 d1 d2}* R^b_{d0 d1 d2}
t = R(d1, -d2, b, -d0)*R(d0, a, -d1, d2)
tc = t.canon_bp()
assert str(tc) == '-R(a, L_0, L_1, L_2)*R(b, -L_0, -L_1, -L_2)'
# A symmetric commuting
# R^{d6 d5}_d2^d1 * R^{d4 d0 d2 d3} * A_{d6 d0} A_{d3 d1} * A_{d4 d5}
# g = [12,10,5,2, 8,0,4,6, 13,1, 7,3, 9,11,14,15]
# T_c = -R^{d0 d1 d2 d3} * R_d0^{d4 d5 d6} * A_{d1 d4}*A_{d2 d5}*A_{d3 d6}
V = TensorHead('V', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = R(d6, d5, -d2, d1)*R(d4, d0, d2, d3)*V(-d6, -d0)*V(-d3, -d1)*V(-d4, -d5)
tc = t.canon_bp()
assert str(tc) == '-R(L_0, L_1, L_2, L_3)*R(-L_0, L_4, L_5, L_6)*V(-L_1, -L_4)*V(-L_2, -L_5)*V(-L_3, -L_6)'
# R^{d2 a0 a2 d0} * R^d1_d2^{a1 a3} * R^{a4 a5}_{d0 d1}
# T_c = R^{a0 d0 a2 d1}*R^{a1 a3}_d0^d2*R^{a4 a5}_{d1 d2}
t = R(d2, a0, a2, d0)*R(d1, -d2, a1, a3)*R(a4, a5, -d0, -d1)
tc = t.canon_bp()
assert str(tc) == 'R(a0, L_0, a2, L_1)*R(a1, a3, -L_0, L_2)*R(a4, a5, -L_1, -L_2)'
######################################################################
def test_canonicalize2():
D = Symbol('D')
Eucl = TensorIndexType('Eucl', metric_symmetry=1, dim=D, dummy_name='E')
i0,i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,i11,i12,i13,i14 = \
tensor_indices('i0:15', Eucl)
A = TensorHead('A', [Eucl]*3, TensorSymmetry.fully_symmetric(-3))
# two examples from Cvitanovic, Group Theory page 59
# of identities for antisymmetric tensors of rank 3
# contracted according to the Kuratowski graph eq.(6.59)
t = A(i0,i1,i2)*A(-i1,i3,i4)*A(-i3,i7,i5)*A(-i2,-i5,i6)*A(-i4,-i6,i8)
t1 = t.canon_bp()
assert t1 == 0
# eq.(6.60)
#t = A(i0,i1,i2)*A(-i1,i3,i4)*A(-i2,i5,i6)*A(-i3,i7,i8)*A(-i6,-i7,i9)*
# A(-i8,i10,i13)*A(-i5,-i10,i11)*A(-i4,-i11,i12)*A(-i3,-i12,i14)
t = A(i0,i1,i2)*A(-i1,i3,i4)*A(-i2,i5,i6)*A(-i3,i7,i8)*A(-i6,-i7,i9)*\
A(-i8,i10,i13)*A(-i5,-i10,i11)*A(-i4,-i11,i12)*A(-i9,-i12,i14)
t1 = t.canon_bp()
assert t1 == 0
def test_canonicalize3():
D = Symbol('D')
Spinor = TensorIndexType('Spinor', dim=D, metric_symmetry=-1, dummy_name='S')
a0,a1,a2,a3,a4 = tensor_indices('a0:5', Spinor)
chi, psi = tensor_heads('chi,psi', [Spinor], TensorSymmetry.no_symmetry(1), 1)
t = chi(a1)*psi(a0)
t1 = t.canon_bp()
assert t1 == t
t = psi(a1)*chi(a0)
t1 = t.canon_bp()
assert t1 == -chi(a0)*psi(a1)
def test_TensorIndexType():
D = Symbol('D')
Lorentz = TensorIndexType('Lorentz', metric_name='g', metric_symmetry=1,
dim=D, dummy_name='L')
m0, m1, m2, m3, m4 = tensor_indices('m0:5', Lorentz)
sym2 = TensorSymmetry.fully_symmetric(2)
sym2n = TensorSymmetry(*get_symmetric_group_sgs(2))
assert sym2 == sym2n
g = Lorentz.metric
assert str(g) == 'g(Lorentz,Lorentz)'
assert Lorentz.eps_dim == Lorentz.dim
TSpace = TensorIndexType('TSpace', dummy_name = 'TSpace')
i0, i1 = tensor_indices('i0 i1', TSpace)
g = TSpace.metric
A = TensorHead('A', [TSpace]*2, sym2)
assert str(A(i0,-i0).canon_bp()) == 'A(TSpace_0, -TSpace_0)'
def test_indices():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b, c, d = tensor_indices('a,b,c,d', Lorentz)
assert a.tensor_index_type == Lorentz
assert a != -a
A, B = tensor_heads('A B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = A(a,b)*B(-b,c)
indices = t.get_indices()
L_0 = TensorIndex('L_0', Lorentz)
assert indices == [a, L_0, -L_0, c]
raises(ValueError, lambda: tensor_indices(3, Lorentz))
raises(ValueError, lambda: A(a,b,c))
A = TensorHead('A', [Lorentz, Lorentz])
assert A('a', 'b') == A(TensorIndex('a', Lorentz),
TensorIndex('b', Lorentz))
assert A('a', '-b') == A(TensorIndex('a', Lorentz),
TensorIndex('b', Lorentz, is_up=False))
assert A('a', TensorIndex('b', Lorentz)) == A(TensorIndex('a', Lorentz),
TensorIndex('b', Lorentz))
def test_TensorSymmetry():
assert TensorSymmetry.fully_symmetric(2) == \
TensorSymmetry(get_symmetric_group_sgs(2))
assert TensorSymmetry.fully_symmetric(-3) == \
TensorSymmetry(get_symmetric_group_sgs(3, True))
assert TensorSymmetry.direct_product(-4) == \
TensorSymmetry.fully_symmetric(-4)
assert TensorSymmetry.fully_symmetric(-1) == \
TensorSymmetry.fully_symmetric(1)
assert TensorSymmetry.direct_product(1, -1, 1) == \
TensorSymmetry.no_symmetry(3)
assert TensorSymmetry(get_symmetric_group_sgs(2)) == \
TensorSymmetry(*get_symmetric_group_sgs(2))
# TODO: add check for *get_symmetric_group_sgs(0)
sym = TensorSymmetry.fully_symmetric(-3)
assert sym.rank == 3
assert sym.base == Tuple(0, 1)
assert sym.generators == Tuple(Permutation(0, 1)(3, 4), Permutation(1, 2)(3, 4))
def test_TensExpr():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b, c, d = tensor_indices('a,b,c,d', Lorentz)
g = Lorentz.metric
A, B = tensor_heads('A B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
raises(ValueError, lambda: g(c, d)/g(a, b))
raises(ValueError, lambda: S.One/g(a, b))
raises(ValueError, lambda: (A(c, d) + g(c, d))/g(a, b))
raises(ValueError, lambda: S.One/(A(c, d) + g(c, d)))
raises(ValueError, lambda: A(a, b) + A(a, c))
A(a, b) + B(a, b) # assigned to t for below
#raises(NotImplementedError, lambda: TensExpr.__mul__(t, 'a'))
#raises(NotImplementedError, lambda: TensExpr.__add__(t, 'a'))
#raises(NotImplementedError, lambda: TensExpr.__radd__(t, 'a'))
#raises(NotImplementedError, lambda: TensExpr.__sub__(t, 'a'))
#raises(NotImplementedError, lambda: TensExpr.__rsub__(t, 'a'))
#raises(NotImplementedError, lambda: TensExpr.__truediv__(t, 'a'))
#raises(NotImplementedError, lambda: TensExpr.__rtruediv__(t, 'a'))
with ignore_warnings(SymPyDeprecationWarning):
# DO NOT REMOVE THIS AFTER DEPRECATION REMOVED:
raises(ValueError, lambda: A(a, b)**2)
raises(NotImplementedError, lambda: 2**A(a, b))
raises(NotImplementedError, lambda: abs(A(a, b)))
def test_TensorHead():
# simple example of algebraic expression
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
A = TensorHead('A', [Lorentz]*2)
assert A.name == 'A'
assert A.index_types == [Lorentz, Lorentz]
assert A.rank == 2
assert A.symmetry == TensorSymmetry.no_symmetry(2)
assert A.comm == 0
def test_add1():
assert TensAdd().args == ()
assert TensAdd().doit() == 0
# simple example of algebraic expression
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a,b,d0,d1,i,j,k = tensor_indices('a,b,d0,d1,i,j,k', Lorentz)
# A, B symmetric
A, B = tensor_heads('A,B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t1 = A(b, -d0)*B(d0, a)
assert TensAdd(t1).equals(t1)
t2a = B(d0, a) + A(d0, a)
t2 = A(b, -d0)*t2a
assert str(t2) == 'A(b, -L_0)*(A(L_0, a) + B(L_0, a))'
t2 = t2.expand()
assert str(t2) == 'A(b, -L_0)*A(L_0, a) + A(b, -L_0)*B(L_0, a)'
t2 = t2.canon_bp()
assert str(t2) == 'A(a, L_0)*A(b, -L_0) + A(b, L_0)*B(a, -L_0)'
t2b = t2 + t1
assert str(t2b) == 'A(a, L_0)*A(b, -L_0) + A(b, -L_0)*B(L_0, a) + A(b, L_0)*B(a, -L_0)'
t2b = t2b.canon_bp()
assert str(t2b) == 'A(a, L_0)*A(b, -L_0) + 2*A(b, L_0)*B(a, -L_0)'
p, q, r = tensor_heads('p,q,r', [Lorentz])
t = q(d0)*2
assert str(t) == '2*q(d0)'
t = 2*q(d0)
assert str(t) == '2*q(d0)'
t1 = p(d0) + 2*q(d0)
assert str(t1) == '2*q(d0) + p(d0)'
t2 = p(-d0) + 2*q(-d0)
assert str(t2) == '2*q(-d0) + p(-d0)'
t1 = p(d0)
t3 = t1*t2
assert str(t3) == 'p(L_0)*(2*q(-L_0) + p(-L_0))'
t3 = t3.expand()
assert str(t3) == 'p(L_0)*p(-L_0) + 2*p(L_0)*q(-L_0)'
t3 = t2*t1
t3 = t3.expand()
assert str(t3) == 'p(-L_0)*p(L_0) + 2*q(-L_0)*p(L_0)'
t3 = t3.canon_bp()
assert str(t3) == 'p(L_0)*p(-L_0) + 2*p(L_0)*q(-L_0)'
t1 = p(d0) + 2*q(d0)
t3 = t1*t2
t3 = t3.canon_bp()
assert str(t3) == 'p(L_0)*p(-L_0) + 4*p(L_0)*q(-L_0) + 4*q(L_0)*q(-L_0)'
t1 = p(d0) - 2*q(d0)
assert str(t1) == '-2*q(d0) + p(d0)'
t2 = p(-d0) + 2*q(-d0)
t3 = t1*t2
t3 = t3.canon_bp()
assert t3 == p(d0)*p(-d0) - 4*q(d0)*q(-d0)
t = p(i)*p(j)*(p(k) + q(k)) + p(i)*(p(j) + q(j))*(p(k) - 3*q(k))
t = t.canon_bp()
assert t == 2*p(i)*p(j)*p(k) - 2*p(i)*p(j)*q(k) + p(i)*p(k)*q(j) - 3*p(i)*q(j)*q(k)
t1 = (p(i) + q(i) + 2*r(i))*(p(j) - q(j))
t2 = (p(j) + q(j) + 2*r(j))*(p(i) - q(i))
t = t1 + t2
t = t.canon_bp()
assert t == 2*p(i)*p(j) + 2*p(i)*r(j) + 2*p(j)*r(i) - 2*q(i)*q(j) - 2*q(i)*r(j) - 2*q(j)*r(i)
t = p(i)*q(j)/2
assert 2*t == p(i)*q(j)
t = (p(i) + q(i))/2
assert 2*t == p(i) + q(i)
t = S.One - p(i)*p(-i)
t = t.canon_bp()
tz1 = t + p(-j)*p(j)
assert tz1 != 1
tz1 = tz1.canon_bp()
assert tz1.equals(1)
t = S.One + p(i)*p(-i)
assert (t - p(-j)*p(j)).canon_bp().equals(1)
t = A(a, b) + B(a, b)
assert t.rank == 2
t1 = t - A(a, b) - B(a, b)
assert t1 == 0
t = 1 - (A(a, -a) + B(a, -a))
t1 = 1 + (A(a, -a) + B(a, -a))
assert (t + t1).expand().equals(2)
t2 = 1 + A(a, -a)
assert t1 != t2
assert t2 != TensMul.from_data(0, [], [], [])
def test_special_eq_ne():
# test special equality cases:
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b, d0, d1, i, j, k = tensor_indices('a,b,d0,d1,i,j,k', Lorentz)
# A, B symmetric
A, B = tensor_heads('A,B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
p, q, r = tensor_heads('p,q,r', [Lorentz])
t = 0*A(a, b)
assert _is_equal(t, 0)
assert _is_equal(t, S.Zero)
assert p(i) != A(a, b)
assert A(a, -a) != A(a, b)
assert 0*(A(a, b) + B(a, b)) == 0
assert 0*(A(a, b) + B(a, b)) is S.Zero
assert 3*(A(a, b) - A(a, b)) is S.Zero
assert p(i) + q(i) != A(a, b)
assert p(i) + q(i) != A(a, b) + B(a, b)
assert p(i) - p(i) == 0
assert p(i) - p(i) is S.Zero
assert _is_equal(A(a, b), A(b, a))
def test_add2():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
m, n, p, q = tensor_indices('m,n,p,q', Lorentz)
R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann())
A = TensorHead('A', [Lorentz]*3, TensorSymmetry.fully_symmetric(-3))
t1 = 2*R(m, n, p, q) - R(m, q, n, p) + R(m, p, n, q)
t2 = t1*A(-n, -p, -q)
t2 = t2.canon_bp()
assert t2 == 0
t1 = Rational(2, 3)*R(m,n,p,q) - Rational(1, 3)*R(m,q,n,p) + Rational(1, 3)*R(m,p,n,q)
t2 = t1*A(-n, -p, -q)
t2 = t2.canon_bp()
assert t2 == 0
t = A(m, -m, n) + A(n, p, -p)
t = t.canon_bp()
assert t == 0
def test_add3():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
i0, i1 = tensor_indices('i0:2', Lorentz)
E, px, py, pz = symbols('E px py pz')
A = TensorHead('A', [Lorentz])
B = TensorHead('B', [Lorentz])
expr1 = A(i0)*A(-i0) - (E**2 - px**2 - py**2 - pz**2)
assert expr1.args == (-E**2, px**2, py**2, pz**2, A(i0)*A(-i0))
expr2 = E**2 - px**2 - py**2 - pz**2 - A(i0)*A(-i0)
assert expr2.args == (E**2, -px**2, -py**2, -pz**2, -A(i0)*A(-i0))
expr3 = A(i0)*A(-i0) - E**2 + px**2 + py**2 + pz**2
assert expr3.args == (-E**2, px**2, py**2, pz**2, A(i0)*A(-i0))
expr4 = B(i1)*B(-i1) + 2*E**2 - 2*px**2 - 2*py**2 - 2*pz**2 - A(i0)*A(-i0)
assert expr4.args == (2*E**2, -2*px**2, -2*py**2, -2*pz**2, B(i1)*B(-i1), -A(i0)*A(-i0))
def test_mul():
from sympy.abc import x
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b, c, d = tensor_indices('a,b,c,d', Lorentz)
t = TensMul.from_data(S.One, [], [], [])
assert str(t) == '1'
A, B = tensor_heads('A B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = (1 + x)*A(a, b)
assert str(t) == '(x + 1)*A(a, b)'
assert t.index_types == [Lorentz, Lorentz]
assert t.rank == 2
assert t.dum == []
assert t.coeff == 1 + x
assert sorted(t.free) == [(a, 0), (b, 1)]
assert t.components == [A]
ts = A(a, b)
assert str(ts) == 'A(a, b)'
assert ts.index_types == [Lorentz, Lorentz]
assert ts.rank == 2
assert ts.dum == []
assert ts.coeff == 1
assert sorted(ts.free) == [(a, 0), (b, 1)]
assert ts.components == [A]
t = A(-b, a)*B(-a, c)*A(-c, d)
t1 = tensor_mul(*t.split())
assert t == t1
assert tensor_mul(*[]) == TensMul.from_data(S.One, [], [], [])
t = TensMul.from_data(1, [], [], [])
C = TensorHead('C', [])
assert str(C()) == 'C'
assert str(t) == '1'
assert t == 1
raises(ValueError, lambda: A(a, b)*A(a, c))
def test_substitute_indices():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
i, j, k, l, m, n, p, q = tensor_indices('i,j,k,l,m,n,p,q', Lorentz)
A, B = tensor_heads('A,B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
p = TensorHead('p', [Lorentz])
t = p(i)
t1 = t.substitute_indices((j, k))
assert t1 == t
t1 = t.substitute_indices((i, j))
assert t1 == p(j)
t1 = t.substitute_indices((i, -j))
assert t1 == p(-j)
t1 = t.substitute_indices((-i, j))
assert t1 == p(-j)
t1 = t.substitute_indices((-i, -j))
assert t1 == p(j)
t = A(m, n)
t1 = t.substitute_indices((m, i), (n, -i))
assert t1 == A(n, -n)
t1 = substitute_indices(t, (m, i), (n, -i))
assert t1 == A(n, -n)
t = A(i, k)*B(-k, -j)
t1 = t.substitute_indices((i, j), (j, k))
t1a = A(j, l)*B(-l, -k)
assert t1 == t1a
t1 = substitute_indices(t, (i, j), (j, k))
assert t1 == t1a
t = A(i, j) + B(i, j)
t1 = t.substitute_indices((j, -i))
t1a = A(i, -i) + B(i, -i)
assert t1 == t1a
t1 = substitute_indices(t, (j, -i))
assert t1 == t1a
def test_riemann_cyclic_replace():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
m0, m1, m2, m3 = tensor_indices('m:4', Lorentz)
R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann())
t = R(m0, m2, m1, m3)
t1 = riemann_cyclic_replace(t)
t1a = Rational(-1, 3)*R(m0, m3, m2, m1) + Rational(1, 3)*R(m0, m1, m2, m3) + Rational(2, 3)*R(m0, m2, m1, m3)
assert t1 == t1a
def test_riemann_cyclic():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
i, j, k, l, m, n, p, q = tensor_indices('i,j,k,l,m,n,p,q', Lorentz)
R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann())
t = R(i,j,k,l) + R(i,l,j,k) + R(i,k,l,j) - \
R(i,j,l,k) - R(i,l,k,j) - R(i,k,j,l)
t2 = t*R(-i,-j,-k,-l)
t3 = riemann_cyclic(t2)
assert t3 == 0
t = R(i,j,k,l)*(R(-i,-j,-k,-l) - 2*R(-i,-k,-j,-l))
t1 = riemann_cyclic(t)
assert t1 == 0
t = R(i,j,k,l)
t1 = riemann_cyclic(t)
assert t1 == Rational(-1, 3)*R(i, l, j, k) + Rational(1, 3)*R(i, k, j, l) + Rational(2, 3)*R(i, j, k, l)
t = R(i,j,k,l)*R(-k,-l,m,n)*(R(-m,-n,-i,-j) + 2*R(-m,-j,-n,-i))
t1 = riemann_cyclic(t)
assert t1 == 0
@XFAIL
def test_div():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
m0, m1, m2, m3 = tensor_indices('m0:4', Lorentz)
R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann())
t = R(m0,m1,-m1,m3)
t1 = t/S(4)
assert str(t1) == '(1/4)*R(m0, L_0, -L_0, m3)'
t = t.canon_bp()
assert not t1._is_canon_bp
t1 = t*4
assert t1._is_canon_bp
t1 = t1/4
assert t1._is_canon_bp
def test_contract_metric1():
D = Symbol('D')
Lorentz = TensorIndexType('Lorentz', dim=D, dummy_name='L')
a, b, c, d, e = tensor_indices('a,b,c,d,e', Lorentz)
g = Lorentz.metric
p = TensorHead('p', [Lorentz])
t = g(a, b)*p(-b)
t1 = t.contract_metric(g)
assert t1 == p(a)
A, B = tensor_heads('A,B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
# case with g with all free indices
t1 = A(a,b)*B(-b,c)*g(d, e)
t2 = t1.contract_metric(g)
assert t1 == t2
# case of g(d, -d)
t1 = A(a,b)*B(-b,c)*g(-d, d)
t2 = t1.contract_metric(g)
assert t2 == D*A(a, d)*B(-d, c)
# g with one free index
t1 = A(a,b)*B(-b,-c)*g(c, d)
t2 = t1.contract_metric(g)
assert t2 == A(a, c)*B(-c, d)
# g with both indices contracted with another tensor
t1 = A(a,b)*B(-b,-c)*g(c, -a)
t2 = t1.contract_metric(g)
assert _is_equal(t2, A(a, b)*B(-b, -a))
t1 = A(a,b)*B(-b,-c)*g(c, d)*g(-a, -d)
t2 = t1.contract_metric(g)
assert _is_equal(t2, A(a,b)*B(-b,-a))
t1 = A(a,b)*g(-a,-b)
t2 = t1.contract_metric(g)
assert _is_equal(t2, A(a, -a))
assert not t2.free
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b = tensor_indices('a,b', Lorentz)
g = Lorentz.metric
assert _is_equal(g(a, -a).contract_metric(g), Lorentz.dim) # no dim
def test_contract_metric2():
D = Symbol('D')
Lorentz = TensorIndexType('Lorentz', dim=D, dummy_name='L')
a, b, c, d, e, L_0 = tensor_indices('a,b,c,d,e,L_0', Lorentz)
g = Lorentz.metric
p, q = tensor_heads('p,q', [Lorentz])
t1 = g(a,b)*p(c)*p(-c)
t2 = 3*g(-a,-b)*q(c)*q(-c)
t = t1*t2
t = t.contract_metric(g)
assert t == 3*D*p(a)*p(-a)*q(b)*q(-b)
t1 = g(a,b)*p(c)*p(-c)
t2 = 3*q(-a)*q(-b)
t = t1*t2
t = t.contract_metric(g)
t = t.canon_bp()
assert t == 3*p(a)*p(-a)*q(b)*q(-b)
t1 = 2*g(a,b)*p(c)*p(-c)
t2 = - 3*g(-a,-b)*q(c)*q(-c)
t = t1*t2
t = t.contract_metric(g)
t = 6*g(a,b)*g(-a,-b)*p(c)*p(-c)*q(d)*q(-d)
t = t.contract_metric(g)
t1 = 2*g(a,b)*p(c)*p(-c)
t2 = q(-a)*q(-b) + 3*g(-a,-b)*q(c)*q(-c)
t = t1*t2
t = t.contract_metric(g)
assert t == (2 + 6*D)*p(a)*p(-a)*q(b)*q(-b)
t1 = p(a)*p(b) + p(a)*q(b) + 2*g(a,b)*p(c)*p(-c)
t2 = q(-a)*q(-b) - g(-a,-b)*q(c)*q(-c)
t = t1*t2
t = t.contract_metric(g)
t1 = (1 - 2*D)*p(a)*p(-a)*q(b)*q(-b) + p(a)*q(-a)*p(b)*q(-b)
assert canon_bp(t - t1) == 0
t = g(a,b)*g(c,d)*g(-b,-c)
t1 = t.contract_metric(g)
assert t1 == g(a, d)
t1 = g(a,b)*g(c,d) + g(a,c)*g(b,d) + g(a,d)*g(b,c)
t2 = t1.substitute_indices((a,-a),(b,-b),(c,-c),(d,-d))
t = t1*t2
t = t.contract_metric(g)
assert t.equals(3*D**2 + 6*D)
t = 2*p(a)*g(b,-b)
t1 = t.contract_metric(g)
assert t1.equals(2*D*p(a))
t = 2*p(a)*g(b,-a)
t1 = t.contract_metric(g)
assert t1 == 2*p(b)
M = Symbol('M')
t = (p(a)*p(b) + g(a, b)*M**2)*g(-a, -b) - D*M**2
t1 = t.contract_metric(g)
assert t1 == p(a)*p(-a)
A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = A(a, b)*p(L_0)*g(-a, -b)
t1 = t.contract_metric(g)
assert str(t1) == 'A(L_1, -L_1)*p(L_0)' or str(t1) == 'A(-L_1, L_1)*p(L_0)'
def test_metric_contract3():
D = Symbol('D')
Spinor = TensorIndexType('Spinor', dim=D, metric_symmetry=-1, dummy_name='S')
a0, a1, a2, a3, a4 = tensor_indices('a0:5', Spinor)
C = Spinor.metric
chi, psi = tensor_heads('chi,psi', [Spinor], TensorSymmetry.no_symmetry(1), 1)
B = TensorHead('B', [Spinor]*2, TensorSymmetry.no_symmetry(2))
t = C(a0,-a0)
t1 = t.contract_metric(C)
assert t1.equals(-D)
t = C(-a0,a0)
t1 = t.contract_metric(C)
assert t1.equals(D)
t = C(a0,a1)*C(-a0,-a1)
t1 = t.contract_metric(C)
assert t1.equals(D)
t = C(a1,a0)*C(-a0,-a1)
t1 = t.contract_metric(C)
assert t1.equals(-D)
t = C(-a0,a1)*C(a0,-a1)
t1 = t.contract_metric(C)
assert t1.equals(-D)
t = C(a1,-a0)*C(a0,-a1)
t1 = t.contract_metric(C)
assert t1.equals(D)
t = C(a0,a1)*B(-a1,-a0)
t1 = t.contract_metric(C)
t1 = t1.canon_bp()
assert _is_equal(t1, B(a0,-a0))
t = C(a1,a0)*B(-a1,-a0)
t1 = t.contract_metric(C)
assert _is_equal(t1, -B(a0,-a0))
t = C(a0,-a1)*B(a1,-a0)
t1 = t.contract_metric(C)
assert _is_equal(t1, -B(a0,-a0))
t = C(-a0,a1)*B(-a1,a0)
t1 = t.contract_metric(C)
assert _is_equal(t1, -B(a0,-a0))
t = C(-a0,-a1)*B(a1,a0)
t1 = t.contract_metric(C)
assert _is_equal(t1, B(a0,-a0))
t = C(-a1, a0)*B(a1,-a0)
t1 = t.contract_metric(C)
assert _is_equal(t1, B(a0,-a0))
t = C(a0,a1)*psi(-a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, psi(a0))
t = C(a1,a0)*psi(-a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, -psi(a0))
t = C(a0,a1)*chi(-a0)*psi(-a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, -chi(a1)*psi(-a1))
t = C(a1,a0)*chi(-a0)*psi(-a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, chi(a1)*psi(-a1))
t = C(-a1,a0)*chi(-a0)*psi(a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, chi(-a1)*psi(a1))
t = C(a0,-a1)*chi(-a0)*psi(a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, -chi(-a1)*psi(a1))
t = C(-a0,-a1)*chi(a0)*psi(a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, chi(-a1)*psi(a1))
t = C(-a1,-a0)*chi(a0)*psi(a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, -chi(-a1)*psi(a1))
t = C(-a1,-a0)*B(a0,a2)*psi(a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, -B(-a1,a2)*psi(a1))
t = C(a1,a0)*B(-a2,-a0)*psi(-a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, B(-a2,a1)*psi(-a1))
def test_epsilon():
Lorentz = TensorIndexType('Lorentz', dim=4, dummy_name='L')
a, b, c, d, e = tensor_indices('a,b,c,d,e', Lorentz)
epsilon = Lorentz.epsilon
p, q, r, s = tensor_heads('p,q,r,s', [Lorentz])
t = epsilon(b,a,c,d)
t1 = t.canon_bp()
assert t1 == -epsilon(a,b,c,d)
t = epsilon(c,b,d,a)
t1 = t.canon_bp()
assert t1 == epsilon(a,b,c,d)
t = epsilon(c,a,d,b)
t1 = t.canon_bp()
assert t1 == -epsilon(a,b,c,d)
t = epsilon(a,b,c,d)*p(-a)*q(-b)
t1 = t.canon_bp()
assert t1 == epsilon(c,d,a,b)*p(-a)*q(-b)
t = epsilon(c,b,d,a)*p(-a)*q(-b)
t1 = t.canon_bp()
assert t1 == epsilon(c,d,a,b)*p(-a)*q(-b)
t = epsilon(c,a,d,b)*p(-a)*q(-b)
t1 = t.canon_bp()
assert t1 == -epsilon(c,d,a,b)*p(-a)*q(-b)
t = epsilon(c,a,d,b)*p(-a)*p(-b)
t1 = t.canon_bp()
assert t1 == 0
t = epsilon(c,a,d,b)*p(-a)*q(-b) + epsilon(a,b,c,d)*p(-b)*q(-a)
t1 = t.canon_bp()
assert t1 == -2*epsilon(c,d,a,b)*p(-a)*q(-b)
# Test that epsilon can be create with a SymPy integer:
Lorentz = TensorIndexType('Lorentz', dim=Integer(4), dummy_name='L')
epsilon = Lorentz.epsilon
assert isinstance(epsilon, TensorHead)
def test_contract_delta1():
# see Group Theory by Cvitanovic page 9
n = Symbol('n')
Color = TensorIndexType('Color', dim=n, dummy_name='C')
a, b, c, d, e, f = tensor_indices('a,b,c,d,e,f', Color)
delta = Color.delta
def idn(a, b, d, c):
assert a.is_up and d.is_up
assert not (b.is_up or c.is_up)
return delta(a,c)*delta(d,b)
def T(a, b, d, c):
assert a.is_up and d.is_up
assert not (b.is_up or c.is_up)
return delta(a,b)*delta(d,c)
def P1(a, b, c, d):
return idn(a,b,c,d) - 1/n*T(a,b,c,d)
def P2(a, b, c, d):
return 1/n*T(a,b,c,d)
t = P1(a, -b, e, -f)*P1(f, -e, d, -c)
t1 = t.contract_delta(delta)
assert canon_bp(t1 - P1(a, -b, d, -c)) == 0
t = P2(a, -b, e, -f)*P2(f, -e, d, -c)
t1 = t.contract_delta(delta)
assert t1 == P2(a, -b, d, -c)
t = P1(a, -b, e, -f)*P2(f, -e, d, -c)
t1 = t.contract_delta(delta)
assert t1 == 0
t = P1(a, -b, b, -a)
t1 = t.contract_delta(delta)
assert t1.equals(n**2 - 1)
@filter_warnings_decorator
def test_fun():
D = Symbol('D')
Lorentz = TensorIndexType('Lorentz', dim=D, dummy_name='L')
a, b, c, d, e = tensor_indices('a,b,c,d,e', Lorentz)
g = Lorentz.metric
p, q = tensor_heads('p q', [Lorentz])
t = q(c)*p(a)*q(b) + g(a,b)*g(c,d)*q(-d)
assert t(a,b,c) == t
assert canon_bp(t - t(b,a,c) - q(c)*p(a)*q(b) + q(c)*p(b)*q(a)) == 0
assert t(b,c,d) == q(d)*p(b)*q(c) + g(b,c)*g(d,e)*q(-e)
t1 = t.substitute_indices((a,b),(b,a))
assert canon_bp(t1 - q(c)*p(b)*q(a) - g(a,b)*g(c,d)*q(-d)) == 0
# check that g_{a b; c} = 0
# example taken from L. Brewin
# "A brief introduction to Cadabra" arxiv:0903.2085
# dg_{a b c} = \partial_{a} g_{b c} is symmetric in b, c
dg = TensorHead('dg', [Lorentz]*3, TensorSymmetry.direct_product(1, 2))
# gamma^a_{b c} is the Christoffel symbol
gamma = S.Half*g(a,d)*(dg(-b,-d,-c) + dg(-c,-b,-d) - dg(-d,-b,-c))
# t = g_{a b; c}
t = dg(-c,-a,-b) - g(-a,-d)*gamma(d,-b,-c) - g(-b,-d)*gamma(d,-a,-c)
t = t.contract_metric(g)
assert t == 0
t = q(c)*p(a)*q(b)
assert t(b,c,d) == q(d)*p(b)*q(c)
def test_TensorManager():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
LorentzH = TensorIndexType('LorentzH', dummy_name='LH')
i, j = tensor_indices('i,j', Lorentz)
ih, jh = tensor_indices('ih,jh', LorentzH)
p, q = tensor_heads('p q', [Lorentz])
ph, qh = tensor_heads('ph qh', [LorentzH])
Gsymbol = Symbol('Gsymbol')
GHsymbol = Symbol('GHsymbol')
TensorManager.set_comm(Gsymbol, GHsymbol, 0)
G = TensorHead('G', [Lorentz], TensorSymmetry.no_symmetry(1), Gsymbol)
assert TensorManager._comm_i2symbol[G.comm] == Gsymbol
GH = TensorHead('GH', [LorentzH], TensorSymmetry.no_symmetry(1), GHsymbol)
ps = G(i)*p(-i)
psh = GH(ih)*ph(-ih)
t = ps + psh
t1 = t*t
assert canon_bp(t1 - ps*ps - 2*ps*psh - psh*psh) == 0
qs = G(i)*q(-i)
qsh = GH(ih)*qh(-ih)
assert _is_equal(ps*qsh, qsh*ps)
assert not _is_equal(ps*qs, qs*ps)
n = TensorManager.comm_symbols2i(Gsymbol)
assert TensorManager.comm_i2symbol(n) == Gsymbol
assert GHsymbol in TensorManager._comm_symbols2i
raises(ValueError, lambda: TensorManager.set_comm(GHsymbol, 1, 2))
TensorManager.set_comms((Gsymbol,GHsymbol,0),(Gsymbol,1,1))
assert TensorManager.get_comm(n, 1) == TensorManager.get_comm(1, n) == 1
TensorManager.clear()
assert TensorManager.comm == [{0:0, 1:0, 2:0}, {0:0, 1:1, 2:None}, {0:0, 1:None}]
assert GHsymbol not in TensorManager._comm_symbols2i
nh = TensorManager.comm_symbols2i(GHsymbol)
assert TensorManager.comm_i2symbol(nh) == GHsymbol
assert GHsymbol in TensorManager._comm_symbols2i
def test_hash():
D = Symbol('D')
Lorentz = TensorIndexType('Lorentz', dim=D, dummy_name='L')
a, b, c, d, e = tensor_indices('a,b,c,d,e', Lorentz)
g = Lorentz.metric
p, q = tensor_heads('p q', [Lorentz])
p_type = p.args[1]
t1 = p(a)*q(b)
t2 = p(a)*p(b)
assert hash(t1) != hash(t2)
t3 = p(a)*p(b) + g(a,b)
t4 = p(a)*p(b) - g(a,b)
assert hash(t3) != hash(t4)
assert a.func(*a.args) == a
assert Lorentz.func(*Lorentz.args) == Lorentz
assert g.func(*g.args) == g
assert p.func(*p.args) == p
assert p_type.func(*p_type.args) == p_type
assert p(a).func(*(p(a)).args) == p(a)
assert t1.func(*t1.args) == t1
assert t2.func(*t2.args) == t2
assert t3.func(*t3.args) == t3
assert t4.func(*t4.args) == t4
assert hash(a.func(*a.args)) == hash(a)
assert hash(Lorentz.func(*Lorentz.args)) == hash(Lorentz)
assert hash(g.func(*g.args)) == hash(g)
assert hash(p.func(*p.args)) == hash(p)
assert hash(p_type.func(*p_type.args)) == hash(p_type)
assert hash(p(a).func(*(p(a)).args)) == hash(p(a))
assert hash(t1.func(*t1.args)) == hash(t1)
assert hash(t2.func(*t2.args)) == hash(t2)
assert hash(t3.func(*t3.args)) == hash(t3)
assert hash(t4.func(*t4.args)) == hash(t4)
def check_all(obj):
return all([isinstance(_, Basic) for _ in obj.args])
assert check_all(a)
assert check_all(Lorentz)
assert check_all(g)
assert check_all(p)
assert check_all(p_type)
assert check_all(p(a))
assert check_all(t1)
assert check_all(t2)
assert check_all(t3)
assert check_all(t4)
tsymmetry = TensorSymmetry.direct_product(-2, 1, 3)
assert tsymmetry.func(*tsymmetry.args) == tsymmetry
assert hash(tsymmetry.func(*tsymmetry.args)) == hash(tsymmetry)
assert check_all(tsymmetry)
### TEST VALUED TENSORS ###
def _get_valued_base_test_variables():
minkowski = Matrix((
(1, 0, 0, 0),
(0, -1, 0, 0),
(0, 0, -1, 0),
(0, 0, 0, -1),
))
Lorentz = TensorIndexType('Lorentz', dim=4)
Lorentz.data = minkowski
i0, i1, i2, i3, i4 = tensor_indices('i0:5', Lorentz)
E, px, py, pz = symbols('E px py pz')
A = TensorHead('A', [Lorentz])
A.data = [E, px, py, pz]
B = TensorHead('B', [Lorentz], TensorSymmetry.no_symmetry(1), 'Gcomm')
B.data = range(4)
AB = TensorHead("AB", [Lorentz]*2)
AB.data = minkowski
ba_matrix = Matrix((
(1, 2, 3, 4),
(5, 6, 7, 8),
(9, 0, -1, -2),
(-3, -4, -5, -6),
))
BA = TensorHead("BA", [Lorentz]*2)
BA.data = ba_matrix
# Let's test the diagonal metric, with inverted Minkowski metric:
LorentzD = TensorIndexType('LorentzD')
LorentzD.data = [-1, 1, 1, 1]
mu0, mu1, mu2 = tensor_indices('mu0:3', LorentzD)
C = TensorHead('C', [LorentzD])
C.data = [E, px, py, pz]
### non-diagonal metric ###
ndm_matrix = (
(1, 1, 0,),
(1, 0, 1),
(0, 1, 0,),
)
ndm = TensorIndexType("ndm")
ndm.data = ndm_matrix
n0, n1, n2 = tensor_indices('n0:3', ndm)
NA = TensorHead('NA', [ndm])
NA.data = range(10, 13)
NB = TensorHead('NB', [ndm]*2)
NB.data = [[i+j for j in range(10, 13)] for i in range(10, 13)]
NC = TensorHead('NC', [ndm]*3)
NC.data = [[[i+j+k for k in range(4, 7)] for j in range(1, 4)] for i in range(2, 5)]
return (A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4)
@filter_warnings_decorator
def test_valued_tensor_iter():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
list_BA = [Array([1, 2, 3, 4]), Array([5, 6, 7, 8]), Array([9, 0, -1, -2]), Array([-3, -4, -5, -6])]
# iteration on VTensorHead
assert list(A) == [E, px, py, pz]
assert list(ba_matrix) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, -1, -2, -3, -4, -5, -6]
assert list(BA) == list_BA
# iteration on VTensMul
assert list(A(i1)) == [E, px, py, pz]
assert list(BA(i1, i2)) == list_BA
assert list(3 * BA(i1, i2)) == [3 * i for i in list_BA]
assert list(-5 * BA(i1, i2)) == [-5 * i for i in list_BA]
# iteration on VTensAdd
# A(i1) + A(i1)
assert list(A(i1) + A(i1)) == [2*E, 2*px, 2*py, 2*pz]
assert BA(i1, i2) - BA(i1, i2) == 0
assert list(BA(i1, i2) - 2 * BA(i1, i2)) == [-i for i in list_BA]
@filter_warnings_decorator
def test_valued_tensor_covariant_contravariant_elements():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
assert A(-i0)[0] == A(i0)[0]
assert A(-i0)[1] == -A(i0)[1]
assert AB(i0, i1)[1, 1] == -1
assert AB(i0, -i1)[1, 1] == 1
assert AB(-i0, -i1)[1, 1] == -1
assert AB(-i0, i1)[1, 1] == 1
@filter_warnings_decorator
def test_valued_tensor_get_matrix():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
matab = AB(i0, i1).get_matrix()
assert matab == Matrix([
[1, 0, 0, 0],
[0, -1, 0, 0],
[0, 0, -1, 0],
[0, 0, 0, -1],
])
# when alternating contravariant/covariant with [1, -1, -1, -1] metric
# it becomes the identity matrix:
assert AB(i0, -i1).get_matrix() == eye(4)
# covariant and contravariant forms:
assert A(i0).get_matrix() == Matrix([E, px, py, pz])
assert A(-i0).get_matrix() == Matrix([E, -px, -py, -pz])
@filter_warnings_decorator
def test_valued_tensor_contraction():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
assert (A(i0) * A(-i0)).data == E ** 2 - px ** 2 - py ** 2 - pz ** 2
assert (A(i0) * A(-i0)).data == A ** 2
assert (A(i0) * A(-i0)).data == A(i0) ** 2
assert (A(i0) * B(-i0)).data == -px - 2 * py - 3 * pz
for i in range(4):
for j in range(4):
assert (A(i0) * B(-i1))[i, j] == [E, px, py, pz][i] * [0, -1, -2, -3][j]
# test contraction on the alternative Minkowski metric: [-1, 1, 1, 1]
assert (C(mu0) * C(-mu0)).data == -E ** 2 + px ** 2 + py ** 2 + pz ** 2
contrexp = A(i0) * AB(i1, -i0)
assert A(i0).rank == 1
assert AB(i1, -i0).rank == 2
assert contrexp.rank == 1
for i in range(4):
assert contrexp[i] == [E, px, py, pz][i]
@filter_warnings_decorator
def test_valued_tensor_self_contraction():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
assert AB(i0, -i0).data == 4
assert BA(i0, -i0).data == 2
@filter_warnings_decorator
def test_valued_tensor_pow():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
assert C**2 == -E**2 + px**2 + py**2 + pz**2
assert C**1 == sqrt(-E**2 + px**2 + py**2 + pz**2)
assert C(mu0)**2 == C**2
assert C(mu0)**1 == C**1
@filter_warnings_decorator
def test_valued_tensor_expressions():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
x1, x2, x3 = symbols('x1:4')
# test coefficient in contraction:
rank2coeff = x1 * A(i3) * B(i2)
assert rank2coeff[1, 1] == x1 * px
assert rank2coeff[3, 3] == 3 * pz * x1
coeff_expr = ((x1 * A(i4)) * (B(-i4) / x2)).data
assert coeff_expr.expand() == -px*x1/x2 - 2*py*x1/x2 - 3*pz*x1/x2
add_expr = A(i0) + B(i0)
assert add_expr[0] == E
assert add_expr[1] == px + 1
assert add_expr[2] == py + 2
assert add_expr[3] == pz + 3
sub_expr = A(i0) - B(i0)
assert sub_expr[0] == E
assert sub_expr[1] == px - 1
assert sub_expr[2] == py - 2
assert sub_expr[3] == pz - 3
assert (add_expr * B(-i0)).data == -px - 2*py - 3*pz - 14
expr1 = x1*A(i0) + x2*B(i0)
expr2 = expr1 * B(i1) * (-4)
expr3 = expr2 + 3*x3*AB(i0, i1)
expr4 = expr3 / 2
assert expr4 * 2 == expr3
expr5 = (expr4 * BA(-i1, -i0))
assert expr5.data.expand() == 28*E*x1 + 12*px*x1 + 20*py*x1 + 28*pz*x1 + 136*x2 + 3*x3
@filter_warnings_decorator
def test_valued_tensor_add_scalar():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
# one scalar summand after the contracted tensor
expr1 = A(i0)*A(-i0) - (E**2 - px**2 - py**2 - pz**2)
assert expr1.data == 0
# multiple scalar summands in front of the contracted tensor
expr2 = E**2 - px**2 - py**2 - pz**2 - A(i0)*A(-i0)
assert expr2.data == 0
# multiple scalar summands after the contracted tensor
expr3 = A(i0)*A(-i0) - E**2 + px**2 + py**2 + pz**2
assert expr3.data == 0
# multiple scalar summands and multiple tensors
expr4 = C(mu0)*C(-mu0) + 2*E**2 - 2*px**2 - 2*py**2 - 2*pz**2 - A(i0)*A(-i0)
assert expr4.data == 0
@filter_warnings_decorator
def test_noncommuting_components():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
euclid = TensorIndexType('Euclidean')
euclid.data = [1, 1]
i1, i2, i3 = tensor_indices('i1:4', euclid)
a, b, c, d = symbols('a b c d', commutative=False)
V1 = TensorHead('V1', [euclid]*2)
V1.data = [[a, b], (c, d)]
V2 = TensorHead('V2', [euclid]*2)
V2.data = [[a, c], [b, d]]
vtp = V1(i1, i2) * V2(-i2, -i1)
assert vtp.data == a**2 + b**2 + c**2 + d**2
assert vtp.data != a**2 + 2*b*c + d**2
vtp2 = V1(i1, i2)*V1(-i2, -i1)
assert vtp2.data == a**2 + b*c + c*b + d**2
assert vtp2.data != a**2 + 2*b*c + d**2
Vc = (b * V1(i1, -i1)).data
assert Vc.expand() == b * a + b * d
@filter_warnings_decorator
def test_valued_non_diagonal_metric():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
mmatrix = Matrix(ndm_matrix)
assert (NA(n0)*NA(-n0)).data == (NA(n0).get_matrix().T * mmatrix * NA(n0).get_matrix())[0, 0]
@filter_warnings_decorator
def test_valued_assign_numpy_ndarray():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
# this is needed to make sure that a numpy.ndarray can be assigned to a
# tensor.
arr = [E+1, px-1, py, pz]
A.data = Array(arr)
for i in range(4):
assert A(i0).data[i] == arr[i]
qx, qy, qz = symbols('qx qy qz')
A(-i0).data = Array([E, qx, qy, qz])
for i in range(4):
assert A(i0).data[i] == [E, -qx, -qy, -qz][i]
assert A.data[i] == [E, -qx, -qy, -qz][i]
# test on multi-indexed tensors.
random_4x4_data = [[(i**3-3*i**2)%(j+7) for i in range(4)] for j in range(4)]
AB(-i0, -i1).data = random_4x4_data
for i in range(4):
for j in range(4):
assert AB(i0, i1).data[i, j] == random_4x4_data[i][j]*(-1 if i else 1)*(-1 if j else 1)
assert AB(-i0, i1).data[i, j] == random_4x4_data[i][j]*(-1 if j else 1)
assert AB(i0, -i1).data[i, j] == random_4x4_data[i][j]*(-1 if i else 1)
assert AB(-i0, -i1).data[i, j] == random_4x4_data[i][j]
AB(-i0, i1).data = random_4x4_data
for i in range(4):
for j in range(4):
assert AB(i0, i1).data[i, j] == random_4x4_data[i][j]*(-1 if i else 1)
assert AB(-i0, i1).data[i, j] == random_4x4_data[i][j]
assert AB(i0, -i1).data[i, j] == random_4x4_data[i][j]*(-1 if i else 1)*(-1 if j else 1)
assert AB(-i0, -i1).data[i, j] == random_4x4_data[i][j]*(-1 if j else 1)
@filter_warnings_decorator
def test_valued_metric_inverse():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
# let's assign some fancy matrix, just to verify it:
# (this has no physical sense, it's just testing sympy);
# it is symmetrical:
md = [[2, 2, 2, 1], [2, 3, 1, 0], [2, 1, 2, 3], [1, 0, 3, 2]]
Lorentz.data = md
m = Matrix(md)
metric = Lorentz.metric
minv = m.inv()
meye = eye(4)
# the Kronecker Delta:
KD = Lorentz.get_kronecker_delta()
for i in range(4):
for j in range(4):
assert metric(i0, i1).data[i, j] == m[i, j]
assert metric(-i0, -i1).data[i, j] == minv[i, j]
assert metric(i0, -i1).data[i, j] == meye[i, j]
assert metric(-i0, i1).data[i, j] == meye[i, j]
assert metric(i0, i1)[i, j] == m[i, j]
assert metric(-i0, -i1)[i, j] == minv[i, j]
assert metric(i0, -i1)[i, j] == meye[i, j]
assert metric(-i0, i1)[i, j] == meye[i, j]
assert KD(i0, -i1)[i, j] == meye[i, j]
@filter_warnings_decorator
def test_valued_canon_bp_swapaxes():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
e1 = A(i1)*A(i0)
e2 = e1.canon_bp()
assert e2 == A(i0)*A(i1)
for i in range(4):
for j in range(4):
assert e1[i, j] == e2[j, i]
o1 = B(i2)*A(i1)*B(i0)
o2 = o1.canon_bp()
for i in range(4):
for j in range(4):
for k in range(4):
assert o1[i, j, k] == o2[j, i, k]
@filter_warnings_decorator
def test_valued_components_with_wrong_symmetry():
IT = TensorIndexType('IT', dim=3)
i0, i1, i2, i3 = tensor_indices('i0:4', IT)
IT.data = [1, 1, 1]
A_nosym = TensorHead('A', [IT]*2)
A_sym = TensorHead('A', [IT]*2, TensorSymmetry.fully_symmetric(2))
A_antisym = TensorHead('A', [IT]*2, TensorSymmetry.fully_symmetric(-2))
mat_nosym = Matrix([[1,2,3],[4,5,6],[7,8,9]])
mat_sym = mat_nosym + mat_nosym.T
mat_antisym = mat_nosym - mat_nosym.T
A_nosym.data = mat_nosym
A_nosym.data = mat_sym
A_nosym.data = mat_antisym
def assign(A, dat):
A.data = dat
A_sym.data = mat_sym
raises(ValueError, lambda: assign(A_sym, mat_nosym))
raises(ValueError, lambda: assign(A_sym, mat_antisym))
A_antisym.data = mat_antisym
raises(ValueError, lambda: assign(A_antisym, mat_sym))
raises(ValueError, lambda: assign(A_antisym, mat_nosym))
A_sym.data = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
A_antisym.data = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
@filter_warnings_decorator
def test_issue_10972_TensMul_data():
Lorentz = TensorIndexType('Lorentz', metric_symmetry=1, dummy_name='i', dim=2)
Lorentz.data = [-1, 1]
mu, nu, alpha, beta = tensor_indices('\\mu, \\nu, \\alpha, \\beta',
Lorentz)
u = TensorHead('u', [Lorentz])
u.data = [1, 0]
F = TensorHead('F', [Lorentz]*2, TensorSymmetry.fully_symmetric(-2))
F.data = [[0, 1],
[-1, 0]]
mul_1 = F(mu, alpha) * u(-alpha) * F(nu, beta) * u(-beta)
assert (mul_1.data == Array([[0, 0], [0, 1]]))
mul_2 = F(mu, alpha) * F(nu, beta) * u(-alpha) * u(-beta)
assert (mul_2.data == mul_1.data)
assert ((mul_1 + mul_1).data == 2 * mul_1.data)
@filter_warnings_decorator
def test_TensMul_data():
Lorentz = TensorIndexType('Lorentz', metric_symmetry=1, dummy_name='L', dim=4)
Lorentz.data = [-1, 1, 1, 1]
mu, nu, alpha, beta = tensor_indices('\\mu, \\nu, \\alpha, \\beta',
Lorentz)
u = TensorHead('u', [Lorentz])
u.data = [1, 0, 0, 0]
F = TensorHead('F', [Lorentz]*2, TensorSymmetry.fully_symmetric(-2))
Ex, Ey, Ez, Bx, By, Bz = symbols('E_x E_y E_z B_x B_y B_z')
F.data = [
[0, Ex, Ey, Ez],
[-Ex, 0, Bz, -By],
[-Ey, -Bz, 0, Bx],
[-Ez, By, -Bx, 0]]
E = F(mu, nu) * u(-nu)
assert ((E(mu) * E(nu)).data ==
Array([[0, 0, 0, 0],
[0, Ex ** 2, Ex * Ey, Ex * Ez],
[0, Ex * Ey, Ey ** 2, Ey * Ez],
[0, Ex * Ez, Ey * Ez, Ez ** 2]])
)
assert ((E(mu) * E(nu)).canon_bp().data == (E(mu) * E(nu)).data)
assert ((F(mu, alpha) * F(beta, nu) * u(-alpha) * u(-beta)).data ==
- (E(mu) * E(nu)).data
)
assert ((F(alpha, mu) * F(beta, nu) * u(-alpha) * u(-beta)).data ==
(E(mu) * E(nu)).data
)
g = TensorHead('g', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
g.data = Lorentz.data
# tensor 'perp' is orthogonal to vector 'u'
perp = u(mu) * u(nu) + g(mu, nu)
mul_1 = u(-mu) * perp(mu, nu)
assert (mul_1.data == Array([0, 0, 0, 0]))
mul_2 = u(-mu) * perp(mu, alpha) * perp(nu, beta)
assert (mul_2.data == Array.zeros(4, 4, 4))
Fperp = perp(mu, alpha) * perp(nu, beta) * F(-alpha, -beta)
assert (Fperp.data[0, :] == Array([0, 0, 0, 0]))
assert (Fperp.data[:, 0] == Array([0, 0, 0, 0]))
mul_3 = u(-mu) * Fperp(mu, nu)
assert (mul_3.data == Array([0, 0, 0, 0]))
@filter_warnings_decorator
def test_issue_11020_TensAdd_data():
Lorentz = TensorIndexType('Lorentz', metric_symmetry=1, dummy_name='i', dim=2)
Lorentz.data = [-1, 1]
a, b, c, d = tensor_indices('a, b, c, d', Lorentz)
i0, i1 = tensor_indices('i_0:2', Lorentz)
# metric tensor
g = TensorHead('g', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
g.data = Lorentz.data
u = TensorHead('u', [Lorentz])
u.data = [1, 0]
add_1 = g(b, c) * g(d, i0) * u(-i0) - g(b, c) * u(d)
assert (add_1.data == Array.zeros(2, 2, 2))
# Now let us replace index `d` with `a`:
add_2 = g(b, c) * g(a, i0) * u(-i0) - g(b, c) * u(a)
assert (add_2.data == Array.zeros(2, 2, 2))
# some more tests
# perp is tensor orthogonal to u^\mu
perp = u(a) * u(b) + g(a, b)
mul_1 = u(-a) * perp(a, b)
assert (mul_1.data == Array([0, 0]))
mul_2 = u(-c) * perp(c, a) * perp(d, b)
assert (mul_2.data == Array.zeros(2, 2, 2))
def test_index_iteration():
L = TensorIndexType("Lorentz", dummy_name="L")
i0, i1, i2, i3, i4 = tensor_indices('i0:5', L)
L0 = tensor_indices('L_0', L)
L1 = tensor_indices('L_1', L)
A = TensorHead("A", [L, L])
B = TensorHead("B", [L, L], TensorSymmetry.fully_symmetric(2))
e1 = A(i0,i2)
e2 = A(i0,-i0)
e3 = A(i0,i1)*B(i2,i3)
e4 = A(i0,i1)*B(i2,-i1)
e5 = A(i0,i1)*B(-i0,-i1)
e6 = e1 + e4
assert list(e1._iterate_free_indices) == [(i0, (1, 0)), (i2, (1, 1))]
assert list(e1._iterate_dummy_indices) == []
assert list(e1._iterate_indices) == [(i0, (1, 0)), (i2, (1, 1))]
assert list(e2._iterate_free_indices) == []
assert list(e2._iterate_dummy_indices) == [(L0, (1, 0)), (-L0, (1, 1))]
assert list(e2._iterate_indices) == [(L0, (1, 0)), (-L0, (1, 1))]
assert list(e3._iterate_free_indices) == [(i0, (0, 1, 0)), (i1, (0, 1, 1)), (i2, (1, 1, 0)), (i3, (1, 1, 1))]
assert list(e3._iterate_dummy_indices) == []
assert list(e3._iterate_indices) == [(i0, (0, 1, 0)), (i1, (0, 1, 1)), (i2, (1, 1, 0)), (i3, (1, 1, 1))]
assert list(e4._iterate_free_indices) == [(i0, (0, 1, 0)), (i2, (1, 1, 0))]
assert list(e4._iterate_dummy_indices) == [(L0, (0, 1, 1)), (-L0, (1, 1, 1))]
assert list(e4._iterate_indices) == [(i0, (0, 1, 0)), (L0, (0, 1, 1)), (i2, (1, 1, 0)), (-L0, (1, 1, 1))]
assert list(e5._iterate_free_indices) == []
assert list(e5._iterate_dummy_indices) == [(L0, (0, 1, 0)), (L1, (0, 1, 1)), (-L0, (1, 1, 0)), (-L1, (1, 1, 1))]
assert list(e5._iterate_indices) == [(L0, (0, 1, 0)), (L1, (0, 1, 1)), (-L0, (1, 1, 0)), (-L1, (1, 1, 1))]
assert list(e6._iterate_free_indices) == [(i0, (0, 0, 1, 0)), (i2, (0, 1, 1, 0)), (i0, (1, 1, 0)), (i2, (1, 1, 1))]
assert list(e6._iterate_dummy_indices) == [(L0, (0, 0, 1, 1)), (-L0, (0, 1, 1, 1))]
assert list(e6._iterate_indices) == [(i0, (0, 0, 1, 0)), (L0, (0, 0, 1, 1)), (i2, (0, 1, 1, 0)), (-L0, (0, 1, 1, 1)), (i0, (1, 1, 0)), (i2, (1, 1, 1))]
assert e1.get_indices() == [i0, i2]
assert e1.get_free_indices() == [i0, i2]
assert e2.get_indices() == [L0, -L0]
assert e2.get_free_indices() == []
assert e3.get_indices() == [i0, i1, i2, i3]
assert e3.get_free_indices() == [i0, i1, i2, i3]
assert e4.get_indices() == [i0, L0, i2, -L0]
assert e4.get_free_indices() == [i0, i2]
assert e5.get_indices() == [L0, L1, -L0, -L1]
assert e5.get_free_indices() == []
def test_tensor_expand():
L = TensorIndexType("L")
i, j, k = tensor_indices("i j k", L)
L_0 = TensorIndex("L_0", L)
A, B, C, D = tensor_heads("A B C D", [L])
assert isinstance(Add(A(i), B(i)), TensAdd)
assert isinstance(expand(A(i)+B(i)), TensAdd)
expr = A(i)*(A(-i)+B(-i))
assert expr.args == (A(L_0), A(-L_0) + B(-L_0))
assert expr != A(i)*A(-i) + A(i)*B(-i)
assert expr.expand() == A(i)*A(-i) + A(i)*B(-i)
assert str(expr) == "A(L_0)*(A(-L_0) + B(-L_0))"
expr = A(i)*A(j) + A(i)*B(j)
assert str(expr) == "A(i)*A(j) + A(i)*B(j)"
expr = A(-i)*(A(i)*A(j) + A(i)*B(j)*C(k)*C(-k))
assert expr != A(-i)*A(i)*A(j) + A(-i)*A(i)*B(j)*C(k)*C(-k)
assert expr.expand() == A(-i)*A(i)*A(j) + A(-i)*A(i)*B(j)*C(k)*C(-k)
assert str(expr) == "A(-L_0)*(A(L_0)*A(j) + A(L_0)*B(j)*C(L_1)*C(-L_1))"
assert str(expr.canon_bp()) == 'A(j)*A(L_0)*A(-L_0) + A(L_0)*A(-L_0)*B(j)*C(L_1)*C(-L_1)'
expr = A(-i)*(2*A(i)*A(j) + A(i)*B(j))
assert expr.expand() == 2*A(-i)*A(i)*A(j) + A(-i)*A(i)*B(j)
expr = 2*A(i)*A(-i)
assert expr.coeff == 2
expr = A(i)*(B(j)*C(k) + C(j)*(A(k) + D(k)))
assert str(expr) == "A(i)*(B(j)*C(k) + C(j)*(A(k) + D(k)))"
assert str(expr.expand()) == "A(i)*B(j)*C(k) + A(i)*C(j)*A(k) + A(i)*C(j)*D(k)"
assert isinstance(TensMul(3), TensMul)
tm = TensMul(3).doit()
assert tm == 3
assert isinstance(tm, Integer)
p1 = B(j)*B(-j) + B(j)*C(-j)
p2 = C(-i)*p1
p3 = A(i)*p2
assert p3.expand() == A(i)*C(-i)*B(j)*B(-j) + A(i)*C(-i)*B(j)*C(-j)
expr = A(i)*(B(-i) + C(-i)*(B(j)*B(-j) + B(j)*C(-j)))
assert expr.expand() == A(i)*B(-i) + A(i)*C(-i)*B(j)*B(-j) + A(i)*C(-i)*B(j)*C(-j)
expr = C(-i)*(B(j)*B(-j) + B(j)*C(-j))
assert expr.expand() == C(-i)*B(j)*B(-j) + C(-i)*B(j)*C(-j)
def test_tensor_alternative_construction():
L = TensorIndexType("L")
i0, i1, i2, i3 = tensor_indices('i0:4', L)
A = TensorHead("A", [L])
x, y = symbols("x y")
assert A(i0) == A(Symbol("i0"))
assert A(-i0) == A(-Symbol("i0"))
raises(TypeError, lambda: A(x+y))
raises(ValueError, lambda: A(2*x))
def test_tensor_replacement():
L = TensorIndexType("L")
L2 = TensorIndexType("L2", dim=2)
i, j, k, l = tensor_indices("i j k l", L)
A, B, C, D = tensor_heads("A B C D", [L])
H = TensorHead("H", [L, L])
K = TensorHead("K", [L]*4)
expr = H(i, j)
repl = {H(i,-j): [[1,2],[3,4]], L: diag(1, -1)}
assert expr._extract_data(repl) == ([i, j], Array([[1, -2], [3, -4]]))
assert expr.replace_with_arrays(repl) == Array([[1, -2], [3, -4]])
assert expr.replace_with_arrays(repl, [i, j]) == Array([[1, -2], [3, -4]])
assert expr.replace_with_arrays(repl, [i, -j]) == Array([[1, 2], [3, 4]])
assert expr.replace_with_arrays(repl, [-i, j]) == Array([[1, -2], [-3, 4]])
assert expr.replace_with_arrays(repl, [-i, -j]) == Array([[1, 2], [-3, -4]])
assert expr.replace_with_arrays(repl, [j, i]) == Array([[1, 3], [-2, -4]])
assert expr.replace_with_arrays(repl, [j, -i]) == Array([[1, -3], [-2, 4]])
assert expr.replace_with_arrays(repl, [-j, i]) == Array([[1, 3], [2, 4]])
assert expr.replace_with_arrays(repl, [-j, -i]) == Array([[1, -3], [2, -4]])
# Test stability of optional parameter 'indices'
assert expr.replace_with_arrays(repl) == Array([[1, -2], [3, -4]])
expr = H(i,j)
repl = {H(i,j): [[1,2],[3,4]], L: diag(1, -1)}
assert expr._extract_data(repl) == ([i, j], Array([[1, 2], [3, 4]]))
assert expr.replace_with_arrays(repl) == Array([[1, 2], [3, 4]])
assert expr.replace_with_arrays(repl, [i, j]) == Array([[1, 2], [3, 4]])
assert expr.replace_with_arrays(repl, [i, -j]) == Array([[1, -2], [3, -4]])
assert expr.replace_with_arrays(repl, [-i, j]) == Array([[1, 2], [-3, -4]])
assert expr.replace_with_arrays(repl, [-i, -j]) == Array([[1, -2], [-3, 4]])
assert expr.replace_with_arrays(repl, [j, i]) == Array([[1, 3], [2, 4]])
assert expr.replace_with_arrays(repl, [j, -i]) == Array([[1, -3], [2, -4]])
assert expr.replace_with_arrays(repl, [-j, i]) == Array([[1, 3], [-2, -4]])
assert expr.replace_with_arrays(repl, [-j, -i]) == Array([[1, -3], [-2, 4]])
# Not the same indices:
expr = H(i,k)
repl = {H(i,j): [[1,2],[3,4]], L: diag(1, -1)}
assert expr._extract_data(repl) == ([i, k], Array([[1, 2], [3, 4]]))
expr = A(i)*A(-i)
repl = {A(i): [1,2], L: diag(1, -1)}
assert expr._extract_data(repl) == ([], -3)
assert expr.replace_with_arrays(repl, []) == -3
expr = K(i, j, -j, k)*A(-i)*A(-k)
repl = {A(i): [1, 2], K(i,j,k,l): Array([1]*2**4).reshape(2,2,2,2), L: diag(1, -1)}
assert expr._extract_data(repl)
expr = H(j, k)
repl = {H(i,j): [[1,2],[3,4]], L: diag(1, -1)}
raises(ValueError, lambda: expr._extract_data(repl))
expr = A(i)
repl = {B(i): [1, 2]}
raises(ValueError, lambda: expr._extract_data(repl))
expr = A(i)
repl = {A(i): [[1, 2], [3, 4]]}
raises(ValueError, lambda: expr._extract_data(repl))
# TensAdd:
expr = A(k)*H(i, j) + B(k)*H(i, j)
repl = {A(k): [1], B(k): [1], H(i, j): [[1, 2],[3,4]], L:diag(1,1)}
assert expr._extract_data(repl) == ([k, i, j], Array([[[2, 4], [6, 8]]]))
assert expr.replace_with_arrays(repl, [k, i, j]) == Array([[[2, 4], [6, 8]]])
assert expr.replace_with_arrays(repl, [k, j, i]) == Array([[[2, 6], [4, 8]]])
expr = A(k)*A(-k) + 100
repl = {A(k): [2, 3], L: diag(1, 1)}
assert expr.replace_with_arrays(repl, []) == 113
## Symmetrization:
expr = H(i, j) + H(j, i)
repl = {H(i, j): [[1, 2], [3, 4]]}
assert expr._extract_data(repl) == ([i, j], Array([[2, 5], [5, 8]]))
assert expr.replace_with_arrays(repl, [i, j]) == Array([[2, 5], [5, 8]])
assert expr.replace_with_arrays(repl, [j, i]) == Array([[2, 5], [5, 8]])
## Anti-symmetrization:
expr = H(i, j) - H(j, i)
repl = {H(i, j): [[1, 2], [3, 4]]}
assert expr.replace_with_arrays(repl, [i, j]) == Array([[0, -1], [1, 0]])
assert expr.replace_with_arrays(repl, [j, i]) == Array([[0, 1], [-1, 0]])
# Tensors with contractions in replacements:
expr = K(i, j, k, -k)
repl = {K(i, j, k, -k): [[1, 2], [3, 4]]}
assert expr._extract_data(repl) == ([i, j], Array([[1, 2], [3, 4]]))
expr = H(i, -i)
repl = {H(i, -i): 42}
assert expr._extract_data(repl) == ([], 42)
expr = H(i, -i)
repl = {
H(-i, -j): Array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, -1]]),
L: Array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, -1]]),
}
assert expr._extract_data(repl) == ([], 4)
# Replace with array, raise exception if indices are not compatible:
expr = A(i)*A(j)
repl = {A(i): [1, 2]}
raises(ValueError, lambda: expr.replace_with_arrays(repl, [j]))
# Raise exception if array dimension is not compatible:
expr = A(i)
repl = {A(i): [[1, 2]]}
raises(ValueError, lambda: expr.replace_with_arrays(repl, [i]))
# TensorIndexType with dimension, wrong dimension in replacement array:
u1, u2, u3 = tensor_indices("u1:4", L2)
U = TensorHead("U", [L2])
expr = U(u1)*U(-u2)
repl = {U(u1): [[1]]}
raises(ValueError, lambda: expr.replace_with_arrays(repl, [u1, -u2]))
def test_rewrite_tensor_to_Indexed():
L = TensorIndexType("L", dim=4)
A = TensorHead("A", [L]*4)
B = TensorHead("B", [L])
i0, i1, i2, i3 = symbols("i0:4")
L_0, L_1 = symbols("L_0:2")
a1 = A(i0, i1, i2, i3)
assert a1.rewrite(Indexed) == Indexed(Symbol("A"), i0, i1, i2, i3)
a2 = A(i0, -i0, i2, i3)
assert a2.rewrite(Indexed) == Sum(Indexed(Symbol("A"), L_0, L_0, i2, i3), (L_0, 0, 3))
a3 = a2 + A(i2, i3, i0, -i0)
assert a3.rewrite(Indexed) == \
Sum(Indexed(Symbol("A"), L_0, L_0, i2, i3), (L_0, 0, 3)) +\
Sum(Indexed(Symbol("A"), i2, i3, L_0, L_0), (L_0, 0, 3))
b1 = B(-i0)*a1
assert b1.rewrite(Indexed) == Sum(Indexed(Symbol("B"), L_0)*Indexed(Symbol("A"), L_0, i1, i2, i3), (L_0, 0, 3))
b2 = B(-i3)*a2
assert b2.rewrite(Indexed) == Sum(Indexed(Symbol("B"), L_1)*Indexed(Symbol("A"), L_0, L_0, i2, L_1), (L_0, 0, 3), (L_1, 0, 3))
def test_tensorsymmetry():
with warns_deprecated_sympy():
tensorsymmetry([1]*2)
def test_tensorhead():
with warns_deprecated_sympy():
tensorhead('A', [])
def test_TensorType():
with warns_deprecated_sympy():
sym2 = TensorSymmetry.fully_symmetric(2)
Lorentz = TensorIndexType('Lorentz')
S2 = TensorType([Lorentz]*2, sym2)
assert isinstance(S2, TensorType)
|
3eef79d73e3261830e5c129c36d787eb785303198d5fcef4da74901ffa5c8851 | from sympy.core import symbols, S, Pow, Function
from sympy.functions import exp
from sympy.testing.pytest import raises
from sympy.tensor.indexed import Idx, IndexedBase
from sympy.tensor.index_methods import IndexConformanceException
from sympy.tensor.index_methods import (get_contraction_structure, get_indices)
def test_trivial_indices():
x, y = symbols('x y')
assert get_indices(x) == (set(), {})
assert get_indices(x*y) == (set(), {})
assert get_indices(x + y) == (set(), {})
assert get_indices(x**y) == (set(), {})
def test_get_indices_Indexed():
x = IndexedBase('x')
i, j = Idx('i'), Idx('j')
assert get_indices(x[i, j]) == ({i, j}, {})
assert get_indices(x[j, i]) == ({j, i}, {})
def test_get_indices_Idx():
f = Function('f')
i, j = Idx('i'), Idx('j')
assert get_indices(f(i)*j) == ({i, j}, {})
assert get_indices(f(j, i)) == ({j, i}, {})
assert get_indices(f(i)*i) == (set(), {})
def test_get_indices_mul():
x = IndexedBase('x')
y = IndexedBase('y')
i, j = Idx('i'), Idx('j')
assert get_indices(x[j]*y[i]) == ({i, j}, {})
assert get_indices(x[i]*y[j]) == ({i, j}, {})
def test_get_indices_exceptions():
x = IndexedBase('x')
y = IndexedBase('y')
i, j = Idx('i'), Idx('j')
raises(IndexConformanceException, lambda: get_indices(x[i] + y[j]))
def test_scalar_broadcast():
x = IndexedBase('x')
y = IndexedBase('y')
i, j = Idx('i'), Idx('j')
assert get_indices(x[i] + y[i, i]) == ({i}, {})
assert get_indices(x[i] + y[j, j]) == ({i}, {})
def test_get_indices_add():
x = IndexedBase('x')
y = IndexedBase('y')
A = IndexedBase('A')
i, j, k = Idx('i'), Idx('j'), Idx('k')
assert get_indices(x[i] + 2*y[i]) == ({i}, {})
assert get_indices(y[i] + 2*A[i, j]*x[j]) == ({i}, {})
assert get_indices(y[i] + 2*(x[i] + A[i, j]*x[j])) == ({i}, {})
assert get_indices(y[i] + x[i]*(A[j, j] + 1)) == ({i}, {})
assert get_indices(
y[i] + x[i]*x[j]*(y[j] + A[j, k]*x[k])) == ({i}, {})
def test_get_indices_Pow():
x = IndexedBase('x')
y = IndexedBase('y')
A = IndexedBase('A')
i, j, k = Idx('i'), Idx('j'), Idx('k')
assert get_indices(Pow(x[i], y[j])) == ({i, j}, {})
assert get_indices(Pow(x[i, k], y[j, k])) == ({i, j, k}, {})
assert get_indices(Pow(A[i, k], y[k] + A[k, j]*x[j])) == ({i, k}, {})
assert get_indices(Pow(2, x[i])) == get_indices(exp(x[i]))
# test of a design decision, this may change:
assert get_indices(Pow(x[i], 2)) == ({i}, {})
def test_get_contraction_structure_basic():
x = IndexedBase('x')
y = IndexedBase('y')
i, j = Idx('i'), Idx('j')
assert get_contraction_structure(x[i]*y[j]) == {None: {x[i]*y[j]}}
assert get_contraction_structure(x[i] + y[j]) == {None: {x[i], y[j]}}
assert get_contraction_structure(x[i]*y[i]) == {(i,): {x[i]*y[i]}}
assert get_contraction_structure(
1 + x[i]*y[i]) == {None: {S.One}, (i,): {x[i]*y[i]}}
assert get_contraction_structure(x[i]**y[i]) == {None: {x[i]**y[i]}}
def test_get_contraction_structure_complex():
x = IndexedBase('x')
y = IndexedBase('y')
A = IndexedBase('A')
i, j, k = Idx('i'), Idx('j'), Idx('k')
expr1 = y[i] + A[i, j]*x[j]
d1 = {None: {y[i]}, (j,): {A[i, j]*x[j]}}
assert get_contraction_structure(expr1) == d1
expr2 = expr1*A[k, i] + x[k]
d2 = {None: {x[k]}, (i,): {expr1*A[k, i]}, expr1*A[k, i]: [d1]}
assert get_contraction_structure(expr2) == d2
def test_contraction_structure_simple_Pow():
x = IndexedBase('x')
y = IndexedBase('y')
i, j, k = Idx('i'), Idx('j'), Idx('k')
ii_jj = x[i, i]**y[j, j]
assert get_contraction_structure(ii_jj) == {
None: {ii_jj},
ii_jj: [
{(i,): {x[i, i]}},
{(j,): {y[j, j]}}
]
}
ii_jk = x[i, i]**y[j, k]
assert get_contraction_structure(ii_jk) == {
None: {x[i, i]**y[j, k]},
x[i, i]**y[j, k]: [
{(i,): {x[i, i]}}
]
}
def test_contraction_structure_Mul_and_Pow():
x = IndexedBase('x')
y = IndexedBase('y')
i, j, k = Idx('i'), Idx('j'), Idx('k')
i_ji = x[i]**(y[j]*x[i])
assert get_contraction_structure(i_ji) == {None: {i_ji}}
ij_i = (x[i]*y[j])**(y[i])
assert get_contraction_structure(ij_i) == {None: {ij_i}}
j_ij_i = x[j]*(x[i]*y[j])**(y[i])
assert get_contraction_structure(j_ij_i) == {(j,): {j_ij_i}}
j_i_ji = x[j]*x[i]**(y[j]*x[i])
assert get_contraction_structure(j_i_ji) == {(j,): {j_i_ji}}
ij_exp_kki = x[i]*y[j]*exp(y[i]*y[k, k])
result = get_contraction_structure(ij_exp_kki)
expected = {
(i,): {ij_exp_kki},
ij_exp_kki: [{
None: {exp(y[i]*y[k, k])},
exp(y[i]*y[k, k]): [{
None: {y[i]*y[k, k]},
y[i]*y[k, k]: [{(k,): {y[k, k]}}]
}]}
]
}
assert result == expected
def test_contraction_structure_Add_in_Pow():
x = IndexedBase('x')
y = IndexedBase('y')
i, j, k = Idx('i'), Idx('j'), Idx('k')
s_ii_jj_s = (1 + x[i, i])**(1 + y[j, j])
expected = {
None: {s_ii_jj_s},
s_ii_jj_s: [
{None: {S.One}, (i,): {x[i, i]}},
{None: {S.One}, (j,): {y[j, j]}}
]
}
result = get_contraction_structure(s_ii_jj_s)
assert result == expected
s_ii_jk_s = (1 + x[i, i]) ** (1 + y[j, k])
expected_2 = {
None: {(x[i, i] + 1)**(y[j, k] + 1)},
s_ii_jk_s: [
{None: {S.One}, (i,): {x[i, i]}}
]
}
result_2 = get_contraction_structure(s_ii_jk_s)
assert result_2 == expected_2
def test_contraction_structure_Pow_in_Pow():
x = IndexedBase('x')
y = IndexedBase('y')
z = IndexedBase('z')
i, j, k = Idx('i'), Idx('j'), Idx('k')
ii_jj_kk = x[i, i]**y[j, j]**z[k, k]
expected = {
None: {ii_jj_kk},
ii_jj_kk: [
{(i,): {x[i, i]}},
{
None: {y[j, j]**z[k, k]},
y[j, j]**z[k, k]: [
{(j,): {y[j, j]}},
{(k,): {z[k, k]}}
]
}
]
}
assert get_contraction_structure(ii_jj_kk) == expected
def test_ufunc_support():
f = Function('f')
g = Function('g')
x = IndexedBase('x')
y = IndexedBase('y')
i, j = Idx('i'), Idx('j')
a = symbols('a')
assert get_indices(f(x[i])) == ({i}, {})
assert get_indices(f(x[i], y[j])) == ({i, j}, {})
assert get_indices(f(y[i])*g(x[i])) == (set(), {})
assert get_indices(f(a, x[i])) == ({i}, {})
assert get_indices(f(a, y[i], x[j])*g(x[i])) == ({j}, {})
assert get_indices(g(f(x[i]))) == ({i}, {})
assert get_contraction_structure(f(x[i])) == {None: {f(x[i])}}
assert get_contraction_structure(
f(y[i])*g(x[i])) == {(i,): {f(y[i])*g(x[i])}}
assert get_contraction_structure(
f(y[i])*g(f(x[i]))) == {(i,): {f(y[i])*g(f(x[i]))}}
assert get_contraction_structure(
f(x[j], y[i])*g(x[i])) == {(i,): {f(x[j], y[i])*g(x[i])}}
|
af05688e495a1720eced63da162200d300ff9c9b8540a79a7faf2095f546e4b8 | from sympy.core import symbols, Symbol, Tuple, oo, Dummy
from sympy.tensor.indexed import IndexException
from sympy.testing.pytest import raises, XFAIL
from sympy.utilities.iterables import iterable
# import test:
from sympy.concrete.summations import Sum
from sympy.core.function import Function, Subs, Derivative
from sympy.core.relational import (StrictLessThan, GreaterThan,
StrictGreaterThan, LessThan)
from sympy.core.singleton import S
from sympy.functions.elementary.exponential import exp, log
from sympy.functions.elementary.trigonometric import cos, sin
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.series.order import Order
from sympy.sets.fancysets import Range
from sympy.tensor.indexed import IndexedBase, Idx, Indexed
def test_Idx_construction():
i, a, b = symbols('i a b', integer=True)
assert Idx(i) != Idx(i, 1)
assert Idx(i, a) == Idx(i, (0, a - 1))
assert Idx(i, oo) == Idx(i, (0, oo))
x = symbols('x', integer=False)
raises(TypeError, lambda: Idx(x))
raises(TypeError, lambda: Idx(0.5))
raises(TypeError, lambda: Idx(i, x))
raises(TypeError, lambda: Idx(i, 0.5))
raises(TypeError, lambda: Idx(i, (x, 5)))
raises(TypeError, lambda: Idx(i, (2, x)))
raises(TypeError, lambda: Idx(i, (2, 3.5)))
def test_Idx_properties():
i, a, b = symbols('i a b', integer=True)
assert Idx(i).is_integer
assert Idx(i).name == 'i'
assert Idx(i + 2).name == 'i + 2'
assert Idx('foo').name == 'foo'
def test_Idx_bounds():
i, a, b = symbols('i a b', integer=True)
assert Idx(i).lower is None
assert Idx(i).upper is None
assert Idx(i, a).lower == 0
assert Idx(i, a).upper == a - 1
assert Idx(i, 5).lower == 0
assert Idx(i, 5).upper == 4
assert Idx(i, oo).lower == 0
assert Idx(i, oo).upper is oo
assert Idx(i, (a, b)).lower == a
assert Idx(i, (a, b)).upper == b
assert Idx(i, (1, 5)).lower == 1
assert Idx(i, (1, 5)).upper == 5
assert Idx(i, (-oo, oo)).lower is -oo
assert Idx(i, (-oo, oo)).upper is oo
def test_Idx_fixed_bounds():
i, a, b, x = symbols('i a b x', integer=True)
assert Idx(x).lower is None
assert Idx(x).upper is None
assert Idx(x, a).lower == 0
assert Idx(x, a).upper == a - 1
assert Idx(x, 5).lower == 0
assert Idx(x, 5).upper == 4
assert Idx(x, oo).lower == 0
assert Idx(x, oo).upper is oo
assert Idx(x, (a, b)).lower == a
assert Idx(x, (a, b)).upper == b
assert Idx(x, (1, 5)).lower == 1
assert Idx(x, (1, 5)).upper == 5
assert Idx(x, (-oo, oo)).lower is -oo
assert Idx(x, (-oo, oo)).upper is oo
def test_Idx_inequalities():
i14 = Idx("i14", (1, 4))
i79 = Idx("i79", (7, 9))
i46 = Idx("i46", (4, 6))
i35 = Idx("i35", (3, 5))
assert i14 <= 5
assert i14 < 5
assert not (i14 >= 5)
assert not (i14 > 5)
assert 5 >= i14
assert 5 > i14
assert not (5 <= i14)
assert not (5 < i14)
assert LessThan(i14, 5)
assert StrictLessThan(i14, 5)
assert not GreaterThan(i14, 5)
assert not StrictGreaterThan(i14, 5)
assert i14 <= 4
assert isinstance(i14 < 4, StrictLessThan)
assert isinstance(i14 >= 4, GreaterThan)
assert not (i14 > 4)
assert isinstance(i14 <= 1, LessThan)
assert not (i14 < 1)
assert i14 >= 1
assert isinstance(i14 > 1, StrictGreaterThan)
assert not (i14 <= 0)
assert not (i14 < 0)
assert i14 >= 0
assert i14 > 0
from sympy.abc import x
assert isinstance(i14 < x, StrictLessThan)
assert isinstance(i14 > x, StrictGreaterThan)
assert isinstance(i14 <= x, LessThan)
assert isinstance(i14 >= x, GreaterThan)
assert i14 < i79
assert i14 <= i79
assert not (i14 > i79)
assert not (i14 >= i79)
assert i14 <= i46
assert isinstance(i14 < i46, StrictLessThan)
assert isinstance(i14 >= i46, GreaterThan)
assert not (i14 > i46)
assert isinstance(i14 < i35, StrictLessThan)
assert isinstance(i14 > i35, StrictGreaterThan)
assert isinstance(i14 <= i35, LessThan)
assert isinstance(i14 >= i35, GreaterThan)
iNone1 = Idx("iNone1")
iNone2 = Idx("iNone2")
assert isinstance(iNone1 < iNone2, StrictLessThan)
assert isinstance(iNone1 > iNone2, StrictGreaterThan)
assert isinstance(iNone1 <= iNone2, LessThan)
assert isinstance(iNone1 >= iNone2, GreaterThan)
@XFAIL
def test_Idx_inequalities_current_fails():
i14 = Idx("i14", (1, 4))
assert S(5) >= i14
assert S(5) > i14
assert not (S(5) <= i14)
assert not (S(5) < i14)
def test_Idx_func_args():
i, a, b = symbols('i a b', integer=True)
ii = Idx(i)
assert ii.func(*ii.args) == ii
ii = Idx(i, a)
assert ii.func(*ii.args) == ii
ii = Idx(i, (a, b))
assert ii.func(*ii.args) == ii
def test_Idx_subs():
i, a, b = symbols('i a b', integer=True)
assert Idx(i, a).subs(a, b) == Idx(i, b)
assert Idx(i, a).subs(i, b) == Idx(b, a)
assert Idx(i).subs(i, 2) == Idx(2)
assert Idx(i, a).subs(a, 2) == Idx(i, 2)
assert Idx(i, (a, b)).subs(i, 2) == Idx(2, (a, b))
def test_IndexedBase_sugar():
i, j = symbols('i j', integer=True)
a = symbols('a')
A1 = Indexed(a, i, j)
A2 = IndexedBase(a)
assert A1 == A2[i, j]
assert A1 == A2[(i, j)]
assert A1 == A2[[i, j]]
assert A1 == A2[Tuple(i, j)]
assert all(a.is_Integer for a in A2[1, 0].args[1:])
def test_IndexedBase_subs():
i = symbols('i', integer=True)
a, b = symbols('a b')
A = IndexedBase(a)
B = IndexedBase(b)
assert A[i] == B[i].subs(b, a)
C = {1: 2}
assert C[1] == A[1].subs(A, C)
def test_IndexedBase_shape():
i, j, m, n = symbols('i j m n', integer=True)
a = IndexedBase('a', shape=(m, m))
b = IndexedBase('a', shape=(m, n))
assert b.shape == Tuple(m, n)
assert a[i, j] != b[i, j]
assert a[i, j] == b[i, j].subs(n, m)
assert b.func(*b.args) == b
assert b[i, j].func(*b[i, j].args) == b[i, j]
raises(IndexException, lambda: b[i])
raises(IndexException, lambda: b[i, i, j])
F = IndexedBase("F", shape=m)
assert F.shape == Tuple(m)
assert F[i].subs(i, j) == F[j]
raises(IndexException, lambda: F[i, j])
def test_IndexedBase_assumptions():
i = Symbol('i', integer=True)
a = Symbol('a')
A = IndexedBase(a, positive=True)
for c in (A, A[i]):
assert c.is_real
assert c.is_complex
assert not c.is_imaginary
assert c.is_nonnegative
assert c.is_nonzero
assert c.is_commutative
assert log(exp(c)) == c
assert A != IndexedBase(a)
assert A == IndexedBase(a, positive=True, real=True)
assert A[i] != Indexed(a, i)
def test_IndexedBase_assumptions_inheritance():
I = Symbol('I', integer=True)
I_inherit = IndexedBase(I)
I_explicit = IndexedBase('I', integer=True)
assert I_inherit.is_integer
assert I_explicit.is_integer
assert I_inherit.label.is_integer
assert I_explicit.label.is_integer
assert I_inherit == I_explicit
def test_issue_17652():
"""Regression test issue #17652.
IndexedBase.label should not upcast subclasses of Symbol
"""
class SubClass(Symbol):
pass
x = SubClass('X')
assert type(x) == SubClass
base = IndexedBase(x)
assert type(x) == SubClass
assert type(base.label) == SubClass
def test_Indexed_constructor():
i, j = symbols('i j', integer=True)
A = Indexed('A', i, j)
assert A == Indexed(Symbol('A'), i, j)
assert A == Indexed(IndexedBase('A'), i, j)
raises(TypeError, lambda: Indexed(A, i, j))
raises(IndexException, lambda: Indexed("A"))
assert A.free_symbols == {A, A.base.label, i, j}
def test_Indexed_func_args():
i, j = symbols('i j', integer=True)
a = symbols('a')
A = Indexed(a, i, j)
assert A == A.func(*A.args)
def test_Indexed_subs():
i, j, k = symbols('i j k', integer=True)
a, b = symbols('a b')
A = IndexedBase(a)
B = IndexedBase(b)
assert A[i, j] == B[i, j].subs(b, a)
assert A[i, j] == A[i, k].subs(k, j)
def test_Indexed_properties():
i, j = symbols('i j', integer=True)
A = Indexed('A', i, j)
assert A.name == 'A[i, j]'
assert A.rank == 2
assert A.indices == (i, j)
assert A.base == IndexedBase('A')
assert A.ranges == [None, None]
raises(IndexException, lambda: A.shape)
n, m = symbols('n m', integer=True)
assert Indexed('A', Idx(
i, m), Idx(j, n)).ranges == [Tuple(0, m - 1), Tuple(0, n - 1)]
assert Indexed('A', Idx(i, m), Idx(j, n)).shape == Tuple(m, n)
raises(IndexException, lambda: Indexed("A", Idx(i, m), Idx(j)).shape)
def test_Indexed_shape_precedence():
i, j = symbols('i j', integer=True)
o, p = symbols('o p', integer=True)
n, m = symbols('n m', integer=True)
a = IndexedBase('a', shape=(o, p))
assert a.shape == Tuple(o, p)
assert Indexed(
a, Idx(i, m), Idx(j, n)).ranges == [Tuple(0, m - 1), Tuple(0, n - 1)]
assert Indexed(a, Idx(i, m), Idx(j, n)).shape == Tuple(o, p)
assert Indexed(
a, Idx(i, m), Idx(j)).ranges == [Tuple(0, m - 1), Tuple(None, None)]
assert Indexed(a, Idx(i, m), Idx(j)).shape == Tuple(o, p)
def test_complex_indices():
i, j = symbols('i j', integer=True)
A = Indexed('A', i, i + j)
assert A.rank == 2
assert A.indices == (i, i + j)
def test_not_interable():
i, j = symbols('i j', integer=True)
A = Indexed('A', i, i + j)
assert not iterable(A)
def test_Indexed_coeff():
N = Symbol('N', integer=True)
len_y = N
i = Idx('i', len_y-1)
y = IndexedBase('y', shape=(len_y,))
a = (1/y[i+1]*y[i]).coeff(y[i])
b = (y[i]/y[i+1]).coeff(y[i])
assert a == b
def test_differentiation():
from sympy.functions.special.tensor_functions import KroneckerDelta
i, j, k, l = symbols('i j k l', cls=Idx)
a = symbols('a')
m, n = symbols("m, n", integer=True, finite=True)
assert m.is_real
h, L = symbols('h L', cls=IndexedBase)
hi, hj = h[i], h[j]
expr = hi
assert expr.diff(hj) == KroneckerDelta(i, j)
assert expr.diff(hi) == KroneckerDelta(i, i)
expr = S(2) * hi
assert expr.diff(hj) == S(2) * KroneckerDelta(i, j)
assert expr.diff(hi) == S(2) * KroneckerDelta(i, i)
assert expr.diff(a) is S.Zero
assert Sum(expr, (i, -oo, oo)).diff(hj) == Sum(2*KroneckerDelta(i, j), (i, -oo, oo))
assert Sum(expr.diff(hj), (i, -oo, oo)) == Sum(2*KroneckerDelta(i, j), (i, -oo, oo))
assert Sum(expr, (i, -oo, oo)).diff(hj).doit() == 2
assert Sum(expr.diff(hi), (i, -oo, oo)).doit() == Sum(2, (i, -oo, oo)).doit()
assert Sum(expr, (i, -oo, oo)).diff(hi).doit() is oo
expr = a * hj * hj / S(2)
assert expr.diff(hi) == a * h[j] * KroneckerDelta(i, j)
assert expr.diff(a) == hj * hj / S(2)
assert expr.diff(a, 2) is S.Zero
assert Sum(expr, (i, -oo, oo)).diff(hi) == Sum(a*KroneckerDelta(i, j)*h[j], (i, -oo, oo))
assert Sum(expr.diff(hi), (i, -oo, oo)) == Sum(a*KroneckerDelta(i, j)*h[j], (i, -oo, oo))
assert Sum(expr, (i, -oo, oo)).diff(hi).doit() == a*h[j]
assert Sum(expr, (j, -oo, oo)).diff(hi) == Sum(a*KroneckerDelta(i, j)*h[j], (j, -oo, oo))
assert Sum(expr.diff(hi), (j, -oo, oo)) == Sum(a*KroneckerDelta(i, j)*h[j], (j, -oo, oo))
assert Sum(expr, (j, -oo, oo)).diff(hi).doit() == a*h[i]
expr = a * sin(hj * hj)
assert expr.diff(hi) == 2*a*cos(hj * hj) * hj * KroneckerDelta(i, j)
assert expr.diff(hj) == 2*a*cos(hj * hj) * hj
expr = a * L[i, j] * h[j]
assert expr.diff(hi) == a*L[i, j]*KroneckerDelta(i, j)
assert expr.diff(hj) == a*L[i, j]
assert expr.diff(L[i, j]) == a*h[j]
assert expr.diff(L[k, l]) == a*KroneckerDelta(i, k)*KroneckerDelta(j, l)*h[j]
assert expr.diff(L[i, l]) == a*KroneckerDelta(j, l)*h[j]
assert Sum(expr, (j, -oo, oo)).diff(L[k, l]) == Sum(a * KroneckerDelta(i, k) * KroneckerDelta(j, l) * h[j], (j, -oo, oo))
assert Sum(expr, (j, -oo, oo)).diff(L[k, l]).doit() == a * KroneckerDelta(i, k) * h[l]
assert h[m].diff(h[m]) == 1
assert h[m].diff(h[n]) == KroneckerDelta(m, n)
assert Sum(a*h[m], (m, -oo, oo)).diff(h[n]) == Sum(a*KroneckerDelta(m, n), (m, -oo, oo))
assert Sum(a*h[m], (m, -oo, oo)).diff(h[n]).doit() == a
assert Sum(a*h[m], (n, -oo, oo)).diff(h[n]) == Sum(a*KroneckerDelta(m, n), (n, -oo, oo))
assert Sum(a*h[m], (m, -oo, oo)).diff(h[m]).doit() == oo*a
def test_indexed_series():
A = IndexedBase("A")
i = symbols("i", integer=True)
assert sin(A[i]).series(A[i]) == A[i] - A[i]**3/6 + A[i]**5/120 + Order(A[i]**6, A[i])
def test_indexed_is_constant():
A = IndexedBase("A")
i, j, k = symbols("i,j,k")
assert not A[i].is_constant()
assert A[i].is_constant(j)
assert not A[1+2*i, k].is_constant()
assert not A[1+2*i, k].is_constant(i)
assert A[1+2*i, k].is_constant(j)
assert not A[1+2*i, k].is_constant(k)
def test_issue_12533():
d = IndexedBase('d')
assert IndexedBase(range(5)) == Range(0, 5, 1)
assert d[0].subs(Symbol("d"), range(5)) == 0
assert d[0].subs(d, range(5)) == 0
assert d[1].subs(d, range(5)) == 1
assert Indexed(Range(5), 2) == 2
def test_issue_12780():
n = symbols("n")
i = Idx("i", (0, n))
raises(TypeError, lambda: i.subs(n, 1.5))
def test_issue_18604():
m = symbols("m")
assert Idx("i", m).name == 'i'
assert Idx("i", m).lower == 0
assert Idx("i", m).upper == m - 1
m = symbols("m", real=False)
raises(TypeError, lambda: Idx("i", m))
def test_Subs_with_Indexed():
A = IndexedBase("A")
i, j, k = symbols("i,j,k")
x, y, z = symbols("x,y,z")
f = Function("f")
assert Subs(A[i], A[i], A[j]).diff(A[j]) == 1
assert Subs(A[i], A[i], x).diff(A[i]) == 0
assert Subs(A[i], A[i], x).diff(A[j]) == 0
assert Subs(A[i], A[i], x).diff(x) == 1
assert Subs(A[i], A[i], x).diff(y) == 0
assert Subs(A[i], A[i], A[j]).diff(A[k]) == KroneckerDelta(j, k)
assert Subs(x, x, A[i]).diff(A[j]) == KroneckerDelta(i, j)
assert Subs(f(A[i]), A[i], x).diff(A[j]) == 0
assert Subs(f(A[i]), A[i], A[k]).diff(A[j]) == Derivative(f(A[k]), A[k])*KroneckerDelta(j, k)
assert Subs(x, x, A[i]**2).diff(A[j]) == 2*KroneckerDelta(i, j)*A[i]
assert Subs(A[i], A[i], A[j]**2).diff(A[k]) == 2*KroneckerDelta(j, k)*A[j]
assert Subs(A[i]*x, x, A[i]).diff(A[i]) == 2*A[i]
assert Subs(A[i]*x, x, A[i]).diff(A[j]) == 2*A[i]*KroneckerDelta(i, j)
assert Subs(A[i]*x, x, A[j]).diff(A[i]) == A[j] + A[i]*KroneckerDelta(i, j)
assert Subs(A[i]*x, x, A[j]).diff(A[j]) == A[i] + A[j]*KroneckerDelta(i, j)
assert Subs(A[i]*x, x, A[i]).diff(A[k]) == 2*A[i]*KroneckerDelta(i, k)
assert Subs(A[i]*x, x, A[j]).diff(A[k]) == KroneckerDelta(i, k)*A[j] + KroneckerDelta(j, k)*A[i]
assert Subs(A[i]*x, A[i], x).diff(A[i]) == 0
assert Subs(A[i]*x, A[i], x).diff(A[j]) == 0
assert Subs(A[i]*x, A[j], x).diff(A[i]) == x
assert Subs(A[i]*x, A[j], x).diff(A[j]) == x*KroneckerDelta(i, j)
assert Subs(A[i]*x, A[i], x).diff(A[k]) == 0
assert Subs(A[i]*x, A[j], x).diff(A[k]) == x*KroneckerDelta(i, k)
def test_complicated_derivative_with_Indexed():
x, y = symbols("x,y", cls=IndexedBase)
sigma = symbols("sigma")
i, j, k = symbols("i,j,k")
m0,m1,m2,m3,m4,m5 = symbols("m0:6")
f = Function("f")
expr = f((x[i] - y[i])**2/sigma)
_xi_1 = symbols("xi_1", cls=Dummy)
assert expr.diff(x[m0]).dummy_eq(
(x[i] - y[i])*KroneckerDelta(i, m0)*\
2*Subs(
Derivative(f(_xi_1), _xi_1),
(_xi_1,),
((x[i] - y[i])**2/sigma,)
)/sigma
)
assert expr.diff(x[m0]).diff(x[m1]).dummy_eq(
2*KroneckerDelta(i, m0)*\
KroneckerDelta(i, m1)*Subs(
Derivative(f(_xi_1), _xi_1),
(_xi_1,),
((x[i] - y[i])**2/sigma,)
)/sigma + \
4*(x[i] - y[i])**2*KroneckerDelta(i, m0)*KroneckerDelta(i, m1)*\
Subs(
Derivative(f(_xi_1), _xi_1, _xi_1),
(_xi_1,),
((x[i] - y[i])**2/sigma,)
)/sigma**2
)
|
d5d17de85b6a506689cdeb61c36def2488f71f929dc6c5355f27780d4e78101e | from sympy.tensor.tensor import (Tensor, TensorIndexType, TensorSymmetry,
tensor_indices, TensorHead, TensorElement)
from sympy.tensor import Array
from sympy.core.symbol import Symbol
def test_tensor_element():
L = TensorIndexType("L")
i, j, k, l, m, n = tensor_indices("i j k l m n", L)
A = TensorHead("A", [L, L], TensorSymmetry.no_symmetry(2))
a = A(i, j)
assert isinstance(TensorElement(a, {}), Tensor)
assert isinstance(TensorElement(a, {k: 1}), Tensor)
te1 = TensorElement(a, {Symbol("i"): 1})
assert te1.free == [(j, 0)]
assert te1.get_free_indices() == [j]
assert te1.dum == []
te2 = TensorElement(a, {i: 1})
assert te2.free == [(j, 0)]
assert te2.get_free_indices() == [j]
assert te2.dum == []
assert te1 == te2
array = Array([[1, 2], [3, 4]])
assert te1.replace_with_arrays({A(i, j): array}, [j]) == array[1, :]
|
765bc61cdff074f63bd541893c57b4b47f44b7e4f14b8f8c07a949b881f96ddf | import random
from sympy.combinatorics import Permutation
from sympy.combinatorics.permutations import _af_invert
from sympy.testing.pytest import raises
from sympy.core.function import diff
from sympy.core.symbol import symbols
from sympy.functions.elementary.complexes import (adjoint, conjugate, transpose)
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.tensor.array import Array, ImmutableDenseNDimArray, ImmutableSparseNDimArray, MutableSparseNDimArray
from sympy.tensor.array.arrayop import tensorproduct, tensorcontraction, derive_by_array, permutedims, Flatten, \
tensordiagonal
def test_import_NDimArray():
from sympy.tensor.array import NDimArray
del NDimArray
def test_tensorproduct():
x,y,z,t = symbols('x y z t')
from sympy.abc import a,b,c,d
assert tensorproduct() == 1
assert tensorproduct([x]) == Array([x])
assert tensorproduct([x], [y]) == Array([[x*y]])
assert tensorproduct([x], [y], [z]) == Array([[[x*y*z]]])
assert tensorproduct([x], [y], [z], [t]) == Array([[[[x*y*z*t]]]])
assert tensorproduct(x) == x
assert tensorproduct(x, y) == x*y
assert tensorproduct(x, y, z) == x*y*z
assert tensorproduct(x, y, z, t) == x*y*z*t
for ArrayType in [ImmutableDenseNDimArray, ImmutableSparseNDimArray]:
A = ArrayType([x, y])
B = ArrayType([1, 2, 3])
C = ArrayType([a, b, c, d])
assert tensorproduct(A, B, C) == ArrayType([[[a*x, b*x, c*x, d*x], [2*a*x, 2*b*x, 2*c*x, 2*d*x], [3*a*x, 3*b*x, 3*c*x, 3*d*x]],
[[a*y, b*y, c*y, d*y], [2*a*y, 2*b*y, 2*c*y, 2*d*y], [3*a*y, 3*b*y, 3*c*y, 3*d*y]]])
assert tensorproduct([x, y], [1, 2, 3]) == tensorproduct(A, B)
assert tensorproduct(A, 2) == ArrayType([2*x, 2*y])
assert tensorproduct(A, [2]) == ArrayType([[2*x], [2*y]])
assert tensorproduct([2], A) == ArrayType([[2*x, 2*y]])
assert tensorproduct(a, A) == ArrayType([a*x, a*y])
assert tensorproduct(a, A, B) == ArrayType([[a*x, 2*a*x, 3*a*x], [a*y, 2*a*y, 3*a*y]])
assert tensorproduct(A, B, a) == ArrayType([[a*x, 2*a*x, 3*a*x], [a*y, 2*a*y, 3*a*y]])
assert tensorproduct(B, a, A) == ArrayType([[a*x, a*y], [2*a*x, 2*a*y], [3*a*x, 3*a*y]])
# tests for large scale sparse array
for SparseArrayType in [ImmutableSparseNDimArray, MutableSparseNDimArray]:
a = SparseArrayType({1:2, 3:4},(1000, 2000))
b = SparseArrayType({1:2, 3:4},(1000, 2000))
assert tensorproduct(a, b) == ImmutableSparseNDimArray({2000001: 4, 2000003: 8, 6000001: 8, 6000003: 16}, (1000, 2000, 1000, 2000))
def test_tensorcontraction():
from sympy.abc import a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x
B = Array(range(18), (2, 3, 3))
assert tensorcontraction(B, (1, 2)) == Array([12, 39])
C1 = Array([a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x], (2, 3, 2, 2))
assert tensorcontraction(C1, (0, 2)) == Array([[a + o, b + p], [e + s, f + t], [i + w, j + x]])
assert tensorcontraction(C1, (0, 2, 3)) == Array([a + p, e + t, i + x])
assert tensorcontraction(C1, (2, 3)) == Array([[a + d, e + h, i + l], [m + p, q + t, u + x]])
def test_derivative_by_array():
from sympy.abc import i, j, t, x, y, z
bexpr = x*y**2*exp(z)*log(t)
sexpr = sin(bexpr)
cexpr = cos(bexpr)
a = Array([sexpr])
assert derive_by_array(sexpr, t) == x*y**2*exp(z)*cos(x*y**2*exp(z)*log(t))/t
assert derive_by_array(sexpr, [x, y, z]) == Array([bexpr/x*cexpr, 2*y*bexpr/y**2*cexpr, bexpr*cexpr])
assert derive_by_array(a, [x, y, z]) == Array([[bexpr/x*cexpr], [2*y*bexpr/y**2*cexpr], [bexpr*cexpr]])
assert derive_by_array(sexpr, [[x, y], [z, t]]) == Array([[bexpr/x*cexpr, 2*y*bexpr/y**2*cexpr], [bexpr*cexpr, bexpr/log(t)/t*cexpr]])
assert derive_by_array(a, [[x, y], [z, t]]) == Array([[[bexpr/x*cexpr], [2*y*bexpr/y**2*cexpr]], [[bexpr*cexpr], [bexpr/log(t)/t*cexpr]]])
assert derive_by_array([[x, y], [z, t]], [x, y]) == Array([[[1, 0], [0, 0]], [[0, 1], [0, 0]]])
assert derive_by_array([[x, y], [z, t]], [[x, y], [z, t]]) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]],
[[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
assert diff(sexpr, t) == x*y**2*exp(z)*cos(x*y**2*exp(z)*log(t))/t
assert diff(sexpr, Array([x, y, z])) == Array([bexpr/x*cexpr, 2*y*bexpr/y**2*cexpr, bexpr*cexpr])
assert diff(a, Array([x, y, z])) == Array([[bexpr/x*cexpr], [2*y*bexpr/y**2*cexpr], [bexpr*cexpr]])
assert diff(sexpr, Array([[x, y], [z, t]])) == Array([[bexpr/x*cexpr, 2*y*bexpr/y**2*cexpr], [bexpr*cexpr, bexpr/log(t)/t*cexpr]])
assert diff(a, Array([[x, y], [z, t]])) == Array([[[bexpr/x*cexpr], [2*y*bexpr/y**2*cexpr]], [[bexpr*cexpr], [bexpr/log(t)/t*cexpr]]])
assert diff(Array([[x, y], [z, t]]), Array([x, y])) == Array([[[1, 0], [0, 0]], [[0, 1], [0, 0]]])
assert diff(Array([[x, y], [z, t]]), Array([[x, y], [z, t]])) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]],
[[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
# test for large scale sparse array
for SparseArrayType in [ImmutableSparseNDimArray, MutableSparseNDimArray]:
b = MutableSparseNDimArray({0:i, 1:j}, (10000, 20000))
assert derive_by_array(b, i) == ImmutableSparseNDimArray({0: 1}, (10000, 20000))
assert derive_by_array(b, (i, j)) == ImmutableSparseNDimArray({0: 1, 200000001: 1}, (2, 10000, 20000))
#https://github.com/sympy/sympy/issues/20655
U = Array([x, y, z])
E = 2
assert derive_by_array(E, U) == ImmutableDenseNDimArray([0, 0, 0])
def test_issue_emerged_while_discussing_10972():
ua = Array([-1,0])
Fa = Array([[0, 1], [-1, 0]])
po = tensorproduct(Fa, ua, Fa, ua)
assert tensorcontraction(po, (1, 2), (4, 5)) == Array([[0, 0], [0, 1]])
sa = symbols('a0:144')
po = Array(sa, [2, 2, 3, 3, 2, 2])
assert tensorcontraction(po, (0, 1), (2, 3), (4, 5)) == sa[0] + sa[108] + sa[111] + sa[124] + sa[127] + sa[140] + sa[143] + sa[16] + sa[19] + sa[3] + sa[32] + sa[35]
assert tensorcontraction(po, (0, 1, 4, 5), (2, 3)) == sa[0] + sa[111] + sa[127] + sa[143] + sa[16] + sa[32]
assert tensorcontraction(po, (0, 1), (4, 5)) == Array([[sa[0] + sa[108] + sa[111] + sa[3], sa[112] + sa[115] + sa[4] + sa[7],
sa[11] + sa[116] + sa[119] + sa[8]], [sa[12] + sa[120] + sa[123] + sa[15],
sa[124] + sa[127] + sa[16] + sa[19], sa[128] + sa[131] + sa[20] + sa[23]],
[sa[132] + sa[135] + sa[24] + sa[27], sa[136] + sa[139] + sa[28] + sa[31],
sa[140] + sa[143] + sa[32] + sa[35]]])
assert tensorcontraction(po, (0, 1), (2, 3)) == Array([[sa[0] + sa[108] + sa[124] + sa[140] + sa[16] + sa[32], sa[1] + sa[109] + sa[125] + sa[141] + sa[17] + sa[33]],
[sa[110] + sa[126] + sa[142] + sa[18] + sa[2] + sa[34], sa[111] + sa[127] + sa[143] + sa[19] + sa[3] + sa[35]]])
def test_array_permutedims():
sa = symbols('a0:144')
for ArrayType in [ImmutableDenseNDimArray, ImmutableSparseNDimArray]:
m1 = ArrayType(sa[:6], (2, 3))
assert permutedims(m1, (1, 0)) == transpose(m1)
assert m1.tomatrix().T == permutedims(m1, (1, 0)).tomatrix()
assert m1.tomatrix().T == transpose(m1).tomatrix()
assert m1.tomatrix().C == conjugate(m1).tomatrix()
assert m1.tomatrix().H == adjoint(m1).tomatrix()
assert m1.tomatrix().T == m1.transpose().tomatrix()
assert m1.tomatrix().C == m1.conjugate().tomatrix()
assert m1.tomatrix().H == m1.adjoint().tomatrix()
raises(ValueError, lambda: permutedims(m1, (0,)))
raises(ValueError, lambda: permutedims(m1, (0, 0)))
raises(ValueError, lambda: permutedims(m1, (1, 2, 0)))
# Some tests with random arrays:
dims = 6
shape = [random.randint(1,5) for i in range(dims)]
elems = [random.random() for i in range(tensorproduct(*shape))]
ra = ArrayType(elems, shape)
perm = list(range(dims))
# Randomize the permutation:
random.shuffle(perm)
# Test inverse permutation:
assert permutedims(permutedims(ra, perm), _af_invert(perm)) == ra
# Test that permuted shape corresponds to action by `Permutation`:
assert permutedims(ra, perm).shape == tuple(Permutation(perm)(shape))
z = ArrayType.zeros(4,5,6,7)
assert permutedims(z, (2, 3, 1, 0)).shape == (6, 7, 5, 4)
assert permutedims(z, [2, 3, 1, 0]).shape == (6, 7, 5, 4)
assert permutedims(z, Permutation([2, 3, 1, 0])).shape == (6, 7, 5, 4)
po = ArrayType(sa, [2, 2, 3, 3, 2, 2])
raises(ValueError, lambda: permutedims(po, (1, 1)))
raises(ValueError, lambda: po.transpose())
raises(ValueError, lambda: po.adjoint())
assert permutedims(po, reversed(range(po.rank()))) == ArrayType(
[[[[[[sa[0], sa[72]], [sa[36], sa[108]]], [[sa[12], sa[84]], [sa[48], sa[120]]], [[sa[24],
sa[96]], [sa[60], sa[132]]]],
[[[sa[4], sa[76]], [sa[40], sa[112]]], [[sa[16],
sa[88]], [sa[52], sa[124]]],
[[sa[28], sa[100]], [sa[64], sa[136]]]],
[[[sa[8],
sa[80]], [sa[44], sa[116]]], [[sa[20], sa[92]], [sa[56], sa[128]]], [[sa[32],
sa[104]], [sa[68], sa[140]]]]],
[[[[sa[2], sa[74]], [sa[38], sa[110]]], [[sa[14],
sa[86]], [sa[50], sa[122]]], [[sa[26], sa[98]], [sa[62], sa[134]]]],
[[[sa[6],
sa[78]], [sa[42], sa[114]]], [[sa[18], sa[90]], [sa[54], sa[126]]], [[sa[30],
sa[102]], [sa[66], sa[138]]]],
[[[sa[10], sa[82]], [sa[46], sa[118]]], [[sa[22],
sa[94]], [sa[58], sa[130]]],
[[sa[34], sa[106]], [sa[70], sa[142]]]]]],
[[[[[sa[1],
sa[73]], [sa[37], sa[109]]], [[sa[13], sa[85]], [sa[49], sa[121]]], [[sa[25],
sa[97]], [sa[61], sa[133]]]],
[[[sa[5], sa[77]], [sa[41], sa[113]]], [[sa[17],
sa[89]], [sa[53], sa[125]]],
[[sa[29], sa[101]], [sa[65], sa[137]]]],
[[[sa[9],
sa[81]], [sa[45], sa[117]]], [[sa[21], sa[93]], [sa[57], sa[129]]], [[sa[33],
sa[105]], [sa[69], sa[141]]]]],
[[[[sa[3], sa[75]], [sa[39], sa[111]]], [[sa[15],
sa[87]], [sa[51], sa[123]]], [[sa[27], sa[99]], [sa[63], sa[135]]]],
[[[sa[7],
sa[79]], [sa[43], sa[115]]], [[sa[19], sa[91]], [sa[55], sa[127]]], [[sa[31],
sa[103]], [sa[67], sa[139]]]],
[[[sa[11], sa[83]], [sa[47], sa[119]]], [[sa[23],
sa[95]], [sa[59], sa[131]]],
[[sa[35], sa[107]], [sa[71], sa[143]]]]]]])
assert permutedims(po, (1, 0, 2, 3, 4, 5)) == ArrayType(
[[[[[[sa[0], sa[1]], [sa[2], sa[3]]], [[sa[4], sa[5]], [sa[6], sa[7]]], [[sa[8], sa[9]], [sa[10],
sa[11]]]],
[[[sa[12], sa[13]], [sa[14], sa[15]]], [[sa[16], sa[17]], [sa[18],
sa[19]]], [[sa[20], sa[21]], [sa[22], sa[23]]]],
[[[sa[24], sa[25]], [sa[26],
sa[27]]], [[sa[28], sa[29]], [sa[30], sa[31]]], [[sa[32], sa[33]], [sa[34],
sa[35]]]]],
[[[[sa[72], sa[73]], [sa[74], sa[75]]], [[sa[76], sa[77]], [sa[78],
sa[79]]], [[sa[80], sa[81]], [sa[82], sa[83]]]],
[[[sa[84], sa[85]], [sa[86],
sa[87]]], [[sa[88], sa[89]], [sa[90], sa[91]]], [[sa[92], sa[93]], [sa[94],
sa[95]]]],
[[[sa[96], sa[97]], [sa[98], sa[99]]], [[sa[100], sa[101]], [sa[102],
sa[103]]],
[[sa[104], sa[105]], [sa[106], sa[107]]]]]], [[[[[sa[36], sa[37]], [sa[38],
sa[39]]],
[[sa[40], sa[41]], [sa[42], sa[43]]],
[[sa[44], sa[45]], [sa[46],
sa[47]]]],
[[[sa[48], sa[49]], [sa[50], sa[51]]],
[[sa[52], sa[53]], [sa[54],
sa[55]]],
[[sa[56], sa[57]], [sa[58], sa[59]]]],
[[[sa[60], sa[61]], [sa[62],
sa[63]]],
[[sa[64], sa[65]], [sa[66], sa[67]]],
[[sa[68], sa[69]], [sa[70],
sa[71]]]]], [
[[[sa[108], sa[109]], [sa[110], sa[111]]],
[[sa[112], sa[113]], [sa[114],
sa[115]]],
[[sa[116], sa[117]], [sa[118], sa[119]]]],
[[[sa[120], sa[121]], [sa[122],
sa[123]]],
[[sa[124], sa[125]], [sa[126], sa[127]]],
[[sa[128], sa[129]], [sa[130],
sa[131]]]],
[[[sa[132], sa[133]], [sa[134], sa[135]]],
[[sa[136], sa[137]], [sa[138],
sa[139]]],
[[sa[140], sa[141]], [sa[142], sa[143]]]]]]])
assert permutedims(po, (0, 2, 1, 4, 3, 5)) == ArrayType(
[[[[[[sa[0], sa[1]], [sa[4], sa[5]], [sa[8], sa[9]]], [[sa[2], sa[3]], [sa[6], sa[7]], [sa[10],
sa[11]]]],
[[[sa[36], sa[37]], [sa[40], sa[41]], [sa[44], sa[45]]], [[sa[38],
sa[39]], [sa[42], sa[43]], [sa[46], sa[47]]]]],
[[[[sa[12], sa[13]], [sa[16],
sa[17]], [sa[20], sa[21]]], [[sa[14], sa[15]], [sa[18], sa[19]], [sa[22],
sa[23]]]],
[[[sa[48], sa[49]], [sa[52], sa[53]], [sa[56], sa[57]]], [[sa[50],
sa[51]], [sa[54], sa[55]], [sa[58], sa[59]]]]],
[[[[sa[24], sa[25]], [sa[28],
sa[29]], [sa[32], sa[33]]], [[sa[26], sa[27]], [sa[30], sa[31]], [sa[34],
sa[35]]]],
[[[sa[60], sa[61]], [sa[64], sa[65]], [sa[68], sa[69]]], [[sa[62],
sa[63]], [sa[66], sa[67]], [sa[70], sa[71]]]]]],
[[[[[sa[72], sa[73]], [sa[76],
sa[77]], [sa[80], sa[81]]], [[sa[74], sa[75]], [sa[78], sa[79]], [sa[82],
sa[83]]]],
[[[sa[108], sa[109]], [sa[112], sa[113]], [sa[116], sa[117]]], [[sa[110],
sa[111]], [sa[114], sa[115]],
[sa[118], sa[119]]]]],
[[[[sa[84], sa[85]], [sa[88],
sa[89]], [sa[92], sa[93]]], [[sa[86], sa[87]], [sa[90], sa[91]], [sa[94],
sa[95]]]],
[[[sa[120], sa[121]], [sa[124], sa[125]], [sa[128], sa[129]]], [[sa[122],
sa[123]], [sa[126], sa[127]],
[sa[130], sa[131]]]]],
[[[[sa[96], sa[97]], [sa[100],
sa[101]], [sa[104], sa[105]]], [[sa[98], sa[99]], [sa[102], sa[103]], [sa[106],
sa[107]]]],
[[[sa[132], sa[133]], [sa[136], sa[137]], [sa[140], sa[141]]], [[sa[134],
sa[135]], [sa[138], sa[139]],
[sa[142], sa[143]]]]]]])
po2 = po.reshape(4, 9, 2, 2)
assert po2 == ArrayType([[[[sa[0], sa[1]], [sa[2], sa[3]]], [[sa[4], sa[5]], [sa[6], sa[7]]], [[sa[8], sa[9]], [sa[10], sa[11]]], [[sa[12], sa[13]], [sa[14], sa[15]]], [[sa[16], sa[17]], [sa[18], sa[19]]], [[sa[20], sa[21]], [sa[22], sa[23]]], [[sa[24], sa[25]], [sa[26], sa[27]]], [[sa[28], sa[29]], [sa[30], sa[31]]], [[sa[32], sa[33]], [sa[34], sa[35]]]], [[[sa[36], sa[37]], [sa[38], sa[39]]], [[sa[40], sa[41]], [sa[42], sa[43]]], [[sa[44], sa[45]], [sa[46], sa[47]]], [[sa[48], sa[49]], [sa[50], sa[51]]], [[sa[52], sa[53]], [sa[54], sa[55]]], [[sa[56], sa[57]], [sa[58], sa[59]]], [[sa[60], sa[61]], [sa[62], sa[63]]], [[sa[64], sa[65]], [sa[66], sa[67]]], [[sa[68], sa[69]], [sa[70], sa[71]]]], [[[sa[72], sa[73]], [sa[74], sa[75]]], [[sa[76], sa[77]], [sa[78], sa[79]]], [[sa[80], sa[81]], [sa[82], sa[83]]], [[sa[84], sa[85]], [sa[86], sa[87]]], [[sa[88], sa[89]], [sa[90], sa[91]]], [[sa[92], sa[93]], [sa[94], sa[95]]], [[sa[96], sa[97]], [sa[98], sa[99]]], [[sa[100], sa[101]], [sa[102], sa[103]]], [[sa[104], sa[105]], [sa[106], sa[107]]]], [[[sa[108], sa[109]], [sa[110], sa[111]]], [[sa[112], sa[113]], [sa[114], sa[115]]], [[sa[116], sa[117]], [sa[118], sa[119]]], [[sa[120], sa[121]], [sa[122], sa[123]]], [[sa[124], sa[125]], [sa[126], sa[127]]], [[sa[128], sa[129]], [sa[130], sa[131]]], [[sa[132], sa[133]], [sa[134], sa[135]]], [[sa[136], sa[137]], [sa[138], sa[139]]], [[sa[140], sa[141]], [sa[142], sa[143]]]]])
assert permutedims(po2, (3, 2, 0, 1)) == ArrayType([[[[sa[0], sa[4], sa[8], sa[12], sa[16], sa[20], sa[24], sa[28], sa[32]], [sa[36], sa[40], sa[44], sa[48], sa[52], sa[56], sa[60], sa[64], sa[68]], [sa[72], sa[76], sa[80], sa[84], sa[88], sa[92], sa[96], sa[100], sa[104]], [sa[108], sa[112], sa[116], sa[120], sa[124], sa[128], sa[132], sa[136], sa[140]]], [[sa[2], sa[6], sa[10], sa[14], sa[18], sa[22], sa[26], sa[30], sa[34]], [sa[38], sa[42], sa[46], sa[50], sa[54], sa[58], sa[62], sa[66], sa[70]], [sa[74], sa[78], sa[82], sa[86], sa[90], sa[94], sa[98], sa[102], sa[106]], [sa[110], sa[114], sa[118], sa[122], sa[126], sa[130], sa[134], sa[138], sa[142]]]], [[[sa[1], sa[5], sa[9], sa[13], sa[17], sa[21], sa[25], sa[29], sa[33]], [sa[37], sa[41], sa[45], sa[49], sa[53], sa[57], sa[61], sa[65], sa[69]], [sa[73], sa[77], sa[81], sa[85], sa[89], sa[93], sa[97], sa[101], sa[105]], [sa[109], sa[113], sa[117], sa[121], sa[125], sa[129], sa[133], sa[137], sa[141]]], [[sa[3], sa[7], sa[11], sa[15], sa[19], sa[23], sa[27], sa[31], sa[35]], [sa[39], sa[43], sa[47], sa[51], sa[55], sa[59], sa[63], sa[67], sa[71]], [sa[75], sa[79], sa[83], sa[87], sa[91], sa[95], sa[99], sa[103], sa[107]], [sa[111], sa[115], sa[119], sa[123], sa[127], sa[131], sa[135], sa[139], sa[143]]]]])
# test for large scale sparse array
for SparseArrayType in [ImmutableSparseNDimArray, MutableSparseNDimArray]:
A = SparseArrayType({1:1, 10000:2}, (10000, 20000, 10000))
assert permutedims(A, (0, 1, 2)) == A
assert permutedims(A, (1, 0, 2)) == SparseArrayType({1: 1, 100000000: 2}, (20000, 10000, 10000))
B = SparseArrayType({1:1, 20000:2}, (10000, 20000))
assert B.transpose() == SparseArrayType({10000: 1, 1: 2}, (20000, 10000))
def test_flatten():
from sympy.matrices.dense import Matrix
for ArrayType in [ImmutableDenseNDimArray, ImmutableSparseNDimArray, Matrix]:
A = ArrayType(range(24)).reshape(4, 6)
assert [i for i in Flatten(A)] == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
for i, v in enumerate(Flatten(A)):
i == v
def test_tensordiagonal():
from sympy.matrices.dense import eye
expr = Array(range(9)).reshape(3, 3)
raises(ValueError, lambda: tensordiagonal(expr, [0], [1]))
raises(ValueError, lambda: tensordiagonal(expr, [0, 0]))
assert tensordiagonal(eye(3), [0, 1]) == Array([1, 1, 1])
assert tensordiagonal(expr, [0, 1]) == Array([0, 4, 8])
x, y, z = symbols("x y z")
expr2 = tensorproduct([x, y, z], expr)
assert tensordiagonal(expr2, [1, 2]) == Array([[0, 4*x, 8*x], [0, 4*y, 8*y], [0, 4*z, 8*z]])
assert tensordiagonal(expr2, [0, 1]) == Array([[0, 3*y, 6*z], [x, 4*y, 7*z], [2*x, 5*y, 8*z]])
assert tensordiagonal(expr2, [0, 1, 2]) == Array([0, 4*y, 8*z])
# assert tensordiagonal(expr2, [0]) == permutedims(expr2, [1, 2, 0])
# assert tensordiagonal(expr2, [1]) == permutedims(expr2, [0, 2, 1])
# assert tensordiagonal(expr2, [2]) == expr2
# assert tensordiagonal(expr2, [1], [2]) == expr2
# assert tensordiagonal(expr2, [0], [1]) == permutedims(expr2, [2, 0, 1])
a, b, c, X, Y, Z = symbols("a b c X Y Z")
expr3 = tensorproduct([x, y, z], [1, 2, 3], [a, b, c], [X, Y, Z])
assert tensordiagonal(expr3, [0, 1, 2, 3]) == Array([x*a*X, 2*y*b*Y, 3*z*c*Z])
assert tensordiagonal(expr3, [0, 1], [2, 3]) == tensorproduct([x, 2*y, 3*z], [a*X, b*Y, c*Z])
# assert tensordiagonal(expr3, [0], [1, 2], [3]) == tensorproduct([x, y, z], [a, 2*b, 3*c], [X, Y, Z])
assert tensordiagonal(tensordiagonal(expr3, [2, 3]), [0, 1]) == tensorproduct([a*X, b*Y, c*Z], [x, 2*y, 3*z])
raises(ValueError, lambda: tensordiagonal([[1, 2, 3], [4, 5, 6]], [0, 1]))
raises(ValueError, lambda: tensordiagonal(expr3.reshape(3, 3, 9), [1, 2]))
|
dceda70f8fddd5314fef9a9c189f170f80f07cf6e51732a163a7c080d43d289d | from sympy.core.symbol import symbols
from sympy.matrices.dense import Matrix
from sympy.matrices.expressions.matexpr import MatrixSymbol
from sympy.tensor.array.ndim_array import NDimArray
from sympy.matrices.common import MatrixCommon
from sympy.tensor.array.array_derivatives import ArrayDerivative
x, y, z, t = symbols("x y z t")
m = Matrix([[x, y], [z, t]])
M = MatrixSymbol("M", 3, 2)
N = MatrixSymbol("N", 4, 3)
def test_array_derivative_construction():
d = ArrayDerivative(x, m, evaluate=False)
assert d.shape == (2, 2)
expr = d.doit()
assert isinstance(expr, MatrixCommon)
assert expr.shape == (2, 2)
d = ArrayDerivative(m, m, evaluate=False)
assert d.shape == (2, 2, 2, 2)
expr = d.doit()
assert isinstance(expr, NDimArray)
assert expr.shape == (2, 2, 2, 2)
d = ArrayDerivative(m, x, evaluate=False)
assert d.shape == (2, 2)
expr = d.doit()
assert isinstance(expr, MatrixCommon)
assert expr.shape == (2, 2)
d = ArrayDerivative(M, N, evaluate=False)
assert d.shape == (4, 3, 3, 2)
expr = d.doit()
assert isinstance(expr, ArrayDerivative)
assert expr.shape == (4, 3, 3, 2)
d = ArrayDerivative(M, (N, 2), evaluate=False)
assert d.shape == (4, 3, 4, 3, 3, 2)
expr = d.doit()
assert isinstance(expr, ArrayDerivative)
assert expr.shape == (4, 3, 4, 3, 3, 2)
d = ArrayDerivative(M.as_explicit(), (N.as_explicit(), 2), evaluate=False)
assert d.doit().shape == (4, 3, 4, 3, 3, 2)
expr = d.doit()
assert isinstance(expr, ArrayDerivative)
assert expr.shape == (4, 3, 4, 3, 3, 2)
|
1f2176e71c7969dd265a7a48480f726b953aacbf3a6eef5150a1032a59098103 | from sympy.testing.pytest import raises
from sympy.functions.elementary.trigonometric import sin, cos
from sympy.matrices.dense import Matrix
from sympy.simplify import simplify
from sympy.tensor.array import Array
from sympy.tensor.array.dense_ndim_array import (
ImmutableDenseNDimArray, MutableDenseNDimArray)
from sympy.tensor.array.sparse_ndim_array import (
ImmutableSparseNDimArray, MutableSparseNDimArray)
from sympy.abc import x, y
array_types = [
ImmutableDenseNDimArray,
ImmutableSparseNDimArray,
MutableDenseNDimArray,
MutableSparseNDimArray
]
def test_array_negative_indices():
for ArrayType in array_types:
test_array = ArrayType([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
assert test_array[:, -1] == Array([5, 10])
assert test_array[:, -2] == Array([4, 9])
assert test_array[:, -3] == Array([3, 8])
assert test_array[:, -4] == Array([2, 7])
assert test_array[:, -5] == Array([1, 6])
assert test_array[:, 0] == Array([1, 6])
assert test_array[:, 1] == Array([2, 7])
assert test_array[:, 2] == Array([3, 8])
assert test_array[:, 3] == Array([4, 9])
assert test_array[:, 4] == Array([5, 10])
raises(ValueError, lambda: test_array[:, -6])
raises(ValueError, lambda: test_array[-3, :])
assert test_array[-1, -1] == 10
def test_issue_18361():
A = Array([sin(2 * x) - 2 * sin(x) * cos(x)])
B = Array([sin(x)**2 + cos(x)**2, 0])
C = Array([(x + x**2)/(x*sin(y)**2 + x*cos(y)**2), 2*sin(x)*cos(x)])
assert simplify(A) == Array([0])
assert simplify(B) == Array([1, 0])
assert simplify(C) == Array([x + 1, sin(2*x)])
def test_issue_20222():
A = Array([[1, 2], [3, 4]])
B = Matrix([[1,2],[3,4]])
raises(TypeError, lambda: A - B)
|
01510480b2b8abe177382e3a8f233f26645c942c1a8f96a1e33daefec26e639e | from copy import copy
from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArray
from sympy.core.containers import Dict
from sympy.core.function import diff
from sympy.core.numbers import Rational
from sympy.core.singleton import S
from sympy.core.symbol import (Symbol, symbols)
from sympy.matrices import SparseMatrix
from sympy.tensor.indexed import (Indexed, IndexedBase)
from sympy.matrices import Matrix
from sympy.tensor.array.sparse_ndim_array import ImmutableSparseNDimArray
from sympy.testing.pytest import raises
def test_ndim_array_initiation():
arr_with_no_elements = ImmutableDenseNDimArray([], shape=(0,))
assert len(arr_with_no_elements) == 0
assert arr_with_no_elements.rank() == 1
raises(ValueError, lambda: ImmutableDenseNDimArray([0], shape=(0,)))
raises(ValueError, lambda: ImmutableDenseNDimArray([1, 2, 3], shape=(0,)))
raises(ValueError, lambda: ImmutableDenseNDimArray([], shape=()))
raises(ValueError, lambda: ImmutableSparseNDimArray([0], shape=(0,)))
raises(ValueError, lambda: ImmutableSparseNDimArray([1, 2, 3], shape=(0,)))
raises(ValueError, lambda: ImmutableSparseNDimArray([], shape=()))
arr_with_one_element = ImmutableDenseNDimArray([23])
assert len(arr_with_one_element) == 1
assert arr_with_one_element[0] == 23
assert arr_with_one_element[:] == ImmutableDenseNDimArray([23])
assert arr_with_one_element.rank() == 1
arr_with_symbol_element = ImmutableDenseNDimArray([Symbol('x')])
assert len(arr_with_symbol_element) == 1
assert arr_with_symbol_element[0] == Symbol('x')
assert arr_with_symbol_element[:] == ImmutableDenseNDimArray([Symbol('x')])
assert arr_with_symbol_element.rank() == 1
number5 = 5
vector = ImmutableDenseNDimArray.zeros(number5)
assert len(vector) == number5
assert vector.shape == (number5,)
assert vector.rank() == 1
vector = ImmutableSparseNDimArray.zeros(number5)
assert len(vector) == number5
assert vector.shape == (number5,)
assert vector._sparse_array == Dict()
assert vector.rank() == 1
n_dim_array = ImmutableDenseNDimArray(range(3**4), (3, 3, 3, 3,))
assert len(n_dim_array) == 3 * 3 * 3 * 3
assert n_dim_array.shape == (3, 3, 3, 3)
assert n_dim_array.rank() == 4
array_shape = (3, 3, 3, 3)
sparse_array = ImmutableSparseNDimArray.zeros(*array_shape)
assert len(sparse_array._sparse_array) == 0
assert len(sparse_array) == 3 * 3 * 3 * 3
assert n_dim_array.shape == array_shape
assert n_dim_array.rank() == 4
one_dim_array = ImmutableDenseNDimArray([2, 3, 1])
assert len(one_dim_array) == 3
assert one_dim_array.shape == (3,)
assert one_dim_array.rank() == 1
assert one_dim_array.tolist() == [2, 3, 1]
shape = (3, 3)
array_with_many_args = ImmutableSparseNDimArray.zeros(*shape)
assert len(array_with_many_args) == 3 * 3
assert array_with_many_args.shape == shape
assert array_with_many_args[0, 0] == 0
assert array_with_many_args.rank() == 2
shape = (int(3), int(3))
array_with_long_shape = ImmutableSparseNDimArray.zeros(*shape)
assert len(array_with_long_shape) == 3 * 3
assert array_with_long_shape.shape == shape
assert array_with_long_shape[int(0), int(0)] == 0
assert array_with_long_shape.rank() == 2
vector_with_long_shape = ImmutableDenseNDimArray(range(5), int(5))
assert len(vector_with_long_shape) == 5
assert vector_with_long_shape.shape == (int(5),)
assert vector_with_long_shape.rank() == 1
raises(ValueError, lambda: vector_with_long_shape[int(5)])
from sympy.abc import x
for ArrayType in [ImmutableDenseNDimArray, ImmutableSparseNDimArray]:
rank_zero_array = ArrayType(x)
assert len(rank_zero_array) == 1
assert rank_zero_array.shape == ()
assert rank_zero_array.rank() == 0
assert rank_zero_array[()] == x
raises(ValueError, lambda: rank_zero_array[0])
def test_reshape():
array = ImmutableDenseNDimArray(range(50), 50)
assert array.shape == (50,)
assert array.rank() == 1
array = array.reshape(5, 5, 2)
assert array.shape == (5, 5, 2)
assert array.rank() == 3
assert len(array) == 50
def test_getitem():
for ArrayType in [ImmutableDenseNDimArray, ImmutableSparseNDimArray]:
array = ArrayType(range(24)).reshape(2, 3, 4)
assert array.tolist() == [[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]], [[12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]]]
assert array[0] == ArrayType([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]])
assert array[0, 0] == ArrayType([0, 1, 2, 3])
value = 0
for i in range(2):
for j in range(3):
for k in range(4):
assert array[i, j, k] == value
value += 1
raises(ValueError, lambda: array[3, 4, 5])
raises(ValueError, lambda: array[3, 4, 5, 6])
raises(ValueError, lambda: array[3, 4, 5, 3:4])
def test_iterator():
array = ImmutableDenseNDimArray(range(4), (2, 2))
array[0] == ImmutableDenseNDimArray([0, 1])
array[1] == ImmutableDenseNDimArray([2, 3])
array = array.reshape(4)
j = 0
for i in array:
assert i == j
j += 1
def test_sparse():
sparse_array = ImmutableSparseNDimArray([0, 0, 0, 1], (2, 2))
assert len(sparse_array) == 2 * 2
# dictionary where all data is, only non-zero entries are actually stored:
assert len(sparse_array._sparse_array) == 1
assert sparse_array.tolist() == [[0, 0], [0, 1]]
for i, j in zip(sparse_array, [[0, 0], [0, 1]]):
assert i == ImmutableSparseNDimArray(j)
def sparse_assignment():
sparse_array[0, 0] = 123
assert len(sparse_array._sparse_array) == 1
raises(TypeError, sparse_assignment)
assert len(sparse_array._sparse_array) == 1
assert sparse_array[0, 0] == 0
assert sparse_array/0 == ImmutableSparseNDimArray([[S.NaN, S.NaN], [S.NaN, S.ComplexInfinity]], (2, 2))
# test for large scale sparse array
# equality test
assert ImmutableSparseNDimArray.zeros(100000, 200000) == ImmutableSparseNDimArray.zeros(100000, 200000)
# __mul__ and __rmul__
a = ImmutableSparseNDimArray({200001: 1}, (100000, 200000))
assert a * 3 == ImmutableSparseNDimArray({200001: 3}, (100000, 200000))
assert 3 * a == ImmutableSparseNDimArray({200001: 3}, (100000, 200000))
assert a * 0 == ImmutableSparseNDimArray({}, (100000, 200000))
assert 0 * a == ImmutableSparseNDimArray({}, (100000, 200000))
# __truediv__
assert a/3 == ImmutableSparseNDimArray({200001: Rational(1, 3)}, (100000, 200000))
# __neg__
assert -a == ImmutableSparseNDimArray({200001: -1}, (100000, 200000))
def test_calculation():
a = ImmutableDenseNDimArray([1]*9, (3, 3))
b = ImmutableDenseNDimArray([9]*9, (3, 3))
c = a + b
for i in c:
assert i == ImmutableDenseNDimArray([10, 10, 10])
assert c == ImmutableDenseNDimArray([10]*9, (3, 3))
assert c == ImmutableSparseNDimArray([10]*9, (3, 3))
c = b - a
for i in c:
assert i == ImmutableDenseNDimArray([8, 8, 8])
assert c == ImmutableDenseNDimArray([8]*9, (3, 3))
assert c == ImmutableSparseNDimArray([8]*9, (3, 3))
def test_ndim_array_converting():
dense_array = ImmutableDenseNDimArray([1, 2, 3, 4], (2, 2))
alist = dense_array.tolist()
alist == [[1, 2], [3, 4]]
matrix = dense_array.tomatrix()
assert (isinstance(matrix, Matrix))
for i in range(len(dense_array)):
assert dense_array[dense_array._get_tuple_index(i)] == matrix[i]
assert matrix.shape == dense_array.shape
assert ImmutableDenseNDimArray(matrix) == dense_array
assert ImmutableDenseNDimArray(matrix.as_immutable()) == dense_array
assert ImmutableDenseNDimArray(matrix.as_mutable()) == dense_array
sparse_array = ImmutableSparseNDimArray([1, 2, 3, 4], (2, 2))
alist = sparse_array.tolist()
assert alist == [[1, 2], [3, 4]]
matrix = sparse_array.tomatrix()
assert(isinstance(matrix, SparseMatrix))
for i in range(len(sparse_array)):
assert sparse_array[sparse_array._get_tuple_index(i)] == matrix[i]
assert matrix.shape == sparse_array.shape
assert ImmutableSparseNDimArray(matrix) == sparse_array
assert ImmutableSparseNDimArray(matrix.as_immutable()) == sparse_array
assert ImmutableSparseNDimArray(matrix.as_mutable()) == sparse_array
def test_converting_functions():
arr_list = [1, 2, 3, 4]
arr_matrix = Matrix(((1, 2), (3, 4)))
# list
arr_ndim_array = ImmutableDenseNDimArray(arr_list, (2, 2))
assert (isinstance(arr_ndim_array, ImmutableDenseNDimArray))
assert arr_matrix.tolist() == arr_ndim_array.tolist()
# Matrix
arr_ndim_array = ImmutableDenseNDimArray(arr_matrix)
assert (isinstance(arr_ndim_array, ImmutableDenseNDimArray))
assert arr_matrix.tolist() == arr_ndim_array.tolist()
assert arr_matrix.shape == arr_ndim_array.shape
def test_equality():
first_list = [1, 2, 3, 4]
second_list = [1, 2, 3, 4]
third_list = [4, 3, 2, 1]
assert first_list == second_list
assert first_list != third_list
first_ndim_array = ImmutableDenseNDimArray(first_list, (2, 2))
second_ndim_array = ImmutableDenseNDimArray(second_list, (2, 2))
fourth_ndim_array = ImmutableDenseNDimArray(first_list, (2, 2))
assert first_ndim_array == second_ndim_array
def assignment_attempt(a):
a[0, 0] = 0
raises(TypeError, lambda: assignment_attempt(second_ndim_array))
assert first_ndim_array == second_ndim_array
assert first_ndim_array == fourth_ndim_array
def test_arithmetic():
a = ImmutableDenseNDimArray([3 for i in range(9)], (3, 3))
b = ImmutableDenseNDimArray([7 for i in range(9)], (3, 3))
c1 = a + b
c2 = b + a
assert c1 == c2
d1 = a - b
d2 = b - a
assert d1 == d2 * (-1)
e1 = a * 5
e2 = 5 * a
e3 = copy(a)
e3 *= 5
assert e1 == e2 == e3
f1 = a / 5
f2 = copy(a)
f2 /= 5
assert f1 == f2
assert f1[0, 0] == f1[0, 1] == f1[0, 2] == f1[1, 0] == f1[1, 1] == \
f1[1, 2] == f1[2, 0] == f1[2, 1] == f1[2, 2] == Rational(3, 5)
assert type(a) == type(b) == type(c1) == type(c2) == type(d1) == type(d2) \
== type(e1) == type(e2) == type(e3) == type(f1)
z0 = -a
assert z0 == ImmutableDenseNDimArray([-3 for i in range(9)], (3, 3))
def test_higher_dimenions():
m3 = ImmutableDenseNDimArray(range(10, 34), (2, 3, 4))
assert m3.tolist() == [[[10, 11, 12, 13],
[14, 15, 16, 17],
[18, 19, 20, 21]],
[[22, 23, 24, 25],
[26, 27, 28, 29],
[30, 31, 32, 33]]]
assert m3._get_tuple_index(0) == (0, 0, 0)
assert m3._get_tuple_index(1) == (0, 0, 1)
assert m3._get_tuple_index(4) == (0, 1, 0)
assert m3._get_tuple_index(12) == (1, 0, 0)
assert str(m3) == '[[[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]], [[22, 23, 24, 25], [26, 27, 28, 29], [30, 31, 32, 33]]]'
m3_rebuilt = ImmutableDenseNDimArray([[[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]], [[22, 23, 24, 25], [26, 27, 28, 29], [30, 31, 32, 33]]])
assert m3 == m3_rebuilt
m3_other = ImmutableDenseNDimArray([[[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]], [[22, 23, 24, 25], [26, 27, 28, 29], [30, 31, 32, 33]]], (2, 3, 4))
assert m3 == m3_other
def test_rebuild_immutable_arrays():
sparr = ImmutableSparseNDimArray(range(10, 34), (2, 3, 4))
densarr = ImmutableDenseNDimArray(range(10, 34), (2, 3, 4))
assert sparr == sparr.func(*sparr.args)
assert densarr == densarr.func(*densarr.args)
def test_slices():
md = ImmutableDenseNDimArray(range(10, 34), (2, 3, 4))
assert md[:] == ImmutableDenseNDimArray(range(10, 34), (2, 3, 4))
assert md[:, :, 0].tomatrix() == Matrix([[10, 14, 18], [22, 26, 30]])
assert md[0, 1:2, :].tomatrix() == Matrix([[14, 15, 16, 17]])
assert md[0, 1:3, :].tomatrix() == Matrix([[14, 15, 16, 17], [18, 19, 20, 21]])
assert md[:, :, :] == md
sd = ImmutableSparseNDimArray(range(10, 34), (2, 3, 4))
assert sd == ImmutableSparseNDimArray(md)
assert sd[:] == ImmutableSparseNDimArray(range(10, 34), (2, 3, 4))
assert sd[:, :, 0].tomatrix() == Matrix([[10, 14, 18], [22, 26, 30]])
assert sd[0, 1:2, :].tomatrix() == Matrix([[14, 15, 16, 17]])
assert sd[0, 1:3, :].tomatrix() == Matrix([[14, 15, 16, 17], [18, 19, 20, 21]])
assert sd[:, :, :] == sd
def test_diff_and_applyfunc():
from sympy.abc import x, y, z
md = ImmutableDenseNDimArray([[x, y], [x*z, x*y*z]])
assert md.diff(x) == ImmutableDenseNDimArray([[1, 0], [z, y*z]])
assert diff(md, x) == ImmutableDenseNDimArray([[1, 0], [z, y*z]])
sd = ImmutableSparseNDimArray(md)
assert sd == ImmutableSparseNDimArray([x, y, x*z, x*y*z], (2, 2))
assert sd.diff(x) == ImmutableSparseNDimArray([[1, 0], [z, y*z]])
assert diff(sd, x) == ImmutableSparseNDimArray([[1, 0], [z, y*z]])
mdn = md.applyfunc(lambda x: x*3)
assert mdn == ImmutableDenseNDimArray([[3*x, 3*y], [3*x*z, 3*x*y*z]])
assert md != mdn
sdn = sd.applyfunc(lambda x: x/2)
assert sdn == ImmutableSparseNDimArray([[x/2, y/2], [x*z/2, x*y*z/2]])
assert sd != sdn
sdp = sd.applyfunc(lambda x: x+1)
assert sdp == ImmutableSparseNDimArray([[x + 1, y + 1], [x*z + 1, x*y*z + 1]])
assert sd != sdp
def test_op_priority():
from sympy.abc import x
md = ImmutableDenseNDimArray([1, 2, 3])
e1 = (1+x)*md
e2 = md*(1+x)
assert e1 == ImmutableDenseNDimArray([1+x, 2+2*x, 3+3*x])
assert e1 == e2
sd = ImmutableSparseNDimArray([1, 2, 3])
e3 = (1+x)*sd
e4 = sd*(1+x)
assert e3 == ImmutableDenseNDimArray([1+x, 2+2*x, 3+3*x])
assert e3 == e4
def test_symbolic_indexing():
x, y, z, w = symbols("x y z w")
M = ImmutableDenseNDimArray([[x, y], [z, w]])
i, j = symbols("i, j")
Mij = M[i, j]
assert isinstance(Mij, Indexed)
Ms = ImmutableSparseNDimArray([[2, 3*x], [4, 5]])
msij = Ms[i, j]
assert isinstance(msij, Indexed)
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 = IndexedBase("A", (0, 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], Indexed)
assert M[3 * i - 2, j].subs({i: 1, j: 0}) == M[1, 0]
assert isinstance(M[i, 0], Indexed)
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) == ImmutableDenseNDimArray([[1, 0], [0, 0]])[i, j]
assert Ms[i, j].diff(x) == ImmutableSparseNDimArray([[0, 3], [0, 0]])[i, j]
Mo = ImmutableDenseNDimArray([1, 2, 3])
assert Mo[i].subs(i, 1) == 2
Mos = ImmutableSparseNDimArray([1, 2, 3])
assert Mos[i].subs(i, 1) == 2
raises(ValueError, lambda: M[i, 2])
raises(ValueError, lambda: M[i, -1])
raises(ValueError, lambda: M[2, i])
raises(ValueError, lambda: M[-1, i])
raises(ValueError, lambda: Ms[i, 2])
raises(ValueError, lambda: Ms[i, -1])
raises(ValueError, lambda: Ms[2, i])
raises(ValueError, lambda: Ms[-1, i])
def test_issue_12665():
# Testing Python 3 hash of immutable arrays:
arr = ImmutableDenseNDimArray([1, 2, 3])
# This should NOT raise an exception:
hash(arr)
def test_zeros_without_shape():
arr = ImmutableDenseNDimArray.zeros()
assert arr == ImmutableDenseNDimArray(0)
def test_issue_21870():
a0 = ImmutableDenseNDimArray(0)
assert a0.rank() == 0
a1 = ImmutableDenseNDimArray(a0)
assert a1.rank() == 0
|
0944f44a09ba6536f5217c61656405cf25f5553dd280f9fb1c1ce394ba59a5d1 | from copy import copy
from sympy.tensor.array.dense_ndim_array import MutableDenseNDimArray
from sympy.core.function import diff
from sympy.core.numbers import Rational
from sympy.core.singleton import S
from sympy.core.symbol import Symbol
from sympy.core.sympify import sympify
from sympy.matrices import SparseMatrix
from sympy.matrices import Matrix
from sympy.tensor.array.sparse_ndim_array import MutableSparseNDimArray
from sympy.testing.pytest import raises
def test_ndim_array_initiation():
arr_with_one_element = MutableDenseNDimArray([23])
assert len(arr_with_one_element) == 1
assert arr_with_one_element[0] == 23
assert arr_with_one_element.rank() == 1
raises(ValueError, lambda: arr_with_one_element[1])
arr_with_symbol_element = MutableDenseNDimArray([Symbol('x')])
assert len(arr_with_symbol_element) == 1
assert arr_with_symbol_element[0] == Symbol('x')
assert arr_with_symbol_element.rank() == 1
number5 = 5
vector = MutableDenseNDimArray.zeros(number5)
assert len(vector) == number5
assert vector.shape == (number5,)
assert vector.rank() == 1
raises(ValueError, lambda: arr_with_one_element[5])
vector = MutableSparseNDimArray.zeros(number5)
assert len(vector) == number5
assert vector.shape == (number5,)
assert vector._sparse_array == {}
assert vector.rank() == 1
n_dim_array = MutableDenseNDimArray(range(3**4), (3, 3, 3, 3,))
assert len(n_dim_array) == 3 * 3 * 3 * 3
assert n_dim_array.shape == (3, 3, 3, 3)
assert n_dim_array.rank() == 4
raises(ValueError, lambda: n_dim_array[0, 0, 0, 3])
raises(ValueError, lambda: n_dim_array[3, 0, 0, 0])
raises(ValueError, lambda: n_dim_array[3**4])
array_shape = (3, 3, 3, 3)
sparse_array = MutableSparseNDimArray.zeros(*array_shape)
assert len(sparse_array._sparse_array) == 0
assert len(sparse_array) == 3 * 3 * 3 * 3
assert n_dim_array.shape == array_shape
assert n_dim_array.rank() == 4
one_dim_array = MutableDenseNDimArray([2, 3, 1])
assert len(one_dim_array) == 3
assert one_dim_array.shape == (3,)
assert one_dim_array.rank() == 1
assert one_dim_array.tolist() == [2, 3, 1]
shape = (3, 3)
array_with_many_args = MutableSparseNDimArray.zeros(*shape)
assert len(array_with_many_args) == 3 * 3
assert array_with_many_args.shape == shape
assert array_with_many_args[0, 0] == 0
assert array_with_many_args.rank() == 2
shape = (int(3), int(3))
array_with_long_shape = MutableSparseNDimArray.zeros(*shape)
assert len(array_with_long_shape) == 3 * 3
assert array_with_long_shape.shape == shape
assert array_with_long_shape[int(0), int(0)] == 0
assert array_with_long_shape.rank() == 2
vector_with_long_shape = MutableDenseNDimArray(range(5), int(5))
assert len(vector_with_long_shape) == 5
assert vector_with_long_shape.shape == (int(5),)
assert vector_with_long_shape.rank() == 1
raises(ValueError, lambda: vector_with_long_shape[int(5)])
from sympy.abc import x
for ArrayType in [MutableDenseNDimArray, MutableSparseNDimArray]:
rank_zero_array = ArrayType(x)
assert len(rank_zero_array) == 1
assert rank_zero_array.shape == ()
assert rank_zero_array.rank() == 0
assert rank_zero_array[()] == x
raises(ValueError, lambda: rank_zero_array[0])
def test_sympify():
from sympy.abc import x, y, z, t
arr = MutableDenseNDimArray([[x, y], [1, z*t]])
arr_other = sympify(arr)
assert arr_other.shape == (2, 2)
assert arr_other == arr
def test_reshape():
array = MutableDenseNDimArray(range(50), 50)
assert array.shape == (50,)
assert array.rank() == 1
array = array.reshape(5, 5, 2)
assert array.shape == (5, 5, 2)
assert array.rank() == 3
assert len(array) == 50
def test_iterator():
array = MutableDenseNDimArray(range(4), (2, 2))
array[0] == MutableDenseNDimArray([0, 1])
array[1] == MutableDenseNDimArray([2, 3])
array = array.reshape(4)
j = 0
for i in array:
assert i == j
j += 1
def test_getitem():
for ArrayType in [MutableDenseNDimArray, MutableSparseNDimArray]:
array = ArrayType(range(24)).reshape(2, 3, 4)
assert array.tolist() == [[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]], [[12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]]]
assert array[0] == ArrayType([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]])
assert array[0, 0] == ArrayType([0, 1, 2, 3])
value = 0
for i in range(2):
for j in range(3):
for k in range(4):
assert array[i, j, k] == value
value += 1
raises(ValueError, lambda: array[3, 4, 5])
raises(ValueError, lambda: array[3, 4, 5, 6])
raises(ValueError, lambda: array[3, 4, 5, 3:4])
def test_sparse():
sparse_array = MutableSparseNDimArray([0, 0, 0, 1], (2, 2))
assert len(sparse_array) == 2 * 2
# dictionary where all data is, only non-zero entries are actually stored:
assert len(sparse_array._sparse_array) == 1
assert sparse_array.tolist() == [[0, 0], [0, 1]]
for i, j in zip(sparse_array, [[0, 0], [0, 1]]):
assert i == MutableSparseNDimArray(j)
sparse_array[0, 0] = 123
assert len(sparse_array._sparse_array) == 2
assert sparse_array[0, 0] == 123
assert sparse_array/0 == MutableSparseNDimArray([[S.ComplexInfinity, S.NaN], [S.NaN, S.ComplexInfinity]], (2, 2))
# when element in sparse array become zero it will disappear from
# dictionary
sparse_array[0, 0] = 0
assert len(sparse_array._sparse_array) == 1
sparse_array[1, 1] = 0
assert len(sparse_array._sparse_array) == 0
assert sparse_array[0, 0] == 0
# test for large scale sparse array
# equality test
a = MutableSparseNDimArray.zeros(100000, 200000)
b = MutableSparseNDimArray.zeros(100000, 200000)
assert a == b
a[1, 1] = 1
b[1, 1] = 2
assert a != b
# __mul__ and __rmul__
assert a * 3 == MutableSparseNDimArray({200001: 3}, (100000, 200000))
assert 3 * a == MutableSparseNDimArray({200001: 3}, (100000, 200000))
assert a * 0 == MutableSparseNDimArray({}, (100000, 200000))
assert 0 * a == MutableSparseNDimArray({}, (100000, 200000))
# __truediv__
assert a/3 == MutableSparseNDimArray({200001: Rational(1, 3)}, (100000, 200000))
# __neg__
assert -a == MutableSparseNDimArray({200001: -1}, (100000, 200000))
def test_calculation():
a = MutableDenseNDimArray([1]*9, (3, 3))
b = MutableDenseNDimArray([9]*9, (3, 3))
c = a + b
for i in c:
assert i == MutableDenseNDimArray([10, 10, 10])
assert c == MutableDenseNDimArray([10]*9, (3, 3))
assert c == MutableSparseNDimArray([10]*9, (3, 3))
c = b - a
for i in c:
assert i == MutableSparseNDimArray([8, 8, 8])
assert c == MutableDenseNDimArray([8]*9, (3, 3))
assert c == MutableSparseNDimArray([8]*9, (3, 3))
def test_ndim_array_converting():
dense_array = MutableDenseNDimArray([1, 2, 3, 4], (2, 2))
alist = dense_array.tolist()
alist == [[1, 2], [3, 4]]
matrix = dense_array.tomatrix()
assert (isinstance(matrix, Matrix))
for i in range(len(dense_array)):
assert dense_array[dense_array._get_tuple_index(i)] == matrix[i]
assert matrix.shape == dense_array.shape
assert MutableDenseNDimArray(matrix) == dense_array
assert MutableDenseNDimArray(matrix.as_immutable()) == dense_array
assert MutableDenseNDimArray(matrix.as_mutable()) == dense_array
sparse_array = MutableSparseNDimArray([1, 2, 3, 4], (2, 2))
alist = sparse_array.tolist()
assert alist == [[1, 2], [3, 4]]
matrix = sparse_array.tomatrix()
assert(isinstance(matrix, SparseMatrix))
for i in range(len(sparse_array)):
assert sparse_array[sparse_array._get_tuple_index(i)] == matrix[i]
assert matrix.shape == sparse_array.shape
assert MutableSparseNDimArray(matrix) == sparse_array
assert MutableSparseNDimArray(matrix.as_immutable()) == sparse_array
assert MutableSparseNDimArray(matrix.as_mutable()) == sparse_array
def test_converting_functions():
arr_list = [1, 2, 3, 4]
arr_matrix = Matrix(((1, 2), (3, 4)))
# list
arr_ndim_array = MutableDenseNDimArray(arr_list, (2, 2))
assert (isinstance(arr_ndim_array, MutableDenseNDimArray))
assert arr_matrix.tolist() == arr_ndim_array.tolist()
# Matrix
arr_ndim_array = MutableDenseNDimArray(arr_matrix)
assert (isinstance(arr_ndim_array, MutableDenseNDimArray))
assert arr_matrix.tolist() == arr_ndim_array.tolist()
assert arr_matrix.shape == arr_ndim_array.shape
def test_equality():
first_list = [1, 2, 3, 4]
second_list = [1, 2, 3, 4]
third_list = [4, 3, 2, 1]
assert first_list == second_list
assert first_list != third_list
first_ndim_array = MutableDenseNDimArray(first_list, (2, 2))
second_ndim_array = MutableDenseNDimArray(second_list, (2, 2))
third_ndim_array = MutableDenseNDimArray(third_list, (2, 2))
fourth_ndim_array = MutableDenseNDimArray(first_list, (2, 2))
assert first_ndim_array == second_ndim_array
second_ndim_array[0, 0] = 0
assert first_ndim_array != second_ndim_array
assert first_ndim_array != third_ndim_array
assert first_ndim_array == fourth_ndim_array
def test_arithmetic():
a = MutableDenseNDimArray([3 for i in range(9)], (3, 3))
b = MutableDenseNDimArray([7 for i in range(9)], (3, 3))
c1 = a + b
c2 = b + a
assert c1 == c2
d1 = a - b
d2 = b - a
assert d1 == d2 * (-1)
e1 = a * 5
e2 = 5 * a
e3 = copy(a)
e3 *= 5
assert e1 == e2 == e3
f1 = a / 5
f2 = copy(a)
f2 /= 5
assert f1 == f2
assert f1[0, 0] == f1[0, 1] == f1[0, 2] == f1[1, 0] == f1[1, 1] == \
f1[1, 2] == f1[2, 0] == f1[2, 1] == f1[2, 2] == Rational(3, 5)
assert type(a) == type(b) == type(c1) == type(c2) == type(d1) == type(d2) \
== type(e1) == type(e2) == type(e3) == type(f1)
z0 = -a
assert z0 == MutableDenseNDimArray([-3 for i in range(9)], (3, 3))
def test_higher_dimenions():
m3 = MutableDenseNDimArray(range(10, 34), (2, 3, 4))
assert m3.tolist() == [[[10, 11, 12, 13],
[14, 15, 16, 17],
[18, 19, 20, 21]],
[[22, 23, 24, 25],
[26, 27, 28, 29],
[30, 31, 32, 33]]]
assert m3._get_tuple_index(0) == (0, 0, 0)
assert m3._get_tuple_index(1) == (0, 0, 1)
assert m3._get_tuple_index(4) == (0, 1, 0)
assert m3._get_tuple_index(12) == (1, 0, 0)
assert str(m3) == '[[[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]], [[22, 23, 24, 25], [26, 27, 28, 29], [30, 31, 32, 33]]]'
m3_rebuilt = MutableDenseNDimArray([[[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]], [[22, 23, 24, 25], [26, 27, 28, 29], [30, 31, 32, 33]]])
assert m3 == m3_rebuilt
m3_other = MutableDenseNDimArray([[[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]], [[22, 23, 24, 25], [26, 27, 28, 29], [30, 31, 32, 33]]], (2, 3, 4))
assert m3 == m3_other
def test_slices():
md = MutableDenseNDimArray(range(10, 34), (2, 3, 4))
assert md[:] == MutableDenseNDimArray(range(10, 34), (2, 3, 4))
assert md[:, :, 0].tomatrix() == Matrix([[10, 14, 18], [22, 26, 30]])
assert md[0, 1:2, :].tomatrix() == Matrix([[14, 15, 16, 17]])
assert md[0, 1:3, :].tomatrix() == Matrix([[14, 15, 16, 17], [18, 19, 20, 21]])
assert md[:, :, :] == md
sd = MutableSparseNDimArray(range(10, 34), (2, 3, 4))
assert sd == MutableSparseNDimArray(md)
assert sd[:] == MutableSparseNDimArray(range(10, 34), (2, 3, 4))
assert sd[:, :, 0].tomatrix() == Matrix([[10, 14, 18], [22, 26, 30]])
assert sd[0, 1:2, :].tomatrix() == Matrix([[14, 15, 16, 17]])
assert sd[0, 1:3, :].tomatrix() == Matrix([[14, 15, 16, 17], [18, 19, 20, 21]])
assert sd[:, :, :] == sd
def test_slices_assign():
a = MutableDenseNDimArray(range(12), shape=(4, 3))
b = MutableSparseNDimArray(range(12), shape=(4, 3))
for i in [a, b]:
assert i.tolist() == [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]
i[0, :] = [2, 2, 2]
assert i.tolist() == [[2, 2, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]
i[0, 1:] = [8, 8]
assert i.tolist() == [[2, 8, 8], [3, 4, 5], [6, 7, 8], [9, 10, 11]]
i[1:3, 1] = [20, 44]
assert i.tolist() == [[2, 8, 8], [3, 20, 5], [6, 44, 8], [9, 10, 11]]
def test_diff():
from sympy.abc import x, y, z
md = MutableDenseNDimArray([[x, y], [x*z, x*y*z]])
assert md.diff(x) == MutableDenseNDimArray([[1, 0], [z, y*z]])
assert diff(md, x) == MutableDenseNDimArray([[1, 0], [z, y*z]])
sd = MutableSparseNDimArray(md)
assert sd == MutableSparseNDimArray([x, y, x*z, x*y*z], (2, 2))
assert sd.diff(x) == MutableSparseNDimArray([[1, 0], [z, y*z]])
assert diff(sd, x) == MutableSparseNDimArray([[1, 0], [z, y*z]])
|
4e3b0b840f3f6422ac6fb5aaf5865d60dedac4a89aab947b1a9ef329603bf85a | from collections import defaultdict
from sympy.concrete.summations import Sum
from sympy.core.add import Add
from sympy.core.mul import Mul
from sympy.core.numbers import Integer
from sympy.core.power import Pow
from sympy.core.sorting import default_sort_key
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.tensor.indexed import (Indexed, IndexedBase)
from sympy.combinatorics import Permutation
from sympy.matrices.expressions.matexpr import MatrixElement
from sympy.tensor.array.expressions.array_expressions import PermuteDims, ArrayDiagonal, \
ArrayContraction, ArrayTensorProduct, ArrayAdd, get_shape, ArrayElement
from sympy.tensor.array.expressions.utils import _get_argindex, _get_diagonal_indices
def convert_indexed_to_array(expr, first_indices=None):
r"""
Parse indexed expression into a form useful for code generation.
Examples
========
>>> from sympy.tensor.array.expressions.conv_indexed_to_array import convert_indexed_to_array
>>> from sympy import MatrixSymbol, Sum, symbols
>>> i, j, k, d = symbols("i j k d")
>>> M = MatrixSymbol("M", d, d)
>>> N = MatrixSymbol("N", d, d)
Recognize the trace in summation form:
>>> expr = Sum(M[i, i], (i, 0, d-1))
>>> convert_indexed_to_array(expr)
ArrayContraction(M, (0, 1))
Recognize the extraction of the diagonal by using the same index `i` on
both axes of the matrix:
>>> expr = M[i, i]
>>> convert_indexed_to_array(expr)
ArrayDiagonal(M, (0, 1))
This function can help perform the transformation expressed in two
different mathematical notations as:
`\sum_{j=0}^{N-1} A_{i,j} B_{j,k} \Longrightarrow \mathbf{A}\cdot \mathbf{B}`
Recognize the matrix multiplication in summation form:
>>> expr = Sum(M[i, j]*N[j, k], (j, 0, d-1))
>>> convert_indexed_to_array(expr)
ArrayContraction(ArrayTensorProduct(M, N), (1, 2))
Specify that ``k`` has to be the starting index:
>>> convert_indexed_to_array(expr, first_indices=[k])
ArrayContraction(ArrayTensorProduct(N, M), (0, 3))
"""
result, indices = _convert_indexed_to_array(expr)
if any(isinstance(i, (int, Integer)) for i in indices):
result = ArrayElement(result, indices)
indices = []
if not first_indices:
return result
def _check_is_in(elem, indices):
if elem in indices:
return True
if any(elem in i for i in indices if isinstance(i, frozenset)):
return True
return False
repl = {j: i for i in indices if isinstance(i, frozenset) for j in i}
first_indices = [repl.get(i, i) for i in first_indices]
for i in first_indices:
if not _check_is_in(i, indices):
first_indices.remove(i)
first_indices.extend([i for i in indices if not _check_is_in(i, first_indices)])
def _get_pos(elem, indices):
if elem in indices:
return indices.index(elem)
for i, e in enumerate(indices):
if not isinstance(e, frozenset):
continue
if elem in e:
return i
raise ValueError("not found")
permutation = [_get_pos(i, first_indices) for i in indices]
return PermuteDims(result, permutation)
def _convert_indexed_to_array(expr):
if isinstance(expr, Sum):
function = expr.function
summation_indices = expr.variables
subexpr, subindices = _convert_indexed_to_array(function)
subindicessets = {j: i for i in subindices if isinstance(i, frozenset) for j in i}
summation_indices = sorted(set([subindicessets.get(i, i) for i in summation_indices]), key=default_sort_key)
# TODO: check that Kronecker delta is only contracted to one other element:
kronecker_indices = set([])
if isinstance(function, Mul):
for arg in function.args:
if not isinstance(arg, KroneckerDelta):
continue
arg_indices = sorted(set(arg.indices), key=default_sort_key)
if len(arg_indices) == 2:
kronecker_indices.update(arg_indices)
kronecker_indices = sorted(kronecker_indices, key=default_sort_key)
# Check dimensional consistency:
shape = get_shape(subexpr)
if shape:
for ind, istart, iend in expr.limits:
i = _get_argindex(subindices, ind)
if istart != 0 or iend+1 != shape[i]:
raise ValueError("summation index and array dimension mismatch: %s" % ind)
contraction_indices = []
subindices = list(subindices)
if isinstance(subexpr, ArrayDiagonal):
diagonal_indices = list(subexpr.diagonal_indices)
dindices = subindices[-len(diagonal_indices):]
subindices = subindices[:-len(diagonal_indices)]
for index in summation_indices:
if index in dindices:
position = dindices.index(index)
contraction_indices.append(diagonal_indices[position])
diagonal_indices[position] = None
diagonal_indices = [i for i in diagonal_indices if i is not None]
for i, ind in enumerate(subindices):
if ind in summation_indices:
pass
if diagonal_indices:
subexpr = ArrayDiagonal(subexpr.expr, *diagonal_indices)
else:
subexpr = subexpr.expr
axes_contraction = defaultdict(list)
for i, ind in enumerate(subindices):
include = all(j not in kronecker_indices for j in ind) if isinstance(ind, frozenset) else ind not in kronecker_indices
if ind in summation_indices and include:
axes_contraction[ind].append(i)
subindices[i] = None
for k, v in axes_contraction.items():
if any(i in kronecker_indices for i in k) if isinstance(k, frozenset) else k in kronecker_indices:
continue
contraction_indices.append(tuple(v))
free_indices = [i for i in subindices if i is not None]
indices_ret = list(free_indices)
indices_ret.sort(key=lambda x: free_indices.index(x))
return ArrayContraction(
subexpr,
*contraction_indices,
free_indices=free_indices
), tuple(indices_ret)
if isinstance(expr, Mul):
args, indices = zip(*[_convert_indexed_to_array(arg) for arg in expr.args])
# Check if there are KroneckerDelta objects:
kronecker_delta_repl = {}
for arg in args:
if not isinstance(arg, KroneckerDelta):
continue
# Diagonalize two indices:
i, j = arg.indices
kindices = set(arg.indices)
if i in kronecker_delta_repl:
kindices.update(kronecker_delta_repl[i])
if j in kronecker_delta_repl:
kindices.update(kronecker_delta_repl[j])
kindices = frozenset(kindices)
for index in kindices:
kronecker_delta_repl[index] = kindices
# Remove KroneckerDelta objects, their relations should be handled by
# ArrayDiagonal:
newargs = []
newindices = []
for arg, loc_indices in zip(args, indices):
if isinstance(arg, KroneckerDelta):
continue
newargs.append(arg)
newindices.append(loc_indices)
flattened_indices = [kronecker_delta_repl.get(j, j) for i in newindices for j in i]
diagonal_indices, ret_indices = _get_diagonal_indices(flattened_indices)
tp = ArrayTensorProduct(*newargs)
if diagonal_indices:
return (ArrayDiagonal(tp, *diagonal_indices), ret_indices)
else:
return tp, ret_indices
if isinstance(expr, MatrixElement):
indices = expr.args[1:]
diagonal_indices, ret_indices = _get_diagonal_indices(indices)
if diagonal_indices:
return (ArrayDiagonal(expr.args[0], *diagonal_indices), ret_indices)
else:
return expr.args[0], ret_indices
if isinstance(expr, Indexed):
indices = expr.indices
diagonal_indices, ret_indices = _get_diagonal_indices(indices)
if diagonal_indices:
return (ArrayDiagonal(expr.base, *diagonal_indices), ret_indices)
else:
return expr.args[0], ret_indices
if isinstance(expr, IndexedBase):
raise NotImplementedError
if isinstance(expr, KroneckerDelta):
return expr, expr.indices
if isinstance(expr, Add):
args, indices = zip(*[_convert_indexed_to_array(arg) for arg in expr.args])
args = list(args)
# Check if all indices are compatible. Otherwise expand the dimensions:
index0set = set(indices[0])
index0 = indices[0]
for i in range(1, len(args)):
if set(indices[i]) != index0set:
raise NotImplementedError("indices must be the same")
permutation = Permutation([index0.index(j) for j in indices[i]])
# Perform index permutations:
args[i] = PermuteDims(args[i], permutation)
return ArrayAdd(*args), index0
if isinstance(expr, Pow):
subexpr, subindices = _convert_indexed_to_array(expr.base)
if isinstance(expr.exp, (int, Integer)):
diags = zip(*[(2*i, 2*i + 1) for i in range(expr.exp)])
arr = ArrayDiagonal(ArrayTensorProduct(*[subexpr for i in range(expr.exp)]), *diags)
return arr, subindices
return expr, ()
|
2a9dba2e48ce307e248aab58f508e2baa6d339a0eccc974f58931fa1f7ffd0e5 | import itertools
from collections import defaultdict
from typing import Tuple as tTuple, Union as tUnion, FrozenSet, Dict as tDict, List, Optional
from functools import singledispatch
from itertools import accumulate
from sympy import MatMul, Basic, Wild
from sympy.assumptions.ask import (Q, ask)
from sympy.core.mul import Mul
from sympy.core.singleton import S
from sympy.matrices.expressions.diagonal import DiagMatrix
from sympy.matrices.expressions.hadamard import hadamard_product, HadamardPower
from sympy.matrices.expressions.matexpr import MatrixExpr
from sympy.matrices.expressions.special import (Identity, ZeroMatrix, OneMatrix)
from sympy.matrices.expressions.trace import Trace
from sympy.matrices.expressions.transpose import Transpose
from sympy.combinatorics.permutations import _af_invert, Permutation
from sympy.matrices.common import MatrixCommon
from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction
from sympy.matrices.expressions.matexpr import MatrixElement
from sympy.tensor.array.expressions.array_expressions import PermuteDims, ArrayDiagonal, \
ArrayTensorProduct, OneArray, get_rank, _get_subrank, ZeroArray, ArrayContraction, \
ArrayAdd, _CodegenArrayAbstract, get_shape, ArrayElementwiseApplyFunc, _ArrayExpr, _EditArrayContraction, _ArgE, \
ArrayElement
from sympy.tensor.array.expressions.utils import _get_mapping_from_subranks
def _get_candidate_for_matmul_from_contraction(scan_indices: List[Optional[int]], remaining_args: List[_ArgE]) -> tTuple[Optional[_ArgE], bool, int]:
scan_indices_int: List[int] = [i for i in scan_indices if i is not None]
if len(scan_indices_int) == 0:
return None, False, -1
transpose: bool = False
candidate: Optional[_ArgE] = None
candidate_index: int = -1
for arg_with_ind2 in remaining_args:
if not isinstance(arg_with_ind2.element, MatrixExpr):
continue
for index in scan_indices_int:
if candidate_index != -1 and candidate_index != index:
# A candidate index has already been selected, check
# repetitions only for that index:
continue
if index in arg_with_ind2.indices:
if set(arg_with_ind2.indices) == {index}:
# Index repeated twice in arg_with_ind2
candidate = None
break
if candidate is None:
candidate = arg_with_ind2
candidate_index = index
transpose = (index == arg_with_ind2.indices[1])
else:
# Index repeated more than twice, break
candidate = None
break
return candidate, transpose, candidate_index
def _insert_candidate_into_editor(editor: _EditArrayContraction, arg_with_ind: _ArgE, candidate: _ArgE, transpose1: bool, transpose2: bool):
other = candidate.element
other_index: Optional[int]
if transpose2:
other = Transpose(other)
other_index = candidate.indices[0]
else:
other_index = candidate.indices[1]
new_element = (Transpose(arg_with_ind.element) if transpose1 else arg_with_ind.element) * other
editor.args_with_ind.remove(candidate)
new_arge = _ArgE(new_element)
return new_arge, other_index
def _support_function_tp1_recognize(contraction_indices, args):
if len(contraction_indices) == 0:
return _a2m_tensor_product(*args)
ac = ArrayContraction(ArrayTensorProduct(*args), *contraction_indices)
editor = _EditArrayContraction(ac)
editor.track_permutation_start()
while True:
flag_stop: bool = True
for i, arg_with_ind in enumerate(editor.args_with_ind):
if not isinstance(arg_with_ind.element, MatrixExpr):
continue
first_index = arg_with_ind.indices[0]
second_index = arg_with_ind.indices[1]
first_frequency = editor.count_args_with_index(first_index)
second_frequency = editor.count_args_with_index(second_index)
if first_index is not None and first_frequency == 1 and first_index == second_index:
flag_stop = False
arg_with_ind.element = Trace(arg_with_ind.element)._normalize()
arg_with_ind.indices = []
break
scan_indices = []
if first_frequency == 2:
scan_indices.append(first_index)
if second_frequency == 2:
scan_indices.append(second_index)
candidate, transpose, found_index = _get_candidate_for_matmul_from_contraction(scan_indices, editor.args_with_ind[i+1:])
if candidate is not None:
flag_stop = False
editor.track_permutation_merge(arg_with_ind, candidate)
transpose1 = found_index == first_index
new_arge, other_index = _insert_candidate_into_editor(editor, arg_with_ind, candidate, transpose1, transpose)
if found_index == first_index:
new_arge.indices = [second_index, other_index]
else:
new_arge.indices = [first_index, other_index]
set_indices = set(new_arge.indices)
if len(set_indices) == 1 and set_indices != {None}:
# This is a trace:
new_arge.element = Trace(new_arge.element)._normalize()
new_arge.indices = []
editor.args_with_ind[i] = new_arge
# TODO: is this break necessary?
break
if flag_stop:
break
editor.refresh_indices()
return editor.to_array_contraction()
def _find_trivial_matrices_rewrite(expr: ArrayTensorProduct):
# If there are matrices of trivial shape in the tensor product (i.e. shape
# (1, 1)), try to check if there is a suitable non-trivial MatMul where the
# expression can be inserted.
# For example, if "a" has shape (1, 1) and "b" has shape (k, 1), the
# expressions "ArrayTensorProduct(a, b*b.T)" can be rewritten as
# "b*a*b.T"
trivial_matrices = []
pos: Optional[int] = None
first: Optional[MatrixExpr] = None
second: Optional[MatrixExpr] = None
removed: List[int] = []
counter: int = 0
args: List[Optional[Basic]] = [i for i in expr.args]
for i, arg in enumerate(expr.args):
if isinstance(arg, MatrixExpr):
if arg.shape == (1, 1):
trivial_matrices.append(arg)
args[i] = None
removed.extend([counter, counter+1])
elif pos is None and isinstance(arg, MatMul):
margs = arg.args
for j, e in enumerate(margs):
if isinstance(e, MatrixExpr) and e.shape[1] == 1:
pos = i
first = MatMul.fromiter(margs[:j+1])
second = MatMul.fromiter(margs[j+1:])
break
counter += get_rank(arg)
if pos is None:
return expr, []
args[pos] = (first*MatMul.fromiter(i for i in trivial_matrices)*second).doit()
return ArrayTensorProduct(*[i for i in args if i is not None]), removed
@singledispatch
def _array2matrix(expr):
return expr
@_array2matrix.register(ZeroArray) # type: ignore
def _(expr: ZeroArray):
if get_rank(expr) == 2:
return ZeroMatrix(*expr.shape)
else:
return expr
@_array2matrix.register(ArrayTensorProduct) # type: ignore
def _(expr: ArrayTensorProduct):
return _a2m_tensor_product(*[_array2matrix(arg) for arg in expr.args])
@_array2matrix.register(ArrayContraction) # type: ignore
def _(expr: ArrayContraction):
expr = expr.flatten_contraction_of_diagonal()
expr = identify_removable_identity_matrices(expr)
expr = expr.split_multiple_contractions()
expr = identify_hadamard_products(expr)
if not isinstance(expr, ArrayContraction):
return _array2matrix(expr)
subexpr = expr.expr
contraction_indices: tTuple[tTuple[int]] = expr.contraction_indices
if contraction_indices == ((0,), (1,)) or (
contraction_indices == ((0,),) and subexpr.shape[1] == 1
) or (
contraction_indices == ((1,),) and subexpr.shape[0] == 1
):
shape = subexpr.shape
subexpr = _array2matrix(subexpr)
if isinstance(subexpr, MatrixExpr):
return OneMatrix(1, shape[0])*subexpr*OneMatrix(shape[1], 1)
if isinstance(subexpr, ArrayTensorProduct):
newexpr = ArrayContraction(_array2matrix(subexpr), *contraction_indices)
contraction_indices = newexpr.contraction_indices
if any(i > 2 for i in newexpr.subranks):
addends = ArrayAdd(*[_a2m_tensor_product(*j) for j in itertools.product(*[i.args if isinstance(i,
ArrayAdd) else [i] for i in expr.expr.args])])
newexpr = ArrayContraction(addends, *contraction_indices)
if isinstance(newexpr, ArrayAdd):
ret = _array2matrix(newexpr)
return ret
assert isinstance(newexpr, ArrayContraction)
ret = _support_function_tp1_recognize(contraction_indices, list(newexpr.expr.args))
return ret
elif not isinstance(subexpr, _CodegenArrayAbstract):
ret = _array2matrix(subexpr)
if isinstance(ret, MatrixExpr):
assert expr.contraction_indices == ((0, 1),)
return _a2m_trace(ret)
else:
return ArrayContraction(ret, *expr.contraction_indices)
@_array2matrix.register(ArrayDiagonal) # type: ignore
def _(expr: ArrayDiagonal):
pexpr = ArrayDiagonal(_array2matrix(expr.expr), *expr.diagonal_indices)
pexpr = identify_hadamard_products(pexpr)
if isinstance(pexpr, ArrayDiagonal):
pexpr = _array_diag2contr_diagmatrix(pexpr)
if expr == pexpr:
return expr
return _array2matrix(pexpr)
@_array2matrix.register(PermuteDims) # type: ignore
def _(expr: PermuteDims):
if expr.permutation.array_form == [1, 0]:
return _a2m_transpose(_array2matrix(expr.expr))
elif isinstance(expr.expr, ArrayTensorProduct):
ranks = expr.expr.subranks
inv_permutation = expr.permutation**(-1)
newrange = [inv_permutation(i) for i in range(sum(ranks))]
newpos = []
counter = 0
for rank in ranks:
newpos.append(newrange[counter:counter+rank])
counter += rank
newargs = []
newperm = []
scalars = []
for pos, arg in zip(newpos, expr.expr.args):
if len(pos) == 0:
scalars.append(_array2matrix(arg))
elif pos == sorted(pos):
newargs.append((_array2matrix(arg), pos[0]))
newperm.extend(pos)
elif len(pos) == 2:
newargs.append((_a2m_transpose(_array2matrix(arg)), pos[0]))
newperm.extend(reversed(pos))
else:
raise NotImplementedError()
newargs = [i[0] for i in newargs]
return PermuteDims(_a2m_tensor_product(*scalars, *newargs), _af_invert(newperm))
elif isinstance(expr.expr, ArrayContraction):
mat_mul_lines = _array2matrix(expr.expr)
if not isinstance(mat_mul_lines, ArrayTensorProduct):
flat_cyclic_form = [j for i in expr.permutation.cyclic_form for j in i]
expr_shape = get_shape(expr)
if all(expr_shape[i] == 1 for i in flat_cyclic_form):
return mat_mul_lines
return mat_mul_lines
# TODO: this assumes that all arguments are matrices, it may not be the case:
permutation = Permutation(2*len(mat_mul_lines.args)-1)*expr.permutation
permuted = [permutation(i) for i in range(2*len(mat_mul_lines.args))]
args_array = [None for i in mat_mul_lines.args]
for i in range(len(mat_mul_lines.args)):
p1 = permuted[2*i]
p2 = permuted[2*i+1]
if p1 // 2 != p2 // 2:
return PermuteDims(mat_mul_lines, permutation)
pos = p1 // 2
if p1 > p2:
args_array[i] = _a2m_transpose(mat_mul_lines.args[pos])
else:
args_array[i] = mat_mul_lines.args[pos]
return _a2m_tensor_product(*args_array)
else:
return expr
@_array2matrix.register(ArrayAdd) # type: ignore
def _(expr: ArrayAdd):
addends = [_array2matrix(arg) for arg in expr.args]
return _a2m_add(*addends)
@_array2matrix.register(ArrayElementwiseApplyFunc) # type: ignore
def _(expr: ArrayElementwiseApplyFunc):
subexpr = _array2matrix(expr.expr)
if isinstance(subexpr, MatrixExpr):
if subexpr.shape != (1, 1):
d = expr.function.bound_symbols[0]
w = Wild("w", exclude=[d])
p = Wild("p", exclude=[d])
m = expr.function.expr.match(w*d**p)
if m is not None:
return m[w]*HadamardPower(subexpr, m[p])
return ElementwiseApplyFunction(expr.function, subexpr)
else:
return ArrayElementwiseApplyFunc(expr.function, subexpr)
@_array2matrix.register(ArrayElement) # type: ignore
def _(expr: ArrayElement):
ret = _array2matrix(expr.name)
if isinstance(ret, MatrixExpr):
return MatrixElement(ret, *expr.indices)
return ArrayElement(ret, expr.indices)
@singledispatch
def _remove_trivial_dims(expr):
return expr, []
@_remove_trivial_dims.register(ArrayTensorProduct) # type: ignore
def _(expr: ArrayTensorProduct):
# Recognize expressions like [x, y] with shape (k, 1, k, 1) as `x*y.T`.
# The matrix expression has to be equivalent to the tensor product of the
# matrices, with trivial dimensions (i.e. dim=1) dropped.
# That is, add contractions over trivial dimensions:
removed = []
newargs = []
cumul = list(accumulate([0] + [get_rank(arg) for arg in expr.args]))
pending = None
prev_i = None
for i, arg in enumerate(expr.args):
current_range = list(range(cumul[i], cumul[i+1]))
if isinstance(arg, OneArray):
removed.extend(current_range)
continue
if not isinstance(arg, (MatrixExpr, MatrixCommon)):
rarg, rem = _remove_trivial_dims(arg)
removed.extend(rem)
newargs.append(rarg)
continue
elif getattr(arg, "is_Identity", False) and arg.shape == (1, 1):
if arg.shape == (1, 1):
# Ignore identity matrices of shape (1, 1) - they are equivalent to scalar 1.
removed.extend(current_range)
continue
elif arg.shape == (1, 1):
arg, _ = _remove_trivial_dims(arg)
# Matrix is equivalent to scalar:
if len(newargs) == 0:
newargs.append(arg)
elif 1 in get_shape(newargs[-1]):
if newargs[-1].shape[1] == 1:
newargs[-1] = newargs[-1]*arg
else:
newargs[-1] = arg*newargs[-1]
removed.extend(current_range)
else:
newargs.append(arg)
elif 1 in arg.shape:
k = [i for i in arg.shape if i != 1][0]
if pending is None:
pending = k
prev_i = i
newargs.append(arg)
elif pending == k:
prev = newargs[-1]
if prev.shape[0] == 1:
d1 = cumul[prev_i]
prev = _a2m_transpose(prev)
else:
d1 = cumul[prev_i] + 1
if arg.shape[1] == 1:
d2 = cumul[i] + 1
arg = _a2m_transpose(arg)
else:
d2 = cumul[i]
newargs[-1] = prev*arg
pending = None
removed.extend([d1, d2])
else:
newargs.append(arg)
pending = k
prev_i = i
else:
newargs.append(arg)
pending = None
newexpr, newremoved = _a2m_tensor_product(*newargs), sorted(removed)
if isinstance(newexpr, ArrayTensorProduct):
newexpr, newremoved2 = _find_trivial_matrices_rewrite(newexpr)
newremoved = _combine_removed(-1, newremoved, newremoved2)
return newexpr, newremoved
@_remove_trivial_dims.register(ArrayAdd) # type: ignore
def _(expr: ArrayAdd):
rec = [_remove_trivial_dims(arg) for arg in expr.args]
newargs, removed = zip(*rec)
if len(set(map(tuple, removed))) != 1:
return expr, []
return _a2m_add(*newargs), removed[0]
@_remove_trivial_dims.register(PermuteDims) # type: ignore
def _(expr: PermuteDims):
subexpr, subremoved = _remove_trivial_dims(expr.expr)
p = expr.permutation.array_form
pinv = _af_invert(expr.permutation.array_form)
shift = list(accumulate([1 if i in subremoved else 0 for i in range(len(p))]))
premoved = [pinv[i] for i in subremoved]
p2 = [e - shift[e] for i, e in enumerate(p) if e not in subremoved]
# TODO: check if subremoved should be permuted as well...
newexpr = PermuteDims(subexpr, p2)
premoved = sorted(premoved)
if newexpr != expr:
newexpr, removed2 = _remove_trivial_dims(_array2matrix(newexpr))
premoved = _combine_removed(-1, premoved, removed2)
return newexpr, premoved
@_remove_trivial_dims.register(ArrayContraction) # type: ignore
def _(expr: ArrayContraction):
new_expr, removed0 = _array_contraction_to_diagonal_multiple_identity(expr)
if new_expr != expr:
new_expr2, removed1 = _remove_trivial_dims(_array2matrix(new_expr))
removed = _combine_removed(-1, removed0, removed1)
return new_expr2, removed
rank1 = get_rank(expr)
expr, removed1 = remove_identity_matrices(expr)
if not isinstance(expr, ArrayContraction):
expr2, removed2 = _remove_trivial_dims(expr)
return expr2, _combine_removed(rank1, removed1, removed2)
newexpr, removed2 = _remove_trivial_dims(expr.expr)
shifts = list(accumulate([1 if i in removed2 else 0 for i in range(get_rank(expr.expr))]))
new_contraction_indices = [tuple(j for j in i if j not in removed2) for i in expr.contraction_indices]
# Remove possible empty tuples "()":
new_contraction_indices = [i for i in new_contraction_indices if len(i) > 0]
contraction_indices_flat = [j for i in expr.contraction_indices for j in i]
removed2 = [i for i in removed2 if i not in contraction_indices_flat]
new_contraction_indices = [tuple(j - shifts[j] for j in i) for i in new_contraction_indices]
# Shift removed2:
removed2 = ArrayContraction._push_indices_up(expr.contraction_indices, removed2)
removed = _combine_removed(rank1, removed1, removed2)
return ArrayContraction(newexpr, *new_contraction_indices), list(removed)
def _remove_diagonalized_identity_matrices(expr: ArrayDiagonal):
assert isinstance(expr, ArrayDiagonal)
editor = _EditArrayContraction(expr)
mapping = {i: {j for j in editor.args_with_ind if i in j.indices} for i in range(-1, -1-editor.number_of_diagonal_indices, -1)}
removed = []
counter: int = 0
for i, arg_with_ind in enumerate(editor.args_with_ind):
counter += len(arg_with_ind.indices)
if isinstance(arg_with_ind.element, Identity):
if None in arg_with_ind.indices and any(i is not None and (i < 0) == True for i in arg_with_ind.indices):
diag_ind = [j for j in arg_with_ind.indices if j is not None][0]
other = [j for j in mapping[diag_ind] if j != arg_with_ind][0]
if not isinstance(other.element, MatrixExpr):
continue
if 1 not in other.element.shape:
continue
if None not in other.indices:
continue
editor.args_with_ind[i].element = None
none_index = other.indices.index(None)
other.element = DiagMatrix(other.element)
other_range = editor.get_absolute_range(other)
removed.extend([other_range[0] + none_index])
editor.args_with_ind = [i for i in editor.args_with_ind if i.element is not None]
removed = ArrayDiagonal._push_indices_up(expr.diagonal_indices, removed, get_rank(expr.expr))
return editor.to_array_contraction(), removed
@_remove_trivial_dims.register(ArrayDiagonal) # type: ignore
def _(expr: ArrayDiagonal):
newexpr, removed = _remove_trivial_dims(expr.expr)
shifts = list(accumulate([0] + [1 if i in removed else 0 for i in range(get_rank(expr.expr))]))
new_diag_indices = {i: tuple(j for j in i if j not in removed) for i in expr.diagonal_indices}
for old_diag_tuple, new_diag_tuple in new_diag_indices.items():
if len(new_diag_tuple) == 1:
removed = [i for i in removed if i not in old_diag_tuple]
new_diag_indices = [tuple(j - shifts[j] for j in i) for i in new_diag_indices.values()]
rank = get_rank(expr.expr)
removed = ArrayDiagonal._push_indices_up(expr.diagonal_indices, removed, rank)
removed = sorted({i for i in removed})
# If there are single axes to diagonalize remaining, it means that their
# corresponding dimension has been removed, they no longer need diagonalization:
new_diag_indices = [i for i in new_diag_indices if len(i) > 0]
if len(new_diag_indices) > 0:
newexpr2 = ArrayDiagonal(newexpr, *new_diag_indices, allow_trivial_diags=True)
else:
newexpr2 = newexpr
if isinstance(newexpr2, ArrayDiagonal):
newexpr3, removed2 = _remove_diagonalized_identity_matrices(newexpr2)
removed = _combine_removed(-1, removed, removed2)
return newexpr3, removed
else:
return newexpr2, removed
@_remove_trivial_dims.register(ElementwiseApplyFunction) # type: ignore
def _(expr: ElementwiseApplyFunction):
subexpr, removed = _remove_trivial_dims(expr.expr)
if subexpr.shape == (1, 1):
# TODO: move this to ElementwiseApplyFunction
return expr.function(subexpr), removed + [0, 1]
return ElementwiseApplyFunction(expr.function, subexpr), []
@_remove_trivial_dims.register(ArrayElementwiseApplyFunc) # type: ignore
def _(expr: ArrayElementwiseApplyFunc):
subexpr, removed = _remove_trivial_dims(expr.expr)
return ArrayElementwiseApplyFunc(expr.function, subexpr), removed
def convert_array_to_matrix(expr):
r"""
Recognize matrix expressions in codegen objects.
If more than one matrix multiplication line have been detected, return a
list with the matrix expressions.
Examples
========
>>> from sympy.tensor.array.expressions.conv_indexed_to_array import convert_indexed_to_array
>>> from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct
>>> from sympy import MatrixSymbol, Sum
>>> from sympy.abc import i, j, k, l, N
>>> from sympy.tensor.array.expressions.array_expressions import ArrayContraction
>>> from sympy.tensor.array.expressions.conv_matrix_to_array import convert_matrix_to_array
>>> from sympy.tensor.array.expressions.conv_array_to_matrix import convert_array_to_matrix
>>> A = MatrixSymbol("A", N, N)
>>> B = MatrixSymbol("B", N, N)
>>> C = MatrixSymbol("C", N, N)
>>> D = MatrixSymbol("D", N, N)
>>> expr = Sum(A[i, j]*B[j, k], (j, 0, N-1))
>>> cg = convert_indexed_to_array(expr)
>>> convert_array_to_matrix(cg)
A*B
>>> cg = convert_indexed_to_array(expr, first_indices=[k])
>>> convert_array_to_matrix(cg)
B.T*A.T
Transposition is detected:
>>> expr = Sum(A[j, i]*B[j, k], (j, 0, N-1))
>>> cg = convert_indexed_to_array(expr)
>>> convert_array_to_matrix(cg)
A.T*B
>>> cg = convert_indexed_to_array(expr, first_indices=[k])
>>> convert_array_to_matrix(cg)
B.T*A
Detect the trace:
>>> expr = Sum(A[i, i], (i, 0, N-1))
>>> cg = convert_indexed_to_array(expr)
>>> convert_array_to_matrix(cg)
Trace(A)
Recognize some more complex traces:
>>> expr = Sum(A[i, j]*B[j, i], (i, 0, N-1), (j, 0, N-1))
>>> cg = convert_indexed_to_array(expr)
>>> convert_array_to_matrix(cg)
Trace(A*B)
More complicated expressions:
>>> expr = Sum(A[i, j]*B[k, j]*A[l, k], (j, 0, N-1), (k, 0, N-1))
>>> cg = convert_indexed_to_array(expr)
>>> convert_array_to_matrix(cg)
A*B.T*A.T
Expressions constructed from matrix expressions do not contain literal
indices, the positions of free indices are returned instead:
>>> expr = A*B
>>> cg = convert_matrix_to_array(expr)
>>> convert_array_to_matrix(cg)
A*B
If more than one line of matrix multiplications is detected, return
separate matrix multiplication factors embedded in a tensor product object:
>>> cg = ArrayContraction(ArrayTensorProduct(A, B, C, D), (1, 2), (5, 6))
>>> convert_array_to_matrix(cg)
ArrayTensorProduct(A*B, C*D)
The two lines have free indices at axes 0, 3 and 4, 7, respectively.
"""
rec = _array2matrix(expr)
rec, removed = _remove_trivial_dims(rec)
return rec
def _array_diag2contr_diagmatrix(expr: ArrayDiagonal):
if isinstance(expr.expr, ArrayTensorProduct):
args = list(expr.expr.args)
diag_indices = list(expr.diagonal_indices)
mapping = _get_mapping_from_subranks([_get_subrank(arg) for arg in args])
tuple_links = [[mapping[j] for j in i] for i in diag_indices]
contr_indices = []
total_rank = get_rank(expr)
replaced = [False for arg in args]
for i, (abs_pos, rel_pos) in enumerate(zip(diag_indices, tuple_links)):
if len(abs_pos) != 2:
continue
(pos1_outer, pos1_inner), (pos2_outer, pos2_inner) = rel_pos
arg1 = args[pos1_outer]
arg2 = args[pos2_outer]
if get_rank(arg1) != 2 or get_rank(arg2) != 2:
if replaced[pos1_outer]:
diag_indices[i] = None
if replaced[pos2_outer]:
diag_indices[i] = None
continue
pos1_in2 = 1 - pos1_inner
pos2_in2 = 1 - pos2_inner
if arg1.shape[pos1_in2] == 1:
if arg1.shape[pos1_inner] != 1:
darg1 = DiagMatrix(arg1)
else:
darg1 = arg1
args.append(darg1)
contr_indices.append(((pos2_outer, pos2_inner), (len(args)-1, pos1_inner)))
total_rank += 1
diag_indices[i] = None
args[pos1_outer] = OneArray(arg1.shape[pos1_in2])
replaced[pos1_outer] = True
elif arg2.shape[pos2_in2] == 1:
if arg2.shape[pos2_inner] != 1:
darg2 = DiagMatrix(arg2)
else:
darg2 = arg2
args.append(darg2)
contr_indices.append(((pos1_outer, pos1_inner), (len(args)-1, pos2_inner)))
total_rank += 1
diag_indices[i] = None
args[pos2_outer] = OneArray(arg2.shape[pos2_in2])
replaced[pos2_outer] = True
diag_indices_new = [i for i in diag_indices if i is not None]
cumul = list(accumulate([0] + [get_rank(arg) for arg in args]))
contr_indices2 = [tuple(cumul[a] + b for a, b in i) for i in contr_indices]
tc = ArrayContraction(
ArrayTensorProduct(*args), *contr_indices2
)
td = ArrayDiagonal(tc, *diag_indices_new)
return td
return expr
def _a2m_mul(*args):
if not any(isinstance(i, _CodegenArrayAbstract) for i in args):
from sympy.matrices.expressions.matmul import MatMul
return MatMul(*args).doit()
else:
return ArrayContraction(
ArrayTensorProduct(*args),
*[(2*i-1, 2*i) for i in range(1, len(args))]
)
def _a2m_tensor_product(*args):
scalars = []
arrays = []
for arg in args:
if isinstance(arg, (MatrixExpr, _ArrayExpr, _CodegenArrayAbstract)):
arrays.append(arg)
else:
scalars.append(arg)
scalar = Mul.fromiter(scalars)
if len(arrays) == 0:
return scalar
if scalar != 1:
if isinstance(arrays[0], _CodegenArrayAbstract):
arrays = [scalar] + arrays
else:
arrays[0] *= scalar
return ArrayTensorProduct(*arrays)
def _a2m_add(*args):
if not any(isinstance(i, _CodegenArrayAbstract) for i in args):
from sympy.matrices.expressions.matadd import MatAdd
return MatAdd(*args).doit()
else:
return ArrayAdd(*args)
def _a2m_trace(arg):
if isinstance(arg, _CodegenArrayAbstract):
return ArrayContraction(arg, (0, 1))
else:
from sympy.matrices.expressions.trace import Trace
return Trace(arg)
def _a2m_transpose(arg):
if isinstance(arg, _CodegenArrayAbstract):
return PermuteDims(arg, [1, 0])
else:
from sympy.matrices.expressions.transpose import Transpose
return Transpose(arg).doit()
def identify_hadamard_products(expr: tUnion[ArrayContraction, ArrayDiagonal]):
editor: _EditArrayContraction = _EditArrayContraction(expr)
map_contr_to_args: tDict[FrozenSet, List[_ArgE]] = defaultdict(list)
map_ind_to_inds: tDict[Optional[int], int] = defaultdict(int)
for arg_with_ind in editor.args_with_ind:
for ind in arg_with_ind.indices:
map_ind_to_inds[ind] += 1
if None in arg_with_ind.indices:
continue
map_contr_to_args[frozenset(arg_with_ind.indices)].append(arg_with_ind)
k: FrozenSet[int]
v: List[_ArgE]
for k, v in map_contr_to_args.items():
make_trace: bool = False
if len(k) == 1 and next(iter(k)) >= 0 and sum([next(iter(k)) in i for i in map_contr_to_args]) == 1:
# This is a trace: the arguments are fully contracted with only one
# index, and the index isn't used anywhere else:
make_trace = True
first_element = S.One
elif len(k) != 2:
# Hadamard product only defined for matrices:
continue
if len(v) == 1:
# Hadamard product with a single argument makes no sense:
continue
for ind in k:
if map_ind_to_inds[ind] <= 2:
# There is no other contraction, skip:
continue
def check_transpose(x):
x = [i if i >= 0 else -1-i for i in x]
return x == sorted(x)
# Check if expression is a trace:
if all([map_ind_to_inds[j] == len(v) and j >= 0 for j in k]) and all([j >= 0 for j in k]):
# This is a trace
make_trace = True
first_element = v[0].element
if not check_transpose(v[0].indices):
first_element = first_element.T
hadamard_factors = v[1:]
else:
hadamard_factors = v
# This is a Hadamard product:
hp = hadamard_product(*[i.element if check_transpose(i.indices) else Transpose(i.element) for i in hadamard_factors])
hp_indices = v[0].indices
if not check_transpose(hadamard_factors[0].indices):
hp_indices = list(reversed(hp_indices))
if make_trace:
hp = Trace(first_element*hp.T)._normalize()
hp_indices = []
editor.insert_after(v[0], _ArgE(hp, hp_indices))
for i in v:
editor.args_with_ind.remove(i)
return editor.to_array_contraction()
def identify_removable_identity_matrices(expr):
editor = _EditArrayContraction(expr)
flag: bool = True
while flag:
flag = False
for arg_with_ind in editor.args_with_ind:
if isinstance(arg_with_ind.element, Identity):
k = arg_with_ind.element.shape[0]
# Candidate for removal:
if arg_with_ind.indices == [None, None]:
# Free identity matrix, will be cleared by _remove_trivial_dims:
continue
elif None in arg_with_ind.indices:
ind = [j for j in arg_with_ind.indices if j is not None][0]
counted = editor.count_args_with_index(ind)
if counted == 1:
# Identity matrix contracted only on one index with itself,
# transform to a OneArray(k) element:
editor.insert_after(arg_with_ind, OneArray(k))
editor.args_with_ind.remove(arg_with_ind)
flag = True
break
elif counted > 2:
# Case counted = 2 is a matrix multiplication by identity matrix, skip it.
# Case counted > 2 is a multiple contraction,
# this is a case where the contraction becomes a diagonalization if the
# identity matrix is dropped.
continue
elif arg_with_ind.indices[0] == arg_with_ind.indices[1]:
ind = arg_with_ind.indices[0]
counted = editor.count_args_with_index(ind)
if counted > 1:
editor.args_with_ind.remove(arg_with_ind)
flag = True
break
else:
# This is a trace, skip it as it will be recognized somewhere else:
pass
elif ask(Q.diagonal(arg_with_ind.element)):
if arg_with_ind.indices == [None, None]:
continue
elif None in arg_with_ind.indices:
pass
elif arg_with_ind.indices[0] == arg_with_ind.indices[1]:
ind = arg_with_ind.indices[0]
counted = editor.count_args_with_index(ind)
if counted == 3:
# A_ai B_bi D_ii ==> A_ai D_ij B_bj
ind_new = editor.get_new_contraction_index()
other_args = [j for j in editor.args_with_ind if j != arg_with_ind]
other_args[1].indices = [ind_new if j == ind else j for j in other_args[1].indices]
arg_with_ind.indices = [ind, ind_new]
flag = True
break
return editor.to_array_contraction()
def remove_identity_matrices(expr: ArrayContraction):
editor = _EditArrayContraction(expr)
removed: List[int] = []
permutation_map = {}
free_indices = list(accumulate([0] + [sum([i is None for i in arg.indices]) for arg in editor.args_with_ind]))
free_map = {k: v for k, v in zip(editor.args_with_ind, free_indices[:-1])}
update_pairs = {}
for ind in range(editor.number_of_contraction_indices):
args = editor.get_args_with_index(ind)
identity_matrices = [i for i in args if isinstance(i.element, Identity)]
number_identity_matrices = len(identity_matrices)
# If the contraction involves a non-identity matrix and multiple identity matrices:
if number_identity_matrices != len(args) - 1 or number_identity_matrices == 0:
continue
# Get the non-identity element:
non_identity = [i for i in args if not isinstance(i.element, Identity)][0]
# Check that all identity matrices have at least one free index
# (otherwise they would be contractions to some other elements)
if any([None not in i.indices for i in identity_matrices]):
continue
# Mark the identity matrices for removal:
for i in identity_matrices:
i.element = None
removed.extend(range(free_map[i], free_map[i] + len([j for j in i.indices if j is None])))
last_removed = removed.pop(-1)
update_pairs[last_removed, ind] = non_identity.indices[:]
# Remove the indices from the non-identity matrix, as the contraction
# no longer exists:
non_identity.indices = [None if i == ind else i for i in non_identity.indices]
removed.sort()
shifts = list(accumulate([1 if i in removed else 0 for i in range(get_rank(expr))]))
for (last_removed, ind), non_identity_indices in update_pairs.items():
pos = [free_map[non_identity] + i for i, e in enumerate(non_identity_indices) if e == ind]
assert len(pos) == 1
for j in pos:
permutation_map[j] = last_removed
editor.args_with_ind = [i for i in editor.args_with_ind if i.element is not None]
ret_expr = editor.to_array_contraction()
permutation = []
counter = 0
counter2 = 0
for j in range(get_rank(expr)):
if j in removed:
continue
if counter2 in permutation_map:
target = permutation_map[counter2]
permutation.append(target - shifts[target])
counter2 += 1
else:
while counter in permutation_map.values():
counter += 1
permutation.append(counter)
counter += 1
counter2 += 1
ret_expr2 = PermuteDims(ret_expr, _af_invert(permutation))
return ret_expr2, removed
def _combine_removed(dim: int, removed1: List[int], removed2: List[int]) -> List[int]:
# Concatenate two axis removal operations as performed by
# _remove_trivial_dims,
removed1 = sorted(removed1)
removed2 = sorted(removed2)
i = 0
j = 0
removed = []
while True:
if j >= len(removed2):
while i < len(removed1):
removed.append(removed1[i])
i += 1
break
elif i < len(removed1) and removed1[i] <= i + removed2[j]:
removed.append(removed1[i])
i += 1
else:
removed.append(i + removed2[j])
j += 1
return removed
def _array_contraction_to_diagonal_multiple_identity(expr: ArrayContraction):
editor = _EditArrayContraction(expr)
editor.track_permutation_start()
removed: List[int] = []
diag_index_counter: int = 0
for i in range(editor.number_of_contraction_indices):
identities = []
args = []
for j, arg in enumerate(editor.args_with_ind):
if i not in arg.indices:
continue
if isinstance(arg.element, Identity):
identities.append(arg)
else:
args.append(arg)
if len(identities) == 0:
continue
if len(args) + len(identities) < 3:
continue
new_diag_ind = -1 - diag_index_counter
diag_index_counter += 1
# Variable "flag" to control whether to skip this contraction set:
flag: bool = True
for i1, id1 in enumerate(identities):
if None not in id1.indices:
flag = True
break
free_pos = list(range(*editor.get_absolute_free_range(id1)))[0]
editor._track_permutation[-1].append(free_pos) # type: ignore
id1.element = None
flag = False
break
if flag:
continue
for arg in identities[:i1] + identities[i1+1:]:
arg.element = None
removed.extend(range(*editor.get_absolute_free_range(arg)))
for arg in args:
arg.indices = [new_diag_ind if j == i else j for j in arg.indices]
for j, e in enumerate(editor.args_with_ind):
if e.element is None:
editor._track_permutation[j] = None # type: ignore
editor._track_permutation = [i for i in editor._track_permutation if i is not None] # type: ignore
# Renumber permutation array form in order to deal with deleted positions:
remap = {e: i for i, e in enumerate(sorted({k for j in editor._track_permutation for k in j}))}
editor._track_permutation = [[remap[j] for j in i] for i in editor._track_permutation]
editor.args_with_ind = [i for i in editor.args_with_ind if i.element is not None]
new_expr = editor.to_array_contraction()
return new_expr, removed
|
0ab34a8f599bbc54892524efb0733918a9a9657fd7193c8a916eb972c6c9bcfb | from sympy.core.basic import Basic
from sympy.core.function import Lambda
from sympy.core.mul import Mul
from sympy.core.numbers import Integer
from sympy.core.power import Pow
from sympy.core.singleton import S
from sympy.core.symbol import (Dummy, symbols)
from sympy.matrices.expressions.hadamard import (HadamardPower, HadamardProduct)
from sympy.matrices.expressions.matadd import MatAdd
from sympy.matrices.expressions.matmul import MatMul
from sympy.matrices.expressions.matpow import MatPow
from sympy.matrices.expressions.trace import Trace
from sympy.matrices.expressions.transpose import Transpose
from sympy.matrices.expressions.matexpr import MatrixExpr
from sympy.tensor.array.expressions.array_expressions import ArrayDiagonal, ArrayTensorProduct, \
PermuteDims, ArrayAdd, ArrayContraction, ArrayElementwiseApplyFunc
def convert_matrix_to_array(expr: Basic) -> Basic:
if isinstance(expr, MatMul):
args_nonmat = []
args = []
for arg in expr.args:
if isinstance(arg, MatrixExpr):
args.append(arg)
else:
args_nonmat.append(convert_matrix_to_array(arg))
contractions = [(2*i+1, 2*i+2) for i in range(len(args)-1)]
scalar = ArrayTensorProduct.fromiter(args_nonmat) if args_nonmat else S.One
if scalar == 1:
tprod = ArrayTensorProduct(
*[convert_matrix_to_array(arg) for arg in args])
else:
tprod = ArrayTensorProduct(
scalar,
*[convert_matrix_to_array(arg) for arg in args])
return ArrayContraction(
tprod,
*contractions
)
elif isinstance(expr, MatAdd):
return ArrayAdd(
*[convert_matrix_to_array(arg) for arg in expr.args]
)
elif isinstance(expr, Transpose):
return PermuteDims(
convert_matrix_to_array(expr.args[0]), [1, 0]
)
elif isinstance(expr, Trace):
inner_expr: MatrixExpr = convert_matrix_to_array(expr.arg) # type: ignore
return ArrayContraction(inner_expr, (0, len(inner_expr.shape) - 1))
elif isinstance(expr, Mul):
return ArrayTensorProduct.fromiter(convert_matrix_to_array(i) for i in expr.args)
elif isinstance(expr, Pow):
base = convert_matrix_to_array(expr.base)
if (expr.exp > 0) == True:
return ArrayTensorProduct.fromiter(base for i in range(expr.exp))
else:
return expr
elif isinstance(expr, MatPow):
base = convert_matrix_to_array(expr.base)
if expr.exp.is_Integer != True:
b = symbols("b", cls=Dummy)
return ArrayElementwiseApplyFunc(Lambda(b, b**expr.exp), convert_matrix_to_array(base))
elif (expr.exp > 0) == True:
return convert_matrix_to_array(MatMul.fromiter(base for i in range(expr.exp)))
else:
return expr
elif isinstance(expr, HadamardProduct):
tp = ArrayTensorProduct.fromiter([convert_matrix_to_array(arg) for arg in expr.args])
diag = [[2*i for i in range(len(expr.args))], [2*i+1 for i in range(len(expr.args))]]
return ArrayDiagonal(tp, *diag)
elif isinstance(expr, HadamardPower):
base, exp = expr.args
if isinstance(exp, Integer) and exp > 0:
return convert_matrix_to_array(HadamardProduct.fromiter(base for i in range(exp)))
else:
d = Dummy("d")
return ArrayElementwiseApplyFunc(Lambda(d, d**exp), base)
else:
return expr
|
5b08e4471eeebe9700ad855337c912ff66b59bf13742a3e4d92d44ad3a357696 | import bisect
from collections import defaultdict
from sympy.core.containers import Tuple
from sympy.core.numbers import Integer
def _get_mapping_from_subranks(subranks):
mapping = {}
counter = 0
for i, rank in enumerate(subranks):
for j in range(rank):
mapping[counter] = (i, j)
counter += 1
return mapping
def _get_contraction_links(args, subranks, *contraction_indices):
mapping = _get_mapping_from_subranks(subranks)
contraction_tuples = [[mapping[j] for j in i] for i in contraction_indices]
dlinks = defaultdict(dict)
for links in contraction_tuples:
if len(links) == 2:
(arg1, pos1), (arg2, pos2) = links
dlinks[arg1][pos1] = (arg2, pos2)
dlinks[arg2][pos2] = (arg1, pos1)
continue
return args, dict(dlinks)
def _sort_contraction_indices(pairing_indices):
pairing_indices = [Tuple(*sorted(i)) for i in pairing_indices]
pairing_indices.sort(key=lambda x: min(x))
return pairing_indices
def _get_diagonal_indices(flattened_indices):
axes_contraction = defaultdict(list)
for i, ind in enumerate(flattened_indices):
if isinstance(ind, (int, Integer)):
# If the indices is a number, there can be no diagonal operation:
continue
axes_contraction[ind].append(i)
axes_contraction = {k: v for k, v in axes_contraction.items() if len(v) > 1}
# Put the diagonalized indices at the end:
ret_indices = [i for i in flattened_indices if i not in axes_contraction]
diag_indices = list(axes_contraction)
diag_indices.sort(key=lambda x: flattened_indices.index(x))
diagonal_indices = [tuple(axes_contraction[i]) for i in diag_indices]
ret_indices += diag_indices
ret_indices = tuple(ret_indices)
return diagonal_indices, ret_indices
def _get_argindex(subindices, ind):
for i, sind in enumerate(subindices):
if ind == sind:
return i
if isinstance(sind, (set, frozenset)) and ind in sind:
return i
raise IndexError("%s not found in %s" % (ind, subindices))
def _apply_recursively_over_nested_lists(func, arr):
if isinstance(arr, (tuple, list, Tuple)):
return tuple(_apply_recursively_over_nested_lists(func, i) for i in arr)
elif isinstance(arr, Tuple):
return Tuple.fromiter(_apply_recursively_over_nested_lists(func, i) for i in arr)
else:
return func(arr)
def _build_push_indices_up_func_transformation(flattened_contraction_indices):
shifts = {0: 0}
i = 0
cumulative = 0
while i < len(flattened_contraction_indices):
j = 1
while i+j < len(flattened_contraction_indices):
if flattened_contraction_indices[i] + j != flattened_contraction_indices[i+j]:
break
j += 1
cumulative += j
shifts[flattened_contraction_indices[i]] = cumulative
i += j
shift_keys = sorted(shifts.keys())
def func(idx):
return shifts[shift_keys[bisect.bisect_right(shift_keys, idx)-1]]
def transform(j):
if j in flattened_contraction_indices:
return None
else:
return j - func(j)
return transform
def _build_push_indices_down_func_transformation(flattened_contraction_indices):
N = flattened_contraction_indices[-1]+2
shifts = [i for i in range(N) if i not in flattened_contraction_indices]
def transform(j):
if j < len(shifts):
return shifts[j]
else:
return j + shifts[-1] - len(shifts) + 1
return transform
|
403d1409181e89cc3dc5a949af42eb497614b689d5219dfa8808798db5d70d38 | import operator
from collections import defaultdict, Counter
from functools import reduce
import itertools
from itertools import accumulate
from typing import Optional, List, Dict as tDict, Tuple as tTuple
import typing
from sympy import Integer
from sympy.core.basic import Basic
from sympy.core.containers import Tuple
from sympy.core.expr import Expr
from sympy.core.function import (Function, Lambda)
from sympy.core.mul import Mul
from sympy.core.singleton import S
from sympy.core.sorting import default_sort_key
from sympy.core.symbol import (Dummy, Symbol)
from sympy.matrices.expressions.diagonal import diagonalize_vector
from sympy.matrices.expressions.matexpr import MatrixExpr
from sympy.matrices.expressions.special import ZeroMatrix
from sympy.tensor.array.arrayop import (permutedims, tensorcontraction, tensordiagonal, tensorproduct)
from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArray
from sympy.tensor.array.ndim_array import NDimArray
from sympy.tensor.indexed import (Indexed, IndexedBase)
from sympy.matrices.expressions.matexpr import MatrixElement
from sympy.tensor.array.expressions.utils import _apply_recursively_over_nested_lists, _sort_contraction_indices, \
_get_mapping_from_subranks, _build_push_indices_up_func_transformation, _get_contraction_links, \
_build_push_indices_down_func_transformation
from sympy.combinatorics import Permutation
from sympy.combinatorics.permutations import _af_invert
from sympy.core.sympify import _sympify
class _ArrayExpr(Expr):
pass
class ArraySymbol(_ArrayExpr):
"""
Symbol representing an array expression
"""
def __new__(cls, symbol, shape: typing.Iterable) -> "ArraySymbol":
if isinstance(symbol, str):
symbol = Symbol(symbol)
# symbol = _sympify(symbol)
shape = Tuple(*map(_sympify, shape))
obj = Expr.__new__(cls, symbol, shape)
return obj
@property
def name(self):
return self._args[0]
@property
def shape(self):
return self._args[1]
def __getitem__(self, item):
return ArrayElement(self, item)
def as_explicit(self):
if not all(i.is_Integer for i in self.shape):
raise ValueError("cannot express explicit array with symbolic shape")
data = [self[i] for i in itertools.product(*[range(j) for j in self.shape])]
return ImmutableDenseNDimArray(data).reshape(*self.shape)
class ArrayElement(_ArrayExpr):
"""
An element of an array.
"""
def __new__(cls, name, indices):
if isinstance(name, str):
name = Symbol(name)
name = _sympify(name)
indices = _sympify(tuple(indices))
if hasattr(name, "shape"):
if any((i >= s) == True for i, s in zip(indices, name.shape)):
raise ValueError("shape is out of bounds")
if any((i < 0) == True for i in indices):
raise ValueError("shape contains negative values")
obj = Expr.__new__(cls, name, indices)
return obj
@property
def name(self):
return self._args[0]
@property
def indices(self):
return self._args[1]
class ZeroArray(_ArrayExpr):
"""
Symbolic array of zeros. Equivalent to ``ZeroMatrix`` for matrices.
"""
def __new__(cls, *shape):
if len(shape) == 0:
return S.Zero
shape = map(_sympify, shape)
obj = Expr.__new__(cls, *shape)
return obj
@property
def shape(self):
return self._args
def as_explicit(self):
if not all(i.is_Integer for i in self.shape):
raise ValueError("Cannot return explicit form for symbolic shape.")
return ImmutableDenseNDimArray.zeros(*self.shape)
class OneArray(_ArrayExpr):
"""
Symbolic array of ones.
"""
def __new__(cls, *shape):
if len(shape) == 0:
return S.One
shape = map(_sympify, shape)
obj = Expr.__new__(cls, *shape)
return obj
@property
def shape(self):
return self._args
def as_explicit(self):
if not all(i.is_Integer for i in self.shape):
raise ValueError("Cannot return explicit form for symbolic shape.")
return ImmutableDenseNDimArray([S.One for i in range(reduce(operator.mul, self.shape))]).reshape(*self.shape)
class _CodegenArrayAbstract(Basic):
@property
def subranks(self):
"""
Returns the ranks of the objects in the uppermost tensor product inside
the current object. In case no tensor products are contained, return
the atomic ranks.
Examples
========
>>> from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct, ArrayContraction
>>> from sympy import MatrixSymbol
>>> M = MatrixSymbol("M", 3, 3)
>>> N = MatrixSymbol("N", 3, 3)
>>> P = MatrixSymbol("P", 3, 3)
Important: do not confuse the rank of the matrix with the rank of an array.
>>> tp = ArrayTensorProduct(M, N, P)
>>> tp.subranks
[2, 2, 2]
>>> co = ArrayContraction(tp, (1, 2), (3, 4))
>>> co.subranks
[2, 2, 2]
"""
return self._subranks[:]
def subrank(self):
"""
The sum of ``subranks``.
"""
return sum(self.subranks)
@property
def shape(self):
return self._shape
class ArrayTensorProduct(_CodegenArrayAbstract):
r"""
Class to represent the tensor product of array-like objects.
"""
def __new__(cls, *args, **kwargs):
args = [_sympify(arg) for arg in args]
normalize = kwargs.pop("normalize", True)
ranks = [get_rank(arg) for arg in args]
obj = Basic.__new__(cls, *args)
obj._subranks = ranks
shapes = [get_shape(i) for i in args]
if any(i is None for i in shapes):
obj._shape = None
else:
obj._shape = tuple(j for i in shapes for j in i)
if normalize:
return obj._normalize()
return obj
def _normalize(self):
args = self.args
args = self._flatten(args)
ranks = [get_rank(arg) for arg in args]
# Check if there are nested permutation and lift them up:
permutation_cycles = []
for i, arg in enumerate(args):
if not isinstance(arg, PermuteDims):
continue
permutation_cycles.extend([[k + sum(ranks[:i]) for k in j] for j in arg.permutation.cyclic_form])
args[i] = arg.expr
if permutation_cycles:
return PermuteDims(ArrayTensorProduct(*args), Permutation(sum(ranks)-1)*Permutation(permutation_cycles))
if len(args) == 1:
return args[0]
# If any object is a ZeroArray, return a ZeroArray:
if any(isinstance(arg, (ZeroArray, ZeroMatrix)) for arg in args):
shapes = reduce(operator.add, [get_shape(i) for i in args], ())
return ZeroArray(*shapes)
# If there are contraction objects inside, transform the whole
# expression into `ArrayContraction`:
contractions = {i: arg for i, arg in enumerate(args) if isinstance(arg, ArrayContraction)}
if contractions:
ranks = [_get_subrank(arg) if isinstance(arg, ArrayContraction) else get_rank(arg) for arg in args]
cumulative_ranks = list(accumulate([0] + ranks))[:-1]
tp = self.func(*[arg.expr if isinstance(arg, ArrayContraction) else arg for arg in args])
contraction_indices = [tuple(cumulative_ranks[i] + k for k in j) for i, arg in contractions.items() for j in arg.contraction_indices]
return ArrayContraction(tp, *contraction_indices)
diagonals = {i: arg for i, arg in enumerate(args) if isinstance(arg, ArrayDiagonal)}
if diagonals:
inverse_permutation = []
last_perm = []
ranks = [get_rank(arg) for arg in args]
cumulative_ranks = list(accumulate([0] + ranks))[:-1]
for i, arg in enumerate(args):
if isinstance(arg, ArrayDiagonal):
i1 = get_rank(arg) - len(arg.diagonal_indices)
i2 = len(arg.diagonal_indices)
inverse_permutation.extend([cumulative_ranks[i] + j for j in range(i1)])
last_perm.extend([cumulative_ranks[i] + j for j in range(i1, i1 + i2)])
else:
inverse_permutation.extend([cumulative_ranks[i] + j for j in range(get_rank(arg))])
inverse_permutation.extend(last_perm)
tp = self.func(*[arg.expr if isinstance(arg, ArrayDiagonal) else arg for arg in args])
ranks2 = [_get_subrank(arg) if isinstance(arg, ArrayDiagonal) else get_rank(arg) for arg in args]
cumulative_ranks2 = list(accumulate([0] + ranks2))[:-1]
diagonal_indices = [tuple(cumulative_ranks2[i] + k for k in j) for i, arg in diagonals.items() for j in arg.diagonal_indices]
return PermuteDims(ArrayDiagonal(tp, *diagonal_indices), _af_invert(inverse_permutation))
return self.func(*args, normalize=False)
@classmethod
def _flatten(cls, args):
args = [i for arg in args for i in (arg.args if isinstance(arg, cls) else [arg])]
return args
def as_explicit(self):
return tensorproduct(*[arg.as_explicit() if hasattr(arg, "as_explicit") else arg for arg in self.args])
class ArrayAdd(_CodegenArrayAbstract):
r"""
Class for elementwise array additions.
"""
def __new__(cls, *args, **kwargs):
args = [_sympify(arg) for arg in args]
ranks = [get_rank(arg) for arg in args]
ranks = list(set(ranks))
if len(ranks) != 1:
raise ValueError("summing arrays of different ranks")
shapes = [arg.shape for arg in args]
if len({i for i in shapes if i is not None}) > 1:
raise ValueError("mismatching shapes in addition")
normalize = kwargs.pop("normalize", True)
obj = Basic.__new__(cls, *args)
obj._subranks = ranks
if any(i is None for i in shapes):
obj._shape = None
else:
obj._shape = shapes[0]
if normalize:
return obj._normalize()
return obj
def _normalize(self):
args = self.args
# Flatten:
args = self._flatten_args(args)
shapes = [get_shape(arg) for arg in args]
args = [arg for arg in args if not isinstance(arg, (ZeroArray, ZeroMatrix))]
if len(args) == 0:
if any(i for i in shapes if i is None):
raise NotImplementedError("cannot handle addition of ZeroMatrix/ZeroArray and undefined shape object")
return ZeroArray(*shapes[0])
elif len(args) == 1:
return args[0]
return self.func(*args, normalize=False)
@classmethod
def _flatten_args(cls, args):
new_args = []
for arg in args:
if isinstance(arg, ArrayAdd):
new_args.extend(arg.args)
else:
new_args.append(arg)
return new_args
def as_explicit(self):
return reduce(operator.add, [arg.as_explicit() for arg in self.args])
class PermuteDims(_CodegenArrayAbstract):
r"""
Class to represent permutation of axes of arrays.
Examples
========
>>> from sympy.tensor.array.expressions.array_expressions import PermuteDims
>>> from sympy import MatrixSymbol
>>> M = MatrixSymbol("M", 3, 3)
>>> cg = PermuteDims(M, [1, 0])
The object ``cg`` represents the transposition of ``M``, as the permutation
``[1, 0]`` will act on its indices by switching them:
`M_{ij} \Rightarrow M_{ji}`
This is evident when transforming back to matrix form:
>>> from sympy.tensor.array.expressions.conv_array_to_matrix import convert_array_to_matrix
>>> convert_array_to_matrix(cg)
M.T
>>> N = MatrixSymbol("N", 3, 2)
>>> cg = PermuteDims(N, [1, 0])
>>> cg.shape
(2, 3)
Permutations of tensor products are simplified in order to achieve a
standard form:
>>> from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct
>>> M = MatrixSymbol("M", 4, 5)
>>> tp = ArrayTensorProduct(M, N)
>>> tp.shape
(4, 5, 3, 2)
>>> perm1 = PermuteDims(tp, [2, 3, 1, 0])
The args ``(M, N)`` have been sorted and the permutation has been
simplified, the expression is equivalent:
>>> perm1.expr.args
(N, M)
>>> perm1.shape
(3, 2, 5, 4)
>>> perm1.permutation
(2 3)
The permutation in its array form has been simplified from
``[2, 3, 1, 0]`` to ``[0, 1, 3, 2]``, as the arguments of the tensor
product `M` and `N` have been switched:
>>> perm1.permutation.array_form
[0, 1, 3, 2]
We can nest a second permutation:
>>> perm2 = PermuteDims(perm1, [1, 0, 2, 3])
>>> perm2.shape
(2, 3, 5, 4)
>>> perm2.permutation.array_form
[1, 0, 3, 2]
"""
def __new__(cls, expr, permutation, **kwargs):
from sympy.combinatorics import Permutation
expr = _sympify(expr)
permutation = Permutation(permutation)
permutation_size = permutation.size
expr_rank = get_rank(expr)
if permutation_size != expr_rank:
raise ValueError("Permutation size must be the length of the shape of expr")
normalize = kwargs.pop("normalize", True)
obj = Basic.__new__(cls, expr, permutation)
obj._subranks = [get_rank(expr)]
shape = get_shape(expr)
if shape is None:
obj._shape = None
else:
obj._shape = tuple(shape[permutation(i)] for i in range(len(shape)))
if normalize:
return obj._normalize()
return obj
def _normalize(self):
expr = self.expr
permutation = self.permutation
if isinstance(expr, PermuteDims):
subexpr = expr.expr
subperm = expr.permutation
permutation = permutation * subperm
expr = subexpr
if isinstance(expr, ArrayContraction):
expr, permutation = self._PermuteDims_denestarg_ArrayContraction(expr, permutation)
if isinstance(expr, ArrayTensorProduct):
expr, permutation = self._PermuteDims_denestarg_ArrayTensorProduct(expr, permutation)
if isinstance(expr, (ZeroArray, ZeroMatrix)):
return ZeroArray(*[expr.shape[i] for i in permutation.array_form])
plist = permutation.array_form
if plist == sorted(plist):
return expr
return self.func(expr, permutation, normalize=False)
@property
def expr(self):
return self.args[0]
@property
def permutation(self):
return self.args[1]
@classmethod
def _PermuteDims_denestarg_ArrayTensorProduct(cls, expr, permutation):
# Get the permutation in its image-form:
perm_image_form = _af_invert(permutation.array_form)
args = list(expr.args)
# Starting index global position for every arg:
cumul = list(accumulate([0] + expr.subranks))
# Split `perm_image_form` into a list of list corresponding to the indices
# of every argument:
perm_image_form_in_components = [perm_image_form[cumul[i]:cumul[i+1]] for i in range(len(args))]
# Create an index, target-position-key array:
ps = [(i, sorted(comp)) for i, comp in enumerate(perm_image_form_in_components)]
# Sort the array according to the target-position-key:
# In this way, we define a canonical way to sort the arguments according
# to the permutation.
ps.sort(key=lambda x: x[1])
# Read the inverse-permutation (i.e. image-form) of the args:
perm_args_image_form = [i[0] for i in ps]
# Apply the args-permutation to the `args`:
args_sorted = [args[i] for i in perm_args_image_form]
# Apply the args-permutation to the array-form of the permutation of the axes (of `expr`):
perm_image_form_sorted_args = [perm_image_form_in_components[i] for i in perm_args_image_form]
new_permutation = Permutation(_af_invert([j for i in perm_image_form_sorted_args for j in i]))
return ArrayTensorProduct(*args_sorted), new_permutation
@classmethod
def _PermuteDims_denestarg_ArrayContraction(cls, expr, permutation):
if not isinstance(expr, ArrayContraction):
return expr, permutation
if not isinstance(expr.expr, ArrayTensorProduct):
return expr, permutation
args = expr.expr.args
subranks = [get_rank(arg) for arg in expr.expr.args]
contraction_indices = expr.contraction_indices
contraction_indices_flat = [j for i in contraction_indices for j in i]
cumul = list(accumulate([0] + subranks))
# Spread the permutation in its array form across the args in the corresponding
# tensor-product arguments with free indices:
permutation_array_blocks_up = []
image_form = _af_invert(permutation.array_form)
counter = 0
for i, e in enumerate(subranks):
current = []
for j in range(cumul[i], cumul[i+1]):
if j in contraction_indices_flat:
continue
current.append(image_form[counter])
counter += 1
permutation_array_blocks_up.append(current)
# Get the map of axis repositioning for every argument of tensor-product:
index_blocks = [[j for j in range(cumul[i], cumul[i+1])] for i, e in enumerate(expr.subranks)]
index_blocks_up = expr._push_indices_up(expr.contraction_indices, index_blocks)
inverse_permutation = permutation**(-1)
index_blocks_up_permuted = [[inverse_permutation(j) for j in i if j is not None] for i in index_blocks_up]
# Sorting key is a list of tuple, first element is the index of `args`, second element of
# the tuple is the sorting key to sort `args` of the tensor product:
sorting_keys = list(enumerate(index_blocks_up_permuted))
sorting_keys.sort(key=lambda x: x[1])
# Now we can get the permutation acting on the args in its image-form:
new_perm_image_form = [i[0] for i in sorting_keys]
# Apply the args-level permutation to various elements:
new_index_blocks = [index_blocks[i] for i in new_perm_image_form]
new_index_perm_array_form = _af_invert([j for i in new_index_blocks for j in i])
new_args = [args[i] for i in new_perm_image_form]
new_contraction_indices = [tuple(new_index_perm_array_form[j] for j in i) for i in contraction_indices]
new_expr = ArrayContraction(ArrayTensorProduct(*new_args), *new_contraction_indices)
new_permutation = Permutation(_af_invert([j for i in [permutation_array_blocks_up[k] for k in new_perm_image_form] for j in i]))
return new_expr, new_permutation
@classmethod
def _check_permutation_mapping(cls, expr, permutation):
subranks = expr.subranks
index2arg = [i for i, arg in enumerate(expr.args) for j in range(expr.subranks[i])]
permuted_indices = [permutation(i) for i in range(expr.subrank())]
new_args = list(expr.args)
arg_candidate_index = index2arg[permuted_indices[0]]
current_indices = []
new_permutation = []
inserted_arg_cand_indices = set([])
for i, idx in enumerate(permuted_indices):
if index2arg[idx] != arg_candidate_index:
new_permutation.extend(current_indices)
current_indices = []
arg_candidate_index = index2arg[idx]
current_indices.append(idx)
arg_candidate_rank = subranks[arg_candidate_index]
if len(current_indices) == arg_candidate_rank:
new_permutation.extend(sorted(current_indices))
local_current_indices = [j - min(current_indices) for j in current_indices]
i1 = index2arg[i]
new_args[i1] = PermuteDims(new_args[i1], Permutation(local_current_indices))
inserted_arg_cand_indices.add(arg_candidate_index)
current_indices = []
new_permutation.extend(current_indices)
# TODO: swap args positions in order to simplify the expression:
# TODO: this should be in a function
args_positions = list(range(len(new_args)))
# Get possible shifts:
maps = {}
cumulative_subranks = [0] + list(accumulate(subranks))
for i in range(0, len(subranks)):
s = set([index2arg[new_permutation[j]] for j in range(cumulative_subranks[i], cumulative_subranks[i+1])])
if len(s) != 1:
continue
elem = next(iter(s))
if i != elem:
maps[i] = elem
# Find cycles in the map:
lines = []
current_line = []
while maps:
if len(current_line) == 0:
k, v = maps.popitem()
current_line.append(k)
else:
k = current_line[-1]
if k not in maps:
current_line = []
continue
v = maps.pop(k)
if v in current_line:
lines.append(current_line)
current_line = []
continue
current_line.append(v)
for line in lines:
for i, e in enumerate(line):
args_positions[line[(i + 1) % len(line)]] = e
# TODO: function in order to permute the args:
permutation_blocks = [[new_permutation[cumulative_subranks[i] + j] for j in range(e)] for i, e in enumerate(subranks)]
new_args = [new_args[i] for i in args_positions]
new_permutation_blocks = [permutation_blocks[i] for i in args_positions]
new_permutation2 = [j for i in new_permutation_blocks for j in i]
return ArrayTensorProduct(*new_args), Permutation(new_permutation2) # **(-1)
@classmethod
def _check_if_there_are_closed_cycles(cls, expr, permutation):
args = list(expr.args)
subranks = expr.subranks
cyclic_form = permutation.cyclic_form
cumulative_subranks = [0] + list(accumulate(subranks))
cyclic_min = [min(i) for i in cyclic_form]
cyclic_max = [max(i) for i in cyclic_form]
cyclic_keep = []
for i, cycle in enumerate(cyclic_form):
flag = True
for j in range(0, len(cumulative_subranks) - 1):
if cyclic_min[i] >= cumulative_subranks[j] and cyclic_max[i] < cumulative_subranks[j+1]:
# Found a sinkable cycle.
args[j] = PermuteDims(args[j], Permutation([[k - cumulative_subranks[j] for k in cyclic_form[i]]]))
flag = False
break
if flag:
cyclic_keep.append(cyclic_form[i])
return ArrayTensorProduct(*args), Permutation(cyclic_keep, size=permutation.size)
def nest_permutation(self):
r"""
DEPRECATED.
"""
ret = self._nest_permutation(self.expr, self.permutation)
if ret is None:
return self
return ret
@classmethod
def _nest_permutation(cls, expr, permutation):
if isinstance(expr, ArrayTensorProduct):
return PermuteDims(*cls._check_if_there_are_closed_cycles(expr, permutation))
elif isinstance(expr, ArrayContraction):
# Invert tree hierarchy: put the contraction above.
cycles = permutation.cyclic_form
newcycles = ArrayContraction._convert_outer_indices_to_inner_indices(expr, *cycles)
newpermutation = Permutation(newcycles)
new_contr_indices = [tuple(newpermutation(j) for j in i) for i in expr.contraction_indices]
return ArrayContraction(PermuteDims(expr.expr, newpermutation), *new_contr_indices)
elif isinstance(expr, ArrayAdd):
return ArrayAdd(*[PermuteDims(arg, permutation) for arg in expr.args])
return None
def as_explicit(self):
return permutedims(self.expr.as_explicit(), self.permutation)
class ArrayDiagonal(_CodegenArrayAbstract):
r"""
Class to represent the diagonal operator.
Explanation
===========
In a 2-dimensional array it returns the diagonal, this looks like the
operation:
`A_{ij} \rightarrow A_{ii}`
The diagonal over axes 1 and 2 (the second and third) of the tensor product
of two 2-dimensional arrays `A \otimes B` is
`\Big[ A_{ab} B_{cd} \Big]_{abcd} \rightarrow \Big[ A_{ai} B_{id} \Big]_{adi}`
In this last example the array expression has been reduced from
4-dimensional to 3-dimensional. Notice that no contraction has occurred,
rather there is a new index `i` for the diagonal, contraction would have
reduced the array to 2 dimensions.
Notice that the diagonalized out dimensions are added as new dimensions at
the end of the indices.
"""
def __new__(cls, expr, *diagonal_indices, **kwargs):
expr = _sympify(expr)
diagonal_indices = [Tuple(*sorted(i)) for i in diagonal_indices]
normalize = kwargs.get("normalize", True)
shape = get_shape(expr)
if shape is not None:
cls._validate(expr, *diagonal_indices, **kwargs)
# Get new shape:
positions, shape = cls._get_positions_shape(shape, diagonal_indices)
else:
positions = None
if len(diagonal_indices) == 0:
return expr
obj = Basic.__new__(cls, expr, *diagonal_indices)
obj._positions = positions
obj._subranks = _get_subranks(expr)
obj._shape = shape
if normalize:
return obj._normalize()
return obj
def _normalize(self):
expr = self.expr
diagonal_indices = self.diagonal_indices
trivial_diags = [i for i in diagonal_indices if len(i) == 1]
if len(trivial_diags) > 0:
trivial_pos = {e[0]: i for i, e in enumerate(diagonal_indices) if len(e) == 1}
diag_pos = {e: i for i, e in enumerate(diagonal_indices) if len(e) > 1}
diagonal_indices_short = [i for i in diagonal_indices if len(i) > 1]
rank1 = get_rank(self)
rank2 = len(diagonal_indices)
rank3 = rank1 - rank2
inv_permutation = []
counter1: int = 0
indices_down = ArrayDiagonal._push_indices_down(diagonal_indices_short, list(range(rank1)), get_rank(expr))
for i in indices_down:
if i in trivial_pos:
inv_permutation.append(rank3 + trivial_pos[i])
elif isinstance(i, (Integer, int)):
inv_permutation.append(counter1)
counter1 += 1
else:
inv_permutation.append(rank3 + diag_pos[i])
permutation = _af_invert(inv_permutation)
if len(diagonal_indices_short) > 0:
return PermuteDims(ArrayDiagonal(expr, *diagonal_indices_short), permutation)
else:
return PermuteDims(expr, permutation)
if isinstance(expr, ArrayAdd):
return self._ArrayDiagonal_denest_ArrayAdd(expr, *diagonal_indices)
if isinstance(expr, ArrayDiagonal):
return self._ArrayDiagonal_denest_ArrayDiagonal(expr, *diagonal_indices)
if isinstance(expr, PermuteDims):
return self._ArrayDiagonal_denest_PermuteDims(expr, *diagonal_indices)
if isinstance(expr, (ZeroArray, ZeroMatrix)):
positions, shape = self._get_positions_shape(expr.shape, diagonal_indices)
return ZeroArray(*shape)
return self.func(expr, *diagonal_indices, normalize=False)
@staticmethod
def _validate(expr, *diagonal_indices, **kwargs):
# Check that no diagonalization happens on indices with mismatched
# dimensions:
shape = get_shape(expr)
for i in diagonal_indices:
if any(j >= len(shape) for j in i):
raise ValueError("index is larger than expression shape")
if len({shape[j] for j in i}) != 1:
raise ValueError("diagonalizing indices of different dimensions")
if not kwargs.get("allow_trivial_diags", False) and len(i) <= 1:
raise ValueError("need at least two axes to diagonalize")
if len(set(i)) != len(i):
raise ValueError("axis index cannot be repeated")
@staticmethod
def _remove_trivial_dimensions(shape, *diagonal_indices):
return [tuple(j for j in i) for i in diagonal_indices if shape[i[0]] != 1]
@property
def expr(self):
return self.args[0]
@property
def diagonal_indices(self):
return self.args[1:]
@staticmethod
def _flatten(expr, *outer_diagonal_indices):
inner_diagonal_indices = expr.diagonal_indices
all_inner = [j for i in inner_diagonal_indices for j in i]
all_inner.sort()
# TODO: add API for total rank and cumulative rank:
total_rank = _get_subrank(expr)
inner_rank = len(all_inner)
outer_rank = total_rank - inner_rank
shifts = [0 for i in range(outer_rank)]
counter = 0
pointer = 0
for i in range(outer_rank):
while pointer < inner_rank and counter >= all_inner[pointer]:
counter += 1
pointer += 1
shifts[i] += pointer
counter += 1
outer_diagonal_indices = tuple(tuple(shifts[j] + j for j in i) for i in outer_diagonal_indices)
diagonal_indices = inner_diagonal_indices + outer_diagonal_indices
return ArrayDiagonal(expr.expr, *diagonal_indices)
@classmethod
def _ArrayDiagonal_denest_ArrayAdd(cls, expr, *diagonal_indices):
return ArrayAdd(*[ArrayDiagonal(arg, *diagonal_indices) for arg in expr.args])
@classmethod
def _ArrayDiagonal_denest_ArrayDiagonal(cls, expr, *diagonal_indices):
return cls._flatten(expr, *diagonal_indices)
@classmethod
def _ArrayDiagonal_denest_PermuteDims(cls, expr: PermuteDims, *diagonal_indices):
back_diagonal_indices = [[expr.permutation(j) for j in i] for i in diagonal_indices]
nondiag = [i for i in range(get_rank(expr)) if not any(i in j for j in diagonal_indices)]
back_nondiag = [expr.permutation(i) for i in nondiag]
remap = {e: i for i, e in enumerate(sorted(back_nondiag))}
new_permutation1 = [remap[i] for i in back_nondiag]
shift = len(new_permutation1)
diag_block_perm = [i + shift for i in range(len(back_diagonal_indices))]
new_permutation = new_permutation1 + diag_block_perm
return PermuteDims(
ArrayDiagonal(
expr.expr,
*back_diagonal_indices
),
new_permutation
)
def _push_indices_down_nonstatic(self, indices):
transform = lambda x: self._positions[x] if x < len(self._positions) else None
return _apply_recursively_over_nested_lists(transform, indices)
def _push_indices_up_nonstatic(self, indices):
def transform(x):
for i, e in enumerate(self._positions):
if (isinstance(e, int) and x == e) or (isinstance(e, tuple) and x in e):
return i
return _apply_recursively_over_nested_lists(transform, indices)
@classmethod
def _push_indices_down(cls, diagonal_indices, indices, rank):
positions, shape = cls._get_positions_shape(range(rank), diagonal_indices)
transform = lambda x: positions[x] if x < len(positions) else None
return _apply_recursively_over_nested_lists(transform, indices)
@classmethod
def _push_indices_up(cls, diagonal_indices, indices, rank):
positions, shape = cls._get_positions_shape(range(rank), diagonal_indices)
def transform(x):
for i, e in enumerate(positions):
if (isinstance(e, int) and x == e) or (isinstance(e, (tuple, Tuple)) and (x in e)):
return i
return _apply_recursively_over_nested_lists(transform, indices)
@classmethod
def _get_positions_shape(cls, shape, diagonal_indices):
data1 = tuple((i, shp) for i, shp in enumerate(shape) if not any(i in j for j in diagonal_indices))
pos1, shp1 = zip(*data1) if data1 else ((), ())
data2 = tuple((i, shape[i[0]]) for i in diagonal_indices)
pos2, shp2 = zip(*data2) if data2 else ((), ())
positions = pos1 + pos2
shape = shp1 + shp2
return positions, shape
def as_explicit(self):
return tensordiagonal(self.expr.as_explicit(), *self.diagonal_indices)
class ArrayElementwiseApplyFunc(_CodegenArrayAbstract):
def __new__(cls, function, element):
if not isinstance(function, Lambda):
d = Dummy('d')
function = Lambda(d, function(d))
obj = _CodegenArrayAbstract.__new__(cls, function, element)
obj._subranks = _get_subranks(element)
return obj
@property
def function(self):
return self.args[0]
@property
def expr(self):
return self.args[1]
@property
def shape(self):
return self.expr.shape
def _get_function_fdiff(self):
d = Dummy("d")
function = self.function(d)
fdiff = function.diff(d)
if isinstance(fdiff, Function):
fdiff = type(fdiff)
else:
fdiff = Lambda(d, fdiff)
return fdiff
class ArrayContraction(_CodegenArrayAbstract):
r"""
This class is meant to represent contractions of arrays in a form easily
processable by the code printers.
"""
def __new__(cls, expr, *contraction_indices, **kwargs):
contraction_indices = _sort_contraction_indices(contraction_indices)
expr = _sympify(expr)
normalize = kwargs.get("normalize", True)
obj = Basic.__new__(cls, expr, *contraction_indices)
obj._subranks = _get_subranks(expr)
obj._mapping = _get_mapping_from_subranks(obj._subranks)
free_indices_to_position = {i: i for i in range(sum(obj._subranks)) if all(i not in cind for cind in contraction_indices)}
obj._free_indices_to_position = free_indices_to_position
shape = get_shape(expr)
cls._validate(expr, *contraction_indices)
if shape:
shape = tuple(shp for i, shp in enumerate(shape) if not any(i in j for j in contraction_indices))
obj._shape = shape
if normalize:
return obj._normalize()
return obj
def _normalize(self):
expr = self.expr
contraction_indices = self.contraction_indices
if len(contraction_indices) == 0:
return expr
if isinstance(expr, ArrayContraction):
return self._ArrayContraction_denest_ArrayContraction(expr, *contraction_indices)
if isinstance(expr, (ZeroArray, ZeroMatrix)):
return self._ArrayContraction_denest_ZeroArray(expr, *contraction_indices)
if isinstance(expr, PermuteDims):
return self._ArrayContraction_denest_PermuteDims(expr, *contraction_indices)
if isinstance(expr, ArrayTensorProduct):
expr, contraction_indices = self._sort_fully_contracted_args(expr, contraction_indices)
expr, contraction_indices = self._lower_contraction_to_addends(expr, contraction_indices)
if len(contraction_indices) == 0:
return expr
if isinstance(expr, ArrayDiagonal):
return self._ArrayContraction_denest_ArrayDiagonal(expr, *contraction_indices)
if isinstance(expr, ArrayAdd):
return self._ArrayContraction_denest_ArrayAdd(expr, *contraction_indices)
# Check single index contractions on 1-dimensional axes:
contraction_indices = [i for i in contraction_indices if len(i) > 1 or get_shape(expr)[i[0]] != 1]
if len(contraction_indices) == 0:
return expr
return self.func(expr, *contraction_indices, normalize=False)
def __mul__(self, other):
if other == 1:
return self
else:
raise NotImplementedError("Product of N-dim arrays is not uniquely defined. Use another method.")
def __rmul__(self, other):
if other == 1:
return self
else:
raise NotImplementedError("Product of N-dim arrays is not uniquely defined. Use another method.")
@staticmethod
def _validate(expr, *contraction_indices):
shape = get_shape(expr)
if shape is None:
return
# Check that no contraction happens when the shape is mismatched:
for i in contraction_indices:
if len({shape[j] for j in i if shape[j] != -1}) != 1:
raise ValueError("contracting indices of different dimensions")
@classmethod
def _push_indices_down(cls, contraction_indices, indices):
flattened_contraction_indices = [j for i in contraction_indices for j in i]
flattened_contraction_indices.sort()
transform = _build_push_indices_down_func_transformation(flattened_contraction_indices)
return _apply_recursively_over_nested_lists(transform, indices)
@classmethod
def _push_indices_up(cls, contraction_indices, indices):
flattened_contraction_indices = [j for i in contraction_indices for j in i]
flattened_contraction_indices.sort()
transform = _build_push_indices_up_func_transformation(flattened_contraction_indices)
return _apply_recursively_over_nested_lists(transform, indices)
@classmethod
def _lower_contraction_to_addends(cls, expr, contraction_indices):
if isinstance(expr, ArrayAdd):
raise NotImplementedError()
if not isinstance(expr, ArrayTensorProduct):
return expr, contraction_indices
subranks = expr.subranks
cumranks = list(accumulate([0] + subranks))
contraction_indices_remaining = []
contraction_indices_args = [[] for i in expr.args]
backshift = set([])
for i, contraction_group in enumerate(contraction_indices):
for j in range(len(expr.args)):
if not isinstance(expr.args[j], ArrayAdd):
continue
if all(cumranks[j] <= k < cumranks[j+1] for k in contraction_group):
contraction_indices_args[j].append([k - cumranks[j] for k in contraction_group])
backshift.update(contraction_group)
break
else:
contraction_indices_remaining.append(contraction_group)
if len(contraction_indices_remaining) == len(contraction_indices):
return expr, contraction_indices
total_rank = get_rank(expr)
shifts = list(accumulate([1 if i in backshift else 0 for i in range(total_rank)]))
contraction_indices_remaining = [Tuple.fromiter(j - shifts[j] for j in i) for i in contraction_indices_remaining]
ret = ArrayTensorProduct(*[
ArrayContraction(arg, *contr) for arg, contr in zip(expr.args, contraction_indices_args)
])
return ret, contraction_indices_remaining
def split_multiple_contractions(self):
"""
Recognize multiple contractions and attempt at rewriting them as paired-contractions.
This allows some contractions involving more than two indices to be
rewritten as multiple contractions involving two indices, thus allowing
the expression to be rewritten as a matrix multiplication line.
Examples:
* `A_ij b_j0 C_jk` ===> `A*DiagMatrix(b)*C`
Care for:
- matrix being diagonalized (i.e. `A_ii`)
- vectors being diagonalized (i.e. `a_i0`)
Multiple contractions can be split into matrix multiplications if
not more than two arguments are non-diagonals or non-vectors.
Vectors get diagonalized while diagonal matrices remain diagonal.
The non-diagonal matrices can be at the beginning or at the end
of the final matrix multiplication line.
"""
editor = _EditArrayContraction(self)
contraction_indices = self.contraction_indices
onearray_insert = []
for indl, links in enumerate(contraction_indices):
if len(links) <= 2:
continue
# Check multiple contractions:
#
# Examples:
#
# * `A_ij b_j0 C_jk` ===> `A*DiagMatrix(b)*C \otimes OneArray(1)` with permutation (1 2)
#
# Care for:
# - matrix being diagonalized (i.e. `A_ii`)
# - vectors being diagonalized (i.e. `a_i0`)
# Multiple contractions can be split into matrix multiplications if
# not more than three arguments are non-diagonals or non-vectors.
#
# Vectors get diagonalized while diagonal matrices remain diagonal.
# The non-diagonal matrices can be at the beginning or at the end
# of the final matrix multiplication line.
positions = editor.get_mapping_for_index(indl)
# Also consider the case of diagonal matrices being contracted:
current_dimension = self.expr.shape[links[0]]
not_vectors: tTuple[_ArgE, int] = []
vectors: tTuple[_ArgE, int] = []
for arg_ind, rel_ind in positions:
arg = editor.args_with_ind[arg_ind]
mat = arg.element
abs_arg_start, abs_arg_end = editor.get_absolute_range(arg)
other_arg_pos = 1-rel_ind
other_arg_abs = abs_arg_start + other_arg_pos
if ((1 not in mat.shape) or
((current_dimension == 1) is True and mat.shape != (1, 1)) or
any(other_arg_abs in l for li, l in enumerate(contraction_indices) if li != indl)
):
not_vectors.append((arg, rel_ind))
else:
vectors.append((arg, rel_ind))
if len(not_vectors) > 2:
# If more than two arguments in the multiple contraction are
# non-vectors and non-diagonal matrices, we cannot find a way
# to split this contraction into a matrix multiplication line:
continue
# Three cases to handle:
# - zero non-vectors
# - one non-vector
# - two non-vectors
for v, rel_ind in vectors:
v.element = diagonalize_vector(v.element)
vectors_to_loop = not_vectors[:1] + vectors + not_vectors[1:]
first_not_vector, rel_ind = vectors_to_loop[0]
new_index = first_not_vector.indices[rel_ind]
for v, rel_ind in vectors_to_loop[1:-1]:
v.indices[rel_ind] = new_index
new_index = editor.get_new_contraction_index()
assert v.indices.index(None) == 1 - rel_ind
v.indices[v.indices.index(None)] = new_index
onearray_insert.append(v)
last_vec, rel_ind = vectors_to_loop[-1]
last_vec.indices[rel_ind] = new_index
for v in onearray_insert:
editor.insert_after(v, _ArgE(OneArray(1), [None]))
return editor.to_array_contraction()
def flatten_contraction_of_diagonal(self):
if not isinstance(self.expr, ArrayDiagonal):
return self
contraction_down = self.expr._push_indices_down(self.expr.diagonal_indices, self.contraction_indices)
new_contraction_indices = []
diagonal_indices = self.expr.diagonal_indices[:]
for i in contraction_down:
contraction_group = list(i)
for j in i:
diagonal_with = [k for k in diagonal_indices if j in k]
contraction_group.extend([l for k in diagonal_with for l in k])
diagonal_indices = [k for k in diagonal_indices if k not in diagonal_with]
new_contraction_indices.append(sorted(set(contraction_group)))
new_contraction_indices = ArrayDiagonal._push_indices_up(diagonal_indices, new_contraction_indices)
return ArrayContraction(
ArrayDiagonal(
self.expr.expr,
*diagonal_indices
),
*new_contraction_indices
)
@staticmethod
def _get_free_indices_to_position_map(free_indices, contraction_indices):
free_indices_to_position = {}
flattened_contraction_indices = [j for i in contraction_indices for j in i]
counter = 0
for ind in free_indices:
while counter in flattened_contraction_indices:
counter += 1
free_indices_to_position[ind] = counter
counter += 1
return free_indices_to_position
@staticmethod
def _get_index_shifts(expr):
"""
Get the mapping of indices at the positions before the contraction
occurs.
Examples
========
>>> from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct
>>> from sympy.tensor.array.expressions.array_expressions import ArrayContraction
>>> from sympy import MatrixSymbol
>>> M = MatrixSymbol("M", 3, 3)
>>> N = MatrixSymbol("N", 3, 3)
>>> cg = ArrayContraction(ArrayTensorProduct(M, N), [1, 2])
>>> cg._get_index_shifts(cg)
[0, 2]
Indeed, ``cg`` after the contraction has two dimensions, 0 and 1. They
need to be shifted by 0 and 2 to get the corresponding positions before
the contraction (that is, 0 and 3).
"""
inner_contraction_indices = expr.contraction_indices
all_inner = [j for i in inner_contraction_indices for j in i]
all_inner.sort()
# TODO: add API for total rank and cumulative rank:
total_rank = _get_subrank(expr)
inner_rank = len(all_inner)
outer_rank = total_rank - inner_rank
shifts = [0 for i in range(outer_rank)]
counter = 0
pointer = 0
for i in range(outer_rank):
while pointer < inner_rank and counter >= all_inner[pointer]:
counter += 1
pointer += 1
shifts[i] += pointer
counter += 1
return shifts
@staticmethod
def _convert_outer_indices_to_inner_indices(expr, *outer_contraction_indices):
shifts = ArrayContraction._get_index_shifts(expr)
outer_contraction_indices = tuple(tuple(shifts[j] + j for j in i) for i in outer_contraction_indices)
return outer_contraction_indices
@staticmethod
def _flatten(expr, *outer_contraction_indices):
inner_contraction_indices = expr.contraction_indices
outer_contraction_indices = ArrayContraction._convert_outer_indices_to_inner_indices(expr, *outer_contraction_indices)
contraction_indices = inner_contraction_indices + outer_contraction_indices
return ArrayContraction(expr.expr, *contraction_indices)
@classmethod
def _ArrayContraction_denest_ArrayContraction(cls, expr, *contraction_indices):
return cls._flatten(expr, *contraction_indices)
@classmethod
def _ArrayContraction_denest_ZeroArray(cls, expr, *contraction_indices):
contraction_indices_flat = [j for i in contraction_indices for j in i]
shape = [e for i, e in enumerate(expr.shape) if i not in contraction_indices_flat]
return ZeroArray(*shape)
@classmethod
def _ArrayContraction_denest_ArrayAdd(cls, expr, *contraction_indices):
return ArrayAdd(*[ArrayContraction(i, *contraction_indices) for i in expr.args])
@classmethod
def _ArrayContraction_denest_PermuteDims(cls, expr, *contraction_indices):
permutation = expr.permutation
plist = permutation.array_form
new_contraction_indices = [tuple(permutation(j) for j in i) for i in contraction_indices]
new_plist = [i for i in plist if not any(i in j for j in new_contraction_indices)]
new_plist = cls._push_indices_up(new_contraction_indices, new_plist)
return PermuteDims(
ArrayContraction(expr.expr, *new_contraction_indices),
Permutation(new_plist)
)
@classmethod
def _ArrayContraction_denest_ArrayDiagonal(cls, expr: 'ArrayDiagonal', *contraction_indices):
diagonal_indices = list(expr.diagonal_indices)
down_contraction_indices = expr._push_indices_down(expr.diagonal_indices, contraction_indices, get_rank(expr.expr))
# Flatten diagonally contracted indices:
down_contraction_indices = [[k for j in i for k in (j if isinstance(j, (tuple, Tuple)) else [j])] for i in down_contraction_indices]
new_contraction_indices = []
for contr_indgrp in down_contraction_indices:
ind = contr_indgrp[:]
for j, diag_indgrp in enumerate(diagonal_indices):
if diag_indgrp is None:
continue
if any(i in diag_indgrp for i in contr_indgrp):
ind.extend(diag_indgrp)
diagonal_indices[j] = None
new_contraction_indices.append(sorted(set(ind)))
new_diagonal_indices_down = [i for i in diagonal_indices if i is not None]
new_diagonal_indices = ArrayContraction._push_indices_up(new_contraction_indices, new_diagonal_indices_down)
return ArrayDiagonal(
ArrayContraction(expr.expr, *new_contraction_indices),
*new_diagonal_indices
)
@classmethod
def _sort_fully_contracted_args(cls, expr, contraction_indices):
if expr.shape is None:
return expr, contraction_indices
cumul = list(accumulate([0] + expr.subranks))
index_blocks = [list(range(cumul[i], cumul[i+1])) for i in range(len(expr.args))]
contraction_indices_flat = {j for i in contraction_indices for j in i}
fully_contracted = [all(j in contraction_indices_flat for j in range(cumul[i], cumul[i+1])) for i, arg in enumerate(expr.args)]
new_pos = sorted(range(len(expr.args)), key=lambda x: (0, default_sort_key(expr.args[x])) if fully_contracted[x] else (1,))
new_args = [expr.args[i] for i in new_pos]
new_index_blocks_flat = [j for i in new_pos for j in index_blocks[i]]
index_permutation_array_form = _af_invert(new_index_blocks_flat)
new_contraction_indices = [tuple(index_permutation_array_form[j] for j in i) for i in contraction_indices]
new_contraction_indices = _sort_contraction_indices(new_contraction_indices)
return ArrayTensorProduct(*new_args), new_contraction_indices
def _get_contraction_tuples(self):
r"""
Return tuples containing the argument index and position within the
argument of the index position.
Examples
========
>>> from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct
>>> from sympy import MatrixSymbol
>>> from sympy.abc import N
>>> from sympy.tensor.array.expressions.array_expressions import ArrayContraction
>>> A = MatrixSymbol("A", N, N)
>>> B = MatrixSymbol("B", N, N)
>>> cg = ArrayContraction(ArrayTensorProduct(A, B), (1, 2))
>>> cg._get_contraction_tuples()
[[(0, 1), (1, 0)]]
Notes
=====
Here the contraction pair `(1, 2)` meaning that the 2nd and 3rd indices
of the tensor product `A\otimes B` are contracted, has been transformed
into `(0, 1)` and `(1, 0)`, identifying the same indices in a different
notation. `(0, 1)` is the second index (1) of the first argument (i.e.
0 or `A`). `(1, 0)` is the first index (i.e. 0) of the second
argument (i.e. 1 or `B`).
"""
mapping = self._mapping
return [[mapping[j] for j in i] for i in self.contraction_indices]
@staticmethod
def _contraction_tuples_to_contraction_indices(expr, contraction_tuples):
# TODO: check that `expr` has `.subranks`:
ranks = expr.subranks
cumulative_ranks = [0] + list(accumulate(ranks))
return [tuple(cumulative_ranks[j]+k for j, k in i) for i in contraction_tuples]
@property
def free_indices(self):
return self._free_indices[:]
@property
def free_indices_to_position(self):
return dict(self._free_indices_to_position)
@property
def expr(self):
return self.args[0]
@property
def contraction_indices(self):
return self.args[1:]
def _contraction_indices_to_components(self):
expr = self.expr
if not isinstance(expr, ArrayTensorProduct):
raise NotImplementedError("only for contractions of tensor products")
ranks = expr.subranks
mapping = {}
counter = 0
for i, rank in enumerate(ranks):
for j in range(rank):
mapping[counter] = (i, j)
counter += 1
return mapping
def sort_args_by_name(self):
"""
Sort arguments in the tensor product so that their order is lexicographical.
Examples
========
>>> from sympy.tensor.array.expressions.conv_matrix_to_array import convert_matrix_to_array
>>> from sympy import MatrixSymbol
>>> from sympy.abc import N
>>> A = MatrixSymbol("A", N, N)
>>> B = MatrixSymbol("B", N, N)
>>> C = MatrixSymbol("C", N, N)
>>> D = MatrixSymbol("D", N, N)
>>> cg = convert_matrix_to_array(C*D*A*B)
>>> cg
ArrayContraction(ArrayTensorProduct(A, D, C, B), (0, 3), (1, 6), (2, 5))
>>> cg.sort_args_by_name()
ArrayContraction(ArrayTensorProduct(A, D, B, C), (0, 3), (1, 4), (2, 7))
"""
expr = self.expr
if not isinstance(expr, ArrayTensorProduct):
return self
args = expr.args
sorted_data = sorted(enumerate(args), key=lambda x: default_sort_key(x[1]))
pos_sorted, args_sorted = zip(*sorted_data)
reordering_map = {i: pos_sorted.index(i) for i, arg in enumerate(args)}
contraction_tuples = self._get_contraction_tuples()
contraction_tuples = [[(reordering_map[j], k) for j, k in i] for i in contraction_tuples]
c_tp = ArrayTensorProduct(*args_sorted)
new_contr_indices = self._contraction_tuples_to_contraction_indices(
c_tp,
contraction_tuples
)
return ArrayContraction(c_tp, *new_contr_indices)
def _get_contraction_links(self):
r"""
Returns a dictionary of links between arguments in the tensor product
being contracted.
See the example for an explanation of the values.
Examples
========
>>> from sympy import MatrixSymbol
>>> from sympy.abc import N
>>> from sympy.tensor.array.expressions.conv_matrix_to_array import convert_matrix_to_array
>>> A = MatrixSymbol("A", N, N)
>>> B = MatrixSymbol("B", N, N)
>>> C = MatrixSymbol("C", N, N)
>>> D = MatrixSymbol("D", N, N)
Matrix multiplications are pairwise contractions between neighboring
matrices:
`A_{ij} B_{jk} C_{kl} D_{lm}`
>>> cg = convert_matrix_to_array(A*B*C*D)
>>> cg
ArrayContraction(ArrayTensorProduct(B, C, A, D), (0, 5), (1, 2), (3, 6))
>>> cg._get_contraction_links()
{0: {0: (2, 1), 1: (1, 0)}, 1: {0: (0, 1), 1: (3, 0)}, 2: {1: (0, 0)}, 3: {0: (1, 1)}}
This dictionary is interpreted as follows: argument in position 0 (i.e.
matrix `A`) has its second index (i.e. 1) contracted to `(1, 0)`, that
is argument in position 1 (matrix `B`) on the first index slot of `B`,
this is the contraction provided by the index `j` from `A`.
The argument in position 1 (that is, matrix `B`) has two contractions,
the ones provided by the indices `j` and `k`, respectively the first
and second indices (0 and 1 in the sub-dict). The link `(0, 1)` and
`(2, 0)` respectively. `(0, 1)` is the index slot 1 (the 2nd) of
argument in position 0 (that is, `A_{\ldot j}`), and so on.
"""
args, dlinks = _get_contraction_links([self], self.subranks, *self.contraction_indices)
return dlinks
def as_explicit(self):
return tensorcontraction(self.expr.as_explicit(), *self.contraction_indices)
class _ArgE:
"""
The ``_ArgE`` object contains references to the array expression
(``.element``) and a list containing the information about index
contractions (``.indices``).
Index contractions are numbered and contracted indices show the number of
the contraction. Uncontracted indices have ``None`` value.
For example:
``_ArgE(M, [None, 3])``
This object means that expression ``M`` is part of an array contraction
and has two indices, the first is not contracted (value ``None``),
the second index is contracted to the 4th (i.e. number ``3``) group of the
array contraction object.
"""
indices: List[Optional[int]]
def __init__(self, element, indices: Optional[List[Optional[int]]] = None):
self.element = element
if indices is None:
self.indices = [None for i in range(get_rank(element))]
else:
self.indices = indices
def __str__(self):
return "_ArgE(%s, %s)" % (self.element, self.indices)
__repr__ = __str__
class _IndPos:
"""
Index position, requiring two integers in the constructor:
- arg: the position of the argument in the tensor product,
- rel: the relative position of the index inside the argument.
"""
def __init__(self, arg: int, rel: int):
self.arg = arg
self.rel = rel
def __str__(self):
return "_IndPos(%i, %i)" % (self.arg, self.rel)
__repr__ = __str__
def __iter__(self):
yield from [self.arg, self.rel]
class _EditArrayContraction:
"""
Utility class to help manipulate array contraction objects.
This class takes as input an ``ArrayContraction`` object and turns it into
an editable object.
The field ``args_with_ind`` of this class is a list of ``_ArgE`` objects
which can be used to easily edit the contraction structure of the
expression.
Once editing is finished, the ``ArrayContraction`` object may be recreated
by calling the ``.to_array_contraction()`` method.
"""
def __init__(self, base_array: typing.Union[ArrayContraction, ArrayDiagonal, ArrayTensorProduct]):
expr: Basic
diagonalized: tTuple[tTuple[int, ...], ...]
contraction_indices: List[tTuple[int]]
if isinstance(base_array, ArrayContraction):
mapping = _get_mapping_from_subranks(base_array.subranks)
expr = base_array.expr
contraction_indices = base_array.contraction_indices
diagonalized = ()
elif isinstance(base_array, ArrayDiagonal):
if isinstance(base_array.expr, ArrayContraction):
mapping = _get_mapping_from_subranks(base_array.expr.subranks)
expr = base_array.expr.expr
diagonalized = ArrayContraction._push_indices_down(base_array.expr.contraction_indices, base_array.diagonal_indices)
contraction_indices = base_array.expr.contraction_indices
elif isinstance(base_array.expr, ArrayTensorProduct):
mapping = {}
expr = base_array.expr
diagonalized = base_array.diagonal_indices
contraction_indices = []
else:
mapping = {}
expr = base_array.expr
diagonalized = base_array.diagonal_indices
contraction_indices = []
elif isinstance(base_array, ArrayTensorProduct):
expr = base_array
contraction_indices = []
diagonalized = ()
else:
raise NotImplementedError()
if isinstance(expr, ArrayTensorProduct):
args = list(expr.args)
else:
args = [expr]
args_with_ind: List[_ArgE] = [_ArgE(arg) for arg in args]
for i, contraction_tuple in enumerate(contraction_indices):
for j in contraction_tuple:
arg_pos, rel_pos = mapping[j]
args_with_ind[arg_pos].indices[rel_pos] = i
self.args_with_ind: List[_ArgE] = args_with_ind
self.number_of_contraction_indices: int = len(contraction_indices)
self._track_permutation: Optional[List[List[int]]] = None
mapping = _get_mapping_from_subranks(base_array.subranks)
# Trick: add diagonalized indices as negative indices into the editor object:
for i, e in enumerate(diagonalized):
for j in e:
arg_pos, rel_pos = mapping[j]
self.args_with_ind[arg_pos].indices[rel_pos] = -1 - i
def insert_after(self, arg: _ArgE, new_arg: _ArgE):
pos = self.args_with_ind.index(arg)
self.args_with_ind.insert(pos + 1, new_arg)
def get_new_contraction_index(self):
self.number_of_contraction_indices += 1
return self.number_of_contraction_indices - 1
def refresh_indices(self):
updates: tDict[int, int] = {}
for arg_with_ind in self.args_with_ind:
updates.update({i: -1 for i in arg_with_ind.indices if i is not None})
for i, e in enumerate(sorted(updates)):
updates[e] = i
self.number_of_contraction_indices: int = len(updates)
for arg_with_ind in self.args_with_ind:
arg_with_ind.indices = [updates.get(i, None) for i in arg_with_ind.indices]
def merge_scalars(self):
scalars = []
for arg_with_ind in self.args_with_ind:
if len(arg_with_ind.indices) == 0:
scalars.append(arg_with_ind)
for i in scalars:
self.args_with_ind.remove(i)
scalar = Mul.fromiter([i.element for i in scalars])
if len(self.args_with_ind) == 0:
self.args_with_ind.append(_ArgE(scalar))
else:
from sympy.tensor.array.expressions.conv_array_to_matrix import _a2m_tensor_product
self.args_with_ind[0].element = _a2m_tensor_product(scalar, self.args_with_ind[0].element)
def to_array_contraction(self):
# Count the ranks of the arguments:
counter = 0
# Create a collector for the new diagonal indices:
diag_indices = defaultdict(list)
count_index_freq = Counter()
for arg_with_ind in self.args_with_ind:
count_index_freq.update(Counter(arg_with_ind.indices))
free_index_count = count_index_freq[None]
# Construct the inverse permutation:
inv_perm1 = []
inv_perm2 = []
# Keep track of which diagonal indices have already been processed:
done = set([])
# Counter for the diagonal indices:
counter4 = 0
for arg_with_ind in self.args_with_ind:
# If some diagonalization axes have been removed, they should be
# permuted in order to keep the permutation.
# Add permutation here
counter2 = 0 # counter for the indices
for i in arg_with_ind.indices:
if i is None:
inv_perm1.append(counter4)
counter2 += 1
counter4 += 1
continue
if i >= 0:
continue
# Reconstruct the diagonal indices:
diag_indices[-1 - i].append(counter + counter2)
if count_index_freq[i] == 1 and i not in done:
inv_perm1.append(free_index_count - 1 - i)
done.add(i)
elif i not in done:
inv_perm2.append(free_index_count - 1 - i)
done.add(i)
counter2 += 1
# Remove negative indices to restore a proper editor object:
arg_with_ind.indices = [i if i is not None and i >= 0 else None for i in arg_with_ind.indices]
counter += len([i for i in arg_with_ind.indices if i is None or i < 0])
inverse_permutation = inv_perm1 + inv_perm2
permutation = _af_invert(inverse_permutation)
# Get the diagonal indices after the detection of HadamardProduct in the expression:
diag_indices_filtered = [tuple(v) for v in diag_indices.values() if len(v) > 1]
self.merge_scalars()
self.refresh_indices()
args = [arg.element for arg in self.args_with_ind]
contraction_indices = self.get_contraction_indices()
expr = ArrayContraction(ArrayTensorProduct(*args), *contraction_indices)
expr2 = ArrayDiagonal(expr, *diag_indices_filtered)
if self._track_permutation is not None:
permutation2 = _af_invert([j for i in self._track_permutation for j in i])
expr2 = PermuteDims(expr2, permutation2)
expr3 = PermuteDims(expr2, permutation)
return expr3
def get_contraction_indices(self) -> List[List[int]]:
contraction_indices: List[List[int]] = [[] for i in range(self.number_of_contraction_indices)]
current_position: int = 0
for i, arg_with_ind in enumerate(self.args_with_ind):
for j in arg_with_ind.indices:
if j is not None:
contraction_indices[j].append(current_position)
current_position += 1
return contraction_indices
def get_mapping_for_index(self, ind) -> List[_IndPos]:
if ind >= self.number_of_contraction_indices:
raise ValueError("index value exceeding the index range")
positions: List[_IndPos] = []
for i, arg_with_ind in enumerate(self.args_with_ind):
for j, arg_ind in enumerate(arg_with_ind.indices):
if ind == arg_ind:
positions.append(_IndPos(i, j))
return positions
def get_contraction_indices_to_ind_rel_pos(self) -> List[List[_IndPos]]:
contraction_indices: List[List[_IndPos]] = [[] for i in range(self.number_of_contraction_indices)]
for i, arg_with_ind in enumerate(self.args_with_ind):
for j, ind in enumerate(arg_with_ind.indices):
if ind is not None:
contraction_indices[ind].append(_IndPos(i, j))
return contraction_indices
def count_args_with_index(self, index: int) -> int:
"""
Count the number of arguments that have the given index.
"""
counter: int = 0
for arg_with_ind in self.args_with_ind:
if index in arg_with_ind.indices:
counter += 1
return counter
def get_args_with_index(self, index: int) -> List[_ArgE]:
"""
Get a list of arguments having the given index.
"""
ret: List[_ArgE] = [i for i in self.args_with_ind if index in i.indices]
return ret
@property
def number_of_diagonal_indices(self):
data = set([])
for arg in self.args_with_ind:
data.update({i for i in arg.indices if i is not None and i < 0})
return len(data)
def track_permutation_start(self):
permutation = []
perm_diag = []
counter: int = 0
counter2: int = -1
for arg_with_ind in self.args_with_ind:
perm = []
for i in arg_with_ind.indices:
if i is not None:
if i < 0:
perm_diag.append(counter2)
counter2 -= 1
continue
perm.append(counter)
counter += 1
permutation.append(perm)
max_ind = max([max(i) if i else -1 for i in permutation]) if permutation else -1
perm_diag = [max_ind - i for i in perm_diag]
self._track_permutation = permutation + [perm_diag]
def track_permutation_merge(self, destination: _ArgE, from_element: _ArgE):
index_destination = self.args_with_ind.index(destination)
index_element = self.args_with_ind.index(from_element)
self._track_permutation[index_destination].extend(self._track_permutation[index_element]) # type: ignore
self._track_permutation.pop(index_element) # type: ignore
def get_absolute_free_range(self, arg: _ArgE) -> typing.Tuple[int, int]:
"""
Return the range of the free indices of the arg as absolute positions
among all free indices.
"""
counter = 0
for arg_with_ind in self.args_with_ind:
number_free_indices = len([i for i in arg_with_ind.indices if i is None])
if arg_with_ind == arg:
return counter, counter + number_free_indices
counter += number_free_indices
raise IndexError("argument not found")
def get_absolute_range(self, arg: _ArgE) -> typing.Tuple[int, int]:
"""
Return the absolute range of indices for arg, disregarding dummy
indices.
"""
counter = 0
for arg_with_ind in self.args_with_ind:
number_indices = len(arg_with_ind.indices)
if arg_with_ind == arg:
return counter, counter + number_indices
counter += number_indices
raise IndexError("argument not found")
def get_rank(expr):
if isinstance(expr, (MatrixExpr, MatrixElement)):
return 2
if isinstance(expr, _CodegenArrayAbstract):
return len(expr.shape)
if isinstance(expr, NDimArray):
return expr.rank()
if isinstance(expr, Indexed):
return expr.rank
if isinstance(expr, IndexedBase):
shape = expr.shape
if shape is None:
return -1
else:
return len(shape)
if hasattr(expr, "shape"):
return len(expr.shape)
return 0
def _get_subrank(expr):
if isinstance(expr, _CodegenArrayAbstract):
return expr.subrank()
return get_rank(expr)
def _get_subranks(expr):
if isinstance(expr, _CodegenArrayAbstract):
return expr.subranks
else:
return [get_rank(expr)]
def get_shape(expr):
if hasattr(expr, "shape"):
return expr.shape
return ()
def nest_permutation(expr):
if isinstance(expr, PermuteDims):
return expr.nest_permutation()
else:
return expr
|
eb06973a25792f45b67210913ba1119d41240865a012f448a087f4b92b0ccf2d | import operator
from functools import reduce, singledispatch
from sympy.core.expr import Expr
from sympy.core.singleton import S
from sympy.matrices.expressions.hadamard import HadamardProduct
from sympy.matrices.expressions.inverse import Inverse
from sympy.matrices.expressions.matexpr import (MatrixExpr, MatrixSymbol)
from sympy.matrices.expressions.special import Identity
from sympy.matrices.expressions.transpose import Transpose
from sympy.combinatorics.permutations import _af_invert
from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction
from sympy.tensor.array.expressions.array_expressions import ZeroArray, ArraySymbol, ArrayTensorProduct, \
ArrayAdd, PermuteDims, ArrayDiagonal, ArrayElementwiseApplyFunc, get_rank, \
get_shape, ArrayContraction
from sympy.tensor.array.expressions.conv_matrix_to_array import convert_matrix_to_array
@singledispatch
def array_derive(expr, x):
raise NotImplementedError(f"not implemented for type {type(expr)}")
@array_derive.register(Expr) # type: ignore
def _(expr: Expr, x: Expr):
return ZeroArray(*x.shape)
@array_derive.register(ArrayTensorProduct) # type: ignore
def _(expr: ArrayTensorProduct, x: Expr):
args = expr.args
addend_list = []
for i, arg in enumerate(expr.args):
darg = array_derive(arg, x)
if darg == 0:
continue
args_prev = args[:i]
args_succ = args[i+1:]
shape_prev = reduce(operator.add, map(get_shape, args_prev), ())
shape_succ = reduce(operator.add, map(get_shape, args_succ), ())
addend = ArrayTensorProduct(*args_prev, darg, *args_succ)
tot1 = len(get_shape(x))
tot2 = tot1 + len(shape_prev)
tot3 = tot2 + len(get_shape(arg))
tot4 = tot3 + len(shape_succ)
perm = [i for i in range(tot1, tot2)] + \
[i for i in range(tot1)] + [i for i in range(tot2, tot3)] + \
[i for i in range(tot3, tot4)]
addend = PermuteDims(addend, _af_invert(perm))
addend_list.append(addend)
if len(addend_list) == 1:
return addend_list[0]
elif len(addend_list) == 0:
return S.Zero
else:
return ArrayAdd(*addend_list)
@array_derive.register(ArraySymbol) # type: ignore
def _(expr: ArraySymbol, x: Expr):
if expr == x:
return PermuteDims(
ArrayTensorProduct.fromiter(Identity(i) for i in expr.shape),
[2*i for i in range(len(expr.shape))] + [2*i+1 for i in range(len(expr.shape))]
)
return ZeroArray(*(x.shape + expr.shape))
@array_derive.register(MatrixSymbol) # type: ignore
def _(expr: MatrixSymbol, x: Expr):
m, n = expr.shape
if expr == x:
return PermuteDims(
ArrayTensorProduct(Identity(m), Identity(n)),
[0, 2, 1, 3]
)
return ZeroArray(*(x.shape + expr.shape))
@array_derive.register(Identity) # type: ignore
def _(expr: Identity, x: Expr):
return ZeroArray(*(x.shape + expr.shape))
@array_derive.register(Transpose) # type: ignore
def _(expr: Transpose, x: Expr):
# D(A.T, A) ==> (m,n,i,j) ==> D(A_ji, A_mn) = d_mj d_ni
# D(B.T, A) ==> (m,n,i,j) ==> D(B_ji, A_mn)
fd = array_derive(expr.arg, x)
return PermuteDims(fd, [0, 1, 3, 2])
@array_derive.register(Inverse) # type: ignore
def _(expr: Inverse, x: Expr):
mat = expr.I
dexpr = array_derive(mat, x)
tp = ArrayTensorProduct(-expr, dexpr, expr)
mp = ArrayContraction(tp, (1, 4), (5, 6))
pp = PermuteDims(mp, [1, 2, 0, 3])
return pp
@array_derive.register(ElementwiseApplyFunction) # type: ignore
def _(expr: ElementwiseApplyFunction, x: Expr):
assert get_rank(expr) == 2
assert get_rank(x) == 2
fdiff = expr._get_function_fdiff()
dexpr = array_derive(expr.expr, x)
tp = ArrayTensorProduct(
ElementwiseApplyFunction(fdiff, expr.expr),
dexpr
)
td = ArrayDiagonal(
tp, (0, 4), (1, 5)
)
return td
@array_derive.register(ArrayElementwiseApplyFunc) # type: ignore
def _(expr: ArrayElementwiseApplyFunc, x: Expr):
fdiff = expr._get_function_fdiff()
subexpr = expr.expr
dsubexpr = array_derive(subexpr, x)
tp = ArrayTensorProduct(
dsubexpr,
ArrayElementwiseApplyFunc(fdiff, subexpr)
)
b = get_rank(x)
c = get_rank(expr)
diag_indices = [(b + i, b + c + i) for i in range(c)]
return ArrayDiagonal(tp, *diag_indices)
@array_derive.register(MatrixExpr) # type: ignore
def _(expr: MatrixExpr, x: Expr):
cg = convert_matrix_to_array(expr)
return array_derive(cg, x)
@array_derive.register(HadamardProduct) # type: ignore
def _(expr: HadamardProduct, x: Expr):
raise NotImplementedError()
@array_derive.register(ArrayContraction) # type: ignore
def _(expr: ArrayContraction, x: Expr):
fd = array_derive(expr.expr, x)
rank_x = len(get_shape(x))
contraction_indices = expr.contraction_indices
new_contraction_indices = [tuple(j + rank_x for j in i) for i in contraction_indices]
return ArrayContraction(fd, *new_contraction_indices)
@array_derive.register(ArrayDiagonal) # type: ignore
def _(expr: ArrayDiagonal, x: Expr):
dsubexpr = array_derive(expr.expr, x)
rank_x = len(get_shape(x))
diag_indices = [[j + rank_x for j in i] for i in expr.diagonal_indices]
return ArrayDiagonal(dsubexpr, *diag_indices)
@array_derive.register(ArrayAdd) # type: ignore
def _(expr: ArrayAdd, x: Expr):
return ArrayAdd(*[array_derive(arg, x) for arg in expr.args])
@array_derive.register(PermuteDims) # type: ignore
def _(expr: PermuteDims, x: Expr):
de = array_derive(expr.expr, x)
perm = [0, 1] + [i + 2 for i in expr.permutation.array_form]
return PermuteDims(de, perm)
def matrix_derive(expr, x):
from sympy.tensor.array.expressions.conv_array_to_matrix import convert_array_to_matrix
ce = convert_matrix_to_array(expr)
dce = array_derive(ce, x)
return convert_array_to_matrix(dce).doit()
|
5bbd4c8bf80dd21148f20e4fe227eba9ce23cfaa65c692606328fb579628e179 | from sympy import Lambda, S, Dummy
from sympy.core.symbol import symbols
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import cos, sin
from sympy.matrices.expressions.hadamard import HadamardProduct, HadamardPower
from sympy.matrices.expressions.special import (Identity, OneMatrix, ZeroMatrix)
from sympy.matrices.expressions.matexpr import MatrixElement
from sympy.tensor.array.expressions.conv_matrix_to_array import convert_matrix_to_array
from sympy.tensor.array.expressions.conv_array_to_matrix import _support_function_tp1_recognize, \
_array_diag2contr_diagmatrix, convert_array_to_matrix, _remove_trivial_dims, _array2matrix, \
_combine_removed, identify_removable_identity_matrices, _array_contraction_to_diagonal_multiple_identity
from sympy.matrices.expressions.matexpr import MatrixSymbol
from sympy.combinatorics import Permutation
from sympy.matrices.expressions.diagonal import DiagMatrix, DiagonalMatrix
from sympy.matrices import Trace, MatMul, Transpose
from sympy.tensor.array.expressions.array_expressions import ZeroArray, OneArray, \
ArrayTensorProduct, ArrayAdd, PermuteDims, ArrayDiagonal, \
ArrayContraction, ArrayElement, ArraySymbol, ArrayElementwiseApplyFunc
from sympy.testing.pytest import raises
i, j, k, l, m, n = symbols("i j k l m n")
I = Identity(k)
I1 = Identity(1)
M = MatrixSymbol("M", k, k)
N = MatrixSymbol("N", k, k)
P = MatrixSymbol("P", k, k)
Q = MatrixSymbol("Q", k, k)
A = MatrixSymbol("A", k, k)
B = MatrixSymbol("B", k, k)
C = MatrixSymbol("C", k, k)
D = MatrixSymbol("D", k, k)
X = MatrixSymbol("X", k, k)
Y = MatrixSymbol("Y", k, k)
a = MatrixSymbol("a", k, 1)
b = MatrixSymbol("b", k, 1)
c = MatrixSymbol("c", k, 1)
d = MatrixSymbol("d", k, 1)
x = MatrixSymbol("x", k, 1)
y = MatrixSymbol("y", k, 1)
def test_arrayexpr_convert_array_to_matrix():
cg = ArrayContraction(ArrayTensorProduct(M), (0, 1))
assert convert_array_to_matrix(cg) == Trace(M)
cg = ArrayContraction(ArrayTensorProduct(M, N), (0, 1), (2, 3))
assert convert_array_to_matrix(cg) == Trace(M) * Trace(N)
cg = ArrayContraction(ArrayTensorProduct(M, N), (0, 3), (1, 2))
assert convert_array_to_matrix(cg) == Trace(M * N)
cg = ArrayContraction(ArrayTensorProduct(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 = ArrayContraction(ArrayTensorProduct(M,N,P,Q), (1, 2), (5, 6))
assert convert_array_to_matrix(cg) == ArrayTensorProduct(M * N, P * Q)
cg = ArrayContraction(ArrayTensorProduct(-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(
ArrayContraction(
ArrayTensorProduct(
a,
ArrayAdd(
ArrayTensorProduct(b, c),
ArrayTensorProduct(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 = ArrayTensorProduct(3, M)
assert convert_array_to_matrix(cg) == 3 * M
# Partial conversion to matrix multiplication:
expr = ArrayContraction(ArrayTensorProduct(M, N, P, Q), (0, 2), (1, 4, 6))
assert convert_array_to_matrix(expr) == ArrayContraction(ArrayTensorProduct(M.T*N, P, Q), (0, 2, 4))
x = MatrixSymbol("x", k, 1)
cg = PermuteDims(
ArrayContraction(ArrayTensorProduct(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_arrayexpr_convert_array_to_matrix2():
cg = ArrayContraction(ArrayTensorProduct(M, N), (1, 3))
assert convert_array_to_matrix(cg) == M * N.T
cg = PermuteDims(ArrayTensorProduct(M, N), Permutation([0, 1, 3, 2]))
assert convert_array_to_matrix(cg) == ArrayTensorProduct(M, N.T)
cg = ArrayTensorProduct(M, PermuteDims(N, Permutation([1, 0])))
assert convert_array_to_matrix(cg) == ArrayTensorProduct(M, N.T)
cg = ArrayContraction(
PermuteDims(
ArrayTensorProduct(M, N, P, Q), Permutation([0, 2, 3, 1, 4, 5, 7, 6])),
(1, 2), (3, 5)
)
assert convert_array_to_matrix(cg) == ArrayTensorProduct(M * P.T * Trace(N), Q.T)
cg = ArrayContraction(
ArrayTensorProduct(M, N, P, PermuteDims(Q, Permutation([1, 0]))),
(1, 5), (2, 3)
)
assert convert_array_to_matrix(cg) == ArrayTensorProduct(M * P.T * Trace(N), Q.T)
cg = ArrayTensorProduct(M, PermuteDims(N, [1, 0]))
assert convert_array_to_matrix(cg) == ArrayTensorProduct(M, N.T)
cg = ArrayTensorProduct(PermuteDims(M, [1, 0]), PermuteDims(N, [1, 0]))
assert convert_array_to_matrix(cg) == ArrayTensorProduct(M.T, N.T)
cg = ArrayTensorProduct(PermuteDims(N, [1, 0]), PermuteDims(M, [1, 0]))
assert convert_array_to_matrix(cg) == ArrayTensorProduct(N.T, M.T)
cg = ArrayContraction(M, (0,), (1,))
assert convert_array_to_matrix(cg) == OneMatrix(1, k)*M*OneMatrix(k, 1)
cg = ArrayContraction(x, (0,), (1,))
assert convert_array_to_matrix(cg) == OneMatrix(1, k)*x
Xm = MatrixSymbol("Xm", m, n)
cg = ArrayContraction(Xm, (0,), (1,))
assert convert_array_to_matrix(cg) == OneMatrix(1, m)*Xm*OneMatrix(n, 1)
def test_arrayexpr_convert_array_to_diagonalized_vector():
# Check matrix recognition over trivial dimensions:
cg = ArrayTensorProduct(a, b)
assert convert_array_to_matrix(cg) == a * b.T
cg = ArrayTensorProduct(I1, a, b)
assert convert_array_to_matrix(cg) == a * b.T
# Recognize trace inside a tensor product:
cg = ArrayContraction(ArrayTensorProduct(A, B, C), (0, 3), (1, 2))
assert convert_array_to_matrix(cg) == Trace(A * B) * C
# Transform diagonal operator to contraction:
cg = ArrayDiagonal(ArrayTensorProduct(A, a), (1, 2))
assert _array_diag2contr_diagmatrix(cg) == ArrayContraction(ArrayTensorProduct(A, OneArray(1), DiagMatrix(a)), (1, 3))
assert convert_array_to_matrix(cg) == A * DiagMatrix(a)
cg = ArrayDiagonal(ArrayTensorProduct(a, b), (0, 2))
assert _array_diag2contr_diagmatrix(cg) == PermuteDims(
ArrayContraction(ArrayTensorProduct(DiagMatrix(a), OneArray(1), b), (0, 3)), [1, 2, 0]
)
assert convert_array_to_matrix(cg) == b.T * DiagMatrix(a)
cg = ArrayDiagonal(ArrayTensorProduct(A, a), (0, 2))
assert _array_diag2contr_diagmatrix(cg) == ArrayContraction(ArrayTensorProduct(A, OneArray(1), DiagMatrix(a)), (0, 3))
assert convert_array_to_matrix(cg) == A.T * DiagMatrix(a)
cg = ArrayDiagonal(ArrayTensorProduct(I, x, I1), (0, 2), (3, 5))
assert _array_diag2contr_diagmatrix(cg) == ArrayContraction(ArrayTensorProduct(I, OneArray(1), I1, DiagMatrix(x)), (0, 5))
assert convert_array_to_matrix(cg) == DiagMatrix(x)
cg = ArrayDiagonal(ArrayTensorProduct(I, x, A, B), (1, 2), (5, 6))
assert _array_diag2contr_diagmatrix(cg) == ArrayDiagonal(ArrayContraction(ArrayTensorProduct(I, OneArray(1), A, B, DiagMatrix(x)), (1, 7)), (5, 6))
# TODO: this is returning a wrong result:
# convert_array_to_matrix(cg)
cg = ArrayDiagonal(ArrayTensorProduct(I1, a, b), (1, 3, 5))
assert convert_array_to_matrix(cg) == a*b.T
cg = ArrayDiagonal(ArrayTensorProduct(I1, a, b), (1, 3))
assert _array_diag2contr_diagmatrix(cg) == ArrayContraction(ArrayTensorProduct(OneArray(1), a, b, I1), (2, 6))
assert convert_array_to_matrix(cg) == a*b.T
cg = ArrayDiagonal(ArrayTensorProduct(x, I1), (1, 2))
assert isinstance(cg, ArrayDiagonal)
assert cg.diagonal_indices == ((1, 2),)
assert convert_array_to_matrix(cg) == x
cg = ArrayDiagonal(ArrayTensorProduct(x, I), (0, 2))
assert _array_diag2contr_diagmatrix(cg) == ArrayContraction(ArrayTensorProduct(OneArray(1), I, DiagMatrix(x)), (1, 3))
assert convert_array_to_matrix(cg).doit() == DiagMatrix(x)
raises(ValueError, lambda: ArrayDiagonal(x, (1,)))
# Ignore identity matrices with contractions:
cg = ArrayContraction(ArrayTensorProduct(I, A, I, I), (0, 2), (1, 3), (5, 7))
assert cg.split_multiple_contractions() == cg
assert convert_array_to_matrix(cg) == Trace(A) * I
cg = ArrayContraction(ArrayTensorProduct(Trace(A) * I, I, I), (1, 5), (3, 4))
assert cg.split_multiple_contractions() == cg
assert convert_array_to_matrix(cg).doit() == Trace(A) * I
# Add DiagMatrix when required:
cg = ArrayContraction(ArrayTensorProduct(A, a), (1, 2))
assert cg.split_multiple_contractions() == cg
assert convert_array_to_matrix(cg) == A * a
cg = ArrayContraction(ArrayTensorProduct(A, a, B), (1, 2, 4))
assert cg.split_multiple_contractions() == ArrayContraction(ArrayTensorProduct(A, DiagMatrix(a), OneArray(1), B), (1, 2), (3, 5))
assert convert_array_to_matrix(cg) == A * DiagMatrix(a) * B
cg = ArrayContraction(ArrayTensorProduct(A, a, B), (0, 2, 4))
assert cg.split_multiple_contractions() == ArrayContraction(ArrayTensorProduct(A, DiagMatrix(a), OneArray(1), B), (0, 2), (3, 5))
assert convert_array_to_matrix(cg) == A.T * DiagMatrix(a) * B
cg = ArrayContraction(ArrayTensorProduct(A, a, b, a.T, B), (0, 2, 4, 7, 9))
assert cg.split_multiple_contractions() == ArrayContraction(ArrayTensorProduct(A, DiagMatrix(a), OneArray(1),
DiagMatrix(b), OneArray(1), DiagMatrix(a), OneArray(1), B),
(0, 2), (3, 5), (6, 9), (8, 12))
assert convert_array_to_matrix(cg) == A.T * DiagMatrix(a) * DiagMatrix(b) * DiagMatrix(a) * B.T
cg = ArrayContraction(ArrayTensorProduct(I1, I1, I1), (1, 2, 4))
assert cg.split_multiple_contractions() == ArrayContraction(ArrayTensorProduct(I1, I1, OneArray(1), I1), (1, 2), (3, 5))
assert convert_array_to_matrix(cg) == 1
cg = ArrayContraction(ArrayTensorProduct(I, I, I, I, A), (1, 2, 8), (5, 6, 9))
assert convert_array_to_matrix(cg.split_multiple_contractions()).doit() == A
cg = ArrayContraction(ArrayTensorProduct(A, a, C, a, B), (1, 2, 4), (5, 6, 8))
expected = ArrayContraction(ArrayTensorProduct(A, DiagMatrix(a), OneArray(1), C, DiagMatrix(a), OneArray(1), B), (1, 3), (2, 5), (6, 7), (8, 10))
assert cg.split_multiple_contractions() == expected
assert convert_array_to_matrix(cg) == A * DiagMatrix(a) * C * DiagMatrix(a) * B
cg = ArrayContraction(ArrayTensorProduct(a, I1, b, I1, (a.T*b).applyfunc(cos)), (1, 2, 8), (5, 6, 9))
expected = ArrayContraction(ArrayTensorProduct(a, I1, OneArray(1), b, I1, OneArray(1), (a.T*b).applyfunc(cos)),
(1, 3), (2, 10), (6, 8), (7, 11))
assert cg.split_multiple_contractions().dummy_eq(expected)
assert convert_array_to_matrix(cg).doit().dummy_eq(MatMul(a, (a.T * b).applyfunc(cos), b.T))
def test_arrayexpr_convert_array_contraction_tp_additions():
a = ArrayAdd(
ArrayTensorProduct(M, N),
ArrayTensorProduct(N, M)
)
tp = ArrayTensorProduct(P, a, Q)
expr = ArrayContraction(tp, (3, 4))
expected = ArrayTensorProduct(
P,
ArrayAdd(
ArrayContraction(ArrayTensorProduct(M, N), (1, 2)),
ArrayContraction(ArrayTensorProduct(N, M), (1, 2)),
),
Q
)
assert expr == expected
assert convert_array_to_matrix(expr) == ArrayTensorProduct(P, M * N + N * M, Q)
expr = ArrayContraction(tp, (1, 2), (3, 4), (5, 6))
result = ArrayContraction(
ArrayTensorProduct(
P,
ArrayAdd(
ArrayContraction(ArrayTensorProduct(M, N), (1, 2)),
ArrayContraction(ArrayTensorProduct(N, M), (1, 2)),
),
Q
), (1, 2), (3, 4))
assert expr == result
assert convert_array_to_matrix(expr) == P * (M * N + N * M) * Q
def test_arrayexpr_convert_array_to_implicit_matmul():
# Trivial dimensions are suppressed, so the result can be expressed in matrix form:
cg = ArrayTensorProduct(a, b)
assert convert_array_to_matrix(cg) == a * b.T
cg = ArrayTensorProduct(a, b, I)
assert convert_array_to_matrix(cg) == ArrayTensorProduct(a*b.T, I)
cg = ArrayTensorProduct(I, a, b)
assert convert_array_to_matrix(cg) == ArrayTensorProduct(I, a*b.T)
cg = ArrayTensorProduct(a, I, b)
assert convert_array_to_matrix(cg) == ArrayTensorProduct(a, I, b)
cg = ArrayContraction(ArrayTensorProduct(I, I), (1, 2))
assert convert_array_to_matrix(cg) == I
cg = PermuteDims(ArrayTensorProduct(I, Identity(1)), [0, 2, 1, 3])
assert convert_array_to_matrix(cg) == I
def test_arrayexpr_convert_array_to_matrix_remove_trivial_dims():
# Tensor Product:
assert _remove_trivial_dims(ArrayTensorProduct(a, b)) == (a * b.T, [1, 3])
assert _remove_trivial_dims(ArrayTensorProduct(a.T, b)) == (a * b.T, [0, 3])
assert _remove_trivial_dims(ArrayTensorProduct(a, b.T)) == (a * b.T, [1, 2])
assert _remove_trivial_dims(ArrayTensorProduct(a.T, b.T)) == (a * b.T, [0, 2])
assert _remove_trivial_dims(ArrayTensorProduct(I, a.T, b.T)) == (ArrayTensorProduct(I, a * b.T), [2, 4])
assert _remove_trivial_dims(ArrayTensorProduct(a.T, I, b.T)) == (ArrayTensorProduct(a.T, I, b.T), [])
assert _remove_trivial_dims(ArrayTensorProduct(a, I)) == (ArrayTensorProduct(a, I), [])
assert _remove_trivial_dims(ArrayTensorProduct(I, a)) == (ArrayTensorProduct(I, a), [])
assert _remove_trivial_dims(ArrayTensorProduct(a.T, b.T, c, d)) == (
ArrayTensorProduct(a * b.T, c * d.T), [0, 2, 5, 7])
assert _remove_trivial_dims(ArrayTensorProduct(a.T, I, b.T, c, d, I)) == (
ArrayTensorProduct(a.T, I, b*c.T, d, I), [4, 7])
# Addition:
cg = ArrayAdd(ArrayTensorProduct(a, b), ArrayTensorProduct(c, d))
assert _remove_trivial_dims(cg) == (a * b.T + c * d.T, [1, 3])
# Permute Dims:
cg = PermuteDims(ArrayTensorProduct(a, b), Permutation(3)(1, 2))
assert _remove_trivial_dims(cg) == (a * b.T, [2, 3])
cg = PermuteDims(ArrayTensorProduct(a, I, b), Permutation(5)(1, 2, 3, 4))
assert _remove_trivial_dims(cg) == (cg, [])
cg = PermuteDims(ArrayTensorProduct(I, b, a), Permutation(5)(1, 2, 4, 5, 3))
assert _remove_trivial_dims(cg) == (PermuteDims(ArrayTensorProduct(I, b * a.T), [0, 2, 3, 1]), [4, 5])
# Diagonal:
cg = ArrayDiagonal(ArrayTensorProduct(M, a), (1, 2))
assert _remove_trivial_dims(cg) == (cg, [])
# Contraction:
cg = ArrayContraction(ArrayTensorProduct(M, a), (1, 2))
assert _remove_trivial_dims(cg) == (cg, [])
# A few more cases to test the removal and shift of nested removed axes
# with array contractions and array diagonals:
tp = ArrayTensorProduct(
OneMatrix(1, 1),
M,
x,
OneMatrix(1, 1),
Identity(1),
)
expr = ArrayContraction(tp, (1, 8))
rexpr, removed = _remove_trivial_dims(expr)
assert removed == [0, 5, 6, 7]
expr = ArrayContraction(tp, (1, 8), (3, 4))
rexpr, removed = _remove_trivial_dims(expr)
assert removed == [0, 3, 4, 5]
expr = ArrayDiagonal(tp, (1, 8))
rexpr, removed = _remove_trivial_dims(expr)
assert removed == [0, 5, 6, 7, 8]
expr = ArrayDiagonal(tp, (1, 8), (3, 4))
rexpr, removed = _remove_trivial_dims(expr)
assert removed == [0, 3, 4, 5, 6]
expr = ArrayDiagonal(ArrayContraction(ArrayTensorProduct(A, x, I, I1), (1, 2, 5)), (1, 4))
rexpr, removed = _remove_trivial_dims(expr)
assert removed == [2, 3]
cg = ArrayDiagonal(ArrayTensorProduct(PermuteDims(ArrayTensorProduct(x, I1), Permutation(1, 2, 3)), (x.T*x).applyfunc(sqrt)), (2, 4), (3, 5))
rexpr, removed = _remove_trivial_dims(cg)
assert removed == [1, 2]
# Contractions with identity matrices need to be followed by a permutation
# in order
cg = ArrayContraction(ArrayTensorProduct(A, B, C, M, I), (1, 8))
ret, removed = _remove_trivial_dims(cg)
assert ret == PermuteDims(ArrayTensorProduct(A, B, C, M), [0, 2, 3, 4, 5, 6, 7, 1])
assert removed == []
cg = ArrayContraction(ArrayTensorProduct(A, B, C, M, I), (1, 8), (3, 4))
ret, removed = _remove_trivial_dims(cg)
assert ret == PermuteDims(ArrayContraction(ArrayTensorProduct(A, B, C, M), (3, 4)), [0, 2, 3, 4, 5, 1])
assert removed == []
# Trivial matrices are sometimes inserted into MatMul expressions:
cg = ArrayTensorProduct(b*b.T, a.T*a)
ret, removed = _remove_trivial_dims(cg)
assert ret == b*a.T*a*b.T
assert removed == [2, 3]
Xs = ArraySymbol("X", (3, 2, k))
cg = ArrayTensorProduct(M, Xs, b.T*c, a*a.T, b*b.T, c.T*d)
ret, removed = _remove_trivial_dims(cg)
assert ret == ArrayTensorProduct(M, Xs, a*b.T*c*c.T*d*a.T, b*b.T)
assert removed == [5, 6, 11, 12]
cg = ArrayDiagonal(ArrayTensorProduct(I, I1, x), (1, 4), (3, 5))
assert _remove_trivial_dims(cg) == (PermuteDims(ArrayDiagonal(ArrayTensorProduct(I, x), (1, 2)), Permutation(1, 2)), [1])
expr = ArrayDiagonal(ArrayTensorProduct(x, I, y), (0, 2))
assert _remove_trivial_dims(expr) == (PermuteDims(ArrayTensorProduct(DiagMatrix(x), y), [1, 2, 3, 0]), [0])
expr = ArrayDiagonal(ArrayTensorProduct(x, I, y), (0, 2), (3, 4))
assert _remove_trivial_dims(expr) == (expr, [])
def test_arrayexpr_convert_array_to_matrix_diag2contraction_diagmatrix():
cg = ArrayDiagonal(ArrayTensorProduct(M, a), (1, 2))
res = _array_diag2contr_diagmatrix(cg)
assert res.shape == cg.shape
assert res == ArrayContraction(ArrayTensorProduct(M, OneArray(1), DiagMatrix(a)), (1, 3))
raises(ValueError, lambda: ArrayDiagonal(ArrayTensorProduct(a, M), (1, 2)))
cg = ArrayDiagonal(ArrayTensorProduct(a.T, M), (1, 2))
res = _array_diag2contr_diagmatrix(cg)
assert res.shape == cg.shape
assert res == ArrayContraction(ArrayTensorProduct(OneArray(1), M, DiagMatrix(a.T)), (1, 4))
cg = ArrayDiagonal(ArrayTensorProduct(a.T, M, N, b.T), (1, 2), (4, 7))
res = _array_diag2contr_diagmatrix(cg)
assert res.shape == cg.shape
assert res == ArrayContraction(
ArrayTensorProduct(OneArray(1), M, N, OneArray(1), DiagMatrix(a.T), DiagMatrix(b.T)), (1, 7), (3, 9))
cg = ArrayDiagonal(ArrayTensorProduct(a, M, N, b.T), (0, 2), (4, 7))
res = _array_diag2contr_diagmatrix(cg)
assert res.shape == cg.shape
assert res == ArrayContraction(
ArrayTensorProduct(OneArray(1), M, N, OneArray(1), DiagMatrix(a), DiagMatrix(b.T)), (1, 6), (3, 9))
cg = ArrayDiagonal(ArrayTensorProduct(a, M, N, b.T), (0, 4), (3, 7))
res = _array_diag2contr_diagmatrix(cg)
assert res.shape == cg.shape
assert res == ArrayContraction(
ArrayTensorProduct(OneArray(1), M, N, OneArray(1), DiagMatrix(a), DiagMatrix(b.T)), (3, 6), (2, 9))
I1 = Identity(1)
x = MatrixSymbol("x", k, 1)
A = MatrixSymbol("A", k, k)
cg = ArrayDiagonal(ArrayTensorProduct(x, A.T, I1), (0, 2))
assert _array_diag2contr_diagmatrix(cg).shape == cg.shape
assert _array2matrix(cg).shape == cg.shape
def test_arrayexpr_convert_array_to_matrix_support_function():
assert _support_function_tp1_recognize([], [2 * k]) == 2 * k
assert _support_function_tp1_recognize([(1, 2)], [A, 2 * k, B, 3]) == 6 * k * A * B
assert _support_function_tp1_recognize([(0, 3), (1, 2)], [A, B]) == Trace(A * B)
assert _support_function_tp1_recognize([(1, 2)], [A, B]) == A * B
assert _support_function_tp1_recognize([(0, 2)], [A, B]) == A.T * B
assert _support_function_tp1_recognize([(1, 3)], [A, B]) == A * B.T
assert _support_function_tp1_recognize([(0, 3)], [A, B]) == A.T * B.T
assert _support_function_tp1_recognize([(1, 2), (5, 6)], [A, B, C, D]) == ArrayTensorProduct(A * B, C * D)
assert _support_function_tp1_recognize([(1, 4), (3, 6)], [A, B, C, D]) == PermuteDims(
ArrayTensorProduct(A * C, B * D), [0, 2, 1, 3])
assert _support_function_tp1_recognize([(0, 3), (1, 4)], [A, B, C]) == B * A * C
assert _support_function_tp1_recognize([(9, 10), (1, 2), (5, 6), (3, 4), (7, 8)],
[X, Y, A, B, C, D]) == X * Y * A * B * C * D
assert _support_function_tp1_recognize([(9, 10), (1, 2), (5, 6), (3, 4)],
[X, Y, A, B, C, D]) == ArrayTensorProduct(X * Y * A * B, C * D)
assert _support_function_tp1_recognize([(1, 7), (3, 8), (4, 11)], [X, Y, A, B, C, D]) == PermuteDims(
ArrayTensorProduct(X * B.T, Y * C, A.T * D.T), [0, 2, 4, 1, 3, 5]
)
assert _support_function_tp1_recognize([(0, 1), (3, 6), (5, 8)], [X, A, B, C, D]) == PermuteDims(
ArrayTensorProduct(Trace(X) * A * C, B * D), [0, 2, 1, 3])
assert _support_function_tp1_recognize([(1, 2), (3, 4), (5, 6), (7, 8)], [A, A, B, C, D]) == A ** 2 * B * C * D
assert _support_function_tp1_recognize([(1, 2), (3, 4), (5, 6), (7, 8)], [X, A, B, C, D]) == X * A * B * C * D
assert _support_function_tp1_recognize([(1, 6), (3, 8), (5, 10)], [X, Y, A, B, C, D]) == PermuteDims(
ArrayTensorProduct(X * B, Y * C, A * D), [0, 2, 4, 1, 3, 5]
)
assert _support_function_tp1_recognize([(1, 4), (3, 6)], [A, B, C, D]) == PermuteDims(
ArrayTensorProduct(A * C, B * D), [0, 2, 1, 3])
assert _support_function_tp1_recognize([(0, 4), (1, 7), (2, 5), (3, 8)], [X, A, B, C, D]) == C*X.T*B*A*D
assert _support_function_tp1_recognize([(0, 4), (1, 7), (2, 5), (3, 8)], [X, A, B, C, D]) == C*X.T*B*A*D
def test_convert_array_to_hadamard_products():
expr = HadamardProduct(M, N)
cg = convert_matrix_to_array(expr)
ret = convert_array_to_matrix(cg)
assert ret == expr
expr = HadamardProduct(M, N)*P
cg = convert_matrix_to_array(expr)
ret = convert_array_to_matrix(cg)
assert ret == expr
expr = Q*HadamardProduct(M, N)*P
cg = convert_matrix_to_array(expr)
ret = convert_array_to_matrix(cg)
assert ret == expr
expr = Q*HadamardProduct(M, N.T)*P
cg = convert_matrix_to_array(expr)
ret = convert_array_to_matrix(cg)
assert ret == expr
expr = HadamardProduct(M, N)*HadamardProduct(Q, P)
cg = convert_matrix_to_array(expr)
ret = convert_array_to_matrix(cg)
assert expr == ret
expr = P.T*HadamardProduct(M, N)*HadamardProduct(Q, P)
cg = convert_matrix_to_array(expr)
ret = convert_array_to_matrix(cg)
assert expr == ret
# ArrayDiagonal should be converted
cg = ArrayDiagonal(ArrayTensorProduct(M, N, Q), (1, 3), (0, 2, 4))
ret = convert_array_to_matrix(cg)
expected = PermuteDims(ArrayDiagonal(ArrayTensorProduct(HadamardProduct(M.T, N.T), Q), (1, 2)), [1, 0, 2])
assert expected == ret
# Special case that should return the same expression:
cg = ArrayDiagonal(ArrayTensorProduct(HadamardProduct(M, N), Q), (0, 2))
ret = convert_array_to_matrix(cg)
assert ret == cg
# Hadamard products with traces:
expr = Trace(HadamardProduct(M, N))
cg = convert_matrix_to_array(expr)
ret = convert_array_to_matrix(cg)
assert ret == Trace(HadamardProduct(M.T, N.T))
expr = Trace(A*HadamardProduct(M, N))
cg = convert_matrix_to_array(expr)
ret = convert_array_to_matrix(cg)
assert ret == Trace(HadamardProduct(M, N)*A)
expr = Trace(HadamardProduct(A, M)*N)
cg = convert_matrix_to_array(expr)
ret = convert_array_to_matrix(cg)
assert ret == Trace(HadamardProduct(M.T, N)*A)
# These should not be converted into Hadamard products:
cg = ArrayDiagonal(ArrayTensorProduct(M, N), (0, 1, 2, 3))
ret = convert_array_to_matrix(cg)
assert ret == cg
cg = ArrayDiagonal(ArrayTensorProduct(A), (0, 1))
ret = convert_array_to_matrix(cg)
assert ret == cg
cg = ArrayDiagonal(ArrayTensorProduct(M, N, P), (0, 2, 4), (1, 3, 5))
assert convert_array_to_matrix(cg) == HadamardProduct(M, N, P)
cg = ArrayDiagonal(ArrayTensorProduct(M, N, P), (0, 3, 4), (1, 2, 5))
assert convert_array_to_matrix(cg) == HadamardProduct(M, P, N.T)
cg = ArrayDiagonal(ArrayTensorProduct(I, I1, x), (1, 4), (3, 5))
assert convert_array_to_matrix(cg) == DiagMatrix(x)
def test_identify_removable_identity_matrices():
D = DiagonalMatrix(MatrixSymbol("D", k, k))
cg = ArrayContraction(ArrayTensorProduct(A, B, I), (1, 2, 4, 5))
expected = ArrayContraction(ArrayTensorProduct(A, B), (1, 2))
assert identify_removable_identity_matrices(cg) == expected
cg = ArrayContraction(ArrayTensorProduct(A, B, C, I), (1, 3, 5, 6, 7))
expected = ArrayContraction(ArrayTensorProduct(A, B, C), (1, 3, 5))
assert identify_removable_identity_matrices(cg) == expected
# Tests with diagonal matrices:
cg = ArrayContraction(ArrayTensorProduct(A, B, D), (1, 2, 4, 5))
ret = identify_removable_identity_matrices(cg)
expected = ArrayContraction(ArrayTensorProduct(A, B, D), (1, 4), (2, 5))
assert ret == expected
cg = ArrayContraction(ArrayTensorProduct(A, B, D, M, N), (1, 2, 4, 5, 6, 8))
ret = identify_removable_identity_matrices(cg)
assert ret == cg
def test_combine_removed():
assert _combine_removed(6, [0, 1, 2], [0, 1, 2]) == [0, 1, 2, 3, 4, 5]
assert _combine_removed(8, [2, 5], [1, 3, 4]) == [1, 2, 4, 5, 6]
assert _combine_removed(8, [7], []) == [7]
def test_array_contraction_to_diagonal_multiple_identities():
expr = ArrayContraction(ArrayTensorProduct(A, B, I, C), (1, 2, 4), (5, 6))
assert _array_contraction_to_diagonal_multiple_identity(expr) == (expr, [])
assert convert_array_to_matrix(expr) == ArrayContraction(ArrayTensorProduct(A, B, C), (1, 2, 4))
expr = ArrayContraction(ArrayTensorProduct(A, I, I), (1, 2, 4))
assert _array_contraction_to_diagonal_multiple_identity(expr) == (A, [2])
assert convert_array_to_matrix(expr) == A
expr = ArrayContraction(ArrayTensorProduct(A, I, I, B), (1, 2, 4), (3, 6))
assert _array_contraction_to_diagonal_multiple_identity(expr) == (expr, [])
expr = ArrayContraction(ArrayTensorProduct(A, I, I, B), (1, 2, 3, 4, 6))
assert _array_contraction_to_diagonal_multiple_identity(expr) == (expr, [])
def test_convert_array_element_to_matrix():
expr = ArrayElement(M, (i, j))
assert convert_array_to_matrix(expr) == MatrixElement(M, i, j)
expr = ArrayElement(ArrayContraction(ArrayTensorProduct(M, N), (1, 3)), (i, j))
assert convert_array_to_matrix(expr) == MatrixElement(M*N.T, i, j)
expr = ArrayElement(ArrayTensorProduct(M, N), (i, j, m, n))
assert convert_array_to_matrix(expr) == expr
def test_convert_array_elementwise_function_to_matrix():
d = Dummy("d")
expr = ArrayElementwiseApplyFunc(Lambda(d, sin(d)), x.T*y)
assert convert_array_to_matrix(expr) == sin(x.T*y)
expr = ArrayElementwiseApplyFunc(Lambda(d, d**2), x.T*y)
assert convert_array_to_matrix(expr) == (x.T*y)**2
expr = ArrayElementwiseApplyFunc(Lambda(d, sin(d)), x)
assert convert_array_to_matrix(expr).dummy_eq(x.applyfunc(sin))
expr = ArrayElementwiseApplyFunc(Lambda(d, 1 / (2 * sqrt(d))), x)
assert convert_array_to_matrix(expr) == S.Half * HadamardPower(x, -S.Half)
|
9ce8c52970aa60dbb63bb4b37354c3d71d5bb147213d1006de71a534611dd588 | from sympy.core.symbol import Symbol
from sympy.matrices.expressions.matexpr import MatrixSymbol
from sympy.tensor.array.arrayop import (permutedims, tensorcontraction, tensordiagonal, tensorproduct)
from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArray
from sympy.tensor.array.expressions.array_expressions import ZeroArray, OneArray, ArraySymbol, \
ArrayTensorProduct, PermuteDims, ArrayDiagonal, ArrayContraction, ArrayAdd
from sympy.testing.pytest import raises
def test_array_as_explicit_call():
assert ZeroArray(3, 2, 4).as_explicit() == ImmutableDenseNDimArray.zeros(3, 2, 4)
assert OneArray(3, 2, 4).as_explicit() == ImmutableDenseNDimArray([1 for i in range(3*2*4)]).reshape(3, 2, 4)
k = Symbol("k")
X = ArraySymbol("X", (k, 3, 2))
raises(ValueError, lambda: X.as_explicit())
raises(ValueError, lambda: ZeroArray(k, 2, 3).as_explicit())
raises(ValueError, lambda: OneArray(2, k, 2).as_explicit())
A = ArraySymbol("A", (3, 3))
B = ArraySymbol("B", (3, 3))
texpr = tensorproduct(A, B)
assert isinstance(texpr, ArrayTensorProduct)
assert texpr.as_explicit() == tensorproduct(A.as_explicit(), B.as_explicit())
texpr = tensorcontraction(A, (0, 1))
assert isinstance(texpr, ArrayContraction)
assert texpr.as_explicit() == A[0, 0] + A[1, 1] + A[2, 2]
texpr = tensordiagonal(A, (0, 1))
assert isinstance(texpr, ArrayDiagonal)
assert texpr.as_explicit() == ImmutableDenseNDimArray([A[0, 0], A[1, 1], A[2, 2]])
texpr = permutedims(A, [1, 0])
assert isinstance(texpr, PermuteDims)
assert texpr.as_explicit() == permutedims(A.as_explicit(), [1, 0])
def test_array_as_explicit_matrix_symbol():
A = MatrixSymbol("A", 3, 3)
B = MatrixSymbol("B", 3, 3)
texpr = tensorproduct(A, B)
assert isinstance(texpr, ArrayTensorProduct)
assert texpr.as_explicit() == tensorproduct(A.as_explicit(), B.as_explicit())
texpr = tensorcontraction(A, (0, 1))
assert isinstance(texpr, ArrayContraction)
assert texpr.as_explicit() == A[0, 0] + A[1, 1] + A[2, 2]
texpr = tensordiagonal(A, (0, 1))
assert isinstance(texpr, ArrayDiagonal)
assert texpr.as_explicit() == ImmutableDenseNDimArray([A[0, 0], A[1, 1], A[2, 2]])
texpr = permutedims(A, [1, 0])
assert isinstance(texpr, PermuteDims)
assert texpr.as_explicit() == permutedims(A.as_explicit(), [1, 0])
expr = ArrayAdd(ArrayTensorProduct(A, B), ArrayTensorProduct(B, A))
assert expr.as_explicit() == expr.args[0].as_explicit() + expr.args[1].as_explicit()
|
e804fedfb3e1bc582fb46325535af8fb3e341851d244208c7780b1dcd7b40d0e | from sympy.concrete.summations import Sum
from sympy.core.symbol import symbols
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.matrices.expressions.matexpr import MatrixSymbol
from sympy.matrices.expressions.special import Identity
from sympy.tensor.indexed import IndexedBase
from sympy.combinatorics import Permutation
from sympy.tensor.array.expressions.array_expressions import ArrayContraction, ArrayTensorProduct, \
ArrayDiagonal, ArrayAdd, PermuteDims, ArrayElement
from sympy.tensor.array.expressions.conv_array_to_matrix import convert_array_to_matrix
from sympy.tensor.array.expressions.conv_indexed_to_array import convert_indexed_to_array, _convert_indexed_to_array
from sympy.testing.pytest import raises
A, B = symbols("A B", cls=IndexedBase)
i, j, k, l, m, n = symbols("i j k l m n")
I = Identity(k)
M = MatrixSymbol("M", k, k)
N = MatrixSymbol("N", k, k)
P = MatrixSymbol("P", k, k)
Q = MatrixSymbol("Q", k, k)
a = MatrixSymbol("a", k, 1)
b = MatrixSymbol("b", k, 1)
c = MatrixSymbol("c", k, 1)
d = MatrixSymbol("d", k, 1)
def test_arrayexpr_convert_index_to_array_support_function():
expr = M[i, j]
assert _convert_indexed_to_array(expr) == (M, (i, j))
expr = M[i, j]*N[k, l]
assert _convert_indexed_to_array(expr) == (ArrayTensorProduct(M, N), (i, j, k, l))
expr = M[i, j]*N[j, k]
assert _convert_indexed_to_array(expr) == (ArrayDiagonal(ArrayTensorProduct(M, N), (1, 2)), (i, k, j))
expr = Sum(M[i, j]*N[j, k], (j, 0, k-1))
assert _convert_indexed_to_array(expr) == (ArrayContraction(ArrayTensorProduct(M, N), (1, 2)), (i, k))
expr = M[i, j] + N[i, j]
assert _convert_indexed_to_array(expr) == (ArrayAdd(M, N), (i, j))
expr = M[i, j] + N[j, i]
assert _convert_indexed_to_array(expr) == (ArrayAdd(M, PermuteDims(N, Permutation([1, 0]))), (i, j))
expr = M[i, j] + M[j, i]
assert _convert_indexed_to_array(expr) == (ArrayAdd(M, PermuteDims(M, Permutation([1, 0]))), (i, j))
expr = (M*N*P)[i, j]
assert _convert_indexed_to_array(expr) == (ArrayContraction(ArrayTensorProduct(M, N, P), (1, 2), (3, 4)), (i, j))
expr = expr.function # Disregard summation in previous expression
ret1, ret2 = _convert_indexed_to_array(expr)
assert ret1 == ArrayDiagonal(ArrayTensorProduct(M, N, P), (1, 2), (3, 4))
assert str(ret2) == "(i, j, _i_1, _i_2)"
expr = KroneckerDelta(i, j)*M[i, k]
assert _convert_indexed_to_array(expr) == (M, ({i, j}, k))
expr = KroneckerDelta(i, j)*KroneckerDelta(j, k)*M[i, l]
assert _convert_indexed_to_array(expr) == (M, ({i, j, k}, l))
expr = KroneckerDelta(j, k)*(M[i, j]*N[k, l] + N[i, j]*M[k, l])
assert _convert_indexed_to_array(expr) == (ArrayDiagonal(ArrayAdd(
ArrayTensorProduct(M, N),
PermuteDims(ArrayTensorProduct(M, N), Permutation(0, 2)(1, 3))
), (1, 2)), (i, l, frozenset({j, k})))
expr = KroneckerDelta(j, m)*KroneckerDelta(m, k)*(M[i, j]*N[k, l] + N[i, j]*M[k, l])
assert _convert_indexed_to_array(expr) == (ArrayDiagonal(ArrayAdd(
ArrayTensorProduct(M, N),
PermuteDims(ArrayTensorProduct(M, N), Permutation(0, 2)(1, 3))
), (1, 2)), (i, l, frozenset({j, m, k})))
expr = KroneckerDelta(i, j)*KroneckerDelta(j, k)*KroneckerDelta(k,m)*M[i, 0]*KroneckerDelta(m, n)
assert _convert_indexed_to_array(expr) == (M, ({i, j, k, m, n}, 0))
expr = M[i, i]
assert _convert_indexed_to_array(expr) == (ArrayDiagonal(M, (0, 1)), (i,))
def test_arrayexpr_convert_indexed_to_array_expression():
s = Sum(A[i]*B[i], (i, 0, 3))
cg = convert_indexed_to_array(s)
assert cg == ArrayContraction(ArrayTensorProduct(A, B), (0, 1))
expr = M*N
result = ArrayContraction(ArrayTensorProduct(M, N), (1, 2))
elem = expr[i, j]
assert convert_indexed_to_array(elem) == result
expr = M*N*M
elem = expr[i, j]
result = ArrayContraction(ArrayTensorProduct(M, M, N), (1, 4), (2, 5))
cg = convert_indexed_to_array(elem)
assert cg == result
cg = convert_indexed_to_array((M * N * P)[i, j])
assert cg == ArrayContraction(ArrayTensorProduct(M, N, P), (1, 2), (3, 4))
cg = convert_indexed_to_array((M * N.T * P)[i, j])
assert cg == ArrayContraction(ArrayTensorProduct(M, N, P), (1, 3), (2, 4))
expr = -2*M*N
elem = expr[i, j]
cg = convert_indexed_to_array(elem)
assert cg == ArrayContraction(ArrayTensorProduct(-2, M, N), (1, 2))
def test_arrayexpr_convert_indexed_to_array_and_back_to_matrix():
expr = a.T*b
elem = expr[0, 0]
cg = convert_indexed_to_array(elem)
assert cg == ArrayElement(ArrayContraction(ArrayTensorProduct(a, b), (0, 2)), [0, 0])
expr = M[i,j] + N[i,j]
p1, p2 = _convert_indexed_to_array(expr)
assert convert_array_to_matrix(p1) == M + N
expr = M[i,j] + N[j,i]
p1, p2 = _convert_indexed_to_array(expr)
assert convert_array_to_matrix(p1) == M + N.T
expr = M[i,j]*N[k,l] + N[i,j]*M[k,l]
p1, p2 = _convert_indexed_to_array(expr)
assert convert_array_to_matrix(p1) == ArrayAdd(
ArrayTensorProduct(M, N),
ArrayTensorProduct(N, M))
expr = (M*N*P)[i, j]
p1, p2 = _convert_indexed_to_array(expr)
assert convert_array_to_matrix(p1) == M * N * P
expr = Sum(M[i,j]*(N*P)[j,m], (j, 0, k-1))
p1, p2 = _convert_indexed_to_array(expr)
assert convert_array_to_matrix(p1) == M * N * P
expr = Sum((P[j, m] + P[m, j])*(M[i,j]*N[m,n] + N[i,j]*M[m,n]), (j, 0, k-1), (m, 0, k-1))
p1, p2 = _convert_indexed_to_array(expr)
assert convert_array_to_matrix(p1) == M * P * N + M * P.T * N + N * P * M + N * P.T * M
def test_arrayexpr_convert_indexed_to_array_out_of_bounds():
expr = Sum(M[i, i], (i, 0, 4))
raises(ValueError, lambda: convert_indexed_to_array(expr))
expr = Sum(M[i, i], (i, 0, k))
raises(ValueError, lambda: convert_indexed_to_array(expr))
expr = Sum(M[i, i], (i, 1, k-1))
raises(ValueError, lambda: convert_indexed_to_array(expr))
expr = Sum(M[i, j]*N[j,m], (j, 0, 4))
raises(ValueError, lambda: convert_indexed_to_array(expr))
expr = Sum(M[i, j]*N[j,m], (j, 0, k))
raises(ValueError, lambda: convert_indexed_to_array(expr))
expr = Sum(M[i, j]*N[j,m], (j, 1, k-1))
raises(ValueError, lambda: convert_indexed_to_array(expr))
|
1d80c985e1b9fb47d301764c9ac183c8a4d7cd9a06c9bbdfa8c906f246320bc0 | from sympy import Lambda
from sympy.core.symbol import symbols, Dummy
from sympy.matrices.expressions.hadamard import (HadamardPower, HadamardProduct)
from sympy.matrices.expressions.inverse import Inverse
from sympy.matrices.expressions.matexpr import MatrixSymbol
from sympy.matrices.expressions.matpow import MatPow
from sympy.matrices.expressions.special import Identity
from sympy.matrices.expressions.trace import Trace
from sympy.matrices.expressions.transpose import Transpose
from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct, ArrayContraction, \
PermuteDims, ArrayDiagonal, ArrayElementwiseApplyFunc
from sympy.tensor.array.expressions.conv_array_to_matrix import convert_array_to_matrix
from sympy.tensor.array.expressions.conv_matrix_to_array import convert_matrix_to_array
i, j, k, l, m, n = symbols("i j k l m n")
I = Identity(k)
M = MatrixSymbol("M", k, k)
N = MatrixSymbol("N", k, k)
P = MatrixSymbol("P", k, k)
Q = MatrixSymbol("Q", k, k)
A = MatrixSymbol("A", k, k)
B = MatrixSymbol("B", k, k)
C = MatrixSymbol("C", k, k)
D = MatrixSymbol("D", k, k)
X = MatrixSymbol("X", k, k)
Y = MatrixSymbol("Y", k, k)
a = MatrixSymbol("a", k, 1)
b = MatrixSymbol("b", k, 1)
c = MatrixSymbol("c", k, 1)
d = MatrixSymbol("d", k, 1)
def test_arrayexpr_convert_matrix_to_array():
expr = M*N
result = ArrayContraction(ArrayTensorProduct(M, N), (1, 2))
assert convert_matrix_to_array(expr) == result
expr = M*N*M
result = ArrayContraction(ArrayTensorProduct(M, N, M), (1, 2), (3, 4))
assert convert_matrix_to_array(expr) == result
expr = Transpose(M)
assert convert_matrix_to_array(expr) == PermuteDims(M, [1, 0])
expr = M*Transpose(N)
assert convert_matrix_to_array(expr) == ArrayContraction(ArrayTensorProduct(M, PermuteDims(N, [1, 0])), (1, 2))
expr = 3*M*N
res = convert_matrix_to_array(expr)
rexpr = convert_array_to_matrix(res)
assert expr == rexpr
expr = 3*M + N*M.T*M + 4*k*N
res = convert_matrix_to_array(expr)
rexpr = convert_array_to_matrix(res)
assert expr == rexpr
expr = Inverse(M)*N
rexpr = convert_array_to_matrix(convert_matrix_to_array(expr))
assert expr == rexpr
expr = M**2
rexpr = convert_array_to_matrix(convert_matrix_to_array(expr))
assert expr == rexpr
expr = M*(2*N + 3*M)
res = convert_matrix_to_array(expr)
rexpr = convert_array_to_matrix(res)
assert expr == rexpr
expr = Trace(M)
result = ArrayContraction(M, (0, 1))
assert convert_matrix_to_array(expr) == result
expr = 3*Trace(M)
result = ArrayContraction(ArrayTensorProduct(3, M), (0, 1))
assert convert_matrix_to_array(expr) == result
expr = 3*Trace(Trace(M) * M)
result = ArrayContraction(ArrayTensorProduct(3, M, M), (0, 1), (2, 3))
assert convert_matrix_to_array(expr) == result
expr = 3*Trace(M)**2
result = ArrayContraction(ArrayTensorProduct(3, M, M), (0, 1), (2, 3))
assert convert_matrix_to_array(expr) == result
expr = HadamardProduct(M, N)
result = ArrayDiagonal(ArrayTensorProduct(M, N), (0, 2), (1, 3))
assert convert_matrix_to_array(expr) == result
expr = HadamardProduct(M*N, N*M)
result = ArrayDiagonal(ArrayContraction(ArrayTensorProduct(M, N, N, M), (1, 2), (5, 6)), (0, 2), (1, 3))
assert convert_matrix_to_array(expr) == result
expr = HadamardPower(M, 2)
result = ArrayDiagonal(ArrayTensorProduct(M, M), (0, 2), (1, 3))
assert convert_matrix_to_array(expr) == result
expr = HadamardPower(M*N, 2)
result = ArrayDiagonal(ArrayContraction(ArrayTensorProduct(M, N, M, N), (1, 2), (5, 6)), (0, 2), (1, 3))
assert convert_matrix_to_array(expr) == result
expr = HadamardPower(M, n)
d0 = Dummy("d0")
result = ArrayElementwiseApplyFunc(Lambda(d0, d0**n), M)
assert convert_matrix_to_array(expr).dummy_eq(result)
expr = M**2
assert isinstance(expr, MatPow)
assert convert_matrix_to_array(expr) == ArrayContraction(ArrayTensorProduct(M, M), (1, 2))
expr = a.T*b
cg = convert_matrix_to_array(expr)
assert cg == ArrayContraction(ArrayTensorProduct(a, b), (0, 2))
|
e68aec6c3d78f71d48738963b0ddab492ce2656831797148b957abebdb25066e | import random
from sympy.core.symbol import symbols
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.matrices.expressions.diagonal import DiagMatrix
from sympy.matrices.expressions.matexpr import MatrixSymbol
from sympy.matrices.expressions.special import ZeroMatrix
from sympy.tensor.array.arrayop import (permutedims, tensorcontraction, tensorproduct)
from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArray
from sympy.combinatorics import Permutation
from sympy.tensor.array.expressions.array_expressions import ZeroArray, OneArray, ArraySymbol, ArrayElement, \
PermuteDims, ArrayContraction, ArrayTensorProduct, ArrayDiagonal, \
ArrayAdd, nest_permutation, ArrayElementwiseApplyFunc, _EditArrayContraction, _ArgE
from sympy.testing.pytest import raises
i, j, k, l, m, n = symbols("i j k l m n")
M = ArraySymbol("M", (k, k))
N = ArraySymbol("N", (k, k))
P = ArraySymbol("P", (k, k))
Q = ArraySymbol("Q", (k, k))
A = ArraySymbol("A", (k, k))
B = ArraySymbol("B", (k, k))
C = ArraySymbol("C", (k, k))
D = ArraySymbol("D", (k, k))
X = ArraySymbol("X", (k, k))
Y = ArraySymbol("Y", (k, k))
a = ArraySymbol("a", (k, 1))
b = ArraySymbol("b", (k, 1))
c = ArraySymbol("c", (k, 1))
d = ArraySymbol("d", (k, 1))
def test_array_symbol_and_element():
A = ArraySymbol("A", (2,))
A0 = ArrayElement(A, (0,))
A1 = ArrayElement(A, (1,))
assert A.as_explicit() == ImmutableDenseNDimArray([A0, A1])
A2 = tensorproduct(A, A)
assert A2.shape == (2, 2)
# TODO: not yet supported:
# assert A2.as_explicit() == Array([[A[0]*A[0], A[1]*A[0]], [A[0]*A[1], A[1]*A[1]]])
A3 = tensorcontraction(A2, (0, 1))
assert A3.shape == ()
# TODO: not yet supported:
# assert A3.as_explicit() == Array([])
A = ArraySymbol("A", (2, 3, 4))
Ae = A.as_explicit()
assert Ae == ImmutableDenseNDimArray(
[[[ArrayElement(A, (i, j, k)) for k in range(4)] for j in range(3)] for i in range(2)])
p = permutedims(A, Permutation(0, 2, 1))
assert isinstance(p, PermuteDims)
def test_zero_array():
assert ZeroArray() == 0
assert ZeroArray().is_Integer
za = ZeroArray(3, 2, 4)
assert za.shape == (3, 2, 4)
za_e = za.as_explicit()
assert za_e.shape == (3, 2, 4)
m, n, k = symbols("m n k")
za = ZeroArray(m, n, k, 2)
assert za.shape == (m, n, k, 2)
raises(ValueError, lambda: za.as_explicit())
def test_one_array():
assert OneArray() == 1
assert OneArray().is_Integer
oa = OneArray(3, 2, 4)
assert oa.shape == (3, 2, 4)
oa_e = oa.as_explicit()
assert oa_e.shape == (3, 2, 4)
m, n, k = symbols("m n k")
oa = OneArray(m, n, k, 2)
assert oa.shape == (m, n, k, 2)
raises(ValueError, lambda: oa.as_explicit())
def test_arrayexpr_contraction_construction():
cg = ArrayContraction(A)
assert cg == A
cg = ArrayContraction(ArrayTensorProduct(A, B), (1, 0))
assert cg == ArrayContraction(ArrayTensorProduct(A, B), (0, 1))
cg = ArrayContraction(ArrayTensorProduct(M, N), (0, 1))
indtup = cg._get_contraction_tuples()
assert indtup == [[(0, 0), (0, 1)]]
assert cg._contraction_tuples_to_contraction_indices(cg.expr, indtup) == [(0, 1)]
cg = ArrayContraction(ArrayTensorProduct(M, N), (1, 2))
indtup = cg._get_contraction_tuples()
assert indtup == [[(0, 1), (1, 0)]]
assert cg._contraction_tuples_to_contraction_indices(cg.expr, indtup) == [(1, 2)]
cg = ArrayContraction(ArrayTensorProduct(M, M, N), (1, 4), (2, 5))
indtup = cg._get_contraction_tuples()
assert indtup == [[(0, 0), (1, 1)], [(0, 1), (2, 0)]]
assert cg._contraction_tuples_to_contraction_indices(cg.expr, indtup) == [(0, 3), (1, 4)]
# Test removal of trivial contraction:
assert ArrayContraction(a, (1,)) == a
assert ArrayContraction(
ArrayTensorProduct(a, b), (0, 2), (1,), (3,)) == ArrayContraction(
ArrayTensorProduct(a, b), (0, 2))
def test_arrayexpr_array_flatten():
# Flatten nested ArrayTensorProduct objects:
expr1 = ArrayTensorProduct(M, N)
expr2 = ArrayTensorProduct(P, Q)
expr = ArrayTensorProduct(expr1, expr2)
assert expr == ArrayTensorProduct(M, N, P, Q)
assert expr.args == (M, N, P, Q)
# Flatten mixed ArrayTensorProduct and ArrayContraction objects:
cg1 = ArrayContraction(expr1, (1, 2))
cg2 = ArrayContraction(expr2, (0, 3))
expr = ArrayTensorProduct(cg1, cg2)
assert expr == ArrayContraction(ArrayTensorProduct(M, N, P, Q), (1, 2), (4, 7))
expr = ArrayTensorProduct(M, cg1)
assert expr == ArrayContraction(ArrayTensorProduct(M, M, N), (3, 4))
# Flatten nested ArrayContraction objects:
cgnested = ArrayContraction(cg1, (0, 1))
assert cgnested == ArrayContraction(ArrayTensorProduct(M, N), (0, 3), (1, 2))
cgnested = ArrayContraction(ArrayTensorProduct(cg1, cg2), (0, 3))
assert cgnested == ArrayContraction(ArrayTensorProduct(M, N, P, Q), (0, 6), (1, 2), (4, 7))
cg3 = ArrayContraction(ArrayTensorProduct(M, N, P, Q), (1, 3), (2, 4))
cgnested = ArrayContraction(cg3, (0, 1))
assert cgnested == ArrayContraction(ArrayTensorProduct(M, N, P, Q), (0, 5), (1, 3), (2, 4))
cgnested = ArrayContraction(cg3, (0, 3), (1, 2))
assert cgnested == ArrayContraction(ArrayTensorProduct(M, N, P, Q), (0, 7), (1, 3), (2, 4), (5, 6))
cg4 = ArrayContraction(ArrayTensorProduct(M, N, P, Q), (1, 5), (3, 7))
cgnested = ArrayContraction(cg4, (0, 1))
assert cgnested == ArrayContraction(ArrayTensorProduct(M, N, P, Q), (0, 2), (1, 5), (3, 7))
cgnested = ArrayContraction(cg4, (0, 1), (2, 3))
assert cgnested == ArrayContraction(ArrayTensorProduct(M, N, P, Q), (0, 2), (1, 5), (3, 7), (4, 6))
cg = ArrayDiagonal(cg4)
assert cg == cg4
assert isinstance(cg, type(cg4))
# Flatten nested ArrayDiagonal objects:
cg1 = ArrayDiagonal(expr1, (1, 2))
cg2 = ArrayDiagonal(expr2, (0, 3))
cg3 = ArrayDiagonal(ArrayTensorProduct(M, N, P, Q), (1, 3), (2, 4))
cg4 = ArrayDiagonal(ArrayTensorProduct(M, N, P, Q), (1, 5), (3, 7))
cgnested = ArrayDiagonal(cg1, (0, 1))
assert cgnested == ArrayDiagonal(ArrayTensorProduct(M, N), (1, 2), (0, 3))
cgnested = ArrayDiagonal(cg3, (1, 2))
assert cgnested == ArrayDiagonal(ArrayTensorProduct(M, N, P, Q), (1, 3), (2, 4), (5, 6))
cgnested = ArrayDiagonal(cg4, (1, 2))
assert cgnested == ArrayDiagonal(ArrayTensorProduct(M, N, P, Q), (1, 5), (3, 7), (2, 4))
cg = ArrayAdd(M, N)
cg2 = ArrayAdd(cg, P)
assert isinstance(cg2, ArrayAdd)
assert cg2.args == (M, N, P)
assert cg2.shape == (k, k)
expr = ArrayTensorProduct(ArrayDiagonal(X, (0, 1)), ArrayDiagonal(A, (0, 1)))
assert expr == ArrayDiagonal(ArrayTensorProduct(X, A), (0, 1), (2, 3))
expr1 = ArrayDiagonal(ArrayTensorProduct(X, A), (1, 2))
expr2 = ArrayTensorProduct(expr1, a)
assert expr2 == PermuteDims(ArrayDiagonal(ArrayTensorProduct(X, A, a), (1, 2)), [0, 1, 4, 2, 3])
expr1 = ArrayContraction(ArrayTensorProduct(X, A), (1, 2))
expr2 = ArrayTensorProduct(expr1, a)
assert isinstance(expr2, ArrayContraction)
assert isinstance(expr2.expr, ArrayTensorProduct)
cg = ArrayTensorProduct(ArrayDiagonal(ArrayTensorProduct(A, X, Y), (0, 3), (1, 5)), a, b)
assert cg == PermuteDims(ArrayDiagonal(ArrayTensorProduct(A, X, Y, a, b), (0, 3), (1, 5)), [0, 1, 6, 7, 2, 3, 4, 5])
def test_arrayexpr_array_diagonal():
cg = ArrayDiagonal(M, (1, 0))
assert cg == ArrayDiagonal(M, (0, 1))
cg = ArrayDiagonal(ArrayTensorProduct(M, N, P), (4, 1), (2, 0))
assert cg == ArrayDiagonal(ArrayTensorProduct(M, N, P), (1, 4), (0, 2))
cg = ArrayDiagonal(ArrayTensorProduct(M, N), (1, 2), (3,), allow_trivial_diags=True)
assert cg == PermuteDims(ArrayDiagonal(ArrayTensorProduct(M, N), (1, 2)), [0, 2, 1])
Ax = ArraySymbol("Ax", shape=(1, 2, 3, 4, 3, 5, 6, 2, 7))
cg = ArrayDiagonal(Ax, (1, 7), (3,), (2, 4), (6,), allow_trivial_diags=True)
assert cg == PermuteDims(ArrayDiagonal(Ax, (1, 7), (2, 4)), [0, 2, 4, 5, 1, 6, 3])
cg = ArrayDiagonal(M, (0,), allow_trivial_diags=True)
assert cg == PermuteDims(M, [1, 0])
raises(ValueError, lambda: ArrayDiagonal(M, (0, 0)))
def test_arrayexpr_array_shape():
expr = ArrayTensorProduct(M, N, P, Q)
assert expr.shape == (k, k, k, k, k, k, k, k)
Z = MatrixSymbol("Z", m, n)
expr = ArrayTensorProduct(M, Z)
assert expr.shape == (k, k, m, n)
expr2 = ArrayContraction(expr, (0, 1))
assert expr2.shape == (m, n)
expr2 = ArrayDiagonal(expr, (0, 1))
assert expr2.shape == (m, n, k)
exprp = PermuteDims(expr, [2, 1, 3, 0])
assert exprp.shape == (m, k, n, k)
expr3 = ArrayTensorProduct(N, Z)
expr2 = ArrayAdd(expr, expr3)
assert expr2.shape == (k, k, m, n)
# Contraction along axes with discordant dimensions:
raises(ValueError, lambda: ArrayContraction(expr, (1, 2)))
# Also diagonal needs the same dimensions:
raises(ValueError, lambda: ArrayDiagonal(expr, (1, 2)))
# Diagonal requires at least to axes to compute the diagonal:
raises(ValueError, lambda: ArrayDiagonal(expr, (1,)))
def test_arrayexpr_permutedims_sink():
cg = PermuteDims(ArrayTensorProduct(M, N), [0, 1, 3, 2], nest_permutation=False)
sunk = nest_permutation(cg)
assert sunk == ArrayTensorProduct(M, PermuteDims(N, [1, 0]))
cg = PermuteDims(ArrayTensorProduct(M, N), [1, 0, 3, 2], nest_permutation=False)
sunk = nest_permutation(cg)
assert sunk == ArrayTensorProduct(PermuteDims(M, [1, 0]), PermuteDims(N, [1, 0]))
cg = PermuteDims(ArrayTensorProduct(M, N), [3, 2, 1, 0], nest_permutation=False)
sunk = nest_permutation(cg)
assert sunk == ArrayTensorProduct(PermuteDims(N, [1, 0]), PermuteDims(M, [1, 0]))
cg = PermuteDims(ArrayContraction(ArrayTensorProduct(M, N), (1, 2)), [1, 0], nest_permutation=False)
sunk = nest_permutation(cg)
assert sunk == ArrayContraction(PermuteDims(ArrayTensorProduct(M, N), [[0, 3]]), (1, 2))
cg = PermuteDims(ArrayTensorProduct(M, N), [1, 0, 3, 2], nest_permutation=False)
sunk = nest_permutation(cg)
assert sunk == ArrayTensorProduct(PermuteDims(M, [1, 0]), PermuteDims(N, [1, 0]))
cg = PermuteDims(ArrayContraction(ArrayTensorProduct(M, N, P), (1, 2), (3, 4)), [1, 0], nest_permutation=False)
sunk = nest_permutation(cg)
assert sunk == ArrayContraction(PermuteDims(ArrayTensorProduct(M, N, P), [[0, 5]]), (1, 2), (3, 4))
def test_arrayexpr_push_indices_up_and_down():
indices = list(range(12))
contr_diag_indices = [(0, 6), (2, 8)]
assert ArrayContraction._push_indices_down(contr_diag_indices, indices) == (1, 3, 4, 5, 7, 9, 10, 11, 12, 13, 14, 15)
assert ArrayContraction._push_indices_up(contr_diag_indices, indices) == (None, 0, None, 1, 2, 3, None, 4, None, 5, 6, 7)
assert ArrayDiagonal._push_indices_down(contr_diag_indices, indices, 10) == (1, 3, 4, 5, 7, 9, (0, 6), (2, 8), None, None, None, None)
assert ArrayDiagonal._push_indices_up(contr_diag_indices, indices, 10) == (6, 0, 7, 1, 2, 3, 6, 4, 7, 5, None, None)
contr_diag_indices = [(1, 2), (7, 8)]
assert ArrayContraction._push_indices_down(contr_diag_indices, indices) == (0, 3, 4, 5, 6, 9, 10, 11, 12, 13, 14, 15)
assert ArrayContraction._push_indices_up(contr_diag_indices, indices) == (0, None, None, 1, 2, 3, 4, None, None, 5, 6, 7)
assert ArrayDiagonal._push_indices_down(contr_diag_indices, indices, 10) == (0, 3, 4, 5, 6, 9, (1, 2), (7, 8), None, None, None, None)
assert ArrayDiagonal._push_indices_up(contr_diag_indices, indices, 10) == (0, 6, 6, 1, 2, 3, 4, 7, 7, 5, None, None)
def test_arrayexpr_split_multiple_contractions():
a = MatrixSymbol("a", k, 1)
b = MatrixSymbol("b", k, 1)
A = MatrixSymbol("A", k, k)
B = MatrixSymbol("B", k, k)
C = MatrixSymbol("C", k, k)
X = MatrixSymbol("X", k, k)
cg = ArrayContraction(ArrayTensorProduct(A.T, a, b, b.T, (A*X*b).applyfunc(cos)), (1, 2, 8), (5, 6, 9))
expected = ArrayContraction(ArrayTensorProduct(A.T, DiagMatrix(a), OneArray(1), b, b.T, (A*X*b).applyfunc(cos)), (1, 3), (2, 9), (6, 7, 10))
assert cg.split_multiple_contractions().dummy_eq(expected)
# Check no overlap of lines:
cg = ArrayContraction(ArrayTensorProduct(A, a, C, a, B), (1, 2, 4), (5, 6, 8), (3, 7))
assert cg.split_multiple_contractions() == cg
cg = ArrayContraction(ArrayTensorProduct(a, b, A), (0, 2, 4), (1, 3))
assert cg.split_multiple_contractions() == cg
def test_arrayexpr_nested_permutations():
cg = PermuteDims(PermuteDims(M, (1, 0)), (1, 0))
assert cg == M
times = 3
plist1 = [list(range(6)) for i in range(times)]
plist2 = [list(range(6)) for i in range(times)]
for i in range(times):
random.shuffle(plist1[i])
random.shuffle(plist2[i])
plist1.append([2, 5, 4, 1, 0, 3])
plist2.append([3, 5, 0, 4, 1, 2])
plist1.append([2, 5, 4, 0, 3, 1])
plist2.append([3, 0, 5, 1, 2, 4])
plist1.append([5, 4, 2, 0, 3, 1])
plist2.append([4, 5, 0, 2, 3, 1])
Me = M.subs(k, 3).as_explicit()
Ne = N.subs(k, 3).as_explicit()
Pe = P.subs(k, 3).as_explicit()
cge = tensorproduct(Me, Ne, Pe)
for permutation_array1, permutation_array2 in zip(plist1, plist2):
p1 = Permutation(permutation_array1)
p2 = Permutation(permutation_array2)
cg = PermuteDims(
PermuteDims(
ArrayTensorProduct(M, N, P),
p1),
p2
)
result = PermuteDims(
ArrayTensorProduct(M, N, P),
p2*p1
)
assert cg == result
# Check that `permutedims` behaves the same way with explicit-component arrays:
result1 = permutedims(permutedims(cge, p1), p2)
result2 = permutedims(cge, p2*p1)
assert result1 == result2
def test_arrayexpr_contraction_permutation_mix():
Me = M.subs(k, 3).as_explicit()
Ne = N.subs(k, 3).as_explicit()
cg1 = ArrayContraction(PermuteDims(ArrayTensorProduct(M, N), Permutation([0, 2, 1, 3])), (2, 3))
cg2 = ArrayContraction(ArrayTensorProduct(M, N), (1, 3))
assert cg1 == cg2
cge1 = tensorcontraction(permutedims(tensorproduct(Me, Ne), Permutation([0, 2, 1, 3])), (2, 3))
cge2 = tensorcontraction(tensorproduct(Me, Ne), (1, 3))
assert cge1 == cge2
cg1 = PermuteDims(ArrayTensorProduct(M, N), Permutation([0, 1, 3, 2]))
cg2 = ArrayTensorProduct(M, PermuteDims(N, Permutation([1, 0])))
assert cg1 == cg2
cg1 = ArrayContraction(
PermuteDims(
ArrayTensorProduct(M, N, P, Q), Permutation([0, 2, 3, 1, 4, 5, 7, 6])),
(1, 2), (3, 5)
)
cg2 = ArrayContraction(
ArrayTensorProduct(M, N, P, PermuteDims(Q, Permutation([1, 0]))),
(1, 5), (2, 3)
)
assert cg1 == cg2
cg1 = ArrayContraction(
PermuteDims(
ArrayTensorProduct(M, N, P, Q), Permutation([1, 0, 4, 6, 2, 7, 5, 3])),
(0, 1), (2, 6), (3, 7)
)
cg2 = PermuteDims(
ArrayContraction(
ArrayTensorProduct(M, P, Q, N),
(0, 1), (2, 3), (4, 7)),
[1, 0]
)
assert cg1 == cg2
cg1 = ArrayContraction(
PermuteDims(
ArrayTensorProduct(M, N, P, Q), Permutation([1, 0, 4, 6, 7, 2, 5, 3])),
(0, 1), (2, 6), (3, 7)
)
cg2 = PermuteDims(
ArrayContraction(
ArrayTensorProduct(PermuteDims(M, [1, 0]), N, P, Q),
(0, 1), (3, 6), (4, 5)
),
Permutation([1, 0])
)
assert cg1 == cg2
def test_arrayexpr_permute_tensor_product():
cg1 = PermuteDims(ArrayTensorProduct(M, N, P, Q), Permutation([2, 3, 1, 0, 5, 4, 6, 7]))
cg2 = ArrayTensorProduct(N, PermuteDims(M, [1, 0]),
PermuteDims(P, [1, 0]), Q)
assert cg1 == cg2
# TODO: reverse operation starting with `PermuteDims` and getting down to `bb`...
cg1 = PermuteDims(ArrayTensorProduct(M, N, P, Q), Permutation([2, 3, 4, 5, 0, 1, 6, 7]))
cg2 = ArrayTensorProduct(N, P, M, Q)
assert cg1 == cg2
cg1 = PermuteDims(ArrayTensorProduct(M, N, P, Q), Permutation([2, 3, 4, 6, 5, 7, 0, 1]))
assert cg1.expr == ArrayTensorProduct(N, P, Q, M)
assert cg1.permutation == Permutation([0, 1, 2, 4, 3, 5, 6, 7])
cg1 = ArrayContraction(
PermuteDims(
ArrayTensorProduct(N, Q, Q, M),
[2, 1, 5, 4, 0, 3, 6, 7]),
[1, 2, 6])
cg2 = PermuteDims(ArrayContraction(ArrayTensorProduct(Q, Q, N, M), (3, 5, 6)), [0, 2, 3, 1, 4])
assert cg1 == cg2
cg1 = ArrayContraction(
ArrayContraction(
ArrayContraction(
ArrayContraction(
PermuteDims(
ArrayTensorProduct(N, Q, Q, M),
[2, 1, 5, 4, 0, 3, 6, 7]),
[1, 2, 6]),
[1, 3, 4]),
[1]),
[0])
cg2 = ArrayContraction(ArrayTensorProduct(M, N, Q, Q), (0, 3, 5), (1, 4, 7), (2,), (6,))
assert cg1 == cg2
def test_arrayexpr_normalize_diagonal_permutedims():
tp = ArrayTensorProduct(M, Q, N, P)
expr = ArrayDiagonal(
PermuteDims(tp, [0, 1, 2, 4, 7, 6, 3, 5]), (2, 4, 5), (6, 7),
(0, 3))
result = ArrayDiagonal(tp, (2, 6, 7), (3, 5), (0, 4))
assert expr == result
tp = ArrayTensorProduct(M, N, P, Q)
expr = ArrayDiagonal(PermuteDims(tp, [0, 5, 2, 4, 1, 6, 3, 7]), (1, 2, 6), (3, 4))
result = ArrayDiagonal(ArrayTensorProduct(M, P, N, Q), (3, 4, 5), (1, 2))
assert expr == result
def test_arrayexpr_normalize_diagonal_contraction():
tp = ArrayTensorProduct(M, N, P, Q)
expr = ArrayContraction(ArrayDiagonal(tp, (1, 3, 4)), (0, 3))
result = ArrayDiagonal(ArrayContraction(ArrayTensorProduct(M, N, P, Q), (0, 6)), (0, 2, 3))
assert expr == result
expr = ArrayContraction(ArrayDiagonal(tp, (0, 1, 2, 3, 7)), (1, 2, 3))
result = ArrayContraction(ArrayTensorProduct(M, N, P, Q), (0, 1, 2, 3, 5, 6, 7))
assert expr == result
expr = ArrayContraction(ArrayDiagonal(tp, (0, 2, 6, 7)), (1, 2, 3))
result = ArrayDiagonal(ArrayContraction(tp, (3, 4, 5)), (0, 2, 3, 4))
assert expr == result
td = ArrayDiagonal(ArrayTensorProduct(M, N, P, Q), (0, 3))
expr = ArrayContraction(td, (2, 1), (0, 4, 6, 5, 3))
result = ArrayContraction(ArrayTensorProduct(M, N, P, Q), (0, 1, 3, 5, 6, 7), (2, 4))
assert expr == result
def test_arrayexpr_array_wrong_permutation_size():
cg = ArrayTensorProduct(M, N)
raises(ValueError, lambda: PermuteDims(cg, [1, 0]))
raises(ValueError, lambda: PermuteDims(cg, [1, 0, 2, 3, 5, 4]))
def test_arrayexpr_nested_array_elementwise_add():
cg = ArrayContraction(ArrayAdd(
ArrayTensorProduct(M, N),
ArrayTensorProduct(N, M)
), (1, 2))
result = ArrayAdd(
ArrayContraction(ArrayTensorProduct(M, N), (1, 2)),
ArrayContraction(ArrayTensorProduct(N, M), (1, 2))
)
assert cg == result
cg = ArrayDiagonal(ArrayAdd(
ArrayTensorProduct(M, N),
ArrayTensorProduct(N, M)
), (1, 2))
result = ArrayAdd(
ArrayDiagonal(ArrayTensorProduct(M, N), (1, 2)),
ArrayDiagonal(ArrayTensorProduct(N, M), (1, 2))
)
assert cg == result
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 ArrayTensorProduct(M, N, za1) == ZeroArray(k, k, k, k, k, l, m, n)
assert ArrayTensorProduct(M, N, zm1) == ZeroArray(k, k, k, k, m, n)
assert ArrayContraction(za1, (3,)) == ZeroArray(k, l, m)
assert ArrayContraction(zm1, (1,)) == ZeroArray(m)
assert ArrayContraction(za2, (1, 2)) == ZeroArray(k, n)
assert ArrayContraction(zm2, (0, 1)) == 0
assert ArrayDiagonal(za2, (1, 2)) == ZeroArray(k, n, m)
assert ArrayDiagonal(zm2, (0, 1)) == ZeroArray(m)
assert PermuteDims(za1, [2, 1, 3, 0]) == ZeroArray(m, l, n, k)
assert PermuteDims(zm1, [1, 0]) == ZeroArray(n, m)
assert ArrayAdd(za1) == za1
assert ArrayAdd(zm1) == ZeroArray(m, n)
tp1 = ArrayTensorProduct(MatrixSymbol("A", k, l), MatrixSymbol("B", m, n))
assert ArrayAdd(tp1, za1) == tp1
tp2 = ArrayTensorProduct(MatrixSymbol("C", k, l), MatrixSymbol("D", m, n))
assert ArrayAdd(tp1, za1, tp2) == ArrayAdd(tp1, tp2)
assert ArrayAdd(M, zm3) == M
assert ArrayAdd(M, N, zm3) == ArrayAdd(M, N)
def test_arrayexpr_array_expr_applyfunc():
A = ArraySymbol("A", (3, k, 2))
aaf = ArrayElementwiseApplyFunc(sin, A)
assert aaf.shape == (3, k, 2)
def test_edit_array_contraction():
cg = ArrayContraction(ArrayTensorProduct(A, B, C, D), (1, 2, 5))
ecg = _EditArrayContraction(cg)
assert ecg.to_array_contraction() == cg
ecg.args_with_ind[1], ecg.args_with_ind[2] = ecg.args_with_ind[2], ecg.args_with_ind[1]
assert ecg.to_array_contraction() == ArrayContraction(ArrayTensorProduct(A, C, B, D), (1, 3, 4))
ci = ecg.get_new_contraction_index()
new_arg = _ArgE(X)
new_arg.indices = [ci, ci]
ecg.args_with_ind.insert(2, new_arg)
assert ecg.to_array_contraction() == ArrayContraction(ArrayTensorProduct(A, C, X, B, D), (1, 3, 6), (4, 5))
assert ecg.get_contraction_indices() == [[1, 3, 6], [4, 5]]
assert [[tuple(j) for j in i] for i in ecg.get_contraction_indices_to_ind_rel_pos()] == [[(0, 1), (1, 1), (3, 0)], [(2, 0), (2, 1)]]
assert [list(i) for i in ecg.get_mapping_for_index(0)] == [[0, 1], [1, 1], [3, 0]]
assert [list(i) for i in ecg.get_mapping_for_index(1)] == [[2, 0], [2, 1]]
raises(ValueError, lambda: ecg.get_mapping_for_index(2))
ecg.args_with_ind.pop(1)
assert ecg.to_array_contraction() == ArrayContraction(ArrayTensorProduct(A, X, B, D), (1, 4), (2, 3))
ecg.args_with_ind[0].indices[1] = ecg.args_with_ind[1].indices[0]
ecg.args_with_ind[1].indices[1] = ecg.args_with_ind[2].indices[0]
assert ecg.to_array_contraction() == ArrayContraction(ArrayTensorProduct(A, X, B, D), (1, 2), (3, 4))
ecg.insert_after(ecg.args_with_ind[1], _ArgE(C))
assert ecg.to_array_contraction() == ArrayContraction(ArrayTensorProduct(A, X, C, B, D), (1, 2), (3, 6))
def test_array_expressions_no_normalization():
tp = ArrayTensorProduct(M, N, P)
# ArrayTensorProduct:
expr = ArrayTensorProduct(tp, N, normalize=False)
assert str(expr) == "ArrayTensorProduct(ArrayTensorProduct(M, N, P), N)"
expr = ArrayTensorProduct(ArrayContraction(M, (0, 1)), N, normalize=False)
assert str(expr) == "ArrayTensorProduct(ArrayContraction(M, (0, 1)), N)"
expr = ArrayTensorProduct(ArrayDiagonal(M, (0, 1)), N, normalize=False)
assert str(expr) == "ArrayTensorProduct(ArrayDiagonal(M, (0, 1)), N)"
expr = ArrayTensorProduct(PermuteDims(M, [1, 0]), N, normalize=False)
assert str(expr) == "ArrayTensorProduct(PermuteDims(M, (0 1)), N)"
# ArrayContraction:
expr = ArrayContraction(ArrayContraction(tp, (0, 2)), (0, 1), normalize=False)
assert isinstance(expr, ArrayContraction)
assert isinstance(expr.expr, ArrayContraction)
assert str(expr) == "ArrayContraction(ArrayContraction(ArrayTensorProduct(M, N, P), (0, 2)), (0, 1))"
expr = ArrayContraction(ArrayDiagonal(tp, (0, 1)), (0, 1), normalize=False)
assert str(expr) == "ArrayContraction(ArrayDiagonal(ArrayTensorProduct(M, N, P), (0, 1)), (0, 1))"
expr = ArrayContraction(PermuteDims(M, [1, 0]), (0, 1), normalize=False)
assert str(expr) == "ArrayContraction(PermuteDims(M, (0 1)), (0, 1))"
# ArrayDiagonal:
expr = ArrayDiagonal(ArrayDiagonal(tp, (0, 2)), (0, 1), normalize=False)
assert str(expr) == "ArrayDiagonal(ArrayDiagonal(ArrayTensorProduct(M, N, P), (0, 2)), (0, 1))"
expr = ArrayDiagonal(ArrayContraction(tp, (0, 1)), (0, 1), normalize=False)
assert str(expr) == "ArrayDiagonal(ArrayContraction(ArrayTensorProduct(M, N, P), (0, 1)), (0, 1))"
expr = ArrayDiagonal(PermuteDims(M, [1, 0]), (0, 1), normalize=False)
assert str(expr) == "ArrayDiagonal(PermuteDims(M, (0 1)), (0, 1))"
# ArrayAdd:
expr = ArrayAdd(ArrayAdd(M, N), P, normalize=False)
assert str(expr) == "ArrayAdd(ArrayAdd(M, N), P)"
expr = ArrayAdd(M, ZeroArray(k, k), N, normalize=False)
assert str(expr) == "ArrayAdd(M, ZeroArray(k, k), N)"
# PermuteDims:
expr = PermuteDims(PermuteDims(M, [1, 0]), [1, 0], normalize=False)
assert str(expr) == "PermuteDims(PermuteDims(M, (0 1)), (0 1))"
|
ad66399a622e34fce5d98ca5ba3acf9fe8389a31ae5937afc9ce1e9eb45760b5 | from sympy.core.symbol import symbols
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.matrices.expressions.matexpr import MatrixSymbol
from sympy.matrices.expressions.special import Identity
from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction
from sympy.tensor.array.expressions.array_expressions import ArraySymbol, ArrayTensorProduct, \
PermuteDims, ArrayDiagonal, ArrayElementwiseApplyFunc, ArrayContraction
from sympy.tensor.array.expressions.arrayexpr_derivatives import array_derive
k = symbols("k")
I = Identity(k)
X = MatrixSymbol("X", k, k)
x = MatrixSymbol("x", k, 1)
A = MatrixSymbol("A", k, k)
B = MatrixSymbol("B", k, k)
C = MatrixSymbol("C", k, k)
D = MatrixSymbol("D", k, k)
A1 = ArraySymbol("A", (3, 2, k))
def test_arrayexpr_derivatives1():
res = array_derive(X, X)
assert res == PermuteDims(ArrayTensorProduct(I, I), [0, 2, 1, 3])
cg = ArrayTensorProduct(A, X, B)
res = array_derive(cg, X)
assert res == PermuteDims(
ArrayTensorProduct(I, A, I, B),
[0, 4, 2, 3, 1, 5, 6, 7])
cg = ArrayContraction(X, (0, 1))
res = array_derive(cg, X)
assert res == ArrayContraction(ArrayTensorProduct(I, I), (1, 3))
cg = ArrayDiagonal(X, (0, 1))
res = array_derive(cg, X)
assert res == ArrayDiagonal(ArrayTensorProduct(I, I), (1, 3))
cg = ElementwiseApplyFunction(sin, X)
res = array_derive(cg, X)
assert res.dummy_eq(ArrayDiagonal(
ArrayTensorProduct(
ElementwiseApplyFunction(cos, X),
I,
I
), (0, 3), (1, 5)))
cg = ArrayElementwiseApplyFunc(sin, X)
res = array_derive(cg, X)
assert res.dummy_eq(ArrayDiagonal(
ArrayTensorProduct(
I,
I,
ArrayElementwiseApplyFunc(cos, X)
), (1, 4), (3, 5)))
res = array_derive(A1, A1)
assert res == PermuteDims(
ArrayTensorProduct(Identity(3), Identity(2), Identity(k)),
[0, 2, 4, 1, 3, 5]
)
cg = ArrayElementwiseApplyFunc(sin, A1)
res = array_derive(cg, A1)
assert res.dummy_eq(ArrayDiagonal(
ArrayTensorProduct(
Identity(3), Identity(2), Identity(k),
ArrayElementwiseApplyFunc(cos, A1)
), (1, 6), (3, 7), (5, 8)
))
|
c2bd4d0d7a916c96c9a7c405ec5b419b835c02ec33ee6afa79b7353879812186 | from typing import Dict as tDict, Any
from sympy.multipledispatch import dispatch
from sympy.multipledispatch.conflict import AmbiguityWarning
from sympy.testing.pytest import raises, warns
from functools import partial
test_namespace = dict() # type: tDict[str, Any]
orig_dispatch = dispatch
dispatch = partial(dispatch, namespace=test_namespace)
def test_singledispatch():
@dispatch(int)
def f(x): # noqa:F811
return x + 1
@dispatch(int)
def g(x): # noqa:F811
return x + 2
@dispatch(float) # noqa:F811
def f(x): # noqa:F811
return x - 1
assert f(1) == 2
assert g(1) == 3
assert f(1.0) == 0
assert raises(NotImplementedError, lambda: f('hello'))
def test_multipledispatch():
@dispatch(int, int)
def f(x, y): # noqa:F811
return x + y
@dispatch(float, float) # noqa:F811
def f(x, y): # noqa:F811
return x - y
assert f(1, 2) == 3
assert f(1.0, 2.0) == -1.0
class A: pass
class B: pass
class C(A): pass
class D(C): pass
class E(C): pass
def test_inheritance():
@dispatch(A)
def f(x): # noqa:F811
return 'a'
@dispatch(B) # noqa:F811
def f(x): # noqa:F811
return 'b'
assert f(A()) == 'a'
assert f(B()) == 'b'
assert f(C()) == 'a'
def test_inheritance_and_multiple_dispatch():
@dispatch(A, A)
def f(x, y): # noqa:F811
return type(x), type(y)
@dispatch(A, B) # noqa:F811
def f(x, y): # noqa:F811
return 0
assert f(A(), A()) == (A, A)
assert f(A(), C()) == (A, C)
assert f(A(), B()) == 0
assert f(C(), B()) == 0
assert raises(NotImplementedError, lambda: f(B(), B()))
def test_competing_solutions():
@dispatch(A)
def h(x): # noqa:F811
return 1
@dispatch(C) # noqa:F811
def h(x): # noqa:F811
return 2
assert h(D()) == 2
def test_competing_multiple():
@dispatch(A, B)
def h(x, y): # noqa:F811
return 1
@dispatch(C, B) # noqa:F811
def h(x, y): # noqa:F811
return 2
assert h(D(), B()) == 2
def test_competing_ambiguous():
test_namespace = dict()
dispatch = partial(orig_dispatch, namespace=test_namespace)
@dispatch(A, C)
def f(x, y): # noqa:F811
return 2
with warns(AmbiguityWarning):
@dispatch(C, A) # noqa:F811
def f(x, y): # noqa:F811
return 2
assert f(A(), C()) == f(C(), A()) == 2
# assert raises(Warning, lambda : f(C(), C()))
def test_caching_correct_behavior():
@dispatch(A)
def f(x): # noqa:F811
return 1
assert f(C()) == 1
@dispatch(C)
def f(x): # noqa:F811
return 2
assert f(C()) == 2
def test_union_types():
@dispatch((A, C))
def f(x): # noqa:F811
return 1
assert f(A()) == 1
assert f(C()) == 1
def test_namespaces():
ns1 = dict()
ns2 = dict()
def foo(x):
return 1
foo1 = orig_dispatch(int, namespace=ns1)(foo)
def foo(x):
return 2
foo2 = orig_dispatch(int, namespace=ns2)(foo)
assert foo1(0) == 1
assert foo2(0) == 2
"""
Fails
def test_dispatch_on_dispatch():
@dispatch(A)
@dispatch(C)
def q(x): # noqa:F811
return 1
assert q(A()) == 1
assert q(C()) == 1
"""
def test_methods():
class Foo:
@dispatch(float)
def f(self, x): # noqa:F811
return x - 1
@dispatch(int) # noqa:F811
def f(self, x): # noqa:F811
return x + 1
@dispatch(int)
def g(self, x): # noqa:F811
return x + 3
foo = Foo()
assert foo.f(1) == 2
assert foo.f(1.0) == 0.0
assert foo.g(1) == 4
def test_methods_multiple_dispatch():
class Foo:
@dispatch(A, A)
def f(x, y): # noqa:F811
return 1
@dispatch(A, C) # noqa:F811
def f(x, y): # noqa:F811
return 2
foo = Foo()
assert foo.f(A(), A()) == 1
assert foo.f(A(), C()) == 2
assert foo.f(C(), C()) == 2
|
d2f3454dbbbdf988527e3c184ec66c3ff6781ccf16a4bd75fb1ba32c14b59188 | from sympy.assumptions.cnf import EncodedCNF
def pycosat_satisfiable(expr, all_models=False):
import pycosat
if not isinstance(expr, EncodedCNF):
exprs = EncodedCNF()
exprs.add_prop(expr)
expr = exprs
# Return UNSAT when False (encoded as 0) is present in the CNF
if {0} in expr.data:
if all_models:
return (f for f in [False])
return False
if not all_models:
r = pycosat.solve(expr.data)
result = (r != "UNSAT")
if not result:
return result
return {expr.symbols[abs(lit) - 1]: lit > 0 for lit in r}
else:
r = pycosat.itersolve(expr.data)
result = (r != "UNSAT")
if not result:
return result
# Make solutions SymPy compatible by creating a generator
def _gen(results):
satisfiable = False
try:
while True:
sol = next(results)
yield {expr.symbols[abs(lit) - 1]: lit > 0 for lit in sol}
satisfiable = True
except StopIteration:
if not satisfiable:
yield False
return _gen(r)
|
185ddb9b0e3f21b978e2911116b5d106edafb95494d19142eb5b7ae36950e038 | """Implementation of DPLL algorithm
Features:
- Clause learning
- Watch literal scheme
- VSIDS heuristic
References:
- https://en.wikipedia.org/wiki/DPLL_algorithm
"""
from collections import defaultdict
from heapq import heappush, heappop
from sympy.core.sorting import ordered
from sympy.assumptions.cnf import EncodedCNF
def dpll_satisfiable(expr, all_models=False):
"""
Check satisfiability of a propositional sentence.
It returns a model rather than True when it succeeds.
Returns a generator of all models if all_models is True.
Examples
========
>>> from sympy.abc import A, B
>>> from sympy.logic.algorithms.dpll2 import dpll_satisfiable
>>> dpll_satisfiable(A & ~B)
{A: True, B: False}
>>> dpll_satisfiable(A & ~A)
False
"""
if not isinstance(expr, EncodedCNF):
exprs = EncodedCNF()
exprs.add_prop(expr)
expr = exprs
# Return UNSAT when False (encoded as 0) is present in the CNF
if {0} in expr.data:
if all_models:
return (f for f in [False])
return False
solver = SATSolver(expr.data, expr.variables, set(), expr.symbols)
models = solver._find_model()
if all_models:
return _all_models(models)
try:
return next(models)
except StopIteration:
return False
# Uncomment to confirm the solution is valid (hitting set for the clauses)
#else:
#for cls in clauses_int_repr:
#assert solver.var_settings.intersection(cls)
def _all_models(models):
satisfiable = False
try:
while True:
yield next(models)
satisfiable = True
except StopIteration:
if not satisfiable:
yield False
class SATSolver:
"""
Class for representing a SAT solver capable of
finding a model to a boolean theory in conjunctive
normal form.
"""
def __init__(self, clauses, variables, var_settings, symbols=None,
heuristic='vsids', clause_learning='none', INTERVAL=500):
self.var_settings = var_settings
self.heuristic = heuristic
self.is_unsatisfied = False
self._unit_prop_queue = []
self.update_functions = []
self.INTERVAL = INTERVAL
if symbols is None:
self.symbols = list(ordered(variables))
else:
self.symbols = symbols
self._initialize_variables(variables)
self._initialize_clauses(clauses)
if 'vsids' == heuristic:
self._vsids_init()
self.heur_calculate = self._vsids_calculate
self.heur_lit_assigned = self._vsids_lit_assigned
self.heur_lit_unset = self._vsids_lit_unset
self.heur_clause_added = self._vsids_clause_added
# Note: Uncomment this if/when clause learning is enabled
#self.update_functions.append(self._vsids_decay)
else:
raise NotImplementedError
if 'simple' == clause_learning:
self.add_learned_clause = self._simple_add_learned_clause
self.compute_conflict = self.simple_compute_conflict
self.update_functions.append(self.simple_clean_clauses)
elif 'none' == clause_learning:
self.add_learned_clause = lambda x: None
self.compute_conflict = lambda: None
else:
raise NotImplementedError
# Create the base level
self.levels = [Level(0)]
self._current_level.varsettings = var_settings
# Keep stats
self.num_decisions = 0
self.num_learned_clauses = 0
self.original_num_clauses = len(self.clauses)
def _initialize_variables(self, variables):
"""Set up the variable data structures needed."""
self.sentinels = defaultdict(set)
self.occurrence_count = defaultdict(int)
self.variable_set = [False] * (len(variables) + 1)
def _initialize_clauses(self, clauses):
"""Set up the clause data structures needed.
For each clause, the following changes are made:
- Unit clauses are queued for propagation right away.
- Non-unit clauses have their first and last literals set as sentinels.
- The number of clauses a literal appears in is computed.
"""
self.clauses = []
for cls in clauses:
self.clauses.append(list(cls))
for i in range(len(self.clauses)):
# Handle the unit clauses
if 1 == len(self.clauses[i]):
self._unit_prop_queue.append(self.clauses[i][0])
continue
self.sentinels[self.clauses[i][0]].add(i)
self.sentinels[self.clauses[i][-1]].add(i)
for lit in self.clauses[i]:
self.occurrence_count[lit] += 1
def _find_model(self):
"""
Main DPLL loop. Returns a generator of models.
Variables are chosen successively, and assigned to be either
True or False. If a solution is not found with this setting,
the opposite is chosen and the search continues. The solver
halts when every variable has a setting.
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
... {3, -2}], {1, 2, 3}, set())
>>> list(l._find_model())
[{1: True, 2: False, 3: False}, {1: True, 2: True, 3: True}]
>>> from sympy.abc import A, B, C
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
... {3, -2}], {1, 2, 3}, set(), [A, B, C])
>>> list(l._find_model())
[{A: True, B: False, C: False}, {A: True, B: True, C: True}]
"""
# We use this variable to keep track of if we should flip a
# variable setting in successive rounds
flip_var = False
# Check if unit prop says the theory is unsat right off the bat
self._simplify()
if self.is_unsatisfied:
return
# While the theory still has clauses remaining
while True:
# Perform cleanup / fixup at regular intervals
if self.num_decisions % self.INTERVAL == 0:
for func in self.update_functions:
func()
if flip_var:
# We have just backtracked and we are trying to opposite literal
flip_var = False
lit = self._current_level.decision
else:
# Pick a literal to set
lit = self.heur_calculate()
self.num_decisions += 1
# Stopping condition for a satisfying theory
if 0 == lit:
yield {self.symbols[abs(lit) - 1]:
lit > 0 for lit in self.var_settings}
while self._current_level.flipped:
self._undo()
if len(self.levels) == 1:
return
flip_lit = -self._current_level.decision
self._undo()
self.levels.append(Level(flip_lit, flipped=True))
flip_var = True
continue
# Start the new decision level
self.levels.append(Level(lit))
# Assign the literal, updating the clauses it satisfies
self._assign_literal(lit)
# _simplify the theory
self._simplify()
# Check if we've made the theory unsat
if self.is_unsatisfied:
self.is_unsatisfied = False
# We unroll all of the decisions until we can flip a literal
while self._current_level.flipped:
self._undo()
# If we've unrolled all the way, the theory is unsat
if 1 == len(self.levels):
return
# Detect and add a learned clause
self.add_learned_clause(self.compute_conflict())
# Try the opposite setting of the most recent decision
flip_lit = -self._current_level.decision
self._undo()
self.levels.append(Level(flip_lit, flipped=True))
flip_var = True
########################
# Helper Methods #
########################
@property
def _current_level(self):
"""The current decision level data structure
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([{1}, {2}], {1, 2}, set())
>>> next(l._find_model())
{1: True, 2: True}
>>> l._current_level.decision
0
>>> l._current_level.flipped
False
>>> l._current_level.var_settings
{1, 2}
"""
return self.levels[-1]
def _clause_sat(self, cls):
"""Check if a clause is satisfied by the current variable setting.
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([{1}, {-1}], {1}, set())
>>> try:
... next(l._find_model())
... except StopIteration:
... pass
>>> l._clause_sat(0)
False
>>> l._clause_sat(1)
True
"""
for lit in self.clauses[cls]:
if lit in self.var_settings:
return True
return False
def _is_sentinel(self, lit, cls):
"""Check if a literal is a sentinel of a given clause.
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
... {3, -2}], {1, 2, 3}, set())
>>> next(l._find_model())
{1: True, 2: False, 3: False}
>>> l._is_sentinel(2, 3)
True
>>> l._is_sentinel(-3, 1)
False
"""
return cls in self.sentinels[lit]
def _assign_literal(self, lit):
"""Make a literal assignment.
The literal assignment must be recorded as part of the current
decision level. Additionally, if the literal is marked as a
sentinel of any clause, then a new sentinel must be chosen. If
this is not possible, then unit propagation is triggered and
another literal is added to the queue to be set in the future.
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
... {3, -2}], {1, 2, 3}, set())
>>> next(l._find_model())
{1: True, 2: False, 3: False}
>>> l.var_settings
{-3, -2, 1}
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
... {3, -2}], {1, 2, 3}, set())
>>> l._assign_literal(-1)
>>> try:
... next(l._find_model())
... except StopIteration:
... pass
>>> l.var_settings
{-1}
"""
self.var_settings.add(lit)
self._current_level.var_settings.add(lit)
self.variable_set[abs(lit)] = True
self.heur_lit_assigned(lit)
sentinel_list = list(self.sentinels[-lit])
for cls in sentinel_list:
if not self._clause_sat(cls):
other_sentinel = None
for newlit in self.clauses[cls]:
if newlit != -lit:
if self._is_sentinel(newlit, cls):
other_sentinel = newlit
elif not self.variable_set[abs(newlit)]:
self.sentinels[-lit].remove(cls)
self.sentinels[newlit].add(cls)
other_sentinel = None
break
# Check if no sentinel update exists
if other_sentinel:
self._unit_prop_queue.append(other_sentinel)
def _undo(self):
"""
_undo the changes of the most recent decision level.
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
... {3, -2}], {1, 2, 3}, set())
>>> next(l._find_model())
{1: True, 2: False, 3: False}
>>> level = l._current_level
>>> level.decision, level.var_settings, level.flipped
(-3, {-3, -2}, False)
>>> l._undo()
>>> level = l._current_level
>>> level.decision, level.var_settings, level.flipped
(0, {1}, False)
"""
# Undo the variable settings
for lit in self._current_level.var_settings:
self.var_settings.remove(lit)
self.heur_lit_unset(lit)
self.variable_set[abs(lit)] = False
# Pop the level off the stack
self.levels.pop()
#########################
# Propagation #
#########################
"""
Propagation methods should attempt to soundly simplify the boolean
theory, and return True if any simplification occurred and False
otherwise.
"""
def _simplify(self):
"""Iterate over the various forms of propagation to simplify the theory.
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
... {3, -2}], {1, 2, 3}, set())
>>> l.variable_set
[False, False, False, False]
>>> l.sentinels
{-3: {0, 2}, -2: {3, 4}, 2: {0, 3}, 3: {2, 4}}
>>> l._simplify()
>>> l.variable_set
[False, True, False, False]
>>> l.sentinels
{-3: {0, 2}, -2: {3, 4}, -1: set(), 2: {0, 3},
...3: {2, 4}}
"""
changed = True
while changed:
changed = False
changed |= self._unit_prop()
changed |= self._pure_literal()
def _unit_prop(self):
"""Perform unit propagation on the current theory."""
result = len(self._unit_prop_queue) > 0
while self._unit_prop_queue:
next_lit = self._unit_prop_queue.pop()
if -next_lit in self.var_settings:
self.is_unsatisfied = True
self._unit_prop_queue = []
return False
else:
self._assign_literal(next_lit)
return result
def _pure_literal(self):
"""Look for pure literals and assign them when found."""
return False
#########################
# Heuristics #
#########################
def _vsids_init(self):
"""Initialize the data structures needed for the VSIDS heuristic."""
self.lit_heap = []
self.lit_scores = {}
for var in range(1, len(self.variable_set)):
self.lit_scores[var] = float(-self.occurrence_count[var])
self.lit_scores[-var] = float(-self.occurrence_count[-var])
heappush(self.lit_heap, (self.lit_scores[var], var))
heappush(self.lit_heap, (self.lit_scores[-var], -var))
def _vsids_decay(self):
"""Decay the VSIDS scores for every literal.
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
... {3, -2}], {1, 2, 3}, set())
>>> l.lit_scores
{-3: -2.0, -2: -2.0, -1: 0.0, 1: 0.0, 2: -2.0, 3: -2.0}
>>> l._vsids_decay()
>>> l.lit_scores
{-3: -1.0, -2: -1.0, -1: 0.0, 1: 0.0, 2: -1.0, 3: -1.0}
"""
# We divide every literal score by 2 for a decay factor
# Note: This doesn't change the heap property
for lit in self.lit_scores.keys():
self.lit_scores[lit] /= 2.0
def _vsids_calculate(self):
"""
VSIDS Heuristic Calculation
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
... {3, -2}], {1, 2, 3}, set())
>>> l.lit_heap
[(-2.0, -3), (-2.0, 2), (-2.0, -2), (0.0, 1), (-2.0, 3), (0.0, -1)]
>>> l._vsids_calculate()
-3
>>> l.lit_heap
[(-2.0, -2), (-2.0, 2), (0.0, -1), (0.0, 1), (-2.0, 3)]
"""
if len(self.lit_heap) == 0:
return 0
# Clean out the front of the heap as long the variables are set
while self.variable_set[abs(self.lit_heap[0][1])]:
heappop(self.lit_heap)
if len(self.lit_heap) == 0:
return 0
return heappop(self.lit_heap)[1]
def _vsids_lit_assigned(self, lit):
"""Handle the assignment of a literal for the VSIDS heuristic."""
pass
def _vsids_lit_unset(self, lit):
"""Handle the unsetting of a literal for the VSIDS heuristic.
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
... {3, -2}], {1, 2, 3}, set())
>>> l.lit_heap
[(-2.0, -3), (-2.0, 2), (-2.0, -2), (0.0, 1), (-2.0, 3), (0.0, -1)]
>>> l._vsids_lit_unset(2)
>>> l.lit_heap
[(-2.0, -3), (-2.0, -2), (-2.0, -2), (-2.0, 2), (-2.0, 3), (0.0, -1),
...(-2.0, 2), (0.0, 1)]
"""
var = abs(lit)
heappush(self.lit_heap, (self.lit_scores[var], var))
heappush(self.lit_heap, (self.lit_scores[-var], -var))
def _vsids_clause_added(self, cls):
"""Handle the addition of a new clause for the VSIDS heuristic.
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
... {3, -2}], {1, 2, 3}, set())
>>> l.num_learned_clauses
0
>>> l.lit_scores
{-3: -2.0, -2: -2.0, -1: 0.0, 1: 0.0, 2: -2.0, 3: -2.0}
>>> l._vsids_clause_added({2, -3})
>>> l.num_learned_clauses
1
>>> l.lit_scores
{-3: -1.0, -2: -2.0, -1: 0.0, 1: 0.0, 2: -1.0, 3: -2.0}
"""
self.num_learned_clauses += 1
for lit in cls:
self.lit_scores[lit] += 1
########################
# Clause Learning #
########################
def _simple_add_learned_clause(self, cls):
"""Add a new clause to the theory.
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
... {3, -2}], {1, 2, 3}, set())
>>> l.num_learned_clauses
0
>>> l.clauses
[[2, -3], [1], [3, -3], [2, -2], [3, -2]]
>>> l.sentinels
{-3: {0, 2}, -2: {3, 4}, 2: {0, 3}, 3: {2, 4}}
>>> l._simple_add_learned_clause([3])
>>> l.clauses
[[2, -3], [1], [3, -3], [2, -2], [3, -2], [3]]
>>> l.sentinels
{-3: {0, 2}, -2: {3, 4}, 2: {0, 3}, 3: {2, 4, 5}}
"""
cls_num = len(self.clauses)
self.clauses.append(cls)
for lit in cls:
self.occurrence_count[lit] += 1
self.sentinels[cls[0]].add(cls_num)
self.sentinels[cls[-1]].add(cls_num)
self.heur_clause_added(cls)
def _simple_compute_conflict(self):
""" Build a clause representing the fact that at least one decision made
so far is wrong.
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
... {3, -2}], {1, 2, 3}, set())
>>> next(l._find_model())
{1: True, 2: False, 3: False}
>>> l._simple_compute_conflict()
[3]
"""
return [-(level.decision) for level in self.levels[1:]]
def _simple_clean_clauses(self):
"""Clean up learned clauses."""
pass
class Level:
"""
Represents a single level in the DPLL algorithm, and contains
enough information for a sound backtracking procedure.
"""
def __init__(self, decision, flipped=False):
self.decision = decision
self.var_settings = set()
self.flipped = flipped
|
cea8990e6d680f9b0dc45aa6ff41de9fa3637c82c80e9e6e46010e69dd6f6172 | """Implementation of DPLL algorithm
Further improvements: eliminate calls to pl_true, implement branching rules,
efficient unit propagation.
References:
- https://en.wikipedia.org/wiki/DPLL_algorithm
- https://www.researchgate.net/publication/242384772_Implementations_of_the_DPLL_Algorithm
"""
from sympy.core.sorting import default_sort_key
from sympy.logic.boolalg import Or, Not, conjuncts, disjuncts, to_cnf, \
to_int_repr, _find_predicates
from sympy.assumptions.cnf import CNF
from sympy.logic.inference import pl_true, literal_symbol
def dpll_satisfiable(expr):
"""
Check satisfiability of a propositional sentence.
It returns a model rather than True when it succeeds
>>> from sympy.abc import A, B
>>> from sympy.logic.algorithms.dpll import dpll_satisfiable
>>> dpll_satisfiable(A & ~B)
{A: True, B: False}
>>> dpll_satisfiable(A & ~A)
False
"""
if not isinstance(expr, CNF):
clauses = conjuncts(to_cnf(expr))
else:
clauses = expr.clauses
if False in clauses:
return False
symbols = sorted(_find_predicates(expr), key=default_sort_key)
symbols_int_repr = set(range(1, len(symbols) + 1))
clauses_int_repr = to_int_repr(clauses, symbols)
result = dpll_int_repr(clauses_int_repr, symbols_int_repr, {})
if not result:
return result
output = {}
for key in result:
output.update({symbols[key - 1]: result[key]})
return output
def dpll(clauses, symbols, model):
"""
Compute satisfiability in a partial model.
Clauses is an array of conjuncts.
>>> from sympy.abc import A, B, D
>>> from sympy.logic.algorithms.dpll import dpll
>>> dpll([A, B, D], [A, B], {D: False})
False
"""
# compute DP kernel
P, value = find_unit_clause(clauses, model)
while P:
model.update({P: value})
symbols.remove(P)
if not value:
P = ~P
clauses = unit_propagate(clauses, P)
P, value = find_unit_clause(clauses, model)
P, value = find_pure_symbol(symbols, clauses)
while P:
model.update({P: value})
symbols.remove(P)
if not value:
P = ~P
clauses = unit_propagate(clauses, P)
P, value = find_pure_symbol(symbols, clauses)
# end DP kernel
unknown_clauses = []
for c in clauses:
val = pl_true(c, model)
if val is False:
return False
if val is not True:
unknown_clauses.append(c)
if not unknown_clauses:
return model
if not clauses:
return model
P = symbols.pop()
model_copy = model.copy()
model.update({P: True})
model_copy.update({P: False})
symbols_copy = symbols[:]
return (dpll(unit_propagate(unknown_clauses, P), symbols, model) or
dpll(unit_propagate(unknown_clauses, Not(P)), symbols_copy, model_copy))
def dpll_int_repr(clauses, symbols, model):
"""
Compute satisfiability in a partial model.
Arguments are expected to be in integer representation
>>> from sympy.logic.algorithms.dpll import dpll_int_repr
>>> dpll_int_repr([{1}, {2}, {3}], {1, 2}, {3: False})
False
"""
# compute DP kernel
P, value = find_unit_clause_int_repr(clauses, model)
while P:
model.update({P: value})
symbols.remove(P)
if not value:
P = -P
clauses = unit_propagate_int_repr(clauses, P)
P, value = find_unit_clause_int_repr(clauses, model)
P, value = find_pure_symbol_int_repr(symbols, clauses)
while P:
model.update({P: value})
symbols.remove(P)
if not value:
P = -P
clauses = unit_propagate_int_repr(clauses, P)
P, value = find_pure_symbol_int_repr(symbols, clauses)
# end DP kernel
unknown_clauses = []
for c in clauses:
val = pl_true_int_repr(c, model)
if val is False:
return False
if val is not True:
unknown_clauses.append(c)
if not unknown_clauses:
return model
P = symbols.pop()
model_copy = model.copy()
model.update({P: True})
model_copy.update({P: False})
symbols_copy = symbols.copy()
return (dpll_int_repr(unit_propagate_int_repr(unknown_clauses, P), symbols, model) or
dpll_int_repr(unit_propagate_int_repr(unknown_clauses, -P), symbols_copy, model_copy))
### helper methods for DPLL
def pl_true_int_repr(clause, model={}):
"""
Lightweight version of pl_true.
Argument clause represents the set of args of an Or clause. This is used
inside dpll_int_repr, it is not meant to be used directly.
>>> from sympy.logic.algorithms.dpll import pl_true_int_repr
>>> pl_true_int_repr({1, 2}, {1: False})
>>> pl_true_int_repr({1, 2}, {1: False, 2: False})
False
"""
result = False
for lit in clause:
if lit < 0:
p = model.get(-lit)
if p is not None:
p = not p
else:
p = model.get(lit)
if p is True:
return True
elif p is None:
result = None
return result
def unit_propagate(clauses, symbol):
"""
Returns an equivalent set of clauses
If a set of clauses contains the unit clause l, the other clauses are
simplified by the application of the two following rules:
1. every clause containing l is removed
2. in every clause that contains ~l this literal is deleted
Arguments are expected to be in CNF.
>>> from sympy.abc import A, B, D
>>> from sympy.logic.algorithms.dpll import unit_propagate
>>> unit_propagate([A | B, D | ~B, B], B)
[D, B]
"""
output = []
for c in clauses:
if c.func != Or:
output.append(c)
continue
for arg in c.args:
if arg == ~symbol:
output.append(Or(*[x for x in c.args if x != ~symbol]))
break
if arg == symbol:
break
else:
output.append(c)
return output
def unit_propagate_int_repr(clauses, s):
"""
Same as unit_propagate, but arguments are expected to be in integer
representation
>>> from sympy.logic.algorithms.dpll import unit_propagate_int_repr
>>> unit_propagate_int_repr([{1, 2}, {3, -2}, {2}], 2)
[{3}]
"""
negated = {-s}
return [clause - negated for clause in clauses if s not in clause]
def find_pure_symbol(symbols, unknown_clauses):
"""
Find a symbol and its value if it appears only as a positive literal
(or only as a negative) in clauses.
>>> from sympy.abc import A, B, D
>>> from sympy.logic.algorithms.dpll import find_pure_symbol
>>> find_pure_symbol([A, B, D], [A|~B,~B|~D,D|A])
(A, True)
"""
for sym in symbols:
found_pos, found_neg = False, False
for c in unknown_clauses:
if not found_pos and sym in disjuncts(c):
found_pos = True
if not found_neg and Not(sym) in disjuncts(c):
found_neg = True
if found_pos != found_neg:
return sym, found_pos
return None, None
def find_pure_symbol_int_repr(symbols, unknown_clauses):
"""
Same as find_pure_symbol, but arguments are expected
to be in integer representation
>>> from sympy.logic.algorithms.dpll import find_pure_symbol_int_repr
>>> find_pure_symbol_int_repr({1,2,3},
... [{1, -2}, {-2, -3}, {3, 1}])
(1, True)
"""
all_symbols = set().union(*unknown_clauses)
found_pos = all_symbols.intersection(symbols)
found_neg = all_symbols.intersection([-s for s in symbols])
for p in found_pos:
if -p not in found_neg:
return p, True
for p in found_neg:
if -p not in found_pos:
return -p, False
return None, None
def find_unit_clause(clauses, model):
"""
A unit clause has only 1 variable that is not bound in the model.
>>> from sympy.abc import A, B, D
>>> from sympy.logic.algorithms.dpll import find_unit_clause
>>> find_unit_clause([A | B | D, B | ~D, A | ~B], {A:True})
(B, False)
"""
for clause in clauses:
num_not_in_model = 0
for literal in disjuncts(clause):
sym = literal_symbol(literal)
if sym not in model:
num_not_in_model += 1
P, value = sym, not isinstance(literal, Not)
if num_not_in_model == 1:
return P, value
return None, None
def find_unit_clause_int_repr(clauses, model):
"""
Same as find_unit_clause, but arguments are expected to be in
integer representation.
>>> from sympy.logic.algorithms.dpll import find_unit_clause_int_repr
>>> find_unit_clause_int_repr([{1, 2, 3},
... {2, -3}, {1, -2}], {1: True})
(2, False)
"""
bound = set(model) | {-sym for sym in model}
for clause in clauses:
unbound = clause - bound
if len(unbound) == 1:
p = unbound.pop()
if p < 0:
return -p, False
else:
return p, True
return None, None
|
b8835cbe42071966096fcbbe4343a09d281a1df55477db586056c1015362012a | from sympy.assumptions.cnf import EncodedCNF
def minisat22_satisfiable(expr, all_models=False, minimal=False):
if not isinstance(expr, EncodedCNF):
exprs = EncodedCNF()
exprs.add_prop(expr)
expr = exprs
from pysat.solvers import Minisat22
# Return UNSAT when False (encoded as 0) is present in the CNF
if {0} in expr.data:
if all_models:
return (f for f in [False])
return False
r = Minisat22(expr.data)
if minimal:
r.set_phases([-(i+1) for i in range(r.nof_vars())])
if not r.solve():
return False
if not all_models:
return {expr.symbols[abs(lit) - 1]: lit > 0 for lit in r.get_model()}
else:
# Make solutions SymPy compatible by creating a generator
def _gen(results):
satisfiable = False
while results.solve():
sol = results.get_model()
yield {expr.symbols[abs(lit) - 1]: lit > 0 for lit in sol}
if minimal:
results.add_clause([-i for i in sol if i>0])
else:
results.add_clause([-i for i in sol])
satisfiable = True
if not satisfiable:
yield False
raise StopIteration
return _gen(r)
|
6ef6df4d35b175c0be7328b52d49111646dca2f7efff7255dce7e0f53a875989 | from sympy.assumptions.ask import Q
from sympy.assumptions.refine import refine
from sympy.core.numbers import oo
from sympy.core.relational import Equality, Eq, Ne
from sympy.core.singleton import S
from sympy.core.symbol import (Dummy, symbols)
from sympy.functions import Piecewise
from sympy.functions.elementary.trigonometric import cos, sin
from sympy.sets.sets import (Interval, Union)
from sympy.simplify.simplify import simplify
from sympy.logic.boolalg import (
And, Boolean, Equivalent, ITE, Implies, Nand, Nor, Not, Or,
POSform, SOPform, Xor, Xnor, conjuncts, disjuncts,
distribute_or_over_and, distribute_and_over_or,
eliminate_implications, is_nnf, is_cnf, is_dnf, simplify_logic,
to_nnf, to_cnf, to_dnf, to_int_repr, bool_map, true, false,
BooleanAtom, is_literal, term_to_integer,
truth_table, as_Boolean, to_anf, is_anf, distribute_xor_over_and,
anf_coeffs, ANFform, bool_minterm, bool_maxterm, bool_monomial,
_check_pair, _convert_to_varsSOP, _convert_to_varsPOS, Exclusive,)
from sympy.assumptions.cnf import CNF
from sympy.testing.pytest import raises, XFAIL, slow
from itertools import combinations, permutations, product
A, B, C, D = symbols('A:D')
a, b, c, d, e, w, x, y, z = symbols('a:e w:z')
def test_overloading():
"""Test that |, & are overloaded as expected"""
assert A & B == And(A, B)
assert A | B == Or(A, B)
assert (A & B) | C == Or(And(A, B), C)
assert A >> B == Implies(A, B)
assert A << B == Implies(B, A)
assert ~A == Not(A)
assert A ^ B == Xor(A, B)
def test_And():
assert And() is true
assert And(A) == A
assert And(True) is true
assert And(False) is false
assert And(True, True) is true
assert And(True, False) is false
assert And(False, False) is false
assert And(True, A) == A
assert And(False, A) is false
assert And(True, True, True) is true
assert And(True, True, A) == A
assert And(True, False, A) is false
assert And(1, A) == A
raises(TypeError, lambda: And(2, A))
raises(TypeError, lambda: And(A < 2, A))
assert And(A < 1, A >= 1) is false
e = A > 1
assert And(e, e.canonical) == e.canonical
g, l, ge, le = A > B, B < A, A >= B, B <= A
assert And(g, l, ge, le) == And(ge, g)
assert {And(*i) for i in permutations((l,g,le,ge))} == {And(ge, g)}
assert And(And(Eq(a, 0), Eq(b, 0)), And(Ne(a, 0), Eq(c, 0))) is false
def test_Or():
assert Or() is false
assert Or(A) == A
assert Or(True) is true
assert Or(False) is false
assert Or(True, True) is true
assert Or(True, False) is true
assert Or(False, False) is false
assert Or(True, A) is true
assert Or(False, A) == A
assert Or(True, False, False) is true
assert Or(True, False, A) is true
assert Or(False, False, A) == A
assert Or(1, A) is true
raises(TypeError, lambda: Or(2, A))
raises(TypeError, lambda: Or(A < 2, A))
assert Or(A < 1, A >= 1) is true
e = A > 1
assert Or(e, e.canonical) == e
g, l, ge, le = A > B, B < A, A >= B, B <= A
assert Or(g, l, ge, le) == Or(g, ge)
def test_Xor():
assert Xor() is false
assert Xor(A) == A
assert Xor(A, A) is false
assert Xor(True, A, A) is true
assert Xor(A, A, A, A, A) == A
assert Xor(True, False, False, A, B) == ~Xor(A, B)
assert Xor(True) is true
assert Xor(False) is false
assert Xor(True, True) is false
assert Xor(True, False) is true
assert Xor(False, False) is false
assert Xor(True, A) == ~A
assert Xor(False, A) == A
assert Xor(True, False, False) is true
assert Xor(True, False, A) == ~A
assert Xor(False, False, A) == A
assert isinstance(Xor(A, B), Xor)
assert Xor(A, B, Xor(C, D)) == Xor(A, B, C, D)
assert Xor(A, B, Xor(B, C)) == Xor(A, C)
assert Xor(A < 1, A >= 1, B) == Xor(0, 1, B) == Xor(1, 0, B)
e = A > 1
assert Xor(e, e.canonical) == Xor(0, 0) == Xor(1, 1)
def test_rewrite_as_And():
expr = x ^ y
assert expr.rewrite(And) == (x | y) & (~x | ~y)
def test_rewrite_as_Or():
expr = x ^ y
assert expr.rewrite(Or) == (x & ~y) | (y & ~x)
def test_rewrite_as_Nand():
expr = (y & z) | (z & ~w)
assert expr.rewrite(Nand) == ~(~(y & z) & ~(z & ~w))
def test_rewrite_as_Nor():
expr = z & (y | ~w)
assert expr.rewrite(Nor) == ~(~z | ~(y | ~w))
def test_Not():
raises(TypeError, lambda: Not(True, False))
assert Not(True) is false
assert Not(False) is true
assert Not(0) is true
assert Not(1) is false
assert Not(2) is false
def test_Nand():
assert Nand() is false
assert Nand(A) == ~A
assert Nand(True) is false
assert Nand(False) is true
assert Nand(True, True) is false
assert Nand(True, False) is true
assert Nand(False, False) is true
assert Nand(True, A) == ~A
assert Nand(False, A) is true
assert Nand(True, True, True) is false
assert Nand(True, True, A) == ~A
assert Nand(True, False, A) is true
def test_Nor():
assert Nor() is true
assert Nor(A) == ~A
assert Nor(True) is false
assert Nor(False) is true
assert Nor(True, True) is false
assert Nor(True, False) is false
assert Nor(False, False) is true
assert Nor(True, A) is false
assert Nor(False, A) == ~A
assert Nor(True, True, True) is false
assert Nor(True, True, A) is false
assert Nor(True, False, A) is false
def test_Xnor():
assert Xnor() is true
assert Xnor(A) == ~A
assert Xnor(A, A) is true
assert Xnor(True, A, A) is false
assert Xnor(A, A, A, A, A) == ~A
assert Xnor(True) is false
assert Xnor(False) is true
assert Xnor(True, True) is true
assert Xnor(True, False) is false
assert Xnor(False, False) is true
assert Xnor(True, A) == A
assert Xnor(False, A) == ~A
assert Xnor(True, False, False) is false
assert Xnor(True, False, A) == A
assert Xnor(False, False, A) == ~A
def test_Implies():
raises(ValueError, lambda: Implies(A, B, C))
assert Implies(True, True) is true
assert Implies(True, False) is false
assert Implies(False, True) is true
assert Implies(False, False) is true
assert Implies(0, A) is true
assert Implies(1, 1) is true
assert Implies(1, 0) is false
assert A >> B == B << A
assert (A < 1) >> (A >= 1) == (A >= 1)
assert (A < 1) >> (S.One > A) is true
assert A >> A is true
def test_Equivalent():
assert Equivalent(A, B) == Equivalent(B, A) == Equivalent(A, B, A)
assert Equivalent() is true
assert Equivalent(A, A) == Equivalent(A) is true
assert Equivalent(True, True) == Equivalent(False, False) is true
assert Equivalent(True, False) == Equivalent(False, True) is false
assert Equivalent(A, True) == A
assert Equivalent(A, False) == Not(A)
assert Equivalent(A, B, True) == A & B
assert Equivalent(A, B, False) == ~A & ~B
assert Equivalent(1, A) == A
assert Equivalent(0, A) == Not(A)
assert Equivalent(A, Equivalent(B, C)) != Equivalent(Equivalent(A, B), C)
assert Equivalent(A < 1, A >= 1) is false
assert Equivalent(A < 1, A >= 1, 0) is false
assert Equivalent(A < 1, A >= 1, 1) is false
assert Equivalent(A < 1, S.One > A) == Equivalent(1, 1) == Equivalent(0, 0)
assert Equivalent(Equality(A, B), Equality(B, A)) is true
def test_Exclusive():
assert Exclusive(False, False, False) is true
assert Exclusive(True, False, False) is true
assert Exclusive(True, True, False) is false
assert Exclusive(True, True, True) is false
def test_equals():
assert Not(Or(A, B)).equals(And(Not(A), Not(B))) is True
assert Equivalent(A, B).equals((A >> B) & (B >> A)) is True
assert ((A | ~B) & (~A | B)).equals((~A & ~B) | (A & B)) is True
assert (A >> B).equals(~A >> ~B) is False
assert (A >> (B >> A)).equals(A >> (C >> A)) is False
raises(NotImplementedError, lambda: (A & B).equals(A > B))
def test_simplification_boolalg():
"""
Test working of simplification methods.
"""
set1 = [[0, 0, 1], [0, 1, 1], [1, 0, 0], [1, 1, 0]]
set2 = [[0, 0, 0], [0, 1, 0], [1, 0, 1], [1, 1, 1]]
assert SOPform([x, y, z], set1) == Or(And(Not(x), z), And(Not(z), x))
assert Not(SOPform([x, y, z], set2)) == \
Not(Or(And(Not(x), Not(z)), And(x, z)))
assert POSform([x, y, z], set1 + set2) is true
assert SOPform([x, y, z], set1 + set2) is true
assert SOPform([Dummy(), Dummy(), Dummy()], set1 + set2) is true
minterms = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 1], [1, 0, 1, 1],
[1, 1, 1, 1]]
dontcares = [[0, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 1]]
assert (
SOPform([w, x, y, z], minterms, dontcares) ==
Or(And(y, z), And(Not(w), Not(x))))
assert POSform([w, x, y, z], minterms, dontcares) == And(Or(Not(w), y), z)
minterms = [1, 3, 7, 11, 15]
dontcares = [0, 2, 5]
assert (
SOPform([w, x, y, z], minterms, dontcares) ==
Or(And(y, z), And(Not(w), Not(x))))
assert POSform([w, x, y, z], minterms, dontcares) == And(Or(Not(w), y), z)
minterms = [1, [0, 0, 1, 1], 7, [1, 0, 1, 1],
[1, 1, 1, 1]]
dontcares = [0, [0, 0, 1, 0], 5]
assert (
SOPform([w, x, y, z], minterms, dontcares) ==
Or(And(y, z), And(Not(w), Not(x))))
assert POSform([w, x, y, z], minterms, dontcares) == And(Or(Not(w), y), z)
minterms = [1, {y: 1, z: 1}]
dontcares = [0, [0, 0, 1, 0], 5]
assert (
SOPform([w, x, y, z], minterms, dontcares) ==
Or(And(y, z), And(Not(w), Not(x))))
assert POSform([w, x, y, z], minterms, dontcares) == And(Or(Not(w), y), z)
minterms = [{y: 1, z: 1}, 1]
dontcares = [[0, 0, 0, 0]]
minterms = [[0, 0, 0]]
raises(ValueError, lambda: SOPform([w, x, y, z], minterms))
raises(ValueError, lambda: POSform([w, x, y, z], minterms))
raises(TypeError, lambda: POSform([w, x, y, z], ["abcdefg"]))
# test simplification
ans = And(A, Or(B, C))
assert simplify_logic(A & (B | C)) == ans
assert simplify_logic((A & B) | (A & C)) == ans
assert simplify_logic(Implies(A, B)) == Or(Not(A), B)
assert simplify_logic(Equivalent(A, B)) == \
Or(And(A, B), And(Not(A), Not(B)))
assert simplify_logic(And(Equality(A, 2), C)) == And(Equality(A, 2), C)
assert simplify_logic(And(Equality(A, 2), A)) is S.false
assert simplify_logic(And(Equality(A, 2), A)) == And(Equality(A, 2), A)
assert simplify_logic(And(Equality(A, B), C)) == And(Equality(A, B), C)
assert simplify_logic(Or(And(Equality(A, 3), B), And(Equality(A, 3), C))) \
== And(Equality(A, 3), Or(B, C))
b = (~x & ~y & ~z) | (~x & ~y & z)
e = And(A, b)
assert simplify_logic(e) == A & ~x & ~y
raises(ValueError, lambda: simplify_logic(A & (B | C), form='blabla'))
assert simplify(Or(x <= y, And(x < y, z))) == (x <= y)
assert simplify(Or(x <= y, And(y > x, z))) == (x <= y)
assert simplify(Or(x >= y, And(y < x, z))) == (x >= y)
# Check that expressions with nine variables or more are not simplified
# (without the force-flag)
a, b, c, d, e, f, g, h, j = symbols('a b c d e f g h j')
expr = a & b & c & d & e & f & g & h & j | \
a & b & c & d & e & f & g & h & ~j
# This expression can be simplified to get rid of the j variables
assert simplify_logic(expr) == expr
# check input
ans = SOPform([x, y], [[1, 0]])
assert SOPform([x, y], [[1, 0]]) == ans
assert POSform([x, y], [[1, 0]]) == ans
raises(ValueError, lambda: SOPform([x], [[1]], [[1]]))
assert SOPform([x], [[1]], [[0]]) is true
assert SOPform([x], [[0]], [[1]]) is true
assert SOPform([x], [], []) is false
raises(ValueError, lambda: POSform([x], [[1]], [[1]]))
assert POSform([x], [[1]], [[0]]) is true
assert POSform([x], [[0]], [[1]]) is true
assert POSform([x], [], []) is false
# check working of simplify
assert simplify((A & B) | (A & C)) == And(A, Or(B, C))
assert simplify(And(x, Not(x))) == False
assert simplify(Or(x, Not(x))) == True
assert simplify(And(Eq(x, 0), Eq(x, y))) == And(Eq(x, 0), Eq(y, 0))
assert And(Eq(x - 1, 0), Eq(x, y)).simplify() == And(Eq(x, 1), Eq(y, 1))
assert And(Ne(x - 1, 0), Ne(x, y)).simplify() == And(Ne(x, 1), Ne(x, y))
assert And(Eq(x - 1, 0), Ne(x, y)).simplify() == And(Eq(x, 1), Ne(y, 1))
assert And(Eq(x - 1, 0), Eq(x, z + y), Eq(y + x, 0)).simplify(
) == And(Eq(x, 1), Eq(y, -1), Eq(z, 2))
assert And(Eq(x - 1, 0), Eq(x + 2, 3)).simplify() == Eq(x, 1)
assert And(Ne(x - 1, 0), Ne(x + 2, 3)).simplify() == Ne(x, 1)
assert And(Eq(x - 1, 0), Eq(x + 2, 2)).simplify() == False
assert And(Ne(x - 1, 0), Ne(x + 2, 2)).simplify(
) == And(Ne(x, 1), Ne(x, 0))
def test_bool_map():
"""
Test working of bool_map function.
"""
minterms = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 1], [1, 0, 1, 1],
[1, 1, 1, 1]]
assert bool_map(Not(Not(a)), a) == (a, {a: a})
assert bool_map(SOPform([w, x, y, z], minterms),
POSform([w, x, y, z], minterms)) == \
(And(Or(Not(w), y), Or(Not(x), y), z), {x: x, w: w, z: z, y: y})
assert bool_map(SOPform([x, z, y], [[1, 0, 1]]),
SOPform([a, b, c], [[1, 0, 1]])) != False
function1 = SOPform([x, z, y], [[1, 0, 1], [0, 0, 1]])
function2 = SOPform([a, b, c], [[1, 0, 1], [1, 0, 0]])
assert bool_map(function1, function2) == \
(function1, {y: a, z: b})
assert bool_map(Xor(x, y), ~Xor(x, y)) == False
assert bool_map(And(x, y), Or(x, y)) is None
assert bool_map(And(x, y), And(x, y, z)) is None
# issue 16179
assert bool_map(Xor(x, y, z), ~Xor(x, y, z)) == False
assert bool_map(Xor(a, x, y, z), ~Xor(a, x, y, z)) == False
def test_bool_symbol():
"""Test that mixing symbols with boolean values
works as expected"""
assert And(A, True) == A
assert And(A, True, True) == A
assert And(A, False) is false
assert And(A, True, False) is false
assert Or(A, True) is true
assert Or(A, False) == A
def test_is_boolean():
assert isinstance(True, Boolean) is False
assert isinstance(true, Boolean) is True
assert 1 == True
assert 1 != true
assert (1 == true) is False
assert 0 == False
assert 0 != false
assert (0 == false) is False
assert true.is_Boolean is True
assert (A & B).is_Boolean
assert (A | B).is_Boolean
assert (~A).is_Boolean
assert (A ^ B).is_Boolean
assert A.is_Boolean != isinstance(A, Boolean)
assert isinstance(A, Boolean)
def test_subs():
assert (A & B).subs(A, True) == B
assert (A & B).subs(A, False) is false
assert (A & B).subs(B, True) == A
assert (A & B).subs(B, False) is false
assert (A & B).subs({A: True, B: True}) is true
assert (A | B).subs(A, True) is true
assert (A | B).subs(A, False) == B
assert (A | B).subs(B, True) is true
assert (A | B).subs(B, False) == A
assert (A | B).subs({A: True, B: True}) is true
"""
we test for axioms of boolean algebra
see https://en.wikipedia.org/wiki/Boolean_algebra_(structure)
"""
def test_commutative():
"""Test for commutativity of And and Or"""
A, B = map(Boolean, symbols('A,B'))
assert A & B == B & A
assert A | B == B | A
def test_and_associativity():
"""Test for associativity of And"""
assert (A & B) & C == A & (B & C)
def test_or_assicativity():
assert ((A | B) | C) == (A | (B | C))
def test_double_negation():
a = Boolean()
assert ~(~a) == a
# test methods
def test_eliminate_implications():
assert eliminate_implications(Implies(A, B, evaluate=False)) == (~A) | B
assert eliminate_implications(
A >> (C >> Not(B))) == Or(Or(Not(B), Not(C)), Not(A))
assert eliminate_implications(Equivalent(A, B, C, D)) == \
(~A | B) & (~B | C) & (~C | D) & (~D | A)
def test_conjuncts():
assert conjuncts(A & B & C) == {A, B, C}
assert conjuncts((A | B) & C) == {A | B, C}
assert conjuncts(A) == {A}
assert conjuncts(True) == {True}
assert conjuncts(False) == {False}
def test_disjuncts():
assert disjuncts(A | B | C) == {A, B, C}
assert disjuncts((A | B) & C) == {(A | B) & C}
assert disjuncts(A) == {A}
assert disjuncts(True) == {True}
assert disjuncts(False) == {False}
def test_distribute():
assert distribute_and_over_or(Or(And(A, B), C)) == And(Or(A, C), Or(B, C))
assert distribute_or_over_and(And(A, Or(B, C))) == Or(And(A, B), And(A, C))
assert distribute_xor_over_and(And(A, Xor(B, C))) == Xor(And(A, B), And(A, C))
def test_to_anf():
x, y, z = symbols('x,y,z')
assert to_anf(And(x, y)) == And(x, y)
assert to_anf(Or(x, y)) == Xor(x, y, And(x, y))
assert to_anf(Or(Implies(x, y), And(x, y), y)) == \
Xor(x, True, x & y, remove_true=False)
assert to_anf(Or(Nand(x, y), Nor(x, y), Xnor(x, y), Implies(x, y))) == True
assert to_anf(Or(x, Not(y), Nor(x,z), And(x, y), Nand(y, z))) == \
Xor(True, And(y, z), And(x, y, z), remove_true=False)
assert to_anf(Xor(x, y)) == Xor(x, y)
assert to_anf(Not(x)) == Xor(x, True, remove_true=False)
assert to_anf(Nand(x, y)) == Xor(True, And(x, y), remove_true=False)
assert to_anf(Nor(x, y)) == Xor(x, y, True, And(x, y), remove_true=False)
assert to_anf(Implies(x, y)) == Xor(x, True, And(x, y), remove_true=False)
assert to_anf(Equivalent(x, y)) == Xor(x, y, True, remove_true=False)
assert to_anf(Nand(x | y, x >> y), deep=False) == \
Xor(True, And(Or(x, y), Implies(x, y)), remove_true=False)
assert to_anf(Nor(x ^ y, x & y), deep=False) == \
Xor(True, Or(Xor(x, y), And(x, y)), remove_true=False)
def test_to_nnf():
assert to_nnf(true) is true
assert to_nnf(false) is false
assert to_nnf(A) == A
assert to_nnf(A | ~A | B) is true
assert to_nnf(A & ~A & B) is false
assert to_nnf(A >> B) == ~A | B
assert to_nnf(Equivalent(A, B, C)) == (~A | B) & (~B | C) & (~C | A)
assert to_nnf(A ^ B ^ C) == \
(A | B | C) & (~A | ~B | C) & (A | ~B | ~C) & (~A | B | ~C)
assert to_nnf(ITE(A, B, C)) == (~A | B) & (A | C)
assert to_nnf(Not(A | B | C)) == ~A & ~B & ~C
assert to_nnf(Not(A & B & C)) == ~A | ~B | ~C
assert to_nnf(Not(A >> B)) == A & ~B
assert to_nnf(Not(Equivalent(A, B, C))) == And(Or(A, B, C), Or(~A, ~B, ~C))
assert to_nnf(Not(A ^ B ^ C)) == \
(~A | B | C) & (A | ~B | C) & (A | B | ~C) & (~A | ~B | ~C)
assert to_nnf(Not(ITE(A, B, C))) == (~A | ~B) & (A | ~C)
assert to_nnf((A >> B) ^ (B >> A)) == (A & ~B) | (~A & B)
assert to_nnf((A >> B) ^ (B >> A), False) == \
(~A | ~B | A | B) & ((A & ~B) | (~A & B))
assert ITE(A, 1, 0).to_nnf() == A
assert ITE(A, 0, 1).to_nnf() == ~A
# although ITE can hold non-Boolean, it will complain if
# an attempt is made to convert the ITE to Boolean nnf
raises(TypeError, lambda: ITE(A < 1, [1], B).to_nnf())
def test_to_cnf():
assert to_cnf(~(B | C)) == And(Not(B), Not(C))
assert to_cnf((A & B) | C) == And(Or(A, C), Or(B, C))
assert to_cnf(A >> B) == (~A) | B
assert to_cnf(A >> (B & C)) == (~A | B) & (~A | C)
assert to_cnf(A & (B | C) | ~A & (B | C), True) == B | C
assert to_cnf(A & B) == And(A, B)
assert to_cnf(Equivalent(A, B)) == And(Or(A, Not(B)), Or(B, Not(A)))
assert to_cnf(Equivalent(A, B & C)) == \
(~A | B) & (~A | C) & (~B | ~C | A)
assert to_cnf(Equivalent(A, B | C), True) == \
And(Or(Not(B), A), Or(Not(C), A), Or(B, C, Not(A)))
assert to_cnf(A + 1) == A + 1
def test_issue_18904():
x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15 = symbols('x1:16')
eq = (( x1 & x2 & x3 & x4 & x5 & x6 & x7 & x8 & x9 ) |
( x1 & x2 & x3 & x4 & x5 & x6 & x7 & x10 & x9 ) |
( x1 & x11 & x3 & x12 & x5 & x13 & x14 & x15 & x9 ))
assert is_cnf(to_cnf(eq))
raises(ValueError, lambda: to_cnf(eq, simplify=True))
for f, t in zip((And, Or), (to_cnf, to_dnf)):
eq = f(x1, x2, x3, x4, x5, x6, x7, x8, x9)
raises(ValueError, lambda: to_cnf(eq, simplify=True))
assert t(eq, simplify=True, force=True) == eq
def test_issue_9949():
assert is_cnf(to_cnf((b > -5) | (a > 2) & (a < 4)))
def test_to_CNF():
assert CNF.CNF_to_cnf(CNF.to_CNF(~(B | C))) == to_cnf(~(B | C))
assert CNF.CNF_to_cnf(CNF.to_CNF((A & B) | C)) == to_cnf((A & B) | C)
assert CNF.CNF_to_cnf(CNF.to_CNF(A >> B)) == to_cnf(A >> B)
assert CNF.CNF_to_cnf(CNF.to_CNF(A >> (B & C))) == to_cnf(A >> (B & C))
assert CNF.CNF_to_cnf(CNF.to_CNF(A & (B | C) | ~A & (B | C))) == to_cnf(A & (B | C) | ~A & (B | C))
assert CNF.CNF_to_cnf(CNF.to_CNF(A & B)) == to_cnf(A & B)
def test_to_dnf():
assert to_dnf(~(B | C)) == And(Not(B), Not(C))
assert to_dnf(A & (B | C)) == Or(And(A, B), And(A, C))
assert to_dnf(A >> B) == (~A) | B
assert to_dnf(A >> (B & C)) == (~A) | (B & C)
assert to_dnf(A | B) == A | B
assert to_dnf(Equivalent(A, B), True) == \
Or(And(A, B), And(Not(A), Not(B)))
assert to_dnf(Equivalent(A, B & C), True) == \
Or(And(A, B, C), And(Not(A), Not(B)), And(Not(A), Not(C)))
assert to_dnf(A + 1) == A + 1
def test_to_int_repr():
x, y, z = map(Boolean, symbols('x,y,z'))
def sorted_recursive(arg):
try:
return sorted(sorted_recursive(x) for x in arg)
except TypeError: # arg is not a sequence
return arg
assert sorted_recursive(to_int_repr([x | y, z | x], [x, y, z])) == \
sorted_recursive([[1, 2], [1, 3]])
assert sorted_recursive(to_int_repr([x | y, z | ~x], [x, y, z])) == \
sorted_recursive([[1, 2], [3, -1]])
def test_is_anf():
x, y = symbols('x,y')
assert is_anf(true) is True
assert is_anf(false) is True
assert is_anf(x) is True
assert is_anf(And(x, y)) is True
assert is_anf(Xor(x, y, And(x, y))) is True
assert is_anf(Xor(x, y, Or(x, y))) is False
assert is_anf(Xor(Not(x), y)) is False
def test_is_nnf():
assert is_nnf(true) is True
assert is_nnf(A) is True
assert is_nnf(~A) is True
assert is_nnf(A & B) is True
assert is_nnf((A & B) | (~A & A) | (~B & B) | (~A & ~B), False) is True
assert is_nnf((A | B) & (~A | ~B)) is True
assert is_nnf(Not(Or(A, B))) is False
assert is_nnf(A ^ B) is False
assert is_nnf((A & B) | (~A & A) | (~B & B) | (~A & ~B), True) is False
def test_is_cnf():
assert is_cnf(x) is True
assert is_cnf(x | y | z) is True
assert is_cnf(x & y & z) is True
assert is_cnf((x | y) & z) is True
assert is_cnf((x & y) | z) is False
assert is_cnf(~(x & y) | z) is False
def test_is_dnf():
assert is_dnf(x) is True
assert is_dnf(x | y | z) is True
assert is_dnf(x & y & z) is True
assert is_dnf((x & y) | z) is True
assert is_dnf((x | y) & z) is False
assert is_dnf(~(x | y) & z) is False
def test_ITE():
A, B, C = symbols('A:C')
assert ITE(True, False, True) is false
assert ITE(True, True, False) is true
assert ITE(False, True, False) is false
assert ITE(False, False, True) is true
assert isinstance(ITE(A, B, C), ITE)
A = True
assert ITE(A, B, C) == B
A = False
assert ITE(A, B, C) == C
B = True
assert ITE(And(A, B), B, C) == C
assert ITE(Or(A, False), And(B, True), False) is false
assert ITE(x, A, B) == Not(x)
assert ITE(x, B, A) == x
assert ITE(1, x, y) == x
assert ITE(0, x, y) == y
raises(TypeError, lambda: ITE(2, x, y))
raises(TypeError, lambda: ITE(1, [], y))
raises(TypeError, lambda: ITE(1, (), y))
raises(TypeError, lambda: ITE(1, y, []))
assert ITE(1, 1, 1) is S.true
assert isinstance(ITE(1, 1, 1, evaluate=False), ITE)
raises(TypeError, lambda: ITE(x > 1, y, x))
assert ITE(Eq(x, True), y, x) == ITE(x, y, x)
assert ITE(Eq(x, False), y, x) == ITE(~x, y, x)
assert ITE(Ne(x, True), y, x) == ITE(~x, y, x)
assert ITE(Ne(x, False), y, x) == ITE(x, y, x)
assert ITE(Eq(S. true, x), y, x) == ITE(x, y, x)
assert ITE(Eq(S.false, x), y, x) == ITE(~x, y, x)
assert ITE(Ne(S.true, x), y, x) == ITE(~x, y, x)
assert ITE(Ne(S.false, x), y, x) == ITE(x, y, x)
# 0 and 1 in the context are not treated as True/False
# so the equality must always be False since dissimilar
# objects cannot be equal
assert ITE(Eq(x, 0), y, x) == x
assert ITE(Eq(x, 1), y, x) == x
assert ITE(Ne(x, 0), y, x) == y
assert ITE(Ne(x, 1), y, x) == y
assert ITE(Eq(x, 0), y, z).subs(x, 0) == y
assert ITE(Eq(x, 0), y, z).subs(x, 1) == z
raises(ValueError, lambda: ITE(x > 1, y, x, z))
def test_is_literal():
assert is_literal(True) is True
assert is_literal(False) is True
assert is_literal(A) is True
assert is_literal(~A) is True
assert is_literal(Or(A, B)) is False
assert is_literal(Q.zero(A)) is True
assert is_literal(Not(Q.zero(A))) is True
assert is_literal(Or(A, B)) is False
assert is_literal(And(Q.zero(A), Q.zero(B))) is False
assert is_literal(x < 3)
assert not is_literal(x + y < 3)
def test_operators():
# Mostly test __and__, __rand__, and so on
assert True & A == A & True == A
assert False & A == A & False == False
assert A & B == And(A, B)
assert True | A == A | True == True
assert False | A == A | False == A
assert A | B == Or(A, B)
assert ~A == Not(A)
assert True >> A == A << True == A
assert False >> A == A << False == True
assert A >> True == True << A == True
assert A >> False == False << A == ~A
assert A >> B == B << A == Implies(A, B)
assert True ^ A == A ^ True == ~A
assert False ^ A == A ^ False == A
assert A ^ B == Xor(A, B)
def test_true_false():
assert true is S.true
assert false is S.false
assert true is not True
assert false is not False
assert true
assert not false
assert true == True
assert false == False
assert not (true == False)
assert not (false == True)
assert not (true == false)
assert hash(true) == hash(True)
assert hash(false) == hash(False)
assert len({true, True}) == len({false, False}) == 1
assert isinstance(true, BooleanAtom)
assert isinstance(false, BooleanAtom)
# We don't want to subclass from bool, because bool subclasses from
# int. But operators like &, |, ^, <<, >>, and ~ act differently on 0 and
# 1 then we want them to on true and false. See the docstrings of the
# various And, Or, etc. functions for examples.
assert not isinstance(true, bool)
assert not isinstance(false, bool)
# Note: using 'is' comparison is important here. We want these to return
# true and false, not True and False
assert Not(true) is false
assert Not(True) is false
assert Not(false) is true
assert Not(False) is true
assert ~true is false
assert ~false is true
for T, F in product((True, true), (False, false)):
assert And(T, F) is false
assert And(F, T) is false
assert And(F, F) is false
assert And(T, T) is true
assert And(T, x) == x
assert And(F, x) is false
if not (T is True and F is False):
assert T & F is false
assert F & T is false
if F is not False:
assert F & F is false
if T is not True:
assert T & T is true
assert Or(T, F) is true
assert Or(F, T) is true
assert Or(F, F) is false
assert Or(T, T) is true
assert Or(T, x) is true
assert Or(F, x) == x
if not (T is True and F is False):
assert T | F is true
assert F | T is true
if F is not False:
assert F | F is false
if T is not True:
assert T | T is true
assert Xor(T, F) is true
assert Xor(F, T) is true
assert Xor(F, F) is false
assert Xor(T, T) is false
assert Xor(T, x) == ~x
assert Xor(F, x) == x
if not (T is True and F is False):
assert T ^ F is true
assert F ^ T is true
if F is not False:
assert F ^ F is false
if T is not True:
assert T ^ T is false
assert Nand(T, F) is true
assert Nand(F, T) is true
assert Nand(F, F) is true
assert Nand(T, T) is false
assert Nand(T, x) == ~x
assert Nand(F, x) is true
assert Nor(T, F) is false
assert Nor(F, T) is false
assert Nor(F, F) is true
assert Nor(T, T) is false
assert Nor(T, x) is false
assert Nor(F, x) == ~x
assert Implies(T, F) is false
assert Implies(F, T) is true
assert Implies(F, F) is true
assert Implies(T, T) is true
assert Implies(T, x) == x
assert Implies(F, x) is true
assert Implies(x, T) is true
assert Implies(x, F) == ~x
if not (T is True and F is False):
assert T >> F is false
assert F << T is false
assert F >> T is true
assert T << F is true
if F is not False:
assert F >> F is true
assert F << F is true
if T is not True:
assert T >> T is true
assert T << T is true
assert Equivalent(T, F) is false
assert Equivalent(F, T) is false
assert Equivalent(F, F) is true
assert Equivalent(T, T) is true
assert Equivalent(T, x) == x
assert Equivalent(F, x) == ~x
assert Equivalent(x, T) == x
assert Equivalent(x, F) == ~x
assert ITE(T, T, T) is true
assert ITE(T, T, F) is true
assert ITE(T, F, T) is false
assert ITE(T, F, F) is false
assert ITE(F, T, T) is true
assert ITE(F, T, F) is false
assert ITE(F, F, T) is true
assert ITE(F, F, F) is false
assert all(i.simplify(1, 2) is i for i in (S.true, S.false))
def test_bool_as_set():
assert ITE(y <= 0, False, y >= 1).as_set() == Interval(1, oo)
assert And(x <= 2, x >= -2).as_set() == Interval(-2, 2)
assert Or(x >= 2, x <= -2).as_set() == Interval(-oo, -2) + Interval(2, oo)
assert Not(x > 2).as_set() == Interval(-oo, 2)
# issue 10240
assert Not(And(x > 2, x < 3)).as_set() == \
Union(Interval(-oo, 2), Interval(3, oo))
assert true.as_set() == S.UniversalSet
assert false.as_set() is S.EmptySet
assert x.as_set() == S.UniversalSet
assert And(Or(x < 1, x > 3), x < 2).as_set() == Interval.open(-oo, 1)
assert And(x < 1, sin(x) < 3).as_set() == (x < 1).as_set()
raises(NotImplementedError, lambda: (sin(x) < 1).as_set())
# watch for object morph in as_set
assert Eq(-1, cos(2*x)**2/sin(2*x)**2).as_set() is S.EmptySet
@XFAIL
def test_multivariate_bool_as_set():
x, y = symbols('x,y')
assert And(x >= 0, y >= 0).as_set() == Interval(0, oo)*Interval(0, oo)
assert Or(x >= 0, y >= 0).as_set() == S.Reals*S.Reals - \
Interval(-oo, 0, True, True)*Interval(-oo, 0, True, True)
def test_all_or_nothing():
x = symbols('x', extended_real=True)
args = x >= -oo, x <= oo
v = And(*args)
if v.func is And:
assert len(v.args) == len(args) - args.count(S.true)
else:
assert v == True
v = Or(*args)
if v.func is Or:
assert len(v.args) == 2
else:
assert v == True
def test_canonical_atoms():
assert true.canonical == true
assert false.canonical == false
def test_negated_atoms():
assert true.negated == false
assert false.negated == true
def test_issue_8777():
assert And(x > 2, x < oo).as_set() == Interval(2, oo, left_open=True)
assert And(x >= 1, x < oo).as_set() == Interval(1, oo)
assert (x < oo).as_set() == Interval(-oo, oo)
assert (x > -oo).as_set() == Interval(-oo, oo)
def test_issue_8975():
assert Or(And(-oo < x, x <= -2), And(2 <= x, x < oo)).as_set() == \
Interval(-oo, -2) + Interval(2, oo)
def test_term_to_integer():
assert term_to_integer([1, 0, 1, 0, 0, 1, 0]) == 82
assert term_to_integer('0010101000111001') == 10809
def test_issue_21971():
a, b, c, d = symbols('a b c d')
f = a & b & c | a & c
assert f.subs(a & c, d) == b & d | d
assert f.subs(a & b & c, d) == a & c | d
f = (a | b | c) & (a | c)
assert f.subs(a | c, d) == (b | d) & d
assert f.subs(a | b | c, d) == (a | c) & d
f = (a ^ b ^ c) & (a ^ c)
assert f.subs(a ^ c, d) == (b ^ d) & d
assert f.subs(a ^ b ^ c, d) == (a ^ c) & d
def test_truth_table():
assert list(truth_table(And(x, y), [x, y], input=False)) == \
[False, False, False, True]
assert list(truth_table(x | y, [x, y], input=False)) == \
[False, True, True, True]
assert list(truth_table(x >> y, [x, y], input=False)) == \
[True, True, False, True]
assert list(truth_table(And(x, y), [x, y])) == \
[([0, 0], False), ([0, 1], False), ([1, 0], False), ([1, 1], True)]
def test_issue_8571():
for t in (S.true, S.false):
raises(TypeError, lambda: +t)
raises(TypeError, lambda: -t)
raises(TypeError, lambda: abs(t))
# use int(bool(t)) to get 0 or 1
raises(TypeError, lambda: int(t))
for o in [S.Zero, S.One, x]:
for _ in range(2):
raises(TypeError, lambda: o + t)
raises(TypeError, lambda: o - t)
raises(TypeError, lambda: o % t)
raises(TypeError, lambda: o*t)
raises(TypeError, lambda: o/t)
raises(TypeError, lambda: o**t)
o, t = t, o # do again in reversed order
def test_expand_relational():
n = symbols('n', negative=True)
p, q = symbols('p q', positive=True)
r = ((n + q*(-n/q + 1))/(q*(-n/q + 1)) < 0)
assert r is not S.false
assert r.expand() is S.false
assert (q > 0).expand() is S.true
def test_issue_12717():
assert S.true.is_Atom == True
assert S.false.is_Atom == True
def test_as_Boolean():
nz = symbols('nz', nonzero=True)
assert all(as_Boolean(i) is S.true for i in (True, S.true, 1, nz))
z = symbols('z', zero=True)
assert all(as_Boolean(i) is S.false for i in (False, S.false, 0, z))
assert all(as_Boolean(i) == i for i in (x, x < 0))
for i in (2, S(2), x + 1, []):
raises(TypeError, lambda: as_Boolean(i))
def test_binary_symbols():
assert ITE(x < 1, y, z).binary_symbols == {y, z}
for f in (Eq, Ne):
assert f(x, 1).binary_symbols == set()
assert f(x, True).binary_symbols == {x}
assert f(x, False).binary_symbols == {x}
assert S.true.binary_symbols == set()
assert S.false.binary_symbols == set()
assert x.binary_symbols == {x}
assert And(x, Eq(y, False), Eq(z, 1)).binary_symbols == {x, y}
assert Q.prime(x).binary_symbols == set()
assert Q.lt(x, 1).binary_symbols == set()
assert Q.is_true(x).binary_symbols == {x}
assert Q.eq(x, True).binary_symbols == {x}
assert Q.prime(x).binary_symbols == set()
def test_BooleanFunction_diff():
assert And(x, y).diff(x) == Piecewise((0, Eq(y, False)), (1, True))
def test_issue_14700():
A, B, C, D, E, F, G, H = symbols('A B C D E F G H')
q = ((B & D & H & ~F) | (B & H & ~C & ~D) | (B & H & ~C & ~F) |
(B & H & ~D & ~G) | (B & H & ~F & ~G) | (C & G & ~B & ~D) |
(C & G & ~D & ~H) | (C & G & ~F & ~H) | (D & F & H & ~B) |
(D & F & ~G & ~H) | (B & D & F & ~C & ~H) | (D & E & F & ~B & ~C) |
(D & F & ~A & ~B & ~C) | (D & F & ~A & ~C & ~H) |
(A & B & D & F & ~E & ~H))
soldnf = ((B & D & H & ~F) | (D & F & H & ~B) | (B & H & ~C & ~D) |
(B & H & ~D & ~G) | (C & G & ~B & ~D) | (C & G & ~D & ~H) |
(C & G & ~F & ~H) | (D & F & ~G & ~H) | (D & E & F & ~C & ~H) |
(D & F & ~A & ~C & ~H) | (A & B & D & F & ~E & ~H))
solcnf = ((B | C | D) & (B | D | G) & (C | D | H) & (C | F | H) &
(D | G | H) & (F | G | H) & (B | F | ~D | ~H) &
(~B | ~D | ~F | ~H) & (D | ~B | ~C | ~G | ~H) &
(A | H | ~C | ~D | ~F | ~G) & (H | ~C | ~D | ~E | ~F | ~G) &
(B | E | H | ~A | ~D | ~F | ~G))
assert simplify_logic(q, "dnf") == soldnf
assert simplify_logic(q, "cnf") == solcnf
minterms = [[0, 1, 0, 0], [0, 1, 0, 1], [0, 1, 1, 0], [0, 1, 1, 1],
[0, 0, 1, 1], [1, 0, 1, 1]]
dontcares = [[1, 0, 0, 0], [1, 0, 0, 1], [1, 1, 0, 0], [1, 1, 0, 1]]
assert SOPform([w, x, y, z], minterms) == (x & ~w) | (y & z & ~x)
# Should not be more complicated with don't cares
assert SOPform([w, x, y, z], minterms, dontcares) == \
(x & ~w) | (y & z & ~x)
def test_relational_simplification():
w, x, y, z = symbols('w x y z', real=True)
d, e = symbols('d e', real=False)
# Test all combinations or sign and order
assert Or(x >= y, x < y).simplify() == S.true
assert Or(x >= y, y > x).simplify() == S.true
assert Or(x >= y, -x > -y).simplify() == S.true
assert Or(x >= y, -y < -x).simplify() == S.true
assert Or(-x <= -y, x < y).simplify() == S.true
assert Or(-x <= -y, -x > -y).simplify() == S.true
assert Or(-x <= -y, y > x).simplify() == S.true
assert Or(-x <= -y, -y < -x).simplify() == S.true
assert Or(y <= x, x < y).simplify() == S.true
assert Or(y <= x, y > x).simplify() == S.true
assert Or(y <= x, -x > -y).simplify() == S.true
assert Or(y <= x, -y < -x).simplify() == S.true
assert Or(-y >= -x, x < y).simplify() == S.true
assert Or(-y >= -x, y > x).simplify() == S.true
assert Or(-y >= -x, -x > -y).simplify() == S.true
assert Or(-y >= -x, -y < -x).simplify() == S.true
assert Or(x < y, x >= y).simplify() == S.true
assert Or(y > x, x >= y).simplify() == S.true
assert Or(-x > -y, x >= y).simplify() == S.true
assert Or(-y < -x, x >= y).simplify() == S.true
assert Or(x < y, -x <= -y).simplify() == S.true
assert Or(-x > -y, -x <= -y).simplify() == S.true
assert Or(y > x, -x <= -y).simplify() == S.true
assert Or(-y < -x, -x <= -y).simplify() == S.true
assert Or(x < y, y <= x).simplify() == S.true
assert Or(y > x, y <= x).simplify() == S.true
assert Or(-x > -y, y <= x).simplify() == S.true
assert Or(-y < -x, y <= x).simplify() == S.true
assert Or(x < y, -y >= -x).simplify() == S.true
assert Or(y > x, -y >= -x).simplify() == S.true
assert Or(-x > -y, -y >= -x).simplify() == S.true
assert Or(-y < -x, -y >= -x).simplify() == S.true
# Some other tests
assert Or(x >= y, w < z, x <= y).simplify() == S.true
assert And(x >= y, x < y).simplify() == S.false
assert Or(x >= y, Eq(y, x)).simplify() == (x >= y)
assert And(x >= y, Eq(y, x)).simplify() == Eq(x, y)
assert And(Eq(x, y), x >= 1, 2 < y, y >= 5, z < y).simplify() == \
(Eq(x, y) & (x >= 1) & (y >= 5) & (y > z))
assert (Eq(x, y) & Eq(d, e) & (x >= y) & (d >= e)).simplify() == \
(Eq(x, y) & Eq(d, e) & (d >= e))
assert And(Eq(x, y), Eq(x, -y)).simplify() == And(Eq(x, 0), Eq(y, 0))
assert Xor(x >= y, x <= y).simplify() == Ne(x, y)
@slow
def test_relational_simplification_numerically():
def test_simplification_numerically_function(original, simplified):
symb = original.free_symbols
n = len(symb)
valuelist = list(set(list(combinations(list(range(-(n-1), n))*n, n))))
for values in valuelist:
sublist = dict(zip(symb, values))
originalvalue = original.subs(sublist)
simplifiedvalue = simplified.subs(sublist)
assert originalvalue == simplifiedvalue, "Original: {}\nand"\
" simplified: {}\ndo not evaluate to the same value for {}"\
"".format(original, simplified, sublist)
w, x, y, z = symbols('w x y z', real=True)
d, e = symbols('d e', real=False)
expressions = (And(Eq(x, y), x >= y, w < y, y >= z, z < y),
And(Eq(x, y), x >= 1, 2 < y, y >= 5, z < y),
Or(Eq(x, y), x >= 1, 2 < y, y >= 5, z < y),
And(x >= y, Eq(y, x)),
Or(And(Eq(x, y), x >= y, w < y, Or(y >= z, z < y)),
And(Eq(x, y), x >= 1, 2 < y, y >= -1, z < y)),
(Eq(x, y) & Eq(d, e) & (x >= y) & (d >= e)),
)
for expression in expressions:
test_simplification_numerically_function(expression,
expression.simplify())
def test_relational_simplification_patterns_numerically():
from sympy.core import Wild
from sympy.logic.boolalg import simplify_patterns_and, \
simplify_patterns_or, simplify_patterns_xor
a = Wild('a')
b = Wild('b')
c = Wild('c')
symb = [a, b, c]
patternlists = [simplify_patterns_and(), simplify_patterns_or(),
simplify_patterns_xor()]
for patternlist in patternlists:
for pattern in patternlist:
original = pattern[0]
simplified = pattern[1]
valuelist = list(set(list(combinations(list(range(-2, 2))*3, 3))))
for values in valuelist:
sublist = dict(zip(symb, values))
originalvalue = original.subs(sublist)
simplifiedvalue = simplified.subs(sublist)
assert originalvalue == simplifiedvalue, "Original: {}\nand"\
" simplified: {}\ndo not evaluate to the same value for"\
"{}".format(original, simplified, sublist)
def test_issue_16803():
n = symbols('n')
# No simplification done, but should not raise an exception
assert ((n > 3) | (n < 0) | ((n > 0) & (n < 3))).simplify() == \
(n > 3) | (n < 0) | ((n > 0) & (n < 3))
def test_issue_17530():
r = {x: oo, y: oo}
assert Or(x + y > 0, x - y < 0).subs(r)
assert not And(x + y < 0, x - y < 0).subs(r)
raises(TypeError, lambda: Or(x + y < 0, x - y < 0).subs(r))
raises(TypeError, lambda: And(x + y > 0, x - y < 0).subs(r))
raises(TypeError, lambda: And(x + y > 0, x - y < 0).subs(r))
def test_anf_coeffs():
assert anf_coeffs([1, 0]) == [1, 1]
assert anf_coeffs([0, 0, 0, 1]) == [0, 0, 0, 1]
assert anf_coeffs([0, 1, 1, 1]) == [0, 1, 1, 1]
assert anf_coeffs([1, 1, 1, 0]) == [1, 0, 0, 1]
assert anf_coeffs([1, 0, 0, 0]) == [1, 1, 1, 1]
assert anf_coeffs([1, 0, 0, 1]) == [1, 1, 1, 0]
assert anf_coeffs([1, 1, 0, 1]) == [1, 0, 1, 1]
def test_ANFform():
x, y = symbols('x,y')
assert ANFform([x], [1, 1]) == True
assert ANFform([x], [0, 0]) == False
assert ANFform([x], [1, 0]) == Xor(x, True, remove_true=False)
assert ANFform([x, y], [1, 1, 1, 0]) == \
Xor(True, And(x, y), remove_true=False)
def test_bool_minterm():
x, y = symbols('x,y')
assert bool_minterm(3, [x, y]) == And(x, y)
assert bool_minterm([1, 0], [x, y]) == And(Not(y), x)
def test_bool_maxterm():
x, y = symbols('x,y')
assert bool_maxterm(2, [x, y]) == Or(Not(x), y)
assert bool_maxterm([0, 1], [x, y]) == Or(Not(y), x)
def test_bool_monomial():
x, y = symbols('x,y')
assert bool_monomial(1, [x, y]) == y
assert bool_monomial([1, 1], [x, y]) == And(x, y)
def test_check_pair():
assert _check_pair([0, 1, 0], [0, 1, 1]) == 2
assert _check_pair([0, 1, 0], [1, 1, 1]) == -1
def test_issue_19114():
expr = (B & C) | (A & ~C) | (~A & ~B)
result = to_dnf(expr, simplify=True)
assert result == expr
def test_issue_20870():
result = SOPform([a, b, c, d], [1, 2, 3, 4, 5, 6, 8, 9, 11, 12, 14, 15])
expected = ((d & ~b) | (a & b & c) | (a & ~c & ~d) |
(b & ~a & ~c) | (c & ~a & ~d))
assert result == expected
def test_convert_to_varsSOP():
assert _convert_to_varsSOP([0, 1, 0], [x, y, z]) == And(Not(x), y, Not(z))
assert _convert_to_varsSOP([3, 1, 0], [x, y, z]) == And(y, Not(z))
def test_convert_to_varsPOS():
assert _convert_to_varsPOS([0, 1, 0], [x, y, z]) == Or(x, Not(y), z)
assert _convert_to_varsPOS([3, 1, 0], [x, y, z]) == Or(Not(y), z)
def test_refine():
# relational
assert not refine(x < 0, ~(x < 0))
assert refine(x < 0, (x < 0))
assert refine(x < 0, (0 > x)) is S.true
assert refine(x < 0, (y < 0)) == (x < 0)
assert not refine(x <= 0, ~(x <= 0))
assert refine(x <= 0, (x <= 0))
assert refine(x <= 0, (0 >= x)) is S.true
assert refine(x <= 0, (y <= 0)) == (x <= 0)
assert not refine(x > 0, ~(x > 0))
assert refine(x > 0, (x > 0))
assert refine(x > 0, (0 < x)) is S.true
assert refine(x > 0, (y > 0)) == (x > 0)
assert not refine(x >= 0, ~(x >= 0))
assert refine(x >= 0, (x >= 0))
assert refine(x >= 0, (0 <= x)) is S.true
assert refine(x >= 0, (y >= 0)) == (x >= 0)
assert not refine(Eq(x, 0), ~(Eq(x, 0)))
assert refine(Eq(x, 0), (Eq(x, 0)))
assert refine(Eq(x, 0), (Eq(0, x))) is S.true
assert refine(Eq(x, 0), (Eq(y, 0))) == Eq(x, 0)
assert not refine(Ne(x, 0), ~(Ne(x, 0)))
assert refine(Ne(x, 0), (Ne(0, x))) is S.true
assert refine(Ne(x, 0), (Ne(x, 0)))
assert refine(Ne(x, 0), (Ne(y, 0))) == (Ne(x, 0))
# boolean functions
assert refine(And(x > 0, y > 0), (x > 0)) == (y > 0)
assert refine(And(x > 0, y > 0), (x > 0) & (y > 0)) is S.true
# predicates
assert refine(Q.positive(x), Q.positive(x)) is S.true
assert refine(Q.positive(x), Q.negative(x)) is S.false
assert refine(Q.positive(x), Q.real(x)) == Q.positive(x)
|
0ce9606f87251142e3301a74706dd9742ad737cbc57712599920dffb5ddb5920 | """For more tests on satisfiability, see test_dimacs"""
from sympy.assumptions.ask import Q
from sympy.core.symbol import symbols
from sympy.logic.boolalg import And, Implies, Equivalent, true, false
from sympy.logic.inference import literal_symbol, \
pl_true, satisfiable, valid, entails, PropKB
from sympy.logic.algorithms.dpll import dpll, dpll_satisfiable, \
find_pure_symbol, find_unit_clause, unit_propagate, \
find_pure_symbol_int_repr, find_unit_clause_int_repr, \
unit_propagate_int_repr
from sympy.logic.algorithms.dpll2 import dpll_satisfiable as dpll2_satisfiable
from sympy.testing.pytest import raises
def test_literal():
A, B = symbols('A,B')
assert literal_symbol(True) is True
assert literal_symbol(False) is False
assert literal_symbol(A) is A
assert literal_symbol(~A) is A
def test_find_pure_symbol():
A, B, C = symbols('A,B,C')
assert find_pure_symbol([A], [A]) == (A, True)
assert find_pure_symbol([A, B], [~A | B, ~B | A]) == (None, None)
assert find_pure_symbol([A, B, C], [ A | ~B, ~B | ~C, C | A]) == (A, True)
assert find_pure_symbol([A, B, C], [~A | B, B | ~C, C | A]) == (B, True)
assert find_pure_symbol([A, B, C], [~A | ~B, ~B | ~C, C | A]) == (B, False)
assert find_pure_symbol(
[A, B, C], [~A | B, ~B | ~C, C | A]) == (None, None)
def test_find_pure_symbol_int_repr():
assert find_pure_symbol_int_repr([1], [{1}]) == (1, True)
assert find_pure_symbol_int_repr([1, 2],
[{-1, 2}, {-2, 1}]) == (None, None)
assert find_pure_symbol_int_repr([1, 2, 3],
[{1, -2}, {-2, -3}, {3, 1}]) == (1, True)
assert find_pure_symbol_int_repr([1, 2, 3],
[{-1, 2}, {2, -3}, {3, 1}]) == (2, True)
assert find_pure_symbol_int_repr([1, 2, 3],
[{-1, -2}, {-2, -3}, {3, 1}]) == (2, False)
assert find_pure_symbol_int_repr([1, 2, 3],
[{-1, 2}, {-2, -3}, {3, 1}]) == (None, None)
def test_unit_clause():
A, B, C = symbols('A,B,C')
assert find_unit_clause([A], {}) == (A, True)
assert find_unit_clause([A, ~A], {}) == (A, True) # Wrong ??
assert find_unit_clause([A | B], {A: True}) == (B, True)
assert find_unit_clause([A | B], {B: True}) == (A, True)
assert find_unit_clause(
[A | B | C, B | ~C, A | ~B], {A: True}) == (B, False)
assert find_unit_clause([A | B | C, B | ~C, A | B], {A: True}) == (B, True)
assert find_unit_clause([A | B | C, B | ~C, A ], {}) == (A, True)
def test_unit_clause_int_repr():
assert find_unit_clause_int_repr(map(set, [[1]]), {}) == (1, True)
assert find_unit_clause_int_repr(map(set, [[1], [-1]]), {}) == (1, True)
assert find_unit_clause_int_repr([{1, 2}], {1: True}) == (2, True)
assert find_unit_clause_int_repr([{1, 2}], {2: True}) == (1, True)
assert find_unit_clause_int_repr(map(set,
[[1, 2, 3], [2, -3], [1, -2]]), {1: True}) == (2, False)
assert find_unit_clause_int_repr(map(set,
[[1, 2, 3], [3, -3], [1, 2]]), {1: True}) == (2, True)
A, B, C = symbols('A,B,C')
assert find_unit_clause([A | B | C, B | ~C, A ], {}) == (A, True)
def test_unit_propagate():
A, B, C = symbols('A,B,C')
assert unit_propagate([A | B], A) == []
assert unit_propagate([A | B, ~A | C, ~C | B, A], A) == [C, ~C | B, A]
def test_unit_propagate_int_repr():
assert unit_propagate_int_repr([{1, 2}], 1) == []
assert unit_propagate_int_repr(map(set,
[[1, 2], [-1, 3], [-3, 2], [1]]), 1) == [{3}, {-3, 2}]
def test_dpll():
"""This is also tested in test_dimacs"""
A, B, C = symbols('A,B,C')
assert dpll([A | B], [A, B], {A: True, B: True}) == {A: True, B: True}
def test_dpll_satisfiable():
A, B, C = symbols('A,B,C')
assert dpll_satisfiable( A & ~A ) is False
assert dpll_satisfiable( A & ~B ) == {A: True, B: False}
assert dpll_satisfiable(
A | B ) in ({A: True}, {B: True}, {A: True, B: True})
assert dpll_satisfiable(
(~A | B) & (~B | A) ) in ({A: True, B: True}, {A: False, B: False})
assert dpll_satisfiable( (A | B) & (~B | C) ) in ({A: True, B: False},
{A: True, C: True}, {B: True, C: True})
assert dpll_satisfiable( A & B & C ) == {A: True, B: True, C: True}
assert dpll_satisfiable( (A | B) & (A >> B) ) == {B: True}
assert dpll_satisfiable( Equivalent(A, B) & A ) == {A: True, B: True}
assert dpll_satisfiable( Equivalent(A, B) & ~A ) == {A: False, B: False}
def test_dpll2_satisfiable():
A, B, C = symbols('A,B,C')
assert dpll2_satisfiable( A & ~A ) is False
assert dpll2_satisfiable( A & ~B ) == {A: True, B: False}
assert dpll2_satisfiable(
A | B ) in ({A: True}, {B: True}, {A: True, B: True})
assert dpll2_satisfiable(
(~A | B) & (~B | A) ) in ({A: True, B: True}, {A: False, B: False})
assert dpll2_satisfiable( (A | B) & (~B | C) ) in ({A: True, B: False, C: True},
{A: True, B: True, C: True})
assert dpll2_satisfiable( A & B & C ) == {A: True, B: True, C: True}
assert dpll2_satisfiable( (A | B) & (A >> B) ) in ({B: True, A: False},
{B: True, A: True})
assert dpll2_satisfiable( Equivalent(A, B) & A ) == {A: True, B: True}
assert dpll2_satisfiable( Equivalent(A, B) & ~A ) == {A: False, B: False}
def test_minisat22_satisfiable():
A, B, C = symbols('A,B,C')
minisat22_satisfiable = lambda expr: satisfiable(expr, algorithm="minisat22")
assert minisat22_satisfiable( A & ~A ) is False
assert minisat22_satisfiable( A & ~B ) == {A: True, B: False}
assert minisat22_satisfiable(
A | B ) in ({A: True}, {B: False}, {A: False, B: True}, {A: True, B: True}, {A: True, B: False})
assert minisat22_satisfiable(
(~A | B) & (~B | A) ) in ({A: True, B: True}, {A: False, B: False})
assert minisat22_satisfiable( (A | B) & (~B | C) ) in ({A: True, B: False, C: True},
{A: True, B: True, C: True}, {A: False, B: True, C: True}, {A: True, B: False, C: False})
assert minisat22_satisfiable( A & B & C ) == {A: True, B: True, C: True}
assert minisat22_satisfiable( (A | B) & (A >> B) ) in ({B: True, A: False},
{B: True, A: True})
assert minisat22_satisfiable( Equivalent(A, B) & A ) == {A: True, B: True}
assert minisat22_satisfiable( Equivalent(A, B) & ~A ) == {A: False, B: False}
def test_minisat22_minimal_satisfiable():
A, B, C = symbols('A,B,C')
minisat22_satisfiable = lambda expr, minimal=True: satisfiable(expr, algorithm="minisat22", minimal=True)
assert minisat22_satisfiable( A & ~A ) is False
assert minisat22_satisfiable( A & ~B ) == {A: True, B: False}
assert minisat22_satisfiable(
A | B ) in ({A: True}, {B: False}, {A: False, B: True}, {A: True, B: True}, {A: True, B: False})
assert minisat22_satisfiable(
(~A | B) & (~B | A) ) in ({A: True, B: True}, {A: False, B: False})
assert minisat22_satisfiable( (A | B) & (~B | C) ) in ({A: True, B: False, C: True},
{A: True, B: True, C: True}, {A: False, B: True, C: True}, {A: True, B: False, C: False})
assert minisat22_satisfiable( A & B & C ) == {A: True, B: True, C: True}
assert minisat22_satisfiable( (A | B) & (A >> B) ) in ({B: True, A: False},
{B: True, A: True})
assert minisat22_satisfiable( Equivalent(A, B) & A ) == {A: True, B: True}
assert minisat22_satisfiable( Equivalent(A, B) & ~A ) == {A: False, B: False}
g = satisfiable((A | B | C),algorithm="minisat22",minimal=True,all_models=True)
sol = next(g)
first_solution = {key for key, value in sol.items() if value}
sol=next(g)
second_solution = {key for key, value in sol.items() if value}
sol=next(g)
third_solution = {key for key, value in sol.items() if value}
assert not first_solution <= second_solution
assert not second_solution <= third_solution
assert not first_solution <= third_solution
def test_satisfiable():
A, B, C = symbols('A,B,C')
assert satisfiable(A & (A >> B) & ~B) is False
def test_valid():
A, B, C = symbols('A,B,C')
assert valid(A >> (B >> A)) is True
assert valid((A >> (B >> C)) >> ((A >> B) >> (A >> C))) is True
assert valid((~B >> ~A) >> (A >> B)) is True
assert valid(A | B | C) is False
assert valid(A >> B) is False
def test_pl_true():
A, B, C = symbols('A,B,C')
assert pl_true(True) is True
assert pl_true( A & B, {A: True, B: True}) is True
assert pl_true( A | B, {A: True}) is True
assert pl_true( A | B, {B: True}) is True
assert pl_true( A | B, {A: None, B: True}) is True
assert pl_true( A >> B, {A: False}) is True
assert pl_true( A | B | ~C, {A: False, B: True, C: True}) is True
assert pl_true(Equivalent(A, B), {A: False, B: False}) is True
# test for false
assert pl_true(False) is False
assert pl_true( A & B, {A: False, B: False}) is False
assert pl_true( A & B, {A: False}) is False
assert pl_true( A & B, {B: False}) is False
assert pl_true( A | B, {A: False, B: False}) is False
#test for None
assert pl_true(B, {B: None}) is None
assert pl_true( A & B, {A: True, B: None}) is None
assert pl_true( A >> B, {A: True, B: None}) is None
assert pl_true(Equivalent(A, B), {A: None}) is None
assert pl_true(Equivalent(A, B), {A: True, B: None}) is None
# Test for deep
assert pl_true(A | B, {A: False}, deep=True) is None
assert pl_true(~A & ~B, {A: False}, deep=True) is None
assert pl_true(A | B, {A: False, B: False}, deep=True) is False
assert pl_true(A & B & (~A | ~B), {A: True}, deep=True) is False
assert pl_true((C >> A) >> (B >> A), {C: True}, deep=True) is True
def test_pl_true_wrong_input():
from sympy.core.numbers import pi
raises(ValueError, lambda: pl_true('John Cleese'))
raises(ValueError, lambda: pl_true(42 + pi + pi ** 2))
raises(ValueError, lambda: pl_true(42))
def test_entails():
A, B, C = symbols('A, B, C')
assert entails(A, [A >> B, ~B]) is False
assert entails(B, [Equivalent(A, B), A]) is True
assert entails((A >> B) >> (~A >> ~B)) is False
assert entails((A >> B) >> (~B >> ~A)) is True
def test_PropKB():
A, B, C = symbols('A,B,C')
kb = PropKB()
assert kb.ask(A >> B) is False
assert kb.ask(A >> (B >> A)) is True
kb.tell(A >> B)
kb.tell(B >> C)
assert kb.ask(A) is False
assert kb.ask(B) is False
assert kb.ask(C) is False
assert kb.ask(~A) is False
assert kb.ask(~B) is False
assert kb.ask(~C) is False
assert kb.ask(A >> C) is True
kb.tell(A)
assert kb.ask(A) is True
assert kb.ask(B) is True
assert kb.ask(C) is True
assert kb.ask(~C) is False
kb.retract(A)
assert kb.ask(C) is False
def test_propKB_tolerant():
""""tolerant to bad input"""
kb = PropKB()
A, B, C = symbols('A,B,C')
assert kb.ask(B) is False
def test_satisfiable_non_symbols():
x, y = symbols('x y')
assumptions = Q.zero(x*y)
facts = Implies(Q.zero(x*y), Q.zero(x) | Q.zero(y))
query = ~Q.zero(x) & ~Q.zero(y)
refutations = [
{Q.zero(x): True, Q.zero(x*y): True},
{Q.zero(y): True, Q.zero(x*y): True},
{Q.zero(x): True, Q.zero(y): True, Q.zero(x*y): True},
{Q.zero(x): True, Q.zero(y): False, Q.zero(x*y): True},
{Q.zero(x): False, Q.zero(y): True, Q.zero(x*y): True}]
assert not satisfiable(And(assumptions, facts, query), algorithm='dpll')
assert satisfiable(And(assumptions, facts, ~query), algorithm='dpll') in refutations
assert not satisfiable(And(assumptions, facts, query), algorithm='dpll2')
assert satisfiable(And(assumptions, facts, ~query), algorithm='dpll2') in refutations
def test_satisfiable_bool():
from sympy.core.singleton import S
assert satisfiable(true) == {true: true}
assert satisfiable(S.true) == {true: true}
assert satisfiable(false) is False
assert satisfiable(S.false) is False
def test_satisfiable_all_models():
from sympy.abc import A, B
assert next(satisfiable(False, all_models=True)) is False
assert list(satisfiable((A >> ~A) & A, all_models=True)) == [False]
assert list(satisfiable(True, all_models=True)) == [{true: true}]
models = [{A: True, B: False}, {A: False, B: True}]
result = satisfiable(A ^ B, all_models=True)
models.remove(next(result))
models.remove(next(result))
raises(StopIteration, lambda: next(result))
assert not models
assert list(satisfiable(Equivalent(A, B), all_models=True)) == \
[{A: False, B: False}, {A: True, B: True}]
models = [{A: False, B: False}, {A: False, B: True}, {A: True, B: True}]
for model in satisfiable(A >> B, all_models=True):
models.remove(model)
assert not models
# This is a santiy test to check that only the required number
# of solutions are generated. The expr below has 2**100 - 1 models
# which would time out the test if all are generated at once.
from sympy.utilities.iterables import numbered_symbols
from sympy.logic.boolalg import Or
sym = numbered_symbols()
X = [next(sym) for i in range(100)]
result = satisfiable(Or(*X), all_models=True)
for i in range(10):
assert next(result)
|
bc632583eda29767057805ab7f4349ea9ccf5f761ddd940cc45810e2ae482d01 | from sympy.core.numbers import Integer
from sympy.matrices.dense import (eye, zeros)
i3 = Integer(3)
M = eye(100)
def timeit_Matrix__getitem_ii():
M[3, 3]
def timeit_Matrix__getitem_II():
M[i3, i3]
def timeit_Matrix__getslice():
M[:, :]
def timeit_Matrix_zeronm():
zeros(100, 100)
|
1f173ffe31b43e077893a411450996c038ce0d99e885f33054196e821ad7658c | from sympy.core.evalf import N
from sympy.core.numbers import (Float, I, Rational)
from sympy.core.symbol import (Symbol, symbols)
from sympy.functions.elementary.complexes import Abs
from sympy.functions.elementary.exponential import exp
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.matrices import eye, Matrix
from sympy.core.singleton import S
from sympy.testing.pytest import raises, XFAIL
from sympy.matrices.matrices import NonSquareMatrixError, MatrixError
from sympy.matrices.expressions.fourier import DFT
from sympy.simplify.simplify import simplify
from sympy.matrices.immutable import ImmutableMatrix
from sympy.testing.pytest import slow
from sympy.testing.matrices import allclose
def test_eigen():
R = Rational
M = Matrix.eye(3)
assert M.eigenvals(multiple=False) == {S.One: 3}
assert M.eigenvals(multiple=True) == [1, 1, 1]
assert M.eigenvects() == (
[(1, 3, [Matrix([1, 0, 0]),
Matrix([0, 1, 0]),
Matrix([0, 0, 1])])])
assert M.left_eigenvects() == (
[(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 M.eigenvects() == (
[
(-1, 1, [Matrix([-1, 1, 0])]),
( 0, 1, [Matrix([0, -1, 1])]),
( 2, 1, [Matrix([R(2, 3), R(1, 3), 1])])
])
assert M.left_eigenvects() == (
[
(-1, 1, [Matrix([[-2, 1, 1]])]),
(0, 1, [Matrix([[-1, -1, 1]])]),
(2, 1, [Matrix([[1, 1, 1]])])
])
a = Symbol('a')
M = Matrix([[a, 0],
[0, 1]])
assert M.eigenvals() == {a: 1, S.One: 1}
M = Matrix([[1, -1],
[1, 3]])
assert M.eigenvects() == ([(2, 2, [Matrix(2, 1, [-1, 1])])])
assert M.left_eigenvects() == ([(2, 2, [Matrix([[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 M.eigenvects() == (
[
( 0, 1, [Matrix([[-I*eps/abs(eps)], [1]])]),
( 2*abs(eps), 1, [ Matrix([[I*eps/abs(eps)], [1]]) ] ),
])
assert M.left_eigenvects() == (
[
(0, 1, [Matrix([[I*eps/Abs(eps), 1]])]),
(2*Abs(eps), 1, [Matrix([[-I*eps/Abs(eps), 1]])])
])
M = Matrix(3, 3, [1, 2, 0, 0, 3, 0, 2, -4, 2])
M._eigenvects = M.eigenvects(simplify=False)
assert max(i.q for i in M._eigenvects[0][2][0]) > 1
M._eigenvects = M.eigenvects(simplify=True)
assert max(i.q for i in M._eigenvects[0][2][0]) == 1
M = Matrix([[Rational(1, 4), 1], [1, 1]])
assert M.eigenvects() == [
(Rational(5, 8) - sqrt(73)/8, 1, [Matrix([[-sqrt(73)/8 - Rational(3, 8)], [1]])]),
(Rational(5, 8) + sqrt(73)/8, 1, [Matrix([[Rational(-3, 8) + sqrt(73)/8], [1]])])]
# issue 10719
assert Matrix([]).eigenvals() == {}
assert Matrix([]).eigenvals(multiple=True) == []
assert Matrix([]).eigenvects() == []
# issue 15119
raises(NonSquareMatrixError,
lambda: Matrix([[1, 2], [0, 4], [0, 0]]).eigenvals())
raises(NonSquareMatrixError,
lambda: Matrix([[1, 0], [3, 4], [5, 6]]).eigenvals())
raises(NonSquareMatrixError,
lambda: Matrix([[1, 2, 3], [0, 5, 6]]).eigenvals())
raises(NonSquareMatrixError,
lambda: Matrix([[1, 0, 0], [4, 5, 0]]).eigenvals())
raises(NonSquareMatrixError,
lambda: Matrix([[1, 2, 3], [0, 5, 6]]).eigenvals(
error_when_incomplete = False))
raises(NonSquareMatrixError,
lambda: Matrix([[1, 0, 0], [4, 5, 0]]).eigenvals(
error_when_incomplete = False))
m = Matrix([[1, 2], [3, 4]])
assert isinstance(m.eigenvals(simplify=True, multiple=False), dict)
assert isinstance(m.eigenvals(simplify=True, multiple=True), list)
assert isinstance(m.eigenvals(simplify=lambda x: x, multiple=False), dict)
assert isinstance(m.eigenvals(simplify=lambda x: x, multiple=True), list)
@slow
def test_eigen_slow():
# issue 15125
from sympy.core.function import count_ops
q = Symbol("q", positive = True)
m = Matrix([[-2, exp(-q), 1], [exp(q), -2, 1], [1, 1, -2]])
assert count_ops(m.eigenvals(simplify=False)) > \
count_ops(m.eigenvals(simplify=True))
assert count_ops(m.eigenvals(simplify=lambda x: x)) > \
count_ops(m.eigenvals(simplify=True))
def test_float_eigenvals():
m = Matrix([[1, .6, .6], [.6, .9, .9], [.9, .6, .6]])
evals = [
Rational(5, 4) - sqrt(385)/20,
sqrt(385)/20 + Rational(5, 4),
S.Zero]
n_evals = m.eigenvals(rational=True, multiple=True)
n_evals = sorted(n_evals)
s_evals = [x.evalf() for x in evals]
s_evals = sorted(s_evals)
for x, y in zip(n_evals, s_evals):
assert abs(x-y) < 10**-9
@XFAIL
def test_eigen_vects():
m = Matrix(2, 2, [1, 0, 0, I])
raises(NotImplementedError, lambda: m.is_diagonalizable(True))
# !!! bug because of eigenvects() or roots(x**2 + (-1 - I)*x + I, x)
# see issue 5292
assert not m.is_diagonalizable(True)
raises(MatrixError, lambda: m.diagonalize(True))
(P, D) = m.diagonalize(True)
def test_issue_8240():
# Eigenvalues of large triangular matrices
x, y = symbols('x y')
n = 200
diagonal_variables = [Symbol('x%s' % i) for i in range(n)]
M = [[0 for i in range(n)] for j in range(n)]
for i in range(n):
M[i][i] = diagonal_variables[i]
M = Matrix(M)
eigenvals = M.eigenvals()
assert len(eigenvals) == n
for i in range(n):
assert eigenvals[diagonal_variables[i]] == 1
eigenvals = M.eigenvals(multiple=True)
assert set(eigenvals) == set(diagonal_variables)
# with multiplicity
M = Matrix([[x, 0, 0], [1, y, 0], [2, 3, x]])
eigenvals = M.eigenvals()
assert eigenvals == {x: 2, y: 1}
eigenvals = M.eigenvals(multiple=True)
assert len(eigenvals) == 3
assert eigenvals.count(x) == 2
assert eigenvals.count(y) == 1
def test_eigenvals():
M = Matrix([[0, 1, 1],
[1, 0, 0],
[1, 1, 1]])
assert M.eigenvals() == {2*S.One: 1, -S.One: 1, S.Zero: 1}
m = Matrix([
[3, 0, 0, 0, -3],
[0, -3, -3, 0, 3],
[0, 3, 0, 3, 0],
[0, 0, 3, 0, 3],
[3, 0, 0, 3, 0]])
# XXX Used dry-run test because arbitrary symbol that appears in
# CRootOf may not be unique.
assert m.eigenvals()
def test_eigenvects():
M = Matrix([[0, 1, 1],
[1, 0, 0],
[1, 1, 1]])
vecs = M.eigenvects()
for val, mult, vec_list in vecs:
assert len(vec_list) == 1
assert M*vec_list[0] == val*vec_list[0]
def test_left_eigenvects():
M = Matrix([[0, 1, 1],
[1, 0, 0],
[1, 1, 1]])
vecs = M.left_eigenvects()
for val, mult, vec_list in vecs:
assert len(vec_list) == 1
assert vec_list[0]*M == val*vec_list[0]
@slow
def test_bidiagonalize():
M = Matrix([[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
assert M.bidiagonalize() == M
assert M.bidiagonalize(upper=False) == M
assert M.bidiagonalize() == M
assert M.bidiagonal_decomposition() == (M, M, M)
assert M.bidiagonal_decomposition(upper=False) == (M, M, M)
assert M.bidiagonalize() == M
import random
#Real Tests
for real_test in range(2):
test_values = []
row = 2
col = 2
for _ in range(row * col):
value = random.randint(-1000000000, 1000000000)
test_values = test_values + [value]
# L -> Lower Bidiagonalization
# M -> Mutable Matrix
# N -> Immutable Matrix
# 0 -> Bidiagonalized form
# 1,2,3 -> Bidiagonal_decomposition matrices
# 4 -> Product of 1 2 3
M = Matrix(row, col, test_values)
N = ImmutableMatrix(M)
N1, N2, N3 = N.bidiagonal_decomposition()
M1, M2, M3 = M.bidiagonal_decomposition()
M0 = M.bidiagonalize()
N0 = N.bidiagonalize()
N4 = N1 * N2 * N3
M4 = M1 * M2 * M3
N2.simplify()
N4.simplify()
N0.simplify()
M0.simplify()
M2.simplify()
M4.simplify()
LM0 = M.bidiagonalize(upper=False)
LM1, LM2, LM3 = M.bidiagonal_decomposition(upper=False)
LN0 = N.bidiagonalize(upper=False)
LN1, LN2, LN3 = N.bidiagonal_decomposition(upper=False)
LN4 = LN1 * LN2 * LN3
LM4 = LM1 * LM2 * LM3
LN2.simplify()
LN4.simplify()
LN0.simplify()
LM0.simplify()
LM2.simplify()
LM4.simplify()
assert M == M4
assert M2 == M0
assert N == N4
assert N2 == N0
assert M == LM4
assert LM2 == LM0
assert N == LN4
assert LN2 == LN0
#Complex Tests
for complex_test in range(2):
test_values = []
size = 2
for _ in range(size * size):
real = random.randint(-1000000000, 1000000000)
comp = random.randint(-1000000000, 1000000000)
value = real + comp * I
test_values = test_values + [value]
M = Matrix(size, size, test_values)
N = ImmutableMatrix(M)
# L -> Lower Bidiagonalization
# M -> Mutable Matrix
# N -> Immutable Matrix
# 0 -> Bidiagonalized form
# 1,2,3 -> Bidiagonal_decomposition matrices
# 4 -> Product of 1 2 3
N1, N2, N3 = N.bidiagonal_decomposition()
M1, M2, M3 = M.bidiagonal_decomposition()
M0 = M.bidiagonalize()
N0 = N.bidiagonalize()
N4 = N1 * N2 * N3
M4 = M1 * M2 * M3
N2.simplify()
N4.simplify()
N0.simplify()
M0.simplify()
M2.simplify()
M4.simplify()
LM0 = M.bidiagonalize(upper=False)
LM1, LM2, LM3 = M.bidiagonal_decomposition(upper=False)
LN0 = N.bidiagonalize(upper=False)
LN1, LN2, LN3 = N.bidiagonal_decomposition(upper=False)
LN4 = LN1 * LN2 * LN3
LM4 = LM1 * LM2 * LM3
LN2.simplify()
LN4.simplify()
LN0.simplify()
LM0.simplify()
LM2.simplify()
LM4.simplify()
assert M == M4
assert M2 == M0
assert N == N4
assert N2 == N0
assert M == LM4
assert LM2 == LM0
assert N == LN4
assert LN2 == LN0
M = Matrix(18, 8, range(1, 145))
M = M.applyfunc(lambda i: Float(i))
assert M.bidiagonal_decomposition()[1] == M.bidiagonalize()
assert M.bidiagonal_decomposition(upper=False)[1] == M.bidiagonalize(upper=False)
a, b, c = M.bidiagonal_decomposition()
diff = a * b * c - M
assert abs(max(diff)) < 10**-12
def test_diagonalize():
m = Matrix(2, 2, [0, -1, 1, 0])
raises(MatrixError, lambda: m.diagonalize(reals_only=True))
P, D = m.diagonalize()
assert D.is_diagonal()
assert D == Matrix([
[-I, 0],
[ 0, I]])
# make sure we use floats out if floats are passed in
m = Matrix(2, 2, [0, .5, .5, 0])
P, D = m.diagonalize()
assert all(isinstance(e, Float) for e in D.values())
assert all(isinstance(e, Float) for e in P.values())
_, D2 = m.diagonalize(reals_only=True)
assert D == D2
m = Matrix(
[[0, 1, 0, 0], [1, 0, 0, 0.002], [0.002, 0, 0, 1], [0, 0, 1, 0]])
P, D = m.diagonalize()
assert allclose(P*D, m*P)
def test_is_diagonalizable():
a, b, c = symbols('a b c')
m = Matrix(2, 2, [a, c, c, b])
assert m.is_symmetric()
assert m.is_diagonalizable()
assert not Matrix(2, 2, [1, 1, 0, 1]).is_diagonalizable()
m = Matrix(2, 2, [0, -1, 1, 0])
assert m.is_diagonalizable()
assert not m.is_diagonalizable(reals_only=True)
def test_jordan_form():
m = Matrix(3, 2, [-3, 1, -3, 20, 3, 10])
raises(NonSquareMatrixError, lambda: m.jordan_form())
# the next two tests test the cases where the old
# algorithm failed due to the fact that the block structure can
# *NOT* be determined from algebraic and geometric multiplicity alone
# This can be seen most easily when one lets compute the J.c.f. of a matrix that
# is in J.c.f already.
m = Matrix(4, 4, [2, 1, 0, 0,
0, 2, 1, 0,
0, 0, 2, 0,
0, 0, 0, 2
])
P, J = m.jordan_form()
assert m == J
m = 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 m == J
A = Matrix([[ 2, 4, 1, 0],
[-4, 2, 0, 1],
[ 0, 0, 2, 4],
[ 0, 0, -4, 2]])
P, J = A.jordan_form()
assert simplify(P*J*P.inv()) == A
assert Matrix(1, 1, [1]).jordan_form() == (Matrix([1]), Matrix([1]))
assert Matrix(1, 1, [1]).jordan_form(calc_transform=False) == Matrix([1])
# If we have eigenvalues in CRootOf form, raise errors
m = Matrix([[3, 0, 0, 0, -3], [0, -3, -3, 0, 3], [0, 3, 0, 3, 0], [0, 0, 3, 0, 3], [3, 0, 0, 3, 0]])
raises(MatrixError, lambda: m.jordan_form())
# make sure that if the input has floats, the output does too
m = Matrix([
[ 0.6875, 0.125 + 0.1875*sqrt(3)],
[0.125 + 0.1875*sqrt(3), 0.3125]])
P, J = m.jordan_form()
assert all(isinstance(x, Float) or x == 0 for x in P)
assert all(isinstance(x, Float) or x == 0 for x in J)
def test_singular_values():
x = Symbol('x', real=True)
A = Matrix([[0, 1*I], [2, 0]])
# if singular values can be sorted, they should be in decreasing order
assert A.singular_values() == [2, 1]
A = eye(3)
A[1, 1] = x
A[2, 2] = 5
vals = A.singular_values()
# since Abs(x) cannot be sorted, test set equality
assert set(vals) == {5, 1, Abs(x)}
A = Matrix([[sin(x), cos(x)], [-cos(x), sin(x)]])
vals = [sv.trigsimp() for sv in A.singular_values()]
assert vals == [S.One, S.One]
A = Matrix([
[2, 4],
[1, 3],
[0, 0],
[0, 0]
])
assert A.singular_values() == \
[sqrt(sqrt(221) + 15), sqrt(15 - sqrt(221))]
assert A.T.singular_values() == \
[sqrt(sqrt(221) + 15), sqrt(15 - sqrt(221)), 0, 0]
def test___eq__():
assert (Matrix(
[[0, 1, 1],
[1, 0, 0],
[1, 1, 1]]) == {}) is False
def test_definite():
# Examples from Gilbert Strang, "Introduction to Linear Algebra"
# Positive definite matrices
m = Matrix([[2, -1, 0], [-1, 2, -1], [0, -1, 2]])
assert m.is_positive_definite == True
assert m.is_positive_semidefinite == True
assert m.is_negative_definite == False
assert m.is_negative_semidefinite == False
assert m.is_indefinite == False
m = Matrix([[5, 4], [4, 5]])
assert m.is_positive_definite == True
assert m.is_positive_semidefinite == True
assert m.is_negative_definite == False
assert m.is_negative_semidefinite == False
assert m.is_indefinite == False
# Positive semidefinite matrices
m = Matrix([[2, -1, -1], [-1, 2, -1], [-1, -1, 2]])
assert m.is_positive_definite == False
assert m.is_positive_semidefinite == True
assert m.is_negative_definite == False
assert m.is_negative_semidefinite == False
assert m.is_indefinite == False
m = Matrix([[1, 2], [2, 4]])
assert m.is_positive_definite == False
assert m.is_positive_semidefinite == True
assert m.is_negative_definite == False
assert m.is_negative_semidefinite == False
assert m.is_indefinite == False
# Examples from Mathematica documentation
# Non-hermitian positive definite matrices
m = Matrix([[2, 3], [4, 8]])
assert m.is_positive_definite == True
assert m.is_positive_semidefinite == True
assert m.is_negative_definite == False
assert m.is_negative_semidefinite == False
assert m.is_indefinite == False
# Hermetian matrices
m = Matrix([[1, 2*I], [-I, 4]])
assert m.is_positive_definite == True
assert m.is_positive_semidefinite == True
assert m.is_negative_definite == False
assert m.is_negative_semidefinite == False
assert m.is_indefinite == False
# Symbolic matrices examples
a = Symbol('a', positive=True)
b = Symbol('b', negative=True)
m = Matrix([[a, 0, 0], [0, a, 0], [0, 0, a]])
assert m.is_positive_definite == True
assert m.is_positive_semidefinite == True
assert m.is_negative_definite == False
assert m.is_negative_semidefinite == False
assert m.is_indefinite == False
m = Matrix([[b, 0, 0], [0, b, 0], [0, 0, b]])
assert m.is_positive_definite == False
assert m.is_positive_semidefinite == False
assert m.is_negative_definite == True
assert m.is_negative_semidefinite == True
assert m.is_indefinite == False
m = Matrix([[a, 0], [0, b]])
assert m.is_positive_definite == False
assert m.is_positive_semidefinite == False
assert m.is_negative_definite == False
assert m.is_negative_semidefinite == False
assert m.is_indefinite == True
m = Matrix([
[0.0228202735623867, 0.00518748979085398,
-0.0743036351048907, -0.00709135324903921],
[0.00518748979085398, 0.0349045359786350,
0.0830317991056637, 0.00233147902806909],
[-0.0743036351048907, 0.0830317991056637,
1.15859676366277, 0.340359081555988],
[-0.00709135324903921, 0.00233147902806909,
0.340359081555988, 0.928147644848199]
])
assert m.is_positive_definite == True
assert m.is_positive_semidefinite == True
assert m.is_indefinite == False
# test for issue 19547: https://github.com/sympy/sympy/issues/19547
m = Matrix([
[0, 0, 0],
[0, 1, 2],
[0, 2, 1]
])
assert not m.is_positive_definite
assert not m.is_positive_semidefinite
def test_positive_semidefinite_cholesky():
from sympy.matrices.eigen import _is_positive_semidefinite_cholesky
m = Matrix([[0, 0, 0], [0, 0, 0], [0, 0, 0]])
assert _is_positive_semidefinite_cholesky(m) == True
m = Matrix([[0, 0, 0], [0, 5, -10*I], [0, 10*I, 5]])
assert _is_positive_semidefinite_cholesky(m) == False
m = Matrix([[1, 0, 0], [0, 0, 0], [0, 0, -1]])
assert _is_positive_semidefinite_cholesky(m) == False
m = Matrix([[0, 1], [1, 0]])
assert _is_positive_semidefinite_cholesky(m) == False
# https://www.value-at-risk.net/cholesky-factorization/
m = Matrix([[4, -2, -6], [-2, 10, 9], [-6, 9, 14]])
assert _is_positive_semidefinite_cholesky(m) == True
m = Matrix([[9, -3, 3], [-3, 2, 1], [3, 1, 6]])
assert _is_positive_semidefinite_cholesky(m) == True
m = Matrix([[4, -2, 2], [-2, 1, -1], [2, -1, 5]])
assert _is_positive_semidefinite_cholesky(m) == True
m = Matrix([[1, 2, -1], [2, 5, 1], [-1, 1, 9]])
assert _is_positive_semidefinite_cholesky(m) == False
def test_issue_20582():
A = Matrix([
[5, -5, -3, 2, -7],
[-2, -5, 0, 2, 1],
[-2, -7, -5, -2, -6],
[7, 10, 3, 9, -2],
[4, -10, 3, -8, -4]
])
# XXX Used dry-run test because arbitrary symbol that appears in
# CRootOf may not be unique.
assert A.eigenvects()
def test_issue_20275():
# XXX We use complex expansions because complex exponentials are not
# recognized by polys.domains
A = DFT(3).as_explicit().expand(complex=True)
eigenvects = A.eigenvects()
assert eigenvects[0] == (
-1, 1,
[Matrix([[1 - sqrt(3)], [1], [1]])]
)
assert eigenvects[1] == (
1, 1,
[Matrix([[1 + sqrt(3)], [1], [1]])]
)
assert eigenvects[2] == (
-I, 1,
[Matrix([[0], [-1], [1]])]
)
A = DFT(4).as_explicit().expand(complex=True)
eigenvects = A.eigenvects()
assert eigenvects[0] == (
-1, 1,
[Matrix([[-1], [1], [1], [1]])]
)
assert eigenvects[1] == (
1, 2,
[Matrix([[1], [0], [1], [0]]), Matrix([[2], [1], [0], [1]])]
)
assert eigenvects[2] == (
-I, 1,
[Matrix([[0], [-1], [0], [1]])]
)
# XXX We skip test for some parts of eigenvectors which are very
# complicated and fragile under expression tree changes
A = DFT(5).as_explicit().expand(complex=True)
eigenvects = A.eigenvects()
assert eigenvects[0] == (
-1, 1,
[Matrix([[1 - sqrt(5)], [1], [1], [1], [1]])]
)
assert eigenvects[1] == (
1, 2,
[Matrix([[S(1)/2 + sqrt(5)/2], [0], [1], [1], [0]]),
Matrix([[S(1)/2 + sqrt(5)/2], [1], [0], [0], [1]])]
)
def test_issue_20752():
b = symbols('b', nonzero=True)
m = Matrix([[0, 0, 0], [0, b, 0], [0, 0, b]])
assert m.is_positive_semidefinite is None
|
86c6efb51c8184bcd3c57eb6018a834e7edb96d19a9d3d4dc1851e7143c45621 | from sympy.core.function import expand_mul
from sympy.core.numbers import (I, Rational)
from sympy.core.singleton import S
from sympy.core.symbol import (Symbol, symbols)
from sympy.core.sympify import sympify
from sympy.simplify.simplify import simplify
from sympy.matrices.matrices import (ShapeError, NonSquareMatrixError)
from sympy.matrices import (
ImmutableMatrix, Matrix, eye, ones, ImmutableDenseMatrix, dotprodsimp)
from sympy.testing.pytest import raises
from sympy.matrices.common import NonInvertibleMatrixError
from sympy.solvers.solveset import linsolve
from sympy.abc import x, y
def test_issue_17247_expression_blowup_29():
M = Matrix(S('''[
[ -3/4, 45/32 - 37*I/16, 0, 0],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert M.gauss_jordan_solve(ones(4, 1)) == (Matrix(S('''[
[ -32549314808672/3306971225785 - 17397006745216*I/3306971225785],
[ 67439348256/3306971225785 - 9167503335872*I/3306971225785],
[-15091965363354518272/21217636514687010905 + 16890163109293858304*I/21217636514687010905],
[ -11328/952745 + 87616*I/952745]]''')), Matrix(0, 1, []))
def test_issue_17247_expression_blowup_30():
M = Matrix(S('''[
[ -3/4, 45/32 - 37*I/16, 0, 0],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert M.cholesky_solve(ones(4, 1)) == Matrix(S('''[
[ -32549314808672/3306971225785 - 17397006745216*I/3306971225785],
[ 67439348256/3306971225785 - 9167503335872*I/3306971225785],
[-15091965363354518272/21217636514687010905 + 16890163109293858304*I/21217636514687010905],
[ -11328/952745 + 87616*I/952745]]'''))
# @XFAIL # This calculation hangs with dotprodsimp.
# def test_issue_17247_expression_blowup_31():
# M = Matrix([
# [x + 1, 1 - x, 0, 0],
# [1 - x, x + 1, 0, x + 1],
# [ 0, 1 - x, x + 1, 0],
# [ 0, 0, 0, x + 1]])
# with dotprodsimp(True):
# assert M.LDLsolve(ones(4, 1)) == Matrix([
# [(x + 1)/(4*x)],
# [(x - 1)/(4*x)],
# [(x + 1)/(4*x)],
# [ 1/(x + 1)]])
def test_issue_17247_expression_blowup_32():
M = Matrix([
[x + 1, 1 - x, 0, 0],
[1 - x, x + 1, 0, x + 1],
[ 0, 1 - x, x + 1, 0],
[ 0, 0, 0, x + 1]])
with dotprodsimp(True):
assert M.LUsolve(ones(4, 1)) == Matrix([
[(x + 1)/(4*x)],
[(x - 1)/(4*x)],
[(x + 1)/(4*x)],
[ 1/(x + 1)]])
def test_LUsolve():
A = Matrix([[2, 3, 5],
[3, 6, 2],
[8, 3, 6]])
x = Matrix(3, 1, [3, 7, 5])
b = A*x
soln = A.LUsolve(b)
assert soln == x
A = Matrix([[0, -1, 2],
[5, 10, 7],
[8, 3, 4]])
x = Matrix(3, 1, [-1, 2, 5])
b = A*x
soln = A.LUsolve(b)
assert soln == x
A = Matrix([[2, 1], [1, 0], [1, 0]]) # issue 14548
b = Matrix([3, 1, 1])
assert A.LUsolve(b) == Matrix([1, 1])
b = Matrix([3, 1, 2]) # inconsistent
raises(ValueError, lambda: A.LUsolve(b))
A = Matrix([[0, -1, 2],
[5, 10, 7],
[8, 3, 4],
[2, 3, 5],
[3, 6, 2],
[8, 3, 6]])
x = Matrix([2, 1, -4])
b = A*x
soln = A.LUsolve(b)
assert soln == x
A = Matrix([[0, -1, 2], [5, 10, 7]]) # underdetermined
x = Matrix([-1, 2, 0])
b = A*x
raises(NotImplementedError, lambda: A.LUsolve(b))
A = Matrix(4, 4, lambda i, j: 1/(i+j+1) if i != 3 else 0)
b = Matrix.zeros(4, 1)
raises(NonInvertibleMatrixError, lambda: A.LUsolve(b))
def test_QRsolve():
A = Matrix([[2, 3, 5],
[3, 6, 2],
[8, 3, 6]])
x = Matrix(3, 1, [3, 7, 5])
b = A*x
soln = A.QRsolve(b)
assert soln == x
x = Matrix([[1, 2], [3, 4], [5, 6]])
b = A*x
soln = A.QRsolve(b)
assert soln == x
A = Matrix([[0, -1, 2],
[5, 10, 7],
[8, 3, 4]])
x = Matrix(3, 1, [-1, 2, 5])
b = A*x
soln = A.QRsolve(b)
assert soln == x
x = Matrix([[7, 8], [9, 10], [11, 12]])
b = A*x
soln = A.QRsolve(b)
assert soln == x
def test_errors():
raises(ShapeError, lambda: Matrix([1]).LUsolve(Matrix([[1, 2], [3, 4]])))
def test_cholesky_solve():
A = Matrix([[2, 3, 5],
[3, 6, 2],
[8, 3, 6]])
x = Matrix(3, 1, [3, 7, 5])
b = A*x
soln = A.cholesky_solve(b)
assert soln == x
A = Matrix([[0, -1, 2],
[5, 10, 7],
[8, 3, 4]])
x = Matrix(3, 1, [-1, 2, 5])
b = A*x
soln = A.cholesky_solve(b)
assert soln == x
A = Matrix(((1, 5), (5, 1)))
x = Matrix((4, -3))
b = A*x
soln = A.cholesky_solve(b)
assert soln == x
A = Matrix(((9, 3*I), (-3*I, 5)))
x = Matrix((-2, 1))
b = A*x
soln = A.cholesky_solve(b)
assert expand_mul(soln) == x
A = Matrix(((9*I, 3), (-3 + I, 5)))
x = Matrix((2 + 3*I, -1))
b = A*x
soln = A.cholesky_solve(b)
assert expand_mul(soln) == x
a00, a01, a11, b0, b1 = symbols('a00, a01, a11, b0, b1')
A = Matrix(((a00, a01), (a01, a11)))
b = Matrix((b0, b1))
x = A.cholesky_solve(b)
assert simplify(A*x) == b
def test_LDLsolve():
A = Matrix([[2, 3, 5],
[3, 6, 2],
[8, 3, 6]])
x = Matrix(3, 1, [3, 7, 5])
b = A*x
soln = A.LDLsolve(b)
assert soln == x
A = Matrix([[0, -1, 2],
[5, 10, 7],
[8, 3, 4]])
x = Matrix(3, 1, [-1, 2, 5])
b = A*x
soln = A.LDLsolve(b)
assert soln == x
A = Matrix(((9, 3*I), (-3*I, 5)))
x = Matrix((-2, 1))
b = A*x
soln = A.LDLsolve(b)
assert expand_mul(soln) == x
A = Matrix(((9*I, 3), (-3 + I, 5)))
x = Matrix((2 + 3*I, -1))
b = A*x
soln = A.LDLsolve(b)
assert expand_mul(soln) == x
A = Matrix(((9, 3), (3, 9)))
x = Matrix((1, 1))
b = A * x
soln = A.LDLsolve(b)
assert expand_mul(soln) == x
A = Matrix([[-5, -3, -4], [-3, -7, 7]])
x = Matrix([[8], [7], [-2]])
b = A * x
raises(NotImplementedError, lambda: A.LDLsolve(b))
def test_lower_triangular_solve():
raises(NonSquareMatrixError,
lambda: Matrix([1, 0]).lower_triangular_solve(Matrix([0, 1])))
raises(ShapeError,
lambda: Matrix([[1, 0], [0, 1]]).lower_triangular_solve(Matrix([1])))
raises(ValueError,
lambda: Matrix([[2, 1], [1, 2]]).lower_triangular_solve(
Matrix([[1, 0], [0, 1]])))
A = Matrix([[1, 0], [0, 1]])
B = Matrix([[x, y], [y, x]])
C = Matrix([[4, 8], [2, 9]])
assert A.lower_triangular_solve(B) == B
assert A.lower_triangular_solve(C) == C
def test_upper_triangular_solve():
raises(NonSquareMatrixError,
lambda: Matrix([1, 0]).upper_triangular_solve(Matrix([0, 1])))
raises(ShapeError,
lambda: Matrix([[1, 0], [0, 1]]).upper_triangular_solve(Matrix([1])))
raises(TypeError,
lambda: Matrix([[2, 1], [1, 2]]).upper_triangular_solve(
Matrix([[1, 0], [0, 1]])))
A = Matrix([[1, 0], [0, 1]])
B = Matrix([[x, y], [y, x]])
C = Matrix([[2, 4], [3, 8]])
assert A.upper_triangular_solve(B) == B
assert A.upper_triangular_solve(C) == C
def test_diagonal_solve():
raises(TypeError, lambda: Matrix([1, 1]).diagonal_solve(Matrix([1])))
A = Matrix([[1, 0], [0, 1]])*2
B = Matrix([[x, y], [y, x]])
assert A.diagonal_solve(B) == B/2
A = Matrix([[1, 0], [1, 2]])
raises(TypeError, lambda: A.diagonal_solve(B))
def test_pinv_solve():
# Fully determined system (unique result, identical to other solvers).
A = Matrix([[1, 5], [7, 9]])
B = Matrix([12, 13])
assert A.pinv_solve(B) == A.cholesky_solve(B)
assert A.pinv_solve(B) == A.LDLsolve(B)
assert A.pinv_solve(B) == Matrix([sympify('-43/26'), sympify('71/26')])
assert A * A.pinv() * B == B
# Fully determined, with two-dimensional B matrix.
B = Matrix([[12, 13, 14], [15, 16, 17]])
assert A.pinv_solve(B) == A.cholesky_solve(B)
assert A.pinv_solve(B) == A.LDLsolve(B)
assert A.pinv_solve(B) == Matrix([[-33, -37, -41], [69, 75, 81]]) / 26
assert A * A.pinv() * B == B
# Underdetermined system (infinite results).
A = Matrix([[1, 0, 1], [0, 1, 1]])
B = Matrix([5, 7])
solution = A.pinv_solve(B)
w = {}
for s in solution.atoms(Symbol):
# Extract dummy symbols used in the solution.
w[s.name] = s
assert solution == Matrix([[w['w0_0']/3 + w['w1_0']/3 - w['w2_0']/3 + 1],
[w['w0_0']/3 + w['w1_0']/3 - w['w2_0']/3 + 3],
[-w['w0_0']/3 - w['w1_0']/3 + w['w2_0']/3 + 4]])
assert A * A.pinv() * B == B
# Overdetermined system (least squares results).
A = Matrix([[1, 0], [0, 0], [0, 1]])
B = Matrix([3, 2, 1])
assert A.pinv_solve(B) == Matrix([3, 1])
# Proof the solution is not exact.
assert A * A.pinv() * B != B
def test_pinv_rank_deficient():
# Test the four properties of the pseudoinverse for various matrices.
As = [Matrix([[1, 1, 1], [2, 2, 2]]),
Matrix([[1, 0], [0, 0]]),
Matrix([[1, 2], [2, 4], [3, 6]])]
for A in As:
A_pinv = A.pinv(method="RD")
AAp = A * A_pinv
ApA = A_pinv * A
assert simplify(AAp * A) == A
assert simplify(ApA * A_pinv) == A_pinv
assert AAp.H == AAp
assert ApA.H == ApA
for A in As:
A_pinv = A.pinv(method="ED")
AAp = A * A_pinv
ApA = A_pinv * A
assert simplify(AAp * A) == A
assert simplify(ApA * A_pinv) == A_pinv
assert AAp.H == AAp
assert ApA.H == ApA
# Test solving with rank-deficient matrices.
A = Matrix([[1, 0], [0, 0]])
# Exact, non-unique solution.
B = Matrix([3, 0])
solution = A.pinv_solve(B)
w1 = solution.atoms(Symbol).pop()
assert w1.name == 'w1_0'
assert solution == Matrix([3, w1])
assert A * A.pinv() * B == B
# Least squares, non-unique solution.
B = Matrix([3, 1])
solution = A.pinv_solve(B)
w1 = solution.atoms(Symbol).pop()
assert w1.name == 'w1_0'
assert solution == Matrix([3, w1])
assert A * A.pinv() * B != B
def test_gauss_jordan_solve():
# Square, full rank, unique solution
A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 10]])
b = Matrix([3, 6, 9])
sol, params = A.gauss_jordan_solve(b)
assert sol == Matrix([[-1], [2], [0]])
assert params == Matrix(0, 1, [])
# Square, full rank, unique solution, B has more columns than rows
A = eye(3)
B = Matrix([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
sol, params = A.gauss_jordan_solve(B)
assert sol == B
assert params == Matrix(0, 4, [])
# Square, reduced rank, parametrized solution
A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
b = Matrix([3, 6, 9])
sol, params, freevar = A.gauss_jordan_solve(b, freevar=True)
w = {}
for s in sol.atoms(Symbol):
# Extract dummy symbols used in the solution.
w[s.name] = s
assert sol == Matrix([[w['tau0'] - 1], [-2*w['tau0'] + 2], [w['tau0']]])
assert params == Matrix([[w['tau0']]])
assert freevar == [2]
# Square, reduced rank, parametrized solution, B has two columns
A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
B = Matrix([[3, 4], [6, 8], [9, 12]])
sol, params, freevar = A.gauss_jordan_solve(B, freevar=True)
w = {}
for s in sol.atoms(Symbol):
# Extract dummy symbols used in the solution.
w[s.name] = s
assert sol == Matrix([[w['tau0'] - 1, w['tau1'] - Rational(4, 3)],
[-2*w['tau0'] + 2, -2*w['tau1'] + Rational(8, 3)],
[w['tau0'], w['tau1']],])
assert params == Matrix([[w['tau0'], w['tau1']]])
assert freevar == [2]
# Square, reduced rank, parametrized solution
A = Matrix([[1, 2, 3], [2, 4, 6], [3, 6, 9]])
b = Matrix([0, 0, 0])
sol, params = A.gauss_jordan_solve(b)
w = {}
for s in sol.atoms(Symbol):
w[s.name] = s
assert sol == Matrix([[-2*w['tau0'] - 3*w['tau1']],
[w['tau0']], [w['tau1']]])
assert params == Matrix([[w['tau0']], [w['tau1']]])
# Square, reduced rank, parametrized solution
A = Matrix([[0, 0, 0], [0, 0, 0], [0, 0, 0]])
b = Matrix([0, 0, 0])
sol, params = A.gauss_jordan_solve(b)
w = {}
for s in sol.atoms(Symbol):
w[s.name] = s
assert sol == Matrix([[w['tau0']], [w['tau1']], [w['tau2']]])
assert params == Matrix([[w['tau0']], [w['tau1']], [w['tau2']]])
# Square, reduced rank, no solution
A = Matrix([[1, 2, 3], [2, 4, 6], [3, 6, 9]])
b = Matrix([0, 0, 1])
raises(ValueError, lambda: A.gauss_jordan_solve(b))
# Rectangular, tall, full rank, unique solution
A = Matrix([[1, 5, 3], [2, 1, 6], [1, 7, 9], [1, 4, 3]])
b = Matrix([0, 0, 1, 0])
sol, params = A.gauss_jordan_solve(b)
assert sol == Matrix([[Rational(-1, 2)], [0], [Rational(1, 6)]])
assert params == Matrix(0, 1, [])
# Rectangular, tall, full rank, unique solution, B has less columns than rows
A = Matrix([[1, 5, 3], [2, 1, 6], [1, 7, 9], [1, 4, 3]])
B = Matrix([[0,0], [0, 0], [1, 2], [0, 0]])
sol, params = A.gauss_jordan_solve(B)
assert sol == Matrix([[Rational(-1, 2), Rational(-2, 2)], [0, 0], [Rational(1, 6), Rational(2, 6)]])
assert params == Matrix(0, 2, [])
# Rectangular, tall, full rank, no solution
A = Matrix([[1, 5, 3], [2, 1, 6], [1, 7, 9], [1, 4, 3]])
b = Matrix([0, 0, 0, 1])
raises(ValueError, lambda: A.gauss_jordan_solve(b))
# Rectangular, tall, full rank, no solution, B has two columns (2nd has no solution)
A = Matrix([[1, 5, 3], [2, 1, 6], [1, 7, 9], [1, 4, 3]])
B = Matrix([[0,0], [0, 0], [1, 0], [0, 1]])
raises(ValueError, lambda: A.gauss_jordan_solve(B))
# Rectangular, tall, full rank, no solution, B has two columns (1st has no solution)
A = Matrix([[1, 5, 3], [2, 1, 6], [1, 7, 9], [1, 4, 3]])
B = Matrix([[0,0], [0, 0], [0, 1], [1, 0]])
raises(ValueError, lambda: A.gauss_jordan_solve(B))
# Rectangular, tall, reduced rank, parametrized solution
A = Matrix([[1, 5, 3], [2, 10, 6], [3, 15, 9], [1, 4, 3]])
b = Matrix([0, 0, 0, 1])
sol, params = A.gauss_jordan_solve(b)
w = {}
for s in sol.atoms(Symbol):
w[s.name] = s
assert sol == Matrix([[-3*w['tau0'] + 5], [-1], [w['tau0']]])
assert params == Matrix([[w['tau0']]])
# Rectangular, tall, reduced rank, no solution
A = Matrix([[1, 5, 3], [2, 10, 6], [3, 15, 9], [1, 4, 3]])
b = Matrix([0, 0, 1, 1])
raises(ValueError, lambda: A.gauss_jordan_solve(b))
# Rectangular, wide, full rank, parametrized solution
A = Matrix([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 1, 12]])
b = Matrix([1, 1, 1])
sol, params = A.gauss_jordan_solve(b)
w = {}
for s in sol.atoms(Symbol):
w[s.name] = s
assert sol == Matrix([[2*w['tau0'] - 1], [-3*w['tau0'] + 1], [0],
[w['tau0']]])
assert params == Matrix([[w['tau0']]])
# Rectangular, wide, reduced rank, parametrized solution
A = Matrix([[1, 2, 3, 4], [5, 6, 7, 8], [2, 4, 6, 8]])
b = Matrix([0, 1, 0])
sol, params = A.gauss_jordan_solve(b)
w = {}
for s in sol.atoms(Symbol):
w[s.name] = s
assert sol == Matrix([[w['tau0'] + 2*w['tau1'] + S.Half],
[-2*w['tau0'] - 3*w['tau1'] - Rational(1, 4)],
[w['tau0']], [w['tau1']]])
assert params == Matrix([[w['tau0']], [w['tau1']]])
# watch out for clashing symbols
x0, x1, x2, _x0 = symbols('_tau0 _tau1 _tau2 tau1')
M = Matrix([[0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, _x0]])
A = M[:, :-1]
b = M[:, -1:]
sol, params = A.gauss_jordan_solve(b)
assert params == Matrix(3, 1, [x0, x1, x2])
assert sol == Matrix(5, 1, [x0, 0, x1, _x0, x2])
# Rectangular, wide, reduced rank, no solution
A = Matrix([[1, 2, 3, 4], [5, 6, 7, 8], [2, 4, 6, 8]])
b = Matrix([1, 1, 1])
raises(ValueError, lambda: A.gauss_jordan_solve(b))
# Test for immutable matrix
A = ImmutableMatrix([[1, 0], [0, 1]])
B = ImmutableMatrix([1, 2])
sol, params = A.gauss_jordan_solve(B)
assert sol == ImmutableMatrix([1, 2])
assert params == ImmutableMatrix(0, 1, [])
assert sol.__class__ == ImmutableDenseMatrix
assert params.__class__ == ImmutableDenseMatrix
# Test placement of free variables
A = Matrix([[1, 0, 0, 0], [0, 0, 0, 1]])
b = Matrix([1, 1])
sol, params = A.gauss_jordan_solve(b)
w = {}
for s in sol.atoms(Symbol):
w[s.name] = s
assert sol == Matrix([[1], [w['tau0']], [w['tau1']], [1]])
assert params == Matrix([[w['tau0']], [w['tau1']]])
def test_linsolve_underdetermined_AND_gauss_jordan_solve():
#Test placement of free variables as per issue 19815
A = Matrix([[1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1]])
B = Matrix([1, 2, 1, 1, 1, 1, 1, 2])
sol, params = A.gauss_jordan_solve(B)
w = {}
for s in sol.atoms(Symbol):
w[s.name] = s
assert params == Matrix([[w['tau0']], [w['tau1']], [w['tau2']],
[w['tau3']], [w['tau4']], [w['tau5']]])
assert sol == Matrix([[1 - 1*w['tau2']],
[w['tau2']],
[1 - 1*w['tau0'] + w['tau1']],
[w['tau0']],
[w['tau3'] + w['tau4']],
[-1*w['tau3'] - 1*w['tau4'] - 1*w['tau1']],
[1 - 1*w['tau2']],
[w['tau1']],
[w['tau2']],
[w['tau3']],
[w['tau4']],
[1 - 1*w['tau5']],
[w['tau5']],
[1]])
from sympy.abc import j,f
# https://github.com/sympy/sympy/issues/20046
A = Matrix([
[1, 1, 1, 1, 1, 1, 1, 1, 1],
[0, -1, 0, -1, 0, -1, 0, -1, -j],
[0, 0, 0, 0, 1, 1, 1, 1, f]
])
sol_1=Matrix(list(linsolve(A))[0])
tau0, tau1, tau2, tau3, tau4 = symbols('tau:5')
assert sol_1 == Matrix([[-f - j - tau0 + tau2 + tau4 + 1],
[j - tau1 - tau2 - tau4],
[tau0],
[tau1],
[f - tau2 - tau3 - tau4],
[tau2],
[tau3],
[tau4]])
# https://github.com/sympy/sympy/issues/19815
sol_2 = A[:, : -1 ] * sol_1 - A[:, -1 ]
assert sol_2 == Matrix([[0], [0], [0]])
def test_solve():
A = Matrix([[1,2], [2,4]])
b = Matrix([[3], [4]])
raises(ValueError, lambda: A.solve(b)) #no solution
b = Matrix([[ 4], [8]])
raises(ValueError, lambda: A.solve(b)) #infinite solution
|
977227359c65ea16d9c1d7db0a8d825eb2c8f8aeff7f061e4c5a7571f3693dd1 | from sympy.assumptions import Q
from sympy.core.expr import Expr
from sympy.core.add import Add
from sympy.core.function import Function
from sympy.core.kind import NumberKind, UndefinedKind
from sympy.core.numbers import I, Integer, oo, pi, Rational
from sympy.core.singleton import S
from sympy.core.symbol import Symbol, symbols
from sympy.functions.elementary.complexes import Abs
from sympy.functions.elementary.exponential import exp
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import cos, sin
from sympy.matrices.common import (ShapeError, NonSquareMatrixError,
_MinimalMatrix, _CastableMatrix, MatrixShaping, MatrixProperties,
MatrixOperations, MatrixArithmetic, MatrixSpecial, MatrixKind)
from sympy.matrices.matrices import MatrixCalculus
from sympy.matrices import (Matrix, diag, eye,
matrix_multiply_elementwise, ones, zeros, SparseMatrix, banded,
MutableDenseMatrix, MutableSparseMatrix, ImmutableDenseMatrix,
ImmutableSparseMatrix)
from sympy.polys.polytools import Poly
from sympy.utilities.iterables import flatten
from sympy.testing.pytest import raises, XFAIL, warns_deprecated_sympy
from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArray as Array
from sympy.abc import x, y, z
# classes to test the basic matrix classes
class ShapingOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixShaping):
pass
def eye_Shaping(n):
return ShapingOnlyMatrix(n, n, lambda i, j: int(i == j))
def zeros_Shaping(n):
return ShapingOnlyMatrix(n, n, lambda i, j: 0)
class PropertiesOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixProperties):
pass
def eye_Properties(n):
return PropertiesOnlyMatrix(n, n, lambda i, j: int(i == j))
def zeros_Properties(n):
return PropertiesOnlyMatrix(n, n, lambda i, j: 0)
class OperationsOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixOperations):
pass
def eye_Operations(n):
return OperationsOnlyMatrix(n, n, lambda i, j: int(i == j))
def zeros_Operations(n):
return OperationsOnlyMatrix(n, n, lambda i, j: 0)
class ArithmeticOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixArithmetic):
pass
def eye_Arithmetic(n):
return ArithmeticOnlyMatrix(n, n, lambda i, j: int(i == j))
def zeros_Arithmetic(n):
return ArithmeticOnlyMatrix(n, n, lambda i, j: 0)
class SpecialOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixSpecial):
pass
class CalculusOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixCalculus):
pass
def test__MinimalMatrix():
x = _MinimalMatrix(2, 3, [1, 2, 3, 4, 5, 6])
assert x.rows == 2
assert x.cols == 3
assert x[2] == 3
assert x[1, 1] == 5
assert list(x) == [1, 2, 3, 4, 5, 6]
assert list(x[1, :]) == [4, 5, 6]
assert list(x[:, 1]) == [2, 5]
assert list(x[:, :]) == list(x)
assert x[:, :] == x
assert _MinimalMatrix(x) == x
assert _MinimalMatrix([[1, 2, 3], [4, 5, 6]]) == x
assert _MinimalMatrix(([1, 2, 3], [4, 5, 6])) == x
assert _MinimalMatrix([(1, 2, 3), (4, 5, 6)]) == x
assert _MinimalMatrix(((1, 2, 3), (4, 5, 6))) == x
assert not (_MinimalMatrix([[1, 2], [3, 4], [5, 6]]) == x)
def test_kind():
assert Matrix([[1, 2], [3, 4]]).kind == MatrixKind(NumberKind)
assert Matrix([[0, 0], [0, 0]]).kind == MatrixKind(NumberKind)
assert Matrix(0, 0, []).kind == MatrixKind(NumberKind)
assert Matrix([[x]]).kind == MatrixKind(NumberKind)
assert Matrix([[1, Matrix([[1]])]]).kind == MatrixKind(UndefinedKind)
assert SparseMatrix([[1]]).kind == MatrixKind(NumberKind)
assert SparseMatrix([[1, Matrix([[1]])]]).kind == MatrixKind(UndefinedKind)
# ShapingOnlyMatrix tests
def test_vec():
m = ShapingOnlyMatrix(2, 2, [1, 3, 2, 4])
m_vec = m.vec()
assert m_vec.cols == 1
for i in range(4):
assert m_vec[i] == i + 1
def test_todok():
a, b, c, d = symbols('a:d')
m1 = MutableDenseMatrix([[a, b], [c, d]])
m2 = ImmutableDenseMatrix([[a, b], [c, d]])
m3 = MutableSparseMatrix([[a, b], [c, d]])
m4 = ImmutableSparseMatrix([[a, b], [c, d]])
assert m1.todok() == m2.todok() == m3.todok() == m4.todok() == \
{(0, 0): a, (0, 1): b, (1, 0): c, (1, 1): d}
def test_tolist():
lst = [[S.One, S.Half, x*y, S.Zero], [x, y, z, x**2], [y, -S.One, z*x, 3]]
flat_lst = [S.One, S.Half, x*y, S.Zero, x, y, z, x**2, y, -S.One, z*x, 3]
m = ShapingOnlyMatrix(3, 4, flat_lst)
assert m.tolist() == lst
def test_todod():
m = ShapingOnlyMatrix(3, 2, [[S.One, 0], [0, S.Half], [x, 0]])
dict = {0: {0: S.One}, 1: {1: S.Half}, 2: {0: x}}
assert m.todod() == dict
def test_row_col_del():
e = ShapingOnlyMatrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9])
raises(IndexError, lambda: e.row_del(5))
raises(IndexError, lambda: e.row_del(-5))
raises(IndexError, lambda: e.col_del(5))
raises(IndexError, lambda: e.col_del(-5))
assert e.row_del(2) == e.row_del(-1) == Matrix([[1, 2, 3], [4, 5, 6]])
assert e.col_del(2) == e.col_del(-1) == Matrix([[1, 2], [4, 5], [7, 8]])
assert e.row_del(1) == e.row_del(-2) == Matrix([[1, 2, 3], [7, 8, 9]])
assert e.col_del(1) == e.col_del(-2) == Matrix([[1, 3], [4, 6], [7, 9]])
def test_get_diag_blocks1():
a = Matrix([[1, 2], [2, 3]])
b = Matrix([[3, x], [y, 3]])
c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]])
assert a.get_diag_blocks() == [a]
assert b.get_diag_blocks() == [b]
assert c.get_diag_blocks() == [c]
def test_get_diag_blocks2():
a = Matrix([[1, 2], [2, 3]])
b = Matrix([[3, x], [y, 3]])
c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]])
A, B, C, D = diag(a, b, b), diag(a, b, c), diag(a, c, b), diag(c, c, b)
A = ShapingOnlyMatrix(A.rows, A.cols, A)
B = ShapingOnlyMatrix(B.rows, B.cols, B)
C = ShapingOnlyMatrix(C.rows, C.cols, C)
D = ShapingOnlyMatrix(D.rows, D.cols, D)
assert A.get_diag_blocks() == [a, b, b]
assert B.get_diag_blocks() == [a, b, c]
assert C.get_diag_blocks() == [a, c, b]
assert D.get_diag_blocks() == [c, c, b]
def test_shape():
m = ShapingOnlyMatrix(1, 2, [0, 0])
m.shape == (1, 2)
def test_reshape():
m0 = eye_Shaping(3)
assert m0.reshape(1, 9) == Matrix(1, 9, (1, 0, 0, 0, 1, 0, 0, 0, 1))
m1 = ShapingOnlyMatrix(3, 4, lambda i, j: i + j)
assert m1.reshape(
4, 3) == Matrix(((0, 1, 2), (3, 1, 2), (3, 4, 2), (3, 4, 5)))
assert m1.reshape(2, 6) == Matrix(((0, 1, 2, 3, 1, 2), (3, 4, 2, 3, 4, 5)))
def test_row_col():
m = ShapingOnlyMatrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9])
assert m.row(0) == Matrix(1, 3, [1, 2, 3])
assert m.col(0) == Matrix(3, 1, [1, 4, 7])
def test_row_join():
assert eye_Shaping(3).row_join(Matrix([7, 7, 7])) == \
Matrix([[1, 0, 0, 7],
[0, 1, 0, 7],
[0, 0, 1, 7]])
def test_col_join():
assert eye_Shaping(3).col_join(Matrix([[7, 7, 7]])) == \
Matrix([[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
[7, 7, 7]])
def test_row_insert():
r4 = Matrix([[4, 4, 4]])
for i in range(-4, 5):
l = [1, 0, 0]
l.insert(i, 4)
assert flatten(eye_Shaping(3).row_insert(i, r4).col(0).tolist()) == l
def test_col_insert():
c4 = Matrix([4, 4, 4])
for i in range(-4, 5):
l = [0, 0, 0]
l.insert(i, 4)
assert flatten(zeros_Shaping(3).col_insert(i, c4).row(0).tolist()) == l
# issue 13643
assert eye_Shaping(6).col_insert(3, Matrix([[2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2]])) == \
Matrix([[1, 0, 0, 2, 2, 0, 0, 0],
[0, 1, 0, 2, 2, 0, 0, 0],
[0, 0, 1, 2, 2, 0, 0, 0],
[0, 0, 0, 2, 2, 1, 0, 0],
[0, 0, 0, 2, 2, 0, 1, 0],
[0, 0, 0, 2, 2, 0, 0, 1]])
def test_extract():
m = ShapingOnlyMatrix(4, 3, lambda i, j: i*3 + j)
assert m.extract([0, 1, 3], [0, 1]) == Matrix(3, 2, [0, 1, 3, 4, 9, 10])
assert m.extract([0, 3], [0, 0, 2]) == Matrix(2, 3, [0, 0, 2, 9, 9, 11])
assert m.extract(range(4), range(3)) == m
raises(IndexError, lambda: m.extract([4], [0]))
raises(IndexError, lambda: m.extract([0], [3]))
def test_hstack():
m = ShapingOnlyMatrix(4, 3, lambda i, j: i*3 + j)
m2 = ShapingOnlyMatrix(3, 4, lambda i, j: i*3 + j)
assert m == m.hstack(m)
assert m.hstack(m, m, m) == ShapingOnlyMatrix.hstack(m, m, m) == Matrix([
[0, 1, 2, 0, 1, 2, 0, 1, 2],
[3, 4, 5, 3, 4, 5, 3, 4, 5],
[6, 7, 8, 6, 7, 8, 6, 7, 8],
[9, 10, 11, 9, 10, 11, 9, 10, 11]])
raises(ShapeError, lambda: m.hstack(m, m2))
assert Matrix.hstack() == Matrix()
# test regression #12938
M1 = Matrix.zeros(0, 0)
M2 = Matrix.zeros(0, 1)
M3 = Matrix.zeros(0, 2)
M4 = Matrix.zeros(0, 3)
m = ShapingOnlyMatrix.hstack(M1, M2, M3, M4)
assert m.rows == 0 and m.cols == 6
def test_vstack():
m = ShapingOnlyMatrix(4, 3, lambda i, j: i*3 + j)
m2 = ShapingOnlyMatrix(3, 4, lambda i, j: i*3 + j)
assert m == m.vstack(m)
assert m.vstack(m, m, m) == ShapingOnlyMatrix.vstack(m, m, m) == Matrix([
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[9, 10, 11],
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[9, 10, 11],
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[9, 10, 11]])
raises(ShapeError, lambda: m.vstack(m, m2))
assert Matrix.vstack() == Matrix()
# PropertiesOnlyMatrix tests
def test_atoms():
m = PropertiesOnlyMatrix(2, 2, [1, 2, x, 1 - 1/x])
assert m.atoms() == {S.One, S(2), S.NegativeOne, x}
assert m.atoms(Symbol) == {x}
def test_free_symbols():
assert PropertiesOnlyMatrix([[x], [0]]).free_symbols == {x}
def test_has():
A = PropertiesOnlyMatrix(((x, y), (2, 3)))
assert A.has(x)
assert not A.has(z)
assert A.has(Symbol)
A = PropertiesOnlyMatrix(((2, y), (2, 3)))
assert not A.has(x)
def test_is_anti_symmetric():
x = symbols('x')
assert PropertiesOnlyMatrix(2, 1, [1, 2]).is_anti_symmetric() is False
m = PropertiesOnlyMatrix(3, 3, [0, x**2 + 2*x + 1, y, -(x + 1)**2, 0, x*y, -y, -x*y, 0])
assert m.is_anti_symmetric() is True
assert m.is_anti_symmetric(simplify=False) is False
assert m.is_anti_symmetric(simplify=lambda x: x) is False
m = PropertiesOnlyMatrix(3, 3, [x.expand() for x in m])
assert m.is_anti_symmetric(simplify=False) is True
m = PropertiesOnlyMatrix(3, 3, [x.expand() for x in [S.One] + list(m)[1:]])
assert m.is_anti_symmetric() is False
def test_diagonal_symmetrical():
m = PropertiesOnlyMatrix(2, 2, [0, 1, 1, 0])
assert not m.is_diagonal()
assert m.is_symmetric()
assert m.is_symmetric(simplify=False)
m = PropertiesOnlyMatrix(2, 2, [1, 0, 0, 1])
assert m.is_diagonal()
m = PropertiesOnlyMatrix(3, 3, diag(1, 2, 3))
assert m.is_diagonal()
assert m.is_symmetric()
m = PropertiesOnlyMatrix(3, 3, [1, 0, 0, 0, 2, 0, 0, 0, 3])
assert m == diag(1, 2, 3)
m = PropertiesOnlyMatrix(2, 3, zeros(2, 3))
assert not m.is_symmetric()
assert m.is_diagonal()
m = PropertiesOnlyMatrix(((5, 0), (0, 6), (0, 0)))
assert m.is_diagonal()
m = PropertiesOnlyMatrix(((5, 0, 0), (0, 6, 0)))
assert m.is_diagonal()
m = Matrix(3, 3, [1, x**2 + 2*x + 1, y, (x + 1)**2, 2, 0, y, 0, 3])
assert m.is_symmetric()
assert not m.is_symmetric(simplify=False)
assert m.expand().is_symmetric(simplify=False)
def test_is_hermitian():
a = PropertiesOnlyMatrix([[1, I], [-I, 1]])
assert a.is_hermitian
a = PropertiesOnlyMatrix([[2*I, I], [-I, 1]])
assert a.is_hermitian is False
a = PropertiesOnlyMatrix([[x, I], [-I, 1]])
assert a.is_hermitian is None
a = PropertiesOnlyMatrix([[x, 1], [-I, 1]])
assert a.is_hermitian is False
def test_is_Identity():
assert eye_Properties(3).is_Identity
assert not PropertiesOnlyMatrix(zeros(3)).is_Identity
assert not PropertiesOnlyMatrix(ones(3)).is_Identity
# issue 6242
assert not PropertiesOnlyMatrix([[1, 0, 0]]).is_Identity
def test_is_symbolic():
a = PropertiesOnlyMatrix([[x, x], [x, x]])
assert a.is_symbolic() is True
a = PropertiesOnlyMatrix([[1, 2, 3, 4], [5, 6, 7, 8]])
assert a.is_symbolic() is False
a = PropertiesOnlyMatrix([[1, 2, 3, 4], [5, 6, x, 8]])
assert a.is_symbolic() is True
a = PropertiesOnlyMatrix([[1, x, 3]])
assert a.is_symbolic() is True
a = PropertiesOnlyMatrix([[1, 2, 3]])
assert a.is_symbolic() is False
a = PropertiesOnlyMatrix([[1], [x], [3]])
assert a.is_symbolic() is True
a = PropertiesOnlyMatrix([[1], [2], [3]])
assert a.is_symbolic() is False
def test_is_upper():
a = PropertiesOnlyMatrix([[1, 2, 3]])
assert a.is_upper is True
a = PropertiesOnlyMatrix([[1], [2], [3]])
assert a.is_upper is False
def test_is_lower():
a = PropertiesOnlyMatrix([[1, 2, 3]])
assert a.is_lower is False
a = PropertiesOnlyMatrix([[1], [2], [3]])
assert a.is_lower is True
def test_is_square():
m = PropertiesOnlyMatrix([[1], [1]])
m2 = PropertiesOnlyMatrix([[2, 2], [2, 2]])
assert not m.is_square
assert m2.is_square
def test_is_symmetric():
m = PropertiesOnlyMatrix(2, 2, [0, 1, 1, 0])
assert m.is_symmetric()
m = PropertiesOnlyMatrix(2, 2, [0, 1, 0, 1])
assert not m.is_symmetric()
def test_is_hessenberg():
A = PropertiesOnlyMatrix([[3, 4, 1], [2, 4, 5], [0, 1, 2]])
assert A.is_upper_hessenberg
A = PropertiesOnlyMatrix(3, 3, [3, 2, 0, 4, 4, 1, 1, 5, 2])
assert A.is_lower_hessenberg
A = PropertiesOnlyMatrix(3, 3, [3, 2, -1, 4, 4, 1, 1, 5, 2])
assert A.is_lower_hessenberg is False
assert A.is_upper_hessenberg is False
A = PropertiesOnlyMatrix([[3, 4, 1], [2, 4, 5], [3, 1, 2]])
assert not A.is_upper_hessenberg
def test_is_zero():
assert PropertiesOnlyMatrix(0, 0, []).is_zero_matrix
assert PropertiesOnlyMatrix([[0, 0], [0, 0]]).is_zero_matrix
assert PropertiesOnlyMatrix(zeros(3, 4)).is_zero_matrix
assert not PropertiesOnlyMatrix(eye(3)).is_zero_matrix
assert PropertiesOnlyMatrix([[x, 0], [0, 0]]).is_zero_matrix == None
assert PropertiesOnlyMatrix([[x, 1], [0, 0]]).is_zero_matrix == False
a = Symbol('a', nonzero=True)
assert PropertiesOnlyMatrix([[a, 0], [0, 0]]).is_zero_matrix == False
def test_values():
assert set(PropertiesOnlyMatrix(2, 2, [0, 1, 2, 3]
).values()) == {1, 2, 3}
x = Symbol('x', real=True)
assert set(PropertiesOnlyMatrix(2, 2, [x, 0, 0, 1]
).values()) == {x, 1}
# OperationsOnlyMatrix tests
def test_applyfunc():
m0 = OperationsOnlyMatrix(eye(3))
assert m0.applyfunc(lambda x: 2*x) == eye(3)*2
assert m0.applyfunc(lambda x: 0) == zeros(3)
assert m0.applyfunc(lambda x: 1) == ones(3)
def test_adjoint():
dat = [[0, I], [1, 0]]
ans = OperationsOnlyMatrix([[0, 1], [-I, 0]])
assert ans.adjoint() == Matrix(dat)
def test_as_real_imag():
m1 = OperationsOnlyMatrix(2, 2, [1, 2, 3, 4])
m3 = OperationsOnlyMatrix(2, 2,
[1 + S.ImaginaryUnit, 2 + 2*S.ImaginaryUnit,
3 + 3*S.ImaginaryUnit, 4 + 4*S.ImaginaryUnit])
a, b = m3.as_real_imag()
assert a == m1
assert b == m1
def test_conjugate():
M = OperationsOnlyMatrix([[0, I, 5],
[1, 2, 0]])
assert M.T == Matrix([[0, 1],
[I, 2],
[5, 0]])
assert M.C == Matrix([[0, -I, 5],
[1, 2, 0]])
assert M.C == M.conjugate()
assert M.H == M.T.C
assert M.H == Matrix([[ 0, 1],
[-I, 2],
[ 5, 0]])
def test_doit():
a = OperationsOnlyMatrix([[Add(x, x, evaluate=False)]])
assert a[0] != 2*x
assert a.doit() == Matrix([[2*x]])
def test_evalf():
a = OperationsOnlyMatrix(2, 1, [sqrt(5), 6])
assert all(a.evalf()[i] == a[i].evalf() for i in range(2))
assert all(a.evalf(2)[i] == a[i].evalf(2) for i in range(2))
assert all(a.n(2)[i] == a[i].n(2) for i in range(2))
def test_expand():
m0 = OperationsOnlyMatrix([[x*(x + y), 2], [((x + y)*y)*x, x*(y + x*(x + y))]])
# Test if expand() returns a matrix
m1 = m0.expand()
assert m1 == Matrix(
[[x*y + x**2, 2], [x*y**2 + y*x**2, x*y + y*x**2 + x**3]])
a = Symbol('a', real=True)
assert OperationsOnlyMatrix(1, 1, [exp(I*a)]).expand(complex=True) == \
Matrix([cos(a) + I*sin(a)])
def test_refine():
m0 = OperationsOnlyMatrix([[Abs(x)**2, sqrt(x**2)],
[sqrt(x**2)*Abs(y)**2, sqrt(y**2)*Abs(x)**2]])
m1 = m0.refine(Q.real(x) & Q.real(y))
assert m1 == Matrix([[x**2, Abs(x)], [y**2*Abs(x), x**2*Abs(y)]])
m1 = m0.refine(Q.positive(x) & Q.positive(y))
assert m1 == Matrix([[x**2, x], [x*y**2, x**2*y]])
m1 = m0.refine(Q.negative(x) & Q.negative(y))
assert m1 == Matrix([[x**2, -x], [-x*y**2, -x**2*y]])
def test_replace():
F, G = symbols('F, G', cls=Function)
K = OperationsOnlyMatrix(2, 2, lambda i, j: G(i+j))
M = OperationsOnlyMatrix(2, 2, lambda i, j: F(i+j))
N = M.replace(F, G)
assert N == K
def test_replace_map():
F, G = symbols('F, G', cls=Function)
K = OperationsOnlyMatrix(2, 2, [(G(0), {F(0): G(0)}), (G(1), {F(1): G(1)}), (G(1), {F(1) \
: G(1)}), (G(2), {F(2): G(2)})])
M = OperationsOnlyMatrix(2, 2, lambda i, j: F(i+j))
N = M.replace(F, G, True)
assert N == K
def test_rot90():
A = Matrix([[1, 2], [3, 4]])
assert A == A.rot90(0) == A.rot90(4)
assert A.rot90(2) == A.rot90(-2) == A.rot90(6) == Matrix(((4, 3), (2, 1)))
assert A.rot90(3) == A.rot90(-1) == A.rot90(7) == Matrix(((2, 4), (1, 3)))
assert A.rot90() == A.rot90(-7) == A.rot90(-3) == Matrix(((3, 1), (4, 2)))
def test_simplify():
n = Symbol('n')
f = Function('f')
M = OperationsOnlyMatrix([[ 1/x + 1/y, (x + x*y) / x ],
[ (f(x) + y*f(x))/f(x), 2 * (1/n - cos(n * pi)/n) / pi ]])
assert M.simplify() == Matrix([[ (x + y)/(x * y), 1 + y ],
[ 1 + y, 2*((1 - 1*cos(pi*n))/(pi*n)) ]])
eq = (1 + x)**2
M = OperationsOnlyMatrix([[eq]])
assert M.simplify() == Matrix([[eq]])
assert M.simplify(ratio=oo) == Matrix([[eq.simplify(ratio=oo)]])
# https://github.com/sympy/sympy/issues/19353
m = Matrix([[30, 2], [3, 4]])
assert (1/(m.trace())).simplify() == Rational(1, 34)
def test_subs():
assert OperationsOnlyMatrix([[1, x], [x, 4]]).subs(x, 5) == Matrix([[1, 5], [5, 4]])
assert OperationsOnlyMatrix([[x, 2], [x + y, 4]]).subs([[x, -1], [y, -2]]) == \
Matrix([[-1, 2], [-3, 4]])
assert OperationsOnlyMatrix([[x, 2], [x + y, 4]]).subs([(x, -1), (y, -2)]) == \
Matrix([[-1, 2], [-3, 4]])
assert OperationsOnlyMatrix([[x, 2], [x + y, 4]]).subs({x: -1, y: -2}) == \
Matrix([[-1, 2], [-3, 4]])
assert OperationsOnlyMatrix([[x*y]]).subs({x: y - 1, y: x - 1}, simultaneous=True) == \
Matrix([[(x - 1)*(y - 1)]])
def test_trace():
M = OperationsOnlyMatrix([[1, 0, 0],
[0, 5, 0],
[0, 0, 8]])
assert M.trace() == 14
def test_xreplace():
assert OperationsOnlyMatrix([[1, x], [x, 4]]).xreplace({x: 5}) == \
Matrix([[1, 5], [5, 4]])
assert OperationsOnlyMatrix([[x, 2], [x + y, 4]]).xreplace({x: -1, y: -2}) == \
Matrix([[-1, 2], [-3, 4]])
def test_permute():
a = OperationsOnlyMatrix(3, 4, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
raises(IndexError, lambda: a.permute([[0, 5]]))
raises(ValueError, lambda: a.permute(Symbol('x')))
b = a.permute_rows([[0, 2], [0, 1]])
assert a.permute([[0, 2], [0, 1]]) == b == Matrix([
[5, 6, 7, 8],
[9, 10, 11, 12],
[1, 2, 3, 4]])
b = a.permute_cols([[0, 2], [0, 1]])
assert a.permute([[0, 2], [0, 1]], orientation='cols') == b ==\
Matrix([
[ 2, 3, 1, 4],
[ 6, 7, 5, 8],
[10, 11, 9, 12]])
b = a.permute_cols([[0, 2], [0, 1]], direction='backward')
assert a.permute([[0, 2], [0, 1]], orientation='cols', direction='backward') == b ==\
Matrix([
[ 3, 1, 2, 4],
[ 7, 5, 6, 8],
[11, 9, 10, 12]])
assert a.permute([1, 2, 0, 3]) == Matrix([
[5, 6, 7, 8],
[9, 10, 11, 12],
[1, 2, 3, 4]])
from sympy.combinatorics import Permutation
assert a.permute(Permutation([1, 2, 0, 3])) == Matrix([
[5, 6, 7, 8],
[9, 10, 11, 12],
[1, 2, 3, 4]])
def test_upper_triangular():
A = OperationsOnlyMatrix([
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]
])
R = A.upper_triangular(2)
assert R == OperationsOnlyMatrix([
[0, 0, 1, 1],
[0, 0, 0, 1],
[0, 0, 0, 0],
[0, 0, 0, 0]
])
R = A.upper_triangular(-2)
assert R == OperationsOnlyMatrix([
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[0, 1, 1, 1]
])
R = A.upper_triangular()
assert R == OperationsOnlyMatrix([
[1, 1, 1, 1],
[0, 1, 1, 1],
[0, 0, 1, 1],
[0, 0, 0, 1]
])
def test_lower_triangular():
A = OperationsOnlyMatrix([
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]
])
L = A.lower_triangular()
assert L == ArithmeticOnlyMatrix([
[1, 0, 0, 0],
[1, 1, 0, 0],
[1, 1, 1, 0],
[1, 1, 1, 1]])
L = A.lower_triangular(2)
assert L == ArithmeticOnlyMatrix([
[1, 1, 1, 0],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]
])
L = A.lower_triangular(-2)
assert L == ArithmeticOnlyMatrix([
[0, 0, 0, 0],
[0, 0, 0, 0],
[1, 0, 0, 0],
[1, 1, 0, 0]
])
# ArithmeticOnlyMatrix tests
def test_abs():
m = ArithmeticOnlyMatrix([[1, -2], [x, y]])
assert abs(m) == ArithmeticOnlyMatrix([[1, 2], [Abs(x), Abs(y)]])
def test_add():
m = ArithmeticOnlyMatrix([[1, 2, 3], [x, y, x], [2*y, -50, z*x]])
assert m + m == ArithmeticOnlyMatrix([[2, 4, 6], [2*x, 2*y, 2*x], [4*y, -100, 2*z*x]])
n = ArithmeticOnlyMatrix(1, 2, [1, 2])
raises(ShapeError, lambda: m + n)
def test_multiplication():
a = ArithmeticOnlyMatrix((
(1, 2),
(3, 1),
(0, 6),
))
b = ArithmeticOnlyMatrix((
(1, 2),
(3, 0),
))
raises(ShapeError, lambda: b*a)
raises(TypeError, lambda: a*{})
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
h = a.multiply_elementwise(c)
assert h == matrix_multiply_elementwise(a, c)
assert h[0, 0] == 7
assert h[0, 1] == 4
assert h[1, 0] == 18
assert h[1, 1] == 6
assert h[2, 0] == 0
assert h[2, 1] == 0
raises(ShapeError, lambda: a.multiply_elementwise(b))
c = b * Symbol("x")
assert isinstance(c, ArithmeticOnlyMatrix)
assert c[0, 0] == x
assert c[0, 1] == 2*x
assert c[1, 0] == 3*x
assert c[1, 1] == 0
c2 = x * b
assert c == c2
c = 5 * b
assert isinstance(c, ArithmeticOnlyMatrix)
assert c[0, 0] == 5
assert c[0, 1] == 2*5
assert c[1, 0] == 3*5
assert c[1, 1] == 0
try:
eval('c = 5 @ b')
except SyntaxError:
pass
else:
assert isinstance(c, ArithmeticOnlyMatrix)
assert c[0, 0] == 5
assert c[0, 1] == 2*5
assert c[1, 0] == 3*5
assert c[1, 1] == 0
# https://github.com/sympy/sympy/issues/22353
A = Matrix(ones(3, 1))
_h = -Rational(1, 2)
B = Matrix([_h, _h, _h])
assert A.multiply_elementwise(B) == Matrix([
[_h],
[_h],
[_h]])
def test_matmul():
a = Matrix([[1, 2], [3, 4]])
assert a.__matmul__(2) == NotImplemented
assert a.__rmatmul__(2) == NotImplemented
#This is done this way because @ is only supported in Python 3.5+
#To check 2@a case
try:
eval('2 @ a')
except SyntaxError:
pass
except TypeError: #TypeError is raised in case of NotImplemented is returned
pass
#Check a@2 case
try:
eval('a @ 2')
except SyntaxError:
pass
except TypeError: #TypeError is raised in case of NotImplemented is returned
pass
def test_non_matmul():
"""
Test that if explicitly specified as non-matrix, mul reverts
to scalar multiplication.
"""
class foo(Expr):
is_Matrix=False
is_MatrixLike=False
shape = (1, 1)
A = Matrix([[1, 2], [3, 4]])
b = foo()
assert b*A == Matrix([[b, 2*b], [3*b, 4*b]])
assert A*b == Matrix([[b, 2*b], [3*b, 4*b]])
def test_power():
raises(NonSquareMatrixError, lambda: Matrix((1, 2))**2)
A = ArithmeticOnlyMatrix([[2, 3], [4, 5]])
assert (A**5)[:] == (6140, 8097, 10796, 14237)
A = ArithmeticOnlyMatrix([[2, 1, 3], [4, 2, 4], [6, 12, 1]])
assert (A**3)[:] == (290, 262, 251, 448, 440, 368, 702, 954, 433)
assert A**0 == eye(3)
assert A**1 == A
assert (ArithmeticOnlyMatrix([[2]]) ** 100)[0, 0] == 2**100
assert ArithmeticOnlyMatrix([[1, 2], [3, 4]])**Integer(2) == ArithmeticOnlyMatrix([[7, 10], [15, 22]])
A = Matrix([[1,2],[4,5]])
assert A.pow(20, method='cayley') == A.pow(20, method='multiply')
def test_neg():
n = ArithmeticOnlyMatrix(1, 2, [1, 2])
assert -n == ArithmeticOnlyMatrix(1, 2, [-1, -2])
def test_sub():
n = ArithmeticOnlyMatrix(1, 2, [1, 2])
assert n - n == ArithmeticOnlyMatrix(1, 2, [0, 0])
def test_div():
n = ArithmeticOnlyMatrix(1, 2, [1, 2])
assert n/2 == ArithmeticOnlyMatrix(1, 2, [S.Half, S(2)/2])
# SpecialOnlyMatrix tests
def test_eye():
assert list(SpecialOnlyMatrix.eye(2, 2)) == [1, 0, 0, 1]
assert list(SpecialOnlyMatrix.eye(2)) == [1, 0, 0, 1]
assert type(SpecialOnlyMatrix.eye(2)) == SpecialOnlyMatrix
assert type(SpecialOnlyMatrix.eye(2, cls=Matrix)) == Matrix
def test_ones():
assert list(SpecialOnlyMatrix.ones(2, 2)) == [1, 1, 1, 1]
assert list(SpecialOnlyMatrix.ones(2)) == [1, 1, 1, 1]
assert SpecialOnlyMatrix.ones(2, 3) == Matrix([[1, 1, 1], [1, 1, 1]])
assert type(SpecialOnlyMatrix.ones(2)) == SpecialOnlyMatrix
assert type(SpecialOnlyMatrix.ones(2, cls=Matrix)) == Matrix
def test_zeros():
assert list(SpecialOnlyMatrix.zeros(2, 2)) == [0, 0, 0, 0]
assert list(SpecialOnlyMatrix.zeros(2)) == [0, 0, 0, 0]
assert SpecialOnlyMatrix.zeros(2, 3) == Matrix([[0, 0, 0], [0, 0, 0]])
assert type(SpecialOnlyMatrix.zeros(2)) == SpecialOnlyMatrix
assert type(SpecialOnlyMatrix.zeros(2, cls=Matrix)) == Matrix
def test_diag_make():
diag = SpecialOnlyMatrix.diag
a = Matrix([[1, 2], [2, 3]])
b = Matrix([[3, x], [y, 3]])
c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]])
assert diag(a, b, b) == Matrix([
[1, 2, 0, 0, 0, 0],
[2, 3, 0, 0, 0, 0],
[0, 0, 3, x, 0, 0],
[0, 0, y, 3, 0, 0],
[0, 0, 0, 0, 3, x],
[0, 0, 0, 0, y, 3],
])
assert diag(a, b, c) == Matrix([
[1, 2, 0, 0, 0, 0, 0],
[2, 3, 0, 0, 0, 0, 0],
[0, 0, 3, x, 0, 0, 0],
[0, 0, y, 3, 0, 0, 0],
[0, 0, 0, 0, 3, x, 3],
[0, 0, 0, 0, y, 3, z],
[0, 0, 0, 0, x, y, z],
])
assert diag(a, c, b) == Matrix([
[1, 2, 0, 0, 0, 0, 0],
[2, 3, 0, 0, 0, 0, 0],
[0, 0, 3, x, 3, 0, 0],
[0, 0, y, 3, z, 0, 0],
[0, 0, x, y, z, 0, 0],
[0, 0, 0, 0, 0, 3, x],
[0, 0, 0, 0, 0, y, 3],
])
a = Matrix([x, y, z])
b = Matrix([[1, 2], [3, 4]])
c = Matrix([[5, 6]])
# this "wandering diagonal" is what makes this
# a block diagonal where each block is independent
# of the others
assert diag(a, 7, b, c) == Matrix([
[x, 0, 0, 0, 0, 0],
[y, 0, 0, 0, 0, 0],
[z, 0, 0, 0, 0, 0],
[0, 7, 0, 0, 0, 0],
[0, 0, 1, 2, 0, 0],
[0, 0, 3, 4, 0, 0],
[0, 0, 0, 0, 5, 6]])
raises(ValueError, lambda: diag(a, 7, b, c, rows=5))
assert diag(1) == Matrix([[1]])
assert diag(1, rows=2) == Matrix([[1, 0], [0, 0]])
assert diag(1, cols=2) == Matrix([[1, 0], [0, 0]])
assert diag(1, rows=3, cols=2) == Matrix([[1, 0], [0, 0], [0, 0]])
assert diag(*[2, 3]) == Matrix([
[2, 0],
[0, 3]])
assert diag(Matrix([2, 3])) == Matrix([
[2],
[3]])
assert diag([1, [2, 3], 4], unpack=False) == \
diag([[1], [2, 3], [4]], unpack=False) == Matrix([
[1, 0],
[2, 3],
[4, 0]])
assert type(diag(1)) == SpecialOnlyMatrix
assert type(diag(1, cls=Matrix)) == Matrix
assert Matrix.diag([1, 2, 3]) == Matrix.diag(1, 2, 3)
assert Matrix.diag([1, 2, 3], unpack=False).shape == (3, 1)
assert Matrix.diag([[1, 2, 3]]).shape == (3, 1)
assert Matrix.diag([[1, 2, 3]], unpack=False).shape == (1, 3)
assert Matrix.diag([[[1, 2, 3]]]).shape == (1, 3)
# kerning can be used to move the starting point
assert Matrix.diag(ones(0, 2), 1, 2) == Matrix([
[0, 0, 1, 0],
[0, 0, 0, 2]])
assert Matrix.diag(ones(2, 0), 1, 2) == Matrix([
[0, 0],
[0, 0],
[1, 0],
[0, 2]])
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_jordan_block():
assert SpecialOnlyMatrix.jordan_block(3, 2) == SpecialOnlyMatrix.jordan_block(3, eigenvalue=2) \
== SpecialOnlyMatrix.jordan_block(size=3, eigenvalue=2) \
== SpecialOnlyMatrix.jordan_block(3, 2, band='upper') \
== SpecialOnlyMatrix.jordan_block(
size=3, eigenval=2, eigenvalue=2) \
== Matrix([
[2, 1, 0],
[0, 2, 1],
[0, 0, 2]])
assert SpecialOnlyMatrix.jordan_block(3, 2, band='lower') == Matrix([
[2, 0, 0],
[1, 2, 0],
[0, 1, 2]])
# missing eigenvalue
raises(ValueError, lambda: SpecialOnlyMatrix.jordan_block(2))
# non-integral size
raises(ValueError, lambda: SpecialOnlyMatrix.jordan_block(3.5, 2))
# size not specified
raises(ValueError, lambda: SpecialOnlyMatrix.jordan_block(eigenvalue=2))
# inconsistent eigenvalue
raises(ValueError,
lambda: SpecialOnlyMatrix.jordan_block(
eigenvalue=2, eigenval=4))
# Deprecated feature
with warns_deprecated_sympy():
assert (SpecialOnlyMatrix.jordan_block(cols=3, eigenvalue=2) ==
SpecialOnlyMatrix(3, 3, (2, 1, 0, 0, 2, 1, 0, 0, 2)))
with warns_deprecated_sympy():
assert (SpecialOnlyMatrix.jordan_block(rows=3, eigenvalue=2) ==
SpecialOnlyMatrix(3, 3, (2, 1, 0, 0, 2, 1, 0, 0, 2)))
with warns_deprecated_sympy():
assert SpecialOnlyMatrix.jordan_block(3, 2) == \
SpecialOnlyMatrix.jordan_block(cols=3, eigenvalue=2) == \
SpecialOnlyMatrix.jordan_block(rows=3, eigenvalue=2)
with warns_deprecated_sympy():
assert SpecialOnlyMatrix.jordan_block(
rows=4, cols=3, eigenvalue=2) == \
Matrix([
[2, 1, 0],
[0, 2, 1],
[0, 0, 2],
[0, 0, 0]])
# Using alias keyword
assert SpecialOnlyMatrix.jordan_block(size=3, eigenvalue=2) == \
SpecialOnlyMatrix.jordan_block(size=3, eigenval=2)
def test_orthogonalize():
m = Matrix([[1, 2], [3, 4]])
assert m.orthogonalize(Matrix([[2], [1]])) == [Matrix([[2], [1]])]
assert m.orthogonalize(Matrix([[2], [1]]), normalize=True) == \
[Matrix([[2*sqrt(5)/5], [sqrt(5)/5]])]
assert m.orthogonalize(Matrix([[1], [2]]), Matrix([[-1], [4]])) == \
[Matrix([[1], [2]]), Matrix([[Rational(-12, 5)], [Rational(6, 5)]])]
assert m.orthogonalize(Matrix([[0], [0]]), Matrix([[-1], [4]])) == \
[Matrix([[-1], [4]])]
assert m.orthogonalize(Matrix([[0], [0]])) == []
n = Matrix([[9, 1, 9], [3, 6, 10], [8, 5, 2]])
vecs = [Matrix([[-5], [1]]), Matrix([[-5], [2]]), Matrix([[-5], [-2]])]
assert n.orthogonalize(*vecs) == \
[Matrix([[-5], [1]]), Matrix([[Rational(5, 26)], [Rational(25, 26)]])]
vecs = [Matrix([0, 0, 0]), Matrix([1, 2, 3]), Matrix([1, 4, 5])]
raises(ValueError, lambda: Matrix.orthogonalize(*vecs, rankcheck=True))
vecs = [Matrix([1, 2, 3]), Matrix([4, 5, 6]), Matrix([7, 8, 9])]
raises(ValueError, lambda: Matrix.orthogonalize(*vecs, rankcheck=True))
def test_wilkinson():
wminus, wplus = Matrix.wilkinson(1)
assert wminus == Matrix([
[-1, 1, 0],
[1, 0, 1],
[0, 1, 1]])
assert wplus == Matrix([
[1, 1, 0],
[1, 0, 1],
[0, 1, 1]])
wminus, wplus = Matrix.wilkinson(3)
assert wminus == Matrix([
[-3, 1, 0, 0, 0, 0, 0],
[1, -2, 1, 0, 0, 0, 0],
[0, 1, -1, 1, 0, 0, 0],
[0, 0, 1, 0, 1, 0, 0],
[0, 0, 0, 1, 1, 1, 0],
[0, 0, 0, 0, 1, 2, 1],
[0, 0, 0, 0, 0, 1, 3]])
assert wplus == Matrix([
[3, 1, 0, 0, 0, 0, 0],
[1, 2, 1, 0, 0, 0, 0],
[0, 1, 1, 1, 0, 0, 0],
[0, 0, 1, 0, 1, 0, 0],
[0, 0, 0, 1, 1, 1, 0],
[0, 0, 0, 0, 1, 2, 1],
[0, 0, 0, 0, 0, 1, 3]])
# CalculusOnlyMatrix tests
@XFAIL
def test_diff():
x, y = symbols('x y')
m = CalculusOnlyMatrix(2, 1, [x, y])
# TODO: currently not working as ``_MinimalMatrix`` cannot be sympified:
assert m.diff(x) == Matrix(2, 1, [1, 0])
def test_integrate():
x, y = symbols('x y')
m = CalculusOnlyMatrix(2, 1, [x, y])
assert m.integrate(x) == Matrix(2, 1, [x**2/2, y*x])
def test_jacobian2():
rho, phi = symbols("rho,phi")
X = CalculusOnlyMatrix(3, 1, [rho*cos(phi), rho*sin(phi), rho**2])
Y = CalculusOnlyMatrix(2, 1, [rho, phi])
J = Matrix([
[cos(phi), -rho*sin(phi)],
[sin(phi), rho*cos(phi)],
[ 2*rho, 0],
])
assert X.jacobian(Y) == J
m = CalculusOnlyMatrix(2, 2, [1, 2, 3, 4])
m2 = CalculusOnlyMatrix(4, 1, [1, 2, 3, 4])
raises(TypeError, lambda: m.jacobian(Matrix([1, 2])))
raises(TypeError, lambda: m2.jacobian(m))
def test_limit():
x, y = symbols('x y')
m = CalculusOnlyMatrix(2, 1, [1/x, y])
assert m.limit(x, 5) == Matrix(2, 1, [Rational(1, 5), y])
def test_issue_13774():
M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
v = [1, 1, 1]
raises(TypeError, lambda: M*v)
raises(TypeError, lambda: v*M)
def test_companion():
x = Symbol('x')
y = Symbol('y')
raises(ValueError, lambda: Matrix.companion(1))
raises(ValueError, lambda: Matrix.companion(Poly([1], x)))
raises(ValueError, lambda: Matrix.companion(Poly([2, 1], x)))
raises(ValueError, lambda: Matrix.companion(Poly(x*y, [x, y])))
c0, c1, c2 = symbols('c0:3')
assert Matrix.companion(Poly([1, c0], x)) == Matrix([-c0])
assert Matrix.companion(Poly([1, c1, c0], x)) == \
Matrix([[0, -c0], [1, -c1]])
assert Matrix.companion(Poly([1, c2, c1, c0], x)) == \
Matrix([[0, 0, -c0], [1, 0, -c1], [0, 1, -c2]])
def test_issue_10589():
x, y, z = symbols("x, y z")
M1 = Matrix([x, y, z])
M1 = M1.subs(zip([x, y, z], [1, 2, 3]))
assert M1 == Matrix([[1], [2], [3]])
M2 = Matrix([[x, x, x, x, x], [x, x, x, x, x], [x, x, x, x, x]])
M2 = M2.subs(zip([x], [1]))
assert M2 == Matrix([[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]])
def test_rmul_pr19860():
class Foo(ImmutableDenseMatrix):
_op_priority = MutableDenseMatrix._op_priority + 0.01
a = Matrix(2, 2, [1, 2, 3, 4])
b = Foo(2, 2, [1, 2, 3, 4])
# This would throw a RecursionError: maximum recursion depth
# since b always has higher priority even after a.as_mutable()
c = a*b
assert isinstance(c, Foo)
assert c == Matrix([[7, 10], [15, 22]])
def test_issue_18956():
A = Array([[1, 2], [3, 4]])
B = Matrix([[1,2],[3,4]])
raises(TypeError, lambda: B + A)
raises(TypeError, lambda: A + B)
|
0001a3e634cb82d0ff23b75ac80b15327a7a94ef4ddee3f66533aab1a1da7803 | from sympy.testing.pytest import ignore_warnings
from sympy.utilities.exceptions import SymPyDeprecationWarning
with ignore_warnings(SymPyDeprecationWarning):
from sympy.matrices.densesolve import LU_solve, rref_solve, cholesky_solve
from sympy.core.symbol import Dummy
from sympy.polys.domains.rationalfield import QQ
def test_LU_solve():
x, y, z = Dummy('x'), Dummy('y'), Dummy('z')
assert LU_solve([[QQ(2), QQ(-1), QQ(-2)], [QQ(-4), QQ(6), QQ(3)], [QQ(-4), QQ(-2), QQ(8)]], [[x], [y], [z]], [[QQ(-1)], [QQ(13)], [QQ(-6)]], QQ) == [[QQ(2,1)], [QQ(3, 1)], [QQ(1, 1)]]
def test_cholesky_solve():
x, y, z = Dummy('x'), Dummy('y'), Dummy('z')
assert cholesky_solve([[QQ(25), QQ(15), QQ(-5)], [QQ(15), QQ(18), QQ(0)], [QQ(-5), QQ(0), QQ(11)]], [[x], [y], [z]], [[QQ(2)], [QQ(3)], [QQ(1)]], QQ) == [[QQ(-1, 225)], [QQ(23, 135)], [QQ(4, 45)]]
def test_rref_solve():
x, y, z = Dummy('x'), Dummy('y'), Dummy('z')
assert rref_solve([[QQ(25), QQ(15), QQ(-5)], [QQ(15), QQ(18), QQ(0)], [QQ(-5), QQ(0), QQ(11)]], [[x], [y], [z]], [[QQ(2)], [QQ(3)], [QQ(1)]], QQ) == [[QQ(-1, 225)], [QQ(23, 135)], [QQ(4, 45)]]
|
1af5cdea405595d8eaa11f1637c23f3e36e52a1466c915af56e2d4819120ba06 | from sympy.core.numbers import (Float, I, Rational)
from sympy.core.singleton import S
from sympy.core.symbol import (Symbol, symbols)
from sympy.functions.elementary.complexes import Abs
from sympy.polys.polytools import PurePoly
from sympy.matrices import \
Matrix, MutableSparseMatrix, ImmutableSparseMatrix, SparseMatrix, eye, \
ones, zeros, ShapeError, NonSquareMatrixError
from sympy.testing.pytest import raises
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 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 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.todok() == {(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]])
S.row_swap(0, 1)
assert S == SparseMatrix([
[1, 0, 0],
[0, 1, 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])
assert SparseMatrix([[1, 2, 3], [1, 2], [1]]) == Matrix([
[1, 2, 3],
[1, 2, 0],
[1, 0, 0]])
assert SparseMatrix(4, 4, {(1, 1): sparse_eye(2)}) == Matrix([
[0, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 0]])
raises(ValueError, lambda: SparseMatrix(1, 1, {(1, 1): 1}))
assert SparseMatrix(1, 2, [1, 2]).tolist() == [[1, 2]]
assert SparseMatrix(2, 2, [1, [2, 3]]).tolist() == [[1, 0], [2, 3]]
raises(ValueError, lambda: SparseMatrix(2, 2, [1]))
raises(ValueError, lambda: SparseMatrix(1, 1, [[1, 2]]))
assert SparseMatrix([.1]).has(Float)
# autosizing
assert SparseMatrix(None, {(0, 1): 0}).shape == (0, 0)
assert SparseMatrix(None, {(0, 1): 1}).shape == (1, 2)
assert SparseMatrix(None, None, {(0, 1): 1}).shape == (1, 2)
raises(ValueError, lambda: SparseMatrix(None, 1, [[1, 2]]))
raises(ValueError, lambda: SparseMatrix(1, None, [[1, 2]]))
raises(ValueError, lambda: SparseMatrix(3, 3, {(0, 0): ones(2), (1, 1): 2}))
# 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(( ( 3, 0, 0, 0),
(-2, 1, 0, 0),
( 0, -2, 5, 0),
( 5, 0, 3, 4) )).det() == 60
assert SparseMatrix(( ( 1, 0, 0, 0),
( 5, 0, 0, 0),
( 9, 10, 11, 0),
(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),
(0, 0, 0, 0, 3) )).det() == 243
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.todok()) == 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]
])
# row insert
assert a.row_insert(2, sparse_eye(2)) == SparseMatrix([
[1, 2 + I],
[3, 4],
[1, 0],
[0, 1]
])
# col insert
assert a.col_insert(2, SparseMatrix.zeros(2, 1)) == SparseMatrix([
[1, 2 + I, 0],
[3, 4, 0],
])
# symmetric
assert not a.is_symmetric(simplify=False)
# col op
M = SparseMatrix.eye(3)*2
M[1, 0] = -1
M.col_op(1, lambda v, i: v + 2*M[i, 0])
assert M == SparseMatrix([
[ 2, 4, 0],
[-1, 0, 0],
[ 0, 0, 2]
])
# fill
M = SparseMatrix.eye(3)
M.fill(2)
assert M == SparseMatrix([
[2, 2, 2],
[2, 2, 2],
[2, 2, 2],
])
# 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 test_scalar_multiply():
assert SparseMatrix([[1, 2]]).scalar_multiply(3) == SparseMatrix([[3, 6]])
def test_transpose():
assert SparseMatrix(((1, 2), (3, 4))).transpose() == \
SparseMatrix(((1, 3), (2, 4)))
def test_trace():
assert SparseMatrix(((1, 2), (3, 4))).trace() == 5
assert SparseMatrix(((0, 0), (0, 4))).trace() == 4
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 test_add():
assert SparseMatrix(((1, 0), (0, 1))) + SparseMatrix(((0, 1), (1, 0))) == \
SparseMatrix(((1, 1), (1, 1)))
a = SparseMatrix(100, 100, lambda i, j: int(j != 0 and i % j == 0))
b = SparseMatrix(100, 100, lambda i, j: int(i != 0 and j % i == 0))
assert (len(a.todok()) + len(b.todok()) - len((a + b).todok()) > 0)
def test_errors():
raises(ValueError, lambda: SparseMatrix(1.4, 2, lambda i, j: 0))
raises(TypeError, lambda: SparseMatrix([1, 2, 3], [1, 2]))
raises(ValueError, lambda: SparseMatrix([[1, 2], [3, 4]])[(1, 2, 3)])
raises(IndexError, lambda: SparseMatrix([[1, 2], [3, 4]])[5])
raises(ValueError, lambda: SparseMatrix([[1, 2], [3, 4]])[1, 2, 3])
raises(TypeError,
lambda: SparseMatrix([[1, 2], [3, 4]]).copyin_list([0, 1], set()))
raises(
IndexError, lambda: SparseMatrix([[1, 2], [3, 4]])[1, 2])
raises(TypeError, lambda: SparseMatrix([1, 2, 3]).cross(1))
raises(IndexError, lambda: SparseMatrix(1, 2, [1, 2])[3])
raises(ShapeError,
lambda: SparseMatrix(1, 2, [1, 2]) + SparseMatrix(2, 1, [2, 1]))
def test_len():
assert not SparseMatrix()
assert SparseMatrix() == SparseMatrix([])
assert SparseMatrix() == SparseMatrix([[]])
def test_sparse_zeros_sparse_eye():
assert SparseMatrix.eye(3) == eye(3, cls=SparseMatrix)
assert len(SparseMatrix.eye(3).todok()) == 3
assert SparseMatrix.zeros(3) == zeros(3, cls=SparseMatrix)
assert len(SparseMatrix.zeros(3).todok()) == 0
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_solve():
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([
[Rational(2, 3), Rational(1, 3), Rational(1, 6)],
[Rational(1, 3), Rational(2, 3), Rational(1, 3)],
[ 0, 0, S.Half]])
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]
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_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_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_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
|
45899fd9b2d6b64f27bb2209ba146948816496c7d5b4019ada0c7602f022d935 | import random
from sympy.core.numbers import I
from sympy.core.numbers import Rational
from sympy.core.symbol import (Symbol, symbols)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.polys.polytools import Poly
from sympy.matrices import Matrix, eye, ones
from sympy.abc import x, y, z
from sympy.testing.pytest import raises
from sympy.matrices.common import NonSquareMatrixError
from sympy.functions.combinatorial.factorials import factorial, subfactorial
def test_determinant():
M = Matrix()
assert M.det() == 1
# Evaluating these directly because they are never reached via M.det()
assert M._eval_det_bareiss() == 1
assert M._eval_det_berkowitz() == 1
assert M._eval_det_lu() == 1
M = Matrix([ [0] ])
assert M.det() == 0
assert M._eval_det_bareiss() == 0
assert M._eval_det_berkowitz() == 0
assert M._eval_det_lu() == 0
M = Matrix([ [5] ])
assert M.det() == 5
assert M._eval_det_bareiss() == 5
assert M._eval_det_berkowitz() == 5
assert M._eval_det_lu() == 5
M = Matrix(( (-3, 2),
( 8, -5) ))
assert M.det(method="domain-ge") == -1
assert M.det(method="bareiss") == -1
assert M.det(method="berkowitz") == -1
assert M.det(method="lu") == -1
M = Matrix(( (x, 1),
(y, 2*y) ))
assert M.det(method="domain-ge") == 2*x*y - y
assert M.det(method="bareiss") == 2*x*y - y
assert M.det(method="berkowitz") == 2*x*y - y
assert M.det(method="lu") == 2*x*y - y
M = Matrix(( (1, 1, 1),
(1, 2, 3),
(1, 3, 6) ))
assert M.det(method="domain-ge") == 1
assert M.det(method="bareiss") == 1
assert M.det(method="berkowitz") == 1
assert M.det(method="lu") == 1
M = Matrix(( ( 3, -2, 0, 5),
(-2, 1, -2, 2),
( 0, -2, 5, 0),
( 5, 0, 3, 4) ))
assert M.det(method="domain-ge") == -289
assert M.det(method="bareiss") == -289
assert M.det(method="berkowitz") == -289
assert M.det(method="lu") == -289
M = Matrix(( ( 1, 2, 3, 4),
( 5, 6, 7, 8),
( 9, 10, 11, 12),
(13, 14, 15, 16) ))
assert M.det(method="domain-ge") == 0
assert M.det(method="bareiss") == 0
assert M.det(method="berkowitz") == 0
assert M.det(method="lu") == 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="domain-ge") == 275
assert M.det(method="bareiss") == 275
assert M.det(method="berkowitz") == 275
assert M.det(method="lu") == 275
M = Matrix(( ( 3, 0, 0, 0),
(-2, 1, 0, 0),
( 0, -2, 5, 0),
( 5, 0, 3, 4) ))
assert M.det(method="domain-ge") == 60
assert M.det(method="bareiss") == 60
assert M.det(method="berkowitz") == 60
assert M.det(method="lu") == 60
M = Matrix(( ( 1, 0, 0, 0),
( 5, 0, 0, 0),
( 9, 10, 11, 0),
(13, 14, 15, 16) ))
assert M.det(method="domain-ge") == 0
assert M.det(method="bareiss") == 0
assert M.det(method="berkowitz") == 0
assert M.det(method="lu") == 0
M = Matrix(( (3, 2, 0, 0, 0),
(0, 3, 2, 0, 0),
(0, 0, 3, 2, 0),
(0, 0, 0, 3, 2),
(0, 0, 0, 0, 3) ))
assert M.det(method="domain-ge") == 243
assert M.det(method="bareiss") == 243
assert M.det(method="berkowitz") == 243
assert M.det(method="lu") == 243
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="domain-ge") == -55
assert M.det(method="bareiss") == -55
assert M.det(method="berkowitz") == -55
assert M.det(method="lu") == -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="domain-ge") == 11664
assert M.det(method="bareiss") == 11664
assert M.det(method="berkowitz") == 11664
assert M.det(method="lu") == 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="domain-ge") == 123
assert M.det(method="bareiss") == 123
assert M.det(method="berkowitz") == 123
assert M.det(method="lu") == 123
M = Matrix(( (x, y, z),
(1, 0, 0),
(y, z, x) ))
assert M.det(method="domain-ge") == z**2 - x*y
assert M.det(method="bareiss") == z**2 - x*y
assert M.det(method="berkowitz") == z**2 - x*y
assert M.det(method="lu") == z**2 - x*y
# issue 13835
a = symbols('a')
M = lambda n: Matrix([[i + a*j for i in range(n)]
for j in range(n)])
assert M(5).det() == 0
assert M(6).det() == 0
assert M(7).det() == 0
def test_issue_14517():
M = Matrix([
[ 0, 10*I, 10*I, 0],
[10*I, 0, 0, 10*I],
[10*I, 0, 5 + 2*I, 10*I],
[ 0, 10*I, 10*I, 5 + 2*I]])
ev = M.eigenvals()
# test one random eigenvalue, the computation is a little slow
test_ev = random.choice(list(ev.keys()))
assert (M - test_ev*eye(4)).det() == 0
def test_legacy_det():
# Minimal support for legacy keys for 'method' in det()
# Partially copied from test_determinant()
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="det_lu") == -289
assert M.det(method="det_LU") == -289
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="det_lu") == 275
assert M.det(method="Bareis") == 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="det_lu") == -55
assert M.det(method="BAREISS") == -55
M = Matrix(( ( 3, 0, 0, 0),
(-2, 1, 0, 0),
( 0, -2, 5, 0),
( 5, 0, 3, 4) ))
assert M.det(method="bareiss") == 60
assert M.det(method="berkowitz") == 60
assert M.det(method="lu") == 60
M = Matrix(( ( 1, 0, 0, 0),
( 5, 0, 0, 0),
( 9, 10, 11, 0),
(13, 14, 15, 16) ))
assert M.det(method="bareiss") == 0
assert M.det(method="berkowitz") == 0
assert M.det(method="lu") == 0
M = Matrix(( (3, 2, 0, 0, 0),
(0, 3, 2, 0, 0),
(0, 0, 3, 2, 0),
(0, 0, 0, 3, 2),
(0, 0, 0, 0, 3) ))
assert M.det(method="bareiss") == 243
assert M.det(method="berkowitz") == 243
assert M.det(method="lu") == 243
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="det_lu") == 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="det_lu") == 123
assert M.det(method="LU") == 123
def eye_Determinant(n):
return Matrix(n, n, lambda i, j: int(i == j))
def zeros_Determinant(n):
return Matrix(n, n, lambda i, j: 0)
def test_det():
a = Matrix(2, 3, [1, 2, 3, 4, 5, 6])
raises(NonSquareMatrixError, lambda: a.det())
z = zeros_Determinant(2)
ey = eye_Determinant(2)
assert z.det() == 0
assert ey.det() == 1
x = Symbol('x')
a = Matrix(0, 0, [])
b = Matrix(1, 1, [5])
c = Matrix(2, 2, [1, 2, 3, 4])
d = Matrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 8])
e = Matrix(4, 4,
[x, 1, 2, 3, 4, 5, 6, 7, 2, 9, 10, 11, 12, 13, 14, 14])
from sympy.abc import i, j, k, l, m, n
f = Matrix(3, 3, [i, l, m, 0, j, n, 0, 0, k])
g = Matrix(3, 3, [i, 0, 0, l, j, 0, m, n, k])
h = Matrix(3, 3, [x**3, 0, 0, i, x**-1, 0, j, k, x**-2])
# the method keyword for `det` doesn't kick in until 4x4 matrices,
# so there is no need to test all methods on smaller ones
assert a.det() == 1
assert b.det() == 5
assert c.det() == -2
assert d.det() == 3
assert e.det() == 4*x - 24
assert e.det(method="domain-ge") == 4*x - 24
assert e.det(method='bareiss') == 4*x - 24
assert e.det(method='berkowitz') == 4*x - 24
assert f.det() == i*j*k
assert g.det() == i*j*k
assert h.det() == 1
raises(ValueError, lambda: e.det(iszerofunc="test"))
def test_permanent():
M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
assert M.per() == 450
for i in range(1, 12):
assert ones(i, i).per() == ones(i, i).T.per() == factorial(i)
assert (ones(i, i)-eye(i)).per() == (ones(i, i)-eye(i)).T.per() == subfactorial(i)
a1, a2, a3, a4, a5 = symbols('a_1 a_2 a_3 a_4 a_5')
M = Matrix([a1, a2, a3, a4, a5])
assert M.per() == M.T.per() == a1 + a2 + a3 + a4 + a5
def test_adjugate():
x = Symbol('x')
e = Matrix(4, 4,
[x, 1, 2, 3, 4, 5, 6, 7, 2, 9, 10, 11, 12, 13, 14, 14])
adj = Matrix([
[ 4, -8, 4, 0],
[ 76, -14*x - 68, 14*x - 8, -4*x + 24],
[-122, 17*x + 142, -21*x + 4, 8*x - 48],
[ 48, -4*x - 72, 8*x, -4*x + 24]])
assert e.adjugate() == adj
assert e.adjugate(method='bareiss') == adj
assert e.adjugate(method='berkowitz') == adj
a = Matrix(2, 3, [1, 2, 3, 4, 5, 6])
raises(NonSquareMatrixError, lambda: a.adjugate())
def test_util():
R = Rational
v1 = Matrix(1, 3, [1, 2, 3])
v2 = Matrix(1, 3, [3, 4, 5])
assert v1.norm() == sqrt(14)
assert v1.project(v2) == Matrix(1, 3, [R(39)/25, R(52)/25, R(13)/5])
assert Matrix.zeros(1, 2) == Matrix(1, 2, [0, 0])
assert ones(1, 2) == Matrix(1, 2, [1, 1])
assert v1.copy() == v1
# cofactor
assert eye(3) == eye(3).cofactor_matrix()
test = Matrix([[1, 3, 2], [2, 6, 3], [2, 3, 6]])
assert test.cofactor_matrix() == \
Matrix([[27, -6, -6], [-12, 2, 3], [-3, 1, 0]])
test = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
assert test.cofactor_matrix() == \
Matrix([[-3, 6, -3], [6, -12, 6], [-3, 6, -3]])
def test_cofactor_and_minors():
x = Symbol('x')
e = Matrix(4, 4,
[x, 1, 2, 3, 4, 5, 6, 7, 2, 9, 10, 11, 12, 13, 14, 14])
m = Matrix([
[ x, 1, 3],
[ 2, 9, 11],
[12, 13, 14]])
cm = Matrix([
[ 4, 76, -122, 48],
[-8, -14*x - 68, 17*x + 142, -4*x - 72],
[ 4, 14*x - 8, -21*x + 4, 8*x],
[ 0, -4*x + 24, 8*x - 48, -4*x + 24]])
sub = Matrix([
[x, 1, 2],
[4, 5, 6],
[2, 9, 10]])
assert e.minor_submatrix(1, 2) == m
assert e.minor_submatrix(-1, -1) == sub
assert e.minor(1, 2) == -17*x - 142
assert e.cofactor(1, 2) == 17*x + 142
assert e.cofactor_matrix() == cm
assert e.cofactor_matrix(method="bareiss") == cm
assert e.cofactor_matrix(method="berkowitz") == cm
raises(ValueError, lambda: e.cofactor(4, 5))
raises(ValueError, lambda: e.minor(4, 5))
raises(ValueError, lambda: e.minor_submatrix(4, 5))
a = Matrix(2, 3, [1, 2, 3, 4, 5, 6])
assert a.minor_submatrix(0, 0) == Matrix([[5, 6]])
raises(ValueError, lambda:
Matrix(0, 0, []).minor_submatrix(0, 0))
raises(NonSquareMatrixError, lambda: a.cofactor(0, 0))
raises(NonSquareMatrixError, lambda: a.minor(0, 0))
raises(NonSquareMatrixError, lambda: a.cofactor_matrix())
def test_charpoly():
x, y = Symbol('x'), Symbol('y')
z, t = Symbol('z'), Symbol('t')
from sympy.abc import a,b,c
m = Matrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9])
assert eye_Determinant(3).charpoly(x) == Poly((x - 1)**3, x)
assert eye_Determinant(3).charpoly(y) == Poly((y - 1)**3, y)
assert m.charpoly() == Poly(x**3 - 15*x**2 - 18*x, x)
raises(NonSquareMatrixError, lambda: Matrix([[1], [2]]).charpoly())
n = Matrix(4, 4, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
assert n.charpoly() == Poly(x**4, x)
n = Matrix(4, 4, [45, 0, 0, 0, 0, 23, 0, 0, 0, 0, 87, 0, 0, 0, 0, 12])
assert n.charpoly() == Poly(x**4 - 167*x**3 + 8811*x**2 - 173457*x + 1080540, x)
n = Matrix(3, 3, [x, 0, 0, a, y, 0, b, c, z])
assert n.charpoly() == Poly(t**3 - (x+y+z)*t**2 + t*(x*y+y*z+x*z) - x*y*z, t)
|
c5b07efef6c5f48608cef91a3a3b157857c91d19376ee15135dc4a199bee6571 | from sympy.core.numbers import I
from sympy.core.symbol import symbols
from sympy.matrices.common import _MinimalMatrix, _CastableMatrix
from sympy.matrices.matrices import MatrixReductions
from sympy.testing.pytest import raises
from sympy.matrices import Matrix, zeros
from sympy.core.symbol import Symbol
from sympy.core.numbers import Rational
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.simplify.simplify import simplify
from sympy.abc import x
class ReductionsOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixReductions):
pass
def eye_Reductions(n):
return ReductionsOnlyMatrix(n, n, lambda i, j: int(i == j))
def zeros_Reductions(n):
return ReductionsOnlyMatrix(n, n, lambda i, j: 0)
# ReductionsOnlyMatrix tests
def test_row_op():
e = eye_Reductions(3)
raises(ValueError, lambda: e.elementary_row_op("abc"))
raises(ValueError, lambda: e.elementary_row_op())
raises(ValueError, lambda: e.elementary_row_op('n->kn', row=5, k=5))
raises(ValueError, lambda: e.elementary_row_op('n->kn', row=-5, k=5))
raises(ValueError, lambda: e.elementary_row_op('n<->m', row1=1, row2=5))
raises(ValueError, lambda: e.elementary_row_op('n<->m', row1=5, row2=1))
raises(ValueError, lambda: e.elementary_row_op('n<->m', row1=-5, row2=1))
raises(ValueError, lambda: e.elementary_row_op('n<->m', row1=1, row2=-5))
raises(ValueError, lambda: e.elementary_row_op('n->n+km', row1=1, row2=5, k=5))
raises(ValueError, lambda: e.elementary_row_op('n->n+km', row1=5, row2=1, k=5))
raises(ValueError, lambda: e.elementary_row_op('n->n+km', row1=-5, row2=1, k=5))
raises(ValueError, lambda: e.elementary_row_op('n->n+km', row1=1, row2=-5, k=5))
raises(ValueError, lambda: e.elementary_row_op('n->n+km', row1=1, row2=1, k=5))
# test various ways to set arguments
assert e.elementary_row_op("n->kn", 0, 5) == Matrix([[5, 0, 0], [0, 1, 0], [0, 0, 1]])
assert e.elementary_row_op("n->kn", 1, 5) == Matrix([[1, 0, 0], [0, 5, 0], [0, 0, 1]])
assert e.elementary_row_op("n->kn", row=1, k=5) == Matrix([[1, 0, 0], [0, 5, 0], [0, 0, 1]])
assert e.elementary_row_op("n->kn", row1=1, k=5) == Matrix([[1, 0, 0], [0, 5, 0], [0, 0, 1]])
assert e.elementary_row_op("n<->m", 0, 1) == Matrix([[0, 1, 0], [1, 0, 0], [0, 0, 1]])
assert e.elementary_row_op("n<->m", row1=0, row2=1) == Matrix([[0, 1, 0], [1, 0, 0], [0, 0, 1]])
assert e.elementary_row_op("n<->m", row=0, row2=1) == Matrix([[0, 1, 0], [1, 0, 0], [0, 0, 1]])
assert e.elementary_row_op("n->n+km", 0, 5, 1) == Matrix([[1, 5, 0], [0, 1, 0], [0, 0, 1]])
assert e.elementary_row_op("n->n+km", row=0, k=5, row2=1) == Matrix([[1, 5, 0], [0, 1, 0], [0, 0, 1]])
assert e.elementary_row_op("n->n+km", row1=0, k=5, row2=1) == Matrix([[1, 5, 0], [0, 1, 0], [0, 0, 1]])
# make sure the matrix doesn't change size
a = ReductionsOnlyMatrix(2, 3, [0]*6)
assert a.elementary_row_op("n->kn", 1, 5) == Matrix(2, 3, [0]*6)
assert a.elementary_row_op("n<->m", 0, 1) == Matrix(2, 3, [0]*6)
assert a.elementary_row_op("n->n+km", 0, 5, 1) == Matrix(2, 3, [0]*6)
def test_col_op():
e = eye_Reductions(3)
raises(ValueError, lambda: e.elementary_col_op("abc"))
raises(ValueError, lambda: e.elementary_col_op())
raises(ValueError, lambda: e.elementary_col_op('n->kn', col=5, k=5))
raises(ValueError, lambda: e.elementary_col_op('n->kn', col=-5, k=5))
raises(ValueError, lambda: e.elementary_col_op('n<->m', col1=1, col2=5))
raises(ValueError, lambda: e.elementary_col_op('n<->m', col1=5, col2=1))
raises(ValueError, lambda: e.elementary_col_op('n<->m', col1=-5, col2=1))
raises(ValueError, lambda: e.elementary_col_op('n<->m', col1=1, col2=-5))
raises(ValueError, lambda: e.elementary_col_op('n->n+km', col1=1, col2=5, k=5))
raises(ValueError, lambda: e.elementary_col_op('n->n+km', col1=5, col2=1, k=5))
raises(ValueError, lambda: e.elementary_col_op('n->n+km', col1=-5, col2=1, k=5))
raises(ValueError, lambda: e.elementary_col_op('n->n+km', col1=1, col2=-5, k=5))
raises(ValueError, lambda: e.elementary_col_op('n->n+km', col1=1, col2=1, k=5))
# test various ways to set arguments
assert e.elementary_col_op("n->kn", 0, 5) == Matrix([[5, 0, 0], [0, 1, 0], [0, 0, 1]])
assert e.elementary_col_op("n->kn", 1, 5) == Matrix([[1, 0, 0], [0, 5, 0], [0, 0, 1]])
assert e.elementary_col_op("n->kn", col=1, k=5) == Matrix([[1, 0, 0], [0, 5, 0], [0, 0, 1]])
assert e.elementary_col_op("n->kn", col1=1, k=5) == Matrix([[1, 0, 0], [0, 5, 0], [0, 0, 1]])
assert e.elementary_col_op("n<->m", 0, 1) == Matrix([[0, 1, 0], [1, 0, 0], [0, 0, 1]])
assert e.elementary_col_op("n<->m", col1=0, col2=1) == Matrix([[0, 1, 0], [1, 0, 0], [0, 0, 1]])
assert e.elementary_col_op("n<->m", col=0, col2=1) == Matrix([[0, 1, 0], [1, 0, 0], [0, 0, 1]])
assert e.elementary_col_op("n->n+km", 0, 5, 1) == Matrix([[1, 0, 0], [5, 1, 0], [0, 0, 1]])
assert e.elementary_col_op("n->n+km", col=0, k=5, col2=1) == Matrix([[1, 0, 0], [5, 1, 0], [0, 0, 1]])
assert e.elementary_col_op("n->n+km", col1=0, k=5, col2=1) == Matrix([[1, 0, 0], [5, 1, 0], [0, 0, 1]])
# make sure the matrix doesn't change size
a = ReductionsOnlyMatrix(2, 3, [0]*6)
assert a.elementary_col_op("n->kn", 1, 5) == Matrix(2, 3, [0]*6)
assert a.elementary_col_op("n<->m", 0, 1) == Matrix(2, 3, [0]*6)
assert a.elementary_col_op("n->n+km", 0, 5, 1) == Matrix(2, 3, [0]*6)
def test_is_echelon():
zro = zeros_Reductions(3)
ident = eye_Reductions(3)
assert zro.is_echelon
assert ident.is_echelon
a = ReductionsOnlyMatrix(0, 0, [])
assert a.is_echelon
a = ReductionsOnlyMatrix(2, 3, [3, 2, 1, 0, 0, 6])
assert a.is_echelon
a = ReductionsOnlyMatrix(2, 3, [0, 0, 6, 3, 2, 1])
assert not a.is_echelon
x = Symbol('x')
a = ReductionsOnlyMatrix(3, 1, [x, 0, 0])
assert a.is_echelon
a = ReductionsOnlyMatrix(3, 1, [x, x, 0])
assert not a.is_echelon
a = ReductionsOnlyMatrix(3, 3, [0, 0, 0, 1, 2, 3, 0, 0, 0])
assert not a.is_echelon
def test_echelon_form():
# echelon form is not unique, but the result
# must be row-equivalent to the original matrix
# and it must be in echelon form.
a = zeros_Reductions(3)
e = eye_Reductions(3)
# we can assume the zero matrix and the identity matrix shouldn't change
assert a.echelon_form() == a
assert e.echelon_form() == e
a = ReductionsOnlyMatrix(0, 0, [])
assert a.echelon_form() == a
a = ReductionsOnlyMatrix(1, 1, [5])
assert a.echelon_form() == a
# now we get to the real tests
def verify_row_null_space(mat, rows, nulls):
for v in nulls:
assert all(t.is_zero for t in a_echelon*v)
for v in rows:
if not all(t.is_zero for t in v):
assert not all(t.is_zero for t in a_echelon*v.transpose())
a = ReductionsOnlyMatrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9])
nulls = [Matrix([
[ 1],
[-2],
[ 1]])]
rows = [a[i, :] for i in range(a.rows)]
a_echelon = a.echelon_form()
assert a_echelon.is_echelon
verify_row_null_space(a, rows, nulls)
a = ReductionsOnlyMatrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 8])
nulls = []
rows = [a[i, :] for i in range(a.rows)]
a_echelon = a.echelon_form()
assert a_echelon.is_echelon
verify_row_null_space(a, rows, nulls)
a = ReductionsOnlyMatrix(3, 3, [2, 1, 3, 0, 0, 0, 2, 1, 3])
nulls = [Matrix([
[Rational(-1, 2)],
[ 1],
[ 0]]),
Matrix([
[Rational(-3, 2)],
[ 0],
[ 1]])]
rows = [a[i, :] for i in range(a.rows)]
a_echelon = a.echelon_form()
assert a_echelon.is_echelon
verify_row_null_space(a, rows, nulls)
# this one requires a row swap
a = ReductionsOnlyMatrix(3, 3, [2, 1, 3, 0, 0, 0, 1, 1, 3])
nulls = [Matrix([
[ 0],
[ -3],
[ 1]])]
rows = [a[i, :] for i in range(a.rows)]
a_echelon = a.echelon_form()
assert a_echelon.is_echelon
verify_row_null_space(a, rows, nulls)
a = ReductionsOnlyMatrix(3, 3, [0, 3, 3, 0, 2, 2, 0, 1, 1])
nulls = [Matrix([
[1],
[0],
[0]]),
Matrix([
[ 0],
[-1],
[ 1]])]
rows = [a[i, :] for i in range(a.rows)]
a_echelon = a.echelon_form()
assert a_echelon.is_echelon
verify_row_null_space(a, rows, nulls)
a = ReductionsOnlyMatrix(2, 3, [2, 2, 3, 3, 3, 0])
nulls = [Matrix([
[-1],
[1],
[0]])]
rows = [a[i, :] for i in range(a.rows)]
a_echelon = a.echelon_form()
assert a_echelon.is_echelon
verify_row_null_space(a, rows, nulls)
def test_rref():
e = ReductionsOnlyMatrix(0, 0, [])
assert e.rref(pivots=False) == e
e = ReductionsOnlyMatrix(1, 1, [1])
a = ReductionsOnlyMatrix(1, 1, [5])
assert e.rref(pivots=False) == a.rref(pivots=False) == e
a = ReductionsOnlyMatrix(3, 1, [1, 2, 3])
assert a.rref(pivots=False) == Matrix([[1], [0], [0]])
a = ReductionsOnlyMatrix(1, 3, [1, 2, 3])
assert a.rref(pivots=False) == Matrix([[1, 2, 3]])
a = ReductionsOnlyMatrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9])
assert a.rref(pivots=False) == Matrix([
[1, 0, -1],
[0, 1, 2],
[0, 0, 0]])
a = ReductionsOnlyMatrix(3, 3, [1, 2, 3, 1, 2, 3, 1, 2, 3])
b = ReductionsOnlyMatrix(3, 3, [1, 2, 3, 0, 0, 0, 0, 0, 0])
c = ReductionsOnlyMatrix(3, 3, [0, 0, 0, 1, 2, 3, 0, 0, 0])
d = ReductionsOnlyMatrix(3, 3, [0, 0, 0, 0, 0, 0, 1, 2, 3])
assert a.rref(pivots=False) == \
b.rref(pivots=False) == \
c.rref(pivots=False) == \
d.rref(pivots=False) == b
e = eye_Reductions(3)
z = zeros_Reductions(3)
assert e.rref(pivots=False) == e
assert z.rref(pivots=False) == z
a = ReductionsOnlyMatrix([
[ 0, 0, 1, 2, 2, -5, 3],
[-1, 5, 2, 2, 1, -7, 5],
[ 0, 0, -2, -3, -3, 8, -5],
[-1, 5, 0, -1, -2, 1, 0]])
mat, pivot_offsets = a.rref()
assert mat == Matrix([
[1, -5, 0, 0, 1, 1, -1],
[0, 0, 1, 0, 0, -1, 1],
[0, 0, 0, 1, 1, -2, 1],
[0, 0, 0, 0, 0, 0, 0]])
assert pivot_offsets == (0, 2, 3)
a = ReductionsOnlyMatrix([[Rational(1, 19), Rational(1, 5), 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[ 12, 13, 14, 15]])
assert a.rref(pivots=False) == Matrix([
[1, 0, 0, Rational(-76, 157)],
[0, 1, 0, Rational(-5, 157)],
[0, 0, 1, Rational(238, 157)],
[0, 0, 0, 0]])
x = Symbol('x')
a = ReductionsOnlyMatrix(2, 3, [x, 1, 1, sqrt(x), x, 1])
for i, j in zip(a.rref(pivots=False),
[1, 0, sqrt(x)*(-x + 1)/(-x**Rational(5, 2) + x),
0, 1, 1/(sqrt(x) + x + 1)]):
assert simplify(i - j).is_zero
def test_issue_17827():
C = Matrix([
[3, 4, -1, 1],
[9, 12, -3, 3],
[0, 2, 1, 3],
[2, 3, 0, -2],
[0, 3, 3, -5],
[8, 15, 0, 6]
])
# Tests for row/col within valid range
D = C.elementary_row_op('n<->m', row1=2, row2=5)
E = C.elementary_row_op('n->n+km', row1=5, row2=3, k=-4)
F = C.elementary_row_op('n->kn', row=5, k=2)
assert(D[5, :] == Matrix([[0, 2, 1, 3]]))
assert(E[5, :] == Matrix([[0, 3, 0, 14]]))
assert(F[5, :] == Matrix([[16, 30, 0, 12]]))
# Tests for row/col out of range
raises(ValueError, lambda: C.elementary_row_op('n<->m', row1=2, row2=6))
raises(ValueError, lambda: C.elementary_row_op('n->kn', row=7, k=2))
raises(ValueError, lambda: C.elementary_row_op('n->n+km', row1=-1, row2=5, k=2))
def test_rank():
m = Matrix([[1, 2], [x, 1 - 1/x]])
assert m.rank() == 2
n = Matrix(3, 3, range(1, 10))
assert n.rank() == 2
p = zeros(3)
assert p.rank() == 0
def test_issue_11434():
ax, ay, bx, by, cx, cy, dx, dy, ex, ey, t0, t1 = \
symbols('a_x a_y b_x b_y c_x c_y d_x d_y e_x e_y t_0 t_1')
M = Matrix([[ax, ay, ax*t0, ay*t0, 0],
[bx, by, bx*t0, by*t0, 0],
[cx, cy, cx*t0, cy*t0, 1],
[dx, dy, dx*t0, dy*t0, 1],
[ex, ey, 2*ex*t1 - ex*t0, 2*ey*t1 - ey*t0, 0]])
assert M.rank() == 4
def test_rank_regression_from_so():
# see:
# https://stackoverflow.com/questions/19072700/why-does-sympy-give-me-the-wrong-answer-when-i-row-reduce-a-symbolic-matrix
nu, lamb = symbols('nu, lambda')
A = Matrix([[-3*nu, 1, 0, 0],
[ 3*nu, -2*nu - 1, 2, 0],
[ 0, 2*nu, (-1*nu) - lamb - 2, 3],
[ 0, 0, nu + lamb, -3]])
expected_reduced = Matrix([[1, 0, 0, 1/(nu**2*(-lamb - nu))],
[0, 1, 0, 3/(nu*(-lamb - nu))],
[0, 0, 1, 3/(-lamb - nu)],
[0, 0, 0, 0]])
expected_pivots = (0, 1, 2)
reduced, pivots = A.rref()
assert simplify(expected_reduced - reduced) == zeros(*A.shape)
assert pivots == expected_pivots
def test_issue_15872():
A = Matrix([[1, 1, 1, 0], [-2, -1, 0, -1], [0, 0, -1, -1], [0, 0, 2, 1]])
B = A - Matrix.eye(4) * I
assert B.rank() == 3
assert (B**2).rank() == 2
assert (B**3).rank() == 2
|
a8c902ced11399287f548382974827a122fd791f6f1a720378cfab7375a80409 | from sympy.core.function import expand_mul
from sympy.core.numbers import (I, Rational)
from sympy.core.singleton import S
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.simplify.simplify import simplify
from sympy.matrices.matrices import NonSquareMatrixError
from sympy.matrices import Matrix, zeros, eye, SparseMatrix
from sympy.abc import x, y, z
from sympy.testing.pytest import raises, slow
from sympy.testing.matrices import allclose
def test_LUdecomp():
testmat = Matrix([[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 == zeros(4)
testmat = Matrix([[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 == zeros(4)
# non-square
testmat = Matrix([[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12]])
L, U, p = testmat.LUdecomposition(rankcheck=False)
assert L.is_lower
assert U.is_upper
assert (L*U).permute_rows(p, 'backward') - testmat == zeros(4, 3)
# square and singular
testmat = Matrix([[1, 2, 3],
[2, 4, 6],
[4, 5, 6]])
L, U, p = testmat.LUdecomposition(rankcheck=False)
assert L.is_lower
assert U.is_upper
assert (L*U).permute_rows(p, 'backward') - testmat == zeros(3)
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 == zeros(3)
mL = Matrix((
(1, 0, 0),
(2, 3, 0),
))
assert mL.is_lower is True
assert mL.is_upper is False
mU = Matrix((
(1, 2, 3),
(0, 4, 5),
))
assert mU.is_lower is False
assert mU.is_upper is True
# test FF LUdecomp
M = Matrix([[1, 3, 3],
[3, 2, 6],
[3, 2, 2]])
P, L, Dee, U = M.LUdecompositionFF()
assert P*M == L*Dee.inv()*U
M = Matrix([[1, 2, 3, 4],
[3, -1, 2, 3],
[3, 1, 3, -2],
[6, -1, 0, 2]])
P, L, Dee, U = M.LUdecompositionFF()
assert P*M == L*Dee.inv()*U
M = Matrix([[0, 0, 1],
[2, 3, 0],
[3, 1, 4]])
P, L, Dee, U = M.LUdecompositionFF()
assert P*M == L*Dee.inv()*U
# issue 15794
M = Matrix(
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
)
raises(ValueError, lambda : M.LUdecomposition_Simple(rankcheck=True))
def test_singular_value_decompositionD():
A = Matrix([[1, 2], [2, 1]])
U, S, V = A.singular_value_decomposition()
assert U * S * V.T == A
assert U.T * U == eye(U.cols)
assert V.T * V == eye(V.cols)
B = Matrix([[1, 2]])
U, S, V = B.singular_value_decomposition()
assert U * S * V.T == B
assert U.T * U == eye(U.cols)
assert V.T * V == eye(V.cols)
C = Matrix([
[1, 0, 0, 0, 2],
[0, 0, 3, 0, 0],
[0, 0, 0, 0, 0],
[0, 2, 0, 0, 0],
])
U, S, V = C.singular_value_decomposition()
assert U * S * V.T == C
assert U.T * U == eye(U.cols)
assert V.T * V == eye(V.cols)
D = Matrix([[Rational(1, 3), sqrt(2)], [0, Rational(1, 4)]])
U, S, V = D.singular_value_decomposition()
assert simplify(U.T * U) == eye(U.cols)
assert simplify(V.T * V) == eye(V.cols)
assert simplify(U * S * V.T) == D
def 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)
A = Matrix([[1, 1, 1], [1, 1, 3], [2, 3, 4]])
Q, R = A.QRdecomposition()
assert Q.T * Q == eye(Q.cols)
assert R.is_upper
assert A == Q*R
A = Matrix([[12, 0, -51], [6, 0, 167], [-4, 0, 24]])
Q, R = A.QRdecomposition()
assert Q.T * Q == eye(Q.cols)
assert R.is_upper
assert A == Q*R
def test_QR_non_square():
# Narrow (cols < rows) matrices
A = Matrix([[9, 0, 26], [12, 0, -7], [0, 4, 4], [0, -3, -3]])
Q, R = A.QRdecomposition()
assert Q.T * Q == eye(Q.cols)
assert R.is_upper
assert A == Q*R
A = Matrix([[1, -1, 4], [1, 4, -2], [1, 4, 2], [1, -1, 0]])
Q, R = A.QRdecomposition()
assert Q.T * Q == eye(Q.cols)
assert R.is_upper
assert A == Q*R
A = Matrix(2, 1, [1, 2])
Q, R = A.QRdecomposition()
assert Q.T * Q == eye(Q.cols)
assert R.is_upper
assert A == Q*R
# Wide (cols > rows) matrices
A = Matrix([[1, 2, 3], [4, 5, 6]])
Q, R = A.QRdecomposition()
assert Q.T * Q == eye(Q.cols)
assert R.is_upper
assert A == Q*R
A = Matrix([[1, 2, 3, 4], [1, 4, 9, 16], [1, 8, 27, 64]])
Q, R = A.QRdecomposition()
assert Q.T * Q == eye(Q.cols)
assert R.is_upper
assert A == Q*R
A = Matrix(1, 2, [1, 2])
Q, R = A.QRdecomposition()
assert Q.T * Q == eye(Q.cols)
assert R.is_upper
assert A == Q*R
def test_QR_trivial():
# Rank deficient matrices
A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
Q, R = A.QRdecomposition()
assert Q.T * Q == eye(Q.cols)
assert R.is_upper
assert A == Q*R
A = Matrix([[1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4]])
Q, R = A.QRdecomposition()
assert Q.T * Q == eye(Q.cols)
assert R.is_upper
assert A == Q*R
A = Matrix([[1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4]]).T
Q, R = A.QRdecomposition()
assert Q.T * Q == eye(Q.cols)
assert R.is_upper
assert A == Q*R
# Zero rank matrices
A = Matrix([[0, 0, 0]])
Q, R = A.QRdecomposition()
assert Q.T * Q == eye(Q.cols)
assert R.is_upper
assert A == Q*R
A = Matrix([[0, 0, 0]]).T
Q, R = A.QRdecomposition()
assert Q.T * Q == eye(Q.cols)
assert R.is_upper
assert A == Q*R
A = Matrix([[0, 0, 0], [0, 0, 0]])
Q, R = A.QRdecomposition()
assert Q.T * Q == eye(Q.cols)
assert R.is_upper
assert A == Q*R
A = Matrix([[0, 0, 0], [0, 0, 0]]).T
Q, R = A.QRdecomposition()
assert Q.T * Q == eye(Q.cols)
assert R.is_upper
assert A == Q*R
# Rank deficient matrices with zero norm from beginning columns
A = Matrix([[0, 0, 0], [1, 2, 3]]).T
Q, R = A.QRdecomposition()
assert Q.T * Q == eye(Q.cols)
assert R.is_upper
assert A == Q*R
A = Matrix([[0, 0, 0, 0], [1, 2, 3, 4], [0, 0, 0, 0]]).T
Q, R = A.QRdecomposition()
assert Q.T * Q == eye(Q.cols)
assert R.is_upper
assert A == Q*R
A = Matrix([[0, 0, 0, 0], [1, 2, 3, 4], [0, 0, 0, 0], [2, 4, 6, 8]]).T
Q, R = A.QRdecomposition()
assert Q.T * Q == eye(Q.cols)
assert R.is_upper
assert A == Q*R
A = Matrix([[0, 0, 0], [0, 0, 0], [0, 0, 0], [1, 2, 3]]).T
Q, R = A.QRdecomposition()
assert Q.T * Q == eye(Q.cols)
assert R.is_upper
assert A == Q*R
def test_QR_float():
A = Matrix([[1, 1], [1, 1.01]])
Q, R = A.QRdecomposition()
assert allclose(Q * R, A)
assert allclose(Q * Q.T, Matrix.eye(2))
assert allclose(Q.T * Q, Matrix.eye(2))
A = Matrix([[1, 1], [1, 1.001]])
Q, R = A.QRdecomposition()
assert allclose(Q * R, A)
assert allclose(Q * Q.T, Matrix.eye(2))
assert allclose(Q.T * Q, Matrix.eye(2))
def test_LUdecomposition_Simple_iszerofunc():
# Test if callable passed to matrices.LUdecomposition_Simple() as iszerofunc keyword argument is used inside
# matrices.LUdecomposition_Simple()
magic_string = "I got passed in!"
def goofyiszero(value):
raise ValueError(magic_string)
try:
lu, p = Matrix([[1, 0], [0, 1]]).LUdecomposition_Simple(iszerofunc=goofyiszero)
except ValueError as err:
assert magic_string == err.args[0]
return
assert False
def test_LUdecomposition_iszerofunc():
# Test if callable passed to matrices.LUdecomposition() as iszerofunc keyword argument is used inside
# matrices.LUdecomposition_Simple()
magic_string = "I got passed in!"
def goofyiszero(value):
raise ValueError(magic_string)
try:
l, u, p = Matrix([[1, 0], [0, 1]]).LUdecomposition(iszerofunc=goofyiszero)
except ValueError as err:
assert magic_string == err.args[0]
return
assert False
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_pinv_succeeds_with_rank_decomposition_method():
# Test rank decomposition method of pseudoinverse succeeding
As = [Matrix([
[61, 89, 55, 20, 71, 0],
[62, 96, 85, 85, 16, 0],
[69, 56, 17, 4, 54, 0],
[10, 54, 91, 41, 71, 0],
[ 7, 30, 10, 48, 90, 0],
[0,0,0,0,0,0]])]
for A in As:
A_pinv = A.pinv(method="RD")
AAp = A * A_pinv
ApA = A_pinv * A
assert simplify(AAp * A) == A
assert simplify(ApA * A_pinv) == A_pinv
assert AAp.H == AAp
assert ApA.H == ApA
def test_rank_decomposition():
a = Matrix(0, 0, [])
c, f = a.rank_decomposition()
assert f.is_echelon
assert c.cols == f.rows == a.rank()
assert c * f == a
a = Matrix(1, 1, [5])
c, f = a.rank_decomposition()
assert f.is_echelon
assert c.cols == f.rows == a.rank()
assert c * f == a
a = Matrix(3, 3, [1, 2, 3, 1, 2, 3, 1, 2, 3])
c, f = a.rank_decomposition()
assert f.is_echelon
assert c.cols == f.rows == a.rank()
assert c * f == a
a = Matrix([
[0, 0, 1, 2, 2, -5, 3],
[-1, 5, 2, 2, 1, -7, 5],
[0, 0, -2, -3, -3, 8, -5],
[-1, 5, 0, -1, -2, 1, 0]])
c, f = a.rank_decomposition()
assert f.is_echelon
assert c.cols == f.rows == a.rank()
assert c * f == a
@slow
def test_upper_hessenberg_decomposition():
A = Matrix([
[1, 0, sqrt(3)],
[sqrt(2), Rational(1, 2), 2],
[1, Rational(1, 4), 3],
])
H, P = A.upper_hessenberg_decomposition()
assert simplify(P * P.H) == eye(P.cols)
assert simplify(P.H * P) == eye(P.cols)
assert H.is_upper_hessenberg
assert (simplify(P * H * P.H)) == A
B = Matrix([
[1, 2, 10],
[8, 2, 5],
[3, 12, 34],
])
H, P = B.upper_hessenberg_decomposition()
assert simplify(P * P.H) == eye(P.cols)
assert simplify(P.H * P) == eye(P.cols)
assert H.is_upper_hessenberg
assert simplify(P * H * P.H) == B
C = Matrix([
[1, sqrt(2), 2, 3],
[0, 5, 3, 4],
[1, 1, 4, sqrt(5)],
[0, 2, 2, 3]
])
H, P = C.upper_hessenberg_decomposition()
assert simplify(P * P.H) == eye(P.cols)
assert simplify(P.H * P) == eye(P.cols)
assert H.is_upper_hessenberg
assert simplify(P * H * P.H) == C
D = Matrix([
[1, 2, 3],
[-3, 5, 6],
[4, -8, 9],
])
H, P = D.upper_hessenberg_decomposition()
assert simplify(P * P.H) == eye(P.cols)
assert simplify(P.H * P) == eye(P.cols)
assert H.is_upper_hessenberg
assert simplify(P * H * P.H) == D
E = Matrix([
[1, 0, 0, 0],
[0, 1, 0, 0],
[1, 1, 0, 1],
[1, 1, 1, 0]
])
H, P = E.upper_hessenberg_decomposition()
assert simplify(P * P.H) == eye(P.cols)
assert simplify(P.H * P) == eye(P.cols)
assert H.is_upper_hessenberg
assert simplify(P * H * P.H) == E
|
83a1ebd3b0ba39fe64a64b65f60e57303384e93554cbca398f9350037a0d79d6 | from sympy.testing.pytest import warns_deprecated_sympy
from sympy.core.symbol import Symbol
from sympy.polys.polytools import Poly
from sympy.matrices import Matrix
from sympy.matrices.normalforms import (
invariant_factors,
smith_normal_form,
hermite_normal_form,
)
from sympy.polys.domains import ZZ, QQ
def test_smith_normal():
m = Matrix([[12,6,4,8],[3,9,6,12],[2,16,14,28],[20,10,10,20]])
smf = Matrix([[1, 0, 0, 0], [0, 10, 0, 0], [0, 0, -30, 0], [0, 0, 0, 0]])
assert smith_normal_form(m) == smf
x = Symbol('x')
with warns_deprecated_sympy():
m = Matrix([[Poly(x-1), Poly(1, x),Poly(-1,x)],
[0, Poly(x), Poly(-1,x)],
[Poly(0,x),Poly(-1,x),Poly(x)]])
invs = 1, x - 1, x**2 - 1
assert invariant_factors(m, domain=QQ[x]) == invs
m = Matrix([[2, 4]])
smf = Matrix([[2, 0]])
assert smith_normal_form(m) == smf
def test_smith_normal_deprecated():
from sympy.polys.solvers import RawMatrix as Matrix
with warns_deprecated_sympy():
m = Matrix([[12, 6, 4,8],[3,9,6,12],[2,16,14,28],[20,10,10,20]])
setattr(m, 'ring', ZZ)
with warns_deprecated_sympy():
smf = Matrix([[1, 0, 0, 0], [0, 10, 0, 0], [0, 0, -30, 0], [0, 0, 0, 0]])
assert smith_normal_form(m) == smf
x = Symbol('x')
with warns_deprecated_sympy():
m = Matrix([[Poly(x-1), Poly(1, x),Poly(-1,x)],
[0, Poly(x), Poly(-1,x)],
[Poly(0,x),Poly(-1,x),Poly(x)]])
setattr(m, 'ring', QQ[x])
invs = (Poly(1, x, domain='QQ'), Poly(x - 1, domain='QQ'), Poly(x**2 - 1, domain='QQ'))
assert invariant_factors(m) == invs
with warns_deprecated_sympy():
m = Matrix([[2, 4]])
setattr(m, 'ring', ZZ)
with warns_deprecated_sympy():
smf = Matrix([[2, 0]])
assert smith_normal_form(m) == smf
def test_hermite_normal():
m = Matrix([[2, 7, 17, 29, 41], [3, 11, 19, 31, 43], [5, 13, 23, 37, 47]])
hnf = Matrix([[1, 0, 0], [0, 2, 1], [0, 0, 1]])
assert hermite_normal_form(m) == hnf
tr_hnf = Matrix([[37, 0, 19], [222, -6, 113], [48, 0, 25], [0, 2, 1], [0, 0, 1]])
assert hermite_normal_form(m.transpose()) == tr_hnf
m = Matrix([[8, 28, 68, 116, 164], [3, 11, 19, 31, 43], [5, 13, 23, 37, 47]])
hnf = Matrix([[4, 0, 0], [0, 2, 1], [0, 0, 1]])
assert hermite_normal_form(m) == hnf
assert hermite_normal_form(m, D=8) == hnf
m = Matrix([[10, 8, 6, 30, 2], [45, 36, 27, 18, 9], [5, 4, 3, 2, 1]])
hnf = Matrix([[26, 2], [0, 9], [0, 1]])
assert hermite_normal_form(m) == hnf
m = Matrix([[2, 7], [0, 0], [0, 0]])
hnf = Matrix(3, 0, [])
assert hermite_normal_form(m) == hnf
|
a95d4bd62f11597de2849c7727e334eecfed85f5e6b94035c0845f42751bab20 | from itertools import product
from sympy.core.relational import (Equality, Unequality)
from sympy.core.singleton import S
from sympy.core.sympify import sympify
from sympy.integrals.integrals import integrate
from sympy.matrices.dense import (Matrix, eye, zeros)
from sympy.matrices.immutable import ImmutableMatrix
from sympy.matrices import SparseMatrix
from sympy.matrices.immutable import \
ImmutableDenseMatrix, ImmutableSparseMatrix
from sympy.abc import x, y
from sympy.testing.pytest import raises
IM = ImmutableDenseMatrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
ISM = ImmutableSparseMatrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
ieye = ImmutableDenseMatrix(eye(3))
def test_creation():
assert IM.shape == ISM.shape == (3, 3)
assert IM[1, 2] == ISM[1, 2] == 6
assert IM[2, 2] == ISM[2, 2] == 9
def test_immutability():
with raises(TypeError):
IM[2, 2] = 5
with raises(TypeError):
ISM[2, 2] = 5
def test_slicing():
assert IM[1, :] == ImmutableDenseMatrix([[4, 5, 6]])
assert IM[:2, :2] == ImmutableDenseMatrix([[1, 2], [4, 5]])
assert ISM[1, :] == ImmutableSparseMatrix([[4, 5, 6]])
assert ISM[:2, :2] == ImmutableSparseMatrix([[1, 2], [4, 5]])
def test_subs():
A = ImmutableMatrix([[1, 2], [3, 4]])
B = ImmutableMatrix([[1, 2], [x, 4]])
C = ImmutableMatrix([[-x, x*y], [-(x + y), y**2]])
assert B.subs(x, 3) == A
assert (x*B).subs(x, 3) == 3*A
assert (x*eye(2) + B).subs(x, 3) == 3*eye(2) + A
assert C.subs([[x, -1], [y, -2]]) == A
assert C.subs([(x, -1), (y, -2)]) == A
assert C.subs({x: -1, y: -2}) == A
assert C.subs({x: y - 1, y: x - 1}, simultaneous=True) == \
ImmutableMatrix([[1 - y, (x - 1)*(y - 1)], [2 - x - y, (x - 1)**2]])
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_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
# issue 6279
# https://github.com/sympy/sympy/issues/6279
# Test that Immutable _op_ Immutable => Immutable and not MatExpr
def test_immutable_evaluation():
X = ImmutableMatrix(eye(3))
A = ImmutableMatrix(3, 3, range(9))
assert isinstance(X + A, ImmutableMatrix)
assert isinstance(X * A, ImmutableMatrix)
assert isinstance(X * 2, ImmutableMatrix)
assert isinstance(2 * X, ImmutableMatrix)
assert isinstance(A**2, ImmutableMatrix)
def test_deterimant():
assert ImmutableMatrix(4, 4, lambda i, j: i + j).det() == 0
def test_Equality():
assert Equality(IM, IM) is S.true
assert Unequality(IM, IM) is S.false
assert Equality(IM, IM.subs(1, 2)) is S.false
assert Unequality(IM, IM.subs(1, 2)) is S.true
assert Equality(IM, 2) is S.false
assert Unequality(IM, 2) is S.true
M = ImmutableMatrix([x, y])
assert Equality(M, IM) is S.false
assert Unequality(M, IM) is S.true
assert Equality(M, M.subs(x, 2)).subs(x, 2) is S.true
assert Unequality(M, M.subs(x, 2)).subs(x, 2) is S.false
assert Equality(M, M.subs(x, 2)).subs(x, 3) is S.false
assert Unequality(M, M.subs(x, 2)).subs(x, 3) is S.true
def test_integrate():
intIM = integrate(IM, x)
assert intIM.shape == IM.shape
assert all([intIM[i, j] == (1 + j + 3*i)*x for i, j in
product(range(3), range(3))])
|
0253ed8a70eba624182d00437535c0378ce8195aff0913748e07f7a555f7f4e1 | from sympy.testing.pytest import ignore_warnings
from sympy.utilities.exceptions import SymPyDeprecationWarning
from sympy.matrices import Matrix, SparseMatrix, ImmutableMatrix
with ignore_warnings(SymPyDeprecationWarning):
from sympy.matrices.densetools import eye
from sympy.matrices.densearith import add, sub, mulmatmat, mulmatscaler
from sympy.polys.domains.integerring import ZZ
def test_add():
a = [[ZZ(3), ZZ(7), ZZ(4)], [ZZ(2), ZZ(4), ZZ(5)], [ZZ(6), ZZ(2), ZZ(3)]]
b = [[ZZ(5), ZZ(4), ZZ(9)], [ZZ(3), ZZ(7), ZZ(1)], [ZZ(12), ZZ(13), ZZ(14)]]
c = [[ZZ(12)], [ZZ(17)], [ZZ(21)]]
d = [[ZZ(3)], [ZZ(4)], [ZZ(5)]]
e = [[ZZ(12), ZZ(78)], [ZZ(56), ZZ(79)]]
f = [[ZZ.zero, ZZ.zero], [ZZ.zero, ZZ.zero]]
assert add(a, b, ZZ) == [[ZZ(8), ZZ(11), ZZ(13)], [ZZ(5), ZZ(11), ZZ(6)], [ZZ(18), ZZ(15), ZZ(17)]]
assert add(c, d, ZZ) == [[ZZ(15)], [ZZ(21)], [ZZ(26)]]
assert add(e, f, ZZ) == e
def test_sub():
a = [[ZZ(3), ZZ(7), ZZ(4)], [ZZ(2), ZZ(4), ZZ(5)], [ZZ(6), ZZ(2), ZZ(3)]]
b = [[ZZ(5), ZZ(4), ZZ(9)], [ZZ(3), ZZ(7), ZZ(1)], [ZZ(12), ZZ(13), ZZ(14)]]
c = [[ZZ(12)], [ZZ(17)], [ZZ(21)]]
d = [[ZZ(3)], [ZZ(4)], [ZZ(5)]]
e = [[ZZ(12), ZZ(78)], [ZZ(56), ZZ(79)]]
f = [[ZZ.zero, ZZ.zero], [ZZ.zero, ZZ.zero]]
assert sub(a, b, ZZ) == [[ZZ(-2), ZZ(3), ZZ(-5)], [ZZ(-1), ZZ(-3), ZZ(4)], [ZZ(-6), ZZ(-11), ZZ(-11)]]
assert sub(c, d, ZZ) == [[ZZ(9)], [ZZ(13)], [ZZ(16)]]
assert sub(e, f, ZZ) == e
def test_mulmatmat():
a = [[ZZ(3), ZZ(4)], [ZZ(5), ZZ(6)]]
b = [[ZZ(1), ZZ(2)], [ZZ(7), ZZ(8)]]
c = eye(2, ZZ)
d = [[ZZ(6)], [ZZ(7)]]
assert mulmatmat(a, b, ZZ) == [[ZZ(31), ZZ(38)], [ZZ(47), ZZ(58)]]
assert mulmatmat(a, c, ZZ) == [[ZZ(3), ZZ(4)], [ZZ(5), ZZ(6)]]
assert mulmatmat(b, d, ZZ) == [[ZZ(20)], [ZZ(98)]]
def test_mulmatscaler():
a = eye(3, ZZ)
b = [[ZZ(3), ZZ(7), ZZ(4)], [ZZ(2), ZZ(4), ZZ(5)], [ZZ(6), ZZ(2), ZZ(3)]]
assert mulmatscaler(a, ZZ(4), ZZ) == [[ZZ(4), ZZ(0), ZZ(0)], [ZZ(0), ZZ(4), ZZ(0)], [ZZ(0), ZZ(0), ZZ(4)]]
assert mulmatscaler(b, ZZ(1), ZZ) == [[ZZ(3), ZZ(7), ZZ(4)], [ZZ(2), ZZ(4), ZZ(5)], [ZZ(6), ZZ(2), ZZ(3)]]
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
|
4e5a8d369b9e03b17d6ba77eae39d7a72a76b5a245048c2270874e2b73db659c | from sympy.testing.pytest import ignore_warnings
from sympy.utilities.exceptions import SymPyDeprecationWarning
with ignore_warnings(SymPyDeprecationWarning):
from sympy.matrices.densetools import trace, transpose, eye
from sympy.polys.domains.integerring import ZZ
def test_trace():
a = [[ZZ(3), ZZ(7), ZZ(4)], [ZZ(2), ZZ(4), ZZ(5)], [ZZ(6), ZZ(2), ZZ(3)]]
b = eye(2, ZZ)
assert trace(a, ZZ) == ZZ(10)
assert trace(b, ZZ) == ZZ(2)
def test_transpose():
a = [[ZZ(3), ZZ(7), ZZ(4)], [ZZ(2), ZZ(4), ZZ(5)], [ZZ(6), ZZ(2), ZZ(3)]]
b = eye(4, ZZ)
assert transpose(a, ZZ) == ([[ZZ(3), ZZ(2), ZZ(6)], [ZZ(7), ZZ(4), ZZ(2)], [ZZ(4), ZZ(5), ZZ(3)]])
assert transpose(b, ZZ) == b
|
44a42c0c38b0b846712fbf9b4c947fb9eec32866c265897ba6f8e3804ec4c846 | """
We have a few different kind of Matrices
Matrix, ImmutableMatrix, MatrixExpr
Here we test the extent to which they cooperate
"""
from sympy.core.symbol import symbols
from sympy.matrices import (Matrix, MatrixSymbol, eye, Identity,
ImmutableMatrix)
from sympy.matrices.expressions import MatrixExpr, MatAdd
from sympy.matrices.common import classof
from sympy.testing.pytest import raises
SM = MatrixSymbol('X', 3, 3)
SV = MatrixSymbol('v', 3, 1)
MM = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
IM = ImmutableMatrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
meye = eye(3)
imeye = ImmutableMatrix(eye(3))
ideye = Identity(3)
a, b, c = symbols('a,b,c')
def test_IM_MM():
assert isinstance(MM + IM, ImmutableMatrix)
assert isinstance(IM + MM, ImmutableMatrix)
assert isinstance(2*IM + MM, ImmutableMatrix)
assert MM.equals(IM)
def test_ME_MM():
assert isinstance(Identity(3) + MM, MatrixExpr)
assert isinstance(SM + MM, MatAdd)
assert isinstance(MM + SM, MatAdd)
assert (Identity(3) + MM)[1, 1] == 6
def test_equality():
a, b, c = Identity(3), eye(3), ImmutableMatrix(eye(3))
for x in [a, b, c]:
for y in [a, b, c]:
assert x.equals(y)
def test_matrix_symbol_MM():
X = MatrixSymbol('X', 3, 3)
Y = eye(3) + X
assert Y[1, 1] == 1 + X[1, 1]
def test_matrix_symbol_vector_matrix_multiplication():
A = MM * SV
B = IM * SV
assert A == B
C = (SV.T * MM.T).T
assert B == C
D = (SV.T * IM.T).T
assert C == D
def test_indexing_interactions():
assert (a * IM)[1, 1] == 5*a
assert (SM + IM)[1, 1] == SM[1, 1] + IM[1, 1]
assert (SM * IM)[1, 1] == SM[1, 0]*IM[0, 1] + SM[1, 1]*IM[1, 1] + \
SM[1, 2]*IM[2, 1]
def test_classof():
A = Matrix(3, 3, range(9))
B = ImmutableMatrix(3, 3, range(9))
C = MatrixSymbol('C', 3, 3)
assert classof(A, A) == Matrix
assert classof(B, B) == ImmutableMatrix
assert classof(A, B) == ImmutableMatrix
assert classof(B, A) == ImmutableMatrix
raises(TypeError, lambda: classof(A, C))
|
a63411e94684311f76368941fc8199f549a4e853d98ef234be4d457781ff0b92 | from sympy.matrices.sparsetools import _doktocsr, _csrtodok, banded
from sympy.matrices.dense import (Matrix, eye, ones, zeros)
from sympy.matrices import SparseMatrix
from sympy.testing.pytest import raises
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_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_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]])
|
47f9d132c15e2b4d6fac842a260d27cbd50bfb5ec468a2ac570fc401d273b88d | import random
import concurrent.futures
from collections.abc import Hashable
from sympy.core.add import Add
from sympy.core.function import (Function, diff, expand)
from sympy.core.numbers import (E, Float, I, Integer, Rational, nan, oo, pi)
from sympy.core.power import Pow
from sympy.core.singleton import S
from sympy.core.symbol import (Symbol, symbols)
from sympy.core.sympify import sympify
from sympy.functions.elementary.complexes import Abs
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.elementary.miscellaneous import (Max, Min, sqrt)
from sympy.functions.elementary.trigonometric import (cos, sin, tan)
from sympy.polys.polytools import (Poly, PurePoly)
from sympy.printing.str import sstr
from sympy.sets.sets import FiniteSet
from sympy.simplify.simplify import (signsimp, simplify)
from sympy.simplify.trigsimp import trigsimp
from sympy.matrices.matrices import (ShapeError, MatrixError,
NonSquareMatrixError, DeferredVector, _find_reasonable_pivot_naive,
_simplify)
from sympy.matrices import (
GramSchmidt, ImmutableMatrix, ImmutableSparseMatrix, Matrix,
SparseMatrix, casoratian, diag, eye, hessian,
matrix_multiply_elementwise, ones, randMatrix, rot_axis1, rot_axis2,
rot_axis3, wronskian, zeros, MutableDenseMatrix, ImmutableDenseMatrix,
MatrixSymbol, dotprodsimp)
from sympy.matrices.utilities import _dotprodsimp_state
from sympy.core import Tuple, Wild
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.utilities.iterables import flatten, capture, iterable
from sympy.testing.pytest import raises, XFAIL, slow, skip, warns_deprecated_sympy
from sympy.assumptions import Q
from sympy.tensor.array import Array
from sympy.matrices.expressions import MatPow
from sympy.abc import a, b, c, d, x, y, z, t
# don't re-order this list
classes = (Matrix, SparseMatrix, ImmutableMatrix, ImmutableSparseMatrix)
def test_args():
for n, cls in enumerate(classes):
m = cls.zeros(3, 2)
# all should give back the same type of arguments, e.g. ints for shape
assert m.shape == (3, 2) and all(type(i) is int for i in m.shape)
assert m.rows == 3 and type(m.rows) is int
assert m.cols == 2 and type(m.cols) is int
if not n % 2:
assert type(m.flat()) in (list, tuple, Tuple)
else:
assert type(m.todok()) is dict
def test_deprecated_mat_smat():
for cls in Matrix, ImmutableMatrix:
m = cls.zeros(3, 2)
with warns_deprecated_sympy():
mat = m._mat
assert mat == m.flat()
for cls in SparseMatrix, ImmutableSparseMatrix:
m = cls.zeros(3, 2)
with warns_deprecated_sympy():
smat = m._smat
assert smat == m.todok()
def test_division():
v = Matrix(1, 2, [x, y])
assert v/z == Matrix(1, 2, [x/z, y/z])
def test_sum():
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]])
n = Matrix(1, 2, [1, 2])
raises(ShapeError, lambda: m + n)
def test_abs():
m = Matrix(1, 2, [-3, x])
n = Matrix(1, 2, [3, Abs(x)])
assert abs(m) == n
def test_addition():
a = Matrix((
(1, 2),
(3, 1),
))
b = Matrix((
(1, 2),
(3, 0),
))
assert a + b == a.add(b) == Matrix([[2, 4], [6, 1]])
def test_fancy_index_matrix():
for M in (Matrix, SparseMatrix):
a = M(3, 3, range(9))
assert a == a[:, :]
assert a[1, :] == Matrix(1, 3, [3, 4, 5])
assert a[:, 1] == Matrix([1, 4, 7])
assert a[[0, 1], :] == Matrix([[0, 1, 2], [3, 4, 5]])
assert a[[0, 1], 2] == a[[0, 1], [2]]
assert a[2, [0, 1]] == a[[2], [0, 1]]
assert a[:, [0, 1]] == Matrix([[0, 1], [3, 4], [6, 7]])
assert a[0, 0] == 0
assert a[0:2, :] == Matrix([[0, 1, 2], [3, 4, 5]])
assert a[:, 0:2] == Matrix([[0, 1], [3, 4], [6, 7]])
assert a[::2, 1] == a[[0, 2], 1]
assert a[1, ::2] == a[1, [0, 2]]
a = M(3, 3, range(9))
assert a[[0, 2, 1, 2, 1], :] == Matrix([
[0, 1, 2],
[6, 7, 8],
[3, 4, 5],
[6, 7, 8],
[3, 4, 5]])
assert a[:, [0,2,1,2,1]] == Matrix([
[0, 2, 1, 2, 1],
[3, 5, 4, 5, 4],
[6, 8, 7, 8, 7]])
a = SparseMatrix.zeros(3)
a[1, 2] = 2
a[0, 1] = 3
a[2, 0] = 4
assert a.extract([1, 1], [2]) == Matrix([
[2],
[2]])
assert a.extract([1, 0], [2, 2, 2]) == Matrix([
[2, 2, 2],
[0, 0, 0]])
assert a.extract([1, 0, 1, 2], [2, 0, 1, 0]) == Matrix([
[2, 0, 0, 0],
[0, 0, 3, 0],
[2, 0, 0, 0],
[0, 4, 0, 4]])
def test_multiplication():
a = Matrix((
(1, 2),
(3, 1),
(0, 6),
))
b = Matrix((
(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
h = matrix_multiply_elementwise(a, c)
assert h == a.multiply_elementwise(c)
assert h[0, 0] == 7
assert h[0, 1] == 4
assert h[1, 0] == 18
assert h[1, 1] == 6
assert h[2, 0] == 0
assert h[2, 1] == 0
raises(ShapeError, lambda: matrix_multiply_elementwise(a, b))
c = b * Symbol("x")
assert isinstance(c, Matrix)
assert c[0, 0] == x
assert c[0, 1] == 2*x
assert c[1, 0] == 3*x
assert c[1, 1] == 0
c2 = x * b
assert c == c2
c = 5 * b
assert isinstance(c, Matrix)
assert c[0, 0] == 5
assert c[0, 1] == 2*5
assert c[1, 0] == 3*5
assert c[1, 1] == 0
try:
eval('c = 5 @ b')
except SyntaxError:
pass
else:
assert isinstance(c, Matrix)
assert c[0, 0] == 5
assert c[0, 1] == 2*5
assert c[1, 0] == 3*5
assert c[1, 1] == 0
M = Matrix([[oo, 0], [0, oo]])
assert M ** 2 == M
M = Matrix([[oo, oo], [0, 0]])
assert M ** 2 == Matrix([[nan, nan], [nan, nan]])
def test_power():
raises(NonSquareMatrixError, lambda: Matrix((1, 2))**2)
R = Rational
A = Matrix([[2, 3], [4, 5]])
assert (A**-3)[:] == [R(-269)/8, R(153)/8, R(51)/2, R(-29)/2]
assert (A**5)[:] == [6140, 8097, 10796, 14237]
A = Matrix([[2, 1, 3], [4, 2, 4], [6, 12, 1]])
assert (A**3)[:] == [290, 262, 251, 448, 440, 368, 702, 954, 433]
assert A**0 == eye(3)
assert A**1 == A
assert (Matrix([[2]]) ** 100)[0, 0] == 2**100
assert eye(2)**10000000 == eye(2)
assert Matrix([[1, 2], [3, 4]])**Integer(2) == Matrix([[7, 10], [15, 22]])
A = Matrix([[33, 24], [48, 57]])
assert (A**S.Half)[:] == [5, 2, 4, 7]
A = Matrix([[0, 4], [-1, 5]])
assert (A**S.Half)**2 == A
assert Matrix([[1, 0], [1, 1]])**S.Half == Matrix([[1, 0], [S.Half, 1]])
assert Matrix([[1, 0], [1, 1]])**0.5 == Matrix([[1.0, 0], [0.5, 1.0]])
from sympy.abc import n
assert Matrix([[1, a], [0, 1]])**n == Matrix([[1, a*n], [0, 1]])
assert Matrix([[b, a], [0, b]])**n == Matrix([[b**n, a*b**(n-1)*n], [0, b**n]])
assert Matrix([
[a**n, a**(n - 1)*n, (a**n*n**2 - a**n*n)/(2*a**2)],
[ 0, a**n, a**(n - 1)*n],
[ 0, 0, a**n]])
assert Matrix([[a, 1, 0], [0, a, 0], [0, 0, b]])**n == Matrix([
[a**n, a**(n-1)*n, 0],
[0, a**n, 0],
[0, 0, b**n]])
A = Matrix([[1, 0], [1, 7]])
assert A._matrix_pow_by_jordan_blocks(S(3)) == A._eval_pow_by_recursion(3)
A = Matrix([[2]])
assert A**10 == Matrix([[2**10]]) == A._matrix_pow_by_jordan_blocks(S(10)) == \
A._eval_pow_by_recursion(10)
# testing a matrix that cannot be jordan blocked issue 11766
m = Matrix([[3, 0, 0, 0, -3], [0, -3, -3, 0, 3], [0, 3, 0, 3, 0], [0, 0, 3, 0, 3], [3, 0, 0, 3, 0]])
raises(MatrixError, lambda: m._matrix_pow_by_jordan_blocks(S(10)))
# test issue 11964
raises(MatrixError, lambda: Matrix([[1, 1], [3, 3]])._matrix_pow_by_jordan_blocks(S(-10)))
A = Matrix([[0, 1, 0], [0, 0, 1], [0, 0, 0]]) # Nilpotent jordan block size 3
assert A**10.0 == Matrix([[0, 0, 0], [0, 0, 0], [0, 0, 0]])
raises(ValueError, lambda: A**2.1)
raises(ValueError, lambda: A**Rational(3, 2))
A = Matrix([[8, 1], [3, 2]])
assert A**10.0 == Matrix([[1760744107, 272388050], [817164150, 126415807]])
A = Matrix([[0, 0, 1], [0, 0, 1], [0, 0, 1]]) # Nilpotent jordan block size 1
assert A**10.0 == Matrix([[0, 0, 1], [0, 0, 1], [0, 0, 1]])
A = Matrix([[0, 1, 0], [0, 0, 1], [0, 0, 1]]) # Nilpotent jordan block size 2
assert A**10.0 == Matrix([[0, 0, 1], [0, 0, 1], [0, 0, 1]])
n = Symbol('n', integer=True)
assert isinstance(A**n, MatPow)
n = Symbol('n', integer=True, negative=True)
raises(ValueError, lambda: A**n)
n = Symbol('n', integer=True, nonnegative=True)
assert A**n == Matrix([
[KroneckerDelta(0, n), KroneckerDelta(1, n), -KroneckerDelta(0, n) - KroneckerDelta(1, n) + 1],
[ 0, KroneckerDelta(0, n), 1 - KroneckerDelta(0, n)],
[ 0, 0, 1]])
assert A**(n + 2) == Matrix([[0, 0, 1], [0, 0, 1], [0, 0, 1]])
raises(ValueError, lambda: A**Rational(3, 2))
A = Matrix([[0, 0, 1], [3, 0, 1], [4, 3, 1]])
assert A**5.0 == Matrix([[168, 72, 89], [291, 144, 161], [572, 267, 329]])
assert A**5.0 == A**5
A = Matrix([[0, 1, 0],[-1, 0, 0],[0, 0, 0]])
n = Symbol("n")
An = A**n
assert An.subs(n, 2).doit() == A**2
raises(ValueError, lambda: An.subs(n, -2).doit())
assert An * An == A**(2*n)
# concretizing behavior for non-integer and complex powers
A = Matrix([[0,0,0],[0,0,0],[0,0,0]])
n = Symbol('n', integer=True, positive=True)
assert A**n == A
n = Symbol('n', integer=True, nonnegative=True)
assert A**n == diag(0**n, 0**n, 0**n)
assert (A**n).subs(n, 0) == eye(3)
assert (A**n).subs(n, 1) == zeros(3)
A = Matrix ([[2,0,0],[0,2,0],[0,0,2]])
assert A**2.1 == diag (2**2.1, 2**2.1, 2**2.1)
assert A**I == diag (2**I, 2**I, 2**I)
A = Matrix([[0, 1, 0], [0, 0, 1], [0, 0, 1]])
raises(ValueError, lambda: A**2.1)
raises(ValueError, lambda: A**I)
A = Matrix([[S.Half, S.Half], [S.Half, S.Half]])
assert A**S.Half == A
A = Matrix([[1, 1],[3, 3]])
assert A**S.Half == Matrix ([[S.Half, S.Half], [3*S.Half, 3*S.Half]])
def test_issue_17247_expression_blowup_1():
M = Matrix([[1+x, 1-x], [1-x, 1+x]])
with dotprodsimp(True):
assert M.exp().expand() == Matrix([
[ (exp(2*x) + exp(2))/2, (-exp(2*x) + exp(2))/2],
[(-exp(2*x) + exp(2))/2, (exp(2*x) + exp(2))/2]])
def test_issue_17247_expression_blowup_2():
M = Matrix([[1+x, 1-x], [1-x, 1+x]])
with dotprodsimp(True):
P, J = M.jordan_form ()
assert P*J*P.inv()
def test_issue_17247_expression_blowup_3():
M = Matrix([[1+x, 1-x], [1-x, 1+x]])
with dotprodsimp(True):
assert M**100 == Matrix([
[633825300114114700748351602688*x**100 + 633825300114114700748351602688, 633825300114114700748351602688 - 633825300114114700748351602688*x**100],
[633825300114114700748351602688 - 633825300114114700748351602688*x**100, 633825300114114700748351602688*x**100 + 633825300114114700748351602688]])
def test_issue_17247_expression_blowup_4():
# This matrix takes extremely long on current master even with intermediate simplification so an abbreviated version is used. It is left here for test in case of future optimizations.
# M = Matrix(S('''[
# [ -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64, -9/32 - I/16, 183/256 - 97*I/128, 3/64 + 13*I/64, -23/32 - 59*I/256, 15/128 - 3*I/32, 19/256 + 551*I/1024],
# [-149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512, -219/128 + 115*I/256, 6301/4096 - 6609*I/1024, 119/128 + 143*I/128, -10879/2048 + 4343*I/4096, 129/256 - 549*I/512, 42533/16384 + 29103*I/8192],
# [ 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64, -9/32 - I/16, 183/256 - 97*I/128, 3/64 + 13*I/64, -23/32 - 59*I/256],
# [ -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512, -219/128 + 115*I/256, 6301/4096 - 6609*I/1024, 119/128 + 143*I/128, -10879/2048 + 4343*I/4096],
# [ 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64, -9/32 - I/16, 183/256 - 97*I/128],
# [ 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512, -219/128 + 115*I/256, 6301/4096 - 6609*I/1024],
# [ -2, 17/4 - 13*I/2, 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64],
# [ 1/4 + 13*I/4, -825/64 - 147*I/32, 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512],
# [ -4*I, 27/2 + 6*I, -2, 17/4 - 13*I/2, 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64],
# [ 1/4 + 5*I/2, -23/8 - 57*I/16, 1/4 + 13*I/4, -825/64 - 147*I/32, 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128],
# [ -4, 9 - 5*I, -4*I, 27/2 + 6*I, -2, 17/4 - 13*I/2, 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16],
# [ -2*I, 119/8 + 29*I/4, 1/4 + 5*I/2, -23/8 - 57*I/16, 1/4 + 13*I/4, -825/64 - 147*I/32, 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128]]'''))
# assert M**10 == Matrix([
# [ 7*(-221393644768594642173548179825793834595 - 1861633166167425978847110897013541127952*I)/9671406556917033397649408, 15*(31670992489131684885307005100073928751695 + 10329090958303458811115024718207404523808*I)/77371252455336267181195264, 7*(-3710978679372178839237291049477017392703 + 1377706064483132637295566581525806894169*I)/19342813113834066795298816, (9727707023582419994616144751727760051598 - 59261571067013123836477348473611225724433*I)/9671406556917033397649408, (31896723509506857062605551443641668183707 + 54643444538699269118869436271152084599580*I)/38685626227668133590597632, (-2024044860947539028275487595741003997397402 + 130959428791783397562960461903698670485863*I)/309485009821345068724781056, 3*(26190251453797590396533756519358368860907 - 27221191754180839338002754608545400941638*I)/77371252455336267181195264, (1154643595139959842768960128434994698330461 + 3385496216250226964322872072260446072295634*I)/618970019642690137449562112, 3*(-31849347263064464698310044805285774295286 - 11877437776464148281991240541742691164309*I)/77371252455336267181195264, (4661330392283532534549306589669150228040221 - 4171259766019818631067810706563064103956871*I)/1237940039285380274899124224, (9598353794289061833850770474812760144506 + 358027153990999990968244906482319780943983*I)/309485009821345068724781056, (-9755135335127734571547571921702373498554177 - 4837981372692695195747379349593041939686540*I)/2475880078570760549798248448],
# [(-379516731607474268954110071392894274962069 - 422272153179747548473724096872271700878296*I)/77371252455336267181195264, (41324748029613152354787280677832014263339501 - 12715121258662668420833935373453570749288074*I)/1237940039285380274899124224, (-339216903907423793947110742819264306542397 + 494174755147303922029979279454787373566517*I)/77371252455336267181195264, (-18121350839962855576667529908850640619878381 - 37413012454129786092962531597292531089199003*I)/1237940039285380274899124224, (2489661087330511608618880408199633556675926 + 1137821536550153872137379935240732287260863*I)/309485009821345068724781056, (-136644109701594123227587016790354220062972119 + 110130123468183660555391413889600443583585272*I)/4951760157141521099596496896, (1488043981274920070468141664150073426459593 - 9691968079933445130866371609614474474327650*I)/1237940039285380274899124224, 27*(4636797403026872518131756991410164760195942 + 3369103221138229204457272860484005850416533*I)/4951760157141521099596496896, (-8534279107365915284081669381642269800472363 + 2241118846262661434336333368511372725482742*I)/1237940039285380274899124224, (60923350128174260992536531692058086830950875 - 263673488093551053385865699805250505661590126*I)/9903520314283042199192993792, (18520943561240714459282253753348921824172569 + 24846649186468656345966986622110971925703604*I)/4951760157141521099596496896, (-232781130692604829085973604213529649638644431 + 35981505277760667933017117949103953338570617*I)/9903520314283042199192993792],
# [ (8742968295129404279528270438201520488950 + 3061473358639249112126847237482570858327*I)/4835703278458516698824704, (-245657313712011778432792959787098074935273 + 253113767861878869678042729088355086740856*I)/38685626227668133590597632, (1947031161734702327107371192008011621193 - 19462330079296259148177542369999791122762*I)/9671406556917033397649408, (552856485625209001527688949522750288619217 + 392928441196156725372494335248099016686580*I)/77371252455336267181195264, (-44542866621905323121630214897126343414629 + 3265340021421335059323962377647649632959*I)/19342813113834066795298816, (136272594005759723105646069956434264218730 - 330975364731707309489523680957584684763587*I)/38685626227668133590597632, (27392593965554149283318732469825168894401 + 75157071243800133880129376047131061115278*I)/38685626227668133590597632, 7*(-357821652913266734749960136017214096276154 - 45509144466378076475315751988405961498243*I)/309485009821345068724781056, (104485001373574280824835174390219397141149 - 99041000529599568255829489765415726168162*I)/77371252455336267181195264, (1198066993119982409323525798509037696321291 + 4249784165667887866939369628840569844519936*I)/618970019642690137449562112, (-114985392587849953209115599084503853611014 - 52510376847189529234864487459476242883449*I)/77371252455336267181195264, (6094620517051332877965959223269600650951573 - 4683469779240530439185019982269137976201163*I)/1237940039285380274899124224],
# [ (611292255597977285752123848828590587708323 - 216821743518546668382662964473055912169502*I)/77371252455336267181195264, (-1144023204575811464652692396337616594307487 + 12295317806312398617498029126807758490062855*I)/309485009821345068724781056, (-374093027769390002505693378578475235158281 - 573533923565898290299607461660384634333639*I)/77371252455336267181195264, (47405570632186659000138546955372796986832987 - 2837476058950808941605000274055970055096534*I)/1237940039285380274899124224, (-571573207393621076306216726219753090535121 + 533381457185823100878764749236639320783831*I)/77371252455336267181195264, (-7096548151856165056213543560958582513797519 - 24035731898756040059329175131592138642195366*I)/618970019642690137449562112, (2396762128833271142000266170154694033849225 + 1448501087375679588770230529017516492953051*I)/309485009821345068724781056, (-150609293845161968447166237242456473262037053 + 92581148080922977153207018003184520294188436*I)/4951760157141521099596496896, 5*(270278244730804315149356082977618054486347 - 1997830155222496880429743815321662710091562*I)/1237940039285380274899124224, (62978424789588828258068912690172109324360330 + 44803641177219298311493356929537007630129097*I)/2475880078570760549798248448, 19*(-451431106327656743945775812536216598712236 + 114924966793632084379437683991151177407937*I)/1237940039285380274899124224, (63417747628891221594106738815256002143915995 - 261508229397507037136324178612212080871150958*I)/9903520314283042199192993792],
# [ (-2144231934021288786200752920446633703357 + 2305614436009705803670842248131563850246*I)/1208925819614629174706176, (-90720949337459896266067589013987007078153 - 221951119475096403601562347412753844534569*I)/19342813113834066795298816, (11590973613116630788176337262688659880376 + 6514520676308992726483494976339330626159*I)/4835703278458516698824704, 3*(-131776217149000326618649542018343107657237 + 79095042939612668486212006406818285287004*I)/38685626227668133590597632, (10100577916793945997239221374025741184951 - 28631383488085522003281589065994018550748*I)/9671406556917033397649408, 67*(10090295594251078955008130473573667572549 + 10449901522697161049513326446427839676762*I)/77371252455336267181195264, (-54270981296988368730689531355811033930513 - 3413683117592637309471893510944045467443*I)/19342813113834066795298816, (440372322928679910536575560069973699181278 - 736603803202303189048085196176918214409081*I)/77371252455336267181195264, (33220374714789391132887731139763250155295 + 92055083048787219934030779066298919603554*I)/38685626227668133590597632, 5*(-594638554579967244348856981610805281527116 - 82309245323128933521987392165716076704057*I)/309485009821345068724781056, (128056368815300084550013708313312073721955 - 114619107488668120303579745393765245911404*I)/77371252455336267181195264, 21*(59839959255173222962789517794121843393573 + 241507883613676387255359616163487405826334*I)/618970019642690137449562112],
# [ (-13454485022325376674626653802541391955147 + 184471402121905621396582628515905949793486*I)/19342813113834066795298816, (-6158730123400322562149780662133074862437105 - 3416173052604643794120262081623703514107476*I)/154742504910672534362390528, (770558003844914708453618983120686116100419 - 127758381209767638635199674005029818518766*I)/77371252455336267181195264, (-4693005771813492267479835161596671660631703 + 12703585094750991389845384539501921531449948*I)/309485009821345068724781056, (-295028157441149027913545676461260860036601 - 841544569970643160358138082317324743450770*I)/77371252455336267181195264, (56716442796929448856312202561538574275502893 + 7216818824772560379753073185990186711454778*I)/1237940039285380274899124224, 15*(-87061038932753366532685677510172566368387 + 61306141156647596310941396434445461895538*I)/154742504910672534362390528, (-3455315109680781412178133042301025723909347 - 24969329563196972466388460746447646686670670*I)/618970019642690137449562112, (2453418854160886481106557323699250865361849 + 1497886802326243014471854112161398141242514*I)/309485009821345068724781056, (-151343224544252091980004429001205664193082173 + 90471883264187337053549090899816228846836628*I)/4951760157141521099596496896, (1652018205533026103358164026239417416432989 - 9959733619236515024261775397109724431400162*I)/1237940039285380274899124224, 3*(40676374242956907656984876692623172736522006 + 31023357083037817469535762230872667581366205*I)/4951760157141521099596496896],
# [ (-1226990509403328460274658603410696548387 - 4131739423109992672186585941938392788458*I)/1208925819614629174706176, (162392818524418973411975140074368079662703 + 23706194236915374831230612374344230400704*I)/9671406556917033397649408, (-3935678233089814180000602553655565621193 + 2283744757287145199688061892165659502483*I)/1208925819614629174706176, (-2400210250844254483454290806930306285131 - 315571356806370996069052930302295432758205*I)/19342813113834066795298816, (13365917938215281056563183751673390817910 + 15911483133819801118348625831132324863881*I)/4835703278458516698824704, 3*(-215950551370668982657516660700301003897855 + 51684341999223632631602864028309400489378*I)/38685626227668133590597632, (20886089946811765149439844691320027184765 - 30806277083146786592790625980769214361844*I)/9671406556917033397649408, (562180634592713285745940856221105667874855 + 1031543963988260765153550559766662245114916*I)/77371252455336267181195264, (-65820625814810177122941758625652476012867 - 12429918324787060890804395323920477537595*I)/19342813113834066795298816, (319147848192012911298771180196635859221089 - 402403304933906769233365689834404519960394*I)/38685626227668133590597632, (23035615120921026080284733394359587955057 + 115351677687031786114651452775242461310624*I)/38685626227668133590597632, (-3426830634881892756966440108592579264936130 - 1022954961164128745603407283836365128598559*I)/309485009821345068724781056],
# [ (-192574788060137531023716449082856117537757 - 69222967328876859586831013062387845780692*I)/19342813113834066795298816, (2736383768828013152914815341491629299773262 - 2773252698016291897599353862072533475408743*I)/77371252455336267181195264, (-23280005281223837717773057436155921656805 + 214784953368021840006305033048142888879224*I)/19342813113834066795298816, (-3035247484028969580570400133318947903462326 - 2195168903335435855621328554626336958674325*I)/77371252455336267181195264, (984552428291526892214541708637840971548653 - 64006622534521425620714598573494988589378*I)/77371252455336267181195264, (-3070650452470333005276715136041262898509903 + 7286424705750810474140953092161794621989080*I)/154742504910672534362390528, (-147848877109756404594659513386972921139270 - 416306113044186424749331418059456047650861*I)/38685626227668133590597632, (55272118474097814260289392337160619494260781 + 7494019668394781211907115583302403519488058*I)/1237940039285380274899124224, (-581537886583682322424771088996959213068864 + 542191617758465339135308203815256798407429*I)/77371252455336267181195264, (-6422548983676355789975736799494791970390991 - 23524183982209004826464749309156698827737702*I)/618970019642690137449562112, 7*(180747195387024536886923192475064903482083 + 84352527693562434817771649853047924991804*I)/154742504910672534362390528, (-135485179036717001055310712747643466592387031 + 102346575226653028836678855697782273460527608*I)/4951760157141521099596496896],
# [ (3384238362616083147067025892852431152105 + 156724444932584900214919898954874618256*I)/604462909807314587353088, (-59558300950677430189587207338385764871866 + 114427143574375271097298201388331237478857*I)/4835703278458516698824704, (-1356835789870635633517710130971800616227 - 7023484098542340388800213478357340875410*I)/1208925819614629174706176, (234884918567993750975181728413524549575881 + 79757294640629983786895695752733890213506*I)/9671406556917033397649408, (-7632732774935120473359202657160313866419 + 2905452608512927560554702228553291839465*I)/1208925819614629174706176, (52291747908702842344842889809762246649489 - 520996778817151392090736149644507525892649*I)/19342813113834066795298816, (17472406829219127839967951180375981717322 + 23464704213841582137898905375041819568669*I)/4835703278458516698824704, (-911026971811893092350229536132730760943307 + 150799318130900944080399439626714846752360*I)/38685626227668133590597632, (26234457233977042811089020440646443590687 - 45650293039576452023692126463683727692890*I)/9671406556917033397649408, 3*(288348388717468992528382586652654351121357 + 454526517721403048270274049572136109264668*I)/77371252455336267181195264, (-91583492367747094223295011999405657956347 - 12704691128268298435362255538069612411331*I)/19342813113834066795298816, (411208730251327843849027957710164064354221 - 569898526380691606955496789378230959965898*I)/38685626227668133590597632],
# [ (27127513117071487872628354831658811211795 - 37765296987901990355760582016892124833857*I)/4835703278458516698824704, (1741779916057680444272938534338833170625435 + 3083041729779495966997526404685535449810378*I)/77371252455336267181195264, 3*(-60642236251815783728374561836962709533401 - 24630301165439580049891518846174101510744*I)/19342813113834066795298816, 3*(445885207364591681637745678755008757483408 - 350948497734812895032502179455610024541643*I)/38685626227668133590597632, (-47373295621391195484367368282471381775684 + 219122969294089357477027867028071400054973*I)/19342813113834066795298816, (-2801565819673198722993348253876353741520438 - 2250142129822658548391697042460298703335701*I)/77371252455336267181195264, (801448252275607253266997552356128790317119 - 50890367688077858227059515894356594900558*I)/77371252455336267181195264, (-5082187758525931944557763799137987573501207 + 11610432359082071866576699236013484487676124*I)/309485009821345068724781056, (-328925127096560623794883760398247685166830 - 643447969697471610060622160899409680422019*I)/77371252455336267181195264, 15*(2954944669454003684028194956846659916299765 + 33434406416888505837444969347824812608566*I)/1237940039285380274899124224, (-415749104352001509942256567958449835766827 + 479330966144175743357171151440020955412219*I)/77371252455336267181195264, 3*(-4639987285852134369449873547637372282914255 - 11994411888966030153196659207284951579243273*I)/1237940039285380274899124224],
# [ (-478846096206269117345024348666145495601 + 1249092488629201351470551186322814883283*I)/302231454903657293676544, (-17749319421930878799354766626365926894989 - 18264580106418628161818752318217357231971*I)/1208925819614629174706176, (2801110795431528876849623279389579072819 + 363258850073786330770713557775566973248*I)/604462909807314587353088, (-59053496693129013745775512127095650616252 + 78143588734197260279248498898321500167517*I)/4835703278458516698824704, (-283186724922498212468162690097101115349 - 6443437753863179883794497936345437398276*I)/1208925819614629174706176, (188799118826748909206887165661384998787543 + 84274736720556630026311383931055307398820*I)/9671406556917033397649408, (-5482217151670072904078758141270295025989 + 1818284338672191024475557065444481298568*I)/1208925819614629174706176, (56564463395350195513805521309731217952281 - 360208541416798112109946262159695452898431*I)/19342813113834066795298816, 11*(1259539805728870739006416869463689438068 + 1409136581547898074455004171305324917387*I)/4835703278458516698824704, 5*(-123701190701414554945251071190688818343325 + 30997157322590424677294553832111902279712*I)/38685626227668133590597632, (16130917381301373033736295883982414239781 - 32752041297570919727145380131926943374516*I)/9671406556917033397649408, (650301385108223834347093740500375498354925 + 899526407681131828596801223402866051809258*I)/77371252455336267181195264],
# [ (9011388245256140876590294262420614839483 + 8167917972423946282513000869327525382672*I)/1208925819614629174706176, (-426393174084720190126376382194036323028924 + 180692224825757525982858693158209545430621*I)/9671406556917033397649408, (24588556702197802674765733448108154175535 - 45091766022876486566421953254051868331066*I)/4835703278458516698824704, (1872113939365285277373877183750416985089691 + 3030392393733212574744122057679633775773130*I)/77371252455336267181195264, (-222173405538046189185754954524429864167549 - 75193157893478637039381059488387511299116*I)/19342813113834066795298816, (2670821320766222522963689317316937579844558 - 2645837121493554383087981511645435472169191*I)/77371252455336267181195264, 5*(-2100110309556476773796963197283876204940 + 41957457246479840487980315496957337371937*I)/19342813113834066795298816, (-5733743755499084165382383818991531258980593 - 3328949988392698205198574824396695027195732*I)/154742504910672534362390528, (707827994365259025461378911159398206329247 - 265730616623227695108042528694302299777294*I)/77371252455336267181195264, (-1442501604682933002895864804409322823788319 + 11504137805563265043376405214378288793343879*I)/309485009821345068724781056, (-56130472299445561499538726459719629522285 - 61117552419727805035810982426639329818864*I)/9671406556917033397649408, (39053692321126079849054272431599539429908717 - 10209127700342570953247177602860848130710666*I)/1237940039285380274899124224]])
M = Matrix(S('''[
[ -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512],
[ 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64],
[ -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128],
[ 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16],
[ 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert M**10 == Matrix(S('''[
[ 7369525394972778926719607798014571861/604462909807314587353088 - 229284202061790301477392339912557559*I/151115727451828646838272, -19704281515163975949388435612632058035/1208925819614629174706176 + 14319858347987648723768698170712102887*I/302231454903657293676544, -3623281909451783042932142262164941211/604462909807314587353088 - 6039240602494288615094338643452320495*I/604462909807314587353088, 109260497799140408739847239685705357695/2417851639229258349412352 - 7427566006564572463236368211555511431*I/2417851639229258349412352, -16095803767674394244695716092817006641/2417851639229258349412352 + 10336681897356760057393429626719177583*I/1208925819614629174706176, -42207883340488041844332828574359769743/2417851639229258349412352 - 182332262671671273188016400290188468499*I/4835703278458516698824704],
[50566491050825573392726324995779608259/1208925819614629174706176 - 90047007594468146222002432884052362145*I/2417851639229258349412352, 74273703462900000967697427843983822011/1208925819614629174706176 + 265947522682943571171988741842776095421*I/1208925819614629174706176, -116900341394390200556829767923360888429/2417851639229258349412352 - 53153263356679268823910621474478756845*I/2417851639229258349412352, 195407378023867871243426523048612490249/1208925819614629174706176 - 1242417915995360200584837585002906728929*I/9671406556917033397649408, -863597594389821970177319682495878193/302231454903657293676544 + 476936100741548328800725360758734300481*I/9671406556917033397649408, -3154451590535653853562472176601754835575/19342813113834066795298816 - 232909875490506237386836489998407329215*I/2417851639229258349412352],
[ -1715444997702484578716037230949868543/302231454903657293676544 + 5009695651321306866158517287924120777*I/302231454903657293676544, -30551582497996879620371947949342101301/604462909807314587353088 - 7632518367986526187139161303331519629*I/151115727451828646838272, 312680739924495153190604170938220575/18889465931478580854784 - 108664334509328818765959789219208459*I/75557863725914323419136, -14693696966703036206178521686918865509/604462909807314587353088 + 72345386220900843930147151999899692401*I/1208925819614629174706176, -8218872496728882299722894680635296519/1208925819614629174706176 - 16776782833358893712645864791807664983*I/1208925819614629174706176, 143237839169380078671242929143670635137/2417851639229258349412352 + 2883817094806115974748882735218469447*I/2417851639229258349412352],
[ 3087979417831061365023111800749855987/151115727451828646838272 + 34441942370802869368851419102423997089*I/604462909807314587353088, -148309181940158040917731426845476175667/604462909807314587353088 - 263987151804109387844966835369350904919*I/9671406556917033397649408, 50259518594816377378747711930008883165/1208925819614629174706176 - 95713974916869240305450001443767979653*I/2417851639229258349412352, 153466447023875527996457943521467271119/2417851639229258349412352 + 517285524891117105834922278517084871349*I/2417851639229258349412352, -29184653615412989036678939366291205575/604462909807314587353088 - 27551322282526322041080173287022121083*I/1208925819614629174706176, 196404220110085511863671393922447671649/1208925819614629174706176 - 1204712019400186021982272049902206202145*I/9671406556917033397649408],
[ -2632581805949645784625606590600098779/151115727451828646838272 - 589957435912868015140272627522612771*I/37778931862957161709568, 26727850893953715274702844733506310247/302231454903657293676544 - 10825791956782128799168209600694020481*I/302231454903657293676544, -1036348763702366164044671908440791295/151115727451828646838272 + 3188624571414467767868303105288107375*I/151115727451828646838272, -36814959939970644875593411585393242449/604462909807314587353088 - 18457555789119782404850043842902832647*I/302231454903657293676544, 12454491297984637815063964572803058647/604462909807314587353088 - 340489532842249733975074349495329171*I/302231454903657293676544, -19547211751145597258386735573258916681/604462909807314587353088 + 87299583775782199663414539883938008933*I/1208925819614629174706176],
[ -40281994229560039213253423262678393183/604462909807314587353088 - 2939986850065527327299273003299736641*I/604462909807314587353088, 331940684638052085845743020267462794181/2417851639229258349412352 - 284574901963624403933361315517248458969*I/1208925819614629174706176, 6453843623051745485064693628073010961/302231454903657293676544 + 36062454107479732681350914931391590957*I/604462909807314587353088, -147665869053634695632880753646441962067/604462909807314587353088 - 305987938660447291246597544085345123927*I/9671406556917033397649408, 107821369195275772166593879711259469423/2417851639229258349412352 - 11645185518211204108659001435013326687*I/302231454903657293676544, 64121228424717666402009446088588091619/1208925819614629174706176 + 265557133337095047883844369272389762133*I/1208925819614629174706176]]'''))
def test_issue_17247_expression_blowup_5():
M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I)
with dotprodsimp(True):
assert M.charpoly('x') == PurePoly(x**6 + (-6 - 6*I)*x**5 + 36*I*x**4, x, domain='EX')
def test_issue_17247_expression_blowup_6():
M = Matrix(8, 8, [x+i for i in range (64)])
with dotprodsimp(True):
assert M.det('bareiss') == 0
def test_issue_17247_expression_blowup_7():
M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I)
with dotprodsimp(True):
assert M.det('berkowitz') == 0
def test_issue_17247_expression_blowup_8():
M = Matrix(8, 8, [x+i for i in range (64)])
with dotprodsimp(True):
assert M.det('lu') == 0
def test_issue_17247_expression_blowup_9():
M = Matrix(8, 8, [x+i for i in range (64)])
with dotprodsimp(True):
assert M.rref() == (Matrix([
[1, 0, -1, -2, -3, -4, -5, -6],
[0, 1, 2, 3, 4, 5, 6, 7],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0]]), (0, 1))
def test_issue_17247_expression_blowup_10():
M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I)
with dotprodsimp(True):
assert M.cofactor(0, 0) == 0
def test_issue_17247_expression_blowup_11():
M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I)
with dotprodsimp(True):
assert M.cofactor_matrix() == Matrix(6, 6, [0]*36)
def test_issue_17247_expression_blowup_12():
M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I)
with dotprodsimp(True):
assert M.eigenvals() == {6: 1, 6*I: 1, 0: 4}
def test_issue_17247_expression_blowup_13():
M = Matrix([
[ 0, 1 - x, x + 1, 1 - x],
[1 - x, x + 1, 0, x + 1],
[ 0, 1 - x, x + 1, 1 - x],
[ 0, 0, 1 - x, 0]])
ev = M.eigenvects()
assert ev[0] == (0, 2, [Matrix([0, -1, 0, 1])])
assert ev[1][0] == x - sqrt(2)*(x - 1) + 1
assert ev[1][1] == 1
assert ev[1][2][0].expand(deep=False, numer=True) == Matrix([
[(-x + sqrt(2)*(x - 1) - 1)/(x - 1)],
[-4*x/(x**2 - 2*x + 1) + (x + 1)*(x - sqrt(2)*(x - 1) + 1)/(x**2 - 2*x + 1)],
[(-x + sqrt(2)*(x - 1) - 1)/(x - 1)],
[1]
])
assert ev[2][0] == x + sqrt(2)*(x - 1) + 1
assert ev[2][1] == 1
assert ev[2][2][0].expand(deep=False, numer=True) == Matrix([
[(-x - sqrt(2)*(x - 1) - 1)/(x - 1)],
[-4*x/(x**2 - 2*x + 1) + (x + 1)*(x + sqrt(2)*(x - 1) + 1)/(x**2 - 2*x + 1)],
[(-x - sqrt(2)*(x - 1) - 1)/(x - 1)],
[1]
])
def test_issue_17247_expression_blowup_14():
M = Matrix(8, 8, ([1+x, 1-x]*4 + [1-x, 1+x]*4)*4)
with dotprodsimp(True):
assert M.echelon_form() == Matrix([
[x + 1, 1 - x, x + 1, 1 - x, x + 1, 1 - x, x + 1, 1 - x],
[ 0, 4*x, 0, 4*x, 0, 4*x, 0, 4*x],
[ 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0]])
def test_issue_17247_expression_blowup_15():
M = Matrix(8, 8, ([1+x, 1-x]*4 + [1-x, 1+x]*4)*4)
with dotprodsimp(True):
assert M.rowspace() == [Matrix([[x + 1, 1 - x, x + 1, 1 - x, x + 1, 1 - x, x + 1, 1 - x]]), Matrix([[0, 4*x, 0, 4*x, 0, 4*x, 0, 4*x]])]
def test_issue_17247_expression_blowup_16():
M = Matrix(8, 8, ([1+x, 1-x]*4 + [1-x, 1+x]*4)*4)
with dotprodsimp(True):
assert M.columnspace() == [Matrix([[x + 1],[1 - x],[x + 1],[1 - x],[x + 1],[1 - x],[x + 1],[1 - x]]), Matrix([[1 - x],[x + 1],[1 - x],[x + 1],[1 - x],[x + 1],[1 - x],[x + 1]])]
def test_issue_17247_expression_blowup_17():
M = Matrix(8, 8, [x+i for i in range (64)])
with dotprodsimp(True):
assert M.nullspace() == [
Matrix([[1],[-2],[1],[0],[0],[0],[0],[0]]),
Matrix([[2],[-3],[0],[1],[0],[0],[0],[0]]),
Matrix([[3],[-4],[0],[0],[1],[0],[0],[0]]),
Matrix([[4],[-5],[0],[0],[0],[1],[0],[0]]),
Matrix([[5],[-6],[0],[0],[0],[0],[1],[0]]),
Matrix([[6],[-7],[0],[0],[0],[0],[0],[1]])]
def test_issue_17247_expression_blowup_18():
M = Matrix(6, 6, ([1+x, 1-x]*3 + [1-x, 1+x]*3)*3)
with dotprodsimp(True):
assert not M.is_nilpotent()
def test_issue_17247_expression_blowup_19():
M = Matrix(S('''[
[ -3/4, 0, 1/4 + I/2, 0],
[ 0, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 1/2 - I, 0, 0, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert not M.is_diagonalizable()
def test_issue_17247_expression_blowup_20():
M = Matrix([
[x + 1, 1 - x, 0, 0],
[1 - x, x + 1, 0, x + 1],
[ 0, 1 - x, x + 1, 0],
[ 0, 0, 0, x + 1]])
with dotprodsimp(True):
assert M.diagonalize() == (Matrix([
[1, 1, 0, (x + 1)/(x - 1)],
[1, -1, 0, 0],
[1, 1, 1, 0],
[0, 0, 0, 1]]),
Matrix([
[2, 0, 0, 0],
[0, 2*x, 0, 0],
[0, 0, x + 1, 0],
[0, 0, 0, x + 1]]))
def test_issue_17247_expression_blowup_21():
M = Matrix(S('''[
[ -3/4, 45/32 - 37*I/16, 0, 0],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert M.inv(method='GE') == Matrix(S('''[
[-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785],
[4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785],
[-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905],
[0, 0, 0, -11328/952745 + 87616*I/952745]]'''))
def test_issue_17247_expression_blowup_22():
M = Matrix(S('''[
[ -3/4, 45/32 - 37*I/16, 0, 0],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert M.inv(method='LU') == Matrix(S('''[
[-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785],
[4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785],
[-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905],
[0, 0, 0, -11328/952745 + 87616*I/952745]]'''))
def test_issue_17247_expression_blowup_23():
M = Matrix(S('''[
[ -3/4, 45/32 - 37*I/16, 0, 0],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert M.inv(method='ADJ').expand() == Matrix(S('''[
[-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785],
[4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785],
[-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905],
[0, 0, 0, -11328/952745 + 87616*I/952745]]'''))
def test_issue_17247_expression_blowup_24():
M = SparseMatrix(S('''[
[ -3/4, 45/32 - 37*I/16, 0, 0],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert M.inv(method='CH') == Matrix(S('''[
[-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785],
[4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785],
[-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905],
[0, 0, 0, -11328/952745 + 87616*I/952745]]'''))
def test_issue_17247_expression_blowup_25():
M = SparseMatrix(S('''[
[ -3/4, 45/32 - 37*I/16, 0, 0],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert M.inv(method='LDL') == Matrix(S('''[
[-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785],
[4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785],
[-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905],
[0, 0, 0, -11328/952745 + 87616*I/952745]]'''))
def test_issue_17247_expression_blowup_26():
M = Matrix(S('''[
[ -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64, -9/32 - I/16, 183/256 - 97*I/128],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512, -219/128 + 115*I/256, 6301/4096 - 6609*I/1024],
[ 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64],
[ -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512],
[ 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64],
[ 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128],
[ -2, 17/4 - 13*I/2, 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16],
[ 1/4 + 13*I/4, -825/64 - 147*I/32, 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert M.rank() == 4
def test_issue_17247_expression_blowup_27():
M = Matrix([
[ 0, 1 - x, x + 1, 1 - x],
[1 - x, x + 1, 0, x + 1],
[ 0, 1 - x, x + 1, 1 - x],
[ 0, 0, 1 - x, 0]])
with dotprodsimp(True):
P, J = M.jordan_form()
assert P.expand() == Matrix(S('''[
[ 0, 4*x/(x**2 - 2*x + 1), -(-17*x**4 + 12*sqrt(2)*x**4 - 4*sqrt(2)*x**3 + 6*x**3 - 6*x - 4*sqrt(2)*x + 12*sqrt(2) + 17)/(-7*x**4 + 5*sqrt(2)*x**4 - 6*sqrt(2)*x**3 + 8*x**3 - 2*x**2 + 8*x + 6*sqrt(2)*x - 5*sqrt(2) - 7), -(12*sqrt(2)*x**4 + 17*x**4 - 6*x**3 - 4*sqrt(2)*x**3 - 4*sqrt(2)*x + 6*x - 17 + 12*sqrt(2))/(7*x**4 + 5*sqrt(2)*x**4 - 6*sqrt(2)*x**3 - 8*x**3 + 2*x**2 - 8*x + 6*sqrt(2)*x - 5*sqrt(2) + 7)],
[x - 1, x/(x - 1) + 1/(x - 1), (-7*x**3 + 5*sqrt(2)*x**3 - x**2 + sqrt(2)*x**2 - sqrt(2)*x - x - 5*sqrt(2) - 7)/(-3*x**3 + 2*sqrt(2)*x**3 - 2*sqrt(2)*x**2 + 3*x**2 + 2*sqrt(2)*x + 3*x - 3 - 2*sqrt(2)), (7*x**3 + 5*sqrt(2)*x**3 + x**2 + sqrt(2)*x**2 - sqrt(2)*x + x - 5*sqrt(2) + 7)/(2*sqrt(2)*x**3 + 3*x**3 - 3*x**2 - 2*sqrt(2)*x**2 - 3*x + 2*sqrt(2)*x - 2*sqrt(2) + 3)],
[ 0, 1, -(-3*x**2 + 2*sqrt(2)*x**2 + 2*x - 3 - 2*sqrt(2))/(-x**2 + sqrt(2)*x**2 - 2*sqrt(2)*x + 1 + sqrt(2)), -(2*sqrt(2)*x**2 + 3*x**2 - 2*x - 2*sqrt(2) + 3)/(x**2 + sqrt(2)*x**2 - 2*sqrt(2)*x - 1 + sqrt(2))],
[1 - x, 0, 1, 1]]''')).expand()
assert J == Matrix(S('''[
[0, 1, 0, 0],
[0, 0, 0, 0],
[0, 0, x - sqrt(2)*(x - 1) + 1, 0],
[0, 0, 0, x + sqrt(2)*(x - 1) + 1]]'''))
def test_issue_17247_expression_blowup_28():
M = Matrix(S('''[
[ -3/4, 45/32 - 37*I/16, 0, 0],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert M.singular_values() == S('''[
sqrt(14609315/131072 + sqrt(64789115132571/2147483648 - 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3) + 76627253330829751075/(35184372088832*sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))) - 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)))/2 + sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))/2),
sqrt(14609315/131072 - sqrt(64789115132571/2147483648 - 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3) + 76627253330829751075/(35184372088832*sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))) - 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)))/2 + sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))/2),
sqrt(14609315/131072 - sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))/2 + sqrt(64789115132571/2147483648 - 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3) - 76627253330829751075/(35184372088832*sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))) - 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)))/2),
sqrt(14609315/131072 - sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))/2 - sqrt(64789115132571/2147483648 - 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3) - 76627253330829751075/(35184372088832*sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))) - 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)))/2)]''')
def test_issue_16823():
# This still needs to be fixed if not using dotprodsimp.
M = Matrix(S('''[
[1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I,1/4-5/16*I,65/128+87/64*I,-9/32-1/16*I,183/256-97/128*I,3/64+13/64*I,-23/32-59/256*I,15/128-3/32*I,19/256+551/1024*I],
[21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I,85/256-33/16*I,805/128+2415/512*I,-219/128+115/256*I,6301/4096-6609/1024*I,119/128+143/128*I,-10879/2048+4343/4096*I,129/256-549/512*I,42533/16384+29103/8192*I],
[-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I,1/4-5/16*I,65/128+87/64*I,-9/32-1/16*I,183/256-97/128*I,3/64+13/64*I,-23/32-59/256*I],
[1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I,85/256-33/16*I,805/128+2415/512*I,-219/128+115/256*I,6301/4096-6609/1024*I,119/128+143/128*I,-10879/2048+4343/4096*I],
[-4*I,27/2+6*I,-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I,1/4-5/16*I,65/128+87/64*I,-9/32-1/16*I,183/256-97/128*I],
[1/4+5/2*I,-23/8-57/16*I,1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I,85/256-33/16*I,805/128+2415/512*I,-219/128+115/256*I,6301/4096-6609/1024*I],
[-4,9-5*I,-4*I,27/2+6*I,-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I,1/4-5/16*I,65/128+87/64*I],
[-2*I,119/8+29/4*I,1/4+5/2*I,-23/8-57/16*I,1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I,85/256-33/16*I,805/128+2415/512*I],
[0,-6,-4,9-5*I,-4*I,27/2+6*I,-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I],
[1,-9/4+3*I,-2*I,119/8+29/4*I,1/4+5/2*I,-23/8-57/16*I,1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I],
[0,-4*I,0,-6,-4,9-5*I,-4*I,27/2+6*I,-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I],
[0,1/4+1/2*I,1,-9/4+3*I,-2*I,119/8+29/4*I,1/4+5/2*I,-23/8-57/16*I,1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I]]'''))
with dotprodsimp(True):
assert M.rank() == 8
def test_issue_18531():
# solve_linear_system still needs fixing but the rref works.
M = Matrix([
[1, 1, 1, 1, 1, 0, 1, 0, 0],
[1 + sqrt(2), -1 + sqrt(2), 1 - sqrt(2), -sqrt(2) - 1, 1, 1, -1, 1, 1],
[-5 + 2*sqrt(2), -5 - 2*sqrt(2), -5 - 2*sqrt(2), -5 + 2*sqrt(2), -7, 2, -7, -2, 0],
[-3*sqrt(2) - 1, 1 - 3*sqrt(2), -1 + 3*sqrt(2), 1 + 3*sqrt(2), -7, -5, 7, -5, 3],
[7 - 4*sqrt(2), 4*sqrt(2) + 7, 4*sqrt(2) + 7, 7 - 4*sqrt(2), 7, -12, 7, 12, 0],
[-1 + 3*sqrt(2), 1 + 3*sqrt(2), -3*sqrt(2) - 1, 1 - 3*sqrt(2), 7, -5, -7, -5, 3],
[-3 + 2*sqrt(2), -3 - 2*sqrt(2), -3 - 2*sqrt(2), -3 + 2*sqrt(2), -1, 2, -1, -2, 0],
[1 - sqrt(2), -sqrt(2) - 1, 1 + sqrt(2), -1 + sqrt(2), -1, 1, 1, 1, 1]
])
with dotprodsimp(True):
assert M.rref() == (Matrix([
[1, 0, 0, 0, 0, 0, 0, 0, 1/2],
[0, 1, 0, 0, 0, 0, 0, 0, -1/2],
[0, 0, 1, 0, 0, 0, 0, 0, 1/2],
[0, 0, 0, 1, 0, 0, 0, 0, -1/2],
[0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, -1/2],
[0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, -1/2]]), (0, 1, 2, 3, 4, 5, 6, 7))
def test_creation():
raises(ValueError, lambda: Matrix(5, 5, range(20)))
raises(ValueError, lambda: Matrix(5, -1, []))
raises(IndexError, lambda: Matrix((1, 2))[2])
with raises(IndexError):
Matrix((1, 2))[3] = 5
assert Matrix() == Matrix([]) == Matrix([[]]) == Matrix(0, 0, [])
# anything used to be allowed in a matrix
with warns_deprecated_sympy():
assert Matrix([[[1], (2,)]]).tolist() == [[[1], (2,)]]
with warns_deprecated_sympy():
assert Matrix([[[1], (2,)]]).T.tolist() == [[[1]], [(2,)]]
M = Matrix([[0]])
with warns_deprecated_sympy():
M[0, 0] = S.EmptySet
a = Matrix([[x, 0], [0, 0]])
m = a
assert m.cols == m.rows
assert m.cols == 2
assert m[:] == [x, 0, 0, 0]
b = Matrix(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
assert Matrix(b) == b
c23 = Matrix(2, 3, range(1, 7))
c13 = Matrix(1, 3, range(7, 10))
c = Matrix([c23, c13])
assert c.cols == 3
assert c.rows == 3
assert c[:] == [1, 2, 3, 4, 5, 6, 7, 8, 9]
assert Matrix(eye(2)) == eye(2)
assert ImmutableMatrix(ImmutableMatrix(eye(2))) == ImmutableMatrix(eye(2))
assert ImmutableMatrix(c) == c.as_immutable()
assert Matrix(ImmutableMatrix(c)) == ImmutableMatrix(c).as_mutable()
assert c is not Matrix(c)
dat = [[ones(3,2), ones(3,3)*2], [ones(2,3)*3, ones(2,2)*4]]
M = Matrix(dat)
assert M == Matrix([
[1, 1, 2, 2, 2],
[1, 1, 2, 2, 2],
[1, 1, 2, 2, 2],
[3, 3, 3, 4, 4],
[3, 3, 3, 4, 4]])
assert M.tolist() != dat
# keep block form if evaluate=False
assert Matrix(dat, evaluate=False).tolist() == dat
A = MatrixSymbol("A", 2, 2)
dat = [ones(2), A]
assert Matrix(dat) == Matrix([
[ 1, 1],
[ 1, 1],
[A[0, 0], A[0, 1]],
[A[1, 0], A[1, 1]]])
with warns_deprecated_sympy():
assert Matrix(dat, evaluate=False).tolist() == [[i] for i in dat]
# 0-dim tolerance
assert Matrix([ones(2), ones(0)]) == Matrix([ones(2)])
raises(ValueError, lambda: Matrix([ones(2), ones(0, 3)]))
raises(ValueError, lambda: Matrix([ones(2), ones(3, 0)]))
# mix of Matrix and iterable
M = Matrix([[1, 2], [3, 4]])
M2 = Matrix([M, (5, 6)])
assert M2 == Matrix([[1, 2], [3, 4], [5, 6]])
def test_irregular_block():
assert Matrix.irregular(3, ones(2,1), ones(3,3)*2, ones(2,2)*3,
ones(1,1)*4, ones(2,2)*5, ones(1,2)*6, ones(1,2)*7) == Matrix([
[1, 2, 2, 2, 3, 3],
[1, 2, 2, 2, 3, 3],
[4, 2, 2, 2, 5, 5],
[6, 6, 7, 7, 5, 5]])
def test_tolist():
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 test_as_mutable():
assert zeros(0, 3).as_mutable() == zeros(0, 3)
assert zeros(0, 3).as_immutable() == ImmutableMatrix(zeros(0, 3))
assert zeros(3, 0).as_immutable() == ImmutableMatrix(zeros(3, 0))
def test_slicing():
m0 = eye(4)
assert m0[:3, :3] == eye(3)
assert m0[2:4, 0:2] == zeros(2)
m1 = Matrix(3, 3, lambda i, j: i + j)
assert m1[0, :] == Matrix(1, 3, (0, 1, 2))
assert m1[1:3, 1] == Matrix(2, 1, (2, 3))
m2 = Matrix([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]])
assert m2[:, -1] == Matrix(4, 1, [3, 7, 11, 15])
assert m2[-2:, :] == Matrix([[8, 9, 10, 11], [12, 13, 14, 15]])
def test_submatrix_assignment():
m = zeros(4)
m[2:4, 2:4] = eye(2)
assert m == Matrix(((0, 0, 0, 0),
(0, 0, 0, 0),
(0, 0, 1, 0),
(0, 0, 0, 1)))
m[:2, :2] = eye(2)
assert m == eye(4)
m[:, 0] = Matrix(4, 1, (1, 2, 3, 4))
assert m == Matrix(((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 == Matrix(((1, 2, 3, 4),
(5, 6, 7, 8),
(9, 10, 11, 12),
(13, 14, 15, 16)))
m[:2, 0] = [0, 0]
assert m == Matrix(((0, 2, 3, 4),
(0, 6, 7, 8),
(9, 10, 11, 12),
(13, 14, 15, 16)))
def test_extract():
m = Matrix(4, 3, lambda i, j: i*3 + j)
assert m.extract([0, 1, 3], [0, 1]) == Matrix(3, 2, [0, 1, 3, 4, 9, 10])
assert m.extract([0, 3], [0, 0, 2]) == Matrix(2, 3, [0, 0, 2, 9, 9, 11])
assert m.extract(range(4), range(3)) == m
raises(IndexError, lambda: m.extract([4], [0]))
raises(IndexError, lambda: m.extract([0], [3]))
def test_reshape():
m0 = eye(3)
assert m0.reshape(1, 9) == Matrix(1, 9, (1, 0, 0, 0, 1, 0, 0, 0, 1))
m1 = Matrix(3, 4, lambda i, j: i + j)
assert m1.reshape(
4, 3) == Matrix(((0, 1, 2), (3, 1, 2), (3, 4, 2), (3, 4, 5)))
assert m1.reshape(2, 6) == Matrix(((0, 1, 2, 3, 1, 2), (3, 4, 2, 3, 4, 5)))
def test_applyfunc():
m0 = eye(3)
assert m0.applyfunc(lambda x: 2*x) == eye(3)*2
assert m0.applyfunc(lambda x: 0) == zeros(3)
def test_expand():
m0 = Matrix([[x*(x + y), 2], [((x + y)*y)*x, x*(y + x*(x + y))]])
# Test if expand() returns a matrix
m1 = m0.expand()
assert m1 == Matrix(
[[x*y + x**2, 2], [x*y**2 + y*x**2, x*y + y*x**2 + x**3]])
a = Symbol('a', real=True)
assert Matrix([exp(I*a)]).expand(complex=True) == \
Matrix([cos(a) + I*sin(a)])
assert Matrix([[0, 1, 2], [0, 0, -1], [0, 0, 0]]).exp() == Matrix([
[1, 1, Rational(3, 2)],
[0, 1, -1],
[0, 0, 1]]
)
def test_refine():
m0 = Matrix([[Abs(x)**2, sqrt(x**2)],
[sqrt(x**2)*Abs(y)**2, sqrt(y**2)*Abs(x)**2]])
m1 = m0.refine(Q.real(x) & Q.real(y))
assert m1 == Matrix([[x**2, Abs(x)], [y**2*Abs(x), x**2*Abs(y)]])
m1 = m0.refine(Q.positive(x) & Q.positive(y))
assert m1 == Matrix([[x**2, x], [x*y**2, x**2*y]])
m1 = m0.refine(Q.negative(x) & Q.negative(y))
assert m1 == Matrix([[x**2, -x], [-x*y**2, -x**2*y]])
def test_random():
M = randMatrix(3, 3)
M = randMatrix(3, 3, seed=3)
assert M == randMatrix(3, 3, seed=3)
M = randMatrix(3, 4, 0, 150)
M = randMatrix(3, seed=4, symmetric=True)
assert M == randMatrix(3, seed=4, symmetric=True)
S = M.copy()
S.simplify()
assert S == M # doesn't fail when elements are Numbers, not int
rng = random.Random(4)
assert M == randMatrix(3, symmetric=True, prng=rng)
# Ensure symmetry
for size in (10, 11): # Test odd and even
for percent in (100, 70, 30):
M = randMatrix(size, symmetric=True, percent=percent, prng=rng)
assert M == M.T
M = randMatrix(10, min=1, percent=70)
zero_count = 0
for i in range(M.shape[0]):
for j in range(M.shape[1]):
if M[i, j] == 0:
zero_count += 1
assert zero_count == 30
def test_inverse():
A = eye(4)
assert A.inv() == eye(4)
assert A.inv(method="LU") == eye(4)
assert A.inv(method="ADJ") == eye(4)
assert A.inv(method="CH") == eye(4)
assert A.inv(method="LDL") == eye(4)
assert A.inv(method="QR") == eye(4)
A = Matrix([[2, 3, 5],
[3, 6, 2],
[8, 3, 6]])
Ainv = A.inv()
assert A*Ainv == eye(3)
assert A.inv(method="LU") == Ainv
assert A.inv(method="ADJ") == Ainv
assert A.inv(method="CH") == Ainv
assert A.inv(method="LDL") == Ainv
assert A.inv(method="QR") == Ainv
AA = Matrix([[0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0],
[1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0],
[1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1],
[1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0],
[1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1],
[0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0],
[1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1],
[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0],
[0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0],
[1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0],
[0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1],
[1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0],
[0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0],
[1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1],
[0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1],
[1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1],
[0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1],
[0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 1],
[0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0],
[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0]])
assert AA.inv(method="BLOCK") * AA == eye(AA.shape[0])
# test that immutability is not a problem
cls = ImmutableMatrix
m = cls([[48, 49, 31],
[ 9, 71, 94],
[59, 28, 65]])
assert all(type(m.inv(s)) is cls for s in 'GE ADJ LU CH LDL QR'.split())
cls = ImmutableSparseMatrix
m = cls([[48, 49, 31],
[ 9, 71, 94],
[59, 28, 65]])
assert all(type(m.inv(s)) is cls for s in 'GE ADJ LU CH LDL QR'.split())
def test_matrix_inverse_mod():
A = Matrix(2, 1, [1, 0])
raises(NonSquareMatrixError, lambda: A.inv_mod(2))
A = Matrix(2, 2, [1, 0, 0, 0])
raises(ValueError, lambda: A.inv_mod(2))
A = Matrix(2, 2, [1, 2, 3, 4])
Ai = Matrix(2, 2, [1, 1, 0, 1])
assert A.inv_mod(3) == Ai
A = Matrix(2, 2, [1, 0, 0, 1])
assert A.inv_mod(2) == A
A = Matrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9])
raises(ValueError, lambda: A.inv_mod(5))
A = Matrix(3, 3, [5, 1, 3, 2, 6, 0, 2, 1, 1])
Ai = Matrix(3, 3, [6, 8, 0, 1, 5, 6, 5, 6, 4])
assert A.inv_mod(9) == Ai
A = Matrix(3, 3, [1, 6, -3, 4, 1, -5, 3, -5, 5])
Ai = Matrix(3, 3, [4, 3, 3, 1, 2, 5, 1, 5, 1])
assert A.inv_mod(6) == Ai
A = Matrix(3, 3, [1, 6, 1, 4, 1, 5, 3, 2, 5])
Ai = Matrix(3, 3, [6, 0, 3, 6, 6, 4, 1, 6, 1])
assert A.inv_mod(7) == Ai
def test_jacobian_hessian():
L = Matrix(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 = Matrix(1, 2, [x, x**2*y**3])
assert L.jacobian(syms) == Matrix([[1, 0], [2*x*y**3, x**2*3*y**2]])
f = x**2*y
syms = [x, y]
assert hessian(f, syms) == Matrix([[2*y, 2*x], [2*x, 0]])
f = x**2*y**3
assert hessian(f, syms) == \
Matrix([[2*y**3, 6*x*y**2], [6*x*y**2, 6*x**2*y]])
f = z + x*y**2
g = x**2 + 2*y**3
ans = Matrix([[0, 2*y],
[2*y, 2*x]])
assert ans == hessian(f, Matrix([x, y]))
assert ans == hessian(f, Matrix([x, y]).T)
assert hessian(f, (y, x), [g]) == Matrix([
[ 0, 6*y**2, 2*x],
[6*y**2, 2*x, 2*y],
[ 2*x, 2*y, 0]])
def test_wronskian():
assert wronskian([cos(x), sin(x)], x) == cos(x)**2 + sin(x)**2
assert wronskian([exp(x), exp(2*x)], x) == exp(3*x)
assert wronskian([exp(x), x], x) == exp(x) - x*exp(x)
assert wronskian([1, x, x**2], x) == 2
w1 = -6*exp(x)*sin(x)*x + 6*cos(x)*exp(x)*x**2 - 6*exp(x)*cos(x)*x - \
exp(x)*cos(x)*x**3 + exp(x)*sin(x)*x**3
assert wronskian([exp(x), cos(x), x**3], x).expand() == w1
assert wronskian([exp(x), cos(x), x**3], x, method='berkowitz').expand() \
== w1
w2 = -x**3*cos(x)**2 - x**3*sin(x)**2 - 6*x*cos(x)**2 - 6*x*sin(x)**2
assert wronskian([sin(x), cos(x), x**3], x).expand() == w2
assert wronskian([sin(x), cos(x), x**3], x, method='berkowitz').expand() \
== w2
assert wronskian([], x) == 1
def test_subs():
assert Matrix([[1, x], [x, 4]]).subs(x, 5) == Matrix([[1, 5], [5, 4]])
assert Matrix([[x, 2], [x + y, 4]]).subs([[x, -1], [y, -2]]) == \
Matrix([[-1, 2], [-3, 4]])
assert Matrix([[x, 2], [x + y, 4]]).subs([(x, -1), (y, -2)]) == \
Matrix([[-1, 2], [-3, 4]])
assert Matrix([[x, 2], [x + y, 4]]).subs({x: -1, y: -2}) == \
Matrix([[-1, 2], [-3, 4]])
assert Matrix([x*y]).subs({x: y - 1, y: x - 1}, simultaneous=True) == \
Matrix([(x - 1)*(y - 1)])
for cls in classes:
assert Matrix([[2, 0], [0, 2]]) == cls.eye(2).subs(1, 2)
def test_xreplace():
assert Matrix([[1, x], [x, 4]]).xreplace({x: 5}) == \
Matrix([[1, 5], [5, 4]])
assert Matrix([[x, 2], [x + y, 4]]).xreplace({x: -1, y: -2}) == \
Matrix([[-1, 2], [-3, 4]])
for cls in classes:
assert Matrix([[2, 0], [0, 2]]) == cls.eye(2).xreplace({1: 2})
def test_simplify():
n = Symbol('n')
f = Function('f')
M = Matrix([[ 1/x + 1/y, (x + x*y) / x ],
[ (f(x) + y*f(x))/f(x), 2 * (1/n - cos(n * pi)/n) / pi ]])
M.simplify()
assert M == Matrix([[ (x + y)/(x * y), 1 + y ],
[ 1 + y, 2*((1 - 1*cos(pi*n))/(pi*n)) ]])
eq = (1 + x)**2
M = Matrix([[eq]])
M.simplify()
assert M == Matrix([[eq]])
M.simplify(ratio=oo) == M
assert M == Matrix([[eq.simplify(ratio=oo)]])
def test_transpose():
M = Matrix([[1, 2, 3, 4, 5, 6, 7, 8, 9, 0],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]])
assert M.T == Matrix( [ [1, 1],
[2, 2],
[3, 3],
[4, 4],
[5, 5],
[6, 6],
[7, 7],
[8, 8],
[9, 9],
[0, 0] ])
assert M.T.T == M
assert M.T == M.transpose()
def test_conjugate():
M = Matrix([[0, I, 5],
[1, 2, 0]])
assert M.T == Matrix([[0, 1],
[I, 2],
[5, 0]])
assert M.C == Matrix([[0, -I, 5],
[1, 2, 0]])
assert M.C == M.conjugate()
assert M.H == M.T.C
assert M.H == Matrix([[ 0, 1],
[-I, 2],
[ 5, 0]])
def test_conj_dirac():
raises(AttributeError, lambda: eye(3).D)
M = Matrix([[1, I, I, I],
[0, 1, I, I],
[0, 0, 1, I],
[0, 0, 0, 1]])
assert M.D == Matrix([[ 1, 0, 0, 0],
[-I, 1, 0, 0],
[-I, -I, -1, 0],
[-I, -I, I, -1]])
def test_trace():
M = Matrix([[1, 0, 0],
[0, 5, 0],
[0, 0, 8]])
assert M.trace() == 14
def test_shape():
M = Matrix([[x, 0, 0],
[0, y, 0]])
assert M.shape == (2, 3)
def test_col_row_op():
M = Matrix([[x, 0, 0],
[0, y, 0]])
M.row_op(1, lambda r, j: r + j + 1)
assert M == Matrix([[x, 0, 0],
[1, y + 2, 3]])
M.col_op(0, lambda c, j: c + y**j)
assert M == Matrix([[x + 1, 0, 0],
[1 + y, y + 2, 3]])
# neither row nor slice give copies that allow the original matrix to
# be changed
assert M.row(0) == Matrix([[x + 1, 0, 0]])
r1 = M.row(0)
r1[0] = 42
assert M[0, 0] == x + 1
r1 = M[0, :-1] # also testing negative slice
r1[0] = 42
assert M[0, 0] == x + 1
c1 = M.col(0)
assert c1 == Matrix([x + 1, 1 + y])
c1[0] = 0
assert M[0, 0] == x + 1
c1 = M[:, 0]
c1[0] = 42
assert M[0, 0] == x + 1
def test_zip_row_op():
for cls in classes[:2]: # XXX: immutable matrices don't support row ops
M = cls.eye(3)
M.zip_row_op(1, 0, lambda v, u: v + 2*u)
assert M == cls([[1, 0, 0],
[2, 1, 0],
[0, 0, 1]])
M = cls.eye(3)*2
M[0, 1] = -1
M.zip_row_op(1, 0, lambda v, u: v + 2*u); M
assert M == cls([[2, -1, 0],
[4, 0, 0],
[0, 0, 2]])
def test_issue_3950():
m = Matrix([1, 2, 3])
a = Matrix([1, 2, 3])
b = Matrix([2, 2, 3])
assert not (m in [])
assert not (m in [1])
assert m != 1
assert m == a
assert m != b
def test_issue_3981():
class Index1:
def __index__(self):
return 1
class Index2:
def __index__(self):
return 2
index1 = Index1()
index2 = Index2()
m = Matrix([1, 2, 3])
assert m[index2] == 3
m[index2] = 5
assert m[2] == 5
m = Matrix([[1, 2, 3], [4, 5, 6]])
assert m[index1, index2] == 6
assert m[1, index2] == 6
assert m[index1, 2] == 6
m[index1, index2] = 4
assert m[1, 2] == 4
m[1, index2] = 6
assert m[1, 2] == 6
m[index1, 2] = 8
assert m[1, 2] == 8
def test_evalf():
a = Matrix([sqrt(5), 6])
assert all(a.evalf()[i] == a[i].evalf() for i in range(2))
assert all(a.evalf(2)[i] == a[i].evalf(2) for i in range(2))
assert all(a.n(2)[i] == a[i].n(2) for i in range(2))
def test_is_symbolic():
a = Matrix([[x, x], [x, x]])
assert a.is_symbolic() is True
a = Matrix([[1, 2, 3, 4], [5, 6, 7, 8]])
assert a.is_symbolic() is False
a = Matrix([[1, 2, 3, 4], [5, 6, x, 8]])
assert a.is_symbolic() is True
a = Matrix([[1, x, 3]])
assert a.is_symbolic() is True
a = Matrix([[1, 2, 3]])
assert a.is_symbolic() is False
a = Matrix([[1], [x], [3]])
assert a.is_symbolic() is True
a = Matrix([[1], [2], [3]])
assert a.is_symbolic() is False
def test_is_upper():
a = Matrix([[1, 2, 3]])
assert a.is_upper is True
a = Matrix([[1], [2], [3]])
assert a.is_upper is False
a = zeros(4, 2)
assert a.is_upper is True
def test_is_lower():
a = Matrix([[1, 2, 3]])
assert a.is_lower is False
a = Matrix([[1], [2], [3]])
assert a.is_lower is True
def test_is_nilpotent():
a = Matrix(4, 4, [0, 2, 1, 6, 0, 0, 1, 2, 0, 0, 0, 3, 0, 0, 0, 0])
assert a.is_nilpotent()
a = Matrix([[1, 0], [0, 1]])
assert not a.is_nilpotent()
a = Matrix([])
assert a.is_nilpotent()
def test_zeros_ones_fill():
n, m = 3, 5
a = zeros(n, m)
a.fill( 5 )
b = 5 * ones(n, m)
assert a == b
assert a.rows == b.rows == 3
assert a.cols == b.cols == 5
assert a.shape == b.shape == (3, 5)
assert zeros(2) == zeros(2, 2)
assert ones(2) == ones(2, 2)
assert zeros(2, 3) == Matrix(2, 3, [0]*6)
assert ones(2, 3) == Matrix(2, 3, [1]*6)
a.fill(0)
assert a == zeros(n, m)
def test_empty_zeros():
a = zeros(0)
assert a == Matrix()
a = zeros(0, 2)
assert a.rows == 0
assert a.cols == 2
a = zeros(2, 0)
assert a.rows == 2
assert a.cols == 0
def test_issue_3749():
a = Matrix([[x**2, x*y], [x*sin(y), x*cos(y)]])
assert a.diff(x) == Matrix([[2*x, y], [sin(y), cos(y)]])
assert Matrix([
[x, -x, x**2],
[exp(x), 1/x - exp(-x), x + 1/x]]).limit(x, oo) == \
Matrix([[oo, -oo, oo], [oo, 0, oo]])
assert Matrix([
[(exp(x) - 1)/x, 2*x + y*x, x**x ],
[1/x, abs(x), abs(sin(x + 1))]]).limit(x, 0) == \
Matrix([[1, 0, 1], [oo, 0, sin(1)]])
assert a.integrate(x) == Matrix([
[Rational(1, 3)*x**3, y*x**2/2],
[x**2*sin(y)/2, x**2*cos(y)/2]])
def test_inv_iszerofunc():
A = eye(4)
A.col_swap(0, 1)
for method in "GE", "LU":
assert A.inv(method=method, iszerofunc=lambda x: x == 0) == \
A.inv(method="ADJ")
def test_jacobian_metrics():
rho, phi = symbols("rho,phi")
X = Matrix([rho*cos(phi), rho*sin(phi)])
Y = Matrix([rho, phi])
J = X.jacobian(Y)
assert J == X.jacobian(Y.T)
assert J == (X.T).jacobian(Y)
assert J == (X.T).jacobian(Y.T)
g = J.T*eye(J.shape[0])*J
g = g.applyfunc(trigsimp)
assert g == Matrix([[1, 0], [0, rho**2]])
def test_jacobian2():
rho, phi = symbols("rho,phi")
X = Matrix([rho*cos(phi), rho*sin(phi), rho**2])
Y = Matrix([rho, phi])
J = Matrix([
[cos(phi), -rho*sin(phi)],
[sin(phi), rho*cos(phi)],
[ 2*rho, 0],
])
assert X.jacobian(Y) == J
def test_issue_4564():
X = Matrix([exp(x + y + z), exp(x + y + z), exp(x + y + z)])
Y = Matrix([x, y, z])
for i in range(1, 3):
for j in range(1, 3):
X_slice = X[:i, :]
Y_slice = Y[:j, :]
J = X_slice.jacobian(Y_slice)
assert J.rows == i
assert J.cols == j
for k in range(j):
assert J[:, k] == X_slice
def test_nonvectorJacobian():
X = Matrix([[exp(x + y + z), exp(x + y + z)],
[exp(x + y + z), exp(x + y + z)]])
raises(TypeError, lambda: X.jacobian(Matrix([x, y, z])))
X = X[0, :]
Y = Matrix([[x, y], [x, z]])
raises(TypeError, lambda: X.jacobian(Y))
raises(TypeError, lambda: X.jacobian(Matrix([ [x, y], [x, z] ])))
def test_vec():
m = Matrix([[1, 3], [2, 4]])
m_vec = m.vec()
assert m_vec.cols == 1
for i in range(4):
assert m_vec[i] == i + 1
def test_vech():
m = Matrix([[1, 2], [2, 3]])
m_vech = m.vech()
assert m_vech.cols == 1
for i in range(3):
assert m_vech[i] == i + 1
m_vech = m.vech(diagonal=False)
assert m_vech[0] == 2
m = Matrix([[1, x*(x + y)], [y*x + x**2, 1]])
m_vech = m.vech(diagonal=False)
assert m_vech[0] == y*x + x**2
m = Matrix([[1, x*(x + y)], [y*x, 1]])
m_vech = m.vech(diagonal=False, check_symmetry=False)
assert m_vech[0] == y*x
raises(ShapeError, lambda: Matrix([[1, 3]]).vech())
raises(ValueError, lambda: Matrix([[1, 3], [2, 4]]).vech())
raises(ShapeError, lambda: Matrix([[1, 3]]).vech())
raises(ValueError, lambda: Matrix([[1, 3], [2, 4]]).vech())
def test_diag():
# mostly tested in testcommonmatrix.py
assert diag([1, 2, 3]) == Matrix([1, 2, 3])
m = [1, 2, [3]]
raises(ValueError, lambda: diag(m))
assert diag(m, strict=False) == Matrix([1, 2, 3])
def test_get_diag_blocks1():
a = Matrix([[1, 2], [2, 3]])
b = Matrix([[3, x], [y, 3]])
c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]])
assert a.get_diag_blocks() == [a]
assert b.get_diag_blocks() == [b]
assert c.get_diag_blocks() == [c]
def test_get_diag_blocks2():
a = Matrix([[1, 2], [2, 3]])
b = Matrix([[3, x], [y, 3]])
c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]])
assert diag(a, b, b).get_diag_blocks() == [a, b, b]
assert diag(a, b, c).get_diag_blocks() == [a, b, c]
assert diag(a, c, b).get_diag_blocks() == [a, c, b]
assert diag(c, c, b).get_diag_blocks() == [c, c, b]
def test_inv_block():
a = Matrix([[1, 2], [2, 3]])
b = Matrix([[3, x], [y, 3]])
c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]])
A = diag(a, b, b)
assert A.inv(try_block_diag=True) == diag(a.inv(), b.inv(), b.inv())
A = diag(a, b, c)
assert A.inv(try_block_diag=True) == diag(a.inv(), b.inv(), c.inv())
A = diag(a, c, b)
assert A.inv(try_block_diag=True) == diag(a.inv(), c.inv(), b.inv())
A = diag(a, a, b, a, c, a)
assert A.inv(try_block_diag=True) == diag(
a.inv(), a.inv(), b.inv(), a.inv(), c.inv(), a.inv())
assert A.inv(try_block_diag=True, method="ADJ") == diag(
a.inv(method="ADJ"), a.inv(method="ADJ"), b.inv(method="ADJ"),
a.inv(method="ADJ"), c.inv(method="ADJ"), a.inv(method="ADJ"))
def test_creation_args():
"""
Check that matrix dimensions can be specified using any reasonable type
(see issue 4614).
"""
raises(ValueError, lambda: zeros(3, -1))
raises(TypeError, lambda: zeros(1, 2, 3, 4))
assert zeros(int(3)) == zeros(3)
assert zeros(Integer(3)) == zeros(3)
raises(ValueError, lambda: zeros(3.))
assert eye(int(3)) == eye(3)
assert eye(Integer(3)) == eye(3)
raises(ValueError, lambda: eye(3.))
assert ones(int(3), Integer(4)) == ones(3, 4)
raises(TypeError, lambda: Matrix(5))
raises(TypeError, lambda: Matrix(1, 2))
raises(ValueError, lambda: Matrix([1, [2]]))
def test_diagonal_symmetrical():
m = Matrix(2, 2, [0, 1, 1, 0])
assert not m.is_diagonal()
assert m.is_symmetric()
assert m.is_symmetric(simplify=False)
m = Matrix(2, 2, [1, 0, 0, 1])
assert m.is_diagonal()
m = diag(1, 2, 3)
assert m.is_diagonal()
assert m.is_symmetric()
m = Matrix(3, 3, [1, 0, 0, 0, 2, 0, 0, 0, 3])
assert m == diag(1, 2, 3)
m = Matrix(2, 3, zeros(2, 3))
assert not m.is_symmetric()
assert m.is_diagonal()
m = Matrix(((5, 0), (0, 6), (0, 0)))
assert m.is_diagonal()
m = Matrix(((5, 0, 0), (0, 6, 0)))
assert m.is_diagonal()
m = Matrix(3, 3, [1, x**2 + 2*x + 1, y, (x + 1)**2, 2, 0, y, 0, 3])
assert m.is_symmetric()
assert not m.is_symmetric(simplify=False)
assert m.expand().is_symmetric(simplify=False)
def test_diagonalization():
m = Matrix([[1, 2+I], [2-I, 3]])
assert m.is_diagonalizable()
m = Matrix(3, 2, [-3, 1, -3, 20, 3, 10])
assert not m.is_diagonalizable()
assert not m.is_symmetric()
raises(NonSquareMatrixError, lambda: 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
for i in P:
assert i.as_numer_denom()[1] == 1
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 == Matrix([[0, 1], [1, 0]])
# diagonalizable, complex only
m = Matrix(2, 2, [0, 1, -1, 0])
assert not m.is_diagonalizable(True)
raises(MatrixError, lambda: m.diagonalize(True))
assert m.is_diagonalizable()
(P, D) = m.diagonalize()
assert P.inv() * m * P == D
# not diagonalizable
m = Matrix(2, 2, [0, 1, 0, 0])
assert not m.is_diagonalizable()
raises(MatrixError, lambda: m.diagonalize())
m = Matrix(3, 3, [-3, 1, -3, 20, 3, 10, 2, -2, 4])
assert not m.is_diagonalizable()
raises(MatrixError, lambda: 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 test_issue_15887():
# Mutable matrix should not use cache
a = MutableDenseMatrix([[0, 1], [1, 0]])
assert a.is_diagonalizable() is True
a[1, 0] = 0
assert a.is_diagonalizable() is False
a = MutableDenseMatrix([[0, 1], [1, 0]])
a.diagonalize()
a[1, 0] = 0
raises(MatrixError, lambda: a.diagonalize())
# Test deprecated cache and kwargs
with warns_deprecated_sympy():
a.is_diagonalizable(clear_cache=True)
with warns_deprecated_sympy():
a.is_diagonalizable(clear_subproducts=True)
def test_jordan_form():
m = Matrix(3, 2, [-3, 1, -3, 20, 3, 10])
raises(NonSquareMatrixError, lambda: 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])
# The blocks are ordered according to the value of their eigenvalues,
# in order to make the matrix compatible with .diagonalize()
Jmust = Matrix(3, 3, [2, 1, 0, 0, 2, 0, 0, 0, 2])
P, J = m.jordan_form()
assert Jmust == J
# 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])
# same here see 1456ff
Jmust = Matrix(3, 3, [-1, 1, 0, 0, -1, 0, 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, [0, 1, 0, 0, 0, 0, 0, 0, 1])
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])
# same here see 1456ff
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
# checking for maximum precision to remain unchanged
m = Matrix([[Float('1.0', precision=110), Float('2.0', precision=110)],
[Float('3.14159265358979323846264338327', precision=110), Float('4.0', precision=110)]])
P, J = m.jordan_form()
for term in J.values():
if isinstance(term, Float):
assert term._prec == 110
def test_jordan_form_complex_issue_9274():
A = Matrix([[ 2, 4, 1, 0],
[-4, 2, 0, 1],
[ 0, 0, 2, 4],
[ 0, 0, -4, 2]])
p = 2 - 4*I;
q = 2 + 4*I;
Jmust1 = Matrix([[p, 1, 0, 0],
[0, p, 0, 0],
[0, 0, q, 1],
[0, 0, 0, q]])
Jmust2 = Matrix([[q, 1, 0, 0],
[0, q, 0, 0],
[0, 0, p, 1],
[0, 0, 0, p]])
P, J = A.jordan_form()
assert J == Jmust1 or J == Jmust2
assert simplify(P*J*P.inv()) == A
def test_issue_10220():
# two non-orthogonal Jordan blocks with eigenvalue 1
M = Matrix([[1, 0, 0, 1],
[0, 1, 1, 0],
[0, 0, 1, 1],
[0, 0, 0, 1]])
P, J = M.jordan_form()
assert P == Matrix([[0, 1, 0, 1],
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0]])
assert J == Matrix([
[1, 1, 0, 0],
[0, 1, 1, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]])
def test_jordan_form_issue_15858():
A = Matrix([
[1, 1, 1, 0],
[-2, -1, 0, -1],
[0, 0, -1, -1],
[0, 0, 2, 1]])
(P, J) = A.jordan_form()
assert P.expand() == Matrix([
[ -I, -I/2, I, I/2],
[-1 + I, 0, -1 - I, 0],
[ 0, -S(1)/2 - I/2, 0, -S(1)/2 + I/2],
[ 0, 1, 0, 1]])
assert J == Matrix([
[-I, 1, 0, 0],
[0, -I, 0, 0],
[0, 0, I, 1],
[0, 0, 0, I]])
def test_Matrix_berkowitz_charpoly():
UA, K_i, K_w = symbols('UA K_i K_w')
A = Matrix([[-K_i - UA + K_i**2/(K_i + K_w), K_i*K_w/(K_i + K_w)],
[ K_i*K_w/(K_i + K_w), -K_w + K_w**2/(K_i + K_w)]])
charpoly = A.charpoly(x)
assert charpoly == \
Poly(x**2 + (K_i*UA + K_w*UA + 2*K_i*K_w)/(K_i + K_w)*x +
K_i*K_w*UA/(K_i + K_w), x, domain='ZZ(K_i,K_w,UA)')
assert type(charpoly) is PurePoly
A = Matrix([[1, 3], [2, 0]])
assert A.charpoly() == A.charpoly(x) == PurePoly(x**2 - x - 6)
A = Matrix([[1, 2], [x, 0]])
p = A.charpoly(x)
assert p.gen != x
assert p.as_expr().subs(p.gen, x) == x**2 - 3*x
def test_exp_jordan_block():
l = Symbol('lamda')
m = Matrix.jordan_block(1, l)
assert m._eval_matrix_exp_jblock() == Matrix([[exp(l)]])
m = Matrix.jordan_block(3, l)
assert m._eval_matrix_exp_jblock() == \
Matrix([
[exp(l), exp(l), exp(l)/2],
[0, exp(l), exp(l)],
[0, 0, exp(l)]])
def test_exp():
m = Matrix([[3, 4], [0, -2]])
m_exp = Matrix([[exp(3), -4*exp(-2)/5 + 4*exp(3)/5], [0, exp(-2)]])
assert m.exp() == m_exp
assert exp(m) == m_exp
m = Matrix([[1, 0], [0, 1]])
assert m.exp() == Matrix([[E, 0], [0, E]])
assert exp(m) == Matrix([[E, 0], [0, E]])
m = Matrix([[1, -1], [1, 1]])
assert m.exp() == Matrix([[E*cos(1), -E*sin(1)], [E*sin(1), E*cos(1)]])
def test_log():
l = Symbol('lamda')
m = Matrix.jordan_block(1, l)
assert m._eval_matrix_log_jblock() == Matrix([[log(l)]])
m = Matrix.jordan_block(4, l)
assert m._eval_matrix_log_jblock() == \
Matrix(
[
[log(l), 1/l, -1/(2*l**2), 1/(3*l**3)],
[0, log(l), 1/l, -1/(2*l**2)],
[0, 0, log(l), 1/l],
[0, 0, 0, log(l)]
]
)
m = Matrix(
[[0, 0, 1],
[0, 0, 0],
[-1, 0, 0]]
)
raises(MatrixError, lambda: m.log())
def test_has():
A = Matrix(((x, y), (2, 3)))
assert A.has(x)
assert not A.has(z)
assert A.has(Symbol)
A = A.subs(x, 2)
assert not A.has(x)
def test_find_reasonable_pivot_naive_finds_guaranteed_nonzero1():
# Test if matrices._find_reasonable_pivot_naive()
# finds a guaranteed non-zero pivot when the
# some of the candidate pivots are symbolic expressions.
# Keyword argument: simpfunc=None indicates that no simplifications
# should be performed during the search.
x = Symbol('x')
column = Matrix(3, 1, [x, cos(x)**2 + sin(x)**2, S.Half])
pivot_offset, pivot_val, pivot_assumed_nonzero, simplified =\
_find_reasonable_pivot_naive(column)
assert pivot_val == S.Half
def test_find_reasonable_pivot_naive_finds_guaranteed_nonzero2():
# Test if matrices._find_reasonable_pivot_naive()
# finds a guaranteed non-zero pivot when the
# some of the candidate pivots are symbolic expressions.
# Keyword argument: simpfunc=_simplify indicates that the search
# should attempt to simplify candidate pivots.
x = Symbol('x')
column = Matrix(3, 1,
[x,
cos(x)**2+sin(x)**2+x**2,
cos(x)**2+sin(x)**2])
pivot_offset, pivot_val, pivot_assumed_nonzero, simplified =\
_find_reasonable_pivot_naive(column, simpfunc=_simplify)
assert pivot_val == 1
def test_find_reasonable_pivot_naive_simplifies():
# Test if matrices._find_reasonable_pivot_naive()
# simplifies candidate pivots, and reports
# their offsets correctly.
x = Symbol('x')
column = Matrix(3, 1,
[x,
cos(x)**2+sin(x)**2+x,
cos(x)**2+sin(x)**2])
pivot_offset, pivot_val, pivot_assumed_nonzero, simplified =\
_find_reasonable_pivot_naive(column, simpfunc=_simplify)
assert len(simplified) == 2
assert simplified[0][0] == 1
assert simplified[0][1] == 1+x
assert simplified[1][0] == 2
assert simplified[1][1] == 1
def test_errors():
raises(ValueError, lambda: Matrix([[1, 2], [1]]))
raises(IndexError, lambda: Matrix([[1, 2]])[1.2, 5])
raises(IndexError, lambda: Matrix([[1, 2]])[1, 5.2])
raises(ValueError, lambda: randMatrix(3, c=4, symmetric=True))
raises(ValueError, lambda: Matrix([1, 2]).reshape(4, 6))
raises(ShapeError,
lambda: Matrix([[1, 2], [3, 4]]).copyin_matrix([1, 0], Matrix([1, 2])))
raises(TypeError, lambda: Matrix([[1, 2], [3, 4]]).copyin_list([0,
1], set()))
raises(NonSquareMatrixError, lambda: Matrix([[1, 2, 3], [2, 3, 0]]).inv())
raises(ShapeError,
lambda: Matrix(1, 2, [1, 2]).row_join(Matrix([[1, 2], [3, 4]])))
raises(
ShapeError, lambda: Matrix([1, 2]).col_join(Matrix([[1, 2], [3, 4]])))
raises(ShapeError, lambda: Matrix([1]).row_insert(1, Matrix([[1,
2], [3, 4]])))
raises(ShapeError, lambda: Matrix([1]).col_insert(1, Matrix([[1,
2], [3, 4]])))
raises(NonSquareMatrixError, lambda: Matrix([1, 2]).trace())
raises(TypeError, lambda: Matrix([1]).applyfunc(1))
raises(ValueError, lambda: Matrix([[1, 2], [3, 4]]).minor(4, 5))
raises(ValueError, lambda: Matrix([[1, 2], [3, 4]]).minor_submatrix(4, 5))
raises(TypeError, lambda: Matrix([1, 2, 3]).cross(1))
raises(TypeError, lambda: Matrix([1, 2, 3]).dot(1))
raises(ShapeError, lambda: Matrix([1, 2, 3]).dot(Matrix([1, 2])))
raises(ShapeError, lambda: Matrix([1, 2]).dot([]))
raises(TypeError, lambda: Matrix([1, 2]).dot('a'))
with warns_deprecated_sympy():
Matrix([[1, 2], [3, 4]]).dot(Matrix([[4, 3], [1, 2]]))
raises(ShapeError, lambda: Matrix([1, 2]).dot([1, 2, 3]))
raises(NonSquareMatrixError, lambda: Matrix([1, 2, 3]).exp())
raises(ShapeError, lambda: Matrix([[1, 2], [3, 4]]).normalized())
raises(ValueError, lambda: Matrix([1, 2]).inv(method='not a method'))
raises(NonSquareMatrixError, lambda: Matrix([1, 2]).inverse_GE())
raises(ValueError, lambda: Matrix([[1, 2], [1, 2]]).inverse_GE())
raises(NonSquareMatrixError, lambda: Matrix([1, 2]).inverse_ADJ())
raises(ValueError, lambda: Matrix([[1, 2], [1, 2]]).inverse_ADJ())
raises(NonSquareMatrixError, lambda: Matrix([1, 2]).inverse_LU())
raises(NonSquareMatrixError, lambda: Matrix([1, 2]).is_nilpotent())
raises(NonSquareMatrixError, lambda: Matrix([1, 2]).det())
raises(ValueError,
lambda: Matrix([[1, 2], [3, 4]]).det(method='Not a real method'))
raises(ValueError,
lambda: Matrix([[1, 2, 3, 4], [5, 6, 7, 8],
[9, 10, 11, 12], [13, 14, 15, 16]]).det(iszerofunc="Not function"))
raises(ValueError,
lambda: Matrix([[1, 2, 3, 4], [5, 6, 7, 8],
[9, 10, 11, 12], [13, 14, 15, 16]]).det(iszerofunc=False))
raises(ValueError,
lambda: hessian(Matrix([[1, 2], [3, 4]]), Matrix([[1, 2], [2, 1]])))
raises(ValueError, lambda: hessian(Matrix([[1, 2], [3, 4]]), []))
raises(ValueError, lambda: hessian(Symbol('x')**2, 'a'))
raises(IndexError, lambda: eye(3)[5, 2])
raises(IndexError, lambda: eye(3)[2, 5])
M = Matrix(((1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16)))
raises(ValueError, lambda: M.det('method=LU_decomposition()'))
V = Matrix([[10, 10, 10]])
M = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
raises(ValueError, lambda: M.row_insert(4.7, V))
M = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
raises(ValueError, lambda: M.col_insert(-4.2, V))
def test_len():
assert len(Matrix()) == 0
assert len(Matrix([[1, 2]])) == len(Matrix([[1], [2]])) == 2
assert len(Matrix(0, 2, lambda i, j: 0)) == \
len(Matrix(2, 0, lambda i, j: 0)) == 0
assert len(Matrix([[0, 1, 2], [3, 4, 5]])) == 6
assert Matrix([1]) == Matrix([[1]])
assert not Matrix()
assert Matrix() == Matrix([])
def test_integrate():
A = Matrix(((1, 4, x), (y, 2, 4), (10, 5, x**2)))
assert A.integrate(x) == \
Matrix(((x, 4*x, x**2/2), (x*y, 2*x, 4*x), (10*x, 5*x, x**3/3)))
assert A.integrate(y) == \
Matrix(((y, 4*y, x*y), (y**2/2, 2*y, 4*y), (10*y, 5*y, y*x**2)))
def test_limit():
A = Matrix(((1, 4, sin(x)/x), (y, 2, 4), (10, 5, x**2 + 1)))
assert A.limit(x, 0) == Matrix(((1, 4, 1), (y, 2, 4), (10, 5, 1)))
def test_diff():
A = MutableDenseMatrix(((1, 4, x), (y, 2, 4), (10, 5, x**2 + 1)))
assert isinstance(A.diff(x), type(A))
assert A.diff(x) == MutableDenseMatrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x)))
assert A.diff(y) == MutableDenseMatrix(((0, 0, 0), (1, 0, 0), (0, 0, 0)))
assert diff(A, x) == MutableDenseMatrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x)))
assert diff(A, y) == MutableDenseMatrix(((0, 0, 0), (1, 0, 0), (0, 0, 0)))
A_imm = A.as_immutable()
assert isinstance(A_imm.diff(x), type(A_imm))
assert A_imm.diff(x) == ImmutableDenseMatrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x)))
assert A_imm.diff(y) == ImmutableDenseMatrix(((0, 0, 0), (1, 0, 0), (0, 0, 0)))
assert diff(A_imm, x) == ImmutableDenseMatrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x)))
assert diff(A_imm, y) == ImmutableDenseMatrix(((0, 0, 0), (1, 0, 0), (0, 0, 0)))
def test_diff_by_matrix():
# Derive matrix by matrix:
A = MutableDenseMatrix([[x, y], [z, t]])
assert A.diff(A) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
assert diff(A, A) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
A_imm = A.as_immutable()
assert A_imm.diff(A_imm) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
assert diff(A_imm, A_imm) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
# Derive a constant matrix:
assert A.diff(a) == MutableDenseMatrix([[0, 0], [0, 0]])
B = ImmutableDenseMatrix([a, b])
assert A.diff(B) == Array.zeros(2, 1, 2, 2)
assert A.diff(A) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
# Test diff with tuples:
dB = B.diff([[a, b]])
assert dB.shape == (2, 2, 1)
assert dB == Array([[[1], [0]], [[0], [1]]])
f = Function("f")
fxyz = f(x, y, z)
assert fxyz.diff([[x, y, z]]) == Array([fxyz.diff(x), fxyz.diff(y), fxyz.diff(z)])
assert fxyz.diff(([x, y, z], 2)) == Array([
[fxyz.diff(x, 2), fxyz.diff(x, y), fxyz.diff(x, z)],
[fxyz.diff(x, y), fxyz.diff(y, 2), fxyz.diff(y, z)],
[fxyz.diff(x, z), fxyz.diff(z, y), fxyz.diff(z, 2)],
])
expr = sin(x)*exp(y)
assert expr.diff([[x, y]]) == Array([cos(x)*exp(y), sin(x)*exp(y)])
assert expr.diff(y, ((x, y),)) == Array([cos(x)*exp(y), sin(x)*exp(y)])
assert expr.diff(x, ((x, y),)) == Array([-sin(x)*exp(y), cos(x)*exp(y)])
assert expr.diff(((y, x),), [[x, y]]) == Array([[cos(x)*exp(y), -sin(x)*exp(y)], [sin(x)*exp(y), cos(x)*exp(y)]])
# Test different notations:
fxyz.diff(x).diff(y).diff(x) == fxyz.diff(((x, y, z),), 3)[0, 1, 0]
fxyz.diff(z).diff(y).diff(x) == fxyz.diff(((x, y, z),), 3)[2, 1, 0]
fxyz.diff([[x, y, z]], ((z, y, x),)) == Array([[fxyz.diff(i).diff(j) for i in (x, y, z)] for j in (z, y, x)])
# Test scalar derived by matrix remains matrix:
res = x.diff(Matrix([[x, y]]))
assert isinstance(res, ImmutableDenseMatrix)
assert res == Matrix([[1, 0]])
res = (x**3).diff(Matrix([[x, y]]))
assert isinstance(res, ImmutableDenseMatrix)
assert res == Matrix([[3*x**2, 0]])
def test_getattr():
A = Matrix(((1, 4, x), (y, 2, 4), (10, 5, x**2 + 1)))
raises(AttributeError, lambda: A.nonexistantattribute)
assert getattr(A, 'diff')(x) == Matrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x)))
def test_hessenberg():
A = Matrix([[3, 4, 1], [2, 4, 5], [0, 1, 2]])
assert A.is_upper_hessenberg
A = A.T
assert A.is_lower_hessenberg
A[0, -1] = 1
assert A.is_lower_hessenberg is False
A = Matrix([[3, 4, 1], [2, 4, 5], [3, 1, 2]])
assert not A.is_upper_hessenberg
A = zeros(5, 2)
assert A.is_upper_hessenberg
def test_cholesky():
raises(NonSquareMatrixError, lambda: Matrix((1, 2)).cholesky())
raises(ValueError, lambda: Matrix(((1, 2), (3, 4))).cholesky())
raises(ValueError, lambda: Matrix(((5 + I, 0), (0, 1))).cholesky())
raises(ValueError, lambda: Matrix(((1, 5), (5, 1))).cholesky())
raises(ValueError, lambda: Matrix(((1, 2), (3, 4))).cholesky(hermitian=False))
assert Matrix(((5 + I, 0), (0, 1))).cholesky(hermitian=False) == Matrix([
[sqrt(5 + I), 0], [0, 1]])
A = Matrix(((1, 5), (5, 1)))
L = A.cholesky(hermitian=False)
assert L == Matrix([[1, 0], [5, 2*sqrt(6)*I]])
assert L*L.T == A
A = Matrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11)))
L = A.cholesky()
assert L * L.T == A
assert L.is_lower
assert L == Matrix([[5, 0, 0], [3, 3, 0], [-1, 1, 3]])
A = Matrix(((4, -2*I, 2 + 2*I), (2*I, 2, -1 + I), (2 - 2*I, -1 - I, 11)))
assert A.cholesky().expand() == Matrix(((2, 0, 0), (I, 1, 0), (1 - I, 0, 3)))
raises(NonSquareMatrixError, lambda: SparseMatrix((1, 2)).cholesky())
raises(ValueError, lambda: SparseMatrix(((1, 2), (3, 4))).cholesky())
raises(ValueError, lambda: SparseMatrix(((5 + I, 0), (0, 1))).cholesky())
raises(ValueError, lambda: SparseMatrix(((1, 5), (5, 1))).cholesky())
raises(ValueError, lambda: SparseMatrix(((1, 2), (3, 4))).cholesky(hermitian=False))
assert SparseMatrix(((5 + I, 0), (0, 1))).cholesky(hermitian=False) == Matrix([
[sqrt(5 + I), 0], [0, 1]])
A = SparseMatrix(((1, 5), (5, 1)))
L = A.cholesky(hermitian=False)
assert L == Matrix([[1, 0], [5, 2*sqrt(6)*I]])
assert L*L.T == A
A = SparseMatrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11)))
L = A.cholesky()
assert L * L.T == A
assert L.is_lower
assert L == Matrix([[5, 0, 0], [3, 3, 0], [-1, 1, 3]])
A = SparseMatrix(((4, -2*I, 2 + 2*I), (2*I, 2, -1 + I), (2 - 2*I, -1 - I, 11)))
assert A.cholesky() == Matrix(((2, 0, 0), (I, 1, 0), (1 - I, 0, 3)))
def test_matrix_norm():
# Vector Tests
# Test columns and symbols
x = Symbol('x', real=True)
v = Matrix([cos(x), sin(x)])
assert trigsimp(v.norm(2)) == 1
assert v.norm(10) == Pow(cos(x)**10 + sin(x)**10, Rational(1, 10))
# Test Rows
A = Matrix([[5, Rational(3, 2)]])
assert A.norm() == Pow(25 + Rational(9, 4), S.Half)
assert A.norm(oo) == max(A)
assert A.norm(-oo) == min(A)
# Matrix Tests
# Intuitive test
A = Matrix([[1, 1], [1, 1]])
assert A.norm(2) == 2
assert A.norm(-2) == 0
assert A.norm('frobenius') == 2
assert eye(10).norm(2) == eye(10).norm(-2) == 1
assert A.norm(oo) == 2
# Test with Symbols and more complex entries
A = Matrix([[3, y, y], [x, S.Half, -pi]])
assert (A.norm('fro')
== sqrt(Rational(37, 4) + 2*abs(y)**2 + pi**2 + x**2))
# Check non-square
A = Matrix([[1, 2, -3], [4, 5, Rational(13, 2)]])
assert A.norm(2) == sqrt(Rational(389, 8) + sqrt(78665)/8)
assert A.norm(-2) is S.Zero
assert A.norm('frobenius') == sqrt(389)/2
# Test properties of matrix norms
# https://en.wikipedia.org/wiki/Matrix_norm#Definition
# Two matrices
A = Matrix([[1, 2], [3, 4]])
B = Matrix([[5, 5], [-2, 2]])
C = Matrix([[0, -I], [I, 0]])
D = Matrix([[1, 0], [0, -1]])
L = [A, B, C, D]
alpha = Symbol('alpha', real=True)
for order in ['fro', 2, -2]:
# Zero Check
assert zeros(3).norm(order) is S.Zero
# Check Triangle Inequality for all Pairs of Matrices
for X in L:
for Y in L:
dif = (X.norm(order) + Y.norm(order) -
(X + Y).norm(order))
assert (dif >= 0)
# Scalar multiplication linearity
for M in [A, B, C, D]:
dif = simplify((alpha*M).norm(order) -
abs(alpha) * M.norm(order))
assert dif == 0
# Test Properties of Vector Norms
# https://en.wikipedia.org/wiki/Vector_norm
# Two column vectors
a = Matrix([1, 1 - 1*I, -3])
b = Matrix([S.Half, 1*I, 1])
c = Matrix([-1, -1, -1])
d = Matrix([3, 2, I])
e = Matrix([Integer(1e2), Rational(1, 1e2), 1])
L = [a, b, c, d, e]
alpha = Symbol('alpha', real=True)
for order in [1, 2, -1, -2, S.Infinity, S.NegativeInfinity, pi]:
# Zero Check
if order > 0:
assert Matrix([0, 0, 0]).norm(order) is S.Zero
# Triangle inequality on all pairs
if order >= 1: # Triangle InEq holds only for these norms
for X in L:
for Y in L:
dif = (X.norm(order) + Y.norm(order) -
(X + Y).norm(order))
assert simplify(dif >= 0) is S.true
# Linear to scalar multiplication
if order in [1, 2, -1, -2, S.Infinity, S.NegativeInfinity]:
for X in L:
dif = simplify((alpha*X).norm(order) -
(abs(alpha) * X.norm(order)))
assert dif == 0
# ord=1
M = Matrix(3, 3, [1, 3, 0, -2, -1, 0, 3, 9, 6])
assert M.norm(1) == 13
def test_condition_number():
x = Symbol('x', real=True)
A = eye(3)
A[0, 0] = 10
A[2, 2] = Rational(1, 10)
assert A.condition_number() == 100
A[1, 1] = x
assert A.condition_number() == Max(10, Abs(x)) / Min(Rational(1, 10), Abs(x))
M = Matrix([[cos(x), sin(x)], [-sin(x), cos(x)]])
Mc = M.condition_number()
assert all(Float(1.).epsilon_eq(Mc.subs(x, val).evalf()) for val in
[Rational(1, 5), S.Half, Rational(1, 10), pi/2, pi, pi*Rational(7, 4) ])
#issue 10782
assert Matrix([]).condition_number() == 0
def test_equality():
A = Matrix(((1, 2, 3), (4, 5, 6), (7, 8, 9)))
B = Matrix(((9, 8, 7), (6, 5, 4), (3, 2, 1)))
assert A == A[:, :]
assert not A != A[:, :]
assert not A == B
assert A != B
assert A != 10
assert not A == 10
# A SparseMatrix can be equal to a Matrix
C = SparseMatrix(((1, 0, 0), (0, 1, 0), (0, 0, 1)))
D = Matrix(((1, 0, 0), (0, 1, 0), (0, 0, 1)))
assert C == D
assert not C != D
def test_col_join():
assert eye(3).col_join(Matrix([[7, 7, 7]])) == \
Matrix([[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
[7, 7, 7]])
def test_row_insert():
r4 = Matrix([[4, 4, 4]])
for i in range(-4, 5):
l = [1, 0, 0]
l.insert(i, 4)
assert flatten(eye(3).row_insert(i, r4).col(0).tolist()) == l
def test_col_insert():
c4 = Matrix([4, 4, 4])
for i in range(-4, 5):
l = [0, 0, 0]
l.insert(i, 4)
assert flatten(zeros(3).col_insert(i, c4).row(0).tolist()) == l
def test_normalized():
assert Matrix([3, 4]).normalized() == \
Matrix([Rational(3, 5), Rational(4, 5)])
# Zero vector trivial cases
assert Matrix([0, 0, 0]).normalized() == Matrix([0, 0, 0])
# Machine precision error truncation trivial cases
m = Matrix([0,0,1.e-100])
assert m.normalized(
iszerofunc=lambda x: x.evalf(n=10, chop=True).is_zero
) == Matrix([0, 0, 0])
def test_print_nonzero():
assert capture(lambda: eye(3).print_nonzero()) == \
'[X ]\n[ X ]\n[ X]\n'
assert capture(lambda: eye(3).print_nonzero('.')) == \
'[. ]\n[ . ]\n[ .]\n'
def test_zeros_eye():
assert Matrix.eye(3) == eye(3)
assert Matrix.zeros(3) == zeros(3)
assert ones(3, 4) == Matrix(3, 4, [1]*12)
i = Matrix([[1, 0], [0, 1]])
z = Matrix([[0, 0], [0, 0]])
for cls in classes:
m = cls.eye(2)
assert i == m # but m == i will fail if m is immutable
assert i == eye(2, cls=cls)
assert type(m) == cls
m = cls.zeros(2)
assert z == m
assert z == zeros(2, cls=cls)
assert type(m) == cls
def test_is_zero():
assert Matrix().is_zero_matrix
assert Matrix([[0, 0], [0, 0]]).is_zero_matrix
assert zeros(3, 4).is_zero_matrix
assert not eye(3).is_zero_matrix
assert Matrix([[x, 0], [0, 0]]).is_zero_matrix == None
assert SparseMatrix([[x, 0], [0, 0]]).is_zero_matrix == None
assert ImmutableMatrix([[x, 0], [0, 0]]).is_zero_matrix == None
assert ImmutableSparseMatrix([[x, 0], [0, 0]]).is_zero_matrix == None
assert Matrix([[x, 1], [0, 0]]).is_zero_matrix == False
a = Symbol('a', nonzero=True)
assert Matrix([[a, 0], [0, 0]]).is_zero_matrix == False
def test_rotation_matrices():
# This tests the rotation matrices by rotating about an axis and back.
theta = pi/3
r3_plus = rot_axis3(theta)
r3_minus = rot_axis3(-theta)
r2_plus = rot_axis2(theta)
r2_minus = rot_axis2(-theta)
r1_plus = rot_axis1(theta)
r1_minus = rot_axis1(-theta)
assert r3_minus*r3_plus*eye(3) == eye(3)
assert r2_minus*r2_plus*eye(3) == eye(3)
assert r1_minus*r1_plus*eye(3) == eye(3)
# Check the correctness of the trace of the rotation matrix
assert r1_plus.trace() == 1 + 2*cos(theta)
assert r2_plus.trace() == 1 + 2*cos(theta)
assert r3_plus.trace() == 1 + 2*cos(theta)
# Check that a rotation with zero angle doesn't change anything.
assert rot_axis1(0) == eye(3)
assert rot_axis2(0) == eye(3)
assert rot_axis3(0) == eye(3)
def test_DeferredVector():
assert str(DeferredVector("vector")[4]) == "vector[4]"
assert sympify(DeferredVector("d")) == DeferredVector("d")
raises(IndexError, lambda: DeferredVector("d")[-1])
assert str(DeferredVector("d")) == "d"
assert repr(DeferredVector("test")) == "DeferredVector('test')"
def test_DeferredVector_not_iterable():
assert not iterable(DeferredVector('X'))
def test_DeferredVector_Matrix():
raises(TypeError, lambda: Matrix(DeferredVector("V")))
def test_GramSchmidt():
R = Rational
m1 = Matrix(1, 2, [1, 2])
m2 = Matrix(1, 2, [2, 3])
assert GramSchmidt([m1, m2]) == \
[Matrix(1, 2, [1, 2]), Matrix(1, 2, [R(2)/5, R(-1)/5])]
assert GramSchmidt([m1.T, m2.T]) == \
[Matrix(2, 1, [1, 2]), Matrix(2, 1, [R(2)/5, R(-1)/5])]
# from wikipedia
assert GramSchmidt([Matrix([3, 1]), Matrix([2, 2])], True) == [
Matrix([3*sqrt(10)/10, sqrt(10)/10]),
Matrix([-sqrt(10)/10, 3*sqrt(10)/10])]
# https://github.com/sympy/sympy/issues/9488
L = FiniteSet(Matrix([1]))
assert GramSchmidt(L) == [Matrix([[1]])]
def test_casoratian():
assert casoratian([1, 2, 3, 4], 1) == 0
assert casoratian([1, 2, 3, 4], 1, zero=False) == 0
def test_zero_dimension_multiply():
assert (Matrix()*zeros(0, 3)).shape == (0, 3)
assert zeros(3, 0)*zeros(0, 3) == zeros(3, 3)
assert zeros(0, 3)*zeros(3, 0) == Matrix()
def test_slice_issue_2884():
m = Matrix(2, 2, range(4))
assert m[1, :] == Matrix([[2, 3]])
assert m[-1, :] == Matrix([[2, 3]])
assert m[:, 1] == Matrix([[1, 3]]).T
assert m[:, -1] == Matrix([[1, 3]]).T
raises(IndexError, lambda: m[2, :])
raises(IndexError, lambda: m[2, 2])
def test_slice_issue_3401():
assert zeros(0, 3)[:, -1].shape == (0, 1)
assert zeros(3, 0)[0, :] == Matrix(1, 0, [])
def test_copyin():
s = zeros(3, 3)
s[3] = 1
assert s[:, 0] == 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:] == Matrix([[42, 0]])
s[1, 1:] = Matrix([[5, 6]])
assert s[1, :] == Matrix([[1, 5, 6]])
s[1, 1:] = [[42, 43]]
assert s[1, :] == Matrix([[1, 42, 43]])
s[0, 0] = 17
assert s[:, :1] == Matrix([17, 1, 0])
s[0, 0] = [1, 1, 1]
assert s[:, 0] == Matrix([1, 1, 1])
s[0, 0] = Matrix([1, 1, 1])
assert s[:, 0] == Matrix([1, 1, 1])
s[0, 0] = SparseMatrix([1, 1, 1])
assert s[:, 0] == Matrix([1, 1, 1])
def test_invertible_check():
# sometimes a singular matrix will have a pivot vector shorter than
# the number of rows in a matrix...
assert Matrix([[1, 2], [1, 2]]).rref() == (Matrix([[1, 2], [0, 0]]), (0,))
raises(ValueError, lambda: Matrix([[1, 2], [1, 2]]).inv())
m = Matrix([
[-1, -1, 0],
[ x, 1, 1],
[ 1, x, -1],
])
assert len(m.rref()[1]) != m.rows
# in addition, unless simplify=True in the call to rref, the identity
# matrix will be returned even though m is not invertible
assert m.rref()[0] != eye(3)
assert m.rref(simplify=signsimp)[0] != eye(3)
raises(ValueError, lambda: m.inv(method="ADJ"))
raises(ValueError, lambda: m.inv(method="GE"))
raises(ValueError, lambda: m.inv(method="LU"))
def test_issue_3959():
x, y = symbols('x, y')
e = x*y
assert e.subs(x, Matrix([3, 5, 3])) == Matrix([3, 5, 3])*y
def test_issue_5964():
assert str(Matrix([[1, 2], [3, 4]])) == 'Matrix([[1, 2], [3, 4]])'
def test_issue_7604():
x, y = symbols("x y")
assert sstr(Matrix([[x, 2*y], [y**2, x + 3]])) == \
'Matrix([\n[ x, 2*y],\n[y**2, x + 3]])'
def test_is_Identity():
assert eye(3).is_Identity
assert eye(3).as_immutable().is_Identity
assert not zeros(3).is_Identity
assert not ones(3).is_Identity
# issue 6242
assert not Matrix([[1, 0, 0]]).is_Identity
# issue 8854
assert SparseMatrix(3,3, {(0,0):1, (1,1):1, (2,2):1}).is_Identity
assert not SparseMatrix(2,3, range(6)).is_Identity
assert not SparseMatrix(3,3, {(0,0):1, (1,1):1}).is_Identity
assert not SparseMatrix(3,3, {(0,0):1, (1,1):1, (2,2):1, (0,1):2, (0,2):3}).is_Identity
def test_dot():
assert ones(1, 3).dot(ones(3, 1)) == 3
assert ones(1, 3).dot([1, 1, 1]) == 3
assert Matrix([1, 2, 3]).dot(Matrix([1, 2, 3])) == 14
assert Matrix([1, 2, 3*I]).dot(Matrix([I, 2, 3*I])) == -5 + I
assert Matrix([1, 2, 3*I]).dot(Matrix([I, 2, 3*I]), hermitian=False) == -5 + I
assert Matrix([1, 2, 3*I]).dot(Matrix([I, 2, 3*I]), hermitian=True) == 13 + I
assert Matrix([1, 2, 3*I]).dot(Matrix([I, 2, 3*I]), hermitian=True, conjugate_convention="physics") == 13 - I
assert Matrix([1, 2, 3*I]).dot(Matrix([4, 5*I, 6]), hermitian=True, conjugate_convention="right") == 4 + 8*I
assert Matrix([1, 2, 3*I]).dot(Matrix([4, 5*I, 6]), hermitian=True, conjugate_convention="left") == 4 - 8*I
assert Matrix([I, 2*I]).dot(Matrix([I, 2*I]), hermitian=False, conjugate_convention="left") == -5
assert Matrix([I, 2*I]).dot(Matrix([I, 2*I]), conjugate_convention="left") == 5
raises(ValueError, lambda: Matrix([1, 2]).dot(Matrix([3, 4]), hermitian=True, conjugate_convention="test"))
def test_dual():
B_x, B_y, B_z, E_x, E_y, E_z = symbols(
'B_x B_y B_z E_x E_y E_z', real=True)
F = Matrix((
( 0, E_x, E_y, E_z),
(-E_x, 0, B_z, -B_y),
(-E_y, -B_z, 0, B_x),
(-E_z, B_y, -B_x, 0)
))
Fd = Matrix((
( 0, -B_x, -B_y, -B_z),
(B_x, 0, E_z, -E_y),
(B_y, -E_z, 0, E_x),
(B_z, E_y, -E_x, 0)
))
assert F.dual().equals(Fd)
assert eye(3).dual().equals(zeros(3))
assert F.dual().dual().equals(-F)
def test_anti_symmetric():
assert Matrix([1, 2]).is_anti_symmetric() is False
m = Matrix(3, 3, [0, x**2 + 2*x + 1, y, -(x + 1)**2, 0, x*y, -y, -x*y, 0])
assert m.is_anti_symmetric() is True
assert m.is_anti_symmetric(simplify=False) is False
assert m.is_anti_symmetric(simplify=lambda x: x) is False
# tweak to fail
m[2, 1] = -m[2, 1]
assert m.is_anti_symmetric() is False
# untweak
m[2, 1] = -m[2, 1]
m = m.expand()
assert m.is_anti_symmetric(simplify=False) is True
m[0, 0] = 1
assert m.is_anti_symmetric() is False
def test_normalize_sort_diogonalization():
A = Matrix(((1, 2), (2, 1)))
P, Q = A.diagonalize(normalize=True)
assert P*P.T == P.T*P == eye(P.cols)
P, Q = A.diagonalize(normalize=True, sort=True)
assert P*P.T == P.T*P == eye(P.cols)
assert P*Q*P.inv() == A
def test_issue_5321():
raises(ValueError, lambda: Matrix([[1, 2, 3], Matrix(0, 1, [])]))
def test_issue_5320():
assert Matrix.hstack(eye(2), 2*eye(2)) == Matrix([
[1, 0, 2, 0],
[0, 1, 0, 2]
])
assert Matrix.vstack(eye(2), 2*eye(2)) == Matrix([
[1, 0],
[0, 1],
[2, 0],
[0, 2]
])
cls = SparseMatrix
assert cls.hstack(cls(eye(2)), cls(2*eye(2))) == Matrix([
[1, 0, 2, 0],
[0, 1, 0, 2]
])
def test_issue_11944():
A = Matrix([[1]])
AIm = sympify(A)
assert Matrix.hstack(AIm, A) == Matrix([[1, 1]])
assert Matrix.vstack(AIm, A) == Matrix([[1], [1]])
def test_cross():
a = [1, 2, 3]
b = [3, 4, 5]
col = Matrix([-2, 4, -2])
row = col.T
def test(M, ans):
assert ans == M
assert type(M) == cls
for cls in classes:
A = cls(a)
B = cls(b)
test(A.cross(B), col)
test(A.cross(B.T), col)
test(A.T.cross(B.T), row)
test(A.T.cross(B), row)
raises(ShapeError, lambda:
Matrix(1, 2, [1, 1]).cross(Matrix(1, 2, [1, 1])))
def test_hash():
for cls in classes[-2:]:
s = {cls.eye(1), cls.eye(1)}
assert len(s) == 1 and s.pop() == cls.eye(1)
# issue 3979
for cls in classes[:2]:
assert not isinstance(cls.eye(1), Hashable)
@XFAIL
def test_issue_3979():
# when this passes, delete this and change the [1:2]
# to [:2] in the test_hash above for issue 3979
cls = classes[0]
raises(AttributeError, lambda: hash(cls.eye(1)))
def test_adjoint():
dat = [[0, I], [1, 0]]
ans = Matrix([[0, 1], [-I, 0]])
for cls in classes:
assert ans == cls(dat).adjoint()
def test_simplify_immutable():
assert simplify(ImmutableMatrix([[sin(x)**2 + cos(x)**2]])) == \
ImmutableMatrix([[1]])
def test_replace():
F, G = symbols('F, G', cls=Function)
K = Matrix(2, 2, lambda i, j: G(i+j))
M = Matrix(2, 2, lambda i, j: F(i+j))
N = M.replace(F, G)
assert N == K
def test_replace_map():
F, G = symbols('F, G', cls=Function)
with warns_deprecated_sympy():
K = Matrix(2, 2, [(G(0), {F(0): G(0)}), (G(1), {F(1): G(1)}),
(G(1), {F(1): G(1)}), (G(2), {F(2): G(2)})])
M = Matrix(2, 2, lambda i, j: F(i+j))
with warns_deprecated_sympy():
N = M.replace(F, G, True)
assert N == K
def test_atoms():
m = Matrix([[1, 2], [x, 1 - 1/x]])
assert m.atoms() == {S.One,S(2),S.NegativeOne, x}
assert m.atoms(Symbol) == {x}
def test_pinv():
# Pseudoinverse of an invertible matrix is the inverse.
A1 = Matrix([[a, b], [c, d]])
assert simplify(A1.pinv(method="RD")) == simplify(A1.inv())
# Test the four properties of the pseudoinverse for various matrices.
As = [Matrix([[13, 104], [2212, 3], [-3, 5]]),
Matrix([[1, 7, 9], [11, 17, 19]]),
Matrix([a, b])]
for A in As:
A_pinv = A.pinv(method="RD")
AAp = A * A_pinv
ApA = A_pinv * A
assert simplify(AAp * A) == A
assert simplify(ApA * A_pinv) == A_pinv
assert AAp.H == AAp
assert ApA.H == ApA
# XXX Pinv with diagonalization makes expression too complicated.
for A in As:
A_pinv = simplify(A.pinv(method="ED"))
AAp = A * A_pinv
ApA = A_pinv * A
assert simplify(AAp * A) == A
assert simplify(ApA * A_pinv) == A_pinv
assert AAp.H == AAp
assert ApA.H == ApA
# XXX Computing pinv using diagonalization makes an expression that
# is too complicated to simplify.
# A1 = Matrix([[a, b], [c, d]])
# assert simplify(A1.pinv(method="ED")) == simplify(A1.inv())
# so this is tested numerically at a fixed random point
from sympy.core.numbers import comp
q = A1.pinv(method="ED")
w = A1.inv()
reps = {a: -73633, b: 11362, c: 55486, d: 62570}
assert all(
comp(i.n(), j.n())
for i, j in zip(q.subs(reps), w.subs(reps))
)
@slow
@XFAIL
def test_pinv_rank_deficient_when_diagonalization_fails():
# Test the four properties of the pseudoinverse for matrices when
# diagonalization of A.H*A fails.
As = [
Matrix([
[61, 89, 55, 20, 71, 0],
[62, 96, 85, 85, 16, 0],
[69, 56, 17, 4, 54, 0],
[10, 54, 91, 41, 71, 0],
[ 7, 30, 10, 48, 90, 0],
[0, 0, 0, 0, 0, 0]])
]
for A in As:
A_pinv = A.pinv(method="ED")
AAp = A * A_pinv
ApA = A_pinv * A
assert AAp.H == AAp
assert ApA.H == ApA
def test_issue_7201():
assert ones(0, 1) + ones(0, 1) == Matrix(0, 1, [])
assert ones(1, 0) + ones(1, 0) == Matrix(1, 0, [])
def test_free_symbols():
for M in ImmutableMatrix, ImmutableSparseMatrix, Matrix, SparseMatrix:
assert M([[x], [0]]).free_symbols == {x}
def test_from_ndarray():
"""See issue 7465."""
try:
from numpy import array
except ImportError:
skip('NumPy must be available to test creating matrices from ndarrays')
assert Matrix(array([1, 2, 3])) == Matrix([1, 2, 3])
assert Matrix(array([[1, 2, 3]])) == Matrix([[1, 2, 3]])
assert Matrix(array([[1, 2, 3], [4, 5, 6]])) == \
Matrix([[1, 2, 3], [4, 5, 6]])
assert Matrix(array([x, y, z])) == Matrix([x, y, z])
raises(NotImplementedError,
lambda: Matrix(array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])))
assert Matrix([array([1, 2]), array([3, 4])]) == Matrix([[1, 2], [3, 4]])
assert Matrix([array([1, 2]), [3, 4]]) == Matrix([[1, 2], [3, 4]])
assert Matrix([array([]), array([])]) == Matrix([])
def test_17522_numpy():
from sympy.matrices.common import _matrixify
try:
from numpy import array, matrix
except ImportError:
skip('NumPy must be available to test indexing matrixified NumPy ndarrays and matrices')
m = _matrixify(array([[1, 2], [3, 4]]))
assert m[3] == 4
assert list(m) == [1, 2, 3, 4]
m = _matrixify(matrix([[1, 2], [3, 4]]))
assert m[3] == 4
assert list(m) == [1, 2, 3, 4]
def test_17522_mpmath():
from sympy.matrices.common import _matrixify
try:
from mpmath import matrix
except ImportError:
skip('mpmath must be available to test indexing matrixified mpmath matrices')
m = _matrixify(matrix([[1, 2], [3, 4]]))
assert m[3] == 4
assert list(m) == [1, 2, 3, 4]
def test_17522_scipy():
from sympy.matrices.common import _matrixify
try:
from scipy.sparse import csr_matrix
except ImportError:
skip('SciPy must be available to test indexing matrixified SciPy sparse matrices')
m = _matrixify(csr_matrix([[1, 2], [3, 4]]))
assert m[3] == 4
assert list(m) == [1, 2, 3, 4]
def test_hermitian():
a = Matrix([[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_doit():
a = Matrix([[Add(x,x, evaluate=False)]])
assert a[0] != 2*x
assert a.doit() == Matrix([[2*x]])
def test_issue_9457_9467_9876():
# for row_del(index)
M = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
M.row_del(1)
assert M == Matrix([[1, 2, 3], [3, 4, 5]])
N = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
N.row_del(-2)
assert N == Matrix([[1, 2, 3], [3, 4, 5]])
O = Matrix([[1, 2, 3], [5, 6, 7], [9, 10, 11]])
O.row_del(-1)
assert O == Matrix([[1, 2, 3], [5, 6, 7]])
P = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
raises(IndexError, lambda: P.row_del(10))
Q = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
raises(IndexError, lambda: Q.row_del(-10))
# for col_del(index)
M = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
M.col_del(1)
assert M == Matrix([[1, 3], [2, 4], [3, 5]])
N = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
N.col_del(-2)
assert N == Matrix([[1, 3], [2, 4], [3, 5]])
P = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
raises(IndexError, lambda: P.col_del(10))
Q = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
raises(IndexError, lambda: Q.col_del(-10))
def test_issue_9422():
x, y = symbols('x y', commutative=False)
a, b = symbols('a b')
M = eye(2)
M1 = Matrix(2, 2, [x, y, y, z])
assert y*x*M != x*y*M
assert b*a*M == a*b*M
assert x*M1 != M1*x
assert a*M1 == M1*a
assert y*x*M == Matrix([[y*x, 0], [0, y*x]])
def test_issue_10770():
M = Matrix([])
a = ['col_insert', 'row_join'], Matrix([9, 6, 3])
b = ['row_insert', 'col_join'], a[1].T
c = ['row_insert', 'col_insert'], Matrix([[1, 2], [3, 4]])
for ops, m in (a, b, c):
for op in ops:
f = getattr(M, op)
new = f(m) if 'join' in op else f(42, m)
assert new == m and id(new) != id(m)
def test_issue_10658():
A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
assert A.extract([0, 1, 2], [True, True, False]) == \
Matrix([[1, 2], [4, 5], [7, 8]])
assert A.extract([0, 1, 2], [True, False, False]) == Matrix([[1], [4], [7]])
assert A.extract([True, False, False], [0, 1, 2]) == Matrix([[1, 2, 3]])
assert A.extract([True, False, True], [0, 1, 2]) == \
Matrix([[1, 2, 3], [7, 8, 9]])
assert A.extract([0, 1, 2], [False, False, False]) == Matrix(3, 0, [])
assert A.extract([False, False, False], [0, 1, 2]) == Matrix(0, 3, [])
assert A.extract([True, False, True], [False, True, False]) == \
Matrix([[2], [8]])
def test_opportunistic_simplification():
# this test relates to issue #10718, #9480, #11434
# issue #9480
m = Matrix([[-5 + 5*sqrt(2), -5], [-5*sqrt(2)/2 + 5, -5*sqrt(2)/2]])
assert m.rank() == 1
# issue #10781
m = Matrix([[3+3*sqrt(3)*I, -9],[4,-3+3*sqrt(3)*I]])
assert simplify(m.rref()[0] - Matrix([[1, -9/(3 + 3*sqrt(3)*I)], [0, 0]])) == zeros(2, 2)
# issue #11434
ax,ay,bx,by,cx,cy,dx,dy,ex,ey,t0,t1 = symbols('a_x a_y b_x b_y c_x c_y d_x d_y e_x e_y t_0 t_1')
m = Matrix([[ax,ay,ax*t0,ay*t0,0],[bx,by,bx*t0,by*t0,0],[cx,cy,cx*t0,cy*t0,1],[dx,dy,dx*t0,dy*t0,1],[ex,ey,2*ex*t1-ex*t0,2*ey*t1-ey*t0,0]])
assert m.rank() == 4
def test_partial_pivoting():
# example from https://en.wikipedia.org/wiki/Pivot_element
# partial pivoting with back substitution gives a perfect result
# naive pivoting give an error ~1e-13, so anything better than
# 1e-15 is good
mm=Matrix([[0.003, 59.14, 59.17], [5.291, -6.13, 46.78]])
assert (mm.rref()[0] - Matrix([[1.0, 0, 10.0],
[ 0, 1.0, 1.0]])).norm() < 1e-15
# issue #11549
m_mixed = Matrix([[6e-17, 1.0, 4],
[ -1.0, 0, 8],
[ 0, 0, 1]])
m_float = Matrix([[6e-17, 1.0, 4.],
[ -1.0, 0., 8.],
[ 0., 0., 1.]])
m_inv = Matrix([[ 0, -1.0, 8.0],
[1.0, 6.0e-17, -4.0],
[ 0, 0, 1]])
# this example is numerically unstable and involves a matrix with a norm >= 8,
# this comparing the difference of the results with 1e-15 is numerically sound.
assert (m_mixed.inv() - m_inv).norm() < 1e-15
assert (m_float.inv() - m_inv).norm() < 1e-15
def test_iszero_substitution():
""" When doing numerical computations, all elements that pass
the iszerofunc test should be set to numerically zero if they
aren't already. """
# Matrix from issue #9060
m = Matrix([[0.9, -0.1, -0.2, 0],[-0.8, 0.9, -0.4, 0],[-0.1, -0.8, 0.6, 0]])
m_rref = m.rref(iszerofunc=lambda x: abs(x)<6e-15)[0]
m_correct = Matrix([[1.0, 0, -0.301369863013699, 0],[ 0, 1.0, -0.712328767123288, 0],[ 0, 0, 0, 0]])
m_diff = m_rref - m_correct
assert m_diff.norm() < 1e-15
# if a zero-substitution wasn't made, this entry will be -1.11022302462516e-16
assert m_rref[2,2] == 0
def test_issue_11238():
from sympy.geometry.point import Point
xx = 8*tan(pi*Rational(13, 45))/(tan(pi*Rational(13, 45)) + sqrt(3))
yy = (-8*sqrt(3)*tan(pi*Rational(13, 45))**2 + 24*tan(pi*Rational(13, 45)))/(-3 + tan(pi*Rational(13, 45))**2)
p1 = Point(0, 0)
p2 = Point(1, -sqrt(3))
p0 = Point(xx,yy)
m1 = Matrix([p1 - simplify(p0), p2 - simplify(p0)])
m2 = Matrix([p1 - p0, p2 - p0])
m3 = Matrix([simplify(p1 - p0), simplify(p2 - p0)])
# This system has expressions which are zero and
# cannot be easily proved to be such, so without
# numerical testing, these assertions will fail.
Z = lambda x: abs(x.n()) < 1e-20
assert m1.rank(simplify=True, iszerofunc=Z) == 1
assert m2.rank(simplify=True, iszerofunc=Z) == 1
assert m3.rank(simplify=True, iszerofunc=Z) == 1
def test_as_real_imag():
m1 = Matrix(2,2,[1,2,3,4])
m2 = m1*S.ImaginaryUnit
m3 = m1 + m2
for kls in classes:
a,b = kls(m3).as_real_imag()
assert list(a) == list(m1)
assert list(b) == list(m1)
def test_deprecated():
# Maintain tests for deprecated functions. We must capture
# the deprecation warnings. When the deprecated functionality is
# removed, the corresponding tests should be removed.
m = Matrix(3, 3, [0, 1, 0, -4, 4, 0, -2, 1, 2])
P, Jcells = m.jordan_cells()
assert Jcells[1] == Matrix(1, 1, [2])
assert Jcells[0] == Matrix(2, 2, [2, 1, 0, 2])
with warns_deprecated_sympy():
assert Matrix([[1,2],[3,4]]).dot(Matrix([[1,3],[4,5]])) == [10, 19, 14, 28]
def test_issue_14489():
from sympy.core.mod import Mod
A = Matrix([-1, 1, 2])
B = Matrix([10, 20, -15])
assert Mod(A, 3) == Matrix([2, 1, 2])
assert Mod(B, 4) == Matrix([2, 0, 1])
def test_issue_14943():
# Test that __array__ accepts the optional dtype argument
try:
from numpy import array
except ImportError:
skip('NumPy must be available to test creating matrices from ndarrays')
M = Matrix([[1,2], [3,4]])
assert array(M, dtype=float).dtype.name == 'float64'
def test_case_6913():
m = MatrixSymbol('m', 1, 1)
a = Symbol("a")
a = m[0, 0]>0
assert str(a) == 'm[0, 0] > 0'
def test_issue_11948():
A = MatrixSymbol('A', 3, 3)
a = Wild('a')
assert A.match(a) == {a: A}
def test_gramschmidt_conjugate_dot():
vecs = [Matrix([1, I]), Matrix([1, -I])]
assert Matrix.orthogonalize(*vecs) == \
[Matrix([[1], [I]]), Matrix([[1], [-I]])]
vecs = [Matrix([1, I, 0]), Matrix([I, 0, -I])]
assert Matrix.orthogonalize(*vecs) == \
[Matrix([[1], [I], [0]]), Matrix([[I/2], [S(1)/2], [-I]])]
mat = Matrix([[1, I], [1, -I]])
Q, R = mat.QRdecomposition()
assert Q * Q.H == Matrix.eye(2)
def test_issue_8207():
a = Matrix(MatrixSymbol('a', 3, 1))
b = Matrix(MatrixSymbol('b', 3, 1))
c = a.dot(b)
d = diff(c, a[0, 0])
e = diff(d, a[0, 0])
assert d == b[0, 0]
assert e == 0
def test_func():
from sympy.simplify.simplify import nthroot
A = Matrix([[1, 2],[0, 3]])
assert A.analytic_func(sin(x*t), x) == Matrix([[sin(t), sin(3*t) - sin(t)], [0, sin(3*t)]])
A = Matrix([[2, 1],[1, 2]])
assert (pi * A / 6).analytic_func(cos(x), x) == Matrix([[sqrt(3)/4, -sqrt(3)/4], [-sqrt(3)/4, sqrt(3)/4]])
raises(ValueError, lambda : zeros(5).analytic_func(log(x), x))
raises(ValueError, lambda : (A*x).analytic_func(log(x), x))
A = Matrix([[0, -1, -2, 3], [0, -1, -2, 3], [0, 1, 0, -1], [0, 0, -1, 1]])
assert A.analytic_func(exp(x), x) == A.exp()
raises(ValueError, lambda : A.analytic_func(sqrt(x), x))
A = Matrix([[41, 12],[12, 34]])
assert simplify(A.analytic_func(sqrt(x), x)**2) == A
A = Matrix([[3, -12, 4], [-1, 0, -2], [-1, 5, -1]])
assert simplify(A.analytic_func(nthroot(x, 3), x)**3) == A
A = Matrix([[2, 0, 0, 0], [1, 2, 0, 0], [0, 1, 3, 0], [0, 0, 1, 3]])
assert A.analytic_func(exp(x), x) == A.exp()
A = Matrix([[0, 2, 1, 6], [0, 0, 1, 2], [0, 0, 0, 3], [0, 0, 0, 0]])
assert A.analytic_func(exp(x*t), x) == expand(simplify((A*t).exp()))
def test_issue_19809():
def f():
assert _dotprodsimp_state.state == None
m = Matrix([[1]])
m = m * m
return True
with dotprodsimp(True):
with concurrent.futures.ThreadPoolExecutor() as executor:
future = executor.submit(f)
assert future.result()
|
cae860009759b98e93170c0ebba94ab7632802f0366050c3f77153c7c8d875c7 | from sympy.core.expr import ExprBuilder
from sympy.core.function import (Function, FunctionClass, Lambda)
from sympy.core.symbol import Dummy
from sympy.core.sympify import sympify, _sympify
from sympy.matrices.expressions import MatrixExpr
from sympy.matrices.matrices import MatrixBase
class ElementwiseApplyFunction(MatrixExpr):
r"""
Apply function to a matrix elementwise without evaluating.
Examples
========
It can be created by calling ``.applyfunc(<function>)`` on a matrix
expression:
>>> from sympy.matrices.expressions import MatrixSymbol
>>> from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction
>>> from sympy import exp
>>> X = MatrixSymbol("X", 3, 3)
>>> X.applyfunc(exp)
Lambda(_d, exp(_d)).(X)
Otherwise using the class constructor:
>>> from sympy import eye
>>> expr = ElementwiseApplyFunction(exp, eye(3))
>>> expr
Lambda(_d, exp(_d)).(Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]]))
>>> expr.doit()
Matrix([
[E, 1, 1],
[1, E, 1],
[1, 1, E]])
Notice the difference with the real mathematical functions:
>>> exp(eye(3))
Matrix([
[E, 0, 0],
[0, E, 0],
[0, 0, E]])
"""
def __new__(cls, function, expr):
expr = _sympify(expr)
if not expr.is_Matrix:
raise ValueError("{} must be a matrix instance.".format(expr))
if expr.shape == (1, 1):
# Check if the function returns a matrix, in that case, just apply
# the function instead of creating an ElementwiseApplyFunc object:
ret = function(expr)
if isinstance(ret, MatrixExpr):
return ret
if not isinstance(function, (FunctionClass, Lambda)):
d = Dummy('d')
function = Lambda(d, function(d))
function = sympify(function)
if not isinstance(function, (FunctionClass, Lambda)):
raise ValueError(
"{} should be compatible with SymPy function classes."
.format(function))
if 1 not in function.nargs:
raise ValueError(
'{} should be able to accept 1 arguments.'.format(function))
if not isinstance(function, Lambda):
d = Dummy('d')
function = Lambda(d, function(d))
obj = MatrixExpr.__new__(cls, function, expr)
return obj
@property
def function(self):
return self.args[0]
@property
def expr(self):
return self.args[1]
@property
def shape(self):
return self.expr.shape
def doit(self, **kwargs):
deep = kwargs.get("deep", True)
expr = self.expr
if deep:
expr = expr.doit(**kwargs)
function = self.function
if isinstance(function, Lambda) and function.is_identity:
# This is a Lambda containing the identity function.
return expr
if isinstance(expr, MatrixBase):
return expr.applyfunc(self.function)
elif isinstance(expr, ElementwiseApplyFunction):
return ElementwiseApplyFunction(
lambda x: self.function(expr.function(x)),
expr.expr
).doit()
else:
return self
def _entry(self, i, j, **kwargs):
return self.function(self.expr._entry(i, j, **kwargs))
def _get_function_fdiff(self):
d = Dummy("d")
function = self.function(d)
fdiff = function.diff(d)
if isinstance(fdiff, Function):
fdiff = type(fdiff)
else:
fdiff = Lambda(d, fdiff)
return fdiff
def _eval_derivative(self, x):
from sympy.matrices.expressions.hadamard import hadamard_product
dexpr = self.expr.diff(x)
fdiff = self._get_function_fdiff()
return hadamard_product(
dexpr,
ElementwiseApplyFunction(fdiff, self.expr)
)
def _eval_derivative_matrix_lines(self, x):
from sympy.matrices.expressions.special import Identity
from sympy.tensor.array.expressions.array_expressions import ArrayContraction
from sympy.tensor.array.expressions.array_expressions import ArrayDiagonal
from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct
fdiff = self._get_function_fdiff()
lr = self.expr._eval_derivative_matrix_lines(x)
ewdiff = ElementwiseApplyFunction(fdiff, self.expr)
if 1 in x.shape:
# Vector:
iscolumn = self.shape[1] == 1
for i in lr:
if iscolumn:
ptr1 = i.first_pointer
ptr2 = Identity(self.shape[1])
else:
ptr1 = Identity(self.shape[0])
ptr2 = i.second_pointer
subexpr = ExprBuilder(
ArrayDiagonal,
[
ExprBuilder(
ArrayTensorProduct,
[
ewdiff,
ptr1,
ptr2,
]
),
(0, 2) if iscolumn else (1, 4)
],
validator=ArrayDiagonal._validate
)
i._lines = [subexpr]
i._first_pointer_parent = subexpr.args[0].args
i._first_pointer_index = 1
i._second_pointer_parent = subexpr.args[0].args
i._second_pointer_index = 2
else:
# Matrix case:
for i in lr:
ptr1 = i.first_pointer
ptr2 = i.second_pointer
newptr1 = Identity(ptr1.shape[1])
newptr2 = Identity(ptr2.shape[1])
subexpr = ExprBuilder(
ArrayContraction,
[
ExprBuilder(
ArrayTensorProduct,
[ptr1, newptr1, ewdiff, ptr2, newptr2]
),
(1, 2, 4),
(5, 7, 8),
],
validator=ArrayContraction._validate
)
i._first_pointer_parent = subexpr.args[0].args
i._first_pointer_index = 1
i._second_pointer_parent = subexpr.args[0].args
i._second_pointer_index = 4
i._lines = [subexpr]
return lr
def _eval_transpose(self):
from sympy.matrices.expressions.transpose import Transpose
return self.func(self.function, Transpose(self.expr).doit())
|
8657c09a60d2dfaab3dcc078457c74dc9529f0616e06a84f99fa6a4bba5f741a | from sympy.core.basic import Basic
from sympy.core.expr import Expr
from sympy.core.singleton import S
from sympy.core.sympify import sympify
from sympy.matrices.common import NonSquareMatrixError
class Determinant(Expr):
"""Matrix Determinant
Represents the determinant of a matrix expression.
Examples
========
>>> from sympy import MatrixSymbol, Determinant, eye
>>> A = MatrixSymbol('A', 3, 3)
>>> Determinant(A)
Determinant(A)
>>> Determinant(eye(3)).doit()
1
"""
is_commutative = True
def __new__(cls, mat):
mat = sympify(mat)
if not mat.is_Matrix:
raise TypeError("Input to Determinant, %s, not a matrix" % str(mat))
if not mat.is_square:
raise NonSquareMatrixError("Det of a non-square matrix")
return Basic.__new__(cls, mat)
@property
def arg(self):
return self.args[0]
@property
def kind(self):
return self.arg.kind.element_kind
def doit(self, expand=False):
try:
return self.arg._eval_determinant()
except (AttributeError, NotImplementedError):
return self
def det(matexpr):
""" Matrix Determinant
Examples
========
>>> from sympy import MatrixSymbol, det, eye
>>> A = MatrixSymbol('A', 3, 3)
>>> det(A)
Determinant(A)
>>> det(eye(3))
1
"""
return Determinant(matexpr).doit()
class Permanent(Expr):
"""Matrix Permanent
Represents the permanent of a matrix expression.
Examples
========
>>> from sympy import MatrixSymbol, Permanent, ones
>>> A = MatrixSymbol('A', 3, 3)
>>> Permanent(A)
Permanent(A)
>>> Permanent(ones(3, 3)).doit()
6
"""
def __new__(cls, mat):
mat = sympify(mat)
if not mat.is_Matrix:
raise TypeError("Input to Permanent, %s, not a matrix" % str(mat))
return Basic.__new__(cls, mat)
@property
def arg(self):
return self.args[0]
def doit(self, expand=False):
try:
return self.arg.per()
except (AttributeError, NotImplementedError):
return self
def per(matexpr):
""" Matrix Permanent
Examples
========
>>> from sympy import MatrixSymbol, Matrix, per, ones
>>> A = MatrixSymbol('A', 3, 3)
>>> per(A)
Permanent(A)
>>> per(ones(5, 5))
120
>>> M = Matrix([1, 2, 5])
>>> per(M)
8
"""
return Permanent(matexpr).doit()
from sympy.assumptions.ask import ask, Q
from sympy.assumptions.refine import handlers_dict
def refine_Determinant(expr, assumptions):
"""
>>> from sympy import MatrixSymbol, Q, assuming, refine, det
>>> X = MatrixSymbol('X', 2, 2)
>>> det(X)
Determinant(X)
>>> with assuming(Q.orthogonal(X)):
... print(refine(det(X)))
1
"""
if ask(Q.orthogonal(expr.arg), assumptions):
return S.One
elif ask(Q.singular(expr.arg), assumptions):
return S.Zero
elif ask(Q.unit_triangular(expr.arg), assumptions):
return S.One
return expr
handlers_dict['Determinant'] = refine_Determinant
|
cc5363301b09aa1b087030fc31ee16f3e43e4d5f3d5a9b5f1b70ddf722bfb4f1 | from sympy.matrices.expressions import MatrixExpr
from sympy.assumptions.ask import Q
class Factorization(MatrixExpr):
arg = property(lambda self: self.args[0])
shape = property(lambda self: self.arg.shape) # type: ignore
class LofLU(Factorization):
@property
def predicates(self):
return (Q.lower_triangular,)
class UofLU(Factorization):
@property
def predicates(self):
return (Q.upper_triangular,)
class LofCholesky(LofLU): pass
class UofCholesky(UofLU): pass
class QofQR(Factorization):
@property
def predicates(self):
return (Q.orthogonal,)
class RofQR(Factorization):
@property
def predicates(self):
return (Q.upper_triangular,)
class EigenVectors(Factorization):
@property
def predicates(self):
return (Q.orthogonal,)
class EigenValues(Factorization):
@property
def predicates(self):
return (Q.diagonal,)
class UofSVD(Factorization):
@property
def predicates(self):
return (Q.orthogonal,)
class SofSVD(Factorization):
@property
def predicates(self):
return (Q.diagonal,)
class VofSVD(Factorization):
@property
def predicates(self):
return (Q.orthogonal,)
def lu(expr):
return LofLU(expr), UofLU(expr)
def qr(expr):
return QofQR(expr), RofQR(expr)
def eig(expr):
return EigenValues(expr), EigenVectors(expr)
def svd(expr):
return UofSVD(expr), SofSVD(expr), VofSVD(expr)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.