U
    Cvf@                     @   s  d Z ddlZddlZddlmZ dZdZdZdZdZ	dZ
dZd	Zd
ZdZdZdZdZdZdZdZdZeddZeeddddZeeddddZeeddddZG dd  d ZG d!d" d"ZG d#d$ d$eZG d%d& d&eZed'ed(d)d*ed+d)d*ed,efd-ed.efd-ed/efd)d0ed1eefd)d0ed2eefd)d0ed3eefd)d0ed4eefd)d0ed5efd)d0ed6efd)d0ed7efd)d0fZeG d8d9 d9Z e d:d;d<d)d=Z!e d>d?d@dAd=Z"edBe!edCdDdBd>edEZ#edBe"edCdDdBd:edEZ$edFe"edGdHdIedJZ%edKe"edLdMdNedJZ&edFe!edGdHdIedJZ'edKe!edLdMdNedJZ(e)dOkrddl*Z*ddPl+m,Z, e,e*- Z.e.j/dQ dQ dR dS Z0e1e0dTdUdVVZ2e23edW  e#e$e'e(e%e&fD ]0Z4e45 D ] Z6e6D ]Z7e23e7dW  qƐqqW 5 Q R X dS )Xa  Generate module and stub file for arithmetic operators of various xarray classes.

For internal xarray development use only.

Usage:
    python xarray/util/generate_aggregations.py
    pytest --doctest-modules xarray/core/_aggregations.py --accept || true
    pytest --doctest-modules xarray/core/_aggregations.py

This requires [pytest-accept](https://github.com/max-sixty/pytest-accept).
The second run of pytest is deliberate, since the first will return an error
while replacing the doctests.

    N)	dataclassa  """Mixin classes with reduction operations."""
# This file was generated using xarray.util.generate_aggregations. Do not edit manually.

from __future__ import annotations

from typing import TYPE_CHECKING, Any, Callable, Sequence

from . import duck_array_ops
from .options import OPTIONS
from .types import Dims
from .utils import contains_only_dask_or_numpy, module_available

if TYPE_CHECKING:
    from .dataarray import DataArray
    from .dataset import Dataset

flox_available = module_available("flox")a\  

class {obj}{cls}Aggregations:
    __slots__ = ()

    def reduce(
        self,
        func: Callable[..., Any],
        dim: Dims = None,
        *,
        axis: int | Sequence[int] | None = None,
        keep_attrs: bool | None = None,
        keepdims: bool = False,
        **kwargs: Any,
    ) -> {obj}:
        raise NotImplementedError()a  

class {obj}{cls}Aggregations:
    _obj: {obj}

    def reduce(
        self,
        func: Callable[..., Any],
        dim: Dims = None,
        *,
        axis: int | Sequence[int] | None = None,
        keep_attrs: bool | None = None,
        keepdims: bool = False,
        **kwargs: Any,
    ) -> {obj}:
        raise NotImplementedError()

    def _flox_reduce(
        self,
        dim: Dims,
        **kwargs: Any,
    ) -> {obj}:
        raise NotImplementedError()a(  
    def {method}(
        self,
        dim: Dims = None,
        *,{extra_kwargs}
        keep_attrs: bool | None = None,
        **kwargs: Any,
    ) -> {obj}:
        """
        Reduce this {obj}'s data by applying ``{method}`` along some dimension(s).

        Parameters
        ----------z
        Returns
        -------
        reduced : {obj}
            New {obj} with ``{method}`` applied to its data and the
            indicated dimension(s) removedz
        See Also
        --------
        numpy.{method}
        dask.array.{method}
        {see_also_obj}.{method}
        :ref:`{docref}`
            User guide on {docref_description}.z,
        Notes
        -----
        {notes}zdim : str, Iterable of Hashable, "..." or None, default: None
    Name of dimension[s] along which to apply ``{method}``. For e.g. ``dim="x"``
    or ``dim=["x", "y"]``. If "..." or None, will reduce over all dimensions.a  dim : str, Iterable of Hashable, "..." or None, default: None
    Name of dimension[s] along which to apply ``{method}``. For e.g. ``dim="x"``
    or ``dim=["x", "y"]``. If None, will reduce over the {cls} dimensions.
    If "...", will reduce over all dimensions.a(  skipna : bool or None, optional
    If True, skip missing values (as marked by NaN). By default, only
    skips missing values for float dtypes; other dtypes either do not
    have a sentinel missing value (int) or ``skipna=True`` has not been
    implemented (object, datetime64 or timedelta64).ay  min_count : int or None, optional
    The required number of valid values to perform the operation. If
    fewer than min_count non-NA values are present the result will be
    NA. Only used if skipna is set to True or defaults to True for the
    array's dtype. Changed in version 0.17.0: if specified on an integer
    array and skipna=True, the result will be a float array.u   ddof : int, default: 0
    “Delta Degrees of Freedom”: the divisor used in the calculation is ``N - ddof``,
    where ``N`` represents the number of elements.zkeep_attrs : bool or None, optional
    If True, ``attrs`` will be copied from the original
    object to the new one.  If False, the new object will be
    returned without attributes.z**kwargs : Any
    Additional keyword arguments passed on to the appropriate array
    function for calculating ``{method}`` on this object's data.
    These could include dask-specific kwargs like ``split_every``.z8Non-numeric variables will be removed prior to reducing.
ExtraKwargzdocs kwarg call examplezskipna: bool | None = None,zskipna=skipna,zf

        Use ``skipna`` to control whether NaNs are ignored.

        >>> {calculation}(skipna=False))docskwargcallexamplezmin_count: int | None = None,zmin_count=min_count,z

        Specify ``min_count`` for finer control over when NaNs are ignored.

        >>> {calculation}(skipna=True, min_count=2)zddof: int = 0,z
ddof=ddof,zf

        Specify ``ddof=1`` for an unbiased estimate.

        >>> {calculation}(skipna=True, ddof=1)c                   @   s   e Zd Zde dfddZdS )MethodFc                 C   s:   || _ || _|| _|r*d| | _d| _n|| _d| _d S )NZarray_zL
        ...     np.array([True, True, True, True, True, False], dtype=bool)z2
        ...     np.array([1, 2, 3, 1, 2, np.nan]))nameextra_kwargsnumeric_onlyarray_methodnp_example_array)selfr	   bool_reducer
   r    r   E/tmp/pip-unpacked-wheel-h316xyqg/xarray/util/generate_aggregations.py__init__   s    zMethod.__init__N)__name__
__module____qualname__tupler   r   r   r   r   r      s   r   c                   @   s6   e Zd ZeZeZd
ddZdd Zdd Z	dd	 Z
dS )AggregationGeneratorNc	           	      C   sP   || _ || _|| _|| _|| _|| _|j|j|d| _|sF| j j| _	n|| _	d S )N)objcls)
datastructurer   methodsdocrefdocref_descriptionexample_call_preambleformatr	   preamblesee_also_obj)	r   r   r   r   r   r   r   definition_preambler!   r   r   r   r      s    zAggregationGenerator.__init__c                 c   s&   | j gV  | jD ]}| |V  qd S N)r    r   generate_method)r   methodr   r   r   generate_methods  s    

z%AggregationGenerator.generate_methodsc                 c   s  t | jj|jd}|jr4dddd |jD  }nd}| jjf |d|iV  | jj|j| jdfdd	 |jD t	t
j|jd
fD ]}|rt|dV  qtjf |V  tjf || j| j| jdV  |jrtjtdV  t| j|d
dV  dV  | |V  d S )N)r   r%   z	
        c                 S   s   g | ]}|j r|j qS r   )r   .0r   r   r   r   
<listcomp>  s      z8AggregationGenerator.generate_method.<locals>.<listcomp> r
   )r%   r   c                 s   s   | ]}|j r|j V  qd S r#   )r   r'   r   r   r   	<genexpr>%  s      z7AggregationGenerator.generate_method.<locals>.<genexpr>)r%   z        )r   r   r!   )Znotesz        """)dictr   r	   r
   join_template_signaturer   _dim_docstringr   _KEEP_ATTRS_DOCSTRING_KWARGS_DOCSTRINGtextwrapindentTEMPLATE_RETURNSTEMPLATE_SEE_ALSOr   r   r!   r   TEMPLATE_NOTES_NUMERIC_ONLY_NOTESgenerate_examplegenerate_code)r   r%   Ztemplate_kwargsr
   textr   r   r   r$     s>    

z$AggregationGenerator.generate_methodc                 C   st   d|j  d}| jj | j d|j }|jrRddd |jD j||jd}nd}d| | jj d	| d
| S )Nz
        >>> da = xr.DataArray(a   ,
        ...     dims="time",
        ...     coords=dict(
        ...         time=("time", pd.date_range("01-01-2001", freq="M", periods=6)),
        ...         labels=("time", np.array(["a", "b", "c", "c", "b", "a"])),
        ...     ),
        ... ).r*   c                 s   s   | ]}|j r|j V  qd S r#   )r   r'   r   r   r   r+   I  s     z8AggregationGenerator.generate_example.<locals>.<genexpr>)calculationr%   z"
        Examples
        --------z

        >>> z())	r   r   example_var_namer   r	   r
   r-   r   docstring_create)r   r%   Z	create_dar<   Zextra_examplesr   r   r   r8   =  s*    	
 z%AggregationGenerator.generate_example)N)r   r   r   _DIM_DOCSTRINGr/   TEMPLATE_REDUCTION_SIGNATUREr.   r   r&   r$   r8   r   r   r   r   r      s    
)r   c                   @   s   e Zd ZeZeZdd ZdS )GroupByAggregationGeneratorc              	   C   s   dd |j D }| jjr,|d|j d |jdk}|r@d}nd}|rdtdd| |d	 }nd
}|rd|j d| dS d|j d| d|j d| d	S d S )Nc                 S   s   g | ]}|j r|j qS r   r   r'   r   r   r   r)   [  s      z=GroupByAggregationGenerator.generate_code.<locals>.<listcomp>numeric_only=,)mediancumsumcumprod      
 r*   7        return self.reduce(
            duck_array_ops.,
            dim=dim,C
            keep_attrs=keep_attrs,
            **kwargs,
        )z        if (
            flox_available
            and OPTIONS["use_flox"]
            and contains_only_dask_or_numpy(self._obj)
        ):
            return self._flox_reduce(
                func="z",
                dim=dim,z
                # fill_value=fill_value,
                keep_attrs=keep_attrs,
                **kwargs,
            )
        else:
            return self.reduce(
                duck_array_ops.z,
                dim=dim,zO
                keep_attrs=keep_attrs,
                **kwargs,
            ))	r
   r   r   appendr	   r2   r3   r-   r   )r   r%   r
   Zmethod_is_not_flox_supportedr3   r   r   r   r9   Z  s2    
	z)GroupByAggregationGenerator.generate_codeN)r   r   r   _DIM_DOCSTRING_GROUPBYr/   $TEMPLATE_REDUCTION_SIGNATURE_GROUPBYr.   r9   r   r   r   r   rA   V  s   rA   c                   @   s   e Zd Zdd ZdS )GenericAggregationGeneratorc                 C   s`   dd |j D }| jjr,|d|j d |rHtdd| d}nd}d|j d	| d
S )Nc                 S   s   g | ]}|j r|j qS r   rB   r'   r   r   r   r)     s      z=GenericAggregationGenerator.generate_code.<locals>.<listcomp>rC   rD   rJ   z            r*   rL   rM   rN   )r
   r   r   rO   r2   r3   r-   r   )r   r%   r
   r   r   r   r9     s    z)GenericAggregationGenerator.generate_codeN)r   r   r   r9   r   r   r   r   rR     s   rR   countallT)r   anymax)r
   minZmean)r
   r   prodsumZstdvarrE   rF   rG   c                   @   s2   e Zd ZU eed< eed< eed< dZeed< dS )DataStructurer	   r>   r=   Fr   N)r   r   r   str__annotations__r   boolr   r   r   r   r[     s   
r[   ZDatasetz8
        >>> ds = xr.Dataset(dict(da=da))
        >>> dsZds)r	   r>   r=   r   Z	DataArrayz
        >>> dadaFr*   Zaggz#reduction or aggregation operations)r   r   r   r   r   r   r!   r"   ZGroupBygroupbyzgroupby operationsz.groupby("labels"))r   r   r   r   r   r   r"   ZResampleZ
resamplingzresampling operationsz.resample(time="3M")__main__)PathZxarraycorez_aggregations.pywzutf-8)modeencodingrJ   )8__doc__collectionsr2   Zdataclassesr   ZMODULE_PREAMBLEZDEFAULT_PREAMBLEZGROUPBY_PREAMBLEZRESAMPLE_PREAMBLEr@   rQ   r4   r5   r6   r?   rP   Z_SKIPNA_DOCSTRINGZ_MINCOUNT_DOCSTRINGZ_DDOF_DOCSTRINGr0   r1   r7   
namedtupler   ZskipnaZ	min_countZddofr   r   rA   rR   ZAGGREGATION_METHODSr[   ZDATASET_OBJECTZDATAARRAY_OBJECTZDATASET_GENERATORZDATAARRAY_GENERATORZDATAARRAY_GROUPBY_GENERATORZDATAARRAY_RESAMPLE_GENERATORZDATASET_GROUPBY_GENERATORZDATASET_RESAMPLE_GENERATORr   ospathlibrb   getcwdpparentfilepathopenfwritegenr&   linesliner   r   r   r   <module>   s   			c7



			
