B
    T\G?              
   @   s  d dl mZmZmZ d dlmZ d dlZd dlZye	 p e
ejddddejdddejdre
ejdd	d
ddre
edddsedejZejjZW dQ R X W n: ek
r   d$ddZejjeejj d dZY nX eejdk rdd Zd%ddZd&ddZeejdk r:dd Zdd Zdd Zdd Zeejed ksreejed!krxeZneZG d"d# d#eZdS )'    )absolute_importdivisionprint_function)LooseVersionNg?   Zunsafe)casting)r   dtypeg      ?Zi8)r      zIDivide not working with dtype: https://github.com/numpy/numpy/issues/3484c             C   s$   t | ||}|dk	r ||}|S )zImplementation of numpy.divide that works with dtype kwarg.

        Temporary compatibility fix for a bug in numpy's version. See
        https://github.com/numpy/numpy/issues/3484 for the relevant issue.N)npdivideZastype)Zx1Zx2outr   x r   6lib/python3.7/site-packages/dask/array/numpy_compat.pyr      s    
r   z1.12.0c             C   sh   t | tj }|rt| } t| jjtjs4| dfS |sFtj| dd} t| }tj	| ||d | |fS )a  
        If `a` is of inexact type, make a copy of `a`, replace NaNs with
        the `val` value, and return the copy together with a boolean mask
        marking the locations where NaNs were present. If `a` is not of
        inexact type, do nothing and return `a` together with a mask of None.

        Note that scalars will end up as array scalars, which is important
        for using the result as the value of the out argument in some
        operations.

        Parameters
        ----------
        a : array-like
            Input array.
        val : float
            NaN values are set to val before doing the operation.

        Returns
        -------
        y : ndarray
            If `a` is of inexact type, return a copy of `a` with the NaNs
            replaced by the fill value, otherwise return `a`.
        mask: {bool, None}
            If `a` is of inexact type, return a boolean mask marking locations of
            NaNs, otherwise return None.

        NT)Zsubok)where)

isinstancer
   ZndarrayZarray
issubclassr   typeZinexactZisnanZcopyto)avalZis_newmaskr   r   r   _replace_nan+   s    

r   c             C   s    t | d\} }tj| |||dS )a  
        Return the cumulative sum of array elements over a given axis treating Not a
        Numbers (NaNs) as zero.  The cumulative sum does not change when NaNs are
        encountered and leading NaNs are replaced by zeros.

        Zeros are returned for slices that are all-NaN or empty.

        .. versionadded:: 1.12.0

        Parameters
        ----------
        a : array_like
            Input array.
        axis : int, optional
            Axis along which the cumulative sum is computed. The default
            (None) is to compute the cumsum over the flattened array.
        dtype : dtype, optional
            Type of the returned array and of the accumulator in which the
            elements are summed.  If `dtype` is not specified, it defaults
            to the dtype of `a`, unless `a` has an integer dtype with a
            precision less than that of the default platform integer.  In
            that case, the default platform integer is used.
        out : ndarray, optional
            Alternative output array in which to place the result. It must
            have the same shape and buffer length as the expected output
            but the type will be cast if necessary. See `doc.ufuncs`
            (Section "Output arguments") for more details.

        Returns
        -------
        nancumsum : ndarray.
            A new array holding the result is returned unless `out` is
            specified, in which it is returned. The result has the same
            size as `a`, and the same shape as `a` if `axis` is not None
            or `a` is a 1-d array.

        See Also
        --------
        :func:`numpy.cumsum` : Cumulative sum across array propagating NaNs.
        isnan : Show which elements are NaN.

        Examples
        --------
        >>> nancumsum(1)
        array([1])
        >>> nancumsum([1])
        array([1])
        >>> nancumsum([1, np.nan])
        array([ 1.,  1.])
        >>> a = np.array([[1, 2], [3, np.nan]])
        >>> nancumsum(a)
        array([ 1.,  3.,  6.,  6.])
        >>> nancumsum(a, axis=0)
        array([[ 1.,  2.],
               [ 4.,  2.]])
        >>> nancumsum(a, axis=1)
        array([[ 1.,  3.],
               [ 3.,  3.]])

        r   )axisr   r   )r   r
   Zcumsum)r   r   r   r   r   r   r   r   	nancumsumT   s    =r   c             C   s    t | d\} }tj| |||dS )a  
        Return the cumulative product of array elements over a given axis treating Not a
        Numbers (NaNs) as one.  The cumulative product does not change when NaNs are
        encountered and leading NaNs are replaced by ones.

        Ones are returned for slices that are all-NaN or empty.

        .. versionadded:: 1.12.0

        Parameters
        ----------
        a : array_like
            Input array.
        axis : int, optional
            Axis along which the cumulative product is computed.  By default
            the input is flattened.
        dtype : dtype, optional
            Type of the returned array, as well as of the accumulator in which
            the elements are multiplied.  If *dtype* is not specified, it
            defaults to the dtype of `a`, unless `a` has an integer dtype with
            a precision less than that of the default platform integer.  In
            that case, the default platform integer is used instead.
        out : ndarray, optional
            Alternative output array in which to place the result. It must
            have the same shape and buffer length as the expected output
            but the type of the resulting values will be cast if necessary.

        Returns
        -------
        nancumprod : ndarray
            A new array holding the result is returned unless `out` is
            specified, in which case it is returned.

        See Also
        --------
        :func:`numpy.cumprod` : Cumulative product across array propagating NaNs.
        isnan : Show which elements are NaN.

        Examples
        --------
        >>> nancumprod(1)
        array([1])
        >>> nancumprod([1])
        array([1])
        >>> nancumprod([1, np.nan])
        array([ 1.,  1.])
        >>> a = np.array([[1, 2], [3, np.nan]])
        >>> nancumprod(a)
        array([ 1.,  2.,  6.,  6.])
        >>> nancumprod(a, axis=0)
        array([[ 1.,  2.],
               [ 3.,  2.]])
        >>> nancumprod(a, axis=1)
        array([[ 1.,  2.],
               [ 3.,  3.]])

        r   )r   r   r   )r   r
   Zcumprod)r   r   r   r   r   r   r   r   
nancumprod   s    :r   z1.15.0c       	      C   s   t |jt jstdt| |jkr.tdd|j }tt	|d g tt	|d |j }g }x`t
|| D ]R\}}|d kr|| qn|d | d ||d d   }|t || qnW t|S )Nz"`indices` must be an integer arrayz;`indices` and `arr` must have the same number of dimensions)r   r   ))r
   Z
issubdtyper   Zinteger
IndexErrorlenndim
ValueErrorlistrangezipappendZarangeZreshapetuple)		arr_shapeindicesr   Z
shape_onesZ	dest_dimsZfancy_indexZdimnZ	ind_shaper   r   r   _make_along_axis_idx   s    
 r(   c             C   sF   |dkr| j } t| f}d}n|dk r0| j| }| j}| t||| S )a  
        Take values from the input array by matching 1d index and data slices.
        This iterates over matching 1d slices oriented along the specified axis in
        the index and data arrays, and uses the former to look up values in the
        latter. These slices can be different lengths.
        Functions returning an index along an axis, like `argsort` and
        `argpartition`, produce suitable indices for this function.
        .. versionadded:: 1.15.0
        Parameters
        ----------
        arr: ndarray (Ni..., M, Nk...)
            Source array
        indices: ndarray (Ni..., J, Nk...)
            Indices to take along each 1d slice of `arr`. This must match the
            dimension of arr, but dimensions Ni and Nj only need to broadcast
            against `arr`.
        axis: int
            The axis to take 1d slices along. If axis is None, the input array is
            treated as if it had first been flattened to 1d, for consistency with
            `sort` and `argsort`.
        Returns
        -------
        out: ndarray (Ni..., J, Nk...)
            The indexed result.
        Notes
        -----
        This is equivalent to (but faster than) the following use of `ndindex` and
        `s_`, which sets each of ``ii`` and ``kk`` to a tuple of indices::
            Ni, M, Nk = a.shape[:axis], a.shape[axis], a.shape[axis+1:]
            J = indices.shape[axis]  # Need not equal M
            out = np.empty(Nk + (J,) + Nk)
            for ii in ndindex(Ni):
                for kk in ndindex(Nk):
                    a_1d       = a      [ii + s_[:,] + kk]
                    indices_1d = indices[ii + s_[:,] + kk]
                    out_1d     = out    [ii + s_[:,] + kk]
                    for j in range(J):
                        out_1d[j] = a_1d[indices_1d[j]]
        Equivalently, eliminating the inner loop, the last two lines would be::
                    out_1d[:] = a_1d[indices_1d]
        See Also
        --------
        take : Take along an axis, using the same indices for every 1d slice
        put_along_axis :
            Put values into the destination array by matching 1d index and data slices
        Examples
        --------
        For this sample array
        >>> a = np.array([[10, 30, 20], [60, 40, 50]])

        We can sort either by using sort directly, or argsort and this function
        >>> np.sort(a, axis=1)
        array([[10, 20, 30],
               [40, 50, 60]])
        >>> ai = np.argsort(a, axis=1); ai
        array([[0, 2, 1],
               [1, 2, 0]])
        >>> take_along_axis(a, ai, axis=1)
        array([[10, 20, 30],
               [40, 50, 60]])

        The same works for max and min, if you expand the dimensions:
        >>> np.expand_dims(np.max(a, axis=1), axis=1)
        array([[30],
               [60]])
        >>> ai = np.expand_dims(np.argmax(a, axis=1), axis=1)
        >>> ai
        array([[1],
               [0]])
        >>> take_along_axis(a, ai, axis=1)
        array([[30],
               [60]])

        If we want to get the max and min at the same time,
        we can stack the indices first:
        >>> ai_min = np.expand_dims(np.argmin(a, axis=1), axis=1)
        >>> ai_max = np.expand_dims(np.argmax(a, axis=1), axis=1)
        >>> ai = np.concatenate([ai_min, ai_max], axis=1)
        >>> ai
        array([[0, 1],
               [1, 0]])
        >>> take_along_axis(a, ai, axis=1)
        array([[10, 30],
               [40, 60]])
        Nr   )Zflatr   r   shaper(   )Zarrr&   r   r%   r   r   r   take_along_axis   s    W

r*   c                s6   | fdd|D  fdd|D  j d}t|S )Nc                s   g | ]} j | d  qS )r   )fields).0name)r   r   r   
<listcomp>[  s    z/_make_sliced_dtype_np_ge_16.<locals>.<listcomp>c                s   g | ]} j | d  qS )r   )r+   )r,   r-   )r   r   r   r.   \  s    )namesZformatsZoffsetsitemsize)r0   r
   r   )r   indexnewr   )r   r   _make_sliced_dtype_np_ge_16Q  s
    	
r3   c                s   t  fdd|D }|S )Nc                s   g | ]}| | fqS r   r   )r,   r-   )r   r   r   r.   d  s    z/_make_sliced_dtype_np_lt_14.<locals>.<listcomp>)r
   r   )r   r1   Zdtr   )r   r   _make_sliced_dtype_np_lt_14b  s    r4   z1.16.0z1.14.0c               @   s>   e Zd ZdZdd Zdd dd dd fdd	ZdddZdS )	_Recurserz;
    Utility class for recursing over nested iterables
    c             C   s
   || _ d S )N)
recurse_if)selfr6   r   r   r   __init__x  s    z_Recurser.__init__c             K   s   | S )Nr   )r   kwargsr   r   r   <lambda>}  s    z_Recurser.<lambda>c             K   s   | S )Nr   )r   r9   r   r   r   r:   ~  s    c              K   s   | S )Nr   )r9   r   r   r   r:     s    c                s     fdd  |f|S )a{  
        Iterate over the nested list, applying:
        * ``f_map`` (T -> U) to items
        * ``f_reduce`` (Iterable[U] -> U) to mapped items

        For instance, ``map_reduce([[1, 2], 3, 4])`` is::

            f_reduce([
              f_reduce([
                f_map(1),
                f_map(2)
              ]),
              f_map(3),
              f_map(4)
            ]])


        State can be passed down through the calls with `f_kwargs`,
        to iterables of mapped items. When kwargs are passed, as in
        ``map_reduce([[1, 2], 3, 4], **kw)``, this becomes::

            kw1 = f_kwargs(**kw)
            kw2 = f_kwargs(**kw1)
            f_reduce([
              f_reduce([
                f_map(1), **kw2)
                f_map(2,  **kw2)
              ],      **kw1),
              f_map(3, **kw1),
              f_map(4, **kw1)
            ]],     **kw)
        c                s@    | s| f|S f |  fdd| D f|S d S )Nc             3   s   | ]} |fV  qd S )Nr   )r,   xi)fnext_kwargsr   r   	<genexpr>  s   z2_Recurser.map_reduce.<locals>.f.<locals>.<genexpr>)r6   )r   r9   )r<   f_kwargsf_mapf_reducer7   )r=   r   r<     s    

z_Recurser.map_reduce.<locals>.fr   )r7   r   r@   rA   r?   r9   r   )r<   r?   r@   rA   r7   r   
map_reduce{  s    &	z_Recurser.map_reducer   c             c   sZ   |  |}|||fV  |sdS x6t|D ]*\}}x | |||f D ]
}|V  qDW q(W dS )aB  
        Iterate over x, yielding (index, value, entering), where

        * ``index``: a tuple of indices up to this point
        * ``value``: equal to ``x[index[0]][...][index[-1]]``. On the first iteration, is
                     ``x`` itself
        * ``entering``: bool. The result of ``recurse_if(value)``
        N)r6   	enumeratewalk)r7   r   r1   Z
do_recurseir;   vr   r   r   rD     s    	
z_Recurser.walkN)r   )__name__
__module____qualname____doc__r8   rB   rD   r   r   r   r   r5   o  s   -r5   )NN)NNN)NNN)Z
__future__r   r   r   Zdistutils.versionr   Znumpyr
   warningscatch_warningsZallcloser   float	TypeErrorZmaZ	ma_divideZcoreZ_DomainedBinaryOperationZ_DomainSafeDivide__version__r   r   r   r(   r*   r3   r4   Z_make_sliced_dtypeobjectr5   r   r   r   r   <module>   s>   




)
@
>d