a
    CCCf8                     @   s  d Z ddlZddlmZ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d Z$d	d
 Z%dd Z&dd Z'dd Z(d>ddZ)d?e	j*dddZ+d@ddZ,e	j-e	j-dddZ.e/dddZ0e/ddd Z1dAdd!e/dd"d#Z2e/dd$d%Z3e/dd&d'Z4e/dd(d)Z5ddd*d+Z6dBdd!e7e8d,f dd-d.Z9d/d0 Z:e/dd1d2Z;dCeeed3  eed4f d5d6d7Z<d8d9 Z=dDd:d;Z>e	j*dd<d=Z?dS )Ez, Utility functions for sparse matrix module
    N)AnyLiteralOptionalUnion)prod)np_longnp_ulong)
upcastgetdtypegetdataisscalarlike	isintlikeisshape
issequenceisdenseismatrixget_sum_dtypec                  G   s`   t t| }|dur|S tj|  }tD ]$}t||r(|t t| < |  S q(td| dS )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')
    <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npZresult_typesupported_dtypescan_cast	TypeError)argstr	    r   Q/var/www/html/django/DPS/env/lib/python3.9/site-packages/scipy/sparse/_sputils.pyr	      s    

r	   c                  G   s2   t | }|dur|S tttj|  }|t | < |S )z9Same as `upcast` but taking dtype.char as input (faster).N)r   r   r	   mapr   dtype)r   r   r   r   r   upcast_char:   s    
r    c                 C   s   t jdg| d| jS )z`Determine data type for binary operation between an array of
    type `dtype` and a scalar.
    r   r   )r   arrayr   )r   Zscalarr   r   r   upcast_scalarD   s    r#   c                 C   sx   | j jt tjjkrt| jdkr,| tjS |  }|  }|ttjjks`|ttjjk rht	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   ZintpsizeZastypemaxminiinfo
ValueError)arrmaxvalminvalr   r   r   downcast_intp_indexK   s    
$r-   c                 C   s$   | j }|jr| S tj| |d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   Zisnativer   asarrayZnewbyteorder)Adtr   r   r   	to_native_   s    r2   c              
   C   sx   | du rXz
|j }W qt tyT } z*|dur6t |}n
td|W Y d}~qtd}~0 0 nt | }|tjkrtt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   Zobject_r)   )r   adefaultZnewdtypeer   r   r   r
   o   s    
"

r
   F)returnc                 C   s   t j| ||d}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   r8   datar   r   r   r      s    
r   r   c                 C   s   t t t jj}t t t jj}t  jdkr<t jnt j}|durbt |}||krbt j}t| t j	rt| f} | D ]l}t 
|}t |jt jsx|r|jdkrqxn2t |jt jr| }| }||kr||krqxt j} qqx|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   Zint32r(   r'   r&   intcr$   Zint64
isinstancendarrayr/   r   r   r%   
issubdtypeinteger)Zarraysr+   Zcheck_contentsZint32minZint32maxr   r*   r,   r   r   r   get_index_dtype   s.    


rA   )r   r7   c                 C   s6   | j dkrt| tjrtjS t| tjr2tjS | S )z Mimic numpy's casting for np.sumu)kindr   r   Zuintint_r!   r   r   r   r      s
    r   c                 C   s   t | pt| o| jdkS )z8Is x either a scalar, an array scalar, or a 0-dim array?r   )r   isscalarr   ndimxr   r   r   r      s    r   c                 C   s   t | dkrdS zt|  W nZ ttfyz   ztt| | k}W n ttfy`   Y Y dS 0 |rrd}t|| Y S 0 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   rF   operatorindexr   r)   boolint)rH   Z	loose_intmsgr   r   r   r      s    

r   )allow_1dc                C   sN   t | }|dkr |r|dks dS | D ]$}t|s6 dS |r$|dk r$ dS q$dS )zIs x a valid tuple of dimensions?

    If nonneg, also checks that the dimensions are non-negative.
    If allow_1d, shapes of length 1 or 2 are allowed.
          Fr   T)lenr   )rH   ZnonnegrN   rF   dr   r   r   r      s    r   c                 C   s>   t | ttfr(t| dkp<t| d p<t | tjo<| jdkS )Nr   rP   )r=   listtuplerQ   r   rE   r>   rF   r   r   r   r   r     s
    r   c                 C   s<   t | ttfr&t| dkr&t| d p:t | tjo:| jdkS )Nr   rO   )r=   rS   rT   rQ   r   r   r>   rF   rU   r   r   r   r     s    

r   c                 C   s   t | tjS N)r=   r   r>   rG   r   r   r   r     s    r   c                 C   sj   | d u rd S t | }|tkr$tdtt|tjsHtd|j d|   kr\dksfn 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 rP   zaxis out of range)	typerT   r   r   r?   r   r@   __name__r)   )ZaxisZ	axis_typer   r   r   validateaxis  s    rZ   .c                C   s  t | dkrtdt | dkrhzt| d }W n" tyR   t| d f}Y qz0 tdd |D }ntdd | D }|du r|rt |dvrtd	nt |d
krtdtdd |D rtdnt|}dd t	|D }|st|}||krtd
||nt |dkr|d }t|d| ||d d  }	t||	\}
}|dkrtdd |D }td
|||d| |
f ||d d  }ntdt |d
kr|rt |dkstd|S )au  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_1d : bool, optional
        If True, then 1-D or 2-D arrays are accepted.
        If False (default), then only 2-D arrays are accepted and an error is
        raised otherwise.

    Returns
    -------
    new_shape: tuple
        The new shape after validation.
    r   z8function missing 1 required positional argument: 'shape'rP   c                 s   s   | ]}t |V  qd S rV   rI   rJ   .0argr   r   r   	<genexpr>E      zcheck_shape.<locals>.<genexpr>c                 s   s   | ]}t |V  qd S rV   r[   r\   r   r   r   r_   G  r`   N)rP   rO   z2shape must be a 1- or 2-tuple of positive integersrO   z,shape must be a 2-tuple of positive integersc                 s   s   | ]}|d k V  qdS )r   Nr   )r]   rR   r   r   r   r_   P  r`   z#'shape' elements cannot be negativec                 S   s   g | ]\}}|d k r|qS )r   r   )r]   irH   r   r   r   
<listcomp>W  r`   zcheck_shape.<locals>.<listcomp>z-cannot reshape array of size {} into shape {}c                 s   s   | ]}|d k rdn|V  qdS )r   ZnewshapeNr   )r]   rH   r   r   r   r_   b  r`   z&can only specify one unknown dimensionz$matrix shape must be two-dimensional)rQ   r   iterrI   rJ   rT   r)   anyr   	enumerateformatdivmod)r   Zcurrent_shaperN   Z
shape_iterZ	new_shapeZcurrent_sizeZnegative_indexesnew_sizeskipZ	specifiedunspecified	remainderZ	err_shaper   r   r   check_shape(  sN    


 
$"rl   c                 C   s<   |  dd}|  dd}| r4t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Cr8   Fz/reshape() got unexpected keywords arguments: {}z, )popr   rf   joinkeys)kwargsrm   r8   r   r   r   check_reshape_kwargso  s    	rs   c                 C   s&   t tjddd}|duo$t| |S )zV
    Check whether object is pydata/sparse matrix, avoiding importing the module.
    sparseZSparseArrayN)getattrsysmodulesr   r=   )mbase_clsr   r   r   is_pydata_spmatrix  s    rz   ZcscZcsrzsp.spmatrix)r^   target_formatr7   c                 C   s:   t | r6|  } |dur$| |} n| jdvr6|  } | S )z_
    Convert a pydata/sparse array to scipy sparse matrix,
    pass through anything else.
    Nr{   )rz   Zto_scipy_sparseZasformatrf   Ztocsc)r^   r|   r   r   r   convert_pydata_sparse_to_scipy  s    
r}   c                  O   s   t j| i |t jS rV   )r   r"   viewmatrix)r   rr   r   r   r   r     s    r   c                 C   s8   t | tjr"|d u s| j|kr"| S tj| |dtjS )Nr!   )r=   r   r   r   r/   r~   )r:   r   r   r   r   asmatrix  s    r   c                 C   sx   t | tjjr|  S t | tjr:tj|  | j	| j
dS t | tjrltj| j
| j	d}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!   )r=   sp_dataZ_data_matrixZ_deduped_dataZ	dok_arrayr   Zfromitervaluesr   ZnnzZ	lil_arrayemptyZ_csparsetoolsZlil_flatten_to_arrayr:   Ztocoo)sr:   r   r   r   _todata  s    r   )NN)NF)r   NF)F)N)N)N)@__doc__rv   typingr   r   r   r   rI   numpyr   mathr   Zscipy.sparsert   r   Zscipy._lib._utilr   r   __all__Zbool_byteZubyteshortZushortr<   ZuintcZlonglongZ	ulonglongZfloat32Zfloat64Z
longdoubleZ	complex64Z
complex128Zclongdoubler   r   r	   r    r#   r-   r2   r
   r>   r   rA   r   r   rK   r   r   r   r   r   r   rZ   rT   rL   rl   rs   rz   r}   r   r   r   r   r   r   r   <module>   sR   "


7	G	 

