Exemplo n.º 1
0
def inv(A):
    """
    Compute the inverse of a sparse matrix

    .. versionadded:: 0.12.0

    Parameters
    ----------
    A : (M,M) ndarray or sparse matrix
        square matrix to be inverted

    Returns
    -------
    Ainv : (M,M) ndarray or sparse matrix
        inverse of `A`

    Notes
    -----
    This computes the sparse inverse of `A`.  If the inverse of `A` is expected
    to be non-sparse, it will likely be faster to convert `A` to dense and use
    scipy.linalg.inv.

    """
    I = speye(A.shape[0], A.shape[1], dtype=A.dtype, format=A.format)
    Ainv = spsolve(A, I)
    return Ainv
Exemplo n.º 2
0
def inv(A):
    """
    Compute the inverse of a sparse matrix

    Parameters
    ----------
    A : (M,M) ndarray or sparse matrix
        square matrix to be inverted

    Returns
    -------
    Ainv : (M,M) ndarray or sparse matrix
        inverse of `A`

    Notes
    -----
    This computes the sparse inverse of `A`.  If the inverse of `A` is expected
    to be non-sparse, it will likely be faster to convert `A` to dense and use
    scipy.linalg.inv.

    .. versionadded:: 0.12.0

    """
    I = speye(A.shape[0], A.shape[1], dtype=A.dtype, format=A.format)
    Ainv = spsolve(A, I)
    return Ainv
Exemplo n.º 3
0
 def test_padecases_dtype_sparse_complex(self):
     # float32 and complex64 lead to errors in spsolve/UMFpack
     dtype = np.complex128
     for scale in [1e-2, 1e-1, 5e-1, 1, 10]:
         a = scale * speye(3, 3, dtype=dtype, format='csc')
         e = exp(scale) * eye(3, dtype=dtype)
         assert_array_almost_equal_nulp(expm(a).toarray(), e, nulp=100)
Exemplo n.º 4
0
 def test_padecases_dtype_sparse_complex(self):
     # float32 and complex64 lead to errors in spsolve/UMFpack
     dtype = np.complex128
     for scale in [1e-2, 1e-1, 5e-1, 1, 10]:
         a = scale * speye(3, 3, dtype=dtype, format='csc')
         e = exp(scale) * eye(3, dtype=dtype)
         assert_array_almost_equal_nulp(expm(a).toarray(), e, nulp=100)
Exemplo n.º 5
0
 def test_padecases_dtype_sparse(self):
     # float32 and complex64 lead to errors in spsolve/UMFpack
     for dtype in [np.float64, np.complex128]:
         # test double-precision cases
         for scale in [1e-2, 1e-1, 5e-1, 1, 10]:
             a = scale * speye(3, 3, dtype=dtype, format='csc')
             e = exp(scale) * identity(3, dtype=dtype)
             assert_array_almost_equal_nulp(expm(a).toarray(), e, nulp=100)
Exemplo n.º 6
0
 def test_padecases_dtype_sparse(self):
     # float32 and complex64 lead to errors in spsolve/UMFpack
     for dtype in [np.float64, np.complex128]:
         # test double-precision cases
         for scale in [1e-2, 1e-1, 5e-1, 1, 10]:
             a = scale * speye(3, 3, dtype=dtype, format='csc')
             e = exp(scale) * identity(3, dtype=dtype)
             assert_array_almost_equal_nulp(expm(a).toarray(), e, nulp=100)
Exemplo n.º 7
0
 def test_padecases_dtype_sparse_complex(self):
     # float32 and complex64 lead to errors in spsolve/UMFpack
     dtype = np.complex128
     with warnings.catch_warnings():
         warnings.simplefilter("ignore", category=SparseEfficiencyWarning)
         for scale in [1e-2, 1e-1, 5e-1, 1, 10]:
             a = scale * speye(3, 3, dtype=dtype, format='csc')
             e = exp(scale) * eye(3, dtype=dtype)
             assert_array_almost_equal_nulp(expm(a).toarray(), e, nulp=100)
Exemplo n.º 8
0
 def test_padecases_dtype_sparse_complex(self):
     # float32 and complex64 lead to errors in spsolve/UMFpack
     dtype = np.complex128
     with warnings.catch_warnings():
         warnings.simplefilter("ignore", category=SparseEfficiencyWarning)
         for scale in [1e-2, 1e-1, 5e-1, 1, 10]:
             a = scale * speye(3, 3, dtype=dtype, format='csc')
             e = exp(scale) * eye(3, dtype=dtype)
             assert_array_almost_equal_nulp(expm(a).toarray(), e, nulp=100)
Exemplo n.º 9
0
 def test_padecases_dtype_sparse_complex(self):
     # float32 and complex64 lead to errors in spsolve/UMFpack
     dtype = np.complex128
     for scale in [1e-2, 1e-1, 5e-1, 1, 10]:
         a = scale * speye(3, 3, dtype=dtype, format='csc')
         e = exp(scale) * eye(3, dtype=dtype)
         with suppress_warnings() as sup:
             sup.filter(SparseEfficiencyWarning,
                        "Changing the sparsity structure of a csc_matrix is expensive.")
             assert_array_almost_equal_nulp(expm(a).toarray(), e, nulp=100)
Exemplo n.º 10
0
 def test_padecases_dtype_sparse_complex(self):
     # float32 and complex64 lead to errors in spsolve/UMFpack
     dtype = np.complex128
     for scale in [1e-2, 1e-1, 5e-1, 1, 10]:
         a = scale * speye(3, 3, dtype=dtype, format='csc')
         e = exp(scale) * eye(3, dtype=dtype)
         with suppress_warnings() as sup:
             sup.filter(SparseEfficiencyWarning,
                        "Changing the sparsity structure of a csc_matrix is expensive.")
             assert_array_almost_equal_nulp(expm(a).toarray(), e, nulp=100)
Exemplo n.º 11
0
def inv(A):
    """
    Compute the inverse of a sparse matrix

    Parameters
    ----------
    A : (M,M) ndarray or sparse matrix
        square matrix to be inverted

    Returns
    -------
    Ainv : (M,M) ndarray or sparse matrix
        inverse of `A`

    Notes
    -----
    This computes the sparse inverse of `A`.  If the inverse of `A` is expected
    to be non-sparse, it will likely be faster to convert `A` to dense and use
    scipy.linalg.inv.

    Examples
    --------
    >>> from scipy.sparse import csc_matrix
    >>> from scipy.sparse.linalg import inv
    >>> A = csc_matrix([[1., 0.], [1., 2.]])
    >>> Ainv = inv(A)
    >>> Ainv
    <2x2 sparse matrix of type '<class 'numpy.float64'>'
        with 3 stored elements in Compressed Sparse Column format>
    >>> A.dot(Ainv)
    <2x2 sparse matrix of type '<class 'numpy.float64'>'
        with 2 stored elements in Compressed Sparse Column format>
    >>> A.dot(Ainv).todense()
    matrix([[ 1.,  0.],
            [ 0.,  1.]])

    .. versionadded:: 0.12.0

    """
    #check input
    if not scipy.sparse.isspmatrix(A):
        raise TypeError('Input must be a sparse matrix')

    I = speye(A.shape[0], A.shape[1], dtype=A.dtype, format=A.format)
    Ainv = spsolve(A, I)
    return Ainv
Exemplo n.º 12
0
def inv(A):
    """
    Compute the inverse of a sparse matrix

    Parameters
    ----------
    A : (M,M) ndarray or sparse matrix
        square matrix to be inverted

    Returns
    -------
    Ainv : (M,M) ndarray or sparse matrix
        inverse of `A`

    Notes
    -----
    This computes the sparse inverse of `A`.  If the inverse of `A` is expected
    to be non-sparse, it will likely be faster to convert `A` to dense and use
    scipy.linalg.inv.

    Examples
    --------
    >>> from scipy.sparse import csc_matrix
    >>> from scipy.sparse.linalg import inv
    >>> A = csc_matrix([[1., 0.], [1., 2.]])
    >>> Ainv = inv(A)
    >>> Ainv
    <2x2 sparse matrix of type '<class 'numpy.float64'>'
        with 3 stored elements in Compressed Sparse Column format>
    >>> A.dot(Ainv)
    <2x2 sparse matrix of type '<class 'numpy.float64'>'
        with 2 stored elements in Compressed Sparse Column format>
    >>> A.dot(Ainv).todense()
    matrix([[ 1.,  0.],
            [ 0.,  1.]])

    .. versionadded:: 0.12.0

    """
    #check input
    if not scipy.sparse.isspmatrix(A):
        raise TypeError('Input must be a sparse matrix')

    I = speye(A.shape[0], A.shape[1], dtype=A.dtype, format=A.format)
    Ainv = spsolve(A, I)
    return Ainv
Exemplo n.º 13
0
Arquivo: matfuncs.py Projeto: 87/scipy
def inv(A):
    """Compute the inverse of a sparse matrix

    Parameters
    ----------
    A : ndarray or sparse matrix
        square matrix to be inverted
    
    Returns
    -------
    Ainv : inverse of A

    Notes
    -----
    This computes the sparse inverse of A.  If the inverse of A is expected
    to be non-sparse, it will likely be faster to convert A to dense and use
    scipy.linalg.inv.
    """
    I = speye(A.shape[0], A.shape[1], dtype=A.dtype, format=A.format)
    Ainv = spsolve(A, I)
    return Ainv
Exemplo n.º 14
0
def inv(A):
    """Compute the inverse of a sparse matrix

    Parameters
    ----------
    A : ndarray or sparse matrix
        square matrix to be inverted
    
    Returns
    -------
    Ainv : inverse of A

    Notes
    -----
    This computes the sparse inverse of A.  If the inverse of A is expected
    to be non-sparse, it will likely be faster to convert A to dense and use
    scipy.linalg.inv.
    """
    I = speye(A.shape[0], A.shape[1], dtype=A.dtype, format=A.format)
    Ainv = spsolve(A, I)
    return Ainv
Exemplo n.º 15
0
def expm(A):
    """
    Compute the matrix exponential using Pade approximation.

    .. versionadded:: 0.12.0

    Parameters
    ----------
    A : (M,M) array or sparse matrix
        2D Array or Matrix (sparse or dense) to be exponentiated

    Returns
    -------
    expA : (M,M) ndarray
        Matrix exponential of `A`

    References
    ----------
    N. J. Higham,
    "The Scaling and Squaring Method for the Matrix Exponential Revisited",
    SIAM. J. Matrix Anal. & Appl. 26, 1179 (2005).

    """
    n_squarings = 0
    Aissparse = isspmatrix(A)

    if Aissparse:
        A_L1 = max(abs(A).sum(axis=0).flat)
        ident = speye(A.shape[0], A.shape[1], dtype=A.dtype, format=A.format)
    else:
        A = asarray(A)
        A_L1 = norm(A, 1)
        ident = eye(A.shape[0], A.shape[1], dtype=A.dtype)

    if A.dtype == 'float64' or A.dtype == 'complex128':
        if A_L1 < 1.495585217958292e-002:
            U, V = _pade3(A, ident)
        elif A_L1 < 2.539398330063230e-001:
            U, V = _pade5(A, ident)
        elif A_L1 < 9.504178996162932e-001:
            U, V = _pade7(A, ident)
        elif A_L1 < 2.097847961257068e+000:
            U, V = _pade9(A, ident)
        else:
            maxnorm = 5.371920351148152
            n_squarings = max(0, int(ceil(log2(A_L1 / maxnorm))))
            A = A / 2**n_squarings
            U, V = _pade13(A, ident)
    elif A.dtype == 'float32' or A.dtype == 'complex64':
        if A_L1 < 4.258730016922831e-001:
            U, V = _pade3(A, ident)
        elif A_L1 < 1.880152677804762e+000:
            U, V = _pade5(A, ident)
        else:
            maxnorm = 3.925724783138660
            n_squarings = max(0, int(ceil(log2(A_L1 / maxnorm))))
            A = A / 2**n_squarings
            U, V = _pade7(A, ident)
    else:
        raise ValueError("invalid type: " + str(A.dtype))

    P = U + V  # p_m(A) : numerator
    Q = -U + V  # q_m(A) : denominator

    if Aissparse:
        from scipy.sparse.linalg import spsolve
        R = spsolve(Q, P)
    else:
        R = solve(Q, P)

    # squaring step to undo scaling
    for i in range(n_squarings):
        R = R.dot(R)

    return R
Exemplo n.º 16
0
def expm(A):
    """Compute the matrix exponential using Pade approximation.

    .. versionadded:: 0.12.0

    Parameters
    ----------
    A : array or sparse matrix, shape(M,M)
        2D Array or Matrix (sparse or dense) to be exponentiated

    Returns
    -------
    expA : array, shape(M,M)
        Matrix exponential of A

    References
    ----------
    N. J. Higham,
    "The Scaling and Squaring Method for the Matrix Exponential Revisited",
    SIAM. J. Matrix Anal. & Appl. 26, 1179 (2005).

    """
    n_squarings = 0
    Aissparse = isspmatrix(A)

    if Aissparse:
        A_L1 = max(abs(A).sum(axis=0).flat)
        ident = speye(A.shape[0], A.shape[1], dtype=A.dtype, format=A.format)
    else:
        A = asarray(A)
        A_L1 = norm(A,1)
        ident = eye(A.shape[0], A.shape[1], dtype=A.dtype)

    if A.dtype == 'float64' or A.dtype == 'complex128':
        if A_L1 < 1.495585217958292e-002:
            U,V = _pade3(A, ident)
        elif A_L1 < 2.539398330063230e-001:
            U,V = _pade5(A, ident)
        elif A_L1 < 9.504178996162932e-001:
            U,V = _pade7(A, ident)
        elif A_L1 < 2.097847961257068e+000:
            U,V = _pade9(A, ident)
        else:
            maxnorm = 5.371920351148152
            n_squarings = max(0, int(ceil(log2(A_L1 / maxnorm))))
            A = A / 2**n_squarings
            U,V = _pade13(A, ident)
    elif A.dtype == 'float32' or A.dtype == 'complex64':
        if A_L1 < 4.258730016922831e-001:
            U,V = _pade3(A, ident)
        elif A_L1 < 1.880152677804762e+000:
            U,V = _pade5(A, ident)
        else:
            maxnorm = 3.925724783138660
            n_squarings = max(0, int(ceil(log2(A_L1 / maxnorm))))
            A = A / 2**n_squarings
            U,V = _pade7(A, ident)
    else:
        raise ValueError("invalid type: "+str(A.dtype))

    P = U + V  # p_m(A) : numerator
    Q = -U + V # q_m(A) : denominator

    if Aissparse:
        from scipy.sparse.linalg import spsolve
        R = spsolve(Q, P)
    else:
        R = solve(Q,P)

    # squaring step to undo scaling
    for i in range(n_squarings):
        R = R.dot(R)

    return R