extras.py 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902
  1. """
  2. Masked arrays add-ons.
  3. A collection of utilities for `numpy.ma`.
  4. :author: Pierre Gerard-Marchant
  5. :contact: pierregm_at_uga_dot_edu
  6. :version: $Id: extras.py 3473 2007-10-29 15:18:13Z jarrod.millman $
  7. """
  8. from __future__ import division, absolute_import, print_function
  9. __all__ = [
  10. 'apply_along_axis', 'apply_over_axes', 'atleast_1d', 'atleast_2d',
  11. 'atleast_3d', 'average', 'clump_masked', 'clump_unmasked',
  12. 'column_stack', 'compress_cols', 'compress_nd', 'compress_rowcols',
  13. 'compress_rows', 'count_masked', 'corrcoef', 'cov', 'diagflat', 'dot',
  14. 'dstack', 'ediff1d', 'flatnotmasked_contiguous', 'flatnotmasked_edges',
  15. 'hsplit', 'hstack', 'isin', 'in1d', 'intersect1d', 'mask_cols', 'mask_rowcols',
  16. 'mask_rows', 'masked_all', 'masked_all_like', 'median', 'mr_',
  17. 'notmasked_contiguous', 'notmasked_edges', 'polyfit', 'row_stack',
  18. 'setdiff1d', 'setxor1d', 'stack', 'unique', 'union1d', 'vander', 'vstack',
  19. ]
  20. import itertools
  21. import warnings
  22. from . import core as ma
  23. from .core import (
  24. MaskedArray, MAError, add, array, asarray, concatenate, filled, count,
  25. getmask, getmaskarray, make_mask_descr, masked, masked_array, mask_or,
  26. nomask, ones, sort, zeros, getdata, get_masked_subclass, dot,
  27. mask_rowcols
  28. )
  29. import numpy as np
  30. from numpy import ndarray, array as nxarray
  31. import numpy.core.umath as umath
  32. from numpy.core.multiarray import normalize_axis_index
  33. from numpy.core.numeric import normalize_axis_tuple
  34. from numpy.lib.function_base import _ureduce
  35. from numpy.lib.index_tricks import AxisConcatenator
  36. def issequence(seq):
  37. """
  38. Is seq a sequence (ndarray, list or tuple)?
  39. """
  40. return isinstance(seq, (ndarray, tuple, list))
  41. def count_masked(arr, axis=None):
  42. """
  43. Count the number of masked elements along the given axis.
  44. Parameters
  45. ----------
  46. arr : array_like
  47. An array with (possibly) masked elements.
  48. axis : int, optional
  49. Axis along which to count. If None (default), a flattened
  50. version of the array is used.
  51. Returns
  52. -------
  53. count : int, ndarray
  54. The total number of masked elements (axis=None) or the number
  55. of masked elements along each slice of the given axis.
  56. See Also
  57. --------
  58. MaskedArray.count : Count non-masked elements.
  59. Examples
  60. --------
  61. >>> import numpy.ma as ma
  62. >>> a = np.arange(9).reshape((3,3))
  63. >>> a = ma.array(a)
  64. >>> a[1, 0] = ma.masked
  65. >>> a[1, 2] = ma.masked
  66. >>> a[2, 1] = ma.masked
  67. >>> a
  68. masked_array(data =
  69. [[0 1 2]
  70. [-- 4 --]
  71. [6 -- 8]],
  72. mask =
  73. [[False False False]
  74. [ True False True]
  75. [False True False]],
  76. fill_value=999999)
  77. >>> ma.count_masked(a)
  78. 3
  79. When the `axis` keyword is used an array is returned.
  80. >>> ma.count_masked(a, axis=0)
  81. array([1, 1, 1])
  82. >>> ma.count_masked(a, axis=1)
  83. array([0, 2, 1])
  84. """
  85. m = getmaskarray(arr)
  86. return m.sum(axis)
  87. def masked_all(shape, dtype=float):
  88. """
  89. Empty masked array with all elements masked.
  90. Return an empty masked array of the given shape and dtype, where all the
  91. data are masked.
  92. Parameters
  93. ----------
  94. shape : tuple
  95. Shape of the required MaskedArray.
  96. dtype : dtype, optional
  97. Data type of the output.
  98. Returns
  99. -------
  100. a : MaskedArray
  101. A masked array with all data masked.
  102. See Also
  103. --------
  104. masked_all_like : Empty masked array modelled on an existing array.
  105. Examples
  106. --------
  107. >>> import numpy.ma as ma
  108. >>> ma.masked_all((3, 3))
  109. masked_array(data =
  110. [[-- -- --]
  111. [-- -- --]
  112. [-- -- --]],
  113. mask =
  114. [[ True True True]
  115. [ True True True]
  116. [ True True True]],
  117. fill_value=1e+20)
  118. The `dtype` parameter defines the underlying data type.
  119. >>> a = ma.masked_all((3, 3))
  120. >>> a.dtype
  121. dtype('float64')
  122. >>> a = ma.masked_all((3, 3), dtype=np.int32)
  123. >>> a.dtype
  124. dtype('int32')
  125. """
  126. a = masked_array(np.empty(shape, dtype),
  127. mask=np.ones(shape, make_mask_descr(dtype)))
  128. return a
  129. def masked_all_like(arr):
  130. """
  131. Empty masked array with the properties of an existing array.
  132. Return an empty masked array of the same shape and dtype as
  133. the array `arr`, where all the data are masked.
  134. Parameters
  135. ----------
  136. arr : ndarray
  137. An array describing the shape and dtype of the required MaskedArray.
  138. Returns
  139. -------
  140. a : MaskedArray
  141. A masked array with all data masked.
  142. Raises
  143. ------
  144. AttributeError
  145. If `arr` doesn't have a shape attribute (i.e. not an ndarray)
  146. See Also
  147. --------
  148. masked_all : Empty masked array with all elements masked.
  149. Examples
  150. --------
  151. >>> import numpy.ma as ma
  152. >>> arr = np.zeros((2, 3), dtype=np.float32)
  153. >>> arr
  154. array([[ 0., 0., 0.],
  155. [ 0., 0., 0.]], dtype=float32)
  156. >>> ma.masked_all_like(arr)
  157. masked_array(data =
  158. [[-- -- --]
  159. [-- -- --]],
  160. mask =
  161. [[ True True True]
  162. [ True True True]],
  163. fill_value=1e+20)
  164. The dtype of the masked array matches the dtype of `arr`.
  165. >>> arr.dtype
  166. dtype('float32')
  167. >>> ma.masked_all_like(arr).dtype
  168. dtype('float32')
  169. """
  170. a = np.empty_like(arr).view(MaskedArray)
  171. a._mask = np.ones(a.shape, dtype=make_mask_descr(a.dtype))
  172. return a
  173. #####--------------------------------------------------------------------------
  174. #---- --- Standard functions ---
  175. #####--------------------------------------------------------------------------
  176. class _fromnxfunction(object):
  177. """
  178. Defines a wrapper to adapt NumPy functions to masked arrays.
  179. An instance of `_fromnxfunction` can be called with the same parameters
  180. as the wrapped NumPy function. The docstring of `newfunc` is adapted from
  181. the wrapped function as well, see `getdoc`.
  182. This class should not be used directly. Instead, one of its extensions that
  183. provides support for a specific type of input should be used.
  184. Parameters
  185. ----------
  186. funcname : str
  187. The name of the function to be adapted. The function should be
  188. in the NumPy namespace (i.e. ``np.funcname``).
  189. """
  190. def __init__(self, funcname):
  191. self.__name__ = funcname
  192. self.__doc__ = self.getdoc()
  193. def getdoc(self):
  194. """
  195. Retrieve the docstring and signature from the function.
  196. The ``__doc__`` attribute of the function is used as the docstring for
  197. the new masked array version of the function. A note on application
  198. of the function to the mask is appended.
  199. .. warning::
  200. If the function docstring already contained a Notes section, the
  201. new docstring will have two Notes sections instead of appending a note
  202. to the existing section.
  203. Parameters
  204. ----------
  205. None
  206. """
  207. npfunc = getattr(np, self.__name__, None)
  208. doc = getattr(npfunc, '__doc__', None)
  209. if doc:
  210. sig = self.__name__ + ma.get_object_signature(npfunc)
  211. locdoc = "Notes\n-----\nThe function is applied to both the _data"\
  212. " and the _mask, if any."
  213. return '\n'.join((sig, doc, locdoc))
  214. return
  215. def __call__(self, *args, **params):
  216. pass
  217. class _fromnxfunction_single(_fromnxfunction):
  218. """
  219. A version of `_fromnxfunction` that is called with a single array
  220. argument followed by auxiliary args that are passed verbatim for
  221. both the data and mask calls.
  222. """
  223. def __call__(self, x, *args, **params):
  224. func = getattr(np, self.__name__)
  225. if isinstance(x, ndarray):
  226. _d = func(x.__array__(), *args, **params)
  227. _m = func(getmaskarray(x), *args, **params)
  228. return masked_array(_d, mask=_m)
  229. else:
  230. _d = func(np.asarray(x), *args, **params)
  231. _m = func(getmaskarray(x), *args, **params)
  232. return masked_array(_d, mask=_m)
  233. class _fromnxfunction_seq(_fromnxfunction):
  234. """
  235. A version of `_fromnxfunction` that is called with a single sequence
  236. of arrays followed by auxiliary args that are passed verbatim for
  237. both the data and mask calls.
  238. """
  239. def __call__(self, x, *args, **params):
  240. func = getattr(np, self.__name__)
  241. _d = func(tuple([np.asarray(a) for a in x]), *args, **params)
  242. _m = func(tuple([getmaskarray(a) for a in x]), *args, **params)
  243. return masked_array(_d, mask=_m)
  244. class _fromnxfunction_args(_fromnxfunction):
  245. """
  246. A version of `_fromnxfunction` that is called with multiple array
  247. arguments. The first non-array-like input marks the beginning of the
  248. arguments that are passed verbatim for both the data and mask calls.
  249. Array arguments are processed independently and the results are
  250. returned in a list. If only one array is found, the return value is
  251. just the processed array instead of a list.
  252. """
  253. def __call__(self, *args, **params):
  254. func = getattr(np, self.__name__)
  255. arrays = []
  256. args = list(args)
  257. while len(args) > 0 and issequence(args[0]):
  258. arrays.append(args.pop(0))
  259. res = []
  260. for x in arrays:
  261. _d = func(np.asarray(x), *args, **params)
  262. _m = func(getmaskarray(x), *args, **params)
  263. res.append(masked_array(_d, mask=_m))
  264. if len(arrays) == 1:
  265. return res[0]
  266. return res
  267. class _fromnxfunction_allargs(_fromnxfunction):
  268. """
  269. A version of `_fromnxfunction` that is called with multiple array
  270. arguments. Similar to `_fromnxfunction_args` except that all args
  271. are converted to arrays even if they are not so already. This makes
  272. it possible to process scalars as 1-D arrays. Only keyword arguments
  273. are passed through verbatim for the data and mask calls. Arrays
  274. arguments are processed independently and the results are returned
  275. in a list. If only one arg is present, the return value is just the
  276. processed array instead of a list.
  277. """
  278. def __call__(self, *args, **params):
  279. func = getattr(np, self.__name__)
  280. res = []
  281. for x in args:
  282. _d = func(np.asarray(x), **params)
  283. _m = func(getmaskarray(x), **params)
  284. res.append(masked_array(_d, mask=_m))
  285. if len(args) == 1:
  286. return res[0]
  287. return res
  288. atleast_1d = _fromnxfunction_allargs('atleast_1d')
  289. atleast_2d = _fromnxfunction_allargs('atleast_2d')
  290. atleast_3d = _fromnxfunction_allargs('atleast_3d')
  291. vstack = row_stack = _fromnxfunction_seq('vstack')
  292. hstack = _fromnxfunction_seq('hstack')
  293. column_stack = _fromnxfunction_seq('column_stack')
  294. dstack = _fromnxfunction_seq('dstack')
  295. stack = _fromnxfunction_seq('stack')
  296. hsplit = _fromnxfunction_single('hsplit')
  297. diagflat = _fromnxfunction_single('diagflat')
  298. #####--------------------------------------------------------------------------
  299. #----
  300. #####--------------------------------------------------------------------------
  301. def flatten_inplace(seq):
  302. """Flatten a sequence in place."""
  303. k = 0
  304. while (k != len(seq)):
  305. while hasattr(seq[k], '__iter__'):
  306. seq[k:(k + 1)] = seq[k]
  307. k += 1
  308. return seq
  309. def apply_along_axis(func1d, axis, arr, *args, **kwargs):
  310. """
  311. (This docstring should be overwritten)
  312. """
  313. arr = array(arr, copy=False, subok=True)
  314. nd = arr.ndim
  315. axis = normalize_axis_index(axis, nd)
  316. ind = [0] * (nd - 1)
  317. i = np.zeros(nd, 'O')
  318. indlist = list(range(nd))
  319. indlist.remove(axis)
  320. i[axis] = slice(None, None)
  321. outshape = np.asarray(arr.shape).take(indlist)
  322. i.put(indlist, ind)
  323. j = i.copy()
  324. res = func1d(arr[tuple(i.tolist())], *args, **kwargs)
  325. # if res is a number, then we have a smaller output array
  326. asscalar = np.isscalar(res)
  327. if not asscalar:
  328. try:
  329. len(res)
  330. except TypeError:
  331. asscalar = True
  332. # Note: we shouldn't set the dtype of the output from the first result
  333. # so we force the type to object, and build a list of dtypes. We'll
  334. # just take the largest, to avoid some downcasting
  335. dtypes = []
  336. if asscalar:
  337. dtypes.append(np.asarray(res).dtype)
  338. outarr = zeros(outshape, object)
  339. outarr[tuple(ind)] = res
  340. Ntot = np.product(outshape)
  341. k = 1
  342. while k < Ntot:
  343. # increment the index
  344. ind[-1] += 1
  345. n = -1
  346. while (ind[n] >= outshape[n]) and (n > (1 - nd)):
  347. ind[n - 1] += 1
  348. ind[n] = 0
  349. n -= 1
  350. i.put(indlist, ind)
  351. res = func1d(arr[tuple(i.tolist())], *args, **kwargs)
  352. outarr[tuple(ind)] = res
  353. dtypes.append(asarray(res).dtype)
  354. k += 1
  355. else:
  356. res = array(res, copy=False, subok=True)
  357. j = i.copy()
  358. j[axis] = ([slice(None, None)] * res.ndim)
  359. j.put(indlist, ind)
  360. Ntot = np.product(outshape)
  361. holdshape = outshape
  362. outshape = list(arr.shape)
  363. outshape[axis] = res.shape
  364. dtypes.append(asarray(res).dtype)
  365. outshape = flatten_inplace(outshape)
  366. outarr = zeros(outshape, object)
  367. outarr[tuple(flatten_inplace(j.tolist()))] = res
  368. k = 1
  369. while k < Ntot:
  370. # increment the index
  371. ind[-1] += 1
  372. n = -1
  373. while (ind[n] >= holdshape[n]) and (n > (1 - nd)):
  374. ind[n - 1] += 1
  375. ind[n] = 0
  376. n -= 1
  377. i.put(indlist, ind)
  378. j.put(indlist, ind)
  379. res = func1d(arr[tuple(i.tolist())], *args, **kwargs)
  380. outarr[tuple(flatten_inplace(j.tolist()))] = res
  381. dtypes.append(asarray(res).dtype)
  382. k += 1
  383. max_dtypes = np.dtype(np.asarray(dtypes).max())
  384. if not hasattr(arr, '_mask'):
  385. result = np.asarray(outarr, dtype=max_dtypes)
  386. else:
  387. result = asarray(outarr, dtype=max_dtypes)
  388. result.fill_value = ma.default_fill_value(result)
  389. return result
  390. apply_along_axis.__doc__ = np.apply_along_axis.__doc__
  391. def apply_over_axes(func, a, axes):
  392. """
  393. (This docstring will be overwritten)
  394. """
  395. val = asarray(a)
  396. N = a.ndim
  397. if array(axes).ndim == 0:
  398. axes = (axes,)
  399. for axis in axes:
  400. if axis < 0:
  401. axis = N + axis
  402. args = (val, axis)
  403. res = func(*args)
  404. if res.ndim == val.ndim:
  405. val = res
  406. else:
  407. res = ma.expand_dims(res, axis)
  408. if res.ndim == val.ndim:
  409. val = res
  410. else:
  411. raise ValueError("function is not returning "
  412. "an array of the correct shape")
  413. return val
  414. if apply_over_axes.__doc__ is not None:
  415. apply_over_axes.__doc__ = np.apply_over_axes.__doc__[
  416. :np.apply_over_axes.__doc__.find('Notes')].rstrip() + \
  417. """
  418. Examples
  419. --------
  420. >>> a = ma.arange(24).reshape(2,3,4)
  421. >>> a[:,0,1] = ma.masked
  422. >>> a[:,1,:] = ma.masked
  423. >>> print(a)
  424. [[[0 -- 2 3]
  425. [-- -- -- --]
  426. [8 9 10 11]]
  427. [[12 -- 14 15]
  428. [-- -- -- --]
  429. [20 21 22 23]]]
  430. >>> print(ma.apply_over_axes(ma.sum, a, [0,2]))
  431. [[[46]
  432. [--]
  433. [124]]]
  434. Tuple axis arguments to ufuncs are equivalent:
  435. >>> print(ma.sum(a, axis=(0,2)).reshape((1,-1,1)))
  436. [[[46]
  437. [--]
  438. [124]]]
  439. """
  440. def average(a, axis=None, weights=None, returned=False):
  441. """
  442. Return the weighted average of array over the given axis.
  443. Parameters
  444. ----------
  445. a : array_like
  446. Data to be averaged.
  447. Masked entries are not taken into account in the computation.
  448. axis : int, optional
  449. Axis along which to average `a`. If `None`, averaging is done over
  450. the flattened array.
  451. weights : array_like, optional
  452. The importance that each element has in the computation of the average.
  453. The weights array can either be 1-D (in which case its length must be
  454. the size of `a` along the given axis) or of the same shape as `a`.
  455. If ``weights=None``, then all data in `a` are assumed to have a
  456. weight equal to one. If `weights` is complex, the imaginary parts
  457. are ignored.
  458. returned : bool, optional
  459. Flag indicating whether a tuple ``(result, sum of weights)``
  460. should be returned as output (True), or just the result (False).
  461. Default is False.
  462. Returns
  463. -------
  464. average, [sum_of_weights] : (tuple of) scalar or MaskedArray
  465. The average along the specified axis. When returned is `True`,
  466. return a tuple with the average as the first element and the sum
  467. of the weights as the second element. The return type is `np.float64`
  468. if `a` is of integer type and floats smaller than `float64`, or the
  469. input data-type, otherwise. If returned, `sum_of_weights` is always
  470. `float64`.
  471. Examples
  472. --------
  473. >>> a = np.ma.array([1., 2., 3., 4.], mask=[False, False, True, True])
  474. >>> np.ma.average(a, weights=[3, 1, 0, 0])
  475. 1.25
  476. >>> x = np.ma.arange(6.).reshape(3, 2)
  477. >>> print(x)
  478. [[ 0. 1.]
  479. [ 2. 3.]
  480. [ 4. 5.]]
  481. >>> avg, sumweights = np.ma.average(x, axis=0, weights=[1, 2, 3],
  482. ... returned=True)
  483. >>> print(avg)
  484. [2.66666666667 3.66666666667]
  485. """
  486. a = asarray(a)
  487. m = getmask(a)
  488. # inspired by 'average' in numpy/lib/function_base.py
  489. if weights is None:
  490. avg = a.mean(axis)
  491. scl = avg.dtype.type(a.count(axis))
  492. else:
  493. wgt = np.asanyarray(weights)
  494. if issubclass(a.dtype.type, (np.integer, np.bool_)):
  495. result_dtype = np.result_type(a.dtype, wgt.dtype, 'f8')
  496. else:
  497. result_dtype = np.result_type(a.dtype, wgt.dtype)
  498. # Sanity checks
  499. if a.shape != wgt.shape:
  500. if axis is None:
  501. raise TypeError(
  502. "Axis must be specified when shapes of a and weights "
  503. "differ.")
  504. if wgt.ndim != 1:
  505. raise TypeError(
  506. "1D weights expected when shapes of a and weights differ.")
  507. if wgt.shape[0] != a.shape[axis]:
  508. raise ValueError(
  509. "Length of weights not compatible with specified axis.")
  510. # setup wgt to broadcast along axis
  511. wgt = np.broadcast_to(wgt, (a.ndim-1)*(1,) + wgt.shape)
  512. wgt = wgt.swapaxes(-1, axis)
  513. if m is not nomask:
  514. wgt = wgt*(~a.mask)
  515. scl = wgt.sum(axis=axis, dtype=result_dtype)
  516. avg = np.multiply(a, wgt, dtype=result_dtype).sum(axis)/scl
  517. if returned:
  518. if scl.shape != avg.shape:
  519. scl = np.broadcast_to(scl, avg.shape).copy()
  520. return avg, scl
  521. else:
  522. return avg
  523. def median(a, axis=None, out=None, overwrite_input=False, keepdims=False):
  524. """
  525. Compute the median along the specified axis.
  526. Returns the median of the array elements.
  527. Parameters
  528. ----------
  529. a : array_like
  530. Input array or object that can be converted to an array.
  531. axis : int, optional
  532. Axis along which the medians are computed. The default (None) is
  533. to compute the median along a flattened version of the array.
  534. out : ndarray, optional
  535. Alternative output array in which to place the result. It must
  536. have the same shape and buffer length as the expected output
  537. but the type will be cast if necessary.
  538. overwrite_input : bool, optional
  539. If True, then allow use of memory of input array (a) for
  540. calculations. The input array will be modified by the call to
  541. median. This will save memory when you do not need to preserve
  542. the contents of the input array. Treat the input as undefined,
  543. but it will probably be fully or partially sorted. Default is
  544. False. Note that, if `overwrite_input` is True, and the input
  545. is not already an `ndarray`, an error will be raised.
  546. keepdims : bool, optional
  547. If this is set to True, the axes which are reduced are left
  548. in the result as dimensions with size one. With this option,
  549. the result will broadcast correctly against the input array.
  550. .. versionadded:: 1.10.0
  551. Returns
  552. -------
  553. median : ndarray
  554. A new array holding the result is returned unless out is
  555. specified, in which case a reference to out is returned.
  556. Return data-type is `float64` for integers and floats smaller than
  557. `float64`, or the input data-type, otherwise.
  558. See Also
  559. --------
  560. mean
  561. Notes
  562. -----
  563. Given a vector ``V`` with ``N`` non masked values, the median of ``V``
  564. is the middle value of a sorted copy of ``V`` (``Vs``) - i.e.
  565. ``Vs[(N-1)/2]``, when ``N`` is odd, or ``{Vs[N/2 - 1] + Vs[N/2]}/2``
  566. when ``N`` is even.
  567. Examples
  568. --------
  569. >>> x = np.ma.array(np.arange(8), mask=[0]*4 + [1]*4)
  570. >>> np.ma.median(x)
  571. 1.5
  572. >>> x = np.ma.array(np.arange(10).reshape(2, 5), mask=[0]*6 + [1]*4)
  573. >>> np.ma.median(x)
  574. 2.5
  575. >>> np.ma.median(x, axis=-1, overwrite_input=True)
  576. masked_array(data = [ 2. 5.],
  577. mask = False,
  578. fill_value = 1e+20)
  579. """
  580. if not hasattr(a, 'mask'):
  581. m = np.median(getdata(a, subok=True), axis=axis,
  582. out=out, overwrite_input=overwrite_input,
  583. keepdims=keepdims)
  584. if isinstance(m, np.ndarray) and 1 <= m.ndim:
  585. return masked_array(m, copy=False)
  586. else:
  587. return m
  588. r, k = _ureduce(a, func=_median, axis=axis, out=out,
  589. overwrite_input=overwrite_input)
  590. if keepdims:
  591. return r.reshape(k)
  592. else:
  593. return r
  594. def _median(a, axis=None, out=None, overwrite_input=False):
  595. # when an unmasked NaN is present return it, so we need to sort the NaN
  596. # values behind the mask
  597. if np.issubdtype(a.dtype, np.inexact):
  598. fill_value = np.inf
  599. else:
  600. fill_value = None
  601. if overwrite_input:
  602. if axis is None:
  603. asorted = a.ravel()
  604. asorted.sort(fill_value=fill_value)
  605. else:
  606. a.sort(axis=axis, fill_value=fill_value)
  607. asorted = a
  608. else:
  609. asorted = sort(a, axis=axis, fill_value=fill_value)
  610. if axis is None:
  611. axis = 0
  612. else:
  613. axis = normalize_axis_index(axis, asorted.ndim)
  614. if asorted.shape[axis] == 0:
  615. # for empty axis integer indices fail so use slicing to get same result
  616. # as median (which is mean of empty slice = nan)
  617. indexer = [slice(None)] * asorted.ndim
  618. indexer[axis] = slice(0, 0)
  619. indexer = tuple(indexer)
  620. return np.ma.mean(asorted[indexer], axis=axis, out=out)
  621. if asorted.ndim == 1:
  622. counts = count(asorted)
  623. idx, odd = divmod(count(asorted), 2)
  624. mid = asorted[idx + odd - 1:idx + 1]
  625. if np.issubdtype(asorted.dtype, np.inexact) and asorted.size > 0:
  626. # avoid inf / x = masked
  627. s = mid.sum(out=out)
  628. if not odd:
  629. s = np.true_divide(s, 2., casting='safe', out=out)
  630. s = np.lib.utils._median_nancheck(asorted, s, axis, out)
  631. else:
  632. s = mid.mean(out=out)
  633. # if result is masked either the input contained enough
  634. # minimum_fill_value so that it would be the median or all values
  635. # masked
  636. if np.ma.is_masked(s) and not np.all(asorted.mask):
  637. return np.ma.minimum_fill_value(asorted)
  638. return s
  639. counts = count(asorted, axis=axis, keepdims=True)
  640. h = counts // 2
  641. # duplicate high if odd number of elements so mean does nothing
  642. odd = counts % 2 == 1
  643. l = np.where(odd, h, h-1)
  644. lh = np.concatenate([l,h], axis=axis)
  645. # get low and high median
  646. low_high = np.take_along_axis(asorted, lh, axis=axis)
  647. def replace_masked(s):
  648. # Replace masked entries with minimum_full_value unless it all values
  649. # are masked. This is required as the sort order of values equal or
  650. # larger than the fill value is undefined and a valid value placed
  651. # elsewhere, e.g. [4, --, inf].
  652. if np.ma.is_masked(s):
  653. rep = (~np.all(asorted.mask, axis=axis, keepdims=True)) & s.mask
  654. s.data[rep] = np.ma.minimum_fill_value(asorted)
  655. s.mask[rep] = False
  656. replace_masked(low_high)
  657. if np.issubdtype(asorted.dtype, np.inexact):
  658. # avoid inf / x = masked
  659. s = np.ma.sum(low_high, axis=axis, out=out)
  660. np.true_divide(s.data, 2., casting='unsafe', out=s.data)
  661. s = np.lib.utils._median_nancheck(asorted, s, axis, out)
  662. else:
  663. s = np.ma.mean(low_high, axis=axis, out=out)
  664. return s
  665. def compress_nd(x, axis=None):
  666. """Suppress slices from multiple dimensions which contain masked values.
  667. Parameters
  668. ----------
  669. x : array_like, MaskedArray
  670. The array to operate on. If not a MaskedArray instance (or if no array
  671. elements are masked, `x` is interpreted as a MaskedArray with `mask`
  672. set to `nomask`.
  673. axis : tuple of ints or int, optional
  674. Which dimensions to suppress slices from can be configured with this
  675. parameter.
  676. - If axis is a tuple of ints, those are the axes to suppress slices from.
  677. - If axis is an int, then that is the only axis to suppress slices from.
  678. - If axis is None, all axis are selected.
  679. Returns
  680. -------
  681. compress_array : ndarray
  682. The compressed array.
  683. """
  684. x = asarray(x)
  685. m = getmask(x)
  686. # Set axis to tuple of ints
  687. if axis is None:
  688. axis = tuple(range(x.ndim))
  689. else:
  690. axis = normalize_axis_tuple(axis, x.ndim)
  691. # Nothing is masked: return x
  692. if m is nomask or not m.any():
  693. return x._data
  694. # All is masked: return empty
  695. if m.all():
  696. return nxarray([])
  697. # Filter elements through boolean indexing
  698. data = x._data
  699. for ax in axis:
  700. axes = tuple(list(range(ax)) + list(range(ax + 1, x.ndim)))
  701. data = data[(slice(None),)*ax + (~m.any(axis=axes),)]
  702. return data
  703. def compress_rowcols(x, axis=None):
  704. """
  705. Suppress the rows and/or columns of a 2-D array that contain
  706. masked values.
  707. The suppression behavior is selected with the `axis` parameter.
  708. - If axis is None, both rows and columns are suppressed.
  709. - If axis is 0, only rows are suppressed.
  710. - If axis is 1 or -1, only columns are suppressed.
  711. Parameters
  712. ----------
  713. x : array_like, MaskedArray
  714. The array to operate on. If not a MaskedArray instance (or if no array
  715. elements are masked), `x` is interpreted as a MaskedArray with
  716. `mask` set to `nomask`. Must be a 2D array.
  717. axis : int, optional
  718. Axis along which to perform the operation. Default is None.
  719. Returns
  720. -------
  721. compressed_array : ndarray
  722. The compressed array.
  723. Examples
  724. --------
  725. >>> x = np.ma.array(np.arange(9).reshape(3, 3), mask=[[1, 0, 0],
  726. ... [1, 0, 0],
  727. ... [0, 0, 0]])
  728. >>> x
  729. masked_array(data =
  730. [[-- 1 2]
  731. [-- 4 5]
  732. [6 7 8]],
  733. mask =
  734. [[ True False False]
  735. [ True False False]
  736. [False False False]],
  737. fill_value = 999999)
  738. >>> np.ma.compress_rowcols(x)
  739. array([[7, 8]])
  740. >>> np.ma.compress_rowcols(x, 0)
  741. array([[6, 7, 8]])
  742. >>> np.ma.compress_rowcols(x, 1)
  743. array([[1, 2],
  744. [4, 5],
  745. [7, 8]])
  746. """
  747. if asarray(x).ndim != 2:
  748. raise NotImplementedError("compress_rowcols works for 2D arrays only.")
  749. return compress_nd(x, axis=axis)
  750. def compress_rows(a):
  751. """
  752. Suppress whole rows of a 2-D array that contain masked values.
  753. This is equivalent to ``np.ma.compress_rowcols(a, 0)``, see
  754. `extras.compress_rowcols` for details.
  755. See Also
  756. --------
  757. extras.compress_rowcols
  758. """
  759. a = asarray(a)
  760. if a.ndim != 2:
  761. raise NotImplementedError("compress_rows works for 2D arrays only.")
  762. return compress_rowcols(a, 0)
  763. def compress_cols(a):
  764. """
  765. Suppress whole columns of a 2-D array that contain masked values.
  766. This is equivalent to ``np.ma.compress_rowcols(a, 1)``, see
  767. `extras.compress_rowcols` for details.
  768. See Also
  769. --------
  770. extras.compress_rowcols
  771. """
  772. a = asarray(a)
  773. if a.ndim != 2:
  774. raise NotImplementedError("compress_cols works for 2D arrays only.")
  775. return compress_rowcols(a, 1)
  776. def mask_rows(a, axis=None):
  777. """
  778. Mask rows of a 2D array that contain masked values.
  779. This function is a shortcut to ``mask_rowcols`` with `axis` equal to 0.
  780. See Also
  781. --------
  782. mask_rowcols : Mask rows and/or columns of a 2D array.
  783. masked_where : Mask where a condition is met.
  784. Examples
  785. --------
  786. >>> import numpy.ma as ma
  787. >>> a = np.zeros((3, 3), dtype=int)
  788. >>> a[1, 1] = 1
  789. >>> a
  790. array([[0, 0, 0],
  791. [0, 1, 0],
  792. [0, 0, 0]])
  793. >>> a = ma.masked_equal(a, 1)
  794. >>> a
  795. masked_array(data =
  796. [[0 0 0]
  797. [0 -- 0]
  798. [0 0 0]],
  799. mask =
  800. [[False False False]
  801. [False True False]
  802. [False False False]],
  803. fill_value=999999)
  804. >>> ma.mask_rows(a)
  805. masked_array(data =
  806. [[0 0 0]
  807. [-- -- --]
  808. [0 0 0]],
  809. mask =
  810. [[False False False]
  811. [ True True True]
  812. [False False False]],
  813. fill_value=999999)
  814. """
  815. return mask_rowcols(a, 0)
  816. def mask_cols(a, axis=None):
  817. """
  818. Mask columns of a 2D array that contain masked values.
  819. This function is a shortcut to ``mask_rowcols`` with `axis` equal to 1.
  820. See Also
  821. --------
  822. mask_rowcols : Mask rows and/or columns of a 2D array.
  823. masked_where : Mask where a condition is met.
  824. Examples
  825. --------
  826. >>> import numpy.ma as ma
  827. >>> a = np.zeros((3, 3), dtype=int)
  828. >>> a[1, 1] = 1
  829. >>> a
  830. array([[0, 0, 0],
  831. [0, 1, 0],
  832. [0, 0, 0]])
  833. >>> a = ma.masked_equal(a, 1)
  834. >>> a
  835. masked_array(data =
  836. [[0 0 0]
  837. [0 -- 0]
  838. [0 0 0]],
  839. mask =
  840. [[False False False]
  841. [False True False]
  842. [False False False]],
  843. fill_value=999999)
  844. >>> ma.mask_cols(a)
  845. masked_array(data =
  846. [[0 -- 0]
  847. [0 -- 0]
  848. [0 -- 0]],
  849. mask =
  850. [[False True False]
  851. [False True False]
  852. [False True False]],
  853. fill_value=999999)
  854. """
  855. return mask_rowcols(a, 1)
  856. #####--------------------------------------------------------------------------
  857. #---- --- arraysetops ---
  858. #####--------------------------------------------------------------------------
  859. def ediff1d(arr, to_end=None, to_begin=None):
  860. """
  861. Compute the differences between consecutive elements of an array.
  862. This function is the equivalent of `numpy.ediff1d` that takes masked
  863. values into account, see `numpy.ediff1d` for details.
  864. See Also
  865. --------
  866. numpy.ediff1d : Equivalent function for ndarrays.
  867. """
  868. arr = ma.asanyarray(arr).flat
  869. ed = arr[1:] - arr[:-1]
  870. arrays = [ed]
  871. #
  872. if to_begin is not None:
  873. arrays.insert(0, to_begin)
  874. if to_end is not None:
  875. arrays.append(to_end)
  876. #
  877. if len(arrays) != 1:
  878. # We'll save ourselves a copy of a potentially large array in the common
  879. # case where neither to_begin or to_end was given.
  880. ed = hstack(arrays)
  881. #
  882. return ed
  883. def unique(ar1, return_index=False, return_inverse=False):
  884. """
  885. Finds the unique elements of an array.
  886. Masked values are considered the same element (masked). The output array
  887. is always a masked array. See `numpy.unique` for more details.
  888. See Also
  889. --------
  890. numpy.unique : Equivalent function for ndarrays.
  891. """
  892. output = np.unique(ar1,
  893. return_index=return_index,
  894. return_inverse=return_inverse)
  895. if isinstance(output, tuple):
  896. output = list(output)
  897. output[0] = output[0].view(MaskedArray)
  898. output = tuple(output)
  899. else:
  900. output = output.view(MaskedArray)
  901. return output
  902. def intersect1d(ar1, ar2, assume_unique=False):
  903. """
  904. Returns the unique elements common to both arrays.
  905. Masked values are considered equal one to the other.
  906. The output is always a masked array.
  907. See `numpy.intersect1d` for more details.
  908. See Also
  909. --------
  910. numpy.intersect1d : Equivalent function for ndarrays.
  911. Examples
  912. --------
  913. >>> x = array([1, 3, 3, 3], mask=[0, 0, 0, 1])
  914. >>> y = array([3, 1, 1, 1], mask=[0, 0, 0, 1])
  915. >>> intersect1d(x, y)
  916. masked_array(data = [1 3 --],
  917. mask = [False False True],
  918. fill_value = 999999)
  919. """
  920. if assume_unique:
  921. aux = ma.concatenate((ar1, ar2))
  922. else:
  923. # Might be faster than unique( intersect1d( ar1, ar2 ) )?
  924. aux = ma.concatenate((unique(ar1), unique(ar2)))
  925. aux.sort()
  926. return aux[:-1][aux[1:] == aux[:-1]]
  927. def setxor1d(ar1, ar2, assume_unique=False):
  928. """
  929. Set exclusive-or of 1-D arrays with unique elements.
  930. The output is always a masked array. See `numpy.setxor1d` for more details.
  931. See Also
  932. --------
  933. numpy.setxor1d : Equivalent function for ndarrays.
  934. """
  935. if not assume_unique:
  936. ar1 = unique(ar1)
  937. ar2 = unique(ar2)
  938. aux = ma.concatenate((ar1, ar2))
  939. if aux.size == 0:
  940. return aux
  941. aux.sort()
  942. auxf = aux.filled()
  943. # flag = ediff1d( aux, to_end = 1, to_begin = 1 ) == 0
  944. flag = ma.concatenate(([True], (auxf[1:] != auxf[:-1]), [True]))
  945. # flag2 = ediff1d( flag ) == 0
  946. flag2 = (flag[1:] == flag[:-1])
  947. return aux[flag2]
  948. def in1d(ar1, ar2, assume_unique=False, invert=False):
  949. """
  950. Test whether each element of an array is also present in a second
  951. array.
  952. The output is always a masked array. See `numpy.in1d` for more details.
  953. We recommend using :func:`isin` instead of `in1d` for new code.
  954. See Also
  955. --------
  956. isin : Version of this function that preserves the shape of ar1.
  957. numpy.in1d : Equivalent function for ndarrays.
  958. Notes
  959. -----
  960. .. versionadded:: 1.4.0
  961. """
  962. if not assume_unique:
  963. ar1, rev_idx = unique(ar1, return_inverse=True)
  964. ar2 = unique(ar2)
  965. ar = ma.concatenate((ar1, ar2))
  966. # We need this to be a stable sort, so always use 'mergesort'
  967. # here. The values from the first array should always come before
  968. # the values from the second array.
  969. order = ar.argsort(kind='mergesort')
  970. sar = ar[order]
  971. if invert:
  972. bool_ar = (sar[1:] != sar[:-1])
  973. else:
  974. bool_ar = (sar[1:] == sar[:-1])
  975. flag = ma.concatenate((bool_ar, [invert]))
  976. indx = order.argsort(kind='mergesort')[:len(ar1)]
  977. if assume_unique:
  978. return flag[indx]
  979. else:
  980. return flag[indx][rev_idx]
  981. def isin(element, test_elements, assume_unique=False, invert=False):
  982. """
  983. Calculates `element in test_elements`, broadcasting over
  984. `element` only.
  985. The output is always a masked array of the same shape as `element`.
  986. See `numpy.isin` for more details.
  987. See Also
  988. --------
  989. in1d : Flattened version of this function.
  990. numpy.isin : Equivalent function for ndarrays.
  991. Notes
  992. -----
  993. .. versionadded:: 1.13.0
  994. """
  995. element = ma.asarray(element)
  996. return in1d(element, test_elements, assume_unique=assume_unique,
  997. invert=invert).reshape(element.shape)
  998. def union1d(ar1, ar2):
  999. """
  1000. Union of two arrays.
  1001. The output is always a masked array. See `numpy.union1d` for more details.
  1002. See also
  1003. --------
  1004. numpy.union1d : Equivalent function for ndarrays.
  1005. """
  1006. return unique(ma.concatenate((ar1, ar2), axis=None))
  1007. def setdiff1d(ar1, ar2, assume_unique=False):
  1008. """
  1009. Set difference of 1D arrays with unique elements.
  1010. The output is always a masked array. See `numpy.setdiff1d` for more
  1011. details.
  1012. See Also
  1013. --------
  1014. numpy.setdiff1d : Equivalent function for ndarrays.
  1015. Examples
  1016. --------
  1017. >>> x = np.ma.array([1, 2, 3, 4], mask=[0, 1, 0, 1])
  1018. >>> np.ma.setdiff1d(x, [1, 2])
  1019. masked_array(data = [3 --],
  1020. mask = [False True],
  1021. fill_value = 999999)
  1022. """
  1023. if assume_unique:
  1024. ar1 = ma.asarray(ar1).ravel()
  1025. else:
  1026. ar1 = unique(ar1)
  1027. ar2 = unique(ar2)
  1028. return ar1[in1d(ar1, ar2, assume_unique=True, invert=True)]
  1029. ###############################################################################
  1030. # Covariance #
  1031. ###############################################################################
  1032. def _covhelper(x, y=None, rowvar=True, allow_masked=True):
  1033. """
  1034. Private function for the computation of covariance and correlation
  1035. coefficients.
  1036. """
  1037. x = ma.array(x, ndmin=2, copy=True, dtype=float)
  1038. xmask = ma.getmaskarray(x)
  1039. # Quick exit if we can't process masked data
  1040. if not allow_masked and xmask.any():
  1041. raise ValueError("Cannot process masked data.")
  1042. #
  1043. if x.shape[0] == 1:
  1044. rowvar = True
  1045. # Make sure that rowvar is either 0 or 1
  1046. rowvar = int(bool(rowvar))
  1047. axis = 1 - rowvar
  1048. if rowvar:
  1049. tup = (slice(None), None)
  1050. else:
  1051. tup = (None, slice(None))
  1052. #
  1053. if y is None:
  1054. xnotmask = np.logical_not(xmask).astype(int)
  1055. else:
  1056. y = array(y, copy=False, ndmin=2, dtype=float)
  1057. ymask = ma.getmaskarray(y)
  1058. if not allow_masked and ymask.any():
  1059. raise ValueError("Cannot process masked data.")
  1060. if xmask.any() or ymask.any():
  1061. if y.shape == x.shape:
  1062. # Define some common mask
  1063. common_mask = np.logical_or(xmask, ymask)
  1064. if common_mask is not nomask:
  1065. xmask = x._mask = y._mask = ymask = common_mask
  1066. x._sharedmask = False
  1067. y._sharedmask = False
  1068. x = ma.concatenate((x, y), axis)
  1069. xnotmask = np.logical_not(np.concatenate((xmask, ymask), axis)).astype(int)
  1070. x -= x.mean(axis=rowvar)[tup]
  1071. return (x, xnotmask, rowvar)
  1072. def cov(x, y=None, rowvar=True, bias=False, allow_masked=True, ddof=None):
  1073. """
  1074. Estimate the covariance matrix.
  1075. Except for the handling of missing data this function does the same as
  1076. `numpy.cov`. For more details and examples, see `numpy.cov`.
  1077. By default, masked values are recognized as such. If `x` and `y` have the
  1078. same shape, a common mask is allocated: if ``x[i,j]`` is masked, then
  1079. ``y[i,j]`` will also be masked.
  1080. Setting `allow_masked` to False will raise an exception if values are
  1081. missing in either of the input arrays.
  1082. Parameters
  1083. ----------
  1084. x : array_like
  1085. A 1-D or 2-D array containing multiple variables and observations.
  1086. Each row of `x` represents a variable, and each column a single
  1087. observation of all those variables. Also see `rowvar` below.
  1088. y : array_like, optional
  1089. An additional set of variables and observations. `y` has the same
  1090. form as `x`.
  1091. rowvar : bool, optional
  1092. If `rowvar` is True (default), then each row represents a
  1093. variable, with observations in the columns. Otherwise, the relationship
  1094. is transposed: each column represents a variable, while the rows
  1095. contain observations.
  1096. bias : bool, optional
  1097. Default normalization (False) is by ``(N-1)``, where ``N`` is the
  1098. number of observations given (unbiased estimate). If `bias` is True,
  1099. then normalization is by ``N``. This keyword can be overridden by
  1100. the keyword ``ddof`` in numpy versions >= 1.5.
  1101. allow_masked : bool, optional
  1102. If True, masked values are propagated pair-wise: if a value is masked
  1103. in `x`, the corresponding value is masked in `y`.
  1104. If False, raises a `ValueError` exception when some values are missing.
  1105. ddof : {None, int}, optional
  1106. If not ``None`` normalization is by ``(N - ddof)``, where ``N`` is
  1107. the number of observations; this overrides the value implied by
  1108. ``bias``. The default value is ``None``.
  1109. .. versionadded:: 1.5
  1110. Raises
  1111. ------
  1112. ValueError
  1113. Raised if some values are missing and `allow_masked` is False.
  1114. See Also
  1115. --------
  1116. numpy.cov
  1117. """
  1118. # Check inputs
  1119. if ddof is not None and ddof != int(ddof):
  1120. raise ValueError("ddof must be an integer")
  1121. # Set up ddof
  1122. if ddof is None:
  1123. if bias:
  1124. ddof = 0
  1125. else:
  1126. ddof = 1
  1127. (x, xnotmask, rowvar) = _covhelper(x, y, rowvar, allow_masked)
  1128. if not rowvar:
  1129. fact = np.dot(xnotmask.T, xnotmask) * 1. - ddof
  1130. result = (dot(x.T, x.conj(), strict=False) / fact).squeeze()
  1131. else:
  1132. fact = np.dot(xnotmask, xnotmask.T) * 1. - ddof
  1133. result = (dot(x, x.T.conj(), strict=False) / fact).squeeze()
  1134. return result
  1135. def corrcoef(x, y=None, rowvar=True, bias=np._NoValue, allow_masked=True,
  1136. ddof=np._NoValue):
  1137. """
  1138. Return Pearson product-moment correlation coefficients.
  1139. Except for the handling of missing data this function does the same as
  1140. `numpy.corrcoef`. For more details and examples, see `numpy.corrcoef`.
  1141. Parameters
  1142. ----------
  1143. x : array_like
  1144. A 1-D or 2-D array containing multiple variables and observations.
  1145. Each row of `x` represents a variable, and each column a single
  1146. observation of all those variables. Also see `rowvar` below.
  1147. y : array_like, optional
  1148. An additional set of variables and observations. `y` has the same
  1149. shape as `x`.
  1150. rowvar : bool, optional
  1151. If `rowvar` is True (default), then each row represents a
  1152. variable, with observations in the columns. Otherwise, the relationship
  1153. is transposed: each column represents a variable, while the rows
  1154. contain observations.
  1155. bias : _NoValue, optional
  1156. Has no effect, do not use.
  1157. .. deprecated:: 1.10.0
  1158. allow_masked : bool, optional
  1159. If True, masked values are propagated pair-wise: if a value is masked
  1160. in `x`, the corresponding value is masked in `y`.
  1161. If False, raises an exception. Because `bias` is deprecated, this
  1162. argument needs to be treated as keyword only to avoid a warning.
  1163. ddof : _NoValue, optional
  1164. Has no effect, do not use.
  1165. .. deprecated:: 1.10.0
  1166. See Also
  1167. --------
  1168. numpy.corrcoef : Equivalent function in top-level NumPy module.
  1169. cov : Estimate the covariance matrix.
  1170. Notes
  1171. -----
  1172. This function accepts but discards arguments `bias` and `ddof`. This is
  1173. for backwards compatibility with previous versions of this function. These
  1174. arguments had no effect on the return values of the function and can be
  1175. safely ignored in this and previous versions of numpy.
  1176. """
  1177. msg = 'bias and ddof have no effect and are deprecated'
  1178. if bias is not np._NoValue or ddof is not np._NoValue:
  1179. # 2015-03-15, 1.10
  1180. warnings.warn(msg, DeprecationWarning, stacklevel=2)
  1181. # Get the data
  1182. (x, xnotmask, rowvar) = _covhelper(x, y, rowvar, allow_masked)
  1183. # Compute the covariance matrix
  1184. if not rowvar:
  1185. fact = np.dot(xnotmask.T, xnotmask) * 1.
  1186. c = (dot(x.T, x.conj(), strict=False) / fact).squeeze()
  1187. else:
  1188. fact = np.dot(xnotmask, xnotmask.T) * 1.
  1189. c = (dot(x, x.T.conj(), strict=False) / fact).squeeze()
  1190. # Check whether we have a scalar
  1191. try:
  1192. diag = ma.diagonal(c)
  1193. except ValueError:
  1194. return 1
  1195. #
  1196. if xnotmask.all():
  1197. _denom = ma.sqrt(ma.multiply.outer(diag, diag))
  1198. else:
  1199. _denom = diagflat(diag)
  1200. _denom._sharedmask = False # We know return is always a copy
  1201. n = x.shape[1 - rowvar]
  1202. if rowvar:
  1203. for i in range(n - 1):
  1204. for j in range(i + 1, n):
  1205. _x = mask_cols(vstack((x[i], x[j]))).var(axis=1)
  1206. _denom[i, j] = _denom[j, i] = ma.sqrt(ma.multiply.reduce(_x))
  1207. else:
  1208. for i in range(n - 1):
  1209. for j in range(i + 1, n):
  1210. _x = mask_cols(
  1211. vstack((x[:, i], x[:, j]))).var(axis=1)
  1212. _denom[i, j] = _denom[j, i] = ma.sqrt(ma.multiply.reduce(_x))
  1213. return c / _denom
  1214. #####--------------------------------------------------------------------------
  1215. #---- --- Concatenation helpers ---
  1216. #####--------------------------------------------------------------------------
  1217. class MAxisConcatenator(AxisConcatenator):
  1218. """
  1219. Translate slice objects to concatenation along an axis.
  1220. For documentation on usage, see `mr_class`.
  1221. See Also
  1222. --------
  1223. mr_class
  1224. """
  1225. concatenate = staticmethod(concatenate)
  1226. @classmethod
  1227. def makemat(cls, arr):
  1228. # There used to be a view as np.matrix here, but we may eventually
  1229. # deprecate that class. In preparation, we use the unmasked version
  1230. # to construct the matrix (with copy=False for backwards compatibility
  1231. # with the .view)
  1232. data = super(MAxisConcatenator, cls).makemat(arr.data, copy=False)
  1233. return array(data, mask=arr.mask)
  1234. def __getitem__(self, key):
  1235. # matrix builder syntax, like 'a, b; c, d'
  1236. if isinstance(key, str):
  1237. raise MAError("Unavailable for masked array.")
  1238. return super(MAxisConcatenator, self).__getitem__(key)
  1239. class mr_class(MAxisConcatenator):
  1240. """
  1241. Translate slice objects to concatenation along the first axis.
  1242. This is the masked array version of `lib.index_tricks.RClass`.
  1243. See Also
  1244. --------
  1245. lib.index_tricks.RClass
  1246. Examples
  1247. --------
  1248. >>> np.ma.mr_[np.ma.array([1,2,3]), 0, 0, np.ma.array([4,5,6])]
  1249. array([1, 2, 3, 0, 0, 4, 5, 6])
  1250. """
  1251. def __init__(self):
  1252. MAxisConcatenator.__init__(self, 0)
  1253. mr_ = mr_class()
  1254. #####--------------------------------------------------------------------------
  1255. #---- Find unmasked data ---
  1256. #####--------------------------------------------------------------------------
  1257. def flatnotmasked_edges(a):
  1258. """
  1259. Find the indices of the first and last unmasked values.
  1260. Expects a 1-D `MaskedArray`, returns None if all values are masked.
  1261. Parameters
  1262. ----------
  1263. a : array_like
  1264. Input 1-D `MaskedArray`
  1265. Returns
  1266. -------
  1267. edges : ndarray or None
  1268. The indices of first and last non-masked value in the array.
  1269. Returns None if all values are masked.
  1270. See Also
  1271. --------
  1272. flatnotmasked_contiguous, notmasked_contiguous, notmasked_edges,
  1273. clump_masked, clump_unmasked
  1274. Notes
  1275. -----
  1276. Only accepts 1-D arrays.
  1277. Examples
  1278. --------
  1279. >>> a = np.ma.arange(10)
  1280. >>> flatnotmasked_edges(a)
  1281. [0,-1]
  1282. >>> mask = (a < 3) | (a > 8) | (a == 5)
  1283. >>> a[mask] = np.ma.masked
  1284. >>> np.array(a[~a.mask])
  1285. array([3, 4, 6, 7, 8])
  1286. >>> flatnotmasked_edges(a)
  1287. array([3, 8])
  1288. >>> a[:] = np.ma.masked
  1289. >>> print(flatnotmasked_edges(ma))
  1290. None
  1291. """
  1292. m = getmask(a)
  1293. if m is nomask or not np.any(m):
  1294. return np.array([0, a.size - 1])
  1295. unmasked = np.flatnonzero(~m)
  1296. if len(unmasked) > 0:
  1297. return unmasked[[0, -1]]
  1298. else:
  1299. return None
  1300. def notmasked_edges(a, axis=None):
  1301. """
  1302. Find the indices of the first and last unmasked values along an axis.
  1303. If all values are masked, return None. Otherwise, return a list
  1304. of two tuples, corresponding to the indices of the first and last
  1305. unmasked values respectively.
  1306. Parameters
  1307. ----------
  1308. a : array_like
  1309. The input array.
  1310. axis : int, optional
  1311. Axis along which to perform the operation.
  1312. If None (default), applies to a flattened version of the array.
  1313. Returns
  1314. -------
  1315. edges : ndarray or list
  1316. An array of start and end indexes if there are any masked data in
  1317. the array. If there are no masked data in the array, `edges` is a
  1318. list of the first and last index.
  1319. See Also
  1320. --------
  1321. flatnotmasked_contiguous, flatnotmasked_edges, notmasked_contiguous,
  1322. clump_masked, clump_unmasked
  1323. Examples
  1324. --------
  1325. >>> a = np.arange(9).reshape((3, 3))
  1326. >>> m = np.zeros_like(a)
  1327. >>> m[1:, 1:] = 1
  1328. >>> am = np.ma.array(a, mask=m)
  1329. >>> np.array(am[~am.mask])
  1330. array([0, 1, 2, 3, 6])
  1331. >>> np.ma.notmasked_edges(ma)
  1332. array([0, 6])
  1333. """
  1334. a = asarray(a)
  1335. if axis is None or a.ndim == 1:
  1336. return flatnotmasked_edges(a)
  1337. m = getmaskarray(a)
  1338. idx = array(np.indices(a.shape), mask=np.asarray([m] * a.ndim))
  1339. return [tuple([idx[i].min(axis).compressed() for i in range(a.ndim)]),
  1340. tuple([idx[i].max(axis).compressed() for i in range(a.ndim)]), ]
  1341. def flatnotmasked_contiguous(a):
  1342. """
  1343. Find contiguous unmasked data in a masked array along the given axis.
  1344. Parameters
  1345. ----------
  1346. a : narray
  1347. The input array.
  1348. Returns
  1349. -------
  1350. slice_list : list
  1351. A sorted sequence of `slice` objects (start index, end index).
  1352. ..versionchanged:: 1.15.0
  1353. Now returns an empty list instead of None for a fully masked array
  1354. See Also
  1355. --------
  1356. flatnotmasked_edges, notmasked_contiguous, notmasked_edges,
  1357. clump_masked, clump_unmasked
  1358. Notes
  1359. -----
  1360. Only accepts 2-D arrays at most.
  1361. Examples
  1362. --------
  1363. >>> a = np.ma.arange(10)
  1364. >>> np.ma.flatnotmasked_contiguous(a)
  1365. [slice(0, 10, None)]
  1366. >>> mask = (a < 3) | (a > 8) | (a == 5)
  1367. >>> a[mask] = np.ma.masked
  1368. >>> np.array(a[~a.mask])
  1369. array([3, 4, 6, 7, 8])
  1370. >>> np.ma.flatnotmasked_contiguous(a)
  1371. [slice(3, 5, None), slice(6, 9, None)]
  1372. >>> a[:] = np.ma.masked
  1373. >>> np.ma.flatnotmasked_contiguous(a)
  1374. []
  1375. """
  1376. m = getmask(a)
  1377. if m is nomask:
  1378. return [slice(0, a.size)]
  1379. i = 0
  1380. result = []
  1381. for (k, g) in itertools.groupby(m.ravel()):
  1382. n = len(list(g))
  1383. if not k:
  1384. result.append(slice(i, i + n))
  1385. i += n
  1386. return result
  1387. def notmasked_contiguous(a, axis=None):
  1388. """
  1389. Find contiguous unmasked data in a masked array along the given axis.
  1390. Parameters
  1391. ----------
  1392. a : array_like
  1393. The input array.
  1394. axis : int, optional
  1395. Axis along which to perform the operation.
  1396. If None (default), applies to a flattened version of the array, and this
  1397. is the same as `flatnotmasked_contiguous`.
  1398. Returns
  1399. -------
  1400. endpoints : list
  1401. A list of slices (start and end indexes) of unmasked indexes
  1402. in the array.
  1403. If the input is 2d and axis is specified, the result is a list of lists.
  1404. See Also
  1405. --------
  1406. flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges,
  1407. clump_masked, clump_unmasked
  1408. Notes
  1409. -----
  1410. Only accepts 2-D arrays at most.
  1411. Examples
  1412. --------
  1413. >>> a = np.arange(12).reshape((3, 4))
  1414. >>> mask = np.zeros_like(a)
  1415. >>> mask[1:, :-1] = 1; mask[0, 1] = 1; mask[-1, 0] = 0
  1416. >>> ma = np.ma.array(a, mask=mask)
  1417. >>> ma
  1418. masked_array(
  1419. data=[[0, --, 2, 3],
  1420. [--, --, --, 7],
  1421. [8, --, --, 11]],
  1422. mask=[[False, True, False, False],
  1423. [ True, True, True, False],
  1424. [False, True, True, False]],
  1425. fill_value=999999)
  1426. >>> np.array(ma[~ma.mask])
  1427. array([ 0, 2, 3, 7, 8, 11])
  1428. >>> np.ma.notmasked_contiguous(ma)
  1429. [slice(0, 1, None), slice(2, 4, None), slice(7, 9, None), slice(11, 12, None)]
  1430. >>> np.ma.notmasked_contiguous(ma, axis=0)
  1431. [[slice(0, 1, None), slice(2, 3, None)], # column broken into two segments
  1432. [], # fully masked column
  1433. [slice(0, 1, None)],
  1434. [slice(0, 3, None)]]
  1435. >>> np.ma.notmasked_contiguous(ma, axis=1)
  1436. [[slice(0, 1, None), slice(2, 4, None)], # row broken into two segments
  1437. [slice(3, 4, None)],
  1438. [slice(0, 1, None), slice(3, 4, None)]]
  1439. """
  1440. a = asarray(a)
  1441. nd = a.ndim
  1442. if nd > 2:
  1443. raise NotImplementedError("Currently limited to atmost 2D array.")
  1444. if axis is None or nd == 1:
  1445. return flatnotmasked_contiguous(a)
  1446. #
  1447. result = []
  1448. #
  1449. other = (axis + 1) % 2
  1450. idx = [0, 0]
  1451. idx[axis] = slice(None, None)
  1452. #
  1453. for i in range(a.shape[other]):
  1454. idx[other] = i
  1455. result.append(flatnotmasked_contiguous(a[tuple(idx)]))
  1456. return result
  1457. def _ezclump(mask):
  1458. """
  1459. Finds the clumps (groups of data with the same values) for a 1D bool array.
  1460. Returns a series of slices.
  1461. """
  1462. if mask.ndim > 1:
  1463. mask = mask.ravel()
  1464. idx = (mask[1:] ^ mask[:-1]).nonzero()
  1465. idx = idx[0] + 1
  1466. if mask[0]:
  1467. if len(idx) == 0:
  1468. return [slice(0, mask.size)]
  1469. r = [slice(0, idx[0])]
  1470. r.extend((slice(left, right)
  1471. for left, right in zip(idx[1:-1:2], idx[2::2])))
  1472. else:
  1473. if len(idx) == 0:
  1474. return []
  1475. r = [slice(left, right) for left, right in zip(idx[:-1:2], idx[1::2])]
  1476. if mask[-1]:
  1477. r.append(slice(idx[-1], mask.size))
  1478. return r
  1479. def clump_unmasked(a):
  1480. """
  1481. Return list of slices corresponding to the unmasked clumps of a 1-D array.
  1482. (A "clump" is defined as a contiguous region of the array).
  1483. Parameters
  1484. ----------
  1485. a : ndarray
  1486. A one-dimensional masked array.
  1487. Returns
  1488. -------
  1489. slices : list of slice
  1490. The list of slices, one for each continuous region of unmasked
  1491. elements in `a`.
  1492. Notes
  1493. -----
  1494. .. versionadded:: 1.4.0
  1495. See Also
  1496. --------
  1497. flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges,
  1498. notmasked_contiguous, clump_masked
  1499. Examples
  1500. --------
  1501. >>> a = np.ma.masked_array(np.arange(10))
  1502. >>> a[[0, 1, 2, 6, 8, 9]] = np.ma.masked
  1503. >>> np.ma.clump_unmasked(a)
  1504. [slice(3, 6, None), slice(7, 8, None)]
  1505. """
  1506. mask = getattr(a, '_mask', nomask)
  1507. if mask is nomask:
  1508. return [slice(0, a.size)]
  1509. return _ezclump(~mask)
  1510. def clump_masked(a):
  1511. """
  1512. Returns a list of slices corresponding to the masked clumps of a 1-D array.
  1513. (A "clump" is defined as a contiguous region of the array).
  1514. Parameters
  1515. ----------
  1516. a : ndarray
  1517. A one-dimensional masked array.
  1518. Returns
  1519. -------
  1520. slices : list of slice
  1521. The list of slices, one for each continuous region of masked elements
  1522. in `a`.
  1523. Notes
  1524. -----
  1525. .. versionadded:: 1.4.0
  1526. See Also
  1527. --------
  1528. flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges,
  1529. notmasked_contiguous, clump_unmasked
  1530. Examples
  1531. --------
  1532. >>> a = np.ma.masked_array(np.arange(10))
  1533. >>> a[[0, 1, 2, 6, 8, 9]] = np.ma.masked
  1534. >>> np.ma.clump_masked(a)
  1535. [slice(0, 3, None), slice(6, 7, None), slice(8, 10, None)]
  1536. """
  1537. mask = ma.getmask(a)
  1538. if mask is nomask:
  1539. return []
  1540. return _ezclump(mask)
  1541. ###############################################################################
  1542. # Polynomial fit #
  1543. ###############################################################################
  1544. def vander(x, n=None):
  1545. """
  1546. Masked values in the input array result in rows of zeros.
  1547. """
  1548. _vander = np.vander(x, n)
  1549. m = getmask(x)
  1550. if m is not nomask:
  1551. _vander[m] = 0
  1552. return _vander
  1553. vander.__doc__ = ma.doc_note(np.vander.__doc__, vander.__doc__)
  1554. def polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False):
  1555. """
  1556. Any masked values in x is propagated in y, and vice-versa.
  1557. """
  1558. x = asarray(x)
  1559. y = asarray(y)
  1560. m = getmask(x)
  1561. if y.ndim == 1:
  1562. m = mask_or(m, getmask(y))
  1563. elif y.ndim == 2:
  1564. my = getmask(mask_rows(y))
  1565. if my is not nomask:
  1566. m = mask_or(m, my[:, 0])
  1567. else:
  1568. raise TypeError("Expected a 1D or 2D array for y!")
  1569. if w is not None:
  1570. w = asarray(w)
  1571. if w.ndim != 1:
  1572. raise TypeError("expected a 1-d array for weights")
  1573. if w.shape[0] != y.shape[0]:
  1574. raise TypeError("expected w and y to have the same length")
  1575. m = mask_or(m, getmask(w))
  1576. if m is not nomask:
  1577. not_m = ~m
  1578. if w is not None:
  1579. w = w[not_m]
  1580. return np.polyfit(x[not_m], y[not_m], deg, rcond, full, w, cov)
  1581. else:
  1582. return np.polyfit(x, y, deg, rcond, full, w, cov)
  1583. polyfit.__doc__ = ma.doc_note(np.polyfit.__doc__, polyfit.__doc__)