test_ufunclike.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import numpy as np
  2. from numpy import fix, isneginf, isposinf
  3. from numpy.testing import assert_, assert_array_equal, assert_equal, assert_raises
  4. class TestUfunclike:
  5. def test_isposinf(self):
  6. a = np.array([np.inf, -np.inf, np.nan, 0.0, 3.0, -3.0])
  7. out = np.zeros(a.shape, bool)
  8. tgt = np.array([True, False, False, False, False, False])
  9. res = isposinf(a)
  10. assert_equal(res, tgt)
  11. res = isposinf(a, out)
  12. assert_equal(res, tgt)
  13. assert_equal(out, tgt)
  14. a = a.astype(np.complex128)
  15. with assert_raises(TypeError):
  16. isposinf(a)
  17. def test_isneginf(self):
  18. a = np.array([np.inf, -np.inf, np.nan, 0.0, 3.0, -3.0])
  19. out = np.zeros(a.shape, bool)
  20. tgt = np.array([False, True, False, False, False, False])
  21. res = isneginf(a)
  22. assert_equal(res, tgt)
  23. res = isneginf(a, out)
  24. assert_equal(res, tgt)
  25. assert_equal(out, tgt)
  26. a = a.astype(np.complex128)
  27. with assert_raises(TypeError):
  28. isneginf(a)
  29. def test_fix(self):
  30. a = np.array([[1.0, 1.1, 1.5, 1.8], [-1.0, -1.1, -1.5, -1.8]])
  31. out = np.zeros(a.shape, float)
  32. tgt = np.array([[1., 1., 1., 1.], [-1., -1., -1., -1.]])
  33. res = fix(a)
  34. assert_equal(res, tgt)
  35. res = fix(a, out)
  36. assert_equal(res, tgt)
  37. assert_equal(out, tgt)
  38. assert_equal(fix(3.14), 3)
  39. def test_fix_with_subclass(self):
  40. class MyArray(np.ndarray):
  41. def __new__(cls, data, metadata=None):
  42. res = np.array(data, copy=True).view(cls)
  43. res.metadata = metadata
  44. return res
  45. def __array_wrap__(self, obj, context=None, return_scalar=False):
  46. if not isinstance(obj, MyArray):
  47. obj = obj.view(MyArray)
  48. if obj.metadata is None:
  49. obj.metadata = self.metadata
  50. return obj
  51. def __array_finalize__(self, obj):
  52. self.metadata = getattr(obj, 'metadata', None)
  53. return self
  54. a = np.array([1.1, -1.1])
  55. m = MyArray(a, metadata='foo')
  56. f = fix(m)
  57. assert_array_equal(f, np.array([1, -1]))
  58. assert_(isinstance(f, MyArray))
  59. assert_equal(f.metadata, 'foo')
  60. # check 0d arrays don't decay to scalars
  61. m0d = m[0, ...]
  62. m0d.metadata = 'bar'
  63. f0d = fix(m0d)
  64. assert_(isinstance(f0d, MyArray))
  65. assert_equal(f0d.metadata, 'bar')
  66. def test_scalar(self):
  67. x = np.inf
  68. actual = np.isposinf(x)
  69. expected = np.True_
  70. assert_equal(actual, expected)
  71. assert_equal(type(actual), type(expected))
  72. x = -3.4
  73. actual = np.fix(x)
  74. expected = np.float64(-3.0)
  75. assert_equal(actual, expected)
  76. assert_equal(type(actual), type(expected))
  77. out = np.array(0.0)
  78. actual = np.fix(x, out=out)
  79. assert_(actual is out)