if mode not in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT:r>', '<STR_LIT>'):<EOL><INDENT>if mode in ('<STR_LIT:f>', '<STR_LIT>'):<EOL><INDENT>msg = "<STR_LIT>".join((<EOL>"<STR_LIT>",<EOL>"<STR_LIT>"))<EOL>warnings.warn(msg, DeprecationWarning)<EOL>mode = '<STR_LIT>'<EOL><DEDENT>elif mode in ('<STR_LIT:e>', '<STR_LIT>'):<EOL><INDENT>msg = "<STR_LIT>",<EOL>warnings.warn(msg, DeprecationWarning)<EOL>mode = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % mode)<EOL><DEDENT><DEDENT>a, wrap = _makearray(a)<EOL>_assertRank2(a)<EOL>_assertNoEmpty2d(a)<EOL>m, n = a.shape<EOL>t, result_t = _commonType(a)<EOL>a = _fastCopyAndTranspose(t, a)<EOL>a = _to_native_byte_order(a)<EOL>mn = min(m, n)<EOL>tau = zeros((mn,), t)<EOL>if isComplexType(t):<EOL><INDENT>lapack_routine = lapack_lite.zgeqrf<EOL>routine_name = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>lapack_routine = lapack_lite.dgeqrf<EOL>routine_name = '<STR_LIT>'<EOL><DEDENT>lwork = <NUM_LIT:1><EOL>work = zeros((lwork,), t)<EOL>results = lapack_routine(m, n, a, m, tau, work, -<NUM_LIT:1>, <NUM_LIT:0>)<EOL>if results['<STR_LIT:info>'] != <NUM_LIT:0>:<EOL><INDENT>raise LinAlgError('<STR_LIT>' % (routine_name, results['<STR_LIT:info>']))<EOL><DEDENT>lwork = int(abs(work[<NUM_LIT:0>]))<EOL>work = zeros((lwork,), t)<EOL>results = lapack_routine(m, n, a, m, tau, work, lwork, <NUM_LIT:0>)<EOL>if results['<STR_LIT:info>'] != <NUM_LIT:0>:<EOL><INDENT>raise LinAlgError('<STR_LIT>' % (routine_name, results['<STR_LIT:info>']))<EOL><DEDENT>if mode == '<STR_LIT:r>':<EOL><INDENT>r = _fastCopyAndTranspose(result_t, a[:, :mn])<EOL>return wrap(triu(r))<EOL><DEDENT>if mode == '<STR_LIT>':<EOL><INDENT>return a, tau<EOL><DEDENT>if mode == '<STR_LIT>':<EOL><INDENT>if t != result_t :<EOL><INDENT>a = a.astype(result_t)<EOL><DEDENT>return wrap(a.T)<EOL><DEDENT>if mode == '<STR_LIT>' and m > n:<EOL><INDENT>mc = m<EOL>q = empty((m, m), t)<EOL><DEDENT>else:<EOL><INDENT>mc = mn<EOL>q = empty((n, m), t)<EOL><DEDENT>q[:n] = a<EOL>if isComplexType(t):<EOL><INDENT>lapack_routine = lapack_lite.zungqr<EOL>routine_name = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>lapack_routine = lapack_lite.dorgqr<EOL>routine_name = '<STR_LIT>'<EOL><DEDENT>lwork = <NUM_LIT:1><EOL>work = zeros((lwork,), t)<EOL>results = lapack_routine(m, mc, mn, q, m, tau, work, -<NUM_LIT:1>, <NUM_LIT:0>)<EOL>if results['<STR_LIT:info>'] != <NUM_LIT:0>:<EOL><INDENT>raise LinAlgError('<STR_LIT>' % (routine_name, results['<STR_LIT:info>']))<EOL><DEDENT>lwork = int(abs(work[<NUM_LIT:0>]))<EOL>work = zeros((lwork,), t)<EOL>results = lapack_routine(m, mc, mn, q, m, tau, work, lwork, <NUM_LIT:0>)<EOL>if results['<STR_LIT:info>'] != <NUM_LIT:0>:<EOL><INDENT>raise LinAlgError('<STR_LIT>' % (routine_name, results['<STR_LIT:info>']))<EOL><DEDENT>q = _fastCopyAndTranspose(result_t, q[:mc])<EOL>r = _fastCopyAndTranspose(result_t, a[:, :mc])<EOL>return wrap(q), wrap(triu(r))<EOL>

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)
    Matrix to be factored.
mode : {'reduced', 'complete', 'r', 'raw', 'full', 'economic'}, 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,)
    'full'     : alias of 'reduced', deprecated
    'economic' : returns h from 'raw', deprecated.

    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
-------
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.
r : ndarray of float or complex, optional
    The upper-triangular matrix.
(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.

Notes
-----
This is an interface to the LAPACK routines dgeqrf, zgeqrf,
dorgqr, and zungqr.

For more information on the qr factorization, see for example:
http://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 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')
>>> r3 = np.linalg.qr(a, mode='economic')
>>> np.allclose(r, r2)  # mode='r' returns the same r as mode='full'
True
>>> # But only triu parts are guaranteed equal when mode='economic'
>>> np.allclose(r, np.triu(r3[:6,:6], k=0))
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, 0, 2, 1])
>>> q, r = LA.qr(A)
>>> p = np.dot(q.T, b)
>>> np.dot(LA.inv(r), p)
array([  1.1e-16,   1.0e+00])


a, wrap = _makearray(a)<EOL>_assertNoEmpty2d(a)<EOL>_assertRankAtLeast2(a)<EOL>_assertNdSquareness(a)<EOL>_assertFinite(a)<EOL>t, result_t = _commonType(a)<EOL>extobj = get_linalg_error_extobj(<EOL>_raise_linalgerror_eigenvalues_nonconvergence)<EOL>signature = '<STR_LIT>' if isComplexType(t) else '<STR_LIT>'<EOL>w = _umath_linalg.eigvals(a, signature=signature, extobj=extobj)<EOL>if not isComplexType(t):<EOL><INDENT>if all(w.imag == <NUM_LIT:0>):<EOL><INDENT>w = w.real<EOL>result_t = _realType(result_t)<EOL><DEDENT>else:<EOL><INDENT>result_t = _complexType(result_t)<EOL><DEDENT><DEDENT>return w.astype(result_t)<EOL>

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 symmetric or Hermitian arrays.
eigh : eigenvalues and eigenvectors of symmetric/Hermitian arrays.

Notes
-----
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.])


UPLO = UPLO.upper()<EOL>if UPLO not in ('<STR_LIT:L>', '<STR_LIT>'):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>extobj = get_linalg_error_extobj(<EOL>_raise_linalgerror_eigenvalues_nonconvergence)<EOL>if UPLO == '<STR_LIT:L>':<EOL><INDENT>gufunc = _umath_linalg.eigvalsh_lo<EOL><DEDENT>else:<EOL><INDENT>gufunc = _umath_linalg.eigvalsh_up<EOL><DEDENT>a, wrap = _makearray(a)<EOL>_assertNoEmpty2d(a)<EOL>_assertRankAtLeast2(a)<EOL>_assertNdSquareness(a)<EOL>t, result_t = _commonType(a)<EOL>signature = '<STR_LIT>' if isComplexType(t) else '<STR_LIT>'<EOL>w = gufunc(a, signature=signature, extobj=extobj)<EOL>return w.astype(_realType(result_t))<EOL>

Compute the eigenvalues of a 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
    Same as `lower`, with 'L' for lower and 'U' for upper triangular.
    Deprecated.

Returns
-------
w : (..., M,) ndarray
    The eigenvalues, not necessarily ordered, each repeated according to
    its multiplicity.

Raises
------
LinAlgError
    If the eigenvalue computation does not converge.

See Also
--------
eigh : eigenvalues and eigenvectors of symmetric/Hermitian arrays.
eigvals : eigenvalues of general real or complex arrays.
eig : eigenvalues and right eigenvectors of general real or complex
      arrays.

Notes
-----
Broadcasting rules apply, see the `numpy.linalg` documentation for
details.

The eigenvalues are computed using LAPACK routines _ssyevd, _heevd

Examples
--------
>>> from numpy import linalg as LA
>>> a = np.array([[1, -2j], [2j, 5]])
>>> LA.eigvalsh(a)
array([ 0.17157288+0.j,  5.82842712+0.j])


a, wrap = _makearray(a)<EOL>_assertRankAtLeast2(a)<EOL>_assertNdSquareness(a)<EOL>_assertFinite(a)<EOL>t, result_t = _commonType(a)<EOL>extobj = get_linalg_error_extobj(<EOL>_raise_linalgerror_eigenvalues_nonconvergence)<EOL>signature = '<STR_LIT>' if isComplexType(t) else '<STR_LIT>'<EOL>w, vt = _umath_linalg.eig(a, signature=signature, extobj=extobj)<EOL>if not isComplexType(t) and all(w.imag == <NUM_LIT:0.0>):<EOL><INDENT>w = w.real<EOL>vt = vt.real<EOL>result_t = _realType(result_t)<EOL><DEDENT>else:<EOL><INDENT>result_t = _complexType(result_t)<EOL><DEDENT>vt = vt.astype(result_t)<EOL>return w.astype(result_t), wrap(vt)<EOL>

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
-------
w : (..., M) array
    The eigenvalues, each repeated according to its multiplicity.
    The eigenvalues are not necessarily ordered. The resulting
    array will be always be of complex type. When `a` is real
    the resulting eigenvalues will be real (0 imaginary part) or
    occur in conjugate pairs

v : (..., M, M) array
    The normalized (unit "length") eigenvectors, such that the
    column ``v[:,i]`` is the eigenvector corresponding to the
    eigenvalue ``w[i]``.

Raises
------
LinAlgError
    If the eigenvalue computation does not converge.

See Also
--------
eigvalsh : eigenvalues of a symmetric or Hermitian (conjugate symmetric)
   array.

eigvals : eigenvalues of a non-symmetric array.

Notes
-----
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 ``dot(a,v) = w * v``. Thus, the arrays `a`, `w`, and
`v` satisfy the equations ``dot(a[:,:], v[:,i]) = w[i] * v[:,i]``
for :math:`i \\in \\{0,...,M-1\\}`.

The array `v` of 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. Likewise, the (complex-valued)
matrix of eigenvectors `v` is unitary if the matrix `a` is normal, i.e.,
if ``dot(a, a.H) = dot(a.H, a)``, where `a.H` denotes the conjugate
transpose of `a`.

Finally, it is emphasized that `v` consists of the *right* (as in
right-hand side) eigenvectors of `a`.  A vector `y` satisfying
``dot(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 e-values and e-vectors.

>>> w, v = LA.eig(np.diag((1, 2, 3)))
>>> w; v
array([ 1.,  2.,  3.])
array([[ 1.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  1.]])

Real matrix possessing complex e-values and e-vectors; note that the
e-values are complex conjugates of each other.

>>> w, v = LA.eig(np.array([[1, -1], [1, 1]]))
>>> w; v
array([ 1. + 1.j,  1. - 1.j])
array([[ 0.70710678+0.j        ,  0.70710678+0.j        ],
       [ 0.00000000-0.70710678j,  0.00000000+0.70710678j]])

Complex-valued matrix with real e-values (but complex-valued e-vectors);
note that a.conj().T = a, i.e., a is Hermitian.

>>> a = np.array([[1, 1j], [-1j, 1]])
>>> w, v = LA.eig(a)
>>> w; v
array([  2.00000000e+00+0.j,   5.98651912e-36+0.j]) # i.e., {2, 0}
array([[ 0.00000000+0.70710678j,  0.70710678+0.j        ],
       [ 0.70710678+0.j        ,  0.00000000+0.70710678j]])

Be careful about round-off error!

>>> a = np.array([[1 + 1e-9, 0], [0, 1 - 1e-9]])
>>> # Theor. e-values are 1 +/- 1e-9
>>> w, v = LA.eig(a)
>>> w; v
array([ 1.,  1.])
array([[ 1.,  0.],
       [ 0.,  1.]])


UPLO = UPLO.upper()<EOL>if UPLO not in ('<STR_LIT:L>', '<STR_LIT>'):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>a, wrap = _makearray(a)<EOL>_assertRankAtLeast2(a)<EOL>_assertNdSquareness(a)<EOL>t, result_t = _commonType(a)<EOL>extobj = get_linalg_error_extobj(<EOL>_raise_linalgerror_eigenvalues_nonconvergence)<EOL>if UPLO == '<STR_LIT:L>':<EOL><INDENT>gufunc = _umath_linalg.eigh_lo<EOL><DEDENT>else:<EOL><INDENT>gufunc = _umath_linalg.eigh_up<EOL><DEDENT>signature = '<STR_LIT>' if isComplexType(t) else '<STR_LIT>'<EOL>w, vt = gufunc(a, signature=signature, extobj=extobj)<EOL>w = w.astype(_realType(result_t))<EOL>vt = vt.astype(result_t)<EOL>return w, wrap(vt)<EOL>

Return the eigenvalues and eigenvectors of a Hermitian or 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/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').

Returns
-------
w : (..., M) ndarray
    The eigenvalues, not necessarily ordered.
v : {(..., M, M) ndarray, (..., M, M) matrix}
    The column ``v[:, i]`` is the normalized eigenvector corresponding
    to the eigenvalue ``w[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 symmetric or Hermitian arrays.
eig : eigenvalues and right eigenvectors for non-symmetric arrays.
eigvals : eigenvalues of non-symmetric arrays.

Notes
-----
Broadcasting rules apply, see the `numpy.linalg` documentation for
details.

The eigenvalues/eigenvectors are computed using LAPACK routines _ssyevd,
_heevd

The eigenvalues of real symmetric or complex Hermitian matrices are
always real. [1]_ The array `v` of (column) eigenvectors is unitary
and `a`, `w`, and `v` satisfy the equations
``dot(a, v[:, i]) = w[i] * v[:, 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]])
>>> w, v = LA.eigh(a)
>>> w; v
array([ 0.17157288,  5.82842712])
array([[-0.92387953+0.j        , -0.38268343+0.j        ],
       [ 0.00000000+0.38268343j,  0.00000000-0.92387953j]])

>>> np.dot(a, v[:, 0]) - w[0] * v[:, 0] # verify 1st e-val/vec pair
array([2.77555756e-17 + 0.j, 0. + 1.38777878e-16j])
>>> np.dot(a, v[:, 1]) - w[1] * v[:, 1] # verify 2nd e-val/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]])
>>> w, v = LA.eigh(A)
>>> w; v
array([ 0.17157288,  5.82842712])
matrix([[-0.92387953+0.j        , -0.38268343+0.j        ],
        [ 0.00000000+0.38268343j,  0.00000000-0.92387953j]])


def svd(a, full_matrices=<NUM_LIT:1>, compute_uv=<NUM_LIT:1>):

a, wrap = _makearray(a)<EOL>_assertNoEmpty2d(a)<EOL>_assertRankAtLeast2(a)<EOL>t, result_t = _commonType(a)<EOL>extobj = get_linalg_error_extobj(_raise_linalgerror_svd_nonconvergence)<EOL>m = a.shape[-<NUM_LIT:2>]<EOL>n = a.shape[-<NUM_LIT:1>]<EOL>if compute_uv:<EOL><INDENT>if full_matrices:<EOL><INDENT>if m < n:<EOL><INDENT>gufunc = _umath_linalg.svd_m_f<EOL><DEDENT>else:<EOL><INDENT>gufunc = _umath_linalg.svd_n_f<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if m < n:<EOL><INDENT>gufunc = _umath_linalg.svd_m_s<EOL><DEDENT>else:<EOL><INDENT>gufunc = _umath_linalg.svd_n_s<EOL><DEDENT><DEDENT>signature = '<STR_LIT>' if isComplexType(t) else '<STR_LIT>'<EOL>u, s, vt = gufunc(a, signature=signature, extobj=extobj)<EOL>u = u.astype(result_t)<EOL>s = s.astype(_realType(result_t))<EOL>vt = vt.astype(result_t)<EOL>return wrap(u), s, wrap(vt)<EOL><DEDENT>else:<EOL><INDENT>if m < n:<EOL><INDENT>gufunc = _umath_linalg.svd_m<EOL><DEDENT>else:<EOL><INDENT>gufunc = _umath_linalg.svd_n<EOL><DEDENT>signature = '<STR_LIT>' if isComplexType(t) else '<STR_LIT>'<EOL>s = gufunc(a, signature=signature, extobj=extobj)<EOL>s = s.astype(_realType(result_t))<EOL>return s<EOL><DEDENT>

Singular Value Decomposition.

Factors the matrix `a` as ``u * np.diag(s) * v``, where `u` and `v`
are unitary and `s` is a 1-d array of `a`'s singular values.

Parameters
----------
a : (..., M, N) array_like
    A real or complex matrix of shape (`M`, `N`) .
full_matrices : bool, optional
    If True (default), `u` and `v` 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 `v` in addition to `s`.  True
    by default.

Returns
-------
u : { (..., M, M), (..., M, K) } array
    Unitary matrices. The actual shape depends on the value of
    ``full_matrices``. Only returned when ``compute_uv`` is True.
s : (..., K) array
    The singular values for every matrix, sorted in descending order.
v : { (..., N, N), (..., K, N) } array
    Unitary matrices. The actual shape depends on the value of
    ``full_matrices``. Only returned when ``compute_uv`` is True.

Raises
------
LinAlgError
    If SVD computation does not converge.

Notes
-----
Broadcasting rules apply, see the `numpy.linalg` documentation for
details.

The decomposition is performed using LAPACK routine _gesdd

The SVD is commonly written as ``a = U S V.H``.  The `v` returned
by this function is ``V.H`` and ``u = U``.

If ``U`` is a unitary matrix, it means that it
satisfies ``U.H = inv(U)``.

The rows of `v` are the eigenvectors of ``a.H a``. The columns
of `u` are the eigenvectors of ``a a.H``.  For row ``i`` in
`v` and column ``i`` in `u`, the corresponding eigenvalue is
``s[i]**2``.

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)

Reconstruction based on full SVD:

>>> U, s, V = np.linalg.svd(a, full_matrices=True)
>>> U.shape, V.shape, s.shape
((9, 9), (6, 6), (6,))
>>> S = np.zeros((9, 6), dtype=complex)
>>> S[:6, :6] = np.diag(s)
>>> np.allclose(a, np.dot(U, np.dot(S, V)))
True

Reconstruction based on reduced SVD:

>>> U, s, V = np.linalg.svd(a, full_matrices=False)
>>> U.shape, V.shape, s.shape
((9, 6), (6, 6), (6,))
>>> S = np.diag(s)
>>> np.allclose(a, np.dot(U, np.dot(S, V)))
True


x = asarray(x) <EOL>if p is None:<EOL><INDENT>s = svd(x, compute_uv=False)<EOL>return s[<NUM_LIT:0>]/s[-<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>return norm(x, p)*norm(inv(x), p)<EOL><DEDENT>

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:

    =====  ============================
    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
>>> min(LA.svd(a, compute_uv=0))*min(LA.svd(LA.inv(a), compute_uv=0))
0.70710678118654746


M = asarray(M)<EOL>if M.ndim > <NUM_LIT:2>:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if M.ndim < <NUM_LIT:2>:<EOL><INDENT>return int(not all(M==<NUM_LIT:0>))<EOL><DEDENT>S = svd(M, compute_uv=False)<EOL>if tol is None:<EOL><INDENT>tol = S.max() * max(M.shape) * finfo(S.dtype).eps<EOL><DEDENT>return sum(S > tol)<EOL>

Return matrix rank of array using SVD method

Rank of the array is the number of SVD singular values of the array that are
greater than `tol`.

Parameters
----------
M : {(M,), (M, N)} array_like
    array of <=2 dimensions
tol : {None, 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.shape) * eps``.

Notes
-----
The default threshold to detect rank deficiency is a test on the magnitude
of the singular values of `M`.  By default, we identify singular values less
than ``S.max() * max(M.shape) * 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 `M` that is an exact (in floating point) linear combination of other
columns in `M`. Computing the SVD on `M` 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 `M` rank deficient even if
the linear combination of some columns of `M` is not exactly equal to
another column of `M` but only numerically very close to another column of
`M`.

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(M.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 `M` 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 documention, "Rank"
       http://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, wrap = _makearray(a)<EOL>_assertNoEmpty2d(a)<EOL>a = a.conjugate()<EOL>u, s, vt = svd(a, <NUM_LIT:0>)<EOL>m = u.shape[<NUM_LIT:0>]<EOL>n = vt.shape[<NUM_LIT:1>]<EOL>cutoff = rcond*maximum.reduce(s)<EOL>for i in range(min(n, m)):<EOL><INDENT>if s[i] > cutoff:<EOL><INDENT>s[i] = <NUM_LIT:1.>/s[i]<EOL><DEDENT>else:<EOL><INDENT>s[i] = <NUM_LIT:0.>;<EOL><DEDENT><DEDENT>res = dot(transpose(vt), multiply(s[:, newaxis], transpose(u)))<EOL>return wrap(res)<EOL>

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.

Parameters
----------
a : (M, N) array_like
  Matrix to be pseudo-inverted.
rcond : float
  Cutoff for small singular values.
  Singular values smaller (in modulus) than
  `rcond` * largest_singular_value (again, in modulus)
  are set to zero.

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.

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 = asarray(a)<EOL>_assertNoEmpty2d(a)<EOL>_assertRankAtLeast2(a)<EOL>_assertNdSquareness(a)<EOL>t, result_t = _commonType(a)<EOL>real_t = _realType(result_t)<EOL>signature = '<STR_LIT>' if isComplexType(t) else '<STR_LIT>'<EOL>sign, logdet = _umath_linalg.slogdet(a, signature=signature)<EOL>return sign.astype(result_t), logdet.astype(real_t)<EOL>

Compute the sign and (natural) logarithm of the determinant of an array.

If an array has a very small or very large determinant, than 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
-------
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.
logdet : (...) array_like
    The natural log of the absolute value of the determinant.

If the determinant is zero, then `sign` will be 0 and `logdet` will be
-Inf. In all cases, the determinant is equal to ``sign * np.exp(logdet)``.

See Also
--------
det

Notes
-----
Broadcasting rules apply, see the `numpy.linalg` documentation for
details.

The determinant is computed via LU factorization using the LAPACK
routine z/dgetrf.

.. versionadded:: 1.6.0.

Examples
--------
The determinant of a 2-D array ``[[a, b], [c, d]]`` is ``ad - bc``:

>>> a = np.array([[1, 2], [3, 4]])
>>> (sign, logdet) = np.linalg.slogdet(a)
>>> (sign, logdet)
(-1, 0.69314718055994529)
>>> sign * np.exp(logdet)
-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, logdet = np.linalg.slogdet(a)
>>> (sign, logdet)
(array([-1., -1., -1.]), array([ 0.69314718,  1.09861229,  2.07944154]))
>>> sign * np.exp(logdet)
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)<EOL>_assertNoEmpty2d(a)<EOL>_assertRankAtLeast2(a)<EOL>_assertNdSquareness(a)<EOL>t, result_t = _commonType(a)<EOL>signature = '<STR_LIT>' if isComplexType(t) else '<STR_LIT>'<EOL>return _umath_linalg.det(a, signature=signature).astype(result_t)<EOL>

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 representing the determinant, more suitable
  for large matrices where underflow/overflow may occur.

Notes
-----
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

Computing determinants for a stack of matrices:

>>> a = np.array([ [[1, 2], [3, 4]], [[1, 2], [2, 1]], [[1, 3], [3, 1]] ])
>>> a.shape
(2, 2, 2
>>> np.linalg.det(a)
array([-2., -3., -8.])


import math<EOL>a, _ = _makearray(a)<EOL>b, wrap = _makearray(b)<EOL>is_1d = len(b.shape) == <NUM_LIT:1><EOL>if is_1d:<EOL><INDENT>b = b[:, newaxis]<EOL><DEDENT>_assertRank2(a, b)<EOL>m  = a.shape[<NUM_LIT:0>]<EOL>n  = a.shape[<NUM_LIT:1>]<EOL>n_rhs = b.shape[<NUM_LIT:1>]<EOL>ldb = max(n, m)<EOL>if m != b.shape[<NUM_LIT:0>]:<EOL><INDENT>raise LinAlgError('<STR_LIT>')<EOL><DEDENT>t, result_t = _commonType(a, b)<EOL>result_real_t = _realType(result_t)<EOL>real_t = _linalgRealType(t)<EOL>bstar = zeros((ldb, n_rhs), t)<EOL>bstar[:b.shape[<NUM_LIT:0>], :n_rhs] = b.copy()<EOL>a, bstar = _fastCopyAndTranspose(t, a, bstar)<EOL>a, bstar = _to_native_byte_order(a, bstar)<EOL>s = zeros((min(m, n),), real_t)<EOL>nlvl = max( <NUM_LIT:0>, int( math.log( float(min(m, n))/<NUM_LIT> ) ) + <NUM_LIT:1> )<EOL>iwork = zeros((<NUM_LIT:3>*min(m, n)*nlvl+<NUM_LIT:11>*min(m, n),), fortran_int)<EOL>if isComplexType(t):<EOL><INDENT>lapack_routine = lapack_lite.zgelsd<EOL>lwork = <NUM_LIT:1><EOL>rwork = zeros((lwork,), real_t)<EOL>work = zeros((lwork,), t)<EOL>results = lapack_routine(m, n, n_rhs, a, m, bstar, ldb, s, rcond,<EOL><NUM_LIT:0>, work, -<NUM_LIT:1>, rwork, iwork, <NUM_LIT:0>)<EOL>lwork = int(abs(work[<NUM_LIT:0>]))<EOL>rwork = zeros((lwork,), real_t)<EOL>a_real = zeros((m, n), real_t)<EOL>bstar_real = zeros((ldb, n_rhs,), real_t)<EOL>results = lapack_lite.dgelsd(m, n, n_rhs, a_real, m,<EOL>bstar_real, ldb, s, rcond,<EOL><NUM_LIT:0>, rwork, -<NUM_LIT:1>, iwork, <NUM_LIT:0>)<EOL>lrwork = int(rwork[<NUM_LIT:0>])<EOL>work = zeros((lwork,), t)<EOL>rwork = zeros((lrwork,), real_t)<EOL>results = lapack_routine(m, n, n_rhs, a, m, bstar, ldb, s, rcond,<EOL><NUM_LIT:0>, work, lwork, rwork, iwork, <NUM_LIT:0>)<EOL><DEDENT>else:<EOL><INDENT>lapack_routine = lapack_lite.dgelsd<EOL>lwork = <NUM_LIT:1><EOL>work = zeros((lwork,), t)<EOL>results = lapack_routine(m, n, n_rhs, a, m, bstar, ldb, s, rcond,<EOL><NUM_LIT:0>, work, -<NUM_LIT:1>, iwork, <NUM_LIT:0>)<EOL>lwork = int(work[<NUM_LIT:0>])<EOL>work = zeros((lwork,), t)<EOL>results = lapack_routine(m, n, n_rhs, a, m, bstar, ldb, s, rcond,<EOL><NUM_LIT:0>, work, lwork, iwork, <NUM_LIT:0>)<EOL><DEDENT>if results['<STR_LIT:info>'] > <NUM_LIT:0>:<EOL><INDENT>raise LinAlgError('<STR_LIT>')<EOL><DEDENT>resids = array([], result_real_t)<EOL>if is_1d:<EOL><INDENT>x = array(ravel(bstar)[:n], dtype=result_t, copy=True)<EOL>if results['<STR_LIT>'] == n and m > n:<EOL><INDENT>if isComplexType(t):<EOL><INDENT>resids = array([sum(abs(ravel(bstar)[n:])**<NUM_LIT:2>)],<EOL>dtype=result_real_t)<EOL><DEDENT>else:<EOL><INDENT>resids = array([sum((ravel(bstar)[n:])**<NUM_LIT:2>)],<EOL>dtype=result_real_t)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>x = array(transpose(bstar)[:n,:], dtype=result_t, copy=True)<EOL>if results['<STR_LIT>'] == n and m > n:<EOL><INDENT>if isComplexType(t):<EOL><INDENT>resids = sum(abs(transpose(bstar)[n:,:])**<NUM_LIT:2>, axis=<NUM_LIT:0>).astype(<EOL>result_real_t)<EOL><DEDENT>else:<EOL><INDENT>resids = sum((transpose(bstar)[n:,:])**<NUM_LIT:2>, axis=<NUM_LIT:0>).astype(<EOL>result_real_t)<EOL><DEDENT><DEDENT><DEDENT>st = s[:min(n, m)].copy().astype(result_real_t)<EOL>return wrap(x), wrap(resids), results['<STR_LIT>'], st<EOL>

Return the least-squares solution to a linear matrix equation.

Solves the equation `a x = b` by computing a vector `x` that
minimizes the Euclidean 2-norm `|| b - a x ||^2`.  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.

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`.
    Singular values are set to zero if they are smaller than `rcond`
    times the largest singular value of `a`.

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,)} ndarray
    Sums of 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.

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)[0]
>>> print m, c
1.0 -0.95

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()


def _multi_svd_norm(x, row_axis, col_axis, op):

if row_axis > col_axis:<EOL><INDENT>row_axis -= <NUM_LIT:1><EOL><DEDENT>y = rollaxis(rollaxis(x, col_axis, x.ndim), row_axis, -<NUM_LIT:1>)<EOL>result = op(svd(y, compute_uv=<NUM_LIT:0>), axis=-<NUM_LIT:1>)<EOL>return result<EOL>

Compute the extreme 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.

    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 of the
        singular values of the matrices, depending on whether `op`
        is `numpy.amin` or `numpy.amax`.


x = asarray(x)<EOL>if ord is None and axis is None:<EOL><INDENT>x = x.ravel(order='<STR_LIT>')<EOL>if isComplexType(x.dtype.type):<EOL><INDENT>sqnorm = dot(x.real, x.real) + dot(x.imag, x.imag)<EOL><DEDENT>else:<EOL><INDENT>sqnorm = dot(x, x)<EOL><DEDENT>return sqrt(sqnorm)<EOL><DEDENT>nd = x.ndim<EOL>if axis is None:<EOL><INDENT>axis = tuple(range(nd))<EOL><DEDENT>elif not isinstance(axis, tuple):<EOL><INDENT>axis = (axis,)<EOL><DEDENT>if len(axis) == <NUM_LIT:1>:<EOL><INDENT>if ord == Inf:<EOL><INDENT>return abs(x).max(axis=axis)<EOL><DEDENT>elif ord == -Inf:<EOL><INDENT>return abs(x).min(axis=axis)<EOL><DEDENT>elif ord == <NUM_LIT:0>:<EOL><INDENT>return (x != <NUM_LIT:0>).sum(axis=axis)<EOL><DEDENT>elif ord == <NUM_LIT:1>:<EOL><INDENT>return add.reduce(abs(x), axis=axis)<EOL><DEDENT>elif ord is None or ord == <NUM_LIT:2>:<EOL><INDENT>s = (x.conj() * x).real<EOL>return sqrt(add.reduce(s, axis=axis))<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>ord + <NUM_LIT:1><EOL><DEDENT>except TypeError:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if x.dtype.type is longdouble:<EOL><INDENT>absx = abs(x)<EOL><DEDENT>else:<EOL><INDENT>absx = x if isComplexType(x.dtype.type) else asfarray(x)<EOL>if absx.dtype is x.dtype:<EOL><INDENT>absx = abs(absx)<EOL><DEDENT>else:<EOL><INDENT>abs(absx, out=absx)<EOL><DEDENT><DEDENT>absx **= ord<EOL>return add.reduce(absx, axis=axis) ** (<NUM_LIT:1.0> / ord)<EOL><DEDENT><DEDENT>elif len(axis) == <NUM_LIT:2>:<EOL><INDENT>row_axis, col_axis = axis<EOL>if not (-nd <= row_axis < nd and -nd <= col_axis < nd):<EOL><INDENT>raise ValueError('<STR_LIT>' %<EOL>(axis, x.shape))<EOL><DEDENT>if row_axis % nd == col_axis % nd:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if ord == <NUM_LIT:2>:<EOL><INDENT>return _multi_svd_norm(x, row_axis, col_axis, amax)<EOL><DEDENT>elif ord == -<NUM_LIT:2>:<EOL><INDENT>return _multi_svd_norm(x, row_axis, col_axis, amin)<EOL><DEDENT>elif ord == <NUM_LIT:1>:<EOL><INDENT>if col_axis > row_axis:<EOL><INDENT>col_axis -= <NUM_LIT:1><EOL><DEDENT>return add.reduce(abs(x), axis=row_axis).max(axis=col_axis)<EOL><DEDENT>elif ord == Inf:<EOL><INDENT>if row_axis > col_axis:<EOL><INDENT>row_axis -= <NUM_LIT:1><EOL><DEDENT>return add.reduce(abs(x), axis=col_axis).max(axis=row_axis)<EOL><DEDENT>elif ord == -<NUM_LIT:1>:<EOL><INDENT>if col_axis > row_axis:<EOL><INDENT>col_axis -= <NUM_LIT:1><EOL><DEDENT>return add.reduce(abs(x), axis=row_axis).min(axis=col_axis)<EOL><DEDENT>elif ord == -Inf:<EOL><INDENT>if row_axis > col_axis:<EOL><INDENT>row_axis -= <NUM_LIT:1><EOL><DEDENT>return add.reduce(abs(x), axis=col_axis).min(axis=row_axis)<EOL><DEDENT>elif ord in [None, '<STR_LIT>', '<STR_LIT:f>']:<EOL><INDENT>return sqrt(add.reduce((x.conj() * x).real, axis=axis))<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>

Matrix or vector norm.

This function is able to return one of seven 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.
ord : {non-zero int, inf, -inf, 'fro'}, optional
    Order of the norm (see table under ``Notes``). inf means numpy's
    `inf` object.
axis : {int, 2-tuple of ints, None}, 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.

Returns
-------
n : float or ndarray
    Norm of the matrix or vector(s).

Notes
-----
For values of ``ord <= 0``, 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                --
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}`

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, -1,  0,  1,  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
>>> LA.norm(b, np.inf)
9
>>> LA.norm(a, -np.inf)
0
>>> LA.norm(b, -np.inf)
2

>>> LA.norm(a, 1)
20
>>> LA.norm(b, 1)
7
>>> LA.norm(a, -1)
-4.6566128774142013e-010
>>> LA.norm(b, -1)
6
>>> LA.norm(a, 2)
7.745966692414834
>>> LA.norm(b, 2)
7.3484692283495345

>>> LA.norm(a, -2)
nan
>>> LA.norm(b, -2)
1.8570331885190563e-016
>>> LA.norm(a, 3)
5.8480354764257312
>>> LA.norm(a, -3)
nan

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)


if not isinstance(x, np.ndarray):<EOL><INDENT>yield x, "<STR_LIT>"<EOL>return<EOL><DEDENT>stride_set = [(<NUM_LIT:1>,)]*x.ndim<EOL>stride_set[-<NUM_LIT:1>] = (<NUM_LIT:1>, <NUM_LIT:3>, -<NUM_LIT:4>)<EOL>if x.ndim > <NUM_LIT:1>:<EOL><INDENT>stride_set[-<NUM_LIT:2>] = (<NUM_LIT:1>, <NUM_LIT:3>, -<NUM_LIT:4>)<EOL><DEDENT>if x.ndim > <NUM_LIT:2>:<EOL><INDENT>stride_set[-<NUM_LIT:3>] = (<NUM_LIT:1>, -<NUM_LIT:4>)<EOL><DEDENT>for repeats in itertools.product(*tuple(stride_set)):<EOL><INDENT>new_shape = [abs(a*b) for a, b in zip(x.shape, repeats)]<EOL>slices = tuple([slice(None, None, repeat) for repeat in repeats])<EOL>xi = np.empty(new_shape, dtype=x.dtype)<EOL>xi.view(np.uint32).fill(<NUM_LIT>)<EOL>xi = xi[slices]<EOL>xi[...] = x<EOL>xi = xi.view(x.__class__)<EOL>assert np.all(xi == x)<EOL>yield xi, "<STR_LIT>" + "<STR_LIT:_>".join(["<STR_LIT>" % j for j in repeats])<EOL>if x.ndim >= <NUM_LIT:1> and x.shape[-<NUM_LIT:1>] == <NUM_LIT:1>:<EOL><INDENT>s = list(x.strides)<EOL>s[-<NUM_LIT:1>] = <NUM_LIT:0><EOL>xi = np.lib.stride_tricks.as_strided(x, strides=s)<EOL>yield xi, "<STR_LIT>"<EOL><DEDENT>if x.ndim >= <NUM_LIT:2> and x.shape[-<NUM_LIT:2>] == <NUM_LIT:1>:<EOL><INDENT>s = list(x.strides)<EOL>s[-<NUM_LIT:2>] = <NUM_LIT:0><EOL>xi = np.lib.stride_tricks.as_strided(x, strides=s)<EOL>yield xi, "<STR_LIT>"<EOL><DEDENT>if x.ndim >= <NUM_LIT:2> and x.shape[:-<NUM_LIT:2>] == (<NUM_LIT:1>, <NUM_LIT:1>):<EOL><INDENT>s = list(x.strides)<EOL>s[-<NUM_LIT:1>] = <NUM_LIT:0><EOL>s[-<NUM_LIT:2>] = <NUM_LIT:0><EOL>xi = np.lib.stride_tricks.as_strided(x, strides=s)<EOL>yield xi, "<STR_LIT>"<EOL><DEDENT><DEDENT>

Generate cartesian product of strides for all axes


return isinstance(object, types.MethodType)<EOL>

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.FunctionType)<EOL>

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.CodeType)<EOL>

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


if not iscode(co):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>code = co.co_code<EOL>nargs = co.co_argcount<EOL>names = co.co_varnames<EOL>args = list(names[:nargs])<EOL>step = <NUM_LIT:0><EOL>for i in range(nargs):<EOL><INDENT>if args[i][:<NUM_LIT:1>] in ['<STR_LIT>', '<STR_LIT:.>']:<EOL><INDENT>stack, remain, count = [], [], []<EOL>while step < len(code):<EOL><INDENT>op = ord(code[step])<EOL>step = step + <NUM_LIT:1><EOL>if op >= dis.HAVE_ARGUMENT:<EOL><INDENT>opname = dis.opname[op]<EOL>value = ord(code[step]) + ord(code[step+<NUM_LIT:1>])*<NUM_LIT><EOL>step = step + <NUM_LIT:2><EOL>if opname in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>remain.append(value)<EOL>count.append(value)<EOL><DEDENT>elif opname == '<STR_LIT>':<EOL><INDENT>stack.append(names[value])<EOL>if not remain:<EOL><INDENT>stack[<NUM_LIT:0>] = [stack[<NUM_LIT:0>]]<EOL>break<EOL><DEDENT>else:<EOL><INDENT>remain[-<NUM_LIT:1>] = remain[-<NUM_LIT:1>] - <NUM_LIT:1><EOL>while remain[-<NUM_LIT:1>] == <NUM_LIT:0>:<EOL><INDENT>remain.pop()<EOL>size = count.pop()<EOL>stack[-size:] = [stack[-size:]]<EOL>if not remain: break<EOL>remain[-<NUM_LIT:1>] = remain[-<NUM_LIT:1>] - <NUM_LIT:1><EOL><DEDENT>if not remain: break<EOL><DEDENT><DEDENT><DEDENT><DEDENT>args[i] = stack[<NUM_LIT:0>]<EOL><DEDENT><DEDENT>varargs = None<EOL>if co.co_flags & CO_VARARGS:<EOL><INDENT>varargs = co.co_varnames[nargs]<EOL>nargs = nargs + <NUM_LIT:1><EOL><DEDENT>varkw = None<EOL>if co.co_flags & CO_VARKEYWORDS:<EOL><INDENT>varkw = co.co_varnames[nargs]<EOL><DEDENT>return args, varargs, varkw<EOL>

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 ismethod(func):<EOL><INDENT>func = func.__func__<EOL><DEDENT>if not isfunction(func):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>args, varargs, varkw = getargs(func.__code__)<EOL>return args, varargs, varkw, func.__defaults__<EOL>

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.


args, varargs, varkw = getargs(frame.f_code)<EOL>return args, varargs, varkw, frame.f_locals<EOL>

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.


def strseq(object, convert, join=joinseq):

if type(object) in [list, tuple]:<EOL><INDENT>return join([strseq(_o, convert, join) for _o in object])<EOL><DEDENT>else:<EOL><INDENT>return convert(object)<EOL><DEDENT>

Recursively walk a sequence, stringifying each element.


def formatargspec(args, varargs=None, varkw=None, defaults=None,<EOL>formatarg=str,<EOL>formatvarargs=lambda name: '<STR_LIT:*>' + name,<EOL>formatvarkw=lambda name: '<STR_LIT>' + name,<EOL>formatvalue=lambda value: '<STR_LIT:=>' + repr(value),<EOL>join=joinseq):

specs = []<EOL>if defaults:<EOL><INDENT>firstdefault = len(args) - len(defaults)<EOL><DEDENT>for i in range(len(args)):<EOL><INDENT>spec = strseq(args[i], formatarg, join)<EOL>if defaults and i >= firstdefault:<EOL><INDENT>spec = spec + formatvalue(defaults[i - firstdefault])<EOL><DEDENT>specs.append(spec)<EOL><DEDENT>if varargs is not None:<EOL><INDENT>specs.append(formatvarargs(varargs))<EOL><DEDENT>if varkw is not None:<EOL><INDENT>specs.append(formatvarkw(varkw))<EOL><DEDENT>return '<STR_LIT:(>' + '<STR_LIT:U+002CU+0020>'.join(specs) + '<STR_LIT:)>'<EOL>

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.


def formatargvalues(args, varargs, varkw, locals,<EOL>formatarg=str,<EOL>formatvarargs=lambda name: '<STR_LIT:*>' + name,<EOL>formatvarkw=lambda name: '<STR_LIT>' + name,<EOL>formatvalue=lambda value: '<STR_LIT:=>' + repr(value),<EOL>join=joinseq):

def convert(name, locals=locals,<EOL>formatarg=formatarg, formatvalue=formatvalue):<EOL><INDENT>return formatarg(name) + formatvalue(locals[name])<EOL><DEDENT>specs = []<EOL>for i in range(len(args)):<EOL><INDENT>specs.append(strseq(args[i], convert, join))<EOL><DEDENT>if varargs:<EOL><INDENT>specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))<EOL><DEDENT>if varkw:<EOL><INDENT>specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))<EOL><DEDENT>return '<STR_LIT:(>' + string.join(specs, '<STR_LIT:U+002CU+0020>') + '<STR_LIT:)>'<EOL>

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.


if isinstance(seq, (ndarray, tuple, list)):<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>

Is seq a sequence (ndarray, list or tuple)?


m = getmaskarray(arr)<EOL>return m.sum(axis)<EOL>

Count the number of masked elements along the given axis.

Parameters
----------
arr : array_like
    An array with (possibly) masked elements.
axis : int, optional
    Axis along which to count. If None (default), a flattened
    version of the array is used.

Returns
-------
count : int, ndarray
    The total number of masked elements (axis=None) or the number
    of masked elements along each slice of the given axis.

See Also
--------
MaskedArray.count : Count non-masked elements.

Examples
--------
>>> import numpy.ma as ma
>>> a = np.arange(9).reshape((3,3))
>>> a = ma.array(a)
>>> a[1, 0] = ma.masked
>>> a[1, 2] = ma.masked
>>> a[2, 1] = ma.masked
>>> a
masked_array(data =
 [[0 1 2]
 [-- 4 --]
 [6 -- 8]],
      mask =
 [[False False False]
 [ True False  True]
 [False  True False]],
      fill_value=999999)
>>> ma.count_masked(a)
3

When the `axis` keyword is used an array is returned.

>>> ma.count_masked(a, axis=0)
array([1, 1, 1])
>>> ma.count_masked(a, axis=1)
array([0, 2, 1])


a = masked_array(np.empty(shape, dtype),<EOL>mask=np.ones(shape, make_mask_descr(dtype)))<EOL>return a<EOL>

Empty masked array with all elements masked.

Return an empty masked array of the given shape and dtype, where all the
data are masked.

Parameters
----------
shape : tuple
    Shape of the required MaskedArray.
dtype : dtype, optional
    Data type of the output.

Returns
-------
a : MaskedArray
    A masked array with all data masked.

See Also
--------
masked_all_like : Empty masked array modelled on an existing array.

Examples
--------
>>> import numpy.ma as ma
>>> ma.masked_all((3, 3))
masked_array(data =
 [[-- -- --]
 [-- -- --]
 [-- -- --]],
      mask =
 [[ True  True  True]
 [ True  True  True]
 [ True  True  True]],
      fill_value=1e+20)

The `dtype` parameter defines the underlying data type.

>>> a = ma.masked_all((3, 3))
>>> a.dtype
dtype('float64')
>>> a = ma.masked_all((3, 3), dtype=np.int32)
>>> a.dtype
dtype('int32')


a = np.empty_like(arr).view(MaskedArray)<EOL>a._mask = np.ones(a.shape, dtype=make_mask_descr(a.dtype))<EOL>return a<EOL>

Empty masked array with the properties of an existing array.

Return an empty masked array of the same shape and dtype as
the array `arr`, where all the data are masked.

Parameters
----------
arr : ndarray
    An array describing the shape and dtype of the required MaskedArray.

Returns
-------
a : MaskedArray
    A masked array with all data masked.

Raises
------
AttributeError
    If `arr` doesn't have a shape attribute (i.e. not an ndarray)

See Also
--------
masked_all : Empty masked array with all elements masked.

Examples
--------
>>> import numpy.ma as ma
>>> arr = np.zeros((2, 3), dtype=np.float32)
>>> arr
array([[ 0.,  0.,  0.],
       [ 0.,  0.,  0.]], dtype=float32)
>>> ma.masked_all_like(arr)
masked_array(data =
 [[-- -- --]
 [-- -- --]],
      mask =
 [[ True  True  True]
 [ True  True  True]],
      fill_value=1e+20)

The dtype of the masked array matches the dtype of `arr`.

>>> arr.dtype
dtype('float32')
>>> ma.masked_all_like(arr).dtype
dtype('float32')


k = <NUM_LIT:0><EOL>while (k != len(seq)):<EOL><INDENT>while hasattr(seq[k], '<STR_LIT>'):<EOL><INDENT>seq[k:(k + <NUM_LIT:1>)] = seq[k]<EOL><DEDENT>k += <NUM_LIT:1><EOL><DEDENT>return seq<EOL>


def apply_along_axis(func1d, axis, arr, *args, **kwargs):

arr = array(arr, copy=False, subok=True)<EOL>nd = arr.ndim<EOL>if axis < <NUM_LIT:0>:<EOL><INDENT>axis += nd<EOL><DEDENT>if (axis >= nd):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>% (axis, nd))<EOL><DEDENT>ind = [<NUM_LIT:0>] * (nd - <NUM_LIT:1>)<EOL>i = np.zeros(nd, '<STR_LIT:O>')<EOL>indlist = list(range(nd))<EOL>indlist.remove(axis)<EOL>i[axis] = slice(None, None)<EOL>outshape = np.asarray(arr.shape).take(indlist)<EOL>i.put(indlist, ind)<EOL>j = i.copy()<EOL>res = func1d(arr[tuple(i.tolist())], *args, **kwargs)<EOL>asscalar = np.isscalar(res)<EOL>if not asscalar:<EOL><INDENT>try:<EOL><INDENT>len(res)<EOL><DEDENT>except TypeError:<EOL><INDENT>asscalar = True<EOL><DEDENT><DEDENT>dtypes = []<EOL>if asscalar:<EOL><INDENT>dtypes.append(np.asarray(res).dtype)<EOL>outarr = zeros(outshape, object)<EOL>outarr[tuple(ind)] = res<EOL>Ntot = np.product(outshape)<EOL>k = <NUM_LIT:1><EOL>while k < Ntot:<EOL><INDENT>ind[-<NUM_LIT:1>] += <NUM_LIT:1><EOL>n = -<NUM_LIT:1><EOL>while (ind[n] >= outshape[n]) and (n > (<NUM_LIT:1> - nd)):<EOL><INDENT>ind[n - <NUM_LIT:1>] += <NUM_LIT:1><EOL>ind[n] = <NUM_LIT:0><EOL>n -= <NUM_LIT:1><EOL><DEDENT>i.put(indlist, ind)<EOL>res = func1d(arr[tuple(i.tolist())], *args, **kwargs)<EOL>outarr[tuple(ind)] = res<EOL>dtypes.append(asarray(res).dtype)<EOL>k += <NUM_LIT:1><EOL><DEDENT><DEDENT>else:<EOL><INDENT>res = array(res, copy=False, subok=True)<EOL>j = i.copy()<EOL>j[axis] = ([slice(None, None)] * res.ndim)<EOL>j.put(indlist, ind)<EOL>Ntot = np.product(outshape)<EOL>holdshape = outshape<EOL>outshape = list(arr.shape)<EOL>outshape[axis] = res.shape<EOL>dtypes.append(asarray(res).dtype)<EOL>outshape = flatten_inplace(outshape)<EOL>outarr = zeros(outshape, object)<EOL>outarr[tuple(flatten_inplace(j.tolist()))] = res<EOL>k = <NUM_LIT:1><EOL>while k < Ntot:<EOL><INDENT>ind[-<NUM_LIT:1>] += <NUM_LIT:1><EOL>n = -<NUM_LIT:1><EOL>while (ind[n] >= holdshape[n]) and (n > (<NUM_LIT:1> - nd)):<EOL><INDENT>ind[n - <NUM_LIT:1>] += <NUM_LIT:1><EOL>ind[n] = <NUM_LIT:0><EOL>n -= <NUM_LIT:1><EOL><DEDENT>i.put(indlist, ind)<EOL>j.put(indlist, ind)<EOL>res = func1d(arr[tuple(i.tolist())], *args, **kwargs)<EOL>outarr[tuple(flatten_inplace(j.tolist()))] = res<EOL>dtypes.append(asarray(res).dtype)<EOL>k += <NUM_LIT:1><EOL><DEDENT><DEDENT>max_dtypes = np.dtype(np.asarray(dtypes).max())<EOL>if not hasattr(arr, '<STR_LIT>'):<EOL><INDENT>result = np.asarray(outarr, dtype=max_dtypes)<EOL><DEDENT>else:<EOL><INDENT>result = asarray(outarr, dtype=max_dtypes)<EOL>result.fill_value = ma.default_fill_value(result)<EOL><DEDENT>return result<EOL>


val = asarray(a)<EOL>N = a.ndim<EOL>if array(axes).ndim == <NUM_LIT:0>:<EOL><INDENT>axes = (axes,)<EOL><DEDENT>for axis in axes:<EOL><INDENT>if axis < <NUM_LIT:0>: axis = N + axis<EOL>args = (val, axis)<EOL>res = func(*args)<EOL>if res.ndim == val.ndim:<EOL><INDENT>val = res<EOL><DEDENT>else:<EOL><INDENT>res = ma.expand_dims(res, axis)<EOL>if res.ndim == val.ndim:<EOL><INDENT>val = res<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT><DEDENT>return val<EOL>


def average(a, axis=None, weights=None, returned=False):

a = asarray(a)<EOL>mask = a.mask<EOL>ash = a.shape<EOL>if ash == ():<EOL><INDENT>ash = (<NUM_LIT:1>,)<EOL><DEDENT>if axis is None:<EOL><INDENT>if mask is nomask:<EOL><INDENT>if weights is None:<EOL><INDENT>n = a.sum(axis=None)<EOL>d = float(a.size)<EOL><DEDENT>else:<EOL><INDENT>w = filled(weights, <NUM_LIT:0.0>).ravel()<EOL>n = umath.add.reduce(a._data.ravel() * w)<EOL>d = umath.add.reduce(w)<EOL>del w<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if weights is None:<EOL><INDENT>n = a.filled(<NUM_LIT:0>).sum(axis=None)<EOL>d = float(umath.add.reduce((~mask).ravel()))<EOL><DEDENT>else:<EOL><INDENT>w = array(filled(weights, <NUM_LIT:0.0>), float, mask=mask).ravel()<EOL>n = add.reduce(a.ravel() * w)<EOL>d = add.reduce(w)<EOL>del w<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>if mask is nomask:<EOL><INDENT>if weights is None:<EOL><INDENT>d = ash[axis] * <NUM_LIT:1.0><EOL>n = add.reduce(a._data, axis)<EOL><DEDENT>else:<EOL><INDENT>w = filled(weights, <NUM_LIT:0.0>)<EOL>wsh = w.shape<EOL>if wsh == ():<EOL><INDENT>wsh = (<NUM_LIT:1>,)<EOL><DEDENT>if wsh == ash:<EOL><INDENT>w = np.array(w, float, copy=<NUM_LIT:0>)<EOL>n = add.reduce(a * w, axis)<EOL>d = add.reduce(w, axis)<EOL>del w<EOL><DEDENT>elif wsh == (ash[axis],):<EOL><INDENT>ni = ash[axis]<EOL>r = [None] * len(ash)<EOL>r[axis] = slice(None, None, <NUM_LIT:1>)<EOL>w = eval ("<STR_LIT>" + repr(tuple(r)) + "<STR_LIT>")<EOL>n = add.reduce(a * w, axis)<EOL>d = add.reduce(w, axis, dtype=float)<EOL>del w, r<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>if weights is None:<EOL><INDENT>n = add.reduce(a, axis)<EOL>d = umath.add.reduce((~mask), axis=axis, dtype=float)<EOL><DEDENT>else:<EOL><INDENT>w = filled(weights, <NUM_LIT:0.0>)<EOL>wsh = w.shape<EOL>if wsh == ():<EOL><INDENT>wsh = (<NUM_LIT:1>,)<EOL><DEDENT>if wsh == ash:<EOL><INDENT>w = array(w, dtype=float, mask=mask, copy=<NUM_LIT:0>)<EOL>n = add.reduce(a * w, axis)<EOL>d = add.reduce(w, axis, dtype=float)<EOL><DEDENT>elif wsh == (ash[axis],):<EOL><INDENT>ni = ash[axis]<EOL>r = [None] * len(ash)<EOL>r[axis] = slice(None, None, <NUM_LIT:1>)<EOL>w = eval ("<STR_LIT>" + repr(tuple(r)) +"<STR_LIT>")<EOL>n = add.reduce(a * w, axis)<EOL>d = add.reduce(w, axis, dtype=float)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>del w<EOL><DEDENT><DEDENT><DEDENT>if n is masked or d is masked:<EOL><INDENT>return masked<EOL><DEDENT>result = n / d<EOL>del n<EOL>if isinstance(result, MaskedArray):<EOL><INDENT>if ((axis is None) or (axis == <NUM_LIT:0> and a.ndim == <NUM_LIT:1>)) and(result.mask is nomask):<EOL><INDENT>result = result._data<EOL><DEDENT>if returned:<EOL><INDENT>if not isinstance(d, MaskedArray):<EOL><INDENT>d = masked_array(d)<EOL><DEDENT>if isinstance(d, ndarray) and (not d.shape == result.shape):<EOL><INDENT>d = ones(result.shape, dtype=float) * d<EOL><DEDENT><DEDENT><DEDENT>if returned:<EOL><INDENT>return result, d<EOL><DEDENT>else:<EOL><INDENT>return result<EOL><DEDENT>

Return the weighted average of array over the given axis.

Parameters
----------
a : array_like
    Data to be averaged.
    Masked entries are not taken into account in the computation.
axis : int, optional
    Axis along which the average is computed. The default is to compute
    the average of the flattened array.
weights : array_like, optional
    The importance that each element has in the computation of the average.
    The weights array can either be 1-D (in which case its length must be
    the size of `a` along the given axis) or of the same shape as `a`.
    If ``weights=None``, then all data in `a` are assumed to have a
    weight equal to one.   If `weights` is complex, the imaginary parts
    are ignored.
returned : bool, optional
    Flag indicating whether a tuple ``(result, sum of weights)``
    should be returned as output (True), or just the result (False).
    Default is False.

Returns
-------
average, [sum_of_weights] : (tuple of) scalar or MaskedArray
    The average along the specified axis. When returned is `True`,
    return a tuple with the average as the first element and the sum
    of the weights as the second element. The return type is `np.float64`
    if `a` is of integer type, otherwise it is of the same type as `a`.
    If returned, `sum_of_weights` is of the same type as `average`.

Examples
--------
>>> a = np.ma.array([1., 2., 3., 4.], mask=[False, False, True, True])
>>> np.ma.average(a, weights=[3, 1, 0, 0])
1.25

>>> x = np.ma.arange(6.).reshape(3, 2)
>>> print x
[[ 0.  1.]
 [ 2.  3.]
 [ 4.  5.]]
>>> avg, sumweights = np.ma.average(x, axis=0, weights=[1, 2, 3],
...                                 returned=True)
>>> print avg
[2.66666666667 3.66666666667]


def median(a, axis=None, out=None, overwrite_input=False):

if not hasattr(a, '<STR_LIT>') or np.count_nonzero(a.mask) == <NUM_LIT:0>:<EOL><INDENT>return masked_array(np.median(getdata(a, subok=True), axis=axis,<EOL>out=out, overwrite_input=overwrite_input), copy=False)<EOL><DEDENT>if overwrite_input:<EOL><INDENT>if axis is None:<EOL><INDENT>asorted = a.ravel()<EOL>asorted.sort()<EOL><DEDENT>else:<EOL><INDENT>a.sort(axis=axis)<EOL>asorted = a<EOL><DEDENT><DEDENT>else:<EOL><INDENT>asorted = sort(a, axis=axis)<EOL><DEDENT>if axis is None:<EOL><INDENT>axis = <NUM_LIT:0><EOL><DEDENT>elif axis < <NUM_LIT:0>:<EOL><INDENT>axis += a.ndim<EOL><DEDENT>counts = asorted.shape[axis] - (asorted.mask).sum(axis=axis)<EOL>h = counts // <NUM_LIT:2><EOL>axes_grid = [np.arange(x) for i, x in enumerate(asorted.shape)<EOL>if i != axis]<EOL>ind = np.meshgrid(*axes_grid, sparse=True, indexing='<STR_LIT>')<EOL>ind.insert(axis, h - <NUM_LIT:1>)<EOL>low = asorted[ind]<EOL>ind[axis] = h<EOL>high = asorted[ind]<EOL>odd = counts % <NUM_LIT:2> == <NUM_LIT:1><EOL>if asorted.ndim == <NUM_LIT:1>:<EOL><INDENT>if odd:<EOL><INDENT>low = high<EOL><DEDENT><DEDENT>else:<EOL><INDENT>low[odd] = high[odd]<EOL><DEDENT>if np.issubdtype(asorted.dtype, np.inexact):<EOL><INDENT>s = np.ma.sum([low, high], axis=<NUM_LIT:0>, out=out)<EOL>np.true_divide(s.data, <NUM_LIT>, casting='<STR_LIT>', out=s.data)<EOL><DEDENT>else:<EOL><INDENT>s = np.ma.mean([low, high], axis=<NUM_LIT:0>, out=out)<EOL><DEDENT>return s<EOL>

Compute the median along the specified axis.

Returns the median of the array elements.

Parameters
----------
a : array_like
    Input array or object that can be converted to an array.
axis : int, optional
    Axis along which the medians are computed. The default (None) is
    to compute the median along a flattened version of the array.
out : ndarray, 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.
overwrite_input : bool, optional
    If True, then allow use of memory of input array (a) for
    calculations. The input array will be modified by the call to
    median. This will save memory when you do not need to preserve
    the contents of the input array. Treat the input as undefined,
    but it will probably be fully or partially sorted. Default is
    False. Note that, if `overwrite_input` is True, and the input
    is not already an `ndarray`, an error will be raised.

Returns
-------
median : ndarray
    A new array holding the result is returned unless out is
    specified, in which case a reference to out is returned.
    Return data-type is `float64` for integers and floats smaller than
    `float64`, or the input data-type, otherwise.

See Also
--------
mean

Notes
-----
Given a vector ``V`` with ``N`` non masked values, the median of ``V``
is the middle value of a sorted copy of ``V`` (``Vs``) - i.e.
``Vs[(N-1)/2]``, when ``N`` is odd, or ``{Vs[N/2 - 1] + Vs[N/2]}/2``
when ``N`` is even.

Examples
--------
>>> x = np.ma.array(np.arange(8), mask=[0]*4 + [1]*4)
>>> np.ma.extras.median(x)
1.5

>>> x = np.ma.array(np.arange(10).reshape(2, 5), mask=[0]*6 + [1]*4)
>>> np.ma.extras.median(x)
2.5
>>> np.ma.extras.median(x, axis=-1, overwrite_input=True)
masked_array(data = [ 2.  5.],
             mask = False,
       fill_value = 1e+20)


x = asarray(x)<EOL>if x.ndim != <NUM_LIT:2>:<EOL><INDENT>raise NotImplementedError("<STR_LIT>")<EOL><DEDENT>m = getmask(x)<EOL>if m is nomask or not m.any():<EOL><INDENT>return x._data<EOL><DEDENT>if m.all():<EOL><INDENT>return nxarray([])<EOL><DEDENT>(idxr, idxc) = (list(range(len(x))), list(range(x.shape[<NUM_LIT:1>])))<EOL>masked = m.nonzero()<EOL>if not axis:<EOL><INDENT>for i in np.unique(masked[<NUM_LIT:0>]):<EOL><INDENT>idxr.remove(i)<EOL><DEDENT><DEDENT>if axis in [None, <NUM_LIT:1>, -<NUM_LIT:1>]:<EOL><INDENT>for j in np.unique(masked[<NUM_LIT:1>]):<EOL><INDENT>idxc.remove(j)<EOL><DEDENT><DEDENT>return x._data[idxr][:, idxc]<EOL>

Suppress the rows and/or columns of a 2-D array that contain
masked values.

The suppression behavior is selected with the `axis` parameter.

- If axis is None, both rows and columns are suppressed.
- If axis is 0, only rows are suppressed.
- If axis is 1 or -1, only columns are suppressed.

Parameters
----------
axis : int, optional
    Axis along which to perform the operation. Default is None.

Returns
-------
compressed_array : ndarray
    The compressed array.

Examples
--------
>>> x = np.ma.array(np.arange(9).reshape(3, 3), mask=[[1, 0, 0],
...                                                   [1, 0, 0],
...                                                   [0, 0, 0]])
>>> x
masked_array(data =
 [[-- 1 2]
 [-- 4 5]
 [6 7 8]],
             mask =
 [[ True False False]
 [ True False False]
 [False False False]],
       fill_value = 999999)

>>> np.ma.extras.compress_rowcols(x)
array([[7, 8]])
>>> np.ma.extras.compress_rowcols(x, 0)
array([[6, 7, 8]])
>>> np.ma.extras.compress_rowcols(x, 1)
array([[1, 2],
       [4, 5],
       [7, 8]])


return compress_rowcols(a, <NUM_LIT:0>)<EOL>

Suppress whole rows of a 2-D array that contain masked values.

This is equivalent to ``np.ma.extras.compress_rowcols(a, 0)``, see
`extras.compress_rowcols` for details.

See Also
--------
extras.compress_rowcols


return compress_rowcols(a, <NUM_LIT:1>)<EOL>

Suppress whole columns of a 2-D array that contain masked values.

This is equivalent to ``np.ma.extras.compress_rowcols(a, 1)``, see
`extras.compress_rowcols` for details.

See Also
--------
extras.compress_rowcols


a = array(a, subok=False)<EOL>if a.ndim != <NUM_LIT:2>:<EOL><INDENT>raise NotImplementedError("<STR_LIT>")<EOL><DEDENT>m = getmask(a)<EOL>if m is nomask or not m.any():<EOL><INDENT>return a<EOL><DEDENT>maskedval = m.nonzero()<EOL>a._mask = a._mask.copy()<EOL>if not axis:<EOL><INDENT>a[np.unique(maskedval[<NUM_LIT:0>])] = masked<EOL><DEDENT>if axis in [None, <NUM_LIT:1>, -<NUM_LIT:1>]:<EOL><INDENT>a[:, np.unique(maskedval[<NUM_LIT:1>])] = masked<EOL><DEDENT>return a<EOL>

Mask rows and/or columns of a 2D array that contain masked values.

Mask whole rows and/or columns of a 2D array that contain
masked values.  The masking behavior is selected using the
`axis` parameter.

  - If `axis` is None, rows *and* columns are masked.
  - If `axis` is 0, only rows are masked.
  - If `axis` is 1 or -1, only columns are masked.

Parameters
----------
a : array_like, MaskedArray
    The array to mask.  If not a MaskedArray instance (or if no array
    elements are masked).  The result is a MaskedArray with `mask` set
    to `nomask` (False). Must be a 2D array.
axis : int, optional
    Axis along which to perform the operation. If None, applies to a
    flattened version of the array.

Returns
-------
a : MaskedArray
    A modified version of the input array, masked depending on the value
    of the `axis` parameter.

Raises
------
NotImplementedError
    If input array `a` is not 2D.

See Also
--------
mask_rows : Mask rows of a 2D array that contain masked values.
mask_cols : Mask cols of a 2D array that contain masked values.
masked_where : Mask where a condition is met.

Notes
-----
The input array's mask is modified by this function.

Examples
--------
>>> import numpy.ma as ma
>>> a = np.zeros((3, 3), dtype=np.int)
>>> a[1, 1] = 1
>>> a
array([[0, 0, 0],
       [0, 1, 0],
       [0, 0, 0]])
>>> a = ma.masked_equal(a, 1)
>>> a
masked_array(data =
 [[0 0 0]
 [0 -- 0]
 [0 0 0]],
      mask =
 [[False False False]
 [False  True False]
 [False False False]],
      fill_value=999999)
>>> ma.mask_rowcols(a)
masked_array(data =
 [[0 -- 0]
 [-- -- --]
 [0 -- 0]],
      mask =
 [[False  True False]
 [ True  True  True]
 [False  True False]],
      fill_value=999999)


return mask_rowcols(a, <NUM_LIT:0>)<EOL>

Mask rows of a 2D array that contain masked values.

This function is a shortcut to ``mask_rowcols`` with `axis` equal to 0.

See Also
--------
mask_rowcols : Mask rows and/or columns of a 2D array.
masked_where : Mask where a condition is met.

Examples
--------
>>> import numpy.ma as ma
>>> a = np.zeros((3, 3), dtype=np.int)
>>> a[1, 1] = 1
>>> a
array([[0, 0, 0],
       [0, 1, 0],
       [0, 0, 0]])
>>> a = ma.masked_equal(a, 1)
>>> a
masked_array(data =
 [[0 0 0]
 [0 -- 0]
 [0 0 0]],
      mask =
 [[False False False]
 [False  True False]
 [False False False]],
      fill_value=999999)
>>> ma.mask_rows(a)
masked_array(data =
 [[0 0 0]
 [-- -- --]
 [0 0 0]],
      mask =
 [[False False False]
 [ True  True  True]
 [False False False]],
      fill_value=999999)


return mask_rowcols(a, <NUM_LIT:1>)<EOL>

Mask columns of a 2D array that contain masked values.

This function is a shortcut to ``mask_rowcols`` with `axis` equal to 1.

See Also
--------
mask_rowcols : Mask rows and/or columns of a 2D array.
masked_where : Mask where a condition is met.

Examples
--------
>>> import numpy.ma as ma
>>> a = np.zeros((3, 3), dtype=np.int)
>>> a[1, 1] = 1
>>> a
array([[0, 0, 0],
       [0, 1, 0],
       [0, 0, 0]])
>>> a = ma.masked_equal(a, 1)
>>> a
masked_array(data =
 [[0 0 0]
 [0 -- 0]
 [0 0 0]],
      mask =
 [[False False False]
 [False  True False]
 [False False False]],
      fill_value=999999)
>>> ma.mask_cols(a)
masked_array(data =
 [[0 -- 0]
 [0 -- 0]
 [0 -- 0]],
      mask =
 [[False  True False]
 [False  True False]
 [False  True False]],
      fill_value=999999)


<EOL>if strict and (a.ndim == <NUM_LIT:2>) and (b.ndim == <NUM_LIT:2>):<EOL><INDENT>a = mask_rows(a)<EOL>b = mask_cols(b)<EOL><DEDENT>d = np.dot(filled(a, <NUM_LIT:0>), filled(b, <NUM_LIT:0>))<EOL>am = (~getmaskarray(a))<EOL>bm = (~getmaskarray(b))<EOL>m = ~np.dot(am, bm)<EOL>return masked_array(d, mask=m)<EOL>

Return the dot product of two arrays.

.. note::
  Works only with 2-D arrays at the moment.

This function is the equivalent of `numpy.dot` that takes masked values
into account, see `numpy.dot` for details.

Parameters
----------
a, b : ndarray
    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.

See Also
--------
numpy.dot : Equivalent function for ndarrays.

Examples
--------
>>> a = ma.array([[1, 2, 3], [4, 5, 6]], mask=[[1, 0, 0], [0, 0, 0]])
>>> b = 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)


def ediff1d(arr, to_end=None, to_begin=None):

arr = ma.asanyarray(arr).flat<EOL>ed = arr[<NUM_LIT:1>:] - arr[:-<NUM_LIT:1>]<EOL>arrays = [ed]<EOL>if to_begin is not None:<EOL><INDENT>arrays.insert(<NUM_LIT:0>, to_begin)<EOL><DEDENT>if to_end is not None:<EOL><INDENT>arrays.append(to_end)<EOL><DEDENT>if len(arrays) != <NUM_LIT:1>:<EOL><INDENT>ed = hstack(arrays)<EOL><DEDENT>return ed<EOL>

Compute the differences between consecutive elements of an array.

This function is the equivalent of `numpy.ediff1d` that takes masked
values into account, see `numpy.ediff1d` for details.

See Also
--------
numpy.ediff1d : Equivalent function for ndarrays.


def unique(ar1, return_index=False, return_inverse=False):

output = np.unique(ar1,<EOL>return_index=return_index,<EOL>return_inverse=return_inverse)<EOL>if isinstance(output, tuple):<EOL><INDENT>output = list(output)<EOL>output[<NUM_LIT:0>] = output[<NUM_LIT:0>].view(MaskedArray)<EOL>output = tuple(output)<EOL><DEDENT>else:<EOL><INDENT>output = output.view(MaskedArray)<EOL><DEDENT>return output<EOL>

Finds the unique elements of an array.

Masked values are considered the same element (masked). The output array
is always a masked array. See `numpy.unique` for more details.

See Also
--------
numpy.unique : Equivalent function for ndarrays.


def intersect1d(ar1, ar2, assume_unique=False):

if assume_unique:<EOL><INDENT>aux = ma.concatenate((ar1, ar2))<EOL><DEDENT>else:<EOL><INDENT>aux = ma.concatenate((unique(ar1), unique(ar2)))<EOL><DEDENT>aux.sort()<EOL>return aux[:-<NUM_LIT:1>][aux[<NUM_LIT:1>:] == aux[:-<NUM_LIT:1>]]<EOL>

Returns the unique elements common to both arrays.

Masked values are considered equal one to the other.
The output is always a masked array.

See `numpy.intersect1d` for more details.

See Also
--------
numpy.intersect1d : Equivalent function for ndarrays.

Examples
--------
>>> x = array([1, 3, 3, 3], mask=[0, 0, 0, 1])
>>> y = array([3, 1, 1, 1], mask=[0, 0, 0, 1])
>>> intersect1d(x, y)
masked_array(data = [1 3 --],
             mask = [False False  True],
       fill_value = 999999)


def setxor1d(ar1, ar2, assume_unique=False):

if not assume_unique:<EOL><INDENT>ar1 = unique(ar1)<EOL>ar2 = unique(ar2)<EOL><DEDENT>aux = ma.concatenate((ar1, ar2))<EOL>if aux.size == <NUM_LIT:0>:<EOL><INDENT>return aux<EOL><DEDENT>aux.sort()<EOL>auxf = aux.filled()<EOL><INDENT>flag = ediff1d( aux, to_end = <NUM_LIT:1>, to_begin = <NUM_LIT:1> ) == <NUM_LIT:0><EOL><DEDENT>flag = ma.concatenate(([True], (auxf[<NUM_LIT:1>:] != auxf[:-<NUM_LIT:1>]), [True]))<EOL><INDENT>flag2 = ediff1d( flag ) == <NUM_LIT:0><EOL><DEDENT>flag2 = (flag[<NUM_LIT:1>:] == flag[:-<NUM_LIT:1>])<EOL>return aux[flag2]<EOL>

Set exclusive-or of 1-D arrays with unique elements.

The output is always a masked array. See `numpy.setxor1d` for more details.

See Also
--------
numpy.setxor1d : Equivalent function for ndarrays.


def in1d(ar1, ar2, assume_unique=False, invert=False):

if not assume_unique:<EOL><INDENT>ar1, rev_idx = unique(ar1, return_inverse=True)<EOL>ar2 = unique(ar2)<EOL><DEDENT>ar = ma.concatenate((ar1, ar2))<EOL>order = ar.argsort(kind='<STR_LIT>')<EOL>sar = ar[order]<EOL>if invert:<EOL><INDENT>bool_ar = (sar[<NUM_LIT:1>:] != sar[:-<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>bool_ar = (sar[<NUM_LIT:1>:] == sar[:-<NUM_LIT:1>])<EOL><DEDENT>flag = ma.concatenate((bool_ar, [invert]))<EOL>indx = order.argsort(kind='<STR_LIT>')[:len(ar1)]<EOL>if assume_unique:<EOL><INDENT>return flag[indx]<EOL><DEDENT>else:<EOL><INDENT>return flag[indx][rev_idx]<EOL><DEDENT>

Test whether each element of an array is also present in a second
array.

The output is always a masked array. See `numpy.in1d` for more details.

See Also
--------
numpy.in1d : Equivalent function for ndarrays.

Notes
-----
.. versionadded:: 1.4.0


return unique(ma.concatenate((ar1, ar2)))<EOL>

Union of two arrays.

The output is always a masked array. See `numpy.union1d` for more details.

See also
--------
numpy.union1d : Equivalent function for ndarrays.


def setdiff1d(ar1, ar2, assume_unique=False):

if not assume_unique:<EOL><INDENT>ar1 = unique(ar1)<EOL>ar2 = unique(ar2)<EOL><DEDENT>aux = in1d(ar1, ar2, assume_unique=True)<EOL>if aux.size == <NUM_LIT:0>:<EOL><INDENT>return aux<EOL><DEDENT>else:<EOL><INDENT>return ma.asarray(ar1)[aux == <NUM_LIT:0>]<EOL><DEDENT>

Set difference of 1D arrays with unique elements.

The output is always a masked array. See `numpy.setdiff1d` for more
details.

See Also
--------
numpy.setdiff1d : Equivalent function for ndarrays.

Examples
--------
>>> x = np.ma.array([1, 2, 3, 4], mask=[0, 1, 0, 1])
>>> np.ma.extras.setdiff1d(x, [1, 2])
masked_array(data = [3 --],
             mask = [False  True],
       fill_value = 999999)


def _covhelper(x, y=None, rowvar=True, allow_masked=True):

x = ma.array(x, ndmin=<NUM_LIT:2>, copy=True, dtype=float)<EOL>xmask = ma.getmaskarray(x)<EOL>if not allow_masked and xmask.any():<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if x.shape[<NUM_LIT:0>] == <NUM_LIT:1>:<EOL><INDENT>rowvar = True<EOL><DEDENT>rowvar = int(bool(rowvar))<EOL>axis = <NUM_LIT:1> - rowvar<EOL>if rowvar:<EOL><INDENT>tup = (slice(None), None)<EOL><DEDENT>else:<EOL><INDENT>tup = (None, slice(None))<EOL><DEDENT>if y is None:<EOL><INDENT>xnotmask = np.logical_not(xmask).astype(int)<EOL><DEDENT>else:<EOL><INDENT>y = array(y, copy=False, ndmin=<NUM_LIT:2>, dtype=float)<EOL>ymask = ma.getmaskarray(y)<EOL>if not allow_masked and ymask.any():<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if xmask.any() or ymask.any():<EOL><INDENT>if y.shape == x.shape:<EOL><INDENT>common_mask = np.logical_or(xmask, ymask)<EOL>if common_mask is not nomask:<EOL><INDENT>x.unshare_mask()<EOL>y.unshare_mask()<EOL>xmask = x._mask = y._mask = ymask = common_mask<EOL><DEDENT><DEDENT><DEDENT>x = ma.concatenate((x, y), axis)<EOL>xnotmask = np.logical_not(np.concatenate((xmask, ymask), axis)).astype(int)<EOL><DEDENT>x -= x.mean(axis=rowvar)[tup]<EOL>return (x, xnotmask, rowvar)<EOL>

Private function for the computation of covariance and correlation
coefficients.


def cov(x, y=None, rowvar=True, bias=False, allow_masked=True, ddof=None):

<EOL>if ddof is not None and ddof != int(ddof):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if ddof is None:<EOL><INDENT>if bias:<EOL><INDENT>ddof = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>ddof = <NUM_LIT:1><EOL><DEDENT><DEDENT>(x, xnotmask, rowvar) = _covhelper(x, y, rowvar, allow_masked)<EOL>if not rowvar:<EOL><INDENT>fact = np.dot(xnotmask.T, xnotmask) * <NUM_LIT:1.> - ddof<EOL>result = (dot(x.T, x.conj(), strict=False) / fact).squeeze()<EOL><DEDENT>else:<EOL><INDENT>fact = np.dot(xnotmask, xnotmask.T) * <NUM_LIT:1.> - ddof<EOL>result = (dot(x, x.T.conj(), strict=False) / fact).squeeze()<EOL><DEDENT>return result<EOL>

Estimate the covariance matrix.

Except for the handling of missing data this function does the same as
`numpy.cov`. For more details and examples, see `numpy.cov`.

By default, masked values are recognized as such. If `x` and `y` have the
same shape, a common mask is allocated: if ``x[i,j]`` is masked, then
``y[i,j]`` will also be masked.
Setting `allow_masked` to False will raise an exception if values are
missing in either of the input arrays.

Parameters
----------
x : array_like
    A 1-D or 2-D array containing multiple variables and observations.
    Each row of `x` represents a variable, and each column a single
    observation of all those variables. Also see `rowvar` below.
y : array_like, optional
    An additional set of variables and observations. `y` has the same
    form as `x`.
rowvar : bool, optional
    If `rowvar` is True (default), then each row represents a
    variable, with observations in the columns. Otherwise, the relationship
    is transposed: each column represents a variable, while the rows
    contain observations.
bias : bool, optional
    Default normalization (False) is by ``(N-1)``, where ``N`` is the
    number of observations given (unbiased estimate). If `bias` is True,
    then normalization is by ``N``. This keyword can be overridden by
    the keyword ``ddof`` in numpy versions >= 1.5.
allow_masked : bool, optional
    If True, masked values are propagated pair-wise: if a value is masked
    in `x`, the corresponding value is masked in `y`.
    If False, raises a `ValueError` exception when some values are missing.
ddof : {None, int}, optional
    .. versionadded:: 1.5
    If not ``None`` normalization is by ``(N - ddof)``, where ``N`` is
    the number of observations; this overrides the value implied by
    ``bias``. The default value is ``None``.

Raises
------
ValueError
    Raised if some values are missing and `allow_masked` is False.

See Also
--------
numpy.cov


def corrcoef(x, y=None, rowvar=True, bias=False, allow_masked=True, ddof=None):

<EOL>if ddof is not None and ddof != int(ddof):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if ddof is None:<EOL><INDENT>if bias:<EOL><INDENT>ddof = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>ddof = <NUM_LIT:1><EOL><DEDENT><DEDENT>(x, xnotmask, rowvar) = _covhelper(x, y, rowvar, allow_masked)<EOL>if not rowvar:<EOL><INDENT>fact = np.dot(xnotmask.T, xnotmask) * <NUM_LIT:1.> - ddof<EOL>c = (dot(x.T, x.conj(), strict=False) / fact).squeeze()<EOL><DEDENT>else:<EOL><INDENT>fact = np.dot(xnotmask, xnotmask.T) * <NUM_LIT:1.> - ddof<EOL>c = (dot(x, x.T.conj(), strict=False) / fact).squeeze()<EOL><DEDENT>try:<EOL><INDENT>diag = ma.diagonal(c)<EOL><DEDENT>except ValueError:<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT>if xnotmask.all():<EOL><INDENT>_denom = ma.sqrt(ma.multiply.outer(diag, diag))<EOL><DEDENT>else:<EOL><INDENT>_denom = diagflat(diag)<EOL>n = x.shape[<NUM_LIT:1> - rowvar]<EOL>if rowvar:<EOL><INDENT>for i in range(n - <NUM_LIT:1>):<EOL><INDENT>for j in range(i + <NUM_LIT:1>, n):<EOL><INDENT>_x = mask_cols(vstack((x[i], x[j]))).var(axis=<NUM_LIT:1>, ddof=ddof)<EOL>_denom[i, j] = _denom[j, i] = ma.sqrt(ma.multiply.reduce(_x))<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>for i in range(n - <NUM_LIT:1>):<EOL><INDENT>for j in range(i + <NUM_LIT:1>, n):<EOL><INDENT>_x = mask_cols(<EOL>vstack((x[:, i], x[:, j]))).var(axis=<NUM_LIT:1>, ddof=ddof)<EOL>_denom[i, j] = _denom[j, i] = ma.sqrt(ma.multiply.reduce(_x))<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return c / _denom<EOL>

Return correlation coefficients of the input array.

Except for the handling of missing data this function does the same as
`numpy.corrcoef`. For more details and examples, see `numpy.corrcoef`.

Parameters
----------
x : array_like
    A 1-D or 2-D array containing multiple variables and observations.
    Each row of `x` represents a variable, and each column a single
    observation of all those variables. Also see `rowvar` below.
y : array_like, optional
    An additional set of variables and observations. `y` has the same
    shape as `x`.
rowvar : bool, optional
    If `rowvar` is True (default), then each row represents a
    variable, with observations in the columns. Otherwise, the relationship
    is transposed: each column represents a variable, while the rows
    contain observations.
bias : bool, optional
    Default normalization (False) is by ``(N-1)``, where ``N`` is the
    number of observations given (unbiased estimate). If `bias` is 1,
    then normalization is by ``N``. This keyword can be overridden by
    the keyword ``ddof`` in numpy versions >= 1.5.
allow_masked : bool, optional
    If True, masked values are propagated pair-wise: if a value is masked
    in `x`, the corresponding value is masked in `y`.
    If False, raises an exception.
ddof : {None, int}, optional
    .. versionadded:: 1.5
    If not ``None`` normalization is by ``(N - ddof)``, where ``N`` is
    the number of observations; this overrides the value implied by
    ``bias``. The default value is ``None``.

See Also
--------
numpy.corrcoef : Equivalent function in top-level NumPy module.
cov : Estimate the covariance matrix.


m = getmask(a)<EOL>if m is nomask or not np.any(m):<EOL><INDENT>return np.array([<NUM_LIT:0>, a.size - <NUM_LIT:1>])<EOL><DEDENT>unmasked = np.flatnonzero(~m)<EOL>if len(unmasked) > <NUM_LIT:0>:<EOL><INDENT>return unmasked[[<NUM_LIT:0>, -<NUM_LIT:1>]]<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>

Find the indices of the first and last unmasked values.

Expects a 1-D `MaskedArray`, returns None if all values are masked.

Parameters
----------
arr : array_like
    Input 1-D `MaskedArray`

Returns
-------
edges : ndarray or None
    The indices of first and last non-masked value in the array.
    Returns None if all values are masked.

See Also
--------
flatnotmasked_contiguous, notmasked_contiguous, notmasked_edges,
clump_masked, clump_unmasked

Notes
-----
Only accepts 1-D arrays.

Examples
--------
>>> a = np.ma.arange(10)
>>> flatnotmasked_edges(a)
[0,-1]

>>> mask = (a < 3) | (a > 8) | (a == 5)
>>> a[mask] = np.ma.masked
>>> np.array(a[~a.mask])
array([3, 4, 6, 7, 8])

>>> flatnotmasked_edges(a)
array([3, 8])

>>> a[:] = np.ma.masked
>>> print flatnotmasked_edges(ma)
None


a = asarray(a)<EOL>if axis is None or a.ndim == <NUM_LIT:1>:<EOL><INDENT>return flatnotmasked_edges(a)<EOL><DEDENT>m = getmaskarray(a)<EOL>idx = array(np.indices(a.shape), mask=np.asarray([m] * a.ndim))<EOL>return [tuple([idx[i].min(axis).compressed() for i in range(a.ndim)]),<EOL>tuple([idx[i].max(axis).compressed() for i in range(a.ndim)]), ]<EOL>

Find the indices of the first and last unmasked values along an axis.

If all values are masked, return None.  Otherwise, return a list
of two tuples, corresponding to the indices of the first and last
unmasked values respectively.

Parameters
----------
a : array_like
    The input array.
axis : int, optional
    Axis along which to perform the operation.
    If None (default), applies to a flattened version of the array.

Returns
-------
edges : ndarray or list
    An array of start and end indexes if there are any masked data in
    the array. If there are no masked data in the array, `edges` is a
    list of the first and last index.

See Also
--------
flatnotmasked_contiguous, flatnotmasked_edges, notmasked_contiguous,
clump_masked, clump_unmasked

Examples
--------
>>> a = np.arange(9).reshape((3, 3))
>>> m = np.zeros_like(a)
>>> m[1:, 1:] = 1

>>> am = np.ma.array(a, mask=m)
>>> np.array(am[~am.mask])
array([0, 1, 2, 3, 6])

>>> np.ma.extras.notmasked_edges(ma)
array([0, 6])


m = getmask(a)<EOL>if m is nomask:<EOL><INDENT>return slice(<NUM_LIT:0>, a.size, None)<EOL><DEDENT>i = <NUM_LIT:0><EOL>result = []<EOL>for (k, g) in itertools.groupby(m.ravel()):<EOL><INDENT>n = len(list(g))<EOL>if not k:<EOL><INDENT>result.append(slice(i, i + n))<EOL><DEDENT>i += n<EOL><DEDENT>return result or None<EOL>

Find contiguous unmasked data in a masked array along the given axis.

Parameters
----------
a : narray
    The input array.

Returns
-------
slice_list : list
    A sorted sequence of slices (start index, end index).

See Also
--------
flatnotmasked_edges, notmasked_contiguous, notmasked_edges,
clump_masked, clump_unmasked

Notes
-----
Only accepts 2-D arrays at most.

Examples
--------
>>> a = np.ma.arange(10)
>>> np.ma.extras.flatnotmasked_contiguous(a)
slice(0, 10, None)

>>> mask = (a < 3) | (a > 8) | (a == 5)
>>> a[mask] = np.ma.masked
>>> np.array(a[~a.mask])
array([3, 4, 6, 7, 8])

>>> np.ma.extras.flatnotmasked_contiguous(a)
[slice(3, 5, None), slice(6, 9, None)]
>>> a[:] = np.ma.masked
>>> print np.ma.extras.flatnotmasked_edges(a)
None


a = asarray(a)<EOL>nd = a.ndim<EOL>if nd > <NUM_LIT:2>:<EOL><INDENT>raise NotImplementedError("<STR_LIT>")<EOL><DEDENT>if axis is None or nd == <NUM_LIT:1>:<EOL><INDENT>return flatnotmasked_contiguous(a)<EOL><DEDENT>result = []<EOL>other = (axis + <NUM_LIT:1>) % <NUM_LIT:2><EOL>idx = [<NUM_LIT:0>, <NUM_LIT:0>]<EOL>idx[axis] = slice(None, None)<EOL>for i in range(a.shape[other]):<EOL><INDENT>idx[other] = i<EOL>result.append(flatnotmasked_contiguous(a[idx]) or None)<EOL><DEDENT>return result<EOL>

Find contiguous unmasked data in a masked array along the given axis.

Parameters
----------
a : array_like
    The input array.
axis : int, optional
    Axis along which to perform the operation.
    If None (default), applies to a flattened version of the array.

Returns
-------
endpoints : list
    A list of slices (start and end indexes) of unmasked indexes
    in the array.

See Also
--------
flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges,
clump_masked, clump_unmasked

Notes
-----
Only accepts 2-D arrays at most.

Examples
--------
>>> a = np.arange(9).reshape((3, 3))
>>> mask = np.zeros_like(a)
>>> mask[1:, 1:] = 1

>>> ma = np.ma.array(a, mask=mask)
>>> np.array(ma[~ma.mask])
array([0, 1, 2, 3, 6])

>>> np.ma.extras.notmasked_contiguous(ma)
[slice(0, 4, None), slice(6, 7, None)]


<EOL>if mask.ndim > <NUM_LIT:1>:<EOL><INDENT>mask = mask.ravel()<EOL><DEDENT>idx = (mask[<NUM_LIT:1>:] ^ mask[:-<NUM_LIT:1>]).nonzero()<EOL>idx = idx[<NUM_LIT:0>] + <NUM_LIT:1><EOL>slices = [slice(left, right)<EOL>for (left, right) in zip(itertools.chain([<NUM_LIT:0>], idx),<EOL>itertools.chain(idx, [len(mask)]),)]<EOL>return slices<EOL>

Finds the clumps (groups of data with the same values) for a 1D bool array.

Returns a series of slices.


mask = getattr(a, '<STR_LIT>', nomask)<EOL>if mask is nomask:<EOL><INDENT>return [slice(<NUM_LIT:0>, a.size)]<EOL><DEDENT>slices = _ezclump(mask)<EOL>if a[<NUM_LIT:0>] is masked:<EOL><INDENT>result = slices[<NUM_LIT:1>::<NUM_LIT:2>]<EOL><DEDENT>else:<EOL><INDENT>result = slices[::<NUM_LIT:2>]<EOL><DEDENT>return result<EOL>

Return list of slices corresponding to the unmasked clumps of a 1-D array.
(A "clump" is defined as a contiguous region of the array).

Parameters
----------
a : ndarray
    A one-dimensional masked array.

Returns
-------
slices : list of slice
    The list of slices, one for each continuous region of unmasked
    elements in `a`.

Notes
-----
.. versionadded:: 1.4.0

See Also
--------
flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges,
notmasked_contiguous, clump_masked

Examples
--------
>>> a = np.ma.masked_array(np.arange(10))
>>> a[[0, 1, 2, 6, 8, 9]] = np.ma.masked
>>> np.ma.extras.clump_unmasked(a)
[slice(3, 6, None), slice(7, 8, None)]


mask = ma.getmask(a)<EOL>if mask is nomask:<EOL><INDENT>return []<EOL><DEDENT>slices = _ezclump(mask)<EOL>if len(slices):<EOL><INDENT>if a[<NUM_LIT:0>] is masked:<EOL><INDENT>slices = slices[::<NUM_LIT:2>]<EOL><DEDENT>else:<EOL><INDENT>slices = slices[<NUM_LIT:1>::<NUM_LIT:2>]<EOL><DEDENT><DEDENT>return slices<EOL>

Returns a list of slices corresponding to the masked clumps of a 1-D array.
(A "clump" is defined as a contiguous region of the array).

Parameters
----------
a : ndarray
    A one-dimensional masked array.

Returns
-------
slices : list of slice
    The list of slices, one for each continuous region of masked elements
    in `a`.

Notes
-----
.. versionadded:: 1.4.0

See Also
--------
flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges,
notmasked_contiguous, clump_unmasked

Examples
--------
>>> a = np.ma.masked_array(np.arange(10))
>>> a[[0, 1, 2, 6, 8, 9]] = np.ma.masked
>>> np.ma.extras.clump_masked(a)
[slice(0, 3, None), slice(6, 7, None), slice(8, 10, None)]


_vander = np.vander(x, n)<EOL>m = getmask(x)<EOL>if m is not nomask:<EOL><INDENT>_vander[m] = <NUM_LIT:0><EOL><DEDENT>return _vander<EOL>

Masked values in the input array result in rows of zeros.


def polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False):

x = asarray(x)<EOL>y = asarray(y)<EOL>m = getmask(x)<EOL>if y.ndim == <NUM_LIT:1>:<EOL><INDENT>m = mask_or(m, getmask(y))<EOL><DEDENT>elif y.ndim == <NUM_LIT:2>:<EOL><INDENT>my = getmask(mask_rows(y))<EOL>if my is not nomask:<EOL><INDENT>m = mask_or(m, my[:, <NUM_LIT:0>])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if w is not None:<EOL><INDENT>w = asarray(w)<EOL>if w.ndim != <NUM_LIT:1>:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if w.shape[<NUM_LIT:0>] != y.shape[<NUM_LIT:0>] :<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>m = mask_or(m, getmask(w))<EOL><DEDENT>if m is not nomask:<EOL><INDENT>if w is not None:<EOL><INDENT>w = ~m*w<EOL><DEDENT>else:<EOL><INDENT>w = ~m<EOL><DEDENT><DEDENT>return np.polyfit(x, y, deg, rcond, full, w, cov)<EOL>

Any masked values in x is propagated in y, and vice-versa.


npfunc = getattr(np, self.__name__, None)<EOL>doc = getattr(npfunc, '<STR_LIT>', None)<EOL>if doc:<EOL><INDENT>sig = self.__name__ + ma.get_object_signature(npfunc)<EOL>locdoc = "<STR_LIT>""<STR_LIT>"<EOL>return '<STR_LIT:\n>'.join((sig, doc, locdoc))<EOL><DEDENT>return<EOL>

Retrieve the docstring and signature from the function.

The ``__doc__`` attribute of the function is used as the docstring for
the new masked array version of the function. A note on application
of the function to the mask is appended.

.. warning::
  If the function docstring already contained a Notes section, the
  new docstring will have two Notes sections instead of appending a note
  to the existing section.

Parameters
----------
None


if hasattr(data, '<STR_LIT>'):<EOL><INDENT>return "<STR_LIT:U+002C>".join([desc[<NUM_LIT:1>] for desc in data.dtype.descr])<EOL><DEDENT>formats = '<STR_LIT>'<EOL>for obj in data:<EOL><INDENT>obj = np.asarray(obj)<EOL>formats += _typestr[obj.dtype.type]<EOL>if issubclass(obj.dtype.type, ntypes.flexible):<EOL><INDENT>formats += repr(obj.itemsize)<EOL><DEDENT>formats += '<STR_LIT:U+002C>'<EOL><DEDENT>return formats[:-<NUM_LIT:1>]<EOL>

Returns the formats of each array of arraylist as a comma-separated string.