a
    CCCfu                     @   s  d Z dZg dZddlmZ ddlZddlmZ ddl	m
Z
 dd	lmZmZ dd
lmZ ddlmZmZmZ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mZm Z m!Z!m"Z"m#Z#m$Z$ G dd deeZ%dd Z&G dd de%eZ'G dd de
e%Z(dS )z"Compressed Block Sparse Row formatzrestructuredtext en)	bsr_array
bsr_matrixisspmatrix_bsr    )warnN)copy_if_needed   )spmatrix)_data_matrix_minmax_mixin)
_cs_matrix)issparse_formats_spbasesparray)isshapegetdtypegetdata	to_nativeupcastcheck_shape)_sparsetools)
bsr_matvecbsr_matvecscsr_matmat_maxnnz
bsr_matmatbsr_transposebsr_sort_indices	bsr_tocsrc                   @   s.  e Zd ZdZd7ddZd8ddZeed	d
dZd9ddZ	e
j	je	_dd Zd:ddZe
jje_dd Zdd Zdd Zdd Zdd Zdd Zd;dd Zd<d!d"Ze
jje_d=d#d$Ze
jje_d>d%d&Zd?d'd(Ze
jje_d@d)d*Ze
jje_d+d, Zd-d. Zd/d0 Zd1d2 ZdAd3d4ZdBd5d6ZdS )C	_bsr_basebsrNFc              
   C   s  t |  t|r`|j| jkr,|r,| }n|j|d}|j|j|j|j	f\| _| _| _| _	nt
|trt|r@t|| _	| j\}}|d u rd}nt|std| t|}td| t|td| _|\}}	|| dks||	 dkrtd| jt|| ||	 ||	d}
tjd|
d	| _tj|| d
 |
d	| _q.t|dkr| j|||d}|j|d}|j|j|j|j	f\| _| _| _| _	q.t|dkr|\}}}d
}|d urt|}|d urt|t|}| j||f|dd}
|st}tj|||
d| _tj|||
d| _t|||d| _| jjdkrJtd| jj |d urt|sltd| t|| jjd
d  krtd|| jjd
d  ntdnzt|}W n6 ty } ztd| j |W Y d }~n
d }~0 0 | j||d	j|d}|j|j|j|j	f\| _| _| _| _	|d urDt|| _	n~| jd u rz t| jd
 }| j d
 }W n0 ty } ztd|W Y d }~n*d }~0 0 | j\}}	t|| ||	 f| _	| jd u r|d u rtdn
t|| _	|d ur| jj|dd| _| j dd d S )N	blocksize)r   r   zinvalid blocksize=%s)r   )defaultr   z#shape must be multiple of blocksizemaxvaldtyper      )r&   shape   T)r$   Zcheck_contents)copyr&   z*BSR data must be 3-dimensional, got shape=zinvalid blocksize=zmismatching blocksize={} vs {}z(unrecognized bsr_array constructor usagez+unrecognized form for %s_matrix constructorz!unable to infer matrix dimensionszneed to infer shapeFr*   )
full_check)!r	   __init__r   formatr*   tobsrindptrindicesdata_shape
isinstancetupler   r   r(   
ValueErrornpzerosr   float_get_index_dtypemaxlen_coo_containerr   arrayr   ndimasarray	Exceptionr!   astypecheck_format)selfZarg1r(   r&   r*   r!   MNRC	idx_dtypeZcoor   r2   r1   r0   r$   e rK   M/var/www/html/django/DPS/env/lib/python3.9/site-packages/scipy/sparse/_bsr.pyr-      s    











 




z_bsr_base.__init__Tc                 C   s  | j \}}| j\}}| jjjdkr<td| jjj ddd | jjjdkrdtd| jjj ddd | jjdks|| jjdkrt	d| j
jd	krt	d
t| j|| d krt	dt| j|| d f | jd dkrt	dt| jt| j
krt	d| jd t| jkrt	d|   |r| jdkr| j || krdt	d|| | j f | j dk r|t	dt| j dk rt	d| | j| jf}tj| j|d| _tj| j|d| _t| j
| _
dS )a  Check whether the array/matrix respects the BSR format.

        Parameters
        ----------
        full_check : bool, optional
            If `True`, run rigorous check, scanning arrays for valid values.
            Note that activating those check might copy arrays for casting,
            modifying indices and index pointers' inplace.
            If `False`, run basic checks on attributes. O(1) operations.
            Default is `True`.
        iz$indptr array has non-integer dtype ()r'   )
stacklevelz%indices array has non-integer dtype (r   z!indices, and indptr should be 1-Dr)   zdata should be 3-Dz&index pointer size (%d) should be (%d)r   z!index pointer should start with 0z*indices and data should have the same sizezQLast value of index pointer should be less than the size of index and data arraysz-column index values must be < %d (now max %d)z column index values must be >= 0z8index pointer values must form a non-decreasing sequencer%   N)r(   r!   r0   r&   kindr   namer1   r?   r6   r2   r<   prunennzr;   minr7   diffr:   r@   r   )rD   r,   rE   rF   rG   rH   rI   rK   rK   rL   rC      sN    

z_bsr_base.check_format)returnc                 C   s   | j jdd S )zBlock size of the matrix.r   N)r2   r(   )rD   rK   rK   rL   r!      s    z_bsr_base.blocksizec                 C   s0   |d urt d| j\}}t| jd | | S )Nz6_getnnz over an axis is not implemented for BSR formatrP   )NotImplementedErrorr!   intr0   )rD   axisrG   rH   rK   rK   rL   _getnnz   s    
z_bsr_base._getnnzc                 C   s|   t | j \}}t| trdnd}ddd | jD }ddd | jD }d| d| d	| jj d
| j	 d| d| dS )Nr>   matrixxc                 s   s   | ]}t |V  qd S Nstr.0r]   rK   rK   rL   	<genexpr>       z%_bsr_base.__repr__.<locals>.<genexpr>c                 s   s   | ]}t |V  qd S r^   r_   ra   rK   rK   rL   rc      rd   <z sparse z
 of type 'z'
	with z stored elements (blocksize = z) in z format>)
r   r.   r4   r   joinr(   r!   r&   typerT   )rD   _fmtZ
sparse_clsZ	shape_strZblkszrK   rK   rL   __repr__   s    z_bsr_base.__repr__r   c                 C   s   | j \}}|| ks||kr.tjd| jjdS | j\}}tjt|t|d |t|d t	| jd}t
||| || ||| j| jt| j|	 |S Nr   r%   )r(   r7   emptyr2   r&   r!   r8   rU   r;   r   r   Zbsr_diagonalr0   r1   ravel)rD   krowscolsrG   rH   yrK   rK   rL   diagonal   s    

 z_bsr_base.diagonalc                 C   s   t d S r^   rX   )rD   keyrK   rK   rL   __getitem__   s    z_bsr_base.__getitem__c                 C   s   t d S r^   rs   )rD   rt   valrK   rK   rL   __setitem__   s    z_bsr_base.__setitem__c                 C   s   | j dd|S NFr+   )tocoo
_add_dense)rD   otherrK   rK   rL   rz     s    z_bsr_base._add_densec              
   C   s`   | j \}}| j\}}tj| j d t| j|jd}t|| || ||| j| j| j	
 ||	 |S rk   )r(   r!   r7   r8   r   r&   r   r0   r1   r2   rm   )rD   r{   rE   rF   rG   rH   resultrK   rK   rL   _matmul_vector  s    

z_bsr_base._matmul_vectorc                 C   sr   | j \}}| j\}}|jd }tj||ft| j|jd}t|| || |||| j| j| j	
 |
 |
 
 |S )Nr   r%   )r!   r(   r7   r8   r   r&   r   r0   r1   r2   rm   )rD   r{   rG   rH   rE   rF   Zn_vecsr|   rK   rK   rL   _matmul_multivector  s    


z_bsr_base._matmul_multivectorc                 C   s  | j \}}|j \}}| j\}}|jdkr4|jd }nd}|jdkr^|dkr^|j||fdd}n|j||fd}| | j| j|j|jf}	t|| || | j|	| j|	|j|	|j|	}
| j| j| j|j|jf|
d}	t	j
| jj |	d}t	j
|
|	d}t	j
|| |
 t| j|jd}t|
|| || |||| j|	| j|	t	| j|j|	|j|	t	|j||| |d	||}| j|||f||f||fd
S )Nr   r   ZcsrF)r!   r*   r    r#   r%   rP   )r(   r!   )r(   r!   r.   r/   r:   r0   r1   r   rB   r7   rl   r   r&   r   rm   r2   reshape_bsr_container)rD   r{   rE   ZK1ZK2rF   rG   nrH   rI   bnnzr0   r1   r2   rK   rK   rL   _matmul_sparse  sR    







 





z_bsr_base._matmul_sparsec                 C   s2   |d| j fvr|  j|dS |r*|  S | S dS )a=  Convert this array/matrix into Block Sparse Row Format.

        With copy=False, the data/indices may be shared between this
        array/matrix and the resultant bsr_array/bsr_matrix.

        If blocksize=(R, C) is provided, it will be used for determining
        block size of the bsr_array/bsr_matrix.
        Nr    )r!   tocsrr/   r*   )rD   r!   r*   rK   rK   rL   r/   V  s
    	z_bsr_base.tobsrc                 C   s   | j \}}| j\}}| j}| j| j| jft||d}tj|d |d}tj||d}	tj|t	| j
d}
t|| || ||| jj|dd| jj|dd| j||	|

 | j|
|	|f| j dS )Nr#   r   r%   Fr+   r(   )r(   r!   rT   r:   r0   r1   r;   r7   rl   r   r&   r   rB   r2   Z_csr_container)rD   r*   rE   rF   rG   rH   rT   rI   r0   r1   r2   rK   rK   rL   r   f  s(    

	z_bsr_base.tocsrc                 C   s   | j ddj|dS rx   )r   tocsc)rD   r*   rK   rK   rL   r   }  s    z_bsr_base.tocscc                 C   sT  | j \}}| j\}}t| j}|jjttjjkr\|tj}t	||krXt
d|}| jt||d}|tj|| |d |}	|	|| d||}	|	ttj||dddd|f7 }	|	d}	|| j j|dd|| d||}
|
ttj||d|df7 }
|
d}
| jd}|r<| }| j||	|
ff| j dS )	zConvert this array/matrix to COOrdinate format.

        When copy=False the data array will be shared between
        this array/matrix and the resultant coo_array/coo_matrix.
        zMatrix too big to convertr#   r%   rP   r   Fr+   r   )r(   r!   r7   rV   r0   r&   itemsizeZintprB   anyr6   r:   r;   Zarangerepeatr   Ztiler1   r2   r*   r=   )rD   r*   rE   rF   rG   rH   Zindptr_diffZindptr_diff_limitedrI   rowcolr2   rK   rK   rL   ry     s4    

&

z_bsr_base.tocooc                 C   s   | j ddj||dS )NFr+   )orderout)ry   toarray)rD   r   r   rK   rK   rL   r     s    z_bsr_base.toarrayc                 C   s   |d ur|dkrt d| j\}}| j\}}| j||  }| jdkr`| j||f||f| j|dS tj|| d | jjd}tj|| j	jd}	tj|||f| j
jd}
t|| || ||| j| j	| j
 ||	|
 
 | j|
|	|f||f|dS )N)r   r   zoSparse matrices do not support an 'axes' parameter because swapping dimensions is the only logical permutation.r   )r!   r&   r*   r   r%   )r(   r*   )r6   r!   r(   rT   r   r&   r7   rl   r0   r1   r2   r   rm   )rD   Zaxesr*   rG   rH   rE   rF   ZNBLKr0   r1   r2   rK   rK   rL   	transpose  s&    



z_bsr_base.transposec                 C   s   | j s
dS | j\}}| j\}}| jdkd|| jdd}| d }| j| | jdt|< t	|| || | j
| j| |   dS )zRemove zero elements in-place.Nr   rP   r   )rZ   )rT   r!   r(   r2   r   sumZnonzeror<   r   Zcsr_eliminate_zerosr0   r1   rS   )rD   rG   rH   rE   rF   maskZnonzero_blocksrK   rK   rL   eliminate_zeros  s    

z_bsr_base.eliminate_zerosc                 C   s   | j r
dS |   | j\}}| j\}}|| }d}d}t|D ]}|}	| j|d  }|	|k r| j|	 }
| j|	 }|	d7 }	|	|k r| j|	 |
kr|| j|	 7 }|	d7 }	qx|
| j|< || j|< |d7 }qT|| j|d < q>|   d| _ dS )zqEliminate duplicate array/matrix entries by adding them together

        The is an *in place* operation
        Nr   r   T)	Zhas_canonical_formatsort_indicesr!   r(   ranger0   r1   r2   rS   )rD   rG   rH   rE   rF   Zn_rowrT   Zrow_endrM   Zjjjr]   rK   rK   rL   sum_duplicates  s0    







z_bsr_base.sum_duplicatesc              	   C   sN   | j r
dS | j\}}| j\}}t|| || ||| j| j| j  d| _ dS )z9Sort the indices of this array/matrix *in place*
        NT)Zhas_sorted_indicesr!   r(   r   r0   r1   r2   rm   )rD   rG   rH   rE   rF   rK   rK   rL   r     s    

&z_bsr_base.sort_indicesc                 C   s   | j \}}| j\}}t| j|| d kr2td| jd }t| j|k rRtdt| j|k rhtd| jd| | _| jd| | _dS )z8Remove empty space after all non-zero elements.
        r   z index pointer has invalid lengthrP   z"indices array has too few elementszdata array has too few elementsN)r!   r(   r<   r0   r6   r1   r2   )rD   rG   rH   rE   rF   r   rK   rK   rL   rS     s    


z_bsr_base.prunec                 C   s  | j || jd}tt| j| | j }| j\}}t| jt|j }| j| j| j	|j|j	f|d}	t
j| jj|	d}
t
j||	d}g d}||v rt
j|| | t
jd}n t
j|| | t| j|jd}|| jd | | jd | ||| j|	| j	|	| j|j|	|j	|	t
|j|
|| |
d }|d| }|d|| |  }||d	 k rp| }| }|d||}| j |||
f| jd
S )z5Apply the binary operation fn to two sparse matrices.r    r#   r%   )Z_ne_Z_lt_Z_gt_Z_le_Z_ge_r   r   rP   Nr'   r   )	__class__r!   getattrr   r.   r<   r2   r:   r0   r1   r7   rl   r(   Zbool_r   r&   rB   rm   r*   r   )rD   r{   opZin_shapeZ	out_shapefnrG   rH   Zmax_bnnzrI   r0   r1   Zbool_opsr2   Zactual_bnnzrK   rK   rL   _binopt#  sD    
 




z_bsr_base._binoptc                 C   sL   |r*| j || j | j f| j|jdS | j || j| jf| j|jdS dS )zReturns a matrix with the same sparsity structure as self,
        but with different data.  By default the structure arrays
        (i.e. .indptr and .indices) are copied.
        )r(   r&   N)r   r1   r*   r0   r(   r&   )rD   r2   r*   rK   rK   rL   
_with_dataT  s    z_bsr_base._with_data)NNFN)T)N)r   )NF)F)F)T)NN)NF)NN)T) __name__
__module____qualname___formatr-   rC   propertyr5   r!   r[   r   __doc__rj   rr   ru   rw   rz   r}   r~   r   r/   r   r   ry   r   r   r   r   r   rS   r   r   rK   rK   rK   rL   r      s@   
r
A




8





&



!
1r   c                 C   s
   t | tS )a  Is `x` of a bsr_matrix type?

    Parameters
    ----------
    x
        object to check for being a bsr matrix

    Returns
    -------
    bool
        True if `x` is a bsr matrix, False otherwise

    Examples
    --------
    >>> from scipy.sparse import bsr_array, bsr_matrix, csr_matrix, isspmatrix_bsr
    >>> isspmatrix_bsr(bsr_matrix([[5]]))
    True
    >>> isspmatrix_bsr(bsr_array([[5]]))
    False
    >>> isspmatrix_bsr(csr_matrix([[5]]))
    False
    )r4   r   )r]   rK   rK   rL   r   h  s    r   c                   @   s   e Zd ZdZdS )r   a  
    Block Sparse Row format sparse array.

    This can be instantiated in several ways:
        bsr_array(D, [blocksize=(R,C)])
            where D is a 2-D ndarray.

        bsr_array(S, [blocksize=(R,C)])
            with another sparse array or matrix S (equivalent to S.tobsr())

        bsr_array((M, N), [blocksize=(R,C), dtype])
            to construct an empty sparse array with shape (M, N)
            dtype is optional, defaulting to dtype='d'.

        bsr_array((data, ij), [blocksize=(R,C), shape=(M, N)])
            where ``data`` and ``ij`` satisfy ``a[ij[0, k], ij[1, k]] = data[k]``

        bsr_array((data, indices, indptr), [shape=(M, N)])
            is the standard BSR representation where the block column
            indices for row i are stored in ``indices[indptr[i]:indptr[i+1]]``
            and their corresponding block values are stored in
            ``data[ indptr[i]: indptr[i+1] ]``. If the shape parameter is not
            supplied, the array dimensions are inferred from the index arrays.

    Attributes
    ----------
    dtype : dtype
        Data type of the array
    shape : 2-tuple
        Shape of the array
    ndim : int
        Number of dimensions (this is always 2)
    nnz
    size
    data
        BSR format data array of the array
    indices
        BSR format index array of the array
    indptr
        BSR format index pointer array of the array
    blocksize
        Block size
    has_sorted_indices : bool
        Whether indices are sorted
    has_canonical_format : bool
    T

    Notes
    -----
    Sparse arrays can be used in arithmetic operations: they support
    addition, subtraction, multiplication, division, and matrix power.

    **Summary of BSR format**

    The Block Sparse Row (BSR) format is very similar to the Compressed
    Sparse Row (CSR) format. BSR is appropriate for sparse matrices with dense
    sub matrices like the last example below. Such sparse block matrices often
    arise in vector-valued finite element discretizations. In such cases, BSR is
    considerably more efficient than CSR and CSC for many sparse arithmetic
    operations.

    **Blocksize**

    The blocksize (R,C) must evenly divide the shape of the sparse array (M,N).
    That is, R and C must satisfy the relationship ``M % R = 0`` and
    ``N % C = 0``.

    If no blocksize is specified, a simple heuristic is applied to determine
    an appropriate blocksize.

    **Canonical Format**

    In canonical format, there are no duplicate blocks and indices are sorted
    per row.

    Examples
    --------
    >>> import numpy as np
    >>> from scipy.sparse import bsr_array
    >>> bsr_array((3, 4), dtype=np.int8).toarray()
    array([[0, 0, 0, 0],
           [0, 0, 0, 0],
           [0, 0, 0, 0]], dtype=int8)

    >>> row = np.array([0, 0, 1, 2, 2, 2])
    >>> col = np.array([0, 2, 2, 0, 1, 2])
    >>> data = np.array([1, 2, 3 ,4, 5, 6])
    >>> bsr_array((data, (row, col)), shape=(3, 3)).toarray()
    array([[1, 0, 2],
           [0, 0, 3],
           [4, 5, 6]])

    >>> indptr = np.array([0, 2, 3, 6])
    >>> indices = np.array([0, 2, 2, 0, 1, 2])
    >>> data = np.array([1, 2, 3, 4, 5, 6]).repeat(4).reshape(6, 2, 2)
    >>> bsr_array((data,indices,indptr), shape=(6, 6)).toarray()
    array([[1, 1, 0, 0, 2, 2],
           [1, 1, 0, 0, 2, 2],
           [0, 0, 0, 0, 3, 3],
           [0, 0, 0, 0, 3, 3],
           [4, 4, 5, 5, 6, 6],
           [4, 4, 5, 5, 6, 6]])

    Nr   r   r   r   rK   rK   rK   rL   r     s   r   c                   @   s   e Zd ZdZdS )r   a  
    Block Sparse Row format sparse matrix.

    This can be instantiated in several ways:
        bsr_matrix(D, [blocksize=(R,C)])
            where D is a 2-D ndarray.

        bsr_matrix(S, [blocksize=(R,C)])
            with another sparse array or matrix S (equivalent to S.tobsr())

        bsr_matrix((M, N), [blocksize=(R,C), dtype])
            to construct an empty sparse matrix with shape (M, N)
            dtype is optional, defaulting to dtype='d'.

        bsr_matrix((data, ij), [blocksize=(R,C), shape=(M, N)])
            where ``data`` and ``ij`` satisfy ``a[ij[0, k], ij[1, k]] = data[k]``

        bsr_matrix((data, indices, indptr), [shape=(M, N)])
            is the standard BSR representation where the block column
            indices for row i are stored in ``indices[indptr[i]:indptr[i+1]]``
            and their corresponding block values are stored in
            ``data[ indptr[i]: indptr[i+1] ]``. If the shape parameter is not
            supplied, the matrix dimensions are inferred from the index arrays.

    Attributes
    ----------
    dtype : dtype
        Data type of the matrix
    shape : 2-tuple
        Shape of the matrix
    ndim : int
        Number of dimensions (this is always 2)
    nnz
    size
    data
        BSR format data array of the matrix
    indices
        BSR format index array of the matrix
    indptr
        BSR format index pointer array of the matrix
    blocksize
        Block size
    has_sorted_indices : bool
        Whether indices are sorted
    has_canonical_format : bool
    T

    Notes
    -----
    Sparse matrices can be used in arithmetic operations: they support
    addition, subtraction, multiplication, division, and matrix power.

    **Summary of BSR format**

    The Block Sparse Row (BSR) format is very similar to the Compressed
    Sparse Row (CSR) format. BSR is appropriate for sparse matrices with dense
    sub matrices like the last example below. Such sparse block matrices often
    arise in vector-valued finite element discretizations. In such cases, BSR is
    considerably more efficient than CSR and CSC for many sparse arithmetic
    operations.

    **Blocksize**

    The blocksize (R,C) must evenly divide the shape of the sparse matrix (M,N).
    That is, R and C must satisfy the relationship ``M % R = 0`` and
    ``N % C = 0``.

    If no blocksize is specified, a simple heuristic is applied to determine
    an appropriate blocksize.

    **Canonical Format**

    In canonical format, there are no duplicate blocks and indices are sorted
    per row.

    Examples
    --------
    >>> import numpy as np
    >>> from scipy.sparse import bsr_matrix
    >>> bsr_matrix((3, 4), dtype=np.int8).toarray()
    array([[0, 0, 0, 0],
           [0, 0, 0, 0],
           [0, 0, 0, 0]], dtype=int8)

    >>> row = np.array([0, 0, 1, 2, 2, 2])
    >>> col = np.array([0, 2, 2, 0, 1, 2])
    >>> data = np.array([1, 2, 3 ,4, 5, 6])
    >>> bsr_matrix((data, (row, col)), shape=(3, 3)).toarray()
    array([[1, 0, 2],
           [0, 0, 3],
           [4, 5, 6]])

    >>> indptr = np.array([0, 2, 3, 6])
    >>> indices = np.array([0, 2, 2, 0, 1, 2])
    >>> data = np.array([1, 2, 3, 4, 5, 6]).repeat(4).reshape(6, 2, 2)
    >>> bsr_matrix((data,indices,indptr), shape=(6, 6)).toarray()
    array([[1, 1, 0, 0, 2, 2],
           [1, 1, 0, 0, 2, 2],
           [0, 0, 0, 0, 3, 3],
           [0, 0, 0, 0, 3, 3],
           [4, 4, 5, 5, 6, 6],
           [4, 4, 5, 5, 6, 6]])

    Nr   rK   rK   rK   rL   r     s   r   ))r   __docformat____all__warningsr   numpyr7   Zscipy._lib._utilr   Z_matrixr   _datar	   r
   Z_compressedr   _baser   r   r   r   Z_sputilsr   r   r   r   r   r    r   r   r   r   r   r   r   r   r   r   r   r   rK   rK   rK   rL   <module>   s(    $    Tk