test_scalarmath.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790
  1. import contextlib
  2. import sys
  3. import warnings
  4. import itertools
  5. import operator
  6. import platform
  7. import pytest
  8. from hypothesis import given, settings, Verbosity, assume
  9. from hypothesis.strategies import sampled_from
  10. import numpy as np
  11. from numpy.testing import (
  12. assert_, assert_equal, assert_raises, assert_almost_equal,
  13. assert_array_equal, IS_PYPY, suppress_warnings, _gen_alignment_data,
  14. assert_warns, assert_raises_regex,
  15. )
  16. types = [np.bool_, np.byte, np.ubyte, np.short, np.ushort, np.intc, np.uintc,
  17. np.int_, np.uint, np.longlong, np.ulonglong,
  18. np.single, np.double, np.longdouble, np.csingle,
  19. np.cdouble, np.clongdouble]
  20. floating_types = np.floating.__subclasses__()
  21. complex_floating_types = np.complexfloating.__subclasses__()
  22. # This compares scalarmath against ufuncs.
  23. class TestTypes:
  24. def test_types(self):
  25. for atype in types:
  26. a = atype(1)
  27. assert_(a == 1, "error with %r: got %r" % (atype, a))
  28. def test_type_add(self):
  29. # list of types
  30. for k, atype in enumerate(types):
  31. a_scalar = atype(3)
  32. a_array = np.array([3], dtype=atype)
  33. for l, btype in enumerate(types):
  34. b_scalar = btype(1)
  35. b_array = np.array([1], dtype=btype)
  36. c_scalar = a_scalar + b_scalar
  37. c_array = a_array + b_array
  38. # It was comparing the type numbers, but the new ufunc
  39. # function-finding mechanism finds the lowest function
  40. # to which both inputs can be cast - which produces 'l'
  41. # when you do 'q' + 'b'. The old function finding mechanism
  42. # skipped ahead based on the first argument, but that
  43. # does not produce properly symmetric results...
  44. assert_equal(c_scalar.dtype, c_array.dtype,
  45. "error with types (%d/'%c' + %d/'%c')" %
  46. (k, np.dtype(atype).char, l, np.dtype(btype).char))
  47. def test_type_create(self):
  48. for k, atype in enumerate(types):
  49. a = np.array([1, 2, 3], atype)
  50. b = atype([1, 2, 3])
  51. assert_equal(a, b)
  52. def test_leak(self):
  53. # test leak of scalar objects
  54. # a leak would show up in valgrind as still-reachable of ~2.6MB
  55. for i in range(200000):
  56. np.add(1, 1)
  57. class TestBaseMath:
  58. def test_blocked(self):
  59. # test alignments offsets for simd instructions
  60. # alignments for vz + 2 * (vs - 1) + 1
  61. for dt, sz in [(np.float32, 11), (np.float64, 7), (np.int32, 11)]:
  62. for out, inp1, inp2, msg in _gen_alignment_data(dtype=dt,
  63. type='binary',
  64. max_size=sz):
  65. exp1 = np.ones_like(inp1)
  66. inp1[...] = np.ones_like(inp1)
  67. inp2[...] = np.zeros_like(inp2)
  68. assert_almost_equal(np.add(inp1, inp2), exp1, err_msg=msg)
  69. assert_almost_equal(np.add(inp1, 2), exp1 + 2, err_msg=msg)
  70. assert_almost_equal(np.add(1, inp2), exp1, err_msg=msg)
  71. np.add(inp1, inp2, out=out)
  72. assert_almost_equal(out, exp1, err_msg=msg)
  73. inp2[...] += np.arange(inp2.size, dtype=dt) + 1
  74. assert_almost_equal(np.square(inp2),
  75. np.multiply(inp2, inp2), err_msg=msg)
  76. # skip true divide for ints
  77. if dt != np.int32:
  78. assert_almost_equal(np.reciprocal(inp2),
  79. np.divide(1, inp2), err_msg=msg)
  80. inp1[...] = np.ones_like(inp1)
  81. np.add(inp1, 2, out=out)
  82. assert_almost_equal(out, exp1 + 2, err_msg=msg)
  83. inp2[...] = np.ones_like(inp2)
  84. np.add(2, inp2, out=out)
  85. assert_almost_equal(out, exp1 + 2, err_msg=msg)
  86. def test_lower_align(self):
  87. # check data that is not aligned to element size
  88. # i.e doubles are aligned to 4 bytes on i386
  89. d = np.zeros(23 * 8, dtype=np.int8)[4:-4].view(np.float64)
  90. o = np.zeros(23 * 8, dtype=np.int8)[4:-4].view(np.float64)
  91. assert_almost_equal(d + d, d * 2)
  92. np.add(d, d, out=o)
  93. np.add(np.ones_like(d), d, out=o)
  94. np.add(d, np.ones_like(d), out=o)
  95. np.add(np.ones_like(d), d)
  96. np.add(d, np.ones_like(d))
  97. class TestPower:
  98. def test_small_types(self):
  99. for t in [np.int8, np.int16, np.float16]:
  100. a = t(3)
  101. b = a ** 4
  102. assert_(b == 81, "error with %r: got %r" % (t, b))
  103. def test_large_types(self):
  104. for t in [np.int32, np.int64, np.float32, np.float64, np.longdouble]:
  105. a = t(51)
  106. b = a ** 4
  107. msg = "error with %r: got %r" % (t, b)
  108. if np.issubdtype(t, np.integer):
  109. assert_(b == 6765201, msg)
  110. else:
  111. assert_almost_equal(b, 6765201, err_msg=msg)
  112. def test_integers_to_negative_integer_power(self):
  113. # Note that the combination of uint64 with a signed integer
  114. # has common type np.float64. The other combinations should all
  115. # raise a ValueError for integer ** negative integer.
  116. exp = [np.array(-1, dt)[()] for dt in 'bhilq']
  117. # 1 ** -1 possible special case
  118. base = [np.array(1, dt)[()] for dt in 'bhilqBHILQ']
  119. for i1, i2 in itertools.product(base, exp):
  120. if i1.dtype != np.uint64:
  121. assert_raises(ValueError, operator.pow, i1, i2)
  122. else:
  123. res = operator.pow(i1, i2)
  124. assert_(res.dtype.type is np.float64)
  125. assert_almost_equal(res, 1.)
  126. # -1 ** -1 possible special case
  127. base = [np.array(-1, dt)[()] for dt in 'bhilq']
  128. for i1, i2 in itertools.product(base, exp):
  129. if i1.dtype != np.uint64:
  130. assert_raises(ValueError, operator.pow, i1, i2)
  131. else:
  132. res = operator.pow(i1, i2)
  133. assert_(res.dtype.type is np.float64)
  134. assert_almost_equal(res, -1.)
  135. # 2 ** -1 perhaps generic
  136. base = [np.array(2, dt)[()] for dt in 'bhilqBHILQ']
  137. for i1, i2 in itertools.product(base, exp):
  138. if i1.dtype != np.uint64:
  139. assert_raises(ValueError, operator.pow, i1, i2)
  140. else:
  141. res = operator.pow(i1, i2)
  142. assert_(res.dtype.type is np.float64)
  143. assert_almost_equal(res, .5)
  144. def test_mixed_types(self):
  145. typelist = [np.int8, np.int16, np.float16,
  146. np.float32, np.float64, np.int8,
  147. np.int16, np.int32, np.int64]
  148. for t1 in typelist:
  149. for t2 in typelist:
  150. a = t1(3)
  151. b = t2(2)
  152. result = a**b
  153. msg = ("error with %r and %r:"
  154. "got %r, expected %r") % (t1, t2, result, 9)
  155. if np.issubdtype(np.dtype(result), np.integer):
  156. assert_(result == 9, msg)
  157. else:
  158. assert_almost_equal(result, 9, err_msg=msg)
  159. def test_modular_power(self):
  160. # modular power is not implemented, so ensure it errors
  161. a = 5
  162. b = 4
  163. c = 10
  164. expected = pow(a, b, c) # noqa: F841
  165. for t in (np.int32, np.float32, np.complex64):
  166. # note that 3-operand power only dispatches on the first argument
  167. assert_raises(TypeError, operator.pow, t(a), b, c)
  168. assert_raises(TypeError, operator.pow, np.array(t(a)), b, c)
  169. def floordiv_and_mod(x, y):
  170. return (x // y, x % y)
  171. def _signs(dt):
  172. if dt in np.typecodes['UnsignedInteger']:
  173. return (+1,)
  174. else:
  175. return (+1, -1)
  176. class TestModulus:
  177. def test_modulus_basic(self):
  178. dt = np.typecodes['AllInteger'] + np.typecodes['Float']
  179. for op in [floordiv_and_mod, divmod]:
  180. for dt1, dt2 in itertools.product(dt, dt):
  181. for sg1, sg2 in itertools.product(_signs(dt1), _signs(dt2)):
  182. fmt = 'op: %s, dt1: %s, dt2: %s, sg1: %s, sg2: %s'
  183. msg = fmt % (op.__name__, dt1, dt2, sg1, sg2)
  184. a = np.array(sg1*71, dtype=dt1)[()]
  185. b = np.array(sg2*19, dtype=dt2)[()]
  186. div, rem = op(a, b)
  187. assert_equal(div*b + rem, a, err_msg=msg)
  188. if sg2 == -1:
  189. assert_(b < rem <= 0, msg)
  190. else:
  191. assert_(b > rem >= 0, msg)
  192. def test_float_modulus_exact(self):
  193. # test that float results are exact for small integers. This also
  194. # holds for the same integers scaled by powers of two.
  195. nlst = list(range(-127, 0))
  196. plst = list(range(1, 128))
  197. dividend = nlst + [0] + plst
  198. divisor = nlst + plst
  199. arg = list(itertools.product(dividend, divisor))
  200. tgt = list(divmod(*t) for t in arg)
  201. a, b = np.array(arg, dtype=int).T
  202. # convert exact integer results from Python to float so that
  203. # signed zero can be used, it is checked.
  204. tgtdiv, tgtrem = np.array(tgt, dtype=float).T
  205. tgtdiv = np.where((tgtdiv == 0.0) & ((b < 0) ^ (a < 0)), -0.0, tgtdiv)
  206. tgtrem = np.where((tgtrem == 0.0) & (b < 0), -0.0, tgtrem)
  207. for op in [floordiv_and_mod, divmod]:
  208. for dt in np.typecodes['Float']:
  209. msg = 'op: %s, dtype: %s' % (op.__name__, dt)
  210. fa = a.astype(dt)
  211. fb = b.astype(dt)
  212. # use list comprehension so a_ and b_ are scalars
  213. div, rem = zip(*[op(a_, b_) for a_, b_ in zip(fa, fb)])
  214. assert_equal(div, tgtdiv, err_msg=msg)
  215. assert_equal(rem, tgtrem, err_msg=msg)
  216. def test_float_modulus_roundoff(self):
  217. # gh-6127
  218. dt = np.typecodes['Float']
  219. for op in [floordiv_and_mod, divmod]:
  220. for dt1, dt2 in itertools.product(dt, dt):
  221. for sg1, sg2 in itertools.product((+1, -1), (+1, -1)):
  222. fmt = 'op: %s, dt1: %s, dt2: %s, sg1: %s, sg2: %s'
  223. msg = fmt % (op.__name__, dt1, dt2, sg1, sg2)
  224. a = np.array(sg1*78*6e-8, dtype=dt1)[()]
  225. b = np.array(sg2*6e-8, dtype=dt2)[()]
  226. div, rem = op(a, b)
  227. # Equal assertion should hold when fmod is used
  228. assert_equal(div*b + rem, a, err_msg=msg)
  229. if sg2 == -1:
  230. assert_(b < rem <= 0, msg)
  231. else:
  232. assert_(b > rem >= 0, msg)
  233. def test_float_modulus_corner_cases(self):
  234. # Check remainder magnitude.
  235. for dt in np.typecodes['Float']:
  236. b = np.array(1.0, dtype=dt)
  237. a = np.nextafter(np.array(0.0, dtype=dt), -b)
  238. rem = operator.mod(a, b)
  239. assert_(rem <= b, 'dt: %s' % dt)
  240. rem = operator.mod(-a, -b)
  241. assert_(rem >= -b, 'dt: %s' % dt)
  242. # Check nans, inf
  243. with suppress_warnings() as sup:
  244. sup.filter(RuntimeWarning, "invalid value encountered in remainder")
  245. sup.filter(RuntimeWarning, "divide by zero encountered in remainder")
  246. sup.filter(RuntimeWarning, "divide by zero encountered in floor_divide")
  247. sup.filter(RuntimeWarning, "divide by zero encountered in divmod")
  248. sup.filter(RuntimeWarning, "invalid value encountered in divmod")
  249. for dt in np.typecodes['Float']:
  250. fone = np.array(1.0, dtype=dt)
  251. fzer = np.array(0.0, dtype=dt)
  252. finf = np.array(np.inf, dtype=dt)
  253. fnan = np.array(np.nan, dtype=dt)
  254. rem = operator.mod(fone, fzer)
  255. assert_(np.isnan(rem), 'dt: %s' % dt)
  256. # MSVC 2008 returns NaN here, so disable the check.
  257. #rem = operator.mod(fone, finf)
  258. #assert_(rem == fone, 'dt: %s' % dt)
  259. rem = operator.mod(fone, fnan)
  260. assert_(np.isnan(rem), 'dt: %s' % dt)
  261. rem = operator.mod(finf, fone)
  262. assert_(np.isnan(rem), 'dt: %s' % dt)
  263. for op in [floordiv_and_mod, divmod]:
  264. div, mod = op(fone, fzer)
  265. assert_(np.isinf(div)) and assert_(np.isnan(mod))
  266. def test_inplace_floordiv_handling(self):
  267. # issue gh-12927
  268. # this only applies to in-place floordiv //=, because the output type
  269. # promotes to float which does not fit
  270. a = np.array([1, 2], np.int64)
  271. b = np.array([1, 2], np.uint64)
  272. pattern = 'could not be coerced to provided output parameter'
  273. with assert_raises_regex(TypeError, pattern):
  274. a //= b
  275. class TestComplexDivision:
  276. def test_zero_division(self):
  277. with np.errstate(all="ignore"):
  278. for t in [np.complex64, np.complex128]:
  279. a = t(0.0)
  280. b = t(1.0)
  281. assert_(np.isinf(b/a))
  282. b = t(complex(np.inf, np.inf))
  283. assert_(np.isinf(b/a))
  284. b = t(complex(np.inf, np.nan))
  285. assert_(np.isinf(b/a))
  286. b = t(complex(np.nan, np.inf))
  287. assert_(np.isinf(b/a))
  288. b = t(complex(np.nan, np.nan))
  289. assert_(np.isnan(b/a))
  290. b = t(0.)
  291. assert_(np.isnan(b/a))
  292. def test_signed_zeros(self):
  293. with np.errstate(all="ignore"):
  294. for t in [np.complex64, np.complex128]:
  295. # tupled (numerator, denominator, expected)
  296. # for testing as expected == numerator/denominator
  297. data = (
  298. (( 0.0,-1.0), ( 0.0, 1.0), (-1.0,-0.0)),
  299. (( 0.0,-1.0), ( 0.0,-1.0), ( 1.0,-0.0)),
  300. (( 0.0,-1.0), (-0.0,-1.0), ( 1.0, 0.0)),
  301. (( 0.0,-1.0), (-0.0, 1.0), (-1.0, 0.0)),
  302. (( 0.0, 1.0), ( 0.0,-1.0), (-1.0, 0.0)),
  303. (( 0.0,-1.0), ( 0.0,-1.0), ( 1.0,-0.0)),
  304. ((-0.0,-1.0), ( 0.0,-1.0), ( 1.0,-0.0)),
  305. ((-0.0, 1.0), ( 0.0,-1.0), (-1.0,-0.0))
  306. )
  307. for cases in data:
  308. n = cases[0]
  309. d = cases[1]
  310. ex = cases[2]
  311. result = t(complex(n[0], n[1])) / t(complex(d[0], d[1]))
  312. # check real and imag parts separately to avoid comparison
  313. # in array context, which does not account for signed zeros
  314. assert_equal(result.real, ex[0])
  315. assert_equal(result.imag, ex[1])
  316. def test_branches(self):
  317. with np.errstate(all="ignore"):
  318. for t in [np.complex64, np.complex128]:
  319. # tupled (numerator, denominator, expected)
  320. # for testing as expected == numerator/denominator
  321. data = list()
  322. # trigger branch: real(fabs(denom)) > imag(fabs(denom))
  323. # followed by else condition as neither are == 0
  324. data.append((( 2.0, 1.0), ( 2.0, 1.0), (1.0, 0.0)))
  325. # trigger branch: real(fabs(denom)) > imag(fabs(denom))
  326. # followed by if condition as both are == 0
  327. # is performed in test_zero_division(), so this is skipped
  328. # trigger else if branch: real(fabs(denom)) < imag(fabs(denom))
  329. data.append((( 1.0, 2.0), ( 1.0, 2.0), (1.0, 0.0)))
  330. for cases in data:
  331. n = cases[0]
  332. d = cases[1]
  333. ex = cases[2]
  334. result = t(complex(n[0], n[1])) / t(complex(d[0], d[1]))
  335. # check real and imag parts separately to avoid comparison
  336. # in array context, which does not account for signed zeros
  337. assert_equal(result.real, ex[0])
  338. assert_equal(result.imag, ex[1])
  339. class TestConversion:
  340. def test_int_from_long(self):
  341. l = [1e6, 1e12, 1e18, -1e6, -1e12, -1e18]
  342. li = [10**6, 10**12, 10**18, -10**6, -10**12, -10**18]
  343. for T in [None, np.float64, np.int64]:
  344. a = np.array(l, dtype=T)
  345. assert_equal([int(_m) for _m in a], li)
  346. a = np.array(l[:3], dtype=np.uint64)
  347. assert_equal([int(_m) for _m in a], li[:3])
  348. def test_iinfo_long_values(self):
  349. for code in 'bBhH':
  350. res = np.array(np.iinfo(code).max + 1, dtype=code)
  351. tgt = np.iinfo(code).min
  352. assert_(res == tgt)
  353. for code in np.typecodes['AllInteger']:
  354. res = np.array(np.iinfo(code).max, dtype=code)
  355. tgt = np.iinfo(code).max
  356. assert_(res == tgt)
  357. for code in np.typecodes['AllInteger']:
  358. res = np.typeDict[code](np.iinfo(code).max)
  359. tgt = np.iinfo(code).max
  360. assert_(res == tgt)
  361. def test_int_raise_behaviour(self):
  362. def overflow_error_func(dtype):
  363. np.typeDict[dtype](np.iinfo(dtype).max + 1)
  364. for code in 'lLqQ':
  365. assert_raises(OverflowError, overflow_error_func, code)
  366. def test_int_from_infinite_longdouble(self):
  367. # gh-627
  368. x = np.longdouble(np.inf)
  369. assert_raises(OverflowError, int, x)
  370. with suppress_warnings() as sup:
  371. sup.record(np.ComplexWarning)
  372. x = np.clongdouble(np.inf)
  373. assert_raises(OverflowError, int, x)
  374. assert_equal(len(sup.log), 1)
  375. @pytest.mark.skipif(not IS_PYPY, reason="Test is PyPy only (gh-9972)")
  376. def test_int_from_infinite_longdouble___int__(self):
  377. x = np.longdouble(np.inf)
  378. assert_raises(OverflowError, x.__int__)
  379. with suppress_warnings() as sup:
  380. sup.record(np.ComplexWarning)
  381. x = np.clongdouble(np.inf)
  382. assert_raises(OverflowError, x.__int__)
  383. assert_equal(len(sup.log), 1)
  384. @pytest.mark.skipif(np.finfo(np.double) == np.finfo(np.longdouble),
  385. reason="long double is same as double")
  386. @pytest.mark.skipif(platform.machine().startswith("ppc"),
  387. reason="IBM double double")
  388. def test_int_from_huge_longdouble(self):
  389. # Produce a longdouble that would overflow a double,
  390. # use exponent that avoids bug in Darwin pow function.
  391. exp = np.finfo(np.double).maxexp - 1
  392. huge_ld = 2 * 1234 * np.longdouble(2) ** exp
  393. huge_i = 2 * 1234 * 2 ** exp
  394. assert_(huge_ld != np.inf)
  395. assert_equal(int(huge_ld), huge_i)
  396. def test_int_from_longdouble(self):
  397. x = np.longdouble(1.5)
  398. assert_equal(int(x), 1)
  399. x = np.longdouble(-10.5)
  400. assert_equal(int(x), -10)
  401. def test_numpy_scalar_relational_operators(self):
  402. # All integer
  403. for dt1 in np.typecodes['AllInteger']:
  404. assert_(1 > np.array(0, dtype=dt1)[()], "type %s failed" % (dt1,))
  405. assert_(not 1 < np.array(0, dtype=dt1)[()], "type %s failed" % (dt1,))
  406. for dt2 in np.typecodes['AllInteger']:
  407. assert_(np.array(1, dtype=dt1)[()] > np.array(0, dtype=dt2)[()],
  408. "type %s and %s failed" % (dt1, dt2))
  409. assert_(not np.array(1, dtype=dt1)[()] < np.array(0, dtype=dt2)[()],
  410. "type %s and %s failed" % (dt1, dt2))
  411. #Unsigned integers
  412. for dt1 in 'BHILQP':
  413. assert_(-1 < np.array(1, dtype=dt1)[()], "type %s failed" % (dt1,))
  414. assert_(not -1 > np.array(1, dtype=dt1)[()], "type %s failed" % (dt1,))
  415. assert_(-1 != np.array(1, dtype=dt1)[()], "type %s failed" % (dt1,))
  416. #unsigned vs signed
  417. for dt2 in 'bhilqp':
  418. assert_(np.array(1, dtype=dt1)[()] > np.array(-1, dtype=dt2)[()],
  419. "type %s and %s failed" % (dt1, dt2))
  420. assert_(not np.array(1, dtype=dt1)[()] < np.array(-1, dtype=dt2)[()],
  421. "type %s and %s failed" % (dt1, dt2))
  422. assert_(np.array(1, dtype=dt1)[()] != np.array(-1, dtype=dt2)[()],
  423. "type %s and %s failed" % (dt1, dt2))
  424. #Signed integers and floats
  425. for dt1 in 'bhlqp' + np.typecodes['Float']:
  426. assert_(1 > np.array(-1, dtype=dt1)[()], "type %s failed" % (dt1,))
  427. assert_(not 1 < np.array(-1, dtype=dt1)[()], "type %s failed" % (dt1,))
  428. assert_(-1 == np.array(-1, dtype=dt1)[()], "type %s failed" % (dt1,))
  429. for dt2 in 'bhlqp' + np.typecodes['Float']:
  430. assert_(np.array(1, dtype=dt1)[()] > np.array(-1, dtype=dt2)[()],
  431. "type %s and %s failed" % (dt1, dt2))
  432. assert_(not np.array(1, dtype=dt1)[()] < np.array(-1, dtype=dt2)[()],
  433. "type %s and %s failed" % (dt1, dt2))
  434. assert_(np.array(-1, dtype=dt1)[()] == np.array(-1, dtype=dt2)[()],
  435. "type %s and %s failed" % (dt1, dt2))
  436. def test_scalar_comparison_to_none(self):
  437. # Scalars should just return False and not give a warnings.
  438. # The comparisons are flagged by pep8, ignore that.
  439. with warnings.catch_warnings(record=True) as w:
  440. warnings.filterwarnings('always', '', FutureWarning)
  441. assert_(not np.float32(1) == None)
  442. assert_(not np.str_('test') == None)
  443. # This is dubious (see below):
  444. assert_(not np.datetime64('NaT') == None)
  445. assert_(np.float32(1) != None)
  446. assert_(np.str_('test') != None)
  447. # This is dubious (see below):
  448. assert_(np.datetime64('NaT') != None)
  449. assert_(len(w) == 0)
  450. # For documentation purposes, this is why the datetime is dubious.
  451. # At the time of deprecation this was no behaviour change, but
  452. # it has to be considered when the deprecations are done.
  453. assert_(np.equal(np.datetime64('NaT'), None))
  454. #class TestRepr:
  455. # def test_repr(self):
  456. # for t in types:
  457. # val = t(1197346475.0137341)
  458. # val_repr = repr(val)
  459. # val2 = eval(val_repr)
  460. # assert_equal( val, val2 )
  461. class TestRepr:
  462. def _test_type_repr(self, t):
  463. finfo = np.finfo(t)
  464. last_fraction_bit_idx = finfo.nexp + finfo.nmant
  465. last_exponent_bit_idx = finfo.nexp
  466. storage_bytes = np.dtype(t).itemsize*8
  467. # could add some more types to the list below
  468. for which in ['small denorm', 'small norm']:
  469. # Values from https://en.wikipedia.org/wiki/IEEE_754
  470. constr = np.array([0x00]*storage_bytes, dtype=np.uint8)
  471. if which == 'small denorm':
  472. byte = last_fraction_bit_idx // 8
  473. bytebit = 7-(last_fraction_bit_idx % 8)
  474. constr[byte] = 1 << bytebit
  475. elif which == 'small norm':
  476. byte = last_exponent_bit_idx // 8
  477. bytebit = 7-(last_exponent_bit_idx % 8)
  478. constr[byte] = 1 << bytebit
  479. else:
  480. raise ValueError('hmm')
  481. val = constr.view(t)[0]
  482. val_repr = repr(val)
  483. val2 = t(eval(val_repr))
  484. if not (val2 == 0 and val < 1e-100):
  485. assert_equal(val, val2)
  486. def test_float_repr(self):
  487. # long double test cannot work, because eval goes through a python
  488. # float
  489. for t in [np.float32, np.float64]:
  490. self._test_type_repr(t)
  491. if not IS_PYPY:
  492. # sys.getsizeof() is not valid on PyPy
  493. class TestSizeOf:
  494. def test_equal_nbytes(self):
  495. for type in types:
  496. x = type(0)
  497. assert_(sys.getsizeof(x) > x.nbytes)
  498. def test_error(self):
  499. d = np.float32()
  500. assert_raises(TypeError, d.__sizeof__, "a")
  501. class TestMultiply:
  502. def test_seq_repeat(self):
  503. # Test that basic sequences get repeated when multiplied with
  504. # numpy integers. And errors are raised when multiplied with others.
  505. # Some of this behaviour may be controversial and could be open for
  506. # change.
  507. accepted_types = set(np.typecodes["AllInteger"])
  508. deprecated_types = {'?'}
  509. forbidden_types = (
  510. set(np.typecodes["All"]) - accepted_types - deprecated_types)
  511. forbidden_types -= {'V'} # can't default-construct void scalars
  512. for seq_type in (list, tuple):
  513. seq = seq_type([1, 2, 3])
  514. for numpy_type in accepted_types:
  515. i = np.dtype(numpy_type).type(2)
  516. assert_equal(seq * i, seq * int(i))
  517. assert_equal(i * seq, int(i) * seq)
  518. for numpy_type in deprecated_types:
  519. i = np.dtype(numpy_type).type()
  520. assert_equal(
  521. assert_warns(DeprecationWarning, operator.mul, seq, i),
  522. seq * int(i))
  523. assert_equal(
  524. assert_warns(DeprecationWarning, operator.mul, i, seq),
  525. int(i) * seq)
  526. for numpy_type in forbidden_types:
  527. i = np.dtype(numpy_type).type()
  528. assert_raises(TypeError, operator.mul, seq, i)
  529. assert_raises(TypeError, operator.mul, i, seq)
  530. def test_no_seq_repeat_basic_array_like(self):
  531. # Test that an array-like which does not know how to be multiplied
  532. # does not attempt sequence repeat (raise TypeError).
  533. # See also gh-7428.
  534. class ArrayLike:
  535. def __init__(self, arr):
  536. self.arr = arr
  537. def __array__(self):
  538. return self.arr
  539. # Test for simple ArrayLike above and memoryviews (original report)
  540. for arr_like in (ArrayLike(np.ones(3)), memoryview(np.ones(3))):
  541. assert_array_equal(arr_like * np.float32(3.), np.full(3, 3.))
  542. assert_array_equal(np.float32(3.) * arr_like, np.full(3, 3.))
  543. assert_array_equal(arr_like * np.int_(3), np.full(3, 3))
  544. assert_array_equal(np.int_(3) * arr_like, np.full(3, 3))
  545. class TestNegative:
  546. def test_exceptions(self):
  547. a = np.ones((), dtype=np.bool_)[()]
  548. assert_raises(TypeError, operator.neg, a)
  549. def test_result(self):
  550. types = np.typecodes['AllInteger'] + np.typecodes['AllFloat']
  551. with suppress_warnings() as sup:
  552. sup.filter(RuntimeWarning)
  553. for dt in types:
  554. a = np.ones((), dtype=dt)[()]
  555. assert_equal(operator.neg(a) + a, 0)
  556. class TestSubtract:
  557. def test_exceptions(self):
  558. a = np.ones((), dtype=np.bool_)[()]
  559. assert_raises(TypeError, operator.sub, a, a)
  560. def test_result(self):
  561. types = np.typecodes['AllInteger'] + np.typecodes['AllFloat']
  562. with suppress_warnings() as sup:
  563. sup.filter(RuntimeWarning)
  564. for dt in types:
  565. a = np.ones((), dtype=dt)[()]
  566. assert_equal(operator.sub(a, a), 0)
  567. class TestAbs:
  568. def _test_abs_func(self, absfunc):
  569. for tp in floating_types + complex_floating_types:
  570. x = tp(-1.5)
  571. assert_equal(absfunc(x), 1.5)
  572. x = tp(0.0)
  573. res = absfunc(x)
  574. # assert_equal() checks zero signedness
  575. assert_equal(res, 0.0)
  576. x = tp(-0.0)
  577. res = absfunc(x)
  578. assert_equal(res, 0.0)
  579. x = tp(np.finfo(tp).max)
  580. assert_equal(absfunc(x), x.real)
  581. x = tp(np.finfo(tp).tiny)
  582. assert_equal(absfunc(x), x.real)
  583. x = tp(np.finfo(tp).min)
  584. assert_equal(absfunc(x), -x.real)
  585. def test_builtin_abs(self):
  586. self._test_abs_func(abs)
  587. def test_numpy_abs(self):
  588. self._test_abs_func(np.abs)
  589. class TestBitShifts:
  590. @pytest.mark.parametrize('type_code', np.typecodes['AllInteger'])
  591. @pytest.mark.parametrize('op',
  592. [operator.rshift, operator.lshift], ids=['>>', '<<'])
  593. def test_shift_all_bits(self, type_code, op):
  594. """ Shifts where the shift amount is the width of the type or wider """
  595. # gh-2449
  596. dt = np.dtype(type_code)
  597. nbits = dt.itemsize * 8
  598. for val in [5, -5]:
  599. for shift in [nbits, nbits + 4]:
  600. val_scl = dt.type(val)
  601. shift_scl = dt.type(shift)
  602. res_scl = op(val_scl, shift_scl)
  603. if val_scl < 0 and op is operator.rshift:
  604. # sign bit is preserved
  605. assert_equal(res_scl, -1)
  606. else:
  607. assert_equal(res_scl, 0)
  608. # Result on scalars should be the same as on arrays
  609. val_arr = np.array([val]*32, dtype=dt)
  610. shift_arr = np.array([shift]*32, dtype=dt)
  611. res_arr = op(val_arr, shift_arr)
  612. assert_equal(res_arr, res_scl)
  613. @contextlib.contextmanager
  614. def recursionlimit(n):
  615. o = sys.getrecursionlimit()
  616. try:
  617. sys.setrecursionlimit(n)
  618. yield
  619. finally:
  620. sys.setrecursionlimit(o)
  621. objecty_things = [object(), None]
  622. reasonable_operators_for_scalars = [
  623. operator.lt, operator.le, operator.eq, operator.ne, operator.ge,
  624. operator.gt, operator.add, operator.floordiv, operator.mod,
  625. operator.mul, operator.matmul, operator.pow, operator.sub,
  626. operator.truediv,
  627. ]
  628. @given(sampled_from(objecty_things),
  629. sampled_from(reasonable_operators_for_scalars),
  630. sampled_from(types))
  631. @settings(verbosity=Verbosity.verbose)
  632. def test_operator_object_left(o, op, type_):
  633. try:
  634. with recursionlimit(200):
  635. op(o, type_(1))
  636. except TypeError:
  637. pass
  638. @given(sampled_from(objecty_things),
  639. sampled_from(reasonable_operators_for_scalars),
  640. sampled_from(types))
  641. def test_operator_object_right(o, op, type_):
  642. try:
  643. with recursionlimit(200):
  644. op(type_(1), o)
  645. except TypeError:
  646. pass
  647. @given(sampled_from(reasonable_operators_for_scalars),
  648. sampled_from(types),
  649. sampled_from(types))
  650. def test_operator_scalars(op, type1, type2):
  651. try:
  652. op(type1(1), type2(1))
  653. except TypeError:
  654. pass
  655. @pytest.mark.parametrize("op", reasonable_operators_for_scalars)
  656. def test_longdouble_inf_loop(op):
  657. try:
  658. op(np.longdouble(3), None)
  659. except TypeError:
  660. pass
  661. try:
  662. op(None, np.longdouble(3))
  663. except TypeError:
  664. pass
  665. @pytest.mark.parametrize("op", reasonable_operators_for_scalars)
  666. def test_clongdouble_inf_loop(op):
  667. if op in {operator.mod} and False:
  668. pytest.xfail("The modulo operator is known to be broken")
  669. try:
  670. op(np.clongdouble(3), None)
  671. except TypeError:
  672. pass
  673. try:
  674. op(None, np.longdouble(3))
  675. except TypeError:
  676. pass