
    _MhQ                        d Z ddlZddlmZmZmZ ddlZddlZddl	m
Z
 ddlmZ ddlmZmZ g dZej        ej        ej        ej        ej        ej        ej        eeej        ej        ej        ej        ej        ej        ej        ej         gZ!i Z"d Z#d Z$d	 Z%d
 Z&d Z'd-dZ(d.dej)        fdZ*ej+        dfdZ,d/dZ-dej.        dej.        fdZ/de0fdZ1de0fdZ2d0ddde0fdZ3de0fdZ4de0fdZ5de0fdZ6d1dZ7d2ddde8e9df         fd Z:d! Z;d" Z<de0fd#Z=	 	 d-d$ed%ded&         z  d'edeed(f         fd)Z>d* Z?d2d+Z@dej)        fd,ZAdS )3z, Utility functions for sparse matrix module
    N)AnyLiteralUnion)prod)np_longnp_ulong)upcastgetdtypegetdataisscalarlike	isintlikeisshape
issequenceisdenseismatrixget_sum_dtypebroadcast_shapesc                     t                               t          |                     }||S t          j        |  }t
          D ]2}t          j        ||          r|t           t          |           <   |c S 3t          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'>

    Nz#no supported conversion for types: )_upcast_memogethashnpresult_typesupported_dtypescan_cast	TypeError)argstr	   s      U/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/scipy/sparse/_sputils.pyr	   r	      s    ( 	d$$A}^T"F  ;vq!! 	'(Ld$HHH	 B$BB
C
CC    c                      t                               |           }||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$   ;   sD    A}BHd##$ALHr    c                 @    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)   E   s#     HaS&&&/66r    c                    | j         j        t          j         t          j                  j        k    r| j        dk    r|                     t          j                  S |                                 }|                                 }|t          j        t          j                  j        k    s'|t          j        t          j                  j        k     rt          d          |                     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_indexr6   L   s     yBHRW--6668q==::bg&&&BHRW%%)))Vbhrw6G6G6K-K-K H I I I zz"'"""Jr    c                 t    | j         }|j        r| S t          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>   `   s=     
B	{  :arx889999r    c                 P   | G	 |j         }nR# t          $ r1}|t          j         |          }nt          d          |Y d}~nd}~ww xY wt          j         |           }|t          vr?d                    d t          D                       }t          d|j         d| d          |S )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 type, c              3   $   K   | ]}|j         V  d S N)__name__).0r   s     r   	<genexpr>zgetdtype.<locals>.<genexpr>   s$      (N(N(N(N(N(N(N(Nr    z$scipy.sparse does not support dtype z . The only supported types are: .)r#   AttributeErrorr   r   r   joinr2   name)r#   adefaultnewdtypeesupported_dtypes_fmts         r   r
   r
   p   s     }	HwHH 	H 	H 	H"8G,, ?@@aG 	H 8E??'''#yy(N(N=M(N(N(NNN R R R:NR R R S S 	SOs    
A'AAF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#   rQ   datas       r   r   r      s1    
 8Cu4000D TZKr     c                    |sd }t          j                  j        | j        dv r| j        d         k    rt          d|           t          | j         k    r/| j        k                                    rt          d|           | j        	                    d          }| j        	                    d          }||fS | j        dk    rdt          | j         k    r2t          fd	| j
        D                       rt          d
|           t          fd| j
        D                       S | j        dk    r_t          | j         k    r/| j        k                                    rt          d|           | j        	                    d          }|S | j        dk    r| j        \  }}| j        d         |z  k    rt          d          t          | j         k    r2| j        |z  k                                    rt          d|           | j        	                    d          }| j        	                    d          }||fS t          d| j         d          )a6	  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 : string, 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rQ   cooc              3   H   K   | ]}|k                                     V  d S rB   )any)rD   co	max_values     r   rE   z+safely_cast_index_arrays.<locals>.<genexpr>   s3      ==bBN''))======r    zcoords values too large for c              3   F   K   | ]}|                     d           V  dS )FrZ   N)r.   )rD   r^   	idx_dtypes     r   rE   z+safely_cast_index_arrays.<locals>.<genexpr>   s3      II"RYYyuY55IIIII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   r1   r/   formatindptrr2   shapeindicesr]   r.   coordstupleoffsets	blocksizer   )	r<   ra   msgrg   re   rj   RCr_   s	    `      @r   safely_cast_index_arraysro      s   |  #"y""##'Ix>!!8B<)##ACAABBB =9$$	I%**,, H !F!F!FGGG)""95"9977	
U		=9$$====AH===== G !E!E!EFFFIIIIIIIIII	
U		=9$$	I%**,, H !F!F!FGGG)""95"99	
U		{18B<!i''@AAA=9$$	A	)..00 H !F!F!FGGG)""95"9977  E!( E E E F F 	Fr     c                 ,   t          j                    j        dk    rt           j        S t          j        t          j        t           j                  j                  }t          j        t          j        t           j                  j                  }|&t          j        |          }||k    rt           j        S t          | t           j	                  r| f} | D ]}t          j
        |          }t          j        |j        t           j                  su|re|j        dk    rHt          j        |j        t           j                  r5|                                }|                                }||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'>
       Nr   )r   intcr+   int64int32r1   r0   r/   
isinstancendarrayr:   r   r#   r-   
issubdtypeinteger)arraysr4   check_contentsint32minint32maxr3   r5   s          r   get_index_dtyper~     sK   R 
wyyQxx**.//Hx**.//H&!!H8O&"*%%   joo{39bh// 	 	!8q==]39bj99 ! WWYYF WWYYF))f.@.@ 8OOO	 8Or    r#   c                     | j         dk    r+t          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   P  sK    zSR[88w	{5"'"" wLr    c                 ^    t          j        |           pt          |           o
| 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   Y  s&    ;q>>9gajj8QVq[9r    c                 4   t          j        |           dk    rdS 	 t          j        |            ng# t          t
          f$ rS 	 t          t          |           | k              }n# t          t
          f$ r Y Y dS w xY w|rd}t          |          |cY S w xY wdS )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   r2   boolint)r   	loose_intrl   s      r   r   r   ^  s     
wqzzQu
qz"   	SVVq[))II:& 	 	 	555	 	"HCS//! 4s3   1 B A$#B$A:5B9A::BB)   )allow_ndc                t    t          |           }||vrdS | D ]}t          |          s dS |r	|dk     r dS  dS )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   ds        r   r   r   t  s`     q66D8u  || 	55 	a!ee554r    c                     t          | t          t          z            r-t          |           dk    pt	          j        | d                   p$t          | t          j                  o
| j        dk    S )Nr      )rv   listri   r   r   r   rw   r   r   s    r   r   r     s\    4%<(( /VVq[-BK!--:2:&&8AFaK;r    c                     t          | t          t          z            r(t          |           dk    rt	          | d                   p$t          | t
          j                  o
| j        dk    S )Nr   r   )rv   r   ri   r   r   r   rw   r   r   s    r   r   r     s]    4%<(( -VVaZ-&qt,,82:&&616Q;9r    c                 6    t          | t          j                  S rB   )rv   r   rw   r   s    r   r   r     s    a$$$r    c                 @   | d S t          |           }t          | t                    rt          d          t	          j        t	          j        |          t          j                  st          d|j                   d| cxk    rdk    sn t          d          d S )NzlTuples are not accepted for the 'axis' parameter. Please pass in one of the following: {-2, -1, 0, 1, None}.zaxis must be an integer, not r   zaxis out of range)
typerv   ri   r   r   rx   r#   ry   rC   r2   )axis	axis_types     r   validateaxisr     s    |T

I $ 1 0 1 1 	1 =),,bj99 NL	8JLLMMM$OOOO!OOOO,--- Or    .c                X   t          |           dk    rt          d          t          |           dk    r[	 t          | d                   }t          d |D                       }nD# t          $ r t	          j        | d                   f}Y nw xY wt          d | D                       }|Pt          |          |vrt          d| d|          t          d	 |D                       rt          d
          nt          |          }d t          |          D             }|s+t          |          }||k    rt          d| d|           nt          |          dk    r|d         }t          |d|         ||dz   d         z             }	t          ||	          \  }
}|dk    r.t          d |D                       }t          d| d|           |d|         |
fz   ||dz   d         z   }nt          d          t          |          |vrt          d| d|          |S )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   >   K   | ]}t          j        |          V  d S rB   r   r   rD   args     r   rE   zcheck_shape.<locals>.<genexpr>  s,      HHchnS11HHHHHHr    c              3   >   K   | ]}t          j        |          V  d S rB   r   r   s     r   rE   zcheck_shape.<locals>.<genexpr>  s,      >>#(.-->>>>>>r    Nzshape must have length in z. Got new_shape=c              3   "   K   | ]
}|d k     V  dS )r   Nrp   )rD   r   s     r   rE   zcheck_shape.<locals>.<genexpr>  s&      ((q1u((((((r    z#'shape' elements cannot be negativec                 $    g | ]\  }}|d k     |S )r   rp   )rD   ir   s      r   
<listcomp>zcheck_shape.<locals>.<listcomp>  s!    HHH$!Q!a%%A%%%r    zcannot reshape array of size z into shape c              3   *   K   | ]}|d k     rdn|V  dS )r   newshapeNrp   )rD   r   s     r   rE   zcheck_shape.<locals>.<genexpr>  s.      !P!PA**1!P!P!P!P!P!Pr    z&can only specify one unknown dimension)r   r   iterri   r   r   r2   r]   r   	enumeratedivmod)r   current_shaper   
shape_iter	new_shapecurrent_sizenegative_indexesnew_sizeskip	specifiedunspecified	remainder	err_shapes                r   check_shaper     s   $ 4yyA~~RSSS
4yyA~~	Id1gJ HHZHHHHHII  	4 	4 	4!Q003III	4
 >>>>>>>	y>>))V(VV)VVWWW((i((((( 	DBCCC	D M** IH)I*>*>HHH 	GIH<''  "< "< "<09"< "< = = = ( !""a''#A&DYuu-	$q&''0BBCCI%+L)%D%D"KA~~!!P!Pi!P!P!PPP	  "< "< "<09"< "< = = =!%4%(K>9Id1fgg<NNIIEFFF
9~~X%%RhRRiRRSSSs   A& &%BBc                  8   | sdS d | D             } t          | t                    }t          |          }| D ]^}||u rt          |t          |                     D ]7\  }}|dk    r,|||         k    r ||         dk    rt	          d          |||<   8_g |R S )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.
    rp   c                 P    g | ]#}t          |t          t          f          r|n|f$S rp   )rv   ri   r   )rD   shps     r   r   z$broadcast_shapes.<locals>.<listcomp>   s1    RRRCZeT]33?cc#RRRr    )key)startr   z-shapes cannot be broadcast to a single shape.)r/   r   r   r   r2   )shapesbig_shpoutr   r   r   s         r   r   r     s    "  rRR6RRRF&c"""G
w--C  '>>c#c((333 	 	DAqAvv!s1v++q6Q;;$%TUUUA		
 S77Nr    c                     |                      dd          }|                      dd          }| r7t          dd                    |                                                      ||fS )a?  Unpack keyword arguments for reshape function.

    This is useful because keyword arguments after star arguments are not
    allowed in Python 2, but star keyword arguments are. This function unpacks
    'order' and 'copy' from the star keyword arguments (with defaults) and
    throws an error for any remaining.
    orderrn   rQ   Fz-reshape() got unexpected keywords arguments: r@   )popr   rH   keys)kwargsr   rQ   s      r   check_reshape_kwargsr     st     JJw$$E::fe$$D 7 699V[[]]336 6 7 7 	7$;r    c                     t          t          j                            d          dd          }|duot	          | |          S )zV
    Check whether object is pydata/sparse matrix, avoiding importing the module.
    sparseSparseArrayN)getattrsysmodulesr   rv   )mbase_clss     r   is_pydata_spmatrixr     s=     s{x00-FFH4;Jq($;$;;r    r   target_formatrV   	accept_fvzsp.spmatrixc                    t          |           rq	 |                     |          } n$# t          $ r |                                 } Y nw xY w||                     |          } n| j        dvr|                                 } | S )z_
    Convert a pydata/sparse array to scipy sparse matrix,
    pass through anything else.
    )r   NrV   )r   to_scipy_sparser   asformatrd   tocsc)r   r   r   s      r   convert_pydata_sparse_to_scipyr   '  s     # 
	(%%	%::CC 	( 	( 	(%%''CCC	($,,}--CCZ~--))++CJs   ( A	A	c                  ^    t          j        | i |                    t           j                  S rB   )r   r'   viewmatrix)r   r   s     r   r   r   D  s'    8T$V$$))")444r    c                     t          | t          j                  r|| j        |k    r| S t          j        | |                              t          j                  S )Nr&   )rv   r   r   r#   r:   r   )rS   r#   s     r   asmatrixr   H  sP    $	"" u9L9L:d%(((--bi888r    c                    t          | t          j        j                  r|                                 S t          | t          j                  r3t          j        |                                 | j	        | j
                  S t          | t          j                  rGt          j        | j
        | j	                  }t          j                            | j        |           |S |                                                                 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&   )rv   sp_data_data_matrix_deduped_data	dok_arrayr   fromitervaluesr#   nnz	lil_arrayempty_csparsetoolslil_flatten_to_arrayrS   tocoo)srS   s     r   _todatar   P  s     !RX*++ !   !R\"" C{188::QWAEBBBB!R\"" xQW---
--afd;;;7799""$$$r    )NN)NF)rp   NF)F)rO   NrB   )B__doc__r   typingr   r   r   r   numpyr   mathr   scipy.sparser   r   scipy._lib._utilr   r   __all__bool_byteubyteshortushortrs   uintclonglong	ulonglongfloat32float64
longdouble	complex64
complex128clongdoubler   r   r	   r$   r)   r6   r>   r
   rw   r   ru   ro   r~   r#   r   r   r   r   r   r   r   r   r   ri   r   r   r   r   r   r   r   r   r   rp   r    r   <module>r     s    


 & & & & & & & & & &                  . . . . . . . .   Hbgrx29bgHgxblJ
BML"-A 
 D D DD  7 7 7  (: : :    <	 	BJ 	 	 	 	 +-( kF kF kF kF\E E E EP bh    :t : : : :
D    ,   $    $;T ; ; ; ;94 9 9 9 9%$ % % % %. . . ..=d = = =uS#X = = = =@  B  "<T < < < < 37 	',//  3	   :5 5 59 9 9 9%"* % % % % % %r    