extras.py 60 KB

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