U
    Cvf                     @  s  d dl mZ d dlZd dlmZ d dlmZ d dlmZ d dl	m
Z
mZmZmZmZmZmZmZmZmZ d dlZd dlZd dlmZmZmZmZmZ d dlmZm Z  d d	l!m"Z" d d
l#m$Z$m%Z%m&Z& zd dl'Z'W n e(k
r   dZ'Y nX dZ)e
rd dl*Z*d dl+m,Z, d dl-m.Z. d dl/m0Z0 d dl1m2Z2 d dl3m4Z4 d dl5m6Z6 d dl7m8Z8m9Z9m:Z:m;Z;m<Z< d dl=m>Z> ee9eee9f f Z?edddZ@edZAedZBG dd dZCG dd dZDG dd dZEG dd  d ZFd]d!d"d#d$d%d&ZGG d'd( d(eFZHed^d)d*d+d)d,d-d.ZIed_d/d*d0d/d,d1d.ZIed`d2d*d+d2d,d3d.ZIedad4d*d0d4d,d5d.ZIedbd6d*d0d6d,d7d.ZIdcd6d*d0d6d,d8d.ZIddd2d*d9d2d,d:d;ZJeded)d+d)d<d=d>ZKedfd/d0d/d<d?d>ZKedgd2d+d2d<d@d>ZKedhd4d0d4d<dAd>ZKedid6d0d6d<dBd>ZKdjd6d0d6d<dCd>ZKedkd)d+d)d<dDdEZLedld/d0d/d<dFdEZLedmd2d+d2d<dGdEZLednd4d0d4d<dHdEZLedod6d0d6d<dIdEZLdpd6d0d6d<dJdEZLdKdLdMdNdOZMd9dPdQdRdSZNd9dPdQdTdUZOdPdVdWdXZPdPdVdYdZZQdPdVd[d\ZRdS )q    )annotationsN)suppress)escape)dedent)
TYPE_CHECKINGAnyCallableHashableIterableIteratorMappingTypeVarUnionoverload)dtypesduck_array_ops
formattingformatting_htmlops)OPTIONS_get_keep_attrs)is_duck_dask_array)Frozeneither_dict_or_kwargs	is_scalar.)	DTypeLike	DataArrayDataset)Index)Resample)
RollingExp)DatetimeLikeDTypeLikeSaveScalarOrArraySideOptionsT_DataWithCoordsVariable
T_Resampler!   )boundCTc                   @  s6   e Zd ZdZeddddddZedZedZd	S )
ImplementsArrayReduce r   boolfuncinclude_skipnanumeric_onlyc                   s&   |rd fdd	}nd fdd	}|S )Nc                   s   | j f  |||d|S )N)r2   dimaxisskipnareduce)selfr5   r6   r7   kwargsr2   r/   6/tmp/pip-unpacked-wheel-h316xyqg/xarray/core/common.pywrapped_funcG   s       z:ImplementsArrayReduce._reduce_method.<locals>.wrapped_funcc                   s   | j f  ||d|S )N)r2   r5   r6   r8   )r:   r5   r6   r;   r<   r/   r=   r>   N   s    )NNN)NNr/   clsr2   r3   r4   r>   r/   r<   r=   _reduce_methodC   s    z$ImplementsArrayReduce._reduce_methoda\          dim : str or sequence of str, optional
            Dimension(s) over which to apply `{name}`.
        axis : int or sequence of int, optional
            Axis(es) over which to apply `{name}`. Only one of the 'dim'
            and 'axis' arguments can be supplied. If neither are supplied, then
            `{name}` is calculated over axes.a	          dim : str or sequence of str, optional
            Dimension over which to apply `{name}`.
        axis : int or sequence of int, optional
            Axis over which to apply `{name}`. Only one of the 'dim'
            and 'axis' arguments can be supplied.N)	__name__
__module____qualname__	__slots__classmethodrA   r   _reduce_extra_args_docstring_cum_extra_args_docstringr/   r/   r/   r=   r.   @   s   
r.   c                   @  s>   e Zd ZdZeddddddZed Zed Z	d	S )
ImplementsDatasetReducer/   r   r0   r1   c                   s*   |rd fdd	}nd fdd	}|S )Nc                   s   | j f  ||d|S )N)r2   r5   r7   r4   r8   )r:   r5   r7   r;   r2   r4   r/   r=   r>   n   s    z<ImplementsDatasetReduce._reduce_method.<locals>.wrapped_funcc                   s   | j f  |d|S )N)r2   r5   r4   r8   )r:   r5   r;   rJ   r/   r=   r>   y   s      )NN)Nr/   r?   r/   rJ   r=   rA   j   s    z&ImplementsDatasetReduce._reduce_methodz
        dim : str or sequence of str, optional
            Dimension(s) over which to apply `{name}`.  By default `{name}` is
            applied over all dimensions.
        a  
        dim : str or sequence of str, optional
            Dimension over which to apply `{name}`.
        axis : int or sequence of int, optional
            Axis over which to apply `{name}`. Only one of the 'dim'
            and 'axis' arguments can be supplied.
        N)
rB   rC   rD   rE   rF   rA   r   striprG   rH   r/   r/   r/   r=   rI   g   s   rI   c                   @  s   e Zd ZdZdZdddddZdddd	d
ZdddddZdddddZd2ddddddZ	ddddZ
dd Zd3dddddd Zdd!dd"d#Zdd!dd$d%Zd&d'd(d)d*Zdd+dd,d-d.Zedd/dd0d1ZdS )4AbstractArrayz-Shared base class for DataArray and Variable.r/   r   r0   r:   returnc                 C  s
   t | jS N)r0   valuesr:   r/   r/   r=   __bool__   s    zAbstractArray.__bool__floatc                 C  s
   t | jS rO   )rS   rP   rQ   r/   r/   r=   	__float__   s    zAbstractArray.__float__intc                 C  s
   t | jS rO   )rU   rP   rQ   r/   r/   r=   __int__   s    zAbstractArray.__int__complexc                 C  s
   t | jS rO   )rW   rP   rQ   r/   r/   r=   __complex__   s    zAbstractArray.__complex__Nr   z
np.ndarray)r:   dtyperN   c                 C  s   t j| j|dS )NrY   )npasarrayrP   )r:   rY   r/   r/   r=   	__array__   s    zAbstractArray.__array__strrN   c                 C  s
   t | S rO   )r   
array_reprrQ   r/   r/   r=   __repr__   s    zAbstractArray.__repr__c                 C  s*   t d dkr dtt|  dS t| S )NZdisplay_styletextz<pre>z</pre>)r   r   reprr   r`   rQ   r/   r/   r=   _repr_html_   s    zAbstractArray._repr_html_ )r:   format_specrN   c                 C  s>   |dkr2| j dkr| j|S td| j  dn|  S d S )Nre   r/   zBUsing format_spec is only supported when shape is (). Got shape = .)shapedata
__format__NotImplementedErrorra   )r:   rf   r/   r/   r=   rj      s    
zAbstractArray.__format__zIterator[Any]c                 c  s    t t| D ]}| | V  qd S rO   )rangelen)r:   nr/   r/   r=   _iter   s    zAbstractArray._iterc                 C  s   | j dkrtd|  S )Nr   ziteration over a 0-d array)ndim	TypeErrorro   rQ   r/   r/   r=   __iter__   s    
zAbstractArray.__iter__zHashable | Iterable[Hashable]zint | tuple[int, ...]r5   rN   c                   s8   t |tr*t |ts*t fdd|D S  |S dS )aV  Return axis number(s) corresponding to dimension(s) in this array.

        Parameters
        ----------
        dim : str or iterable of str
            Dimension name(s) for which to lookup axes.

        Returns
        -------
        int or tuple of int
            Axis number or numbers corresponding to the given dimensions.
        c                 3  s   | ]}  |V  qd S rO   )_get_axis_num.0drQ   r/   r=   	<genexpr>   s     z-AbstractArray.get_axis_num.<locals>.<genexpr>N)
isinstancer
   r^   tuplert   r:   r5   r/   rQ   r=   get_axis_num   s    zAbstractArray.get_axis_numr	   )r:   r5   rN   c                 C  s<   z| j |W S  tk
r6   t|d| j Y nX d S )Nz not found in array dimensions )dimsindex
ValueErrorr{   r/   r/   r=   rt      s    zAbstractArray._get_axis_numzFrozen[Hashable, int]c                 C  s   t tt| j| jS )zOrdered mapping from dimension names to lengths.

        Immutable.

        See Also
        --------
        Dataset.sizes
        )r   dictzipr}   rh   rQ   r/   r/   r=   sizes   s    
zAbstractArray.sizes)N)re   )rB   rC   rD   __doc__rE   rR   rT   rV   rX   r]   ra   rd   rj   ro   rr   r|   rt   propertyr   r/   r/   r/   r=   rL      s    rL   c                      s   e Zd ZdZdZ fddZeddddZeddd	d
ZdddddZ	ddddddZ
ddddddZddddZddddZ  ZS )AttrAccessMixinz:Mixin class that allows getting keys with attribute accessr/   c                   sd   t t| dsn@| jdr0t| j dn"| j| _t	j
d| j dtdd t jf | dS )	zVerify that all subclasses explicitly define ``__slots__``. If they don't,
        raise error in the core xarray module and a FutureWarning in third-party
        extensions.
        __dict__zxarray.z! must explicitly define __slots__zxarray subclass z# should explicitly define __slots__   
stacklevelN)hasattrobject__new__rC   
startswithAttributeErrorrB   _setattr_dict__setattr__warningswarnFutureWarningsuper__init_subclass__)r@   r;   	__class__r/   r=   r      s    z!AttrAccessMixin.__init_subclass__z Iterable[Mapping[Hashable, Any]]r_   c                 c  s   dE dH  dS )z2Places to look-up items for attribute-style accessr/   Nr/   rQ   r/   r/   r=   _attr_sources  s    zAttrAccessMixin._attr_sourcesc                 c  s   dE dH  dS )z.Places to look-up items for key-autocompletionr/   Nr/   rQ   r/   r/   r=   _item_sources
  s    zAttrAccessMixin._item_sourcesr^   r   )namerN   c                 C  sX   |dkr<| j D ],}tt || W  5 Q R    S Q R X qtt| jd|d S )N>   __setstate__r   z object has no attribute )r   r   KeyErrorr   typerB   )r:   r   sourcer/   r/   r=   __getattr__  s    

 zAttrAccessMixin.__getattr__None)r   valuerN   c                 C  s@   t | || || jkr<tjd|dt| jdtdd dS )zADeprecated third party subclass (see ``__init_subclass__`` above)zSetting attribute  on a z object. Explicitly define __slots__ to suppress this warning for legitimate custom attributes and raise an error when attempting variables assignments.r   r   N)r   r   r   r   r   r   rB   r   )r:   r   r   r/   r/   r=   r     s    
zAttrAccessMixin._setattr_dictc              
   C  st   zt | || W n\ tk
rn } z>t|dt| j|kr@ td|dt| jd|W 5 d}~X Y nX dS )zObjects with ``__slots__`` raise AttributeError if you try setting an
        undeclared attribute. This is desirable, but the error message could use some
        improvement.
        z!{!r} object has no attribute {!r}zcannot set attribute r   zc object. Use __setitem__ styleassignment (e.g., `ds['name'] = ...`) instead of assigning variables.N)r   r   r   r^   formatr   rB   )r:   r   r   er/   r/   r=   r   ,  s    
 zAttrAccessMixin.__setattr__z	list[str]c                 C  s(   dd | j D }tttt| |B S )zZProvide method name lookup and completion. Only provide 'public'
        methods.
        c                 S  s$   h | ]}|D ]}t |tr|qqS r/   ry   r^   rv   r   itemr/   r/   r=   	<setcomp>C  s
    
z*AttrAccessMixin.__dir__.<locals>.<setcomp>)r   sortedsetdirr   )r:   Zextra_attrsr/   r/   r=   __dir__?  s    zAttrAccessMixin.__dir__c                 C  s   dd | j D }t|S )zProvide method for the key-autocompletions in IPython.
        See http://ipython.readthedocs.io/en/stable/config/integrating.html#tab-completion
        For the details.
        c                 S  s$   h | ]}|D ]}t |tr|qqS r/   r   r   r/   r/   r=   r   P  s
    
z<AttrAccessMixin._ipython_key_completions_.<locals>.<setcomp>)r   list)r:   itemsr/   r/   r=   _ipython_key_completions_K  s    z)AttrAccessMixin._ipython_key_completions_)rB   rC   rD   r   rE   r   r   r   r   r   r   r   r   r   __classcell__r/   r/   r   r=   r      s   r   $Hashable | Iterable[Hashable] | Noneint | Iterable[int] | Nonezlist[Hashable])r5   r6   rN   c                   s   |dk	r|dk	rt d|dkr<|dkr<dd j D S t|trZt|tsZt|}nn|dk	rj|g}n^|dk	svtt|tr|g}t|}t	dd |D rt
dtj   fdd|D }t	fd	d|D rt d
|S )z(Get a list of dimensions to squeeze out.Nz+cannot use both parameters `axis` and `dim`c                 S  s   g | ]\}}|d kr|qS )   r/   )rv   rw   sr/   r/   r=   
<listcomp>b  s      z$get_squeeze_dims.<locals>.<listcomp>c                 s  s   | ]}t |t V  qd S rO   )ry   rU   rv   ar/   r/   r=   rx   m  s     z#get_squeeze_dims.<locals>.<genexpr>z0parameter `axis` must be int or iterable of int.c                   s   g | ]} | qS r/   r/   r   )alldimsr/   r=   r   p  s     c                 3  s   | ]} j | d kV  qdS )r   N)r   rv   k)
xarray_objr/   r=   rx   r  s     zJcannot select a dimension to squeeze out which has length greater than one)r   r   r   ry   r
   r^   r   AssertionErrorrU   anyrq   keys)r   r5   r6   r/   )r   r   r=   get_squeeze_dimsY  s*    

r   c                   @  s  e Zd ZU dZded< ded< dZd]d	d
ddd	dddZd^ddd	dddd	dddZdddddZdddddd Z	d_d	d!d"d	d#d$d%Z
d	d"d"d	d&d'd(Zd)d"d"d*d+d,d-Zd`d	d/d0d1d2d3d4Zd5d6dd7d7d8d9d:dd;dd0d<d=d>d?Zejdfd	d"d"dd	d@dAdBZddCdDdEdFZdCdGdHdIZdad	dd	dJdKdLZdbd	dd	dJdMdNZd	d"d	dOdPdQZdddddRdSd	d	dTdUdVZd	d	dTdWdXZdCdGdYdZZd[d\ ZdS )cDataWithCoordsz,Shared base class for Dataset and DataArray.zCallable[[], None] | None_closezdict[Hashable, Index]_indexesr   NFr'   r   r0   r   )r:   r5   dropr6   rN   c                 C  s*   t | ||}| jf d|idd |D S )a9  Return a new object with squeezed data.

        Parameters
        ----------
        dim : None or Hashable or iterable of Hashable, optional
            Selects a subset of the length one dimensions. If a dimension is
            selected with length greater than one, an error is raised. If
            None, all length one dimensions are squeezed.
        drop : bool, default: False
            If ``drop=True``, drop squeezed coordinates instead of making them
            scalar.
        axis : None or int or iterable of int, optional
            Like dim, but positional.

        Returns
        -------
        squeezed : same type as caller
            This object, but with with all or a subset of the dimensions of
            length 1 removed.

        See Also
        --------
        numpy.squeeze
        r   c                 S  s   i | ]
}|d qS )r   r/   ru   r/   r/   r=   
<dictcomp>  s      z*DataWithCoords.squeeze.<locals>.<dictcomp>)r   isel)r:   r5   r   r6   r}   r/   r/   r=   squeeze  s    zDataWithCoords.squeeze)
keep_attrszScalarOrArray | Nonezbool | None)r:   minmaxr   rN   c                C  s4   ddl m} |dkrtdd}|tj| |||ddS )al  
        Return an array whose values are limited to ``[min, max]``.
        At least one of max or min must be given.

        Parameters
        ----------
        min : None or Hashable, optional
            Minimum value. If None, no lower clipping is performed.
        max : None or Hashable, optional
            Maximum value. If None, no upper clipping is performed.
        keep_attrs : bool or None, optional
            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.

        Returns
        -------
        clipped : same type as caller
            This object, but with with values < min are replaced with min,
            and those > max with max.

        See Also
        --------
        numpy.clip : equivalent function
        r   apply_ufuncNTdefaultallowed)r   dask)xarray.core.computationr   r   r[   clip)r:   r   r   r   r   r/   r/   r=   r     s     
     zDataWithCoords.clipr	   zpd.Index)keyrN   c                 C  sT   || j krt|z| j|  W S  tk
rN   tjt| j| |d Y S X dS )zDGet an index for a dimension, with fall-back to a default RangeIndex)r   N)r}   r   r   to_pandas_indexpdr    rl   r   )r:   r   r/   r/   r=   	get_index  s    
zDataWithCoords.get_indexr,   z"Mapping[Any, T | Callable[[C], T]]zdict[Hashable, T])r:   r;   rN   c                   s    fdd|  D S )Nc                   s&   i | ]\}}|t |r| n|qS r/   )callablerv   r   vrQ   r/   r=   r     s      z7DataWithCoords._calc_assign_results.<locals>.<dictcomp>)r   )r:   r;   r/   rQ   r=   _calc_assign_results  s    z#DataWithCoords._calc_assign_resultszMapping[Any, Any] | Noner   )r:   coordscoords_kwargsrN   c                 K  s2   t ||d}| jdd}| |}|j| |S )aQ  Assign new coordinates to this object.

        Returns a new object with all the original data in addition to the new
        coordinates.

        Parameters
        ----------
        coords : dict-like or None, optional
            A dict where the keys are the names of the coordinates
            with the new values to assign. If the values are callable, they are
            computed on this object and assigned to new coordinate variables.
            If the values are not callable, (e.g. a ``DataArray``, scalar, or
            array), they are simply assigned. A new coordinate can also be
            defined and attached to an existing dimension using a tuple with
            the first element the dimension name and the second element the
            values for this new coordinate.
        **coords_kwargs : optional
            The keyword arguments form of ``coords``.
            One of ``coords`` or ``coords_kwargs`` must be provided.

        Returns
        -------
        assigned : same type as caller
            A new object with the new coordinates in addition to the existing
            data.

        Examples
        --------
        Convert `DataArray` longitude coordinates from 0-359 to -180-179:

        >>> da = xr.DataArray(
        ...     np.random.rand(4),
        ...     coords=[np.array([358, 359, 0, 1])],
        ...     dims="lon",
        ... )
        >>> da
        <xarray.DataArray (lon: 4)>
        array([0.5488135 , 0.71518937, 0.60276338, 0.54488318])
        Coordinates:
          * lon      (lon) int64 358 359 0 1
        >>> da.assign_coords(lon=(((da.lon + 180) % 360) - 180))
        <xarray.DataArray (lon: 4)>
        array([0.5488135 , 0.71518937, 0.60276338, 0.54488318])
        Coordinates:
          * lon      (lon) int64 -2 -1 0 1

        The function also accepts dictionary arguments:

        >>> da.assign_coords({"lon": (((da.lon + 180) % 360) - 180)})
        <xarray.DataArray (lon: 4)>
        array([0.5488135 , 0.71518937, 0.60276338, 0.54488318])
        Coordinates:
          * lon      (lon) int64 -2 -1 0 1

        New coordinate can also be attached to an existing dimension:

        >>> lon_2 = np.array([300, 289, 0, 1])
        >>> da.assign_coords(lon_2=("lon", lon_2))
        <xarray.DataArray (lon: 4)>
        array([0.5488135 , 0.71518937, 0.60276338, 0.54488318])
        Coordinates:
          * lon      (lon) int64 358 359 0 1
            lon_2    (lon) int64 300 289 0 1

        Note that the same result can also be obtained with a dict e.g.

        >>> _ = da.assign_coords({"lon_2": ("lon", lon_2)})

        Note the same method applies to `Dataset` objects.

        Convert `Dataset` longitude coordinates from 0-359 to -180-179:

        >>> temperature = np.linspace(20, 32, num=16).reshape(2, 2, 4)
        >>> precipitation = 2 * np.identity(4).reshape(2, 2, 4)
        >>> ds = xr.Dataset(
        ...     data_vars=dict(
        ...         temperature=(["x", "y", "time"], temperature),
        ...         precipitation=(["x", "y", "time"], precipitation),
        ...     ),
        ...     coords=dict(
        ...         lon=(["x", "y"], [[260.17, 260.68], [260.21, 260.77]]),
        ...         lat=(["x", "y"], [[42.25, 42.21], [42.63, 42.59]]),
        ...         time=pd.date_range("2014-09-06", periods=4),
        ...         reference_time=pd.Timestamp("2014-09-05"),
        ...     ),
        ...     attrs=dict(description="Weather-related data"),
        ... )
        >>> ds
        <xarray.Dataset>
        Dimensions:         (x: 2, y: 2, time: 4)
        Coordinates:
            lon             (x, y) float64 260.2 260.7 260.2 260.8
            lat             (x, y) float64 42.25 42.21 42.63 42.59
          * time            (time) datetime64[ns] 2014-09-06 2014-09-07 ... 2014-09-09
            reference_time  datetime64[ns] 2014-09-05
        Dimensions without coordinates: x, y
        Data variables:
            temperature     (x, y, time) float64 20.0 20.8 21.6 22.4 ... 30.4 31.2 32.0
            precipitation   (x, y, time) float64 2.0 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 2.0
        Attributes:
            description:  Weather-related data
        >>> ds.assign_coords(lon=(((ds.lon + 180) % 360) - 180))
        <xarray.Dataset>
        Dimensions:         (x: 2, y: 2, time: 4)
        Coordinates:
            lon             (x, y) float64 -99.83 -99.32 -99.79 -99.23
            lat             (x, y) float64 42.25 42.21 42.63 42.59
          * time            (time) datetime64[ns] 2014-09-06 2014-09-07 ... 2014-09-09
            reference_time  datetime64[ns] 2014-09-05
        Dimensions without coordinates: x, y
        Data variables:
            temperature     (x, y, time) float64 20.0 20.8 21.6 22.4 ... 30.4 31.2 32.0
            precipitation   (x, y, time) float64 2.0 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 2.0
        Attributes:
            description:  Weather-related data

        Notes
        -----
        Since ``coords_kwargs`` is a dictionary, the order of your arguments
        may not be preserved, and so the order of the new variables is not well
        defined. Assigning multiple variables within the same ``assign_coords``
        is possible, but you cannot reference other variables created within
        the same ``assign_coords`` call.

        See Also
        --------
        Dataset.assign
        Dataset.swap_dims
        Dataset.set_coords
        assign_coordsFdeep)r   copyr   r   update)r:   r   r   Zcoords_combinedri   resultsr/   r/   r=   r     s     
zDataWithCoords.assign_coords)r:   argsr;   rN   c                 O  s   | j dd}|jj|| |S )a  Assign new attrs to this object.

        Returns a new object equivalent to ``self.attrs.update(*args, **kwargs)``.

        Parameters
        ----------
        *args
            positional arguments passed into ``attrs.update``.
        **kwargs
            keyword arguments passed into ``attrs.update``.

        Returns
        -------
        assigned : same type as caller
            A new object with the new attrs in addition to the existing data.

        See Also
        --------
        Dataset.assign
        Fr   )r   attrsr   )r:   r   r;   outr/   r/   r=   assign_attrsj  s    zDataWithCoords.assign_attrsz/Callable[..., T] | tuple[Callable[..., T], str]r-   )r2   r   r;   rN   c                 O  sN   t |tr:|\}}||kr(t| d| ||< |||S || f||S dS )a  
        Apply ``func(self, *args, **kwargs)``

        This method replicates the pandas method of the same name.

        Parameters
        ----------
        func : callable
            function to apply to this xarray object (Dataset/DataArray).
            ``args``, and ``kwargs`` are passed into ``func``.
            Alternatively a ``(callable, data_keyword)`` tuple where
            ``data_keyword`` is a string indicating the keyword of
            ``callable`` that expects the xarray object.
        *args
            positional arguments passed into ``func``.
        **kwargs
            a dictionary of keyword arguments passed into ``func``.

        Returns
        -------
        object : Any
            the return type of ``func``.

        Notes
        -----
        Use ``.pipe`` when chaining together functions that expect
        xarray or pandas objects, e.g., instead of writing

        .. code:: python

            f(g(h(ds), arg1=a), arg2=b, arg3=c)

        You can write

        .. code:: python

            (ds.pipe(h).pipe(g, arg1=a).pipe(f, arg2=b, arg3=c))

        If you have a function that takes the data as (say) the second
        argument, pass a tuple indicating which keyword expects the
        data. For example, suppose ``f`` takes its data as ``arg2``:

        .. code:: python

            (ds.pipe(h).pipe(g, arg1=a).pipe((f, "arg2"), arg1=a, arg3=c))

        Examples
        --------
        >>> x = xr.Dataset(
        ...     {
        ...         "temperature_c": (
        ...             ("lat", "lon"),
        ...             20 * np.random.rand(4).reshape(2, 2),
        ...         ),
        ...         "precipitation": (("lat", "lon"), np.random.rand(4).reshape(2, 2)),
        ...     },
        ...     coords={"lat": [10, 20], "lon": [150, 160]},
        ... )
        >>> x
        <xarray.Dataset>
        Dimensions:        (lat: 2, lon: 2)
        Coordinates:
          * lat            (lat) int64 10 20
          * lon            (lon) int64 150 160
        Data variables:
            temperature_c  (lat, lon) float64 10.98 14.3 12.06 10.9
            precipitation  (lat, lon) float64 0.4237 0.6459 0.4376 0.8918

        >>> def adder(data, arg):
        ...     return data + arg
        ...
        >>> def div(data, arg):
        ...     return data / arg
        ...
        >>> def sub_mult(data, sub_arg, mult_arg):
        ...     return (data * mult_arg) - sub_arg
        ...
        >>> x.pipe(adder, 2)
        <xarray.Dataset>
        Dimensions:        (lat: 2, lon: 2)
        Coordinates:
          * lat            (lat) int64 10 20
          * lon            (lon) int64 150 160
        Data variables:
            temperature_c  (lat, lon) float64 12.98 16.3 14.06 12.9
            precipitation  (lat, lon) float64 2.424 2.646 2.438 2.892

        >>> x.pipe(adder, arg=2)
        <xarray.Dataset>
        Dimensions:        (lat: 2, lon: 2)
        Coordinates:
          * lat            (lat) int64 10 20
          * lon            (lon) int64 150 160
        Data variables:
            temperature_c  (lat, lon) float64 12.98 16.3 14.06 12.9
            precipitation  (lat, lon) float64 2.424 2.646 2.438 2.892

        >>> (
        ...     x.pipe(adder, arg=2)
        ...     .pipe(div, arg=2)
        ...     .pipe(sub_mult, sub_arg=2, mult_arg=2)
        ... )
        <xarray.Dataset>
        Dimensions:        (lat: 2, lon: 2)
        Coordinates:
          * lat            (lat) int64 10 20
          * lon            (lon) int64 150 160
        Data variables:
            temperature_c  (lat, lon) float64 10.98 14.3 12.06 10.9
            precipitation  (lat, lon) float64 0.4237 0.6459 0.4376 0.8918

        See Also
        --------
        pandas.DataFrame.pipe
        z/ is both the pipe target and a keyword argumentN)ry   rz   r   )r:   r2   r   r;   targetr/   r/   r=   pipe  s    y

zDataWithCoords.pipespanzMapping[Any, int] | Noner^   zRollingExp[T_DataWithCoords])r:   windowwindow_typerN   c                 K  s8   ddl m} d|krtd t||d}|| ||S )a  
        Exponentially-weighted moving window.
        Similar to EWM in pandas

        Requires the optional Numbagg dependency.

        Parameters
        ----------
        window : mapping of hashable to int, optional
            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.
        window_type : {"span", "com", "halflife", "alpha"}, default: "span"
            The format of the previously supplied window. Each is a simple
            numerical transformation of the others. Described in detail:
            https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.ewm.html
        **window_kwargs : optional
            The keyword arguments form of ``window``.
            One of window or window_kwargs must be provided.

        See Also
        --------
        core.rolling_exp.RollingExp
        r   )rolling_expr   zPassing ``keep_attrs`` to ``rolling_exp`` has no effect. Pass ``keep_attrs`` directly to the applied function, e.g. ``rolling_exp(...).mean(keep_attrs=False)``.r   )xarray.corer   r   r   r   r"   )r:   r   r   Zwindow_kwargsr   r/   r/   r=   r   	  s    zDataWithCoords.rolling_expztype[T_Resample]zMapping[Any, str] | NonezSideOptions | Nonez
int | Nonez.pd.Timedelta | datetime.timedelta | str | Nonezstr | DatetimeLikezdatetime.timedelta | str | Noner*   )resample_clsindexerr7   closedlabelbaseoffsetoriginr   loffsetrestore_coord_dimsindexer_kwargsrN   c              
   K  sR  ddl m} ddlm} ddlm} |	dk	r6td |dk	rHt|t	rld|krZd| j
ksld|krtd| j
krttd	t||d
}t|dkrtdtt| \}}|}| | }t h tjddtd t| j|  |rddlm} ||||||
||d}ntj|||||||
d}W 5 Q R X |||j|j
|d}|| |||||dS )a  Returns a Resample object for performing resampling operations.

        Handles both downsampling and upsampling. The resampled
        dimension must be a datetime-like coordinate. If any intervals
        contain no values from the original object, they will be given
        the value ``NaN``.

        Parameters
        ----------
        indexer : {dim: freq}, optional
            Mapping from the dimension name to resample frequency [1]_. The
            dimension must be datetime-like.
        skipna : bool, optional
            Whether to skip missing values when aggregating in downsampling.
        closed : {"left", "right"}, optional
            Side of each interval to treat as closed.
        label : {"left", "right"}, optional
            Side of each interval to use for labeling.
        base : int, optional
            For frequencies that evenly subdivide 1 day, the "origin" of the
            aggregated intervals. For example, for "24H" frequency, base could
            range from 0 through 23.
        origin : {'epoch', 'start', 'start_day', 'end', 'end_day'}, pd.Timestamp, datetime.datetime, np.datetime64, or cftime.datetime, default 'start_day'
            The datetime on which to adjust the grouping. The timezone of origin
            must match the timezone of the index.

            If a datetime is not used, these values are also supported:
            - 'epoch': `origin` is 1970-01-01
            - 'start': `origin` is the first value of the timeseries
            - 'start_day': `origin` is the first day at midnight of the timeseries
            - 'end': `origin` is the last value of the timeseries
            - 'end_day': `origin` is the ceiling midnight of the last day
        offset : pd.Timedelta, datetime.timedelta, or str, default is None
            An offset timedelta added to the origin.
        loffset : timedelta or str, optional
            Offset used to adjust the resampled time labels. Some pandas date
            offset strings are supported.
        restore_coord_dims : bool, optional
            If True, also restore the dimension order of multi-dimensional
            coordinates.
        **indexer_kwargs : {dim: freq}
            The keyword arguments form of ``indexer``.
            One of indexer or indexer_kwargs must be provided.

        Returns
        -------
        resampled : same type as caller
            This object resampled.

        Examples
        --------
        Downsample monthly time-series data to seasonal data:

        >>> da = xr.DataArray(
        ...     np.linspace(0, 11, num=12),
        ...     coords=[
        ...         pd.date_range(
        ...             "1999-12-15",
        ...             periods=12,
        ...             freq=pd.DateOffset(months=1),
        ...         )
        ...     ],
        ...     dims="time",
        ... )
        >>> da
        <xarray.DataArray (time: 12)>
        array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10., 11.])
        Coordinates:
          * time     (time) datetime64[ns] 1999-12-15 2000-01-15 ... 2000-11-15
        >>> da.resample(time="QS-DEC").mean()
        <xarray.DataArray (time: 4)>
        array([ 1.,  4.,  7., 10.])
        Coordinates:
          * time     (time) datetime64[ns] 1999-12-01 2000-03-01 2000-06-01 2000-09-01

        Upsample monthly time-series data to daily data:

        >>> da.resample(time="1D").interpolate("linear")  # +doctest: ELLIPSIS
        <xarray.DataArray (time: 337)>
        array([ 0.        ,  0.03225806,  0.06451613,  0.09677419,  0.12903226,
                0.16129032,  0.19354839,  0.22580645,  0.25806452,  0.29032258,
                0.32258065,  0.35483871,  0.38709677,  0.41935484,  0.4516129 ,
        ...
               10.80645161, 10.83870968, 10.87096774, 10.90322581, 10.93548387,
               10.96774194, 11.        ])
        Coordinates:
          * time     (time) datetime64[ns] 1999-12-15 1999-12-16 ... 2000-11-15

        Limit scope of upsampling method

        >>> da.resample(time="1D").nearest(tolerance="1D")
        <xarray.DataArray (time: 337)>
        array([ 0.,  0., nan, ..., nan, 11., 11.])
        Coordinates:
          * time     (time) datetime64[ns] 1999-12-15 1999-12-16 ... 2000-11-15

        See Also
        --------
        pandas.Series.resample
        pandas.DataFrame.resample

        References
        ----------
        .. [1] https://pandas.pydata.org/docs/user_guide/timeseries.html#dateoffset-objects
        r   )CFTimeIndexr   )RESAMPLE_DIMNzPassing ``keep_attrs`` to ``resample`` has no effect and will raise an error in xarray 0.20. Pass ``keep_attrs`` directly to the applied function, e.g. ``resample(...).mean(keep_attrs=True)``.howr5   zresample() no longer supports the `how` or `dim` arguments. Instead call methods on resample objects, e.g., data.resample(time='1D').mean()Zresampler   z2Resampling only supported along single dimensions.ignorezC'(base|loffset)' in .resample\(\) and in Grouper\(\) is deprecated.)category)CFTimeGrouper)freqr   r   r   r   r   r   )r   r   r   r   r   r   r   )r   r}   r   )groupr5   grouperZresample_dimr   )Zxarray.coding.cftimeindexr   xarray.core.dataarrayr   xarray.core.resampler   r   r   ry   r0   r}   rq   r   rm   r   nextiterr   catch_warningsfilterwarningsr   r   r   Zxarray.core.resample_cftimer   r   ZGrouperr   )r:   r   r   r7   r   r   r   r   r   r   r   r   r   r   r   r   r5   r   Zdim_nameZ	dim_coordr   r   r   r/   r/   r=   	_resample3  s    z

	   zDataWithCoords._resample)r:   condotherr   rN   c                   s   ddl m} ddlm} ddlm} t r4 |  |rt ||fs`td d|d|||  \}  dd	d
 fdd}dd	d
 fdd}t |r|n|}	i }
 j	
 D ]}|	||
|< q| jf |
}  jf |
 t|  |S )al  Filter elements from this object according to a condition.

        This operation follows the normal broadcasting and alignment rules that
        xarray uses for binary arithmetic.

        Parameters
        ----------
        cond : DataArray, Dataset, or callable
            Locations at which to preserve this object's values. dtype must be `bool`.
            If a callable, it must expect this object as its only parameter.
        other : scalar, DataArray or Dataset, optional
            Value to use for locations in this object where ``cond`` is False.
            By default, these locations filled with NA.
        drop : bool, default: False
            If True, coordinate labels that only correspond to False values of
            the condition are dropped from the result.

        Returns
        -------
        DataArray or Dataset
            Same xarray type as caller, with dtype float64.

        Examples
        --------
        >>> a = xr.DataArray(np.arange(25).reshape(5, 5), dims=("x", "y"))
        >>> a
        <xarray.DataArray (x: 5, y: 5)>
        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, 24]])
        Dimensions without coordinates: x, y

        >>> a.where(a.x + a.y < 4)
        <xarray.DataArray (x: 5, y: 5)>
        array([[ 0.,  1.,  2.,  3., nan],
               [ 5.,  6.,  7., nan, nan],
               [10., 11., nan, nan, nan],
               [15., nan, nan, nan, nan],
               [nan, nan, nan, nan, nan]])
        Dimensions without coordinates: x, y

        >>> a.where(a.x + a.y < 5, -1)
        <xarray.DataArray (x: 5, y: 5)>
        array([[ 0,  1,  2,  3,  4],
               [ 5,  6,  7,  8, -1],
               [10, 11, 12, -1, -1],
               [15, 16, -1, -1, -1],
               [20, -1, -1, -1, -1]])
        Dimensions without coordinates: x, y

        >>> a.where(a.x + a.y < 4, drop=True)
        <xarray.DataArray (x: 4, y: 4)>
        array([[ 0.,  1.,  2.,  3.],
               [ 5.,  6.,  7., nan],
               [10., 11., nan, nan],
               [15., nan, nan, nan]])
        Dimensions without coordinates: x, y

        >>> a.where(lambda x: x.x + x.y < 4, drop=True)
        <xarray.DataArray (x: 4, y: 4)>
        array([[ 0.,  1.,  2.,  3.],
               [ 5.,  6.,  7., nan],
               [10., 11., nan, nan],
               [15., nan, nan, nan]])
        Dimensions without coordinates: x, y

        >>> a.where(a.x + a.y < 4, -1, drop=True)
        <xarray.DataArray (x: 4, y: 4)>
        array([[ 0,  1,  2,  3],
               [ 5,  6,  7, -1],
               [10, 11, -1, -1],
               [15, -1, -1, -1]])
        Dimensions without coordinates: x, y

        See Also
        --------
        numpy.where : corresponding numpy function
        where : equivalent function
        r   )alignr   r   zcond argument is z but must be a z or r	   r   rs   c                   s   j  fddjD dS )Nc                 3  s   | ]}| kr|V  qd S rO   r/   ru   r5   r/   r=   rx   Z  s      zCDataWithCoords.where.<locals>._dataarray_indexer.<locals>.<genexpr>r  )r   r}   r  r  r  r=   _dataarray_indexerY  s    z0DataWithCoords.where.<locals>._dataarray_indexerc                   sH     fddD }|j fddj D d}| dS )Nc                 3  s    | ]} | j kr|V  qd S rO   )r}   )rv   var)r  r5   r/   r=   rx   ]  s     zADataWithCoords.where.<locals>._dataset_indexer.<locals>.<genexpr>c                 3  s   | ]}| kr|V  qd S rO   r/   ru   r  r/   r=   rx   `  s      r  variable)Z	drop_varsr   r}   r   Zto_array)r5   Z	cond_wdimZkeepanyr  r  r=   _dataset_indexer\  s
     z.DataWithCoords.where.<locals>._dataset_indexer)Zxarray.core.alignmentr
  r  r   xarray.core.datasetr   r   ry   rq   r   r   r   r   Zwhere_method)r:   r  r	  r   r
  r   r   r  r  Z_get_indexerZindexersr5   r/   r  r=   where  s*    TzDataWithCoords.wherer   )closerN   c                 C  s
   || _ dS )a  Register the function that releases any resources linked to this object.

        This method controls how xarray cleans up resources associated
        with this object when the ``.close()`` method is called. It is mostly
        intended for backend developers and it is rarely needed by regular
        end-users.

        Parameters
        ----------
        close : callable
            The function that when called like ``close()`` releases
            any resources linked to this object.
        Nr   )r:   r  r/   r/   r=   	set_closep  s    zDataWithCoords.set_closer_   c                 C  s   | j dk	r|    d| _ dS )z,Release any resources linked to this object.Nr   rQ   r/   r/   r=   r    s    
zDataWithCoords.close)r:   r   rN   c                 C  s0   ddl m} |dkrtdd}|tj| d|dS )a  Test each value in the array for whether it is a missing value.

        Parameters
        ----------
        keep_attrs : bool or None, optional
            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.

        Returns
        -------
        isnull : DataArray or Dataset
            Same type and shape as object, but the dtype of the data is bool.

        See Also
        --------
        pandas.isnull

        Examples
        --------
        >>> array = xr.DataArray([1, np.nan, 3], dims="x")
        >>> array
        <xarray.DataArray (x: 3)>
        array([ 1., nan,  3.])
        Dimensions without coordinates: x
        >>> array.isnull()
        <xarray.DataArray (x: 3)>
        array([False,  True, False])
        Dimensions without coordinates: x
        r   r   NFr   r   r   r   )r   r   r   r   isnullr:   r   r   r/   r/   r=   r    s    !
zDataWithCoords.isnullc                 C  s0   ddl m} |dkrtdd}|tj| d|dS )a  Test each value in the array for whether it is not a missing value.

        Parameters
        ----------
        keep_attrs : bool or None, optional
            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.

        Returns
        -------
        notnull : DataArray or Dataset
            Same type and shape as object, but the dtype of the data is bool.

        See Also
        --------
        pandas.notnull

        Examples
        --------
        >>> array = xr.DataArray([1, np.nan, 3], dims="x")
        >>> array
        <xarray.DataArray (x: 3)>
        array([ 1., nan,  3.])
        Dimensions without coordinates: x
        >>> array.notnull()
        <xarray.DataArray (x: 3)>
        array([ True, False,  True])
        Dimensions without coordinates: x
        r   r   NFr   r   r  )r   r   r   r   notnullr  r/   r/   r=   r    s    !
zDataWithCoords.notnull)r:   test_elementsrN   c                 C  sv   ddl m} ddlm} ddlm} ddlm} t||rJt	d
|nt|||fr^|j}|tj| t|ddd	S )
a  Tests each value in the array for whether it is in test elements.

        Parameters
        ----------
        test_elements : array_like
            The values against which to test each value of `element`.
            This argument is flattened if an array or array_like.
            See numpy notes for behavior with non-array-like parameters.

        Returns
        -------
        isin : DataArray or Dataset
            Has the same type and shape as this object, but with a bool dtype.

        Examples
        --------
        >>> array = xr.DataArray([1, 2, 3], dims="x")
        >>> array.isin([1, 3])
        <xarray.DataArray (x: 3)>
        array([ True, False,  True])
        Dimensions without coordinates: x

        See Also
        --------
        numpy.isin
        r   r   r   r   r(   z3isin() argument must be convertible to an array: {})r  r   )r;   r   )r   r   r  r   r  r   xarray.core.variabler)   ry   rq   r   ri   r   isinr   )r:   r  r   r   r   r)   r/   r/   r=   r    s$    
zDataWithCoords.isinT)ordercastingsubokr   r   rM   c          	      C  sD   ddl m} t||||d}dd | D }|tj| |||ddS )u
	  
        Copy of the xarray object, with data cast to a specified type.
        Leaves coordinate dtype unchanged.

        Parameters
        ----------
        dtype : str or dtype
            Typecode or data-type to which the array is cast.
        order : {'C', 'F', 'A', 'K'}, optional
            Controls the memory layout order of the result. ‘C’ means C order,
            ‘F’ means Fortran order, ‘A’ means ‘F’ order if all the arrays are
            Fortran contiguous, ‘C’ order otherwise, and ‘K’ means as close to
            the order the array elements appear in memory as possible.
        casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
            Controls what kind of data casting may occur.

            * 'no' means the data types should not be cast at all.
            * 'equiv' means only byte-order changes are allowed.
            * 'safe' means only casts which can preserve values are allowed.
            * 'same_kind' means only safe casts or casts within a kind,
              like float64 to float32, are allowed.
            * 'unsafe' means any data conversions may be done.
        subok : bool, optional
            If True, then sub-classes will be passed-through, otherwise the
            returned array will be forced to be a base-class array.
        copy : bool, optional
            By default, astype always returns a newly allocated array. If this
            is set to False and the `dtype` requirement is satisfied, the input
            array is returned instead of a copy.
        keep_attrs : bool, optional
            By default, astype keeps attributes. Set to False to remove
            attributes in the returned object.

        Returns
        -------
        out : same as object
            New object with data cast to the specified type.

        Notes
        -----
        The ``order``, ``casting``, ``subok`` and ``copy`` arguments are only passed
        through to the ``astype`` method of the underlying array when a value
        different than ``None`` is supplied.
        Make sure to only supply these arguments if the underlying array class
        supports them.

        See Also
        --------
        numpy.ndarray.astype
        dask.array.Array.astype
        sparse.COO.astype
        r   r   )r  r  r  r   c                 S  s   i | ]\}}|d k	r||qS rO   r/   r   r/   r/   r=   r   S  s       z)DataWithCoords.astype.<locals>.<dictcomp>r   )r;   r   r   )r   r   r   r   r   astype)	r:   rY   r  r  r  r   r   r   r;   r/   r/   r=   r    s    >zDataWithCoords.astypec                 C  s   | S rO   r/   rQ   r/   r/   r=   	__enter__^  s    zDataWithCoords.__enter__c                 C  s   |    d S rO   )r  )r:   exc_type	exc_value	tracebackr/   r/   r=   __exit__a  s    zDataWithCoords.__exit__c                 C  s
   t  d S rO   )rk   )r:   r   r/   r/   r=   __getitem__d  s    zDataWithCoords.__getitem__)NFN)NN)N)Nr   )N)N)rB   rC   rD   r   __annotations__rE   r   r   r   r   r   r   r   r   r  r   NAr  r  r  r  r  r  r  r   r$  r%  r/   r/   r/   r=   r   z  sZ   
   #  +
     *& E z . -6Lr   r   r   r$   )r	  
fill_valuerY   rN   c                 C  s   d S rO   r/   r	  r(  rY   r/   r/   r=   	full_likei  s    r*  r   DTypeMaybeMappingc                 C  s   d S rO   r/   r)  r/   r/   r=   r*  p  s    r)   c                 C  s   d S rO   r/   r)  r/   r/   r=   r*  w  s    zDataset | DataArrayc                 C  s   d S rO   r/   r)  r/   r/   r=   r*  ~  s    zDataset | DataArray | Variablec                 C  s   d S rO   r/   r)  r/   r/   r=   r*    s    c                   sJ  ddl m} ddlm} ddlm} tsPt| |r@ttsPt	d dt| |rtts|fdd| j
 D t ts fd	d| j
 D n fd
d| j
 D }||| j| jdS t| |rt trt	d|t| j | j| j| j| jdS t| |r>t tr2t	dt|  S tddS )a  Return a new object with the same shape and type as a given object.

    Parameters
    ----------
    other : DataArray, Dataset or Variable
        The reference object in input
    fill_value : scalar or dict-like
        Value to fill the new object with before returning it. If
        other is a Dataset, may also be a dict-like mapping data
        variables to fill values.
    dtype : dtype or dict-like of dtype, optional
        dtype of the new array. If a dict-like, maps dtypes to
        variables. If omitted, it defaults to other.dtype.

    Returns
    -------
    out : same as object
        New object with the same shape and type as other, with the data
        filled with fill_value. Coords will be copied from other.
        If other is based on dask, the new one will be as well, and will be
        split in the same chunks.

    Examples
    --------
    >>> x = xr.DataArray(
    ...     np.arange(6).reshape(2, 3),
    ...     dims=["lat", "lon"],
    ...     coords={"lat": [1, 2], "lon": [0, 1, 2]},
    ... )
    >>> x
    <xarray.DataArray (lat: 2, lon: 3)>
    array([[0, 1, 2],
           [3, 4, 5]])
    Coordinates:
      * lat      (lat) int64 1 2
      * lon      (lon) int64 0 1 2

    >>> xr.full_like(x, 1)
    <xarray.DataArray (lat: 2, lon: 3)>
    array([[1, 1, 1],
           [1, 1, 1]])
    Coordinates:
      * lat      (lat) int64 1 2
      * lon      (lon) int64 0 1 2

    >>> xr.full_like(x, 0.5)
    <xarray.DataArray (lat: 2, lon: 3)>
    array([[0, 0, 0],
           [0, 0, 0]])
    Coordinates:
      * lat      (lat) int64 1 2
      * lon      (lon) int64 0 1 2

    >>> xr.full_like(x, 0.5, dtype=np.double)
    <xarray.DataArray (lat: 2, lon: 3)>
    array([[0.5, 0.5, 0.5],
           [0.5, 0.5, 0.5]])
    Coordinates:
      * lat      (lat) int64 1 2
      * lon      (lon) int64 0 1 2

    >>> xr.full_like(x, np.nan, dtype=np.double)
    <xarray.DataArray (lat: 2, lon: 3)>
    array([[nan, nan, nan],
           [nan, nan, nan]])
    Coordinates:
      * lat      (lat) int64 1 2
      * lon      (lon) int64 0 1 2

    >>> ds = xr.Dataset(
    ...     {"a": ("x", [3, 5, 2]), "b": ("x", [9, 1, 0])}, coords={"x": [2, 4, 6]}
    ... )
    >>> ds
    <xarray.Dataset>
    Dimensions:  (x: 3)
    Coordinates:
      * x        (x) int64 2 4 6
    Data variables:
        a        (x) int64 3 5 2
        b        (x) int64 9 1 0
    >>> xr.full_like(ds, fill_value={"a": 1, "b": 2})
    <xarray.Dataset>
    Dimensions:  (x: 3)
    Coordinates:
      * x        (x) int64 2 4 6
    Data variables:
        a        (x) int64 1 1 1
        b        (x) int64 2 2 2
    >>> xr.full_like(ds, fill_value={"a": 1, "b": 2}, dtype={"a": bool, "b": float})
    <xarray.Dataset>
    Dimensions:  (x: 3)
    Coordinates:
      * x        (x) int64 2 4 6
    Data variables:
        a        (x) bool True True True
        b        (x) float64 2.0 2.0 2.0

    See Also
    --------
    zeros_like
    ones_like

    r   r   r   r(   zBfill_value must be scalar or, for datasets, a dict-like. Received z	 instead.c                   s   i | ]
}| qS r/   r/   r   )r(  r/   r=   r     s      zfull_like.<locals>.<dictcomp>c                   s   i | ]
}| qS r/   r/   r   rZ   r/   r=   r     s      c              
     s2   i | ]*\}}|t |j|tj |d qS rO   )_full_like_variabler  getr   r'  r   )dtype_r(  r/   r=   r     s      
)r   r   z4'dtype' cannot be dict-like when passing a DataArray)r}   r   r   r   z3'dtype' cannot be dict-like when passing a Variablez(Expected DataArray, Dataset, or VariableN)r  r   r  r   r  r)   r   ry   r   r   	data_varsr   r   r   r   r   r,  r  r}   r   rq   )r	  r(  rY   r   r   r)   r/  r/   )rY   r.  r(  r=   r*    sH    l




r   c                 C  s   ddl m} |tjkr.t|dk	r&|n| j}t| jrjddl}|dkrN| j}|j	j
| j||| jjd}ntj| j||d}|| j|| jdS )z;Inner function of full_like, where other must be a variabler   r(   N)rY   chunksrZ   )r}   ri   r   )r  r)   r   r'  Zget_fill_valuerY   r   ri   Z
dask.arrayarrayfullrh   r0  r[   r*  r}   r   )r	  r(  rY   r)   r   ri   r/   r/   r=   r,  (  s    

   r,  )r	  rY   rN   c                 C  s   d S rO   r/   r	  rY   r/   r/   r=   
zeros_like?  s    r4  c                 C  s   d S rO   r/   r3  r/   r/   r=   r4  D  s    c                 C  s   d S rO   r/   r3  r/   r/   r=   r4  I  s    c                 C  s   d S rO   r/   r3  r/   r/   r=   r4  N  s    c                 C  s   d S rO   r/   r3  r/   r/   r=   r4  U  s    c                 C  s   t | d|S )aB  Return a new object of zeros with the same shape and
    type as a given dataarray or dataset.

    Parameters
    ----------
    other : DataArray, Dataset or Variable
        The reference object. The output will have the same dimensions and coordinates as this object.
    dtype : dtype, optional
        dtype of the new array. If omitted, it defaults to other.dtype.

    Returns
    -------
    out : DataArray, Dataset or Variable
        New object of zeros with the same shape and type as other.

    Examples
    --------
    >>> x = xr.DataArray(
    ...     np.arange(6).reshape(2, 3),
    ...     dims=["lat", "lon"],
    ...     coords={"lat": [1, 2], "lon": [0, 1, 2]},
    ... )
    >>> x
    <xarray.DataArray (lat: 2, lon: 3)>
    array([[0, 1, 2],
           [3, 4, 5]])
    Coordinates:
      * lat      (lat) int64 1 2
      * lon      (lon) int64 0 1 2

    >>> xr.zeros_like(x)
    <xarray.DataArray (lat: 2, lon: 3)>
    array([[0, 0, 0],
           [0, 0, 0]])
    Coordinates:
      * lat      (lat) int64 1 2
      * lon      (lon) int64 0 1 2

    >>> xr.zeros_like(x, dtype=float)
    <xarray.DataArray (lat: 2, lon: 3)>
    array([[0., 0., 0.],
           [0., 0., 0.]])
    Coordinates:
      * lat      (lat) int64 1 2
      * lon      (lon) int64 0 1 2

    See Also
    --------
    ones_like
    full_like

    r   r*  r3  r/   r/   r=   r4  \  s    7c                 C  s   d S rO   r/   r3  r/   r/   r=   	ones_like  s    r6  c                 C  s   d S rO   r/   r3  r/   r/   r=   r6    s    c                 C  s   d S rO   r/   r3  r/   r/   r=   r6    s    c                 C  s   d S rO   r/   r3  r/   r/   r=   r6    s    c                 C  s   d S rO   r/   r3  r/   r/   r=   r6    s    c                 C  s   t | d|S )aZ  Return a new object of ones with the same shape and
    type as a given dataarray or dataset.

    Parameters
    ----------
    other : DataArray, Dataset, or Variable
        The reference object. The output will have the same dimensions and coordinates as this object.
    dtype : dtype, optional
        dtype of the new array. If omitted, it defaults to other.dtype.

    Returns
    -------
    out : same as object
        New object of ones with the same shape and type as other.

    Examples
    --------
    >>> x = xr.DataArray(
    ...     np.arange(6).reshape(2, 3),
    ...     dims=["lat", "lon"],
    ...     coords={"lat": [1, 2], "lon": [0, 1, 2]},
    ... )
    >>> x
    <xarray.DataArray (lat: 2, lon: 3)>
    array([[0, 1, 2],
           [3, 4, 5]])
    Coordinates:
      * lat      (lat) int64 1 2
      * lon      (lon) int64 0 1 2

    >>> xr.ones_like(x)
    <xarray.DataArray (lat: 2, lon: 3)>
    array([[1, 1, 1],
           [1, 1, 1]])
    Coordinates:
      * lat      (lat) int64 1 2
      * lon      (lon) int64 0 1 2

    See Also
    --------
    zeros_like
    full_like

    r   r5  r3  r/   r/   r=   r6    s    /zIterable[Variable]zMapping[Any, tuple[int, ...]])	variablesrN   c                 C  sb   i }| D ]P}t |jdr|j D ]4\}}||krN||| krNtd| d|||< q"qt|S )Nr0  z/Object has inconsistent chunks along dimension z.. This can be fixed by calling unify_chunks().)r   _dataZ
chunksizesr   r   r   )r7  r0  r   r5   cr/   r/   r=   get_chunksizes  s    
r:  r0   )rY   rN   c                 C  s   t | t jpt | t jS )z:Check if a dtype is a subclass of the numpy datetime types)r[   
issubdtypeZ
datetime64timedelta64rZ   r/   r/   r=   is_np_datetime_like  s    r=  c                 C  s   t | t jS )z0Check whether dtype is of the timedelta64 dtype.)r[   r;  r<  rZ   r/   r/   r=   is_np_timedelta_like  s    r>  r_   c                 C  sn   t dkrdS | jtdkrf| jdkrft| jd }t|rZ| }t|tj	rZ|
 }t|t jS dS dS )z2Check if an array contains cftime.datetime objectsNFOr   )cftimerY   r[   sizer\   Zflatr   Zcomputery   Zndarrayr   datetime)r1  sampler/   r/   r=   _contains_cftime_datetimes   s    rD  c                 C  s,   | j t dkr$| jdkr$t| jS dS dS )z<Check if an xarray.Variable contains cftime.datetime objectsr?  r   FN)rY   r[   rA  rD  ri   r  r/   r/   r=   contains_cftime_datetimes  s    
rF  c                 C  s   t | jpt| S )zvCheck if a variable contains datetime like objects (either
    np.datetime64, np.timedelta64, or cftime.datetime)
    )r=  rY   rF  rE  r/   r/   r=   _contains_datetime_like_objects  s    rG  )NN)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)N)S
__future__r   r   
contextlibr   htmlr   textwrapr   typingr   r   r   r	   r
   r   r   r   r   r   Znumpyr[   Zpandasr   r   r   r   r   r   r   Zxarray.core.optionsr   r   Zxarray.core.pycompatr   Zxarray.core.utilsr   r   r   r@  ImportErrorZALL_DIMSrB  Znumpy.typingr   r  r   r  r   Zxarray.core.indexesr    r  r!   Zxarray.core.rolling_expr"   Zxarray.core.typesr#   r$   r%   r&   r'   r  r)   r+  r*   r,   r-   r.   rI   rL   r   r   r   r*  r,  r4  r6  r:  r=  r>  rD  rF  rG  r/   r/   r/   r=   <module>   s   0
',[m  !       v           :   2