extras.py 69 KB

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