
    d                       d dl mZ d dlZd dlZd dlZd dlZd dlmZmZm	Z	 d dl
mZmZmZmZmZ d dlZd dlmZmZmZ d dlmZ d dlmZmZ d dlmZ d d	lmZmZm Z  d d
l!m"Z" 	 d dl#Z#n# e$$ r dZ#Y nw xY werd dl%m&Z& d dl'm(Z( eZ) ed          Z*dZ+ G d dee                    Z, G d de,d                   Z- G d de,d                   Z. G d deee                    Z/ G d de/d                   Z0 G d de/d                   Z1dS )    )annotationsN)HashableIteratorMapping)TYPE_CHECKINGAnyCallableGenericTypeVar)dtypesduck_array_opsutils)CoarsenArithmetic)OPTIONS_get_keep_attrs)is_duck_dask_array)CoarsenBoundaryOptionsSideOptionsT_Xarray)either_dict_or_kwargs	DataArrayDataset_Ta  Reduce this object's data windows by applying `{name}` along its dimension.

Parameters
----------
keep_attrs : bool, default: None
    If True, the attributes (``attrs``) will be copied from the original
    object to the new one. If False, the new object will be returned
    without attributes. If None uses the global default.
**kwargs : dict
    Additional keyword arguments passed on to `{name}`.

Returns
-------
reduced : same type as caller
    New object with `{name}` applied along its rolling dimension.
c                     e Zd ZdZdZdZ	 	 d;d<dZd=dZd>dZe	d>d            Z
	 d?d@dZd Ze                    d          e_         ed ej                  Z ed!ej                  Z ed"ej                  Z ed#ej                  Z ed$d%          Z ed&d'          Z edde          Z ed(d          Z ed)d          Z ed*d          ZdAd-Zd?dAd.Ze                    d/          e_        	 	 	 dBdCd9Zd: ZdS )DRollingzA object that implements the moving window pattern.

    See Also
    --------
    xarray.Dataset.groupby
    xarray.DataArray.groupby
    xarray.Dataset.rolling
    xarray.DataArray.rolling
    )objwindowmin_periodscenterdim)r   r    r!   r"   NFr   r   windowsMapping[Any, int]r    
int | Noner!   bool | Mapping[Any, bool]returnNonec                   g | _         g | _        |                                D ]N\  }}| j                             |           |dk    rt	          d          | j                            |           O|                     |d          | _        || _        ||dk    rt	          d          |t          j	        | j                  n|| _
        dS )ac  
        Moving window object.

        Parameters
        ----------
        obj : Dataset or DataArray
            Object to window.
        windows : mapping of hashable to int
            A mapping from the name of the dimension to create the rolling
            window along (e.g. `time`) to the size of the moving window.
        min_periods : int or None, default: None
            Minimum number of observations in window required to have a value
            (otherwise result is NA). The default, None, is equivalent to
            setting min_periods equal to the size of the window.
        center : bool or dict-like Hashable to bool, default: False
            Set the labels at the center of the window. If dict-like, set this
            property per rolling dimension.

        Returns
        -------
        rolling : type of input argument
        r   zwindow must be > 0FdefaultNz-min_periods must be greater than zero or None)r"   r   itemsappend
ValueError_mapping_to_listr!   r   mathprodr    )selfr   r#   r    r!   dws          3lib/python3.11/site-packages/xarray/core/rolling.py__init__zRolling.__init__A   s    : $&!#MMOO 	" 	"DAqHOOAAvv !5666Kq!!!!++FE+BB  "{a'7'7LMMM '2&9DIdk"""{ 	    strc                    d t          | j        | j        | j                  D             }d                    | j        j        d                    |                    S )z-provide a nice str repr of our rolling objectc                N    g | ]"\  }}}d                      |||rdnd          #S )z{k}->{v}{c}z(center) )kvc)format).0r<   r4   r>   s       r5   
<listcomp>z$Rolling.__repr__.<locals>.<listcomp>t   sL     
 
 
1a   11-DZZ" EE
 
 
r7   {klass} [{attrs}],klassattrs)zipr"   r   r!   r?   	__class____name__joinr2   rF   s     r5   __repr__zRolling.__repr__q   se    
 
txdkBB
 
 
 #)).)% * 
 
 	
r7   intc                N     t          j         fd j        D                       S )Nc              3  <   K   | ]}j         j        |         V  d S N)r   sizesr@   r3   r2   s     r5   	<genexpr>z"Rolling.__len__.<locals>.<genexpr>}   s,      ==q*======r7   )r0   r1   r"   r2   s   `r5   __len__zRolling.__len__|   s*    y====DH======r7   c                *    t          | j                  S rP   )lenr"   rT   s    r5   ndimzRolling.ndim   s    48}}r7   namefillnar   rolling_agg_funcCallable | NoneCallable[..., T_Xarray]c                    rdnt          t          |           t          t          d| z   d          dfd	}| |_        t                              |           |_        |S )zConstructs reduction methods built on a numpy reduction function (e.g. sum),
        a bottleneck reduction function (e.g. move_sum), or a Rolling reduction (_mean).
        Nmove_c                T    |                      |          } | j        f|d|S )N)
keep_attrsrZ   )r   _numpy_or_bottleneck_reduce)r2   ra   kwargsarray_agg_funcbottleneck_move_funcrZ   r[   s      r5   methodz&Rolling._reduce_method.<locals>.method   sR    --j99J343$  &    r7   rY   rP   )getattrr   
bottleneckrI   "_ROLLING_REDUCE_DOCSTRING_TEMPLATEr?   __doc__)rY   rZ   r[   rf   rd   re   s    `` @@r5   _reduce_methodzRolling._reduce_method   s      	;!NN$^T::N&z7T>4HH
	 
	 
	 
	 
	 
	 
	 
	 
	 ;BBBMMr7   c                     | j         dddi|t          j        |                     d          | j        j        d          z  }|r| j        j        |_        |S )Nra   Fra   )dtypecopy )sumr   astypecountr   ro   rF   )r2   ra   rc   results       r5   _meanzRolling._mean   sj    55U5f558MJJ%J((U9
 9
 9
 
  	*8>FLr7   meanrg   argmaxargminmaxminr1      rr   r   stdvarmedianra   bool | Nonec                    t                      rP   )NotImplementedErrorr2   ra   s     r5   _countszRolling._counts   s    !###r7   c                    |                      |          }|                     |          }|| j        k    }|                    |          S Nrn   )r   r   r    where)r2   ra   rolling_countenough_periodss       r5   rt   zRolling.count   sI    ))*55

;;&$*::"">222r7   rt   Targ_T | Mapping[Any, _T]r+   	_T | Noneallow_defaultboolallow_allsamelist[_T]c                (   t          j                  rJ|rfd| j        D             S | j        D ]}|vrt          d| d          fd| j        D             S |rg| j        z  S | j        dk    rgS t          d| j         d          )Nc                <    g | ]}                     |          S rq   get)r@   r3   r   r+   s     r5   rA   z,Rolling._mapping_to_list.<locals>.<listcomp>   s'    >>>7++>>>r7   zArgument has no dimension key .c                     g | ]
}|         S rq   rq   )r@   r3   r   s     r5   rA   z,Rolling._mapping_to_list.<locals>.<listcomp>   s    ---qCF---r7   r|   z"Mapping argument is necessary for z
d-rolling.)r   is_dict_liker"   KeyErrorrX   r.   )r2   r   r+   r   r   r3   s    ``   r5   r/   zRolling._mapping_to_list   s     c"" 	. ?>>>>>TX>>>>X J JC<<"#HA#H#H#HIII  ----DH---- 	%549$$9>>5LSdiSSSTTTr7   c                *    |t          d          }|S NTr*   r   r   s     r5   r   zRolling._get_keep_attrs       (666Jr7   NF)
r   r   r#   r$   r    r%   r!   r&   r'   r(   r'   r8   )r'   rM   rP   )rY   r8   rZ   r   r[   r\   r'   r]   )ra   r   r'   r   )NTT)
r   r   r+   r   r   r   r   r   r'   r   ) rI   
__module____qualname__rk   	__slots___attributesr6   rL   rU   propertyrX   rl   rv   rj   r?   r   NINFrx   INFry   rz   r{   r1   rr   rw   r}   r~   r   r   rt   r/   r   rq   r7   r5   r   r   3   s         BI<K #',1.
 .
 .
 .
 .
`	
 	
 	
 	
> > > >    X EI    :   7==6=JJEM^Hfk22F^Hfj11F
.
,
,C
.

+
+C>&!$$D
.
"
"C>&$..D
.
%
%C
.
%
%C^Hd++F$ $ $ $3 3 3 3 3 7==7=KKEM
 """U U U U U(    r7   r   c                       e Zd ZdZ	 	 d%d& fdZd'dZddej        dfd(dZddej        dfd)dZ		 d*d+d!Z
d,d"Zd# Zd$ Z xZS )-DataArrayRolling)window_labelsNFr   r   r#   r$   r    r%   r!   r&   r'   r(   c                    t                                          ||||           | j        | j        d                  | _        dS )a!  
        Moving window object for DataArray.
        You should use DataArray.rolling() method to construct this object
        instead of the class constructor.

        Parameters
        ----------
        obj : DataArray
            Object to window.
        windows : mapping of hashable to int
            A mapping from the name of the dimension to create the rolling
            exponential window along (e.g. `time`) to the size of the moving window.
        min_periods : int, default: None
            Minimum number of observations in window required to have a value
            (otherwise result is NA). The default, None, is equivalent to
            setting min_periods equal to the size of the window.
        center : bool, default: False
            Set the labels at the center of the window.

        Returns
        -------
        rolling : type of input argument

        See Also
        --------
        xarray.DataArray.rolling
        xarray.DataArray.groupby
        xarray.Dataset.rolling
        xarray.Dataset.groupby
        )r    r!   r   N)superr6   r   r"   r   )r2   r   r#   r    r!   rH   s        r5   r6   zDataArrayRolling.__init__   sD    J 	g;vNNN "Xdhqk2r7   %Iterator[tuple[DataArray, DataArray]]c              #  ,  K   | j         dk    rt          d          | j        d         }t          | j        d                   }| j        d         r|dz   dz  nd}t          j        || j        j	        |         |z             }||z
  }d|d ||z
  <   t          | j        ||          D ]k\  }}}| j                            |t          ||          i          }	|	                    |g          }
|	                    |
| j        k              }	||	fV  ld S )Nr|   z)__iter__ is only supported for 1d-rollingr      )r"   )rX   r.   r"   rM   r   r!   nparanger   rQ   rG   r   iselslicert   r   r    )r2   dim0window0offsetstopsstartslabelstartstopr   countss              r5   __iter__zDataArrayRolling.__iter__  s+     9q==HIIIx{dk!n%%'+{1~<'A+!##1	&$(."6"?@@%&!6!!""%d&8&%"H"H 	" 	"E5$X]]D%t*<*<#=>>F\\tf\--F\\&D,<"<==F&/!!!!	" 	"r7   r|   
window_dim(Hashable | Mapping[Any, Hashable] | Nonestrideint | Mapping[Any, int]
fill_valuer   ra   r   window_dim_kwargsr   c                2     | j         | j        f||||d|S )aG  
        Convert this rolling object to xr.DataArray,
        where the window dimension is stacked as a new dimension

        Parameters
        ----------
        window_dim : Hashable or dict-like to Hashable, optional
            A mapping from dimension name to the new window dimension names.
        stride : int or mapping of int, default: 1
            Size of stride for the rolling window.
        fill_value : default: dtypes.NA
            Filling value to match the dimension size.
        keep_attrs : bool, default: None
            If True, the attributes (``attrs``) will be copied from the original
            object to the new one. If False, the new object will be returned
            without attributes. If None uses the global default.
        **window_dim_kwargs : Hashable, optional
            The keyword arguments form of ``window_dim`` {dim: new_name, ...}.

        Returns
        -------
        DataArray that is a view of the original array. The returned array is
        not writeable.

        Examples
        --------
        >>> da = xr.DataArray(np.arange(8).reshape(2, 4), dims=("a", "b"))

        >>> rolling = da.rolling(b=3)
        >>> rolling.construct("window_dim")
        <xarray.DataArray (a: 2, b: 4, window_dim: 3)>
        array([[[nan, nan,  0.],
                [nan,  0.,  1.],
                [ 0.,  1.,  2.],
                [ 1.,  2.,  3.]],
        <BLANKLINE>
               [[nan, nan,  4.],
                [nan,  4.,  5.],
                [ 4.,  5.,  6.],
                [ 5.,  6.,  7.]]])
        Dimensions without coordinates: a, b, window_dim

        >>> rolling = da.rolling(b=3, center=True)
        >>> rolling.construct("window_dim")
        <xarray.DataArray (a: 2, b: 4, window_dim: 3)>
        array([[[nan,  0.,  1.],
                [ 0.,  1.,  2.],
                [ 1.,  2.,  3.],
                [ 2.,  3., nan]],
        <BLANKLINE>
               [[nan,  4.,  5.],
                [ 4.,  5.,  6.],
                [ 5.,  6.,  7.],
                [ 6.,  7., nan]]])
        Dimensions without coordinates: a, b, window_dim

        )r   r   r   ra   )
_constructr   )r2   r   r   r   ra   r   s         r5   	constructzDataArrayRolling.construct  s@    D tH
!!!
 
  
 
 	
r7   c                :   ddl m} |                     |          }|5t                    dk    rt	          d          fd| j        D             }|                     |dd          }|                     |d          }	|j                            | j        | j	        || j
        |	          }
|r|j        ni } ||
|j        t          |          z   |j        ||j        
          }|                    d t#          | j        |	          D                       S )Nr   r   <Either window_dim or window_dim_kwargs need to be specified.c                <    i | ]}|t          |                   S rq   r8   r@   r3   r   s     r5   
<dictcomp>z/DataArrayRolling._construct.<locals>.<dictcomp>x  '    III1!.s1vv6IIIr7   Fr   r   r|   r*   )r   )dimscoordsrF   rY   c                8    i | ]\  }}|t          d d |          S rP   r   r@   r3   ss      r5   r   z/DataArrayRolling._construct.<locals>.<dictcomp>  s*    WWW1AuT433WWWr7   )xarray.core.dataarrayr   r   rW   r.   r"   r/   variablerolling_windowr   r!   rF   r   tupler   rY   r   rG   )r2   r   r   r   r   ra   r   r   window_dimsstridesr   rF   ru   s         `      r5   r   zDataArrayRolling._constructf  sX    	433333))*55
$%%** R   JIIIIIIJ++e5 , 
 
 '''::,,Hdk;
 - 
 
 (/		RE+...:
 
 
 {{WWDHg@V@VWWWXXXr7   funcr	   rc   c                                          |          } fd j        D             }|                    dt          j                  }|t          j        ur j                            |          }n j        }                     ||||          } |j        |ft          |
                                          |d|}                     d          }	|                    |	 j        k              S )a  Reduce the items in this group by applying `func` along some
        dimension(s).

        Parameters
        ----------
        func : callable
            Function which can be called in the form
            `func(x, **kwargs)` to return the result of collapsing an
            np.ndarray over an the rolling dimension.
        keep_attrs : bool, default: None
            If True, the attributes (``attrs``) will be copied from the original
            object to the new one. If False, the new object will be returned
            without attributes. If None uses the global default.
        **kwargs : dict
            Additional keyword arguments passed on to `func`.

        Returns
        -------
        reduced : DataArray
            Array with summarized data.

        Examples
        --------
        >>> da = xr.DataArray(np.arange(8).reshape(2, 4), dims=("a", "b"))
        >>> rolling = da.rolling(b=3)
        >>> rolling.construct("window_dim")
        <xarray.DataArray (a: 2, b: 4, window_dim: 3)>
        array([[[nan, nan,  0.],
                [nan,  0.,  1.],
                [ 0.,  1.,  2.],
                [ 1.,  2.,  3.]],
        <BLANKLINE>
               [[nan, nan,  4.],
                [nan,  4.,  5.],
                [ 4.,  5.,  6.],
                [ 5.,  6.,  7.]]])
        Dimensions without coordinates: a, b, window_dim

        >>> rolling.reduce(np.sum)
        <xarray.DataArray (a: 2, b: 4)>
        array([[nan, nan,  3.,  6.],
               [nan, nan, 15., 18.]])
        Dimensions without coordinates: a, b

        >>> rolling = da.rolling(b=3, min_periods=1)
        >>> rolling.reduce(np.nansum)
        <xarray.DataArray (a: 2, b: 4)>
        array([[ 0.,  1.,  3.,  6.],
               [ 4.,  9., 15., 18.]])
        Dimensions without coordinates: a, b
        c                V    i | ]%}|t          j        j        j        d |           &S _rolling_dim_r   get_temp_dimnamer   r   rR   s     r5   r   z+DataArrayRolling.reduce.<locals>.<dictcomp>  E     
 
 
 u%dhm5HQ5H5HII
 
 
r7   rZ   )ra   r   )r"   ra   Frn   )r   r"   popr   NAr   rZ   r   reducelistvaluesr   r   r    )
r2   r   ra   rc   rolling_dimrZ   r   r#   ru   r   s
   `         r5   r   zDataArrayRolling.reduce  s   n ))*55

 
 
 
X
 
 
 Hfi00""(//&))CC(C// " 
 
  
;--//00Z
 
KQ
 

 //||Fd&66777r7   c                     fd j         D             } j                            |                              d t	           j          j                  D              fdt           j                   D                                           |d|                              t          |
                                          d|          }|S )	z1Number of non-nan entries in each rolling window.c                V    i | ]%}|t          j        j        j        d |           &S r   r   rR   s     r5   r   z,DataArrayRolling._counts.<locals>.<dictcomp>  r   r7   rn   c                    i | ]\  }}||	S rq   rq   )r@   r3   r4   s      r5   r   z,DataArrayRolling._counts.<locals>.<dictcomp>  s    ===$!QA===r7   c                2    i | ]\  }}|j         |         S rq   r!   )r@   ir3   r2   s      r5   r   z,DataArrayRolling._counts.<locals>.<dictcomp>  s%    JJJda4;q>JJJr7   r   F)r   ra   )r"   skipnara   )r"   r   notnullrollingrG   r   	enumerater   rr   r   r   )r2   ra   r   r   s   `   r5   r   zDataArrayRolling._counts  s    
 
 
 
X
 
 
 H
33W==#dh"<"<===JJJJi6I6IJJJ    Y{uYLLST+,,..//*SUU 	 r7   c                   ddl m} | j        | j        dk    rd}n| j        }| j                            | j        d                   }| j        j        }| j        d         rt          |j	                  r`| j
        d         dz    dz  }| j
        d         dz
  dz  }	t          d           f|z  t          |	|	| j        j        |         z             fz   }
n:| j
        d          dz  dz   }t          d           f|z  t          | d           fz   }
|                    | j        d         d| fid          }t          |j	                  rt          d           ||j	        | j
        d         ||          }| j        d         r||
         }|r| j        j        ni } ||| j        j        || j        j        	          S )
Nr   r   r|   r   constant)modezshould not be reachable)r   	min_countaxis)rF   rY   )r   r   r    r   get_axis_numr"   r   r!   r   datar   r   shapepadAssertionErrorrF   r   rY   )r2   r   ra   rc   r   r   r   paddedshiftr   validr   rF   s                r5   _bottleneck_reducez#DataArrayRolling._bottleneck_reduce  s   333333
 'D,<,A,AII(Ix$$TXa[11";q> 	M!&+.. 
G +a.1,-2+a.1,2t-&&48>$+?"?@@1  +a.A-2t-vt1D1D0FFZZ!q5&k :ZLLFfk** 	 !:;;;TDKNid  F ;q> 	#E]F",4"yDHMRRRRr7   c                Z   d|v r(t          j        d| j         dt          d           |d= t          d         r6|4t          | j        j                  s| j        dk    r | j	        |fd|i|S |r  || | 
                    |          	          S ||t          j        u r!t          j        | j        j        d
          }n.|t          j        u r t          j        | j        j        d
          }|                    dd           |                    d|            | j        |fd|i|S )Nr"   z7Reductions are applied along the rolling dimension(s) 'zA'. Passing the 'dim' kwarg to reduction operations has no effect.   )
stackleveluse_bottleneckr|   ra   rn   T)max_for_int)min_for_intr   FrZ   )warningswarnr"   DeprecationWarningr   r   r   r   rX   r   r   r   r   get_pos_infinityro   r   get_neg_infinity
setdefaultr   )r2   rd   re   r[   ra   rZ   rc   s          r5   rb   z,DataArrayRolling._numpy_or_bottleneck_reduce  s    F??M-H- - - #    u $%	$0&tx}55 1	Q
 +4*$ 1;?E    	W##DT5I5I*5U5UVVVV##0TRRR6;&&0TRRRh...h///t{>KKjKFKKKr7   r   )
r   r   r#   r$   r    r%   r!   r&   r'   r(   )r'   r   )r   r   r   r   r   r   ra   r   r   r   r'   r   )r   r   r   r   r   r   r   r   ra   r   r   r   r'   r   rP   r   r	   ra   r   rc   r   r'   r   )ra   r   r'   r   )rI   r   r   r   r6   r   r   r   r   r   r   r   r   rb   __classcell__rH   s   @r5   r   r      s'       "I #',1(3 (3 (3 (3 (3 (3 (3T" " " "* @D*+ )"&I
 I
 I
 I
 I
\ @D*+ )"&&Y &Y &Y &Y &YR 9=N8 N8 N8 N8 N8`   ,(S (S (ST)L )L )L )L )L )L )Lr7   r   r   c                  f     e Zd ZdZ	 	 d#d$ fdZd Z	 d%d&dZd'dZd Zdde	j
        dfd(d"Z xZS ))DatasetRolling)rollingsNFr   r   r#   r$   r    r%   r!   r&   r'   r(   c                    t                                          |||           t           fd j        D                       rt	           j                  i  _         j        j                                        D ]{\  }}g i }}t           j                  D ]3\  }}	|	|j
        v r%|                    |	            j        |         ||	<   4|r(fd|D             }
t          ||
||           j        |<   |dS )a:  
        Moving window object for Dataset.
        You should use Dataset.rolling() method to construct this object
        instead of the class constructor.

        Parameters
        ----------
        obj : Dataset
            Object to window.
        windows : mapping of hashable to int
            A mapping from the name of the dimension to create the rolling
            exponential window along (e.g. `time`) to the size of the moving window.
        min_periods : int, default: None
            Minimum number of observations in window required to have a value
            (otherwise result is NA). The default, None, is equivalent to
            setting min_periods equal to the size of the window.
        center : bool or mapping of hashable to bool, default: False
            Set the labels at the center of the window.

        Returns
        -------
        rolling : type of input argument

        See Also
        --------
        xarray.Dataset.rolling
        xarray.DataArray.rolling
        xarray.Dataset.groupby
        xarray.DataArray.groupby
        c              3  4   K   | ]}|j         j        vV  d S rP   r   r   rR   s     r5   rS   z*DatasetRolling.__init__.<locals>.<genexpr>s  s,      88!q%888888r7   c                "    i | ]}||         S rq   rq   )r@   r3   r#   s     r5   r   z+DatasetRolling.__init__.<locals>.<dictcomp>  s    111qQ
111r7   N)r   r6   anyr"   r   r  r   	data_varsr,   r   r   r-   r!   r   )r2   r   r#   r    r!   keydar   r   r3   r4   rH   s   ` `        r5   r6   zDatasetRolling.__init__M  s#   J 	g{F;;;8888tx88888 	%48$$$x)//11 
	R 
	RGCr&D!$(++ / /1<<KKNNN $AF1I R1111D111%5b![&%Q%Qc"
	R 
	Rr7   c                   ddl m} |                     |          }i }| j        j                                        D ]p\  }t          fd| j        D                       r || j        |         fd|i|||<   ?| j        |         	                                ||<   |si ||         _
        q|r| j        j
        ni } ||| j        j        |          S )Nr   r   c              3  *   K   | ]}|j         v V  d S rP   r   r@   r3   r  s     r5   rS   z9DatasetRolling._dataset_implementation.<locals>.<genexpr>  s)      22A1<222222r7   ra   r   rF   )xarray.core.datasetr   r   r   r  r,   r  r"   r  rp   rF   r   )	r2   r   ra   rc   r   reducedr  rF   r  s	           @r5   _dataset_implementationz&DatasetRolling._dataset_implementation  s    //////))*55
x)//11 	, 	,GC222222222 ,#tDM#$6XX:XQWXX#x}1133! ,)+GCL&",4"wwtxeDDDDr7   r   r	   ra   r   rc   r   r   c                ^     | j         t          j        t          j        |          fd|i|S )a  Reduce the items in this group by applying `func` along some
        dimension(s).

        Parameters
        ----------
        func : callable
            Function which can be called in the form
            `func(x, **kwargs)` to return the result of collapsing an
            np.ndarray over an the rolling dimension.
        keep_attrs : bool, default: None
            If True, the attributes (``attrs``) will be copied from the original
            object to the new one. If False, the new object will be returned
            without attributes. If None uses the global default.
        **kwargs : dict
            Additional keyword arguments passed on to `func`.

        Returns
        -------
        reduced : DataArray
            Array with summarized data.
        )r   ra   )r   	functoolspartialr   r   )r2   r   ra   rc   s       r5   r   zDatasetRolling.reduce  sI    0 ,t+.5DAAA
 
!
 
 
 	
r7   c                D    |                      t          j        |          S r   )r   r   r   r   s     r5   r   zDatasetRolling._counts  s'    ++$ , 
 
 	
r7   c                b     | j         t          j        t          j        |||          fd|i|S )N)rd   re   r[   ra   )r   r"  r#  r   rb   )r2   rd   re   r[   ra   rc   s         r5   rb   z*DatasetRolling._numpy_or_bottleneck_reduce  sX     ,t+ <-%9!1	  	
 	
 "	
 	
 	
 		
r7   r|   r   r   r   r   r   r   r   c                R   ddl m} |                     |          }|5t                    dk    rt	          d          fd| j        D             }|                     |dd          |                     |d	          i }| j        j        	                                D ]\  }fd
| j        D             }	|	rjfdt          | j                  D             }
fdt          | j                  D             }| j        |                             |
|||          ||<   n                                ||<   |si ||         _        |r| j        j        ni } ||| j        j        |                              d t#          | j                  D                       S )a  
        Convert this rolling object to xr.Dataset,
        where the window dimension is stacked as a new dimension

        Parameters
        ----------
        window_dim : str or mapping, optional
            A mapping from dimension name to the new window dimension names.
            Just a string can be used for 1d-rolling.
        stride : int, optional
            size of stride for the rolling window.
        fill_value : Any, default: dtypes.NA
            Filling value to match the dimension size.
        **window_dim_kwargs : {dim: new_name, ...}, optional
            The keyword arguments form of ``window_dim``.

        Returns
        -------
        Dataset with variables converted from rolling object.
        r   r   Nr   c                <    i | ]}|t          |                   S rq   r   r   s     r5   r   z,DatasetRolling.construct.<locals>.<dictcomp>  r   r7   Fr   r|   r*   c                &    g | ]}|j         v |S rq   r  r  s     r5   rA   z,DatasetRolling.construct.<locals>.<listcomp>  s     888!1<<A<<<r7   c                :    i | ]\  }}|j         v ||         S rq   r  )r@   r   r3   r  r   s      r5   r   z,DatasetRolling.construct.<locals>.<dictcomp>  s,    XXXDAq1PRPW<<aQ<<<r7   c                :    i | ]\  }}|j         v ||         S rq   r  )r@   r   r3   r  r   s      r5   r   z,DatasetRolling.construct.<locals>.<dictcomp>  s*    TTT1qBG||a|||r7   )r   r   r   ra   r  c                8    i | ]\  }}|t          d d |          S rP   r   r   s      r5   r   z,DatasetRolling.construct.<locals>.<dictcomp>  s*    HHHAQdD!$$HHHr7   )r  r   r   rW   r.   r"   r/   r   r  r,   r   r  r   rp   rF   r   r   rG   )r2   r   r   r   ra   r   r   datasetr  r   wistrF   r  r   r   s        `       @@@r5   r   zDatasetRolling.construct  s   : 	0/////))*55
$%%** R   JIIIIIIJ++e5 , 
 
 '''::x)//11 	( 	(GC8888tx888D )XXXXXIdh4G4GXXXTTTTT	$(0C0CTTT#}S1;;!))	  <      "wwyy  (%'"",4"wwtxeDDDIIHHTXw1G1GHHH
 
 	
r7   r   )
r   r   r#   r$   r    r%   r!   r&   r'   r(   rP   r  )ra   r   r'   r   )r   r   r   r   r   r   ra   r   r   r   r'   r   )rI   r   r   r   r6   r   r   r   rb   r   r   r   r  r  s   @r5   r  r  J  s        I #',14R 4R 4R 4R 4R 4R 4RlE E E& 9=
 
 
 
 
<
 
 
 


 
 
* @D*+ )"&F
 F
 F
 F
 F
 F
 F
 F
 F
r7   r  r   c                  J    e Zd ZU dZdZdZded<   ddZd ZddZ		 	 dddZ
dS )CoarsenzoA object that implements the coarsen.

    See Also
    --------
    Dataset.coarsen
    DataArray.coarsen
    )r   boundary
coord_funcr#   sidetrim_excess)r#   r3  r4  r   r   r#   r$   r1  r   r3  'SideOptions | Mapping[Any, SideOptions]r2  -str | Callable | Mapping[Any, str | Callable]r'   r(   c                z    | _         | _        | _        | _         fd|                                D             }|r%t          d|d j         j        j         d          t          j	                  sfd j         j
        D              j         j        D ]}|vrt          j        |<    _        dS )a*  
        Moving window object.

        Parameters
        ----------
        obj : Dataset or DataArray
            Object to window.
        windows : mapping of hashable to int
            A mapping from the name of the dimension to create the rolling
            exponential window along (e.g. `time`) to the size of the moving window.
        boundary : {"exact", "trim", "pad"}
            If 'exact', a ValueError will be raised if dimension size is not a
            multiple of window size. If 'trim', the excess indexes are trimmed.
            If 'pad', NA will be padded.
        side : 'left' or 'right' or mapping from dimension to 'left' or 'right'
        coord_func : function (name) or mapping from coordinate name to function (name).

        Returns
        -------
        coarsen
        c                0    g | ]}|j         j        v|S rq   r  )r@   r"   r2   s     r5   rA   z$Coarsen.__init__.<locals>.<listcomp>J  s'    QQQs48=8P8Ps8P8P8Pr7   zDimensions z not found in r   c                    i | ]}|S rq   rq   )r@   r3   r2  s     r5   r   z$Coarsen.__init__.<locals>.<dictcomp>P  s    ???A!Z???r7   N)r   r#   r3  r1  keysr.   rH   rI   r   r   r   r   r   rw   r2  )r2   r   r#   r1  r3  r2  absent_dimsr>   s   `    `  r5   r6   zCoarsen.__init__(  s    : 	 QQQQgllnnQQQ 	YkYY48;M;VYYY   !*-- 	@???????J 	4 	4A
"" . 3
1=Gr7   c                *    |t          d          }|S r   r   r   s     r5   r   zCoarsen._get_keep_attrsV  r   r7   r8   c                      fd j         D             }d                     j        j        d                    |                    S )z-provide a nice str repr of our coarsen objectc                \    g | ](}t          |d           | dt          |           )S )Nz->)rh   )r@   r<   r2   s     r5   rA   z$Coarsen.__repr__.<locals>.<listcomp>_  sM     
 
 
tQ%%1 &&GD!$$&&111r7   rB   rC   rD   )r   r?   rH   rI   rJ   rK   s   ` r5   rL   zCoarsen.__repr__\  sa    
 
 
 
%
 
 

 #)).)% * 
 
 	
r7   Nc           	         ddl m} ddlm} t	          |d          st          d          t          d                                 D                       }|rt          d|           |t          d	
          }t                    t           j
                  z
  }|rt          d|           t           j
                  t                    z
  }|rt          d|            |            }	t           j        |          r j                                        }
n j        }
|r|
j        ni |	_        |
j                                        D ]\  }t          t!          j        fdt%          j                  D                        }|j        k    rG fdD             }                    | j         j                  \  }}|rj        ni }|||f|	|<   |	|<   t                    t           j        j                  z  t           j        j                  z  }|	                    |          }t           j        |          r j                            |          S |S )a  
        Convert this Coarsen object to a DataArray or Dataset,
        where the coarsening dimension is split or reshaped to two
        new dimensions.

        Parameters
        ----------
        window_dim: mapping
            A mapping from existing dimension name to new dimension names.
            The size of the second dimension will be the length of the
            coarsening window.
        keep_attrs: bool, optional
            Preserve attributes if True
        **window_dim_kwargs : {dim: new_name, ...}
            The keyword arguments form of ``window_dim``.

        Returns
        -------
        Dataset or DataArray with reshaped dimensions

        Examples
        --------
        >>> da = xr.DataArray(np.arange(24), dims="time")
        >>> da.coarsen(time=12).construct(time=("year", "month"))
        <xarray.DataArray (year: 2, month: 12)>
        array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11],
               [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]])
        Dimensions without coordinates: year, month

        See Also
        --------
        DataArrayRolling.construct
        DatasetRolling.construct
        r   r   r   zCoarsen.constructr   c              3  p   K   | ]1\  }}t          |          d k    st          |t                    -|V  2dS )r   N)rW   
isinstancer8   )r@   winr   s      r5   rS   z$Coarsen.construct.<locals>.<genexpr>  sL       
 
T4yyA~~D#!6!6~ ~~~
 
r7   zTPlease provide exactly two dimension names for the following coarsening dimensions: NTr*   zI'window_dim' must contain entries for all dimensions to coarsen. Missing z='window_dim' includes dimensions that will not be coarsened: c                >    g | ]}                     ||g          S rq   r   )r@   r"   r   s     r5   rA   z%Coarsen.construct.<locals>.<listcomp>  s)    !W!W!W*..se"<"<!W!W!Wr7   c                >    i | ]}|j         v |j        |         S rq   )r   r#   )r@   r4   r2   r~   s     r5   r   z%Coarsen.construct.<locals>.<dictcomp>  s(    SSS!Q#(]]1dl1o]]]r7   )r   r   r  r   r   r.   r   r,   r   setr#   rA  r   _to_temp_datasetrF   	variables	itertoolschainr   r   coarsen_reshaper1  r3  r   
set_coords_from_temp_dataset)r2   r   ra   r   r   r   bad_new_dimsmissing_dimsextra_windowsreshapedr   r  reshaped_dimsr#   reshaped_var_rF   should_be_coordsru   r~   s   ``                 @r5   r   zCoarsen.constructh  s   R 	433333//////*)+>
 

  	N    
 
'--//
 
 
 
 

  	ugsuu   (666J:T\):):: 	j\hjj   DL))C
OO; 	_P]__   799dh	** 	(++--CC(C&08b++-- 
	$ 
	$HC!!W!W!W!WSX!W!W!WX M ((SSSSSzSSS"%"5"5gt}di"X"Xa%/7		R!.e D #  
OOc$(/.B.BBcHOG
 G
 
 $$%566dh	** 	8..v666Mr7   )r   r   r#   r$   r1  r   r3  r5  r2  r6  r'   r(   r   )NN)r'   r   )rI   r   r   rk   r   r   __annotations__r6   r   rL   r   rq   r7   r5   r0  r0    s          I 5KMMM,H ,H ,H ,H\  

 

 

 

 h h h h h h hr7   r0  c                  >    e Zd ZdZdZe	 ddd            Z	 dddZdS )DataArrayCoarsenrq   r;   Fr   r	   include_skipnar   numeric_onlyr'   Callable[..., DataArray]c                *    i }|rd|d<   	 d
dfd	}|S )r
        Return a wrapped function for injecting reduction methods.
        see ops.inject_reduce_methods
        Nr   r2   rW  ra   r   r'   r   c                    ddl m}                      |          }  j        j        j         j         j         j        |fi |}i } j        j	        
                                D ]u\  }}| j        j        k    r|||<   t           fd|j        D                       r5 |j        j         j         j        |          j         j        |fi |||<   p|||<   v || j        j        | j        j                  S )Nr   r   c              3  *   K   | ]}|j         v V  d S rP   )r#   rR   s     r5   rS   zHDataArrayCoarsen._reduce_method.<locals>.wrapped_func.<locals>.<genexpr>  s*      ==1,======r7   )r   r   rY   )r   r   r   r   r   coarsenr#   r1  r3  r   r,   rY   r  r   r2  )	r2   ra   rc   r   r  r   r>   r=   r   s	   `       r5   wrapped_funcz5DataArrayCoarsen._reduce_method.<locals>.wrapped_func  sK    877777--j99J/dh'/dDM49j LR G F--// & &1%% 'F1II====af===== 
&$6AJ$6 L OA. M I&% % %% %q		 %&q		9dhmF   r7   rP   )r2   rW  ra   r   r'   r   rq   clsr   rX  rY  rc   r`  s    `    r5   rl   zDataArrayCoarsen._reduce_method  sM     "$ 	$#F8 ?C	 	 	 	 	 	 	< r7   Nra   r   r   c                B    |                      |          } || fd|i|S )a  Reduce the items in this group by applying `func` along some
        dimension(s).

        Parameters
        ----------
        func : callable
            Function which can be called in the form `func(x, axis, **kwargs)`
            to return the result of collapsing an np.ndarray over the coarsening
            dimensions.  It must be possible to provide the `axis` argument
            with a tuple of integers.
        keep_attrs : bool, default: None
            If True, the attributes (``attrs``) will be copied from the original
            object to the new one. If False, the new object will be returned
            without attributes. If None uses the global default.
        **kwargs : dict
            Additional keyword arguments passed on to `func`.

        Returns
        -------
        reduced : DataArray
            Array with summarized data.

        Examples
        --------
        >>> da = xr.DataArray(np.arange(8).reshape(2, 4), dims=("a", "b"))
        >>> coarsen = da.coarsen(b=2)
        >>> coarsen.reduce(np.sum)
        <xarray.DataArray (a: 2, b: 2)>
        array([[ 1,  5],
               [ 9, 13]])
        Dimensions without coordinates: a, b
        ra   rl   r2   r   ra   rc   r`  s        r5   r   zDataArrayCoarsen.reduce  s5    F **400|DBBZB6BBBr7   FF)r   r	   rX  r   rY  r   r'   rZ  rP   )r   r	   ra   r   r'   r   rI   r   r   r   _reduce_extra_args_docstringclassmethodrl   r   rq   r7   r5   rW  rW    sk        I#) PU) ) ) ) [)X 9=$C $C $C $C $C $C $Cr7   rW  c                  <    e Zd ZdZdZe	 ddd            ZdddZdS )DatasetCoarsenrq   r;   Fr   r	   rX  r   rY  r'   Callable[..., Dataset]c                *    i }|rd|d<   	 d
dfd	}|S )r\  Nr   r2   rk  ra   r   r'   r   c                   ddl m} |                     |          }|r| j        j        }ni }i }| j        j                                        D ]/\  }} |j        j        | j	        | j
        | j        fd|i|||<   0i }| j        j                                        D ]:\  }	}
 |
j        j        | j	        | j        |	         | j
        | j        fd|i|||	<   ; ||||          S )Nr   r   ra   r  )r  r   r   r   rF   r  r,   r   r_  r#   r1  r3  r   r2  )r2   ra   rc   r   rF   r  r  r  r   r>   r=   r   s              r5   r`  z3DatasetCoarsen._reduce_method.<locals>.wrapped_func<  sE    433333--j99J G8-3355  R2r{2LMI	   
  *      F--// 
 
1 /AJ.LOA&MI	 
  *  q		 776????r7   rP   )r2   rk  ra   r   r'   r   rq   ra  s    `    r5   rl   zDatasetCoarsen._reduce_method0  sU     "$ 	$#F8 =A$	@ $	@ $	@ $	@ $	@ $	@ $	@L r7   Nr   c                B    |                      |          } || fd|i|S )an  Reduce the items in this group by applying `func` along some
        dimension(s).

        Parameters
        ----------
        func : callable
            Function which can be called in the form `func(x, axis, **kwargs)`
            to return the result of collapsing an np.ndarray over the coarsening
            dimensions.  It must be possible to provide the `axis` argument with
            a tuple of integers.
        keep_attrs : bool, default: None
            If True, the attributes (``attrs``) will be copied from the original
            object to the new one. If False, the new object will be returned
            without attributes. If None uses the global default.
        **kwargs : dict
            Additional keyword arguments passed on to `func`.

        Returns
        -------
        reduced : Dataset
            Arrays with summarized data.
        ra   rd  re  s        r5   r   zDatasetCoarsen.reduced  s4    . **400|DBBZB6BBBr7   rf  )r   r	   rX  r   rY  r   r'   rl  rP   )r   r	   r'   r   rg  rq   r7   r5   rk  rk  +  sf        I#) PU1 1 1 1 [1fC C C C C C Cr7   rk  )2
__future__r   r"  rH  r0   r  collections.abcr   r   r   typingr   r   r	   r
   r   numpyr   xarray.corer   r   r   xarray.core.arithmeticr   xarray.core.optionsr   r   xarray.core.pycompatr   xarray.core.typesr   r   r   xarray.core.utilsr   ri   ImportErrorr   r   r  r   
RollingKeyr   rj   r   r   r  r0  rW  rk  rq   r7   r5   <module>r|     s   " " " " " "           7 7 7 7 7 7 7 7 7 7 A A A A A A A A A A A A A A     5 5 5 5 5 5 5 5 5 5 4 4 4 4 4 4 8 8 8 8 8 8 8 8 3 3 3 3 3 3 K K K K K K K K K K 3 3 3 3 3 3   JJJ  //////++++++J	B& "&e e e e egh e e ePlL lL lL lL lLw{+ lL lL lL^G
 G
 G
 G
 G
WY' G
 G
 G
T| | | | |!2 | | |~UC UC UC UC UCw{+ UC UC UCpQC QC QC QC QCWY' QC QC QC QC QCs   "A' 'A10A1