U
    Cvft9                     @  s   d dl mZ d dlZd dlmZmZmZmZmZm	Z	 d dl
Zd dlmZmZ d dlmZmZmZ d dlmZmZmZ erd dlmZ d dlmZ d	ZG d
d dee ZG dd ded eeZG dd ded eeZdS )    )annotationsN)TYPE_CHECKINGAnyCallableHashableIterableSequence)DataArrayResampleAggregationsDatasetResampleAggregations)DataArrayGroupByBaseDatasetGroupByBaseGroupBy)DimsInterpOptionsT_Xarray	DataArray)DatasetZ__resample_dim__c                      s   e Zd ZdZddddddd fddZd!d	d
dd fddZddddZd"dddddZeZd#dddddZ	e	Z
d$dddddZd%dddddZd&dddd Z  ZS )'ResampleaS  An object that extends the `GroupBy` object with additional logic
    for handling specialized re-sampling operations.

    You should create a `Resample` object by using the `DataArray.resample` or
    `Dataset.resample` methods. The dimension along re-sampling

    See Also
    --------
    DataArray.resample
    Dataset.resample

    N)dimresample_dimzHashable | NoneNone)r   r   returnc                  s6   ||krt d| d| d|| _t j|| d S )NzProxy resampling dimension ('z3') cannot have the same name as actual dimension ('z')!)
ValueError_dimsuper__init__)selfr   r   argskwargs	__class__ 8/tmp/pip-unpacked-wheel-h316xyqg/xarray/core/resample.pyr   $   s    zResample.__init__r   bool | Noner   )r   
keep_attrsr   c                   s   ddl m} |dd g }| jD ]@}t|ts4t|jd k	rD|jn| jj	| j
 }|||j  q"t| jj|}||| j
f| jjd}	t jf ||	|d|}
| |
}
|
t| j
i}
|
S )Nr   r   methodZcohorts)dimsname)r   groupr%   )xarray.core.dataarrayr   
setdefaultZ_group_indices
isinstancesliceAssertionErrorstop_objZsizesZ
_group_dimappendstartnprepeatZ_unique_coorddatar(   r   _flox_reduceZ_maybe_restore_empty_groupsrenameRESAMPLE_DIM)r   r   r%   r   r   ZrepeatsZslicerr/   labelsr)   resultr    r"   r#   r6   5   s,    
  
zResample._flox_reducer   c                 C  s>   | j }|j D ](\}}|| jkr| j|jkr||}q|S )z=Drop non-dimension coordinates along the resampled dimension.)r0   coordsitemsr   r'   	drop_vars)r   objkvr"   r"   r#   _drop_coordsT   s
    zResample._drop_coordszfloat | Iterable[float] | None)	tolerancer   c                 C  s    |   }|j| j| jid|dS )aT  Forward fill new values at up-sampled frequency.

        Parameters
        ----------
        tolerance : float | Iterable[float] | None, default: None
            Maximum distance between original and new labels to limit
            the up-sampling method.
            Up-sampled data with indices that satisfy the equation
            ``abs(index[indexer] - target) <= tolerance`` are filled by
            new values. Data with indices that are outside the given
            tolerance are filled with ``NaN`` s.

        Returns
        -------
        padded : DataArray or Dataset
        padr&   rC   rB   Zreindexr   _full_indexr   rC   r?   r"   r"   r#   rD   \   s    
  zResample.padc                 C  s    |   }|j| j| jid|dS )aY  Backward fill new values at up-sampled frequency.

        Parameters
        ----------
        tolerance : float | Iterable[float] | None, default: None
            Maximum distance between original and new labels to limit
            the up-sampling method.
            Up-sampled data with indices that satisfy the equation
            ``abs(index[indexer] - target) <= tolerance`` are filled by
            new values. Data with indices that are outside the given
            tolerance are filled with ``NaN`` s.

        Returns
        -------
        backfilled : DataArray or Dataset
        backfillrE   rF   rH   r"   r"   r#   rI   t   s    
  zResample.backfillc                 C  s    |   }|j| j| jid|dS )a  Take new values from nearest original coordinate to up-sampled
        frequency coordinates.

        Parameters
        ----------
        tolerance : float | Iterable[float] | None, default: None
            Maximum distance between original and new labels to limit
            the up-sampling method.
            Up-sampled data with indices that satisfy the equation
            ``abs(index[indexer] - target) <= tolerance`` are filled by
            new values. Data with indices that are outside the given
            tolerance are filled with ``NaN`` s.

        Returns
        -------
        upsampled : DataArray or Dataset
        nearestrE   rF   rH   r"   r"   r#   rJ      s    
  zResample.nearestlinearr   )kindr   c                 C  s   | j |dS )a9  Interpolate up-sampled data using the original data as knots.

        Parameters
        ----------
        kind : {"linear", "nearest", "zero", "slinear",                 "quadratic", "cubic", "polynomial"}, default: "linear"
            The method used to interpolate. The method should be supported by
            the scipy interpolator:

            - ``interp1d``: {"linear", "nearest", "zero", "slinear",
              "quadratic", "cubic", "polynomial"}
            - ``interpn``: {"linear", "nearest"}

            If ``"polynomial"`` is passed, the ``order`` keyword argument must
            also be provided.

        Returns
        -------
        interpolated : DataArray or Dataset

        See Also
        --------
        DataArray.interp
        Dataset.interp
        scipy.interpolate.interp1d

        )rL   )_interpolate)r   rL   r"   r"   r#   interpolate   s    zResample.interpolatec                 C  s&   |   }|j| j| jid|ddidS )z<Apply scipy.interpolate.interp1d along resampling dimension.TZbounds_errorF)r<   Zassume_sortedr&   r   )rB   Zinterpr   rG   )r   rL   r?   r"   r"   r#   rM      s    
zResample._interpolate)N)N)N)N)rK   )rK   )__name__
__module____qualname____doc__r   r6   rB   rD   ZffillrI   ZbfillrJ   rN   rM   __classcell__r"   r"   r    r#   r      s    r   c                      sH   e Zd ZdZddddddd	 fd
dZdddZddddZ  ZS )DataArrayResamplezeDataArrayGroupBy object specialized to time resampling operations over a
    specified dimension
    r"   FCallable[..., Any]tuple[Any, ...]r$   r   r   funcr   shortcutr   r   c                   sP   t  j|f||d|}| j|jkr2|| j}t|jkrL|t| ji}|S )a  Apply a function to each array in the group and concatenate them
        together into a new array.

        `func` is called like `func(ar, *args, **kwargs)` for each array `ar`
        in this group.

        Apply uses heuristics (like `pandas.GroupBy.apply`) to figure out how
        to stack together the array. The rule is:

        1. If the dimension along which the group coordinate is defined is
           still in the first grouped array after applying `func`, then stack
           over this dimension.
        2. Otherwise, stack over the new dimension given by name of this
           grouping (the argument to the `groupby` function).

        Parameters
        ----------
        func : callable
            Callable to apply to each array.
        shortcut : bool, optional
            Whether or not to shortcut evaluation under the assumptions that:

            (1) The action of `func` does not depend on any of the array
                metadata (attributes or coordinates) but only on the data and
                dimensions.
            (2) The action of `func` creates arrays with homogeneous metadata,
                that is, with the same dimensions and attributes.

            If these conditions are satisfied `shortcut` provides significant
            speedup. This should be the case for many common groupby operations
            (e.g., applying numpy ufuncs).
        args : tuple, optional
            Positional arguments passed on to `func`.
        **kwargs
            Used to call `func(ar, **kwargs)` for each array `ar`.

        Returns
        -------
        applied : DataArray
            The result of splitting, applying and combining this array.
        )rY   r   )r   mapr   r<   r>   r8   r'   r7   )r   rX   r   rY   r   combinedr    r"   r#   rZ      s    2
zDataArrayResample.mapNc                 K  s(   t jdtdd | jf |||d|S )z
        Backward compatible implementation of ``map``

        See Also
        --------
        DataArrayResample.map
        PResample.apply may be deprecated in the future. Using Resample.map is encouraged   
stacklevelrX   rY   r   warningswarnPendingDeprecationWarningrZ   r   rX   r   rY   r   r"   r"   r#   apply  s    zDataArrayResample.applyr;   c                 C  s&   |   | _| | jdkrdn| jgS )zReturn values of original object at the new up-sampling frequency;
        essentially a re-index with new times set to NaN.

        Returns
        -------
        resampled : DataArray
        NrB   r0   Zmeanr   r   r"   r"   r#   asfreq   s    
zDataArrayResample.asfreq)r"   F)r"   N)rO   rP   rQ   rR   rZ   rf   ri   rS   r"   r"   r    r#   rT      s     ?
rT   r   c                      sr   e Zd ZdZddddddd	d
dZdddZddddddddddddddd fddZddddZ  ZS )DatasetResamplezEDatasetGroupBy object specialized to resampling a specified dimensionr"   NrU   rV   r$   r   r   rW   c                   sZ    fdd|   D }| |}| j|jkr<|| j}t|jkrV|t| ji}|S )a^  Apply a function over each Dataset in the groups generated for
        resampling and concatenate them together into a new Dataset.

        `func` is called like `func(ds, *args, **kwargs)` for each dataset `ds`
        in this group.

        Apply uses heuristics (like `pandas.GroupBy.apply`) to figure out how
        to stack together the datasets. The rule is:

        1. If the dimension along which the group coordinate is defined is
           still in the first grouped item after applying `func`, then stack
           over this dimension.
        2. Otherwise, stack over the new dimension given by name of this
           grouping (the argument to the `groupby` function).

        Parameters
        ----------
        func : callable
            Callable to apply to each sub-dataset.
        args : tuple, optional
            Positional arguments passed on to `func`.
        **kwargs
            Used to call `func(ds, **kwargs)` for each sub-dataset `ar`.

        Returns
        -------
        applied : Dataset
            The result of splitting, applying and combining this dataset.
        c                 3  s   | ]}|f V  qd S )Nr"   ).0Zdsr   rX   r   r"   r#   	<genexpr>U  s     z&DatasetResample.map.<locals>.<genexpr>)Z_iter_groupedZ_combiner   r<   r>   r8   r'   r7   )r   rX   r   rY   r   Zappliedr[   r"   rl   r#   rZ   0  s    %

zDatasetResample.mapc                 K  s(   t jdtdd | jf |||d|S )z~
        Backward compatible implementation of ``map``

        See Also
        --------
        DataSetResample.map
        r\   r]   r^   r`   ra   re   r"   r"   r#   rf   c  s    	zDatasetResample.applyFT)axisr%   keepdimsrY   r   zint | Sequence[int] | Nonebool)rX   r   rn   r%   ro   rY   r   r   c             	     s    t  jf ||||||d|S )a  Reduce the items in this group by applying `func` along the
        pre-defined resampling dimension.

        Parameters
        ----------
        func : callable
            Function which can be called in the form
            `func(x, axis=axis, **kwargs)` to return the result of collapsing
            an np.ndarray over an integer valued axis.
        dim : "...", str, Iterable of Hashable or None, optional
            Dimension(s) over which to apply `func`.
        keep_attrs : bool, optional
            If True, the datasets's attributes (`attrs`) will be copied from
            the original object to the new one.  If False (default), the new
            object will be returned without attributes.
        **kwargs : dict
            Additional keyword arguments passed on to `func`.

        Returns
        -------
        reduced : Dataset
            Array with summarized data and the indicated dimension(s)
            removed.
        )rX   r   rn   r%   ro   rY   )r   reduce)r   rX   r   rn   r%   ro   rY   r   r    r"   r#   rq   s  s    #zDatasetResample.reducer;   c                 C  s&   |   | _| | jdkrdn| jgS )zReturn values of original object at the new up-sampling frequency;
        essentially a re-index with new times set to NaN.

        Returns
        -------
        resampled : Dataset
        Nrg   rh   r"   r"   r#   ri     s    
zDatasetResample.asfreq)r"   N)r"   N)N)	rO   rP   rQ   rR   rZ   rf   rq   ri   rS   r"   r"   r    r#   rj   -  s     3
 $-rj   r   )
__future__r   rb   typingr   r   r   r   r   r   Znumpyr3   Zxarray.core._aggregationsr	   r
   Zxarray.core.groupbyr   r   r   Zxarray.core.typesr   r   r   r*   r   Zxarray.core.datasetr   r8   r   rT   rj   r"   r"   r"   r#   <module>   s     8`