
    _Mh                        d Z ddlZddlmZmZmZmZmZm	Z	m
Z
mZmZ ddlmZ g dZ G d de          Z G d	 d
e          Z G d de          Zi dddgdddgdddgdddgdddgdddgdddgd d!d"gd#d$d%gd&d'd(gd)d*d+gd,d-d.gd/d0d1gd2d3d4gd5d6d7gd8d9d:gd;d<d=gd>d?gd@dAgdBdCgdDZ eej        ej        ej        ej        ej        ej        ej        ej        ej        ej        ej         ej!        ej"        ej#        ej$        ej%        ej&        ej'        g          Z(dEZ) G dF dG          Z* G dH dI          Z+e*j         e+_         dJ Z,dK Z-dS )LzBase class for sparse matrices    N   )	asmatrixcheck_reshape_kwargscheck_shapeget_sum_dtypeisdenseisscalarlikematrixvalidateaxisgetdtype)spmatrix)
isspmatrixissparsesparraySparseWarningSparseEfficiencyWarningc                       e Zd ZdS )r   N__name__
__module____qualname__     R/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/scipy/sparse/_base.pyr   r              Dr   r   c                       e Zd ZdS )SparseFormatWarningNr   r   r   r   r   r      r   r   r   c                       e Zd ZdS )r   Nr   r   r   r   r   r      r   r   r   csczCompressed Sparse ColumncsrzCompressed Sparse Rowdok   zDictionary Of Keyslil   zList of Listsdod   zDictionary of Dictionariessss   zSymmetric Sparse Skylinecoo   
COOrdinatelba   zLinpack BAndedegd   z#Ellpack-itpack Generalized Diagonaldia	   DIAgonalbsr
   zBlock Sparse Rowmsr   zModified compressed Sparse Rowbsc   zBlock Sparse Columnmsc   z!Modified compressed Sparse Columnssk   zSymmetric SKylinensk   zNonsymmetric SKylinejad   zJAgged Diagonal   zUnsymmetric Sparse Skyline   zVariable Block Row   	Undefined)ussvbrund2   c                      e Zd ZdZdZdZdZedefd            Z	ed             Z
ed             Zed	             Zed
             Zed             Zed             Zed             Zed             ZdddZed             Zd Zd ZdtdZed             Zed             Zd Zd Zd ZdudZdudZedefd            Zedefd             Z ede!fd!            Z"ed"             Z#ed#             Z$ed$             Z%d% Z&d& Z'd' Z(e(Z)d( Z*dvd*Z+d+ Z,d, Z-d- Z.d. Z/dud/Z0dvd0Z1d1 Z2d2 Z3d3 Z4d4 Z5d5 Z6d6 Z7d7 Z8dwd9Z9d: Z:d; Z;d< Z<d= Z=d> Z>d? Z?d@ Z@dA ZAdB ZBdC ZCdD ZDdE ZEdF ZFdG ZGdH ZHdI ZIdJ ZJdK ZKdL ZLdxdMZMdN ZNdO ZOdP ZPdQ ZQdR ZRdS ZSdT ZTdU ZUdV ZVdW ZWdX ZXdydYZYdzdZZZdzd[Z[eZj        e[_        d\ Z\d] Z]d^ Z^d_ Z_d` Z`d{daZad{dbZbdvdcZcdvddZddvdeZedvdfZfdvdgZgdydhZhdvdiZidj Zjd|dkZkd|dlZldwdmZmdwdnZndwdoZodp Zpdq Zqd}dsZrdS )~_spbasez This class provides a base class for all sparse arrays.  It
    cannot be instantiated.  Most of the work is provided by subclasses.
    g333333$@rG   )r"   returnc                 *    t          | j                  S N)len_shapeselfs    r   ndimz_spbase.ndimF   s    4;r   c                 N    | j         }t          |          dk    r
d|d         fn|S )Nr   )rO   rN   )rQ   ss     r   _shape_as_2dz_spbase._shape_as_2dJ   s)    K VVq[[1R5zza/r   c                     ddl m} |S )Nr   )	bsr_array)_bsrrX   )rQ   rX   s     r   _bsr_containerz_spbase._bsr_containerO       ######r   c                     ddl m} |S )Nr   )	coo_array)_coor]   )rQ   r]   s     r   _coo_containerz_spbase._coo_containerT   r[   r   c                     ddl m} |S )Nr   )	csc_array)_cscra   )rQ   ra   s     r   _csc_containerz_spbase._csc_containerY   r[   r   c                     ddl m} |S )Nr   )	csr_array)_csrre   )rQ   re   s     r   _csr_containerz_spbase._csr_container^   r[   r   c                     ddl m} |S )Nr   )	dia_array)_diari   )rQ   ri   s     r   _dia_containerz_spbase._dia_containerc   r[   r   c                     ddl m} |S )Nr   )	dok_array)_dokrm   )rQ   rm   s     r   _dok_containerz_spbase._dok_containerh   r[   r   c                     ddl m} |S )Nr   )	lil_array)_lilrq   )rQ   rq   s     r   _lil_containerz_spbase._lil_containerm   r[   r   Nmaxprintc                    d | _         | j        j        dk    rt          d          t	          | t
                    r#t          j        |          rt          d          |t          n|| _	        d S )NrJ   z7This class is not intended to be instantiated directly.zEscipy sparse array classes do not support instantiation from a scalar)
rO   	__class__r   
ValueError
isinstancer   npisscalarMAXPRINTru   )rQ   arg1ru   s      r   __init__z_spbase.__init__r   s~    >"i// = > > >dG$$ 	T):): 	W   %-$4(r   c                     | j         S rM   )rO   rP   s    r   shapez_spbase.shape}   s
    {r   c                    t          || j        t          dd                    }t          |          \  }}|| j        k    r|r|                                 S | S |                     |                              ||d          S )a  reshape(self, shape, order='C', copy=False)

        Gives a new shape to a sparse array/matrix without changing its data.

        Parameters
        ----------
        shape : length-2 tuple of ints
            The new shape should be compatible with the original shape.
        order : {'C', 'F'}, optional
            Read the elements using this index order. 'C' means to read and
            write the elements using C-like index order; e.g., read entire first
            row, then second row, etc. 'F' means to read and write the elements
            using Fortran-like index order; e.g., read entire first column, then
            second column, etc.
        copy : bool, optional
            Indicates whether or not attributes of self should be copied
            whenever possible. The degree to which attributes are copied varies
            depending on the type of sparse array being used.

        Returns
        -------
        reshaped : sparse array/matrix
            A sparse array/matrix with the given `shape`, not necessarily of the same
            format as the current object.

        See Also
        --------
        numpy.reshape : NumPy's implementation of 'reshape' for ndarrays
        r   A   )allow_ndcopyF)orderr   )r   r   ranger   r   tocooreshape)rQ   argskwargsr   r   r   s         r   r   z_spbase.reshape   s    B D$*uQ||DDD*622tDJ yy{{"zztz$$,,U%e,LLLr   c                 J    t          t          |           j         d          )a  Resize the array/matrix in-place to dimensions given by ``shape``

        Any elements that lie within the new shape will remain at the same
        indices, while non-zero elements lying outside the new shape are
        removed.

        Parameters
        ----------
        shape : (int, int)
            number of rows and columns in the new array/matrix

        Notes
        -----
        The semantics are not identical to `numpy.ndarray.resize` or
        `numpy.resize`. Here, the same data will be maintained at each index
        before and after reshape, if that index is within the new bounds. In
        numpy, resizing maintains contiguity of the array, moving elements
        around in the logical array but not within a flattened representation.

        We give no guarantees about whether the underlying data attributes
        (arrays, etc.) will be modified in place or replaced with new objects.
        z.resize is not implemented)NotImplementedErrortyper   )rQ   r   s     r   resizez_spbase.resize   s.    0 "Dzz">>>@ @ 	@r   unsafeTc                     t          |          }| j        |k    rB|                                                     |||                              | j                  S |r|                                 S | S )a  Cast the array/matrix elements to a specified type.

        Parameters
        ----------
        dtype : string or numpy dtype
            Typecode or data-type to which to cast the data.
        casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
            Controls what kind of data casting may occur.
            Defaults to 'unsafe' for backwards compatibility.
            'no' means the data types should not be cast at all.
            'equiv' means only byte-order changes are allowed.
            'safe' means only casts which can preserve values are allowed.
            'same_kind' means only safe casts or casts within a kind,
            like float64 to float32, are allowed.
            'unsafe' means any data conversions may be done.
        copy : bool, optional
            If `copy` is `False`, the result might share some memory with this
            array/matrix. If `copy` is `True`, it is guaranteed that the result and
            this array/matrix do not share any memory.
        )castingr   )r   dtypetocsrastypeasformatformatr   )rQ   r   r   r   s       r   r   z_spbase.astype   ss    , :::<<&&wT ' 3 33;8DK3H3HI 	99;;Kr   c                 j    t          | t                    rt          j        |fi |S t	          |fi |S rM   )
issubclassr   rz   asarrayr   clsXr   s      r   _ascontainerz_spbase._ascontainer   sB    c7## 	):a**6***A(((((r   c                 j    t          | t                    rt          j        |fi |S t	          |fi |S rM   )r   r   rz   arrayr
   r   s      r   
_containerz_spbase._container   sB    c7## 	'8A(((((!&&v&&&r   c                     g d}| j         j        |v r| S |D ]6}| j         t          j         |          k    r|                     |          c S 7t	          d| j         j         d          )z6Upcast array to a floating point format (if necessary))fdFDzcannot upcast [z] to a floating point format)r   charrz   r   	TypeErrorname)rQ   fp_typesfp_types      r   	_asfptypez_spbase._asfptype   s     ('':?h&&K# 0 0:'!2!222;;w///// 3 O$*/OOO  r   c              #   X   K   t          | j        d                   D ]}| |         V  d S )Nr   )r   r   )rQ   rs     r   __iter__z_spbase.__iter__  s<      tz!}%% 	 	Aq'MMMM	 	r   c                     | j         S )z3Maximum number of elements to display when printed.rt   rP   s    r   _getmaxprintz_spbase._getmaxprint  s
    }r   c                 @    | j         j        }t          d| d          )a  Number of non-zero entries, equivalent to

        np.count_nonzero(a.toarray(), axis=axis)

        Unlike the nnz property, which return the number of stored
        entries (the length of the data attribute), this method counts the
        actual number of non-zero entries in data.

        Duplicate entries are summed before counting.

        Parameters
        ----------
        axis : {-2, -1, 0, 1, None} optional
            Count nonzeros for the whole array, or along a specified axis.

            .. versionadded:: 1.15.0

        Returns
        -------
        numpy array
            A reduced array (no axis `axis`) holding the number of nonzero values
            for each of the indices of the nonaxis dimensions.

        Notes
        -----
        If you want to count nonzero and explicit zero stored values (e.g. nnz)
        along an axis, two fast idioms are provided by `numpy` functions for the
        common CSR, CSC, COO formats.

        For the major axis in CSR (rows) and CSC (cols) use `np.diff`:

            >>> import numpy as np
            >>> import scipy as sp
            >>> A = sp.sparse.csr_array([[4, 5, 0], [7, 0, 0]])
            >>> major_axis_stored_values = np.diff(A.indptr)  # -> np.array([2, 1])

        For the minor axis in CSR (cols) and CSC (rows) use `numpy.bincount` with
        minlength ``A.shape[1]`` for CSR and ``A.shape[0]`` for CSC:

            >>> csr_minor_stored_values = np.bincount(A.indices, minlength=A.shape[1])

        For COO, use the minor axis approach for either `axis`:

            >>> A = A.tocoo()
            >>> coo_axis0_stored_values = np.bincount(A.coords[0], minlength=A.shape[1])
            >>> coo_axis1_stored_values = np.bincount(A.coords[1], minlength=A.shape[0])

        Examples
        --------

            >>> A = sp.sparse.csr_array([[4, 5, 0], [7, 0, 0]])
            >>> A.count_nonzero(axis=0)
            array([2, 1, 0])
        z"count_nonzero not implemented for .rw   r   r   rQ   axisclsnames      r   count_nonzeroz_spbase.count_nonzero  s)    n .)!"Qw"Q"Q"QRRRr   c                 @    | j         j        }t          d| d          )a6  Number of stored values, including explicit zeros.

        Parameters
        ----------
        axis : {-2, -1, 0, 1, None} optional
            Report stored values for the whole array, or along a specified axis.

        See also
        --------
        count_nonzero : Number of non-zero entries
        zgetnnz not implemented for r   r   r   s      r   _getnnzz_spbase._getnnzF  s(     .)!"J"J"J"JKKKr   c                 *    |                                  S )zNumber of stored values, including explicit zeros.

        See also
        --------
        count_nonzero : Number of non-zero entries
        r   rP   s    r   nnzz_spbase.nnzU       ||~~r   c                 *    |                                  S )zwNumber of stored values.

        See also
        --------
        count_nonzero : Number of non-zero values.
        r   rP   s    r   sizez_spbase.size_  r   r   c                     | j         S )zFormat string for matrix.)_formatrP   s    r   r   z_spbase.formati  s     |r   c                 *    |                                  S )z
Transpose.)	transposerP   s    r   Tz	_spbase.Tn  s     ~~r   c                 *    |                                  S rM   )_realrP   s    r   realz_spbase.reals      zz||r   c                 *    |                                  S rM   )_imagrP   s    r   imagz_spbase.imagw  r   r   c                     t           | j                 \  }}t          | t                    rdnd}d| d| d| j         d| j         d| j         dS )	Nr   r
   <z sparse z of dtype 'z'
	with z stored elements and shape >)_formatsr   ry   r   r   r   r   )rQ   _format_name
sparse_clss       r   __repr__z_spbase.__repr__{  s    !$+.; *4 9 9GWWx
I I IZ I IDJ I IhI I;?:I I I	
r   c                    |                                  }|                                 }d }t          |           }| j        dk    r|S |dz  }| j        |k    r|dz  | |t	          fd|j        D                       |j        d                    z  }|dz  }|z
  | |t	          fd|j        D                       |j         d                    z  }n| ||j        |j                  z  }|S )Nc                     t          t          d | D              |          }d                    d |D                       S )Nc              3   >   K   | ]}|                                 V  d S rM   )tolist).0cs     r   	<genexpr>z1_spbase.__str__.<locals>.tostr.<locals>.<genexpr>  s*      99Qahhjj999999r   
c              3   ,   K   | ]\  }}d | d| V  dS )z  	Nr   )r   idxvals      r   r   z1_spbase.__str__.<locals>.tostr.<locals>.<genexpr>  s7      EE83.#....EEEEEEr   )zipjoin)coordsdatapairss      r   tostrz_spbase.__str__.<locals>.tostr  sF    99&999:DAAE99EEuEEEEEEr   r   z
  Coords	Values
r"   c              3   ,   K   | ]}|d          V  d S rM   r   r   r   halfs     r   r   z"_spbase.__str__.<locals>.<genexpr>  s+      ::Aq$x::::::r   z
  :	:
c              3   .   K   | ]}| d          V  d S rM   r   r   s     r   r   z"_spbase.__str__.<locals>.<genexpr>  s-      ;;Qq$y;;;;;;r   )r   r   reprr   tupler   r   )rQ   ru   Ar   outr   s        @r   __str__z_spbase.__str__  s%   $$&&JJLL	F 	F 	F 4jj8q==J%%8hq=D55:::::::::AF5D5MJJJC<Cd?D55;;;;!(;;;;;QVTEFF^LLLCC5516***C
r   c                 L    | j         dk    r| j        dk    S t          d          )N)r   r   r   z\The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().)r   r   rx   rP   s    r   __bool__z_spbase.__bool__  s6    :8q=  M N N Nr   c                      t          d          )Nz:sparse array length is ambiguous; use getnnz() or shape[0])r   rP   s    r   __len__z_spbase.__len__  s     ' ( ( 	(r   Fc                    ||| j         k    r|r|                                 S | S 	 t          | d|z             }n&# t          $ r}t	          d| d          |d}~ww xY w	  ||          S # t
          $ r  |            cY S w xY w)a  Return this array/matrix in the passed format.

        Parameters
        ----------
        format : {str, None}
            The desired sparse format ("csr", "csc", "lil", "dok", "array", ...)
            or None for no conversion.
        copy : bool, optional
            If True, the result is guaranteed to not share data with self.

        Returns
        -------
        A : This array/matrix in the passed format.
        NtozFormat z is unknown.r   )r   r   getattrAttributeErrorrx   r   )rQ   r   r   convert_methodes        r   r   z_spbase.asformat  s     >Vt{22 yy{{"H!(tf}!=!=! H H H !?6!?!?!?@@aGH(%~40000 ( ( (%~'''''(s'   ; 
AAA"A. .BBc                     t          |          r|                     |          S |                                                     |          S )z2Point-wise multiplication by another array/matrix.)r	   _mul_scalarr   multiplyrQ   others     r   r   z_spbase.multiply  sB     	+##E***zz||$$U+++r   c                 P    |                                                      |          S )z;Element-wise maximum between this and another array/matrix.)r   maximumr   s     r   r   z_spbase.maximum      zz||##E***r   c                 P    |                                                      |          S )z;Element-wise minimum between this and another array/matrix.)r   minimumr   s     r   r  z_spbase.minimum  r  r   c                 >    t          j        |          r| |z  S | |z  S )a/  Ordinary dot product

        Examples
        --------
        >>> import numpy as np
        >>> from scipy.sparse import csr_array
        >>> A = csr_array([[1, 2, 0], [0, 0, 3], [4, 0, 5]])
        >>> v = np.array([1, 0, -1])
        >>> A.dot(v)
        array([ 1, -3, -1], dtype=int64)

        )rz   r{   r   s     r   dotz_spbase.dot  s*     ;u 	 %<%<r   c                 T    |                                                      ||          S )zElement-wise power.r   )r   power)rQ   nr   s      r   r  z_spbase.power  s#    zz||!!!5!111r   c                     | j         |k    r|r|                                 n| S |                                                     ||          S rM   )r   r   r   _broadcast_to)rQ   r   r   s      r   r  z_spbase._broadcast_to  sD    :"&0499;;;D0::<<--eT:::r   c                 P    |                                                      |          S rM   )r   __eq__r   s     r   r  z_spbase.__eq__      zz||""5)))r   c                 P    |                                                      |          S rM   )r   __ne__r   s     r   r  z_spbase.__ne__   r  r   c                 P    |                                                      |          S rM   )r   __lt__r   s     r   r  z_spbase.__lt__  r  r   c                 P    |                                                      |          S rM   )r   __gt__r   s     r   r  z_spbase.__gt__  r  r   c                 P    |                                                      |          S rM   )r   __le__r   s     r   r  z_spbase.__le__	  r  r   c                 P    |                                                      |          S rM   )r   __ge__r   s     r   r  z_spbase.__ge__  r  r   c                 D    t          |                                           S rM   )absr   rP   s    r   __abs__z_spbase.__abs__  s    4::<<   r   r   c                 H    t          |                                 |          S )N)ndigits)roundr   )rQ   r  s     r   	__round__z_spbase.__round__  s    TZZ\\73333r   c                 P    |                                                      |          S rM   )r   _add_sparser   s     r   r!  z_spbase._add_sparse      zz||''...r   c                 P    |                                                      |          S rM   )r   
_add_denser   s     r   r$  z_spbase._add_dense  s    zz||&&u---r   c                 P    |                                                      |          S rM   )r   _sub_sparser   s     r   r&  z_spbase._sub_sparse  r"  r   c                 0    |                                  |z
  S rM   todenser   s     r   
_sub_densez_spbase._sub_dense  s    ||~~%%r   c                 0    ||                                  z
  S rM   r(  r   s     r   _rsub_densez_spbase._rsub_dense!  s    t||~~%%r   c                    t          |          r)|dk    r|                                 S t          d          t          |          r4|j        | j        k    rt          d          |                     |          S t          |          r/t          j	        || j                  }| 
                    |          S t          S )Nr   z:adding a nonzero scalar to a sparse array is not supportedinconsistent shapes)r	   r   r   r   r   rx   r!  r   rz   broadcast_tor$  NotImplementedr   s     r   __add__z_spbase.__add__%  s     	"zzyy{{"% 'F G G Ge__ 	"{dj(( !6777##E***U^^ 	"OE4:66E??5)))!!r   c                 ,    |                      |          S rM   )r1  r   s     r   __radd__z_spbase.__radd__6  s    ||E"""r   c                    t          |          r)|dk    r|                                 S t          d          t          |          r4|j        | j        k    rt          d          |                     |          S t          |          r/t          j	        || j                  }| 
                    |          S t          S )Nr   zAsubtracting a nonzero scalar from a sparse array is not supportedr.  )r	   r   r   r   r   rx   r&  r   rz   r/  r*  r0  r   s     r   __sub__z_spbase.__sub__9  s     	"zzyy{{"% 'F G G Ge__ 	"{dj(( !6777##E***U^^ 	"OE4:66E??5)))!!r   c                     t          |          r*|dk    r|                                  S t          d          t          |          r/t	          j        || j                  }|                     |          S t          S )Nr   zAsubtracting a sparse array from a nonzero scalar is not supported)	r	   r   r   r   rz   r/  r   r,  r0  r   s     r   __rsub__z_spbase.__rsub__I  s     		"zz		|#% 'H I I IU^^ 	"OE4:66E##E***!!r   c                    | j         \  }}|j        t          j        u r|j        |fk    r|                     |          S |j        |dfk    r]|                     |                                          }| j        dk    r|                    d          S |                    |d          S |j        dk    r&|j        d         |k    r| 	                    |          S t          |          r|                     |          S d}t          |          rI||j        d         k    r#t          | d| d|j        d          d          |                     |          S t          j        |          }|j        dk    r|j        t          j        k    rt$          S 	 |j         n# t&          $ r |}Y nw xY w|j        dk    s|j        dk    r|j        d         dk    r|j        d         |k    r#t          | d| d|j        d          d          |                     t          j        |                    }t)          |t          j                  r|                     |          }|j        dk    rH|j        d         dk    r7| j        dk    r|                    d          }n|                    d	d          }|S |j        dk    r|j        d         |k    r#t          | d| d|j        d          d          | 	                    t          j        |                    }t)          |t          j                  r|                     |          }|S t          d
          )a  np.array-like matmul & `np.matrix`-like mul, i.e. `dot` or `NotImplemented`

        interpret other and call one of the following
        self._mul_scalar()
        self._matmul_vector()
        self._matmul_multivector()
        self._matmul_sparse()
        r   r"   r   z)matmul: dimension mismatch with signaturez (n,k=z),(k=z
,m)->(n,m)z,1?)->(n,1?)rT   zcould not interpret dimensions)rV   rw   rz   ndarrayr   _matmul_vectorravelrR   r   _matmul_multivectorr	   r   r   rx   _matmul_sparse
asanyarrayr   object_r0  r   ry   r
   r   r   )rQ   r   MNresult
err_prefixother_as          r   _matmul_dispatchz_spbase._matmul_dispatchU  su     1?bj(({qd""**5111A&&,,U[[]];;9>>!>>!,,,~~a+++qU[^q%8%8//666 	+##E***@
E?? 	.EKN"" !KKKKQKKK   &&u--- -&&<1"*!<!< "!	KKK 	 	 	EEE	 :??ejAoo%+a.A2E2E{1~"" !MMMMQMMM   ((%99F%++ 3**622zQ5;q>Q#6#69>>#^^A..FF#^^B22FMZ1__ {1~"" !KKKKQKKK   --bj.?.?@@F%++ 3**622M =>>>s   F F+*F+c                 ,    |                      |          S rM   r   r   s     r   __mul__z_spbase.__mul__      }}U###r   c                 ,    |                      |          S rM   rG  r   s     r   __rmul__z_spbase.__rmul__  rI  r   c                 P    |                                                      |          S rM   )r   r   r   s     r   r   z_spbase._mul_scalar  r"  r   c                 P    |                                                      |          S rM   )r   r:  r   s     r   r:  z_spbase._matmul_vector      zz||**5111r   c                 P    |                                                      |          S rM   )r   r<  r   s     r   r<  z_spbase._matmul_multivector  s    zz||//666r   c                 P    |                                                      |          S rM   )r   r=  r   s     r   r=  z_spbase._matmul_sparse  rN  r   c                 x   t          |          r|                     |          S 	 |                                }n6# t          $ r) t	          j        |                                          }Y nw xY w|                                                     |          }|t          u rt          S |                                S rM   )r	   r   r   r   rz   r   rE  r0  )rQ   r   trrets       r   _rmatmul_dispatchz_spbase._rmatmul_dispatch  s     	###E***3__&&! 3 3 3Z&&00223..""33B77Cn$$%%==??"s   ; 0A.-A.c                 h    t          |          rt          d          |                     |          S Nz0Scalar operands are not allowed, use '*' instead)r	   rx   rE  r   s     r   
__matmul__z_spbase.__matmul__  s=     	0 / 0 0 0$$U+++r   c                 h    t          |          rt          d          |                     |          S rV  )r	   rx   rT  r   s     r   __rmatmul__z_spbase.__rmatmul__  s=     	0 / 0 0 0%%e,,,r   c                 D   t          |          r=|rP|r't          j        ||                                           S t          j        ||                                           S |rYt          j        | j        t          j                  r5|                     t          j                  	                    d|z            S | 	                    d|z            }t          j
        |          j        }t          j        | j        t          j                  r9t          j        |t          j                  r|                    | j                  S |S t          |          r|sB|rt          j        d|          }nt          j        d|          }|                     |          S |r't          j        ||                                           S t          j        ||                                           S t          |          r|r|                    | |d          S |                                 }|rVt          j        | j        t          j                  r2|                    t          j                                      |          S |                    |          S t&          S )N      ?F)rdivide)r	   rz   true_divider)  dividecan_castr   float64r   r   r   
issubdtypeintegerr   r   r   _divider   _divide_sparser0  )rQ   r   r]  r\  r   scalar_dtyperecipself_csrs           r   rc  z_spbase._divide  s2    )	" < <>%@@@9UDLLNN;;; 
r{4:rzBB 
{{2:..::2e8DDD$$RX..!z%006M$*bj99 lBJ??88DJ///HU^^ 	" 
< 1N2u55EEIb%00E}}U+++ <>%@@@9UDLLNN;;;e__ 
	" G}}T;}FFFzz||H 6r{4:rzBB 6rz22AA%HHH..u555!!r   c                 0    |                      |d          S NT)r]  rc  r   s     r   __truediv__z_spbase.__truediv__  s    ||Et|444r   c                 0    |                      |d          S ri  rj  r   s     r   __div__z_spbase.__div__  s    ||Et|444r   c                     t           S rM   r0  r   s     r   __rtruediv__z_spbase.__rtruediv__      r   c                     t           S rM   ro  r   s     r   __rdiv__z_spbase.__rdiv__  rq  r   c                 ,    |                                   S rM   )r   rP   s    r   __neg__z_spbase.__neg__#  s    

}r   c                     t           S rM   ro  r   s     r   __iadd__z_spbase.__iadd__&      r   c                     t           S rM   ro  r   s     r   __isub__z_spbase.__isub__)  rx  r   c                     t           S rM   ro  r   s     r   __imul__z_spbase.__imul__,  rx  r   c                 ,    |                      |          S rM   )__itruediv__r   s     r   __idiv__z_spbase.__idiv__/  s      '''r   c                     t           S rM   ro  r   s     r   r~  z_spbase.__itruediv__2  rx  r   c                      | j         |i |S rM   )r  )rQ   r   r   s      r   __pow__z_spbase.__pow__5  s    tz4*6***r   c                 X    |                      |                              |d          S )a  
        Reverses the dimensions of the sparse array/matrix.

        Parameters
        ----------
        axes : None, optional
            This argument is in the signature *solely* for NumPy
            compatibility reasons. Do not pass in anything except
            for the default value.
        copy : bool, optional
            Indicates whether or not attributes of `self` should be
            copied whenever possible. The degree to which attributes
            are copied varies depending on the type of sparse array/matrix
            being used.

        Returns
        -------
        p : `self` with the dimensions reversed.

        Notes
        -----
        If `self` is a `csr_array` or a `csc_array`, then this will return a
        `csc_array` or a `csr_array`, respectively.

        See Also
        --------
        numpy.transpose : NumPy's implementation of 'transpose' for ndarrays
        r   F)axesr   )r   r   )rQ   r  r   s      r   r   z_spbase.transpose8  s+    : zztz$$..Du.EEEr   c                     t          j        | j        t           j                  r*|                     |                              d          S |r|                                 S | S )a  Element-wise complex conjugation.

        If the array/matrix is of non-complex data type and `copy` is False,
        this method does nothing and the data is not copied.

        Parameters
        ----------
        copy : bool, optional
            If True, the result is guaranteed to not share data with self.

        Returns
        -------
        A : The element-wise complex conjugate.

        r   F)rz   ra  r   complexfloatingr   	conjugater   rQ   r   s     r   r  z_spbase.conjugateW  s]      =R%788 	::4:((222>>> 	99;;Kr   c                 .    |                      |          S )Nr   )r  r  s     r   conjz_spbase.conjn  s    ~~4~(((r   c                 N    |                                                                  S rM   )r   r   rP   s    r   r   z_spbase._reals      zz||!!###r   c                 N    |                                                                  S rM   )r   r   rP   s    r   r   z_spbase._imagv  r  r   c                     |                                  }|j        dk    t          fd|j        D                       S )a  Nonzero indices of the array/matrix.

        Returns a tuple of arrays (row,col) containing the indices
        of the non-zero elements of the array.

        Examples
        --------
        >>> from scipy.sparse import csr_array
        >>> A = csr_array([[1, 2, 0], [0, 0, 3], [4, 0, 5]])
        >>> A.nonzero()
        (array([0, 0, 1, 2, 2], dtype=int32), array([0, 1, 2, 0, 2], dtype=int32))

        r   c              3   (   K   | ]}|         V  d S rM   r   )r   r   nz_masks     r   r   z"_spbase.nonzero.<locals>.<genexpr>  s'      66cS\666666r   )r   r   r   r   )rQ   r   r  s     @r   nonzeroz_spbase.nonzeroy  sB      JJLL&A+6666QX666666r   c                     | j         dk    rt          d          | j        d         }|dk     r||z  }|dk     s||k    rt          d          |                     dg|gdggf|df| j                  }| |z  }|S )zeReturns a copy of column j of the array, as an (m x 1) sparse
        array (column vector).
        r   z4getcol not provided for 1d arrays. Use indexing A[j]rT   r   index out of boundsr   r   )rR   rx   r   
IndexErrorrc   r   )rQ   jrA  col_selectorrB  s        r   _getcolz_spbase._getcol  s     9>>STTT JrNq55FAq55AFF2333**QC1#s+<23Qtz + K K$r   c                     | j         dk    rt          d          | j        d         }|dk     r||z  }|dk     s||k    rt          d          |                     dgdg|ggfd|f| j                  }|| z  S )z^Returns a copy of row i of the array, as a (1 x n) sparse
        array (row vector).
        r   z$getrow not meaningful for a 1d arrayr   r  r  )rR   rx   r   r  rg   r   )rQ   ir@  row_selectors       r   _getrowz_spbase._getrow  s     9>>CDDD JqMq55FAq55AFF2333**QC1#s+<23Qtz + K Kd""r   c                 V    |                      |                     ||                    S )a6  
        Return a dense representation of this sparse array.

        Parameters
        ----------
        order : {'C', 'F'}, optional
            Whether to store multi-dimensional data in C (row-major)
            or Fortran (column-major) order in memory. The default
            is 'None', which provides no ordering guarantees.
            Cannot be specified in conjunction with the `out`
            argument.

        out : ndarray, 2-D, optional
            If specified, uses this array as the output buffer
            instead of allocating a new array to return. The
            provided array must have the same shape and dtype as
            the sparse array on which you are calling the method.

        Returns
        -------
        arr : ndarray, 2-D
            An array with the same shape and containing the same
            data represented by the sparse array, with the requested
            memory order. If `out` was passed, the same object is
            returned after being modified in-place to contain the
            appropriate values.
        r   r   )r   toarrayrQ   r   r   s      r   r)  z_spbase.todense  s(    8   Es!C!CDDDr   c                 X    |                      d                              ||          S )a  
        Return a dense ndarray representation of this sparse array/matrix.

        Parameters
        ----------
        order : {'C', 'F'}, optional
            Whether to store multidimensional data in C (row-major)
            or Fortran (column-major) order in memory. The default
            is 'None', which provides no ordering guarantees.
            Cannot be specified in conjunction with the `out`
            argument.

        out : ndarray, 2-D, optional
            If specified, uses this array as the output buffer
            instead of allocating a new array to return. The provided
            array must have the same shape and dtype as the sparse
            array/matrix on which you are calling the method. For most
            sparse types, `out` is required to be memory contiguous
            (either C or Fortran ordered).

        Returns
        -------
        arr : ndarray, 2-D
            An array with the same shape and containing the same
            data represented by the sparse array/matrix, with the requested
            memory order. If `out` was passed, the same object is
            returned after being modified in-place to contain the
            appropriate values.
        Fr   r  )r   r  r  s      r   r  z_spbase.toarray  s+    < zzuz%%--Es-CCCr   c                 V    |                      |                              d          S )zConvert this array/matrix to Compressed Sparse Row format.

        With copy=False, the data/indices may be shared between this array/matrix and
        the resultant csr_array/matrix.
        r   F)r   r   r  s     r   r   z_spbase.tocsr  )     zztz$$***666r   c                 V    |                      |                              d          S )zConvert this array/matrix to Dictionary Of Keys format.

        With copy=False, the data/indices may be shared between this array/matrix and
        the resultant dok_array/matrix.
        r   F)r   todokr  s     r   r  z_spbase.todok  r  r   c                 V    |                      d                              |          S )zConvert this array/matrix to COOrdinate format.

        With copy=False, the data/indices may be shared between this array/matrix and
        the resultant coo_array/matrix.
        Fr   )r   r   r  s     r   r   z_spbase.tocoo  )     zzuz%%+++666r   c                 V    |                      d                              |          S )zConvert this array/matrix to List of Lists format.

        With copy=False, the data/indices may be shared between this array/matrix and
        the resultant lil_array/matrix.
        Fr   )r   tolilr  s     r   r  z_spbase.tolil  r  r   c                 V    |                      |                              d          S )zConvert this array/matrix to sparse DIAgonal format.

        With copy=False, the data/indices may be shared between this array/matrix and
        the resultant dia_array/matrix.
        r   F)r   todiar  s     r   r  z_spbase.todia'  r  r   c                 X    |                      d                              ||          S )a+  Convert this array/matrix to Block Sparse Row format.

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

        When blocksize=(R, C) is provided, it will be used for construction of
        the bsr_array/matrix.
        Fr   )	blocksizer   )r   tobsr)rQ   r  r   s      r   r  z_spbase.tobsr/  s+     zzuz%%++id+KKKr   c                 V    |                      |                              d          S )zConvert this array/matrix to Compressed Sparse Column format.

        With copy=False, the data/indices may be shared between this array/matrix and
        the resultant csc_array/matrix.
        r   F)r   tocscr  s     r   r  z_spbase.tocsc:  r  r   c                 0    |                      | d          S )zReturns a copy of this array/matrix.

        No data/indices will be shared between the returned value and current
        array/matrix.
        Tr   )rw   rP   s    r   r   z_spbase.copyB  s     ~~d~...r   c                    t          |           t          | j                  }| j        dk    rH|dvrt	          d          | t          j        | j        |          z  }|                    ||          S | j        \  }}|C| | 	                    t          j        |df|                    z                      ||          S |dk     r|dz  }|dk    r/| 	                    t          j        d|f|                    | z  }n.| | 	                    t          j        |df|                    z  }|                    |||	          S )
a  
        Sum the array/matrix elements over a given axis.

        Parameters
        ----------
        axis : {-2, -1, 0, 1, None} optional
            Axis along which the sum is computed. The default is to
            compute the sum of all the array/matrix elements, returning a scalar
            (i.e., `axis` = `None`).
        dtype : dtype, optional
            The type of the returned array/matrix and of the accumulator in which
            the elements are summed.  The dtype of `a` is used by default
            unless `a` has an integer dtype of less precision than the default
            platform integer.  In that case, if `a` is signed then the platform
            integer is used while if `a` is unsigned then an unsigned integer
            of the same precision as the platform integer is used.

            .. versionadded:: 0.18.0

        out : np.matrix, optional
            Alternative output matrix in which to place the result. It must
            have the same shape as the expected output, but the type of the
            output values will be cast if necessary.

            .. versionadded:: 0.18.0

        Returns
        -------
        sum_along_axis : np.matrix
            A matrix with the same shape as `self`, with the specified
            axis removed.

        See Also
        --------
        numpy.matrix.sum : NumPy's implementation of 'sum' for matrices

        r   NrT   r   axis must be None, -1 or 0r  r   r   Nr   r"   r   r   r   )
r   r   r   rR   rx   rz   onesr   sumr   )	rQ   r   r   r   	res_dtyperesr@  rA  rS  s	            r   r  z_spbase.sumJ  so   L 	T "$*--	9>>=(( !=>>>9====C77C7000
 z1< t((!Qy)I)I)IJJJc3c''( !88AID 199##Ai000 CC
 **Ai000  C wwD3w777r   c                     t          |           | j        j        }t          j        | j        t          j                  p#t          j        | j        t          j                  }||rt          j        }nt          j        |          j        }|rt          j        n|}|                     |          }| j	        dk    r:|dvrt          d          || j        d         z  }|                    ||          S |3|| j        d         | j        d         z  z                      ||          S |dk     r|dz  }|dk    r)|d	| j        d         z  z                      d||
          S |d	| j        d         z  z                      d||
          S )a  
        Compute the arithmetic mean along the specified axis.

        Returns the average of the array/matrix elements. The average is taken
        over all elements in the array/matrix by default, otherwise over the
        specified axis. `float64` intermediate and return values are used
        for integer inputs.

        Parameters
        ----------
        axis : {-2, -1, 0, 1, None} optional
            Axis along which the mean is computed. The default is to compute
            the mean of all elements in the array/matrix (i.e., `axis` = `None`).
        dtype : data-type, optional
            Type to use in computing the mean. For integer inputs, the default
            is `float64`; for floating point inputs, it is the same as the
            input dtype.

            .. versionadded:: 0.18.0

        out : np.matrix, optional
            Alternative output matrix in which to place the result. It must
            have the same shape as the expected output, but the type of the
            output values will be cast if necessary.

            .. versionadded:: 0.18.0

        Returns
        -------
        m : np.matrix

        See Also
        --------
        numpy.matrix.mean : NumPy's implementation of 'mean' for matrices

        Nr   r  r  rT   r  r   r"   r[  r  )r   r   r   rz   ra  rb  bool_r`  r   rR   rx   r   r  )	rQ   r   r   r   r  integralinter_dtype
inter_selfr  s	            r   meanz_spbase.mean  s   J 	TJO	M$*bj99 8M$*bh77 	 = 'J	,I %-;bjj)[[--
9>>=(( !=>>>tz"~-C777444<$*Q-$*Q-"?@9#../ !88AID 199#
1"56;;iS < 2 2 2 #
1"56;;iS < 2 2 2r   c                 R    |                                                      |          S )aX  Returns the kth diagonal of the array/matrix.

        Parameters
        ----------
        k : int, optional
            Which diagonal to get, corresponding to elements a[i, i+k].
            Default: 0 (the main diagonal).

            .. versionadded:: 1.0

        See also
        --------
        numpy.diagonal : Equivalent numpy function.

        Examples
        --------
        >>> from scipy.sparse import csr_array
        >>> A = csr_array([[1, 2, 0], [0, 0, 3], [4, 0, 5]])
        >>> A.diagonal()
        array([1, 0, 5])
        >>> A.diagonal(k=1)
        array([2, 3])
        k)r   diagonal)rQ   r  s     r   r  z_spbase.diagonal  s#    0 zz||$$q$)))r   c                 R    |                      |                                          S )a  Returns the sum along diagonals of the sparse array/matrix.

        Parameters
        ----------
        offset : int, optional
            Which diagonal to get, corresponding to elements a[i, i+offset].
            Default: 0 (the main diagonal).

        r  )r  r  )rQ   offsets     r   tracez_spbase.trace  s$     }}v}&&**,,,r   c                     | j         \  }}|dk    r||k    s|dk     r| |k    rt          d          |                     t          j        |          |           dS )a  
        Set diagonal or off-diagonal elements of the array/matrix.

        Parameters
        ----------
        values : array_like
            New values of the diagonal elements.

            Values may have any length. If the diagonal is longer than values,
            then the remaining diagonal entries will not be set. If values are
            longer than the diagonal, then the remaining values are ignored.

            If a scalar value is given, all of the diagonal is set to it.

        k : int, optional
            Which off-diagonal to set, corresponding to elements a[i,i+k].
            Default: 0 (the main diagonal).

        r   zk exceeds array dimensionsN)r   rx   _setdiagrz   r   )rQ   valuesr  r@  rA  s        r   setdiagz_spbase.setdiag  se    ( z1EEa1ff!a%%QB!GG9:::bj((!,,,,,r   c                 Z   | j         \  }}|dk     r|j        dk    r1t          ||z   |          }t          |          D ]}|| ||z
  |f<   dS t          ||z   |t	          |                    }|dk    rdS t          |d|                   D ]\  }}|| ||z
  |f<   dS |j        dk    r1t          |||z
            }t          |          D ]}|| |||z   f<   dS t          |||z
  t	          |                    }|dk    rdS t          |d|                   D ]\  }}|| |||z   f<   dS )zZThis part of the implementation gets overridden by the
        different formats.
        r   N)r   rR   minr   rN   	enumerate)rQ   r  r  r@  rA  	max_indexr  vs           r   r  z_spbase._setdiag!  s    z1q55{a!QKK	y)) , ,A%+DQNN, ,  !QF44	>>F%fZiZ&899 ' 'DAq%&DQNN' ' {a1Q3KK	y)) , ,A%+DAENN, ,  1Q3F44	>>F%fZiZ&899 ' 'DAq%&DAENN' 'r   c                     |G|t          d          |j        | j        k    s|j        | j        k    rt          d          d|d<   |S t          j        | j        | j        |          S )Nz,order cannot be specified if out is not Nonez6out array must be same dtype and shape as sparse arrayg        .)r   r   )rx   r   r   rz   zerosr  s      r   _process_toarray_argsz_spbase._process_toarray_args?  s    ?   "/ 0 0 0yDJ&&#)tz*A*A  "0 1 1 1CHJ8DJdjFFFFr   r   c                 T    ddl m}  ||||ot          | t                               S )a  
        Determine index dtype for array.

        This wraps _sputils.get_index_dtype, providing compatibility for both
        array and matrix API sparse matrices. Matrix API sparse matrices would
        attempt to downcast the indices - which can be computationally
        expensive and undesirable for users. The array API changes this
        behaviour.

        See discussion: https://github.com/scipy/scipy/issues/16774

        The get_index_dtype import is due to implementation details of the test
        suite. It allows the decorator ``with_64bit_maxval_limit`` to mock a
        lower int32 max value for checks on the matrix API's downcasting
        behaviour.
        r   )get_index_dtype)_sputilsr  ry   r   )rQ   arraysmaxvalcheck_contentsr  s        r   _get_index_dtypez_spbase._get_index_dtypeL  sI    " 	.----- v% . Pz$7P7P3PS S 	Sr   )r   TrM   )F)r   )FF)NF)T)NN)NNN)r   NF)sr   r   r   __doc____array_priority__r   	_allow_ndpropertyintrR   rV   rZ   r_   rc   rg   rk   ro   rs   r~   r   r   r   r   classmethodr   r   r   r   r   r   r   r   r   strr   r   r   r   r   r   r   __nonzero__r   r   r   r   r  r  r  r  r  r  r  r  r  r  r  r  r!  r$  r&  r*  r,  r1  r3  r5  r7  rE  rH  rK  r   r:  r<  r=  rT  rW  rY  rc  rk  rm  rp  rs  ru  rw  rz  r|  r  r~  r  r   r  r  r   r   r  r  r  r)  r  r   r  r   r  r  r  r  r   r  r  r  r  r  r  r  r  r   r   r   rJ   rJ   =   s&         GI c       X  0 0 X0   X   X   X   X   X   X   X *. 	C 	C 	C 	C 	C   X)M )M )MV@ @ @6   > ) ) [) ' ' ['       8S 8S 8S 8StL L L L S    X c    X     X     X    X   X
 
 
  4N N N K
( ( (( ( ( (N, , ,+ + ++ + +     $2 2 2 2; ; ; ;* * ** * ** * ** * ** * ** * *! ! !4 4 4 4/ / /. . ./ / /& & && & &" " ""# # #" " " 
" 
" 
"\? \? \?|$ $ $$ $ $/ / /2 2 27 7 72 2 2# # #$, , ,- - -*" *" *" *"X5 5 55 5 5            ( ( (  + + +F F F F>   .) ) ) ) $DL$ $ $$ $ $7 7 7(  &# # #LE E E E<D D D DF7 7 7 77 7 7 77 7 7 77 7 7 77 7 7 7	L 	L 	L 	L7 7 7 7/ / /K8 K8 K8 K8ZI2 I2 I2 I2V* * * *4
- 
- 
- 
-- - - -2' ' '<G G GS S S S S Sr   rJ   c                       e Zd ZdZdS )r   z3A namespace class to separate sparray from spmatrixN)r   r   r   r  r   r   r   r   r   e  s        ====r   r   c                 ,    t          | t                    S )a  Is `x` of a sparse array or sparse matrix type?

    Parameters
    ----------
    x
        object to check for being a sparse array or sparse matrix

    Returns
    -------
    bool
        True if `x` is a sparse array or a sparse matrix, False otherwise

    Notes
    -----
    Use `isinstance(x, sp.sparse.sparray)` to check between an array or matrix.
    Use `a.format` to check the sparse format, e.g. `a.format == 'csr'`.

    Examples
    --------
    >>> import numpy as np
    >>> from scipy.sparse import csr_array, csr_matrix, issparse
    >>> issparse(csr_matrix([[5]]))
    True
    >>> issparse(csr_array([[5]]))
    True
    >>> issparse(np.array([[5]]))
    False
    >>> issparse(5)
    False
    )ry   rJ   xs    r   r   r   l  s    > a!!!r   c                 ,    t          | t                    S )a  Is `x` of a sparse matrix type?

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

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

    Examples
    --------
    >>> import numpy as np
    >>> from scipy.sparse import csr_array, csr_matrix, isspmatrix
    >>> isspmatrix(csr_matrix([[5]]))
    True
    >>> isspmatrix(csr_array([[5]]))
    False
    >>> isspmatrix(np.array([[5]]))
    False
    >>> isspmatrix(5)
    False
    )ry   r   r  s    r   r   r     s    4 a"""r   ).r  numpyrz   r  r   r   r   r   r   r	   r
   r   r   _matrixr   __all__Warningr   r   r   r   	frozensetsintanarcsinarctansinhtanharcsinharctanhrintsignexpm1log1pdeg2radrad2degfloorceiltruncsqrt _ufuncs_with_fixed_point_at_zeror|   rJ   r   r   r   r   r   r   <module>r      s   $ $    7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7      7 7 7	 	 	 	 	G 	 	 		 	 	 	 	- 	 	 		 	 	 	 	m 	 	 	
EA12 A./A+, A' A34	
 A12 A|$ A'( A<= Az? B*+ B89 B-. B;< B+, B./  B)*!" 45,-$'  0 $-9
	29bgrw


BGRWbh"*

BHbgrx.: $; $;   eS eS eS eS eS eS eS eSP)> > > > > > > > /" " "D# # # # #r   