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

Return a random symmetric (Hermitian) matrix.

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

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


H = eye(dim)<EOL>D = ones((dim,))<EOL>for n in range(<NUM_LIT:1>, dim):<EOL><INDENT>x = normal(size=(dim-n+<NUM_LIT:1>,))<EOL>D[n-<NUM_LIT:1>] = sign(x[<NUM_LIT:0>])<EOL>x[<NUM_LIT:0>] -= D[n-<NUM_LIT:1>]*sqrt((x*x).sum())<EOL>Hx = eye(dim-n+<NUM_LIT:1>) - <NUM_LIT>*outer(x, x)/(x*x).sum()<EOL>mat = eye(dim)<EOL>mat[n-<NUM_LIT:1>:,n-<NUM_LIT:1>:] = Hx<EOL>H = dot(H, mat)<EOL><DEDENT>D[-<NUM_LIT:1>] = -D.prod()<EOL>H = (D*H.T).T<EOL>return H<EOL>

Return a random rotation matrix, drawn from the Haar distribution
    (the only uniform distribution on SO(n)).
    The algorithm is described in the paper
    Stewart, G.W., 'The efficient generation of random orthogonal
    matrices with an application to condition estimators', SIAM Journal
    on Numerical Analysis, 17(3), pp. 403-409, 1980.
    For more information see
    http://en.wikipedia.org/wiki/Orthogonal_matrix#Randomization


def eigenhproblem_standard(desc, dim, dtype,<EOL>overwrite, lower, turbo,<EOL>eigvals):

if iscomplex(empty(<NUM_LIT:1>, dtype=dtype)):<EOL><INDENT>a = _complex_symrand(dim, dtype)<EOL><DEDENT>else:<EOL><INDENT>a = symrand(dim).astype(dtype)<EOL><DEDENT>if overwrite:<EOL><INDENT>a_c = a.copy()<EOL><DEDENT>else:<EOL><INDENT>a_c = a<EOL><DEDENT>w, z = eigh(a, overwrite_a=overwrite, lower=lower, eigvals=eigvals)<EOL>assert_dtype_equal(z.dtype, dtype)<EOL>w = w.astype(dtype)<EOL>diag_ = diag(dot(z.T.conj(), dot(a_c, z))).real<EOL>assert_array_almost_equal(diag_, w, DIGITS[dtype])<EOL>


def eigenhproblem_general(desc, dim, dtype,<EOL>overwrite, lower, turbo,<EOL>eigvals):

if iscomplex(empty(<NUM_LIT:1>, dtype=dtype)):<EOL><INDENT>a = _complex_symrand(dim, dtype)<EOL>b = _complex_symrand(dim, dtype)+diag([<NUM_LIT>]*dim).astype(dtype)<EOL><DEDENT>else:<EOL><INDENT>a = symrand(dim).astype(dtype)<EOL>b = symrand(dim).astype(dtype)+diag([<NUM_LIT>]*dim).astype(dtype)<EOL><DEDENT>if overwrite:<EOL><INDENT>a_c, b_c = a.copy(), b.copy()<EOL><DEDENT>else:<EOL><INDENT>a_c, b_c = a, b<EOL><DEDENT>w, z = eigh(a, b, overwrite_a=overwrite, lower=lower,<EOL>overwrite_b=overwrite, turbo=turbo, eigvals=eigvals)<EOL>assert_dtype_equal(z.dtype, dtype)<EOL>w = w.astype(dtype)<EOL>diag1_ = diag(dot(z.T.conj(), dot(a_c, z))).real<EOL>assert_array_almost_equal(diag1_, w, DIGITS[dtype])<EOL>diag2_ = diag(dot(z.T.conj(), dot(b_c, z))).real<EOL>assert_array_almost_equal(diag2_, ones(diag2_.shape[<NUM_LIT:0>]), DIGITS[dtype])<EOL>


N = <NUM_LIT:10><EOL>self.KL = <NUM_LIT:2>   <EOL>self.KU = <NUM_LIT:2>   <EOL>self.sym_mat = (diag(<NUM_LIT:1.0>*ones(N))<EOL>+ diag(-<NUM_LIT:1.0>*ones(N-<NUM_LIT:1>), -<NUM_LIT:1>) + diag(-<NUM_LIT:1.0>*ones(N-<NUM_LIT:1>), <NUM_LIT:1>)<EOL>+ diag(-<NUM_LIT>*ones(N-<NUM_LIT:2>), -<NUM_LIT:2>) + diag(-<NUM_LIT>*ones(N-<NUM_LIT:2>), <NUM_LIT:2>))<EOL>self.herm_mat = (diag(-<NUM_LIT:1.0>*ones(N))<EOL>+ <NUM_LIT>*diag(<NUM_LIT:1.0>*ones(N-<NUM_LIT:1>), -<NUM_LIT:1>) - <NUM_LIT>*diag(<NUM_LIT:1.0>*ones(N-<NUM_LIT:1>), <NUM_LIT:1>)<EOL>+ diag(-<NUM_LIT>*ones(N-<NUM_LIT:2>), -<NUM_LIT:2>) + diag(-<NUM_LIT>*ones(N-<NUM_LIT:2>), <NUM_LIT:2>))<EOL>self.real_mat = (diag(<NUM_LIT:1.0>*ones(N))<EOL>+ diag(-<NUM_LIT:1.0>*ones(N-<NUM_LIT:1>), -<NUM_LIT:1>) + diag(-<NUM_LIT>*ones(N-<NUM_LIT:1>), <NUM_LIT:1>)<EOL>+ diag(<NUM_LIT>*ones(N-<NUM_LIT:2>), -<NUM_LIT:2>) + diag(-<NUM_LIT>*ones(N-<NUM_LIT:2>), <NUM_LIT:2>))<EOL>self.comp_mat = (<NUM_LIT>*diag(<NUM_LIT:1.0>*ones(N))<EOL>+ diag(-<NUM_LIT:1.0>*ones(N-<NUM_LIT:1>), -<NUM_LIT:1>) + <NUM_LIT>*diag(-<NUM_LIT>*ones(N-<NUM_LIT:1>), <NUM_LIT:1>)<EOL>+ diag(<NUM_LIT>*ones(N-<NUM_LIT:2>), -<NUM_LIT:2>) + diag(-<NUM_LIT>*ones(N-<NUM_LIT:2>), <NUM_LIT:2>))<EOL>ew, ev = linalg.eig(self.sym_mat)<EOL>ew = ew.real<EOL>args = argsort(ew)<EOL>self.w_sym_lin = ew[args]<EOL>self.evec_sym_lin = ev[:,args]<EOL>ew, ev = linalg.eig(self.herm_mat)<EOL>ew = ew.real<EOL>args = argsort(ew)<EOL>self.w_herm_lin = ew[args]<EOL>self.evec_herm_lin = ev[:,args]<EOL>LDAB = self.KU + <NUM_LIT:1><EOL>self.bandmat_sym = zeros((LDAB, N), dtype=float)<EOL>self.bandmat_herm = zeros((LDAB, N), dtype=complex)<EOL>for i in xrange(LDAB):<EOL><INDENT>self.bandmat_sym[LDAB-i-<NUM_LIT:1>,i:N] = diag(self.sym_mat, i)<EOL>self.bandmat_herm[LDAB-i-<NUM_LIT:1>,i:N] = diag(self.herm_mat, i)<EOL><DEDENT>LDAB = <NUM_LIT:2>*self.KL + self.KU + <NUM_LIT:1><EOL>self.bandmat_real = zeros((LDAB, N), dtype=float)<EOL>self.bandmat_real[<NUM_LIT:2>*self.KL,:] = diag(self.real_mat)     <EOL>for i in xrange(self.KL):<EOL><INDENT>self.bandmat_real[<NUM_LIT:2>*self.KL-<NUM_LIT:1>-i,i+<NUM_LIT:1>:N] = diag(self.real_mat, i+<NUM_LIT:1>)<EOL>self.bandmat_real[<NUM_LIT:2>*self.KL+<NUM_LIT:1>+i,<NUM_LIT:0>:N-<NUM_LIT:1>-i] = diag(self.real_mat,-i-<NUM_LIT:1>)<EOL><DEDENT>self.bandmat_comp = zeros((LDAB, N), dtype=complex)<EOL>self.bandmat_comp[<NUM_LIT:2>*self.KL,:] = diag(self.comp_mat)     <EOL>for i in xrange(self.KL):<EOL><INDENT>self.bandmat_comp[<NUM_LIT:2>*self.KL-<NUM_LIT:1>-i,i+<NUM_LIT:1>:N] = diag(self.comp_mat, i+<NUM_LIT:1>)<EOL>self.bandmat_comp[<NUM_LIT:2>*self.KL+<NUM_LIT:1>+i,<NUM_LIT:0>:N-<NUM_LIT:1>-i] = diag(self.comp_mat,-i-<NUM_LIT:1>)<EOL><DEDENT>self.b = <NUM_LIT:1.0>*arange(N)<EOL>self.bc = self.b * (<NUM_LIT:1> + <NUM_LIT>)<EOL>

Create the full matrix `self.fullmat` and
           the corresponding band matrix `self.bandmat`.


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

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


<EOL>if isinstance(seed, str) and seed == '<STR_LIT:default>':<EOL><INDENT>backend.id_srando()<EOL><DEDENT>elif hasattr(seed, '<STR_LIT>'):<EOL><INDENT>state = np.asfortranarray(seed, dtype=float)<EOL>if state.shape != (<NUM_LIT>,):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>elif state.min() < <NUM_LIT:0> or state.max() > <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>backend.id_srandi(state)<EOL><DEDENT>elif seed is None:<EOL><INDENT>backend.id_srandi(np.random.rand(<NUM_LIT>))<EOL><DEDENT>else:<EOL><INDENT>rnd = np.random.RandomState(seed)<EOL>backend.id_srandi(rnd.rand(<NUM_LIT>))<EOL><DEDENT>

Seed the internal random number generator used in this ID package.

The generator is a lagged Fibonacci method with 55-element internal state.

Parameters
----------
seed : int, sequence, 'default', optional
    If 'default', the random seed is reset to a default value.

    If `seed` is a sequence containing 55 floating-point numbers
    in range [0,1], these are used to set the internal state of
    the generator.

    If the value is an integer, the internal state is obtained
    from `numpy.random.RandomState` (MT19937) with the integer
    used as the initial seed.

    If `seed` is omitted (None), `numpy.random` is used to
    initialize the generator.


<EOL>return backend.id_srand(np.prod(shape)).reshape(shape)<EOL>

Generate standard uniform pseudorandom numbers via a very efficient lagged
Fibonacci method.

This routine is used for all random number generation in this package and
can affect ID and SVD results.

Parameters
----------
shape
    Shape of output array


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

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

Compute ID of a matrix.

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

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

The original matrix can then be reconstructed as::

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

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

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

in terms of the skeleton and interpolation matrices::

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

and::

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

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

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

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

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

    idx, proj = interp_decomp(A, eps_or_k)

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

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

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


def reconstruct_matrix_from_id(B, idx, proj):

if _is_real(B):<EOL><INDENT>return backend.idd_reconid(B, idx + <NUM_LIT:1>, proj)<EOL><DEDENT>else:<EOL><INDENT>return backend.idz_reconid(B, idx + <NUM_LIT:1>, proj)<EOL><DEDENT>

Reconstruct matrix from its ID.

A matrix `A` with skeleton matrix `B` and ID indices and coefficients `idx`
and `proj`, respectively, can be reconstructed as::

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

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

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

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

Returns
-------
:class:`numpy.ndarray`
    Reconstructed matrix.


if _is_real(proj):<EOL><INDENT>return backend.idd_reconint(idx + <NUM_LIT:1>, proj)<EOL><DEDENT>else:<EOL><INDENT>return backend.idz_reconint(idx + <NUM_LIT:1>, proj)<EOL><DEDENT>

Reconstruct interpolation matrix from ID.

The interpolation matrix can be reconstructed from the ID indices and
coefficients `idx` and `proj`, respectively, as::

    P = numpy.hstack([numpy.eye(proj.shape[0]), proj])[:,numpy.argsort(idx)]

The original matrix can then be reconstructed from its skeleton matrix `B`
via::

    numpy.dot(B, P)

See also :func:`reconstruct_matrix_from_id` and
:func:`reconstruct_skel_matrix`.

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

Parameters
----------
idx : :class:`numpy.ndarray`
    Column index array.
proj : :class:`numpy.ndarray`
    Interpolation coefficients.

Returns
-------
:class:`numpy.ndarray`
    Interpolation matrix.


if _is_real(A):<EOL><INDENT>return backend.idd_copycols(A, k, idx + <NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>return backend.idz_copycols(A, k, idx + <NUM_LIT:1>)<EOL><DEDENT>

Reconstruct skeleton matrix from ID.

The skeleton matrix can be reconstructed from the original matrix `A` and its
ID rank and indices `k` and `idx`, respectively, as::

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

The original matrix can then be reconstructed via::

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

See also :func:`reconstruct_matrix_from_id` and
:func:`reconstruct_interp_matrix`.

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

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

Returns
-------
:class:`numpy.ndarray`
    Skeleton matrix.


if _is_real(B):<EOL><INDENT>U, V, S = backend.idd_id2svd(B, idx + <NUM_LIT:1>, proj)<EOL><DEDENT>else:<EOL><INDENT>U, V, S = backend.idz_id2svd(B, idx + <NUM_LIT:1>, proj)<EOL><DEDENT>return U, S, V<EOL>

Convert ID to SVD.

The SVD reconstruction of a matrix with skeleton matrix `B` and ID indices and
coefficients `idx` and `proj`, respectively, is::

    U, S, V = id_to_svd(B, idx, proj)
    A = numpy.dot(U, numpy.dot(numpy.diag(S), V.conj().T))

See also :func:`svd`.

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

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

Returns
-------
U : :class:`numpy.ndarray`
    Left singular vectors.
S : :class:`numpy.ndarray`
    Singular values.
V : :class:`numpy.ndarray`
    Right singular vectors.


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

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

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

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

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


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

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

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

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

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

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


from scipy.sparse.linalg import LinearOperator<EOL>real = _is_real(A)<EOL>if isinstance(A, np.ndarray):<EOL><INDENT>if eps_or_k < <NUM_LIT:1>:<EOL><INDENT>eps = eps_or_k<EOL>if rand:<EOL><INDENT>if real:<EOL><INDENT>U, V, S = backend.iddp_asvd(eps, A)<EOL><DEDENT>else:<EOL><INDENT>U, V, S = backend.idzp_asvd(eps, A)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if real:<EOL><INDENT>U, V, S = backend.iddp_svd(eps, A)<EOL><DEDENT>else:<EOL><INDENT>U, V, S = backend.idzp_svd(eps, A)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>k = int(eps_or_k)<EOL>if rand:<EOL><INDENT>if real:<EOL><INDENT>U, V, S = backend.iddr_asvd(A, k)<EOL><DEDENT>else:<EOL><INDENT>U, V, S = backend.idzr_asvd(A, k)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if real:<EOL><INDENT>U, V, S = backend.iddr_svd(A, k)<EOL><DEDENT>else:<EOL><INDENT>U, V, S = backend.idzr_svd(A, k)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>elif isinstance(A, LinearOperator):<EOL><INDENT>m, n = A.shape<EOL>matvec = lambda x: A.matvec(x)<EOL>matveca = lambda x: A.rmatvec(x)<EOL>if eps_or_k < <NUM_LIT:1>:<EOL><INDENT>eps = eps_or_k<EOL>if real:<EOL><INDENT>U, V, S = backend.iddp_rsvd(eps, m, n, matveca, matvec)<EOL><DEDENT>else:<EOL><INDENT>U, V, S = backend.idzp_rsvd(eps, m, n, matveca, matvec)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>k = int(eps_or_k)<EOL>if real:<EOL><INDENT>U, V, S = backend.iddr_rsvd(m, n, matveca, matvec, k)<EOL><DEDENT>else:<EOL><INDENT>U, V, S = backend.idzr_rsvd(m, n, matveca, matvec, k)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>raise _TYPE_ERROR<EOL><DEDENT>return U, S, V<EOL>

Compute SVD of a matrix via an ID.

An SVD of a matrix `A` is a factorization::

    A = numpy.dot(U, numpy.dot(numpy.diag(S), V.conj().T))

where `U` and `V` have orthonormal columns and `S` is nonnegative.

The SVD can be computed to any relative precision or rank (depending on the
value of `eps_or_k`).

See also :func:`interp_decomp` and :func:`id_to_svd`.

..  This function automatically detects the form of the input parameters and
    passes them to the appropriate backend. For details, see
    :func:`backend.iddp_svd`, :func:`backend.iddp_asvd`,
    :func:`backend.iddp_rsvd`, :func:`backend.iddr_svd`,
    :func:`backend.iddr_asvd`, :func:`backend.iddr_rsvd`,
    :func:`backend.idzp_svd`, :func:`backend.idzp_asvd`,
    :func:`backend.idzp_rsvd`, :func:`backend.idzr_svd`,
    :func:`backend.idzr_asvd`, and :func:`backend.idzr_rsvd`.

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

Returns
-------
U : :class:`numpy.ndarray`
    Left singular vectors.
S : :class:`numpy.ndarray`
    Singular values.
V : :class:`numpy.ndarray`
    Right singular vectors.


from scipy.sparse.linalg import LinearOperator<EOL>real = _is_real(A)<EOL>if isinstance(A, np.ndarray):<EOL><INDENT>if real:<EOL><INDENT>rank = backend.idd_estrank(eps, A)<EOL><DEDENT>else:<EOL><INDENT>rank = backend.idz_estrank(eps, A)<EOL><DEDENT>if rank == <NUM_LIT:0>:<EOL><INDENT>rank = min(A.shape)<EOL><DEDENT>return rank<EOL><DEDENT>elif isinstance(A, LinearOperator):<EOL><INDENT>m, n = A.shape<EOL>matveca = A.rmatvec<EOL>if real:<EOL><INDENT>return backend.idd_findrank(eps, m, n, matveca)<EOL><DEDENT>else:<EOL><INDENT>return backend.idz_findrank(eps, m, n, matveca)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise _TYPE_ERROR<EOL><DEDENT>

Estimate matrix rank to a specified relative precision using randomized
methods.

The matrix `A` can be given as either a :class:`numpy.ndarray` or a
:class:`scipy.sparse.linalg.LinearOperator`, with different algorithms used
for each case. If `A` is of type :class:`numpy.ndarray`, then the output
rank is typically about 8 higher than the actual numerical rank.

..  This function automatically detects the form of the input parameters and
    passes them to the appropriate backend. For details,
    see :func:`backend.idd_estrank`, :func:`backend.idd_findrank`,
    :func:`backend.idz_estrank`, and :func:`backend.idz_findrank`.

Parameters
----------
A : :class:`numpy.ndarray` or :class:`scipy.sparse.linalg.LinearOperator`
    Matrix whose rank is to be estimated, given as either a
    :class:`numpy.ndarray` or a :class:`scipy.sparse.linalg.LinearOperator`
    with the `rmatvec` method (to apply the matrix adjoint).
eps : float
    Relative error for numerical rank definition.

Returns
-------
int
    Estimated matrix rank.


def _cholesky(a, lower=False, overwrite_a=False, clean=True,<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>potrf, = get_lapack_funcs(('<STR_LIT>',), (a1,))<EOL>c, info = potrf(a1, lower=lower, overwrite_a=overwrite_a, clean=clean)<EOL>if info > <NUM_LIT:0>:<EOL><INDENT>raise LinAlgError("<STR_LIT>" % info)<EOL><DEDENT>if info < <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>% -info)<EOL><DEDENT>return c, lower<EOL>

Common code for cholesky() and cho_factor().


def cholesky(a, lower=False, overwrite_a=False, check_finite=True):

c, lower = _cholesky(a, lower=lower, overwrite_a=overwrite_a, clean=True,<EOL>check_finite=check_finite)<EOL>return c<EOL>

Compute the Cholesky decomposition of a matrix.

Returns the Cholesky decomposition, :math:`A = L L^*` or
:math:`A = U^* U` of a Hermitian positive-definite matrix A.

Parameters
----------
a : (M, M) array_like
    Matrix to be decomposed
lower : bool
    Whether to compute the upper or lower triangular Cholesky
    factorization.  Default is upper-triangular.
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
-------
c : (M, M) ndarray
    Upper- or lower-triangular Cholesky factor of `a`.

Raises
------
LinAlgError : if decomposition fails.

Examples
--------
>>> from scipy import array, linalg, dot
>>> a = array([[1,-2j],[2j,5]])
>>> L = linalg.cholesky(a, lower=True)
>>> L
array([[ 1.+0.j,  0.+0.j],
       [ 0.+2.j,  1.+0.j]])
>>> dot(L, L.T.conj())
array([[ 1.+0.j,  0.-2.j],
       [ 0.+2.j,  5.+0.j]])


def cho_factor(a, lower=False, overwrite_a=False, check_finite=True):

c, lower = _cholesky(a, lower=lower, overwrite_a=overwrite_a, clean=False,<EOL>check_finite=check_finite)<EOL>return c, lower<EOL>

Compute the Cholesky decomposition of a matrix, to use in cho_solve

Returns a matrix containing the Cholesky decomposition,
``A = L L*`` or ``A = U* U`` of a Hermitian positive-definite matrix `a`.
The return value can be directly used as the first parameter to cho_solve.

.. warning::
    The returned matrix also contains random data in the entries not
    used by the Cholesky decomposition. If you need to zero these
    entries, use the function `cholesky` instead.

Parameters
----------
a : (M, M) array_like
    Matrix to be decomposed
lower : boolean
    Whether to compute the upper or lower triangular Cholesky factorization
    (Default: upper-triangular)
overwrite_a : boolean
    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
-------
c : (M, M) ndarray
    Matrix whose upper or lower triangle contains the Cholesky factor
    of `a`. Other parts of the matrix contain random data.
lower : boolean
    Flag indicating whether the factor is in the lower or upper triangle

Raises
------
LinAlgError
    Raised if decomposition fails.

See also
--------
cho_solve : Solve a linear set equations using the Cholesky factorization
            of a matrix.


def cho_solve(c_and_lower, b, overwrite_b=False, check_finite=True):

(c, lower) = c_and_lower<EOL>if check_finite:<EOL><INDENT>b1 = asarray_chkfinite(b)<EOL>c = asarray_chkfinite(c)<EOL><DEDENT>else:<EOL><INDENT>b1 = asarray(b)<EOL>c = asarray(c)<EOL><DEDENT>if c.ndim != <NUM_LIT:2> or c.shape[<NUM_LIT:0>] != c.shape[<NUM_LIT:1>]:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if c.shape[<NUM_LIT:1>] != b1.shape[<NUM_LIT:0>]:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>overwrite_b = overwrite_b or _datacopied(b1, b)<EOL>potrs, = get_lapack_funcs(('<STR_LIT>',), (c, b1))<EOL>x, info = potrs(c, b1, lower=lower, overwrite_b=overwrite_b)<EOL>if info != <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>% -info)<EOL><DEDENT>return x<EOL>

Solve the linear equations A x = b, given the Cholesky factorization of A.

    Parameters
    ----------
    (c, lower) : tuple, (array, bool)
        Cholesky factorization of a, as given by cho_factor
    b : array
        Right-hand side
    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
        The solution to the system A x = b

    See also
    --------
    cho_factor : Cholesky factorization of a matrix


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

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

Cholesky decompose a banded Hermitian positive-definite matrix

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

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

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

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

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

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

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


def cho_solve_banded(cb_and_lower, b, overwrite_b=False, check_finite=True):

(cb, lower) = cb_and_lower<EOL>if check_finite:<EOL><INDENT>cb = asarray_chkfinite(cb)<EOL>b = asarray_chkfinite(b)<EOL><DEDENT>else:<EOL><INDENT>cb = asarray(cb)<EOL>b = asarray(b)<EOL><DEDENT>if cb.shape[-<NUM_LIT:1>] != b.shape[<NUM_LIT:0>]:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>pbtrs, = get_lapack_funcs(('<STR_LIT>',), (cb, b))<EOL>x, info = pbtrs(cb, b, lower=lower, 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 the linear equations A x = b, given the Cholesky factorization of A.

    Parameters
    ----------
    (cb, lower) : tuple, (array, bool)
        `cb` is the Cholesky factorization of A, as given by cholesky_banded.
        `lower` must be the same value that was given to cholesky_banded.
    b : array
        Right-hand side
    overwrite_b : bool
        If True, the function will overwrite the values in `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
        The solution to the system A x = b

    See also
    --------
    cholesky_banded : Cholesky factorization of a banded matrix

    Notes
    -----

    .. versionadded:: 0.8.0


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

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

Singular Value Decomposition.

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

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

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

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

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

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

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

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

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


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

return svd(a, compute_uv=<NUM_LIT:0>, overwrite_a=overwrite_a,<EOL>check_finite=check_finite)<EOL>

Compute singular values of a matrix.

Parameters
----------
a : (M, N) array_like
    Matrix to decompose.
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
-------
s : (min(M, N),) ndarray
    The singular values, sorted in decreasing order.

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

See also
--------
svd : Compute the full singular value decomposition of a matrix.
diagsvd : Construct the Sigma matrix, given the vector s.


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

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

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

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


u, s, vh = svd(A, full_matrices=False)<EOL>M, N = A.shape<EOL>eps = numpy.finfo(float).eps<EOL>tol = max(M,N) * numpy.amax(s) * eps<EOL>num = numpy.sum(s > tol, dtype=int)<EOL>Q = u[:,:num]<EOL>return Q<EOL>

Construct an orthonormal basis for the range of A using SVD

Parameters
----------
A : (M, N) ndarray
    Input array

Returns
-------
Q : (M, K) ndarray
    Orthonormal basis for the range of A.
    K = effective rank of A, as determined by automatic cutoff

See also
--------
svd : Singular value decomposition of a matrix


def orthogonal_procrustes(A, B, check_finite=True):

if check_finite:<EOL><INDENT>A = np.asarray_chkfinite(A)<EOL>B = np.asarray_chkfinite(B)<EOL><DEDENT>else:<EOL><INDENT>A = np.asanyarray(A)<EOL>B = np.asanyarray(B)<EOL><DEDENT>if A.ndim != <NUM_LIT:2>:<EOL><INDENT>raise ValueError('<STR_LIT>' % A.ndim)<EOL><DEDENT>if A.shape != B.shape:<EOL><INDENT>raise ValueError('<STR_LIT>' % (<EOL>A.shape, B.shape))<EOL><DEDENT>u, w, vt = svd(B.T.dot(A).T)<EOL>R = u.dot(vt)<EOL>scale = w.sum()<EOL>return R, scale<EOL>

Compute the matrix solution of the orthogonal Procrustes problem.

Given matrices A and B of equal shape, find an orthogonal matrix R
that most closely maps A to B [1]_.
Note that unlike higher level Procrustes analyses of spatial data,
this function only uses orthogonal transformations like rotations
and reflections, and it does not use scaling or translation.

Parameters
----------
A : (M, N) array_like
    Matrix to be mapped.
B : (M, N) array_like
    Target matrix.
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
-------
R : (N, N) ndarray
    The matrix solution of the orthogonal Procrustes problem.
    Minimizes the Frobenius norm of dot(A, R) - B, subject to
    dot(R.T, R) == I.
scale : float
    Sum of the singular values of ``dot(A.T, B)``.

Raises
------
ValueError
    If the input arrays are incompatibly shaped.
    This may also be raised if matrix A or B contains an inf or nan
    and check_finite is True, or if the matrix product AB contains
    an inf or nan.

References
----------
.. [1] Peter H. Schonemann, "A generalized solution of the orthogonal
       Procrustes problem", Psychometrica -- Vol. 31, No. 1, March, 1996.


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

Compute the polar decomposition.

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

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

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

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

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

A non-square example, with m < n:

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

Another non-square example, with m > n:

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


T_diag = np.diag(T)<EOL>keep_it_real = np.isrealobj(T) and np.min(T_diag) >= <NUM_LIT:0><EOL>if not keep_it_real:<EOL><INDENT>T_diag = T_diag.astype(complex)<EOL><DEDENT>R = np.diag(np.sqrt(T_diag))<EOL>n, n = T.shape<EOL>nblocks = max(n // blocksize, <NUM_LIT:1>)<EOL>bsmall, nlarge = divmod(n, nblocks)<EOL>blarge = bsmall + <NUM_LIT:1><EOL>nsmall = nblocks - nlarge<EOL>if nsmall * bsmall + nlarge * blarge != n:<EOL><INDENT>raise Exception('<STR_LIT>')<EOL><DEDENT>start_stop_pairs = []<EOL>start = <NUM_LIT:0><EOL>for count, size in ((nsmall, bsmall), (nlarge, blarge)):<EOL><INDENT>for i in range(count):<EOL><INDENT>start_stop_pairs.append((start, start + size))<EOL>start += size<EOL><DEDENT><DEDENT>for start, stop in start_stop_pairs:<EOL><INDENT>for j in range(start, stop):<EOL><INDENT>for i in range(j-<NUM_LIT:1>, start-<NUM_LIT:1>, -<NUM_LIT:1>):<EOL><INDENT>s = <NUM_LIT:0><EOL>if j - i > <NUM_LIT:1>:<EOL><INDENT>s = R[i, i+<NUM_LIT:1>:j].dot(R[i+<NUM_LIT:1>:j, j])<EOL><DEDENT>denom = R[i, i] + R[j, j]<EOL>if not denom:<EOL><INDENT>raise SqrtmError('<STR_LIT>')<EOL><DEDENT>R[i,j] = (T[i,j] - s) / denom<EOL><DEDENT><DEDENT><DEDENT>for j in range(nblocks):<EOL><INDENT>jstart, jstop = start_stop_pairs[j]<EOL>for i in range(j-<NUM_LIT:1>, -<NUM_LIT:1>, -<NUM_LIT:1>):<EOL><INDENT>istart, istop = start_stop_pairs[i]<EOL>S = T[istart:istop, jstart:jstop]<EOL>if j - i > <NUM_LIT:1>:<EOL><INDENT>S = S - R[istart:istop, istop:jstart].dot(<EOL>R[istop:jstart, jstart:jstop])<EOL><DEDENT>Rii = R[istart:istop, istart:istop]<EOL>Rjj = R[jstart:jstop, jstart:jstop]<EOL>if keep_it_real:<EOL><INDENT>x, scale, info = dtrsyl(Rii, Rjj, S)<EOL><DEDENT>else:<EOL><INDENT>x, scale, info = ztrsyl(Rii, Rjj, S)<EOL><DEDENT>R[istart:istop, jstart:jstop] = x * scale<EOL><DEDENT><DEDENT>return R<EOL>

Matrix square root of an upper triangular matrix.

This is a helper function for `sqrtm` and `logm`.

Parameters
----------
T : (N, N) array_like upper triangular
    Matrix whose square root to evaluate
blocksize : integer, optional
    If the blocksize is not degenerate with respect to the
    size of the input array, then use a blocked algorithm. (Default: 64)

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

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


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

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

Matrix square root.

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

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

errest : float
    (if disp == False)

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

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

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


def expm_frechet(A, E, method=None, compute_expm=True, check_finite=True):

if check_finite:<EOL><INDENT>A = np.asarray_chkfinite(A)<EOL>E = np.asarray_chkfinite(E)<EOL><DEDENT>else:<EOL><INDENT>A = np.asarray(A)<EOL>E = np.asarray(E)<EOL><DEDENT>if A.ndim != <NUM_LIT:2> or A.shape[<NUM_LIT:0>] != A.shape[<NUM_LIT:1>]:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if E.ndim != <NUM_LIT:2> or E.shape[<NUM_LIT:0>] != E.shape[<NUM_LIT:1>]:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if A.shape != E.shape:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if method is None:<EOL><INDENT>method = '<STR_LIT>'<EOL><DEDENT>if method == '<STR_LIT>':<EOL><INDENT>expm_A, expm_frechet_AE = expm_frechet_algo_64(A, E)<EOL><DEDENT>elif method == '<STR_LIT>':<EOL><INDENT>expm_A, expm_frechet_AE = expm_frechet_block_enlarge(A, E)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>' % method)<EOL><DEDENT>if compute_expm:<EOL><INDENT>return expm_A, expm_frechet_AE<EOL><DEDENT>else:<EOL><INDENT>return expm_frechet_AE<EOL><DEDENT>

Frechet derivative of the matrix exponential of A in the direction E.

Parameters
----------
A : (N, N) array_like
    Matrix of which to take the matrix exponential.
E : (N, N) array_like
    Matrix direction in which to take the Frechet derivative.
method : str, optional
    Choice of algorithm.  Should be one of

    - `SPS` (default)
    - `blockEnlarge`

compute_expm : bool, optional
    Whether to compute also `expm_A` in addition to `expm_frechet_AE`.
    Default is True.
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
-------
expm_A : ndarray
    Matrix exponential of A.
expm_frechet_AE : ndarray
    Frechet derivative of the matrix exponential of A in the direction E.

For ``compute_expm = False``, only `expm_frechet_AE` is returned.

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

Notes
-----
This section describes the available implementations that can be selected
by the `method` parameter. The default method is *SPS*.

Method *blockEnlarge* is a naive algorithm.

Method *SPS* is Scaling-Pade-Squaring [1]_.
It is a sophisticated implementation which should take
only about 3/8 as much time as the naive implementation.
The asymptotics are the same.

.. versionadded:: 0.13.0

References
----------
.. [1] Awad H. Al-Mohy and Nicholas J. Higham (2009)
       Computing the Frechet Derivative of the Matrix Exponential,
       with an application to Condition Number Estimation.
       SIAM Journal On Matrix Analysis and Applications.,
       30 (4). pp. 1639-1657. ISSN 1095-7162

Examples
--------
>>> import scipy.linalg
>>> A = np.random.randn(3, 3)
>>> E = np.random.randn(3, 3)
>>> expm_A, expm_frechet_AE = scipy.linalg.expm_frechet(A, E)
>>> expm_A.shape, expm_frechet_AE.shape
((3, 3), (3, 3))

>>> import scipy.linalg
>>> A = np.random.randn(3, 3)
>>> E = np.random.randn(3, 3)
>>> expm_A, expm_frechet_AE = scipy.linalg.expm_frechet(A, E)
>>> M = np.zeros((6, 6))
>>> M[:3, :3] = A; M[:3, 3:] = E; M[3:, 3:] = A
>>> expm_M = scipy.linalg.expm(M)
>>> np.allclose(expm_A, expm_M[:3, :3])
True
>>> np.allclose(expm_frechet_AE, expm_M[:3, 3:])
True


n = A.shape[<NUM_LIT:0>]<EOL>M = np.vstack([<EOL>np.hstack([A, E]),<EOL>np.hstack([np.zeros_like(A), A])])<EOL>expm_M = scipy.linalg.expm(M)<EOL>return expm_M[:n, :n], expm_M[:n, n:]<EOL>

This is a helper function, mostly for testing and profiling.
Return expm(A), frechet(A, E)


return M.T.ravel()<EOL>

Stack columns of M to construct a single vector.

This is somewhat standard notation in linear algebra.

Parameters
----------
M : 2d array-like
    Input matrix

Returns
-------
v : 1d ndarray
    Output vector


def expm_frechet_kronform(A, method=None, check_finite=True):

if check_finite:<EOL><INDENT>A = np.asarray_chkfinite(A)<EOL><DEDENT>else:<EOL><INDENT>A = np.asarray(A)<EOL><DEDENT>if len(A.shape) != <NUM_LIT:2> or A.shape[<NUM_LIT:0>] != A.shape[<NUM_LIT:1>]:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>n = A.shape[<NUM_LIT:0>]<EOL>ident = np.identity(n)<EOL>cols = []<EOL>for i in range(n):<EOL><INDENT>for j in range(n):<EOL><INDENT>E = np.outer(ident[i], ident[j])<EOL>F = expm_frechet(A, E,<EOL>method=method, compute_expm=False, check_finite=False)<EOL>cols.append(vec(F))<EOL><DEDENT><DEDENT>return np.vstack(cols).T<EOL>

Construct the Kronecker form of the Frechet derivative of expm.

Parameters
----------
A : array-like with shape (N, N)
    Matrix to be expm'd.
method : str, optional
    Extra keyword to be passed to expm_frechet.
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
-------
K : 2d ndarray with shape (N*N, N*N)
    Kronecker form of the Frechet derivative of the matrix exponential.

Notes
-----
This function is used to help compute the condition number
of the matrix exponential.

See also
--------
expm : Compute a matrix exponential.
expm_frechet : Compute the Frechet derivative of the matrix exponential.
expm_cond : Compute the relative condition number of the matrix exponential
            in the Frobenius norm.


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

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

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

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

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

.. versionadded:: 0.14.0

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


return _id.id_srand(n)<EOL>

Generate standard uniform pseudorandom numbers via a very efficient lagged
Fibonacci method.

:param n:
    Number of pseudorandom numbers to generate.
:type n: int

:return:
    Pseudorandom numbers.
:rtype: :class:`numpy.ndarray`


t = np.asfortranarray(t)<EOL>_id.id_srandi(t)<EOL>

Initialize seed values for :func:`id_srand` (any appropriately random
numbers will do).

:param t:
    Array of 55 seed values.
:type t: :class:`numpy.ndarray`


Reset seed values to their original values.


return _id.idd_frm(n, w, x)<EOL>

Transform real vector via a composition of Rokhlin's random transform,
random subselection, and an FFT.

In contrast to :func:`idd_sfrm`, this routine works best when the length of
the transformed vector is the power-of-two integer output by
:func:`idd_frmi`, or when the length is not specified but instead
determined a posteriori from the output. The returned transformed vector is
randomly permuted.

:param n:
    Greatest power-of-two integer satisfying `n <= x.size` as obtained from
    :func:`idd_frmi`; `n` is also the length of the output vector.
:type n: int
:param w:
    Initialization array constructed by :func:`idd_frmi`.
:type w: :class:`numpy.ndarray`
:param x:
    Vector to be transformed.
:type x: :class:`numpy.ndarray`

:return:
    Transformed vector.
:rtype: :class:`numpy.ndarray`


return _id.idd_sfrm(l, n, w, x)<EOL>

Transform real vector via a composition of Rokhlin's random transform,
random subselection, and an FFT.

In contrast to :func:`idd_frm`, this routine works best when the length of
the transformed vector is known a priori.

:param l:
    Length of transformed vector, satisfying `l <= n`.
:type l: int
:param n:
    Greatest power-of-two integer satisfying `n <= x.size` as obtained from
    :func:`idd_sfrmi`.
:type n: int
:param w:
    Initialization array constructed by :func:`idd_sfrmi`.
:type w: :class:`numpy.ndarray`
:param x:
    Vector to be transformed.
:type x: :class:`numpy.ndarray`

:return:
    Transformed vector.
:rtype: :class:`numpy.ndarray`


return _id.idd_frmi(m)<EOL>

Initialize data for :func:`idd_frm`.

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

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


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

Initialize data for :func:`idd_sfrm`.

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

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


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

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

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

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


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

Compute ID of a real matrix to a specified rank.

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

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


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

Reconstruct matrix from real ID.

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

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


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

Reconstruct interpolation matrix from real ID.

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

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


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

Reconstruct skeleton matrix from real ID.

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

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


B = np.asfortranarray(B)<EOL>U, V, S, ier = _id.idd_id2svd(B, idx, proj)<EOL>if ier:<EOL><INDENT>raise _RETCODE_ERROR<EOL><DEDENT>return U, V, S<EOL>

Convert real ID to SVD.

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

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


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

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

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

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

:return:
    Spectral norm estimate.
:rtype: float


def idd_diffsnorm(m, n, matvect, matvect2, matvec, matvec2, its=<NUM_LIT:20>):

return _id.idd_diffsnorm(m, n, matvect, matvect2, matvec, matvec2, its)<EOL>

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

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

:return:
    Spectral norm estimate of matrix difference.
:rtype: float


A = np.asfortranarray(A)<EOL>U, V, S, ier = _id.iddr_svd(A, k)<EOL>if ier:<EOL><INDENT>raise _RETCODE_ERROR<EOL><DEDENT>return U, V, S<EOL>

Compute SVD of a real matrix to a specified rank.

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

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


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

Compute SVD of a real matrix to a specified relative precision.

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

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


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

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

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

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


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

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

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

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

:return:
    Rank estimate.
:rtype: int


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

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

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

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


proj = np.empty(m + <NUM_LIT:1> + <NUM_LIT:2>*n*(min(m, n) + <NUM_LIT:1>), order='<STR_LIT:F>')<EOL>k, idx, proj, ier = _id.iddp_rid(eps, m, n, matvect, proj)<EOL>if ier != <NUM_LIT:0>:<EOL><INDENT>raise _RETCODE_ERROR<EOL><DEDENT>proj = proj[:k*(n-k)].reshape((k, n-k), order='<STR_LIT:F>')<EOL>return k, idx, proj<EOL>

Compute ID of a real matrix to a specified relative precision using random
matrix-vector multiplication.

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

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


k, ra, ier = _id.idd_findrank(eps, m, n, matvect)<EOL>if ier:<EOL><INDENT>raise _RETCODE_ERROR<EOL><DEDENT>return k<EOL>

Estimate rank of a real matrix to a specified relative precision using
random matrix-vector multiplication.

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

:return:
    Rank estimate.
:rtype: int


def iddp_rsvd(eps, m, n, matvect, matvec):

k, iU, iV, iS, w, ier = _id.iddp_rsvd(eps, m, n, matvect, matvec)<EOL>if ier:<EOL><INDENT>raise _RETCODE_ERROR<EOL><DEDENT>U = w[iU-<NUM_LIT:1>:iU+m*k-<NUM_LIT:1>].reshape((m, k), order='<STR_LIT:F>')<EOL>V = w[iV-<NUM_LIT:1>:iV+n*k-<NUM_LIT:1>].reshape((n, k), order='<STR_LIT:F>')<EOL>S = w[iS-<NUM_LIT:1>:iS+k-<NUM_LIT:1>]<EOL>return U, V, S<EOL>

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

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

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


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

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

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

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


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

Initialize array for :func:`iddr_aid`.

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

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


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

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

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

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


idx, proj = _id.iddr_rid(m, n, matvect, k)<EOL>proj = proj[:k*(n-k)].reshape((k, n-k), order='<STR_LIT:F>')<EOL>return idx, proj<EOL>

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

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

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


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

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

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

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

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


return _id.idz_frm(n, w, x)<EOL>

Transform complex vector via a composition of Rokhlin's random transform,
random subselection, and an FFT.

In contrast to :func:`idz_sfrm`, this routine works best when the length of
the transformed vector is the power-of-two integer output by
:func:`idz_frmi`, or when the length is not specified but instead
determined a posteriori from the output. The returned transformed vector is
randomly permuted.

:param n:
    Greatest power-of-two integer satisfying `n <= x.size` as obtained from
    :func:`idz_frmi`; `n` is also the length of the output vector.
:type n: int
:param w:
    Initialization array constructed by :func:`idz_frmi`.
:type w: :class:`numpy.ndarray`
:param x:
    Vector to be transformed.
:type x: :class:`numpy.ndarray`

:return:
    Transformed vector.
:rtype: :class:`numpy.ndarray`


return _id.idz_sfrm(l, n, w, x)<EOL>

Transform complex vector via a composition of Rokhlin's random transform,
random subselection, and an FFT.

In contrast to :func:`idz_frm`, this routine works best when the length of
the transformed vector is known a priori.

:param l:
    Length of transformed vector, satisfying `l <= n`.
:type l: int
:param n:
    Greatest power-of-two integer satisfying `n <= x.size` as obtained from
    :func:`idz_sfrmi`.
:type n: int
:param w:
    Initialization array constructed by :func:`idd_sfrmi`.
:type w: :class:`numpy.ndarray`
:param x:
    Vector to be transformed.
:type x: :class:`numpy.ndarray`

:return:
    Transformed vector.
:rtype: :class:`numpy.ndarray`


return _id.idz_frmi(m)<EOL>

Initialize data for :func:`idz_frm`.

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

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


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

Initialize data for :func:`idz_sfrm`.

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

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


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

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

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

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


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

Compute ID of a complex matrix to a specified rank.

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

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


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

Reconstruct matrix from complex ID.

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

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


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

Reconstruct interpolation matrix from complex ID.

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

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


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

Reconstruct skeleton matrix from complex ID.

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

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


B = np.asfortranarray(B)<EOL>U, V, S, ier = _id.idz_id2svd(B, idx, proj)<EOL>if ier:<EOL><INDENT>raise _RETCODE_ERROR<EOL><DEDENT>return U, V, S<EOL>

Convert complex ID to SVD.

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

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


def idz_snorm(m, n, matveca, matvec, its=<NUM_LIT:20>):

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

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

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

:return:
    Spectral norm estimate.
:rtype: float


def idz_diffsnorm(m, n, matveca, matveca2, matvec, matvec2, its=<NUM_LIT:20>):

return _id.idz_diffsnorm(m, n, matveca, matveca2, matvec, matvec2, its)<EOL>

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

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

:return:
    Spectral norm estimate of matrix difference.
:rtype: float


A = np.asfortranarray(A)<EOL>U, V, S, ier = _id.idzr_svd(A, k)<EOL>if ier:<EOL><INDENT>raise _RETCODE_ERROR<EOL><DEDENT>return U, V, S<EOL>

Compute SVD of a complex matrix to a specified rank.

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

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


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

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

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

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


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

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

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

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


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

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

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

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

:return:
    Rank estimate.
:rtype: int


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

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

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

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


proj = np.empty(<EOL>m + <NUM_LIT:1> + <NUM_LIT:2>*n*(min(m, n) + <NUM_LIT:1>),<EOL>dtype=np.complex128, order='<STR_LIT:F>')<EOL>k, idx, proj, ier = _id.idzp_rid(eps, m, n, matveca, proj)<EOL>if ier:<EOL><INDENT>raise _RETCODE_ERROR<EOL><DEDENT>proj = proj[:k*(n-k)].reshape((k, n-k), order='<STR_LIT:F>')<EOL>return k, idx, proj<EOL>

Compute ID of a complex matrix to a specified relative precision using
random matrix-vector multiplication.

:param eps:
    Relative precision.
:type eps: float
:param m:
    Matrix row dimension.
:type m: int
:param n:
    Matrix column dimension.
:type n: int
:param matveca:
    Function to apply the matrix adjoint to a vector, with call signature
    `y = matveca(x)`, where `x` and `y` are the input and output vectors,
    respectively.
:type matveca: function

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


k, ra, ier = _id.idz_findrank(eps, m, n, matveca)<EOL>if ier:<EOL><INDENT>raise _RETCODE_ERROR<EOL><DEDENT>return k<EOL>

Estimate rank of a complex matrix to a specified relative precision using
random matrix-vector multiplication.

:param eps:
    Relative precision.
:type eps: float
:param m:
    Matrix row dimension.
:type m: int
:param n:
    Matrix column dimension.
:type n: int
:param matveca:
    Function to apply the matrix adjoint to a vector, with call signature
    `y = matveca(x)`, where `x` and `y` are the input and output vectors,
    respectively.
:type matveca: function

:return:
    Rank estimate.
:rtype: int


def idzp_rsvd(eps, m, n, matveca, matvec):

k, iU, iV, iS, w, ier = _id.idzp_rsvd(eps, m, n, matveca, matvec)<EOL>if ier:<EOL><INDENT>raise _RETCODE_ERROR<EOL><DEDENT>U = w[iU-<NUM_LIT:1>:iU+m*k-<NUM_LIT:1>].reshape((m, k), order='<STR_LIT:F>')<EOL>V = w[iV-<NUM_LIT:1>:iV+n*k-<NUM_LIT:1>].reshape((n, k), order='<STR_LIT:F>')<EOL>S = w[iS-<NUM_LIT:1>:iS+k-<NUM_LIT:1>]<EOL>return U, V, S<EOL>

Compute SVD of a complex matrix to a specified relative precision using
random matrix-vector multiplication.

:param eps:
    Relative precision.
:type eps: float
:param m:
    Matrix row dimension.
:type m: int
:param n:
    Matrix column dimension.
:type n: int
:param matveca:
    Function to apply the matrix adjoint to a vector, with call signature
    `y = matveca(x)`, where `x` and `y` are the input and output vectors,
    respectively.
:type matveca: function
:param matvec:
    Function to apply the matrix to a vector, with call signature
    `y = matvec(x)`, where `x` and `y` are the input and output vectors,
    respectively.
:type matvec: function

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


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

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

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

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


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

Initialize array for :func:`idzr_aid`.

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

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


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

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

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

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


idx, proj = _id.idzr_rid(m, n, matveca, k)<EOL>proj = proj[:k*(n-k)].reshape((k, n-k), order='<STR_LIT:F>')<EOL>return idx, proj<EOL>

Compute ID of a complex matrix to a specified rank using random
matrix-vector multiplication.

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

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


def idzr_rsvd(m, n, matveca, matvec, k):

U, V, S, ier = _id.idzr_rsvd(m, n, matveca, matvec, k)<EOL>if ier:<EOL><INDENT>raise _RETCODE_ERROR<EOL><DEDENT>return U, V, S<EOL>

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

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

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


lwork = kwargs.pop("<STR_LIT>", None)<EOL>if lwork is None:<EOL><INDENT>kwargs['<STR_LIT>'] = -<NUM_LIT:1><EOL>ret = f(*args, **kwargs)<EOL>kwargs['<STR_LIT>'] = ret[-<NUM_LIT:2>][<NUM_LIT:0>].real.astype(numpy.int)<EOL><DEDENT>ret = f(*args, **kwargs)<EOL>if ret[-<NUM_LIT:1>] < <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>% (-ret[-<NUM_LIT:1>], name))<EOL><DEDENT>return ret[:-<NUM_LIT:2>]<EOL>

Call a LAPACK routine, determining lwork automatically and handling
    error return values


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

<EOL>if mode not in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT:r>', '<STR_LIT>', '<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>if pivoting:<EOL><INDENT>geqp3, = get_lapack_funcs(('<STR_LIT>',), (a1,))<EOL>qr, jpvt, tau = safecall(geqp3, "<STR_LIT>", a1, overwrite_a=overwrite_a)<EOL>jpvt -= <NUM_LIT:1>  <EOL><DEDENT>else:<EOL><INDENT>geqrf, = get_lapack_funcs(('<STR_LIT>',), (a1,))<EOL>qr, tau = safecall(geqrf, "<STR_LIT>", a1, lwork=lwork,<EOL>overwrite_a=overwrite_a)<EOL><DEDENT>if mode not in ['<STR_LIT>', '<STR_LIT>'] or M < N:<EOL><INDENT>R = numpy.triu(qr)<EOL><DEDENT>else:<EOL><INDENT>R = numpy.triu(qr[:N, :])<EOL><DEDENT>if pivoting:<EOL><INDENT>Rj = R, jpvt<EOL><DEDENT>else:<EOL><INDENT>Rj = R,<EOL><DEDENT>if mode == '<STR_LIT:r>':<EOL><INDENT>return Rj<EOL><DEDENT>elif mode == '<STR_LIT>':<EOL><INDENT>return ((qr, tau),) + Rj<EOL><DEDENT>gor_un_gqr, = get_lapack_funcs(('<STR_LIT>',), (qr,))<EOL>if M < N:<EOL><INDENT>Q, = safecall(gor_un_gqr, "<STR_LIT>", qr[:, :M], tau,<EOL>lwork=lwork, overwrite_a=<NUM_LIT:1>)<EOL><DEDENT>elif mode == '<STR_LIT>':<EOL><INDENT>Q, = safecall(gor_un_gqr, "<STR_LIT>", qr, tau, lwork=lwork,<EOL>overwrite_a=<NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>t = qr.dtype.char<EOL>qqr = numpy.empty((M, M), dtype=t)<EOL>qqr[:, :N] = qr<EOL>Q, = safecall(gor_un_gqr, "<STR_LIT>", qqr, tau, lwork=lwork,<EOL>overwrite_a=<NUM_LIT:1>)<EOL><DEDENT>return (Q,) + Rj<EOL>

Compute QR decomposition of a matrix.

Calculate the decomposition ``A = Q R`` 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', 'raw'}, 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). The final option 'raw'
    (added in Scipy 0.11) makes the function return two matrices
    (Q, TAU) in the internal format used by LAPACK.
pivoting : bool, optional
    Whether or not factorization should include pivoting for rank-revealing
    qr decomposition. If pivoting, compute the decomposition
    ``A P = Q R`` as above, but where P is chosen such that the diagonal
    of R is non-increasing.
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
-------
Q : float or complex ndarray
    Of shape (M, M), or (M, K) for ``mode='economic'``.  Not returned
    if ``mode='r'``.
R : float or complex ndarray
    Of shape (M, N), or (K, N) for ``mode='economic'``.  ``K = min(M, N)``.
P : int ndarray
    Of shape (N,) for ``pivoting=True``. Not returned if
    ``pivoting=False``.

Raises
------
LinAlgError
    Raised if decomposition fails

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

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

Examples
--------
>>> from scipy import random, linalg, dot, diag, all, allclose
>>> a = random.randn(9, 6)

>>> q, r = linalg.qr(a)
>>> allclose(a, np.dot(q, r))
True
>>> q.shape, r.shape
((9, 9), (9, 6))

>>> r2 = linalg.qr(a, mode='r')
>>> allclose(r, r2)
True

>>> q3, r3 = linalg.qr(a, mode='economic')
>>> q3.shape, r3.shape
((9, 6), (6, 6))

>>> q4, r4, p4 = linalg.qr(a, pivoting=True)
>>> d = abs(diag(r4))
>>> all(d[1:] <= d[:-1])
True
>>> allclose(a[:, p4], dot(q4, r4))
True
>>> q4.shape, r4.shape, p4.shape
((9, 9), (9, 6), (6,))

>>> q5, r5, p5 = linalg.qr(a, mode='economic', pivoting=True)
>>> q5.shape, r5.shape, p5.shape
((9, 6), (6, 6), (6,))


def qr_multiply(a, c, mode='<STR_LIT:right>', pivoting=False, conjugate=False,<EOL>overwrite_a=False, overwrite_c=False):

if mode not in ['<STR_LIT:left>', '<STR_LIT:right>']:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>c = numpy.asarray_chkfinite(c)<EOL>onedim = c.ndim == <NUM_LIT:1><EOL>if onedim:<EOL><INDENT>c = c.reshape(<NUM_LIT:1>, len(c))<EOL>if mode == "<STR_LIT:left>":<EOL><INDENT>c = c.T<EOL><DEDENT><DEDENT>a = numpy.asarray(a)  <EOL>M, N = a.shape<EOL>if not (mode == "<STR_LIT:left>" and<EOL>(not overwrite_c and min(M, N) == c.shape[<NUM_LIT:0>] or<EOL>overwrite_c and M == c.shape[<NUM_LIT:0>]) or<EOL>mode == "<STR_LIT:right>" and M == c.shape[<NUM_LIT:1>]):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>raw = qr(a, overwrite_a, None, "<STR_LIT>", pivoting)<EOL>Q, tau = raw[<NUM_LIT:0>]<EOL>gor_un_mqr, = get_lapack_funcs(('<STR_LIT>',), (Q,))<EOL>if gor_un_mqr.typecode in ('<STR_LIT:s>', '<STR_LIT:d>'):<EOL><INDENT>trans = "<STR_LIT:T>"<EOL><DEDENT>else:<EOL><INDENT>trans = "<STR_LIT:C>"<EOL><DEDENT>Q = Q[:, :min(M, N)]<EOL>if M > N and mode == "<STR_LIT:left>" and not overwrite_c:<EOL><INDENT>if conjugate:<EOL><INDENT>cc = numpy.zeros((c.shape[<NUM_LIT:1>], M), dtype=c.dtype, order="<STR_LIT:F>")<EOL>cc[:, :N] = c.T<EOL><DEDENT>else:<EOL><INDENT>cc = numpy.zeros((M, c.shape[<NUM_LIT:1>]), dtype=c.dtype, order="<STR_LIT:F>")<EOL>cc[:N, :] = c<EOL>trans = "<STR_LIT:N>"<EOL><DEDENT>if conjugate:<EOL><INDENT>lr = "<STR_LIT:R>"<EOL><DEDENT>else:<EOL><INDENT>lr = "<STR_LIT:L>"<EOL><DEDENT>overwrite_c = True<EOL><DEDENT>elif c.flags["<STR_LIT>"] and trans == "<STR_LIT:T>" or conjugate:<EOL><INDENT>cc = c.T<EOL>if mode == "<STR_LIT:left>":<EOL><INDENT>lr = "<STR_LIT:R>"<EOL><DEDENT>else:<EOL><INDENT>lr = "<STR_LIT:L>"<EOL><DEDENT><DEDENT>else:<EOL><INDENT>trans = "<STR_LIT:N>"<EOL>cc = c<EOL>if mode == "<STR_LIT:left>":<EOL><INDENT>lr = "<STR_LIT:L>"<EOL><DEDENT>else:<EOL><INDENT>lr = "<STR_LIT:R>"<EOL><DEDENT><DEDENT>cQ, = safecall(gor_un_mqr, "<STR_LIT>", lr, trans, Q, tau, cc,<EOL>overwrite_c=overwrite_c)<EOL>if trans != "<STR_LIT:N>":<EOL><INDENT>cQ = cQ.T<EOL><DEDENT>if mode == "<STR_LIT:right>":<EOL><INDENT>cQ = cQ[:, :min(M, N)]<EOL><DEDENT>if onedim:<EOL><INDENT>cQ = cQ.ravel()<EOL><DEDENT>return (cQ,) + raw[<NUM_LIT:1>:]<EOL>

Calculate the QR decomposition and multiply Q with a matrix.

Calculate the decomposition ``A = Q R`` where Q is unitary/orthogonal
and R upper triangular. Multiply Q with a vector or a matrix c.

Parameters
----------
a : ndarray, shape (M, N)
    Matrix to be decomposed
c : ndarray, one- or two-dimensional
    calculate the product of c and q, depending on the mode:
mode : {'left', 'right'}, optional
    ``dot(Q, c)`` is returned if mode is 'left',
    ``dot(c, Q)`` is returned if mode is 'right'.
    The shape of c must be appropriate for the matrix multiplications,
    if mode is 'left', ``min(a.shape) == c.shape[0]``,
    if mode is 'right', ``a.shape[0] == c.shape[1]``.
pivoting : bool, optional
    Whether or not factorization should include pivoting for rank-revealing
    qr decomposition, see the documentation of qr.
conjugate : bool, optional
    Whether Q should be complex-conjugated. This might be faster
    than explicit conjugation.
overwrite_a : bool, optional
    Whether data in a is overwritten (may improve performance)
overwrite_c : bool, optional
    Whether data in c is overwritten (may improve performance).
    If this is used, c must be big enough to keep the result,
    i.e. c.shape[0] = a.shape[0] if mode is 'left'.

Returns
-------
CQ : float or complex ndarray
    the product of Q and c, as defined in mode
R : float or complex ndarray
    Of shape (K, N), ``K = min(M, N)``.
P : ndarray of ints
    Of shape (N,) for ``pivoting=True``.
    Not returned if ``pivoting=False``.

Raises
------
LinAlgError
    Raised if decomposition fails

Notes
-----
This is an interface to the LAPACK routines dgeqrf, zgeqrf,
dormqr, zunmqr, dgeqp3, and zgeqp3.

.. versionadded:: 0.11.0