Skip to content

Commit

Permalink
Merge pull request #22295 from oscargus/replacenpmatrixwithnparray
Browse files Browse the repository at this point in the history
Removed deprecated numpy.matrix
  • Loading branch information
oscarbenjamin committed Feb 16, 2022
2 parents c820a87 + 1bdd027 commit 131caae
Show file tree
Hide file tree
Showing 8 changed files with 34 additions and 32 deletions.
7 changes: 0 additions & 7 deletions pytest.ini
Expand Up @@ -4,13 +4,6 @@
# collect tests from e.g. the bin/ directory as well.
testpaths = sympy doc/src

# np.matrix is deprecated but still used in sympy.physics.quantum:
# https://github.com/sympy/sympy/issues/15563
# This prevents ~800 warnings showing up running the tests under pytest.
filterwarnings =
ignore:.*the matrix subclass is not the recommended way.*:PendingDeprecationWarning
ignore:IPython.utils.signatures backport for Python 2 is deprecated.*:DeprecationWarning

# Normalise output of doctests.
doctest_optionflags =
NORMALIZE_WHITESPACE
Expand Down
6 changes: 3 additions & 3 deletions sympy/physics/quantum/matrixutils.py
Expand Up @@ -49,7 +49,7 @@ def sympy_to_numpy(m, **options):
raise ImportError
dtype = options.get('dtype', 'complex')
if isinstance(m, MatrixBase):
return np.matrix(m.tolist(), dtype=dtype)
return np.array(m.tolist(), dtype=dtype)
elif isinstance(m, Expr):
if m.is_Number or m.is_NumberSymbol or m == I:
return complex(m)
Expand All @@ -62,7 +62,7 @@ def sympy_to_scipy_sparse(m, **options):
raise ImportError
dtype = options.get('dtype', 'complex')
if isinstance(m, MatrixBase):
return sparse.csr_matrix(np.matrix(m.tolist(), dtype=dtype))
return sparse.csr_matrix(np.array(m.tolist(), dtype=dtype))
elif isinstance(m, Expr):
if m.is_Number or m.is_NumberSymbol or m == I:
return complex(m)
Expand Down Expand Up @@ -183,7 +183,7 @@ def _numpy_eye(n):
"""numpy version of complex eye."""
if not np:
raise ImportError
return np.matrix(np.eye(n, dtype='complex'))
return np.array(np.eye(n, dtype='complex'))


def _scipy_sparse_eye(n):
Expand Down
2 changes: 1 addition & 1 deletion sympy/physics/quantum/qubit.py
Expand Up @@ -209,7 +209,7 @@ def _represent_ZGate(self, basis, **options):
return Matrix(result)
elif _format == 'numpy':
import numpy as np
return np.matrix(result, dtype='complex').transpose()
return np.array(result, dtype='complex').transpose()
elif _format == 'scipy.sparse':
from scipy import sparse
return sparse.csr_matrix(result, dtype='complex').transpose()
Expand Down
23 changes: 16 additions & 7 deletions sympy/physics/quantum/represent.py
Expand Up @@ -139,6 +139,8 @@ def _represent_FooBasis(self, e, basis, **options)
"""

format = options.get('format', 'sympy')
if format == 'numpy':
import numpy as np
if isinstance(expr, QExpr) and not isinstance(expr, OuterProduct):
options['replace_none'] = False
temp_basis = get_basis(expr, **options)
Expand Down Expand Up @@ -181,20 +183,22 @@ def _represent_FooBasis(self, e, basis, **options)
from scipy.sparse.linalg import inv
exp = - exp
base = inv(base.tocsc()).tocsr()
if format == 'numpy':
return np.linalg.matrix_power(base, exp)
return base ** exp
elif isinstance(expr, TensorProduct):
new_args = [represent(arg, **options) for arg in expr.args]
return TensorProduct(*new_args)
elif isinstance(expr, Dagger):
return Dagger(represent(expr.args[0], **options))
elif isinstance(expr, Commutator):
A = represent(expr.args[0], **options)
B = represent(expr.args[1], **options)
return A*B - B*A
A = expr.args[0]
B = expr.args[1]
return represent(Mul(A, B) - Mul(B, A), **options)
elif isinstance(expr, AntiCommutator):
A = represent(expr.args[0], **options)
B = represent(expr.args[1], **options)
return A*B + B*A
A = expr.args[0]
B = expr.args[1]
return represent(Mul(A, B) + Mul(B, A), **options)
elif isinstance(expr, InnerProduct):
return represent(Mul(expr.bra, expr.ket), **options)
elif not isinstance(expr, (Mul, OuterProduct)):
Expand Down Expand Up @@ -228,7 +232,12 @@ def _represent_FooBasis(self, e, basis, **options)
elif isinstance(last_arg, KetBase) and isinstance(arg, BraBase):
options["unities"].append(options["index"])

result = represent(arg, **options)*result
next_arg = represent(arg, **options)
if format == 'numpy' and isinstance(next_arg, np.ndarray):
# Must use np.matmult to "matrix multiply" two np.ndarray
result = np.matmul(next_arg, result)
else:
result = next_arg*result
last_arg = arg

# All three matrix formats create 1 by 1 matrices when inner products of
Expand Down
2 changes: 1 addition & 1 deletion sympy/physics/quantum/tests/test_dagger.py
Expand Up @@ -62,7 +62,7 @@ def test_numpy_dagger():
if not np:
skip("numpy not installed.")

a = np.matrix([[1.0, 2.0j], [-1.0j, 2.0]])
a = np.array([[1.0, 2.0j], [-1.0j, 2.0]])
adag = a.copy().transpose().conjugate()
assert (Dagger(a) == adag).all()

Expand Down
2 changes: 1 addition & 1 deletion sympy/physics/quantum/tests/test_density.py
Expand Up @@ -174,7 +174,7 @@ def test_entropy():
#do this test only if 'numpy' is available on test machine
np_mat = represent(d, format='numpy')
ent = entropy(np_mat)
assert isinstance(np_mat, np.matrixlib.defmatrix.matrix)
assert isinstance(np_mat, np.ndarray)
assert ent.real == 0.69314718055994529
assert ent.imag == 0

Expand Down
10 changes: 5 additions & 5 deletions sympy/physics/quantum/tests/test_matrixutils.py
Expand Up @@ -29,7 +29,7 @@ def test_to_numpy():
if not np:
skip("numpy not installed.")

result = np.matrix([[1, 2], [3, 4]], dtype='complex')
result = np.array([[1, 2], [3, 4]], dtype='complex')
assert (to_numpy(m) == result).all()


Expand All @@ -49,8 +49,8 @@ def test_matrix_tensor_product():
vec = Matrix([1, 2, 3])

#test for Matrix known 4x4 matricies
numpyl1 = np.matrix(l1.tolist())
numpyl2 = np.matrix(l2.tolist())
numpyl1 = np.array(l1.tolist())
numpyl2 = np.array(l2.tolist())
numpy_product = np.kron(numpyl1, numpyl2)
args = [l1, l2]
sympy_product = matrix_tensor_product(*args)
Expand All @@ -61,7 +61,7 @@ def test_matrix_tensor_product():
assert numpy_product.tolist() == sympy_product.tolist()

#test for other known matrix of different dimensions
numpyl2 = np.matrix(l3.tolist())
numpyl2 = np.array(l3.tolist())
numpy_product = np.kron(numpyl1, numpyl2)
args = [l1, l3]
sympy_product = matrix_tensor_product(*args)
Expand All @@ -72,7 +72,7 @@ def test_matrix_tensor_product():
assert numpy_product.tolist() == sympy_product.tolist()

#test for non square matrix
numpyl2 = np.matrix(vec.tolist())
numpyl2 = np.array(vec.tolist())
numpy_product = np.kron(numpyl1, numpyl2)
args = [l1, vec]
sympy_product = matrix_tensor_product(*args)
Expand Down
14 changes: 7 additions & 7 deletions sympy/printing/tests/test_numpy.py
Expand Up @@ -88,9 +88,9 @@ def test_codegen_einsum():
cg = convert_matrix_to_array(M * N)
f = lambdify((M, N), cg, 'numpy')

ma = np.matrix([[1, 2], [3, 4]])
mb = np.matrix([[1,-2], [-1, 3]])
assert (f(ma, mb) == ma*mb).all()
ma = np.array([[1, 2], [3, 4]])
mb = np.array([[1,-2], [-1, 3]])
assert (f(ma, mb) == np.matmul(ma, mb)).all()


def test_codegen_extra():
Expand All @@ -101,10 +101,10 @@ def test_codegen_extra():
N = MatrixSymbol("N", 2, 2)
P = MatrixSymbol("P", 2, 2)
Q = MatrixSymbol("Q", 2, 2)
ma = np.matrix([[1, 2], [3, 4]])
mb = np.matrix([[1,-2], [-1, 3]])
mc = np.matrix([[2, 0], [1, 2]])
md = np.matrix([[1,-1], [4, 7]])
ma = np.array([[1, 2], [3, 4]])
mb = np.array([[1,-2], [-1, 3]])
mc = np.array([[2, 0], [1, 2]])
md = np.array([[1,-1], [4, 7]])

cg = ArrayTensorProduct(M, N)
f = lambdify((M, N), cg, 'numpy')
Expand Down

0 comments on commit 131caae

Please sign in to comment.