B
    &]\=                 @   s  d Z ddlmZmZmZ ddlZddlZddlZdddddd	d
ddg	Z	dddddddddddddddgZ
dd e
D Z
i Zdd Zdd  Zd!d" Zd#d$ Zd%d& Zd;d'dZd<d*d+Zd,d Zd-d Zd.d Zd=d/dZd0d	 Zd1d Zd2d
 Zd3d4 Zd>d5d6Zd7d8 ZG d9d: d:eZdS )?z, Utility functions for sparse matrix module
    )divisionprint_functionabsolute_importNupcastgetdtypeisscalarlike	isintlikeisshape
issequenceisdenseismatrixget_sum_dtypeboolZint8Zuint8ZshortZushortintcZuintcZlonglongZ	ulonglongZsingleZdoubleZ
longdoubleZcsingleZcdoubleZclongdoublec             C   s   g | ]}t j| qS  )npZtypeDict).0xr   r   3lib/python3.7/site-packages/scipy/sparse/sputils.py
<listcomp>   s    r   c              G   sb   t t| }|dk	r|S t| g }x(tD ] }t||r,|t t| < |S q,W td| f 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
    --------

    >>> 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: %r)_upcast_memogethashr   Zfind_common_typesupported_dtypescan_cast	TypeError)argstr   r   r   r   r      s    
c              G   s2   t | }|dk	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_char7   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   Zarrayr   )r   Zscalarr   r   r   upcast_scalarA   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_indexH   s    
$r+   c             C   s   t j| | jddS )NZnative)r   )r   asarrayr   Znewbyteorder)Ar   r   r   	to_native\   s    r.   c             C   sh   | dkrFy
|j }W qd tk
rB   |dk	r6t |}ntdY qdX nt | }|tjkrdtd |S )aS  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_warningswarn)r   adefaultZnewdtyper   r   r   r   `   s    



r   Fc             C   s   t t jj}t t jj}t j}|dk	r8||kr8t j}t| t jrJ| f} xr| D ]j}t 	|}t 
|jt jsP|r|jdkrqPn2t |jt jr| }| }||kr||krqPt j}P qPW |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   r&   Zint32r%   r$   r   Zint64
isinstancendarrayr,   r   r   r#   
issubdtypeinteger)Zarraysr)   Zcheck_contentsZint32minZint32maxr   r(   r*   r   r   r   get_index_dtypex   s,    


r8   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uintZint_)r   r   r   r   r      s
    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)r   r   r   r   r      s    c             C   s|   t | dkrdS yt|  W nV ttfk
rv   ytt| | k}W n ttfk
r`   dS X |rrt	dt
 |S X 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   Fz3Inexact indices into sparse matrices are deprecatedT)r   r<   operatorindexr   r'   r   intr0   r1   DeprecationWarning)r   Z	loose_intr   r   r   r      s    c             C   sn   y| \}}W n t k
r    dS X t|rft|rft|dkrft|dkrf|rb|dkrf|dkrfdS dS dS )zjIs x a valid 2-tuple of dimensions?

    If nonneg, also checks that the dimensions are non-negative.
    Fr   TN)	Exceptionr   r   r<   )r   ZnonnegMNr   r   r   r	      s    c             C   s>   t | ttfr(t| dkp<t| d p<t | tjo<| jdkS )Nr      )r4   listtuplelenr   r;   r5   r<   )r   r   r   r   r
      s    c             C   s<   t | ttfr&t| dkr&t| d p:t | tjo:| jdkS )Nr      )r4   rE   rF   rG   r
   r   r5   r<   )r   r   r   r   r      s    c             C   s   t | tjS )N)r4   r   r5   )r   r   r   r   r      s    c             C   sh   | d k	rdt | }|tkr tdtt|tjsFtdj|jdd|   krZdksdn 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 {name})namerD   zaxis out of range)
typerF   r   r   r6   r   r7   format__name__r'   )ZaxisZ	axis_typer   r   r   validateaxis   s    rN   c             C   s  t | dkrtdnht | dkrlyt| d }W n$ tk
rV   t| d f}Y q~X tdd |D }ntdd | D }|dkrt |dkrtd	n |d dk s|d dk rtd
nDtj|t	d}dd t
|D }t |dkrtj|t	d}||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tdd |D }t |dkrd}nt |dkrd|d f}t |dkrtd|S )z0Imitate numpy.matrix handling of shape argumentsr   z8function missing 1 required positional argument: 'shape'rD   c             s   s   | ]}t |V  qd S )N)r=   r>   )r   argr   r   r   	<genexpr>  s    zcheck_shape.<locals>.<genexpr>c             s   s   | ]}t |V  qd S )N)r=   r>   )r   rO   r   r   r   rP     s    NrH   z,shape must be a 2-tuple of positive integersz#'shape' elements cannot be negative)r   c             S   s   g | ]\}}|d k r|qS )r   r   )r   ir   r   r   r   r   $  s    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   r   r   r   r   rP   /  s    z&can only specify one unknown dimensionc             s   s   | ]}|d kr|V  qdS )rD   Nr   )r   rO   r   r   r   rP   8  s    )rD   rD   zshape too large to be a matrix)rG   r   iterr=   r>   rF   r'   r   Zprodr?   	enumeraterL   divmod)r   Zcurrent_shapeZ
shape_iterZ	new_shapeZcurrent_sizeZnegative_indexesZnew_sizeskipZ	specifiedZunspecifiedZ	remainderZ	err_shaper   r   r   check_shape
  sP    


"

$rV   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CcopyFz/reshape() got unexpected keywords arguments: {}z, )popr   rL   joinkeys)kwargsrW   rY   r   r   r   check_reshape_kwargsE  s    	r^   c               @   s@   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dS )
IndexMixinzT
    This class simply exists to hold the methods necessary for fancy indexing.
    c             C   s   | |\}}}t|||S )zT Given a slice object, use numpy arange to change it to a 1D
        array.
        )indicesr   Zarange)selfjshapestartstopstepr   r   r   _slicetoarangeZ  s    zIndexMixin._slicetoarangec             C   s   ddl m} t||tjfr:|jdkr:|jjdkr:| S | 	|}t|t
rt|dkrd|\}}qt|dkr|d td }}qtdn|td }}| ||\}}||fS )z Parse index. Always return a tuple of the form (row, col).
        Where row/col is a integer, slice, or array of integers.
        rD   )spmatrixrH   br   Nzinvalid number of indices)baserh   r4   r   r5   r<   r   r:   nonzero_check_ellipsisrF   rG   slice
IndexError_check_boolean)ra   r>   rh   rowcolr   r   r   _unpack_indexa  s    



zIndexMixin._unpack_indexc             C   s0  |t krtdtdfS t|tr,x&t|D ]\}}|t kr.|}P q.W d}|dk	r,t|dkrrtdtdfS t|dkr|dkr|d t krtdtdfS td|d fS n|d tdfS d}x*||d d D ]}|t k	r||f }qW |t| }tdd| }|d| tdf|  | S |S )z6Process indices with Ellipsis. Returns modified index.NrD   rH   r   r   )Ellipsisrm   r4   rF   rS   rG   r$   )ra   r>   rb   vZfirst_ellipsistailZndZnslicer   r   r   rl   }  s2    
zIndexMixin._check_ellipsisc             C   sp   ddl m} ||s||r$tdt|tjrF|jjdkrF| |}t|tjrh|jjdkrh| |}||fS )NrD   )
isspmatrixzoIndexing with sparse matrices is not supported except boolean indexing where matrix and index are equal shapes.ri   )	rj   rv   rn   r4   r   r5   r   r:   _boolean_index_to_array)ra   rp   rq   rv   r   r   r   ro     s    

zIndexMixin._check_booleanc             C   s   |j dkrtd| d S )NrD   zinvalid index shaper   )r<   rn   rk   )ra   rQ   r   r   r   rw     s    
z"IndexMixin._boolean_index_to_arrayc             C   sn  |  ||\}}t|t}|r>| || jd d d d f }n
t|}t|tr| || jd d d d f }|jdkr|d d d f }n|stdnzt	|rt|}|jdkrt
||\}}|d d d f }|d d d f }||fS n$t|}|r|jdkrtdt
||\}}|jdkrR|d d d f }|d d d f }n|jdkrftd||fS )Nr   rD   zindex returns 3-dim structurerH   zIndex dimension must be <= 2)ro   r4   rm   rg   rc   r   Z
atleast_1dr<   rn   r   Zbroadcast_arrays)ra   rQ   rb   Zi_slicer   r   r   _index_to_arrays  s8    
 







zIndexMixin._index_to_arraysN)
rM   
__module____qualname____doc__rg   rr   rl   ro   rw   rx   r   r   r   r   r_   V  s   &r_   )NN)r   NF)F)N)r{   Z
__future__r   r   r   r=   r0   Znumpyr   __all__r   r   r   r    r!   r+   r.   r   r8   r   r   r   r	   r
   r   r   rN   rV   r^   objectr_   r   r   r   r   <module>   s:   
"


5	

;