testutils.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. """Miscellaneous functions for testing masked arrays and subclasses
  2. :author: Pierre Gerard-Marchant
  3. :contact: pierregm_at_uga_dot_edu
  4. :version: $Id: testutils.py 3529 2007-11-13 08:01:14Z jarrod.millman $
  5. """
  6. import operator
  7. import numpy as np
  8. from numpy import ndarray, float_
  9. import numpy.core.umath as umath
  10. import numpy.testing
  11. from numpy.testing import (
  12. assert_, assert_allclose, assert_array_almost_equal_nulp,
  13. assert_raises, build_err_msg
  14. )
  15. from .core import mask_or, getmask, masked_array, nomask, masked, filled
  16. __all__masked = [
  17. 'almost', 'approx', 'assert_almost_equal', 'assert_array_almost_equal',
  18. 'assert_array_approx_equal', 'assert_array_compare',
  19. 'assert_array_equal', 'assert_array_less', 'assert_close',
  20. 'assert_equal', 'assert_equal_records', 'assert_mask_equal',
  21. 'assert_not_equal', 'fail_if_array_equal',
  22. ]
  23. # Include some normal test functions to avoid breaking other projects who
  24. # have mistakenly included them from this file. SciPy is one. That is
  25. # unfortunate, as some of these functions are not intended to work with
  26. # masked arrays. But there was no way to tell before.
  27. from unittest import TestCase
  28. __some__from_testing = [
  29. 'TestCase', 'assert_', 'assert_allclose', 'assert_array_almost_equal_nulp',
  30. 'assert_raises'
  31. ]
  32. __all__ = __all__masked + __some__from_testing
  33. def approx(a, b, fill_value=True, rtol=1e-5, atol=1e-8):
  34. """
  35. Returns true if all components of a and b are equal to given tolerances.
  36. If fill_value is True, masked values considered equal. Otherwise,
  37. masked values are considered unequal. The relative error rtol should
  38. be positive and << 1.0 The absolute error atol comes into play for
  39. those elements of b that are very small or zero; it says how small a
  40. must be also.
  41. """
  42. m = mask_or(getmask(a), getmask(b))
  43. d1 = filled(a)
  44. d2 = filled(b)
  45. if d1.dtype.char == "O" or d2.dtype.char == "O":
  46. return np.equal(d1, d2).ravel()
  47. x = filled(masked_array(d1, copy=False, mask=m), fill_value).astype(float_)
  48. y = filled(masked_array(d2, copy=False, mask=m), 1).astype(float_)
  49. d = np.less_equal(umath.absolute(x - y), atol + rtol * umath.absolute(y))
  50. return d.ravel()
  51. def almost(a, b, decimal=6, fill_value=True):
  52. """
  53. Returns True if a and b are equal up to decimal places.
  54. If fill_value is True, masked values considered equal. Otherwise,
  55. masked values are considered unequal.
  56. """
  57. m = mask_or(getmask(a), getmask(b))
  58. d1 = filled(a)
  59. d2 = filled(b)
  60. if d1.dtype.char == "O" or d2.dtype.char == "O":
  61. return np.equal(d1, d2).ravel()
  62. x = filled(masked_array(d1, copy=False, mask=m), fill_value).astype(float_)
  63. y = filled(masked_array(d2, copy=False, mask=m), 1).astype(float_)
  64. d = np.around(np.abs(x - y), decimal) <= 10.0 ** (-decimal)
  65. return d.ravel()
  66. def _assert_equal_on_sequences(actual, desired, err_msg=''):
  67. """
  68. Asserts the equality of two non-array sequences.
  69. """
  70. assert_equal(len(actual), len(desired), err_msg)
  71. for k in range(len(desired)):
  72. assert_equal(actual[k], desired[k], f'item={k!r}\n{err_msg}')
  73. return
  74. def assert_equal_records(a, b):
  75. """
  76. Asserts that two records are equal.
  77. Pretty crude for now.
  78. """
  79. assert_equal(a.dtype, b.dtype)
  80. for f in a.dtype.names:
  81. (af, bf) = (operator.getitem(a, f), operator.getitem(b, f))
  82. if not (af is masked) and not (bf is masked):
  83. assert_equal(operator.getitem(a, f), operator.getitem(b, f))
  84. return
  85. def assert_equal(actual, desired, err_msg=''):
  86. """
  87. Asserts that two items are equal.
  88. """
  89. # Case #1: dictionary .....
  90. if isinstance(desired, dict):
  91. if not isinstance(actual, dict):
  92. raise AssertionError(repr(type(actual)))
  93. assert_equal(len(actual), len(desired), err_msg)
  94. for k, i in desired.items():
  95. if k not in actual:
  96. raise AssertionError(f"{k} not in {actual}")
  97. assert_equal(actual[k], desired[k], f'key={k!r}\n{err_msg}')
  98. return
  99. # Case #2: lists .....
  100. if isinstance(desired, (list, tuple)) and isinstance(actual, (list, tuple)):
  101. return _assert_equal_on_sequences(actual, desired, err_msg='')
  102. if not (isinstance(actual, ndarray) or isinstance(desired, ndarray)):
  103. msg = build_err_msg([actual, desired], err_msg,)
  104. if not desired == actual:
  105. raise AssertionError(msg)
  106. return
  107. # Case #4. arrays or equivalent
  108. if ((actual is masked) and not (desired is masked)) or \
  109. ((desired is masked) and not (actual is masked)):
  110. msg = build_err_msg([actual, desired],
  111. err_msg, header='', names=('x', 'y'))
  112. raise ValueError(msg)
  113. actual = np.asanyarray(actual)
  114. desired = np.asanyarray(desired)
  115. (actual_dtype, desired_dtype) = (actual.dtype, desired.dtype)
  116. if actual_dtype.char == "S" and desired_dtype.char == "S":
  117. return _assert_equal_on_sequences(actual.tolist(),
  118. desired.tolist(),
  119. err_msg='')
  120. return assert_array_equal(actual, desired, err_msg)
  121. def fail_if_equal(actual, desired, err_msg='',):
  122. """
  123. Raises an assertion error if two items are equal.
  124. """
  125. if isinstance(desired, dict):
  126. if not isinstance(actual, dict):
  127. raise AssertionError(repr(type(actual)))
  128. fail_if_equal(len(actual), len(desired), err_msg)
  129. for k, i in desired.items():
  130. if k not in actual:
  131. raise AssertionError(repr(k))
  132. fail_if_equal(actual[k], desired[k], f'key={k!r}\n{err_msg}')
  133. return
  134. if isinstance(desired, (list, tuple)) and isinstance(actual, (list, tuple)):
  135. fail_if_equal(len(actual), len(desired), err_msg)
  136. for k in range(len(desired)):
  137. fail_if_equal(actual[k], desired[k], f'item={k!r}\n{err_msg}')
  138. return
  139. if isinstance(actual, np.ndarray) or isinstance(desired, np.ndarray):
  140. return fail_if_array_equal(actual, desired, err_msg)
  141. msg = build_err_msg([actual, desired], err_msg)
  142. if not desired != actual:
  143. raise AssertionError(msg)
  144. assert_not_equal = fail_if_equal
  145. def assert_almost_equal(actual, desired, decimal=7, err_msg='', verbose=True):
  146. """
  147. Asserts that two items are almost equal.
  148. The test is equivalent to abs(desired-actual) < 0.5 * 10**(-decimal).
  149. """
  150. if isinstance(actual, np.ndarray) or isinstance(desired, np.ndarray):
  151. return assert_array_almost_equal(actual, desired, decimal=decimal,
  152. err_msg=err_msg, verbose=verbose)
  153. msg = build_err_msg([actual, desired],
  154. err_msg=err_msg, verbose=verbose)
  155. if not round(abs(desired - actual), decimal) == 0:
  156. raise AssertionError(msg)
  157. assert_close = assert_almost_equal
  158. def assert_array_compare(comparison, x, y, err_msg='', verbose=True, header='',
  159. fill_value=True):
  160. """
  161. Asserts that comparison between two masked arrays is satisfied.
  162. The comparison is elementwise.
  163. """
  164. # Allocate a common mask and refill
  165. m = mask_or(getmask(x), getmask(y))
  166. x = masked_array(x, copy=False, mask=m, keep_mask=False, subok=False)
  167. y = masked_array(y, copy=False, mask=m, keep_mask=False, subok=False)
  168. if ((x is masked) and not (y is masked)) or \
  169. ((y is masked) and not (x is masked)):
  170. msg = build_err_msg([x, y], err_msg=err_msg, verbose=verbose,
  171. header=header, names=('x', 'y'))
  172. raise ValueError(msg)
  173. # OK, now run the basic tests on filled versions
  174. return np.testing.assert_array_compare(comparison,
  175. x.filled(fill_value),
  176. y.filled(fill_value),
  177. err_msg=err_msg,
  178. verbose=verbose, header=header)
  179. def assert_array_equal(x, y, err_msg='', verbose=True):
  180. """
  181. Checks the elementwise equality of two masked arrays.
  182. """
  183. assert_array_compare(operator.__eq__, x, y,
  184. err_msg=err_msg, verbose=verbose,
  185. header='Arrays are not equal')
  186. def fail_if_array_equal(x, y, err_msg='', verbose=True):
  187. """
  188. Raises an assertion error if two masked arrays are not equal elementwise.
  189. """
  190. def compare(x, y):
  191. return (not np.all(approx(x, y)))
  192. assert_array_compare(compare, x, y, err_msg=err_msg, verbose=verbose,
  193. header='Arrays are not equal')
  194. def assert_array_approx_equal(x, y, decimal=6, err_msg='', verbose=True):
  195. """
  196. Checks the equality of two masked arrays, up to given number odecimals.
  197. The equality is checked elementwise.
  198. """
  199. def compare(x, y):
  200. "Returns the result of the loose comparison between x and y)."
  201. return approx(x, y, rtol=10. ** -decimal)
  202. assert_array_compare(compare, x, y, err_msg=err_msg, verbose=verbose,
  203. header='Arrays are not almost equal')
  204. def assert_array_almost_equal(x, y, decimal=6, err_msg='', verbose=True):
  205. """
  206. Checks the equality of two masked arrays, up to given number odecimals.
  207. The equality is checked elementwise.
  208. """
  209. def compare(x, y):
  210. "Returns the result of the loose comparison between x and y)."
  211. return almost(x, y, decimal)
  212. assert_array_compare(compare, x, y, err_msg=err_msg, verbose=verbose,
  213. header='Arrays are not almost equal')
  214. def assert_array_less(x, y, err_msg='', verbose=True):
  215. """
  216. Checks that x is smaller than y elementwise.
  217. """
  218. assert_array_compare(operator.__lt__, x, y,
  219. err_msg=err_msg, verbose=verbose,
  220. header='Arrays are not less-ordered')
  221. def assert_mask_equal(m1, m2, err_msg=''):
  222. """
  223. Asserts the equality of two masks.
  224. """
  225. if m1 is nomask:
  226. assert_(m2 is nomask)
  227. if m2 is nomask:
  228. assert_(m1 is nomask)
  229. assert_array_equal(m1, m2, err_msg=err_msg)