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


dtype = _np.dtype(dtype)<EOL>prefer_fortran = False<EOL>if arrays:<EOL><INDENT>dtypes = [ar.dtype for ar in arrays]<EOL>dtype = _np.find_common_type(dtypes, ())<EOL>try:<EOL><INDENT>index = dtypes.index(dtype)<EOL><DEDENT>except ValueError:<EOL><INDENT>index = <NUM_LIT:0><EOL><DEDENT>if arrays[index].flags['<STR_LIT>']:<EOL><INDENT>prefer_fortran = True<EOL><DEDENT><DEDENT>prefix = _type_conv.get(dtype.char, '<STR_LIT:d>')<EOL>return prefix, dtype, prefer_fortran<EOL>

Find best-matching BLAS/LAPACK type.

    Arrays are used to determine the optimal prefix of BLAS routines.

    Parameters
    ----------
    arrays : sequence of ndarrays, optional
        Arrays can be given to determine optimal prefix of BLAS
        routines. If not given, double-precision routines will be
        used, otherwise the most generic type in arrays will be used.
    dtype : str or dtype, optional
        Data-type specifier. Not used if `arrays` is non-empty.

    Returns
    -------
    prefix : str
        BLAS/LAPACK prefix character.
    dtype : dtype
        Inferred Numpy data type.
    prefer_fortran : bool
        Whether to prefer Fortran order routines over C order.


def _get_funcs(names, arrays, dtype,<EOL>lib_name, fmodule, cmodule,<EOL>fmodule_name, cmodule_name, alias):

funcs = []<EOL>unpack = False<EOL>dtype = _np.dtype(dtype)<EOL>module1 = (cmodule, cmodule_name)<EOL>module2 = (fmodule, fmodule_name)<EOL>if isinstance(names, str):<EOL><INDENT>names = (names,)<EOL>unpack = True<EOL><DEDENT>prefix, dtype, prefer_fortran = find_best_blas_type(arrays, dtype)<EOL>if prefer_fortran:<EOL><INDENT>module1, module2 = module2, module1<EOL><DEDENT>for i, name in enumerate(names):<EOL><INDENT>func_name = prefix + name<EOL>func_name = alias.get(func_name, func_name)<EOL>func = getattr(module1[<NUM_LIT:0>], func_name, None)<EOL>module_name = module1[<NUM_LIT:1>]<EOL>if func is None:<EOL><INDENT>func = getattr(module2[<NUM_LIT:0>], func_name, None)<EOL>module_name = module2[<NUM_LIT:1>]<EOL><DEDENT>if func is None:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>' % (lib_name, func_name))<EOL><DEDENT>func.module_name, func.typecode = module_name, prefix<EOL>func.dtype = dtype<EOL>func.prefix = prefix  <EOL>funcs.append(func)<EOL><DEDENT>if unpack:<EOL><INDENT>return funcs[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>return funcs<EOL><DEDENT>

Return available BLAS/LAPACK functions.

Used also in lapack.py. See get_blas_funcs for docstring.


def get_blas_funcs(names, arrays=(), dtype=None):

return _get_funcs(names, arrays, dtype,<EOL>"<STR_LIT>", _fblas, _cblas, "<STR_LIT>", "<STR_LIT>",<EOL>_blas_alias)<EOL>

Return available BLAS function objects from names.

    Arrays are used to determine the optimal prefix of BLAS routines.

    Parameters
    ----------
    names : str or sequence of str
        Name(s) of BLAS functions without type prefix.

    arrays : sequence of ndarrays, optional
        Arrays can be given to determine optimal prefix of BLAS
        routines. If not given, double-precision routines will be
        used, otherwise the most generic type in arrays will be used.

    dtype : str or dtype, optional
        Data-type specifier. Not used if `arrays` is non-empty.

    Returns
    -------
    funcs : list
        List containing the found function(s).

    Notes
    -----
    This routine automatically chooses between Fortran/C
    interfaces. Fortran code is used whenever possible for arrays with
    column major order. In all other cases, C code is preferred.

    In BLAS, the naming convention is that all functions start with a
    type prefix, which depends on the type of the principal
    matrix. These can be one of {'s', 'd', 'c', 'z'} for the numpy
    types {float32, float64, complex64, complex128} respectively.
    The code and the dtype are stored in attributes `typecode` and `dtype`
    of the returned functions.


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 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 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 eigvals(a, b=None, overwrite_a=False, check_finite=True):

return eig(a, b=b, left=<NUM_LIT:0>, right=<NUM_LIT:0>, overwrite_a=overwrite_a,<EOL>check_finite=check_finite)<EOL>

Compute eigenvalues from an ordinary or generalized eigenvalue problem.

Find eigenvalues of a general matrix::

    a   vr[:,i] = w[i]        b   vr[:,i]

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.
    If omitted, identity matrix is assumed.
overwrite_a : boolean, optional
    Whether to overwrite data in a (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 : (M,) double or complex ndarray
    The eigenvalues, each repeated according to its multiplicity,
    but not in any specific order.

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

See Also
--------
eigvalsh : eigenvalues of symmetric or Hermitian arrays,
eig : eigenvalues and right eigenvectors of general arrays.
eigh : eigenvalues and eigenvectors of symmetric/Hermitian arrays.


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

return eigh(a, b=b, lower=lower, eigvals_only=True,<EOL>overwrite_a=overwrite_a, overwrite_b=overwrite_b,<EOL>turbo=turbo, eigvals=eigvals, type=type,<EOL>check_finite=check_finite)<EOL>

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

Find eigenvalues w 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)
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 : integer, 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.

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
--------
eigvals : eigenvalues of general arrays
eigh : eigenvalues and right eigenvectors for symmetric/Hermitian arrays
eig : eigenvalues and right eigenvectors for non-symmetric arrays


def eigvals_banded(a_band, lower=False, overwrite_a_band=False,<EOL>select='<STR_LIT:a>', select_range=None, check_finite=True):

return eig_banded(a_band, lower=lower, eigvals_only=<NUM_LIT:1>,<EOL>overwrite_a_band=overwrite_a_band, select=select,<EOL>select_range=select_range, check_finite=check_finite)<EOL>

Solve real symmetric or complex hermitian band matrix eigenvalue problem.

Find eigenvalues w 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 : boolean
    Is the matrix in the lower form. (Default is upper form)
overwrite_a_band:
    Discard data in a_band (may enhance performance)
select : {'a', 'v', 'i'}
    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)
    Range of selected eigenvalues
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.

Raises LinAlgError if eigenvalue computation does not converge

See Also
--------
eig_banded : eigenvalues and right eigenvectors for symmetric/Hermitian
    band matrices
eigvals : eigenvalues of general arrays
eigh : eigenvalues and right eigenvectors for symmetric/Hermitian arrays
eig : eigenvalues and right eigenvectors for non-symmetric arrays


def hessenberg(a, calc_q=False, overwrite_a=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>gehrd, gebal, gehrd_lwork = get_lapack_funcs(('<STR_LIT>','<STR_LIT>', '<STR_LIT>'), (a1,))<EOL>ba, lo, hi, pivscale, info = gebal(a1, permute=<NUM_LIT:0>, overwrite_a=overwrite_a)<EOL>if info < <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>' % -info)<EOL><DEDENT>n = len(a1)<EOL>lwork, info = gehrd_lwork(ba.shape[<NUM_LIT:0>], lo=lo, hi=hi)<EOL>if info != <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>' % info)<EOL><DEDENT>lwork = int(lwork.real)<EOL>hq, tau, info = gehrd(ba, lo=lo, hi=hi, lwork=lwork, overwrite_a=<NUM_LIT:1>)<EOL>if info < <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>' % -info)<EOL><DEDENT>if not calc_q:<EOL><INDENT>for i in range(lo, hi):<EOL><INDENT>hq[i+<NUM_LIT:2>:hi+<NUM_LIT:1>, i] = <NUM_LIT:0.0><EOL><DEDENT>return hq<EOL><DEDENT>typecode = hq.dtype<EOL>ger,gemm = get_blas_funcs(('<STR_LIT>','<STR_LIT>'), dtype=typecode)<EOL>q = None<EOL>for i in range(lo, hi):<EOL><INDENT>if tau[i] == <NUM_LIT:0.0>:<EOL><INDENT>continue<EOL><DEDENT>v = zeros(n, dtype=typecode)<EOL>v[i+<NUM_LIT:1>] = <NUM_LIT:1.0><EOL>v[i+<NUM_LIT:2>:hi+<NUM_LIT:1>] = hq[i+<NUM_LIT:2>:hi+<NUM_LIT:1>, i]<EOL>hq[i+<NUM_LIT:2>:hi+<NUM_LIT:1>, i] = <NUM_LIT:0.0><EOL>h = ger(-tau[i], v, v,a=diag(ones(n, dtype=typecode)), overwrite_a=<NUM_LIT:1>)<EOL>if q is None:<EOL><INDENT>q = h<EOL><DEDENT>else:<EOL><INDENT>q = gemm(<NUM_LIT:1.0>, q, h)<EOL><DEDENT><DEDENT>if q is None:<EOL><INDENT>q = diag(ones(n, dtype=typecode))<EOL><DEDENT>return hq, q<EOL>

Compute Hessenberg form of a matrix.

The Hessenberg decomposition is::

    A = Q H Q^H

where `Q` is unitary/orthogonal and `H` has only zero elements below
the first sub-diagonal.

Parameters
----------
a : (M, M) array_like
    Matrix to bring into Hessenberg form.
calc_q : bool, optional
    Whether to compute the transformation matrix.  Default is False.
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
-------
H : (M, M) ndarray
    Hessenberg form of `a`.
Q : (M, M) ndarray
    Unitary/orthogonal similarity transformation matrix ``A = Q H Q^H``.
    Only returned if ``calc_q=True``.


def solve(a, b, sym_pos=False, lower=False, overwrite_a=False, overwrite_b=False,<EOL>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_a = overwrite_a or _datacopied(a1, a)<EOL>overwrite_b = overwrite_b or _datacopied(b1, b)<EOL>if debug:<EOL><INDENT>print('<STR_LIT>',overwrite_a)<EOL>print('<STR_LIT>',overwrite_b)<EOL><DEDENT>if sym_pos:<EOL><INDENT>posv, = get_lapack_funcs(('<STR_LIT>',), (a1,b1))<EOL>c, x, info = posv(a1, b1, lower=lower,<EOL>overwrite_a=overwrite_a,<EOL>overwrite_b=overwrite_b)<EOL><DEDENT>else:<EOL><INDENT>gesv, = get_lapack_funcs(('<STR_LIT>',), (a1,b1))<EOL>lu, piv, x, info = gesv(a1, b1, overwrite_a=overwrite_a,<EOL>overwrite_b=overwrite_b)<EOL><DEDENT>if info == <NUM_LIT:0>:<EOL><INDENT>return x<EOL><DEDENT>if info > <NUM_LIT:0>:<EOL><INDENT>raise LinAlgError("<STR_LIT>")<EOL><DEDENT>raise ValueError('<STR_LIT>'<EOL>% -info)<EOL>

Solve the equation ``a x = b`` for ``x``.

Parameters
----------
a : (M, M) array_like
    A square matrix.
b : (M,) or (M, N) array_like
    Right-hand side matrix in ``a x = b``.
sym_pos : bool
    Assume `a` is symmetric and positive definite.
lower : boolean
    Use only data contained in the lower triangle of `a`, if `sym_pos` is
    true.  Default is to use upper triangle.
overwrite_a : bool
    Allow overwriting data in `a` (may enhance performance).
    Default is False.
overwrite_b : bool
    Allow overwriting 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 : (M,) or (M, N) ndarray
    Solution to the system ``a x = b``.  Shape of the return matches the
    shape of `b`.

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

Examples
--------
Given `a` and `b`, solve for `x`:

>>> a = np.array([[3,2,0],[1,-1,0],[0,5,1]])
>>> b = np.array([2,4,-1])
>>> x = linalg.solve(a,b)
>>> x
array([ 2., -2.,  9.])
>>> np.dot(a, x) == b
array([ True,  True,  True], dtype=bool)


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 solve_banded(l_and_u, ab, b, overwrite_ab=False, overwrite_b=False,<EOL>debug=False, check_finite=True):

(l, u) = l_and_u<EOL>if check_finite:<EOL><INDENT>a1, b1 = map(np.asarray_chkfinite, (ab, b))<EOL><DEDENT>else:<EOL><INDENT>a1, b1 = map(np.asarray, (ab,b))<EOL><DEDENT>if a1.shape[-<NUM_LIT:1>] != b1.shape[<NUM_LIT:0>]:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if l + u + <NUM_LIT:1> != a1.shape[<NUM_LIT:0>]:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>" % (l+u+<NUM_LIT:1>, ab.shape[<NUM_LIT:0>]))<EOL><DEDENT>overwrite_b = overwrite_b or _datacopied(b1, b)<EOL>gbsv, = get_lapack_funcs(('<STR_LIT>',), (a1, b1))<EOL>a2 = np.zeros((<NUM_LIT:2>*l+u+<NUM_LIT:1>, a1.shape[<NUM_LIT:1>]), dtype=gbsv.dtype)<EOL>a2[l:,:] = a1<EOL>lu, piv, x, info = gbsv(l, u, a2, b1, overwrite_ab=True,<EOL>overwrite_b=overwrite_b)<EOL>if info == <NUM_LIT:0>:<EOL><INDENT>return x<EOL><DEDENT>if info > <NUM_LIT:0>:<EOL><INDENT>raise LinAlgError("<STR_LIT>")<EOL><DEDENT>raise ValueError('<STR_LIT>' % -info)<EOL>

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

The matrix a is stored in `ab` using the matrix diagonal ordered form::

    ab[u + i - j, j] == a[i,j]

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

    *    a01  a12  a23  a34  a45
    a00  a11  a22  a33  a44  a55
    a10  a21  a32  a43  a54   *
    a20  a31  a42  a53   *    *

Parameters
----------
(l, u) : (integer, integer)
    Number of non-zero lower and upper diagonals
ab : (`l` + `u` + 1, M) array_like
    Banded matrix
b : (M,) or (M, K) array_like
    Right-hand side
overwrite_ab : boolean, optional
    Discard data in `ab` (may enhance performance)
overwrite_b : boolean, optional
    Discard data in `b` (may enhance 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
-------
x : (M,) or (M, K) ndarray
    The solution to the system a x = b.  Returned shape depends on the
    shape of `b`.


def solveh_banded(ab, b, overwrite_ab=False, overwrite_b=False, lower=False,<EOL>check_finite=True):

if check_finite:<EOL><INDENT>ab, b = map(np.asarray_chkfinite, (ab, b))<EOL><DEDENT>else:<EOL><INDENT>ab, b = map(np.asarray, (ab,b))<EOL><DEDENT>if ab.shape[-<NUM_LIT:1>] != b.shape[<NUM_LIT:0>]:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>pbsv, = get_lapack_funcs(('<STR_LIT>',), (ab, b))<EOL>c, x, info = pbsv(ab, b, lower=lower, overwrite_ab=overwrite_ab,<EOL>overwrite_b=overwrite_b)<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 x<EOL>

Solve equation a x = b. a is Hermitian positive-definite banded 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 *   *

Cells marked with * are not used.

Parameters
----------
ab : (`u` + 1, M) array_like
    Banded matrix
b : (M,) or (M, K) array_like
    Right-hand side
overwrite_ab : bool, optional
    Discard data in `ab` (may enhance performance)
overwrite_b : bool, optional
    Discard data in `b` (may enhance performance)
lower : bool, optional
    Is the matrix in the lower form. (Default is upper form)
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 : (M,) or (M, K) ndarray
    The solution to the system a x = b.  Shape of return matches shape
    of `b`.


def inv(a, overwrite_a=False, check_finite=True):

if check_finite:<EOL><INDENT>a1 = np.asarray_chkfinite(a)<EOL><DEDENT>else:<EOL><INDENT>a1 = np.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><INDENT>finv, = get_flinalg_funcs(('<STR_LIT>',),(a1,))<EOL>if finv is not None:<EOL><INDENT>a_inv,info = finv(a1,overwrite_a=overwrite_a)<EOL>if info==<NUM_LIT:0>:<EOL><INDENT>return a_inv<EOL><DEDENT>if info><NUM_LIT:0>: raise LinAlgError, "<STR_LIT>"<EOL>if info<<NUM_LIT:0>: raise ValueError,'<STR_LIT>'%(-info)<EOL><DEDENT><DEDENT>getrf, getri, getri_lwork = get_lapack_funcs(('<STR_LIT>','<STR_LIT>', '<STR_LIT>'), (a1,))<EOL>lu, piv, info = getrf(a1, overwrite_a=overwrite_a)<EOL>if info == <NUM_LIT:0>:<EOL><INDENT>lwork, info = getri_lwork(a1.shape[<NUM_LIT:0>])<EOL>if info != <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>' % (info,))<EOL><DEDENT>lwork = int(lwork.real)<EOL>lwork = int(<NUM_LIT> * lwork)<EOL>inv_a, info = getri(lu, piv, lwork=lwork, overwrite_lu=<NUM_LIT:1>)<EOL><DEDENT>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>'<STR_LIT>' % -info)<EOL><DEDENT>return inv_a<EOL>

Compute the inverse of a matrix.

Parameters
----------
a : array_like
    Square matrix to be inverted.
overwrite_a : bool, optional
    Discard data in `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
-------
ainv : ndarray
    Inverse of the matrix `a`.

Raises
------
LinAlgError :
    If `a` is singular.
ValueError :
    If `a` is not square, or not 2-dimensional.

Examples
--------
>>> a = np.array([[1., 2.], [3., 4.]])
>>> sp.linalg.inv(a)
array([[-2. ,  1. ],
       [ 1.5, -0.5]])
>>> np.dot(a, sp.linalg.inv(a))
array([[ 1.,  0.],
       [ 0.,  1.]])


def det(a, overwrite_a=False, check_finite=True):

if check_finite:<EOL><INDENT>a1 = np.asarray_chkfinite(a)<EOL><DEDENT>else:<EOL><INDENT>a1 = np.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>fdet, = get_flinalg_funcs(('<STR_LIT>',), (a1,))<EOL>a_det, info = fdet(a1, overwrite_a=overwrite_a)<EOL>if info < <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>' % -info)<EOL><DEDENT>return a_det<EOL>

Compute the determinant of a matrix

The determinant of a square matrix is a value derived arithmetically
from the coefficients of the matrix.

The determinant for a 3x3 matrix, for example, is computed as follows::

    a    b    c
    d    e    f = A
    g    h    i

    det(A) = a*e*i + b*f*g + c*d*h - c*e*g - b*d*i - a*f*h

Parameters
----------
a : (M, M) array_like
    A square matrix.
overwrite_a : bool
    Allow overwriting data in a (may enhance performance).
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
-------
det : float or complex
    Determinant of `a`.

Notes
-----
The determinant is computed via LU factorization, LAPACK routine z/dgetrf.

Examples
--------
>>> a = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> linalg.det(a)
0.0
>>> a = np.array([[0,2,3],[4,5,6],[7,8,9]])
>>> linalg.det(a)
3.0


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


def lu_factor(a, overwrite_a=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>getrf, = get_lapack_funcs(('<STR_LIT>',), (a1,))<EOL>lu, piv, info = getrf(a1, overwrite_a=overwrite_a)<EOL>if info < <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>' % -info)<EOL><DEDENT>if info > <NUM_LIT:0>:<EOL><INDENT>warn("<STR_LIT>" % info,<EOL>RuntimeWarning)<EOL><DEDENT>return lu, piv<EOL>

Compute pivoted LU decomposition of a matrix.

The decomposition is::

    A = P L U

where P is a permutation matrix, L lower triangular with unit
diagonal elements, and U upper triangular.

Parameters
----------
a : (M, M) array_like
    Matrix to decompose
overwrite_a : boolean
    Whether to overwrite data in A (may increase performance)
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
-------
lu : (N, N) ndarray
    Matrix containing U in its upper triangle, and L in its lower triangle.
    The unit diagonal elements of L are not stored.
piv : (N,) ndarray
    Pivot indices representing the permutation matrix P:
    row i of matrix was interchanged with row piv[i].

See also
--------
lu_solve : solve an equation system using the LU factorization of a matrix

Notes
-----
This is a wrapper to the ``*GETRF`` routines from LAPACK.


def lu_solve(lu_and_piv, b, trans=<NUM_LIT:0>, overwrite_b=False, check_finite=True):

(lu, piv) = lu_and_piv<EOL>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 lu.shape[<NUM_LIT:0>] != b1.shape[<NUM_LIT:0>]:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>getrs, = get_lapack_funcs(('<STR_LIT>',), (lu, b1))<EOL>x,info = getrs(lu, piv, b1, trans=trans, overwrite_b=overwrite_b)<EOL>if info == <NUM_LIT:0>:<EOL><INDENT>return x<EOL><DEDENT>raise ValueError('<STR_LIT>'<EOL>% -info)<EOL>

Solve an equation system, a x = b, given the LU factorization of a

    Parameters
    ----------
    (lu, piv)
        Factorization of the coefficient matrix a, as given by lu_factor
    b : array
        Right-hand side
    trans : {0, 1, 2}
        Type of system to solve:

        =====  =========
        trans  system
        =====  =========
        0      a x   = b
        1      a^T x = b
        2      a^H x = b
        =====  =========
    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 : array
        Solution to the system

    See also
    --------
    lu_factor : LU factorize a matrix


def lu(a, permute_l=False, overwrite_a=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>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>overwrite_a = overwrite_a or (_datacopied(a1, a))<EOL>flu, = get_flinalg_funcs(('<STR_LIT>',), (a1,))<EOL>p, l, u, info = flu(a1, permute_l=permute_l, overwrite_a=overwrite_a)<EOL>if info < <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>' % -info)<EOL><DEDENT>if permute_l:<EOL><INDENT>return l, u<EOL><DEDENT>return p, l, u<EOL>

Compute pivoted LU decomposition of a matrix.

The decomposition is::

    A = P L U

where P is a permutation matrix, L lower triangular with unit
diagonal elements, and U upper triangular.

Parameters
----------
a : (M, N) array_like
    Array to decompose
permute_l : bool
    Perform the multiplication P*L  (Default: do not permute)
overwrite_a : bool
    Whether to overwrite data in a (may improve performance)
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
-------
**(If permute_l == False)**

p : (M, M) ndarray
    Permutation matrix
l : (M, K) ndarray
    Lower triangular or trapezoidal matrix with unit diagonal.
    K = min(M, N)
u : (K, N) ndarray
    Upper triangular or trapezoidal matrix

**(If permute_l == True)**

pl : (M, K) ndarray
    Permuted L matrix.
    K = min(M, N)
u : (K, N) ndarray
    Upper triangular or trapezoidal matrix

Notes
-----
This is a LU factorization routine written for Scipy.


def qz(A, B, output='<STR_LIT>', lwork=None, sort=None, overwrite_a=False,<EOL>overwrite_b=False, check_finite=True):

if sort is not None:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if output not in ['<STR_LIT>','<STR_LIT>','<STR_LIT:r>','<STR_LIT:c>']:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if check_finite:<EOL><INDENT>a1 = asarray_chkfinite(A)<EOL>b1 = asarray_chkfinite(B)<EOL><DEDENT>else:<EOL><INDENT>a1 = np.asarray(A)<EOL>b1 = np.asarray(B)<EOL><DEDENT>a_m, a_n = a1.shape<EOL>b_m, b_n = b1.shape<EOL>if not (a_m == a_n == b_m == b_n):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>typa = a1.dtype.char<EOL>if output in ['<STR_LIT>', '<STR_LIT:c>'] and typa not in ['<STR_LIT:F>','<STR_LIT:D>']:<EOL><INDENT>if typa in _double_precision:<EOL><INDENT>a1 = a1.astype('<STR_LIT:D>')<EOL>typa = '<STR_LIT:D>'<EOL><DEDENT>else:<EOL><INDENT>a1 = a1.astype('<STR_LIT:F>')<EOL>typa = '<STR_LIT:F>'<EOL><DEDENT><DEDENT>typb = b1.dtype.char<EOL>if output in ['<STR_LIT>', '<STR_LIT:c>'] and typb not in ['<STR_LIT:F>','<STR_LIT:D>']:<EOL><INDENT>if typb in _double_precision:<EOL><INDENT>b1 = b1.astype('<STR_LIT:D>')<EOL>typb = '<STR_LIT:D>'<EOL><DEDENT>else:<EOL><INDENT>b1 = b1.astype('<STR_LIT:F>')<EOL>typb = '<STR_LIT:F>'<EOL><DEDENT><DEDENT>overwrite_a = overwrite_a or (_datacopied(a1,A))<EOL>overwrite_b = overwrite_b or (_datacopied(b1,B))<EOL>gges, = get_lapack_funcs(('<STR_LIT>',), (a1,b1))<EOL>if lwork is None or lwork == -<NUM_LIT:1>:<EOL><INDENT>result = gges(lambda x: None, a1, b1, lwork=-<NUM_LIT:1>)<EOL>lwork = result[-<NUM_LIT:2>][<NUM_LIT:0>].real.astype(np.int)<EOL><DEDENT>if sort is None:<EOL><INDENT>sort_t = <NUM_LIT:0><EOL>sfunction = lambda x: None<EOL><DEDENT>else:<EOL><INDENT>sort_t = <NUM_LIT:1><EOL>sfunction = _select_function(sort, typa)<EOL><DEDENT>result = gges(sfunction, a1, b1, lwork=lwork, overwrite_a=overwrite_a,<EOL>overwrite_b=overwrite_b, sort_t=sort_t)<EOL>info = result[-<NUM_LIT:1>]<EOL>if info < <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>" % -info)<EOL><DEDENT>elif info > <NUM_LIT:0> and info <= a_n:<EOL><INDENT>warnings.warn("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % info-<NUM_LIT:1>, UserWarning)<EOL><DEDENT>elif info == a_n+<NUM_LIT:1>:<EOL><INDENT>raise LinAlgError("<STR_LIT>")<EOL><DEDENT>elif info == a_n+<NUM_LIT:2>:<EOL><INDENT>raise LinAlgError("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>elif info == a_n+<NUM_LIT:3>:<EOL><INDENT>raise LinAlgError("<STR_LIT>")<EOL><DEDENT>if sort_t == <NUM_LIT:0>:<EOL><INDENT>return result[<NUM_LIT:0>], result[<NUM_LIT:1>], result[-<NUM_LIT:4>], result[-<NUM_LIT:3>]<EOL><DEDENT>else:<EOL><INDENT>return result[<NUM_LIT:0>], result[<NUM_LIT:1>], result[-<NUM_LIT:4>], result[-<NUM_LIT:3>], result[<NUM_LIT:2>]<EOL><DEDENT>

QZ decomposition for generalized eigenvalues of a pair of matrices.

The QZ, or generalized Schur, decomposition for a pair of N x N
nonsymmetric matrices (A,B) is::

    (A,B) = (Q*AA*Z', Q*BB*Z')

where AA, BB is in generalized Schur form if BB is upper-triangular
with non-negative diagonal and AA is upper-triangular, or for real QZ
decomposition (``output='real'``) block upper triangular with 1x1
and 2x2 blocks.  In this case, the 1x1 blocks correspond to real
generalized eigenvalues and 2x2 blocks are 'standardized' by making
the corresponding elements of BB have the form::

    [ a 0 ]
    [ 0 b ]

and the pair of corresponding 2x2 blocks in AA and BB will have a complex
conjugate pair of generalized eigenvalues.  If (``output='complex'``) or
A and B are complex matrices, Z' denotes the conjugate-transpose of Z.
Q and Z are unitary matrices.

Parameters
----------
A : (N, N) array_like
    2d array to decompose
B : (N, N) array_like
    2d array to decompose
output : str {'real','complex'}
    Construct the real or complex QZ decomposition for real matrices.
    Default is 'real'.
lwork : int, optional
    Work array size.  If None or -1, it is automatically computed.
sort : {None, callable, 'lhp', 'rhp', 'iuc', 'ouc'}, optional
    NOTE: THIS INPUT IS DISABLED FOR NOW, IT DOESN'T WORK WELL ON WINDOWS.

    Specifies whether the upper eigenvalues should be sorted.  A callable
    may be passed that, given a eigenvalue, returns a boolean denoting
    whether the eigenvalue should be sorted to the top-left (True). For
    real matrix pairs, the sort function takes three real arguments
    (alphar, alphai, beta). The eigenvalue x = (alphar + alphai*1j)/beta.
    For complex matrix pairs or output='complex', the sort function
    takes two complex arguments (alpha, beta). The eigenvalue
    x = (alpha/beta).
    Alternatively, string parameters may be used:

        - 'lhp'   Left-hand plane (x.real < 0.0)
        - 'rhp'   Right-hand plane (x.real > 0.0)
        - 'iuc'   Inside the unit circle (x*x.conjugate() <= 1.0)
        - 'ouc'   Outside the unit circle (x*x.conjugate() > 1.0)

    Defaults to None (no sorting).
check_finite : boolean
    If true checks the elements of `A` and `B` are finite numbers. If
    false does no checking and passes matrix through to
    underlying algorithm.

Returns
-------
AA : (N, N) ndarray
    Generalized Schur form of A.
BB : (N, N) ndarray
    Generalized Schur form of B.
Q : (N, N) ndarray
    The left Schur vectors.
Z : (N, N) ndarray
    The right Schur vectors.
sdim : int, optional
    If sorting was requested, a fifth return value will contain the
    number of eigenvalues for which the sort condition was True.

Notes
-----
Q is transposed versus the equivalent function in Matlab.

.. versionadded:: 0.11.0

Examples
--------
>>> from scipy import linalg
>>> np.random.seed(1234)
>>> A = np.arange(9).reshape((3, 3))
>>> B = np.random.randn(3, 3)

>>> AA, BB, Q, Z = linalg.qz(A, B)
>>> AA
array([[-13.40928183,  -4.62471562,   1.09215523],
       [  0.        ,   0.        ,   1.22805978],
       [  0.        ,   0.        ,   0.31973817]])
>>> BB
array([[ 0.33362547, -1.37393632,  0.02179805],
       [ 0.        ,  1.68144922,  0.74683866],
       [ 0.        ,  0.        ,  0.9258294 ]])
>>> Q
array([[ 0.14134727, -0.97562773,  0.16784365],
       [ 0.49835904, -0.07636948, -0.86360059],
       [ 0.85537081,  0.20571399,  0.47541828]])
>>> Z
array([[-0.24900855, -0.51772687,  0.81850696],
       [-0.79813178,  0.58842606,  0.12938478],
       [-0.54861681, -0.6210585 , -0.55973739]])


def schur(a, output='<STR_LIT>', lwork=None, overwrite_a=False, sort=None,<EOL>check_finite=True):

if output not in ['<STR_LIT>','<STR_LIT>','<STR_LIT:r>','<STR_LIT:c>']:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>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>typ = a1.dtype.char<EOL>if output in ['<STR_LIT>','<STR_LIT:c>'] and typ not in ['<STR_LIT:F>','<STR_LIT:D>']:<EOL><INDENT>if typ in _double_precision:<EOL><INDENT>a1 = a1.astype('<STR_LIT:D>')<EOL>typ = '<STR_LIT:D>'<EOL><DEDENT>else:<EOL><INDENT>a1 = a1.astype('<STR_LIT:F>')<EOL>typ = '<STR_LIT:F>'<EOL><DEDENT><DEDENT>overwrite_a = overwrite_a or (_datacopied(a1, a))<EOL>gees, = get_lapack_funcs(('<STR_LIT>',), (a1,))<EOL>if lwork is None or lwork == -<NUM_LIT:1>:<EOL><INDENT>result = gees(lambda x: None, a1, lwork=-<NUM_LIT:1>)<EOL>lwork = result[-<NUM_LIT:2>][<NUM_LIT:0>].real.astype(numpy.int)<EOL><DEDENT>if sort is None:<EOL><INDENT>sort_t = <NUM_LIT:0><EOL>sfunction = lambda x: None<EOL><DEDENT>else:<EOL><INDENT>sort_t = <NUM_LIT:1><EOL>if callable(sort):<EOL><INDENT>sfunction = sort<EOL><DEDENT>elif sort == '<STR_LIT>':<EOL><INDENT>sfunction = lambda x: (numpy.real(x) < <NUM_LIT:0.0>)<EOL><DEDENT>elif sort == '<STR_LIT>':<EOL><INDENT>sfunction = lambda x: (numpy.real(x) >= <NUM_LIT:0.0>)<EOL><DEDENT>elif sort == '<STR_LIT>':<EOL><INDENT>sfunction = lambda x: (abs(x) <= <NUM_LIT:1.0>)<EOL><DEDENT>elif sort == '<STR_LIT>':<EOL><INDENT>sfunction = lambda x: (abs(x) > <NUM_LIT:1.0>)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" +<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT>result = gees(sfunction, a1, lwork=lwork, overwrite_a=overwrite_a,<EOL>sort_t=sort_t)<EOL>info = result[-<NUM_LIT:1>]<EOL>if info < <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>% -info)<EOL><DEDENT>elif info == a1.shape[<NUM_LIT:0>] + <NUM_LIT:1>:<EOL><INDENT>raise LinAlgError('<STR_LIT>')<EOL><DEDENT>elif info == a1.shape[<NUM_LIT:0>] + <NUM_LIT:2>:<EOL><INDENT>raise LinAlgError('<STR_LIT>')<EOL><DEDENT>elif info > <NUM_LIT:0>:<EOL><INDENT>raise LinAlgError("<STR_LIT>")<EOL><DEDENT>if sort_t == <NUM_LIT:0>:<EOL><INDENT>return result[<NUM_LIT:0>], result[-<NUM_LIT:3>]<EOL><DEDENT>else:<EOL><INDENT>return result[<NUM_LIT:0>], result[-<NUM_LIT:3>], result[<NUM_LIT:1>]<EOL><DEDENT>

Compute Schur decomposition of a matrix.

The Schur decomposition is::

    A = Z T Z^H

where Z is unitary and T is either upper-triangular, or for real
Schur decomposition (output='real'), quasi-upper triangular.  In
the quasi-triangular form, 2x2 blocks describing complex-valued
eigenvalue pairs may extrude from the diagonal.

Parameters
----------
a : (M, M) array_like
    Matrix to decompose
output : {'real', 'complex'}, optional
    Construct the real or complex Schur decomposition (for real matrices).
lwork : int, optional
    Work array size. If None or -1, it is automatically computed.
overwrite_a : bool, optional
    Whether to overwrite data in a (may improve performance).
sort : {None, callable, 'lhp', 'rhp', 'iuc', 'ouc'}, optional
    Specifies whether the upper eigenvalues should be sorted.  A callable
    may be passed that, given a eigenvalue, returns a boolean denoting
    whether the eigenvalue should be sorted to the top-left (True).
    Alternatively, string parameters may be used::

        'lhp'   Left-hand plane (x.real < 0.0)
        'rhp'   Right-hand plane (x.real > 0.0)
        'iuc'   Inside the unit circle (x*x.conjugate() <= 1.0)
        'ouc'   Outside the unit circle (x*x.conjugate() > 1.0)

    Defaults to None (no sorting).
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
-------
T : (M, M) ndarray
    Schur form of A. It is real-valued for the real Schur decomposition.
Z : (M, M) ndarray
    An unitary Schur transformation matrix for A.
    It is real-valued for the real Schur decomposition.
sdim : int
    If and only if sorting was requested, a third return value will
    contain the number of eigenvalues satisfying the sort condition.

Raises
------
LinAlgError
    Error raised under three conditions:

    1. The algorithm failed due to a failure of the QR algorithm to
       compute all eigenvalues
    2. If eigenvalue sorting was requested, the eigenvalues could not be
       reordered due to a failure to separate eigenvalues, usually because
       of poor conditioning
    3. If eigenvalue sorting was requested, roundoff errors caused the
       leading eigenvalues to no longer satisfy the sorting condition

See also
--------
rsf2csf : Convert real Schur form to complex Schur form


if check_finite:<EOL><INDENT>Z, T = map(asarray_chkfinite, (Z, T))<EOL><DEDENT>else:<EOL><INDENT>Z,T = map(asarray, (Z,T))<EOL><DEDENT>if len(Z.shape) != <NUM_LIT:2> or Z.shape[<NUM_LIT:0>] != Z.shape[<NUM_LIT:1>]:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>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>if T.shape[<NUM_LIT:0>] != Z.shape[<NUM_LIT:0>]:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>N = T.shape[<NUM_LIT:0>]<EOL>arr = numpy.array<EOL>t = _commonType(Z, T, arr([<NUM_LIT>],'<STR_LIT:F>'))<EOL>Z, T = _castCopy(t, Z, T)<EOL>conj = numpy.conj<EOL>dot = numpy.dot<EOL>r_ = numpy.r_<EOL>transp = numpy.transpose<EOL>for m in range(N-<NUM_LIT:1>, <NUM_LIT:0>, -<NUM_LIT:1>):<EOL><INDENT>if abs(T[m,m-<NUM_LIT:1>]) > eps*(abs(T[m-<NUM_LIT:1>,m-<NUM_LIT:1>]) + abs(T[m,m])):<EOL><INDENT>k = slice(m-<NUM_LIT:1>, m+<NUM_LIT:1>)<EOL>mu = eigvals(T[k,k]) - T[m,m]<EOL>r = misc.norm([mu[<NUM_LIT:0>], T[m,m-<NUM_LIT:1>]])<EOL>c = mu[<NUM_LIT:0>] / r<EOL>s = T[m,m-<NUM_LIT:1>] / r<EOL>G = r_[arr([[conj(c), s]], dtype=t), arr([[-s, c]], dtype=t)]<EOL>Gc = conj(transp(G))<EOL>j = slice(m-<NUM_LIT:1>, N)<EOL>T[k,j] = dot(G, T[k,j])<EOL>i = slice(<NUM_LIT:0>, m+<NUM_LIT:1>)<EOL>T[i,k] = dot(T[i,k], Gc)<EOL>i = slice(<NUM_LIT:0>, N)<EOL>Z[i,k] = dot(Z[i,k], Gc)<EOL><DEDENT>T[m,m-<NUM_LIT:1>] = <NUM_LIT:0.0><EOL><DEDENT>return T, Z<EOL>

Convert real Schur form to complex Schur form.

Convert a quasi-diagonal real-valued Schur form to the upper triangular
complex-valued Schur form.

Parameters
----------
T : (M, M) array_like
    Real Schur form of the original matrix
Z : (M, M) array_like
    Schur transformation matrix
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
-------
T : (M, M) ndarray
    Complex Schur form of the original matrix
Z : (M, M) ndarray
    Schur transformation matrix corresponding to the complex form

See also
--------
schur : Schur decompose a matrix


A = np.asarray(A)<EOL>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>return A<EOL>

Wraps asarray with the extra requirement that the input be a square matrix.

The motivation is that the matfuncs module has real functions that have
been lifted to square matrix functions.

Parameters
----------
A : array_like
    A square matrix.

Returns
-------
out : ndarray
    An ndarray copy or view or other representation of A.


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


<EOL>A = _asarray_square(A)<EOL>import scipy.linalg._matfuncs_inv_ssq<EOL>return scipy.linalg._matfuncs_inv_ssq._fractional_matrix_power(A, t)<EOL>

Compute the fractional power of a matrix.

Proceeds according to the discussion in section (6) of [1]_.

Parameters
----------
A : (N, N) array_like
    Matrix whose fractional power to evaluate.
t : float
    Fractional power.

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

References
----------
.. [1] 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

Examples
--------
>>> from scipy.linalg import fractional_matrix_power
>>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
>>> b = fractional_matrix_power(a, 0.5)
>>> b
array([[ 0.75592895,  1.13389342],
       [ 0.37796447,  1.88982237]])
>>> np.dot(b, b)      # Verify square root
array([[ 1.,  3.],
       [ 1.,  4.]])


A = _asarray_square(A)<EOL>import scipy.linalg._matfuncs_inv_ssq<EOL>F = scipy.linalg._matfuncs_inv_ssq._logm(A)<EOL>errtol = <NUM_LIT:1000>*eps<EOL>errest = norm(expm(F)-A,<NUM_LIT:1>) / norm(A,<NUM_LIT:1>)<EOL>if disp:<EOL><INDENT>if not isfinite(errest) or errest >= errtol:<EOL><INDENT>print("<STR_LIT>", errest)<EOL><DEDENT>return F<EOL><DEDENT>else:<EOL><INDENT>return F, errest<EOL><DEDENT>

Compute matrix logarithm.

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

Parameters
----------
A : (N, N) array_like
    Matrix whose logarithm to evaluate
disp : bool, optional
    Print warning if error in the result is estimated large
    instead of returning estimated error. (Default: True)

Returns
-------
logm : (N, N) ndarray
    Matrix logarithm of `A`
errest : float
    (if disp == False)

    1-norm of the estimated error, ||err||_1 / ||A||_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

.. [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

Examples
--------
>>> from scipy.linalg import logm, expm
>>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
>>> b = logm(a)
>>> b
array([[-1.02571087,  2.05142174],
       [ 0.68380725,  1.02571087]])
>>> expm(b)         # Verify expm(logm(a)) returns a
array([[ 1.,  3.],
       [ 1.,  4.]])


if q is not None:<EOL><INDENT>msg = "<STR_LIT>" <EOL>warnings.warn(msg, DeprecationWarning)<EOL><DEDENT>import scipy.sparse.linalg<EOL>return scipy.sparse.linalg.expm(A)<EOL>

Compute the matrix exponential using Pade approximation.

Parameters
----------
A : (N, N) array_like or sparse matrix
    Matrix to be exponentiated.

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

References
----------
.. [1] Awad H. Al-Mohy and Nicholas J. Higham (2009)
       "A New Scaling and Squaring Algorithm for the Matrix Exponential."
       SIAM Journal on Matrix Analysis and Applications.
       31 (3). pp. 970-989. ISSN 1095-7162

Examples
--------
>>> from scipy.linalg import expm, sinm, cosm

Matrix version of the formula exp(0) = 1:

>>> expm(np.zeros((2,2)))
array([[ 1.,  0.],
       [ 0.,  1.]])

Euler's identity (exp(i*theta) = cos(theta) + i*sin(theta))
applied to a matrix:

>>> a = np.array([[1.0, 2.0], [-1.0, 3.0]])
>>> expm(1j*a)
array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j],
       [ 1.06860742+0.48905626j, -1.71075555+0.91406299j]])
>>> cosm(a) + 1j*sinm(a)
array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j],
       [ 1.06860742+0.48905626j, -1.71075555+0.91406299j]])


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`


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>if np.iscomplexobj(A):<EOL><INDENT>return <NUM_LIT:0.5>*(expm(<NUM_LIT>*A) + expm(-<NUM_LIT>*A))<EOL><DEDENT>else:<EOL><INDENT>return expm(<NUM_LIT>*A).real<EOL><DEDENT>


A = _asarray_square(A)<EOL>if np.iscomplexobj(A):<EOL><INDENT>return -<NUM_LIT>*(expm(<NUM_LIT>*A) - expm(-<NUM_LIT>*A))<EOL><DEDENT>else:<EOL><INDENT>return expm(<NUM_LIT>*A).imag<EOL><DEDENT>


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>return _maybe_real(A, <NUM_LIT:0.5> * (expm(A) + expm(-A)))<EOL>

Compute the hyperbolic matrix cosine.

This routine uses expm to compute the matrix exponentials.

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

Returns
-------
coshm : (N, N) ndarray
    Hyperbolic matrix cosine of `A`

Examples
--------
>>> from scipy.linalg import tanhm, sinhm, coshm
>>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
>>> c = coshm(a)
>>> c
array([[ 11.24592233,  38.76236492],
       [ 12.92078831,  50.00828725]])

Verify tanhm(a) = sinhm(a).dot(inv(coshm(a)))

>>> t = tanhm(a)
>>> s = sinhm(a)
>>> t - s.dot(np.linalg.inv(c))
array([[  2.72004641e-15,   4.55191440e-15],
       [  0.00000000e+00,  -5.55111512e-16]])


A = _asarray_square(A)<EOL>return _maybe_real(A, <NUM_LIT:0.5> * (expm(A) - expm(-A)))<EOL>

Compute the hyperbolic matrix sine.

This routine uses expm to compute the matrix exponentials.

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

Returns
-------
sinhm : (N, N) ndarray
    Hyperbolic matrix sine of `A`

Examples
--------
>>> from scipy.linalg import tanhm, sinhm, coshm
>>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
>>> s = sinhm(a)
>>> s
array([[ 10.57300653,  39.28826594],
       [ 13.09608865,  49.86127247]])

Verify tanhm(a) = sinhm(a).dot(inv(coshm(a)))

>>> t = tanhm(a)
>>> c = coshm(a)
>>> t - s.dot(np.linalg.inv(c))
array([[  2.72004641e-15,   4.55191440e-15],
       [  0.00000000e+00,  -5.55111512e-16]])


A = _asarray_square(A)<EOL>return _maybe_real(A, solve(coshm(A), sinhm(A)))<EOL>

Compute the hyperbolic matrix tangent.

This routine uses expm to compute the matrix exponentials.

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

Returns
-------
tanhm : (N, N) ndarray
    Hyperbolic matrix tangent of `A`

Examples
--------
>>> from scipy.linalg import tanhm, sinhm, coshm
>>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
>>> t = tanhm(a)
>>> t
array([[ 0.3428582 ,  0.51987926],
       [ 0.17329309,  0.86273746]])

Verify tanhm(a) = sinhm(a).dot(inv(coshm(a)))

>>> s = sinhm(a)
>>> c = coshm(a)
>>> t - s.dot(np.linalg.inv(c))
array([[  2.72004641e-15,   4.55191440e-15],
       [  0.00000000e+00,  -5.55111512e-16]])


A = _asarray_square(A)<EOL>T, Z = schur(A)<EOL>T, Z = rsf2csf(T,Z)<EOL>n,n = T.shape<EOL>F = diag(func(diag(T)))  <EOL>F = F.astype(T.dtype.char)  <EOL>minden = abs(T[<NUM_LIT:0>,<NUM_LIT:0>])<EOL>for p in range(<NUM_LIT:1>,n):<EOL><INDENT>for i in range(<NUM_LIT:1>,n-p+<NUM_LIT:1>):<EOL><INDENT>j = i + p<EOL>s = T[i-<NUM_LIT:1>,j-<NUM_LIT:1>] * (F[j-<NUM_LIT:1>,j-<NUM_LIT:1>] - F[i-<NUM_LIT:1>,i-<NUM_LIT:1>])<EOL>ksl = slice(i,j-<NUM_LIT:1>)<EOL>val = dot(T[i-<NUM_LIT:1>,ksl],F[ksl,j-<NUM_LIT:1>]) - dot(F[i-<NUM_LIT:1>,ksl],T[ksl,j-<NUM_LIT:1>])<EOL>s = s + val<EOL>den = T[j-<NUM_LIT:1>,j-<NUM_LIT:1>] - T[i-<NUM_LIT:1>,i-<NUM_LIT:1>]<EOL>if den != <NUM_LIT:0.0>:<EOL><INDENT>s = s / den<EOL><DEDENT>F[i-<NUM_LIT:1>,j-<NUM_LIT:1>] = s<EOL>minden = min(minden,abs(den))<EOL><DEDENT><DEDENT>F = dot(dot(Z, F), transpose(conjugate(Z)))<EOL>F = _maybe_real(A, F)<EOL>tol = {<NUM_LIT:0>:feps, <NUM_LIT:1>:eps}[_array_precision[F.dtype.char]]<EOL>if minden == <NUM_LIT:0.0>:<EOL><INDENT>minden = tol<EOL><DEDENT>err = min(<NUM_LIT:1>, max(tol,(tol/minden)*norm(triu(T,<NUM_LIT:1>),<NUM_LIT:1>)))<EOL>if product(ravel(logical_not(isfinite(F))),axis=<NUM_LIT:0>):<EOL><INDENT>err = Inf<EOL><DEDENT>if disp:<EOL><INDENT>if err > <NUM_LIT:1000>*tol:<EOL><INDENT>print("<STR_LIT>", err)<EOL><DEDENT>return F<EOL><DEDENT>else:<EOL><INDENT>return F, err<EOL><DEDENT>

Evaluate a matrix function specified by a callable.

Returns the value of matrix-valued function ``f`` at `A`. The
function ``f`` is an extension of the scalar-valued function `func`
to matrices.

Parameters
----------
A : (N, N) array_like
    Matrix at which to evaluate the function
func : callable
    Callable object that evaluates a scalar function f.
    Must be vectorized (eg. using vectorize).
disp : bool, optional
    Print warning if error in the result is estimated large
    instead of returning estimated error. (Default: True)

Returns
-------
funm : (N, N) ndarray
    Value of the matrix function specified by func evaluated at `A`
errest : float
    (if disp == False)

    1-norm of the estimated error, ||err||_1 / ||A||_1

Examples
--------
>>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
>>> funm(a, lambda x: x*x)
array([[  4.,  15.],
       [  5.,  19.]])
>>> a.dot(a)
array([[  4.,  15.],
       [  5.,  19.]])


A = _asarray_square(A)<EOL>def rounded_sign(x):<EOL><INDENT>rx = np.real(x)<EOL>if rx.dtype.char == '<STR_LIT:f>':<EOL><INDENT>c = <NUM_LIT>*feps*amax(x)<EOL><DEDENT>else:<EOL><INDENT>c = <NUM_LIT>*eps*amax(x)<EOL><DEDENT>return sign((absolute(rx) > c) * rx)<EOL><DEDENT>result, errest = funm(A, rounded_sign, disp=<NUM_LIT:0>)<EOL>errtol = {<NUM_LIT:0>:<NUM_LIT>*feps, <NUM_LIT:1>:<NUM_LIT>*eps}[_array_precision[result.dtype.char]]<EOL>if errest < errtol:<EOL><INDENT>return result<EOL><DEDENT>vals = svd(A, compute_uv=<NUM_LIT:0>)<EOL>max_sv = np.amax(vals)<EOL>c = <NUM_LIT:0.5>/max_sv<EOL>S0 = A + c*np.identity(A.shape[<NUM_LIT:0>])<EOL>prev_errest = errest<EOL>for i in range(<NUM_LIT:100>):<EOL><INDENT>iS0 = inv(S0)<EOL>S0 = <NUM_LIT:0.5>*(S0 + iS0)<EOL>Pp = <NUM_LIT:0.5>*(dot(S0,S0)+S0)<EOL>errest = norm(dot(Pp,Pp)-Pp,<NUM_LIT:1>)<EOL>if errest < errtol or prev_errest == errest:<EOL><INDENT>break<EOL><DEDENT>prev_errest = errest<EOL><DEDENT>if disp:<EOL><INDENT>if not isfinite(errest) or errest >= errtol:<EOL><INDENT>print("<STR_LIT>", errest)<EOL><DEDENT>return S0<EOL><DEDENT>else:<EOL><INDENT>return S0, errest<EOL><DEDENT>

Matrix sign function.

Extension of the scalar sign(x) to matrices.

Parameters
----------
A : (N, N) array_like
    Matrix at which to evaluate the sign function
disp : bool, optional
    Print warning if error in the result is estimated large
    instead of returning estimated error. (Default: True)

Returns
-------
signm : (N, N) ndarray
    Value of the sign function at `A`
errest : float
    (if disp == False)

    1-norm of the estimated error, ||err||_1 / ||A||_1

Examples
--------
>>> from scipy.linalg import signm, eigvals
>>> a = [[1,2,3], [1,2,1], [1,1,1]]
>>> eigvals(a)
array([ 4.12488542+0.j, -0.76155718+0.j,  0.63667176+0.j])
>>> eigvals(signm(a))
array([-1.+0.j,  1.+0.j,  1.+0.j])


<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


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


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.


eye = np.eye(a.shape[<NUM_LIT:0>])<EOL>aH = a.conj().transpose()<EOL>aHI_inv = inv(aH + eye)<EOL>b = np.dot(aH - eye, aHI_inv)<EOL>c = <NUM_LIT:2>*np.dot(np.dot(inv(a + eye), q), aHI_inv)<EOL>return solve_lyapunov(b.conj().transpose(), -c)<EOL>

Solves the discrete Lyapunov equation using a bilinear transformation.

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


def solve_discrete_lyapunov(a, q, method=None):

a = np.asarray(a)<EOL>q = np.asarray(q)<EOL>if method is None:<EOL><INDENT>if a.shape[<NUM_LIT:0>] >= <NUM_LIT:10>:<EOL><INDENT>method = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>method = '<STR_LIT>'<EOL><DEDENT><DEDENT>meth = method.lower()<EOL>if meth == '<STR_LIT>':<EOL><INDENT>x = _solve_discrete_lyapunov_direct(a, q)<EOL><DEDENT>elif meth == '<STR_LIT>':<EOL><INDENT>x = _solve_discrete_lyapunov_bilinear(a, q)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>' % method)<EOL><DEDENT>return x<EOL>

Solves the discrete Lyapunov equation :math:`(A'XA-X=-Q)`.

Parameters
----------
a : (M, M) array_like
    A square matrix

q : (M, M) array_like
    Right-hand side square matrix

method : {'direct', 'bilinear'}, optional
    Type of solver.

    If not given, chosen to be ``direct`` if ``M`` is less than 10 and
    ``bilinear`` otherwise.

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

See Also
--------
solve_lyapunov : computes the solution to the continuous Lyapunov equation

Notes
-----
This section describes the available solvers that can be selected by the
'method' parameter. The default method is *direct* if ``M`` is less than 10
and ``bilinear`` otherwise.

Method *direct* uses a direct analytical solution to the discrete Lyapunov
equation. The algorithm is given in, for example, [1]_. However it requires
the linear solution of a system with dimension :math:`M^2` so that
performance degrades rapidly for even moderately sized matrices.

Method *bilinear* uses a bilinear transformation to convert the discrete
Lyapunov equation to a continuous Lyapunov equation :math:`(B'X+XB=-C)`
where :math:`B=(A-I)(A+I)^{-1}` and
:math:`C=2(A' + I)^{-1} Q (A + I)^{-1}`. The continuous equation can be
efficiently solved since it is a special case of a Sylvester equation.
The transformation algorithm is from Popov (1964) as described in [2]_.

.. versionadded:: 0.11.0

References
----------
.. [1] Hamilton, James D. Time Series Analysis, Princeton: Princeton
   University Press, 1994.  265.  Print.
   http://www.scribd.com/doc/20577138/Hamilton-1994-Time-Series-Analysis
.. [2] Gajic, Z., and M.T.J. Qureshi. 2008.
   Lyapunov Matrix Equation in System Stability and Control.
   Dover Books on Engineering Series. Dover Publications.


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>z11 = a<EOL>z12 = -<NUM_LIT:1.0>*g<EOL>z21 = -<NUM_LIT:1.0>*q<EOL>z22 = -<NUM_LIT:1.0>*a.conj().transpose()<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 continuous algebraic Riccati equation, or CARE, defined
as (A'X + XA - XBR^-1B'X+Q=0) directly using a Schur decomposition
method.

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

Returns
-------
x : (M, M) ndarray
    Solution to the continuous algebraic Riccati equation

See Also
--------
solve_discrete_are : Solves the discrete 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


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


def tri(N, M=None, k=<NUM_LIT:0>, dtype=None):

if M is None:<EOL><INDENT>M = N<EOL><DEDENT>if isinstance(M, string_types):<EOL><INDENT>dtype = M<EOL>M = N<EOL><DEDENT>m = np.greater_equal(np.subtract.outer(np.arange(N), np.arange(M)), -k)<EOL>if dtype is None:<EOL><INDENT>return m<EOL><DEDENT>else:<EOL><INDENT>return m.astype(dtype)<EOL><DEDENT>

Construct (N, M) matrix filled with ones at and below the k-th diagonal.

The matrix has A[i,j] == 1 for i <= j + k

Parameters
----------
N : integer
    The size of the first dimension of the matrix.
M : integer or None
    The size of the second dimension of the matrix. If `M` is None,
    `M = N` is assumed.
k : integer
    Number of subdiagonal below which matrix is filled with ones.
    `k` = 0 is the main diagonal, `k` < 0 subdiagonal and `k` > 0
    superdiagonal.
dtype : dtype
    Data type of the matrix.

Returns
-------
tri : (N, M) ndarray
    Tri matrix.

Examples
--------
>>> from scipy.linalg import tri
>>> tri(3, 5, 2, dtype=int)
array([[1, 1, 1, 0, 0],
       [1, 1, 1, 1, 0],
       [1, 1, 1, 1, 1]])
>>> tri(3, 5, -1, dtype=int)
array([[0, 0, 0, 0, 0],
       [1, 0, 0, 0, 0],
       [1, 1, 0, 0, 0]])


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

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

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

Returns
-------
tril : ndarray
    Return is the same shape and type as `m`.

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


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