
    d)7                       d dl mZ d dlZd dlmZmZmZ d dlmZm	Z	m
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rd dlmZ d d	lmZ d
Z G d dee                   Z G d ded         ee          Z G d ded         ee          ZdS )    )annotationsN)HashableIterableSequence)TYPE_CHECKINGAnyCallable)DataArrayResampleAggregationsDatasetResampleAggregations)DataArrayGroupByBaseDatasetGroupByBaseGroupBy)DimsInterpOptionsT_Xarray)	DataArray)Dataset__resample_dim__c                  ~     e Zd ZdZdddd fd	Z	 dd fdZddZdddZeZdddZ	e	Z
dddZdd dZdddZ x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_dimr   Hashable | Noner   returnNonec                   ||k    rt          d| d| d          || _         t                      j        |i | 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__s        4lib/python3.11/site-packages/xarray/core/resample.pyr    zResample.__init__#   sv     ,L L LCFL L L   	$)&)))))    r   
keep_attrsbool | Noner   c                     t                      j        d||d|}|                    t          | j        i          }|S )N)r   r'    )r   _flox_reducerenameRESAMPLE_DIM
_group_dim)r!   r   r'   r#   resultr$   s        r%   r+   zResample._flox_reduce3   sE     &%O#*OOOOdo>??r&   c                    | j         }|j                                        D ]3\  }}|| j        k    r#| j        |j        v r|                    |          }4|S )z=Drop non-dimension coordinates along the resampled dimension.)_objcoordsitemsr   dims	drop_vars)r!   objkvs       r%   _drop_coordszResample._drop_coords=   sZ    iJ$$&& 	' 	'DAqDI~~$)qv"5"5mmA&&
r&   	tolerancefloat | Iterable[float] | Nonec                    |                                  }| j        \  }|                    | j        |j        i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methodr:   r9   groupersreindexr   
full_indexr!   r:   r6   groupers       r%   r=   zResample.padE   sJ    " !!]
{{Y*+EY  
 
 	
r&   c                    |                                  }| j        \  }|                    | j        |j        i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
        backfillr>   r@   rD   s       r%   rG   zResample.backfill^   sJ    " !!]
{{Y*+J)  
 
 	
r&   c                    |                                  }| j        \  }|                    | j        |j        i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
        nearestr>   r@   rD   s       r%   rI   zResample.nearestw   sJ    $ !!]
{{Y*+I  
 
 	
r&   linearkindr   c                .    |                      |          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

        )rK   )_interpolate)r!   rK   s     r%   interpolatezResample.interpolate   s    8   d +++r&   c                    |                                  }| j        \  }|                    | j        |j        id|ddi          S )z<Apply scipy.interpolate.interp1d along resampling dimension.Tbounds_errorF)r2   assume_sortedr?   r#   )r9   rA   interpr   rC   )r!   rK   r6   rE   s       r%   rM   zResample._interpolate   sR    !!]
zzIw12"E*	  
 
 	
r&   )r   r   r   r   r   r   N)r   r   r'   r(   r   r   )r   r   )r:   r;   r   r   )rJ   )rK   r   r   r   )__name__
__module____qualname____doc__r    r+   r9   r=   ffillrG   bfillrI   rN   rM   __classcell__r$   s   @r%   r   r      s            $(,	* * * * * * * *& #'         
 
 
 
 
. E
 
 
 
 
. E
 
 
 
 
0, , , , ,<	
 	
 	
 	
 	
 	
 	
 	
 	
r&   r   c                  :     e Zd ZdZ	 	 dd fdZddZddZ xZS )DataArrayResamplezeDataArrayGroupBy object specialized to time resampling operations over a
    specified dimension
    r*   FfuncCallable[..., Any]r"   tuple[Any, ...]shortcutr(   r#   r   r   r   c                     t                      j        |f||d|}| j        |j        v r|                    | j                  }t
          |j        v r!|                    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.
        )ra   r"   )r   mapr   r2   r5   r-   r4   r,   )r!   r^   r"   ra   r#   combinedr$   s         r%   rc   zDataArrayResample.map   sz    d 577;tLhTLLVLL
 9''))$)44H8=((di'@AAHr&   Nc                \    t          j        dt          d            | j        d|||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r^   ra   r"   r*   warningswarnPendingDeprecationWarningrc   r!   r^   r"   ra   r#   s        r%   applyzDataArrayResample.apply   sI     	^%	
 	
 	
 	

 txJTH4JJ6JJJr&   c                |    |                                  | _        |                     | j        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r9   r1   meanr   r!   s    r%   asfreqzDataArrayResample.asfreq  8     %%''	yy!2DDDr&   )r*   F)
r^   r_   r"   r`   ra   r(   r#   r   r   r   r*   N)r   r   )rT   rU   rV   rW   rc   rp   ru   rZ   r[   s   @r%   r]   r]      s          !# %	= = = = = = =~K K K K	E 	E 	E 	E 	E 	E 	E 	Er&   r]   r   c                  R     e Zd ZdZ	 	 dddZddZ	 ddddddd fdZd dZ xZS )!DatasetResamplezEDatasetGroupBy object specialized to resampling a specified dimensionr*   Nr^   r_   r"   r`   ra   r(   r#   r   r   r   c                (   fd|                                  D             }|                     |          }| j        |j        v r|                    | j                  }t
          |j        v r!|                    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  0   K   | ]} |gR i V  d S rS   r*   ).0dsr"   r^   r#   s     r%   	<genexpr>z&DatasetResample.map.<locals>.<genexpr>B  s=      LL44,T,,,V,,LLLLLLr&   )_iter_grouped_combiner   r2   r5   r-   r4   r,   )r!   r^   r"   ra   r#   appliedrd   s    `` `  r%   rc   zDatasetResample.map  s    J MLLLLLt7I7I7K7KLLL==))
 9''))$)44H8=((di'@AAHr&   c                \    t          j        dt          d            | j        d|||d|S )z~
        Backward compatible implementation of ``map``

        See Also
        --------
        DataSetResample.map
        rf   rg   rh   rj   r*   rk   ro   s        r%   rp   zDatasetResample.applyP  sI     	^%	
 	
 	
 	

 txJTH4JJ6JJJr&   FT)axisr'   keepdimsra   r   r   r   int | Sequence[int] | Noner'   r   boolc          
     D     t                      j        d||||||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.
        )r^   r   r   r'   r   ra   r*   )r   reduce)	r!   r^   r   r   r'   r   ra   r#   r$   s	           r%   r   zDatasetResample.reduce`  sF    F uww~ 
!
 
 
 
 	
r&   c                |    |                                  | _        |                     | j        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
        Nrr   rt   s    r%   ru   zDatasetResample.asfreq  rv   r&   rw   )
r^   r_   r"   r`   ra   r(   r#   r   r   r   rS   )r^   r_   r   r   r   r   r'   r(   r   r   ra   r   r#   r   r   r   )r   r   )	rT   rU   rV   rW   rc   rp   r   ru   rZ   r[   s   @r%   ry   ry     s        OO
 !# $	1 1 1 1 1fK K K K& +

 ,0"&+
 +
 +
 +
 +
 +
 +
 +
Z	E 	E 	E 	E 	E 	E 	E 	Er&   ry   r   )
__future__r   rl   collections.abcr   r   r   typingr   r   r	   xarray.core._aggregationsr
   r   xarray.core.groupbyr   r   r   xarray.core.typesr   r   r   xarray.core.dataarrayr   xarray.core.datasetr   r-   r   r]   ry   r*   r&   r%   <module>r      s   " " " " " "  8 8 8 8 8 8 8 8 8 8 / / / / / / / / / /        R Q Q Q Q Q Q Q Q Q ; ; ; ; ; ; ; ; ; ; ,//////++++++!a
 a
 a
 a
 a
wx  a
 a
 a
J\E \E \E \E \E-/CEb \E \E \E@|E |E |E |E |Ehy)+=?Z |E |E |E |E |Er&   