test_subclassing.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. # pylint: disable-msg=W0611, W0612, W0511,R0201
  2. """Tests suite for MaskedArray & subclassing.
  3. :author: Pierre Gerard-Marchant
  4. :contact: pierregm_at_uga_dot_edu
  5. :version: $Id: test_subclassing.py 3473 2007-10-29 15:18:13Z jarrod.millman $
  6. """
  7. import numpy as np
  8. from numpy.lib.mixins import NDArrayOperatorsMixin
  9. from numpy.testing import assert_, assert_raises
  10. from numpy.ma.testutils import assert_equal
  11. from numpy.ma.core import (
  12. array, arange, masked, MaskedArray, masked_array, log, add, hypot,
  13. divide, asarray, asanyarray, nomask
  14. )
  15. # from numpy.ma.core import (
  16. def assert_startswith(a, b):
  17. # produces a better error message than assert_(a.startswith(b))
  18. assert_equal(a[:len(b)], b)
  19. class SubArray(np.ndarray):
  20. # Defines a generic np.ndarray subclass, that stores some metadata
  21. # in the dictionary `info`.
  22. def __new__(cls,arr,info={}):
  23. x = np.asanyarray(arr).view(cls)
  24. x.info = info.copy()
  25. return x
  26. def __array_finalize__(self, obj):
  27. super().__array_finalize__(obj)
  28. self.info = getattr(obj, 'info', {}).copy()
  29. return
  30. def __add__(self, other):
  31. result = super().__add__(other)
  32. result.info['added'] = result.info.get('added', 0) + 1
  33. return result
  34. def __iadd__(self, other):
  35. result = super().__iadd__(other)
  36. result.info['iadded'] = result.info.get('iadded', 0) + 1
  37. return result
  38. subarray = SubArray
  39. class SubMaskedArray(MaskedArray):
  40. """Pure subclass of MaskedArray, keeping some info on subclass."""
  41. def __new__(cls, info=None, **kwargs):
  42. obj = super().__new__(cls, **kwargs)
  43. obj._optinfo['info'] = info
  44. return obj
  45. class MSubArray(SubArray, MaskedArray):
  46. def __new__(cls, data, info={}, mask=nomask):
  47. subarr = SubArray(data, info)
  48. _data = MaskedArray.__new__(cls, data=subarr, mask=mask)
  49. _data.info = subarr.info
  50. return _data
  51. @property
  52. def _series(self):
  53. _view = self.view(MaskedArray)
  54. _view._sharedmask = False
  55. return _view
  56. msubarray = MSubArray
  57. # Also a subclass that overrides __str__, __repr__ and __setitem__, disallowing
  58. # setting to non-class values (and thus np.ma.core.masked_print_option)
  59. # and overrides __array_wrap__, updating the info dict, to check that this
  60. # doesn't get destroyed by MaskedArray._update_from. But this one also needs
  61. # its own iterator...
  62. class CSAIterator:
  63. """
  64. Flat iterator object that uses its own setter/getter
  65. (works around ndarray.flat not propagating subclass setters/getters
  66. see https://github.com/numpy/numpy/issues/4564)
  67. roughly following MaskedIterator
  68. """
  69. def __init__(self, a):
  70. self._original = a
  71. self._dataiter = a.view(np.ndarray).flat
  72. def __iter__(self):
  73. return self
  74. def __getitem__(self, indx):
  75. out = self._dataiter.__getitem__(indx)
  76. if not isinstance(out, np.ndarray):
  77. out = out.__array__()
  78. out = out.view(type(self._original))
  79. return out
  80. def __setitem__(self, index, value):
  81. self._dataiter[index] = self._original._validate_input(value)
  82. def __next__(self):
  83. return next(self._dataiter).__array__().view(type(self._original))
  84. class ComplicatedSubArray(SubArray):
  85. def __str__(self):
  86. return f'myprefix {self.view(SubArray)} mypostfix'
  87. def __repr__(self):
  88. # Return a repr that does not start with 'name('
  89. return f'<{self.__class__.__name__} {self}>'
  90. def _validate_input(self, value):
  91. if not isinstance(value, ComplicatedSubArray):
  92. raise ValueError("Can only set to MySubArray values")
  93. return value
  94. def __setitem__(self, item, value):
  95. # validation ensures direct assignment with ndarray or
  96. # masked_print_option will fail
  97. super().__setitem__(item, self._validate_input(value))
  98. def __getitem__(self, item):
  99. # ensure getter returns our own class also for scalars
  100. value = super().__getitem__(item)
  101. if not isinstance(value, np.ndarray): # scalar
  102. value = value.__array__().view(ComplicatedSubArray)
  103. return value
  104. @property
  105. def flat(self):
  106. return CSAIterator(self)
  107. @flat.setter
  108. def flat(self, value):
  109. y = self.ravel()
  110. y[:] = value
  111. def __array_wrap__(self, obj, context=None):
  112. obj = super().__array_wrap__(obj, context)
  113. if context is not None and context[0] is np.multiply:
  114. obj.info['multiplied'] = obj.info.get('multiplied', 0) + 1
  115. return obj
  116. class WrappedArray(NDArrayOperatorsMixin):
  117. """
  118. Wrapping a MaskedArray rather than subclassing to test that
  119. ufunc deferrals are commutative.
  120. See: https://github.com/numpy/numpy/issues/15200)
  121. """
  122. __array_priority__ = 20
  123. def __init__(self, array, **attrs):
  124. self._array = array
  125. self.attrs = attrs
  126. def __repr__(self):
  127. return f"{self.__class__.__name__}(\n{self._array}\n{self.attrs}\n)"
  128. def __array__(self):
  129. return np.asarray(self._array)
  130. def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
  131. if method == '__call__':
  132. inputs = [arg._array if isinstance(arg, self.__class__) else arg
  133. for arg in inputs]
  134. return self.__class__(ufunc(*inputs, **kwargs), **self.attrs)
  135. else:
  136. return NotImplemented
  137. class TestSubclassing:
  138. # Test suite for masked subclasses of ndarray.
  139. def setup_method(self):
  140. x = np.arange(5, dtype='float')
  141. mx = msubarray(x, mask=[0, 1, 0, 0, 0])
  142. self.data = (x, mx)
  143. def test_data_subclassing(self):
  144. # Tests whether the subclass is kept.
  145. x = np.arange(5)
  146. m = [0, 0, 1, 0, 0]
  147. xsub = SubArray(x)
  148. xmsub = masked_array(xsub, mask=m)
  149. assert_(isinstance(xmsub, MaskedArray))
  150. assert_equal(xmsub._data, xsub)
  151. assert_(isinstance(xmsub._data, SubArray))
  152. def test_maskedarray_subclassing(self):
  153. # Tests subclassing MaskedArray
  154. (x, mx) = self.data
  155. assert_(isinstance(mx._data, subarray))
  156. def test_masked_unary_operations(self):
  157. # Tests masked_unary_operation
  158. (x, mx) = self.data
  159. with np.errstate(divide='ignore'):
  160. assert_(isinstance(log(mx), msubarray))
  161. assert_equal(log(x), np.log(x))
  162. def test_masked_binary_operations(self):
  163. # Tests masked_binary_operation
  164. (x, mx) = self.data
  165. # Result should be a msubarray
  166. assert_(isinstance(add(mx, mx), msubarray))
  167. assert_(isinstance(add(mx, x), msubarray))
  168. # Result should work
  169. assert_equal(add(mx, x), mx+x)
  170. assert_(isinstance(add(mx, mx)._data, subarray))
  171. assert_(isinstance(add.outer(mx, mx), msubarray))
  172. assert_(isinstance(hypot(mx, mx), msubarray))
  173. assert_(isinstance(hypot(mx, x), msubarray))
  174. def test_masked_binary_operations2(self):
  175. # Tests domained_masked_binary_operation
  176. (x, mx) = self.data
  177. xmx = masked_array(mx.data.__array__(), mask=mx.mask)
  178. assert_(isinstance(divide(mx, mx), msubarray))
  179. assert_(isinstance(divide(mx, x), msubarray))
  180. assert_equal(divide(mx, mx), divide(xmx, xmx))
  181. def test_attributepropagation(self):
  182. x = array(arange(5), mask=[0]+[1]*4)
  183. my = masked_array(subarray(x))
  184. ym = msubarray(x)
  185. #
  186. z = (my+1)
  187. assert_(isinstance(z, MaskedArray))
  188. assert_(not isinstance(z, MSubArray))
  189. assert_(isinstance(z._data, SubArray))
  190. assert_equal(z._data.info, {})
  191. #
  192. z = (ym+1)
  193. assert_(isinstance(z, MaskedArray))
  194. assert_(isinstance(z, MSubArray))
  195. assert_(isinstance(z._data, SubArray))
  196. assert_(z._data.info['added'] > 0)
  197. # Test that inplace methods from data get used (gh-4617)
  198. ym += 1
  199. assert_(isinstance(ym, MaskedArray))
  200. assert_(isinstance(ym, MSubArray))
  201. assert_(isinstance(ym._data, SubArray))
  202. assert_(ym._data.info['iadded'] > 0)
  203. #
  204. ym._set_mask([1, 0, 0, 0, 1])
  205. assert_equal(ym._mask, [1, 0, 0, 0, 1])
  206. ym._series._set_mask([0, 0, 0, 0, 1])
  207. assert_equal(ym._mask, [0, 0, 0, 0, 1])
  208. #
  209. xsub = subarray(x, info={'name':'x'})
  210. mxsub = masked_array(xsub)
  211. assert_(hasattr(mxsub, 'info'))
  212. assert_equal(mxsub.info, xsub.info)
  213. def test_subclasspreservation(self):
  214. # Checks that masked_array(...,subok=True) preserves the class.
  215. x = np.arange(5)
  216. m = [0, 0, 1, 0, 0]
  217. xinfo = [(i, j) for (i, j) in zip(x, m)]
  218. xsub = MSubArray(x, mask=m, info={'xsub':xinfo})
  219. #
  220. mxsub = masked_array(xsub, subok=False)
  221. assert_(not isinstance(mxsub, MSubArray))
  222. assert_(isinstance(mxsub, MaskedArray))
  223. assert_equal(mxsub._mask, m)
  224. #
  225. mxsub = asarray(xsub)
  226. assert_(not isinstance(mxsub, MSubArray))
  227. assert_(isinstance(mxsub, MaskedArray))
  228. assert_equal(mxsub._mask, m)
  229. #
  230. mxsub = masked_array(xsub, subok=True)
  231. assert_(isinstance(mxsub, MSubArray))
  232. assert_equal(mxsub.info, xsub.info)
  233. assert_equal(mxsub._mask, xsub._mask)
  234. #
  235. mxsub = asanyarray(xsub)
  236. assert_(isinstance(mxsub, MSubArray))
  237. assert_equal(mxsub.info, xsub.info)
  238. assert_equal(mxsub._mask, m)
  239. def test_subclass_items(self):
  240. """test that getter and setter go via baseclass"""
  241. x = np.arange(5)
  242. xcsub = ComplicatedSubArray(x)
  243. mxcsub = masked_array(xcsub, mask=[True, False, True, False, False])
  244. # getter should return a ComplicatedSubArray, even for single item
  245. # first check we wrote ComplicatedSubArray correctly
  246. assert_(isinstance(xcsub[1], ComplicatedSubArray))
  247. assert_(isinstance(xcsub[1,...], ComplicatedSubArray))
  248. assert_(isinstance(xcsub[1:4], ComplicatedSubArray))
  249. # now that it propagates inside the MaskedArray
  250. assert_(isinstance(mxcsub[1], ComplicatedSubArray))
  251. assert_(isinstance(mxcsub[1,...].data, ComplicatedSubArray))
  252. assert_(mxcsub[0] is masked)
  253. assert_(isinstance(mxcsub[0,...].data, ComplicatedSubArray))
  254. assert_(isinstance(mxcsub[1:4].data, ComplicatedSubArray))
  255. # also for flattened version (which goes via MaskedIterator)
  256. assert_(isinstance(mxcsub.flat[1].data, ComplicatedSubArray))
  257. assert_(mxcsub.flat[0] is masked)
  258. assert_(isinstance(mxcsub.flat[1:4].base, ComplicatedSubArray))
  259. # setter should only work with ComplicatedSubArray input
  260. # first check we wrote ComplicatedSubArray correctly
  261. assert_raises(ValueError, xcsub.__setitem__, 1, x[4])
  262. # now that it propagates inside the MaskedArray
  263. assert_raises(ValueError, mxcsub.__setitem__, 1, x[4])
  264. assert_raises(ValueError, mxcsub.__setitem__, slice(1, 4), x[1:4])
  265. mxcsub[1] = xcsub[4]
  266. mxcsub[1:4] = xcsub[1:4]
  267. # also for flattened version (which goes via MaskedIterator)
  268. assert_raises(ValueError, mxcsub.flat.__setitem__, 1, x[4])
  269. assert_raises(ValueError, mxcsub.flat.__setitem__, slice(1, 4), x[1:4])
  270. mxcsub.flat[1] = xcsub[4]
  271. mxcsub.flat[1:4] = xcsub[1:4]
  272. def test_subclass_nomask_items(self):
  273. x = np.arange(5)
  274. xcsub = ComplicatedSubArray(x)
  275. mxcsub_nomask = masked_array(xcsub)
  276. assert_(isinstance(mxcsub_nomask[1,...].data, ComplicatedSubArray))
  277. assert_(isinstance(mxcsub_nomask[0,...].data, ComplicatedSubArray))
  278. assert_(isinstance(mxcsub_nomask[1], ComplicatedSubArray))
  279. assert_(isinstance(mxcsub_nomask[0], ComplicatedSubArray))
  280. def test_subclass_repr(self):
  281. """test that repr uses the name of the subclass
  282. and 'array' for np.ndarray"""
  283. x = np.arange(5)
  284. mx = masked_array(x, mask=[True, False, True, False, False])
  285. assert_startswith(repr(mx), 'masked_array')
  286. xsub = SubArray(x)
  287. mxsub = masked_array(xsub, mask=[True, False, True, False, False])
  288. assert_startswith(repr(mxsub),
  289. f'masked_{SubArray.__name__}(data=[--, 1, --, 3, 4]')
  290. def test_subclass_str(self):
  291. """test str with subclass that has overridden str, setitem"""
  292. # first without override
  293. x = np.arange(5)
  294. xsub = SubArray(x)
  295. mxsub = masked_array(xsub, mask=[True, False, True, False, False])
  296. assert_equal(str(mxsub), '[-- 1 -- 3 4]')
  297. xcsub = ComplicatedSubArray(x)
  298. assert_raises(ValueError, xcsub.__setitem__, 0,
  299. np.ma.core.masked_print_option)
  300. mxcsub = masked_array(xcsub, mask=[True, False, True, False, False])
  301. assert_equal(str(mxcsub), 'myprefix [-- 1 -- 3 4] mypostfix')
  302. def test_pure_subclass_info_preservation(self):
  303. # Test that ufuncs and methods conserve extra information consistently;
  304. # see gh-7122.
  305. arr1 = SubMaskedArray('test', data=[1,2,3,4,5,6])
  306. arr2 = SubMaskedArray(data=[0,1,2,3,4,5])
  307. diff1 = np.subtract(arr1, arr2)
  308. assert_('info' in diff1._optinfo)
  309. assert_(diff1._optinfo['info'] == 'test')
  310. diff2 = arr1 - arr2
  311. assert_('info' in diff2._optinfo)
  312. assert_(diff2._optinfo['info'] == 'test')
  313. class ArrayNoInheritance:
  314. """Quantity-like class that does not inherit from ndarray"""
  315. def __init__(self, data, units):
  316. self.magnitude = data
  317. self.units = units
  318. def __getattr__(self, attr):
  319. return getattr(self.magnitude, attr)
  320. def test_array_no_inheritance():
  321. data_masked = np.ma.array([1, 2, 3], mask=[True, False, True])
  322. data_masked_units = ArrayNoInheritance(data_masked, 'meters')
  323. # Get the masked representation of the Quantity-like class
  324. new_array = np.ma.array(data_masked_units)
  325. assert_equal(data_masked.data, new_array.data)
  326. assert_equal(data_masked.mask, new_array.mask)
  327. # Test sharing the mask
  328. data_masked.mask = [True, False, False]
  329. assert_equal(data_masked.mask, new_array.mask)
  330. assert_(new_array.sharedmask)
  331. # Get the masked representation of the Quantity-like class
  332. new_array = np.ma.array(data_masked_units, copy=True)
  333. assert_equal(data_masked.data, new_array.data)
  334. assert_equal(data_masked.mask, new_array.mask)
  335. # Test that the mask is not shared when copy=True
  336. data_masked.mask = [True, False, True]
  337. assert_equal([True, False, False], new_array.mask)
  338. assert_(not new_array.sharedmask)
  339. # Get the masked representation of the Quantity-like class
  340. new_array = np.ma.array(data_masked_units, keep_mask=False)
  341. assert_equal(data_masked.data, new_array.data)
  342. # The change did not affect the original mask
  343. assert_equal(data_masked.mask, [True, False, True])
  344. # Test that the mask is False and not shared when keep_mask=False
  345. assert_(not new_array.mask)
  346. assert_(not new_array.sharedmask)
  347. class TestClassWrapping:
  348. # Test suite for classes that wrap MaskedArrays
  349. def setup_method(self):
  350. m = np.ma.masked_array([1, 3, 5], mask=[False, True, False])
  351. wm = WrappedArray(m)
  352. self.data = (m, wm)
  353. def test_masked_unary_operations(self):
  354. # Tests masked_unary_operation
  355. (m, wm) = self.data
  356. with np.errstate(divide='ignore'):
  357. assert_(isinstance(np.log(wm), WrappedArray))
  358. def test_masked_binary_operations(self):
  359. # Tests masked_binary_operation
  360. (m, wm) = self.data
  361. # Result should be a WrappedArray
  362. assert_(isinstance(np.add(wm, wm), WrappedArray))
  363. assert_(isinstance(np.add(m, wm), WrappedArray))
  364. assert_(isinstance(np.add(wm, m), WrappedArray))
  365. # add and '+' should call the same ufunc
  366. assert_equal(np.add(m, wm), m + wm)
  367. assert_(isinstance(np.hypot(m, wm), WrappedArray))
  368. assert_(isinstance(np.hypot(wm, m), WrappedArray))
  369. # Test domained binary operations
  370. assert_(isinstance(np.divide(wm, m), WrappedArray))
  371. assert_(isinstance(np.divide(m, wm), WrappedArray))
  372. assert_equal(np.divide(wm, m) * m, np.divide(m, m) * wm)
  373. # Test broadcasting
  374. m2 = np.stack([m, m])
  375. assert_(isinstance(np.divide(wm, m2), WrappedArray))
  376. assert_(isinstance(np.divide(m2, wm), WrappedArray))
  377. assert_equal(np.divide(m2, wm), np.divide(wm, m2))