extras.py 57 KB

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