U
    Â»|e‡b  ã                   @   s  d dl mZ d dlZd dlmZ d dlmZmZmZm	Z	m
Z
mZ d dlmZ d dlmZ d dlZddlmZ d	Zzd dlmZ W n ek
r˜   d
ZY nX e ZdddddddgZG dd„ deƒZdd„ Zdd„ Zddd„Zddddeƒ fdd„Zddd„Z dd„ Z!ddd„Z"dS )é    )ÚwarnN)Úasarray)Úisspmatrix_cscÚisspmatrix_csrÚ
isspmatrixÚSparseEfficiencyWarningÚ
csc_matrixÚ
csr_matrix)Úis_pydata_spmatrix)ÚLinAlgErroré   )Ú_superluFTÚ
use_solverÚspsolveÚspluÚspiluÚ
factorizedÚMatrixRankWarningÚspsolve_triangularc                   @   s   e Zd ZdS )r   N)Ú__name__Ú
__module__Ú__qualname__© r   r   úa/var/www/website-v5/atlas_env/lib/python3.8/site-packages/scipy/sparse/linalg/_dsolve/linsolve.pyr      s   c                  K   s6   d| kr| d t ƒ d< tr2d| kr2tj| d d� dS )as	  
    Select default sparse direct solver to be used.

    Parameters
    ----------
    useUmfpack : bool, optional
        Use UMFPACK [1]_, [2]_, [3]_, [4]_. over SuperLU. Has effect only
        if ``scikits.umfpack`` is installed. Default: True
    assumeSortedIndices : bool, optional
        Allow UMFPACK to skip the step of sorting indices for a CSR/CSC matrix.
        Has effect only if useUmfpack is True and ``scikits.umfpack`` is
        installed. Default: False

    Notes
    -----
    The default sparse solver is UMFPACK when available
    (``scikits.umfpack`` is installed). This can be changed by passing
    useUmfpack = False, which then causes the always present SuperLU
    based solver to be used.

    UMFPACK requires a CSR/CSC matrix to have sorted column/row indices. If
    sure that the matrix fulfills this, pass ``assumeSortedIndices=True``
    to gain some speed.

    References
    ----------
    .. [1] T. A. Davis, Algorithm 832:  UMFPACK - an unsymmetric-pattern
           multifrontal method with a column pre-ordering strategy, ACM
           Trans. on Mathematical Software, 30(2), 2004, pp. 196--199.
           https://dl.acm.org/doi/abs/10.1145/992200.992206

    .. [2] T. A. Davis, A column pre-ordering strategy for the
           unsymmetric-pattern multifrontal method, ACM Trans.
           on Mathematical Software, 30(2), 2004, pp. 165--195.
           https://dl.acm.org/doi/abs/10.1145/992200.992205

    .. [3] T. A. Davis and I. S. Duff, A combined unifrontal/multifrontal
           method for unsymmetric sparse matrices, ACM Trans. on
           Mathematical Software, 25(1), 1999, pp. 1--19.
           https://doi.org/10.1145/305658.287640

    .. [4] T. A. Davis and I. S. Duff, An unsymmetric-pattern multifrontal
           method for sparse LU factorization, SIAM J. Matrix Analysis and
           Computations, 18(1), 1997, pp. 140--158.
           https://doi.org/10.1137/S0895479894246905T.

    Examples
    --------
    >>> import numpy as np
    >>> from scipy.sparse.linalg import use_solver, spsolve
    >>> from scipy.sparse import csc_matrix
    >>> R = np.random.randn(5, 5)
    >>> A = csc_matrix(R)
    >>> b = np.random.randn(5)
    >>> use_solver(useUmfpack=False) # enforce superLU over UMFPACK
    >>> x = spsolve(A, b)
    >>> np.allclose(A.dot(x), b)
    True
    >>> use_solver(useUmfpack=True) # reset umfPack usage to default
    Ú
useUmfpackÚassumeSortedIndices)r   N)Úglobalsr   ÚumfpackÚ	configure)Úkwargsr   r   r   r      s    =c              
   C   sæ   t jt jfdt jt jfdt jt jfdt jt jfdi}t j| jj }t j| jjj }z|||f }W n8 t	k
rš } zd||f }t
|ƒ|‚W 5 d}~X Y nX |d d }t | ¡}t j| jd	t jd
�|_t j| jd	t jd
�|_||fS )z8Get umfpack family string given the sparse matrix dtype.ÚdiZziÚdlZzlzmonly float64 or complex128 matrices with int32 or int64 indices are supported! (got: matrix: %s, indices: %s)Nr   ÚlF)ÚcopyÚdtype)ÚnpÚfloat64Úint32Ú
complex128Úint64Ú
sctypeDictr$   ÚnameÚindicesÚKeyErrorÚ
ValueErrorr#   ÚarrayÚindptr)ÚAZ	_familiesZf_typeZi_typeÚfamilyÚeÚmsgZA_newr   r   r   Ú_get_umf_family_   s.    
 
 
 
 üþ
r5   c              
   C   s<  t | ƒr|  ¡  ¡ } t| ƒs6t| ƒs6t| ƒ} tdtƒ t|ƒpDt |ƒ}|sRt	|ƒ}|j
dkpr|j
dkor|jd dk}|  ¡  |  ¡ } t | j|j¡}| j|kr¨|  |¡} |j|kr¼| |¡}| j\}}||kràtd||ff ƒ‚||jd k�rtd| j|jd f ƒ‚|�ot}|�r–|�r–|�r.| ¡ }	n|}	t	|	| jd� ¡ }	t�rRtdƒ‚| jjd	k�rhtd
ƒ‚t| ƒ\}
} t |
¡}|jtj| |	dd�}�n¢|�r®|�r®| ¡ }d}|�s*t| ƒ�rÄd}nd}t|d�}tj || j!| j"| j#| j$|||d�\}}|dk�rtdt%ƒ | &tj'¡ |�r8| ¡ }�nt(| ƒ}t|ƒ�sXt |ƒ�sXtdtƒ t|ƒ}g }g }g }t)|jd ƒD ]v}|dd…|gf  ¡  ¡ }||ƒ}t *|¡}|jd }| +|¡ | +tj,||t-d�¡ | +tj	|| | jd�¡ �qrt .|¡}t .|¡}t .|¡}| j/|||ff|j| jd�}t |ƒ�r8| /|¡}|S )aì  Solve the sparse linear system Ax=b, where b may be a vector or a matrix.

    Parameters
    ----------
    A : ndarray or sparse matrix
        The square matrix A will be converted into CSC or CSR form
    b : ndarray or sparse matrix
        The matrix or vector representing the right hand side of the equation.
        If a vector, b.shape must be (n,) or (n, 1).
    permc_spec : str, optional
        How to permute the columns of the matrix for sparsity preservation.
        (default: 'COLAMD')

        - ``NATURAL``: natural ordering.
        - ``MMD_ATA``: minimum degree ordering on the structure of A^T A.
        - ``MMD_AT_PLUS_A``: minimum degree ordering on the structure of A^T+A.
        - ``COLAMD``: approximate minimum degree column ordering [1]_, [2]_.

    use_umfpack : bool, optional
        if True (default) then use UMFPACK for the solution [3]_, [4]_, [5]_,
        [6]_ . This is only referenced if b is a vector and
        ``scikits.umfpack`` is installed.

    Returns
    -------
    x : ndarray or sparse matrix
        the solution of the sparse linear equation.
        If b is a vector, then x is a vector of size A.shape[1]
        If b is a matrix, then x is a matrix of size (A.shape[1], b.shape[1])

    Notes
    -----
    For solving the matrix expression AX = B, this solver assumes the resulting
    matrix X is sparse, as is often the case for very sparse inputs.  If the
    resulting X is dense, the construction of this sparse result will be
    relatively expensive.  In that case, consider converting A to a dense
    matrix and using scipy.linalg.solve or its variants.

    References
    ----------
    .. [1] T. A. Davis, J. R. Gilbert, S. Larimore, E. Ng, Algorithm 836:
           COLAMD, an approximate column minimum degree ordering algorithm,
           ACM Trans. on Mathematical Software, 30(3), 2004, pp. 377--380.
           :doi:`10.1145/1024074.1024080`

    .. [2] T. A. Davis, J. R. Gilbert, S. Larimore, E. Ng, A column approximate
           minimum degree ordering algorithm, ACM Trans. on Mathematical
           Software, 30(3), 2004, pp. 353--376. :doi:`10.1145/1024074.1024079`

    .. [3] T. A. Davis, Algorithm 832:  UMFPACK - an unsymmetric-pattern
           multifrontal method with a column pre-ordering strategy, ACM
           Trans. on Mathematical Software, 30(2), 2004, pp. 196--199.
           https://dl.acm.org/doi/abs/10.1145/992200.992206

    .. [4] T. A. Davis, A column pre-ordering strategy for the
           unsymmetric-pattern multifrontal method, ACM Trans.
           on Mathematical Software, 30(2), 2004, pp. 165--195.
           https://dl.acm.org/doi/abs/10.1145/992200.992205

    .. [5] T. A. Davis and I. S. Duff, A combined unifrontal/multifrontal
           method for unsymmetric sparse matrices, ACM Trans. on
           Mathematical Software, 25(1), 1999, pp. 1--19.
           https://doi.org/10.1145/305658.287640

    .. [6] T. A. Davis and I. S. Duff, An unsymmetric-pattern multifrontal
           method for sparse LU factorization, SIAM J. Matrix Analysis and
           Computations, 18(1), 1997, pp. 140--158.
           https://doi.org/10.1137/S0895479894246905T.


    Examples
    --------
    >>> import numpy as np
    >>> from scipy.sparse import csc_matrix
    >>> from scipy.sparse.linalg import spsolve
    >>> A = csc_matrix([[3, 2, 0], [1, -1, 0], [0, 5, 1]], dtype=float)
    >>> B = csc_matrix([[2, 0], [-1, 0], [2, 0]], dtype=float)
    >>> x = spsolve(A, B)
    >>> np.allclose(A.dot(x).toarray(), B.toarray())
    True
    z.spsolve requires A be CSC or CSR matrix formatr   é   z$matrix must be square (has shape %s)r   z)matrix - rhs dimension mismatch (%s - %s))r$   úScikits.umfpack not installed.ÚdDúZconvert matrix data to double, please, using .astype(), or set linsolve.useUmfpack = FalseT©ZautoTransposeF)ÚColPerm)ÚoptionszMatrix is exactly singularzCspsolve is more efficient when sparse b is in the CSC matrix formatN)Úshaper$   )0r
   Úto_scipy_sparseÚtocscr   r   r   r   r   r   r   Úndimr=   Úsum_duplicatesÚasfptyper%   Úpromote_typesr$   Úastyper.   r   ÚtoarrayÚravelÚnoScikitÚRuntimeErrorÚcharr5   r   ÚUmfpackContextÚlinsolveÚ	UMFPACK_AÚdictr   ZgssvÚnnzÚdatar,   r0   r   ÚfillÚnanr   ÚrangeÚflatnonzeroÚappendÚfullÚintÚconcatenateÚ	__class__)r1   ÚbÚ
permc_specZuse_umfpackZb_is_sparseZb_is_vectorÚresult_dtypeÚMÚNZb_vecÚ
umf_familyÚumfÚxÚflagr<   ÚinfoZ
AfactsolveZ	data_segsZrow_segsZcol_segsÚjÚbjZxjÚwZsegment_lengthZsparse_dataZ
sparse_rowZ
sparse_colr   r   r   r   ~   sª    Sÿ"




ÿ


ÿ


  ÿ


ÿ





 ÿ

c           
   
   C   sÈ   t | ƒr(t| ƒdœdd„}|  ¡  ¡ } nt}t| ƒsFt| ƒ} tdtƒ |  ¡  |  	¡ } | j
\}}||krptdƒ‚t||||d�}	|dk	r’|	 |¡ |	d d	kr¦d
|	d< tj|| j| j| j| j|d|	d�S )a×  
    Compute the LU decomposition of a sparse, square matrix.

    Parameters
    ----------
    A : sparse matrix
        Sparse matrix to factorize. Most efficient when provided in CSC
        format. Other formats will be converted to CSC before factorization.
    permc_spec : str, optional
        How to permute the columns of the matrix for sparsity preservation.
        (default: 'COLAMD')

        - ``NATURAL``: natural ordering.
        - ``MMD_ATA``: minimum degree ordering on the structure of A^T A.
        - ``MMD_AT_PLUS_A``: minimum degree ordering on the structure of A^T+A.
        - ``COLAMD``: approximate minimum degree column ordering

    diag_pivot_thresh : float, optional
        Threshold used for a diagonal entry to be an acceptable pivot.
        See SuperLU user's guide for details [1]_
    relax : int, optional
        Expert option for customizing the degree of relaxing supernodes.
        See SuperLU user's guide for details [1]_
    panel_size : int, optional
        Expert option for customizing the panel size.
        See SuperLU user's guide for details [1]_
    options : dict, optional
        Dictionary containing additional expert options to SuperLU.
        See SuperLU user guide [1]_ (section 2.4 on the 'Options' argument)
        for more details. For example, you can specify
        ``options=dict(Equil=False, IterRefine='SINGLE'))``
        to turn equilibration off and perform a single iterative refinement.

    Returns
    -------
    invA : scipy.sparse.linalg.SuperLU
        Object, which has a ``solve`` method.

    See also
    --------
    spilu : incomplete LU decomposition

    Notes
    -----
    This function uses the SuperLU library.

    References
    ----------
    .. [1] SuperLU https://portal.nersc.gov/project/sparse/superlu/

    Examples
    --------
    >>> import numpy as np
    >>> from scipy.sparse import csc_matrix
    >>> from scipy.sparse.linalg import splu
    >>> A = csc_matrix([[1., 0., 0.], [5., 0., 2.], [0., -1., 0.]], dtype=float)
    >>> B = splu(A)
    >>> x = np.array([1., 2., 3.], dtype=float)
    >>> B.solve(x)
    array([ 1. , -3. , -1.5])
    >>> A.dot(B.solve(x))
    array([ 1.,  2.,  3.])
    >>> B.solve(A.dot(x))
    array([ 1.,  2.,  3.])
    ©Úclsc                 W   s   | t |Ž ƒS ©N©r   ©rg   Úar   r   r   Ú<lambda>ƒ  ó    zsplu.<locals>.<lambda>ú&splu converted its input to CSC formatúcan only factor square matrices)ÚDiagPivotThreshr;   Ú	PanelSizeÚRelaxNr;   ÚNATURALTÚSymmetricModeF©Úcsc_construct_funcZilur<   ©r
   Útyper>   r?   r   r   r   r   rA   rB   r=   r.   rM   Úupdater   ZgstrfrN   rO   r,   r0   )
r1   rZ   Údiag_pivot_threshÚrelaxÚ
panel_sizer<   rv   r\   r]   Ú_optionsr   r   r   r   >  s2    D

 ÿ
 þc	              
   C   sÎ   t | ƒr(t| ƒdœdd„}	|  ¡  ¡ } nt}	t| ƒsFt| ƒ} tdtƒ |  ¡  |  	¡ } | j
\}
}|
|krptdƒ‚t|||||||d�}|dk	r˜| |¡ |d d	kr¬d
|d< tj|| j| j| j| j|	d
|d�S )aÏ  
    Compute an incomplete LU decomposition for a sparse, square matrix.

    The resulting object is an approximation to the inverse of `A`.

    Parameters
    ----------
    A : (N, N) array_like
        Sparse matrix to factorize. Most efficient when provided in CSC format.
        Other formats will be converted to CSC before factorization.
    drop_tol : float, optional
        Drop tolerance (0 <= tol <= 1) for an incomplete LU decomposition.
        (default: 1e-4)
    fill_factor : float, optional
        Specifies the fill ratio upper bound (>= 1.0) for ILU. (default: 10)
    drop_rule : str, optional
        Comma-separated string of drop rules to use.
        Available rules: ``basic``, ``prows``, ``column``, ``area``,
        ``secondary``, ``dynamic``, ``interp``. (Default: ``basic,area``)

        See SuperLU documentation for details.

    Remaining other options
        Same as for `splu`

    Returns
    -------
    invA_approx : scipy.sparse.linalg.SuperLU
        Object, which has a ``solve`` method.

    See also
    --------
    splu : complete LU decomposition

    Notes
    -----
    To improve the better approximation to the inverse, you may need to
    increase `fill_factor` AND decrease `drop_tol`.

    This function uses the SuperLU library.

    Examples
    --------
    >>> import numpy as np
    >>> from scipy.sparse import csc_matrix
    >>> from scipy.sparse.linalg import spilu
    >>> A = csc_matrix([[1., 0., 0.], [5., 0., 2.], [0., -1., 0.]], dtype=float)
    >>> B = spilu(A)
    >>> x = np.array([1., 2., 3.], dtype=float)
    >>> B.solve(x)
    array([ 1. , -3. , -1.5])
    >>> A.dot(B.solve(x))
    array([ 1.,  2.,  3.])
    >>> B.solve(A.dot(x))
    array([ 1.,  2.,  3.])
    rf   c                 W   s   | t |Ž ƒS rh   ri   rj   r   r   r   rl   Þ  rm   zspilu.<locals>.<lambda>z'spilu converted its input to CSC formatro   )ZILU_DropRuleZILU_DropTolZILU_FillFactorrp   r;   rq   rr   Nr;   rs   Trt   ru   rw   )r1   Zdrop_tolZfill_factorZ	drop_rulerZ   rz   r{   r|   r<   rv   r\   r]   r}   r   r   r   r   ¢  s<    ;ÿ
  ý
 þc                    sš   t ˆ ƒrˆ  ¡  ¡ ‰ trŒtr$tdƒ‚tˆ ƒs>tˆ ƒ‰ tdt	ƒ ˆ  
¡ ‰ ˆ jjdkrZtdƒ‚tˆ ƒ\}‰ t |¡‰ˆ ˆ ¡ ‡ ‡fdd„}|S tˆ ƒjS dS )aK  
    Return a function for solving a sparse linear system, with A pre-factorized.

    Parameters
    ----------
    A : (N, N) array_like
        Input. A in CSC format is most efficient. A CSR format matrix will
        be converted to CSC before factorization.

    Returns
    -------
    solve : callable
        To solve the linear system of equations given in `A`, the `solve`
        callable should be passed an ndarray of shape (N,).

    Examples
    --------
    >>> import numpy as np
    >>> from scipy.sparse.linalg import factorized
    >>> A = np.array([[ 3. ,  2. , -1. ],
    ...               [ 2. , -2. ,  4. ],
    ...               [-1. ,  0.5, -1. ]])
    >>> solve = factorized(A) # Makes LU decomposition.
    >>> rhs1 = np.array([1, -2, 0])
    >>> solve(rhs1) # Uses the LU factors.
    array([ 1., -2., -2.])

    r7   rn   r8   r9   c              	      s2   t jddd�� ˆjtjˆ | dd�}W 5 Q R X |S )NÚignore)ÚdivideÚinvalidTr:   )r%   ÚerrstateÚsolver   rL   )rY   Úresult©r1   r_   r   r   r‚   5  s    zfactorized.<locals>.solveN)r
   r>   r?   r   rG   rH   r   r   r   r   rB   r$   rI   r.   r5   r   rJ   Únumericr   r‚   )r1   r^   r‚   r   r„   r   r      s&    ÿ

c                 C   s,  t | ƒr|  ¡  ¡ } t| ƒs0tdtƒ t| ƒ} n|s<|  ¡ } | jd | jd kr`t	d 
| j¡ƒ‚|  ¡  t |¡}|jdkrŒt	d 
|j¡ƒ‚| jd |jd kr´t	d 
| j|j¡ƒ‚t | j|tj¡}|rötj|j|dd	�râ|}nt	d
 
|j|¡ƒ‚n|j|dd�}|�rtt|ƒƒ}ntt|ƒd ddƒ}|D ]ö}	| j|	 }
| j|	d  }|�rj|d }t|
|d ƒ}n|
}t|
d |ƒ}|�sª||
k�sœ| j| |	k �rªtd 
|	¡ƒ‚|�sÖ| j| |	k�rÖtd 
|	| j| ¡ƒ‚| j| }| j| }||	  t || j|¡8  < |�s0||	  | j|   < �q0|S )a  
    Solve the equation ``A x = b`` for `x`, assuming A is a triangular matrix.

    Parameters
    ----------
    A : (M, M) sparse matrix
        A sparse square triangular matrix. Should be in CSR format.
    b : (M,) or (M, N) array_like
        Right-hand side matrix in ``A x = b``
    lower : bool, optional
        Whether `A` is a lower or upper triangular matrix.
        Default is lower triangular matrix.
    overwrite_A : bool, optional
        Allow changing `A`. The indices of `A` are going to be sorted and zero
        entries are going to be removed.
        Enabling gives a performance gain. Default is False.
    overwrite_b : bool, optional
        Allow overwriting data in `b`.
        Enabling gives a performance gain. Default is False.
        If `overwrite_b` is True, it should be ensured that
        `b` has an appropriate dtype to be able to store the result.
    unit_diagonal : bool, optional
        If True, diagonal elements of `a` are assumed to be 1 and will not be
        referenced.

        .. versionadded:: 1.4.0

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

    Raises
    ------
    LinAlgError
        If `A` is singular or not triangular.
    ValueError
        If shape of `A` or shape of `b` do not match the requirements.

    Notes
    -----
    .. versionadded:: 0.19.0

    Examples
    --------
    >>> import numpy as np
    >>> from scipy.sparse import csr_matrix
    >>> from scipy.sparse.linalg import spsolve_triangular
    >>> A = csr_matrix([[3, 0, 0], [1, -1, 0], [2, 0, 1]], dtype=float)
    >>> B = np.array([[2, 0], [-1, 0], [2, 0]], dtype=float)
    >>> x = spsolve_triangular(A, B)
    >>> np.allclose(A.dot(x), B)
    True
    z8CSR matrix format is required. Converting to CSR matrix.r   r   z.A must be a square matrix but its shape is {}.)r   r6   z,b must have 1 or 2 dims but its shape is {}.zˆThe size of the dimensions of A must be equal to the size of the first dimension of b but the shape of A is {} and the shape of b is {}.Ú	same_kind)Úcastingz5Cannot overwrite b (dtype {}) with result of type {}.T)r#   éÿÿÿÿz#A is singular: diagonal {} is zero.z*A is not triangular: A[{}, {}] is nonzero.)r
   r>   Útocsrr   r   r   r	   r#   r=   r.   ÚformatrA   r%   Ú
asanyarrayr@   Úresult_typerO   r&   Úcan_castr$   rD   rR   Úlenr0   Úslicer,   r   ÚdotÚT)r1   rY   ÚlowerZoverwrite_AÚoverwrite_bÚunit_diagonalZx_dtyper`   Úrow_indicesÚiZindptr_startZindptr_stopZA_diagonal_index_row_iZA_off_diagonal_indices_row_iZA_column_indices_in_row_iZA_values_in_row_ir   r   r   r   A  s†    :ÿ

ÿ


ÿ þÿ ÿÿ
ÿÿ ÿÿ

)NT)NNNNNNNN)TFFF)#Úwarningsr   Únumpyr%   r   Úscipy.sparser   r   r   r   r   r	   Zscipy.sparse._sputilsr
   Úscipy.linalgr   r#   Ú r   rG   Zscikits.umfpackr   ÚImportErrorr   Ú__all__ÚUserWarningr   r   r5   r   rM   r   r   r   r   r   r   r   r   Ú<module>   sJ    

 ÿB
 A  ÿ
d        ÿ
^A  ÿ