T = np.asarray(T)<EOL>if len(T.shape) != <NUM_LIT:2> or T.shape[<NUM_LIT:0>] != T.shape[<NUM_LIT:1>]:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>n, n = T.shape<EOL>T_diag = np.diag(T)<EOL>keep_it_real = np.isrealobj(T) and np.min(T_diag) >= <NUM_LIT:0><EOL>if keep_it_real:<EOL><INDENT>T0 = T<EOL><DEDENT>else:<EOL><INDENT>T0 = T.astype(complex)<EOL><DEDENT>theta = (None,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>)<EOL>R, s, m = _inverse_squaring_helper(T0, theta)<EOL>nodes, weights = scipy.special.p_roots(m)<EOL>nodes = nodes.real<EOL>if nodes.shape != (m,) or weights.shape != (m,):<EOL><INDENT>raise Exception('<STR_LIT>')<EOL><DEDENT>nodes = <NUM_LIT:0.5> + <NUM_LIT:0.5> * nodes<EOL>weights = <NUM_LIT:0.5> * weights<EOL>ident = np.identity(n)<EOL>U = np.zeros_like(R)<EOL>for alpha, beta in zip(weights, nodes):<EOL><INDENT>U += solve_triangular(ident + beta*R, alpha*R)<EOL><DEDENT>U *= np.exp2(s)<EOL>has_principal_branch = all(x.real > <NUM_LIT:0> or x.imag != <NUM_LIT:0> for x in np.diag(T0))<EOL>if has_principal_branch:<EOL><INDENT>U[np.diag_indices(n)] = np.log(np.diag(T0))<EOL>for i in range(n-<NUM_LIT:1>):<EOL><INDENT>l1 = T0[i, i]<EOL>l2 = T0[i+<NUM_LIT:1>, i+<NUM_LIT:1>]<EOL>t12 = T0[i, i+<NUM_LIT:1>]<EOL>U[i, i+<NUM_LIT:1>] = _logm_superdiag_entry(l1, l2, t12)<EOL><DEDENT><DEDENT>if not np.array_equal(U, np.triu(U)):<EOL><INDENT>raise Exception('<STR_LIT>')<EOL><DEDENT>return U<EOL>

Compute matrix logarithm of an upper triangular matrix.

The matrix logarithm is the inverse of
expm: expm(logm(`T`)) == `T`

Parameters
----------
T : (N, N) array_like
    Upper triangular matrix whose logarithm to evaluate

Returns
-------
logm : (N, N) ndarray
    Matrix logarithm of `T`

References
----------
.. [1] Awad H. Al-Mohy and Nicholas J. Higham (2012)
       "Improved Inverse Scaling and Squaring Algorithms
       for the Matrix Logarithm."
       SIAM Journal on Scientific Computing, 34 (4). C152-C169.
       ISSN 1095-7197

.. [2] Nicholas J. Higham (2008)
       "Functions of Matrices: Theory and Computation"
       ISBN 978-0-898716-46-7

.. [3] Nicholas J. Higham and Lijing lin (2011)
       "A Schur-Pade Algorithm for Fractional Powers of a Matrix."
       SIAM Journal on Matrix Analysis and Applications,
       32 (3). pp. 1056-1078. ISSN 0895-4798


def _onenormest_m1_power(A, p,<EOL>t=<NUM_LIT:2>, itmax=<NUM_LIT:5>, compute_v=False, compute_w=False):

return onenormest(_MatrixM1PowerOperator(A, p),<EOL>t=t, itmax=itmax, compute_v=compute_v, compute_w=compute_w)<EOL>

Efficiently estimate the 1-norm of (A - I)^p.

Parameters
----------
A : ndarray
    Matrix whose 1-norm of a power is to be computed.
p : int
    Non-negative integer power.
t : int, optional
    A positive parameter controlling the tradeoff between
    accuracy versus time and memory usage.
    Larger values take longer and use more memory
    but give more accurate output.
itmax : int, optional
    Use at most this many iterations.
compute_v : bool, optional
    Request a norm-maximizing linear operator input vector if True.
compute_w : bool, optional
    Request a norm-maximizing linear operator output vector if True.

Returns
-------
est : float
    An underestimate of the 1-norm of the sparse matrix.
v : ndarray, optional
    The vector such that ||Av||_1 == est*||v||_1.
    It can be thought of as an input to the linear operator
    that gives an output with particularly large norm.
w : ndarray, optional
    The vector Av which has relatively large 1-norm.
    It can be thought of as an output of the linear operator
    that is relatively large in norm compared to the input.


m_to_theta = {<EOL><NUM_LIT:1>: <NUM_LIT>,<EOL><NUM_LIT:2>: <NUM_LIT>,<EOL><NUM_LIT:3>: <NUM_LIT>,<EOL><NUM_LIT:4>: <NUM_LIT>,<EOL><NUM_LIT:5>: <NUM_LIT>,<EOL><NUM_LIT:6>: <NUM_LIT>,<EOL><NUM_LIT:7>: <NUM_LIT>,<EOL>}<EOL>n, n = T.shape<EOL>T0 = T<EOL>T0_diag = np.diag(T0)<EOL>if np.array_equal(T0, np.diag(T0_diag)):<EOL><INDENT>U = np.diag(T0_diag ** t)<EOL><DEDENT>else:<EOL><INDENT>R, s, m = _inverse_squaring_helper(T0, m_to_theta)<EOL>U = _fractional_power_pade(-R, t, m)<EOL>eivals = np.diag(T0)<EOL>has_principal_branch = all(x.real > <NUM_LIT:0> or x.imag != <NUM_LIT:0> for x in eivals)<EOL>for i in range(s, -<NUM_LIT:1>, -<NUM_LIT:1>):<EOL><INDENT>if i < s:<EOL><INDENT>U = U.dot(U)<EOL><DEDENT>else:<EOL><INDENT>if has_principal_branch:<EOL><INDENT>p = t * np.exp2(-i)<EOL>U[np.diag_indices(n)] = T0_diag ** p<EOL>for j in range(n-<NUM_LIT:1>):<EOL><INDENT>l1 = T0[j, j]<EOL>l2 = T0[j+<NUM_LIT:1>, j+<NUM_LIT:1>]<EOL>t12 = T0[j, j+<NUM_LIT:1>]<EOL>f12 = _fractional_power_superdiag_entry(l1, l2, t12, p)<EOL>U[j, j+<NUM_LIT:1>] = f12<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>if not np.array_equal(U, np.triu(U)):<EOL><INDENT>raise Exception('<STR_LIT>')<EOL><DEDENT>return U<EOL>

Compute a fractional power of an upper triangular matrix.

The fractional power is restricted to fractions -1 < t < 1.
This uses algorithm (3.1) of [1]_.
The Pade approximation itself uses algorithm (4.1) of [2]_.

Parameters
----------
T : (N, N) array_like
    Upper triangular matrix whose fractional power to evaluate.
t : float
    Fractional power between -1 and 1 exclusive.

Returns
-------
X : (N, N) array_like
    The fractional power of the matrix.

References
----------
.. [1] Nicholas J. Higham and Lijing Lin (2013)
       "An Improved Schur-Pade Algorithm for Fractional Powers
       of a Matrix and their Frechet Derivatives."

.. [2] Nicholas J. Higham and Lijing lin (2011)
       "A Schur-Pade Algorithm for Fractional Powers of a Matrix."
       SIAM Journal on Matrix Analysis and Applications,
       32 (3). pp. 1056-1078. ISSN 0895-4798


<EOL>a = np.asarray_chkfinite(a)<EOL>if ord in (None, <NUM_LIT:2>) and (a.ndim == <NUM_LIT:1>) and (a.dtype.char in '<STR_LIT>'):<EOL><INDENT>func_name = _nrm2_prefix.get(a.dtype.char, '<STR_LIT:d>') + '<STR_LIT>'<EOL>nrm2 = getattr(blas, func_name)<EOL>return nrm2(a)<EOL><DEDENT>return np.linalg.norm(a, ord=ord)<EOL>

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 : (M,) or (M, N) array_like
    Input array.
ord : {non-zero int, inf, -inf, 'fro'}, optional
    Order of the norm (see table under ``Notes``). inf means numpy's
    `inf` object.

Returns
-------
norm : float
    Norm of the matrix or vector.

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 scipy.linalg import norm
>>> 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]])

>>> norm(a)
7.745966692414834
>>> norm(b)
7.745966692414834
>>> norm(b, 'fro')
7.745966692414834
>>> norm(a, np.inf)
4
>>> norm(b, np.inf)
9
>>> norm(a, -np.inf)
0
>>> norm(b, -np.inf)
2

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

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


A = np.array([<EOL>[<NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>],<EOL>[<NUM_LIT:0>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>],<EOL>[<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT>, <NUM_LIT>],<EOL>[<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT>]], dtype=float)<EOL>return A<EOL>

Return the test matrix from Experiment (1) of [1]_.

References
----------
.. [1] Awad H. Al-Mohy and Nicholas J. Higham (2012)
       "Improved Inverse Scaling and Squaring Algorithms
       for the Matrix Logarithm."
       SIAM Journal on Scientific Computing, 34 (4). C152-C169.
       ISSN 1095-7197


x = solve_continuous_are(a, b, q, r)<EOL>assert_array_almost_equal(<EOL>a.getH()*x + x*a - x*b*inv(r)*b.getH()*x + q, <NUM_LIT:0.0>)<EOL>

Checks if (A'X + XA - XBR^-1B'X+Q=0) is true


if isinstance(dim_or_eigv, int):<EOL><INDENT>dim = dim_or_eigv<EOL>d = (rand(dim)*<NUM_LIT:2>)-<NUM_LIT:1><EOL><DEDENT>elif (isinstance(dim_or_eigv, ndarray) and<EOL>len(dim_or_eigv.shape) == <NUM_LIT:1>):<EOL><INDENT>dim = dim_or_eigv.shape[<NUM_LIT:0>]<EOL>d = dim_or_eigv<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>v = random_rot(dim)<EOL>h = dot(dot(v.T.conj(), diag(d)), v)<EOL>h = <NUM_LIT:0.5>*(h.T+h)<EOL>return h<EOL>

Return a random symmetric (Hermitian) matrix.

    If 'dim_or_eigv' is an integer N, return a NxN matrix, with eigenvalues
        uniformly distributed on (-1,1).

    If 'dim_or_eigv' is  1-D real array 'a', return a matrix whose
                      eigenvalues are 'a'.


for p in ps:<EOL><INDENT>f = getattr(fblas, p+func, None)<EOL>if f is None:<EOL><INDENT>continue<EOL><DEDENT>yield f<EOL><DEDENT>

Just a helper: return a specified BLAS function w/typecode.


def interp_decomp(A, eps_or_k, rand=True):

from scipy.sparse.linalg import LinearOperator<EOL>real = _is_real(A)<EOL>if isinstance(A, np.ndarray):<EOL><INDENT>if eps_or_k < <NUM_LIT:1>:<EOL><INDENT>eps = eps_or_k<EOL>if rand:<EOL><INDENT>if real:<EOL><INDENT>k, idx, proj = backend.iddp_aid(eps, A)<EOL><DEDENT>else:<EOL><INDENT>k, idx, proj = backend.idzp_aid(eps, A)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if real:<EOL><INDENT>k, idx, proj = backend.iddp_id(eps, A)<EOL><DEDENT>else:<EOL><INDENT>k, idx, proj = backend.idzp_id(eps, A)<EOL><DEDENT><DEDENT>return k, idx - <NUM_LIT:1>, proj<EOL><DEDENT>else:<EOL><INDENT>k = int(eps_or_k)<EOL>if rand:<EOL><INDENT>if real:<EOL><INDENT>idx, proj = backend.iddr_aid(A, k)<EOL><DEDENT>else:<EOL><INDENT>idx, proj = backend.idzr_aid(A, k)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if real:<EOL><INDENT>idx, proj = backend.iddr_id(A, k)<EOL><DEDENT>else:<EOL><INDENT>idx, proj = backend.idzr_id(A, k)<EOL><DEDENT><DEDENT>return idx - <NUM_LIT:1>, proj<EOL><DEDENT><DEDENT>elif isinstance(A, LinearOperator):<EOL><INDENT>m, n = A.shape<EOL>matveca = A.rmatvec<EOL>if eps_or_k < <NUM_LIT:1>:<EOL><INDENT>eps = eps_or_k<EOL>if real:<EOL><INDENT>k, idx, proj = backend.iddp_rid(eps, m, n, matveca)<EOL><DEDENT>else:<EOL><INDENT>k, idx, proj = backend.idzp_rid(eps, m, n, matveca)<EOL><DEDENT>return k, idx - <NUM_LIT:1>, proj<EOL><DEDENT>else:<EOL><INDENT>k = int(eps_or_k)<EOL>if real:<EOL><INDENT>idx, proj = backend.iddr_rid(m, n, matveca, k)<EOL><DEDENT>else:<EOL><INDENT>idx, proj = backend.idzr_rid(m, n, matveca, k)<EOL><DEDENT>return idx - <NUM_LIT:1>, proj<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise _TYPE_ERROR<EOL><DEDENT>

Compute ID of a matrix.

An ID of a matrix `A` is a factorization defined by a rank `k`, a column
index array `idx`, and interpolation coefficients `proj` such that::

    numpy.dot(A[:,idx[:k]], proj) = A[:,idx[k:]]

The original matrix can then be reconstructed as::

    numpy.hstack([A[:,idx[:k]],
                                numpy.dot(A[:,idx[:k]], proj)]
                            )[:,numpy.argsort(idx)]

or via the routine :func:`reconstruct_matrix_from_id`. This can
equivalently be written as::

    numpy.dot(A[:,idx[:k]],
                        numpy.hstack([numpy.eye(k), proj])
                      )[:,np.argsort(idx)]

in terms of the skeleton and interpolation matrices::

    B = A[:,idx[:k]]

and::

    P = numpy.hstack([numpy.eye(k), proj])[:,np.argsort(idx)]

respectively. See also :func:`reconstruct_interp_matrix` and
:func:`reconstruct_skel_matrix`.

The ID can be computed to any relative precision or rank (depending on the
value of `eps_or_k`). If a precision is specified (`eps_or_k < 1`), then
this function has the output signature::

    k, idx, proj = interp_decomp(A, eps_or_k)

Otherwise, if a rank is specified (`eps_or_k >= 1`), then the output
signature is::

    idx, proj = interp_decomp(A, eps_or_k)

..  This function automatically detects the form of the input parameters
    and passes them to the appropriate backend. For details, see
    :func:`backend.iddp_id`, :func:`backend.iddp_aid`,
    :func:`backend.iddp_rid`, :func:`backend.iddr_id`,
    :func:`backend.iddr_aid`, :func:`backend.iddr_rid`,
    :func:`backend.idzp_id`, :func:`backend.idzp_aid`,
    :func:`backend.idzp_rid`, :func:`backend.idzr_id`,
    :func:`backend.idzr_aid`, and :func:`backend.idzr_rid`.

Parameters
----------
A : :class:`numpy.ndarray` or :class:`scipy.sparse.linalg.LinearOperator` with `rmatvec`
    Matrix to be factored
eps_or_k : float or int
    Relative error (if `eps_or_k < 1`) or rank (if `eps_or_k >= 1`) of
    approximation.
rand : bool, optional
    Whether to use random sampling if `A` is of type :class:`numpy.ndarray`
    (randomized algorithms are always used if `A` is of type
    :class:`scipy.sparse.linalg.LinearOperator`).

Returns
-------
k : int
    Rank required to achieve specified relative precision if
    `eps_or_k < 1`.
idx : :class:`numpy.ndarray`
    Column index array.
proj : :class:`numpy.ndarray`
    Interpolation coefficients.


def estimate_spectral_norm_diff(A, B, its=<NUM_LIT:20>):

from scipy.sparse.linalg import aslinearoperator<EOL>A = aslinearoperator(A)<EOL>B = aslinearoperator(B)<EOL>m, n = A.shape<EOL>matvec1 = lambda x: A. matvec(x)<EOL>matveca1 = lambda x: A.rmatvec(x)<EOL>matvec2 = lambda x: B. matvec(x)<EOL>matveca2 = lambda x: B.rmatvec(x)<EOL>if _is_real(A):<EOL><INDENT>return backend.idd_diffsnorm(<EOL>m, n, matveca1, matveca2, matvec1, matvec2, its=its)<EOL><DEDENT>else:<EOL><INDENT>return backend.idz_diffsnorm(<EOL>m, n, matveca1, matveca2, matvec1, matvec2, its=its)<EOL><DEDENT>

Estimate spectral norm of the difference of two matrices by the randomized
power method.

..  This function automatically detects the matrix data type and calls the
    appropriate backend. For details, see :func:`backend.idd_diffsnorm` and
    :func:`backend.idz_diffsnorm`.

Parameters
----------
A : :class:`scipy.sparse.linalg.LinearOperator`
    First matrix given as a :class:`scipy.sparse.linalg.LinearOperator` with the
    `matvec` and `rmatvec` methods (to apply the matrix and its adjoint).
B : :class:`scipy.sparse.linalg.LinearOperator`
    Second matrix given as a :class:`scipy.sparse.linalg.LinearOperator` with
    the `matvec` and `rmatvec` methods (to apply the matrix and its adjoint).
its : int
    Number of power method iterations.

Returns
-------
float
    Spectral norm estimate of matrix difference.


from scipy.sparse.linalg import aslinearoperator<EOL>A = aslinearoperator(A)<EOL>m, n = A.shape<EOL>matvec = lambda x: A. matvec(x)<EOL>matveca = lambda x: A.rmatvec(x)<EOL>if _is_real(A):<EOL><INDENT>return backend.idd_snorm(m, n, matveca, matvec, its=its)<EOL><DEDENT>else:<EOL><INDENT>return backend.idz_snorm(m, n, matveca, matvec, its=its)<EOL><DEDENT>

Estimate spectral norm of a matrix by the randomized power method.

..  This function automatically detects the matrix data type and calls the
    appropriate backend. For details, see :func:`backend.idd_snorm` and
    :func:`backend.idz_snorm`.

Parameters
----------
A : :class:`scipy.sparse.linalg.LinearOperator`
    Matrix given as a :class:`scipy.sparse.linalg.LinearOperator` with the
    `matvec` and `rmatvec` methods (to apply the matrix and its adjoint).
its : int
    Number of power method iterations.

Returns
-------
float
    Spectral norm estimate.


def cholesky_banded(ab, overwrite_ab=False, lower=False, check_finite=True):

if check_finite:<EOL><INDENT>ab = asarray_chkfinite(ab)<EOL><DEDENT>else:<EOL><INDENT>ab = asarray(ab)<EOL><DEDENT>pbtrf, = get_lapack_funcs(('<STR_LIT>',), (ab,))<EOL>c, info = pbtrf(ab, lower=lower, overwrite_ab=overwrite_ab)<EOL>if info > <NUM_LIT:0>:<EOL><INDENT>raise LinAlgError("<STR_LIT>" % info)<EOL><DEDENT>if info < <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>% -info)<EOL><DEDENT>return c<EOL>

Cholesky decompose a banded Hermitian positive-definite matrix

The matrix a is stored in ab either in lower diagonal or upper
diagonal ordered form:

    ab[u + i - j, j] == a[i,j]        (if upper form; i <= j)
    ab[    i - j, j] == a[i,j]        (if lower form; i >= j)

Example of ab (shape of a is (6,6), u=2)::

    upper form:
    *   *   a02 a13 a24 a35
    *   a01 a12 a23 a34 a45
    a00 a11 a22 a33 a44 a55

    lower form:
    a00 a11 a22 a33 a44 a55
    a10 a21 a32 a43 a54 *
    a20 a31 a42 a53 *   *

Parameters
----------
ab : (u + 1, M) array_like
    Banded matrix
overwrite_ab : boolean
    Discard data in ab (may enhance performance)
lower : boolean
    Is the matrix in the lower form. (Default is upper form)
check_finite : boolean, optional
    Whether to check that the input matrix contains only finite numbers.
    Disabling may give a performance gain, but may result in problems
    (crashes, non-termination) if the inputs do contain infinities or NaNs.

Returns
-------
c : (u + 1, M) ndarray
    Cholesky factorization of a, in the same banded format as ab


part = diag(s)<EOL>typ = part.dtype.char<EOL>MorN = len(s)<EOL>if MorN == M:<EOL><INDENT>return r_['<STR_LIT>', part, zeros((M, N-M), typ)]<EOL><DEDENT>elif MorN == N:<EOL><INDENT>return r_[part, zeros((M-N,N), typ)]<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>

Construct the sigma matrix in SVD from singular values and size M, N.

Parameters
----------
s : (M,) or (N,) array_like
    Singular values
M : int
    Size of the matrix whose singular values are `s`.
N : int
    Size of the matrix whose singular values are `s`.

Returns
-------
S : (M, N) ndarray
    The S-matrix in the singular value decomposition


def svd(a, full_matrices=True, compute_uv=True, overwrite_a=False,<EOL>check_finite=True):

if check_finite:<EOL><INDENT>a1 = asarray_chkfinite(a)<EOL><DEDENT>else:<EOL><INDENT>a1 = asarray(a)<EOL><DEDENT>if len(a1.shape) != <NUM_LIT:2>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>m,n = a1.shape<EOL>overwrite_a = overwrite_a or (_datacopied(a1, a))<EOL>gesdd, gesdd_lwork = get_lapack_funcs(('<STR_LIT>', '<STR_LIT>'), (a1,))<EOL>lwork, info = gesdd_lwork(a1.shape[<NUM_LIT:0>], a1.shape[<NUM_LIT:1>], compute_uv=compute_uv, full_matrices=full_matrices)<EOL>if info != <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>' % info)<EOL><DEDENT>lwork = int(lwork.real)<EOL>u,s,v,info = gesdd(a1, compute_uv=compute_uv, lwork=lwork,<EOL>full_matrices=full_matrices, overwrite_a=overwrite_a)<EOL>if info > <NUM_LIT:0>:<EOL><INDENT>raise LinAlgError("<STR_LIT>")<EOL><DEDENT>if info < <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>% -info)<EOL><DEDENT>if compute_uv:<EOL><INDENT>return u, s, v<EOL><DEDENT>else:<EOL><INDENT>return s<EOL><DEDENT>

Singular Value Decomposition.

Factorizes the matrix a into two unitary matrices U and Vh, and
a 1-D array s of singular values (real, non-negative) such that
``a == U*S*Vh``, where S is a suitably shaped matrix of zeros with
main diagonal s.

Parameters
----------
a : (M, N) array_like
    Matrix to decompose.
full_matrices : bool, optional
    If True, `U` and `Vh` are of shape ``(M,M)``, ``(N,N)``.
    If False, the shapes are ``(M,K)`` and ``(K,N)``, where
    ``K = min(M,N)``.
compute_uv : bool, optional
    Whether to compute also `U` and `Vh` in addition to `s`.
    Default is True.
overwrite_a : bool, optional
    Whether to overwrite `a`; may improve performance.
    Default is False.
check_finite : boolean, optional
    Whether to check that the input matrix contains only finite numbers.
    Disabling may give a performance gain, but may result in problems
    (crashes, non-termination) if the inputs do contain infinities or NaNs.

Returns
-------
U : ndarray
    Unitary matrix having left singular vectors as columns.
    Of shape ``(M,M)`` or ``(M,K)``, depending on `full_matrices`.
s : ndarray
    The singular values, sorted in non-increasing order.
    Of shape (K,), with ``K = min(M, N)``.
Vh : ndarray
    Unitary matrix having right singular vectors as rows.
    Of shape ``(N,N)`` or ``(K,N)`` depending on `full_matrices`.

For ``compute_uv = False``, only `s` is returned.

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

See also
--------
svdvals : Compute singular values of a matrix.
diagsvd : Construct the Sigma matrix, given the vector s.

Examples
--------
>>> from scipy import linalg
>>> a = np.random.randn(9, 6) + 1.j*np.random.randn(9, 6)
>>> U, s, Vh = linalg.svd(a)
>>> U.shape, Vh.shape, s.shape
((9, 9), (6, 6), (6,))

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

>>> s2 = linalg.svd(a, compute_uv=False)
>>> np.allclose(s, s2)
True


if side not in ['<STR_LIT:right>', '<STR_LIT:left>']:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>a = np.asarray(a)<EOL>if a.ndim != <NUM_LIT:2>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>w, s, vh = svd(a, full_matrices=False)<EOL>u = w.dot(vh)<EOL>if side == '<STR_LIT:right>':<EOL><INDENT>p = (vh.T.conj() * s).dot(vh)<EOL><DEDENT>else:<EOL><INDENT>p = (w * s).dot(w.T.conj())<EOL><DEDENT>return u, p<EOL>

Compute the polar decomposition.

Returns the factors of the polar decomposition [1]_ `u` and `p` such
that ``a = up`` (if `side` is "right") or ``a = pu`` (if `side` is
"left"), where `p` is positive semidefinite.  Depending on the shape
of `a`, either the rows or columns of `u` are orthonormal.  When `a`
is a square array, `u` is a square unitary array.  When `a` is not
square, the "canonical polar decomposition" [2]_ is computed.

Parameters
----------
a : (m, n) array_like
    The array to be factored.
side : string, optional
    Determines whether a right or left polar decomposition is computed.
    If `side` is "right", then ``a = up``.  If `side` is "left",  then
    ``a = pu``.  The default is "right".

Returns
-------
u : (m, n) ndarray
    If `a` is square, then `u` is unitary.  If m > n, then the columns
    of `a` are orthonormal, and if m < n, then the rows of `u` are
    orthonormal.
p : ndarray
    `p` is Hermitian positive semidefinite.  If `a` is nonsingular, `p`
    is positive definite.  The shape of `p` is (n, n) or (m, m), depending
    on whether `side` is "right" or "left", respectively.

References
----------
.. [1] R. A. Horn and C. R. Johnson, "Matrix Analysis", Cambridge University
       Press, 1985.
.. [2] N. J. Higham, "Functions of Matrices: Theory and Computation",
       SIAM, 2008.

Examples
--------
>>> a = np.array([[1, -1], [2, 4]])
>>> u, p = polar(a)
>>> u
array([[ 0.85749293, -0.51449576],
       [ 0.51449576,  0.85749293]])
>>> p
array([[ 1.88648444,  1.2004901 ],
       [ 1.2004901 ,  3.94446746]])

A non-square example, with m < n:

>>> b = np.array([[0.5, 1, 2], [1.5, 3, 4]])
>>> u, p = polar(b)
>>> u
array([[-0.21196618, -0.42393237,  0.88054056],
       [ 0.39378971,  0.78757942,  0.4739708 ]])
>>> p
array([[ 0.48470147,  0.96940295,  1.15122648],
       [ 0.96940295,  1.9388059 ,  2.30245295],
       [ 1.15122648,  2.30245295,  3.65696431]])
>>> u.dot(p)   # Verify the decomposition.
array([[ 0.5,  1. ,  2. ],
       [ 1.5,  3. ,  4. ]])
>>> u.dot(u.T)   # The rows of u are orthonormal.
array([[  1.00000000e+00,  -2.07353665e-17],
       [ -2.07353665e-17,   1.00000000e+00]])

Another non-square example, with m > n:

>>> c = b.T
>>> u, p = polar(c)
>>> u
array([[-0.21196618,  0.39378971],
       [-0.42393237,  0.78757942],
       [ 0.88054056,  0.4739708 ]])
>>> p
array([[ 1.23116567,  1.93241587],
       [ 1.93241587,  4.84930602]])
>>> u.dot(p)   # Verify the decomposition.
array([[ 0.5,  1.5],
       [ 1. ,  3. ],
       [ 2. ,  4. ]])
>>> u.T.dot(u)  # The columns of u are orthonormal.
array([[  1.00000000e+00,  -1.26363763e-16],
       [ -1.26363763e-16,   1.00000000e+00]])


def sqrtm(A, disp=True, blocksize=<NUM_LIT:64>):

A = np.asarray(A)<EOL>if len(A.shape) != <NUM_LIT:2>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if blocksize < <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>keep_it_real = np.isrealobj(A)<EOL>if keep_it_real:<EOL><INDENT>T, Z = schur(A)<EOL>if not np.array_equal(T, np.triu(T)):<EOL><INDENT>T, Z = rsf2csf(T,Z)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>T, Z = schur(A, output='<STR_LIT>')<EOL><DEDENT>failflag = False<EOL>try:<EOL><INDENT>R = _sqrtm_triu(T, blocksize=blocksize)<EOL>ZH = np.conjugate(Z).T<EOL>X = Z.dot(R).dot(ZH)<EOL><DEDENT>except SqrtmError as e:<EOL><INDENT>failflag = True<EOL>X = np.empty_like(A)<EOL>X.fill(np.nan)<EOL><DEDENT>if disp:<EOL><INDENT>nzeig = np.any(np.diag(T) == <NUM_LIT:0>)<EOL>if nzeig:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>elif failflag:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>return X<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>arg2 = norm(X.dot(X) - A,'<STR_LIT>')**<NUM_LIT:2> / norm(A,'<STR_LIT>')<EOL><DEDENT>except ValueError:<EOL><INDENT>arg2 = np.inf<EOL><DEDENT>return X, arg2<EOL><DEDENT>

Matrix square root.

Parameters
----------
A : (N, N) array_like
    Matrix whose square root to evaluate
disp : bool, optional
    Print warning if error in the result is estimated large
    instead of returning estimated error. (Default: True)
blocksize : integer, optional
    If the blocksize is not degenerate with respect to the
    size of the input array, then use a blocked algorithm. (Default: 64)

Returns
-------
sqrtm : (N, N) ndarray
    Value of the sqrt function at `A`

errest : float
    (if disp == False)

    Frobenius norm of the estimated error, ||err||_F / ||A||_F

References
----------
.. [1] Edvin Deadman, Nicholas J. Higham, Rui Ralha (2013)
       "Blocked Schur Algorithms for Computing the Matrix Square Root,
       Lecture Notes in Computer Science, 7782. pp. 171-182.

Examples
--------
>>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
>>> r = sqrtm(a)
>>> r
array([[ 0.75592895,  1.13389342],
       [ 0.37796447,  1.88982237]])
>>> r.dot(r)
array([[ 1.,  3.],
       [ 1.,  4.]])


if check_finite:<EOL><INDENT>A = np.asarray_chkfinite(A)<EOL><DEDENT>else:<EOL><INDENT>A = np.asarray(A)<EOL><DEDENT>if len(A.shape) != <NUM_LIT:2> or A.shape[<NUM_LIT:0>] != A.shape[<NUM_LIT:1>]:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>X = scipy.linalg.expm(A)<EOL>K = expm_frechet_kronform(A, check_finite=False)<EOL>A_norm = scipy.linalg.norm(A, '<STR_LIT>')<EOL>X_norm = scipy.linalg.norm(X, '<STR_LIT>')<EOL>K_norm = scipy.linalg.norm(K, <NUM_LIT:2>)<EOL>kappa = (K_norm * A_norm) / X_norm<EOL>return kappa<EOL>

Relative condition number of the matrix exponential in the Frobenius norm.

Parameters
----------
A : 2d array-like
    Square input matrix with shape (N, N).
check_finite : boolean, optional
    Whether to check that the input matrix contains only finite numbers.
    Disabling may give a performance gain, but may result in problems
    (crashes, non-termination) if the inputs do contain infinities or NaNs.

Returns
-------
kappa : float
    The relative condition number of the matrix exponential
    in the Frobenius norm

Notes
-----
A faster estimate for the condition number in the 1-norm
has been published but is not yet implemented in scipy.

.. versionadded:: 0.14.0

See also
--------
expm : Compute the exponential of a matrix.
expm_frechet : Compute the Frechet derivative of the matrix exponential.


def iddr_rsvd(m, n, matvect, matvec, k):

U, V, S, ier = _id.iddr_rsvd(m, n, matvect, matvec, k)<EOL>if ier != <NUM_LIT:0>:<EOL><INDENT>raise _RETCODE_ERROR<EOL><DEDENT>return U, V, S<EOL>

Compute SVD of a real matrix to a specified rank using random matrix-vector
multiplication.

:param m:
    Matrix row dimension.
:type m: int
:param n:
    Matrix column dimension.
:type n: int
:param matvect:
    Function to apply the matrix transpose to a vector, with call signature
    `y = matvect(x)`, where `x` and `y` are the input and output vectors,
    respectively.
:type matvect: function
:param matvec:
    Function to apply the matrix to a vector, with call signature
    `y = matvec(x)`, where `x` and `y` are the input and output vectors,
    respectively.
:type matvec: function
:param k:
    Rank of SVD.
:type k: int

:return:
    Left singular vectors.
:rtype: :class:`numpy.ndarray`
:return:
    Right singular vectors.
:rtype: :class:`numpy.ndarray`
:return:
    Singular values.
:rtype: :class:`numpy.ndarray`


return _id.idz_frmi(m)<EOL>

Initialize data for :func:`idz_frm`.

:param m:
    Length of vector to be transformed.
:type m: int

:return:
    Greatest power-of-two integer `n` satisfying `n <= m`.
:rtype: int
:return:
    Initialization array to be used by :func:`idz_frm`.
:rtype: :class:`numpy.ndarray`


A = np.asfortranarray(A)<EOL>m, n = A.shape<EOL>w = iddr_aidi(m, n, k)<EOL>idx, proj = _id.iddr_aid(A, k, w)<EOL>if k == n:<EOL><INDENT>proj = np.array([], dtype='<STR_LIT>', order='<STR_LIT:F>')<EOL><DEDENT>else:<EOL><INDENT>proj = proj.reshape((k, n-k), order='<STR_LIT:F>')<EOL><DEDENT>return idx, proj<EOL>

Compute ID of a real matrix to a specified rank using random sampling.

:param A:
    Matrix.
:type A: :class:`numpy.ndarray`
:param k:
    Rank of ID.
:type k: int

:return:
    Column index array.
:rtype: :class:`numpy.ndarray`
:return:
    Interpolation coefficients.
:rtype: :class:`numpy.ndarray`


A = np.asfortranarray(A)<EOL>return _id.idd_copycols(A, k, idx)<EOL>

Reconstruct skeleton matrix from real ID.

:param A:
    Original matrix.
:type A: :class:`numpy.ndarray`
:param k:
    Rank of ID.
:type k: int
:param idx:
    Column index array.
:type idx: :class:`numpy.ndarray`

:return:
    Skeleton matrix.
:rtype: :class:`numpy.ndarray`


A = np.asfortranarray(A)<EOL>idx, rnorms = _id.idzr_id(A, k)<EOL>n = A.shape[<NUM_LIT:1>]<EOL>proj = A.T.ravel()[:k*(n-k)].reshape((k, n-k), order='<STR_LIT:F>')<EOL>return idx, proj<EOL>

Compute ID of a complex matrix to a specified rank.

:param A:
    Matrix.
:type A: :class:`numpy.ndarray`
:param k:
    Rank of ID.
:type k: int

:return:
    Column index array.
:rtype: :class:`numpy.ndarray`
:return:
    Interpolation coefficients.
:rtype: :class:`numpy.ndarray`


return _id.idzr_aidi(m, n, k)<EOL>

Initialize array for :func:`idzr_aid`.

:param m:
    Matrix row dimension.
:type m: int
:param n:
    Matrix column dimension.
:type n: int
:param k:
    Rank of ID.
:type k: int

:return:
    Initialization array to be used by :func:`idzr_aid`.
:rtype: :class:`numpy.ndarray`


B = np.asfortranarray(B)<EOL>if proj.size > <NUM_LIT:0>:<EOL><INDENT>return _id.idz_reconid(B, idx, proj)<EOL><DEDENT>else:<EOL><INDENT>return B[:, np.argsort(idx)]<EOL><DEDENT>

Reconstruct matrix from complex ID.

:param B:
    Skeleton matrix.
:type B: :class:`numpy.ndarray`
:param idx:
    Column index array.
:type idx: :class:`numpy.ndarray`
:param proj:
    Interpolation coefficients.
:type proj: :class:`numpy.ndarray`

:return:
    Reconstructed matrix.
:rtype: :class:`numpy.ndarray`


return _id.idz_reconint(idx, proj)<EOL>

Reconstruct interpolation matrix from complex ID.

:param idx:
    Column index array.
:type idx: :class:`numpy.ndarray`
:param proj:
    Interpolation coefficients.
:type proj: :class:`numpy.ndarray`

:return:
    Interpolation matrix.
:rtype: :class:`numpy.ndarray`


A = np.asfortranarray(A)<EOL>m, n = A.shape<EOL>n2, winit = _id.idd_frmi(m)<EOL>w = np.empty(<EOL>max((min(m, n) + <NUM_LIT:1>)*(<NUM_LIT:3>*m + <NUM_LIT:5>*n + <NUM_LIT:1>) + <NUM_LIT>*min(m, n)**<NUM_LIT:2>,<EOL>(<NUM_LIT:2>*n + <NUM_LIT:1>)*(n2 + <NUM_LIT:1>)),<EOL>order='<STR_LIT:F>')<EOL>k, iU, iV, iS, w, ier = _id.iddp_asvd(eps, A, winit, w)<EOL>if ier:<EOL><INDENT>raise _RETCODE_ERROR<EOL><DEDENT>U = w[iU-<NUM_LIT:1>:iU+m*k-<NUM_LIT:1>].reshape((m, k), order='<STR_LIT:F>')<EOL>V = w[iV-<NUM_LIT:1>:iV+n*k-<NUM_LIT:1>].reshape((n, k), order='<STR_LIT:F>')<EOL>S = w[iS-<NUM_LIT:1>:iS+k-<NUM_LIT:1>]<EOL>return U, V, S<EOL>

Compute SVD of a real matrix to a specified relative precision using random
sampling.

:param eps:
    Relative precision.
:type eps: float
:param A:
    Matrix.
:type A: :class:`numpy.ndarray`

:return:
    Left singular vectors.
:rtype: :class:`numpy.ndarray`
:return:
    Right singular vectors.
:rtype: :class:`numpy.ndarray`
:return:
    Singular values.
:rtype: :class:`numpy.ndarray`


A = np.asfortranarray(A)<EOL>m, n = A.shape<EOL>w = np.empty((<NUM_LIT:2>*k + <NUM_LIT>)*m + (<NUM_LIT:6>*k + <NUM_LIT>)*n + <NUM_LIT>*k**<NUM_LIT:2> + <NUM_LIT:100>, order='<STR_LIT:F>')<EOL>w_ = iddr_aidi(m, n, k)<EOL>w[:w_.size] = w_<EOL>U, V, S, ier = _id.iddr_asvd(A, k, w)<EOL>if ier != <NUM_LIT:0>:<EOL><INDENT>raise _RETCODE_ERROR<EOL><DEDENT>return U, V, S<EOL>

Compute SVD of a real matrix to a specified rank using random sampling.

:param A:
    Matrix.
:type A: :class:`numpy.ndarray`
:param k:
    Rank of SVD.
:type k: int

:return:
    Left singular vectors.
:rtype: :class:`numpy.ndarray`
:return:
    Right singular vectors.
:rtype: :class:`numpy.ndarray`
:return:
    Singular values.
:rtype: :class:`numpy.ndarray`


A = np.asfortranarray(A)<EOL>k, idx, rnorms = _id.idzp_id(eps, A)<EOL>n = A.shape[<NUM_LIT:1>]<EOL>proj = A.T.ravel()[:k*(n-k)].reshape((k, n-k), order='<STR_LIT:F>')<EOL>return k, idx, proj<EOL>

Compute ID of a complex matrix to a specified relative precision.

:param eps:
    Relative precision.
:type eps: float
:param A:
    Matrix.
:type A: :class:`numpy.ndarray`

:return:
    Rank of ID.
:rtype: int
:return:
    Column index array.
:rtype: :class:`numpy.ndarray`
:return:
    Interpolation coefficients.
:rtype: :class:`numpy.ndarray`


A = np.asfortranarray(A)<EOL>m, n = A.shape<EOL>n2, w = idd_frmi(m)<EOL>ra = np.empty(n*n2 + (n + <NUM_LIT:1>)*(n2 + <NUM_LIT:1>), order='<STR_LIT:F>')<EOL>k, ra = _id.idd_estrank(eps, A, w, ra)<EOL>return k<EOL>

Estimate rank of a real matrix to a specified relative precision using
random sampling.

The output rank is typically about 8 higher than the actual rank.

:param eps:
    Relative precision.
:type eps: float
:param A:
    Matrix.
:type A: :class:`numpy.ndarray`

:return:
    Rank estimate.
:rtype: int


return _id.idd_reconint(idx, proj)<EOL>

Reconstruct interpolation matrix from real ID.

:param idx:
    Column index array.
:type idx: :class:`numpy.ndarray`
:param proj:
    Interpolation coefficients.
:type proj: :class:`numpy.ndarray`

:return:
    Interpolation matrix.
:rtype: :class:`numpy.ndarray`


return _id.idd_sfrmi(l, m)<EOL>

Initialize data for :func:`idd_sfrm`.

:param l:
    Length of output transformed vector.
:type l: int
:param m:
    Length of the vector to be transformed.
:type m: int

:return:
    Greatest power-of-two integer `n` satisfying `n <= m`.
:rtype: int
:return:
    Initialization array to be used by :func:`idd_sfrm`.
:rtype: :class:`numpy.ndarray`


def idd_snorm(m, n, matvect, matvec, its=<NUM_LIT:20>):

snorm, v = _id.idd_snorm(m, n, matvect, matvec, its)<EOL>return snorm<EOL>

Estimate spectral norm of a real matrix by the randomized power method.

:param m:
    Matrix row dimension.
:type m: int
:param n:
    Matrix column dimension.
:type n: int
:param matvect:
    Function to apply the matrix transpose to a vector, with call signature
    `y = matvect(x)`, where `x` and `y` are the input and output vectors,
    respectively.
:type matvect: function
:param matvec:
    Function to apply the matrix to a vector, with call signature
    `y = matvec(x)`, where `x` and `y` are the input and output vectors,
    respectively.
:type matvec: function
:param its:
    Number of power method iterations.
:type its: int

:return:
    Spectral norm estimate.
:rtype: float


A = np.asfortranarray(A)<EOL>m, n = A.shape<EOL>n2, w = idz_frmi(m)<EOL>proj = np.empty(n*(<NUM_LIT:2>*n2 + <NUM_LIT:1>) + n2 + <NUM_LIT:1>, dtype='<STR_LIT>', order='<STR_LIT:F>')<EOL>k, idx, proj = _id.idzp_aid(eps, A, w, proj)<EOL>proj = proj[:k*(n-k)].reshape((k, n-k), order='<STR_LIT:F>')<EOL>return k, idx, proj<EOL>

Compute ID of a complex matrix to a specified relative precision using
random sampling.

:param eps:
    Relative precision.
:type eps: float
:param A:
    Matrix.
:type A: :class:`numpy.ndarray`

:return:
    Rank of ID.
:rtype: int
:return:
    Column index array.
:rtype: :class:`numpy.ndarray`
:return:
    Interpolation coefficients.
:rtype: :class:`numpy.ndarray`


def rq(a, overwrite_a=False, lwork=None, mode='<STR_LIT>', check_finite=True):

if mode not in ['<STR_LIT>', '<STR_LIT:r>', '<STR_LIT>']:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>")<EOL><DEDENT>if check_finite:<EOL><INDENT>a1 = numpy.asarray_chkfinite(a)<EOL><DEDENT>else:<EOL><INDENT>a1 = numpy.asarray(a)<EOL><DEDENT>if len(a1.shape) != <NUM_LIT:2>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>M, N = a1.shape<EOL>overwrite_a = overwrite_a or (_datacopied(a1, a))<EOL>gerqf, = get_lapack_funcs(('<STR_LIT>',), (a1,))<EOL>if lwork is None or lwork == -<NUM_LIT:1>:<EOL><INDENT>rq, tau, work, info = gerqf(a1, lwork=-<NUM_LIT:1>, overwrite_a=<NUM_LIT:1>)<EOL>lwork = work[<NUM_LIT:0>].real.astype(numpy.int)<EOL><DEDENT>rq, tau, work, info = gerqf(a1, lwork=lwork, overwrite_a=overwrite_a)<EOL>if info < <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>% -info)<EOL><DEDENT>if not mode == '<STR_LIT>' or N < M:<EOL><INDENT>R = numpy.triu(rq, N-M)<EOL><DEDENT>else:<EOL><INDENT>R = numpy.triu(rq[-M:, -M:])<EOL><DEDENT>if mode == '<STR_LIT:r>':<EOL><INDENT>return R<EOL><DEDENT>gor_un_grq, = get_lapack_funcs(('<STR_LIT>',), (rq,))<EOL>if N < M:<EOL><INDENT>Q, work, info = gor_un_grq(rq[-N:], tau, lwork=-<NUM_LIT:1>, overwrite_a=<NUM_LIT:1>)<EOL>lwork = work[<NUM_LIT:0>].real.astype(numpy.int)<EOL>Q, work, info = gor_un_grq(rq[-N:], tau, lwork=lwork, overwrite_a=<NUM_LIT:1>)<EOL><DEDENT>elif mode == '<STR_LIT>':<EOL><INDENT>Q, work, info = gor_un_grq(rq, tau, lwork=-<NUM_LIT:1>, overwrite_a=<NUM_LIT:1>)<EOL>lwork = work[<NUM_LIT:0>].real.astype(numpy.int)<EOL>Q, work, info = gor_un_grq(rq, tau, lwork=lwork, overwrite_a=<NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>rq1 = numpy.empty((N, N), dtype=rq.dtype)<EOL>rq1[-M:] = rq<EOL>Q, work, info = gor_un_grq(rq1, tau, lwork=-<NUM_LIT:1>, overwrite_a=<NUM_LIT:1>)<EOL>lwork = work[<NUM_LIT:0>].real.astype(numpy.int)<EOL>Q, work, info = gor_un_grq(rq1, tau, lwork=lwork, overwrite_a=<NUM_LIT:1>)<EOL><DEDENT>if info < <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>% -info)<EOL><DEDENT>return R, Q<EOL>

Compute RQ decomposition of a matrix.

Calculate the decomposition ``A = R Q`` where Q is unitary/orthogonal
and R upper triangular.

Parameters
----------
a : (M, N) array_like
    Matrix to be decomposed
overwrite_a : bool, optional
    Whether data in a is overwritten (may improve performance)
lwork : int, optional
    Work array size, lwork >= a.shape[1]. If None or -1, an optimal size
    is computed.
mode : {'full', 'r', 'economic'}, optional
    Determines what information is to be returned: either both Q and R
    ('full', default), only R ('r') or both Q and R but computed in
    economy-size ('economic', see Notes).
check_finite : bool, optional
    Whether to check that the input matrix contains only finite numbers.
    Disabling may give a performance gain, but may result in problems
    (crashes, non-termination) if the inputs do contain infinities or NaNs.

Returns
-------
R : float or complex ndarray
    Of shape (M, N) or (M, K) for ``mode='economic'``.  ``K = min(M, N)``.
Q : float or complex ndarray
    Of shape (N, N) or (K, N) for ``mode='economic'``.  Not returned
    if ``mode='r'``.

Raises
------
LinAlgError
    If decomposition fails.

Notes
-----
This is an interface to the LAPACK routines sgerqf, dgerqf, cgerqf, zgerqf,
sorgrq, dorgrq, cungrq and zungrq.

If ``mode=economic``, the shapes of Q and R are (K, N) and (M, K) instead
of (N,N) and (M,N), with ``K=min(M,N)``.

Examples
--------
>>> from scipy import linalg
>>> from numpy import random, dot, allclose
>>> a = random.randn(6, 9)
>>> r, q = linalg.rq(a)
>>> allclose(a, dot(r, q))
True
>>> r.shape, q.shape
((6, 9), (9, 9))
>>> r2 = linalg.rq(a, mode='r')
>>> allclose(r, r2)
True
>>> r3, q3 = linalg.rq(a, mode='economic')
>>> r3.shape, q3.shape
((6, 6), (6, 9))


def _make_complex_eigvecs(w, vin, dtype):

<EOL>v = numpy.array(vin, dtype=dtype)<EOL>m = (w.imag > <NUM_LIT:0>)<EOL>m[:-<NUM_LIT:1>] |= (w.imag[<NUM_LIT:1>:] < <NUM_LIT:0>)  <EOL>for i in flatnonzero(m):<EOL><INDENT>v.imag[:,i] = vin[:,i+<NUM_LIT:1>]<EOL>conj(v[:,i], v[:,i+<NUM_LIT:1>])<EOL><DEDENT>return v<EOL>

Produce complex-valued eigenvectors from LAPACK DGGEV real-valued output


def eigh(a, b=None, lower=True, eigvals_only=False, overwrite_a=False,<EOL>overwrite_b=False, turbo=True, eigvals=None, type=<NUM_LIT:1>,<EOL>check_finite=True):

if check_finite:<EOL><INDENT>a1 = asarray_chkfinite(a)<EOL><DEDENT>else:<EOL><INDENT>a1 = asarray(a)<EOL><DEDENT>if len(a1.shape) != <NUM_LIT:2> or a1.shape[<NUM_LIT:0>] != a1.shape[<NUM_LIT:1>]:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>overwrite_a = overwrite_a or (_datacopied(a1, a))<EOL>if iscomplexobj(a1):<EOL><INDENT>cplx = True<EOL><DEDENT>else:<EOL><INDENT>cplx = False<EOL><DEDENT>if b is not None:<EOL><INDENT>if check_finite:<EOL><INDENT>b1 = asarray_chkfinite(b)<EOL><DEDENT>else:<EOL><INDENT>b1 = asarray(b)<EOL><DEDENT>overwrite_b = overwrite_b or _datacopied(b1, b)<EOL>if len(b1.shape) != <NUM_LIT:2> or b1.shape[<NUM_LIT:0>] != b1.shape[<NUM_LIT:1>]:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if b1.shape != a1.shape:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>" % (str(b1.shape), str(a1.shape)))<EOL><DEDENT>if iscomplexobj(b1):<EOL><INDENT>cplx = True<EOL><DEDENT>else:<EOL><INDENT>cplx = cplx or False<EOL><DEDENT><DEDENT>else:<EOL><INDENT>b1 = None<EOL><DEDENT>_job = (eigvals_only and '<STR_LIT:N>') or '<STR_LIT>'<EOL>if eigvals is not None:<EOL><INDENT>lo, hi = eigvals<EOL>if lo < <NUM_LIT:0> or hi >= a1.shape[<NUM_LIT:0>]:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>' % (<NUM_LIT:0>, a1.shape[<NUM_LIT:0>]-<NUM_LIT:1>))<EOL><DEDENT>lo += <NUM_LIT:1><EOL>hi += <NUM_LIT:1><EOL>eigvals = (lo, hi)<EOL><DEDENT>if lower:<EOL><INDENT>uplo = '<STR_LIT:L>'<EOL><DEDENT>else:<EOL><INDENT>uplo = '<STR_LIT>'<EOL><DEDENT>if cplx:<EOL><INDENT>pfx = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>pfx = '<STR_LIT>'<EOL><DEDENT>if b1 is None:<EOL><INDENT>(evr,) = get_lapack_funcs((pfx+'<STR_LIT>',), (a1,))<EOL>if eigvals is None:<EOL><INDENT>w, v, info = evr(a1, uplo=uplo, jobz=_job, range="<STR_LIT:A>", il=<NUM_LIT:1>,<EOL>iu=a1.shape[<NUM_LIT:0>], overwrite_a=overwrite_a)<EOL><DEDENT>else:<EOL><INDENT>(lo, hi) = eigvals<EOL>w_tot, v, info = evr(a1, uplo=uplo, jobz=_job, range="<STR_LIT:I>",<EOL>il=lo, iu=hi, overwrite_a=overwrite_a)<EOL>w = w_tot[<NUM_LIT:0>:hi-lo+<NUM_LIT:1>]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if eigvals is not None:<EOL><INDENT>(gvx,) = get_lapack_funcs((pfx+'<STR_LIT>',), (a1,b1))<EOL>(lo, hi) = eigvals<EOL>w_tot, v, ifail, info = gvx(a1, b1, uplo=uplo, iu=hi,<EOL>itype=type,jobz=_job, il=lo,<EOL>overwrite_a=overwrite_a,<EOL>overwrite_b=overwrite_b)<EOL>w = w_tot[<NUM_LIT:0>:hi-lo+<NUM_LIT:1>]<EOL><DEDENT>elif turbo:<EOL><INDENT>(gvd,) = get_lapack_funcs((pfx+'<STR_LIT>',), (a1,b1))<EOL>v, w, info = gvd(a1, b1, uplo=uplo, itype=type, jobz=_job,<EOL>overwrite_a=overwrite_a,<EOL>overwrite_b=overwrite_b)<EOL><DEDENT>else:<EOL><INDENT>(gv,) = get_lapack_funcs((pfx+'<STR_LIT>',), (a1,b1))<EOL>v, w, info = gv(a1, b1, uplo=uplo, itype=type, jobz=_job,<EOL>overwrite_a=overwrite_a,<EOL>overwrite_b=overwrite_b)<EOL><DEDENT><DEDENT>if info == <NUM_LIT:0>:<EOL><INDENT>if eigvals_only:<EOL><INDENT>return w<EOL><DEDENT>else:<EOL><INDENT>return w, v<EOL><DEDENT><DEDENT>elif info < <NUM_LIT:0>:<EOL><INDENT>raise LinAlgError("<STR_LIT>"<EOL>"<STR_LIT>" % (-info))<EOL><DEDENT>elif info > <NUM_LIT:0> and b1 is None:<EOL><INDENT>raise LinAlgError("<STR_LIT>")<EOL><DEDENT>elif info > <NUM_LIT:0> and info <= b1.shape[<NUM_LIT:0>]:<EOL><INDENT>if eigvals is not None:<EOL><INDENT>raise LinAlgError("<STR_LIT>"<EOL>"<STR_LIT>" % nonzero(ifail)-<NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>raise LinAlgError("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % info)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise LinAlgError("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % (info-b1.shape[<NUM_LIT:0>]))<EOL><DEDENT>

Solve an ordinary or generalized eigenvalue problem for a complex
Hermitian or real symmetric matrix.

Find eigenvalues w and optionally eigenvectors v of matrix `a`, where
`b` is positive definite::

                  a v[:,i] = w[i] b v[:,i]
    v[i,:].conj() a v[:,i] = w[i]
    v[i,:].conj() b v[:,i] = 1

Parameters
----------
a : (M, M) array_like
    A complex Hermitian or real symmetric matrix whose eigenvalues and
    eigenvectors will be computed.
b : (M, M) array_like, optional
    A complex Hermitian or real symmetric definite positive matrix in.
    If omitted, identity matrix is assumed.
lower : bool, optional
    Whether the pertinent array data is taken from the lower or upper
    triangle of `a`. (Default: lower)
eigvals_only : bool, optional
    Whether to calculate only eigenvalues and no eigenvectors.
    (Default: both are calculated)
turbo : bool, optional
    Use divide and conquer algorithm (faster but expensive in memory,
    only for generalized eigenvalue problem and if eigvals=None)
eigvals : tuple (lo, hi), optional
    Indexes of the smallest and largest (in ascending order) eigenvalues
    and corresponding eigenvectors to be returned: 0 <= lo <= hi <= M-1.
    If omitted, all eigenvalues and eigenvectors are returned.
type : int, optional
    Specifies the problem type to be solved:

       type = 1: a   v[:,i] = w[i] b v[:,i]

       type = 2: a b v[:,i] = w[i]   v[:,i]

       type = 3: b a v[:,i] = w[i]   v[:,i]
overwrite_a : bool, optional
    Whether to overwrite data in `a` (may improve performance)
overwrite_b : bool, optional
    Whether to overwrite data in `b` (may improve performance)
check_finite : boolean, optional
    Whether to check that the input matrices contain only finite numbers.
    Disabling may give a performance gain, but may result in problems
    (crashes, non-termination) if the inputs do contain infinities or NaNs.

Returns
-------
w : (N,) float ndarray
    The N (1<=N<=M) selected eigenvalues, in ascending order, each
    repeated according to its multiplicity.
v : (M, N) complex ndarray
    (if eigvals_only == False)

    The normalized selected eigenvector corresponding to the
    eigenvalue w[i] is the column v[:,i].

    Normalization:

        type 1 and 3: v.conj() a      v  = w

        type 2: inv(v).conj() a  inv(v) = w

        type = 1 or 2: v.conj() b      v  = I

        type = 3: v.conj() inv(b) v  = I

Raises
------
LinAlgError :
    If eigenvalue computation does not converge,
    an error occurred, or b matrix is not definite positive. Note that
    if input matrices are not symmetric or hermitian, no error is reported
    but results will be wrong.

See Also
--------
eig : eigenvalues and right eigenvectors for non-symmetric arrays


def eig_banded(a_band, lower=False, eigvals_only=False, overwrite_a_band=False,<EOL>select='<STR_LIT:a>', select_range=None, max_ev=<NUM_LIT:0>, check_finite=True):

if eigvals_only or overwrite_a_band:<EOL><INDENT>if check_finite:<EOL><INDENT>a1 = asarray_chkfinite(a_band)<EOL><DEDENT>else:<EOL><INDENT>a1 = asarray(a_band)<EOL><DEDENT>overwrite_a_band = overwrite_a_band or (_datacopied(a1, a_band))<EOL><DEDENT>else:<EOL><INDENT>a1 = array(a_band)<EOL>if issubclass(a1.dtype.type, inexact) and not isfinite(a1).all():<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>overwrite_a_band = <NUM_LIT:1><EOL><DEDENT>if len(a1.shape) != <NUM_LIT:2>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if select.lower() not in [<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:2>, '<STR_LIT:a>', '<STR_LIT:v>', '<STR_LIT:i>', '<STR_LIT:all>', '<STR_LIT:value>', '<STR_LIT:index>']:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if select.lower() in [<NUM_LIT:0>, '<STR_LIT:a>', '<STR_LIT:all>']:<EOL><INDENT>if a1.dtype.char in '<STR_LIT>':<EOL><INDENT>bevd, = get_lapack_funcs(('<STR_LIT>',), (a1,))<EOL>internal_name = '<STR_LIT>'<EOL><DEDENT>else:  <EOL><INDENT>bevd, = get_lapack_funcs(('<STR_LIT>',), (a1,))<EOL>internal_name = '<STR_LIT>'<EOL><DEDENT>w,v,info = bevd(a1, compute_v=not eigvals_only,<EOL>lower=lower,<EOL>overwrite_ab=overwrite_a_band)<EOL><DEDENT>if select.lower() in [<NUM_LIT:1>, <NUM_LIT:2>, '<STR_LIT:i>', '<STR_LIT:v>', '<STR_LIT:index>', '<STR_LIT:value>']:<EOL><INDENT>if select.lower() in [<NUM_LIT:2>, '<STR_LIT:i>', '<STR_LIT:index>']:<EOL><INDENT>select = <NUM_LIT:2><EOL>vl, vu, il, iu = <NUM_LIT:0.0>, <NUM_LIT:0.0>, min(select_range), max(select_range)<EOL>if min(il, iu) < <NUM_LIT:0> or max(il, iu) >= a1.shape[<NUM_LIT:1>]:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>max_ev = iu - il + <NUM_LIT:1><EOL><DEDENT>else:  <EOL><INDENT>select = <NUM_LIT:1><EOL>vl, vu, il, iu = min(select_range), max(select_range), <NUM_LIT:0>, <NUM_LIT:0><EOL>if max_ev == <NUM_LIT:0>:<EOL><INDENT>max_ev = a_band.shape[<NUM_LIT:1>]<EOL><DEDENT><DEDENT>if eigvals_only:<EOL><INDENT>max_ev = <NUM_LIT:1><EOL><DEDENT>if a1.dtype.char in '<STR_LIT>':  <EOL><INDENT>lamch, = get_lapack_funcs(('<STR_LIT>',), (array(<NUM_LIT:0>, dtype='<STR_LIT:f>'),))<EOL><DEDENT>else:<EOL><INDENT>lamch, = get_lapack_funcs(('<STR_LIT>',), (array(<NUM_LIT:0>, dtype='<STR_LIT:d>'),))<EOL><DEDENT>abstol = <NUM_LIT:2> * lamch('<STR_LIT:s>')<EOL>if a1.dtype.char in '<STR_LIT>':<EOL><INDENT>bevx, = get_lapack_funcs(('<STR_LIT>',), (a1,))<EOL>internal_name = '<STR_LIT>'<EOL><DEDENT>else:  <EOL><INDENT>bevx, = get_lapack_funcs(('<STR_LIT>',), (a1,))<EOL>internal_name = '<STR_LIT>'<EOL><DEDENT>w, v, m, ifail, info = bevx(a1, vl, vu, il+<NUM_LIT:1>, iu+<NUM_LIT:1>,<EOL>compute_v=not eigvals_only,<EOL>mmax=max_ev,<EOL>range=select, lower=lower,<EOL>overwrite_ab=overwrite_a_band,<EOL>abstol=abstol)<EOL>w = w[:m]<EOL>if not eigvals_only:<EOL><INDENT>v = v[:, :m]<EOL><DEDENT><DEDENT>if info < <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>% (-info, internal_name))<EOL><DEDENT>if info > <NUM_LIT:0>:<EOL><INDENT>raise LinAlgError("<STR_LIT>")<EOL><DEDENT>if eigvals_only:<EOL><INDENT>return w<EOL><DEDENT>return w, v<EOL>

Solve real symmetric or complex hermitian band matrix eigenvalue problem.

Find eigenvalues w and optionally right eigenvectors v of a::

    a v[:,i] = w[i] v[:,i]
    v.H v    = identity

The matrix a is stored in a_band either in lower diagonal or upper
diagonal ordered form:

    a_band[u + i - j, j] == a[i,j]        (if upper form; i <= j)
    a_band[    i - j, j] == a[i,j]        (if lower form; i >= j)

where u is the number of bands above the diagonal.

Example of a_band (shape of a is (6,6), u=2)::

    upper form:
    *   *   a02 a13 a24 a35
    *   a01 a12 a23 a34 a45
    a00 a11 a22 a33 a44 a55

    lower form:
    a00 a11 a22 a33 a44 a55
    a10 a21 a32 a43 a54 *
    a20 a31 a42 a53 *   *

Cells marked with * are not used.

Parameters
----------
a_band : (u+1, M) array_like
    The bands of the M by M matrix a.
lower : bool, optional
    Is the matrix in the lower form. (Default is upper form)
eigvals_only : bool, optional
    Compute only the eigenvalues and no eigenvectors.
    (Default: calculate also eigenvectors)
overwrite_a_band : bool, optional
    Discard data in a_band (may enhance performance)
select : {'a', 'v', 'i'}, optional
    Which eigenvalues to calculate

    ======  ========================================
    select  calculated
    ======  ========================================
    'a'     All eigenvalues
    'v'     Eigenvalues in the interval (min, max]
    'i'     Eigenvalues with indices min <= i <= max
    ======  ========================================
select_range : (min, max), optional
    Range of selected eigenvalues
max_ev : int, optional
    For select=='v', maximum number of eigenvalues expected.
    For other values of select, has no meaning.

    In doubt, leave this parameter untouched.

check_finite : boolean, optional
    Whether to check that the input matrix contains only finite numbers.
    Disabling may give a performance gain, but may result in problems
    (crashes, non-termination) if the inputs do contain infinities or NaNs.

Returns
-------
w : (M,) ndarray
    The eigenvalues, in ascending order, each repeated according to its
    multiplicity.
v : (M, M) float or complex ndarray
    The normalized eigenvector corresponding to the eigenvalue w[i] is
    the column v[:,i].

Raises LinAlgError if eigenvalue computation does not converge


def eig(a, b=None, left=False, right=True, overwrite_a=False,<EOL>overwrite_b=False, check_finite=True):

if check_finite:<EOL><INDENT>a1 = asarray_chkfinite(a)<EOL><DEDENT>else:<EOL><INDENT>a1 = asarray(a)<EOL><DEDENT>if len(a1.shape) != <NUM_LIT:2> or a1.shape[<NUM_LIT:0>] != a1.shape[<NUM_LIT:1>]:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>overwrite_a = overwrite_a or (_datacopied(a1, a))<EOL>if b is not None:<EOL><INDENT>if check_finite:<EOL><INDENT>b1 = asarray_chkfinite(b)<EOL><DEDENT>else:<EOL><INDENT>b1 = asarray(b)<EOL><DEDENT>overwrite_b = overwrite_b or _datacopied(b1, b)<EOL>if len(b1.shape) != <NUM_LIT:2> or b1.shape[<NUM_LIT:0>] != b1.shape[<NUM_LIT:1>]:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if b1.shape != a1.shape:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return _geneig(a1, b1, left, right, overwrite_a, overwrite_b)<EOL><DEDENT>geev, geev_lwork = get_lapack_funcs(('<STR_LIT>', '<STR_LIT>'), (a1,))<EOL>compute_vl, compute_vr = left, right<EOL>lwork, info = geev_lwork(a1.shape[<NUM_LIT:0>],<EOL>compute_vl=compute_vl,<EOL>compute_vr=compute_vr)<EOL>if info != <NUM_LIT:0>:<EOL><INDENT>raise LinAlgError("<STR_LIT>" % (info,))<EOL><DEDENT>lwork = int(lwork.real)<EOL>if geev.typecode in '<STR_LIT>':<EOL><INDENT>w, vl, vr, info = geev(a1, lwork=lwork,<EOL>compute_vl=compute_vl,<EOL>compute_vr=compute_vr,<EOL>overwrite_a=overwrite_a)<EOL><DEDENT>else:<EOL><INDENT>wr, wi, vl, vr, info = geev(a1, lwork=lwork,<EOL>compute_vl=compute_vl,<EOL>compute_vr=compute_vr,<EOL>overwrite_a=overwrite_a)<EOL>t = {'<STR_LIT:f>':'<STR_LIT:F>','<STR_LIT:d>':'<STR_LIT:D>'}[wr.dtype.char]<EOL>w = wr + _I * wi<EOL><DEDENT>if info < <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>% -info)<EOL><DEDENT>if info > <NUM_LIT:0>:<EOL><INDENT>raise LinAlgError("<STR_LIT>"<EOL>"<STR_LIT>" % info)<EOL><DEDENT>only_real = numpy.logical_and.reduce(numpy.equal(w.imag, <NUM_LIT:0.0>))<EOL>if not (geev.typecode in '<STR_LIT>' or only_real):<EOL><INDENT>t = w.dtype.char<EOL>if left:<EOL><INDENT>vl = _make_complex_eigvecs(w, vl, t)<EOL><DEDENT>if right:<EOL><INDENT>vr = _make_complex_eigvecs(w, vr, t)<EOL><DEDENT><DEDENT>if not (left or right):<EOL><INDENT>return w<EOL><DEDENT>if left:<EOL><INDENT>if right:<EOL><INDENT>return w, vl, vr<EOL><DEDENT>return w, vl<EOL><DEDENT>return w, vr<EOL>

Solve an ordinary or generalized eigenvalue problem of a square matrix.

Find eigenvalues w and right or left eigenvectors of a general matrix::

    a   vr[:,i] = w[i]        b   vr[:,i]
    a.H vl[:,i] = w[i].conj() b.H vl[:,i]

where ``.H`` is the Hermitian conjugation.

Parameters
----------
a : (M, M) array_like
    A complex or real matrix whose eigenvalues and eigenvectors
    will be computed.
b : (M, M) array_like, optional
    Right-hand side matrix in a generalized eigenvalue problem.
    Default is None, identity matrix is assumed.
left : bool, optional
    Whether to calculate and return left eigenvectors.  Default is False.
right : bool, optional
    Whether to calculate and return right eigenvectors.  Default is True.
overwrite_a : bool, optional
    Whether to overwrite `a`; may improve performance.  Default is False.
overwrite_b : bool, optional
    Whether to overwrite `b`; may improve performance.  Default is False.
check_finite : boolean, optional
    Whether to check that the input matrices contain only finite numbers.
    Disabling may give a performance gain, but may result in problems
    (crashes, non-termination) if the inputs do contain infinities or NaNs.

Returns
-------
w : (M,) double or complex ndarray
    The eigenvalues, each repeated according to its multiplicity.
vl : (M, M) double or complex ndarray
    The normalized left eigenvector corresponding to the eigenvalue
    ``w[i]`` is the column vl[:,i]. Only returned if ``left=True``.
vr : (M, M) double or complex ndarray
    The normalized right eigenvector corresponding to the eigenvalue
    ``w[i]`` is the column ``vr[:,i]``.  Only returned if ``right=True``.

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

See Also
--------
eigh : Eigenvalues and right eigenvectors for symmetric/Hermitian arrays.


def pinv2(a, cond=None, rcond=None, return_rank=False, check_finite=True):

if check_finite:<EOL><INDENT>a = np.asarray_chkfinite(a)<EOL><DEDENT>else:<EOL><INDENT>a = np.asarray(a)<EOL><DEDENT>u, s, vh = decomp_svd.svd(a, full_matrices=False, check_finite=False)<EOL>if rcond is not None:<EOL><INDENT>cond = rcond<EOL><DEDENT>if cond in [None,-<NUM_LIT:1>]:<EOL><INDENT>t = u.dtype.char.lower()<EOL>factor = {'<STR_LIT:f>': <NUM_LIT>, '<STR_LIT:d>': <NUM_LIT>}<EOL>cond = factor[t] * np.finfo(t).eps<EOL><DEDENT>rank = np.sum(s > cond * np.max(s))<EOL>psigma_diag = <NUM_LIT:1.0> / s[: rank]<EOL>B = np.transpose(np.conjugate(np.dot(u[:, : rank] *<EOL>psigma_diag, vh[: rank])))<EOL>if return_rank:<EOL><INDENT>return B, rank<EOL><DEDENT>else:<EOL><INDENT>return B<EOL><DEDENT>

Compute the (Moore-Penrose) pseudo-inverse of a matrix.

Calculate a generalized inverse of a matrix using its
singular-value decomposition and including all 'large' singular
values.

Parameters
----------
a : (M, N) array_like
    Matrix to be pseudo-inverted.
cond, rcond : float or None
    Cutoff for 'small' singular values.
    Singular values smaller than ``rcond*largest_singular_value``
    are considered zero.
    If None or -1, suitable machine precision is used.
return_rank : bool, optional
    if True, return the effective rank of the matrix
check_finite : boolean, optional
    Whether to check that the input matrix contains only finite numbers.
    Disabling may give a performance gain, but may result in problems
    (crashes, non-termination) if the inputs do contain infinities or NaNs.

Returns
-------
B : (N, M) ndarray
    The pseudo-inverse of matrix `a`.
rank : int
    The effective rank of the matrix.  Returned if return_rank == True

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

Examples
--------
>>> a = np.random.randn(9, 6)
>>> B = linalg.pinv2(a)
>>> np.allclose(a, dot(a, dot(B, a)))
True
>>> np.allclose(B, dot(B, dot(a, B)))
True


def lstsq(a, b, cond=None, overwrite_a=False, overwrite_b=False,<EOL>check_finite=True):

if check_finite:<EOL><INDENT>a1,b1 = map(np.asarray_chkfinite, (a,b))<EOL><DEDENT>else:<EOL><INDENT>a1,b1 = map(np.asarray, (a,b))<EOL><DEDENT>if len(a1.shape) != <NUM_LIT:2>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>m, n = a1.shape<EOL>if len(b1.shape) == <NUM_LIT:2>:<EOL><INDENT>nrhs = b1.shape[<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>nrhs = <NUM_LIT:1><EOL><DEDENT>if m != b1.shape[<NUM_LIT:0>]:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>gelss, = get_lapack_funcs(('<STR_LIT>',), (a1, b1))<EOL>if n > m:<EOL><INDENT>if len(b1.shape) == <NUM_LIT:2>:<EOL><INDENT>b2 = np.zeros((n, nrhs), dtype=gelss.dtype)<EOL>b2[:m,:] = b1<EOL><DEDENT>else:<EOL><INDENT>b2 = np.zeros(n, dtype=gelss.dtype)<EOL>b2[:m] = b1<EOL><DEDENT>b1 = b2<EOL><DEDENT>overwrite_a = overwrite_a or _datacopied(a1, a)<EOL>overwrite_b = overwrite_b or _datacopied(b1, b)<EOL>work = gelss(a1, b1, lwork=-<NUM_LIT:1>)[<NUM_LIT:4>]<EOL>lwork = work[<NUM_LIT:0>].real.astype(np.int)<EOL>v, x, s, rank, work, info = gelss(<EOL>a1, b1, cond=cond, lwork=lwork, overwrite_a=overwrite_a,<EOL>overwrite_b=overwrite_b)<EOL>if info > <NUM_LIT:0>:<EOL><INDENT>raise LinAlgError("<STR_LIT>")<EOL><DEDENT>if info < <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>% -info)<EOL><DEDENT>resids = np.asarray([], dtype=x.dtype)<EOL>if n < m:<EOL><INDENT>x1 = x[:n]<EOL>if rank == n:<EOL><INDENT>resids = np.sum(np.abs(x[n:])**<NUM_LIT:2>, axis=<NUM_LIT:0>)<EOL><DEDENT>x = x1<EOL><DEDENT>return x, resids, rank, s<EOL>

Compute least-squares solution to equation Ax = b.

Compute a vector x such that the 2-norm ``|b - A x|`` is minimized.

Parameters
----------
a : (M, N) array_like
    Left hand side matrix (2-D array).
b : (M,) or (M, K) array_like
    Right hand side matrix or vector (1-D or 2-D array).
cond : float, optional
    Cutoff for 'small' singular values; used to determine effective
    rank of a. Singular values smaller than
    ``rcond * largest_singular_value`` are considered zero.
overwrite_a : bool, optional
    Discard data in `a` (may enhance performance). Default is False.
overwrite_b : bool, optional
    Discard data in `b` (may enhance performance). Default is False.
check_finite : boolean, optional
    Whether to check that the input matrices contain only finite numbers.
    Disabling may give a performance gain, but may result in problems
    (crashes, non-termination) if the inputs do contain infinities or NaNs.

Returns
-------
x : (N,) or (N, K) ndarray
    Least-squares solution.  Return shape matches shape of `b`.
residues : () or (1,) or (K,) ndarray
    Sums of residues, squared 2-norm for each column in ``b - a x``.
    If rank of matrix a is < N or > M this is an empty array.
    If b was 1-D, this is an (1,) shape array, otherwise the shape is (K,).
rank : int
    Effective rank of matrix `a`.
s : (min(M,N),) ndarray
    Singular values of `a`. The condition number of a is
    ``abs(s[0]/s[-1])``.

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

See Also
--------
optimize.nnls : linear least squares with non-negativity constraint


def solve_triangular(a, b, trans=<NUM_LIT:0>, lower=False, unit_diagonal=False,<EOL>overwrite_b=False, debug=False, check_finite=True):

if check_finite:<EOL><INDENT>a1, b1 = map(np.asarray_chkfinite,(a,b))<EOL><DEDENT>else:<EOL><INDENT>a1, b1 = map(np.asarray, (a,b))<EOL><DEDENT>if len(a1.shape) != <NUM_LIT:2> or a1.shape[<NUM_LIT:0>] != a1.shape[<NUM_LIT:1>]:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if a1.shape[<NUM_LIT:0>] != b1.shape[<NUM_LIT:0>]:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>overwrite_b = overwrite_b or _datacopied(b1, b)<EOL>if debug:<EOL><INDENT>print('<STR_LIT>',overwrite_b)<EOL><DEDENT>trans = {'<STR_LIT:N>': <NUM_LIT:0>, '<STR_LIT:T>': <NUM_LIT:1>, '<STR_LIT:C>': <NUM_LIT:2>}.get(trans, trans)<EOL>trtrs, = get_lapack_funcs(('<STR_LIT>',), (a1,b1))<EOL>x, info = trtrs(a1, b1, overwrite_b=overwrite_b, lower=lower,<EOL>trans=trans, unitdiag=unit_diagonal)<EOL>if info == <NUM_LIT:0>:<EOL><INDENT>return x<EOL><DEDENT>if info > <NUM_LIT:0>:<EOL><INDENT>raise LinAlgError("<STR_LIT>" % (info-<NUM_LIT:1>))<EOL><DEDENT>raise ValueError('<STR_LIT>'<EOL>% -info)<EOL>

Solve the equation `a x = b` for `x`, assuming a is a triangular matrix.

Parameters
----------
a : (M, M) array_like
    A triangular matrix
b : (M,) or (M, N) array_like
    Right-hand side matrix in `a x = b`
lower : boolean
    Use only data contained in the lower triangle of `a`.
    Default is to use upper triangle.
trans : {0, 1, 2, 'N', 'T', 'C'}, optional
    Type of system to solve:

    ========  =========
    trans     system
    ========  =========
    0 or 'N'  a x  = b
    1 or 'T'  a^T x = b
    2 or 'C'  a^H x = b
    ========  =========
unit_diagonal : bool, optional
    If True, diagonal elements of `a` are assumed to be 1 and
    will not be referenced.
overwrite_b : bool, optional
    Allow overwriting data in `b` (may enhance performance)
check_finite : bool, optional
    Whether to check that the input matrices contain only finite numbers.
    Disabling may give a performance gain, but may result in problems
    (crashes, non-termination) if the inputs do contain infinities or NaNs.

Returns
-------
x : (M,) or (M, N) ndarray
    Solution to the system `a x = b`.  Shape of return matches `b`.

Raises
------
LinAlgError
    If `a` is singular

Notes
-----
.. versionadded:: 0.9.0


def pinv(a, cond=None, rcond=None, return_rank=False, check_finite=True):

if check_finite:<EOL><INDENT>a = np.asarray_chkfinite(a)<EOL><DEDENT>else:<EOL><INDENT>a = np.asarray(a)<EOL><DEDENT>b = np.identity(a.shape[<NUM_LIT:0>], dtype=a.dtype)<EOL>if rcond is not None:<EOL><INDENT>cond = rcond<EOL><DEDENT>x, resids, rank, s = lstsq(a, b, cond=cond, check_finite=False)<EOL>if return_rank:<EOL><INDENT>return x, rank<EOL><DEDENT>else:<EOL><INDENT>return x<EOL><DEDENT>

Compute the (Moore-Penrose) pseudo-inverse of a matrix.

Calculate a generalized inverse of a matrix using a least-squares
solver.

Parameters
----------
a : (M, N) array_like
    Matrix to be pseudo-inverted.
cond, rcond : float, optional
    Cutoff for 'small' singular values in the least-squares solver.
    Singular values smaller than ``rcond * largest_singular_value``
    are considered zero.
return_rank : bool, optional
    if True, return the effective rank of the matrix
check_finite : boolean, optional
    Whether to check that the input matrix contains only finite numbers.
    Disabling may give a performance gain, but may result in problems
    (crashes, non-termination) if the inputs do contain infinities or NaNs.

Returns
-------
B : (N, M) ndarray
    The pseudo-inverse of matrix `a`.
rank : int
    The effective rank of the matrix.  Returned if return_rank == True

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

Examples
--------
>>> a = np.random.randn(9, 6)
>>> B = linalg.pinv(a)
>>> np.allclose(a, dot(a, dot(B, a)))
True
>>> np.allclose(B, dot(B, dot(a, B)))
True


def pinvh(a, cond=None, rcond=None, lower=True, return_rank=False,<EOL>check_finite=True):

if check_finite:<EOL><INDENT>a = np.asarray_chkfinite(a)<EOL><DEDENT>else:<EOL><INDENT>a = np.asarray(a)<EOL><DEDENT>s, u = decomp.eigh(a, lower=lower, check_finite=False)<EOL>if rcond is not None:<EOL><INDENT>cond = rcond<EOL><DEDENT>if cond in [None, -<NUM_LIT:1>]:<EOL><INDENT>t = u.dtype.char.lower()<EOL>factor = {'<STR_LIT:f>': <NUM_LIT>, '<STR_LIT:d>': <NUM_LIT>}<EOL>cond = factor[t] * np.finfo(t).eps<EOL><DEDENT>above_cutoff = (abs(s) > cond * np.max(abs(s)))<EOL>psigma_diag = <NUM_LIT:1.0> / s[above_cutoff]<EOL>u = u[:, above_cutoff]<EOL>B = np.dot(u * psigma_diag, np.conjugate(u).T)<EOL>if return_rank:<EOL><INDENT>return B, len(psigma_diag)<EOL><DEDENT>else:<EOL><INDENT>return B<EOL><DEDENT>

Compute the (Moore-Penrose) pseudo-inverse of a Hermitian matrix.

Calculate a generalized inverse of a Hermitian or real symmetric matrix
using its eigenvalue decomposition and including all eigenvalues with
'large' absolute value.

Parameters
----------
a : (N, N) array_like
    Real symmetric or complex hermetian matrix to be pseudo-inverted
cond, rcond : float or None
    Cutoff for 'small' eigenvalues.
    Singular values smaller than rcond * largest_eigenvalue are considered
    zero.

    If None or -1, suitable machine precision is used.
lower : bool
    Whether the pertinent array data is taken from the lower or upper
    triangle of a. (Default: lower)
return_rank : bool, optional
    if True, return the effective rank of the matrix
check_finite : boolean, optional
    Whether to check that the input matrix contains only finite numbers.
    Disabling may give a performance gain, but may result in problems
    (crashes, non-termination) if the inputs do contain infinities or NaNs.

Returns
-------
B : (N, N) ndarray
    The pseudo-inverse of matrix `a`.
rank : int
    The effective rank of the matrix.  Returned if return_rank == True

Raises
------
LinAlgError
    If eigenvalue does not converge

Examples
--------
>>> import numpy as np
>>> a = np.random.randn(9, 6)
>>> a = np.dot(a, a.T)
>>> B = pinvh(a)
>>> np.allclose(a, np.dot(a, np.dot(B, a)))
True
>>> np.allclose(B, np.dot(B, np.dot(a, B)))
True


<EOL>if np.isrealobj(A) and np.iscomplexobj(B):<EOL><INDENT>if tol is None:<EOL><INDENT>tol = {<NUM_LIT:0>:feps*<NUM_LIT>, <NUM_LIT:1>:eps*<NUM_LIT>}[_array_precision[B.dtype.char]]<EOL><DEDENT>if np.allclose(B.imag, <NUM_LIT:0.0>, atol=tol):<EOL><INDENT>B = B.real<EOL><DEDENT><DEDENT>return B<EOL>

Return either B or the real part of B, depending on properties of A and B.

The motivation is that B has been computed as a complicated function of A,
and B may be perturbed by negligible imaginary components.
If A is real and B is complex with small imaginary components,
then return a real copy of B.  The assumption in that case would be that
the imaginary components of B are numerical artifacts.

Parameters
----------
A : ndarray
    Input array whose type is to be checked as real vs. complex.
B : ndarray
    Array to be returned, possibly without its imaginary part.
tol : float
    Absolute tolerance.

Returns
-------
out : real or complex array
    Either the input array B or only the real part of the input array B.


A = _asarray_square(A)<EOL>return _maybe_real(A, solve(cosm(A), sinm(A)))<EOL>

Compute the matrix tangent.

This routine uses expm to compute the matrix exponentials.

Parameters
----------
A : (N, N) array_like
    Input array.

Returns
-------
tanm : (N, N) ndarray
    Matrix tangent of `A`

Examples
--------
>>> from scipy.linalg import tanm, sinm, cosm
>>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
>>> t = tanm(a)
>>> t
array([[ -2.00876993,  -8.41880636],
       [ -2.80626879, -10.42757629]])

Verify tanm(a) = sinm(a).dot(inv(cosm(a)))

>>> s = sinm(a)
>>> c = cosm(a)
>>> s.dot(np.linalg.inv(c))
array([[ -2.00876993,  -8.41880636],
       [ -2.80626879, -10.42757629]])


A = _asarray_square(A)<EOL>n = A.shape[<NUM_LIT:0>]<EOL>t = A.dtype.char<EOL>if t not in ['<STR_LIT:f>','<STR_LIT:F>','<STR_LIT:d>','<STR_LIT:D>']:<EOL><INDENT>A = A.astype('<STR_LIT:d>')<EOL>t = '<STR_LIT:d>'<EOL><DEDENT>eA = np.identity(n, dtype=t)<EOL>trm = np.identity(n, dtype=t)<EOL>castfunc = cast[t]<EOL>for k in range(<NUM_LIT:1>, q):<EOL><INDENT>trm[:] = trm.dot(A) / castfunc(k)<EOL>eA += trm<EOL><DEDENT>return eA<EOL>

Compute the matrix exponential using Taylor series.

Parameters
----------
A : (N, N) array_like
    Matrix to be exponentiated
q : int
    Order of the Taylor series used is `q-1`

Returns
-------
expm3 : (N, N) ndarray
    Matrix exponential of `A`


A = _asarray_square(A)<EOL>t = A.dtype.char<EOL>if t not in ['<STR_LIT:f>','<STR_LIT:F>','<STR_LIT:d>','<STR_LIT:D>']:<EOL><INDENT>A = A.astype('<STR_LIT:d>')<EOL>t = '<STR_LIT:d>'<EOL><DEDENT>s, vr = eig(A)<EOL>vri = inv(vr)<EOL>r = dot(dot(vr, diag(exp(s))), vri)<EOL>if t in ['<STR_LIT:f>', '<STR_LIT:d>']:<EOL><INDENT>return r.real.astype(t)<EOL><DEDENT>else:<EOL><INDENT>return r.astype(t)<EOL><DEDENT>

Compute the matrix exponential using eigenvalue decomposition.

Parameters
----------
A : (N, N) array_like
    Matrix to be exponentiated

Returns
-------
expm2 : (N, N) ndarray
    Matrix exponential of `A`


lhs = kron(a, a.conj())<EOL>lhs = np.eye(lhs.shape[<NUM_LIT:0>]) - lhs<EOL>x = solve(lhs, q.flatten())<EOL>return np.reshape(x, q.shape)<EOL>

Solves the discrete Lyapunov equation directly.

This function is called by the `solve_discrete_lyapunov` function with
`method=direct`. It is not supposed to be called directly.


return solve_sylvester(a, a.conj().transpose(), q)<EOL>

Solves the continuous Lyapunov equation (AX + XA^H = Q) given the values
of A and Q using the Bartels-Stewart algorithm.

Parameters
----------
a : array_like
    A square matrix

q : array_like
    Right-hand side square matrix

Returns
-------
x : array_like
    Solution to the continuous Lyapunov equation

See Also
--------
solve_sylvester : computes the solution to the Sylvester equation

Notes
-----
Because the continuous Lyapunov equation is just a special form of the
Sylvester equation, this solver relies entirely on solve_sylvester for a
solution.

.. versionadded:: 0.11.0


<EOL>r,u = schur(a, output='<STR_LIT>')<EOL>s,v = schur(b.conj().transpose(), output='<STR_LIT>')<EOL>f = np.dot(np.dot(u.conj().transpose(), q), v)<EOL>trsyl, = get_lapack_funcs(('<STR_LIT>',), (r,s,f))<EOL>if trsyl is None:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>y, scale, info = trsyl(r, s, f, tranb='<STR_LIT:C>')<EOL>y = scale*y<EOL>if info < <NUM_LIT:0>:<EOL><INDENT>raise LinAlgError("<STR_LIT>" % (-info,))<EOL><DEDENT>return np.dot(np.dot(u, y), v.conj().transpose())<EOL>

Computes a solution (X) to the Sylvester equation (AX + XB = Q).

Parameters
----------
a : (M, M) array_like
    Leading matrix of the Sylvester equation
b : (N, N) array_like
    Trailing matrix of the Sylvester equation
q : (M, N) array_like
    Right-hand side

Returns
-------
x : (M, N) ndarray
    The solution to the Sylvester equation.

Raises
------
LinAlgError
    If solution was not found

Notes
-----
Computes a solution to the Sylvester matrix equation via the Bartels-
Stewart algorithm.  The A and B matrices first undergo Schur
decompositions.  The resulting matrices are used to construct an
alternative Sylvester equation (``RY + YS^T = F``) where the R and S
matrices are in quasi-triangular form (or, when R, S or F are complex,
triangular form).  The simplified equation is then solved using
``*TRSYL`` from LAPACK directly.

.. versionadded:: 0.11.0


try:<EOL><INDENT>g = inv(r)<EOL><DEDENT>except LinAlgError:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>g = np.dot(np.dot(b, g), b.conj().transpose())<EOL>try:<EOL><INDENT>ait = inv(a).conj().transpose()  <EOL><DEDENT>except LinAlgError:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>z11 = a+np.dot(np.dot(g, ait), q)<EOL>z12 = -<NUM_LIT:1.0>*np.dot(g, ait)<EOL>z21 = -<NUM_LIT:1.0>*np.dot(ait, q)<EOL>z22 = ait<EOL>z = np.vstack((np.hstack((z11, z12)), np.hstack((z21, z22))))<EOL>[s, u, sorted] = schur(z, sort='<STR_LIT>')<EOL>(m,n) = u.shape<EOL>u11 = u[<NUM_LIT:0>:m//<NUM_LIT:2>, <NUM_LIT:0>:n//<NUM_LIT:2>]<EOL>u21 = u[m//<NUM_LIT:2>:m, <NUM_LIT:0>:n//<NUM_LIT:2>]<EOL>u11i = inv(u11)<EOL>return np.dot(u21, u11i)<EOL>

Solves the disctrete algebraic Riccati equation, or DARE, defined as
(X = A'XA-(A'XB)(R+B'XB)^-1(B'XA)+Q), directly using a Schur decomposition
method.

Parameters
----------
a : (M, M) array_like
    Non-singular, square matrix
b : (M, N) array_like
    Input
q : (M, M) array_like
    Input
r : (N, N) array_like
    Non-singular, square matrix

Returns
-------
x : ndarray
    Solution to the continuous Lyapunov equation

See Also
--------
solve_continuous_are : Solves the continuous algebraic Riccati equation

Notes
-----
Method taken from:
Laub, "A Schur Method for Solving Algebraic Riccati Equations."
U.S. Energy Research and Development Agency under contract
ERDA-E(49-18)-2087.
http://dspace.mit.edu/bitstream/handle/1721.1/1301/R-0859-05666488.pdf

.. versionadded:: 0.11.0


c = np.asarray(c).ravel()<EOL>if r is None:<EOL><INDENT>r = np.zeros_like(c)<EOL><DEDENT>else:<EOL><INDENT>r = np.asarray(r).ravel()<EOL><DEDENT>vals = np.concatenate((c, r[<NUM_LIT:1>:]))<EOL>a, b = np.ogrid[<NUM_LIT:0>:len(c), <NUM_LIT:0>:len(r)]<EOL>indx = a + b<EOL>return vals[indx]<EOL>

Construct a Hankel matrix.

The Hankel matrix has constant anti-diagonals, with `c` as its
first column and `r` as its last row.  If `r` is not given, then
`r = zeros_like(c)` is assumed.

Parameters
----------
c : array_like
    First column of the matrix.  Whatever the actual shape of `c`, it
    will be converted to a 1-D array.
r : array_like
    Last row of the matrix. If None, ``r = zeros_like(c)`` is assumed.
    r[0] is ignored; the last row of the returned matrix is
    ``[c[-1], r[1:]]``.  Whatever the actual shape of `r`, it will be
    converted to a 1-D array.

Returns
-------
A : (len(c), len(r)) ndarray
    The Hankel matrix. Dtype is the same as ``(c[0] + r[0]).dtype``.

See also
--------
toeplitz : Toeplitz matrix
circulant : circulant matrix

Examples
--------
>>> from scipy.linalg import hankel
>>> hankel([1, 17, 99])
array([[ 1, 17, 99],
       [17, 99,  0],
       [99,  0,  0]])
>>> hankel([1,2,3,4], [4,7,7,8,9])
array([[1, 2, 3, 4, 7],
       [2, 3, 4, 7, 7],
       [3, 4, 7, 7, 8],
       [4, 7, 7, 8, 9]])


m = np.asarray(m)<EOL>out = (<NUM_LIT:1> - tri(m.shape[<NUM_LIT:0>], m.shape[<NUM_LIT:1>], k - <NUM_LIT:1>, m.dtype.char)) * m<EOL>return out<EOL>

Make a copy of a matrix with elements below the k-th diagonal zeroed.

Parameters
----------
m : array_like
    Matrix whose elements to return
k : int, optional
    Diagonal below which to zero elements.
    `k` == 0 is the main diagonal, `k` < 0 subdiagonal and
    `k` > 0 superdiagonal.

Returns
-------
triu : ndarray
    Return matrix with zeroed elements below the k-th diagonal and has
    same shape and type as `m`.

Examples
--------
>>> from scipy.linalg import triu
>>> triu([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1)
array([[ 1,  2,  3],
       [ 4,  5,  6],
       [ 0,  8,  9],
       [ 0,  0, 12]])


<EOL>if n < <NUM_LIT:1>:<EOL><INDENT>lg2 = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>lg2 = int(math.log(n, <NUM_LIT:2>))<EOL><DEDENT>if <NUM_LIT:2> ** lg2 != n:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>H = np.array([[<NUM_LIT:1>]], dtype=dtype)<EOL>for i in range(<NUM_LIT:0>, lg2):<EOL><INDENT>H = np.vstack((np.hstack((H, H)), np.hstack((H, -H))))<EOL><DEDENT>return H<EOL>

Construct a Hadamard matrix.

Constructs an n-by-n Hadamard matrix, using Sylvester's
construction.  `n` must be a power of 2.

Parameters
----------
n : int
    The order of the matrix.  `n` must be a power of 2.
dtype : numpy dtype
    The data type of the array to be constructed.

Returns
-------
H : (n, n) ndarray
    The Hadamard matrix.

Notes
-----
.. versionadded:: 0.8.0

Examples
--------
>>> from scipy.linalg import hadamard
>>> hadamard(2, dtype=complex)
array([[ 1.+0.j,  1.+0.j],
       [ 1.+0.j, -1.-0.j]])
>>> hadamard(4)
array([[ 1,  1,  1,  1],
       [ 1, -1,  1, -1],
       [ 1,  1, -1, -1],
       [ 1, -1, -1,  1]])


f = np.atleast_1d(f)<EOL>s = np.atleast_1d(s)<EOL>if f.ndim != <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if s.ndim != <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if f.size != s.size + <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if s.size == <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>tmp = f[<NUM_LIT:0>] + s[<NUM_LIT:0>]<EOL>n = f.size<EOL>a = np.zeros((n, n), dtype=tmp.dtype)<EOL>a[<NUM_LIT:0>] = f<EOL>a[list(range(<NUM_LIT:1>, n)), list(range(<NUM_LIT:0>, n - <NUM_LIT:1>))] = s<EOL>return a<EOL>

Create a Leslie matrix.

Given the length n array of fecundity coefficients `f` and the length
n-1 array of survival coefficents `s`, return the associated Leslie matrix.

Parameters
----------
f : (N,) array_like
    The "fecundity" coefficients.
s : (N-1,) array_like
    The "survival" coefficients, has to be 1-D.  The length of `s`
    must be one less than the length of `f`, and it must be at least 1.

Returns
-------
L : (N, N) ndarray
    The array is zero except for the first row,
    which is `f`, and the first sub-diagonal, which is `s`.
    The data-type of the array will be the data-type of ``f[0]+s[0]``.

Notes
-----
.. versionadded:: 0.8.0

The Leslie matrix is used to model discrete-time, age-structured
population growth [1]_ [2]_. In a population with `n` age classes, two sets
of parameters define a Leslie matrix: the `n` "fecundity coefficients",
which give the number of offspring per-capita produced by each age
class, and the `n` - 1 "survival coefficients", which give the
per-capita survival rate of each age class.

References
----------
.. [1] P. H. Leslie, On the use of matrices in certain population
       mathematics, Biometrika, Vol. 33, No. 3, 183--212 (Nov. 1945)
.. [2] P. H. Leslie, Some further notes on the use of matrices in
       population mathematics, Biometrika, Vol. 35, No. 3/4, 213--245
       (Dec. 1948)

Examples
--------
>>> from scipy.linalg import leslie
>>> leslie([0.1, 2.0, 1.0, 0.1], [0.2, 0.8, 0.7])
array([[ 0.1,  2. ,  1. ,  0.1],
       [ 0.2,  0. ,  0. ,  0. ],
       [ 0. ,  0.8,  0. ,  0. ],
       [ 0. ,  0. ,  0.7,  0. ]])


c = np.asarray(c).ravel()<EOL>if r is None:<EOL><INDENT>r = c.conjugate()<EOL><DEDENT>else:<EOL><INDENT>r = np.asarray(r).ravel()<EOL><DEDENT>vals = np.concatenate((r[-<NUM_LIT:1>:<NUM_LIT:0>:-<NUM_LIT:1>], c))<EOL>a, b = np.ogrid[<NUM_LIT:0>:len(c), len(r) - <NUM_LIT:1>:-<NUM_LIT:1>:-<NUM_LIT:1>]<EOL>indx = a + b<EOL>return vals[indx]<EOL>

Construct a Toeplitz matrix.

The Toeplitz matrix has constant diagonals, with c as its first column
and r as its first row.  If r is not given, ``r == conjugate(c)`` is
assumed.

Parameters
----------
c : array_like
    First column of the matrix.  Whatever the actual shape of `c`, it
    will be converted to a 1-D array.
r : array_like
    First row of the matrix. If None, ``r = conjugate(c)`` is assumed;
    in this case, if c[0] is real, the result is a Hermitian matrix.
    r[0] is ignored; the first row of the returned matrix is
    ``[c[0], r[1:]]``.  Whatever the actual shape of `r`, it will be
    converted to a 1-D array.

Returns
-------
A : (len(c), len(r)) ndarray
    The Toeplitz matrix. Dtype is the same as ``(c[0] + r[0]).dtype``.

See also
--------
circulant : circulant matrix
hankel : Hankel matrix

Notes
-----
The behavior when `c` or `r` is a scalar, or when `c` is complex and
`r` is None, was changed in version 0.8.0.  The behavior in previous
versions was undocumented and is no longer supported.

Examples
--------
>>> from scipy.linalg import toeplitz
>>> toeplitz([1,2,3], [1,4,5,6])
array([[1, 4, 5, 6],
       [2, 1, 4, 5],
       [3, 2, 1, 4]])
>>> toeplitz([1.0, 2+3j, 4-1j])
array([[ 1.+0.j,  2.-3.j,  4.+1.j],
       [ 2.+3.j,  1.+0.j,  2.-3.j],
       [ 4.-1.j,  2.+3.j,  1.+0.j]])


values = <NUM_LIT:1.0> / (<NUM_LIT:1.0> + np.arange(<NUM_LIT:2> * n - <NUM_LIT:1>))<EOL>h = hankel(values[:n], r=values[n - <NUM_LIT:1>:])<EOL>return h<EOL>

Create a Hilbert matrix of order `n`.

Returns the `n` by `n` array with entries `h[i,j] = 1 / (i + j + 1)`.

Parameters
----------
n : int
    The size of the array to create.

Returns
-------
h : (n, n) ndarray
    The Hilbert matrix.

See Also
--------
invhilbert : Compute the inverse of a Hilbert matrix.

Notes
-----
.. versionadded:: 0.10.0

Examples
--------
>>> from scipy.linalg import hilbert
>>> hilbert(3)
array([[ 1.        ,  0.5       ,  0.33333333],
       [ 0.5       ,  0.33333333,  0.25      ],
       [ 0.33333333,  0.25      ,  0.2       ]])


def kmeans(obs, k_or_guess, iter=<NUM_LIT:20>, thresh=<NUM_LIT>):

if int(iter) < <NUM_LIT:1>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if type(k_or_guess) == type(array([])):<EOL><INDENT>guess = k_or_guess<EOL>if guess.size < <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>" %<EOL>guess)<EOL><DEDENT>result = _kmeans(obs, guess, thresh=thresh)<EOL><DEDENT>else:<EOL><INDENT>best_dist = np.inf<EOL>No = obs.shape[<NUM_LIT:0>]<EOL>k = k_or_guess<EOL>if k < <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>for i in range(iter):<EOL><INDENT>guess = take(obs, randint(<NUM_LIT:0>, No, k), <NUM_LIT:0>)<EOL>book, dist = _kmeans(obs, guess, thresh=thresh)<EOL>if dist < best_dist:<EOL><INDENT>best_book = book<EOL>best_dist = dist<EOL><DEDENT><DEDENT>result = best_book, best_dist<EOL><DEDENT>return result<EOL>

Performs k-means on a set of observation vectors forming k clusters.

The k-means algorithm adjusts the centroids until sufficient
progress cannot be made, i.e. the change in distortion since
the last iteration is less than some threshold. This yields
a code book mapping centroids to codes and vice versa.

Distortion is defined as the sum of the squared differences
between the observations and the corresponding centroid.

Parameters
----------
obs : ndarray
   Each row of the M by N array is an observation vector. The
   columns are the features seen during each observation.
   The features must be whitened first with the `whiten` function.

k_or_guess : int or ndarray
   The number of centroids to generate. A code is assigned to
   each centroid, which is also the row index of the centroid
   in the code_book matrix generated.

   The initial k centroids are chosen by randomly selecting
   observations from the observation matrix. Alternatively,
   passing a k by N array specifies the initial k centroids.

iter : int, optional
   The number of times to run k-means, returning the codebook
   with the lowest distortion. This argument is ignored if
   initial centroids are specified with an array for the
   ``k_or_guess`` parameter. This parameter does not represent the
   number of iterations of the k-means algorithm.

thresh : float, optional
   Terminates the k-means algorithm if the change in
   distortion since the last k-means iteration is less than
   or equal to thresh.

Returns
-------
codebook : ndarray
   A k by N array of k centroids. The i'th centroid
   codebook[i] is represented with the code i. The centroids
   and codes generated represent the lowest distortion seen,
   not necessarily the globally minimal distortion.

distortion : float
   The distortion between the observations passed and the
   centroids generated.

See Also
--------
kmeans2 : a different implementation of k-means clustering
   with more methods for generating initial centroids but without
   using a distortion change threshold as a stopping criterion.

whiten : must be called prior to passing an observation matrix
   to kmeans.

Examples
--------
>>> from numpy import array
>>> from scipy.cluster.vq import vq, kmeans, whiten
>>> features  = array([[ 1.9,2.3],
...                    [ 1.5,2.5],
...                    [ 0.8,0.6],
...                    [ 0.4,1.8],
...                    [ 0.1,0.1],
...                    [ 0.2,1.8],
...                    [ 2.0,0.5],
...                    [ 0.3,1.5],
...                    [ 1.0,1.0]])
>>> whitened = whiten(features)
>>> book = array((whitened[0],whitened[2]))
>>> kmeans(whitened,book)
(array([[ 2.3110306 ,  2.86287398],
       [ 0.93218041,  1.24398691]]), 0.85684700941625547)

>>> from numpy import random
>>> random.seed((1000,2000))
>>> codes = 3
>>> kmeans(whitened,codes)
(array([[ 2.3110306 ,  2.86287398],
       [ 1.32544402,  0.65607529],
       [ 0.40782893,  2.02786907]]), 0.5196582527686241)


def init_rank1(data):<EOL><INDENT>mu = np.mean(data)<EOL>cov = np.cov(data)<EOL>x = np.random.randn(k)<EOL>x *= np.sqrt(cov)<EOL>x += mu<EOL>return x<EOL><DEDENT>def init_rankn(data):<EOL><INDENT>mu = np.mean(data, <NUM_LIT:0>)<EOL>cov = np.atleast_2d(np.cov(data, rowvar=<NUM_LIT:0>))<EOL>x = np.random.randn(k, mu.size)<EOL>x = np.dot(x, np.linalg.cholesky(cov).T) + mu<EOL>return x<EOL><DEDENT>nd = np.ndim(data)<EOL>if nd == <NUM_LIT:1>:<EOL><INDENT>return init_rank1(data)<EOL><DEDENT>else:<EOL><INDENT>return init_rankn(data)<EOL><DEDENT>

Returns k samples of a random variable which parameters depend on data.

    More precisely, it returns k observations sampled from a Gaussian random
    variable which mean and covariances are the one estimated from data.

    Parameters
    ----------
    data : ndarray
        Expect a rank 1 or 2 array. Rank 1 are assumed to describe one
        dimensional data, rank 2 multidimensional data, in which case one
        row is one observation.
    k : int
        Number of samples to generate.


seen_before = set([])<EOL>L2 = []<EOL>for i in L:<EOL><INDENT>if i not in seen_before:<EOL><INDENT>seen_before.add(i)<EOL>L2.append(i)<EOL><DEDENT><DEDENT>return L2<EOL>

Removes duplicates AND preserves the original order of the elements.
The set class is not guaranteed to do this.


Z = np.asarray(Z, order='<STR_LIT:c>')<EOL>T = np.asarray(T, order='<STR_LIT:c>')<EOL>if type(T) != np.ndarray or T.dtype != '<STR_LIT:i>':<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>is_valid_linkage(Z, throw=True, name='<STR_LIT>')<EOL>if len(T) != Z.shape[<NUM_LIT:0>] + <NUM_LIT:1>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>Cl = np.unique(T)<EOL>kk = len(Cl)<EOL>L = np.zeros((kk,), dtype='<STR_LIT:i>')<EOL>M = np.zeros((kk,), dtype='<STR_LIT:i>')<EOL>n = Z.shape[<NUM_LIT:0>] + <NUM_LIT:1><EOL>[Z, T] = _copy_arrays_if_base_present([Z, T])<EOL>s = _hierarchy.leaders(Z, T, L, M, int(kk), int(n))<EOL>if s >= <NUM_LIT:0>:<EOL><INDENT>raise ValueError(('<STR_LIT>'<EOL>'<STR_LIT>') % s)<EOL><DEDENT>return (L, M)<EOL>

Returns the root nodes in a hierarchical clustering.

Returns the root nodes in a hierarchical clustering corresponding
to a cut defined by a flat cluster assignment vector ``T``. See
the ``fcluster`` function for more information on the format of ``T``.

For each flat cluster :math:`j` of the :math:`k` flat clusters
represented in the n-sized flat cluster assignment vector ``T``,
this function finds the lowest cluster node :math:`i` in the linkage
tree Z such that:

  * leaf descendents belong only to flat cluster j
    (i.e. ``T[p]==j`` for all :math:`p` in :math:`S(i)` where
    :math:`S(i)` is the set of leaf ids of leaf nodes descendent
    with cluster node :math:`i`)

  * there does not exist a leaf that is not descendent with
    :math:`i` that also belongs to cluster :math:`j`
    (i.e. ``T[q]!=j`` for all :math:`q` not in :math:`S(i)`).  If
    this condition is violated, ``T`` is not a valid cluster
    assignment vector, and an exception will be thrown.

Parameters
----------
Z : ndarray
    The hierarchical clustering encoded as a matrix. See
    ``linkage`` for more information.
T : ndarray
    The flat cluster assignment vector.

Returns
-------
L : ndarray
    The leader linkage node id's stored as a k-element 1-D array
    where ``k`` is the number of flat clusters found in ``T``.

    ``L[j]=i`` is the linkage cluster node id that is the
    leader of flat cluster with id M[j].  If ``i < n``, ``i``
    corresponds to an original observation, otherwise it
    corresponds to a non-singleton cluster.

    For example: if ``L[3]=2`` and ``M[3]=8``, the flat cluster with
    id 8's leader is linkage node 2.
M : ndarray
    The leader linkage node id's stored as a k-element 1-D array where
    ``k`` is the number of flat clusters found in ``T``. This allows the
    set of flat cluster ids to be any arbitrary set of ``k`` integers.


if pnts >= <NUM_LIT:2>:<EOL><INDENT>D = np.random.rand(pnts * (pnts - <NUM_LIT:1>) / <NUM_LIT:2>)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>return D<EOL>

Generates a random distance matrix stored in condensed form. A
        pnts * (pnts - 1) / 2 sized vector is returned.


if a.base is not None:<EOL><INDENT>return a.copy()<EOL><DEDENT>elif np.issubsctype(a, np.float32):<EOL><INDENT>return np.array(a, dtype=np.double)<EOL><DEDENT>else:<EOL><INDENT>return a<EOL><DEDENT>

Copies the array if its base points to a parent array.


def linkage(y, method='<STR_LIT>', metric='<STR_LIT>'):

if not isinstance(method, string_types):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>y = _convert_to_double(np.asarray(y, order='<STR_LIT:c>'))<EOL>s = y.shape<EOL>if len(s) == <NUM_LIT:1>:<EOL><INDENT>distance.is_valid_y(y, throw=True, name='<STR_LIT:y>')<EOL>d = distance.num_obs_y(y)<EOL>if method not in _cpy_non_euclid_methods:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>[y] = _copy_arrays_if_base_present([y])<EOL>Z = np.zeros((d - <NUM_LIT:1>, <NUM_LIT:4>))<EOL>if method == '<STR_LIT>':<EOL><INDENT>_hierarchy.slink(y, Z, int(d))<EOL><DEDENT>else:<EOL><INDENT>_hierarchy.linkage(y, Z, int(d),<EOL>int(_cpy_non_euclid_methods[method]))<EOL><DEDENT><DEDENT>elif len(s) == <NUM_LIT:2>:<EOL><INDENT>X = y<EOL>n = s[<NUM_LIT:0>]<EOL>if method not in _cpy_linkage_methods:<EOL><INDENT>raise ValueError('<STR_LIT>' % method)<EOL><DEDENT>if method in _cpy_non_euclid_methods:<EOL><INDENT>dm = distance.pdist(X, metric)<EOL>Z = np.zeros((n - <NUM_LIT:1>, <NUM_LIT:4>))<EOL>if method == '<STR_LIT>':<EOL><INDENT>_hierarchy.slink(dm, Z, n)<EOL><DEDENT>else:<EOL><INDENT>_hierarchy.linkage(dm, Z, n,<EOL>int(_cpy_non_euclid_methods[method]))<EOL><DEDENT><DEDENT>elif method in _cpy_euclid_methods:<EOL><INDENT>if metric != '<STR_LIT>':<EOL><INDENT>raise ValueError(("<STR_LIT>"<EOL>"<STR_LIT>") % method)<EOL><DEDENT>dm = distance.pdist(X, metric)<EOL>Z = np.zeros((n - <NUM_LIT:1>, <NUM_LIT:4>))<EOL>_hierarchy.linkage(dm, Z, n,<EOL>int(_cpy_euclid_methods[method]))<EOL><DEDENT><DEDENT>return Z<EOL>

Performs hierarchical/agglomerative clustering on the condensed
distance matrix y.

y must be a :math:`{n \\choose 2}` sized
vector where n is the number of original observations paired
in the distance matrix. The behavior of this function is very
similar to the MATLAB linkage function.

A 4 by :math:`(n-1)` matrix ``Z`` is returned. At the
:math:`i`-th iteration, clusters with indices ``Z[i, 0]`` and
``Z[i, 1]`` are combined to form cluster :math:`n + i`. A
cluster with an index less than :math:`n` corresponds to one of
the :math:`n` original observations. The distance between
clusters ``Z[i, 0]`` and ``Z[i, 1]`` is given by ``Z[i, 2]``. The
fourth value ``Z[i, 3]`` represents the number of original
observations in the newly formed cluster.

The following linkage methods are used to compute the distance
:math:`d(s, t)` between two clusters :math:`s` and
:math:`t`. The algorithm begins with a forest of clusters that
have yet to be used in the hierarchy being formed. When two
clusters :math:`s` and :math:`t` from this forest are combined
into a single cluster :math:`u`, :math:`s` and :math:`t` are
removed from the forest, and :math:`u` is added to the
forest. When only one cluster remains in the forest, the algorithm
stops, and this cluster becomes the root.

A distance matrix is maintained at each iteration. The ``d[i,j]``
entry corresponds to the distance between cluster :math:`i` and
:math:`j` in the original forest.

At each iteration, the algorithm must update the distance matrix
to reflect the distance of the newly formed cluster u with the
remaining clusters in the forest.

Suppose there are :math:`|u|` original observations
:math:`u[0], \\ldots, u[|u|-1]` in cluster :math:`u` and
:math:`|v|` original objects :math:`v[0], \\ldots, v[|v|-1]` in
cluster :math:`v`. Recall :math:`s` and :math:`t` are
combined to form cluster :math:`u`. Let :math:`v` be any
remaining cluster in the forest that is not :math:`u`.

The following are methods for calculating the distance between the
newly formed cluster :math:`u` and each :math:`v`.

  * method='single' assigns

    .. math::
       d(u,v) = \\min(dist(u[i],v[j]))

    for all points :math:`i` in cluster :math:`u` and
    :math:`j` in cluster :math:`v`. This is also known as the
    Nearest Point Algorithm.

  * method='complete' assigns

    .. math::
       d(u, v) = \\max(dist(u[i],v[j]))

    for all points :math:`i` in cluster u and :math:`j` in
    cluster :math:`v`. This is also known by the Farthest Point
    Algorithm or Voor Hees Algorithm.

  * method='average' assigns

    .. math::
       d(u,v) = \\sum_{ij} \\frac{d(u[i], v[j])}
                               {(|u|*|v|)}

    for all points :math:`i` and :math:`j` where :math:`|u|`
    and :math:`|v|` are the cardinalities of clusters :math:`u`
    and :math:`v`, respectively. This is also called the UPGMA
    algorithm.

  * method='weighted' assigns

    .. math::
       d(u,v) = (dist(s,v) + dist(t,v))/2

    where cluster u was formed with cluster s and t and v
    is a remaining cluster in the forest. (also called WPGMA)

  * method='centroid' assigns

    .. math::
       dist(s,t) = ||c_s-c_t||_2

    where :math:`c_s` and :math:`c_t` are the centroids of
    clusters :math:`s` and :math:`t`, respectively. When two
    clusters :math:`s` and :math:`t` are combined into a new
    cluster :math:`u`, the new centroid is computed over all the
    original objects in clusters :math:`s` and :math:`t`. The
    distance then becomes the Euclidean distance between the
    centroid of :math:`u` and the centroid of a remaining cluster
    :math:`v` in the forest. This is also known as the UPGMC
    algorithm.

  * method='median' assigns math:`d(s,t)` like the ``centroid``
    method. When two clusters :math:`s` and :math:`t` are combined
    into a new cluster :math:`u`, the average of centroids s and t
    give the new centroid :math:`u`. This is also known as the
    WPGMC algorithm.

  * method='ward' uses the Ward variance minimization algorithm.
    The new entry :math:`d(u,v)` is computed as follows,

    .. math::

       d(u,v) = \\sqrt{\\frac{|v|+|s|}
                           {T}d(v,s)^2
                    + \\frac{|v|+|t|}
                           {T}d(v,t)^2
                    + \\frac{|v|}
                           {T}d(s,t)^2}

    where :math:`u` is the newly joined cluster consisting of
    clusters :math:`s` and :math:`t`, :math:`v` is an unused
    cluster in the forest, :math:`T=|v|+|s|+|t|`, and
    :math:`|*|` is the cardinality of its argument. This is also
    known as the incremental algorithm.

Warning: When the minimum distance pair in the forest is chosen, there
may be two or more pairs with the same minimum distance. This
implementation may chose a different minimum than the MATLAB
version.

Parameters
----------
y : ndarray
    A condensed or redundant distance matrix. A condensed distance matrix
    is a flat array containing the upper triangular of the distance matrix.
    This is the form that ``pdist`` returns. Alternatively, a collection of
    :math:`m` observation vectors in n dimensions may be passed as an
    :math:`m` by :math:`n` array.
method : str, optional
    The linkage algorithm to use. See the ``Linkage Methods`` section below
    for full descriptions.
metric : str, optional
    The distance metric to use. See the ``distance.pdist`` function for a
    list of valid distance metrics.

Returns
-------
Z : ndarray
    The hierarchical clustering encoded as a linkage matrix.