test_extras.py 76 KB

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