
    CpjO                        S r SSKrSSKJrJr  SSKrSSKrSSKJ	r	  SSK
Jr  / SQr\R                  \R                  \R                   \R"                  \R$                  \R&                  \R(                  \R*                  \R,                  \R.                  \R0                  \R2                  \R4                  \R6                  \R8                  \R:                  \R<                  /r0 r S r!S r"S r#S	 r$S
 r%S-S jr&S.S\RN                  4S jjr(\RR                  S4S jr*S/S jr+S\RX                  S\RX                  \-\R\                     -  4S jr/S\04S jr1S\04S jr2S0SSS.S\04S jjjr3S\04S jr4S\04S jr5S\04S jr6SS.S\7\8S4   S-  4S jjr9S1SS .S\7\8S4   4S! jjjr:S" r;S\04S# jr<  S-S$\S%S\S&   -  S'\SS(4S) jjr=S* r>S1S+ jr?S\RN                  4S, jr@g)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                     [         R                  [        U 5      5      nUb  U$ [        R                  " U 6 n[
         H4  n[        R                  " X!5      (       d  M   U[         [        U 5      '   Us  $    [        SU < 35      e)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      Q/var/www/html/pdf-tiff/venv/lib/python3.13/site-packages/scipy/sparse/_sputils.pyr   r      sq    ( 	d$A}^^T"F;;v!!'(Ld$H 
 9$B
CC    c                      [         R                  U 5      nUb  U$ [        [        [        R
                  U 5      6 nU[         U '   U$ )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                 H    [         R                  " S/U S9U-  R                  $ )zXDetermine 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                 L   U R                   R                  [        R                   " [        R                  5      R                  :  a  U R                  S:X  a  U R                  [        R                  5      $ U R                  5       nU R                  5       nU[        R                  " [        R                  5      R                  :  d2  U[        R                  " [        R                  5      R                  :  a  [        S5      eU R                  [        R                  5      $ U $ )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                     U R                   nUR                  (       a  U $ [        R                  " XR	                  S5      S9$ )z
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;   _   s3     
B	{{ ::ax899r   c                 <   U c   UR                   nO[        R                   " U 5      nU[        ;  a.  SR                  S [         5       5      n[        SU SU S35      eU$ ! [         a/  nUb  [        R                   " U5      n SnANb[        S5      UeSnAff = f)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   8   #    U  H  oR                   v   M     g 7fN)__name__).0r   s     r   	<genexpr>getdtype.<locals>.<genexpr>   s     (N=M=Ms   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Breturnc                 Z    [         R                  " XUS9n[        UR                  5        U$ )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    rM   datas       r   r   r      s'    
 88C40D TZZKr    c                 <  ^^ U(       d  ST 3n[         R                  " T5      R                  mU R                  S;   a  U R                  S   T:  a  [        SU 35      e[        U R                  6 T:  a0  U R                  T:  R                  5       (       a  [        SU 35      eU R                  R                  TSS9nU R                  R                  TSS9nX44$ U R                  S:X  ag  [        U R                  6 T:  a2  [        U4S	 jU R                   5       5      (       a  [        S
U 35      e[        U4S jU R                   5       5      $ U R                  S:X  ab  [        U R                  6 T:  a0  U R                  T:  R                  5       (       a  [        SU 35      eU R                  R                  TSS9nU$ U R                  S:X  a  U R                  u  pgU R                  S   U-  T:  a  [        S5      e[        U R                  6 T:  a3  U R                  U-  T:  R                  5       (       a  [        SU 35      eU R                  R                  TSS9nU R                  R                  TSS9nX44$ [        SU R                   S35      e)ac  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rM   cooc              3   H   >#    U  H  oT:  R                  5       v   M     g 7fr>   )any)r@   co	max_values     r   rA   +safely_cast_index_arrays.<locals>.<genexpr>   s     =HbN''))Hs   "zcoords values too large for c              3   B   >#    U  H  oR                  TS S9v   M     g7f)FrV   N)r+   )r@   rZ   	idx_dtypes     r   rA   r\      s     I"YYyuY5s   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indicesrY   r+   coordstupleoffsets	blocksizer   )	r9   r^   msgrd   rb   rg   RCr[   s	    `      @r   safely_cast_index_arraysrl      s_   | 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	{{88B<!i'@AA=9$		A	)..00 #@!FGG))""95"97 '!(( ,E E F 	Fr   c                    [         R                  " 5       R                  S:w  a  [         R                  $ [         R                  " [         R
                  " [         R                  5      R                  5      n[         R                  " [         R
                  " [         R                  5      R                  5      nUb+  [         R                  " U5      nX:  a  [         R                  $ [        U [         R                  5      (       a  U 4n U  H  n[         R                  " U5      n[         R                  " UR                  [         R                  5      (       a  MO  U(       ar  UR                  S:X  a  Mh  [         R                  " UR                  [         R                  5      (       a,  UR                  5       nUR                  5       nXc:  a  X::  a  M  [         R                  s  $    [         R                  $ )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_dtyperz     s1   R 
wwyQxxxx*../Hxx*../H&!88O&"**%%jjo{{399bhh//88q=]]399bjj99 WWYF WWYF)f.@ 88O  88Or   r    c                    U R                   S:X  a:  [        R                  " U [        R                  5      (       a  [        R                  $ [        R                  " U [        R                  5      (       a  [        R                  $ U $ )z Mimic numpy's casting for np.sumu)kindr   r   uintint_r#   s    r   r   r   O  sN    zzSR[[88ww	{{5"''""wwLr   c                 ~    [         R                  " U 5      =(       d!    [        U 5      =(       a    U R                  S:H  $ )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                     [         R                  " U 5      S:w  a  g [        R                  " U 5        g! [        [
        4 aI     [        [        U 5      U :H  5      nO! [        [
        4 a      gf = fU(       a  Sn[        U5      eUs $ f = f)zkIs 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_intri   s      r   r
   r
   ]  s     
wwqzQ
q  z" 	SVq[)I:& 		HCS/!s3   4 BABA1-B0A11BB)   T)allow_ndcheck_ndc                    [        U 5      nU(       a  XB;  a  gU  H&  n[        U5      (       d    gU(       d  M  US:  d  M&    g   g)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  sA     q6DD(||6a!e	 
 r   c                    [        U [        [        -  5      =(       a.    [        U 5      S:H  =(       d    [        R
                  " U S   5      =(       d0    [        U [        R                  5      =(       a    U R                  S:H  $ )Nr      )rr   listrf   r   r   r   rs   r   r   s    r   r   r     sW    4%<( /Vq[-BKK!-:2::&8AFFaK;r   c                     [        U [        [        -  5      =(       a#    [        U 5      S:  =(       a    [	        U S   5      =(       d0    [        U [
        R                  5      =(       a    U R                  S:H  $ )Nr   r   )rr   r   rf   r   r   r   rs   r   r   s    r   r   r     sV    4%<( -VaZ-&qt,82::&6166Q;9r   c                 6    [        U [        R                  5      $ r>   )rr   r   rs   r   s    r   r   r     s    a$$r   r   )r   .c                l   U c  g U S:X  a  [        S5      e[        U [        5      (       da  [        R                  " [        R
                  " [        U 5      5      [        R                  5      (       d  [        S[        U 5       35      eU 4n / nU  HS  n[        U5      (       d  [        SU S35      eUS:  a  X1-  nUS:  d  X1:  a  [        S5      eUR                  U5        MU     [        U5      nU[        [        U5      5      :w  a  [        S5      eXA:  a  [        S	5      eXA:X  a  g [        U5      $ )
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/   rr   rf   r   rt   r    typeru   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6RZ9::"  :H3s:''233	;<<		Z  r   )r   c                   [        U 5      S:X  a  [        S5      e[        U 5      S:X  a"   [        U S   5      n[        S U 5       5      nO[        S U  5       5      nUcD  [        U5      U;  a  [        SU SU< 35      e[        S	 U 5       5      (       a  [        S
5      eO[        U5      n[        U5       VVs/ s H  u  pgUS:  d  M  UPM     nnnU(       d"  [        U5      n	X:w  a  [        SU SU 35      eO}[        U5      S:X  ac  US   n
[        USU
 XJS-   S -   5      n[        X[5      u  pUS:w  a#  [        S U 5       5      n[        SU SU 35      eUSU
 U4-   XJS-   S -   nO[        S5      e[        U5      U;  a  [        SU SU< 35      eU$ ! [         a    [        R
                  " U S   5      4n GNif = fs  snnf )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   N   #    U  H  n[         R                  " U5      v   M     g 7fr>   r   r   r@   args     r   rA   check_shape.<locals>.<genexpr>  s     HZchnnS11Z   #%c              3   N   #    U  H  n[         R                  " U5      v   M     g 7fr>   r   r   s     r   rA   r     s     >#(..--r   Nzshape must have length in z. Got new_shape=c              3   *   #    U  H	  oS :  v   M     g7f)r   Nr   )r@   r   s     r   rA   r     s     (i1uis   z#'shape' elements cannot be negativezcannot reshape array of size z into shape c              3   4   #    U  H  oS :  a  SOUv   M     g7f)r   newshapeNr   )r@   r   s     r   rA   r     s     !PiA*1"<is   z&can only specify one unknown dimension)r   r   iterrf   r   r   r/   rY   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*>$!!a%A*>HIH' #@#/	{"< = = ( !"a'#A&DYu-	q&'0BBCI%+L%D"KA~!!Pi!PP	 #@#/	{"< = =!%4(K>9I1fg<NNIEFF
9~X%5hZ?Pi\RSSM  	4!Q03I	4" Is   F  >GG $GGc                  d   U (       d  gU  Vs/ s H$  n[        U[        [        -  5      (       a  UOU4PM&     n n[        U [        S9n[        U5      nU  HO  nXL a  M	  [        U[	        U5      * S9 H.  u  pEUS:w  d  M  XSU   :w  d  M  X4   S:w  a  [        S5      eXSU'   M0     MQ     / UQ7$ s  snf )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.)rr   rf   r   r,   r   r   r/   )shapesshpbig_shpoutr   r   s         r   r   r     s    " JPQ&3ZUT\22c>&FQ&c"G
w-C>c#c(3DAAv!1v+6Q;$%TUUA	 4  S7N Rs   +B-c                     [        [        R                  R                  S5      SS5      nUSL=(       a    [	        X5      $ )zN
Check whether object is pydata/sparse matrix, avoiding importing the module.
sparseSparseArrayN)getattrsysmodulesr   rr   )mbase_clss     r   is_pydata_spmatrixr     s4     s{{x0-FH4;Jq$;;r   r   target_formatrR   	accept_fvzsp.spmatrix | Anyc                     [        U 5      (       aF   U R                  US9n Ub  U R                  U5      n U $ U R                  S;  a  U R                  5       n U $ ! [         a    U R                  5       n  NTf = f)zS
Convert a pydata/sparse array to scipy sparse matrix,
pass through anything else.
)r   rR   )r   to_scipy_sparser   asformatra   tocsc)r   r   r   s      r   convert_pydata_sparse_to_scipyr   $  s     #	(%%	%:C $,,}-C J ZZ~-))+CJ  	(%%'C	(s   A A65A6c                  h    [         R                  " U 0 UD6R                  [         R                  5      $ r>   )r   r$   viewmatrix)r   kwargss     r   r   r   A  s%    88T$V$))"))44r   c                     [        U [        R                  5      (       a  Ub  U R                  U:X  a  U $ [        R                  " XS9R                  [        R                  5      $ )Nr#   )rr   r   r   r    r7   r   )rO   r    s     r   asmatrixr   E  sE    $		""u9L::d(--bii88r   c                 F   [        U [        R                  R                  5      (       a  U R	                  5       $ [        U [        R
                  5      (       a8  [        R                  " U R                  5       U R                  U R                  S9$ [        U [        R                  5      (       aU  [        R                  " U R                  U R                  S9n[        R                  R                  U R                  U5        U$ U R!                  5       R	                  5       $ )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#   )rr   sp_data_data_matrix_deduped_data	dok_arrayr   fromitervaluesr    nnz	lil_arrayempty_csparsetoolslil_flatten_to_arrayrO   tocoo)srO   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ushortro   uintclongulonglonglong	ulonglongfloat32float64
longdouble	complex64
complex128clongdoubler   r   r   r!   r&   r3   r;   r   rs   r   rq   rl   rz   r    r   genericr   r   r	   r
   r   r   r   r   rf   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   