test_numpy.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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):
  163. from numpy import array
  164. return array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
  165. matarr = matarray()
  166. assert Matrix(matarr) == Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
  167. def test_matrix2numpy():
  168. a = matrix2numpy(Matrix([[1, x**2], [3*sin(x), 0]]))
  169. assert isinstance(a, ndarray)
  170. assert a.shape == (2, 2)
  171. assert a[0, 0] == 1
  172. assert a[0, 1] == x**2
  173. assert a[1, 0] == 3*sin(x)
  174. assert a[1, 1] == 0
  175. def test_matrix2numpy_conversion():
  176. a = Matrix([[1, 2, sin(x)], [x**2, x, Rational(1, 2)]])
  177. b = array([[1, 2, sin(x)], [x**2, x, Rational(1, 2)]])
  178. assert (matrix2numpy(a) == b).all()
  179. assert matrix2numpy(a).dtype == numpy.dtype('object')
  180. c = matrix2numpy(Matrix([[1, 2], [10, 20]]), dtype='int8')
  181. d = matrix2numpy(Matrix([[1, 2], [10, 20]]), dtype='float64')
  182. assert c.dtype == numpy.dtype('int8')
  183. assert d.dtype == numpy.dtype('float64')
  184. def test_issue_3728():
  185. assert (Rational(1, 2)*array([2*x, 0]) == array([x, 0])).all()
  186. assert (Rational(1, 2) + array(
  187. [2*x, 0]) == array([2*x + Rational(1, 2), Rational(1, 2)])).all()
  188. assert (Float("0.5")*array([2*x, 0]) == array([Float("1.0")*x, 0])).all()
  189. assert (Float("0.5") + array(
  190. [2*x, 0]) == array([2*x + Float("0.5"), Float("0.5")])).all()
  191. @conserve_mpmath_dps
  192. def test_lambdify():
  193. mpmath.mp.dps = 16
  194. sin02 = mpmath.mpf("0.198669330795061215459412627")
  195. f = lambdify(x, sin(x), "numpy")
  196. prec = 1e-15
  197. assert -prec < f(0.2) - sin02 < prec
  198. # if this succeeds, it can't be a numpy function
  199. if version_tuple(numpy.__version__) >= version_tuple('1.17'):
  200. with raises(TypeError):
  201. f(x)
  202. else:
  203. with raises(AttributeError):
  204. f(x)
  205. def test_lambdify_matrix():
  206. f = lambdify(x, Matrix([[x, 2*x], [1, 2]]), [{'ImmutableMatrix': numpy.array}, "numpy"])
  207. assert (f(1) == array([[1, 2], [1, 2]])).all()
  208. def test_lambdify_matrix_multi_input():
  209. M = sympy.Matrix([[x**2, x*y, x*z],
  210. [y*x, y**2, y*z],
  211. [z*x, z*y, z**2]])
  212. f = lambdify((x, y, z), M, [{'ImmutableMatrix': numpy.array}, "numpy"])
  213. xh, yh, zh = 1.0, 2.0, 3.0
  214. expected = array([[xh**2, xh*yh, xh*zh],
  215. [yh*xh, yh**2, yh*zh],
  216. [zh*xh, zh*yh, zh**2]])
  217. actual = f(xh, yh, zh)
  218. assert numpy.allclose(actual, expected)
  219. def test_lambdify_matrix_vec_input():
  220. X = sympy.DeferredVector('X')
  221. M = Matrix([
  222. [X[0]**2, X[0]*X[1], X[0]*X[2]],
  223. [X[1]*X[0], X[1]**2, X[1]*X[2]],
  224. [X[2]*X[0], X[2]*X[1], X[2]**2]])
  225. f = lambdify(X, M, [{'ImmutableMatrix': numpy.array}, "numpy"])
  226. Xh = array([1.0, 2.0, 3.0])
  227. expected = array([[Xh[0]**2, Xh[0]*Xh[1], Xh[0]*Xh[2]],
  228. [Xh[1]*Xh[0], Xh[1]**2, Xh[1]*Xh[2]],
  229. [Xh[2]*Xh[0], Xh[2]*Xh[1], Xh[2]**2]])
  230. actual = f(Xh)
  231. assert numpy.allclose(actual, expected)
  232. def test_lambdify_transl():
  233. from sympy.utilities.lambdify import NUMPY_TRANSLATIONS
  234. for sym, mat in NUMPY_TRANSLATIONS.items():
  235. assert sym in sympy.__dict__
  236. assert mat in numpy.__dict__
  237. def test_symarray():
  238. """Test creation of numpy arrays of SymPy symbols."""
  239. import numpy as np
  240. import numpy.testing as npt
  241. syms = symbols('_0,_1,_2')
  242. s1 = symarray("", 3)
  243. s2 = symarray("", 3)
  244. npt.assert_array_equal(s1, np.array(syms, dtype=object))
  245. assert s1[0] == s2[0]
  246. a = symarray('a', 3)
  247. b = symarray('b', 3)
  248. assert not(a[0] == b[0])
  249. asyms = symbols('a_0,a_1,a_2')
  250. npt.assert_array_equal(a, np.array(asyms, dtype=object))
  251. # Multidimensional checks
  252. a2d = symarray('a', (2, 3))
  253. assert a2d.shape == (2, 3)
  254. a00, a12 = symbols('a_0_0,a_1_2')
  255. assert a2d[0, 0] == a00
  256. assert a2d[1, 2] == a12
  257. a3d = symarray('a', (2, 3, 2))
  258. assert a3d.shape == (2, 3, 2)
  259. a000, a120, a121 = symbols('a_0_0_0,a_1_2_0,a_1_2_1')
  260. assert a3d[0, 0, 0] == a000
  261. assert a3d[1, 2, 0] == a120
  262. assert a3d[1, 2, 1] == a121
  263. def test_vectorize():
  264. assert (numpy.vectorize(
  265. sin)([1, 2, 3]) == numpy.array([sin(1), sin(2), sin(3)])).all()