test_old_ma.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939
  1. import pickle
  2. from functools import reduce
  3. import pytest
  4. import numpy as np
  5. import numpy._core.fromnumeric as fromnumeric
  6. import numpy._core.umath as umath
  7. from numpy.ma import (
  8. MaskedArray,
  9. MaskType,
  10. absolute,
  11. add,
  12. all,
  13. allclose,
  14. allequal,
  15. alltrue,
  16. arange,
  17. arccos,
  18. arcsin,
  19. arctan,
  20. arctan2,
  21. array,
  22. average,
  23. choose,
  24. concatenate,
  25. conjugate,
  26. cos,
  27. cosh,
  28. count,
  29. divide,
  30. equal,
  31. exp,
  32. filled,
  33. getmask,
  34. greater,
  35. greater_equal,
  36. inner,
  37. isMaskedArray,
  38. less,
  39. less_equal,
  40. log,
  41. log10,
  42. make_mask,
  43. masked,
  44. masked_array,
  45. masked_equal,
  46. masked_greater,
  47. masked_greater_equal,
  48. masked_inside,
  49. masked_less,
  50. masked_less_equal,
  51. masked_not_equal,
  52. masked_outside,
  53. masked_print_option,
  54. masked_values,
  55. masked_where,
  56. maximum,
  57. minimum,
  58. multiply,
  59. nomask,
  60. nonzero,
  61. not_equal,
  62. ones,
  63. outer,
  64. product,
  65. put,
  66. ravel,
  67. repeat,
  68. resize,
  69. shape,
  70. sin,
  71. sinh,
  72. sometrue,
  73. sort,
  74. sqrt,
  75. subtract,
  76. sum,
  77. take,
  78. tan,
  79. tanh,
  80. transpose,
  81. where,
  82. zeros,
  83. )
  84. from numpy.testing import assert_, assert_equal, assert_raises
  85. pi = np.pi
  86. def eq(v, w, msg=''):
  87. result = allclose(v, w)
  88. if not result:
  89. print(f'Not eq:{msg}\n{v}\n----{w}')
  90. return result
  91. class TestMa:
  92. def _create_data(self):
  93. x = np.array([1., 1., 1., -2., pi / 2.0, 4., 5., -10., 10., 1., 2., 3.])
  94. y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.])
  95. a10 = 10.
  96. m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
  97. m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1]
  98. xm = array(x, mask=m1)
  99. ym = array(y, mask=m2)
  100. z = np.array([-.5, 0., .5, .8])
  101. zm = array(z, mask=[0, 1, 0, 0])
  102. xf = np.where(m1, 1e+20, x)
  103. s = x.shape
  104. xm.set_fill_value(1e+20)
  105. return x, y, a10, m1, m2, xm, ym, z, zm, xf, s
  106. def test_testBasic1d(self):
  107. # Test of basic array creation and properties in 1 dimension.
  108. x, _, _, m1, _, xm, _, _, _, xf, s = self._create_data()
  109. assert_(not isMaskedArray(x))
  110. assert_(isMaskedArray(xm))
  111. assert_equal(shape(xm), s)
  112. assert_equal(xm.shape, s)
  113. assert_equal(xm.dtype, x.dtype)
  114. assert_equal(xm.size, reduce(lambda x, y: x * y, s))
  115. assert_equal(count(xm), len(m1) - reduce(lambda x, y: x + y, m1))
  116. assert_(eq(xm, xf))
  117. assert_(eq(filled(xm, 1.e20), xf))
  118. assert_(eq(x, xm))
  119. @pytest.mark.parametrize("s", [(4, 3), (6, 2)])
  120. def test_testBasic2d(self, s):
  121. # Test of basic array creation and properties in 2 dimensions.
  122. x, y, _, m1, _, xm, ym, _, _, xf, s = self._create_data()
  123. x.shape = s
  124. y.shape = s
  125. xm.shape = s
  126. ym.shape = s
  127. xf.shape = s
  128. assert_(not isMaskedArray(x))
  129. assert_(isMaskedArray(xm))
  130. assert_equal(shape(xm), s)
  131. assert_equal(xm.shape, s)
  132. assert_equal(xm.size, reduce(lambda x, y: x * y, s))
  133. assert_equal(count(xm), len(m1) - reduce(lambda x, y: x + y, m1))
  134. assert_(eq(xm, xf))
  135. assert_(eq(filled(xm, 1.e20), xf))
  136. assert_(eq(x, xm))
  137. def test_testArithmetic(self):
  138. # Test of basic arithmetic.
  139. x, y, a10, _, _, xm, ym, _, _, xf, s = self._create_data()
  140. a2d = array([[1, 2], [0, 4]])
  141. a2dm = masked_array(a2d, [[0, 0], [1, 0]])
  142. assert_(eq(a2d * a2d, a2d * a2dm))
  143. assert_(eq(a2d + a2d, a2d + a2dm))
  144. assert_(eq(a2d - a2d, a2d - a2dm))
  145. for s in [(12,), (4, 3), (2, 6)]:
  146. x = x.reshape(s)
  147. y = y.reshape(s)
  148. xm = xm.reshape(s)
  149. ym = ym.reshape(s)
  150. xf = xf.reshape(s)
  151. assert_(eq(-x, -xm))
  152. assert_(eq(x + y, xm + ym))
  153. assert_(eq(x - y, xm - ym))
  154. assert_(eq(x * y, xm * ym))
  155. with np.errstate(divide='ignore', invalid='ignore'):
  156. assert_(eq(x / y, xm / ym))
  157. assert_(eq(a10 + y, a10 + ym))
  158. assert_(eq(a10 - y, a10 - ym))
  159. assert_(eq(a10 * y, a10 * ym))
  160. with np.errstate(divide='ignore', invalid='ignore'):
  161. assert_(eq(a10 / y, a10 / ym))
  162. assert_(eq(x + a10, xm + a10))
  163. assert_(eq(x - a10, xm - a10))
  164. assert_(eq(x * a10, xm * a10))
  165. assert_(eq(x / a10, xm / a10))
  166. assert_(eq(x ** 2, xm ** 2))
  167. assert_(eq(abs(x) ** 2.5, abs(xm) ** 2.5))
  168. assert_(eq(x ** y, xm ** ym))
  169. assert_(eq(np.add(x, y), add(xm, ym)))
  170. assert_(eq(np.subtract(x, y), subtract(xm, ym)))
  171. assert_(eq(np.multiply(x, y), multiply(xm, ym)))
  172. with np.errstate(divide='ignore', invalid='ignore'):
  173. assert_(eq(np.divide(x, y), divide(xm, ym)))
  174. def test_testMixedArithmetic(self):
  175. na = np.array([1])
  176. ma = array([1])
  177. assert_(isinstance(na + ma, MaskedArray))
  178. assert_(isinstance(ma + na, MaskedArray))
  179. def test_testUfuncs1(self):
  180. # Test various functions such as sin, cos.
  181. x, y, _, _, _, xm, ym, z, zm, _, _ = self._create_data()
  182. assert_(eq(np.cos(x), cos(xm)))
  183. assert_(eq(np.cosh(x), cosh(xm)))
  184. assert_(eq(np.sin(x), sin(xm)))
  185. assert_(eq(np.sinh(x), sinh(xm)))
  186. assert_(eq(np.tan(x), tan(xm)))
  187. assert_(eq(np.tanh(x), tanh(xm)))
  188. with np.errstate(divide='ignore', invalid='ignore'):
  189. assert_(eq(np.sqrt(abs(x)), sqrt(xm)))
  190. assert_(eq(np.log(abs(x)), log(xm)))
  191. assert_(eq(np.log10(abs(x)), log10(xm)))
  192. assert_(eq(np.exp(x), exp(xm)))
  193. assert_(eq(np.arcsin(z), arcsin(zm)))
  194. assert_(eq(np.arccos(z), arccos(zm)))
  195. assert_(eq(np.arctan(z), arctan(zm)))
  196. assert_(eq(np.arctan2(x, y), arctan2(xm, ym)))
  197. assert_(eq(np.absolute(x), absolute(xm)))
  198. assert_(eq(np.equal(x, y), equal(xm, ym)))
  199. assert_(eq(np.not_equal(x, y), not_equal(xm, ym)))
  200. assert_(eq(np.less(x, y), less(xm, ym)))
  201. assert_(eq(np.greater(x, y), greater(xm, ym)))
  202. assert_(eq(np.less_equal(x, y), less_equal(xm, ym)))
  203. assert_(eq(np.greater_equal(x, y), greater_equal(xm, ym)))
  204. assert_(eq(np.conjugate(x), conjugate(xm)))
  205. assert_(eq(np.concatenate((x, y)), concatenate((xm, ym))))
  206. assert_(eq(np.concatenate((x, y)), concatenate((x, y))))
  207. assert_(eq(np.concatenate((x, y)), concatenate((xm, y))))
  208. assert_(eq(np.concatenate((x, y, x)), concatenate((x, ym, x))))
  209. def test_xtestCount(self):
  210. # Test count
  211. ott = array([0., 1., 2., 3.], mask=[1, 0, 0, 0])
  212. assert_(count(ott).dtype.type is np.intp)
  213. assert_equal(3, count(ott))
  214. assert_equal(1, count(1))
  215. assert_(eq(0, array(1, mask=[1])))
  216. ott = ott.reshape((2, 2))
  217. assert_(count(ott).dtype.type is np.intp)
  218. assert_(isinstance(count(ott, 0), np.ndarray))
  219. assert_(count(ott).dtype.type is np.intp)
  220. assert_(eq(3, count(ott)))
  221. assert_(getmask(count(ott, 0)) is nomask)
  222. assert_(eq([1, 2], count(ott, 0)))
  223. def test_testMinMax(self):
  224. # Test minimum and maximum.
  225. x, _, _, _, _, xm, _, _, _, _, _ = self._create_data()
  226. xr = np.ravel(x) # max doesn't work if shaped
  227. xmr = ravel(xm)
  228. # true because of careful selection of data
  229. assert_(eq(max(xr), maximum.reduce(xmr)))
  230. assert_(eq(min(xr), minimum.reduce(xmr)))
  231. def test_testAddSumProd(self):
  232. # Test add, sum, product.
  233. x, y, _, _, _, xm, ym, _, _, _, s = self._create_data()
  234. assert_(eq(np.add.reduce(x), add.reduce(x)))
  235. assert_(eq(np.add.accumulate(x), add.accumulate(x)))
  236. assert_(eq(4, sum(array(4), axis=0)))
  237. assert_(eq(4, sum(array(4), axis=0)))
  238. assert_(eq(np.sum(x, axis=0), sum(x, axis=0)))
  239. assert_(eq(np.sum(filled(xm, 0), axis=0), sum(xm, axis=0)))
  240. assert_(eq(np.sum(x, 0), sum(x, 0)))
  241. assert_(eq(np.prod(x, axis=0), product(x, axis=0)))
  242. assert_(eq(np.prod(x, 0), product(x, 0)))
  243. assert_(eq(np.prod(filled(xm, 1), axis=0),
  244. product(xm, axis=0)))
  245. if len(s) > 1:
  246. assert_(eq(np.concatenate((x, y), 1),
  247. concatenate((xm, ym), 1)))
  248. assert_(eq(np.add.reduce(x, 1), add.reduce(x, 1)))
  249. assert_(eq(np.sum(x, 1), sum(x, 1)))
  250. assert_(eq(np.prod(x, 1), product(x, 1)))
  251. def test_testCI(self):
  252. # Test of conversions and indexing
  253. x1 = np.array([1, 2, 4, 3])
  254. x2 = array(x1, mask=[1, 0, 0, 0])
  255. x3 = array(x1, mask=[0, 1, 0, 1])
  256. x4 = array(x1)
  257. # test conversion to strings
  258. str(x2) # raises?
  259. repr(x2) # raises?
  260. assert_(eq(np.sort(x1), sort(x2, fill_value=0)))
  261. # tests of indexing
  262. assert_(type(x2[1]) is type(x1[1]))
  263. assert_(x1[1] == x2[1])
  264. assert_(x2[0] is masked)
  265. assert_(eq(x1[2], x2[2]))
  266. assert_(eq(x1[2:5], x2[2:5]))
  267. assert_(eq(x1[:], x2[:]))
  268. assert_(eq(x1[1:], x3[1:]))
  269. x1[2] = 9
  270. x2[2] = 9
  271. assert_(eq(x1, x2))
  272. x1[1:3] = 99
  273. x2[1:3] = 99
  274. assert_(eq(x1, x2))
  275. x2[1] = masked
  276. assert_(eq(x1, x2))
  277. x2[1:3] = masked
  278. assert_(eq(x1, x2))
  279. x2[:] = x1
  280. x2[1] = masked
  281. assert_(allequal(getmask(x2), array([0, 1, 0, 0])))
  282. x3[:] = masked_array([1, 2, 3, 4], [0, 1, 1, 0])
  283. assert_(allequal(getmask(x3), array([0, 1, 1, 0])))
  284. x4[:] = masked_array([1, 2, 3, 4], [0, 1, 1, 0])
  285. assert_(allequal(getmask(x4), array([0, 1, 1, 0])))
  286. assert_(allequal(x4, array([1, 2, 3, 4])))
  287. x1 = np.arange(5) * 1.0
  288. x2 = masked_values(x1, 3.0)
  289. assert_(eq(x1, x2))
  290. assert_(allequal(array([0, 0, 0, 1, 0], MaskType), x2.mask))
  291. assert_(eq(3.0, x2.fill_value))
  292. x1 = array([1, 'hello', 2, 3], object)
  293. x2 = np.array([1, 'hello', 2, 3], object)
  294. s1 = x1[1]
  295. s2 = x2[1]
  296. assert_equal(type(s2), str)
  297. assert_equal(type(s1), str)
  298. assert_equal(s1, s2)
  299. assert_(x1[1:1].shape == (0,))
  300. def test_testCopySize(self):
  301. # Tests of some subtle points of copying and sizing.
  302. n = [0, 0, 1, 0, 0]
  303. m = make_mask(n)
  304. m2 = make_mask(m)
  305. assert_(m is m2)
  306. m3 = make_mask(m, copy=True)
  307. assert_(m is not m3)
  308. x1 = np.arange(5)
  309. y1 = array(x1, mask=m)
  310. assert_(y1._data is not x1)
  311. assert_(allequal(x1, y1._data))
  312. assert_(y1._mask is m)
  313. y1a = array(y1, copy=0)
  314. # For copy=False, one might expect that the array would just
  315. # passed on, i.e., that it would be "is" instead of "==".
  316. # See gh-4043 for discussion.
  317. assert_(y1a._mask.__array_interface__ ==
  318. y1._mask.__array_interface__)
  319. y2 = array(x1, mask=m3, copy=0)
  320. assert_(y2._mask is m3)
  321. assert_(y2[2] is masked)
  322. y2[2] = 9
  323. assert_(y2[2] is not masked)
  324. assert_(y2._mask is m3)
  325. assert_(allequal(y2.mask, 0))
  326. y2a = array(x1, mask=m, copy=1)
  327. assert_(y2a._mask is not m)
  328. assert_(y2a[2] is masked)
  329. y2a[2] = 9
  330. assert_(y2a[2] is not masked)
  331. assert_(y2a._mask is not m)
  332. assert_(allequal(y2a.mask, 0))
  333. y3 = array(x1 * 1.0, mask=m)
  334. assert_(filled(y3).dtype is (x1 * 1.0).dtype)
  335. x4 = arange(4)
  336. x4[2] = masked
  337. y4 = resize(x4, (8,))
  338. assert_(eq(concatenate([x4, x4]), y4))
  339. assert_(eq(getmask(y4), [0, 0, 1, 0, 0, 0, 1, 0]))
  340. y5 = repeat(x4, (2, 2, 2, 2), axis=0)
  341. assert_(eq(y5, [0, 0, 1, 1, 2, 2, 3, 3]))
  342. y6 = repeat(x4, 2, axis=0)
  343. assert_(eq(y5, y6))
  344. def test_testPut(self):
  345. # Test of put
  346. d = arange(5)
  347. n = [0, 0, 0, 1, 1]
  348. m = make_mask(n)
  349. m2 = m.copy()
  350. x = array(d, mask=m)
  351. assert_(x[3] is masked)
  352. assert_(x[4] is masked)
  353. x[[1, 4]] = [10, 40]
  354. assert_(x._mask is m)
  355. assert_(x[3] is masked)
  356. assert_(x[4] is not masked)
  357. assert_(eq(x, [0, 10, 2, -1, 40]))
  358. x = array(d, mask=m2, copy=True)
  359. x.put([0, 1, 2], [-1, 100, 200])
  360. assert_(x._mask is not m2)
  361. assert_(x[3] is masked)
  362. assert_(x[4] is masked)
  363. assert_(eq(x, [-1, 100, 200, 0, 0]))
  364. def test_testPut2(self):
  365. # Test of put
  366. d = arange(5)
  367. x = array(d, mask=[0, 0, 0, 0, 0])
  368. z = array([10, 40], mask=[1, 0])
  369. assert_(x[2] is not masked)
  370. assert_(x[3] is not masked)
  371. x[2:4] = z
  372. assert_(x[2] is masked)
  373. assert_(x[3] is not masked)
  374. assert_(eq(x, [0, 1, 10, 40, 4]))
  375. d = arange(5)
  376. x = array(d, mask=[0, 0, 0, 0, 0])
  377. y = x[2:4]
  378. z = array([10, 40], mask=[1, 0])
  379. assert_(x[2] is not masked)
  380. assert_(x[3] is not masked)
  381. y[:] = z
  382. assert_(y[0] is masked)
  383. assert_(y[1] is not masked)
  384. assert_(eq(y, [10, 40]))
  385. assert_(x[2] is masked)
  386. assert_(x[3] is not masked)
  387. assert_(eq(x, [0, 1, 10, 40, 4]))
  388. def test_testMaPut(self):
  389. _, _, _, _, _, _, ym, _, zm, _, _ = self._create_data()
  390. m = [1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1]
  391. i = np.nonzero(m)[0]
  392. put(ym, i, zm)
  393. assert_(all(take(ym, i, axis=0) == zm))
  394. def test_testOddFeatures(self):
  395. # Test of other odd features
  396. x = arange(20)
  397. x = x.reshape(4, 5)
  398. x.flat[5] = 12
  399. assert_(x[1, 0] == 12)
  400. z = x + 10j * x
  401. assert_(eq(z.real, x))
  402. assert_(eq(z.imag, 10 * x))
  403. assert_(eq((z * conjugate(z)).real, 101 * x * x))
  404. z.imag[...] = 0.0
  405. x = arange(10)
  406. x[3] = masked
  407. assert_(str(x[3]) == str(masked))
  408. c = x >= 8
  409. assert_(count(where(c, masked, masked)) == 0)
  410. assert_(shape(where(c, masked, masked)) == c.shape)
  411. z = where(c, x, masked)
  412. assert_(z.dtype is x.dtype)
  413. assert_(z[3] is masked)
  414. assert_(z[4] is masked)
  415. assert_(z[7] is masked)
  416. assert_(z[8] is not masked)
  417. assert_(z[9] is not masked)
  418. assert_(eq(x, z))
  419. z = where(c, masked, x)
  420. assert_(z.dtype is x.dtype)
  421. assert_(z[3] is masked)
  422. assert_(z[4] is not masked)
  423. assert_(z[7] is not masked)
  424. assert_(z[8] is masked)
  425. assert_(z[9] is masked)
  426. z = masked_where(c, x)
  427. assert_(z.dtype is x.dtype)
  428. assert_(z[3] is masked)
  429. assert_(z[4] is not masked)
  430. assert_(z[7] is not masked)
  431. assert_(z[8] is masked)
  432. assert_(z[9] is masked)
  433. assert_(eq(x, z))
  434. x = array([1., 2., 3., 4., 5.])
  435. c = array([1, 1, 1, 0, 0])
  436. x[2] = masked
  437. z = where(c, x, -x)
  438. assert_(eq(z, [1., 2., 0., -4., -5]))
  439. c[0] = masked
  440. z = where(c, x, -x)
  441. assert_(eq(z, [1., 2., 0., -4., -5]))
  442. assert_(z[0] is masked)
  443. assert_(z[1] is not masked)
  444. assert_(z[2] is masked)
  445. assert_(eq(masked_where(greater(x, 2), x), masked_greater(x, 2)))
  446. assert_(eq(masked_where(greater_equal(x, 2), x),
  447. masked_greater_equal(x, 2)))
  448. assert_(eq(masked_where(less(x, 2), x), masked_less(x, 2)))
  449. assert_(eq(masked_where(less_equal(x, 2), x), masked_less_equal(x, 2)))
  450. assert_(eq(masked_where(not_equal(x, 2), x), masked_not_equal(x, 2)))
  451. assert_(eq(masked_where(equal(x, 2), x), masked_equal(x, 2)))
  452. assert_(eq(masked_where(not_equal(x, 2), x), masked_not_equal(x, 2)))
  453. assert_(eq(masked_inside(list(range(5)), 1, 3), [0, 199, 199, 199, 4]))
  454. assert_(eq(masked_outside(list(range(5)), 1, 3), [199, 1, 2, 3, 199]))
  455. assert_(eq(masked_inside(array(list(range(5)),
  456. mask=[1, 0, 0, 0, 0]), 1, 3).mask,
  457. [1, 1, 1, 1, 0]))
  458. assert_(eq(masked_outside(array(list(range(5)),
  459. mask=[0, 1, 0, 0, 0]), 1, 3).mask,
  460. [1, 1, 0, 0, 1]))
  461. assert_(eq(masked_equal(array(list(range(5)),
  462. mask=[1, 0, 0, 0, 0]), 2).mask,
  463. [1, 0, 1, 0, 0]))
  464. assert_(eq(masked_not_equal(array([2, 2, 1, 2, 1],
  465. mask=[1, 0, 0, 0, 0]), 2).mask,
  466. [1, 0, 1, 0, 1]))
  467. assert_(eq(masked_where([1, 1, 0, 0, 0], [1, 2, 3, 4, 5]),
  468. [99, 99, 3, 4, 5]))
  469. atest = ones((10, 10, 10), dtype=np.float32)
  470. btest = zeros(atest.shape, MaskType)
  471. ctest = masked_where(btest, atest)
  472. assert_(eq(atest, ctest))
  473. z = choose(c, (-x, x))
  474. assert_(eq(z, [1., 2., 0., -4., -5]))
  475. assert_(z[0] is masked)
  476. assert_(z[1] is not masked)
  477. assert_(z[2] is masked)
  478. x = arange(6)
  479. x[5] = masked
  480. y = arange(6) * 10
  481. y[2] = masked
  482. c = array([1, 1, 1, 0, 0, 0], mask=[1, 0, 0, 0, 0, 0])
  483. cm = c.filled(1)
  484. z = where(c, x, y)
  485. zm = where(cm, x, y)
  486. assert_(eq(z, zm))
  487. assert_(getmask(zm) is nomask)
  488. assert_(eq(zm, [0, 1, 2, 30, 40, 50]))
  489. z = where(c, masked, 1)
  490. assert_(eq(z, [99, 99, 99, 1, 1, 1]))
  491. z = where(c, 1, masked)
  492. assert_(eq(z, [99, 1, 1, 99, 99, 99]))
  493. def test_testMinMax2(self):
  494. # Test of minimum, maximum.
  495. assert_(eq(minimum([1, 2, 3], [4, 0, 9]), [1, 0, 3]))
  496. assert_(eq(maximum([1, 2, 3], [4, 0, 9]), [4, 2, 9]))
  497. x = arange(5)
  498. y = arange(5) - 2
  499. x[3] = masked
  500. y[0] = masked
  501. assert_(eq(minimum(x, y), where(less(x, y), x, y)))
  502. assert_(eq(maximum(x, y), where(greater(x, y), x, y)))
  503. assert_(minimum.reduce(x) == 0)
  504. assert_(maximum.reduce(x) == 4)
  505. def test_testTakeTransposeInnerOuter(self):
  506. # Test of take, transpose, inner, outer products
  507. x = arange(24)
  508. y = np.arange(24)
  509. x[5:6] = masked
  510. x = x.reshape(2, 3, 4)
  511. y = y.reshape(2, 3, 4)
  512. assert_(eq(np.transpose(y, (2, 0, 1)), transpose(x, (2, 0, 1))))
  513. assert_(eq(np.take(y, (2, 0, 1), 1), take(x, (2, 0, 1), 1)))
  514. assert_(eq(np.inner(filled(x, 0), filled(y, 0)),
  515. inner(x, y)))
  516. assert_(eq(np.outer(filled(x, 0), filled(y, 0)),
  517. outer(x, y)))
  518. y = array(['abc', 1, 'def', 2, 3], object)
  519. y[2] = masked
  520. t = take(y, [0, 3, 4])
  521. assert_(t[0] == 'abc')
  522. assert_(t[1] == 2)
  523. assert_(t[2] == 3)
  524. def test_testInplace(self):
  525. # Test of inplace operations and rich comparisons
  526. y = arange(10)
  527. x = arange(10)
  528. xm = arange(10)
  529. xm[2] = masked
  530. x += 1
  531. assert_(eq(x, y + 1))
  532. xm += 1
  533. assert_(eq(x, y + 1))
  534. x = arange(10)
  535. xm = arange(10)
  536. xm[2] = masked
  537. x -= 1
  538. assert_(eq(x, y - 1))
  539. xm -= 1
  540. assert_(eq(xm, y - 1))
  541. x = arange(10) * 1.0
  542. xm = arange(10) * 1.0
  543. xm[2] = masked
  544. x *= 2.0
  545. assert_(eq(x, y * 2))
  546. xm *= 2.0
  547. assert_(eq(xm, y * 2))
  548. x = arange(10) * 2
  549. xm = arange(10)
  550. xm[2] = masked
  551. x //= 2
  552. assert_(eq(x, y))
  553. xm //= 2
  554. assert_(eq(x, y))
  555. x = arange(10) * 1.0
  556. xm = arange(10) * 1.0
  557. xm[2] = masked
  558. x /= 2.0
  559. assert_(eq(x, y / 2.0))
  560. xm /= arange(10)
  561. assert_(eq(xm, ones((10,))))
  562. x = arange(10).astype(np.float32)
  563. xm = arange(10)
  564. xm[2] = masked
  565. x += 1.
  566. assert_(eq(x, y + 1.))
  567. def test_testPickle(self):
  568. # Test of pickling
  569. x = arange(12)
  570. x[4:10:2] = masked
  571. x = x.reshape(4, 3)
  572. for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
  573. s = pickle.dumps(x, protocol=proto)
  574. y = pickle.loads(s)
  575. assert_(eq(x, y))
  576. def test_testMasked(self):
  577. # Test of masked element
  578. xx = arange(6)
  579. xx[1] = masked
  580. assert_(str(masked) == '--')
  581. assert_(xx[1] is masked)
  582. assert_equal(filled(xx[1], 0), 0)
  583. def test_testAverage1(self):
  584. # Test of average.
  585. ott = array([0., 1., 2., 3.], mask=[1, 0, 0, 0])
  586. assert_(eq(2.0, average(ott, axis=0)))
  587. assert_(eq(2.0, average(ott, weights=[1., 1., 2., 1.])))
  588. result, wts = average(ott, weights=[1., 1., 2., 1.], returned=True)
  589. assert_(eq(2.0, result))
  590. assert_(wts == 4.0)
  591. ott[:] = masked
  592. assert_(average(ott, axis=0) is masked)
  593. ott = array([0., 1., 2., 3.], mask=[1, 0, 0, 0])
  594. ott = ott.reshape(2, 2)
  595. ott[:, 1] = masked
  596. assert_(eq(average(ott, axis=0), [2.0, 0.0]))
  597. assert_(average(ott, axis=1)[0] is masked)
  598. assert_(eq([2., 0.], average(ott, axis=0)))
  599. result, wts = average(ott, axis=0, returned=True)
  600. assert_(eq(wts, [1., 0.]))
  601. def test_testAverage2(self):
  602. # More tests of average.
  603. w1 = [0, 1, 1, 1, 1, 0]
  604. w2 = [[0, 1, 1, 1, 1, 0], [1, 0, 0, 0, 0, 1]]
  605. x = arange(6)
  606. assert_(allclose(average(x, axis=0), 2.5))
  607. assert_(allclose(average(x, axis=0, weights=w1), 2.5))
  608. y = array([arange(6), 2.0 * arange(6)])
  609. assert_(allclose(average(y, None),
  610. np.add.reduce(np.arange(6)) * 3. / 12.))
  611. assert_(allclose(average(y, axis=0), np.arange(6) * 3. / 2.))
  612. assert_(allclose(average(y, axis=1),
  613. [average(x, axis=0), average(x, axis=0) * 2.0]))
  614. assert_(allclose(average(y, None, weights=w2), 20. / 6.))
  615. assert_(allclose(average(y, axis=0, weights=w2),
  616. [0., 1., 2., 3., 4., 10.]))
  617. assert_(allclose(average(y, axis=1),
  618. [average(x, axis=0), average(x, axis=0) * 2.0]))
  619. m1 = zeros(6)
  620. m2 = [0, 0, 1, 1, 0, 0]
  621. m3 = [[0, 0, 1, 1, 0, 0], [0, 1, 1, 1, 1, 0]]
  622. m4 = ones(6)
  623. m5 = [0, 1, 1, 1, 1, 1]
  624. assert_(allclose(average(masked_array(x, m1), axis=0), 2.5))
  625. assert_(allclose(average(masked_array(x, m2), axis=0), 2.5))
  626. assert_(average(masked_array(x, m4), axis=0) is masked)
  627. assert_equal(average(masked_array(x, m5), axis=0), 0.0)
  628. assert_equal(count(average(masked_array(x, m4), axis=0)), 0)
  629. z = masked_array(y, m3)
  630. assert_(allclose(average(z, None), 20. / 6.))
  631. assert_(allclose(average(z, axis=0),
  632. [0., 1., 99., 99., 4.0, 7.5]))
  633. assert_(allclose(average(z, axis=1), [2.5, 5.0]))
  634. assert_(allclose(average(z, axis=0, weights=w2),
  635. [0., 1., 99., 99., 4.0, 10.0]))
  636. a = arange(6)
  637. b = arange(6) * 3
  638. r1, w1 = average([[a, b], [b, a]], axis=1, returned=True)
  639. assert_equal(shape(r1), shape(w1))
  640. assert_equal(r1.shape, w1.shape)
  641. r2, w2 = average(ones((2, 2, 3)), axis=0, weights=[3, 1], returned=True)
  642. assert_equal(shape(w2), shape(r2))
  643. r2, w2 = average(ones((2, 2, 3)), returned=True)
  644. assert_equal(shape(w2), shape(r2))
  645. r2, w2 = average(ones((2, 2, 3)), weights=ones((2, 2, 3)), returned=True)
  646. assert_(shape(w2) == shape(r2))
  647. a2d = array([[1, 2], [0, 4]], float)
  648. a2dm = masked_array(a2d, [[0, 0], [1, 0]])
  649. a2da = average(a2d, axis=0)
  650. assert_(eq(a2da, [0.5, 3.0]))
  651. a2dma = average(a2dm, axis=0)
  652. assert_(eq(a2dma, [1.0, 3.0]))
  653. a2dma = average(a2dm, axis=None)
  654. assert_(eq(a2dma, 7. / 3.))
  655. a2dma = average(a2dm, axis=1)
  656. assert_(eq(a2dma, [1.5, 4.0]))
  657. def test_testToPython(self):
  658. assert_equal(1, int(array(1)))
  659. assert_equal(1.0, float(array(1)))
  660. assert_equal(1, int(array([[[1]]])))
  661. assert_equal(1.0, float(array([[1]])))
  662. assert_raises(TypeError, float, array([1, 1]))
  663. assert_raises(ValueError, bool, array([0, 1]))
  664. assert_raises(ValueError, bool, array([0, 0], mask=[0, 1]))
  665. def test_testScalarArithmetic(self):
  666. xm = array(0, mask=1)
  667. # TODO FIXME: Find out what the following raises a warning in r8247
  668. with np.errstate(divide='ignore'):
  669. assert_((1 / array(0)).mask)
  670. assert_((1 + xm).mask)
  671. assert_((-xm).mask)
  672. assert_((-xm).mask)
  673. assert_(maximum(xm, xm).mask)
  674. assert_(minimum(xm, xm).mask)
  675. assert_(xm.filled().dtype is xm._data.dtype)
  676. x = array(0, mask=0)
  677. assert_(x.filled() == x._data)
  678. assert_equal(str(xm), str(masked_print_option))
  679. def test_testArrayMethods(self):
  680. a = array([1, 3, 2])
  681. assert_(eq(a.any(), a._data.any()))
  682. assert_(eq(a.all(), a._data.all()))
  683. assert_(eq(a.argmax(), a._data.argmax()))
  684. assert_(eq(a.argmin(), a._data.argmin()))
  685. assert_(eq(a.choose(0, 1, 2, 3, 4),
  686. a._data.choose(0, 1, 2, 3, 4)))
  687. assert_(eq(a.compress([1, 0, 1]), a._data.compress([1, 0, 1])))
  688. assert_(eq(a.conj(), a._data.conj()))
  689. assert_(eq(a.conjugate(), a._data.conjugate()))
  690. m = array([[1, 2], [3, 4]])
  691. assert_(eq(m.diagonal(), m._data.diagonal()))
  692. assert_(eq(a.sum(), a._data.sum()))
  693. assert_(eq(a.take([1, 2]), a._data.take([1, 2])))
  694. assert_(eq(m.transpose(), m._data.transpose()))
  695. def test_testArrayAttributes(self):
  696. a = array([1, 3, 2])
  697. assert_equal(a.ndim, 1)
  698. def test_testAPI(self):
  699. assert_(not [m for m in dir(np.ndarray)
  700. if m not in dir(MaskedArray) and
  701. not m.startswith('_')])
  702. def test_testSingleElementSubscript(self):
  703. a = array([1, 3, 2])
  704. b = array([1, 3, 2], mask=[1, 0, 1])
  705. assert_equal(a[0].shape, ())
  706. assert_equal(b[0].shape, ())
  707. assert_equal(b[1].shape, ())
  708. def test_assignment_by_condition(self):
  709. # Test for gh-18951
  710. a = array([1, 2, 3, 4], mask=[1, 0, 1, 0])
  711. c = a >= 3
  712. a[c] = 5
  713. assert_(a[2] is masked)
  714. def test_assignment_by_condition_2(self):
  715. # gh-19721
  716. a = masked_array([0, 1], mask=[False, False])
  717. b = masked_array([0, 1], mask=[True, True])
  718. mask = a < 1
  719. b[mask] = a[mask]
  720. expected_mask = [False, True]
  721. assert_equal(b.mask, expected_mask)
  722. class TestUfuncs:
  723. def _create_data(self):
  724. return (array([1.0, 0, -1, pi / 2] * 2, mask=[0, 1] + [0] * 6),
  725. array([1.0, 0, -1, pi / 2] * 2, mask=[1, 0] + [0] * 6),)
  726. def test_testUfuncRegression(self):
  727. f_invalid_ignore = [
  728. 'sqrt', 'arctanh', 'arcsin', 'arccos',
  729. 'arccosh', 'arctanh', 'log', 'log10', 'divide',
  730. 'true_divide', 'floor_divide', 'remainder', 'fmod']
  731. for f in ['sqrt', 'log', 'log10', 'exp', 'conjugate',
  732. 'sin', 'cos', 'tan',
  733. 'arcsin', 'arccos', 'arctan',
  734. 'sinh', 'cosh', 'tanh',
  735. 'arcsinh',
  736. 'arccosh',
  737. 'arctanh',
  738. 'absolute', 'fabs', 'negative',
  739. 'floor', 'ceil',
  740. 'logical_not',
  741. 'add', 'subtract', 'multiply',
  742. 'divide', 'true_divide', 'floor_divide',
  743. 'remainder', 'fmod', 'hypot', 'arctan2',
  744. 'equal', 'not_equal', 'less_equal', 'greater_equal',
  745. 'less', 'greater',
  746. 'logical_and', 'logical_or', 'logical_xor']:
  747. try:
  748. uf = getattr(umath, f)
  749. except AttributeError:
  750. uf = getattr(fromnumeric, f)
  751. mf = getattr(np.ma, f)
  752. args = self._create_data()[:uf.nin]
  753. with np.errstate():
  754. if f in f_invalid_ignore:
  755. np.seterr(invalid='ignore')
  756. if f in ['arctanh', 'log', 'log10']:
  757. np.seterr(divide='ignore')
  758. ur = uf(*args)
  759. mr = mf(*args)
  760. assert_(eq(ur.filled(0), mr.filled(0), f))
  761. assert_(eqmask(ur.mask, mr.mask))
  762. def test_reduce(self):
  763. a = self._create_data()[0]
  764. assert_(not alltrue(a, axis=0))
  765. assert_(sometrue(a, axis=0))
  766. assert_equal(sum(a[:3], axis=0), 0)
  767. assert_equal(product(a, axis=0), 0)
  768. def test_minmax(self):
  769. a = arange(1, 13).reshape(3, 4)
  770. amask = masked_where(a < 5, a)
  771. assert_equal(amask.max(), a.max())
  772. assert_equal(amask.min(), 5)
  773. assert_((amask.max(0) == a.max(0)).all())
  774. assert_((amask.min(0) == [5, 6, 7, 8]).all())
  775. assert_(amask.max(1)[0].mask)
  776. assert_(amask.min(1)[0].mask)
  777. def test_nonzero(self):
  778. for t in "?bhilqpBHILQPfdgFDGO":
  779. x = array([1, 0, 2, 0], mask=[0, 0, 1, 1])
  780. assert_(eq(nonzero(x), [0]))
  781. class TestArrayMethods:
  782. def _create_data(self):
  783. x = np.array([8.375, 7.545, 8.828, 8.5, 1.757, 5.928,
  784. 8.43, 7.78, 9.865, 5.878, 8.979, 4.732,
  785. 3.012, 6.022, 5.095, 3.116, 5.238, 3.957,
  786. 6.04, 9.63, 7.712, 3.382, 4.489, 6.479,
  787. 7.189, 9.645, 5.395, 4.961, 9.894, 2.893,
  788. 7.357, 9.828, 6.272, 3.758, 6.693, 0.993])
  789. X = x.reshape(6, 6)
  790. XX = x.reshape(3, 2, 2, 3)
  791. m = np.array([0, 1, 0, 1, 0, 0,
  792. 1, 0, 1, 1, 0, 1,
  793. 0, 0, 0, 1, 0, 1,
  794. 0, 0, 0, 1, 1, 1,
  795. 1, 0, 0, 1, 0, 0,
  796. 0, 0, 1, 0, 1, 0])
  797. mx = array(data=x, mask=m)
  798. mX = array(data=X, mask=m.reshape(X.shape))
  799. mXX = array(data=XX, mask=m.reshape(XX.shape))
  800. return x, X, XX, m, mx, mX, mXX
  801. def test_trace(self):
  802. _, X, _, _, _, mX, _ = self._create_data()
  803. mXdiag = mX.diagonal()
  804. assert_equal(mX.trace(), mX.diagonal().compressed().sum())
  805. assert_(eq(mX.trace(),
  806. X.trace() - sum(mXdiag.mask * X.diagonal(),
  807. axis=0)))
  808. def test_clip(self):
  809. x, _, _, _, mx, _, _ = self._create_data()
  810. clipped = mx.clip(2, 8)
  811. assert_(eq(clipped.mask, mx.mask))
  812. assert_(eq(clipped._data, x.clip(2, 8)))
  813. assert_(eq(clipped._data, mx._data.clip(2, 8)))
  814. def test_ptp(self):
  815. _, X, _, m, mx, mX, _ = self._create_data()
  816. n, m = X.shape
  817. # print(type(mx), mx.compressed())
  818. # raise Exception()
  819. assert_equal(mx.ptp(), np.ptp(mx.compressed()))
  820. rows = np.zeros(n, np.float64)
  821. cols = np.zeros(m, np.float64)
  822. for k in range(m):
  823. cols[k] = np.ptp(mX[:, k].compressed())
  824. for k in range(n):
  825. rows[k] = np.ptp(mX[k].compressed())
  826. assert_(eq(mX.ptp(0), cols))
  827. assert_(eq(mX.ptp(1), rows))
  828. def test_swapaxes(self):
  829. _, _, _, _, _, mX, mXX = self._create_data()
  830. mXswapped = mX.swapaxes(0, 1)
  831. assert_(eq(mXswapped[-1], mX[:, -1]))
  832. mXXswapped = mXX.swapaxes(0, 2)
  833. assert_equal(mXXswapped.shape, (2, 2, 3, 3))
  834. def test_cumprod(self):
  835. mX = self._create_data()[5]
  836. mXcp = mX.cumprod(0)
  837. assert_(eq(mXcp._data, mX.filled(1).cumprod(0)))
  838. mXcp = mX.cumprod(1)
  839. assert_(eq(mXcp._data, mX.filled(1).cumprod(1)))
  840. def test_cumsum(self):
  841. mX = self._create_data()[5]
  842. mXcp = mX.cumsum(0)
  843. assert_(eq(mXcp._data, mX.filled(0).cumsum(0)))
  844. mXcp = mX.cumsum(1)
  845. assert_(eq(mXcp._data, mX.filled(0).cumsum(1)))
  846. def test_varstd(self):
  847. _, X, XX, _, _, mX, mXX = self._create_data()
  848. assert_(eq(mX.var(axis=None), mX.compressed().var()))
  849. assert_(eq(mX.std(axis=None), mX.compressed().std()))
  850. assert_(eq(mXX.var(axis=3).shape, XX.var(axis=3).shape))
  851. assert_(eq(mX.var().shape, X.var().shape))
  852. (mXvar0, mXvar1) = (mX.var(axis=0), mX.var(axis=1))
  853. for k in range(6):
  854. assert_(eq(mXvar1[k], mX[k].compressed().var()))
  855. assert_(eq(mXvar0[k], mX[:, k].compressed().var()))
  856. assert_(eq(np.sqrt(mXvar0[k]),
  857. mX[:, k].compressed().std()))
  858. def eqmask(m1, m2):
  859. if m1 is nomask:
  860. return m2 is nomask
  861. if m2 is nomask:
  862. return m1 is nomask
  863. return (m1 == m2).all()