test_numpy.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. # This testfile tests SymPy <-> NumPy compatibility
  2. # Don't test any SymPy features here. Just pure interaction with NumPy.
  3. # Always write regular SymPy tests for anything, that can be tested in pure
  4. # Python (without numpy). Here we test everything, that a user may need when
  5. # using SymPy with NumPy
  6. from sympy.external.importtools import version_tuple
  7. from sympy.external import import_module
  8. numpy = import_module('numpy')
  9. if numpy:
  10. array, matrix, ndarray = numpy.array, numpy.matrix, numpy.ndarray
  11. else:
  12. #bin/test will not execute any tests now
  13. disabled = True
  14. from sympy.core.numbers import (Float, Integer, Rational)
  15. from sympy.core.symbol import (Symbol, symbols)
  16. from sympy.functions.elementary.trigonometric import sin
  17. from sympy.matrices.dense import (Matrix, list2numpy, matrix2numpy, symarray)
  18. from sympy.utilities.lambdify import lambdify
  19. import sympy
  20. import mpmath
  21. from sympy.abc import x, y, z
  22. from sympy.utilities.decorator import conserve_mpmath_dps
  23. from sympy.utilities.exceptions import ignore_warnings
  24. from sympy.testing.pytest import raises
  25. # first, systematically check, that all operations are implemented and don't
  26. # raise an exception
  27. def test_systematic_basic():
  28. def s(sympy_object, numpy_array):
  29. _ = [sympy_object + numpy_array,
  30. numpy_array + sympy_object,
  31. sympy_object - numpy_array,
  32. numpy_array - sympy_object,
  33. sympy_object * numpy_array,
  34. numpy_array * sympy_object,
  35. sympy_object / numpy_array,
  36. numpy_array / sympy_object,
  37. sympy_object ** numpy_array,
  38. numpy_array ** sympy_object]
  39. x = Symbol("x")
  40. y = Symbol("y")
  41. sympy_objs = [
  42. Rational(2, 3),
  43. Float("1.3"),
  44. x,
  45. y,
  46. pow(x, y)*y,
  47. Integer(5),
  48. Float(5.5),
  49. ]
  50. numpy_objs = [
  51. array([1]),
  52. array([3, 8, -1]),
  53. array([x, x**2, Rational(5)]),
  54. array([x/y*sin(y), 5, Rational(5)]),
  55. ]
  56. for x in sympy_objs:
  57. for y in numpy_objs:
  58. s(x, y)
  59. # now some random tests, that test particular problems and that also
  60. # check that the results of the operations are correct
  61. def test_basics():
  62. one = Rational(1)
  63. zero = Rational(0)
  64. assert array(1) == array(one)
  65. assert array([one]) == array([one])
  66. assert array([x]) == array([x])
  67. assert array(x) == array(Symbol("x"))
  68. assert array(one + x) == array(1 + x)
  69. X = array([one, zero, zero])
  70. assert (X == array([one, zero, zero])).all()
  71. assert (X == array([one, 0, 0])).all()
  72. def test_arrays():
  73. one = Rational(1)
  74. zero = Rational(0)
  75. X = array([one, zero, zero])
  76. Y = one*X
  77. X = array([Symbol("a") + Rational(1, 2)])
  78. Y = X + X
  79. assert Y == array([1 + 2*Symbol("a")])
  80. Y = Y + 1
  81. assert Y == array([2 + 2*Symbol("a")])
  82. Y = X - X
  83. assert Y == array([0])
  84. def test_conversion1():
  85. a = list2numpy([x**2, x])
  86. #looks like an array?
  87. assert isinstance(a, ndarray)
  88. assert a[0] == x**2
  89. assert a[1] == x
  90. assert len(a) == 2
  91. #yes, it's the array
  92. def test_conversion2():
  93. a = 2*list2numpy([x**2, x])
  94. b = list2numpy([2*x**2, 2*x])
  95. assert (a == b).all()
  96. one = Rational(1)
  97. zero = Rational(0)
  98. X = list2numpy([one, zero, zero])
  99. Y = one*X
  100. X = list2numpy([Symbol("a") + Rational(1, 2)])
  101. Y = X + X
  102. assert Y == array([1 + 2*Symbol("a")])
  103. Y = Y + 1
  104. assert Y == array([2 + 2*Symbol("a")])
  105. Y = X - X
  106. assert Y == array([0])
  107. def test_list2numpy():
  108. assert (array([x**2, x]) == list2numpy([x**2, x])).all()
  109. def test_Matrix1():
  110. m = Matrix([[x, x**2], [5, 2/x]])
  111. assert (array(m.subs(x, 2)) == array([[2, 4], [5, 1]])).all()
  112. m = Matrix([[sin(x), x**2], [5, 2/x]])
  113. assert (array(m.subs(x, 2)) == array([[sin(2), 4], [5, 1]])).all()
  114. def test_Matrix2():
  115. m = Matrix([[x, x**2], [5, 2/x]])
  116. with ignore_warnings(PendingDeprecationWarning):
  117. assert (matrix(m.subs(x, 2)) == matrix([[2, 4], [5, 1]])).all()
  118. m = Matrix([[sin(x), x**2], [5, 2/x]])
  119. with ignore_warnings(PendingDeprecationWarning):
  120. assert (matrix(m.subs(x, 2)) == matrix([[sin(2), 4], [5, 1]])).all()
  121. def test_Matrix3():
  122. a = array([[2, 4], [5, 1]])
  123. assert Matrix(a) == Matrix([[2, 4], [5, 1]])
  124. assert Matrix(a) != Matrix([[2, 4], [5, 2]])
  125. a = array([[sin(2), 4], [5, 1]])
  126. assert Matrix(a) == Matrix([[sin(2), 4], [5, 1]])
  127. assert Matrix(a) != Matrix([[sin(0), 4], [5, 1]])
  128. def test_Matrix4():
  129. with ignore_warnings(PendingDeprecationWarning):
  130. a = matrix([[2, 4], [5, 1]])
  131. assert Matrix(a) == Matrix([[2, 4], [5, 1]])
  132. assert Matrix(a) != Matrix([[2, 4], [5, 2]])
  133. with ignore_warnings(PendingDeprecationWarning):
  134. a = matrix([[sin(2), 4], [5, 1]])
  135. assert Matrix(a) == Matrix([[sin(2), 4], [5, 1]])
  136. assert Matrix(a) != Matrix([[sin(0), 4], [5, 1]])
  137. def test_Matrix_sum():
  138. M = Matrix([[1, 2, 3], [x, y, x], [2*y, -50, z*x]])
  139. with ignore_warnings(PendingDeprecationWarning):
  140. m = matrix([[2, 3, 4], [x, 5, 6], [x, y, z**2]])
  141. assert M + m == Matrix([[3, 5, 7], [2*x, y + 5, x + 6], [2*y + x, y - 50, z*x + z**2]])
  142. assert m + M == Matrix([[3, 5, 7], [2*x, y + 5, x + 6], [2*y + x, y - 50, z*x + z**2]])
  143. assert M + m == M.add(m)
  144. def test_Matrix_mul():
  145. M = Matrix([[1, 2, 3], [x, y, x]])
  146. with ignore_warnings(PendingDeprecationWarning):
  147. m = matrix([[2, 4], [x, 6], [x, z**2]])
  148. assert M*m == Matrix([
  149. [ 2 + 5*x, 16 + 3*z**2],
  150. [2*x + x*y + x**2, 4*x + 6*y + x*z**2],
  151. ])
  152. assert m*M == Matrix([
  153. [ 2 + 4*x, 4 + 4*y, 6 + 4*x],
  154. [ 7*x, 2*x + 6*y, 9*x],
  155. [x + x*z**2, 2*x + y*z**2, 3*x + x*z**2],
  156. ])
  157. a = array([2])
  158. assert a[0] * M == 2 * M
  159. assert M * a[0] == 2 * M
  160. def test_Matrix_array():
  161. class matarray:
  162. def __array__(self, dtype=object, copy=None):
  163. if copy is not None and not copy:
  164. raise TypeError("Cannot implement copy=False when converting Matrix to ndarray")
  165. from numpy import array
  166. return array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
  167. matarr = matarray()
  168. assert Matrix(matarr) == Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
  169. def test_matrix2numpy():
  170. a = matrix2numpy(Matrix([[1, x**2], [3*sin(x), 0]]))
  171. assert isinstance(a, ndarray)
  172. assert a.shape == (2, 2)
  173. assert a[0, 0] == 1
  174. assert a[0, 1] == x**2
  175. assert a[1, 0] == 3*sin(x)
  176. assert a[1, 1] == 0
  177. def test_matrix2numpy_conversion():
  178. a = Matrix([[1, 2, sin(x)], [x**2, x, Rational(1, 2)]])
  179. b = array([[1, 2, sin(x)], [x**2, x, Rational(1, 2)]])
  180. assert (matrix2numpy(a) == b).all()
  181. assert matrix2numpy(a).dtype == numpy.dtype('object')
  182. c = matrix2numpy(Matrix([[1, 2], [10, 20]]), dtype='int8')
  183. d = matrix2numpy(Matrix([[1, 2], [10, 20]]), dtype='float64')
  184. assert c.dtype == numpy.dtype('int8')
  185. assert d.dtype == numpy.dtype('float64')
  186. def test_issue_3728():
  187. assert (Rational(1, 2)*array([2*x, 0]) == array([x, 0])).all()
  188. assert (Rational(1, 2) + array(
  189. [2*x, 0]) == array([2*x + Rational(1, 2), Rational(1, 2)])).all()
  190. assert (Float("0.5")*array([2*x, 0]) == array([Float("1.0")*x, 0])).all()
  191. assert (Float("0.5") + array(
  192. [2*x, 0]) == array([2*x + Float("0.5"), Float("0.5")])).all()
  193. @conserve_mpmath_dps
  194. def test_lambdify():
  195. mpmath.mp.dps = 16
  196. sin02 = mpmath.mpf("0.198669330795061215459412627")
  197. f = lambdify(x, sin(x), "numpy")
  198. prec = 1e-15
  199. assert -prec < f(0.2) - sin02 < prec
  200. # if this succeeds, it can't be a numpy function
  201. if version_tuple(numpy.__version__) >= version_tuple('1.17'):
  202. with raises(TypeError):
  203. f(x)
  204. else:
  205. with raises(AttributeError):
  206. f(x)
  207. def test_lambdify_matrix():
  208. f = lambdify(x, Matrix([[x, 2*x], [1, 2]]), [{'ImmutableMatrix': numpy.array}, "numpy"])
  209. assert (f(1) == array([[1, 2], [1, 2]])).all()
  210. def test_lambdify_matrix_multi_input():
  211. M = sympy.Matrix([[x**2, x*y, x*z],
  212. [y*x, y**2, y*z],
  213. [z*x, z*y, z**2]])
  214. f = lambdify((x, y, z), M, [{'ImmutableMatrix': numpy.array}, "numpy"])
  215. xh, yh, zh = 1.0, 2.0, 3.0
  216. expected = array([[xh**2, xh*yh, xh*zh],
  217. [yh*xh, yh**2, yh*zh],
  218. [zh*xh, zh*yh, zh**2]])
  219. actual = f(xh, yh, zh)
  220. assert numpy.allclose(actual, expected)
  221. def test_lambdify_matrix_vec_input():
  222. X = sympy.DeferredVector('X')
  223. M = Matrix([
  224. [X[0]**2, X[0]*X[1], X[0]*X[2]],
  225. [X[1]*X[0], X[1]**2, X[1]*X[2]],
  226. [X[2]*X[0], X[2]*X[1], X[2]**2]])
  227. f = lambdify(X, M, [{'ImmutableMatrix': numpy.array}, "numpy"])
  228. Xh = array([1.0, 2.0, 3.0])
  229. expected = array([[Xh[0]**2, Xh[0]*Xh[1], Xh[0]*Xh[2]],
  230. [Xh[1]*Xh[0], Xh[1]**2, Xh[1]*Xh[2]],
  231. [Xh[2]*Xh[0], Xh[2]*Xh[1], Xh[2]**2]])
  232. actual = f(Xh)
  233. assert numpy.allclose(actual, expected)
  234. def test_lambdify_transl():
  235. from sympy.utilities.lambdify import NUMPY_TRANSLATIONS
  236. for sym, mat in NUMPY_TRANSLATIONS.items():
  237. assert sym in sympy.__dict__
  238. assert mat in numpy.__dict__
  239. def test_symarray():
  240. """Test creation of numpy arrays of SymPy symbols."""
  241. import numpy as np
  242. import numpy.testing as npt
  243. syms = symbols('_0,_1,_2')
  244. s1 = symarray("", 3)
  245. s2 = symarray("", 3)
  246. npt.assert_array_equal(s1, np.array(syms, dtype=object))
  247. assert s1[0] == s2[0]
  248. a = symarray('a', 3)
  249. b = symarray('b', 3)
  250. assert not(a[0] == b[0])
  251. asyms = symbols('a_0,a_1,a_2')
  252. npt.assert_array_equal(a, np.array(asyms, dtype=object))
  253. # Multidimensional checks
  254. a2d = symarray('a', (2, 3))
  255. assert a2d.shape == (2, 3)
  256. a00, a12 = symbols('a_0_0,a_1_2')
  257. assert a2d[0, 0] == a00
  258. assert a2d[1, 2] == a12
  259. a3d = symarray('a', (2, 3, 2))
  260. assert a3d.shape == (2, 3, 2)
  261. a000, a120, a121 = symbols('a_0_0_0,a_1_2_0,a_1_2_1')
  262. assert a3d[0, 0, 0] == a000
  263. assert a3d[1, 2, 0] == a120
  264. assert a3d[1, 2, 1] == a121
  265. def test_vectorize():
  266. assert (numpy.vectorize(
  267. sin)([1, 2, 3]) == numpy.array([sin(1), sin(2), sin(3)])).all()