test_extras.py 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870
  1. # pylint: disable-msg=W0611, W0612, W0511
  2. """Tests suite for MaskedArray.
  3. Adapted from the original test_ma by Pierre Gerard-Marchant
  4. :author: Pierre Gerard-Marchant
  5. :contact: pierregm_at_uga_dot_edu
  6. :version: $Id: test_extras.py 3473 2007-10-29 15:18:13Z jarrod.millman $
  7. """
  8. import warnings
  9. import itertools
  10. import pytest
  11. import numpy as np
  12. from numpy.core.numeric import normalize_axis_tuple
  13. from numpy.testing import (
  14. assert_warns, suppress_warnings
  15. )
  16. from numpy.ma.testutils import (
  17. assert_, assert_array_equal, assert_equal, assert_almost_equal
  18. )
  19. from numpy.ma.core import (
  20. array, arange, masked, MaskedArray, masked_array, getmaskarray, shape,
  21. nomask, ones, zeros, count
  22. )
  23. from numpy.ma.extras import (
  24. atleast_1d, atleast_2d, atleast_3d, mr_, dot, polyfit, cov, corrcoef,
  25. median, average, unique, setxor1d, setdiff1d, union1d, intersect1d, in1d,
  26. ediff1d, apply_over_axes, apply_along_axis, compress_nd, compress_rowcols,
  27. mask_rowcols, clump_masked, clump_unmasked, flatnotmasked_contiguous,
  28. notmasked_contiguous, notmasked_edges, masked_all, masked_all_like, isin,
  29. diagflat, ndenumerate, stack, vstack
  30. )
  31. class TestGeneric:
  32. #
  33. def test_masked_all(self):
  34. # Tests masked_all
  35. # Standard dtype
  36. test = masked_all((2,), dtype=float)
  37. control = array([1, 1], mask=[1, 1], dtype=float)
  38. assert_equal(test, control)
  39. # Flexible dtype
  40. dt = np.dtype({'names': ['a', 'b'], 'formats': ['f', 'f']})
  41. test = masked_all((2,), dtype=dt)
  42. control = array([(0, 0), (0, 0)], mask=[(1, 1), (1, 1)], dtype=dt)
  43. assert_equal(test, control)
  44. test = masked_all((2, 2), dtype=dt)
  45. control = array([[(0, 0), (0, 0)], [(0, 0), (0, 0)]],
  46. mask=[[(1, 1), (1, 1)], [(1, 1), (1, 1)]],
  47. dtype=dt)
  48. assert_equal(test, control)
  49. # Nested dtype
  50. dt = np.dtype([('a', 'f'), ('b', [('ba', 'f'), ('bb', 'f')])])
  51. test = masked_all((2,), dtype=dt)
  52. control = array([(1, (1, 1)), (1, (1, 1))],
  53. mask=[(1, (1, 1)), (1, (1, 1))], dtype=dt)
  54. assert_equal(test, control)
  55. test = masked_all((2,), dtype=dt)
  56. control = array([(1, (1, 1)), (1, (1, 1))],
  57. mask=[(1, (1, 1)), (1, (1, 1))], dtype=dt)
  58. assert_equal(test, control)
  59. test = masked_all((1, 1), dtype=dt)
  60. control = array([[(1, (1, 1))]], mask=[[(1, (1, 1))]], dtype=dt)
  61. assert_equal(test, control)
  62. def test_masked_all_with_object_nested(self):
  63. # Test masked_all works with nested array with dtype of an 'object'
  64. # refers to issue #15895
  65. my_dtype = np.dtype([('b', ([('c', object)], (1,)))])
  66. masked_arr = np.ma.masked_all((1,), my_dtype)
  67. assert_equal(type(masked_arr['b']), np.ma.core.MaskedArray)
  68. assert_equal(type(masked_arr['b']['c']), np.ma.core.MaskedArray)
  69. assert_equal(len(masked_arr['b']['c']), 1)
  70. assert_equal(masked_arr['b']['c'].shape, (1, 1))
  71. assert_equal(masked_arr['b']['c']._fill_value.shape, ())
  72. def test_masked_all_with_object(self):
  73. # same as above except that the array is not nested
  74. my_dtype = np.dtype([('b', (object, (1,)))])
  75. masked_arr = np.ma.masked_all((1,), my_dtype)
  76. assert_equal(type(masked_arr['b']), np.ma.core.MaskedArray)
  77. assert_equal(len(masked_arr['b']), 1)
  78. assert_equal(masked_arr['b'].shape, (1, 1))
  79. assert_equal(masked_arr['b']._fill_value.shape, ())
  80. def test_masked_all_like(self):
  81. # Tests masked_all
  82. # Standard dtype
  83. base = array([1, 2], dtype=float)
  84. test = masked_all_like(base)
  85. control = array([1, 1], mask=[1, 1], dtype=float)
  86. assert_equal(test, control)
  87. # Flexible dtype
  88. dt = np.dtype({'names': ['a', 'b'], 'formats': ['f', 'f']})
  89. base = array([(0, 0), (0, 0)], mask=[(1, 1), (1, 1)], dtype=dt)
  90. test = masked_all_like(base)
  91. control = array([(10, 10), (10, 10)], mask=[(1, 1), (1, 1)], dtype=dt)
  92. assert_equal(test, control)
  93. # Nested dtype
  94. dt = np.dtype([('a', 'f'), ('b', [('ba', 'f'), ('bb', 'f')])])
  95. control = array([(1, (1, 1)), (1, (1, 1))],
  96. mask=[(1, (1, 1)), (1, (1, 1))], dtype=dt)
  97. test = masked_all_like(control)
  98. assert_equal(test, control)
  99. def check_clump(self, f):
  100. for i in range(1, 7):
  101. for j in range(2**i):
  102. k = np.arange(i, dtype=int)
  103. ja = np.full(i, j, dtype=int)
  104. a = masked_array(2**k)
  105. a.mask = (ja & (2**k)) != 0
  106. s = 0
  107. for sl in f(a):
  108. s += a.data[sl].sum()
  109. if f == clump_unmasked:
  110. assert_equal(a.compressed().sum(), s)
  111. else:
  112. a.mask = ~a.mask
  113. assert_equal(a.compressed().sum(), s)
  114. def test_clump_masked(self):
  115. # Test clump_masked
  116. a = masked_array(np.arange(10))
  117. a[[0, 1, 2, 6, 8, 9]] = masked
  118. #
  119. test = clump_masked(a)
  120. control = [slice(0, 3), slice(6, 7), slice(8, 10)]
  121. assert_equal(test, control)
  122. self.check_clump(clump_masked)
  123. def test_clump_unmasked(self):
  124. # Test clump_unmasked
  125. a = masked_array(np.arange(10))
  126. a[[0, 1, 2, 6, 8, 9]] = masked
  127. test = clump_unmasked(a)
  128. control = [slice(3, 6), slice(7, 8), ]
  129. assert_equal(test, control)
  130. self.check_clump(clump_unmasked)
  131. def test_flatnotmasked_contiguous(self):
  132. # Test flatnotmasked_contiguous
  133. a = arange(10)
  134. # No mask
  135. test = flatnotmasked_contiguous(a)
  136. assert_equal(test, [slice(0, a.size)])
  137. # mask of all false
  138. a.mask = np.zeros(10, dtype=bool)
  139. assert_equal(test, [slice(0, a.size)])
  140. # Some mask
  141. a[(a < 3) | (a > 8) | (a == 5)] = masked
  142. test = flatnotmasked_contiguous(a)
  143. assert_equal(test, [slice(3, 5), slice(6, 9)])
  144. #
  145. a[:] = masked
  146. test = flatnotmasked_contiguous(a)
  147. assert_equal(test, [])
  148. class TestAverage:
  149. # Several tests of average. Why so many ? Good point...
  150. def test_testAverage1(self):
  151. # Test of average.
  152. ott = array([0., 1., 2., 3.], mask=[True, False, False, False])
  153. assert_equal(2.0, average(ott, axis=0))
  154. assert_equal(2.0, average(ott, weights=[1., 1., 2., 1.]))
  155. result, wts = average(ott, weights=[1., 1., 2., 1.], returned=True)
  156. assert_equal(2.0, result)
  157. assert_(wts == 4.0)
  158. ott[:] = masked
  159. assert_equal(average(ott, axis=0).mask, [True])
  160. ott = array([0., 1., 2., 3.], mask=[True, False, False, False])
  161. ott = ott.reshape(2, 2)
  162. ott[:, 1] = masked
  163. assert_equal(average(ott, axis=0), [2.0, 0.0])
  164. assert_equal(average(ott, axis=1).mask[0], [True])
  165. assert_equal([2., 0.], average(ott, axis=0))
  166. result, wts = average(ott, axis=0, returned=True)
  167. assert_equal(wts, [1., 0.])
  168. def test_testAverage2(self):
  169. # More tests of average.
  170. w1 = [0, 1, 1, 1, 1, 0]
  171. w2 = [[0, 1, 1, 1, 1, 0], [1, 0, 0, 0, 0, 1]]
  172. x = arange(6, dtype=np.float_)
  173. assert_equal(average(x, axis=0), 2.5)
  174. assert_equal(average(x, axis=0, weights=w1), 2.5)
  175. y = array([arange(6, dtype=np.float_), 2.0 * arange(6)])
  176. assert_equal(average(y, None), np.add.reduce(np.arange(6)) * 3. / 12.)
  177. assert_equal(average(y, axis=0), np.arange(6) * 3. / 2.)
  178. assert_equal(average(y, axis=1),
  179. [average(x, axis=0), average(x, axis=0) * 2.0])
  180. assert_equal(average(y, None, weights=w2), 20. / 6.)
  181. assert_equal(average(y, axis=0, weights=w2),
  182. [0., 1., 2., 3., 4., 10.])
  183. assert_equal(average(y, axis=1),
  184. [average(x, axis=0), average(x, axis=0) * 2.0])
  185. m1 = zeros(6)
  186. m2 = [0, 0, 1, 1, 0, 0]
  187. m3 = [[0, 0, 1, 1, 0, 0], [0, 1, 1, 1, 1, 0]]
  188. m4 = ones(6)
  189. m5 = [0, 1, 1, 1, 1, 1]
  190. assert_equal(average(masked_array(x, m1), axis=0), 2.5)
  191. assert_equal(average(masked_array(x, m2), axis=0), 2.5)
  192. assert_equal(average(masked_array(x, m4), axis=0).mask, [True])
  193. assert_equal(average(masked_array(x, m5), axis=0), 0.0)
  194. assert_equal(count(average(masked_array(x, m4), axis=0)), 0)
  195. z = masked_array(y, m3)
  196. assert_equal(average(z, None), 20. / 6.)
  197. assert_equal(average(z, axis=0), [0., 1., 99., 99., 4.0, 7.5])
  198. assert_equal(average(z, axis=1), [2.5, 5.0])
  199. assert_equal(average(z, axis=0, weights=w2),
  200. [0., 1., 99., 99., 4.0, 10.0])
  201. def test_testAverage3(self):
  202. # Yet more tests of average!
  203. a = arange(6)
  204. b = arange(6) * 3
  205. r1, w1 = average([[a, b], [b, a]], axis=1, returned=True)
  206. assert_equal(shape(r1), shape(w1))
  207. assert_equal(r1.shape, w1.shape)
  208. r2, w2 = average(ones((2, 2, 3)), axis=0, weights=[3, 1], returned=True)
  209. assert_equal(shape(w2), shape(r2))
  210. r2, w2 = average(ones((2, 2, 3)), returned=True)
  211. assert_equal(shape(w2), shape(r2))
  212. r2, w2 = average(ones((2, 2, 3)), weights=ones((2, 2, 3)), returned=True)
  213. assert_equal(shape(w2), shape(r2))
  214. a2d = array([[1, 2], [0, 4]], float)
  215. a2dm = masked_array(a2d, [[False, False], [True, False]])
  216. a2da = average(a2d, axis=0)
  217. assert_equal(a2da, [0.5, 3.0])
  218. a2dma = average(a2dm, axis=0)
  219. assert_equal(a2dma, [1.0, 3.0])
  220. a2dma = average(a2dm, axis=None)
  221. assert_equal(a2dma, 7. / 3.)
  222. a2dma = average(a2dm, axis=1)
  223. assert_equal(a2dma, [1.5, 4.0])
  224. def test_testAverage4(self):
  225. # Test that `keepdims` works with average
  226. x = np.array([2, 3, 4]).reshape(3, 1)
  227. b = np.ma.array(x, mask=[[False], [False], [True]])
  228. w = np.array([4, 5, 6]).reshape(3, 1)
  229. actual = average(b, weights=w, axis=1, keepdims=True)
  230. desired = masked_array([[2.], [3.], [4.]], [[False], [False], [True]])
  231. assert_equal(actual, desired)
  232. def test_onintegers_with_mask(self):
  233. # Test average on integers with mask
  234. a = average(array([1, 2]))
  235. assert_equal(a, 1.5)
  236. a = average(array([1, 2, 3, 4], mask=[False, False, True, True]))
  237. assert_equal(a, 1.5)
  238. def test_complex(self):
  239. # Test with complex data.
  240. # (Regression test for https://github.com/numpy/numpy/issues/2684)
  241. mask = np.array([[0, 0, 0, 1, 0],
  242. [0, 1, 0, 0, 0]], dtype=bool)
  243. a = masked_array([[0, 1+2j, 3+4j, 5+6j, 7+8j],
  244. [9j, 0+1j, 2+3j, 4+5j, 7+7j]],
  245. mask=mask)
  246. av = average(a)
  247. expected = np.average(a.compressed())
  248. assert_almost_equal(av.real, expected.real)
  249. assert_almost_equal(av.imag, expected.imag)
  250. av0 = average(a, axis=0)
  251. expected0 = average(a.real, axis=0) + average(a.imag, axis=0)*1j
  252. assert_almost_equal(av0.real, expected0.real)
  253. assert_almost_equal(av0.imag, expected0.imag)
  254. av1 = average(a, axis=1)
  255. expected1 = average(a.real, axis=1) + average(a.imag, axis=1)*1j
  256. assert_almost_equal(av1.real, expected1.real)
  257. assert_almost_equal(av1.imag, expected1.imag)
  258. # Test with the 'weights' argument.
  259. wts = np.array([[0.5, 1.0, 2.0, 1.0, 0.5],
  260. [1.0, 1.0, 1.0, 1.0, 1.0]])
  261. wav = average(a, weights=wts)
  262. expected = np.average(a.compressed(), weights=wts[~mask])
  263. assert_almost_equal(wav.real, expected.real)
  264. assert_almost_equal(wav.imag, expected.imag)
  265. wav0 = average(a, weights=wts, axis=0)
  266. expected0 = (average(a.real, weights=wts, axis=0) +
  267. average(a.imag, weights=wts, axis=0)*1j)
  268. assert_almost_equal(wav0.real, expected0.real)
  269. assert_almost_equal(wav0.imag, expected0.imag)
  270. wav1 = average(a, weights=wts, axis=1)
  271. expected1 = (average(a.real, weights=wts, axis=1) +
  272. average(a.imag, weights=wts, axis=1)*1j)
  273. assert_almost_equal(wav1.real, expected1.real)
  274. assert_almost_equal(wav1.imag, expected1.imag)
  275. @pytest.mark.parametrize(
  276. 'x, axis, expected_avg, weights, expected_wavg, expected_wsum',
  277. [([1, 2, 3], None, [2.0], [3, 4, 1], [1.75], [8.0]),
  278. ([[1, 2, 5], [1, 6, 11]], 0, [[1.0, 4.0, 8.0]],
  279. [1, 3], [[1.0, 5.0, 9.5]], [[4, 4, 4]])],
  280. )
  281. def test_basic_keepdims(self, x, axis, expected_avg,
  282. weights, expected_wavg, expected_wsum):
  283. avg = np.ma.average(x, axis=axis, keepdims=True)
  284. assert avg.shape == np.shape(expected_avg)
  285. assert_array_equal(avg, expected_avg)
  286. wavg = np.ma.average(x, axis=axis, weights=weights, keepdims=True)
  287. assert wavg.shape == np.shape(expected_wavg)
  288. assert_array_equal(wavg, expected_wavg)
  289. wavg, wsum = np.ma.average(x, axis=axis, weights=weights,
  290. returned=True, keepdims=True)
  291. assert wavg.shape == np.shape(expected_wavg)
  292. assert_array_equal(wavg, expected_wavg)
  293. assert wsum.shape == np.shape(expected_wsum)
  294. assert_array_equal(wsum, expected_wsum)
  295. def test_masked_weights(self):
  296. # Test with masked weights.
  297. # (Regression test for https://github.com/numpy/numpy/issues/10438)
  298. a = np.ma.array(np.arange(9).reshape(3, 3),
  299. mask=[[1, 0, 0], [1, 0, 0], [0, 0, 0]])
  300. weights_unmasked = masked_array([5, 28, 31], mask=False)
  301. weights_masked = masked_array([5, 28, 31], mask=[1, 0, 0])
  302. avg_unmasked = average(a, axis=0,
  303. weights=weights_unmasked, returned=False)
  304. expected_unmasked = np.array([6.0, 5.21875, 6.21875])
  305. assert_almost_equal(avg_unmasked, expected_unmasked)
  306. avg_masked = average(a, axis=0, weights=weights_masked, returned=False)
  307. expected_masked = np.array([6.0, 5.576271186440678, 6.576271186440678])
  308. assert_almost_equal(avg_masked, expected_masked)
  309. # weights should be masked if needed
  310. # depending on the array mask. This is to avoid summing
  311. # masked nan or other values that are not cancelled by a zero
  312. a = np.ma.array([1.0, 2.0, 3.0, 4.0],
  313. mask=[False, False, True, True])
  314. avg_unmasked = average(a, weights=[1, 1, 1, np.nan])
  315. assert_almost_equal(avg_unmasked, 1.5)
  316. a = np.ma.array([
  317. [1.0, 2.0, 3.0, 4.0],
  318. [5.0, 6.0, 7.0, 8.0],
  319. [9.0, 1.0, 2.0, 3.0],
  320. ], mask=[
  321. [False, True, True, False],
  322. [True, False, True, True],
  323. [True, False, True, False],
  324. ])
  325. avg_masked = np.ma.average(a, weights=[1, np.nan, 1], axis=0)
  326. avg_expected = np.ma.array([1.0, np.nan, np.nan, 3.5],
  327. mask=[False, True, True, False])
  328. assert_almost_equal(avg_masked, avg_expected)
  329. assert_equal(avg_masked.mask, avg_expected.mask)
  330. class TestConcatenator:
  331. # Tests for mr_, the equivalent of r_ for masked arrays.
  332. def test_1d(self):
  333. # Tests mr_ on 1D arrays.
  334. assert_array_equal(mr_[1, 2, 3, 4, 5, 6], array([1, 2, 3, 4, 5, 6]))
  335. b = ones(5)
  336. m = [1, 0, 0, 0, 0]
  337. d = masked_array(b, mask=m)
  338. c = mr_[d, 0, 0, d]
  339. assert_(isinstance(c, MaskedArray))
  340. assert_array_equal(c, [1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1])
  341. assert_array_equal(c.mask, mr_[m, 0, 0, m])
  342. def test_2d(self):
  343. # Tests mr_ on 2D arrays.
  344. a_1 = np.random.rand(5, 5)
  345. a_2 = np.random.rand(5, 5)
  346. m_1 = np.round(np.random.rand(5, 5), 0)
  347. m_2 = np.round(np.random.rand(5, 5), 0)
  348. b_1 = masked_array(a_1, mask=m_1)
  349. b_2 = masked_array(a_2, mask=m_2)
  350. # append columns
  351. d = mr_['1', b_1, b_2]
  352. assert_(d.shape == (5, 10))
  353. assert_array_equal(d[:, :5], b_1)
  354. assert_array_equal(d[:, 5:], b_2)
  355. assert_array_equal(d.mask, np.r_['1', m_1, m_2])
  356. d = mr_[b_1, b_2]
  357. assert_(d.shape == (10, 5))
  358. assert_array_equal(d[:5,:], b_1)
  359. assert_array_equal(d[5:,:], b_2)
  360. assert_array_equal(d.mask, np.r_[m_1, m_2])
  361. def test_masked_constant(self):
  362. actual = mr_[np.ma.masked, 1]
  363. assert_equal(actual.mask, [True, False])
  364. assert_equal(actual.data[1], 1)
  365. actual = mr_[[1, 2], np.ma.masked]
  366. assert_equal(actual.mask, [False, False, True])
  367. assert_equal(actual.data[:2], [1, 2])
  368. class TestNotMasked:
  369. # Tests notmasked_edges and notmasked_contiguous.
  370. def test_edges(self):
  371. # Tests unmasked_edges
  372. data = masked_array(np.arange(25).reshape(5, 5),
  373. mask=[[0, 0, 1, 0, 0],
  374. [0, 0, 0, 1, 1],
  375. [1, 1, 0, 0, 0],
  376. [0, 0, 0, 0, 0],
  377. [1, 1, 1, 0, 0]],)
  378. test = notmasked_edges(data, None)
  379. assert_equal(test, [0, 24])
  380. test = notmasked_edges(data, 0)
  381. assert_equal(test[0], [(0, 0, 1, 0, 0), (0, 1, 2, 3, 4)])
  382. assert_equal(test[1], [(3, 3, 3, 4, 4), (0, 1, 2, 3, 4)])
  383. test = notmasked_edges(data, 1)
  384. assert_equal(test[0], [(0, 1, 2, 3, 4), (0, 0, 2, 0, 3)])
  385. assert_equal(test[1], [(0, 1, 2, 3, 4), (4, 2, 4, 4, 4)])
  386. #
  387. test = notmasked_edges(data.data, None)
  388. assert_equal(test, [0, 24])
  389. test = notmasked_edges(data.data, 0)
  390. assert_equal(test[0], [(0, 0, 0, 0, 0), (0, 1, 2, 3, 4)])
  391. assert_equal(test[1], [(4, 4, 4, 4, 4), (0, 1, 2, 3, 4)])
  392. test = notmasked_edges(data.data, -1)
  393. assert_equal(test[0], [(0, 1, 2, 3, 4), (0, 0, 0, 0, 0)])
  394. assert_equal(test[1], [(0, 1, 2, 3, 4), (4, 4, 4, 4, 4)])
  395. #
  396. data[-2] = masked
  397. test = notmasked_edges(data, 0)
  398. assert_equal(test[0], [(0, 0, 1, 0, 0), (0, 1, 2, 3, 4)])
  399. assert_equal(test[1], [(1, 1, 2, 4, 4), (0, 1, 2, 3, 4)])
  400. test = notmasked_edges(data, -1)
  401. assert_equal(test[0], [(0, 1, 2, 4), (0, 0, 2, 3)])
  402. assert_equal(test[1], [(0, 1, 2, 4), (4, 2, 4, 4)])
  403. def test_contiguous(self):
  404. # Tests notmasked_contiguous
  405. a = masked_array(np.arange(24).reshape(3, 8),
  406. mask=[[0, 0, 0, 0, 1, 1, 1, 1],
  407. [1, 1, 1, 1, 1, 1, 1, 1],
  408. [0, 0, 0, 0, 0, 0, 1, 0]])
  409. tmp = notmasked_contiguous(a, None)
  410. assert_equal(tmp, [
  411. slice(0, 4, None),
  412. slice(16, 22, None),
  413. slice(23, 24, None)
  414. ])
  415. tmp = notmasked_contiguous(a, 0)
  416. assert_equal(tmp, [
  417. [slice(0, 1, None), slice(2, 3, None)],
  418. [slice(0, 1, None), slice(2, 3, None)],
  419. [slice(0, 1, None), slice(2, 3, None)],
  420. [slice(0, 1, None), slice(2, 3, None)],
  421. [slice(2, 3, None)],
  422. [slice(2, 3, None)],
  423. [],
  424. [slice(2, 3, None)]
  425. ])
  426. #
  427. tmp = notmasked_contiguous(a, 1)
  428. assert_equal(tmp, [
  429. [slice(0, 4, None)],
  430. [],
  431. [slice(0, 6, None), slice(7, 8, None)]
  432. ])
  433. class TestCompressFunctions:
  434. def test_compress_nd(self):
  435. # Tests compress_nd
  436. x = np.array(list(range(3*4*5))).reshape(3, 4, 5)
  437. m = np.zeros((3,4,5)).astype(bool)
  438. m[1,1,1] = True
  439. x = array(x, mask=m)
  440. # axis=None
  441. a = compress_nd(x)
  442. assert_equal(a, [[[ 0, 2, 3, 4],
  443. [10, 12, 13, 14],
  444. [15, 17, 18, 19]],
  445. [[40, 42, 43, 44],
  446. [50, 52, 53, 54],
  447. [55, 57, 58, 59]]])
  448. # axis=0
  449. a = compress_nd(x, 0)
  450. assert_equal(a, [[[ 0, 1, 2, 3, 4],
  451. [ 5, 6, 7, 8, 9],
  452. [10, 11, 12, 13, 14],
  453. [15, 16, 17, 18, 19]],
  454. [[40, 41, 42, 43, 44],
  455. [45, 46, 47, 48, 49],
  456. [50, 51, 52, 53, 54],
  457. [55, 56, 57, 58, 59]]])
  458. # axis=1
  459. a = compress_nd(x, 1)
  460. assert_equal(a, [[[ 0, 1, 2, 3, 4],
  461. [10, 11, 12, 13, 14],
  462. [15, 16, 17, 18, 19]],
  463. [[20, 21, 22, 23, 24],
  464. [30, 31, 32, 33, 34],
  465. [35, 36, 37, 38, 39]],
  466. [[40, 41, 42, 43, 44],
  467. [50, 51, 52, 53, 54],
  468. [55, 56, 57, 58, 59]]])
  469. a2 = compress_nd(x, (1,))
  470. a3 = compress_nd(x, -2)
  471. a4 = compress_nd(x, (-2,))
  472. assert_equal(a, a2)
  473. assert_equal(a, a3)
  474. assert_equal(a, a4)
  475. # axis=2
  476. a = compress_nd(x, 2)
  477. assert_equal(a, [[[ 0, 2, 3, 4],
  478. [ 5, 7, 8, 9],
  479. [10, 12, 13, 14],
  480. [15, 17, 18, 19]],
  481. [[20, 22, 23, 24],
  482. [25, 27, 28, 29],
  483. [30, 32, 33, 34],
  484. [35, 37, 38, 39]],
  485. [[40, 42, 43, 44],
  486. [45, 47, 48, 49],
  487. [50, 52, 53, 54],
  488. [55, 57, 58, 59]]])
  489. a2 = compress_nd(x, (2,))
  490. a3 = compress_nd(x, -1)
  491. a4 = compress_nd(x, (-1,))
  492. assert_equal(a, a2)
  493. assert_equal(a, a3)
  494. assert_equal(a, a4)
  495. # axis=(0, 1)
  496. a = compress_nd(x, (0, 1))
  497. assert_equal(a, [[[ 0, 1, 2, 3, 4],
  498. [10, 11, 12, 13, 14],
  499. [15, 16, 17, 18, 19]],
  500. [[40, 41, 42, 43, 44],
  501. [50, 51, 52, 53, 54],
  502. [55, 56, 57, 58, 59]]])
  503. a2 = compress_nd(x, (0, -2))
  504. assert_equal(a, a2)
  505. # axis=(1, 2)
  506. a = compress_nd(x, (1, 2))
  507. assert_equal(a, [[[ 0, 2, 3, 4],
  508. [10, 12, 13, 14],
  509. [15, 17, 18, 19]],
  510. [[20, 22, 23, 24],
  511. [30, 32, 33, 34],
  512. [35, 37, 38, 39]],
  513. [[40, 42, 43, 44],
  514. [50, 52, 53, 54],
  515. [55, 57, 58, 59]]])
  516. a2 = compress_nd(x, (-2, 2))
  517. a3 = compress_nd(x, (1, -1))
  518. a4 = compress_nd(x, (-2, -1))
  519. assert_equal(a, a2)
  520. assert_equal(a, a3)
  521. assert_equal(a, a4)
  522. # axis=(0, 2)
  523. a = compress_nd(x, (0, 2))
  524. assert_equal(a, [[[ 0, 2, 3, 4],
  525. [ 5, 7, 8, 9],
  526. [10, 12, 13, 14],
  527. [15, 17, 18, 19]],
  528. [[40, 42, 43, 44],
  529. [45, 47, 48, 49],
  530. [50, 52, 53, 54],
  531. [55, 57, 58, 59]]])
  532. a2 = compress_nd(x, (0, -1))
  533. assert_equal(a, a2)
  534. def test_compress_rowcols(self):
  535. # Tests compress_rowcols
  536. x = array(np.arange(9).reshape(3, 3),
  537. mask=[[1, 0, 0], [0, 0, 0], [0, 0, 0]])
  538. assert_equal(compress_rowcols(x), [[4, 5], [7, 8]])
  539. assert_equal(compress_rowcols(x, 0), [[3, 4, 5], [6, 7, 8]])
  540. assert_equal(compress_rowcols(x, 1), [[1, 2], [4, 5], [7, 8]])
  541. x = array(x._data, mask=[[0, 0, 0], [0, 1, 0], [0, 0, 0]])
  542. assert_equal(compress_rowcols(x), [[0, 2], [6, 8]])
  543. assert_equal(compress_rowcols(x, 0), [[0, 1, 2], [6, 7, 8]])
  544. assert_equal(compress_rowcols(x, 1), [[0, 2], [3, 5], [6, 8]])
  545. x = array(x._data, mask=[[1, 0, 0], [0, 1, 0], [0, 0, 0]])
  546. assert_equal(compress_rowcols(x), [[8]])
  547. assert_equal(compress_rowcols(x, 0), [[6, 7, 8]])
  548. assert_equal(compress_rowcols(x, 1,), [[2], [5], [8]])
  549. x = array(x._data, mask=[[1, 0, 0], [0, 1, 0], [0, 0, 1]])
  550. assert_equal(compress_rowcols(x).size, 0)
  551. assert_equal(compress_rowcols(x, 0).size, 0)
  552. assert_equal(compress_rowcols(x, 1).size, 0)
  553. def test_mask_rowcols(self):
  554. # Tests mask_rowcols.
  555. x = array(np.arange(9).reshape(3, 3),
  556. mask=[[1, 0, 0], [0, 0, 0], [0, 0, 0]])
  557. assert_equal(mask_rowcols(x).mask,
  558. [[1, 1, 1], [1, 0, 0], [1, 0, 0]])
  559. assert_equal(mask_rowcols(x, 0).mask,
  560. [[1, 1, 1], [0, 0, 0], [0, 0, 0]])
  561. assert_equal(mask_rowcols(x, 1).mask,
  562. [[1, 0, 0], [1, 0, 0], [1, 0, 0]])
  563. x = array(x._data, mask=[[0, 0, 0], [0, 1, 0], [0, 0, 0]])
  564. assert_equal(mask_rowcols(x).mask,
  565. [[0, 1, 0], [1, 1, 1], [0, 1, 0]])
  566. assert_equal(mask_rowcols(x, 0).mask,
  567. [[0, 0, 0], [1, 1, 1], [0, 0, 0]])
  568. assert_equal(mask_rowcols(x, 1).mask,
  569. [[0, 1, 0], [0, 1, 0], [0, 1, 0]])
  570. x = array(x._data, mask=[[1, 0, 0], [0, 1, 0], [0, 0, 0]])
  571. assert_equal(mask_rowcols(x).mask,
  572. [[1, 1, 1], [1, 1, 1], [1, 1, 0]])
  573. assert_equal(mask_rowcols(x, 0).mask,
  574. [[1, 1, 1], [1, 1, 1], [0, 0, 0]])
  575. assert_equal(mask_rowcols(x, 1,).mask,
  576. [[1, 1, 0], [1, 1, 0], [1, 1, 0]])
  577. x = array(x._data, mask=[[1, 0, 0], [0, 1, 0], [0, 0, 1]])
  578. assert_(mask_rowcols(x).all() is masked)
  579. assert_(mask_rowcols(x, 0).all() is masked)
  580. assert_(mask_rowcols(x, 1).all() is masked)
  581. assert_(mask_rowcols(x).mask.all())
  582. assert_(mask_rowcols(x, 0).mask.all())
  583. assert_(mask_rowcols(x, 1).mask.all())
  584. @pytest.mark.parametrize("axis", [None, 0, 1])
  585. @pytest.mark.parametrize(["func", "rowcols_axis"],
  586. [(np.ma.mask_rows, 0), (np.ma.mask_cols, 1)])
  587. def test_mask_row_cols_axis_deprecation(self, axis, func, rowcols_axis):
  588. # Test deprecation of the axis argument to `mask_rows` and `mask_cols`
  589. x = array(np.arange(9).reshape(3, 3),
  590. mask=[[1, 0, 0], [0, 0, 0], [0, 0, 0]])
  591. with assert_warns(DeprecationWarning):
  592. res = func(x, axis=axis)
  593. assert_equal(res, mask_rowcols(x, rowcols_axis))
  594. def test_dot(self):
  595. # Tests dot product
  596. n = np.arange(1, 7)
  597. #
  598. m = [1, 0, 0, 0, 0, 0]
  599. a = masked_array(n, mask=m).reshape(2, 3)
  600. b = masked_array(n, mask=m).reshape(3, 2)
  601. c = dot(a, b, strict=True)
  602. assert_equal(c.mask, [[1, 1], [1, 0]])
  603. c = dot(b, a, strict=True)
  604. assert_equal(c.mask, [[1, 1, 1], [1, 0, 0], [1, 0, 0]])
  605. c = dot(a, b, strict=False)
  606. assert_equal(c, np.dot(a.filled(0), b.filled(0)))
  607. c = dot(b, a, strict=False)
  608. assert_equal(c, np.dot(b.filled(0), a.filled(0)))
  609. #
  610. m = [0, 0, 0, 0, 0, 1]
  611. a = masked_array(n, mask=m).reshape(2, 3)
  612. b = masked_array(n, mask=m).reshape(3, 2)
  613. c = dot(a, b, strict=True)
  614. assert_equal(c.mask, [[0, 1], [1, 1]])
  615. c = dot(b, a, strict=True)
  616. assert_equal(c.mask, [[0, 0, 1], [0, 0, 1], [1, 1, 1]])
  617. c = dot(a, b, strict=False)
  618. assert_equal(c, np.dot(a.filled(0), b.filled(0)))
  619. assert_equal(c, dot(a, b))
  620. c = dot(b, a, strict=False)
  621. assert_equal(c, np.dot(b.filled(0), a.filled(0)))
  622. #
  623. m = [0, 0, 0, 0, 0, 0]
  624. a = masked_array(n, mask=m).reshape(2, 3)
  625. b = masked_array(n, mask=m).reshape(3, 2)
  626. c = dot(a, b)
  627. assert_equal(c.mask, nomask)
  628. c = dot(b, a)
  629. assert_equal(c.mask, nomask)
  630. #
  631. a = masked_array(n, mask=[1, 0, 0, 0, 0, 0]).reshape(2, 3)
  632. b = masked_array(n, mask=[0, 0, 0, 0, 0, 0]).reshape(3, 2)
  633. c = dot(a, b, strict=True)
  634. assert_equal(c.mask, [[1, 1], [0, 0]])
  635. c = dot(a, b, strict=False)
  636. assert_equal(c, np.dot(a.filled(0), b.filled(0)))
  637. c = dot(b, a, strict=True)
  638. assert_equal(c.mask, [[1, 0, 0], [1, 0, 0], [1, 0, 0]])
  639. c = dot(b, a, strict=False)
  640. assert_equal(c, np.dot(b.filled(0), a.filled(0)))
  641. #
  642. a = masked_array(n, mask=[0, 0, 0, 0, 0, 1]).reshape(2, 3)
  643. b = masked_array(n, mask=[0, 0, 0, 0, 0, 0]).reshape(3, 2)
  644. c = dot(a, b, strict=True)
  645. assert_equal(c.mask, [[0, 0], [1, 1]])
  646. c = dot(a, b)
  647. assert_equal(c, np.dot(a.filled(0), b.filled(0)))
  648. c = dot(b, a, strict=True)
  649. assert_equal(c.mask, [[0, 0, 1], [0, 0, 1], [0, 0, 1]])
  650. c = dot(b, a, strict=False)
  651. assert_equal(c, np.dot(b.filled(0), a.filled(0)))
  652. #
  653. a = masked_array(n, mask=[0, 0, 0, 0, 0, 1]).reshape(2, 3)
  654. b = masked_array(n, mask=[0, 0, 1, 0, 0, 0]).reshape(3, 2)
  655. c = dot(a, b, strict=True)
  656. assert_equal(c.mask, [[1, 0], [1, 1]])
  657. c = dot(a, b, strict=False)
  658. assert_equal(c, np.dot(a.filled(0), b.filled(0)))
  659. c = dot(b, a, strict=True)
  660. assert_equal(c.mask, [[0, 0, 1], [1, 1, 1], [0, 0, 1]])
  661. c = dot(b, a, strict=False)
  662. assert_equal(c, np.dot(b.filled(0), a.filled(0)))
  663. #
  664. a = masked_array(np.arange(8).reshape(2, 2, 2),
  665. mask=[[[1, 0], [0, 0]], [[0, 0], [0, 0]]])
  666. b = masked_array(np.arange(8).reshape(2, 2, 2),
  667. mask=[[[0, 0], [0, 0]], [[0, 0], [0, 1]]])
  668. c = dot(a, b, strict=True)
  669. assert_equal(c.mask,
  670. [[[[1, 1], [1, 1]], [[0, 0], [0, 1]]],
  671. [[[0, 0], [0, 1]], [[0, 0], [0, 1]]]])
  672. c = dot(a, b, strict=False)
  673. assert_equal(c.mask,
  674. [[[[0, 0], [0, 1]], [[0, 0], [0, 0]]],
  675. [[[0, 0], [0, 0]], [[0, 0], [0, 0]]]])
  676. c = dot(b, a, strict=True)
  677. assert_equal(c.mask,
  678. [[[[1, 0], [0, 0]], [[1, 0], [0, 0]]],
  679. [[[1, 0], [0, 0]], [[1, 1], [1, 1]]]])
  680. c = dot(b, a, strict=False)
  681. assert_equal(c.mask,
  682. [[[[0, 0], [0, 0]], [[0, 0], [0, 0]]],
  683. [[[0, 0], [0, 0]], [[1, 0], [0, 0]]]])
  684. #
  685. a = masked_array(np.arange(8).reshape(2, 2, 2),
  686. mask=[[[1, 0], [0, 0]], [[0, 0], [0, 0]]])
  687. b = 5.
  688. c = dot(a, b, strict=True)
  689. assert_equal(c.mask, [[[1, 0], [0, 0]], [[0, 0], [0, 0]]])
  690. c = dot(a, b, strict=False)
  691. assert_equal(c.mask, [[[1, 0], [0, 0]], [[0, 0], [0, 0]]])
  692. c = dot(b, a, strict=True)
  693. assert_equal(c.mask, [[[1, 0], [0, 0]], [[0, 0], [0, 0]]])
  694. c = dot(b, a, strict=False)
  695. assert_equal(c.mask, [[[1, 0], [0, 0]], [[0, 0], [0, 0]]])
  696. #
  697. a = masked_array(np.arange(8).reshape(2, 2, 2),
  698. mask=[[[1, 0], [0, 0]], [[0, 0], [0, 0]]])
  699. b = masked_array(np.arange(2), mask=[0, 1])
  700. c = dot(a, b, strict=True)
  701. assert_equal(c.mask, [[1, 1], [1, 1]])
  702. c = dot(a, b, strict=False)
  703. assert_equal(c.mask, [[1, 0], [0, 0]])
  704. def test_dot_returns_maskedarray(self):
  705. # See gh-6611
  706. a = np.eye(3)
  707. b = array(a)
  708. assert_(type(dot(a, a)) is MaskedArray)
  709. assert_(type(dot(a, b)) is MaskedArray)
  710. assert_(type(dot(b, a)) is MaskedArray)
  711. assert_(type(dot(b, b)) is MaskedArray)
  712. def test_dot_out(self):
  713. a = array(np.eye(3))
  714. out = array(np.zeros((3, 3)))
  715. res = dot(a, a, out=out)
  716. assert_(res is out)
  717. assert_equal(a, res)
  718. class TestApplyAlongAxis:
  719. # Tests 2D functions
  720. def test_3d(self):
  721. a = arange(12.).reshape(2, 2, 3)
  722. def myfunc(b):
  723. return b[1]
  724. xa = apply_along_axis(myfunc, 2, a)
  725. assert_equal(xa, [[1, 4], [7, 10]])
  726. # Tests kwargs functions
  727. def test_3d_kwargs(self):
  728. a = arange(12).reshape(2, 2, 3)
  729. def myfunc(b, offset=0):
  730. return b[1+offset]
  731. xa = apply_along_axis(myfunc, 2, a, offset=1)
  732. assert_equal(xa, [[2, 5], [8, 11]])
  733. class TestApplyOverAxes:
  734. # Tests apply_over_axes
  735. def test_basic(self):
  736. a = arange(24).reshape(2, 3, 4)
  737. test = apply_over_axes(np.sum, a, [0, 2])
  738. ctrl = np.array([[[60], [92], [124]]])
  739. assert_equal(test, ctrl)
  740. a[(a % 2).astype(bool)] = masked
  741. test = apply_over_axes(np.sum, a, [0, 2])
  742. ctrl = np.array([[[28], [44], [60]]])
  743. assert_equal(test, ctrl)
  744. class TestMedian:
  745. def test_pytype(self):
  746. r = np.ma.median([[np.inf, np.inf], [np.inf, np.inf]], axis=-1)
  747. assert_equal(r, np.inf)
  748. def test_inf(self):
  749. # test that even which computes handles inf / x = masked
  750. r = np.ma.median(np.ma.masked_array([[np.inf, np.inf],
  751. [np.inf, np.inf]]), axis=-1)
  752. assert_equal(r, np.inf)
  753. r = np.ma.median(np.ma.masked_array([[np.inf, np.inf],
  754. [np.inf, np.inf]]), axis=None)
  755. assert_equal(r, np.inf)
  756. # all masked
  757. r = np.ma.median(np.ma.masked_array([[np.inf, np.inf],
  758. [np.inf, np.inf]], mask=True),
  759. axis=-1)
  760. assert_equal(r.mask, True)
  761. r = np.ma.median(np.ma.masked_array([[np.inf, np.inf],
  762. [np.inf, np.inf]], mask=True),
  763. axis=None)
  764. assert_equal(r.mask, True)
  765. def test_non_masked(self):
  766. x = np.arange(9)
  767. assert_equal(np.ma.median(x), 4.)
  768. assert_(type(np.ma.median(x)) is not MaskedArray)
  769. x = range(8)
  770. assert_equal(np.ma.median(x), 3.5)
  771. assert_(type(np.ma.median(x)) is not MaskedArray)
  772. x = 5
  773. assert_equal(np.ma.median(x), 5.)
  774. assert_(type(np.ma.median(x)) is not MaskedArray)
  775. # integer
  776. x = np.arange(9 * 8).reshape(9, 8)
  777. assert_equal(np.ma.median(x, axis=0), np.median(x, axis=0))
  778. assert_equal(np.ma.median(x, axis=1), np.median(x, axis=1))
  779. assert_(np.ma.median(x, axis=1) is not MaskedArray)
  780. # float
  781. x = np.arange(9 * 8.).reshape(9, 8)
  782. assert_equal(np.ma.median(x, axis=0), np.median(x, axis=0))
  783. assert_equal(np.ma.median(x, axis=1), np.median(x, axis=1))
  784. assert_(np.ma.median(x, axis=1) is not MaskedArray)
  785. def test_docstring_examples(self):
  786. "test the examples given in the docstring of ma.median"
  787. x = array(np.arange(8), mask=[0]*4 + [1]*4)
  788. assert_equal(np.ma.median(x), 1.5)
  789. assert_equal(np.ma.median(x).shape, (), "shape mismatch")
  790. assert_(type(np.ma.median(x)) is not MaskedArray)
  791. x = array(np.arange(10).reshape(2, 5), mask=[0]*6 + [1]*4)
  792. assert_equal(np.ma.median(x), 2.5)
  793. assert_equal(np.ma.median(x).shape, (), "shape mismatch")
  794. assert_(type(np.ma.median(x)) is not MaskedArray)
  795. ma_x = np.ma.median(x, axis=-1, overwrite_input=True)
  796. assert_equal(ma_x, [2., 5.])
  797. assert_equal(ma_x.shape, (2,), "shape mismatch")
  798. assert_(type(ma_x) is MaskedArray)
  799. def test_axis_argument_errors(self):
  800. msg = "mask = %s, ndim = %s, axis = %s, overwrite_input = %s"
  801. for ndmin in range(5):
  802. for mask in [False, True]:
  803. x = array(1, ndmin=ndmin, mask=mask)
  804. # Valid axis values should not raise exception
  805. args = itertools.product(range(-ndmin, ndmin), [False, True])
  806. for axis, over in args:
  807. try:
  808. np.ma.median(x, axis=axis, overwrite_input=over)
  809. except Exception:
  810. raise AssertionError(msg % (mask, ndmin, axis, over))
  811. # Invalid axis values should raise exception
  812. args = itertools.product([-(ndmin + 1), ndmin], [False, True])
  813. for axis, over in args:
  814. try:
  815. np.ma.median(x, axis=axis, overwrite_input=over)
  816. except np.AxisError:
  817. pass
  818. else:
  819. raise AssertionError(msg % (mask, ndmin, axis, over))
  820. def test_masked_0d(self):
  821. # Check values
  822. x = array(1, mask=False)
  823. assert_equal(np.ma.median(x), 1)
  824. x = array(1, mask=True)
  825. assert_equal(np.ma.median(x), np.ma.masked)
  826. def test_masked_1d(self):
  827. x = array(np.arange(5), mask=True)
  828. assert_equal(np.ma.median(x), np.ma.masked)
  829. assert_equal(np.ma.median(x).shape, (), "shape mismatch")
  830. assert_(type(np.ma.median(x)) is np.ma.core.MaskedConstant)
  831. x = array(np.arange(5), mask=False)
  832. assert_equal(np.ma.median(x), 2.)
  833. assert_equal(np.ma.median(x).shape, (), "shape mismatch")
  834. assert_(type(np.ma.median(x)) is not MaskedArray)
  835. x = array(np.arange(5), mask=[0,1,0,0,0])
  836. assert_equal(np.ma.median(x), 2.5)
  837. assert_equal(np.ma.median(x).shape, (), "shape mismatch")
  838. assert_(type(np.ma.median(x)) is not MaskedArray)
  839. x = array(np.arange(5), mask=[0,1,1,1,1])
  840. assert_equal(np.ma.median(x), 0.)
  841. assert_equal(np.ma.median(x).shape, (), "shape mismatch")
  842. assert_(type(np.ma.median(x)) is not MaskedArray)
  843. # integer
  844. x = array(np.arange(5), mask=[0,1,1,0,0])
  845. assert_equal(np.ma.median(x), 3.)
  846. assert_equal(np.ma.median(x).shape, (), "shape mismatch")
  847. assert_(type(np.ma.median(x)) is not MaskedArray)
  848. # float
  849. x = array(np.arange(5.), mask=[0,1,1,0,0])
  850. assert_equal(np.ma.median(x), 3.)
  851. assert_equal(np.ma.median(x).shape, (), "shape mismatch")
  852. assert_(type(np.ma.median(x)) is not MaskedArray)
  853. # integer
  854. x = array(np.arange(6), mask=[0,1,1,1,1,0])
  855. assert_equal(np.ma.median(x), 2.5)
  856. assert_equal(np.ma.median(x).shape, (), "shape mismatch")
  857. assert_(type(np.ma.median(x)) is not MaskedArray)
  858. # float
  859. x = array(np.arange(6.), mask=[0,1,1,1,1,0])
  860. assert_equal(np.ma.median(x), 2.5)
  861. assert_equal(np.ma.median(x).shape, (), "shape mismatch")
  862. assert_(type(np.ma.median(x)) is not MaskedArray)
  863. def test_1d_shape_consistency(self):
  864. assert_equal(np.ma.median(array([1,2,3],mask=[0,0,0])).shape,
  865. np.ma.median(array([1,2,3],mask=[0,1,0])).shape )
  866. def test_2d(self):
  867. # Tests median w/ 2D
  868. (n, p) = (101, 30)
  869. x = masked_array(np.linspace(-1., 1., n),)
  870. x[:10] = x[-10:] = masked
  871. z = masked_array(np.empty((n, p), dtype=float))
  872. z[:, 0] = x[:]
  873. idx = np.arange(len(x))
  874. for i in range(1, p):
  875. np.random.shuffle(idx)
  876. z[:, i] = x[idx]
  877. assert_equal(median(z[:, 0]), 0)
  878. assert_equal(median(z), 0)
  879. assert_equal(median(z, axis=0), np.zeros(p))
  880. assert_equal(median(z.T, axis=1), np.zeros(p))
  881. def test_2d_waxis(self):
  882. # Tests median w/ 2D arrays and different axis.
  883. x = masked_array(np.arange(30).reshape(10, 3))
  884. x[:3] = x[-3:] = masked
  885. assert_equal(median(x), 14.5)
  886. assert_(type(np.ma.median(x)) is not MaskedArray)
  887. assert_equal(median(x, axis=0), [13.5, 14.5, 15.5])
  888. assert_(type(np.ma.median(x, axis=0)) is MaskedArray)
  889. assert_equal(median(x, axis=1), [0, 0, 0, 10, 13, 16, 19, 0, 0, 0])
  890. assert_(type(np.ma.median(x, axis=1)) is MaskedArray)
  891. assert_equal(median(x, axis=1).mask, [1, 1, 1, 0, 0, 0, 0, 1, 1, 1])
  892. def test_3d(self):
  893. # Tests median w/ 3D
  894. x = np.ma.arange(24).reshape(3, 4, 2)
  895. x[x % 3 == 0] = masked
  896. assert_equal(median(x, 0), [[12, 9], [6, 15], [12, 9], [18, 15]])
  897. x.shape = (4, 3, 2)
  898. assert_equal(median(x, 0), [[99, 10], [11, 99], [13, 14]])
  899. x = np.ma.arange(24).reshape(4, 3, 2)
  900. x[x % 5 == 0] = masked
  901. assert_equal(median(x, 0), [[12, 10], [8, 9], [16, 17]])
  902. def test_neg_axis(self):
  903. x = masked_array(np.arange(30).reshape(10, 3))
  904. x[:3] = x[-3:] = masked
  905. assert_equal(median(x, axis=-1), median(x, axis=1))
  906. def test_out_1d(self):
  907. # integer float even odd
  908. for v in (30, 30., 31, 31.):
  909. x = masked_array(np.arange(v))
  910. x[:3] = x[-3:] = masked
  911. out = masked_array(np.ones(()))
  912. r = median(x, out=out)
  913. if v == 30:
  914. assert_equal(out, 14.5)
  915. else:
  916. assert_equal(out, 15.)
  917. assert_(r is out)
  918. assert_(type(r) is MaskedArray)
  919. def test_out(self):
  920. # integer float even odd
  921. for v in (40, 40., 30, 30.):
  922. x = masked_array(np.arange(v).reshape(10, -1))
  923. x[:3] = x[-3:] = masked
  924. out = masked_array(np.ones(10))
  925. r = median(x, axis=1, out=out)
  926. if v == 30:
  927. e = masked_array([0.]*3 + [10, 13, 16, 19] + [0.]*3,
  928. mask=[True] * 3 + [False] * 4 + [True] * 3)
  929. else:
  930. e = masked_array([0.]*3 + [13.5, 17.5, 21.5, 25.5] + [0.]*3,
  931. mask=[True]*3 + [False]*4 + [True]*3)
  932. assert_equal(r, e)
  933. assert_(r is out)
  934. assert_(type(r) is MaskedArray)
  935. @pytest.mark.parametrize(
  936. argnames='axis',
  937. argvalues=[
  938. None,
  939. 1,
  940. (1, ),
  941. (0, 1),
  942. (-3, -1),
  943. ]
  944. )
  945. def test_keepdims_out(self, axis):
  946. mask = np.zeros((3, 5, 7, 11), dtype=bool)
  947. # Randomly set some elements to True:
  948. w = np.random.random((4, 200)) * np.array(mask.shape)[:, None]
  949. w = w.astype(np.intp)
  950. mask[tuple(w)] = np.nan
  951. d = masked_array(np.ones(mask.shape), mask=mask)
  952. if axis is None:
  953. shape_out = (1,) * d.ndim
  954. else:
  955. axis_norm = normalize_axis_tuple(axis, d.ndim)
  956. shape_out = tuple(
  957. 1 if i in axis_norm else d.shape[i] for i in range(d.ndim))
  958. out = masked_array(np.empty(shape_out))
  959. result = median(d, axis=axis, keepdims=True, out=out)
  960. assert result is out
  961. assert_equal(result.shape, shape_out)
  962. def test_single_non_masked_value_on_axis(self):
  963. data = [[1., 0.],
  964. [0., 3.],
  965. [0., 0.]]
  966. masked_arr = np.ma.masked_equal(data, 0)
  967. expected = [1., 3.]
  968. assert_array_equal(np.ma.median(masked_arr, axis=0),
  969. expected)
  970. def test_nan(self):
  971. for mask in (False, np.zeros(6, dtype=bool)):
  972. dm = np.ma.array([[1, np.nan, 3], [1, 2, 3]])
  973. dm.mask = mask
  974. # scalar result
  975. r = np.ma.median(dm, axis=None)
  976. assert_(np.isscalar(r))
  977. assert_array_equal(r, np.nan)
  978. r = np.ma.median(dm.ravel(), axis=0)
  979. assert_(np.isscalar(r))
  980. assert_array_equal(r, np.nan)
  981. r = np.ma.median(dm, axis=0)
  982. assert_equal(type(r), MaskedArray)
  983. assert_array_equal(r, [1, np.nan, 3])
  984. r = np.ma.median(dm, axis=1)
  985. assert_equal(type(r), MaskedArray)
  986. assert_array_equal(r, [np.nan, 2])
  987. r = np.ma.median(dm, axis=-1)
  988. assert_equal(type(r), MaskedArray)
  989. assert_array_equal(r, [np.nan, 2])
  990. dm = np.ma.array([[1, np.nan, 3], [1, 2, 3]])
  991. dm[:, 2] = np.ma.masked
  992. assert_array_equal(np.ma.median(dm, axis=None), np.nan)
  993. assert_array_equal(np.ma.median(dm, axis=0), [1, np.nan, 3])
  994. assert_array_equal(np.ma.median(dm, axis=1), [np.nan, 1.5])
  995. def test_out_nan(self):
  996. o = np.ma.masked_array(np.zeros((4,)))
  997. d = np.ma.masked_array(np.ones((3, 4)))
  998. d[2, 1] = np.nan
  999. d[2, 2] = np.ma.masked
  1000. assert_equal(np.ma.median(d, 0, out=o), o)
  1001. o = np.ma.masked_array(np.zeros((3,)))
  1002. assert_equal(np.ma.median(d, 1, out=o), o)
  1003. o = np.ma.masked_array(np.zeros(()))
  1004. assert_equal(np.ma.median(d, out=o), o)
  1005. def test_nan_behavior(self):
  1006. a = np.ma.masked_array(np.arange(24, dtype=float))
  1007. a[::3] = np.ma.masked
  1008. a[2] = np.nan
  1009. assert_array_equal(np.ma.median(a), np.nan)
  1010. assert_array_equal(np.ma.median(a, axis=0), np.nan)
  1011. a = np.ma.masked_array(np.arange(24, dtype=float).reshape(2, 3, 4))
  1012. a.mask = np.arange(a.size) % 2 == 1
  1013. aorig = a.copy()
  1014. a[1, 2, 3] = np.nan
  1015. a[1, 1, 2] = np.nan
  1016. # no axis
  1017. assert_array_equal(np.ma.median(a), np.nan)
  1018. assert_(np.isscalar(np.ma.median(a)))
  1019. # axis0
  1020. b = np.ma.median(aorig, axis=0)
  1021. b[2, 3] = np.nan
  1022. b[1, 2] = np.nan
  1023. assert_equal(np.ma.median(a, 0), b)
  1024. # axis1
  1025. b = np.ma.median(aorig, axis=1)
  1026. b[1, 3] = np.nan
  1027. b[1, 2] = np.nan
  1028. assert_equal(np.ma.median(a, 1), b)
  1029. # axis02
  1030. b = np.ma.median(aorig, axis=(0, 2))
  1031. b[1] = np.nan
  1032. b[2] = np.nan
  1033. assert_equal(np.ma.median(a, (0, 2)), b)
  1034. def test_ambigous_fill(self):
  1035. # 255 is max value, used as filler for sort
  1036. a = np.array([[3, 3, 255], [3, 3, 255]], dtype=np.uint8)
  1037. a = np.ma.masked_array(a, mask=a == 3)
  1038. assert_array_equal(np.ma.median(a, axis=1), 255)
  1039. assert_array_equal(np.ma.median(a, axis=1).mask, False)
  1040. assert_array_equal(np.ma.median(a, axis=0), a[0])
  1041. assert_array_equal(np.ma.median(a), 255)
  1042. def test_special(self):
  1043. for inf in [np.inf, -np.inf]:
  1044. a = np.array([[inf, np.nan], [np.nan, np.nan]])
  1045. a = np.ma.masked_array(a, mask=np.isnan(a))
  1046. assert_equal(np.ma.median(a, axis=0), [inf, np.nan])
  1047. assert_equal(np.ma.median(a, axis=1), [inf, np.nan])
  1048. assert_equal(np.ma.median(a), inf)
  1049. a = np.array([[np.nan, np.nan, inf], [np.nan, np.nan, inf]])
  1050. a = np.ma.masked_array(a, mask=np.isnan(a))
  1051. assert_array_equal(np.ma.median(a, axis=1), inf)
  1052. assert_array_equal(np.ma.median(a, axis=1).mask, False)
  1053. assert_array_equal(np.ma.median(a, axis=0), a[0])
  1054. assert_array_equal(np.ma.median(a), inf)
  1055. # no mask
  1056. a = np.array([[inf, inf], [inf, inf]])
  1057. assert_equal(np.ma.median(a), inf)
  1058. assert_equal(np.ma.median(a, axis=0), inf)
  1059. assert_equal(np.ma.median(a, axis=1), inf)
  1060. a = np.array([[inf, 7, -inf, -9],
  1061. [-10, np.nan, np.nan, 5],
  1062. [4, np.nan, np.nan, inf]],
  1063. dtype=np.float32)
  1064. a = np.ma.masked_array(a, mask=np.isnan(a))
  1065. if inf > 0:
  1066. assert_equal(np.ma.median(a, axis=0), [4., 7., -inf, 5.])
  1067. assert_equal(np.ma.median(a), 4.5)
  1068. else:
  1069. assert_equal(np.ma.median(a, axis=0), [-10., 7., -inf, -9.])
  1070. assert_equal(np.ma.median(a), -2.5)
  1071. assert_equal(np.ma.median(a, axis=1), [-1., -2.5, inf])
  1072. for i in range(0, 10):
  1073. for j in range(1, 10):
  1074. a = np.array([([np.nan] * i) + ([inf] * j)] * 2)
  1075. a = np.ma.masked_array(a, mask=np.isnan(a))
  1076. assert_equal(np.ma.median(a), inf)
  1077. assert_equal(np.ma.median(a, axis=1), inf)
  1078. assert_equal(np.ma.median(a, axis=0),
  1079. ([np.nan] * i) + [inf] * j)
  1080. def test_empty(self):
  1081. # empty arrays
  1082. a = np.ma.masked_array(np.array([], dtype=float))
  1083. with suppress_warnings() as w:
  1084. w.record(RuntimeWarning)
  1085. assert_array_equal(np.ma.median(a), np.nan)
  1086. assert_(w.log[0].category is RuntimeWarning)
  1087. # multiple dimensions
  1088. a = np.ma.masked_array(np.array([], dtype=float, ndmin=3))
  1089. # no axis
  1090. with suppress_warnings() as w:
  1091. w.record(RuntimeWarning)
  1092. warnings.filterwarnings('always', '', RuntimeWarning)
  1093. assert_array_equal(np.ma.median(a), np.nan)
  1094. assert_(w.log[0].category is RuntimeWarning)
  1095. # axis 0 and 1
  1096. b = np.ma.masked_array(np.array([], dtype=float, ndmin=2))
  1097. assert_equal(np.ma.median(a, axis=0), b)
  1098. assert_equal(np.ma.median(a, axis=1), b)
  1099. # axis 2
  1100. b = np.ma.masked_array(np.array(np.nan, dtype=float, ndmin=2))
  1101. with warnings.catch_warnings(record=True) as w:
  1102. warnings.filterwarnings('always', '', RuntimeWarning)
  1103. assert_equal(np.ma.median(a, axis=2), b)
  1104. assert_(w[0].category is RuntimeWarning)
  1105. def test_object(self):
  1106. o = np.ma.masked_array(np.arange(7.))
  1107. assert_(type(np.ma.median(o.astype(object))), float)
  1108. o[2] = np.nan
  1109. assert_(type(np.ma.median(o.astype(object))), float)
  1110. class TestCov:
  1111. def setup_method(self):
  1112. self.data = array(np.random.rand(12))
  1113. def test_1d_without_missing(self):
  1114. # Test cov on 1D variable w/o missing values
  1115. x = self.data
  1116. assert_almost_equal(np.cov(x), cov(x))
  1117. assert_almost_equal(np.cov(x, rowvar=False), cov(x, rowvar=False))
  1118. assert_almost_equal(np.cov(x, rowvar=False, bias=True),
  1119. cov(x, rowvar=False, bias=True))
  1120. def test_2d_without_missing(self):
  1121. # Test cov on 1 2D variable w/o missing values
  1122. x = self.data.reshape(3, 4)
  1123. assert_almost_equal(np.cov(x), cov(x))
  1124. assert_almost_equal(np.cov(x, rowvar=False), cov(x, rowvar=False))
  1125. assert_almost_equal(np.cov(x, rowvar=False, bias=True),
  1126. cov(x, rowvar=False, bias=True))
  1127. def test_1d_with_missing(self):
  1128. # Test cov 1 1D variable w/missing values
  1129. x = self.data
  1130. x[-1] = masked
  1131. x -= x.mean()
  1132. nx = x.compressed()
  1133. assert_almost_equal(np.cov(nx), cov(x))
  1134. assert_almost_equal(np.cov(nx, rowvar=False), cov(x, rowvar=False))
  1135. assert_almost_equal(np.cov(nx, rowvar=False, bias=True),
  1136. cov(x, rowvar=False, bias=True))
  1137. #
  1138. try:
  1139. cov(x, allow_masked=False)
  1140. except ValueError:
  1141. pass
  1142. #
  1143. # 2 1D variables w/ missing values
  1144. nx = x[1:-1]
  1145. assert_almost_equal(np.cov(nx, nx[::-1]), cov(x, x[::-1]))
  1146. assert_almost_equal(np.cov(nx, nx[::-1], rowvar=False),
  1147. cov(x, x[::-1], rowvar=False))
  1148. assert_almost_equal(np.cov(nx, nx[::-1], rowvar=False, bias=True),
  1149. cov(x, x[::-1], rowvar=False, bias=True))
  1150. def test_2d_with_missing(self):
  1151. # Test cov on 2D variable w/ missing value
  1152. x = self.data
  1153. x[-1] = masked
  1154. x = x.reshape(3, 4)
  1155. valid = np.logical_not(getmaskarray(x)).astype(int)
  1156. frac = np.dot(valid, valid.T)
  1157. xf = (x - x.mean(1)[:, None]).filled(0)
  1158. assert_almost_equal(cov(x),
  1159. np.cov(xf) * (x.shape[1] - 1) / (frac - 1.))
  1160. assert_almost_equal(cov(x, bias=True),
  1161. np.cov(xf, bias=True) * x.shape[1] / frac)
  1162. frac = np.dot(valid.T, valid)
  1163. xf = (x - x.mean(0)).filled(0)
  1164. assert_almost_equal(cov(x, rowvar=False),
  1165. (np.cov(xf, rowvar=False) *
  1166. (x.shape[0] - 1) / (frac - 1.)))
  1167. assert_almost_equal(cov(x, rowvar=False, bias=True),
  1168. (np.cov(xf, rowvar=False, bias=True) *
  1169. x.shape[0] / frac))
  1170. class TestCorrcoef:
  1171. def setup_method(self):
  1172. self.data = array(np.random.rand(12))
  1173. self.data2 = array(np.random.rand(12))
  1174. def test_ddof(self):
  1175. # ddof raises DeprecationWarning
  1176. x, y = self.data, self.data2
  1177. expected = np.corrcoef(x)
  1178. expected2 = np.corrcoef(x, y)
  1179. with suppress_warnings() as sup:
  1180. warnings.simplefilter("always")
  1181. assert_warns(DeprecationWarning, corrcoef, x, ddof=-1)
  1182. sup.filter(DeprecationWarning, "bias and ddof have no effect")
  1183. # ddof has no or negligible effect on the function
  1184. assert_almost_equal(np.corrcoef(x, ddof=0), corrcoef(x, ddof=0))
  1185. assert_almost_equal(corrcoef(x, ddof=-1), expected)
  1186. assert_almost_equal(corrcoef(x, y, ddof=-1), expected2)
  1187. assert_almost_equal(corrcoef(x, ddof=3), expected)
  1188. assert_almost_equal(corrcoef(x, y, ddof=3), expected2)
  1189. def test_bias(self):
  1190. x, y = self.data, self.data2
  1191. expected = np.corrcoef(x)
  1192. # bias raises DeprecationWarning
  1193. with suppress_warnings() as sup:
  1194. warnings.simplefilter("always")
  1195. assert_warns(DeprecationWarning, corrcoef, x, y, True, False)
  1196. assert_warns(DeprecationWarning, corrcoef, x, y, True, True)
  1197. assert_warns(DeprecationWarning, corrcoef, x, bias=False)
  1198. sup.filter(DeprecationWarning, "bias and ddof have no effect")
  1199. # bias has no or negligible effect on the function
  1200. assert_almost_equal(corrcoef(x, bias=1), expected)
  1201. def test_1d_without_missing(self):
  1202. # Test cov on 1D variable w/o missing values
  1203. x = self.data
  1204. assert_almost_equal(np.corrcoef(x), corrcoef(x))
  1205. assert_almost_equal(np.corrcoef(x, rowvar=False),
  1206. corrcoef(x, rowvar=False))
  1207. with suppress_warnings() as sup:
  1208. sup.filter(DeprecationWarning, "bias and ddof have no effect")
  1209. assert_almost_equal(np.corrcoef(x, rowvar=False, bias=True),
  1210. corrcoef(x, rowvar=False, bias=True))
  1211. def test_2d_without_missing(self):
  1212. # Test corrcoef on 1 2D variable w/o missing values
  1213. x = self.data.reshape(3, 4)
  1214. assert_almost_equal(np.corrcoef(x), corrcoef(x))
  1215. assert_almost_equal(np.corrcoef(x, rowvar=False),
  1216. corrcoef(x, rowvar=False))
  1217. with suppress_warnings() as sup:
  1218. sup.filter(DeprecationWarning, "bias and ddof have no effect")
  1219. assert_almost_equal(np.corrcoef(x, rowvar=False, bias=True),
  1220. corrcoef(x, rowvar=False, bias=True))
  1221. def test_1d_with_missing(self):
  1222. # Test corrcoef 1 1D variable w/missing values
  1223. x = self.data
  1224. x[-1] = masked
  1225. x -= x.mean()
  1226. nx = x.compressed()
  1227. assert_almost_equal(np.corrcoef(nx), corrcoef(x))
  1228. assert_almost_equal(np.corrcoef(nx, rowvar=False),
  1229. corrcoef(x, rowvar=False))
  1230. with suppress_warnings() as sup:
  1231. sup.filter(DeprecationWarning, "bias and ddof have no effect")
  1232. assert_almost_equal(np.corrcoef(nx, rowvar=False, bias=True),
  1233. corrcoef(x, rowvar=False, bias=True))
  1234. try:
  1235. corrcoef(x, allow_masked=False)
  1236. except ValueError:
  1237. pass
  1238. # 2 1D variables w/ missing values
  1239. nx = x[1:-1]
  1240. assert_almost_equal(np.corrcoef(nx, nx[::-1]), corrcoef(x, x[::-1]))
  1241. assert_almost_equal(np.corrcoef(nx, nx[::-1], rowvar=False),
  1242. corrcoef(x, x[::-1], rowvar=False))
  1243. with suppress_warnings() as sup:
  1244. sup.filter(DeprecationWarning, "bias and ddof have no effect")
  1245. # ddof and bias have no or negligible effect on the function
  1246. assert_almost_equal(np.corrcoef(nx, nx[::-1]),
  1247. corrcoef(x, x[::-1], bias=1))
  1248. assert_almost_equal(np.corrcoef(nx, nx[::-1]),
  1249. corrcoef(x, x[::-1], ddof=2))
  1250. def test_2d_with_missing(self):
  1251. # Test corrcoef on 2D variable w/ missing value
  1252. x = self.data
  1253. x[-1] = masked
  1254. x = x.reshape(3, 4)
  1255. test = corrcoef(x)
  1256. control = np.corrcoef(x)
  1257. assert_almost_equal(test[:-1, :-1], control[:-1, :-1])
  1258. with suppress_warnings() as sup:
  1259. sup.filter(DeprecationWarning, "bias and ddof have no effect")
  1260. # ddof and bias have no or negligible effect on the function
  1261. assert_almost_equal(corrcoef(x, ddof=-2)[:-1, :-1],
  1262. control[:-1, :-1])
  1263. assert_almost_equal(corrcoef(x, ddof=3)[:-1, :-1],
  1264. control[:-1, :-1])
  1265. assert_almost_equal(corrcoef(x, bias=1)[:-1, :-1],
  1266. control[:-1, :-1])
  1267. class TestPolynomial:
  1268. #
  1269. def test_polyfit(self):
  1270. # Tests polyfit
  1271. # On ndarrays
  1272. x = np.random.rand(10)
  1273. y = np.random.rand(20).reshape(-1, 2)
  1274. assert_almost_equal(polyfit(x, y, 3), np.polyfit(x, y, 3))
  1275. # ON 1D maskedarrays
  1276. x = x.view(MaskedArray)
  1277. x[0] = masked
  1278. y = y.view(MaskedArray)
  1279. y[0, 0] = y[-1, -1] = masked
  1280. #
  1281. (C, R, K, S, D) = polyfit(x, y[:, 0], 3, full=True)
  1282. (c, r, k, s, d) = np.polyfit(x[1:], y[1:, 0].compressed(), 3,
  1283. full=True)
  1284. for (a, a_) in zip((C, R, K, S, D), (c, r, k, s, d)):
  1285. assert_almost_equal(a, a_)
  1286. #
  1287. (C, R, K, S, D) = polyfit(x, y[:, -1], 3, full=True)
  1288. (c, r, k, s, d) = np.polyfit(x[1:-1], y[1:-1, -1], 3, full=True)
  1289. for (a, a_) in zip((C, R, K, S, D), (c, r, k, s, d)):
  1290. assert_almost_equal(a, a_)
  1291. #
  1292. (C, R, K, S, D) = polyfit(x, y, 3, full=True)
  1293. (c, r, k, s, d) = np.polyfit(x[1:-1], y[1:-1,:], 3, full=True)
  1294. for (a, a_) in zip((C, R, K, S, D), (c, r, k, s, d)):
  1295. assert_almost_equal(a, a_)
  1296. #
  1297. w = np.random.rand(10) + 1
  1298. wo = w.copy()
  1299. xs = x[1:-1]
  1300. ys = y[1:-1]
  1301. ws = w[1:-1]
  1302. (C, R, K, S, D) = polyfit(x, y, 3, full=True, w=w)
  1303. (c, r, k, s, d) = np.polyfit(xs, ys, 3, full=True, w=ws)
  1304. assert_equal(w, wo)
  1305. for (a, a_) in zip((C, R, K, S, D), (c, r, k, s, d)):
  1306. assert_almost_equal(a, a_)
  1307. def test_polyfit_with_masked_NaNs(self):
  1308. x = np.random.rand(10)
  1309. y = np.random.rand(20).reshape(-1, 2)
  1310. x[0] = np.nan
  1311. y[-1,-1] = np.nan
  1312. x = x.view(MaskedArray)
  1313. y = y.view(MaskedArray)
  1314. x[0] = masked
  1315. y[-1,-1] = masked
  1316. (C, R, K, S, D) = polyfit(x, y, 3, full=True)
  1317. (c, r, k, s, d) = np.polyfit(x[1:-1], y[1:-1,:], 3, full=True)
  1318. for (a, a_) in zip((C, R, K, S, D), (c, r, k, s, d)):
  1319. assert_almost_equal(a, a_)
  1320. class TestArraySetOps:
  1321. def test_unique_onlist(self):
  1322. # Test unique on list
  1323. data = [1, 1, 1, 2, 2, 3]
  1324. test = unique(data, return_index=True, return_inverse=True)
  1325. assert_(isinstance(test[0], MaskedArray))
  1326. assert_equal(test[0], masked_array([1, 2, 3], mask=[0, 0, 0]))
  1327. assert_equal(test[1], [0, 3, 5])
  1328. assert_equal(test[2], [0, 0, 0, 1, 1, 2])
  1329. def test_unique_onmaskedarray(self):
  1330. # Test unique on masked data w/use_mask=True
  1331. data = masked_array([1, 1, 1, 2, 2, 3], mask=[0, 0, 1, 0, 1, 0])
  1332. test = unique(data, return_index=True, return_inverse=True)
  1333. assert_equal(test[0], masked_array([1, 2, 3, -1], mask=[0, 0, 0, 1]))
  1334. assert_equal(test[1], [0, 3, 5, 2])
  1335. assert_equal(test[2], [0, 0, 3, 1, 3, 2])
  1336. #
  1337. data.fill_value = 3
  1338. data = masked_array(data=[1, 1, 1, 2, 2, 3],
  1339. mask=[0, 0, 1, 0, 1, 0], fill_value=3)
  1340. test = unique(data, return_index=True, return_inverse=True)
  1341. assert_equal(test[0], masked_array([1, 2, 3, -1], mask=[0, 0, 0, 1]))
  1342. assert_equal(test[1], [0, 3, 5, 2])
  1343. assert_equal(test[2], [0, 0, 3, 1, 3, 2])
  1344. def test_unique_allmasked(self):
  1345. # Test all masked
  1346. data = masked_array([1, 1, 1], mask=True)
  1347. test = unique(data, return_index=True, return_inverse=True)
  1348. assert_equal(test[0], masked_array([1, ], mask=[True]))
  1349. assert_equal(test[1], [0])
  1350. assert_equal(test[2], [0, 0, 0])
  1351. #
  1352. # Test masked
  1353. data = masked
  1354. test = unique(data, return_index=True, return_inverse=True)
  1355. assert_equal(test[0], masked_array(masked))
  1356. assert_equal(test[1], [0])
  1357. assert_equal(test[2], [0])
  1358. def test_ediff1d(self):
  1359. # Tests mediff1d
  1360. x = masked_array(np.arange(5), mask=[1, 0, 0, 0, 1])
  1361. control = array([1, 1, 1, 4], mask=[1, 0, 0, 1])
  1362. test = ediff1d(x)
  1363. assert_equal(test, control)
  1364. assert_equal(test.filled(0), control.filled(0))
  1365. assert_equal(test.mask, control.mask)
  1366. def test_ediff1d_tobegin(self):
  1367. # Test ediff1d w/ to_begin
  1368. x = masked_array(np.arange(5), mask=[1, 0, 0, 0, 1])
  1369. test = ediff1d(x, to_begin=masked)
  1370. control = array([0, 1, 1, 1, 4], mask=[1, 1, 0, 0, 1])
  1371. assert_equal(test, control)
  1372. assert_equal(test.filled(0), control.filled(0))
  1373. assert_equal(test.mask, control.mask)
  1374. #
  1375. test = ediff1d(x, to_begin=[1, 2, 3])
  1376. control = array([1, 2, 3, 1, 1, 1, 4], mask=[0, 0, 0, 1, 0, 0, 1])
  1377. assert_equal(test, control)
  1378. assert_equal(test.filled(0), control.filled(0))
  1379. assert_equal(test.mask, control.mask)
  1380. def test_ediff1d_toend(self):
  1381. # Test ediff1d w/ to_end
  1382. x = masked_array(np.arange(5), mask=[1, 0, 0, 0, 1])
  1383. test = ediff1d(x, to_end=masked)
  1384. control = array([1, 1, 1, 4, 0], mask=[1, 0, 0, 1, 1])
  1385. assert_equal(test, control)
  1386. assert_equal(test.filled(0), control.filled(0))
  1387. assert_equal(test.mask, control.mask)
  1388. #
  1389. test = ediff1d(x, to_end=[1, 2, 3])
  1390. control = array([1, 1, 1, 4, 1, 2, 3], mask=[1, 0, 0, 1, 0, 0, 0])
  1391. assert_equal(test, control)
  1392. assert_equal(test.filled(0), control.filled(0))
  1393. assert_equal(test.mask, control.mask)
  1394. def test_ediff1d_tobegin_toend(self):
  1395. # Test ediff1d w/ to_begin and to_end
  1396. x = masked_array(np.arange(5), mask=[1, 0, 0, 0, 1])
  1397. test = ediff1d(x, to_end=masked, to_begin=masked)
  1398. control = array([0, 1, 1, 1, 4, 0], mask=[1, 1, 0, 0, 1, 1])
  1399. assert_equal(test, control)
  1400. assert_equal(test.filled(0), control.filled(0))
  1401. assert_equal(test.mask, control.mask)
  1402. #
  1403. test = ediff1d(x, to_end=[1, 2, 3], to_begin=masked)
  1404. control = array([0, 1, 1, 1, 4, 1, 2, 3],
  1405. mask=[1, 1, 0, 0, 1, 0, 0, 0])
  1406. assert_equal(test, control)
  1407. assert_equal(test.filled(0), control.filled(0))
  1408. assert_equal(test.mask, control.mask)
  1409. def test_ediff1d_ndarray(self):
  1410. # Test ediff1d w/ a ndarray
  1411. x = np.arange(5)
  1412. test = ediff1d(x)
  1413. control = array([1, 1, 1, 1], mask=[0, 0, 0, 0])
  1414. assert_equal(test, control)
  1415. assert_(isinstance(test, MaskedArray))
  1416. assert_equal(test.filled(0), control.filled(0))
  1417. assert_equal(test.mask, control.mask)
  1418. #
  1419. test = ediff1d(x, to_end=masked, to_begin=masked)
  1420. control = array([0, 1, 1, 1, 1, 0], mask=[1, 0, 0, 0, 0, 1])
  1421. assert_(isinstance(test, MaskedArray))
  1422. assert_equal(test.filled(0), control.filled(0))
  1423. assert_equal(test.mask, control.mask)
  1424. def test_intersect1d(self):
  1425. # Test intersect1d
  1426. x = array([1, 3, 3, 3], mask=[0, 0, 0, 1])
  1427. y = array([3, 1, 1, 1], mask=[0, 0, 0, 1])
  1428. test = intersect1d(x, y)
  1429. control = array([1, 3, -1], mask=[0, 0, 1])
  1430. assert_equal(test, control)
  1431. def test_setxor1d(self):
  1432. # Test setxor1d
  1433. a = array([1, 2, 5, 7, -1], mask=[0, 0, 0, 0, 1])
  1434. b = array([1, 2, 3, 4, 5, -1], mask=[0, 0, 0, 0, 0, 1])
  1435. test = setxor1d(a, b)
  1436. assert_equal(test, array([3, 4, 7]))
  1437. #
  1438. a = array([1, 2, 5, 7, -1], mask=[0, 0, 0, 0, 1])
  1439. b = [1, 2, 3, 4, 5]
  1440. test = setxor1d(a, b)
  1441. assert_equal(test, array([3, 4, 7, -1], mask=[0, 0, 0, 1]))
  1442. #
  1443. a = array([1, 2, 3])
  1444. b = array([6, 5, 4])
  1445. test = setxor1d(a, b)
  1446. assert_(isinstance(test, MaskedArray))
  1447. assert_equal(test, [1, 2, 3, 4, 5, 6])
  1448. #
  1449. a = array([1, 8, 2, 3], mask=[0, 1, 0, 0])
  1450. b = array([6, 5, 4, 8], mask=[0, 0, 0, 1])
  1451. test = setxor1d(a, b)
  1452. assert_(isinstance(test, MaskedArray))
  1453. assert_equal(test, [1, 2, 3, 4, 5, 6])
  1454. #
  1455. assert_array_equal([], setxor1d([], []))
  1456. def test_isin(self):
  1457. # the tests for in1d cover most of isin's behavior
  1458. # if in1d is removed, would need to change those tests to test
  1459. # isin instead.
  1460. a = np.arange(24).reshape([2, 3, 4])
  1461. mask = np.zeros([2, 3, 4])
  1462. mask[1, 2, 0] = 1
  1463. a = array(a, mask=mask)
  1464. b = array(data=[0, 10, 20, 30, 1, 3, 11, 22, 33],
  1465. mask=[0, 1, 0, 1, 0, 1, 0, 1, 0])
  1466. ec = zeros((2, 3, 4), dtype=bool)
  1467. ec[0, 0, 0] = True
  1468. ec[0, 0, 1] = True
  1469. ec[0, 2, 3] = True
  1470. c = isin(a, b)
  1471. assert_(isinstance(c, MaskedArray))
  1472. assert_array_equal(c, ec)
  1473. #compare results of np.isin to ma.isin
  1474. d = np.isin(a, b[~b.mask]) & ~a.mask
  1475. assert_array_equal(c, d)
  1476. def test_in1d(self):
  1477. # Test in1d
  1478. a = array([1, 2, 5, 7, -1], mask=[0, 0, 0, 0, 1])
  1479. b = array([1, 2, 3, 4, 5, -1], mask=[0, 0, 0, 0, 0, 1])
  1480. test = in1d(a, b)
  1481. assert_equal(test, [True, True, True, False, True])
  1482. #
  1483. a = array([5, 5, 2, 1, -1], mask=[0, 0, 0, 0, 1])
  1484. b = array([1, 5, -1], mask=[0, 0, 1])
  1485. test = in1d(a, b)
  1486. assert_equal(test, [True, True, False, True, True])
  1487. #
  1488. assert_array_equal([], in1d([], []))
  1489. def test_in1d_invert(self):
  1490. # Test in1d's invert parameter
  1491. a = array([1, 2, 5, 7, -1], mask=[0, 0, 0, 0, 1])
  1492. b = array([1, 2, 3, 4, 5, -1], mask=[0, 0, 0, 0, 0, 1])
  1493. assert_equal(np.invert(in1d(a, b)), in1d(a, b, invert=True))
  1494. a = array([5, 5, 2, 1, -1], mask=[0, 0, 0, 0, 1])
  1495. b = array([1, 5, -1], mask=[0, 0, 1])
  1496. assert_equal(np.invert(in1d(a, b)), in1d(a, b, invert=True))
  1497. assert_array_equal([], in1d([], [], invert=True))
  1498. def test_union1d(self):
  1499. # Test union1d
  1500. a = array([1, 2, 5, 7, 5, -1], mask=[0, 0, 0, 0, 0, 1])
  1501. b = array([1, 2, 3, 4, 5, -1], mask=[0, 0, 0, 0, 0, 1])
  1502. test = union1d(a, b)
  1503. control = array([1, 2, 3, 4, 5, 7, -1], mask=[0, 0, 0, 0, 0, 0, 1])
  1504. assert_equal(test, control)
  1505. # Tests gh-10340, arguments to union1d should be
  1506. # flattened if they are not already 1D
  1507. x = array([[0, 1, 2], [3, 4, 5]], mask=[[0, 0, 0], [0, 0, 1]])
  1508. y = array([0, 1, 2, 3, 4], mask=[0, 0, 0, 0, 1])
  1509. ez = array([0, 1, 2, 3, 4, 5], mask=[0, 0, 0, 0, 0, 1])
  1510. z = union1d(x, y)
  1511. assert_equal(z, ez)
  1512. #
  1513. assert_array_equal([], union1d([], []))
  1514. def test_setdiff1d(self):
  1515. # Test setdiff1d
  1516. a = array([6, 5, 4, 7, 7, 1, 2, 1], mask=[0, 0, 0, 0, 0, 0, 0, 1])
  1517. b = array([2, 4, 3, 3, 2, 1, 5])
  1518. test = setdiff1d(a, b)
  1519. assert_equal(test, array([6, 7, -1], mask=[0, 0, 1]))
  1520. #
  1521. a = arange(10)
  1522. b = arange(8)
  1523. assert_equal(setdiff1d(a, b), array([8, 9]))
  1524. a = array([], np.uint32, mask=[])
  1525. assert_equal(setdiff1d(a, []).dtype, np.uint32)
  1526. def test_setdiff1d_char_array(self):
  1527. # Test setdiff1d_charray
  1528. a = np.array(['a', 'b', 'c'])
  1529. b = np.array(['a', 'b', 's'])
  1530. assert_array_equal(setdiff1d(a, b), np.array(['c']))
  1531. class TestShapeBase:
  1532. def test_atleast_2d(self):
  1533. # Test atleast_2d
  1534. a = masked_array([0, 1, 2], mask=[0, 1, 0])
  1535. b = atleast_2d(a)
  1536. assert_equal(b.shape, (1, 3))
  1537. assert_equal(b.mask.shape, b.data.shape)
  1538. assert_equal(a.shape, (3,))
  1539. assert_equal(a.mask.shape, a.data.shape)
  1540. assert_equal(b.mask.shape, b.data.shape)
  1541. def test_shape_scalar(self):
  1542. # the atleast and diagflat function should work with scalars
  1543. # GitHub issue #3367
  1544. # Additionally, the atleast functions should accept multiple scalars
  1545. # correctly
  1546. b = atleast_1d(1.0)
  1547. assert_equal(b.shape, (1,))
  1548. assert_equal(b.mask.shape, b.shape)
  1549. assert_equal(b.data.shape, b.shape)
  1550. b = atleast_1d(1.0, 2.0)
  1551. for a in b:
  1552. assert_equal(a.shape, (1,))
  1553. assert_equal(a.mask.shape, a.shape)
  1554. assert_equal(a.data.shape, a.shape)
  1555. b = atleast_2d(1.0)
  1556. assert_equal(b.shape, (1, 1))
  1557. assert_equal(b.mask.shape, b.shape)
  1558. assert_equal(b.data.shape, b.shape)
  1559. b = atleast_2d(1.0, 2.0)
  1560. for a in b:
  1561. assert_equal(a.shape, (1, 1))
  1562. assert_equal(a.mask.shape, a.shape)
  1563. assert_equal(a.data.shape, a.shape)
  1564. b = atleast_3d(1.0)
  1565. assert_equal(b.shape, (1, 1, 1))
  1566. assert_equal(b.mask.shape, b.shape)
  1567. assert_equal(b.data.shape, b.shape)
  1568. b = atleast_3d(1.0, 2.0)
  1569. for a in b:
  1570. assert_equal(a.shape, (1, 1, 1))
  1571. assert_equal(a.mask.shape, a.shape)
  1572. assert_equal(a.data.shape, a.shape)
  1573. b = diagflat(1.0)
  1574. assert_equal(b.shape, (1, 1))
  1575. assert_equal(b.mask.shape, b.data.shape)
  1576. class TestNDEnumerate:
  1577. def test_ndenumerate_nomasked(self):
  1578. ordinary = np.arange(6.).reshape((1, 3, 2))
  1579. empty_mask = np.zeros_like(ordinary, dtype=bool)
  1580. with_mask = masked_array(ordinary, mask=empty_mask)
  1581. assert_equal(list(np.ndenumerate(ordinary)),
  1582. list(ndenumerate(ordinary)))
  1583. assert_equal(list(ndenumerate(ordinary)),
  1584. list(ndenumerate(with_mask)))
  1585. assert_equal(list(ndenumerate(with_mask)),
  1586. list(ndenumerate(with_mask, compressed=False)))
  1587. def test_ndenumerate_allmasked(self):
  1588. a = masked_all(())
  1589. b = masked_all((100,))
  1590. c = masked_all((2, 3, 4))
  1591. assert_equal(list(ndenumerate(a)), [])
  1592. assert_equal(list(ndenumerate(b)), [])
  1593. assert_equal(list(ndenumerate(b, compressed=False)),
  1594. list(zip(np.ndindex((100,)), 100 * [masked])))
  1595. assert_equal(list(ndenumerate(c)), [])
  1596. assert_equal(list(ndenumerate(c, compressed=False)),
  1597. list(zip(np.ndindex((2, 3, 4)), 2 * 3 * 4 * [masked])))
  1598. def test_ndenumerate_mixedmasked(self):
  1599. a = masked_array(np.arange(12).reshape((3, 4)),
  1600. mask=[[1, 1, 1, 1],
  1601. [1, 1, 0, 1],
  1602. [0, 0, 0, 0]])
  1603. items = [((1, 2), 6),
  1604. ((2, 0), 8), ((2, 1), 9), ((2, 2), 10), ((2, 3), 11)]
  1605. assert_equal(list(ndenumerate(a)), items)
  1606. assert_equal(len(list(ndenumerate(a, compressed=False))), a.size)
  1607. for coordinate, value in ndenumerate(a, compressed=False):
  1608. assert_equal(a[coordinate], value)
  1609. class TestStack:
  1610. def test_stack_1d(self):
  1611. a = masked_array([0, 1, 2], mask=[0, 1, 0])
  1612. b = masked_array([9, 8, 7], mask=[1, 0, 0])
  1613. c = stack([a, b], axis=0)
  1614. assert_equal(c.shape, (2, 3))
  1615. assert_array_equal(a.mask, c[0].mask)
  1616. assert_array_equal(b.mask, c[1].mask)
  1617. d = vstack([a, b])
  1618. assert_array_equal(c.data, d.data)
  1619. assert_array_equal(c.mask, d.mask)
  1620. c = stack([a, b], axis=1)
  1621. assert_equal(c.shape, (3, 2))
  1622. assert_array_equal(a.mask, c[:, 0].mask)
  1623. assert_array_equal(b.mask, c[:, 1].mask)
  1624. def test_stack_masks(self):
  1625. a = masked_array([0, 1, 2], mask=True)
  1626. b = masked_array([9, 8, 7], mask=False)
  1627. c = stack([a, b], axis=0)
  1628. assert_equal(c.shape, (2, 3))
  1629. assert_array_equal(a.mask, c[0].mask)
  1630. assert_array_equal(b.mask, c[1].mask)
  1631. d = vstack([a, b])
  1632. assert_array_equal(c.data, d.data)
  1633. assert_array_equal(c.mask, d.mask)
  1634. c = stack([a, b], axis=1)
  1635. assert_equal(c.shape, (3, 2))
  1636. assert_array_equal(a.mask, c[:, 0].mask)
  1637. assert_array_equal(b.mask, c[:, 1].mask)
  1638. def test_stack_nd(self):
  1639. # 2D
  1640. shp = (3, 2)
  1641. d1 = np.random.randint(0, 10, shp)
  1642. d2 = np.random.randint(0, 10, shp)
  1643. m1 = np.random.randint(0, 2, shp).astype(bool)
  1644. m2 = np.random.randint(0, 2, shp).astype(bool)
  1645. a1 = masked_array(d1, mask=m1)
  1646. a2 = masked_array(d2, mask=m2)
  1647. c = stack([a1, a2], axis=0)
  1648. c_shp = (2,) + shp
  1649. assert_equal(c.shape, c_shp)
  1650. assert_array_equal(a1.mask, c[0].mask)
  1651. assert_array_equal(a2.mask, c[1].mask)
  1652. c = stack([a1, a2], axis=-1)
  1653. c_shp = shp + (2,)
  1654. assert_equal(c.shape, c_shp)
  1655. assert_array_equal(a1.mask, c[..., 0].mask)
  1656. assert_array_equal(a2.mask, c[..., 1].mask)
  1657. # 4D
  1658. shp = (3, 2, 4, 5,)
  1659. d1 = np.random.randint(0, 10, shp)
  1660. d2 = np.random.randint(0, 10, shp)
  1661. m1 = np.random.randint(0, 2, shp).astype(bool)
  1662. m2 = np.random.randint(0, 2, shp).astype(bool)
  1663. a1 = masked_array(d1, mask=m1)
  1664. a2 = masked_array(d2, mask=m2)
  1665. c = stack([a1, a2], axis=0)
  1666. c_shp = (2,) + shp
  1667. assert_equal(c.shape, c_shp)
  1668. assert_array_equal(a1.mask, c[0].mask)
  1669. assert_array_equal(a2.mask, c[1].mask)
  1670. c = stack([a1, a2], axis=-1)
  1671. c_shp = shp + (2,)
  1672. assert_equal(c.shape, c_shp)
  1673. assert_array_equal(a1.mask, c[..., 0].mask)
  1674. assert_array_equal(a2.mask, c[..., 1].mask)