test_extras.py 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829
  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. def test_dot_returns_maskedarray(self):
  664. # See gh-6611
  665. a = np.eye(3)
  666. b = array(a)
  667. assert_(type(dot(a, a)) is MaskedArray)
  668. assert_(type(dot(a, b)) is MaskedArray)
  669. assert_(type(dot(b, a)) is MaskedArray)
  670. assert_(type(dot(b, b)) is MaskedArray)
  671. def test_dot_out(self):
  672. a = array(np.eye(3))
  673. out = array(np.zeros((3, 3)))
  674. res = dot(a, a, out=out)
  675. assert_(res is out)
  676. assert_equal(a, res)
  677. class TestApplyAlongAxis:
  678. # Tests 2D functions
  679. def test_3d(self):
  680. a = arange(12.).reshape(2, 2, 3)
  681. def myfunc(b):
  682. return b[1]
  683. xa = apply_along_axis(myfunc, 2, a)
  684. assert_equal(xa, [[1, 4], [7, 10]])
  685. # Tests kwargs functions
  686. def test_3d_kwargs(self):
  687. a = arange(12).reshape(2, 2, 3)
  688. def myfunc(b, offset=0):
  689. return b[1+offset]
  690. xa = apply_along_axis(myfunc, 2, a, offset=1)
  691. assert_equal(xa, [[2, 5], [8, 11]])
  692. class TestApplyOverAxes:
  693. # Tests apply_over_axes
  694. def test_basic(self):
  695. a = arange(24).reshape(2, 3, 4)
  696. test = apply_over_axes(np.sum, a, [0, 2])
  697. ctrl = np.array([[[60], [92], [124]]])
  698. assert_equal(test, ctrl)
  699. a[(a % 2).astype(bool)] = masked
  700. test = apply_over_axes(np.sum, a, [0, 2])
  701. ctrl = np.array([[[28], [44], [60]]])
  702. assert_equal(test, ctrl)
  703. class TestMedian:
  704. def test_pytype(self):
  705. r = np.ma.median([[np.inf, np.inf], [np.inf, np.inf]], axis=-1)
  706. assert_equal(r, np.inf)
  707. def test_inf(self):
  708. # test that even which computes handles inf / x = masked
  709. r = np.ma.median(np.ma.masked_array([[np.inf, np.inf],
  710. [np.inf, np.inf]]), axis=-1)
  711. assert_equal(r, np.inf)
  712. r = np.ma.median(np.ma.masked_array([[np.inf, np.inf],
  713. [np.inf, np.inf]]), axis=None)
  714. assert_equal(r, np.inf)
  715. # all masked
  716. r = np.ma.median(np.ma.masked_array([[np.inf, np.inf],
  717. [np.inf, np.inf]], mask=True),
  718. axis=-1)
  719. assert_equal(r.mask, True)
  720. r = np.ma.median(np.ma.masked_array([[np.inf, np.inf],
  721. [np.inf, np.inf]], mask=True),
  722. axis=None)
  723. assert_equal(r.mask, True)
  724. def test_non_masked(self):
  725. x = np.arange(9)
  726. assert_equal(np.ma.median(x), 4.)
  727. assert_(type(np.ma.median(x)) is not MaskedArray)
  728. x = range(8)
  729. assert_equal(np.ma.median(x), 3.5)
  730. assert_(type(np.ma.median(x)) is not MaskedArray)
  731. x = 5
  732. assert_equal(np.ma.median(x), 5.)
  733. assert_(type(np.ma.median(x)) is not MaskedArray)
  734. # integer
  735. x = np.arange(9 * 8).reshape(9, 8)
  736. assert_equal(np.ma.median(x, axis=0), np.median(x, axis=0))
  737. assert_equal(np.ma.median(x, axis=1), np.median(x, axis=1))
  738. assert_(np.ma.median(x, axis=1) is not MaskedArray)
  739. # float
  740. x = np.arange(9 * 8.).reshape(9, 8)
  741. assert_equal(np.ma.median(x, axis=0), np.median(x, axis=0))
  742. assert_equal(np.ma.median(x, axis=1), np.median(x, axis=1))
  743. assert_(np.ma.median(x, axis=1) is not MaskedArray)
  744. def test_docstring_examples(self):
  745. "test the examples given in the docstring of ma.median"
  746. x = array(np.arange(8), mask=[0]*4 + [1]*4)
  747. assert_equal(np.ma.median(x), 1.5)
  748. assert_equal(np.ma.median(x).shape, (), "shape mismatch")
  749. assert_(type(np.ma.median(x)) is not MaskedArray)
  750. x = array(np.arange(10).reshape(2, 5), mask=[0]*6 + [1]*4)
  751. assert_equal(np.ma.median(x), 2.5)
  752. assert_equal(np.ma.median(x).shape, (), "shape mismatch")
  753. assert_(type(np.ma.median(x)) is not MaskedArray)
  754. ma_x = np.ma.median(x, axis=-1, overwrite_input=True)
  755. assert_equal(ma_x, [2., 5.])
  756. assert_equal(ma_x.shape, (2,), "shape mismatch")
  757. assert_(type(ma_x) is MaskedArray)
  758. def test_axis_argument_errors(self):
  759. msg = "mask = %s, ndim = %s, axis = %s, overwrite_input = %s"
  760. for ndmin in range(5):
  761. for mask in [False, True]:
  762. x = array(1, ndmin=ndmin, mask=mask)
  763. # Valid axis values should not raise exception
  764. args = itertools.product(range(-ndmin, ndmin), [False, True])
  765. for axis, over in args:
  766. try:
  767. np.ma.median(x, axis=axis, overwrite_input=over)
  768. except Exception:
  769. raise AssertionError(msg % (mask, ndmin, axis, over))
  770. # Invalid axis values should raise exception
  771. args = itertools.product([-(ndmin + 1), ndmin], [False, True])
  772. for axis, over in args:
  773. try:
  774. np.ma.median(x, axis=axis, overwrite_input=over)
  775. except np.AxisError:
  776. pass
  777. else:
  778. raise AssertionError(msg % (mask, ndmin, axis, over))
  779. def test_masked_0d(self):
  780. # Check values
  781. x = array(1, mask=False)
  782. assert_equal(np.ma.median(x), 1)
  783. x = array(1, mask=True)
  784. assert_equal(np.ma.median(x), np.ma.masked)
  785. def test_masked_1d(self):
  786. x = array(np.arange(5), mask=True)
  787. assert_equal(np.ma.median(x), np.ma.masked)
  788. assert_equal(np.ma.median(x).shape, (), "shape mismatch")
  789. assert_(type(np.ma.median(x)) is np.ma.core.MaskedConstant)
  790. x = array(np.arange(5), mask=False)
  791. assert_equal(np.ma.median(x), 2.)
  792. assert_equal(np.ma.median(x).shape, (), "shape mismatch")
  793. assert_(type(np.ma.median(x)) is not MaskedArray)
  794. x = array(np.arange(5), mask=[0,1,0,0,0])
  795. assert_equal(np.ma.median(x), 2.5)
  796. assert_equal(np.ma.median(x).shape, (), "shape mismatch")
  797. assert_(type(np.ma.median(x)) is not MaskedArray)
  798. x = array(np.arange(5), mask=[0,1,1,1,1])
  799. assert_equal(np.ma.median(x), 0.)
  800. assert_equal(np.ma.median(x).shape, (), "shape mismatch")
  801. assert_(type(np.ma.median(x)) is not MaskedArray)
  802. # integer
  803. x = array(np.arange(5), mask=[0,1,1,0,0])
  804. assert_equal(np.ma.median(x), 3.)
  805. assert_equal(np.ma.median(x).shape, (), "shape mismatch")
  806. assert_(type(np.ma.median(x)) is not MaskedArray)
  807. # float
  808. x = array(np.arange(5.), mask=[0,1,1,0,0])
  809. assert_equal(np.ma.median(x), 3.)
  810. assert_equal(np.ma.median(x).shape, (), "shape mismatch")
  811. assert_(type(np.ma.median(x)) is not MaskedArray)
  812. # integer
  813. x = array(np.arange(6), mask=[0,1,1,1,1,0])
  814. assert_equal(np.ma.median(x), 2.5)
  815. assert_equal(np.ma.median(x).shape, (), "shape mismatch")
  816. assert_(type(np.ma.median(x)) is not MaskedArray)
  817. # float
  818. x = array(np.arange(6.), mask=[0,1,1,1,1,0])
  819. assert_equal(np.ma.median(x), 2.5)
  820. assert_equal(np.ma.median(x).shape, (), "shape mismatch")
  821. assert_(type(np.ma.median(x)) is not MaskedArray)
  822. def test_1d_shape_consistency(self):
  823. assert_equal(np.ma.median(array([1,2,3],mask=[0,0,0])).shape,
  824. np.ma.median(array([1,2,3],mask=[0,1,0])).shape )
  825. def test_2d(self):
  826. # Tests median w/ 2D
  827. (n, p) = (101, 30)
  828. x = masked_array(np.linspace(-1., 1., n),)
  829. x[:10] = x[-10:] = masked
  830. z = masked_array(np.empty((n, p), dtype=float))
  831. z[:, 0] = x[:]
  832. idx = np.arange(len(x))
  833. for i in range(1, p):
  834. np.random.shuffle(idx)
  835. z[:, i] = x[idx]
  836. assert_equal(median(z[:, 0]), 0)
  837. assert_equal(median(z), 0)
  838. assert_equal(median(z, axis=0), np.zeros(p))
  839. assert_equal(median(z.T, axis=1), np.zeros(p))
  840. def test_2d_waxis(self):
  841. # Tests median w/ 2D arrays and different axis.
  842. x = masked_array(np.arange(30).reshape(10, 3))
  843. x[:3] = x[-3:] = masked
  844. assert_equal(median(x), 14.5)
  845. assert_(type(np.ma.median(x)) is not MaskedArray)
  846. assert_equal(median(x, axis=0), [13.5, 14.5, 15.5])
  847. assert_(type(np.ma.median(x, axis=0)) is MaskedArray)
  848. assert_equal(median(x, axis=1), [0, 0, 0, 10, 13, 16, 19, 0, 0, 0])
  849. assert_(type(np.ma.median(x, axis=1)) is MaskedArray)
  850. assert_equal(median(x, axis=1).mask, [1, 1, 1, 0, 0, 0, 0, 1, 1, 1])
  851. def test_3d(self):
  852. # Tests median w/ 3D
  853. x = np.ma.arange(24).reshape(3, 4, 2)
  854. x[x % 3 == 0] = masked
  855. assert_equal(median(x, 0), [[12, 9], [6, 15], [12, 9], [18, 15]])
  856. x.shape = (4, 3, 2)
  857. assert_equal(median(x, 0), [[99, 10], [11, 99], [13, 14]])
  858. x = np.ma.arange(24).reshape(4, 3, 2)
  859. x[x % 5 == 0] = masked
  860. assert_equal(median(x, 0), [[12, 10], [8, 9], [16, 17]])
  861. def test_neg_axis(self):
  862. x = masked_array(np.arange(30).reshape(10, 3))
  863. x[:3] = x[-3:] = masked
  864. assert_equal(median(x, axis=-1), median(x, axis=1))
  865. def test_out_1d(self):
  866. # integer float even odd
  867. for v in (30, 30., 31, 31.):
  868. x = masked_array(np.arange(v))
  869. x[:3] = x[-3:] = masked
  870. out = masked_array(np.ones(()))
  871. r = median(x, out=out)
  872. if v == 30:
  873. assert_equal(out, 14.5)
  874. else:
  875. assert_equal(out, 15.)
  876. assert_(r is out)
  877. assert_(type(r) is MaskedArray)
  878. def test_out(self):
  879. # integer float even odd
  880. for v in (40, 40., 30, 30.):
  881. x = masked_array(np.arange(v).reshape(10, -1))
  882. x[:3] = x[-3:] = masked
  883. out = masked_array(np.ones(10))
  884. r = median(x, axis=1, out=out)
  885. if v == 30:
  886. e = masked_array([0.]*3 + [10, 13, 16, 19] + [0.]*3,
  887. mask=[True] * 3 + [False] * 4 + [True] * 3)
  888. else:
  889. e = masked_array([0.]*3 + [13.5, 17.5, 21.5, 25.5] + [0.]*3,
  890. mask=[True]*3 + [False]*4 + [True]*3)
  891. assert_equal(r, e)
  892. assert_(r is out)
  893. assert_(type(r) is MaskedArray)
  894. @pytest.mark.parametrize(
  895. argnames='axis',
  896. argvalues=[
  897. None,
  898. 1,
  899. (1, ),
  900. (0, 1),
  901. (-3, -1),
  902. ]
  903. )
  904. def test_keepdims_out(self, axis):
  905. mask = np.zeros((3, 5, 7, 11), dtype=bool)
  906. # Randomly set some elements to True:
  907. w = np.random.random((4, 200)) * np.array(mask.shape)[:, None]
  908. w = w.astype(np.intp)
  909. mask[tuple(w)] = np.nan
  910. d = masked_array(np.ones(mask.shape), mask=mask)
  911. if axis is None:
  912. shape_out = (1,) * d.ndim
  913. else:
  914. axis_norm = normalize_axis_tuple(axis, d.ndim)
  915. shape_out = tuple(
  916. 1 if i in axis_norm else d.shape[i] for i in range(d.ndim))
  917. out = masked_array(np.empty(shape_out))
  918. result = median(d, axis=axis, keepdims=True, out=out)
  919. assert result is out
  920. assert_equal(result.shape, shape_out)
  921. def test_single_non_masked_value_on_axis(self):
  922. data = [[1., 0.],
  923. [0., 3.],
  924. [0., 0.]]
  925. masked_arr = np.ma.masked_equal(data, 0)
  926. expected = [1., 3.]
  927. assert_array_equal(np.ma.median(masked_arr, axis=0),
  928. expected)
  929. def test_nan(self):
  930. for mask in (False, np.zeros(6, dtype=bool)):
  931. dm = np.ma.array([[1, np.nan, 3], [1, 2, 3]])
  932. dm.mask = mask
  933. # scalar result
  934. r = np.ma.median(dm, axis=None)
  935. assert_(np.isscalar(r))
  936. assert_array_equal(r, np.nan)
  937. r = np.ma.median(dm.ravel(), axis=0)
  938. assert_(np.isscalar(r))
  939. assert_array_equal(r, np.nan)
  940. r = np.ma.median(dm, axis=0)
  941. assert_equal(type(r), MaskedArray)
  942. assert_array_equal(r, [1, np.nan, 3])
  943. r = np.ma.median(dm, axis=1)
  944. assert_equal(type(r), MaskedArray)
  945. assert_array_equal(r, [np.nan, 2])
  946. r = np.ma.median(dm, axis=-1)
  947. assert_equal(type(r), MaskedArray)
  948. assert_array_equal(r, [np.nan, 2])
  949. dm = np.ma.array([[1, np.nan, 3], [1, 2, 3]])
  950. dm[:, 2] = np.ma.masked
  951. assert_array_equal(np.ma.median(dm, axis=None), np.nan)
  952. assert_array_equal(np.ma.median(dm, axis=0), [1, np.nan, 3])
  953. assert_array_equal(np.ma.median(dm, axis=1), [np.nan, 1.5])
  954. def test_out_nan(self):
  955. o = np.ma.masked_array(np.zeros((4,)))
  956. d = np.ma.masked_array(np.ones((3, 4)))
  957. d[2, 1] = np.nan
  958. d[2, 2] = np.ma.masked
  959. assert_equal(np.ma.median(d, 0, out=o), o)
  960. o = np.ma.masked_array(np.zeros((3,)))
  961. assert_equal(np.ma.median(d, 1, out=o), o)
  962. o = np.ma.masked_array(np.zeros(()))
  963. assert_equal(np.ma.median(d, out=o), o)
  964. def test_nan_behavior(self):
  965. a = np.ma.masked_array(np.arange(24, dtype=float))
  966. a[::3] = np.ma.masked
  967. a[2] = np.nan
  968. assert_array_equal(np.ma.median(a), np.nan)
  969. assert_array_equal(np.ma.median(a, axis=0), np.nan)
  970. a = np.ma.masked_array(np.arange(24, dtype=float).reshape(2, 3, 4))
  971. a.mask = np.arange(a.size) % 2 == 1
  972. aorig = a.copy()
  973. a[1, 2, 3] = np.nan
  974. a[1, 1, 2] = np.nan
  975. # no axis
  976. assert_array_equal(np.ma.median(a), np.nan)
  977. assert_(np.isscalar(np.ma.median(a)))
  978. # axis0
  979. b = np.ma.median(aorig, axis=0)
  980. b[2, 3] = np.nan
  981. b[1, 2] = np.nan
  982. assert_equal(np.ma.median(a, 0), b)
  983. # axis1
  984. b = np.ma.median(aorig, axis=1)
  985. b[1, 3] = np.nan
  986. b[1, 2] = np.nan
  987. assert_equal(np.ma.median(a, 1), b)
  988. # axis02
  989. b = np.ma.median(aorig, axis=(0, 2))
  990. b[1] = np.nan
  991. b[2] = np.nan
  992. assert_equal(np.ma.median(a, (0, 2)), b)
  993. def test_ambigous_fill(self):
  994. # 255 is max value, used as filler for sort
  995. a = np.array([[3, 3, 255], [3, 3, 255]], dtype=np.uint8)
  996. a = np.ma.masked_array(a, mask=a == 3)
  997. assert_array_equal(np.ma.median(a, axis=1), 255)
  998. assert_array_equal(np.ma.median(a, axis=1).mask, False)
  999. assert_array_equal(np.ma.median(a, axis=0), a[0])
  1000. assert_array_equal(np.ma.median(a), 255)
  1001. def test_special(self):
  1002. for inf in [np.inf, -np.inf]:
  1003. a = np.array([[inf, np.nan], [np.nan, np.nan]])
  1004. a = np.ma.masked_array(a, mask=np.isnan(a))
  1005. assert_equal(np.ma.median(a, axis=0), [inf, np.nan])
  1006. assert_equal(np.ma.median(a, axis=1), [inf, np.nan])
  1007. assert_equal(np.ma.median(a), inf)
  1008. a = np.array([[np.nan, np.nan, inf], [np.nan, np.nan, inf]])
  1009. a = np.ma.masked_array(a, mask=np.isnan(a))
  1010. assert_array_equal(np.ma.median(a, axis=1), inf)
  1011. assert_array_equal(np.ma.median(a, axis=1).mask, False)
  1012. assert_array_equal(np.ma.median(a, axis=0), a[0])
  1013. assert_array_equal(np.ma.median(a), inf)
  1014. # no mask
  1015. a = np.array([[inf, inf], [inf, inf]])
  1016. assert_equal(np.ma.median(a), inf)
  1017. assert_equal(np.ma.median(a, axis=0), inf)
  1018. assert_equal(np.ma.median(a, axis=1), inf)
  1019. a = np.array([[inf, 7, -inf, -9],
  1020. [-10, np.nan, np.nan, 5],
  1021. [4, np.nan, np.nan, inf]],
  1022. dtype=np.float32)
  1023. a = np.ma.masked_array(a, mask=np.isnan(a))
  1024. if inf > 0:
  1025. assert_equal(np.ma.median(a, axis=0), [4., 7., -inf, 5.])
  1026. assert_equal(np.ma.median(a), 4.5)
  1027. else:
  1028. assert_equal(np.ma.median(a, axis=0), [-10., 7., -inf, -9.])
  1029. assert_equal(np.ma.median(a), -2.5)
  1030. assert_equal(np.ma.median(a, axis=1), [-1., -2.5, inf])
  1031. for i in range(0, 10):
  1032. for j in range(1, 10):
  1033. a = np.array([([np.nan] * i) + ([inf] * j)] * 2)
  1034. a = np.ma.masked_array(a, mask=np.isnan(a))
  1035. assert_equal(np.ma.median(a), inf)
  1036. assert_equal(np.ma.median(a, axis=1), inf)
  1037. assert_equal(np.ma.median(a, axis=0),
  1038. ([np.nan] * i) + [inf] * j)
  1039. def test_empty(self):
  1040. # empty arrays
  1041. a = np.ma.masked_array(np.array([], dtype=float))
  1042. with suppress_warnings() as w:
  1043. w.record(RuntimeWarning)
  1044. assert_array_equal(np.ma.median(a), np.nan)
  1045. assert_(w.log[0].category is RuntimeWarning)
  1046. # multiple dimensions
  1047. a = np.ma.masked_array(np.array([], dtype=float, ndmin=3))
  1048. # no axis
  1049. with suppress_warnings() as w:
  1050. w.record(RuntimeWarning)
  1051. warnings.filterwarnings('always', '', RuntimeWarning)
  1052. assert_array_equal(np.ma.median(a), np.nan)
  1053. assert_(w.log[0].category is RuntimeWarning)
  1054. # axis 0 and 1
  1055. b = np.ma.masked_array(np.array([], dtype=float, ndmin=2))
  1056. assert_equal(np.ma.median(a, axis=0), b)
  1057. assert_equal(np.ma.median(a, axis=1), b)
  1058. # axis 2
  1059. b = np.ma.masked_array(np.array(np.nan, dtype=float, ndmin=2))
  1060. with warnings.catch_warnings(record=True) as w:
  1061. warnings.filterwarnings('always', '', RuntimeWarning)
  1062. assert_equal(np.ma.median(a, axis=2), b)
  1063. assert_(w[0].category is RuntimeWarning)
  1064. def test_object(self):
  1065. o = np.ma.masked_array(np.arange(7.))
  1066. assert_(type(np.ma.median(o.astype(object))), float)
  1067. o[2] = np.nan
  1068. assert_(type(np.ma.median(o.astype(object))), float)
  1069. class TestCov:
  1070. def setup_method(self):
  1071. self.data = array(np.random.rand(12))
  1072. def test_1d_without_missing(self):
  1073. # Test cov on 1D variable w/o missing values
  1074. x = self.data
  1075. assert_almost_equal(np.cov(x), cov(x))
  1076. assert_almost_equal(np.cov(x, rowvar=False), cov(x, rowvar=False))
  1077. assert_almost_equal(np.cov(x, rowvar=False, bias=True),
  1078. cov(x, rowvar=False, bias=True))
  1079. def test_2d_without_missing(self):
  1080. # Test cov on 1 2D variable w/o missing values
  1081. x = self.data.reshape(3, 4)
  1082. assert_almost_equal(np.cov(x), cov(x))
  1083. assert_almost_equal(np.cov(x, rowvar=False), cov(x, rowvar=False))
  1084. assert_almost_equal(np.cov(x, rowvar=False, bias=True),
  1085. cov(x, rowvar=False, bias=True))
  1086. def test_1d_with_missing(self):
  1087. # Test cov 1 1D variable w/missing values
  1088. x = self.data
  1089. x[-1] = masked
  1090. x -= x.mean()
  1091. nx = x.compressed()
  1092. assert_almost_equal(np.cov(nx), cov(x))
  1093. assert_almost_equal(np.cov(nx, rowvar=False), cov(x, rowvar=False))
  1094. assert_almost_equal(np.cov(nx, rowvar=False, bias=True),
  1095. cov(x, rowvar=False, bias=True))
  1096. #
  1097. try:
  1098. cov(x, allow_masked=False)
  1099. except ValueError:
  1100. pass
  1101. #
  1102. # 2 1D variables w/ missing values
  1103. nx = x[1:-1]
  1104. assert_almost_equal(np.cov(nx, nx[::-1]), cov(x, x[::-1]))
  1105. assert_almost_equal(np.cov(nx, nx[::-1], rowvar=False),
  1106. cov(x, x[::-1], rowvar=False))
  1107. assert_almost_equal(np.cov(nx, nx[::-1], rowvar=False, bias=True),
  1108. cov(x, x[::-1], rowvar=False, bias=True))
  1109. def test_2d_with_missing(self):
  1110. # Test cov on 2D variable w/ missing value
  1111. x = self.data
  1112. x[-1] = masked
  1113. x = x.reshape(3, 4)
  1114. valid = np.logical_not(getmaskarray(x)).astype(int)
  1115. frac = np.dot(valid, valid.T)
  1116. xf = (x - x.mean(1)[:, None]).filled(0)
  1117. assert_almost_equal(cov(x),
  1118. np.cov(xf) * (x.shape[1] - 1) / (frac - 1.))
  1119. assert_almost_equal(cov(x, bias=True),
  1120. np.cov(xf, bias=True) * x.shape[1] / frac)
  1121. frac = np.dot(valid.T, valid)
  1122. xf = (x - x.mean(0)).filled(0)
  1123. assert_almost_equal(cov(x, rowvar=False),
  1124. (np.cov(xf, rowvar=False) *
  1125. (x.shape[0] - 1) / (frac - 1.)))
  1126. assert_almost_equal(cov(x, rowvar=False, bias=True),
  1127. (np.cov(xf, rowvar=False, bias=True) *
  1128. x.shape[0] / frac))
  1129. class TestCorrcoef:
  1130. def setup_method(self):
  1131. self.data = array(np.random.rand(12))
  1132. self.data2 = array(np.random.rand(12))
  1133. def test_ddof(self):
  1134. # ddof raises DeprecationWarning
  1135. x, y = self.data, self.data2
  1136. expected = np.corrcoef(x)
  1137. expected2 = np.corrcoef(x, y)
  1138. with suppress_warnings() as sup:
  1139. warnings.simplefilter("always")
  1140. assert_warns(DeprecationWarning, corrcoef, x, ddof=-1)
  1141. sup.filter(DeprecationWarning, "bias and ddof have no effect")
  1142. # ddof has no or negligible effect on the function
  1143. assert_almost_equal(np.corrcoef(x, ddof=0), corrcoef(x, ddof=0))
  1144. assert_almost_equal(corrcoef(x, ddof=-1), expected)
  1145. assert_almost_equal(corrcoef(x, y, ddof=-1), expected2)
  1146. assert_almost_equal(corrcoef(x, ddof=3), expected)
  1147. assert_almost_equal(corrcoef(x, y, ddof=3), expected2)
  1148. def test_bias(self):
  1149. x, y = self.data, self.data2
  1150. expected = np.corrcoef(x)
  1151. # bias raises DeprecationWarning
  1152. with suppress_warnings() as sup:
  1153. warnings.simplefilter("always")
  1154. assert_warns(DeprecationWarning, corrcoef, x, y, True, False)
  1155. assert_warns(DeprecationWarning, corrcoef, x, y, True, True)
  1156. assert_warns(DeprecationWarning, corrcoef, x, bias=False)
  1157. sup.filter(DeprecationWarning, "bias and ddof have no effect")
  1158. # bias has no or negligible effect on the function
  1159. assert_almost_equal(corrcoef(x, bias=1), expected)
  1160. def test_1d_without_missing(self):
  1161. # Test cov on 1D variable w/o missing values
  1162. x = self.data
  1163. assert_almost_equal(np.corrcoef(x), corrcoef(x))
  1164. assert_almost_equal(np.corrcoef(x, rowvar=False),
  1165. corrcoef(x, rowvar=False))
  1166. with suppress_warnings() as sup:
  1167. sup.filter(DeprecationWarning, "bias and ddof have no effect")
  1168. assert_almost_equal(np.corrcoef(x, rowvar=False, bias=True),
  1169. corrcoef(x, rowvar=False, bias=True))
  1170. def test_2d_without_missing(self):
  1171. # Test corrcoef on 1 2D variable w/o missing values
  1172. x = self.data.reshape(3, 4)
  1173. assert_almost_equal(np.corrcoef(x), corrcoef(x))
  1174. assert_almost_equal(np.corrcoef(x, rowvar=False),
  1175. corrcoef(x, rowvar=False))
  1176. with suppress_warnings() as sup:
  1177. sup.filter(DeprecationWarning, "bias and ddof have no effect")
  1178. assert_almost_equal(np.corrcoef(x, rowvar=False, bias=True),
  1179. corrcoef(x, rowvar=False, bias=True))
  1180. def test_1d_with_missing(self):
  1181. # Test corrcoef 1 1D variable w/missing values
  1182. x = self.data
  1183. x[-1] = masked
  1184. x -= x.mean()
  1185. nx = x.compressed()
  1186. assert_almost_equal(np.corrcoef(nx), corrcoef(x))
  1187. assert_almost_equal(np.corrcoef(nx, rowvar=False),
  1188. corrcoef(x, rowvar=False))
  1189. with suppress_warnings() as sup:
  1190. sup.filter(DeprecationWarning, "bias and ddof have no effect")
  1191. assert_almost_equal(np.corrcoef(nx, rowvar=False, bias=True),
  1192. corrcoef(x, rowvar=False, bias=True))
  1193. try:
  1194. corrcoef(x, allow_masked=False)
  1195. except ValueError:
  1196. pass
  1197. # 2 1D variables w/ missing values
  1198. nx = x[1:-1]
  1199. assert_almost_equal(np.corrcoef(nx, nx[::-1]), corrcoef(x, x[::-1]))
  1200. assert_almost_equal(np.corrcoef(nx, nx[::-1], rowvar=False),
  1201. corrcoef(x, x[::-1], rowvar=False))
  1202. with suppress_warnings() as sup:
  1203. sup.filter(DeprecationWarning, "bias and ddof have no effect")
  1204. # ddof and bias have no or negligible effect on the function
  1205. assert_almost_equal(np.corrcoef(nx, nx[::-1]),
  1206. corrcoef(x, x[::-1], bias=1))
  1207. assert_almost_equal(np.corrcoef(nx, nx[::-1]),
  1208. corrcoef(x, x[::-1], ddof=2))
  1209. def test_2d_with_missing(self):
  1210. # Test corrcoef on 2D variable w/ missing value
  1211. x = self.data
  1212. x[-1] = masked
  1213. x = x.reshape(3, 4)
  1214. test = corrcoef(x)
  1215. control = np.corrcoef(x)
  1216. assert_almost_equal(test[:-1, :-1], control[:-1, :-1])
  1217. with suppress_warnings() as sup:
  1218. sup.filter(DeprecationWarning, "bias and ddof have no effect")
  1219. # ddof and bias have no or negligible effect on the function
  1220. assert_almost_equal(corrcoef(x, ddof=-2)[:-1, :-1],
  1221. control[:-1, :-1])
  1222. assert_almost_equal(corrcoef(x, ddof=3)[:-1, :-1],
  1223. control[:-1, :-1])
  1224. assert_almost_equal(corrcoef(x, bias=1)[:-1, :-1],
  1225. control[:-1, :-1])
  1226. class TestPolynomial:
  1227. #
  1228. def test_polyfit(self):
  1229. # Tests polyfit
  1230. # On ndarrays
  1231. x = np.random.rand(10)
  1232. y = np.random.rand(20).reshape(-1, 2)
  1233. assert_almost_equal(polyfit(x, y, 3), np.polyfit(x, y, 3))
  1234. # ON 1D maskedarrays
  1235. x = x.view(MaskedArray)
  1236. x[0] = masked
  1237. y = y.view(MaskedArray)
  1238. y[0, 0] = y[-1, -1] = masked
  1239. #
  1240. (C, R, K, S, D) = polyfit(x, y[:, 0], 3, full=True)
  1241. (c, r, k, s, d) = np.polyfit(x[1:], y[1:, 0].compressed(), 3,
  1242. full=True)
  1243. for (a, a_) in zip((C, R, K, S, D), (c, r, k, s, d)):
  1244. assert_almost_equal(a, a_)
  1245. #
  1246. (C, R, K, S, D) = polyfit(x, y[:, -1], 3, full=True)
  1247. (c, r, k, s, d) = np.polyfit(x[1:-1], y[1:-1, -1], 3, full=True)
  1248. for (a, a_) in zip((C, R, K, S, D), (c, r, k, s, d)):
  1249. assert_almost_equal(a, a_)
  1250. #
  1251. (C, R, K, S, D) = polyfit(x, y, 3, full=True)
  1252. (c, r, k, s, d) = np.polyfit(x[1:-1], y[1:-1,:], 3, full=True)
  1253. for (a, a_) in zip((C, R, K, S, D), (c, r, k, s, d)):
  1254. assert_almost_equal(a, a_)
  1255. #
  1256. w = np.random.rand(10) + 1
  1257. wo = w.copy()
  1258. xs = x[1:-1]
  1259. ys = y[1:-1]
  1260. ws = w[1:-1]
  1261. (C, R, K, S, D) = polyfit(x, y, 3, full=True, w=w)
  1262. (c, r, k, s, d) = np.polyfit(xs, ys, 3, full=True, w=ws)
  1263. assert_equal(w, wo)
  1264. for (a, a_) in zip((C, R, K, S, D), (c, r, k, s, d)):
  1265. assert_almost_equal(a, a_)
  1266. def test_polyfit_with_masked_NaNs(self):
  1267. x = np.random.rand(10)
  1268. y = np.random.rand(20).reshape(-1, 2)
  1269. x[0] = np.nan
  1270. y[-1,-1] = np.nan
  1271. x = x.view(MaskedArray)
  1272. y = y.view(MaskedArray)
  1273. x[0] = masked
  1274. y[-1,-1] = masked
  1275. (C, R, K, S, D) = polyfit(x, y, 3, full=True)
  1276. (c, r, k, s, d) = np.polyfit(x[1:-1], y[1:-1,:], 3, full=True)
  1277. for (a, a_) in zip((C, R, K, S, D), (c, r, k, s, d)):
  1278. assert_almost_equal(a, a_)
  1279. class TestArraySetOps:
  1280. def test_unique_onlist(self):
  1281. # Test unique on list
  1282. data = [1, 1, 1, 2, 2, 3]
  1283. test = unique(data, return_index=True, return_inverse=True)
  1284. assert_(isinstance(test[0], MaskedArray))
  1285. assert_equal(test[0], masked_array([1, 2, 3], mask=[0, 0, 0]))
  1286. assert_equal(test[1], [0, 3, 5])
  1287. assert_equal(test[2], [0, 0, 0, 1, 1, 2])
  1288. def test_unique_onmaskedarray(self):
  1289. # Test unique on masked data w/use_mask=True
  1290. data = masked_array([1, 1, 1, 2, 2, 3], mask=[0, 0, 1, 0, 1, 0])
  1291. test = unique(data, return_index=True, return_inverse=True)
  1292. assert_equal(test[0], masked_array([1, 2, 3, -1], mask=[0, 0, 0, 1]))
  1293. assert_equal(test[1], [0, 3, 5, 2])
  1294. assert_equal(test[2], [0, 0, 3, 1, 3, 2])
  1295. #
  1296. data.fill_value = 3
  1297. data = masked_array(data=[1, 1, 1, 2, 2, 3],
  1298. mask=[0, 0, 1, 0, 1, 0], fill_value=3)
  1299. test = unique(data, return_index=True, return_inverse=True)
  1300. assert_equal(test[0], masked_array([1, 2, 3, -1], mask=[0, 0, 0, 1]))
  1301. assert_equal(test[1], [0, 3, 5, 2])
  1302. assert_equal(test[2], [0, 0, 3, 1, 3, 2])
  1303. def test_unique_allmasked(self):
  1304. # Test all masked
  1305. data = masked_array([1, 1, 1], mask=True)
  1306. test = unique(data, return_index=True, return_inverse=True)
  1307. assert_equal(test[0], masked_array([1, ], mask=[True]))
  1308. assert_equal(test[1], [0])
  1309. assert_equal(test[2], [0, 0, 0])
  1310. #
  1311. # Test masked
  1312. data = masked
  1313. test = unique(data, return_index=True, return_inverse=True)
  1314. assert_equal(test[0], masked_array(masked))
  1315. assert_equal(test[1], [0])
  1316. assert_equal(test[2], [0])
  1317. def test_ediff1d(self):
  1318. # Tests mediff1d
  1319. x = masked_array(np.arange(5), mask=[1, 0, 0, 0, 1])
  1320. control = array([1, 1, 1, 4], mask=[1, 0, 0, 1])
  1321. test = ediff1d(x)
  1322. assert_equal(test, control)
  1323. assert_equal(test.filled(0), control.filled(0))
  1324. assert_equal(test.mask, control.mask)
  1325. def test_ediff1d_tobegin(self):
  1326. # Test ediff1d w/ to_begin
  1327. x = masked_array(np.arange(5), mask=[1, 0, 0, 0, 1])
  1328. test = ediff1d(x, to_begin=masked)
  1329. control = array([0, 1, 1, 1, 4], mask=[1, 1, 0, 0, 1])
  1330. assert_equal(test, control)
  1331. assert_equal(test.filled(0), control.filled(0))
  1332. assert_equal(test.mask, control.mask)
  1333. #
  1334. test = ediff1d(x, to_begin=[1, 2, 3])
  1335. control = array([1, 2, 3, 1, 1, 1, 4], mask=[0, 0, 0, 1, 0, 0, 1])
  1336. assert_equal(test, control)
  1337. assert_equal(test.filled(0), control.filled(0))
  1338. assert_equal(test.mask, control.mask)
  1339. def test_ediff1d_toend(self):
  1340. # Test ediff1d w/ to_end
  1341. x = masked_array(np.arange(5), mask=[1, 0, 0, 0, 1])
  1342. test = ediff1d(x, to_end=masked)
  1343. control = array([1, 1, 1, 4, 0], mask=[1, 0, 0, 1, 1])
  1344. assert_equal(test, control)
  1345. assert_equal(test.filled(0), control.filled(0))
  1346. assert_equal(test.mask, control.mask)
  1347. #
  1348. test = ediff1d(x, to_end=[1, 2, 3])
  1349. control = array([1, 1, 1, 4, 1, 2, 3], mask=[1, 0, 0, 1, 0, 0, 0])
  1350. assert_equal(test, control)
  1351. assert_equal(test.filled(0), control.filled(0))
  1352. assert_equal(test.mask, control.mask)
  1353. def test_ediff1d_tobegin_toend(self):
  1354. # Test ediff1d w/ to_begin and to_end
  1355. x = masked_array(np.arange(5), mask=[1, 0, 0, 0, 1])
  1356. test = ediff1d(x, to_end=masked, to_begin=masked)
  1357. control = array([0, 1, 1, 1, 4, 0], mask=[1, 1, 0, 0, 1, 1])
  1358. assert_equal(test, control)
  1359. assert_equal(test.filled(0), control.filled(0))
  1360. assert_equal(test.mask, control.mask)
  1361. #
  1362. test = ediff1d(x, to_end=[1, 2, 3], to_begin=masked)
  1363. control = array([0, 1, 1, 1, 4, 1, 2, 3],
  1364. mask=[1, 1, 0, 0, 1, 0, 0, 0])
  1365. assert_equal(test, control)
  1366. assert_equal(test.filled(0), control.filled(0))
  1367. assert_equal(test.mask, control.mask)
  1368. def test_ediff1d_ndarray(self):
  1369. # Test ediff1d w/ a ndarray
  1370. x = np.arange(5)
  1371. test = ediff1d(x)
  1372. control = array([1, 1, 1, 1], mask=[0, 0, 0, 0])
  1373. assert_equal(test, control)
  1374. assert_(isinstance(test, MaskedArray))
  1375. assert_equal(test.filled(0), control.filled(0))
  1376. assert_equal(test.mask, control.mask)
  1377. #
  1378. test = ediff1d(x, to_end=masked, to_begin=masked)
  1379. control = array([0, 1, 1, 1, 1, 0], mask=[1, 0, 0, 0, 0, 1])
  1380. assert_(isinstance(test, MaskedArray))
  1381. assert_equal(test.filled(0), control.filled(0))
  1382. assert_equal(test.mask, control.mask)
  1383. def test_intersect1d(self):
  1384. # Test intersect1d
  1385. x = array([1, 3, 3, 3], mask=[0, 0, 0, 1])
  1386. y = array([3, 1, 1, 1], mask=[0, 0, 0, 1])
  1387. test = intersect1d(x, y)
  1388. control = array([1, 3, -1], mask=[0, 0, 1])
  1389. assert_equal(test, control)
  1390. def test_setxor1d(self):
  1391. # Test setxor1d
  1392. a = array([1, 2, 5, 7, -1], mask=[0, 0, 0, 0, 1])
  1393. b = array([1, 2, 3, 4, 5, -1], mask=[0, 0, 0, 0, 0, 1])
  1394. test = setxor1d(a, b)
  1395. assert_equal(test, array([3, 4, 7]))
  1396. #
  1397. a = array([1, 2, 5, 7, -1], mask=[0, 0, 0, 0, 1])
  1398. b = [1, 2, 3, 4, 5]
  1399. test = setxor1d(a, b)
  1400. assert_equal(test, array([3, 4, 7, -1], mask=[0, 0, 0, 1]))
  1401. #
  1402. a = array([1, 2, 3])
  1403. b = array([6, 5, 4])
  1404. test = setxor1d(a, b)
  1405. assert_(isinstance(test, MaskedArray))
  1406. assert_equal(test, [1, 2, 3, 4, 5, 6])
  1407. #
  1408. a = array([1, 8, 2, 3], mask=[0, 1, 0, 0])
  1409. b = array([6, 5, 4, 8], mask=[0, 0, 0, 1])
  1410. test = setxor1d(a, b)
  1411. assert_(isinstance(test, MaskedArray))
  1412. assert_equal(test, [1, 2, 3, 4, 5, 6])
  1413. #
  1414. assert_array_equal([], setxor1d([], []))
  1415. def test_isin(self):
  1416. # the tests for in1d cover most of isin's behavior
  1417. # if in1d is removed, would need to change those tests to test
  1418. # isin instead.
  1419. a = np.arange(24).reshape([2, 3, 4])
  1420. mask = np.zeros([2, 3, 4])
  1421. mask[1, 2, 0] = 1
  1422. a = array(a, mask=mask)
  1423. b = array(data=[0, 10, 20, 30, 1, 3, 11, 22, 33],
  1424. mask=[0, 1, 0, 1, 0, 1, 0, 1, 0])
  1425. ec = zeros((2, 3, 4), dtype=bool)
  1426. ec[0, 0, 0] = True
  1427. ec[0, 0, 1] = True
  1428. ec[0, 2, 3] = True
  1429. c = isin(a, b)
  1430. assert_(isinstance(c, MaskedArray))
  1431. assert_array_equal(c, ec)
  1432. #compare results of np.isin to ma.isin
  1433. d = np.isin(a, b[~b.mask]) & ~a.mask
  1434. assert_array_equal(c, d)
  1435. def test_in1d(self):
  1436. # Test in1d
  1437. a = array([1, 2, 5, 7, -1], mask=[0, 0, 0, 0, 1])
  1438. b = array([1, 2, 3, 4, 5, -1], mask=[0, 0, 0, 0, 0, 1])
  1439. test = in1d(a, b)
  1440. assert_equal(test, [True, True, True, False, True])
  1441. #
  1442. a = array([5, 5, 2, 1, -1], mask=[0, 0, 0, 0, 1])
  1443. b = array([1, 5, -1], mask=[0, 0, 1])
  1444. test = in1d(a, b)
  1445. assert_equal(test, [True, True, False, True, True])
  1446. #
  1447. assert_array_equal([], in1d([], []))
  1448. def test_in1d_invert(self):
  1449. # Test in1d's invert parameter
  1450. a = array([1, 2, 5, 7, -1], mask=[0, 0, 0, 0, 1])
  1451. b = array([1, 2, 3, 4, 5, -1], mask=[0, 0, 0, 0, 0, 1])
  1452. assert_equal(np.invert(in1d(a, b)), in1d(a, b, invert=True))
  1453. a = array([5, 5, 2, 1, -1], mask=[0, 0, 0, 0, 1])
  1454. b = array([1, 5, -1], mask=[0, 0, 1])
  1455. assert_equal(np.invert(in1d(a, b)), in1d(a, b, invert=True))
  1456. assert_array_equal([], in1d([], [], invert=True))
  1457. def test_union1d(self):
  1458. # Test union1d
  1459. a = array([1, 2, 5, 7, 5, -1], mask=[0, 0, 0, 0, 0, 1])
  1460. b = array([1, 2, 3, 4, 5, -1], mask=[0, 0, 0, 0, 0, 1])
  1461. test = union1d(a, b)
  1462. control = array([1, 2, 3, 4, 5, 7, -1], mask=[0, 0, 0, 0, 0, 0, 1])
  1463. assert_equal(test, control)
  1464. # Tests gh-10340, arguments to union1d should be
  1465. # flattened if they are not already 1D
  1466. x = array([[0, 1, 2], [3, 4, 5]], mask=[[0, 0, 0], [0, 0, 1]])
  1467. y = array([0, 1, 2, 3, 4], mask=[0, 0, 0, 0, 1])
  1468. ez = array([0, 1, 2, 3, 4, 5], mask=[0, 0, 0, 0, 0, 1])
  1469. z = union1d(x, y)
  1470. assert_equal(z, ez)
  1471. #
  1472. assert_array_equal([], union1d([], []))
  1473. def test_setdiff1d(self):
  1474. # Test setdiff1d
  1475. a = array([6, 5, 4, 7, 7, 1, 2, 1], mask=[0, 0, 0, 0, 0, 0, 0, 1])
  1476. b = array([2, 4, 3, 3, 2, 1, 5])
  1477. test = setdiff1d(a, b)
  1478. assert_equal(test, array([6, 7, -1], mask=[0, 0, 1]))
  1479. #
  1480. a = arange(10)
  1481. b = arange(8)
  1482. assert_equal(setdiff1d(a, b), array([8, 9]))
  1483. a = array([], np.uint32, mask=[])
  1484. assert_equal(setdiff1d(a, []).dtype, np.uint32)
  1485. def test_setdiff1d_char_array(self):
  1486. # Test setdiff1d_charray
  1487. a = np.array(['a', 'b', 'c'])
  1488. b = np.array(['a', 'b', 's'])
  1489. assert_array_equal(setdiff1d(a, b), np.array(['c']))
  1490. class TestShapeBase:
  1491. def test_atleast_2d(self):
  1492. # Test atleast_2d
  1493. a = masked_array([0, 1, 2], mask=[0, 1, 0])
  1494. b = atleast_2d(a)
  1495. assert_equal(b.shape, (1, 3))
  1496. assert_equal(b.mask.shape, b.data.shape)
  1497. assert_equal(a.shape, (3,))
  1498. assert_equal(a.mask.shape, a.data.shape)
  1499. assert_equal(b.mask.shape, b.data.shape)
  1500. def test_shape_scalar(self):
  1501. # the atleast and diagflat function should work with scalars
  1502. # GitHub issue #3367
  1503. # Additionally, the atleast functions should accept multiple scalars
  1504. # correctly
  1505. b = atleast_1d(1.0)
  1506. assert_equal(b.shape, (1,))
  1507. assert_equal(b.mask.shape, b.shape)
  1508. assert_equal(b.data.shape, b.shape)
  1509. b = atleast_1d(1.0, 2.0)
  1510. for a in b:
  1511. assert_equal(a.shape, (1,))
  1512. assert_equal(a.mask.shape, a.shape)
  1513. assert_equal(a.data.shape, a.shape)
  1514. b = atleast_2d(1.0)
  1515. assert_equal(b.shape, (1, 1))
  1516. assert_equal(b.mask.shape, b.shape)
  1517. assert_equal(b.data.shape, b.shape)
  1518. b = atleast_2d(1.0, 2.0)
  1519. for a in b:
  1520. assert_equal(a.shape, (1, 1))
  1521. assert_equal(a.mask.shape, a.shape)
  1522. assert_equal(a.data.shape, a.shape)
  1523. b = atleast_3d(1.0)
  1524. assert_equal(b.shape, (1, 1, 1))
  1525. assert_equal(b.mask.shape, b.shape)
  1526. assert_equal(b.data.shape, b.shape)
  1527. b = atleast_3d(1.0, 2.0)
  1528. for a in b:
  1529. assert_equal(a.shape, (1, 1, 1))
  1530. assert_equal(a.mask.shape, a.shape)
  1531. assert_equal(a.data.shape, a.shape)
  1532. b = diagflat(1.0)
  1533. assert_equal(b.shape, (1, 1))
  1534. assert_equal(b.mask.shape, b.data.shape)
  1535. class TestNDEnumerate:
  1536. def test_ndenumerate_nomasked(self):
  1537. ordinary = np.arange(6.).reshape((1, 3, 2))
  1538. empty_mask = np.zeros_like(ordinary, dtype=bool)
  1539. with_mask = masked_array(ordinary, mask=empty_mask)
  1540. assert_equal(list(np.ndenumerate(ordinary)),
  1541. list(ndenumerate(ordinary)))
  1542. assert_equal(list(ndenumerate(ordinary)),
  1543. list(ndenumerate(with_mask)))
  1544. assert_equal(list(ndenumerate(with_mask)),
  1545. list(ndenumerate(with_mask, compressed=False)))
  1546. def test_ndenumerate_allmasked(self):
  1547. a = masked_all(())
  1548. b = masked_all((100,))
  1549. c = masked_all((2, 3, 4))
  1550. assert_equal(list(ndenumerate(a)), [])
  1551. assert_equal(list(ndenumerate(b)), [])
  1552. assert_equal(list(ndenumerate(b, compressed=False)),
  1553. list(zip(np.ndindex((100,)), 100 * [masked])))
  1554. assert_equal(list(ndenumerate(c)), [])
  1555. assert_equal(list(ndenumerate(c, compressed=False)),
  1556. list(zip(np.ndindex((2, 3, 4)), 2 * 3 * 4 * [masked])))
  1557. def test_ndenumerate_mixedmasked(self):
  1558. a = masked_array(np.arange(12).reshape((3, 4)),
  1559. mask=[[1, 1, 1, 1],
  1560. [1, 1, 0, 1],
  1561. [0, 0, 0, 0]])
  1562. items = [((1, 2), 6),
  1563. ((2, 0), 8), ((2, 1), 9), ((2, 2), 10), ((2, 3), 11)]
  1564. assert_equal(list(ndenumerate(a)), items)
  1565. assert_equal(len(list(ndenumerate(a, compressed=False))), a.size)
  1566. for coordinate, value in ndenumerate(a, compressed=False):
  1567. assert_equal(a[coordinate], value)
  1568. class TestStack:
  1569. def test_stack_1d(self):
  1570. a = masked_array([0, 1, 2], mask=[0, 1, 0])
  1571. b = masked_array([9, 8, 7], mask=[1, 0, 0])
  1572. c = stack([a, b], axis=0)
  1573. assert_equal(c.shape, (2, 3))
  1574. assert_array_equal(a.mask, c[0].mask)
  1575. assert_array_equal(b.mask, c[1].mask)
  1576. d = vstack([a, b])
  1577. assert_array_equal(c.data, d.data)
  1578. assert_array_equal(c.mask, d.mask)
  1579. c = stack([a, b], axis=1)
  1580. assert_equal(c.shape, (3, 2))
  1581. assert_array_equal(a.mask, c[:, 0].mask)
  1582. assert_array_equal(b.mask, c[:, 1].mask)
  1583. def test_stack_masks(self):
  1584. a = masked_array([0, 1, 2], mask=True)
  1585. b = masked_array([9, 8, 7], mask=False)
  1586. c = stack([a, b], axis=0)
  1587. assert_equal(c.shape, (2, 3))
  1588. assert_array_equal(a.mask, c[0].mask)
  1589. assert_array_equal(b.mask, c[1].mask)
  1590. d = vstack([a, b])
  1591. assert_array_equal(c.data, d.data)
  1592. assert_array_equal(c.mask, d.mask)
  1593. c = stack([a, b], axis=1)
  1594. assert_equal(c.shape, (3, 2))
  1595. assert_array_equal(a.mask, c[:, 0].mask)
  1596. assert_array_equal(b.mask, c[:, 1].mask)
  1597. def test_stack_nd(self):
  1598. # 2D
  1599. shp = (3, 2)
  1600. d1 = np.random.randint(0, 10, shp)
  1601. d2 = np.random.randint(0, 10, shp)
  1602. m1 = np.random.randint(0, 2, shp).astype(bool)
  1603. m2 = np.random.randint(0, 2, shp).astype(bool)
  1604. a1 = masked_array(d1, mask=m1)
  1605. a2 = masked_array(d2, mask=m2)
  1606. c = stack([a1, a2], axis=0)
  1607. c_shp = (2,) + shp
  1608. assert_equal(c.shape, c_shp)
  1609. assert_array_equal(a1.mask, c[0].mask)
  1610. assert_array_equal(a2.mask, c[1].mask)
  1611. c = stack([a1, a2], axis=-1)
  1612. c_shp = shp + (2,)
  1613. assert_equal(c.shape, c_shp)
  1614. assert_array_equal(a1.mask, c[..., 0].mask)
  1615. assert_array_equal(a2.mask, c[..., 1].mask)
  1616. # 4D
  1617. shp = (3, 2, 4, 5,)
  1618. d1 = np.random.randint(0, 10, shp)
  1619. d2 = np.random.randint(0, 10, shp)
  1620. m1 = np.random.randint(0, 2, shp).astype(bool)
  1621. m2 = np.random.randint(0, 2, shp).astype(bool)
  1622. a1 = masked_array(d1, mask=m1)
  1623. a2 = masked_array(d2, mask=m2)
  1624. c = stack([a1, a2], axis=0)
  1625. c_shp = (2,) + shp
  1626. assert_equal(c.shape, c_shp)
  1627. assert_array_equal(a1.mask, c[0].mask)
  1628. assert_array_equal(a2.mask, c[1].mask)
  1629. c = stack([a1, a2], axis=-1)
  1630. c_shp = shp + (2,)
  1631. assert_equal(c.shape, c_shp)
  1632. assert_array_equal(a1.mask, c[..., 0].mask)
  1633. assert_array_equal(a2.mask, c[..., 1].mask)