
    9=e2                        d Z ddl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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%d dZ&d Z'de(fdZ)de(fdZ*d!de(fdZ+de(fdZ,de(fdZ-de(fdZ.d"dZ/d#dZ0d Z1de(fdZ2d Z3d#dZ4dej$        fdZ5dS )$z, Utility functions for sparse matrix module
    N)prod)
upcastgetdtypegetdataisscalarlike	isintlikeisshape
issequenceisdenseismatrixget_sum_dtypec                     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
    --------

    >>> upcast('int32')
    <type 'numpy.int32'>
    >>> upcast('bool')
    <type 'numpy.bool_'>
    >>> upcast('int32','float32')
    <type 'numpy.float64'>
    >>> upcast('bool',complex,float)
    <type 'numpy.complex128'>

    Nz#no supported conversion for types: )_upcast_memogethashnpresult_typesupported_dtypescan_cast	TypeError)argstr   s      5lib/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   8   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#   B   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_indexr0   I   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_nativer8   ]   s=     
B	{  :arx889999r   c                     | G	 |j         }nq# t          $ r1}|t          j         |          }nt          d          |Y d}~n;d}~ww xY wt          j         |           }|t          j        k    rt          d          |S )aQ  Function used to simplify argument processing. If 'dtype' is not
    specified (is None), returns a.dtype; otherwise returns a np.dtype
    object created from the specified dtype argument. If 'dtype' and 'a'
    are both None, construct a data type out of the 'default' parameter.
    Furthermore, 'dtype' must be in 'allowed' set.
    Nzcould not interpret data typez0object dtype is not supported by sparse matrices)r   AttributeErrorr   r   object_r,   )r   adefaultnewdtypees        r   r   r   m   s     }	HwHH 	H 	H 	H"8G,, ?@@aG 	H 8E??rz!!B   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   rB   datas       r   r   r      s1    
 8Cu4000D TZKr    c                 0   t          j        t          j        t           j                  j                  }t          j        t          j        t           j                  j                  }t          j                    j        dk    rt           j        nt           j        }|&t          j        |          }||k    rt           j        }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        } n|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)

       Nr   )r   int32r+   r*   r)   intcr%   int64
isinstancendarrayr4   r   r   r'   
issubdtypeinteger)arraysr.   check_contentsint32minint32maxr   r-   r/   s           r   get_index_dtyperS      sP   , x**.//Hx**.//H 		*a//BHHRXE&!!HHE&"*%%   joo{39bh// 	 	!8q==]39bj99 ! WWYYF WWYYF))f.@.@ HEE	 Lr   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      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      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   r,   boolint)r]   	loose_intmsgs      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c                 |    t          |           }|s|dk    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.
    If allow_ndim, shapes of any dimensionality are allowed.
       Fr   T)lenr   )r]   nonneg
allow_ndimr[   ds        r   r	   r	      se     q66D $!))u  || 	55 	a!ee554r   c                     t          | t          t          f          r-t          |           dk    pt	          j        | d                   p$t          | t          j                  o
| j        dk    S )Nr      )rK   listtuplerg   r   rZ   rL   r[   r   s    r   r
   r
      s\    D%=)) /VVq[-BK!--:2:&&8AFaK;r   c                     t          | t          t          f          r(t          |           dk    rt	          | d                   p$t          | t
          j                  o
| j        dk    S )Nr   rf   )rK   rm   rn   rg   r
   r   rL   r[   ro   s    r   r   r     s]    D%=)) -VVaZ-&qt,,82:&&616Q;9r   c                 6    t          | t          j                  S N)rK   r   rL   r\   s    r   r   r     s    a$$$r   c                 ,   | d S t          |           }|t          k    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 rl   zaxis out of range)	typern   r   r   rM   r   rN   __name__r,   )axis	axis_types     r   validateaxisry     s    |T

I E 0 1 1 	1 =),,bj99 NL	8JLLMMM$OOOO!OOOO,--- Or   c                    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                       }|Lt          |          dk    rt          d          t          d	 |D                       rt          d
          n$t          |          }d t          |          D             }|s9t          |          }||k    r#t          d
                    ||                    nt          |          dk    r|d         }t          |d|         ||dz   d         z             }t          ||          \  }	}
|
dk    r<t          d |D                       }t          d
                    ||                    |d|         |	fz   ||dz   d         z   }nt          d          t          |          dk    rt          d          |S )z0Imitate numpy.matrix handling of shape argumentsr   z8function missing 1 required positional argument: 'shape'rl   c              3   >   K   | ]}t          j        |          V  d S rr   r_   r`   .0args     r   	<genexpr>zcheck_shape.<locals>.<genexpr>1  s,      HHchnS11HHHHHHr   c              3   >   K   | ]}t          j        |          V  d S rr   r|   r}   s     r   r   zcheck_shape.<locals>.<genexpr>3  s,      >>#(.-->>>>>>r   Nrf   z,shape must be a 2-tuple of positive integersc              3   "   K   | ]
}|d k     V  dS )r   NrE   )r~   rj   s     r   r   zcheck_shape.<locals>.<genexpr>8  s&      **1Q******r   z#'shape' elements cannot be negativec                 $    g | ]\  }}|d k     |S )r   rE   )r~   ir]   s      r   
<listcomp>zcheck_shape.<locals>.<listcomp>?  s!    HHH$!Q!a%%A%%%r   z-cannot reshape array of size {} into shape {}c              3   *   K   | ]}|d k     rdn|V  dS )r   newshapeNrE   )r~   r]   s     r   r   zcheck_shape.<locals>.<genexpr>J  s.      !P!PA**1!P!P!P!P!P!Pr   z&can only specify one unknown dimensionz$matrix shape must be two-dimensional)rg   r   iterrn   r_   r`   r,   anyr   	enumerateformatdivmod)r   current_shape
shape_iter	new_shapecurrent_sizenegative_indexesnew_sizeskip	specifiedunspecified	remainder	err_shapes               r   check_shaper   &  s   
4yyA~~ " # # 	#
4yyA~~	Id1gJ HHZHHHHHII  	4 	4 	4!Q003III	4
 >>>>>>>	y>>QKLLL**	***** 	DBCCC	D M** IH)I*>*>HHH 	GIH<'' !P"(&y"A"AC C C ( !""a''#A&DYuu-	$q&''0BBCCI%+L)%D%D"KA~~!!P!Pi!P!P!PPP	  "$$*F<$C$CE E E!%4%(K>9Id1fgg<NNIIEFFF
9~~?@@@s   A& &%BBc                     |                      dd          }|                      dd          }| rGt          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.
    orderCrB   Fz/reshape() got unexpected keywords arguments: {}z, )popr   r   joinkeys)kwargsr   rB   s      r   check_reshape_kwargsr   W  sr     JJw$$E::fe$$D ;I		&++-- 8 899; ; 	;$;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   rK   )mbase_clss     r   is_pydata_spmatrixr   h  s=     s{x00-FFH4;Jq($;$;;r   c                  ^    t          j        | i |                    t           j                  S rr   )r   r!   viewmatrix)r   r   s     r   r   r   v  s'    8T$V$$))")444r   c                     t          | t          j                  r|| j        |k    r| S t          j        | |                              t          j                  S )Nr    )rK   r   r   r   r4   r   )rD   r   s     r   asmatrixr   z  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    )rK   sp_data_data_matrix_deduped_data	dok_arrayr   fromitervaluesr   nnz	lil_arrayempty_csparsetoolslil_flatten_to_arrayrD   tocoo)srD   s     r   _todatar     s     !RX*++ !   !R\"" C{188::QWAEBBBB!R\"" xQW---
--afd;;;7799""$$$r   )NN)NF)rE   NF)FF)r@   Nrr   )6__doc__r   r_   numpyr   mathr   scipy.sparser   r   __all__bool_byteubyteshortushortrI   uintcrX   rW   longlong	ulonglongsingledouble
longdoublecsinglecdoubleclongdoubler   r   r   r   r#   r0   r8   r   rL   r   rS   r   ra   r   r   r	   r
   r   r   ry   r   r   r   r   r   r   rE   r   r   <module>r      s    


                 L L L Hbgrx29bgHbgrwR\IryM2:rz2>K 
 D D DD  7 7 7  (: : :    4	 	BJ 	 	 	 	4 4 4 4n  :t : : : :
D    , $    ";T ; ; ; ;94 9 9 9 9%$ % % % %. . . ... . . .b  "<T < < < <5 5 59 9 9 9%"* % % % % % %r   