diff --git a/ckpts/universal/global_step60/zero/10.mlp.dense_4h_to_h.weight/exp_avg.pt b/ckpts/universal/global_step60/zero/10.mlp.dense_4h_to_h.weight/exp_avg.pt new file mode 100644 index 0000000000000000000000000000000000000000..a21f0526f2b2e7faa57e4d62cc24c98987b89839 --- /dev/null +++ b/ckpts/universal/global_step60/zero/10.mlp.dense_4h_to_h.weight/exp_avg.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7c5cf66504193ddfc2f1a66aab0560cd5eaa7453205ac8c09ac87876001e734b +size 33555612 diff --git a/ckpts/universal/global_step60/zero/10.mlp.dense_4h_to_h.weight/exp_avg_sq.pt b/ckpts/universal/global_step60/zero/10.mlp.dense_4h_to_h.weight/exp_avg_sq.pt new file mode 100644 index 0000000000000000000000000000000000000000..61eb0f6b9b5b2961e3e6da3b1f96c83ff2e000d4 --- /dev/null +++ b/ckpts/universal/global_step60/zero/10.mlp.dense_4h_to_h.weight/exp_avg_sq.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:38d6824ac47b721ab1a9e34448572f832bc7e5e60f18216cafb57b38fafe9fcc +size 33555627 diff --git a/ckpts/universal/global_step60/zero/10.mlp.dense_4h_to_h.weight/fp32.pt b/ckpts/universal/global_step60/zero/10.mlp.dense_4h_to_h.weight/fp32.pt new file mode 100644 index 0000000000000000000000000000000000000000..a07c4de9c94891ad293e940b4c7b837b2116a56e --- /dev/null +++ b/ckpts/universal/global_step60/zero/10.mlp.dense_4h_to_h.weight/fp32.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cfc7a15498a589c0fdde19f3e022679301f6ca0f35e7a901ac863216f9c03b3b +size 33555533 diff --git a/ckpts/universal/global_step60/zero/12.attention.dense.weight/exp_avg.pt b/ckpts/universal/global_step60/zero/12.attention.dense.weight/exp_avg.pt new file mode 100644 index 0000000000000000000000000000000000000000..63a1fc609893f8a9ce576fddea83a4603d91259f --- /dev/null +++ b/ckpts/universal/global_step60/zero/12.attention.dense.weight/exp_avg.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:27da9c6159be5e36247fd7e2e11deff175a7b49a0396079364f9422b1c34aca3 +size 16778396 diff --git a/ckpts/universal/global_step60/zero/12.attention.dense.weight/exp_avg_sq.pt b/ckpts/universal/global_step60/zero/12.attention.dense.weight/exp_avg_sq.pt new file mode 100644 index 0000000000000000000000000000000000000000..0106724c4d92df91eab9faa2b0b22e945e409a0c --- /dev/null +++ b/ckpts/universal/global_step60/zero/12.attention.dense.weight/exp_avg_sq.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0d0385130c0db44568b7d1560887bb48b2c29039dd0d362e48106aa24ba14d5e +size 16778411 diff --git a/ckpts/universal/global_step60/zero/22.mlp.dense_h_to_4h_swiglu.weight/exp_avg.pt b/ckpts/universal/global_step60/zero/22.mlp.dense_h_to_4h_swiglu.weight/exp_avg.pt new file mode 100644 index 0000000000000000000000000000000000000000..8600f834f1bdac233eacc8ae451ef4032f75ea72 --- /dev/null +++ b/ckpts/universal/global_step60/zero/22.mlp.dense_h_to_4h_swiglu.weight/exp_avg.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e6917da9b2c7e936632420afb61a22f551a9b5fba59e43be876f844343826482 +size 33555612 diff --git a/ckpts/universal/global_step60/zero/7.mlp.dense_4h_to_h.weight/exp_avg_sq.pt b/ckpts/universal/global_step60/zero/7.mlp.dense_4h_to_h.weight/exp_avg_sq.pt new file mode 100644 index 0000000000000000000000000000000000000000..ecd56a59a46a63c43f029af5355c7a4d6a9c165d --- /dev/null +++ b/ckpts/universal/global_step60/zero/7.mlp.dense_4h_to_h.weight/exp_avg_sq.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7f9a59fbed1ed282cf87f7cea6ad615a54b186e8853e8abe12d7294a2f88efe8 +size 33555627 diff --git a/venv/lib/python3.10/site-packages/numpy/_utils/__init__.py b/venv/lib/python3.10/site-packages/numpy/_utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..388dd9174f356c74d6cdd6ad9a8b1ad603234420 --- /dev/null +++ b/venv/lib/python3.10/site-packages/numpy/_utils/__init__.py @@ -0,0 +1,29 @@ +""" +This is a module for defining private helpers which do not depend on the +rest of NumPy. + +Everything in here must be self-contained so that it can be +imported anywhere else without creating circular imports. +If a utility requires the import of NumPy, it probably belongs +in ``numpy.core``. +""" + +from ._convertions import asunicode, asbytes + + +def set_module(module): + """Private decorator for overriding __module__ on a function or class. + + Example usage:: + + @set_module('numpy') + def example(): + pass + + assert example.__module__ == 'numpy' + """ + def decorator(func): + if module is not None: + func.__module__ = module + return func + return decorator diff --git a/venv/lib/python3.10/site-packages/numpy/_utils/__pycache__/_convertions.cpython-310.pyc b/venv/lib/python3.10/site-packages/numpy/_utils/__pycache__/_convertions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..54dd79559496f0db632b985d321ffc197cba1880 Binary files /dev/null and b/venv/lib/python3.10/site-packages/numpy/_utils/__pycache__/_convertions.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/numpy/_utils/__pycache__/_inspect.cpython-310.pyc b/venv/lib/python3.10/site-packages/numpy/_utils/__pycache__/_inspect.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be347e121f6f144531660697003d1434ee192c5e Binary files /dev/null and b/venv/lib/python3.10/site-packages/numpy/_utils/__pycache__/_inspect.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/numpy/_utils/_convertions.py b/venv/lib/python3.10/site-packages/numpy/_utils/_convertions.py new file mode 100644 index 0000000000000000000000000000000000000000..ab15a8ba019f1b6a40ac3f562897fa4581323efc --- /dev/null +++ b/venv/lib/python3.10/site-packages/numpy/_utils/_convertions.py @@ -0,0 +1,18 @@ +""" +A set of methods retained from np.compat module that +are still used across codebase. +""" + +__all__ = ["asunicode", "asbytes"] + + +def asunicode(s): + if isinstance(s, bytes): + return s.decode('latin1') + return str(s) + + +def asbytes(s): + if isinstance(s, bytes): + return s + return str(s).encode('latin1') diff --git a/venv/lib/python3.10/site-packages/numpy/_utils/_inspect.py b/venv/lib/python3.10/site-packages/numpy/_utils/_inspect.py new file mode 100644 index 0000000000000000000000000000000000000000..9a874a71dd0a53e25a671c51bfdceec850702bfe --- /dev/null +++ b/venv/lib/python3.10/site-packages/numpy/_utils/_inspect.py @@ -0,0 +1,191 @@ +"""Subset of inspect module from upstream python + +We use this instead of upstream because upstream inspect is slow to import, and +significantly contributes to numpy import times. Importing this copy has almost +no overhead. + +""" +import types + +__all__ = ['getargspec', 'formatargspec'] + +# ----------------------------------------------------------- type-checking +def ismethod(object): + """Return true if the object is an instance method. + + Instance method objects provide these attributes: + __doc__ documentation string + __name__ name with which this method was defined + im_class class object in which this method belongs + im_func function object containing implementation of method + im_self instance to which this method is bound, or None + + """ + return isinstance(object, types.MethodType) + +def isfunction(object): + """Return true if the object is a user-defined function. + + Function objects provide these attributes: + __doc__ documentation string + __name__ name with which this function was defined + func_code code object containing compiled function bytecode + func_defaults tuple of any default values for arguments + func_doc (same as __doc__) + func_globals global namespace in which this function was defined + func_name (same as __name__) + + """ + return isinstance(object, types.FunctionType) + +def iscode(object): + """Return true if the object is a code object. + + Code objects provide these attributes: + co_argcount number of arguments (not including * or ** args) + co_code string of raw compiled bytecode + co_consts tuple of constants used in the bytecode + co_filename name of file in which this code object was created + co_firstlineno number of first line in Python source code + co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg + co_lnotab encoded mapping of line numbers to bytecode indices + co_name name with which this code object was defined + co_names tuple of names of local variables + co_nlocals number of local variables + co_stacksize virtual machine stack space required + co_varnames tuple of names of arguments and local variables + + """ + return isinstance(object, types.CodeType) + +# ------------------------------------------------ argument list extraction +# These constants are from Python's compile.h. +CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS = 1, 2, 4, 8 + +def getargs(co): + """Get information about the arguments accepted by a code object. + + Three things are returned: (args, varargs, varkw), where 'args' is + a list of argument names (possibly containing nested lists), and + 'varargs' and 'varkw' are the names of the * and ** arguments or None. + + """ + + if not iscode(co): + raise TypeError('arg is not a code object') + + nargs = co.co_argcount + names = co.co_varnames + args = list(names[:nargs]) + + # The following acrobatics are for anonymous (tuple) arguments. + # Which we do not need to support, so remove to avoid importing + # the dis module. + for i in range(nargs): + if args[i][:1] in ['', '.']: + raise TypeError("tuple function arguments are not supported") + varargs = None + if co.co_flags & CO_VARARGS: + varargs = co.co_varnames[nargs] + nargs = nargs + 1 + varkw = None + if co.co_flags & CO_VARKEYWORDS: + varkw = co.co_varnames[nargs] + return args, varargs, varkw + +def getargspec(func): + """Get the names and default values of a function's arguments. + + A tuple of four things is returned: (args, varargs, varkw, defaults). + 'args' is a list of the argument names (it may contain nested lists). + 'varargs' and 'varkw' are the names of the * and ** arguments or None. + 'defaults' is an n-tuple of the default values of the last n arguments. + + """ + + if ismethod(func): + func = func.__func__ + if not isfunction(func): + raise TypeError('arg is not a Python function') + args, varargs, varkw = getargs(func.__code__) + return args, varargs, varkw, func.__defaults__ + +def getargvalues(frame): + """Get information about arguments passed into a particular frame. + + A tuple of four things is returned: (args, varargs, varkw, locals). + 'args' is a list of the argument names (it may contain nested lists). + 'varargs' and 'varkw' are the names of the * and ** arguments or None. + 'locals' is the locals dictionary of the given frame. + + """ + args, varargs, varkw = getargs(frame.f_code) + return args, varargs, varkw, frame.f_locals + +def joinseq(seq): + if len(seq) == 1: + return '(' + seq[0] + ',)' + else: + return '(' + ', '.join(seq) + ')' + +def strseq(object, convert, join=joinseq): + """Recursively walk a sequence, stringifying each element. + + """ + if type(object) in [list, tuple]: + return join([strseq(_o, convert, join) for _o in object]) + else: + return convert(object) + +def formatargspec(args, varargs=None, varkw=None, defaults=None, + formatarg=str, + formatvarargs=lambda name: '*' + name, + formatvarkw=lambda name: '**' + name, + formatvalue=lambda value: '=' + repr(value), + join=joinseq): + """Format an argument spec from the 4 values returned by getargspec. + + The first four arguments are (args, varargs, varkw, defaults). The + other four arguments are the corresponding optional formatting functions + that are called to turn names and values into strings. The ninth + argument is an optional function to format the sequence of arguments. + + """ + specs = [] + if defaults: + firstdefault = len(args) - len(defaults) + for i in range(len(args)): + spec = strseq(args[i], formatarg, join) + if defaults and i >= firstdefault: + spec = spec + formatvalue(defaults[i - firstdefault]) + specs.append(spec) + if varargs is not None: + specs.append(formatvarargs(varargs)) + if varkw is not None: + specs.append(formatvarkw(varkw)) + return '(' + ', '.join(specs) + ')' + +def formatargvalues(args, varargs, varkw, locals, + formatarg=str, + formatvarargs=lambda name: '*' + name, + formatvarkw=lambda name: '**' + name, + formatvalue=lambda value: '=' + repr(value), + join=joinseq): + """Format an argument spec from the 4 values returned by getargvalues. + + The first four arguments are (args, varargs, varkw, locals). The + next four arguments are the corresponding optional formatting functions + that are called to turn names and values into strings. The ninth + argument is an optional function to format the sequence of arguments. + + """ + def convert(name, locals=locals, + formatarg=formatarg, formatvalue=formatvalue): + return formatarg(name) + formatvalue(locals[name]) + specs = [strseq(arg, convert, join) for arg in args] + + if varargs: + specs.append(formatvarargs(varargs) + formatvalue(locals[varargs])) + if varkw: + specs.append(formatvarkw(varkw) + formatvalue(locals[varkw])) + return '(' + ', '.join(specs) + ')' diff --git a/venv/lib/python3.10/site-packages/numpy/_utils/_pep440.py b/venv/lib/python3.10/site-packages/numpy/_utils/_pep440.py new file mode 100644 index 0000000000000000000000000000000000000000..73d0afb5e95f099f8b04253177e8a3ab3d80d0c4 --- /dev/null +++ b/venv/lib/python3.10/site-packages/numpy/_utils/_pep440.py @@ -0,0 +1,487 @@ +"""Utility to compare pep440 compatible version strings. + +The LooseVersion and StrictVersion classes that distutils provides don't +work; they don't recognize anything like alpha/beta/rc/dev versions. +""" + +# Copyright (c) Donald Stufft and individual contributors. +# All rights reserved. + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: + +# 1. Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. + +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +import collections +import itertools +import re + + +__all__ = [ + "parse", "Version", "LegacyVersion", "InvalidVersion", "VERSION_PATTERN", +] + + +# BEGIN packaging/_structures.py + + +class Infinity: + def __repr__(self): + return "Infinity" + + def __hash__(self): + return hash(repr(self)) + + def __lt__(self, other): + return False + + def __le__(self, other): + return False + + def __eq__(self, other): + return isinstance(other, self.__class__) + + def __ne__(self, other): + return not isinstance(other, self.__class__) + + def __gt__(self, other): + return True + + def __ge__(self, other): + return True + + def __neg__(self): + return NegativeInfinity + + +Infinity = Infinity() + + +class NegativeInfinity: + def __repr__(self): + return "-Infinity" + + def __hash__(self): + return hash(repr(self)) + + def __lt__(self, other): + return True + + def __le__(self, other): + return True + + def __eq__(self, other): + return isinstance(other, self.__class__) + + def __ne__(self, other): + return not isinstance(other, self.__class__) + + def __gt__(self, other): + return False + + def __ge__(self, other): + return False + + def __neg__(self): + return Infinity + + +# BEGIN packaging/version.py + + +NegativeInfinity = NegativeInfinity() + +_Version = collections.namedtuple( + "_Version", + ["epoch", "release", "dev", "pre", "post", "local"], +) + + +def parse(version): + """ + Parse the given version string and return either a :class:`Version` object + or a :class:`LegacyVersion` object depending on if the given version is + a valid PEP 440 version or a legacy version. + """ + try: + return Version(version) + except InvalidVersion: + return LegacyVersion(version) + + +class InvalidVersion(ValueError): + """ + An invalid version was found, users should refer to PEP 440. + """ + + +class _BaseVersion: + + def __hash__(self): + return hash(self._key) + + def __lt__(self, other): + return self._compare(other, lambda s, o: s < o) + + def __le__(self, other): + return self._compare(other, lambda s, o: s <= o) + + def __eq__(self, other): + return self._compare(other, lambda s, o: s == o) + + def __ge__(self, other): + return self._compare(other, lambda s, o: s >= o) + + def __gt__(self, other): + return self._compare(other, lambda s, o: s > o) + + def __ne__(self, other): + return self._compare(other, lambda s, o: s != o) + + def _compare(self, other, method): + if not isinstance(other, _BaseVersion): + return NotImplemented + + return method(self._key, other._key) + + +class LegacyVersion(_BaseVersion): + + def __init__(self, version): + self._version = str(version) + self._key = _legacy_cmpkey(self._version) + + def __str__(self): + return self._version + + def __repr__(self): + return "".format(repr(str(self))) + + @property + def public(self): + return self._version + + @property + def base_version(self): + return self._version + + @property + def local(self): + return None + + @property + def is_prerelease(self): + return False + + @property + def is_postrelease(self): + return False + + +_legacy_version_component_re = re.compile( + r"(\d+ | [a-z]+ | \.| -)", re.VERBOSE, +) + +_legacy_version_replacement_map = { + "pre": "c", "preview": "c", "-": "final-", "rc": "c", "dev": "@", +} + + +def _parse_version_parts(s): + for part in _legacy_version_component_re.split(s): + part = _legacy_version_replacement_map.get(part, part) + + if not part or part == ".": + continue + + if part[:1] in "0123456789": + # pad for numeric comparison + yield part.zfill(8) + else: + yield "*" + part + + # ensure that alpha/beta/candidate are before final + yield "*final" + + +def _legacy_cmpkey(version): + # We hardcode an epoch of -1 here. A PEP 440 version can only have an epoch + # greater than or equal to 0. This will effectively put the LegacyVersion, + # which uses the defacto standard originally implemented by setuptools, + # as before all PEP 440 versions. + epoch = -1 + + # This scheme is taken from pkg_resources.parse_version setuptools prior to + # its adoption of the packaging library. + parts = [] + for part in _parse_version_parts(version.lower()): + if part.startswith("*"): + # remove "-" before a prerelease tag + if part < "*final": + while parts and parts[-1] == "*final-": + parts.pop() + + # remove trailing zeros from each series of numeric parts + while parts and parts[-1] == "00000000": + parts.pop() + + parts.append(part) + parts = tuple(parts) + + return epoch, parts + + +# Deliberately not anchored to the start and end of the string, to make it +# easier for 3rd party code to reuse +VERSION_PATTERN = r""" + v? + (?: + (?:(?P[0-9]+)!)? # epoch + (?P[0-9]+(?:\.[0-9]+)*) # release segment + (?P
                                          # pre-release
+            [-_\.]?
+            (?P(a|b|c|rc|alpha|beta|pre|preview))
+            [-_\.]?
+            (?P[0-9]+)?
+        )?
+        (?P                                         # post release
+            (?:-(?P[0-9]+))
+            |
+            (?:
+                [-_\.]?
+                (?Ppost|rev|r)
+                [-_\.]?
+                (?P[0-9]+)?
+            )
+        )?
+        (?P                                          # dev release
+            [-_\.]?
+            (?Pdev)
+            [-_\.]?
+            (?P[0-9]+)?
+        )?
+    )
+    (?:\+(?P[a-z0-9]+(?:[-_\.][a-z0-9]+)*))?       # local version
+"""
+
+
+class Version(_BaseVersion):
+
+    _regex = re.compile(
+        r"^\s*" + VERSION_PATTERN + r"\s*$",
+        re.VERBOSE | re.IGNORECASE,
+    )
+
+    def __init__(self, version):
+        # Validate the version and parse it into pieces
+        match = self._regex.search(version)
+        if not match:
+            raise InvalidVersion("Invalid version: '{0}'".format(version))
+
+        # Store the parsed out pieces of the version
+        self._version = _Version(
+            epoch=int(match.group("epoch")) if match.group("epoch") else 0,
+            release=tuple(int(i) for i in match.group("release").split(".")),
+            pre=_parse_letter_version(
+                match.group("pre_l"),
+                match.group("pre_n"),
+            ),
+            post=_parse_letter_version(
+                match.group("post_l"),
+                match.group("post_n1") or match.group("post_n2"),
+            ),
+            dev=_parse_letter_version(
+                match.group("dev_l"),
+                match.group("dev_n"),
+            ),
+            local=_parse_local_version(match.group("local")),
+        )
+
+        # Generate a key which will be used for sorting
+        self._key = _cmpkey(
+            self._version.epoch,
+            self._version.release,
+            self._version.pre,
+            self._version.post,
+            self._version.dev,
+            self._version.local,
+        )
+
+    def __repr__(self):
+        return "".format(repr(str(self)))
+
+    def __str__(self):
+        parts = []
+
+        # Epoch
+        if self._version.epoch != 0:
+            parts.append("{0}!".format(self._version.epoch))
+
+        # Release segment
+        parts.append(".".join(str(x) for x in self._version.release))
+
+        # Pre-release
+        if self._version.pre is not None:
+            parts.append("".join(str(x) for x in self._version.pre))
+
+        # Post-release
+        if self._version.post is not None:
+            parts.append(".post{0}".format(self._version.post[1]))
+
+        # Development release
+        if self._version.dev is not None:
+            parts.append(".dev{0}".format(self._version.dev[1]))
+
+        # Local version segment
+        if self._version.local is not None:
+            parts.append(
+                "+{0}".format(".".join(str(x) for x in self._version.local))
+            )
+
+        return "".join(parts)
+
+    @property
+    def public(self):
+        return str(self).split("+", 1)[0]
+
+    @property
+    def base_version(self):
+        parts = []
+
+        # Epoch
+        if self._version.epoch != 0:
+            parts.append("{0}!".format(self._version.epoch))
+
+        # Release segment
+        parts.append(".".join(str(x) for x in self._version.release))
+
+        return "".join(parts)
+
+    @property
+    def local(self):
+        version_string = str(self)
+        if "+" in version_string:
+            return version_string.split("+", 1)[1]
+
+    @property
+    def is_prerelease(self):
+        return bool(self._version.dev or self._version.pre)
+
+    @property
+    def is_postrelease(self):
+        return bool(self._version.post)
+
+
+def _parse_letter_version(letter, number):
+    if letter:
+        # We assume there is an implicit 0 in a pre-release if there is
+        # no numeral associated with it.
+        if number is None:
+            number = 0
+
+        # We normalize any letters to their lower-case form
+        letter = letter.lower()
+
+        # We consider some words to be alternate spellings of other words and
+        # in those cases we want to normalize the spellings to our preferred
+        # spelling.
+        if letter == "alpha":
+            letter = "a"
+        elif letter == "beta":
+            letter = "b"
+        elif letter in ["c", "pre", "preview"]:
+            letter = "rc"
+        elif letter in ["rev", "r"]:
+            letter = "post"
+
+        return letter, int(number)
+    if not letter and number:
+        # We assume that if we are given a number but not given a letter,
+        # then this is using the implicit post release syntax (e.g., 1.0-1)
+        letter = "post"
+
+        return letter, int(number)
+
+
+_local_version_seperators = re.compile(r"[\._-]")
+
+
+def _parse_local_version(local):
+    """
+    Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
+    """
+    if local is not None:
+        return tuple(
+            part.lower() if not part.isdigit() else int(part)
+            for part in _local_version_seperators.split(local)
+        )
+
+
+def _cmpkey(epoch, release, pre, post, dev, local):
+    # When we compare a release version, we want to compare it with all of the
+    # trailing zeros removed. So we'll use a reverse the list, drop all the now
+    # leading zeros until we come to something non-zero, then take the rest,
+    # re-reverse it back into the correct order, and make it a tuple and use
+    # that for our sorting key.
+    release = tuple(
+        reversed(list(
+            itertools.dropwhile(
+                lambda x: x == 0,
+                reversed(release),
+            )
+        ))
+    )
+
+    # We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
+    # We'll do this by abusing the pre-segment, but we _only_ want to do this
+    # if there is no pre- or a post-segment. If we have one of those, then
+    # the normal sorting rules will handle this case correctly.
+    if pre is None and post is None and dev is not None:
+        pre = -Infinity
+    # Versions without a pre-release (except as noted above) should sort after
+    # those with one.
+    elif pre is None:
+        pre = Infinity
+
+    # Versions without a post-segment should sort before those with one.
+    if post is None:
+        post = -Infinity
+
+    # Versions without a development segment should sort after those with one.
+    if dev is None:
+        dev = Infinity
+
+    if local is None:
+        # Versions without a local segment should sort before those with one.
+        local = -Infinity
+    else:
+        # Versions with a local segment need that segment parsed to implement
+        # the sorting rules in PEP440.
+        # - Alphanumeric segments sort before numeric segments
+        # - Alphanumeric segments sort lexicographically
+        # - Numeric segments sort numerically
+        # - Shorter versions sort before longer versions when the prefixes
+        #   match exactly
+        local = tuple(
+            (i, "") if isinstance(i, int) else (-Infinity, i)
+            for i in local
+        )
+
+    return epoch, release, pre, post, dev, local
diff --git a/venv/lib/python3.10/site-packages/numpy/linalg/__init__.py b/venv/lib/python3.10/site-packages/numpy/linalg/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..93943de3896c135dde00080d30fd6cbe55a86e5d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/numpy/linalg/__init__.py
@@ -0,0 +1,80 @@
+"""
+``numpy.linalg``
+================
+
+The NumPy linear algebra functions rely on BLAS and LAPACK to provide efficient
+low level implementations of standard linear algebra algorithms. Those
+libraries may be provided by NumPy itself using C versions of a subset of their
+reference implementations but, when possible, highly optimized libraries that
+take advantage of specialized processor functionality are preferred. Examples
+of such libraries are OpenBLAS, MKL (TM), and ATLAS. Because those libraries
+are multithreaded and processor dependent, environmental variables and external
+packages such as threadpoolctl may be needed to control the number of threads
+or specify the processor architecture.
+
+- OpenBLAS: https://www.openblas.net/
+- threadpoolctl: https://github.com/joblib/threadpoolctl
+
+Please note that the most-used linear algebra functions in NumPy are present in
+the main ``numpy`` namespace rather than in ``numpy.linalg``.  There are:
+``dot``, ``vdot``, ``inner``, ``outer``, ``matmul``, ``tensordot``, ``einsum``,
+``einsum_path`` and ``kron``.
+
+Functions present in numpy.linalg are listed below.
+
+
+Matrix and vector products
+--------------------------
+
+   multi_dot
+   matrix_power
+
+Decompositions
+--------------
+
+   cholesky
+   qr
+   svd
+
+Matrix eigenvalues
+------------------
+
+   eig
+   eigh
+   eigvals
+   eigvalsh
+
+Norms and other numbers
+-----------------------
+
+   norm
+   cond
+   det
+   matrix_rank
+   slogdet
+
+Solving equations and inverting matrices
+----------------------------------------
+
+   solve
+   tensorsolve
+   lstsq
+   inv
+   pinv
+   tensorinv
+
+Exceptions
+----------
+
+   LinAlgError
+
+"""
+# To get sub-modules
+from . import linalg
+from .linalg import *
+
+__all__ = linalg.__all__.copy()
+
+from numpy._pytesttester import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/venv/lib/python3.10/site-packages/numpy/linalg/__init__.pyi b/venv/lib/python3.10/site-packages/numpy/linalg/__init__.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..d9acd55817325fb703ebddb7db594fac9cab5faf
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/numpy/linalg/__init__.pyi
@@ -0,0 +1,30 @@
+from numpy.linalg.linalg import (
+    matrix_power as matrix_power,
+    solve as solve,
+    tensorsolve as tensorsolve,
+    tensorinv as tensorinv,
+    inv as inv,
+    cholesky as cholesky,
+    eigvals as eigvals,
+    eigvalsh as eigvalsh,
+    pinv as pinv,
+    slogdet as slogdet,
+    det as det,
+    svd as svd,
+    eig as eig,
+    eigh as eigh,
+    lstsq as lstsq,
+    norm as norm,
+    qr as qr,
+    cond as cond,
+    matrix_rank as matrix_rank,
+    multi_dot as multi_dot,
+)
+
+from numpy._pytesttester import PytestTester
+
+__all__: list[str]
+__path__: list[str]
+test: PytestTester
+
+class LinAlgError(Exception): ...
diff --git a/venv/lib/python3.10/site-packages/numpy/linalg/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/numpy/linalg/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..381ead7da9a8f4f8386df231c0c41d0102bee17b
Binary files /dev/null and b/venv/lib/python3.10/site-packages/numpy/linalg/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/numpy/linalg/__pycache__/linalg.cpython-310.pyc b/venv/lib/python3.10/site-packages/numpy/linalg/__pycache__/linalg.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..421c57ef73d587dfc6539de8b7189f825171b2ae
Binary files /dev/null and b/venv/lib/python3.10/site-packages/numpy/linalg/__pycache__/linalg.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/numpy/linalg/_umath_linalg.cpython-310-x86_64-linux-gnu.so b/venv/lib/python3.10/site-packages/numpy/linalg/_umath_linalg.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..ca8e1ea2ceb9052f14a563467623ef90e32713bb
Binary files /dev/null and b/venv/lib/python3.10/site-packages/numpy/linalg/_umath_linalg.cpython-310-x86_64-linux-gnu.so differ
diff --git a/venv/lib/python3.10/site-packages/numpy/linalg/lapack_lite.cpython-310-x86_64-linux-gnu.so b/venv/lib/python3.10/site-packages/numpy/linalg/lapack_lite.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..17e196d0d51819f4c933f6a5b49c5e5645938e6b
Binary files /dev/null and b/venv/lib/python3.10/site-packages/numpy/linalg/lapack_lite.cpython-310-x86_64-linux-gnu.so differ
diff --git a/venv/lib/python3.10/site-packages/numpy/linalg/linalg.py b/venv/lib/python3.10/site-packages/numpy/linalg/linalg.py
new file mode 100644
index 0000000000000000000000000000000000000000..b838b9397024c028c1459e2e769e12d2fa767d88
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/numpy/linalg/linalg.py
@@ -0,0 +1,2836 @@
+"""Lite version of scipy.linalg.
+
+Notes
+-----
+This module is a lite version of the linalg.py module in SciPy which
+contains high-level Python interface to the LAPACK library.  The lite
+version only accesses the following LAPACK functions: dgesv, zgesv,
+dgeev, zgeev, dgesdd, zgesdd, dgelsd, zgelsd, dsyevd, zheevd, dgetrf,
+zgetrf, dpotrf, zpotrf, dgeqrf, zgeqrf, zungqr, dorgqr.
+"""
+
+__all__ = ['matrix_power', 'solve', 'tensorsolve', 'tensorinv', 'inv',
+           'cholesky', 'eigvals', 'eigvalsh', 'pinv', 'slogdet', 'det',
+           'svd', 'eig', 'eigh', 'lstsq', 'norm', 'qr', 'cond', 'matrix_rank',
+           'LinAlgError', 'multi_dot']
+
+import functools
+import operator
+import warnings
+from typing import NamedTuple, Any
+
+from .._utils import set_module
+from numpy.core import (
+    array, asarray, zeros, empty, empty_like, intc, single, double,
+    csingle, cdouble, inexact, complexfloating, newaxis, all, Inf, dot,
+    add, multiply, sqrt, sum, isfinite,
+    finfo, errstate, geterrobj, moveaxis, amin, amax, prod, abs,
+    atleast_2d, intp, asanyarray, object_, matmul,
+    swapaxes, divide, count_nonzero, isnan, sign, argsort, sort,
+    reciprocal
+)
+from numpy.core.multiarray import normalize_axis_index
+from numpy.core import overrides
+from numpy.lib.twodim_base import triu, eye
+from numpy.linalg import _umath_linalg
+
+from numpy._typing import NDArray
+
+class EigResult(NamedTuple):
+    eigenvalues: NDArray[Any]
+    eigenvectors: NDArray[Any]
+
+class EighResult(NamedTuple):
+    eigenvalues: NDArray[Any]
+    eigenvectors: NDArray[Any]
+
+class QRResult(NamedTuple):
+    Q: NDArray[Any]
+    R: NDArray[Any]
+
+class SlogdetResult(NamedTuple):
+    sign: NDArray[Any]
+    logabsdet: NDArray[Any]
+
+class SVDResult(NamedTuple):
+    U: NDArray[Any]
+    S: NDArray[Any]
+    Vh: NDArray[Any]
+
+array_function_dispatch = functools.partial(
+    overrides.array_function_dispatch, module='numpy.linalg')
+
+
+fortran_int = intc
+
+
+@set_module('numpy.linalg')
+class LinAlgError(ValueError):
+    """
+    Generic Python-exception-derived object raised by linalg functions.
+
+    General purpose exception class, derived from Python's ValueError
+    class, programmatically raised in linalg functions when a Linear
+    Algebra-related condition would prevent further correct execution of the
+    function.
+
+    Parameters
+    ----------
+    None
+
+    Examples
+    --------
+    >>> from numpy import linalg as LA
+    >>> LA.inv(np.zeros((2,2)))
+    Traceback (most recent call last):
+      File "", line 1, in 
+      File "...linalg.py", line 350,
+        in inv return wrap(solve(a, identity(a.shape[0], dtype=a.dtype)))
+      File "...linalg.py", line 249,
+        in solve
+        raise LinAlgError('Singular matrix')
+    numpy.linalg.LinAlgError: Singular matrix
+
+    """
+
+
+def _determine_error_states():
+    errobj = geterrobj()
+    bufsize = errobj[0]
+
+    with errstate(invalid='call', over='ignore',
+                  divide='ignore', under='ignore'):
+        invalid_call_errmask = geterrobj()[1]
+
+    return [bufsize, invalid_call_errmask, None]
+
+# Dealing with errors in _umath_linalg
+_linalg_error_extobj = _determine_error_states()
+del _determine_error_states
+
+def _raise_linalgerror_singular(err, flag):
+    raise LinAlgError("Singular matrix")
+
+def _raise_linalgerror_nonposdef(err, flag):
+    raise LinAlgError("Matrix is not positive definite")
+
+def _raise_linalgerror_eigenvalues_nonconvergence(err, flag):
+    raise LinAlgError("Eigenvalues did not converge")
+
+def _raise_linalgerror_svd_nonconvergence(err, flag):
+    raise LinAlgError("SVD did not converge")
+
+def _raise_linalgerror_lstsq(err, flag):
+    raise LinAlgError("SVD did not converge in Linear Least Squares")
+
+def _raise_linalgerror_qr(err, flag):
+    raise LinAlgError("Incorrect argument found while performing "
+                      "QR factorization")
+
+def get_linalg_error_extobj(callback):
+    extobj = list(_linalg_error_extobj)  # make a copy
+    extobj[2] = callback
+    return extobj
+
+def _makearray(a):
+    new = asarray(a)
+    wrap = getattr(a, "__array_prepare__", new.__array_wrap__)
+    return new, wrap
+
+def isComplexType(t):
+    return issubclass(t, complexfloating)
+
+_real_types_map = {single : single,
+                   double : double,
+                   csingle : single,
+                   cdouble : double}
+
+_complex_types_map = {single : csingle,
+                      double : cdouble,
+                      csingle : csingle,
+                      cdouble : cdouble}
+
+def _realType(t, default=double):
+    return _real_types_map.get(t, default)
+
+def _complexType(t, default=cdouble):
+    return _complex_types_map.get(t, default)
+
+def _commonType(*arrays):
+    # in lite version, use higher precision (always double or cdouble)
+    result_type = single
+    is_complex = False
+    for a in arrays:
+        type_ = a.dtype.type
+        if issubclass(type_, inexact):
+            if isComplexType(type_):
+                is_complex = True
+            rt = _realType(type_, default=None)
+            if rt is double:
+                result_type = double
+            elif rt is None:
+                # unsupported inexact scalar
+                raise TypeError("array type %s is unsupported in linalg" %
+                        (a.dtype.name,))
+        else:
+            result_type = double
+    if is_complex:
+        result_type = _complex_types_map[result_type]
+        return cdouble, result_type
+    else:
+        return double, result_type
+
+
+def _to_native_byte_order(*arrays):
+    ret = []
+    for arr in arrays:
+        if arr.dtype.byteorder not in ('=', '|'):
+            ret.append(asarray(arr, dtype=arr.dtype.newbyteorder('=')))
+        else:
+            ret.append(arr)
+    if len(ret) == 1:
+        return ret[0]
+    else:
+        return ret
+
+
+def _assert_2d(*arrays):
+    for a in arrays:
+        if a.ndim != 2:
+            raise LinAlgError('%d-dimensional array given. Array must be '
+                    'two-dimensional' % a.ndim)
+
+def _assert_stacked_2d(*arrays):
+    for a in arrays:
+        if a.ndim < 2:
+            raise LinAlgError('%d-dimensional array given. Array must be '
+                    'at least two-dimensional' % a.ndim)
+
+def _assert_stacked_square(*arrays):
+    for a in arrays:
+        m, n = a.shape[-2:]
+        if m != n:
+            raise LinAlgError('Last 2 dimensions of the array must be square')
+
+def _assert_finite(*arrays):
+    for a in arrays:
+        if not isfinite(a).all():
+            raise LinAlgError("Array must not contain infs or NaNs")
+
+def _is_empty_2d(arr):
+    # check size first for efficiency
+    return arr.size == 0 and prod(arr.shape[-2:]) == 0
+
+
+def transpose(a):
+    """
+    Transpose each matrix in a stack of matrices.
+
+    Unlike np.transpose, this only swaps the last two axes, rather than all of
+    them
+
+    Parameters
+    ----------
+    a : (...,M,N) array_like
+
+    Returns
+    -------
+    aT : (...,N,M) ndarray
+    """
+    return swapaxes(a, -1, -2)
+
+# Linear equations
+
+def _tensorsolve_dispatcher(a, b, axes=None):
+    return (a, b)
+
+
+@array_function_dispatch(_tensorsolve_dispatcher)
+def tensorsolve(a, b, axes=None):
+    """
+    Solve the tensor equation ``a x = b`` for x.
+
+    It is assumed that all indices of `x` are summed over in the product,
+    together with the rightmost indices of `a`, as is done in, for example,
+    ``tensordot(a, x, axes=x.ndim)``.
+
+    Parameters
+    ----------
+    a : array_like
+        Coefficient tensor, of shape ``b.shape + Q``. `Q`, a tuple, equals
+        the shape of that sub-tensor of `a` consisting of the appropriate
+        number of its rightmost indices, and must be such that
+        ``prod(Q) == prod(b.shape)`` (in which sense `a` is said to be
+        'square').
+    b : array_like
+        Right-hand tensor, which can be of any shape.
+    axes : tuple of ints, optional
+        Axes in `a` to reorder to the right, before inversion.
+        If None (default), no reordering is done.
+
+    Returns
+    -------
+    x : ndarray, shape Q
+
+    Raises
+    ------
+    LinAlgError
+        If `a` is singular or not 'square' (in the above sense).
+
+    See Also
+    --------
+    numpy.tensordot, tensorinv, numpy.einsum
+
+    Examples
+    --------
+    >>> a = np.eye(2*3*4)
+    >>> a.shape = (2*3, 4, 2, 3, 4)
+    >>> b = np.random.randn(2*3, 4)
+    >>> x = np.linalg.tensorsolve(a, b)
+    >>> x.shape
+    (2, 3, 4)
+    >>> np.allclose(np.tensordot(a, x, axes=3), b)
+    True
+
+    """
+    a, wrap = _makearray(a)
+    b = asarray(b)
+    an = a.ndim
+
+    if axes is not None:
+        allaxes = list(range(0, an))
+        for k in axes:
+            allaxes.remove(k)
+            allaxes.insert(an, k)
+        a = a.transpose(allaxes)
+
+    oldshape = a.shape[-(an-b.ndim):]
+    prod = 1
+    for k in oldshape:
+        prod *= k
+
+    if a.size != prod ** 2:
+        raise LinAlgError(
+            "Input arrays must satisfy the requirement \
+            prod(a.shape[b.ndim:]) == prod(a.shape[:b.ndim])"
+        )
+
+    a = a.reshape(prod, prod)
+    b = b.ravel()
+    res = wrap(solve(a, b))
+    res.shape = oldshape
+    return res
+
+
+def _solve_dispatcher(a, b):
+    return (a, b)
+
+
+@array_function_dispatch(_solve_dispatcher)
+def solve(a, b):
+    """
+    Solve a linear matrix equation, or system of linear scalar equations.
+
+    Computes the "exact" solution, `x`, of the well-determined, i.e., full
+    rank, linear matrix equation `ax = b`.
+
+    Parameters
+    ----------
+    a : (..., M, M) array_like
+        Coefficient matrix.
+    b : {(..., M,), (..., M, K)}, array_like
+        Ordinate or "dependent variable" values.
+
+    Returns
+    -------
+    x : {(..., M,), (..., M, K)} ndarray
+        Solution to the system a x = b.  Returned shape is identical to `b`.
+
+    Raises
+    ------
+    LinAlgError
+        If `a` is singular or not square.
+
+    See Also
+    --------
+    scipy.linalg.solve : Similar function in SciPy.
+
+    Notes
+    -----
+
+    .. versionadded:: 1.8.0
+
+    Broadcasting rules apply, see the `numpy.linalg` documentation for
+    details.
+
+    The solutions are computed using LAPACK routine ``_gesv``.
+
+    `a` must be square and of full-rank, i.e., all rows (or, equivalently,
+    columns) must be linearly independent; if either is not true, use
+    `lstsq` for the least-squares best "solution" of the
+    system/equation.
+
+    References
+    ----------
+    .. [1] G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando,
+           FL, Academic Press, Inc., 1980, pg. 22.
+
+    Examples
+    --------
+    Solve the system of equations ``x0 + 2 * x1 = 1`` and ``3 * x0 + 5 * x1 = 2``:
+
+    >>> a = np.array([[1, 2], [3, 5]])
+    >>> b = np.array([1, 2])
+    >>> x = np.linalg.solve(a, b)
+    >>> x
+    array([-1.,  1.])
+
+    Check that the solution is correct:
+
+    >>> np.allclose(np.dot(a, x), b)
+    True
+
+    """
+    a, _ = _makearray(a)
+    _assert_stacked_2d(a)
+    _assert_stacked_square(a)
+    b, wrap = _makearray(b)
+    t, result_t = _commonType(a, b)
+
+    # We use the b = (..., M,) logic, only if the number of extra dimensions
+    # match exactly
+    if b.ndim == a.ndim - 1:
+        gufunc = _umath_linalg.solve1
+    else:
+        gufunc = _umath_linalg.solve
+
+    signature = 'DD->D' if isComplexType(t) else 'dd->d'
+    extobj = get_linalg_error_extobj(_raise_linalgerror_singular)
+    r = gufunc(a, b, signature=signature, extobj=extobj)
+
+    return wrap(r.astype(result_t, copy=False))
+
+
+def _tensorinv_dispatcher(a, ind=None):
+    return (a,)
+
+
+@array_function_dispatch(_tensorinv_dispatcher)
+def tensorinv(a, ind=2):
+    """
+    Compute the 'inverse' of an N-dimensional array.
+
+    The result is an inverse for `a` relative to the tensordot operation
+    ``tensordot(a, b, ind)``, i. e., up to floating-point accuracy,
+    ``tensordot(tensorinv(a), a, ind)`` is the "identity" tensor for the
+    tensordot operation.
+
+    Parameters
+    ----------
+    a : array_like
+        Tensor to 'invert'. Its shape must be 'square', i. e.,
+        ``prod(a.shape[:ind]) == prod(a.shape[ind:])``.
+    ind : int, optional
+        Number of first indices that are involved in the inverse sum.
+        Must be a positive integer, default is 2.
+
+    Returns
+    -------
+    b : ndarray
+        `a`'s tensordot inverse, shape ``a.shape[ind:] + a.shape[:ind]``.
+
+    Raises
+    ------
+    LinAlgError
+        If `a` is singular or not 'square' (in the above sense).
+
+    See Also
+    --------
+    numpy.tensordot, tensorsolve
+
+    Examples
+    --------
+    >>> a = np.eye(4*6)
+    >>> a.shape = (4, 6, 8, 3)
+    >>> ainv = np.linalg.tensorinv(a, ind=2)
+    >>> ainv.shape
+    (8, 3, 4, 6)
+    >>> b = np.random.randn(4, 6)
+    >>> np.allclose(np.tensordot(ainv, b), np.linalg.tensorsolve(a, b))
+    True
+
+    >>> a = np.eye(4*6)
+    >>> a.shape = (24, 8, 3)
+    >>> ainv = np.linalg.tensorinv(a, ind=1)
+    >>> ainv.shape
+    (8, 3, 24)
+    >>> b = np.random.randn(24)
+    >>> np.allclose(np.tensordot(ainv, b, 1), np.linalg.tensorsolve(a, b))
+    True
+
+    """
+    a = asarray(a)
+    oldshape = a.shape
+    prod = 1
+    if ind > 0:
+        invshape = oldshape[ind:] + oldshape[:ind]
+        for k in oldshape[ind:]:
+            prod *= k
+    else:
+        raise ValueError("Invalid ind argument.")
+    a = a.reshape(prod, -1)
+    ia = inv(a)
+    return ia.reshape(*invshape)
+
+
+# Matrix inversion
+
+def _unary_dispatcher(a):
+    return (a,)
+
+
+@array_function_dispatch(_unary_dispatcher)
+def inv(a):
+    """
+    Compute the (multiplicative) inverse of a matrix.
+
+    Given a square matrix `a`, return the matrix `ainv` satisfying
+    ``dot(a, ainv) = dot(ainv, a) = eye(a.shape[0])``.
+
+    Parameters
+    ----------
+    a : (..., M, M) array_like
+        Matrix to be inverted.
+
+    Returns
+    -------
+    ainv : (..., M, M) ndarray or matrix
+        (Multiplicative) inverse of the matrix `a`.
+
+    Raises
+    ------
+    LinAlgError
+        If `a` is not square or inversion fails.
+
+    See Also
+    --------
+    scipy.linalg.inv : Similar function in SciPy.
+
+    Notes
+    -----
+
+    .. versionadded:: 1.8.0
+
+    Broadcasting rules apply, see the `numpy.linalg` documentation for
+    details.
+
+    Examples
+    --------
+    >>> from numpy.linalg import inv
+    >>> a = np.array([[1., 2.], [3., 4.]])
+    >>> ainv = inv(a)
+    >>> np.allclose(np.dot(a, ainv), np.eye(2))
+    True
+    >>> np.allclose(np.dot(ainv, a), np.eye(2))
+    True
+
+    If a is a matrix object, then the return value is a matrix as well:
+
+    >>> ainv = inv(np.matrix(a))
+    >>> ainv
+    matrix([[-2. ,  1. ],
+            [ 1.5, -0.5]])
+
+    Inverses of several matrices can be computed at once:
+
+    >>> a = np.array([[[1., 2.], [3., 4.]], [[1, 3], [3, 5]]])
+    >>> inv(a)
+    array([[[-2.  ,  1.  ],
+            [ 1.5 , -0.5 ]],
+           [[-1.25,  0.75],
+            [ 0.75, -0.25]]])
+
+    """
+    a, wrap = _makearray(a)
+    _assert_stacked_2d(a)
+    _assert_stacked_square(a)
+    t, result_t = _commonType(a)
+
+    signature = 'D->D' if isComplexType(t) else 'd->d'
+    extobj = get_linalg_error_extobj(_raise_linalgerror_singular)
+    ainv = _umath_linalg.inv(a, signature=signature, extobj=extobj)
+    return wrap(ainv.astype(result_t, copy=False))
+
+
+def _matrix_power_dispatcher(a, n):
+    return (a,)
+
+
+@array_function_dispatch(_matrix_power_dispatcher)
+def matrix_power(a, n):
+    """
+    Raise a square matrix to the (integer) power `n`.
+
+    For positive integers `n`, the power is computed by repeated matrix
+    squarings and matrix multiplications. If ``n == 0``, the identity matrix
+    of the same shape as M is returned. If ``n < 0``, the inverse
+    is computed and then raised to the ``abs(n)``.
+
+    .. note:: Stacks of object matrices are not currently supported.
+
+    Parameters
+    ----------
+    a : (..., M, M) array_like
+        Matrix to be "powered".
+    n : int
+        The exponent can be any integer or long integer, positive,
+        negative, or zero.
+
+    Returns
+    -------
+    a**n : (..., M, M) ndarray or matrix object
+        The return value is the same shape and type as `M`;
+        if the exponent is positive or zero then the type of the
+        elements is the same as those of `M`. If the exponent is
+        negative the elements are floating-point.
+
+    Raises
+    ------
+    LinAlgError
+        For matrices that are not square or that (for negative powers) cannot
+        be inverted numerically.
+
+    Examples
+    --------
+    >>> from numpy.linalg import matrix_power
+    >>> i = np.array([[0, 1], [-1, 0]]) # matrix equiv. of the imaginary unit
+    >>> matrix_power(i, 3) # should = -i
+    array([[ 0, -1],
+           [ 1,  0]])
+    >>> matrix_power(i, 0)
+    array([[1, 0],
+           [0, 1]])
+    >>> matrix_power(i, -3) # should = 1/(-i) = i, but w/ f.p. elements
+    array([[ 0.,  1.],
+           [-1.,  0.]])
+
+    Somewhat more sophisticated example
+
+    >>> q = np.zeros((4, 4))
+    >>> q[0:2, 0:2] = -i
+    >>> q[2:4, 2:4] = i
+    >>> q # one of the three quaternion units not equal to 1
+    array([[ 0., -1.,  0.,  0.],
+           [ 1.,  0.,  0.,  0.],
+           [ 0.,  0.,  0.,  1.],
+           [ 0.,  0., -1.,  0.]])
+    >>> matrix_power(q, 2) # = -np.eye(4)
+    array([[-1.,  0.,  0.,  0.],
+           [ 0., -1.,  0.,  0.],
+           [ 0.,  0., -1.,  0.],
+           [ 0.,  0.,  0., -1.]])
+
+    """
+    a = asanyarray(a)
+    _assert_stacked_2d(a)
+    _assert_stacked_square(a)
+
+    try:
+        n = operator.index(n)
+    except TypeError as e:
+        raise TypeError("exponent must be an integer") from e
+
+    # Fall back on dot for object arrays. Object arrays are not supported by
+    # the current implementation of matmul using einsum
+    if a.dtype != object:
+        fmatmul = matmul
+    elif a.ndim == 2:
+        fmatmul = dot
+    else:
+        raise NotImplementedError(
+            "matrix_power not supported for stacks of object arrays")
+
+    if n == 0:
+        a = empty_like(a)
+        a[...] = eye(a.shape[-2], dtype=a.dtype)
+        return a
+
+    elif n < 0:
+        a = inv(a)
+        n = abs(n)
+
+    # short-cuts.
+    if n == 1:
+        return a
+
+    elif n == 2:
+        return fmatmul(a, a)
+
+    elif n == 3:
+        return fmatmul(fmatmul(a, a), a)
+
+    # Use binary decomposition to reduce the number of matrix multiplications.
+    # Here, we iterate over the bits of n, from LSB to MSB, raise `a` to
+    # increasing powers of 2, and multiply into the result as needed.
+    z = result = None
+    while n > 0:
+        z = a if z is None else fmatmul(z, z)
+        n, bit = divmod(n, 2)
+        if bit:
+            result = z if result is None else fmatmul(result, z)
+
+    return result
+
+
+# Cholesky decomposition
+
+
+@array_function_dispatch(_unary_dispatcher)
+def cholesky(a):
+    """
+    Cholesky decomposition.
+
+    Return the Cholesky decomposition, `L * L.H`, of the square matrix `a`,
+    where `L` is lower-triangular and .H is the conjugate transpose operator
+    (which is the ordinary transpose if `a` is real-valued).  `a` must be
+    Hermitian (symmetric if real-valued) and positive-definite. No
+    checking is performed to verify whether `a` is Hermitian or not.
+    In addition, only the lower-triangular and diagonal elements of `a`
+    are used. Only `L` is actually returned.
+
+    Parameters
+    ----------
+    a : (..., M, M) array_like
+        Hermitian (symmetric if all elements are real), positive-definite
+        input matrix.
+
+    Returns
+    -------
+    L : (..., M, M) array_like
+        Lower-triangular Cholesky factor of `a`.  Returns a matrix object if
+        `a` is a matrix object.
+
+    Raises
+    ------
+    LinAlgError
+       If the decomposition fails, for example, if `a` is not
+       positive-definite.
+
+    See Also
+    --------
+    scipy.linalg.cholesky : Similar function in SciPy.
+    scipy.linalg.cholesky_banded : Cholesky decompose a banded Hermitian
+                                   positive-definite matrix.
+    scipy.linalg.cho_factor : Cholesky decomposition of a matrix, to use in
+                              `scipy.linalg.cho_solve`.
+
+    Notes
+    -----
+
+    .. versionadded:: 1.8.0
+
+    Broadcasting rules apply, see the `numpy.linalg` documentation for
+    details.
+
+    The Cholesky decomposition is often used as a fast way of solving
+
+    .. math:: A \\mathbf{x} = \\mathbf{b}
+
+    (when `A` is both Hermitian/symmetric and positive-definite).
+
+    First, we solve for :math:`\\mathbf{y}` in
+
+    .. math:: L \\mathbf{y} = \\mathbf{b},
+
+    and then for :math:`\\mathbf{x}` in
+
+    .. math:: L.H \\mathbf{x} = \\mathbf{y}.
+
+    Examples
+    --------
+    >>> A = np.array([[1,-2j],[2j,5]])
+    >>> A
+    array([[ 1.+0.j, -0.-2.j],
+           [ 0.+2.j,  5.+0.j]])
+    >>> L = np.linalg.cholesky(A)
+    >>> L
+    array([[1.+0.j, 0.+0.j],
+           [0.+2.j, 1.+0.j]])
+    >>> np.dot(L, L.T.conj()) # verify that L * L.H = A
+    array([[1.+0.j, 0.-2.j],
+           [0.+2.j, 5.+0.j]])
+    >>> A = [[1,-2j],[2j,5]] # what happens if A is only array_like?
+    >>> np.linalg.cholesky(A) # an ndarray object is returned
+    array([[1.+0.j, 0.+0.j],
+           [0.+2.j, 1.+0.j]])
+    >>> # But a matrix object is returned if A is a matrix object
+    >>> np.linalg.cholesky(np.matrix(A))
+    matrix([[ 1.+0.j,  0.+0.j],
+            [ 0.+2.j,  1.+0.j]])
+
+    """
+    extobj = get_linalg_error_extobj(_raise_linalgerror_nonposdef)
+    gufunc = _umath_linalg.cholesky_lo
+    a, wrap = _makearray(a)
+    _assert_stacked_2d(a)
+    _assert_stacked_square(a)
+    t, result_t = _commonType(a)
+    signature = 'D->D' if isComplexType(t) else 'd->d'
+    r = gufunc(a, signature=signature, extobj=extobj)
+    return wrap(r.astype(result_t, copy=False))
+
+
+# QR decomposition
+
+def _qr_dispatcher(a, mode=None):
+    return (a,)
+
+
+@array_function_dispatch(_qr_dispatcher)
+def qr(a, mode='reduced'):
+    """
+    Compute the qr factorization of a matrix.
+
+    Factor the matrix `a` as *qr*, where `q` is orthonormal and `r` is
+    upper-triangular.
+
+    Parameters
+    ----------
+    a : array_like, shape (..., M, N)
+        An array-like object with the dimensionality of at least 2.
+    mode : {'reduced', 'complete', 'r', 'raw'}, optional
+        If K = min(M, N), then
+
+        * 'reduced'  : returns Q, R with dimensions (..., M, K), (..., K, N) (default)
+        * 'complete' : returns Q, R with dimensions (..., M, M), (..., M, N)
+        * 'r'        : returns R only with dimensions (..., K, N)
+        * 'raw'      : returns h, tau with dimensions (..., N, M), (..., K,)
+
+        The options 'reduced', 'complete, and 'raw' are new in numpy 1.8,
+        see the notes for more information. The default is 'reduced', and to
+        maintain backward compatibility with earlier versions of numpy both
+        it and the old default 'full' can be omitted. Note that array h
+        returned in 'raw' mode is transposed for calling Fortran. The
+        'economic' mode is deprecated.  The modes 'full' and 'economic' may
+        be passed using only the first letter for backwards compatibility,
+        but all others must be spelled out. See the Notes for more
+        explanation.
+
+
+    Returns
+    -------
+    When mode is 'reduced' or 'complete', the result will be a namedtuple with
+    the attributes `Q` and `R`.
+
+    Q : ndarray of float or complex, optional
+        A matrix with orthonormal columns. When mode = 'complete' the
+        result is an orthogonal/unitary matrix depending on whether or not
+        a is real/complex. The determinant may be either +/- 1 in that
+        case. In case the number of dimensions in the input array is
+        greater than 2 then a stack of the matrices with above properties
+        is returned.
+    R : ndarray of float or complex, optional
+        The upper-triangular matrix or a stack of upper-triangular
+        matrices if the number of dimensions in the input array is greater
+        than 2.
+    (h, tau) : ndarrays of np.double or np.cdouble, optional
+        The array h contains the Householder reflectors that generate q
+        along with r. The tau array contains scaling factors for the
+        reflectors. In the deprecated  'economic' mode only h is returned.
+
+    Raises
+    ------
+    LinAlgError
+        If factoring fails.
+
+    See Also
+    --------
+    scipy.linalg.qr : Similar function in SciPy.
+    scipy.linalg.rq : Compute RQ decomposition of a matrix.
+
+    Notes
+    -----
+    This is an interface to the LAPACK routines ``dgeqrf``, ``zgeqrf``,
+    ``dorgqr``, and ``zungqr``.
+
+    For more information on the qr factorization, see for example:
+    https://en.wikipedia.org/wiki/QR_factorization
+
+    Subclasses of `ndarray` are preserved except for the 'raw' mode. So if
+    `a` is of type `matrix`, all the return values will be matrices too.
+
+    New 'reduced', 'complete', and 'raw' options for mode were added in
+    NumPy 1.8.0 and the old option 'full' was made an alias of 'reduced'.  In
+    addition the options 'full' and 'economic' were deprecated.  Because
+    'full' was the previous default and 'reduced' is the new default,
+    backward compatibility can be maintained by letting `mode` default.
+    The 'raw' option was added so that LAPACK routines that can multiply
+    arrays by q using the Householder reflectors can be used. Note that in
+    this case the returned arrays are of type np.double or np.cdouble and
+    the h array is transposed to be FORTRAN compatible.  No routines using
+    the 'raw' return are currently exposed by numpy, but some are available
+    in lapack_lite and just await the necessary work.
+
+    Examples
+    --------
+    >>> a = np.random.randn(9, 6)
+    >>> Q, R = np.linalg.qr(a)
+    >>> np.allclose(a, np.dot(Q, R))  # a does equal QR
+    True
+    >>> R2 = np.linalg.qr(a, mode='r')
+    >>> np.allclose(R, R2)  # mode='r' returns the same R as mode='full'
+    True
+    >>> a = np.random.normal(size=(3, 2, 2)) # Stack of 2 x 2 matrices as input
+    >>> Q, R = np.linalg.qr(a)
+    >>> Q.shape
+    (3, 2, 2)
+    >>> R.shape
+    (3, 2, 2)
+    >>> np.allclose(a, np.matmul(Q, R))
+    True
+
+    Example illustrating a common use of `qr`: solving of least squares
+    problems
+
+    What are the least-squares-best `m` and `y0` in ``y = y0 + mx`` for
+    the following data: {(0,1), (1,0), (1,2), (2,1)}. (Graph the points
+    and you'll see that it should be y0 = 0, m = 1.)  The answer is provided
+    by solving the over-determined matrix equation ``Ax = b``, where::
+
+      A = array([[0, 1], [1, 1], [1, 1], [2, 1]])
+      x = array([[y0], [m]])
+      b = array([[1], [0], [2], [1]])
+
+    If A = QR such that Q is orthonormal (which is always possible via
+    Gram-Schmidt), then ``x = inv(R) * (Q.T) * b``.  (In numpy practice,
+    however, we simply use `lstsq`.)
+
+    >>> A = np.array([[0, 1], [1, 1], [1, 1], [2, 1]])
+    >>> A
+    array([[0, 1],
+           [1, 1],
+           [1, 1],
+           [2, 1]])
+    >>> b = np.array([1, 2, 2, 3])
+    >>> Q, R = np.linalg.qr(A)
+    >>> p = np.dot(Q.T, b)
+    >>> np.dot(np.linalg.inv(R), p)
+    array([  1.,   1.])
+
+    """
+    if mode not in ('reduced', 'complete', 'r', 'raw'):
+        if mode in ('f', 'full'):
+            # 2013-04-01, 1.8
+            msg = "".join((
+                    "The 'full' option is deprecated in favor of 'reduced'.\n",
+                    "For backward compatibility let mode default."))
+            warnings.warn(msg, DeprecationWarning, stacklevel=2)
+            mode = 'reduced'
+        elif mode in ('e', 'economic'):
+            # 2013-04-01, 1.8
+            msg = "The 'economic' option is deprecated."
+            warnings.warn(msg, DeprecationWarning, stacklevel=2)
+            mode = 'economic'
+        else:
+            raise ValueError(f"Unrecognized mode '{mode}'")
+
+    a, wrap = _makearray(a)
+    _assert_stacked_2d(a)
+    m, n = a.shape[-2:]
+    t, result_t = _commonType(a)
+    a = a.astype(t, copy=True)
+    a = _to_native_byte_order(a)
+    mn = min(m, n)
+
+    if m <= n:
+        gufunc = _umath_linalg.qr_r_raw_m
+    else:
+        gufunc = _umath_linalg.qr_r_raw_n
+
+    signature = 'D->D' if isComplexType(t) else 'd->d'
+    extobj = get_linalg_error_extobj(_raise_linalgerror_qr)
+    tau = gufunc(a, signature=signature, extobj=extobj)
+
+    # handle modes that don't return q
+    if mode == 'r':
+        r = triu(a[..., :mn, :])
+        r = r.astype(result_t, copy=False)
+        return wrap(r)
+
+    if mode == 'raw':
+        q = transpose(a)
+        q = q.astype(result_t, copy=False)
+        tau = tau.astype(result_t, copy=False)
+        return wrap(q), tau
+
+    if mode == 'economic':
+        a = a.astype(result_t, copy=False)
+        return wrap(a)
+
+    # mc is the number of columns in the resulting q
+    # matrix. If the mode is complete then it is
+    # same as number of rows, and if the mode is reduced,
+    # then it is the minimum of number of rows and columns.
+    if mode == 'complete' and m > n:
+        mc = m
+        gufunc = _umath_linalg.qr_complete
+    else:
+        mc = mn
+        gufunc = _umath_linalg.qr_reduced
+
+    signature = 'DD->D' if isComplexType(t) else 'dd->d'
+    extobj = get_linalg_error_extobj(_raise_linalgerror_qr)
+    q = gufunc(a, tau, signature=signature, extobj=extobj)
+    r = triu(a[..., :mc, :])
+
+    q = q.astype(result_t, copy=False)
+    r = r.astype(result_t, copy=False)
+
+    return QRResult(wrap(q), wrap(r))
+
+# Eigenvalues
+
+
+@array_function_dispatch(_unary_dispatcher)
+def eigvals(a):
+    """
+    Compute the eigenvalues of a general matrix.
+
+    Main difference between `eigvals` and `eig`: the eigenvectors aren't
+    returned.
+
+    Parameters
+    ----------
+    a : (..., M, M) array_like
+        A complex- or real-valued matrix whose eigenvalues will be computed.
+
+    Returns
+    -------
+    w : (..., M,) ndarray
+        The eigenvalues, each repeated according to its multiplicity.
+        They are not necessarily ordered, nor are they necessarily
+        real for real matrices.
+
+    Raises
+    ------
+    LinAlgError
+        If the eigenvalue computation does not converge.
+
+    See Also
+    --------
+    eig : eigenvalues and right eigenvectors of general arrays
+    eigvalsh : eigenvalues of real symmetric or complex Hermitian
+               (conjugate symmetric) arrays.
+    eigh : eigenvalues and eigenvectors of real symmetric or complex
+           Hermitian (conjugate symmetric) arrays.
+    scipy.linalg.eigvals : Similar function in SciPy.
+
+    Notes
+    -----
+
+    .. versionadded:: 1.8.0
+
+    Broadcasting rules apply, see the `numpy.linalg` documentation for
+    details.
+
+    This is implemented using the ``_geev`` LAPACK routines which compute
+    the eigenvalues and eigenvectors of general square arrays.
+
+    Examples
+    --------
+    Illustration, using the fact that the eigenvalues of a diagonal matrix
+    are its diagonal elements, that multiplying a matrix on the left
+    by an orthogonal matrix, `Q`, and on the right by `Q.T` (the transpose
+    of `Q`), preserves the eigenvalues of the "middle" matrix.  In other words,
+    if `Q` is orthogonal, then ``Q * A * Q.T`` has the same eigenvalues as
+    ``A``:
+
+    >>> from numpy import linalg as LA
+    >>> x = np.random.random()
+    >>> Q = np.array([[np.cos(x), -np.sin(x)], [np.sin(x), np.cos(x)]])
+    >>> LA.norm(Q[0, :]), LA.norm(Q[1, :]), np.dot(Q[0, :],Q[1, :])
+    (1.0, 1.0, 0.0)
+
+    Now multiply a diagonal matrix by ``Q`` on one side and by ``Q.T`` on the other:
+
+    >>> D = np.diag((-1,1))
+    >>> LA.eigvals(D)
+    array([-1.,  1.])
+    >>> A = np.dot(Q, D)
+    >>> A = np.dot(A, Q.T)
+    >>> LA.eigvals(A)
+    array([ 1., -1.]) # random
+
+    """
+    a, wrap = _makearray(a)
+    _assert_stacked_2d(a)
+    _assert_stacked_square(a)
+    _assert_finite(a)
+    t, result_t = _commonType(a)
+
+    extobj = get_linalg_error_extobj(
+        _raise_linalgerror_eigenvalues_nonconvergence)
+    signature = 'D->D' if isComplexType(t) else 'd->D'
+    w = _umath_linalg.eigvals(a, signature=signature, extobj=extobj)
+
+    if not isComplexType(t):
+        if all(w.imag == 0):
+            w = w.real
+            result_t = _realType(result_t)
+        else:
+            result_t = _complexType(result_t)
+
+    return w.astype(result_t, copy=False)
+
+
+def _eigvalsh_dispatcher(a, UPLO=None):
+    return (a,)
+
+
+@array_function_dispatch(_eigvalsh_dispatcher)
+def eigvalsh(a, UPLO='L'):
+    """
+    Compute the eigenvalues of a complex Hermitian or real symmetric matrix.
+
+    Main difference from eigh: the eigenvectors are not computed.
+
+    Parameters
+    ----------
+    a : (..., M, M) array_like
+        A complex- or real-valued matrix whose eigenvalues are to be
+        computed.
+    UPLO : {'L', 'U'}, optional
+        Specifies whether the calculation is done with the lower triangular
+        part of `a` ('L', default) or the upper triangular part ('U').
+        Irrespective of this value only the real parts of the diagonal will
+        be considered in the computation to preserve the notion of a Hermitian
+        matrix. It therefore follows that the imaginary part of the diagonal
+        will always be treated as zero.
+
+    Returns
+    -------
+    w : (..., M,) ndarray
+        The eigenvalues in ascending order, each repeated according to
+        its multiplicity.
+
+    Raises
+    ------
+    LinAlgError
+        If the eigenvalue computation does not converge.
+
+    See Also
+    --------
+    eigh : eigenvalues and eigenvectors of real symmetric or complex Hermitian
+           (conjugate symmetric) arrays.
+    eigvals : eigenvalues of general real or complex arrays.
+    eig : eigenvalues and right eigenvectors of general real or complex
+          arrays.
+    scipy.linalg.eigvalsh : Similar function in SciPy.
+
+    Notes
+    -----
+
+    .. versionadded:: 1.8.0
+
+    Broadcasting rules apply, see the `numpy.linalg` documentation for
+    details.
+
+    The eigenvalues are computed using LAPACK routines ``_syevd``, ``_heevd``.
+
+    Examples
+    --------
+    >>> from numpy import linalg as LA
+    >>> a = np.array([[1, -2j], [2j, 5]])
+    >>> LA.eigvalsh(a)
+    array([ 0.17157288,  5.82842712]) # may vary
+
+    >>> # demonstrate the treatment of the imaginary part of the diagonal
+    >>> a = np.array([[5+2j, 9-2j], [0+2j, 2-1j]])
+    >>> a
+    array([[5.+2.j, 9.-2.j],
+           [0.+2.j, 2.-1.j]])
+    >>> # with UPLO='L' this is numerically equivalent to using LA.eigvals()
+    >>> # with:
+    >>> b = np.array([[5.+0.j, 0.-2.j], [0.+2.j, 2.-0.j]])
+    >>> b
+    array([[5.+0.j, 0.-2.j],
+           [0.+2.j, 2.+0.j]])
+    >>> wa = LA.eigvalsh(a)
+    >>> wb = LA.eigvals(b)
+    >>> wa; wb
+    array([1., 6.])
+    array([6.+0.j, 1.+0.j])
+
+    """
+    UPLO = UPLO.upper()
+    if UPLO not in ('L', 'U'):
+        raise ValueError("UPLO argument must be 'L' or 'U'")
+
+    extobj = get_linalg_error_extobj(
+        _raise_linalgerror_eigenvalues_nonconvergence)
+    if UPLO == 'L':
+        gufunc = _umath_linalg.eigvalsh_lo
+    else:
+        gufunc = _umath_linalg.eigvalsh_up
+
+    a, wrap = _makearray(a)
+    _assert_stacked_2d(a)
+    _assert_stacked_square(a)
+    t, result_t = _commonType(a)
+    signature = 'D->d' if isComplexType(t) else 'd->d'
+    w = gufunc(a, signature=signature, extobj=extobj)
+    return w.astype(_realType(result_t), copy=False)
+
+def _convertarray(a):
+    t, result_t = _commonType(a)
+    a = a.astype(t).T.copy()
+    return a, t, result_t
+
+
+# Eigenvectors
+
+
+@array_function_dispatch(_unary_dispatcher)
+def eig(a):
+    """
+    Compute the eigenvalues and right eigenvectors of a square array.
+
+    Parameters
+    ----------
+    a : (..., M, M) array
+        Matrices for which the eigenvalues and right eigenvectors will
+        be computed
+
+    Returns
+    -------
+    A namedtuple with the following attributes:
+
+    eigenvalues : (..., M) array
+        The eigenvalues, each repeated according to its multiplicity.
+        The eigenvalues are not necessarily ordered. The resulting
+        array will be of complex type, unless the imaginary part is
+        zero in which case it will be cast to a real type. When `a`
+        is real the resulting eigenvalues will be real (0 imaginary
+        part) or occur in conjugate pairs
+
+    eigenvectors : (..., M, M) array
+        The normalized (unit "length") eigenvectors, such that the
+        column ``eigenvectors[:,i]`` is the eigenvector corresponding to the
+        eigenvalue ``eigenvalues[i]``.
+
+    Raises
+    ------
+    LinAlgError
+        If the eigenvalue computation does not converge.
+
+    See Also
+    --------
+    eigvals : eigenvalues of a non-symmetric array.
+    eigh : eigenvalues and eigenvectors of a real symmetric or complex
+           Hermitian (conjugate symmetric) array.
+    eigvalsh : eigenvalues of a real symmetric or complex Hermitian
+               (conjugate symmetric) array.
+    scipy.linalg.eig : Similar function in SciPy that also solves the
+                       generalized eigenvalue problem.
+    scipy.linalg.schur : Best choice for unitary and other non-Hermitian
+                         normal matrices.
+
+    Notes
+    -----
+
+    .. versionadded:: 1.8.0
+
+    Broadcasting rules apply, see the `numpy.linalg` documentation for
+    details.
+
+    This is implemented using the ``_geev`` LAPACK routines which compute
+    the eigenvalues and eigenvectors of general square arrays.
+
+    The number `w` is an eigenvalue of `a` if there exists a vector `v` such
+    that ``a @ v = w * v``. Thus, the arrays `a`, `eigenvalues`, and
+    `eigenvectors` satisfy the equations ``a @ eigenvectors[:,i] =
+    eigenvalues[i] * eigenvalues[:,i]`` for :math:`i \\in \\{0,...,M-1\\}`.
+
+    The array `eigenvectors` may not be of maximum rank, that is, some of the
+    columns may be linearly dependent, although round-off error may obscure
+    that fact. If the eigenvalues are all different, then theoretically the
+    eigenvectors are linearly independent and `a` can be diagonalized by a
+    similarity transformation using `eigenvectors`, i.e, ``inv(eigenvectors) @
+    a @ eigenvectors`` is diagonal.
+
+    For non-Hermitian normal matrices the SciPy function `scipy.linalg.schur`
+    is preferred because the matrix `eigenvectors` is guaranteed to be
+    unitary, which is not the case when using `eig`. The Schur factorization
+    produces an upper triangular matrix rather than a diagonal matrix, but for
+    normal matrices only the diagonal of the upper triangular matrix is
+    needed, the rest is roundoff error.
+
+    Finally, it is emphasized that `eigenvectors` consists of the *right* (as
+    in right-hand side) eigenvectors of `a`. A vector `y` satisfying ``y.T @ a
+    = z * y.T`` for some number `z` is called a *left* eigenvector of `a`,
+    and, in general, the left and right eigenvectors of a matrix are not
+    necessarily the (perhaps conjugate) transposes of each other.
+
+    References
+    ----------
+    G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando, FL,
+    Academic Press, Inc., 1980, Various pp.
+
+    Examples
+    --------
+    >>> from numpy import linalg as LA
+
+    (Almost) trivial example with real eigenvalues and eigenvectors.
+
+    >>> eigenvalues, eigenvectors = LA.eig(np.diag((1, 2, 3)))
+    >>> eigenvalues
+    array([1., 2., 3.])
+    >>> eigenvectors
+    array([[1., 0., 0.],
+           [0., 1., 0.],
+           [0., 0., 1.]])
+
+    Real matrix possessing complex eigenvalues and eigenvectors; note that the
+    eigenvalues are complex conjugates of each other.
+
+    >>> eigenvalues, eigenvectors = LA.eig(np.array([[1, -1], [1, 1]]))
+    >>> eigenvalues
+    array([1.+1.j, 1.-1.j])
+    >>> eigenvectors
+    array([[0.70710678+0.j        , 0.70710678-0.j        ],
+           [0.        -0.70710678j, 0.        +0.70710678j]])
+
+    Complex-valued matrix with real eigenvalues (but complex-valued eigenvectors);
+    note that ``a.conj().T == a``, i.e., `a` is Hermitian.
+
+    >>> a = np.array([[1, 1j], [-1j, 1]])
+    >>> eigenvalues, eigenvectors = LA.eig(a)
+    >>> eigenvalues
+    array([2.+0.j, 0.+0.j])
+    >>> eigenvectors
+    array([[ 0.        +0.70710678j,  0.70710678+0.j        ], # may vary
+           [ 0.70710678+0.j        , -0.        +0.70710678j]])
+
+    Be careful about round-off error!
+
+    >>> a = np.array([[1 + 1e-9, 0], [0, 1 - 1e-9]])
+    >>> # Theor. eigenvalues are 1 +/- 1e-9
+    >>> eigenvalues, eigenvectors = LA.eig(a)
+    >>> eigenvalues
+    array([1., 1.])
+    >>> eigenvectors
+    array([[1., 0.],
+           [0., 1.]])
+
+    """
+    a, wrap = _makearray(a)
+    _assert_stacked_2d(a)
+    _assert_stacked_square(a)
+    _assert_finite(a)
+    t, result_t = _commonType(a)
+
+    extobj = get_linalg_error_extobj(
+        _raise_linalgerror_eigenvalues_nonconvergence)
+    signature = 'D->DD' if isComplexType(t) else 'd->DD'
+    w, vt = _umath_linalg.eig(a, signature=signature, extobj=extobj)
+
+    if not isComplexType(t) and all(w.imag == 0.0):
+        w = w.real
+        vt = vt.real
+        result_t = _realType(result_t)
+    else:
+        result_t = _complexType(result_t)
+
+    vt = vt.astype(result_t, copy=False)
+    return EigResult(w.astype(result_t, copy=False), wrap(vt))
+
+
+@array_function_dispatch(_eigvalsh_dispatcher)
+def eigh(a, UPLO='L'):
+    """
+    Return the eigenvalues and eigenvectors of a complex Hermitian
+    (conjugate symmetric) or a real symmetric matrix.
+
+    Returns two objects, a 1-D array containing the eigenvalues of `a`, and
+    a 2-D square array or matrix (depending on the input type) of the
+    corresponding eigenvectors (in columns).
+
+    Parameters
+    ----------
+    a : (..., M, M) array
+        Hermitian or real symmetric matrices whose eigenvalues and
+        eigenvectors are to be computed.
+    UPLO : {'L', 'U'}, optional
+        Specifies whether the calculation is done with the lower triangular
+        part of `a` ('L', default) or the upper triangular part ('U').
+        Irrespective of this value only the real parts of the diagonal will
+        be considered in the computation to preserve the notion of a Hermitian
+        matrix. It therefore follows that the imaginary part of the diagonal
+        will always be treated as zero.
+
+    Returns
+    -------
+    A namedtuple with the following attributes:
+
+    eigenvalues : (..., M) ndarray
+        The eigenvalues in ascending order, each repeated according to
+        its multiplicity.
+    eigenvectors : {(..., M, M) ndarray, (..., M, M) matrix}
+        The column ``eigenvectors[:, i]`` is the normalized eigenvector
+        corresponding to the eigenvalue ``eigenvalues[i]``.  Will return a
+        matrix object if `a` is a matrix object.
+
+    Raises
+    ------
+    LinAlgError
+        If the eigenvalue computation does not converge.
+
+    See Also
+    --------
+    eigvalsh : eigenvalues of real symmetric or complex Hermitian
+               (conjugate symmetric) arrays.
+    eig : eigenvalues and right eigenvectors for non-symmetric arrays.
+    eigvals : eigenvalues of non-symmetric arrays.
+    scipy.linalg.eigh : Similar function in SciPy (but also solves the
+                        generalized eigenvalue problem).
+
+    Notes
+    -----
+
+    .. versionadded:: 1.8.0
+
+    Broadcasting rules apply, see the `numpy.linalg` documentation for
+    details.
+
+    The eigenvalues/eigenvectors are computed using LAPACK routines ``_syevd``,
+    ``_heevd``.
+
+    The eigenvalues of real symmetric or complex Hermitian matrices are always
+    real. [1]_ The array `eigenvalues` of (column) eigenvectors is unitary and
+    `a`, `eigenvalues`, and `eigenvectors` satisfy the equations ``dot(a,
+    eigenvectors[:, i]) = eigenvalues[i] * eigenvectors[:, i]``.
+
+    References
+    ----------
+    .. [1] G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando,
+           FL, Academic Press, Inc., 1980, pg. 222.
+
+    Examples
+    --------
+    >>> from numpy import linalg as LA
+    >>> a = np.array([[1, -2j], [2j, 5]])
+    >>> a
+    array([[ 1.+0.j, -0.-2.j],
+           [ 0.+2.j,  5.+0.j]])
+    >>> eigenvalues, eigenvectors = LA.eigh(a)
+    >>> eigenvalues
+    array([0.17157288, 5.82842712])
+    >>> eigenvectors
+    array([[-0.92387953+0.j        , -0.38268343+0.j        ], # may vary
+           [ 0.        +0.38268343j,  0.        -0.92387953j]])
+
+    >>> np.dot(a, eigenvectors[:, 0]) - eigenvalues[0] * eigenvectors[:, 0] # verify 1st eigenval/vec pair
+    array([5.55111512e-17+0.0000000e+00j, 0.00000000e+00+1.2490009e-16j])
+    >>> np.dot(a, eigenvectors[:, 1]) - eigenvalues[1] * eigenvectors[:, 1] # verify 2nd eigenval/vec pair
+    array([0.+0.j, 0.+0.j])
+
+    >>> A = np.matrix(a) # what happens if input is a matrix object
+    >>> A
+    matrix([[ 1.+0.j, -0.-2.j],
+            [ 0.+2.j,  5.+0.j]])
+    >>> eigenvalues, eigenvectors = LA.eigh(A)
+    >>> eigenvalues
+    array([0.17157288, 5.82842712])
+    >>> eigenvectors
+    matrix([[-0.92387953+0.j        , -0.38268343+0.j        ], # may vary
+            [ 0.        +0.38268343j,  0.        -0.92387953j]])
+
+    >>> # demonstrate the treatment of the imaginary part of the diagonal
+    >>> a = np.array([[5+2j, 9-2j], [0+2j, 2-1j]])
+    >>> a
+    array([[5.+2.j, 9.-2.j],
+           [0.+2.j, 2.-1.j]])
+    >>> # with UPLO='L' this is numerically equivalent to using LA.eig() with:
+    >>> b = np.array([[5.+0.j, 0.-2.j], [0.+2.j, 2.-0.j]])
+    >>> b
+    array([[5.+0.j, 0.-2.j],
+           [0.+2.j, 2.+0.j]])
+    >>> wa, va = LA.eigh(a)
+    >>> wb, vb = LA.eig(b)
+    >>> wa; wb
+    array([1., 6.])
+    array([6.+0.j, 1.+0.j])
+    >>> va; vb
+    array([[-0.4472136 +0.j        , -0.89442719+0.j        ], # may vary
+           [ 0.        +0.89442719j,  0.        -0.4472136j ]])
+    array([[ 0.89442719+0.j       , -0.        +0.4472136j],
+           [-0.        +0.4472136j,  0.89442719+0.j       ]])
+
+    """
+    UPLO = UPLO.upper()
+    if UPLO not in ('L', 'U'):
+        raise ValueError("UPLO argument must be 'L' or 'U'")
+
+    a, wrap = _makearray(a)
+    _assert_stacked_2d(a)
+    _assert_stacked_square(a)
+    t, result_t = _commonType(a)
+
+    extobj = get_linalg_error_extobj(
+        _raise_linalgerror_eigenvalues_nonconvergence)
+    if UPLO == 'L':
+        gufunc = _umath_linalg.eigh_lo
+    else:
+        gufunc = _umath_linalg.eigh_up
+
+    signature = 'D->dD' if isComplexType(t) else 'd->dd'
+    w, vt = gufunc(a, signature=signature, extobj=extobj)
+    w = w.astype(_realType(result_t), copy=False)
+    vt = vt.astype(result_t, copy=False)
+    return EighResult(w, wrap(vt))
+
+
+# Singular value decomposition
+
+def _svd_dispatcher(a, full_matrices=None, compute_uv=None, hermitian=None):
+    return (a,)
+
+
+@array_function_dispatch(_svd_dispatcher)
+def svd(a, full_matrices=True, compute_uv=True, hermitian=False):
+    """
+    Singular Value Decomposition.
+
+    When `a` is a 2D array, and ``full_matrices=False``, then it is
+    factorized as ``u @ np.diag(s) @ vh = (u * s) @ vh``, where
+    `u` and the Hermitian transpose of `vh` are 2D arrays with
+    orthonormal columns and `s` is a 1D array of `a`'s singular
+    values. When `a` is higher-dimensional, SVD is applied in
+    stacked mode as explained below.
+
+    Parameters
+    ----------
+    a : (..., M, N) array_like
+        A real or complex array with ``a.ndim >= 2``.
+    full_matrices : bool, optional
+        If True (default), `u` and `vh` have the shapes ``(..., M, M)`` and
+        ``(..., N, N)``, respectively.  Otherwise, the shapes are
+        ``(..., M, K)`` and ``(..., K, N)``, respectively, where
+        ``K = min(M, N)``.
+    compute_uv : bool, optional
+        Whether or not to compute `u` and `vh` in addition to `s`.  True
+        by default.
+    hermitian : bool, optional
+        If True, `a` is assumed to be Hermitian (symmetric if real-valued),
+        enabling a more efficient method for finding singular values.
+        Defaults to False.
+
+        .. versionadded:: 1.17.0
+
+    Returns
+    -------
+    When `compute_uv` is True, the result is a namedtuple with the following
+    attribute names:
+
+    U : { (..., M, M), (..., M, K) } array
+        Unitary array(s). The first ``a.ndim - 2`` dimensions have the same
+        size as those of the input `a`. The size of the last two dimensions
+        depends on the value of `full_matrices`. Only returned when
+        `compute_uv` is True.
+    S : (..., K) array
+        Vector(s) with the singular values, within each vector sorted in
+        descending order. The first ``a.ndim - 2`` dimensions have the same
+        size as those of the input `a`.
+    Vh : { (..., N, N), (..., K, N) } array
+        Unitary array(s). The first ``a.ndim - 2`` dimensions have the same
+        size as those of the input `a`. The size of the last two dimensions
+        depends on the value of `full_matrices`. Only returned when
+        `compute_uv` is True.
+
+    Raises
+    ------
+    LinAlgError
+        If SVD computation does not converge.
+
+    See Also
+    --------
+    scipy.linalg.svd : Similar function in SciPy.
+    scipy.linalg.svdvals : Compute singular values of a matrix.
+
+    Notes
+    -----
+
+    .. versionchanged:: 1.8.0
+       Broadcasting rules apply, see the `numpy.linalg` documentation for
+       details.
+
+    The decomposition is performed using LAPACK routine ``_gesdd``.
+
+    SVD is usually described for the factorization of a 2D matrix :math:`A`.
+    The higher-dimensional case will be discussed below. In the 2D case, SVD is
+    written as :math:`A = U S V^H`, where :math:`A = a`, :math:`U= u`,
+    :math:`S= \\mathtt{np.diag}(s)` and :math:`V^H = vh`. The 1D array `s`
+    contains the singular values of `a` and `u` and `vh` are unitary. The rows
+    of `vh` are the eigenvectors of :math:`A^H A` and the columns of `u` are
+    the eigenvectors of :math:`A A^H`. In both cases the corresponding
+    (possibly non-zero) eigenvalues are given by ``s**2``.
+
+    If `a` has more than two dimensions, then broadcasting rules apply, as
+    explained in :ref:`routines.linalg-broadcasting`. This means that SVD is
+    working in "stacked" mode: it iterates over all indices of the first
+    ``a.ndim - 2`` dimensions and for each combination SVD is applied to the
+    last two indices. The matrix `a` can be reconstructed from the
+    decomposition with either ``(u * s[..., None, :]) @ vh`` or
+    ``u @ (s[..., None] * vh)``. (The ``@`` operator can be replaced by the
+    function ``np.matmul`` for python versions below 3.5.)
+
+    If `a` is a ``matrix`` object (as opposed to an ``ndarray``), then so are
+    all the return values.
+
+    Examples
+    --------
+    >>> a = np.random.randn(9, 6) + 1j*np.random.randn(9, 6)
+    >>> b = np.random.randn(2, 7, 8, 3) + 1j*np.random.randn(2, 7, 8, 3)
+
+    Reconstruction based on full SVD, 2D case:
+
+    >>> U, S, Vh = np.linalg.svd(a, full_matrices=True)
+    >>> U.shape, S.shape, Vh.shape
+    ((9, 9), (6,), (6, 6))
+    >>> np.allclose(a, np.dot(U[:, :6] * S, Vh))
+    True
+    >>> smat = np.zeros((9, 6), dtype=complex)
+    >>> smat[:6, :6] = np.diag(S)
+    >>> np.allclose(a, np.dot(U, np.dot(smat, Vh)))
+    True
+
+    Reconstruction based on reduced SVD, 2D case:
+
+    >>> U, S, Vh = np.linalg.svd(a, full_matrices=False)
+    >>> U.shape, S.shape, Vh.shape
+    ((9, 6), (6,), (6, 6))
+    >>> np.allclose(a, np.dot(U * S, Vh))
+    True
+    >>> smat = np.diag(S)
+    >>> np.allclose(a, np.dot(U, np.dot(smat, Vh)))
+    True
+
+    Reconstruction based on full SVD, 4D case:
+
+    >>> U, S, Vh = np.linalg.svd(b, full_matrices=True)
+    >>> U.shape, S.shape, Vh.shape
+    ((2, 7, 8, 8), (2, 7, 3), (2, 7, 3, 3))
+    >>> np.allclose(b, np.matmul(U[..., :3] * S[..., None, :], Vh))
+    True
+    >>> np.allclose(b, np.matmul(U[..., :3], S[..., None] * Vh))
+    True
+
+    Reconstruction based on reduced SVD, 4D case:
+
+    >>> U, S, Vh = np.linalg.svd(b, full_matrices=False)
+    >>> U.shape, S.shape, Vh.shape
+    ((2, 7, 8, 3), (2, 7, 3), (2, 7, 3, 3))
+    >>> np.allclose(b, np.matmul(U * S[..., None, :], Vh))
+    True
+    >>> np.allclose(b, np.matmul(U, S[..., None] * Vh))
+    True
+
+    """
+    import numpy as _nx
+    a, wrap = _makearray(a)
+
+    if hermitian:
+        # note: lapack svd returns eigenvalues with s ** 2 sorted descending,
+        # but eig returns s sorted ascending, so we re-order the eigenvalues
+        # and related arrays to have the correct order
+        if compute_uv:
+            s, u = eigh(a)
+            sgn = sign(s)
+            s = abs(s)
+            sidx = argsort(s)[..., ::-1]
+            sgn = _nx.take_along_axis(sgn, sidx, axis=-1)
+            s = _nx.take_along_axis(s, sidx, axis=-1)
+            u = _nx.take_along_axis(u, sidx[..., None, :], axis=-1)
+            # singular values are unsigned, move the sign into v
+            vt = transpose(u * sgn[..., None, :]).conjugate()
+            return SVDResult(wrap(u), s, wrap(vt))
+        else:
+            s = eigvalsh(a)
+            s = abs(s)
+            return sort(s)[..., ::-1]
+
+    _assert_stacked_2d(a)
+    t, result_t = _commonType(a)
+
+    extobj = get_linalg_error_extobj(_raise_linalgerror_svd_nonconvergence)
+
+    m, n = a.shape[-2:]
+    if compute_uv:
+        if full_matrices:
+            if m < n:
+                gufunc = _umath_linalg.svd_m_f
+            else:
+                gufunc = _umath_linalg.svd_n_f
+        else:
+            if m < n:
+                gufunc = _umath_linalg.svd_m_s
+            else:
+                gufunc = _umath_linalg.svd_n_s
+
+        signature = 'D->DdD' if isComplexType(t) else 'd->ddd'
+        u, s, vh = gufunc(a, signature=signature, extobj=extobj)
+        u = u.astype(result_t, copy=False)
+        s = s.astype(_realType(result_t), copy=False)
+        vh = vh.astype(result_t, copy=False)
+        return SVDResult(wrap(u), s, wrap(vh))
+    else:
+        if m < n:
+            gufunc = _umath_linalg.svd_m
+        else:
+            gufunc = _umath_linalg.svd_n
+
+        signature = 'D->d' if isComplexType(t) else 'd->d'
+        s = gufunc(a, signature=signature, extobj=extobj)
+        s = s.astype(_realType(result_t), copy=False)
+        return s
+
+
+def _cond_dispatcher(x, p=None):
+    return (x,)
+
+
+@array_function_dispatch(_cond_dispatcher)
+def cond(x, p=None):
+    """
+    Compute the condition number of a matrix.
+
+    This function is capable of returning the condition number using
+    one of seven different norms, depending on the value of `p` (see
+    Parameters below).
+
+    Parameters
+    ----------
+    x : (..., M, N) array_like
+        The matrix whose condition number is sought.
+    p : {None, 1, -1, 2, -2, inf, -inf, 'fro'}, optional
+        Order of the norm used in the condition number computation:
+
+        =====  ============================
+        p      norm for matrices
+        =====  ============================
+        None   2-norm, computed directly using the ``SVD``
+        'fro'  Frobenius norm
+        inf    max(sum(abs(x), axis=1))
+        -inf   min(sum(abs(x), axis=1))
+        1      max(sum(abs(x), axis=0))
+        -1     min(sum(abs(x), axis=0))
+        2      2-norm (largest sing. value)
+        -2     smallest singular value
+        =====  ============================
+
+        inf means the `numpy.inf` object, and the Frobenius norm is
+        the root-of-sum-of-squares norm.
+
+    Returns
+    -------
+    c : {float, inf}
+        The condition number of the matrix. May be infinite.
+
+    See Also
+    --------
+    numpy.linalg.norm
+
+    Notes
+    -----
+    The condition number of `x` is defined as the norm of `x` times the
+    norm of the inverse of `x` [1]_; the norm can be the usual L2-norm
+    (root-of-sum-of-squares) or one of a number of other matrix norms.
+
+    References
+    ----------
+    .. [1] G. Strang, *Linear Algebra and Its Applications*, Orlando, FL,
+           Academic Press, Inc., 1980, pg. 285.
+
+    Examples
+    --------
+    >>> from numpy import linalg as LA
+    >>> a = np.array([[1, 0, -1], [0, 1, 0], [1, 0, 1]])
+    >>> a
+    array([[ 1,  0, -1],
+           [ 0,  1,  0],
+           [ 1,  0,  1]])
+    >>> LA.cond(a)
+    1.4142135623730951
+    >>> LA.cond(a, 'fro')
+    3.1622776601683795
+    >>> LA.cond(a, np.inf)
+    2.0
+    >>> LA.cond(a, -np.inf)
+    1.0
+    >>> LA.cond(a, 1)
+    2.0
+    >>> LA.cond(a, -1)
+    1.0
+    >>> LA.cond(a, 2)
+    1.4142135623730951
+    >>> LA.cond(a, -2)
+    0.70710678118654746 # may vary
+    >>> min(LA.svd(a, compute_uv=False))*min(LA.svd(LA.inv(a), compute_uv=False))
+    0.70710678118654746 # may vary
+
+    """
+    x = asarray(x)  # in case we have a matrix
+    if _is_empty_2d(x):
+        raise LinAlgError("cond is not defined on empty arrays")
+    if p is None or p == 2 or p == -2:
+        s = svd(x, compute_uv=False)
+        with errstate(all='ignore'):
+            if p == -2:
+                r = s[..., -1] / s[..., 0]
+            else:
+                r = s[..., 0] / s[..., -1]
+    else:
+        # Call inv(x) ignoring errors. The result array will
+        # contain nans in the entries where inversion failed.
+        _assert_stacked_2d(x)
+        _assert_stacked_square(x)
+        t, result_t = _commonType(x)
+        signature = 'D->D' if isComplexType(t) else 'd->d'
+        with errstate(all='ignore'):
+            invx = _umath_linalg.inv(x, signature=signature)
+            r = norm(x, p, axis=(-2, -1)) * norm(invx, p, axis=(-2, -1))
+        r = r.astype(result_t, copy=False)
+
+    # Convert nans to infs unless the original array had nan entries
+    r = asarray(r)
+    nan_mask = isnan(r)
+    if nan_mask.any():
+        nan_mask &= ~isnan(x).any(axis=(-2, -1))
+        if r.ndim > 0:
+            r[nan_mask] = Inf
+        elif nan_mask:
+            r[()] = Inf
+
+    # Convention is to return scalars instead of 0d arrays
+    if r.ndim == 0:
+        r = r[()]
+
+    return r
+
+
+def _matrix_rank_dispatcher(A, tol=None, hermitian=None):
+    return (A,)
+
+
+@array_function_dispatch(_matrix_rank_dispatcher)
+def matrix_rank(A, tol=None, hermitian=False):
+    """
+    Return matrix rank of array using SVD method
+
+    Rank of the array is the number of singular values of the array that are
+    greater than `tol`.
+
+    .. versionchanged:: 1.14
+       Can now operate on stacks of matrices
+
+    Parameters
+    ----------
+    A : {(M,), (..., M, N)} array_like
+        Input vector or stack of matrices.
+    tol : (...) array_like, float, optional
+        Threshold below which SVD values are considered zero. If `tol` is
+        None, and ``S`` is an array with singular values for `M`, and
+        ``eps`` is the epsilon value for datatype of ``S``, then `tol` is
+        set to ``S.max() * max(M, N) * eps``.
+
+        .. versionchanged:: 1.14
+           Broadcasted against the stack of matrices
+    hermitian : bool, optional
+        If True, `A` is assumed to be Hermitian (symmetric if real-valued),
+        enabling a more efficient method for finding singular values.
+        Defaults to False.
+
+        .. versionadded:: 1.14
+
+    Returns
+    -------
+    rank : (...) array_like
+        Rank of A.
+
+    Notes
+    -----
+    The default threshold to detect rank deficiency is a test on the magnitude
+    of the singular values of `A`.  By default, we identify singular values less
+    than ``S.max() * max(M, N) * eps`` as indicating rank deficiency (with
+    the symbols defined above). This is the algorithm MATLAB uses [1].  It also
+    appears in *Numerical recipes* in the discussion of SVD solutions for linear
+    least squares [2].
+
+    This default threshold is designed to detect rank deficiency accounting for
+    the numerical errors of the SVD computation.  Imagine that there is a column
+    in `A` that is an exact (in floating point) linear combination of other
+    columns in `A`. Computing the SVD on `A` will not produce a singular value
+    exactly equal to 0 in general: any difference of the smallest SVD value from
+    0 will be caused by numerical imprecision in the calculation of the SVD.
+    Our threshold for small SVD values takes this numerical imprecision into
+    account, and the default threshold will detect such numerical rank
+    deficiency.  The threshold may declare a matrix `A` rank deficient even if
+    the linear combination of some columns of `A` is not exactly equal to
+    another column of `A` but only numerically very close to another column of
+    `A`.
+
+    We chose our default threshold because it is in wide use.  Other thresholds
+    are possible.  For example, elsewhere in the 2007 edition of *Numerical
+    recipes* there is an alternative threshold of ``S.max() *
+    np.finfo(A.dtype).eps / 2. * np.sqrt(m + n + 1.)``. The authors describe
+    this threshold as being based on "expected roundoff error" (p 71).
+
+    The thresholds above deal with floating point roundoff error in the
+    calculation of the SVD.  However, you may have more information about the
+    sources of error in `A` that would make you consider other tolerance values
+    to detect *effective* rank deficiency.  The most useful measure of the
+    tolerance depends on the operations you intend to use on your matrix.  For
+    example, if your data come from uncertain measurements with uncertainties
+    greater than floating point epsilon, choosing a tolerance near that
+    uncertainty may be preferable.  The tolerance may be absolute if the
+    uncertainties are absolute rather than relative.
+
+    References
+    ----------
+    .. [1] MATLAB reference documentation, "Rank"
+           https://www.mathworks.com/help/techdoc/ref/rank.html
+    .. [2] W. H. Press, S. A. Teukolsky, W. T. Vetterling and B. P. Flannery,
+           "Numerical Recipes (3rd edition)", Cambridge University Press, 2007,
+           page 795.
+
+    Examples
+    --------
+    >>> from numpy.linalg import matrix_rank
+    >>> matrix_rank(np.eye(4)) # Full rank matrix
+    4
+    >>> I=np.eye(4); I[-1,-1] = 0. # rank deficient matrix
+    >>> matrix_rank(I)
+    3
+    >>> matrix_rank(np.ones((4,))) # 1 dimension - rank 1 unless all 0
+    1
+    >>> matrix_rank(np.zeros((4,)))
+    0
+    """
+    A = asarray(A)
+    if A.ndim < 2:
+        return int(not all(A==0))
+    S = svd(A, compute_uv=False, hermitian=hermitian)
+    if tol is None:
+        tol = S.max(axis=-1, keepdims=True) * max(A.shape[-2:]) * finfo(S.dtype).eps
+    else:
+        tol = asarray(tol)[..., newaxis]
+    return count_nonzero(S > tol, axis=-1)
+
+
+# Generalized inverse
+
+def _pinv_dispatcher(a, rcond=None, hermitian=None):
+    return (a,)
+
+
+@array_function_dispatch(_pinv_dispatcher)
+def pinv(a, rcond=1e-15, hermitian=False):
+    """
+    Compute the (Moore-Penrose) pseudo-inverse of a matrix.
+
+    Calculate the generalized inverse of a matrix using its
+    singular-value decomposition (SVD) and including all
+    *large* singular values.
+
+    .. versionchanged:: 1.14
+       Can now operate on stacks of matrices
+
+    Parameters
+    ----------
+    a : (..., M, N) array_like
+        Matrix or stack of matrices to be pseudo-inverted.
+    rcond : (...) array_like of float
+        Cutoff for small singular values.
+        Singular values less than or equal to
+        ``rcond * largest_singular_value`` are set to zero.
+        Broadcasts against the stack of matrices.
+    hermitian : bool, optional
+        If True, `a` is assumed to be Hermitian (symmetric if real-valued),
+        enabling a more efficient method for finding singular values.
+        Defaults to False.
+
+        .. versionadded:: 1.17.0
+
+    Returns
+    -------
+    B : (..., N, M) ndarray
+        The pseudo-inverse of `a`. If `a` is a `matrix` instance, then so
+        is `B`.
+
+    Raises
+    ------
+    LinAlgError
+        If the SVD computation does not converge.
+
+    See Also
+    --------
+    scipy.linalg.pinv : Similar function in SciPy.
+    scipy.linalg.pinvh : Compute the (Moore-Penrose) pseudo-inverse of a
+                         Hermitian matrix.
+
+    Notes
+    -----
+    The pseudo-inverse of a matrix A, denoted :math:`A^+`, is
+    defined as: "the matrix that 'solves' [the least-squares problem]
+    :math:`Ax = b`," i.e., if :math:`\\bar{x}` is said solution, then
+    :math:`A^+` is that matrix such that :math:`\\bar{x} = A^+b`.
+
+    It can be shown that if :math:`Q_1 \\Sigma Q_2^T = A` is the singular
+    value decomposition of A, then
+    :math:`A^+ = Q_2 \\Sigma^+ Q_1^T`, where :math:`Q_{1,2}` are
+    orthogonal matrices, :math:`\\Sigma` is a diagonal matrix consisting
+    of A's so-called singular values, (followed, typically, by
+    zeros), and then :math:`\\Sigma^+` is simply the diagonal matrix
+    consisting of the reciprocals of A's singular values
+    (again, followed by zeros). [1]_
+
+    References
+    ----------
+    .. [1] G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando,
+           FL, Academic Press, Inc., 1980, pp. 139-142.
+
+    Examples
+    --------
+    The following example checks that ``a * a+ * a == a`` and
+    ``a+ * a * a+ == a+``:
+
+    >>> a = np.random.randn(9, 6)
+    >>> B = np.linalg.pinv(a)
+    >>> np.allclose(a, np.dot(a, np.dot(B, a)))
+    True
+    >>> np.allclose(B, np.dot(B, np.dot(a, B)))
+    True
+
+    """
+    a, wrap = _makearray(a)
+    rcond = asarray(rcond)
+    if _is_empty_2d(a):
+        m, n = a.shape[-2:]
+        res = empty(a.shape[:-2] + (n, m), dtype=a.dtype)
+        return wrap(res)
+    a = a.conjugate()
+    u, s, vt = svd(a, full_matrices=False, hermitian=hermitian)
+
+    # discard small singular values
+    cutoff = rcond[..., newaxis] * amax(s, axis=-1, keepdims=True)
+    large = s > cutoff
+    s = divide(1, s, where=large, out=s)
+    s[~large] = 0
+
+    res = matmul(transpose(vt), multiply(s[..., newaxis], transpose(u)))
+    return wrap(res)
+
+
+# Determinant
+
+
+@array_function_dispatch(_unary_dispatcher)
+def slogdet(a):
+    """
+    Compute the sign and (natural) logarithm of the determinant of an array.
+
+    If an array has a very small or very large determinant, then a call to
+    `det` may overflow or underflow. This routine is more robust against such
+    issues, because it computes the logarithm of the determinant rather than
+    the determinant itself.
+
+    Parameters
+    ----------
+    a : (..., M, M) array_like
+        Input array, has to be a square 2-D array.
+
+    Returns
+    -------
+    A namedtuple with the following attributes:
+
+    sign : (...) array_like
+        A number representing the sign of the determinant. For a real matrix,
+        this is 1, 0, or -1. For a complex matrix, this is a complex number
+        with absolute value 1 (i.e., it is on the unit circle), or else 0.
+    logabsdet : (...) array_like
+        The natural log of the absolute value of the determinant.
+
+    If the determinant is zero, then `sign` will be 0 and `logabsdet` will be
+    -Inf. In all cases, the determinant is equal to ``sign * np.exp(logabsdet)``.
+
+    See Also
+    --------
+    det
+
+    Notes
+    -----
+
+    .. versionadded:: 1.8.0
+
+    Broadcasting rules apply, see the `numpy.linalg` documentation for
+    details.
+
+    .. versionadded:: 1.6.0
+
+    The determinant is computed via LU factorization using the LAPACK
+    routine ``z/dgetrf``.
+
+
+    Examples
+    --------
+    The determinant of a 2-D array ``[[a, b], [c, d]]`` is ``ad - bc``:
+
+    >>> a = np.array([[1, 2], [3, 4]])
+    >>> (sign, logabsdet) = np.linalg.slogdet(a)
+    >>> (sign, logabsdet)
+    (-1, 0.69314718055994529) # may vary
+    >>> sign * np.exp(logabsdet)
+    -2.0
+
+    Computing log-determinants for a stack of matrices:
+
+    >>> a = np.array([ [[1, 2], [3, 4]], [[1, 2], [2, 1]], [[1, 3], [3, 1]] ])
+    >>> a.shape
+    (3, 2, 2)
+    >>> sign, logabsdet = np.linalg.slogdet(a)
+    >>> (sign, logabsdet)
+    (array([-1., -1., -1.]), array([ 0.69314718,  1.09861229,  2.07944154]))
+    >>> sign * np.exp(logabsdet)
+    array([-2., -3., -8.])
+
+    This routine succeeds where ordinary `det` does not:
+
+    >>> np.linalg.det(np.eye(500) * 0.1)
+    0.0
+    >>> np.linalg.slogdet(np.eye(500) * 0.1)
+    (1, -1151.2925464970228)
+
+    """
+    a = asarray(a)
+    _assert_stacked_2d(a)
+    _assert_stacked_square(a)
+    t, result_t = _commonType(a)
+    real_t = _realType(result_t)
+    signature = 'D->Dd' if isComplexType(t) else 'd->dd'
+    sign, logdet = _umath_linalg.slogdet(a, signature=signature)
+    sign = sign.astype(result_t, copy=False)
+    logdet = logdet.astype(real_t, copy=False)
+    return SlogdetResult(sign, logdet)
+
+
+@array_function_dispatch(_unary_dispatcher)
+def det(a):
+    """
+    Compute the determinant of an array.
+
+    Parameters
+    ----------
+    a : (..., M, M) array_like
+        Input array to compute determinants for.
+
+    Returns
+    -------
+    det : (...) array_like
+        Determinant of `a`.
+
+    See Also
+    --------
+    slogdet : Another way to represent the determinant, more suitable
+      for large matrices where underflow/overflow may occur.
+    scipy.linalg.det : Similar function in SciPy.
+
+    Notes
+    -----
+
+    .. versionadded:: 1.8.0
+
+    Broadcasting rules apply, see the `numpy.linalg` documentation for
+    details.
+
+    The determinant is computed via LU factorization using the LAPACK
+    routine ``z/dgetrf``.
+
+    Examples
+    --------
+    The determinant of a 2-D array [[a, b], [c, d]] is ad - bc:
+
+    >>> a = np.array([[1, 2], [3, 4]])
+    >>> np.linalg.det(a)
+    -2.0 # may vary
+
+    Computing determinants for a stack of matrices:
+
+    >>> a = np.array([ [[1, 2], [3, 4]], [[1, 2], [2, 1]], [[1, 3], [3, 1]] ])
+    >>> a.shape
+    (3, 2, 2)
+    >>> np.linalg.det(a)
+    array([-2., -3., -8.])
+
+    """
+    a = asarray(a)
+    _assert_stacked_2d(a)
+    _assert_stacked_square(a)
+    t, result_t = _commonType(a)
+    signature = 'D->D' if isComplexType(t) else 'd->d'
+    r = _umath_linalg.det(a, signature=signature)
+    r = r.astype(result_t, copy=False)
+    return r
+
+
+# Linear Least Squares
+
+def _lstsq_dispatcher(a, b, rcond=None):
+    return (a, b)
+
+
+@array_function_dispatch(_lstsq_dispatcher)
+def lstsq(a, b, rcond="warn"):
+    r"""
+    Return the least-squares solution to a linear matrix equation.
+
+    Computes the vector `x` that approximately solves the equation
+    ``a @ x = b``. The equation may be under-, well-, or over-determined
+    (i.e., the number of linearly independent rows of `a` can be less than,
+    equal to, or greater than its number of linearly independent columns).
+    If `a` is square and of full rank, then `x` (but for round-off error)
+    is the "exact" solution of the equation. Else, `x` minimizes the
+    Euclidean 2-norm :math:`||b - ax||`. If there are multiple minimizing
+    solutions, the one with the smallest 2-norm :math:`||x||` is returned.
+
+    Parameters
+    ----------
+    a : (M, N) array_like
+        "Coefficient" matrix.
+    b : {(M,), (M, K)} array_like
+        Ordinate or "dependent variable" values. If `b` is two-dimensional,
+        the least-squares solution is calculated for each of the `K` columns
+        of `b`.
+    rcond : float, optional
+        Cut-off ratio for small singular values of `a`.
+        For the purposes of rank determination, singular values are treated
+        as zero if they are smaller than `rcond` times the largest singular
+        value of `a`.
+
+        .. versionchanged:: 1.14.0
+           If not set, a FutureWarning is given. The previous default
+           of ``-1`` will use the machine precision as `rcond` parameter,
+           the new default will use the machine precision times `max(M, N)`.
+           To silence the warning and use the new default, use ``rcond=None``,
+           to keep using the old behavior, use ``rcond=-1``.
+
+    Returns
+    -------
+    x : {(N,), (N, K)} ndarray
+        Least-squares solution. If `b` is two-dimensional,
+        the solutions are in the `K` columns of `x`.
+    residuals : {(1,), (K,), (0,)} ndarray
+        Sums of squared residuals: Squared Euclidean 2-norm for each column in
+        ``b - a @ x``.
+        If the rank of `a` is < N or M <= N, this is an empty array.
+        If `b` is 1-dimensional, this is a (1,) shape array.
+        Otherwise the shape is (K,).
+    rank : int
+        Rank of matrix `a`.
+    s : (min(M, N),) ndarray
+        Singular values of `a`.
+
+    Raises
+    ------
+    LinAlgError
+        If computation does not converge.
+
+    See Also
+    --------
+    scipy.linalg.lstsq : Similar function in SciPy.
+
+    Notes
+    -----
+    If `b` is a matrix, then all array results are returned as matrices.
+
+    Examples
+    --------
+    Fit a line, ``y = mx + c``, through some noisy data-points:
+
+    >>> x = np.array([0, 1, 2, 3])
+    >>> y = np.array([-1, 0.2, 0.9, 2.1])
+
+    By examining the coefficients, we see that the line should have a
+    gradient of roughly 1 and cut the y-axis at, more or less, -1.
+
+    We can rewrite the line equation as ``y = Ap``, where ``A = [[x 1]]``
+    and ``p = [[m], [c]]``.  Now use `lstsq` to solve for `p`:
+
+    >>> A = np.vstack([x, np.ones(len(x))]).T
+    >>> A
+    array([[ 0.,  1.],
+           [ 1.,  1.],
+           [ 2.,  1.],
+           [ 3.,  1.]])
+
+    >>> m, c = np.linalg.lstsq(A, y, rcond=None)[0]
+    >>> m, c
+    (1.0 -0.95) # may vary
+
+    Plot the data along with the fitted line:
+
+    >>> import matplotlib.pyplot as plt
+    >>> _ = plt.plot(x, y, 'o', label='Original data', markersize=10)
+    >>> _ = plt.plot(x, m*x + c, 'r', label='Fitted line')
+    >>> _ = plt.legend()
+    >>> plt.show()
+
+    """
+    a, _ = _makearray(a)
+    b, wrap = _makearray(b)
+    is_1d = b.ndim == 1
+    if is_1d:
+        b = b[:, newaxis]
+    _assert_2d(a, b)
+    m, n = a.shape[-2:]
+    m2, n_rhs = b.shape[-2:]
+    if m != m2:
+        raise LinAlgError('Incompatible dimensions')
+
+    t, result_t = _commonType(a, b)
+    result_real_t = _realType(result_t)
+
+    # Determine default rcond value
+    if rcond == "warn":
+        # 2017-08-19, 1.14.0
+        warnings.warn("`rcond` parameter will change to the default of "
+                      "machine precision times ``max(M, N)`` where M and N "
+                      "are the input matrix dimensions.\n"
+                      "To use the future default and silence this warning "
+                      "we advise to pass `rcond=None`, to keep using the old, "
+                      "explicitly pass `rcond=-1`.",
+                      FutureWarning, stacklevel=2)
+        rcond = -1
+    if rcond is None:
+        rcond = finfo(t).eps * max(n, m)
+
+    if m <= n:
+        gufunc = _umath_linalg.lstsq_m
+    else:
+        gufunc = _umath_linalg.lstsq_n
+
+    signature = 'DDd->Ddid' if isComplexType(t) else 'ddd->ddid'
+    extobj = get_linalg_error_extobj(_raise_linalgerror_lstsq)
+    if n_rhs == 0:
+        # lapack can't handle n_rhs = 0 - so allocate the array one larger in that axis
+        b = zeros(b.shape[:-2] + (m, n_rhs + 1), dtype=b.dtype)
+    x, resids, rank, s = gufunc(a, b, rcond, signature=signature, extobj=extobj)
+    if m == 0:
+        x[...] = 0
+    if n_rhs == 0:
+        # remove the item we added
+        x = x[..., :n_rhs]
+        resids = resids[..., :n_rhs]
+
+    # remove the axis we added
+    if is_1d:
+        x = x.squeeze(axis=-1)
+        # we probably should squeeze resids too, but we can't
+        # without breaking compatibility.
+
+    # as documented
+    if rank != n or m <= n:
+        resids = array([], result_real_t)
+
+    # coerce output arrays
+    s = s.astype(result_real_t, copy=False)
+    resids = resids.astype(result_real_t, copy=False)
+    x = x.astype(result_t, copy=True)  # Copying lets the memory in r_parts be freed
+    return wrap(x), wrap(resids), rank, s
+
+
+def _multi_svd_norm(x, row_axis, col_axis, op):
+    """Compute a function of the singular values of the 2-D matrices in `x`.
+
+    This is a private utility function used by `numpy.linalg.norm()`.
+
+    Parameters
+    ----------
+    x : ndarray
+    row_axis, col_axis : int
+        The axes of `x` that hold the 2-D matrices.
+    op : callable
+        This should be either numpy.amin or `numpy.amax` or `numpy.sum`.
+
+    Returns
+    -------
+    result : float or ndarray
+        If `x` is 2-D, the return values is a float.
+        Otherwise, it is an array with ``x.ndim - 2`` dimensions.
+        The return values are either the minimum or maximum or sum of the
+        singular values of the matrices, depending on whether `op`
+        is `numpy.amin` or `numpy.amax` or `numpy.sum`.
+
+    """
+    y = moveaxis(x, (row_axis, col_axis), (-2, -1))
+    result = op(svd(y, compute_uv=False), axis=-1)
+    return result
+
+
+def _norm_dispatcher(x, ord=None, axis=None, keepdims=None):
+    return (x,)
+
+
+@array_function_dispatch(_norm_dispatcher)
+def norm(x, ord=None, axis=None, keepdims=False):
+    """
+    Matrix or vector norm.
+
+    This function is able to return one of eight different matrix norms,
+    or one of an infinite number of vector norms (described below), depending
+    on the value of the ``ord`` parameter.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.  If `axis` is None, `x` must be 1-D or 2-D, unless `ord`
+        is None. If both `axis` and `ord` are None, the 2-norm of
+        ``x.ravel`` will be returned.
+    ord : {non-zero int, inf, -inf, 'fro', 'nuc'}, optional
+        Order of the norm (see table under ``Notes``). inf means numpy's
+        `inf` object. The default is None.
+    axis : {None, int, 2-tuple of ints}, optional.
+        If `axis` is an integer, it specifies the axis of `x` along which to
+        compute the vector norms.  If `axis` is a 2-tuple, it specifies the
+        axes that hold 2-D matrices, and the matrix norms of these matrices
+        are computed.  If `axis` is None then either a vector norm (when `x`
+        is 1-D) or a matrix norm (when `x` is 2-D) is returned. The default
+        is None.
+
+        .. versionadded:: 1.8.0
+
+    keepdims : bool, optional
+        If this is set to True, the axes which are normed over are left in the
+        result as dimensions with size one.  With this option the result will
+        broadcast correctly against the original `x`.
+
+        .. versionadded:: 1.10.0
+
+    Returns
+    -------
+    n : float or ndarray
+        Norm of the matrix or vector(s).
+
+    See Also
+    --------
+    scipy.linalg.norm : Similar function in SciPy.
+
+    Notes
+    -----
+    For values of ``ord < 1``, the result is, strictly speaking, not a
+    mathematical 'norm', but it may still be useful for various numerical
+    purposes.
+
+    The following norms can be calculated:
+
+    =====  ============================  ==========================
+    ord    norm for matrices             norm for vectors
+    =====  ============================  ==========================
+    None   Frobenius norm                2-norm
+    'fro'  Frobenius norm                --
+    'nuc'  nuclear norm                  --
+    inf    max(sum(abs(x), axis=1))      max(abs(x))
+    -inf   min(sum(abs(x), axis=1))      min(abs(x))
+    0      --                            sum(x != 0)
+    1      max(sum(abs(x), axis=0))      as below
+    -1     min(sum(abs(x), axis=0))      as below
+    2      2-norm (largest sing. value)  as below
+    -2     smallest singular value       as below
+    other  --                            sum(abs(x)**ord)**(1./ord)
+    =====  ============================  ==========================
+
+    The Frobenius norm is given by [1]_:
+
+        :math:`||A||_F = [\\sum_{i,j} abs(a_{i,j})^2]^{1/2}`
+
+    The nuclear norm is the sum of the singular values.
+
+    Both the Frobenius and nuclear norm orders are only defined for
+    matrices and raise a ValueError when ``x.ndim != 2``.
+
+    References
+    ----------
+    .. [1] G. H. Golub and C. F. Van Loan, *Matrix Computations*,
+           Baltimore, MD, Johns Hopkins University Press, 1985, pg. 15
+
+    Examples
+    --------
+    >>> from numpy import linalg as LA
+    >>> a = np.arange(9) - 4
+    >>> a
+    array([-4, -3, -2, ...,  2,  3,  4])
+    >>> b = a.reshape((3, 3))
+    >>> b
+    array([[-4, -3, -2],
+           [-1,  0,  1],
+           [ 2,  3,  4]])
+
+    >>> LA.norm(a)
+    7.745966692414834
+    >>> LA.norm(b)
+    7.745966692414834
+    >>> LA.norm(b, 'fro')
+    7.745966692414834
+    >>> LA.norm(a, np.inf)
+    4.0
+    >>> LA.norm(b, np.inf)
+    9.0
+    >>> LA.norm(a, -np.inf)
+    0.0
+    >>> LA.norm(b, -np.inf)
+    2.0
+
+    >>> LA.norm(a, 1)
+    20.0
+    >>> LA.norm(b, 1)
+    7.0
+    >>> LA.norm(a, -1)
+    -4.6566128774142013e-010
+    >>> LA.norm(b, -1)
+    6.0
+    >>> LA.norm(a, 2)
+    7.745966692414834
+    >>> LA.norm(b, 2)
+    7.3484692283495345
+
+    >>> LA.norm(a, -2)
+    0.0
+    >>> LA.norm(b, -2)
+    1.8570331885190563e-016 # may vary
+    >>> LA.norm(a, 3)
+    5.8480354764257312 # may vary
+    >>> LA.norm(a, -3)
+    0.0
+
+    Using the `axis` argument to compute vector norms:
+
+    >>> c = np.array([[ 1, 2, 3],
+    ...               [-1, 1, 4]])
+    >>> LA.norm(c, axis=0)
+    array([ 1.41421356,  2.23606798,  5.        ])
+    >>> LA.norm(c, axis=1)
+    array([ 3.74165739,  4.24264069])
+    >>> LA.norm(c, ord=1, axis=1)
+    array([ 6.,  6.])
+
+    Using the `axis` argument to compute matrix norms:
+
+    >>> m = np.arange(8).reshape(2,2,2)
+    >>> LA.norm(m, axis=(1,2))
+    array([  3.74165739,  11.22497216])
+    >>> LA.norm(m[0, :, :]), LA.norm(m[1, :, :])
+    (3.7416573867739413, 11.224972160321824)
+
+    """
+    x = asarray(x)
+
+    if not issubclass(x.dtype.type, (inexact, object_)):
+        x = x.astype(float)
+
+    # Immediately handle some default, simple, fast, and common cases.
+    if axis is None:
+        ndim = x.ndim
+        if ((ord is None) or
+            (ord in ('f', 'fro') and ndim == 2) or
+            (ord == 2 and ndim == 1)):
+
+            x = x.ravel(order='K')
+            if isComplexType(x.dtype.type):
+                x_real = x.real
+                x_imag = x.imag
+                sqnorm = x_real.dot(x_real) + x_imag.dot(x_imag)
+            else:
+                sqnorm = x.dot(x)
+            ret = sqrt(sqnorm)
+            if keepdims:
+                ret = ret.reshape(ndim*[1])
+            return ret
+
+    # Normalize the `axis` argument to a tuple.
+    nd = x.ndim
+    if axis is None:
+        axis = tuple(range(nd))
+    elif not isinstance(axis, tuple):
+        try:
+            axis = int(axis)
+        except Exception as e:
+            raise TypeError("'axis' must be None, an integer or a tuple of integers") from e
+        axis = (axis,)
+
+    if len(axis) == 1:
+        if ord == Inf:
+            return abs(x).max(axis=axis, keepdims=keepdims)
+        elif ord == -Inf:
+            return abs(x).min(axis=axis, keepdims=keepdims)
+        elif ord == 0:
+            # Zero norm
+            return (x != 0).astype(x.real.dtype).sum(axis=axis, keepdims=keepdims)
+        elif ord == 1:
+            # special case for speedup
+            return add.reduce(abs(x), axis=axis, keepdims=keepdims)
+        elif ord is None or ord == 2:
+            # special case for speedup
+            s = (x.conj() * x).real
+            return sqrt(add.reduce(s, axis=axis, keepdims=keepdims))
+        # None of the str-type keywords for ord ('fro', 'nuc')
+        # are valid for vectors
+        elif isinstance(ord, str):
+            raise ValueError(f"Invalid norm order '{ord}' for vectors")
+        else:
+            absx = abs(x)
+            absx **= ord
+            ret = add.reduce(absx, axis=axis, keepdims=keepdims)
+            ret **= reciprocal(ord, dtype=ret.dtype)
+            return ret
+    elif len(axis) == 2:
+        row_axis, col_axis = axis
+        row_axis = normalize_axis_index(row_axis, nd)
+        col_axis = normalize_axis_index(col_axis, nd)
+        if row_axis == col_axis:
+            raise ValueError('Duplicate axes given.')
+        if ord == 2:
+            ret =  _multi_svd_norm(x, row_axis, col_axis, amax)
+        elif ord == -2:
+            ret = _multi_svd_norm(x, row_axis, col_axis, amin)
+        elif ord == 1:
+            if col_axis > row_axis:
+                col_axis -= 1
+            ret = add.reduce(abs(x), axis=row_axis).max(axis=col_axis)
+        elif ord == Inf:
+            if row_axis > col_axis:
+                row_axis -= 1
+            ret = add.reduce(abs(x), axis=col_axis).max(axis=row_axis)
+        elif ord == -1:
+            if col_axis > row_axis:
+                col_axis -= 1
+            ret = add.reduce(abs(x), axis=row_axis).min(axis=col_axis)
+        elif ord == -Inf:
+            if row_axis > col_axis:
+                row_axis -= 1
+            ret = add.reduce(abs(x), axis=col_axis).min(axis=row_axis)
+        elif ord in [None, 'fro', 'f']:
+            ret = sqrt(add.reduce((x.conj() * x).real, axis=axis))
+        elif ord == 'nuc':
+            ret = _multi_svd_norm(x, row_axis, col_axis, sum)
+        else:
+            raise ValueError("Invalid norm order for matrices.")
+        if keepdims:
+            ret_shape = list(x.shape)
+            ret_shape[axis[0]] = 1
+            ret_shape[axis[1]] = 1
+            ret = ret.reshape(ret_shape)
+        return ret
+    else:
+        raise ValueError("Improper number of dimensions to norm.")
+
+
+# multi_dot
+
+def _multidot_dispatcher(arrays, *, out=None):
+    yield from arrays
+    yield out
+
+
+@array_function_dispatch(_multidot_dispatcher)
+def multi_dot(arrays, *, out=None):
+    """
+    Compute the dot product of two or more arrays in a single function call,
+    while automatically selecting the fastest evaluation order.
+
+    `multi_dot` chains `numpy.dot` and uses optimal parenthesization
+    of the matrices [1]_ [2]_. Depending on the shapes of the matrices,
+    this can speed up the multiplication a lot.
+
+    If the first argument is 1-D it is treated as a row vector.
+    If the last argument is 1-D it is treated as a column vector.
+    The other arguments must be 2-D.
+
+    Think of `multi_dot` as::
+
+        def multi_dot(arrays): return functools.reduce(np.dot, arrays)
+
+
+    Parameters
+    ----------
+    arrays : sequence of array_like
+        If the first argument is 1-D it is treated as row vector.
+        If the last argument is 1-D it is treated as column vector.
+        The other arguments must be 2-D.
+    out : ndarray, optional
+        Output argument. This must have the exact kind that would be returned
+        if it was not used. In particular, it must have the right type, must be
+        C-contiguous, and its dtype must be the dtype that would be returned
+        for `dot(a, b)`. This is a performance feature. Therefore, if these
+        conditions are not met, an exception is raised, instead of attempting
+        to be flexible.
+
+        .. versionadded:: 1.19.0
+
+    Returns
+    -------
+    output : ndarray
+        Returns the dot product of the supplied arrays.
+
+    See Also
+    --------
+    numpy.dot : dot multiplication with two arguments.
+
+    References
+    ----------
+
+    .. [1] Cormen, "Introduction to Algorithms", Chapter 15.2, p. 370-378
+    .. [2] https://en.wikipedia.org/wiki/Matrix_chain_multiplication
+
+    Examples
+    --------
+    `multi_dot` allows you to write::
+
+    >>> from numpy.linalg import multi_dot
+    >>> # Prepare some data
+    >>> A = np.random.random((10000, 100))
+    >>> B = np.random.random((100, 1000))
+    >>> C = np.random.random((1000, 5))
+    >>> D = np.random.random((5, 333))
+    >>> # the actual dot multiplication
+    >>> _ = multi_dot([A, B, C, D])
+
+    instead of::
+
+    >>> _ = np.dot(np.dot(np.dot(A, B), C), D)
+    >>> # or
+    >>> _ = A.dot(B).dot(C).dot(D)
+
+    Notes
+    -----
+    The cost for a matrix multiplication can be calculated with the
+    following function::
+
+        def cost(A, B):
+            return A.shape[0] * A.shape[1] * B.shape[1]
+
+    Assume we have three matrices
+    :math:`A_{10x100}, B_{100x5}, C_{5x50}`.
+
+    The costs for the two different parenthesizations are as follows::
+
+        cost((AB)C) = 10*100*5 + 10*5*50   = 5000 + 2500   = 7500
+        cost(A(BC)) = 10*100*50 + 100*5*50 = 50000 + 25000 = 75000
+
+    """
+    n = len(arrays)
+    # optimization only makes sense for len(arrays) > 2
+    if n < 2:
+        raise ValueError("Expecting at least two arrays.")
+    elif n == 2:
+        return dot(arrays[0], arrays[1], out=out)
+
+    arrays = [asanyarray(a) for a in arrays]
+
+    # save original ndim to reshape the result array into the proper form later
+    ndim_first, ndim_last = arrays[0].ndim, arrays[-1].ndim
+    # Explicitly convert vectors to 2D arrays to keep the logic of the internal
+    # _multi_dot_* functions as simple as possible.
+    if arrays[0].ndim == 1:
+        arrays[0] = atleast_2d(arrays[0])
+    if arrays[-1].ndim == 1:
+        arrays[-1] = atleast_2d(arrays[-1]).T
+    _assert_2d(*arrays)
+
+    # _multi_dot_three is much faster than _multi_dot_matrix_chain_order
+    if n == 3:
+        result = _multi_dot_three(arrays[0], arrays[1], arrays[2], out=out)
+    else:
+        order = _multi_dot_matrix_chain_order(arrays)
+        result = _multi_dot(arrays, order, 0, n - 1, out=out)
+
+    # return proper shape
+    if ndim_first == 1 and ndim_last == 1:
+        return result[0, 0]  # scalar
+    elif ndim_first == 1 or ndim_last == 1:
+        return result.ravel()  # 1-D
+    else:
+        return result
+
+
+def _multi_dot_three(A, B, C, out=None):
+    """
+    Find the best order for three arrays and do the multiplication.
+
+    For three arguments `_multi_dot_three` is approximately 15 times faster
+    than `_multi_dot_matrix_chain_order`
+
+    """
+    a0, a1b0 = A.shape
+    b1c0, c1 = C.shape
+    # cost1 = cost((AB)C) = a0*a1b0*b1c0 + a0*b1c0*c1
+    cost1 = a0 * b1c0 * (a1b0 + c1)
+    # cost2 = cost(A(BC)) = a1b0*b1c0*c1 + a0*a1b0*c1
+    cost2 = a1b0 * c1 * (a0 + b1c0)
+
+    if cost1 < cost2:
+        return dot(dot(A, B), C, out=out)
+    else:
+        return dot(A, dot(B, C), out=out)
+
+
+def _multi_dot_matrix_chain_order(arrays, return_costs=False):
+    """
+    Return a np.array that encodes the optimal order of mutiplications.
+
+    The optimal order array is then used by `_multi_dot()` to do the
+    multiplication.
+
+    Also return the cost matrix if `return_costs` is `True`
+
+    The implementation CLOSELY follows Cormen, "Introduction to Algorithms",
+    Chapter 15.2, p. 370-378.  Note that Cormen uses 1-based indices.
+
+        cost[i, j] = min([
+            cost[prefix] + cost[suffix] + cost_mult(prefix, suffix)
+            for k in range(i, j)])
+
+    """
+    n = len(arrays)
+    # p stores the dimensions of the matrices
+    # Example for p: A_{10x100}, B_{100x5}, C_{5x50} --> p = [10, 100, 5, 50]
+    p = [a.shape[0] for a in arrays] + [arrays[-1].shape[1]]
+    # m is a matrix of costs of the subproblems
+    # m[i,j]: min number of scalar multiplications needed to compute A_{i..j}
+    m = zeros((n, n), dtype=double)
+    # s is the actual ordering
+    # s[i, j] is the value of k at which we split the product A_i..A_j
+    s = empty((n, n), dtype=intp)
+
+    for l in range(1, n):
+        for i in range(n - l):
+            j = i + l
+            m[i, j] = Inf
+            for k in range(i, j):
+                q = m[i, k] + m[k+1, j] + p[i]*p[k+1]*p[j+1]
+                if q < m[i, j]:
+                    m[i, j] = q
+                    s[i, j] = k  # Note that Cormen uses 1-based index
+
+    return (s, m) if return_costs else s
+
+
+def _multi_dot(arrays, order, i, j, out=None):
+    """Actually do the multiplication with the given order."""
+    if i == j:
+        # the initial call with non-None out should never get here
+        assert out is None
+
+        return arrays[i]
+    else:
+        return dot(_multi_dot(arrays, order, i, order[i, j]),
+                   _multi_dot(arrays, order, order[i, j] + 1, j),
+                   out=out)
diff --git a/venv/lib/python3.10/site-packages/numpy/linalg/linalg.pyi b/venv/lib/python3.10/site-packages/numpy/linalg/linalg.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..c0b2f29b28d9528556151bb0139e671c5ecbb4c4
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/numpy/linalg/linalg.pyi
@@ -0,0 +1,297 @@
+from collections.abc import Iterable
+from typing import (
+    Literal as L,
+    overload,
+    TypeVar,
+    Any,
+    SupportsIndex,
+    SupportsInt,
+    NamedTuple,
+    Generic,
+)
+
+from numpy import (
+    generic,
+    floating,
+    complexfloating,
+    int32,
+    float64,
+    complex128,
+)
+
+from numpy.linalg import LinAlgError as LinAlgError
+
+from numpy._typing import (
+    NDArray,
+    ArrayLike,
+    _ArrayLikeInt_co,
+    _ArrayLikeFloat_co,
+    _ArrayLikeComplex_co,
+    _ArrayLikeTD64_co,
+    _ArrayLikeObject_co,
+)
+
+_T = TypeVar("_T")
+_ArrayType = TypeVar("_ArrayType", bound=NDArray[Any])
+_SCT = TypeVar("_SCT", bound=generic, covariant=True)
+_SCT2 = TypeVar("_SCT2", bound=generic, covariant=True)
+
+_2Tuple = tuple[_T, _T]
+_ModeKind = L["reduced", "complete", "r", "raw"]
+
+__all__: list[str]
+
+class EigResult(NamedTuple):
+    eigenvalues: NDArray[Any]
+    eigenvectors: NDArray[Any]
+
+class EighResult(NamedTuple):
+    eigenvalues: NDArray[Any]
+    eigenvectors: NDArray[Any]
+
+class QRResult(NamedTuple):
+    Q: NDArray[Any]
+    R: NDArray[Any]
+
+class SlogdetResult(NamedTuple):
+    # TODO: `sign` and `logabsdet` are scalars for input 2D arrays and
+    # a `(x.ndim - 2)`` dimensionl arrays otherwise
+    sign: Any
+    logabsdet: Any
+
+class SVDResult(NamedTuple):
+    U: NDArray[Any]
+    S: NDArray[Any]
+    Vh: NDArray[Any]
+
+@overload
+def tensorsolve(
+    a: _ArrayLikeInt_co,
+    b: _ArrayLikeInt_co,
+    axes: None | Iterable[int] =...,
+) -> NDArray[float64]: ...
+@overload
+def tensorsolve(
+    a: _ArrayLikeFloat_co,
+    b: _ArrayLikeFloat_co,
+    axes: None | Iterable[int] =...,
+) -> NDArray[floating[Any]]: ...
+@overload
+def tensorsolve(
+    a: _ArrayLikeComplex_co,
+    b: _ArrayLikeComplex_co,
+    axes: None | Iterable[int] =...,
+) -> NDArray[complexfloating[Any, Any]]: ...
+
+@overload
+def solve(
+    a: _ArrayLikeInt_co,
+    b: _ArrayLikeInt_co,
+) -> NDArray[float64]: ...
+@overload
+def solve(
+    a: _ArrayLikeFloat_co,
+    b: _ArrayLikeFloat_co,
+) -> NDArray[floating[Any]]: ...
+@overload
+def solve(
+    a: _ArrayLikeComplex_co,
+    b: _ArrayLikeComplex_co,
+) -> NDArray[complexfloating[Any, Any]]: ...
+
+@overload
+def tensorinv(
+    a: _ArrayLikeInt_co,
+    ind: int = ...,
+) -> NDArray[float64]: ...
+@overload
+def tensorinv(
+    a: _ArrayLikeFloat_co,
+    ind: int = ...,
+) -> NDArray[floating[Any]]: ...
+@overload
+def tensorinv(
+    a: _ArrayLikeComplex_co,
+    ind: int = ...,
+) -> NDArray[complexfloating[Any, Any]]: ...
+
+@overload
+def inv(a: _ArrayLikeInt_co) -> NDArray[float64]: ...
+@overload
+def inv(a: _ArrayLikeFloat_co) -> NDArray[floating[Any]]: ...
+@overload
+def inv(a: _ArrayLikeComplex_co) -> NDArray[complexfloating[Any, Any]]: ...
+
+# TODO: The supported input and output dtypes are dependent on the value of `n`.
+# For example: `n < 0` always casts integer types to float64
+def matrix_power(
+    a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
+    n: SupportsIndex,
+) -> NDArray[Any]: ...
+
+@overload
+def cholesky(a: _ArrayLikeInt_co) -> NDArray[float64]: ...
+@overload
+def cholesky(a: _ArrayLikeFloat_co) -> NDArray[floating[Any]]: ...
+@overload
+def cholesky(a: _ArrayLikeComplex_co) -> NDArray[complexfloating[Any, Any]]: ...
+
+@overload
+def qr(a: _ArrayLikeInt_co, mode: _ModeKind = ...) -> QRResult: ...
+@overload
+def qr(a: _ArrayLikeFloat_co, mode: _ModeKind = ...) -> QRResult: ...
+@overload
+def qr(a: _ArrayLikeComplex_co, mode: _ModeKind = ...) -> QRResult: ...
+
+@overload
+def eigvals(a: _ArrayLikeInt_co) -> NDArray[float64] | NDArray[complex128]: ...
+@overload
+def eigvals(a: _ArrayLikeFloat_co) -> NDArray[floating[Any]] | NDArray[complexfloating[Any, Any]]: ...
+@overload
+def eigvals(a: _ArrayLikeComplex_co) -> NDArray[complexfloating[Any, Any]]: ...
+
+@overload
+def eigvalsh(a: _ArrayLikeInt_co, UPLO: L["L", "U", "l", "u"] = ...) -> NDArray[float64]: ...
+@overload
+def eigvalsh(a: _ArrayLikeComplex_co, UPLO: L["L", "U", "l", "u"] = ...) -> NDArray[floating[Any]]: ...
+
+@overload
+def eig(a: _ArrayLikeInt_co) -> EigResult: ...
+@overload
+def eig(a: _ArrayLikeFloat_co) -> EigResult: ...
+@overload
+def eig(a: _ArrayLikeComplex_co) -> EigResult: ...
+
+@overload
+def eigh(
+    a: _ArrayLikeInt_co,
+    UPLO: L["L", "U", "l", "u"] = ...,
+) -> EighResult: ...
+@overload
+def eigh(
+    a: _ArrayLikeFloat_co,
+    UPLO: L["L", "U", "l", "u"] = ...,
+) -> EighResult: ...
+@overload
+def eigh(
+    a: _ArrayLikeComplex_co,
+    UPLO: L["L", "U", "l", "u"] = ...,
+) -> EighResult: ...
+
+@overload
+def svd(
+    a: _ArrayLikeInt_co,
+    full_matrices: bool = ...,
+    compute_uv: L[True] = ...,
+    hermitian: bool = ...,
+) -> SVDResult: ...
+@overload
+def svd(
+    a: _ArrayLikeFloat_co,
+    full_matrices: bool = ...,
+    compute_uv: L[True] = ...,
+    hermitian: bool = ...,
+) -> SVDResult: ...
+@overload
+def svd(
+    a: _ArrayLikeComplex_co,
+    full_matrices: bool = ...,
+    compute_uv: L[True] = ...,
+    hermitian: bool = ...,
+) -> SVDResult: ...
+@overload
+def svd(
+    a: _ArrayLikeInt_co,
+    full_matrices: bool = ...,
+    compute_uv: L[False] = ...,
+    hermitian: bool = ...,
+) -> NDArray[float64]: ...
+@overload
+def svd(
+    a: _ArrayLikeComplex_co,
+    full_matrices: bool = ...,
+    compute_uv: L[False] = ...,
+    hermitian: bool = ...,
+) -> NDArray[floating[Any]]: ...
+
+# TODO: Returns a scalar for 2D arrays and
+# a `(x.ndim - 2)`` dimensionl array otherwise
+def cond(x: _ArrayLikeComplex_co, p: None | float | L["fro", "nuc"] = ...) -> Any: ...
+
+# TODO: Returns `int` for <2D arrays and `intp` otherwise
+def matrix_rank(
+    A: _ArrayLikeComplex_co,
+    tol: None | _ArrayLikeFloat_co = ...,
+    hermitian: bool = ...,
+) -> Any: ...
+
+@overload
+def pinv(
+    a: _ArrayLikeInt_co,
+    rcond: _ArrayLikeFloat_co = ...,
+    hermitian: bool = ...,
+) -> NDArray[float64]: ...
+@overload
+def pinv(
+    a: _ArrayLikeFloat_co,
+    rcond: _ArrayLikeFloat_co = ...,
+    hermitian: bool = ...,
+) -> NDArray[floating[Any]]: ...
+@overload
+def pinv(
+    a: _ArrayLikeComplex_co,
+    rcond: _ArrayLikeFloat_co = ...,
+    hermitian: bool = ...,
+) -> NDArray[complexfloating[Any, Any]]: ...
+
+# TODO: Returns a 2-tuple of scalars for 2D arrays and
+# a 2-tuple of `(a.ndim - 2)`` dimensionl arrays otherwise
+def slogdet(a: _ArrayLikeComplex_co) -> SlogdetResult: ...
+
+# TODO: Returns a 2-tuple of scalars for 2D arrays and
+# a 2-tuple of `(a.ndim - 2)`` dimensionl arrays otherwise
+def det(a: _ArrayLikeComplex_co) -> Any: ...
+
+@overload
+def lstsq(a: _ArrayLikeInt_co, b: _ArrayLikeInt_co, rcond: None | float = ...) -> tuple[
+    NDArray[float64],
+    NDArray[float64],
+    int32,
+    NDArray[float64],
+]: ...
+@overload
+def lstsq(a: _ArrayLikeFloat_co, b: _ArrayLikeFloat_co, rcond: None | float = ...) -> tuple[
+    NDArray[floating[Any]],
+    NDArray[floating[Any]],
+    int32,
+    NDArray[floating[Any]],
+]: ...
+@overload
+def lstsq(a: _ArrayLikeComplex_co, b: _ArrayLikeComplex_co, rcond: None | float = ...) -> tuple[
+    NDArray[complexfloating[Any, Any]],
+    NDArray[floating[Any]],
+    int32,
+    NDArray[floating[Any]],
+]: ...
+
+@overload
+def norm(
+    x: ArrayLike,
+    ord: None | float | L["fro", "nuc"] = ...,
+    axis: None = ...,
+    keepdims: bool = ...,
+) -> floating[Any]: ...
+@overload
+def norm(
+    x: ArrayLike,
+    ord: None | float | L["fro", "nuc"] = ...,
+    axis: SupportsInt | SupportsIndex | tuple[int, ...] = ...,
+    keepdims: bool = ...,
+) -> Any: ...
+
+# TODO: Returns a scalar or array
+def multi_dot(
+    arrays: Iterable[_ArrayLikeComplex_co | _ArrayLikeObject_co | _ArrayLikeTD64_co],
+    *,
+    out: None | NDArray[Any] = ...,
+) -> Any: ...
diff --git a/venv/lib/python3.10/site-packages/numpy/linalg/tests/__init__.py b/venv/lib/python3.10/site-packages/numpy/linalg/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/venv/lib/python3.10/site-packages/numpy/linalg/tests/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/numpy/linalg/tests/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e2a505474531321adfc70cbbc9b04c3526c7a341
Binary files /dev/null and b/venv/lib/python3.10/site-packages/numpy/linalg/tests/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/numpy/linalg/tests/__pycache__/test_deprecations.cpython-310.pyc b/venv/lib/python3.10/site-packages/numpy/linalg/tests/__pycache__/test_deprecations.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3e19a6311ebe1526ccfc724714ef2139103637f3
Binary files /dev/null and b/venv/lib/python3.10/site-packages/numpy/linalg/tests/__pycache__/test_deprecations.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/numpy/linalg/tests/__pycache__/test_linalg.cpython-310.pyc b/venv/lib/python3.10/site-packages/numpy/linalg/tests/__pycache__/test_linalg.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4e414022af8983ee985717e554a4545cf644c965
Binary files /dev/null and b/venv/lib/python3.10/site-packages/numpy/linalg/tests/__pycache__/test_linalg.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/numpy/linalg/tests/__pycache__/test_regression.cpython-310.pyc b/venv/lib/python3.10/site-packages/numpy/linalg/tests/__pycache__/test_regression.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..58fc813efe41a05599afa01035a53d2d35546b4f
Binary files /dev/null and b/venv/lib/python3.10/site-packages/numpy/linalg/tests/__pycache__/test_regression.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/numpy/linalg/tests/test_deprecations.py b/venv/lib/python3.10/site-packages/numpy/linalg/tests/test_deprecations.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd4c10832e7e7240175571605a07541f0c188f89
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/numpy/linalg/tests/test_deprecations.py
@@ -0,0 +1,20 @@
+"""Test deprecation and future warnings.
+
+"""
+import numpy as np
+from numpy.testing import assert_warns
+
+
+def test_qr_mode_full_future_warning():
+    """Check mode='full' FutureWarning.
+
+    In numpy 1.8 the mode options 'full' and 'economic' in linalg.qr were
+    deprecated. The release date will probably be sometime in the summer
+    of 2013.
+
+    """
+    a = np.eye(2)
+    assert_warns(DeprecationWarning, np.linalg.qr, a, mode='full')
+    assert_warns(DeprecationWarning, np.linalg.qr, a, mode='f')
+    assert_warns(DeprecationWarning, np.linalg.qr, a, mode='economic')
+    assert_warns(DeprecationWarning, np.linalg.qr, a, mode='e')
diff --git a/venv/lib/python3.10/site-packages/numpy/linalg/tests/test_linalg.py b/venv/lib/python3.10/site-packages/numpy/linalg/tests/test_linalg.py
new file mode 100644
index 0000000000000000000000000000000000000000..5dabdfdf010a336741a1f89af101b36c4f62f5ab
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/numpy/linalg/tests/test_linalg.py
@@ -0,0 +1,2198 @@
+""" Test functions for linalg module
+
+"""
+import os
+import sys
+import itertools
+import traceback
+import textwrap
+import subprocess
+import pytest
+
+import numpy as np
+from numpy import array, single, double, csingle, cdouble, dot, identity, matmul
+from numpy.core import swapaxes
+from numpy import multiply, atleast_2d, inf, asarray
+from numpy import linalg
+from numpy.linalg import matrix_power, norm, matrix_rank, multi_dot, LinAlgError
+from numpy.linalg.linalg import _multi_dot_matrix_chain_order
+from numpy.testing import (
+    assert_, assert_equal, assert_raises, assert_array_equal,
+    assert_almost_equal, assert_allclose, suppress_warnings,
+    assert_raises_regex, HAS_LAPACK64, IS_WASM
+    )
+try:
+    import numpy.linalg.lapack_lite
+except ImportError:
+    # May be broken when numpy was built without BLAS/LAPACK present
+    # If so, ensure we don't break the whole test suite - the `lapack_lite`
+    # submodule should be removed, it's only used in two tests in this file.
+    pass
+
+
+def consistent_subclass(out, in_):
+    # For ndarray subclass input, our output should have the same subclass
+    # (non-ndarray input gets converted to ndarray).
+    return type(out) is (type(in_) if isinstance(in_, np.ndarray)
+                         else np.ndarray)
+
+
+old_assert_almost_equal = assert_almost_equal
+
+
+def assert_almost_equal(a, b, single_decimal=6, double_decimal=12, **kw):
+    if asarray(a).dtype.type in (single, csingle):
+        decimal = single_decimal
+    else:
+        decimal = double_decimal
+    old_assert_almost_equal(a, b, decimal=decimal, **kw)
+
+
+def get_real_dtype(dtype):
+    return {single: single, double: double,
+            csingle: single, cdouble: double}[dtype]
+
+
+def get_complex_dtype(dtype):
+    return {single: csingle, double: cdouble,
+            csingle: csingle, cdouble: cdouble}[dtype]
+
+
+def get_rtol(dtype):
+    # Choose a safe rtol
+    if dtype in (single, csingle):
+        return 1e-5
+    else:
+        return 1e-11
+
+
+# used to categorize tests
+all_tags = {
+  'square', 'nonsquare', 'hermitian',  # mutually exclusive
+  'generalized', 'size-0', 'strided' # optional additions
+}
+
+
+class LinalgCase:
+    def __init__(self, name, a, b, tags=set()):
+        """
+        A bundle of arguments to be passed to a test case, with an identifying
+        name, the operands a and b, and a set of tags to filter the tests
+        """
+        assert_(isinstance(name, str))
+        self.name = name
+        self.a = a
+        self.b = b
+        self.tags = frozenset(tags)  # prevent shared tags
+
+    def check(self, do):
+        """
+        Run the function `do` on this test case, expanding arguments
+        """
+        do(self.a, self.b, tags=self.tags)
+
+    def __repr__(self):
+        return f''
+
+
+def apply_tag(tag, cases):
+    """
+    Add the given tag (a string) to each of the cases (a list of LinalgCase
+    objects)
+    """
+    assert tag in all_tags, "Invalid tag"
+    for case in cases:
+        case.tags = case.tags | {tag}
+    return cases
+
+
+#
+# Base test cases
+#
+
+np.random.seed(1234)
+
+CASES = []
+
+# square test cases
+CASES += apply_tag('square', [
+    LinalgCase("single",
+               array([[1., 2.], [3., 4.]], dtype=single),
+               array([2., 1.], dtype=single)),
+    LinalgCase("double",
+               array([[1., 2.], [3., 4.]], dtype=double),
+               array([2., 1.], dtype=double)),
+    LinalgCase("double_2",
+               array([[1., 2.], [3., 4.]], dtype=double),
+               array([[2., 1., 4.], [3., 4., 6.]], dtype=double)),
+    LinalgCase("csingle",
+               array([[1. + 2j, 2 + 3j], [3 + 4j, 4 + 5j]], dtype=csingle),
+               array([2. + 1j, 1. + 2j], dtype=csingle)),
+    LinalgCase("cdouble",
+               array([[1. + 2j, 2 + 3j], [3 + 4j, 4 + 5j]], dtype=cdouble),
+               array([2. + 1j, 1. + 2j], dtype=cdouble)),
+    LinalgCase("cdouble_2",
+               array([[1. + 2j, 2 + 3j], [3 + 4j, 4 + 5j]], dtype=cdouble),
+               array([[2. + 1j, 1. + 2j, 1 + 3j], [1 - 2j, 1 - 3j, 1 - 6j]], dtype=cdouble)),
+    LinalgCase("0x0",
+               np.empty((0, 0), dtype=double),
+               np.empty((0,), dtype=double),
+               tags={'size-0'}),
+    LinalgCase("8x8",
+               np.random.rand(8, 8),
+               np.random.rand(8)),
+    LinalgCase("1x1",
+               np.random.rand(1, 1),
+               np.random.rand(1)),
+    LinalgCase("nonarray",
+               [[1, 2], [3, 4]],
+               [2, 1]),
+])
+
+# non-square test-cases
+CASES += apply_tag('nonsquare', [
+    LinalgCase("single_nsq_1",
+               array([[1., 2., 3.], [3., 4., 6.]], dtype=single),
+               array([2., 1.], dtype=single)),
+    LinalgCase("single_nsq_2",
+               array([[1., 2.], [3., 4.], [5., 6.]], dtype=single),
+               array([2., 1., 3.], dtype=single)),
+    LinalgCase("double_nsq_1",
+               array([[1., 2., 3.], [3., 4., 6.]], dtype=double),
+               array([2., 1.], dtype=double)),
+    LinalgCase("double_nsq_2",
+               array([[1., 2.], [3., 4.], [5., 6.]], dtype=double),
+               array([2., 1., 3.], dtype=double)),
+    LinalgCase("csingle_nsq_1",
+               array(
+                   [[1. + 1j, 2. + 2j, 3. - 3j], [3. - 5j, 4. + 9j, 6. + 2j]], dtype=csingle),
+               array([2. + 1j, 1. + 2j], dtype=csingle)),
+    LinalgCase("csingle_nsq_2",
+               array(
+                   [[1. + 1j, 2. + 2j], [3. - 3j, 4. - 9j], [5. - 4j, 6. + 8j]], dtype=csingle),
+               array([2. + 1j, 1. + 2j, 3. - 3j], dtype=csingle)),
+    LinalgCase("cdouble_nsq_1",
+               array(
+                   [[1. + 1j, 2. + 2j, 3. - 3j], [3. - 5j, 4. + 9j, 6. + 2j]], dtype=cdouble),
+               array([2. + 1j, 1. + 2j], dtype=cdouble)),
+    LinalgCase("cdouble_nsq_2",
+               array(
+                   [[1. + 1j, 2. + 2j], [3. - 3j, 4. - 9j], [5. - 4j, 6. + 8j]], dtype=cdouble),
+               array([2. + 1j, 1. + 2j, 3. - 3j], dtype=cdouble)),
+    LinalgCase("cdouble_nsq_1_2",
+               array(
+                   [[1. + 1j, 2. + 2j, 3. - 3j], [3. - 5j, 4. + 9j, 6. + 2j]], dtype=cdouble),
+               array([[2. + 1j, 1. + 2j], [1 - 1j, 2 - 2j]], dtype=cdouble)),
+    LinalgCase("cdouble_nsq_2_2",
+               array(
+                   [[1. + 1j, 2. + 2j], [3. - 3j, 4. - 9j], [5. - 4j, 6. + 8j]], dtype=cdouble),
+               array([[2. + 1j, 1. + 2j], [1 - 1j, 2 - 2j], [1 - 1j, 2 - 2j]], dtype=cdouble)),
+    LinalgCase("8x11",
+               np.random.rand(8, 11),
+               np.random.rand(8)),
+    LinalgCase("1x5",
+               np.random.rand(1, 5),
+               np.random.rand(1)),
+    LinalgCase("5x1",
+               np.random.rand(5, 1),
+               np.random.rand(5)),
+    LinalgCase("0x4",
+               np.random.rand(0, 4),
+               np.random.rand(0),
+               tags={'size-0'}),
+    LinalgCase("4x0",
+               np.random.rand(4, 0),
+               np.random.rand(4),
+               tags={'size-0'}),
+])
+
+# hermitian test-cases
+CASES += apply_tag('hermitian', [
+    LinalgCase("hsingle",
+               array([[1., 2.], [2., 1.]], dtype=single),
+               None),
+    LinalgCase("hdouble",
+               array([[1., 2.], [2., 1.]], dtype=double),
+               None),
+    LinalgCase("hcsingle",
+               array([[1., 2 + 3j], [2 - 3j, 1]], dtype=csingle),
+               None),
+    LinalgCase("hcdouble",
+               array([[1., 2 + 3j], [2 - 3j, 1]], dtype=cdouble),
+               None),
+    LinalgCase("hempty",
+               np.empty((0, 0), dtype=double),
+               None,
+               tags={'size-0'}),
+    LinalgCase("hnonarray",
+               [[1, 2], [2, 1]],
+               None),
+    LinalgCase("matrix_b_only",
+               array([[1., 2.], [2., 1.]]),
+               None),
+    LinalgCase("hmatrix_1x1",
+               np.random.rand(1, 1),
+               None),
+])
+
+
+#
+# Gufunc test cases
+#
+def _make_generalized_cases():
+    new_cases = []
+
+    for case in CASES:
+        if not isinstance(case.a, np.ndarray):
+            continue
+
+        a = np.array([case.a, 2 * case.a, 3 * case.a])
+        if case.b is None:
+            b = None
+        else:
+            b = np.array([case.b, 7 * case.b, 6 * case.b])
+        new_case = LinalgCase(case.name + "_tile3", a, b,
+                              tags=case.tags | {'generalized'})
+        new_cases.append(new_case)
+
+        a = np.array([case.a] * 2 * 3).reshape((3, 2) + case.a.shape)
+        if case.b is None:
+            b = None
+        else:
+            b = np.array([case.b] * 2 * 3).reshape((3, 2) + case.b.shape)
+        new_case = LinalgCase(case.name + "_tile213", a, b,
+                              tags=case.tags | {'generalized'})
+        new_cases.append(new_case)
+
+    return new_cases
+
+
+CASES += _make_generalized_cases()
+
+
+#
+# Generate stride combination variations of the above
+#
+def _stride_comb_iter(x):
+    """
+    Generate cartesian product of strides for all axes
+    """
+
+    if not isinstance(x, np.ndarray):
+        yield x, "nop"
+        return
+
+    stride_set = [(1,)] * x.ndim
+    stride_set[-1] = (1, 3, -4)
+    if x.ndim > 1:
+        stride_set[-2] = (1, 3, -4)
+    if x.ndim > 2:
+        stride_set[-3] = (1, -4)
+
+    for repeats in itertools.product(*tuple(stride_set)):
+        new_shape = [abs(a * b) for a, b in zip(x.shape, repeats)]
+        slices = tuple([slice(None, None, repeat) for repeat in repeats])
+
+        # new array with different strides, but same data
+        xi = np.empty(new_shape, dtype=x.dtype)
+        xi.view(np.uint32).fill(0xdeadbeef)
+        xi = xi[slices]
+        xi[...] = x
+        xi = xi.view(x.__class__)
+        assert_(np.all(xi == x))
+        yield xi, "stride_" + "_".join(["%+d" % j for j in repeats])
+
+        # generate also zero strides if possible
+        if x.ndim >= 1 and x.shape[-1] == 1:
+            s = list(x.strides)
+            s[-1] = 0
+            xi = np.lib.stride_tricks.as_strided(x, strides=s)
+            yield xi, "stride_xxx_0"
+        if x.ndim >= 2 and x.shape[-2] == 1:
+            s = list(x.strides)
+            s[-2] = 0
+            xi = np.lib.stride_tricks.as_strided(x, strides=s)
+            yield xi, "stride_xxx_0_x"
+        if x.ndim >= 2 and x.shape[:-2] == (1, 1):
+            s = list(x.strides)
+            s[-1] = 0
+            s[-2] = 0
+            xi = np.lib.stride_tricks.as_strided(x, strides=s)
+            yield xi, "stride_xxx_0_0"
+
+
+def _make_strided_cases():
+    new_cases = []
+    for case in CASES:
+        for a, a_label in _stride_comb_iter(case.a):
+            for b, b_label in _stride_comb_iter(case.b):
+                new_case = LinalgCase(case.name + "_" + a_label + "_" + b_label, a, b,
+                                      tags=case.tags | {'strided'})
+                new_cases.append(new_case)
+    return new_cases
+
+
+CASES += _make_strided_cases()
+
+
+#
+# Test different routines against the above cases
+#
+class LinalgTestCase:
+    TEST_CASES = CASES
+
+    def check_cases(self, require=set(), exclude=set()):
+        """
+        Run func on each of the cases with all of the tags in require, and none
+        of the tags in exclude
+        """
+        for case in self.TEST_CASES:
+            # filter by require and exclude
+            if case.tags & require != require:
+                continue
+            if case.tags & exclude:
+                continue
+
+            try:
+                case.check(self.do)
+            except Exception as e:
+                msg = f'In test case: {case!r}\n\n'
+                msg += traceback.format_exc()
+                raise AssertionError(msg) from e
+
+
+class LinalgSquareTestCase(LinalgTestCase):
+
+    def test_sq_cases(self):
+        self.check_cases(require={'square'},
+                         exclude={'generalized', 'size-0'})
+
+    def test_empty_sq_cases(self):
+        self.check_cases(require={'square', 'size-0'},
+                         exclude={'generalized'})
+
+
+class LinalgNonsquareTestCase(LinalgTestCase):
+
+    def test_nonsq_cases(self):
+        self.check_cases(require={'nonsquare'},
+                         exclude={'generalized', 'size-0'})
+
+    def test_empty_nonsq_cases(self):
+        self.check_cases(require={'nonsquare', 'size-0'},
+                         exclude={'generalized'})
+
+
+class HermitianTestCase(LinalgTestCase):
+
+    def test_herm_cases(self):
+        self.check_cases(require={'hermitian'},
+                         exclude={'generalized', 'size-0'})
+
+    def test_empty_herm_cases(self):
+        self.check_cases(require={'hermitian', 'size-0'},
+                         exclude={'generalized'})
+
+
+class LinalgGeneralizedSquareTestCase(LinalgTestCase):
+
+    @pytest.mark.slow
+    def test_generalized_sq_cases(self):
+        self.check_cases(require={'generalized', 'square'},
+                         exclude={'size-0'})
+
+    @pytest.mark.slow
+    def test_generalized_empty_sq_cases(self):
+        self.check_cases(require={'generalized', 'square', 'size-0'})
+
+
+class LinalgGeneralizedNonsquareTestCase(LinalgTestCase):
+
+    @pytest.mark.slow
+    def test_generalized_nonsq_cases(self):
+        self.check_cases(require={'generalized', 'nonsquare'},
+                         exclude={'size-0'})
+
+    @pytest.mark.slow
+    def test_generalized_empty_nonsq_cases(self):
+        self.check_cases(require={'generalized', 'nonsquare', 'size-0'})
+
+
+class HermitianGeneralizedTestCase(LinalgTestCase):
+
+    @pytest.mark.slow
+    def test_generalized_herm_cases(self):
+        self.check_cases(require={'generalized', 'hermitian'},
+                         exclude={'size-0'})
+
+    @pytest.mark.slow
+    def test_generalized_empty_herm_cases(self):
+        self.check_cases(require={'generalized', 'hermitian', 'size-0'},
+                         exclude={'none'})
+
+
+def dot_generalized(a, b):
+    a = asarray(a)
+    if a.ndim >= 3:
+        if a.ndim == b.ndim:
+            # matrix x matrix
+            new_shape = a.shape[:-1] + b.shape[-1:]
+        elif a.ndim == b.ndim + 1:
+            # matrix x vector
+            new_shape = a.shape[:-1]
+        else:
+            raise ValueError("Not implemented...")
+        r = np.empty(new_shape, dtype=np.common_type(a, b))
+        for c in itertools.product(*map(range, a.shape[:-2])):
+            r[c] = dot(a[c], b[c])
+        return r
+    else:
+        return dot(a, b)
+
+
+def identity_like_generalized(a):
+    a = asarray(a)
+    if a.ndim >= 3:
+        r = np.empty(a.shape, dtype=a.dtype)
+        r[...] = identity(a.shape[-2])
+        return r
+    else:
+        return identity(a.shape[0])
+
+
+class SolveCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase):
+    # kept apart from TestSolve for use for testing with matrices.
+    def do(self, a, b, tags):
+        x = linalg.solve(a, b)
+        assert_almost_equal(b, dot_generalized(a, x))
+        assert_(consistent_subclass(x, b))
+
+
+class TestSolve(SolveCases):
+    @pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
+    def test_types(self, dtype):
+        x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
+        assert_equal(linalg.solve(x, x).dtype, dtype)
+
+    def test_0_size(self):
+        class ArraySubclass(np.ndarray):
+            pass
+        # Test system of 0x0 matrices
+        a = np.arange(8).reshape(2, 2, 2)
+        b = np.arange(6).reshape(1, 2, 3).view(ArraySubclass)
+
+        expected = linalg.solve(a, b)[:, 0:0, :]
+        result = linalg.solve(a[:, 0:0, 0:0], b[:, 0:0, :])
+        assert_array_equal(result, expected)
+        assert_(isinstance(result, ArraySubclass))
+
+        # Test errors for non-square and only b's dimension being 0
+        assert_raises(linalg.LinAlgError, linalg.solve, a[:, 0:0, 0:1], b)
+        assert_raises(ValueError, linalg.solve, a, b[:, 0:0, :])
+
+        # Test broadcasting error
+        b = np.arange(6).reshape(1, 3, 2)  # broadcasting error
+        assert_raises(ValueError, linalg.solve, a, b)
+        assert_raises(ValueError, linalg.solve, a[0:0], b[0:0])
+
+        # Test zero "single equations" with 0x0 matrices.
+        b = np.arange(2).reshape(1, 2).view(ArraySubclass)
+        expected = linalg.solve(a, b)[:, 0:0]
+        result = linalg.solve(a[:, 0:0, 0:0], b[:, 0:0])
+        assert_array_equal(result, expected)
+        assert_(isinstance(result, ArraySubclass))
+
+        b = np.arange(3).reshape(1, 3)
+        assert_raises(ValueError, linalg.solve, a, b)
+        assert_raises(ValueError, linalg.solve, a[0:0], b[0:0])
+        assert_raises(ValueError, linalg.solve, a[:, 0:0, 0:0], b)
+
+    def test_0_size_k(self):
+        # test zero multiple equation (K=0) case.
+        class ArraySubclass(np.ndarray):
+            pass
+        a = np.arange(4).reshape(1, 2, 2)
+        b = np.arange(6).reshape(3, 2, 1).view(ArraySubclass)
+
+        expected = linalg.solve(a, b)[:, :, 0:0]
+        result = linalg.solve(a, b[:, :, 0:0])
+        assert_array_equal(result, expected)
+        assert_(isinstance(result, ArraySubclass))
+
+        # test both zero.
+        expected = linalg.solve(a, b)[:, 0:0, 0:0]
+        result = linalg.solve(a[:, 0:0, 0:0], b[:, 0:0, 0:0])
+        assert_array_equal(result, expected)
+        assert_(isinstance(result, ArraySubclass))
+
+
+class InvCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase):
+
+    def do(self, a, b, tags):
+        a_inv = linalg.inv(a)
+        assert_almost_equal(dot_generalized(a, a_inv),
+                            identity_like_generalized(a))
+        assert_(consistent_subclass(a_inv, a))
+
+
+class TestInv(InvCases):
+    @pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
+    def test_types(self, dtype):
+        x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
+        assert_equal(linalg.inv(x).dtype, dtype)
+
+    def test_0_size(self):
+        # Check that all kinds of 0-sized arrays work
+        class ArraySubclass(np.ndarray):
+            pass
+        a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
+        res = linalg.inv(a)
+        assert_(res.dtype.type is np.float64)
+        assert_equal(a.shape, res.shape)
+        assert_(isinstance(res, ArraySubclass))
+
+        a = np.zeros((0, 0), dtype=np.complex64).view(ArraySubclass)
+        res = linalg.inv(a)
+        assert_(res.dtype.type is np.complex64)
+        assert_equal(a.shape, res.shape)
+        assert_(isinstance(res, ArraySubclass))
+
+
+class EigvalsCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase):
+
+    def do(self, a, b, tags):
+        ev = linalg.eigvals(a)
+        evalues, evectors = linalg.eig(a)
+        assert_almost_equal(ev, evalues)
+
+
+class TestEigvals(EigvalsCases):
+    @pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
+    def test_types(self, dtype):
+        x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
+        assert_equal(linalg.eigvals(x).dtype, dtype)
+        x = np.array([[1, 0.5], [-1, 1]], dtype=dtype)
+        assert_equal(linalg.eigvals(x).dtype, get_complex_dtype(dtype))
+
+    def test_0_size(self):
+        # Check that all kinds of 0-sized arrays work
+        class ArraySubclass(np.ndarray):
+            pass
+        a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
+        res = linalg.eigvals(a)
+        assert_(res.dtype.type is np.float64)
+        assert_equal((0, 1), res.shape)
+        # This is just for documentation, it might make sense to change:
+        assert_(isinstance(res, np.ndarray))
+
+        a = np.zeros((0, 0), dtype=np.complex64).view(ArraySubclass)
+        res = linalg.eigvals(a)
+        assert_(res.dtype.type is np.complex64)
+        assert_equal((0,), res.shape)
+        # This is just for documentation, it might make sense to change:
+        assert_(isinstance(res, np.ndarray))
+
+
+class EigCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase):
+
+    def do(self, a, b, tags):
+        res = linalg.eig(a)
+        eigenvalues, eigenvectors = res.eigenvalues, res.eigenvectors
+        assert_allclose(dot_generalized(a, eigenvectors),
+                        np.asarray(eigenvectors) * np.asarray(eigenvalues)[..., None, :],
+                        rtol=get_rtol(eigenvalues.dtype))
+        assert_(consistent_subclass(eigenvectors, a))
+
+
+class TestEig(EigCases):
+    @pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
+    def test_types(self, dtype):
+        x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
+        w, v = np.linalg.eig(x)
+        assert_equal(w.dtype, dtype)
+        assert_equal(v.dtype, dtype)
+
+        x = np.array([[1, 0.5], [-1, 1]], dtype=dtype)
+        w, v = np.linalg.eig(x)
+        assert_equal(w.dtype, get_complex_dtype(dtype))
+        assert_equal(v.dtype, get_complex_dtype(dtype))
+
+    def test_0_size(self):
+        # Check that all kinds of 0-sized arrays work
+        class ArraySubclass(np.ndarray):
+            pass
+        a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
+        res, res_v = linalg.eig(a)
+        assert_(res_v.dtype.type is np.float64)
+        assert_(res.dtype.type is np.float64)
+        assert_equal(a.shape, res_v.shape)
+        assert_equal((0, 1), res.shape)
+        # This is just for documentation, it might make sense to change:
+        assert_(isinstance(a, np.ndarray))
+
+        a = np.zeros((0, 0), dtype=np.complex64).view(ArraySubclass)
+        res, res_v = linalg.eig(a)
+        assert_(res_v.dtype.type is np.complex64)
+        assert_(res.dtype.type is np.complex64)
+        assert_equal(a.shape, res_v.shape)
+        assert_equal((0,), res.shape)
+        # This is just for documentation, it might make sense to change:
+        assert_(isinstance(a, np.ndarray))
+
+
+class SVDBaseTests:
+    hermitian = False
+
+    @pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
+    def test_types(self, dtype):
+        x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
+        res = linalg.svd(x)
+        U, S, Vh = res.U, res.S, res.Vh
+        assert_equal(U.dtype, dtype)
+        assert_equal(S.dtype, get_real_dtype(dtype))
+        assert_equal(Vh.dtype, dtype)
+        s = linalg.svd(x, compute_uv=False, hermitian=self.hermitian)
+        assert_equal(s.dtype, get_real_dtype(dtype))
+
+
+class SVDCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase):
+
+    def do(self, a, b, tags):
+        u, s, vt = linalg.svd(a, False)
+        assert_allclose(a, dot_generalized(np.asarray(u) * np.asarray(s)[..., None, :],
+                                           np.asarray(vt)),
+                        rtol=get_rtol(u.dtype))
+        assert_(consistent_subclass(u, a))
+        assert_(consistent_subclass(vt, a))
+
+
+class TestSVD(SVDCases, SVDBaseTests):
+    def test_empty_identity(self):
+        """ Empty input should put an identity matrix in u or vh """
+        x = np.empty((4, 0))
+        u, s, vh = linalg.svd(x, compute_uv=True, hermitian=self.hermitian)
+        assert_equal(u.shape, (4, 4))
+        assert_equal(vh.shape, (0, 0))
+        assert_equal(u, np.eye(4))
+
+        x = np.empty((0, 4))
+        u, s, vh = linalg.svd(x, compute_uv=True, hermitian=self.hermitian)
+        assert_equal(u.shape, (0, 0))
+        assert_equal(vh.shape, (4, 4))
+        assert_equal(vh, np.eye(4))
+
+
+class SVDHermitianCases(HermitianTestCase, HermitianGeneralizedTestCase):
+
+    def do(self, a, b, tags):
+        u, s, vt = linalg.svd(a, False, hermitian=True)
+        assert_allclose(a, dot_generalized(np.asarray(u) * np.asarray(s)[..., None, :],
+                                           np.asarray(vt)),
+                        rtol=get_rtol(u.dtype))
+        def hermitian(mat):
+            axes = list(range(mat.ndim))
+            axes[-1], axes[-2] = axes[-2], axes[-1]
+            return np.conj(np.transpose(mat, axes=axes))
+
+        assert_almost_equal(np.matmul(u, hermitian(u)), np.broadcast_to(np.eye(u.shape[-1]), u.shape))
+        assert_almost_equal(np.matmul(vt, hermitian(vt)), np.broadcast_to(np.eye(vt.shape[-1]), vt.shape))
+        assert_equal(np.sort(s)[..., ::-1], s)
+        assert_(consistent_subclass(u, a))
+        assert_(consistent_subclass(vt, a))
+
+
+class TestSVDHermitian(SVDHermitianCases, SVDBaseTests):
+    hermitian = True
+
+
+class CondCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase):
+    # cond(x, p) for p in (None, 2, -2)
+
+    def do(self, a, b, tags):
+        c = asarray(a)  # a might be a matrix
+        if 'size-0' in tags:
+            assert_raises(LinAlgError, linalg.cond, c)
+            return
+
+        # +-2 norms
+        s = linalg.svd(c, compute_uv=False)
+        assert_almost_equal(
+            linalg.cond(a), s[..., 0] / s[..., -1],
+            single_decimal=5, double_decimal=11)
+        assert_almost_equal(
+            linalg.cond(a, 2), s[..., 0] / s[..., -1],
+            single_decimal=5, double_decimal=11)
+        assert_almost_equal(
+            linalg.cond(a, -2), s[..., -1] / s[..., 0],
+            single_decimal=5, double_decimal=11)
+
+        # Other norms
+        cinv = np.linalg.inv(c)
+        assert_almost_equal(
+            linalg.cond(a, 1),
+            abs(c).sum(-2).max(-1) * abs(cinv).sum(-2).max(-1),
+            single_decimal=5, double_decimal=11)
+        assert_almost_equal(
+            linalg.cond(a, -1),
+            abs(c).sum(-2).min(-1) * abs(cinv).sum(-2).min(-1),
+            single_decimal=5, double_decimal=11)
+        assert_almost_equal(
+            linalg.cond(a, np.inf),
+            abs(c).sum(-1).max(-1) * abs(cinv).sum(-1).max(-1),
+            single_decimal=5, double_decimal=11)
+        assert_almost_equal(
+            linalg.cond(a, -np.inf),
+            abs(c).sum(-1).min(-1) * abs(cinv).sum(-1).min(-1),
+            single_decimal=5, double_decimal=11)
+        assert_almost_equal(
+            linalg.cond(a, 'fro'),
+            np.sqrt((abs(c)**2).sum(-1).sum(-1)
+                    * (abs(cinv)**2).sum(-1).sum(-1)),
+            single_decimal=5, double_decimal=11)
+
+
+class TestCond(CondCases):
+    def test_basic_nonsvd(self):
+        # Smoketest the non-svd norms
+        A = array([[1., 0, 1], [0, -2., 0], [0, 0, 3.]])
+        assert_almost_equal(linalg.cond(A, inf), 4)
+        assert_almost_equal(linalg.cond(A, -inf), 2/3)
+        assert_almost_equal(linalg.cond(A, 1), 4)
+        assert_almost_equal(linalg.cond(A, -1), 0.5)
+        assert_almost_equal(linalg.cond(A, 'fro'), np.sqrt(265 / 12))
+
+    def test_singular(self):
+        # Singular matrices have infinite condition number for
+        # positive norms, and negative norms shouldn't raise
+        # exceptions
+        As = [np.zeros((2, 2)), np.ones((2, 2))]
+        p_pos = [None, 1, 2, 'fro']
+        p_neg = [-1, -2]
+        for A, p in itertools.product(As, p_pos):
+            # Inversion may not hit exact infinity, so just check the
+            # number is large
+            assert_(linalg.cond(A, p) > 1e15)
+        for A, p in itertools.product(As, p_neg):
+            linalg.cond(A, p)
+
+    @pytest.mark.xfail(True, run=False,
+                       reason="Platform/LAPACK-dependent failure, "
+                              "see gh-18914")
+    def test_nan(self):
+        # nans should be passed through, not converted to infs
+        ps = [None, 1, -1, 2, -2, 'fro']
+        p_pos = [None, 1, 2, 'fro']
+
+        A = np.ones((2, 2))
+        A[0,1] = np.nan
+        for p in ps:
+            c = linalg.cond(A, p)
+            assert_(isinstance(c, np.float_))
+            assert_(np.isnan(c))
+
+        A = np.ones((3, 2, 2))
+        A[1,0,1] = np.nan
+        for p in ps:
+            c = linalg.cond(A, p)
+            assert_(np.isnan(c[1]))
+            if p in p_pos:
+                assert_(c[0] > 1e15)
+                assert_(c[2] > 1e15)
+            else:
+                assert_(not np.isnan(c[0]))
+                assert_(not np.isnan(c[2]))
+
+    def test_stacked_singular(self):
+        # Check behavior when only some of the stacked matrices are
+        # singular
+        np.random.seed(1234)
+        A = np.random.rand(2, 2, 2, 2)
+        A[0,0] = 0
+        A[1,1] = 0
+
+        for p in (None, 1, 2, 'fro', -1, -2):
+            c = linalg.cond(A, p)
+            assert_equal(c[0,0], np.inf)
+            assert_equal(c[1,1], np.inf)
+            assert_(np.isfinite(c[0,1]))
+            assert_(np.isfinite(c[1,0]))
+
+
+class PinvCases(LinalgSquareTestCase,
+                LinalgNonsquareTestCase,
+                LinalgGeneralizedSquareTestCase,
+                LinalgGeneralizedNonsquareTestCase):
+
+    def do(self, a, b, tags):
+        a_ginv = linalg.pinv(a)
+        # `a @ a_ginv == I` does not hold if a is singular
+        dot = dot_generalized
+        assert_almost_equal(dot(dot(a, a_ginv), a), a, single_decimal=5, double_decimal=11)
+        assert_(consistent_subclass(a_ginv, a))
+
+
+class TestPinv(PinvCases):
+    pass
+
+
+class PinvHermitianCases(HermitianTestCase, HermitianGeneralizedTestCase):
+
+    def do(self, a, b, tags):
+        a_ginv = linalg.pinv(a, hermitian=True)
+        # `a @ a_ginv == I` does not hold if a is singular
+        dot = dot_generalized
+        assert_almost_equal(dot(dot(a, a_ginv), a), a, single_decimal=5, double_decimal=11)
+        assert_(consistent_subclass(a_ginv, a))
+
+
+class TestPinvHermitian(PinvHermitianCases):
+    pass
+
+
+class DetCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase):
+
+    def do(self, a, b, tags):
+        d = linalg.det(a)
+        res = linalg.slogdet(a)
+        s, ld = res.sign, res.logabsdet
+        if asarray(a).dtype.type in (single, double):
+            ad = asarray(a).astype(double)
+        else:
+            ad = asarray(a).astype(cdouble)
+        ev = linalg.eigvals(ad)
+        assert_almost_equal(d, multiply.reduce(ev, axis=-1))
+        assert_almost_equal(s * np.exp(ld), multiply.reduce(ev, axis=-1))
+
+        s = np.atleast_1d(s)
+        ld = np.atleast_1d(ld)
+        m = (s != 0)
+        assert_almost_equal(np.abs(s[m]), 1)
+        assert_equal(ld[~m], -inf)
+
+
+class TestDet(DetCases):
+    def test_zero(self):
+        assert_equal(linalg.det([[0.0]]), 0.0)
+        assert_equal(type(linalg.det([[0.0]])), double)
+        assert_equal(linalg.det([[0.0j]]), 0.0)
+        assert_equal(type(linalg.det([[0.0j]])), cdouble)
+
+        assert_equal(linalg.slogdet([[0.0]]), (0.0, -inf))
+        assert_equal(type(linalg.slogdet([[0.0]])[0]), double)
+        assert_equal(type(linalg.slogdet([[0.0]])[1]), double)
+        assert_equal(linalg.slogdet([[0.0j]]), (0.0j, -inf))
+        assert_equal(type(linalg.slogdet([[0.0j]])[0]), cdouble)
+        assert_equal(type(linalg.slogdet([[0.0j]])[1]), double)
+
+    @pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
+    def test_types(self, dtype):
+        x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
+        assert_equal(np.linalg.det(x).dtype, dtype)
+        ph, s = np.linalg.slogdet(x)
+        assert_equal(s.dtype, get_real_dtype(dtype))
+        assert_equal(ph.dtype, dtype)
+
+    def test_0_size(self):
+        a = np.zeros((0, 0), dtype=np.complex64)
+        res = linalg.det(a)
+        assert_equal(res, 1.)
+        assert_(res.dtype.type is np.complex64)
+        res = linalg.slogdet(a)
+        assert_equal(res, (1, 0))
+        assert_(res[0].dtype.type is np.complex64)
+        assert_(res[1].dtype.type is np.float32)
+
+        a = np.zeros((0, 0), dtype=np.float64)
+        res = linalg.det(a)
+        assert_equal(res, 1.)
+        assert_(res.dtype.type is np.float64)
+        res = linalg.slogdet(a)
+        assert_equal(res, (1, 0))
+        assert_(res[0].dtype.type is np.float64)
+        assert_(res[1].dtype.type is np.float64)
+
+
+class LstsqCases(LinalgSquareTestCase, LinalgNonsquareTestCase):
+
+    def do(self, a, b, tags):
+        arr = np.asarray(a)
+        m, n = arr.shape
+        u, s, vt = linalg.svd(a, False)
+        x, residuals, rank, sv = linalg.lstsq(a, b, rcond=-1)
+        if m == 0:
+            assert_((x == 0).all())
+        if m <= n:
+            assert_almost_equal(b, dot(a, x))
+            assert_equal(rank, m)
+        else:
+            assert_equal(rank, n)
+        assert_almost_equal(sv, sv.__array_wrap__(s))
+        if rank == n and m > n:
+            expect_resids = (
+                np.asarray(abs(np.dot(a, x) - b)) ** 2).sum(axis=0)
+            expect_resids = np.asarray(expect_resids)
+            if np.asarray(b).ndim == 1:
+                expect_resids.shape = (1,)
+                assert_equal(residuals.shape, expect_resids.shape)
+        else:
+            expect_resids = np.array([]).view(type(x))
+        assert_almost_equal(residuals, expect_resids)
+        assert_(np.issubdtype(residuals.dtype, np.floating))
+        assert_(consistent_subclass(x, b))
+        assert_(consistent_subclass(residuals, b))
+
+
+class TestLstsq(LstsqCases):
+    def test_future_rcond(self):
+        a = np.array([[0., 1.,  0.,  1.,  2.,  0.],
+                      [0., 2.,  0.,  0.,  1.,  0.],
+                      [1., 0.,  1.,  0.,  0.,  4.],
+                      [0., 0.,  0.,  2.,  3.,  0.]]).T
+
+        b = np.array([1, 0, 0, 0, 0, 0])
+        with suppress_warnings() as sup:
+            w = sup.record(FutureWarning, "`rcond` parameter will change")
+            x, residuals, rank, s = linalg.lstsq(a, b)
+            assert_(rank == 4)
+            x, residuals, rank, s = linalg.lstsq(a, b, rcond=-1)
+            assert_(rank == 4)
+            x, residuals, rank, s = linalg.lstsq(a, b, rcond=None)
+            assert_(rank == 3)
+            # Warning should be raised exactly once (first command)
+            assert_(len(w) == 1)
+
+    @pytest.mark.parametrize(["m", "n", "n_rhs"], [
+        (4, 2, 2),
+        (0, 4, 1),
+        (0, 4, 2),
+        (4, 0, 1),
+        (4, 0, 2),
+        (4, 2, 0),
+        (0, 0, 0)
+    ])
+    def test_empty_a_b(self, m, n, n_rhs):
+        a = np.arange(m * n).reshape(m, n)
+        b = np.ones((m, n_rhs))
+        x, residuals, rank, s = linalg.lstsq(a, b, rcond=None)
+        if m == 0:
+            assert_((x == 0).all())
+        assert_equal(x.shape, (n, n_rhs))
+        assert_equal(residuals.shape, ((n_rhs,) if m > n else (0,)))
+        if m > n and n_rhs > 0:
+            # residuals are exactly the squared norms of b's columns
+            r = b - np.dot(a, x)
+            assert_almost_equal(residuals, (r * r).sum(axis=-2))
+        assert_equal(rank, min(m, n))
+        assert_equal(s.shape, (min(m, n),))
+
+    def test_incompatible_dims(self):
+        # use modified version of docstring example
+        x = np.array([0, 1, 2, 3])
+        y = np.array([-1, 0.2, 0.9, 2.1, 3.3])
+        A = np.vstack([x, np.ones(len(x))]).T
+        with assert_raises_regex(LinAlgError, "Incompatible dimensions"):
+            linalg.lstsq(A, y, rcond=None)
+
+
+@pytest.mark.parametrize('dt', [np.dtype(c) for c in '?bBhHiIqQefdgFDGO'])
+class TestMatrixPower:
+
+    rshft_0 = np.eye(4)
+    rshft_1 = rshft_0[[3, 0, 1, 2]]
+    rshft_2 = rshft_0[[2, 3, 0, 1]]
+    rshft_3 = rshft_0[[1, 2, 3, 0]]
+    rshft_all = [rshft_0, rshft_1, rshft_2, rshft_3]
+    noninv = array([[1, 0], [0, 0]])
+    stacked = np.block([[[rshft_0]]]*2)
+    #FIXME the 'e' dtype might work in future
+    dtnoinv = [object, np.dtype('e'), np.dtype('g'), np.dtype('G')]
+
+    def test_large_power(self, dt):
+        rshft = self.rshft_1.astype(dt)
+        assert_equal(
+            matrix_power(rshft, 2**100 + 2**10 + 2**5 + 0), self.rshft_0)
+        assert_equal(
+            matrix_power(rshft, 2**100 + 2**10 + 2**5 + 1), self.rshft_1)
+        assert_equal(
+            matrix_power(rshft, 2**100 + 2**10 + 2**5 + 2), self.rshft_2)
+        assert_equal(
+            matrix_power(rshft, 2**100 + 2**10 + 2**5 + 3), self.rshft_3)
+
+    def test_power_is_zero(self, dt):
+        def tz(M):
+            mz = matrix_power(M, 0)
+            assert_equal(mz, identity_like_generalized(M))
+            assert_equal(mz.dtype, M.dtype)
+
+        for mat in self.rshft_all:
+            tz(mat.astype(dt))
+            if dt != object:
+                tz(self.stacked.astype(dt))
+
+    def test_power_is_one(self, dt):
+        def tz(mat):
+            mz = matrix_power(mat, 1)
+            assert_equal(mz, mat)
+            assert_equal(mz.dtype, mat.dtype)
+
+        for mat in self.rshft_all:
+            tz(mat.astype(dt))
+            if dt != object:
+                tz(self.stacked.astype(dt))
+
+    def test_power_is_two(self, dt):
+        def tz(mat):
+            mz = matrix_power(mat, 2)
+            mmul = matmul if mat.dtype != object else dot
+            assert_equal(mz, mmul(mat, mat))
+            assert_equal(mz.dtype, mat.dtype)
+
+        for mat in self.rshft_all:
+            tz(mat.astype(dt))
+            if dt != object:
+                tz(self.stacked.astype(dt))
+
+    def test_power_is_minus_one(self, dt):
+        def tz(mat):
+            invmat = matrix_power(mat, -1)
+            mmul = matmul if mat.dtype != object else dot
+            assert_almost_equal(
+                mmul(invmat, mat), identity_like_generalized(mat))
+
+        for mat in self.rshft_all:
+            if dt not in self.dtnoinv:
+                tz(mat.astype(dt))
+
+    def test_exceptions_bad_power(self, dt):
+        mat = self.rshft_0.astype(dt)
+        assert_raises(TypeError, matrix_power, mat, 1.5)
+        assert_raises(TypeError, matrix_power, mat, [1])
+
+    def test_exceptions_non_square(self, dt):
+        assert_raises(LinAlgError, matrix_power, np.array([1], dt), 1)
+        assert_raises(LinAlgError, matrix_power, np.array([[1], [2]], dt), 1)
+        assert_raises(LinAlgError, matrix_power, np.ones((4, 3, 2), dt), 1)
+
+    @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
+    def test_exceptions_not_invertible(self, dt):
+        if dt in self.dtnoinv:
+            return
+        mat = self.noninv.astype(dt)
+        assert_raises(LinAlgError, matrix_power, mat, -1)
+
+
+class TestEigvalshCases(HermitianTestCase, HermitianGeneralizedTestCase):
+
+    def do(self, a, b, tags):
+        # note that eigenvalue arrays returned by eig must be sorted since
+        # their order isn't guaranteed.
+        ev = linalg.eigvalsh(a, 'L')
+        evalues, evectors = linalg.eig(a)
+        evalues.sort(axis=-1)
+        assert_allclose(ev, evalues, rtol=get_rtol(ev.dtype))
+
+        ev2 = linalg.eigvalsh(a, 'U')
+        assert_allclose(ev2, evalues, rtol=get_rtol(ev.dtype))
+
+
+class TestEigvalsh:
+    @pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
+    def test_types(self, dtype):
+        x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
+        w = np.linalg.eigvalsh(x)
+        assert_equal(w.dtype, get_real_dtype(dtype))
+
+    def test_invalid(self):
+        x = np.array([[1, 0.5], [0.5, 1]], dtype=np.float32)
+        assert_raises(ValueError, np.linalg.eigvalsh, x, UPLO="lrong")
+        assert_raises(ValueError, np.linalg.eigvalsh, x, "lower")
+        assert_raises(ValueError, np.linalg.eigvalsh, x, "upper")
+
+    def test_UPLO(self):
+        Klo = np.array([[0, 0], [1, 0]], dtype=np.double)
+        Kup = np.array([[0, 1], [0, 0]], dtype=np.double)
+        tgt = np.array([-1, 1], dtype=np.double)
+        rtol = get_rtol(np.double)
+
+        # Check default is 'L'
+        w = np.linalg.eigvalsh(Klo)
+        assert_allclose(w, tgt, rtol=rtol)
+        # Check 'L'
+        w = np.linalg.eigvalsh(Klo, UPLO='L')
+        assert_allclose(w, tgt, rtol=rtol)
+        # Check 'l'
+        w = np.linalg.eigvalsh(Klo, UPLO='l')
+        assert_allclose(w, tgt, rtol=rtol)
+        # Check 'U'
+        w = np.linalg.eigvalsh(Kup, UPLO='U')
+        assert_allclose(w, tgt, rtol=rtol)
+        # Check 'u'
+        w = np.linalg.eigvalsh(Kup, UPLO='u')
+        assert_allclose(w, tgt, rtol=rtol)
+
+    def test_0_size(self):
+        # Check that all kinds of 0-sized arrays work
+        class ArraySubclass(np.ndarray):
+            pass
+        a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
+        res = linalg.eigvalsh(a)
+        assert_(res.dtype.type is np.float64)
+        assert_equal((0, 1), res.shape)
+        # This is just for documentation, it might make sense to change:
+        assert_(isinstance(res, np.ndarray))
+
+        a = np.zeros((0, 0), dtype=np.complex64).view(ArraySubclass)
+        res = linalg.eigvalsh(a)
+        assert_(res.dtype.type is np.float32)
+        assert_equal((0,), res.shape)
+        # This is just for documentation, it might make sense to change:
+        assert_(isinstance(res, np.ndarray))
+
+
+class TestEighCases(HermitianTestCase, HermitianGeneralizedTestCase):
+
+    def do(self, a, b, tags):
+        # note that eigenvalue arrays returned by eig must be sorted since
+        # their order isn't guaranteed.
+        res = linalg.eigh(a)
+        ev, evc = res.eigenvalues, res.eigenvectors
+        evalues, evectors = linalg.eig(a)
+        evalues.sort(axis=-1)
+        assert_almost_equal(ev, evalues)
+
+        assert_allclose(dot_generalized(a, evc),
+                        np.asarray(ev)[..., None, :] * np.asarray(evc),
+                        rtol=get_rtol(ev.dtype))
+
+        ev2, evc2 = linalg.eigh(a, 'U')
+        assert_almost_equal(ev2, evalues)
+
+        assert_allclose(dot_generalized(a, evc2),
+                        np.asarray(ev2)[..., None, :] * np.asarray(evc2),
+                        rtol=get_rtol(ev.dtype), err_msg=repr(a))
+
+
+class TestEigh:
+    @pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
+    def test_types(self, dtype):
+        x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
+        w, v = np.linalg.eigh(x)
+        assert_equal(w.dtype, get_real_dtype(dtype))
+        assert_equal(v.dtype, dtype)
+
+    def test_invalid(self):
+        x = np.array([[1, 0.5], [0.5, 1]], dtype=np.float32)
+        assert_raises(ValueError, np.linalg.eigh, x, UPLO="lrong")
+        assert_raises(ValueError, np.linalg.eigh, x, "lower")
+        assert_raises(ValueError, np.linalg.eigh, x, "upper")
+
+    def test_UPLO(self):
+        Klo = np.array([[0, 0], [1, 0]], dtype=np.double)
+        Kup = np.array([[0, 1], [0, 0]], dtype=np.double)
+        tgt = np.array([-1, 1], dtype=np.double)
+        rtol = get_rtol(np.double)
+
+        # Check default is 'L'
+        w, v = np.linalg.eigh(Klo)
+        assert_allclose(w, tgt, rtol=rtol)
+        # Check 'L'
+        w, v = np.linalg.eigh(Klo, UPLO='L')
+        assert_allclose(w, tgt, rtol=rtol)
+        # Check 'l'
+        w, v = np.linalg.eigh(Klo, UPLO='l')
+        assert_allclose(w, tgt, rtol=rtol)
+        # Check 'U'
+        w, v = np.linalg.eigh(Kup, UPLO='U')
+        assert_allclose(w, tgt, rtol=rtol)
+        # Check 'u'
+        w, v = np.linalg.eigh(Kup, UPLO='u')
+        assert_allclose(w, tgt, rtol=rtol)
+
+    def test_0_size(self):
+        # Check that all kinds of 0-sized arrays work
+        class ArraySubclass(np.ndarray):
+            pass
+        a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
+        res, res_v = linalg.eigh(a)
+        assert_(res_v.dtype.type is np.float64)
+        assert_(res.dtype.type is np.float64)
+        assert_equal(a.shape, res_v.shape)
+        assert_equal((0, 1), res.shape)
+        # This is just for documentation, it might make sense to change:
+        assert_(isinstance(a, np.ndarray))
+
+        a = np.zeros((0, 0), dtype=np.complex64).view(ArraySubclass)
+        res, res_v = linalg.eigh(a)
+        assert_(res_v.dtype.type is np.complex64)
+        assert_(res.dtype.type is np.float32)
+        assert_equal(a.shape, res_v.shape)
+        assert_equal((0,), res.shape)
+        # This is just for documentation, it might make sense to change:
+        assert_(isinstance(a, np.ndarray))
+
+
+class _TestNormBase:
+    dt = None
+    dec = None
+
+    @staticmethod
+    def check_dtype(x, res):
+        if issubclass(x.dtype.type, np.inexact):
+            assert_equal(res.dtype, x.real.dtype)
+        else:
+            # For integer input, don't have to test float precision of output.
+            assert_(issubclass(res.dtype.type, np.floating))
+
+
+class _TestNormGeneral(_TestNormBase):
+
+    def test_empty(self):
+        assert_equal(norm([]), 0.0)
+        assert_equal(norm(array([], dtype=self.dt)), 0.0)
+        assert_equal(norm(atleast_2d(array([], dtype=self.dt))), 0.0)
+
+    def test_vector_return_type(self):
+        a = np.array([1, 0, 1])
+
+        exact_types = np.typecodes['AllInteger']
+        inexact_types = np.typecodes['AllFloat']
+
+        all_types = exact_types + inexact_types
+
+        for each_type in all_types:
+            at = a.astype(each_type)
+
+            an = norm(at, -np.inf)
+            self.check_dtype(at, an)
+            assert_almost_equal(an, 0.0)
+
+            with suppress_warnings() as sup:
+                sup.filter(RuntimeWarning, "divide by zero encountered")
+                an = norm(at, -1)
+                self.check_dtype(at, an)
+                assert_almost_equal(an, 0.0)
+
+            an = norm(at, 0)
+            self.check_dtype(at, an)
+            assert_almost_equal(an, 2)
+
+            an = norm(at, 1)
+            self.check_dtype(at, an)
+            assert_almost_equal(an, 2.0)
+
+            an = norm(at, 2)
+            self.check_dtype(at, an)
+            assert_almost_equal(an, an.dtype.type(2.0)**an.dtype.type(1.0/2.0))
+
+            an = norm(at, 4)
+            self.check_dtype(at, an)
+            assert_almost_equal(an, an.dtype.type(2.0)**an.dtype.type(1.0/4.0))
+
+            an = norm(at, np.inf)
+            self.check_dtype(at, an)
+            assert_almost_equal(an, 1.0)
+
+    def test_vector(self):
+        a = [1, 2, 3, 4]
+        b = [-1, -2, -3, -4]
+        c = [-1, 2, -3, 4]
+
+        def _test(v):
+            np.testing.assert_almost_equal(norm(v), 30 ** 0.5,
+                                           decimal=self.dec)
+            np.testing.assert_almost_equal(norm(v, inf), 4.0,
+                                           decimal=self.dec)
+            np.testing.assert_almost_equal(norm(v, -inf), 1.0,
+                                           decimal=self.dec)
+            np.testing.assert_almost_equal(norm(v, 1), 10.0,
+                                           decimal=self.dec)
+            np.testing.assert_almost_equal(norm(v, -1), 12.0 / 25,
+                                           decimal=self.dec)
+            np.testing.assert_almost_equal(norm(v, 2), 30 ** 0.5,
+                                           decimal=self.dec)
+            np.testing.assert_almost_equal(norm(v, -2), ((205. / 144) ** -0.5),
+                                           decimal=self.dec)
+            np.testing.assert_almost_equal(norm(v, 0), 4,
+                                           decimal=self.dec)
+
+        for v in (a, b, c,):
+            _test(v)
+
+        for v in (array(a, dtype=self.dt), array(b, dtype=self.dt),
+                  array(c, dtype=self.dt)):
+            _test(v)
+
+    def test_axis(self):
+        # Vector norms.
+        # Compare the use of `axis` with computing the norm of each row
+        # or column separately.
+        A = array([[1, 2, 3], [4, 5, 6]], dtype=self.dt)
+        for order in [None, -1, 0, 1, 2, 3, np.Inf, -np.Inf]:
+            expected0 = [norm(A[:, k], ord=order) for k in range(A.shape[1])]
+            assert_almost_equal(norm(A, ord=order, axis=0), expected0)
+            expected1 = [norm(A[k, :], ord=order) for k in range(A.shape[0])]
+            assert_almost_equal(norm(A, ord=order, axis=1), expected1)
+
+        # Matrix norms.
+        B = np.arange(1, 25, dtype=self.dt).reshape(2, 3, 4)
+        nd = B.ndim
+        for order in [None, -2, 2, -1, 1, np.Inf, -np.Inf, 'fro']:
+            for axis in itertools.combinations(range(-nd, nd), 2):
+                row_axis, col_axis = axis
+                if row_axis < 0:
+                    row_axis += nd
+                if col_axis < 0:
+                    col_axis += nd
+                if row_axis == col_axis:
+                    assert_raises(ValueError, norm, B, ord=order, axis=axis)
+                else:
+                    n = norm(B, ord=order, axis=axis)
+
+                    # The logic using k_index only works for nd = 3.
+                    # This has to be changed if nd is increased.
+                    k_index = nd - (row_axis + col_axis)
+                    if row_axis < col_axis:
+                        expected = [norm(B[:].take(k, axis=k_index), ord=order)
+                                    for k in range(B.shape[k_index])]
+                    else:
+                        expected = [norm(B[:].take(k, axis=k_index).T, ord=order)
+                                    for k in range(B.shape[k_index])]
+                    assert_almost_equal(n, expected)
+
+    def test_keepdims(self):
+        A = np.arange(1, 25, dtype=self.dt).reshape(2, 3, 4)
+
+        allclose_err = 'order {0}, axis = {1}'
+        shape_err = 'Shape mismatch found {0}, expected {1}, order={2}, axis={3}'
+
+        # check the order=None, axis=None case
+        expected = norm(A, ord=None, axis=None)
+        found = norm(A, ord=None, axis=None, keepdims=True)
+        assert_allclose(np.squeeze(found), expected,
+                        err_msg=allclose_err.format(None, None))
+        expected_shape = (1, 1, 1)
+        assert_(found.shape == expected_shape,
+                shape_err.format(found.shape, expected_shape, None, None))
+
+        # Vector norms.
+        for order in [None, -1, 0, 1, 2, 3, np.Inf, -np.Inf]:
+            for k in range(A.ndim):
+                expected = norm(A, ord=order, axis=k)
+                found = norm(A, ord=order, axis=k, keepdims=True)
+                assert_allclose(np.squeeze(found), expected,
+                                err_msg=allclose_err.format(order, k))
+                expected_shape = list(A.shape)
+                expected_shape[k] = 1
+                expected_shape = tuple(expected_shape)
+                assert_(found.shape == expected_shape,
+                        shape_err.format(found.shape, expected_shape, order, k))
+
+        # Matrix norms.
+        for order in [None, -2, 2, -1, 1, np.Inf, -np.Inf, 'fro', 'nuc']:
+            for k in itertools.permutations(range(A.ndim), 2):
+                expected = norm(A, ord=order, axis=k)
+                found = norm(A, ord=order, axis=k, keepdims=True)
+                assert_allclose(np.squeeze(found), expected,
+                                err_msg=allclose_err.format(order, k))
+                expected_shape = list(A.shape)
+                expected_shape[k[0]] = 1
+                expected_shape[k[1]] = 1
+                expected_shape = tuple(expected_shape)
+                assert_(found.shape == expected_shape,
+                        shape_err.format(found.shape, expected_shape, order, k))
+
+
+class _TestNorm2D(_TestNormBase):
+    # Define the part for 2d arrays separately, so we can subclass this
+    # and run the tests using np.matrix in matrixlib.tests.test_matrix_linalg.
+    array = np.array
+
+    def test_matrix_empty(self):
+        assert_equal(norm(self.array([[]], dtype=self.dt)), 0.0)
+
+    def test_matrix_return_type(self):
+        a = self.array([[1, 0, 1], [0, 1, 1]])
+
+        exact_types = np.typecodes['AllInteger']
+
+        # float32, complex64, float64, complex128 types are the only types
+        # allowed by `linalg`, which performs the matrix operations used
+        # within `norm`.
+        inexact_types = 'fdFD'
+
+        all_types = exact_types + inexact_types
+
+        for each_type in all_types:
+            at = a.astype(each_type)
+
+            an = norm(at, -np.inf)
+            self.check_dtype(at, an)
+            assert_almost_equal(an, 2.0)
+
+            with suppress_warnings() as sup:
+                sup.filter(RuntimeWarning, "divide by zero encountered")
+                an = norm(at, -1)
+                self.check_dtype(at, an)
+                assert_almost_equal(an, 1.0)
+
+            an = norm(at, 1)
+            self.check_dtype(at, an)
+            assert_almost_equal(an, 2.0)
+
+            an = norm(at, 2)
+            self.check_dtype(at, an)
+            assert_almost_equal(an, 3.0**(1.0/2.0))
+
+            an = norm(at, -2)
+            self.check_dtype(at, an)
+            assert_almost_equal(an, 1.0)
+
+            an = norm(at, np.inf)
+            self.check_dtype(at, an)
+            assert_almost_equal(an, 2.0)
+
+            an = norm(at, 'fro')
+            self.check_dtype(at, an)
+            assert_almost_equal(an, 2.0)
+
+            an = norm(at, 'nuc')
+            self.check_dtype(at, an)
+            # Lower bar needed to support low precision floats.
+            # They end up being off by 1 in the 7th place.
+            np.testing.assert_almost_equal(an, 2.7320508075688772, decimal=6)
+
+    def test_matrix_2x2(self):
+        A = self.array([[1, 3], [5, 7]], dtype=self.dt)
+        assert_almost_equal(norm(A), 84 ** 0.5)
+        assert_almost_equal(norm(A, 'fro'), 84 ** 0.5)
+        assert_almost_equal(norm(A, 'nuc'), 10.0)
+        assert_almost_equal(norm(A, inf), 12.0)
+        assert_almost_equal(norm(A, -inf), 4.0)
+        assert_almost_equal(norm(A, 1), 10.0)
+        assert_almost_equal(norm(A, -1), 6.0)
+        assert_almost_equal(norm(A, 2), 9.1231056256176615)
+        assert_almost_equal(norm(A, -2), 0.87689437438234041)
+
+        assert_raises(ValueError, norm, A, 'nofro')
+        assert_raises(ValueError, norm, A, -3)
+        assert_raises(ValueError, norm, A, 0)
+
+    def test_matrix_3x3(self):
+        # This test has been added because the 2x2 example
+        # happened to have equal nuclear norm and induced 1-norm.
+        # The 1/10 scaling factor accommodates the absolute tolerance
+        # used in assert_almost_equal.
+        A = (1 / 10) * \
+            self.array([[1, 2, 3], [6, 0, 5], [3, 2, 1]], dtype=self.dt)
+        assert_almost_equal(norm(A), (1 / 10) * 89 ** 0.5)
+        assert_almost_equal(norm(A, 'fro'), (1 / 10) * 89 ** 0.5)
+        assert_almost_equal(norm(A, 'nuc'), 1.3366836911774836)
+        assert_almost_equal(norm(A, inf), 1.1)
+        assert_almost_equal(norm(A, -inf), 0.6)
+        assert_almost_equal(norm(A, 1), 1.0)
+        assert_almost_equal(norm(A, -1), 0.4)
+        assert_almost_equal(norm(A, 2), 0.88722940323461277)
+        assert_almost_equal(norm(A, -2), 0.19456584790481812)
+
+    def test_bad_args(self):
+        # Check that bad arguments raise the appropriate exceptions.
+
+        A = self.array([[1, 2, 3], [4, 5, 6]], dtype=self.dt)
+        B = np.arange(1, 25, dtype=self.dt).reshape(2, 3, 4)
+
+        # Using `axis=` or passing in a 1-D array implies vector
+        # norms are being computed, so also using `ord='fro'`
+        # or `ord='nuc'` or any other string raises a ValueError.
+        assert_raises(ValueError, norm, A, 'fro', 0)
+        assert_raises(ValueError, norm, A, 'nuc', 0)
+        assert_raises(ValueError, norm, [3, 4], 'fro', None)
+        assert_raises(ValueError, norm, [3, 4], 'nuc', None)
+        assert_raises(ValueError, norm, [3, 4], 'test', None)
+
+        # Similarly, norm should raise an exception when ord is any finite
+        # number other than 1, 2, -1 or -2 when computing matrix norms.
+        for order in [0, 3]:
+            assert_raises(ValueError, norm, A, order, None)
+            assert_raises(ValueError, norm, A, order, (0, 1))
+            assert_raises(ValueError, norm, B, order, (1, 2))
+
+        # Invalid axis
+        assert_raises(np.AxisError, norm, B, None, 3)
+        assert_raises(np.AxisError, norm, B, None, (2, 3))
+        assert_raises(ValueError, norm, B, None, (0, 1, 2))
+
+
+class _TestNorm(_TestNorm2D, _TestNormGeneral):
+    pass
+
+
+class TestNorm_NonSystematic:
+
+    def test_longdouble_norm(self):
+        # Non-regression test: p-norm of longdouble would previously raise
+        # UnboundLocalError.
+        x = np.arange(10, dtype=np.longdouble)
+        old_assert_almost_equal(norm(x, ord=3), 12.65, decimal=2)
+
+    def test_intmin(self):
+        # Non-regression test: p-norm of signed integer would previously do
+        # float cast and abs in the wrong order.
+        x = np.array([-2 ** 31], dtype=np.int32)
+        old_assert_almost_equal(norm(x, ord=3), 2 ** 31, decimal=5)
+
+    def test_complex_high_ord(self):
+        # gh-4156
+        d = np.empty((2,), dtype=np.clongdouble)
+        d[0] = 6 + 7j
+        d[1] = -6 + 7j
+        res = 11.615898132184
+        old_assert_almost_equal(np.linalg.norm(d, ord=3), res, decimal=10)
+        d = d.astype(np.complex128)
+        old_assert_almost_equal(np.linalg.norm(d, ord=3), res, decimal=9)
+        d = d.astype(np.complex64)
+        old_assert_almost_equal(np.linalg.norm(d, ord=3), res, decimal=5)
+
+
+# Separate definitions so we can use them for matrix tests.
+class _TestNormDoubleBase(_TestNormBase):
+    dt = np.double
+    dec = 12
+
+
+class _TestNormSingleBase(_TestNormBase):
+    dt = np.float32
+    dec = 6
+
+
+class _TestNormInt64Base(_TestNormBase):
+    dt = np.int64
+    dec = 12
+
+
+class TestNormDouble(_TestNorm, _TestNormDoubleBase):
+    pass
+
+
+class TestNormSingle(_TestNorm, _TestNormSingleBase):
+    pass
+
+
+class TestNormInt64(_TestNorm, _TestNormInt64Base):
+    pass
+
+
+class TestMatrixRank:
+
+    def test_matrix_rank(self):
+        # Full rank matrix
+        assert_equal(4, matrix_rank(np.eye(4)))
+        # rank deficient matrix
+        I = np.eye(4)
+        I[-1, -1] = 0.
+        assert_equal(matrix_rank(I), 3)
+        # All zeros - zero rank
+        assert_equal(matrix_rank(np.zeros((4, 4))), 0)
+        # 1 dimension - rank 1 unless all 0
+        assert_equal(matrix_rank([1, 0, 0, 0]), 1)
+        assert_equal(matrix_rank(np.zeros((4,))), 0)
+        # accepts array-like
+        assert_equal(matrix_rank([1]), 1)
+        # greater than 2 dimensions treated as stacked matrices
+        ms = np.array([I, np.eye(4), np.zeros((4,4))])
+        assert_equal(matrix_rank(ms), np.array([3, 4, 0]))
+        # works on scalar
+        assert_equal(matrix_rank(1), 1)
+
+    def test_symmetric_rank(self):
+        assert_equal(4, matrix_rank(np.eye(4), hermitian=True))
+        assert_equal(1, matrix_rank(np.ones((4, 4)), hermitian=True))
+        assert_equal(0, matrix_rank(np.zeros((4, 4)), hermitian=True))
+        # rank deficient matrix
+        I = np.eye(4)
+        I[-1, -1] = 0.
+        assert_equal(3, matrix_rank(I, hermitian=True))
+        # manually supplied tolerance
+        I[-1, -1] = 1e-8
+        assert_equal(4, matrix_rank(I, hermitian=True, tol=0.99e-8))
+        assert_equal(3, matrix_rank(I, hermitian=True, tol=1.01e-8))
+
+
+def test_reduced_rank():
+    # Test matrices with reduced rank
+    rng = np.random.RandomState(20120714)
+    for i in range(100):
+        # Make a rank deficient matrix
+        X = rng.normal(size=(40, 10))
+        X[:, 0] = X[:, 1] + X[:, 2]
+        # Assert that matrix_rank detected deficiency
+        assert_equal(matrix_rank(X), 9)
+        X[:, 3] = X[:, 4] + X[:, 5]
+        assert_equal(matrix_rank(X), 8)
+
+
+class TestQR:
+    # Define the array class here, so run this on matrices elsewhere.
+    array = np.array
+
+    def check_qr(self, a):
+        # This test expects the argument `a` to be an ndarray or
+        # a subclass of an ndarray of inexact type.
+        a_type = type(a)
+        a_dtype = a.dtype
+        m, n = a.shape
+        k = min(m, n)
+
+        # mode == 'complete'
+        res = linalg.qr(a, mode='complete')
+        Q, R = res.Q, res.R
+        assert_(Q.dtype == a_dtype)
+        assert_(R.dtype == a_dtype)
+        assert_(isinstance(Q, a_type))
+        assert_(isinstance(R, a_type))
+        assert_(Q.shape == (m, m))
+        assert_(R.shape == (m, n))
+        assert_almost_equal(dot(Q, R), a)
+        assert_almost_equal(dot(Q.T.conj(), Q), np.eye(m))
+        assert_almost_equal(np.triu(R), R)
+
+        # mode == 'reduced'
+        q1, r1 = linalg.qr(a, mode='reduced')
+        assert_(q1.dtype == a_dtype)
+        assert_(r1.dtype == a_dtype)
+        assert_(isinstance(q1, a_type))
+        assert_(isinstance(r1, a_type))
+        assert_(q1.shape == (m, k))
+        assert_(r1.shape == (k, n))
+        assert_almost_equal(dot(q1, r1), a)
+        assert_almost_equal(dot(q1.T.conj(), q1), np.eye(k))
+        assert_almost_equal(np.triu(r1), r1)
+
+        # mode == 'r'
+        r2 = linalg.qr(a, mode='r')
+        assert_(r2.dtype == a_dtype)
+        assert_(isinstance(r2, a_type))
+        assert_almost_equal(r2, r1)
+
+
+    @pytest.mark.parametrize(["m", "n"], [
+        (3, 0),
+        (0, 3),
+        (0, 0)
+    ])
+    def test_qr_empty(self, m, n):
+        k = min(m, n)
+        a = np.empty((m, n))
+
+        self.check_qr(a)
+
+        h, tau = np.linalg.qr(a, mode='raw')
+        assert_equal(h.dtype, np.double)
+        assert_equal(tau.dtype, np.double)
+        assert_equal(h.shape, (n, m))
+        assert_equal(tau.shape, (k,))
+
+    def test_mode_raw(self):
+        # The factorization is not unique and varies between libraries,
+        # so it is not possible to check against known values. Functional
+        # testing is a possibility, but awaits the exposure of more
+        # of the functions in lapack_lite. Consequently, this test is
+        # very limited in scope. Note that the results are in FORTRAN
+        # order, hence the h arrays are transposed.
+        a = self.array([[1, 2], [3, 4], [5, 6]], dtype=np.double)
+
+        # Test double
+        h, tau = linalg.qr(a, mode='raw')
+        assert_(h.dtype == np.double)
+        assert_(tau.dtype == np.double)
+        assert_(h.shape == (2, 3))
+        assert_(tau.shape == (2,))
+
+        h, tau = linalg.qr(a.T, mode='raw')
+        assert_(h.dtype == np.double)
+        assert_(tau.dtype == np.double)
+        assert_(h.shape == (3, 2))
+        assert_(tau.shape == (2,))
+
+    def test_mode_all_but_economic(self):
+        a = self.array([[1, 2], [3, 4]])
+        b = self.array([[1, 2], [3, 4], [5, 6]])
+        for dt in "fd":
+            m1 = a.astype(dt)
+            m2 = b.astype(dt)
+            self.check_qr(m1)
+            self.check_qr(m2)
+            self.check_qr(m2.T)
+
+        for dt in "fd":
+            m1 = 1 + 1j * a.astype(dt)
+            m2 = 1 + 1j * b.astype(dt)
+            self.check_qr(m1)
+            self.check_qr(m2)
+            self.check_qr(m2.T)
+
+    def check_qr_stacked(self, a):
+        # This test expects the argument `a` to be an ndarray or
+        # a subclass of an ndarray of inexact type.
+        a_type = type(a)
+        a_dtype = a.dtype
+        m, n = a.shape[-2:]
+        k = min(m, n)
+
+        # mode == 'complete'
+        q, r = linalg.qr(a, mode='complete')
+        assert_(q.dtype == a_dtype)
+        assert_(r.dtype == a_dtype)
+        assert_(isinstance(q, a_type))
+        assert_(isinstance(r, a_type))
+        assert_(q.shape[-2:] == (m, m))
+        assert_(r.shape[-2:] == (m, n))
+        assert_almost_equal(matmul(q, r), a)
+        I_mat = np.identity(q.shape[-1])
+        stack_I_mat = np.broadcast_to(I_mat,
+                        q.shape[:-2] + (q.shape[-1],)*2)
+        assert_almost_equal(matmul(swapaxes(q, -1, -2).conj(), q), stack_I_mat)
+        assert_almost_equal(np.triu(r[..., :, :]), r)
+
+        # mode == 'reduced'
+        q1, r1 = linalg.qr(a, mode='reduced')
+        assert_(q1.dtype == a_dtype)
+        assert_(r1.dtype == a_dtype)
+        assert_(isinstance(q1, a_type))
+        assert_(isinstance(r1, a_type))
+        assert_(q1.shape[-2:] == (m, k))
+        assert_(r1.shape[-2:] == (k, n))
+        assert_almost_equal(matmul(q1, r1), a)
+        I_mat = np.identity(q1.shape[-1])
+        stack_I_mat = np.broadcast_to(I_mat,
+                        q1.shape[:-2] + (q1.shape[-1],)*2)
+        assert_almost_equal(matmul(swapaxes(q1, -1, -2).conj(), q1),
+                            stack_I_mat)
+        assert_almost_equal(np.triu(r1[..., :, :]), r1)
+
+        # mode == 'r'
+        r2 = linalg.qr(a, mode='r')
+        assert_(r2.dtype == a_dtype)
+        assert_(isinstance(r2, a_type))
+        assert_almost_equal(r2, r1)
+
+    @pytest.mark.parametrize("size", [
+        (3, 4), (4, 3), (4, 4),
+        (3, 0), (0, 3)])
+    @pytest.mark.parametrize("outer_size", [
+        (2, 2), (2,), (2, 3, 4)])
+    @pytest.mark.parametrize("dt", [
+        np.single, np.double,
+        np.csingle, np.cdouble])
+    def test_stacked_inputs(self, outer_size, size, dt):
+
+        A = np.random.normal(size=outer_size + size).astype(dt)
+        B = np.random.normal(size=outer_size + size).astype(dt)
+        self.check_qr_stacked(A)
+        self.check_qr_stacked(A + 1.j*B)
+
+
+class TestCholesky:
+    # TODO: are there no other tests for cholesky?
+
+    @pytest.mark.parametrize(
+        'shape', [(1, 1), (2, 2), (3, 3), (50, 50), (3, 10, 10)]
+    )
+    @pytest.mark.parametrize(
+        'dtype', (np.float32, np.float64, np.complex64, np.complex128)
+    )
+    def test_basic_property(self, shape, dtype):
+        # Check A = L L^H
+        np.random.seed(1)
+        a = np.random.randn(*shape)
+        if np.issubdtype(dtype, np.complexfloating):
+            a = a + 1j*np.random.randn(*shape)
+
+        t = list(range(len(shape)))
+        t[-2:] = -1, -2
+
+        a = np.matmul(a.transpose(t).conj(), a)
+        a = np.asarray(a, dtype=dtype)
+
+        c = np.linalg.cholesky(a)
+
+        b = np.matmul(c, c.transpose(t).conj())
+        with np._no_nep50_warning():
+            atol = 500 * a.shape[0] * np.finfo(dtype).eps
+        assert_allclose(b, a, atol=atol, err_msg=f'{shape} {dtype}\n{a}\n{c}')
+
+    def test_0_size(self):
+        class ArraySubclass(np.ndarray):
+            pass
+        a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
+        res = linalg.cholesky(a)
+        assert_equal(a.shape, res.shape)
+        assert_(res.dtype.type is np.float64)
+        # for documentation purpose:
+        assert_(isinstance(res, np.ndarray))
+
+        a = np.zeros((1, 0, 0), dtype=np.complex64).view(ArraySubclass)
+        res = linalg.cholesky(a)
+        assert_equal(a.shape, res.shape)
+        assert_(res.dtype.type is np.complex64)
+        assert_(isinstance(res, np.ndarray))
+
+
+def test_byteorder_check():
+    # Byte order check should pass for native order
+    if sys.byteorder == 'little':
+        native = '<'
+    else:
+        native = '>'
+
+    for dtt in (np.float32, np.float64):
+        arr = np.eye(4, dtype=dtt)
+        n_arr = arr.newbyteorder(native)
+        sw_arr = arr.newbyteorder('S').byteswap()
+        assert_equal(arr.dtype.byteorder, '=')
+        for routine in (linalg.inv, linalg.det, linalg.pinv):
+            # Normal call
+            res = routine(arr)
+            # Native but not '='
+            assert_array_equal(res, routine(n_arr))
+            # Swapped
+            assert_array_equal(res, routine(sw_arr))
+
+
+@pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
+def test_generalized_raise_multiloop():
+    # It should raise an error even if the error doesn't occur in the
+    # last iteration of the ufunc inner loop
+
+    invertible = np.array([[1, 2], [3, 4]])
+    non_invertible = np.array([[1, 1], [1, 1]])
+
+    x = np.zeros([4, 4, 2, 2])[1::2]
+    x[...] = invertible
+    x[0, 0] = non_invertible
+
+    assert_raises(np.linalg.LinAlgError, np.linalg.inv, x)
+
+
+def test_xerbla_override():
+    # Check that our xerbla has been successfully linked in. If it is not,
+    # the default xerbla routine is called, which prints a message to stdout
+    # and may, or may not, abort the process depending on the LAPACK package.
+
+    XERBLA_OK = 255
+
+    try:
+        pid = os.fork()
+    except (OSError, AttributeError):
+        # fork failed, or not running on POSIX
+        pytest.skip("Not POSIX or fork failed.")
+
+    if pid == 0:
+        # child; close i/o file handles
+        os.close(1)
+        os.close(0)
+        # Avoid producing core files.
+        import resource
+        resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
+        # These calls may abort.
+        try:
+            np.linalg.lapack_lite.xerbla()
+        except ValueError:
+            pass
+        except Exception:
+            os._exit(os.EX_CONFIG)
+
+        try:
+            a = np.array([[1.]])
+            np.linalg.lapack_lite.dorgqr(
+                1, 1, 1, a,
+                0,  # <- invalid value
+                a, a, 0, 0)
+        except ValueError as e:
+            if "DORGQR parameter number 5" in str(e):
+                # success, reuse error code to mark success as
+                # FORTRAN STOP returns as success.
+                os._exit(XERBLA_OK)
+
+        # Did not abort, but our xerbla was not linked in.
+        os._exit(os.EX_CONFIG)
+    else:
+        # parent
+        pid, status = os.wait()
+        if os.WEXITSTATUS(status) != XERBLA_OK:
+            pytest.skip('Numpy xerbla not linked in.')
+
+
+@pytest.mark.skipif(IS_WASM, reason="Cannot start subprocess")
+@pytest.mark.slow
+def test_sdot_bug_8577():
+    # Regression test that loading certain other libraries does not
+    # result to wrong results in float32 linear algebra.
+    #
+    # There's a bug gh-8577 on OSX that can trigger this, and perhaps
+    # there are also other situations in which it occurs.
+    #
+    # Do the check in a separate process.
+
+    bad_libs = ['PyQt5.QtWidgets', 'IPython']
+
+    template = textwrap.dedent("""
+    import sys
+    {before}
+    try:
+        import {bad_lib}
+    except ImportError:
+        sys.exit(0)
+    {after}
+    x = np.ones(2, dtype=np.float32)
+    sys.exit(0 if np.allclose(x.dot(x), 2.0) else 1)
+    """)
+
+    for bad_lib in bad_libs:
+        code = template.format(before="import numpy as np", after="",
+                               bad_lib=bad_lib)
+        subprocess.check_call([sys.executable, "-c", code])
+
+        # Swapped import order
+        code = template.format(after="import numpy as np", before="",
+                               bad_lib=bad_lib)
+        subprocess.check_call([sys.executable, "-c", code])
+
+
+class TestMultiDot:
+
+    def test_basic_function_with_three_arguments(self):
+        # multi_dot with three arguments uses a fast hand coded algorithm to
+        # determine the optimal order. Therefore test it separately.
+        A = np.random.random((6, 2))
+        B = np.random.random((2, 6))
+        C = np.random.random((6, 2))
+
+        assert_almost_equal(multi_dot([A, B, C]), A.dot(B).dot(C))
+        assert_almost_equal(multi_dot([A, B, C]), np.dot(A, np.dot(B, C)))
+
+    def test_basic_function_with_two_arguments(self):
+        # separate code path with two arguments
+        A = np.random.random((6, 2))
+        B = np.random.random((2, 6))
+
+        assert_almost_equal(multi_dot([A, B]), A.dot(B))
+        assert_almost_equal(multi_dot([A, B]), np.dot(A, B))
+
+    def test_basic_function_with_dynamic_programming_optimization(self):
+        # multi_dot with four or more arguments uses the dynamic programming
+        # optimization and therefore deserve a separate
+        A = np.random.random((6, 2))
+        B = np.random.random((2, 6))
+        C = np.random.random((6, 2))
+        D = np.random.random((2, 1))
+        assert_almost_equal(multi_dot([A, B, C, D]), A.dot(B).dot(C).dot(D))
+
+    def test_vector_as_first_argument(self):
+        # The first argument can be 1-D
+        A1d = np.random.random(2)  # 1-D
+        B = np.random.random((2, 6))
+        C = np.random.random((6, 2))
+        D = np.random.random((2, 2))
+
+        # the result should be 1-D
+        assert_equal(multi_dot([A1d, B, C, D]).shape, (2,))
+
+    def test_vector_as_last_argument(self):
+        # The last argument can be 1-D
+        A = np.random.random((6, 2))
+        B = np.random.random((2, 6))
+        C = np.random.random((6, 2))
+        D1d = np.random.random(2)  # 1-D
+
+        # the result should be 1-D
+        assert_equal(multi_dot([A, B, C, D1d]).shape, (6,))
+
+    def test_vector_as_first_and_last_argument(self):
+        # The first and last arguments can be 1-D
+        A1d = np.random.random(2)  # 1-D
+        B = np.random.random((2, 6))
+        C = np.random.random((6, 2))
+        D1d = np.random.random(2)  # 1-D
+
+        # the result should be a scalar
+        assert_equal(multi_dot([A1d, B, C, D1d]).shape, ())
+
+    def test_three_arguments_and_out(self):
+        # multi_dot with three arguments uses a fast hand coded algorithm to
+        # determine the optimal order. Therefore test it separately.
+        A = np.random.random((6, 2))
+        B = np.random.random((2, 6))
+        C = np.random.random((6, 2))
+
+        out = np.zeros((6, 2))
+        ret = multi_dot([A, B, C], out=out)
+        assert out is ret
+        assert_almost_equal(out, A.dot(B).dot(C))
+        assert_almost_equal(out, np.dot(A, np.dot(B, C)))
+
+    def test_two_arguments_and_out(self):
+        # separate code path with two arguments
+        A = np.random.random((6, 2))
+        B = np.random.random((2, 6))
+        out = np.zeros((6, 6))
+        ret = multi_dot([A, B], out=out)
+        assert out is ret
+        assert_almost_equal(out, A.dot(B))
+        assert_almost_equal(out, np.dot(A, B))
+
+    def test_dynamic_programming_optimization_and_out(self):
+        # multi_dot with four or more arguments uses the dynamic programming
+        # optimization and therefore deserve a separate test
+        A = np.random.random((6, 2))
+        B = np.random.random((2, 6))
+        C = np.random.random((6, 2))
+        D = np.random.random((2, 1))
+        out = np.zeros((6, 1))
+        ret = multi_dot([A, B, C, D], out=out)
+        assert out is ret
+        assert_almost_equal(out, A.dot(B).dot(C).dot(D))
+
+    def test_dynamic_programming_logic(self):
+        # Test for the dynamic programming part
+        # This test is directly taken from Cormen page 376.
+        arrays = [np.random.random((30, 35)),
+                  np.random.random((35, 15)),
+                  np.random.random((15, 5)),
+                  np.random.random((5, 10)),
+                  np.random.random((10, 20)),
+                  np.random.random((20, 25))]
+        m_expected = np.array([[0., 15750., 7875., 9375., 11875., 15125.],
+                               [0.,     0., 2625., 4375.,  7125., 10500.],
+                               [0.,     0.,    0.,  750.,  2500.,  5375.],
+                               [0.,     0.,    0.,    0.,  1000.,  3500.],
+                               [0.,     0.,    0.,    0.,     0.,  5000.],
+                               [0.,     0.,    0.,    0.,     0.,     0.]])
+        s_expected = np.array([[0,  1,  1,  3,  3,  3],
+                               [0,  0,  2,  3,  3,  3],
+                               [0,  0,  0,  3,  3,  3],
+                               [0,  0,  0,  0,  4,  5],
+                               [0,  0,  0,  0,  0,  5],
+                               [0,  0,  0,  0,  0,  0]], dtype=int)
+        s_expected -= 1  # Cormen uses 1-based index, python does not.
+
+        s, m = _multi_dot_matrix_chain_order(arrays, return_costs=True)
+
+        # Only the upper triangular part (without the diagonal) is interesting.
+        assert_almost_equal(np.triu(s[:-1, 1:]),
+                            np.triu(s_expected[:-1, 1:]))
+        assert_almost_equal(np.triu(m), np.triu(m_expected))
+
+    def test_too_few_input_arrays(self):
+        assert_raises(ValueError, multi_dot, [])
+        assert_raises(ValueError, multi_dot, [np.random.random((3, 3))])
+
+
+class TestTensorinv:
+
+    @pytest.mark.parametrize("arr, ind", [
+        (np.ones((4, 6, 8, 2)), 2),
+        (np.ones((3, 3, 2)), 1),
+        ])
+    def test_non_square_handling(self, arr, ind):
+        with assert_raises(LinAlgError):
+            linalg.tensorinv(arr, ind=ind)
+
+    @pytest.mark.parametrize("shape, ind", [
+        # examples from docstring
+        ((4, 6, 8, 3), 2),
+        ((24, 8, 3), 1),
+        ])
+    def test_tensorinv_shape(self, shape, ind):
+        a = np.eye(24)
+        a.shape = shape
+        ainv = linalg.tensorinv(a=a, ind=ind)
+        expected = a.shape[ind:] + a.shape[:ind]
+        actual = ainv.shape
+        assert_equal(actual, expected)
+
+    @pytest.mark.parametrize("ind", [
+        0, -2,
+        ])
+    def test_tensorinv_ind_limit(self, ind):
+        a = np.eye(24)
+        a.shape = (4, 6, 8, 3)
+        with assert_raises(ValueError):
+            linalg.tensorinv(a=a, ind=ind)
+
+    def test_tensorinv_result(self):
+        # mimic a docstring example
+        a = np.eye(24)
+        a.shape = (24, 8, 3)
+        ainv = linalg.tensorinv(a, ind=1)
+        b = np.ones(24)
+        assert_allclose(np.tensordot(ainv, b, 1), np.linalg.tensorsolve(a, b))
+
+
+class TestTensorsolve:
+
+    @pytest.mark.parametrize("a, axes", [
+        (np.ones((4, 6, 8, 2)), None),
+        (np.ones((3, 3, 2)), (0, 2)),
+        ])
+    def test_non_square_handling(self, a, axes):
+        with assert_raises(LinAlgError):
+            b = np.ones(a.shape[:2])
+            linalg.tensorsolve(a, b, axes=axes)
+
+    @pytest.mark.parametrize("shape",
+        [(2, 3, 6), (3, 4, 4, 3), (0, 3, 3, 0)],
+    )
+    def test_tensorsolve_result(self, shape):
+        a = np.random.randn(*shape)
+        b = np.ones(a.shape[:2])
+        x = np.linalg.tensorsolve(a, b)
+        assert_allclose(np.tensordot(a, x, axes=len(x.shape)), b)
+
+
+def test_unsupported_commontype():
+    # linalg gracefully handles unsupported type
+    arr = np.array([[1, -2], [2, 5]], dtype='float16')
+    with assert_raises_regex(TypeError, "unsupported in linalg"):
+        linalg.cholesky(arr)
+
+
+#@pytest.mark.slow
+#@pytest.mark.xfail(not HAS_LAPACK64, run=False,
+#                   reason="Numpy not compiled with 64-bit BLAS/LAPACK")
+#@requires_memory(free_bytes=16e9)
+@pytest.mark.skip(reason="Bad memory reports lead to OOM in ci testing")
+def test_blas64_dot():
+    n = 2**32
+    a = np.zeros([1, n], dtype=np.float32)
+    b = np.ones([1, 1], dtype=np.float32)
+    a[0,-1] = 1
+    c = np.dot(b, a)
+    assert_equal(c[0,-1], 1)
+
+
+@pytest.mark.xfail(not HAS_LAPACK64,
+                   reason="Numpy not compiled with 64-bit BLAS/LAPACK")
+def test_blas64_geqrf_lwork_smoketest():
+    # Smoke test LAPACK geqrf lwork call with 64-bit integers
+    dtype = np.float64
+    lapack_routine = np.linalg.lapack_lite.dgeqrf
+
+    m = 2**32 + 1
+    n = 2**32 + 1
+    lda = m
+
+    # Dummy arrays, not referenced by the lapack routine, so don't
+    # need to be of the right size
+    a = np.zeros([1, 1], dtype=dtype)
+    work = np.zeros([1], dtype=dtype)
+    tau = np.zeros([1], dtype=dtype)
+
+    # Size query
+    results = lapack_routine(m, n, a, lda, tau, work, -1, 0)
+    assert_equal(results['info'], 0)
+    assert_equal(results['m'], m)
+    assert_equal(results['n'], m)
+
+    # Should result to an integer of a reasonable size
+    lwork = int(work.item())
+    assert_(2**32 < lwork < 2**42)
diff --git a/venv/lib/python3.10/site-packages/numpy/linalg/tests/test_regression.py b/venv/lib/python3.10/site-packages/numpy/linalg/tests/test_regression.py
new file mode 100644
index 0000000000000000000000000000000000000000..af38443a93c3b74d4344130ab7bbac0206e9f7f7
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/numpy/linalg/tests/test_regression.py
@@ -0,0 +1,145 @@
+""" Test functions for linalg module
+"""
+import warnings
+
+import numpy as np
+from numpy import linalg, arange, float64, array, dot, transpose
+from numpy.testing import (
+    assert_, assert_raises, assert_equal, assert_array_equal,
+    assert_array_almost_equal, assert_array_less
+)
+
+
+class TestRegression:
+
+    def test_eig_build(self):
+        # Ticket #652
+        rva = array([1.03221168e+02 + 0.j,
+                     -1.91843603e+01 + 0.j,
+                     -6.04004526e-01 + 15.84422474j,
+                     -6.04004526e-01 - 15.84422474j,
+                     -1.13692929e+01 + 0.j,
+                     -6.57612485e-01 + 10.41755503j,
+                     -6.57612485e-01 - 10.41755503j,
+                     1.82126812e+01 + 0.j,
+                     1.06011014e+01 + 0.j,
+                     7.80732773e+00 + 0.j,
+                     -7.65390898e-01 + 0.j,
+                     1.51971555e-15 + 0.j,
+                     -1.51308713e-15 + 0.j])
+        a = arange(13 * 13, dtype=float64)
+        a.shape = (13, 13)
+        a = a % 17
+        va, ve = linalg.eig(a)
+        va.sort()
+        rva.sort()
+        assert_array_almost_equal(va, rva)
+
+    def test_eigh_build(self):
+        # Ticket 662.
+        rvals = [68.60568999, 89.57756725, 106.67185574]
+
+        cov = array([[77.70273908,   3.51489954,  15.64602427],
+                     [3.51489954,  88.97013878,  -1.07431931],
+                     [15.64602427,  -1.07431931,  98.18223512]])
+
+        vals, vecs = linalg.eigh(cov)
+        assert_array_almost_equal(vals, rvals)
+
+    def test_svd_build(self):
+        # Ticket 627.
+        a = array([[0., 1.], [1., 1.], [2., 1.], [3., 1.]])
+        m, n = a.shape
+        u, s, vh = linalg.svd(a)
+
+        b = dot(transpose(u[:, n:]), a)
+
+        assert_array_almost_equal(b, np.zeros((2, 2)))
+
+    def test_norm_vector_badarg(self):
+        # Regression for #786: Frobenius norm for vectors raises
+        # ValueError.
+        assert_raises(ValueError, linalg.norm, array([1., 2., 3.]), 'fro')
+
+    def test_lapack_endian(self):
+        # For bug #1482
+        a = array([[5.7998084,  -2.1825367],
+                   [-2.1825367,   9.85910595]], dtype='>f8')
+        b = array(a, dtype=' 0.5)
+                assert_equal(c, 1)
+                assert_equal(np.linalg.matrix_rank(a), 1)
+                assert_array_less(1, np.linalg.norm(a, ord=2))
+
+    def test_norm_object_array(self):
+        # gh-7575
+        testvector = np.array([np.array([0, 1]), 0, 0], dtype=object)
+
+        norm = linalg.norm(testvector)
+        assert_array_equal(norm, [0, 1])
+        assert_(norm.dtype == np.dtype('float64'))
+
+        norm = linalg.norm(testvector, ord=1)
+        assert_array_equal(norm, [0, 1])
+        assert_(norm.dtype != np.dtype('float64'))
+
+        norm = linalg.norm(testvector, ord=2)
+        assert_array_equal(norm, [0, 1])
+        assert_(norm.dtype == np.dtype('float64'))
+
+        assert_raises(ValueError, linalg.norm, testvector, ord='fro')
+        assert_raises(ValueError, linalg.norm, testvector, ord='nuc')
+        assert_raises(ValueError, linalg.norm, testvector, ord=np.inf)
+        assert_raises(ValueError, linalg.norm, testvector, ord=-np.inf)
+        assert_raises(ValueError, linalg.norm, testvector, ord=0)
+        assert_raises(ValueError, linalg.norm, testvector, ord=-1)
+        assert_raises(ValueError, linalg.norm, testvector, ord=-2)
+
+        testmatrix = np.array([[np.array([0, 1]), 0, 0],
+                               [0,                0, 0]], dtype=object)
+
+        norm = linalg.norm(testmatrix)
+        assert_array_equal(norm, [0, 1])
+        assert_(norm.dtype == np.dtype('float64'))
+
+        norm = linalg.norm(testmatrix, ord='fro')
+        assert_array_equal(norm, [0, 1])
+        assert_(norm.dtype == np.dtype('float64'))
+
+        assert_raises(TypeError, linalg.norm, testmatrix, ord='nuc')
+        assert_raises(ValueError, linalg.norm, testmatrix, ord=np.inf)
+        assert_raises(ValueError, linalg.norm, testmatrix, ord=-np.inf)
+        assert_raises(ValueError, linalg.norm, testmatrix, ord=0)
+        assert_raises(ValueError, linalg.norm, testmatrix, ord=1)
+        assert_raises(ValueError, linalg.norm, testmatrix, ord=-1)
+        assert_raises(TypeError, linalg.norm, testmatrix, ord=2)
+        assert_raises(TypeError, linalg.norm, testmatrix, ord=-2)
+        assert_raises(ValueError, linalg.norm, testmatrix, ord=3)
+
+    def test_lstsq_complex_larger_rhs(self):
+        # gh-9891
+        size = 20
+        n_rhs = 70
+        G = np.random.randn(size, size) + 1j * np.random.randn(size, size)
+        u = np.random.randn(size, n_rhs) + 1j * np.random.randn(size, n_rhs)
+        b = G.dot(u)
+        # This should work without segmentation fault.
+        u_lstsq, res, rank, sv = linalg.lstsq(G, b, rcond=None)
+        # check results just in case
+        assert_array_almost_equal(u_lstsq, u)
diff --git a/venv/lib/python3.10/site-packages/numpy/ma/LICENSE b/venv/lib/python3.10/site-packages/numpy/ma/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..b41aae0c89a0f2486843d395f972db759c73c4b8
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/numpy/ma/LICENSE
@@ -0,0 +1,24 @@
+* Copyright (c) 2006, University of Georgia and Pierre G.F. Gerard-Marchant
+* All rights reserved.
+* Redistribution and use in source and binary forms, with or without
+* modification, are permitted provided that the following conditions are met:
+*
+*     * Redistributions of source code must retain the above copyright
+*       notice, this list of conditions and the following disclaimer.
+*     * Redistributions in binary form must reproduce the above copyright
+*       notice, this list of conditions and the following disclaimer in the
+*       documentation and/or other materials provided with the distribution.
+*     * Neither the name of the University of Georgia nor the
+*       names of its contributors may be used to endorse or promote products
+*       derived from this software without specific prior written permission.
+*
+* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
+* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
+* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/numpy/ma/README.rst b/venv/lib/python3.10/site-packages/numpy/ma/README.rst
new file mode 100644
index 0000000000000000000000000000000000000000..47f20d6458e835319252a327d31f77531ab14e8c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/numpy/ma/README.rst
@@ -0,0 +1,236 @@
+==================================
+A Guide to Masked Arrays in NumPy
+==================================
+
+.. Contents::
+
+See http://www.scipy.org/scipy/numpy/wiki/MaskedArray (dead link)
+for updates of this document.
+
+
+History
+-------
+
+As a regular user of MaskedArray, I (Pierre G.F. Gerard-Marchant) became
+increasingly frustrated with the subclassing of masked arrays (even if
+I can only blame my inexperience). I needed to develop a class of arrays
+that could store some additional information along with numerical values,
+while keeping the possibility for missing data (picture storing a series
+of dates along with measurements, what would later become the `TimeSeries
+Scikit `__
+(dead link).
+
+I started to implement such a class, but then quickly realized that
+any additional information disappeared when processing these subarrays
+(for example, adding a constant value to a subarray would erase its
+dates). I ended up writing the equivalent of *numpy.core.ma* for my
+particular class, ufuncs included. Everything went fine until I needed to
+subclass my new class, when more problems showed up: some attributes of
+the new subclass were lost during processing. I identified the culprit as
+MaskedArray, which returns masked ndarrays when I expected masked
+arrays of my class. I was preparing myself to rewrite *numpy.core.ma*
+when I forced myself to learn how to subclass ndarrays. As I became more
+familiar with the *__new__* and *__array_finalize__* methods,
+I started to wonder why masked arrays were objects, and not ndarrays,
+and whether it wouldn't be more convenient for subclassing if they did
+behave like regular ndarrays.
+
+The new *maskedarray* is what I eventually come up with. The
+main differences with the initial *numpy.core.ma* package are
+that MaskedArray is now a subclass of *ndarray* and that the
+*_data* section can now be any subclass of *ndarray*. Apart from a
+couple of issues listed below, the behavior of the new MaskedArray
+class reproduces the old one. Initially the *maskedarray*
+implementation was marginally slower than *numpy.ma* in some areas,
+but work is underway to speed it up; the expectation is that it can be
+made substantially faster than the present *numpy.ma*.
+
+
+Note that if the subclass has some special methods and
+attributes, they are not propagated to the masked version:
+this would require a modification of the *__getattribute__*
+method (first trying *ndarray.__getattribute__*, then trying
+*self._data.__getattribute__* if an exception is raised in the first
+place), which really slows things down.
+
+Main differences
+----------------
+
+ * The *_data* part of the masked array can be any subclass of ndarray (but not recarray, cf below).
+ * *fill_value* is now a property, not a function.
+ * in the majority of cases, the mask is forced to *nomask* when no value is actually masked. A notable exception is when a masked array (with no masked values) has just been unpickled.
+ * I got rid of the *share_mask* flag, I never understood its purpose.
+ * *put*, *putmask* and *take* now mimic the ndarray methods, to avoid unpleasant surprises. Moreover, *put* and *putmask* both update the mask when needed.  * if *a* is a masked array, *bool(a)* raises a *ValueError*, as it does with ndarrays.
+ * in the same way, the comparison of two masked arrays is a masked array, not a boolean
+ * *filled(a)* returns an array of the same subclass as *a._data*, and no test is performed on whether it is contiguous or not.
+ * the mask is always printed, even if it's *nomask*, which makes things easy (for me at least) to remember that a masked array is used.
+ * *cumsum* works as if the *_data* array was filled with 0. The mask is preserved, but not updated.
+ * *cumprod* works as if the *_data* array was filled with 1. The mask is preserved, but not updated.
+
+New features
+------------
+
+This list is non-exhaustive...
+
+ * the *mr_* function mimics *r_* for masked arrays.
+ * the *anom* method returns the anomalies (deviations from the average)
+
+Using the new package with numpy.core.ma
+----------------------------------------
+
+I tried to make sure that the new package can understand old masked
+arrays. Unfortunately, there's no upward compatibility.
+
+For example:
+
+>>> import numpy.core.ma as old_ma
+>>> import maskedarray as new_ma
+>>> x = old_ma.array([1,2,3,4,5], mask=[0,0,1,0,0])
+>>> x
+array(data =
+ [     1      2 999999      4      5],
+      mask =
+ [False False True False False],
+      fill_value=999999)
+>>> y = new_ma.array([1,2,3,4,5], mask=[0,0,1,0,0])
+>>> y
+array(data = [1 2 -- 4 5],
+      mask = [False False True False False],
+      fill_value=999999)
+>>> x==y
+array(data =
+ [True True True True True],
+      mask =
+ [False False True False False],
+      fill_value=?)
+>>> old_ma.getmask(x) == new_ma.getmask(x)
+array([True, True, True, True, True])
+>>> old_ma.getmask(y) == new_ma.getmask(y)
+array([True, True, False, True, True])
+>>> old_ma.getmask(y)
+False
+
+
+Using maskedarray with matplotlib
+---------------------------------
+
+Starting with matplotlib 0.91.2, the masked array importing will work with
+the maskedarray branch) as well as with earlier versions.
+
+By default matplotlib still uses numpy.ma, but there is an rcParams setting
+that you can use to select maskedarray instead.  In the matplotlibrc file
+you will find::
+
+  #maskedarray : False       # True to use external maskedarray module
+                             # instead of numpy.ma; this is a temporary #
+                             setting for testing maskedarray.
+
+
+Uncomment and set to True to select maskedarray everywhere.
+Alternatively, you can test a script with maskedarray by using a
+command-line option, e.g.::
+
+  python simple_plot.py --maskedarray
+
+
+Masked records
+--------------
+
+Like *numpy.core.ma*, the *ndarray*-based implementation
+of MaskedArray is limited when working with records: you can
+mask any record of the array, but not a field in a record. If you
+need this feature, you may want to give the *mrecords* package
+a try (available in the *maskedarray* directory in the scipy
+sandbox). This module defines a new class, *MaskedRecord*. An
+instance of this class accepts a *recarray* as data, and uses two
+masks: the *fieldmask* has as many entries as records in the array,
+each entry with the same fields as a record, but of boolean types:
+they indicate whether the field is masked or not; a record entry
+is flagged as masked in the *mask* array if all the fields are
+masked. A few examples in the file should give you an idea of what
+can be done. Note that *mrecords* is still experimental...
+
+Optimizing maskedarray
+----------------------
+
+Should masked arrays be filled before processing or not?
+--------------------------------------------------------
+
+In the current implementation, most operations on masked arrays involve
+the following steps:
+
+ * the input arrays are filled
+ * the operation is performed on the filled arrays
+ * the mask is set for the results, from the combination of the input masks and the mask corresponding to the domain of the operation.
+
+For example, consider the division of two masked arrays::
+
+  import numpy
+  import maskedarray as ma
+  x = ma.array([1,2,3,4],mask=[1,0,0,0], dtype=numpy.float_)
+  y = ma.array([-1,0,1,2], mask=[0,0,0,1], dtype=numpy.float_)
+
+The division of x by y is then computed as::
+
+  d1 = x.filled(0) # d1 = array([0., 2., 3., 4.])
+  d2 = y.filled(1) # array([-1.,  0.,  1.,  1.])
+  m = ma.mask_or(ma.getmask(x), ma.getmask(y)) # m =
+  array([True,False,False,True])
+  dm = ma.divide.domain(d1,d2) # array([False,  True, False, False])
+  result = (d1/d2).view(MaskedArray) # masked_array([-0. inf, 3., 4.])
+  result._mask = logical_or(m, dm)
+
+Note that a division by zero takes place. To avoid it, we can consider
+to fill the input arrays, taking the domain mask into account, so that::
+
+  d1 = x._data.copy() # d1 = array([1., 2., 3., 4.])
+  d2 = y._data.copy() # array([-1.,  0.,  1.,  2.])
+  dm = ma.divide.domain(d1,d2) # array([False,  True, False, False])
+  numpy.putmask(d2, dm, 1) # d2 = array([-1.,  1.,  1.,  2.])
+  m = ma.mask_or(ma.getmask(x), ma.getmask(y)) # m =
+  array([True,False,False,True])
+  result = (d1/d2).view(MaskedArray) # masked_array([-1. 0., 3., 2.])
+  result._mask = logical_or(m, dm)
+
+Note that the *.copy()* is required to avoid updating the inputs with
+*putmask*.  The *.filled()* method also involves a *.copy()*.
+
+A third possibility consists in avoid filling the arrays::
+
+  d1 = x._data # d1 = array([1., 2., 3., 4.])
+  d2 = y._data # array([-1.,  0.,  1.,  2.])
+  dm = ma.divide.domain(d1,d2) # array([False,  True, False, False])
+  m = ma.mask_or(ma.getmask(x), ma.getmask(y)) # m =
+  array([True,False,False,True])
+  result = (d1/d2).view(MaskedArray) # masked_array([-1. inf, 3., 2.])
+  result._mask = logical_or(m, dm)
+
+Note that here again the division by zero takes place.
+
+A quick benchmark gives the following results:
+
+ * *numpy.ma.divide*  : 2.69 ms per loop
+ * classical division     : 2.21 ms per loop
+ * division w/ prefilling : 2.34 ms per loop
+ * division w/o filling   : 1.55 ms per loop
+
+So, is it worth filling the arrays beforehand ? Yes, if we are interested
+in avoiding floating-point exceptions that may fill the result with infs
+and nans. No, if we are only interested into speed...
+
+
+Thanks
+------
+
+I'd like to thank Paul Dubois, Travis Oliphant and Sasha for the
+original masked array package: without you, I would never have started
+that (it might be argued that I shouldn't have anyway, but that's
+another story...).  I also wish to extend these thanks to Reggie Dugard
+and Eric Firing for their suggestions and numerous improvements.
+
+
+Revision notes
+--------------
+
+  * 08/25/2007 : Creation of this page
+  * 01/23/2007 : The package has been moved to the SciPy sandbox, and is regularly updated: please check out your SVN version!
diff --git a/venv/lib/python3.10/site-packages/numpy/ma/__init__.py b/venv/lib/python3.10/site-packages/numpy/ma/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..870cc4ef2daabf7ac770415f73940b3edfd2477c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/numpy/ma/__init__.py
@@ -0,0 +1,54 @@
+"""
+=============
+Masked Arrays
+=============
+
+Arrays sometimes contain invalid or missing data.  When doing operations
+on such arrays, we wish to suppress invalid values, which is the purpose masked
+arrays fulfill (an example of typical use is given below).
+
+For example, examine the following array:
+
+>>> x = np.array([2, 1, 3, np.nan, 5, 2, 3, np.nan])
+
+When we try to calculate the mean of the data, the result is undetermined:
+
+>>> np.mean(x)
+nan
+
+The mean is calculated using roughly ``np.sum(x)/len(x)``, but since
+any number added to ``NaN`` [1]_ produces ``NaN``, this doesn't work.  Enter
+masked arrays:
+
+>>> m = np.ma.masked_array(x, np.isnan(x))
+>>> m
+masked_array(data = [2.0 1.0 3.0 -- 5.0 2.0 3.0 --],
+      mask = [False False False  True False False False  True],
+      fill_value=1e+20)
+
+Here, we construct a masked array that suppress all ``NaN`` values.  We
+may now proceed to calculate the mean of the other values:
+
+>>> np.mean(m)
+2.6666666666666665
+
+.. [1] Not-a-Number, a floating point value that is the result of an
+       invalid operation.
+
+.. moduleauthor:: Pierre Gerard-Marchant
+.. moduleauthor:: Jarrod Millman
+
+"""
+from . import core
+from .core import *
+
+from . import extras
+from .extras import *
+
+__all__ = ['core', 'extras']
+__all__ += core.__all__
+__all__ += extras.__all__
+
+from numpy._pytesttester import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/venv/lib/python3.10/site-packages/numpy/ma/__init__.pyi b/venv/lib/python3.10/site-packages/numpy/ma/__init__.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..ce72383e5ea3d62d763e74a48694202425f10558
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/numpy/ma/__init__.pyi
@@ -0,0 +1,234 @@
+from numpy._pytesttester import PytestTester
+
+from numpy.ma import extras as extras
+
+from numpy.ma.core import (
+    MAError as MAError,
+    MaskError as MaskError,
+    MaskType as MaskType,
+    MaskedArray as MaskedArray,
+    abs as abs,
+    absolute as absolute,
+    add as add,
+    all as all,
+    allclose as allclose,
+    allequal as allequal,
+    alltrue as alltrue,
+    amax as amax,
+    amin as amin,
+    angle as angle,
+    anom as anom,
+    anomalies as anomalies,
+    any as any,
+    append as append,
+    arange as arange,
+    arccos as arccos,
+    arccosh as arccosh,
+    arcsin as arcsin,
+    arcsinh as arcsinh,
+    arctan as arctan,
+    arctan2 as arctan2,
+    arctanh as arctanh,
+    argmax as argmax,
+    argmin as argmin,
+    argsort as argsort,
+    around as around,
+    array as array,
+    asanyarray as asanyarray,
+    asarray as asarray,
+    bitwise_and as bitwise_and,
+    bitwise_or as bitwise_or,
+    bitwise_xor as bitwise_xor,
+    bool_ as bool_,
+    ceil as ceil,
+    choose as choose,
+    clip as clip,
+    common_fill_value as common_fill_value,
+    compress as compress,
+    compressed as compressed,
+    concatenate as concatenate,
+    conjugate as conjugate,
+    convolve as convolve,
+    copy as copy,
+    correlate as correlate,
+    cos as cos,
+    cosh as cosh,
+    count as count,
+    cumprod as cumprod,
+    cumsum as cumsum,
+    default_fill_value as default_fill_value,
+    diag as diag,
+    diagonal as diagonal,
+    diff as diff,
+    divide as divide,
+    empty as empty,
+    empty_like as empty_like,
+    equal as equal,
+    exp as exp,
+    expand_dims as expand_dims,
+    fabs as fabs,
+    filled as filled,
+    fix_invalid as fix_invalid,
+    flatten_mask as flatten_mask,
+    flatten_structured_array as flatten_structured_array,
+    floor as floor,
+    floor_divide as floor_divide,
+    fmod as fmod,
+    frombuffer as frombuffer,
+    fromflex as fromflex,
+    fromfunction as fromfunction,
+    getdata as getdata,
+    getmask as getmask,
+    getmaskarray as getmaskarray,
+    greater as greater,
+    greater_equal as greater_equal,
+    harden_mask as harden_mask,
+    hypot as hypot,
+    identity as identity,
+    ids as ids,
+    indices as indices,
+    inner as inner,
+    innerproduct as innerproduct,
+    isMA as isMA,
+    isMaskedArray as isMaskedArray,
+    is_mask as is_mask,
+    is_masked as is_masked,
+    isarray as isarray,
+    left_shift as left_shift,
+    less as less,
+    less_equal as less_equal,
+    log as log,
+    log10 as log10,
+    log2 as log2,
+    logical_and as logical_and,
+    logical_not as logical_not,
+    logical_or as logical_or,
+    logical_xor as logical_xor,
+    make_mask as make_mask,
+    make_mask_descr as make_mask_descr,
+    make_mask_none as make_mask_none,
+    mask_or as mask_or,
+    masked as masked,
+    masked_array as masked_array,
+    masked_equal as masked_equal,
+    masked_greater as masked_greater,
+    masked_greater_equal as masked_greater_equal,
+    masked_inside as masked_inside,
+    masked_invalid as masked_invalid,
+    masked_less as masked_less,
+    masked_less_equal as masked_less_equal,
+    masked_not_equal as masked_not_equal,
+    masked_object as masked_object,
+    masked_outside as masked_outside,
+    masked_print_option as masked_print_option,
+    masked_singleton as masked_singleton,
+    masked_values as masked_values,
+    masked_where as masked_where,
+    max as max,
+    maximum as maximum,
+    maximum_fill_value as maximum_fill_value,
+    mean as mean,
+    min as min,
+    minimum as minimum,
+    minimum_fill_value as minimum_fill_value,
+    mod as mod,
+    multiply as multiply,
+    mvoid as mvoid,
+    ndim as ndim,
+    negative as negative,
+    nomask as nomask,
+    nonzero as nonzero,
+    not_equal as not_equal,
+    ones as ones,
+    outer as outer,
+    outerproduct as outerproduct,
+    power as power,
+    prod as prod,
+    product as product,
+    ptp as ptp,
+    put as put,
+    putmask as putmask,
+    ravel as ravel,
+    remainder as remainder,
+    repeat as repeat,
+    reshape as reshape,
+    resize as resize,
+    right_shift as right_shift,
+    round as round,
+    set_fill_value as set_fill_value,
+    shape as shape,
+    sin as sin,
+    sinh as sinh,
+    size as size,
+    soften_mask as soften_mask,
+    sometrue as sometrue,
+    sort as sort,
+    sqrt as sqrt,
+    squeeze as squeeze,
+    std as std,
+    subtract as subtract,
+    sum as sum,
+    swapaxes as swapaxes,
+    take as take,
+    tan as tan,
+    tanh as tanh,
+    trace as trace,
+    transpose as transpose,
+    true_divide as true_divide,
+    var as var,
+    where as where,
+    zeros as zeros,
+)
+
+from numpy.ma.extras import (
+    apply_along_axis as apply_along_axis,
+    apply_over_axes as apply_over_axes,
+    atleast_1d as atleast_1d,
+    atleast_2d as atleast_2d,
+    atleast_3d as atleast_3d,
+    average as average,
+    clump_masked as clump_masked,
+    clump_unmasked as clump_unmasked,
+    column_stack as column_stack,
+    compress_cols as compress_cols,
+    compress_nd as compress_nd,
+    compress_rowcols as compress_rowcols,
+    compress_rows as compress_rows,
+    count_masked as count_masked,
+    corrcoef as corrcoef,
+    cov as cov,
+    diagflat as diagflat,
+    dot as dot,
+    dstack as dstack,
+    ediff1d as ediff1d,
+    flatnotmasked_contiguous as flatnotmasked_contiguous,
+    flatnotmasked_edges as flatnotmasked_edges,
+    hsplit as hsplit,
+    hstack as hstack,
+    isin as isin,
+    in1d as in1d,
+    intersect1d as intersect1d,
+    mask_cols as mask_cols,
+    mask_rowcols as mask_rowcols,
+    mask_rows as mask_rows,
+    masked_all as masked_all,
+    masked_all_like as masked_all_like,
+    median as median,
+    mr_ as mr_,
+    ndenumerate as ndenumerate,
+    notmasked_contiguous as notmasked_contiguous,
+    notmasked_edges as notmasked_edges,
+    polyfit as polyfit,
+    row_stack as row_stack,
+    setdiff1d as setdiff1d,
+    setxor1d as setxor1d,
+    stack as stack,
+    unique as unique,
+    union1d as union1d,
+    vander as vander,
+    vstack as vstack,
+)
+
+__all__: list[str]
+__path__: list[str]
+test: PytestTester
diff --git a/venv/lib/python3.10/site-packages/numpy/ma/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/numpy/ma/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a0e551ec10d7beb1c87776d44ff4002caa22ed74
Binary files /dev/null and b/venv/lib/python3.10/site-packages/numpy/ma/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/numpy/ma/__pycache__/core.cpython-310.pyc b/venv/lib/python3.10/site-packages/numpy/ma/__pycache__/core.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fa8c11055c36c617efb05b74cfe836e2acb1ac07
Binary files /dev/null and b/venv/lib/python3.10/site-packages/numpy/ma/__pycache__/core.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/numpy/ma/__pycache__/extras.cpython-310.pyc b/venv/lib/python3.10/site-packages/numpy/ma/__pycache__/extras.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fa94898f5697863472d28df1fb034b757cc6edaa
Binary files /dev/null and b/venv/lib/python3.10/site-packages/numpy/ma/__pycache__/extras.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/numpy/ma/__pycache__/mrecords.cpython-310.pyc b/venv/lib/python3.10/site-packages/numpy/ma/__pycache__/mrecords.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..00114779c2143fe17d30c4eafb4d9b164492ec4e
Binary files /dev/null and b/venv/lib/python3.10/site-packages/numpy/ma/__pycache__/mrecords.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/numpy/ma/__pycache__/setup.cpython-310.pyc b/venv/lib/python3.10/site-packages/numpy/ma/__pycache__/setup.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8aa4d4a6b043ba980d56df7bc797a895232ac768
Binary files /dev/null and b/venv/lib/python3.10/site-packages/numpy/ma/__pycache__/setup.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/numpy/ma/__pycache__/testutils.cpython-310.pyc b/venv/lib/python3.10/site-packages/numpy/ma/__pycache__/testutils.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c29debb3cde3b55c07adc81e1d3ee249e6beb956
Binary files /dev/null and b/venv/lib/python3.10/site-packages/numpy/ma/__pycache__/testutils.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/numpy/ma/__pycache__/timer_comparison.cpython-310.pyc b/venv/lib/python3.10/site-packages/numpy/ma/__pycache__/timer_comparison.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..23ac8faab8e3c715e825e2466adb9e3ba5c2f2d9
Binary files /dev/null and b/venv/lib/python3.10/site-packages/numpy/ma/__pycache__/timer_comparison.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/numpy/ma/core.py b/venv/lib/python3.10/site-packages/numpy/ma/core.py
new file mode 100644
index 0000000000000000000000000000000000000000..16f74e89e9023fffef14b459fb21736f3219ac2f
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/numpy/ma/core.py
@@ -0,0 +1,8565 @@
+"""
+numpy.ma : a package to handle missing or invalid values.
+
+This package was initially written for numarray by Paul F. Dubois
+at Lawrence Livermore National Laboratory.
+In 2006, the package was completely rewritten by Pierre Gerard-Marchant
+(University of Georgia) to make the MaskedArray class a subclass of ndarray,
+and to improve support of structured arrays.
+
+
+Copyright 1999, 2000, 2001 Regents of the University of California.
+Released for unlimited redistribution.
+
+* Adapted for numpy_core 2005 by Travis Oliphant and (mainly) Paul Dubois.
+* Subclassing of the base `ndarray` 2006 by Pierre Gerard-Marchant
+  (pgmdevlist_AT_gmail_DOT_com)
+* Improvements suggested by Reggie Dugard (reggie_AT_merfinllc_DOT_com)
+
+.. moduleauthor:: Pierre Gerard-Marchant
+
+"""
+# pylint: disable-msg=E1002
+import builtins
+import inspect
+import operator
+import warnings
+import textwrap
+import re
+from functools import reduce
+
+import numpy as np
+import numpy.core.umath as umath
+import numpy.core.numerictypes as ntypes
+from numpy.core import multiarray as mu
+from numpy import ndarray, amax, amin, iscomplexobj, bool_, _NoValue
+from numpy import array as narray
+from numpy.lib.function_base import angle
+from numpy.compat import (
+    getargspec, formatargspec, long, unicode, bytes
+    )
+from numpy import expand_dims
+from numpy.core.numeric import normalize_axis_tuple
+
+
+__all__ = [
+    'MAError', 'MaskError', 'MaskType', 'MaskedArray', 'abs', 'absolute',
+    'add', 'all', 'allclose', 'allequal', 'alltrue', 'amax', 'amin',
+    'angle', 'anom', 'anomalies', 'any', 'append', 'arange', 'arccos',
+    'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctan2', 'arctanh',
+    'argmax', 'argmin', 'argsort', 'around', 'array', 'asanyarray',
+    'asarray', 'bitwise_and', 'bitwise_or', 'bitwise_xor', 'bool_', 'ceil',
+    'choose', 'clip', 'common_fill_value', 'compress', 'compressed',
+    'concatenate', 'conjugate', 'convolve', 'copy', 'correlate', 'cos', 'cosh',
+    'count', 'cumprod', 'cumsum', 'default_fill_value', 'diag', 'diagonal',
+    'diff', 'divide', 'empty', 'empty_like', 'equal', 'exp',
+    'expand_dims', 'fabs', 'filled', 'fix_invalid', 'flatten_mask',
+    'flatten_structured_array', 'floor', 'floor_divide', 'fmod',
+    'frombuffer', 'fromflex', 'fromfunction', 'getdata', 'getmask',
+    'getmaskarray', 'greater', 'greater_equal', 'harden_mask', 'hypot',
+    'identity', 'ids', 'indices', 'inner', 'innerproduct', 'isMA',
+    'isMaskedArray', 'is_mask', 'is_masked', 'isarray', 'left_shift',
+    'less', 'less_equal', 'log', 'log10', 'log2',
+    'logical_and', 'logical_not', 'logical_or', 'logical_xor', 'make_mask',
+    'make_mask_descr', 'make_mask_none', 'mask_or', 'masked',
+    'masked_array', 'masked_equal', 'masked_greater',
+    'masked_greater_equal', 'masked_inside', 'masked_invalid',
+    'masked_less', 'masked_less_equal', 'masked_not_equal',
+    'masked_object', 'masked_outside', 'masked_print_option',
+    'masked_singleton', 'masked_values', 'masked_where', 'max', 'maximum',
+    'maximum_fill_value', 'mean', 'min', 'minimum', 'minimum_fill_value',
+    'mod', 'multiply', 'mvoid', 'ndim', 'negative', 'nomask', 'nonzero',
+    'not_equal', 'ones', 'ones_like', 'outer', 'outerproduct', 'power', 'prod',
+    'product', 'ptp', 'put', 'putmask', 'ravel', 'remainder',
+    'repeat', 'reshape', 'resize', 'right_shift', 'round', 'round_',
+    'set_fill_value', 'shape', 'sin', 'sinh', 'size', 'soften_mask',
+    'sometrue', 'sort', 'sqrt', 'squeeze', 'std', 'subtract', 'sum',
+    'swapaxes', 'take', 'tan', 'tanh', 'trace', 'transpose', 'true_divide',
+    'var', 'where', 'zeros', 'zeros_like',
+    ]
+
+MaskType = np.bool_
+nomask = MaskType(0)
+
+class MaskedArrayFutureWarning(FutureWarning):
+    pass
+
+def _deprecate_argsort_axis(arr):
+    """
+    Adjust the axis passed to argsort, warning if necessary
+
+    Parameters
+    ----------
+    arr
+        The array which argsort was called on
+
+    np.ma.argsort has a long-term bug where the default of the axis argument
+    is wrong (gh-8701), which now must be kept for backwards compatibility.
+    Thankfully, this only makes a difference when arrays are 2- or more-
+    dimensional, so we only need a warning then.
+    """
+    if arr.ndim <= 1:
+        # no warning needed - but switch to -1 anyway, to avoid surprising
+        # subclasses, which are more likely to implement scalar axes.
+        return -1
+    else:
+        # 2017-04-11, Numpy 1.13.0, gh-8701: warn on axis default
+        warnings.warn(
+            "In the future the default for argsort will be axis=-1, not the "
+            "current None, to match its documentation and np.argsort. "
+            "Explicitly pass -1 or None to silence this warning.",
+            MaskedArrayFutureWarning, stacklevel=3)
+        return None
+
+
+def doc_note(initialdoc, note):
+    """
+    Adds a Notes section to an existing docstring.
+
+    """
+    if initialdoc is None:
+        return
+    if note is None:
+        return initialdoc
+
+    notesplit = re.split(r'\n\s*?Notes\n\s*?-----', inspect.cleandoc(initialdoc))
+    notedoc = "\n\nNotes\n-----\n%s\n" % inspect.cleandoc(note)
+
+    return ''.join(notesplit[:1] + [notedoc] + notesplit[1:])
+
+
+def get_object_signature(obj):
+    """
+    Get the signature from obj
+
+    """
+    try:
+        sig = formatargspec(*getargspec(obj))
+    except TypeError:
+        sig = ''
+    return sig
+
+
+###############################################################################
+#                              Exceptions                                     #
+###############################################################################
+
+
+class MAError(Exception):
+    """
+    Class for masked array related errors.
+
+    """
+    pass
+
+
+class MaskError(MAError):
+    """
+    Class for mask related errors.
+
+    """
+    pass
+
+
+###############################################################################
+#                           Filling options                                   #
+###############################################################################
+
+
+# b: boolean - c: complex - f: floats - i: integer - O: object - S: string
+default_filler = {'b': True,
+                  'c': 1.e20 + 0.0j,
+                  'f': 1.e20,
+                  'i': 999999,
+                  'O': '?',
+                  'S': b'N/A',
+                  'u': 999999,
+                  'V': b'???',
+                  'U': 'N/A'
+                  }
+
+# Add datetime64 and timedelta64 types
+for v in ["Y", "M", "W", "D", "h", "m", "s", "ms", "us", "ns", "ps",
+          "fs", "as"]:
+    default_filler["M8[" + v + "]"] = np.datetime64("NaT", v)
+    default_filler["m8[" + v + "]"] = np.timedelta64("NaT", v)
+
+float_types_list = [np.half, np.single, np.double, np.longdouble,
+                    np.csingle, np.cdouble, np.clongdouble]
+max_filler = ntypes._minvals
+max_filler.update([(k, -np.inf) for k in float_types_list[:4]])
+max_filler.update([(k, complex(-np.inf, -np.inf)) for k in float_types_list[-3:]])
+
+min_filler = ntypes._maxvals
+min_filler.update([(k,  +np.inf) for k in float_types_list[:4]])
+min_filler.update([(k, complex(+np.inf, +np.inf)) for k in float_types_list[-3:]])
+
+del float_types_list
+
+def _recursive_fill_value(dtype, f):
+    """
+    Recursively produce a fill value for `dtype`, calling f on scalar dtypes
+    """
+    if dtype.names is not None:
+        # We wrap into `array` here, which ensures we use NumPy cast rules
+        # for integer casts, this allows the use of 99999 as a fill value
+        # for int8.
+        # TODO: This is probably a mess, but should best preserve behavior?
+        vals = tuple(
+                np.array(_recursive_fill_value(dtype[name], f))
+                for name in dtype.names)
+        return np.array(vals, dtype=dtype)[()]  # decay to void scalar from 0d
+    elif dtype.subdtype:
+        subtype, shape = dtype.subdtype
+        subval = _recursive_fill_value(subtype, f)
+        return np.full(shape, subval)
+    else:
+        return f(dtype)
+
+
+def _get_dtype_of(obj):
+    """ Convert the argument for *_fill_value into a dtype """
+    if isinstance(obj, np.dtype):
+        return obj
+    elif hasattr(obj, 'dtype'):
+        return obj.dtype
+    else:
+        return np.asanyarray(obj).dtype
+
+
+def default_fill_value(obj):
+    """
+    Return the default fill value for the argument object.
+
+    The default filling value depends on the datatype of the input
+    array or the type of the input scalar:
+
+       ========  ========
+       datatype  default
+       ========  ========
+       bool      True
+       int       999999
+       float     1.e20
+       complex   1.e20+0j
+       object    '?'
+       string    'N/A'
+       ========  ========
+
+    For structured types, a structured scalar is returned, with each field the
+    default fill value for its type.
+
+    For subarray types, the fill value is an array of the same size containing
+    the default scalar fill value.
+
+    Parameters
+    ----------
+    obj : ndarray, dtype or scalar
+        The array data-type or scalar for which the default fill value
+        is returned.
+
+    Returns
+    -------
+    fill_value : scalar
+        The default fill value.
+
+    Examples
+    --------
+    >>> np.ma.default_fill_value(1)
+    999999
+    >>> np.ma.default_fill_value(np.array([1.1, 2., np.pi]))
+    1e+20
+    >>> np.ma.default_fill_value(np.dtype(complex))
+    (1e+20+0j)
+
+    """
+    def _scalar_fill_value(dtype):
+        if dtype.kind in 'Mm':
+            return default_filler.get(dtype.str[1:], '?')
+        else:
+            return default_filler.get(dtype.kind, '?')
+
+    dtype = _get_dtype_of(obj)
+    return _recursive_fill_value(dtype, _scalar_fill_value)
+
+
+def _extremum_fill_value(obj, extremum, extremum_name):
+
+    def _scalar_fill_value(dtype):
+        try:
+            return extremum[dtype]
+        except KeyError as e:
+            raise TypeError(
+                f"Unsuitable type {dtype} for calculating {extremum_name}."
+            ) from None
+
+    dtype = _get_dtype_of(obj)
+    return _recursive_fill_value(dtype, _scalar_fill_value)
+
+
+def minimum_fill_value(obj):
+    """
+    Return the maximum value that can be represented by the dtype of an object.
+
+    This function is useful for calculating a fill value suitable for
+    taking the minimum of an array with a given dtype.
+
+    Parameters
+    ----------
+    obj : ndarray, dtype or scalar
+        An object that can be queried for it's numeric type.
+
+    Returns
+    -------
+    val : scalar
+        The maximum representable value.
+
+    Raises
+    ------
+    TypeError
+        If `obj` isn't a suitable numeric type.
+
+    See Also
+    --------
+    maximum_fill_value : The inverse function.
+    set_fill_value : Set the filling value of a masked array.
+    MaskedArray.fill_value : Return current fill value.
+
+    Examples
+    --------
+    >>> import numpy.ma as ma
+    >>> a = np.int8()
+    >>> ma.minimum_fill_value(a)
+    127
+    >>> a = np.int32()
+    >>> ma.minimum_fill_value(a)
+    2147483647
+
+    An array of numeric data can also be passed.
+
+    >>> a = np.array([1, 2, 3], dtype=np.int8)
+    >>> ma.minimum_fill_value(a)
+    127
+    >>> a = np.array([1, 2, 3], dtype=np.float32)
+    >>> ma.minimum_fill_value(a)
+    inf
+
+    """
+    return _extremum_fill_value(obj, min_filler, "minimum")
+
+
+def maximum_fill_value(obj):
+    """
+    Return the minimum value that can be represented by the dtype of an object.
+
+    This function is useful for calculating a fill value suitable for
+    taking the maximum of an array with a given dtype.
+
+    Parameters
+    ----------
+    obj : ndarray, dtype or scalar
+        An object that can be queried for it's numeric type.
+
+    Returns
+    -------
+    val : scalar
+        The minimum representable value.
+
+    Raises
+    ------
+    TypeError
+        If `obj` isn't a suitable numeric type.
+
+    See Also
+    --------
+    minimum_fill_value : The inverse function.
+    set_fill_value : Set the filling value of a masked array.
+    MaskedArray.fill_value : Return current fill value.
+
+    Examples
+    --------
+    >>> import numpy.ma as ma
+    >>> a = np.int8()
+    >>> ma.maximum_fill_value(a)
+    -128
+    >>> a = np.int32()
+    >>> ma.maximum_fill_value(a)
+    -2147483648
+
+    An array of numeric data can also be passed.
+
+    >>> a = np.array([1, 2, 3], dtype=np.int8)
+    >>> ma.maximum_fill_value(a)
+    -128
+    >>> a = np.array([1, 2, 3], dtype=np.float32)
+    >>> ma.maximum_fill_value(a)
+    -inf
+
+    """
+    return _extremum_fill_value(obj, max_filler, "maximum")
+
+
+def _recursive_set_fill_value(fillvalue, dt):
+    """
+    Create a fill value for a structured dtype.
+
+    Parameters
+    ----------
+    fillvalue : scalar or array_like
+        Scalar or array representing the fill value. If it is of shorter
+        length than the number of fields in dt, it will be resized.
+    dt : dtype
+        The structured dtype for which to create the fill value.
+
+    Returns
+    -------
+    val : tuple
+        A tuple of values corresponding to the structured fill value.
+
+    """
+    fillvalue = np.resize(fillvalue, len(dt.names))
+    output_value = []
+    for (fval, name) in zip(fillvalue, dt.names):
+        cdtype = dt[name]
+        if cdtype.subdtype:
+            cdtype = cdtype.subdtype[0]
+
+        if cdtype.names is not None:
+            output_value.append(tuple(_recursive_set_fill_value(fval, cdtype)))
+        else:
+            output_value.append(np.array(fval, dtype=cdtype).item())
+    return tuple(output_value)
+
+
+def _check_fill_value(fill_value, ndtype):
+    """
+    Private function validating the given `fill_value` for the given dtype.
+
+    If fill_value is None, it is set to the default corresponding to the dtype.
+
+    If fill_value is not None, its value is forced to the given dtype.
+
+    The result is always a 0d array.
+
+    """
+    ndtype = np.dtype(ndtype)
+    if fill_value is None:
+        fill_value = default_fill_value(ndtype)
+    elif ndtype.names is not None:
+        if isinstance(fill_value, (ndarray, np.void)):
+            try:
+                fill_value = np.array(fill_value, copy=False, dtype=ndtype)
+            except ValueError as e:
+                err_msg = "Unable to transform %s to dtype %s"
+                raise ValueError(err_msg % (fill_value, ndtype)) from e
+        else:
+            fill_value = np.asarray(fill_value, dtype=object)
+            fill_value = np.array(_recursive_set_fill_value(fill_value, ndtype),
+                                  dtype=ndtype)
+    else:
+        if isinstance(fill_value, str) and (ndtype.char not in 'OSVU'):
+            # Note this check doesn't work if fill_value is not a scalar
+            err_msg = "Cannot set fill value of string with array of dtype %s"
+            raise TypeError(err_msg % ndtype)
+        else:
+            # In case we want to convert 1e20 to int.
+            # Also in case of converting string arrays.
+            try:
+                fill_value = np.array(fill_value, copy=False, dtype=ndtype)
+            except (OverflowError, ValueError) as e:
+                # Raise TypeError instead of OverflowError or ValueError.
+                # OverflowError is seldom used, and the real problem here is
+                # that the passed fill_value is not compatible with the ndtype.
+                err_msg = "Cannot convert fill_value %s to dtype %s"
+                raise TypeError(err_msg % (fill_value, ndtype)) from e
+    return np.array(fill_value)
+
+
+def set_fill_value(a, fill_value):
+    """
+    Set the filling value of a, if a is a masked array.
+
+    This function changes the fill value of the masked array `a` in place.
+    If `a` is not a masked array, the function returns silently, without
+    doing anything.
+
+    Parameters
+    ----------
+    a : array_like
+        Input array.
+    fill_value : dtype
+        Filling value. A consistency test is performed to make sure
+        the value is compatible with the dtype of `a`.
+
+    Returns
+    -------
+    None
+        Nothing returned by this function.
+
+    See Also
+    --------
+    maximum_fill_value : Return the default fill value for a dtype.
+    MaskedArray.fill_value : Return current fill value.
+    MaskedArray.set_fill_value : Equivalent method.
+
+    Examples
+    --------
+    >>> import numpy.ma as ma
+    >>> a = np.arange(5)
+    >>> a
+    array([0, 1, 2, 3, 4])
+    >>> a = ma.masked_where(a < 3, a)
+    >>> a
+    masked_array(data=[--, --, --, 3, 4],
+                 mask=[ True,  True,  True, False, False],
+           fill_value=999999)
+    >>> ma.set_fill_value(a, -999)
+    >>> a
+    masked_array(data=[--, --, --, 3, 4],
+                 mask=[ True,  True,  True, False, False],
+           fill_value=-999)
+
+    Nothing happens if `a` is not a masked array.
+
+    >>> a = list(range(5))
+    >>> a
+    [0, 1, 2, 3, 4]
+    >>> ma.set_fill_value(a, 100)
+    >>> a
+    [0, 1, 2, 3, 4]
+    >>> a = np.arange(5)
+    >>> a
+    array([0, 1, 2, 3, 4])
+    >>> ma.set_fill_value(a, 100)
+    >>> a
+    array([0, 1, 2, 3, 4])
+
+    """
+    if isinstance(a, MaskedArray):
+        a.set_fill_value(fill_value)
+    return
+
+
+def get_fill_value(a):
+    """
+    Return the filling value of a, if any.  Otherwise, returns the
+    default filling value for that type.
+
+    """
+    if isinstance(a, MaskedArray):
+        result = a.fill_value
+    else:
+        result = default_fill_value(a)
+    return result
+
+
+def common_fill_value(a, b):
+    """
+    Return the common filling value of two masked arrays, if any.
+
+    If ``a.fill_value == b.fill_value``, return the fill value,
+    otherwise return None.
+
+    Parameters
+    ----------
+    a, b : MaskedArray
+        The masked arrays for which to compare fill values.
+
+    Returns
+    -------
+    fill_value : scalar or None
+        The common fill value, or None.
+
+    Examples
+    --------
+    >>> x = np.ma.array([0, 1.], fill_value=3)
+    >>> y = np.ma.array([0, 1.], fill_value=3)
+    >>> np.ma.common_fill_value(x, y)
+    3.0
+
+    """
+    t1 = get_fill_value(a)
+    t2 = get_fill_value(b)
+    if t1 == t2:
+        return t1
+    return None
+
+
+def filled(a, fill_value=None):
+    """
+    Return input as an array with masked data replaced by a fill value.
+
+    If `a` is not a `MaskedArray`, `a` itself is returned.
+    If `a` is a `MaskedArray` and `fill_value` is None, `fill_value` is set to
+    ``a.fill_value``.
+
+    Parameters
+    ----------
+    a : MaskedArray or array_like
+        An input object.
+    fill_value : array_like, optional.
+        Can be scalar or non-scalar. If non-scalar, the
+        resulting filled array should be broadcastable
+        over input array. Default is None.
+
+    Returns
+    -------
+    a : ndarray
+        The filled array.
+
+    See Also
+    --------
+    compressed
+
+    Examples
+    --------
+    >>> x = np.ma.array(np.arange(9).reshape(3, 3), mask=[[1, 0, 0],
+    ...                                                   [1, 0, 0],
+    ...                                                   [0, 0, 0]])
+    >>> x.filled()
+    array([[999999,      1,      2],
+           [999999,      4,      5],
+           [     6,      7,      8]])
+    >>> x.filled(fill_value=333)
+    array([[333,   1,   2],
+           [333,   4,   5],
+           [  6,   7,   8]])
+    >>> x.filled(fill_value=np.arange(3))
+    array([[0, 1, 2],
+           [0, 4, 5],
+           [6, 7, 8]])
+
+    """
+    if hasattr(a, 'filled'):
+        return a.filled(fill_value)
+
+    elif isinstance(a, ndarray):
+        # Should we check for contiguity ? and a.flags['CONTIGUOUS']:
+        return a
+    elif isinstance(a, dict):
+        return np.array(a, 'O')
+    else:
+        return np.array(a)
+
+
+def get_masked_subclass(*arrays):
+    """
+    Return the youngest subclass of MaskedArray from a list of (masked) arrays.
+
+    In case of siblings, the first listed takes over.
+
+    """
+    if len(arrays) == 1:
+        arr = arrays[0]
+        if isinstance(arr, MaskedArray):
+            rcls = type(arr)
+        else:
+            rcls = MaskedArray
+    else:
+        arrcls = [type(a) for a in arrays]
+        rcls = arrcls[0]
+        if not issubclass(rcls, MaskedArray):
+            rcls = MaskedArray
+        for cls in arrcls[1:]:
+            if issubclass(cls, rcls):
+                rcls = cls
+    # Don't return MaskedConstant as result: revert to MaskedArray
+    if rcls.__name__ == 'MaskedConstant':
+        return MaskedArray
+    return rcls
+
+
+def getdata(a, subok=True):
+    """
+    Return the data of a masked array as an ndarray.
+
+    Return the data of `a` (if any) as an ndarray if `a` is a ``MaskedArray``,
+    else return `a` as a ndarray or subclass (depending on `subok`) if not.
+
+    Parameters
+    ----------
+    a : array_like
+        Input ``MaskedArray``, alternatively a ndarray or a subclass thereof.
+    subok : bool
+        Whether to force the output to be a `pure` ndarray (False) or to
+        return a subclass of ndarray if appropriate (True, default).
+
+    See Also
+    --------
+    getmask : Return the mask of a masked array, or nomask.
+    getmaskarray : Return the mask of a masked array, or full array of False.
+
+    Examples
+    --------
+    >>> import numpy.ma as ma
+    >>> a = ma.masked_equal([[1,2],[3,4]], 2)
+    >>> a
+    masked_array(
+      data=[[1, --],
+            [3, 4]],
+      mask=[[False,  True],
+            [False, False]],
+      fill_value=2)
+    >>> ma.getdata(a)
+    array([[1, 2],
+           [3, 4]])
+
+    Equivalently use the ``MaskedArray`` `data` attribute.
+
+    >>> a.data
+    array([[1, 2],
+           [3, 4]])
+
+    """
+    try:
+        data = a._data
+    except AttributeError:
+        data = np.array(a, copy=False, subok=subok)
+    if not subok:
+        return data.view(ndarray)
+    return data
+
+
+get_data = getdata
+
+
+def fix_invalid(a, mask=nomask, copy=True, fill_value=None):
+    """
+    Return input with invalid data masked and replaced by a fill value.
+
+    Invalid data means values of `nan`, `inf`, etc.
+
+    Parameters
+    ----------
+    a : array_like
+        Input array, a (subclass of) ndarray.
+    mask : sequence, optional
+        Mask. Must be convertible to an array of booleans with the same
+        shape as `data`. True indicates a masked (i.e. invalid) data.
+    copy : bool, optional
+        Whether to use a copy of `a` (True) or to fix `a` in place (False).
+        Default is True.
+    fill_value : scalar, optional
+        Value used for fixing invalid data. Default is None, in which case
+        the ``a.fill_value`` is used.
+
+    Returns
+    -------
+    b : MaskedArray
+        The input array with invalid entries fixed.
+
+    Notes
+    -----
+    A copy is performed by default.
+
+    Examples
+    --------
+    >>> x = np.ma.array([1., -1, np.nan, np.inf], mask=[1] + [0]*3)
+    >>> x
+    masked_array(data=[--, -1.0, nan, inf],
+                 mask=[ True, False, False, False],
+           fill_value=1e+20)
+    >>> np.ma.fix_invalid(x)
+    masked_array(data=[--, -1.0, --, --],
+                 mask=[ True, False,  True,  True],
+           fill_value=1e+20)
+
+    >>> fixed = np.ma.fix_invalid(x)
+    >>> fixed.data
+    array([ 1.e+00, -1.e+00,  1.e+20,  1.e+20])
+    >>> x.data
+    array([ 1., -1., nan, inf])
+
+    """
+    a = masked_array(a, copy=copy, mask=mask, subok=True)
+    invalid = np.logical_not(np.isfinite(a._data))
+    if not invalid.any():
+        return a
+    a._mask |= invalid
+    if fill_value is None:
+        fill_value = a.fill_value
+    a._data[invalid] = fill_value
+    return a
+
+def is_string_or_list_of_strings(val):
+    return (isinstance(val, str) or
+            (isinstance(val, list) and val and
+             builtins.all(isinstance(s, str) for s in val)))
+
+###############################################################################
+#                                  Ufuncs                                     #
+###############################################################################
+
+
+ufunc_domain = {}
+ufunc_fills = {}
+
+
+class _DomainCheckInterval:
+    """
+    Define a valid interval, so that :
+
+    ``domain_check_interval(a,b)(x) == True`` where
+    ``x < a`` or ``x > b``.
+
+    """
+
+    def __init__(self, a, b):
+        "domain_check_interval(a,b)(x) = true where x < a or y > b"
+        if a > b:
+            (a, b) = (b, a)
+        self.a = a
+        self.b = b
+
+    def __call__(self, x):
+        "Execute the call behavior."
+        # nans at masked positions cause RuntimeWarnings, even though
+        # they are masked. To avoid this we suppress warnings.
+        with np.errstate(invalid='ignore'):
+            return umath.logical_or(umath.greater(x, self.b),
+                                    umath.less(x, self.a))
+
+
+class _DomainTan:
+    """
+    Define a valid interval for the `tan` function, so that:
+
+    ``domain_tan(eps) = True`` where ``abs(cos(x)) < eps``
+
+    """
+
+    def __init__(self, eps):
+        "domain_tan(eps) = true where abs(cos(x)) < eps)"
+        self.eps = eps
+
+    def __call__(self, x):
+        "Executes the call behavior."
+        with np.errstate(invalid='ignore'):
+            return umath.less(umath.absolute(umath.cos(x)), self.eps)
+
+
+class _DomainSafeDivide:
+    """
+    Define a domain for safe division.
+
+    """
+
+    def __init__(self, tolerance=None):
+        self.tolerance = tolerance
+
+    def __call__(self, a, b):
+        # Delay the selection of the tolerance to here in order to reduce numpy
+        # import times. The calculation of these parameters is a substantial
+        # component of numpy's import time.
+        if self.tolerance is None:
+            self.tolerance = np.finfo(float).tiny
+        # don't call ma ufuncs from __array_wrap__ which would fail for scalars
+        a, b = np.asarray(a), np.asarray(b)
+        with np.errstate(invalid='ignore'):
+            return umath.absolute(a) * self.tolerance >= umath.absolute(b)
+
+
+class _DomainGreater:
+    """
+    DomainGreater(v)(x) is True where x <= v.
+
+    """
+
+    def __init__(self, critical_value):
+        "DomainGreater(v)(x) = true where x <= v"
+        self.critical_value = critical_value
+
+    def __call__(self, x):
+        "Executes the call behavior."
+        with np.errstate(invalid='ignore'):
+            return umath.less_equal(x, self.critical_value)
+
+
+class _DomainGreaterEqual:
+    """
+    DomainGreaterEqual(v)(x) is True where x < v.
+
+    """
+
+    def __init__(self, critical_value):
+        "DomainGreaterEqual(v)(x) = true where x < v"
+        self.critical_value = critical_value
+
+    def __call__(self, x):
+        "Executes the call behavior."
+        with np.errstate(invalid='ignore'):
+            return umath.less(x, self.critical_value)
+
+
+class _MaskedUFunc:
+    def __init__(self, ufunc):
+        self.f = ufunc
+        self.__doc__ = ufunc.__doc__
+        self.__name__ = ufunc.__name__
+
+    def __str__(self):
+        return f"Masked version of {self.f}"
+
+
+class _MaskedUnaryOperation(_MaskedUFunc):
+    """
+    Defines masked version of unary operations, where invalid values are
+    pre-masked.
+
+    Parameters
+    ----------
+    mufunc : callable
+        The function for which to define a masked version. Made available
+        as ``_MaskedUnaryOperation.f``.
+    fill : scalar, optional
+        Filling value, default is 0.
+    domain : class instance
+        Domain for the function. Should be one of the ``_Domain*``
+        classes. Default is None.
+
+    """
+
+    def __init__(self, mufunc, fill=0, domain=None):
+        super().__init__(mufunc)
+        self.fill = fill
+        self.domain = domain
+        ufunc_domain[mufunc] = domain
+        ufunc_fills[mufunc] = fill
+
+    def __call__(self, a, *args, **kwargs):
+        """
+        Execute the call behavior.
+
+        """
+        d = getdata(a)
+        # Deal with domain
+        if self.domain is not None:
+            # Case 1.1. : Domained function
+            # nans at masked positions cause RuntimeWarnings, even though
+            # they are masked. To avoid this we suppress warnings.
+            with np.errstate(divide='ignore', invalid='ignore'):
+                result = self.f(d, *args, **kwargs)
+            # Make a mask
+            m = ~umath.isfinite(result)
+            m |= self.domain(d)
+            m |= getmask(a)
+        else:
+            # Case 1.2. : Function without a domain
+            # Get the result and the mask
+            with np.errstate(divide='ignore', invalid='ignore'):
+                result = self.f(d, *args, **kwargs)
+            m = getmask(a)
+
+        if not result.ndim:
+            # Case 2.1. : The result is scalarscalar
+            if m:
+                return masked
+            return result
+
+        if m is not nomask:
+            # Case 2.2. The result is an array
+            # We need to fill the invalid data back w/ the input Now,
+            # that's plain silly: in C, we would just skip the element and
+            # keep the original, but we do have to do it that way in Python
+
+            # In case result has a lower dtype than the inputs (as in
+            # equal)
+            try:
+                np.copyto(result, d, where=m)
+            except TypeError:
+                pass
+        # Transform to
+        masked_result = result.view(get_masked_subclass(a))
+        masked_result._mask = m
+        masked_result._update_from(a)
+        return masked_result
+
+
+class _MaskedBinaryOperation(_MaskedUFunc):
+    """
+    Define masked version of binary operations, where invalid
+    values are pre-masked.
+
+    Parameters
+    ----------
+    mbfunc : function
+        The function for which to define a masked version. Made available
+        as ``_MaskedBinaryOperation.f``.
+    domain : class instance
+        Default domain for the function. Should be one of the ``_Domain*``
+        classes. Default is None.
+    fillx : scalar, optional
+        Filling value for the first argument, default is 0.
+    filly : scalar, optional
+        Filling value for the second argument, default is 0.
+
+    """
+
+    def __init__(self, mbfunc, fillx=0, filly=0):
+        """
+        abfunc(fillx, filly) must be defined.
+
+        abfunc(x, filly) = x for all x to enable reduce.
+
+        """
+        super().__init__(mbfunc)
+        self.fillx = fillx
+        self.filly = filly
+        ufunc_domain[mbfunc] = None
+        ufunc_fills[mbfunc] = (fillx, filly)
+
+    def __call__(self, a, b, *args, **kwargs):
+        """
+        Execute the call behavior.
+
+        """
+        # Get the data, as ndarray
+        (da, db) = (getdata(a), getdata(b))
+        # Get the result
+        with np.errstate():
+            np.seterr(divide='ignore', invalid='ignore')
+            result = self.f(da, db, *args, **kwargs)
+        # Get the mask for the result
+        (ma, mb) = (getmask(a), getmask(b))
+        if ma is nomask:
+            if mb is nomask:
+                m = nomask
+            else:
+                m = umath.logical_or(getmaskarray(a), mb)
+        elif mb is nomask:
+            m = umath.logical_or(ma, getmaskarray(b))
+        else:
+            m = umath.logical_or(ma, mb)
+
+        # Case 1. : scalar
+        if not result.ndim:
+            if m:
+                return masked
+            return result
+
+        # Case 2. : array
+        # Revert result to da where masked
+        if m is not nomask and m.any():
+            # any errors, just abort; impossible to guarantee masked values
+            try:
+                np.copyto(result, da, casting='unsafe', where=m)
+            except Exception:
+                pass
+
+        # Transforms to a (subclass of) MaskedArray
+        masked_result = result.view(get_masked_subclass(a, b))
+        masked_result._mask = m
+        if isinstance(a, MaskedArray):
+            masked_result._update_from(a)
+        elif isinstance(b, MaskedArray):
+            masked_result._update_from(b)
+        return masked_result
+
+    def reduce(self, target, axis=0, dtype=None):
+        """
+        Reduce `target` along the given `axis`.
+
+        """
+        tclass = get_masked_subclass(target)
+        m = getmask(target)
+        t = filled(target, self.filly)
+        if t.shape == ():
+            t = t.reshape(1)
+            if m is not nomask:
+                m = make_mask(m, copy=True)
+                m.shape = (1,)
+
+        if m is nomask:
+            tr = self.f.reduce(t, axis)
+            mr = nomask
+        else:
+            tr = self.f.reduce(t, axis, dtype=dtype)
+            mr = umath.logical_and.reduce(m, axis)
+
+        if not tr.shape:
+            if mr:
+                return masked
+            else:
+                return tr
+        masked_tr = tr.view(tclass)
+        masked_tr._mask = mr
+        return masked_tr
+
+    def outer(self, a, b):
+        """
+        Return the function applied to the outer product of a and b.
+
+        """
+        (da, db) = (getdata(a), getdata(b))
+        d = self.f.outer(da, db)
+        ma = getmask(a)
+        mb = getmask(b)
+        if ma is nomask and mb is nomask:
+            m = nomask
+        else:
+            ma = getmaskarray(a)
+            mb = getmaskarray(b)
+            m = umath.logical_or.outer(ma, mb)
+        if (not m.ndim) and m:
+            return masked
+        if m is not nomask:
+            np.copyto(d, da, where=m)
+        if not d.shape:
+            return d
+        masked_d = d.view(get_masked_subclass(a, b))
+        masked_d._mask = m
+        return masked_d
+
+    def accumulate(self, target, axis=0):
+        """Accumulate `target` along `axis` after filling with y fill
+        value.
+
+        """
+        tclass = get_masked_subclass(target)
+        t = filled(target, self.filly)
+        result = self.f.accumulate(t, axis)
+        masked_result = result.view(tclass)
+        return masked_result
+
+
+
+class _DomainedBinaryOperation(_MaskedUFunc):
+    """
+    Define binary operations that have a domain, like divide.
+
+    They have no reduce, outer or accumulate.
+
+    Parameters
+    ----------
+    mbfunc : function
+        The function for which to define a masked version. Made available
+        as ``_DomainedBinaryOperation.f``.
+    domain : class instance
+        Default domain for the function. Should be one of the ``_Domain*``
+        classes.
+    fillx : scalar, optional
+        Filling value for the first argument, default is 0.
+    filly : scalar, optional
+        Filling value for the second argument, default is 0.
+
+    """
+
+    def __init__(self, dbfunc, domain, fillx=0, filly=0):
+        """abfunc(fillx, filly) must be defined.
+           abfunc(x, filly) = x for all x to enable reduce.
+        """
+        super().__init__(dbfunc)
+        self.domain = domain
+        self.fillx = fillx
+        self.filly = filly
+        ufunc_domain[dbfunc] = domain
+        ufunc_fills[dbfunc] = (fillx, filly)
+
+    def __call__(self, a, b, *args, **kwargs):
+        "Execute the call behavior."
+        # Get the data
+        (da, db) = (getdata(a), getdata(b))
+        # Get the result
+        with np.errstate(divide='ignore', invalid='ignore'):
+            result = self.f(da, db, *args, **kwargs)
+        # Get the mask as a combination of the source masks and invalid
+        m = ~umath.isfinite(result)
+        m |= getmask(a)
+        m |= getmask(b)
+        # Apply the domain
+        domain = ufunc_domain.get(self.f, None)
+        if domain is not None:
+            m |= domain(da, db)
+        # Take care of the scalar case first
+        if not m.ndim:
+            if m:
+                return masked
+            else:
+                return result
+        # When the mask is True, put back da if possible
+        # any errors, just abort; impossible to guarantee masked values
+        try:
+            np.copyto(result, 0, casting='unsafe', where=m)
+            # avoid using "*" since this may be overlaid
+            masked_da = umath.multiply(m, da)
+            # only add back if it can be cast safely
+            if np.can_cast(masked_da.dtype, result.dtype, casting='safe'):
+                result += masked_da
+        except Exception:
+            pass
+
+        # Transforms to a (subclass of) MaskedArray
+        masked_result = result.view(get_masked_subclass(a, b))
+        masked_result._mask = m
+        if isinstance(a, MaskedArray):
+            masked_result._update_from(a)
+        elif isinstance(b, MaskedArray):
+            masked_result._update_from(b)
+        return masked_result
+
+
+# Unary ufuncs
+exp = _MaskedUnaryOperation(umath.exp)
+conjugate = _MaskedUnaryOperation(umath.conjugate)
+sin = _MaskedUnaryOperation(umath.sin)
+cos = _MaskedUnaryOperation(umath.cos)
+arctan = _MaskedUnaryOperation(umath.arctan)
+arcsinh = _MaskedUnaryOperation(umath.arcsinh)
+sinh = _MaskedUnaryOperation(umath.sinh)
+cosh = _MaskedUnaryOperation(umath.cosh)
+tanh = _MaskedUnaryOperation(umath.tanh)
+abs = absolute = _MaskedUnaryOperation(umath.absolute)
+angle = _MaskedUnaryOperation(angle)  # from numpy.lib.function_base
+fabs = _MaskedUnaryOperation(umath.fabs)
+negative = _MaskedUnaryOperation(umath.negative)
+floor = _MaskedUnaryOperation(umath.floor)
+ceil = _MaskedUnaryOperation(umath.ceil)
+around = _MaskedUnaryOperation(np.round_)
+logical_not = _MaskedUnaryOperation(umath.logical_not)
+
+# Domained unary ufuncs
+sqrt = _MaskedUnaryOperation(umath.sqrt, 0.0,
+                             _DomainGreaterEqual(0.0))
+log = _MaskedUnaryOperation(umath.log, 1.0,
+                            _DomainGreater(0.0))
+log2 = _MaskedUnaryOperation(umath.log2, 1.0,
+                             _DomainGreater(0.0))
+log10 = _MaskedUnaryOperation(umath.log10, 1.0,
+                              _DomainGreater(0.0))
+tan = _MaskedUnaryOperation(umath.tan, 0.0,
+                            _DomainTan(1e-35))
+arcsin = _MaskedUnaryOperation(umath.arcsin, 0.0,
+                               _DomainCheckInterval(-1.0, 1.0))
+arccos = _MaskedUnaryOperation(umath.arccos, 0.0,
+                               _DomainCheckInterval(-1.0, 1.0))
+arccosh = _MaskedUnaryOperation(umath.arccosh, 1.0,
+                                _DomainGreaterEqual(1.0))
+arctanh = _MaskedUnaryOperation(umath.arctanh, 0.0,
+                                _DomainCheckInterval(-1.0 + 1e-15, 1.0 - 1e-15))
+
+# Binary ufuncs
+add = _MaskedBinaryOperation(umath.add)
+subtract = _MaskedBinaryOperation(umath.subtract)
+multiply = _MaskedBinaryOperation(umath.multiply, 1, 1)
+arctan2 = _MaskedBinaryOperation(umath.arctan2, 0.0, 1.0)
+equal = _MaskedBinaryOperation(umath.equal)
+equal.reduce = None
+not_equal = _MaskedBinaryOperation(umath.not_equal)
+not_equal.reduce = None
+less_equal = _MaskedBinaryOperation(umath.less_equal)
+less_equal.reduce = None
+greater_equal = _MaskedBinaryOperation(umath.greater_equal)
+greater_equal.reduce = None
+less = _MaskedBinaryOperation(umath.less)
+less.reduce = None
+greater = _MaskedBinaryOperation(umath.greater)
+greater.reduce = None
+logical_and = _MaskedBinaryOperation(umath.logical_and)
+alltrue = _MaskedBinaryOperation(umath.logical_and, 1, 1).reduce
+logical_or = _MaskedBinaryOperation(umath.logical_or)
+sometrue = logical_or.reduce
+logical_xor = _MaskedBinaryOperation(umath.logical_xor)
+bitwise_and = _MaskedBinaryOperation(umath.bitwise_and)
+bitwise_or = _MaskedBinaryOperation(umath.bitwise_or)
+bitwise_xor = _MaskedBinaryOperation(umath.bitwise_xor)
+hypot = _MaskedBinaryOperation(umath.hypot)
+
+# Domained binary ufuncs
+divide = _DomainedBinaryOperation(umath.divide, _DomainSafeDivide(), 0, 1)
+true_divide = _DomainedBinaryOperation(umath.true_divide,
+                                       _DomainSafeDivide(), 0, 1)
+floor_divide = _DomainedBinaryOperation(umath.floor_divide,
+                                        _DomainSafeDivide(), 0, 1)
+remainder = _DomainedBinaryOperation(umath.remainder,
+                                     _DomainSafeDivide(), 0, 1)
+fmod = _DomainedBinaryOperation(umath.fmod, _DomainSafeDivide(), 0, 1)
+mod = _DomainedBinaryOperation(umath.mod, _DomainSafeDivide(), 0, 1)
+
+
+###############################################################################
+#                        Mask creation functions                              #
+###############################################################################
+
+
+def _replace_dtype_fields_recursive(dtype, primitive_dtype):
+    "Private function allowing recursion in _replace_dtype_fields."
+    _recurse = _replace_dtype_fields_recursive
+
+    # Do we have some name fields ?
+    if dtype.names is not None:
+        descr = []
+        for name in dtype.names:
+            field = dtype.fields[name]
+            if len(field) == 3:
+                # Prepend the title to the name
+                name = (field[-1], name)
+            descr.append((name, _recurse(field[0], primitive_dtype)))
+        new_dtype = np.dtype(descr)
+
+    # Is this some kind of composite a la (float,2)
+    elif dtype.subdtype:
+        descr = list(dtype.subdtype)
+        descr[0] = _recurse(dtype.subdtype[0], primitive_dtype)
+        new_dtype = np.dtype(tuple(descr))
+
+    # this is a primitive type, so do a direct replacement
+    else:
+        new_dtype = primitive_dtype
+
+    # preserve identity of dtypes
+    if new_dtype == dtype:
+        new_dtype = dtype
+
+    return new_dtype
+
+
+def _replace_dtype_fields(dtype, primitive_dtype):
+    """
+    Construct a dtype description list from a given dtype.
+
+    Returns a new dtype object, with all fields and subtypes in the given type
+    recursively replaced with `primitive_dtype`.
+
+    Arguments are coerced to dtypes first.
+    """
+    dtype = np.dtype(dtype)
+    primitive_dtype = np.dtype(primitive_dtype)
+    return _replace_dtype_fields_recursive(dtype, primitive_dtype)
+
+
+def make_mask_descr(ndtype):
+    """
+    Construct a dtype description list from a given dtype.
+
+    Returns a new dtype object, with the type of all fields in `ndtype` to a
+    boolean type. Field names are not altered.
+
+    Parameters
+    ----------
+    ndtype : dtype
+        The dtype to convert.
+
+    Returns
+    -------
+    result : dtype
+        A dtype that looks like `ndtype`, the type of all fields is boolean.
+
+    Examples
+    --------
+    >>> import numpy.ma as ma
+    >>> dtype = np.dtype({'names':['foo', 'bar'],
+    ...                   'formats':[np.float32, np.int64]})
+    >>> dtype
+    dtype([('foo', '>> ma.make_mask_descr(dtype)
+    dtype([('foo', '|b1'), ('bar', '|b1')])
+    >>> ma.make_mask_descr(np.float32)
+    dtype('bool')
+
+    """
+    return _replace_dtype_fields(ndtype, MaskType)
+
+
+def getmask(a):
+    """
+    Return the mask of a masked array, or nomask.
+
+    Return the mask of `a` as an ndarray if `a` is a `MaskedArray` and the
+    mask is not `nomask`, else return `nomask`. To guarantee a full array
+    of booleans of the same shape as a, use `getmaskarray`.
+
+    Parameters
+    ----------
+    a : array_like
+        Input `MaskedArray` for which the mask is required.
+
+    See Also
+    --------
+    getdata : Return the data of a masked array as an ndarray.
+    getmaskarray : Return the mask of a masked array, or full array of False.
+
+    Examples
+    --------
+    >>> import numpy.ma as ma
+    >>> a = ma.masked_equal([[1,2],[3,4]], 2)
+    >>> a
+    masked_array(
+      data=[[1, --],
+            [3, 4]],
+      mask=[[False,  True],
+            [False, False]],
+      fill_value=2)
+    >>> ma.getmask(a)
+    array([[False,  True],
+           [False, False]])
+
+    Equivalently use the `MaskedArray` `mask` attribute.
+
+    >>> a.mask
+    array([[False,  True],
+           [False, False]])
+
+    Result when mask == `nomask`
+
+    >>> b = ma.masked_array([[1,2],[3,4]])
+    >>> b
+    masked_array(
+      data=[[1, 2],
+            [3, 4]],
+      mask=False,
+      fill_value=999999)
+    >>> ma.nomask
+    False
+    >>> ma.getmask(b) == ma.nomask
+    True
+    >>> b.mask == ma.nomask
+    True
+
+    """
+    return getattr(a, '_mask', nomask)
+
+
+get_mask = getmask
+
+
+def getmaskarray(arr):
+    """
+    Return the mask of a masked array, or full boolean array of False.
+
+    Return the mask of `arr` as an ndarray if `arr` is a `MaskedArray` and
+    the mask is not `nomask`, else return a full boolean array of False of
+    the same shape as `arr`.
+
+    Parameters
+    ----------
+    arr : array_like
+        Input `MaskedArray` for which the mask is required.
+
+    See Also
+    --------
+    getmask : Return the mask of a masked array, or nomask.
+    getdata : Return the data of a masked array as an ndarray.
+
+    Examples
+    --------
+    >>> import numpy.ma as ma
+    >>> a = ma.masked_equal([[1,2],[3,4]], 2)
+    >>> a
+    masked_array(
+      data=[[1, --],
+            [3, 4]],
+      mask=[[False,  True],
+            [False, False]],
+      fill_value=2)
+    >>> ma.getmaskarray(a)
+    array([[False,  True],
+           [False, False]])
+
+    Result when mask == ``nomask``
+
+    >>> b = ma.masked_array([[1,2],[3,4]])
+    >>> b
+    masked_array(
+      data=[[1, 2],
+            [3, 4]],
+      mask=False,
+      fill_value=999999)
+    >>> ma.getmaskarray(b)
+    array([[False, False],
+           [False, False]])
+
+    """
+    mask = getmask(arr)
+    if mask is nomask:
+        mask = make_mask_none(np.shape(arr), getattr(arr, 'dtype', None))
+    return mask
+
+
+def is_mask(m):
+    """
+    Return True if m is a valid, standard mask.
+
+    This function does not check the contents of the input, only that the
+    type is MaskType. In particular, this function returns False if the
+    mask has a flexible dtype.
+
+    Parameters
+    ----------
+    m : array_like
+        Array to test.
+
+    Returns
+    -------
+    result : bool
+        True if `m.dtype.type` is MaskType, False otherwise.
+
+    See Also
+    --------
+    ma.isMaskedArray : Test whether input is an instance of MaskedArray.
+
+    Examples
+    --------
+    >>> import numpy.ma as ma
+    >>> m = ma.masked_equal([0, 1, 0, 2, 3], 0)
+    >>> m
+    masked_array(data=[--, 1, --, 2, 3],
+                 mask=[ True, False,  True, False, False],
+           fill_value=0)
+    >>> ma.is_mask(m)
+    False
+    >>> ma.is_mask(m.mask)
+    True
+
+    Input must be an ndarray (or have similar attributes)
+    for it to be considered a valid mask.
+
+    >>> m = [False, True, False]
+    >>> ma.is_mask(m)
+    False
+    >>> m = np.array([False, True, False])
+    >>> m
+    array([False,  True, False])
+    >>> ma.is_mask(m)
+    True
+
+    Arrays with complex dtypes don't return True.
+
+    >>> dtype = np.dtype({'names':['monty', 'pithon'],
+    ...                   'formats':[bool, bool]})
+    >>> dtype
+    dtype([('monty', '|b1'), ('pithon', '|b1')])
+    >>> m = np.array([(True, False), (False, True), (True, False)],
+    ...              dtype=dtype)
+    >>> m
+    array([( True, False), (False,  True), ( True, False)],
+          dtype=[('monty', '?'), ('pithon', '?')])
+    >>> ma.is_mask(m)
+    False
+
+    """
+    try:
+        return m.dtype.type is MaskType
+    except AttributeError:
+        return False
+
+
+def _shrink_mask(m):
+    """
+    Shrink a mask to nomask if possible
+    """
+    if m.dtype.names is None and not m.any():
+        return nomask
+    else:
+        return m
+
+
+def make_mask(m, copy=False, shrink=True, dtype=MaskType):
+    """
+    Create a boolean mask from an array.
+
+    Return `m` as a boolean mask, creating a copy if necessary or requested.
+    The function can accept any sequence that is convertible to integers,
+    or ``nomask``.  Does not require that contents must be 0s and 1s, values
+    of 0 are interpreted as False, everything else as True.
+
+    Parameters
+    ----------
+    m : array_like
+        Potential mask.
+    copy : bool, optional
+        Whether to return a copy of `m` (True) or `m` itself (False).
+    shrink : bool, optional
+        Whether to shrink `m` to ``nomask`` if all its values are False.
+    dtype : dtype, optional
+        Data-type of the output mask. By default, the output mask has a
+        dtype of MaskType (bool). If the dtype is flexible, each field has
+        a boolean dtype. This is ignored when `m` is ``nomask``, in which
+        case ``nomask`` is always returned.
+
+    Returns
+    -------
+    result : ndarray
+        A boolean mask derived from `m`.
+
+    Examples
+    --------
+    >>> import numpy.ma as ma
+    >>> m = [True, False, True, True]
+    >>> ma.make_mask(m)
+    array([ True, False,  True,  True])
+    >>> m = [1, 0, 1, 1]
+    >>> ma.make_mask(m)
+    array([ True, False,  True,  True])
+    >>> m = [1, 0, 2, -3]
+    >>> ma.make_mask(m)
+    array([ True, False,  True,  True])
+
+    Effect of the `shrink` parameter.
+
+    >>> m = np.zeros(4)
+    >>> m
+    array([0., 0., 0., 0.])
+    >>> ma.make_mask(m)
+    False
+    >>> ma.make_mask(m, shrink=False)
+    array([False, False, False, False])
+
+    Using a flexible `dtype`.
+
+    >>> m = [1, 0, 1, 1]
+    >>> n = [0, 1, 0, 0]
+    >>> arr = []
+    >>> for man, mouse in zip(m, n):
+    ...     arr.append((man, mouse))
+    >>> arr
+    [(1, 0), (0, 1), (1, 0), (1, 0)]
+    >>> dtype = np.dtype({'names':['man', 'mouse'],
+    ...                   'formats':[np.int64, np.int64]})
+    >>> arr = np.array(arr, dtype=dtype)
+    >>> arr
+    array([(1, 0), (0, 1), (1, 0), (1, 0)],
+          dtype=[('man', '>> ma.make_mask(arr, dtype=dtype)
+    array([(True, False), (False, True), (True, False), (True, False)],
+          dtype=[('man', '|b1'), ('mouse', '|b1')])
+
+    """
+    if m is nomask:
+        return nomask
+
+    # Make sure the input dtype is valid.
+    dtype = make_mask_descr(dtype)
+
+    # legacy boolean special case: "existence of fields implies true"
+    if isinstance(m, ndarray) and m.dtype.fields and dtype == np.bool_:
+        return np.ones(m.shape, dtype=dtype)
+
+    # Fill the mask in case there are missing data; turn it into an ndarray.
+    result = np.array(filled(m, True), copy=copy, dtype=dtype, subok=True)
+    # Bas les masques !
+    if shrink:
+        result = _shrink_mask(result)
+    return result
+
+
+def make_mask_none(newshape, dtype=None):
+    """
+    Return a boolean mask of the given shape, filled with False.
+
+    This function returns a boolean ndarray with all entries False, that can
+    be used in common mask manipulations. If a complex dtype is specified, the
+    type of each field is converted to a boolean type.
+
+    Parameters
+    ----------
+    newshape : tuple
+        A tuple indicating the shape of the mask.
+    dtype : {None, dtype}, optional
+        If None, use a MaskType instance. Otherwise, use a new datatype with
+        the same fields as `dtype`, converted to boolean types.
+
+    Returns
+    -------
+    result : ndarray
+        An ndarray of appropriate shape and dtype, filled with False.
+
+    See Also
+    --------
+    make_mask : Create a boolean mask from an array.
+    make_mask_descr : Construct a dtype description list from a given dtype.
+
+    Examples
+    --------
+    >>> import numpy.ma as ma
+    >>> ma.make_mask_none((3,))
+    array([False, False, False])
+
+    Defining a more complex dtype.
+
+    >>> dtype = np.dtype({'names':['foo', 'bar'],
+    ...                   'formats':[np.float32, np.int64]})
+    >>> dtype
+    dtype([('foo', '>> ma.make_mask_none((3,), dtype=dtype)
+    array([(False, False), (False, False), (False, False)],
+          dtype=[('foo', '|b1'), ('bar', '|b1')])
+
+    """
+    if dtype is None:
+        result = np.zeros(newshape, dtype=MaskType)
+    else:
+        result = np.zeros(newshape, dtype=make_mask_descr(dtype))
+    return result
+
+
+def _recursive_mask_or(m1, m2, newmask):
+    names = m1.dtype.names
+    for name in names:
+        current1 = m1[name]
+        if current1.dtype.names is not None:
+            _recursive_mask_or(current1, m2[name], newmask[name])
+        else:
+            umath.logical_or(current1, m2[name], newmask[name])
+
+
+def mask_or(m1, m2, copy=False, shrink=True):
+    """
+    Combine two masks with the ``logical_or`` operator.
+
+    The result may be a view on `m1` or `m2` if the other is `nomask`
+    (i.e. False).
+
+    Parameters
+    ----------
+    m1, m2 : array_like
+        Input masks.
+    copy : bool, optional
+        If copy is False and one of the inputs is `nomask`, return a view
+        of the other input mask. Defaults to False.
+    shrink : bool, optional
+        Whether to shrink the output to `nomask` if all its values are
+        False. Defaults to True.
+
+    Returns
+    -------
+    mask : output mask
+        The result masks values that are masked in either `m1` or `m2`.
+
+    Raises
+    ------
+    ValueError
+        If `m1` and `m2` have different flexible dtypes.
+
+    Examples
+    --------
+    >>> m1 = np.ma.make_mask([0, 1, 1, 0])
+    >>> m2 = np.ma.make_mask([1, 0, 0, 0])
+    >>> np.ma.mask_or(m1, m2)
+    array([ True,  True,  True, False])
+
+    """
+
+    if (m1 is nomask) or (m1 is False):
+        dtype = getattr(m2, 'dtype', MaskType)
+        return make_mask(m2, copy=copy, shrink=shrink, dtype=dtype)
+    if (m2 is nomask) or (m2 is False):
+        dtype = getattr(m1, 'dtype', MaskType)
+        return make_mask(m1, copy=copy, shrink=shrink, dtype=dtype)
+    if m1 is m2 and is_mask(m1):
+        return m1
+    (dtype1, dtype2) = (getattr(m1, 'dtype', None), getattr(m2, 'dtype', None))
+    if dtype1 != dtype2:
+        raise ValueError("Incompatible dtypes '%s'<>'%s'" % (dtype1, dtype2))
+    if dtype1.names is not None:
+        # Allocate an output mask array with the properly broadcast shape.
+        newmask = np.empty(np.broadcast(m1, m2).shape, dtype1)
+        _recursive_mask_or(m1, m2, newmask)
+        return newmask
+    return make_mask(umath.logical_or(m1, m2), copy=copy, shrink=shrink)
+
+
+def flatten_mask(mask):
+    """
+    Returns a completely flattened version of the mask, where nested fields
+    are collapsed.
+
+    Parameters
+    ----------
+    mask : array_like
+        Input array, which will be interpreted as booleans.
+
+    Returns
+    -------
+    flattened_mask : ndarray of bools
+        The flattened input.
+
+    Examples
+    --------
+    >>> mask = np.array([0, 0, 1])
+    >>> np.ma.flatten_mask(mask)
+    array([False, False,  True])
+
+    >>> mask = np.array([(0, 0), (0, 1)], dtype=[('a', bool), ('b', bool)])
+    >>> np.ma.flatten_mask(mask)
+    array([False, False, False,  True])
+
+    >>> mdtype = [('a', bool), ('b', [('ba', bool), ('bb', bool)])]
+    >>> mask = np.array([(0, (0, 0)), (0, (0, 1))], dtype=mdtype)
+    >>> np.ma.flatten_mask(mask)
+    array([False, False, False, False, False,  True])
+
+    """
+
+    def _flatmask(mask):
+        "Flatten the mask and returns a (maybe nested) sequence of booleans."
+        mnames = mask.dtype.names
+        if mnames is not None:
+            return [flatten_mask(mask[name]) for name in mnames]
+        else:
+            return mask
+
+    def _flatsequence(sequence):
+        "Generates a flattened version of the sequence."
+        try:
+            for element in sequence:
+                if hasattr(element, '__iter__'):
+                    yield from _flatsequence(element)
+                else:
+                    yield element
+        except TypeError:
+            yield sequence
+
+    mask = np.asarray(mask)
+    flattened = _flatsequence(_flatmask(mask))
+    return np.array([_ for _ in flattened], dtype=bool)
+
+
+def _check_mask_axis(mask, axis, keepdims=np._NoValue):
+    "Check whether there are masked values along the given axis"
+    kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims}
+    if mask is not nomask:
+        return mask.all(axis=axis, **kwargs)
+    return nomask
+
+
+###############################################################################
+#                             Masking functions                               #
+###############################################################################
+
+def masked_where(condition, a, copy=True):
+    """
+    Mask an array where a condition is met.
+
+    Return `a` as an array masked where `condition` is True.
+    Any masked values of `a` or `condition` are also masked in the output.
+
+    Parameters
+    ----------
+    condition : array_like
+        Masking condition.  When `condition` tests floating point values for
+        equality, consider using ``masked_values`` instead.
+    a : array_like
+        Array to mask.
+    copy : bool
+        If True (default) make a copy of `a` in the result.  If False modify
+        `a` in place and return a view.
+
+    Returns
+    -------
+    result : MaskedArray
+        The result of masking `a` where `condition` is True.
+
+    See Also
+    --------
+    masked_values : Mask using floating point equality.
+    masked_equal : Mask where equal to a given value.
+    masked_not_equal : Mask where `not` equal to a given value.
+    masked_less_equal : Mask where less than or equal to a given value.
+    masked_greater_equal : Mask where greater than or equal to a given value.
+    masked_less : Mask where less than a given value.
+    masked_greater : Mask where greater than a given value.
+    masked_inside : Mask inside a given interval.
+    masked_outside : Mask outside a given interval.
+    masked_invalid : Mask invalid values (NaNs or infs).
+
+    Examples
+    --------
+    >>> import numpy.ma as ma
+    >>> a = np.arange(4)
+    >>> a
+    array([0, 1, 2, 3])
+    >>> ma.masked_where(a <= 2, a)
+    masked_array(data=[--, --, --, 3],
+                 mask=[ True,  True,  True, False],
+           fill_value=999999)
+
+    Mask array `b` conditional on `a`.
+
+    >>> b = ['a', 'b', 'c', 'd']
+    >>> ma.masked_where(a == 2, b)
+    masked_array(data=['a', 'b', --, 'd'],
+                 mask=[False, False,  True, False],
+           fill_value='N/A',
+                dtype='>> c = ma.masked_where(a <= 2, a)
+    >>> c
+    masked_array(data=[--, --, --, 3],
+                 mask=[ True,  True,  True, False],
+           fill_value=999999)
+    >>> c[0] = 99
+    >>> c
+    masked_array(data=[99, --, --, 3],
+                 mask=[False,  True,  True, False],
+           fill_value=999999)
+    >>> a
+    array([0, 1, 2, 3])
+    >>> c = ma.masked_where(a <= 2, a, copy=False)
+    >>> c[0] = 99
+    >>> c
+    masked_array(data=[99, --, --, 3],
+                 mask=[False,  True,  True, False],
+           fill_value=999999)
+    >>> a
+    array([99,  1,  2,  3])
+
+    When `condition` or `a` contain masked values.
+
+    >>> a = np.arange(4)
+    >>> a = ma.masked_where(a == 2, a)
+    >>> a
+    masked_array(data=[0, 1, --, 3],
+                 mask=[False, False,  True, False],
+           fill_value=999999)
+    >>> b = np.arange(4)
+    >>> b = ma.masked_where(b == 0, b)
+    >>> b
+    masked_array(data=[--, 1, 2, 3],
+                 mask=[ True, False, False, False],
+           fill_value=999999)
+    >>> ma.masked_where(a == 3, b)
+    masked_array(data=[--, 1, --, --],
+                 mask=[ True, False,  True,  True],
+           fill_value=999999)
+
+    """
+    # Make sure that condition is a valid standard-type mask.
+    cond = make_mask(condition, shrink=False)
+    a = np.array(a, copy=copy, subok=True)
+
+    (cshape, ashape) = (cond.shape, a.shape)
+    if cshape and cshape != ashape:
+        raise IndexError("Inconsistent shape between the condition and the input"
+                         " (got %s and %s)" % (cshape, ashape))
+    if hasattr(a, '_mask'):
+        cond = mask_or(cond, a._mask)
+        cls = type(a)
+    else:
+        cls = MaskedArray
+    result = a.view(cls)
+    # Assign to *.mask so that structured masks are handled correctly.
+    result.mask = _shrink_mask(cond)
+    # There is no view of a boolean so when 'a' is a MaskedArray with nomask
+    # the update to the result's mask has no effect.
+    if not copy and hasattr(a, '_mask') and getmask(a) is nomask:
+        a._mask = result._mask.view()
+    return result
+
+
+def masked_greater(x, value, copy=True):
+    """
+    Mask an array where greater than a given value.
+
+    This function is a shortcut to ``masked_where``, with
+    `condition` = (x > value).
+
+    See Also
+    --------
+    masked_where : Mask where a condition is met.
+
+    Examples
+    --------
+    >>> import numpy.ma as ma
+    >>> a = np.arange(4)
+    >>> a
+    array([0, 1, 2, 3])
+    >>> ma.masked_greater(a, 2)
+    masked_array(data=[0, 1, 2, --],
+                 mask=[False, False, False,  True],
+           fill_value=999999)
+
+    """
+    return masked_where(greater(x, value), x, copy=copy)
+
+
+def masked_greater_equal(x, value, copy=True):
+    """
+    Mask an array where greater than or equal to a given value.
+
+    This function is a shortcut to ``masked_where``, with
+    `condition` = (x >= value).
+
+    See Also
+    --------
+    masked_where : Mask where a condition is met.
+
+    Examples
+    --------
+    >>> import numpy.ma as ma
+    >>> a = np.arange(4)
+    >>> a
+    array([0, 1, 2, 3])
+    >>> ma.masked_greater_equal(a, 2)
+    masked_array(data=[0, 1, --, --],
+                 mask=[False, False,  True,  True],
+           fill_value=999999)
+
+    """
+    return masked_where(greater_equal(x, value), x, copy=copy)
+
+
+def masked_less(x, value, copy=True):
+    """
+    Mask an array where less than a given value.
+
+    This function is a shortcut to ``masked_where``, with
+    `condition` = (x < value).
+
+    See Also
+    --------
+    masked_where : Mask where a condition is met.
+
+    Examples
+    --------
+    >>> import numpy.ma as ma
+    >>> a = np.arange(4)
+    >>> a
+    array([0, 1, 2, 3])
+    >>> ma.masked_less(a, 2)
+    masked_array(data=[--, --, 2, 3],
+                 mask=[ True,  True, False, False],
+           fill_value=999999)
+
+    """
+    return masked_where(less(x, value), x, copy=copy)
+
+
+def masked_less_equal(x, value, copy=True):
+    """
+    Mask an array where less than or equal to a given value.
+
+    This function is a shortcut to ``masked_where``, with
+    `condition` = (x <= value).
+
+    See Also
+    --------
+    masked_where : Mask where a condition is met.
+
+    Examples
+    --------
+    >>> import numpy.ma as ma
+    >>> a = np.arange(4)
+    >>> a
+    array([0, 1, 2, 3])
+    >>> ma.masked_less_equal(a, 2)
+    masked_array(data=[--, --, --, 3],
+                 mask=[ True,  True,  True, False],
+           fill_value=999999)
+
+    """
+    return masked_where(less_equal(x, value), x, copy=copy)
+
+
+def masked_not_equal(x, value, copy=True):
+    """
+    Mask an array where `not` equal to a given value.
+
+    This function is a shortcut to ``masked_where``, with
+    `condition` = (x != value).
+
+    See Also
+    --------
+    masked_where : Mask where a condition is met.
+
+    Examples
+    --------
+    >>> import numpy.ma as ma
+    >>> a = np.arange(4)
+    >>> a
+    array([0, 1, 2, 3])
+    >>> ma.masked_not_equal(a, 2)
+    masked_array(data=[--, --, 2, --],
+                 mask=[ True,  True, False,  True],
+           fill_value=999999)
+
+    """
+    return masked_where(not_equal(x, value), x, copy=copy)
+
+
+def masked_equal(x, value, copy=True):
+    """
+    Mask an array where equal to a given value.
+
+    Return a MaskedArray, masked where the data in array `x` are
+    equal to `value`. The fill_value of the returned MaskedArray
+    is set to `value`.
+
+    For floating point arrays, consider using ``masked_values(x, value)``.
+
+    See Also
+    --------
+    masked_where : Mask where a condition is met.
+    masked_values : Mask using floating point equality.
+
+    Examples
+    --------
+    >>> import numpy.ma as ma
+    >>> a = np.arange(4)
+    >>> a
+    array([0, 1, 2, 3])
+    >>> ma.masked_equal(a, 2)
+    masked_array(data=[0, 1, --, 3],
+                 mask=[False, False,  True, False],
+           fill_value=2)
+
+    """
+    output = masked_where(equal(x, value), x, copy=copy)
+    output.fill_value = value
+    return output
+
+
+def masked_inside(x, v1, v2, copy=True):
+    """
+    Mask an array inside a given interval.
+
+    Shortcut to ``masked_where``, where `condition` is True for `x` inside
+    the interval [v1,v2] (v1 <= x <= v2).  The boundaries `v1` and `v2`
+    can be given in either order.
+
+    See Also
+    --------
+    masked_where : Mask where a condition is met.
+
+    Notes
+    -----
+    The array `x` is prefilled with its filling value.
+
+    Examples
+    --------
+    >>> import numpy.ma as ma
+    >>> x = [0.31, 1.2, 0.01, 0.2, -0.4, -1.1]
+    >>> ma.masked_inside(x, -0.3, 0.3)
+    masked_array(data=[0.31, 1.2, --, --, -0.4, -1.1],
+                 mask=[False, False,  True,  True, False, False],
+           fill_value=1e+20)
+
+    The order of `v1` and `v2` doesn't matter.
+
+    >>> ma.masked_inside(x, 0.3, -0.3)
+    masked_array(data=[0.31, 1.2, --, --, -0.4, -1.1],
+                 mask=[False, False,  True,  True, False, False],
+           fill_value=1e+20)
+
+    """
+    if v2 < v1:
+        (v1, v2) = (v2, v1)
+    xf = filled(x)
+    condition = (xf >= v1) & (xf <= v2)
+    return masked_where(condition, x, copy=copy)
+
+
+def masked_outside(x, v1, v2, copy=True):
+    """
+    Mask an array outside a given interval.
+
+    Shortcut to ``masked_where``, where `condition` is True for `x` outside
+    the interval [v1,v2] (x < v1)|(x > v2).
+    The boundaries `v1` and `v2` can be given in either order.
+
+    See Also
+    --------
+    masked_where : Mask where a condition is met.
+
+    Notes
+    -----
+    The array `x` is prefilled with its filling value.
+
+    Examples
+    --------
+    >>> import numpy.ma as ma
+    >>> x = [0.31, 1.2, 0.01, 0.2, -0.4, -1.1]
+    >>> ma.masked_outside(x, -0.3, 0.3)
+    masked_array(data=[--, --, 0.01, 0.2, --, --],
+                 mask=[ True,  True, False, False,  True,  True],
+           fill_value=1e+20)
+
+    The order of `v1` and `v2` doesn't matter.
+
+    >>> ma.masked_outside(x, 0.3, -0.3)
+    masked_array(data=[--, --, 0.01, 0.2, --, --],
+                 mask=[ True,  True, False, False,  True,  True],
+           fill_value=1e+20)
+
+    """
+    if v2 < v1:
+        (v1, v2) = (v2, v1)
+    xf = filled(x)
+    condition = (xf < v1) | (xf > v2)
+    return masked_where(condition, x, copy=copy)
+
+
+def masked_object(x, value, copy=True, shrink=True):
+    """
+    Mask the array `x` where the data are exactly equal to value.
+
+    This function is similar to `masked_values`, but only suitable
+    for object arrays: for floating point, use `masked_values` instead.
+
+    Parameters
+    ----------
+    x : array_like
+        Array to mask
+    value : object
+        Comparison value
+    copy : {True, False}, optional
+        Whether to return a copy of `x`.
+    shrink : {True, False}, optional
+        Whether to collapse a mask full of False to nomask
+
+    Returns
+    -------
+    result : MaskedArray
+        The result of masking `x` where equal to `value`.
+
+    See Also
+    --------
+    masked_where : Mask where a condition is met.
+    masked_equal : Mask where equal to a given value (integers).
+    masked_values : Mask using floating point equality.
+
+    Examples
+    --------
+    >>> import numpy.ma as ma
+    >>> food = np.array(['green_eggs', 'ham'], dtype=object)
+    >>> # don't eat spoiled food
+    >>> eat = ma.masked_object(food, 'green_eggs')
+    >>> eat
+    masked_array(data=[--, 'ham'],
+                 mask=[ True, False],
+           fill_value='green_eggs',
+                dtype=object)
+    >>> # plain ol` ham is boring
+    >>> fresh_food = np.array(['cheese', 'ham', 'pineapple'], dtype=object)
+    >>> eat = ma.masked_object(fresh_food, 'green_eggs')
+    >>> eat
+    masked_array(data=['cheese', 'ham', 'pineapple'],
+                 mask=False,
+           fill_value='green_eggs',
+                dtype=object)
+
+    Note that `mask` is set to ``nomask`` if possible.
+
+    >>> eat
+    masked_array(data=['cheese', 'ham', 'pineapple'],
+                 mask=False,
+           fill_value='green_eggs',
+                dtype=object)
+
+    """
+    if isMaskedArray(x):
+        condition = umath.equal(x._data, value)
+        mask = x._mask
+    else:
+        condition = umath.equal(np.asarray(x), value)
+        mask = nomask
+    mask = mask_or(mask, make_mask(condition, shrink=shrink))
+    return masked_array(x, mask=mask, copy=copy, fill_value=value)
+
+
+def masked_values(x, value, rtol=1e-5, atol=1e-8, copy=True, shrink=True):
+    """
+    Mask using floating point equality.
+
+    Return a MaskedArray, masked where the data in array `x` are approximately
+    equal to `value`, determined using `isclose`. The default tolerances for
+    `masked_values` are the same as those for `isclose`.
+
+    For integer types, exact equality is used, in the same way as
+    `masked_equal`.
+
+    The fill_value is set to `value` and the mask is set to ``nomask`` if
+    possible.
+
+    Parameters
+    ----------
+    x : array_like
+        Array to mask.
+    value : float
+        Masking value.
+    rtol, atol : float, optional
+        Tolerance parameters passed on to `isclose`
+    copy : bool, optional
+        Whether to return a copy of `x`.
+    shrink : bool, optional
+        Whether to collapse a mask full of False to ``nomask``.
+
+    Returns
+    -------
+    result : MaskedArray
+        The result of masking `x` where approximately equal to `value`.
+
+    See Also
+    --------
+    masked_where : Mask where a condition is met.
+    masked_equal : Mask where equal to a given value (integers).
+
+    Examples
+    --------
+    >>> import numpy.ma as ma
+    >>> x = np.array([1, 1.1, 2, 1.1, 3])
+    >>> ma.masked_values(x, 1.1)
+    masked_array(data=[1.0, --, 2.0, --, 3.0],
+                 mask=[False,  True, False,  True, False],
+           fill_value=1.1)
+
+    Note that `mask` is set to ``nomask`` if possible.
+
+    >>> ma.masked_values(x, 2.1)
+    masked_array(data=[1. , 1.1, 2. , 1.1, 3. ],
+                 mask=False,
+           fill_value=2.1)
+
+    Unlike `masked_equal`, `masked_values` can perform approximate equalities.
+
+    >>> ma.masked_values(x, 2.1, atol=1e-1)
+    masked_array(data=[1.0, 1.1, --, 1.1, 3.0],
+                 mask=[False, False,  True, False, False],
+           fill_value=2.1)
+
+    """
+    xnew = filled(x, value)
+    if np.issubdtype(xnew.dtype, np.floating):
+        mask = np.isclose(xnew, value, atol=atol, rtol=rtol)
+    else:
+        mask = umath.equal(xnew, value)
+    ret = masked_array(xnew, mask=mask, copy=copy, fill_value=value)
+    if shrink:
+        ret.shrink_mask()
+    return ret
+
+
+def masked_invalid(a, copy=True):
+    """
+    Mask an array where invalid values occur (NaNs or infs).
+
+    This function is a shortcut to ``masked_where``, with
+    `condition` = ~(np.isfinite(a)). Any pre-existing mask is conserved.
+    Only applies to arrays with a dtype where NaNs or infs make sense
+    (i.e. floating point types), but accepts any array_like object.
+
+    See Also
+    --------
+    masked_where : Mask where a condition is met.
+
+    Examples
+    --------
+    >>> import numpy.ma as ma
+    >>> a = np.arange(5, dtype=float)
+    >>> a[2] = np.NaN
+    >>> a[3] = np.PINF
+    >>> a
+    array([ 0.,  1., nan, inf,  4.])
+    >>> ma.masked_invalid(a)
+    masked_array(data=[0.0, 1.0, --, --, 4.0],
+                 mask=[False, False,  True,  True, False],
+           fill_value=1e+20)
+
+    """
+    a = np.array(a, copy=False, subok=True)
+    res = masked_where(~(np.isfinite(a)), a, copy=copy)
+    # masked_invalid previously never returned nomask as a mask and doing so
+    # threw off matplotlib (gh-22842).  So use shrink=False:
+    if res._mask is nomask:
+        res._mask = make_mask_none(res.shape, res.dtype)
+    return res
+
+###############################################################################
+#                            Printing options                                 #
+###############################################################################
+
+
+class _MaskedPrintOption:
+    """
+    Handle the string used to represent missing data in a masked array.
+
+    """
+
+    def __init__(self, display):
+        """
+        Create the masked_print_option object.
+
+        """
+        self._display = display
+        self._enabled = True
+
+    def display(self):
+        """
+        Display the string to print for masked values.
+
+        """
+        return self._display
+
+    def set_display(self, s):
+        """
+        Set the string to print for masked values.
+
+        """
+        self._display = s
+
+    def enabled(self):
+        """
+        Is the use of the display value enabled?
+
+        """
+        return self._enabled
+
+    def enable(self, shrink=1):
+        """
+        Set the enabling shrink to `shrink`.
+
+        """
+        self._enabled = shrink
+
+    def __str__(self):
+        return str(self._display)
+
+    __repr__ = __str__
+
+# if you single index into a masked location you get this object.
+masked_print_option = _MaskedPrintOption('--')
+
+
+def _recursive_printoption(result, mask, printopt):
+    """
+    Puts printoptions in result where mask is True.
+
+    Private function allowing for recursion
+
+    """
+    names = result.dtype.names
+    if names is not None:
+        for name in names:
+            curdata = result[name]
+            curmask = mask[name]
+            _recursive_printoption(curdata, curmask, printopt)
+    else:
+        np.copyto(result, printopt, where=mask)
+    return
+
+# For better or worse, these end in a newline
+_legacy_print_templates = dict(
+    long_std=textwrap.dedent("""\
+        masked_%(name)s(data =
+         %(data)s,
+        %(nlen)s        mask =
+         %(mask)s,
+        %(nlen)s  fill_value = %(fill)s)
+        """),
+    long_flx=textwrap.dedent("""\
+        masked_%(name)s(data =
+         %(data)s,
+        %(nlen)s        mask =
+         %(mask)s,
+        %(nlen)s  fill_value = %(fill)s,
+        %(nlen)s       dtype = %(dtype)s)
+        """),
+    short_std=textwrap.dedent("""\
+        masked_%(name)s(data = %(data)s,
+        %(nlen)s        mask = %(mask)s,
+        %(nlen)s  fill_value = %(fill)s)
+        """),
+    short_flx=textwrap.dedent("""\
+        masked_%(name)s(data = %(data)s,
+        %(nlen)s        mask = %(mask)s,
+        %(nlen)s  fill_value = %(fill)s,
+        %(nlen)s       dtype = %(dtype)s)
+        """)
+)
+
+###############################################################################
+#                          MaskedArray class                                  #
+###############################################################################
+
+
+def _recursive_filled(a, mask, fill_value):
+    """
+    Recursively fill `a` with `fill_value`.
+
+    """
+    names = a.dtype.names
+    for name in names:
+        current = a[name]
+        if current.dtype.names is not None:
+            _recursive_filled(current, mask[name], fill_value[name])
+        else:
+            np.copyto(current, fill_value[name], where=mask[name])
+
+
+def flatten_structured_array(a):
+    """
+    Flatten a structured array.
+
+    The data type of the output is chosen such that it can represent all of the
+    (nested) fields.
+
+    Parameters
+    ----------
+    a : structured array
+
+    Returns
+    -------
+    output : masked array or ndarray
+        A flattened masked array if the input is a masked array, otherwise a
+        standard ndarray.
+
+    Examples
+    --------
+    >>> ndtype = [('a', int), ('b', float)]
+    >>> a = np.array([(1, 1), (2, 2)], dtype=ndtype)
+    >>> np.ma.flatten_structured_array(a)
+    array([[1., 1.],
+           [2., 2.]])
+
+    """
+
+    def flatten_sequence(iterable):
+        """
+        Flattens a compound of nested iterables.
+
+        """
+        for elm in iter(iterable):
+            if hasattr(elm, '__iter__'):
+                yield from flatten_sequence(elm)
+            else:
+                yield elm
+
+    a = np.asanyarray(a)
+    inishape = a.shape
+    a = a.ravel()
+    if isinstance(a, MaskedArray):
+        out = np.array([tuple(flatten_sequence(d.item())) for d in a._data])
+        out = out.view(MaskedArray)
+        out._mask = np.array([tuple(flatten_sequence(d.item()))
+                              for d in getmaskarray(a)])
+    else:
+        out = np.array([tuple(flatten_sequence(d.item())) for d in a])
+    if len(inishape) > 1:
+        newshape = list(out.shape)
+        newshape[0] = inishape
+        out.shape = tuple(flatten_sequence(newshape))
+    return out
+
+
+def _arraymethod(funcname, onmask=True):
+    """
+    Return a class method wrapper around a basic array method.
+
+    Creates a class method which returns a masked array, where the new
+    ``_data`` array is the output of the corresponding basic method called
+    on the original ``_data``.
+
+    If `onmask` is True, the new mask is the output of the method called
+    on the initial mask. Otherwise, the new mask is just a reference
+    to the initial mask.
+
+    Parameters
+    ----------
+    funcname : str
+        Name of the function to apply on data.
+    onmask : bool
+        Whether the mask must be processed also (True) or left
+        alone (False). Default is True. Make available as `_onmask`
+        attribute.
+
+    Returns
+    -------
+    method : instancemethod
+        Class method wrapper of the specified basic array method.
+
+    """
+    def wrapped_method(self, *args, **params):
+        result = getattr(self._data, funcname)(*args, **params)
+        result = result.view(type(self))
+        result._update_from(self)
+        mask = self._mask
+        if not onmask:
+            result.__setmask__(mask)
+        elif mask is not nomask:
+            # __setmask__ makes a copy, which we don't want
+            result._mask = getattr(mask, funcname)(*args, **params)
+        return result
+    methdoc = getattr(ndarray, funcname, None) or getattr(np, funcname, None)
+    if methdoc is not None:
+        wrapped_method.__doc__ = methdoc.__doc__
+    wrapped_method.__name__ = funcname
+    return wrapped_method
+
+
+class MaskedIterator:
+    """
+    Flat iterator object to iterate over masked arrays.
+
+    A `MaskedIterator` iterator is returned by ``x.flat`` for any masked array
+    `x`. It allows iterating over the array as if it were a 1-D array,
+    either in a for-loop or by calling its `next` method.
+
+    Iteration is done in C-contiguous style, with the last index varying the
+    fastest. The iterator can also be indexed using basic slicing or
+    advanced indexing.
+
+    See Also
+    --------
+    MaskedArray.flat : Return a flat iterator over an array.
+    MaskedArray.flatten : Returns a flattened copy of an array.
+
+    Notes
+    -----
+    `MaskedIterator` is not exported by the `ma` module. Instead of
+    instantiating a `MaskedIterator` directly, use `MaskedArray.flat`.
+
+    Examples
+    --------
+    >>> x = np.ma.array(arange(6).reshape(2, 3))
+    >>> fl = x.flat
+    >>> type(fl)
+    
+    >>> for item in fl:
+    ...     print(item)
+    ...
+    0
+    1
+    2
+    3
+    4
+    5
+
+    Extracting more than a single element b indexing the `MaskedIterator`
+    returns a masked array:
+
+    >>> fl[2:4]
+    masked_array(data = [2 3],
+                 mask = False,
+           fill_value = 999999)
+
+    """
+
+    def __init__(self, ma):
+        self.ma = ma
+        self.dataiter = ma._data.flat
+
+        if ma._mask is nomask:
+            self.maskiter = None
+        else:
+            self.maskiter = ma._mask.flat
+
+    def __iter__(self):
+        return self
+
+    def __getitem__(self, indx):
+        result = self.dataiter.__getitem__(indx).view(type(self.ma))
+        if self.maskiter is not None:
+            _mask = self.maskiter.__getitem__(indx)
+            if isinstance(_mask, ndarray):
+                # set shape to match that of data; this is needed for matrices
+                _mask.shape = result.shape
+                result._mask = _mask
+            elif isinstance(_mask, np.void):
+                return mvoid(result, mask=_mask, hardmask=self.ma._hardmask)
+            elif _mask:  # Just a scalar, masked
+                return masked
+        return result
+
+    # This won't work if ravel makes a copy
+    def __setitem__(self, index, value):
+        self.dataiter[index] = getdata(value)
+        if self.maskiter is not None:
+            self.maskiter[index] = getmaskarray(value)
+
+    def __next__(self):
+        """
+        Return the next value, or raise StopIteration.
+
+        Examples
+        --------
+        >>> x = np.ma.array([3, 2], mask=[0, 1])
+        >>> fl = x.flat
+        >>> next(fl)
+        3
+        >>> next(fl)
+        masked
+        >>> next(fl)
+        Traceback (most recent call last):
+          ...
+        StopIteration
+
+        """
+        d = next(self.dataiter)
+        if self.maskiter is not None:
+            m = next(self.maskiter)
+            if isinstance(m, np.void):
+                return mvoid(d, mask=m, hardmask=self.ma._hardmask)
+            elif m:  # Just a scalar, masked
+                return masked
+        return d
+
+
+class MaskedArray(ndarray):
+    """
+    An array class with possibly masked values.
+
+    Masked values of True exclude the corresponding element from any
+    computation.
+
+    Construction::
+
+      x = MaskedArray(data, mask=nomask, dtype=None, copy=False, subok=True,
+                      ndmin=0, fill_value=None, keep_mask=True, hard_mask=None,
+                      shrink=True, order=None)
+
+    Parameters
+    ----------
+    data : array_like
+        Input data.
+    mask : sequence, optional
+        Mask. Must be convertible to an array of booleans with the same
+        shape as `data`. True indicates a masked (i.e. invalid) data.
+    dtype : dtype, optional
+        Data type of the output.
+        If `dtype` is None, the type of the data argument (``data.dtype``)
+        is used. If `dtype` is not None and different from ``data.dtype``,
+        a copy is performed.
+    copy : bool, optional
+        Whether to copy the input data (True), or to use a reference instead.
+        Default is False.
+    subok : bool, optional
+        Whether to return a subclass of `MaskedArray` if possible (True) or a
+        plain `MaskedArray`. Default is True.
+    ndmin : int, optional
+        Minimum number of dimensions. Default is 0.
+    fill_value : scalar, optional
+        Value used to fill in the masked values when necessary.
+        If None, a default based on the data-type is used.
+    keep_mask : bool, optional
+        Whether to combine `mask` with the mask of the input data, if any
+        (True), or to use only `mask` for the output (False). Default is True.
+    hard_mask : bool, optional
+        Whether to use a hard mask or not. With a hard mask, masked values
+        cannot be unmasked. Default is False.
+    shrink : bool, optional
+        Whether to force compression of an empty mask. Default is True.
+    order : {'C', 'F', 'A'}, optional
+        Specify the order of the array.  If order is 'C', then the array
+        will be in C-contiguous order (last-index varies the fastest).
+        If order is 'F', then the returned array will be in
+        Fortran-contiguous order (first-index varies the fastest).
+        If order is 'A' (default), then the returned array may be
+        in any order (either C-, Fortran-contiguous, or even discontiguous),
+        unless a copy is required, in which case it will be C-contiguous.
+
+    Examples
+    --------
+
+    The ``mask`` can be initialized with an array of boolean values
+    with the same shape as ``data``.
+
+    >>> data = np.arange(6).reshape((2, 3))
+    >>> np.ma.MaskedArray(data, mask=[[False, True, False],
+    ...                               [False, False, True]])
+    masked_array(
+      data=[[0, --, 2],
+            [3, 4, --]],
+      mask=[[False,  True, False],
+            [False, False,  True]],
+      fill_value=999999)
+
+    Alternatively, the ``mask`` can be initialized to homogeneous boolean
+    array with the same shape as ``data`` by passing in a scalar
+    boolean value:
+
+    >>> np.ma.MaskedArray(data, mask=False)
+    masked_array(
+      data=[[0, 1, 2],
+            [3, 4, 5]],
+      mask=[[False, False, False],
+            [False, False, False]],
+      fill_value=999999)
+
+    >>> np.ma.MaskedArray(data, mask=True)
+    masked_array(
+      data=[[--, --, --],
+            [--, --, --]],
+      mask=[[ True,  True,  True],
+            [ True,  True,  True]],
+      fill_value=999999,
+      dtype=int64)
+
+    .. note::
+        The recommended practice for initializing ``mask`` with a scalar
+        boolean value is to use ``True``/``False`` rather than
+        ``np.True_``/``np.False_``. The reason is :attr:`nomask`
+        is represented internally as ``np.False_``.
+
+        >>> np.False_ is np.ma.nomask
+        True
+
+    """
+
+    __array_priority__ = 15
+    _defaultmask = nomask
+    _defaulthardmask = False
+    _baseclass = ndarray
+
+    # Maximum number of elements per axis used when printing an array. The
+    # 1d case is handled separately because we need more values in this case.
+    _print_width = 100
+    _print_width_1d = 1500
+
+    def __new__(cls, data=None, mask=nomask, dtype=None, copy=False,
+                subok=True, ndmin=0, fill_value=None, keep_mask=True,
+                hard_mask=None, shrink=True, order=None):
+        """
+        Create a new masked array from scratch.
+
+        Notes
+        -----
+        A masked array can also be created by taking a .view(MaskedArray).
+
+        """
+        # Process data.
+        _data = np.array(data, dtype=dtype, copy=copy,
+                         order=order, subok=True, ndmin=ndmin)
+        _baseclass = getattr(data, '_baseclass', type(_data))
+        # Check that we're not erasing the mask.
+        if isinstance(data, MaskedArray) and (data.shape != _data.shape):
+            copy = True
+
+        # Here, we copy the _view_, so that we can attach new properties to it
+        # we must never do .view(MaskedConstant), as that would create a new
+        # instance of np.ma.masked, which make identity comparison fail
+        if isinstance(data, cls) and subok and not isinstance(data, MaskedConstant):
+            _data = ndarray.view(_data, type(data))
+        else:
+            _data = ndarray.view(_data, cls)
+
+        # Handle the case where data is not a subclass of ndarray, but
+        # still has the _mask attribute like MaskedArrays
+        if hasattr(data, '_mask') and not isinstance(data, ndarray):
+            _data._mask = data._mask
+            # FIXME: should we set `_data._sharedmask = True`?
+        # Process mask.
+        # Type of the mask
+        mdtype = make_mask_descr(_data.dtype)
+        if mask is nomask:
+            # Case 1. : no mask in input.
+            # Erase the current mask ?
+            if not keep_mask:
+                # With a reduced version
+                if shrink:
+                    _data._mask = nomask
+                # With full version
+                else:
+                    _data._mask = np.zeros(_data.shape, dtype=mdtype)
+            # Check whether we missed something
+            elif isinstance(data, (tuple, list)):
+                try:
+                    # If data is a sequence of masked array
+                    mask = np.array(
+                        [getmaskarray(np.asanyarray(m, dtype=_data.dtype))
+                         for m in data], dtype=mdtype)
+                except (ValueError, TypeError):
+                    # If data is nested
+                    mask = nomask
+                # Force shrinking of the mask if needed (and possible)
+                if (mdtype == MaskType) and mask.any():
+                    _data._mask = mask
+                    _data._sharedmask = False
+            else:
+                _data._sharedmask = not copy
+                if copy:
+                    _data._mask = _data._mask.copy()
+                    # Reset the shape of the original mask
+                    if getmask(data) is not nomask:
+                        # gh-21022 encounters an issue here
+                        # because data._mask.shape is not writeable, but
+                        # the op was also pointless in that case, because
+                        # the shapes were the same, so we can at least
+                        # avoid that path
+                        if data._mask.shape != data.shape:
+                            data._mask.shape = data.shape
+        else:
+            # Case 2. : With a mask in input.
+            # If mask is boolean, create an array of True or False
+
+            # if users pass `mask=None` be forgiving here and cast it False
+            # for speed; although the default is `mask=nomask` and can differ.
+            if mask is None:
+                mask = False
+
+            if mask is True and mdtype == MaskType:
+                mask = np.ones(_data.shape, dtype=mdtype)
+            elif mask is False and mdtype == MaskType:
+                mask = np.zeros(_data.shape, dtype=mdtype)
+            else:
+                # Read the mask with the current mdtype
+                try:
+                    mask = np.array(mask, copy=copy, dtype=mdtype)
+                # Or assume it's a sequence of bool/int
+                except TypeError:
+                    mask = np.array([tuple([m] * len(mdtype)) for m in mask],
+                                    dtype=mdtype)
+            # Make sure the mask and the data have the same shape
+            if mask.shape != _data.shape:
+                (nd, nm) = (_data.size, mask.size)
+                if nm == 1:
+                    mask = np.resize(mask, _data.shape)
+                elif nm == nd:
+                    mask = np.reshape(mask, _data.shape)
+                else:
+                    msg = "Mask and data not compatible: data size is %i, " + \
+                          "mask size is %i."
+                    raise MaskError(msg % (nd, nm))
+                copy = True
+            # Set the mask to the new value
+            if _data._mask is nomask:
+                _data._mask = mask
+                _data._sharedmask = not copy
+            else:
+                if not keep_mask:
+                    _data._mask = mask
+                    _data._sharedmask = not copy
+                else:
+                    if _data.dtype.names is not None:
+                        def _recursive_or(a, b):
+                            "do a|=b on each field of a, recursively"
+                            for name in a.dtype.names:
+                                (af, bf) = (a[name], b[name])
+                                if af.dtype.names is not None:
+                                    _recursive_or(af, bf)
+                                else:
+                                    af |= bf
+
+                        _recursive_or(_data._mask, mask)
+                    else:
+                        _data._mask = np.logical_or(mask, _data._mask)
+                    _data._sharedmask = False
+
+        # Update fill_value.
+        if fill_value is None:
+            fill_value = getattr(data, '_fill_value', None)
+        # But don't run the check unless we have something to check.
+        if fill_value is not None:
+            _data._fill_value = _check_fill_value(fill_value, _data.dtype)
+        # Process extra options ..
+        if hard_mask is None:
+            _data._hardmask = getattr(data, '_hardmask', False)
+        else:
+            _data._hardmask = hard_mask
+        _data._baseclass = _baseclass
+        return _data
+
+
+    def _update_from(self, obj):
+        """
+        Copies some attributes of obj to self.
+
+        """
+        if isinstance(obj, ndarray):
+            _baseclass = type(obj)
+        else:
+            _baseclass = ndarray
+        # We need to copy the _basedict to avoid backward propagation
+        _optinfo = {}
+        _optinfo.update(getattr(obj, '_optinfo', {}))
+        _optinfo.update(getattr(obj, '_basedict', {}))
+        if not isinstance(obj, MaskedArray):
+            _optinfo.update(getattr(obj, '__dict__', {}))
+        _dict = dict(_fill_value=getattr(obj, '_fill_value', None),
+                     _hardmask=getattr(obj, '_hardmask', False),
+                     _sharedmask=getattr(obj, '_sharedmask', False),
+                     _isfield=getattr(obj, '_isfield', False),
+                     _baseclass=getattr(obj, '_baseclass', _baseclass),
+                     _optinfo=_optinfo,
+                     _basedict=_optinfo)
+        self.__dict__.update(_dict)
+        self.__dict__.update(_optinfo)
+        return
+
+    def __array_finalize__(self, obj):
+        """
+        Finalizes the masked array.
+
+        """
+        # Get main attributes.
+        self._update_from(obj)
+
+        # We have to decide how to initialize self.mask, based on
+        # obj.mask. This is very difficult.  There might be some
+        # correspondence between the elements in the array we are being
+        # created from (= obj) and us. Or there might not. This method can
+        # be called in all kinds of places for all kinds of reasons -- could
+        # be empty_like, could be slicing, could be a ufunc, could be a view.
+        # The numpy subclassing interface simply doesn't give us any way
+        # to know, which means that at best this method will be based on
+        # guesswork and heuristics. To make things worse, there isn't even any
+        # clear consensus about what the desired behavior is. For instance,
+        # most users think that np.empty_like(marr) -- which goes via this
+        # method -- should return a masked array with an empty mask (see
+        # gh-3404 and linked discussions), but others disagree, and they have
+        # existing code which depends on empty_like returning an array that
+        # matches the input mask.
+        #
+        # Historically our algorithm was: if the template object mask had the
+        # same *number of elements* as us, then we used *it's mask object
+        # itself* as our mask, so that writes to us would also write to the
+        # original array. This is horribly broken in multiple ways.
+        #
+        # Now what we do instead is, if the template object mask has the same
+        # number of elements as us, and we do not have the same base pointer
+        # as the template object (b/c views like arr[...] should keep the same
+        # mask), then we make a copy of the template object mask and use
+        # that. This is also horribly broken but somewhat less so. Maybe.
+        if isinstance(obj, ndarray):
+            # XX: This looks like a bug -- shouldn't it check self.dtype
+            # instead?
+            if obj.dtype.names is not None:
+                _mask = getmaskarray(obj)
+            else:
+                _mask = getmask(obj)
+
+            # If self and obj point to exactly the same data, then probably
+            # self is a simple view of obj (e.g., self = obj[...]), so they
+            # should share the same mask. (This isn't 100% reliable, e.g. self
+            # could be the first row of obj, or have strange strides, but as a
+            # heuristic it's not bad.) In all other cases, we make a copy of
+            # the mask, so that future modifications to 'self' do not end up
+            # side-effecting 'obj' as well.
+            if (_mask is not nomask and obj.__array_interface__["data"][0]
+                    != self.__array_interface__["data"][0]):
+                # We should make a copy. But we could get here via astype,
+                # in which case the mask might need a new dtype as well
+                # (e.g., changing to or from a structured dtype), and the
+                # order could have changed. So, change the mask type if
+                # needed and use astype instead of copy.
+                if self.dtype == obj.dtype:
+                    _mask_dtype = _mask.dtype
+                else:
+                    _mask_dtype = make_mask_descr(self.dtype)
+
+                if self.flags.c_contiguous:
+                    order = "C"
+                elif self.flags.f_contiguous:
+                    order = "F"
+                else:
+                    order = "K"
+
+                _mask = _mask.astype(_mask_dtype, order)
+            else:
+                # Take a view so shape changes, etc., do not propagate back.
+                _mask = _mask.view()
+        else:
+            _mask = nomask
+
+        self._mask = _mask
+        # Finalize the mask
+        if self._mask is not nomask:
+            try:
+                self._mask.shape = self.shape
+            except ValueError:
+                self._mask = nomask
+            except (TypeError, AttributeError):
+                # When _mask.shape is not writable (because it's a void)
+                pass
+
+        # Finalize the fill_value
+        if self._fill_value is not None:
+            self._fill_value = _check_fill_value(self._fill_value, self.dtype)
+        elif self.dtype.names is not None:
+            # Finalize the default fill_value for structured arrays
+            self._fill_value = _check_fill_value(None, self.dtype)
+
+    def __array_wrap__(self, obj, context=None):
+        """
+        Special hook for ufuncs.
+
+        Wraps the numpy array and sets the mask according to context.
+
+        """
+        if obj is self:  # for in-place operations
+            result = obj
+        else:
+            result = obj.view(type(self))
+            result._update_from(self)
+
+        if context is not None:
+            result._mask = result._mask.copy()
+            func, args, out_i = context
+            # args sometimes contains outputs (gh-10459), which we don't want
+            input_args = args[:func.nin]
+            m = reduce(mask_or, [getmaskarray(arg) for arg in input_args])
+            # Get the domain mask
+            domain = ufunc_domain.get(func, None)
+            if domain is not None:
+                # Take the domain, and make sure it's a ndarray
+                with np.errstate(divide='ignore', invalid='ignore'):
+                    d = filled(domain(*input_args), True)
+
+                if d.any():
+                    # Fill the result where the domain is wrong
+                    try:
+                        # Binary domain: take the last value
+                        fill_value = ufunc_fills[func][-1]
+                    except TypeError:
+                        # Unary domain: just use this one
+                        fill_value = ufunc_fills[func]
+                    except KeyError:
+                        # Domain not recognized, use fill_value instead
+                        fill_value = self.fill_value
+
+                    np.copyto(result, fill_value, where=d)
+
+                    # Update the mask
+                    if m is nomask:
+                        m = d
+                    else:
+                        # Don't modify inplace, we risk back-propagation
+                        m = (m | d)
+
+            # Make sure the mask has the proper size
+            if result is not self and result.shape == () and m:
+                return masked
+            else:
+                result._mask = m
+                result._sharedmask = False
+
+        return result
+
+    def view(self, dtype=None, type=None, fill_value=None):
+        """
+        Return a view of the MaskedArray data.
+
+        Parameters
+        ----------
+        dtype : data-type or ndarray sub-class, optional
+            Data-type descriptor of the returned view, e.g., float32 or int16.
+            The default, None, results in the view having the same data-type
+            as `a`. As with ``ndarray.view``, dtype can also be specified as
+            an ndarray sub-class, which then specifies the type of the
+            returned object (this is equivalent to setting the ``type``
+            parameter).
+        type : Python type, optional
+            Type of the returned view, either ndarray or a subclass.  The
+            default None results in type preservation.
+        fill_value : scalar, optional
+            The value to use for invalid entries (None by default).
+            If None, then this argument is inferred from the passed `dtype`, or
+            in its absence the original array, as discussed in the notes below.
+
+        See Also
+        --------
+        numpy.ndarray.view : Equivalent method on ndarray object.
+
+        Notes
+        -----
+
+        ``a.view()`` is used two different ways:
+
+        ``a.view(some_dtype)`` or ``a.view(dtype=some_dtype)`` constructs a view
+        of the array's memory with a different data-type.  This can cause a
+        reinterpretation of the bytes of memory.
+
+        ``a.view(ndarray_subclass)`` or ``a.view(type=ndarray_subclass)`` just
+        returns an instance of `ndarray_subclass` that looks at the same array
+        (same shape, dtype, etc.)  This does not cause a reinterpretation of the
+        memory.
+
+        If `fill_value` is not specified, but `dtype` is specified (and is not
+        an ndarray sub-class), the `fill_value` of the MaskedArray will be
+        reset. If neither `fill_value` nor `dtype` are specified (or if
+        `dtype` is an ndarray sub-class), then the fill value is preserved.
+        Finally, if `fill_value` is specified, but `dtype` is not, the fill
+        value is set to the specified value.
+
+        For ``a.view(some_dtype)``, if ``some_dtype`` has a different number of
+        bytes per entry than the previous dtype (for example, converting a
+        regular array to a structured array), then the behavior of the view
+        cannot be predicted just from the superficial appearance of ``a`` (shown
+        by ``print(a)``). It also depends on exactly how ``a`` is stored in
+        memory. Therefore if ``a`` is C-ordered versus fortran-ordered, versus
+        defined as a slice or transpose, etc., the view may give different
+        results.
+        """
+
+        if dtype is None:
+            if type is None:
+                output = ndarray.view(self)
+            else:
+                output = ndarray.view(self, type)
+        elif type is None:
+            try:
+                if issubclass(dtype, ndarray):
+                    output = ndarray.view(self, dtype)
+                    dtype = None
+                else:
+                    output = ndarray.view(self, dtype)
+            except TypeError:
+                output = ndarray.view(self, dtype)
+        else:
+            output = ndarray.view(self, dtype, type)
+
+        # also make the mask be a view (so attr changes to the view's
+        # mask do no affect original object's mask)
+        # (especially important to avoid affecting np.masked singleton)
+        if getmask(output) is not nomask:
+            output._mask = output._mask.view()
+
+        # Make sure to reset the _fill_value if needed
+        if getattr(output, '_fill_value', None) is not None:
+            if fill_value is None:
+                if dtype is None:
+                    pass  # leave _fill_value as is
+                else:
+                    output._fill_value = None
+            else:
+                output.fill_value = fill_value
+        return output
+
+    def __getitem__(self, indx):
+        """
+        x.__getitem__(y) <==> x[y]
+
+        Return the item described by i, as a masked array.
+
+        """
+        # We could directly use ndarray.__getitem__ on self.
+        # But then we would have to modify __array_finalize__ to prevent the
+        # mask of being reshaped if it hasn't been set up properly yet
+        # So it's easier to stick to the current version
+        dout = self.data[indx]
+        _mask = self._mask
+
+        def _is_scalar(m):
+            return not isinstance(m, np.ndarray)
+
+        def _scalar_heuristic(arr, elem):
+            """
+            Return whether `elem` is a scalar result of indexing `arr`, or None
+            if undecidable without promoting nomask to a full mask
+            """
+            # obviously a scalar
+            if not isinstance(elem, np.ndarray):
+                return True
+
+            # object array scalar indexing can return anything
+            elif arr.dtype.type is np.object_:
+                if arr.dtype is not elem.dtype:
+                    # elem is an array, but dtypes do not match, so must be
+                    # an element
+                    return True
+
+            # well-behaved subclass that only returns 0d arrays when
+            # expected - this is not a scalar
+            elif type(arr).__getitem__ == ndarray.__getitem__:
+                return False
+
+            return None
+
+        if _mask is not nomask:
+            # _mask cannot be a subclass, so it tells us whether we should
+            # expect a scalar. It also cannot be of dtype object.
+            mout = _mask[indx]
+            scalar_expected = _is_scalar(mout)
+
+        else:
+            # attempt to apply the heuristic to avoid constructing a full mask
+            mout = nomask
+            scalar_expected = _scalar_heuristic(self.data, dout)
+            if scalar_expected is None:
+                # heuristics have failed
+                # construct a full array, so we can be certain. This is costly.
+                # we could also fall back on ndarray.__getitem__(self.data, indx)
+                scalar_expected = _is_scalar(getmaskarray(self)[indx])
+
+        # Did we extract a single item?
+        if scalar_expected:
+            # A record
+            if isinstance(dout, np.void):
+                # We should always re-cast to mvoid, otherwise users can
+                # change masks on rows that already have masked values, but not
+                # on rows that have no masked values, which is inconsistent.
+                return mvoid(dout, mask=mout, hardmask=self._hardmask)
+
+            # special case introduced in gh-5962
+            elif (self.dtype.type is np.object_ and
+                  isinstance(dout, np.ndarray) and
+                  dout is not masked):
+                # If masked, turn into a MaskedArray, with everything masked.
+                if mout:
+                    return MaskedArray(dout, mask=True)
+                else:
+                    return dout
+
+            # Just a scalar
+            else:
+                if mout:
+                    return masked
+                else:
+                    return dout
+        else:
+            # Force dout to MA
+            dout = dout.view(type(self))
+            # Inherit attributes from self
+            dout._update_from(self)
+            # Check the fill_value
+            if is_string_or_list_of_strings(indx):
+                if self._fill_value is not None:
+                    dout._fill_value = self._fill_value[indx]
+
+                    # Something like gh-15895 has happened if this check fails.
+                    # _fill_value should always be an ndarray.
+                    if not isinstance(dout._fill_value, np.ndarray):
+                        raise RuntimeError('Internal NumPy error.')
+                    # If we're indexing a multidimensional field in a
+                    # structured array (such as dtype("(2,)i2,(2,)i1")),
+                    # dimensionality goes up (M[field].ndim == M.ndim +
+                    # M.dtype[field].ndim).  That's fine for
+                    # M[field] but problematic for M[field].fill_value
+                    # which should have shape () to avoid breaking several
+                    # methods. There is no great way out, so set to
+                    # first element. See issue #6723.
+                    if dout._fill_value.ndim > 0:
+                        if not (dout._fill_value ==
+                                dout._fill_value.flat[0]).all():
+                            warnings.warn(
+                                "Upon accessing multidimensional field "
+                                f"{indx!s}, need to keep dimensionality "
+                                "of fill_value at 0. Discarding "
+                                "heterogeneous fill_value and setting "
+                                f"all to {dout._fill_value[0]!s}.",
+                                stacklevel=2)
+                        # Need to use `.flat[0:1].squeeze(...)` instead of just
+                        # `.flat[0]` to ensure the result is a 0d array and not
+                        # a scalar.
+                        dout._fill_value = dout._fill_value.flat[0:1].squeeze(axis=0)
+                dout._isfield = True
+            # Update the mask if needed
+            if mout is not nomask:
+                # set shape to match that of data; this is needed for matrices
+                dout._mask = reshape(mout, dout.shape)
+                dout._sharedmask = True
+                # Note: Don't try to check for m.any(), that'll take too long
+        return dout
+
+    # setitem may put NaNs into integer arrays or occasionally overflow a
+    # float.  But this may happen in masked values, so avoid otherwise
+    # correct warnings (as is typical also in masked calculations).
+    @np.errstate(over='ignore', invalid='ignore')
+    def __setitem__(self, indx, value):
+        """
+        x.__setitem__(i, y) <==> x[i]=y
+
+        Set item described by index. If value is masked, masks those
+        locations.
+
+        """
+        if self is masked:
+            raise MaskError('Cannot alter the masked element.')
+        _data = self._data
+        _mask = self._mask
+        if isinstance(indx, str):
+            _data[indx] = value
+            if _mask is nomask:
+                self._mask = _mask = make_mask_none(self.shape, self.dtype)
+            _mask[indx] = getmask(value)
+            return
+
+        _dtype = _data.dtype
+
+        if value is masked:
+            # The mask wasn't set: create a full version.
+            if _mask is nomask:
+                _mask = self._mask = make_mask_none(self.shape, _dtype)
+            # Now, set the mask to its value.
+            if _dtype.names is not None:
+                _mask[indx] = tuple([True] * len(_dtype.names))
+            else:
+                _mask[indx] = True
+            return
+
+        # Get the _data part of the new value
+        dval = getattr(value, '_data', value)
+        # Get the _mask part of the new value
+        mval = getmask(value)
+        if _dtype.names is not None and mval is nomask:
+            mval = tuple([False] * len(_dtype.names))
+        if _mask is nomask:
+            # Set the data, then the mask
+            _data[indx] = dval
+            if mval is not nomask:
+                _mask = self._mask = make_mask_none(self.shape, _dtype)
+                _mask[indx] = mval
+        elif not self._hardmask:
+            # Set the data, then the mask
+            if (isinstance(indx, masked_array) and
+                    not isinstance(value, masked_array)):
+                _data[indx.data] = dval
+            else:
+                _data[indx] = dval
+                _mask[indx] = mval
+        elif hasattr(indx, 'dtype') and (indx.dtype == MaskType):
+            indx = indx * umath.logical_not(_mask)
+            _data[indx] = dval
+        else:
+            if _dtype.names is not None:
+                err_msg = "Flexible 'hard' masks are not yet supported."
+                raise NotImplementedError(err_msg)
+            mindx = mask_or(_mask[indx], mval, copy=True)
+            dindx = self._data[indx]
+            if dindx.size > 1:
+                np.copyto(dindx, dval, where=~mindx)
+            elif mindx is nomask:
+                dindx = dval
+            _data[indx] = dindx
+            _mask[indx] = mindx
+        return
+
+    # Define so that we can overwrite the setter.
+    @property
+    def dtype(self):
+        return super().dtype
+
+    @dtype.setter
+    def dtype(self, dtype):
+        super(MaskedArray, type(self)).dtype.__set__(self, dtype)
+        if self._mask is not nomask:
+            self._mask = self._mask.view(make_mask_descr(dtype), ndarray)
+            # Try to reset the shape of the mask (if we don't have a void).
+            # This raises a ValueError if the dtype change won't work.
+            try:
+                self._mask.shape = self.shape
+            except (AttributeError, TypeError):
+                pass
+
+    @property
+    def shape(self):
+        return super().shape
+
+    @shape.setter
+    def shape(self, shape):
+        super(MaskedArray, type(self)).shape.__set__(self, shape)
+        # Cannot use self._mask, since it may not (yet) exist when a
+        # masked matrix sets the shape.
+        if getmask(self) is not nomask:
+            self._mask.shape = self.shape
+
+    def __setmask__(self, mask, copy=False):
+        """
+        Set the mask.
+
+        """
+        idtype = self.dtype
+        current_mask = self._mask
+        if mask is masked:
+            mask = True
+
+        if current_mask is nomask:
+            # Make sure the mask is set
+            # Just don't do anything if there's nothing to do.
+            if mask is nomask:
+                return
+            current_mask = self._mask = make_mask_none(self.shape, idtype)
+
+        if idtype.names is None:
+            # No named fields.
+            # Hardmask: don't unmask the data
+            if self._hardmask:
+                current_mask |= mask
+            # Softmask: set everything to False
+            # If it's obviously a compatible scalar, use a quick update
+            # method.
+            elif isinstance(mask, (int, float, np.bool_, np.number)):
+                current_mask[...] = mask
+            # Otherwise fall back to the slower, general purpose way.
+            else:
+                current_mask.flat = mask
+        else:
+            # Named fields w/
+            mdtype = current_mask.dtype
+            mask = np.array(mask, copy=False)
+            # Mask is a singleton
+            if not mask.ndim:
+                # It's a boolean : make a record
+                if mask.dtype.kind == 'b':
+                    mask = np.array(tuple([mask.item()] * len(mdtype)),
+                                    dtype=mdtype)
+                # It's a record: make sure the dtype is correct
+                else:
+                    mask = mask.astype(mdtype)
+            # Mask is a sequence
+            else:
+                # Make sure the new mask is a ndarray with the proper dtype
+                try:
+                    mask = np.array(mask, copy=copy, dtype=mdtype)
+                # Or assume it's a sequence of bool/int
+                except TypeError:
+                    mask = np.array([tuple([m] * len(mdtype)) for m in mask],
+                                    dtype=mdtype)
+            # Hardmask: don't unmask the data
+            if self._hardmask:
+                for n in idtype.names:
+                    current_mask[n] |= mask[n]
+            # Softmask: set everything to False
+            # If it's obviously a compatible scalar, use a quick update
+            # method.
+            elif isinstance(mask, (int, float, np.bool_, np.number)):
+                current_mask[...] = mask
+            # Otherwise fall back to the slower, general purpose way.
+            else:
+                current_mask.flat = mask
+        # Reshape if needed
+        if current_mask.shape:
+            current_mask.shape = self.shape
+        return
+
+    _set_mask = __setmask__
+
+    @property
+    def mask(self):
+        """ Current mask. """
+
+        # We could try to force a reshape, but that wouldn't work in some
+        # cases.
+        # Return a view so that the dtype and shape cannot be changed in place
+        # This still preserves nomask by identity
+        return self._mask.view()
+
+    @mask.setter
+    def mask(self, value):
+        self.__setmask__(value)
+
+    @property
+    def recordmask(self):
+        """
+        Get or set the mask of the array if it has no named fields. For
+        structured arrays, returns a ndarray of booleans where entries are
+        ``True`` if **all** the fields are masked, ``False`` otherwise:
+
+        >>> x = np.ma.array([(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)],
+        ...         mask=[(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)],
+        ...        dtype=[('a', int), ('b', int)])
+        >>> x.recordmask
+        array([False, False,  True, False, False])
+        """
+
+        _mask = self._mask.view(ndarray)
+        if _mask.dtype.names is None:
+            return _mask
+        return np.all(flatten_structured_array(_mask), axis=-1)
+
+    @recordmask.setter
+    def recordmask(self, mask):
+        raise NotImplementedError("Coming soon: setting the mask per records!")
+
+    def harden_mask(self):
+        """
+        Force the mask to hard, preventing unmasking by assignment.
+
+        Whether the mask of a masked array is hard or soft is determined by
+        its `~ma.MaskedArray.hardmask` property. `harden_mask` sets
+        `~ma.MaskedArray.hardmask` to ``True`` (and returns the modified
+        self).
+
+        See Also
+        --------
+        ma.MaskedArray.hardmask
+        ma.MaskedArray.soften_mask
+
+        """
+        self._hardmask = True
+        return self
+
+    def soften_mask(self):
+        """
+        Force the mask to soft (default), allowing unmasking by assignment.
+
+        Whether the mask of a masked array is hard or soft is determined by
+        its `~ma.MaskedArray.hardmask` property. `soften_mask` sets
+        `~ma.MaskedArray.hardmask` to ``False`` (and returns the modified
+        self).
+
+        See Also
+        --------
+        ma.MaskedArray.hardmask
+        ma.MaskedArray.harden_mask
+
+        """
+        self._hardmask = False
+        return self
+
+    @property
+    def hardmask(self):
+        """
+        Specifies whether values can be unmasked through assignments.
+
+        By default, assigning definite values to masked array entries will
+        unmask them.  When `hardmask` is ``True``, the mask will not change
+        through assignments.
+
+        See Also
+        --------
+        ma.MaskedArray.harden_mask
+        ma.MaskedArray.soften_mask
+
+        Examples
+        --------
+        >>> x = np.arange(10)
+        >>> m = np.ma.masked_array(x, x>5)
+        >>> assert not m.hardmask
+
+        Since `m` has a soft mask, assigning an element value unmasks that
+        element:
+
+        >>> m[8] = 42
+        >>> m
+        masked_array(data=[0, 1, 2, 3, 4, 5, --, --, 42, --],
+                     mask=[False, False, False, False, False, False,
+                           True, True, False, True],
+               fill_value=999999)
+
+        After hardening, the mask is not affected by assignments:
+
+        >>> hardened = np.ma.harden_mask(m)
+        >>> assert m.hardmask and hardened is m
+        >>> m[:] = 23
+        >>> m
+        masked_array(data=[23, 23, 23, 23, 23, 23, --, --, 23, --],
+                     mask=[False, False, False, False, False, False,
+                           True, True, False, True],
+               fill_value=999999)
+
+        """
+        return self._hardmask
+
+    def unshare_mask(self):
+        """
+        Copy the mask and set the `sharedmask` flag to ``False``.
+
+        Whether the mask is shared between masked arrays can be seen from
+        the `sharedmask` property. `unshare_mask` ensures the mask is not
+        shared. A copy of the mask is only made if it was shared.
+
+        See Also
+        --------
+        sharedmask
+
+        """
+        if self._sharedmask:
+            self._mask = self._mask.copy()
+            self._sharedmask = False
+        return self
+
+    @property
+    def sharedmask(self):
+        """ Share status of the mask (read-only). """
+        return self._sharedmask
+
+    def shrink_mask(self):
+        """
+        Reduce a mask to nomask when possible.
+
+        Parameters
+        ----------
+        None
+
+        Returns
+        -------
+        None
+
+        Examples
+        --------
+        >>> x = np.ma.array([[1,2 ], [3, 4]], mask=[0]*4)
+        >>> x.mask
+        array([[False, False],
+               [False, False]])
+        >>> x.shrink_mask()
+        masked_array(
+          data=[[1, 2],
+                [3, 4]],
+          mask=False,
+          fill_value=999999)
+        >>> x.mask
+        False
+
+        """
+        self._mask = _shrink_mask(self._mask)
+        return self
+
+    @property
+    def baseclass(self):
+        """ Class of the underlying data (read-only). """
+        return self._baseclass
+
+    def _get_data(self):
+        """
+        Returns the underlying data, as a view of the masked array.
+
+        If the underlying data is a subclass of :class:`numpy.ndarray`, it is
+        returned as such.
+
+        >>> x = np.ma.array(np.matrix([[1, 2], [3, 4]]), mask=[[0, 1], [1, 0]])
+        >>> x.data
+        matrix([[1, 2],
+                [3, 4]])
+
+        The type of the data can be accessed through the :attr:`baseclass`
+        attribute.
+        """
+        return ndarray.view(self, self._baseclass)
+
+    _data = property(fget=_get_data)
+    data = property(fget=_get_data)
+
+    @property
+    def flat(self):
+        """ Return a flat iterator, or set a flattened version of self to value. """
+        return MaskedIterator(self)
+
+    @flat.setter
+    def flat(self, value):
+        y = self.ravel()
+        y[:] = value
+
+    @property
+    def fill_value(self):
+        """
+        The filling value of the masked array is a scalar. When setting, None
+        will set to a default based on the data type.
+
+        Examples
+        --------
+        >>> for dt in [np.int32, np.int64, np.float64, np.complex128]:
+        ...     np.ma.array([0, 1], dtype=dt).get_fill_value()
+        ...
+        999999
+        999999
+        1e+20
+        (1e+20+0j)
+
+        >>> x = np.ma.array([0, 1.], fill_value=-np.inf)
+        >>> x.fill_value
+        -inf
+        >>> x.fill_value = np.pi
+        >>> x.fill_value
+        3.1415926535897931 # may vary
+
+        Reset to default:
+
+        >>> x.fill_value = None
+        >>> x.fill_value
+        1e+20
+
+        """
+        if self._fill_value is None:
+            self._fill_value = _check_fill_value(None, self.dtype)
+
+        # Temporary workaround to account for the fact that str and bytes
+        # scalars cannot be indexed with (), whereas all other numpy
+        # scalars can. See issues #7259 and #7267.
+        # The if-block can be removed after #7267 has been fixed.
+        if isinstance(self._fill_value, ndarray):
+            return self._fill_value[()]
+        return self._fill_value
+
+    @fill_value.setter
+    def fill_value(self, value=None):
+        target = _check_fill_value(value, self.dtype)
+        if not target.ndim == 0:
+            # 2019-11-12, 1.18.0
+            warnings.warn(
+                "Non-scalar arrays for the fill value are deprecated. Use "
+                "arrays with scalar values instead. The filled function "
+                "still supports any array as `fill_value`.",
+                DeprecationWarning, stacklevel=2)
+
+        _fill_value = self._fill_value
+        if _fill_value is None:
+            # Create the attribute if it was undefined
+            self._fill_value = target
+        else:
+            # Don't overwrite the attribute, just fill it (for propagation)
+            _fill_value[()] = target
+
+    # kept for compatibility
+    get_fill_value = fill_value.fget
+    set_fill_value = fill_value.fset
+
+    def filled(self, fill_value=None):
+        """
+        Return a copy of self, with masked values filled with a given value.
+        **However**, if there are no masked values to fill, self will be
+        returned instead as an ndarray.
+
+        Parameters
+        ----------
+        fill_value : array_like, optional
+            The value to use for invalid entries. Can be scalar or non-scalar.
+            If non-scalar, the resulting ndarray must be broadcastable over
+            input array. Default is None, in which case, the `fill_value`
+            attribute of the array is used instead.
+
+        Returns
+        -------
+        filled_array : ndarray
+            A copy of ``self`` with invalid entries replaced by *fill_value*
+            (be it the function argument or the attribute of ``self``), or
+            ``self`` itself as an ndarray if there are no invalid entries to
+            be replaced.
+
+        Notes
+        -----
+        The result is **not** a MaskedArray!
+
+        Examples
+        --------
+        >>> x = np.ma.array([1,2,3,4,5], mask=[0,0,1,0,1], fill_value=-999)
+        >>> x.filled()
+        array([   1,    2, -999,    4, -999])
+        >>> x.filled(fill_value=1000)
+        array([   1,    2, 1000,    4, 1000])
+        >>> type(x.filled())
+        
+
+        Subclassing is preserved. This means that if, e.g., the data part of
+        the masked array is a recarray, `filled` returns a recarray:
+
+        >>> x = np.array([(-1, 2), (-3, 4)], dtype='i8,i8').view(np.recarray)
+        >>> m = np.ma.array(x, mask=[(True, False), (False, True)])
+        >>> m.filled()
+        rec.array([(999999,      2), (    -3, 999999)],
+                  dtype=[('f0', '>> x = np.ma.array(np.arange(5), mask=[0]*2 + [1]*3)
+        >>> x.compressed()
+        array([0, 1])
+        >>> type(x.compressed())
+        
+
+        """
+        data = ndarray.ravel(self._data)
+        if self._mask is not nomask:
+            data = data.compress(np.logical_not(ndarray.ravel(self._mask)))
+        return data
+
+    def compress(self, condition, axis=None, out=None):
+        """
+        Return `a` where condition is ``True``.
+
+        If condition is a `~ma.MaskedArray`, missing values are considered
+        as ``False``.
+
+        Parameters
+        ----------
+        condition : var
+            Boolean 1-d array selecting which entries to return. If len(condition)
+            is less than the size of a along the axis, then output is truncated
+            to length of condition array.
+        axis : {None, int}, optional
+            Axis along which the operation must be performed.
+        out : {None, ndarray}, optional
+            Alternative output array in which to place the result. It must have
+            the same shape as the expected output but the type will be cast if
+            necessary.
+
+        Returns
+        -------
+        result : MaskedArray
+            A :class:`~ma.MaskedArray` object.
+
+        Notes
+        -----
+        Please note the difference with :meth:`compressed` !
+        The output of :meth:`compress` has a mask, the output of
+        :meth:`compressed` does not.
+
+        Examples
+        --------
+        >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
+        >>> x
+        masked_array(
+          data=[[1, --, 3],
+                [--, 5, --],
+                [7, --, 9]],
+          mask=[[False,  True, False],
+                [ True, False,  True],
+                [False,  True, False]],
+          fill_value=999999)
+        >>> x.compress([1, 0, 1])
+        masked_array(data=[1, 3],
+                     mask=[False, False],
+               fill_value=999999)
+
+        >>> x.compress([1, 0, 1], axis=1)
+        masked_array(
+          data=[[1, 3],
+                [--, --],
+                [7, 9]],
+          mask=[[False, False],
+                [ True,  True],
+                [False, False]],
+          fill_value=999999)
+
+        """
+        # Get the basic components
+        (_data, _mask) = (self._data, self._mask)
+
+        # Force the condition to a regular ndarray and forget the missing
+        # values.
+        condition = np.asarray(condition)
+
+        _new = _data.compress(condition, axis=axis, out=out).view(type(self))
+        _new._update_from(self)
+        if _mask is not nomask:
+            _new._mask = _mask.compress(condition, axis=axis)
+        return _new
+
+    def _insert_masked_print(self):
+        """
+        Replace masked values with masked_print_option, casting all innermost
+        dtypes to object.
+        """
+        if masked_print_option.enabled():
+            mask = self._mask
+            if mask is nomask:
+                res = self._data
+            else:
+                # convert to object array to make filled work
+                data = self._data
+                # For big arrays, to avoid a costly conversion to the
+                # object dtype, extract the corners before the conversion.
+                print_width = (self._print_width if self.ndim > 1
+                               else self._print_width_1d)
+                for axis in range(self.ndim):
+                    if data.shape[axis] > print_width:
+                        ind = print_width // 2
+                        arr = np.split(data, (ind, -ind), axis=axis)
+                        data = np.concatenate((arr[0], arr[2]), axis=axis)
+                        arr = np.split(mask, (ind, -ind), axis=axis)
+                        mask = np.concatenate((arr[0], arr[2]), axis=axis)
+
+                rdtype = _replace_dtype_fields(self.dtype, "O")
+                res = data.astype(rdtype)
+                _recursive_printoption(res, mask, masked_print_option)
+        else:
+            res = self.filled(self.fill_value)
+        return res
+
+    def __str__(self):
+        return str(self._insert_masked_print())
+
+    def __repr__(self):
+        """
+        Literal string representation.
+
+        """
+        if self._baseclass is np.ndarray:
+            name = 'array'
+        else:
+            name = self._baseclass.__name__
+
+
+        # 2016-11-19: Demoted to legacy format
+        if np.core.arrayprint._get_legacy_print_mode() <= 113:
+            is_long = self.ndim > 1
+            parameters = dict(
+                name=name,
+                nlen=" " * len(name),
+                data=str(self),
+                mask=str(self._mask),
+                fill=str(self.fill_value),
+                dtype=str(self.dtype)
+            )
+            is_structured = bool(self.dtype.names)
+            key = '{}_{}'.format(
+                'long' if is_long else 'short',
+                'flx' if is_structured else 'std'
+            )
+            return _legacy_print_templates[key] % parameters
+
+        prefix = f"masked_{name}("
+
+        dtype_needed = (
+            not np.core.arrayprint.dtype_is_implied(self.dtype) or
+            np.all(self.mask) or
+            self.size == 0
+        )
+
+        # determine which keyword args need to be shown
+        keys = ['data', 'mask', 'fill_value']
+        if dtype_needed:
+            keys.append('dtype')
+
+        # array has only one row (non-column)
+        is_one_row = builtins.all(dim == 1 for dim in self.shape[:-1])
+
+        # choose what to indent each keyword with
+        min_indent = 2
+        if is_one_row:
+            # first key on the same line as the type, remaining keys
+            # aligned by equals
+            indents = {}
+            indents[keys[0]] = prefix
+            for k in keys[1:]:
+                n = builtins.max(min_indent, len(prefix + keys[0]) - len(k))
+                indents[k] = ' ' * n
+            prefix = ''  # absorbed into the first indent
+        else:
+            # each key on its own line, indented by two spaces
+            indents = {k: ' ' * min_indent for k in keys}
+            prefix = prefix + '\n'  # first key on the next line
+
+        # format the field values
+        reprs = {}
+        reprs['data'] = np.array2string(
+            self._insert_masked_print(),
+            separator=", ",
+            prefix=indents['data'] + 'data=',
+            suffix=',')
+        reprs['mask'] = np.array2string(
+            self._mask,
+            separator=", ",
+            prefix=indents['mask'] + 'mask=',
+            suffix=',')
+        reprs['fill_value'] = repr(self.fill_value)
+        if dtype_needed:
+            reprs['dtype'] = np.core.arrayprint.dtype_short_repr(self.dtype)
+
+        # join keys with values and indentations
+        result = ',\n'.join(
+            '{}{}={}'.format(indents[k], k, reprs[k])
+            for k in keys
+        )
+        return prefix + result + ')'
+
+    def _delegate_binop(self, other):
+        # This emulates the logic in
+        #     private/binop_override.h:forward_binop_should_defer
+        if isinstance(other, type(self)):
+            return False
+        array_ufunc = getattr(other, "__array_ufunc__", False)
+        if array_ufunc is False:
+            other_priority = getattr(other, "__array_priority__", -1000000)
+            return self.__array_priority__ < other_priority
+        else:
+            # If array_ufunc is not None, it will be called inside the ufunc;
+            # None explicitly tells us to not call the ufunc, i.e., defer.
+            return array_ufunc is None
+
+    def _comparison(self, other, compare):
+        """Compare self with other using operator.eq or operator.ne.
+
+        When either of the elements is masked, the result is masked as well,
+        but the underlying boolean data are still set, with self and other
+        considered equal if both are masked, and unequal otherwise.
+
+        For structured arrays, all fields are combined, with masked values
+        ignored. The result is masked if all fields were masked, with self
+        and other considered equal only if both were fully masked.
+        """
+        omask = getmask(other)
+        smask = self.mask
+        mask = mask_or(smask, omask, copy=True)
+
+        odata = getdata(other)
+        if mask.dtype.names is not None:
+            # only == and != are reasonably defined for structured dtypes,
+            # so give up early for all other comparisons:
+            if compare not in (operator.eq, operator.ne):
+                return NotImplemented
+            # For possibly masked structured arrays we need to be careful,
+            # since the standard structured array comparison will use all
+            # fields, masked or not. To avoid masked fields influencing the
+            # outcome, we set all masked fields in self to other, so they'll
+            # count as equal.  To prepare, we ensure we have the right shape.
+            broadcast_shape = np.broadcast(self, odata).shape
+            sbroadcast = np.broadcast_to(self, broadcast_shape, subok=True)
+            sbroadcast._mask = mask
+            sdata = sbroadcast.filled(odata)
+            # Now take care of the mask; the merged mask should have an item
+            # masked if all fields were masked (in one and/or other).
+            mask = (mask == np.ones((), mask.dtype))
+            # Ensure we can compare masks below if other was not masked.
+            if omask is np.False_:
+                omask = np.zeros((), smask.dtype)
+
+        else:
+            # For regular arrays, just use the data as they come.
+            sdata = self.data
+
+        check = compare(sdata, odata)
+
+        if isinstance(check, (np.bool_, bool)):
+            return masked if mask else check
+
+        if mask is not nomask:
+            if compare in (operator.eq, operator.ne):
+                # Adjust elements that were masked, which should be treated
+                # as equal if masked in both, unequal if masked in one.
+                # Note that this works automatically for structured arrays too.
+                # Ignore this for operations other than `==` and `!=`
+                check = np.where(mask, compare(smask, omask), check)
+
+            if mask.shape != check.shape:
+                # Guarantee consistency of the shape, making a copy since the
+                # the mask may need to get written to later.
+                mask = np.broadcast_to(mask, check.shape).copy()
+
+        check = check.view(type(self))
+        check._update_from(self)
+        check._mask = mask
+
+        # Cast fill value to bool_ if needed. If it cannot be cast, the
+        # default boolean fill value is used.
+        if check._fill_value is not None:
+            try:
+                fill = _check_fill_value(check._fill_value, np.bool_)
+            except (TypeError, ValueError):
+                fill = _check_fill_value(None, np.bool_)
+            check._fill_value = fill
+
+        return check
+
+    def __eq__(self, other):
+        """Check whether other equals self elementwise.
+
+        When either of the elements is masked, the result is masked as well,
+        but the underlying boolean data are still set, with self and other
+        considered equal if both are masked, and unequal otherwise.
+
+        For structured arrays, all fields are combined, with masked values
+        ignored. The result is masked if all fields were masked, with self
+        and other considered equal only if both were fully masked.
+        """
+        return self._comparison(other, operator.eq)
+
+    def __ne__(self, other):
+        """Check whether other does not equal self elementwise.
+
+        When either of the elements is masked, the result is masked as well,
+        but the underlying boolean data are still set, with self and other
+        considered equal if both are masked, and unequal otherwise.
+
+        For structured arrays, all fields are combined, with masked values
+        ignored. The result is masked if all fields were masked, with self
+        and other considered equal only if both were fully masked.
+        """
+        return self._comparison(other, operator.ne)
+
+    # All other comparisons:
+    def __le__(self, other):
+        return self._comparison(other, operator.le)
+
+    def __lt__(self, other):
+        return self._comparison(other, operator.lt)
+
+    def __ge__(self, other):
+        return self._comparison(other, operator.ge)
+
+    def __gt__(self, other):
+        return self._comparison(other, operator.gt)
+
+    def __add__(self, other):
+        """
+        Add self to other, and return a new masked array.
+
+        """
+        if self._delegate_binop(other):
+            return NotImplemented
+        return add(self, other)
+
+    def __radd__(self, other):
+        """
+        Add other to self, and return a new masked array.
+
+        """
+        # In analogy with __rsub__ and __rdiv__, use original order:
+        # we get here from `other + self`.
+        return add(other, self)
+
+    def __sub__(self, other):
+        """
+        Subtract other from self, and return a new masked array.
+
+        """
+        if self._delegate_binop(other):
+            return NotImplemented
+        return subtract(self, other)
+
+    def __rsub__(self, other):
+        """
+        Subtract self from other, and return a new masked array.
+
+        """
+        return subtract(other, self)
+
+    def __mul__(self, other):
+        "Multiply self by other, and return a new masked array."
+        if self._delegate_binop(other):
+            return NotImplemented
+        return multiply(self, other)
+
+    def __rmul__(self, other):
+        """
+        Multiply other by self, and return a new masked array.
+
+        """
+        # In analogy with __rsub__ and __rdiv__, use original order:
+        # we get here from `other * self`.
+        return multiply(other, self)
+
+    def __div__(self, other):
+        """
+        Divide other into self, and return a new masked array.
+
+        """
+        if self._delegate_binop(other):
+            return NotImplemented
+        return divide(self, other)
+
+    def __truediv__(self, other):
+        """
+        Divide other into self, and return a new masked array.
+
+        """
+        if self._delegate_binop(other):
+            return NotImplemented
+        return true_divide(self, other)
+
+    def __rtruediv__(self, other):
+        """
+        Divide self into other, and return a new masked array.
+
+        """
+        return true_divide(other, self)
+
+    def __floordiv__(self, other):
+        """
+        Divide other into self, and return a new masked array.
+
+        """
+        if self._delegate_binop(other):
+            return NotImplemented
+        return floor_divide(self, other)
+
+    def __rfloordiv__(self, other):
+        """
+        Divide self into other, and return a new masked array.
+
+        """
+        return floor_divide(other, self)
+
+    def __pow__(self, other):
+        """
+        Raise self to the power other, masking the potential NaNs/Infs
+
+        """
+        if self._delegate_binop(other):
+            return NotImplemented
+        return power(self, other)
+
+    def __rpow__(self, other):
+        """
+        Raise other to the power self, masking the potential NaNs/Infs
+
+        """
+        return power(other, self)
+
+    def __iadd__(self, other):
+        """
+        Add other to self in-place.
+
+        """
+        m = getmask(other)
+        if self._mask is nomask:
+            if m is not nomask and m.any():
+                self._mask = make_mask_none(self.shape, self.dtype)
+                self._mask += m
+        else:
+            if m is not nomask:
+                self._mask += m
+        other_data = getdata(other)
+        other_data = np.where(self._mask, other_data.dtype.type(0), other_data)
+        self._data.__iadd__(other_data)
+        return self
+
+    def __isub__(self, other):
+        """
+        Subtract other from self in-place.
+
+        """
+        m = getmask(other)
+        if self._mask is nomask:
+            if m is not nomask and m.any():
+                self._mask = make_mask_none(self.shape, self.dtype)
+                self._mask += m
+        elif m is not nomask:
+            self._mask += m
+        other_data = getdata(other)
+        other_data = np.where(self._mask, other_data.dtype.type(0), other_data)
+        self._data.__isub__(other_data)
+        return self
+
+    def __imul__(self, other):
+        """
+        Multiply self by other in-place.
+
+        """
+        m = getmask(other)
+        if self._mask is nomask:
+            if m is not nomask and m.any():
+                self._mask = make_mask_none(self.shape, self.dtype)
+                self._mask += m
+        elif m is not nomask:
+            self._mask += m
+        other_data = getdata(other)
+        other_data = np.where(self._mask, other_data.dtype.type(1), other_data)
+        self._data.__imul__(other_data)
+        return self
+
+    def __idiv__(self, other):
+        """
+        Divide self by other in-place.
+
+        """
+        other_data = getdata(other)
+        dom_mask = _DomainSafeDivide().__call__(self._data, other_data)
+        other_mask = getmask(other)
+        new_mask = mask_or(other_mask, dom_mask)
+        # The following 4 lines control the domain filling
+        if dom_mask.any():
+            (_, fval) = ufunc_fills[np.divide]
+            other_data = np.where(
+                    dom_mask, other_data.dtype.type(fval), other_data)
+        self._mask |= new_mask
+        other_data = np.where(self._mask, other_data.dtype.type(1), other_data)
+        self._data.__idiv__(other_data)
+        return self
+
+    def __ifloordiv__(self, other):
+        """
+        Floor divide self by other in-place.
+
+        """
+        other_data = getdata(other)
+        dom_mask = _DomainSafeDivide().__call__(self._data, other_data)
+        other_mask = getmask(other)
+        new_mask = mask_or(other_mask, dom_mask)
+        # The following 3 lines control the domain filling
+        if dom_mask.any():
+            (_, fval) = ufunc_fills[np.floor_divide]
+            other_data = np.where(
+                    dom_mask, other_data.dtype.type(fval), other_data)
+        self._mask |= new_mask
+        other_data = np.where(self._mask, other_data.dtype.type(1), other_data)
+        self._data.__ifloordiv__(other_data)
+        return self
+
+    def __itruediv__(self, other):
+        """
+        True divide self by other in-place.
+
+        """
+        other_data = getdata(other)
+        dom_mask = _DomainSafeDivide().__call__(self._data, other_data)
+        other_mask = getmask(other)
+        new_mask = mask_or(other_mask, dom_mask)
+        # The following 3 lines control the domain filling
+        if dom_mask.any():
+            (_, fval) = ufunc_fills[np.true_divide]
+            other_data = np.where(
+                    dom_mask, other_data.dtype.type(fval), other_data)
+        self._mask |= new_mask
+        other_data = np.where(self._mask, other_data.dtype.type(1), other_data)
+        self._data.__itruediv__(other_data)
+        return self
+
+    def __ipow__(self, other):
+        """
+        Raise self to the power other, in place.
+
+        """
+        other_data = getdata(other)
+        other_data = np.where(self._mask, other_data.dtype.type(1), other_data)
+        other_mask = getmask(other)
+        with np.errstate(divide='ignore', invalid='ignore'):
+            self._data.__ipow__(other_data)
+        invalid = np.logical_not(np.isfinite(self._data))
+        if invalid.any():
+            if self._mask is not nomask:
+                self._mask |= invalid
+            else:
+                self._mask = invalid
+            np.copyto(self._data, self.fill_value, where=invalid)
+        new_mask = mask_or(other_mask, invalid)
+        self._mask = mask_or(self._mask, new_mask)
+        return self
+
+    def __float__(self):
+        """
+        Convert to float.
+
+        """
+        if self.size > 1:
+            raise TypeError("Only length-1 arrays can be converted "
+                            "to Python scalars")
+        elif self._mask:
+            warnings.warn("Warning: converting a masked element to nan.", stacklevel=2)
+            return np.nan
+        return float(self.item())
+
+    def __int__(self):
+        """
+        Convert to int.
+
+        """
+        if self.size > 1:
+            raise TypeError("Only length-1 arrays can be converted "
+                            "to Python scalars")
+        elif self._mask:
+            raise MaskError('Cannot convert masked element to a Python int.')
+        return int(self.item())
+
+    @property
+    def imag(self):
+        """
+        The imaginary part of the masked array.
+
+        This property is a view on the imaginary part of this `MaskedArray`.
+
+        See Also
+        --------
+        real
+
+        Examples
+        --------
+        >>> x = np.ma.array([1+1.j, -2j, 3.45+1.6j], mask=[False, True, False])
+        >>> x.imag
+        masked_array(data=[1.0, --, 1.6],
+                     mask=[False,  True, False],
+               fill_value=1e+20)
+
+        """
+        result = self._data.imag.view(type(self))
+        result.__setmask__(self._mask)
+        return result
+
+    # kept for compatibility
+    get_imag = imag.fget
+
+    @property
+    def real(self):
+        """
+        The real part of the masked array.
+
+        This property is a view on the real part of this `MaskedArray`.
+
+        See Also
+        --------
+        imag
+
+        Examples
+        --------
+        >>> x = np.ma.array([1+1.j, -2j, 3.45+1.6j], mask=[False, True, False])
+        >>> x.real
+        masked_array(data=[1.0, --, 3.45],
+                     mask=[False,  True, False],
+               fill_value=1e+20)
+
+        """
+        result = self._data.real.view(type(self))
+        result.__setmask__(self._mask)
+        return result
+
+    # kept for compatibility
+    get_real = real.fget
+
+    def count(self, axis=None, keepdims=np._NoValue):
+        """
+        Count the non-masked elements of the array along the given axis.
+
+        Parameters
+        ----------
+        axis : None or int or tuple of ints, optional
+            Axis or axes along which the count is performed.
+            The default, None, performs the count over all
+            the dimensions of the input array. `axis` may be negative, in
+            which case it counts from the last to the first axis.
+
+            .. versionadded:: 1.10.0
+
+            If this is a tuple of ints, the count is performed on multiple
+            axes, instead of a single axis or all the axes as before.
+        keepdims : bool, optional
+            If this is set to True, the axes which are reduced are left
+            in the result as dimensions with size one. With this option,
+            the result will broadcast correctly against the array.
+
+        Returns
+        -------
+        result : ndarray or scalar
+            An array with the same shape as the input array, with the specified
+            axis removed. If the array is a 0-d array, or if `axis` is None, a
+            scalar is returned.
+
+        See Also
+        --------
+        ma.count_masked : Count masked elements in array or along a given axis.
+
+        Examples
+        --------
+        >>> import numpy.ma as ma
+        >>> a = ma.arange(6).reshape((2, 3))
+        >>> a[1, :] = ma.masked
+        >>> a
+        masked_array(
+          data=[[0, 1, 2],
+                [--, --, --]],
+          mask=[[False, False, False],
+                [ True,  True,  True]],
+          fill_value=999999)
+        >>> a.count()
+        3
+
+        When the `axis` keyword is specified an array of appropriate size is
+        returned.
+
+        >>> a.count(axis=0)
+        array([1, 1, 1])
+        >>> a.count(axis=1)
+        array([3, 0])
+
+        """
+        kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims}
+
+        m = self._mask
+        # special case for matrices (we assume no other subclasses modify
+        # their dimensions)
+        if isinstance(self.data, np.matrix):
+            if m is nomask:
+                m = np.zeros(self.shape, dtype=np.bool_)
+            m = m.view(type(self.data))
+
+        if m is nomask:
+            # compare to _count_reduce_items in _methods.py
+
+            if self.shape == ():
+                if axis not in (None, 0):
+                    raise np.AxisError(axis=axis, ndim=self.ndim)
+                return 1
+            elif axis is None:
+                if kwargs.get('keepdims', False):
+                    return np.array(self.size, dtype=np.intp, ndmin=self.ndim)
+                return self.size
+
+            axes = normalize_axis_tuple(axis, self.ndim)
+            items = 1
+            for ax in axes:
+                items *= self.shape[ax]
+
+            if kwargs.get('keepdims', False):
+                out_dims = list(self.shape)
+                for a in axes:
+                    out_dims[a] = 1
+            else:
+                out_dims = [d for n, d in enumerate(self.shape)
+                            if n not in axes]
+            # make sure to return a 0-d array if axis is supplied
+            return np.full(out_dims, items, dtype=np.intp)
+
+        # take care of the masked singleton
+        if self is masked:
+            return 0
+
+        return (~m).sum(axis=axis, dtype=np.intp, **kwargs)
+
+    def ravel(self, order='C'):
+        """
+        Returns a 1D version of self, as a view.
+
+        Parameters
+        ----------
+        order : {'C', 'F', 'A', 'K'}, optional
+            The elements of `a` are read using this index order. 'C' means to
+            index the elements in C-like order, with the last axis index
+            changing fastest, back to the first axis index changing slowest.
+            'F' means to index the elements in Fortran-like index order, with
+            the first index changing fastest, and the last index changing
+            slowest. Note that the 'C' and 'F' options take no account of the
+            memory layout of the underlying array, and only refer to the order
+            of axis indexing.  'A' means to read the elements in Fortran-like
+            index order if `m` is Fortran *contiguous* in memory, C-like order
+            otherwise.  'K' means to read the elements in the order they occur
+            in memory, except for reversing the data when strides are negative.
+            By default, 'C' index order is used.
+            (Masked arrays currently use 'A' on the data when 'K' is passed.)
+
+        Returns
+        -------
+        MaskedArray
+            Output view is of shape ``(self.size,)`` (or
+            ``(np.ma.product(self.shape),)``).
+
+        Examples
+        --------
+        >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
+        >>> x
+        masked_array(
+          data=[[1, --, 3],
+                [--, 5, --],
+                [7, --, 9]],
+          mask=[[False,  True, False],
+                [ True, False,  True],
+                [False,  True, False]],
+          fill_value=999999)
+        >>> x.ravel()
+        masked_array(data=[1, --, 3, --, 5, --, 7, --, 9],
+                     mask=[False,  True, False,  True, False,  True, False,  True,
+                           False],
+               fill_value=999999)
+
+        """
+        # The order of _data and _mask could be different (it shouldn't be
+        # normally).  Passing order `K` or `A` would be incorrect.
+        # So we ignore the mask memory order.
+        # TODO: We don't actually support K, so use A instead.  We could
+        #       try to guess this correct by sorting strides or deprecate.
+        if order in "kKaA":
+            order = "F" if self._data.flags.fnc else "C"
+        r = ndarray.ravel(self._data, order=order).view(type(self))
+        r._update_from(self)
+        if self._mask is not nomask:
+            r._mask = ndarray.ravel(self._mask, order=order).reshape(r.shape)
+        else:
+            r._mask = nomask
+        return r
+
+
+    def reshape(self, *s, **kwargs):
+        """
+        Give a new shape to the array without changing its data.
+
+        Returns a masked array containing the same data, but with a new shape.
+        The result is a view on the original array; if this is not possible, a
+        ValueError is raised.
+
+        Parameters
+        ----------
+        shape : int or tuple of ints
+            The new shape should be compatible with the original shape. If an
+            integer is supplied, then the result will be a 1-D array of that
+            length.
+        order : {'C', 'F'}, optional
+            Determines whether the array data should be viewed as in C
+            (row-major) or FORTRAN (column-major) order.
+
+        Returns
+        -------
+        reshaped_array : array
+            A new view on the array.
+
+        See Also
+        --------
+        reshape : Equivalent function in the masked array module.
+        numpy.ndarray.reshape : Equivalent method on ndarray object.
+        numpy.reshape : Equivalent function in the NumPy module.
+
+        Notes
+        -----
+        The reshaping operation cannot guarantee that a copy will not be made,
+        to modify the shape in place, use ``a.shape = s``
+
+        Examples
+        --------
+        >>> x = np.ma.array([[1,2],[3,4]], mask=[1,0,0,1])
+        >>> x
+        masked_array(
+          data=[[--, 2],
+                [3, --]],
+          mask=[[ True, False],
+                [False,  True]],
+          fill_value=999999)
+        >>> x = x.reshape((4,1))
+        >>> x
+        masked_array(
+          data=[[--],
+                [2],
+                [3],
+                [--]],
+          mask=[[ True],
+                [False],
+                [False],
+                [ True]],
+          fill_value=999999)
+
+        """
+        kwargs.update(order=kwargs.get('order', 'C'))
+        result = self._data.reshape(*s, **kwargs).view(type(self))
+        result._update_from(self)
+        mask = self._mask
+        if mask is not nomask:
+            result._mask = mask.reshape(*s, **kwargs)
+        return result
+
+    def resize(self, newshape, refcheck=True, order=False):
+        """
+        .. warning::
+
+            This method does nothing, except raise a ValueError exception. A
+            masked array does not own its data and therefore cannot safely be
+            resized in place. Use the `numpy.ma.resize` function instead.
+
+        This method is difficult to implement safely and may be deprecated in
+        future releases of NumPy.
+
+        """
+        # Note : the 'order' keyword looks broken, let's just drop it
+        errmsg = "A masked array does not own its data "\
+                 "and therefore cannot be resized.\n" \
+                 "Use the numpy.ma.resize function instead."
+        raise ValueError(errmsg)
+
+    def put(self, indices, values, mode='raise'):
+        """
+        Set storage-indexed locations to corresponding values.
+
+        Sets self._data.flat[n] = values[n] for each n in indices.
+        If `values` is shorter than `indices` then it will repeat.
+        If `values` has some masked values, the initial mask is updated
+        in consequence, else the corresponding values are unmasked.
+
+        Parameters
+        ----------
+        indices : 1-D array_like
+            Target indices, interpreted as integers.
+        values : array_like
+            Values to place in self._data copy at target indices.
+        mode : {'raise', 'wrap', 'clip'}, optional
+            Specifies how out-of-bounds indices will behave.
+            'raise' : raise an error.
+            'wrap' : wrap around.
+            'clip' : clip to the range.
+
+        Notes
+        -----
+        `values` can be a scalar or length 1 array.
+
+        Examples
+        --------
+        >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
+        >>> x
+        masked_array(
+          data=[[1, --, 3],
+                [--, 5, --],
+                [7, --, 9]],
+          mask=[[False,  True, False],
+                [ True, False,  True],
+                [False,  True, False]],
+          fill_value=999999)
+        >>> x.put([0,4,8],[10,20,30])
+        >>> x
+        masked_array(
+          data=[[10, --, 3],
+                [--, 20, --],
+                [7, --, 30]],
+          mask=[[False,  True, False],
+                [ True, False,  True],
+                [False,  True, False]],
+          fill_value=999999)
+
+        >>> x.put(4,999)
+        >>> x
+        masked_array(
+          data=[[10, --, 3],
+                [--, 999, --],
+                [7, --, 30]],
+          mask=[[False,  True, False],
+                [ True, False,  True],
+                [False,  True, False]],
+          fill_value=999999)
+
+        """
+        # Hard mask: Get rid of the values/indices that fall on masked data
+        if self._hardmask and self._mask is not nomask:
+            mask = self._mask[indices]
+            indices = narray(indices, copy=False)
+            values = narray(values, copy=False, subok=True)
+            values.resize(indices.shape)
+            indices = indices[~mask]
+            values = values[~mask]
+
+        self._data.put(indices, values, mode=mode)
+
+        # short circuit if neither self nor values are masked
+        if self._mask is nomask and getmask(values) is nomask:
+            return
+
+        m = getmaskarray(self)
+
+        if getmask(values) is nomask:
+            m.put(indices, False, mode=mode)
+        else:
+            m.put(indices, values._mask, mode=mode)
+        m = make_mask(m, copy=False, shrink=True)
+        self._mask = m
+        return
+
+    def ids(self):
+        """
+        Return the addresses of the data and mask areas.
+
+        Parameters
+        ----------
+        None
+
+        Examples
+        --------
+        >>> x = np.ma.array([1, 2, 3], mask=[0, 1, 1])
+        >>> x.ids()
+        (166670640, 166659832) # may vary
+
+        If the array has no mask, the address of `nomask` is returned. This address
+        is typically not close to the data in memory:
+
+        >>> x = np.ma.array([1, 2, 3])
+        >>> x.ids()
+        (166691080, 3083169284) # may vary
+
+        """
+        if self._mask is nomask:
+            return (self.ctypes.data, id(nomask))
+        return (self.ctypes.data, self._mask.ctypes.data)
+
+    def iscontiguous(self):
+        """
+        Return a boolean indicating whether the data is contiguous.
+
+        Parameters
+        ----------
+        None
+
+        Examples
+        --------
+        >>> x = np.ma.array([1, 2, 3])
+        >>> x.iscontiguous()
+        True
+
+        `iscontiguous` returns one of the flags of the masked array:
+
+        >>> x.flags
+          C_CONTIGUOUS : True
+          F_CONTIGUOUS : True
+          OWNDATA : False
+          WRITEABLE : True
+          ALIGNED : True
+          WRITEBACKIFCOPY : False
+
+        """
+        return self.flags['CONTIGUOUS']
+
+    def all(self, axis=None, out=None, keepdims=np._NoValue):
+        """
+        Returns True if all elements evaluate to True.
+
+        The output array is masked where all the values along the given axis
+        are masked: if the output would have been a scalar and that all the
+        values are masked, then the output is `masked`.
+
+        Refer to `numpy.all` for full documentation.
+
+        See Also
+        --------
+        numpy.ndarray.all : corresponding function for ndarrays
+        numpy.all : equivalent function
+
+        Examples
+        --------
+        >>> np.ma.array([1,2,3]).all()
+        True
+        >>> a = np.ma.array([1,2,3], mask=True)
+        >>> (a.all() is np.ma.masked)
+        True
+
+        """
+        kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims}
+
+        mask = _check_mask_axis(self._mask, axis, **kwargs)
+        if out is None:
+            d = self.filled(True).all(axis=axis, **kwargs).view(type(self))
+            if d.ndim:
+                d.__setmask__(mask)
+            elif mask:
+                return masked
+            return d
+        self.filled(True).all(axis=axis, out=out, **kwargs)
+        if isinstance(out, MaskedArray):
+            if out.ndim or mask:
+                out.__setmask__(mask)
+        return out
+
+    def any(self, axis=None, out=None, keepdims=np._NoValue):
+        """
+        Returns True if any of the elements of `a` evaluate to True.
+
+        Masked values are considered as False during computation.
+
+        Refer to `numpy.any` for full documentation.
+
+        See Also
+        --------
+        numpy.ndarray.any : corresponding function for ndarrays
+        numpy.any : equivalent function
+
+        """
+        kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims}
+
+        mask = _check_mask_axis(self._mask, axis, **kwargs)
+        if out is None:
+            d = self.filled(False).any(axis=axis, **kwargs).view(type(self))
+            if d.ndim:
+                d.__setmask__(mask)
+            elif mask:
+                d = masked
+            return d
+        self.filled(False).any(axis=axis, out=out, **kwargs)
+        if isinstance(out, MaskedArray):
+            if out.ndim or mask:
+                out.__setmask__(mask)
+        return out
+
+    def nonzero(self):
+        """
+        Return the indices of unmasked elements that are not zero.
+
+        Returns a tuple of arrays, one for each dimension, containing the
+        indices of the non-zero elements in that dimension. The corresponding
+        non-zero values can be obtained with::
+
+            a[a.nonzero()]
+
+        To group the indices by element, rather than dimension, use
+        instead::
+
+            np.transpose(a.nonzero())
+
+        The result of this is always a 2d array, with a row for each non-zero
+        element.
+
+        Parameters
+        ----------
+        None
+
+        Returns
+        -------
+        tuple_of_arrays : tuple
+            Indices of elements that are non-zero.
+
+        See Also
+        --------
+        numpy.nonzero :
+            Function operating on ndarrays.
+        flatnonzero :
+            Return indices that are non-zero in the flattened version of the input
+            array.
+        numpy.ndarray.nonzero :
+            Equivalent ndarray method.
+        count_nonzero :
+            Counts the number of non-zero elements in the input array.
+
+        Examples
+        --------
+        >>> import numpy.ma as ma
+        >>> x = ma.array(np.eye(3))
+        >>> x
+        masked_array(
+          data=[[1., 0., 0.],
+                [0., 1., 0.],
+                [0., 0., 1.]],
+          mask=False,
+          fill_value=1e+20)
+        >>> x.nonzero()
+        (array([0, 1, 2]), array([0, 1, 2]))
+
+        Masked elements are ignored.
+
+        >>> x[1, 1] = ma.masked
+        >>> x
+        masked_array(
+          data=[[1.0, 0.0, 0.0],
+                [0.0, --, 0.0],
+                [0.0, 0.0, 1.0]],
+          mask=[[False, False, False],
+                [False,  True, False],
+                [False, False, False]],
+          fill_value=1e+20)
+        >>> x.nonzero()
+        (array([0, 2]), array([0, 2]))
+
+        Indices can also be grouped by element.
+
+        >>> np.transpose(x.nonzero())
+        array([[0, 0],
+               [2, 2]])
+
+        A common use for ``nonzero`` is to find the indices of an array, where
+        a condition is True.  Given an array `a`, the condition `a` > 3 is a
+        boolean array and since False is interpreted as 0, ma.nonzero(a > 3)
+        yields the indices of the `a` where the condition is true.
+
+        >>> a = ma.array([[1,2,3],[4,5,6],[7,8,9]])
+        >>> a > 3
+        masked_array(
+          data=[[False, False, False],
+                [ True,  True,  True],
+                [ True,  True,  True]],
+          mask=False,
+          fill_value=True)
+        >>> ma.nonzero(a > 3)
+        (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
+
+        The ``nonzero`` method of the condition array can also be called.
+
+        >>> (a > 3).nonzero()
+        (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
+
+        """
+        return narray(self.filled(0), copy=False).nonzero()
+
+    def trace(self, offset=0, axis1=0, axis2=1, dtype=None, out=None):
+        """
+        (this docstring should be overwritten)
+        """
+        #!!!: implement out + test!
+        m = self._mask
+        if m is nomask:
+            result = super().trace(offset=offset, axis1=axis1, axis2=axis2,
+                                   out=out)
+            return result.astype(dtype)
+        else:
+            D = self.diagonal(offset=offset, axis1=axis1, axis2=axis2)
+            return D.astype(dtype).filled(0).sum(axis=-1, out=out)
+    trace.__doc__ = ndarray.trace.__doc__
+
+    def dot(self, b, out=None, strict=False):
+        """
+        a.dot(b, out=None)
+
+        Masked dot product of two arrays. Note that `out` and `strict` are
+        located in different positions than in `ma.dot`. In order to
+        maintain compatibility with the functional version, it is
+        recommended that the optional arguments be treated as keyword only.
+        At some point that may be mandatory.
+
+        .. versionadded:: 1.10.0
+
+        Parameters
+        ----------
+        b : masked_array_like
+            Inputs array.
+        out : masked_array, optional
+            Output argument. This must have the exact kind that would be
+            returned if it was not used. In particular, it must have the
+            right type, must be C-contiguous, and its dtype must be the
+            dtype that would be returned for `ma.dot(a,b)`. This is a
+            performance feature. Therefore, if these conditions are not
+            met, an exception is raised, instead of attempting to be
+            flexible.
+        strict : bool, optional
+            Whether masked data are propagated (True) or set to 0 (False)
+            for the computation. Default is False.  Propagating the mask
+            means that if a masked value appears in a row or column, the
+            whole row or column is considered masked.
+
+            .. versionadded:: 1.10.2
+
+        See Also
+        --------
+        numpy.ma.dot : equivalent function
+
+        """
+        return dot(self, b, out=out, strict=strict)
+
+    def sum(self, axis=None, dtype=None, out=None, keepdims=np._NoValue):
+        """
+        Return the sum of the array elements over the given axis.
+
+        Masked elements are set to 0 internally.
+
+        Refer to `numpy.sum` for full documentation.
+
+        See Also
+        --------
+        numpy.ndarray.sum : corresponding function for ndarrays
+        numpy.sum : equivalent function
+
+        Examples
+        --------
+        >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
+        >>> x
+        masked_array(
+          data=[[1, --, 3],
+                [--, 5, --],
+                [7, --, 9]],
+          mask=[[False,  True, False],
+                [ True, False,  True],
+                [False,  True, False]],
+          fill_value=999999)
+        >>> x.sum()
+        25
+        >>> x.sum(axis=1)
+        masked_array(data=[4, 5, 16],
+                     mask=[False, False, False],
+               fill_value=999999)
+        >>> x.sum(axis=0)
+        masked_array(data=[8, 5, 12],
+                     mask=[False, False, False],
+               fill_value=999999)
+        >>> print(type(x.sum(axis=0, dtype=np.int64)[0]))
+        
+
+        """
+        kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims}
+
+        _mask = self._mask
+        newmask = _check_mask_axis(_mask, axis, **kwargs)
+        # No explicit output
+        if out is None:
+            result = self.filled(0).sum(axis, dtype=dtype, **kwargs)
+            rndim = getattr(result, 'ndim', 0)
+            if rndim:
+                result = result.view(type(self))
+                result.__setmask__(newmask)
+            elif newmask:
+                result = masked
+            return result
+        # Explicit output
+        result = self.filled(0).sum(axis, dtype=dtype, out=out, **kwargs)
+        if isinstance(out, MaskedArray):
+            outmask = getmask(out)
+            if outmask is nomask:
+                outmask = out._mask = make_mask_none(out.shape)
+            outmask.flat = newmask
+        return out
+
+    def cumsum(self, axis=None, dtype=None, out=None):
+        """
+        Return the cumulative sum of the array elements over the given axis.
+
+        Masked values are set to 0 internally during the computation.
+        However, their position is saved, and the result will be masked at
+        the same locations.
+
+        Refer to `numpy.cumsum` for full documentation.
+
+        Notes
+        -----
+        The mask is lost if `out` is not a valid :class:`ma.MaskedArray` !
+
+        Arithmetic is modular when using integer types, and no error is
+        raised on overflow.
+
+        See Also
+        --------
+        numpy.ndarray.cumsum : corresponding function for ndarrays
+        numpy.cumsum : equivalent function
+
+        Examples
+        --------
+        >>> marr = np.ma.array(np.arange(10), mask=[0,0,0,1,1,1,0,0,0,0])
+        >>> marr.cumsum()
+        masked_array(data=[0, 1, 3, --, --, --, 9, 16, 24, 33],
+                     mask=[False, False, False,  True,  True,  True, False, False,
+                           False, False],
+               fill_value=999999)
+
+        """
+        result = self.filled(0).cumsum(axis=axis, dtype=dtype, out=out)
+        if out is not None:
+            if isinstance(out, MaskedArray):
+                out.__setmask__(self.mask)
+            return out
+        result = result.view(type(self))
+        result.__setmask__(self._mask)
+        return result
+
+    def prod(self, axis=None, dtype=None, out=None, keepdims=np._NoValue):
+        """
+        Return the product of the array elements over the given axis.
+
+        Masked elements are set to 1 internally for computation.
+
+        Refer to `numpy.prod` for full documentation.
+
+        Notes
+        -----
+        Arithmetic is modular when using integer types, and no error is raised
+        on overflow.
+
+        See Also
+        --------
+        numpy.ndarray.prod : corresponding function for ndarrays
+        numpy.prod : equivalent function
+        """
+        kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims}
+
+        _mask = self._mask
+        newmask = _check_mask_axis(_mask, axis, **kwargs)
+        # No explicit output
+        if out is None:
+            result = self.filled(1).prod(axis, dtype=dtype, **kwargs)
+            rndim = getattr(result, 'ndim', 0)
+            if rndim:
+                result = result.view(type(self))
+                result.__setmask__(newmask)
+            elif newmask:
+                result = masked
+            return result
+        # Explicit output
+        result = self.filled(1).prod(axis, dtype=dtype, out=out, **kwargs)
+        if isinstance(out, MaskedArray):
+            outmask = getmask(out)
+            if outmask is nomask:
+                outmask = out._mask = make_mask_none(out.shape)
+            outmask.flat = newmask
+        return out
+    product = prod
+
+    def cumprod(self, axis=None, dtype=None, out=None):
+        """
+        Return the cumulative product of the array elements over the given axis.
+
+        Masked values are set to 1 internally during the computation.
+        However, their position is saved, and the result will be masked at
+        the same locations.
+
+        Refer to `numpy.cumprod` for full documentation.
+
+        Notes
+        -----
+        The mask is lost if `out` is not a valid MaskedArray !
+
+        Arithmetic is modular when using integer types, and no error is
+        raised on overflow.
+
+        See Also
+        --------
+        numpy.ndarray.cumprod : corresponding function for ndarrays
+        numpy.cumprod : equivalent function
+        """
+        result = self.filled(1).cumprod(axis=axis, dtype=dtype, out=out)
+        if out is not None:
+            if isinstance(out, MaskedArray):
+                out.__setmask__(self._mask)
+            return out
+        result = result.view(type(self))
+        result.__setmask__(self._mask)
+        return result
+
+    def mean(self, axis=None, dtype=None, out=None, keepdims=np._NoValue):
+        """
+        Returns the average of the array elements along given axis.
+
+        Masked entries are ignored, and result elements which are not
+        finite will be masked.
+
+        Refer to `numpy.mean` for full documentation.
+
+        See Also
+        --------
+        numpy.ndarray.mean : corresponding function for ndarrays
+        numpy.mean : Equivalent function
+        numpy.ma.average : Weighted average.
+
+        Examples
+        --------
+        >>> a = np.ma.array([1,2,3], mask=[False, False, True])
+        >>> a
+        masked_array(data=[1, 2, --],
+                     mask=[False, False,  True],
+               fill_value=999999)
+        >>> a.mean()
+        1.5
+
+        """
+        kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims}
+        if self._mask is nomask:
+            result = super().mean(axis=axis, dtype=dtype, **kwargs)[()]
+        else:
+            is_float16_result = False
+            if dtype is None:
+                if issubclass(self.dtype.type, (ntypes.integer, ntypes.bool_)):
+                    dtype = mu.dtype('f8')
+                elif issubclass(self.dtype.type, ntypes.float16):
+                    dtype = mu.dtype('f4')
+                    is_float16_result = True
+            dsum = self.sum(axis=axis, dtype=dtype, **kwargs)
+            cnt = self.count(axis=axis, **kwargs)
+            if cnt.shape == () and (cnt == 0):
+                result = masked
+            elif is_float16_result:
+                result = self.dtype.type(dsum * 1. / cnt)
+            else:
+                result = dsum * 1. / cnt
+        if out is not None:
+            out.flat = result
+            if isinstance(out, MaskedArray):
+                outmask = getmask(out)
+                if outmask is nomask:
+                    outmask = out._mask = make_mask_none(out.shape)
+                outmask.flat = getmask(result)
+            return out
+        return result
+
+    def anom(self, axis=None, dtype=None):
+        """
+        Compute the anomalies (deviations from the arithmetic mean)
+        along the given axis.
+
+        Returns an array of anomalies, with the same shape as the input and
+        where the arithmetic mean is computed along the given axis.
+
+        Parameters
+        ----------
+        axis : int, optional
+            Axis over which the anomalies are taken.
+            The default is to use the mean of the flattened array as reference.
+        dtype : dtype, optional
+            Type to use in computing the variance. For arrays of integer type
+             the default is float32; for arrays of float types it is the same as
+             the array type.
+
+        See Also
+        --------
+        mean : Compute the mean of the array.
+
+        Examples
+        --------
+        >>> a = np.ma.array([1,2,3])
+        >>> a.anom()
+        masked_array(data=[-1.,  0.,  1.],
+                     mask=False,
+               fill_value=1e+20)
+
+        """
+        m = self.mean(axis, dtype)
+        if not axis:
+            return self - m
+        else:
+            return self - expand_dims(m, axis)
+
+    def var(self, axis=None, dtype=None, out=None, ddof=0,
+            keepdims=np._NoValue):
+        """
+        Returns the variance of the array elements along given axis.
+
+        Masked entries are ignored, and result elements which are not
+        finite will be masked.
+
+        Refer to `numpy.var` for full documentation.
+
+        See Also
+        --------
+        numpy.ndarray.var : corresponding function for ndarrays
+        numpy.var : Equivalent function
+        """
+        kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims}
+
+        # Easy case: nomask, business as usual
+        if self._mask is nomask:
+            ret = super().var(axis=axis, dtype=dtype, out=out, ddof=ddof,
+                              **kwargs)[()]
+            if out is not None:
+                if isinstance(out, MaskedArray):
+                    out.__setmask__(nomask)
+                return out
+            return ret
+
+        # Some data are masked, yay!
+        cnt = self.count(axis=axis, **kwargs) - ddof
+        danom = self - self.mean(axis, dtype, keepdims=True)
+        if iscomplexobj(self):
+            danom = umath.absolute(danom) ** 2
+        else:
+            danom *= danom
+        dvar = divide(danom.sum(axis, **kwargs), cnt).view(type(self))
+        # Apply the mask if it's not a scalar
+        if dvar.ndim:
+            dvar._mask = mask_or(self._mask.all(axis, **kwargs), (cnt <= 0))
+            dvar._update_from(self)
+        elif getmask(dvar):
+            # Make sure that masked is returned when the scalar is masked.
+            dvar = masked
+            if out is not None:
+                if isinstance(out, MaskedArray):
+                    out.flat = 0
+                    out.__setmask__(True)
+                elif out.dtype.kind in 'biu':
+                    errmsg = "Masked data information would be lost in one or "\
+                             "more location."
+                    raise MaskError(errmsg)
+                else:
+                    out.flat = np.nan
+                return out
+        # In case with have an explicit output
+        if out is not None:
+            # Set the data
+            out.flat = dvar
+            # Set the mask if needed
+            if isinstance(out, MaskedArray):
+                out.__setmask__(dvar.mask)
+            return out
+        return dvar
+    var.__doc__ = np.var.__doc__
+
+    def std(self, axis=None, dtype=None, out=None, ddof=0,
+            keepdims=np._NoValue):
+        """
+        Returns the standard deviation of the array elements along given axis.
+
+        Masked entries are ignored.
+
+        Refer to `numpy.std` for full documentation.
+
+        See Also
+        --------
+        numpy.ndarray.std : corresponding function for ndarrays
+        numpy.std : Equivalent function
+        """
+        kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims}
+
+        dvar = self.var(axis, dtype, out, ddof, **kwargs)
+        if dvar is not masked:
+            if out is not None:
+                np.power(out, 0.5, out=out, casting='unsafe')
+                return out
+            dvar = sqrt(dvar)
+        return dvar
+
+    def round(self, decimals=0, out=None):
+        """
+        Return each element rounded to the given number of decimals.
+
+        Refer to `numpy.around` for full documentation.
+
+        See Also
+        --------
+        numpy.ndarray.round : corresponding function for ndarrays
+        numpy.around : equivalent function
+        """
+        result = self._data.round(decimals=decimals, out=out).view(type(self))
+        if result.ndim > 0:
+            result._mask = self._mask
+            result._update_from(self)
+        elif self._mask:
+            # Return masked when the scalar is masked
+            result = masked
+        # No explicit output: we're done
+        if out is None:
+            return result
+        if isinstance(out, MaskedArray):
+            out.__setmask__(self._mask)
+        return out
+
+    def argsort(self, axis=np._NoValue, kind=None, order=None,
+                endwith=True, fill_value=None):
+        """
+        Return an ndarray of indices that sort the array along the
+        specified axis.  Masked values are filled beforehand to
+        `fill_value`.
+
+        Parameters
+        ----------
+        axis : int, optional
+            Axis along which to sort. If None, the default, the flattened array
+            is used.
+
+            ..  versionchanged:: 1.13.0
+                Previously, the default was documented to be -1, but that was
+                in error. At some future date, the default will change to -1, as
+                originally intended.
+                Until then, the axis should be given explicitly when
+                ``arr.ndim > 1``, to avoid a FutureWarning.
+        kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
+            The sorting algorithm used.
+        order : list, optional
+            When `a` is an array with fields defined, this argument specifies
+            which fields to compare first, second, etc.  Not all fields need be
+            specified.
+        endwith : {True, False}, optional
+            Whether missing values (if any) should be treated as the largest values
+            (True) or the smallest values (False)
+            When the array contains unmasked values at the same extremes of the
+            datatype, the ordering of these values and the masked values is
+            undefined.
+        fill_value : scalar or None, optional
+            Value used internally for the masked values.
+            If ``fill_value`` is not None, it supersedes ``endwith``.
+
+        Returns
+        -------
+        index_array : ndarray, int
+            Array of indices that sort `a` along the specified axis.
+            In other words, ``a[index_array]`` yields a sorted `a`.
+
+        See Also
+        --------
+        ma.MaskedArray.sort : Describes sorting algorithms used.
+        lexsort : Indirect stable sort with multiple keys.
+        numpy.ndarray.sort : Inplace sort.
+
+        Notes
+        -----
+        See `sort` for notes on the different sorting algorithms.
+
+        Examples
+        --------
+        >>> a = np.ma.array([3,2,1], mask=[False, False, True])
+        >>> a
+        masked_array(data=[3, 2, --],
+                     mask=[False, False,  True],
+               fill_value=999999)
+        >>> a.argsort()
+        array([1, 0, 2])
+
+        """
+
+        # 2017-04-11, Numpy 1.13.0, gh-8701: warn on axis default
+        if axis is np._NoValue:
+            axis = _deprecate_argsort_axis(self)
+
+        if fill_value is None:
+            if endwith:
+                # nan > inf
+                if np.issubdtype(self.dtype, np.floating):
+                    fill_value = np.nan
+                else:
+                    fill_value = minimum_fill_value(self)
+            else:
+                fill_value = maximum_fill_value(self)
+
+        filled = self.filled(fill_value)
+        return filled.argsort(axis=axis, kind=kind, order=order)
+
+    def argmin(self, axis=None, fill_value=None, out=None, *,
+                keepdims=np._NoValue):
+        """
+        Return array of indices to the minimum values along the given axis.
+
+        Parameters
+        ----------
+        axis : {None, integer}
+            If None, the index is into the flattened array, otherwise along
+            the specified axis
+        fill_value : scalar or None, optional
+            Value used to fill in the masked values.  If None, the output of
+            minimum_fill_value(self._data) is used instead.
+        out : {None, array}, optional
+            Array into which the result can be placed. Its type is preserved
+            and it must be of the right shape to hold the output.
+
+        Returns
+        -------
+        ndarray or scalar
+            If multi-dimension input, returns a new ndarray of indices to the
+            minimum values along the given axis.  Otherwise, returns a scalar
+            of index to the minimum values along the given axis.
+
+        Examples
+        --------
+        >>> x = np.ma.array(np.arange(4), mask=[1,1,0,0])
+        >>> x.shape = (2,2)
+        >>> x
+        masked_array(
+          data=[[--, --],
+                [2, 3]],
+          mask=[[ True,  True],
+                [False, False]],
+          fill_value=999999)
+        >>> x.argmin(axis=0, fill_value=-1)
+        array([0, 0])
+        >>> x.argmin(axis=0, fill_value=9)
+        array([1, 1])
+
+        """
+        if fill_value is None:
+            fill_value = minimum_fill_value(self)
+        d = self.filled(fill_value).view(ndarray)
+        keepdims = False if keepdims is np._NoValue else bool(keepdims)
+        return d.argmin(axis, out=out, keepdims=keepdims)
+
+    def argmax(self, axis=None, fill_value=None, out=None, *,
+                keepdims=np._NoValue):
+        """
+        Returns array of indices of the maximum values along the given axis.
+        Masked values are treated as if they had the value fill_value.
+
+        Parameters
+        ----------
+        axis : {None, integer}
+            If None, the index is into the flattened array, otherwise along
+            the specified axis
+        fill_value : scalar or None, optional
+            Value used to fill in the masked values.  If None, the output of
+            maximum_fill_value(self._data) is used instead.
+        out : {None, array}, optional
+            Array into which the result can be placed. Its type is preserved
+            and it must be of the right shape to hold the output.
+
+        Returns
+        -------
+        index_array : {integer_array}
+
+        Examples
+        --------
+        >>> a = np.arange(6).reshape(2,3)
+        >>> a.argmax()
+        5
+        >>> a.argmax(0)
+        array([1, 1, 1])
+        >>> a.argmax(1)
+        array([2, 2])
+
+        """
+        if fill_value is None:
+            fill_value = maximum_fill_value(self._data)
+        d = self.filled(fill_value).view(ndarray)
+        keepdims = False if keepdims is np._NoValue else bool(keepdims)
+        return d.argmax(axis, out=out, keepdims=keepdims)
+
+    def sort(self, axis=-1, kind=None, order=None,
+             endwith=True, fill_value=None):
+        """
+        Sort the array, in-place
+
+        Parameters
+        ----------
+        a : array_like
+            Array to be sorted.
+        axis : int, optional
+            Axis along which to sort. If None, the array is flattened before
+            sorting. The default is -1, which sorts along the last axis.
+        kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
+            The sorting algorithm used.
+        order : list, optional
+            When `a` is a structured array, this argument specifies which fields
+            to compare first, second, and so on.  This list does not need to
+            include all of the fields.
+        endwith : {True, False}, optional
+            Whether missing values (if any) should be treated as the largest values
+            (True) or the smallest values (False)
+            When the array contains unmasked values sorting at the same extremes of the
+            datatype, the ordering of these values and the masked values is
+            undefined.
+        fill_value : scalar or None, optional
+            Value used internally for the masked values.
+            If ``fill_value`` is not None, it supersedes ``endwith``.
+
+        Returns
+        -------
+        sorted_array : ndarray
+            Array of the same type and shape as `a`.
+
+        See Also
+        --------
+        numpy.ndarray.sort : Method to sort an array in-place.
+        argsort : Indirect sort.
+        lexsort : Indirect stable sort on multiple keys.
+        searchsorted : Find elements in a sorted array.
+
+        Notes
+        -----
+        See ``sort`` for notes on the different sorting algorithms.
+
+        Examples
+        --------
+        >>> a = np.ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0])
+        >>> # Default
+        >>> a.sort()
+        >>> a
+        masked_array(data=[1, 3, 5, --, --],
+                     mask=[False, False, False,  True,  True],
+               fill_value=999999)
+
+        >>> a = np.ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0])
+        >>> # Put missing values in the front
+        >>> a.sort(endwith=False)
+        >>> a
+        masked_array(data=[--, --, 1, 3, 5],
+                     mask=[ True,  True, False, False, False],
+               fill_value=999999)
+
+        >>> a = np.ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0])
+        >>> # fill_value takes over endwith
+        >>> a.sort(endwith=False, fill_value=3)
+        >>> a
+        masked_array(data=[1, --, --, 3, 5],
+                     mask=[False,  True,  True, False, False],
+               fill_value=999999)
+
+        """
+        if self._mask is nomask:
+            ndarray.sort(self, axis=axis, kind=kind, order=order)
+            return
+
+        if self is masked:
+            return
+
+        sidx = self.argsort(axis=axis, kind=kind, order=order,
+                            fill_value=fill_value, endwith=endwith)
+
+        self[...] = np.take_along_axis(self, sidx, axis=axis)
+
+    def min(self, axis=None, out=None, fill_value=None, keepdims=np._NoValue):
+        """
+        Return the minimum along a given axis.
+
+        Parameters
+        ----------
+        axis : None or int or tuple of ints, optional
+            Axis along which to operate.  By default, ``axis`` is None and the
+            flattened input is used.
+            .. versionadded:: 1.7.0
+            If this is a tuple of ints, the minimum is selected over multiple
+            axes, instead of a single axis or all the axes as before.
+        out : array_like, optional
+            Alternative output array in which to place the result.  Must be of
+            the same shape and buffer length as the expected output.
+        fill_value : scalar or None, optional
+            Value used to fill in the masked values.
+            If None, use the output of `minimum_fill_value`.
+        keepdims : bool, optional
+            If this is set to True, the axes which are reduced are left
+            in the result as dimensions with size one. With this option,
+            the result will broadcast correctly against the array.
+
+        Returns
+        -------
+        amin : array_like
+            New array holding the result.
+            If ``out`` was specified, ``out`` is returned.
+
+        See Also
+        --------
+        ma.minimum_fill_value
+            Returns the minimum filling value for a given datatype.
+
+        Examples
+        --------
+        >>> import numpy.ma as ma
+        >>> x = [[1., -2., 3.], [0.2, -0.7, 0.1]]
+        >>> mask = [[1, 1, 0], [0, 0, 1]]
+        >>> masked_x = ma.masked_array(x, mask)
+        >>> masked_x
+        masked_array(
+          data=[[--, --, 3.0],
+                [0.2, -0.7, --]],
+          mask=[[ True,  True, False],
+                [False, False,  True]],
+          fill_value=1e+20)
+        >>> ma.min(masked_x)
+        -0.7
+        >>> ma.min(masked_x, axis=-1)
+        masked_array(data=[3.0, -0.7],
+                     mask=[False, False],
+                fill_value=1e+20)
+        >>> ma.min(masked_x, axis=0, keepdims=True)
+        masked_array(data=[[0.2, -0.7, 3.0]],
+                     mask=[[False, False, False]],
+                fill_value=1e+20)
+        >>> mask = [[1, 1, 1,], [1, 1, 1]]
+        >>> masked_x = ma.masked_array(x, mask)
+        >>> ma.min(masked_x, axis=0)
+        masked_array(data=[--, --, --],
+                     mask=[ True,  True,  True],
+                fill_value=1e+20,
+                    dtype=float64)
+        """
+        kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims}
+
+        _mask = self._mask
+        newmask = _check_mask_axis(_mask, axis, **kwargs)
+        if fill_value is None:
+            fill_value = minimum_fill_value(self)
+        # No explicit output
+        if out is None:
+            result = self.filled(fill_value).min(
+                axis=axis, out=out, **kwargs).view(type(self))
+            if result.ndim:
+                # Set the mask
+                result.__setmask__(newmask)
+                # Get rid of Infs
+                if newmask.ndim:
+                    np.copyto(result, result.fill_value, where=newmask)
+            elif newmask:
+                result = masked
+            return result
+        # Explicit output
+        result = self.filled(fill_value).min(axis=axis, out=out, **kwargs)
+        if isinstance(out, MaskedArray):
+            outmask = getmask(out)
+            if outmask is nomask:
+                outmask = out._mask = make_mask_none(out.shape)
+            outmask.flat = newmask
+        else:
+            if out.dtype.kind in 'biu':
+                errmsg = "Masked data information would be lost in one or more"\
+                         " location."
+                raise MaskError(errmsg)
+            np.copyto(out, np.nan, where=newmask)
+        return out
+
+    def max(self, axis=None, out=None, fill_value=None, keepdims=np._NoValue):
+        """
+        Return the maximum along a given axis.
+
+        Parameters
+        ----------
+        axis : None or int or tuple of ints, optional
+            Axis along which to operate.  By default, ``axis`` is None and the
+            flattened input is used.
+            .. versionadded:: 1.7.0
+            If this is a tuple of ints, the maximum is selected over multiple
+            axes, instead of a single axis or all the axes as before.
+        out : array_like, optional
+            Alternative output array in which to place the result.  Must
+            be of the same shape and buffer length as the expected output.
+        fill_value : scalar or None, optional
+            Value used to fill in the masked values.
+            If None, use the output of maximum_fill_value().
+        keepdims : bool, optional
+            If this is set to True, the axes which are reduced are left
+            in the result as dimensions with size one. With this option,
+            the result will broadcast correctly against the array.
+
+        Returns
+        -------
+        amax : array_like
+            New array holding the result.
+            If ``out`` was specified, ``out`` is returned.
+
+        See Also
+        --------
+        ma.maximum_fill_value
+            Returns the maximum filling value for a given datatype.
+
+        Examples
+        --------
+        >>> import numpy.ma as ma
+        >>> x = [[-1., 2.5], [4., -2.], [3., 0.]]
+        >>> mask = [[0, 0], [1, 0], [1, 0]]
+        >>> masked_x = ma.masked_array(x, mask)
+        >>> masked_x
+        masked_array(
+          data=[[-1.0, 2.5],
+                [--, -2.0],
+                [--, 0.0]],
+          mask=[[False, False],
+                [ True, False],
+                [ True, False]],
+          fill_value=1e+20)
+        >>> ma.max(masked_x)
+        2.5
+        >>> ma.max(masked_x, axis=0)
+        masked_array(data=[-1.0, 2.5],
+                     mask=[False, False],
+               fill_value=1e+20)
+        >>> ma.max(masked_x, axis=1, keepdims=True)
+        masked_array(
+          data=[[2.5],
+                [-2.0],
+                [0.0]],
+          mask=[[False],
+                [False],
+                [False]],
+          fill_value=1e+20)
+        >>> mask = [[1, 1], [1, 1], [1, 1]]
+        >>> masked_x = ma.masked_array(x, mask)
+        >>> ma.max(masked_x, axis=1)
+        masked_array(data=[--, --, --],
+                     mask=[ True,  True,  True],
+               fill_value=1e+20,
+                    dtype=float64)
+        """
+        kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims}
+
+        _mask = self._mask
+        newmask = _check_mask_axis(_mask, axis, **kwargs)
+        if fill_value is None:
+            fill_value = maximum_fill_value(self)
+        # No explicit output
+        if out is None:
+            result = self.filled(fill_value).max(
+                axis=axis, out=out, **kwargs).view(type(self))
+            if result.ndim:
+                # Set the mask
+                result.__setmask__(newmask)
+                # Get rid of Infs
+                if newmask.ndim:
+                    np.copyto(result, result.fill_value, where=newmask)
+            elif newmask:
+                result = masked
+            return result
+        # Explicit output
+        result = self.filled(fill_value).max(axis=axis, out=out, **kwargs)
+        if isinstance(out, MaskedArray):
+            outmask = getmask(out)
+            if outmask is nomask:
+                outmask = out._mask = make_mask_none(out.shape)
+            outmask.flat = newmask
+        else:
+
+            if out.dtype.kind in 'biu':
+                errmsg = "Masked data information would be lost in one or more"\
+                         " location."
+                raise MaskError(errmsg)
+            np.copyto(out, np.nan, where=newmask)
+        return out
+
+    def ptp(self, axis=None, out=None, fill_value=None, keepdims=False):
+        """
+        Return (maximum - minimum) along the given dimension
+        (i.e. peak-to-peak value).
+
+        .. warning::
+            `ptp` preserves the data type of the array. This means the
+            return value for an input of signed integers with n bits
+            (e.g. `np.int8`, `np.int16`, etc) is also a signed integer
+            with n bits.  In that case, peak-to-peak values greater than
+            ``2**(n-1)-1`` will be returned as negative values. An example
+            with a work-around is shown below.
+
+        Parameters
+        ----------
+        axis : {None, int}, optional
+            Axis along which to find the peaks.  If None (default) the
+            flattened array is used.
+        out : {None, array_like}, optional
+            Alternative output array in which to place the result. It must
+            have the same shape and buffer length as the expected output
+            but the type will be cast if necessary.
+        fill_value : scalar or None, optional
+            Value used to fill in the masked values.
+        keepdims : bool, optional
+            If this is set to True, the axes which are reduced are left
+            in the result as dimensions with size one. With this option,
+            the result will broadcast correctly against the array.
+
+        Returns
+        -------
+        ptp : ndarray.
+            A new array holding the result, unless ``out`` was
+            specified, in which case a reference to ``out`` is returned.
+
+        Examples
+        --------
+        >>> x = np.ma.MaskedArray([[4, 9, 2, 10],
+        ...                        [6, 9, 7, 12]])
+
+        >>> x.ptp(axis=1)
+        masked_array(data=[8, 6],
+                     mask=False,
+               fill_value=999999)
+
+        >>> x.ptp(axis=0)
+        masked_array(data=[2, 0, 5, 2],
+                     mask=False,
+               fill_value=999999)
+
+        >>> x.ptp()
+        10
+
+        This example shows that a negative value can be returned when
+        the input is an array of signed integers.
+
+        >>> y = np.ma.MaskedArray([[1, 127],
+        ...                        [0, 127],
+        ...                        [-1, 127],
+        ...                        [-2, 127]], dtype=np.int8)
+        >>> y.ptp(axis=1)
+        masked_array(data=[ 126,  127, -128, -127],
+                     mask=False,
+               fill_value=999999,
+                    dtype=int8)
+
+        A work-around is to use the `view()` method to view the result as
+        unsigned integers with the same bit width:
+
+        >>> y.ptp(axis=1).view(np.uint8)
+        masked_array(data=[126, 127, 128, 129],
+                     mask=False,
+               fill_value=999999,
+                    dtype=uint8)
+        """
+        if out is None:
+            result = self.max(axis=axis, fill_value=fill_value,
+                              keepdims=keepdims)
+            result -= self.min(axis=axis, fill_value=fill_value,
+                               keepdims=keepdims)
+            return result
+        out.flat = self.max(axis=axis, out=out, fill_value=fill_value,
+                            keepdims=keepdims)
+        min_value = self.min(axis=axis, fill_value=fill_value,
+                             keepdims=keepdims)
+        np.subtract(out, min_value, out=out, casting='unsafe')
+        return out
+
+    def partition(self, *args, **kwargs):
+        warnings.warn("Warning: 'partition' will ignore the 'mask' "
+                      f"of the {self.__class__.__name__}.",
+                      stacklevel=2)
+        return super().partition(*args, **kwargs)
+
+    def argpartition(self, *args, **kwargs):
+        warnings.warn("Warning: 'argpartition' will ignore the 'mask' "
+                      f"of the {self.__class__.__name__}.",
+                      stacklevel=2)
+        return super().argpartition(*args, **kwargs)
+
+    def take(self, indices, axis=None, out=None, mode='raise'):
+        """
+        """
+        (_data, _mask) = (self._data, self._mask)
+        cls = type(self)
+        # Make sure the indices are not masked
+        maskindices = getmask(indices)
+        if maskindices is not nomask:
+            indices = indices.filled(0)
+        # Get the data, promoting scalars to 0d arrays with [...] so that
+        # .view works correctly
+        if out is None:
+            out = _data.take(indices, axis=axis, mode=mode)[...].view(cls)
+        else:
+            np.take(_data, indices, axis=axis, mode=mode, out=out)
+        # Get the mask
+        if isinstance(out, MaskedArray):
+            if _mask is nomask:
+                outmask = maskindices
+            else:
+                outmask = _mask.take(indices, axis=axis, mode=mode)
+                outmask |= maskindices
+            out.__setmask__(outmask)
+        # demote 0d arrays back to scalars, for consistency with ndarray.take
+        return out[()]
+
+    # Array methods
+    copy = _arraymethod('copy')
+    diagonal = _arraymethod('diagonal')
+    flatten = _arraymethod('flatten')
+    repeat = _arraymethod('repeat')
+    squeeze = _arraymethod('squeeze')
+    swapaxes = _arraymethod('swapaxes')
+    T = property(fget=lambda self: self.transpose())
+    transpose = _arraymethod('transpose')
+
+    def tolist(self, fill_value=None):
+        """
+        Return the data portion of the masked array as a hierarchical Python list.
+
+        Data items are converted to the nearest compatible Python type.
+        Masked values are converted to `fill_value`. If `fill_value` is None,
+        the corresponding entries in the output list will be ``None``.
+
+        Parameters
+        ----------
+        fill_value : scalar, optional
+            The value to use for invalid entries. Default is None.
+
+        Returns
+        -------
+        result : list
+            The Python list representation of the masked array.
+
+        Examples
+        --------
+        >>> x = np.ma.array([[1,2,3], [4,5,6], [7,8,9]], mask=[0] + [1,0]*4)
+        >>> x.tolist()
+        [[1, None, 3], [None, 5, None], [7, None, 9]]
+        >>> x.tolist(-999)
+        [[1, -999, 3], [-999, 5, -999], [7, -999, 9]]
+
+        """
+        _mask = self._mask
+        # No mask ? Just return .data.tolist ?
+        if _mask is nomask:
+            return self._data.tolist()
+        # Explicit fill_value: fill the array and get the list
+        if fill_value is not None:
+            return self.filled(fill_value).tolist()
+        # Structured array.
+        names = self.dtype.names
+        if names:
+            result = self._data.astype([(_, object) for _ in names])
+            for n in names:
+                result[n][_mask[n]] = None
+            return result.tolist()
+        # Standard arrays.
+        if _mask is nomask:
+            return [None]
+        # Set temps to save time when dealing w/ marrays.
+        inishape = self.shape
+        result = np.array(self._data.ravel(), dtype=object)
+        result[_mask.ravel()] = None
+        result.shape = inishape
+        return result.tolist()
+
+    def tostring(self, fill_value=None, order='C'):
+        r"""
+        A compatibility alias for `tobytes`, with exactly the same behavior.
+
+        Despite its name, it returns `bytes` not `str`\ s.
+
+        .. deprecated:: 1.19.0
+        """
+        # 2020-03-30, Numpy 1.19.0
+        warnings.warn(
+            "tostring() is deprecated. Use tobytes() instead.",
+            DeprecationWarning, stacklevel=2)
+
+        return self.tobytes(fill_value, order=order)
+
+    def tobytes(self, fill_value=None, order='C'):
+        """
+        Return the array data as a string containing the raw bytes in the array.
+
+        The array is filled with a fill value before the string conversion.
+
+        .. versionadded:: 1.9.0
+
+        Parameters
+        ----------
+        fill_value : scalar, optional
+            Value used to fill in the masked values. Default is None, in which
+            case `MaskedArray.fill_value` is used.
+        order : {'C','F','A'}, optional
+            Order of the data item in the copy. Default is 'C'.
+
+            - 'C'   -- C order (row major).
+            - 'F'   -- Fortran order (column major).
+            - 'A'   -- Any, current order of array.
+            - None  -- Same as 'A'.
+
+        See Also
+        --------
+        numpy.ndarray.tobytes
+        tolist, tofile
+
+        Notes
+        -----
+        As for `ndarray.tobytes`, information about the shape, dtype, etc.,
+        but also about `fill_value`, will be lost.
+
+        Examples
+        --------
+        >>> x = np.ma.array(np.array([[1, 2], [3, 4]]), mask=[[0, 1], [1, 0]])
+        >>> x.tobytes()
+        b'\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00?B\\x0f\\x00\\x00\\x00\\x00\\x00?B\\x0f\\x00\\x00\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\x00\\x00\\x00\\x00'
+
+        """
+        return self.filled(fill_value).tobytes(order=order)
+
+    def tofile(self, fid, sep="", format="%s"):
+        """
+        Save a masked array to a file in binary format.
+
+        .. warning::
+          This function is not implemented yet.
+
+        Raises
+        ------
+        NotImplementedError
+            When `tofile` is called.
+
+        """
+        raise NotImplementedError("MaskedArray.tofile() not implemented yet.")
+
+    def toflex(self):
+        """
+        Transforms a masked array into a flexible-type array.
+
+        The flexible type array that is returned will have two fields:
+
+        * the ``_data`` field stores the ``_data`` part of the array.
+        * the ``_mask`` field stores the ``_mask`` part of the array.
+
+        Parameters
+        ----------
+        None
+
+        Returns
+        -------
+        record : ndarray
+            A new flexible-type `ndarray` with two fields: the first element
+            containing a value, the second element containing the corresponding
+            mask boolean. The returned record shape matches self.shape.
+
+        Notes
+        -----
+        A side-effect of transforming a masked array into a flexible `ndarray` is
+        that meta information (``fill_value``, ...) will be lost.
+
+        Examples
+        --------
+        >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
+        >>> x
+        masked_array(
+          data=[[1, --, 3],
+                [--, 5, --],
+                [7, --, 9]],
+          mask=[[False,  True, False],
+                [ True, False,  True],
+                [False,  True, False]],
+          fill_value=999999)
+        >>> x.toflex()
+        array([[(1, False), (2,  True), (3, False)],
+               [(4,  True), (5, False), (6,  True)],
+               [(7, False), (8,  True), (9, False)]],
+              dtype=[('_data', 'i2", (2,))])
+            # x = A[0]; y = x["A"]; then y.mask["A"].size==2
+            # and we can not say masked/unmasked.
+            # The result is no longer mvoid!
+            # See also issue #6724.
+            return masked_array(
+                data=self._data[indx], mask=m[indx],
+                fill_value=self._fill_value[indx],
+                hard_mask=self._hardmask)
+        if m is not nomask and m[indx]:
+            return masked
+        return self._data[indx]
+
+    def __setitem__(self, indx, value):
+        self._data[indx] = value
+        if self._hardmask:
+            self._mask[indx] |= getattr(value, "_mask", False)
+        else:
+            self._mask[indx] = getattr(value, "_mask", False)
+
+    def __str__(self):
+        m = self._mask
+        if m is nomask:
+            return str(self._data)
+
+        rdtype = _replace_dtype_fields(self._data.dtype, "O")
+        data_arr = super()._data
+        res = data_arr.astype(rdtype)
+        _recursive_printoption(res, self._mask, masked_print_option)
+        return str(res)
+
+    __repr__ = __str__
+
+    def __iter__(self):
+        "Defines an iterator for mvoid"
+        (_data, _mask) = (self._data, self._mask)
+        if _mask is nomask:
+            yield from _data
+        else:
+            for (d, m) in zip(_data, _mask):
+                if m:
+                    yield masked
+                else:
+                    yield d
+
+    def __len__(self):
+        return self._data.__len__()
+
+    def filled(self, fill_value=None):
+        """
+        Return a copy with masked fields filled with a given value.
+
+        Parameters
+        ----------
+        fill_value : array_like, optional
+            The value to use for invalid entries. Can be scalar or
+            non-scalar. If latter is the case, the filled array should
+            be broadcastable over input array. Default is None, in
+            which case the `fill_value` attribute is used instead.
+
+        Returns
+        -------
+        filled_void
+            A `np.void` object
+
+        See Also
+        --------
+        MaskedArray.filled
+
+        """
+        return asarray(self).filled(fill_value)[()]
+
+    def tolist(self):
+        """
+    Transforms the mvoid object into a tuple.
+
+    Masked fields are replaced by None.
+
+    Returns
+    -------
+    returned_tuple
+        Tuple of fields
+        """
+        _mask = self._mask
+        if _mask is nomask:
+            return self._data.tolist()
+        result = []
+        for (d, m) in zip(self._data, self._mask):
+            if m:
+                result.append(None)
+            else:
+                # .item() makes sure we return a standard Python object
+                result.append(d.item())
+        return tuple(result)
+
+
+##############################################################################
+#                                Shortcuts                                   #
+##############################################################################
+
+
+def isMaskedArray(x):
+    """
+    Test whether input is an instance of MaskedArray.
+
+    This function returns True if `x` is an instance of MaskedArray
+    and returns False otherwise.  Any object is accepted as input.
+
+    Parameters
+    ----------
+    x : object
+        Object to test.
+
+    Returns
+    -------
+    result : bool
+        True if `x` is a MaskedArray.
+
+    See Also
+    --------
+    isMA : Alias to isMaskedArray.
+    isarray : Alias to isMaskedArray.
+
+    Examples
+    --------
+    >>> import numpy.ma as ma
+    >>> a = np.eye(3, 3)
+    >>> a
+    array([[ 1.,  0.,  0.],
+           [ 0.,  1.,  0.],
+           [ 0.,  0.,  1.]])
+    >>> m = ma.masked_values(a, 0)
+    >>> m
+    masked_array(
+      data=[[1.0, --, --],
+            [--, 1.0, --],
+            [--, --, 1.0]],
+      mask=[[False,  True,  True],
+            [ True, False,  True],
+            [ True,  True, False]],
+      fill_value=0.0)
+    >>> ma.isMaskedArray(a)
+    False
+    >>> ma.isMaskedArray(m)
+    True
+    >>> ma.isMaskedArray([0, 1, 2])
+    False
+
+    """
+    return isinstance(x, MaskedArray)
+
+
+isarray = isMaskedArray
+isMA = isMaskedArray  # backward compatibility
+
+
+class MaskedConstant(MaskedArray):
+    # the lone np.ma.masked instance
+    __singleton = None
+
+    @classmethod
+    def __has_singleton(cls):
+        # second case ensures `cls.__singleton` is not just a view on the
+        # superclass singleton
+        return cls.__singleton is not None and type(cls.__singleton) is cls
+
+    def __new__(cls):
+        if not cls.__has_singleton():
+            # We define the masked singleton as a float for higher precedence.
+            # Note that it can be tricky sometimes w/ type comparison
+            data = np.array(0.)
+            mask = np.array(True)
+
+            # prevent any modifications
+            data.flags.writeable = False
+            mask.flags.writeable = False
+
+            # don't fall back on MaskedArray.__new__(MaskedConstant), since
+            # that might confuse it - this way, the construction is entirely
+            # within our control
+            cls.__singleton = MaskedArray(data, mask=mask).view(cls)
+
+        return cls.__singleton
+
+    def __array_finalize__(self, obj):
+        if not self.__has_singleton():
+            # this handles the `.view` in __new__, which we want to copy across
+            # properties normally
+            return super().__array_finalize__(obj)
+        elif self is self.__singleton:
+            # not clear how this can happen, play it safe
+            pass
+        else:
+            # everywhere else, we want to downcast to MaskedArray, to prevent a
+            # duplicate maskedconstant.
+            self.__class__ = MaskedArray
+            MaskedArray.__array_finalize__(self, obj)
+
+    def __array_prepare__(self, obj, context=None):
+        return self.view(MaskedArray).__array_prepare__(obj, context)
+
+    def __array_wrap__(self, obj, context=None):
+        return self.view(MaskedArray).__array_wrap__(obj, context)
+
+    def __str__(self):
+        return str(masked_print_option._display)
+
+    def __repr__(self):
+        if self is MaskedConstant.__singleton:
+            return 'masked'
+        else:
+            # it's a subclass, or something is wrong, make it obvious
+            return object.__repr__(self)
+
+    def __format__(self, format_spec):
+        # Replace ndarray.__format__ with the default, which supports no format characters.
+        # Supporting format characters is unwise here, because we do not know what type
+        # the user was expecting - better to not guess.
+        try:
+            return object.__format__(self, format_spec)
+        except TypeError:
+            # 2020-03-23, NumPy 1.19.0
+            warnings.warn(
+                "Format strings passed to MaskedConstant are ignored, but in future may "
+                "error or produce different behavior",
+                FutureWarning, stacklevel=2
+            )
+            return object.__format__(self, "")
+
+    def __reduce__(self):
+        """Override of MaskedArray's __reduce__.
+        """
+        return (self.__class__, ())
+
+    # inplace operations have no effect. We have to override them to avoid
+    # trying to modify the readonly data and mask arrays
+    def __iop__(self, other):
+        return self
+    __iadd__ = \
+    __isub__ = \
+    __imul__ = \
+    __ifloordiv__ = \
+    __itruediv__ = \
+    __ipow__ = \
+        __iop__
+    del __iop__  # don't leave this around
+
+    def copy(self, *args, **kwargs):
+        """ Copy is a no-op on the maskedconstant, as it is a scalar """
+        # maskedconstant is a scalar, so copy doesn't need to copy. There's
+        # precedent for this with `np.bool_` scalars.
+        return self
+
+    def __copy__(self):
+        return self
+
+    def __deepcopy__(self, memo):
+        return self
+
+    def __setattr__(self, attr, value):
+        if not self.__has_singleton():
+            # allow the singleton to be initialized
+            return super().__setattr__(attr, value)
+        elif self is self.__singleton:
+            raise AttributeError(
+                f"attributes of {self!r} are not writeable")
+        else:
+            # duplicate instance - we can end up here from __array_finalize__,
+            # where we set the __class__ attribute
+            return super().__setattr__(attr, value)
+
+
+masked = masked_singleton = MaskedConstant()
+masked_array = MaskedArray
+
+
+def array(data, dtype=None, copy=False, order=None,
+          mask=nomask, fill_value=None, keep_mask=True,
+          hard_mask=False, shrink=True, subok=True, ndmin=0):
+    """
+    Shortcut to MaskedArray.
+
+    The options are in a different order for convenience and backwards
+    compatibility.
+
+    """
+    return MaskedArray(data, mask=mask, dtype=dtype, copy=copy,
+                       subok=subok, keep_mask=keep_mask,
+                       hard_mask=hard_mask, fill_value=fill_value,
+                       ndmin=ndmin, shrink=shrink, order=order)
+array.__doc__ = masked_array.__doc__
+
+
+def is_masked(x):
+    """
+    Determine whether input has masked values.
+
+    Accepts any object as input, but always returns False unless the
+    input is a MaskedArray containing masked values.
+
+    Parameters
+    ----------
+    x : array_like
+        Array to check for masked values.
+
+    Returns
+    -------
+    result : bool
+        True if `x` is a MaskedArray with masked values, False otherwise.
+
+    Examples
+    --------
+    >>> import numpy.ma as ma
+    >>> x = ma.masked_equal([0, 1, 0, 2, 3], 0)
+    >>> x
+    masked_array(data=[--, 1, --, 2, 3],
+                 mask=[ True, False,  True, False, False],
+           fill_value=0)
+    >>> ma.is_masked(x)
+    True
+    >>> x = ma.masked_equal([0, 1, 0, 2, 3], 42)
+    >>> x
+    masked_array(data=[0, 1, 0, 2, 3],
+                 mask=False,
+           fill_value=42)
+    >>> ma.is_masked(x)
+    False
+
+    Always returns False if `x` isn't a MaskedArray.
+
+    >>> x = [False, True, False]
+    >>> ma.is_masked(x)
+    False
+    >>> x = 'a string'
+    >>> ma.is_masked(x)
+    False
+
+    """
+    m = getmask(x)
+    if m is nomask:
+        return False
+    elif m.any():
+        return True
+    return False
+
+
+##############################################################################
+#                             Extrema functions                              #
+##############################################################################
+
+
+class _extrema_operation(_MaskedUFunc):
+    """
+    Generic class for maximum/minimum functions.
+
+    .. note::
+      This is the base class for `_maximum_operation` and
+      `_minimum_operation`.
+
+    """
+    def __init__(self, ufunc, compare, fill_value):
+        super().__init__(ufunc)
+        self.compare = compare
+        self.fill_value_func = fill_value
+
+    def __call__(self, a, b):
+        "Executes the call behavior."
+
+        return where(self.compare(a, b), a, b)
+
+    def reduce(self, target, axis=np._NoValue):
+        "Reduce target along the given axis."
+        target = narray(target, copy=False, subok=True)
+        m = getmask(target)
+
+        if axis is np._NoValue and target.ndim > 1:
+            # 2017-05-06, Numpy 1.13.0: warn on axis default
+            warnings.warn(
+                f"In the future the default for ma.{self.__name__}.reduce will be axis=0, "
+                f"not the current None, to match np.{self.__name__}.reduce. "
+                "Explicitly pass 0 or None to silence this warning.",
+                MaskedArrayFutureWarning, stacklevel=2)
+            axis = None
+
+        if axis is not np._NoValue:
+            kwargs = dict(axis=axis)
+        else:
+            kwargs = dict()
+
+        if m is nomask:
+            t = self.f.reduce(target, **kwargs)
+        else:
+            target = target.filled(
+                self.fill_value_func(target)).view(type(target))
+            t = self.f.reduce(target, **kwargs)
+            m = umath.logical_and.reduce(m, **kwargs)
+            if hasattr(t, '_mask'):
+                t._mask = m
+            elif m:
+                t = masked
+        return t
+
+    def outer(self, a, b):
+        "Return the function applied to the outer product of a and b."
+        ma = getmask(a)
+        mb = getmask(b)
+        if ma is nomask and mb is nomask:
+            m = nomask
+        else:
+            ma = getmaskarray(a)
+            mb = getmaskarray(b)
+            m = logical_or.outer(ma, mb)
+        result = self.f.outer(filled(a), filled(b))
+        if not isinstance(result, MaskedArray):
+            result = result.view(MaskedArray)
+        result._mask = m
+        return result
+
+def min(obj, axis=None, out=None, fill_value=None, keepdims=np._NoValue):
+    kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims}
+
+    try:
+        return obj.min(axis=axis, fill_value=fill_value, out=out, **kwargs)
+    except (AttributeError, TypeError):
+        # If obj doesn't have a min method, or if the method doesn't accept a
+        # fill_value argument
+        return asanyarray(obj).min(axis=axis, fill_value=fill_value,
+                                   out=out, **kwargs)
+min.__doc__ = MaskedArray.min.__doc__
+
+def max(obj, axis=None, out=None, fill_value=None, keepdims=np._NoValue):
+    kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims}
+
+    try:
+        return obj.max(axis=axis, fill_value=fill_value, out=out, **kwargs)
+    except (AttributeError, TypeError):
+        # If obj doesn't have a max method, or if the method doesn't accept a
+        # fill_value argument
+        return asanyarray(obj).max(axis=axis, fill_value=fill_value,
+                                   out=out, **kwargs)
+max.__doc__ = MaskedArray.max.__doc__
+
+
+def ptp(obj, axis=None, out=None, fill_value=None, keepdims=np._NoValue):
+    kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims}
+    try:
+        return obj.ptp(axis, out=out, fill_value=fill_value, **kwargs)
+    except (AttributeError, TypeError):
+        # If obj doesn't have a ptp method or if the method doesn't accept
+        # a fill_value argument
+        return asanyarray(obj).ptp(axis=axis, fill_value=fill_value,
+                                   out=out, **kwargs)
+ptp.__doc__ = MaskedArray.ptp.__doc__
+
+
+##############################################################################
+#           Definition of functions from the corresponding methods           #
+##############################################################################
+
+
+class _frommethod:
+    """
+    Define functions from existing MaskedArray methods.
+
+    Parameters
+    ----------
+    methodname : str
+        Name of the method to transform.
+
+    """
+
+    def __init__(self, methodname, reversed=False):
+        self.__name__ = methodname
+        self.__doc__ = self.getdoc()
+        self.reversed = reversed
+
+    def getdoc(self):
+        "Return the doc of the function (from the doc of the method)."
+        meth = getattr(MaskedArray, self.__name__, None) or\
+            getattr(np, self.__name__, None)
+        signature = self.__name__ + get_object_signature(meth)
+        if meth is not None:
+            doc = """    %s\n%s""" % (
+                signature, getattr(meth, '__doc__', None))
+            return doc
+
+    def __call__(self, a, *args, **params):
+        if self.reversed:
+            args = list(args)
+            a, args[0] = args[0], a
+
+        marr = asanyarray(a)
+        method_name = self.__name__
+        method = getattr(type(marr), method_name, None)
+        if method is None:
+            # use the corresponding np function
+            method = getattr(np, method_name)
+
+        return method(marr, *args, **params)
+
+
+all = _frommethod('all')
+anomalies = anom = _frommethod('anom')
+any = _frommethod('any')
+compress = _frommethod('compress', reversed=True)
+cumprod = _frommethod('cumprod')
+cumsum = _frommethod('cumsum')
+copy = _frommethod('copy')
+diagonal = _frommethod('diagonal')
+harden_mask = _frommethod('harden_mask')
+ids = _frommethod('ids')
+maximum = _extrema_operation(umath.maximum, greater, maximum_fill_value)
+mean = _frommethod('mean')
+minimum = _extrema_operation(umath.minimum, less, minimum_fill_value)
+nonzero = _frommethod('nonzero')
+prod = _frommethod('prod')
+product = _frommethod('prod')
+ravel = _frommethod('ravel')
+repeat = _frommethod('repeat')
+shrink_mask = _frommethod('shrink_mask')
+soften_mask = _frommethod('soften_mask')
+std = _frommethod('std')
+sum = _frommethod('sum')
+swapaxes = _frommethod('swapaxes')
+#take = _frommethod('take')
+trace = _frommethod('trace')
+var = _frommethod('var')
+
+count = _frommethod('count')
+
+def take(a, indices, axis=None, out=None, mode='raise'):
+    """
+    """
+    a = masked_array(a)
+    return a.take(indices, axis=axis, out=out, mode=mode)
+
+
+def power(a, b, third=None):
+    """
+    Returns element-wise base array raised to power from second array.
+
+    This is the masked array version of `numpy.power`. For details see
+    `numpy.power`.
+
+    See Also
+    --------
+    numpy.power
+
+    Notes
+    -----
+    The *out* argument to `numpy.power` is not supported, `third` has to be
+    None.
+
+    Examples
+    --------
+    >>> import numpy.ma as ma
+    >>> x = [11.2, -3.973, 0.801, -1.41]
+    >>> mask = [0, 0, 0, 1]
+    >>> masked_x = ma.masked_array(x, mask)
+    >>> masked_x
+    masked_array(data=[11.2, -3.973, 0.801, --],
+             mask=[False, False, False,  True],
+       fill_value=1e+20)
+    >>> ma.power(masked_x, 2)
+    masked_array(data=[125.43999999999998, 15.784728999999999,
+                   0.6416010000000001, --],
+             mask=[False, False, False,  True],
+       fill_value=1e+20)
+    >>> y = [-0.5, 2, 0, 17]
+    >>> masked_y = ma.masked_array(y, mask)
+    >>> masked_y
+    masked_array(data=[-0.5, 2.0, 0.0, --],
+             mask=[False, False, False,  True],
+       fill_value=1e+20)
+    >>> ma.power(masked_x, masked_y)
+    masked_array(data=[0.29880715233359845, 15.784728999999999, 1.0, --],
+             mask=[False, False, False,  True],
+       fill_value=1e+20)
+
+    """
+    if third is not None:
+        raise MaskError("3-argument power not supported.")
+    # Get the masks
+    ma = getmask(a)
+    mb = getmask(b)
+    m = mask_or(ma, mb)
+    # Get the rawdata
+    fa = getdata(a)
+    fb = getdata(b)
+    # Get the type of the result (so that we preserve subclasses)
+    if isinstance(a, MaskedArray):
+        basetype = type(a)
+    else:
+        basetype = MaskedArray
+    # Get the result and view it as a (subclass of) MaskedArray
+    with np.errstate(divide='ignore', invalid='ignore'):
+        result = np.where(m, fa, umath.power(fa, fb)).view(basetype)
+    result._update_from(a)
+    # Find where we're in trouble w/ NaNs and Infs
+    invalid = np.logical_not(np.isfinite(result.view(ndarray)))
+    # Add the initial mask
+    if m is not nomask:
+        if not result.ndim:
+            return masked
+        result._mask = np.logical_or(m, invalid)
+    # Fix the invalid parts
+    if invalid.any():
+        if not result.ndim:
+            return masked
+        elif result._mask is nomask:
+            result._mask = invalid
+        result._data[invalid] = result.fill_value
+    return result
+
+argmin = _frommethod('argmin')
+argmax = _frommethod('argmax')
+
+def argsort(a, axis=np._NoValue, kind=None, order=None, endwith=True, fill_value=None):
+    "Function version of the eponymous method."
+    a = np.asanyarray(a)
+
+    # 2017-04-11, Numpy 1.13.0, gh-8701: warn on axis default
+    if axis is np._NoValue:
+        axis = _deprecate_argsort_axis(a)
+
+    if isinstance(a, MaskedArray):
+        return a.argsort(axis=axis, kind=kind, order=order,
+                         endwith=endwith, fill_value=fill_value)
+    else:
+        return a.argsort(axis=axis, kind=kind, order=order)
+argsort.__doc__ = MaskedArray.argsort.__doc__
+
+def sort(a, axis=-1, kind=None, order=None, endwith=True, fill_value=None):
+    """
+    Return a sorted copy of the masked array.
+
+    Equivalent to creating a copy of the array
+    and applying the  MaskedArray ``sort()`` method.
+
+    Refer to ``MaskedArray.sort`` for the full documentation
+
+    See Also
+    --------
+    MaskedArray.sort : equivalent method
+
+    Examples
+    --------
+    >>> import numpy.ma as ma
+    >>> x = [11.2, -3.973, 0.801, -1.41]
+    >>> mask = [0, 0, 0, 1]
+    >>> masked_x = ma.masked_array(x, mask)
+    >>> masked_x
+    masked_array(data=[11.2, -3.973, 0.801, --],
+                 mask=[False, False, False,  True],
+           fill_value=1e+20)
+    >>> ma.sort(masked_x)
+    masked_array(data=[-3.973, 0.801, 11.2, --],
+                 mask=[False, False, False,  True],
+           fill_value=1e+20)
+    """
+    a = np.array(a, copy=True, subok=True)
+    if axis is None:
+        a = a.flatten()
+        axis = 0
+
+    if isinstance(a, MaskedArray):
+        a.sort(axis=axis, kind=kind, order=order,
+               endwith=endwith, fill_value=fill_value)
+    else:
+        a.sort(axis=axis, kind=kind, order=order)
+    return a
+
+
+def compressed(x):
+    """
+    Return all the non-masked data as a 1-D array.
+
+    This function is equivalent to calling the "compressed" method of a
+    `ma.MaskedArray`, see `ma.MaskedArray.compressed` for details.
+
+    See Also
+    --------
+    ma.MaskedArray.compressed : Equivalent method.
+
+    Examples
+    --------
+    
+    Create an array with negative values masked:
+
+    >>> import numpy as np
+    >>> x = np.array([[1, -1, 0], [2, -1, 3], [7, 4, -1]])
+    >>> masked_x = np.ma.masked_array(x, mask=x < 0)
+    >>> masked_x
+    masked_array(
+      data=[[1, --, 0],
+            [2, --, 3],
+            [7, 4, --]],
+      mask=[[False,  True, False],
+            [False,  True, False],
+            [False, False,  True]],
+      fill_value=999999)
+
+    Compress the masked array into a 1-D array of non-masked values:
+
+    >>> np.ma.compressed(masked_x)
+    array([1, 0, 2, 3, 7, 4])
+
+    """
+    return asanyarray(x).compressed()
+
+
+def concatenate(arrays, axis=0):
+    """
+    Concatenate a sequence of arrays along the given axis.
+
+    Parameters
+    ----------
+    arrays : sequence of array_like
+        The arrays must have the same shape, except in the dimension
+        corresponding to `axis` (the first, by default).
+    axis : int, optional
+        The axis along which the arrays will be joined. Default is 0.
+
+    Returns
+    -------
+    result : MaskedArray
+        The concatenated array with any masked entries preserved.
+
+    See Also
+    --------
+    numpy.concatenate : Equivalent function in the top-level NumPy module.
+
+    Examples
+    --------
+    >>> import numpy.ma as ma
+    >>> a = ma.arange(3)
+    >>> a[1] = ma.masked
+    >>> b = ma.arange(2, 5)
+    >>> a
+    masked_array(data=[0, --, 2],
+                 mask=[False,  True, False],
+           fill_value=999999)
+    >>> b
+    masked_array(data=[2, 3, 4],
+                 mask=False,
+           fill_value=999999)
+    >>> ma.concatenate([a, b])
+    masked_array(data=[0, --, 2, 2, 3, 4],
+                 mask=[False,  True, False, False, False, False],
+           fill_value=999999)
+
+    """
+    d = np.concatenate([getdata(a) for a in arrays], axis)
+    rcls = get_masked_subclass(*arrays)
+    data = d.view(rcls)
+    # Check whether one of the arrays has a non-empty mask.
+    for x in arrays:
+        if getmask(x) is not nomask:
+            break
+    else:
+        return data
+    # OK, so we have to concatenate the masks
+    dm = np.concatenate([getmaskarray(a) for a in arrays], axis)
+    dm = dm.reshape(d.shape)
+
+    # If we decide to keep a '_shrinkmask' option, we want to check that
+    # all of them are True, and then check for dm.any()
+    data._mask = _shrink_mask(dm)
+    return data
+
+
+def diag(v, k=0):
+    """
+    Extract a diagonal or construct a diagonal array.
+
+    This function is the equivalent of `numpy.diag` that takes masked
+    values into account, see `numpy.diag` for details.
+
+    See Also
+    --------
+    numpy.diag : Equivalent function for ndarrays.
+
+    Examples
+    --------
+
+    Create an array with negative values masked:
+
+    >>> import numpy as np
+    >>> x = np.array([[11.2, -3.973, 18], [0.801, -1.41, 12], [7, 33, -12]])
+    >>> masked_x = np.ma.masked_array(x, mask=x < 0)
+    >>> masked_x
+    masked_array(
+      data=[[11.2, --, 18.0],
+            [0.801, --, 12.0],
+            [7.0, 33.0, --]],
+      mask=[[False,  True, False],
+            [False,  True, False],
+            [False, False,  True]],
+      fill_value=1e+20)
+
+    Isolate the main diagonal from the masked array:
+
+    >>> np.ma.diag(masked_x)
+    masked_array(data=[11.2, --, --],
+                 mask=[False,  True,  True],
+           fill_value=1e+20)
+
+    Isolate the first diagonal below the main diagonal:
+
+    >>> np.ma.diag(masked_x, -1)
+    masked_array(data=[0.801, 33.0],
+                 mask=[False, False],
+           fill_value=1e+20)
+
+    """
+    output = np.diag(v, k).view(MaskedArray)
+    if getmask(v) is not nomask:
+        output._mask = np.diag(v._mask, k)
+    return output
+
+
+def left_shift(a, n):
+    """
+    Shift the bits of an integer to the left.
+
+    This is the masked array version of `numpy.left_shift`, for details
+    see that function.
+
+    See Also
+    --------
+    numpy.left_shift
+
+    """
+    m = getmask(a)
+    if m is nomask:
+        d = umath.left_shift(filled(a), n)
+        return masked_array(d)
+    else:
+        d = umath.left_shift(filled(a, 0), n)
+        return masked_array(d, mask=m)
+
+
+def right_shift(a, n):
+    """
+    Shift the bits of an integer to the right.
+
+    This is the masked array version of `numpy.right_shift`, for details
+    see that function.
+
+    See Also
+    --------
+    numpy.right_shift
+
+    Examples
+    --------
+    >>> import numpy.ma as ma
+    >>> x = [11, 3, 8, 1]
+    >>> mask = [0, 0, 0, 1]
+    >>> masked_x = ma.masked_array(x, mask)
+    >>> masked_x
+    masked_array(data=[11, 3, 8, --],
+                 mask=[False, False, False,  True],
+           fill_value=999999)
+    >>> ma.right_shift(masked_x,1)
+    masked_array(data=[5, 1, 4, --],
+                 mask=[False, False, False,  True],
+           fill_value=999999)
+
+    """
+    m = getmask(a)
+    if m is nomask:
+        d = umath.right_shift(filled(a), n)
+        return masked_array(d)
+    else:
+        d = umath.right_shift(filled(a, 0), n)
+        return masked_array(d, mask=m)
+
+
+def put(a, indices, values, mode='raise'):
+    """
+    Set storage-indexed locations to corresponding values.
+
+    This function is equivalent to `MaskedArray.put`, see that method
+    for details.
+
+    See Also
+    --------
+    MaskedArray.put
+
+    """
+    # We can't use 'frommethod', the order of arguments is different
+    try:
+        return a.put(indices, values, mode=mode)
+    except AttributeError:
+        return narray(a, copy=False).put(indices, values, mode=mode)
+
+
+def putmask(a, mask, values):  # , mode='raise'):
+    """
+    Changes elements of an array based on conditional and input values.
+
+    This is the masked array version of `numpy.putmask`, for details see
+    `numpy.putmask`.
+
+    See Also
+    --------
+    numpy.putmask
+
+    Notes
+    -----
+    Using a masked array as `values` will **not** transform a `ndarray` into
+    a `MaskedArray`.
+
+    """
+    # We can't use 'frommethod', the order of arguments is different
+    if not isinstance(a, MaskedArray):
+        a = a.view(MaskedArray)
+    (valdata, valmask) = (getdata(values), getmask(values))
+    if getmask(a) is nomask:
+        if valmask is not nomask:
+            a._sharedmask = True
+            a._mask = make_mask_none(a.shape, a.dtype)
+            np.copyto(a._mask, valmask, where=mask)
+    elif a._hardmask:
+        if valmask is not nomask:
+            m = a._mask.copy()
+            np.copyto(m, valmask, where=mask)
+            a.mask |= m
+    else:
+        if valmask is nomask:
+            valmask = getmaskarray(values)
+        np.copyto(a._mask, valmask, where=mask)
+    np.copyto(a._data, valdata, where=mask)
+    return
+
+
+def transpose(a, axes=None):
+    """
+    Permute the dimensions of an array.
+
+    This function is exactly equivalent to `numpy.transpose`.
+
+    See Also
+    --------
+    numpy.transpose : Equivalent function in top-level NumPy module.
+
+    Examples
+    --------
+    >>> import numpy.ma as ma
+    >>> x = ma.arange(4).reshape((2,2))
+    >>> x[1, 1] = ma.masked
+    >>> x
+    masked_array(
+      data=[[0, 1],
+            [2, --]],
+      mask=[[False, False],
+            [False,  True]],
+      fill_value=999999)
+
+    >>> ma.transpose(x)
+    masked_array(
+      data=[[0, 2],
+            [1, --]],
+      mask=[[False, False],
+            [False,  True]],
+      fill_value=999999)
+    """
+    # We can't use 'frommethod', as 'transpose' doesn't take keywords
+    try:
+        return a.transpose(axes)
+    except AttributeError:
+        return narray(a, copy=False).transpose(axes).view(MaskedArray)
+
+
+def reshape(a, new_shape, order='C'):
+    """
+    Returns an array containing the same data with a new shape.
+
+    Refer to `MaskedArray.reshape` for full documentation.
+
+    See Also
+    --------
+    MaskedArray.reshape : equivalent function
+
+    """
+    # We can't use 'frommethod', it whine about some parameters. Dmmit.
+    try:
+        return a.reshape(new_shape, order=order)
+    except AttributeError:
+        _tmp = narray(a, copy=False).reshape(new_shape, order=order)
+        return _tmp.view(MaskedArray)
+
+
+def resize(x, new_shape):
+    """
+    Return a new masked array with the specified size and shape.
+
+    This is the masked equivalent of the `numpy.resize` function. The new
+    array is filled with repeated copies of `x` (in the order that the
+    data are stored in memory). If `x` is masked, the new array will be
+    masked, and the new mask will be a repetition of the old one.
+
+    See Also
+    --------
+    numpy.resize : Equivalent function in the top level NumPy module.
+
+    Examples
+    --------
+    >>> import numpy.ma as ma
+    >>> a = ma.array([[1, 2] ,[3, 4]])
+    >>> a[0, 1] = ma.masked
+    >>> a
+    masked_array(
+      data=[[1, --],
+            [3, 4]],
+      mask=[[False,  True],
+            [False, False]],
+      fill_value=999999)
+    >>> np.resize(a, (3, 3))
+    masked_array(
+      data=[[1, 2, 3],
+            [4, 1, 2],
+            [3, 4, 1]],
+      mask=False,
+      fill_value=999999)
+    >>> ma.resize(a, (3, 3))
+    masked_array(
+      data=[[1, --, 3],
+            [4, 1, --],
+            [3, 4, 1]],
+      mask=[[False,  True, False],
+            [False, False,  True],
+            [False, False, False]],
+      fill_value=999999)
+
+    A MaskedArray is always returned, regardless of the input type.
+
+    >>> a = np.array([[1, 2] ,[3, 4]])
+    >>> ma.resize(a, (3, 3))
+    masked_array(
+      data=[[1, 2, 3],
+            [4, 1, 2],
+            [3, 4, 1]],
+      mask=False,
+      fill_value=999999)
+
+    """
+    # We can't use _frommethods here, as N.resize is notoriously whiny.
+    m = getmask(x)
+    if m is not nomask:
+        m = np.resize(m, new_shape)
+    result = np.resize(x, new_shape).view(get_masked_subclass(x))
+    if result.ndim:
+        result._mask = m
+    return result
+
+
+def ndim(obj):
+    """
+    maskedarray version of the numpy function.
+
+    """
+    return np.ndim(getdata(obj))
+
+ndim.__doc__ = np.ndim.__doc__
+
+
+def shape(obj):
+    "maskedarray version of the numpy function."
+    return np.shape(getdata(obj))
+shape.__doc__ = np.shape.__doc__
+
+
+def size(obj, axis=None):
+    "maskedarray version of the numpy function."
+    return np.size(getdata(obj), axis)
+size.__doc__ = np.size.__doc__
+
+
+def diff(a, /, n=1, axis=-1, prepend=np._NoValue, append=np._NoValue):
+    """
+    Calculate the n-th discrete difference along the given axis.
+    The first difference is given by ``out[i] = a[i+1] - a[i]`` along
+    the given axis, higher differences are calculated by using `diff`
+    recursively.
+    Preserves the input mask.
+
+    Parameters
+    ----------
+    a : array_like
+        Input array
+    n : int, optional
+        The number of times values are differenced. If zero, the input
+        is returned as-is.
+    axis : int, optional
+        The axis along which the difference is taken, default is the
+        last axis.
+    prepend, append : array_like, optional
+        Values to prepend or append to `a` along axis prior to
+        performing the difference.  Scalar values are expanded to
+        arrays with length 1 in the direction of axis and the shape
+        of the input array in along all other axes.  Otherwise the
+        dimension and shape must match `a` except along axis.
+
+    Returns
+    -------
+    diff : MaskedArray
+        The n-th differences. The shape of the output is the same as `a`
+        except along `axis` where the dimension is smaller by `n`. The
+        type of the output is the same as the type of the difference
+        between any two elements of `a`. This is the same as the type of
+        `a` in most cases. A notable exception is `datetime64`, which
+        results in a `timedelta64` output array.
+
+    See Also
+    --------
+    numpy.diff : Equivalent function in the top-level NumPy module.
+
+    Notes
+    -----
+    Type is preserved for boolean arrays, so the result will contain
+    `False` when consecutive elements are the same and `True` when they
+    differ.
+
+    For unsigned integer arrays, the results will also be unsigned. This
+    should not be surprising, as the result is consistent with
+    calculating the difference directly:
+
+    >>> u8_arr = np.array([1, 0], dtype=np.uint8)
+    >>> np.ma.diff(u8_arr)
+    masked_array(data=[255],
+                 mask=False,
+           fill_value=999999,
+                dtype=uint8)
+    >>> u8_arr[1,...] - u8_arr[0,...]
+    255
+
+    If this is not desirable, then the array should be cast to a larger
+    integer type first:
+
+    >>> i16_arr = u8_arr.astype(np.int16)
+    >>> np.ma.diff(i16_arr)
+    masked_array(data=[-1],
+                 mask=False,
+           fill_value=999999,
+                dtype=int16)
+
+    Examples
+    --------
+    >>> a = np.array([1, 2, 3, 4, 7, 0, 2, 3])
+    >>> x = np.ma.masked_where(a < 2, a)
+    >>> np.ma.diff(x)
+    masked_array(data=[--, 1, 1, 3, --, --, 1],
+            mask=[ True, False, False, False,  True,  True, False],
+        fill_value=999999)
+
+    >>> np.ma.diff(x, n=2)
+    masked_array(data=[--, 0, 2, --, --, --],
+                mask=[ True, False, False,  True,  True,  True],
+        fill_value=999999)
+
+    >>> a = np.array([[1, 3, 1, 5, 10], [0, 1, 5, 6, 8]])
+    >>> x = np.ma.masked_equal(a, value=1)
+    >>> np.ma.diff(x)
+    masked_array(
+        data=[[--, --, --, 5],
+                [--, --, 1, 2]],
+        mask=[[ True,  True,  True, False],
+                [ True,  True, False, False]],
+        fill_value=1)
+
+    >>> np.ma.diff(x, axis=0)
+    masked_array(data=[[--, --, --, 1, -2]],
+            mask=[[ True,  True,  True, False, False]],
+        fill_value=1)
+
+    """
+    if n == 0:
+        return a
+    if n < 0:
+        raise ValueError("order must be non-negative but got " + repr(n))
+
+    a = np.ma.asanyarray(a)
+    if a.ndim == 0:
+        raise ValueError(
+            "diff requires input that is at least one dimensional"
+            )
+
+    combined = []
+    if prepend is not np._NoValue:
+        prepend = np.ma.asanyarray(prepend)
+        if prepend.ndim == 0:
+            shape = list(a.shape)
+            shape[axis] = 1
+            prepend = np.broadcast_to(prepend, tuple(shape))
+        combined.append(prepend)
+
+    combined.append(a)
+
+    if append is not np._NoValue:
+        append = np.ma.asanyarray(append)
+        if append.ndim == 0:
+            shape = list(a.shape)
+            shape[axis] = 1
+            append = np.broadcast_to(append, tuple(shape))
+        combined.append(append)
+
+    if len(combined) > 1:
+        a = np.ma.concatenate(combined, axis)
+
+    # GH 22465 np.diff without prepend/append preserves the mask
+    return np.diff(a, n, axis)
+
+
+##############################################################################
+#                            Extra functions                                 #
+##############################################################################
+
+
+def where(condition, x=_NoValue, y=_NoValue):
+    """
+    Return a masked array with elements from `x` or `y`, depending on condition.
+
+    .. note::
+        When only `condition` is provided, this function is identical to
+        `nonzero`. The rest of this documentation covers only the case where
+        all three arguments are provided.
+
+    Parameters
+    ----------
+    condition : array_like, bool
+        Where True, yield `x`, otherwise yield `y`.
+    x, y : array_like, optional
+        Values from which to choose. `x`, `y` and `condition` need to be
+        broadcastable to some shape.
+
+    Returns
+    -------
+    out : MaskedArray
+        An masked array with `masked` elements where the condition is masked,
+        elements from `x` where `condition` is True, and elements from `y`
+        elsewhere.
+
+    See Also
+    --------
+    numpy.where : Equivalent function in the top-level NumPy module.
+    nonzero : The function that is called when x and y are omitted
+
+    Examples
+    --------
+    >>> x = np.ma.array(np.arange(9.).reshape(3, 3), mask=[[0, 1, 0],
+    ...                                                    [1, 0, 1],
+    ...                                                    [0, 1, 0]])
+    >>> x
+    masked_array(
+      data=[[0.0, --, 2.0],
+            [--, 4.0, --],
+            [6.0, --, 8.0]],
+      mask=[[False,  True, False],
+            [ True, False,  True],
+            [False,  True, False]],
+      fill_value=1e+20)
+    >>> np.ma.where(x > 5, x, -3.1416)
+    masked_array(
+      data=[[-3.1416, --, -3.1416],
+            [--, -3.1416, --],
+            [6.0, --, 8.0]],
+      mask=[[False,  True, False],
+            [ True, False,  True],
+            [False,  True, False]],
+      fill_value=1e+20)
+
+    """
+
+    # handle the single-argument case
+    missing = (x is _NoValue, y is _NoValue).count(True)
+    if missing == 1:
+        raise ValueError("Must provide both 'x' and 'y' or neither.")
+    if missing == 2:
+        return nonzero(condition)
+
+    # we only care if the condition is true - false or masked pick y
+    cf = filled(condition, False)
+    xd = getdata(x)
+    yd = getdata(y)
+
+    # we need the full arrays here for correct final dimensions
+    cm = getmaskarray(condition)
+    xm = getmaskarray(x)
+    ym = getmaskarray(y)
+
+    # deal with the fact that masked.dtype == float64, but we don't actually
+    # want to treat it as that.
+    if x is masked and y is not masked:
+        xd = np.zeros((), dtype=yd.dtype)
+        xm = np.ones((),  dtype=ym.dtype)
+    elif y is masked and x is not masked:
+        yd = np.zeros((), dtype=xd.dtype)
+        ym = np.ones((),  dtype=xm.dtype)
+
+    data = np.where(cf, xd, yd)
+    mask = np.where(cf, xm, ym)
+    mask = np.where(cm, np.ones((), dtype=mask.dtype), mask)
+
+    # collapse the mask, for backwards compatibility
+    mask = _shrink_mask(mask)
+
+    return masked_array(data, mask=mask)
+
+
+def choose(indices, choices, out=None, mode='raise'):
+    """
+    Use an index array to construct a new array from a list of choices.
+
+    Given an array of integers and a list of n choice arrays, this method
+    will create a new array that merges each of the choice arrays.  Where a
+    value in `index` is i, the new array will have the value that choices[i]
+    contains in the same place.
+
+    Parameters
+    ----------
+    indices : ndarray of ints
+        This array must contain integers in ``[0, n-1]``, where n is the
+        number of choices.
+    choices : sequence of arrays
+        Choice arrays. The index array and all of the choices should be
+        broadcastable to the same shape.
+    out : array, optional
+        If provided, the result will be inserted into this array. It should
+        be of the appropriate shape and `dtype`.
+    mode : {'raise', 'wrap', 'clip'}, optional
+        Specifies how out-of-bounds indices will behave.
+
+        * 'raise' : raise an error
+        * 'wrap' : wrap around
+        * 'clip' : clip to the range
+
+    Returns
+    -------
+    merged_array : array
+
+    See Also
+    --------
+    choose : equivalent function
+
+    Examples
+    --------
+    >>> choice = np.array([[1,1,1], [2,2,2], [3,3,3]])
+    >>> a = np.array([2, 1, 0])
+    >>> np.ma.choose(a, choice)
+    masked_array(data=[3, 2, 1],
+                 mask=False,
+           fill_value=999999)
+
+    """
+    def fmask(x):
+        "Returns the filled array, or True if masked."
+        if x is masked:
+            return True
+        return filled(x)
+
+    def nmask(x):
+        "Returns the mask, True if ``masked``, False if ``nomask``."
+        if x is masked:
+            return True
+        return getmask(x)
+    # Get the indices.
+    c = filled(indices, 0)
+    # Get the masks.
+    masks = [nmask(x) for x in choices]
+    data = [fmask(x) for x in choices]
+    # Construct the mask
+    outputmask = np.choose(c, masks, mode=mode)
+    outputmask = make_mask(mask_or(outputmask, getmask(indices)),
+                           copy=False, shrink=True)
+    # Get the choices.
+    d = np.choose(c, data, mode=mode, out=out).view(MaskedArray)
+    if out is not None:
+        if isinstance(out, MaskedArray):
+            out.__setmask__(outputmask)
+        return out
+    d.__setmask__(outputmask)
+    return d
+
+
+def round_(a, decimals=0, out=None):
+    """
+    Return a copy of a, rounded to 'decimals' places.
+
+    When 'decimals' is negative, it specifies the number of positions
+    to the left of the decimal point.  The real and imaginary parts of
+    complex numbers are rounded separately. Nothing is done if the
+    array is not of float type and 'decimals' is greater than or equal
+    to 0.
+
+    Parameters
+    ----------
+    decimals : int
+        Number of decimals to round to. May be negative.
+    out : array_like
+        Existing array to use for output.
+        If not given, returns a default copy of a.
+
+    Notes
+    -----
+    If out is given and does not have a mask attribute, the mask of a
+    is lost!
+
+    Examples
+    --------
+    >>> import numpy.ma as ma
+    >>> x = [11.2, -3.973, 0.801, -1.41]
+    >>> mask = [0, 0, 0, 1]
+    >>> masked_x = ma.masked_array(x, mask)
+    >>> masked_x
+    masked_array(data=[11.2, -3.973, 0.801, --],
+                 mask=[False, False, False, True],
+        fill_value=1e+20)
+    >>> ma.round_(masked_x)
+    masked_array(data=[11.0, -4.0, 1.0, --],
+                 mask=[False, False, False, True],
+        fill_value=1e+20)
+    >>> ma.round(masked_x, decimals=1)
+    masked_array(data=[11.2, -4.0, 0.8, --],
+                 mask=[False, False, False, True],
+        fill_value=1e+20)
+    >>> ma.round_(masked_x, decimals=-1)
+    masked_array(data=[10.0, -0.0, 0.0, --],
+                 mask=[False, False, False, True],
+        fill_value=1e+20)
+    """
+    if out is None:
+        return np.round_(a, decimals, out)
+    else:
+        np.round_(getdata(a), decimals, out)
+        if hasattr(out, '_mask'):
+            out._mask = getmask(a)
+        return out
+round = round_
+
+
+def _mask_propagate(a, axis):
+    """
+    Mask whole 1-d vectors of an array that contain masked values.
+    """
+    a = array(a, subok=False)
+    m = getmask(a)
+    if m is nomask or not m.any() or axis is None:
+        return a
+    a._mask = a._mask.copy()
+    axes = normalize_axis_tuple(axis, a.ndim)
+    for ax in axes:
+        a._mask |= m.any(axis=ax, keepdims=True)
+    return a
+
+
+# Include masked dot here to avoid import problems in getting it from
+# extras.py. Note that it is not included in __all__, but rather exported
+# from extras in order to avoid backward compatibility problems.
+def dot(a, b, strict=False, out=None):
+    """
+    Return the dot product of two arrays.
+
+    This function is the equivalent of `numpy.dot` that takes masked values
+    into account. Note that `strict` and `out` are in different position
+    than in the method version. In order to maintain compatibility with the
+    corresponding method, it is recommended that the optional arguments be
+    treated as keyword only.  At some point that may be mandatory.
+
+    Parameters
+    ----------
+    a, b : masked_array_like
+        Inputs arrays.
+    strict : bool, optional
+        Whether masked data are propagated (True) or set to 0 (False) for
+        the computation. Default is False.  Propagating the mask means that
+        if a masked value appears in a row or column, the whole row or
+        column is considered masked.
+    out : masked_array, optional
+        Output argument. This must have the exact kind that would be returned
+        if it was not used. In particular, it must have the right type, must be
+        C-contiguous, and its dtype must be the dtype that would be returned
+        for `dot(a,b)`. This is a performance feature. Therefore, if these
+        conditions are not met, an exception is raised, instead of attempting
+        to be flexible.
+
+        .. versionadded:: 1.10.2
+
+    See Also
+    --------
+    numpy.dot : Equivalent function for ndarrays.
+
+    Examples
+    --------
+    >>> a = np.ma.array([[1, 2, 3], [4, 5, 6]], mask=[[1, 0, 0], [0, 0, 0]])
+    >>> b = np.ma.array([[1, 2], [3, 4], [5, 6]], mask=[[1, 0], [0, 0], [0, 0]])
+    >>> np.ma.dot(a, b)
+    masked_array(
+      data=[[21, 26],
+            [45, 64]],
+      mask=[[False, False],
+            [False, False]],
+      fill_value=999999)
+    >>> np.ma.dot(a, b, strict=True)
+    masked_array(
+      data=[[--, --],
+            [--, 64]],
+      mask=[[ True,  True],
+            [ True, False]],
+      fill_value=999999)
+
+    """
+    if strict is True:
+        if np.ndim(a) == 0 or np.ndim(b) == 0:
+            pass
+        elif b.ndim == 1:
+            a = _mask_propagate(a, a.ndim - 1)
+            b = _mask_propagate(b, b.ndim - 1)
+        else:
+            a = _mask_propagate(a, a.ndim - 1)
+            b = _mask_propagate(b, b.ndim - 2)
+    am = ~getmaskarray(a)
+    bm = ~getmaskarray(b)
+
+    if out is None:
+        d = np.dot(filled(a, 0), filled(b, 0))
+        m = ~np.dot(am, bm)
+        if np.ndim(d) == 0:
+            d = np.asarray(d)
+        r = d.view(get_masked_subclass(a, b))
+        r.__setmask__(m)
+        return r
+    else:
+        d = np.dot(filled(a, 0), filled(b, 0), out._data)
+        if out.mask.shape != d.shape:
+            out._mask = np.empty(d.shape, MaskType)
+        np.dot(am, bm, out._mask)
+        np.logical_not(out._mask, out._mask)
+        return out
+
+
+def inner(a, b):
+    """
+    Returns the inner product of a and b for arrays of floating point types.
+
+    Like the generic NumPy equivalent the product sum is over the last dimension
+    of a and b. The first argument is not conjugated.
+
+    """
+    fa = filled(a, 0)
+    fb = filled(b, 0)
+    if fa.ndim == 0:
+        fa.shape = (1,)
+    if fb.ndim == 0:
+        fb.shape = (1,)
+    return np.inner(fa, fb).view(MaskedArray)
+inner.__doc__ = doc_note(np.inner.__doc__,
+                         "Masked values are replaced by 0.")
+innerproduct = inner
+
+
+def outer(a, b):
+    "maskedarray version of the numpy function."
+    fa = filled(a, 0).ravel()
+    fb = filled(b, 0).ravel()
+    d = np.outer(fa, fb)
+    ma = getmask(a)
+    mb = getmask(b)
+    if ma is nomask and mb is nomask:
+        return masked_array(d)
+    ma = getmaskarray(a)
+    mb = getmaskarray(b)
+    m = make_mask(1 - np.outer(1 - ma, 1 - mb), copy=False)
+    return masked_array(d, mask=m)
+outer.__doc__ = doc_note(np.outer.__doc__,
+                         "Masked values are replaced by 0.")
+outerproduct = outer
+
+
+def _convolve_or_correlate(f, a, v, mode, propagate_mask):
+    """
+    Helper function for ma.correlate and ma.convolve
+    """
+    if propagate_mask:
+        # results which are contributed to by either item in any pair being invalid
+        mask = (
+            f(getmaskarray(a), np.ones(np.shape(v), dtype=bool), mode=mode)
+          | f(np.ones(np.shape(a), dtype=bool), getmaskarray(v), mode=mode)
+        )
+        data = f(getdata(a), getdata(v), mode=mode)
+    else:
+        # results which are not contributed to by any pair of valid elements
+        mask = ~f(~getmaskarray(a), ~getmaskarray(v))
+        data = f(filled(a, 0), filled(v, 0), mode=mode)
+
+    return masked_array(data, mask=mask)
+
+
+def correlate(a, v, mode='valid', propagate_mask=True):
+    """
+    Cross-correlation of two 1-dimensional sequences.
+
+    Parameters
+    ----------
+    a, v : array_like
+        Input sequences.
+    mode : {'valid', 'same', 'full'}, optional
+        Refer to the `np.convolve` docstring.  Note that the default
+        is 'valid', unlike `convolve`, which uses 'full'.
+    propagate_mask : bool
+        If True, then a result element is masked if any masked element contributes towards it.
+        If False, then a result element is only masked if no non-masked element
+        contribute towards it
+
+    Returns
+    -------
+    out : MaskedArray
+        Discrete cross-correlation of `a` and `v`.
+
+    See Also
+    --------
+    numpy.correlate : Equivalent function in the top-level NumPy module.
+    """
+    return _convolve_or_correlate(np.correlate, a, v, mode, propagate_mask)
+
+
+def convolve(a, v, mode='full', propagate_mask=True):
+    """
+    Returns the discrete, linear convolution of two one-dimensional sequences.
+
+    Parameters
+    ----------
+    a, v : array_like
+        Input sequences.
+    mode : {'valid', 'same', 'full'}, optional
+        Refer to the `np.convolve` docstring.
+    propagate_mask : bool
+        If True, then if any masked element is included in the sum for a result
+        element, then the result is masked.
+        If False, then the result element is only masked if no non-masked cells
+        contribute towards it
+
+    Returns
+    -------
+    out : MaskedArray
+        Discrete, linear convolution of `a` and `v`.
+
+    See Also
+    --------
+    numpy.convolve : Equivalent function in the top-level NumPy module.
+    """
+    return _convolve_or_correlate(np.convolve, a, v, mode, propagate_mask)
+
+
+def allequal(a, b, fill_value=True):
+    """
+    Return True if all entries of a and b are equal, using
+    fill_value as a truth value where either or both are masked.
+
+    Parameters
+    ----------
+    a, b : array_like
+        Input arrays to compare.
+    fill_value : bool, optional
+        Whether masked values in a or b are considered equal (True) or not
+        (False).
+
+    Returns
+    -------
+    y : bool
+        Returns True if the two arrays are equal within the given
+        tolerance, False otherwise. If either array contains NaN,
+        then False is returned.
+
+    See Also
+    --------
+    all, any
+    numpy.ma.allclose
+
+    Examples
+    --------
+    >>> a = np.ma.array([1e10, 1e-7, 42.0], mask=[0, 0, 1])
+    >>> a
+    masked_array(data=[10000000000.0, 1e-07, --],
+                 mask=[False, False,  True],
+           fill_value=1e+20)
+
+    >>> b = np.array([1e10, 1e-7, -42.0])
+    >>> b
+    array([  1.00000000e+10,   1.00000000e-07,  -4.20000000e+01])
+    >>> np.ma.allequal(a, b, fill_value=False)
+    False
+    >>> np.ma.allequal(a, b)
+    True
+
+    """
+    m = mask_or(getmask(a), getmask(b))
+    if m is nomask:
+        x = getdata(a)
+        y = getdata(b)
+        d = umath.equal(x, y)
+        return d.all()
+    elif fill_value:
+        x = getdata(a)
+        y = getdata(b)
+        d = umath.equal(x, y)
+        dm = array(d, mask=m, copy=False)
+        return dm.filled(True).all(None)
+    else:
+        return False
+
+
+def allclose(a, b, masked_equal=True, rtol=1e-5, atol=1e-8):
+    """
+    Returns True if two arrays are element-wise equal within a tolerance.
+
+    This function is equivalent to `allclose` except that masked values
+    are treated as equal (default) or unequal, depending on the `masked_equal`
+    argument.
+
+    Parameters
+    ----------
+    a, b : array_like
+        Input arrays to compare.
+    masked_equal : bool, optional
+        Whether masked values in `a` and `b` are considered equal (True) or not
+        (False). They are considered equal by default.
+    rtol : float, optional
+        Relative tolerance. The relative difference is equal to ``rtol * b``.
+        Default is 1e-5.
+    atol : float, optional
+        Absolute tolerance. The absolute difference is equal to `atol`.
+        Default is 1e-8.
+
+    Returns
+    -------
+    y : bool
+        Returns True if the two arrays are equal within the given
+        tolerance, False otherwise. If either array contains NaN, then
+        False is returned.
+
+    See Also
+    --------
+    all, any
+    numpy.allclose : the non-masked `allclose`.
+
+    Notes
+    -----
+    If the following equation is element-wise True, then `allclose` returns
+    True::
+
+      absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`))
+
+    Return True if all elements of `a` and `b` are equal subject to
+    given tolerances.
+
+    Examples
+    --------
+    >>> a = np.ma.array([1e10, 1e-7, 42.0], mask=[0, 0, 1])
+    >>> a
+    masked_array(data=[10000000000.0, 1e-07, --],
+                 mask=[False, False,  True],
+           fill_value=1e+20)
+    >>> b = np.ma.array([1e10, 1e-8, -42.0], mask=[0, 0, 1])
+    >>> np.ma.allclose(a, b)
+    False
+
+    >>> a = np.ma.array([1e10, 1e-8, 42.0], mask=[0, 0, 1])
+    >>> b = np.ma.array([1.00001e10, 1e-9, -42.0], mask=[0, 0, 1])
+    >>> np.ma.allclose(a, b)
+    True
+    >>> np.ma.allclose(a, b, masked_equal=False)
+    False
+
+    Masked values are not compared directly.
+
+    >>> a = np.ma.array([1e10, 1e-8, 42.0], mask=[0, 0, 1])
+    >>> b = np.ma.array([1.00001e10, 1e-9, 42.0], mask=[0, 0, 1])
+    >>> np.ma.allclose(a, b)
+    True
+    >>> np.ma.allclose(a, b, masked_equal=False)
+    False
+
+    """
+    x = masked_array(a, copy=False)
+    y = masked_array(b, copy=False)
+
+    # make sure y is an inexact type to avoid abs(MIN_INT); will cause
+    # casting of x later.
+    # NOTE: We explicitly allow timedelta, which used to work. This could
+    #       possibly be deprecated. See also gh-18286.
+    #       timedelta works if `atol` is an integer or also a timedelta.
+    #       Although, the default tolerances are unlikely to be useful
+    if y.dtype.kind != "m":
+        dtype = np.result_type(y, 1.)
+        if y.dtype != dtype:
+            y = masked_array(y, dtype=dtype, copy=False)
+
+    m = mask_or(getmask(x), getmask(y))
+    xinf = np.isinf(masked_array(x, copy=False, mask=m)).filled(False)
+    # If we have some infs, they should fall at the same place.
+    if not np.all(xinf == filled(np.isinf(y), False)):
+        return False
+    # No infs at all
+    if not np.any(xinf):
+        d = filled(less_equal(absolute(x - y), atol + rtol * absolute(y)),
+                   masked_equal)
+        return np.all(d)
+
+    if not np.all(filled(x[xinf] == y[xinf], masked_equal)):
+        return False
+    x = x[~xinf]
+    y = y[~xinf]
+
+    d = filled(less_equal(absolute(x - y), atol + rtol * absolute(y)),
+               masked_equal)
+
+    return np.all(d)
+
+
+def asarray(a, dtype=None, order=None):
+    """
+    Convert the input to a masked array of the given data-type.
+
+    No copy is performed if the input is already an `ndarray`. If `a` is
+    a subclass of `MaskedArray`, a base class `MaskedArray` is returned.
+
+    Parameters
+    ----------
+    a : array_like
+        Input data, in any form that can be converted to a masked array. This
+        includes lists, lists of tuples, tuples, tuples of tuples, tuples
+        of lists, ndarrays and masked arrays.
+    dtype : dtype, optional
+        By default, the data-type is inferred from the input data.
+    order : {'C', 'F'}, optional
+        Whether to use row-major ('C') or column-major ('FORTRAN') memory
+        representation.  Default is 'C'.
+
+    Returns
+    -------
+    out : MaskedArray
+        Masked array interpretation of `a`.
+
+    See Also
+    --------
+    asanyarray : Similar to `asarray`, but conserves subclasses.
+
+    Examples
+    --------
+    >>> x = np.arange(10.).reshape(2, 5)
+    >>> x
+    array([[0., 1., 2., 3., 4.],
+           [5., 6., 7., 8., 9.]])
+    >>> np.ma.asarray(x)
+    masked_array(
+      data=[[0., 1., 2., 3., 4.],
+            [5., 6., 7., 8., 9.]],
+      mask=False,
+      fill_value=1e+20)
+    >>> type(np.ma.asarray(x))
+    
+
+    """
+    order = order or 'C'
+    return masked_array(a, dtype=dtype, copy=False, keep_mask=True,
+                        subok=False, order=order)
+
+
+def asanyarray(a, dtype=None):
+    """
+    Convert the input to a masked array, conserving subclasses.
+
+    If `a` is a subclass of `MaskedArray`, its class is conserved.
+    No copy is performed if the input is already an `ndarray`.
+
+    Parameters
+    ----------
+    a : array_like
+        Input data, in any form that can be converted to an array.
+    dtype : dtype, optional
+        By default, the data-type is inferred from the input data.
+    order : {'C', 'F'}, optional
+        Whether to use row-major ('C') or column-major ('FORTRAN') memory
+        representation.  Default is 'C'.
+
+    Returns
+    -------
+    out : MaskedArray
+        MaskedArray interpretation of `a`.
+
+    See Also
+    --------
+    asarray : Similar to `asanyarray`, but does not conserve subclass.
+
+    Examples
+    --------
+    >>> x = np.arange(10.).reshape(2, 5)
+    >>> x
+    array([[0., 1., 2., 3., 4.],
+           [5., 6., 7., 8., 9.]])
+    >>> np.ma.asanyarray(x)
+    masked_array(
+      data=[[0., 1., 2., 3., 4.],
+            [5., 6., 7., 8., 9.]],
+      mask=False,
+      fill_value=1e+20)
+    >>> type(np.ma.asanyarray(x))
+    
+
+    """
+    # workaround for #8666, to preserve identity. Ideally the bottom line
+    # would handle this for us.
+    if isinstance(a, MaskedArray) and (dtype is None or dtype == a.dtype):
+        return a
+    return masked_array(a, dtype=dtype, copy=False, keep_mask=True, subok=True)
+
+
+##############################################################################
+#                               Pickling                                     #
+##############################################################################
+
+
+def fromfile(file, dtype=float, count=-1, sep=''):
+    raise NotImplementedError(
+        "fromfile() not yet implemented for a MaskedArray.")
+
+
+def fromflex(fxarray):
+    """
+    Build a masked array from a suitable flexible-type array.
+
+    The input array has to have a data-type with ``_data`` and ``_mask``
+    fields. This type of array is output by `MaskedArray.toflex`.
+
+    Parameters
+    ----------
+    fxarray : ndarray
+        The structured input array, containing ``_data`` and ``_mask``
+        fields. If present, other fields are discarded.
+
+    Returns
+    -------
+    result : MaskedArray
+        The constructed masked array.
+
+    See Also
+    --------
+    MaskedArray.toflex : Build a flexible-type array from a masked array.
+
+    Examples
+    --------
+    >>> x = np.ma.array(np.arange(9).reshape(3, 3), mask=[0] + [1, 0] * 4)
+    >>> rec = x.toflex()
+    >>> rec
+    array([[(0, False), (1,  True), (2, False)],
+           [(3,  True), (4, False), (5,  True)],
+           [(6, False), (7,  True), (8, False)]],
+          dtype=[('_data', '>> x2 = np.ma.fromflex(rec)
+    >>> x2
+    masked_array(
+      data=[[0, --, 2],
+            [--, 4, --],
+            [6, --, 8]],
+      mask=[[False,  True, False],
+            [ True, False,  True],
+            [False,  True, False]],
+      fill_value=999999)
+
+    Extra fields can be present in the structured array but are discarded:
+
+    >>> dt = [('_data', '>> rec2 = np.zeros((2, 2), dtype=dt)
+    >>> rec2
+    array([[(0, False, 0.), (0, False, 0.)],
+           [(0, False, 0.), (0, False, 0.)]],
+          dtype=[('_data', '>> y = np.ma.fromflex(rec2)
+    >>> y
+    masked_array(
+      data=[[0, 0],
+            [0, 0]],
+      mask=[[False, False],
+            [False, False]],
+      fill_value=999999,
+      dtype=int32)
+
+    """
+    return masked_array(fxarray['_data'], mask=fxarray['_mask'])
+
+
+class _convert2ma:
+
+    """
+    Convert functions from numpy to numpy.ma.
+
+    Parameters
+    ----------
+        _methodname : string
+            Name of the method to transform.
+
+    """
+    __doc__ = None
+
+    def __init__(self, funcname, np_ret, np_ma_ret, params=None):
+        self._func = getattr(np, funcname)
+        self.__doc__ = self.getdoc(np_ret, np_ma_ret)
+        self._extras = params or {}
+
+    def getdoc(self, np_ret, np_ma_ret):
+        "Return the doc of the function (from the doc of the method)."
+        doc = getattr(self._func, '__doc__', None)
+        sig = get_object_signature(self._func)
+        if doc:
+            doc = self._replace_return_type(doc, np_ret, np_ma_ret)
+            # Add the signature of the function at the beginning of the doc
+            if sig:
+                sig = "%s%s\n" % (self._func.__name__, sig)
+            doc = sig + doc
+        return doc
+
+    def _replace_return_type(self, doc, np_ret, np_ma_ret):
+        """
+        Replace documentation of ``np`` function's return type.
+
+        Replaces it with the proper type for the ``np.ma`` function.
+
+        Parameters
+        ----------
+        doc : str
+            The documentation of the ``np`` method.
+        np_ret : str
+            The return type string of the ``np`` method that we want to
+            replace. (e.g. "out : ndarray")
+        np_ma_ret : str
+            The return type string of the ``np.ma`` method.
+            (e.g. "out : MaskedArray")
+        """
+        if np_ret not in doc:
+            raise RuntimeError(
+                f"Failed to replace `{np_ret}` with `{np_ma_ret}`. "
+                f"The documentation string for return type, {np_ret}, is not "
+                f"found in the docstring for `np.{self._func.__name__}`. "
+                f"Fix the docstring for `np.{self._func.__name__}` or "
+                "update the expected string for return type."
+            )
+
+        return doc.replace(np_ret, np_ma_ret)
+
+    def __call__(self, *args, **params):
+        # Find the common parameters to the call and the definition
+        _extras = self._extras
+        common_params = set(params).intersection(_extras)
+        # Drop the common parameters from the call
+        for p in common_params:
+            _extras[p] = params.pop(p)
+        # Get the result
+        result = self._func.__call__(*args, **params).view(MaskedArray)
+        if "fill_value" in common_params:
+            result.fill_value = _extras.get("fill_value", None)
+        if "hardmask" in common_params:
+            result._hardmask = bool(_extras.get("hard_mask", False))
+        return result
+
+
+arange = _convert2ma(
+    'arange',
+    params=dict(fill_value=None, hardmask=False),
+    np_ret='arange : ndarray',
+    np_ma_ret='arange : MaskedArray',
+)
+clip = _convert2ma(
+    'clip',
+    params=dict(fill_value=None, hardmask=False),
+    np_ret='clipped_array : ndarray',
+    np_ma_ret='clipped_array : MaskedArray',
+)
+empty = _convert2ma(
+    'empty',
+    params=dict(fill_value=None, hardmask=False),
+    np_ret='out : ndarray',
+    np_ma_ret='out : MaskedArray',
+)
+empty_like = _convert2ma(
+    'empty_like',
+    np_ret='out : ndarray',
+    np_ma_ret='out : MaskedArray',
+)
+frombuffer = _convert2ma(
+    'frombuffer',
+    np_ret='out : ndarray',
+    np_ma_ret='out: MaskedArray',
+)
+fromfunction = _convert2ma(
+   'fromfunction',
+   np_ret='fromfunction : any',
+   np_ma_ret='fromfunction: MaskedArray',
+)
+identity = _convert2ma(
+    'identity',
+    params=dict(fill_value=None, hardmask=False),
+    np_ret='out : ndarray',
+    np_ma_ret='out : MaskedArray',
+)
+indices = _convert2ma(
+    'indices',
+    params=dict(fill_value=None, hardmask=False),
+    np_ret='grid : one ndarray or tuple of ndarrays',
+    np_ma_ret='grid : one MaskedArray or tuple of MaskedArrays',
+)
+ones = _convert2ma(
+    'ones',
+    params=dict(fill_value=None, hardmask=False),
+    np_ret='out : ndarray',
+    np_ma_ret='out : MaskedArray',
+)
+ones_like = _convert2ma(
+    'ones_like',
+    np_ret='out : ndarray',
+    np_ma_ret='out : MaskedArray',
+)
+squeeze = _convert2ma(
+    'squeeze',
+    params=dict(fill_value=None, hardmask=False),
+    np_ret='squeezed : ndarray',
+    np_ma_ret='squeezed : MaskedArray',
+)
+zeros = _convert2ma(
+    'zeros',
+    params=dict(fill_value=None, hardmask=False),
+    np_ret='out : ndarray',
+    np_ma_ret='out : MaskedArray',
+)
+zeros_like = _convert2ma(
+    'zeros_like',
+    np_ret='out : ndarray',
+    np_ma_ret='out : MaskedArray',
+)
+
+
+def append(a, b, axis=None):
+    """Append values to the end of an array.
+
+    .. versionadded:: 1.9.0
+
+    Parameters
+    ----------
+    a : array_like
+        Values are appended to a copy of this array.
+    b : array_like
+        These values are appended to a copy of `a`.  It must be of the
+        correct shape (the same shape as `a`, excluding `axis`).  If `axis`
+        is not specified, `b` can be any shape and will be flattened
+        before use.
+    axis : int, optional
+        The axis along which `v` are appended.  If `axis` is not given,
+        both `a` and `b` are flattened before use.
+
+    Returns
+    -------
+    append : MaskedArray
+        A copy of `a` with `b` appended to `axis`.  Note that `append`
+        does not occur in-place: a new array is allocated and filled.  If
+        `axis` is None, the result is a flattened array.
+
+    See Also
+    --------
+    numpy.append : Equivalent function in the top-level NumPy module.
+
+    Examples
+    --------
+    >>> import numpy.ma as ma
+    >>> a = ma.masked_values([1, 2, 3], 2)
+    >>> b = ma.masked_values([[4, 5, 6], [7, 8, 9]], 7)
+    >>> ma.append(a, b)
+    masked_array(data=[1, --, 3, 4, 5, 6, --, 8, 9],
+                 mask=[False,  True, False, False, False, False,  True, False,
+                       False],
+           fill_value=999999)
+    """
+    return concatenate([a, b], axis)
diff --git a/venv/lib/python3.10/site-packages/numpy/ma/core.pyi b/venv/lib/python3.10/site-packages/numpy/ma/core.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..e94ebce3c31a00094f4a04953f1716f46c13d8d0
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/numpy/ma/core.pyi
@@ -0,0 +1,471 @@
+from collections.abc import Callable
+from typing import Any, TypeVar
+from numpy import ndarray, dtype, float64
+
+from numpy import (
+    amax as amax,
+    amin as amin,
+    bool_ as bool_,
+    expand_dims as expand_dims,
+    clip as clip,
+    indices as indices,
+    ones_like as ones_like,
+    squeeze as squeeze,
+    zeros_like as zeros_like,
+)
+
+from numpy.lib.function_base import (
+    angle as angle,
+)
+
+# TODO: Set the `bound` to something more suitable once we
+# have proper shape support
+_ShapeType = TypeVar("_ShapeType", bound=Any)
+_DType_co = TypeVar("_DType_co", bound=dtype[Any], covariant=True)
+
+__all__: list[str]
+
+MaskType = bool_
+nomask: bool_
+
+class MaskedArrayFutureWarning(FutureWarning): ...
+class MAError(Exception): ...
+class MaskError(MAError): ...
+
+def default_fill_value(obj): ...
+def minimum_fill_value(obj): ...
+def maximum_fill_value(obj): ...
+def set_fill_value(a, fill_value): ...
+def common_fill_value(a, b): ...
+def filled(a, fill_value=...): ...
+def getdata(a, subok=...): ...
+get_data = getdata
+
+def fix_invalid(a, mask=..., copy=..., fill_value=...): ...
+
+class _MaskedUFunc:
+    f: Any
+    __doc__: Any
+    __name__: Any
+    def __init__(self, ufunc): ...
+
+class _MaskedUnaryOperation(_MaskedUFunc):
+    fill: Any
+    domain: Any
+    def __init__(self, mufunc, fill=..., domain=...): ...
+    def __call__(self, a, *args, **kwargs): ...
+
+class _MaskedBinaryOperation(_MaskedUFunc):
+    fillx: Any
+    filly: Any
+    def __init__(self, mbfunc, fillx=..., filly=...): ...
+    def __call__(self, a, b, *args, **kwargs): ...
+    def reduce(self, target, axis=..., dtype=...): ...
+    def outer(self, a, b): ...
+    def accumulate(self, target, axis=...): ...
+
+class _DomainedBinaryOperation(_MaskedUFunc):
+    domain: Any
+    fillx: Any
+    filly: Any
+    def __init__(self, dbfunc, domain, fillx=..., filly=...): ...
+    def __call__(self, a, b, *args, **kwargs): ...
+
+exp: _MaskedUnaryOperation
+conjugate: _MaskedUnaryOperation
+sin: _MaskedUnaryOperation
+cos: _MaskedUnaryOperation
+arctan: _MaskedUnaryOperation
+arcsinh: _MaskedUnaryOperation
+sinh: _MaskedUnaryOperation
+cosh: _MaskedUnaryOperation
+tanh: _MaskedUnaryOperation
+abs: _MaskedUnaryOperation
+absolute: _MaskedUnaryOperation
+fabs: _MaskedUnaryOperation
+negative: _MaskedUnaryOperation
+floor: _MaskedUnaryOperation
+ceil: _MaskedUnaryOperation
+around: _MaskedUnaryOperation
+logical_not: _MaskedUnaryOperation
+sqrt: _MaskedUnaryOperation
+log: _MaskedUnaryOperation
+log2: _MaskedUnaryOperation
+log10: _MaskedUnaryOperation
+tan: _MaskedUnaryOperation
+arcsin: _MaskedUnaryOperation
+arccos: _MaskedUnaryOperation
+arccosh: _MaskedUnaryOperation
+arctanh: _MaskedUnaryOperation
+
+add: _MaskedBinaryOperation
+subtract: _MaskedBinaryOperation
+multiply: _MaskedBinaryOperation
+arctan2: _MaskedBinaryOperation
+equal: _MaskedBinaryOperation
+not_equal: _MaskedBinaryOperation
+less_equal: _MaskedBinaryOperation
+greater_equal: _MaskedBinaryOperation
+less: _MaskedBinaryOperation
+greater: _MaskedBinaryOperation
+logical_and: _MaskedBinaryOperation
+alltrue: _MaskedBinaryOperation
+logical_or: _MaskedBinaryOperation
+sometrue: Callable[..., Any]
+logical_xor: _MaskedBinaryOperation
+bitwise_and: _MaskedBinaryOperation
+bitwise_or: _MaskedBinaryOperation
+bitwise_xor: _MaskedBinaryOperation
+hypot: _MaskedBinaryOperation
+divide: _MaskedBinaryOperation
+true_divide: _MaskedBinaryOperation
+floor_divide: _MaskedBinaryOperation
+remainder: _MaskedBinaryOperation
+fmod: _MaskedBinaryOperation
+mod: _MaskedBinaryOperation
+
+def make_mask_descr(ndtype): ...
+def getmask(a): ...
+get_mask = getmask
+
+def getmaskarray(arr): ...
+def is_mask(m): ...
+def make_mask(m, copy=..., shrink=..., dtype=...): ...
+def make_mask_none(newshape, dtype=...): ...
+def mask_or(m1, m2, copy=..., shrink=...): ...
+def flatten_mask(mask): ...
+def masked_where(condition, a, copy=...): ...
+def masked_greater(x, value, copy=...): ...
+def masked_greater_equal(x, value, copy=...): ...
+def masked_less(x, value, copy=...): ...
+def masked_less_equal(x, value, copy=...): ...
+def masked_not_equal(x, value, copy=...): ...
+def masked_equal(x, value, copy=...): ...
+def masked_inside(x, v1, v2, copy=...): ...
+def masked_outside(x, v1, v2, copy=...): ...
+def masked_object(x, value, copy=..., shrink=...): ...
+def masked_values(x, value, rtol=..., atol=..., copy=..., shrink=...): ...
+def masked_invalid(a, copy=...): ...
+
+class _MaskedPrintOption:
+    def __init__(self, display): ...
+    def display(self): ...
+    def set_display(self, s): ...
+    def enabled(self): ...
+    def enable(self, shrink=...): ...
+
+masked_print_option: _MaskedPrintOption
+
+def flatten_structured_array(a): ...
+
+class MaskedIterator:
+    ma: Any
+    dataiter: Any
+    maskiter: Any
+    def __init__(self, ma): ...
+    def __iter__(self): ...
+    def __getitem__(self, indx): ...
+    def __setitem__(self, index, value): ...
+    def __next__(self): ...
+
+class MaskedArray(ndarray[_ShapeType, _DType_co]):
+    __array_priority__: Any
+    def __new__(cls, data=..., mask=..., dtype=..., copy=..., subok=..., ndmin=..., fill_value=..., keep_mask=..., hard_mask=..., shrink=..., order=...): ...
+    def __array_finalize__(self, obj): ...
+    def __array_wrap__(self, obj, context=...): ...
+    def view(self, dtype=..., type=..., fill_value=...): ...
+    def __getitem__(self, indx): ...
+    def __setitem__(self, indx, value): ...
+    @property
+    def dtype(self): ...
+    @dtype.setter
+    def dtype(self, dtype): ...
+    @property
+    def shape(self): ...
+    @shape.setter
+    def shape(self, shape): ...
+    def __setmask__(self, mask, copy=...): ...
+    @property
+    def mask(self): ...
+    @mask.setter
+    def mask(self, value): ...
+    @property
+    def recordmask(self): ...
+    @recordmask.setter
+    def recordmask(self, mask): ...
+    def harden_mask(self): ...
+    def soften_mask(self): ...
+    @property
+    def hardmask(self): ...
+    def unshare_mask(self): ...
+    @property
+    def sharedmask(self): ...
+    def shrink_mask(self): ...
+    @property
+    def baseclass(self): ...
+    data: Any
+    @property
+    def flat(self): ...
+    @flat.setter
+    def flat(self, value): ...
+    @property
+    def fill_value(self): ...
+    @fill_value.setter
+    def fill_value(self, value=...): ...
+    get_fill_value: Any
+    set_fill_value: Any
+    def filled(self, fill_value=...): ...
+    def compressed(self): ...
+    def compress(self, condition, axis=..., out=...): ...
+    def __eq__(self, other): ...
+    def __ne__(self, other): ...
+    def __ge__(self, other): ...
+    def __gt__(self, other): ...
+    def __le__(self, other): ...
+    def __lt__(self, other): ...
+    def __add__(self, other): ...
+    def __radd__(self, other): ...
+    def __sub__(self, other): ...
+    def __rsub__(self, other): ...
+    def __mul__(self, other): ...
+    def __rmul__(self, other): ...
+    def __div__(self, other): ...
+    def __truediv__(self, other): ...
+    def __rtruediv__(self, other): ...
+    def __floordiv__(self, other): ...
+    def __rfloordiv__(self, other): ...
+    def __pow__(self, other): ...
+    def __rpow__(self, other): ...
+    def __iadd__(self, other): ...
+    def __isub__(self, other): ...
+    def __imul__(self, other): ...
+    def __idiv__(self, other): ...
+    def __ifloordiv__(self, other): ...
+    def __itruediv__(self, other): ...
+    def __ipow__(self, other): ...
+    def __float__(self): ...
+    def __int__(self): ...
+    @property  # type: ignore[misc]
+    def imag(self): ...
+    get_imag: Any
+    @property  # type: ignore[misc]
+    def real(self): ...
+    get_real: Any
+    def count(self, axis=..., keepdims=...): ...
+    def ravel(self, order=...): ...
+    def reshape(self, *s, **kwargs): ...
+    def resize(self, newshape, refcheck=..., order=...): ...
+    def put(self, indices, values, mode=...): ...
+    def ids(self): ...
+    def iscontiguous(self): ...
+    def all(self, axis=..., out=..., keepdims=...): ...
+    def any(self, axis=..., out=..., keepdims=...): ...
+    def nonzero(self): ...
+    def trace(self, offset=..., axis1=..., axis2=..., dtype=..., out=...): ...
+    def dot(self, b, out=..., strict=...): ...
+    def sum(self, axis=..., dtype=..., out=..., keepdims=...): ...
+    def cumsum(self, axis=..., dtype=..., out=...): ...
+    def prod(self, axis=..., dtype=..., out=..., keepdims=...): ...
+    product: Any
+    def cumprod(self, axis=..., dtype=..., out=...): ...
+    def mean(self, axis=..., dtype=..., out=..., keepdims=...): ...
+    def anom(self, axis=..., dtype=...): ...
+    def var(self, axis=..., dtype=..., out=..., ddof=..., keepdims=...): ...
+    def std(self, axis=..., dtype=..., out=..., ddof=..., keepdims=...): ...
+    def round(self, decimals=..., out=...): ...
+    def argsort(self, axis=..., kind=..., order=..., endwith=..., fill_value=...): ...
+    def argmin(self, axis=..., fill_value=..., out=..., *, keepdims=...): ...
+    def argmax(self, axis=..., fill_value=..., out=..., *, keepdims=...): ...
+    def sort(self, axis=..., kind=..., order=..., endwith=..., fill_value=...): ...
+    def min(self, axis=..., out=..., fill_value=..., keepdims=...): ...
+    # NOTE: deprecated
+    # def tostring(self, fill_value=..., order=...): ...
+    def max(self, axis=..., out=..., fill_value=..., keepdims=...): ...
+    def ptp(self, axis=..., out=..., fill_value=..., keepdims=...): ...
+    def partition(self, *args, **kwargs): ...
+    def argpartition(self, *args, **kwargs): ...
+    def take(self, indices, axis=..., out=..., mode=...): ...
+    copy: Any
+    diagonal: Any
+    flatten: Any
+    repeat: Any
+    squeeze: Any
+    swapaxes: Any
+    T: Any
+    transpose: Any
+    def tolist(self, fill_value=...): ...
+    def tobytes(self, fill_value=..., order=...): ...
+    def tofile(self, fid, sep=..., format=...): ...
+    def toflex(self): ...
+    torecords: Any
+    def __reduce__(self): ...
+    def __deepcopy__(self, memo=...): ...
+
+class mvoid(MaskedArray[_ShapeType, _DType_co]):
+    def __new__(
+        self,
+        data,
+        mask=...,
+        dtype=...,
+        fill_value=...,
+        hardmask=...,
+        copy=...,
+        subok=...,
+    ): ...
+    def __getitem__(self, indx): ...
+    def __setitem__(self, indx, value): ...
+    def __iter__(self): ...
+    def __len__(self): ...
+    def filled(self, fill_value=...): ...
+    def tolist(self): ...
+
+def isMaskedArray(x): ...
+isarray = isMaskedArray
+isMA = isMaskedArray
+
+# 0D float64 array
+class MaskedConstant(MaskedArray[Any, dtype[float64]]):
+    def __new__(cls): ...
+    __class__: Any
+    def __array_finalize__(self, obj): ...
+    def __array_prepare__(self, obj, context=...): ...
+    def __array_wrap__(self, obj, context=...): ...
+    def __format__(self, format_spec): ...
+    def __reduce__(self): ...
+    def __iop__(self, other): ...
+    __iadd__: Any
+    __isub__: Any
+    __imul__: Any
+    __ifloordiv__: Any
+    __itruediv__: Any
+    __ipow__: Any
+    def copy(self, *args, **kwargs): ...
+    def __copy__(self): ...
+    def __deepcopy__(self, memo): ...
+    def __setattr__(self, attr, value): ...
+
+masked: MaskedConstant
+masked_singleton: MaskedConstant
+masked_array = MaskedArray
+
+def array(
+    data,
+    dtype=...,
+    copy=...,
+    order=...,
+    mask=...,
+    fill_value=...,
+    keep_mask=...,
+    hard_mask=...,
+    shrink=...,
+    subok=...,
+    ndmin=...,
+): ...
+def is_masked(x): ...
+
+class _extrema_operation(_MaskedUFunc):
+    compare: Any
+    fill_value_func: Any
+    def __init__(self, ufunc, compare, fill_value): ...
+    # NOTE: in practice `b` has a default value, but users should
+    # explicitly provide a value here as the default is deprecated
+    def __call__(self, a, b): ...
+    def reduce(self, target, axis=...): ...
+    def outer(self, a, b): ...
+
+def min(obj, axis=..., out=..., fill_value=..., keepdims=...): ...
+def max(obj, axis=..., out=..., fill_value=..., keepdims=...): ...
+def ptp(obj, axis=..., out=..., fill_value=..., keepdims=...): ...
+
+class _frommethod:
+    __name__: Any
+    __doc__: Any
+    reversed: Any
+    def __init__(self, methodname, reversed=...): ...
+    def getdoc(self): ...
+    def __call__(self, a, *args, **params): ...
+
+all: _frommethod
+anomalies: _frommethod
+anom: _frommethod
+any: _frommethod
+compress: _frommethod
+cumprod: _frommethod
+cumsum: _frommethod
+copy: _frommethod
+diagonal: _frommethod
+harden_mask: _frommethod
+ids: _frommethod
+mean: _frommethod
+nonzero: _frommethod
+prod: _frommethod
+product: _frommethod
+ravel: _frommethod
+repeat: _frommethod
+soften_mask: _frommethod
+std: _frommethod
+sum: _frommethod
+swapaxes: _frommethod
+trace: _frommethod
+var: _frommethod
+count: _frommethod
+argmin: _frommethod
+argmax: _frommethod
+
+minimum: _extrema_operation
+maximum: _extrema_operation
+
+def take(a, indices, axis=..., out=..., mode=...): ...
+def power(a, b, third=...): ...
+def argsort(a, axis=..., kind=..., order=..., endwith=..., fill_value=...): ...
+def sort(a, axis=..., kind=..., order=..., endwith=..., fill_value=...): ...
+def compressed(x): ...
+def concatenate(arrays, axis=...): ...
+def diag(v, k=...): ...
+def left_shift(a, n): ...
+def right_shift(a, n): ...
+def put(a, indices, values, mode=...): ...
+def putmask(a, mask, values): ...
+def transpose(a, axes=...): ...
+def reshape(a, new_shape, order=...): ...
+def resize(x, new_shape): ...
+def ndim(obj): ...
+def shape(obj): ...
+def size(obj, axis=...): ...
+def diff(a, /, n=..., axis=..., prepend=..., append=...): ...
+def where(condition, x=..., y=...): ...
+def choose(indices, choices, out=..., mode=...): ...
+def round(a, decimals=..., out=...): ...
+
+def inner(a, b): ...
+innerproduct = inner
+
+def outer(a, b): ...
+outerproduct = outer
+
+def correlate(a, v, mode=..., propagate_mask=...): ...
+def convolve(a, v, mode=..., propagate_mask=...): ...
+def allequal(a, b, fill_value=...): ...
+def allclose(a, b, masked_equal=..., rtol=..., atol=...): ...
+def asarray(a, dtype=..., order=...): ...
+def asanyarray(a, dtype=...): ...
+def fromflex(fxarray): ...
+
+class _convert2ma:
+    __doc__: Any
+    def __init__(self, funcname, params=...): ...
+    def getdoc(self): ...
+    def __call__(self, *args, **params): ...
+
+arange: _convert2ma
+empty: _convert2ma
+empty_like: _convert2ma
+frombuffer: _convert2ma
+fromfunction: _convert2ma
+identity: _convert2ma
+ones: _convert2ma
+zeros: _convert2ma
+
+def append(a, b, axis=...): ...
+def dot(a, b, strict=..., out=...): ...
+def mask_rowcols(a, axis=...): ...
diff --git a/venv/lib/python3.10/site-packages/numpy/ma/extras.pyi b/venv/lib/python3.10/site-packages/numpy/ma/extras.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..56228b927080a3963159206a9afc830d6d7335cc
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/numpy/ma/extras.pyi
@@ -0,0 +1,85 @@
+from typing import Any
+from numpy.lib.index_tricks import AxisConcatenator
+
+from numpy.ma.core import (
+    dot as dot,
+    mask_rowcols as mask_rowcols,
+)
+
+__all__: list[str]
+
+def count_masked(arr, axis=...): ...
+def masked_all(shape, dtype = ...): ...
+def masked_all_like(arr): ...
+
+class _fromnxfunction:
+    __name__: Any
+    __doc__: Any
+    def __init__(self, funcname): ...
+    def getdoc(self): ...
+    def __call__(self, *args, **params): ...
+
+class _fromnxfunction_single(_fromnxfunction):
+    def __call__(self, x, *args, **params): ...
+
+class _fromnxfunction_seq(_fromnxfunction):
+    def __call__(self, x, *args, **params): ...
+
+class _fromnxfunction_allargs(_fromnxfunction):
+    def __call__(self, *args, **params): ...
+
+atleast_1d: _fromnxfunction_allargs
+atleast_2d: _fromnxfunction_allargs
+atleast_3d: _fromnxfunction_allargs
+
+vstack: _fromnxfunction_seq
+row_stack: _fromnxfunction_seq
+hstack: _fromnxfunction_seq
+column_stack: _fromnxfunction_seq
+dstack: _fromnxfunction_seq
+stack: _fromnxfunction_seq
+
+hsplit: _fromnxfunction_single
+diagflat: _fromnxfunction_single
+
+def apply_along_axis(func1d, axis, arr, *args, **kwargs): ...
+def apply_over_axes(func, a, axes): ...
+def average(a, axis=..., weights=..., returned=..., keepdims=...): ...
+def median(a, axis=..., out=..., overwrite_input=..., keepdims=...): ...
+def compress_nd(x, axis=...): ...
+def compress_rowcols(x, axis=...): ...
+def compress_rows(a): ...
+def compress_cols(a): ...
+def mask_rows(a, axis = ...): ...
+def mask_cols(a, axis = ...): ...
+def ediff1d(arr, to_end=..., to_begin=...): ...
+def unique(ar1, return_index=..., return_inverse=...): ...
+def intersect1d(ar1, ar2, assume_unique=...): ...
+def setxor1d(ar1, ar2, assume_unique=...): ...
+def in1d(ar1, ar2, assume_unique=..., invert=...): ...
+def isin(element, test_elements, assume_unique=..., invert=...): ...
+def union1d(ar1, ar2): ...
+def setdiff1d(ar1, ar2, assume_unique=...): ...
+def cov(x, y=..., rowvar=..., bias=..., allow_masked=..., ddof=...): ...
+def corrcoef(x, y=..., rowvar=..., bias = ..., allow_masked=..., ddof = ...): ...
+
+class MAxisConcatenator(AxisConcatenator):
+    concatenate: Any
+    @classmethod
+    def makemat(cls, arr): ...
+    def __getitem__(self, key): ...
+
+class mr_class(MAxisConcatenator):
+    def __init__(self): ...
+
+mr_: mr_class
+
+def ndenumerate(a, compressed=...): ...
+def flatnotmasked_edges(a): ...
+def notmasked_edges(a, axis=...): ...
+def flatnotmasked_contiguous(a): ...
+def notmasked_contiguous(a, axis=...): ...
+def clump_unmasked(a): ...
+def clump_masked(a): ...
+def vander(x, n=...): ...
+def polyfit(x, y, deg, rcond=..., full=..., w=..., cov=...): ...
diff --git a/venv/lib/python3.10/site-packages/numpy/ma/mrecords.pyi b/venv/lib/python3.10/site-packages/numpy/ma/mrecords.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..264807e05d57e03e2f8b71d2db2677d8a68ab17e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/numpy/ma/mrecords.pyi
@@ -0,0 +1,90 @@
+from typing import Any, TypeVar
+
+from numpy import dtype
+from numpy.ma import MaskedArray
+
+__all__: list[str]
+
+# TODO: Set the `bound` to something more suitable once we
+# have proper shape support
+_ShapeType = TypeVar("_ShapeType", bound=Any)
+_DType_co = TypeVar("_DType_co", bound=dtype[Any], covariant=True)
+
+class MaskedRecords(MaskedArray[_ShapeType, _DType_co]):
+    def __new__(
+        cls,
+        shape,
+        dtype=...,
+        buf=...,
+        offset=...,
+        strides=...,
+        formats=...,
+        names=...,
+        titles=...,
+        byteorder=...,
+        aligned=...,
+        mask=...,
+        hard_mask=...,
+        fill_value=...,
+        keep_mask=...,
+        copy=...,
+        **options,
+    ): ...
+    _mask: Any
+    _fill_value: Any
+    @property
+    def _data(self): ...
+    @property
+    def _fieldmask(self): ...
+    def __array_finalize__(self, obj): ...
+    def __len__(self): ...
+    def __getattribute__(self, attr): ...
+    def __setattr__(self, attr, val): ...
+    def __getitem__(self, indx): ...
+    def __setitem__(self, indx, value): ...
+    def view(self, dtype=..., type=...): ...
+    def harden_mask(self): ...
+    def soften_mask(self): ...
+    def copy(self): ...
+    def tolist(self, fill_value=...): ...
+    def __reduce__(self): ...
+
+mrecarray = MaskedRecords
+
+def fromarrays(
+    arraylist,
+    dtype=...,
+    shape=...,
+    formats=...,
+    names=...,
+    titles=...,
+    aligned=...,
+    byteorder=...,
+    fill_value=...,
+): ...
+
+def fromrecords(
+    reclist,
+    dtype=...,
+    shape=...,
+    formats=...,
+    names=...,
+    titles=...,
+    aligned=...,
+    byteorder=...,
+    fill_value=...,
+    mask=...,
+): ...
+
+def fromtextfile(
+    fname,
+    delimiter=...,
+    commentchar=...,
+    missingchar=...,
+    varnames=...,
+    vartypes=...,
+    # NOTE: deprecated: NumPy 1.22.0, 2021-09-23
+    # delimitor=...,
+): ...
+
+def addfield(mrecord, newfield, newfieldname=...): ...
diff --git a/venv/lib/python3.10/site-packages/numpy/ma/tests/__init__.py b/venv/lib/python3.10/site-packages/numpy/ma/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/venv/lib/python3.10/site-packages/numpy/ma/tests/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/numpy/ma/tests/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..04805c2ee13a9056fad3b3f4647383a78690e1ef
Binary files /dev/null and b/venv/lib/python3.10/site-packages/numpy/ma/tests/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/numpy/ma/tests/__pycache__/test_core.cpython-310.pyc b/venv/lib/python3.10/site-packages/numpy/ma/tests/__pycache__/test_core.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..896a7cd396039d02cb3bb1768ea1ed9b06b764ad
Binary files /dev/null and b/venv/lib/python3.10/site-packages/numpy/ma/tests/__pycache__/test_core.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/numpy/ma/tests/__pycache__/test_deprecations.cpython-310.pyc b/venv/lib/python3.10/site-packages/numpy/ma/tests/__pycache__/test_deprecations.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c8373814f852aa3bbd7fb2e206adcbe0719b8984
Binary files /dev/null and b/venv/lib/python3.10/site-packages/numpy/ma/tests/__pycache__/test_deprecations.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/numpy/ma/tests/__pycache__/test_extras.cpython-310.pyc b/venv/lib/python3.10/site-packages/numpy/ma/tests/__pycache__/test_extras.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..687306df1b9707398601cd02fc4c4ca3a37fc72f
Binary files /dev/null and b/venv/lib/python3.10/site-packages/numpy/ma/tests/__pycache__/test_extras.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/numpy/ma/tests/__pycache__/test_mrecords.cpython-310.pyc b/venv/lib/python3.10/site-packages/numpy/ma/tests/__pycache__/test_mrecords.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d3ec334392081a3fdec08bd7a526b63defe188b5
Binary files /dev/null and b/venv/lib/python3.10/site-packages/numpy/ma/tests/__pycache__/test_mrecords.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/numpy/ma/tests/__pycache__/test_old_ma.cpython-310.pyc b/venv/lib/python3.10/site-packages/numpy/ma/tests/__pycache__/test_old_ma.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f8caacc22b0abc8b114e8cbd43519b2fdb447eb2
Binary files /dev/null and b/venv/lib/python3.10/site-packages/numpy/ma/tests/__pycache__/test_old_ma.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/numpy/ma/tests/__pycache__/test_regression.cpython-310.pyc b/venv/lib/python3.10/site-packages/numpy/ma/tests/__pycache__/test_regression.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ba75c30f92355198d90c18f012861532afb57936
Binary files /dev/null and b/venv/lib/python3.10/site-packages/numpy/ma/tests/__pycache__/test_regression.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/numpy/ma/tests/__pycache__/test_subclassing.cpython-310.pyc b/venv/lib/python3.10/site-packages/numpy/ma/tests/__pycache__/test_subclassing.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..071eba967936652d50ace447f5d136abb1925fab
Binary files /dev/null and b/venv/lib/python3.10/site-packages/numpy/ma/tests/__pycache__/test_subclassing.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/numpy/ma/tests/test_core.py b/venv/lib/python3.10/site-packages/numpy/ma/tests/test_core.py
new file mode 100644
index 0000000000000000000000000000000000000000..08ddc46c2498e923105bcb47c34abf9b694bdd3f
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/numpy/ma/tests/test_core.py
@@ -0,0 +1,5687 @@
+# pylint: disable-msg=W0400,W0511,W0611,W0612,W0614,R0201,E1102
+"""Tests suite for MaskedArray & subclassing.
+
+:author: Pierre Gerard-Marchant
+:contact: pierregm_at_uga_dot_edu
+"""
+__author__ = "Pierre GF Gerard-Marchant"
+
+import sys
+import warnings
+import copy
+import operator
+import itertools
+import textwrap
+import pytest
+
+from functools import reduce
+
+
+import numpy as np
+import numpy.ma.core
+import numpy.core.fromnumeric as fromnumeric
+import numpy.core.umath as umath
+from numpy.testing import (
+    assert_raises, assert_warns, suppress_warnings, IS_WASM
+    )
+from numpy.testing._private.utils import requires_memory
+from numpy import ndarray
+from numpy.compat import asbytes
+from numpy.ma.testutils import (
+    assert_, assert_array_equal, assert_equal, assert_almost_equal,
+    assert_equal_records, fail_if_equal, assert_not_equal,
+    assert_mask_equal
+    )
+from numpy.ma.core import (
+    MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all,
+    allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2,
+    arcsin, arctan, argsort, array, asarray, choose, concatenate,
+    conjugate, cos, cosh, count, default_fill_value, diag, divide, doc_note,
+    empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid,
+    flatten_structured_array, fromflex, getmask, getmaskarray, greater,
+    greater_equal, identity, inner, isMaskedArray, less, less_equal, log,
+    log10, make_mask, make_mask_descr, mask_or, masked, masked_array,
+    masked_equal, masked_greater, masked_greater_equal, masked_inside,
+    masked_less, masked_less_equal, masked_not_equal, masked_outside,
+    masked_print_option, masked_values, masked_where, max, maximum,
+    maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply,
+    mvoid, nomask, not_equal, ones, ones_like, outer, power, product, put,
+    putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort,
+    sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros, zeros_like,
+    )
+from numpy.compat import pickle
+
+pi = np.pi
+
+
+suppress_copy_mask_on_assignment = suppress_warnings()
+suppress_copy_mask_on_assignment.filter(
+    numpy.ma.core.MaskedArrayFutureWarning,
+    "setting an item on a masked array which has a shared mask will not copy")
+
+
+# For parametrized numeric testing
+num_dts = [np.dtype(dt_) for dt_ in '?bhilqBHILQefdgFD']
+num_ids = [dt_.char for dt_ in num_dts]
+
+
+class TestMaskedArray:
+    # Base test class for MaskedArrays.
+
+    def setup_method(self):
+        # Base data definition.
+        x = np.array([1., 1., 1., -2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.])
+        y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.])
+        a10 = 10.
+        m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
+        m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1]
+        xm = masked_array(x, mask=m1)
+        ym = masked_array(y, mask=m2)
+        z = np.array([-.5, 0., .5, .8])
+        zm = masked_array(z, mask=[0, 1, 0, 0])
+        xf = np.where(m1, 1e+20, x)
+        xm.set_fill_value(1e+20)
+        self.d = (x, y, a10, m1, m2, xm, ym, z, zm, xf)
+
+    def test_basicattributes(self):
+        # Tests some basic array attributes.
+        a = array([1, 3, 2])
+        b = array([1, 3, 2], mask=[1, 0, 1])
+        assert_equal(a.ndim, 1)
+        assert_equal(b.ndim, 1)
+        assert_equal(a.size, 3)
+        assert_equal(b.size, 3)
+        assert_equal(a.shape, (3,))
+        assert_equal(b.shape, (3,))
+
+    def test_basic0d(self):
+        # Checks masking a scalar
+        x = masked_array(0)
+        assert_equal(str(x), '0')
+        x = masked_array(0, mask=True)
+        assert_equal(str(x), str(masked_print_option))
+        x = masked_array(0, mask=False)
+        assert_equal(str(x), '0')
+        x = array(0, mask=1)
+        assert_(x.filled().dtype is x._data.dtype)
+
+    def test_basic1d(self):
+        # Test of basic array creation and properties in 1 dimension.
+        (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
+        assert_(not isMaskedArray(x))
+        assert_(isMaskedArray(xm))
+        assert_((xm - ym).filled(0).any())
+        fail_if_equal(xm.mask.astype(int), ym.mask.astype(int))
+        s = x.shape
+        assert_equal(np.shape(xm), s)
+        assert_equal(xm.shape, s)
+        assert_equal(xm.dtype, x.dtype)
+        assert_equal(zm.dtype, z.dtype)
+        assert_equal(xm.size, reduce(lambda x, y:x * y, s))
+        assert_equal(count(xm), len(m1) - reduce(lambda x, y:x + y, m1))
+        assert_array_equal(xm, xf)
+        assert_array_equal(filled(xm, 1.e20), xf)
+        assert_array_equal(x, xm)
+
+    def test_basic2d(self):
+        # Test of basic array creation and properties in 2 dimensions.
+        (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
+        for s in [(4, 3), (6, 2)]:
+            x.shape = s
+            y.shape = s
+            xm.shape = s
+            ym.shape = s
+            xf.shape = s
+
+            assert_(not isMaskedArray(x))
+            assert_(isMaskedArray(xm))
+            assert_equal(shape(xm), s)
+            assert_equal(xm.shape, s)
+            assert_equal(xm.size, reduce(lambda x, y:x * y, s))
+            assert_equal(count(xm), len(m1) - reduce(lambda x, y:x + y, m1))
+            assert_equal(xm, xf)
+            assert_equal(filled(xm, 1.e20), xf)
+            assert_equal(x, xm)
+
+    def test_concatenate_basic(self):
+        # Tests concatenations.
+        (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
+        # basic concatenation
+        assert_equal(np.concatenate((x, y)), concatenate((xm, ym)))
+        assert_equal(np.concatenate((x, y)), concatenate((x, y)))
+        assert_equal(np.concatenate((x, y)), concatenate((xm, y)))
+        assert_equal(np.concatenate((x, y, x)), concatenate((x, ym, x)))
+
+    def test_concatenate_alongaxis(self):
+        # Tests concatenations.
+        (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
+        # Concatenation along an axis
+        s = (3, 4)
+        x.shape = y.shape = xm.shape = ym.shape = s
+        assert_equal(xm.mask, np.reshape(m1, s))
+        assert_equal(ym.mask, np.reshape(m2, s))
+        xmym = concatenate((xm, ym), 1)
+        assert_equal(np.concatenate((x, y), 1), xmym)
+        assert_equal(np.concatenate((xm.mask, ym.mask), 1), xmym._mask)
+
+        x = zeros(2)
+        y = array(ones(2), mask=[False, True])
+        z = concatenate((x, y))
+        assert_array_equal(z, [0, 0, 1, 1])
+        assert_array_equal(z.mask, [False, False, False, True])
+        z = concatenate((y, x))
+        assert_array_equal(z, [1, 1, 0, 0])
+        assert_array_equal(z.mask, [False, True, False, False])
+
+    def test_concatenate_flexible(self):
+        # Tests the concatenation on flexible arrays.
+        data = masked_array(list(zip(np.random.rand(10),
+                                     np.arange(10))),
+                            dtype=[('a', float), ('b', int)])
+
+        test = concatenate([data[:5], data[5:]])
+        assert_equal_records(test, data)
+
+    def test_creation_ndmin(self):
+        # Check the use of ndmin
+        x = array([1, 2, 3], mask=[1, 0, 0], ndmin=2)
+        assert_equal(x.shape, (1, 3))
+        assert_equal(x._data, [[1, 2, 3]])
+        assert_equal(x._mask, [[1, 0, 0]])
+
+    def test_creation_ndmin_from_maskedarray(self):
+        # Make sure we're not losing the original mask w/ ndmin
+        x = array([1, 2, 3])
+        x[-1] = masked
+        xx = array(x, ndmin=2, dtype=float)
+        assert_equal(x.shape, x._mask.shape)
+        assert_equal(xx.shape, xx._mask.shape)
+
+    def test_creation_maskcreation(self):
+        # Tests how masks are initialized at the creation of Maskedarrays.
+        data = arange(24, dtype=float)
+        data[[3, 6, 15]] = masked
+        dma_1 = MaskedArray(data)
+        assert_equal(dma_1.mask, data.mask)
+        dma_2 = MaskedArray(dma_1)
+        assert_equal(dma_2.mask, dma_1.mask)
+        dma_3 = MaskedArray(dma_1, mask=[1, 0, 0, 0] * 6)
+        fail_if_equal(dma_3.mask, dma_1.mask)
+
+        x = array([1, 2, 3], mask=True)
+        assert_equal(x._mask, [True, True, True])
+        x = array([1, 2, 3], mask=False)
+        assert_equal(x._mask, [False, False, False])
+        y = array([1, 2, 3], mask=x._mask, copy=False)
+        assert_(np.may_share_memory(x.mask, y.mask))
+        y = array([1, 2, 3], mask=x._mask, copy=True)
+        assert_(not np.may_share_memory(x.mask, y.mask))
+        x = array([1, 2, 3], mask=None)
+        assert_equal(x._mask, [False, False, False])
+
+    def test_masked_singleton_array_creation_warns(self):
+        # The first works, but should not (ideally), there may be no way
+        # to solve this, however, as long as `np.ma.masked` is an ndarray.
+        np.array(np.ma.masked)
+        with pytest.warns(UserWarning):
+            # Tries to create a float array, using `float(np.ma.masked)`.
+            # We may want to define this is invalid behaviour in the future!
+            # (requiring np.ma.masked to be a known NumPy scalar probably
+            # with a DType.)
+            np.array([3., np.ma.masked])
+
+    def test_creation_with_list_of_maskedarrays(self):
+        # Tests creating a masked array from a list of masked arrays.
+        x = array(np.arange(5), mask=[1, 0, 0, 0, 0])
+        data = array((x, x[::-1]))
+        assert_equal(data, [[0, 1, 2, 3, 4], [4, 3, 2, 1, 0]])
+        assert_equal(data._mask, [[1, 0, 0, 0, 0], [0, 0, 0, 0, 1]])
+
+        x.mask = nomask
+        data = array((x, x[::-1]))
+        assert_equal(data, [[0, 1, 2, 3, 4], [4, 3, 2, 1, 0]])
+        assert_(data.mask is nomask)
+
+    def test_creation_with_list_of_maskedarrays_no_bool_cast(self):
+        # Tests the regression in gh-18551
+        masked_str = np.ma.masked_array(['a', 'b'], mask=[True, False])
+        normal_int = np.arange(2)
+        res = np.ma.asarray([masked_str, normal_int], dtype="U21")
+        assert_array_equal(res.mask, [[True, False], [False, False]])
+
+        # The above only failed due a long chain of oddity, try also with
+        # an object array that cannot be converted to bool always:
+        class NotBool():
+            def __bool__(self):
+                raise ValueError("not a bool!")
+        masked_obj = np.ma.masked_array([NotBool(), 'b'], mask=[True, False])
+        # Check that the NotBool actually fails like we would expect:
+        with pytest.raises(ValueError, match="not a bool!"):
+            np.asarray([masked_obj], dtype=bool)
+
+        res = np.ma.asarray([masked_obj, normal_int])
+        assert_array_equal(res.mask, [[True, False], [False, False]])
+
+    def test_creation_from_ndarray_with_padding(self):
+        x = np.array([('A', 0)], dtype={'names':['f0','f1'],
+                                        'formats':['S4','i8'],
+                                        'offsets':[0,8]})
+        array(x)  # used to fail due to 'V' padding field in x.dtype.descr
+
+    def test_unknown_keyword_parameter(self):
+        with pytest.raises(TypeError, match="unexpected keyword argument"):
+            MaskedArray([1, 2, 3], maks=[0, 1, 0])  # `mask` is misspelled.
+
+    def test_asarray(self):
+        (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
+        xm.fill_value = -9999
+        xm._hardmask = True
+        xmm = asarray(xm)
+        assert_equal(xmm._data, xm._data)
+        assert_equal(xmm._mask, xm._mask)
+        assert_equal(xmm.fill_value, xm.fill_value)
+        assert_equal(xmm._hardmask, xm._hardmask)
+
+    def test_asarray_default_order(self):
+        # See Issue #6646
+        m = np.eye(3).T
+        assert_(not m.flags.c_contiguous)
+
+        new_m = asarray(m)
+        assert_(new_m.flags.c_contiguous)
+
+    def test_asarray_enforce_order(self):
+        # See Issue #6646
+        m = np.eye(3).T
+        assert_(not m.flags.c_contiguous)
+
+        new_m = asarray(m, order='C')
+        assert_(new_m.flags.c_contiguous)
+
+    def test_fix_invalid(self):
+        # Checks fix_invalid.
+        with np.errstate(invalid='ignore'):
+            data = masked_array([np.nan, 0., 1.], mask=[0, 0, 1])
+            data_fixed = fix_invalid(data)
+            assert_equal(data_fixed._data, [data.fill_value, 0., 1.])
+            assert_equal(data_fixed._mask, [1., 0., 1.])
+
+    def test_maskedelement(self):
+        # Test of masked element
+        x = arange(6)
+        x[1] = masked
+        assert_(str(masked) == '--')
+        assert_(x[1] is masked)
+        assert_equal(filled(x[1], 0), 0)
+
+    def test_set_element_as_object(self):
+        # Tests setting elements with object
+        a = empty(1, dtype=object)
+        x = (1, 2, 3, 4, 5)
+        a[0] = x
+        assert_equal(a[0], x)
+        assert_(a[0] is x)
+
+        import datetime
+        dt = datetime.datetime.now()
+        a[0] = dt
+        assert_(a[0] is dt)
+
+    def test_indexing(self):
+        # Tests conversions and indexing
+        x1 = np.array([1, 2, 4, 3])
+        x2 = array(x1, mask=[1, 0, 0, 0])
+        x3 = array(x1, mask=[0, 1, 0, 1])
+        x4 = array(x1)
+        # test conversion to strings
+        str(x2)  # raises?
+        repr(x2)  # raises?
+        assert_equal(np.sort(x1), sort(x2, endwith=False))
+        # tests of indexing
+        assert_(type(x2[1]) is type(x1[1]))
+        assert_(x1[1] == x2[1])
+        assert_(x2[0] is masked)
+        assert_equal(x1[2], x2[2])
+        assert_equal(x1[2:5], x2[2:5])
+        assert_equal(x1[:], x2[:])
+        assert_equal(x1[1:], x3[1:])
+        x1[2] = 9
+        x2[2] = 9
+        assert_equal(x1, x2)
+        x1[1:3] = 99
+        x2[1:3] = 99
+        assert_equal(x1, x2)
+        x2[1] = masked
+        assert_equal(x1, x2)
+        x2[1:3] = masked
+        assert_equal(x1, x2)
+        x2[:] = x1
+        x2[1] = masked
+        assert_(allequal(getmask(x2), array([0, 1, 0, 0])))
+        x3[:] = masked_array([1, 2, 3, 4], [0, 1, 1, 0])
+        assert_(allequal(getmask(x3), array([0, 1, 1, 0])))
+        x4[:] = masked_array([1, 2, 3, 4], [0, 1, 1, 0])
+        assert_(allequal(getmask(x4), array([0, 1, 1, 0])))
+        assert_(allequal(x4, array([1, 2, 3, 4])))
+        x1 = np.arange(5) * 1.0
+        x2 = masked_values(x1, 3.0)
+        assert_equal(x1, x2)
+        assert_(allequal(array([0, 0, 0, 1, 0], MaskType), x2.mask))
+        assert_equal(3.0, x2.fill_value)
+        x1 = array([1, 'hello', 2, 3], object)
+        x2 = np.array([1, 'hello', 2, 3], object)
+        s1 = x1[1]
+        s2 = x2[1]
+        assert_equal(type(s2), str)
+        assert_equal(type(s1), str)
+        assert_equal(s1, s2)
+        assert_(x1[1:1].shape == (0,))
+
+    def test_setitem_no_warning(self):
+        # Setitem shouldn't warn, because the assignment might be masked
+        # and warning for a masked assignment is weird (see gh-23000)
+        # (When the value is masked, otherwise a warning would be acceptable
+        # but is not given currently.)
+        x = np.ma.arange(60).reshape((6, 10))
+        index = (slice(1, 5, 2), [7, 5])
+        value = np.ma.masked_all((2, 2))
+        value._data[...] = np.inf  # not a valid integer...
+        x[index] = value
+        # The masked scalar is special cased, but test anyway (it's NaN):
+        x[...] = np.ma.masked
+        # Finally, a large value that cannot be cast to the float32 `x`
+        x = np.ma.arange(3., dtype=np.float32)
+        value = np.ma.array([2e234, 1, 1], mask=[True, False, False])
+        x[...] = value
+        x[[0, 1, 2]] = value
+
+    @suppress_copy_mask_on_assignment
+    def test_copy(self):
+        # Tests of some subtle points of copying and sizing.
+        n = [0, 0, 1, 0, 0]
+        m = make_mask(n)
+        m2 = make_mask(m)
+        assert_(m is m2)
+        m3 = make_mask(m, copy=True)
+        assert_(m is not m3)
+
+        x1 = np.arange(5)
+        y1 = array(x1, mask=m)
+        assert_equal(y1._data.__array_interface__, x1.__array_interface__)
+        assert_(allequal(x1, y1.data))
+        assert_equal(y1._mask.__array_interface__, m.__array_interface__)
+
+        y1a = array(y1)
+        # Default for masked array is not to copy; see gh-10318.
+        assert_(y1a._data.__array_interface__ ==
+                        y1._data.__array_interface__)
+        assert_(y1a._mask.__array_interface__ ==
+                        y1._mask.__array_interface__)
+
+        y2 = array(x1, mask=m3)
+        assert_(y2._data.__array_interface__ == x1.__array_interface__)
+        assert_(y2._mask.__array_interface__ == m3.__array_interface__)
+        assert_(y2[2] is masked)
+        y2[2] = 9
+        assert_(y2[2] is not masked)
+        assert_(y2._mask.__array_interface__ == m3.__array_interface__)
+        assert_(allequal(y2.mask, 0))
+
+        y2a = array(x1, mask=m, copy=1)
+        assert_(y2a._data.__array_interface__ != x1.__array_interface__)
+        #assert_( y2a._mask is not m)
+        assert_(y2a._mask.__array_interface__ != m.__array_interface__)
+        assert_(y2a[2] is masked)
+        y2a[2] = 9
+        assert_(y2a[2] is not masked)
+        #assert_( y2a._mask is not m)
+        assert_(y2a._mask.__array_interface__ != m.__array_interface__)
+        assert_(allequal(y2a.mask, 0))
+
+        y3 = array(x1 * 1.0, mask=m)
+        assert_(filled(y3).dtype is (x1 * 1.0).dtype)
+
+        x4 = arange(4)
+        x4[2] = masked
+        y4 = resize(x4, (8,))
+        assert_equal(concatenate([x4, x4]), y4)
+        assert_equal(getmask(y4), [0, 0, 1, 0, 0, 0, 1, 0])
+        y5 = repeat(x4, (2, 2, 2, 2), axis=0)
+        assert_equal(y5, [0, 0, 1, 1, 2, 2, 3, 3])
+        y6 = repeat(x4, 2, axis=0)
+        assert_equal(y5, y6)
+        y7 = x4.repeat((2, 2, 2, 2), axis=0)
+        assert_equal(y5, y7)
+        y8 = x4.repeat(2, 0)
+        assert_equal(y5, y8)
+
+        y9 = x4.copy()
+        assert_equal(y9._data, x4._data)
+        assert_equal(y9._mask, x4._mask)
+
+        x = masked_array([1, 2, 3], mask=[0, 1, 0])
+        # Copy is False by default
+        y = masked_array(x)
+        assert_equal(y._data.ctypes.data, x._data.ctypes.data)
+        assert_equal(y._mask.ctypes.data, x._mask.ctypes.data)
+        y = masked_array(x, copy=True)
+        assert_not_equal(y._data.ctypes.data, x._data.ctypes.data)
+        assert_not_equal(y._mask.ctypes.data, x._mask.ctypes.data)
+
+    def test_copy_0d(self):
+        # gh-9430
+        x = np.ma.array(43, mask=True)
+        xc = x.copy()
+        assert_equal(xc.mask, True)
+
+    def test_copy_on_python_builtins(self):
+        # Tests copy works on python builtins (issue#8019)
+        assert_(isMaskedArray(np.ma.copy([1,2,3])))
+        assert_(isMaskedArray(np.ma.copy((1,2,3))))
+
+    def test_copy_immutable(self):
+        # Tests that the copy method is immutable, GitHub issue #5247
+        a = np.ma.array([1, 2, 3])
+        b = np.ma.array([4, 5, 6])
+        a_copy_method = a.copy
+        b.copy
+        assert_equal(a_copy_method(), [1, 2, 3])
+
+    def test_deepcopy(self):
+        from copy import deepcopy
+        a = array([0, 1, 2], mask=[False, True, False])
+        copied = deepcopy(a)
+        assert_equal(copied.mask, a.mask)
+        assert_not_equal(id(a._mask), id(copied._mask))
+
+        copied[1] = 1
+        assert_equal(copied.mask, [0, 0, 0])
+        assert_equal(a.mask, [0, 1, 0])
+
+        copied = deepcopy(a)
+        assert_equal(copied.mask, a.mask)
+        copied.mask[1] = False
+        assert_equal(copied.mask, [0, 0, 0])
+        assert_equal(a.mask, [0, 1, 0])
+
+    def test_format(self):
+        a = array([0, 1, 2], mask=[False, True, False])
+        assert_equal(format(a), "[0 -- 2]")
+        assert_equal(format(masked), "--")
+        assert_equal(format(masked, ""), "--")
+
+        # Postponed from PR #15410, perhaps address in the future.
+        # assert_equal(format(masked, " >5"), "   --")
+        # assert_equal(format(masked, " <5"), "--   ")
+
+        # Expect a FutureWarning for using format_spec with MaskedElement
+        with assert_warns(FutureWarning):
+            with_format_string = format(masked, " >5")
+        assert_equal(with_format_string, "--")
+
+    def test_str_repr(self):
+        a = array([0, 1, 2], mask=[False, True, False])
+        assert_equal(str(a), '[0 -- 2]')
+        assert_equal(
+            repr(a),
+            textwrap.dedent('''\
+            masked_array(data=[0, --, 2],
+                         mask=[False,  True, False],
+                   fill_value=999999)''')
+        )
+
+        # arrays with a continuation
+        a = np.ma.arange(2000)
+        a[1:50] = np.ma.masked
+        assert_equal(
+            repr(a),
+            textwrap.dedent('''\
+            masked_array(data=[0, --, --, ..., 1997, 1998, 1999],
+                         mask=[False,  True,  True, ..., False, False, False],
+                   fill_value=999999)''')
+        )
+
+        # line-wrapped 1d arrays are correctly aligned
+        a = np.ma.arange(20)
+        assert_equal(
+            repr(a),
+            textwrap.dedent('''\
+            masked_array(data=[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13,
+                               14, 15, 16, 17, 18, 19],
+                         mask=False,
+                   fill_value=999999)''')
+        )
+
+        # 2d arrays cause wrapping
+        a = array([[1, 2, 3], [4, 5, 6]], dtype=np.int8)
+        a[1,1] = np.ma.masked
+        assert_equal(
+            repr(a),
+            textwrap.dedent('''\
+            masked_array(
+              data=[[1, 2, 3],
+                    [4, --, 6]],
+              mask=[[False, False, False],
+                    [False,  True, False]],
+              fill_value=999999,
+              dtype=int8)''')
+        )
+
+        # but not it they're a row vector
+        assert_equal(
+            repr(a[:1]),
+            textwrap.dedent('''\
+            masked_array(data=[[1, 2, 3]],
+                         mask=[[False, False, False]],
+                   fill_value=999999,
+                        dtype=int8)''')
+        )
+
+        # dtype=int is implied, so not shown
+        assert_equal(
+            repr(a.astype(int)),
+            textwrap.dedent('''\
+            masked_array(
+              data=[[1, 2, 3],
+                    [4, --, 6]],
+              mask=[[False, False, False],
+                    [False,  True, False]],
+              fill_value=999999)''')
+        )
+
+    def test_str_repr_legacy(self):
+        oldopts = np.get_printoptions()
+        np.set_printoptions(legacy='1.13')
+        try:
+            a = array([0, 1, 2], mask=[False, True, False])
+            assert_equal(str(a), '[0 -- 2]')
+            assert_equal(repr(a), 'masked_array(data = [0 -- 2],\n'
+                                  '             mask = [False  True False],\n'
+                                  '       fill_value = 999999)\n')
+
+            a = np.ma.arange(2000)
+            a[1:50] = np.ma.masked
+            assert_equal(
+                repr(a),
+                'masked_array(data = [0 -- -- ..., 1997 1998 1999],\n'
+                '             mask = [False  True  True ..., False False False],\n'
+                '       fill_value = 999999)\n'
+            )
+        finally:
+            np.set_printoptions(**oldopts)
+
+    def test_0d_unicode(self):
+        u = 'caf\xe9'
+        utype = type(u)
+
+        arr_nomask = np.ma.array(u)
+        arr_masked = np.ma.array(u, mask=True)
+
+        assert_equal(utype(arr_nomask), u)
+        assert_equal(utype(arr_masked), '--')
+
+    def test_pickling(self):
+        # Tests pickling
+        for dtype in (int, float, str, object):
+            a = arange(10).astype(dtype)
+            a.fill_value = 999
+
+            masks = ([0, 0, 0, 1, 0, 1, 0, 1, 0, 1],  # partially masked
+                     True,                            # Fully masked
+                     False)                           # Fully unmasked
+
+            for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
+                for mask in masks:
+                    a.mask = mask
+                    a_pickled = pickle.loads(pickle.dumps(a, protocol=proto))
+                    assert_equal(a_pickled._mask, a._mask)
+                    assert_equal(a_pickled._data, a._data)
+                    if dtype in (object, int):
+                        assert_equal(a_pickled.fill_value, 999)
+                    else:
+                        assert_equal(a_pickled.fill_value, dtype(999))
+                    assert_array_equal(a_pickled.mask, mask)
+
+    def test_pickling_subbaseclass(self):
+        # Test pickling w/ a subclass of ndarray
+        x = np.array([(1.0, 2), (3.0, 4)],
+                     dtype=[('x', float), ('y', int)]).view(np.recarray)
+        a = masked_array(x, mask=[(True, False), (False, True)])
+        for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
+            a_pickled = pickle.loads(pickle.dumps(a, protocol=proto))
+            assert_equal(a_pickled._mask, a._mask)
+            assert_equal(a_pickled, a)
+            assert_(isinstance(a_pickled._data, np.recarray))
+
+    def test_pickling_maskedconstant(self):
+        # Test pickling MaskedConstant
+        mc = np.ma.masked
+        for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
+            mc_pickled = pickle.loads(pickle.dumps(mc, protocol=proto))
+            assert_equal(mc_pickled._baseclass, mc._baseclass)
+            assert_equal(mc_pickled._mask, mc._mask)
+            assert_equal(mc_pickled._data, mc._data)
+
+    def test_pickling_wstructured(self):
+        # Tests pickling w/ structured array
+        a = array([(1, 1.), (2, 2.)], mask=[(0, 0), (0, 1)],
+                  dtype=[('a', int), ('b', float)])
+        for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
+            a_pickled = pickle.loads(pickle.dumps(a, protocol=proto))
+            assert_equal(a_pickled._mask, a._mask)
+            assert_equal(a_pickled, a)
+
+    def test_pickling_keepalignment(self):
+        # Tests pickling w/ F_CONTIGUOUS arrays
+        a = arange(10)
+        a.shape = (-1, 2)
+        b = a.T
+        for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
+            test = pickle.loads(pickle.dumps(b, protocol=proto))
+            assert_equal(test, b)
+
+    def test_single_element_subscript(self):
+        # Tests single element subscripts of Maskedarrays.
+        a = array([1, 3, 2])
+        b = array([1, 3, 2], mask=[1, 0, 1])
+        assert_equal(a[0].shape, ())
+        assert_equal(b[0].shape, ())
+        assert_equal(b[1].shape, ())
+
+    def test_topython(self):
+        # Tests some communication issues with Python.
+        assert_equal(1, int(array(1)))
+        assert_equal(1.0, float(array(1)))
+        assert_equal(1, int(array([[[1]]])))
+        assert_equal(1.0, float(array([[1]])))
+        assert_raises(TypeError, float, array([1, 1]))
+
+        with suppress_warnings() as sup:
+            sup.filter(UserWarning, 'Warning: converting a masked element')
+            assert_(np.isnan(float(array([1], mask=[1]))))
+
+            a = array([1, 2, 3], mask=[1, 0, 0])
+            assert_raises(TypeError, lambda: float(a))
+            assert_equal(float(a[-1]), 3.)
+            assert_(np.isnan(float(a[0])))
+        assert_raises(TypeError, int, a)
+        assert_equal(int(a[-1]), 3)
+        assert_raises(MAError, lambda:int(a[0]))
+
+    def test_oddfeatures_1(self):
+        # Test of other odd features
+        x = arange(20)
+        x = x.reshape(4, 5)
+        x.flat[5] = 12
+        assert_(x[1, 0] == 12)
+        z = x + 10j * x
+        assert_equal(z.real, x)
+        assert_equal(z.imag, 10 * x)
+        assert_equal((z * conjugate(z)).real, 101 * x * x)
+        z.imag[...] = 0.0
+
+        x = arange(10)
+        x[3] = masked
+        assert_(str(x[3]) == str(masked))
+        c = x >= 8
+        assert_(count(where(c, masked, masked)) == 0)
+        assert_(shape(where(c, masked, masked)) == c.shape)
+
+        z = masked_where(c, x)
+        assert_(z.dtype is x.dtype)
+        assert_(z[3] is masked)
+        assert_(z[4] is not masked)
+        assert_(z[7] is not masked)
+        assert_(z[8] is masked)
+        assert_(z[9] is masked)
+        assert_equal(x, z)
+
+    def test_oddfeatures_2(self):
+        # Tests some more features.
+        x = array([1., 2., 3., 4., 5.])
+        c = array([1, 1, 1, 0, 0])
+        x[2] = masked
+        z = where(c, x, -x)
+        assert_equal(z, [1., 2., 0., -4., -5])
+        c[0] = masked
+        z = where(c, x, -x)
+        assert_equal(z, [1., 2., 0., -4., -5])
+        assert_(z[0] is masked)
+        assert_(z[1] is not masked)
+        assert_(z[2] is masked)
+
+    @suppress_copy_mask_on_assignment
+    def test_oddfeatures_3(self):
+        # Tests some generic features
+        atest = array([10], mask=True)
+        btest = array([20])
+        idx = atest.mask
+        atest[idx] = btest[idx]
+        assert_equal(atest, [20])
+
+    def test_filled_with_object_dtype(self):
+        a = np.ma.masked_all(1, dtype='O')
+        assert_equal(a.filled('x')[0], 'x')
+
+    def test_filled_with_flexible_dtype(self):
+        # Test filled w/ flexible dtype
+        flexi = array([(1, 1, 1)],
+                      dtype=[('i', int), ('s', '|S8'), ('f', float)])
+        flexi[0] = masked
+        assert_equal(flexi.filled(),
+                     np.array([(default_fill_value(0),
+                                default_fill_value('0'),
+                                default_fill_value(0.),)], dtype=flexi.dtype))
+        flexi[0] = masked
+        assert_equal(flexi.filled(1),
+                     np.array([(1, '1', 1.)], dtype=flexi.dtype))
+
+    def test_filled_with_mvoid(self):
+        # Test filled w/ mvoid
+        ndtype = [('a', int), ('b', float)]
+        a = mvoid((1, 2.), mask=[(0, 1)], dtype=ndtype)
+        # Filled using default
+        test = a.filled()
+        assert_equal(tuple(test), (1, default_fill_value(1.)))
+        # Explicit fill_value
+        test = a.filled((-1, -1))
+        assert_equal(tuple(test), (1, -1))
+        # Using predefined filling values
+        a.fill_value = (-999, -999)
+        assert_equal(tuple(a.filled()), (1, -999))
+
+    def test_filled_with_nested_dtype(self):
+        # Test filled w/ nested dtype
+        ndtype = [('A', int), ('B', [('BA', int), ('BB', int)])]
+        a = array([(1, (1, 1)), (2, (2, 2))],
+                  mask=[(0, (1, 0)), (0, (0, 1))], dtype=ndtype)
+        test = a.filled(0)
+        control = np.array([(1, (0, 1)), (2, (2, 0))], dtype=ndtype)
+        assert_equal(test, control)
+
+        test = a['B'].filled(0)
+        control = np.array([(0, 1), (2, 0)], dtype=a['B'].dtype)
+        assert_equal(test, control)
+
+        # test if mask gets set correctly (see #6760)
+        Z = numpy.ma.zeros(2, numpy.dtype([("A", "(2,2)i1,(2,2)i1", (2,2))]))
+        assert_equal(Z.data.dtype, numpy.dtype([('A', [('f0', 'i1', (2, 2)),
+                                          ('f1', 'i1', (2, 2))], (2, 2))]))
+        assert_equal(Z.mask.dtype, numpy.dtype([('A', [('f0', '?', (2, 2)),
+                                          ('f1', '?', (2, 2))], (2, 2))]))
+
+    def test_filled_with_f_order(self):
+        # Test filled w/ F-contiguous array
+        a = array(np.array([(0, 1, 2), (4, 5, 6)], order='F'),
+                  mask=np.array([(0, 0, 1), (1, 0, 0)], order='F'),
+                  order='F')  # this is currently ignored
+        assert_(a.flags['F_CONTIGUOUS'])
+        assert_(a.filled(0).flags['F_CONTIGUOUS'])
+
+    def test_optinfo_propagation(self):
+        # Checks that _optinfo dictionary isn't back-propagated
+        x = array([1, 2, 3, ], dtype=float)
+        x._optinfo['info'] = '???'
+        y = x.copy()
+        assert_equal(y._optinfo['info'], '???')
+        y._optinfo['info'] = '!!!'
+        assert_equal(x._optinfo['info'], '???')
+
+    def test_optinfo_forward_propagation(self):
+        a = array([1,2,2,4])
+        a._optinfo["key"] = "value"
+        assert_equal(a._optinfo["key"], (a == 2)._optinfo["key"])
+        assert_equal(a._optinfo["key"], (a != 2)._optinfo["key"])
+        assert_equal(a._optinfo["key"], (a > 2)._optinfo["key"])
+        assert_equal(a._optinfo["key"], (a >= 2)._optinfo["key"])
+        assert_equal(a._optinfo["key"], (a <= 2)._optinfo["key"])
+        assert_equal(a._optinfo["key"], (a + 2)._optinfo["key"])
+        assert_equal(a._optinfo["key"], (a - 2)._optinfo["key"])
+        assert_equal(a._optinfo["key"], (a * 2)._optinfo["key"])
+        assert_equal(a._optinfo["key"], (a / 2)._optinfo["key"])
+        assert_equal(a._optinfo["key"], a[:2]._optinfo["key"])
+        assert_equal(a._optinfo["key"], a[[0,0,2]]._optinfo["key"])
+        assert_equal(a._optinfo["key"], np.exp(a)._optinfo["key"])
+        assert_equal(a._optinfo["key"], np.abs(a)._optinfo["key"])
+        assert_equal(a._optinfo["key"], array(a, copy=True)._optinfo["key"])
+        assert_equal(a._optinfo["key"], np.zeros_like(a)._optinfo["key"])
+
+    def test_fancy_printoptions(self):
+        # Test printing a masked array w/ fancy dtype.
+        fancydtype = np.dtype([('x', int), ('y', [('t', int), ('s', float)])])
+        test = array([(1, (2, 3.0)), (4, (5, 6.0))],
+                     mask=[(1, (0, 1)), (0, (1, 0))],
+                     dtype=fancydtype)
+        control = "[(--, (2, --)) (4, (--, 6.0))]"
+        assert_equal(str(test), control)
+
+        # Test 0-d array with multi-dimensional dtype
+        t_2d0 = masked_array(data = (0, [[0.0, 0.0, 0.0],
+                                        [0.0, 0.0, 0.0]],
+                                    0.0),
+                             mask = (False, [[True, False, True],
+                                             [False, False, True]],
+                                     False),
+                             dtype = "int, (2,3)float, float")
+        control = "(0, [[--, 0.0, --], [0.0, 0.0, --]], 0.0)"
+        assert_equal(str(t_2d0), control)
+
+    def test_flatten_structured_array(self):
+        # Test flatten_structured_array on arrays
+        # On ndarray
+        ndtype = [('a', int), ('b', float)]
+        a = np.array([(1, 1), (2, 2)], dtype=ndtype)
+        test = flatten_structured_array(a)
+        control = np.array([[1., 1.], [2., 2.]], dtype=float)
+        assert_equal(test, control)
+        assert_equal(test.dtype, control.dtype)
+        # On masked_array
+        a = array([(1, 1), (2, 2)], mask=[(0, 1), (1, 0)], dtype=ndtype)
+        test = flatten_structured_array(a)
+        control = array([[1., 1.], [2., 2.]],
+                        mask=[[0, 1], [1, 0]], dtype=float)
+        assert_equal(test, control)
+        assert_equal(test.dtype, control.dtype)
+        assert_equal(test.mask, control.mask)
+        # On masked array with nested structure
+        ndtype = [('a', int), ('b', [('ba', int), ('bb', float)])]
+        a = array([(1, (1, 1.1)), (2, (2, 2.2))],
+                  mask=[(0, (1, 0)), (1, (0, 1))], dtype=ndtype)
+        test = flatten_structured_array(a)
+        control = array([[1., 1., 1.1], [2., 2., 2.2]],
+                        mask=[[0, 1, 0], [1, 0, 1]], dtype=float)
+        assert_equal(test, control)
+        assert_equal(test.dtype, control.dtype)
+        assert_equal(test.mask, control.mask)
+        # Keeping the initial shape
+        ndtype = [('a', int), ('b', float)]
+        a = np.array([[(1, 1), ], [(2, 2), ]], dtype=ndtype)
+        test = flatten_structured_array(a)
+        control = np.array([[[1., 1.], ], [[2., 2.], ]], dtype=float)
+        assert_equal(test, control)
+        assert_equal(test.dtype, control.dtype)
+
+    def test_void0d(self):
+        # Test creating a mvoid object
+        ndtype = [('a', int), ('b', int)]
+        a = np.array([(1, 2,)], dtype=ndtype)[0]
+        f = mvoid(a)
+        assert_(isinstance(f, mvoid))
+
+        a = masked_array([(1, 2)], mask=[(1, 0)], dtype=ndtype)[0]
+        assert_(isinstance(a, mvoid))
+
+        a = masked_array([(1, 2), (1, 2)], mask=[(1, 0), (0, 0)], dtype=ndtype)
+        f = mvoid(a._data[0], a._mask[0])
+        assert_(isinstance(f, mvoid))
+
+    def test_mvoid_getitem(self):
+        # Test mvoid.__getitem__
+        ndtype = [('a', int), ('b', int)]
+        a = masked_array([(1, 2,), (3, 4)], mask=[(0, 0), (1, 0)],
+                         dtype=ndtype)
+        # w/o mask
+        f = a[0]
+        assert_(isinstance(f, mvoid))
+        assert_equal((f[0], f['a']), (1, 1))
+        assert_equal(f['b'], 2)
+        # w/ mask
+        f = a[1]
+        assert_(isinstance(f, mvoid))
+        assert_(f[0] is masked)
+        assert_(f['a'] is masked)
+        assert_equal(f[1], 4)
+
+        # exotic dtype
+        A = masked_array(data=[([0,1],)],
+                         mask=[([True, False],)],
+                         dtype=[("A", ">i2", (2,))])
+        assert_equal(A[0]["A"], A["A"][0])
+        assert_equal(A[0]["A"], masked_array(data=[0, 1],
+                         mask=[True, False], dtype=">i2"))
+
+    def test_mvoid_iter(self):
+        # Test iteration on __getitem__
+        ndtype = [('a', int), ('b', int)]
+        a = masked_array([(1, 2,), (3, 4)], mask=[(0, 0), (1, 0)],
+                         dtype=ndtype)
+        # w/o mask
+        assert_equal(list(a[0]), [1, 2])
+        # w/ mask
+        assert_equal(list(a[1]), [masked, 4])
+
+    def test_mvoid_print(self):
+        # Test printing a mvoid
+        mx = array([(1, 1), (2, 2)], dtype=[('a', int), ('b', int)])
+        assert_equal(str(mx[0]), "(1, 1)")
+        mx['b'][0] = masked
+        ini_display = masked_print_option._display
+        masked_print_option.set_display("-X-")
+        try:
+            assert_equal(str(mx[0]), "(1, -X-)")
+            assert_equal(repr(mx[0]), "(1, -X-)")
+        finally:
+            masked_print_option.set_display(ini_display)
+
+        # also check if there are object datatypes (see gh-7493)
+        mx = array([(1,), (2,)], dtype=[('a', 'O')])
+        assert_equal(str(mx[0]), "(1,)")
+
+    def test_mvoid_multidim_print(self):
+
+        # regression test for gh-6019
+        t_ma = masked_array(data = [([1, 2, 3],)],
+                            mask = [([False, True, False],)],
+                            fill_value = ([999999, 999999, 999999],),
+                            dtype = [('a', ' 1:
+            assert_equal(np.concatenate((x, y), 1), concatenate((xm, ym), 1))
+            assert_equal(np.add.reduce(x, 1), add.reduce(x, 1))
+            assert_equal(np.sum(x, 1), sum(x, 1))
+            assert_equal(np.prod(x, 1), product(x, 1))
+
+    def test_binops_d2D(self):
+        # Test binary operations on 2D data
+        a = array([[1.], [2.], [3.]], mask=[[False], [True], [True]])
+        b = array([[2., 3.], [4., 5.], [6., 7.]])
+
+        test = a * b
+        control = array([[2., 3.], [2., 2.], [3., 3.]],
+                        mask=[[0, 0], [1, 1], [1, 1]])
+        assert_equal(test, control)
+        assert_equal(test.data, control.data)
+        assert_equal(test.mask, control.mask)
+
+        test = b * a
+        control = array([[2., 3.], [4., 5.], [6., 7.]],
+                        mask=[[0, 0], [1, 1], [1, 1]])
+        assert_equal(test, control)
+        assert_equal(test.data, control.data)
+        assert_equal(test.mask, control.mask)
+
+        a = array([[1.], [2.], [3.]])
+        b = array([[2., 3.], [4., 5.], [6., 7.]],
+                  mask=[[0, 0], [0, 0], [0, 1]])
+        test = a * b
+        control = array([[2, 3], [8, 10], [18, 3]],
+                        mask=[[0, 0], [0, 0], [0, 1]])
+        assert_equal(test, control)
+        assert_equal(test.data, control.data)
+        assert_equal(test.mask, control.mask)
+
+        test = b * a
+        control = array([[2, 3], [8, 10], [18, 7]],
+                        mask=[[0, 0], [0, 0], [0, 1]])
+        assert_equal(test, control)
+        assert_equal(test.data, control.data)
+        assert_equal(test.mask, control.mask)
+
+    def test_domained_binops_d2D(self):
+        # Test domained binary operations on 2D data
+        a = array([[1.], [2.], [3.]], mask=[[False], [True], [True]])
+        b = array([[2., 3.], [4., 5.], [6., 7.]])
+
+        test = a / b
+        control = array([[1. / 2., 1. / 3.], [2., 2.], [3., 3.]],
+                        mask=[[0, 0], [1, 1], [1, 1]])
+        assert_equal(test, control)
+        assert_equal(test.data, control.data)
+        assert_equal(test.mask, control.mask)
+
+        test = b / a
+        control = array([[2. / 1., 3. / 1.], [4., 5.], [6., 7.]],
+                        mask=[[0, 0], [1, 1], [1, 1]])
+        assert_equal(test, control)
+        assert_equal(test.data, control.data)
+        assert_equal(test.mask, control.mask)
+
+        a = array([[1.], [2.], [3.]])
+        b = array([[2., 3.], [4., 5.], [6., 7.]],
+                  mask=[[0, 0], [0, 0], [0, 1]])
+        test = a / b
+        control = array([[1. / 2, 1. / 3], [2. / 4, 2. / 5], [3. / 6, 3]],
+                        mask=[[0, 0], [0, 0], [0, 1]])
+        assert_equal(test, control)
+        assert_equal(test.data, control.data)
+        assert_equal(test.mask, control.mask)
+
+        test = b / a
+        control = array([[2 / 1., 3 / 1.], [4 / 2., 5 / 2.], [6 / 3., 7]],
+                        mask=[[0, 0], [0, 0], [0, 1]])
+        assert_equal(test, control)
+        assert_equal(test.data, control.data)
+        assert_equal(test.mask, control.mask)
+
+    def test_noshrinking(self):
+        # Check that we don't shrink a mask when not wanted
+        # Binary operations
+        a = masked_array([1., 2., 3.], mask=[False, False, False],
+                         shrink=False)
+        b = a + 1
+        assert_equal(b.mask, [0, 0, 0])
+        # In place binary operation
+        a += 1
+        assert_equal(a.mask, [0, 0, 0])
+        # Domained binary operation
+        b = a / 1.
+        assert_equal(b.mask, [0, 0, 0])
+        # In place binary operation
+        a /= 1.
+        assert_equal(a.mask, [0, 0, 0])
+
+    def test_ufunc_nomask(self):
+        # check the case ufuncs should set the mask to false
+        m = np.ma.array([1])
+        # check we don't get array([False], dtype=bool)
+        assert_equal(np.true_divide(m, 5).mask.shape, ())
+
+    def test_noshink_on_creation(self):
+        # Check that the mask is not shrunk on array creation when not wanted
+        a = np.ma.masked_values([1., 2.5, 3.1], 1.5, shrink=False)
+        assert_equal(a.mask, [0, 0, 0])
+
+    def test_mod(self):
+        # Tests mod
+        (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
+        assert_equal(mod(x, y), mod(xm, ym))
+        test = mod(ym, xm)
+        assert_equal(test, np.mod(ym, xm))
+        assert_equal(test.mask, mask_or(xm.mask, ym.mask))
+        test = mod(xm, ym)
+        assert_equal(test, np.mod(xm, ym))
+        assert_equal(test.mask, mask_or(mask_or(xm.mask, ym.mask), (ym == 0)))
+
+    def test_TakeTransposeInnerOuter(self):
+        # Test of take, transpose, inner, outer products
+        x = arange(24)
+        y = np.arange(24)
+        x[5:6] = masked
+        x = x.reshape(2, 3, 4)
+        y = y.reshape(2, 3, 4)
+        assert_equal(np.transpose(y, (2, 0, 1)), transpose(x, (2, 0, 1)))
+        assert_equal(np.take(y, (2, 0, 1), 1), take(x, (2, 0, 1), 1))
+        assert_equal(np.inner(filled(x, 0), filled(y, 0)),
+                     inner(x, y))
+        assert_equal(np.outer(filled(x, 0), filled(y, 0)),
+                     outer(x, y))
+        y = array(['abc', 1, 'def', 2, 3], object)
+        y[2] = masked
+        t = take(y, [0, 3, 4])
+        assert_(t[0] == 'abc')
+        assert_(t[1] == 2)
+        assert_(t[2] == 3)
+
+    def test_imag_real(self):
+        # Check complex
+        xx = array([1 + 10j, 20 + 2j], mask=[1, 0])
+        assert_equal(xx.imag, [10, 2])
+        assert_equal(xx.imag.filled(), [1e+20, 2])
+        assert_equal(xx.imag.dtype, xx._data.imag.dtype)
+        assert_equal(xx.real, [1, 20])
+        assert_equal(xx.real.filled(), [1e+20, 20])
+        assert_equal(xx.real.dtype, xx._data.real.dtype)
+
+    def test_methods_with_output(self):
+        xm = array(np.random.uniform(0, 10, 12)).reshape(3, 4)
+        xm[:, 0] = xm[0] = xm[-1, -1] = masked
+
+        funclist = ('sum', 'prod', 'var', 'std', 'max', 'min', 'ptp', 'mean',)
+
+        for funcname in funclist:
+            npfunc = getattr(np, funcname)
+            xmmeth = getattr(xm, funcname)
+            # A ndarray as explicit input
+            output = np.empty(4, dtype=float)
+            output.fill(-9999)
+            result = npfunc(xm, axis=0, out=output)
+            # ... the result should be the given output
+            assert_(result is output)
+            assert_equal(result, xmmeth(axis=0, out=output))
+
+            output = empty(4, dtype=int)
+            result = xmmeth(axis=0, out=output)
+            assert_(result is output)
+            assert_(output[0] is masked)
+
+    def test_eq_on_structured(self):
+        # Test the equality of structured arrays
+        ndtype = [('A', int), ('B', int)]
+        a = array([(1, 1), (2, 2)], mask=[(0, 1), (0, 0)], dtype=ndtype)
+
+        test = (a == a)
+        assert_equal(test.data, [True, True])
+        assert_equal(test.mask, [False, False])
+        assert_(test.fill_value == True)
+
+        test = (a == a[0])
+        assert_equal(test.data, [True, False])
+        assert_equal(test.mask, [False, False])
+        assert_(test.fill_value == True)
+
+        b = array([(1, 1), (2, 2)], mask=[(1, 0), (0, 0)], dtype=ndtype)
+        test = (a == b)
+        assert_equal(test.data, [False, True])
+        assert_equal(test.mask, [True, False])
+        assert_(test.fill_value == True)
+
+        test = (a[0] == b)
+        assert_equal(test.data, [False, False])
+        assert_equal(test.mask, [True, False])
+        assert_(test.fill_value == True)
+
+        b = array([(1, 1), (2, 2)], mask=[(0, 1), (1, 0)], dtype=ndtype)
+        test = (a == b)
+        assert_equal(test.data, [True, True])
+        assert_equal(test.mask, [False, False])
+        assert_(test.fill_value == True)
+
+        # complicated dtype, 2-dimensional array.
+        ndtype = [('A', int), ('B', [('BA', int), ('BB', int)])]
+        a = array([[(1, (1, 1)), (2, (2, 2))],
+                   [(3, (3, 3)), (4, (4, 4))]],
+                  mask=[[(0, (1, 0)), (0, (0, 1))],
+                        [(1, (0, 0)), (1, (1, 1))]], dtype=ndtype)
+        test = (a[0, 0] == a)
+        assert_equal(test.data, [[True, False], [False, False]])
+        assert_equal(test.mask, [[False, False], [False, True]])
+        assert_(test.fill_value == True)
+
+    def test_ne_on_structured(self):
+        # Test the equality of structured arrays
+        ndtype = [('A', int), ('B', int)]
+        a = array([(1, 1), (2, 2)], mask=[(0, 1), (0, 0)], dtype=ndtype)
+
+        test = (a != a)
+        assert_equal(test.data, [False, False])
+        assert_equal(test.mask, [False, False])
+        assert_(test.fill_value == True)
+
+        test = (a != a[0])
+        assert_equal(test.data, [False, True])
+        assert_equal(test.mask, [False, False])
+        assert_(test.fill_value == True)
+
+        b = array([(1, 1), (2, 2)], mask=[(1, 0), (0, 0)], dtype=ndtype)
+        test = (a != b)
+        assert_equal(test.data, [True, False])
+        assert_equal(test.mask, [True, False])
+        assert_(test.fill_value == True)
+
+        test = (a[0] != b)
+        assert_equal(test.data, [True, True])
+        assert_equal(test.mask, [True, False])
+        assert_(test.fill_value == True)
+
+        b = array([(1, 1), (2, 2)], mask=[(0, 1), (1, 0)], dtype=ndtype)
+        test = (a != b)
+        assert_equal(test.data, [False, False])
+        assert_equal(test.mask, [False, False])
+        assert_(test.fill_value == True)
+
+        # complicated dtype, 2-dimensional array.
+        ndtype = [('A', int), ('B', [('BA', int), ('BB', int)])]
+        a = array([[(1, (1, 1)), (2, (2, 2))],
+                   [(3, (3, 3)), (4, (4, 4))]],
+                  mask=[[(0, (1, 0)), (0, (0, 1))],
+                        [(1, (0, 0)), (1, (1, 1))]], dtype=ndtype)
+        test = (a[0, 0] != a)
+        assert_equal(test.data, [[False, True], [True, True]])
+        assert_equal(test.mask, [[False, False], [False, True]])
+        assert_(test.fill_value == True)
+
+    def test_eq_ne_structured_with_non_masked(self):
+        a = array([(1, 1), (2, 2), (3, 4)],
+                  mask=[(0, 1), (0, 0), (1, 1)], dtype='i4,i4')
+        eq = a == a.data
+        ne = a.data != a
+        # Test the obvious.
+        assert_(np.all(eq))
+        assert_(not np.any(ne))
+        # Expect the mask set only for items with all fields masked.
+        expected_mask = a.mask == np.ones((), a.mask.dtype)
+        assert_array_equal(eq.mask, expected_mask)
+        assert_array_equal(ne.mask, expected_mask)
+        # The masked element will indicated not equal, because the
+        # masks did not match.
+        assert_equal(eq.data, [True, True, False])
+        assert_array_equal(eq.data, ~ne.data)
+
+    def test_eq_ne_structured_extra(self):
+        # ensure simple examples are symmetric and make sense.
+        # from https://github.com/numpy/numpy/pull/8590#discussion_r101126465
+        dt = np.dtype('i4,i4')
+        for m1 in (mvoid((1, 2), mask=(0, 0), dtype=dt),
+                   mvoid((1, 2), mask=(0, 1), dtype=dt),
+                   mvoid((1, 2), mask=(1, 0), dtype=dt),
+                   mvoid((1, 2), mask=(1, 1), dtype=dt)):
+            ma1 = m1.view(MaskedArray)
+            r1 = ma1.view('2i4')
+            for m2 in (np.array((1, 1), dtype=dt),
+                       mvoid((1, 1), dtype=dt),
+                       mvoid((1, 0), mask=(0, 1), dtype=dt),
+                       mvoid((3, 2), mask=(0, 1), dtype=dt)):
+                ma2 = m2.view(MaskedArray)
+                r2 = ma2.view('2i4')
+                eq_expected = (r1 == r2).all()
+                assert_equal(m1 == m2, eq_expected)
+                assert_equal(m2 == m1, eq_expected)
+                assert_equal(ma1 == m2, eq_expected)
+                assert_equal(m1 == ma2, eq_expected)
+                assert_equal(ma1 == ma2, eq_expected)
+                # Also check it is the same if we do it element by element.
+                el_by_el = [m1[name] == m2[name] for name in dt.names]
+                assert_equal(array(el_by_el, dtype=bool).all(), eq_expected)
+                ne_expected = (r1 != r2).any()
+                assert_equal(m1 != m2, ne_expected)
+                assert_equal(m2 != m1, ne_expected)
+                assert_equal(ma1 != m2, ne_expected)
+                assert_equal(m1 != ma2, ne_expected)
+                assert_equal(ma1 != ma2, ne_expected)
+                el_by_el = [m1[name] != m2[name] for name in dt.names]
+                assert_equal(array(el_by_el, dtype=bool).any(), ne_expected)
+
+    @pytest.mark.parametrize('dt', ['S', 'U'])
+    @pytest.mark.parametrize('fill', [None, 'A'])
+    def test_eq_for_strings(self, dt, fill):
+        # Test the equality of structured arrays
+        a = array(['a', 'b'], dtype=dt, mask=[0, 1], fill_value=fill)
+
+        test = (a == a)
+        assert_equal(test.data, [True, True])
+        assert_equal(test.mask, [False, True])
+        assert_(test.fill_value == True)
+
+        test = (a == a[0])
+        assert_equal(test.data, [True, False])
+        assert_equal(test.mask, [False, True])
+        assert_(test.fill_value == True)
+
+        b = array(['a', 'b'], dtype=dt, mask=[1, 0], fill_value=fill)
+        test = (a == b)
+        assert_equal(test.data, [False, False])
+        assert_equal(test.mask, [True, True])
+        assert_(test.fill_value == True)
+
+        test = (a[0] == b)
+        assert_equal(test.data, [False, False])
+        assert_equal(test.mask, [True, False])
+        assert_(test.fill_value == True)
+
+        test = (b == a[0])
+        assert_equal(test.data, [False, False])
+        assert_equal(test.mask, [True, False])
+        assert_(test.fill_value == True)
+
+    @pytest.mark.parametrize('dt', ['S', 'U'])
+    @pytest.mark.parametrize('fill', [None, 'A'])
+    def test_ne_for_strings(self, dt, fill):
+        # Test the equality of structured arrays
+        a = array(['a', 'b'], dtype=dt, mask=[0, 1], fill_value=fill)
+
+        test = (a != a)
+        assert_equal(test.data, [False, False])
+        assert_equal(test.mask, [False, True])
+        assert_(test.fill_value == True)
+
+        test = (a != a[0])
+        assert_equal(test.data, [False, True])
+        assert_equal(test.mask, [False, True])
+        assert_(test.fill_value == True)
+
+        b = array(['a', 'b'], dtype=dt, mask=[1, 0], fill_value=fill)
+        test = (a != b)
+        assert_equal(test.data, [True, True])
+        assert_equal(test.mask, [True, True])
+        assert_(test.fill_value == True)
+
+        test = (a[0] != b)
+        assert_equal(test.data, [True, True])
+        assert_equal(test.mask, [True, False])
+        assert_(test.fill_value == True)
+
+        test = (b != a[0])
+        assert_equal(test.data, [True, True])
+        assert_equal(test.mask, [True, False])
+        assert_(test.fill_value == True)
+
+    @pytest.mark.parametrize('dt1', num_dts, ids=num_ids)
+    @pytest.mark.parametrize('dt2', num_dts, ids=num_ids)
+    @pytest.mark.parametrize('fill', [None, 1])
+    def test_eq_for_numeric(self, dt1, dt2, fill):
+        # Test the equality of structured arrays
+        a = array([0, 1], dtype=dt1, mask=[0, 1], fill_value=fill)
+
+        test = (a == a)
+        assert_equal(test.data, [True, True])
+        assert_equal(test.mask, [False, True])
+        assert_(test.fill_value == True)
+
+        test = (a == a[0])
+        assert_equal(test.data, [True, False])
+        assert_equal(test.mask, [False, True])
+        assert_(test.fill_value == True)
+
+        b = array([0, 1], dtype=dt2, mask=[1, 0], fill_value=fill)
+        test = (a == b)
+        assert_equal(test.data, [False, False])
+        assert_equal(test.mask, [True, True])
+        assert_(test.fill_value == True)
+
+        test = (a[0] == b)
+        assert_equal(test.data, [False, False])
+        assert_equal(test.mask, [True, False])
+        assert_(test.fill_value == True)
+
+        test = (b == a[0])
+        assert_equal(test.data, [False, False])
+        assert_equal(test.mask, [True, False])
+        assert_(test.fill_value == True)
+
+    @pytest.mark.parametrize("op", [operator.eq, operator.lt])
+    def test_eq_broadcast_with_unmasked(self, op):
+        a = array([0, 1], mask=[0, 1])
+        b = np.arange(10).reshape(5, 2)
+        result = op(a, b)
+        assert_(result.mask.shape == b.shape)
+        assert_equal(result.mask, np.zeros(b.shape, bool) | a.mask)
+
+    @pytest.mark.parametrize("op", [operator.eq, operator.gt])
+    def test_comp_no_mask_not_broadcast(self, op):
+        # Regression test for failing doctest in MaskedArray.nonzero
+        # after gh-24556.
+        a = array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
+        result = op(a, 3)
+        assert_(not result.mask.shape)
+        assert_(result.mask is nomask)
+
+    @pytest.mark.parametrize('dt1', num_dts, ids=num_ids)
+    @pytest.mark.parametrize('dt2', num_dts, ids=num_ids)
+    @pytest.mark.parametrize('fill', [None, 1])
+    def test_ne_for_numeric(self, dt1, dt2, fill):
+        # Test the equality of structured arrays
+        a = array([0, 1], dtype=dt1, mask=[0, 1], fill_value=fill)
+
+        test = (a != a)
+        assert_equal(test.data, [False, False])
+        assert_equal(test.mask, [False, True])
+        assert_(test.fill_value == True)
+
+        test = (a != a[0])
+        assert_equal(test.data, [False, True])
+        assert_equal(test.mask, [False, True])
+        assert_(test.fill_value == True)
+
+        b = array([0, 1], dtype=dt2, mask=[1, 0], fill_value=fill)
+        test = (a != b)
+        assert_equal(test.data, [True, True])
+        assert_equal(test.mask, [True, True])
+        assert_(test.fill_value == True)
+
+        test = (a[0] != b)
+        assert_equal(test.data, [True, True])
+        assert_equal(test.mask, [True, False])
+        assert_(test.fill_value == True)
+
+        test = (b != a[0])
+        assert_equal(test.data, [True, True])
+        assert_equal(test.mask, [True, False])
+        assert_(test.fill_value == True)
+
+    @pytest.mark.parametrize('dt1', num_dts, ids=num_ids)
+    @pytest.mark.parametrize('dt2', num_dts, ids=num_ids)
+    @pytest.mark.parametrize('fill', [None, 1])
+    @pytest.mark.parametrize('op',
+            [operator.le, operator.lt, operator.ge, operator.gt])
+    def test_comparisons_for_numeric(self, op, dt1, dt2, fill):
+        # Test the equality of structured arrays
+        a = array([0, 1], dtype=dt1, mask=[0, 1], fill_value=fill)
+
+        test = op(a, a)
+        assert_equal(test.data, op(a._data, a._data))
+        assert_equal(test.mask, [False, True])
+        assert_(test.fill_value == True)
+
+        test = op(a, a[0])
+        assert_equal(test.data, op(a._data, a._data[0]))
+        assert_equal(test.mask, [False, True])
+        assert_(test.fill_value == True)
+
+        b = array([0, 1], dtype=dt2, mask=[1, 0], fill_value=fill)
+        test = op(a, b)
+        assert_equal(test.data, op(a._data, b._data))
+        assert_equal(test.mask, [True, True])
+        assert_(test.fill_value == True)
+
+        test = op(a[0], b)
+        assert_equal(test.data, op(a._data[0], b._data))
+        assert_equal(test.mask, [True, False])
+        assert_(test.fill_value == True)
+
+        test = op(b, a[0])
+        assert_equal(test.data, op(b._data, a._data[0]))
+        assert_equal(test.mask, [True, False])
+        assert_(test.fill_value == True)
+
+    @pytest.mark.parametrize('op',
+            [operator.le, operator.lt, operator.ge, operator.gt])
+    @pytest.mark.parametrize('fill', [None, "N/A"])
+    def test_comparisons_strings(self, op, fill):
+        # See gh-21770, mask propagation is broken for strings (and some other
+        # cases) so we explicitly test strings here.
+        # In principle only == and != may need special handling...
+        ma1 = masked_array(["a", "b", "cde"], mask=[0, 1, 0], fill_value=fill)
+        ma2 = masked_array(["cde", "b", "a"], mask=[0, 1, 0], fill_value=fill)
+        assert_equal(op(ma1, ma2)._data, op(ma1._data, ma2._data))
+
+    def test_eq_with_None(self):
+        # Really, comparisons with None should not be done, but check them
+        # anyway. Note that pep8 will flag these tests.
+        # Deprecation is in place for arrays, and when it happens this
+        # test will fail (and have to be changed accordingly).
+
+        # With partial mask
+        with suppress_warnings() as sup:
+            sup.filter(FutureWarning, "Comparison to `None`")
+            a = array([None, 1], mask=[0, 1])
+            assert_equal(a == None, array([True, False], mask=[0, 1]))
+            assert_equal(a.data == None, [True, False])
+            assert_equal(a != None, array([False, True], mask=[0, 1]))
+            # With nomask
+            a = array([None, 1], mask=False)
+            assert_equal(a == None, [True, False])
+            assert_equal(a != None, [False, True])
+            # With complete mask
+            a = array([None, 2], mask=True)
+            assert_equal(a == None, array([False, True], mask=True))
+            assert_equal(a != None, array([True, False], mask=True))
+            # Fully masked, even comparison to None should return "masked"
+            a = masked
+            assert_equal(a == None, masked)
+
+    def test_eq_with_scalar(self):
+        a = array(1)
+        assert_equal(a == 1, True)
+        assert_equal(a == 0, False)
+        assert_equal(a != 1, False)
+        assert_equal(a != 0, True)
+        b = array(1, mask=True)
+        assert_equal(b == 0, masked)
+        assert_equal(b == 1, masked)
+        assert_equal(b != 0, masked)
+        assert_equal(b != 1, masked)
+
+    def test_eq_different_dimensions(self):
+        m1 = array([1, 1], mask=[0, 1])
+        # test comparison with both masked and regular arrays.
+        for m2 in (array([[0, 1], [1, 2]]),
+                   np.array([[0, 1], [1, 2]])):
+            test = (m1 == m2)
+            assert_equal(test.data, [[False, False],
+                                     [True, False]])
+            assert_equal(test.mask, [[False, True],
+                                     [False, True]])
+
+    def test_numpyarithmetic(self):
+        # Check that the mask is not back-propagated when using numpy functions
+        a = masked_array([-1, 0, 1, 2, 3], mask=[0, 0, 0, 0, 1])
+        control = masked_array([np.nan, np.nan, 0, np.log(2), -1],
+                               mask=[1, 1, 0, 0, 1])
+
+        test = log(a)
+        assert_equal(test, control)
+        assert_equal(test.mask, control.mask)
+        assert_equal(a.mask, [0, 0, 0, 0, 1])
+
+        test = np.log(a)
+        assert_equal(test, control)
+        assert_equal(test.mask, control.mask)
+        assert_equal(a.mask, [0, 0, 0, 0, 1])
+
+
+class TestMaskedArrayAttributes:
+
+    def test_keepmask(self):
+        # Tests the keep mask flag
+        x = masked_array([1, 2, 3], mask=[1, 0, 0])
+        mx = masked_array(x)
+        assert_equal(mx.mask, x.mask)
+        mx = masked_array(x, mask=[0, 1, 0], keep_mask=False)
+        assert_equal(mx.mask, [0, 1, 0])
+        mx = masked_array(x, mask=[0, 1, 0], keep_mask=True)
+        assert_equal(mx.mask, [1, 1, 0])
+        # We default to true
+        mx = masked_array(x, mask=[0, 1, 0])
+        assert_equal(mx.mask, [1, 1, 0])
+
+    def test_hardmask(self):
+        # Test hard_mask
+        d = arange(5)
+        n = [0, 0, 0, 1, 1]
+        m = make_mask(n)
+        xh = array(d, mask=m, hard_mask=True)
+        # We need to copy, to avoid updating d in xh !
+        xs = array(d, mask=m, hard_mask=False, copy=True)
+        xh[[1, 4]] = [10, 40]
+        xs[[1, 4]] = [10, 40]
+        assert_equal(xh._data, [0, 10, 2, 3, 4])
+        assert_equal(xs._data, [0, 10, 2, 3, 40])
+        assert_equal(xs.mask, [0, 0, 0, 1, 0])
+        assert_(xh._hardmask)
+        assert_(not xs._hardmask)
+        xh[1:4] = [10, 20, 30]
+        xs[1:4] = [10, 20, 30]
+        assert_equal(xh._data, [0, 10, 20, 3, 4])
+        assert_equal(xs._data, [0, 10, 20, 30, 40])
+        assert_equal(xs.mask, nomask)
+        xh[0] = masked
+        xs[0] = masked
+        assert_equal(xh.mask, [1, 0, 0, 1, 1])
+        assert_equal(xs.mask, [1, 0, 0, 0, 0])
+        xh[:] = 1
+        xs[:] = 1
+        assert_equal(xh._data, [0, 1, 1, 3, 4])
+        assert_equal(xs._data, [1, 1, 1, 1, 1])
+        assert_equal(xh.mask, [1, 0, 0, 1, 1])
+        assert_equal(xs.mask, nomask)
+        # Switch to soft mask
+        xh.soften_mask()
+        xh[:] = arange(5)
+        assert_equal(xh._data, [0, 1, 2, 3, 4])
+        assert_equal(xh.mask, nomask)
+        # Switch back to hard mask
+        xh.harden_mask()
+        xh[xh < 3] = masked
+        assert_equal(xh._data, [0, 1, 2, 3, 4])
+        assert_equal(xh._mask, [1, 1, 1, 0, 0])
+        xh[filled(xh > 1, False)] = 5
+        assert_equal(xh._data, [0, 1, 2, 5, 5])
+        assert_equal(xh._mask, [1, 1, 1, 0, 0])
+
+        xh = array([[1, 2], [3, 4]], mask=[[1, 0], [0, 0]], hard_mask=True)
+        xh[0] = 0
+        assert_equal(xh._data, [[1, 0], [3, 4]])
+        assert_equal(xh._mask, [[1, 0], [0, 0]])
+        xh[-1, -1] = 5
+        assert_equal(xh._data, [[1, 0], [3, 5]])
+        assert_equal(xh._mask, [[1, 0], [0, 0]])
+        xh[filled(xh < 5, False)] = 2
+        assert_equal(xh._data, [[1, 2], [2, 5]])
+        assert_equal(xh._mask, [[1, 0], [0, 0]])
+
+    def test_hardmask_again(self):
+        # Another test of hardmask
+        d = arange(5)
+        n = [0, 0, 0, 1, 1]
+        m = make_mask(n)
+        xh = array(d, mask=m, hard_mask=True)
+        xh[4:5] = 999
+        xh[0:1] = 999
+        assert_equal(xh._data, [999, 1, 2, 3, 4])
+
+    def test_hardmask_oncemore_yay(self):
+        # OK, yet another test of hardmask
+        # Make sure that harden_mask/soften_mask//unshare_mask returns self
+        a = array([1, 2, 3], mask=[1, 0, 0])
+        b = a.harden_mask()
+        assert_equal(a, b)
+        b[0] = 0
+        assert_equal(a, b)
+        assert_equal(b, array([1, 2, 3], mask=[1, 0, 0]))
+        a = b.soften_mask()
+        a[0] = 0
+        assert_equal(a, b)
+        assert_equal(b, array([0, 2, 3], mask=[0, 0, 0]))
+
+    def test_smallmask(self):
+        # Checks the behaviour of _smallmask
+        a = arange(10)
+        a[1] = masked
+        a[1] = 1
+        assert_equal(a._mask, nomask)
+        a = arange(10)
+        a._smallmask = False
+        a[1] = masked
+        a[1] = 1
+        assert_equal(a._mask, zeros(10))
+
+    def test_shrink_mask(self):
+        # Tests .shrink_mask()
+        a = array([1, 2, 3], mask=[0, 0, 0])
+        b = a.shrink_mask()
+        assert_equal(a, b)
+        assert_equal(a.mask, nomask)
+
+        # Mask cannot be shrunk on structured types, so is a no-op
+        a = np.ma.array([(1, 2.0)], [('a', int), ('b', float)])
+        b = a.copy()
+        a.shrink_mask()
+        assert_equal(a.mask, b.mask)
+
+    def test_flat(self):
+        # Test that flat can return all types of items [#4585, #4615]
+        # test 2-D record array
+        # ... on structured array w/ masked records
+        x = array([[(1, 1.1, 'one'), (2, 2.2, 'two'), (3, 3.3, 'thr')],
+                   [(4, 4.4, 'fou'), (5, 5.5, 'fiv'), (6, 6.6, 'six')]],
+                  dtype=[('a', int), ('b', float), ('c', '|S8')])
+        x['a'][0, 1] = masked
+        x['b'][1, 0] = masked
+        x['c'][0, 2] = masked
+        x[-1, -1] = masked
+        xflat = x.flat
+        assert_equal(xflat[0], x[0, 0])
+        assert_equal(xflat[1], x[0, 1])
+        assert_equal(xflat[2], x[0, 2])
+        assert_equal(xflat[:3], x[0])
+        assert_equal(xflat[3], x[1, 0])
+        assert_equal(xflat[4], x[1, 1])
+        assert_equal(xflat[5], x[1, 2])
+        assert_equal(xflat[3:], x[1])
+        assert_equal(xflat[-1], x[-1, -1])
+        i = 0
+        j = 0
+        for xf in xflat:
+            assert_equal(xf, x[j, i])
+            i += 1
+            if i >= x.shape[-1]:
+                i = 0
+                j += 1
+
+    def test_assign_dtype(self):
+        # check that the mask's dtype is updated when dtype is changed
+        a = np.zeros(4, dtype='f4,i4')
+
+        m = np.ma.array(a)
+        m.dtype = np.dtype('f4')
+        repr(m)  # raises?
+        assert_equal(m.dtype, np.dtype('f4'))
+
+        # check that dtype changes that change shape of mask too much
+        # are not allowed
+        def assign():
+            m = np.ma.array(a)
+            m.dtype = np.dtype('f8')
+        assert_raises(ValueError, assign)
+
+        b = a.view(dtype='f4', type=np.ma.MaskedArray)  # raises?
+        assert_equal(b.dtype, np.dtype('f4'))
+
+        # check that nomask is preserved
+        a = np.zeros(4, dtype='f4')
+        m = np.ma.array(a)
+        m.dtype = np.dtype('f4,i4')
+        assert_equal(m.dtype, np.dtype('f4,i4'))
+        assert_equal(m._mask, np.ma.nomask)
+
+
+class TestFillingValues:
+
+    def test_check_on_scalar(self):
+        # Test _check_fill_value set to valid and invalid values
+        _check_fill_value = np.ma.core._check_fill_value
+
+        fval = _check_fill_value(0, int)
+        assert_equal(fval, 0)
+        fval = _check_fill_value(None, int)
+        assert_equal(fval, default_fill_value(0))
+
+        fval = _check_fill_value(0, "|S3")
+        assert_equal(fval, b"0")
+        fval = _check_fill_value(None, "|S3")
+        assert_equal(fval, default_fill_value(b"camelot!"))
+        assert_raises(TypeError, _check_fill_value, 1e+20, int)
+        assert_raises(TypeError, _check_fill_value, 'stuff', int)
+
+    def test_check_on_fields(self):
+        # Tests _check_fill_value with records
+        _check_fill_value = np.ma.core._check_fill_value
+        ndtype = [('a', int), ('b', float), ('c', "|S3")]
+        # A check on a list should return a single record
+        fval = _check_fill_value([-999, -12345678.9, "???"], ndtype)
+        assert_(isinstance(fval, ndarray))
+        assert_equal(fval.item(), [-999, -12345678.9, b"???"])
+        # A check on None should output the defaults
+        fval = _check_fill_value(None, ndtype)
+        assert_(isinstance(fval, ndarray))
+        assert_equal(fval.item(), [default_fill_value(0),
+                                   default_fill_value(0.),
+                                   asbytes(default_fill_value("0"))])
+        #.....Using a structured type as fill_value should work
+        fill_val = np.array((-999, -12345678.9, "???"), dtype=ndtype)
+        fval = _check_fill_value(fill_val, ndtype)
+        assert_(isinstance(fval, ndarray))
+        assert_equal(fval.item(), [-999, -12345678.9, b"???"])
+
+        #.....Using a flexible type w/ a different type shouldn't matter
+        # BEHAVIOR in 1.5 and earlier, and 1.13 and later: match structured
+        # types by position
+        fill_val = np.array((-999, -12345678.9, "???"),
+                            dtype=[("A", int), ("B", float), ("C", "|S3")])
+        fval = _check_fill_value(fill_val, ndtype)
+        assert_(isinstance(fval, ndarray))
+        assert_equal(fval.item(), [-999, -12345678.9, b"???"])
+
+        #.....Using an object-array shouldn't matter either
+        fill_val = np.ndarray(shape=(1,), dtype=object)
+        fill_val[0] = (-999, -12345678.9, b"???")
+        fval = _check_fill_value(fill_val, object)
+        assert_(isinstance(fval, ndarray))
+        assert_equal(fval.item(), [-999, -12345678.9, b"???"])
+        # NOTE: This test was never run properly as "fill_value" rather than
+        # "fill_val" was assigned.  Written properly, it fails.
+        #fill_val = np.array((-999, -12345678.9, "???"))
+        #fval = _check_fill_value(fill_val, ndtype)
+        #assert_(isinstance(fval, ndarray))
+        #assert_equal(fval.item(), [-999, -12345678.9, b"???"])
+        #.....One-field-only flexible type should work as well
+        ndtype = [("a", int)]
+        fval = _check_fill_value(-999999999, ndtype)
+        assert_(isinstance(fval, ndarray))
+        assert_equal(fval.item(), (-999999999,))
+
+    def test_fillvalue_conversion(self):
+        # Tests the behavior of fill_value during conversion
+        # We had a tailored comment to make sure special attributes are
+        # properly dealt with
+        a = array([b'3', b'4', b'5'])
+        a._optinfo.update({'comment':"updated!"})
+
+        b = array(a, dtype=int)
+        assert_equal(b._data, [3, 4, 5])
+        assert_equal(b.fill_value, default_fill_value(0))
+
+        b = array(a, dtype=float)
+        assert_equal(b._data, [3, 4, 5])
+        assert_equal(b.fill_value, default_fill_value(0.))
+
+        b = a.astype(int)
+        assert_equal(b._data, [3, 4, 5])
+        assert_equal(b.fill_value, default_fill_value(0))
+        assert_equal(b._optinfo['comment'], "updated!")
+
+        b = a.astype([('a', '|S3')])
+        assert_equal(b['a']._data, a._data)
+        assert_equal(b['a'].fill_value, a.fill_value)
+
+    def test_default_fill_value(self):
+        # check all calling conventions
+        f1 = default_fill_value(1.)
+        f2 = default_fill_value(np.array(1.))
+        f3 = default_fill_value(np.array(1.).dtype)
+        assert_equal(f1, f2)
+        assert_equal(f1, f3)
+
+    def test_default_fill_value_structured(self):
+        fields = array([(1, 1, 1)],
+                      dtype=[('i', int), ('s', '|S8'), ('f', float)])
+
+        f1 = default_fill_value(fields)
+        f2 = default_fill_value(fields.dtype)
+        expected = np.array((default_fill_value(0),
+                             default_fill_value('0'),
+                             default_fill_value(0.)), dtype=fields.dtype)
+        assert_equal(f1, expected)
+        assert_equal(f2, expected)
+
+    def test_default_fill_value_void(self):
+        dt = np.dtype([('v', 'V7')])
+        f = default_fill_value(dt)
+        assert_equal(f['v'], np.array(default_fill_value(dt['v']), dt['v']))
+
+    def test_fillvalue(self):
+        # Yet more fun with the fill_value
+        data = masked_array([1, 2, 3], fill_value=-999)
+        series = data[[0, 2, 1]]
+        assert_equal(series._fill_value, data._fill_value)
+
+        mtype = [('f', float), ('s', '|S3')]
+        x = array([(1, 'a'), (2, 'b'), (pi, 'pi')], dtype=mtype)
+        x.fill_value = 999
+        assert_equal(x.fill_value.item(), [999., b'999'])
+        assert_equal(x['f'].fill_value, 999)
+        assert_equal(x['s'].fill_value, b'999')
+
+        x.fill_value = (9, '???')
+        assert_equal(x.fill_value.item(), (9, b'???'))
+        assert_equal(x['f'].fill_value, 9)
+        assert_equal(x['s'].fill_value, b'???')
+
+        x = array([1, 2, 3.1])
+        x.fill_value = 999
+        assert_equal(np.asarray(x.fill_value).dtype, float)
+        assert_equal(x.fill_value, 999.)
+        assert_equal(x._fill_value, np.array(999.))
+
+    def test_subarray_fillvalue(self):
+        # gh-10483   test multi-field index fill value
+        fields = array([(1, 1, 1)],
+                      dtype=[('i', int), ('s', '|S8'), ('f', float)])
+        with suppress_warnings() as sup:
+            sup.filter(FutureWarning, "Numpy has detected")
+            subfields = fields[['i', 'f']]
+            assert_equal(tuple(subfields.fill_value), (999999, 1.e+20))
+            # test comparison does not raise:
+            subfields[1:] == subfields[:-1]
+
+    def test_fillvalue_exotic_dtype(self):
+        # Tests yet more exotic flexible dtypes
+        _check_fill_value = np.ma.core._check_fill_value
+        ndtype = [('i', int), ('s', '|S8'), ('f', float)]
+        control = np.array((default_fill_value(0),
+                            default_fill_value('0'),
+                            default_fill_value(0.),),
+                           dtype=ndtype)
+        assert_equal(_check_fill_value(None, ndtype), control)
+        # The shape shouldn't matter
+        ndtype = [('f0', float, (2, 2))]
+        control = np.array((default_fill_value(0.),),
+                           dtype=[('f0', float)]).astype(ndtype)
+        assert_equal(_check_fill_value(None, ndtype), control)
+        control = np.array((0,), dtype=[('f0', float)]).astype(ndtype)
+        assert_equal(_check_fill_value(0, ndtype), control)
+
+        ndtype = np.dtype("int, (2,3)float, float")
+        control = np.array((default_fill_value(0),
+                            default_fill_value(0.),
+                            default_fill_value(0.),),
+                           dtype="int, float, float").astype(ndtype)
+        test = _check_fill_value(None, ndtype)
+        assert_equal(test, control)
+        control = np.array((0, 0, 0), dtype="int, float, float").astype(ndtype)
+        assert_equal(_check_fill_value(0, ndtype), control)
+        # but when indexing, fill value should become scalar not tuple
+        # See issue #6723
+        M = masked_array(control)
+        assert_equal(M["f1"].fill_value.ndim, 0)
+
+    def test_fillvalue_datetime_timedelta(self):
+        # Test default fillvalue for datetime64 and timedelta64 types.
+        # See issue #4476, this would return '?' which would cause errors
+        # elsewhere
+
+        for timecode in ("as", "fs", "ps", "ns", "us", "ms", "s", "m",
+                         "h", "D", "W", "M", "Y"):
+            control = numpy.datetime64("NaT", timecode)
+            test = default_fill_value(numpy.dtype(" 0
+
+            # test different unary domains
+            sqrt(m)
+            log(m)
+            tan(m)
+            arcsin(m)
+            arccos(m)
+            arccosh(m)
+
+            # test binary domains
+            divide(m, 2)
+
+            # also check that allclose uses ma ufuncs, to avoid warning
+            allclose(m, 0.5)
+
+class TestMaskedArrayInPlaceArithmetic:
+    # Test MaskedArray Arithmetic
+
+    def setup_method(self):
+        x = arange(10)
+        y = arange(10)
+        xm = arange(10)
+        xm[2] = masked
+        self.intdata = (x, y, xm)
+        self.floatdata = (x.astype(float), y.astype(float), xm.astype(float))
+        self.othertypes = np.typecodes['AllInteger'] + np.typecodes['AllFloat']
+        self.othertypes = [np.dtype(_).type for _ in self.othertypes]
+        self.uint8data = (
+            x.astype(np.uint8),
+            y.astype(np.uint8),
+            xm.astype(np.uint8)
+        )
+
+    def test_inplace_addition_scalar(self):
+        # Test of inplace additions
+        (x, y, xm) = self.intdata
+        xm[2] = masked
+        x += 1
+        assert_equal(x, y + 1)
+        xm += 1
+        assert_equal(xm, y + 1)
+
+        (x, _, xm) = self.floatdata
+        id1 = x.data.ctypes.data
+        x += 1.
+        assert_(id1 == x.data.ctypes.data)
+        assert_equal(x, y + 1.)
+
+    def test_inplace_addition_array(self):
+        # Test of inplace additions
+        (x, y, xm) = self.intdata
+        m = xm.mask
+        a = arange(10, dtype=np.int16)
+        a[-1] = masked
+        x += a
+        xm += a
+        assert_equal(x, y + a)
+        assert_equal(xm, y + a)
+        assert_equal(xm.mask, mask_or(m, a.mask))
+
+    def test_inplace_subtraction_scalar(self):
+        # Test of inplace subtractions
+        (x, y, xm) = self.intdata
+        x -= 1
+        assert_equal(x, y - 1)
+        xm -= 1
+        assert_equal(xm, y - 1)
+
+    def test_inplace_subtraction_array(self):
+        # Test of inplace subtractions
+        (x, y, xm) = self.floatdata
+        m = xm.mask
+        a = arange(10, dtype=float)
+        a[-1] = masked
+        x -= a
+        xm -= a
+        assert_equal(x, y - a)
+        assert_equal(xm, y - a)
+        assert_equal(xm.mask, mask_or(m, a.mask))
+
+    def test_inplace_multiplication_scalar(self):
+        # Test of inplace multiplication
+        (x, y, xm) = self.floatdata
+        x *= 2.0
+        assert_equal(x, y * 2)
+        xm *= 2.0
+        assert_equal(xm, y * 2)
+
+    def test_inplace_multiplication_array(self):
+        # Test of inplace multiplication
+        (x, y, xm) = self.floatdata
+        m = xm.mask
+        a = arange(10, dtype=float)
+        a[-1] = masked
+        x *= a
+        xm *= a
+        assert_equal(x, y * a)
+        assert_equal(xm, y * a)
+        assert_equal(xm.mask, mask_or(m, a.mask))
+
+    def test_inplace_division_scalar_int(self):
+        # Test of inplace division
+        (x, y, xm) = self.intdata
+        x = arange(10) * 2
+        xm = arange(10) * 2
+        xm[2] = masked
+        x //= 2
+        assert_equal(x, y)
+        xm //= 2
+        assert_equal(xm, y)
+
+    def test_inplace_division_scalar_float(self):
+        # Test of inplace division
+        (x, y, xm) = self.floatdata
+        x /= 2.0
+        assert_equal(x, y / 2.0)
+        xm /= arange(10)
+        assert_equal(xm, ones((10,)))
+
+    def test_inplace_division_array_float(self):
+        # Test of inplace division
+        (x, y, xm) = self.floatdata
+        m = xm.mask
+        a = arange(10, dtype=float)
+        a[-1] = masked
+        x /= a
+        xm /= a
+        assert_equal(x, y / a)
+        assert_equal(xm, y / a)
+        assert_equal(xm.mask, mask_or(mask_or(m, a.mask), (a == 0)))
+
+    def test_inplace_division_misc(self):
+
+        x = [1., 1., 1., -2., pi / 2., 4., 5., -10., 10., 1., 2., 3.]
+        y = [5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.]
+        m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
+        m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1]
+        xm = masked_array(x, mask=m1)
+        ym = masked_array(y, mask=m2)
+
+        z = xm / ym
+        assert_equal(z._mask, [1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1])
+        assert_equal(z._data,
+                     [1., 1., 1., -1., -pi / 2., 4., 5., 1., 1., 1., 2., 3.])
+
+        xm = xm.copy()
+        xm /= ym
+        assert_equal(xm._mask, [1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1])
+        assert_equal(z._data,
+                     [1., 1., 1., -1., -pi / 2., 4., 5., 1., 1., 1., 2., 3.])
+
+    def test_datafriendly_add(self):
+        # Test keeping data w/ (inplace) addition
+        x = array([1, 2, 3], mask=[0, 0, 1])
+        # Test add w/ scalar
+        xx = x + 1
+        assert_equal(xx.data, [2, 3, 3])
+        assert_equal(xx.mask, [0, 0, 1])
+        # Test iadd w/ scalar
+        x += 1
+        assert_equal(x.data, [2, 3, 3])
+        assert_equal(x.mask, [0, 0, 1])
+        # Test add w/ array
+        x = array([1, 2, 3], mask=[0, 0, 1])
+        xx = x + array([1, 2, 3], mask=[1, 0, 0])
+        assert_equal(xx.data, [1, 4, 3])
+        assert_equal(xx.mask, [1, 0, 1])
+        # Test iadd w/ array
+        x = array([1, 2, 3], mask=[0, 0, 1])
+        x += array([1, 2, 3], mask=[1, 0, 0])
+        assert_equal(x.data, [1, 4, 3])
+        assert_equal(x.mask, [1, 0, 1])
+
+    def test_datafriendly_sub(self):
+        # Test keeping data w/ (inplace) subtraction
+        # Test sub w/ scalar
+        x = array([1, 2, 3], mask=[0, 0, 1])
+        xx = x - 1
+        assert_equal(xx.data, [0, 1, 3])
+        assert_equal(xx.mask, [0, 0, 1])
+        # Test isub w/ scalar
+        x = array([1, 2, 3], mask=[0, 0, 1])
+        x -= 1
+        assert_equal(x.data, [0, 1, 3])
+        assert_equal(x.mask, [0, 0, 1])
+        # Test sub w/ array
+        x = array([1, 2, 3], mask=[0, 0, 1])
+        xx = x - array([1, 2, 3], mask=[1, 0, 0])
+        assert_equal(xx.data, [1, 0, 3])
+        assert_equal(xx.mask, [1, 0, 1])
+        # Test isub w/ array
+        x = array([1, 2, 3], mask=[0, 0, 1])
+        x -= array([1, 2, 3], mask=[1, 0, 0])
+        assert_equal(x.data, [1, 0, 3])
+        assert_equal(x.mask, [1, 0, 1])
+
+    def test_datafriendly_mul(self):
+        # Test keeping data w/ (inplace) multiplication
+        # Test mul w/ scalar
+        x = array([1, 2, 3], mask=[0, 0, 1])
+        xx = x * 2
+        assert_equal(xx.data, [2, 4, 3])
+        assert_equal(xx.mask, [0, 0, 1])
+        # Test imul w/ scalar
+        x = array([1, 2, 3], mask=[0, 0, 1])
+        x *= 2
+        assert_equal(x.data, [2, 4, 3])
+        assert_equal(x.mask, [0, 0, 1])
+        # Test mul w/ array
+        x = array([1, 2, 3], mask=[0, 0, 1])
+        xx = x * array([10, 20, 30], mask=[1, 0, 0])
+        assert_equal(xx.data, [1, 40, 3])
+        assert_equal(xx.mask, [1, 0, 1])
+        # Test imul w/ array
+        x = array([1, 2, 3], mask=[0, 0, 1])
+        x *= array([10, 20, 30], mask=[1, 0, 0])
+        assert_equal(x.data, [1, 40, 3])
+        assert_equal(x.mask, [1, 0, 1])
+
+    def test_datafriendly_div(self):
+        # Test keeping data w/ (inplace) division
+        # Test div on scalar
+        x = array([1, 2, 3], mask=[0, 0, 1])
+        xx = x / 2.
+        assert_equal(xx.data, [1 / 2., 2 / 2., 3])
+        assert_equal(xx.mask, [0, 0, 1])
+        # Test idiv on scalar
+        x = array([1., 2., 3.], mask=[0, 0, 1])
+        x /= 2.
+        assert_equal(x.data, [1 / 2., 2 / 2., 3])
+        assert_equal(x.mask, [0, 0, 1])
+        # Test div on array
+        x = array([1., 2., 3.], mask=[0, 0, 1])
+        xx = x / array([10., 20., 30.], mask=[1, 0, 0])
+        assert_equal(xx.data, [1., 2. / 20., 3.])
+        assert_equal(xx.mask, [1, 0, 1])
+        # Test idiv on array
+        x = array([1., 2., 3.], mask=[0, 0, 1])
+        x /= array([10., 20., 30.], mask=[1, 0, 0])
+        assert_equal(x.data, [1., 2 / 20., 3.])
+        assert_equal(x.mask, [1, 0, 1])
+
+    def test_datafriendly_pow(self):
+        # Test keeping data w/ (inplace) power
+        # Test pow on scalar
+        x = array([1., 2., 3.], mask=[0, 0, 1])
+        xx = x ** 2.5
+        assert_equal(xx.data, [1., 2. ** 2.5, 3.])
+        assert_equal(xx.mask, [0, 0, 1])
+        # Test ipow on scalar
+        x **= 2.5
+        assert_equal(x.data, [1., 2. ** 2.5, 3])
+        assert_equal(x.mask, [0, 0, 1])
+
+    def test_datafriendly_add_arrays(self):
+        a = array([[1, 1], [3, 3]])
+        b = array([1, 1], mask=[0, 0])
+        a += b
+        assert_equal(a, [[2, 2], [4, 4]])
+        if a.mask is not nomask:
+            assert_equal(a.mask, [[0, 0], [0, 0]])
+
+        a = array([[1, 1], [3, 3]])
+        b = array([1, 1], mask=[0, 1])
+        a += b
+        assert_equal(a, [[2, 2], [4, 4]])
+        assert_equal(a.mask, [[0, 1], [0, 1]])
+
+    def test_datafriendly_sub_arrays(self):
+        a = array([[1, 1], [3, 3]])
+        b = array([1, 1], mask=[0, 0])
+        a -= b
+        assert_equal(a, [[0, 0], [2, 2]])
+        if a.mask is not nomask:
+            assert_equal(a.mask, [[0, 0], [0, 0]])
+
+        a = array([[1, 1], [3, 3]])
+        b = array([1, 1], mask=[0, 1])
+        a -= b
+        assert_equal(a, [[0, 0], [2, 2]])
+        assert_equal(a.mask, [[0, 1], [0, 1]])
+
+    def test_datafriendly_mul_arrays(self):
+        a = array([[1, 1], [3, 3]])
+        b = array([1, 1], mask=[0, 0])
+        a *= b
+        assert_equal(a, [[1, 1], [3, 3]])
+        if a.mask is not nomask:
+            assert_equal(a.mask, [[0, 0], [0, 0]])
+
+        a = array([[1, 1], [3, 3]])
+        b = array([1, 1], mask=[0, 1])
+        a *= b
+        assert_equal(a, [[1, 1], [3, 3]])
+        assert_equal(a.mask, [[0, 1], [0, 1]])
+
+    def test_inplace_addition_scalar_type(self):
+        # Test of inplace additions
+        for t in self.othertypes:
+            with warnings.catch_warnings():
+                warnings.filterwarnings("error")
+                (x, y, xm) = (_.astype(t) for _ in self.uint8data)
+                xm[2] = masked
+                x += t(1)
+                assert_equal(x, y + t(1))
+                xm += t(1)
+                assert_equal(xm, y + t(1))
+
+    def test_inplace_addition_array_type(self):
+        # Test of inplace additions
+        for t in self.othertypes:
+            with warnings.catch_warnings():
+                warnings.filterwarnings("error")
+                (x, y, xm) = (_.astype(t) for _ in self.uint8data)
+                m = xm.mask
+                a = arange(10, dtype=t)
+                a[-1] = masked
+                x += a
+                xm += a
+                assert_equal(x, y + a)
+                assert_equal(xm, y + a)
+                assert_equal(xm.mask, mask_or(m, a.mask))
+
+    def test_inplace_subtraction_scalar_type(self):
+        # Test of inplace subtractions
+        for t in self.othertypes:
+            with warnings.catch_warnings():
+                warnings.filterwarnings("error")
+                (x, y, xm) = (_.astype(t) for _ in self.uint8data)
+                x -= t(1)
+                assert_equal(x, y - t(1))
+                xm -= t(1)
+                assert_equal(xm, y - t(1))
+
+    def test_inplace_subtraction_array_type(self):
+        # Test of inplace subtractions
+        for t in self.othertypes:
+            with warnings.catch_warnings():
+                warnings.filterwarnings("error")
+                (x, y, xm) = (_.astype(t) for _ in self.uint8data)
+                m = xm.mask
+                a = arange(10, dtype=t)
+                a[-1] = masked
+                x -= a
+                xm -= a
+                assert_equal(x, y - a)
+                assert_equal(xm, y - a)
+                assert_equal(xm.mask, mask_or(m, a.mask))
+
+    def test_inplace_multiplication_scalar_type(self):
+        # Test of inplace multiplication
+        for t in self.othertypes:
+            with warnings.catch_warnings():
+                warnings.filterwarnings("error")
+                (x, y, xm) = (_.astype(t) for _ in self.uint8data)
+                x *= t(2)
+                assert_equal(x, y * t(2))
+                xm *= t(2)
+                assert_equal(xm, y * t(2))
+
+    def test_inplace_multiplication_array_type(self):
+        # Test of inplace multiplication
+        for t in self.othertypes:
+            with warnings.catch_warnings():
+                warnings.filterwarnings("error")
+                (x, y, xm) = (_.astype(t) for _ in self.uint8data)
+                m = xm.mask
+                a = arange(10, dtype=t)
+                a[-1] = masked
+                x *= a
+                xm *= a
+                assert_equal(x, y * a)
+                assert_equal(xm, y * a)
+                assert_equal(xm.mask, mask_or(m, a.mask))
+
+    def test_inplace_floor_division_scalar_type(self):
+        # Test of inplace division
+        # Check for TypeError in case of unsupported types
+        unsupported = {np.dtype(t).type for t in np.typecodes["Complex"]}
+        for t in self.othertypes:
+            with warnings.catch_warnings():
+                warnings.filterwarnings("error")
+                (x, y, xm) = (_.astype(t) for _ in self.uint8data)
+                x = arange(10, dtype=t) * t(2)
+                xm = arange(10, dtype=t) * t(2)
+                xm[2] = masked
+                try:
+                    x //= t(2)
+                    xm //= t(2)
+                    assert_equal(x, y)
+                    assert_equal(xm, y)
+                except TypeError:
+                    msg = f"Supported type {t} throwing TypeError"
+                    assert t in unsupported, msg
+
+    def test_inplace_floor_division_array_type(self):
+        # Test of inplace division
+        # Check for TypeError in case of unsupported types
+        unsupported = {np.dtype(t).type for t in np.typecodes["Complex"]}
+        for t in self.othertypes:
+            with warnings.catch_warnings():
+                warnings.filterwarnings("error")
+                (x, y, xm) = (_.astype(t) for _ in self.uint8data)
+                m = xm.mask
+                a = arange(10, dtype=t)
+                a[-1] = masked
+                try:
+                    x //= a
+                    xm //= a
+                    assert_equal(x, y // a)
+                    assert_equal(xm, y // a)
+                    assert_equal(
+                        xm.mask,
+                        mask_or(mask_or(m, a.mask), (a == t(0)))
+                    )
+                except TypeError:
+                    msg = f"Supported type {t} throwing TypeError"
+                    assert t in unsupported, msg
+
+    def test_inplace_division_scalar_type(self):
+        # Test of inplace division
+        for t in self.othertypes:
+            with suppress_warnings() as sup:
+                sup.record(UserWarning)
+
+                (x, y, xm) = (_.astype(t) for _ in self.uint8data)
+                x = arange(10, dtype=t) * t(2)
+                xm = arange(10, dtype=t) * t(2)
+                xm[2] = masked
+
+                # May get a DeprecationWarning or a TypeError.
+                #
+                # This is a consequence of the fact that this is true divide
+                # and will require casting to float for calculation and
+                # casting back to the original type. This will only be raised
+                # with integers. Whether it is an error or warning is only
+                # dependent on how stringent the casting rules are.
+                #
+                # Will handle the same way.
+                try:
+                    x /= t(2)
+                    assert_equal(x, y)
+                except (DeprecationWarning, TypeError) as e:
+                    warnings.warn(str(e), stacklevel=1)
+                try:
+                    xm /= t(2)
+                    assert_equal(xm, y)
+                except (DeprecationWarning, TypeError) as e:
+                    warnings.warn(str(e), stacklevel=1)
+
+                if issubclass(t, np.integer):
+                    assert_equal(len(sup.log), 2, f'Failed on type={t}.')
+                else:
+                    assert_equal(len(sup.log), 0, f'Failed on type={t}.')
+
+    def test_inplace_division_array_type(self):
+        # Test of inplace division
+        for t in self.othertypes:
+            with suppress_warnings() as sup:
+                sup.record(UserWarning)
+                (x, y, xm) = (_.astype(t) for _ in self.uint8data)
+                m = xm.mask
+                a = arange(10, dtype=t)
+                a[-1] = masked
+
+                # May get a DeprecationWarning or a TypeError.
+                #
+                # This is a consequence of the fact that this is true divide
+                # and will require casting to float for calculation and
+                # casting back to the original type. This will only be raised
+                # with integers. Whether it is an error or warning is only
+                # dependent on how stringent the casting rules are.
+                #
+                # Will handle the same way.
+                try:
+                    x /= a
+                    assert_equal(x, y / a)
+                except (DeprecationWarning, TypeError) as e:
+                    warnings.warn(str(e), stacklevel=1)
+                try:
+                    xm /= a
+                    assert_equal(xm, y / a)
+                    assert_equal(
+                        xm.mask,
+                        mask_or(mask_or(m, a.mask), (a == t(0)))
+                    )
+                except (DeprecationWarning, TypeError) as e:
+                    warnings.warn(str(e), stacklevel=1)
+
+                if issubclass(t, np.integer):
+                    assert_equal(len(sup.log), 2, f'Failed on type={t}.')
+                else:
+                    assert_equal(len(sup.log), 0, f'Failed on type={t}.')
+
+    def test_inplace_pow_type(self):
+        # Test keeping data w/ (inplace) power
+        for t in self.othertypes:
+            with warnings.catch_warnings():
+                warnings.filterwarnings("error")
+                # Test pow on scalar
+                x = array([1, 2, 3], mask=[0, 0, 1], dtype=t)
+                xx = x ** t(2)
+                xx_r = array([1, 2 ** 2, 3], mask=[0, 0, 1], dtype=t)
+                assert_equal(xx.data, xx_r.data)
+                assert_equal(xx.mask, xx_r.mask)
+                # Test ipow on scalar
+                x **= t(2)
+                assert_equal(x.data, xx_r.data)
+                assert_equal(x.mask, xx_r.mask)
+
+
+class TestMaskedArrayMethods:
+    # Test class for miscellaneous MaskedArrays methods.
+    def setup_method(self):
+        # Base data definition.
+        x = np.array([8.375, 7.545, 8.828, 8.5, 1.757, 5.928,
+                      8.43, 7.78, 9.865, 5.878, 8.979, 4.732,
+                      3.012, 6.022, 5.095, 3.116, 5.238, 3.957,
+                      6.04, 9.63, 7.712, 3.382, 4.489, 6.479,
+                      7.189, 9.645, 5.395, 4.961, 9.894, 2.893,
+                      7.357, 9.828, 6.272, 3.758, 6.693, 0.993])
+        X = x.reshape(6, 6)
+        XX = x.reshape(3, 2, 2, 3)
+
+        m = np.array([0, 1, 0, 1, 0, 0,
+                     1, 0, 1, 1, 0, 1,
+                     0, 0, 0, 1, 0, 1,
+                     0, 0, 0, 1, 1, 1,
+                     1, 0, 0, 1, 0, 0,
+                     0, 0, 1, 0, 1, 0])
+        mx = array(data=x, mask=m)
+        mX = array(data=X, mask=m.reshape(X.shape))
+        mXX = array(data=XX, mask=m.reshape(XX.shape))
+
+        m2 = np.array([1, 1, 0, 1, 0, 0,
+                      1, 1, 1, 1, 0, 1,
+                      0, 0, 1, 1, 0, 1,
+                      0, 0, 0, 1, 1, 1,
+                      1, 0, 0, 1, 1, 0,
+                      0, 0, 1, 0, 1, 1])
+        m2x = array(data=x, mask=m2)
+        m2X = array(data=X, mask=m2.reshape(X.shape))
+        m2XX = array(data=XX, mask=m2.reshape(XX.shape))
+        self.d = (x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX)
+
+    def test_generic_methods(self):
+        # Tests some MaskedArray methods.
+        a = array([1, 3, 2])
+        assert_equal(a.any(), a._data.any())
+        assert_equal(a.all(), a._data.all())
+        assert_equal(a.argmax(), a._data.argmax())
+        assert_equal(a.argmin(), a._data.argmin())
+        assert_equal(a.choose(0, 1, 2, 3, 4), a._data.choose(0, 1, 2, 3, 4))
+        assert_equal(a.compress([1, 0, 1]), a._data.compress([1, 0, 1]))
+        assert_equal(a.conj(), a._data.conj())
+        assert_equal(a.conjugate(), a._data.conjugate())
+
+        m = array([[1, 2], [3, 4]])
+        assert_equal(m.diagonal(), m._data.diagonal())
+        assert_equal(a.sum(), a._data.sum())
+        assert_equal(a.take([1, 2]), a._data.take([1, 2]))
+        assert_equal(m.transpose(), m._data.transpose())
+
+    def test_allclose(self):
+        # Tests allclose on arrays
+        a = np.random.rand(10)
+        b = a + np.random.rand(10) * 1e-8
+        assert_(allclose(a, b))
+        # Test allclose w/ infs
+        a[0] = np.inf
+        assert_(not allclose(a, b))
+        b[0] = np.inf
+        assert_(allclose(a, b))
+        # Test allclose w/ masked
+        a = masked_array(a)
+        a[-1] = masked
+        assert_(allclose(a, b, masked_equal=True))
+        assert_(not allclose(a, b, masked_equal=False))
+        # Test comparison w/ scalar
+        a *= 1e-8
+        a[0] = 0
+        assert_(allclose(a, 0, masked_equal=True))
+
+        # Test that the function works for MIN_INT integer typed arrays
+        a = masked_array([np.iinfo(np.int_).min], dtype=np.int_)
+        assert_(allclose(a, a))
+
+    def test_allclose_timedelta(self):
+        # Allclose currently works for timedelta64 as long as `atol` is
+        # an integer or also a timedelta64
+        a = np.array([[1, 2, 3, 4]], dtype="m8[ns]")
+        assert allclose(a, a, atol=0)
+        assert allclose(a, a, atol=np.timedelta64(1, "ns"))
+
+    def test_allany(self):
+        # Checks the any/all methods/functions.
+        x = np.array([[0.13, 0.26, 0.90],
+                      [0.28, 0.33, 0.63],
+                      [0.31, 0.87, 0.70]])
+        m = np.array([[True, False, False],
+                      [False, False, False],
+                      [True, True, False]], dtype=np.bool_)
+        mx = masked_array(x, mask=m)
+        mxbig = (mx > 0.5)
+        mxsmall = (mx < 0.5)
+
+        assert_(not mxbig.all())
+        assert_(mxbig.any())
+        assert_equal(mxbig.all(0), [False, False, True])
+        assert_equal(mxbig.all(1), [False, False, True])
+        assert_equal(mxbig.any(0), [False, False, True])
+        assert_equal(mxbig.any(1), [True, True, True])
+
+        assert_(not mxsmall.all())
+        assert_(mxsmall.any())
+        assert_equal(mxsmall.all(0), [True, True, False])
+        assert_equal(mxsmall.all(1), [False, False, False])
+        assert_equal(mxsmall.any(0), [True, True, False])
+        assert_equal(mxsmall.any(1), [True, True, False])
+
+    def test_allany_oddities(self):
+        # Some fun with all and any
+        store = empty((), dtype=bool)
+        full = array([1, 2, 3], mask=True)
+
+        assert_(full.all() is masked)
+        full.all(out=store)
+        assert_(store)
+        assert_(store._mask, True)
+        assert_(store is not masked)
+
+        store = empty((), dtype=bool)
+        assert_(full.any() is masked)
+        full.any(out=store)
+        assert_(not store)
+        assert_(store._mask, True)
+        assert_(store is not masked)
+
+    def test_argmax_argmin(self):
+        # Tests argmin & argmax on MaskedArrays.
+        (x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX) = self.d
+
+        assert_equal(mx.argmin(), 35)
+        assert_equal(mX.argmin(), 35)
+        assert_equal(m2x.argmin(), 4)
+        assert_equal(m2X.argmin(), 4)
+        assert_equal(mx.argmax(), 28)
+        assert_equal(mX.argmax(), 28)
+        assert_equal(m2x.argmax(), 31)
+        assert_equal(m2X.argmax(), 31)
+
+        assert_equal(mX.argmin(0), [2, 2, 2, 5, 0, 5])
+        assert_equal(m2X.argmin(0), [2, 2, 4, 5, 0, 4])
+        assert_equal(mX.argmax(0), [0, 5, 0, 5, 4, 0])
+        assert_equal(m2X.argmax(0), [5, 5, 0, 5, 1, 0])
+
+        assert_equal(mX.argmin(1), [4, 1, 0, 0, 5, 5, ])
+        assert_equal(m2X.argmin(1), [4, 4, 0, 0, 5, 3])
+        assert_equal(mX.argmax(1), [2, 4, 1, 1, 4, 1])
+        assert_equal(m2X.argmax(1), [2, 4, 1, 1, 1, 1])
+
+    def test_clip(self):
+        # Tests clip on MaskedArrays.
+        x = np.array([8.375, 7.545, 8.828, 8.5, 1.757, 5.928,
+                      8.43, 7.78, 9.865, 5.878, 8.979, 4.732,
+                      3.012, 6.022, 5.095, 3.116, 5.238, 3.957,
+                      6.04, 9.63, 7.712, 3.382, 4.489, 6.479,
+                      7.189, 9.645, 5.395, 4.961, 9.894, 2.893,
+                      7.357, 9.828, 6.272, 3.758, 6.693, 0.993])
+        m = np.array([0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1,
+                      0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1,
+                      1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0])
+        mx = array(x, mask=m)
+        clipped = mx.clip(2, 8)
+        assert_equal(clipped.mask, mx.mask)
+        assert_equal(clipped._data, x.clip(2, 8))
+        assert_equal(clipped._data, mx._data.clip(2, 8))
+
+    def test_clip_out(self):
+        # gh-14140
+        a = np.arange(10)
+        m = np.ma.MaskedArray(a, mask=[0, 1] * 5)
+        m.clip(0, 5, out=m)
+        assert_equal(m.mask, [0, 1] * 5)
+
+    def test_compress(self):
+        # test compress
+        a = masked_array([1., 2., 3., 4., 5.], fill_value=9999)
+        condition = (a > 1.5) & (a < 3.5)
+        assert_equal(a.compress(condition), [2., 3.])
+
+        a[[2, 3]] = masked
+        b = a.compress(condition)
+        assert_equal(b._data, [2., 3.])
+        assert_equal(b._mask, [0, 1])
+        assert_equal(b.fill_value, 9999)
+        assert_equal(b, a[condition])
+
+        condition = (a < 4.)
+        b = a.compress(condition)
+        assert_equal(b._data, [1., 2., 3.])
+        assert_equal(b._mask, [0, 0, 1])
+        assert_equal(b.fill_value, 9999)
+        assert_equal(b, a[condition])
+
+        a = masked_array([[10, 20, 30], [40, 50, 60]],
+                         mask=[[0, 0, 1], [1, 0, 0]])
+        b = a.compress(a.ravel() >= 22)
+        assert_equal(b._data, [30, 40, 50, 60])
+        assert_equal(b._mask, [1, 1, 0, 0])
+
+        x = np.array([3, 1, 2])
+        b = a.compress(x >= 2, axis=1)
+        assert_equal(b._data, [[10, 30], [40, 60]])
+        assert_equal(b._mask, [[0, 1], [1, 0]])
+
+    def test_compressed(self):
+        # Tests compressed
+        a = array([1, 2, 3, 4], mask=[0, 0, 0, 0])
+        b = a.compressed()
+        assert_equal(b, a)
+        a[0] = masked
+        b = a.compressed()
+        assert_equal(b, [2, 3, 4])
+
+    def test_empty(self):
+        # Tests empty/like
+        datatype = [('a', int), ('b', float), ('c', '|S8')]
+        a = masked_array([(1, 1.1, '1.1'), (2, 2.2, '2.2'), (3, 3.3, '3.3')],
+                         dtype=datatype)
+        assert_equal(len(a.fill_value.item()), len(datatype))
+
+        b = empty_like(a)
+        assert_equal(b.shape, a.shape)
+        assert_equal(b.fill_value, a.fill_value)
+
+        b = empty(len(a), dtype=datatype)
+        assert_equal(b.shape, a.shape)
+        assert_equal(b.fill_value, a.fill_value)
+
+        # check empty_like mask handling
+        a = masked_array([1, 2, 3], mask=[False, True, False])
+        b = empty_like(a)
+        assert_(not np.may_share_memory(a.mask, b.mask))
+        b = a.view(masked_array)
+        assert_(np.may_share_memory(a.mask, b.mask))
+
+    def test_zeros(self):
+        # Tests zeros/like
+        datatype = [('a', int), ('b', float), ('c', '|S8')]
+        a = masked_array([(1, 1.1, '1.1'), (2, 2.2, '2.2'), (3, 3.3, '3.3')],
+                         dtype=datatype)
+        assert_equal(len(a.fill_value.item()), len(datatype))
+
+        b = zeros(len(a), dtype=datatype)
+        assert_equal(b.shape, a.shape)
+        assert_equal(b.fill_value, a.fill_value)
+
+        b = zeros_like(a)
+        assert_equal(b.shape, a.shape)
+        assert_equal(b.fill_value, a.fill_value)
+
+        # check zeros_like mask handling
+        a = masked_array([1, 2, 3], mask=[False, True, False])
+        b = zeros_like(a)
+        assert_(not np.may_share_memory(a.mask, b.mask))
+        b = a.view()
+        assert_(np.may_share_memory(a.mask, b.mask))
+
+    def test_ones(self):
+        # Tests ones/like
+        datatype = [('a', int), ('b', float), ('c', '|S8')]
+        a = masked_array([(1, 1.1, '1.1'), (2, 2.2, '2.2'), (3, 3.3, '3.3')],
+                         dtype=datatype)
+        assert_equal(len(a.fill_value.item()), len(datatype))
+
+        b = ones(len(a), dtype=datatype)
+        assert_equal(b.shape, a.shape)
+        assert_equal(b.fill_value, a.fill_value)
+
+        b = ones_like(a)
+        assert_equal(b.shape, a.shape)
+        assert_equal(b.fill_value, a.fill_value)
+
+        # check ones_like mask handling
+        a = masked_array([1, 2, 3], mask=[False, True, False])
+        b = ones_like(a)
+        assert_(not np.may_share_memory(a.mask, b.mask))
+        b = a.view()
+        assert_(np.may_share_memory(a.mask, b.mask))
+
+    @suppress_copy_mask_on_assignment
+    def test_put(self):
+        # Tests put.
+        d = arange(5)
+        n = [0, 0, 0, 1, 1]
+        m = make_mask(n)
+        x = array(d, mask=m)
+        assert_(x[3] is masked)
+        assert_(x[4] is masked)
+        x[[1, 4]] = [10, 40]
+        assert_(x[3] is masked)
+        assert_(x[4] is not masked)
+        assert_equal(x, [0, 10, 2, -1, 40])
+
+        x = masked_array(arange(10), mask=[1, 0, 0, 0, 0] * 2)
+        i = [0, 2, 4, 6]
+        x.put(i, [6, 4, 2, 0])
+        assert_equal(x, asarray([6, 1, 4, 3, 2, 5, 0, 7, 8, 9, ]))
+        assert_equal(x.mask, [0, 0, 0, 0, 0, 1, 0, 0, 0, 0])
+        x.put(i, masked_array([0, 2, 4, 6], [1, 0, 1, 0]))
+        assert_array_equal(x, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ])
+        assert_equal(x.mask, [1, 0, 0, 0, 1, 1, 0, 0, 0, 0])
+
+        x = masked_array(arange(10), mask=[1, 0, 0, 0, 0] * 2)
+        put(x, i, [6, 4, 2, 0])
+        assert_equal(x, asarray([6, 1, 4, 3, 2, 5, 0, 7, 8, 9, ]))
+        assert_equal(x.mask, [0, 0, 0, 0, 0, 1, 0, 0, 0, 0])
+        put(x, i, masked_array([0, 2, 4, 6], [1, 0, 1, 0]))
+        assert_array_equal(x, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ])
+        assert_equal(x.mask, [1, 0, 0, 0, 1, 1, 0, 0, 0, 0])
+
+    def test_put_nomask(self):
+        # GitHub issue 6425
+        x = zeros(10)
+        z = array([3., -1.], mask=[False, True])
+
+        x.put([1, 2], z)
+        assert_(x[0] is not masked)
+        assert_equal(x[0], 0)
+        assert_(x[1] is not masked)
+        assert_equal(x[1], 3)
+        assert_(x[2] is masked)
+        assert_(x[3] is not masked)
+        assert_equal(x[3], 0)
+
+    def test_put_hardmask(self):
+        # Tests put on hardmask
+        d = arange(5)
+        n = [0, 0, 0, 1, 1]
+        m = make_mask(n)
+        xh = array(d + 1, mask=m, hard_mask=True, copy=True)
+        xh.put([4, 2, 0, 1, 3], [1, 2, 3, 4, 5])
+        assert_equal(xh._data, [3, 4, 2, 4, 5])
+
+    def test_putmask(self):
+        x = arange(6) + 1
+        mx = array(x, mask=[0, 0, 0, 1, 1, 1])
+        mask = [0, 0, 1, 0, 0, 1]
+        # w/o mask, w/o masked values
+        xx = x.copy()
+        putmask(xx, mask, 99)
+        assert_equal(xx, [1, 2, 99, 4, 5, 99])
+        # w/ mask, w/o masked values
+        mxx = mx.copy()
+        putmask(mxx, mask, 99)
+        assert_equal(mxx._data, [1, 2, 99, 4, 5, 99])
+        assert_equal(mxx._mask, [0, 0, 0, 1, 1, 0])
+        # w/o mask, w/ masked values
+        values = array([10, 20, 30, 40, 50, 60], mask=[1, 1, 1, 0, 0, 0])
+        xx = x.copy()
+        putmask(xx, mask, values)
+        assert_equal(xx._data, [1, 2, 30, 4, 5, 60])
+        assert_equal(xx._mask, [0, 0, 1, 0, 0, 0])
+        # w/ mask, w/ masked values
+        mxx = mx.copy()
+        putmask(mxx, mask, values)
+        assert_equal(mxx._data, [1, 2, 30, 4, 5, 60])
+        assert_equal(mxx._mask, [0, 0, 1, 1, 1, 0])
+        # w/ mask, w/ masked values + hardmask
+        mxx = mx.copy()
+        mxx.harden_mask()
+        putmask(mxx, mask, values)
+        assert_equal(mxx, [1, 2, 30, 4, 5, 60])
+
+    def test_ravel(self):
+        # Tests ravel
+        a = array([[1, 2, 3, 4, 5]], mask=[[0, 1, 0, 0, 0]])
+        aravel = a.ravel()
+        assert_equal(aravel._mask.shape, aravel.shape)
+        a = array([0, 0], mask=[1, 1])
+        aravel = a.ravel()
+        assert_equal(aravel._mask.shape, a.shape)
+        # Checks that small_mask is preserved
+        a = array([1, 2, 3, 4], mask=[0, 0, 0, 0], shrink=False)
+        assert_equal(a.ravel()._mask, [0, 0, 0, 0])
+        # Test that the fill_value is preserved
+        a.fill_value = -99
+        a.shape = (2, 2)
+        ar = a.ravel()
+        assert_equal(ar._mask, [0, 0, 0, 0])
+        assert_equal(ar._data, [1, 2, 3, 4])
+        assert_equal(ar.fill_value, -99)
+        # Test index ordering
+        assert_equal(a.ravel(order='C'), [1, 2, 3, 4])
+        assert_equal(a.ravel(order='F'), [1, 3, 2, 4])
+
+    @pytest.mark.parametrize("order", "AKCF")
+    @pytest.mark.parametrize("data_order", "CF")
+    def test_ravel_order(self, order, data_order):
+        # Ravelling must ravel mask and data in the same order always to avoid
+        # misaligning the two in the ravel result.
+        arr = np.ones((5, 10), order=data_order)
+        arr[0, :] = 0
+        mask = np.ones((10, 5), dtype=bool, order=data_order).T
+        mask[0, :] = False
+        x = array(arr, mask=mask)
+        assert x._data.flags.fnc != x._mask.flags.fnc
+        assert (x.filled(0) == 0).all()
+        raveled = x.ravel(order)
+        assert (raveled.filled(0) == 0).all()
+
+        # NOTE: Can be wrong if arr order is neither C nor F and `order="K"`
+        assert_array_equal(arr.ravel(order), x.ravel(order)._data)
+
+    def test_reshape(self):
+        # Tests reshape
+        x = arange(4)
+        x[0] = masked
+        y = x.reshape(2, 2)
+        assert_equal(y.shape, (2, 2,))
+        assert_equal(y._mask.shape, (2, 2,))
+        assert_equal(x.shape, (4,))
+        assert_equal(x._mask.shape, (4,))
+
+    def test_sort(self):
+        # Test sort
+        x = array([1, 4, 2, 3], mask=[0, 1, 0, 0], dtype=np.uint8)
+
+        sortedx = sort(x)
+        assert_equal(sortedx._data, [1, 2, 3, 4])
+        assert_equal(sortedx._mask, [0, 0, 0, 1])
+
+        sortedx = sort(x, endwith=False)
+        assert_equal(sortedx._data, [4, 1, 2, 3])
+        assert_equal(sortedx._mask, [1, 0, 0, 0])
+
+        x.sort()
+        assert_equal(x._data, [1, 2, 3, 4])
+        assert_equal(x._mask, [0, 0, 0, 1])
+
+        x = array([1, 4, 2, 3], mask=[0, 1, 0, 0], dtype=np.uint8)
+        x.sort(endwith=False)
+        assert_equal(x._data, [4, 1, 2, 3])
+        assert_equal(x._mask, [1, 0, 0, 0])
+
+        x = [1, 4, 2, 3]
+        sortedx = sort(x)
+        assert_(not isinstance(sorted, MaskedArray))
+
+        x = array([0, 1, -1, -2, 2], mask=nomask, dtype=np.int8)
+        sortedx = sort(x, endwith=False)
+        assert_equal(sortedx._data, [-2, -1, 0, 1, 2])
+        x = array([0, 1, -1, -2, 2], mask=[0, 1, 0, 0, 1], dtype=np.int8)
+        sortedx = sort(x, endwith=False)
+        assert_equal(sortedx._data, [1, 2, -2, -1, 0])
+        assert_equal(sortedx._mask, [1, 1, 0, 0, 0])
+
+        x = array([0, -1], dtype=np.int8)
+        sortedx = sort(x, kind="stable")
+        assert_equal(sortedx, array([-1, 0], dtype=np.int8))
+
+    def test_stable_sort(self):
+        x = array([1, 2, 3, 1, 2, 3], dtype=np.uint8)
+        expected = array([0, 3, 1, 4, 2, 5])
+        computed = argsort(x, kind='stable')
+        assert_equal(computed, expected)
+
+    def test_argsort_matches_sort(self):
+        x = array([1, 4, 2, 3], mask=[0, 1, 0, 0], dtype=np.uint8)
+
+        for kwargs in [dict(),
+                       dict(endwith=True),
+                       dict(endwith=False),
+                       dict(fill_value=2),
+                       dict(fill_value=2, endwith=True),
+                       dict(fill_value=2, endwith=False)]:
+            sortedx = sort(x, **kwargs)
+            argsortedx = x[argsort(x, **kwargs)]
+            assert_equal(sortedx._data, argsortedx._data)
+            assert_equal(sortedx._mask, argsortedx._mask)
+
+    def test_sort_2d(self):
+        # Check sort of 2D array.
+        # 2D array w/o mask
+        a = masked_array([[8, 4, 1], [2, 0, 9]])
+        a.sort(0)
+        assert_equal(a, [[2, 0, 1], [8, 4, 9]])
+        a = masked_array([[8, 4, 1], [2, 0, 9]])
+        a.sort(1)
+        assert_equal(a, [[1, 4, 8], [0, 2, 9]])
+        # 2D array w/mask
+        a = masked_array([[8, 4, 1], [2, 0, 9]], mask=[[1, 0, 0], [0, 0, 1]])
+        a.sort(0)
+        assert_equal(a, [[2, 0, 1], [8, 4, 9]])
+        assert_equal(a._mask, [[0, 0, 0], [1, 0, 1]])
+        a = masked_array([[8, 4, 1], [2, 0, 9]], mask=[[1, 0, 0], [0, 0, 1]])
+        a.sort(1)
+        assert_equal(a, [[1, 4, 8], [0, 2, 9]])
+        assert_equal(a._mask, [[0, 0, 1], [0, 0, 1]])
+        # 3D
+        a = masked_array([[[7, 8, 9], [4, 5, 6], [1, 2, 3]],
+                          [[1, 2, 3], [7, 8, 9], [4, 5, 6]],
+                          [[7, 8, 9], [1, 2, 3], [4, 5, 6]],
+                          [[4, 5, 6], [1, 2, 3], [7, 8, 9]]])
+        a[a % 4 == 0] = masked
+        am = a.copy()
+        an = a.filled(99)
+        am.sort(0)
+        an.sort(0)
+        assert_equal(am, an)
+        am = a.copy()
+        an = a.filled(99)
+        am.sort(1)
+        an.sort(1)
+        assert_equal(am, an)
+        am = a.copy()
+        an = a.filled(99)
+        am.sort(2)
+        an.sort(2)
+        assert_equal(am, an)
+
+    def test_sort_flexible(self):
+        # Test sort on structured dtype.
+        a = array(
+            data=[(3, 3), (3, 2), (2, 2), (2, 1), (1, 0), (1, 1), (1, 2)],
+            mask=[(0, 0), (0, 1), (0, 0), (0, 0), (1, 0), (0, 0), (0, 0)],
+            dtype=[('A', int), ('B', int)])
+        mask_last = array(
+            data=[(1, 1), (1, 2), (2, 1), (2, 2), (3, 3), (3, 2), (1, 0)],
+            mask=[(0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 1), (1, 0)],
+            dtype=[('A', int), ('B', int)])
+        mask_first = array(
+            data=[(1, 0), (1, 1), (1, 2), (2, 1), (2, 2), (3, 2), (3, 3)],
+            mask=[(1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 1), (0, 0)],
+            dtype=[('A', int), ('B', int)])
+
+        test = sort(a)
+        assert_equal(test, mask_last)
+        assert_equal(test.mask, mask_last.mask)
+
+        test = sort(a, endwith=False)
+        assert_equal(test, mask_first)
+        assert_equal(test.mask, mask_first.mask)
+
+        # Test sort on dtype with subarray (gh-8069)
+        # Just check that the sort does not error, structured array subarrays
+        # are treated as byte strings and that leads to differing behavior
+        # depending on endianness and `endwith`.
+        dt = np.dtype([('v', int, 2)])
+        a = a.view(dt)
+        test = sort(a)
+        test = sort(a, endwith=False)
+
+    def test_argsort(self):
+        # Test argsort
+        a = array([1, 5, 2, 4, 3], mask=[1, 0, 0, 1, 0])
+        assert_equal(np.argsort(a), argsort(a))
+
+    def test_squeeze(self):
+        # Check squeeze
+        data = masked_array([[1, 2, 3]])
+        assert_equal(data.squeeze(), [1, 2, 3])
+        data = masked_array([[1, 2, 3]], mask=[[1, 1, 1]])
+        assert_equal(data.squeeze(), [1, 2, 3])
+        assert_equal(data.squeeze()._mask, [1, 1, 1])
+
+        # normal ndarrays return a view
+        arr = np.array([[1]])
+        arr_sq = arr.squeeze()
+        assert_equal(arr_sq, 1)
+        arr_sq[...] = 2
+        assert_equal(arr[0,0], 2)
+
+        # so maskedarrays should too
+        m_arr = masked_array([[1]], mask=True)
+        m_arr_sq = m_arr.squeeze()
+        assert_(m_arr_sq is not np.ma.masked)
+        assert_equal(m_arr_sq.mask, True)
+        m_arr_sq[...] = 2
+        assert_equal(m_arr[0,0], 2)
+
+    def test_swapaxes(self):
+        # Tests swapaxes on MaskedArrays.
+        x = np.array([8.375, 7.545, 8.828, 8.5, 1.757, 5.928,
+                      8.43, 7.78, 9.865, 5.878, 8.979, 4.732,
+                      3.012, 6.022, 5.095, 3.116, 5.238, 3.957,
+                      6.04, 9.63, 7.712, 3.382, 4.489, 6.479,
+                      7.189, 9.645, 5.395, 4.961, 9.894, 2.893,
+                      7.357, 9.828, 6.272, 3.758, 6.693, 0.993])
+        m = np.array([0, 1, 0, 1, 0, 0,
+                      1, 0, 1, 1, 0, 1,
+                      0, 0, 0, 1, 0, 1,
+                      0, 0, 0, 1, 1, 1,
+                      1, 0, 0, 1, 0, 0,
+                      0, 0, 1, 0, 1, 0])
+        mX = array(x, mask=m).reshape(6, 6)
+        mXX = mX.reshape(3, 2, 2, 3)
+
+        mXswapped = mX.swapaxes(0, 1)
+        assert_equal(mXswapped[-1], mX[:, -1])
+
+        mXXswapped = mXX.swapaxes(0, 2)
+        assert_equal(mXXswapped.shape, (2, 2, 3, 3))
+
+    def test_take(self):
+        # Tests take
+        x = masked_array([10, 20, 30, 40], [0, 1, 0, 1])
+        assert_equal(x.take([0, 0, 3]), masked_array([10, 10, 40], [0, 0, 1]))
+        assert_equal(x.take([0, 0, 3]), x[[0, 0, 3]])
+        assert_equal(x.take([[0, 1], [0, 1]]),
+                     masked_array([[10, 20], [10, 20]], [[0, 1], [0, 1]]))
+
+        # assert_equal crashes when passed np.ma.mask
+        assert_(x[1] is np.ma.masked)
+        assert_(x.take(1) is np.ma.masked)
+
+        x = array([[10, 20, 30], [40, 50, 60]], mask=[[0, 0, 1], [1, 0, 0, ]])
+        assert_equal(x.take([0, 2], axis=1),
+                     array([[10, 30], [40, 60]], mask=[[0, 1], [1, 0]]))
+        assert_equal(take(x, [0, 2], axis=1),
+                     array([[10, 30], [40, 60]], mask=[[0, 1], [1, 0]]))
+
+    def test_take_masked_indices(self):
+        # Test take w/ masked indices
+        a = np.array((40, 18, 37, 9, 22))
+        indices = np.arange(3)[None,:] + np.arange(5)[:, None]
+        mindices = array(indices, mask=(indices >= len(a)))
+        # No mask
+        test = take(a, mindices, mode='clip')
+        ctrl = array([[40, 18, 37],
+                      [18, 37, 9],
+                      [37, 9, 22],
+                      [9, 22, 22],
+                      [22, 22, 22]])
+        assert_equal(test, ctrl)
+        # Masked indices
+        test = take(a, mindices)
+        ctrl = array([[40, 18, 37],
+                      [18, 37, 9],
+                      [37, 9, 22],
+                      [9, 22, 40],
+                      [22, 40, 40]])
+        ctrl[3, 2] = ctrl[4, 1] = ctrl[4, 2] = masked
+        assert_equal(test, ctrl)
+        assert_equal(test.mask, ctrl.mask)
+        # Masked input + masked indices
+        a = array((40, 18, 37, 9, 22), mask=(0, 1, 0, 0, 0))
+        test = take(a, mindices)
+        ctrl[0, 1] = ctrl[1, 0] = masked
+        assert_equal(test, ctrl)
+        assert_equal(test.mask, ctrl.mask)
+
+    def test_tolist(self):
+        # Tests to list
+        # ... on 1D
+        x = array(np.arange(12))
+        x[[1, -2]] = masked
+        xlist = x.tolist()
+        assert_(xlist[1] is None)
+        assert_(xlist[-2] is None)
+        # ... on 2D
+        x.shape = (3, 4)
+        xlist = x.tolist()
+        ctrl = [[0, None, 2, 3], [4, 5, 6, 7], [8, 9, None, 11]]
+        assert_equal(xlist[0], [0, None, 2, 3])
+        assert_equal(xlist[1], [4, 5, 6, 7])
+        assert_equal(xlist[2], [8, 9, None, 11])
+        assert_equal(xlist, ctrl)
+        # ... on structured array w/ masked records
+        x = array(list(zip([1, 2, 3],
+                           [1.1, 2.2, 3.3],
+                           ['one', 'two', 'thr'])),
+                  dtype=[('a', int), ('b', float), ('c', '|S8')])
+        x[-1] = masked
+        assert_equal(x.tolist(),
+                     [(1, 1.1, b'one'),
+                      (2, 2.2, b'two'),
+                      (None, None, None)])
+        # ... on structured array w/ masked fields
+        a = array([(1, 2,), (3, 4)], mask=[(0, 1), (0, 0)],
+                  dtype=[('a', int), ('b', int)])
+        test = a.tolist()
+        assert_equal(test, [[1, None], [3, 4]])
+        # ... on mvoid
+        a = a[0]
+        test = a.tolist()
+        assert_equal(test, [1, None])
+
+    def test_tolist_specialcase(self):
+        # Test mvoid.tolist: make sure we return a standard Python object
+        a = array([(0, 1), (2, 3)], dtype=[('a', int), ('b', int)])
+        # w/o mask: each entry is a np.void whose elements are standard Python
+        for entry in a:
+            for item in entry.tolist():
+                assert_(not isinstance(item, np.generic))
+        # w/ mask: each entry is a ma.void whose elements should be
+        # standard Python
+        a.mask[0] = (0, 1)
+        for entry in a:
+            for item in entry.tolist():
+                assert_(not isinstance(item, np.generic))
+
+    def test_toflex(self):
+        # Test the conversion to records
+        data = arange(10)
+        record = data.toflex()
+        assert_equal(record['_data'], data._data)
+        assert_equal(record['_mask'], data._mask)
+
+        data[[0, 1, 2, -1]] = masked
+        record = data.toflex()
+        assert_equal(record['_data'], data._data)
+        assert_equal(record['_mask'], data._mask)
+
+        ndtype = [('i', int), ('s', '|S3'), ('f', float)]
+        data = array([(i, s, f) for (i, s, f) in zip(np.arange(10),
+                                                     'ABCDEFGHIJKLM',
+                                                     np.random.rand(10))],
+                     dtype=ndtype)
+        data[[0, 1, 2, -1]] = masked
+        record = data.toflex()
+        assert_equal(record['_data'], data._data)
+        assert_equal(record['_mask'], data._mask)
+
+        ndtype = np.dtype("int, (2,3)float, float")
+        data = array([(i, f, ff) for (i, f, ff) in zip(np.arange(10),
+                                                       np.random.rand(10),
+                                                       np.random.rand(10))],
+                     dtype=ndtype)
+        data[[0, 1, 2, -1]] = masked
+        record = data.toflex()
+        assert_equal_records(record['_data'], data._data)
+        assert_equal_records(record['_mask'], data._mask)
+
+    def test_fromflex(self):
+        # Test the reconstruction of a masked_array from a record
+        a = array([1, 2, 3])
+        test = fromflex(a.toflex())
+        assert_equal(test, a)
+        assert_equal(test.mask, a.mask)
+
+        a = array([1, 2, 3], mask=[0, 0, 1])
+        test = fromflex(a.toflex())
+        assert_equal(test, a)
+        assert_equal(test.mask, a.mask)
+
+        a = array([(1, 1.), (2, 2.), (3, 3.)], mask=[(1, 0), (0, 0), (0, 1)],
+                  dtype=[('A', int), ('B', float)])
+        test = fromflex(a.toflex())
+        assert_equal(test, a)
+        assert_equal(test.data, a.data)
+
+    def test_arraymethod(self):
+        # Test a _arraymethod w/ n argument
+        marray = masked_array([[1, 2, 3, 4, 5]], mask=[0, 0, 1, 0, 0])
+        control = masked_array([[1], [2], [3], [4], [5]],
+                               mask=[0, 0, 1, 0, 0])
+        assert_equal(marray.T, control)
+        assert_equal(marray.transpose(), control)
+
+        assert_equal(MaskedArray.cumsum(marray.T, 0), control.cumsum(0))
+
+    def test_arraymethod_0d(self):
+        # gh-9430
+        x = np.ma.array(42, mask=True)
+        assert_equal(x.T.mask, x.mask)
+        assert_equal(x.T.data, x.data)
+
+    def test_transpose_view(self):
+        x = np.ma.array([[1, 2, 3], [4, 5, 6]])
+        x[0,1] = np.ma.masked
+        xt = x.T
+
+        xt[1,0] = 10
+        xt[0,1] = np.ma.masked
+
+        assert_equal(x.data, xt.T.data)
+        assert_equal(x.mask, xt.T.mask)
+
+    def test_diagonal_view(self):
+        x = np.ma.zeros((3,3))
+        x[0,0] = 10
+        x[1,1] = np.ma.masked
+        x[2,2] = 20
+        xd = x.diagonal()
+        x[1,1] = 15
+        assert_equal(xd.mask, x.diagonal().mask)
+        assert_equal(xd.data, x.diagonal().data)
+
+
+class TestMaskedArrayMathMethods:
+
+    def setup_method(self):
+        # Base data definition.
+        x = np.array([8.375, 7.545, 8.828, 8.5, 1.757, 5.928,
+                      8.43, 7.78, 9.865, 5.878, 8.979, 4.732,
+                      3.012, 6.022, 5.095, 3.116, 5.238, 3.957,
+                      6.04, 9.63, 7.712, 3.382, 4.489, 6.479,
+                      7.189, 9.645, 5.395, 4.961, 9.894, 2.893,
+                      7.357, 9.828, 6.272, 3.758, 6.693, 0.993])
+        X = x.reshape(6, 6)
+        XX = x.reshape(3, 2, 2, 3)
+
+        m = np.array([0, 1, 0, 1, 0, 0,
+                     1, 0, 1, 1, 0, 1,
+                     0, 0, 0, 1, 0, 1,
+                     0, 0, 0, 1, 1, 1,
+                     1, 0, 0, 1, 0, 0,
+                     0, 0, 1, 0, 1, 0])
+        mx = array(data=x, mask=m)
+        mX = array(data=X, mask=m.reshape(X.shape))
+        mXX = array(data=XX, mask=m.reshape(XX.shape))
+
+        m2 = np.array([1, 1, 0, 1, 0, 0,
+                      1, 1, 1, 1, 0, 1,
+                      0, 0, 1, 1, 0, 1,
+                      0, 0, 0, 1, 1, 1,
+                      1, 0, 0, 1, 1, 0,
+                      0, 0, 1, 0, 1, 1])
+        m2x = array(data=x, mask=m2)
+        m2X = array(data=X, mask=m2.reshape(X.shape))
+        m2XX = array(data=XX, mask=m2.reshape(XX.shape))
+        self.d = (x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX)
+
+    def test_cumsumprod(self):
+        # Tests cumsum & cumprod on MaskedArrays.
+        (x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX) = self.d
+        mXcp = mX.cumsum(0)
+        assert_equal(mXcp._data, mX.filled(0).cumsum(0))
+        mXcp = mX.cumsum(1)
+        assert_equal(mXcp._data, mX.filled(0).cumsum(1))
+
+        mXcp = mX.cumprod(0)
+        assert_equal(mXcp._data, mX.filled(1).cumprod(0))
+        mXcp = mX.cumprod(1)
+        assert_equal(mXcp._data, mX.filled(1).cumprod(1))
+
+    def test_cumsumprod_with_output(self):
+        # Tests cumsum/cumprod w/ output
+        xm = array(np.random.uniform(0, 10, 12)).reshape(3, 4)
+        xm[:, 0] = xm[0] = xm[-1, -1] = masked
+
+        for funcname in ('cumsum', 'cumprod'):
+            npfunc = getattr(np, funcname)
+            xmmeth = getattr(xm, funcname)
+
+            # A ndarray as explicit input
+            output = np.empty((3, 4), dtype=float)
+            output.fill(-9999)
+            result = npfunc(xm, axis=0, out=output)
+            # ... the result should be the given output
+            assert_(result is output)
+            assert_equal(result, xmmeth(axis=0, out=output))
+
+            output = empty((3, 4), dtype=int)
+            result = xmmeth(axis=0, out=output)
+            assert_(result is output)
+
+    def test_ptp(self):
+        # Tests ptp on MaskedArrays.
+        (x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX) = self.d
+        (n, m) = X.shape
+        assert_equal(mx.ptp(), mx.compressed().ptp())
+        rows = np.zeros(n, float)
+        cols = np.zeros(m, float)
+        for k in range(m):
+            cols[k] = mX[:, k].compressed().ptp()
+        for k in range(n):
+            rows[k] = mX[k].compressed().ptp()
+        assert_equal(mX.ptp(0), cols)
+        assert_equal(mX.ptp(1), rows)
+
+    def test_add_object(self):
+        x = masked_array(['a', 'b'], mask=[1, 0], dtype=object)
+        y = x + 'x'
+        assert_equal(y[1], 'bx')
+        assert_(y.mask[0])
+
+    def test_sum_object(self):
+        # Test sum on object dtype
+        a = masked_array([1, 2, 3], mask=[1, 0, 0], dtype=object)
+        assert_equal(a.sum(), 5)
+        a = masked_array([[1, 2, 3], [4, 5, 6]], dtype=object)
+        assert_equal(a.sum(axis=0), [5, 7, 9])
+
+    def test_prod_object(self):
+        # Test prod on object dtype
+        a = masked_array([1, 2, 3], mask=[1, 0, 0], dtype=object)
+        assert_equal(a.prod(), 2 * 3)
+        a = masked_array([[1, 2, 3], [4, 5, 6]], dtype=object)
+        assert_equal(a.prod(axis=0), [4, 10, 18])
+
+    def test_meananom_object(self):
+        # Test mean/anom on object dtype
+        a = masked_array([1, 2, 3], dtype=object)
+        assert_equal(a.mean(), 2)
+        assert_equal(a.anom(), [-1, 0, 1])
+
+    def test_anom_shape(self):
+        a = masked_array([1, 2, 3])
+        assert_equal(a.anom().shape, a.shape)
+        a.mask = True
+        assert_equal(a.anom().shape, a.shape)
+        assert_(np.ma.is_masked(a.anom()))
+
+    def test_anom(self):
+        a = masked_array(np.arange(1, 7).reshape(2, 3))
+        assert_almost_equal(a.anom(),
+                            [[-2.5, -1.5, -0.5], [0.5, 1.5, 2.5]])
+        assert_almost_equal(a.anom(axis=0),
+                            [[-1.5, -1.5, -1.5], [1.5, 1.5, 1.5]])
+        assert_almost_equal(a.anom(axis=1),
+                            [[-1., 0., 1.], [-1., 0., 1.]])
+        a.mask = [[0, 0, 1], [0, 1, 0]]
+        mval = -99
+        assert_almost_equal(a.anom().filled(mval),
+                            [[-2.25, -1.25, mval], [0.75, mval, 2.75]])
+        assert_almost_equal(a.anom(axis=0).filled(mval),
+                            [[-1.5, 0.0, mval], [1.5, mval, 0.0]])
+        assert_almost_equal(a.anom(axis=1).filled(mval),
+                            [[-0.5, 0.5, mval], [-1.0, mval, 1.0]])
+
+    def test_trace(self):
+        # Tests trace on MaskedArrays.
+        (x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX) = self.d
+        mXdiag = mX.diagonal()
+        assert_equal(mX.trace(), mX.diagonal().compressed().sum())
+        assert_almost_equal(mX.trace(),
+                            X.trace() - sum(mXdiag.mask * X.diagonal(),
+                                            axis=0))
+        assert_equal(np.trace(mX), mX.trace())
+
+        # gh-5560
+        arr = np.arange(2*4*4).reshape(2,4,4)
+        m_arr = np.ma.masked_array(arr, False)
+        assert_equal(arr.trace(axis1=1, axis2=2), m_arr.trace(axis1=1, axis2=2))
+
+    def test_dot(self):
+        # Tests dot on MaskedArrays.
+        (x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX) = self.d
+        fx = mx.filled(0)
+        r = mx.dot(mx)
+        assert_almost_equal(r.filled(0), fx.dot(fx))
+        assert_(r.mask is nomask)
+
+        fX = mX.filled(0)
+        r = mX.dot(mX)
+        assert_almost_equal(r.filled(0), fX.dot(fX))
+        assert_(r.mask[1,3])
+        r1 = empty_like(r)
+        mX.dot(mX, out=r1)
+        assert_almost_equal(r, r1)
+
+        mYY = mXX.swapaxes(-1, -2)
+        fXX, fYY = mXX.filled(0), mYY.filled(0)
+        r = mXX.dot(mYY)
+        assert_almost_equal(r.filled(0), fXX.dot(fYY))
+        r1 = empty_like(r)
+        mXX.dot(mYY, out=r1)
+        assert_almost_equal(r, r1)
+
+    def test_dot_shape_mismatch(self):
+        # regression test
+        x = masked_array([[1,2],[3,4]], mask=[[0,1],[0,0]])
+        y = masked_array([[1,2],[3,4]], mask=[[0,1],[0,0]])
+        z = masked_array([[0,1],[3,3]])
+        x.dot(y, out=z)
+        assert_almost_equal(z.filled(0), [[1, 0], [15, 16]])
+        assert_almost_equal(z.mask, [[0, 1], [0, 0]])
+
+    def test_varmean_nomask(self):
+        # gh-5769
+        foo = array([1,2,3,4], dtype='f8')
+        bar = array([1,2,3,4], dtype='f8')
+        assert_equal(type(foo.mean()), np.float64)
+        assert_equal(type(foo.var()), np.float64)
+        assert((foo.mean() == bar.mean()) is np.bool_(True))
+
+        # check array type is preserved and out works
+        foo = array(np.arange(16).reshape((4,4)), dtype='f8')
+        bar = empty(4, dtype='f4')
+        assert_equal(type(foo.mean(axis=1)), MaskedArray)
+        assert_equal(type(foo.var(axis=1)), MaskedArray)
+        assert_(foo.mean(axis=1, out=bar) is bar)
+        assert_(foo.var(axis=1, out=bar) is bar)
+
+    def test_varstd(self):
+        # Tests var & std on MaskedArrays.
+        (x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX) = self.d
+        assert_almost_equal(mX.var(axis=None), mX.compressed().var())
+        assert_almost_equal(mX.std(axis=None), mX.compressed().std())
+        assert_almost_equal(mX.std(axis=None, ddof=1),
+                            mX.compressed().std(ddof=1))
+        assert_almost_equal(mX.var(axis=None, ddof=1),
+                            mX.compressed().var(ddof=1))
+        assert_equal(mXX.var(axis=3).shape, XX.var(axis=3).shape)
+        assert_equal(mX.var().shape, X.var().shape)
+        (mXvar0, mXvar1) = (mX.var(axis=0), mX.var(axis=1))
+        assert_almost_equal(mX.var(axis=None, ddof=2),
+                            mX.compressed().var(ddof=2))
+        assert_almost_equal(mX.std(axis=None, ddof=2),
+                            mX.compressed().std(ddof=2))
+        for k in range(6):
+            assert_almost_equal(mXvar1[k], mX[k].compressed().var())
+            assert_almost_equal(mXvar0[k], mX[:, k].compressed().var())
+            assert_almost_equal(np.sqrt(mXvar0[k]),
+                                mX[:, k].compressed().std())
+
+    @suppress_copy_mask_on_assignment
+    def test_varstd_specialcases(self):
+        # Test a special case for var
+        nout = np.array(-1, dtype=float)
+        mout = array(-1, dtype=float)
+
+        x = array(arange(10), mask=True)
+        for methodname in ('var', 'std'):
+            method = getattr(x, methodname)
+            assert_(method() is masked)
+            assert_(method(0) is masked)
+            assert_(method(-1) is masked)
+            # Using a masked array as explicit output
+            method(out=mout)
+            assert_(mout is not masked)
+            assert_equal(mout.mask, True)
+            # Using a ndarray as explicit output
+            method(out=nout)
+            assert_(np.isnan(nout))
+
+        x = array(arange(10), mask=True)
+        x[-1] = 9
+        for methodname in ('var', 'std'):
+            method = getattr(x, methodname)
+            assert_(method(ddof=1) is masked)
+            assert_(method(0, ddof=1) is masked)
+            assert_(method(-1, ddof=1) is masked)
+            # Using a masked array as explicit output
+            method(out=mout, ddof=1)
+            assert_(mout is not masked)
+            assert_equal(mout.mask, True)
+            # Using a ndarray as explicit output
+            method(out=nout, ddof=1)
+            assert_(np.isnan(nout))
+
+    def test_varstd_ddof(self):
+        a = array([[1, 1, 0], [1, 1, 0]], mask=[[0, 0, 1], [0, 0, 1]])
+        test = a.std(axis=0, ddof=0)
+        assert_equal(test.filled(0), [0, 0, 0])
+        assert_equal(test.mask, [0, 0, 1])
+        test = a.std(axis=0, ddof=1)
+        assert_equal(test.filled(0), [0, 0, 0])
+        assert_equal(test.mask, [0, 0, 1])
+        test = a.std(axis=0, ddof=2)
+        assert_equal(test.filled(0), [0, 0, 0])
+        assert_equal(test.mask, [1, 1, 1])
+
+    def test_diag(self):
+        # Test diag
+        x = arange(9).reshape((3, 3))
+        x[1, 1] = masked
+        out = np.diag(x)
+        assert_equal(out, [0, 4, 8])
+        out = diag(x)
+        assert_equal(out, [0, 4, 8])
+        assert_equal(out.mask, [0, 1, 0])
+        out = diag(out)
+        control = array([[0, 0, 0], [0, 4, 0], [0, 0, 8]],
+                        mask=[[0, 0, 0], [0, 1, 0], [0, 0, 0]])
+        assert_equal(out, control)
+
+    def test_axis_methods_nomask(self):
+        # Test the combination nomask & methods w/ axis
+        a = array([[1, 2, 3], [4, 5, 6]])
+
+        assert_equal(a.sum(0), [5, 7, 9])
+        assert_equal(a.sum(-1), [6, 15])
+        assert_equal(a.sum(1), [6, 15])
+
+        assert_equal(a.prod(0), [4, 10, 18])
+        assert_equal(a.prod(-1), [6, 120])
+        assert_equal(a.prod(1), [6, 120])
+
+        assert_equal(a.min(0), [1, 2, 3])
+        assert_equal(a.min(-1), [1, 4])
+        assert_equal(a.min(1), [1, 4])
+
+        assert_equal(a.max(0), [4, 5, 6])
+        assert_equal(a.max(-1), [3, 6])
+        assert_equal(a.max(1), [3, 6])
+
+    @requires_memory(free_bytes=2 * 10000 * 1000 * 2)
+    def test_mean_overflow(self):
+        # Test overflow in masked arrays
+        # gh-20272
+        a = masked_array(np.full((10000, 10000), 65535, dtype=np.uint16),
+                         mask=np.zeros((10000, 10000)))
+        assert_equal(a.mean(), 65535.0)
+
+    def test_diff_with_prepend(self):
+        # GH 22465
+        x = np.array([1, 2, 2, 3, 4, 2, 1, 1])
+
+        a = np.ma.masked_equal(x[3:], value=2)
+        a_prep = np.ma.masked_equal(x[:3], value=2)
+        diff1 = np.ma.diff(a, prepend=a_prep, axis=0)
+
+        b = np.ma.masked_equal(x, value=2)
+        diff2 = np.ma.diff(b, axis=0)
+
+        assert_(np.ma.allequal(diff1, diff2))
+
+    def test_diff_with_append(self):
+        # GH 22465
+        x = np.array([1, 2, 2, 3, 4, 2, 1, 1])
+
+        a = np.ma.masked_equal(x[:3], value=2)
+        a_app = np.ma.masked_equal(x[3:], value=2)
+        diff1 = np.ma.diff(a, append=a_app, axis=0)
+
+        b = np.ma.masked_equal(x, value=2)
+        diff2 = np.ma.diff(b, axis=0)
+
+        assert_(np.ma.allequal(diff1, diff2))
+
+    def test_diff_with_dim_0(self):
+        with pytest.raises(
+            ValueError,
+            match="diff requires input that is at least one dimensional"
+            ):
+            np.ma.diff(np.array(1))
+
+    def test_diff_with_n_0(self):
+        a = np.ma.masked_equal([1, 2, 2, 3, 4, 2, 1, 1], value=2)
+        diff = np.ma.diff(a, n=0, axis=0)
+
+        assert_(np.ma.allequal(a, diff))
+
+
+class TestMaskedArrayMathMethodsComplex:
+    # Test class for miscellaneous MaskedArrays methods.
+    def setup_method(self):
+        # Base data definition.
+        x = np.array([8.375j, 7.545j, 8.828j, 8.5j, 1.757j, 5.928,
+                      8.43, 7.78, 9.865, 5.878, 8.979, 4.732,
+                      3.012, 6.022, 5.095, 3.116, 5.238, 3.957,
+                      6.04, 9.63, 7.712, 3.382, 4.489, 6.479j,
+                      7.189j, 9.645, 5.395, 4.961, 9.894, 2.893,
+                      7.357, 9.828, 6.272, 3.758, 6.693, 0.993j])
+        X = x.reshape(6, 6)
+        XX = x.reshape(3, 2, 2, 3)
+
+        m = np.array([0, 1, 0, 1, 0, 0,
+                     1, 0, 1, 1, 0, 1,
+                     0, 0, 0, 1, 0, 1,
+                     0, 0, 0, 1, 1, 1,
+                     1, 0, 0, 1, 0, 0,
+                     0, 0, 1, 0, 1, 0])
+        mx = array(data=x, mask=m)
+        mX = array(data=X, mask=m.reshape(X.shape))
+        mXX = array(data=XX, mask=m.reshape(XX.shape))
+
+        m2 = np.array([1, 1, 0, 1, 0, 0,
+                      1, 1, 1, 1, 0, 1,
+                      0, 0, 1, 1, 0, 1,
+                      0, 0, 0, 1, 1, 1,
+                      1, 0, 0, 1, 1, 0,
+                      0, 0, 1, 0, 1, 1])
+        m2x = array(data=x, mask=m2)
+        m2X = array(data=X, mask=m2.reshape(X.shape))
+        m2XX = array(data=XX, mask=m2.reshape(XX.shape))
+        self.d = (x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX)
+
+    def test_varstd(self):
+        # Tests var & std on MaskedArrays.
+        (x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX) = self.d
+        assert_almost_equal(mX.var(axis=None), mX.compressed().var())
+        assert_almost_equal(mX.std(axis=None), mX.compressed().std())
+        assert_equal(mXX.var(axis=3).shape, XX.var(axis=3).shape)
+        assert_equal(mX.var().shape, X.var().shape)
+        (mXvar0, mXvar1) = (mX.var(axis=0), mX.var(axis=1))
+        assert_almost_equal(mX.var(axis=None, ddof=2),
+                            mX.compressed().var(ddof=2))
+        assert_almost_equal(mX.std(axis=None, ddof=2),
+                            mX.compressed().std(ddof=2))
+        for k in range(6):
+            assert_almost_equal(mXvar1[k], mX[k].compressed().var())
+            assert_almost_equal(mXvar0[k], mX[:, k].compressed().var())
+            assert_almost_equal(np.sqrt(mXvar0[k]),
+                                mX[:, k].compressed().std())
+
+
+class TestMaskedArrayFunctions:
+    # Test class for miscellaneous functions.
+
+    def setup_method(self):
+        x = np.array([1., 1., 1., -2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.])
+        y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.])
+        m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
+        m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1]
+        xm = masked_array(x, mask=m1)
+        ym = masked_array(y, mask=m2)
+        xm.set_fill_value(1e+20)
+        self.info = (xm, ym)
+
+    def test_masked_where_bool(self):
+        x = [1, 2]
+        y = masked_where(False, x)
+        assert_equal(y, [1, 2])
+        assert_equal(y[1], 2)
+
+    def test_masked_equal_wlist(self):
+        x = [1, 2, 3]
+        mx = masked_equal(x, 3)
+        assert_equal(mx, x)
+        assert_equal(mx._mask, [0, 0, 1])
+        mx = masked_not_equal(x, 3)
+        assert_equal(mx, x)
+        assert_equal(mx._mask, [1, 1, 0])
+
+    def test_masked_equal_fill_value(self):
+        x = [1, 2, 3]
+        mx = masked_equal(x, 3)
+        assert_equal(mx._mask, [0, 0, 1])
+        assert_equal(mx.fill_value, 3)
+
+    def test_masked_where_condition(self):
+        # Tests masking functions.
+        x = array([1., 2., 3., 4., 5.])
+        x[2] = masked
+        assert_equal(masked_where(greater(x, 2), x), masked_greater(x, 2))
+        assert_equal(masked_where(greater_equal(x, 2), x),
+                     masked_greater_equal(x, 2))
+        assert_equal(masked_where(less(x, 2), x), masked_less(x, 2))
+        assert_equal(masked_where(less_equal(x, 2), x),
+                     masked_less_equal(x, 2))
+        assert_equal(masked_where(not_equal(x, 2), x), masked_not_equal(x, 2))
+        assert_equal(masked_where(equal(x, 2), x), masked_equal(x, 2))
+        assert_equal(masked_where(not_equal(x, 2), x), masked_not_equal(x, 2))
+        assert_equal(masked_where([1, 1, 0, 0, 0], [1, 2, 3, 4, 5]),
+                     [99, 99, 3, 4, 5])
+
+    def test_masked_where_oddities(self):
+        # Tests some generic features.
+        atest = ones((10, 10, 10), dtype=float)
+        btest = zeros(atest.shape, MaskType)
+        ctest = masked_where(btest, atest)
+        assert_equal(atest, ctest)
+
+    def test_masked_where_shape_constraint(self):
+        a = arange(10)
+        with assert_raises(IndexError):
+            masked_equal(1, a)
+        test = masked_equal(a, 1)
+        assert_equal(test.mask, [0, 1, 0, 0, 0, 0, 0, 0, 0, 0])
+
+    def test_masked_where_structured(self):
+        # test that masked_where on a structured array sets a structured
+        # mask (see issue #2972)
+        a = np.zeros(10, dtype=[("A", " 6, x)
+
+    def test_masked_otherfunctions(self):
+        assert_equal(masked_inside(list(range(5)), 1, 3),
+                     [0, 199, 199, 199, 4])
+        assert_equal(masked_outside(list(range(5)), 1, 3), [199, 1, 2, 3, 199])
+        assert_equal(masked_inside(array(list(range(5)),
+                                         mask=[1, 0, 0, 0, 0]), 1, 3).mask,
+                     [1, 1, 1, 1, 0])
+        assert_equal(masked_outside(array(list(range(5)),
+                                          mask=[0, 1, 0, 0, 0]), 1, 3).mask,
+                     [1, 1, 0, 0, 1])
+        assert_equal(masked_equal(array(list(range(5)),
+                                        mask=[1, 0, 0, 0, 0]), 2).mask,
+                     [1, 0, 1, 0, 0])
+        assert_equal(masked_not_equal(array([2, 2, 1, 2, 1],
+                                            mask=[1, 0, 0, 0, 0]), 2).mask,
+                     [1, 0, 1, 0, 1])
+
+    def test_round(self):
+        a = array([1.23456, 2.34567, 3.45678, 4.56789, 5.67890],
+                  mask=[0, 1, 0, 0, 0])
+        assert_equal(a.round(), [1., 2., 3., 5., 6.])
+        assert_equal(a.round(1), [1.2, 2.3, 3.5, 4.6, 5.7])
+        assert_equal(a.round(3), [1.235, 2.346, 3.457, 4.568, 5.679])
+        b = empty_like(a)
+        a.round(out=b)
+        assert_equal(b, [1., 2., 3., 5., 6.])
+
+        x = array([1., 2., 3., 4., 5.])
+        c = array([1, 1, 1, 0, 0])
+        x[2] = masked
+        z = where(c, x, -x)
+        assert_equal(z, [1., 2., 0., -4., -5])
+        c[0] = masked
+        z = where(c, x, -x)
+        assert_equal(z, [1., 2., 0., -4., -5])
+        assert_(z[0] is masked)
+        assert_(z[1] is not masked)
+        assert_(z[2] is masked)
+
+    def test_round_with_output(self):
+        # Testing round with an explicit output
+
+        xm = array(np.random.uniform(0, 10, 12)).reshape(3, 4)
+        xm[:, 0] = xm[0] = xm[-1, -1] = masked
+
+        # A ndarray as explicit input
+        output = np.empty((3, 4), dtype=float)
+        output.fill(-9999)
+        result = np.round(xm, decimals=2, out=output)
+        # ... the result should be the given output
+        assert_(result is output)
+        assert_equal(result, xm.round(decimals=2, out=output))
+
+        output = empty((3, 4), dtype=float)
+        result = xm.round(decimals=2, out=output)
+        assert_(result is output)
+
+    def test_round_with_scalar(self):
+        # Testing round with scalar/zero dimension input
+        # GH issue 2244
+        a = array(1.1, mask=[False])
+        assert_equal(a.round(), 1)
+
+        a = array(1.1, mask=[True])
+        assert_(a.round() is masked)
+
+        a = array(1.1, mask=[False])
+        output = np.empty(1, dtype=float)
+        output.fill(-9999)
+        a.round(out=output)
+        assert_equal(output, 1)
+
+        a = array(1.1, mask=[False])
+        output = array(-9999., mask=[True])
+        a.round(out=output)
+        assert_equal(output[()], 1)
+
+        a = array(1.1, mask=[True])
+        output = array(-9999., mask=[False])
+        a.round(out=output)
+        assert_(output[()] is masked)
+
+    def test_identity(self):
+        a = identity(5)
+        assert_(isinstance(a, MaskedArray))
+        assert_equal(a, np.identity(5))
+
+    def test_power(self):
+        x = -1.1
+        assert_almost_equal(power(x, 2.), 1.21)
+        assert_(power(x, masked) is masked)
+        x = array([-1.1, -1.1, 1.1, 1.1, 0.])
+        b = array([0.5, 2., 0.5, 2., -1.], mask=[0, 0, 0, 0, 1])
+        y = power(x, b)
+        assert_almost_equal(y, [0, 1.21, 1.04880884817, 1.21, 0.])
+        assert_equal(y._mask, [1, 0, 0, 0, 1])
+        b.mask = nomask
+        y = power(x, b)
+        assert_equal(y._mask, [1, 0, 0, 0, 1])
+        z = x ** b
+        assert_equal(z._mask, y._mask)
+        assert_almost_equal(z, y)
+        assert_almost_equal(z._data, y._data)
+        x **= b
+        assert_equal(x._mask, y._mask)
+        assert_almost_equal(x, y)
+        assert_almost_equal(x._data, y._data)
+
+    def test_power_with_broadcasting(self):
+        # Test power w/ broadcasting
+        a2 = np.array([[1., 2., 3.], [4., 5., 6.]])
+        a2m = array(a2, mask=[[1, 0, 0], [0, 0, 1]])
+        b1 = np.array([2, 4, 3])
+        b2 = np.array([b1, b1])
+        b2m = array(b2, mask=[[0, 1, 0], [0, 1, 0]])
+
+        ctrl = array([[1 ** 2, 2 ** 4, 3 ** 3], [4 ** 2, 5 ** 4, 6 ** 3]],
+                     mask=[[1, 1, 0], [0, 1, 1]])
+        # No broadcasting, base & exp w/ mask
+        test = a2m ** b2m
+        assert_equal(test, ctrl)
+        assert_equal(test.mask, ctrl.mask)
+        # No broadcasting, base w/ mask, exp w/o mask
+        test = a2m ** b2
+        assert_equal(test, ctrl)
+        assert_equal(test.mask, a2m.mask)
+        # No broadcasting, base w/o mask, exp w/ mask
+        test = a2 ** b2m
+        assert_equal(test, ctrl)
+        assert_equal(test.mask, b2m.mask)
+
+        ctrl = array([[2 ** 2, 4 ** 4, 3 ** 3], [2 ** 2, 4 ** 4, 3 ** 3]],
+                     mask=[[0, 1, 0], [0, 1, 0]])
+        test = b1 ** b2m
+        assert_equal(test, ctrl)
+        assert_equal(test.mask, ctrl.mask)
+        test = b2m ** b1
+        assert_equal(test, ctrl)
+        assert_equal(test.mask, ctrl.mask)
+
+    @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
+    def test_where(self):
+        # Test the where function
+        x = np.array([1., 1., 1., -2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.])
+        y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.])
+        m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
+        m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1]
+        xm = masked_array(x, mask=m1)
+        ym = masked_array(y, mask=m2)
+        xm.set_fill_value(1e+20)
+
+        d = where(xm > 2, xm, -9)
+        assert_equal(d, [-9., -9., -9., -9., -9., 4.,
+                         -9., -9., 10., -9., -9., 3.])
+        assert_equal(d._mask, xm._mask)
+        d = where(xm > 2, -9, ym)
+        assert_equal(d, [5., 0., 3., 2., -1., -9.,
+                         -9., -10., -9., 1., 0., -9.])
+        assert_equal(d._mask, [1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0])
+        d = where(xm > 2, xm, masked)
+        assert_equal(d, [-9., -9., -9., -9., -9., 4.,
+                         -9., -9., 10., -9., -9., 3.])
+        tmp = xm._mask.copy()
+        tmp[(xm <= 2).filled(True)] = True
+        assert_equal(d._mask, tmp)
+
+        with np.errstate(invalid="warn"):
+            # The fill value is 1e20, it cannot be converted to `int`:
+            with pytest.warns(RuntimeWarning, match="invalid value"):
+                ixm = xm.astype(int)
+        d = where(ixm > 2, ixm, masked)
+        assert_equal(d, [-9, -9, -9, -9, -9, 4, -9, -9, 10, -9, -9, 3])
+        assert_equal(d.dtype, ixm.dtype)
+
+    def test_where_object(self):
+        a = np.array(None)
+        b = masked_array(None)
+        r = b.copy()
+        assert_equal(np.ma.where(True, a, a), r)
+        assert_equal(np.ma.where(True, b, b), r)
+
+    def test_where_with_masked_choice(self):
+        x = arange(10)
+        x[3] = masked
+        c = x >= 8
+        # Set False to masked
+        z = where(c, x, masked)
+        assert_(z.dtype is x.dtype)
+        assert_(z[3] is masked)
+        assert_(z[4] is masked)
+        assert_(z[7] is masked)
+        assert_(z[8] is not masked)
+        assert_(z[9] is not masked)
+        assert_equal(x, z)
+        # Set True to masked
+        z = where(c, masked, x)
+        assert_(z.dtype is x.dtype)
+        assert_(z[3] is masked)
+        assert_(z[4] is not masked)
+        assert_(z[7] is not masked)
+        assert_(z[8] is masked)
+        assert_(z[9] is masked)
+
+    def test_where_with_masked_condition(self):
+        x = array([1., 2., 3., 4., 5.])
+        c = array([1, 1, 1, 0, 0])
+        x[2] = masked
+        z = where(c, x, -x)
+        assert_equal(z, [1., 2., 0., -4., -5])
+        c[0] = masked
+        z = where(c, x, -x)
+        assert_equal(z, [1., 2., 0., -4., -5])
+        assert_(z[0] is masked)
+        assert_(z[1] is not masked)
+        assert_(z[2] is masked)
+
+        x = arange(1, 6)
+        x[-1] = masked
+        y = arange(1, 6) * 10
+        y[2] = masked
+        c = array([1, 1, 1, 0, 0], mask=[1, 0, 0, 0, 0])
+        cm = c.filled(1)
+        z = where(c, x, y)
+        zm = where(cm, x, y)
+        assert_equal(z, zm)
+        assert_(getmask(zm) is nomask)
+        assert_equal(zm, [1, 2, 3, 40, 50])
+        z = where(c, masked, 1)
+        assert_equal(z, [99, 99, 99, 1, 1])
+        z = where(c, 1, masked)
+        assert_equal(z, [99, 1, 1, 99, 99])
+
+    def test_where_type(self):
+        # Test the type conservation with where
+        x = np.arange(4, dtype=np.int32)
+        y = np.arange(4, dtype=np.float32) * 2.2
+        test = where(x > 1.5, y, x).dtype
+        control = np.result_type(np.int32, np.float32)
+        assert_equal(test, control)
+
+    def test_where_broadcast(self):
+        # Issue 8599
+        x = np.arange(9).reshape(3, 3)
+        y = np.zeros(3)
+        core = np.where([1, 0, 1], x, y)
+        ma = where([1, 0, 1], x, y)
+
+        assert_equal(core, ma)
+        assert_equal(core.dtype, ma.dtype)
+
+    def test_where_structured(self):
+        # Issue 8600
+        dt = np.dtype([('a', int), ('b', int)])
+        x = np.array([(1, 2), (3, 4), (5, 6)], dtype=dt)
+        y = np.array((10, 20), dtype=dt)
+        core = np.where([0, 1, 1], x, y)
+        ma = np.where([0, 1, 1], x, y)
+
+        assert_equal(core, ma)
+        assert_equal(core.dtype, ma.dtype)
+
+    def test_where_structured_masked(self):
+        dt = np.dtype([('a', int), ('b', int)])
+        x = np.array([(1, 2), (3, 4), (5, 6)], dtype=dt)
+
+        ma = where([0, 1, 1], x, masked)
+        expected = masked_where([1, 0, 0], x)
+
+        assert_equal(ma.dtype, expected.dtype)
+        assert_equal(ma, expected)
+        assert_equal(ma.mask, expected.mask)
+
+    def test_masked_invalid_error(self):
+        a = np.arange(5, dtype=object)
+        a[3] = np.PINF
+        a[2] = np.NaN
+        with pytest.raises(TypeError,
+                           match="not supported for the input types"):
+            np.ma.masked_invalid(a)
+
+    def test_masked_invalid_pandas(self):
+        # getdata() used to be bad for pandas series due to its _data
+        # attribute.  This test is a regression test mainly and may be
+        # removed if getdata() is adjusted.
+        class Series():
+            _data = "nonsense"
+
+            def __array__(self):
+                return np.array([5, np.nan, np.inf])
+
+        arr = np.ma.masked_invalid(Series())
+        assert_array_equal(arr._data, np.array(Series()))
+        assert_array_equal(arr._mask, [False, True, True])
+
+    @pytest.mark.parametrize("copy", [True, False])
+    def test_masked_invalid_full_mask(self, copy):
+        # Matplotlib relied on masked_invalid always returning a full mask
+        # (Also astropy projects, but were ok with it gh-22720 and gh-22842)
+        a = np.ma.array([1, 2, 3, 4])
+        assert a._mask is nomask
+        res = np.ma.masked_invalid(a, copy=copy)
+        assert res.mask is not nomask
+        # mask of a should not be mutated
+        assert a.mask is nomask
+        assert np.may_share_memory(a._data, res._data) != copy
+
+    def test_choose(self):
+        # Test choose
+        choices = [[0, 1, 2, 3], [10, 11, 12, 13],
+                   [20, 21, 22, 23], [30, 31, 32, 33]]
+        chosen = choose([2, 3, 1, 0], choices)
+        assert_equal(chosen, array([20, 31, 12, 3]))
+        chosen = choose([2, 4, 1, 0], choices, mode='clip')
+        assert_equal(chosen, array([20, 31, 12, 3]))
+        chosen = choose([2, 4, 1, 0], choices, mode='wrap')
+        assert_equal(chosen, array([20, 1, 12, 3]))
+        # Check with some masked indices
+        indices_ = array([2, 4, 1, 0], mask=[1, 0, 0, 1])
+        chosen = choose(indices_, choices, mode='wrap')
+        assert_equal(chosen, array([99, 1, 12, 99]))
+        assert_equal(chosen.mask, [1, 0, 0, 1])
+        # Check with some masked choices
+        choices = array(choices, mask=[[0, 0, 0, 1], [1, 1, 0, 1],
+                                       [1, 0, 0, 0], [0, 0, 0, 0]])
+        indices_ = [2, 3, 1, 0]
+        chosen = choose(indices_, choices, mode='wrap')
+        assert_equal(chosen, array([20, 31, 12, 3]))
+        assert_equal(chosen.mask, [1, 0, 0, 1])
+
+    def test_choose_with_out(self):
+        # Test choose with an explicit out keyword
+        choices = [[0, 1, 2, 3], [10, 11, 12, 13],
+                   [20, 21, 22, 23], [30, 31, 32, 33]]
+        store = empty(4, dtype=int)
+        chosen = choose([2, 3, 1, 0], choices, out=store)
+        assert_equal(store, array([20, 31, 12, 3]))
+        assert_(store is chosen)
+        # Check with some masked indices + out
+        store = empty(4, dtype=int)
+        indices_ = array([2, 3, 1, 0], mask=[1, 0, 0, 1])
+        chosen = choose(indices_, choices, mode='wrap', out=store)
+        assert_equal(store, array([99, 31, 12, 99]))
+        assert_equal(store.mask, [1, 0, 0, 1])
+        # Check with some masked choices + out ina ndarray !
+        choices = array(choices, mask=[[0, 0, 0, 1], [1, 1, 0, 1],
+                                       [1, 0, 0, 0], [0, 0, 0, 0]])
+        indices_ = [2, 3, 1, 0]
+        store = empty(4, dtype=int).view(ndarray)
+        chosen = choose(indices_, choices, mode='wrap', out=store)
+        assert_equal(store, array([999999, 31, 12, 999999]))
+
+    def test_reshape(self):
+        a = arange(10)
+        a[0] = masked
+        # Try the default
+        b = a.reshape((5, 2))
+        assert_equal(b.shape, (5, 2))
+        assert_(b.flags['C'])
+        # Try w/ arguments as list instead of tuple
+        b = a.reshape(5, 2)
+        assert_equal(b.shape, (5, 2))
+        assert_(b.flags['C'])
+        # Try w/ order
+        b = a.reshape((5, 2), order='F')
+        assert_equal(b.shape, (5, 2))
+        assert_(b.flags['F'])
+        # Try w/ order
+        b = a.reshape(5, 2, order='F')
+        assert_equal(b.shape, (5, 2))
+        assert_(b.flags['F'])
+
+        c = np.reshape(a, (2, 5))
+        assert_(isinstance(c, MaskedArray))
+        assert_equal(c.shape, (2, 5))
+        assert_(c[0, 0] is masked)
+        assert_(c.flags['C'])
+
+    def test_make_mask_descr(self):
+        # Flexible
+        ntype = [('a', float), ('b', float)]
+        test = make_mask_descr(ntype)
+        assert_equal(test, [('a', bool), ('b', bool)])
+        assert_(test is make_mask_descr(test))
+
+        # Standard w/ shape
+        ntype = (float, 2)
+        test = make_mask_descr(ntype)
+        assert_equal(test, (bool, 2))
+        assert_(test is make_mask_descr(test))
+
+        # Standard standard
+        ntype = float
+        test = make_mask_descr(ntype)
+        assert_equal(test, np.dtype(bool))
+        assert_(test is make_mask_descr(test))
+
+        # Nested
+        ntype = [('a', float), ('b', [('ba', float), ('bb', float)])]
+        test = make_mask_descr(ntype)
+        control = np.dtype([('a', 'b1'), ('b', [('ba', 'b1'), ('bb', 'b1')])])
+        assert_equal(test, control)
+        assert_(test is make_mask_descr(test))
+
+        # Named+ shape
+        ntype = [('a', (float, 2))]
+        test = make_mask_descr(ntype)
+        assert_equal(test, np.dtype([('a', (bool, 2))]))
+        assert_(test is make_mask_descr(test))
+
+        # 2 names
+        ntype = [(('A', 'a'), float)]
+        test = make_mask_descr(ntype)
+        assert_equal(test, np.dtype([(('A', 'a'), bool)]))
+        assert_(test is make_mask_descr(test))
+
+        # nested boolean types should preserve identity
+        base_type = np.dtype([('a', int, 3)])
+        base_mtype = make_mask_descr(base_type)
+        sub_type = np.dtype([('a', int), ('b', base_mtype)])
+        test = make_mask_descr(sub_type)
+        assert_equal(test, np.dtype([('a', bool), ('b', [('a', bool, 3)])]))
+        assert_(test.fields['b'][0] is base_mtype)
+
+    def test_make_mask(self):
+        # Test make_mask
+        # w/ a list as an input
+        mask = [0, 1]
+        test = make_mask(mask)
+        assert_equal(test.dtype, MaskType)
+        assert_equal(test, [0, 1])
+        # w/ a ndarray as an input
+        mask = np.array([0, 1], dtype=bool)
+        test = make_mask(mask)
+        assert_equal(test.dtype, MaskType)
+        assert_equal(test, [0, 1])
+        # w/ a flexible-type ndarray as an input - use default
+        mdtype = [('a', bool), ('b', bool)]
+        mask = np.array([(0, 0), (0, 1)], dtype=mdtype)
+        test = make_mask(mask)
+        assert_equal(test.dtype, MaskType)
+        assert_equal(test, [1, 1])
+        # w/ a flexible-type ndarray as an input - use input dtype
+        mdtype = [('a', bool), ('b', bool)]
+        mask = np.array([(0, 0), (0, 1)], dtype=mdtype)
+        test = make_mask(mask, dtype=mask.dtype)
+        assert_equal(test.dtype, mdtype)
+        assert_equal(test, mask)
+        # w/ a flexible-type ndarray as an input - use input dtype
+        mdtype = [('a', float), ('b', float)]
+        bdtype = [('a', bool), ('b', bool)]
+        mask = np.array([(0, 0), (0, 1)], dtype=mdtype)
+        test = make_mask(mask, dtype=mask.dtype)
+        assert_equal(test.dtype, bdtype)
+        assert_equal(test, np.array([(0, 0), (0, 1)], dtype=bdtype))
+        # Ensure this also works for void
+        mask = np.array((False, True), dtype='?,?')[()]
+        assert_(isinstance(mask, np.void))
+        test = make_mask(mask, dtype=mask.dtype)
+        assert_equal(test, mask)
+        assert_(test is not mask)
+        mask = np.array((0, 1), dtype='i4,i4')[()]
+        test2 = make_mask(mask, dtype=mask.dtype)
+        assert_equal(test2, test)
+        # test that nomask is returned when m is nomask.
+        bools = [True, False]
+        dtypes = [MaskType, float]
+        msgformat = 'copy=%s, shrink=%s, dtype=%s'
+        for cpy, shr, dt in itertools.product(bools, bools, dtypes):
+            res = make_mask(nomask, copy=cpy, shrink=shr, dtype=dt)
+            assert_(res is nomask, msgformat % (cpy, shr, dt))
+
+    def test_mask_or(self):
+        # Initialize
+        mtype = [('a', bool), ('b', bool)]
+        mask = np.array([(0, 0), (0, 1), (1, 0), (0, 0)], dtype=mtype)
+        # Test using nomask as input
+        test = mask_or(mask, nomask)
+        assert_equal(test, mask)
+        test = mask_or(nomask, mask)
+        assert_equal(test, mask)
+        # Using False as input
+        test = mask_or(mask, False)
+        assert_equal(test, mask)
+        # Using another array w / the same dtype
+        other = np.array([(0, 1), (0, 1), (0, 1), (0, 1)], dtype=mtype)
+        test = mask_or(mask, other)
+        control = np.array([(0, 1), (0, 1), (1, 1), (0, 1)], dtype=mtype)
+        assert_equal(test, control)
+        # Using another array w / a different dtype
+        othertype = [('A', bool), ('B', bool)]
+        other = np.array([(0, 1), (0, 1), (0, 1), (0, 1)], dtype=othertype)
+        try:
+            test = mask_or(mask, other)
+        except ValueError:
+            pass
+        # Using nested arrays
+        dtype = [('a', bool), ('b', [('ba', bool), ('bb', bool)])]
+        amask = np.array([(0, (1, 0)), (0, (1, 0))], dtype=dtype)
+        bmask = np.array([(1, (0, 1)), (0, (0, 0))], dtype=dtype)
+        cntrl = np.array([(1, (1, 1)), (0, (1, 0))], dtype=dtype)
+        assert_equal(mask_or(amask, bmask), cntrl)
+
+    def test_flatten_mask(self):
+        # Tests flatten mask
+        # Standard dtype
+        mask = np.array([0, 0, 1], dtype=bool)
+        assert_equal(flatten_mask(mask), mask)
+        # Flexible dtype
+        mask = np.array([(0, 0), (0, 1)], dtype=[('a', bool), ('b', bool)])
+        test = flatten_mask(mask)
+        control = np.array([0, 0, 0, 1], dtype=bool)
+        assert_equal(test, control)
+
+        mdtype = [('a', bool), ('b', [('ba', bool), ('bb', bool)])]
+        data = [(0, (0, 0)), (0, (0, 1))]
+        mask = np.array(data, dtype=mdtype)
+        test = flatten_mask(mask)
+        control = np.array([0, 0, 0, 0, 0, 1], dtype=bool)
+        assert_equal(test, control)
+
+    def test_on_ndarray(self):
+        # Test functions on ndarrays
+        a = np.array([1, 2, 3, 4])
+        m = array(a, mask=False)
+        test = anom(a)
+        assert_equal(test, m.anom())
+        test = reshape(a, (2, 2))
+        assert_equal(test, m.reshape(2, 2))
+
+    def test_compress(self):
+        # Test compress function on ndarray and masked array
+        # Address Github #2495.
+        arr = np.arange(8)
+        arr.shape = 4, 2
+        cond = np.array([True, False, True, True])
+        control = arr[[0, 2, 3]]
+        test = np.ma.compress(cond, arr, axis=0)
+        assert_equal(test, control)
+        marr = np.ma.array(arr)
+        test = np.ma.compress(cond, marr, axis=0)
+        assert_equal(test, control)
+
+    def test_compressed(self):
+        # Test ma.compressed function.
+        # Address gh-4026
+        a = np.ma.array([1, 2])
+        test = np.ma.compressed(a)
+        assert_(type(test) is np.ndarray)
+
+        # Test case when input data is ndarray subclass
+        class A(np.ndarray):
+            pass
+
+        a = np.ma.array(A(shape=0))
+        test = np.ma.compressed(a)
+        assert_(type(test) is A)
+
+        # Test that compress flattens
+        test = np.ma.compressed([[1],[2]])
+        assert_equal(test.ndim, 1)
+        test = np.ma.compressed([[[[[1]]]]])
+        assert_equal(test.ndim, 1)
+
+        # Test case when input is MaskedArray subclass
+        class M(MaskedArray):
+            pass
+
+        test = np.ma.compressed(M([[[]], [[]]]))
+        assert_equal(test.ndim, 1)
+
+        # with .compressed() overridden
+        class M(MaskedArray):
+            def compressed(self):
+                return 42
+
+        test = np.ma.compressed(M([[[]], [[]]]))
+        assert_equal(test, 42)
+
+    def test_convolve(self):
+        a = masked_equal(np.arange(5), 2)
+        b = np.array([1, 1])
+        test = np.ma.convolve(a, b)
+        assert_equal(test, masked_equal([0, 1, -1, -1, 7, 4], -1))
+
+        test = np.ma.convolve(a, b, propagate_mask=False)
+        assert_equal(test, masked_equal([0, 1, 1, 3, 7, 4], -1))
+
+        test = np.ma.convolve([1, 1], [1, 1, 1])
+        assert_equal(test, masked_equal([1, 2, 2, 1], -1))
+
+        a = [1, 1]
+        b = masked_equal([1, -1, -1, 1], -1)
+        test = np.ma.convolve(a, b, propagate_mask=False)
+        assert_equal(test, masked_equal([1, 1, -1, 1, 1], -1))
+        test = np.ma.convolve(a, b, propagate_mask=True)
+        assert_equal(test, masked_equal([-1, -1, -1, -1, -1], -1))
+
+
+class TestMaskedFields:
+
+    def setup_method(self):
+        ilist = [1, 2, 3, 4, 5]
+        flist = [1.1, 2.2, 3.3, 4.4, 5.5]
+        slist = ['one', 'two', 'three', 'four', 'five']
+        ddtype = [('a', int), ('b', float), ('c', '|S8')]
+        mdtype = [('a', bool), ('b', bool), ('c', bool)]
+        mask = [0, 1, 0, 0, 1]
+        base = array(list(zip(ilist, flist, slist)), mask=mask, dtype=ddtype)
+        self.data = dict(base=base, mask=mask, ddtype=ddtype, mdtype=mdtype)
+
+    def test_set_records_masks(self):
+        base = self.data['base']
+        mdtype = self.data['mdtype']
+        # Set w/ nomask or masked
+        base.mask = nomask
+        assert_equal_records(base._mask, np.zeros(base.shape, dtype=mdtype))
+        base.mask = masked
+        assert_equal_records(base._mask, np.ones(base.shape, dtype=mdtype))
+        # Set w/ simple boolean
+        base.mask = False
+        assert_equal_records(base._mask, np.zeros(base.shape, dtype=mdtype))
+        base.mask = True
+        assert_equal_records(base._mask, np.ones(base.shape, dtype=mdtype))
+        # Set w/ list
+        base.mask = [0, 0, 0, 1, 1]
+        assert_equal_records(base._mask,
+                             np.array([(x, x, x) for x in [0, 0, 0, 1, 1]],
+                                      dtype=mdtype))
+
+    def test_set_record_element(self):
+        # Check setting an element of a record)
+        base = self.data['base']
+        (base_a, base_b, base_c) = (base['a'], base['b'], base['c'])
+        base[0] = (pi, pi, 'pi')
+
+        assert_equal(base_a.dtype, int)
+        assert_equal(base_a._data, [3, 2, 3, 4, 5])
+
+        assert_equal(base_b.dtype, float)
+        assert_equal(base_b._data, [pi, 2.2, 3.3, 4.4, 5.5])
+
+        assert_equal(base_c.dtype, '|S8')
+        assert_equal(base_c._data,
+                     [b'pi', b'two', b'three', b'four', b'five'])
+
+    def test_set_record_slice(self):
+        base = self.data['base']
+        (base_a, base_b, base_c) = (base['a'], base['b'], base['c'])
+        base[:3] = (pi, pi, 'pi')
+
+        assert_equal(base_a.dtype, int)
+        assert_equal(base_a._data, [3, 3, 3, 4, 5])
+
+        assert_equal(base_b.dtype, float)
+        assert_equal(base_b._data, [pi, pi, pi, 4.4, 5.5])
+
+        assert_equal(base_c.dtype, '|S8')
+        assert_equal(base_c._data,
+                     [b'pi', b'pi', b'pi', b'four', b'five'])
+
+    def test_mask_element(self):
+        "Check record access"
+        base = self.data['base']
+        base[0] = masked
+
+        for n in ('a', 'b', 'c'):
+            assert_equal(base[n].mask, [1, 1, 0, 0, 1])
+            assert_equal(base[n]._data, base._data[n])
+
+    def test_getmaskarray(self):
+        # Test getmaskarray on flexible dtype
+        ndtype = [('a', int), ('b', float)]
+        test = empty(3, dtype=ndtype)
+        assert_equal(getmaskarray(test),
+                     np.array([(0, 0), (0, 0), (0, 0)],
+                              dtype=[('a', '|b1'), ('b', '|b1')]))
+        test[:] = masked
+        assert_equal(getmaskarray(test),
+                     np.array([(1, 1), (1, 1), (1, 1)],
+                              dtype=[('a', '|b1'), ('b', '|b1')]))
+
+    def test_view(self):
+        # Test view w/ flexible dtype
+        iterator = list(zip(np.arange(10), np.random.rand(10)))
+        data = np.array(iterator)
+        a = array(iterator, dtype=[('a', float), ('b', float)])
+        a.mask[0] = (1, 0)
+        controlmask = np.array([1] + 19 * [0], dtype=bool)
+        # Transform globally to simple dtype
+        test = a.view(float)
+        assert_equal(test, data.ravel())
+        assert_equal(test.mask, controlmask)
+        # Transform globally to dty
+        test = a.view((float, 2))
+        assert_equal(test, data)
+        assert_equal(test.mask, controlmask.reshape(-1, 2))
+
+    def test_getitem(self):
+        ndtype = [('a', float), ('b', float)]
+        a = array(list(zip(np.random.rand(10), np.arange(10))), dtype=ndtype)
+        a.mask = np.array(list(zip([0, 0, 0, 0, 0, 0, 0, 0, 1, 1],
+                                   [1, 0, 0, 0, 0, 0, 0, 0, 1, 0])),
+                          dtype=[('a', bool), ('b', bool)])
+
+        def _test_index(i):
+            assert_equal(type(a[i]), mvoid)
+            assert_equal_records(a[i]._data, a._data[i])
+            assert_equal_records(a[i]._mask, a._mask[i])
+
+            assert_equal(type(a[i, ...]), MaskedArray)
+            assert_equal_records(a[i,...]._data, a._data[i,...])
+            assert_equal_records(a[i,...]._mask, a._mask[i,...])
+
+        _test_index(1)   # No mask
+        _test_index(0)   # One element masked
+        _test_index(-2)  # All element masked
+
+    def test_setitem(self):
+        # Issue 4866: check that one can set individual items in [record][col]
+        # and [col][record] order
+        ndtype = np.dtype([('a', float), ('b', int)])
+        ma = np.ma.MaskedArray([(1.0, 1), (2.0, 2)], dtype=ndtype)
+        ma['a'][1] = 3.0
+        assert_equal(ma['a'], np.array([1.0, 3.0]))
+        ma[1]['a'] = 4.0
+        assert_equal(ma['a'], np.array([1.0, 4.0]))
+        # Issue 2403
+        mdtype = np.dtype([('a', bool), ('b', bool)])
+        # soft mask
+        control = np.array([(False, True), (True, True)], dtype=mdtype)
+        a = np.ma.masked_all((2,), dtype=ndtype)
+        a['a'][0] = 2
+        assert_equal(a.mask, control)
+        a = np.ma.masked_all((2,), dtype=ndtype)
+        a[0]['a'] = 2
+        assert_equal(a.mask, control)
+        # hard mask
+        control = np.array([(True, True), (True, True)], dtype=mdtype)
+        a = np.ma.masked_all((2,), dtype=ndtype)
+        a.harden_mask()
+        a['a'][0] = 2
+        assert_equal(a.mask, control)
+        a = np.ma.masked_all((2,), dtype=ndtype)
+        a.harden_mask()
+        a[0]['a'] = 2
+        assert_equal(a.mask, control)
+
+    def test_setitem_scalar(self):
+        # 8510
+        mask_0d = np.ma.masked_array(1, mask=True)
+        arr = np.ma.arange(3)
+        arr[0] = mask_0d
+        assert_array_equal(arr.mask, [True, False, False])
+
+    def test_element_len(self):
+        # check that len() works for mvoid (Github issue #576)
+        for rec in self.data['base']:
+            assert_equal(len(rec), len(self.data['ddtype']))
+
+
+class TestMaskedObjectArray:
+
+    def test_getitem(self):
+        arr = np.ma.array([None, None])
+        for dt in [float, object]:
+            a0 = np.eye(2).astype(dt)
+            a1 = np.eye(3).astype(dt)
+            arr[0] = a0
+            arr[1] = a1
+
+            assert_(arr[0] is a0)
+            assert_(arr[1] is a1)
+            assert_(isinstance(arr[0,...], MaskedArray))
+            assert_(isinstance(arr[1,...], MaskedArray))
+            assert_(arr[0,...][()] is a0)
+            assert_(arr[1,...][()] is a1)
+
+            arr[0] = np.ma.masked
+
+            assert_(arr[1] is a1)
+            assert_(isinstance(arr[0,...], MaskedArray))
+            assert_(isinstance(arr[1,...], MaskedArray))
+            assert_equal(arr[0,...].mask, True)
+            assert_(arr[1,...][()] is a1)
+
+            # gh-5962 - object arrays of arrays do something special
+            assert_equal(arr[0].data, a0)
+            assert_equal(arr[0].mask, True)
+            assert_equal(arr[0,...][()].data, a0)
+            assert_equal(arr[0,...][()].mask, True)
+
+    def test_nested_ma(self):
+
+        arr = np.ma.array([None, None])
+        # set the first object to be an unmasked masked constant. A little fiddly
+        arr[0,...] = np.array([np.ma.masked], object)[0,...]
+
+        # check the above line did what we were aiming for
+        assert_(arr.data[0] is np.ma.masked)
+
+        # test that getitem returned the value by identity
+        assert_(arr[0] is np.ma.masked)
+
+        # now mask the masked value!
+        arr[0] = np.ma.masked
+        assert_(arr[0] is np.ma.masked)
+
+
+class TestMaskedView:
+
+    def setup_method(self):
+        iterator = list(zip(np.arange(10), np.random.rand(10)))
+        data = np.array(iterator)
+        a = array(iterator, dtype=[('a', float), ('b', float)])
+        a.mask[0] = (1, 0)
+        controlmask = np.array([1] + 19 * [0], dtype=bool)
+        self.data = (data, a, controlmask)
+
+    def test_view_to_nothing(self):
+        (data, a, controlmask) = self.data
+        test = a.view()
+        assert_(isinstance(test, MaskedArray))
+        assert_equal(test._data, a._data)
+        assert_equal(test._mask, a._mask)
+
+    def test_view_to_type(self):
+        (data, a, controlmask) = self.data
+        test = a.view(np.ndarray)
+        assert_(not isinstance(test, MaskedArray))
+        assert_equal(test, a._data)
+        assert_equal_records(test, data.view(a.dtype).squeeze())
+
+    def test_view_to_simple_dtype(self):
+        (data, a, controlmask) = self.data
+        # View globally
+        test = a.view(float)
+        assert_(isinstance(test, MaskedArray))
+        assert_equal(test, data.ravel())
+        assert_equal(test.mask, controlmask)
+
+    def test_view_to_flexible_dtype(self):
+        (data, a, controlmask) = self.data
+
+        test = a.view([('A', float), ('B', float)])
+        assert_equal(test.mask.dtype.names, ('A', 'B'))
+        assert_equal(test['A'], a['a'])
+        assert_equal(test['B'], a['b'])
+
+        test = a[0].view([('A', float), ('B', float)])
+        assert_(isinstance(test, MaskedArray))
+        assert_equal(test.mask.dtype.names, ('A', 'B'))
+        assert_equal(test['A'], a['a'][0])
+        assert_equal(test['B'], a['b'][0])
+
+        test = a[-1].view([('A', float), ('B', float)])
+        assert_(isinstance(test, MaskedArray))
+        assert_equal(test.dtype.names, ('A', 'B'))
+        assert_equal(test['A'], a['a'][-1])
+        assert_equal(test['B'], a['b'][-1])
+
+    def test_view_to_subdtype(self):
+        (data, a, controlmask) = self.data
+        # View globally
+        test = a.view((float, 2))
+        assert_(isinstance(test, MaskedArray))
+        assert_equal(test, data)
+        assert_equal(test.mask, controlmask.reshape(-1, 2))
+        # View on 1 masked element
+        test = a[0].view((float, 2))
+        assert_(isinstance(test, MaskedArray))
+        assert_equal(test, data[0])
+        assert_equal(test.mask, (1, 0))
+        # View on 1 unmasked element
+        test = a[-1].view((float, 2))
+        assert_(isinstance(test, MaskedArray))
+        assert_equal(test, data[-1])
+
+    def test_view_to_dtype_and_type(self):
+        (data, a, controlmask) = self.data
+
+        test = a.view((float, 2), np.recarray)
+        assert_equal(test, data)
+        assert_(isinstance(test, np.recarray))
+        assert_(not isinstance(test, MaskedArray))
+
+
+class TestOptionalArgs:
+    def test_ndarrayfuncs(self):
+        # test axis arg behaves the same as ndarray (including multiple axes)
+
+        d = np.arange(24.0).reshape((2,3,4))
+        m = np.zeros(24, dtype=bool).reshape((2,3,4))
+        # mask out last element of last dimension
+        m[:,:,-1] = True
+        a = np.ma.array(d, mask=m)
+
+        def testaxis(f, a, d):
+            numpy_f = numpy.__getattribute__(f)
+            ma_f = np.ma.__getattribute__(f)
+
+            # test axis arg
+            assert_equal(ma_f(a, axis=1)[...,:-1], numpy_f(d[...,:-1], axis=1))
+            assert_equal(ma_f(a, axis=(0,1))[...,:-1],
+                         numpy_f(d[...,:-1], axis=(0,1)))
+
+        def testkeepdims(f, a, d):
+            numpy_f = numpy.__getattribute__(f)
+            ma_f = np.ma.__getattribute__(f)
+
+            # test keepdims arg
+            assert_equal(ma_f(a, keepdims=True).shape,
+                         numpy_f(d, keepdims=True).shape)
+            assert_equal(ma_f(a, keepdims=False).shape,
+                         numpy_f(d, keepdims=False).shape)
+
+            # test both at once
+            assert_equal(ma_f(a, axis=1, keepdims=True)[...,:-1],
+                         numpy_f(d[...,:-1], axis=1, keepdims=True))
+            assert_equal(ma_f(a, axis=(0,1), keepdims=True)[...,:-1],
+                         numpy_f(d[...,:-1], axis=(0,1), keepdims=True))
+
+        for f in ['sum', 'prod', 'mean', 'var', 'std']:
+            testaxis(f, a, d)
+            testkeepdims(f, a, d)
+
+        for f in ['min', 'max']:
+            testaxis(f, a, d)
+
+        d = (np.arange(24).reshape((2,3,4))%2 == 0)
+        a = np.ma.array(d, mask=m)
+        for f in ['all', 'any']:
+            testaxis(f, a, d)
+            testkeepdims(f, a, d)
+
+    def test_count(self):
+        # test np.ma.count specially
+
+        d = np.arange(24.0).reshape((2,3,4))
+        m = np.zeros(24, dtype=bool).reshape((2,3,4))
+        m[:,0,:] = True
+        a = np.ma.array(d, mask=m)
+
+        assert_equal(count(a), 16)
+        assert_equal(count(a, axis=1), 2*ones((2,4)))
+        assert_equal(count(a, axis=(0,1)), 4*ones((4,)))
+        assert_equal(count(a, keepdims=True), 16*ones((1,1,1)))
+        assert_equal(count(a, axis=1, keepdims=True), 2*ones((2,1,4)))
+        assert_equal(count(a, axis=(0,1), keepdims=True), 4*ones((1,1,4)))
+        assert_equal(count(a, axis=-2), 2*ones((2,4)))
+        assert_raises(ValueError, count, a, axis=(1,1))
+        assert_raises(np.AxisError, count, a, axis=3)
+
+        # check the 'nomask' path
+        a = np.ma.array(d, mask=nomask)
+
+        assert_equal(count(a), 24)
+        assert_equal(count(a, axis=1), 3*ones((2,4)))
+        assert_equal(count(a, axis=(0,1)), 6*ones((4,)))
+        assert_equal(count(a, keepdims=True), 24*ones((1,1,1)))
+        assert_equal(np.ndim(count(a, keepdims=True)), 3)
+        assert_equal(count(a, axis=1, keepdims=True), 3*ones((2,1,4)))
+        assert_equal(count(a, axis=(0,1), keepdims=True), 6*ones((1,1,4)))
+        assert_equal(count(a, axis=-2), 3*ones((2,4)))
+        assert_raises(ValueError, count, a, axis=(1,1))
+        assert_raises(np.AxisError, count, a, axis=3)
+
+        # check the 'masked' singleton
+        assert_equal(count(np.ma.masked), 0)
+
+        # check 0-d arrays do not allow axis > 0
+        assert_raises(np.AxisError, count, np.ma.array(1), axis=1)
+
+
+class TestMaskedConstant:
+    def _do_add_test(self, add):
+        # sanity check
+        assert_(add(np.ma.masked, 1) is np.ma.masked)
+
+        # now try with a vector
+        vector = np.array([1, 2, 3])
+        result = add(np.ma.masked, vector)
+
+        # lots of things could go wrong here
+        assert_(result is not np.ma.masked)
+        assert_(not isinstance(result, np.ma.core.MaskedConstant))
+        assert_equal(result.shape, vector.shape)
+        assert_equal(np.ma.getmask(result), np.ones(vector.shape, dtype=bool))
+
+    def test_ufunc(self):
+        self._do_add_test(np.add)
+
+    def test_operator(self):
+        self._do_add_test(lambda a, b: a + b)
+
+    def test_ctor(self):
+        m = np.ma.array(np.ma.masked)
+
+        # most importantly, we do not want to create a new MaskedConstant
+        # instance
+        assert_(not isinstance(m, np.ma.core.MaskedConstant))
+        assert_(m is not np.ma.masked)
+
+    def test_repr(self):
+        # copies should not exist, but if they do, it should be obvious that
+        # something is wrong
+        assert_equal(repr(np.ma.masked), 'masked')
+
+        # create a new instance in a weird way
+        masked2 = np.ma.MaskedArray.__new__(np.ma.core.MaskedConstant)
+        assert_not_equal(repr(masked2), 'masked')
+
+    def test_pickle(self):
+        from io import BytesIO
+
+        for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
+            with BytesIO() as f:
+                pickle.dump(np.ma.masked, f, protocol=proto)
+                f.seek(0)
+                res = pickle.load(f)
+            assert_(res is np.ma.masked)
+
+    def test_copy(self):
+        # gh-9328
+        # copy is a no-op, like it is with np.True_
+        assert_equal(
+            np.ma.masked.copy() is np.ma.masked,
+            np.True_.copy() is np.True_)
+
+    def test__copy(self):
+        import copy
+        assert_(
+            copy.copy(np.ma.masked) is np.ma.masked)
+
+    def test_deepcopy(self):
+        import copy
+        assert_(
+            copy.deepcopy(np.ma.masked) is np.ma.masked)
+
+    def test_immutable(self):
+        orig = np.ma.masked
+        assert_raises(np.ma.core.MaskError, operator.setitem, orig, (), 1)
+        assert_raises(ValueError,operator.setitem, orig.data, (), 1)
+        assert_raises(ValueError, operator.setitem, orig.mask, (), False)
+
+        view = np.ma.masked.view(np.ma.MaskedArray)
+        assert_raises(ValueError, operator.setitem, view, (), 1)
+        assert_raises(ValueError, operator.setitem, view.data, (), 1)
+        assert_raises(ValueError, operator.setitem, view.mask, (), False)
+
+    def test_coercion_int(self):
+        a_i = np.zeros((), int)
+        assert_raises(MaskError, operator.setitem, a_i, (), np.ma.masked)
+        assert_raises(MaskError, int, np.ma.masked)
+
+    def test_coercion_float(self):
+        a_f = np.zeros((), float)
+        assert_warns(UserWarning, operator.setitem, a_f, (), np.ma.masked)
+        assert_(np.isnan(a_f[()]))
+
+    @pytest.mark.xfail(reason="See gh-9750")
+    def test_coercion_unicode(self):
+        a_u = np.zeros((), 'U10')
+        a_u[()] = np.ma.masked
+        assert_equal(a_u[()], '--')
+
+    @pytest.mark.xfail(reason="See gh-9750")
+    def test_coercion_bytes(self):
+        a_b = np.zeros((), 'S10')
+        a_b[()] = np.ma.masked
+        assert_equal(a_b[()], b'--')
+
+    def test_subclass(self):
+        # https://github.com/astropy/astropy/issues/6645
+        class Sub(type(np.ma.masked)): pass
+
+        a = Sub()
+        assert_(a is Sub())
+        assert_(a is not np.ma.masked)
+        assert_not_equal(repr(a), 'masked')
+
+    def test_attributes_readonly(self):
+        assert_raises(AttributeError, setattr, np.ma.masked, 'shape', (1,))
+        assert_raises(AttributeError, setattr, np.ma.masked, 'dtype', np.int64)
+
+
+class TestMaskedWhereAliases:
+
+    # TODO: Test masked_object, masked_equal, ...
+
+    def test_masked_values(self):
+        res = masked_values(np.array([-32768.0]), np.int16(-32768))
+        assert_equal(res.mask, [True])
+
+        res = masked_values(np.inf, np.inf)
+        assert_equal(res.mask, True)
+
+        res = np.ma.masked_values(np.inf, -np.inf)
+        assert_equal(res.mask, False)
+
+        res = np.ma.masked_values([1, 2, 3, 4], 5, shrink=True)
+        assert_(res.mask is np.ma.nomask)
+
+        res = np.ma.masked_values([1, 2, 3, 4], 5, shrink=False)
+        assert_equal(res.mask, [False] * 4)
+
+
+def test_masked_array():
+    a = np.ma.array([0, 1, 2, 3], mask=[0, 0, 1, 0])
+    assert_equal(np.argwhere(a), [[1], [3]])
+
+def test_masked_array_no_copy():
+    # check nomask array is updated in place
+    a = np.ma.array([1, 2, 3, 4])
+    _ = np.ma.masked_where(a == 3, a, copy=False)
+    assert_array_equal(a.mask, [False, False, True, False])
+    # check masked array is updated in place
+    a = np.ma.array([1, 2, 3, 4], mask=[1, 0, 0, 0])
+    _ = np.ma.masked_where(a == 3, a, copy=False)
+    assert_array_equal(a.mask, [True, False, True, False])
+    # check masked array with masked_invalid is updated in place
+    a = np.ma.array([np.inf, 1, 2, 3, 4])
+    _ = np.ma.masked_invalid(a, copy=False)
+    assert_array_equal(a.mask, [True, False, False, False, False])
+
+def test_append_masked_array():
+    a = np.ma.masked_equal([1,2,3], value=2)
+    b = np.ma.masked_equal([4,3,2], value=2)
+
+    result = np.ma.append(a, b)
+    expected_data = [1, 2, 3, 4, 3, 2]
+    expected_mask = [False, True, False, False, False, True]
+    assert_array_equal(result.data, expected_data)
+    assert_array_equal(result.mask, expected_mask)
+
+    a = np.ma.masked_all((2,2))
+    b = np.ma.ones((3,1))
+
+    result = np.ma.append(a, b)
+    expected_data = [1] * 3
+    expected_mask = [True] * 4 + [False] * 3
+    assert_array_equal(result.data[-3], expected_data)
+    assert_array_equal(result.mask, expected_mask)
+
+    result = np.ma.append(a, b, axis=None)
+    assert_array_equal(result.data[-3], expected_data)
+    assert_array_equal(result.mask, expected_mask)
+
+
+def test_append_masked_array_along_axis():
+    a = np.ma.masked_equal([1,2,3], value=2)
+    b = np.ma.masked_values([[4, 5, 6], [7, 8, 9]], 7)
+
+    # When `axis` is specified, `values` must have the correct shape.
+    assert_raises(ValueError, np.ma.append, a, b, axis=0)
+
+    result = np.ma.append(a[np.newaxis,:], b, axis=0)
+    expected = np.ma.arange(1, 10)
+    expected[[1, 6]] = np.ma.masked
+    expected = expected.reshape((3,3))
+    assert_array_equal(result.data, expected.data)
+    assert_array_equal(result.mask, expected.mask)
+
+def test_default_fill_value_complex():
+    # regression test for Python 3, where 'unicode' was not defined
+    assert_(default_fill_value(1 + 1j) == 1.e20 + 0.0j)
+
+
+def test_ufunc_with_output():
+    # check that giving an output argument always returns that output.
+    # Regression test for gh-8416.
+    x = array([1., 2., 3.], mask=[0, 0, 1])
+    y = np.add(x, 1., out=x)
+    assert_(y is x)
+
+
+def test_ufunc_with_out_varied():
+    """ Test that masked arrays are immune to gh-10459 """
+    # the mask of the output should not affect the result, however it is passed
+    a        = array([ 1,  2,  3], mask=[1, 0, 0])
+    b        = array([10, 20, 30], mask=[1, 0, 0])
+    out      = array([ 0,  0,  0], mask=[0, 0, 1])
+    expected = array([11, 22, 33], mask=[1, 0, 0])
+
+    out_pos = out.copy()
+    res_pos = np.add(a, b, out_pos)
+
+    out_kw = out.copy()
+    res_kw = np.add(a, b, out=out_kw)
+
+    out_tup = out.copy()
+    res_tup = np.add(a, b, out=(out_tup,))
+
+    assert_equal(res_kw.mask,  expected.mask)
+    assert_equal(res_kw.data,  expected.data)
+    assert_equal(res_tup.mask, expected.mask)
+    assert_equal(res_tup.data, expected.data)
+    assert_equal(res_pos.mask, expected.mask)
+    assert_equal(res_pos.data, expected.data)
+
+
+def test_astype_mask_ordering():
+    descr = np.dtype([('v', int, 3), ('x', [('y', float)])])
+    x = array([
+        [([1, 2, 3], (1.0,)),  ([1, 2, 3], (2.0,))],
+        [([1, 2, 3], (3.0,)),  ([1, 2, 3], (4.0,))]], dtype=descr)
+    x[0]['v'][0] = np.ma.masked
+
+    x_a = x.astype(descr)
+    assert x_a.dtype.names == np.dtype(descr).names
+    assert x_a.mask.dtype.names == np.dtype(descr).names
+    assert_equal(x, x_a)
+
+    assert_(x is x.astype(x.dtype, copy=False))
+    assert_equal(type(x.astype(x.dtype, subok=False)), np.ndarray)
+
+    x_f = x.astype(x.dtype, order='F')
+    assert_(x_f.flags.f_contiguous)
+    assert_(x_f.mask.flags.f_contiguous)
+
+    # Also test the same indirectly, via np.array
+    x_a2 = np.array(x, dtype=descr, subok=True)
+    assert x_a2.dtype.names == np.dtype(descr).names
+    assert x_a2.mask.dtype.names == np.dtype(descr).names
+    assert_equal(x, x_a2)
+
+    assert_(x is np.array(x, dtype=descr, copy=False, subok=True))
+
+    x_f2 = np.array(x, dtype=x.dtype, order='F', subok=True)
+    assert_(x_f2.flags.f_contiguous)
+    assert_(x_f2.mask.flags.f_contiguous)
+
+
+@pytest.mark.parametrize('dt1', num_dts, ids=num_ids)
+@pytest.mark.parametrize('dt2', num_dts, ids=num_ids)
+@pytest.mark.filterwarnings('ignore::numpy.ComplexWarning')
+def test_astype_basic(dt1, dt2):
+    # See gh-12070
+    src = np.ma.array(ones(3, dt1), fill_value=1)
+    dst = src.astype(dt2)
+
+    assert_(src.fill_value == 1)
+    assert_(src.dtype == dt1)
+    assert_(src.fill_value.dtype == dt1)
+
+    assert_(dst.fill_value == 1)
+    assert_(dst.dtype == dt2)
+    assert_(dst.fill_value.dtype == dt2)
+
+    assert_equal(src, dst)
+
+
+def test_fieldless_void():
+    dt = np.dtype([])  # a void dtype with no fields
+    x = np.empty(4, dt)
+
+    # these arrays contain no values, so there's little to test - but this
+    # shouldn't crash
+    mx = np.ma.array(x)
+    assert_equal(mx.dtype, x.dtype)
+    assert_equal(mx.shape, x.shape)
+
+    mx = np.ma.array(x, mask=x)
+    assert_equal(mx.dtype, x.dtype)
+    assert_equal(mx.shape, x.shape)
+
+
+def test_mask_shape_assignment_does_not_break_masked():
+    a = np.ma.masked
+    b = np.ma.array(1, mask=a.mask)
+    b.shape = (1,)
+    assert_equal(a.mask.shape, ())
+
+@pytest.mark.skipif(sys.flags.optimize > 1,
+                    reason="no docstrings present to inspect when PYTHONOPTIMIZE/Py_OptimizeFlag > 1")
+def test_doc_note():
+    def method(self):
+        """This docstring
+
+        Has multiple lines
+
+        And notes
+
+        Notes
+        -----
+        original note
+        """
+        pass
+
+    expected_doc = """This docstring
+
+Has multiple lines
+
+And notes
+
+Notes
+-----
+note
+
+original note"""
+
+    assert_equal(np.ma.core.doc_note(method.__doc__, "note"), expected_doc)
+
+
+def test_gh_22556():
+    source = np.ma.array([0, [0, 1, 2]], dtype=object)
+    deepcopy = copy.deepcopy(source)
+    deepcopy[1].append('this should not appear in source')
+    assert len(source[1]) == 3
+
+
+def test_gh_21022():
+    # testing for absence of reported error
+    source = np.ma.masked_array(data=[-1, -1], mask=True, dtype=np.float64)
+    axis = np.array(0)
+    result = np.prod(source, axis=axis, keepdims=False)
+    result = np.ma.masked_array(result,
+                                mask=np.ones(result.shape, dtype=np.bool_))
+    array = np.ma.masked_array(data=-1, mask=True, dtype=np.float64)
+    copy.deepcopy(array)
+    copy.deepcopy(result)
+
+
+def test_deepcopy_2d_obj():
+    source = np.ma.array([[0, "dog"],
+                          [1, 1],
+                          [[1, 2], "cat"]],
+                        mask=[[0, 1],
+                              [0, 0],
+                              [0, 0]],
+                        dtype=object)
+    deepcopy = copy.deepcopy(source)
+    deepcopy[2, 0].extend(['this should not appear in source', 3])
+    assert len(source[2, 0]) == 2
+    assert len(deepcopy[2, 0]) == 4
+    assert_equal(deepcopy._mask, source._mask)
+    deepcopy._mask[0, 0] = 1
+    assert source._mask[0, 0] == 0
+
+
+def test_deepcopy_0d_obj():
+    source = np.ma.array(0, mask=[0], dtype=object)
+    deepcopy = copy.deepcopy(source)
+    deepcopy[...] = 17
+    assert_equal(source, 0)
+    assert_equal(deepcopy, 17)
diff --git a/venv/lib/python3.10/site-packages/numpy/ma/tests/test_deprecations.py b/venv/lib/python3.10/site-packages/numpy/ma/tests/test_deprecations.py
new file mode 100644
index 0000000000000000000000000000000000000000..40c8418f5c1809130672dca46e8c43469692da09
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/numpy/ma/tests/test_deprecations.py
@@ -0,0 +1,84 @@
+"""Test deprecation and future warnings.
+
+"""
+import pytest
+import numpy as np
+from numpy.testing import assert_warns
+from numpy.ma.testutils import assert_equal
+from numpy.ma.core import MaskedArrayFutureWarning
+import io
+import textwrap
+
+class TestArgsort:
+    """ gh-8701 """
+    def _test_base(self, argsort, cls):
+        arr_0d = np.array(1).view(cls)
+        argsort(arr_0d)
+
+        arr_1d = np.array([1, 2, 3]).view(cls)
+        argsort(arr_1d)
+
+        # argsort has a bad default for >1d arrays
+        arr_2d = np.array([[1, 2], [3, 4]]).view(cls)
+        result = assert_warns(
+            np.ma.core.MaskedArrayFutureWarning, argsort, arr_2d)
+        assert_equal(result, argsort(arr_2d, axis=None))
+
+        # should be no warnings for explicitly specifying it
+        argsort(arr_2d, axis=None)
+        argsort(arr_2d, axis=-1)
+
+    def test_function_ndarray(self):
+        return self._test_base(np.ma.argsort, np.ndarray)
+
+    def test_function_maskedarray(self):
+        return self._test_base(np.ma.argsort, np.ma.MaskedArray)
+
+    def test_method(self):
+        return self._test_base(np.ma.MaskedArray.argsort, np.ma.MaskedArray)
+
+
+class TestMinimumMaximum:
+
+    def test_axis_default(self):
+        # NumPy 1.13, 2017-05-06
+
+        data1d = np.ma.arange(6)
+        data2d = data1d.reshape(2, 3)
+
+        ma_min = np.ma.minimum.reduce
+        ma_max = np.ma.maximum.reduce
+
+        # check that the default axis is still None, but warns on 2d arrays
+        result = assert_warns(MaskedArrayFutureWarning, ma_max, data2d)
+        assert_equal(result, ma_max(data2d, axis=None))
+
+        result = assert_warns(MaskedArrayFutureWarning, ma_min, data2d)
+        assert_equal(result, ma_min(data2d, axis=None))
+
+        # no warnings on 1d, as both new and old defaults are equivalent
+        result = ma_min(data1d)
+        assert_equal(result, ma_min(data1d, axis=None))
+        assert_equal(result, ma_min(data1d, axis=0))
+
+        result = ma_max(data1d)
+        assert_equal(result, ma_max(data1d, axis=None))
+        assert_equal(result, ma_max(data1d, axis=0))
+
+
+class TestFromtextfile:
+    def test_fromtextfile_delimitor(self):
+        # NumPy 1.22.0, 2021-09-23
+
+        textfile = io.StringIO(textwrap.dedent(
+            """
+            A,B,C,D
+            'string 1';1;1.0;'mixed column'
+            'string 2';2;2.0;
+            'string 3';3;3.0;123
+            'string 4';4;4.0;3.14
+            """
+        ))
+
+        with pytest.warns(DeprecationWarning):
+            result = np.ma.mrecords.fromtextfile(textfile, delimitor=';')
diff --git a/venv/lib/python3.10/site-packages/numpy/ma/tests/test_extras.py b/venv/lib/python3.10/site-packages/numpy/ma/tests/test_extras.py
new file mode 100644
index 0000000000000000000000000000000000000000..d09a50fecd4a62e06e202a2c07443d9a58332e4a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/numpy/ma/tests/test_extras.py
@@ -0,0 +1,1870 @@
+# pylint: disable-msg=W0611, W0612, W0511
+"""Tests suite for MaskedArray.
+Adapted from the original test_ma by Pierre Gerard-Marchant
+
+:author: Pierre Gerard-Marchant
+:contact: pierregm_at_uga_dot_edu
+:version: $Id: test_extras.py 3473 2007-10-29 15:18:13Z jarrod.millman $
+
+"""
+import warnings
+import itertools
+import pytest
+
+import numpy as np
+from numpy.core.numeric import normalize_axis_tuple
+from numpy.testing import (
+    assert_warns, suppress_warnings
+    )
+from numpy.ma.testutils import (
+    assert_, assert_array_equal, assert_equal, assert_almost_equal
+    )
+from numpy.ma.core import (
+    array, arange, masked, MaskedArray, masked_array, getmaskarray, shape,
+    nomask, ones, zeros, count
+    )
+from numpy.ma.extras import (
+    atleast_1d, atleast_2d, atleast_3d, mr_, dot, polyfit, cov, corrcoef,
+    median, average, unique, setxor1d, setdiff1d, union1d, intersect1d, in1d,
+    ediff1d, apply_over_axes, apply_along_axis, compress_nd, compress_rowcols,
+    mask_rowcols, clump_masked, clump_unmasked, flatnotmasked_contiguous,
+    notmasked_contiguous, notmasked_edges, masked_all, masked_all_like, isin,
+    diagflat, ndenumerate, stack, vstack
+    )
+
+
+class TestGeneric:
+    #
+    def test_masked_all(self):
+        # Tests masked_all
+        # Standard dtype
+        test = masked_all((2,), dtype=float)
+        control = array([1, 1], mask=[1, 1], dtype=float)
+        assert_equal(test, control)
+        # Flexible dtype
+        dt = np.dtype({'names': ['a', 'b'], 'formats': ['f', 'f']})
+        test = masked_all((2,), dtype=dt)
+        control = array([(0, 0), (0, 0)], mask=[(1, 1), (1, 1)], dtype=dt)
+        assert_equal(test, control)
+        test = masked_all((2, 2), dtype=dt)
+        control = array([[(0, 0), (0, 0)], [(0, 0), (0, 0)]],
+                        mask=[[(1, 1), (1, 1)], [(1, 1), (1, 1)]],
+                        dtype=dt)
+        assert_equal(test, control)
+        # Nested dtype
+        dt = np.dtype([('a', 'f'), ('b', [('ba', 'f'), ('bb', 'f')])])
+        test = masked_all((2,), dtype=dt)
+        control = array([(1, (1, 1)), (1, (1, 1))],
+                        mask=[(1, (1, 1)), (1, (1, 1))], dtype=dt)
+        assert_equal(test, control)
+        test = masked_all((2,), dtype=dt)
+        control = array([(1, (1, 1)), (1, (1, 1))],
+                        mask=[(1, (1, 1)), (1, (1, 1))], dtype=dt)
+        assert_equal(test, control)
+        test = masked_all((1, 1), dtype=dt)
+        control = array([[(1, (1, 1))]], mask=[[(1, (1, 1))]], dtype=dt)
+        assert_equal(test, control)
+
+    def test_masked_all_with_object_nested(self):
+        # Test masked_all works with nested array with dtype of an 'object'
+        # refers to issue #15895
+        my_dtype = np.dtype([('b', ([('c', object)], (1,)))])
+        masked_arr = np.ma.masked_all((1,), my_dtype)
+
+        assert_equal(type(masked_arr['b']), np.ma.core.MaskedArray)
+        assert_equal(type(masked_arr['b']['c']), np.ma.core.MaskedArray)
+        assert_equal(len(masked_arr['b']['c']), 1)
+        assert_equal(masked_arr['b']['c'].shape, (1, 1))
+        assert_equal(masked_arr['b']['c']._fill_value.shape, ())
+
+    def test_masked_all_with_object(self):
+        # same as above except that the array is not nested
+        my_dtype = np.dtype([('b', (object, (1,)))])
+        masked_arr = np.ma.masked_all((1,), my_dtype)
+
+        assert_equal(type(masked_arr['b']), np.ma.core.MaskedArray)
+        assert_equal(len(masked_arr['b']), 1)
+        assert_equal(masked_arr['b'].shape, (1, 1))
+        assert_equal(masked_arr['b']._fill_value.shape, ())
+
+    def test_masked_all_like(self):
+        # Tests masked_all
+        # Standard dtype
+        base = array([1, 2], dtype=float)
+        test = masked_all_like(base)
+        control = array([1, 1], mask=[1, 1], dtype=float)
+        assert_equal(test, control)
+        # Flexible dtype
+        dt = np.dtype({'names': ['a', 'b'], 'formats': ['f', 'f']})
+        base = array([(0, 0), (0, 0)], mask=[(1, 1), (1, 1)], dtype=dt)
+        test = masked_all_like(base)
+        control = array([(10, 10), (10, 10)], mask=[(1, 1), (1, 1)], dtype=dt)
+        assert_equal(test, control)
+        # Nested dtype
+        dt = np.dtype([('a', 'f'), ('b', [('ba', 'f'), ('bb', 'f')])])
+        control = array([(1, (1, 1)), (1, (1, 1))],
+                        mask=[(1, (1, 1)), (1, (1, 1))], dtype=dt)
+        test = masked_all_like(control)
+        assert_equal(test, control)
+
+    def check_clump(self, f):
+        for i in range(1, 7):
+            for j in range(2**i):
+                k = np.arange(i, dtype=int)
+                ja = np.full(i, j, dtype=int)
+                a = masked_array(2**k)
+                a.mask = (ja & (2**k)) != 0
+                s = 0
+                for sl in f(a):
+                    s += a.data[sl].sum()
+                if f == clump_unmasked:
+                    assert_equal(a.compressed().sum(), s)
+                else:
+                    a.mask = ~a.mask
+                    assert_equal(a.compressed().sum(), s)
+
+    def test_clump_masked(self):
+        # Test clump_masked
+        a = masked_array(np.arange(10))
+        a[[0, 1, 2, 6, 8, 9]] = masked
+        #
+        test = clump_masked(a)
+        control = [slice(0, 3), slice(6, 7), slice(8, 10)]
+        assert_equal(test, control)
+
+        self.check_clump(clump_masked)
+
+    def test_clump_unmasked(self):
+        # Test clump_unmasked
+        a = masked_array(np.arange(10))
+        a[[0, 1, 2, 6, 8, 9]] = masked
+        test = clump_unmasked(a)
+        control = [slice(3, 6), slice(7, 8), ]
+        assert_equal(test, control)
+
+        self.check_clump(clump_unmasked)
+
+    def test_flatnotmasked_contiguous(self):
+        # Test flatnotmasked_contiguous
+        a = arange(10)
+        # No mask
+        test = flatnotmasked_contiguous(a)
+        assert_equal(test, [slice(0, a.size)])
+        # mask of all false
+        a.mask = np.zeros(10, dtype=bool)
+        assert_equal(test, [slice(0, a.size)])
+        # Some mask
+        a[(a < 3) | (a > 8) | (a == 5)] = masked
+        test = flatnotmasked_contiguous(a)
+        assert_equal(test, [slice(3, 5), slice(6, 9)])
+        #
+        a[:] = masked
+        test = flatnotmasked_contiguous(a)
+        assert_equal(test, [])
+
+
+class TestAverage:
+    # Several tests of average. Why so many ? Good point...
+    def test_testAverage1(self):
+        # Test of average.
+        ott = array([0., 1., 2., 3.], mask=[True, False, False, False])
+        assert_equal(2.0, average(ott, axis=0))
+        assert_equal(2.0, average(ott, weights=[1., 1., 2., 1.]))
+        result, wts = average(ott, weights=[1., 1., 2., 1.], returned=True)
+        assert_equal(2.0, result)
+        assert_(wts == 4.0)
+        ott[:] = masked
+        assert_equal(average(ott, axis=0).mask, [True])
+        ott = array([0., 1., 2., 3.], mask=[True, False, False, False])
+        ott = ott.reshape(2, 2)
+        ott[:, 1] = masked
+        assert_equal(average(ott, axis=0), [2.0, 0.0])
+        assert_equal(average(ott, axis=1).mask[0], [True])
+        assert_equal([2., 0.], average(ott, axis=0))
+        result, wts = average(ott, axis=0, returned=True)
+        assert_equal(wts, [1., 0.])
+
+    def test_testAverage2(self):
+        # More tests of average.
+        w1 = [0, 1, 1, 1, 1, 0]
+        w2 = [[0, 1, 1, 1, 1, 0], [1, 0, 0, 0, 0, 1]]
+        x = arange(6, dtype=np.float_)
+        assert_equal(average(x, axis=0), 2.5)
+        assert_equal(average(x, axis=0, weights=w1), 2.5)
+        y = array([arange(6, dtype=np.float_), 2.0 * arange(6)])
+        assert_equal(average(y, None), np.add.reduce(np.arange(6)) * 3. / 12.)
+        assert_equal(average(y, axis=0), np.arange(6) * 3. / 2.)
+        assert_equal(average(y, axis=1),
+                     [average(x, axis=0), average(x, axis=0) * 2.0])
+        assert_equal(average(y, None, weights=w2), 20. / 6.)
+        assert_equal(average(y, axis=0, weights=w2),
+                     [0., 1., 2., 3., 4., 10.])
+        assert_equal(average(y, axis=1),
+                     [average(x, axis=0), average(x, axis=0) * 2.0])
+        m1 = zeros(6)
+        m2 = [0, 0, 1, 1, 0, 0]
+        m3 = [[0, 0, 1, 1, 0, 0], [0, 1, 1, 1, 1, 0]]
+        m4 = ones(6)
+        m5 = [0, 1, 1, 1, 1, 1]
+        assert_equal(average(masked_array(x, m1), axis=0), 2.5)
+        assert_equal(average(masked_array(x, m2), axis=0), 2.5)
+        assert_equal(average(masked_array(x, m4), axis=0).mask, [True])
+        assert_equal(average(masked_array(x, m5), axis=0), 0.0)
+        assert_equal(count(average(masked_array(x, m4), axis=0)), 0)
+        z = masked_array(y, m3)
+        assert_equal(average(z, None), 20. / 6.)
+        assert_equal(average(z, axis=0), [0., 1., 99., 99., 4.0, 7.5])
+        assert_equal(average(z, axis=1), [2.5, 5.0])
+        assert_equal(average(z, axis=0, weights=w2),
+                     [0., 1., 99., 99., 4.0, 10.0])
+
+    def test_testAverage3(self):
+        # Yet more tests of average!
+        a = arange(6)
+        b = arange(6) * 3
+        r1, w1 = average([[a, b], [b, a]], axis=1, returned=True)
+        assert_equal(shape(r1), shape(w1))
+        assert_equal(r1.shape, w1.shape)
+        r2, w2 = average(ones((2, 2, 3)), axis=0, weights=[3, 1], returned=True)
+        assert_equal(shape(w2), shape(r2))
+        r2, w2 = average(ones((2, 2, 3)), returned=True)
+        assert_equal(shape(w2), shape(r2))
+        r2, w2 = average(ones((2, 2, 3)), weights=ones((2, 2, 3)), returned=True)
+        assert_equal(shape(w2), shape(r2))
+        a2d = array([[1, 2], [0, 4]], float)
+        a2dm = masked_array(a2d, [[False, False], [True, False]])
+        a2da = average(a2d, axis=0)
+        assert_equal(a2da, [0.5, 3.0])
+        a2dma = average(a2dm, axis=0)
+        assert_equal(a2dma, [1.0, 3.0])
+        a2dma = average(a2dm, axis=None)
+        assert_equal(a2dma, 7. / 3.)
+        a2dma = average(a2dm, axis=1)
+        assert_equal(a2dma, [1.5, 4.0])
+
+    def test_testAverage4(self):
+        # Test that `keepdims` works with average
+        x = np.array([2, 3, 4]).reshape(3, 1)
+        b = np.ma.array(x, mask=[[False], [False], [True]])
+        w = np.array([4, 5, 6]).reshape(3, 1)
+        actual = average(b, weights=w, axis=1, keepdims=True)
+        desired = masked_array([[2.], [3.], [4.]], [[False], [False], [True]])
+        assert_equal(actual, desired)
+
+    def test_onintegers_with_mask(self):
+        # Test average on integers with mask
+        a = average(array([1, 2]))
+        assert_equal(a, 1.5)
+        a = average(array([1, 2, 3, 4], mask=[False, False, True, True]))
+        assert_equal(a, 1.5)
+
+    def test_complex(self):
+        # Test with complex data.
+        # (Regression test for https://github.com/numpy/numpy/issues/2684)
+        mask = np.array([[0, 0, 0, 1, 0],
+                         [0, 1, 0, 0, 0]], dtype=bool)
+        a = masked_array([[0, 1+2j, 3+4j, 5+6j, 7+8j],
+                          [9j, 0+1j, 2+3j, 4+5j, 7+7j]],
+                         mask=mask)
+
+        av = average(a)
+        expected = np.average(a.compressed())
+        assert_almost_equal(av.real, expected.real)
+        assert_almost_equal(av.imag, expected.imag)
+
+        av0 = average(a, axis=0)
+        expected0 = average(a.real, axis=0) + average(a.imag, axis=0)*1j
+        assert_almost_equal(av0.real, expected0.real)
+        assert_almost_equal(av0.imag, expected0.imag)
+
+        av1 = average(a, axis=1)
+        expected1 = average(a.real, axis=1) + average(a.imag, axis=1)*1j
+        assert_almost_equal(av1.real, expected1.real)
+        assert_almost_equal(av1.imag, expected1.imag)
+
+        # Test with the 'weights' argument.
+        wts = np.array([[0.5, 1.0, 2.0, 1.0, 0.5],
+                        [1.0, 1.0, 1.0, 1.0, 1.0]])
+        wav = average(a, weights=wts)
+        expected = np.average(a.compressed(), weights=wts[~mask])
+        assert_almost_equal(wav.real, expected.real)
+        assert_almost_equal(wav.imag, expected.imag)
+
+        wav0 = average(a, weights=wts, axis=0)
+        expected0 = (average(a.real, weights=wts, axis=0) +
+                     average(a.imag, weights=wts, axis=0)*1j)
+        assert_almost_equal(wav0.real, expected0.real)
+        assert_almost_equal(wav0.imag, expected0.imag)
+
+        wav1 = average(a, weights=wts, axis=1)
+        expected1 = (average(a.real, weights=wts, axis=1) +
+                     average(a.imag, weights=wts, axis=1)*1j)
+        assert_almost_equal(wav1.real, expected1.real)
+        assert_almost_equal(wav1.imag, expected1.imag)
+
+    @pytest.mark.parametrize(
+        'x, axis, expected_avg, weights, expected_wavg, expected_wsum',
+        [([1, 2, 3], None, [2.0], [3, 4, 1], [1.75], [8.0]),
+         ([[1, 2, 5], [1, 6, 11]], 0, [[1.0, 4.0, 8.0]],
+          [1, 3], [[1.0, 5.0, 9.5]], [[4, 4, 4]])],
+    )
+    def test_basic_keepdims(self, x, axis, expected_avg,
+                            weights, expected_wavg, expected_wsum):
+        avg = np.ma.average(x, axis=axis, keepdims=True)
+        assert avg.shape == np.shape(expected_avg)
+        assert_array_equal(avg, expected_avg)
+
+        wavg = np.ma.average(x, axis=axis, weights=weights, keepdims=True)
+        assert wavg.shape == np.shape(expected_wavg)
+        assert_array_equal(wavg, expected_wavg)
+
+        wavg, wsum = np.ma.average(x, axis=axis, weights=weights,
+                                   returned=True, keepdims=True)
+        assert wavg.shape == np.shape(expected_wavg)
+        assert_array_equal(wavg, expected_wavg)
+        assert wsum.shape == np.shape(expected_wsum)
+        assert_array_equal(wsum, expected_wsum)
+
+    def test_masked_weights(self):
+        # Test with masked weights.
+        # (Regression test for https://github.com/numpy/numpy/issues/10438)
+        a = np.ma.array(np.arange(9).reshape(3, 3),
+                        mask=[[1, 0, 0], [1, 0, 0], [0, 0, 0]])
+        weights_unmasked = masked_array([5, 28, 31], mask=False)
+        weights_masked = masked_array([5, 28, 31], mask=[1, 0, 0])
+
+        avg_unmasked = average(a, axis=0,
+                               weights=weights_unmasked, returned=False)
+        expected_unmasked = np.array([6.0, 5.21875, 6.21875])
+        assert_almost_equal(avg_unmasked, expected_unmasked)
+
+        avg_masked = average(a, axis=0, weights=weights_masked, returned=False)
+        expected_masked = np.array([6.0, 5.576271186440678, 6.576271186440678])
+        assert_almost_equal(avg_masked, expected_masked)
+
+        # weights should be masked if needed
+        # depending on the array mask. This is to avoid summing
+        # masked nan or other values that are not cancelled by a zero
+        a = np.ma.array([1.0,   2.0,   3.0,  4.0],
+                   mask=[False, False, True, True])
+        avg_unmasked = average(a, weights=[1, 1, 1, np.nan])
+
+        assert_almost_equal(avg_unmasked, 1.5)
+
+        a = np.ma.array([
+            [1.0, 2.0, 3.0, 4.0],
+            [5.0, 6.0, 7.0, 8.0],
+            [9.0, 1.0, 2.0, 3.0],
+        ], mask=[
+            [False, True, True, False],
+            [True, False, True, True],
+            [True, False, True, False],
+        ])
+
+        avg_masked = np.ma.average(a, weights=[1, np.nan, 1], axis=0)
+        avg_expected = np.ma.array([1.0, np.nan, np.nan, 3.5],
+                              mask=[False, True, True, False])
+
+        assert_almost_equal(avg_masked, avg_expected)
+        assert_equal(avg_masked.mask, avg_expected.mask)
+
+
+class TestConcatenator:
+    # Tests for mr_, the equivalent of r_ for masked arrays.
+
+    def test_1d(self):
+        # Tests mr_ on 1D arrays.
+        assert_array_equal(mr_[1, 2, 3, 4, 5, 6], array([1, 2, 3, 4, 5, 6]))
+        b = ones(5)
+        m = [1, 0, 0, 0, 0]
+        d = masked_array(b, mask=m)
+        c = mr_[d, 0, 0, d]
+        assert_(isinstance(c, MaskedArray))
+        assert_array_equal(c, [1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1])
+        assert_array_equal(c.mask, mr_[m, 0, 0, m])
+
+    def test_2d(self):
+        # Tests mr_ on 2D arrays.
+        a_1 = np.random.rand(5, 5)
+        a_2 = np.random.rand(5, 5)
+        m_1 = np.round(np.random.rand(5, 5), 0)
+        m_2 = np.round(np.random.rand(5, 5), 0)
+        b_1 = masked_array(a_1, mask=m_1)
+        b_2 = masked_array(a_2, mask=m_2)
+        # append columns
+        d = mr_['1', b_1, b_2]
+        assert_(d.shape == (5, 10))
+        assert_array_equal(d[:, :5], b_1)
+        assert_array_equal(d[:, 5:], b_2)
+        assert_array_equal(d.mask, np.r_['1', m_1, m_2])
+        d = mr_[b_1, b_2]
+        assert_(d.shape == (10, 5))
+        assert_array_equal(d[:5,:], b_1)
+        assert_array_equal(d[5:,:], b_2)
+        assert_array_equal(d.mask, np.r_[m_1, m_2])
+
+    def test_masked_constant(self):
+        actual = mr_[np.ma.masked, 1]
+        assert_equal(actual.mask, [True, False])
+        assert_equal(actual.data[1], 1)
+
+        actual = mr_[[1, 2], np.ma.masked]
+        assert_equal(actual.mask, [False, False, True])
+        assert_equal(actual.data[:2], [1, 2])
+
+
+class TestNotMasked:
+    # Tests notmasked_edges and notmasked_contiguous.
+
+    def test_edges(self):
+        # Tests unmasked_edges
+        data = masked_array(np.arange(25).reshape(5, 5),
+                            mask=[[0, 0, 1, 0, 0],
+                                  [0, 0, 0, 1, 1],
+                                  [1, 1, 0, 0, 0],
+                                  [0, 0, 0, 0, 0],
+                                  [1, 1, 1, 0, 0]],)
+        test = notmasked_edges(data, None)
+        assert_equal(test, [0, 24])
+        test = notmasked_edges(data, 0)
+        assert_equal(test[0], [(0, 0, 1, 0, 0), (0, 1, 2, 3, 4)])
+        assert_equal(test[1], [(3, 3, 3, 4, 4), (0, 1, 2, 3, 4)])
+        test = notmasked_edges(data, 1)
+        assert_equal(test[0], [(0, 1, 2, 3, 4), (0, 0, 2, 0, 3)])
+        assert_equal(test[1], [(0, 1, 2, 3, 4), (4, 2, 4, 4, 4)])
+        #
+        test = notmasked_edges(data.data, None)
+        assert_equal(test, [0, 24])
+        test = notmasked_edges(data.data, 0)
+        assert_equal(test[0], [(0, 0, 0, 0, 0), (0, 1, 2, 3, 4)])
+        assert_equal(test[1], [(4, 4, 4, 4, 4), (0, 1, 2, 3, 4)])
+        test = notmasked_edges(data.data, -1)
+        assert_equal(test[0], [(0, 1, 2, 3, 4), (0, 0, 0, 0, 0)])
+        assert_equal(test[1], [(0, 1, 2, 3, 4), (4, 4, 4, 4, 4)])
+        #
+        data[-2] = masked
+        test = notmasked_edges(data, 0)
+        assert_equal(test[0], [(0, 0, 1, 0, 0), (0, 1, 2, 3, 4)])
+        assert_equal(test[1], [(1, 1, 2, 4, 4), (0, 1, 2, 3, 4)])
+        test = notmasked_edges(data, -1)
+        assert_equal(test[0], [(0, 1, 2, 4), (0, 0, 2, 3)])
+        assert_equal(test[1], [(0, 1, 2, 4), (4, 2, 4, 4)])
+
+    def test_contiguous(self):
+        # Tests notmasked_contiguous
+        a = masked_array(np.arange(24).reshape(3, 8),
+                         mask=[[0, 0, 0, 0, 1, 1, 1, 1],
+                               [1, 1, 1, 1, 1, 1, 1, 1],
+                               [0, 0, 0, 0, 0, 0, 1, 0]])
+        tmp = notmasked_contiguous(a, None)
+        assert_equal(tmp, [
+            slice(0, 4, None),
+            slice(16, 22, None),
+            slice(23, 24, None)
+        ])
+
+        tmp = notmasked_contiguous(a, 0)
+        assert_equal(tmp, [
+            [slice(0, 1, None), slice(2, 3, None)],
+            [slice(0, 1, None), slice(2, 3, None)],
+            [slice(0, 1, None), slice(2, 3, None)],
+            [slice(0, 1, None), slice(2, 3, None)],
+            [slice(2, 3, None)],
+            [slice(2, 3, None)],
+            [],
+            [slice(2, 3, None)]
+        ])
+        #
+        tmp = notmasked_contiguous(a, 1)
+        assert_equal(tmp, [
+            [slice(0, 4, None)],
+            [],
+            [slice(0, 6, None), slice(7, 8, None)]
+        ])
+
+
+class TestCompressFunctions:
+
+    def test_compress_nd(self):
+        # Tests compress_nd
+        x = np.array(list(range(3*4*5))).reshape(3, 4, 5)
+        m = np.zeros((3,4,5)).astype(bool)
+        m[1,1,1] = True
+        x = array(x, mask=m)
+
+        # axis=None
+        a = compress_nd(x)
+        assert_equal(a, [[[ 0,  2,  3,  4],
+                          [10, 12, 13, 14],
+                          [15, 17, 18, 19]],
+                         [[40, 42, 43, 44],
+                          [50, 52, 53, 54],
+                          [55, 57, 58, 59]]])
+
+        # axis=0
+        a = compress_nd(x, 0)
+        assert_equal(a, [[[ 0,  1,  2,  3,  4],
+                          [ 5,  6,  7,  8,  9],
+                          [10, 11, 12, 13, 14],
+                          [15, 16, 17, 18, 19]],
+                         [[40, 41, 42, 43, 44],
+                          [45, 46, 47, 48, 49],
+                          [50, 51, 52, 53, 54],
+                          [55, 56, 57, 58, 59]]])
+
+        # axis=1
+        a = compress_nd(x, 1)
+        assert_equal(a, [[[ 0,  1,  2,  3,  4],
+                          [10, 11, 12, 13, 14],
+                          [15, 16, 17, 18, 19]],
+                         [[20, 21, 22, 23, 24],
+                          [30, 31, 32, 33, 34],
+                          [35, 36, 37, 38, 39]],
+                         [[40, 41, 42, 43, 44],
+                          [50, 51, 52, 53, 54],
+                          [55, 56, 57, 58, 59]]])
+
+        a2 = compress_nd(x, (1,))
+        a3 = compress_nd(x, -2)
+        a4 = compress_nd(x, (-2,))
+        assert_equal(a, a2)
+        assert_equal(a, a3)
+        assert_equal(a, a4)
+
+        # axis=2
+        a = compress_nd(x, 2)
+        assert_equal(a, [[[ 0, 2,  3,  4],
+                          [ 5, 7,  8,  9],
+                          [10, 12, 13, 14],
+                          [15, 17, 18, 19]],
+                         [[20, 22, 23, 24],
+                          [25, 27, 28, 29],
+                          [30, 32, 33, 34],
+                          [35, 37, 38, 39]],
+                         [[40, 42, 43, 44],
+                          [45, 47, 48, 49],
+                          [50, 52, 53, 54],
+                          [55, 57, 58, 59]]])
+
+        a2 = compress_nd(x, (2,))
+        a3 = compress_nd(x, -1)
+        a4 = compress_nd(x, (-1,))
+        assert_equal(a, a2)
+        assert_equal(a, a3)
+        assert_equal(a, a4)
+
+        # axis=(0, 1)
+        a = compress_nd(x, (0, 1))
+        assert_equal(a, [[[ 0,  1,  2,  3,  4],
+                          [10, 11, 12, 13, 14],
+                          [15, 16, 17, 18, 19]],
+                         [[40, 41, 42, 43, 44],
+                          [50, 51, 52, 53, 54],
+                          [55, 56, 57, 58, 59]]])
+        a2 = compress_nd(x, (0, -2))
+        assert_equal(a, a2)
+
+        # axis=(1, 2)
+        a = compress_nd(x, (1, 2))
+        assert_equal(a, [[[ 0,  2,  3,  4],
+                          [10, 12, 13, 14],
+                          [15, 17, 18, 19]],
+                         [[20, 22, 23, 24],
+                          [30, 32, 33, 34],
+                          [35, 37, 38, 39]],
+                         [[40, 42, 43, 44],
+                          [50, 52, 53, 54],
+                          [55, 57, 58, 59]]])
+
+        a2 = compress_nd(x, (-2, 2))
+        a3 = compress_nd(x, (1, -1))
+        a4 = compress_nd(x, (-2, -1))
+        assert_equal(a, a2)
+        assert_equal(a, a3)
+        assert_equal(a, a4)
+
+        # axis=(0, 2)
+        a = compress_nd(x, (0, 2))
+        assert_equal(a, [[[ 0,  2,  3,  4],
+                          [ 5,  7,  8,  9],
+                          [10, 12, 13, 14],
+                          [15, 17, 18, 19]],
+                         [[40, 42, 43, 44],
+                          [45, 47, 48, 49],
+                          [50, 52, 53, 54],
+                          [55, 57, 58, 59]]])
+
+        a2 = compress_nd(x, (0, -1))
+        assert_equal(a, a2)
+
+    def test_compress_rowcols(self):
+        # Tests compress_rowcols
+        x = array(np.arange(9).reshape(3, 3),
+                  mask=[[1, 0, 0], [0, 0, 0], [0, 0, 0]])
+        assert_equal(compress_rowcols(x), [[4, 5], [7, 8]])
+        assert_equal(compress_rowcols(x, 0), [[3, 4, 5], [6, 7, 8]])
+        assert_equal(compress_rowcols(x, 1), [[1, 2], [4, 5], [7, 8]])
+        x = array(x._data, mask=[[0, 0, 0], [0, 1, 0], [0, 0, 0]])
+        assert_equal(compress_rowcols(x), [[0, 2], [6, 8]])
+        assert_equal(compress_rowcols(x, 0), [[0, 1, 2], [6, 7, 8]])
+        assert_equal(compress_rowcols(x, 1), [[0, 2], [3, 5], [6, 8]])
+        x = array(x._data, mask=[[1, 0, 0], [0, 1, 0], [0, 0, 0]])
+        assert_equal(compress_rowcols(x), [[8]])
+        assert_equal(compress_rowcols(x, 0), [[6, 7, 8]])
+        assert_equal(compress_rowcols(x, 1,), [[2], [5], [8]])
+        x = array(x._data, mask=[[1, 0, 0], [0, 1, 0], [0, 0, 1]])
+        assert_equal(compress_rowcols(x).size, 0)
+        assert_equal(compress_rowcols(x, 0).size, 0)
+        assert_equal(compress_rowcols(x, 1).size, 0)
+
+    def test_mask_rowcols(self):
+        # Tests mask_rowcols.
+        x = array(np.arange(9).reshape(3, 3),
+                  mask=[[1, 0, 0], [0, 0, 0], [0, 0, 0]])
+        assert_equal(mask_rowcols(x).mask,
+                     [[1, 1, 1], [1, 0, 0], [1, 0, 0]])
+        assert_equal(mask_rowcols(x, 0).mask,
+                     [[1, 1, 1], [0, 0, 0], [0, 0, 0]])
+        assert_equal(mask_rowcols(x, 1).mask,
+                     [[1, 0, 0], [1, 0, 0], [1, 0, 0]])
+        x = array(x._data, mask=[[0, 0, 0], [0, 1, 0], [0, 0, 0]])
+        assert_equal(mask_rowcols(x).mask,
+                     [[0, 1, 0], [1, 1, 1], [0, 1, 0]])
+        assert_equal(mask_rowcols(x, 0).mask,
+                     [[0, 0, 0], [1, 1, 1], [0, 0, 0]])
+        assert_equal(mask_rowcols(x, 1).mask,
+                     [[0, 1, 0], [0, 1, 0], [0, 1, 0]])
+        x = array(x._data, mask=[[1, 0, 0], [0, 1, 0], [0, 0, 0]])
+        assert_equal(mask_rowcols(x).mask,
+                     [[1, 1, 1], [1, 1, 1], [1, 1, 0]])
+        assert_equal(mask_rowcols(x, 0).mask,
+                     [[1, 1, 1], [1, 1, 1], [0, 0, 0]])
+        assert_equal(mask_rowcols(x, 1,).mask,
+                     [[1, 1, 0], [1, 1, 0], [1, 1, 0]])
+        x = array(x._data, mask=[[1, 0, 0], [0, 1, 0], [0, 0, 1]])
+        assert_(mask_rowcols(x).all() is masked)
+        assert_(mask_rowcols(x, 0).all() is masked)
+        assert_(mask_rowcols(x, 1).all() is masked)
+        assert_(mask_rowcols(x).mask.all())
+        assert_(mask_rowcols(x, 0).mask.all())
+        assert_(mask_rowcols(x, 1).mask.all())
+
+    @pytest.mark.parametrize("axis", [None, 0, 1])
+    @pytest.mark.parametrize(["func", "rowcols_axis"],
+                             [(np.ma.mask_rows, 0), (np.ma.mask_cols, 1)])
+    def test_mask_row_cols_axis_deprecation(self, axis, func, rowcols_axis):
+        # Test deprecation of the axis argument to `mask_rows` and `mask_cols`
+        x = array(np.arange(9).reshape(3, 3),
+                  mask=[[1, 0, 0], [0, 0, 0], [0, 0, 0]])
+
+        with assert_warns(DeprecationWarning):
+            res = func(x, axis=axis)
+            assert_equal(res, mask_rowcols(x, rowcols_axis))
+
+    def test_dot(self):
+        # Tests dot product
+        n = np.arange(1, 7)
+        #
+        m = [1, 0, 0, 0, 0, 0]
+        a = masked_array(n, mask=m).reshape(2, 3)
+        b = masked_array(n, mask=m).reshape(3, 2)
+        c = dot(a, b, strict=True)
+        assert_equal(c.mask, [[1, 1], [1, 0]])
+        c = dot(b, a, strict=True)
+        assert_equal(c.mask, [[1, 1, 1], [1, 0, 0], [1, 0, 0]])
+        c = dot(a, b, strict=False)
+        assert_equal(c, np.dot(a.filled(0), b.filled(0)))
+        c = dot(b, a, strict=False)
+        assert_equal(c, np.dot(b.filled(0), a.filled(0)))
+        #
+        m = [0, 0, 0, 0, 0, 1]
+        a = masked_array(n, mask=m).reshape(2, 3)
+        b = masked_array(n, mask=m).reshape(3, 2)
+        c = dot(a, b, strict=True)
+        assert_equal(c.mask, [[0, 1], [1, 1]])
+        c = dot(b, a, strict=True)
+        assert_equal(c.mask, [[0, 0, 1], [0, 0, 1], [1, 1, 1]])
+        c = dot(a, b, strict=False)
+        assert_equal(c, np.dot(a.filled(0), b.filled(0)))
+        assert_equal(c, dot(a, b))
+        c = dot(b, a, strict=False)
+        assert_equal(c, np.dot(b.filled(0), a.filled(0)))
+        #
+        m = [0, 0, 0, 0, 0, 0]
+        a = masked_array(n, mask=m).reshape(2, 3)
+        b = masked_array(n, mask=m).reshape(3, 2)
+        c = dot(a, b)
+        assert_equal(c.mask, nomask)
+        c = dot(b, a)
+        assert_equal(c.mask, nomask)
+        #
+        a = masked_array(n, mask=[1, 0, 0, 0, 0, 0]).reshape(2, 3)
+        b = masked_array(n, mask=[0, 0, 0, 0, 0, 0]).reshape(3, 2)
+        c = dot(a, b, strict=True)
+        assert_equal(c.mask, [[1, 1], [0, 0]])
+        c = dot(a, b, strict=False)
+        assert_equal(c, np.dot(a.filled(0), b.filled(0)))
+        c = dot(b, a, strict=True)
+        assert_equal(c.mask, [[1, 0, 0], [1, 0, 0], [1, 0, 0]])
+        c = dot(b, a, strict=False)
+        assert_equal(c, np.dot(b.filled(0), a.filled(0)))
+        #
+        a = masked_array(n, mask=[0, 0, 0, 0, 0, 1]).reshape(2, 3)
+        b = masked_array(n, mask=[0, 0, 0, 0, 0, 0]).reshape(3, 2)
+        c = dot(a, b, strict=True)
+        assert_equal(c.mask, [[0, 0], [1, 1]])
+        c = dot(a, b)
+        assert_equal(c, np.dot(a.filled(0), b.filled(0)))
+        c = dot(b, a, strict=True)
+        assert_equal(c.mask, [[0, 0, 1], [0, 0, 1], [0, 0, 1]])
+        c = dot(b, a, strict=False)
+        assert_equal(c, np.dot(b.filled(0), a.filled(0)))
+        #
+        a = masked_array(n, mask=[0, 0, 0, 0, 0, 1]).reshape(2, 3)
+        b = masked_array(n, mask=[0, 0, 1, 0, 0, 0]).reshape(3, 2)
+        c = dot(a, b, strict=True)
+        assert_equal(c.mask, [[1, 0], [1, 1]])
+        c = dot(a, b, strict=False)
+        assert_equal(c, np.dot(a.filled(0), b.filled(0)))
+        c = dot(b, a, strict=True)
+        assert_equal(c.mask, [[0, 0, 1], [1, 1, 1], [0, 0, 1]])
+        c = dot(b, a, strict=False)
+        assert_equal(c, np.dot(b.filled(0), a.filled(0)))
+        #
+        a = masked_array(np.arange(8).reshape(2, 2, 2),
+                         mask=[[[1, 0], [0, 0]], [[0, 0], [0, 0]]])
+        b = masked_array(np.arange(8).reshape(2, 2, 2),
+                         mask=[[[0, 0], [0, 0]], [[0, 0], [0, 1]]])
+        c = dot(a, b, strict=True)
+        assert_equal(c.mask,
+                     [[[[1, 1], [1, 1]], [[0, 0], [0, 1]]],
+                      [[[0, 0], [0, 1]], [[0, 0], [0, 1]]]])
+        c = dot(a, b, strict=False)
+        assert_equal(c.mask,
+                     [[[[0, 0], [0, 1]], [[0, 0], [0, 0]]],
+                      [[[0, 0], [0, 0]], [[0, 0], [0, 0]]]])
+        c = dot(b, a, strict=True)
+        assert_equal(c.mask,
+                     [[[[1, 0], [0, 0]], [[1, 0], [0, 0]]],
+                      [[[1, 0], [0, 0]], [[1, 1], [1, 1]]]])
+        c = dot(b, a, strict=False)
+        assert_equal(c.mask,
+                     [[[[0, 0], [0, 0]], [[0, 0], [0, 0]]],
+                      [[[0, 0], [0, 0]], [[1, 0], [0, 0]]]])
+        #
+        a = masked_array(np.arange(8).reshape(2, 2, 2),
+                         mask=[[[1, 0], [0, 0]], [[0, 0], [0, 0]]])
+        b = 5.
+        c = dot(a, b, strict=True)
+        assert_equal(c.mask, [[[1, 0], [0, 0]], [[0, 0], [0, 0]]])
+        c = dot(a, b, strict=False)
+        assert_equal(c.mask, [[[1, 0], [0, 0]], [[0, 0], [0, 0]]])
+        c = dot(b, a, strict=True)
+        assert_equal(c.mask, [[[1, 0], [0, 0]], [[0, 0], [0, 0]]])
+        c = dot(b, a, strict=False)
+        assert_equal(c.mask, [[[1, 0], [0, 0]], [[0, 0], [0, 0]]])
+        #
+        a = masked_array(np.arange(8).reshape(2, 2, 2),
+                         mask=[[[1, 0], [0, 0]], [[0, 0], [0, 0]]])
+        b = masked_array(np.arange(2), mask=[0, 1])
+        c = dot(a, b, strict=True)
+        assert_equal(c.mask, [[1, 1], [1, 1]])
+        c = dot(a, b, strict=False)
+        assert_equal(c.mask, [[1, 0], [0, 0]])
+
+    def test_dot_returns_maskedarray(self):
+        # See gh-6611
+        a = np.eye(3)
+        b = array(a)
+        assert_(type(dot(a, a)) is MaskedArray)
+        assert_(type(dot(a, b)) is MaskedArray)
+        assert_(type(dot(b, a)) is MaskedArray)
+        assert_(type(dot(b, b)) is MaskedArray)
+
+    def test_dot_out(self):
+        a = array(np.eye(3))
+        out = array(np.zeros((3, 3)))
+        res = dot(a, a, out=out)
+        assert_(res is out)
+        assert_equal(a, res)
+
+
+class TestApplyAlongAxis:
+    # Tests 2D functions
+    def test_3d(self):
+        a = arange(12.).reshape(2, 2, 3)
+
+        def myfunc(b):
+            return b[1]
+
+        xa = apply_along_axis(myfunc, 2, a)
+        assert_equal(xa, [[1, 4], [7, 10]])
+
+    # Tests kwargs functions
+    def test_3d_kwargs(self):
+        a = arange(12).reshape(2, 2, 3)
+
+        def myfunc(b, offset=0):
+            return b[1+offset]
+
+        xa = apply_along_axis(myfunc, 2, a, offset=1)
+        assert_equal(xa, [[2, 5], [8, 11]])
+
+
+class TestApplyOverAxes:
+    # Tests apply_over_axes
+    def test_basic(self):
+        a = arange(24).reshape(2, 3, 4)
+        test = apply_over_axes(np.sum, a, [0, 2])
+        ctrl = np.array([[[60], [92], [124]]])
+        assert_equal(test, ctrl)
+        a[(a % 2).astype(bool)] = masked
+        test = apply_over_axes(np.sum, a, [0, 2])
+        ctrl = np.array([[[28], [44], [60]]])
+        assert_equal(test, ctrl)
+
+
+class TestMedian:
+    def test_pytype(self):
+        r = np.ma.median([[np.inf, np.inf], [np.inf, np.inf]], axis=-1)
+        assert_equal(r, np.inf)
+
+    def test_inf(self):
+        # test that even which computes handles inf / x = masked
+        r = np.ma.median(np.ma.masked_array([[np.inf, np.inf],
+                                             [np.inf, np.inf]]), axis=-1)
+        assert_equal(r, np.inf)
+        r = np.ma.median(np.ma.masked_array([[np.inf, np.inf],
+                                             [np.inf, np.inf]]), axis=None)
+        assert_equal(r, np.inf)
+        # all masked
+        r = np.ma.median(np.ma.masked_array([[np.inf, np.inf],
+                                             [np.inf, np.inf]], mask=True),
+                         axis=-1)
+        assert_equal(r.mask, True)
+        r = np.ma.median(np.ma.masked_array([[np.inf, np.inf],
+                                             [np.inf, np.inf]], mask=True),
+                         axis=None)
+        assert_equal(r.mask, True)
+
+    def test_non_masked(self):
+        x = np.arange(9)
+        assert_equal(np.ma.median(x), 4.)
+        assert_(type(np.ma.median(x)) is not MaskedArray)
+        x = range(8)
+        assert_equal(np.ma.median(x), 3.5)
+        assert_(type(np.ma.median(x)) is not MaskedArray)
+        x = 5
+        assert_equal(np.ma.median(x), 5.)
+        assert_(type(np.ma.median(x)) is not MaskedArray)
+        # integer
+        x = np.arange(9 * 8).reshape(9, 8)
+        assert_equal(np.ma.median(x, axis=0), np.median(x, axis=0))
+        assert_equal(np.ma.median(x, axis=1), np.median(x, axis=1))
+        assert_(np.ma.median(x, axis=1) is not MaskedArray)
+        # float
+        x = np.arange(9 * 8.).reshape(9, 8)
+        assert_equal(np.ma.median(x, axis=0), np.median(x, axis=0))
+        assert_equal(np.ma.median(x, axis=1), np.median(x, axis=1))
+        assert_(np.ma.median(x, axis=1) is not MaskedArray)
+
+    def test_docstring_examples(self):
+        "test the examples given in the docstring of ma.median"
+        x = array(np.arange(8), mask=[0]*4 + [1]*4)
+        assert_equal(np.ma.median(x), 1.5)
+        assert_equal(np.ma.median(x).shape, (), "shape mismatch")
+        assert_(type(np.ma.median(x)) is not MaskedArray)
+        x = array(np.arange(10).reshape(2, 5), mask=[0]*6 + [1]*4)
+        assert_equal(np.ma.median(x), 2.5)
+        assert_equal(np.ma.median(x).shape, (), "shape mismatch")
+        assert_(type(np.ma.median(x)) is not MaskedArray)
+        ma_x = np.ma.median(x, axis=-1, overwrite_input=True)
+        assert_equal(ma_x, [2., 5.])
+        assert_equal(ma_x.shape, (2,), "shape mismatch")
+        assert_(type(ma_x) is MaskedArray)
+
+    def test_axis_argument_errors(self):
+        msg = "mask = %s, ndim = %s, axis = %s, overwrite_input = %s"
+        for ndmin in range(5):
+            for mask in [False, True]:
+                x = array(1, ndmin=ndmin, mask=mask)
+
+                # Valid axis values should not raise exception
+                args = itertools.product(range(-ndmin, ndmin), [False, True])
+                for axis, over in args:
+                    try:
+                        np.ma.median(x, axis=axis, overwrite_input=over)
+                    except Exception:
+                        raise AssertionError(msg % (mask, ndmin, axis, over))
+
+                # Invalid axis values should raise exception
+                args = itertools.product([-(ndmin + 1), ndmin], [False, True])
+                for axis, over in args:
+                    try:
+                        np.ma.median(x, axis=axis, overwrite_input=over)
+                    except np.AxisError:
+                        pass
+                    else:
+                        raise AssertionError(msg % (mask, ndmin, axis, over))
+
+    def test_masked_0d(self):
+        # Check values
+        x = array(1, mask=False)
+        assert_equal(np.ma.median(x), 1)
+        x = array(1, mask=True)
+        assert_equal(np.ma.median(x), np.ma.masked)
+
+    def test_masked_1d(self):
+        x = array(np.arange(5), mask=True)
+        assert_equal(np.ma.median(x), np.ma.masked)
+        assert_equal(np.ma.median(x).shape, (), "shape mismatch")
+        assert_(type(np.ma.median(x)) is np.ma.core.MaskedConstant)
+        x = array(np.arange(5), mask=False)
+        assert_equal(np.ma.median(x), 2.)
+        assert_equal(np.ma.median(x).shape, (), "shape mismatch")
+        assert_(type(np.ma.median(x)) is not MaskedArray)
+        x = array(np.arange(5), mask=[0,1,0,0,0])
+        assert_equal(np.ma.median(x), 2.5)
+        assert_equal(np.ma.median(x).shape, (), "shape mismatch")
+        assert_(type(np.ma.median(x)) is not MaskedArray)
+        x = array(np.arange(5), mask=[0,1,1,1,1])
+        assert_equal(np.ma.median(x), 0.)
+        assert_equal(np.ma.median(x).shape, (), "shape mismatch")
+        assert_(type(np.ma.median(x)) is not MaskedArray)
+        # integer
+        x = array(np.arange(5), mask=[0,1,1,0,0])
+        assert_equal(np.ma.median(x), 3.)
+        assert_equal(np.ma.median(x).shape, (), "shape mismatch")
+        assert_(type(np.ma.median(x)) is not MaskedArray)
+        # float
+        x = array(np.arange(5.), mask=[0,1,1,0,0])
+        assert_equal(np.ma.median(x), 3.)
+        assert_equal(np.ma.median(x).shape, (), "shape mismatch")
+        assert_(type(np.ma.median(x)) is not MaskedArray)
+        # integer
+        x = array(np.arange(6), mask=[0,1,1,1,1,0])
+        assert_equal(np.ma.median(x), 2.5)
+        assert_equal(np.ma.median(x).shape, (), "shape mismatch")
+        assert_(type(np.ma.median(x)) is not MaskedArray)
+        # float
+        x = array(np.arange(6.), mask=[0,1,1,1,1,0])
+        assert_equal(np.ma.median(x), 2.5)
+        assert_equal(np.ma.median(x).shape, (), "shape mismatch")
+        assert_(type(np.ma.median(x)) is not MaskedArray)
+
+    def test_1d_shape_consistency(self):
+        assert_equal(np.ma.median(array([1,2,3],mask=[0,0,0])).shape,
+                     np.ma.median(array([1,2,3],mask=[0,1,0])).shape )
+
+    def test_2d(self):
+        # Tests median w/ 2D
+        (n, p) = (101, 30)
+        x = masked_array(np.linspace(-1., 1., n),)
+        x[:10] = x[-10:] = masked
+        z = masked_array(np.empty((n, p), dtype=float))
+        z[:, 0] = x[:]
+        idx = np.arange(len(x))
+        for i in range(1, p):
+            np.random.shuffle(idx)
+            z[:, i] = x[idx]
+        assert_equal(median(z[:, 0]), 0)
+        assert_equal(median(z), 0)
+        assert_equal(median(z, axis=0), np.zeros(p))
+        assert_equal(median(z.T, axis=1), np.zeros(p))
+
+    def test_2d_waxis(self):
+        # Tests median w/ 2D arrays and different axis.
+        x = masked_array(np.arange(30).reshape(10, 3))
+        x[:3] = x[-3:] = masked
+        assert_equal(median(x), 14.5)
+        assert_(type(np.ma.median(x)) is not MaskedArray)
+        assert_equal(median(x, axis=0), [13.5, 14.5, 15.5])
+        assert_(type(np.ma.median(x, axis=0)) is MaskedArray)
+        assert_equal(median(x, axis=1), [0, 0, 0, 10, 13, 16, 19, 0, 0, 0])
+        assert_(type(np.ma.median(x, axis=1)) is MaskedArray)
+        assert_equal(median(x, axis=1).mask, [1, 1, 1, 0, 0, 0, 0, 1, 1, 1])
+
+    def test_3d(self):
+        # Tests median w/ 3D
+        x = np.ma.arange(24).reshape(3, 4, 2)
+        x[x % 3 == 0] = masked
+        assert_equal(median(x, 0), [[12, 9], [6, 15], [12, 9], [18, 15]])
+        x.shape = (4, 3, 2)
+        assert_equal(median(x, 0), [[99, 10], [11, 99], [13, 14]])
+        x = np.ma.arange(24).reshape(4, 3, 2)
+        x[x % 5 == 0] = masked
+        assert_equal(median(x, 0), [[12, 10], [8, 9], [16, 17]])
+
+    def test_neg_axis(self):
+        x = masked_array(np.arange(30).reshape(10, 3))
+        x[:3] = x[-3:] = masked
+        assert_equal(median(x, axis=-1), median(x, axis=1))
+
+    def test_out_1d(self):
+        # integer float even odd
+        for v in (30, 30., 31, 31.):
+            x = masked_array(np.arange(v))
+            x[:3] = x[-3:] = masked
+            out = masked_array(np.ones(()))
+            r = median(x, out=out)
+            if v == 30:
+                assert_equal(out, 14.5)
+            else:
+                assert_equal(out, 15.)
+            assert_(r is out)
+            assert_(type(r) is MaskedArray)
+
+    def test_out(self):
+        # integer float even odd
+        for v in (40, 40., 30, 30.):
+            x = masked_array(np.arange(v).reshape(10, -1))
+            x[:3] = x[-3:] = masked
+            out = masked_array(np.ones(10))
+            r = median(x, axis=1, out=out)
+            if v == 30:
+                e = masked_array([0.]*3 + [10, 13, 16, 19] + [0.]*3,
+                                 mask=[True] * 3 + [False] * 4 + [True] * 3)
+            else:
+                e = masked_array([0.]*3 + [13.5, 17.5, 21.5, 25.5] + [0.]*3,
+                                 mask=[True]*3 + [False]*4 + [True]*3)
+            assert_equal(r, e)
+            assert_(r is out)
+            assert_(type(r) is MaskedArray)
+
+    @pytest.mark.parametrize(
+        argnames='axis',
+        argvalues=[
+            None,
+            1,
+            (1, ),
+            (0, 1),
+            (-3, -1),
+        ]
+    )
+    def test_keepdims_out(self, axis):
+        mask = np.zeros((3, 5, 7, 11), dtype=bool)
+        # Randomly set some elements to True:
+        w = np.random.random((4, 200)) * np.array(mask.shape)[:, None]
+        w = w.astype(np.intp)
+        mask[tuple(w)] = np.nan
+        d = masked_array(np.ones(mask.shape), mask=mask)
+        if axis is None:
+            shape_out = (1,) * d.ndim
+        else:
+            axis_norm = normalize_axis_tuple(axis, d.ndim)
+            shape_out = tuple(
+                1 if i in axis_norm else d.shape[i] for i in range(d.ndim))
+        out = masked_array(np.empty(shape_out))
+        result = median(d, axis=axis, keepdims=True, out=out)
+        assert result is out
+        assert_equal(result.shape, shape_out)
+
+    def test_single_non_masked_value_on_axis(self):
+        data = [[1., 0.],
+                [0., 3.],
+                [0., 0.]]
+        masked_arr = np.ma.masked_equal(data, 0)
+        expected = [1., 3.]
+        assert_array_equal(np.ma.median(masked_arr, axis=0),
+                           expected)
+
+    def test_nan(self):
+        for mask in (False, np.zeros(6, dtype=bool)):
+            dm = np.ma.array([[1, np.nan, 3], [1, 2, 3]])
+            dm.mask = mask
+
+            # scalar result
+            r = np.ma.median(dm, axis=None)
+            assert_(np.isscalar(r))
+            assert_array_equal(r, np.nan)
+            r = np.ma.median(dm.ravel(), axis=0)
+            assert_(np.isscalar(r))
+            assert_array_equal(r, np.nan)
+
+            r = np.ma.median(dm, axis=0)
+            assert_equal(type(r), MaskedArray)
+            assert_array_equal(r, [1, np.nan, 3])
+            r = np.ma.median(dm, axis=1)
+            assert_equal(type(r), MaskedArray)
+            assert_array_equal(r, [np.nan, 2])
+            r = np.ma.median(dm, axis=-1)
+            assert_equal(type(r), MaskedArray)
+            assert_array_equal(r, [np.nan, 2])
+
+        dm = np.ma.array([[1, np.nan, 3], [1, 2, 3]])
+        dm[:, 2] = np.ma.masked
+        assert_array_equal(np.ma.median(dm, axis=None), np.nan)
+        assert_array_equal(np.ma.median(dm, axis=0), [1, np.nan, 3])
+        assert_array_equal(np.ma.median(dm, axis=1), [np.nan, 1.5])
+
+    def test_out_nan(self):
+        o = np.ma.masked_array(np.zeros((4,)))
+        d = np.ma.masked_array(np.ones((3, 4)))
+        d[2, 1] = np.nan
+        d[2, 2] = np.ma.masked
+        assert_equal(np.ma.median(d, 0, out=o), o)
+        o = np.ma.masked_array(np.zeros((3,)))
+        assert_equal(np.ma.median(d, 1, out=o), o)
+        o = np.ma.masked_array(np.zeros(()))
+        assert_equal(np.ma.median(d, out=o), o)
+
+    def test_nan_behavior(self):
+        a = np.ma.masked_array(np.arange(24, dtype=float))
+        a[::3] = np.ma.masked
+        a[2] = np.nan
+        assert_array_equal(np.ma.median(a), np.nan)
+        assert_array_equal(np.ma.median(a, axis=0), np.nan)
+
+        a = np.ma.masked_array(np.arange(24, dtype=float).reshape(2, 3, 4))
+        a.mask = np.arange(a.size) % 2 == 1
+        aorig = a.copy()
+        a[1, 2, 3] = np.nan
+        a[1, 1, 2] = np.nan
+
+        # no axis
+        assert_array_equal(np.ma.median(a), np.nan)
+        assert_(np.isscalar(np.ma.median(a)))
+
+        # axis0
+        b = np.ma.median(aorig, axis=0)
+        b[2, 3] = np.nan
+        b[1, 2] = np.nan
+        assert_equal(np.ma.median(a, 0), b)
+
+        # axis1
+        b = np.ma.median(aorig, axis=1)
+        b[1, 3] = np.nan
+        b[1, 2] = np.nan
+        assert_equal(np.ma.median(a, 1), b)
+
+        # axis02
+        b = np.ma.median(aorig, axis=(0, 2))
+        b[1] = np.nan
+        b[2] = np.nan
+        assert_equal(np.ma.median(a, (0, 2)), b)
+
+    def test_ambigous_fill(self):
+        # 255 is max value, used as filler for sort
+        a = np.array([[3, 3, 255], [3, 3, 255]], dtype=np.uint8)
+        a = np.ma.masked_array(a, mask=a == 3)
+        assert_array_equal(np.ma.median(a, axis=1), 255)
+        assert_array_equal(np.ma.median(a, axis=1).mask, False)
+        assert_array_equal(np.ma.median(a, axis=0), a[0])
+        assert_array_equal(np.ma.median(a), 255)
+
+    def test_special(self):
+        for inf in [np.inf, -np.inf]:
+            a = np.array([[inf,  np.nan], [np.nan, np.nan]])
+            a = np.ma.masked_array(a, mask=np.isnan(a))
+            assert_equal(np.ma.median(a, axis=0), [inf,  np.nan])
+            assert_equal(np.ma.median(a, axis=1), [inf,  np.nan])
+            assert_equal(np.ma.median(a), inf)
+
+            a = np.array([[np.nan, np.nan, inf], [np.nan, np.nan, inf]])
+            a = np.ma.masked_array(a, mask=np.isnan(a))
+            assert_array_equal(np.ma.median(a, axis=1), inf)
+            assert_array_equal(np.ma.median(a, axis=1).mask, False)
+            assert_array_equal(np.ma.median(a, axis=0), a[0])
+            assert_array_equal(np.ma.median(a), inf)
+
+            # no mask
+            a = np.array([[inf, inf], [inf, inf]])
+            assert_equal(np.ma.median(a), inf)
+            assert_equal(np.ma.median(a, axis=0), inf)
+            assert_equal(np.ma.median(a, axis=1), inf)
+
+            a = np.array([[inf, 7, -inf, -9],
+                          [-10, np.nan, np.nan, 5],
+                          [4, np.nan, np.nan, inf]],
+                          dtype=np.float32)
+            a = np.ma.masked_array(a, mask=np.isnan(a))
+            if inf > 0:
+                assert_equal(np.ma.median(a, axis=0), [4., 7., -inf, 5.])
+                assert_equal(np.ma.median(a), 4.5)
+            else:
+                assert_equal(np.ma.median(a, axis=0), [-10., 7., -inf, -9.])
+                assert_equal(np.ma.median(a), -2.5)
+            assert_equal(np.ma.median(a, axis=1), [-1., -2.5, inf])
+
+            for i in range(0, 10):
+                for j in range(1, 10):
+                    a = np.array([([np.nan] * i) + ([inf] * j)] * 2)
+                    a = np.ma.masked_array(a, mask=np.isnan(a))
+                    assert_equal(np.ma.median(a), inf)
+                    assert_equal(np.ma.median(a, axis=1), inf)
+                    assert_equal(np.ma.median(a, axis=0),
+                                 ([np.nan] * i) + [inf] * j)
+
+    def test_empty(self):
+        # empty arrays
+        a = np.ma.masked_array(np.array([], dtype=float))
+        with suppress_warnings() as w:
+            w.record(RuntimeWarning)
+            assert_array_equal(np.ma.median(a), np.nan)
+            assert_(w.log[0].category is RuntimeWarning)
+
+        # multiple dimensions
+        a = np.ma.masked_array(np.array([], dtype=float, ndmin=3))
+        # no axis
+        with suppress_warnings() as w:
+            w.record(RuntimeWarning)
+            warnings.filterwarnings('always', '', RuntimeWarning)
+            assert_array_equal(np.ma.median(a), np.nan)
+            assert_(w.log[0].category is RuntimeWarning)
+
+        # axis 0 and 1
+        b = np.ma.masked_array(np.array([], dtype=float, ndmin=2))
+        assert_equal(np.ma.median(a, axis=0), b)
+        assert_equal(np.ma.median(a, axis=1), b)
+
+        # axis 2
+        b = np.ma.masked_array(np.array(np.nan, dtype=float, ndmin=2))
+        with warnings.catch_warnings(record=True) as w:
+            warnings.filterwarnings('always', '', RuntimeWarning)
+            assert_equal(np.ma.median(a, axis=2), b)
+            assert_(w[0].category is RuntimeWarning)
+
+    def test_object(self):
+        o = np.ma.masked_array(np.arange(7.))
+        assert_(type(np.ma.median(o.astype(object))), float)
+        o[2] = np.nan
+        assert_(type(np.ma.median(o.astype(object))), float)
+
+
+class TestCov:
+
+    def setup_method(self):
+        self.data = array(np.random.rand(12))
+
+    def test_1d_without_missing(self):
+        # Test cov on 1D variable w/o missing values
+        x = self.data
+        assert_almost_equal(np.cov(x), cov(x))
+        assert_almost_equal(np.cov(x, rowvar=False), cov(x, rowvar=False))
+        assert_almost_equal(np.cov(x, rowvar=False, bias=True),
+                            cov(x, rowvar=False, bias=True))
+
+    def test_2d_without_missing(self):
+        # Test cov on 1 2D variable w/o missing values
+        x = self.data.reshape(3, 4)
+        assert_almost_equal(np.cov(x), cov(x))
+        assert_almost_equal(np.cov(x, rowvar=False), cov(x, rowvar=False))
+        assert_almost_equal(np.cov(x, rowvar=False, bias=True),
+                            cov(x, rowvar=False, bias=True))
+
+    def test_1d_with_missing(self):
+        # Test cov 1 1D variable w/missing values
+        x = self.data
+        x[-1] = masked
+        x -= x.mean()
+        nx = x.compressed()
+        assert_almost_equal(np.cov(nx), cov(x))
+        assert_almost_equal(np.cov(nx, rowvar=False), cov(x, rowvar=False))
+        assert_almost_equal(np.cov(nx, rowvar=False, bias=True),
+                            cov(x, rowvar=False, bias=True))
+        #
+        try:
+            cov(x, allow_masked=False)
+        except ValueError:
+            pass
+        #
+        # 2 1D variables w/ missing values
+        nx = x[1:-1]
+        assert_almost_equal(np.cov(nx, nx[::-1]), cov(x, x[::-1]))
+        assert_almost_equal(np.cov(nx, nx[::-1], rowvar=False),
+                            cov(x, x[::-1], rowvar=False))
+        assert_almost_equal(np.cov(nx, nx[::-1], rowvar=False, bias=True),
+                            cov(x, x[::-1], rowvar=False, bias=True))
+
+    def test_2d_with_missing(self):
+        # Test cov on 2D variable w/ missing value
+        x = self.data
+        x[-1] = masked
+        x = x.reshape(3, 4)
+        valid = np.logical_not(getmaskarray(x)).astype(int)
+        frac = np.dot(valid, valid.T)
+        xf = (x - x.mean(1)[:, None]).filled(0)
+        assert_almost_equal(cov(x),
+                            np.cov(xf) * (x.shape[1] - 1) / (frac - 1.))
+        assert_almost_equal(cov(x, bias=True),
+                            np.cov(xf, bias=True) * x.shape[1] / frac)
+        frac = np.dot(valid.T, valid)
+        xf = (x - x.mean(0)).filled(0)
+        assert_almost_equal(cov(x, rowvar=False),
+                            (np.cov(xf, rowvar=False) *
+                             (x.shape[0] - 1) / (frac - 1.)))
+        assert_almost_equal(cov(x, rowvar=False, bias=True),
+                            (np.cov(xf, rowvar=False, bias=True) *
+                             x.shape[0] / frac))
+
+
+class TestCorrcoef:
+
+    def setup_method(self):
+        self.data = array(np.random.rand(12))
+        self.data2 = array(np.random.rand(12))
+
+    def test_ddof(self):
+        # ddof raises DeprecationWarning
+        x, y = self.data, self.data2
+        expected = np.corrcoef(x)
+        expected2 = np.corrcoef(x, y)
+        with suppress_warnings() as sup:
+            warnings.simplefilter("always")
+            assert_warns(DeprecationWarning, corrcoef, x, ddof=-1)
+            sup.filter(DeprecationWarning, "bias and ddof have no effect")
+            # ddof has no or negligible effect on the function
+            assert_almost_equal(np.corrcoef(x, ddof=0), corrcoef(x, ddof=0))
+            assert_almost_equal(corrcoef(x, ddof=-1), expected)
+            assert_almost_equal(corrcoef(x, y, ddof=-1), expected2)
+            assert_almost_equal(corrcoef(x, ddof=3), expected)
+            assert_almost_equal(corrcoef(x, y, ddof=3), expected2)
+
+    def test_bias(self):
+        x, y = self.data, self.data2
+        expected = np.corrcoef(x)
+        # bias raises DeprecationWarning
+        with suppress_warnings() as sup:
+            warnings.simplefilter("always")
+            assert_warns(DeprecationWarning, corrcoef, x, y, True, False)
+            assert_warns(DeprecationWarning, corrcoef, x, y, True, True)
+            assert_warns(DeprecationWarning, corrcoef, x, bias=False)
+            sup.filter(DeprecationWarning, "bias and ddof have no effect")
+            # bias has no or negligible effect on the function
+            assert_almost_equal(corrcoef(x, bias=1), expected)
+
+    def test_1d_without_missing(self):
+        # Test cov on 1D variable w/o missing values
+        x = self.data
+        assert_almost_equal(np.corrcoef(x), corrcoef(x))
+        assert_almost_equal(np.corrcoef(x, rowvar=False),
+                            corrcoef(x, rowvar=False))
+        with suppress_warnings() as sup:
+            sup.filter(DeprecationWarning, "bias and ddof have no effect")
+            assert_almost_equal(np.corrcoef(x, rowvar=False, bias=True),
+                                corrcoef(x, rowvar=False, bias=True))
+
+    def test_2d_without_missing(self):
+        # Test corrcoef on 1 2D variable w/o missing values
+        x = self.data.reshape(3, 4)
+        assert_almost_equal(np.corrcoef(x), corrcoef(x))
+        assert_almost_equal(np.corrcoef(x, rowvar=False),
+                            corrcoef(x, rowvar=False))
+        with suppress_warnings() as sup:
+            sup.filter(DeprecationWarning, "bias and ddof have no effect")
+            assert_almost_equal(np.corrcoef(x, rowvar=False, bias=True),
+                                corrcoef(x, rowvar=False, bias=True))
+
+    def test_1d_with_missing(self):
+        # Test corrcoef 1 1D variable w/missing values
+        x = self.data
+        x[-1] = masked
+        x -= x.mean()
+        nx = x.compressed()
+        assert_almost_equal(np.corrcoef(nx), corrcoef(x))
+        assert_almost_equal(np.corrcoef(nx, rowvar=False),
+                            corrcoef(x, rowvar=False))
+        with suppress_warnings() as sup:
+            sup.filter(DeprecationWarning, "bias and ddof have no effect")
+            assert_almost_equal(np.corrcoef(nx, rowvar=False, bias=True),
+                                corrcoef(x, rowvar=False, bias=True))
+        try:
+            corrcoef(x, allow_masked=False)
+        except ValueError:
+            pass
+        # 2 1D variables w/ missing values
+        nx = x[1:-1]
+        assert_almost_equal(np.corrcoef(nx, nx[::-1]), corrcoef(x, x[::-1]))
+        assert_almost_equal(np.corrcoef(nx, nx[::-1], rowvar=False),
+                            corrcoef(x, x[::-1], rowvar=False))
+        with suppress_warnings() as sup:
+            sup.filter(DeprecationWarning, "bias and ddof have no effect")
+            # ddof and bias have no or negligible effect on the function
+            assert_almost_equal(np.corrcoef(nx, nx[::-1]),
+                                corrcoef(x, x[::-1], bias=1))
+            assert_almost_equal(np.corrcoef(nx, nx[::-1]),
+                                corrcoef(x, x[::-1], ddof=2))
+
+    def test_2d_with_missing(self):
+        # Test corrcoef on 2D variable w/ missing value
+        x = self.data
+        x[-1] = masked
+        x = x.reshape(3, 4)
+
+        test = corrcoef(x)
+        control = np.corrcoef(x)
+        assert_almost_equal(test[:-1, :-1], control[:-1, :-1])
+        with suppress_warnings() as sup:
+            sup.filter(DeprecationWarning, "bias and ddof have no effect")
+            # ddof and bias have no or negligible effect on the function
+            assert_almost_equal(corrcoef(x, ddof=-2)[:-1, :-1],
+                                control[:-1, :-1])
+            assert_almost_equal(corrcoef(x, ddof=3)[:-1, :-1],
+                                control[:-1, :-1])
+            assert_almost_equal(corrcoef(x, bias=1)[:-1, :-1],
+                                control[:-1, :-1])
+
+
+class TestPolynomial:
+    #
+    def test_polyfit(self):
+        # Tests polyfit
+        # On ndarrays
+        x = np.random.rand(10)
+        y = np.random.rand(20).reshape(-1, 2)
+        assert_almost_equal(polyfit(x, y, 3), np.polyfit(x, y, 3))
+        # ON 1D maskedarrays
+        x = x.view(MaskedArray)
+        x[0] = masked
+        y = y.view(MaskedArray)
+        y[0, 0] = y[-1, -1] = masked
+        #
+        (C, R, K, S, D) = polyfit(x, y[:, 0], 3, full=True)
+        (c, r, k, s, d) = np.polyfit(x[1:], y[1:, 0].compressed(), 3,
+                                     full=True)
+        for (a, a_) in zip((C, R, K, S, D), (c, r, k, s, d)):
+            assert_almost_equal(a, a_)
+        #
+        (C, R, K, S, D) = polyfit(x, y[:, -1], 3, full=True)
+        (c, r, k, s, d) = np.polyfit(x[1:-1], y[1:-1, -1], 3, full=True)
+        for (a, a_) in zip((C, R, K, S, D), (c, r, k, s, d)):
+            assert_almost_equal(a, a_)
+        #
+        (C, R, K, S, D) = polyfit(x, y, 3, full=True)
+        (c, r, k, s, d) = np.polyfit(x[1:-1], y[1:-1,:], 3, full=True)
+        for (a, a_) in zip((C, R, K, S, D), (c, r, k, s, d)):
+            assert_almost_equal(a, a_)
+        #
+        w = np.random.rand(10) + 1
+        wo = w.copy()
+        xs = x[1:-1]
+        ys = y[1:-1]
+        ws = w[1:-1]
+        (C, R, K, S, D) = polyfit(x, y, 3, full=True, w=w)
+        (c, r, k, s, d) = np.polyfit(xs, ys, 3, full=True, w=ws)
+        assert_equal(w, wo)
+        for (a, a_) in zip((C, R, K, S, D), (c, r, k, s, d)):
+            assert_almost_equal(a, a_)
+
+    def test_polyfit_with_masked_NaNs(self):
+        x = np.random.rand(10)
+        y = np.random.rand(20).reshape(-1, 2)
+
+        x[0] = np.nan
+        y[-1,-1] = np.nan
+        x = x.view(MaskedArray)
+        y = y.view(MaskedArray)
+        x[0] = masked
+        y[-1,-1] = masked
+
+        (C, R, K, S, D) = polyfit(x, y, 3, full=True)
+        (c, r, k, s, d) = np.polyfit(x[1:-1], y[1:-1,:], 3, full=True)
+        for (a, a_) in zip((C, R, K, S, D), (c, r, k, s, d)):
+            assert_almost_equal(a, a_)
+
+
+class TestArraySetOps:
+
+    def test_unique_onlist(self):
+        # Test unique on list
+        data = [1, 1, 1, 2, 2, 3]
+        test = unique(data, return_index=True, return_inverse=True)
+        assert_(isinstance(test[0], MaskedArray))
+        assert_equal(test[0], masked_array([1, 2, 3], mask=[0, 0, 0]))
+        assert_equal(test[1], [0, 3, 5])
+        assert_equal(test[2], [0, 0, 0, 1, 1, 2])
+
+    def test_unique_onmaskedarray(self):
+        # Test unique on masked data w/use_mask=True
+        data = masked_array([1, 1, 1, 2, 2, 3], mask=[0, 0, 1, 0, 1, 0])
+        test = unique(data, return_index=True, return_inverse=True)
+        assert_equal(test[0], masked_array([1, 2, 3, -1], mask=[0, 0, 0, 1]))
+        assert_equal(test[1], [0, 3, 5, 2])
+        assert_equal(test[2], [0, 0, 3, 1, 3, 2])
+        #
+        data.fill_value = 3
+        data = masked_array(data=[1, 1, 1, 2, 2, 3],
+                            mask=[0, 0, 1, 0, 1, 0], fill_value=3)
+        test = unique(data, return_index=True, return_inverse=True)
+        assert_equal(test[0], masked_array([1, 2, 3, -1], mask=[0, 0, 0, 1]))
+        assert_equal(test[1], [0, 3, 5, 2])
+        assert_equal(test[2], [0, 0, 3, 1, 3, 2])
+
+    def test_unique_allmasked(self):
+        # Test all masked
+        data = masked_array([1, 1, 1], mask=True)
+        test = unique(data, return_index=True, return_inverse=True)
+        assert_equal(test[0], masked_array([1, ], mask=[True]))
+        assert_equal(test[1], [0])
+        assert_equal(test[2], [0, 0, 0])
+        #
+        # Test masked
+        data = masked
+        test = unique(data, return_index=True, return_inverse=True)
+        assert_equal(test[0], masked_array(masked))
+        assert_equal(test[1], [0])
+        assert_equal(test[2], [0])
+
+    def test_ediff1d(self):
+        # Tests mediff1d
+        x = masked_array(np.arange(5), mask=[1, 0, 0, 0, 1])
+        control = array([1, 1, 1, 4], mask=[1, 0, 0, 1])
+        test = ediff1d(x)
+        assert_equal(test, control)
+        assert_equal(test.filled(0), control.filled(0))
+        assert_equal(test.mask, control.mask)
+
+    def test_ediff1d_tobegin(self):
+        # Test ediff1d w/ to_begin
+        x = masked_array(np.arange(5), mask=[1, 0, 0, 0, 1])
+        test = ediff1d(x, to_begin=masked)
+        control = array([0, 1, 1, 1, 4], mask=[1, 1, 0, 0, 1])
+        assert_equal(test, control)
+        assert_equal(test.filled(0), control.filled(0))
+        assert_equal(test.mask, control.mask)
+        #
+        test = ediff1d(x, to_begin=[1, 2, 3])
+        control = array([1, 2, 3, 1, 1, 1, 4], mask=[0, 0, 0, 1, 0, 0, 1])
+        assert_equal(test, control)
+        assert_equal(test.filled(0), control.filled(0))
+        assert_equal(test.mask, control.mask)
+
+    def test_ediff1d_toend(self):
+        # Test ediff1d w/ to_end
+        x = masked_array(np.arange(5), mask=[1, 0, 0, 0, 1])
+        test = ediff1d(x, to_end=masked)
+        control = array([1, 1, 1, 4, 0], mask=[1, 0, 0, 1, 1])
+        assert_equal(test, control)
+        assert_equal(test.filled(0), control.filled(0))
+        assert_equal(test.mask, control.mask)
+        #
+        test = ediff1d(x, to_end=[1, 2, 3])
+        control = array([1, 1, 1, 4, 1, 2, 3], mask=[1, 0, 0, 1, 0, 0, 0])
+        assert_equal(test, control)
+        assert_equal(test.filled(0), control.filled(0))
+        assert_equal(test.mask, control.mask)
+
+    def test_ediff1d_tobegin_toend(self):
+        # Test ediff1d w/ to_begin and to_end
+        x = masked_array(np.arange(5), mask=[1, 0, 0, 0, 1])
+        test = ediff1d(x, to_end=masked, to_begin=masked)
+        control = array([0, 1, 1, 1, 4, 0], mask=[1, 1, 0, 0, 1, 1])
+        assert_equal(test, control)
+        assert_equal(test.filled(0), control.filled(0))
+        assert_equal(test.mask, control.mask)
+        #
+        test = ediff1d(x, to_end=[1, 2, 3], to_begin=masked)
+        control = array([0, 1, 1, 1, 4, 1, 2, 3],
+                        mask=[1, 1, 0, 0, 1, 0, 0, 0])
+        assert_equal(test, control)
+        assert_equal(test.filled(0), control.filled(0))
+        assert_equal(test.mask, control.mask)
+
+    def test_ediff1d_ndarray(self):
+        # Test ediff1d w/ a ndarray
+        x = np.arange(5)
+        test = ediff1d(x)
+        control = array([1, 1, 1, 1], mask=[0, 0, 0, 0])
+        assert_equal(test, control)
+        assert_(isinstance(test, MaskedArray))
+        assert_equal(test.filled(0), control.filled(0))
+        assert_equal(test.mask, control.mask)
+        #
+        test = ediff1d(x, to_end=masked, to_begin=masked)
+        control = array([0, 1, 1, 1, 1, 0], mask=[1, 0, 0, 0, 0, 1])
+        assert_(isinstance(test, MaskedArray))
+        assert_equal(test.filled(0), control.filled(0))
+        assert_equal(test.mask, control.mask)
+
+    def test_intersect1d(self):
+        # Test intersect1d
+        x = array([1, 3, 3, 3], mask=[0, 0, 0, 1])
+        y = array([3, 1, 1, 1], mask=[0, 0, 0, 1])
+        test = intersect1d(x, y)
+        control = array([1, 3, -1], mask=[0, 0, 1])
+        assert_equal(test, control)
+
+    def test_setxor1d(self):
+        # Test setxor1d
+        a = array([1, 2, 5, 7, -1], mask=[0, 0, 0, 0, 1])
+        b = array([1, 2, 3, 4, 5, -1], mask=[0, 0, 0, 0, 0, 1])
+        test = setxor1d(a, b)
+        assert_equal(test, array([3, 4, 7]))
+        #
+        a = array([1, 2, 5, 7, -1], mask=[0, 0, 0, 0, 1])
+        b = [1, 2, 3, 4, 5]
+        test = setxor1d(a, b)
+        assert_equal(test, array([3, 4, 7, -1], mask=[0, 0, 0, 1]))
+        #
+        a = array([1, 2, 3])
+        b = array([6, 5, 4])
+        test = setxor1d(a, b)
+        assert_(isinstance(test, MaskedArray))
+        assert_equal(test, [1, 2, 3, 4, 5, 6])
+        #
+        a = array([1, 8, 2, 3], mask=[0, 1, 0, 0])
+        b = array([6, 5, 4, 8], mask=[0, 0, 0, 1])
+        test = setxor1d(a, b)
+        assert_(isinstance(test, MaskedArray))
+        assert_equal(test, [1, 2, 3, 4, 5, 6])
+        #
+        assert_array_equal([], setxor1d([], []))
+
+    def test_isin(self):
+        # the tests for in1d cover most of isin's behavior
+        # if in1d is removed, would need to change those tests to test
+        # isin instead.
+        a = np.arange(24).reshape([2, 3, 4])
+        mask = np.zeros([2, 3, 4])
+        mask[1, 2, 0] = 1
+        a = array(a, mask=mask)
+        b = array(data=[0, 10, 20, 30,  1,  3, 11, 22, 33],
+                  mask=[0,  1,  0,  1,  0,  1,  0,  1,  0])
+        ec = zeros((2, 3, 4), dtype=bool)
+        ec[0, 0, 0] = True
+        ec[0, 0, 1] = True
+        ec[0, 2, 3] = True
+        c = isin(a, b)
+        assert_(isinstance(c, MaskedArray))
+        assert_array_equal(c, ec)
+        #compare results of np.isin to ma.isin
+        d = np.isin(a, b[~b.mask]) & ~a.mask
+        assert_array_equal(c, d)
+
+    def test_in1d(self):
+        # Test in1d
+        a = array([1, 2, 5, 7, -1], mask=[0, 0, 0, 0, 1])
+        b = array([1, 2, 3, 4, 5, -1], mask=[0, 0, 0, 0, 0, 1])
+        test = in1d(a, b)
+        assert_equal(test, [True, True, True, False, True])
+        #
+        a = array([5, 5, 2, 1, -1], mask=[0, 0, 0, 0, 1])
+        b = array([1, 5, -1], mask=[0, 0, 1])
+        test = in1d(a, b)
+        assert_equal(test, [True, True, False, True, True])
+        #
+        assert_array_equal([], in1d([], []))
+
+    def test_in1d_invert(self):
+        # Test in1d's invert parameter
+        a = array([1, 2, 5, 7, -1], mask=[0, 0, 0, 0, 1])
+        b = array([1, 2, 3, 4, 5, -1], mask=[0, 0, 0, 0, 0, 1])
+        assert_equal(np.invert(in1d(a, b)), in1d(a, b, invert=True))
+
+        a = array([5, 5, 2, 1, -1], mask=[0, 0, 0, 0, 1])
+        b = array([1, 5, -1], mask=[0, 0, 1])
+        assert_equal(np.invert(in1d(a, b)), in1d(a, b, invert=True))
+
+        assert_array_equal([], in1d([], [], invert=True))
+
+    def test_union1d(self):
+        # Test union1d
+        a = array([1, 2, 5, 7, 5, -1], mask=[0, 0, 0, 0, 0, 1])
+        b = array([1, 2, 3, 4, 5, -1], mask=[0, 0, 0, 0, 0, 1])
+        test = union1d(a, b)
+        control = array([1, 2, 3, 4, 5, 7, -1], mask=[0, 0, 0, 0, 0, 0, 1])
+        assert_equal(test, control)
+
+        # Tests gh-10340, arguments to union1d should be
+        # flattened if they are not already 1D
+        x = array([[0, 1, 2], [3, 4, 5]], mask=[[0, 0, 0], [0, 0, 1]])
+        y = array([0, 1, 2, 3, 4], mask=[0, 0, 0, 0, 1])
+        ez = array([0, 1, 2, 3, 4, 5], mask=[0, 0, 0, 0, 0, 1])
+        z = union1d(x, y)
+        assert_equal(z, ez)
+        #
+        assert_array_equal([], union1d([], []))
+
+    def test_setdiff1d(self):
+        # Test setdiff1d
+        a = array([6, 5, 4, 7, 7, 1, 2, 1], mask=[0, 0, 0, 0, 0, 0, 0, 1])
+        b = array([2, 4, 3, 3, 2, 1, 5])
+        test = setdiff1d(a, b)
+        assert_equal(test, array([6, 7, -1], mask=[0, 0, 1]))
+        #
+        a = arange(10)
+        b = arange(8)
+        assert_equal(setdiff1d(a, b), array([8, 9]))
+        a = array([], np.uint32, mask=[])
+        assert_equal(setdiff1d(a, []).dtype, np.uint32)
+
+    def test_setdiff1d_char_array(self):
+        # Test setdiff1d_charray
+        a = np.array(['a', 'b', 'c'])
+        b = np.array(['a', 'b', 's'])
+        assert_array_equal(setdiff1d(a, b), np.array(['c']))
+
+
+class TestShapeBase:
+
+    def test_atleast_2d(self):
+        # Test atleast_2d
+        a = masked_array([0, 1, 2], mask=[0, 1, 0])
+        b = atleast_2d(a)
+        assert_equal(b.shape, (1, 3))
+        assert_equal(b.mask.shape, b.data.shape)
+        assert_equal(a.shape, (3,))
+        assert_equal(a.mask.shape, a.data.shape)
+        assert_equal(b.mask.shape, b.data.shape)
+
+    def test_shape_scalar(self):
+        # the atleast and diagflat function should work with scalars
+        # GitHub issue #3367
+        # Additionally, the atleast functions should accept multiple scalars
+        # correctly
+        b = atleast_1d(1.0)
+        assert_equal(b.shape, (1,))
+        assert_equal(b.mask.shape, b.shape)
+        assert_equal(b.data.shape, b.shape)
+
+        b = atleast_1d(1.0, 2.0)
+        for a in b:
+            assert_equal(a.shape, (1,))
+            assert_equal(a.mask.shape, a.shape)
+            assert_equal(a.data.shape, a.shape)
+
+        b = atleast_2d(1.0)
+        assert_equal(b.shape, (1, 1))
+        assert_equal(b.mask.shape, b.shape)
+        assert_equal(b.data.shape, b.shape)
+
+        b = atleast_2d(1.0, 2.0)
+        for a in b:
+            assert_equal(a.shape, (1, 1))
+            assert_equal(a.mask.shape, a.shape)
+            assert_equal(a.data.shape, a.shape)
+
+        b = atleast_3d(1.0)
+        assert_equal(b.shape, (1, 1, 1))
+        assert_equal(b.mask.shape, b.shape)
+        assert_equal(b.data.shape, b.shape)
+
+        b = atleast_3d(1.0, 2.0)
+        for a in b:
+            assert_equal(a.shape, (1, 1, 1))
+            assert_equal(a.mask.shape, a.shape)
+            assert_equal(a.data.shape, a.shape)
+
+        b = diagflat(1.0)
+        assert_equal(b.shape, (1, 1))
+        assert_equal(b.mask.shape, b.data.shape)
+
+
+class TestNDEnumerate:
+
+    def test_ndenumerate_nomasked(self):
+        ordinary = np.arange(6.).reshape((1, 3, 2))
+        empty_mask = np.zeros_like(ordinary, dtype=bool)
+        with_mask = masked_array(ordinary, mask=empty_mask)
+        assert_equal(list(np.ndenumerate(ordinary)),
+                     list(ndenumerate(ordinary)))
+        assert_equal(list(ndenumerate(ordinary)),
+                     list(ndenumerate(with_mask)))
+        assert_equal(list(ndenumerate(with_mask)),
+                     list(ndenumerate(with_mask, compressed=False)))
+
+    def test_ndenumerate_allmasked(self):
+        a = masked_all(())
+        b = masked_all((100,))
+        c = masked_all((2, 3, 4))
+        assert_equal(list(ndenumerate(a)), [])
+        assert_equal(list(ndenumerate(b)), [])
+        assert_equal(list(ndenumerate(b, compressed=False)),
+                     list(zip(np.ndindex((100,)), 100 * [masked])))
+        assert_equal(list(ndenumerate(c)), [])
+        assert_equal(list(ndenumerate(c, compressed=False)),
+                     list(zip(np.ndindex((2, 3, 4)), 2 * 3 * 4 * [masked])))
+
+    def test_ndenumerate_mixedmasked(self):
+        a = masked_array(np.arange(12).reshape((3, 4)),
+                         mask=[[1, 1, 1, 1],
+                               [1, 1, 0, 1],
+                               [0, 0, 0, 0]])
+        items = [((1, 2), 6),
+                 ((2, 0), 8), ((2, 1), 9), ((2, 2), 10), ((2, 3), 11)]
+        assert_equal(list(ndenumerate(a)), items)
+        assert_equal(len(list(ndenumerate(a, compressed=False))), a.size)
+        for coordinate, value in ndenumerate(a, compressed=False):
+            assert_equal(a[coordinate], value)
+
+
+class TestStack:
+
+    def test_stack_1d(self):
+        a = masked_array([0, 1, 2], mask=[0, 1, 0])
+        b = masked_array([9, 8, 7], mask=[1, 0, 0])
+
+        c = stack([a, b], axis=0)
+        assert_equal(c.shape, (2, 3))
+        assert_array_equal(a.mask, c[0].mask)
+        assert_array_equal(b.mask, c[1].mask)
+
+        d = vstack([a, b])
+        assert_array_equal(c.data, d.data)
+        assert_array_equal(c.mask, d.mask)
+
+        c = stack([a, b], axis=1)
+        assert_equal(c.shape, (3, 2))
+        assert_array_equal(a.mask, c[:, 0].mask)
+        assert_array_equal(b.mask, c[:, 1].mask)
+
+    def test_stack_masks(self):
+        a = masked_array([0, 1, 2], mask=True)
+        b = masked_array([9, 8, 7], mask=False)
+
+        c = stack([a, b], axis=0)
+        assert_equal(c.shape, (2, 3))
+        assert_array_equal(a.mask, c[0].mask)
+        assert_array_equal(b.mask, c[1].mask)
+
+        d = vstack([a, b])
+        assert_array_equal(c.data, d.data)
+        assert_array_equal(c.mask, d.mask)
+
+        c = stack([a, b], axis=1)
+        assert_equal(c.shape, (3, 2))
+        assert_array_equal(a.mask, c[:, 0].mask)
+        assert_array_equal(b.mask, c[:, 1].mask)
+
+    def test_stack_nd(self):
+        # 2D
+        shp = (3, 2)
+        d1 = np.random.randint(0, 10, shp)
+        d2 = np.random.randint(0, 10, shp)
+        m1 = np.random.randint(0, 2, shp).astype(bool)
+        m2 = np.random.randint(0, 2, shp).astype(bool)
+        a1 = masked_array(d1, mask=m1)
+        a2 = masked_array(d2, mask=m2)
+
+        c = stack([a1, a2], axis=0)
+        c_shp = (2,) + shp
+        assert_equal(c.shape, c_shp)
+        assert_array_equal(a1.mask, c[0].mask)
+        assert_array_equal(a2.mask, c[1].mask)
+
+        c = stack([a1, a2], axis=-1)
+        c_shp = shp + (2,)
+        assert_equal(c.shape, c_shp)
+        assert_array_equal(a1.mask, c[..., 0].mask)
+        assert_array_equal(a2.mask, c[..., 1].mask)
+
+        # 4D
+        shp = (3, 2, 4, 5,)
+        d1 = np.random.randint(0, 10, shp)
+        d2 = np.random.randint(0, 10, shp)
+        m1 = np.random.randint(0, 2, shp).astype(bool)
+        m2 = np.random.randint(0, 2, shp).astype(bool)
+        a1 = masked_array(d1, mask=m1)
+        a2 = masked_array(d2, mask=m2)
+
+        c = stack([a1, a2], axis=0)
+        c_shp = (2,) + shp
+        assert_equal(c.shape, c_shp)
+        assert_array_equal(a1.mask, c[0].mask)
+        assert_array_equal(a2.mask, c[1].mask)
+
+        c = stack([a1, a2], axis=-1)
+        c_shp = shp + (2,)
+        assert_equal(c.shape, c_shp)
+        assert_array_equal(a1.mask, c[..., 0].mask)
+        assert_array_equal(a2.mask, c[..., 1].mask)
diff --git a/venv/lib/python3.10/site-packages/numpy/ma/tests/test_mrecords.py b/venv/lib/python3.10/site-packages/numpy/ma/tests/test_mrecords.py
new file mode 100644
index 0000000000000000000000000000000000000000..77123c3cda941636354a7b282777f3f0e55d3ab0
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/numpy/ma/tests/test_mrecords.py
@@ -0,0 +1,493 @@
+# pylint: disable-msg=W0611, W0612, W0511,R0201
+"""Tests suite for mrecords.
+
+:author: Pierre Gerard-Marchant
+:contact: pierregm_at_uga_dot_edu
+
+"""
+import numpy as np
+import numpy.ma as ma
+from numpy import recarray
+from numpy.ma import masked, nomask
+from numpy.testing import temppath
+from numpy.core.records import (
+    fromrecords as recfromrecords, fromarrays as recfromarrays
+    )
+from numpy.ma.mrecords import (
+    MaskedRecords, mrecarray, fromarrays, fromtextfile, fromrecords,
+    addfield
+    )
+from numpy.ma.testutils import (
+    assert_, assert_equal,
+    assert_equal_records,
+    )
+from numpy.compat import pickle
+
+
+class TestMRecords:
+
+    ilist = [1, 2, 3, 4, 5]
+    flist = [1.1, 2.2, 3.3, 4.4, 5.5]
+    slist = [b'one', b'two', b'three', b'four', b'five']
+    ddtype = [('a', int), ('b', float), ('c', '|S8')]
+    mask = [0, 1, 0, 0, 1]
+    base = ma.array(list(zip(ilist, flist, slist)), mask=mask, dtype=ddtype)
+
+    def test_byview(self):
+        # Test creation by view
+        base = self.base
+        mbase = base.view(mrecarray)
+        assert_equal(mbase.recordmask, base.recordmask)
+        assert_equal_records(mbase._mask, base._mask)
+        assert_(isinstance(mbase._data, recarray))
+        assert_equal_records(mbase._data, base._data.view(recarray))
+        for field in ('a', 'b', 'c'):
+            assert_equal(base[field], mbase[field])
+        assert_equal_records(mbase.view(mrecarray), mbase)
+
+    def test_get(self):
+        # Tests fields retrieval
+        base = self.base.copy()
+        mbase = base.view(mrecarray)
+        # As fields..........
+        for field in ('a', 'b', 'c'):
+            assert_equal(getattr(mbase, field), mbase[field])
+            assert_equal(base[field], mbase[field])
+        # as elements .......
+        mbase_first = mbase[0]
+        assert_(isinstance(mbase_first, mrecarray))
+        assert_equal(mbase_first.dtype, mbase.dtype)
+        assert_equal(mbase_first.tolist(), (1, 1.1, b'one'))
+        # Used to be mask, now it's recordmask
+        assert_equal(mbase_first.recordmask, nomask)
+        assert_equal(mbase_first._mask.item(), (False, False, False))
+        assert_equal(mbase_first['a'], mbase['a'][0])
+        mbase_last = mbase[-1]
+        assert_(isinstance(mbase_last, mrecarray))
+        assert_equal(mbase_last.dtype, mbase.dtype)
+        assert_equal(mbase_last.tolist(), (None, None, None))
+        # Used to be mask, now it's recordmask
+        assert_equal(mbase_last.recordmask, True)
+        assert_equal(mbase_last._mask.item(), (True, True, True))
+        assert_equal(mbase_last['a'], mbase['a'][-1])
+        assert_((mbase_last['a'] is masked))
+        # as slice ..........
+        mbase_sl = mbase[:2]
+        assert_(isinstance(mbase_sl, mrecarray))
+        assert_equal(mbase_sl.dtype, mbase.dtype)
+        # Used to be mask, now it's recordmask
+        assert_equal(mbase_sl.recordmask, [0, 1])
+        assert_equal_records(mbase_sl.mask,
+                             np.array([(False, False, False),
+                                       (True, True, True)],
+                                      dtype=mbase._mask.dtype))
+        assert_equal_records(mbase_sl, base[:2].view(mrecarray))
+        for field in ('a', 'b', 'c'):
+            assert_equal(getattr(mbase_sl, field), base[:2][field])
+
+    def test_set_fields(self):
+        # Tests setting fields.
+        base = self.base.copy()
+        mbase = base.view(mrecarray)
+        mbase = mbase.copy()
+        mbase.fill_value = (999999, 1e20, 'N/A')
+        # Change the data, the mask should be conserved
+        mbase.a._data[:] = 5
+        assert_equal(mbase['a']._data, [5, 5, 5, 5, 5])
+        assert_equal(mbase['a']._mask, [0, 1, 0, 0, 1])
+        # Change the elements, and the mask will follow
+        mbase.a = 1
+        assert_equal(mbase['a']._data, [1]*5)
+        assert_equal(ma.getmaskarray(mbase['a']), [0]*5)
+        # Use to be _mask, now it's recordmask
+        assert_equal(mbase.recordmask, [False]*5)
+        assert_equal(mbase._mask.tolist(),
+                     np.array([(0, 0, 0),
+                               (0, 1, 1),
+                               (0, 0, 0),
+                               (0, 0, 0),
+                               (0, 1, 1)],
+                              dtype=bool))
+        # Set a field to mask ........................
+        mbase.c = masked
+        # Use to be mask, and now it's still mask !
+        assert_equal(mbase.c.mask, [1]*5)
+        assert_equal(mbase.c.recordmask, [1]*5)
+        assert_equal(ma.getmaskarray(mbase['c']), [1]*5)
+        assert_equal(ma.getdata(mbase['c']), [b'N/A']*5)
+        assert_equal(mbase._mask.tolist(),
+                     np.array([(0, 0, 1),
+                               (0, 1, 1),
+                               (0, 0, 1),
+                               (0, 0, 1),
+                               (0, 1, 1)],
+                              dtype=bool))
+        # Set fields by slices .......................
+        mbase = base.view(mrecarray).copy()
+        mbase.a[3:] = 5
+        assert_equal(mbase.a, [1, 2, 3, 5, 5])
+        assert_equal(mbase.a._mask, [0, 1, 0, 0, 0])
+        mbase.b[3:] = masked
+        assert_equal(mbase.b, base['b'])
+        assert_equal(mbase.b._mask, [0, 1, 0, 1, 1])
+        # Set fields globally..........................
+        ndtype = [('alpha', '|S1'), ('num', int)]
+        data = ma.array([('a', 1), ('b', 2), ('c', 3)], dtype=ndtype)
+        rdata = data.view(MaskedRecords)
+        val = ma.array([10, 20, 30], mask=[1, 0, 0])
+
+        rdata['num'] = val
+        assert_equal(rdata.num, val)
+        assert_equal(rdata.num.mask, [1, 0, 0])
+
+    def test_set_fields_mask(self):
+        # Tests setting the mask of a field.
+        base = self.base.copy()
+        # This one has already a mask....
+        mbase = base.view(mrecarray)
+        mbase['a'][-2] = masked
+        assert_equal(mbase.a, [1, 2, 3, 4, 5])
+        assert_equal(mbase.a._mask, [0, 1, 0, 1, 1])
+        # This one has not yet
+        mbase = fromarrays([np.arange(5), np.random.rand(5)],
+                           dtype=[('a', int), ('b', float)])
+        mbase['a'][-2] = masked
+        assert_equal(mbase.a, [0, 1, 2, 3, 4])
+        assert_equal(mbase.a._mask, [0, 0, 0, 1, 0])
+
+    def test_set_mask(self):
+        base = self.base.copy()
+        mbase = base.view(mrecarray)
+        # Set the mask to True .......................
+        mbase.mask = masked
+        assert_equal(ma.getmaskarray(mbase['b']), [1]*5)
+        assert_equal(mbase['a']._mask, mbase['b']._mask)
+        assert_equal(mbase['a']._mask, mbase['c']._mask)
+        assert_equal(mbase._mask.tolist(),
+                     np.array([(1, 1, 1)]*5, dtype=bool))
+        # Delete the mask ............................
+        mbase.mask = nomask
+        assert_equal(ma.getmaskarray(mbase['c']), [0]*5)
+        assert_equal(mbase._mask.tolist(),
+                     np.array([(0, 0, 0)]*5, dtype=bool))
+
+    def test_set_mask_fromarray(self):
+        base = self.base.copy()
+        mbase = base.view(mrecarray)
+        # Sets the mask w/ an array
+        mbase.mask = [1, 0, 0, 0, 1]
+        assert_equal(mbase.a.mask, [1, 0, 0, 0, 1])
+        assert_equal(mbase.b.mask, [1, 0, 0, 0, 1])
+        assert_equal(mbase.c.mask, [1, 0, 0, 0, 1])
+        # Yay, once more !
+        mbase.mask = [0, 0, 0, 0, 1]
+        assert_equal(mbase.a.mask, [0, 0, 0, 0, 1])
+        assert_equal(mbase.b.mask, [0, 0, 0, 0, 1])
+        assert_equal(mbase.c.mask, [0, 0, 0, 0, 1])
+
+    def test_set_mask_fromfields(self):
+        mbase = self.base.copy().view(mrecarray)
+
+        nmask = np.array(
+            [(0, 1, 0), (0, 1, 0), (1, 0, 1), (1, 0, 1), (0, 0, 0)],
+            dtype=[('a', bool), ('b', bool), ('c', bool)])
+        mbase.mask = nmask
+        assert_equal(mbase.a.mask, [0, 0, 1, 1, 0])
+        assert_equal(mbase.b.mask, [1, 1, 0, 0, 0])
+        assert_equal(mbase.c.mask, [0, 0, 1, 1, 0])
+        # Reinitialize and redo
+        mbase.mask = False
+        mbase.fieldmask = nmask
+        assert_equal(mbase.a.mask, [0, 0, 1, 1, 0])
+        assert_equal(mbase.b.mask, [1, 1, 0, 0, 0])
+        assert_equal(mbase.c.mask, [0, 0, 1, 1, 0])
+
+    def test_set_elements(self):
+        base = self.base.copy()
+        # Set an element to mask .....................
+        mbase = base.view(mrecarray).copy()
+        mbase[-2] = masked
+        assert_equal(
+            mbase._mask.tolist(),
+            np.array([(0, 0, 0), (1, 1, 1), (0, 0, 0), (1, 1, 1), (1, 1, 1)],
+                     dtype=bool))
+        # Used to be mask, now it's recordmask!
+        assert_equal(mbase.recordmask, [0, 1, 0, 1, 1])
+        # Set slices .................................
+        mbase = base.view(mrecarray).copy()
+        mbase[:2] = (5, 5, 5)
+        assert_equal(mbase.a._data, [5, 5, 3, 4, 5])
+        assert_equal(mbase.a._mask, [0, 0, 0, 0, 1])
+        assert_equal(mbase.b._data, [5., 5., 3.3, 4.4, 5.5])
+        assert_equal(mbase.b._mask, [0, 0, 0, 0, 1])
+        assert_equal(mbase.c._data,
+                     [b'5', b'5', b'three', b'four', b'five'])
+        assert_equal(mbase.b._mask, [0, 0, 0, 0, 1])
+
+        mbase = base.view(mrecarray).copy()
+        mbase[:2] = masked
+        assert_equal(mbase.a._data, [1, 2, 3, 4, 5])
+        assert_equal(mbase.a._mask, [1, 1, 0, 0, 1])
+        assert_equal(mbase.b._data, [1.1, 2.2, 3.3, 4.4, 5.5])
+        assert_equal(mbase.b._mask, [1, 1, 0, 0, 1])
+        assert_equal(mbase.c._data,
+                     [b'one', b'two', b'three', b'four', b'five'])
+        assert_equal(mbase.b._mask, [1, 1, 0, 0, 1])
+
+    def test_setslices_hardmask(self):
+        # Tests setting slices w/ hardmask.
+        base = self.base.copy()
+        mbase = base.view(mrecarray)
+        mbase.harden_mask()
+        try:
+            mbase[-2:] = (5, 5, 5)
+            assert_equal(mbase.a._data, [1, 2, 3, 5, 5])
+            assert_equal(mbase.b._data, [1.1, 2.2, 3.3, 5, 5.5])
+            assert_equal(mbase.c._data,
+                         [b'one', b'two', b'three', b'5', b'five'])
+            assert_equal(mbase.a._mask, [0, 1, 0, 0, 1])
+            assert_equal(mbase.b._mask, mbase.a._mask)
+            assert_equal(mbase.b._mask, mbase.c._mask)
+        except NotImplementedError:
+            # OK, not implemented yet...
+            pass
+        except AssertionError:
+            raise
+        else:
+            raise Exception("Flexible hard masks should be supported !")
+        # Not using a tuple should crash
+        try:
+            mbase[-2:] = 3
+        except (NotImplementedError, TypeError):
+            pass
+        else:
+            raise TypeError("Should have expected a readable buffer object!")
+
+    def test_hardmask(self):
+        # Test hardmask
+        base = self.base.copy()
+        mbase = base.view(mrecarray)
+        mbase.harden_mask()
+        assert_(mbase._hardmask)
+        mbase.mask = nomask
+        assert_equal_records(mbase._mask, base._mask)
+        mbase.soften_mask()
+        assert_(not mbase._hardmask)
+        mbase.mask = nomask
+        # So, the mask of a field is no longer set to nomask...
+        assert_equal_records(mbase._mask,
+                             ma.make_mask_none(base.shape, base.dtype))
+        assert_(ma.make_mask(mbase['b']._mask) is nomask)
+        assert_equal(mbase['a']._mask, mbase['b']._mask)
+
+    def test_pickling(self):
+        # Test pickling
+        base = self.base.copy()
+        mrec = base.view(mrecarray)
+        for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
+            _ = pickle.dumps(mrec, protocol=proto)
+            mrec_ = pickle.loads(_)
+            assert_equal(mrec_.dtype, mrec.dtype)
+            assert_equal_records(mrec_._data, mrec._data)
+            assert_equal(mrec_._mask, mrec._mask)
+            assert_equal_records(mrec_._mask, mrec._mask)
+
+    def test_filled(self):
+        # Test filling the array
+        _a = ma.array([1, 2, 3], mask=[0, 0, 1], dtype=int)
+        _b = ma.array([1.1, 2.2, 3.3], mask=[0, 0, 1], dtype=float)
+        _c = ma.array(['one', 'two', 'three'], mask=[0, 0, 1], dtype='|S8')
+        ddtype = [('a', int), ('b', float), ('c', '|S8')]
+        mrec = fromarrays([_a, _b, _c], dtype=ddtype,
+                          fill_value=(99999, 99999., 'N/A'))
+        mrecfilled = mrec.filled()
+        assert_equal(mrecfilled['a'], np.array((1, 2, 99999), dtype=int))
+        assert_equal(mrecfilled['b'], np.array((1.1, 2.2, 99999.),
+                                               dtype=float))
+        assert_equal(mrecfilled['c'], np.array(('one', 'two', 'N/A'),
+                                               dtype='|S8'))
+
+    def test_tolist(self):
+        # Test tolist.
+        _a = ma.array([1, 2, 3], mask=[0, 0, 1], dtype=int)
+        _b = ma.array([1.1, 2.2, 3.3], mask=[0, 0, 1], dtype=float)
+        _c = ma.array(['one', 'two', 'three'], mask=[1, 0, 0], dtype='|S8')
+        ddtype = [('a', int), ('b', float), ('c', '|S8')]
+        mrec = fromarrays([_a, _b, _c], dtype=ddtype,
+                          fill_value=(99999, 99999., 'N/A'))
+
+        assert_equal(mrec.tolist(),
+                     [(1, 1.1, None), (2, 2.2, b'two'),
+                      (None, None, b'three')])
+
+    def test_withnames(self):
+        # Test the creation w/ format and names
+        x = mrecarray(1, formats=float, names='base')
+        x[0]['base'] = 10
+        assert_equal(x['base'][0], 10)
+
+    def test_exotic_formats(self):
+        # Test that 'exotic' formats are processed properly
+        easy = mrecarray(1, dtype=[('i', int), ('s', '|S8'), ('f', float)])
+        easy[0] = masked
+        assert_equal(easy.filled(1).item(), (1, b'1', 1.))
+
+        solo = mrecarray(1, dtype=[('f0', ' 1:
+            assert_(eq(np.concatenate((x, y), 1),
+                               concatenate((xm, ym), 1)))
+            assert_(eq(np.add.reduce(x, 1), add.reduce(x, 1)))
+            assert_(eq(np.sum(x, 1), sum(x, 1)))
+            assert_(eq(np.prod(x, 1), product(x, 1)))
+
+    def test_testCI(self):
+        # Test of conversions and indexing
+        x1 = np.array([1, 2, 4, 3])
+        x2 = array(x1, mask=[1, 0, 0, 0])
+        x3 = array(x1, mask=[0, 1, 0, 1])
+        x4 = array(x1)
+        # test conversion to strings
+        str(x2)  # raises?
+        repr(x2)  # raises?
+        assert_(eq(np.sort(x1), sort(x2, fill_value=0)))
+        # tests of indexing
+        assert_(type(x2[1]) is type(x1[1]))
+        assert_(x1[1] == x2[1])
+        assert_(x2[0] is masked)
+        assert_(eq(x1[2], x2[2]))
+        assert_(eq(x1[2:5], x2[2:5]))
+        assert_(eq(x1[:], x2[:]))
+        assert_(eq(x1[1:], x3[1:]))
+        x1[2] = 9
+        x2[2] = 9
+        assert_(eq(x1, x2))
+        x1[1:3] = 99
+        x2[1:3] = 99
+        assert_(eq(x1, x2))
+        x2[1] = masked
+        assert_(eq(x1, x2))
+        x2[1:3] = masked
+        assert_(eq(x1, x2))
+        x2[:] = x1
+        x2[1] = masked
+        assert_(allequal(getmask(x2), array([0, 1, 0, 0])))
+        x3[:] = masked_array([1, 2, 3, 4], [0, 1, 1, 0])
+        assert_(allequal(getmask(x3), array([0, 1, 1, 0])))
+        x4[:] = masked_array([1, 2, 3, 4], [0, 1, 1, 0])
+        assert_(allequal(getmask(x4), array([0, 1, 1, 0])))
+        assert_(allequal(x4, array([1, 2, 3, 4])))
+        x1 = np.arange(5) * 1.0
+        x2 = masked_values(x1, 3.0)
+        assert_(eq(x1, x2))
+        assert_(allequal(array([0, 0, 0, 1, 0], MaskType), x2.mask))
+        assert_(eq(3.0, x2.fill_value))
+        x1 = array([1, 'hello', 2, 3], object)
+        x2 = np.array([1, 'hello', 2, 3], object)
+        s1 = x1[1]
+        s2 = x2[1]
+        assert_equal(type(s2), str)
+        assert_equal(type(s1), str)
+        assert_equal(s1, s2)
+        assert_(x1[1:1].shape == (0,))
+
+    def test_testCopySize(self):
+        # Tests of some subtle points of copying and sizing.
+        n = [0, 0, 1, 0, 0]
+        m = make_mask(n)
+        m2 = make_mask(m)
+        assert_(m is m2)
+        m3 = make_mask(m, copy=True)
+        assert_(m is not m3)
+
+        x1 = np.arange(5)
+        y1 = array(x1, mask=m)
+        assert_(y1._data is not x1)
+        assert_(allequal(x1, y1._data))
+        assert_(y1._mask is m)
+
+        y1a = array(y1, copy=0)
+        # For copy=False, one might expect that the array would just
+        # passed on, i.e., that it would be "is" instead of "==".
+        # See gh-4043 for discussion.
+        assert_(y1a._mask.__array_interface__ ==
+                y1._mask.__array_interface__)
+
+        y2 = array(x1, mask=m3, copy=0)
+        assert_(y2._mask is m3)
+        assert_(y2[2] is masked)
+        y2[2] = 9
+        assert_(y2[2] is not masked)
+        assert_(y2._mask is m3)
+        assert_(allequal(y2.mask, 0))
+
+        y2a = array(x1, mask=m, copy=1)
+        assert_(y2a._mask is not m)
+        assert_(y2a[2] is masked)
+        y2a[2] = 9
+        assert_(y2a[2] is not masked)
+        assert_(y2a._mask is not m)
+        assert_(allequal(y2a.mask, 0))
+
+        y3 = array(x1 * 1.0, mask=m)
+        assert_(filled(y3).dtype is (x1 * 1.0).dtype)
+
+        x4 = arange(4)
+        x4[2] = masked
+        y4 = resize(x4, (8,))
+        assert_(eq(concatenate([x4, x4]), y4))
+        assert_(eq(getmask(y4), [0, 0, 1, 0, 0, 0, 1, 0]))
+        y5 = repeat(x4, (2, 2, 2, 2), axis=0)
+        assert_(eq(y5, [0, 0, 1, 1, 2, 2, 3, 3]))
+        y6 = repeat(x4, 2, axis=0)
+        assert_(eq(y5, y6))
+
+    def test_testPut(self):
+        # Test of put
+        d = arange(5)
+        n = [0, 0, 0, 1, 1]
+        m = make_mask(n)
+        m2 = m.copy()
+        x = array(d, mask=m)
+        assert_(x[3] is masked)
+        assert_(x[4] is masked)
+        x[[1, 4]] = [10, 40]
+        assert_(x._mask is m)
+        assert_(x[3] is masked)
+        assert_(x[4] is not masked)
+        assert_(eq(x, [0, 10, 2, -1, 40]))
+
+        x = array(d, mask=m2, copy=True)
+        x.put([0, 1, 2], [-1, 100, 200])
+        assert_(x._mask is not m2)
+        assert_(x[3] is masked)
+        assert_(x[4] is masked)
+        assert_(eq(x, [-1, 100, 200, 0, 0]))
+
+    def test_testPut2(self):
+        # Test of put
+        d = arange(5)
+        x = array(d, mask=[0, 0, 0, 0, 0])
+        z = array([10, 40], mask=[1, 0])
+        assert_(x[2] is not masked)
+        assert_(x[3] is not masked)
+        x[2:4] = z
+        assert_(x[2] is masked)
+        assert_(x[3] is not masked)
+        assert_(eq(x, [0, 1, 10, 40, 4]))
+
+        d = arange(5)
+        x = array(d, mask=[0, 0, 0, 0, 0])
+        y = x[2:4]
+        z = array([10, 40], mask=[1, 0])
+        assert_(x[2] is not masked)
+        assert_(x[3] is not masked)
+        y[:] = z
+        assert_(y[0] is masked)
+        assert_(y[1] is not masked)
+        assert_(eq(y, [10, 40]))
+        assert_(x[2] is masked)
+        assert_(x[3] is not masked)
+        assert_(eq(x, [0, 1, 10, 40, 4]))
+
+    def test_testMaPut(self):
+        (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d
+        m = [1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1]
+        i = np.nonzero(m)[0]
+        put(ym, i, zm)
+        assert_(all(take(ym, i, axis=0) == zm))
+
+    def test_testOddFeatures(self):
+        # Test of other odd features
+        x = arange(20)
+        x = x.reshape(4, 5)
+        x.flat[5] = 12
+        assert_(x[1, 0] == 12)
+        z = x + 10j * x
+        assert_(eq(z.real, x))
+        assert_(eq(z.imag, 10 * x))
+        assert_(eq((z * conjugate(z)).real, 101 * x * x))
+        z.imag[...] = 0.0
+
+        x = arange(10)
+        x[3] = masked
+        assert_(str(x[3]) == str(masked))
+        c = x >= 8
+        assert_(count(where(c, masked, masked)) == 0)
+        assert_(shape(where(c, masked, masked)) == c.shape)
+        z = where(c, x, masked)
+        assert_(z.dtype is x.dtype)
+        assert_(z[3] is masked)
+        assert_(z[4] is masked)
+        assert_(z[7] is masked)
+        assert_(z[8] is not masked)
+        assert_(z[9] is not masked)
+        assert_(eq(x, z))
+        z = where(c, masked, x)
+        assert_(z.dtype is x.dtype)
+        assert_(z[3] is masked)
+        assert_(z[4] is not masked)
+        assert_(z[7] is not masked)
+        assert_(z[8] is masked)
+        assert_(z[9] is masked)
+        z = masked_where(c, x)
+        assert_(z.dtype is x.dtype)
+        assert_(z[3] is masked)
+        assert_(z[4] is not masked)
+        assert_(z[7] is not masked)
+        assert_(z[8] is masked)
+        assert_(z[9] is masked)
+        assert_(eq(x, z))
+        x = array([1., 2., 3., 4., 5.])
+        c = array([1, 1, 1, 0, 0])
+        x[2] = masked
+        z = where(c, x, -x)
+        assert_(eq(z, [1., 2., 0., -4., -5]))
+        c[0] = masked
+        z = where(c, x, -x)
+        assert_(eq(z, [1., 2., 0., -4., -5]))
+        assert_(z[0] is masked)
+        assert_(z[1] is not masked)
+        assert_(z[2] is masked)
+        assert_(eq(masked_where(greater(x, 2), x), masked_greater(x, 2)))
+        assert_(eq(masked_where(greater_equal(x, 2), x),
+                   masked_greater_equal(x, 2)))
+        assert_(eq(masked_where(less(x, 2), x), masked_less(x, 2)))
+        assert_(eq(masked_where(less_equal(x, 2), x), masked_less_equal(x, 2)))
+        assert_(eq(masked_where(not_equal(x, 2), x), masked_not_equal(x, 2)))
+        assert_(eq(masked_where(equal(x, 2), x), masked_equal(x, 2)))
+        assert_(eq(masked_where(not_equal(x, 2), x), masked_not_equal(x, 2)))
+        assert_(eq(masked_inside(list(range(5)), 1, 3), [0, 199, 199, 199, 4]))
+        assert_(eq(masked_outside(list(range(5)), 1, 3), [199, 1, 2, 3, 199]))
+        assert_(eq(masked_inside(array(list(range(5)),
+                                       mask=[1, 0, 0, 0, 0]), 1, 3).mask,
+                   [1, 1, 1, 1, 0]))
+        assert_(eq(masked_outside(array(list(range(5)),
+                                        mask=[0, 1, 0, 0, 0]), 1, 3).mask,
+                   [1, 1, 0, 0, 1]))
+        assert_(eq(masked_equal(array(list(range(5)),
+                                      mask=[1, 0, 0, 0, 0]), 2).mask,
+                   [1, 0, 1, 0, 0]))
+        assert_(eq(masked_not_equal(array([2, 2, 1, 2, 1],
+                                          mask=[1, 0, 0, 0, 0]), 2).mask,
+                   [1, 0, 1, 0, 1]))
+        assert_(eq(masked_where([1, 1, 0, 0, 0], [1, 2, 3, 4, 5]),
+                   [99, 99, 3, 4, 5]))
+        atest = ones((10, 10, 10), dtype=np.float32)
+        btest = zeros(atest.shape, MaskType)
+        ctest = masked_where(btest, atest)
+        assert_(eq(atest, ctest))
+        z = choose(c, (-x, x))
+        assert_(eq(z, [1., 2., 0., -4., -5]))
+        assert_(z[0] is masked)
+        assert_(z[1] is not masked)
+        assert_(z[2] is masked)
+        x = arange(6)
+        x[5] = masked
+        y = arange(6) * 10
+        y[2] = masked
+        c = array([1, 1, 1, 0, 0, 0], mask=[1, 0, 0, 0, 0, 0])
+        cm = c.filled(1)
+        z = where(c, x, y)
+        zm = where(cm, x, y)
+        assert_(eq(z, zm))
+        assert_(getmask(zm) is nomask)
+        assert_(eq(zm, [0, 1, 2, 30, 40, 50]))
+        z = where(c, masked, 1)
+        assert_(eq(z, [99, 99, 99, 1, 1, 1]))
+        z = where(c, 1, masked)
+        assert_(eq(z, [99, 1, 1, 99, 99, 99]))
+
+    def test_testMinMax2(self):
+        # Test of minimum, maximum.
+        assert_(eq(minimum([1, 2, 3], [4, 0, 9]), [1, 0, 3]))
+        assert_(eq(maximum([1, 2, 3], [4, 0, 9]), [4, 2, 9]))
+        x = arange(5)
+        y = arange(5) - 2
+        x[3] = masked
+        y[0] = masked
+        assert_(eq(minimum(x, y), where(less(x, y), x, y)))
+        assert_(eq(maximum(x, y), where(greater(x, y), x, y)))
+        assert_(minimum.reduce(x) == 0)
+        assert_(maximum.reduce(x) == 4)
+
+    def test_testTakeTransposeInnerOuter(self):
+        # Test of take, transpose, inner, outer products
+        x = arange(24)
+        y = np.arange(24)
+        x[5:6] = masked
+        x = x.reshape(2, 3, 4)
+        y = y.reshape(2, 3, 4)
+        assert_(eq(np.transpose(y, (2, 0, 1)), transpose(x, (2, 0, 1))))
+        assert_(eq(np.take(y, (2, 0, 1), 1), take(x, (2, 0, 1), 1)))
+        assert_(eq(np.inner(filled(x, 0), filled(y, 0)),
+                   inner(x, y)))
+        assert_(eq(np.outer(filled(x, 0), filled(y, 0)),
+                   outer(x, y)))
+        y = array(['abc', 1, 'def', 2, 3], object)
+        y[2] = masked
+        t = take(y, [0, 3, 4])
+        assert_(t[0] == 'abc')
+        assert_(t[1] == 2)
+        assert_(t[2] == 3)
+
+    def test_testInplace(self):
+        # Test of inplace operations and rich comparisons
+        y = arange(10)
+
+        x = arange(10)
+        xm = arange(10)
+        xm[2] = masked
+        x += 1
+        assert_(eq(x, y + 1))
+        xm += 1
+        assert_(eq(x, y + 1))
+
+        x = arange(10)
+        xm = arange(10)
+        xm[2] = masked
+        x -= 1
+        assert_(eq(x, y - 1))
+        xm -= 1
+        assert_(eq(xm, y - 1))
+
+        x = arange(10) * 1.0
+        xm = arange(10) * 1.0
+        xm[2] = masked
+        x *= 2.0
+        assert_(eq(x, y * 2))
+        xm *= 2.0
+        assert_(eq(xm, y * 2))
+
+        x = arange(10) * 2
+        xm = arange(10)
+        xm[2] = masked
+        x //= 2
+        assert_(eq(x, y))
+        xm //= 2
+        assert_(eq(x, y))
+
+        x = arange(10) * 1.0
+        xm = arange(10) * 1.0
+        xm[2] = masked
+        x /= 2.0
+        assert_(eq(x, y / 2.0))
+        xm /= arange(10)
+        assert_(eq(xm, ones((10,))))
+
+        x = arange(10).astype(np.float32)
+        xm = arange(10)
+        xm[2] = masked
+        x += 1.
+        assert_(eq(x, y + 1.))
+
+    def test_testPickle(self):
+        # Test of pickling
+        x = arange(12)
+        x[4:10:2] = masked
+        x = x.reshape(4, 3)
+        for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
+            s = pickle.dumps(x, protocol=proto)
+            y = pickle.loads(s)
+            assert_(eq(x, y))
+
+    def test_testMasked(self):
+        # Test of masked element
+        xx = arange(6)
+        xx[1] = masked
+        assert_(str(masked) == '--')
+        assert_(xx[1] is masked)
+        assert_equal(filled(xx[1], 0), 0)
+
+    def test_testAverage1(self):
+        # Test of average.
+        ott = array([0., 1., 2., 3.], mask=[1, 0, 0, 0])
+        assert_(eq(2.0, average(ott, axis=0)))
+        assert_(eq(2.0, average(ott, weights=[1., 1., 2., 1.])))
+        result, wts = average(ott, weights=[1., 1., 2., 1.], returned=True)
+        assert_(eq(2.0, result))
+        assert_(wts == 4.0)
+        ott[:] = masked
+        assert_(average(ott, axis=0) is masked)
+        ott = array([0., 1., 2., 3.], mask=[1, 0, 0, 0])
+        ott = ott.reshape(2, 2)
+        ott[:, 1] = masked
+        assert_(eq(average(ott, axis=0), [2.0, 0.0]))
+        assert_(average(ott, axis=1)[0] is masked)
+        assert_(eq([2., 0.], average(ott, axis=0)))
+        result, wts = average(ott, axis=0, returned=True)
+        assert_(eq(wts, [1., 0.]))
+
+    def test_testAverage2(self):
+        # More tests of average.
+        w1 = [0, 1, 1, 1, 1, 0]
+        w2 = [[0, 1, 1, 1, 1, 0], [1, 0, 0, 0, 0, 1]]
+        x = arange(6)
+        assert_(allclose(average(x, axis=0), 2.5))
+        assert_(allclose(average(x, axis=0, weights=w1), 2.5))
+        y = array([arange(6), 2.0 * arange(6)])
+        assert_(allclose(average(y, None),
+                                 np.add.reduce(np.arange(6)) * 3. / 12.))
+        assert_(allclose(average(y, axis=0), np.arange(6) * 3. / 2.))
+        assert_(allclose(average(y, axis=1),
+                                 [average(x, axis=0), average(x, axis=0)*2.0]))
+        assert_(allclose(average(y, None, weights=w2), 20. / 6.))
+        assert_(allclose(average(y, axis=0, weights=w2),
+                                 [0., 1., 2., 3., 4., 10.]))
+        assert_(allclose(average(y, axis=1),
+                                 [average(x, axis=0), average(x, axis=0)*2.0]))
+        m1 = zeros(6)
+        m2 = [0, 0, 1, 1, 0, 0]
+        m3 = [[0, 0, 1, 1, 0, 0], [0, 1, 1, 1, 1, 0]]
+        m4 = ones(6)
+        m5 = [0, 1, 1, 1, 1, 1]
+        assert_(allclose(average(masked_array(x, m1), axis=0), 2.5))
+        assert_(allclose(average(masked_array(x, m2), axis=0), 2.5))
+        assert_(average(masked_array(x, m4), axis=0) is masked)
+        assert_equal(average(masked_array(x, m5), axis=0), 0.0)
+        assert_equal(count(average(masked_array(x, m4), axis=0)), 0)
+        z = masked_array(y, m3)
+        assert_(allclose(average(z, None), 20. / 6.))
+        assert_(allclose(average(z, axis=0),
+                                 [0., 1., 99., 99., 4.0, 7.5]))
+        assert_(allclose(average(z, axis=1), [2.5, 5.0]))
+        assert_(allclose(average(z, axis=0, weights=w2),
+                                 [0., 1., 99., 99., 4.0, 10.0]))
+
+        a = arange(6)
+        b = arange(6) * 3
+        r1, w1 = average([[a, b], [b, a]], axis=1, returned=True)
+        assert_equal(shape(r1), shape(w1))
+        assert_equal(r1.shape, w1.shape)
+        r2, w2 = average(ones((2, 2, 3)), axis=0, weights=[3, 1], returned=True)
+        assert_equal(shape(w2), shape(r2))
+        r2, w2 = average(ones((2, 2, 3)), returned=True)
+        assert_equal(shape(w2), shape(r2))
+        r2, w2 = average(ones((2, 2, 3)), weights=ones((2, 2, 3)), returned=True)
+        assert_(shape(w2) == shape(r2))
+        a2d = array([[1, 2], [0, 4]], float)
+        a2dm = masked_array(a2d, [[0, 0], [1, 0]])
+        a2da = average(a2d, axis=0)
+        assert_(eq(a2da, [0.5, 3.0]))
+        a2dma = average(a2dm, axis=0)
+        assert_(eq(a2dma, [1.0, 3.0]))
+        a2dma = average(a2dm, axis=None)
+        assert_(eq(a2dma, 7. / 3.))
+        a2dma = average(a2dm, axis=1)
+        assert_(eq(a2dma, [1.5, 4.0]))
+
+    def test_testToPython(self):
+        assert_equal(1, int(array(1)))
+        assert_equal(1.0, float(array(1)))
+        assert_equal(1, int(array([[[1]]])))
+        assert_equal(1.0, float(array([[1]])))
+        assert_raises(TypeError, float, array([1, 1]))
+        assert_raises(ValueError, bool, array([0, 1]))
+        assert_raises(ValueError, bool, array([0, 0], mask=[0, 1]))
+
+    def test_testScalarArithmetic(self):
+        xm = array(0, mask=1)
+        #TODO FIXME: Find out what the following raises a warning in r8247
+        with np.errstate(divide='ignore'):
+            assert_((1 / array(0)).mask)
+        assert_((1 + xm).mask)
+        assert_((-xm).mask)
+        assert_((-xm).mask)
+        assert_(maximum(xm, xm).mask)
+        assert_(minimum(xm, xm).mask)
+        assert_(xm.filled().dtype is xm._data.dtype)
+        x = array(0, mask=0)
+        assert_(x.filled() == x._data)
+        assert_equal(str(xm), str(masked_print_option))
+
+    def test_testArrayMethods(self):
+        a = array([1, 3, 2])
+        assert_(eq(a.any(), a._data.any()))
+        assert_(eq(a.all(), a._data.all()))
+        assert_(eq(a.argmax(), a._data.argmax()))
+        assert_(eq(a.argmin(), a._data.argmin()))
+        assert_(eq(a.choose(0, 1, 2, 3, 4),
+                           a._data.choose(0, 1, 2, 3, 4)))
+        assert_(eq(a.compress([1, 0, 1]), a._data.compress([1, 0, 1])))
+        assert_(eq(a.conj(), a._data.conj()))
+        assert_(eq(a.conjugate(), a._data.conjugate()))
+        m = array([[1, 2], [3, 4]])
+        assert_(eq(m.diagonal(), m._data.diagonal()))
+        assert_(eq(a.sum(), a._data.sum()))
+        assert_(eq(a.take([1, 2]), a._data.take([1, 2])))
+        assert_(eq(m.transpose(), m._data.transpose()))
+
+    def test_testArrayAttributes(self):
+        a = array([1, 3, 2])
+        assert_equal(a.ndim, 1)
+
+    def test_testAPI(self):
+        assert_(not [m for m in dir(np.ndarray)
+                     if m not in dir(MaskedArray) and
+                     not m.startswith('_')])
+
+    def test_testSingleElementSubscript(self):
+        a = array([1, 3, 2])
+        b = array([1, 3, 2], mask=[1, 0, 1])
+        assert_equal(a[0].shape, ())
+        assert_equal(b[0].shape, ())
+        assert_equal(b[1].shape, ())
+
+    def test_assignment_by_condition(self):
+        # Test for gh-18951
+        a = array([1, 2, 3, 4], mask=[1, 0, 1, 0])
+        c = a >= 3
+        a[c] = 5
+        assert_(a[2] is masked)
+
+    def test_assignment_by_condition_2(self):
+        # gh-19721
+        a = masked_array([0, 1], mask=[False, False])
+        b = masked_array([0, 1], mask=[True, True])
+        mask = a < 1
+        b[mask] = a[mask]
+        expected_mask = [False, True]
+        assert_equal(b.mask, expected_mask)
+
+
+class TestUfuncs:
+    def setup_method(self):
+        self.d = (array([1.0, 0, -1, pi / 2] * 2, mask=[0, 1] + [0] * 6),
+                  array([1.0, 0, -1, pi / 2] * 2, mask=[1, 0] + [0] * 6),)
+
+    def test_testUfuncRegression(self):
+        f_invalid_ignore = [
+            'sqrt', 'arctanh', 'arcsin', 'arccos',
+            'arccosh', 'arctanh', 'log', 'log10', 'divide',
+            'true_divide', 'floor_divide', 'remainder', 'fmod']
+        for f in ['sqrt', 'log', 'log10', 'exp', 'conjugate',
+                  'sin', 'cos', 'tan',
+                  'arcsin', 'arccos', 'arctan',
+                  'sinh', 'cosh', 'tanh',
+                  'arcsinh',
+                  'arccosh',
+                  'arctanh',
+                  'absolute', 'fabs', 'negative',
+                  'floor', 'ceil',
+                  'logical_not',
+                  'add', 'subtract', 'multiply',
+                  'divide', 'true_divide', 'floor_divide',
+                  'remainder', 'fmod', 'hypot', 'arctan2',
+                  'equal', 'not_equal', 'less_equal', 'greater_equal',
+                  'less', 'greater',
+                  'logical_and', 'logical_or', 'logical_xor']:
+            try:
+                uf = getattr(umath, f)
+            except AttributeError:
+                uf = getattr(fromnumeric, f)
+            mf = getattr(np.ma, f)
+            args = self.d[:uf.nin]
+            with np.errstate():
+                if f in f_invalid_ignore:
+                    np.seterr(invalid='ignore')
+                if f in ['arctanh', 'log', 'log10']:
+                    np.seterr(divide='ignore')
+                ur = uf(*args)
+                mr = mf(*args)
+            assert_(eq(ur.filled(0), mr.filled(0), f))
+            assert_(eqmask(ur.mask, mr.mask))
+
+    def test_reduce(self):
+        a = self.d[0]
+        assert_(not alltrue(a, axis=0))
+        assert_(sometrue(a, axis=0))
+        assert_equal(sum(a[:3], axis=0), 0)
+        assert_equal(product(a, axis=0), 0)
+
+    def test_minmax(self):
+        a = arange(1, 13).reshape(3, 4)
+        amask = masked_where(a < 5, a)
+        assert_equal(amask.max(), a.max())
+        assert_equal(amask.min(), 5)
+        assert_((amask.max(0) == a.max(0)).all())
+        assert_((amask.min(0) == [5, 6, 7, 8]).all())
+        assert_(amask.max(1)[0].mask)
+        assert_(amask.min(1)[0].mask)
+
+    def test_nonzero(self):
+        for t in "?bhilqpBHILQPfdgFDGO":
+            x = array([1, 0, 2, 0], mask=[0, 0, 1, 1])
+            assert_(eq(nonzero(x), [0]))
+
+
+class TestArrayMethods:
+
+    def setup_method(self):
+        x = np.array([8.375, 7.545, 8.828, 8.5, 1.757, 5.928,
+                      8.43, 7.78, 9.865, 5.878, 8.979, 4.732,
+                      3.012, 6.022, 5.095, 3.116, 5.238, 3.957,
+                      6.04, 9.63, 7.712, 3.382, 4.489, 6.479,
+                      7.189, 9.645, 5.395, 4.961, 9.894, 2.893,
+                      7.357, 9.828, 6.272, 3.758, 6.693, 0.993])
+        X = x.reshape(6, 6)
+        XX = x.reshape(3, 2, 2, 3)
+
+        m = np.array([0, 1, 0, 1, 0, 0,
+                      1, 0, 1, 1, 0, 1,
+                      0, 0, 0, 1, 0, 1,
+                      0, 0, 0, 1, 1, 1,
+                      1, 0, 0, 1, 0, 0,
+                      0, 0, 1, 0, 1, 0])
+        mx = array(data=x, mask=m)
+        mX = array(data=X, mask=m.reshape(X.shape))
+        mXX = array(data=XX, mask=m.reshape(XX.shape))
+
+        self.d = (x, X, XX, m, mx, mX, mXX)
+
+    def test_trace(self):
+        (x, X, XX, m, mx, mX, mXX,) = self.d
+        mXdiag = mX.diagonal()
+        assert_equal(mX.trace(), mX.diagonal().compressed().sum())
+        assert_(eq(mX.trace(),
+                           X.trace() - sum(mXdiag.mask * X.diagonal(),
+                                           axis=0)))
+
+    def test_clip(self):
+        (x, X, XX, m, mx, mX, mXX,) = self.d
+        clipped = mx.clip(2, 8)
+        assert_(eq(clipped.mask, mx.mask))
+        assert_(eq(clipped._data, x.clip(2, 8)))
+        assert_(eq(clipped._data, mx._data.clip(2, 8)))
+
+    def test_ptp(self):
+        (x, X, XX, m, mx, mX, mXX,) = self.d
+        (n, m) = X.shape
+        assert_equal(mx.ptp(), mx.compressed().ptp())
+        rows = np.zeros(n, np.float_)
+        cols = np.zeros(m, np.float_)
+        for k in range(m):
+            cols[k] = mX[:, k].compressed().ptp()
+        for k in range(n):
+            rows[k] = mX[k].compressed().ptp()
+        assert_(eq(mX.ptp(0), cols))
+        assert_(eq(mX.ptp(1), rows))
+
+    def test_swapaxes(self):
+        (x, X, XX, m, mx, mX, mXX,) = self.d
+        mXswapped = mX.swapaxes(0, 1)
+        assert_(eq(mXswapped[-1], mX[:, -1]))
+        mXXswapped = mXX.swapaxes(0, 2)
+        assert_equal(mXXswapped.shape, (2, 2, 3, 3))
+
+    def test_cumprod(self):
+        (x, X, XX, m, mx, mX, mXX,) = self.d
+        mXcp = mX.cumprod(0)
+        assert_(eq(mXcp._data, mX.filled(1).cumprod(0)))
+        mXcp = mX.cumprod(1)
+        assert_(eq(mXcp._data, mX.filled(1).cumprod(1)))
+
+    def test_cumsum(self):
+        (x, X, XX, m, mx, mX, mXX,) = self.d
+        mXcp = mX.cumsum(0)
+        assert_(eq(mXcp._data, mX.filled(0).cumsum(0)))
+        mXcp = mX.cumsum(1)
+        assert_(eq(mXcp._data, mX.filled(0).cumsum(1)))
+
+    def test_varstd(self):
+        (x, X, XX, m, mx, mX, mXX,) = self.d
+        assert_(eq(mX.var(axis=None), mX.compressed().var()))
+        assert_(eq(mX.std(axis=None), mX.compressed().std()))
+        assert_(eq(mXX.var(axis=3).shape, XX.var(axis=3).shape))
+        assert_(eq(mX.var().shape, X.var().shape))
+        (mXvar0, mXvar1) = (mX.var(axis=0), mX.var(axis=1))
+        for k in range(6):
+            assert_(eq(mXvar1[k], mX[k].compressed().var()))
+            assert_(eq(mXvar0[k], mX[:, k].compressed().var()))
+            assert_(eq(np.sqrt(mXvar0[k]),
+                               mX[:, k].compressed().std()))
+
+
+def eqmask(m1, m2):
+    if m1 is nomask:
+        return m2 is nomask
+    if m2 is nomask:
+        return m1 is nomask
+    return (m1 == m2).all()
diff --git a/venv/lib/python3.10/site-packages/numpy/ma/tests/test_regression.py b/venv/lib/python3.10/site-packages/numpy/ma/tests/test_regression.py
new file mode 100644
index 0000000000000000000000000000000000000000..f4f32cc7a98b4567076c9ccb340f6063321ba607
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/numpy/ma/tests/test_regression.py
@@ -0,0 +1,97 @@
+import numpy as np
+from numpy.testing import (
+    assert_, assert_array_equal, assert_allclose, suppress_warnings
+    )
+
+
+class TestRegression:
+    def test_masked_array_create(self):
+        # Ticket #17
+        x = np.ma.masked_array([0, 1, 2, 3, 0, 4, 5, 6],
+                               mask=[0, 0, 0, 1, 1, 1, 0, 0])
+        assert_array_equal(np.ma.nonzero(x), [[1, 2, 6, 7]])
+
+    def test_masked_array(self):
+        # Ticket #61
+        np.ma.array(1, mask=[1])
+
+    def test_mem_masked_where(self):
+        # Ticket #62
+        from numpy.ma import masked_where, MaskType
+        a = np.zeros((1, 1))
+        b = np.zeros(a.shape, MaskType)
+        c = masked_where(b, a)
+        a-c
+
+    def test_masked_array_multiply(self):
+        # Ticket #254
+        a = np.ma.zeros((4, 1))
+        a[2, 0] = np.ma.masked
+        b = np.zeros((4, 2))
+        a*b
+        b*a
+
+    def test_masked_array_repeat(self):
+        # Ticket #271
+        np.ma.array([1], mask=False).repeat(10)
+
+    def test_masked_array_repr_unicode(self):
+        # Ticket #1256
+        repr(np.ma.array("Unicode"))
+
+    def test_atleast_2d(self):
+        # Ticket #1559
+        a = np.ma.masked_array([0.0, 1.2, 3.5], mask=[False, True, False])
+        b = np.atleast_2d(a)
+        assert_(a.mask.ndim == 1)
+        assert_(b.mask.ndim == 2)
+
+    def test_set_fill_value_unicode_py3(self):
+        # Ticket #2733
+        a = np.ma.masked_array(['a', 'b', 'c'], mask=[1, 0, 0])
+        a.fill_value = 'X'
+        assert_(a.fill_value == 'X')
+
+    def test_var_sets_maskedarray_scalar(self):
+        # Issue gh-2757
+        a = np.ma.array(np.arange(5), mask=True)
+        mout = np.ma.array(-1, dtype=float)
+        a.var(out=mout)
+        assert_(mout._data == 0)
+
+    def test_ddof_corrcoef(self):
+        # See gh-3336
+        x = np.ma.masked_equal([1, 2, 3, 4, 5], 4)
+        y = np.array([2, 2.5, 3.1, 3, 5])
+        # this test can be removed after deprecation.
+        with suppress_warnings() as sup:
+            sup.filter(DeprecationWarning, "bias and ddof have no effect")
+            r0 = np.ma.corrcoef(x, y, ddof=0)
+            r1 = np.ma.corrcoef(x, y, ddof=1)
+            # ddof should not have an effect (it gets cancelled out)
+            assert_allclose(r0.data, r1.data)
+
+    def test_mask_not_backmangled(self):
+        # See gh-10314.  Test case taken from gh-3140.
+        a = np.ma.MaskedArray([1., 2.], mask=[False, False])
+        assert_(a.mask.shape == (2,))
+        b = np.tile(a, (2, 1))
+        # Check that the above no longer changes a.shape to (1, 2)
+        assert_(a.mask.shape == (2,))
+        assert_(b.shape == (2, 2))
+        assert_(b.mask.shape == (2, 2))
+
+    def test_empty_list_on_structured(self):
+        # See gh-12464. Indexing with empty list should give empty result.
+        ma = np.ma.MaskedArray([(1, 1.), (2, 2.), (3, 3.)], dtype='i4,f4')
+        assert_array_equal(ma[[]], ma[:0])
+
+    def test_masked_array_tobytes_fortran(self):
+        ma = np.ma.arange(4).reshape((2,2))
+        assert_array_equal(ma.tobytes(order='F'), ma.T.tobytes())
+
+    def test_structured_array(self):
+        # see gh-22041
+        np.ma.array((1, (b"", b"")),
+                    dtype=[("x", np.int_),
+                          ("y", [("i", np.void), ("j", np.void)])])
diff --git a/venv/lib/python3.10/site-packages/numpy/ma/tests/test_subclassing.py b/venv/lib/python3.10/site-packages/numpy/ma/tests/test_subclassing.py
new file mode 100644
index 0000000000000000000000000000000000000000..e3c88525371edbf742d4e2e9c7401b60b29cd740
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/numpy/ma/tests/test_subclassing.py
@@ -0,0 +1,460 @@
+# pylint: disable-msg=W0611, W0612, W0511,R0201
+"""Tests suite for MaskedArray & subclassing.
+
+:author: Pierre Gerard-Marchant
+:contact: pierregm_at_uga_dot_edu
+:version: $Id: test_subclassing.py 3473 2007-10-29 15:18:13Z jarrod.millman $
+
+"""
+import numpy as np
+from numpy.lib.mixins import NDArrayOperatorsMixin
+from numpy.testing import assert_, assert_raises
+from numpy.ma.testutils import assert_equal
+from numpy.ma.core import (
+    array, arange, masked, MaskedArray, masked_array, log, add, hypot,
+    divide, asarray, asanyarray, nomask
+    )
+# from numpy.ma.core import (
+
+def assert_startswith(a, b):
+    # produces a better error message than assert_(a.startswith(b))
+    assert_equal(a[:len(b)], b)
+
+class SubArray(np.ndarray):
+    # Defines a generic np.ndarray subclass, that stores some metadata
+    # in the  dictionary `info`.
+    def __new__(cls,arr,info={}):
+        x = np.asanyarray(arr).view(cls)
+        x.info = info.copy()
+        return x
+
+    def __array_finalize__(self, obj):
+        super().__array_finalize__(obj)
+        self.info = getattr(obj, 'info', {}).copy()
+        return
+
+    def __add__(self, other):
+        result = super().__add__(other)
+        result.info['added'] = result.info.get('added', 0) + 1
+        return result
+
+    def __iadd__(self, other):
+        result = super().__iadd__(other)
+        result.info['iadded'] = result.info.get('iadded', 0) + 1
+        return result
+
+
+subarray = SubArray
+
+
+class SubMaskedArray(MaskedArray):
+    """Pure subclass of MaskedArray, keeping some info on subclass."""
+    def __new__(cls, info=None, **kwargs):
+        obj = super().__new__(cls, **kwargs)
+        obj._optinfo['info'] = info
+        return obj
+
+
+class MSubArray(SubArray, MaskedArray):
+
+    def __new__(cls, data, info={}, mask=nomask):
+        subarr = SubArray(data, info)
+        _data = MaskedArray.__new__(cls, data=subarr, mask=mask)
+        _data.info = subarr.info
+        return _data
+
+    @property
+    def _series(self):
+        _view = self.view(MaskedArray)
+        _view._sharedmask = False
+        return _view
+
+msubarray = MSubArray
+
+
+# Also a subclass that overrides __str__, __repr__ and __setitem__, disallowing
+# setting to non-class values (and thus np.ma.core.masked_print_option)
+# and overrides __array_wrap__, updating the info dict, to check that this
+# doesn't get destroyed by MaskedArray._update_from.  But this one also needs
+# its own iterator...
+class CSAIterator:
+    """
+    Flat iterator object that uses its own setter/getter
+    (works around ndarray.flat not propagating subclass setters/getters
+    see https://github.com/numpy/numpy/issues/4564)
+    roughly following MaskedIterator
+    """
+    def __init__(self, a):
+        self._original = a
+        self._dataiter = a.view(np.ndarray).flat
+
+    def __iter__(self):
+        return self
+
+    def __getitem__(self, indx):
+        out = self._dataiter.__getitem__(indx)
+        if not isinstance(out, np.ndarray):
+            out = out.__array__()
+        out = out.view(type(self._original))
+        return out
+
+    def __setitem__(self, index, value):
+        self._dataiter[index] = self._original._validate_input(value)
+
+    def __next__(self):
+        return next(self._dataiter).__array__().view(type(self._original))
+
+
+class ComplicatedSubArray(SubArray):
+
+    def __str__(self):
+        return f'myprefix {self.view(SubArray)} mypostfix'
+
+    def __repr__(self):
+        # Return a repr that does not start with 'name('
+        return f'<{self.__class__.__name__} {self}>'
+
+    def _validate_input(self, value):
+        if not isinstance(value, ComplicatedSubArray):
+            raise ValueError("Can only set to MySubArray values")
+        return value
+
+    def __setitem__(self, item, value):
+        # validation ensures direct assignment with ndarray or
+        # masked_print_option will fail
+        super().__setitem__(item, self._validate_input(value))
+
+    def __getitem__(self, item):
+        # ensure getter returns our own class also for scalars
+        value = super().__getitem__(item)
+        if not isinstance(value, np.ndarray):  # scalar
+            value = value.__array__().view(ComplicatedSubArray)
+        return value
+
+    @property
+    def flat(self):
+        return CSAIterator(self)
+
+    @flat.setter
+    def flat(self, value):
+        y = self.ravel()
+        y[:] = value
+
+    def __array_wrap__(self, obj, context=None):
+        obj = super().__array_wrap__(obj, context)
+        if context is not None and context[0] is np.multiply:
+            obj.info['multiplied'] = obj.info.get('multiplied', 0) + 1
+
+        return obj
+
+
+class WrappedArray(NDArrayOperatorsMixin):
+    """
+    Wrapping a MaskedArray rather than subclassing to test that
+    ufunc deferrals are commutative.
+    See: https://github.com/numpy/numpy/issues/15200)
+    """
+    __slots__ = ('_array', 'attrs')
+    __array_priority__ = 20
+
+    def __init__(self, array, **attrs):
+        self._array = array
+        self.attrs = attrs
+
+    def __repr__(self):
+        return f"{self.__class__.__name__}(\n{self._array}\n{self.attrs}\n)"
+
+    def __array__(self):
+        return np.asarray(self._array)
+
+    def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
+        if method == '__call__':
+            inputs = [arg._array if isinstance(arg, self.__class__) else arg
+                      for arg in inputs]
+            return self.__class__(ufunc(*inputs, **kwargs), **self.attrs)
+        else:
+            return NotImplemented
+
+
+class TestSubclassing:
+    # Test suite for masked subclasses of ndarray.
+
+    def setup_method(self):
+        x = np.arange(5, dtype='float')
+        mx = msubarray(x, mask=[0, 1, 0, 0, 0])
+        self.data = (x, mx)
+
+    def test_data_subclassing(self):
+        # Tests whether the subclass is kept.
+        x = np.arange(5)
+        m = [0, 0, 1, 0, 0]
+        xsub = SubArray(x)
+        xmsub = masked_array(xsub, mask=m)
+        assert_(isinstance(xmsub, MaskedArray))
+        assert_equal(xmsub._data, xsub)
+        assert_(isinstance(xmsub._data, SubArray))
+
+    def test_maskedarray_subclassing(self):
+        # Tests subclassing MaskedArray
+        (x, mx) = self.data
+        assert_(isinstance(mx._data, subarray))
+
+    def test_masked_unary_operations(self):
+        # Tests masked_unary_operation
+        (x, mx) = self.data
+        with np.errstate(divide='ignore'):
+            assert_(isinstance(log(mx), msubarray))
+            assert_equal(log(x), np.log(x))
+
+    def test_masked_binary_operations(self):
+        # Tests masked_binary_operation
+        (x, mx) = self.data
+        # Result should be a msubarray
+        assert_(isinstance(add(mx, mx), msubarray))
+        assert_(isinstance(add(mx, x), msubarray))
+        # Result should work
+        assert_equal(add(mx, x), mx+x)
+        assert_(isinstance(add(mx, mx)._data, subarray))
+        assert_(isinstance(add.outer(mx, mx), msubarray))
+        assert_(isinstance(hypot(mx, mx), msubarray))
+        assert_(isinstance(hypot(mx, x), msubarray))
+
+    def test_masked_binary_operations2(self):
+        # Tests domained_masked_binary_operation
+        (x, mx) = self.data
+        xmx = masked_array(mx.data.__array__(), mask=mx.mask)
+        assert_(isinstance(divide(mx, mx), msubarray))
+        assert_(isinstance(divide(mx, x), msubarray))
+        assert_equal(divide(mx, mx), divide(xmx, xmx))
+
+    def test_attributepropagation(self):
+        x = array(arange(5), mask=[0]+[1]*4)
+        my = masked_array(subarray(x))
+        ym = msubarray(x)
+        #
+        z = (my+1)
+        assert_(isinstance(z, MaskedArray))
+        assert_(not isinstance(z, MSubArray))
+        assert_(isinstance(z._data, SubArray))
+        assert_equal(z._data.info, {})
+        #
+        z = (ym+1)
+        assert_(isinstance(z, MaskedArray))
+        assert_(isinstance(z, MSubArray))
+        assert_(isinstance(z._data, SubArray))
+        assert_(z._data.info['added'] > 0)
+        # Test that inplace methods from data get used (gh-4617)
+        ym += 1
+        assert_(isinstance(ym, MaskedArray))
+        assert_(isinstance(ym, MSubArray))
+        assert_(isinstance(ym._data, SubArray))
+        assert_(ym._data.info['iadded'] > 0)
+        #
+        ym._set_mask([1, 0, 0, 0, 1])
+        assert_equal(ym._mask, [1, 0, 0, 0, 1])
+        ym._series._set_mask([0, 0, 0, 0, 1])
+        assert_equal(ym._mask, [0, 0, 0, 0, 1])
+        #
+        xsub = subarray(x, info={'name':'x'})
+        mxsub = masked_array(xsub)
+        assert_(hasattr(mxsub, 'info'))
+        assert_equal(mxsub.info, xsub.info)
+
+    def test_subclasspreservation(self):
+        # Checks that masked_array(...,subok=True) preserves the class.
+        x = np.arange(5)
+        m = [0, 0, 1, 0, 0]
+        xinfo = [(i, j) for (i, j) in zip(x, m)]
+        xsub = MSubArray(x, mask=m, info={'xsub':xinfo})
+        #
+        mxsub = masked_array(xsub, subok=False)
+        assert_(not isinstance(mxsub, MSubArray))
+        assert_(isinstance(mxsub, MaskedArray))
+        assert_equal(mxsub._mask, m)
+        #
+        mxsub = asarray(xsub)
+        assert_(not isinstance(mxsub, MSubArray))
+        assert_(isinstance(mxsub, MaskedArray))
+        assert_equal(mxsub._mask, m)
+        #
+        mxsub = masked_array(xsub, subok=True)
+        assert_(isinstance(mxsub, MSubArray))
+        assert_equal(mxsub.info, xsub.info)
+        assert_equal(mxsub._mask, xsub._mask)
+        #
+        mxsub = asanyarray(xsub)
+        assert_(isinstance(mxsub, MSubArray))
+        assert_equal(mxsub.info, xsub.info)
+        assert_equal(mxsub._mask, m)
+
+    def test_subclass_items(self):
+        """test that getter and setter go via baseclass"""
+        x = np.arange(5)
+        xcsub = ComplicatedSubArray(x)
+        mxcsub = masked_array(xcsub, mask=[True, False, True, False, False])
+        # getter should  return a ComplicatedSubArray, even for single item
+        # first check we wrote ComplicatedSubArray correctly
+        assert_(isinstance(xcsub[1], ComplicatedSubArray))
+        assert_(isinstance(xcsub[1,...], ComplicatedSubArray))
+        assert_(isinstance(xcsub[1:4], ComplicatedSubArray))
+
+        # now that it propagates inside the MaskedArray
+        assert_(isinstance(mxcsub[1], ComplicatedSubArray))
+        assert_(isinstance(mxcsub[1,...].data, ComplicatedSubArray))
+        assert_(mxcsub[0] is masked)
+        assert_(isinstance(mxcsub[0,...].data, ComplicatedSubArray))
+        assert_(isinstance(mxcsub[1:4].data, ComplicatedSubArray))
+
+        # also for flattened version (which goes via MaskedIterator)
+        assert_(isinstance(mxcsub.flat[1].data, ComplicatedSubArray))
+        assert_(mxcsub.flat[0] is masked)
+        assert_(isinstance(mxcsub.flat[1:4].base, ComplicatedSubArray))
+
+        # setter should only work with ComplicatedSubArray input
+        # first check we wrote ComplicatedSubArray correctly
+        assert_raises(ValueError, xcsub.__setitem__, 1, x[4])
+        # now that it propagates inside the MaskedArray
+        assert_raises(ValueError, mxcsub.__setitem__, 1, x[4])
+        assert_raises(ValueError, mxcsub.__setitem__, slice(1, 4), x[1:4])
+        mxcsub[1] = xcsub[4]
+        mxcsub[1:4] = xcsub[1:4]
+        # also for flattened version (which goes via MaskedIterator)
+        assert_raises(ValueError, mxcsub.flat.__setitem__, 1, x[4])
+        assert_raises(ValueError, mxcsub.flat.__setitem__, slice(1, 4), x[1:4])
+        mxcsub.flat[1] = xcsub[4]
+        mxcsub.flat[1:4] = xcsub[1:4]
+
+    def test_subclass_nomask_items(self):
+        x = np.arange(5)
+        xcsub = ComplicatedSubArray(x)
+        mxcsub_nomask = masked_array(xcsub)
+
+        assert_(isinstance(mxcsub_nomask[1,...].data, ComplicatedSubArray))
+        assert_(isinstance(mxcsub_nomask[0,...].data, ComplicatedSubArray))
+
+        assert_(isinstance(mxcsub_nomask[1], ComplicatedSubArray))
+        assert_(isinstance(mxcsub_nomask[0], ComplicatedSubArray))
+
+    def test_subclass_repr(self):
+        """test that repr uses the name of the subclass
+        and 'array' for np.ndarray"""
+        x = np.arange(5)
+        mx = masked_array(x, mask=[True, False, True, False, False])
+        assert_startswith(repr(mx), 'masked_array')
+        xsub = SubArray(x)
+        mxsub = masked_array(xsub, mask=[True, False, True, False, False])
+        assert_startswith(repr(mxsub),
+            f'masked_{SubArray.__name__}(data=[--, 1, --, 3, 4]')
+
+    def test_subclass_str(self):
+        """test str with subclass that has overridden str, setitem"""
+        # first without override
+        x = np.arange(5)
+        xsub = SubArray(x)
+        mxsub = masked_array(xsub, mask=[True, False, True, False, False])
+        assert_equal(str(mxsub), '[-- 1 -- 3 4]')
+
+        xcsub = ComplicatedSubArray(x)
+        assert_raises(ValueError, xcsub.__setitem__, 0,
+                      np.ma.core.masked_print_option)
+        mxcsub = masked_array(xcsub, mask=[True, False, True, False, False])
+        assert_equal(str(mxcsub), 'myprefix [-- 1 -- 3 4] mypostfix')
+
+    def test_pure_subclass_info_preservation(self):
+        # Test that ufuncs and methods conserve extra information consistently;
+        # see gh-7122.
+        arr1 = SubMaskedArray('test', data=[1,2,3,4,5,6])
+        arr2 = SubMaskedArray(data=[0,1,2,3,4,5])
+        diff1 = np.subtract(arr1, arr2)
+        assert_('info' in diff1._optinfo)
+        assert_(diff1._optinfo['info'] == 'test')
+        diff2 = arr1 - arr2
+        assert_('info' in diff2._optinfo)
+        assert_(diff2._optinfo['info'] == 'test')
+
+
+class ArrayNoInheritance:
+    """Quantity-like class that does not inherit from ndarray"""
+    def __init__(self, data, units):
+        self.magnitude = data
+        self.units = units
+
+    def __getattr__(self, attr):
+        return getattr(self.magnitude, attr)
+
+
+def test_array_no_inheritance():
+    data_masked = np.ma.array([1, 2, 3], mask=[True, False, True])
+    data_masked_units = ArrayNoInheritance(data_masked, 'meters')
+
+    # Get the masked representation of the Quantity-like class
+    new_array = np.ma.array(data_masked_units)
+    assert_equal(data_masked.data, new_array.data)
+    assert_equal(data_masked.mask, new_array.mask)
+    # Test sharing the mask
+    data_masked.mask = [True, False, False]
+    assert_equal(data_masked.mask, new_array.mask)
+    assert_(new_array.sharedmask)
+
+    # Get the masked representation of the Quantity-like class
+    new_array = np.ma.array(data_masked_units, copy=True)
+    assert_equal(data_masked.data, new_array.data)
+    assert_equal(data_masked.mask, new_array.mask)
+    # Test that the mask is not shared when copy=True
+    data_masked.mask = [True, False, True]
+    assert_equal([True, False, False], new_array.mask)
+    assert_(not new_array.sharedmask)
+
+    # Get the masked representation of the Quantity-like class
+    new_array = np.ma.array(data_masked_units, keep_mask=False)
+    assert_equal(data_masked.data, new_array.data)
+    # The change did not affect the original mask
+    assert_equal(data_masked.mask, [True, False, True])
+    # Test that the mask is False and not shared when keep_mask=False
+    assert_(not new_array.mask)
+    assert_(not new_array.sharedmask)
+
+
+class TestClassWrapping:
+    # Test suite for classes that wrap MaskedArrays
+
+    def setup_method(self):
+        m = np.ma.masked_array([1, 3, 5], mask=[False, True, False])
+        wm = WrappedArray(m)
+        self.data = (m, wm)
+
+    def test_masked_unary_operations(self):
+        # Tests masked_unary_operation
+        (m, wm) = self.data
+        with np.errstate(divide='ignore'):
+            assert_(isinstance(np.log(wm), WrappedArray))
+
+    def test_masked_binary_operations(self):
+        # Tests masked_binary_operation
+        (m, wm) = self.data
+        # Result should be a WrappedArray
+        assert_(isinstance(np.add(wm, wm), WrappedArray))
+        assert_(isinstance(np.add(m, wm), WrappedArray))
+        assert_(isinstance(np.add(wm, m), WrappedArray))
+        # add and '+' should call the same ufunc
+        assert_equal(np.add(m, wm), m + wm)
+        assert_(isinstance(np.hypot(m, wm), WrappedArray))
+        assert_(isinstance(np.hypot(wm, m), WrappedArray))
+        # Test domained binary operations
+        assert_(isinstance(np.divide(wm, m), WrappedArray))
+        assert_(isinstance(np.divide(m, wm), WrappedArray))
+        assert_equal(np.divide(wm, m) * m, np.divide(m, m) * wm)
+        # Test broadcasting
+        m2 = np.stack([m, m])
+        assert_(isinstance(np.divide(wm, m2), WrappedArray))
+        assert_(isinstance(np.divide(m2, wm), WrappedArray))
+        assert_equal(np.divide(m2, wm), np.divide(wm, m2))
+
+    def test_mixins_have_slots(self):
+        mixin = NDArrayOperatorsMixin()
+        # Should raise an error
+        assert_raises(AttributeError, mixin.__setattr__, "not_a_real_attr", 1)
+
+        m = np.ma.masked_array([1, 3, 5], mask=[False, True, False])
+        wm = WrappedArray(m)
+        assert_raises(AttributeError, wm.__setattr__, "not_an_attr", 2)
diff --git a/venv/lib/python3.10/site-packages/numpy/ma/testutils.py b/venv/lib/python3.10/site-packages/numpy/ma/testutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a633906bb4245261d71e9e783e188f3d44b7790
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/numpy/ma/testutils.py
@@ -0,0 +1,288 @@
+"""Miscellaneous functions for testing masked arrays and subclasses
+
+:author: Pierre Gerard-Marchant
+:contact: pierregm_at_uga_dot_edu
+:version: $Id: testutils.py 3529 2007-11-13 08:01:14Z jarrod.millman $
+
+"""
+import operator
+
+import numpy as np
+from numpy import ndarray, float_
+import numpy.core.umath as umath
+import numpy.testing
+from numpy.testing import (
+    assert_, assert_allclose, assert_array_almost_equal_nulp,
+    assert_raises, build_err_msg
+    )
+from .core import mask_or, getmask, masked_array, nomask, masked, filled
+
+__all__masked = [
+    'almost', 'approx', 'assert_almost_equal', 'assert_array_almost_equal',
+    'assert_array_approx_equal', 'assert_array_compare',
+    'assert_array_equal', 'assert_array_less', 'assert_close',
+    'assert_equal', 'assert_equal_records', 'assert_mask_equal',
+    'assert_not_equal', 'fail_if_array_equal',
+    ]
+
+# Include some normal test functions to avoid breaking other projects who
+# have mistakenly included them from this file. SciPy is one. That is
+# unfortunate, as some of these functions are not intended to work with
+# masked arrays. But there was no way to tell before.
+from unittest import TestCase
+__some__from_testing = [
+    'TestCase', 'assert_', 'assert_allclose', 'assert_array_almost_equal_nulp',
+    'assert_raises'
+    ]
+
+__all__ = __all__masked + __some__from_testing
+
+
+def approx(a, b, fill_value=True, rtol=1e-5, atol=1e-8):
+    """
+    Returns true if all components of a and b are equal to given tolerances.
+
+    If fill_value is True, masked values considered equal. Otherwise,
+    masked values are considered unequal.  The relative error rtol should
+    be positive and << 1.0 The absolute error atol comes into play for
+    those elements of b that are very small or zero; it says how small a
+    must be also.
+
+    """
+    m = mask_or(getmask(a), getmask(b))
+    d1 = filled(a)
+    d2 = filled(b)
+    if d1.dtype.char == "O" or d2.dtype.char == "O":
+        return np.equal(d1, d2).ravel()
+    x = filled(masked_array(d1, copy=False, mask=m), fill_value).astype(float_)
+    y = filled(masked_array(d2, copy=False, mask=m), 1).astype(float_)
+    d = np.less_equal(umath.absolute(x - y), atol + rtol * umath.absolute(y))
+    return d.ravel()
+
+
+def almost(a, b, decimal=6, fill_value=True):
+    """
+    Returns True if a and b are equal up to decimal places.
+
+    If fill_value is True, masked values considered equal. Otherwise,
+    masked values are considered unequal.
+
+    """
+    m = mask_or(getmask(a), getmask(b))
+    d1 = filled(a)
+    d2 = filled(b)
+    if d1.dtype.char == "O" or d2.dtype.char == "O":
+        return np.equal(d1, d2).ravel()
+    x = filled(masked_array(d1, copy=False, mask=m), fill_value).astype(float_)
+    y = filled(masked_array(d2, copy=False, mask=m), 1).astype(float_)
+    d = np.around(np.abs(x - y), decimal) <= 10.0 ** (-decimal)
+    return d.ravel()
+
+
+def _assert_equal_on_sequences(actual, desired, err_msg=''):
+    """
+    Asserts the equality of two non-array sequences.
+
+    """
+    assert_equal(len(actual), len(desired), err_msg)
+    for k in range(len(desired)):
+        assert_equal(actual[k], desired[k], f'item={k!r}\n{err_msg}')
+    return
+
+
+def assert_equal_records(a, b):
+    """
+    Asserts that two records are equal.
+
+    Pretty crude for now.
+
+    """
+    assert_equal(a.dtype, b.dtype)
+    for f in a.dtype.names:
+        (af, bf) = (operator.getitem(a, f), operator.getitem(b, f))
+        if not (af is masked) and not (bf is masked):
+            assert_equal(operator.getitem(a, f), operator.getitem(b, f))
+    return
+
+
+def assert_equal(actual, desired, err_msg=''):
+    """
+    Asserts that two items are equal.
+
+    """
+    # Case #1: dictionary .....
+    if isinstance(desired, dict):
+        if not isinstance(actual, dict):
+            raise AssertionError(repr(type(actual)))
+        assert_equal(len(actual), len(desired), err_msg)
+        for k, i in desired.items():
+            if k not in actual:
+                raise AssertionError(f"{k} not in {actual}")
+            assert_equal(actual[k], desired[k], f'key={k!r}\n{err_msg}')
+        return
+    # Case #2: lists .....
+    if isinstance(desired, (list, tuple)) and isinstance(actual, (list, tuple)):
+        return _assert_equal_on_sequences(actual, desired, err_msg='')
+    if not (isinstance(actual, ndarray) or isinstance(desired, ndarray)):
+        msg = build_err_msg([actual, desired], err_msg,)
+        if not desired == actual:
+            raise AssertionError(msg)
+        return
+    # Case #4. arrays or equivalent
+    if ((actual is masked) and not (desired is masked)) or \
+            ((desired is masked) and not (actual is masked)):
+        msg = build_err_msg([actual, desired],
+                            err_msg, header='', names=('x', 'y'))
+        raise ValueError(msg)
+    actual = np.asanyarray(actual)
+    desired = np.asanyarray(desired)
+    (actual_dtype, desired_dtype) = (actual.dtype, desired.dtype)
+    if actual_dtype.char == "S" and desired_dtype.char == "S":
+        return _assert_equal_on_sequences(actual.tolist(),
+                                          desired.tolist(),
+                                          err_msg='')
+    return assert_array_equal(actual, desired, err_msg)
+
+
+def fail_if_equal(actual, desired, err_msg='',):
+    """
+    Raises an assertion error if two items are equal.
+
+    """
+    if isinstance(desired, dict):
+        if not isinstance(actual, dict):
+            raise AssertionError(repr(type(actual)))
+        fail_if_equal(len(actual), len(desired), err_msg)
+        for k, i in desired.items():
+            if k not in actual:
+                raise AssertionError(repr(k))
+            fail_if_equal(actual[k], desired[k], f'key={k!r}\n{err_msg}')
+        return
+    if isinstance(desired, (list, tuple)) and isinstance(actual, (list, tuple)):
+        fail_if_equal(len(actual), len(desired), err_msg)
+        for k in range(len(desired)):
+            fail_if_equal(actual[k], desired[k], f'item={k!r}\n{err_msg}')
+        return
+    if isinstance(actual, np.ndarray) or isinstance(desired, np.ndarray):
+        return fail_if_array_equal(actual, desired, err_msg)
+    msg = build_err_msg([actual, desired], err_msg)
+    if not desired != actual:
+        raise AssertionError(msg)
+
+
+assert_not_equal = fail_if_equal
+
+
+def assert_almost_equal(actual, desired, decimal=7, err_msg='', verbose=True):
+    """
+    Asserts that two items are almost equal.
+
+    The test is equivalent to abs(desired-actual) < 0.5 * 10**(-decimal).
+
+    """
+    if isinstance(actual, np.ndarray) or isinstance(desired, np.ndarray):
+        return assert_array_almost_equal(actual, desired, decimal=decimal,
+                                         err_msg=err_msg, verbose=verbose)
+    msg = build_err_msg([actual, desired],
+                        err_msg=err_msg, verbose=verbose)
+    if not round(abs(desired - actual), decimal) == 0:
+        raise AssertionError(msg)
+
+
+assert_close = assert_almost_equal
+
+
+def assert_array_compare(comparison, x, y, err_msg='', verbose=True, header='',
+                         fill_value=True):
+    """
+    Asserts that comparison between two masked arrays is satisfied.
+
+    The comparison is elementwise.
+
+    """
+    # Allocate a common mask and refill
+    m = mask_or(getmask(x), getmask(y))
+    x = masked_array(x, copy=False, mask=m, keep_mask=False, subok=False)
+    y = masked_array(y, copy=False, mask=m, keep_mask=False, subok=False)
+    if ((x is masked) and not (y is masked)) or \
+            ((y is masked) and not (x is masked)):
+        msg = build_err_msg([x, y], err_msg=err_msg, verbose=verbose,
+                            header=header, names=('x', 'y'))
+        raise ValueError(msg)
+    # OK, now run the basic tests on filled versions
+    return np.testing.assert_array_compare(comparison,
+                                           x.filled(fill_value),
+                                           y.filled(fill_value),
+                                           err_msg=err_msg,
+                                           verbose=verbose, header=header)
+
+
+def assert_array_equal(x, y, err_msg='', verbose=True):
+    """
+    Checks the elementwise equality of two masked arrays.
+
+    """
+    assert_array_compare(operator.__eq__, x, y,
+                         err_msg=err_msg, verbose=verbose,
+                         header='Arrays are not equal')
+
+
+def fail_if_array_equal(x, y, err_msg='', verbose=True):
+    """
+    Raises an assertion error if two masked arrays are not equal elementwise.
+
+    """
+    def compare(x, y):
+        return (not np.all(approx(x, y)))
+    assert_array_compare(compare, x, y, err_msg=err_msg, verbose=verbose,
+                         header='Arrays are not equal')
+
+
+def assert_array_approx_equal(x, y, decimal=6, err_msg='', verbose=True):
+    """
+    Checks the equality of two masked arrays, up to given number odecimals.
+
+    The equality is checked elementwise.
+
+    """
+    def compare(x, y):
+        "Returns the result of the loose comparison between x and y)."
+        return approx(x, y, rtol=10. ** -decimal)
+    assert_array_compare(compare, x, y, err_msg=err_msg, verbose=verbose,
+                         header='Arrays are not almost equal')
+
+
+def assert_array_almost_equal(x, y, decimal=6, err_msg='', verbose=True):
+    """
+    Checks the equality of two masked arrays, up to given number odecimals.
+
+    The equality is checked elementwise.
+
+    """
+    def compare(x, y):
+        "Returns the result of the loose comparison between x and y)."
+        return almost(x, y, decimal)
+    assert_array_compare(compare, x, y, err_msg=err_msg, verbose=verbose,
+                         header='Arrays are not almost equal')
+
+
+def assert_array_less(x, y, err_msg='', verbose=True):
+    """
+    Checks that x is smaller than y elementwise.
+
+    """
+    assert_array_compare(operator.__lt__, x, y,
+                         err_msg=err_msg, verbose=verbose,
+                         header='Arrays are not less-ordered')
+
+
+def assert_mask_equal(m1, m2, err_msg=''):
+    """
+    Asserts the equality of two masks.
+
+    """
+    if m1 is nomask:
+        assert_(m2 is nomask)
+    if m2 is nomask:
+        assert_(m1 is nomask)
+    assert_array_equal(m1, m2, err_msg=err_msg)
diff --git a/venv/lib/python3.10/site-packages/numpy/ma/timer_comparison.py b/venv/lib/python3.10/site-packages/numpy/ma/timer_comparison.py
new file mode 100644
index 0000000000000000000000000000000000000000..9eb1a23cd693b7f9176f4076c26c47caee3ce94c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/numpy/ma/timer_comparison.py
@@ -0,0 +1,443 @@
+import timeit
+from functools import reduce
+
+import numpy as np
+from numpy import float_
+import numpy.core.fromnumeric as fromnumeric
+
+from numpy.testing import build_err_msg
+
+
+pi = np.pi
+
+class ModuleTester:
+    def __init__(self, module):
+        self.module = module
+        self.allequal = module.allequal
+        self.arange = module.arange
+        self.array = module.array
+        self.concatenate = module.concatenate
+        self.count = module.count
+        self.equal = module.equal
+        self.filled = module.filled
+        self.getmask = module.getmask
+        self.getmaskarray = module.getmaskarray
+        self.id = id
+        self.inner = module.inner
+        self.make_mask = module.make_mask
+        self.masked = module.masked
+        self.masked_array = module.masked_array
+        self.masked_values = module.masked_values
+        self.mask_or = module.mask_or
+        self.nomask = module.nomask
+        self.ones = module.ones
+        self.outer = module.outer
+        self.repeat = module.repeat
+        self.resize = module.resize
+        self.sort = module.sort
+        self.take = module.take
+        self.transpose = module.transpose
+        self.zeros = module.zeros
+        self.MaskType = module.MaskType
+        try:
+            self.umath = module.umath
+        except AttributeError:
+            self.umath = module.core.umath
+        self.testnames = []
+
+    def assert_array_compare(self, comparison, x, y, err_msg='', header='',
+                         fill_value=True):
+        """
+        Assert that a comparison of two masked arrays is satisfied elementwise.
+
+        """
+        xf = self.filled(x)
+        yf = self.filled(y)
+        m = self.mask_or(self.getmask(x), self.getmask(y))
+
+        x = self.filled(self.masked_array(xf, mask=m), fill_value)
+        y = self.filled(self.masked_array(yf, mask=m), fill_value)
+        if (x.dtype.char != "O"):
+            x = x.astype(float_)
+            if isinstance(x, np.ndarray) and x.size > 1:
+                x[np.isnan(x)] = 0
+            elif np.isnan(x):
+                x = 0
+        if (y.dtype.char != "O"):
+            y = y.astype(float_)
+            if isinstance(y, np.ndarray) and y.size > 1:
+                y[np.isnan(y)] = 0
+            elif np.isnan(y):
+                y = 0
+        try:
+            cond = (x.shape == () or y.shape == ()) or x.shape == y.shape
+            if not cond:
+                msg = build_err_msg([x, y],
+                                    err_msg
+                                    + f'\n(shapes {x.shape}, {y.shape} mismatch)',
+                                    header=header,
+                                    names=('x', 'y'))
+                assert cond, msg
+            val = comparison(x, y)
+            if m is not self.nomask and fill_value:
+                val = self.masked_array(val, mask=m)
+            if isinstance(val, bool):
+                cond = val
+                reduced = [0]
+            else:
+                reduced = val.ravel()
+                cond = reduced.all()
+                reduced = reduced.tolist()
+            if not cond:
+                match = 100-100.0*reduced.count(1)/len(reduced)
+                msg = build_err_msg([x, y],
+                                    err_msg
+                                    + '\n(mismatch %s%%)' % (match,),
+                                    header=header,
+                                    names=('x', 'y'))
+                assert cond, msg
+        except ValueError as e:
+            msg = build_err_msg([x, y], err_msg, header=header, names=('x', 'y'))
+            raise ValueError(msg) from e
+
+    def assert_array_equal(self, x, y, err_msg=''):
+        """
+        Checks the elementwise equality of two masked arrays.
+
+        """
+        self.assert_array_compare(self.equal, x, y, err_msg=err_msg,
+                                  header='Arrays are not equal')
+
+    @np.errstate(all='ignore')
+    def test_0(self):
+        """
+        Tests creation
+
+        """
+        x = np.array([1., 1., 1., -2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.])
+        m = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
+        xm = self.masked_array(x, mask=m)
+        xm[0]
+
+    @np.errstate(all='ignore')
+    def test_1(self):
+        """
+        Tests creation
+
+        """
+        x = np.array([1., 1., 1., -2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.])
+        y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.])
+        m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
+        m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1]
+        xm = self.masked_array(x, mask=m1)
+        ym = self.masked_array(y, mask=m2)
+        xf = np.where(m1, 1.e+20, x)
+        xm.set_fill_value(1.e+20)
+
+        assert((xm-ym).filled(0).any())
+        s = x.shape
+        assert(xm.size == reduce(lambda x, y:x*y, s))
+        assert(self.count(xm) == len(m1) - reduce(lambda x, y:x+y, m1))
+
+        for s in [(4, 3), (6, 2)]:
+            x.shape = s
+            y.shape = s
+            xm.shape = s
+            ym.shape = s
+            xf.shape = s
+            assert(self.count(xm) == len(m1) - reduce(lambda x, y:x+y, m1))
+
+    @np.errstate(all='ignore')
+    def test_2(self):
+        """
+        Tests conversions and indexing.
+
+        """
+        x1 = np.array([1, 2, 4, 3])
+        x2 = self.array(x1, mask=[1, 0, 0, 0])
+        x3 = self.array(x1, mask=[0, 1, 0, 1])
+        x4 = self.array(x1)
+        # test conversion to strings, no errors
+        str(x2)
+        repr(x2)
+        # tests of indexing
+        assert type(x2[1]) is type(x1[1])
+        assert x1[1] == x2[1]
+        x1[2] = 9
+        x2[2] = 9
+        self.assert_array_equal(x1, x2)
+        x1[1:3] = 99
+        x2[1:3] = 99
+        x2[1] = self.masked
+        x2[1:3] = self.masked
+        x2[:] = x1
+        x2[1] = self.masked
+        x3[:] = self.masked_array([1, 2, 3, 4], [0, 1, 1, 0])
+        x4[:] = self.masked_array([1, 2, 3, 4], [0, 1, 1, 0])
+        x1 = np.arange(5)*1.0
+        x2 = self.masked_values(x1, 3.0)
+        x1 = self.array([1, 'hello', 2, 3], object)
+        x2 = np.array([1, 'hello', 2, 3], object)
+        # check that no error occurs.
+        x1[1]
+        x2[1]
+        assert x1[1:1].shape == (0,)
+        # Tests copy-size
+        n = [0, 0, 1, 0, 0]
+        m = self.make_mask(n)
+        m2 = self.make_mask(m)
+        assert(m is m2)
+        m3 = self.make_mask(m, copy=1)
+        assert(m is not m3)
+
+    @np.errstate(all='ignore')
+    def test_3(self):
+        """
+        Tests resize/repeat
+
+        """
+        x4 = self.arange(4)
+        x4[2] = self.masked
+        y4 = self.resize(x4, (8,))
+        assert self.allequal(self.concatenate([x4, x4]), y4)
+        assert self.allequal(self.getmask(y4), [0, 0, 1, 0, 0, 0, 1, 0])
+        y5 = self.repeat(x4, (2, 2, 2, 2), axis=0)
+        self.assert_array_equal(y5, [0, 0, 1, 1, 2, 2, 3, 3])
+        y6 = self.repeat(x4, 2, axis=0)
+        assert self.allequal(y5, y6)
+        y7 = x4.repeat((2, 2, 2, 2), axis=0)
+        assert self.allequal(y5, y7)
+        y8 = x4.repeat(2, 0)
+        assert self.allequal(y5, y8)
+
+    @np.errstate(all='ignore')
+    def test_4(self):
+        """
+        Test of take, transpose, inner, outer products.
+
+        """
+        x = self.arange(24)
+        y = np.arange(24)
+        x[5:6] = self.masked
+        x = x.reshape(2, 3, 4)
+        y = y.reshape(2, 3, 4)
+        assert self.allequal(np.transpose(y, (2, 0, 1)), self.transpose(x, (2, 0, 1)))
+        assert self.allequal(np.take(y, (2, 0, 1), 1), self.take(x, (2, 0, 1), 1))
+        assert self.allequal(np.inner(self.filled(x, 0), self.filled(y, 0)),
+                            self.inner(x, y))
+        assert self.allequal(np.outer(self.filled(x, 0), self.filled(y, 0)),
+                            self.outer(x, y))
+        y = self.array(['abc', 1, 'def', 2, 3], object)
+        y[2] = self.masked
+        t = self.take(y, [0, 3, 4])
+        assert t[0] == 'abc'
+        assert t[1] == 2
+        assert t[2] == 3
+
+    @np.errstate(all='ignore')
+    def test_5(self):
+        """
+        Tests inplace w/ scalar
+
+        """
+        x = self.arange(10)
+        y = self.arange(10)
+        xm = self.arange(10)
+        xm[2] = self.masked
+        x += 1
+        assert self.allequal(x, y+1)
+        xm += 1
+        assert self.allequal(xm, y+1)
+
+        x = self.arange(10)
+        xm = self.arange(10)
+        xm[2] = self.masked
+        x -= 1
+        assert self.allequal(x, y-1)
+        xm -= 1
+        assert self.allequal(xm, y-1)
+
+        x = self.arange(10)*1.0
+        xm = self.arange(10)*1.0
+        xm[2] = self.masked
+        x *= 2.0
+        assert self.allequal(x, y*2)
+        xm *= 2.0
+        assert self.allequal(xm, y*2)
+
+        x = self.arange(10)*2
+        xm = self.arange(10)*2
+        xm[2] = self.masked
+        x /= 2
+        assert self.allequal(x, y)
+        xm /= 2
+        assert self.allequal(xm, y)
+
+        x = self.arange(10)*1.0
+        xm = self.arange(10)*1.0
+        xm[2] = self.masked
+        x /= 2.0
+        assert self.allequal(x, y/2.0)
+        xm /= self.arange(10)
+        self.assert_array_equal(xm, self.ones((10,)))
+
+        x = self.arange(10).astype(float_)
+        xm = self.arange(10)
+        xm[2] = self.masked
+        x += 1.
+        assert self.allequal(x, y + 1.)
+
+    @np.errstate(all='ignore')
+    def test_6(self):
+        """
+        Tests inplace w/ array
+
+        """
+        x = self.arange(10, dtype=float_)
+        y = self.arange(10)
+        xm = self.arange(10, dtype=float_)
+        xm[2] = self.masked
+        m = xm.mask
+        a = self.arange(10, dtype=float_)
+        a[-1] = self.masked
+        x += a
+        xm += a
+        assert self.allequal(x, y+a)
+        assert self.allequal(xm, y+a)
+        assert self.allequal(xm.mask, self.mask_or(m, a.mask))
+
+        x = self.arange(10, dtype=float_)
+        xm = self.arange(10, dtype=float_)
+        xm[2] = self.masked
+        m = xm.mask
+        a = self.arange(10, dtype=float_)
+        a[-1] = self.masked
+        x -= a
+        xm -= a
+        assert self.allequal(x, y-a)
+        assert self.allequal(xm, y-a)
+        assert self.allequal(xm.mask, self.mask_or(m, a.mask))
+
+        x = self.arange(10, dtype=float_)
+        xm = self.arange(10, dtype=float_)
+        xm[2] = self.masked
+        m = xm.mask
+        a = self.arange(10, dtype=float_)
+        a[-1] = self.masked
+        x *= a
+        xm *= a
+        assert self.allequal(x, y*a)
+        assert self.allequal(xm, y*a)
+        assert self.allequal(xm.mask, self.mask_or(m, a.mask))
+
+        x = self.arange(10, dtype=float_)
+        xm = self.arange(10, dtype=float_)
+        xm[2] = self.masked
+        m = xm.mask
+        a = self.arange(10, dtype=float_)
+        a[-1] = self.masked
+        x /= a
+        xm /= a
+
+    @np.errstate(all='ignore')
+    def test_7(self):
+        "Tests ufunc"
+        d = (self.array([1.0, 0, -1, pi/2]*2, mask=[0, 1]+[0]*6),
+             self.array([1.0, 0, -1, pi/2]*2, mask=[1, 0]+[0]*6),)
+        for f in ['sqrt', 'log', 'log10', 'exp', 'conjugate',
+#                  'sin', 'cos', 'tan',
+#                  'arcsin', 'arccos', 'arctan',
+#                  'sinh', 'cosh', 'tanh',
+#                  'arcsinh',
+#                  'arccosh',
+#                  'arctanh',
+#                  'absolute', 'fabs', 'negative',
+#                  # 'nonzero', 'around',
+#                  'floor', 'ceil',
+#                  # 'sometrue', 'alltrue',
+#                  'logical_not',
+#                  'add', 'subtract', 'multiply',
+#                  'divide', 'true_divide', 'floor_divide',
+#                  'remainder', 'fmod', 'hypot', 'arctan2',
+#                  'equal', 'not_equal', 'less_equal', 'greater_equal',
+#                  'less', 'greater',
+#                  'logical_and', 'logical_or', 'logical_xor',
+                  ]:
+            try:
+                uf = getattr(self.umath, f)
+            except AttributeError:
+                uf = getattr(fromnumeric, f)
+            mf = getattr(self.module, f)
+            args = d[:uf.nin]
+            ur = uf(*args)
+            mr = mf(*args)
+            self.assert_array_equal(ur.filled(0), mr.filled(0), f)
+            self.assert_array_equal(ur._mask, mr._mask)
+
+    @np.errstate(all='ignore')
+    def test_99(self):
+        # test average
+        ott = self.array([0., 1., 2., 3.], mask=[1, 0, 0, 0])
+        self.assert_array_equal(2.0, self.average(ott, axis=0))
+        self.assert_array_equal(2.0, self.average(ott, weights=[1., 1., 2., 1.]))
+        result, wts = self.average(ott, weights=[1., 1., 2., 1.], returned=1)
+        self.assert_array_equal(2.0, result)
+        assert(wts == 4.0)
+        ott[:] = self.masked
+        assert(self.average(ott, axis=0) is self.masked)
+        ott = self.array([0., 1., 2., 3.], mask=[1, 0, 0, 0])
+        ott = ott.reshape(2, 2)
+        ott[:, 1] = self.masked
+        self.assert_array_equal(self.average(ott, axis=0), [2.0, 0.0])
+        assert(self.average(ott, axis=1)[0] is self.masked)
+        self.assert_array_equal([2., 0.], self.average(ott, axis=0))
+        result, wts = self.average(ott, axis=0, returned=1)
+        self.assert_array_equal(wts, [1., 0.])
+        w1 = [0, 1, 1, 1, 1, 0]
+        w2 = [[0, 1, 1, 1, 1, 0], [1, 0, 0, 0, 0, 1]]
+        x = self.arange(6)
+        self.assert_array_equal(self.average(x, axis=0), 2.5)
+        self.assert_array_equal(self.average(x, axis=0, weights=w1), 2.5)
+        y = self.array([self.arange(6), 2.0*self.arange(6)])
+        self.assert_array_equal(self.average(y, None), np.add.reduce(np.arange(6))*3./12.)
+        self.assert_array_equal(self.average(y, axis=0), np.arange(6) * 3./2.)
+        self.assert_array_equal(self.average(y, axis=1), [self.average(x, axis=0), self.average(x, axis=0) * 2.0])
+        self.assert_array_equal(self.average(y, None, weights=w2), 20./6.)
+        self.assert_array_equal(self.average(y, axis=0, weights=w2), [0., 1., 2., 3., 4., 10.])
+        self.assert_array_equal(self.average(y, axis=1), [self.average(x, axis=0), self.average(x, axis=0) * 2.0])
+        m1 = self.zeros(6)
+        m2 = [0, 0, 1, 1, 0, 0]
+        m3 = [[0, 0, 1, 1, 0, 0], [0, 1, 1, 1, 1, 0]]
+        m4 = self.ones(6)
+        m5 = [0, 1, 1, 1, 1, 1]
+        self.assert_array_equal(self.average(self.masked_array(x, m1), axis=0), 2.5)
+        self.assert_array_equal(self.average(self.masked_array(x, m2), axis=0), 2.5)
+        self.assert_array_equal(self.average(self.masked_array(x, m5), axis=0), 0.0)
+        self.assert_array_equal(self.count(self.average(self.masked_array(x, m4), axis=0)), 0)
+        z = self.masked_array(y, m3)
+        self.assert_array_equal(self.average(z, None), 20./6.)
+        self.assert_array_equal(self.average(z, axis=0), [0., 1., 99., 99., 4.0, 7.5])
+        self.assert_array_equal(self.average(z, axis=1), [2.5, 5.0])
+        self.assert_array_equal(self.average(z, axis=0, weights=w2), [0., 1., 99., 99., 4.0, 10.0])
+
+    @np.errstate(all='ignore')
+    def test_A(self):
+        x = self.arange(24)
+        x[5:6] = self.masked
+        x = x.reshape(2, 3, 4)
+
+
+if __name__ == '__main__':
+    setup_base = ("from __main__ import ModuleTester \n"
+                  "import numpy\n"
+                  "tester = ModuleTester(module)\n")
+    setup_cur = "import numpy.ma.core as module\n" + setup_base
+    (nrepeat, nloop) = (10, 10)
+
+    for i in range(1, 8):
+        func = 'tester.test_%i()' % i
+        cur = timeit.Timer(func, setup_cur).repeat(nrepeat, nloop*10)
+        cur = np.sort(cur)
+        print("#%i" % i + 50*'.')
+        print(eval("ModuleTester.test_%i.__doc__" % i))
+        print(f'core_current : {cur[0]:.3f} - {cur[1]:.3f}')
diff --git a/venv/lib/python3.10/site-packages/numpy/matrixlib/__pycache__/setup.cpython-310.pyc b/venv/lib/python3.10/site-packages/numpy/matrixlib/__pycache__/setup.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4d918beaa3f54cf6aeb595f5ddfbe643fa698f47
Binary files /dev/null and b/venv/lib/python3.10/site-packages/numpy/matrixlib/__pycache__/setup.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/numpy/matrixlib/tests/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/numpy/matrixlib/tests/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eee88fd281e36c5bae349e0982e52af55e7c18d8
Binary files /dev/null and b/venv/lib/python3.10/site-packages/numpy/matrixlib/tests/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/numpy/matrixlib/tests/__pycache__/test_defmatrix.cpython-310.pyc b/venv/lib/python3.10/site-packages/numpy/matrixlib/tests/__pycache__/test_defmatrix.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..32c98431ff3d029f894185366a86bd67a8add87d
Binary files /dev/null and b/venv/lib/python3.10/site-packages/numpy/matrixlib/tests/__pycache__/test_defmatrix.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/numpy/matrixlib/tests/__pycache__/test_interaction.cpython-310.pyc b/venv/lib/python3.10/site-packages/numpy/matrixlib/tests/__pycache__/test_interaction.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5a535398404dd15d14d8818e22f2f595e0f994a1
Binary files /dev/null and b/venv/lib/python3.10/site-packages/numpy/matrixlib/tests/__pycache__/test_interaction.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/numpy/matrixlib/tests/__pycache__/test_masked_matrix.cpython-310.pyc b/venv/lib/python3.10/site-packages/numpy/matrixlib/tests/__pycache__/test_masked_matrix.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3deda2f42e0244b16b91f33155bab43f996b205c
Binary files /dev/null and b/venv/lib/python3.10/site-packages/numpy/matrixlib/tests/__pycache__/test_masked_matrix.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/numpy/matrixlib/tests/__pycache__/test_matrix_linalg.cpython-310.pyc b/venv/lib/python3.10/site-packages/numpy/matrixlib/tests/__pycache__/test_matrix_linalg.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eb4c11d3e5d0621cf06e260616cc0ef4ed4eb268
Binary files /dev/null and b/venv/lib/python3.10/site-packages/numpy/matrixlib/tests/__pycache__/test_matrix_linalg.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/numpy/matrixlib/tests/__pycache__/test_multiarray.cpython-310.pyc b/venv/lib/python3.10/site-packages/numpy/matrixlib/tests/__pycache__/test_multiarray.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..23da1d5cb50d89aac0d06189181d960c6eb6b43e
Binary files /dev/null and b/venv/lib/python3.10/site-packages/numpy/matrixlib/tests/__pycache__/test_multiarray.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/numpy/matrixlib/tests/__pycache__/test_numeric.cpython-310.pyc b/venv/lib/python3.10/site-packages/numpy/matrixlib/tests/__pycache__/test_numeric.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..88a623adb0d84273faa96d74489e3f7a4f1d8209
Binary files /dev/null and b/venv/lib/python3.10/site-packages/numpy/matrixlib/tests/__pycache__/test_numeric.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/numpy/matrixlib/tests/__pycache__/test_regression.cpython-310.pyc b/venv/lib/python3.10/site-packages/numpy/matrixlib/tests/__pycache__/test_regression.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4b28042c41b4c8f990025474c714de2dd6a314f4
Binary files /dev/null and b/venv/lib/python3.10/site-packages/numpy/matrixlib/tests/__pycache__/test_regression.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/numpy/matrixlib/tests/test_masked_matrix.py b/venv/lib/python3.10/site-packages/numpy/matrixlib/tests/test_masked_matrix.py
new file mode 100644
index 0000000000000000000000000000000000000000..d0ce357aef2765ad72cd3a5f4d0ed48fc07463c1
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/numpy/matrixlib/tests/test_masked_matrix.py
@@ -0,0 +1,231 @@
+import numpy as np
+from numpy.testing import assert_warns
+from numpy.ma.testutils import (assert_, assert_equal, assert_raises,
+                                assert_array_equal)
+from numpy.ma.core import (masked_array, masked_values, masked, allequal,
+                           MaskType, getmask, MaskedArray, nomask,
+                           log, add, hypot, divide)
+from numpy.ma.extras import mr_
+from numpy.compat import pickle
+
+
+class MMatrix(MaskedArray, np.matrix,):
+
+    def __new__(cls, data, mask=nomask):
+        mat = np.matrix(data)
+        _data = MaskedArray.__new__(cls, data=mat, mask=mask)
+        return _data
+
+    def __array_finalize__(self, obj):
+        np.matrix.__array_finalize__(self, obj)
+        MaskedArray.__array_finalize__(self, obj)
+        return
+
+    @property
+    def _series(self):
+        _view = self.view(MaskedArray)
+        _view._sharedmask = False
+        return _view
+
+
+class TestMaskedMatrix:
+    def test_matrix_indexing(self):
+        # Tests conversions and indexing
+        x1 = np.matrix([[1, 2, 3], [4, 3, 2]])
+        x2 = masked_array(x1, mask=[[1, 0, 0], [0, 1, 0]])
+        x3 = masked_array(x1, mask=[[0, 1, 0], [1, 0, 0]])
+        x4 = masked_array(x1)
+        # test conversion to strings
+        str(x2)  # raises?
+        repr(x2)  # raises?
+        # tests of indexing
+        assert_(type(x2[1, 0]) is type(x1[1, 0]))
+        assert_(x1[1, 0] == x2[1, 0])
+        assert_(x2[1, 1] is masked)
+        assert_equal(x1[0, 2], x2[0, 2])
+        assert_equal(x1[0, 1:], x2[0, 1:])
+        assert_equal(x1[:, 2], x2[:, 2])
+        assert_equal(x1[:], x2[:])
+        assert_equal(x1[1:], x3[1:])
+        x1[0, 2] = 9
+        x2[0, 2] = 9
+        assert_equal(x1, x2)
+        x1[0, 1:] = 99
+        x2[0, 1:] = 99
+        assert_equal(x1, x2)
+        x2[0, 1] = masked
+        assert_equal(x1, x2)
+        x2[0, 1:] = masked
+        assert_equal(x1, x2)
+        x2[0, :] = x1[0, :]
+        x2[0, 1] = masked
+        assert_(allequal(getmask(x2), np.array([[0, 1, 0], [0, 1, 0]])))
+        x3[1, :] = masked_array([1, 2, 3], [1, 1, 0])
+        assert_(allequal(getmask(x3)[1], masked_array([1, 1, 0])))
+        assert_(allequal(getmask(x3[1]), masked_array([1, 1, 0])))
+        x4[1, :] = masked_array([1, 2, 3], [1, 1, 0])
+        assert_(allequal(getmask(x4[1]), masked_array([1, 1, 0])))
+        assert_(allequal(x4[1], masked_array([1, 2, 3])))
+        x1 = np.matrix(np.arange(5) * 1.0)
+        x2 = masked_values(x1, 3.0)
+        assert_equal(x1, x2)
+        assert_(allequal(masked_array([0, 0, 0, 1, 0], dtype=MaskType),
+                         x2.mask))
+        assert_equal(3.0, x2.fill_value)
+
+    def test_pickling_subbaseclass(self):
+        # Test pickling w/ a subclass of ndarray
+        a = masked_array(np.matrix(list(range(10))), mask=[1, 0, 1, 0, 0] * 2)
+        for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
+            a_pickled = pickle.loads(pickle.dumps(a, protocol=proto))
+            assert_equal(a_pickled._mask, a._mask)
+            assert_equal(a_pickled, a)
+            assert_(isinstance(a_pickled._data, np.matrix))
+
+    def test_count_mean_with_matrix(self):
+        m = masked_array(np.matrix([[1, 2], [3, 4]]), mask=np.zeros((2, 2)))
+
+        assert_equal(m.count(axis=0).shape, (1, 2))
+        assert_equal(m.count(axis=1).shape, (2, 1))
+
+        # Make sure broadcasting inside mean and var work
+        assert_equal(m.mean(axis=0), [[2., 3.]])
+        assert_equal(m.mean(axis=1), [[1.5], [3.5]])
+
+    def test_flat(self):
+        # Test that flat can return items even for matrices [#4585, #4615]
+        # test simple access
+        test = masked_array(np.matrix([[1, 2, 3]]), mask=[0, 0, 1])
+        assert_equal(test.flat[1], 2)
+        assert_equal(test.flat[2], masked)
+        assert_(np.all(test.flat[0:2] == test[0, 0:2]))
+        # Test flat on masked_matrices
+        test = masked_array(np.matrix([[1, 2, 3]]), mask=[0, 0, 1])
+        test.flat = masked_array([3, 2, 1], mask=[1, 0, 0])
+        control = masked_array(np.matrix([[3, 2, 1]]), mask=[1, 0, 0])
+        assert_equal(test, control)
+        # Test setting
+        test = masked_array(np.matrix([[1, 2, 3]]), mask=[0, 0, 1])
+        testflat = test.flat
+        testflat[:] = testflat[[2, 1, 0]]
+        assert_equal(test, control)
+        testflat[0] = 9
+        # test that matrices keep the correct shape (#4615)
+        a = masked_array(np.matrix(np.eye(2)), mask=0)
+        b = a.flat
+        b01 = b[:2]
+        assert_equal(b01.data, np.array([[1., 0.]]))
+        assert_equal(b01.mask, np.array([[False, False]]))
+
+    def test_allany_onmatrices(self):
+        x = np.array([[0.13, 0.26, 0.90],
+                      [0.28, 0.33, 0.63],
+                      [0.31, 0.87, 0.70]])
+        X = np.matrix(x)
+        m = np.array([[True, False, False],
+                      [False, False, False],
+                      [True, True, False]], dtype=np.bool_)
+        mX = masked_array(X, mask=m)
+        mXbig = (mX > 0.5)
+        mXsmall = (mX < 0.5)
+
+        assert_(not mXbig.all())
+        assert_(mXbig.any())
+        assert_equal(mXbig.all(0), np.matrix([False, False, True]))
+        assert_equal(mXbig.all(1), np.matrix([False, False, True]).T)
+        assert_equal(mXbig.any(0), np.matrix([False, False, True]))
+        assert_equal(mXbig.any(1), np.matrix([True, True, True]).T)
+
+        assert_(not mXsmall.all())
+        assert_(mXsmall.any())
+        assert_equal(mXsmall.all(0), np.matrix([True, True, False]))
+        assert_equal(mXsmall.all(1), np.matrix([False, False, False]).T)
+        assert_equal(mXsmall.any(0), np.matrix([True, True, False]))
+        assert_equal(mXsmall.any(1), np.matrix([True, True, False]).T)
+
+    def test_compressed(self):
+        a = masked_array(np.matrix([1, 2, 3, 4]), mask=[0, 0, 0, 0])
+        b = a.compressed()
+        assert_equal(b, a)
+        assert_(isinstance(b, np.matrix))
+        a[0, 0] = masked
+        b = a.compressed()
+        assert_equal(b, [[2, 3, 4]])
+
+    def test_ravel(self):
+        a = masked_array(np.matrix([1, 2, 3, 4, 5]), mask=[[0, 1, 0, 0, 0]])
+        aravel = a.ravel()
+        assert_equal(aravel.shape, (1, 5))
+        assert_equal(aravel._mask.shape, a.shape)
+
+    def test_view(self):
+        # Test view w/ flexible dtype
+        iterator = list(zip(np.arange(10), np.random.rand(10)))
+        data = np.array(iterator)
+        a = masked_array(iterator, dtype=[('a', float), ('b', float)])
+        a.mask[0] = (1, 0)
+        test = a.view((float, 2), np.matrix)
+        assert_equal(test, data)
+        assert_(isinstance(test, np.matrix))
+        assert_(not isinstance(test, MaskedArray))
+
+
+class TestSubclassing:
+    # Test suite for masked subclasses of ndarray.
+
+    def setup_method(self):
+        x = np.arange(5, dtype='float')
+        mx = MMatrix(x, mask=[0, 1, 0, 0, 0])
+        self.data = (x, mx)
+
+    def test_maskedarray_subclassing(self):
+        # Tests subclassing MaskedArray
+        (x, mx) = self.data
+        assert_(isinstance(mx._data, np.matrix))
+
+    def test_masked_unary_operations(self):
+        # Tests masked_unary_operation
+        (x, mx) = self.data
+        with np.errstate(divide='ignore'):
+            assert_(isinstance(log(mx), MMatrix))
+            assert_equal(log(x), np.log(x))
+
+    def test_masked_binary_operations(self):
+        # Tests masked_binary_operation
+        (x, mx) = self.data
+        # Result should be a MMatrix
+        assert_(isinstance(add(mx, mx), MMatrix))
+        assert_(isinstance(add(mx, x), MMatrix))
+        # Result should work
+        assert_equal(add(mx, x), mx+x)
+        assert_(isinstance(add(mx, mx)._data, np.matrix))
+        with assert_warns(DeprecationWarning):
+            assert_(isinstance(add.outer(mx, mx), MMatrix))
+        assert_(isinstance(hypot(mx, mx), MMatrix))
+        assert_(isinstance(hypot(mx, x), MMatrix))
+
+    def test_masked_binary_operations2(self):
+        # Tests domained_masked_binary_operation
+        (x, mx) = self.data
+        xmx = masked_array(mx.data.__array__(), mask=mx.mask)
+        assert_(isinstance(divide(mx, mx), MMatrix))
+        assert_(isinstance(divide(mx, x), MMatrix))
+        assert_equal(divide(mx, mx), divide(xmx, xmx))
+
+class TestConcatenator:
+    # Tests for mr_, the equivalent of r_ for masked arrays.
+
+    def test_matrix_builder(self):
+        assert_raises(np.ma.MAError, lambda: mr_['1, 2; 3, 4'])
+
+    def test_matrix(self):
+        # Test consistency with unmasked version.  If we ever deprecate
+        # matrix, this test should either still pass, or both actual and
+        # expected should fail to be build.
+        actual = mr_['r', 1, 2, 3]
+        expected = np.ma.array(np.r_['r', 1, 2, 3])
+        assert_array_equal(actual, expected)
+
+        # outer type is masked array, inner type is matrix
+        assert_equal(type(actual), type(expected))
+        assert_equal(type(actual.data), type(expected.data))
diff --git a/venv/lib/python3.10/site-packages/numpy/random/tests/__init__.py b/venv/lib/python3.10/site-packages/numpy/random/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/venv/lib/python3.10/site-packages/numpy/random/tests/test_direct.py b/venv/lib/python3.10/site-packages/numpy/random/tests/test_direct.py
new file mode 100644
index 0000000000000000000000000000000000000000..fa2ae866beeb7c36a585eaf9eb04df31a2f2a6c3
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/numpy/random/tests/test_direct.py
@@ -0,0 +1,518 @@
+import os
+from os.path import join
+import sys
+
+import numpy as np
+from numpy.testing import (assert_equal, assert_allclose, assert_array_equal,
+                           assert_raises)
+import pytest
+
+from numpy.random import (
+    Generator, MT19937, PCG64, PCG64DXSM, Philox, RandomState, SeedSequence,
+    SFC64, default_rng
+)
+from numpy.random._common import interface
+
+try:
+    import cffi  # noqa: F401
+
+    MISSING_CFFI = False
+except ImportError:
+    MISSING_CFFI = True
+
+try:
+    import ctypes  # noqa: F401
+
+    MISSING_CTYPES = False
+except ImportError:
+    MISSING_CTYPES = False
+
+if sys.flags.optimize > 1:
+    # no docstrings present to inspect when PYTHONOPTIMIZE/Py_OptimizeFlag > 1
+    # cffi cannot succeed
+    MISSING_CFFI = True
+
+
+pwd = os.path.dirname(os.path.abspath(__file__))
+
+
+def assert_state_equal(actual, target):
+    for key in actual:
+        if isinstance(actual[key], dict):
+            assert_state_equal(actual[key], target[key])
+        elif isinstance(actual[key], np.ndarray):
+            assert_array_equal(actual[key], target[key])
+        else:
+            assert actual[key] == target[key]
+
+
+def uint32_to_float32(u):
+    return ((u >> np.uint32(8)) * (1.0 / 2**24)).astype(np.float32)
+
+
+def uniform32_from_uint64(x):
+    x = np.uint64(x)
+    upper = np.array(x >> np.uint64(32), dtype=np.uint32)
+    lower = np.uint64(0xffffffff)
+    lower = np.array(x & lower, dtype=np.uint32)
+    joined = np.column_stack([lower, upper]).ravel()
+    return uint32_to_float32(joined)
+
+
+def uniform32_from_uint53(x):
+    x = np.uint64(x) >> np.uint64(16)
+    x = np.uint32(x & np.uint64(0xffffffff))
+    return uint32_to_float32(x)
+
+
+def uniform32_from_uint32(x):
+    return uint32_to_float32(x)
+
+
+def uniform32_from_uint(x, bits):
+    if bits == 64:
+        return uniform32_from_uint64(x)
+    elif bits == 53:
+        return uniform32_from_uint53(x)
+    elif bits == 32:
+        return uniform32_from_uint32(x)
+    else:
+        raise NotImplementedError
+
+
+def uniform_from_uint(x, bits):
+    if bits in (64, 63, 53):
+        return uniform_from_uint64(x)
+    elif bits == 32:
+        return uniform_from_uint32(x)
+
+
+def uniform_from_uint64(x):
+    return (x >> np.uint64(11)) * (1.0 / 9007199254740992.0)
+
+
+def uniform_from_uint32(x):
+    out = np.empty(len(x) // 2)
+    for i in range(0, len(x), 2):
+        a = x[i] >> 5
+        b = x[i + 1] >> 6
+        out[i // 2] = (a * 67108864.0 + b) / 9007199254740992.0
+    return out
+
+
+def uniform_from_dsfmt(x):
+    return x.view(np.double) - 1.0
+
+
+def gauss_from_uint(x, n, bits):
+    if bits in (64, 63):
+        doubles = uniform_from_uint64(x)
+    elif bits == 32:
+        doubles = uniform_from_uint32(x)
+    else:  # bits == 'dsfmt'
+        doubles = uniform_from_dsfmt(x)
+    gauss = []
+    loc = 0
+    x1 = x2 = 0.0
+    while len(gauss) < n:
+        r2 = 2
+        while r2 >= 1.0 or r2 == 0.0:
+            x1 = 2.0 * doubles[loc] - 1.0
+            x2 = 2.0 * doubles[loc + 1] - 1.0
+            r2 = x1 * x1 + x2 * x2
+            loc += 2
+
+        f = np.sqrt(-2.0 * np.log(r2) / r2)
+        gauss.append(f * x2)
+        gauss.append(f * x1)
+
+    return gauss[:n]
+
+
+def test_seedsequence():
+    from numpy.random.bit_generator import (ISeedSequence,
+                                            ISpawnableSeedSequence,
+                                            SeedlessSeedSequence)
+
+    s1 = SeedSequence(range(10), spawn_key=(1, 2), pool_size=6)
+    s1.spawn(10)
+    s2 = SeedSequence(**s1.state)
+    assert_equal(s1.state, s2.state)
+    assert_equal(s1.n_children_spawned, s2.n_children_spawned)
+
+    # The interfaces cannot be instantiated themselves.
+    assert_raises(TypeError, ISeedSequence)
+    assert_raises(TypeError, ISpawnableSeedSequence)
+    dummy = SeedlessSeedSequence()
+    assert_raises(NotImplementedError, dummy.generate_state, 10)
+    assert len(dummy.spawn(10)) == 10
+
+
+def test_generator_spawning():
+    """ Test spawning new generators and bit_generators directly.
+    """
+    rng = np.random.default_rng()
+    seq = rng.bit_generator.seed_seq
+    new_ss = seq.spawn(5)
+    expected_keys = [seq.spawn_key + (i,) for i in range(5)]
+    assert [c.spawn_key for c in new_ss] == expected_keys
+
+    new_bgs = rng.bit_generator.spawn(5)
+    expected_keys = [seq.spawn_key + (i,) for i in range(5, 10)]
+    assert [bg.seed_seq.spawn_key for bg in new_bgs] == expected_keys
+
+    new_rngs = rng.spawn(5)
+    expected_keys = [seq.spawn_key + (i,) for i in range(10, 15)]
+    found_keys = [rng.bit_generator.seed_seq.spawn_key for rng in new_rngs]
+    assert found_keys == expected_keys
+
+    # Sanity check that streams are actually different:
+    assert new_rngs[0].uniform() != new_rngs[1].uniform()
+
+
+def test_non_spawnable():
+    from numpy.random.bit_generator import ISeedSequence
+
+    class FakeSeedSequence:
+        def generate_state(self, n_words, dtype=np.uint32):
+            return np.zeros(n_words, dtype=dtype)
+
+    ISeedSequence.register(FakeSeedSequence)
+
+    rng = np.random.default_rng(FakeSeedSequence())
+
+    with pytest.raises(TypeError, match="The underlying SeedSequence"):
+        rng.spawn(5)
+
+    with pytest.raises(TypeError, match="The underlying SeedSequence"):
+        rng.bit_generator.spawn(5)
+
+
+class Base:
+    dtype = np.uint64
+    data2 = data1 = {}
+
+    @classmethod
+    def setup_class(cls):
+        cls.bit_generator = PCG64
+        cls.bits = 64
+        cls.dtype = np.uint64
+        cls.seed_error_type = TypeError
+        cls.invalid_init_types = []
+        cls.invalid_init_values = []
+
+    @classmethod
+    def _read_csv(cls, filename):
+        with open(filename) as csv:
+            seed = csv.readline()
+            seed = seed.split(',')
+            seed = [int(s.strip(), 0) for s in seed[1:]]
+            data = []
+            for line in csv:
+                data.append(int(line.split(',')[-1].strip(), 0))
+            return {'seed': seed, 'data': np.array(data, dtype=cls.dtype)}
+
+    def test_raw(self):
+        bit_generator = self.bit_generator(*self.data1['seed'])
+        uints = bit_generator.random_raw(1000)
+        assert_equal(uints, self.data1['data'])
+
+        bit_generator = self.bit_generator(*self.data1['seed'])
+        uints = bit_generator.random_raw()
+        assert_equal(uints, self.data1['data'][0])
+
+        bit_generator = self.bit_generator(*self.data2['seed'])
+        uints = bit_generator.random_raw(1000)
+        assert_equal(uints, self.data2['data'])
+
+    def test_random_raw(self):
+        bit_generator = self.bit_generator(*self.data1['seed'])
+        uints = bit_generator.random_raw(output=False)
+        assert uints is None
+        uints = bit_generator.random_raw(1000, output=False)
+        assert uints is None
+
+    def test_gauss_inv(self):
+        n = 25
+        rs = RandomState(self.bit_generator(*self.data1['seed']))
+        gauss = rs.standard_normal(n)
+        assert_allclose(gauss,
+                        gauss_from_uint(self.data1['data'], n, self.bits))
+
+        rs = RandomState(self.bit_generator(*self.data2['seed']))
+        gauss = rs.standard_normal(25)
+        assert_allclose(gauss,
+                        gauss_from_uint(self.data2['data'], n, self.bits))
+
+    def test_uniform_double(self):
+        rs = Generator(self.bit_generator(*self.data1['seed']))
+        vals = uniform_from_uint(self.data1['data'], self.bits)
+        uniforms = rs.random(len(vals))
+        assert_allclose(uniforms, vals)
+        assert_equal(uniforms.dtype, np.float64)
+
+        rs = Generator(self.bit_generator(*self.data2['seed']))
+        vals = uniform_from_uint(self.data2['data'], self.bits)
+        uniforms = rs.random(len(vals))
+        assert_allclose(uniforms, vals)
+        assert_equal(uniforms.dtype, np.float64)
+
+    def test_uniform_float(self):
+        rs = Generator(self.bit_generator(*self.data1['seed']))
+        vals = uniform32_from_uint(self.data1['data'], self.bits)
+        uniforms = rs.random(len(vals), dtype=np.float32)
+        assert_allclose(uniforms, vals)
+        assert_equal(uniforms.dtype, np.float32)
+
+        rs = Generator(self.bit_generator(*self.data2['seed']))
+        vals = uniform32_from_uint(self.data2['data'], self.bits)
+        uniforms = rs.random(len(vals), dtype=np.float32)
+        assert_allclose(uniforms, vals)
+        assert_equal(uniforms.dtype, np.float32)
+
+    def test_repr(self):
+        rs = Generator(self.bit_generator(*self.data1['seed']))
+        assert 'Generator' in repr(rs)
+        assert f'{id(rs):#x}'.upper().replace('X', 'x') in repr(rs)
+
+    def test_str(self):
+        rs = Generator(self.bit_generator(*self.data1['seed']))
+        assert 'Generator' in str(rs)
+        assert str(self.bit_generator.__name__) in str(rs)
+        assert f'{id(rs):#x}'.upper().replace('X', 'x') not in str(rs)
+
+    def test_pickle(self):
+        import pickle
+
+        bit_generator = self.bit_generator(*self.data1['seed'])
+        state = bit_generator.state
+        bitgen_pkl = pickle.dumps(bit_generator)
+        reloaded = pickle.loads(bitgen_pkl)
+        reloaded_state = reloaded.state
+        assert_array_equal(Generator(bit_generator).standard_normal(1000),
+                           Generator(reloaded).standard_normal(1000))
+        assert bit_generator is not reloaded
+        assert_state_equal(reloaded_state, state)
+
+        ss = SeedSequence(100)
+        aa = pickle.loads(pickle.dumps(ss))
+        assert_equal(ss.state, aa.state)
+
+    def test_invalid_state_type(self):
+        bit_generator = self.bit_generator(*self.data1['seed'])
+        with pytest.raises(TypeError):
+            bit_generator.state = {'1'}
+
+    def test_invalid_state_value(self):
+        bit_generator = self.bit_generator(*self.data1['seed'])
+        state = bit_generator.state
+        state['bit_generator'] = 'otherBitGenerator'
+        with pytest.raises(ValueError):
+            bit_generator.state = state
+
+    def test_invalid_init_type(self):
+        bit_generator = self.bit_generator
+        for st in self.invalid_init_types:
+            with pytest.raises(TypeError):
+                bit_generator(*st)
+
+    def test_invalid_init_values(self):
+        bit_generator = self.bit_generator
+        for st in self.invalid_init_values:
+            with pytest.raises((ValueError, OverflowError)):
+                bit_generator(*st)
+
+    def test_benchmark(self):
+        bit_generator = self.bit_generator(*self.data1['seed'])
+        bit_generator._benchmark(1)
+        bit_generator._benchmark(1, 'double')
+        with pytest.raises(ValueError):
+            bit_generator._benchmark(1, 'int32')
+
+    @pytest.mark.skipif(MISSING_CFFI, reason='cffi not available')
+    def test_cffi(self):
+        bit_generator = self.bit_generator(*self.data1['seed'])
+        cffi_interface = bit_generator.cffi
+        assert isinstance(cffi_interface, interface)
+        other_cffi_interface = bit_generator.cffi
+        assert other_cffi_interface is cffi_interface
+
+    @pytest.mark.skipif(MISSING_CTYPES, reason='ctypes not available')
+    def test_ctypes(self):
+        bit_generator = self.bit_generator(*self.data1['seed'])
+        ctypes_interface = bit_generator.ctypes
+        assert isinstance(ctypes_interface, interface)
+        other_ctypes_interface = bit_generator.ctypes
+        assert other_ctypes_interface is ctypes_interface
+
+    def test_getstate(self):
+        bit_generator = self.bit_generator(*self.data1['seed'])
+        state = bit_generator.state
+        alt_state = bit_generator.__getstate__()
+        assert_state_equal(state, alt_state)
+
+
+class TestPhilox(Base):
+    @classmethod
+    def setup_class(cls):
+        cls.bit_generator = Philox
+        cls.bits = 64
+        cls.dtype = np.uint64
+        cls.data1 = cls._read_csv(
+            join(pwd, './data/philox-testset-1.csv'))
+        cls.data2 = cls._read_csv(
+            join(pwd, './data/philox-testset-2.csv'))
+        cls.seed_error_type = TypeError
+        cls.invalid_init_types = []
+        cls.invalid_init_values = [(1, None, 1), (-1,), (None, None, 2 ** 257 + 1)]
+
+    def test_set_key(self):
+        bit_generator = self.bit_generator(*self.data1['seed'])
+        state = bit_generator.state
+        keyed = self.bit_generator(counter=state['state']['counter'],
+                                   key=state['state']['key'])
+        assert_state_equal(bit_generator.state, keyed.state)
+
+
+class TestPCG64(Base):
+    @classmethod
+    def setup_class(cls):
+        cls.bit_generator = PCG64
+        cls.bits = 64
+        cls.dtype = np.uint64
+        cls.data1 = cls._read_csv(join(pwd, './data/pcg64-testset-1.csv'))
+        cls.data2 = cls._read_csv(join(pwd, './data/pcg64-testset-2.csv'))
+        cls.seed_error_type = (ValueError, TypeError)
+        cls.invalid_init_types = [(3.2,), ([None],), (1, None)]
+        cls.invalid_init_values = [(-1,)]
+
+    def test_advance_symmetry(self):
+        rs = Generator(self.bit_generator(*self.data1['seed']))
+        state = rs.bit_generator.state
+        step = -0x9e3779b97f4a7c150000000000000000
+        rs.bit_generator.advance(step)
+        val_neg = rs.integers(10)
+        rs.bit_generator.state = state
+        rs.bit_generator.advance(2**128 + step)
+        val_pos = rs.integers(10)
+        rs.bit_generator.state = state
+        rs.bit_generator.advance(10 * 2**128 + step)
+        val_big = rs.integers(10)
+        assert val_neg == val_pos
+        assert val_big == val_pos
+
+    def test_advange_large(self):
+        rs = Generator(self.bit_generator(38219308213743))
+        pcg = rs.bit_generator
+        state = pcg.state["state"]
+        initial_state = 287608843259529770491897792873167516365
+        assert state["state"] == initial_state
+        pcg.advance(sum(2**i for i in (96, 64, 32, 16, 8, 4, 2, 1)))
+        state = pcg.state["state"]
+        advanced_state = 135275564607035429730177404003164635391
+        assert state["state"] == advanced_state
+
+
+class TestPCG64DXSM(Base):
+    @classmethod
+    def setup_class(cls):
+        cls.bit_generator = PCG64DXSM
+        cls.bits = 64
+        cls.dtype = np.uint64
+        cls.data1 = cls._read_csv(join(pwd, './data/pcg64dxsm-testset-1.csv'))
+        cls.data2 = cls._read_csv(join(pwd, './data/pcg64dxsm-testset-2.csv'))
+        cls.seed_error_type = (ValueError, TypeError)
+        cls.invalid_init_types = [(3.2,), ([None],), (1, None)]
+        cls.invalid_init_values = [(-1,)]
+
+    def test_advance_symmetry(self):
+        rs = Generator(self.bit_generator(*self.data1['seed']))
+        state = rs.bit_generator.state
+        step = -0x9e3779b97f4a7c150000000000000000
+        rs.bit_generator.advance(step)
+        val_neg = rs.integers(10)
+        rs.bit_generator.state = state
+        rs.bit_generator.advance(2**128 + step)
+        val_pos = rs.integers(10)
+        rs.bit_generator.state = state
+        rs.bit_generator.advance(10 * 2**128 + step)
+        val_big = rs.integers(10)
+        assert val_neg == val_pos
+        assert val_big == val_pos
+
+    def test_advange_large(self):
+        rs = Generator(self.bit_generator(38219308213743))
+        pcg = rs.bit_generator
+        state = pcg.state
+        initial_state = 287608843259529770491897792873167516365
+        assert state["state"]["state"] == initial_state
+        pcg.advance(sum(2**i for i in (96, 64, 32, 16, 8, 4, 2, 1)))
+        state = pcg.state["state"]
+        advanced_state = 277778083536782149546677086420637664879
+        assert state["state"] == advanced_state
+
+
+class TestMT19937(Base):
+    @classmethod
+    def setup_class(cls):
+        cls.bit_generator = MT19937
+        cls.bits = 32
+        cls.dtype = np.uint32
+        cls.data1 = cls._read_csv(join(pwd, './data/mt19937-testset-1.csv'))
+        cls.data2 = cls._read_csv(join(pwd, './data/mt19937-testset-2.csv'))
+        cls.seed_error_type = ValueError
+        cls.invalid_init_types = []
+        cls.invalid_init_values = [(-1,)]
+
+    def test_seed_float_array(self):
+        assert_raises(TypeError, self.bit_generator, np.array([np.pi]))
+        assert_raises(TypeError, self.bit_generator, np.array([-np.pi]))
+        assert_raises(TypeError, self.bit_generator, np.array([np.pi, -np.pi]))
+        assert_raises(TypeError, self.bit_generator, np.array([0, np.pi]))
+        assert_raises(TypeError, self.bit_generator, [np.pi])
+        assert_raises(TypeError, self.bit_generator, [0, np.pi])
+
+    def test_state_tuple(self):
+        rs = Generator(self.bit_generator(*self.data1['seed']))
+        bit_generator = rs.bit_generator
+        state = bit_generator.state
+        desired = rs.integers(2 ** 16)
+        tup = (state['bit_generator'], state['state']['key'],
+               state['state']['pos'])
+        bit_generator.state = tup
+        actual = rs.integers(2 ** 16)
+        assert_equal(actual, desired)
+        tup = tup + (0, 0.0)
+        bit_generator.state = tup
+        actual = rs.integers(2 ** 16)
+        assert_equal(actual, desired)
+
+
+class TestSFC64(Base):
+    @classmethod
+    def setup_class(cls):
+        cls.bit_generator = SFC64
+        cls.bits = 64
+        cls.dtype = np.uint64
+        cls.data1 = cls._read_csv(
+            join(pwd, './data/sfc64-testset-1.csv'))
+        cls.data2 = cls._read_csv(
+            join(pwd, './data/sfc64-testset-2.csv'))
+        cls.seed_error_type = (ValueError, TypeError)
+        cls.invalid_init_types = [(3.2,), ([None],), (1, None)]
+        cls.invalid_init_values = [(-1,)]
+
+
+class TestDefaultRNG:
+    def test_seed(self):
+        for args in [(), (None,), (1234,), ([1234, 5678],)]:
+            rg = default_rng(*args)
+            assert isinstance(rg.bit_generator, PCG64)
+
+    def test_passthrough(self):
+        bg = Philox()
+        rg = default_rng(bg)
+        assert rg.bit_generator is bg
+        rg2 = default_rng(rg)
+        assert rg2 is rg
+        assert rg2.bit_generator is bg
diff --git a/venv/lib/python3.10/site-packages/numpy/random/tests/test_generator_mt19937.py b/venv/lib/python3.10/site-packages/numpy/random/tests/test_generator_mt19937.py
new file mode 100644
index 0000000000000000000000000000000000000000..e744f5ba611b177b10034cada76f0dd28f63cf16
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/numpy/random/tests/test_generator_mt19937.py
@@ -0,0 +1,2746 @@
+import sys
+import hashlib
+
+import pytest
+
+import numpy as np
+from numpy.linalg import LinAlgError
+from numpy.testing import (
+    assert_, assert_raises, assert_equal, assert_allclose,
+    assert_warns, assert_no_warnings, assert_array_equal,
+    assert_array_almost_equal, suppress_warnings, IS_WASM)
+
+from numpy.random import Generator, MT19937, SeedSequence, RandomState
+
+random = Generator(MT19937())
+
+JUMP_TEST_DATA = [
+    {
+        "seed": 0,
+        "steps": 10,
+        "initial": {"key_sha256": "bb1636883c2707b51c5b7fc26c6927af4430f2e0785a8c7bc886337f919f9edf", "pos": 9},
+        "jumped": {"key_sha256": "ff682ac12bb140f2d72fba8d3506cf4e46817a0db27aae1683867629031d8d55", "pos": 598},
+    },
+    {
+        "seed":384908324,
+        "steps":312,
+        "initial": {"key_sha256": "16b791a1e04886ccbbb4d448d6ff791267dc458ae599475d08d5cced29d11614", "pos": 311},
+        "jumped": {"key_sha256": "a0110a2cf23b56be0feaed8f787a7fc84bef0cb5623003d75b26bdfa1c18002c", "pos": 276},
+    },
+    {
+        "seed": [839438204, 980239840, 859048019, 821],
+        "steps": 511,
+        "initial": {"key_sha256": "d306cf01314d51bd37892d874308200951a35265ede54d200f1e065004c3e9ea", "pos": 510},
+        "jumped": {"key_sha256": "0e00ab449f01a5195a83b4aee0dfbc2ce8d46466a640b92e33977d2e42f777f8", "pos": 475},
+    },
+]
+
+
+@pytest.fixture(scope='module', params=[True, False])
+def endpoint(request):
+    return request.param
+
+
+class TestSeed:
+    def test_scalar(self):
+        s = Generator(MT19937(0))
+        assert_equal(s.integers(1000), 479)
+        s = Generator(MT19937(4294967295))
+        assert_equal(s.integers(1000), 324)
+
+    def test_array(self):
+        s = Generator(MT19937(range(10)))
+        assert_equal(s.integers(1000), 465)
+        s = Generator(MT19937(np.arange(10)))
+        assert_equal(s.integers(1000), 465)
+        s = Generator(MT19937([0]))
+        assert_equal(s.integers(1000), 479)
+        s = Generator(MT19937([4294967295]))
+        assert_equal(s.integers(1000), 324)
+
+    def test_seedsequence(self):
+        s = MT19937(SeedSequence(0))
+        assert_equal(s.random_raw(1), 2058676884)
+
+    def test_invalid_scalar(self):
+        # seed must be an unsigned 32 bit integer
+        assert_raises(TypeError, MT19937, -0.5)
+        assert_raises(ValueError, MT19937, -1)
+
+    def test_invalid_array(self):
+        # seed must be an unsigned integer
+        assert_raises(TypeError, MT19937, [-0.5])
+        assert_raises(ValueError, MT19937, [-1])
+        assert_raises(ValueError, MT19937, [1, -2, 4294967296])
+
+    def test_noninstantized_bitgen(self):
+        assert_raises(ValueError, Generator, MT19937)
+
+
+class TestBinomial:
+    def test_n_zero(self):
+        # Tests the corner case of n == 0 for the binomial distribution.
+        # binomial(0, p) should be zero for any p in [0, 1].
+        # This test addresses issue #3480.
+        zeros = np.zeros(2, dtype='int')
+        for p in [0, .5, 1]:
+            assert_(random.binomial(0, p) == 0)
+            assert_array_equal(random.binomial(zeros, p), zeros)
+
+    def test_p_is_nan(self):
+        # Issue #4571.
+        assert_raises(ValueError, random.binomial, 1, np.nan)
+
+
+class TestMultinomial:
+    def test_basic(self):
+        random.multinomial(100, [0.2, 0.8])
+
+    def test_zero_probability(self):
+        random.multinomial(100, [0.2, 0.8, 0.0, 0.0, 0.0])
+
+    def test_int_negative_interval(self):
+        assert_(-5 <= random.integers(-5, -1) < -1)
+        x = random.integers(-5, -1, 5)
+        assert_(np.all(-5 <= x))
+        assert_(np.all(x < -1))
+
+    def test_size(self):
+        # gh-3173
+        p = [0.5, 0.5]
+        assert_equal(random.multinomial(1, p, np.uint32(1)).shape, (1, 2))
+        assert_equal(random.multinomial(1, p, np.uint32(1)).shape, (1, 2))
+        assert_equal(random.multinomial(1, p, np.uint32(1)).shape, (1, 2))
+        assert_equal(random.multinomial(1, p, [2, 2]).shape, (2, 2, 2))
+        assert_equal(random.multinomial(1, p, (2, 2)).shape, (2, 2, 2))
+        assert_equal(random.multinomial(1, p, np.array((2, 2))).shape,
+                     (2, 2, 2))
+
+        assert_raises(TypeError, random.multinomial, 1, p,
+                      float(1))
+
+    def test_invalid_prob(self):
+        assert_raises(ValueError, random.multinomial, 100, [1.1, 0.2])
+        assert_raises(ValueError, random.multinomial, 100, [-.1, 0.9])
+
+    def test_invalid_n(self):
+        assert_raises(ValueError, random.multinomial, -1, [0.8, 0.2])
+        assert_raises(ValueError, random.multinomial, [-1] * 10, [0.8, 0.2])
+
+    def test_p_non_contiguous(self):
+        p = np.arange(15.)
+        p /= np.sum(p[1::3])
+        pvals = p[1::3]
+        random = Generator(MT19937(1432985819))
+        non_contig = random.multinomial(100, pvals=pvals)
+        random = Generator(MT19937(1432985819))
+        contig = random.multinomial(100, pvals=np.ascontiguousarray(pvals))
+        assert_array_equal(non_contig, contig)
+
+    def test_multinomial_pvals_float32(self):
+        x = np.array([9.9e-01, 9.9e-01, 1.0e-09, 1.0e-09, 1.0e-09, 1.0e-09,
+                      1.0e-09, 1.0e-09, 1.0e-09, 1.0e-09], dtype=np.float32)
+        pvals = x / x.sum()
+        random = Generator(MT19937(1432985819))
+        match = r"[\w\s]*pvals array is cast to 64-bit floating"
+        with pytest.raises(ValueError, match=match):
+            random.multinomial(1, pvals)
+
+
+class TestMultivariateHypergeometric:
+
+    def setup_method(self):
+        self.seed = 8675309
+
+    def test_argument_validation(self):
+        # Error cases...
+
+        # `colors` must be a 1-d sequence
+        assert_raises(ValueError, random.multivariate_hypergeometric,
+                      10, 4)
+
+        # Negative nsample
+        assert_raises(ValueError, random.multivariate_hypergeometric,
+                      [2, 3, 4], -1)
+
+        # Negative color
+        assert_raises(ValueError, random.multivariate_hypergeometric,
+                      [-1, 2, 3], 2)
+
+        # nsample exceeds sum(colors)
+        assert_raises(ValueError, random.multivariate_hypergeometric,
+                      [2, 3, 4], 10)
+
+        # nsample exceeds sum(colors) (edge case of empty colors)
+        assert_raises(ValueError, random.multivariate_hypergeometric,
+                      [], 1)
+
+        # Validation errors associated with very large values in colors.
+        assert_raises(ValueError, random.multivariate_hypergeometric,
+                      [999999999, 101], 5, 1, 'marginals')
+
+        int64_info = np.iinfo(np.int64)
+        max_int64 = int64_info.max
+        max_int64_index = max_int64 // int64_info.dtype.itemsize
+        assert_raises(ValueError, random.multivariate_hypergeometric,
+                      [max_int64_index - 100, 101], 5, 1, 'count')
+
+    @pytest.mark.parametrize('method', ['count', 'marginals'])
+    def test_edge_cases(self, method):
+        # Set the seed, but in fact, all the results in this test are
+        # deterministic, so we don't really need this.
+        random = Generator(MT19937(self.seed))
+
+        x = random.multivariate_hypergeometric([0, 0, 0], 0, method=method)
+        assert_array_equal(x, [0, 0, 0])
+
+        x = random.multivariate_hypergeometric([], 0, method=method)
+        assert_array_equal(x, [])
+
+        x = random.multivariate_hypergeometric([], 0, size=1, method=method)
+        assert_array_equal(x, np.empty((1, 0), dtype=np.int64))
+
+        x = random.multivariate_hypergeometric([1, 2, 3], 0, method=method)
+        assert_array_equal(x, [0, 0, 0])
+
+        x = random.multivariate_hypergeometric([9, 0, 0], 3, method=method)
+        assert_array_equal(x, [3, 0, 0])
+
+        colors = [1, 1, 0, 1, 1]
+        x = random.multivariate_hypergeometric(colors, sum(colors),
+                                               method=method)
+        assert_array_equal(x, colors)
+
+        x = random.multivariate_hypergeometric([3, 4, 5], 12, size=3,
+                                               method=method)
+        assert_array_equal(x, [[3, 4, 5]]*3)
+
+    # Cases for nsample:
+    #     nsample < 10
+    #     10 <= nsample < colors.sum()/2
+    #     colors.sum()/2 < nsample < colors.sum() - 10
+    #     colors.sum() - 10 < nsample < colors.sum()
+    @pytest.mark.parametrize('nsample', [8, 25, 45, 55])
+    @pytest.mark.parametrize('method', ['count', 'marginals'])
+    @pytest.mark.parametrize('size', [5, (2, 3), 150000])
+    def test_typical_cases(self, nsample, method, size):
+        random = Generator(MT19937(self.seed))
+
+        colors = np.array([10, 5, 20, 25])
+        sample = random.multivariate_hypergeometric(colors, nsample, size,
+                                                    method=method)
+        if isinstance(size, int):
+            expected_shape = (size,) + colors.shape
+        else:
+            expected_shape = size + colors.shape
+        assert_equal(sample.shape, expected_shape)
+        assert_((sample >= 0).all())
+        assert_((sample <= colors).all())
+        assert_array_equal(sample.sum(axis=-1),
+                           np.full(size, fill_value=nsample, dtype=int))
+        if isinstance(size, int) and size >= 100000:
+            # This sample is large enough to compare its mean to
+            # the expected values.
+            assert_allclose(sample.mean(axis=0),
+                            nsample * colors / colors.sum(),
+                            rtol=1e-3, atol=0.005)
+
+    def test_repeatability1(self):
+        random = Generator(MT19937(self.seed))
+        sample = random.multivariate_hypergeometric([3, 4, 5], 5, size=5,
+                                                    method='count')
+        expected = np.array([[2, 1, 2],
+                             [2, 1, 2],
+                             [1, 1, 3],
+                             [2, 0, 3],
+                             [2, 1, 2]])
+        assert_array_equal(sample, expected)
+
+    def test_repeatability2(self):
+        random = Generator(MT19937(self.seed))
+        sample = random.multivariate_hypergeometric([20, 30, 50], 50,
+                                                    size=5,
+                                                    method='marginals')
+        expected = np.array([[ 9, 17, 24],
+                             [ 7, 13, 30],
+                             [ 9, 15, 26],
+                             [ 9, 17, 24],
+                             [12, 14, 24]])
+        assert_array_equal(sample, expected)
+
+    def test_repeatability3(self):
+        random = Generator(MT19937(self.seed))
+        sample = random.multivariate_hypergeometric([20, 30, 50], 12,
+                                                    size=5,
+                                                    method='marginals')
+        expected = np.array([[2, 3, 7],
+                             [5, 3, 4],
+                             [2, 5, 5],
+                             [5, 3, 4],
+                             [1, 5, 6]])
+        assert_array_equal(sample, expected)
+
+
+class TestSetState:
+    def setup_method(self):
+        self.seed = 1234567890
+        self.rg = Generator(MT19937(self.seed))
+        self.bit_generator = self.rg.bit_generator
+        self.state = self.bit_generator.state
+        self.legacy_state = (self.state['bit_generator'],
+                             self.state['state']['key'],
+                             self.state['state']['pos'])
+
+    def test_gaussian_reset(self):
+        # Make sure the cached every-other-Gaussian is reset.
+        old = self.rg.standard_normal(size=3)
+        self.bit_generator.state = self.state
+        new = self.rg.standard_normal(size=3)
+        assert_(np.all(old == new))
+
+    def test_gaussian_reset_in_media_res(self):
+        # When the state is saved with a cached Gaussian, make sure the
+        # cached Gaussian is restored.
+
+        self.rg.standard_normal()
+        state = self.bit_generator.state
+        old = self.rg.standard_normal(size=3)
+        self.bit_generator.state = state
+        new = self.rg.standard_normal(size=3)
+        assert_(np.all(old == new))
+
+    def test_negative_binomial(self):
+        # Ensure that the negative binomial results take floating point
+        # arguments without truncation.
+        self.rg.negative_binomial(0.5, 0.5)
+
+
+class TestIntegers:
+    rfunc = random.integers
+
+    # valid integer/boolean types
+    itype = [bool, np.int8, np.uint8, np.int16, np.uint16,
+             np.int32, np.uint32, np.int64, np.uint64]
+
+    def test_unsupported_type(self, endpoint):
+        assert_raises(TypeError, self.rfunc, 1, endpoint=endpoint, dtype=float)
+
+    def test_bounds_checking(self, endpoint):
+        for dt in self.itype:
+            lbnd = 0 if dt is bool else np.iinfo(dt).min
+            ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
+            ubnd = ubnd - 1 if endpoint else ubnd
+            assert_raises(ValueError, self.rfunc, lbnd - 1, ubnd,
+                          endpoint=endpoint, dtype=dt)
+            assert_raises(ValueError, self.rfunc, lbnd, ubnd + 1,
+                          endpoint=endpoint, dtype=dt)
+            assert_raises(ValueError, self.rfunc, ubnd, lbnd,
+                          endpoint=endpoint, dtype=dt)
+            assert_raises(ValueError, self.rfunc, 1, 0, endpoint=endpoint,
+                          dtype=dt)
+
+            assert_raises(ValueError, self.rfunc, [lbnd - 1], ubnd,
+                          endpoint=endpoint, dtype=dt)
+            assert_raises(ValueError, self.rfunc, [lbnd], [ubnd + 1],
+                          endpoint=endpoint, dtype=dt)
+            assert_raises(ValueError, self.rfunc, [ubnd], [lbnd],
+                          endpoint=endpoint, dtype=dt)
+            assert_raises(ValueError, self.rfunc, 1, [0],
+                          endpoint=endpoint, dtype=dt)
+            assert_raises(ValueError, self.rfunc, [ubnd+1], [ubnd],
+                          endpoint=endpoint, dtype=dt)
+
+    def test_bounds_checking_array(self, endpoint):
+        for dt in self.itype:
+            lbnd = 0 if dt is bool else np.iinfo(dt).min
+            ubnd = 2 if dt is bool else np.iinfo(dt).max + (not endpoint)
+
+            assert_raises(ValueError, self.rfunc, [lbnd - 1] * 2, [ubnd] * 2,
+                          endpoint=endpoint, dtype=dt)
+            assert_raises(ValueError, self.rfunc, [lbnd] * 2,
+                          [ubnd + 1] * 2, endpoint=endpoint, dtype=dt)
+            assert_raises(ValueError, self.rfunc, ubnd, [lbnd] * 2,
+                          endpoint=endpoint, dtype=dt)
+            assert_raises(ValueError, self.rfunc, [1] * 2, 0,
+                          endpoint=endpoint, dtype=dt)
+
+    def test_rng_zero_and_extremes(self, endpoint):
+        for dt in self.itype:
+            lbnd = 0 if dt is bool else np.iinfo(dt).min
+            ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
+            ubnd = ubnd - 1 if endpoint else ubnd
+            is_open = not endpoint
+
+            tgt = ubnd - 1
+            assert_equal(self.rfunc(tgt, tgt + is_open, size=1000,
+                                    endpoint=endpoint, dtype=dt), tgt)
+            assert_equal(self.rfunc([tgt], tgt + is_open, size=1000,
+                                    endpoint=endpoint, dtype=dt), tgt)
+
+            tgt = lbnd
+            assert_equal(self.rfunc(tgt, tgt + is_open, size=1000,
+                                    endpoint=endpoint, dtype=dt), tgt)
+            assert_equal(self.rfunc(tgt, [tgt + is_open], size=1000,
+                                    endpoint=endpoint, dtype=dt), tgt)
+
+            tgt = (lbnd + ubnd) // 2
+            assert_equal(self.rfunc(tgt, tgt + is_open, size=1000,
+                                    endpoint=endpoint, dtype=dt), tgt)
+            assert_equal(self.rfunc([tgt], [tgt + is_open],
+                                    size=1000, endpoint=endpoint, dtype=dt),
+                         tgt)
+
+    def test_rng_zero_and_extremes_array(self, endpoint):
+        size = 1000
+        for dt in self.itype:
+            lbnd = 0 if dt is bool else np.iinfo(dt).min
+            ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
+            ubnd = ubnd - 1 if endpoint else ubnd
+
+            tgt = ubnd - 1
+            assert_equal(self.rfunc([tgt], [tgt + 1],
+                                    size=size, dtype=dt), tgt)
+            assert_equal(self.rfunc(
+                [tgt] * size, [tgt + 1] * size, dtype=dt), tgt)
+            assert_equal(self.rfunc(
+                [tgt] * size, [tgt + 1] * size, size=size, dtype=dt), tgt)
+
+            tgt = lbnd
+            assert_equal(self.rfunc([tgt], [tgt + 1],
+                                    size=size, dtype=dt), tgt)
+            assert_equal(self.rfunc(
+                [tgt] * size, [tgt + 1] * size, dtype=dt), tgt)
+            assert_equal(self.rfunc(
+                [tgt] * size, [tgt + 1] * size, size=size, dtype=dt), tgt)
+
+            tgt = (lbnd + ubnd) // 2
+            assert_equal(self.rfunc([tgt], [tgt + 1],
+                                    size=size, dtype=dt), tgt)
+            assert_equal(self.rfunc(
+                [tgt] * size, [tgt + 1] * size, dtype=dt), tgt)
+            assert_equal(self.rfunc(
+                [tgt] * size, [tgt + 1] * size, size=size, dtype=dt), tgt)
+
+    def test_full_range(self, endpoint):
+        # Test for ticket #1690
+
+        for dt in self.itype:
+            lbnd = 0 if dt is bool else np.iinfo(dt).min
+            ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
+            ubnd = ubnd - 1 if endpoint else ubnd
+
+            try:
+                self.rfunc(lbnd, ubnd, endpoint=endpoint, dtype=dt)
+            except Exception as e:
+                raise AssertionError("No error should have been raised, "
+                                     "but one was with the following "
+                                     "message:\n\n%s" % str(e))
+
+    def test_full_range_array(self, endpoint):
+        # Test for ticket #1690
+
+        for dt in self.itype:
+            lbnd = 0 if dt is bool else np.iinfo(dt).min
+            ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
+            ubnd = ubnd - 1 if endpoint else ubnd
+
+            try:
+                self.rfunc([lbnd] * 2, [ubnd], endpoint=endpoint, dtype=dt)
+            except Exception as e:
+                raise AssertionError("No error should have been raised, "
+                                     "but one was with the following "
+                                     "message:\n\n%s" % str(e))
+
+    def test_in_bounds_fuzz(self, endpoint):
+        # Don't use fixed seed
+        random = Generator(MT19937())
+
+        for dt in self.itype[1:]:
+            for ubnd in [4, 8, 16]:
+                vals = self.rfunc(2, ubnd - endpoint, size=2 ** 16,
+                                  endpoint=endpoint, dtype=dt)
+                assert_(vals.max() < ubnd)
+                assert_(vals.min() >= 2)
+
+        vals = self.rfunc(0, 2 - endpoint, size=2 ** 16, endpoint=endpoint,
+                          dtype=bool)
+        assert_(vals.max() < 2)
+        assert_(vals.min() >= 0)
+
+    def test_scalar_array_equiv(self, endpoint):
+        for dt in self.itype:
+            lbnd = 0 if dt is bool else np.iinfo(dt).min
+            ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
+            ubnd = ubnd - 1 if endpoint else ubnd
+
+            size = 1000
+            random = Generator(MT19937(1234))
+            scalar = random.integers(lbnd, ubnd, size=size, endpoint=endpoint,
+                                dtype=dt)
+
+            random = Generator(MT19937(1234))
+            scalar_array = random.integers([lbnd], [ubnd], size=size,
+                                      endpoint=endpoint, dtype=dt)
+
+            random = Generator(MT19937(1234))
+            array = random.integers([lbnd] * size, [ubnd] *
+                               size, size=size, endpoint=endpoint, dtype=dt)
+            assert_array_equal(scalar, scalar_array)
+            assert_array_equal(scalar, array)
+
+    def test_repeatability(self, endpoint):
+        # We use a sha256 hash of generated sequences of 1000 samples
+        # in the range [0, 6) for all but bool, where the range
+        # is [0, 2). Hashes are for little endian numbers.
+        tgt = {'bool':   '053594a9b82d656f967c54869bc6970aa0358cf94ad469c81478459c6a90eee3',
+               'int16':  '54de9072b6ee9ff7f20b58329556a46a447a8a29d67db51201bf88baa6e4e5d4',
+               'int32':  'd3a0d5efb04542b25ac712e50d21f39ac30f312a5052e9bbb1ad3baa791ac84b',
+               'int64':  '14e224389ac4580bfbdccb5697d6190b496f91227cf67df60989de3d546389b1',
+               'int8':   '0e203226ff3fbbd1580f15da4621e5f7164d0d8d6b51696dd42d004ece2cbec1',
+               'uint16': '54de9072b6ee9ff7f20b58329556a46a447a8a29d67db51201bf88baa6e4e5d4',
+               'uint32': 'd3a0d5efb04542b25ac712e50d21f39ac30f312a5052e9bbb1ad3baa791ac84b',
+               'uint64': '14e224389ac4580bfbdccb5697d6190b496f91227cf67df60989de3d546389b1',
+               'uint8':  '0e203226ff3fbbd1580f15da4621e5f7164d0d8d6b51696dd42d004ece2cbec1'}
+
+        for dt in self.itype[1:]:
+            random = Generator(MT19937(1234))
+
+            # view as little endian for hash
+            if sys.byteorder == 'little':
+                val = random.integers(0, 6 - endpoint, size=1000, endpoint=endpoint,
+                                 dtype=dt)
+            else:
+                val = random.integers(0, 6 - endpoint, size=1000, endpoint=endpoint,
+                                 dtype=dt).byteswap()
+
+            res = hashlib.sha256(val).hexdigest()
+            assert_(tgt[np.dtype(dt).name] == res)
+
+        # bools do not depend on endianness
+        random = Generator(MT19937(1234))
+        val = random.integers(0, 2 - endpoint, size=1000, endpoint=endpoint,
+                         dtype=bool).view(np.int8)
+        res = hashlib.sha256(val).hexdigest()
+        assert_(tgt[np.dtype(bool).name] == res)
+
+    def test_repeatability_broadcasting(self, endpoint):
+        for dt in self.itype:
+            lbnd = 0 if dt in (bool, np.bool_) else np.iinfo(dt).min
+            ubnd = 2 if dt in (bool, np.bool_) else np.iinfo(dt).max + 1
+            ubnd = ubnd - 1 if endpoint else ubnd
+
+            # view as little endian for hash
+            random = Generator(MT19937(1234))
+            val = random.integers(lbnd, ubnd, size=1000, endpoint=endpoint,
+                             dtype=dt)
+
+            random = Generator(MT19937(1234))
+            val_bc = random.integers([lbnd] * 1000, ubnd, endpoint=endpoint,
+                                dtype=dt)
+
+            assert_array_equal(val, val_bc)
+
+            random = Generator(MT19937(1234))
+            val_bc = random.integers([lbnd] * 1000, [ubnd] * 1000,
+                                endpoint=endpoint, dtype=dt)
+
+            assert_array_equal(val, val_bc)
+
+    @pytest.mark.parametrize(
+        'bound, expected',
+        [(2**32 - 1, np.array([517043486, 1364798665, 1733884389, 1353720612,
+                               3769704066, 1170797179, 4108474671])),
+         (2**32, np.array([517043487, 1364798666, 1733884390, 1353720613,
+                           3769704067, 1170797180, 4108474672])),
+         (2**32 + 1, np.array([517043487, 1733884390, 3769704068, 4108474673,
+                               1831631863, 1215661561, 3869512430]))]
+    )
+    def test_repeatability_32bit_boundary(self, bound, expected):
+        for size in [None, len(expected)]:
+            random = Generator(MT19937(1234))
+            x = random.integers(bound, size=size)
+            assert_equal(x, expected if size is not None else expected[0])
+
+    def test_repeatability_32bit_boundary_broadcasting(self):
+        desired = np.array([[[1622936284, 3620788691, 1659384060],
+                             [1417365545,  760222891, 1909653332],
+                             [3788118662,  660249498, 4092002593]],
+                            [[3625610153, 2979601262, 3844162757],
+                             [ 685800658,  120261497, 2694012896],
+                             [1207779440, 1586594375, 3854335050]],
+                            [[3004074748, 2310761796, 3012642217],
+                             [2067714190, 2786677879, 1363865881],
+                             [ 791663441, 1867303284, 2169727960]],
+                            [[1939603804, 1250951100,  298950036],
+                             [1040128489, 3791912209, 3317053765],
+                             [3155528714,   61360675, 2305155588]],
+                            [[ 817688762, 1335621943, 3288952434],
+                             [1770890872, 1102951817, 1957607470],
+                             [3099996017,  798043451,   48334215]]])
+        for size in [None, (5, 3, 3)]:
+            random = Generator(MT19937(12345))
+            x = random.integers([[-1], [0], [1]],
+                                [2**32 - 1, 2**32, 2**32 + 1],
+                                size=size)
+            assert_array_equal(x, desired if size is not None else desired[0])
+
+    def test_int64_uint64_broadcast_exceptions(self, endpoint):
+        configs = {np.uint64: ((0, 2**65), (-1, 2**62), (10, 9), (0, 0)),
+                   np.int64: ((0, 2**64), (-(2**64), 2**62), (10, 9), (0, 0),
+                              (-2**63-1, -2**63-1))}
+        for dtype in configs:
+            for config in configs[dtype]:
+                low, high = config
+                high = high - endpoint
+                low_a = np.array([[low]*10])
+                high_a = np.array([high] * 10)
+                assert_raises(ValueError, random.integers, low, high,
+                              endpoint=endpoint, dtype=dtype)
+                assert_raises(ValueError, random.integers, low_a, high,
+                              endpoint=endpoint, dtype=dtype)
+                assert_raises(ValueError, random.integers, low, high_a,
+                              endpoint=endpoint, dtype=dtype)
+                assert_raises(ValueError, random.integers, low_a, high_a,
+                              endpoint=endpoint, dtype=dtype)
+
+                low_o = np.array([[low]*10], dtype=object)
+                high_o = np.array([high] * 10, dtype=object)
+                assert_raises(ValueError, random.integers, low_o, high,
+                              endpoint=endpoint, dtype=dtype)
+                assert_raises(ValueError, random.integers, low, high_o,
+                              endpoint=endpoint, dtype=dtype)
+                assert_raises(ValueError, random.integers, low_o, high_o,
+                              endpoint=endpoint, dtype=dtype)
+
+    def test_int64_uint64_corner_case(self, endpoint):
+        # When stored in Numpy arrays, `lbnd` is casted
+        # as np.int64, and `ubnd` is casted as np.uint64.
+        # Checking whether `lbnd` >= `ubnd` used to be
+        # done solely via direct comparison, which is incorrect
+        # because when Numpy tries to compare both numbers,
+        # it casts both to np.float64 because there is
+        # no integer superset of np.int64 and np.uint64. However,
+        # `ubnd` is too large to be represented in np.float64,
+        # causing it be round down to np.iinfo(np.int64).max,
+        # leading to a ValueError because `lbnd` now equals
+        # the new `ubnd`.
+
+        dt = np.int64
+        tgt = np.iinfo(np.int64).max
+        lbnd = np.int64(np.iinfo(np.int64).max)
+        ubnd = np.uint64(np.iinfo(np.int64).max + 1 - endpoint)
+
+        # None of these function calls should
+        # generate a ValueError now.
+        actual = random.integers(lbnd, ubnd, endpoint=endpoint, dtype=dt)
+        assert_equal(actual, tgt)
+
+    def test_respect_dtype_singleton(self, endpoint):
+        # See gh-7203
+        for dt in self.itype:
+            lbnd = 0 if dt is bool else np.iinfo(dt).min
+            ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
+            ubnd = ubnd - 1 if endpoint else ubnd
+            dt = np.bool_ if dt is bool else dt
+
+            sample = self.rfunc(lbnd, ubnd, endpoint=endpoint, dtype=dt)
+            assert_equal(sample.dtype, dt)
+
+        for dt in (bool, int):
+            lbnd = 0 if dt is bool else np.iinfo(dt).min
+            ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
+            ubnd = ubnd - 1 if endpoint else ubnd
+
+            # gh-7284: Ensure that we get Python data types
+            sample = self.rfunc(lbnd, ubnd, endpoint=endpoint, dtype=dt)
+            assert not hasattr(sample, 'dtype')
+            assert_equal(type(sample), dt)
+
+    def test_respect_dtype_array(self, endpoint):
+        # See gh-7203
+        for dt in self.itype:
+            lbnd = 0 if dt is bool else np.iinfo(dt).min
+            ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
+            ubnd = ubnd - 1 if endpoint else ubnd
+            dt = np.bool_ if dt is bool else dt
+
+            sample = self.rfunc([lbnd], [ubnd], endpoint=endpoint, dtype=dt)
+            assert_equal(sample.dtype, dt)
+            sample = self.rfunc([lbnd] * 2, [ubnd] * 2, endpoint=endpoint,
+                                dtype=dt)
+            assert_equal(sample.dtype, dt)
+
+    def test_zero_size(self, endpoint):
+        # See gh-7203
+        for dt in self.itype:
+            sample = self.rfunc(0, 0, (3, 0, 4), endpoint=endpoint, dtype=dt)
+            assert sample.shape == (3, 0, 4)
+            assert sample.dtype == dt
+            assert self.rfunc(0, -10, 0, endpoint=endpoint,
+                              dtype=dt).shape == (0,)
+            assert_equal(random.integers(0, 0, size=(3, 0, 4)).shape,
+                         (3, 0, 4))
+            assert_equal(random.integers(0, -10, size=0).shape, (0,))
+            assert_equal(random.integers(10, 10, size=0).shape, (0,))
+
+    def test_error_byteorder(self):
+        other_byteord_dt = 'i4'
+        with pytest.raises(ValueError):
+            random.integers(0, 200, size=10, dtype=other_byteord_dt)
+
+    # chi2max is the maximum acceptable chi-squared value.
+    @pytest.mark.slow
+    @pytest.mark.parametrize('sample_size,high,dtype,chi2max',
+        [(5000000, 5, np.int8, 125.0),          # p-value ~4.6e-25
+         (5000000, 7, np.uint8, 150.0),         # p-value ~7.7e-30
+         (10000000, 2500, np.int16, 3300.0),    # p-value ~3.0e-25
+         (50000000, 5000, np.uint16, 6500.0),   # p-value ~3.5e-25
+        ])
+    def test_integers_small_dtype_chisquared(self, sample_size, high,
+                                             dtype, chi2max):
+        # Regression test for gh-14774.
+        samples = random.integers(high, size=sample_size, dtype=dtype)
+
+        values, counts = np.unique(samples, return_counts=True)
+        expected = sample_size / high
+        chi2 = ((counts - expected)**2 / expected).sum()
+        assert chi2 < chi2max
+
+
+class TestRandomDist:
+    # Make sure the random distribution returns the correct value for a
+    # given seed
+
+    def setup_method(self):
+        self.seed = 1234567890
+
+    def test_integers(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.integers(-99, 99, size=(3, 2))
+        desired = np.array([[-80, -56], [41, 37], [-83, -16]])
+        assert_array_equal(actual, desired)
+
+    def test_integers_masked(self):
+        # Test masked rejection sampling algorithm to generate array of
+        # uint32 in an interval.
+        random = Generator(MT19937(self.seed))
+        actual = random.integers(0, 99, size=(3, 2), dtype=np.uint32)
+        desired = np.array([[9, 21], [70, 68], [8, 41]], dtype=np.uint32)
+        assert_array_equal(actual, desired)
+
+    def test_integers_closed(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.integers(-99, 99, size=(3, 2), endpoint=True)
+        desired = np.array([[-80, -56], [ 41, 38], [-83, -15]])
+        assert_array_equal(actual, desired)
+
+    def test_integers_max_int(self):
+        # Tests whether integers with closed=True can generate the
+        # maximum allowed Python int that can be converted
+        # into a C long. Previous implementations of this
+        # method have thrown an OverflowError when attempting
+        # to generate this integer.
+        actual = random.integers(np.iinfo('l').max, np.iinfo('l').max,
+                                 endpoint=True)
+
+        desired = np.iinfo('l').max
+        assert_equal(actual, desired)
+
+    def test_random(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.random((3, 2))
+        desired = np.array([[0.096999199829214, 0.707517457682192],
+                            [0.084364834598269, 0.767731206553125],
+                            [0.665069021359413, 0.715487190596693]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+        random = Generator(MT19937(self.seed))
+        actual = random.random()
+        assert_array_almost_equal(actual, desired[0, 0], decimal=15)
+
+    def test_random_float(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.random((3, 2))
+        desired = np.array([[0.0969992 , 0.70751746],
+                            [0.08436483, 0.76773121],
+                            [0.66506902, 0.71548719]])
+        assert_array_almost_equal(actual, desired, decimal=7)
+
+    def test_random_float_scalar(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.random(dtype=np.float32)
+        desired = 0.0969992
+        assert_array_almost_equal(actual, desired, decimal=7)
+
+    @pytest.mark.parametrize('dtype, uint_view_type',
+                             [(np.float32, np.uint32),
+                              (np.float64, np.uint64)])
+    def test_random_distribution_of_lsb(self, dtype, uint_view_type):
+        random = Generator(MT19937(self.seed))
+        sample = random.random(100000, dtype=dtype)
+        num_ones_in_lsb = np.count_nonzero(sample.view(uint_view_type) & 1)
+        # The probability of a 1 in the least significant bit is 0.25.
+        # With a sample size of 100000, the probability that num_ones_in_lsb
+        # is outside the following range is less than 5e-11.
+        assert 24100 < num_ones_in_lsb < 25900
+
+    def test_random_unsupported_type(self):
+        assert_raises(TypeError, random.random, dtype='int32')
+
+    def test_choice_uniform_replace(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.choice(4, 4)
+        desired = np.array([0, 0, 2, 2], dtype=np.int64)
+        assert_array_equal(actual, desired)
+
+    def test_choice_nonuniform_replace(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.choice(4, 4, p=[0.4, 0.4, 0.1, 0.1])
+        desired = np.array([0, 1, 0, 1], dtype=np.int64)
+        assert_array_equal(actual, desired)
+
+    def test_choice_uniform_noreplace(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.choice(4, 3, replace=False)
+        desired = np.array([2, 0, 3], dtype=np.int64)
+        assert_array_equal(actual, desired)
+        actual = random.choice(4, 4, replace=False, shuffle=False)
+        desired = np.arange(4, dtype=np.int64)
+        assert_array_equal(actual, desired)
+
+    def test_choice_nonuniform_noreplace(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.choice(4, 3, replace=False, p=[0.1, 0.3, 0.5, 0.1])
+        desired = np.array([0, 2, 3], dtype=np.int64)
+        assert_array_equal(actual, desired)
+
+    def test_choice_noninteger(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.choice(['a', 'b', 'c', 'd'], 4)
+        desired = np.array(['a', 'a', 'c', 'c'])
+        assert_array_equal(actual, desired)
+
+    def test_choice_multidimensional_default_axis(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.choice([[0, 1], [2, 3], [4, 5], [6, 7]], 3)
+        desired = np.array([[0, 1], [0, 1], [4, 5]])
+        assert_array_equal(actual, desired)
+
+    def test_choice_multidimensional_custom_axis(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.choice([[0, 1], [2, 3], [4, 5], [6, 7]], 1, axis=1)
+        desired = np.array([[0], [2], [4], [6]])
+        assert_array_equal(actual, desired)
+
+    def test_choice_exceptions(self):
+        sample = random.choice
+        assert_raises(ValueError, sample, -1, 3)
+        assert_raises(ValueError, sample, 3., 3)
+        assert_raises(ValueError, sample, [], 3)
+        assert_raises(ValueError, sample, [1, 2, 3, 4], 3,
+                      p=[[0.25, 0.25], [0.25, 0.25]])
+        assert_raises(ValueError, sample, [1, 2], 3, p=[0.4, 0.4, 0.2])
+        assert_raises(ValueError, sample, [1, 2], 3, p=[1.1, -0.1])
+        assert_raises(ValueError, sample, [1, 2], 3, p=[0.4, 0.4])
+        assert_raises(ValueError, sample, [1, 2, 3], 4, replace=False)
+        # gh-13087
+        assert_raises(ValueError, sample, [1, 2, 3], -2, replace=False)
+        assert_raises(ValueError, sample, [1, 2, 3], (-1,), replace=False)
+        assert_raises(ValueError, sample, [1, 2, 3], (-1, 1), replace=False)
+        assert_raises(ValueError, sample, [1, 2, 3], 2,
+                      replace=False, p=[1, 0, 0])
+
+    def test_choice_return_shape(self):
+        p = [0.1, 0.9]
+        # Check scalar
+        assert_(np.isscalar(random.choice(2, replace=True)))
+        assert_(np.isscalar(random.choice(2, replace=False)))
+        assert_(np.isscalar(random.choice(2, replace=True, p=p)))
+        assert_(np.isscalar(random.choice(2, replace=False, p=p)))
+        assert_(np.isscalar(random.choice([1, 2], replace=True)))
+        assert_(random.choice([None], replace=True) is None)
+        a = np.array([1, 2])
+        arr = np.empty(1, dtype=object)
+        arr[0] = a
+        assert_(random.choice(arr, replace=True) is a)
+
+        # Check 0-d array
+        s = tuple()
+        assert_(not np.isscalar(random.choice(2, s, replace=True)))
+        assert_(not np.isscalar(random.choice(2, s, replace=False)))
+        assert_(not np.isscalar(random.choice(2, s, replace=True, p=p)))
+        assert_(not np.isscalar(random.choice(2, s, replace=False, p=p)))
+        assert_(not np.isscalar(random.choice([1, 2], s, replace=True)))
+        assert_(random.choice([None], s, replace=True).ndim == 0)
+        a = np.array([1, 2])
+        arr = np.empty(1, dtype=object)
+        arr[0] = a
+        assert_(random.choice(arr, s, replace=True).item() is a)
+
+        # Check multi dimensional array
+        s = (2, 3)
+        p = [0.1, 0.1, 0.1, 0.1, 0.4, 0.2]
+        assert_equal(random.choice(6, s, replace=True).shape, s)
+        assert_equal(random.choice(6, s, replace=False).shape, s)
+        assert_equal(random.choice(6, s, replace=True, p=p).shape, s)
+        assert_equal(random.choice(6, s, replace=False, p=p).shape, s)
+        assert_equal(random.choice(np.arange(6), s, replace=True).shape, s)
+
+        # Check zero-size
+        assert_equal(random.integers(0, 0, size=(3, 0, 4)).shape, (3, 0, 4))
+        assert_equal(random.integers(0, -10, size=0).shape, (0,))
+        assert_equal(random.integers(10, 10, size=0).shape, (0,))
+        assert_equal(random.choice(0, size=0).shape, (0,))
+        assert_equal(random.choice([], size=(0,)).shape, (0,))
+        assert_equal(random.choice(['a', 'b'], size=(3, 0, 4)).shape,
+                     (3, 0, 4))
+        assert_raises(ValueError, random.choice, [], 10)
+
+    def test_choice_nan_probabilities(self):
+        a = np.array([42, 1, 2])
+        p = [None, None, None]
+        assert_raises(ValueError, random.choice, a, p=p)
+
+    def test_choice_p_non_contiguous(self):
+        p = np.ones(10) / 5
+        p[1::2] = 3.0
+        random = Generator(MT19937(self.seed))
+        non_contig = random.choice(5, 3, p=p[::2])
+        random = Generator(MT19937(self.seed))
+        contig = random.choice(5, 3, p=np.ascontiguousarray(p[::2]))
+        assert_array_equal(non_contig, contig)
+
+    def test_choice_return_type(self):
+        # gh 9867
+        p = np.ones(4) / 4.
+        actual = random.choice(4, 2)
+        assert actual.dtype == np.int64
+        actual = random.choice(4, 2, replace=False)
+        assert actual.dtype == np.int64
+        actual = random.choice(4, 2, p=p)
+        assert actual.dtype == np.int64
+        actual = random.choice(4, 2, p=p, replace=False)
+        assert actual.dtype == np.int64
+
+    def test_choice_large_sample(self):
+        choice_hash = '4266599d12bfcfb815213303432341c06b4349f5455890446578877bb322e222'
+        random = Generator(MT19937(self.seed))
+        actual = random.choice(10000, 5000, replace=False)
+        if sys.byteorder != 'little':
+            actual = actual.byteswap()
+        res = hashlib.sha256(actual.view(np.int8)).hexdigest()
+        assert_(choice_hash == res)
+
+    def test_bytes(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.bytes(10)
+        desired = b'\x86\xf0\xd4\x18\xe1\x81\t8%\xdd'
+        assert_equal(actual, desired)
+
+    def test_shuffle(self):
+        # Test lists, arrays (of various dtypes), and multidimensional versions
+        # of both, c-contiguous or not:
+        for conv in [lambda x: np.array([]),
+                     lambda x: x,
+                     lambda x: np.asarray(x).astype(np.int8),
+                     lambda x: np.asarray(x).astype(np.float32),
+                     lambda x: np.asarray(x).astype(np.complex64),
+                     lambda x: np.asarray(x).astype(object),
+                     lambda x: [(i, i) for i in x],
+                     lambda x: np.asarray([[i, i] for i in x]),
+                     lambda x: np.vstack([x, x]).T,
+                     # gh-11442
+                     lambda x: (np.asarray([(i, i) for i in x],
+                                           [("a", int), ("b", int)])
+                                .view(np.recarray)),
+                     # gh-4270
+                     lambda x: np.asarray([(i, i) for i in x],
+                                          [("a", object, (1,)),
+                                           ("b", np.int32, (1,))])]:
+            random = Generator(MT19937(self.seed))
+            alist = conv([1, 2, 3, 4, 5, 6, 7, 8, 9, 0])
+            random.shuffle(alist)
+            actual = alist
+            desired = conv([4, 1, 9, 8, 0, 5, 3, 6, 2, 7])
+            assert_array_equal(actual, desired)
+
+    def test_shuffle_custom_axis(self):
+        random = Generator(MT19937(self.seed))
+        actual = np.arange(16).reshape((4, 4))
+        random.shuffle(actual, axis=1)
+        desired = np.array([[ 0,  3,  1,  2],
+                            [ 4,  7,  5,  6],
+                            [ 8, 11,  9, 10],
+                            [12, 15, 13, 14]])
+        assert_array_equal(actual, desired)
+        random = Generator(MT19937(self.seed))
+        actual = np.arange(16).reshape((4, 4))
+        random.shuffle(actual, axis=-1)
+        assert_array_equal(actual, desired)
+
+    def test_shuffle_custom_axis_empty(self):
+        random = Generator(MT19937(self.seed))
+        desired = np.array([]).reshape((0, 6))
+        for axis in (0, 1):
+            actual = np.array([]).reshape((0, 6))
+            random.shuffle(actual, axis=axis)
+            assert_array_equal(actual, desired)
+
+    def test_shuffle_axis_nonsquare(self):
+        y1 = np.arange(20).reshape(2, 10)
+        y2 = y1.copy()
+        random = Generator(MT19937(self.seed))
+        random.shuffle(y1, axis=1)
+        random = Generator(MT19937(self.seed))
+        random.shuffle(y2.T)
+        assert_array_equal(y1, y2)
+
+    def test_shuffle_masked(self):
+        # gh-3263
+        a = np.ma.masked_values(np.reshape(range(20), (5, 4)) % 3 - 1, -1)
+        b = np.ma.masked_values(np.arange(20) % 3 - 1, -1)
+        a_orig = a.copy()
+        b_orig = b.copy()
+        for i in range(50):
+            random.shuffle(a)
+            assert_equal(
+                sorted(a.data[~a.mask]), sorted(a_orig.data[~a_orig.mask]))
+            random.shuffle(b)
+            assert_equal(
+                sorted(b.data[~b.mask]), sorted(b_orig.data[~b_orig.mask]))
+
+    def test_shuffle_exceptions(self):
+        random = Generator(MT19937(self.seed))
+        arr = np.arange(10)
+        assert_raises(np.AxisError, random.shuffle, arr, 1)
+        arr = np.arange(9).reshape((3, 3))
+        assert_raises(np.AxisError, random.shuffle, arr, 3)
+        assert_raises(TypeError, random.shuffle, arr, slice(1, 2, None))
+        arr = [[1, 2, 3], [4, 5, 6]]
+        assert_raises(NotImplementedError, random.shuffle, arr, 1)
+
+        arr = np.array(3)
+        assert_raises(TypeError, random.shuffle, arr)
+        arr = np.ones((3, 2))
+        assert_raises(np.AxisError, random.shuffle, arr, 2)
+
+    def test_shuffle_not_writeable(self):
+        random = Generator(MT19937(self.seed))
+        a = np.zeros(5)
+        a.flags.writeable = False
+        with pytest.raises(ValueError, match='read-only'):
+            random.shuffle(a)
+
+    def test_permutation(self):
+        random = Generator(MT19937(self.seed))
+        alist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
+        actual = random.permutation(alist)
+        desired = [4, 1, 9, 8, 0, 5, 3, 6, 2, 7]
+        assert_array_equal(actual, desired)
+
+        random = Generator(MT19937(self.seed))
+        arr_2d = np.atleast_2d([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]).T
+        actual = random.permutation(arr_2d)
+        assert_array_equal(actual, np.atleast_2d(desired).T)
+
+        bad_x_str = "abcd"
+        assert_raises(np.AxisError, random.permutation, bad_x_str)
+
+        bad_x_float = 1.2
+        assert_raises(np.AxisError, random.permutation, bad_x_float)
+
+        random = Generator(MT19937(self.seed))
+        integer_val = 10
+        desired = [3, 0, 8, 7, 9, 4, 2, 5, 1, 6]
+
+        actual = random.permutation(integer_val)
+        assert_array_equal(actual, desired)
+
+    def test_permutation_custom_axis(self):
+        a = np.arange(16).reshape((4, 4))
+        desired = np.array([[ 0,  3,  1,  2],
+                            [ 4,  7,  5,  6],
+                            [ 8, 11,  9, 10],
+                            [12, 15, 13, 14]])
+        random = Generator(MT19937(self.seed))
+        actual = random.permutation(a, axis=1)
+        assert_array_equal(actual, desired)
+        random = Generator(MT19937(self.seed))
+        actual = random.permutation(a, axis=-1)
+        assert_array_equal(actual, desired)
+
+    def test_permutation_exceptions(self):
+        random = Generator(MT19937(self.seed))
+        arr = np.arange(10)
+        assert_raises(np.AxisError, random.permutation, arr, 1)
+        arr = np.arange(9).reshape((3, 3))
+        assert_raises(np.AxisError, random.permutation, arr, 3)
+        assert_raises(TypeError, random.permutation, arr, slice(1, 2, None))
+
+    @pytest.mark.parametrize("dtype", [int, object])
+    @pytest.mark.parametrize("axis, expected",
+                             [(None, np.array([[3, 7, 0, 9, 10, 11],
+                                               [8, 4, 2, 5,  1,  6]])),
+                              (0, np.array([[6, 1, 2, 9, 10, 11],
+                                            [0, 7, 8, 3,  4,  5]])),
+                              (1, np.array([[ 5, 3,  4, 0, 2, 1],
+                                            [11, 9, 10, 6, 8, 7]]))])
+    def test_permuted(self, dtype, axis, expected):
+        random = Generator(MT19937(self.seed))
+        x = np.arange(12).reshape(2, 6).astype(dtype)
+        random.permuted(x, axis=axis, out=x)
+        assert_array_equal(x, expected)
+
+        random = Generator(MT19937(self.seed))
+        x = np.arange(12).reshape(2, 6).astype(dtype)
+        y = random.permuted(x, axis=axis)
+        assert y.dtype == dtype
+        assert_array_equal(y, expected)
+
+    def test_permuted_with_strides(self):
+        random = Generator(MT19937(self.seed))
+        x0 = np.arange(22).reshape(2, 11)
+        x1 = x0.copy()
+        x = x0[:, ::3]
+        y = random.permuted(x, axis=1, out=x)
+        expected = np.array([[0, 9, 3, 6],
+                             [14, 20, 11, 17]])
+        assert_array_equal(y, expected)
+        x1[:, ::3] = expected
+        # Verify that the original x0 was modified in-place as expected.
+        assert_array_equal(x1, x0)
+
+    def test_permuted_empty(self):
+        y = random.permuted([])
+        assert_array_equal(y, [])
+
+    @pytest.mark.parametrize('outshape', [(2, 3), 5])
+    def test_permuted_out_with_wrong_shape(self, outshape):
+        a = np.array([1, 2, 3])
+        out = np.zeros(outshape, dtype=a.dtype)
+        with pytest.raises(ValueError, match='same shape'):
+            random.permuted(a, out=out)
+
+    def test_permuted_out_with_wrong_type(self):
+        out = np.zeros((3, 5), dtype=np.int32)
+        x = np.ones((3, 5))
+        with pytest.raises(TypeError, match='Cannot cast'):
+            random.permuted(x, axis=1, out=out)
+
+    def test_permuted_not_writeable(self):
+        x = np.zeros((2, 5))
+        x.flags.writeable = False
+        with pytest.raises(ValueError, match='read-only'):
+            random.permuted(x, axis=1, out=x)
+
+    def test_beta(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.beta(.1, .9, size=(3, 2))
+        desired = np.array(
+            [[1.083029353267698e-10, 2.449965303168024e-11],
+             [2.397085162969853e-02, 3.590779671820755e-08],
+             [2.830254190078299e-04, 1.744709918330393e-01]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_binomial(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.binomial(100.123, .456, size=(3, 2))
+        desired = np.array([[42, 41],
+                            [42, 48],
+                            [44, 50]])
+        assert_array_equal(actual, desired)
+
+        random = Generator(MT19937(self.seed))
+        actual = random.binomial(100.123, .456)
+        desired = 42
+        assert_array_equal(actual, desired)
+
+    def test_chisquare(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.chisquare(50, size=(3, 2))
+        desired = np.array([[32.9850547060149, 39.0219480493301],
+                            [56.2006134779419, 57.3474165711485],
+                            [55.4243733880198, 55.4209797925213]])
+        assert_array_almost_equal(actual, desired, decimal=13)
+
+    def test_dirichlet(self):
+        random = Generator(MT19937(self.seed))
+        alpha = np.array([51.72840233779265162, 39.74494232180943953])
+        actual = random.dirichlet(alpha, size=(3, 2))
+        desired = np.array([[[0.5439892869558927,  0.45601071304410745],
+                             [0.5588917345860708,  0.4411082654139292 ]],
+                            [[0.5632074165063435,  0.43679258349365657],
+                             [0.54862581112627,    0.45137418887373015]],
+                            [[0.49961831357047226, 0.5003816864295278 ],
+                             [0.52374806183482,    0.47625193816517997]]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+        bad_alpha = np.array([5.4e-01, -1.0e-16])
+        assert_raises(ValueError, random.dirichlet, bad_alpha)
+
+        random = Generator(MT19937(self.seed))
+        alpha = np.array([51.72840233779265162, 39.74494232180943953])
+        actual = random.dirichlet(alpha)
+        assert_array_almost_equal(actual, desired[0, 0], decimal=15)
+
+    def test_dirichlet_size(self):
+        # gh-3173
+        p = np.array([51.72840233779265162, 39.74494232180943953])
+        assert_equal(random.dirichlet(p, np.uint32(1)).shape, (1, 2))
+        assert_equal(random.dirichlet(p, np.uint32(1)).shape, (1, 2))
+        assert_equal(random.dirichlet(p, np.uint32(1)).shape, (1, 2))
+        assert_equal(random.dirichlet(p, [2, 2]).shape, (2, 2, 2))
+        assert_equal(random.dirichlet(p, (2, 2)).shape, (2, 2, 2))
+        assert_equal(random.dirichlet(p, np.array((2, 2))).shape, (2, 2, 2))
+
+        assert_raises(TypeError, random.dirichlet, p, float(1))
+
+    def test_dirichlet_bad_alpha(self):
+        # gh-2089
+        alpha = np.array([5.4e-01, -1.0e-16])
+        assert_raises(ValueError, random.dirichlet, alpha)
+
+        # gh-15876
+        assert_raises(ValueError, random.dirichlet, [[5, 1]])
+        assert_raises(ValueError, random.dirichlet, [[5], [1]])
+        assert_raises(ValueError, random.dirichlet, [[[5], [1]], [[1], [5]]])
+        assert_raises(ValueError, random.dirichlet, np.array([[5, 1], [1, 5]]))
+
+    def test_dirichlet_alpha_non_contiguous(self):
+        a = np.array([51.72840233779265162, -1.0, 39.74494232180943953])
+        alpha = a[::2]
+        random = Generator(MT19937(self.seed))
+        non_contig = random.dirichlet(alpha, size=(3, 2))
+        random = Generator(MT19937(self.seed))
+        contig = random.dirichlet(np.ascontiguousarray(alpha),
+                                  size=(3, 2))
+        assert_array_almost_equal(non_contig, contig)
+
+    def test_dirichlet_small_alpha(self):
+        eps = 1.0e-9  # 1.0e-10 -> runtime x 10; 1e-11 -> runtime x 200, etc.
+        alpha = eps * np.array([1., 1.0e-3])
+        random = Generator(MT19937(self.seed))
+        actual = random.dirichlet(alpha, size=(3, 2))
+        expected = np.array([
+            [[1., 0.],
+             [1., 0.]],
+            [[1., 0.],
+             [1., 0.]],
+            [[1., 0.],
+             [1., 0.]]
+        ])
+        assert_array_almost_equal(actual, expected, decimal=15)
+
+    @pytest.mark.slow
+    def test_dirichlet_moderately_small_alpha(self):
+        # Use alpha.max() < 0.1 to trigger stick breaking code path
+        alpha = np.array([0.02, 0.04, 0.03])
+        exact_mean = alpha / alpha.sum()
+        random = Generator(MT19937(self.seed))
+        sample = random.dirichlet(alpha, size=20000000)
+        sample_mean = sample.mean(axis=0)
+        assert_allclose(sample_mean, exact_mean, rtol=1e-3)
+
+    # This set of parameters includes inputs with alpha.max() >= 0.1 and
+    # alpha.max() < 0.1 to exercise both generation methods within the
+    # dirichlet code.
+    @pytest.mark.parametrize(
+        'alpha',
+        [[5, 9, 0, 8],
+         [0.5, 0, 0, 0],
+         [1, 5, 0, 0, 1.5, 0, 0, 0],
+         [0.01, 0.03, 0, 0.005],
+         [1e-5, 0, 0, 0],
+         [0.002, 0.015, 0, 0, 0.04, 0, 0, 0],
+         [0.0],
+         [0, 0, 0]],
+    )
+    def test_dirichlet_multiple_zeros_in_alpha(self, alpha):
+        alpha = np.array(alpha)
+        y = random.dirichlet(alpha)
+        assert_equal(y[alpha == 0], 0.0)
+
+    def test_exponential(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.exponential(1.1234, size=(3, 2))
+        desired = np.array([[0.098845481066258, 1.560752510746964],
+                            [0.075730916041636, 1.769098974710777],
+                            [1.488602544592235, 2.49684815275751 ]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_exponential_0(self):
+        assert_equal(random.exponential(scale=0), 0)
+        assert_raises(ValueError, random.exponential, scale=-0.)
+
+    def test_f(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.f(12, 77, size=(3, 2))
+        desired = np.array([[0.461720027077085, 1.100441958872451],
+                            [1.100337455217484, 0.91421736740018 ],
+                            [0.500811891303113, 0.826802454552058]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_gamma(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.gamma(5, 3, size=(3, 2))
+        desired = np.array([[ 5.03850858902096,  7.9228656732049 ],
+                            [18.73983605132985, 19.57961681699238],
+                            [18.17897755150825, 18.17653912505234]])
+        assert_array_almost_equal(actual, desired, decimal=14)
+
+    def test_gamma_0(self):
+        assert_equal(random.gamma(shape=0, scale=0), 0)
+        assert_raises(ValueError, random.gamma, shape=-0., scale=-0.)
+
+    def test_geometric(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.geometric(.123456789, size=(3, 2))
+        desired = np.array([[1, 11],
+                            [1, 12],
+                            [11, 17]])
+        assert_array_equal(actual, desired)
+
+    def test_geometric_exceptions(self):
+        assert_raises(ValueError, random.geometric, 1.1)
+        assert_raises(ValueError, random.geometric, [1.1] * 10)
+        assert_raises(ValueError, random.geometric, -0.1)
+        assert_raises(ValueError, random.geometric, [-0.1] * 10)
+        with np.errstate(invalid='ignore'):
+            assert_raises(ValueError, random.geometric, np.nan)
+            assert_raises(ValueError, random.geometric, [np.nan] * 10)
+
+    def test_gumbel(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.gumbel(loc=.123456789, scale=2.0, size=(3, 2))
+        desired = np.array([[ 4.688397515056245, -0.289514845417841],
+                            [ 4.981176042584683, -0.633224272589149],
+                            [-0.055915275687488, -0.333962478257953]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_gumbel_0(self):
+        assert_equal(random.gumbel(scale=0), 0)
+        assert_raises(ValueError, random.gumbel, scale=-0.)
+
+    def test_hypergeometric(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.hypergeometric(10.1, 5.5, 14, size=(3, 2))
+        desired = np.array([[ 9, 9],
+                            [ 9, 9],
+                            [10, 9]])
+        assert_array_equal(actual, desired)
+
+        # Test nbad = 0
+        actual = random.hypergeometric(5, 0, 3, size=4)
+        desired = np.array([3, 3, 3, 3])
+        assert_array_equal(actual, desired)
+
+        actual = random.hypergeometric(15, 0, 12, size=4)
+        desired = np.array([12, 12, 12, 12])
+        assert_array_equal(actual, desired)
+
+        # Test ngood = 0
+        actual = random.hypergeometric(0, 5, 3, size=4)
+        desired = np.array([0, 0, 0, 0])
+        assert_array_equal(actual, desired)
+
+        actual = random.hypergeometric(0, 15, 12, size=4)
+        desired = np.array([0, 0, 0, 0])
+        assert_array_equal(actual, desired)
+
+    def test_laplace(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.laplace(loc=.123456789, scale=2.0, size=(3, 2))
+        desired = np.array([[-3.156353949272393,  1.195863024830054],
+                            [-3.435458081645966,  1.656882398925444],
+                            [ 0.924824032467446,  1.251116432209336]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_laplace_0(self):
+        assert_equal(random.laplace(scale=0), 0)
+        assert_raises(ValueError, random.laplace, scale=-0.)
+
+    def test_logistic(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.logistic(loc=.123456789, scale=2.0, size=(3, 2))
+        desired = np.array([[-4.338584631510999,  1.890171436749954],
+                            [-4.64547787337966 ,  2.514545562919217],
+                            [ 1.495389489198666,  1.967827627577474]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_lognormal(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.lognormal(mean=.123456789, sigma=2.0, size=(3, 2))
+        desired = np.array([[ 0.0268252166335, 13.9534486483053],
+                            [ 0.1204014788936,  2.2422077497792],
+                            [ 4.2484199496128, 12.0093343977523]])
+        assert_array_almost_equal(actual, desired, decimal=13)
+
+    def test_lognormal_0(self):
+        assert_equal(random.lognormal(sigma=0), 1)
+        assert_raises(ValueError, random.lognormal, sigma=-0.)
+
+    def test_logseries(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.logseries(p=.923456789, size=(3, 2))
+        desired = np.array([[14, 17],
+                            [3, 18],
+                            [5, 1]])
+        assert_array_equal(actual, desired)
+
+    def test_logseries_zero(self):
+        random = Generator(MT19937(self.seed))
+        assert random.logseries(0) == 1
+
+    @pytest.mark.parametrize("value", [np.nextafter(0., -1), 1., np.nan, 5.])
+    def test_logseries_exceptions(self, value):
+        random = Generator(MT19937(self.seed))
+        with np.errstate(invalid="ignore"):
+            with pytest.raises(ValueError):
+                random.logseries(value)
+            with pytest.raises(ValueError):
+                # contiguous path:
+                random.logseries(np.array([value] * 10))
+            with pytest.raises(ValueError):
+                # non-contiguous path:
+                random.logseries(np.array([value] * 10)[::2])
+
+    def test_multinomial(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.multinomial(20, [1 / 6.] * 6, size=(3, 2))
+        desired = np.array([[[1, 5, 1, 6, 4, 3],
+                             [4, 2, 6, 2, 4, 2]],
+                            [[5, 3, 2, 6, 3, 1],
+                             [4, 4, 0, 2, 3, 7]],
+                            [[6, 3, 1, 5, 3, 2],
+                             [5, 5, 3, 1, 2, 4]]])
+        assert_array_equal(actual, desired)
+
+    @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
+    @pytest.mark.parametrize("method", ["svd", "eigh", "cholesky"])
+    def test_multivariate_normal(self, method):
+        random = Generator(MT19937(self.seed))
+        mean = (.123456789, 10)
+        cov = [[1, 0], [0, 1]]
+        size = (3, 2)
+        actual = random.multivariate_normal(mean, cov, size, method=method)
+        desired = np.array([[[-1.747478062846581,  11.25613495182354  ],
+                             [-0.9967333370066214, 10.342002097029821 ]],
+                            [[ 0.7850019631242964, 11.181113712443013 ],
+                             [ 0.8901349653255224,  8.873825399642492 ]],
+                            [[ 0.7130260107430003,  9.551628690083056 ],
+                             [ 0.7127098726541128, 11.991709234143173 ]]])
+
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+        # Check for default size, was raising deprecation warning
+        actual = random.multivariate_normal(mean, cov, method=method)
+        desired = np.array([0.233278563284287, 9.424140804347195])
+        assert_array_almost_equal(actual, desired, decimal=15)
+        # Check that non symmetric covariance input raises exception when
+        # check_valid='raises' if using default svd method.
+        mean = [0, 0]
+        cov = [[1, 2], [1, 2]]
+        assert_raises(ValueError, random.multivariate_normal, mean, cov,
+                      check_valid='raise')
+
+        # Check that non positive-semidefinite covariance warns with
+        # RuntimeWarning
+        cov = [[1, 2], [2, 1]]
+        assert_warns(RuntimeWarning, random.multivariate_normal, mean, cov)
+        assert_warns(RuntimeWarning, random.multivariate_normal, mean, cov,
+                     method='eigh')
+        assert_raises(LinAlgError, random.multivariate_normal, mean, cov,
+                      method='cholesky')
+
+        # and that it doesn't warn with RuntimeWarning check_valid='ignore'
+        assert_no_warnings(random.multivariate_normal, mean, cov,
+                           check_valid='ignore')
+
+        # and that it raises with RuntimeWarning check_valid='raises'
+        assert_raises(ValueError, random.multivariate_normal, mean, cov,
+                      check_valid='raise')
+        assert_raises(ValueError, random.multivariate_normal, mean, cov,
+                      check_valid='raise', method='eigh')
+
+        # check degenerate samples from singular covariance matrix
+        cov = [[1, 1], [1, 1]]
+        if method in ('svd', 'eigh'):
+            samples = random.multivariate_normal(mean, cov, size=(3, 2),
+                                                 method=method)
+            assert_array_almost_equal(samples[..., 0], samples[..., 1],
+                                      decimal=6)
+        else:
+            assert_raises(LinAlgError, random.multivariate_normal, mean, cov,
+                          method='cholesky')
+
+        cov = np.array([[1, 0.1], [0.1, 1]], dtype=np.float32)
+        with suppress_warnings() as sup:
+            random.multivariate_normal(mean, cov, method=method)
+            w = sup.record(RuntimeWarning)
+            assert len(w) == 0
+
+        mu = np.zeros(2)
+        cov = np.eye(2)
+        assert_raises(ValueError, random.multivariate_normal, mean, cov,
+                      check_valid='other')
+        assert_raises(ValueError, random.multivariate_normal,
+                      np.zeros((2, 1, 1)), cov)
+        assert_raises(ValueError, random.multivariate_normal,
+                      mu, np.empty((3, 2)))
+        assert_raises(ValueError, random.multivariate_normal,
+                      mu, np.eye(3))
+
+    @pytest.mark.parametrize('mean, cov', [([0], [[1+1j]]), ([0j], [[1]])])
+    def test_multivariate_normal_disallow_complex(self, mean, cov):
+        random = Generator(MT19937(self.seed))
+        with pytest.raises(TypeError, match="must not be complex"):
+            random.multivariate_normal(mean, cov)
+
+    @pytest.mark.parametrize("method", ["svd", "eigh", "cholesky"])
+    def test_multivariate_normal_basic_stats(self, method):
+        random = Generator(MT19937(self.seed))
+        n_s = 1000
+        mean = np.array([1, 2])
+        cov = np.array([[2, 1], [1, 2]])
+        s = random.multivariate_normal(mean, cov, size=(n_s,), method=method)
+        s_center = s - mean
+        cov_emp = (s_center.T @ s_center) / (n_s - 1)
+        # these are pretty loose and are only designed to detect major errors
+        assert np.all(np.abs(s_center.mean(-2)) < 0.1)
+        assert np.all(np.abs(cov_emp - cov) < 0.2)
+
+    def test_negative_binomial(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.negative_binomial(n=100, p=.12345, size=(3, 2))
+        desired = np.array([[543, 727],
+                            [775, 760],
+                            [600, 674]])
+        assert_array_equal(actual, desired)
+
+    def test_negative_binomial_exceptions(self):
+        with np.errstate(invalid='ignore'):
+            assert_raises(ValueError, random.negative_binomial, 100, np.nan)
+            assert_raises(ValueError, random.negative_binomial, 100,
+                          [np.nan] * 10)
+
+    def test_negative_binomial_p0_exception(self):
+        # Verify that p=0 raises an exception.
+        with assert_raises(ValueError):
+            x = random.negative_binomial(1, 0)
+
+    def test_negative_binomial_invalid_p_n_combination(self):
+        # Verify that values of p and n that would result in an overflow
+        # or infinite loop raise an exception.
+        with np.errstate(invalid='ignore'):
+            assert_raises(ValueError, random.negative_binomial, 2**62, 0.1)
+            assert_raises(ValueError, random.negative_binomial, [2**62], [0.1])
+
+    def test_noncentral_chisquare(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.noncentral_chisquare(df=5, nonc=5, size=(3, 2))
+        desired = np.array([[ 1.70561552362133, 15.97378184942111],
+                            [13.71483425173724, 20.17859633310629],
+                            [11.3615477156643 ,  3.67891108738029]])
+        assert_array_almost_equal(actual, desired, decimal=14)
+
+        actual = random.noncentral_chisquare(df=.5, nonc=.2, size=(3, 2))
+        desired = np.array([[9.41427665607629e-04, 1.70473157518850e-04],
+                            [1.14554372041263e+00, 1.38187755933435e-03],
+                            [1.90659181905387e+00, 1.21772577941822e+00]])
+        assert_array_almost_equal(actual, desired, decimal=14)
+
+        random = Generator(MT19937(self.seed))
+        actual = random.noncentral_chisquare(df=5, nonc=0, size=(3, 2))
+        desired = np.array([[0.82947954590419, 1.80139670767078],
+                            [6.58720057417794, 7.00491463609814],
+                            [6.31101879073157, 6.30982307753005]])
+        assert_array_almost_equal(actual, desired, decimal=14)
+
+    def test_noncentral_f(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.noncentral_f(dfnum=5, dfden=2, nonc=1,
+                                     size=(3, 2))
+        desired = np.array([[0.060310671139  , 0.23866058175939],
+                            [0.86860246709073, 0.2668510459738 ],
+                            [0.23375780078364, 1.88922102885943]])
+        assert_array_almost_equal(actual, desired, decimal=14)
+
+    def test_noncentral_f_nan(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.noncentral_f(dfnum=5, dfden=2, nonc=np.nan)
+        assert np.isnan(actual)
+
+    def test_normal(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.normal(loc=.123456789, scale=2.0, size=(3, 2))
+        desired = np.array([[-3.618412914693162,  2.635726692647081],
+                            [-2.116923463013243,  0.807460983059643],
+                            [ 1.446547137248593,  2.485684213886024]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_normal_0(self):
+        assert_equal(random.normal(scale=0), 0)
+        assert_raises(ValueError, random.normal, scale=-0.)
+
+    def test_pareto(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.pareto(a=.123456789, size=(3, 2))
+        desired = np.array([[1.0394926776069018e+00, 7.7142534343505773e+04],
+                            [7.2640150889064703e-01, 3.4650454783825594e+05],
+                            [4.5852344481994740e+04, 6.5851383009539105e+07]])
+        # For some reason on 32-bit x86 Ubuntu 12.10 the [1, 0] entry in this
+        # matrix differs by 24 nulps. Discussion:
+        #   https://mail.python.org/pipermail/numpy-discussion/2012-September/063801.html
+        # Consensus is that this is probably some gcc quirk that affects
+        # rounding but not in any important way, so we just use a looser
+        # tolerance on this test:
+        np.testing.assert_array_almost_equal_nulp(actual, desired, nulp=30)
+
+    def test_poisson(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.poisson(lam=.123456789, size=(3, 2))
+        desired = np.array([[0, 0],
+                            [0, 0],
+                            [0, 0]])
+        assert_array_equal(actual, desired)
+
+    def test_poisson_exceptions(self):
+        lambig = np.iinfo('int64').max
+        lamneg = -1
+        assert_raises(ValueError, random.poisson, lamneg)
+        assert_raises(ValueError, random.poisson, [lamneg] * 10)
+        assert_raises(ValueError, random.poisson, lambig)
+        assert_raises(ValueError, random.poisson, [lambig] * 10)
+        with np.errstate(invalid='ignore'):
+            assert_raises(ValueError, random.poisson, np.nan)
+            assert_raises(ValueError, random.poisson, [np.nan] * 10)
+
+    def test_power(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.power(a=.123456789, size=(3, 2))
+        desired = np.array([[1.977857368842754e-09, 9.806792196620341e-02],
+                            [2.482442984543471e-10, 1.527108843266079e-01],
+                            [8.188283434244285e-02, 3.950547209346948e-01]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_rayleigh(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.rayleigh(scale=10, size=(3, 2))
+        desired = np.array([[4.19494429102666, 16.66920198906598],
+                            [3.67184544902662, 17.74695521962917],
+                            [16.27935397855501, 21.08355560691792]])
+        assert_array_almost_equal(actual, desired, decimal=14)
+
+    def test_rayleigh_0(self):
+        assert_equal(random.rayleigh(scale=0), 0)
+        assert_raises(ValueError, random.rayleigh, scale=-0.)
+
+    def test_standard_cauchy(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.standard_cauchy(size=(3, 2))
+        desired = np.array([[-1.489437778266206, -3.275389641569784],
+                            [ 0.560102864910406, -0.680780916282552],
+                            [-1.314912905226277,  0.295852965660225]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_standard_exponential(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.standard_exponential(size=(3, 2), method='inv')
+        desired = np.array([[0.102031839440643, 1.229350298474972],
+                            [0.088137284693098, 1.459859985522667],
+                            [1.093830802293668, 1.256977002164613]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_standard_expoential_type_error(self):
+        assert_raises(TypeError, random.standard_exponential, dtype=np.int32)
+
+    def test_standard_gamma(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.standard_gamma(shape=3, size=(3, 2))
+        desired = np.array([[0.62970724056362, 1.22379851271008],
+                            [3.899412530884  , 4.12479964250139],
+                            [3.74994102464584, 3.74929307690815]])
+        assert_array_almost_equal(actual, desired, decimal=14)
+
+    def test_standard_gammma_scalar_float(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.standard_gamma(3, dtype=np.float32)
+        desired = 2.9242148399353027
+        assert_array_almost_equal(actual, desired, decimal=6)
+
+    def test_standard_gamma_float(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.standard_gamma(shape=3, size=(3, 2))
+        desired = np.array([[0.62971, 1.2238 ],
+                            [3.89941, 4.1248 ],
+                            [3.74994, 3.74929]])
+        assert_array_almost_equal(actual, desired, decimal=5)
+
+    def test_standard_gammma_float_out(self):
+        actual = np.zeros((3, 2), dtype=np.float32)
+        random = Generator(MT19937(self.seed))
+        random.standard_gamma(10.0, out=actual, dtype=np.float32)
+        desired = np.array([[10.14987,  7.87012],
+                             [ 9.46284, 12.56832],
+                             [13.82495,  7.81533]], dtype=np.float32)
+        assert_array_almost_equal(actual, desired, decimal=5)
+
+        random = Generator(MT19937(self.seed))
+        random.standard_gamma(10.0, out=actual, size=(3, 2), dtype=np.float32)
+        assert_array_almost_equal(actual, desired, decimal=5)
+
+    def test_standard_gamma_unknown_type(self):
+        assert_raises(TypeError, random.standard_gamma, 1.,
+                      dtype='int32')
+
+    def test_out_size_mismatch(self):
+        out = np.zeros(10)
+        assert_raises(ValueError, random.standard_gamma, 10.0, size=20,
+                      out=out)
+        assert_raises(ValueError, random.standard_gamma, 10.0, size=(10, 1),
+                      out=out)
+
+    def test_standard_gamma_0(self):
+        assert_equal(random.standard_gamma(shape=0), 0)
+        assert_raises(ValueError, random.standard_gamma, shape=-0.)
+
+    def test_standard_normal(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.standard_normal(size=(3, 2))
+        desired = np.array([[-1.870934851846581,  1.25613495182354 ],
+                            [-1.120190126006621,  0.342002097029821],
+                            [ 0.661545174124296,  1.181113712443012]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_standard_normal_unsupported_type(self):
+        assert_raises(TypeError, random.standard_normal, dtype=np.int32)
+
+    def test_standard_t(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.standard_t(df=10, size=(3, 2))
+        desired = np.array([[-1.484666193042647,  0.30597891831161 ],
+                            [ 1.056684299648085, -0.407312602088507],
+                            [ 0.130704414281157, -2.038053410490321]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_triangular(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.triangular(left=5.12, mode=10.23, right=20.34,
+                                   size=(3, 2))
+        desired = np.array([[ 7.86664070590917, 13.6313848513185 ],
+                            [ 7.68152445215983, 14.36169131136546],
+                            [13.16105603911429, 13.72341621856971]])
+        assert_array_almost_equal(actual, desired, decimal=14)
+
+    def test_uniform(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.uniform(low=1.23, high=10.54, size=(3, 2))
+        desired = np.array([[2.13306255040998 , 7.816987531021207],
+                            [2.015436610109887, 8.377577533009589],
+                            [7.421792588856135, 7.891185744455209]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_uniform_range_bounds(self):
+        fmin = np.finfo('float').min
+        fmax = np.finfo('float').max
+
+        func = random.uniform
+        assert_raises(OverflowError, func, -np.inf, 0)
+        assert_raises(OverflowError, func, 0, np.inf)
+        assert_raises(OverflowError, func, fmin, fmax)
+        assert_raises(OverflowError, func, [-np.inf], [0])
+        assert_raises(OverflowError, func, [0], [np.inf])
+
+        # (fmax / 1e17) - fmin is within range, so this should not throw
+        # account for i386 extended precision DBL_MAX / 1e17 + DBL_MAX >
+        # DBL_MAX by increasing fmin a bit
+        random.uniform(low=np.nextafter(fmin, 1), high=fmax / 1e17)
+
+    def test_uniform_zero_range(self):
+        func = random.uniform
+        result = func(1.5, 1.5)
+        assert_allclose(result, 1.5)
+        result = func([0.0, np.pi], [0.0, np.pi])
+        assert_allclose(result, [0.0, np.pi])
+        result = func([[2145.12], [2145.12]], [2145.12, 2145.12])
+        assert_allclose(result, 2145.12 + np.zeros((2, 2)))
+
+    def test_uniform_neg_range(self):
+        func = random.uniform
+        assert_raises(ValueError, func, 2, 1)
+        assert_raises(ValueError, func,  [1, 2], [1, 1])
+        assert_raises(ValueError, func,  [[0, 1],[2, 3]], 2)
+
+    def test_scalar_exception_propagation(self):
+        # Tests that exceptions are correctly propagated in distributions
+        # when called with objects that throw exceptions when converted to
+        # scalars.
+        #
+        # Regression test for gh: 8865
+
+        class ThrowingFloat(np.ndarray):
+            def __float__(self):
+                raise TypeError
+
+        throwing_float = np.array(1.0).view(ThrowingFloat)
+        assert_raises(TypeError, random.uniform, throwing_float,
+                      throwing_float)
+
+        class ThrowingInteger(np.ndarray):
+            def __int__(self):
+                raise TypeError
+
+        throwing_int = np.array(1).view(ThrowingInteger)
+        assert_raises(TypeError, random.hypergeometric, throwing_int, 1, 1)
+
+    def test_vonmises(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.vonmises(mu=1.23, kappa=1.54, size=(3, 2))
+        desired = np.array([[ 1.107972248690106,  2.841536476232361],
+                            [ 1.832602376042457,  1.945511926976032],
+                            [-0.260147475776542,  2.058047492231698]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_vonmises_small(self):
+        # check infinite loop, gh-4720
+        random = Generator(MT19937(self.seed))
+        r = random.vonmises(mu=0., kappa=1.1e-8, size=10**6)
+        assert_(np.isfinite(r).all())
+
+    def test_vonmises_nan(self):
+        random = Generator(MT19937(self.seed))
+        r = random.vonmises(mu=0., kappa=np.nan)
+        assert_(np.isnan(r))
+
+    @pytest.mark.parametrize("kappa", [1e4, 1e15])
+    def test_vonmises_large_kappa(self, kappa):
+        random = Generator(MT19937(self.seed))
+        rs = RandomState(random.bit_generator)
+        state = random.bit_generator.state
+
+        random_state_vals = rs.vonmises(0, kappa, size=10)
+        random.bit_generator.state = state
+        gen_vals = random.vonmises(0, kappa, size=10)
+        if kappa < 1e6:
+            assert_allclose(random_state_vals, gen_vals)
+        else:
+            assert np.all(random_state_vals != gen_vals)
+
+    @pytest.mark.parametrize("mu", [-7., -np.pi, -3.1, np.pi, 3.2])
+    @pytest.mark.parametrize("kappa", [1e-9, 1e-6, 1, 1e3, 1e15])
+    def test_vonmises_large_kappa_range(self, mu, kappa):
+        random = Generator(MT19937(self.seed))
+        r = random.vonmises(mu, kappa, 50)
+        assert_(np.all(r > -np.pi) and np.all(r <= np.pi))
+
+    def test_wald(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.wald(mean=1.23, scale=1.54, size=(3, 2))
+        desired = np.array([[0.26871721804551, 3.2233942732115 ],
+                            [2.20328374987066, 2.40958405189353],
+                            [2.07093587449261, 0.73073890064369]])
+        assert_array_almost_equal(actual, desired, decimal=14)
+
+    def test_weibull(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.weibull(a=1.23, size=(3, 2))
+        desired = np.array([[0.138613914769468, 1.306463419753191],
+                            [0.111623365934763, 1.446570494646721],
+                            [1.257145775276011, 1.914247725027957]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_weibull_0(self):
+        random = Generator(MT19937(self.seed))
+        assert_equal(random.weibull(a=0, size=12), np.zeros(12))
+        assert_raises(ValueError, random.weibull, a=-0.)
+
+    def test_zipf(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.zipf(a=1.23, size=(3, 2))
+        desired = np.array([[  1,   1],
+                            [ 10, 867],
+                            [354,   2]])
+        assert_array_equal(actual, desired)
+
+
+class TestBroadcast:
+    # tests that functions that broadcast behave
+    # correctly when presented with non-scalar arguments
+    def setup_method(self):
+        self.seed = 123456789
+
+    def test_uniform(self):
+        random = Generator(MT19937(self.seed))
+        low = [0]
+        high = [1]
+        uniform = random.uniform
+        desired = np.array([0.16693771389729, 0.19635129550675, 0.75563050964095])
+
+        random = Generator(MT19937(self.seed))
+        actual = random.uniform(low * 3, high)
+        assert_array_almost_equal(actual, desired, decimal=14)
+
+        random = Generator(MT19937(self.seed))
+        actual = random.uniform(low, high * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+
+    def test_normal(self):
+        loc = [0]
+        scale = [1]
+        bad_scale = [-1]
+        random = Generator(MT19937(self.seed))
+        desired = np.array([-0.38736406738527,  0.79594375042255,  0.0197076236097])
+
+        random = Generator(MT19937(self.seed))
+        actual = random.normal(loc * 3, scale)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, random.normal, loc * 3, bad_scale)
+
+        random = Generator(MT19937(self.seed))
+        normal = random.normal
+        actual = normal(loc, scale * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, normal, loc, bad_scale * 3)
+
+    def test_beta(self):
+        a = [1]
+        b = [2]
+        bad_a = [-1]
+        bad_b = [-2]
+        desired = np.array([0.18719338682602, 0.73234824491364, 0.17928615186455])
+
+        random = Generator(MT19937(self.seed))
+        beta = random.beta
+        actual = beta(a * 3, b)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, beta, bad_a * 3, b)
+        assert_raises(ValueError, beta, a * 3, bad_b)
+
+        random = Generator(MT19937(self.seed))
+        actual = random.beta(a, b * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+
+    def test_exponential(self):
+        scale = [1]
+        bad_scale = [-1]
+        desired = np.array([0.67245993212806, 0.21380495318094, 0.7177848928629])
+
+        random = Generator(MT19937(self.seed))
+        actual = random.exponential(scale * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, random.exponential, bad_scale * 3)
+
+    def test_standard_gamma(self):
+        shape = [1]
+        bad_shape = [-1]
+        desired = np.array([0.67245993212806, 0.21380495318094, 0.7177848928629])
+
+        random = Generator(MT19937(self.seed))
+        std_gamma = random.standard_gamma
+        actual = std_gamma(shape * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, std_gamma, bad_shape * 3)
+
+    def test_gamma(self):
+        shape = [1]
+        scale = [2]
+        bad_shape = [-1]
+        bad_scale = [-2]
+        desired = np.array([1.34491986425611, 0.42760990636187, 1.4355697857258])
+
+        random = Generator(MT19937(self.seed))
+        gamma = random.gamma
+        actual = gamma(shape * 3, scale)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, gamma, bad_shape * 3, scale)
+        assert_raises(ValueError, gamma, shape * 3, bad_scale)
+
+        random = Generator(MT19937(self.seed))
+        gamma = random.gamma
+        actual = gamma(shape, scale * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, gamma, bad_shape, scale * 3)
+        assert_raises(ValueError, gamma, shape, bad_scale * 3)
+
+    def test_f(self):
+        dfnum = [1]
+        dfden = [2]
+        bad_dfnum = [-1]
+        bad_dfden = [-2]
+        desired = np.array([0.07765056244107, 7.72951397913186, 0.05786093891763])
+
+        random = Generator(MT19937(self.seed))
+        f = random.f
+        actual = f(dfnum * 3, dfden)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, f, bad_dfnum * 3, dfden)
+        assert_raises(ValueError, f, dfnum * 3, bad_dfden)
+
+        random = Generator(MT19937(self.seed))
+        f = random.f
+        actual = f(dfnum, dfden * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, f, bad_dfnum, dfden * 3)
+        assert_raises(ValueError, f, dfnum, bad_dfden * 3)
+
+    def test_noncentral_f(self):
+        dfnum = [2]
+        dfden = [3]
+        nonc = [4]
+        bad_dfnum = [0]
+        bad_dfden = [-1]
+        bad_nonc = [-2]
+        desired = np.array([2.02434240411421, 12.91838601070124, 1.24395160354629])
+
+        random = Generator(MT19937(self.seed))
+        nonc_f = random.noncentral_f
+        actual = nonc_f(dfnum * 3, dfden, nonc)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert np.all(np.isnan(nonc_f(dfnum, dfden, [np.nan] * 3)))
+
+        assert_raises(ValueError, nonc_f, bad_dfnum * 3, dfden, nonc)
+        assert_raises(ValueError, nonc_f, dfnum * 3, bad_dfden, nonc)
+        assert_raises(ValueError, nonc_f, dfnum * 3, dfden, bad_nonc)
+
+        random = Generator(MT19937(self.seed))
+        nonc_f = random.noncentral_f
+        actual = nonc_f(dfnum, dfden * 3, nonc)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, nonc_f, bad_dfnum, dfden * 3, nonc)
+        assert_raises(ValueError, nonc_f, dfnum, bad_dfden * 3, nonc)
+        assert_raises(ValueError, nonc_f, dfnum, dfden * 3, bad_nonc)
+
+        random = Generator(MT19937(self.seed))
+        nonc_f = random.noncentral_f
+        actual = nonc_f(dfnum, dfden, nonc * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, nonc_f, bad_dfnum, dfden, nonc * 3)
+        assert_raises(ValueError, nonc_f, dfnum, bad_dfden, nonc * 3)
+        assert_raises(ValueError, nonc_f, dfnum, dfden, bad_nonc * 3)
+
+    def test_noncentral_f_small_df(self):
+        random = Generator(MT19937(self.seed))
+        desired = np.array([0.04714867120827, 0.1239390327694])
+        actual = random.noncentral_f(0.9, 0.9, 2, size=2)
+        assert_array_almost_equal(actual, desired, decimal=14)
+
+    def test_chisquare(self):
+        df = [1]
+        bad_df = [-1]
+        desired = np.array([0.05573640064251, 1.47220224353539, 2.9469379318589])
+
+        random = Generator(MT19937(self.seed))
+        actual = random.chisquare(df * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, random.chisquare, bad_df * 3)
+
+    def test_noncentral_chisquare(self):
+        df = [1]
+        nonc = [2]
+        bad_df = [-1]
+        bad_nonc = [-2]
+        desired = np.array([0.07710766249436, 5.27829115110304, 0.630732147399])
+
+        random = Generator(MT19937(self.seed))
+        nonc_chi = random.noncentral_chisquare
+        actual = nonc_chi(df * 3, nonc)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, nonc_chi, bad_df * 3, nonc)
+        assert_raises(ValueError, nonc_chi, df * 3, bad_nonc)
+
+        random = Generator(MT19937(self.seed))
+        nonc_chi = random.noncentral_chisquare
+        actual = nonc_chi(df, nonc * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, nonc_chi, bad_df, nonc * 3)
+        assert_raises(ValueError, nonc_chi, df, bad_nonc * 3)
+
+    def test_standard_t(self):
+        df = [1]
+        bad_df = [-1]
+        desired = np.array([-1.39498829447098, -1.23058658835223, 0.17207021065983])
+
+        random = Generator(MT19937(self.seed))
+        actual = random.standard_t(df * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, random.standard_t, bad_df * 3)
+
+    def test_vonmises(self):
+        mu = [2]
+        kappa = [1]
+        bad_kappa = [-1]
+        desired = np.array([2.25935584988528, 2.23326261461399, -2.84152146503326])
+
+        random = Generator(MT19937(self.seed))
+        actual = random.vonmises(mu * 3, kappa)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, random.vonmises, mu * 3, bad_kappa)
+
+        random = Generator(MT19937(self.seed))
+        actual = random.vonmises(mu, kappa * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, random.vonmises, mu, bad_kappa * 3)
+
+    def test_pareto(self):
+        a = [1]
+        bad_a = [-1]
+        desired = np.array([0.95905052946317, 0.2383810889437 , 1.04988745750013])
+
+        random = Generator(MT19937(self.seed))
+        actual = random.pareto(a * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, random.pareto, bad_a * 3)
+
+    def test_weibull(self):
+        a = [1]
+        bad_a = [-1]
+        desired = np.array([0.67245993212806, 0.21380495318094, 0.7177848928629])
+
+        random = Generator(MT19937(self.seed))
+        actual = random.weibull(a * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, random.weibull, bad_a * 3)
+
+    def test_power(self):
+        a = [1]
+        bad_a = [-1]
+        desired = np.array([0.48954864361052, 0.19249412888486, 0.51216834058807])
+
+        random = Generator(MT19937(self.seed))
+        actual = random.power(a * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, random.power, bad_a * 3)
+
+    def test_laplace(self):
+        loc = [0]
+        scale = [1]
+        bad_scale = [-1]
+        desired = np.array([-1.09698732625119, -0.93470271947368, 0.71592671378202])
+
+        random = Generator(MT19937(self.seed))
+        laplace = random.laplace
+        actual = laplace(loc * 3, scale)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, laplace, loc * 3, bad_scale)
+
+        random = Generator(MT19937(self.seed))
+        laplace = random.laplace
+        actual = laplace(loc, scale * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, laplace, loc, bad_scale * 3)
+
+    def test_gumbel(self):
+        loc = [0]
+        scale = [1]
+        bad_scale = [-1]
+        desired = np.array([1.70020068231762, 1.52054354273631, -0.34293267607081])
+
+        random = Generator(MT19937(self.seed))
+        gumbel = random.gumbel
+        actual = gumbel(loc * 3, scale)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, gumbel, loc * 3, bad_scale)
+
+        random = Generator(MT19937(self.seed))
+        gumbel = random.gumbel
+        actual = gumbel(loc, scale * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, gumbel, loc, bad_scale * 3)
+
+    def test_logistic(self):
+        loc = [0]
+        scale = [1]
+        bad_scale = [-1]
+        desired = np.array([-1.607487640433, -1.40925686003678, 1.12887112820397])
+
+        random = Generator(MT19937(self.seed))
+        actual = random.logistic(loc * 3, scale)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, random.logistic, loc * 3, bad_scale)
+
+        random = Generator(MT19937(self.seed))
+        actual = random.logistic(loc, scale * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, random.logistic, loc, bad_scale * 3)
+        assert_equal(random.logistic(1.0, 0.0), 1.0)
+
+    def test_lognormal(self):
+        mean = [0]
+        sigma = [1]
+        bad_sigma = [-1]
+        desired = np.array([0.67884390500697, 2.21653186290321, 1.01990310084276])
+
+        random = Generator(MT19937(self.seed))
+        lognormal = random.lognormal
+        actual = lognormal(mean * 3, sigma)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, lognormal, mean * 3, bad_sigma)
+
+        random = Generator(MT19937(self.seed))
+        actual = random.lognormal(mean, sigma * 3)
+        assert_raises(ValueError, random.lognormal, mean, bad_sigma * 3)
+
+    def test_rayleigh(self):
+        scale = [1]
+        bad_scale = [-1]
+        desired = np.array(
+            [1.1597068009872629,
+             0.6539188836253857,
+             1.1981526554349398]
+        )
+
+        random = Generator(MT19937(self.seed))
+        actual = random.rayleigh(scale * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, random.rayleigh, bad_scale * 3)
+
+    def test_wald(self):
+        mean = [0.5]
+        scale = [1]
+        bad_mean = [0]
+        bad_scale = [-2]
+        desired = np.array([0.38052407392905, 0.50701641508592, 0.484935249864])
+
+        random = Generator(MT19937(self.seed))
+        actual = random.wald(mean * 3, scale)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, random.wald, bad_mean * 3, scale)
+        assert_raises(ValueError, random.wald, mean * 3, bad_scale)
+
+        random = Generator(MT19937(self.seed))
+        actual = random.wald(mean, scale * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, random.wald, bad_mean, scale * 3)
+        assert_raises(ValueError, random.wald, mean, bad_scale * 3)
+
+    def test_triangular(self):
+        left = [1]
+        right = [3]
+        mode = [2]
+        bad_left_one = [3]
+        bad_mode_one = [4]
+        bad_left_two, bad_mode_two = right * 2
+        desired = np.array([1.57781954604754, 1.62665986867957, 2.30090130831326])
+
+        random = Generator(MT19937(self.seed))
+        triangular = random.triangular
+        actual = triangular(left * 3, mode, right)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, triangular, bad_left_one * 3, mode, right)
+        assert_raises(ValueError, triangular, left * 3, bad_mode_one, right)
+        assert_raises(ValueError, triangular, bad_left_two * 3, bad_mode_two,
+                      right)
+
+        random = Generator(MT19937(self.seed))
+        triangular = random.triangular
+        actual = triangular(left, mode * 3, right)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, triangular, bad_left_one, mode * 3, right)
+        assert_raises(ValueError, triangular, left, bad_mode_one * 3, right)
+        assert_raises(ValueError, triangular, bad_left_two, bad_mode_two * 3,
+                      right)
+
+        random = Generator(MT19937(self.seed))
+        triangular = random.triangular
+        actual = triangular(left, mode, right * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, triangular, bad_left_one, mode, right * 3)
+        assert_raises(ValueError, triangular, left, bad_mode_one, right * 3)
+        assert_raises(ValueError, triangular, bad_left_two, bad_mode_two,
+                      right * 3)
+
+        assert_raises(ValueError, triangular, 10., 0., 20.)
+        assert_raises(ValueError, triangular, 10., 25., 20.)
+        assert_raises(ValueError, triangular, 10., 10., 10.)
+
+    def test_binomial(self):
+        n = [1]
+        p = [0.5]
+        bad_n = [-1]
+        bad_p_one = [-1]
+        bad_p_two = [1.5]
+        desired = np.array([0, 0, 1])
+
+        random = Generator(MT19937(self.seed))
+        binom = random.binomial
+        actual = binom(n * 3, p)
+        assert_array_equal(actual, desired)
+        assert_raises(ValueError, binom, bad_n * 3, p)
+        assert_raises(ValueError, binom, n * 3, bad_p_one)
+        assert_raises(ValueError, binom, n * 3, bad_p_two)
+
+        random = Generator(MT19937(self.seed))
+        actual = random.binomial(n, p * 3)
+        assert_array_equal(actual, desired)
+        assert_raises(ValueError, binom, bad_n, p * 3)
+        assert_raises(ValueError, binom, n, bad_p_one * 3)
+        assert_raises(ValueError, binom, n, bad_p_two * 3)
+
+    def test_negative_binomial(self):
+        n = [1]
+        p = [0.5]
+        bad_n = [-1]
+        bad_p_one = [-1]
+        bad_p_two = [1.5]
+        desired = np.array([0, 2, 1], dtype=np.int64)
+
+        random = Generator(MT19937(self.seed))
+        neg_binom = random.negative_binomial
+        actual = neg_binom(n * 3, p)
+        assert_array_equal(actual, desired)
+        assert_raises(ValueError, neg_binom, bad_n * 3, p)
+        assert_raises(ValueError, neg_binom, n * 3, bad_p_one)
+        assert_raises(ValueError, neg_binom, n * 3, bad_p_two)
+
+        random = Generator(MT19937(self.seed))
+        neg_binom = random.negative_binomial
+        actual = neg_binom(n, p * 3)
+        assert_array_equal(actual, desired)
+        assert_raises(ValueError, neg_binom, bad_n, p * 3)
+        assert_raises(ValueError, neg_binom, n, bad_p_one * 3)
+        assert_raises(ValueError, neg_binom, n, bad_p_two * 3)
+
+    def test_poisson(self):
+
+        lam = [1]
+        bad_lam_one = [-1]
+        desired = np.array([0, 0, 3])
+
+        random = Generator(MT19937(self.seed))
+        max_lam = random._poisson_lam_max
+        bad_lam_two = [max_lam * 2]
+        poisson = random.poisson
+        actual = poisson(lam * 3)
+        assert_array_equal(actual, desired)
+        assert_raises(ValueError, poisson, bad_lam_one * 3)
+        assert_raises(ValueError, poisson, bad_lam_two * 3)
+
+    def test_zipf(self):
+        a = [2]
+        bad_a = [0]
+        desired = np.array([1, 8, 1])
+
+        random = Generator(MT19937(self.seed))
+        zipf = random.zipf
+        actual = zipf(a * 3)
+        assert_array_equal(actual, desired)
+        assert_raises(ValueError, zipf, bad_a * 3)
+        with np.errstate(invalid='ignore'):
+            assert_raises(ValueError, zipf, np.nan)
+            assert_raises(ValueError, zipf, [0, 0, np.nan])
+
+    def test_geometric(self):
+        p = [0.5]
+        bad_p_one = [-1]
+        bad_p_two = [1.5]
+        desired = np.array([1, 1, 3])
+
+        random = Generator(MT19937(self.seed))
+        geometric = random.geometric
+        actual = geometric(p * 3)
+        assert_array_equal(actual, desired)
+        assert_raises(ValueError, geometric, bad_p_one * 3)
+        assert_raises(ValueError, geometric, bad_p_two * 3)
+
+    def test_hypergeometric(self):
+        ngood = [1]
+        nbad = [2]
+        nsample = [2]
+        bad_ngood = [-1]
+        bad_nbad = [-2]
+        bad_nsample_one = [-1]
+        bad_nsample_two = [4]
+        desired = np.array([0, 0, 1])
+
+        random = Generator(MT19937(self.seed))
+        actual = random.hypergeometric(ngood * 3, nbad, nsample)
+        assert_array_equal(actual, desired)
+        assert_raises(ValueError, random.hypergeometric, bad_ngood * 3, nbad, nsample)
+        assert_raises(ValueError, random.hypergeometric, ngood * 3, bad_nbad, nsample)
+        assert_raises(ValueError, random.hypergeometric, ngood * 3, nbad, bad_nsample_one)
+        assert_raises(ValueError, random.hypergeometric, ngood * 3, nbad, bad_nsample_two)
+
+        random = Generator(MT19937(self.seed))
+        actual = random.hypergeometric(ngood, nbad * 3, nsample)
+        assert_array_equal(actual, desired)
+        assert_raises(ValueError, random.hypergeometric, bad_ngood, nbad * 3, nsample)
+        assert_raises(ValueError, random.hypergeometric, ngood, bad_nbad * 3, nsample)
+        assert_raises(ValueError, random.hypergeometric, ngood, nbad * 3, bad_nsample_one)
+        assert_raises(ValueError, random.hypergeometric, ngood, nbad * 3, bad_nsample_two)
+
+        random = Generator(MT19937(self.seed))
+        hypergeom = random.hypergeometric
+        actual = hypergeom(ngood, nbad, nsample * 3)
+        assert_array_equal(actual, desired)
+        assert_raises(ValueError, hypergeom, bad_ngood, nbad, nsample * 3)
+        assert_raises(ValueError, hypergeom, ngood, bad_nbad, nsample * 3)
+        assert_raises(ValueError, hypergeom, ngood, nbad, bad_nsample_one * 3)
+        assert_raises(ValueError, hypergeom, ngood, nbad, bad_nsample_two * 3)
+
+        assert_raises(ValueError, hypergeom, -1, 10, 20)
+        assert_raises(ValueError, hypergeom, 10, -1, 20)
+        assert_raises(ValueError, hypergeom, 10, 10, -1)
+        assert_raises(ValueError, hypergeom, 10, 10, 25)
+
+        # ValueError for arguments that are too big.
+        assert_raises(ValueError, hypergeom, 2**30, 10, 20)
+        assert_raises(ValueError, hypergeom, 999, 2**31, 50)
+        assert_raises(ValueError, hypergeom, 999, [2**29, 2**30], 1000)
+
+    def test_logseries(self):
+        p = [0.5]
+        bad_p_one = [2]
+        bad_p_two = [-1]
+        desired = np.array([1, 1, 1])
+
+        random = Generator(MT19937(self.seed))
+        logseries = random.logseries
+        actual = logseries(p * 3)
+        assert_array_equal(actual, desired)
+        assert_raises(ValueError, logseries, bad_p_one * 3)
+        assert_raises(ValueError, logseries, bad_p_two * 3)
+
+    def test_multinomial(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.multinomial([5, 20], [1 / 6.] * 6, size=(3, 2))
+        desired = np.array([[[0, 0, 2, 1, 2, 0],
+                             [2, 3, 6, 4, 2, 3]],
+                            [[1, 0, 1, 0, 2, 1],
+                             [7, 2, 2, 1, 4, 4]],
+                            [[0, 2, 0, 1, 2, 0],
+                             [3, 2, 3, 3, 4, 5]]], dtype=np.int64)
+        assert_array_equal(actual, desired)
+
+        random = Generator(MT19937(self.seed))
+        actual = random.multinomial([5, 20], [1 / 6.] * 6)
+        desired = np.array([[0, 0, 2, 1, 2, 0],
+                            [2, 3, 6, 4, 2, 3]], dtype=np.int64)
+        assert_array_equal(actual, desired)
+
+        random = Generator(MT19937(self.seed))
+        actual = random.multinomial([5, 20], [[1 / 6.] * 6] * 2)
+        desired = np.array([[0, 0, 2, 1, 2, 0],
+                            [2, 3, 6, 4, 2, 3]], dtype=np.int64)
+        assert_array_equal(actual, desired)
+
+        random = Generator(MT19937(self.seed))
+        actual = random.multinomial([[5], [20]], [[1 / 6.] * 6] * 2)
+        desired = np.array([[[0, 0, 2, 1, 2, 0],
+                             [0, 0, 2, 1, 1, 1]],
+                            [[4, 2, 3, 3, 5, 3],
+                             [7, 2, 2, 1, 4, 4]]], dtype=np.int64)
+        assert_array_equal(actual, desired)
+
+    @pytest.mark.parametrize("n", [10,
+                                   np.array([10, 10]),
+                                   np.array([[[10]], [[10]]])
+                                   ]
+                             )
+    def test_multinomial_pval_broadcast(self, n):
+        random = Generator(MT19937(self.seed))
+        pvals = np.array([1 / 4] * 4)
+        actual = random.multinomial(n, pvals)
+        n_shape = tuple() if isinstance(n, int) else n.shape
+        expected_shape = n_shape + (4,)
+        assert actual.shape == expected_shape
+        pvals = np.vstack([pvals, pvals])
+        actual = random.multinomial(n, pvals)
+        expected_shape = np.broadcast_shapes(n_shape, pvals.shape[:-1]) + (4,)
+        assert actual.shape == expected_shape
+
+        pvals = np.vstack([[pvals], [pvals]])
+        actual = random.multinomial(n, pvals)
+        expected_shape = np.broadcast_shapes(n_shape, pvals.shape[:-1])
+        assert actual.shape == expected_shape + (4,)
+        actual = random.multinomial(n, pvals, size=(3, 2) + expected_shape)
+        assert actual.shape == (3, 2) + expected_shape + (4,)
+
+        with pytest.raises(ValueError):
+            # Ensure that size is not broadcast
+            actual = random.multinomial(n, pvals, size=(1,) * 6)
+
+    def test_invalid_pvals_broadcast(self):
+        random = Generator(MT19937(self.seed))
+        pvals = [[1 / 6] * 6, [1 / 4] * 6]
+        assert_raises(ValueError, random.multinomial, 1, pvals)
+        assert_raises(ValueError, random.multinomial, 6, 0.5)
+
+    def test_empty_outputs(self):
+        random = Generator(MT19937(self.seed))
+        actual = random.multinomial(np.empty((10, 0, 6), "i8"), [1 / 6] * 6)
+        assert actual.shape == (10, 0, 6, 6)
+        actual = random.multinomial(12, np.empty((10, 0, 10)))
+        assert actual.shape == (10, 0, 10)
+        actual = random.multinomial(np.empty((3, 0, 7), "i8"),
+                                    np.empty((3, 0, 7, 4)))
+        assert actual.shape == (3, 0, 7, 4)
+
+
+@pytest.mark.skipif(IS_WASM, reason="can't start thread")
+class TestThread:
+    # make sure each state produces the same sequence even in threads
+    def setup_method(self):
+        self.seeds = range(4)
+
+    def check_function(self, function, sz):
+        from threading import Thread
+
+        out1 = np.empty((len(self.seeds),) + sz)
+        out2 = np.empty((len(self.seeds),) + sz)
+
+        # threaded generation
+        t = [Thread(target=function, args=(Generator(MT19937(s)), o))
+             for s, o in zip(self.seeds, out1)]
+        [x.start() for x in t]
+        [x.join() for x in t]
+
+        # the same serial
+        for s, o in zip(self.seeds, out2):
+            function(Generator(MT19937(s)), o)
+
+        # these platforms change x87 fpu precision mode in threads
+        if np.intp().dtype.itemsize == 4 and sys.platform == "win32":
+            assert_array_almost_equal(out1, out2)
+        else:
+            assert_array_equal(out1, out2)
+
+    def test_normal(self):
+        def gen_random(state, out):
+            out[...] = state.normal(size=10000)
+
+        self.check_function(gen_random, sz=(10000,))
+
+    def test_exp(self):
+        def gen_random(state, out):
+            out[...] = state.exponential(scale=np.ones((100, 1000)))
+
+        self.check_function(gen_random, sz=(100, 1000))
+
+    def test_multinomial(self):
+        def gen_random(state, out):
+            out[...] = state.multinomial(10, [1 / 6.] * 6, size=10000)
+
+        self.check_function(gen_random, sz=(10000, 6))
+
+
+# See Issue #4263
+class TestSingleEltArrayInput:
+    def setup_method(self):
+        self.argOne = np.array([2])
+        self.argTwo = np.array([3])
+        self.argThree = np.array([4])
+        self.tgtShape = (1,)
+
+    def test_one_arg_funcs(self):
+        funcs = (random.exponential, random.standard_gamma,
+                 random.chisquare, random.standard_t,
+                 random.pareto, random.weibull,
+                 random.power, random.rayleigh,
+                 random.poisson, random.zipf,
+                 random.geometric, random.logseries)
+
+        probfuncs = (random.geometric, random.logseries)
+
+        for func in funcs:
+            if func in probfuncs:  # p < 1.0
+                out = func(np.array([0.5]))
+
+            else:
+                out = func(self.argOne)
+
+            assert_equal(out.shape, self.tgtShape)
+
+    def test_two_arg_funcs(self):
+        funcs = (random.uniform, random.normal,
+                 random.beta, random.gamma,
+                 random.f, random.noncentral_chisquare,
+                 random.vonmises, random.laplace,
+                 random.gumbel, random.logistic,
+                 random.lognormal, random.wald,
+                 random.binomial, random.negative_binomial)
+
+        probfuncs = (random.binomial, random.negative_binomial)
+
+        for func in funcs:
+            if func in probfuncs:  # p <= 1
+                argTwo = np.array([0.5])
+
+            else:
+                argTwo = self.argTwo
+
+            out = func(self.argOne, argTwo)
+            assert_equal(out.shape, self.tgtShape)
+
+            out = func(self.argOne[0], argTwo)
+            assert_equal(out.shape, self.tgtShape)
+
+            out = func(self.argOne, argTwo[0])
+            assert_equal(out.shape, self.tgtShape)
+
+    def test_integers(self, endpoint):
+        itype = [np.bool_, np.int8, np.uint8, np.int16, np.uint16,
+                 np.int32, np.uint32, np.int64, np.uint64]
+        func = random.integers
+        high = np.array([1])
+        low = np.array([0])
+
+        for dt in itype:
+            out = func(low, high, endpoint=endpoint, dtype=dt)
+            assert_equal(out.shape, self.tgtShape)
+
+            out = func(low[0], high, endpoint=endpoint, dtype=dt)
+            assert_equal(out.shape, self.tgtShape)
+
+            out = func(low, high[0], endpoint=endpoint, dtype=dt)
+            assert_equal(out.shape, self.tgtShape)
+
+    def test_three_arg_funcs(self):
+        funcs = [random.noncentral_f, random.triangular,
+                 random.hypergeometric]
+
+        for func in funcs:
+            out = func(self.argOne, self.argTwo, self.argThree)
+            assert_equal(out.shape, self.tgtShape)
+
+            out = func(self.argOne[0], self.argTwo, self.argThree)
+            assert_equal(out.shape, self.tgtShape)
+
+            out = func(self.argOne, self.argTwo[0], self.argThree)
+            assert_equal(out.shape, self.tgtShape)
+
+
+@pytest.mark.parametrize("config", JUMP_TEST_DATA)
+def test_jumped(config):
+    # Each config contains the initial seed, a number of raw steps
+    # the sha256 hashes of the initial and the final states' keys and
+    # the position of the initial and the final state.
+    # These were produced using the original C implementation.
+    seed = config["seed"]
+    steps = config["steps"]
+
+    mt19937 = MT19937(seed)
+    # Burn step
+    mt19937.random_raw(steps)
+    key = mt19937.state["state"]["key"]
+    if sys.byteorder == 'big':
+        key = key.byteswap()
+    sha256 = hashlib.sha256(key)
+    assert mt19937.state["state"]["pos"] == config["initial"]["pos"]
+    assert sha256.hexdigest() == config["initial"]["key_sha256"]
+
+    jumped = mt19937.jumped()
+    key = jumped.state["state"]["key"]
+    if sys.byteorder == 'big':
+        key = key.byteswap()
+    sha256 = hashlib.sha256(key)
+    assert jumped.state["state"]["pos"] == config["jumped"]["pos"]
+    assert sha256.hexdigest() == config["jumped"]["key_sha256"]
+
+
+def test_broadcast_size_error():
+    mu = np.ones(3)
+    sigma = np.ones((4, 3))
+    size = (10, 4, 2)
+    assert random.normal(mu, sigma, size=(5, 4, 3)).shape == (5, 4, 3)
+    with pytest.raises(ValueError):
+        random.normal(mu, sigma, size=size)
+    with pytest.raises(ValueError):
+        random.normal(mu, sigma, size=(1, 3))
+    with pytest.raises(ValueError):
+        random.normal(mu, sigma, size=(4, 1, 1))
+    # 1 arg
+    shape = np.ones((4, 3))
+    with pytest.raises(ValueError):
+        random.standard_gamma(shape, size=size)
+    with pytest.raises(ValueError):
+        random.standard_gamma(shape, size=(3,))
+    with pytest.raises(ValueError):
+        random.standard_gamma(shape, size=3)
+    # Check out
+    out = np.empty(size)
+    with pytest.raises(ValueError):
+        random.standard_gamma(shape, out=out)
+
+    # 2 arg
+    with pytest.raises(ValueError):
+        random.binomial(1, [0.3, 0.7], size=(2, 1))
+    with pytest.raises(ValueError):
+        random.binomial([1, 2], 0.3, size=(2, 1))
+    with pytest.raises(ValueError):
+        random.binomial([1, 2], [0.3, 0.7], size=(2, 1))
+    with pytest.raises(ValueError):
+        random.multinomial([2, 2], [.3, .7], size=(2, 1))
+
+    # 3 arg
+    a = random.chisquare(5, size=3)
+    b = random.chisquare(5, size=(4, 3))
+    c = random.chisquare(5, size=(5, 4, 3))
+    assert random.noncentral_f(a, b, c).shape == (5, 4, 3)
+    with pytest.raises(ValueError, match=r"Output size \(6, 5, 1, 1\) is"):
+        random.noncentral_f(a, b, c, size=(6, 5, 1, 1))
+
+
+def test_broadcast_size_scalar():
+    mu = np.ones(3)
+    sigma = np.ones(3)
+    random.normal(mu, sigma, size=3)
+    with pytest.raises(ValueError):
+        random.normal(mu, sigma, size=2)
+
+
+def test_ragged_shuffle():
+    # GH 18142
+    seq = [[], [], 1]
+    gen = Generator(MT19937(0))
+    assert_no_warnings(gen.shuffle, seq)
+    assert seq == [1, [], []]
+
+
+@pytest.mark.parametrize("high", [-2, [-2]])
+@pytest.mark.parametrize("endpoint", [True, False])
+def test_single_arg_integer_exception(high, endpoint):
+    # GH 14333
+    gen = Generator(MT19937(0))
+    msg = 'high < 0' if endpoint else 'high <= 0'
+    with pytest.raises(ValueError, match=msg):
+        gen.integers(high, endpoint=endpoint)
+    msg = 'low > high' if endpoint else 'low >= high'
+    with pytest.raises(ValueError, match=msg):
+        gen.integers(-1, high, endpoint=endpoint)
+    with pytest.raises(ValueError, match=msg):
+        gen.integers([-1], high, endpoint=endpoint)
+
+
+@pytest.mark.parametrize("dtype", ["f4", "f8"])
+def test_c_contig_req_out(dtype):
+    # GH 18704
+    out = np.empty((2, 3), order="F", dtype=dtype)
+    shape = [1, 2, 3]
+    with pytest.raises(ValueError, match="Supplied output array"):
+        random.standard_gamma(shape, out=out, dtype=dtype)
+    with pytest.raises(ValueError, match="Supplied output array"):
+        random.standard_gamma(shape, out=out, size=out.shape, dtype=dtype)
+
+
+@pytest.mark.parametrize("dtype", ["f4", "f8"])
+@pytest.mark.parametrize("order", ["F", "C"])
+@pytest.mark.parametrize("dist", [random.standard_normal, random.random])
+def test_contig_req_out(dist, order, dtype):
+    # GH 18704
+    out = np.empty((2, 3), dtype=dtype, order=order)
+    variates = dist(out=out, dtype=dtype)
+    assert variates is out
+    variates = dist(out=out, dtype=dtype, size=out.shape)
+    assert variates is out
+
+
+def test_generator_ctor_old_style_pickle():
+    rg = np.random.Generator(np.random.PCG64DXSM(0))
+    rg.standard_normal(1)
+    # Directly call reduce which is used in pickling
+    ctor, args, state_a = rg.__reduce__()
+    # Simulate unpickling an old pickle that only has the name
+    assert args[:1] == ("PCG64DXSM",)
+    b = ctor(*args[:1])
+    b.bit_generator.state = state_a
+    state_b = b.bit_generator.state
+    assert state_a == state_b
diff --git a/venv/lib/python3.10/site-packages/numpy/random/tests/test_generator_mt19937_regressions.py b/venv/lib/python3.10/site-packages/numpy/random/tests/test_generator_mt19937_regressions.py
new file mode 100644
index 0000000000000000000000000000000000000000..f16af2b293ce21642c32e90af6f3ed22476158e6
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/numpy/random/tests/test_generator_mt19937_regressions.py
@@ -0,0 +1,165 @@
+from numpy.testing import (assert_, assert_array_equal)
+import numpy as np
+import pytest
+from numpy.random import Generator, MT19937
+
+
+class TestRegression:
+
+    def setup_method(self):
+        self.mt19937 = Generator(MT19937(121263137472525314065))
+
+    def test_vonmises_range(self):
+        # Make sure generated random variables are in [-pi, pi].
+        # Regression test for ticket #986.
+        for mu in np.linspace(-7., 7., 5):
+            r = self.mt19937.vonmises(mu, 1, 50)
+            assert_(np.all(r > -np.pi) and np.all(r <= np.pi))
+
+    def test_hypergeometric_range(self):
+        # Test for ticket #921
+        assert_(np.all(self.mt19937.hypergeometric(3, 18, 11, size=10) < 4))
+        assert_(np.all(self.mt19937.hypergeometric(18, 3, 11, size=10) > 0))
+
+        # Test for ticket #5623
+        args = (2**20 - 2, 2**20 - 2, 2**20 - 2)  # Check for 32-bit systems
+        assert_(self.mt19937.hypergeometric(*args) > 0)
+
+    def test_logseries_convergence(self):
+        # Test for ticket #923
+        N = 1000
+        rvsn = self.mt19937.logseries(0.8, size=N)
+        # these two frequency counts should be close to theoretical
+        # numbers with this large sample
+        # theoretical large N result is 0.49706795
+        freq = np.sum(rvsn == 1) / N
+        msg = f'Frequency was {freq:f}, should be > 0.45'
+        assert_(freq > 0.45, msg)
+        # theoretical large N result is 0.19882718
+        freq = np.sum(rvsn == 2) / N
+        msg = f'Frequency was {freq:f}, should be < 0.23'
+        assert_(freq < 0.23, msg)
+
+    def test_shuffle_mixed_dimension(self):
+        # Test for trac ticket #2074
+        for t in [[1, 2, 3, None],
+                  [(1, 1), (2, 2), (3, 3), None],
+                  [1, (2, 2), (3, 3), None],
+                  [(1, 1), 2, 3, None]]:
+            mt19937 = Generator(MT19937(12345))
+            shuffled = np.array(t, dtype=object)
+            mt19937.shuffle(shuffled)
+            expected = np.array([t[2], t[0], t[3], t[1]], dtype=object)
+            assert_array_equal(np.array(shuffled, dtype=object), expected)
+
+    def test_call_within_randomstate(self):
+        # Check that custom BitGenerator does not call into global state
+        res = np.array([1, 8, 0, 1, 5, 3, 3, 8, 1, 4])
+        for i in range(3):
+            mt19937 = Generator(MT19937(i))
+            m = Generator(MT19937(4321))
+            # If m.state is not honored, the result will change
+            assert_array_equal(m.choice(10, size=10, p=np.ones(10)/10.), res)
+
+    def test_multivariate_normal_size_types(self):
+        # Test for multivariate_normal issue with 'size' argument.
+        # Check that the multivariate_normal size argument can be a
+        # numpy integer.
+        self.mt19937.multivariate_normal([0], [[0]], size=1)
+        self.mt19937.multivariate_normal([0], [[0]], size=np.int_(1))
+        self.mt19937.multivariate_normal([0], [[0]], size=np.int64(1))
+
+    def test_beta_small_parameters(self):
+        # Test that beta with small a and b parameters does not produce
+        # NaNs due to roundoff errors causing 0 / 0, gh-5851
+        x = self.mt19937.beta(0.0001, 0.0001, size=100)
+        assert_(not np.any(np.isnan(x)), 'Nans in mt19937.beta')
+
+    def test_beta_very_small_parameters(self):
+        # gh-24203: beta would hang with very small parameters.
+        self.mt19937.beta(1e-49, 1e-40)
+
+    def test_beta_ridiculously_small_parameters(self):
+        # gh-24266: beta would generate nan when the parameters
+        # were subnormal or a small multiple of the smallest normal.
+        tiny = np.finfo(1.0).tiny
+        x = self.mt19937.beta(tiny/32, tiny/40, size=50)
+        assert not np.any(np.isnan(x))
+
+    def test_choice_sum_of_probs_tolerance(self):
+        # The sum of probs should be 1.0 with some tolerance.
+        # For low precision dtypes the tolerance was too tight.
+        # See numpy github issue 6123.
+        a = [1, 2, 3]
+        counts = [4, 4, 2]
+        for dt in np.float16, np.float32, np.float64:
+            probs = np.array(counts, dtype=dt) / sum(counts)
+            c = self.mt19937.choice(a, p=probs)
+            assert_(c in a)
+            with pytest.raises(ValueError):
+                self.mt19937.choice(a, p=probs*0.9)
+
+    def test_shuffle_of_array_of_different_length_strings(self):
+        # Test that permuting an array of different length strings
+        # will not cause a segfault on garbage collection
+        # Tests gh-7710
+
+        a = np.array(['a', 'a' * 1000])
+
+        for _ in range(100):
+            self.mt19937.shuffle(a)
+
+        # Force Garbage Collection - should not segfault.
+        import gc
+        gc.collect()
+
+    def test_shuffle_of_array_of_objects(self):
+        # Test that permuting an array of objects will not cause
+        # a segfault on garbage collection.
+        # See gh-7719
+        a = np.array([np.arange(1), np.arange(4)], dtype=object)
+
+        for _ in range(1000):
+            self.mt19937.shuffle(a)
+
+        # Force Garbage Collection - should not segfault.
+        import gc
+        gc.collect()
+
+    def test_permutation_subclass(self):
+
+        class N(np.ndarray):
+            pass
+
+        mt19937 = Generator(MT19937(1))
+        orig = np.arange(3).view(N)
+        perm = mt19937.permutation(orig)
+        assert_array_equal(perm, np.array([2, 0, 1]))
+        assert_array_equal(orig, np.arange(3).view(N))
+
+        class M:
+            a = np.arange(5)
+
+            def __array__(self):
+                return self.a
+
+        mt19937 = Generator(MT19937(1))
+        m = M()
+        perm = mt19937.permutation(m)
+        assert_array_equal(perm, np.array([4, 1, 3, 0, 2]))
+        assert_array_equal(m.__array__(), np.arange(5))
+
+    def test_gamma_0(self):
+        assert self.mt19937.standard_gamma(0.0) == 0.0
+        assert_array_equal(self.mt19937.standard_gamma([0.0]), 0.0)
+
+        actual = self.mt19937.standard_gamma([0.0], dtype='float')
+        expected = np.array([0.], dtype=np.float32)
+        assert_array_equal(actual, expected)
+
+    def test_geometric_tiny_prob(self):
+        # Regression test for gh-17007.
+        # When p = 1e-30, the probability that a sample will exceed 2**63-1
+        # is 0.9999999999907766, so we expect the result to be all 2**63-1.
+        assert_array_equal(self.mt19937.geometric(p=1e-30, size=3),
+                           np.iinfo(np.int64).max)
diff --git a/venv/lib/python3.10/site-packages/numpy/random/tests/test_random.py b/venv/lib/python3.10/site-packages/numpy/random/tests/test_random.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d081fe1dbd1c868fe022480330711024804ca20
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/numpy/random/tests/test_random.py
@@ -0,0 +1,1750 @@
+import warnings
+
+import pytest
+
+import numpy as np
+from numpy.testing import (
+        assert_, assert_raises, assert_equal, assert_warns,
+        assert_no_warnings, assert_array_equal, assert_array_almost_equal,
+        suppress_warnings, IS_WASM
+        )
+from numpy import random
+import sys
+
+
+class TestSeed:
+    def test_scalar(self):
+        s = np.random.RandomState(0)
+        assert_equal(s.randint(1000), 684)
+        s = np.random.RandomState(4294967295)
+        assert_equal(s.randint(1000), 419)
+
+    def test_array(self):
+        s = np.random.RandomState(range(10))
+        assert_equal(s.randint(1000), 468)
+        s = np.random.RandomState(np.arange(10))
+        assert_equal(s.randint(1000), 468)
+        s = np.random.RandomState([0])
+        assert_equal(s.randint(1000), 973)
+        s = np.random.RandomState([4294967295])
+        assert_equal(s.randint(1000), 265)
+
+    def test_invalid_scalar(self):
+        # seed must be an unsigned 32 bit integer
+        assert_raises(TypeError, np.random.RandomState, -0.5)
+        assert_raises(ValueError, np.random.RandomState, -1)
+
+    def test_invalid_array(self):
+        # seed must be an unsigned 32 bit integer
+        assert_raises(TypeError, np.random.RandomState, [-0.5])
+        assert_raises(ValueError, np.random.RandomState, [-1])
+        assert_raises(ValueError, np.random.RandomState, [4294967296])
+        assert_raises(ValueError, np.random.RandomState, [1, 2, 4294967296])
+        assert_raises(ValueError, np.random.RandomState, [1, -2, 4294967296])
+
+    def test_invalid_array_shape(self):
+        # gh-9832
+        assert_raises(ValueError, np.random.RandomState,
+                      np.array([], dtype=np.int64))
+        assert_raises(ValueError, np.random.RandomState, [[1, 2, 3]])
+        assert_raises(ValueError, np.random.RandomState, [[1, 2, 3],
+                                                          [4, 5, 6]])
+
+
+class TestBinomial:
+    def test_n_zero(self):
+        # Tests the corner case of n == 0 for the binomial distribution.
+        # binomial(0, p) should be zero for any p in [0, 1].
+        # This test addresses issue #3480.
+        zeros = np.zeros(2, dtype='int')
+        for p in [0, .5, 1]:
+            assert_(random.binomial(0, p) == 0)
+            assert_array_equal(random.binomial(zeros, p), zeros)
+
+    def test_p_is_nan(self):
+        # Issue #4571.
+        assert_raises(ValueError, random.binomial, 1, np.nan)
+
+
+class TestMultinomial:
+    def test_basic(self):
+        random.multinomial(100, [0.2, 0.8])
+
+    def test_zero_probability(self):
+        random.multinomial(100, [0.2, 0.8, 0.0, 0.0, 0.0])
+
+    def test_int_negative_interval(self):
+        assert_(-5 <= random.randint(-5, -1) < -1)
+        x = random.randint(-5, -1, 5)
+        assert_(np.all(-5 <= x))
+        assert_(np.all(x < -1))
+
+    def test_size(self):
+        # gh-3173
+        p = [0.5, 0.5]
+        assert_equal(np.random.multinomial(1, p, np.uint32(1)).shape, (1, 2))
+        assert_equal(np.random.multinomial(1, p, np.uint32(1)).shape, (1, 2))
+        assert_equal(np.random.multinomial(1, p, np.uint32(1)).shape, (1, 2))
+        assert_equal(np.random.multinomial(1, p, [2, 2]).shape, (2, 2, 2))
+        assert_equal(np.random.multinomial(1, p, (2, 2)).shape, (2, 2, 2))
+        assert_equal(np.random.multinomial(1, p, np.array((2, 2))).shape,
+                     (2, 2, 2))
+
+        assert_raises(TypeError, np.random.multinomial, 1, p,
+                      float(1))
+
+    def test_multidimensional_pvals(self):
+        assert_raises(ValueError, np.random.multinomial, 10, [[0, 1]])
+        assert_raises(ValueError, np.random.multinomial, 10, [[0], [1]])
+        assert_raises(ValueError, np.random.multinomial, 10, [[[0], [1]], [[1], [0]]])
+        assert_raises(ValueError, np.random.multinomial, 10, np.array([[0, 1], [1, 0]]))
+
+
+class TestSetState:
+    def setup_method(self):
+        self.seed = 1234567890
+        self.prng = random.RandomState(self.seed)
+        self.state = self.prng.get_state()
+
+    def test_basic(self):
+        old = self.prng.tomaxint(16)
+        self.prng.set_state(self.state)
+        new = self.prng.tomaxint(16)
+        assert_(np.all(old == new))
+
+    def test_gaussian_reset(self):
+        # Make sure the cached every-other-Gaussian is reset.
+        old = self.prng.standard_normal(size=3)
+        self.prng.set_state(self.state)
+        new = self.prng.standard_normal(size=3)
+        assert_(np.all(old == new))
+
+    def test_gaussian_reset_in_media_res(self):
+        # When the state is saved with a cached Gaussian, make sure the
+        # cached Gaussian is restored.
+
+        self.prng.standard_normal()
+        state = self.prng.get_state()
+        old = self.prng.standard_normal(size=3)
+        self.prng.set_state(state)
+        new = self.prng.standard_normal(size=3)
+        assert_(np.all(old == new))
+
+    def test_backwards_compatibility(self):
+        # Make sure we can accept old state tuples that do not have the
+        # cached Gaussian value.
+        old_state = self.state[:-2]
+        x1 = self.prng.standard_normal(size=16)
+        self.prng.set_state(old_state)
+        x2 = self.prng.standard_normal(size=16)
+        self.prng.set_state(self.state)
+        x3 = self.prng.standard_normal(size=16)
+        assert_(np.all(x1 == x2))
+        assert_(np.all(x1 == x3))
+
+    def test_negative_binomial(self):
+        # Ensure that the negative binomial results take floating point
+        # arguments without truncation.
+        self.prng.negative_binomial(0.5, 0.5)
+
+    def test_set_invalid_state(self):
+        # gh-25402
+        with pytest.raises(IndexError):
+            self.prng.set_state(())
+
+
+class TestRandint:
+
+    rfunc = np.random.randint
+
+    # valid integer/boolean types
+    itype = [np.bool_, np.int8, np.uint8, np.int16, np.uint16,
+             np.int32, np.uint32, np.int64, np.uint64]
+
+    def test_unsupported_type(self):
+        assert_raises(TypeError, self.rfunc, 1, dtype=float)
+
+    def test_bounds_checking(self):
+        for dt in self.itype:
+            lbnd = 0 if dt is np.bool_ else np.iinfo(dt).min
+            ubnd = 2 if dt is np.bool_ else np.iinfo(dt).max + 1
+            assert_raises(ValueError, self.rfunc, lbnd - 1, ubnd, dtype=dt)
+            assert_raises(ValueError, self.rfunc, lbnd, ubnd + 1, dtype=dt)
+            assert_raises(ValueError, self.rfunc, ubnd, lbnd, dtype=dt)
+            assert_raises(ValueError, self.rfunc, 1, 0, dtype=dt)
+
+    def test_rng_zero_and_extremes(self):
+        for dt in self.itype:
+            lbnd = 0 if dt is np.bool_ else np.iinfo(dt).min
+            ubnd = 2 if dt is np.bool_ else np.iinfo(dt).max + 1
+
+            tgt = ubnd - 1
+            assert_equal(self.rfunc(tgt, tgt + 1, size=1000, dtype=dt), tgt)
+
+            tgt = lbnd
+            assert_equal(self.rfunc(tgt, tgt + 1, size=1000, dtype=dt), tgt)
+
+            tgt = (lbnd + ubnd)//2
+            assert_equal(self.rfunc(tgt, tgt + 1, size=1000, dtype=dt), tgt)
+
+    def test_full_range(self):
+        # Test for ticket #1690
+
+        for dt in self.itype:
+            lbnd = 0 if dt is np.bool_ else np.iinfo(dt).min
+            ubnd = 2 if dt is np.bool_ else np.iinfo(dt).max + 1
+
+            try:
+                self.rfunc(lbnd, ubnd, dtype=dt)
+            except Exception as e:
+                raise AssertionError("No error should have been raised, "
+                                     "but one was with the following "
+                                     "message:\n\n%s" % str(e))
+
+    def test_in_bounds_fuzz(self):
+        # Don't use fixed seed
+        np.random.seed()
+
+        for dt in self.itype[1:]:
+            for ubnd in [4, 8, 16]:
+                vals = self.rfunc(2, ubnd, size=2**16, dtype=dt)
+                assert_(vals.max() < ubnd)
+                assert_(vals.min() >= 2)
+
+        vals = self.rfunc(0, 2, size=2**16, dtype=np.bool_)
+
+        assert_(vals.max() < 2)
+        assert_(vals.min() >= 0)
+
+    def test_repeatability(self):
+        import hashlib
+        # We use a sha256 hash of generated sequences of 1000 samples
+        # in the range [0, 6) for all but bool, where the range
+        # is [0, 2). Hashes are for little endian numbers.
+        tgt = {'bool': '509aea74d792fb931784c4b0135392c65aec64beee12b0cc167548a2c3d31e71',
+               'int16': '7b07f1a920e46f6d0fe02314155a2330bcfd7635e708da50e536c5ebb631a7d4',
+               'int32': 'e577bfed6c935de944424667e3da285012e741892dcb7051a8f1ce68ab05c92f',
+               'int64': '0fbead0b06759df2cfb55e43148822d4a1ff953c7eb19a5b08445a63bb64fa9e',
+               'int8': '001aac3a5acb935a9b186cbe14a1ca064b8bb2dd0b045d48abeacf74d0203404',
+               'uint16': '7b07f1a920e46f6d0fe02314155a2330bcfd7635e708da50e536c5ebb631a7d4',
+               'uint32': 'e577bfed6c935de944424667e3da285012e741892dcb7051a8f1ce68ab05c92f',
+               'uint64': '0fbead0b06759df2cfb55e43148822d4a1ff953c7eb19a5b08445a63bb64fa9e',
+               'uint8': '001aac3a5acb935a9b186cbe14a1ca064b8bb2dd0b045d48abeacf74d0203404'}
+
+        for dt in self.itype[1:]:
+            np.random.seed(1234)
+
+            # view as little endian for hash
+            if sys.byteorder == 'little':
+                val = self.rfunc(0, 6, size=1000, dtype=dt)
+            else:
+                val = self.rfunc(0, 6, size=1000, dtype=dt).byteswap()
+
+            res = hashlib.sha256(val.view(np.int8)).hexdigest()
+            assert_(tgt[np.dtype(dt).name] == res)
+
+        # bools do not depend on endianness
+        np.random.seed(1234)
+        val = self.rfunc(0, 2, size=1000, dtype=bool).view(np.int8)
+        res = hashlib.sha256(val).hexdigest()
+        assert_(tgt[np.dtype(bool).name] == res)
+
+    def test_int64_uint64_corner_case(self):
+        # When stored in Numpy arrays, `lbnd` is casted
+        # as np.int64, and `ubnd` is casted as np.uint64.
+        # Checking whether `lbnd` >= `ubnd` used to be
+        # done solely via direct comparison, which is incorrect
+        # because when Numpy tries to compare both numbers,
+        # it casts both to np.float64 because there is
+        # no integer superset of np.int64 and np.uint64. However,
+        # `ubnd` is too large to be represented in np.float64,
+        # causing it be round down to np.iinfo(np.int64).max,
+        # leading to a ValueError because `lbnd` now equals
+        # the new `ubnd`.
+
+        dt = np.int64
+        tgt = np.iinfo(np.int64).max
+        lbnd = np.int64(np.iinfo(np.int64).max)
+        ubnd = np.uint64(np.iinfo(np.int64).max + 1)
+
+        # None of these function calls should
+        # generate a ValueError now.
+        actual = np.random.randint(lbnd, ubnd, dtype=dt)
+        assert_equal(actual, tgt)
+
+    def test_respect_dtype_singleton(self):
+        # See gh-7203
+        for dt in self.itype:
+            lbnd = 0 if dt is np.bool_ else np.iinfo(dt).min
+            ubnd = 2 if dt is np.bool_ else np.iinfo(dt).max + 1
+
+            sample = self.rfunc(lbnd, ubnd, dtype=dt)
+            assert_equal(sample.dtype, np.dtype(dt))
+
+        for dt in (bool, int):
+            lbnd = 0 if dt is bool else np.iinfo(dt).min
+            ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
+
+            # gh-7284: Ensure that we get Python data types
+            sample = self.rfunc(lbnd, ubnd, dtype=dt)
+            assert_(not hasattr(sample, 'dtype'))
+            assert_equal(type(sample), dt)
+
+
+class TestRandomDist:
+    # Make sure the random distribution returns the correct value for a
+    # given seed
+
+    def setup_method(self):
+        self.seed = 1234567890
+
+    def test_rand(self):
+        np.random.seed(self.seed)
+        actual = np.random.rand(3, 2)
+        desired = np.array([[0.61879477158567997, 0.59162362775974664],
+                            [0.88868358904449662, 0.89165480011560816],
+                            [0.4575674820298663, 0.7781880808593471]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_randn(self):
+        np.random.seed(self.seed)
+        actual = np.random.randn(3, 2)
+        desired = np.array([[1.34016345771863121, 1.73759122771936081],
+                           [1.498988344300628, -0.2286433324536169],
+                           [2.031033998682787, 2.17032494605655257]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_randint(self):
+        np.random.seed(self.seed)
+        actual = np.random.randint(-99, 99, size=(3, 2))
+        desired = np.array([[31, 3],
+                            [-52, 41],
+                            [-48, -66]])
+        assert_array_equal(actual, desired)
+
+    def test_random_integers(self):
+        np.random.seed(self.seed)
+        with suppress_warnings() as sup:
+            w = sup.record(DeprecationWarning)
+            actual = np.random.random_integers(-99, 99, size=(3, 2))
+            assert_(len(w) == 1)
+        desired = np.array([[31, 3],
+                            [-52, 41],
+                            [-48, -66]])
+        assert_array_equal(actual, desired)
+
+    def test_random_integers_max_int(self):
+        # Tests whether random_integers can generate the
+        # maximum allowed Python int that can be converted
+        # into a C long. Previous implementations of this
+        # method have thrown an OverflowError when attempting
+        # to generate this integer.
+        with suppress_warnings() as sup:
+            w = sup.record(DeprecationWarning)
+            actual = np.random.random_integers(np.iinfo('l').max,
+                                               np.iinfo('l').max)
+            assert_(len(w) == 1)
+
+        desired = np.iinfo('l').max
+        assert_equal(actual, desired)
+
+    def test_random_integers_deprecated(self):
+        with warnings.catch_warnings():
+            warnings.simplefilter("error", DeprecationWarning)
+
+            # DeprecationWarning raised with high == None
+            assert_raises(DeprecationWarning,
+                          np.random.random_integers,
+                          np.iinfo('l').max)
+
+            # DeprecationWarning raised with high != None
+            assert_raises(DeprecationWarning,
+                          np.random.random_integers,
+                          np.iinfo('l').max, np.iinfo('l').max)
+
+    def test_random(self):
+        np.random.seed(self.seed)
+        actual = np.random.random((3, 2))
+        desired = np.array([[0.61879477158567997, 0.59162362775974664],
+                            [0.88868358904449662, 0.89165480011560816],
+                            [0.4575674820298663, 0.7781880808593471]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_choice_uniform_replace(self):
+        np.random.seed(self.seed)
+        actual = np.random.choice(4, 4)
+        desired = np.array([2, 3, 2, 3])
+        assert_array_equal(actual, desired)
+
+    def test_choice_nonuniform_replace(self):
+        np.random.seed(self.seed)
+        actual = np.random.choice(4, 4, p=[0.4, 0.4, 0.1, 0.1])
+        desired = np.array([1, 1, 2, 2])
+        assert_array_equal(actual, desired)
+
+    def test_choice_uniform_noreplace(self):
+        np.random.seed(self.seed)
+        actual = np.random.choice(4, 3, replace=False)
+        desired = np.array([0, 1, 3])
+        assert_array_equal(actual, desired)
+
+    def test_choice_nonuniform_noreplace(self):
+        np.random.seed(self.seed)
+        actual = np.random.choice(4, 3, replace=False,
+                                  p=[0.1, 0.3, 0.5, 0.1])
+        desired = np.array([2, 3, 1])
+        assert_array_equal(actual, desired)
+
+    def test_choice_noninteger(self):
+        np.random.seed(self.seed)
+        actual = np.random.choice(['a', 'b', 'c', 'd'], 4)
+        desired = np.array(['c', 'd', 'c', 'd'])
+        assert_array_equal(actual, desired)
+
+    def test_choice_exceptions(self):
+        sample = np.random.choice
+        assert_raises(ValueError, sample, -1, 3)
+        assert_raises(ValueError, sample, 3., 3)
+        assert_raises(ValueError, sample, [[1, 2], [3, 4]], 3)
+        assert_raises(ValueError, sample, [], 3)
+        assert_raises(ValueError, sample, [1, 2, 3, 4], 3,
+                      p=[[0.25, 0.25], [0.25, 0.25]])
+        assert_raises(ValueError, sample, [1, 2], 3, p=[0.4, 0.4, 0.2])
+        assert_raises(ValueError, sample, [1, 2], 3, p=[1.1, -0.1])
+        assert_raises(ValueError, sample, [1, 2], 3, p=[0.4, 0.4])
+        assert_raises(ValueError, sample, [1, 2, 3], 4, replace=False)
+        # gh-13087
+        assert_raises(ValueError, sample, [1, 2, 3], -2, replace=False)
+        assert_raises(ValueError, sample, [1, 2, 3], (-1,), replace=False)
+        assert_raises(ValueError, sample, [1, 2, 3], (-1, 1), replace=False)
+        assert_raises(ValueError, sample, [1, 2, 3], 2,
+                      replace=False, p=[1, 0, 0])
+
+    def test_choice_return_shape(self):
+        p = [0.1, 0.9]
+        # Check scalar
+        assert_(np.isscalar(np.random.choice(2, replace=True)))
+        assert_(np.isscalar(np.random.choice(2, replace=False)))
+        assert_(np.isscalar(np.random.choice(2, replace=True, p=p)))
+        assert_(np.isscalar(np.random.choice(2, replace=False, p=p)))
+        assert_(np.isscalar(np.random.choice([1, 2], replace=True)))
+        assert_(np.random.choice([None], replace=True) is None)
+        a = np.array([1, 2])
+        arr = np.empty(1, dtype=object)
+        arr[0] = a
+        assert_(np.random.choice(arr, replace=True) is a)
+
+        # Check 0-d array
+        s = tuple()
+        assert_(not np.isscalar(np.random.choice(2, s, replace=True)))
+        assert_(not np.isscalar(np.random.choice(2, s, replace=False)))
+        assert_(not np.isscalar(np.random.choice(2, s, replace=True, p=p)))
+        assert_(not np.isscalar(np.random.choice(2, s, replace=False, p=p)))
+        assert_(not np.isscalar(np.random.choice([1, 2], s, replace=True)))
+        assert_(np.random.choice([None], s, replace=True).ndim == 0)
+        a = np.array([1, 2])
+        arr = np.empty(1, dtype=object)
+        arr[0] = a
+        assert_(np.random.choice(arr, s, replace=True).item() is a)
+
+        # Check multi dimensional array
+        s = (2, 3)
+        p = [0.1, 0.1, 0.1, 0.1, 0.4, 0.2]
+        assert_equal(np.random.choice(6, s, replace=True).shape, s)
+        assert_equal(np.random.choice(6, s, replace=False).shape, s)
+        assert_equal(np.random.choice(6, s, replace=True, p=p).shape, s)
+        assert_equal(np.random.choice(6, s, replace=False, p=p).shape, s)
+        assert_equal(np.random.choice(np.arange(6), s, replace=True).shape, s)
+
+        # Check zero-size
+        assert_equal(np.random.randint(0, 0, size=(3, 0, 4)).shape, (3, 0, 4))
+        assert_equal(np.random.randint(0, -10, size=0).shape, (0,))
+        assert_equal(np.random.randint(10, 10, size=0).shape, (0,))
+        assert_equal(np.random.choice(0, size=0).shape, (0,))
+        assert_equal(np.random.choice([], size=(0,)).shape, (0,))
+        assert_equal(np.random.choice(['a', 'b'], size=(3, 0, 4)).shape,
+                     (3, 0, 4))
+        assert_raises(ValueError, np.random.choice, [], 10)
+
+    def test_choice_nan_probabilities(self):
+        a = np.array([42, 1, 2])
+        p = [None, None, None]
+        assert_raises(ValueError, np.random.choice, a, p=p)
+
+    def test_bytes(self):
+        np.random.seed(self.seed)
+        actual = np.random.bytes(10)
+        desired = b'\x82Ui\x9e\xff\x97+Wf\xa5'
+        assert_equal(actual, desired)
+
+    def test_shuffle(self):
+        # Test lists, arrays (of various dtypes), and multidimensional versions
+        # of both, c-contiguous or not:
+        for conv in [lambda x: np.array([]),
+                     lambda x: x,
+                     lambda x: np.asarray(x).astype(np.int8),
+                     lambda x: np.asarray(x).astype(np.float32),
+                     lambda x: np.asarray(x).astype(np.complex64),
+                     lambda x: np.asarray(x).astype(object),
+                     lambda x: [(i, i) for i in x],
+                     lambda x: np.asarray([[i, i] for i in x]),
+                     lambda x: np.vstack([x, x]).T,
+                     # gh-11442
+                     lambda x: (np.asarray([(i, i) for i in x],
+                                           [("a", int), ("b", int)])
+                                .view(np.recarray)),
+                     # gh-4270
+                     lambda x: np.asarray([(i, i) for i in x],
+                                          [("a", object), ("b", np.int32)])]:
+            np.random.seed(self.seed)
+            alist = conv([1, 2, 3, 4, 5, 6, 7, 8, 9, 0])
+            np.random.shuffle(alist)
+            actual = alist
+            desired = conv([0, 1, 9, 6, 2, 4, 5, 8, 7, 3])
+            assert_array_equal(actual, desired)
+
+    def test_shuffle_masked(self):
+        # gh-3263
+        a = np.ma.masked_values(np.reshape(range(20), (5, 4)) % 3 - 1, -1)
+        b = np.ma.masked_values(np.arange(20) % 3 - 1, -1)
+        a_orig = a.copy()
+        b_orig = b.copy()
+        for i in range(50):
+            np.random.shuffle(a)
+            assert_equal(
+                sorted(a.data[~a.mask]), sorted(a_orig.data[~a_orig.mask]))
+            np.random.shuffle(b)
+            assert_equal(
+                sorted(b.data[~b.mask]), sorted(b_orig.data[~b_orig.mask]))
+
+    @pytest.mark.parametrize("random",
+            [np.random, np.random.RandomState(), np.random.default_rng()])
+    def test_shuffle_untyped_warning(self, random):
+        # Create a dict works like a sequence but isn't one
+        values = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6}
+        with pytest.warns(UserWarning,
+                match="you are shuffling a 'dict' object") as rec:
+            random.shuffle(values)
+        assert "test_random" in rec[0].filename
+
+    @pytest.mark.parametrize("random",
+        [np.random, np.random.RandomState(), np.random.default_rng()])
+    @pytest.mark.parametrize("use_array_like", [True, False])
+    def test_shuffle_no_object_unpacking(self, random, use_array_like):
+        class MyArr(np.ndarray):
+            pass
+
+        items = [
+            None, np.array([3]), np.float64(3), np.array(10), np.float64(7)
+        ]
+        arr = np.array(items, dtype=object)
+        item_ids = {id(i) for i in items}
+        if use_array_like:
+            arr = arr.view(MyArr)
+
+        # The array was created fine, and did not modify any objects:
+        assert all(id(i) in item_ids for i in arr)
+
+        if use_array_like and not isinstance(random, np.random.Generator):
+            # The old API gives incorrect results, but warns about it.
+            with pytest.warns(UserWarning,
+                    match="Shuffling a one dimensional array.*"):
+                random.shuffle(arr)
+        else:
+            random.shuffle(arr)
+            assert all(id(i) in item_ids for i in arr)
+
+    def test_shuffle_memoryview(self):
+        # gh-18273
+        # allow graceful handling of memoryviews
+        # (treat the same as arrays)
+        np.random.seed(self.seed)
+        a = np.arange(5).data
+        np.random.shuffle(a)
+        assert_equal(np.asarray(a), [0, 1, 4, 3, 2])
+        rng = np.random.RandomState(self.seed)
+        rng.shuffle(a)
+        assert_equal(np.asarray(a), [0, 1, 2, 3, 4])
+        rng = np.random.default_rng(self.seed)
+        rng.shuffle(a)
+        assert_equal(np.asarray(a), [4, 1, 0, 3, 2])
+
+    def test_shuffle_not_writeable(self):
+        a = np.zeros(3)
+        a.flags.writeable = False
+        with pytest.raises(ValueError, match='read-only'):
+            np.random.shuffle(a)
+
+    def test_beta(self):
+        np.random.seed(self.seed)
+        actual = np.random.beta(.1, .9, size=(3, 2))
+        desired = np.array(
+                [[1.45341850513746058e-02, 5.31297615662868145e-04],
+                 [1.85366619058432324e-06, 4.19214516800110563e-03],
+                 [1.58405155108498093e-04, 1.26252891949397652e-04]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_binomial(self):
+        np.random.seed(self.seed)
+        actual = np.random.binomial(100, .456, size=(3, 2))
+        desired = np.array([[37, 43],
+                            [42, 48],
+                            [46, 45]])
+        assert_array_equal(actual, desired)
+
+    def test_chisquare(self):
+        np.random.seed(self.seed)
+        actual = np.random.chisquare(50, size=(3, 2))
+        desired = np.array([[63.87858175501090585, 68.68407748911370447],
+                            [65.77116116901505904, 47.09686762438974483],
+                            [72.3828403199695174, 74.18408615260374006]])
+        assert_array_almost_equal(actual, desired, decimal=13)
+
+    def test_dirichlet(self):
+        np.random.seed(self.seed)
+        alpha = np.array([51.72840233779265162, 39.74494232180943953])
+        actual = np.random.mtrand.dirichlet(alpha, size=(3, 2))
+        desired = np.array([[[0.54539444573611562, 0.45460555426388438],
+                             [0.62345816822039413, 0.37654183177960598]],
+                            [[0.55206000085785778, 0.44793999914214233],
+                             [0.58964023305154301, 0.41035976694845688]],
+                            [[0.59266909280647828, 0.40733090719352177],
+                             [0.56974431743975207, 0.43025568256024799]]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_dirichlet_size(self):
+        # gh-3173
+        p = np.array([51.72840233779265162, 39.74494232180943953])
+        assert_equal(np.random.dirichlet(p, np.uint32(1)).shape, (1, 2))
+        assert_equal(np.random.dirichlet(p, np.uint32(1)).shape, (1, 2))
+        assert_equal(np.random.dirichlet(p, np.uint32(1)).shape, (1, 2))
+        assert_equal(np.random.dirichlet(p, [2, 2]).shape, (2, 2, 2))
+        assert_equal(np.random.dirichlet(p, (2, 2)).shape, (2, 2, 2))
+        assert_equal(np.random.dirichlet(p, np.array((2, 2))).shape, (2, 2, 2))
+
+        assert_raises(TypeError, np.random.dirichlet, p, float(1))
+
+    def test_dirichlet_bad_alpha(self):
+        # gh-2089
+        alpha = np.array([5.4e-01, -1.0e-16])
+        assert_raises(ValueError, np.random.mtrand.dirichlet, alpha)
+
+        # gh-15876
+        assert_raises(ValueError, random.dirichlet, [[5, 1]])
+        assert_raises(ValueError, random.dirichlet, [[5], [1]])
+        assert_raises(ValueError, random.dirichlet, [[[5], [1]], [[1], [5]]])
+        assert_raises(ValueError, random.dirichlet, np.array([[5, 1], [1, 5]]))
+
+    def test_exponential(self):
+        np.random.seed(self.seed)
+        actual = np.random.exponential(1.1234, size=(3, 2))
+        desired = np.array([[1.08342649775011624, 1.00607889924557314],
+                            [2.46628830085216721, 2.49668106809923884],
+                            [0.68717433461363442, 1.69175666993575979]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_exponential_0(self):
+        assert_equal(np.random.exponential(scale=0), 0)
+        assert_raises(ValueError, np.random.exponential, scale=-0.)
+
+    def test_f(self):
+        np.random.seed(self.seed)
+        actual = np.random.f(12, 77, size=(3, 2))
+        desired = np.array([[1.21975394418575878, 1.75135759791559775],
+                            [1.44803115017146489, 1.22108959480396262],
+                            [1.02176975757740629, 1.34431827623300415]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_gamma(self):
+        np.random.seed(self.seed)
+        actual = np.random.gamma(5, 3, size=(3, 2))
+        desired = np.array([[24.60509188649287182, 28.54993563207210627],
+                            [26.13476110204064184, 12.56988482927716078],
+                            [31.71863275789960568, 33.30143302795922011]])
+        assert_array_almost_equal(actual, desired, decimal=14)
+
+    def test_gamma_0(self):
+        assert_equal(np.random.gamma(shape=0, scale=0), 0)
+        assert_raises(ValueError, np.random.gamma, shape=-0., scale=-0.)
+
+    def test_geometric(self):
+        np.random.seed(self.seed)
+        actual = np.random.geometric(.123456789, size=(3, 2))
+        desired = np.array([[8, 7],
+                            [17, 17],
+                            [5, 12]])
+        assert_array_equal(actual, desired)
+
+    def test_gumbel(self):
+        np.random.seed(self.seed)
+        actual = np.random.gumbel(loc=.123456789, scale=2.0, size=(3, 2))
+        desired = np.array([[0.19591898743416816, 0.34405539668096674],
+                            [-1.4492522252274278, -1.47374816298446865],
+                            [1.10651090478803416, -0.69535848626236174]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_gumbel_0(self):
+        assert_equal(np.random.gumbel(scale=0), 0)
+        assert_raises(ValueError, np.random.gumbel, scale=-0.)
+
+    def test_hypergeometric(self):
+        np.random.seed(self.seed)
+        actual = np.random.hypergeometric(10, 5, 14, size=(3, 2))
+        desired = np.array([[10, 10],
+                            [10, 10],
+                            [9, 9]])
+        assert_array_equal(actual, desired)
+
+        # Test nbad = 0
+        actual = np.random.hypergeometric(5, 0, 3, size=4)
+        desired = np.array([3, 3, 3, 3])
+        assert_array_equal(actual, desired)
+
+        actual = np.random.hypergeometric(15, 0, 12, size=4)
+        desired = np.array([12, 12, 12, 12])
+        assert_array_equal(actual, desired)
+
+        # Test ngood = 0
+        actual = np.random.hypergeometric(0, 5, 3, size=4)
+        desired = np.array([0, 0, 0, 0])
+        assert_array_equal(actual, desired)
+
+        actual = np.random.hypergeometric(0, 15, 12, size=4)
+        desired = np.array([0, 0, 0, 0])
+        assert_array_equal(actual, desired)
+
+    def test_laplace(self):
+        np.random.seed(self.seed)
+        actual = np.random.laplace(loc=.123456789, scale=2.0, size=(3, 2))
+        desired = np.array([[0.66599721112760157, 0.52829452552221945],
+                            [3.12791959514407125, 3.18202813572992005],
+                            [-0.05391065675859356, 1.74901336242837324]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_laplace_0(self):
+        assert_equal(np.random.laplace(scale=0), 0)
+        assert_raises(ValueError, np.random.laplace, scale=-0.)
+
+    def test_logistic(self):
+        np.random.seed(self.seed)
+        actual = np.random.logistic(loc=.123456789, scale=2.0, size=(3, 2))
+        desired = np.array([[1.09232835305011444, 0.8648196662399954],
+                            [4.27818590694950185, 4.33897006346929714],
+                            [-0.21682183359214885, 2.63373365386060332]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_lognormal(self):
+        np.random.seed(self.seed)
+        actual = np.random.lognormal(mean=.123456789, sigma=2.0, size=(3, 2))
+        desired = np.array([[16.50698631688883822, 36.54846706092654784],
+                            [22.67886599981281748, 0.71617561058995771],
+                            [65.72798501792723869, 86.84341601437161273]])
+        assert_array_almost_equal(actual, desired, decimal=13)
+
+    def test_lognormal_0(self):
+        assert_equal(np.random.lognormal(sigma=0), 1)
+        assert_raises(ValueError, np.random.lognormal, sigma=-0.)
+
+    def test_logseries(self):
+        np.random.seed(self.seed)
+        actual = np.random.logseries(p=.923456789, size=(3, 2))
+        desired = np.array([[2, 2],
+                            [6, 17],
+                            [3, 6]])
+        assert_array_equal(actual, desired)
+
+    def test_multinomial(self):
+        np.random.seed(self.seed)
+        actual = np.random.multinomial(20, [1/6.]*6, size=(3, 2))
+        desired = np.array([[[4, 3, 5, 4, 2, 2],
+                             [5, 2, 8, 2, 2, 1]],
+                            [[3, 4, 3, 6, 0, 4],
+                             [2, 1, 4, 3, 6, 4]],
+                            [[4, 4, 2, 5, 2, 3],
+                             [4, 3, 4, 2, 3, 4]]])
+        assert_array_equal(actual, desired)
+
+    def test_multivariate_normal(self):
+        np.random.seed(self.seed)
+        mean = (.123456789, 10)
+        cov = [[1, 0], [0, 1]]
+        size = (3, 2)
+        actual = np.random.multivariate_normal(mean, cov, size)
+        desired = np.array([[[1.463620246718631, 11.73759122771936],
+                             [1.622445133300628, 9.771356667546383]],
+                            [[2.154490787682787, 12.170324946056553],
+                             [1.719909438201865, 9.230548443648306]],
+                            [[0.689515026297799, 9.880729819607714],
+                             [-0.023054015651998, 9.201096623542879]]])
+
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+        # Check for default size, was raising deprecation warning
+        actual = np.random.multivariate_normal(mean, cov)
+        desired = np.array([0.895289569463708, 9.17180864067987])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+        # Check that non positive-semidefinite covariance warns with
+        # RuntimeWarning
+        mean = [0, 0]
+        cov = [[1, 2], [2, 1]]
+        assert_warns(RuntimeWarning, np.random.multivariate_normal, mean, cov)
+
+        # and that it doesn't warn with RuntimeWarning check_valid='ignore'
+        assert_no_warnings(np.random.multivariate_normal, mean, cov,
+                           check_valid='ignore')
+
+        # and that it raises with RuntimeWarning check_valid='raises'
+        assert_raises(ValueError, np.random.multivariate_normal, mean, cov,
+                      check_valid='raise')
+
+        cov = np.array([[1, 0.1], [0.1, 1]], dtype=np.float32)
+        with suppress_warnings() as sup:
+            np.random.multivariate_normal(mean, cov)
+            w = sup.record(RuntimeWarning)
+            assert len(w) == 0
+
+    def test_negative_binomial(self):
+        np.random.seed(self.seed)
+        actual = np.random.negative_binomial(n=100, p=.12345, size=(3, 2))
+        desired = np.array([[848, 841],
+                            [892, 611],
+                            [779, 647]])
+        assert_array_equal(actual, desired)
+
+    def test_noncentral_chisquare(self):
+        np.random.seed(self.seed)
+        actual = np.random.noncentral_chisquare(df=5, nonc=5, size=(3, 2))
+        desired = np.array([[23.91905354498517511, 13.35324692733826346],
+                            [31.22452661329736401, 16.60047399466177254],
+                            [5.03461598262724586, 17.94973089023519464]])
+        assert_array_almost_equal(actual, desired, decimal=14)
+
+        actual = np.random.noncentral_chisquare(df=.5, nonc=.2, size=(3, 2))
+        desired = np.array([[1.47145377828516666,  0.15052899268012659],
+                            [0.00943803056963588,  1.02647251615666169],
+                            [0.332334982684171,  0.15451287602753125]])
+        assert_array_almost_equal(actual, desired, decimal=14)
+
+        np.random.seed(self.seed)
+        actual = np.random.noncentral_chisquare(df=5, nonc=0, size=(3, 2))
+        desired = np.array([[9.597154162763948, 11.725484450296079],
+                            [10.413711048138335, 3.694475922923986],
+                            [13.484222138963087, 14.377255424602957]])
+        assert_array_almost_equal(actual, desired, decimal=14)
+
+    def test_noncentral_f(self):
+        np.random.seed(self.seed)
+        actual = np.random.noncentral_f(dfnum=5, dfden=2, nonc=1,
+                                        size=(3, 2))
+        desired = np.array([[1.40598099674926669, 0.34207973179285761],
+                            [3.57715069265772545, 7.92632662577829805],
+                            [0.43741599463544162, 1.1774208752428319]])
+        assert_array_almost_equal(actual, desired, decimal=14)
+
+    def test_normal(self):
+        np.random.seed(self.seed)
+        actual = np.random.normal(loc=.123456789, scale=2.0, size=(3, 2))
+        desired = np.array([[2.80378370443726244, 3.59863924443872163],
+                            [3.121433477601256, -0.33382987590723379],
+                            [4.18552478636557357, 4.46410668111310471]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_normal_0(self):
+        assert_equal(np.random.normal(scale=0), 0)
+        assert_raises(ValueError, np.random.normal, scale=-0.)
+
+    def test_pareto(self):
+        np.random.seed(self.seed)
+        actual = np.random.pareto(a=.123456789, size=(3, 2))
+        desired = np.array(
+                [[2.46852460439034849e+03, 1.41286880810518346e+03],
+                 [5.28287797029485181e+07, 6.57720981047328785e+07],
+                 [1.40840323350391515e+02, 1.98390255135251704e+05]])
+        # For some reason on 32-bit x86 Ubuntu 12.10 the [1, 0] entry in this
+        # matrix differs by 24 nulps. Discussion:
+        #   https://mail.python.org/pipermail/numpy-discussion/2012-September/063801.html
+        # Consensus is that this is probably some gcc quirk that affects
+        # rounding but not in any important way, so we just use a looser
+        # tolerance on this test:
+        np.testing.assert_array_almost_equal_nulp(actual, desired, nulp=30)
+
+    def test_poisson(self):
+        np.random.seed(self.seed)
+        actual = np.random.poisson(lam=.123456789, size=(3, 2))
+        desired = np.array([[0, 0],
+                            [1, 0],
+                            [0, 0]])
+        assert_array_equal(actual, desired)
+
+    def test_poisson_exceptions(self):
+        lambig = np.iinfo('l').max
+        lamneg = -1
+        assert_raises(ValueError, np.random.poisson, lamneg)
+        assert_raises(ValueError, np.random.poisson, [lamneg]*10)
+        assert_raises(ValueError, np.random.poisson, lambig)
+        assert_raises(ValueError, np.random.poisson, [lambig]*10)
+
+    def test_power(self):
+        np.random.seed(self.seed)
+        actual = np.random.power(a=.123456789, size=(3, 2))
+        desired = np.array([[0.02048932883240791, 0.01424192241128213],
+                            [0.38446073748535298, 0.39499689943484395],
+                            [0.00177699707563439, 0.13115505880863756]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_rayleigh(self):
+        np.random.seed(self.seed)
+        actual = np.random.rayleigh(scale=10, size=(3, 2))
+        desired = np.array([[13.8882496494248393, 13.383318339044731],
+                            [20.95413364294492098, 21.08285015800712614],
+                            [11.06066537006854311, 17.35468505778271009]])
+        assert_array_almost_equal(actual, desired, decimal=14)
+
+    def test_rayleigh_0(self):
+        assert_equal(np.random.rayleigh(scale=0), 0)
+        assert_raises(ValueError, np.random.rayleigh, scale=-0.)
+
+    def test_standard_cauchy(self):
+        np.random.seed(self.seed)
+        actual = np.random.standard_cauchy(size=(3, 2))
+        desired = np.array([[0.77127660196445336, -6.55601161955910605],
+                            [0.93582023391158309, -2.07479293013759447],
+                            [-4.74601644297011926, 0.18338989290760804]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_standard_exponential(self):
+        np.random.seed(self.seed)
+        actual = np.random.standard_exponential(size=(3, 2))
+        desired = np.array([[0.96441739162374596, 0.89556604882105506],
+                            [2.1953785836319808, 2.22243285392490542],
+                            [0.6116915921431676, 1.50592546727413201]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_standard_gamma(self):
+        np.random.seed(self.seed)
+        actual = np.random.standard_gamma(shape=3, size=(3, 2))
+        desired = np.array([[5.50841531318455058, 6.62953470301903103],
+                            [5.93988484943779227, 2.31044849402133989],
+                            [7.54838614231317084, 8.012756093271868]])
+        assert_array_almost_equal(actual, desired, decimal=14)
+
+    def test_standard_gamma_0(self):
+        assert_equal(np.random.standard_gamma(shape=0), 0)
+        assert_raises(ValueError, np.random.standard_gamma, shape=-0.)
+
+    def test_standard_normal(self):
+        np.random.seed(self.seed)
+        actual = np.random.standard_normal(size=(3, 2))
+        desired = np.array([[1.34016345771863121, 1.73759122771936081],
+                            [1.498988344300628, -0.2286433324536169],
+                            [2.031033998682787, 2.17032494605655257]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_standard_t(self):
+        np.random.seed(self.seed)
+        actual = np.random.standard_t(df=10, size=(3, 2))
+        desired = np.array([[0.97140611862659965, -0.08830486548450577],
+                            [1.36311143689505321, -0.55317463909867071],
+                            [-0.18473749069684214, 0.61181537341755321]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_triangular(self):
+        np.random.seed(self.seed)
+        actual = np.random.triangular(left=5.12, mode=10.23, right=20.34,
+                                      size=(3, 2))
+        desired = np.array([[12.68117178949215784, 12.4129206149193152],
+                            [16.20131377335158263, 16.25692138747600524],
+                            [11.20400690911820263, 14.4978144835829923]])
+        assert_array_almost_equal(actual, desired, decimal=14)
+
+    def test_uniform(self):
+        np.random.seed(self.seed)
+        actual = np.random.uniform(low=1.23, high=10.54, size=(3, 2))
+        desired = np.array([[6.99097932346268003, 6.73801597444323974],
+                            [9.50364421400426274, 9.53130618907631089],
+                            [5.48995325769805476, 8.47493103280052118]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_uniform_range_bounds(self):
+        fmin = np.finfo('float').min
+        fmax = np.finfo('float').max
+
+        func = np.random.uniform
+        assert_raises(OverflowError, func, -np.inf, 0)
+        assert_raises(OverflowError, func,  0,      np.inf)
+        assert_raises(OverflowError, func,  fmin,   fmax)
+        assert_raises(OverflowError, func, [-np.inf], [0])
+        assert_raises(OverflowError, func, [0], [np.inf])
+
+        # (fmax / 1e17) - fmin is within range, so this should not throw
+        # account for i386 extended precision DBL_MAX / 1e17 + DBL_MAX >
+        # DBL_MAX by increasing fmin a bit
+        np.random.uniform(low=np.nextafter(fmin, 1), high=fmax / 1e17)
+
+    def test_scalar_exception_propagation(self):
+        # Tests that exceptions are correctly propagated in distributions
+        # when called with objects that throw exceptions when converted to
+        # scalars.
+        #
+        # Regression test for gh: 8865
+
+        class ThrowingFloat(np.ndarray):
+            def __float__(self):
+                raise TypeError
+
+        throwing_float = np.array(1.0).view(ThrowingFloat)
+        assert_raises(TypeError, np.random.uniform, throwing_float,
+                      throwing_float)
+
+        class ThrowingInteger(np.ndarray):
+            def __int__(self):
+                raise TypeError
+
+            __index__ = __int__
+
+        throwing_int = np.array(1).view(ThrowingInteger)
+        assert_raises(TypeError, np.random.hypergeometric, throwing_int, 1, 1)
+
+    def test_vonmises(self):
+        np.random.seed(self.seed)
+        actual = np.random.vonmises(mu=1.23, kappa=1.54, size=(3, 2))
+        desired = np.array([[2.28567572673902042, 2.89163838442285037],
+                            [0.38198375564286025, 2.57638023113890746],
+                            [1.19153771588353052, 1.83509849681825354]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_vonmises_small(self):
+        # check infinite loop, gh-4720
+        np.random.seed(self.seed)
+        r = np.random.vonmises(mu=0., kappa=1.1e-8, size=10**6)
+        np.testing.assert_(np.isfinite(r).all())
+
+    def test_wald(self):
+        np.random.seed(self.seed)
+        actual = np.random.wald(mean=1.23, scale=1.54, size=(3, 2))
+        desired = np.array([[3.82935265715889983, 5.13125249184285526],
+                            [0.35045403618358717, 1.50832396872003538],
+                            [0.24124319895843183, 0.22031101461955038]])
+        assert_array_almost_equal(actual, desired, decimal=14)
+
+    def test_weibull(self):
+        np.random.seed(self.seed)
+        actual = np.random.weibull(a=1.23, size=(3, 2))
+        desired = np.array([[0.97097342648766727, 0.91422896443565516],
+                            [1.89517770034962929, 1.91414357960479564],
+                            [0.67057783752390987, 1.39494046635066793]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_weibull_0(self):
+        np.random.seed(self.seed)
+        assert_equal(np.random.weibull(a=0, size=12), np.zeros(12))
+        assert_raises(ValueError, np.random.weibull, a=-0.)
+
+    def test_zipf(self):
+        np.random.seed(self.seed)
+        actual = np.random.zipf(a=1.23, size=(3, 2))
+        desired = np.array([[66, 29],
+                            [1, 1],
+                            [3, 13]])
+        assert_array_equal(actual, desired)
+
+
+class TestBroadcast:
+    # tests that functions that broadcast behave
+    # correctly when presented with non-scalar arguments
+    def setup_method(self):
+        self.seed = 123456789
+
+    def setSeed(self):
+        np.random.seed(self.seed)
+
+    # TODO: Include test for randint once it can broadcast
+    # Can steal the test written in PR #6938
+
+    def test_uniform(self):
+        low = [0]
+        high = [1]
+        uniform = np.random.uniform
+        desired = np.array([0.53283302478975902,
+                            0.53413660089041659,
+                            0.50955303552646702])
+
+        self.setSeed()
+        actual = uniform(low * 3, high)
+        assert_array_almost_equal(actual, desired, decimal=14)
+
+        self.setSeed()
+        actual = uniform(low, high * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+
+    def test_normal(self):
+        loc = [0]
+        scale = [1]
+        bad_scale = [-1]
+        normal = np.random.normal
+        desired = np.array([2.2129019979039612,
+                            2.1283977976520019,
+                            1.8417114045748335])
+
+        self.setSeed()
+        actual = normal(loc * 3, scale)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, normal, loc * 3, bad_scale)
+
+        self.setSeed()
+        actual = normal(loc, scale * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, normal, loc, bad_scale * 3)
+
+    def test_beta(self):
+        a = [1]
+        b = [2]
+        bad_a = [-1]
+        bad_b = [-2]
+        beta = np.random.beta
+        desired = np.array([0.19843558305989056,
+                            0.075230336409423643,
+                            0.24976865978980844])
+
+        self.setSeed()
+        actual = beta(a * 3, b)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, beta, bad_a * 3, b)
+        assert_raises(ValueError, beta, a * 3, bad_b)
+
+        self.setSeed()
+        actual = beta(a, b * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, beta, bad_a, b * 3)
+        assert_raises(ValueError, beta, a, bad_b * 3)
+
+    def test_exponential(self):
+        scale = [1]
+        bad_scale = [-1]
+        exponential = np.random.exponential
+        desired = np.array([0.76106853658845242,
+                            0.76386282278691653,
+                            0.71243813125891797])
+
+        self.setSeed()
+        actual = exponential(scale * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, exponential, bad_scale * 3)
+
+    def test_standard_gamma(self):
+        shape = [1]
+        bad_shape = [-1]
+        std_gamma = np.random.standard_gamma
+        desired = np.array([0.76106853658845242,
+                            0.76386282278691653,
+                            0.71243813125891797])
+
+        self.setSeed()
+        actual = std_gamma(shape * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, std_gamma, bad_shape * 3)
+
+    def test_gamma(self):
+        shape = [1]
+        scale = [2]
+        bad_shape = [-1]
+        bad_scale = [-2]
+        gamma = np.random.gamma
+        desired = np.array([1.5221370731769048,
+                            1.5277256455738331,
+                            1.4248762625178359])
+
+        self.setSeed()
+        actual = gamma(shape * 3, scale)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, gamma, bad_shape * 3, scale)
+        assert_raises(ValueError, gamma, shape * 3, bad_scale)
+
+        self.setSeed()
+        actual = gamma(shape, scale * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, gamma, bad_shape, scale * 3)
+        assert_raises(ValueError, gamma, shape, bad_scale * 3)
+
+    def test_f(self):
+        dfnum = [1]
+        dfden = [2]
+        bad_dfnum = [-1]
+        bad_dfden = [-2]
+        f = np.random.f
+        desired = np.array([0.80038951638264799,
+                            0.86768719635363512,
+                            2.7251095168386801])
+
+        self.setSeed()
+        actual = f(dfnum * 3, dfden)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, f, bad_dfnum * 3, dfden)
+        assert_raises(ValueError, f, dfnum * 3, bad_dfden)
+
+        self.setSeed()
+        actual = f(dfnum, dfden * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, f, bad_dfnum, dfden * 3)
+        assert_raises(ValueError, f, dfnum, bad_dfden * 3)
+
+    def test_noncentral_f(self):
+        dfnum = [2]
+        dfden = [3]
+        nonc = [4]
+        bad_dfnum = [0]
+        bad_dfden = [-1]
+        bad_nonc = [-2]
+        nonc_f = np.random.noncentral_f
+        desired = np.array([9.1393943263705211,
+                            13.025456344595602,
+                            8.8018098359100545])
+
+        self.setSeed()
+        actual = nonc_f(dfnum * 3, dfden, nonc)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, nonc_f, bad_dfnum * 3, dfden, nonc)
+        assert_raises(ValueError, nonc_f, dfnum * 3, bad_dfden, nonc)
+        assert_raises(ValueError, nonc_f, dfnum * 3, dfden, bad_nonc)
+
+        self.setSeed()
+        actual = nonc_f(dfnum, dfden * 3, nonc)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, nonc_f, bad_dfnum, dfden * 3, nonc)
+        assert_raises(ValueError, nonc_f, dfnum, bad_dfden * 3, nonc)
+        assert_raises(ValueError, nonc_f, dfnum, dfden * 3, bad_nonc)
+
+        self.setSeed()
+        actual = nonc_f(dfnum, dfden, nonc * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, nonc_f, bad_dfnum, dfden, nonc * 3)
+        assert_raises(ValueError, nonc_f, dfnum, bad_dfden, nonc * 3)
+        assert_raises(ValueError, nonc_f, dfnum, dfden, bad_nonc * 3)
+
+    def test_noncentral_f_small_df(self):
+        self.setSeed()
+        desired = np.array([6.869638627492048, 0.785880199263955])
+        actual = np.random.noncentral_f(0.9, 0.9, 2, size=2)
+        assert_array_almost_equal(actual, desired, decimal=14)
+
+    def test_chisquare(self):
+        df = [1]
+        bad_df = [-1]
+        chisquare = np.random.chisquare
+        desired = np.array([0.57022801133088286,
+                            0.51947702108840776,
+                            0.1320969254923558])
+
+        self.setSeed()
+        actual = chisquare(df * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, chisquare, bad_df * 3)
+
+    def test_noncentral_chisquare(self):
+        df = [1]
+        nonc = [2]
+        bad_df = [-1]
+        bad_nonc = [-2]
+        nonc_chi = np.random.noncentral_chisquare
+        desired = np.array([9.0015599467913763,
+                            4.5804135049718742,
+                            6.0872302432834564])
+
+        self.setSeed()
+        actual = nonc_chi(df * 3, nonc)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, nonc_chi, bad_df * 3, nonc)
+        assert_raises(ValueError, nonc_chi, df * 3, bad_nonc)
+
+        self.setSeed()
+        actual = nonc_chi(df, nonc * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, nonc_chi, bad_df, nonc * 3)
+        assert_raises(ValueError, nonc_chi, df, bad_nonc * 3)
+
+    def test_standard_t(self):
+        df = [1]
+        bad_df = [-1]
+        t = np.random.standard_t
+        desired = np.array([3.0702872575217643,
+                            5.8560725167361607,
+                            1.0274791436474273])
+
+        self.setSeed()
+        actual = t(df * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, t, bad_df * 3)
+
+    def test_vonmises(self):
+        mu = [2]
+        kappa = [1]
+        bad_kappa = [-1]
+        vonmises = np.random.vonmises
+        desired = np.array([2.9883443664201312,
+                            -2.7064099483995943,
+                            -1.8672476700665914])
+
+        self.setSeed()
+        actual = vonmises(mu * 3, kappa)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, vonmises, mu * 3, bad_kappa)
+
+        self.setSeed()
+        actual = vonmises(mu, kappa * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, vonmises, mu, bad_kappa * 3)
+
+    def test_pareto(self):
+        a = [1]
+        bad_a = [-1]
+        pareto = np.random.pareto
+        desired = np.array([1.1405622680198362,
+                            1.1465519762044529,
+                            1.0389564467453547])
+
+        self.setSeed()
+        actual = pareto(a * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, pareto, bad_a * 3)
+
+    def test_weibull(self):
+        a = [1]
+        bad_a = [-1]
+        weibull = np.random.weibull
+        desired = np.array([0.76106853658845242,
+                            0.76386282278691653,
+                            0.71243813125891797])
+
+        self.setSeed()
+        actual = weibull(a * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, weibull, bad_a * 3)
+
+    def test_power(self):
+        a = [1]
+        bad_a = [-1]
+        power = np.random.power
+        desired = np.array([0.53283302478975902,
+                            0.53413660089041659,
+                            0.50955303552646702])
+
+        self.setSeed()
+        actual = power(a * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, power, bad_a * 3)
+
+    def test_laplace(self):
+        loc = [0]
+        scale = [1]
+        bad_scale = [-1]
+        laplace = np.random.laplace
+        desired = np.array([0.067921356028507157,
+                            0.070715642226971326,
+                            0.019290950698972624])
+
+        self.setSeed()
+        actual = laplace(loc * 3, scale)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, laplace, loc * 3, bad_scale)
+
+        self.setSeed()
+        actual = laplace(loc, scale * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, laplace, loc, bad_scale * 3)
+
+    def test_gumbel(self):
+        loc = [0]
+        scale = [1]
+        bad_scale = [-1]
+        gumbel = np.random.gumbel
+        desired = np.array([0.2730318639556768,
+                            0.26936705726291116,
+                            0.33906220393037939])
+
+        self.setSeed()
+        actual = gumbel(loc * 3, scale)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, gumbel, loc * 3, bad_scale)
+
+        self.setSeed()
+        actual = gumbel(loc, scale * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, gumbel, loc, bad_scale * 3)
+
+    def test_logistic(self):
+        loc = [0]
+        scale = [1]
+        bad_scale = [-1]
+        logistic = np.random.logistic
+        desired = np.array([0.13152135837586171,
+                            0.13675915696285773,
+                            0.038216792802833396])
+
+        self.setSeed()
+        actual = logistic(loc * 3, scale)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, logistic, loc * 3, bad_scale)
+
+        self.setSeed()
+        actual = logistic(loc, scale * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, logistic, loc, bad_scale * 3)
+
+    def test_lognormal(self):
+        mean = [0]
+        sigma = [1]
+        bad_sigma = [-1]
+        lognormal = np.random.lognormal
+        desired = np.array([9.1422086044848427,
+                            8.4013952870126261,
+                            6.3073234116578671])
+
+        self.setSeed()
+        actual = lognormal(mean * 3, sigma)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, lognormal, mean * 3, bad_sigma)
+
+        self.setSeed()
+        actual = lognormal(mean, sigma * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, lognormal, mean, bad_sigma * 3)
+
+    def test_rayleigh(self):
+        scale = [1]
+        bad_scale = [-1]
+        rayleigh = np.random.rayleigh
+        desired = np.array([1.2337491937897689,
+                            1.2360119924878694,
+                            1.1936818095781789])
+
+        self.setSeed()
+        actual = rayleigh(scale * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, rayleigh, bad_scale * 3)
+
+    def test_wald(self):
+        mean = [0.5]
+        scale = [1]
+        bad_mean = [0]
+        bad_scale = [-2]
+        wald = np.random.wald
+        desired = np.array([0.11873681120271318,
+                            0.12450084820795027,
+                            0.9096122728408238])
+
+        self.setSeed()
+        actual = wald(mean * 3, scale)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, wald, bad_mean * 3, scale)
+        assert_raises(ValueError, wald, mean * 3, bad_scale)
+
+        self.setSeed()
+        actual = wald(mean, scale * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, wald, bad_mean, scale * 3)
+        assert_raises(ValueError, wald, mean, bad_scale * 3)
+        assert_raises(ValueError, wald, 0.0, 1)
+        assert_raises(ValueError, wald, 0.5, 0.0)
+
+    def test_triangular(self):
+        left = [1]
+        right = [3]
+        mode = [2]
+        bad_left_one = [3]
+        bad_mode_one = [4]
+        bad_left_two, bad_mode_two = right * 2
+        triangular = np.random.triangular
+        desired = np.array([2.03339048710429,
+                            2.0347400359389356,
+                            2.0095991069536208])
+
+        self.setSeed()
+        actual = triangular(left * 3, mode, right)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, triangular, bad_left_one * 3, mode, right)
+        assert_raises(ValueError, triangular, left * 3, bad_mode_one, right)
+        assert_raises(ValueError, triangular, bad_left_two * 3, bad_mode_two,
+                      right)
+
+        self.setSeed()
+        actual = triangular(left, mode * 3, right)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, triangular, bad_left_one, mode * 3, right)
+        assert_raises(ValueError, triangular, left, bad_mode_one * 3, right)
+        assert_raises(ValueError, triangular, bad_left_two, bad_mode_two * 3,
+                      right)
+
+        self.setSeed()
+        actual = triangular(left, mode, right * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, triangular, bad_left_one, mode, right * 3)
+        assert_raises(ValueError, triangular, left, bad_mode_one, right * 3)
+        assert_raises(ValueError, triangular, bad_left_two, bad_mode_two,
+                      right * 3)
+
+    def test_binomial(self):
+        n = [1]
+        p = [0.5]
+        bad_n = [-1]
+        bad_p_one = [-1]
+        bad_p_two = [1.5]
+        binom = np.random.binomial
+        desired = np.array([1, 1, 1])
+
+        self.setSeed()
+        actual = binom(n * 3, p)
+        assert_array_equal(actual, desired)
+        assert_raises(ValueError, binom, bad_n * 3, p)
+        assert_raises(ValueError, binom, n * 3, bad_p_one)
+        assert_raises(ValueError, binom, n * 3, bad_p_two)
+
+        self.setSeed()
+        actual = binom(n, p * 3)
+        assert_array_equal(actual, desired)
+        assert_raises(ValueError, binom, bad_n, p * 3)
+        assert_raises(ValueError, binom, n, bad_p_one * 3)
+        assert_raises(ValueError, binom, n, bad_p_two * 3)
+
+    def test_negative_binomial(self):
+        n = [1]
+        p = [0.5]
+        bad_n = [-1]
+        bad_p_one = [-1]
+        bad_p_two = [1.5]
+        neg_binom = np.random.negative_binomial
+        desired = np.array([1, 0, 1])
+
+        self.setSeed()
+        actual = neg_binom(n * 3, p)
+        assert_array_equal(actual, desired)
+        assert_raises(ValueError, neg_binom, bad_n * 3, p)
+        assert_raises(ValueError, neg_binom, n * 3, bad_p_one)
+        assert_raises(ValueError, neg_binom, n * 3, bad_p_two)
+
+        self.setSeed()
+        actual = neg_binom(n, p * 3)
+        assert_array_equal(actual, desired)
+        assert_raises(ValueError, neg_binom, bad_n, p * 3)
+        assert_raises(ValueError, neg_binom, n, bad_p_one * 3)
+        assert_raises(ValueError, neg_binom, n, bad_p_two * 3)
+
+    def test_poisson(self):
+        max_lam = np.random.RandomState()._poisson_lam_max
+
+        lam = [1]
+        bad_lam_one = [-1]
+        bad_lam_two = [max_lam * 2]
+        poisson = np.random.poisson
+        desired = np.array([1, 1, 0])
+
+        self.setSeed()
+        actual = poisson(lam * 3)
+        assert_array_equal(actual, desired)
+        assert_raises(ValueError, poisson, bad_lam_one * 3)
+        assert_raises(ValueError, poisson, bad_lam_two * 3)
+
+    def test_zipf(self):
+        a = [2]
+        bad_a = [0]
+        zipf = np.random.zipf
+        desired = np.array([2, 2, 1])
+
+        self.setSeed()
+        actual = zipf(a * 3)
+        assert_array_equal(actual, desired)
+        assert_raises(ValueError, zipf, bad_a * 3)
+        with np.errstate(invalid='ignore'):
+            assert_raises(ValueError, zipf, np.nan)
+            assert_raises(ValueError, zipf, [0, 0, np.nan])
+
+    def test_geometric(self):
+        p = [0.5]
+        bad_p_one = [-1]
+        bad_p_two = [1.5]
+        geom = np.random.geometric
+        desired = np.array([2, 2, 2])
+
+        self.setSeed()
+        actual = geom(p * 3)
+        assert_array_equal(actual, desired)
+        assert_raises(ValueError, geom, bad_p_one * 3)
+        assert_raises(ValueError, geom, bad_p_two * 3)
+
+    def test_hypergeometric(self):
+        ngood = [1]
+        nbad = [2]
+        nsample = [2]
+        bad_ngood = [-1]
+        bad_nbad = [-2]
+        bad_nsample_one = [0]
+        bad_nsample_two = [4]
+        hypergeom = np.random.hypergeometric
+        desired = np.array([1, 1, 1])
+
+        self.setSeed()
+        actual = hypergeom(ngood * 3, nbad, nsample)
+        assert_array_equal(actual, desired)
+        assert_raises(ValueError, hypergeom, bad_ngood * 3, nbad, nsample)
+        assert_raises(ValueError, hypergeom, ngood * 3, bad_nbad, nsample)
+        assert_raises(ValueError, hypergeom, ngood * 3, nbad, bad_nsample_one)
+        assert_raises(ValueError, hypergeom, ngood * 3, nbad, bad_nsample_two)
+
+        self.setSeed()
+        actual = hypergeom(ngood, nbad * 3, nsample)
+        assert_array_equal(actual, desired)
+        assert_raises(ValueError, hypergeom, bad_ngood, nbad * 3, nsample)
+        assert_raises(ValueError, hypergeom, ngood, bad_nbad * 3, nsample)
+        assert_raises(ValueError, hypergeom, ngood, nbad * 3, bad_nsample_one)
+        assert_raises(ValueError, hypergeom, ngood, nbad * 3, bad_nsample_two)
+
+        self.setSeed()
+        actual = hypergeom(ngood, nbad, nsample * 3)
+        assert_array_equal(actual, desired)
+        assert_raises(ValueError, hypergeom, bad_ngood, nbad, nsample * 3)
+        assert_raises(ValueError, hypergeom, ngood, bad_nbad, nsample * 3)
+        assert_raises(ValueError, hypergeom, ngood, nbad, bad_nsample_one * 3)
+        assert_raises(ValueError, hypergeom, ngood, nbad, bad_nsample_two * 3)
+
+    def test_logseries(self):
+        p = [0.5]
+        bad_p_one = [2]
+        bad_p_two = [-1]
+        logseries = np.random.logseries
+        desired = np.array([1, 1, 1])
+
+        self.setSeed()
+        actual = logseries(p * 3)
+        assert_array_equal(actual, desired)
+        assert_raises(ValueError, logseries, bad_p_one * 3)
+        assert_raises(ValueError, logseries, bad_p_two * 3)
+
+
+@pytest.mark.skipif(IS_WASM, reason="can't start thread")
+class TestThread:
+    # make sure each state produces the same sequence even in threads
+    def setup_method(self):
+        self.seeds = range(4)
+
+    def check_function(self, function, sz):
+        from threading import Thread
+
+        out1 = np.empty((len(self.seeds),) + sz)
+        out2 = np.empty((len(self.seeds),) + sz)
+
+        # threaded generation
+        t = [Thread(target=function, args=(np.random.RandomState(s), o))
+             for s, o in zip(self.seeds, out1)]
+        [x.start() for x in t]
+        [x.join() for x in t]
+
+        # the same serial
+        for s, o in zip(self.seeds, out2):
+            function(np.random.RandomState(s), o)
+
+        # these platforms change x87 fpu precision mode in threads
+        if np.intp().dtype.itemsize == 4 and sys.platform == "win32":
+            assert_array_almost_equal(out1, out2)
+        else:
+            assert_array_equal(out1, out2)
+
+    def test_normal(self):
+        def gen_random(state, out):
+            out[...] = state.normal(size=10000)
+        self.check_function(gen_random, sz=(10000,))
+
+    def test_exp(self):
+        def gen_random(state, out):
+            out[...] = state.exponential(scale=np.ones((100, 1000)))
+        self.check_function(gen_random, sz=(100, 1000))
+
+    def test_multinomial(self):
+        def gen_random(state, out):
+            out[...] = state.multinomial(10, [1/6.]*6, size=10000)
+        self.check_function(gen_random, sz=(10000, 6))
+
+
+# See Issue #4263
+class TestSingleEltArrayInput:
+    def setup_method(self):
+        self.argOne = np.array([2])
+        self.argTwo = np.array([3])
+        self.argThree = np.array([4])
+        self.tgtShape = (1,)
+
+    def test_one_arg_funcs(self):
+        funcs = (np.random.exponential, np.random.standard_gamma,
+                 np.random.chisquare, np.random.standard_t,
+                 np.random.pareto, np.random.weibull,
+                 np.random.power, np.random.rayleigh,
+                 np.random.poisson, np.random.zipf,
+                 np.random.geometric, np.random.logseries)
+
+        probfuncs = (np.random.geometric, np.random.logseries)
+
+        for func in funcs:
+            if func in probfuncs:  # p < 1.0
+                out = func(np.array([0.5]))
+
+            else:
+                out = func(self.argOne)
+
+            assert_equal(out.shape, self.tgtShape)
+
+    def test_two_arg_funcs(self):
+        funcs = (np.random.uniform, np.random.normal,
+                 np.random.beta, np.random.gamma,
+                 np.random.f, np.random.noncentral_chisquare,
+                 np.random.vonmises, np.random.laplace,
+                 np.random.gumbel, np.random.logistic,
+                 np.random.lognormal, np.random.wald,
+                 np.random.binomial, np.random.negative_binomial)
+
+        probfuncs = (np.random.binomial, np.random.negative_binomial)
+
+        for func in funcs:
+            if func in probfuncs:  # p <= 1
+                argTwo = np.array([0.5])
+
+            else:
+                argTwo = self.argTwo
+
+            out = func(self.argOne, argTwo)
+            assert_equal(out.shape, self.tgtShape)
+
+            out = func(self.argOne[0], argTwo)
+            assert_equal(out.shape, self.tgtShape)
+
+            out = func(self.argOne, argTwo[0])
+            assert_equal(out.shape, self.tgtShape)
+
+    def test_randint(self):
+        itype = [bool, np.int8, np.uint8, np.int16, np.uint16,
+                 np.int32, np.uint32, np.int64, np.uint64]
+        func = np.random.randint
+        high = np.array([1])
+        low = np.array([0])
+
+        for dt in itype:
+            out = func(low, high, dtype=dt)
+            assert_equal(out.shape, self.tgtShape)
+
+            out = func(low[0], high, dtype=dt)
+            assert_equal(out.shape, self.tgtShape)
+
+            out = func(low, high[0], dtype=dt)
+            assert_equal(out.shape, self.tgtShape)
+
+    def test_three_arg_funcs(self):
+        funcs = [np.random.noncentral_f, np.random.triangular,
+                 np.random.hypergeometric]
+
+        for func in funcs:
+            out = func(self.argOne, self.argTwo, self.argThree)
+            assert_equal(out.shape, self.tgtShape)
+
+            out = func(self.argOne[0], self.argTwo, self.argThree)
+            assert_equal(out.shape, self.tgtShape)
+
+            out = func(self.argOne, self.argTwo[0], self.argThree)
+            assert_equal(out.shape, self.tgtShape)
diff --git a/venv/lib/python3.10/site-packages/numpy/random/tests/test_randomstate.py b/venv/lib/python3.10/site-packages/numpy/random/tests/test_randomstate.py
new file mode 100644
index 0000000000000000000000000000000000000000..c77bfce883aea276304c817be9ef93584b59cb28
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/numpy/random/tests/test_randomstate.py
@@ -0,0 +1,2121 @@
+import hashlib
+import pickle
+import sys
+import warnings
+
+import numpy as np
+import pytest
+from numpy.testing import (
+        assert_, assert_raises, assert_equal, assert_warns,
+        assert_no_warnings, assert_array_equal, assert_array_almost_equal,
+        suppress_warnings, IS_WASM
+        )
+
+from numpy.random import MT19937, PCG64
+from numpy import random
+
+INT_FUNCS = {'binomial': (100.0, 0.6),
+             'geometric': (.5,),
+             'hypergeometric': (20, 20, 10),
+             'logseries': (.5,),
+             'multinomial': (20, np.ones(6) / 6.0),
+             'negative_binomial': (100, .5),
+             'poisson': (10.0,),
+             'zipf': (2,),
+             }
+
+if np.iinfo(int).max < 2**32:
+    # Windows and some 32-bit platforms, e.g., ARM
+    INT_FUNC_HASHES = {'binomial': '2fbead005fc63942decb5326d36a1f32fe2c9d32c904ee61e46866b88447c263',
+                       'logseries': '23ead5dcde35d4cfd4ef2c105e4c3d43304b45dc1b1444b7823b9ee4fa144ebb',
+                       'geometric': '0d764db64f5c3bad48c8c33551c13b4d07a1e7b470f77629bef6c985cac76fcf',
+                       'hypergeometric': '7b59bf2f1691626c5815cdcd9a49e1dd68697251d4521575219e4d2a1b8b2c67',
+                       'multinomial': 'd754fa5b92943a38ec07630de92362dd2e02c43577fc147417dc5b9db94ccdd3',
+                       'negative_binomial': '8eb216f7cb2a63cf55605422845caaff002fddc64a7dc8b2d45acd477a49e824',
+                       'poisson': '70c891d76104013ebd6f6bcf30d403a9074b886ff62e4e6b8eb605bf1a4673b7',
+                       'zipf': '01f074f97517cd5d21747148ac6ca4074dde7fcb7acbaec0a936606fecacd93f',
+                       }
+else:
+    INT_FUNC_HASHES = {'binomial': '8626dd9d052cb608e93d8868de0a7b347258b199493871a1dc56e2a26cacb112',
+                       'geometric': '8edd53d272e49c4fc8fbbe6c7d08d563d62e482921f3131d0a0e068af30f0db9',
+                       'hypergeometric': '83496cc4281c77b786c9b7ad88b74d42e01603a55c60577ebab81c3ba8d45657',
+                       'logseries': '65878a38747c176bc00e930ebafebb69d4e1e16cd3a704e264ea8f5e24f548db',
+                       'multinomial': '7a984ae6dca26fd25374479e118b22f55db0aedccd5a0f2584ceada33db98605',
+                       'negative_binomial': 'd636d968e6a24ae92ab52fe11c46ac45b0897e98714426764e820a7d77602a61',
+                       'poisson': '956552176f77e7c9cb20d0118fc9cf690be488d790ed4b4c4747b965e61b0bb4',
+                       'zipf': 'f84ba7feffda41e606e20b28dfc0f1ea9964a74574513d4a4cbc98433a8bfa45',
+                       }
+
+
+@pytest.fixture(scope='module', params=INT_FUNCS)
+def int_func(request):
+    return (request.param, INT_FUNCS[request.param],
+            INT_FUNC_HASHES[request.param])
+
+
+@pytest.fixture
+def restore_singleton_bitgen():
+    """Ensures that the singleton bitgen is restored after a test"""
+    orig_bitgen = np.random.get_bit_generator()
+    yield
+    np.random.set_bit_generator(orig_bitgen)
+
+
+def assert_mt19937_state_equal(a, b):
+    assert_equal(a['bit_generator'], b['bit_generator'])
+    assert_array_equal(a['state']['key'], b['state']['key'])
+    assert_array_equal(a['state']['pos'], b['state']['pos'])
+    assert_equal(a['has_gauss'], b['has_gauss'])
+    assert_equal(a['gauss'], b['gauss'])
+
+
+class TestSeed:
+    def test_scalar(self):
+        s = random.RandomState(0)
+        assert_equal(s.randint(1000), 684)
+        s = random.RandomState(4294967295)
+        assert_equal(s.randint(1000), 419)
+
+    def test_array(self):
+        s = random.RandomState(range(10))
+        assert_equal(s.randint(1000), 468)
+        s = random.RandomState(np.arange(10))
+        assert_equal(s.randint(1000), 468)
+        s = random.RandomState([0])
+        assert_equal(s.randint(1000), 973)
+        s = random.RandomState([4294967295])
+        assert_equal(s.randint(1000), 265)
+
+    def test_invalid_scalar(self):
+        # seed must be an unsigned 32 bit integer
+        assert_raises(TypeError, random.RandomState, -0.5)
+        assert_raises(ValueError, random.RandomState, -1)
+
+    def test_invalid_array(self):
+        # seed must be an unsigned 32 bit integer
+        assert_raises(TypeError, random.RandomState, [-0.5])
+        assert_raises(ValueError, random.RandomState, [-1])
+        assert_raises(ValueError, random.RandomState, [4294967296])
+        assert_raises(ValueError, random.RandomState, [1, 2, 4294967296])
+        assert_raises(ValueError, random.RandomState, [1, -2, 4294967296])
+
+    def test_invalid_array_shape(self):
+        # gh-9832
+        assert_raises(ValueError, random.RandomState, np.array([],
+                                                               dtype=np.int64))
+        assert_raises(ValueError, random.RandomState, [[1, 2, 3]])
+        assert_raises(ValueError, random.RandomState, [[1, 2, 3],
+                                                       [4, 5, 6]])
+
+    def test_cannot_seed(self):
+        rs = random.RandomState(PCG64(0))
+        with assert_raises(TypeError):
+            rs.seed(1234)
+
+    def test_invalid_initialization(self):
+        assert_raises(ValueError, random.RandomState, MT19937)
+
+
+class TestBinomial:
+    def test_n_zero(self):
+        # Tests the corner case of n == 0 for the binomial distribution.
+        # binomial(0, p) should be zero for any p in [0, 1].
+        # This test addresses issue #3480.
+        zeros = np.zeros(2, dtype='int')
+        for p in [0, .5, 1]:
+            assert_(random.binomial(0, p) == 0)
+            assert_array_equal(random.binomial(zeros, p), zeros)
+
+    def test_p_is_nan(self):
+        # Issue #4571.
+        assert_raises(ValueError, random.binomial, 1, np.nan)
+
+
+class TestMultinomial:
+    def test_basic(self):
+        random.multinomial(100, [0.2, 0.8])
+
+    def test_zero_probability(self):
+        random.multinomial(100, [0.2, 0.8, 0.0, 0.0, 0.0])
+
+    def test_int_negative_interval(self):
+        assert_(-5 <= random.randint(-5, -1) < -1)
+        x = random.randint(-5, -1, 5)
+        assert_(np.all(-5 <= x))
+        assert_(np.all(x < -1))
+
+    def test_size(self):
+        # gh-3173
+        p = [0.5, 0.5]
+        assert_equal(random.multinomial(1, p, np.uint32(1)).shape, (1, 2))
+        assert_equal(random.multinomial(1, p, np.uint32(1)).shape, (1, 2))
+        assert_equal(random.multinomial(1, p, np.uint32(1)).shape, (1, 2))
+        assert_equal(random.multinomial(1, p, [2, 2]).shape, (2, 2, 2))
+        assert_equal(random.multinomial(1, p, (2, 2)).shape, (2, 2, 2))
+        assert_equal(random.multinomial(1, p, np.array((2, 2))).shape,
+                     (2, 2, 2))
+
+        assert_raises(TypeError, random.multinomial, 1, p,
+                      float(1))
+
+    def test_invalid_prob(self):
+        assert_raises(ValueError, random.multinomial, 100, [1.1, 0.2])
+        assert_raises(ValueError, random.multinomial, 100, [-.1, 0.9])
+
+    def test_invalid_n(self):
+        assert_raises(ValueError, random.multinomial, -1, [0.8, 0.2])
+
+    def test_p_non_contiguous(self):
+        p = np.arange(15.)
+        p /= np.sum(p[1::3])
+        pvals = p[1::3]
+        random.seed(1432985819)
+        non_contig = random.multinomial(100, pvals=pvals)
+        random.seed(1432985819)
+        contig = random.multinomial(100, pvals=np.ascontiguousarray(pvals))
+        assert_array_equal(non_contig, contig)
+
+    def test_multinomial_pvals_float32(self):
+        x = np.array([9.9e-01, 9.9e-01, 1.0e-09, 1.0e-09, 1.0e-09, 1.0e-09,
+                      1.0e-09, 1.0e-09, 1.0e-09, 1.0e-09], dtype=np.float32)
+        pvals = x / x.sum()
+        match = r"[\w\s]*pvals array is cast to 64-bit floating"
+        with pytest.raises(ValueError, match=match):
+            random.multinomial(1, pvals)
+
+    def test_multinomial_n_float(self):
+        # Non-index integer types should gracefully truncate floats
+        random.multinomial(100.5, [0.2, 0.8])
+
+class TestSetState:
+    def setup_method(self):
+        self.seed = 1234567890
+        self.random_state = random.RandomState(self.seed)
+        self.state = self.random_state.get_state()
+
+    def test_basic(self):
+        old = self.random_state.tomaxint(16)
+        self.random_state.set_state(self.state)
+        new = self.random_state.tomaxint(16)
+        assert_(np.all(old == new))
+
+    def test_gaussian_reset(self):
+        # Make sure the cached every-other-Gaussian is reset.
+        old = self.random_state.standard_normal(size=3)
+        self.random_state.set_state(self.state)
+        new = self.random_state.standard_normal(size=3)
+        assert_(np.all(old == new))
+
+    def test_gaussian_reset_in_media_res(self):
+        # When the state is saved with a cached Gaussian, make sure the
+        # cached Gaussian is restored.
+
+        self.random_state.standard_normal()
+        state = self.random_state.get_state()
+        old = self.random_state.standard_normal(size=3)
+        self.random_state.set_state(state)
+        new = self.random_state.standard_normal(size=3)
+        assert_(np.all(old == new))
+
+    def test_backwards_compatibility(self):
+        # Make sure we can accept old state tuples that do not have the
+        # cached Gaussian value.
+        old_state = self.state[:-2]
+        x1 = self.random_state.standard_normal(size=16)
+        self.random_state.set_state(old_state)
+        x2 = self.random_state.standard_normal(size=16)
+        self.random_state.set_state(self.state)
+        x3 = self.random_state.standard_normal(size=16)
+        assert_(np.all(x1 == x2))
+        assert_(np.all(x1 == x3))
+
+    def test_negative_binomial(self):
+        # Ensure that the negative binomial results take floating point
+        # arguments without truncation.
+        self.random_state.negative_binomial(0.5, 0.5)
+
+    def test_get_state_warning(self):
+        rs = random.RandomState(PCG64())
+        with suppress_warnings() as sup:
+            w = sup.record(RuntimeWarning)
+            state = rs.get_state()
+            assert_(len(w) == 1)
+            assert isinstance(state, dict)
+            assert state['bit_generator'] == 'PCG64'
+
+    def test_invalid_legacy_state_setting(self):
+        state = self.random_state.get_state()
+        new_state = ('Unknown', ) + state[1:]
+        assert_raises(ValueError, self.random_state.set_state, new_state)
+        assert_raises(TypeError, self.random_state.set_state,
+                      np.array(new_state, dtype=object))
+        state = self.random_state.get_state(legacy=False)
+        del state['bit_generator']
+        assert_raises(ValueError, self.random_state.set_state, state)
+
+    def test_pickle(self):
+        self.random_state.seed(0)
+        self.random_state.random_sample(100)
+        self.random_state.standard_normal()
+        pickled = self.random_state.get_state(legacy=False)
+        assert_equal(pickled['has_gauss'], 1)
+        rs_unpick = pickle.loads(pickle.dumps(self.random_state))
+        unpickled = rs_unpick.get_state(legacy=False)
+        assert_mt19937_state_equal(pickled, unpickled)
+
+    def test_state_setting(self):
+        attr_state = self.random_state.__getstate__()
+        self.random_state.standard_normal()
+        self.random_state.__setstate__(attr_state)
+        state = self.random_state.get_state(legacy=False)
+        assert_mt19937_state_equal(attr_state, state)
+
+    def test_repr(self):
+        assert repr(self.random_state).startswith('RandomState(MT19937)')
+
+
+class TestRandint:
+
+    rfunc = random.randint
+
+    # valid integer/boolean types
+    itype = [np.bool_, np.int8, np.uint8, np.int16, np.uint16,
+             np.int32, np.uint32, np.int64, np.uint64]
+
+    def test_unsupported_type(self):
+        assert_raises(TypeError, self.rfunc, 1, dtype=float)
+
+    def test_bounds_checking(self):
+        for dt in self.itype:
+            lbnd = 0 if dt is np.bool_ else np.iinfo(dt).min
+            ubnd = 2 if dt is np.bool_ else np.iinfo(dt).max + 1
+            assert_raises(ValueError, self.rfunc, lbnd - 1, ubnd, dtype=dt)
+            assert_raises(ValueError, self.rfunc, lbnd, ubnd + 1, dtype=dt)
+            assert_raises(ValueError, self.rfunc, ubnd, lbnd, dtype=dt)
+            assert_raises(ValueError, self.rfunc, 1, 0, dtype=dt)
+
+    def test_rng_zero_and_extremes(self):
+        for dt in self.itype:
+            lbnd = 0 if dt is np.bool_ else np.iinfo(dt).min
+            ubnd = 2 if dt is np.bool_ else np.iinfo(dt).max + 1
+
+            tgt = ubnd - 1
+            assert_equal(self.rfunc(tgt, tgt + 1, size=1000, dtype=dt), tgt)
+
+            tgt = lbnd
+            assert_equal(self.rfunc(tgt, tgt + 1, size=1000, dtype=dt), tgt)
+
+            tgt = (lbnd + ubnd)//2
+            assert_equal(self.rfunc(tgt, tgt + 1, size=1000, dtype=dt), tgt)
+
+    def test_full_range(self):
+        # Test for ticket #1690
+
+        for dt in self.itype:
+            lbnd = 0 if dt is np.bool_ else np.iinfo(dt).min
+            ubnd = 2 if dt is np.bool_ else np.iinfo(dt).max + 1
+
+            try:
+                self.rfunc(lbnd, ubnd, dtype=dt)
+            except Exception as e:
+                raise AssertionError("No error should have been raised, "
+                                     "but one was with the following "
+                                     "message:\n\n%s" % str(e))
+
+    def test_in_bounds_fuzz(self):
+        # Don't use fixed seed
+        random.seed()
+
+        for dt in self.itype[1:]:
+            for ubnd in [4, 8, 16]:
+                vals = self.rfunc(2, ubnd, size=2**16, dtype=dt)
+                assert_(vals.max() < ubnd)
+                assert_(vals.min() >= 2)
+
+        vals = self.rfunc(0, 2, size=2**16, dtype=np.bool_)
+
+        assert_(vals.max() < 2)
+        assert_(vals.min() >= 0)
+
+    def test_repeatability(self):
+        # We use a sha256 hash of generated sequences of 1000 samples
+        # in the range [0, 6) for all but bool, where the range
+        # is [0, 2). Hashes are for little endian numbers.
+        tgt = {'bool': '509aea74d792fb931784c4b0135392c65aec64beee12b0cc167548a2c3d31e71',
+               'int16': '7b07f1a920e46f6d0fe02314155a2330bcfd7635e708da50e536c5ebb631a7d4',
+               'int32': 'e577bfed6c935de944424667e3da285012e741892dcb7051a8f1ce68ab05c92f',
+               'int64': '0fbead0b06759df2cfb55e43148822d4a1ff953c7eb19a5b08445a63bb64fa9e',
+               'int8': '001aac3a5acb935a9b186cbe14a1ca064b8bb2dd0b045d48abeacf74d0203404',
+               'uint16': '7b07f1a920e46f6d0fe02314155a2330bcfd7635e708da50e536c5ebb631a7d4',
+               'uint32': 'e577bfed6c935de944424667e3da285012e741892dcb7051a8f1ce68ab05c92f',
+               'uint64': '0fbead0b06759df2cfb55e43148822d4a1ff953c7eb19a5b08445a63bb64fa9e',
+               'uint8': '001aac3a5acb935a9b186cbe14a1ca064b8bb2dd0b045d48abeacf74d0203404'}
+
+        for dt in self.itype[1:]:
+            random.seed(1234)
+
+            # view as little endian for hash
+            if sys.byteorder == 'little':
+                val = self.rfunc(0, 6, size=1000, dtype=dt)
+            else:
+                val = self.rfunc(0, 6, size=1000, dtype=dt).byteswap()
+
+            res = hashlib.sha256(val.view(np.int8)).hexdigest()
+            assert_(tgt[np.dtype(dt).name] == res)
+
+        # bools do not depend on endianness
+        random.seed(1234)
+        val = self.rfunc(0, 2, size=1000, dtype=bool).view(np.int8)
+        res = hashlib.sha256(val).hexdigest()
+        assert_(tgt[np.dtype(bool).name] == res)
+
+    @pytest.mark.skipif(np.iinfo('l').max < 2**32,
+                        reason='Cannot test with 32-bit C long')
+    def test_repeatability_32bit_boundary_broadcasting(self):
+        desired = np.array([[[3992670689, 2438360420, 2557845020],
+                             [4107320065, 4142558326, 3216529513],
+                             [1605979228, 2807061240,  665605495]],
+                            [[3211410639, 4128781000,  457175120],
+                             [1712592594, 1282922662, 3081439808],
+                             [3997822960, 2008322436, 1563495165]],
+                            [[1398375547, 4269260146,  115316740],
+                             [3414372578, 3437564012, 2112038651],
+                             [3572980305, 2260248732, 3908238631]],
+                            [[2561372503,  223155946, 3127879445],
+                             [ 441282060, 3514786552, 2148440361],
+                             [1629275283, 3479737011, 3003195987]],
+                            [[ 412181688,  940383289, 3047321305],
+                             [2978368172,  764731833, 2282559898],
+                             [ 105711276,  720447391, 3596512484]]])
+        for size in [None, (5, 3, 3)]:
+            random.seed(12345)
+            x = self.rfunc([[-1], [0], [1]], [2**32 - 1, 2**32, 2**32 + 1],
+                           size=size)
+            assert_array_equal(x, desired if size is not None else desired[0])
+
+    def test_int64_uint64_corner_case(self):
+        # When stored in Numpy arrays, `lbnd` is casted
+        # as np.int64, and `ubnd` is casted as np.uint64.
+        # Checking whether `lbnd` >= `ubnd` used to be
+        # done solely via direct comparison, which is incorrect
+        # because when Numpy tries to compare both numbers,
+        # it casts both to np.float64 because there is
+        # no integer superset of np.int64 and np.uint64. However,
+        # `ubnd` is too large to be represented in np.float64,
+        # causing it be round down to np.iinfo(np.int64).max,
+        # leading to a ValueError because `lbnd` now equals
+        # the new `ubnd`.
+
+        dt = np.int64
+        tgt = np.iinfo(np.int64).max
+        lbnd = np.int64(np.iinfo(np.int64).max)
+        ubnd = np.uint64(np.iinfo(np.int64).max + 1)
+
+        # None of these function calls should
+        # generate a ValueError now.
+        actual = random.randint(lbnd, ubnd, dtype=dt)
+        assert_equal(actual, tgt)
+
+    def test_respect_dtype_singleton(self):
+        # See gh-7203
+        for dt in self.itype:
+            lbnd = 0 if dt is np.bool_ else np.iinfo(dt).min
+            ubnd = 2 if dt is np.bool_ else np.iinfo(dt).max + 1
+
+            sample = self.rfunc(lbnd, ubnd, dtype=dt)
+            assert_equal(sample.dtype, np.dtype(dt))
+
+        for dt in (bool, int):
+            lbnd = 0 if dt is bool else np.iinfo(dt).min
+            ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
+
+            # gh-7284: Ensure that we get Python data types
+            sample = self.rfunc(lbnd, ubnd, dtype=dt)
+            assert_(not hasattr(sample, 'dtype'))
+            assert_equal(type(sample), dt)
+
+
+class TestRandomDist:
+    # Make sure the random distribution returns the correct value for a
+    # given seed
+
+    def setup_method(self):
+        self.seed = 1234567890
+
+    def test_rand(self):
+        random.seed(self.seed)
+        actual = random.rand(3, 2)
+        desired = np.array([[0.61879477158567997, 0.59162362775974664],
+                            [0.88868358904449662, 0.89165480011560816],
+                            [0.4575674820298663, 0.7781880808593471]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_rand_singleton(self):
+        random.seed(self.seed)
+        actual = random.rand()
+        desired = 0.61879477158567997
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_randn(self):
+        random.seed(self.seed)
+        actual = random.randn(3, 2)
+        desired = np.array([[1.34016345771863121, 1.73759122771936081],
+                           [1.498988344300628, -0.2286433324536169],
+                           [2.031033998682787, 2.17032494605655257]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+        random.seed(self.seed)
+        actual = random.randn()
+        assert_array_almost_equal(actual, desired[0, 0], decimal=15)
+
+    def test_randint(self):
+        random.seed(self.seed)
+        actual = random.randint(-99, 99, size=(3, 2))
+        desired = np.array([[31, 3],
+                            [-52, 41],
+                            [-48, -66]])
+        assert_array_equal(actual, desired)
+
+    def test_random_integers(self):
+        random.seed(self.seed)
+        with suppress_warnings() as sup:
+            w = sup.record(DeprecationWarning)
+            actual = random.random_integers(-99, 99, size=(3, 2))
+            assert_(len(w) == 1)
+        desired = np.array([[31, 3],
+                            [-52, 41],
+                            [-48, -66]])
+        assert_array_equal(actual, desired)
+
+        random.seed(self.seed)
+        with suppress_warnings() as sup:
+            w = sup.record(DeprecationWarning)
+            actual = random.random_integers(198, size=(3, 2))
+            assert_(len(w) == 1)
+        assert_array_equal(actual, desired + 100)
+
+    def test_tomaxint(self):
+        random.seed(self.seed)
+        rs = random.RandomState(self.seed)
+        actual = rs.tomaxint(size=(3, 2))
+        if np.iinfo(int).max == 2147483647:
+            desired = np.array([[1328851649,  731237375],
+                                [1270502067,  320041495],
+                                [1908433478,  499156889]], dtype=np.int64)
+        else:
+            desired = np.array([[5707374374421908479, 5456764827585442327],
+                                [8196659375100692377, 8224063923314595285],
+                                [4220315081820346526, 7177518203184491332]],
+                               dtype=np.int64)
+
+        assert_equal(actual, desired)
+
+        rs.seed(self.seed)
+        actual = rs.tomaxint()
+        assert_equal(actual, desired[0, 0])
+
+    def test_random_integers_max_int(self):
+        # Tests whether random_integers can generate the
+        # maximum allowed Python int that can be converted
+        # into a C long. Previous implementations of this
+        # method have thrown an OverflowError when attempting
+        # to generate this integer.
+        with suppress_warnings() as sup:
+            w = sup.record(DeprecationWarning)
+            actual = random.random_integers(np.iinfo('l').max,
+                                            np.iinfo('l').max)
+            assert_(len(w) == 1)
+
+        desired = np.iinfo('l').max
+        assert_equal(actual, desired)
+        with suppress_warnings() as sup:
+            w = sup.record(DeprecationWarning)
+            typer = np.dtype('l').type
+            actual = random.random_integers(typer(np.iinfo('l').max),
+                                            typer(np.iinfo('l').max))
+            assert_(len(w) == 1)
+        assert_equal(actual, desired)
+
+    def test_random_integers_deprecated(self):
+        with warnings.catch_warnings():
+            warnings.simplefilter("error", DeprecationWarning)
+
+            # DeprecationWarning raised with high == None
+            assert_raises(DeprecationWarning,
+                          random.random_integers,
+                          np.iinfo('l').max)
+
+            # DeprecationWarning raised with high != None
+            assert_raises(DeprecationWarning,
+                          random.random_integers,
+                          np.iinfo('l').max, np.iinfo('l').max)
+
+    def test_random_sample(self):
+        random.seed(self.seed)
+        actual = random.random_sample((3, 2))
+        desired = np.array([[0.61879477158567997, 0.59162362775974664],
+                            [0.88868358904449662, 0.89165480011560816],
+                            [0.4575674820298663, 0.7781880808593471]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+        random.seed(self.seed)
+        actual = random.random_sample()
+        assert_array_almost_equal(actual, desired[0, 0], decimal=15)
+
+    def test_choice_uniform_replace(self):
+        random.seed(self.seed)
+        actual = random.choice(4, 4)
+        desired = np.array([2, 3, 2, 3])
+        assert_array_equal(actual, desired)
+
+    def test_choice_nonuniform_replace(self):
+        random.seed(self.seed)
+        actual = random.choice(4, 4, p=[0.4, 0.4, 0.1, 0.1])
+        desired = np.array([1, 1, 2, 2])
+        assert_array_equal(actual, desired)
+
+    def test_choice_uniform_noreplace(self):
+        random.seed(self.seed)
+        actual = random.choice(4, 3, replace=False)
+        desired = np.array([0, 1, 3])
+        assert_array_equal(actual, desired)
+
+    def test_choice_nonuniform_noreplace(self):
+        random.seed(self.seed)
+        actual = random.choice(4, 3, replace=False, p=[0.1, 0.3, 0.5, 0.1])
+        desired = np.array([2, 3, 1])
+        assert_array_equal(actual, desired)
+
+    def test_choice_noninteger(self):
+        random.seed(self.seed)
+        actual = random.choice(['a', 'b', 'c', 'd'], 4)
+        desired = np.array(['c', 'd', 'c', 'd'])
+        assert_array_equal(actual, desired)
+
+    def test_choice_exceptions(self):
+        sample = random.choice
+        assert_raises(ValueError, sample, -1, 3)
+        assert_raises(ValueError, sample, 3., 3)
+        assert_raises(ValueError, sample, [[1, 2], [3, 4]], 3)
+        assert_raises(ValueError, sample, [], 3)
+        assert_raises(ValueError, sample, [1, 2, 3, 4], 3,
+                      p=[[0.25, 0.25], [0.25, 0.25]])
+        assert_raises(ValueError, sample, [1, 2], 3, p=[0.4, 0.4, 0.2])
+        assert_raises(ValueError, sample, [1, 2], 3, p=[1.1, -0.1])
+        assert_raises(ValueError, sample, [1, 2], 3, p=[0.4, 0.4])
+        assert_raises(ValueError, sample, [1, 2, 3], 4, replace=False)
+        # gh-13087
+        assert_raises(ValueError, sample, [1, 2, 3], -2, replace=False)
+        assert_raises(ValueError, sample, [1, 2, 3], (-1,), replace=False)
+        assert_raises(ValueError, sample, [1, 2, 3], (-1, 1), replace=False)
+        assert_raises(ValueError, sample, [1, 2, 3], 2,
+                      replace=False, p=[1, 0, 0])
+
+    def test_choice_return_shape(self):
+        p = [0.1, 0.9]
+        # Check scalar
+        assert_(np.isscalar(random.choice(2, replace=True)))
+        assert_(np.isscalar(random.choice(2, replace=False)))
+        assert_(np.isscalar(random.choice(2, replace=True, p=p)))
+        assert_(np.isscalar(random.choice(2, replace=False, p=p)))
+        assert_(np.isscalar(random.choice([1, 2], replace=True)))
+        assert_(random.choice([None], replace=True) is None)
+        a = np.array([1, 2])
+        arr = np.empty(1, dtype=object)
+        arr[0] = a
+        assert_(random.choice(arr, replace=True) is a)
+
+        # Check 0-d array
+        s = tuple()
+        assert_(not np.isscalar(random.choice(2, s, replace=True)))
+        assert_(not np.isscalar(random.choice(2, s, replace=False)))
+        assert_(not np.isscalar(random.choice(2, s, replace=True, p=p)))
+        assert_(not np.isscalar(random.choice(2, s, replace=False, p=p)))
+        assert_(not np.isscalar(random.choice([1, 2], s, replace=True)))
+        assert_(random.choice([None], s, replace=True).ndim == 0)
+        a = np.array([1, 2])
+        arr = np.empty(1, dtype=object)
+        arr[0] = a
+        assert_(random.choice(arr, s, replace=True).item() is a)
+
+        # Check multi dimensional array
+        s = (2, 3)
+        p = [0.1, 0.1, 0.1, 0.1, 0.4, 0.2]
+        assert_equal(random.choice(6, s, replace=True).shape, s)
+        assert_equal(random.choice(6, s, replace=False).shape, s)
+        assert_equal(random.choice(6, s, replace=True, p=p).shape, s)
+        assert_equal(random.choice(6, s, replace=False, p=p).shape, s)
+        assert_equal(random.choice(np.arange(6), s, replace=True).shape, s)
+
+        # Check zero-size
+        assert_equal(random.randint(0, 0, size=(3, 0, 4)).shape, (3, 0, 4))
+        assert_equal(random.randint(0, -10, size=0).shape, (0,))
+        assert_equal(random.randint(10, 10, size=0).shape, (0,))
+        assert_equal(random.choice(0, size=0).shape, (0,))
+        assert_equal(random.choice([], size=(0,)).shape, (0,))
+        assert_equal(random.choice(['a', 'b'], size=(3, 0, 4)).shape,
+                     (3, 0, 4))
+        assert_raises(ValueError, random.choice, [], 10)
+
+    def test_choice_nan_probabilities(self):
+        a = np.array([42, 1, 2])
+        p = [None, None, None]
+        assert_raises(ValueError, random.choice, a, p=p)
+
+    def test_choice_p_non_contiguous(self):
+        p = np.ones(10) / 5
+        p[1::2] = 3.0
+        random.seed(self.seed)
+        non_contig = random.choice(5, 3, p=p[::2])
+        random.seed(self.seed)
+        contig = random.choice(5, 3, p=np.ascontiguousarray(p[::2]))
+        assert_array_equal(non_contig, contig)
+
+    def test_bytes(self):
+        random.seed(self.seed)
+        actual = random.bytes(10)
+        desired = b'\x82Ui\x9e\xff\x97+Wf\xa5'
+        assert_equal(actual, desired)
+
+    def test_shuffle(self):
+        # Test lists, arrays (of various dtypes), and multidimensional versions
+        # of both, c-contiguous or not:
+        for conv in [lambda x: np.array([]),
+                     lambda x: x,
+                     lambda x: np.asarray(x).astype(np.int8),
+                     lambda x: np.asarray(x).astype(np.float32),
+                     lambda x: np.asarray(x).astype(np.complex64),
+                     lambda x: np.asarray(x).astype(object),
+                     lambda x: [(i, i) for i in x],
+                     lambda x: np.asarray([[i, i] for i in x]),
+                     lambda x: np.vstack([x, x]).T,
+                     # gh-11442
+                     lambda x: (np.asarray([(i, i) for i in x],
+                                           [("a", int), ("b", int)])
+                                .view(np.recarray)),
+                     # gh-4270
+                     lambda x: np.asarray([(i, i) for i in x],
+                                          [("a", object, (1,)),
+                                           ("b", np.int32, (1,))])]:
+            random.seed(self.seed)
+            alist = conv([1, 2, 3, 4, 5, 6, 7, 8, 9, 0])
+            random.shuffle(alist)
+            actual = alist
+            desired = conv([0, 1, 9, 6, 2, 4, 5, 8, 7, 3])
+            assert_array_equal(actual, desired)
+
+    def test_shuffle_masked(self):
+        # gh-3263
+        a = np.ma.masked_values(np.reshape(range(20), (5, 4)) % 3 - 1, -1)
+        b = np.ma.masked_values(np.arange(20) % 3 - 1, -1)
+        a_orig = a.copy()
+        b_orig = b.copy()
+        for i in range(50):
+            random.shuffle(a)
+            assert_equal(
+                sorted(a.data[~a.mask]), sorted(a_orig.data[~a_orig.mask]))
+            random.shuffle(b)
+            assert_equal(
+                sorted(b.data[~b.mask]), sorted(b_orig.data[~b_orig.mask]))
+
+        def test_shuffle_invalid_objects(self):
+            x = np.array(3)
+            assert_raises(TypeError, random.shuffle, x)
+
+    def test_permutation(self):
+        random.seed(self.seed)
+        alist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
+        actual = random.permutation(alist)
+        desired = [0, 1, 9, 6, 2, 4, 5, 8, 7, 3]
+        assert_array_equal(actual, desired)
+
+        random.seed(self.seed)
+        arr_2d = np.atleast_2d([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]).T
+        actual = random.permutation(arr_2d)
+        assert_array_equal(actual, np.atleast_2d(desired).T)
+
+        random.seed(self.seed)
+        bad_x_str = "abcd"
+        assert_raises(IndexError, random.permutation, bad_x_str)
+
+        random.seed(self.seed)
+        bad_x_float = 1.2
+        assert_raises(IndexError, random.permutation, bad_x_float)
+
+        integer_val = 10
+        desired = [9, 0, 8, 5, 1, 3, 4, 7, 6, 2]
+
+        random.seed(self.seed)
+        actual = random.permutation(integer_val)
+        assert_array_equal(actual, desired)
+
+    def test_beta(self):
+        random.seed(self.seed)
+        actual = random.beta(.1, .9, size=(3, 2))
+        desired = np.array(
+                [[1.45341850513746058e-02, 5.31297615662868145e-04],
+                 [1.85366619058432324e-06, 4.19214516800110563e-03],
+                 [1.58405155108498093e-04, 1.26252891949397652e-04]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_binomial(self):
+        random.seed(self.seed)
+        actual = random.binomial(100.123, .456, size=(3, 2))
+        desired = np.array([[37, 43],
+                            [42, 48],
+                            [46, 45]])
+        assert_array_equal(actual, desired)
+
+        random.seed(self.seed)
+        actual = random.binomial(100.123, .456)
+        desired = 37
+        assert_array_equal(actual, desired)
+
+    def test_chisquare(self):
+        random.seed(self.seed)
+        actual = random.chisquare(50, size=(3, 2))
+        desired = np.array([[63.87858175501090585, 68.68407748911370447],
+                            [65.77116116901505904, 47.09686762438974483],
+                            [72.3828403199695174, 74.18408615260374006]])
+        assert_array_almost_equal(actual, desired, decimal=13)
+
+    def test_dirichlet(self):
+        random.seed(self.seed)
+        alpha = np.array([51.72840233779265162, 39.74494232180943953])
+        actual = random.dirichlet(alpha, size=(3, 2))
+        desired = np.array([[[0.54539444573611562, 0.45460555426388438],
+                             [0.62345816822039413, 0.37654183177960598]],
+                            [[0.55206000085785778, 0.44793999914214233],
+                             [0.58964023305154301, 0.41035976694845688]],
+                            [[0.59266909280647828, 0.40733090719352177],
+                             [0.56974431743975207, 0.43025568256024799]]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+        bad_alpha = np.array([5.4e-01, -1.0e-16])
+        assert_raises(ValueError, random.dirichlet, bad_alpha)
+
+        random.seed(self.seed)
+        alpha = np.array([51.72840233779265162, 39.74494232180943953])
+        actual = random.dirichlet(alpha)
+        assert_array_almost_equal(actual, desired[0, 0], decimal=15)
+
+    def test_dirichlet_size(self):
+        # gh-3173
+        p = np.array([51.72840233779265162, 39.74494232180943953])
+        assert_equal(random.dirichlet(p, np.uint32(1)).shape, (1, 2))
+        assert_equal(random.dirichlet(p, np.uint32(1)).shape, (1, 2))
+        assert_equal(random.dirichlet(p, np.uint32(1)).shape, (1, 2))
+        assert_equal(random.dirichlet(p, [2, 2]).shape, (2, 2, 2))
+        assert_equal(random.dirichlet(p, (2, 2)).shape, (2, 2, 2))
+        assert_equal(random.dirichlet(p, np.array((2, 2))).shape, (2, 2, 2))
+
+        assert_raises(TypeError, random.dirichlet, p, float(1))
+
+    def test_dirichlet_bad_alpha(self):
+        # gh-2089
+        alpha = np.array([5.4e-01, -1.0e-16])
+        assert_raises(ValueError, random.dirichlet, alpha)
+
+    def test_dirichlet_alpha_non_contiguous(self):
+        a = np.array([51.72840233779265162, -1.0, 39.74494232180943953])
+        alpha = a[::2]
+        random.seed(self.seed)
+        non_contig = random.dirichlet(alpha, size=(3, 2))
+        random.seed(self.seed)
+        contig = random.dirichlet(np.ascontiguousarray(alpha),
+                                  size=(3, 2))
+        assert_array_almost_equal(non_contig, contig)
+
+    def test_exponential(self):
+        random.seed(self.seed)
+        actual = random.exponential(1.1234, size=(3, 2))
+        desired = np.array([[1.08342649775011624, 1.00607889924557314],
+                            [2.46628830085216721, 2.49668106809923884],
+                            [0.68717433461363442, 1.69175666993575979]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_exponential_0(self):
+        assert_equal(random.exponential(scale=0), 0)
+        assert_raises(ValueError, random.exponential, scale=-0.)
+
+    def test_f(self):
+        random.seed(self.seed)
+        actual = random.f(12, 77, size=(3, 2))
+        desired = np.array([[1.21975394418575878, 1.75135759791559775],
+                            [1.44803115017146489, 1.22108959480396262],
+                            [1.02176975757740629, 1.34431827623300415]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_gamma(self):
+        random.seed(self.seed)
+        actual = random.gamma(5, 3, size=(3, 2))
+        desired = np.array([[24.60509188649287182, 28.54993563207210627],
+                            [26.13476110204064184, 12.56988482927716078],
+                            [31.71863275789960568, 33.30143302795922011]])
+        assert_array_almost_equal(actual, desired, decimal=14)
+
+    def test_gamma_0(self):
+        assert_equal(random.gamma(shape=0, scale=0), 0)
+        assert_raises(ValueError, random.gamma, shape=-0., scale=-0.)
+
+    def test_geometric(self):
+        random.seed(self.seed)
+        actual = random.geometric(.123456789, size=(3, 2))
+        desired = np.array([[8, 7],
+                            [17, 17],
+                            [5, 12]])
+        assert_array_equal(actual, desired)
+
+    def test_geometric_exceptions(self):
+        assert_raises(ValueError, random.geometric, 1.1)
+        assert_raises(ValueError, random.geometric, [1.1] * 10)
+        assert_raises(ValueError, random.geometric, -0.1)
+        assert_raises(ValueError, random.geometric, [-0.1] * 10)
+        with suppress_warnings() as sup:
+            sup.record(RuntimeWarning)
+            assert_raises(ValueError, random.geometric, np.nan)
+            assert_raises(ValueError, random.geometric, [np.nan] * 10)
+
+    def test_gumbel(self):
+        random.seed(self.seed)
+        actual = random.gumbel(loc=.123456789, scale=2.0, size=(3, 2))
+        desired = np.array([[0.19591898743416816, 0.34405539668096674],
+                            [-1.4492522252274278, -1.47374816298446865],
+                            [1.10651090478803416, -0.69535848626236174]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_gumbel_0(self):
+        assert_equal(random.gumbel(scale=0), 0)
+        assert_raises(ValueError, random.gumbel, scale=-0.)
+
+    def test_hypergeometric(self):
+        random.seed(self.seed)
+        actual = random.hypergeometric(10.1, 5.5, 14, size=(3, 2))
+        desired = np.array([[10, 10],
+                            [10, 10],
+                            [9, 9]])
+        assert_array_equal(actual, desired)
+
+        # Test nbad = 0
+        actual = random.hypergeometric(5, 0, 3, size=4)
+        desired = np.array([3, 3, 3, 3])
+        assert_array_equal(actual, desired)
+
+        actual = random.hypergeometric(15, 0, 12, size=4)
+        desired = np.array([12, 12, 12, 12])
+        assert_array_equal(actual, desired)
+
+        # Test ngood = 0
+        actual = random.hypergeometric(0, 5, 3, size=4)
+        desired = np.array([0, 0, 0, 0])
+        assert_array_equal(actual, desired)
+
+        actual = random.hypergeometric(0, 15, 12, size=4)
+        desired = np.array([0, 0, 0, 0])
+        assert_array_equal(actual, desired)
+
+    def test_laplace(self):
+        random.seed(self.seed)
+        actual = random.laplace(loc=.123456789, scale=2.0, size=(3, 2))
+        desired = np.array([[0.66599721112760157, 0.52829452552221945],
+                            [3.12791959514407125, 3.18202813572992005],
+                            [-0.05391065675859356, 1.74901336242837324]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_laplace_0(self):
+        assert_equal(random.laplace(scale=0), 0)
+        assert_raises(ValueError, random.laplace, scale=-0.)
+
+    def test_logistic(self):
+        random.seed(self.seed)
+        actual = random.logistic(loc=.123456789, scale=2.0, size=(3, 2))
+        desired = np.array([[1.09232835305011444, 0.8648196662399954],
+                            [4.27818590694950185, 4.33897006346929714],
+                            [-0.21682183359214885, 2.63373365386060332]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_lognormal(self):
+        random.seed(self.seed)
+        actual = random.lognormal(mean=.123456789, sigma=2.0, size=(3, 2))
+        desired = np.array([[16.50698631688883822, 36.54846706092654784],
+                            [22.67886599981281748, 0.71617561058995771],
+                            [65.72798501792723869, 86.84341601437161273]])
+        assert_array_almost_equal(actual, desired, decimal=13)
+
+    def test_lognormal_0(self):
+        assert_equal(random.lognormal(sigma=0), 1)
+        assert_raises(ValueError, random.lognormal, sigma=-0.)
+
+    def test_logseries(self):
+        random.seed(self.seed)
+        actual = random.logseries(p=.923456789, size=(3, 2))
+        desired = np.array([[2, 2],
+                            [6, 17],
+                            [3, 6]])
+        assert_array_equal(actual, desired)
+
+    def test_logseries_zero(self):
+        assert random.logseries(0) == 1
+
+    @pytest.mark.parametrize("value", [np.nextafter(0., -1), 1., np.nan, 5.])
+    def test_logseries_exceptions(self, value):
+        with np.errstate(invalid="ignore"):
+            with pytest.raises(ValueError):
+                random.logseries(value)
+            with pytest.raises(ValueError):
+                # contiguous path:
+                random.logseries(np.array([value] * 10))
+            with pytest.raises(ValueError):
+                # non-contiguous path:
+                random.logseries(np.array([value] * 10)[::2])
+
+    def test_multinomial(self):
+        random.seed(self.seed)
+        actual = random.multinomial(20, [1 / 6.] * 6, size=(3, 2))
+        desired = np.array([[[4, 3, 5, 4, 2, 2],
+                             [5, 2, 8, 2, 2, 1]],
+                            [[3, 4, 3, 6, 0, 4],
+                             [2, 1, 4, 3, 6, 4]],
+                            [[4, 4, 2, 5, 2, 3],
+                             [4, 3, 4, 2, 3, 4]]])
+        assert_array_equal(actual, desired)
+
+    def test_multivariate_normal(self):
+        random.seed(self.seed)
+        mean = (.123456789, 10)
+        cov = [[1, 0], [0, 1]]
+        size = (3, 2)
+        actual = random.multivariate_normal(mean, cov, size)
+        desired = np.array([[[1.463620246718631, 11.73759122771936],
+                             [1.622445133300628, 9.771356667546383]],
+                            [[2.154490787682787, 12.170324946056553],
+                             [1.719909438201865, 9.230548443648306]],
+                            [[0.689515026297799, 9.880729819607714],
+                             [-0.023054015651998, 9.201096623542879]]])
+
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+        # Check for default size, was raising deprecation warning
+        actual = random.multivariate_normal(mean, cov)
+        desired = np.array([0.895289569463708, 9.17180864067987])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+        # Check that non positive-semidefinite covariance warns with
+        # RuntimeWarning
+        mean = [0, 0]
+        cov = [[1, 2], [2, 1]]
+        assert_warns(RuntimeWarning, random.multivariate_normal, mean, cov)
+
+        # and that it doesn't warn with RuntimeWarning check_valid='ignore'
+        assert_no_warnings(random.multivariate_normal, mean, cov,
+                           check_valid='ignore')
+
+        # and that it raises with RuntimeWarning check_valid='raises'
+        assert_raises(ValueError, random.multivariate_normal, mean, cov,
+                      check_valid='raise')
+
+        cov = np.array([[1, 0.1], [0.1, 1]], dtype=np.float32)
+        with suppress_warnings() as sup:
+            random.multivariate_normal(mean, cov)
+            w = sup.record(RuntimeWarning)
+            assert len(w) == 0
+
+        mu = np.zeros(2)
+        cov = np.eye(2)
+        assert_raises(ValueError, random.multivariate_normal, mean, cov,
+                      check_valid='other')
+        assert_raises(ValueError, random.multivariate_normal,
+                      np.zeros((2, 1, 1)), cov)
+        assert_raises(ValueError, random.multivariate_normal,
+                      mu, np.empty((3, 2)))
+        assert_raises(ValueError, random.multivariate_normal,
+                      mu, np.eye(3))
+
+    def test_negative_binomial(self):
+        random.seed(self.seed)
+        actual = random.negative_binomial(n=100, p=.12345, size=(3, 2))
+        desired = np.array([[848, 841],
+                            [892, 611],
+                            [779, 647]])
+        assert_array_equal(actual, desired)
+
+    def test_negative_binomial_exceptions(self):
+        with suppress_warnings() as sup:
+            sup.record(RuntimeWarning)
+            assert_raises(ValueError, random.negative_binomial, 100, np.nan)
+            assert_raises(ValueError, random.negative_binomial, 100,
+                          [np.nan] * 10)
+
+    def test_noncentral_chisquare(self):
+        random.seed(self.seed)
+        actual = random.noncentral_chisquare(df=5, nonc=5, size=(3, 2))
+        desired = np.array([[23.91905354498517511, 13.35324692733826346],
+                            [31.22452661329736401, 16.60047399466177254],
+                            [5.03461598262724586, 17.94973089023519464]])
+        assert_array_almost_equal(actual, desired, decimal=14)
+
+        actual = random.noncentral_chisquare(df=.5, nonc=.2, size=(3, 2))
+        desired = np.array([[1.47145377828516666,  0.15052899268012659],
+                            [0.00943803056963588,  1.02647251615666169],
+                            [0.332334982684171,  0.15451287602753125]])
+        assert_array_almost_equal(actual, desired, decimal=14)
+
+        random.seed(self.seed)
+        actual = random.noncentral_chisquare(df=5, nonc=0, size=(3, 2))
+        desired = np.array([[9.597154162763948, 11.725484450296079],
+                            [10.413711048138335, 3.694475922923986],
+                            [13.484222138963087, 14.377255424602957]])
+        assert_array_almost_equal(actual, desired, decimal=14)
+
+    def test_noncentral_f(self):
+        random.seed(self.seed)
+        actual = random.noncentral_f(dfnum=5, dfden=2, nonc=1,
+                                     size=(3, 2))
+        desired = np.array([[1.40598099674926669, 0.34207973179285761],
+                            [3.57715069265772545, 7.92632662577829805],
+                            [0.43741599463544162, 1.1774208752428319]])
+        assert_array_almost_equal(actual, desired, decimal=14)
+
+    def test_noncentral_f_nan(self):
+        random.seed(self.seed)
+        actual = random.noncentral_f(dfnum=5, dfden=2, nonc=np.nan)
+        assert np.isnan(actual)
+
+    def test_normal(self):
+        random.seed(self.seed)
+        actual = random.normal(loc=.123456789, scale=2.0, size=(3, 2))
+        desired = np.array([[2.80378370443726244, 3.59863924443872163],
+                            [3.121433477601256, -0.33382987590723379],
+                            [4.18552478636557357, 4.46410668111310471]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_normal_0(self):
+        assert_equal(random.normal(scale=0), 0)
+        assert_raises(ValueError, random.normal, scale=-0.)
+
+    def test_pareto(self):
+        random.seed(self.seed)
+        actual = random.pareto(a=.123456789, size=(3, 2))
+        desired = np.array(
+                [[2.46852460439034849e+03, 1.41286880810518346e+03],
+                 [5.28287797029485181e+07, 6.57720981047328785e+07],
+                 [1.40840323350391515e+02, 1.98390255135251704e+05]])
+        # For some reason on 32-bit x86 Ubuntu 12.10 the [1, 0] entry in this
+        # matrix differs by 24 nulps. Discussion:
+        #   https://mail.python.org/pipermail/numpy-discussion/2012-September/063801.html
+        # Consensus is that this is probably some gcc quirk that affects
+        # rounding but not in any important way, so we just use a looser
+        # tolerance on this test:
+        np.testing.assert_array_almost_equal_nulp(actual, desired, nulp=30)
+
+    def test_poisson(self):
+        random.seed(self.seed)
+        actual = random.poisson(lam=.123456789, size=(3, 2))
+        desired = np.array([[0, 0],
+                            [1, 0],
+                            [0, 0]])
+        assert_array_equal(actual, desired)
+
+    def test_poisson_exceptions(self):
+        lambig = np.iinfo('l').max
+        lamneg = -1
+        assert_raises(ValueError, random.poisson, lamneg)
+        assert_raises(ValueError, random.poisson, [lamneg] * 10)
+        assert_raises(ValueError, random.poisson, lambig)
+        assert_raises(ValueError, random.poisson, [lambig] * 10)
+        with suppress_warnings() as sup:
+            sup.record(RuntimeWarning)
+            assert_raises(ValueError, random.poisson, np.nan)
+            assert_raises(ValueError, random.poisson, [np.nan] * 10)
+
+    def test_power(self):
+        random.seed(self.seed)
+        actual = random.power(a=.123456789, size=(3, 2))
+        desired = np.array([[0.02048932883240791, 0.01424192241128213],
+                            [0.38446073748535298, 0.39499689943484395],
+                            [0.00177699707563439, 0.13115505880863756]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_rayleigh(self):
+        random.seed(self.seed)
+        actual = random.rayleigh(scale=10, size=(3, 2))
+        desired = np.array([[13.8882496494248393, 13.383318339044731],
+                            [20.95413364294492098, 21.08285015800712614],
+                            [11.06066537006854311, 17.35468505778271009]])
+        assert_array_almost_equal(actual, desired, decimal=14)
+
+    def test_rayleigh_0(self):
+        assert_equal(random.rayleigh(scale=0), 0)
+        assert_raises(ValueError, random.rayleigh, scale=-0.)
+
+    def test_standard_cauchy(self):
+        random.seed(self.seed)
+        actual = random.standard_cauchy(size=(3, 2))
+        desired = np.array([[0.77127660196445336, -6.55601161955910605],
+                            [0.93582023391158309, -2.07479293013759447],
+                            [-4.74601644297011926, 0.18338989290760804]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_standard_exponential(self):
+        random.seed(self.seed)
+        actual = random.standard_exponential(size=(3, 2))
+        desired = np.array([[0.96441739162374596, 0.89556604882105506],
+                            [2.1953785836319808, 2.22243285392490542],
+                            [0.6116915921431676, 1.50592546727413201]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_standard_gamma(self):
+        random.seed(self.seed)
+        actual = random.standard_gamma(shape=3, size=(3, 2))
+        desired = np.array([[5.50841531318455058, 6.62953470301903103],
+                            [5.93988484943779227, 2.31044849402133989],
+                            [7.54838614231317084, 8.012756093271868]])
+        assert_array_almost_equal(actual, desired, decimal=14)
+
+    def test_standard_gamma_0(self):
+        assert_equal(random.standard_gamma(shape=0), 0)
+        assert_raises(ValueError, random.standard_gamma, shape=-0.)
+
+    def test_standard_normal(self):
+        random.seed(self.seed)
+        actual = random.standard_normal(size=(3, 2))
+        desired = np.array([[1.34016345771863121, 1.73759122771936081],
+                            [1.498988344300628, -0.2286433324536169],
+                            [2.031033998682787, 2.17032494605655257]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_randn_singleton(self):
+        random.seed(self.seed)
+        actual = random.randn()
+        desired = np.array(1.34016345771863121)
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_standard_t(self):
+        random.seed(self.seed)
+        actual = random.standard_t(df=10, size=(3, 2))
+        desired = np.array([[0.97140611862659965, -0.08830486548450577],
+                            [1.36311143689505321, -0.55317463909867071],
+                            [-0.18473749069684214, 0.61181537341755321]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_triangular(self):
+        random.seed(self.seed)
+        actual = random.triangular(left=5.12, mode=10.23, right=20.34,
+                                   size=(3, 2))
+        desired = np.array([[12.68117178949215784, 12.4129206149193152],
+                            [16.20131377335158263, 16.25692138747600524],
+                            [11.20400690911820263, 14.4978144835829923]])
+        assert_array_almost_equal(actual, desired, decimal=14)
+
+    def test_uniform(self):
+        random.seed(self.seed)
+        actual = random.uniform(low=1.23, high=10.54, size=(3, 2))
+        desired = np.array([[6.99097932346268003, 6.73801597444323974],
+                            [9.50364421400426274, 9.53130618907631089],
+                            [5.48995325769805476, 8.47493103280052118]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_uniform_range_bounds(self):
+        fmin = np.finfo('float').min
+        fmax = np.finfo('float').max
+
+        func = random.uniform
+        assert_raises(OverflowError, func, -np.inf, 0)
+        assert_raises(OverflowError, func, 0, np.inf)
+        assert_raises(OverflowError, func, fmin, fmax)
+        assert_raises(OverflowError, func, [-np.inf], [0])
+        assert_raises(OverflowError, func, [0], [np.inf])
+
+        # (fmax / 1e17) - fmin is within range, so this should not throw
+        # account for i386 extended precision DBL_MAX / 1e17 + DBL_MAX >
+        # DBL_MAX by increasing fmin a bit
+        random.uniform(low=np.nextafter(fmin, 1), high=fmax / 1e17)
+
+    def test_scalar_exception_propagation(self):
+        # Tests that exceptions are correctly propagated in distributions
+        # when called with objects that throw exceptions when converted to
+        # scalars.
+        #
+        # Regression test for gh: 8865
+
+        class ThrowingFloat(np.ndarray):
+            def __float__(self):
+                raise TypeError
+
+        throwing_float = np.array(1.0).view(ThrowingFloat)
+        assert_raises(TypeError, random.uniform, throwing_float,
+                      throwing_float)
+
+        class ThrowingInteger(np.ndarray):
+            def __int__(self):
+                raise TypeError
+
+        throwing_int = np.array(1).view(ThrowingInteger)
+        assert_raises(TypeError, random.hypergeometric, throwing_int, 1, 1)
+
+    def test_vonmises(self):
+        random.seed(self.seed)
+        actual = random.vonmises(mu=1.23, kappa=1.54, size=(3, 2))
+        desired = np.array([[2.28567572673902042, 2.89163838442285037],
+                            [0.38198375564286025, 2.57638023113890746],
+                            [1.19153771588353052, 1.83509849681825354]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_vonmises_small(self):
+        # check infinite loop, gh-4720
+        random.seed(self.seed)
+        r = random.vonmises(mu=0., kappa=1.1e-8, size=10**6)
+        assert_(np.isfinite(r).all())
+
+    def test_vonmises_large(self):
+        # guard against changes in RandomState when Generator is fixed
+        random.seed(self.seed)
+        actual = random.vonmises(mu=0., kappa=1e7, size=3)
+        desired = np.array([4.634253748521111e-04,
+                            3.558873596114509e-04,
+                            -2.337119622577433e-04])
+        assert_array_almost_equal(actual, desired, decimal=8)
+
+    def test_vonmises_nan(self):
+        random.seed(self.seed)
+        r = random.vonmises(mu=0., kappa=np.nan)
+        assert_(np.isnan(r))
+
+    def test_wald(self):
+        random.seed(self.seed)
+        actual = random.wald(mean=1.23, scale=1.54, size=(3, 2))
+        desired = np.array([[3.82935265715889983, 5.13125249184285526],
+                            [0.35045403618358717, 1.50832396872003538],
+                            [0.24124319895843183, 0.22031101461955038]])
+        assert_array_almost_equal(actual, desired, decimal=14)
+
+    def test_weibull(self):
+        random.seed(self.seed)
+        actual = random.weibull(a=1.23, size=(3, 2))
+        desired = np.array([[0.97097342648766727, 0.91422896443565516],
+                            [1.89517770034962929, 1.91414357960479564],
+                            [0.67057783752390987, 1.39494046635066793]])
+        assert_array_almost_equal(actual, desired, decimal=15)
+
+    def test_weibull_0(self):
+        random.seed(self.seed)
+        assert_equal(random.weibull(a=0, size=12), np.zeros(12))
+        assert_raises(ValueError, random.weibull, a=-0.)
+
+    def test_zipf(self):
+        random.seed(self.seed)
+        actual = random.zipf(a=1.23, size=(3, 2))
+        desired = np.array([[66, 29],
+                            [1, 1],
+                            [3, 13]])
+        assert_array_equal(actual, desired)
+
+
+class TestBroadcast:
+    # tests that functions that broadcast behave
+    # correctly when presented with non-scalar arguments
+    def setup_method(self):
+        self.seed = 123456789
+
+    def set_seed(self):
+        random.seed(self.seed)
+
+    def test_uniform(self):
+        low = [0]
+        high = [1]
+        uniform = random.uniform
+        desired = np.array([0.53283302478975902,
+                            0.53413660089041659,
+                            0.50955303552646702])
+
+        self.set_seed()
+        actual = uniform(low * 3, high)
+        assert_array_almost_equal(actual, desired, decimal=14)
+
+        self.set_seed()
+        actual = uniform(low, high * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+
+    def test_normal(self):
+        loc = [0]
+        scale = [1]
+        bad_scale = [-1]
+        normal = random.normal
+        desired = np.array([2.2129019979039612,
+                            2.1283977976520019,
+                            1.8417114045748335])
+
+        self.set_seed()
+        actual = normal(loc * 3, scale)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, normal, loc * 3, bad_scale)
+
+        self.set_seed()
+        actual = normal(loc, scale * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, normal, loc, bad_scale * 3)
+
+    def test_beta(self):
+        a = [1]
+        b = [2]
+        bad_a = [-1]
+        bad_b = [-2]
+        beta = random.beta
+        desired = np.array([0.19843558305989056,
+                            0.075230336409423643,
+                            0.24976865978980844])
+
+        self.set_seed()
+        actual = beta(a * 3, b)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, beta, bad_a * 3, b)
+        assert_raises(ValueError, beta, a * 3, bad_b)
+
+        self.set_seed()
+        actual = beta(a, b * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, beta, bad_a, b * 3)
+        assert_raises(ValueError, beta, a, bad_b * 3)
+
+    def test_exponential(self):
+        scale = [1]
+        bad_scale = [-1]
+        exponential = random.exponential
+        desired = np.array([0.76106853658845242,
+                            0.76386282278691653,
+                            0.71243813125891797])
+
+        self.set_seed()
+        actual = exponential(scale * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, exponential, bad_scale * 3)
+
+    def test_standard_gamma(self):
+        shape = [1]
+        bad_shape = [-1]
+        std_gamma = random.standard_gamma
+        desired = np.array([0.76106853658845242,
+                            0.76386282278691653,
+                            0.71243813125891797])
+
+        self.set_seed()
+        actual = std_gamma(shape * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, std_gamma, bad_shape * 3)
+
+    def test_gamma(self):
+        shape = [1]
+        scale = [2]
+        bad_shape = [-1]
+        bad_scale = [-2]
+        gamma = random.gamma
+        desired = np.array([1.5221370731769048,
+                            1.5277256455738331,
+                            1.4248762625178359])
+
+        self.set_seed()
+        actual = gamma(shape * 3, scale)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, gamma, bad_shape * 3, scale)
+        assert_raises(ValueError, gamma, shape * 3, bad_scale)
+
+        self.set_seed()
+        actual = gamma(shape, scale * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, gamma, bad_shape, scale * 3)
+        assert_raises(ValueError, gamma, shape, bad_scale * 3)
+
+    def test_f(self):
+        dfnum = [1]
+        dfden = [2]
+        bad_dfnum = [-1]
+        bad_dfden = [-2]
+        f = random.f
+        desired = np.array([0.80038951638264799,
+                            0.86768719635363512,
+                            2.7251095168386801])
+
+        self.set_seed()
+        actual = f(dfnum * 3, dfden)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, f, bad_dfnum * 3, dfden)
+        assert_raises(ValueError, f, dfnum * 3, bad_dfden)
+
+        self.set_seed()
+        actual = f(dfnum, dfden * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, f, bad_dfnum, dfden * 3)
+        assert_raises(ValueError, f, dfnum, bad_dfden * 3)
+
+    def test_noncentral_f(self):
+        dfnum = [2]
+        dfden = [3]
+        nonc = [4]
+        bad_dfnum = [0]
+        bad_dfden = [-1]
+        bad_nonc = [-2]
+        nonc_f = random.noncentral_f
+        desired = np.array([9.1393943263705211,
+                            13.025456344595602,
+                            8.8018098359100545])
+
+        self.set_seed()
+        actual = nonc_f(dfnum * 3, dfden, nonc)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert np.all(np.isnan(nonc_f(dfnum, dfden, [np.nan] * 3)))
+
+        assert_raises(ValueError, nonc_f, bad_dfnum * 3, dfden, nonc)
+        assert_raises(ValueError, nonc_f, dfnum * 3, bad_dfden, nonc)
+        assert_raises(ValueError, nonc_f, dfnum * 3, dfden, bad_nonc)
+
+        self.set_seed()
+        actual = nonc_f(dfnum, dfden * 3, nonc)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, nonc_f, bad_dfnum, dfden * 3, nonc)
+        assert_raises(ValueError, nonc_f, dfnum, bad_dfden * 3, nonc)
+        assert_raises(ValueError, nonc_f, dfnum, dfden * 3, bad_nonc)
+
+        self.set_seed()
+        actual = nonc_f(dfnum, dfden, nonc * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, nonc_f, bad_dfnum, dfden, nonc * 3)
+        assert_raises(ValueError, nonc_f, dfnum, bad_dfden, nonc * 3)
+        assert_raises(ValueError, nonc_f, dfnum, dfden, bad_nonc * 3)
+
+    def test_noncentral_f_small_df(self):
+        self.set_seed()
+        desired = np.array([6.869638627492048, 0.785880199263955])
+        actual = random.noncentral_f(0.9, 0.9, 2, size=2)
+        assert_array_almost_equal(actual, desired, decimal=14)
+
+    def test_chisquare(self):
+        df = [1]
+        bad_df = [-1]
+        chisquare = random.chisquare
+        desired = np.array([0.57022801133088286,
+                            0.51947702108840776,
+                            0.1320969254923558])
+
+        self.set_seed()
+        actual = chisquare(df * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, chisquare, bad_df * 3)
+
+    def test_noncentral_chisquare(self):
+        df = [1]
+        nonc = [2]
+        bad_df = [-1]
+        bad_nonc = [-2]
+        nonc_chi = random.noncentral_chisquare
+        desired = np.array([9.0015599467913763,
+                            4.5804135049718742,
+                            6.0872302432834564])
+
+        self.set_seed()
+        actual = nonc_chi(df * 3, nonc)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, nonc_chi, bad_df * 3, nonc)
+        assert_raises(ValueError, nonc_chi, df * 3, bad_nonc)
+
+        self.set_seed()
+        actual = nonc_chi(df, nonc * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, nonc_chi, bad_df, nonc * 3)
+        assert_raises(ValueError, nonc_chi, df, bad_nonc * 3)
+
+    def test_standard_t(self):
+        df = [1]
+        bad_df = [-1]
+        t = random.standard_t
+        desired = np.array([3.0702872575217643,
+                            5.8560725167361607,
+                            1.0274791436474273])
+
+        self.set_seed()
+        actual = t(df * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, t, bad_df * 3)
+        assert_raises(ValueError, random.standard_t, bad_df * 3)
+
+    def test_vonmises(self):
+        mu = [2]
+        kappa = [1]
+        bad_kappa = [-1]
+        vonmises = random.vonmises
+        desired = np.array([2.9883443664201312,
+                            -2.7064099483995943,
+                            -1.8672476700665914])
+
+        self.set_seed()
+        actual = vonmises(mu * 3, kappa)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, vonmises, mu * 3, bad_kappa)
+
+        self.set_seed()
+        actual = vonmises(mu, kappa * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, vonmises, mu, bad_kappa * 3)
+
+    def test_pareto(self):
+        a = [1]
+        bad_a = [-1]
+        pareto = random.pareto
+        desired = np.array([1.1405622680198362,
+                            1.1465519762044529,
+                            1.0389564467453547])
+
+        self.set_seed()
+        actual = pareto(a * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, pareto, bad_a * 3)
+        assert_raises(ValueError, random.pareto, bad_a * 3)
+
+    def test_weibull(self):
+        a = [1]
+        bad_a = [-1]
+        weibull = random.weibull
+        desired = np.array([0.76106853658845242,
+                            0.76386282278691653,
+                            0.71243813125891797])
+
+        self.set_seed()
+        actual = weibull(a * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, weibull, bad_a * 3)
+        assert_raises(ValueError, random.weibull, bad_a * 3)
+
+    def test_power(self):
+        a = [1]
+        bad_a = [-1]
+        power = random.power
+        desired = np.array([0.53283302478975902,
+                            0.53413660089041659,
+                            0.50955303552646702])
+
+        self.set_seed()
+        actual = power(a * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, power, bad_a * 3)
+        assert_raises(ValueError, random.power, bad_a * 3)
+
+    def test_laplace(self):
+        loc = [0]
+        scale = [1]
+        bad_scale = [-1]
+        laplace = random.laplace
+        desired = np.array([0.067921356028507157,
+                            0.070715642226971326,
+                            0.019290950698972624])
+
+        self.set_seed()
+        actual = laplace(loc * 3, scale)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, laplace, loc * 3, bad_scale)
+
+        self.set_seed()
+        actual = laplace(loc, scale * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, laplace, loc, bad_scale * 3)
+
+    def test_gumbel(self):
+        loc = [0]
+        scale = [1]
+        bad_scale = [-1]
+        gumbel = random.gumbel
+        desired = np.array([0.2730318639556768,
+                            0.26936705726291116,
+                            0.33906220393037939])
+
+        self.set_seed()
+        actual = gumbel(loc * 3, scale)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, gumbel, loc * 3, bad_scale)
+
+        self.set_seed()
+        actual = gumbel(loc, scale * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, gumbel, loc, bad_scale * 3)
+
+    def test_logistic(self):
+        loc = [0]
+        scale = [1]
+        bad_scale = [-1]
+        logistic = random.logistic
+        desired = np.array([0.13152135837586171,
+                            0.13675915696285773,
+                            0.038216792802833396])
+
+        self.set_seed()
+        actual = logistic(loc * 3, scale)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, logistic, loc * 3, bad_scale)
+
+        self.set_seed()
+        actual = logistic(loc, scale * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, logistic, loc, bad_scale * 3)
+        assert_equal(random.logistic(1.0, 0.0), 1.0)
+
+    def test_lognormal(self):
+        mean = [0]
+        sigma = [1]
+        bad_sigma = [-1]
+        lognormal = random.lognormal
+        desired = np.array([9.1422086044848427,
+                            8.4013952870126261,
+                            6.3073234116578671])
+
+        self.set_seed()
+        actual = lognormal(mean * 3, sigma)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, lognormal, mean * 3, bad_sigma)
+        assert_raises(ValueError, random.lognormal, mean * 3, bad_sigma)
+
+        self.set_seed()
+        actual = lognormal(mean, sigma * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, lognormal, mean, bad_sigma * 3)
+        assert_raises(ValueError, random.lognormal, mean, bad_sigma * 3)
+
+    def test_rayleigh(self):
+        scale = [1]
+        bad_scale = [-1]
+        rayleigh = random.rayleigh
+        desired = np.array([1.2337491937897689,
+                            1.2360119924878694,
+                            1.1936818095781789])
+
+        self.set_seed()
+        actual = rayleigh(scale * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, rayleigh, bad_scale * 3)
+
+    def test_wald(self):
+        mean = [0.5]
+        scale = [1]
+        bad_mean = [0]
+        bad_scale = [-2]
+        wald = random.wald
+        desired = np.array([0.11873681120271318,
+                            0.12450084820795027,
+                            0.9096122728408238])
+
+        self.set_seed()
+        actual = wald(mean * 3, scale)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, wald, bad_mean * 3, scale)
+        assert_raises(ValueError, wald, mean * 3, bad_scale)
+        assert_raises(ValueError, random.wald, bad_mean * 3, scale)
+        assert_raises(ValueError, random.wald, mean * 3, bad_scale)
+
+        self.set_seed()
+        actual = wald(mean, scale * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, wald, bad_mean, scale * 3)
+        assert_raises(ValueError, wald, mean, bad_scale * 3)
+        assert_raises(ValueError, wald, 0.0, 1)
+        assert_raises(ValueError, wald, 0.5, 0.0)
+
+    def test_triangular(self):
+        left = [1]
+        right = [3]
+        mode = [2]
+        bad_left_one = [3]
+        bad_mode_one = [4]
+        bad_left_two, bad_mode_two = right * 2
+        triangular = random.triangular
+        desired = np.array([2.03339048710429,
+                            2.0347400359389356,
+                            2.0095991069536208])
+
+        self.set_seed()
+        actual = triangular(left * 3, mode, right)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, triangular, bad_left_one * 3, mode, right)
+        assert_raises(ValueError, triangular, left * 3, bad_mode_one, right)
+        assert_raises(ValueError, triangular, bad_left_two * 3, bad_mode_two,
+                      right)
+
+        self.set_seed()
+        actual = triangular(left, mode * 3, right)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, triangular, bad_left_one, mode * 3, right)
+        assert_raises(ValueError, triangular, left, bad_mode_one * 3, right)
+        assert_raises(ValueError, triangular, bad_left_two, bad_mode_two * 3,
+                      right)
+
+        self.set_seed()
+        actual = triangular(left, mode, right * 3)
+        assert_array_almost_equal(actual, desired, decimal=14)
+        assert_raises(ValueError, triangular, bad_left_one, mode, right * 3)
+        assert_raises(ValueError, triangular, left, bad_mode_one, right * 3)
+        assert_raises(ValueError, triangular, bad_left_two, bad_mode_two,
+                      right * 3)
+
+        assert_raises(ValueError, triangular, 10., 0., 20.)
+        assert_raises(ValueError, triangular, 10., 25., 20.)
+        assert_raises(ValueError, triangular, 10., 10., 10.)
+
+    def test_binomial(self):
+        n = [1]
+        p = [0.5]
+        bad_n = [-1]
+        bad_p_one = [-1]
+        bad_p_two = [1.5]
+        binom = random.binomial
+        desired = np.array([1, 1, 1])
+
+        self.set_seed()
+        actual = binom(n * 3, p)
+        assert_array_equal(actual, desired)
+        assert_raises(ValueError, binom, bad_n * 3, p)
+        assert_raises(ValueError, binom, n * 3, bad_p_one)
+        assert_raises(ValueError, binom, n * 3, bad_p_two)
+
+        self.set_seed()
+        actual = binom(n, p * 3)
+        assert_array_equal(actual, desired)
+        assert_raises(ValueError, binom, bad_n, p * 3)
+        assert_raises(ValueError, binom, n, bad_p_one * 3)
+        assert_raises(ValueError, binom, n, bad_p_two * 3)
+
+    def test_negative_binomial(self):
+        n = [1]
+        p = [0.5]
+        bad_n = [-1]
+        bad_p_one = [-1]
+        bad_p_two = [1.5]
+        neg_binom = random.negative_binomial
+        desired = np.array([1, 0, 1])
+
+        self.set_seed()
+        actual = neg_binom(n * 3, p)
+        assert_array_equal(actual, desired)
+        assert_raises(ValueError, neg_binom, bad_n * 3, p)
+        assert_raises(ValueError, neg_binom, n * 3, bad_p_one)
+        assert_raises(ValueError, neg_binom, n * 3, bad_p_two)
+
+        self.set_seed()
+        actual = neg_binom(n, p * 3)
+        assert_array_equal(actual, desired)
+        assert_raises(ValueError, neg_binom, bad_n, p * 3)
+        assert_raises(ValueError, neg_binom, n, bad_p_one * 3)
+        assert_raises(ValueError, neg_binom, n, bad_p_two * 3)
+
+    def test_poisson(self):
+        max_lam = random.RandomState()._poisson_lam_max
+
+        lam = [1]
+        bad_lam_one = [-1]
+        bad_lam_two = [max_lam * 2]
+        poisson = random.poisson
+        desired = np.array([1, 1, 0])
+
+        self.set_seed()
+        actual = poisson(lam * 3)
+        assert_array_equal(actual, desired)
+        assert_raises(ValueError, poisson, bad_lam_one * 3)
+        assert_raises(ValueError, poisson, bad_lam_two * 3)
+
+    def test_zipf(self):
+        a = [2]
+        bad_a = [0]
+        zipf = random.zipf
+        desired = np.array([2, 2, 1])
+
+        self.set_seed()
+        actual = zipf(a * 3)
+        assert_array_equal(actual, desired)
+        assert_raises(ValueError, zipf, bad_a * 3)
+        with np.errstate(invalid='ignore'):
+            assert_raises(ValueError, zipf, np.nan)
+            assert_raises(ValueError, zipf, [0, 0, np.nan])
+
+    def test_geometric(self):
+        p = [0.5]
+        bad_p_one = [-1]
+        bad_p_two = [1.5]
+        geom = random.geometric
+        desired = np.array([2, 2, 2])
+
+        self.set_seed()
+        actual = geom(p * 3)
+        assert_array_equal(actual, desired)
+        assert_raises(ValueError, geom, bad_p_one * 3)
+        assert_raises(ValueError, geom, bad_p_two * 3)
+
+    def test_hypergeometric(self):
+        ngood = [1]
+        nbad = [2]
+        nsample = [2]
+        bad_ngood = [-1]
+        bad_nbad = [-2]
+        bad_nsample_one = [0]
+        bad_nsample_two = [4]
+        hypergeom = random.hypergeometric
+        desired = np.array([1, 1, 1])
+
+        self.set_seed()
+        actual = hypergeom(ngood * 3, nbad, nsample)
+        assert_array_equal(actual, desired)
+        assert_raises(ValueError, hypergeom, bad_ngood * 3, nbad, nsample)
+        assert_raises(ValueError, hypergeom, ngood * 3, bad_nbad, nsample)
+        assert_raises(ValueError, hypergeom, ngood * 3, nbad, bad_nsample_one)
+        assert_raises(ValueError, hypergeom, ngood * 3, nbad, bad_nsample_two)
+
+        self.set_seed()
+        actual = hypergeom(ngood, nbad * 3, nsample)
+        assert_array_equal(actual, desired)
+        assert_raises(ValueError, hypergeom, bad_ngood, nbad * 3, nsample)
+        assert_raises(ValueError, hypergeom, ngood, bad_nbad * 3, nsample)
+        assert_raises(ValueError, hypergeom, ngood, nbad * 3, bad_nsample_one)
+        assert_raises(ValueError, hypergeom, ngood, nbad * 3, bad_nsample_two)
+
+        self.set_seed()
+        actual = hypergeom(ngood, nbad, nsample * 3)
+        assert_array_equal(actual, desired)
+        assert_raises(ValueError, hypergeom, bad_ngood, nbad, nsample * 3)
+        assert_raises(ValueError, hypergeom, ngood, bad_nbad, nsample * 3)
+        assert_raises(ValueError, hypergeom, ngood, nbad, bad_nsample_one * 3)
+        assert_raises(ValueError, hypergeom, ngood, nbad, bad_nsample_two * 3)
+
+        assert_raises(ValueError, hypergeom, -1, 10, 20)
+        assert_raises(ValueError, hypergeom, 10, -1, 20)
+        assert_raises(ValueError, hypergeom, 10, 10, 0)
+        assert_raises(ValueError, hypergeom, 10, 10, 25)
+
+    def test_logseries(self):
+        p = [0.5]
+        bad_p_one = [2]
+        bad_p_two = [-1]
+        logseries = random.logseries
+        desired = np.array([1, 1, 1])
+
+        self.set_seed()
+        actual = logseries(p * 3)
+        assert_array_equal(actual, desired)
+        assert_raises(ValueError, logseries, bad_p_one * 3)
+        assert_raises(ValueError, logseries, bad_p_two * 3)
+
+
+@pytest.mark.skipif(IS_WASM, reason="can't start thread")
+class TestThread:
+    # make sure each state produces the same sequence even in threads
+    def setup_method(self):
+        self.seeds = range(4)
+
+    def check_function(self, function, sz):
+        from threading import Thread
+
+        out1 = np.empty((len(self.seeds),) + sz)
+        out2 = np.empty((len(self.seeds),) + sz)
+
+        # threaded generation
+        t = [Thread(target=function, args=(random.RandomState(s), o))
+             for s, o in zip(self.seeds, out1)]
+        [x.start() for x in t]
+        [x.join() for x in t]
+
+        # the same serial
+        for s, o in zip(self.seeds, out2):
+            function(random.RandomState(s), o)
+
+        # these platforms change x87 fpu precision mode in threads
+        if np.intp().dtype.itemsize == 4 and sys.platform == "win32":
+            assert_array_almost_equal(out1, out2)
+        else:
+            assert_array_equal(out1, out2)
+
+    def test_normal(self):
+        def gen_random(state, out):
+            out[...] = state.normal(size=10000)
+
+        self.check_function(gen_random, sz=(10000,))
+
+    def test_exp(self):
+        def gen_random(state, out):
+            out[...] = state.exponential(scale=np.ones((100, 1000)))
+
+        self.check_function(gen_random, sz=(100, 1000))
+
+    def test_multinomial(self):
+        def gen_random(state, out):
+            out[...] = state.multinomial(10, [1 / 6.] * 6, size=10000)
+
+        self.check_function(gen_random, sz=(10000, 6))
+
+
+# See Issue #4263
+class TestSingleEltArrayInput:
+    def setup_method(self):
+        self.argOne = np.array([2])
+        self.argTwo = np.array([3])
+        self.argThree = np.array([4])
+        self.tgtShape = (1,)
+
+    def test_one_arg_funcs(self):
+        funcs = (random.exponential, random.standard_gamma,
+                 random.chisquare, random.standard_t,
+                 random.pareto, random.weibull,
+                 random.power, random.rayleigh,
+                 random.poisson, random.zipf,
+                 random.geometric, random.logseries)
+
+        probfuncs = (random.geometric, random.logseries)
+
+        for func in funcs:
+            if func in probfuncs:  # p < 1.0
+                out = func(np.array([0.5]))
+
+            else:
+                out = func(self.argOne)
+
+            assert_equal(out.shape, self.tgtShape)
+
+    def test_two_arg_funcs(self):
+        funcs = (random.uniform, random.normal,
+                 random.beta, random.gamma,
+                 random.f, random.noncentral_chisquare,
+                 random.vonmises, random.laplace,
+                 random.gumbel, random.logistic,
+                 random.lognormal, random.wald,
+                 random.binomial, random.negative_binomial)
+
+        probfuncs = (random.binomial, random.negative_binomial)
+
+        for func in funcs:
+            if func in probfuncs:  # p <= 1
+                argTwo = np.array([0.5])
+
+            else:
+                argTwo = self.argTwo
+
+            out = func(self.argOne, argTwo)
+            assert_equal(out.shape, self.tgtShape)
+
+            out = func(self.argOne[0], argTwo)
+            assert_equal(out.shape, self.tgtShape)
+
+            out = func(self.argOne, argTwo[0])
+            assert_equal(out.shape, self.tgtShape)
+
+    def test_three_arg_funcs(self):
+        funcs = [random.noncentral_f, random.triangular,
+                 random.hypergeometric]
+
+        for func in funcs:
+            out = func(self.argOne, self.argTwo, self.argThree)
+            assert_equal(out.shape, self.tgtShape)
+
+            out = func(self.argOne[0], self.argTwo, self.argThree)
+            assert_equal(out.shape, self.tgtShape)
+
+            out = func(self.argOne, self.argTwo[0], self.argThree)
+            assert_equal(out.shape, self.tgtShape)
+
+
+# Ensure returned array dtype is correct for platform
+def test_integer_dtype(int_func):
+    random.seed(123456789)
+    fname, args, sha256 = int_func
+    f = getattr(random, fname)
+    actual = f(*args, size=2)
+    assert_(actual.dtype == np.dtype('l'))
+
+
+def test_integer_repeat(int_func):
+    random.seed(123456789)
+    fname, args, sha256 = int_func
+    f = getattr(random, fname)
+    val = f(*args, size=1000000)
+    if sys.byteorder != 'little':
+        val = val.byteswap()
+    res = hashlib.sha256(val.view(np.int8)).hexdigest()
+    assert_(res == sha256)
+
+
+def test_broadcast_size_error():
+    # GH-16833
+    with pytest.raises(ValueError):
+        random.binomial(1, [0.3, 0.7], size=(2, 1))
+    with pytest.raises(ValueError):
+        random.binomial([1, 2], 0.3, size=(2, 1))
+    with pytest.raises(ValueError):
+        random.binomial([1, 2], [0.3, 0.7], size=(2, 1))
+
+
+def test_randomstate_ctor_old_style_pickle():
+    rs = np.random.RandomState(MT19937(0))
+    rs.standard_normal(1)
+    # Directly call reduce which is used in pickling
+    ctor, args, state_a = rs.__reduce__()
+    # Simulate unpickling an old pickle that only has the name
+    assert args[:1] == ("MT19937",)
+    b = ctor(*args[:1])
+    b.set_state(state_a)
+    state_b = b.get_state(legacy=False)
+
+    assert_equal(state_a['bit_generator'], state_b['bit_generator'])
+    assert_array_equal(state_a['state']['key'], state_b['state']['key'])
+    assert_array_equal(state_a['state']['pos'], state_b['state']['pos'])
+    assert_equal(state_a['has_gauss'], state_b['has_gauss'])
+    assert_equal(state_a['gauss'], state_b['gauss'])
+
+
+def test_hot_swap(restore_singleton_bitgen):
+    # GH 21808
+    def_bg = np.random.default_rng(0)
+    bg = def_bg.bit_generator
+    np.random.set_bit_generator(bg)
+    assert isinstance(np.random.mtrand._rand._bit_generator, type(bg))
+
+    second_bg = np.random.get_bit_generator()
+    assert bg is second_bg
+
+
+def test_seed_alt_bit_gen(restore_singleton_bitgen):
+    # GH 21808
+    bg = PCG64(0)
+    np.random.set_bit_generator(bg)
+    state = np.random.get_state(legacy=False)
+    np.random.seed(1)
+    new_state = np.random.get_state(legacy=False)
+    print(state)
+    print(new_state)
+    assert state["bit_generator"] == "PCG64"
+    assert state["state"]["state"] != new_state["state"]["state"]
+    assert state["state"]["inc"] != new_state["state"]["inc"]
+
+
+def test_state_error_alt_bit_gen(restore_singleton_bitgen):
+    # GH 21808
+    state = np.random.get_state()
+    bg = PCG64(0)
+    np.random.set_bit_generator(bg)
+    with pytest.raises(ValueError, match="state must be for a PCG64"):
+        np.random.set_state(state)
+
+
+def test_swap_worked(restore_singleton_bitgen):
+    # GH 21808
+    np.random.seed(98765)
+    vals = np.random.randint(0, 2 ** 30, 10)
+    bg = PCG64(0)
+    state = bg.state
+    np.random.set_bit_generator(bg)
+    state_direct = np.random.get_state(legacy=False)
+    for field in state:
+        assert state[field] == state_direct[field]
+    np.random.seed(98765)
+    pcg_vals = np.random.randint(0, 2 ** 30, 10)
+    assert not np.all(vals == pcg_vals)
+    new_state = bg.state
+    assert new_state["state"]["state"] != state["state"]["state"]
+    assert new_state["state"]["inc"] == new_state["state"]["inc"]
+
+
+def test_swapped_singleton_against_direct(restore_singleton_bitgen):
+    np.random.set_bit_generator(PCG64(98765))
+    singleton_vals = np.random.randint(0, 2 ** 30, 10)
+    rg = np.random.RandomState(PCG64(98765))
+    non_singleton_vals = rg.randint(0, 2 ** 30, 10)
+    assert_equal(non_singleton_vals, singleton_vals)
diff --git a/venv/lib/python3.10/site-packages/numpy/random/tests/test_randomstate_regression.py b/venv/lib/python3.10/site-packages/numpy/random/tests/test_randomstate_regression.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ad19ab5562b87305a0391c80c602259816a984e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/numpy/random/tests/test_randomstate_regression.py
@@ -0,0 +1,216 @@
+import sys
+
+import pytest
+
+from numpy.testing import (
+    assert_, assert_array_equal, assert_raises,
+    )
+import numpy as np
+
+from numpy import random
+
+
+class TestRegression:
+
+    def test_VonMises_range(self):
+        # Make sure generated random variables are in [-pi, pi].
+        # Regression test for ticket #986.
+        for mu in np.linspace(-7., 7., 5):
+            r = random.vonmises(mu, 1, 50)
+            assert_(np.all(r > -np.pi) and np.all(r <= np.pi))
+
+    def test_hypergeometric_range(self):
+        # Test for ticket #921
+        assert_(np.all(random.hypergeometric(3, 18, 11, size=10) < 4))
+        assert_(np.all(random.hypergeometric(18, 3, 11, size=10) > 0))
+
+        # Test for ticket #5623
+        args = [
+            (2**20 - 2, 2**20 - 2, 2**20 - 2),  # Check for 32-bit systems
+        ]
+        is_64bits = sys.maxsize > 2**32
+        if is_64bits and sys.platform != 'win32':
+            # Check for 64-bit systems
+            args.append((2**40 - 2, 2**40 - 2, 2**40 - 2))
+        for arg in args:
+            assert_(random.hypergeometric(*arg) > 0)
+
+    def test_logseries_convergence(self):
+        # Test for ticket #923
+        N = 1000
+        random.seed(0)
+        rvsn = random.logseries(0.8, size=N)
+        # these two frequency counts should be close to theoretical
+        # numbers with this large sample
+        # theoretical large N result is 0.49706795
+        freq = np.sum(rvsn == 1) / N
+        msg = f'Frequency was {freq:f}, should be > 0.45'
+        assert_(freq > 0.45, msg)
+        # theoretical large N result is 0.19882718
+        freq = np.sum(rvsn == 2) / N
+        msg = f'Frequency was {freq:f}, should be < 0.23'
+        assert_(freq < 0.23, msg)
+
+    def test_shuffle_mixed_dimension(self):
+        # Test for trac ticket #2074
+        for t in [[1, 2, 3, None],
+                  [(1, 1), (2, 2), (3, 3), None],
+                  [1, (2, 2), (3, 3), None],
+                  [(1, 1), 2, 3, None]]:
+            random.seed(12345)
+            shuffled = list(t)
+            random.shuffle(shuffled)
+            expected = np.array([t[0], t[3], t[1], t[2]], dtype=object)
+            assert_array_equal(np.array(shuffled, dtype=object), expected)
+
+    def test_call_within_randomstate(self):
+        # Check that custom RandomState does not call into global state
+        m = random.RandomState()
+        res = np.array([0, 8, 7, 2, 1, 9, 4, 7, 0, 3])
+        for i in range(3):
+            random.seed(i)
+            m.seed(4321)
+            # If m.state is not honored, the result will change
+            assert_array_equal(m.choice(10, size=10, p=np.ones(10)/10.), res)
+
+    def test_multivariate_normal_size_types(self):
+        # Test for multivariate_normal issue with 'size' argument.
+        # Check that the multivariate_normal size argument can be a
+        # numpy integer.
+        random.multivariate_normal([0], [[0]], size=1)
+        random.multivariate_normal([0], [[0]], size=np.int_(1))
+        random.multivariate_normal([0], [[0]], size=np.int64(1))
+
+    def test_beta_small_parameters(self):
+        # Test that beta with small a and b parameters does not produce
+        # NaNs due to roundoff errors causing 0 / 0, gh-5851
+        random.seed(1234567890)
+        x = random.beta(0.0001, 0.0001, size=100)
+        assert_(not np.any(np.isnan(x)), 'Nans in random.beta')
+
+    def test_choice_sum_of_probs_tolerance(self):
+        # The sum of probs should be 1.0 with some tolerance.
+        # For low precision dtypes the tolerance was too tight.
+        # See numpy github issue 6123.
+        random.seed(1234)
+        a = [1, 2, 3]
+        counts = [4, 4, 2]
+        for dt in np.float16, np.float32, np.float64:
+            probs = np.array(counts, dtype=dt) / sum(counts)
+            c = random.choice(a, p=probs)
+            assert_(c in a)
+            assert_raises(ValueError, random.choice, a, p=probs*0.9)
+
+    def test_shuffle_of_array_of_different_length_strings(self):
+        # Test that permuting an array of different length strings
+        # will not cause a segfault on garbage collection
+        # Tests gh-7710
+        random.seed(1234)
+
+        a = np.array(['a', 'a' * 1000])
+
+        for _ in range(100):
+            random.shuffle(a)
+
+        # Force Garbage Collection - should not segfault.
+        import gc
+        gc.collect()
+
+    def test_shuffle_of_array_of_objects(self):
+        # Test that permuting an array of objects will not cause
+        # a segfault on garbage collection.
+        # See gh-7719
+        random.seed(1234)
+        a = np.array([np.arange(1), np.arange(4)], dtype=object)
+
+        for _ in range(1000):
+            random.shuffle(a)
+
+        # Force Garbage Collection - should not segfault.
+        import gc
+        gc.collect()
+
+    def test_permutation_subclass(self):
+        class N(np.ndarray):
+            pass
+
+        random.seed(1)
+        orig = np.arange(3).view(N)
+        perm = random.permutation(orig)
+        assert_array_equal(perm, np.array([0, 2, 1]))
+        assert_array_equal(orig, np.arange(3).view(N))
+
+        class M:
+            a = np.arange(5)
+
+            def __array__(self):
+                return self.a
+
+        random.seed(1)
+        m = M()
+        perm = random.permutation(m)
+        assert_array_equal(perm, np.array([2, 1, 4, 0, 3]))
+        assert_array_equal(m.__array__(), np.arange(5))
+
+    def test_warns_byteorder(self):
+        # GH 13159
+        other_byteord_dt = 'i4'
+        with pytest.deprecated_call(match='non-native byteorder is not'):
+            random.randint(0, 200, size=10, dtype=other_byteord_dt)
+
+    def test_named_argument_initialization(self):
+        # GH 13669
+        rs1 = np.random.RandomState(123456789)
+        rs2 = np.random.RandomState(seed=123456789)
+        assert rs1.randint(0, 100) == rs2.randint(0, 100)
+
+    def test_choice_retun_dtype(self):
+        # GH 9867
+        c = np.random.choice(10, p=[.1]*10, size=2)
+        assert c.dtype == np.dtype(int)
+        c = np.random.choice(10, p=[.1]*10, replace=False, size=2)
+        assert c.dtype == np.dtype(int)
+        c = np.random.choice(10, size=2)
+        assert c.dtype == np.dtype(int)
+        c = np.random.choice(10, replace=False, size=2)
+        assert c.dtype == np.dtype(int)
+
+    @pytest.mark.skipif(np.iinfo('l').max < 2**32,
+                        reason='Cannot test with 32-bit C long')
+    def test_randint_117(self):
+        # GH 14189
+        random.seed(0)
+        expected = np.array([2357136044, 2546248239, 3071714933, 3626093760,
+                             2588848963, 3684848379, 2340255427, 3638918503,
+                             1819583497, 2678185683], dtype='int64')
+        actual = random.randint(2**32, size=10)
+        assert_array_equal(actual, expected)
+
+    def test_p_zero_stream(self):
+        # Regression test for gh-14522.  Ensure that future versions
+        # generate the same variates as version 1.16.
+        np.random.seed(12345)
+        assert_array_equal(random.binomial(1, [0, 0.25, 0.5, 0.75, 1]),
+                           [0, 0, 0, 1, 1])
+
+    def test_n_zero_stream(self):
+        # Regression test for gh-14522.  Ensure that future versions
+        # generate the same variates as version 1.16.
+        np.random.seed(8675309)
+        expected = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+                             [3, 4, 2, 3, 3, 1, 5, 3, 1, 3]])
+        assert_array_equal(random.binomial([[0], [10]], 0.25, size=(2, 10)),
+                           expected)
+
+
+def test_multinomial_empty():
+    # gh-20483
+    # Ensure that empty p-vals are correctly handled
+    assert random.multinomial(10, []).shape == (0,)
+    assert random.multinomial(3, [], size=(7, 5, 3)).shape == (7, 5, 3, 0)
+
+
+def test_multinomial_1d_pval():
+    # gh-20483
+    with pytest.raises(TypeError, match="pvals must be a 1-d"):
+        random.multinomial(10, 0.3)
diff --git a/venv/lib/python3.10/site-packages/numpy/random/tests/test_regression.py b/venv/lib/python3.10/site-packages/numpy/random/tests/test_regression.py
new file mode 100644
index 0000000000000000000000000000000000000000..8bf419875b3f37cd4cc121030d65be9fc77999a3
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/numpy/random/tests/test_regression.py
@@ -0,0 +1,149 @@
+import sys
+from numpy.testing import (
+    assert_, assert_array_equal, assert_raises,
+    )
+from numpy import random
+import numpy as np
+
+
+class TestRegression:
+
+    def test_VonMises_range(self):
+        # Make sure generated random variables are in [-pi, pi].
+        # Regression test for ticket #986.
+        for mu in np.linspace(-7., 7., 5):
+            r = random.mtrand.vonmises(mu, 1, 50)
+            assert_(np.all(r > -np.pi) and np.all(r <= np.pi))
+
+    def test_hypergeometric_range(self):
+        # Test for ticket #921
+        assert_(np.all(np.random.hypergeometric(3, 18, 11, size=10) < 4))
+        assert_(np.all(np.random.hypergeometric(18, 3, 11, size=10) > 0))
+
+        # Test for ticket #5623
+        args = [
+            (2**20 - 2, 2**20 - 2, 2**20 - 2),  # Check for 32-bit systems
+        ]
+        is_64bits = sys.maxsize > 2**32
+        if is_64bits and sys.platform != 'win32':
+            # Check for 64-bit systems
+            args.append((2**40 - 2, 2**40 - 2, 2**40 - 2))
+        for arg in args:
+            assert_(np.random.hypergeometric(*arg) > 0)
+
+    def test_logseries_convergence(self):
+        # Test for ticket #923
+        N = 1000
+        np.random.seed(0)
+        rvsn = np.random.logseries(0.8, size=N)
+        # these two frequency counts should be close to theoretical
+        # numbers with this large sample
+        # theoretical large N result is 0.49706795
+        freq = np.sum(rvsn == 1) / N
+        msg = f'Frequency was {freq:f}, should be > 0.45'
+        assert_(freq > 0.45, msg)
+        # theoretical large N result is 0.19882718
+        freq = np.sum(rvsn == 2) / N
+        msg = f'Frequency was {freq:f}, should be < 0.23'
+        assert_(freq < 0.23, msg)
+
+    def test_shuffle_mixed_dimension(self):
+        # Test for trac ticket #2074
+        for t in [[1, 2, 3, None],
+                  [(1, 1), (2, 2), (3, 3), None],
+                  [1, (2, 2), (3, 3), None],
+                  [(1, 1), 2, 3, None]]:
+            np.random.seed(12345)
+            shuffled = list(t)
+            random.shuffle(shuffled)
+            expected = np.array([t[0], t[3], t[1], t[2]], dtype=object)
+            assert_array_equal(np.array(shuffled, dtype=object), expected)
+
+    def test_call_within_randomstate(self):
+        # Check that custom RandomState does not call into global state
+        m = np.random.RandomState()
+        res = np.array([0, 8, 7, 2, 1, 9, 4, 7, 0, 3])
+        for i in range(3):
+            np.random.seed(i)
+            m.seed(4321)
+            # If m.state is not honored, the result will change
+            assert_array_equal(m.choice(10, size=10, p=np.ones(10)/10.), res)
+
+    def test_multivariate_normal_size_types(self):
+        # Test for multivariate_normal issue with 'size' argument.
+        # Check that the multivariate_normal size argument can be a
+        # numpy integer.
+        np.random.multivariate_normal([0], [[0]], size=1)
+        np.random.multivariate_normal([0], [[0]], size=np.int_(1))
+        np.random.multivariate_normal([0], [[0]], size=np.int64(1))
+
+    def test_beta_small_parameters(self):
+        # Test that beta with small a and b parameters does not produce
+        # NaNs due to roundoff errors causing 0 / 0, gh-5851
+        np.random.seed(1234567890)
+        x = np.random.beta(0.0001, 0.0001, size=100)
+        assert_(not np.any(np.isnan(x)), 'Nans in np.random.beta')
+
+    def test_choice_sum_of_probs_tolerance(self):
+        # The sum of probs should be 1.0 with some tolerance.
+        # For low precision dtypes the tolerance was too tight.
+        # See numpy github issue 6123.
+        np.random.seed(1234)
+        a = [1, 2, 3]
+        counts = [4, 4, 2]
+        for dt in np.float16, np.float32, np.float64:
+            probs = np.array(counts, dtype=dt) / sum(counts)
+            c = np.random.choice(a, p=probs)
+            assert_(c in a)
+            assert_raises(ValueError, np.random.choice, a, p=probs*0.9)
+
+    def test_shuffle_of_array_of_different_length_strings(self):
+        # Test that permuting an array of different length strings
+        # will not cause a segfault on garbage collection
+        # Tests gh-7710
+        np.random.seed(1234)
+
+        a = np.array(['a', 'a' * 1000])
+
+        for _ in range(100):
+            np.random.shuffle(a)
+
+        # Force Garbage Collection - should not segfault.
+        import gc
+        gc.collect()
+
+    def test_shuffle_of_array_of_objects(self):
+        # Test that permuting an array of objects will not cause
+        # a segfault on garbage collection.
+        # See gh-7719
+        np.random.seed(1234)
+        a = np.array([np.arange(1), np.arange(4)], dtype=object)
+
+        for _ in range(1000):
+            np.random.shuffle(a)
+
+        # Force Garbage Collection - should not segfault.
+        import gc
+        gc.collect()
+
+    def test_permutation_subclass(self):
+        class N(np.ndarray):
+            pass
+
+        np.random.seed(1)
+        orig = np.arange(3).view(N)
+        perm = np.random.permutation(orig)
+        assert_array_equal(perm, np.array([0, 2, 1]))
+        assert_array_equal(orig, np.arange(3).view(N))
+
+        class M:
+            a = np.arange(5)
+
+            def __array__(self):
+                return self.a
+
+        np.random.seed(1)
+        m = M()
+        perm = np.random.permutation(m)
+        assert_array_equal(perm, np.array([2, 1, 4, 0, 3]))
+        assert_array_equal(m.__array__(), np.arange(5))
diff --git a/venv/lib/python3.10/site-packages/numpy/random/tests/test_seed_sequence.py b/venv/lib/python3.10/site-packages/numpy/random/tests/test_seed_sequence.py
new file mode 100644
index 0000000000000000000000000000000000000000..f08cf80faafa2fc1a369eaf7dd4d6fcccd5e9158
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/numpy/random/tests/test_seed_sequence.py
@@ -0,0 +1,80 @@
+import numpy as np
+from numpy.testing import assert_array_equal, assert_array_compare
+
+from numpy.random import SeedSequence
+
+
+def test_reference_data():
+    """ Check that SeedSequence generates data the same as the C++ reference.
+
+    https://gist.github.com/imneme/540829265469e673d045
+    """
+    inputs = [
+        [3735928559, 195939070, 229505742, 305419896],
+        [3668361503, 4165561550, 1661411377, 3634257570],
+        [164546577, 4166754639, 1765190214, 1303880213],
+        [446610472, 3941463886, 522937693, 1882353782],
+        [1864922766, 1719732118, 3882010307, 1776744564],
+        [4141682960, 3310988675, 553637289, 902896340],
+        [1134851934, 2352871630, 3699409824, 2648159817],
+        [1240956131, 3107113773, 1283198141, 1924506131],
+        [2669565031, 579818610, 3042504477, 2774880435],
+        [2766103236, 2883057919, 4029656435, 862374500],
+    ]
+    outputs = [
+        [3914649087, 576849849, 3593928901, 2229911004],
+        [2240804226, 3691353228, 1365957195, 2654016646],
+        [3562296087, 3191708229, 1147942216, 3726991905],
+        [1403443605, 3591372999, 1291086759, 441919183],
+        [1086200464, 2191331643, 560336446, 3658716651],
+        [3249937430, 2346751812, 847844327, 2996632307],
+        [2584285912, 4034195531, 3523502488, 169742686],
+        [959045797, 3875435559, 1886309314, 359682705],
+        [3978441347, 432478529, 3223635119, 138903045],
+        [296367413, 4262059219, 13109864, 3283683422],
+    ]
+    outputs64 = [
+        [2477551240072187391, 9577394838764454085],
+        [15854241394484835714, 11398914698975566411],
+        [13708282465491374871, 16007308345579681096],
+        [15424829579845884309, 1898028439751125927],
+        [9411697742461147792, 15714068361935982142],
+        [10079222287618677782, 12870437757549876199],
+        [17326737873898640088, 729039288628699544],
+        [16644868984619524261, 1544825456798124994],
+        [1857481142255628931, 596584038813451439],
+        [18305404959516669237, 14103312907920476776],
+    ]
+    for seed, expected, expected64 in zip(inputs, outputs, outputs64):
+        expected = np.array(expected, dtype=np.uint32)
+        ss = SeedSequence(seed)
+        state = ss.generate_state(len(expected))
+        assert_array_equal(state, expected)
+        state64 = ss.generate_state(len(expected64), dtype=np.uint64)
+        assert_array_equal(state64, expected64)
+
+
+def test_zero_padding():
+    """ Ensure that the implicit zero-padding does not cause problems.
+    """
+    # Ensure that large integers are inserted in little-endian fashion to avoid
+    # trailing 0s.
+    ss0 = SeedSequence(42)
+    ss1 = SeedSequence(42 << 32)
+    assert_array_compare(
+        np.not_equal,
+        ss0.generate_state(4),
+        ss1.generate_state(4))
+
+    # Ensure backwards compatibility with the original 0.17 release for small
+    # integers and no spawn key.
+    expected42 = np.array([3444837047, 2669555309, 2046530742, 3581440988],
+                          dtype=np.uint32)
+    assert_array_equal(SeedSequence(42).generate_state(4), expected42)
+
+    # Regression test for gh-16539 to ensure that the implicit 0s don't
+    # conflict with spawn keys.
+    assert_array_compare(
+        np.not_equal,
+        SeedSequence(42, spawn_key=(0,)).generate_state(4),
+        expected42)
diff --git a/venv/lib/python3.10/site-packages/numpy/random/tests/test_smoke.py b/venv/lib/python3.10/site-packages/numpy/random/tests/test_smoke.py
new file mode 100644
index 0000000000000000000000000000000000000000..9becc434d0d1a66b7c9987d8c5dffdf221fd45b1
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/numpy/random/tests/test_smoke.py
@@ -0,0 +1,818 @@
+import pickle
+from functools import partial
+
+import numpy as np
+import pytest
+from numpy.testing import assert_equal, assert_, assert_array_equal
+from numpy.random import (Generator, MT19937, PCG64, PCG64DXSM, Philox, SFC64)
+
+@pytest.fixture(scope='module',
+                params=(np.bool_, np.int8, np.int16, np.int32, np.int64,
+                        np.uint8, np.uint16, np.uint32, np.uint64))
+def dtype(request):
+    return request.param
+
+
+def params_0(f):
+    val = f()
+    assert_(np.isscalar(val))
+    val = f(10)
+    assert_(val.shape == (10,))
+    val = f((10, 10))
+    assert_(val.shape == (10, 10))
+    val = f((10, 10, 10))
+    assert_(val.shape == (10, 10, 10))
+    val = f(size=(5, 5))
+    assert_(val.shape == (5, 5))
+
+
+def params_1(f, bounded=False):
+    a = 5.0
+    b = np.arange(2.0, 12.0)
+    c = np.arange(2.0, 102.0).reshape((10, 10))
+    d = np.arange(2.0, 1002.0).reshape((10, 10, 10))
+    e = np.array([2.0, 3.0])
+    g = np.arange(2.0, 12.0).reshape((1, 10, 1))
+    if bounded:
+        a = 0.5
+        b = b / (1.5 * b.max())
+        c = c / (1.5 * c.max())
+        d = d / (1.5 * d.max())
+        e = e / (1.5 * e.max())
+        g = g / (1.5 * g.max())
+
+    # Scalar
+    f(a)
+    # Scalar - size
+    f(a, size=(10, 10))
+    # 1d
+    f(b)
+    # 2d
+    f(c)
+    # 3d
+    f(d)
+    # 1d size
+    f(b, size=10)
+    # 2d - size - broadcast
+    f(e, size=(10, 2))
+    # 3d - size
+    f(g, size=(10, 10, 10))
+
+
+def comp_state(state1, state2):
+    identical = True
+    if isinstance(state1, dict):
+        for key in state1:
+            identical &= comp_state(state1[key], state2[key])
+    elif type(state1) != type(state2):
+        identical &= type(state1) == type(state2)
+    else:
+        if (isinstance(state1, (list, tuple, np.ndarray)) and isinstance(
+                state2, (list, tuple, np.ndarray))):
+            for s1, s2 in zip(state1, state2):
+                identical &= comp_state(s1, s2)
+        else:
+            identical &= state1 == state2
+    return identical
+
+
+def warmup(rg, n=None):
+    if n is None:
+        n = 11 + np.random.randint(0, 20)
+    rg.standard_normal(n)
+    rg.standard_normal(n)
+    rg.standard_normal(n, dtype=np.float32)
+    rg.standard_normal(n, dtype=np.float32)
+    rg.integers(0, 2 ** 24, n, dtype=np.uint64)
+    rg.integers(0, 2 ** 48, n, dtype=np.uint64)
+    rg.standard_gamma(11.0, n)
+    rg.standard_gamma(11.0, n, dtype=np.float32)
+    rg.random(n, dtype=np.float64)
+    rg.random(n, dtype=np.float32)
+
+
+class RNG:
+    @classmethod
+    def setup_class(cls):
+        # Overridden in test classes. Place holder to silence IDE noise
+        cls.bit_generator = PCG64
+        cls.advance = None
+        cls.seed = [12345]
+        cls.rg = Generator(cls.bit_generator(*cls.seed))
+        cls.initial_state = cls.rg.bit_generator.state
+        cls.seed_vector_bits = 64
+        cls._extra_setup()
+
+    @classmethod
+    def _extra_setup(cls):
+        cls.vec_1d = np.arange(2.0, 102.0)
+        cls.vec_2d = np.arange(2.0, 102.0)[None, :]
+        cls.mat = np.arange(2.0, 102.0, 0.01).reshape((100, 100))
+        cls.seed_error = TypeError
+
+    def _reset_state(self):
+        self.rg.bit_generator.state = self.initial_state
+
+    def test_init(self):
+        rg = Generator(self.bit_generator())
+        state = rg.bit_generator.state
+        rg.standard_normal(1)
+        rg.standard_normal(1)
+        rg.bit_generator.state = state
+        new_state = rg.bit_generator.state
+        assert_(comp_state(state, new_state))
+
+    def test_advance(self):
+        state = self.rg.bit_generator.state
+        if hasattr(self.rg.bit_generator, 'advance'):
+            self.rg.bit_generator.advance(self.advance)
+            assert_(not comp_state(state, self.rg.bit_generator.state))
+        else:
+            bitgen_name = self.rg.bit_generator.__class__.__name__
+            pytest.skip(f'Advance is not supported by {bitgen_name}')
+
+    def test_jump(self):
+        state = self.rg.bit_generator.state
+        if hasattr(self.rg.bit_generator, 'jumped'):
+            bit_gen2 = self.rg.bit_generator.jumped()
+            jumped_state = bit_gen2.state
+            assert_(not comp_state(state, jumped_state))
+            self.rg.random(2 * 3 * 5 * 7 * 11 * 13 * 17)
+            self.rg.bit_generator.state = state
+            bit_gen3 = self.rg.bit_generator.jumped()
+            rejumped_state = bit_gen3.state
+            assert_(comp_state(jumped_state, rejumped_state))
+        else:
+            bitgen_name = self.rg.bit_generator.__class__.__name__
+            if bitgen_name not in ('SFC64',):
+                raise AttributeError(f'no "jumped" in {bitgen_name}')
+            pytest.skip(f'Jump is not supported by {bitgen_name}')
+
+    def test_uniform(self):
+        r = self.rg.uniform(-1.0, 0.0, size=10)
+        assert_(len(r) == 10)
+        assert_((r > -1).all())
+        assert_((r <= 0).all())
+
+    def test_uniform_array(self):
+        r = self.rg.uniform(np.array([-1.0] * 10), 0.0, size=10)
+        assert_(len(r) == 10)
+        assert_((r > -1).all())
+        assert_((r <= 0).all())
+        r = self.rg.uniform(np.array([-1.0] * 10),
+                            np.array([0.0] * 10), size=10)
+        assert_(len(r) == 10)
+        assert_((r > -1).all())
+        assert_((r <= 0).all())
+        r = self.rg.uniform(-1.0, np.array([0.0] * 10), size=10)
+        assert_(len(r) == 10)
+        assert_((r > -1).all())
+        assert_((r <= 0).all())
+
+    def test_random(self):
+        assert_(len(self.rg.random(10)) == 10)
+        params_0(self.rg.random)
+
+    def test_standard_normal_zig(self):
+        assert_(len(self.rg.standard_normal(10)) == 10)
+
+    def test_standard_normal(self):
+        assert_(len(self.rg.standard_normal(10)) == 10)
+        params_0(self.rg.standard_normal)
+
+    def test_standard_gamma(self):
+        assert_(len(self.rg.standard_gamma(10, 10)) == 10)
+        assert_(len(self.rg.standard_gamma(np.array([10] * 10), 10)) == 10)
+        params_1(self.rg.standard_gamma)
+
+    def test_standard_exponential(self):
+        assert_(len(self.rg.standard_exponential(10)) == 10)
+        params_0(self.rg.standard_exponential)
+
+    def test_standard_exponential_float(self):
+        randoms = self.rg.standard_exponential(10, dtype='float32')
+        assert_(len(randoms) == 10)
+        assert randoms.dtype == np.float32
+        params_0(partial(self.rg.standard_exponential, dtype='float32'))
+
+    def test_standard_exponential_float_log(self):
+        randoms = self.rg.standard_exponential(10, dtype='float32',
+                                               method='inv')
+        assert_(len(randoms) == 10)
+        assert randoms.dtype == np.float32
+        params_0(partial(self.rg.standard_exponential, dtype='float32',
+                         method='inv'))
+
+    def test_standard_cauchy(self):
+        assert_(len(self.rg.standard_cauchy(10)) == 10)
+        params_0(self.rg.standard_cauchy)
+
+    def test_standard_t(self):
+        assert_(len(self.rg.standard_t(10, 10)) == 10)
+        params_1(self.rg.standard_t)
+
+    def test_binomial(self):
+        assert_(self.rg.binomial(10, .5) >= 0)
+        assert_(self.rg.binomial(1000, .5) >= 0)
+
+    def test_reset_state(self):
+        state = self.rg.bit_generator.state
+        int_1 = self.rg.integers(2**31)
+        self.rg.bit_generator.state = state
+        int_2 = self.rg.integers(2**31)
+        assert_(int_1 == int_2)
+
+    def test_entropy_init(self):
+        rg = Generator(self.bit_generator())
+        rg2 = Generator(self.bit_generator())
+        assert_(not comp_state(rg.bit_generator.state,
+                               rg2.bit_generator.state))
+
+    def test_seed(self):
+        rg = Generator(self.bit_generator(*self.seed))
+        rg2 = Generator(self.bit_generator(*self.seed))
+        rg.random()
+        rg2.random()
+        assert_(comp_state(rg.bit_generator.state, rg2.bit_generator.state))
+
+    def test_reset_state_gauss(self):
+        rg = Generator(self.bit_generator(*self.seed))
+        rg.standard_normal()
+        state = rg.bit_generator.state
+        n1 = rg.standard_normal(size=10)
+        rg2 = Generator(self.bit_generator())
+        rg2.bit_generator.state = state
+        n2 = rg2.standard_normal(size=10)
+        assert_array_equal(n1, n2)
+
+    def test_reset_state_uint32(self):
+        rg = Generator(self.bit_generator(*self.seed))
+        rg.integers(0, 2 ** 24, 120, dtype=np.uint32)
+        state = rg.bit_generator.state
+        n1 = rg.integers(0, 2 ** 24, 10, dtype=np.uint32)
+        rg2 = Generator(self.bit_generator())
+        rg2.bit_generator.state = state
+        n2 = rg2.integers(0, 2 ** 24, 10, dtype=np.uint32)
+        assert_array_equal(n1, n2)
+
+    def test_reset_state_float(self):
+        rg = Generator(self.bit_generator(*self.seed))
+        rg.random(dtype='float32')
+        state = rg.bit_generator.state
+        n1 = rg.random(size=10, dtype='float32')
+        rg2 = Generator(self.bit_generator())
+        rg2.bit_generator.state = state
+        n2 = rg2.random(size=10, dtype='float32')
+        assert_((n1 == n2).all())
+
+    def test_shuffle(self):
+        original = np.arange(200, 0, -1)
+        permuted = self.rg.permutation(original)
+        assert_((original != permuted).any())
+
+    def test_permutation(self):
+        original = np.arange(200, 0, -1)
+        permuted = self.rg.permutation(original)
+        assert_((original != permuted).any())
+
+    def test_beta(self):
+        vals = self.rg.beta(2.0, 2.0, 10)
+        assert_(len(vals) == 10)
+        vals = self.rg.beta(np.array([2.0] * 10), 2.0)
+        assert_(len(vals) == 10)
+        vals = self.rg.beta(2.0, np.array([2.0] * 10))
+        assert_(len(vals) == 10)
+        vals = self.rg.beta(np.array([2.0] * 10), np.array([2.0] * 10))
+        assert_(len(vals) == 10)
+        vals = self.rg.beta(np.array([2.0] * 10), np.array([[2.0]] * 10))
+        assert_(vals.shape == (10, 10))
+
+    def test_bytes(self):
+        vals = self.rg.bytes(10)
+        assert_(len(vals) == 10)
+
+    def test_chisquare(self):
+        vals = self.rg.chisquare(2.0, 10)
+        assert_(len(vals) == 10)
+        params_1(self.rg.chisquare)
+
+    def test_exponential(self):
+        vals = self.rg.exponential(2.0, 10)
+        assert_(len(vals) == 10)
+        params_1(self.rg.exponential)
+
+    def test_f(self):
+        vals = self.rg.f(3, 1000, 10)
+        assert_(len(vals) == 10)
+
+    def test_gamma(self):
+        vals = self.rg.gamma(3, 2, 10)
+        assert_(len(vals) == 10)
+
+    def test_geometric(self):
+        vals = self.rg.geometric(0.5, 10)
+        assert_(len(vals) == 10)
+        params_1(self.rg.exponential, bounded=True)
+
+    def test_gumbel(self):
+        vals = self.rg.gumbel(2.0, 2.0, 10)
+        assert_(len(vals) == 10)
+
+    def test_laplace(self):
+        vals = self.rg.laplace(2.0, 2.0, 10)
+        assert_(len(vals) == 10)
+
+    def test_logitic(self):
+        vals = self.rg.logistic(2.0, 2.0, 10)
+        assert_(len(vals) == 10)
+
+    def test_logseries(self):
+        vals = self.rg.logseries(0.5, 10)
+        assert_(len(vals) == 10)
+
+    def test_negative_binomial(self):
+        vals = self.rg.negative_binomial(10, 0.2, 10)
+        assert_(len(vals) == 10)
+
+    def test_noncentral_chisquare(self):
+        vals = self.rg.noncentral_chisquare(10, 2, 10)
+        assert_(len(vals) == 10)
+
+    def test_noncentral_f(self):
+        vals = self.rg.noncentral_f(3, 1000, 2, 10)
+        assert_(len(vals) == 10)
+        vals = self.rg.noncentral_f(np.array([3] * 10), 1000, 2)
+        assert_(len(vals) == 10)
+        vals = self.rg.noncentral_f(3, np.array([1000] * 10), 2)
+        assert_(len(vals) == 10)
+        vals = self.rg.noncentral_f(3, 1000, np.array([2] * 10))
+        assert_(len(vals) == 10)
+
+    def test_normal(self):
+        vals = self.rg.normal(10, 0.2, 10)
+        assert_(len(vals) == 10)
+
+    def test_pareto(self):
+        vals = self.rg.pareto(3.0, 10)
+        assert_(len(vals) == 10)
+
+    def test_poisson(self):
+        vals = self.rg.poisson(10, 10)
+        assert_(len(vals) == 10)
+        vals = self.rg.poisson(np.array([10] * 10))
+        assert_(len(vals) == 10)
+        params_1(self.rg.poisson)
+
+    def test_power(self):
+        vals = self.rg.power(0.2, 10)
+        assert_(len(vals) == 10)
+
+    def test_integers(self):
+        vals = self.rg.integers(10, 20, 10)
+        assert_(len(vals) == 10)
+
+    def test_rayleigh(self):
+        vals = self.rg.rayleigh(0.2, 10)
+        assert_(len(vals) == 10)
+        params_1(self.rg.rayleigh, bounded=True)
+
+    def test_vonmises(self):
+        vals = self.rg.vonmises(10, 0.2, 10)
+        assert_(len(vals) == 10)
+
+    def test_wald(self):
+        vals = self.rg.wald(1.0, 1.0, 10)
+        assert_(len(vals) == 10)
+
+    def test_weibull(self):
+        vals = self.rg.weibull(1.0, 10)
+        assert_(len(vals) == 10)
+
+    def test_zipf(self):
+        vals = self.rg.zipf(10, 10)
+        assert_(len(vals) == 10)
+        vals = self.rg.zipf(self.vec_1d)
+        assert_(len(vals) == 100)
+        vals = self.rg.zipf(self.vec_2d)
+        assert_(vals.shape == (1, 100))
+        vals = self.rg.zipf(self.mat)
+        assert_(vals.shape == (100, 100))
+
+    def test_hypergeometric(self):
+        vals = self.rg.hypergeometric(25, 25, 20)
+        assert_(np.isscalar(vals))
+        vals = self.rg.hypergeometric(np.array([25] * 10), 25, 20)
+        assert_(vals.shape == (10,))
+
+    def test_triangular(self):
+        vals = self.rg.triangular(-5, 0, 5)
+        assert_(np.isscalar(vals))
+        vals = self.rg.triangular(-5, np.array([0] * 10), 5)
+        assert_(vals.shape == (10,))
+
+    def test_multivariate_normal(self):
+        mean = [0, 0]
+        cov = [[1, 0], [0, 100]]  # diagonal covariance
+        x = self.rg.multivariate_normal(mean, cov, 5000)
+        assert_(x.shape == (5000, 2))
+        x_zig = self.rg.multivariate_normal(mean, cov, 5000)
+        assert_(x.shape == (5000, 2))
+        x_inv = self.rg.multivariate_normal(mean, cov, 5000)
+        assert_(x.shape == (5000, 2))
+        assert_((x_zig != x_inv).any())
+
+    def test_multinomial(self):
+        vals = self.rg.multinomial(100, [1.0 / 3, 2.0 / 3])
+        assert_(vals.shape == (2,))
+        vals = self.rg.multinomial(100, [1.0 / 3, 2.0 / 3], size=10)
+        assert_(vals.shape == (10, 2))
+
+    def test_dirichlet(self):
+        s = self.rg.dirichlet((10, 5, 3), 20)
+        assert_(s.shape == (20, 3))
+
+    def test_pickle(self):
+        pick = pickle.dumps(self.rg)
+        unpick = pickle.loads(pick)
+        assert_((type(self.rg) == type(unpick)))
+        assert_(comp_state(self.rg.bit_generator.state,
+                           unpick.bit_generator.state))
+
+        pick = pickle.dumps(self.rg)
+        unpick = pickle.loads(pick)
+        assert_((type(self.rg) == type(unpick)))
+        assert_(comp_state(self.rg.bit_generator.state,
+                           unpick.bit_generator.state))
+
+    def test_seed_array(self):
+        if self.seed_vector_bits is None:
+            bitgen_name = self.bit_generator.__name__
+            pytest.skip(f'Vector seeding is not supported by {bitgen_name}')
+
+        if self.seed_vector_bits == 32:
+            dtype = np.uint32
+        else:
+            dtype = np.uint64
+        seed = np.array([1], dtype=dtype)
+        bg = self.bit_generator(seed)
+        state1 = bg.state
+        bg = self.bit_generator(1)
+        state2 = bg.state
+        assert_(comp_state(state1, state2))
+
+        seed = np.arange(4, dtype=dtype)
+        bg = self.bit_generator(seed)
+        state1 = bg.state
+        bg = self.bit_generator(seed[0])
+        state2 = bg.state
+        assert_(not comp_state(state1, state2))
+
+        seed = np.arange(1500, dtype=dtype)
+        bg = self.bit_generator(seed)
+        state1 = bg.state
+        bg = self.bit_generator(seed[0])
+        state2 = bg.state
+        assert_(not comp_state(state1, state2))
+
+        seed = 2 ** np.mod(np.arange(1500, dtype=dtype),
+                           self.seed_vector_bits - 1) + 1
+        bg = self.bit_generator(seed)
+        state1 = bg.state
+        bg  = self.bit_generator(seed[0])
+        state2 = bg.state
+        assert_(not comp_state(state1, state2))
+
+    def test_uniform_float(self):
+        rg = Generator(self.bit_generator(12345))
+        warmup(rg)
+        state = rg.bit_generator.state
+        r1 = rg.random(11, dtype=np.float32)
+        rg2 = Generator(self.bit_generator())
+        warmup(rg2)
+        rg2.bit_generator.state = state
+        r2 = rg2.random(11, dtype=np.float32)
+        assert_array_equal(r1, r2)
+        assert_equal(r1.dtype, np.float32)
+        assert_(comp_state(rg.bit_generator.state, rg2.bit_generator.state))
+
+    def test_gamma_floats(self):
+        rg = Generator(self.bit_generator())
+        warmup(rg)
+        state = rg.bit_generator.state
+        r1 = rg.standard_gamma(4.0, 11, dtype=np.float32)
+        rg2 = Generator(self.bit_generator())
+        warmup(rg2)
+        rg2.bit_generator.state = state
+        r2 = rg2.standard_gamma(4.0, 11, dtype=np.float32)
+        assert_array_equal(r1, r2)
+        assert_equal(r1.dtype, np.float32)
+        assert_(comp_state(rg.bit_generator.state, rg2.bit_generator.state))
+
+    def test_normal_floats(self):
+        rg = Generator(self.bit_generator())
+        warmup(rg)
+        state = rg.bit_generator.state
+        r1 = rg.standard_normal(11, dtype=np.float32)
+        rg2 = Generator(self.bit_generator())
+        warmup(rg2)
+        rg2.bit_generator.state = state
+        r2 = rg2.standard_normal(11, dtype=np.float32)
+        assert_array_equal(r1, r2)
+        assert_equal(r1.dtype, np.float32)
+        assert_(comp_state(rg.bit_generator.state, rg2.bit_generator.state))
+
+    def test_normal_zig_floats(self):
+        rg = Generator(self.bit_generator())
+        warmup(rg)
+        state = rg.bit_generator.state
+        r1 = rg.standard_normal(11, dtype=np.float32)
+        rg2 = Generator(self.bit_generator())
+        warmup(rg2)
+        rg2.bit_generator.state = state
+        r2 = rg2.standard_normal(11, dtype=np.float32)
+        assert_array_equal(r1, r2)
+        assert_equal(r1.dtype, np.float32)
+        assert_(comp_state(rg.bit_generator.state, rg2.bit_generator.state))
+
+    def test_output_fill(self):
+        rg = self.rg
+        state = rg.bit_generator.state
+        size = (31, 7, 97)
+        existing = np.empty(size)
+        rg.bit_generator.state = state
+        rg.standard_normal(out=existing)
+        rg.bit_generator.state = state
+        direct = rg.standard_normal(size=size)
+        assert_equal(direct, existing)
+
+        sized = np.empty(size)
+        rg.bit_generator.state = state
+        rg.standard_normal(out=sized, size=sized.shape)
+
+        existing = np.empty(size, dtype=np.float32)
+        rg.bit_generator.state = state
+        rg.standard_normal(out=existing, dtype=np.float32)
+        rg.bit_generator.state = state
+        direct = rg.standard_normal(size=size, dtype=np.float32)
+        assert_equal(direct, existing)
+
+    def test_output_filling_uniform(self):
+        rg = self.rg
+        state = rg.bit_generator.state
+        size = (31, 7, 97)
+        existing = np.empty(size)
+        rg.bit_generator.state = state
+        rg.random(out=existing)
+        rg.bit_generator.state = state
+        direct = rg.random(size=size)
+        assert_equal(direct, existing)
+
+        existing = np.empty(size, dtype=np.float32)
+        rg.bit_generator.state = state
+        rg.random(out=existing, dtype=np.float32)
+        rg.bit_generator.state = state
+        direct = rg.random(size=size, dtype=np.float32)
+        assert_equal(direct, existing)
+
+    def test_output_filling_exponential(self):
+        rg = self.rg
+        state = rg.bit_generator.state
+        size = (31, 7, 97)
+        existing = np.empty(size)
+        rg.bit_generator.state = state
+        rg.standard_exponential(out=existing)
+        rg.bit_generator.state = state
+        direct = rg.standard_exponential(size=size)
+        assert_equal(direct, existing)
+
+        existing = np.empty(size, dtype=np.float32)
+        rg.bit_generator.state = state
+        rg.standard_exponential(out=existing, dtype=np.float32)
+        rg.bit_generator.state = state
+        direct = rg.standard_exponential(size=size, dtype=np.float32)
+        assert_equal(direct, existing)
+
+    def test_output_filling_gamma(self):
+        rg = self.rg
+        state = rg.bit_generator.state
+        size = (31, 7, 97)
+        existing = np.zeros(size)
+        rg.bit_generator.state = state
+        rg.standard_gamma(1.0, out=existing)
+        rg.bit_generator.state = state
+        direct = rg.standard_gamma(1.0, size=size)
+        assert_equal(direct, existing)
+
+        existing = np.zeros(size, dtype=np.float32)
+        rg.bit_generator.state = state
+        rg.standard_gamma(1.0, out=existing, dtype=np.float32)
+        rg.bit_generator.state = state
+        direct = rg.standard_gamma(1.0, size=size, dtype=np.float32)
+        assert_equal(direct, existing)
+
+    def test_output_filling_gamma_broadcast(self):
+        rg = self.rg
+        state = rg.bit_generator.state
+        size = (31, 7, 97)
+        mu = np.arange(97.0) + 1.0
+        existing = np.zeros(size)
+        rg.bit_generator.state = state
+        rg.standard_gamma(mu, out=existing)
+        rg.bit_generator.state = state
+        direct = rg.standard_gamma(mu, size=size)
+        assert_equal(direct, existing)
+
+        existing = np.zeros(size, dtype=np.float32)
+        rg.bit_generator.state = state
+        rg.standard_gamma(mu, out=existing, dtype=np.float32)
+        rg.bit_generator.state = state
+        direct = rg.standard_gamma(mu, size=size, dtype=np.float32)
+        assert_equal(direct, existing)
+
+    def test_output_fill_error(self):
+        rg = self.rg
+        size = (31, 7, 97)
+        existing = np.empty(size)
+        with pytest.raises(TypeError):
+            rg.standard_normal(out=existing, dtype=np.float32)
+        with pytest.raises(ValueError):
+            rg.standard_normal(out=existing[::3])
+        existing = np.empty(size, dtype=np.float32)
+        with pytest.raises(TypeError):
+            rg.standard_normal(out=existing, dtype=np.float64)
+
+        existing = np.zeros(size, dtype=np.float32)
+        with pytest.raises(TypeError):
+            rg.standard_gamma(1.0, out=existing, dtype=np.float64)
+        with pytest.raises(ValueError):
+            rg.standard_gamma(1.0, out=existing[::3], dtype=np.float32)
+        existing = np.zeros(size, dtype=np.float64)
+        with pytest.raises(TypeError):
+            rg.standard_gamma(1.0, out=existing, dtype=np.float32)
+        with pytest.raises(ValueError):
+            rg.standard_gamma(1.0, out=existing[::3])
+
+    def test_integers_broadcast(self, dtype):
+        if dtype == np.bool_:
+            upper = 2
+            lower = 0
+        else:
+            info = np.iinfo(dtype)
+            upper = int(info.max) + 1
+            lower = info.min
+        self._reset_state()
+        a = self.rg.integers(lower, [upper] * 10, dtype=dtype)
+        self._reset_state()
+        b = self.rg.integers([lower] * 10, upper, dtype=dtype)
+        assert_equal(a, b)
+        self._reset_state()
+        c = self.rg.integers(lower, upper, size=10, dtype=dtype)
+        assert_equal(a, c)
+        self._reset_state()
+        d = self.rg.integers(np.array(
+            [lower] * 10), np.array([upper], dtype=object), size=10,
+            dtype=dtype)
+        assert_equal(a, d)
+        self._reset_state()
+        e = self.rg.integers(
+            np.array([lower] * 10), np.array([upper] * 10), size=10,
+            dtype=dtype)
+        assert_equal(a, e)
+
+        self._reset_state()
+        a = self.rg.integers(0, upper, size=10, dtype=dtype)
+        self._reset_state()
+        b = self.rg.integers([upper] * 10, dtype=dtype)
+        assert_equal(a, b)
+
+    def test_integers_numpy(self, dtype):
+        high = np.array([1])
+        low = np.array([0])
+
+        out = self.rg.integers(low, high, dtype=dtype)
+        assert out.shape == (1,)
+
+        out = self.rg.integers(low[0], high, dtype=dtype)
+        assert out.shape == (1,)
+
+        out = self.rg.integers(low, high[0], dtype=dtype)
+        assert out.shape == (1,)
+
+    def test_integers_broadcast_errors(self, dtype):
+        if dtype == np.bool_:
+            upper = 2
+            lower = 0
+        else:
+            info = np.iinfo(dtype)
+            upper = int(info.max) + 1
+            lower = info.min
+        with pytest.raises(ValueError):
+            self.rg.integers(lower, [upper + 1] * 10, dtype=dtype)
+        with pytest.raises(ValueError):
+            self.rg.integers(lower - 1, [upper] * 10, dtype=dtype)
+        with pytest.raises(ValueError):
+            self.rg.integers([lower - 1], [upper] * 10, dtype=dtype)
+        with pytest.raises(ValueError):
+            self.rg.integers([0], [0], dtype=dtype)
+
+
+class TestMT19937(RNG):
+    @classmethod
+    def setup_class(cls):
+        cls.bit_generator = MT19937
+        cls.advance = None
+        cls.seed = [2 ** 21 + 2 ** 16 + 2 ** 5 + 1]
+        cls.rg = Generator(cls.bit_generator(*cls.seed))
+        cls.initial_state = cls.rg.bit_generator.state
+        cls.seed_vector_bits = 32
+        cls._extra_setup()
+        cls.seed_error = ValueError
+
+    def test_numpy_state(self):
+        nprg = np.random.RandomState()
+        nprg.standard_normal(99)
+        state = nprg.get_state()
+        self.rg.bit_generator.state = state
+        state2 = self.rg.bit_generator.state
+        assert_((state[1] == state2['state']['key']).all())
+        assert_((state[2] == state2['state']['pos']))
+
+
+class TestPhilox(RNG):
+    @classmethod
+    def setup_class(cls):
+        cls.bit_generator = Philox
+        cls.advance = 2**63 + 2**31 + 2**15 + 1
+        cls.seed = [12345]
+        cls.rg = Generator(cls.bit_generator(*cls.seed))
+        cls.initial_state = cls.rg.bit_generator.state
+        cls.seed_vector_bits = 64
+        cls._extra_setup()
+
+
+class TestSFC64(RNG):
+    @classmethod
+    def setup_class(cls):
+        cls.bit_generator = SFC64
+        cls.advance = None
+        cls.seed = [12345]
+        cls.rg = Generator(cls.bit_generator(*cls.seed))
+        cls.initial_state = cls.rg.bit_generator.state
+        cls.seed_vector_bits = 192
+        cls._extra_setup()
+
+
+class TestPCG64(RNG):
+    @classmethod
+    def setup_class(cls):
+        cls.bit_generator = PCG64
+        cls.advance = 2**63 + 2**31 + 2**15 + 1
+        cls.seed = [12345]
+        cls.rg = Generator(cls.bit_generator(*cls.seed))
+        cls.initial_state = cls.rg.bit_generator.state
+        cls.seed_vector_bits = 64
+        cls._extra_setup()
+
+
+class TestPCG64DXSM(RNG):
+    @classmethod
+    def setup_class(cls):
+        cls.bit_generator = PCG64DXSM
+        cls.advance = 2**63 + 2**31 + 2**15 + 1
+        cls.seed = [12345]
+        cls.rg = Generator(cls.bit_generator(*cls.seed))
+        cls.initial_state = cls.rg.bit_generator.state
+        cls.seed_vector_bits = 64
+        cls._extra_setup()
+
+
+class TestDefaultRNG(RNG):
+    @classmethod
+    def setup_class(cls):
+        # This will duplicate some tests that directly instantiate a fresh
+        # Generator(), but that's okay.
+        cls.bit_generator = PCG64
+        cls.advance = 2**63 + 2**31 + 2**15 + 1
+        cls.seed = [12345]
+        cls.rg = np.random.default_rng(*cls.seed)
+        cls.initial_state = cls.rg.bit_generator.state
+        cls.seed_vector_bits = 64
+        cls._extra_setup()
+
+    def test_default_is_pcg64(self):
+        # In order to change the default BitGenerator, we'll go through
+        # a deprecation cycle to move to a different function.
+        assert_(isinstance(self.rg.bit_generator, PCG64))
+
+    def test_seed(self):
+        np.random.default_rng()
+        np.random.default_rng(None)
+        np.random.default_rng(12345)
+        np.random.default_rng(0)
+        np.random.default_rng(43660444402423911716352051725018508569)
+        np.random.default_rng([43660444402423911716352051725018508569,
+                               279705150948142787361475340226491943209])
+        with pytest.raises(ValueError):
+            np.random.default_rng(-1)
+        with pytest.raises(ValueError):
+            np.random.default_rng([12345, -1])