
    ^jO                        d Z ddlZddlmZmZ ddlZddlZddlm	Z	 ddl
mZ g dZej                  ej                  ej                   ej"                  ej$                  ej&                  ej(                  ej*                  ej,                  ej.                  ej0                  ej2                  ej4                  ej6                  ej8                  ej:                  ej<                  gZi Z d Z!d Z"d Z#d	 Z$d
 Z%d-dZ&d.dejN                  fdZ(ejR                  dfdZ*d/dZ+dejX                  dejX                  e-ej\                     z  fdZ/de0fdZ1de0fdZ2d0dddde0fdZ3de0fdZ4de0fdZ5de0fdZ6ddde7e8df   dz  fdZ9d1dd de7e8df   fd!Z:d" Z;de0fd#Z<	 	 d-d$ed%ded&   z  d'edd(fd)Z=d* Z>d1d+Z?dejN                  fd,Z@y)2z, Utility functions for sparse matrix module
    N)AnyLiteral)prod)upcastgetdtypegetdataisscalarlike	isintlikeisshape
issequenceisdenseismatrixget_sum_dtypebroadcast_shapesc                      t         j                  t        |             }||S t        j                  |  }t
        D ].  }t        j                  ||      s|t         t        |       <   |c S  t        d|       )a  Returns the nearest supported sparse dtype for the
    combination of one or more types.

    upcast(t0, t1, ..., tn) -> T  where T is a supported dtype

    Examples
    --------
    >>> from scipy.sparse._sputils import upcast
    >>> upcast('int32')
    <class 'numpy.int32'>
    >>> upcast('bool')
    <class 'numpy.bool'>
    >>> upcast('int32','float32')
    <class 'numpy.float64'>
    >>> upcast('bool',complex,float)
    <class 'numpy.complex128'>

    z#no supported conversion for types: )_upcast_memogethashnpresult_typesupported_dtypescan_cast	TypeError)argstr   s      N/opt/ringagent/.cad-venv/lib/python3.12/site-packages/scipy/sparse/_sputils.pyr   r      su    ( 	d$A}^^T"F ;;vq!'(Ld$H
 9$B
CC    c                      t         j                  |       }||S t        t        t        j
                  |        }|t         | <   |S )z9Same as `upcast` but taking dtype.char as input (faster).)r   r   r   mapr   dtype)r   r   s     r   upcast_charr!   :   s@    A}BHHd#$ALHr   c                 L    t        j                  dg|       |z  j                  S )z`Determine data type for binary operation between an array of
    type `dtype` and a scalar.
    r   r    )r   arrayr    )r    scalars     r   upcast_scalarr&   D   s"     HHaS&/666r   c                 >   | j                   j                  t        j                   t        j                        j                  kD  r| j                  dk(  r| j                  t        j                        S | j                         }| j                         }|t        j                  t        j                        j                  kD  s0|t        j                  t        j                        j                  k  rt        d      | j                  t        j                        S | S )z
    Down-cast index array to np.intp dtype if it is of a larger dtype.

    Raise an error if the array contains a value that is too large for
    intp.
    r   zzCannot deal with arrays with indices larger than the machine maximum address size (e.g. 64-bit indices on 32-bit machine).)
r    itemsizer   intpsizeastypemaxminiinfo
ValueError)arrmaxvalminvals      r   downcast_intp_indexr3   K   s     yyBHHRWW-66688q=::bgg&&BHHRWW%)))Vbhhrww6G6K6K-K H I I zz"''""Jr   c                     | j                   }|j                  r| S t        j                  | |j	                  d            S )a  
    Ensure that the data type of the NumPy array `A` has native byte order.

    `A` must be a NumPy array.  If the data type of `A` does not have native
    byte order, a copy of `A` with a native byte order is returned. Otherwise
    `A` is returned.
    nativer#   )r    isnativer   asarraynewbyteorder)Adts     r   	to_nativer;   _   s5     
B	{{ ::arx899r   c                 0   | 	 |j                   }nt        j                   |       }|t        vr.dj                  d t        D              }t        d| d| d      |S # t        $ r.}|t        j                   |      }nt        d      |Y d}~jd}~ww xY w)a  Form a supported numpy dtype based on input arguments.

    Returns a valid ``numpy.dtype`` from `dtype` if not None,
    or else ``a.dtype`` if possible, or else the given `default`
    if not None, or else raise a ``TypeError``.

    The resulting ``dtype`` must be in ``supported_dtypes``:
        bool_, int8, uint8, int16, uint16, int32, uint32,
        int64, uint64, longlong, ulonglong, float32, float64,
        longdouble, complex64, complex128, clongdouble
    Nzcould not interpret data typez, c              3   4   K   | ]  }|j                     y wN)__name__).0r   s     r   	<genexpr>zgetdtype.<locals>.<genexpr>   s     (N(Ns   z$scipy.sparse does not support dtype z . The only supported types are: .)r    AttributeErrorr   r   r   joinr/   )r    adefaultnewdtypeesupported_dtypes_fmts         r   r   r   o   s     }	HwwH 88E?''#yy(N=M(NN?z J::N9OqR S 	SO  	H"88G, ?@aG 	Hs   A 	B'$BBreturnc                 `    t        j                  | ||      }t        |j                         |S )z
    This is a wrapper of `np.array(obj, dtype=dtype, copy=copy)`
    that will generate a warning if the result is an object array.
    )r    copy)r   r$   r   r    )objr    rL   datas       r   r   r      s)    
 88Cu40D TZZKr    c                    |sd }t        j                        j                  | j                  dv r| j                  d   kD  rt        d|       t        | j                   kD  r+| j                  kD  j                         rt        d|       | j                  j                  d      }| j                  j                  d      }||fS | j                  dk(  r_t        | j                   kD  r,t        fd	| j                  D              rt        d
|       t        fd| j                  D              S | j                  dk(  r_t        | j                   kD  r+| j                  kD  j                         rt        d|       | j                  j                  d      }|S | j                  dk(  r| j                  \  }}| j                  d   |z  kD  rt        d      t        | j                   kD  r.| j                  |z  kD  j                         rt        d|       | j                  j                  d      }| j                  j                  d      }||fS t        d| j                   d      )a3	  Safely cast sparse array indices to `idx_dtype`.

    Check the shape of `A` to determine if it is safe to cast its index
    arrays to dtype `idx_dtype`. If any dimension in shape is larger than
    fits in the dtype, casting is unsafe so raise ``ValueError``.
    If safe, cast the index arrays to `idx_dtype` and return the result
    without changing the input `A`. The caller can assign results to `A`
    attributes if desired or use the recast index arrays directly.

    Unless downcasting is needed, the original index arrays are returned.
    You can test e.g. ``A.indptr is new_indptr`` to see if downcasting occurred.

    .. versionadded:: 1.15.0

    Parameters
    ----------
    A : sparse array or matrix
        The array for which index arrays should be downcast.
    idx_dtype : dtype
        Desired dtype. Should be an integer dtype (default: ``np.int32``).
        Most of scipy.sparse uses either int64 or int32.
    msg : str, optional
        A string to be added to the end of the ValueError message
        if the array shape is too big to fit in `idx_dtype`.
        The error message is ``f"<index> values too large for {msg}"``
        It should indicate why the downcasting is needed, e.g. "SuperLU",
        and defaults to f"dtype {idx_dtype}".

    Returns
    -------
    idx_arrays : ndarray or tuple of ndarrays
        Based on ``A.format``, index arrays are returned after casting to `idx_dtype`.
        For CSC/CSR, returns ``(indices, indptr)``.
        For COO, returns ``coords``.
        For DIA, returns ``offsets``.
        For BSR, returns ``(indices, indptr)``.

    Raises
    ------
    ValueError
        If the array has shape that would not fit in the new dtype, or if
        the sparse format does not use index arrays.

    Examples
    --------
    >>> import numpy as np
    >>> from scipy import sparse
    >>> data = [3]
    >>> coords = (np.array([3]), np.array([1]))  # Note: int64 arrays
    >>> A = sparse.coo_array((data, coords))
    >>> A.coords[0].dtype
    dtype('int64')

    >>> # rescast after construction, raising exception if shape too big
    >>> coords = sparse.safely_cast_index_arrays(A, np.int32)
    >>> A.coords[0] is coords[0]  # False if casting is needed
    False
    >>> A.coords = coords  # set the index dtype of A
    >>> A.coords[0].dtype
    dtype('int32')
    zdtype csccsrzindptr values too large for zindices values too large for FrL   cooc              3   D   K   | ]  }|kD  j                           y wr>   )any)r@   co	max_values     r   rA   z+safely_cast_index_arrays.<locals>.<genexpr>   s     =bBN'')=    zcoords values too large for c              3   D   K   | ]  }|j                  d         yw)FrU   N)r+   )r@   rY   	idx_dtypes     r   rA   z+safely_cast_index_arrays.<locals>.<genexpr>   s     I"RYYyuY5Ir[   diazoffsets values too large for bsrz!indptr values too large for {msg}zFormat zP is not associated with index arrays. DOK and LIL have dict and list, not array.)r   r.   r,   formatindptrr/   shapeindicesrX   r+   coordstupleoffsets	blocksizer   )	r9   r]   msgrc   ra   rf   RCrZ   s	    `      @r   safely_cast_index_arraysrk      sY   | yk"#''Ixx>!88B<)#;C5ABB =9$		I%**, #@!FGG))""95"97	
U	=9$=AHH== #?u!EFFIIII	
U	=9$		I%**, #@!FGG))""95"9	
U	{{188B<!i'@AA=9$		A	)..0 #@!FGG))""95"97 '!(( ,E E F 	Fr   c                    t        j                         j                  dk7  rt         j                  S t        j                  t        j
                  t         j                        j                        }t        j                  t        j
                  t         j                        j                        }|*t        j                  |      }||kD  rt         j                  S t        | t         j                        r| f} | D ]  }t        j                  |      }t        j                  |j                  t         j                        rG|ri|j                  dk(  rYt        j                  |j                  t         j                        r+|j                         }|j                         }||k\  r||k  rt         j                  c S  t         j                  S )a  
    Based on input (integer) arrays `a`, determine a suitable index data
    type that can hold the data in the arrays.

    Parameters
    ----------
    arrays : tuple of array_like
        Input arrays whose types/contents to check
    maxval : float, optional
        Maximum value needed
    check_contents : bool, optional
        Whether to check the values in the arrays and not just their types.
        Default: False (check only the types)

    Returns
    -------
    dtype : dtype
        Suitable index data type (int32 or int64)

    Examples
    --------
    >>> import numpy as np
    >>> from scipy import sparse
    >>> # select index dtype based on shape
    >>> shape = (3, 3)
    >>> idx_dtype = sparse.get_index_dtype(maxval=max(shape))
    >>> data = [1.1, 3.0, 1.5]
    >>> indices = np.array([0, 1, 0], dtype=idx_dtype)
    >>> indptr = np.array([0, 2, 3, 3], dtype=idx_dtype)
    >>> A = sparse.csr_array((data, indices, indptr), shape=shape)
    >>> A.indptr.dtype
    dtype('int32')

    >>> # select based on larger of existing arrays and shape
    >>> shape = (3, 3)
    >>> idx_dtype = sparse.get_index_dtype(A.indptr, maxval=max(shape))
    >>> idx_dtype
    <class 'numpy.int32'>
       r   )r   intcr(   int64int32r.   r-   r,   
isinstancendarrayr7   r   r    r*   
issubdtypeinteger)arraysr1   check_contentsint32minint32maxr0   r2   s          r   get_index_dtypery     s3   R 
wwyQxxxx*../Hxx*../H&!H88O&"**% jjo{{399bhh/88q=]]399bjj9 WWYF WWYF)f.@ 88O 88Or   r    c                     | j                   dk(  r4t        j                  | t        j                        rt        j                  S t        j                  | t        j                        rt        j                  S | S )z Mimic numpy's casting for np.sumu)kindr   r   uintint_r#   s    r   r   r   O  sH    zzSR[[8ww	{{5"''"wwLr   c                 h    t        j                  |       xs t        |       xr | j                  dk(  S )z8Is x either a scalar, an array scalar, or a 0-dim array?r   )r   isscalarr   ndimxs    r   r	   r	   X  s&    ;;q>9gaj8QVVq[9r   c                    t        j                  |       dk7  ry	 t        j                  |        y# t        t
        f$ rC 	 t        t        |       | k(        }n# t        t
        f$ r Y Y yw xY w|rd}t        |      |cY S w xY w)zsIs x appropriate as an index into a sparse matrix? Returns True
    if it can be cast safely to a machine int.
    r   Fz4Inexact indices into sparse matrices are not allowedT)r   r   operatorindexr   r/   boolint)r   	loose_intrh   s      r   r
   r
   ]  s     
wwqzQ
q  z" 	SVq[)I:& 		HCS/!s3   1 BABA,(B+A,,BB)   T)allow_ndcheck_ndc                d    t        |       }|r||vry| D ]  }t        |      s y|s|dk  s y y)zIs x a valid tuple of dimensions?

    If nonneg, also checks that the dimensions are non-negative.
    Shapes of length in the tuple allow_nd are allowed.
    Fr   T)lenr
   )r   nonnegr   r   r   ds         r   r   r   s  sD     q6DD( |a!e	
 r   c                     t        | t        t        z        xr( t        |       dk(  xs t	        j
                  | d         xs+ t        | t        j                        xr | j                  dk(  S )Nr      )rq   listre   r   r   r   rr   r   r   s    r   r   r     sW    4%<( /Vq[-BKK!-:2::&8AFFaK;r   c                     t        | t        t        z        xr t        |       dkD  xr t	        | d         xs+ t        | t
        j                        xr | j                  dk(  S )Nr   r   )rq   r   re   r   r   r   rr   r   r   s    r   r   r     sV    4%<( -VaZ-&qt,82::&6166Q;9r   c                 6    t        | t        j                        S r>   )rq   r   rr   r   s    r   r   r     s    a$$r   r   )r   .c                >   | y | dk(  rt        d      t        | t              sZt        j                  t        j
                  t        |             t        j                        st        dt        |              | f} g }| D ]L  }t        |      st        d| d      |dk  r||z  }|dk  s||k\  rt        d      |j                  |       N t        |      }|t        t        |            k7  rt        d      ||kD  rt        d	      ||k(  ry t        |      S )
N zWsparse does not accept 0D axis (). Either use toarray (for dense) or copy (for sparse).z+axis must be an integer/tuple of ints, not z axis must be an integer. (given )r   zaxis out of range for ndimzduplicate value in axisz axis tuple has too many elements)r/   rq   re   r   rs   r    typert   r   r
   appendr   set)axisr   
canon_axisaxlen_axiss        r   validateaxisr     s&   |rz$
 	

 dE" }}RXXd4j12::>I$t*VWWwJ }>rd!DEE6$JB6R4Z9::" :H3s:''233	D;<<	T	Z  r   )r   c                p   t        |       dk(  rt        d      t        |       dk(  r"	 t        | d         }t        d |D              }nt        d | D              }|;t        |      |vrt        d| d|      t        d	 |D              rt        d
      t        |      }t        |      D cg c]  \  }}|dk  s| }}}|s!t        |      }	|	|k7  rt        d| d|       t        |      dk(  rf|d   }
t        |d|
 ||
dz   d z         }t        ||      \  }}|dk7  r#t        d |D              }t        d| d|       |d|
 |fz   ||
dz   d z   }nt        d      t        |      |vrt        d| d|      |S # t        $ r t	        j
                  | d         f}Y Rw xY wc c}}w )a@  Imitate numpy.matrix handling of shape arguments

    Parameters
    ----------
    args : array_like
        Data structures providing information about the shape of the sparse array.
    current_shape : tuple, optional
        The current shape of the sparse array or matrix.
        If None (default), the current shape will be inferred from args.
    allow_nd : tuple of ints, optional default: (2,)
        If shape does not have a length in the tuple allow_nd an error is raised.

    Returns
    -------
    new_shape: tuple
        The new shape after validation.
    r   z8function missing 1 required positional argument: 'shape'r   c              3   F   K   | ]  }t        j                  |        y wr>   r   r   r@   args     r   rA   zcheck_shape.<locals>.<genexpr>  s     HchnnS1H   !c              3   F   K   | ]  }t        j                  |        y wr>   r   r   s     r   rA   zcheck_shape.<locals>.<genexpr>  s     >#(..->r   Nzshape must have length in z. Got new_shape=c              3   &   K   | ]	  }|d k    yw)r   Nr   )r@   r   s     r   rA   zcheck_shape.<locals>.<genexpr>  s     (q1u(s   z#'shape' elements cannot be negativezcannot reshape array of size z into shape c              3   .   K   | ]  }|d k  rdn|  yw)r   newshapeNr   )r@   r   s     r   rA   zcheck_shape.<locals>.<genexpr>  s     !PA*1"<!Ps   z&can only specify one unknown dimension)r   r   iterre   r   r   r/   rX   r   	enumeratedivmod)r   current_shaper   
shape_iter	new_shapecurrent_sizeir   negative_indexesnew_sizeskip	specifiedunspecified	remainder	err_shapes                  r   check_shaper     s   $ 4yA~RSS
4yA~	Id1gJ HZHHI>>>	y>)9(CT)VWW(i((BCC M* +4I*>H$!Q!a%AHHIH<' #@#/	{"< = =!"a'#A&DYu-	$q&'0BBCI%+L)%D"KA~!!Pi!PP	 #@#/	{"< = =!%4(K>9Id1fg<NNIEFF
9~X%5hZ?Pi\RSSM  	4!Q03I	4" Is   F	 2F2 F2	"F/.F/c                  J   | sy| D cg c]  }t        |t        t        z        r|n|f  } }t        | t              }t        |      }| D ]M  }||u rt        |t	        |             D ],  \  }}|dk7  s|||   k7  s||   dk7  rt        d      |||<   . O g |S c c}w )a  Check if shapes can be broadcast and return resulting shape

    This is similar to the NumPy ``broadcast_shapes`` function but
    does not check memory consequences of the resulting dense matrix.

    Parameters
    ----------
    *shapes : tuple of shape tuples
        The tuple of shapes to be considered for broadcasting.
        Shapes should be tuples of non-negative integers.

    Returns
    -------
    new_shape : tuple of integers
        The shape that results from broadcasting th input shapes.
    r   )key)startr   z-shapes cannot be broadcast to a single shape.)rq   re   r   r,   r   r   r/   )shapesshpbig_shpoutr   r   s         r   r   r     s    " JPQ3ZUT\2c>QFQ&c"G
w-C '>c#c(3 	DAqAv!s1v+q6Q;$%TUUA		 S7N Rs   #B c                 z    t        t        j                  j                  d      dd      }|duxr t	        | |      S )zV
    Check whether object is pydata/sparse matrix, avoiding importing the module.
    sparseSparseArrayN)getattrsysmodulesr   rq   )mbase_clss     r   is_pydata_spmatrixr     s6     s{{x0-FH4;Jq($;;r   r   target_formatrQ   	accept_fvzsp.spmatrix | Anyc                     t        |       rF	 | j                  |      } || j                  |      } | S | j                  dvr| j                         } | S # t        $ r | j                         } Y Pw xY w)z_
    Convert a pydata/sparse array to scipy sparse matrix,
    pass through anything else.
    )r   rQ   )r   to_scipy_sparser   asformatr`   tocsc)r   r   r   s      r   convert_pydata_sparse_to_scipyr   $  s~     #	(%%	%:C $,,}-C J ZZ~-))+CJ  	(%%'C	(s   A A0/A0c                  f    t        j                  | i |j                  t         j                        S r>   )r   r$   viewmatrix)r   kwargss     r   r   r   A  s%    88T$V$))"))44r   c                     t        | t        j                        r|| j                  |k(  r| S t        j                  | |      j                  t        j                        S )Nr#   )rq   r   r   r    r7   r   )rN   r    s     r   asmatrixr   E  sD    $		"u9L::d%(--bii88r   c                 0   t        | t        j                  j                        r| j	                         S t        | t        j
                        r:t        j                  | j                         | j                  | j                        S t        | t        j                        rWt        j                  | j                  | j                        }t        j                  j                  | j                  |       |S | j!                         j	                         S )zAccess nonzero values, possibly after summing duplicates.

    Parameters
    ----------
    s : sparse array
        Input sparse array.

    Returns
    -------
    data: ndarray
      Nonzero values of the array, with shape (s.nnz,)

    )r    countr#   )rq   sp_data_data_matrix_deduped_data	dok_arrayr   fromitervaluesr    nnz	lil_arrayempty_csparsetoolslil_flatten_to_arrayrN   tocoo)srN   s     r   _todatar   M  s     !RXX**+  !R\\"{{188:QWWAEEBB!R\\"xxQWW-
--affd;779""$$r   )NN)NF)r   NF)Fr>   )A__doc__r   typingr   r   r   numpyr   mathr   scipy.sparser   r   __all__bool_byteubyteshortushortrn   uintclongulonglonglong	ulonglongfloat32float64
longdouble	complex64
complex128clongdoubler   r   r   r!   r&   r3   r;   r   rr   r   rp   rk   ry   r    r   genericr   r   r	   r
   r   r   r   r   re   r   r   r   r   r   r   r   r   r   r   r   r   <module>r     s         HHbggrxx299bggHHbggrxxbllJJ

BMMLL"--A 
 DD7(: <	BJJ 	 +-(( kF\EP bhhbjj1A&A :t :
D ,  $;T ;94 9%$ %  ! #!U38_t%; #!L=d =uS#X =@B<T < 37	',//  	:59%"** %r   