testutils.py 10 KB

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