
    _Mhw                     H   d dl mZmZ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mZmZmZ d dlmZ d dlZd dlZddlmZ d	Z	 d dlmZ n# e$ r d
ZY nw xY w ej                    ag dZ G d de           Z!d Z"d Z#ddZ$	 	 ddZ%	 	 ddZ&d Z'	 	 ddZ(d Z)d Z*dS )    )warncatch_warningssimplefilterN)asarray)issparseSparseEfficiencyWarning	csr_array	csc_array	eye_arraydiags_array)is_pydata_spmatrixconvert_pydata_sparse_to_scipyget_index_dtypesafely_cast_index_arrays)LinAlgError   )_superluFT)	
use_solverspsolvespluspilu
factorizedMatrixRankWarningspsolve_triangularis_sptriangularspbandwidthc                       e Zd ZdS )r   N)__name__
__module____qualname__     d/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/scipy/sparse/linalg/_dsolve/linsolve.pyr   r      s        Dr"   r   c                      d| v r| d         t           _        t           j        r!d| v rt          j        | d                    dS dS dS )aq	  
    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_array
    >>> R = np.random.randn(5, 5)
    >>> A = csc_array(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)r%   uumfpack	configure)kwargss    r#   r   r       sd    | vl+
| M-77f5J.KLLLLLLM M77r"   c                    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          t           | j        j                  }t          t           | j        j        j                  }	 |||f         }n+# t          $ r}d| d| d}t          |          |d}~ww xY w|d	         d
z   }t          j        |           }t          j        | j        t           j                  |_        t          j        | j        t           j                  |_        ||fS )z8Get umfpack family string given the sparse matrix dtype.dizidlzlz]only float64 or complex128 matrices with int32 or int64 indices are supported! (got: matrix: z, indices: )Nr   ldtype)npfloat64int32
complex128int64getattrr3   nameindicesKeyError
ValueErrorcopyr   indptr)A	_familiesf_typei_typefamilyemsgA_news           r#   _get_umf_familyrH   c   s9    
RX	!4	RX	!4	I R&&F R-..F%FF+, % % %T7=T TJPT T Too1$% AY_FIaLLE:ahbh777ELJqy999EM5=s   '
B2 2
C<CCc           
      
   t          |          }|r|j        nd}t          |           } t          |          }t          |           r	| j        dv s&t          |           } t          dt          d           t          |          }|st          |          }|j	        dk    p|j	        dk    o|j
        d         dk    }|                                  |                                 } t          j        | j        |j                  }| j        |k    r|                     |          } |j        |k    r|                    |          }| j
        \  }	}
|	|
k    rt#          d|	|
f d          |	|j
        d	         k    r&t#          d
| j
         d|j
        d	          d          t%          t&          d          st(           t&          _        |ot&          j        }|r|r|r|                                }n|}t          || j                                                  }t(          rt1          d          | j        j        dvrt#          d          t5          |           \  }} t7          j        |          }|                    t6          j        | |d          }n|r|r|                                }d}|s| j        dk    rd}nd	}| j                            t          j         d          }| j!                            t          j         d          }tE          |          }tG          j$        |
| j%        | j&        |||||          \  }}|d	k    r6t          dtN          d           |(                    t          j)                   |r|                                }ntU          |           }|j        dk    s5t          |          s&t          dt          d           t          |          }g }g }g }tW          |j
        d                   D ]}|dd|f                                                                         } ||          }t          j,        |          }|j
        d	         }|-                    |           |-                    t          j.        ||t^                               |-                    t          j        ||         | j                             t          j0        |          }tc          te          |j
                            }t          j0        ||          }t          j0        ||          } |                     ||| ff|j
        | j                  }|r|3                    |          }|S )a  Solve the sparse linear system Ax=b, where b may be a vector or a matrix.

    Parameters
    ----------
    A : ndarray or sparse array or matrix
        The square matrix A will be converted into CSC or CSR form
    b : ndarray or sparse array or 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 array or 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_array
    >>> from scipy.sparse.linalg import spsolve
    >>> A = csc_array([[3, 2, 0], [1, -1, 0], [0, 5, 1]], dtype=float)
    >>> B = csc_array([[2, 0], [-1, 0], [2, 0]], dtype=float)
    >>> x = spsolve(A, B)
    >>> np.allclose(A.dot(x).toarray(), B.toarray())
    True
    Ncsccsrz.spsolve requires A be CSC or CSR matrix format   
stacklevelr   z!matrix must be square (has shape r0   r   z!matrix - rhs dimension mismatch (z - r'   r2   Scikits.umfpack not installed.dD\convert matrix data to double, please, using .astype(), or set linsolve.useUmfpack.u = FalseTautoTransposeFrK   )r>   )ColPerm)optionszMatrix is exactly singularzCspsolve is more efficient when sparse b is in the CSC matrix format)maxval)shaper3   )4r   	__class__r   r   formatr
   r   r   r   ndimrX   sum_duplicates	_asfptyper4   promote_typesr3   astyper=   hasattrr%   noScikitr'   toarrayravelRuntimeErrorcharrH   r(   UmfpackContextlinsolve	UMFPACK_Ar;   intcr?   dictr   gssvnnzdatar   fillnanr   rangeflatnonzeroappendfullintconcatenater   maxfrom_scipy_sparse)!r@   b
permc_specuse_umfpackis_pydata_sparsepydata_sparse_clsb_is_sparseb_is_vectorresult_dtypeMNb_vec
umf_familyumfxflagr;   r?   rV   info
Afactsolve	data_segsrow_segscol_segsjbjxjwsegment_lengthsparse_data	idx_dtype
sparse_row
sparse_cols!                                    r#   r   r      sz   d *!,,'7AT&q))A&q))AQKK 4AH66aLL=$	4 	4 	4 	4 1++K AJJFaKEQVq[%DQWQZ1_K 	A#AGQW55Lw,HH\""w,HH\"" 7DAq	QFaVFFFGGGAGAJVQWVVQRVVVWWW:s## $#|
.*,K F;{ F; 	IIKKEEEQW---3355 	A?@@@7<t## E F F F (**
A$Z00LL*Au'+  - -  	 ; 	 		AK /	;x5  i&&rwU&;;GX__RW5_99F:...GmAquafgv$%tW> > >GAtqyy13DQRSSSSrv GGII $AJH%%);A)>)>% 3,< < < < aLL IHH171:&& C Cqqq!tW__&&,,..Z^^N2&&!"""" E E EFFF  BqE!A!A!ABBBB.33K's17||<<<I	BBBJ	BBBJ[:z*BC!"  9 9A   ;%77::Hr"   c           
         t          |           r<t          |           }|dd}|                                                                 } nt          }t          |           r| j        dk    s&t	          |           } t          dt          d           | 	                                 | 
                                } | j        \  }}	||	k    rt          d          t          | t          j        d          \  }
}t!          ||||	          }||                    |           |d         dk    rd|d<   t%          j        |	| j        | j        |
||d|          S )a  
    Compute the LU decomposition of a sparse, square matrix.

    Parameters
    ----------
    A : sparse array or matrix
        Sparse array 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_array
    >>> from scipy.sparse.linalg import splu
    >>> A = csc_array([[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                 :    |                      t          |           S Nrw   r
   r   as     r#   csc_construct_funcz splu.<locals>.csc_construct_func      ((A777r"   rK   &splu converted its input to CSC formatrM   rN   can only factor square matricesSuperLU)DiagPivotThreshrU   	PanelSizeRelaxNrU   NATURALTSymmetricModeFr   ilurV   r   typeto_scipy_sparsetocscr
   r   rZ   r   r   r\   r]   rX   r=   r   r4   ri   rj   updater   gstrfrl   rm   )r@   ry   diag_pivot_threshrelax
panel_sizerV   A_clsr   r   r   r;   r?   _optionss                r#   r   r   H  s   H ! 'Q', 	8 	8 	8 	8 	8%%''&QKK 4AH--aLL5$	4 	4 	4 	4 	A7DAq	Q:;;;.q"'9EEOGV$5z(7 7 7H    	y(($(!>!QUAFGV-?#X7 7 7 7r"   c	           
         t          |           r<t          |           }	|	dd}
|                                                                 } nt          }
t          |           r| j        dk    s&t	          |           } t          dt          d           | 	                                 | 
                                } | j        \  }}||k    rt          d          t          | t          j        d          \  }}t!          |||||||	          }||                    |           |d         dk    rd|d<   t%          j        || j        | j        |||
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 array 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_array
    >>> from scipy.sparse.linalg import spilu
    >>> A = csc_array([[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.])
    r   c                 :    |                      t          |           S r   r   r   s     r#   r   z!spilu.<locals>.csc_construct_func  r   r"   rK   z'spilu converted its input to CSC formatrM   rN   r   r   )ILU_DropRuleILU_DropTolILU_FillFactorr   rU   r   r   NrU   r   Tr   r   r   )r@   drop_tolfill_factor	drop_rulery   r   r   r   rV   r   r   r   r   r;   r?   r   s                   r#   r   r     s   v ! 'Q', 	8 	8 	8 	8 	8%%''&QKK 4AH--aLL6$	4 	4 	4 	4 	A7DAq	Q:;;;.q"'9EEOGV#.$5z(7 7 7H     	y(($(!>!QUAFGV-?"H6 6 6 6r"   c                     t                     r&                                                                  t          t          d          st
           t          _        t          j        rt
          rt          d          t                     r j	        dk    s&t                      t          dt          d                                              j        j        dvrt!          d          t#                     \  } t%          j        |                                           fd	}|S t+                     j        S )
a  
    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
    >>> from scipy.sparse import csc_array
    >>> A = np.array([[ 3. ,  2. , -1. ],
    ...               [ 2. , -2. ,  4. ],
    ...               [-1. ,  0.5, -1. ]])
    >>> solve = factorized(csc_array(A)) # Makes LU decomposition.
    >>> rhs1 = np.array([1, -2, 0])
    >>> solve(rhs1) # Uses the LU factors.
    array([ 1., -2., -2.])

    r'   rP   rK   r   rM   rN   rQ   rR   c                     t          j        dd          5                      t          j        | d          }d d d            n# 1 swxY w Y   |S )Nignore)divideinvalidTrS   )r4   errstatesolver(   rh   )rx   resultr@   r   s     r#   r   zfactorized.<locals>.solveL  s    Hh??? P P7#4a$OOP P P P P P P P P P P P P P P Ms   $AAA)r   r   r   r`   r%   ra   r'   rd   r   rZ   r
   r   r   r]   r3   re   r=   rH   r(   rf   numericr   r   )r@   r   r   r   s   `  @r#   r   r     sT   < ! (%%'':s## $#|
|  	A?@@@ 	8E 1 1!A9(Q8 8 8 8 KKMM7<t## E F F F (**
A$Z00 	A	 	 	 	 	 	 Aww}r"   c                    t          |           r&|                                                                 } d}t          |           r| j        dk    r| j        } d}| }t          |           r| j        dk    s't          dt          d           t          |           } n|s| 	                                } | j
        \  }}||k    rt          d| j
         d	          |rQt                      5  t          d
t                     |                     d           ddd           n# 1 swxY w Y   nu|                                 }	t!          j        |	dk              rt%          d          d|	z  }
|dk    r| t'          |
          z  } n| j        t'          |
          z  j        } |                                  t!          j        |          }|j        dvrt          d|j
         d	          ||j
        d         k    r t          d| j
         d|j
         d	          t!          j        t!          j        | j        t           j                  |j                  }| j        |k    r|                     |          } |j        |k    r|                    |          }n|s|	                                }|r| }t          ||f|          }n)t7          ||d          }| }|                    d           t9          j        |||j        |j        |j         |j!        ||j        |j        |j         |j!        |          \  }}|rt%          d          |s, |
j"        dgdgtG          |j
                  dz
  z  R  }
||
z  }|S )a  
    Solve the equation ``A x = b`` for `x`, assuming A is a triangular matrix.

    Parameters
    ----------
    A : (M, M) sparse array or matrix
        A sparse square triangular matrix. Should be in CSR or CSC 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`.
        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.

        .. 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 csc_array
    >>> from scipy.sparse.linalg import spsolve_triangular
    >>> A = csc_array([[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
    r   rL   TrK   z?CSC or CSR matrix format is required. Converting to CSC matrix.rM   rN   z+A must be a square matrix but its shape is .r   r   Nr   z&A is singular: zero entry on diagonal.)r   rM   z)b must have 1 or 2 dims but its shape is zlThe size of the dimensions of A must be equal to the size of the first dimension of b but the shape of A is z and the shape of b is r2   )r3   rZ   zA is singular.)$r   r   r   r   rZ   r   r   r   r
   r>   rX   r=   r   r   setdiagdiagonalr4   anyr   r   r\   
asanyarrayr[   r^   r3   float32r_   r   r   gstrsrl   rm   r;   r?   reshapelen)r@   rx   loweroverwrite_Aoverwrite_bunit_diagonaltransr   r   diaginvdiagr   LUr   r   s                   r#   r   r   X  s   p ! (%%''E{{ qx5((C	QKK AH--N$	4 	4 	4 	4aLL FFHH 7DAqAvvD!'DDDF F 	F  / 	 	#:;;;IIaLLL	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 zz||6$!) 	:8: : :D&C<<K(((AA{7+++.A 
aAvVBBBBD D 	DAGAJ:w: :/0w: : :
 
 	
 #B$4QWbj$I$I17SSLw,HH\""w,HH\"" FFHH q!fL111a|E:::			!nUqvqy!(qvqy!(   GAt  ,*+++ !'/"Bs17||a/?(@BBBKHs   -+D$$D(+D(c                 *   t          |           r	| j        dv s&t          dt          d           t	          |           } | j        dk    r:| j                                        dk    | j                                        dk    fS | j        dk    r:| j        \  }}||k    	                                ||k    	                                fS | j        dk    rVt          d	 | 
                                D                       t          d
 | 
                                D                       fS | j        dk    rZt          d t          | j                  D                       }t          d t          | j                  D                       }||fS | j        | j        }}t          |          dz
  }d\  }}|dz  ddfD ]V}|||         ||dz                     }|o||k    	                                }|o||k    	                                }|s|s dS Wt!          j        t!          j        |          t!          j        |                    }|}|o||k    	                                }|o||k    	                                }| j        dk    r||fS ||fS )a  Returns 2-tuple indicating lower/upper triangular structure for sparse ``A``

    Checks for triangular structure in ``A``. The result is summarized in
    two boolean values ``lower`` and ``upper`` to designate whether ``A`` is
    lower triangular or upper triangular respectively. Diagonal ``A`` will
    result in both being True. Non-triangular structure results in False for both.

    Only the sparse structure is used here. Values are not checked for zeros.

    This function will convert a copy of ``A`` to CSC format if it is not already
    CSR or CSC format. So it may be more efficient to convert it yourself if you
    have other uses for the CSR/CSC version.

    If ``A`` is not square, the portions outside the upper left square of the
    matrix do not affect its triangular structure. You probably want to work
    with the square portion of the matrix, though it is not requred here.

    Parameters
    ----------
    A : SciPy sparse array or matrix
        A sparse matrix preferrably in CSR or CSC format.

    Returns
    -------
    lower, upper : 2-tuple of bool

        .. versionadded:: 1.15.0

    Examples
    --------
    >>> import numpy as np
    >>> from scipy.sparse import csc_array, eye_array
    >>> from scipy.sparse.linalg import is_sptriangular
    >>> A = csc_array([[3, 0, 0], [1, -1, 0], [2, 0, 1]], dtype=float)
    >>> is_sptriangular(A)
    (True, False)
    >>> D = eye_array(3, format='csr')
    >>> is_sptriangular(D)
    (True, True)
    )rK   rL   coodiadoklilzCis_sptriangular needs sparse and not BSR format. Converting to CSR.rM   rN   r   r   r   r   c              3   (   K   | ]\  }}||k    V  d S r   r!   .0rcs      r#   	<genexpr>z"is_sptriangular.<locals>.<genexpr>  s*      //da16//////r"   c              3   (   K   | ]\  }}||k    V  d S r   r!   r   s      r#   r   z"is_sptriangular.<locals>.<genexpr>  s*      4Q4Q1Q!V4Q4Q4Q4Q4Q4Qr"   r   c              3   2   K   | ]\  }}|D ]
}||k    V  d S r   r!   r   rowcolscols       r#   r   z"is_sptriangular.<locals>.<genexpr>  7      RR93TRRcC3JRRRRRRRr"   c              3   2   K   | ]\  }}|D ]
}||k    V  d S r   r!   r   s       r#   r   z"is_sptriangular.<locals>.<genexpr>  r   r"   r   )TTr   )FFrL   )r   rZ   r   r   r	   offsetsrv   mincoordsallkeys	enumeraterowsr?   r;   r   r4   repeatarangediff)	r@   r   r   r   upperr?   r;   r   r   s	            r#   r   r     s   R QKK AH(RRRR$	4 	4 	4 	4aLL 	x5y}}!#QY]]__%999	
U		X
d!!##ddl%7%7%9%999	
U		//affhh/////4Q4Q4Q4Q4Q1Q1QQQ	
U		RR	!&0A0ARRRRRRR	!&0A0ARRRRRe|h	GFFaALE5Q2    vc{6#'?23-3$;++---3$;++-- 	 U 	 <<9RYq\\276??33DD*tt|((**E*tt|((**Ex5e|%<r"   c                    t          |           r	| j        dv s&t          dt          d           t	          |           } | j        dk    rst          d| j                                                                                   t          d| j                                                                                  fS | j        dv rk| j	        | j
        }}t          |          dz
  }t          j        t          j        |          t          j        |                    |z
  }| j        d	k    r| }ns| j        d
k    r| j        d         | j        d         z
  }nL| j        dk    rAd |                                 D             dgz   }t          |           t          |          fS t          t          j        |                                           d          t          t          j        |                                          d          fS )ab  Return the lower and upper bandwidth of a 2D numeric array.

    Computes the lower and upper limits on the bandwidth of the
    sparse 2D array ``A``. The result is summarized as a 2-tuple
    of positive integers ``(lo, hi)``. A zero denotes no sub/super
    diagonal entries on that side (tringular). The maximum value
    for ``lo``(``hi``) is one less than the number of rows(cols).

    Only the sparse structure is used here. Values are not checked for zeros.

    Parameters
    ----------
    A : SciPy sparse array or matrix
        A sparse matrix preferrably in CSR or CSC format.

    Returns
    -------
    below, above : 2-tuple of int
        The distance to the farthest non-zero diagonal below/above the
        main diagonal.

        .. versionadded:: 1.15.0

    Examples
    --------
    >>> import numpy as np
    >>> from scipy.sparse.linalg import spbandwidth
    >>> from scipy.sparse import csc_array, eye_array
    >>> A = csc_array([[3, 0, 0], [1, -1, 0], [2, 0, 1]], dtype=float)
    >>> spbandwidth(A)
    (2, 0)
    >>> D = eye_array(3, format='csr')
    >>> spbandwidth(D)
    (0, 0)
    )rK   rL   r   r   r   zCspbandwidth needs sparse format not LIL and BSR. Converting to CSR.rM   rN   r   r   rJ   r   rL   r   r   c                     g | ]
\  }}||z
  S r!   r!   r   s      r#   
<listcomp>zspbandwidth.<locals>.<listcomp>g  s     ,,,41aA,,,r"   )r   rZ   r   r   r	   rv   r   r   itemr?   r;   r   r4   r   r   r   r   r   )r@   r?   r;   r   gaps        r#   r   r   2  s   H QKK AH(KKKR$	4 	4 	4 	4aLL 	x51qy}}++---..Aqy}}7K7K7M7M0N0NNNx>!!(AIKK!Oi	!bgfoo66@8u$C	
U		hqkAHQK'	
U		,,16688,,,s2Cy#c((""s  """A&&BF3KK,<,<,>,>(B(BBBr"   )NT)NNNNN)NNNNNNNN)TFFF)+warningsr   r   r   numpyr4   r   scipy.sparser   r   r	   r
   r   r   scipy.sparse._sputilsr   r   r   r   scipy.linalgr   r>   	threading r   ra   scikits.umfpackr(   ImportErrorlocalr%   __all__UserWarningr   r   rH   r   r   r   r   r   r   r   r!   r"   r#   <module>r	     s   7 7 7 7 7 7 7 7 7 7          H H H H H H H H H H H H H H H HN N N N N N N N N N N N $ $ $ $ $ $           %%%%%%%   HHH Y_
X X X	 	 	 	 	 	 	 	AM AM AMF     D@ @ @ @F 04.2f7 f7 f7 f7R JNGK_6 _6 _6 _6DB B BJ IN%*G G G GTM M M`7C 7C 7C 7C 7Cs   A AA