
    dD                        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dZe                    dd          Ze                    dd          Z ej        dd          Z eeddd          Z eedd d!          Z eed"d#d$          Z G d% d&          Z G d' d(          Z  G d) d*e           Z! G d+ d,e           Z" ed-           ed.d/0           ed1d/0           ed2ef3           ed4ef3           ed5efd/6           ed7eefd/6           ed8eefd/6           ed9eefd/6           ed:eefd/6           ed;efd/6           ed<efd/6           ed=efd/6          fZ#e G d> d?                      Z$ e$d@dAdBd/C          Z% e$dDdEdFdGC          Z& e"dHe%e#dIdJdHdDeK          Z' e"dHe&e#dIdJdHd@eK          Z( e!dLe&e#ddMdNeeO          Z) e!dPe&e#ddQdReeO          Z* e!dLe%e#ddMdNeeO          Z+ e!dPe%e#ddQdReeO          Z,e-dSk    rddl.Z.ddTl/m0Z0  e0 e.j1                              Z2e2j3        dUz  dUz  dVz  dWz  Z4 e5e4dXdYZ          5 Z6e67                    ed[z              e'e(e+e,e)e*fD ]6Z8e89                                D ]Z:e:D ]Z;e67                    e;d[z               7	 ddd           dS # 1 swxY w Y   dS dS )\a  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 xarray.core import duck_array_ops
from xarray.core.options import OPTIONS
from xarray.core.types import Dims
from xarray.core.utils import contains_only_dask_or_numpy, module_available

if TYPE_CHECKING:
    from xarray.core.dataarray import DataArray
    from xarray.core.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.a  Use the ``flox`` package to significantly speed up {kind} computations,
especially with dask arrays. Xarray will use flox by default if installed.
Pass flox-specific keyword arguments in ``**kwargs``.
The default choice is ``method="cohorts"`` which generalizes the best,
{recco} might work better for your problem.
See the `flox documentation <https://flox.readthedocs.io>`_ for more.groupbyzother methods)kindrecco
resamplingz``method="blockwise"``
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                   ,    e Zd Zd e            dfdZdS )MethodFc                 v    || _         || _        || _        |rd| | _        d| _        d S || _        d| _        d S )N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   s        Alib/python3.11/site-packages/xarray/util/generate_aggregations.py__init__zMethod.__init__   s\     	(( 	5 /D%OD!!! !%D%5D!!!    N)__name__
__module____qualname__tupler    r   r   r   r      s9         UWW5 5 5 5 5 5r   r   c                   4    e Zd ZeZeZ	 	 ddZd Zd Z	d Z
dS )AggregationGeneratorNc
                     || _         || _        || _        || _        || _        || _        |                    |j        |          | _        |	dn|	| _	        |s| j         j        | _
        d S || _
        d S )N)objcls )datastructurer$   methodsdocrefdocref_descriptionexample_call_preambleformatr   preamblenotessee_also_obj)
r   r$   r&   r'   r(   r)   r*   definition_preambler.   r-   s
             r   r   zAggregationGenerator.__init__  s     +"4%:"+22}7Is2SS =RRe
 	- $ 2 7D ,Dr   c              #   `   K   | j         gV  | j        D ]}|                     |          V  d S N)r,   r'   generate_method)r   methods     r   generate_methodsz%AggregationGenerator.generate_methods  sN      }ol 	/ 	/F&&v......	/ 	/r   c              #     K   t          | j        j        |j                  }|j        r(dd                    d |j        D                       z   }nd} | j        j        di |d|iV  | j                            |j        | j                  gd |j        D             t          t                              |j                  D ]}|rt          j        |d	          V  t          j        di |V  t          j        di || j        | j        | j        d
V  | j        }|j        r|dk    r|dz  }|t(          z  }|dk    r0t*                              t          j        |d	                    V  t          j        |                     |          d          V  dV  |                     |          V  d S )N)r#   r3   z	
        c                 *    g | ]}|j         	|j         S r   )r
   .0r
   s     r   
<listcomp>z8AggregationGenerator.generate_method.<locals>.<listcomp>%  s!    MMMMMMMr   r%   r   )r3   r$   c              3   2   K   | ]}|j         	|j         V  d S r1   )r	   r7   s     r   	<genexpr>z7AggregationGenerator.generate_method.<locals>.<genexpr>1  s+      HHUUZHejHHHHHHr   )r3   z        )r(   r)   r.   z

)r-   z        """r   )dictr&   r   r   join_template_signaturer+   _dim_docstringr$   _KEEP_ATTRS_DOCSTRING_KWARGS_DOCSTRINGtextwrapindentTEMPLATE_RETURNSTEMPLATE_SEE_ALSOr(   r)   r.   r-   r   _NUMERIC_ONLY_NOTESTEMPLATE_NOTESgenerate_examplegenerate_code)r   r3   template_kwargsr   textr-   s         r   r2   z$AggregationGenerator.generate_method   s[     4#5#:6;OOO 	',*;*;MM&*=MMM+ + LL L-d&- 
 

 
%
 
 
 	
 	
 	
 &&fktx&HH
HHf&9HHH
 "
 $$FK$88	
 	5 	5D  5odG44444%8888888& 
 

;#6*	
 
 
 
 	
 	
 	
 
 	){{((EB;; ''hoeW.M.M'NNNNNod3363BBBGGGGG  (((((((r   c                    d|j          d}| j        j         | j         d|j         }|j        r?d                    d |j        D                                           ||j                  }nd}d| | j        j         d| d	| S )
Nz
        >>> da = xr.DataArray(a   ,
        ...     dims="time",
        ...     coords=dict(
        ...         time=("time", pd.date_range("2001-01-01", freq="M", periods=6)),
        ...         labels=("time", np.array(["a", "b", "c", "c", "b", "a"])),
        ...     ),
        ... ).r%   c              3   2   K   | ]}|j         	|j         V  d S r1   )r   r7   s     r   r;   z8AggregationGenerator.generate_example.<locals>.<genexpr>[  s?       % %"'%-%% % % % % %r   )calculationr3   z"
        Examples
        --------z

        >>> z())	r   r&   example_var_namer*   r   r   r=   r+   docstring_create)r   r3   	create_darO   extra_exampless        r   rH   z%AggregationGenerator.generate_exampleO  s    %6  	 +<hd>Xhh[a[fhh 	 WW % %+1+>% % %  fV[fAA N  N// .?/ / 	/ / +	/ / 	/r   )NN)r   r   r   _DIM_DOCSTRINGr?   TEMPLATE_REDUCTION_SIGNATUREr>   r   r4   r2   rH   r   r   r   r!   r!      si        #N6 - - - -2/ / /
-) -) -)^/ / / / /r   r!   c                       e Zd ZeZeZd ZdS )GroupByAggregationGeneratorc           	      P   d |j         D             }| j        j        r|                    d|j         d           |j        dv }|rd}nd}|r/t          j        dd                    |          z   |dz            }nd	}|rd
|j         d| dS d|j         d| d|j         d| d	S )Nc                 *    g | ]}|j         	|j         S r   r   r7   s     r   r9   z=GroupByAggregationGenerator.generate_code.<locals>.<listcomp>m  !    RRRuuzR
RRRr   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   rB   rC   r=   r   )r   r3   r   method_is_not_flox_supportedrC   s        r   rI   z)GroupByAggregationGenerator.generate_codel  s*   RR0CRRR* 	H F0C F F FGGG (.{6U'U$' 	FFF 	#?4$))L2I2I+I6TW<XXLLL' 	"/  "    {  &  !' 3   &!   r   N)r   r   r   _DIM_DOCSTRING_GROUPBYr?   $TEMPLATE_REDUCTION_SIGNATURE_GROUPBYr>   rI   r   r   r   rW   rW   h  s.        +N>0 0 0 0 0r   rW   c                       e Zd Zd ZdS )GenericAggregationGeneratorc                     d |j         D             }| j        j        r|                    d|j         d           |r,t	          j        dd                    |          z   d          }nd}d|j         d| d	S )
Nc                 *    g | ]}|j         	|j         S r   rZ   r7   s     r   r9   z=GenericAggregationGenerator.generate_code.<locals>.<listcomp>  r[   r   r\   r]   rc   z            r%   re   rf   rg   )r   r&   r   rh   rB   rC   r=   r   )r   r3   r   s      r   rI   z)GenericAggregationGenerator.generate_code  s    RR0CRRR* 	H F0C F F FGGG 	#?4$))L2I2I+I8TTLLL"/  "   	r   N)r   r   r   rI   r   r   r   rm   rm     s#            r   rm   countallT)r   anymax)r   minmean)r   r   prodsumstdvarr^   r_   r`   c                   <    e Zd ZU eed<   eed<   eed<   dZeed<   dS )DataStructurer   rQ   rP   Fr   N)r   r   r   str__annotations__r   boolr   r   r   r{   r{     sC         
IIIL$r   r{   Datasetz8
        >>> ds = xr.Dataset(dict(da=da))
        >>> dsds)r   rQ   rP   r   	DataArrayz
        >>> dadaFr%   aggz#reduction or aggregation operations)r$   r&   r'   r(   r)   r*   r.   r/   GroupByzgroupby operationsz.groupby("labels"))r$   r&   r'   r(   r)   r*   r/   r-   Resamplezresampling operationsz.resample(time="3M")__main__)Pathxarraycorez_aggregations.pywzutf-8)modeencodingrc   )<__doc__collectionsrB   dataclassesr   MODULE_PREAMBLEDEFAULT_PREAMBLEGROUPBY_PREAMBLERESAMPLE_PREAMBLErU   rk   rD   rE   rG   rT   rj   _SKIPNA_DOCSTRING_MINCOUNT_DOCSTRING_DDOF_DOCSTRINGr@   rA   rF   _FLOX_NOTES_TEMPLATEr+   _FLOX_GROUPBY_NOTES_FLOX_RESAMPLE_NOTES
namedtupler   skipna	min_countddofr   r!   rW   rm   AGGREGATION_METHODSr{   DATASET_OBJECTDATAARRAY_OBJECTDATASET_GENERATORDATAARRAY_GENERATORDATAARRAY_GROUPBY_GENERATORDATAARRAY_RESAMPLE_GENERATORDATASET_GROUPBY_GENERATORDATASET_RESAMPLE_GENERATORr   ospathlibr   getcwdpparentfilepathopenfwritegenr4   linesliner   r   r   <module>r      so         ! ! ! ! ! !-&' "' 0' 0  ( $. 3 
Q2 
8 @ 6$ 
F 
 Q I  +11y1XX +22	5 3    $[#L2KLL
		
'	+	
 
 
 J	
)	7	  	 z	
	2	  5 5 5 5 5 5 5 5.g/ g/ g/ g/ g/ g/ g/ g/T4 4 4 4 4"6 4 4 4n    "6   , F7OO
F5d###
F5d###
F5y)))
F5y)))
F6	===
F6 3$GGG
F5	2FFF
F5~DAAA
F5~DAAA
F86)$???
F86)$???
F9F94@@@ &         	    !=	    0/
 <(	 	 	  21
"<(	 	 	  :9"+.(
	 	 	   ;:".0)
	  	  	   87 +.(
	 	 	  98 .0)
	 	 	  zIIIYRY[[Ax("X-69KKH	hS7	3	3	3 )q	$&'''%&'(
 
	) 
	)C --// ) )! ) )DGGD4K(((())
	)) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) s   7AKK!$K!