U
    Cvf+                    @  s\  d dl mZ d dlZd dl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mZ d dlZd dlZd dlmZmZ d dlmZ d dlmZmZmZmZm Z m!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+ d dl,m-Z- d dl.m/Z/m0Z0m1Z1 d dl2m3Z3 d dl4m5Z5m6Z6 d dl7m8Z8 d dl9m:Z: d dl;m<Z<m=Z=m>Z>m?Z?m@Z@ d dlAmBZBmCZC d dlDmEZEmFZFmGZG d dlHmIZImJZJ d dlKmLZLmMZMmNZNmOZOmPZP d dlQmRZRmSZSmTZTmUZU d dlVmWZW d dlXmYZY erd dlmZZZm[Z[ d dl\m]Z] zd dl^m_Z_ W n e`k
r   dZ_Y nX zd dlamSZb W n e`k
rH   dZbY nX zd dlcmdZe W n e`k
rt   dZeY nX d dlfmgZgmhZh d d limjZj d d!lkmlZl d d"lmmnZnmoZo d d#lpmqZqmrZrmsZsmtZtmuZumvZvmwZwmxZxmyZymzZzm{Z{m|Z|m}Z}m~Z~mZmZ d d$lmZ eZd%e[d&e8f d'Zd(d)d*d+Zd,d- ZG d.d/ d/ZeNd0ZG d1d& d&e/e0e-e#ZdS )2    )annotationsN)PathLike)TYPE_CHECKINGAnyCallableHashableIterableLiteralMappingNoReturnSequencecastoverload)convert_calendarinterp_calendar)CFTimeIndex)	alignmentcomputationdtypesindexingopsutils)DataArrayAggregations)CombinedDatetimelikeAccessor)StringAccessor)_broadcast_helper%_get_broadcast_dims_map_common_coordsalign)DataArrayArithmetic)AbstractArrayDataWithCoordsget_chunksizesunify_chunks)DataArrayCoordinatesassert_coordinate_consistent)Dataset)format_item)IndexIndexesPandasMultiIndexfilter_indexes_from_coordsisel_indexes)is_fancy_indexermap_index_queries)PANDAS_TYPES
MergeError_create_indexes_from_coords)OPTIONS_get_keep_attrs)DefaultHybridMappingProxy
ReprObject_defaulteither_dict_or_kwargs)IndexVariableVariableas_compatible_dataas_variable)DataArrayPlotAccessor)_get_units_from_attrs)TypeVarUnion)	ArrayLike)Delayed)r:   )Cube)T_NetcdfEngineT_NetcdfTypesDataArrayGroupByDataArrayResample)DataArrayCoarsenDataArrayRolling)CoarsenBoundaryOptionsDatetimeLikeDatetimeUnitOptionsDimsErrorOptionsErrorOptionsWithWarnInterpOptionsPadModeOptionsPadReflectOptionsQuantileMethodsQueryEngineOptionsQueryParserOptionsReindexMethodOptionsSideOptionsT_DataArrayT_XarrayDataArrayWeightedT_XarrayOther	DataArray)boundz5tuple[dict[Hashable, Variable], tuple[Hashable, ...]]returnc                   s  |dk	r@t |s@t|t| kr@tdt| dt|  dt trP f  dkrdd tt| D  |dk	rt|t| krt |rt|  n:t	t
 |D ]*\}\}}t| | d }|j |< qt  nXt t| krtdt|  d	t  n( D ]"}t|tstd
| dqi }t |rp| D ]\}}	t|	|d||< qRn@|dk	rt
 |D ]*\}}t||d}
|f|
_|
 ||< qtt
 | }| D ]\}}	t fdd|	jD rtd| d|	j d  t
|	j|	jD ]<\}}||| krtd|d||  d| d|q||kr|	j|| fkrtd|d|	jd|| dq| fS )z*All the logic for creating a new DataArrayNz$coords is not dict-like, but it has z! items, which does not match the z dimensions of the datac                 S  s   g | ]}d | qS )Zdim_ ).0nrc   rc   9/tmp/pip-unpacked-wheel-h316xyqg/xarray/core/dataarray.py
<listcomp>   s     z*_infer_coords_and_dims.<locals>.<listcomp>namez1different number of dimensions on data and dims: z vs z
dimension z is not a stringc                 3  s   | ]}| kV  qd S Nrc   rd   ddimsrc   rf   	<genexpr>   s     z)_infer_coords_and_dims.<locals>.<genexpr>zcoordinate z has dimensions z9, but these are not a subset of the DataArray dimensions z conflicting sizes for dimension z	: length z on the data but length z on coordinate z, is a DataArray dimension, but it has shape z rather than expected shape z matching the dimension size)r   is_dict_likelen
ValueError
isinstancestrrangelistkeys	enumeratezipr<   Zto_index_variableri   tuple	TypeErroritemsrn   dictanyshape)r   coordsrn   re   dimcoordrl   
new_coordskvvarZsizessrc   rm   rf   _infer_coords_and_dimso   sh    



r   c                   sv   | t jkrtj}  d k	rrtj| ddrrt rT|d kr<| S t fdd|D }ntdd  D }t|| } | S )NF)Z
include_0dc                 3  s.   | ]&}|   kr"t | |jnd V  qdS )   N)rw   r<   sizerd   r   r   rc   rf   ro      s   z$_check_data_shape.<locals>.<genexpr>c                 s  s   | ]}t |d jV  qdS )ZfooN)r<   r   )rd   r   rc   rc   rf   ro      s     )	r   NAnpnanr   Z	is_scalarrp   rz   full)datar   rn   Z
data_shaperc   r   rf   _check_data_shape   s    


r   c                   @  s:   e Zd ZdZddddZddddZddd	d
ZdS )_LocIndexer
data_arrayr_   c                 C  s
   || _ d S rj   r   )selfr   rc   rc   rf   __init__   s    z_LocIndexer.__init__ra   c                 C  s8   t |s,t|| jj}tt| jj|}| j	|S rj   )
r   rp   r   expanded_indexerr   ndimr}   ry   rn   sel)r   keylabelsrc   rc   rf   __getitem__   s    
z_LocIndexer.__getitem__Nonec                 C  sH   t |s,t|| jj}tt| jj|}t	| j|j
}|| j|< d S rj   )r   rp   r   r   r   r   r}   ry   rn   r.   dim_indexers)r   r   valuer   r   rc   rc   rf   __setitem__   s
    
z_LocIndexer.__setitem__N)__name__
__module____qualname__	__slots__r   r   r   rc   rc   rc   rf   r      s   r   z<this-array>c                   @  s  e Zd ZU dZded< ded< ded< ded	< d
ed< ded< dZeed  Z	e
jddddddfdddd
dddddddZeddddddddd Zddedfdd!d"dd#d$d%Zefddd"dd#d&d'ZdKdd(d)d*d+dd,d-d.Zd/d0d1d2Zefdd/d"dd3d4d5Zdd/d6d7d8ZdLddd/d:d;d<ZdMddd=dddd/d>d?d@Zed
d0dAdBZejd
ddCdDdBZedd0dEdFZedGd0dHdIZedJd0dKdLZedMd0dNdOZedMd0dPdQZedMd0dRdSZ dMd0dTdUZ!edd0dVdWZ"e"jdddCdXdWZ"edYd0dZd[Z#e#jdddCd\d[Z#dYd0d]d^Z$ddd_d`daZ%edd0dbdcZ&ddd0dedfZ'ddd0dgdhZ(edid0djdkZ)e)jddldCdmdkZ)ddndodpdqZ*ddddrdsdtZ+ddddrdudvZ,ddddwdxdyZ-dddodzd{Z.ed|d0d}d~Z/ed|d0ddZ0dddoddZ1edd0ddZ2edd0ddZ3e3jdddCddZ3edd0ddZ4e4jdddCddZ4edd0ddZ5edd0ddZ6edd0ddZ7e8dNdddd/dddZ9e8dOdddddddZ9dPdddddddZ9dd Z:dd Z;dd Z<dd Z=edd Z>edd Z?dd Z@dd ZAeBd d0ddZCddd_ddZDddd_ddZEddd_ddZFdQdddddddZGdRddddddddZHddd_ddZIdSddddddZJdZKedd0ddńZLedd0ddȄZMi ddddfddddddddd͜ddτZNdTdd+dddddҜddԄZOdUdd+ddddd՜ddׄZPdVdddddٜddۄZQdWdddddٜdd݄ZRdXdddddٜdd߄ZSdYdddddddZTdddddddddd	ddZUddd9e
jfdddddddddZVdddd9e
jfdd+ddddddddZWdZdd+ddddddddZXd[dddddddddZYd\ddd dd dZZd]ddddddZ[d^dddd dd	d
Z\d_dddd dddZ]d`ddd dddZ^dadddddddZ_dbdddddddZ`dd9eafddddd dd!d"d#Zbde
jdfdddd d$d%d&Zcdcdd(d/d)d*d+Zdd9dАd,dddddd-d.d/Zeeddd_d0d1ZfdАd2d3d4d d5d6d7ZgdАd2dd3d4dd8d9d:ZhdddАd2dd+d
d4dd;d<d=ZidedАd2dd+d4dd>d?d@Zjdfdd+ddAdBdCZkdgdddEdFddGdHdIZlddddJdKdLZmdhdd
ddFdMdNddddO	dPdQZndidddFddRdSdTZodjdddFddRdUdVZpddddWdXdYZqdkddddZdd[dd\ddddd]d^d_Zrd`d0dadbZsdld
dcdddedfdgZtdhd0didjZudmddkdldmdnZve8dnddpdqd̐drdsddddtdu
dvdwZwe8dodxdpdqd̐drdsdddddu
dydwZwe8dpddzdxdpdqd̐drdsdddd{du
d|dwZwdqd}dpdqd̐drdsdddd~du
ddwZwdrddddddZxeddddddZyedsdhdd dddZzdd0ddZ{edd dddZ|dd0ddZ}edd dddZ~dddddddZddddWddZddddWddZddddWddZdtdd
dddZduddd_ddZddddddZddddWddZddddddZdvddddddddZdddddddZdddddZeeZdwdMdːdddZdxdddMdddddZde
jfddddMddddÄZdyddddMddŜdƐdǄZeddd_dȐdɄZeddd_dʐd˄Zdzddddd̜d͐d΄Zd{ddd dМdѐd҄Zd|ddddԐddddd֜dאd؄Zd}ddddddٜdڐdۄZd~dddܐdddޜdߐdZdddd dddZdddd dddZd d0ddZdddddddddZdddMdddddd/dddZdddddddddddd
ddZdde
jdfd
dddd dd dZdde
jdfddddd dddZdddFddddddZdddFdddddd	Zdd+ddddd dddZddd[ddddddd/d	ddZddd3dddddZdddd̐ddd dddZdd dd d!d"d#Zdd$ddd%d&d'd(Zdd$ddd*dMdddd%d+	d,d-Zd d.d/d0d1ZdddFd2dMd3d4d5d6Zddd:d;d<dMd=d>d?d@ZddBddCdCdFdDdEddFddːdGdHdIdJZeed  ZdS (  r_   a  N-dimensional array with labeled coordinates and dimensions.

    DataArray provides a wrapper around numpy ndarrays that uses
    labeled dimensions and coordinates to support metadata aware
    operations. The API is similar to that for the pandas Series or
    DataFrame, but DataArray objects can have any number of dimensions,
    and their contents have fixed data types.

    Additional features over raw numpy arrays:

    - Apply operations over dimensions by name: ``x.sum('time')``.
    - Select or assign values by integer location (like numpy):
      ``x[:10]`` or by label (like pandas): ``x.loc['2014-01-01']`` or
      ``x.sel(time='2014-01-01')``.
    - Mathematical operations (e.g., ``x - y``) vectorize across
      multiple dimensions (known in numpy as "broadcasting") based on
      dimension names, regardless of their original order.
    - Keep track of arbitrary metadata in the form of a Python
      dictionary: ``x.attrs``
    - Convert to a pandas Series: ``x.to_series()``.

    Getting items from or doing mathematical operations with a
    DataArray always returns another DataArray.

    Parameters
    ----------
    data : array_like
        Values for this array. Must be an ``numpy.ndarray``, ndarray
        like, or castable to an ``ndarray``. If a self-described xarray
        or pandas object, attempts are made to use this array's
        metadata to fill in other unspecified arguments. A view of the
        array's data is used instead of a copy if possible.
    coords : sequence or dict of array_like, optional
        Coordinates (tick labels) to use for indexing along each
        dimension. The following notations are accepted:

        - mapping {dimension name: array-like}
        - sequence of tuples that are valid arguments for
          ``xarray.Variable()``
          - (dims, data)
          - (dims, data, attrs)
          - (dims, data, attrs, encoding)

        Additionally, it is possible to define a coord whose name
        does not match the dimension name, or a coord based on multiple
        dimensions, with one of the following notations:

        - mapping {coord name: DataArray}
        - mapping {coord name: Variable}
        - mapping {coord name: (dimension name, array-like)}
        - mapping {coord name: (tuple of dimension names, array-like)}

    dims : Hashable or sequence of Hashable, optional
        Name(s) of the data dimension(s). Must be either a Hashable
        (only for 1D data) or a sequence of Hashables with length equal
        to the number of dimensions. If this argument is omitted,
        dimension names are taken from ``coords`` (if possible) and
        otherwise default to ``['dim_0', ... 'dim_n']``.
    name : str or None, optional
        Name of this array.
    attrs : dict_like or None, optional
        Attributes to assign to the new instance. By default, an empty
        attribute dictionary is initialized.

    Examples
    --------
    Create data:

    >>> np.random.seed(0)
    >>> temperature = 15 + 8 * np.random.randn(2, 2, 3)
    >>> lon = [[-99.83, -99.32], [-99.79, -99.23]]
    >>> lat = [[42.25, 42.21], [42.63, 42.59]]
    >>> time = pd.date_range("2014-09-06", periods=3)
    >>> reference_time = pd.Timestamp("2014-09-05")

    Initialize a dataarray with multiple dimensions:

    >>> da = xr.DataArray(
    ...     data=temperature,
    ...     dims=["x", "y", "time"],
    ...     coords=dict(
    ...         lon=(["x", "y"], lon),
    ...         lat=(["x", "y"], lat),
    ...         time=time,
    ...         reference_time=reference_time,
    ...     ),
    ...     attrs=dict(
    ...         description="Ambient temperature.",
    ...         units="degC",
    ...     ),
    ... )
    >>> da
    <xarray.DataArray (x: 2, y: 2, time: 3)>
    array([[[29.11241877, 18.20125767, 22.82990387],
            [32.92714559, 29.94046392,  7.18177696]],
    <BLANKLINE>
           [[22.60070734, 13.78914233, 14.17424919],
            [18.28478802, 16.15234857, 26.63418806]]])
    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-08
        reference_time  datetime64[ns] 2014-09-05
    Dimensions without coordinates: x, y
    Attributes:
        description:  Ambient temperature.
        units:        degC

    Find out where the coldest temperature was:

    >>> da.isel(da.argmin(...))
    <xarray.DataArray ()>
    array(7.18177696)
    Coordinates:
        lon             float64 -99.32
        lat             float64 42.21
        time            datetime64[ns] 2014-09-08
        reference_time  datetime64[ns] 2014-09-05
    Attributes:
        description:  Ambient temperature.
        units:        degC
    zdict[str, Any]_cachezdict[Any, Variable]_coordszCallable[[], None] | None_closezdict[Hashable, Index]_indexeszHashable | None_namer:   	_variable)r   r   r   r   r   r   __weakref__NFr   zISequence[Sequence[Any] | pd.Index | DataArray] | Mapping[Any, Any] | Nonez$Hashable | Sequence[Hashable] | NonezMapping | Nonezdict[Hashable, Index] | Noneboolr   )r   r   rn   ri   attrsindexesfastpathrb   c           	      C  sb  |r0|}|d kst |d ks t |d k	s,t n |d k	r@td|d krt|trZ|j}nFt|tjrp|jg}n0t|tjr|j|j	g}nt|tj
tfr|g}|d krt|dt|dd }|d krt|dd }|d krt|tst|dd }t|||}t|}t|j||\}}t|||dd}t|\}}|| _t|tsFt || _|| _|| _d | _d S )Nz/Providing explicit indexes is not supported yetrn   ri   r   T)r   )AssertionErrorrr   rs   r_   r   pdSeriesindex	DataFramecolumnsr(   r9   getattrr/   r   r;   r   r   r:   r1   r   r}   r   r   r   r   )	r   r   r   rn   ri   r   r   r   variablerc   rc   rf   r     sB    

zDataArray.__init__ztype[T_DataArray]r   rZ   )clsr   r   ri   r   rb   c                 C  s,   t | }||_||_||_||_d|_|S )zaShortcut around __init__ for internal use when we want to skip
        costly validation
        N)object__new__r   r   r   r   r   )r   r   r   ri   r   objrc   rc   rf   _construct_direct  s    
zDataArray._construct_directzVariable | NonezHashable | None | Default)r   r   ri   rb   c                 C  sN   |d kr| j }|d kr| j}|d kr*| j}|tkr8| j}t| ||||ddS NT)ri   r   r   )r   r   r   r7   ri   type)r   r   r   ri   r   rc   rc   rf   _replace  s    zDataArray._replacec                   s   |j | j kr*|j| jkr*| j }| j}nz|j | j krrtt| j |jfdd| j D }t| jt	|}n2t	|j   fdd| j D }t| jt	|}| j
||||dS )Nc                   s4   i | ],\}}|j t fd d|jD kr||qS )c                 3  s   | ]} | V  qd S rj   rc   rk   	new_sizesrc   rf   ro     s     z@DataArray._replace_maybe_drop_dims.<locals>.<dictcomp>.<genexpr>)r   rz   rn   rd   r   r   r   rc   rf   
<dictcomp>  s    z6DataArray._replace_maybe_drop_dims.<locals>.<dictcomp>c                   s$   i | ]\}}t |j kr||qS rc   )setrn   r   )allowed_dimsrc   rf   r     s      r   )rn   r   r   copyr   r}   ry   r|   r+   r   r   )r   r   ri   r   r   rc   )r   r   rf   _replace_maybe_drop_dims  s    



z"DataArray._replace_maybe_drop_dimszMapping[Any, Index]zMapping[Any, Variable] | Nonezlist[Hashable] | NonezMapping[Any, Any] | None)r   r   r   drop_coordsrename_dimsrb   c           	        s   |s| S |dkri }|dkr g }| j  }| j }t| j}|D ]}|| ||< || ||< qB|D ]}|| || qd rt fdd|jD |_| j|||dS )z:Maybe replace indexes and their corresponding coordinates.Nc                 3  s   | ]}  ||V  qd S rj   getrk   r   rc   rf   ro     s     z/DataArray._overwrite_indexes.<locals>.<genexpr>r   r   r   )	r   r   r   r}   r   poprz   rn   r   )	r   r   r   r   r   Znew_variabler   Znew_indexesri   rc   r   rf   _overwrite_indexes  s,    



  zDataArray._overwrite_indexesr&   ra   c                 C  s   | j tddS )NF)ri   shallow_copy)_to_dataset_whole_THIS_ARRAYr   rc   rc   rf   _to_temp_dataset  s    zDataArray._to_temp_dataset)r   datasetri   rb   c                 C  s*   |j t}|j }|j}| j||||dS )Nr   )
_variablesr   r   r   r   )r   r   ri   r   r   r   rc   rc   rf   _from_temp_dataset  s    zDataArray._from_temp_dataset)r   rb   c                   sx   fdd fdd  D }| fddj D  tj h }tj|}tj|||j	d}|S )z&splits dataarray along dimension 'dim'c                   s    j | |i }i |_t|S rj   )locr   r<   )r   labelarrayr   rc   rf   subset*  s    z+DataArray._to_dataset_split.<locals>.subsetc                   s   i | ]}| |qS rc   rc   )rd   r   )r   r   rc   rf   r   /  s      z/DataArray._to_dataset_split.<locals>.<dictcomp>c                   s   i | ]\}}| kr||qS rc   rc   r   r   rc   rf   r   0  s       )r   r   )
	get_indexupdater   r|   r   r+   r   r&   r   r   )r   r   	variablescoord_namesr   r   rc   )r   r   r   rf   _to_dataset_split'  s       zDataArray._to_dataset_splitT)ri   r   rb   c                 C  s   |d kr| j }|d krtd|| jkr0td| j }| j||< |rf|D ]}|| jdd||< qL| j}t| j}tj	|||dS )NzSunable to convert unnamed DataArray to a Dataset without providing an explicit namezUcannot create a Dataset from a DataArray with the same name as one of its coordinatesFdeepr   )
ri   rr   r   r   r   r   r   r   r&   r   )r   ri   r   r   r   r   r   rc   rc   rf   r   8  s$    



zDataArray._to_dataset_whole)ri   promote_attrs)r   ri   r   rb   c                C  sb   |dk	r || j kr t| d|dk	rD|dk	r8td| |}n
| |}|r^t| j|_|S )a  Convert a DataArray to a Dataset.

        Parameters
        ----------
        dim : Hashable, optional
            Name of the dimension on this array along which to split this array
            into separate variables. If not provided, this array is converted
            into a Dataset of one variable.
        name : Hashable, optional
            Name to substitute for this array's name. Only valid if ``dim`` is
            not provided.
        promote_attrs : bool, default: False
            Set to True to shallow copy attrs of DataArray to returned Dataset.

        Returns
        -------
        dataset : Dataset
        Nz8 is not a dim. If supplying a ``name``, pass as a kwarg.z)cannot supply both dim and name arguments)rn   r{   r   r   r}   r   )r   r   ri   r   resultrc   rc   rf   
to_datasetS  s    
zDataArray.to_datasetc                 C  s   | j S )zThe name of this array.r   r   rc   rc   rf   ri   }  s    zDataArray.name)r   rb   c                 C  s
   || _ d S rj   r   r   r   rc   rc   rf   ri     s    c                 C  s   | j S )z>Low level interface to the Variable object for this DataArray.)r   r   rc   rc   rf   r     s    zDataArray.variableznp.dtypec                 C  s   | j jS )u   
        Data-type of the array’s elements.

        See Also
        --------
        ndarray.dtype
        numpy.dtype
        )r   dtyper   rc   rc   rf   r     s    
zDataArray.dtypeztuple[int, ...]c                 C  s   | j jS )zk
        Tuple of array dimensions.

        See Also
        --------
        numpy.ndarray.shape
        )r   r   r   rc   rc   rf   r     s    	zDataArray.shapeintc                 C  s   | j jS )u   
        Number of elements in the array.

        Equal to ``np.prod(a.shape)``, i.e., the product of the array’s dimensions.

        See Also
        --------
        numpy.ndarray.size
        )r   r   r   rc   rc   rf   r     s    zDataArray.sizec                 C  s   | j jS )z
        Total bytes consumed by the elements of this DataArray's data.

        If the underlying data array does not include ``nbytes``, estimates
        the bytes consumed based on the ``size`` and ``dtype``.
        )r   nbytesr   rc   rc   rf   r     s    zDataArray.nbytesc                 C  s   | j jS )zk
        Number of array dimensions.

        See Also
        --------
        numpy.ndarray.ndim
        )r   r   r   rc   rc   rf   r     s    	zDataArray.ndimc                 C  s
   t | jS rj   )rq   r   r   rc   rc   rf   __len__  s    zDataArray.__len__c                 C  s   | j jS )z
        The DataArray's data as an array. The underlying array type
        (e.g. dask, sparse, pint) is preserved.

        See Also
        --------
        DataArray.to_numpy
        DataArray.as_numpy
        DataArray.values
        r   r   r   rc   rc   rf   r     s    zDataArray.datac                 C  s   || j _d S rj   r   r   rc   rc   rf   r     s    z
np.ndarrayc                 C  s   | j jS )a  
        The array's data as a numpy.ndarray.

        If the array's data is not a numpy.ndarray this will attempt to convert
        it naively using np.array(), which will raise an error if the array
        type does not support coercion like this (e.g. cupy).
        r   valuesr   rc   rc   rf   r     s    	zDataArray.valuesc                 C  s   || j _d S rj   r   r   rc   rc   rf   r     s    c                 C  s
   | j  S )a	  
        Coerces wrapped data to numpy and returns a numpy.ndarray.

        See Also
        --------
        DataArray.as_numpy : Same but returns the surrounding DataArray instead.
        Dataset.as_numpy
        DataArray.values
        DataArray.data
        )r   to_numpyr   rc   rc   rf   r     s    zDataArray.to_numpy)r   rb   c                 C  s,   dd | j  D }| j| j || jdS )aJ  
        Coerces wrapped data and coordinates into numpy arrays, returning a DataArray.

        See Also
        --------
        DataArray.to_numpy : Same but returns only the data as a numpy.ndarray object.
        Dataset.as_numpy : Converts all variables in a Dataset.
        DataArray.values
        DataArray.data
        c                 S  s   i | ]\}}||  qS rc   )as_numpyr   rc   rc   rf   r      s      z&DataArray.as_numpy.<locals>.<dictcomp>r   )r   r|   r   r   r   r   )r   r   rc   rc   rf   r     s    zDataArray.as_numpyc                 C  s   | j jS rj   )r   
_in_memoryr   rc   rc   rf   r     s    zDataArray._in_memoryzpd.Indexc                 C  s
   | j  S rj   )r   	_to_indexr   rc   rc   rf   r     s    zDataArray._to_indexc                 C  s
   | j  S )zVConvert this variable to a pandas.Index. Only possible for 1D
        arrays.
        )r   to_indexr   rc   rc   rf   r   
  s    zDataArray.to_indexztuple[Hashable, ...]c                 C  s   | j jS )a=  Tuple of dimension names associated with this array.

        Note that the type of this property is inconsistent with
        `Dataset.dims`.  See `Dataset.sizes` and `DataArray.sizes` for
        consistently named properties.

        See Also
        --------
        DataArray.sizes
        Dataset.dims
        )r   rn   r   rc   rc   rf   rn     s    zDataArray.dimsr   c                 C  s   t dd S )NzMyou cannot assign dims on a DataArray. Use .rename() or .swap_dims() instead.)AttributeErrorr   rc   rc   rf   rn     s    zMapping[Hashable, Any])r   rb   c                 C  s,   t |r|S t|| j}tt| j|S rj   )r   rp   r   r   r   r}   ry   rn   r   r   rc   rc   rf   _item_key_to_dict&  s    
zDataArray._item_key_to_dict)r   r   rb   c                 C  sd   ddl m} z| j| }W n: tk
rT   tt| j| j}|| j||\}}}Y nX | j||dS )Nr   )_get_virtual_variablerh   )	xarray.core.datasetr   r   KeyErrorr}   ry   rn   r   r   )r   r   r   r   Z	dim_sizes_rc   rc   rf   _getitem_coord,  s    zDataArray._getitem_coordc                 C  s*   t |tr| |S | j| |dS d S )N)indexers)rs   rt   r   iselr   r   rc   rc   rf   r   7  s    

zDataArray.__getitem__)r   r   rb   c                 C  s\   t |tr|| j|< nB| | }t |tr6t||jj dd | | D }|| j|< d S )Nc                 S  s&   i | ]\}}|t |tr|jn|qS rc   )rs   r_   r   r   rc   rc   rf   r   I  s    z)DataArray.__setitem__.<locals>.<dictcomp>)	rs   rt   r   r_   r%   r   r   r|   r   )r   r   r   r   rc   rc   rf   r   >  s    

zDataArray.__setitem__c                 C  s   | j |= d S rj   r   r   rc   rc   rf   __delitem__O  s    zDataArray.__delitem__z Iterable[Mapping[Hashable, Any]]c                 c  s   | j E dH  | jV  dS )z2Places to look-up items for attribute-style accessN)_item_sourcesr   r   rc   rc   rf   _attr_sourcesR  s    zDataArray._attr_sourcesc                 c  s&   t | j| jdV  t | ji dV  dS )z*Places to look-up items for key-completion)rw   mappingN)r5   r   r   rn   r   rc   rc   rf   r  X  s    zDataArray._item_sourcesc                 C  s
   || j kS rj   r   r   rc   rc   rf   __contains__a  s    zDataArray.__contains__r   c                 C  s   t | S )z2Attribute for location based indexing like pandas.)r   r   rc   rc   rf   r   d  s    zDataArray.loczdict[Any, Any]c                 C  s   | j jS )z6Dictionary storing arbitrary metadata with this array.)r   r   r   rc   rc   rf   r   i  s    zDataArray.attrszMapping[Any, Any]c                 C  s   t || j_d S rj   )r}   r   r   r   rc   rc   rf   r   n  s    c                 C  s   | j jS )zWDictionary of format-specific settings for how this array should be
        serialized.)r   encodingr   rc   rc   rf   r  r  s    zDataArray.encodingc                 C  s   t || j_d S rj   )r}   r   r  r   rc   rc   rf   r  x  s    r)   c                 C  s
   | j  S )zMapping of pandas.Index objects used for label based indexing.

        Raises an error if this Dataset has indexes that cannot be coerced
        to pandas.Index objects.

        See Also
        --------
        DataArray.xindexes

        )xindexesZto_pandas_indexesr   rc   rc   rf   r   |  s    zDataArray.indexesc                   s   t  j fdd jD S )z>Mapping of xarray Index objects used for label based indexing.c                   s   i | ]}| j | qS rc   )r   r   r   rc   rf   r     s      z&DataArray.xindexes.<locals>.<dictcomp>)r)   r   r   rc   r   rf   r    s    zDataArray.xindexesr$   c                 C  s   t | S )z/Dictionary-like container of coordinate arrays.)r$   r   rc   rc   rf   r     s    zDataArray.coordsrO   zLiteral[False])r   namesdroprb   c                 C  s   d S rj   rc   r   r	  r
  rc   rc   rf   reset_coords  s    zDataArray.reset_coordszLiteral[True]c                C  s   d S rj   rc   r  rc   rc   rf   r    s    zT_DataArray | Datasetc                 C  sb   |dkrt | jt | j }| j ||}|r@| j|jdS | jdkrRtd| j	|| j< |S )a3
  Given names of coordinates, reset them to become variables.

        Parameters
        ----------
        names : str, Iterable of Hashable or None, optional
            Name(s) of non-index coordinates in this dataset to reset into
            variables. By default, all non-index coordinates are reset.
        drop : bool, default: False
            If True, remove coordinates instead of converting them into
            variables.

        Returns
        -------
        Dataset, or DataArray if ``drop == True``

        Examples
        --------
        >>> temperature = np.arange(25).reshape(5, 5)
        >>> pressure = np.arange(50, 75).reshape(5, 5)
        >>> da = xr.DataArray(
        ...     data=temperature,
        ...     dims=["x", "y"],
        ...     coords=dict(
        ...         lon=("x", np.arange(10, 15)),
        ...         lat=("y", np.arange(20, 25)),
        ...         Pressure=(["x", "y"], pressure),
        ...     ),
        ...     name="Temperature",
        ... )
        >>> da
        <xarray.DataArray 'Temperature' (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]])
        Coordinates:
            lon       (x) int64 10 11 12 13 14
            lat       (y) int64 20 21 22 23 24
            Pressure  (x, y) int64 50 51 52 53 54 55 56 57 ... 67 68 69 70 71 72 73 74
        Dimensions without coordinates: x, y

        Return Dataset with target coordinate as a data variable rather than a coordinate variable:

        >>> da.reset_coords(names="Pressure")
        <xarray.Dataset>
        Dimensions:      (x: 5, y: 5)
        Coordinates:
            lon          (x) int64 10 11 12 13 14
            lat          (y) int64 20 21 22 23 24
        Dimensions without coordinates: x, y
        Data variables:
            Pressure     (x, y) int64 50 51 52 53 54 55 56 57 ... 68 69 70 71 72 73 74
            Temperature  (x, y) int64 0 1 2 3 4 5 6 7 8 9 ... 16 17 18 19 20 21 22 23 24

        Return DataArray without targeted coordinate:

        >>> da.reset_coords(names="Pressure", drop=True)
        <xarray.DataArray 'Temperature' (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]])
        Coordinates:
            lon      (x) int64 10 11 12 13 14
            lat      (y) int64 20 21 22 23 24
        Dimensions without coordinates: x, y
        Nr   z<cannot reset_coords with drop=False on an unnamed DataArrray)
r   r   r   r   r  r   r   ri   rr   r   )r   r	  r
  r   rc   rc   rf   r    s    J
c                 C  s&   ddl m} |t| | j| j| jfS )Nr   )normalize_token)Z	dask.baser  r   r   r   r   )r   r  rc   rc   rf   __dask_tokenize__  s    zDataArray.__dask_tokenize__c                 C  s   |    S rj   )r   __dask_graph__r   rc   rc   rf   r     s    zDataArray.__dask_graph__c                 C  s   |    S rj   )r   __dask_keys__r   rc   rc   rf   r    s    zDataArray.__dask_keys__c                 C  s   |    S rj   )r   __dask_layers__r   rc   rc   rf   r    s    zDataArray.__dask_layers__c                 C  s
   |   jS rj   )r   __dask_optimize__r   rc   rc   rf   r  	  s    zDataArray.__dask_optimize__c                 C  s
   |   jS rj   )r   __dask_scheduler__r   rc   rc   rf   r    s    zDataArray.__dask_scheduler__c                 C  s$   |    \}}| j| j|f| fS rj   )r   __dask_postcompute___dask_finalizeri   r   funcargsrc   rc   rf   r    s    zDataArray.__dask_postcompute__c                 C  s$   |    \}}| j| j|f| fS rj   )r   __dask_postpersist__r  ri   r  rc   rc   rf   r    s    zDataArray.__dask_postpersist__c           	      O  s:   || f||}|j t}|j }|j}t||||ddS r   )r   r   r   r   r_   )	resultsri   r  r  kwargsdsr   r   r   rc   rc   rf   r    s
    zDataArray._dask_finalizec                 K  s.   |   jf |}| |}|j| _|j| _| S )aU  Manually trigger loading of this array's data from disk or a
        remote source into memory and return this array.

        Normally, it should not be necessary to call this method in user code,
        because all xarray functions should either work on deferred data or
        load data automatically. However, this method can be necessary when
        working with many file objects on disk.

        Parameters
        ----------
        **kwargs : dict
            Additional keyword arguments passed on to ``dask.compute``.

        See Also
        --------
        dask.compute
        )r   loadr   r   r   )r   r  r  newrc   rc   rf   r  !  s
    
zDataArray.loadc                 K  s   | j dd}|jf |S )a~  Manually trigger loading of this array's data from disk or a
        remote source into memory and return a new array. The original is
        left unaltered.

        Normally, it should not be necessary to call this method in user code,
        because all xarray functions should either work on deferred data or
        load data automatically. However, this method can be necessary when
        working with many file objects on disk.

        Parameters
        ----------
        **kwargs : dict
            Additional keyword arguments passed on to ``dask.compute``.

        See Also
        --------
        dask.compute
        Fr   )r   r  )r   r  r  rc   rc   rf   compute9  s    zDataArray.computec                 K  s   |   jf |}| |S )a  Trigger computation in constituent dask arrays

        This keeps them as dask arrays but encourages them to keep data in
        memory.  This is particularly useful when on a distributed machine.
        When on a single machine consider using ``.compute()`` instead.

        Parameters
        ----------
        **kwargs : dict
            Additional keyword arguments passed on to ``dask.persist``.

        See Also
        --------
        dask.persist
        )r   persistr   )r   r  r  rc   rc   rf   r   O  s    zDataArray.persist)r   r   r   rb   c                 C  s   | j ||dS )a}  Returns a copy of this array.

        If `deep=True`, a deep copy is made of the data array.
        Otherwise, a shallow copy is made, and the returned data array's
        values are a new view of this data array's values.

        Use `data` to create a new object with the same structure as
        original but entirely new data.

        Parameters
        ----------
        deep : bool, optional
            Whether the data array and its coordinates are loaded into memory
            and copied onto the new object. Default is True.
        data : array_like, optional
            Data to use in the new object. Must have same shape as original.
            When `data` is used, `deep` is ignored for all data variables,
            and only used for coords.

        Returns
        -------
        copy : DataArray
            New object with dimensions, attributes, coordinates, name,
            encoding, and optionally data copied from original.

        Examples
        --------
        Shallow versus deep copy

        >>> array = xr.DataArray([1, 2, 3], dims="x", coords={"x": ["a", "b", "c"]})
        >>> array.copy()
        <xarray.DataArray (x: 3)>
        array([1, 2, 3])
        Coordinates:
          * x        (x) <U1 'a' 'b' 'c'
        >>> array_0 = array.copy(deep=False)
        >>> array_0[0] = 7
        >>> array_0
        <xarray.DataArray (x: 3)>
        array([7, 2, 3])
        Coordinates:
          * x        (x) <U1 'a' 'b' 'c'
        >>> array
        <xarray.DataArray (x: 3)>
        array([7, 2, 3])
        Coordinates:
          * x        (x) <U1 'a' 'b' 'c'

        Changing the data using the ``data`` argument maintains the
        structure of the original object, but with the new data. Original
        object is unaffected.

        >>> array.copy(data=[0.1, 0.2, 0.3])
        <xarray.DataArray (x: 3)>
        array([0.1, 0.2, 0.3])
        Coordinates:
          * x        (x) <U1 'a' 'b' 'c'
        >>> array
        <xarray.DataArray (x: 3)>
        array([7, 2, 3])
        Coordinates:
          * x        (x) <U1 'a' 'b' 'c'

        See Also
        --------
        pandas.DataFrame.copy
        )r   r   _copy)r   r   r   rc   rc   rf   r   b  s    DzDataArray.copyzdict[int, Any] | None)r   r   r   memorb   c           
      C  st   | j j|||d}| jj|d\}}i }| j D ]0\}}	||krP|| ||< q2|	j||d||< q2| j|||dS )N)r   r   r#  r   r   r#  r   )r   r"  r  Zcopy_indexesr   r|   r   )
r   r   r   r#  r   r   Z
index_varsr   r   r   rc   rc   rf   r"    s    zDataArray._copyc                 C  s   | j ddS )NFr   r!  r   rc   rc   rf   __copy__  s    zDataArray.__copy__)r   r#  rb   c                 C  s   | j d|dS )NTr$  r!  )r   r#  rc   rc   rf   __deepcopy__  s    zDataArray.__deepcopy__z"tuple[tuple[int, ...], ...] | Nonec                 C  s   | j jS )a  
        Tuple of block lengths for this dataarray's data, in order of dimensions, or None if
        the underlying data is not a dask array.

        See Also
        --------
        DataArray.chunk
        DataArray.chunksizes
        xarray.unify_chunks
        )r   chunksr   rc   rc   rf   r'    s    zDataArray.chunkszMapping[Any, tuple[int, ...]]c                 C  s$   | j gdd | j D  }t|S )a  
        Mapping from dimension names to block lengths for this dataarray's data, or None if
        the underlying data is not a dask array.
        Cannot be modified directly, but can be modified by calling .chunk().

        Differs from DataArray.chunks because it returns a mapping of dimensions to chunk shapes
        instead of a tuple of chunk shapes.

        See Also
        --------
        DataArray.chunk
        DataArray.chunks
        xarray.unify_chunks
        c                 S  s   g | ]
}|j qS rc   r   rd   crc   rc   rf   rg     s     z(DataArray.chunksizes.<locals>.<listcomp>)r   r   r   r!   )r   Zall_variablesrc   rc   rf   
chunksizes  s    zDataArray.chunksizeszxarray-zrint | Literal['auto'] | tuple[int, ...] | tuple[tuple[int, ...], ...] | Mapping[Any, None | int | tuple[int, ...]]rt   z
str | None)r   r'  name_prefixtokenlockinline_arraychunks_kwargsrb   c                 K  s   |dkrt jdtd i }t|tttfr:t| j	|}n,t|t
tfrZtt| j	|}nt||d}|  j|||||d}| |S )a  Coerce this array's data into a dask arrays with the given chunks.

        If this variable is a non-dask array, it will be converted to dask
        array. If it's a dask array, it will be rechunked to the given chunk
        sizes.

        If neither chunks is not provided for one or more dimensions, chunk
        sizes along that dimension will not be updated; non-dask arrays will be
        converted into dask arrays with a single block.

        Parameters
        ----------
        chunks : int, "auto", tuple of int or mapping of Hashable to int, optional
            Chunk sizes along each dimension, e.g., ``5``, ``"auto"``, ``(5, 5)`` or
            ``{"x": 5, "y": 5}``.
        name_prefix : str, optional
            Prefix for the name of the new dask array.
        token : str, optional
            Token uniquely identifying this array.
        lock : optional
            Passed on to :py:func:`dask.array.from_array`, if the array is not
            already as dask array.
        inline_array: optional
            Passed on to :py:func:`dask.array.from_array`, if the array is not
            already as dask array.
        **chunks_kwargs : {dim: chunks, ...}, optional
            The keyword arguments form of ``chunks``.
            One of chunks or chunks_kwargs must be provided.

        Returns
        -------
        chunked : xarray.DataArray

        See Also
        --------
        DataArray.chunks
        DataArray.chunksizes
        xarray.unify_chunks
        dask.array.from_array
        Nz]None value for 'chunks' is deprecated. It will raise an error in the future. Use instead '{}'categorychunk)r,  r-  r.  r/  )warningswarnFutureWarningrs   floatrt   r   r}   fromkeysrn   rz   rv   ry   r8   r   r3  r   )r   r'  r,  r-  r.  r/  r0  r  rc   rc   rf   r3    s&    7zDataArray.chunkraiserQ   )r   r   r
  missing_dimsindexers_kwargsrb   c                   s   t ||d}tdd | D r@|  j|||d}| |S | jj||d}t| j	|\}}i }	| j
 D ]V\}
 |
|kr||
  n4 fdd| D }|r | |r jdkrqn |	|
< qn| j||	|d	S )
a  Return a new DataArray whose data is given by selecting indexes
        along the specified dimension(s).

        Parameters
        ----------
        indexers : dict, optional
            A dict with keys matching dimensions and values given
            by integers, slice objects or arrays.
            indexer can be a integer, slice, array-like or DataArray.
            If DataArrays are passed as indexers, xarray-style indexing will be
            carried out. See :ref:`indexing` for the details.
            One of indexers or indexers_kwargs must be provided.
        drop : bool, default: False
            If ``drop=True``, drop coordinates variables indexed by integers
            instead of making them scalar.
        missing_dims : {"raise", "warn", "ignore"}, default: "raise"
            What to do if dimensions that should be selected from are not present in the
            DataArray:
            - "raise": raise an exception
            - "warn": raise a warning, and ignore the missing dimensions
            - "ignore": ignore the missing dimensions
        **indexers_kwargs : {dim: indexer, ...}, optional
            The keyword arguments form of ``indexers``.

        Returns
        -------
        indexed : xarray.DataArray

        See Also
        --------
        Dataset.isel
        DataArray.sel

        Examples
        --------
        >>> da = xr.DataArray(np.arange(25).reshape(5, 5), dims=("x", "y"))
        >>> da
        <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

        >>> tgt_x = xr.DataArray(np.arange(0, 5), dims="points")
        >>> tgt_y = xr.DataArray(np.arange(0, 5), dims="points")
        >>> da = da.isel(x=tgt_x, y=tgt_y)
        >>> da
        <xarray.DataArray (points: 5)>
        array([ 0,  6, 12, 18, 24])
        Dimensions without coordinates: points
        r   c                 s  s   | ]}t |V  qd S rj   )r-   )rd   idxrc   rc   rf   ro   v  s     z!DataArray.isel.<locals>.<genexpr>)r
  r:  )r:  c                   s    i | ]\}}| j kr||qS rc   rm   r   Zcoord_valuerc   rf   r     s    
  z"DataArray.isel.<locals>.<dictcomp>r   r   )r8   r~   r   r   Z_isel_fancyr   r   r   r,   r  r   r|   r   r   )r   r   r
  r:  r;  r  r   r   Zindex_variablesr   Z
coord_nameZcoord_indexersrc   r=  rf   r   7  s.    =  




zDataArray.isel)r   r   methodr
  r;  rb   c                 K  s(   |   jf ||||d|}| |S )a  Return a new DataArray whose data is given by selecting index
        labels along the specified dimension(s).

        In contrast to `DataArray.isel`, indexers for this method should use
        labels instead of integers.

        Under the hood, this method is powered by using pandas's powerful Index
        objects. This makes label based indexing essentially just as fast as
        using integer indexing.

        It also means this method uses pandas's (well documented) logic for
        indexing. This means you can use string shortcuts for datetime indexes
        (e.g., '2000-01' to select all values in January 2000). It also means
        that slices are treated as inclusive of both the start and stop values,
        unlike normal Python indexing.

        .. warning::

          Do not try to assign values when using any of the indexing methods
          ``isel`` or ``sel``::

            da = xr.DataArray([0, 1, 2, 3], dims=['x'])
            # DO NOT do this
            da.isel(x=[0, 1, 2])[1] = -1

          Assigning values with the chained indexing using ``.sel`` or
          ``.isel`` fails silently.

        Parameters
        ----------
        indexers : dict, optional
            A dict with keys matching dimensions and values given
            by scalars, slices or arrays of tick labels. For dimensions with
            multi-index, the indexer may also be a dict-like object with keys
            matching index level names.
            If DataArrays are passed as indexers, xarray-style indexing will be
            carried out. See :ref:`indexing` for the details.
            One of indexers or indexers_kwargs must be provided.
        method : {None, "nearest", "pad", "ffill", "backfill", "bfill"}, optional
            Method to use for inexact matches:

            - None (default): only exact matches
            - pad / ffill: propagate last valid index value forward
            - backfill / bfill: propagate next valid index value backward
            - nearest: use nearest valid index value

        tolerance : optional
            Maximum distance between original and new labels for inexact
            matches. The values of the index at the matching locations must
            satisfy the equation ``abs(index[indexer] - target) <= tolerance``.
        drop : bool, optional
            If ``drop=True``, drop coordinates variables in `indexers` instead
            of making them scalar.
        **indexers_kwargs : {dim: indexer, ...}, optional
            The keyword arguments form of ``indexers``.
            One of indexers or indexers_kwargs must be provided.

        Returns
        -------
        obj : DataArray
            A new DataArray with the same contents as this DataArray, except the
            data and each dimension is indexed by the appropriate indexers.
            If indexer DataArrays have coordinates that do not conflict with
            this object, then these coordinates will be attached.
            In general, each array's data will be a view of the array's data
            in this DataArray, unless vectorized indexing was triggered by using
            an array indexer, in which case the data will be a copy.

        See Also
        --------
        Dataset.sel
        DataArray.isel

        Examples
        --------
        >>> da = xr.DataArray(
        ...     np.arange(25).reshape(5, 5),
        ...     coords={"x": np.arange(5), "y": np.arange(5)},
        ...     dims=("x", "y"),
        ... )
        >>> da
        <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]])
        Coordinates:
          * x        (x) int64 0 1 2 3 4
          * y        (y) int64 0 1 2 3 4

        >>> tgt_x = xr.DataArray(np.linspace(0, 4, num=5), dims="points")
        >>> tgt_y = xr.DataArray(np.linspace(0, 4, num=5), dims="points")
        >>> da = da.sel(x=tgt_x, y=tgt_y, method="nearest")
        >>> da
        <xarray.DataArray (points: 5)>
        array([ 0,  6, 12, 18, 24])
        Coordinates:
            x        (points) int64 0 1 2 3 4
            y        (points) int64 0 1 2 3 4
        Dimensions without coordinates: points
        )r   r
  r>  	tolerance)r   r   r   )r   r   r>  r?  r
  r;  r  rc   rc   rf   r     s    n
zDataArray.selzMapping[Any, int] | int | None)r   r   r;  rb   c                 K  s   |   j|f|}| |S )a  Return a new DataArray whose data is given by the the first `n`
        values along the specified dimension(s). Default `n` = 5

        See Also
        --------
        Dataset.head
        DataArray.tail
        DataArray.thin

        Examples
        --------
        >>> da = xr.DataArray(
        ...     np.arange(25).reshape(5, 5),
        ...     dims=("x", "y"),
        ... )
        >>> da
        <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

        >>> da.head(x=1)
        <xarray.DataArray (x: 1, y: 5)>
        array([[0, 1, 2, 3, 4]])
        Dimensions without coordinates: x, y

        >>> da.head({"x": 2, "y": 2})
        <xarray.DataArray (x: 2, y: 2)>
        array([[0, 1],
               [5, 6]])
        Dimensions without coordinates: x, y
        )r   headr   r   r   r;  r  rc   rc   rf   r@  	  s    (zDataArray.headc                 K  s   |   j|f|}| |S )a2  Return a new DataArray whose data is given by the the last `n`
        values along the specified dimension(s). Default `n` = 5

        See Also
        --------
        Dataset.tail
        DataArray.head
        DataArray.thin

        Examples
        --------
        >>> da = xr.DataArray(
        ...     np.arange(25).reshape(5, 5),
        ...     dims=("x", "y"),
        ... )
        >>> da
        <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

        >>> da.tail(y=1)
        <xarray.DataArray (x: 5, y: 1)>
        array([[ 4],
               [ 9],
               [14],
               [19],
               [24]])
        Dimensions without coordinates: x, y

        >>> da.tail({"x": 2, "y": 2})
        <xarray.DataArray (x: 2, y: 2)>
        array([[18, 19],
               [23, 24]])
        Dimensions without coordinates: x, y
        )r   tailr   rA  rc   rc   rf   rB  4  s    ,zDataArray.tailc                 K  s   |   j|f|}| |S )a:  Return a new DataArray whose data is given by each `n` value
        along the specified dimension(s).

        Examples
        --------
        >>> x_arr = np.arange(0, 26)
        >>> x_arr
        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, 25])
        >>> x = xr.DataArray(
        ...     np.reshape(x_arr, (2, 13)),
        ...     dims=("x", "y"),
        ...     coords={"x": [0, 1], "y": np.arange(0, 13)},
        ... )
        >>> x
        <xarray.DataArray (x: 2, y: 13)>
        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, 25]])
        Coordinates:
          * x        (x) int64 0 1
          * y        (y) int64 0 1 2 3 4 5 6 7 8 9 10 11 12

        >>>
        >>> x.thin(3)
        <xarray.DataArray (x: 1, y: 5)>
        array([[ 0,  3,  6,  9, 12]])
        Coordinates:
          * x        (x) int64 0
          * y        (y) int64 0 3 6 9 12
        >>> x.thin({"x": 2, "y": 5})
        <xarray.DataArray (x: 1, y: 3)>
        array([[ 0,  5, 10]])
        Coordinates:
          * x        (x) int64 0
          * y        (y) int64 0 5 10

        See Also
        --------
        Dataset.thin
        DataArray.head
        DataArray.tail
        )r   thinr   rA  rc   rc   rf   rC  c  s    /zDataArray.thinzDataArray | DatasetzIterable[Hashable] | None)r   otherexcluderb   c                 C  sP   |dkrt  }nt |}t|| dd|d}t||\}}ttd|d |||S )aG  Broadcast this DataArray against another Dataset or DataArray.

        This is equivalent to xr.broadcast(other, self)[1]

        xarray objects are broadcast against each other in arithmetic
        operations, so this method is not be necessary for most uses.

        If no change is needed, the input data is returned to the output
        without being copied.

        If new coords are added by the broadcast, their values are
        NaN filled.

        Parameters
        ----------
        other : Dataset or DataArray
            Object against which to broadcast this array.
        exclude : iterable of Hashable, optional
            Dimensions that must not be broadcasted

        Returns
        -------
        new_da : DataArray
            The caller broadcasted against ``other``.

        Examples
        --------
        >>> arr1 = xr.DataArray(
        ...     np.random.randn(2, 3),
        ...     dims=("x", "y"),
        ...     coords={"x": ["a", "b"], "y": ["a", "b", "c"]},
        ... )
        >>> arr2 = xr.DataArray(
        ...     np.random.randn(3, 2),
        ...     dims=("x", "y"),
        ...     coords={"x": ["a", "b", "c"], "y": ["a", "b"]},
        ... )
        >>> arr1
        <xarray.DataArray (x: 2, y: 3)>
        array([[ 1.76405235,  0.40015721,  0.97873798],
               [ 2.2408932 ,  1.86755799, -0.97727788]])
        Coordinates:
          * x        (x) <U1 'a' 'b'
          * y        (y) <U1 'a' 'b' 'c'
        >>> arr2
        <xarray.DataArray (x: 3, y: 2)>
        array([[ 0.95008842, -0.15135721],
               [-0.10321885,  0.4105985 ],
               [ 0.14404357,  1.45427351]])
        Coordinates:
          * x        (x) <U1 'a' 'b' 'c'
          * y        (y) <U1 'a' 'b'
        >>> arr1.broadcast_like(arr2)
        <xarray.DataArray (x: 3, y: 3)>
        array([[ 1.76405235,  0.40015721,  0.97873798],
               [ 2.2408932 ,  1.86755799, -0.97727788],
               [        nan,         nan,         nan]])
        Coordinates:
          * x        (x) <U1 'a' 'b' 'c'
          * y        (y) <U1 'a' 'b' 'c'
        NouterF)joinr   rE  rZ   r   )r   r   r   r   r   )r   rD  rE  r  Zdims_mapZcommon_coordsrc   rc   rf   broadcast_like  s    B   zDataArray.broadcast_likezalignment.Alignerzdict[Hashable, Any]zdict[Hashable, Variable]zfrozenset[Hashable])	r   alignerdim_pos_indexersr   r   
fill_valueexclude_dimsexclude_varsrb   c              	   C  s^   t |tr6| }t }|| j|}	|	|k	r6|	|t< |  }
|
|||||||}| 	|S )zECallback called from ``Aligner`` to create a new reindexed DataArray.)
rs   r}   r   r   r   ri   r   r   _reindex_callbackr   )r   rI  rJ  r   r   rK  rL  rM  sentinelr   r  Z	reindexedrc   rc   rf   rN    s"    
	zDataArray._reindex_callbackrX   z*int | float | Iterable[int | float] | None)r   rD  r>  r?  r   rb   c                 C  s   t j| |||||dS )u  Conform this object onto the indexes of another object, filling in
        missing values with ``fill_value``. The default fill value is NaN.

        Parameters
        ----------
        other : Dataset or DataArray
            Object with an 'indexes' attribute giving a mapping from dimension
            names to pandas.Index objects, which provides coordinates upon
            which to index the variables in this dataset. The indexes on this
            other object need not be the same as the indexes on this
            dataset. Any mis-matched index values will be filled in with
            NaN, and any mis-matched dimension names will simply be ignored.
        method : {None, "nearest", "pad", "ffill", "backfill", "bfill"}, optional
            Method to use for filling index values from other not found on this
            data array:

            - None (default): don't fill gaps
            - pad / ffill: propagate last valid index value forward
            - backfill / bfill: propagate next valid index value backward
            - nearest: use nearest valid index value

        tolerance : optional
            Maximum distance between original and new labels for inexact
            matches. The values of the index at the matching locations must
            satisfy the equation ``abs(index[indexer] - target) <= tolerance``.
            Tolerance may be a scalar value, which applies the same tolerance
            to all values, or list-like, which applies variable tolerance per
            element. List-like must be the same size as the index and its dtype
            must exactly match the index’s type.
        copy : bool, default: True
            If ``copy=True``, data in the return value is always copied. If
            ``copy=False`` and reindexing is unnecessary, or can be performed
            with only slice operations, then the output may share memory with
            the input. In either case, a new xarray object is always returned.
        fill_value : scalar or dict-like, optional
            Value to use for newly missing values. If a dict-like, maps
            variable names (including coordinates) to fill values. Use this
            data array's name to refer to the data array's values.

        Returns
        -------
        reindexed : DataArray
            Another dataset array, with this array's data but coordinates from
            the other object.

        Examples
        --------
        >>> data = np.arange(12).reshape(4, 3)
        >>> da1 = xr.DataArray(
        ...     data=data,
        ...     dims=["x", "y"],
        ...     coords={"x": [10, 20, 30, 40], "y": [70, 80, 90]},
        ... )
        >>> da1
        <xarray.DataArray (x: 4, y: 3)>
        array([[ 0,  1,  2],
               [ 3,  4,  5],
               [ 6,  7,  8],
               [ 9, 10, 11]])
        Coordinates:
          * x        (x) int64 10 20 30 40
          * y        (y) int64 70 80 90
        >>> da2 = xr.DataArray(
        ...     data=data,
        ...     dims=["x", "y"],
        ...     coords={"x": [40, 30, 20, 10], "y": [90, 80, 70]},
        ... )
        >>> da2
        <xarray.DataArray (x: 4, y: 3)>
        array([[ 0,  1,  2],
               [ 3,  4,  5],
               [ 6,  7,  8],
               [ 9, 10, 11]])
        Coordinates:
          * x        (x) int64 40 30 20 10
          * y        (y) int64 90 80 70

        Reindexing with both DataArrays having the same coordinates set, but in different order:

        >>> da1.reindex_like(da2)
        <xarray.DataArray (x: 4, y: 3)>
        array([[11, 10,  9],
               [ 8,  7,  6],
               [ 5,  4,  3],
               [ 2,  1,  0]])
        Coordinates:
          * x        (x) int64 40 30 20 10
          * y        (y) int64 90 80 70

        Reindexing with the other array having coordinates which the source array doesn't have:

        >>> data = np.arange(12).reshape(4, 3)
        >>> da1 = xr.DataArray(
        ...     data=data,
        ...     dims=["x", "y"],
        ...     coords={"x": [10, 20, 30, 40], "y": [70, 80, 90]},
        ... )
        >>> da2 = xr.DataArray(
        ...     data=data,
        ...     dims=["x", "y"],
        ...     coords={"x": [20, 10, 29, 39], "y": [70, 80, 90]},
        ... )
        >>> da1.reindex_like(da2)
        <xarray.DataArray (x: 4, y: 3)>
        array([[ 3.,  4.,  5.],
               [ 0.,  1.,  2.],
               [nan, nan, nan],
               [nan, nan, nan]])
        Coordinates:
          * x        (x) int64 20 10 29 39
          * y        (y) int64 70 80 90

        Filling missing values with the previous valid index with respect to the coordinates' value:

        >>> da1.reindex_like(da2, method="ffill")
        <xarray.DataArray (x: 4, y: 3)>
        array([[3, 4, 5],
               [0, 1, 2],
               [3, 4, 5],
               [6, 7, 8]])
        Coordinates:
          * x        (x) int64 20 10 29 39
          * y        (y) int64 70 80 90

        Filling missing values while tolerating specified error for inexact matches:

        >>> da1.reindex_like(da2, method="ffill", tolerance=5)
        <xarray.DataArray (x: 4, y: 3)>
        array([[ 3.,  4.,  5.],
               [ 0.,  1.,  2.],
               [nan, nan, nan],
               [nan, nan, nan]])
        Coordinates:
          * x        (x) int64 20 10 29 39
          * y        (y) int64 70 80 90

        Filling missing values with manually specified values:

        >>> da1.reindex_like(da2, fill_value=19)
        <xarray.DataArray (x: 4, y: 3)>
        array([[ 3,  4,  5],
               [ 0,  1,  2],
               [19, 19, 19],
               [19, 19, 19]])
        Coordinates:
          * x        (x) int64 20 10 29 39
          * y        (y) int64 70 80 90

        See Also
        --------
        DataArray.reindex
        align
        )rD  r>  r?  r   rK  )r   reindex_like)r   rD  r>  r?  r   rK  rc   rc   rf   rP    s     "zDataArray.reindex_likezfloat | Iterable[float] | None)r   r   r>  r?  r   r;  rb   c                 K  s$   t ||d}tj| |||||dS )u<  Conform this object onto the indexes of another object, filling in
        missing values with ``fill_value``. The default fill value is NaN.

        Parameters
        ----------
        indexers : dict, optional
            Dictionary with keys given by dimension names and values given by
            arrays of coordinates tick labels. Any mis-matched coordinate
            values will be filled in with NaN, and any mis-matched dimension
            names will simply be ignored.
            One of indexers or indexers_kwargs must be provided.
        copy : bool, optional
            If ``copy=True``, data in the return value is always copied. If
            ``copy=False`` and reindexing is unnecessary, or can be performed
            with only slice operations, then the output may share memory with
            the input. In either case, a new xarray object is always returned.
        method : {None, 'nearest', 'pad'/'ffill', 'backfill'/'bfill'}, optional
            Method to use for filling index values in ``indexers`` not found on
            this data array:

            - None (default): don't fill gaps
            - pad / ffill: propagate last valid index value forward
            - backfill / bfill: propagate next valid index value backward
            - nearest: use nearest valid index value

        tolerance : float | Iterable[float] | None, default: None
            Maximum distance between original and new labels for inexact
            matches. The values of the index at the matching locations must
            satisfy the equation ``abs(index[indexer] - target) <= tolerance``.
            Tolerance may be a scalar value, which applies the same tolerance
            to all values, or list-like, which applies variable tolerance per
            element. List-like must be the same size as the index and its dtype
            must exactly match the index’s type.
        fill_value : scalar or dict-like, optional
            Value to use for newly missing values. If a dict-like, maps
            variable names (including coordinates) to fill values. Use this
            data array's name to refer to the data array's values.
        **indexers_kwargs : {dim: indexer, ...}, optional
            The keyword arguments form of ``indexers``.
            One of indexers or indexers_kwargs must be provided.

        Returns
        -------
        reindexed : DataArray
            Another dataset array, with this array's data but replaced
            coordinates.

        Examples
        --------
        Reverse latitude:

        >>> da = xr.DataArray(
        ...     np.arange(4),
        ...     coords=[np.array([90, 89, 88, 87])],
        ...     dims="lat",
        ... )
        >>> da
        <xarray.DataArray (lat: 4)>
        array([0, 1, 2, 3])
        Coordinates:
          * lat      (lat) int64 90 89 88 87
        >>> da.reindex(lat=da.lat[::-1])
        <xarray.DataArray (lat: 4)>
        array([3, 2, 1, 0])
        Coordinates:
          * lat      (lat) int64 87 88 89 90

        See Also
        --------
        DataArray.reindex_like
        align
        reindex)r   r>  r?  r   rK  )r   r8   r   rQ  )r   r   r>  r?  r   rK  r;  rc   rc   rf   rQ    s    QzDataArray.reindexlinearrR   zMapping[str, Any] | None)r   r   r>  assume_sortedr  coords_kwargsrb   c                 K  sD   | j jdkrtd| j |  j|f|||d|}| |S )a*  Interpolate a DataArray onto new coordinates

        Performs univariate or multivariate interpolation of a DataArray onto
        new coordinates using scipy's interpolation routines. If interpolating
        along an existing dimension, :py:class:`scipy.interpolate.interp1d` is
        called. When interpolating along multiple existing dimensions, an
        attempt is made to decompose the interpolation into multiple
        1-dimensional interpolations. If this is possible,
        :py:class:`scipy.interpolate.interp1d` is called. Otherwise,
        :py:func:`scipy.interpolate.interpn` is called.

        Parameters
        ----------
        coords : dict, optional
            Mapping from dimension names to the new coordinates.
            New coordinate can be a scalar, array-like or DataArray.
            If DataArrays are passed as new coordinates, their dimensions are
            used for the broadcasting. Missing values are skipped.
        method : {"linear", "nearest", "zero", "slinear", "quadratic", "cubic", "polynomial"}, default: "linear"
            The method used to interpolate. The method should be supported by
            the scipy interpolator:

            - ``interp1d``: {"linear", "nearest", "zero", "slinear",
              "quadratic", "cubic", "polynomial"}
            - ``interpn``: {"linear", "nearest"}

            If ``"polynomial"`` is passed, the ``order`` keyword argument must
            also be provided.
        assume_sorted : bool, default: False
            If False, values of x can be in any order and they are sorted
            first. If True, x has to be an array of monotonically increasing
            values.
        kwargs : dict-like or None, default: None
            Additional keyword arguments passed to scipy's interpolator. Valid
            options and their behavior depend whether ``interp1d`` or
            ``interpn`` is used.
        **coords_kwargs : {dim: coordinate, ...}, optional
            The keyword arguments form of ``coords``.
            One of coords or coords_kwargs must be provided.

        Returns
        -------
        interpolated : DataArray
            New dataarray on the new coordinates.

        Notes
        -----
        scipy is required.

        See Also
        --------
        scipy.interpolate.interp1d
        scipy.interpolate.interpn

        Examples
        --------
        >>> da = xr.DataArray(
        ...     data=[[1, 4, 2, 9], [2, 7, 6, np.nan], [6, np.nan, 5, 8]],
        ...     dims=("x", "y"),
        ...     coords={"x": [0, 1, 2], "y": [10, 12, 14, 16]},
        ... )
        >>> da
        <xarray.DataArray (x: 3, y: 4)>
        array([[ 1.,  4.,  2.,  9.],
               [ 2.,  7.,  6., nan],
               [ 6., nan,  5.,  8.]])
        Coordinates:
          * x        (x) int64 0 1 2
          * y        (y) int64 10 12 14 16

        1D linear interpolation (the default):

        >>> da.interp(x=[0, 0.75, 1.25, 1.75])
        <xarray.DataArray (x: 4, y: 4)>
        array([[1.  , 4.  , 2.  ,  nan],
               [1.75, 6.25, 5.  ,  nan],
               [3.  ,  nan, 5.75,  nan],
               [5.  ,  nan, 5.25,  nan]])
        Coordinates:
          * y        (y) int64 10 12 14 16
          * x        (x) float64 0.0 0.75 1.25 1.75

        1D nearest interpolation:

        >>> da.interp(x=[0, 0.75, 1.25, 1.75], method="nearest")
        <xarray.DataArray (x: 4, y: 4)>
        array([[ 1.,  4.,  2.,  9.],
               [ 2.,  7.,  6., nan],
               [ 2.,  7.,  6., nan],
               [ 6., nan,  5.,  8.]])
        Coordinates:
          * y        (y) int64 10 12 14 16
          * x        (x) float64 0.0 0.75 1.25 1.75

        1D linear extrapolation:

        >>> da.interp(
        ...     x=[1, 1.5, 2.5, 3.5],
        ...     method="linear",
        ...     kwargs={"fill_value": "extrapolate"},
        ... )
        <xarray.DataArray (x: 4, y: 4)>
        array([[ 2. ,  7. ,  6. ,  nan],
               [ 4. ,  nan,  5.5,  nan],
               [ 8. ,  nan,  4.5,  nan],
               [12. ,  nan,  3.5,  nan]])
        Coordinates:
          * y        (y) int64 10 12 14 16
          * x        (x) float64 1.0 1.5 2.5 3.5

        2D linear interpolation:

        >>> da.interp(x=[0, 0.75, 1.25, 1.75], y=[11, 13, 15], method="linear")
        <xarray.DataArray (x: 4, y: 3)>
        array([[2.5  , 3.   ,   nan],
               [4.   , 5.625,   nan],
               [  nan,   nan,   nan],
               [  nan,   nan,   nan]])
        Coordinates:
          * x        (x) float64 0.0 0.75 1.25 1.75
          * y        (y) int64 11 13 15
        uifc5interp only works for a numeric type array. Given {}.r>  r  rS  )r   kindr{   formatr   interpr   )r   r   r>  rS  r  rT  r  rc   rc   rf   rZ    s"     zDataArray.interp)r   rD  r>  rS  r  rb   c                 C  s<   | j jdkrtd| j |  j||||d}| |S )a  Interpolate this object onto the coordinates of another object,
        filling out of range values with NaN.

        If interpolating along a single existing dimension,
        :py:class:`scipy.interpolate.interp1d` is called. When interpolating
        along multiple existing dimensions, an attempt is made to decompose the
        interpolation into multiple 1-dimensional interpolations. If this is
        possible, :py:class:`scipy.interpolate.interp1d` is called. Otherwise,
        :py:func:`scipy.interpolate.interpn` is called.

        Parameters
        ----------
        other : Dataset or DataArray
            Object with an 'indexes' attribute giving a mapping from dimension
            names to an 1d array-like, which provides coordinates upon
            which to index the variables in this dataset. Missing values are skipped.
        method : {"linear", "nearest", "zero", "slinear", "quadratic", "cubic", "polynomial"}, default: "linear"
            The method used to interpolate. The method should be supported by
            the scipy interpolator:

            - {"linear", "nearest", "zero", "slinear", "quadratic", "cubic",
              "polynomial"} when ``interp1d`` is called.
            - {"linear", "nearest"} when ``interpn`` is called.

            If ``"polynomial"`` is passed, the ``order`` keyword argument must
            also be provided.
        assume_sorted : bool, default: False
            If False, values of coordinates that are interpolated over can be
            in any order and they are sorted first. If True, interpolated
            coordinates are assumed to be an array of monotonically increasing
            values.
        kwargs : dict, optional
            Additional keyword passed to scipy's interpolator.

        Returns
        -------
        interpolated : DataArray
            Another dataarray by interpolating this dataarray's data along the
            coordinates of the other object.

        Examples
        --------
        >>> data = np.arange(12).reshape(4, 3)
        >>> da1 = xr.DataArray(
        ...     data=data,
        ...     dims=["x", "y"],
        ...     coords={"x": [10, 20, 30, 40], "y": [70, 80, 90]},
        ... )
        >>> da1
        <xarray.DataArray (x: 4, y: 3)>
        array([[ 0,  1,  2],
               [ 3,  4,  5],
               [ 6,  7,  8],
               [ 9, 10, 11]])
        Coordinates:
          * x        (x) int64 10 20 30 40
          * y        (y) int64 70 80 90
        >>> da2 = xr.DataArray(
        ...     data=data,
        ...     dims=["x", "y"],
        ...     coords={"x": [10, 20, 29, 39], "y": [70, 80, 90]},
        ... )
        >>> da2
        <xarray.DataArray (x: 4, y: 3)>
        array([[ 0,  1,  2],
               [ 3,  4,  5],
               [ 6,  7,  8],
               [ 9, 10, 11]])
        Coordinates:
          * x        (x) int64 10 20 29 39
          * y        (y) int64 70 80 90

        Interpolate the values in the coordinates of the other DataArray with respect to the source's values:

        >>> da2.interp_like(da1)
        <xarray.DataArray (x: 4, y: 3)>
        array([[0. , 1. , 2. ],
               [3. , 4. , 5. ],
               [6.3, 7.3, 8.3],
               [nan, nan, nan]])
        Coordinates:
          * x        (x) int64 10 20 30 40
          * y        (y) int64 70 80 90

        Could also extrapolate missing values:

        >>> da2.interp_like(da1, kwargs={"fill_value": "extrapolate"})
        <xarray.DataArray (x: 4, y: 3)>
        array([[ 0. ,  1. ,  2. ],
               [ 3. ,  4. ,  5. ],
               [ 6.3,  7.3,  8.3],
               [ 9.3, 10.3, 11.3]])
        Coordinates:
          * x        (x) int64 10 20 30 40
          * y        (y) int64 70 80 90

        Notes
        -----
        scipy is required.
        If the dataarray has object-type coordinates, reindex is used for these
        coordinates instead of the interpolation.

        See Also
        --------
        DataArray.interp
        DataArray.reindex_like
        rU  rV  rW  )r   rX  r{   rY  r   interp_liker   )r   rD  r>  rS  r  r  rc   rc   rf   r[    s    r   zDataArray.interp_likez(Hashable | Mapping[Any, Hashable] | None)new_name_or_name_dictr	  rb   c                 K  s   |dkr|s| j ddS t|s*|dkrNt||d}|  |}| |S t|r|r|  |}| |}|j |dS | j |dS )a8  Returns a new DataArray with renamed coordinates, dimensions or a new name.

        Parameters
        ----------
        new_name_or_name_dict : str or dict-like, optional
            If the argument is dict-like, it used as a mapping from old
            names to new names for coordinates or dimensions. Otherwise,
            use the argument as the new name for this array.
        **names : Hashable, optional
            The keyword arguments form of a mapping from old names to
            new names for coordinates or dimensions.
            One of new_name_or_name_dict or names must be provided.

        Returns
        -------
        renamed : DataArray
            Renamed array or array with renamed coordinates.

        See Also
        --------
        Dataset.rename
        DataArray.swap_dims
        Nrh   rename)r   r   rp   r8   r   Z_renamer   Zhashable)r   r\  r	  Z	name_dictr   Z	dataarrayrc   rc   rf   r]  	  s    

zDataArray.renamezMapping[Any, Hashable] | None)r   	dims_dictrb   c                 K  s$   t ||d}|  |}| |S )am  Returns a new DataArray with swapped dimensions.

        Parameters
        ----------
        dims_dict : dict-like
            Dictionary whose keys are current dimension names and whose values
            are new names.
        **dims_kwargs : {existing_dim: new_dim, ...}, optional
            The keyword arguments form of ``dims_dict``.
            One of dims_dict or dims_kwargs must be provided.

        Returns
        -------
        swapped : DataArray
            DataArray with swapped dimensions.

        Examples
        --------
        >>> arr = xr.DataArray(
        ...     data=[0, 1],
        ...     dims="x",
        ...     coords={"x": ["a", "b"], "y": ("x", [0, 1])},
        ... )
        >>> arr
        <xarray.DataArray (x: 2)>
        array([0, 1])
        Coordinates:
          * x        (x) <U1 'a' 'b'
            y        (x) int64 0 1

        >>> arr.swap_dims({"x": "y"})
        <xarray.DataArray (y: 2)>
        array([0, 1])
        Coordinates:
            x        (y) <U1 'a' 'b'
          * y        (y) int64 0 1

        >>> arr.swap_dims({"x": "z"})
        <xarray.DataArray (z: 2)>
        array([0, 1])
        Coordinates:
            x        (z) <U1 'a' 'b'
            y        (z) int64 0 1
        Dimensions without coordinates: z

        See Also
        --------
        DataArray.rename
        Dataset.swap_dims
        	swap_dims)r8   r   r_  r   )r   r^  Zdims_kwargsr  rc   rc   rf   r_  A	  s    7zDataArray.swap_dimsz8None | Hashable | Sequence[Hashable] | Mapping[Any, Any]zNone | int | Sequence[int])r   axis
dim_kwargsrb   c                 K  s   t |trtdn^t |trRt |tsRt|tt|krDtdt	|d}n |dk	rrt |t
srtt|di}t||d}|  ||}| |S )aX  Return a new object with an additional axis (or axes) inserted at
        the corresponding position in the array shape. The new object is a
        view into the underlying array, not a copy.

        If dim is already a scalar coordinate, it will be promoted to a 1D
        coordinate consisting of a single value.

        Parameters
        ----------
        dim : Hashable, sequence of Hashable, dict, or None, optional
            Dimensions to include on the new variable.
            If provided as str or sequence of str, then dimensions are inserted
            with length 1. If provided as a dict, then the keys are the new
            dimensions and the values are either integers (giving the length of
            the new dimensions) or sequence/ndarray (giving the coordinates of
            the new dimensions).
        axis : int, sequence of int, or None, default: None
            Axis position(s) where new axis is to be inserted (position(s) on
            the result array). If a sequence of integers is passed,
            multiple axes are inserted. In this case, dim arguments should be
            same length list. If axis=None is passed, all the axes will be
            inserted to the start of the result array.
        **dim_kwargs : int or sequence or ndarray
            The keywords are arbitrary dimensions being inserted and the values
            are either the lengths of the new dims (if int is given), or their
            coordinates. Note, this is an alternative to passing a dict to the
            dim kwarg and will only be used if dim is None.

        Returns
        -------
        expanded : DataArray
            This object, but with additional dimension(s).

        See Also
        --------
        Dataset.expand_dims

        Examples
        --------
        >>> da = xr.DataArray(np.arange(5), dims=("x"))
        >>> da
        <xarray.DataArray (x: 5)>
        array([0, 1, 2, 3, 4])
        Dimensions without coordinates: x

        Add new dimension of length 2:

        >>> da.expand_dims(dim={"y": 2})
        <xarray.DataArray (y: 2, x: 5)>
        array([[0, 1, 2, 3, 4],
               [0, 1, 2, 3, 4]])
        Dimensions without coordinates: y, x

        >>> da.expand_dims(dim={"y": 2}, axis=1)
        <xarray.DataArray (x: 5, y: 2)>
        array([[0, 0],
               [1, 1],
               [2, 2],
               [3, 3],
               [4, 4]])
        Dimensions without coordinates: x, y

        Add a new dimension with coordinates from array:

        >>> da.expand_dims(dim={"y": np.arange(5)}, axis=0)
        <xarray.DataArray (y: 5, x: 5)>
        array([[0, 1, 2, 3, 4],
               [0, 1, 2, 3, 4],
               [0, 1, 2, 3, 4],
               [0, 1, 2, 3, 4],
               [0, 1, 2, 3, 4]])
        Coordinates:
          * y        (y) int64 0 1 2 3 4
        Dimensions without coordinates: x
        z7dim should be Hashable or sequence/mapping of Hashablesz)dims should not contain duplicate values.r   Nexpand_dims)rs   r   r{   r   rt   rq   r   rr   r}   r8  r
   r   r   r8   r   rb  r   )r   r   r`  ra  r  rc   rc   rf   rb  ~	  s    Q

zDataArray.expand_dimsz2Mapping[Any, Hashable | Sequence[Hashable]] | NonezHashable | Sequence[Hashable])r   appendindexes_kwargsrb   c                 K  s$   |   j|fd|i|}| |S )a;  Set DataArray (multi-)indexes using one or more existing
        coordinates.

        This legacy method is limited to pandas (multi-)indexes and
        1-dimensional "dimension" coordinates. See
        :py:meth:`~DataArray.set_xindex` for setting a pandas or a custom
        Xarray-compatible index from one or more arbitrary coordinates.

        Parameters
        ----------
        indexes : {dim: index, ...}
            Mapping from names matching dimensions and values given
            by (lists of) the names of existing coordinates or variables to set
            as new (multi-)index.
        append : bool, default: False
            If True, append the supplied index(es) to the existing index(es).
            Otherwise replace the existing index(es).
        **indexes_kwargs : optional
            The keyword arguments form of ``indexes``.
            One of indexes or indexes_kwargs must be provided.

        Returns
        -------
        obj : DataArray
            Another DataArray, with this data but replaced coordinates.

        Examples
        --------
        >>> arr = xr.DataArray(
        ...     data=np.ones((2, 3)),
        ...     dims=["x", "y"],
        ...     coords={"x": range(2), "y": range(3), "a": ("x", [3, 4])},
        ... )
        >>> arr
        <xarray.DataArray (x: 2, y: 3)>
        array([[1., 1., 1.],
               [1., 1., 1.]])
        Coordinates:
          * x        (x) int64 0 1
          * y        (y) int64 0 1 2
            a        (x) int64 3 4
        >>> arr.set_index(x="a")
        <xarray.DataArray (x: 2, y: 3)>
        array([[1., 1., 1.],
               [1., 1., 1.]])
        Coordinates:
          * x        (x) int64 3 4
          * y        (y) int64 0 1 2

        See Also
        --------
        DataArray.reset_index
        DataArray.set_xindex
        rc  )r   	set_indexr   )r   r   rc  rd  r  rc   rc   rf   re  	  s    <zDataArray.set_index)dims_or_levelsr
  rb   c                 C  s   |   j||d}| |S )a  Reset the specified index(es) or multi-index level(s).

        This legacy method is specific to pandas (multi-)indexes and
        1-dimensional "dimension" coordinates. See the more generic
        :py:meth:`~DataArray.drop_indexes` and :py:meth:`~DataArray.set_xindex`
        method to respectively drop and set pandas or custom indexes for
        arbitrary coordinates.

        Parameters
        ----------
        dims_or_levels : Hashable or sequence of Hashable
            Name(s) of the dimension(s) and/or multi-index level(s) that will
            be reset.
        drop : bool, default: False
            If True, remove the specified indexes and/or multi-index levels
            instead of extracting them as new coordinates (default: False).

        Returns
        -------
        obj : DataArray
            Another dataarray, with this dataarray's data but replaced
            coordinates.

        See Also
        --------
        DataArray.set_index
        DataArray.set_xindex
        DataArray.drop_indexes
        r
  )r   reset_indexr   )r   rf  r
  r  rc   rc   rf   rh  
  s    "zDataArray.reset_indexzstr | Sequence[Hashable]ztype[Index] | None)r   r   	index_clsrb   c                 K  s   |   j||f|}| |S )a  Set a new, Xarray-compatible index from one or more existing
        coordinate(s).

        Parameters
        ----------
        coord_names : str or list
            Name(s) of the coordinate(s) used to build the index.
            If several names are given, their order matters.
        index_cls : subclass of :class:`~xarray.indexes.Index`
            The type of index to create. By default, try setting
            a pandas (multi-)index from the supplied coordinates.
        **options
            Options passed to the index constructor.

        Returns
        -------
        obj : DataArray
            Another dataarray, with this dataarray's data and with a new index.

        )r   
set_xindexr   )r   r   ri  optionsr  rc   rc   rf   rj  D
  s    zDataArray.set_xindexz-Mapping[Any, Sequence[int | Hashable]] | NonezSequence[int | Hashable])r   	dim_orderdim_order_kwargsrb   c                 K  s   |   j|f|}| |S )a  Rearrange index levels using input order.

        Parameters
        ----------
        dim_order dict-like of Hashable to int or Hashable: optional
            Mapping from names matching dimensions and values given
            by lists representing new level orders. Every given dimension
            must have a multi-index.
        **dim_order_kwargs : optional
            The keyword arguments form of ``dim_order``.
            One of dim_order or dim_order_kwargs must be provided.

        Returns
        -------
        obj : DataArray
            Another dataarray, with this dataarray's data but replaced
            coordinates.
        )r   reorder_levelsr   )r   rl  rm  r  rc   rc   rf   rn  a
  s    zDataArray.reorder_levelsz'Mapping[Any, Sequence[Hashable]] | Nonezbool | Noneztype[Index]zSequence[Hashable])r   
dimensionscreate_indexri  dimensions_kwargsrb   c                 K  s&   |   j|f||d|}| |S )a  
        Stack any number of existing dimensions into a single new dimension.

        New dimensions will be added at the end, and the corresponding
        coordinate variables will be combined into a MultiIndex.

        Parameters
        ----------
        dimensions : mapping of Hashable to sequence of Hashable
            Mapping of the form `new_name=(dim1, dim2, ...)`.
            Names of new dimensions, and the existing dimensions that they
            replace. An ellipsis (`...`) will be replaced by all unlisted dimensions.
            Passing a list containing an ellipsis (`stacked_dim=[...]`) will stack over
            all dimensions.
        create_index : bool or None, default: True
            If True, create a multi-index for each of the stacked dimensions.
            If False, don't create any index.
            If None, create a multi-index only if exactly one single (1-d) coordinate
            index is found for every dimension to stack.
        index_cls: class, optional
            Can be used to pass a custom multi-index type. Must be an Xarray index that
            implements `.stack()`. By default, a pandas multi-index wrapper is used.
        **dimensions_kwargs
            The keyword arguments form of ``dimensions``.
            One of dimensions or dimensions_kwargs must be provided.

        Returns
        -------
        stacked : DataArray
            DataArray with stacked data.

        Examples
        --------
        >>> arr = xr.DataArray(
        ...     np.arange(6).reshape(2, 3),
        ...     coords=[("x", ["a", "b"]), ("y", [0, 1, 2])],
        ... )
        >>> arr
        <xarray.DataArray (x: 2, y: 3)>
        array([[0, 1, 2],
               [3, 4, 5]])
        Coordinates:
          * x        (x) <U1 'a' 'b'
          * y        (y) int64 0 1 2
        >>> stacked = arr.stack(z=("x", "y"))
        >>> stacked.indexes["z"]
        MultiIndex([('a', 0),
                    ('a', 1),
                    ('a', 2),
                    ('b', 0),
                    ('b', 1),
                    ('b', 2)],
                   name='z')

        See Also
        --------
        DataArray.unstack
        )rp  ri  )r   stackr   )r   ro  rp  ri  rq  r  rc   rc   rf   rr  {
  s    AzDataArray.stack)r   rK  sparserb   c                 C  s   |   |||}| |S )a  
        Unstack existing dimensions corresponding to MultiIndexes into
        multiple new dimensions.

        New dimensions will be added at the end.

        Parameters
        ----------
        dim : str, Iterable of Hashable or None, optional
            Dimension(s) over which to unstack. By default unstacks all
            MultiIndexes.
        fill_value : scalar or dict-like, default: nan
            Value to be filled. If a dict-like, maps variable names to
            fill values. Use the data array's name to refer to its
            name. If not provided or if the dict-like does not contain
            all variables, the dtype's NA value will be used.
        sparse : bool, default: False
            Use sparse-array if True

        Returns
        -------
        unstacked : DataArray
            Array with unstacked data.

        Examples
        --------
        >>> arr = xr.DataArray(
        ...     np.arange(6).reshape(2, 3),
        ...     coords=[("x", ["a", "b"]), ("y", [0, 1, 2])],
        ... )
        >>> arr
        <xarray.DataArray (x: 2, y: 3)>
        array([[0, 1, 2],
               [3, 4, 5]])
        Coordinates:
          * x        (x) <U1 'a' 'b'
          * y        (y) int64 0 1 2
        >>> stacked = arr.stack(z=("x", "y"))
        >>> stacked.indexes["z"]
        MultiIndex([('a', 0),
                    ('a', 1),
                    ('a', 2),
                    ('b', 0),
                    ('b', 1),
                    ('b', 2)],
                   name='z')
        >>> roundtripped = stacked.unstack()
        >>> arr.identical(roundtripped)
        True

        See Also
        --------
        DataArray.stack
        )r   unstackr   )r   r   rK  rs  r  rc   rc   rf   rt  
  s    <zDataArray.unstackr   zint | Hashable)r   levelrb   c           	      C  s|   | j |  }t|tjs*td| d||}|j| }|j| }i }|D ]"}| j	||iddj
dd||< qPt|S )a  Unstack DataArray expanding to Dataset along a given level of a
        stacked coordinate.

        This is the inverse operation of Dataset.to_stacked_array.

        Parameters
        ----------
        dim : Hashable
            Name of existing dimension to unstack
        level : int or Hashable, default: 0
            The MultiIndex level to expand to a dataset along. Can either be
            the integer index of the level or its name.

        Returns
        -------
        unstacked: Dataset

        Examples
        --------
        >>> arr = xr.DataArray(
        ...     np.arange(6).reshape(2, 3),
        ...     coords=[("x", ["a", "b"]), ("y", [0, 1, 2])],
        ... )
        >>> data = xr.Dataset({"a": arr, "b": arr.isel(y=0)})
        >>> data
        <xarray.Dataset>
        Dimensions:  (x: 2, y: 3)
        Coordinates:
          * x        (x) <U1 'a' 'b'
          * y        (y) int64 0 1 2
        Data variables:
            a        (x, y) int64 0 1 2 3 4 5
            b        (x) int64 0 3
        >>> stacked = data.to_stacked_array("z", ["x"])
        >>> stacked.indexes["z"]
        MultiIndex([('a', 0.0),
                    ('a', 1.0),
                    ('a', 2.0),
                    ('b', nan)],
                   name='z')
        >>> roundtripped = stacked.to_unstacked_dataset(dim="z")
        >>> data.identical(roundtripped)
        True

        See Also
        --------
        Dataset.to_stacked_array
        'z' is not a stacked coordinateTrg  )r   Zto_pandas_indexrs   r   Z
MultiIndexrr   Z_get_level_numberlevelsr	  r   squeezer&   )	r   r   ru  r<  level_numberr   Zvariable_dimZ	data_dictr   rc   rc   rf   to_unstacked_dataset  s    1


 zDataArray.to_unstacked_dataset)transpose_coordsr:  )r   rn   r{  r:  rb   c                  s   |rt t|| j|}| jj| }|rri }| j D ].\} t  fdd|D } jj| ||< q6| ||S | |S dS )aq  Return a new DataArray object with transposed dimensions.

        Parameters
        ----------
        *dims : Hashable, optional
            By default, reverse the dimensions. Otherwise, reorder the
            dimensions to this order.
        transpose_coords : bool, default: True
            If True, also transpose the coordinates of this DataArray.
        missing_dims : {"raise", "warn", "ignore"}, default: "raise"
            What to do if dimensions that should be selected from are not present in the
            DataArray:
            - "raise": raise an exception
            - "warn": raise a warning, and ignore the missing dimensions
            - "ignore": ignore the missing dimensions

        Returns
        -------
        transposed : DataArray
            The returned DataArray's array is transposed.

        Notes
        -----
        This operation returns a view of this array's data. It is
        lazy for dask-backed DataArrays but not for numpy-backed DataArrays
        -- the data will be fully loaded.

        See Also
        --------
        numpy.transpose
        Dataset.transpose
        c                 3  s   | ]}| j kr|V  qd S rj   rm   rd   r   r   rc   rf   ro   r  s     
 z&DataArray.transpose.<locals>.<genexpr>N)	rz   r   Z
infix_dimsrn   r   	transposer   r|   r   )r   r{  r:  rn   r   r   ri   Z
coord_dimsrc   r}  rf   r~  F  s    &zDataArray.transposec                 C  s   |   S rj   )r~  r   rc   rc   rf   Tx  s    zDataArray.TerrorszHashable | Iterable[Hashable]rP   )r	  r  rb   c                C  s   |   j||d}| |S )a  Returns an array with dropped variables.

        Parameters
        ----------
        names : Hashable or iterable of Hashable
            Name(s) of variables to drop.
        errors : {"raise", "ignore"}, default: "raise"
            If 'raise', raises a ValueError error if any of the variable
            passed are not in the dataset. If 'ignore', any given names that are in the
            DataArray are dropped and no error is raised.

        Returns
        -------
        dropped : Dataset
            New Dataset copied from `self` with variables removed.

        Examples
        -------
        >>> data = np.arange(12).reshape(4, 3)
        >>> da = xr.DataArray(
        ...     data=data,
        ...     dims=["x", "y"],
        ...     coords={"x": [10, 20, 30, 40], "y": [70, 80, 90]},
        ... )
        >>> da
        <xarray.DataArray (x: 4, y: 3)>
        array([[ 0,  1,  2],
               [ 3,  4,  5],
               [ 6,  7,  8],
               [ 9, 10, 11]])
        Coordinates:
          * x        (x) int64 10 20 30 40
          * y        (y) int64 70 80 90

        Removing a single variable:

        >>> da.drop_vars("x")
        <xarray.DataArray (x: 4, y: 3)>
        array([[ 0,  1,  2],
               [ 3,  4,  5],
               [ 6,  7,  8],
               [ 9, 10, 11]])
        Coordinates:
          * y        (y) int64 70 80 90
        Dimensions without coordinates: x

        Removing a list of variables:

        >>> da.drop_vars(["x", "y"])
        <xarray.DataArray (x: 4, y: 3)>
        array([[ 0,  1,  2],
               [ 3,  4,  5],
               [ 6,  7,  8],
               [ 9, 10, 11]])
        Dimensions without coordinates: x, y
        r  )r   	drop_varsr   )r   r	  r  r  rc   rc   rf   r  ~  s    >zDataArray.drop_vars)r   r   r  rb   c                C  s   |   j||d}| |S )a;  Drop the indexes assigned to the given coordinates.

        Parameters
        ----------
        coord_names : hashable or iterable of hashable
            Name(s) of the coordinate(s) for which to drop the index.
        errors : {"raise", "ignore"}, default: "raise"
            If 'raise', raises a ValueError error if any of the coordinates
            passed have no index or are not in the dataset.
            If 'ignore', no error is raised.

        Returns
        -------
        dropped : DataArray
            A new dataarray with dropped indexes.
        r  )r   drop_indexesr   )r   r   r  r  rc   rc   rf   r    s    zDataArray.drop_indexes)r   r   r   r  rb   c                K  s&   |   j||fd|i|}| |S )zBackward compatible method based on `drop_vars` and `drop_sel`

        Using either `drop_vars` or `drop_sel` is encouraged

        See Also
        --------
        DataArray.drop_vars
        DataArray.drop_sel
        r  )r   r
  r   )r   r   r   r  labels_kwargsr  rc   rc   rf   r
    s    zDataArray.drop)r   r   r  rb   c                K  s6   |st |trt||d}|  j||d}| |S )a   Drop index labels from this DataArray.

        Parameters
        ----------
        labels : mapping of Hashable to Any
            Index labels to drop
        errors : {"raise", "ignore"}, default: "raise"
            If 'raise', raises a ValueError error if
            any of the index labels passed are not
            in the dataset. If 'ignore', any given labels that are in the
            dataset are dropped and no error is raised.
        **labels_kwargs : {dim: label, ...}, optional
            The keyword arguments form of ``dim`` and ``labels``

        Returns
        -------
        dropped : DataArray

        Examples
        --------
        >>> da = xr.DataArray(
        ...     np.arange(25).reshape(5, 5),
        ...     coords={"x": np.arange(0, 9, 2), "y": np.arange(0, 13, 3)},
        ...     dims=("x", "y"),
        ... )
        >>> da
        <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]])
        Coordinates:
          * x        (x) int64 0 2 4 6 8
          * y        (y) int64 0 3 6 9 12

        >>> da.drop_sel(x=[0, 2], y=9)
        <xarray.DataArray (x: 3, y: 4)>
        array([[10, 11, 12, 14],
               [15, 16, 17, 19],
               [20, 21, 22, 24]])
        Coordinates:
          * x        (x) int64 4 6 8
          * y        (y) int64 0 3 6 12

        >>> da.drop_sel({"x": 6, "y": [0, 3]})
        <xarray.DataArray (x: 4, y: 3)>
        array([[ 2,  3,  4],
               [ 7,  8,  9],
               [12, 13, 14],
               [22, 23, 24]])
        Coordinates:
          * x        (x) int64 0 2 4 8
          * y        (y) int64 6 9 12
        r
  r  )rs   r}   r8   r   drop_selr   )r   r   r  r  r  rc   rc   rf   r    s    >zDataArray.drop_sel)r   r   rb   c                 K  s&   |   }|jf d|i|}| |S )a%  Drop index positions from this DataArray.

        Parameters
        ----------
        indexers : mapping of Hashable to Any or None, default: None
            Index locations to drop
        **indexers_kwargs : {dim: position, ...}, optional
            The keyword arguments form of ``dim`` and ``positions``

        Returns
        -------
        dropped : DataArray

        Raises
        ------
        IndexError

        Examples
        --------
        >>> da = xr.DataArray(np.arange(25).reshape(5, 5), dims=("X", "Y"))
        >>> da
        <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

        >>> da.drop_isel(X=[0, 4], Y=2)
        <xarray.DataArray (X: 3, Y: 4)>
        array([[ 5,  6,  8,  9],
               [10, 11, 13, 14],
               [15, 16, 18, 19]])
        Dimensions without coordinates: X, Y

        >>> da.drop_isel({"X": 3, "Y": 3})
        <xarray.DataArray (X: 4, Y: 4)>
        array([[ 0,  1,  2,  4],
               [ 5,  6,  7,  9],
               [10, 11, 12, 14],
               [20, 21, 22, 24]])
        Dimensions without coordinates: X, Y
        r   )r   	drop_iselr   )r   r   r;  r   rc   rc   rf   r  0  s    /zDataArray.drop_iselr~   zLiteral[('any', 'all')]z
int | None)r   r   howthreshrb   c                 C  s   |   j|||d}| |S )a	  Returns a new array with dropped labels for missing values along
        the provided dimension.

        Parameters
        ----------
        dim : Hashable
            Dimension along which to drop missing values. Dropping along
            multiple dimensions simultaneously is not yet supported.
        how : {"any", "all"}, default: "any"
            - any : if any NA values are present, drop that label
            - all : if all values are NA, drop that label

        thresh : int or None, default: None
            If supplied, require this many non-NA values.

        Returns
        -------
        dropped : DataArray

        Examples
        --------
        >>> temperature = [
        ...     [0, 4, 2, 9],
        ...     [np.nan, np.nan, np.nan, np.nan],
        ...     [np.nan, 4, 2, 0],
        ...     [3, 1, 0, 0],
        ... ]
        >>> da = xr.DataArray(
        ...     data=temperature,
        ...     dims=["Y", "X"],
        ...     coords=dict(
        ...         lat=("Y", np.array([-20.0, -20.25, -20.50, -20.75])),
        ...         lon=("X", np.array([10.0, 10.25, 10.5, 10.75])),
        ...     ),
        ... )
        >>> da
        <xarray.DataArray (Y: 4, X: 4)>
        array([[ 0.,  4.,  2.,  9.],
               [nan, nan, nan, nan],
               [nan,  4.,  2.,  0.],
               [ 3.,  1.,  0.,  0.]])
        Coordinates:
            lat      (Y) float64 -20.0 -20.25 -20.5 -20.75
            lon      (X) float64 10.0 10.25 10.5 10.75
        Dimensions without coordinates: Y, X

        >>> da.dropna(dim="Y", how="any")
        <xarray.DataArray (Y: 2, X: 4)>
        array([[0., 4., 2., 9.],
               [3., 1., 0., 0.]])
        Coordinates:
            lat      (Y) float64 -20.0 -20.75
            lon      (X) float64 10.0 10.25 10.5 10.75
        Dimensions without coordinates: Y, X

        Drop values only if all values along the dimension are NaN:

        >>> da.dropna(dim="Y", how="all")
        <xarray.DataArray (Y: 3, X: 4)>
        array([[ 0.,  4.,  2.,  9.],
               [nan,  4.,  2.,  0.],
               [ 3.,  1.,  0.,  0.]])
        Coordinates:
            lat      (Y) float64 -20.0 -20.5 -20.75
            lon      (X) float64 10.0 10.25 10.5 10.75
        Dimensions without coordinates: Y, X
        )r  r  )r   dropnar   )r   r   r  r  r  rc   rc   rf   r  c  s    IzDataArray.dropna)r   r   rb   c                 C  s"   t |rtdt| |}|S )a  Fill missing values in this object.

        This operation follows the normal broadcasting and alignment rules that
        xarray uses for binary arithmetic, except the result is aligned to this
        object (``join='left'``) instead of aligned to the intersection of
        index coordinates (``join='inner'``).

        Parameters
        ----------
        value : scalar, ndarray or DataArray
            Used to fill all matching missing values in this array. If the
            argument is a DataArray, it is first aligned with (reindexed to)
            this array.

        Returns
        -------
        filled : DataArray

        Examples
        --------
        >>> da = xr.DataArray(
        ...     np.array([1, 4, np.nan, 0, 3, np.nan]),
        ...     dims="Z",
        ...     coords=dict(
        ...         Z=("Z", np.arange(6)),
        ...         height=("Z", np.array([0, 10, 20, 30, 40, 50])),
        ...     ),
        ... )
        >>> da
        <xarray.DataArray (Z: 6)>
        array([ 1.,  4., nan,  0.,  3., nan])
        Coordinates:
          * Z        (Z) int64 0 1 2 3 4 5
            height   (Z) int64 0 10 20 30 40 50

        Fill all NaN values with 0:

        >>> da.fillna(0)
        <xarray.DataArray (Z: 6)>
        array([1., 4., 0., 0., 3., 0.])
        Coordinates:
          * Z        (Z) int64 0 1 2 3 4 5
            height   (Z) int64 0 10 20 30 40 50

        Fill NaN values with corresponding values in array:

        >>> da.fillna(np.array([2, 9, 4, 2, 8, 9]))
        <xarray.DataArray (Z: 6)>
        array([1., 4., 4., 0., 3., 9.])
        Coordinates:
          * Z        (Z) int64 0 1 2 3 4 5
            height   (Z) int64 0 10 20 30 40 50
        zDcannot provide fill value as a dictionary with fillna on a DataArray)r   rp   r{   r   fillna)r   r   outrc   rc   rf   r    s    6
zDataArray.fillnaz
bool | strzMNone | int | float | str | pd.Timedelta | np.timedelta64 | datetime.timedelta)	r   r   r>  limituse_coordinatemax_gap
keep_attrsr  rb   c           	   	   K  s*   ddl m} || f||||||d|S )a  Fill in NaNs by interpolating according to different methods.

        Parameters
        ----------
        dim : Hashable or None, optional
            Specifies the dimension along which to interpolate.
        method : {"linear", "nearest", "zero", "slinear", "quadratic", "cubic", "polynomial",             "barycentric", "krog", "pchip", "spline", "akima"}, default: "linear"
            String indicating which method to use for interpolation:

            - 'linear': linear interpolation. Additional keyword
              arguments are passed to :py:func:`numpy.interp`
            - 'nearest', 'zero', 'slinear', 'quadratic', 'cubic', 'polynomial':
              are passed to :py:func:`scipy.interpolate.interp1d`. If
              ``method='polynomial'``, the ``order`` keyword argument must also be
              provided.
            - 'barycentric', 'krog', 'pchip', 'spline', 'akima': use their
              respective :py:class:`scipy.interpolate` classes.

        use_coordinate : bool or str, default: True
            Specifies which index to use as the x values in the interpolation
            formulated as `y = f(x)`. If False, values are treated as if
            eqaully-spaced along ``dim``. If True, the IndexVariable `dim` is
            used. If ``use_coordinate`` is a string, it specifies the name of a
            coordinate variariable to use as the index.
        limit : int or None, default: None
            Maximum number of consecutive NaNs to fill. Must be greater than 0
            or None for no limit. This filling is done regardless of the size of
            the gap in the data. To only interpolate over gaps less than a given length,
            see ``max_gap``.
        max_gap : int, float, str, pandas.Timedelta, numpy.timedelta64, datetime.timedelta, default: None
            Maximum size of gap, a continuous sequence of NaNs, that will be filled.
            Use None for no limit. When interpolating along a datetime64 dimension
            and ``use_coordinate=True``, ``max_gap`` can be one of the following:

            - a string that is valid input for pandas.to_timedelta
            - a :py:class:`numpy.timedelta64` object
            - a :py:class:`pandas.Timedelta` object
            - a :py:class:`datetime.timedelta` object

            Otherwise, ``max_gap`` must be an int or a float. Use of ``max_gap`` with unlabeled
            dimensions has not been implemented yet. Gap length is defined as the difference
            between coordinate values at the first data point after a gap and the last value
            before a gap. For gaps at the beginning (end), gap length is defined as the difference
            between coordinate values at the first (last) valid data point and the first (last) NaN.
            For example, consider::

                <xarray.DataArray (x: 9)>
                array([nan, nan, nan,  1., nan, nan,  4., nan, nan])
                Coordinates:
                  * x        (x) int64 0 1 2 3 4 5 6 7 8

            The gap lengths are 3-0 = 3; 6-3 = 3; and 8-6 = 2 respectively
        keep_attrs : bool or None, default: None
            If True, the dataarray's attributes (`attrs`) will be copied from
            the original object to the new one.  If False, the new
            object will be returned without attributes.
        **kwargs : dict, optional
            parameters passed verbatim to the underlying interpolation function

        Returns
        -------
        interpolated: DataArray
            Filled in DataArray.

        See Also
        --------
        numpy.interp
        scipy.interpolate

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

        >>> da.interpolate_na(dim="x", method="linear")
        <xarray.DataArray (x: 5)>
        array([nan, 2. , 3. , 1.5, 0. ])
        Coordinates:
          * x        (x) int64 0 1 2 3 4

        >>> da.interpolate_na(dim="x", method="linear", fill_value="extrapolate")
        <xarray.DataArray (x: 5)>
        array([1. , 2. , 3. , 1.5, 0. ])
        Coordinates:
          * x        (x) int64 0 1 2 3 4
        r   )	interp_na)r   r>  r  r  r  r  )xarray.core.missingr  )	r   r   r>  r  r  r  r  r  r  rc   rc   rf   interpolate_na  s    ozDataArray.interpolate_na)r   r   r  rb   c                 C  s   ddl m} || ||dS )ae
  Fill NaN values by propagating values forward

        *Requires bottleneck.*

        Parameters
        ----------
        dim : Hashable
            Specifies the dimension along which to propagate values when
            filling.
        limit : int or None, default: None
            The maximum number of consecutive NaN values to forward fill. In
            other words, if there is a gap with more than this number of
            consecutive NaNs, it will only be partially filled. Must be greater
            than 0 or None for no limit. Must be None or greater than or equal
            to axis length if filling along chunked axes (dimensions).

        Returns
        -------
        filled : DataArray

        Examples
        --------
        >>> temperature = np.array(
        ...     [
        ...         [np.nan, 1, 3],
        ...         [0, np.nan, 5],
        ...         [5, np.nan, np.nan],
        ...         [3, np.nan, np.nan],
        ...         [0, 2, 0],
        ...     ]
        ... )
        >>> da = xr.DataArray(
        ...     data=temperature,
        ...     dims=["Y", "X"],
        ...     coords=dict(
        ...         lat=("Y", np.array([-20.0, -20.25, -20.50, -20.75, -21.0])),
        ...         lon=("X", np.array([10.0, 10.25, 10.5])),
        ...     ),
        ... )
        >>> da
        <xarray.DataArray (Y: 5, X: 3)>
        array([[nan,  1.,  3.],
               [ 0., nan,  5.],
               [ 5., nan, nan],
               [ 3., nan, nan],
               [ 0.,  2.,  0.]])
        Coordinates:
            lat      (Y) float64 -20.0 -20.25 -20.5 -20.75 -21.0
            lon      (X) float64 10.0 10.25 10.5
        Dimensions without coordinates: Y, X

        Fill all NaN values:

        >>> da.ffill(dim="Y", limit=None)
        <xarray.DataArray (Y: 5, X: 3)>
        array([[nan,  1.,  3.],
               [ 0.,  1.,  5.],
               [ 5.,  1.,  5.],
               [ 3.,  1.,  5.],
               [ 0.,  2.,  0.]])
        Coordinates:
            lat      (Y) float64 -20.0 -20.25 -20.5 -20.75 -21.0
            lon      (X) float64 10.0 10.25 10.5
        Dimensions without coordinates: Y, X

        Fill only the first of consecutive NaN values:

        >>> da.ffill(dim="Y", limit=1)
        <xarray.DataArray (Y: 5, X: 3)>
        array([[nan,  1.,  3.],
               [ 0.,  1.,  5.],
               [ 5., nan,  5.],
               [ 3., nan, nan],
               [ 0.,  2.,  0.]])
        Coordinates:
            lat      (Y) float64 -20.0 -20.25 -20.5 -20.75 -21.0
            lon      (X) float64 10.0 10.25 10.5
        Dimensions without coordinates: Y, X
        r   )ffillr  )r  r  )r   r   r  r  rc   rc   rf   r  i  s    RzDataArray.ffillc                 C  s   ddl m} || ||dS )ab
  Fill NaN values by propagating values backward

        *Requires bottleneck.*

        Parameters
        ----------
        dim : str
            Specifies the dimension along which to propagate values when
            filling.
        limit : int or None, default: None
            The maximum number of consecutive NaN values to backward fill. In
            other words, if there is a gap with more than this number of
            consecutive NaNs, it will only be partially filled. Must be greater
            than 0 or None for no limit. Must be None or greater than or equal
            to axis length if filling along chunked axes (dimensions).

        Returns
        -------
        filled : DataArray

        Examples
        --------
        >>> temperature = np.array(
        ...     [
        ...         [0, 1, 3],
        ...         [0, np.nan, 5],
        ...         [5, np.nan, np.nan],
        ...         [3, np.nan, np.nan],
        ...         [np.nan, 2, 0],
        ...     ]
        ... )
        >>> da = xr.DataArray(
        ...     data=temperature,
        ...     dims=["Y", "X"],
        ...     coords=dict(
        ...         lat=("Y", np.array([-20.0, -20.25, -20.50, -20.75, -21.0])),
        ...         lon=("X", np.array([10.0, 10.25, 10.5])),
        ...     ),
        ... )
        >>> da
        <xarray.DataArray (Y: 5, X: 3)>
        array([[ 0.,  1.,  3.],
               [ 0., nan,  5.],
               [ 5., nan, nan],
               [ 3., nan, nan],
               [nan,  2.,  0.]])
        Coordinates:
            lat      (Y) float64 -20.0 -20.25 -20.5 -20.75 -21.0
            lon      (X) float64 10.0 10.25 10.5
        Dimensions without coordinates: Y, X

        Fill all NaN values:

        >>> da.bfill(dim="Y", limit=None)
        <xarray.DataArray (Y: 5, X: 3)>
        array([[ 0.,  1.,  3.],
               [ 0.,  2.,  5.],
               [ 5.,  2.,  0.],
               [ 3.,  2.,  0.],
               [nan,  2.,  0.]])
        Coordinates:
            lat      (Y) float64 -20.0 -20.25 -20.5 -20.75 -21.0
            lon      (X) float64 10.0 10.25 10.5
        Dimensions without coordinates: Y, X

        Fill only the first of consecutive NaN values:

        >>> da.bfill(dim="Y", limit=1)
        <xarray.DataArray (Y: 5, X: 3)>
        array([[ 0.,  1.,  3.],
               [ 0., nan,  5.],
               [ 5., nan, nan],
               [ 3.,  2.,  0.],
               [nan,  2.,  0.]])
        Coordinates:
            lat      (Y) float64 -20.0 -20.25 -20.5 -20.75 -21.0
            lon      (X) float64 10.0 10.25 10.5
        Dimensions without coordinates: Y, X
        r   )bfillr  )r  r  )r   r   r  r  rc   rc   rf   r    s    RzDataArray.bfill)r   rD  rb   c                 C  s   t j| |ddS )a  Combine two DataArray objects, with union of coordinates.

        This operation follows the normal broadcasting and alignment rules of
        ``join='outer'``.  Default to non-null values of array calling the
        method.  Use np.nan to fill in vacant cells after alignment.

        Parameters
        ----------
        other : DataArray
            Used to fill all matching missing values in this array.

        Returns
        -------
        DataArray
        rF  )rG  )r   r  r   rD  rc   rc   rf   combine_first  s    zDataArray.combine_first)r`  r  keepdimszCallable[..., Any]zint | Sequence[int] | None)r   r  r   r`  r  r  r  rb   c                K  s"   | j j|||||f|}| |S )a6  Reduce this array by applying `func` along some dimension(s).

        Parameters
        ----------
        func : callable
            Function which can be called in the form
            `f(x, axis=axis, **kwargs)` to return the result of reducing an
            np.ndarray over an integer valued axis.
        dim : "...", str, Iterable of Hashable or None, optional
            Dimension(s) over which to apply `func`. By default `func` is
            applied over all dimensions.
        axis : int or sequence of int, optional
            Axis(es) over which to repeatedly apply `func`. Only one of the
            'dim' and 'axis' arguments can be supplied. If neither are
            supplied, then the reduction is calculated over the flattened array
            (by calling `f(x)` without an axis argument).
        keep_attrs : bool or None, optional
            If True, the variable's attributes (`attrs`) will be copied from
            the original object to the new one.  If False (default), the new
            object will be returned without attributes.
        keepdims : bool, default: False
            If True, the dimensions which are reduced are left in the result
            as dimensions of size one. Coordinates that use these dimensions
            are removed.
        **kwargs : dict
            Additional keyword arguments passed on to `func`.

        Returns
        -------
        reduced : DataArray
            DataArray with this object's array replaced with an array with
            summarized data and the indicated dimension(s) removed.
        )r   reducer   )r   r  r   r`  r  r  r  r   rc   rc   rf   r  '  s    ,zDataArray.reducez$DataArray | pd.Series | pd.DataFramec                   sn   dd t jt jd}z| j }W n& tk
rH   td j dY nX  fdd jD }| jf| S )a  Convert this array into a pandas object with the same shape.

        The type of the returned object depends on the number of DataArray
        dimensions:

        * 0D -> `xarray.DataArray`
        * 1D -> `pandas.Series`
        * 2D -> `pandas.DataFrame`

        Only works for arrays with 2 or fewer dimensions.

        The DataArray constructor performs the inverse transformation.

        Returns
        -------
        result : DataArray | Series | DataFrame
            DataArray, pandas Series or pandas DataFrame.
        c                 S  s   | S rj   rc   )xrc   rc   rf   <lambda>k      z%DataArray.to_pandas.<locals>.<lambda>)r   r      zCannot convert arrays with z@ dimensions into pandas objects. Requires 2 or fewer dimensions.c                   s   g | ]}  |qS rc   )r   r|  r   rc   rf   rg   s  s     z'DataArray.to_pandas.<locals>.<listcomp>)r   r   r   r   r   rr   rn   r   )r   constructorsconstructorr   rc   r   rf   	to_pandasV  s    
zDataArray.to_pandaszSequence[Hashable] | Nonezpd.DataFrame)ri   rl  rb   c                   s    dkr| j   dkrtd| jdkr0tdd| jd}|dkr\tt| j| j}n|j|d}|	|} fdd	|j
D |_
|S )
ai  Convert this array and its coordinates into a tidy pandas.DataFrame.

        The DataFrame is indexed by the Cartesian product of index coordinates
        (in the form of a :py:class:`pandas.MultiIndex`). Other coordinates are
        included as columns in the DataFrame.

        For 1D and 2D DataArrays, see also :py:func:`DataArray.to_pandas` which
        doesn't rely on a MultiIndex to build the DataFrame.

        Parameters
        ----------
        name: Hashable or None, optional
            Name to give to this array (required if unnamed).
        dim_order: Sequence of Hashable or None, optional
            Hierarchical dimension order for the resulting dataframe.
            Array content is transposed to this order and then written out as flat
            vectors in contiguous order, so the last dimension in this list
            will be contiguous in the resulting DataFrame. This has a major
            influence on which operations are efficient on the resulting
            dataframe.

            If provided, must include all dimensions of this DataArray. By default,
            dimensions are sorted according to the DataArray dimensions order.

        Returns
        -------
        result: DataFrame
            DataArray as a pandas DataFrame.

        See also
        --------
        DataArray.to_pandas
        DataArray.to_series
        NzNcannot convert an unnamed DataArray to a DataFrame: use the ``name`` parameterr   z&cannot convert a scalar to a DataFrameZ,__unique_name_identifier_z98xfz98xugfg73ho__rh   )rl  c                   s   g | ]}|kr n|qS rc   rc   r)  ri   Zunique_namerc   rf   rg     s     z*DataArray.to_dataframe.<locals>.<listcomp>)ri   rr   r   r   r}   ry   rn   r   Z_normalize_dim_orderZ_to_dataframer   )r   ri   rl  r  Zordered_dimsdfrc   r  rf   to_dataframev  s     %

zDataArray.to_dataframez	pd.Seriesc                 C  s$   | j  }tj| jd|| jdS )ay  Convert this array into a pandas.Series.

        The Series is indexed by the Cartesian product of index coordinates
        (in the form of a :py:class:`pandas.MultiIndex`).

        Returns
        -------
        result : Series
            DataArray as a pandas Series.

        See also
        --------
        DataArray.to_pandas
        DataArray.to_dataframe
        )r   ri   )r   r   r   r   r   Zreshaperi   )r   r   rc   rc   rf   	to_series  s    
zDataArray.to_seriesznp.ma.MaskedArray)r   rb   c                 C  s$   |   }t|}tjj|||dS )a  Convert this array into a numpy.ma.MaskedArray

        Parameters
        ----------
        copy : bool, default: True
            If True make a copy of the array in the result. If False,
            a MaskedArray view of DataArray.values is returned.

        Returns
        -------
        result : MaskedArray
            Masked where invalid values (nan or inf) occur.
        )r   maskr   )r   r   isnullr   maZMaskedArray)r   r   r   r  rc   rc   rf   to_masked_array  s    
zDataArray.to_masked_arraywzLiteral[('w', 'a')]zT_NetcdfTypes | NonezT_NetcdfEngine | Nonez+Mapping[Hashable, Mapping[str, Any]] | Nonebytes)
pathmoderY  groupenginer  unlimited_dimsr  invalid_netcdfrb   c
           
      C  s   d S rj   rc   
r   r  r  rY  r  r  r  r  r  r  rc   rc   rf   	to_netcdf  s    zDataArray.to_netcdfzstr | PathLikec
           
      C  s   d S rj   rc   r  rc   rc   rf   r    s    )r  rB   c          
      C  s   d S rj   rc   r  rc   rc   rf   r    s    zstr | PathLike | Nonezbytes | Delayed | Nonec
                 C  s   ddl m}
m}m} | jdkr,| j|d}n:| j| jksD| j| jkr^| j|d}| j|j|
< n|  }||||||||||d|	dS )a  Write dataset contents to a netCDF file.

        Parameters
        ----------
        path : str, path-like or None, optional
            Path to which to save this dataset. File-like objects are only
            supported by the scipy engine. If no path is provided, this
            function returns the resulting netCDF file as bytes; in this case,
            we need to use scipy, which does not support netCDF version 4 (the
            default format becomes NETCDF3_64BIT).
        mode : {"w", "a"}, default: "w"
            Write ('w') or append ('a') mode. If mode='w', any existing file at
            this location will be overwritten. If mode='a', existing variables
            will be overwritten.
        format : {"NETCDF4", "NETCDF4_CLASSIC", "NETCDF3_64BIT",                   "NETCDF3_CLASSIC"}, optional
            File format for the resulting netCDF file:

            * NETCDF4: Data is stored in an HDF5 file, using netCDF4 API
              features.
            * NETCDF4_CLASSIC: Data is stored in an HDF5 file, using only
              netCDF 3 compatible API features.
            * NETCDF3_64BIT: 64-bit offset version of the netCDF 3 file format,
              which fully supports 2+ GB files, but is only compatible with
              clients linked against netCDF version 3.6.0 or later.
            * NETCDF3_CLASSIC: The classic netCDF 3 file format. It does not
              handle 2+ GB files very well.

            All formats are supported by the netCDF4-python library.
            scipy.io.netcdf only supports the last two formats.

            The default format is NETCDF4 if you are saving a file to disk and
            have the netCDF4-python library available. Otherwise, xarray falls
            back to using scipy to write netCDF files and defaults to the
            NETCDF3_64BIT format (scipy does not support netCDF4).
        group : str, optional
            Path to the netCDF4 group in the given file to open (only works for
            format='NETCDF4'). The group(s) will be created if necessary.
        engine : {"netcdf4", "scipy", "h5netcdf"}, optional
            Engine to use when writing netCDF files. If not provided, the
            default engine is chosen based on available dependencies, with a
            preference for 'netcdf4' if writing to a file on disk.
        encoding : dict, optional
            Nested dictionary with variable names as keys and dictionaries of
            variable specific encodings as values, e.g.,
            ``{"my_variable": {"dtype": "int16", "scale_factor": 0.1,
            "zlib": True}, ...}``

            The `h5netcdf` engine supports both the NetCDF4-style compression
            encoding parameters ``{"zlib": True, "complevel": 9}`` and the h5py
            ones ``{"compression": "gzip", "compression_opts": 9}``.
            This allows using any compression plugin installed in the HDF5
            library, e.g. LZF.

        unlimited_dims : iterable of Hashable, optional
            Dimension(s) that should be serialized as unlimited dimensions.
            By default, no dimensions are treated as unlimited dimensions.
            Note that unlimited_dims may also be set via
            ``dataset.encoding["unlimited_dims"]``.
        compute: bool, default: True
            If true compute immediately, otherwise return a
            ``dask.delayed.Delayed`` object that can be computed later.
        invalid_netcdf: bool, default: False
            Only valid along with ``engine="h5netcdf"``. If True, allow writing
            hdf5 files which are invalid netcdf as described in
            https://github.com/h5netcdf/h5netcdf.

        Returns
        -------
        store: bytes or Delayed or None
            * ``bytes`` if path is None
            * ``dask.delayed.Delayed`` if compute is False
            * None otherwise

        Notes
        -----
        Only xarray.Dataset objects can be written to netCDF files, so
        the xarray.DataArray is converted to a xarray.Dataset object
        containing a single variable. If the DataArray has no name, or if the
        name is the same as a coordinate name, then it is given the name
        ``"__xarray_dataarray_variable__"``.

        See Also
        --------
        Dataset.to_netcdf
        r   )DATAARRAY_NAMEDATAARRAY_VARIABLEr  Nrh   F)	r  rY  r  r  r  r  r  Z	multifiler  )	xarray.backends.apir  r  r  ri   r   r   rn   r   )r   r  r  rY  r  r  r  r  r  r  r  r  r  r   rc   rc   rf   r    s(    b
)r   r  rb   c                 C  s`   | j j|d}|i | jd | j D ]\}}|j j|d|d |< q*|r\t| j|d< |S )a  
        Convert this xarray.DataArray into a dictionary following xarray
        naming conventions.

        Converts all variables and attributes to native Python objects.
        Useful for converting to json. To avoid datetime incompatibility
        use decode_times=False kwarg in xarray.open_dataset.

        Parameters
        ----------
        data : bool, default: True
            Whether to include the actual data in the dictionary. When set to
            False, returns just the schema.
        encoding : bool, default: False
            Whether to include the Dataset's encoding in the dictionary.

        Returns
        -------
        dict: dict

        See Also
        --------
        DataArray.from_dict
        Dataset.to_dict
        r  )r   ri   r   r  )r   to_dictr   ri   r   r|   r}   r  )r   r   r  rl   r   r   rc   rc   rf   r    s    zDataArray.to_dictzMapping[str, Any])r   rl   rb   c              
   C  s   d}d|krdzdd |d   D }W n< tk
rb } ztdjt|jd dW 5 d}~X Y nX z|d }W n tk
r   td	Y n$X | |||d
|d|d}|j|di  |S )aq  Convert a dictionary into an xarray.DataArray

        Parameters
        ----------
        d : dict
            Mapping with a minimum structure of {"dims": [...], "data": [...]}

        Returns
        -------
        obj : xarray.DataArray

        See Also
        --------
        DataArray.to_dict
        Dataset.from_dict

        Examples
        --------
        >>> d = {"dims": "t", "data": [1, 2, 3]}
        >>> da = xr.DataArray.from_dict(d)
        >>> da
        <xarray.DataArray (t: 3)>
        array([1, 2, 3])
        Dimensions without coordinates: t

        >>> d = {
        ...     "coords": {
        ...         "t": {"dims": "t", "data": [0, 1, 2], "attrs": {"units": "s"}}
        ...     },
        ...     "attrs": {"title": "air temperature"},
        ...     "dims": "t",
        ...     "data": [10, 20, 30],
        ...     "name": "a",
        ... }
        >>> da = xr.DataArray.from_dict(d)
        >>> da
        <xarray.DataArray 'a' (t: 3)>
        array([10, 20, 30])
        Coordinates:
          * t        (t) int64 0 1 2
        Attributes:
            title:    air temperature
        Nr   c                 S  s*   i | ]"\}}||d  |d | dfqS )rn   r   r   r   r   rc   rc   rf   r     s    z'DataArray.from_dict.<locals>.<dictcomp>zAcannot convert dict when coords are missing the key '{dims_data}'r   )Z	dims_datar   z+cannot convert dict without the key 'data''rn   ri   r   r  )	r|   r   rr   rY  rt   r  r   r  r   )r   rl   r   er   r   rc   rc   rf   	from_dict  s&    -

"zDataArray.from_dict)seriesrs  rb   c                 C  s:   d}t ||i}tj||d}tt|| }|j|_|S )a  Convert a pandas.Series into an xarray.DataArray.

        If the series's index is a MultiIndex, it will be expanded into a
        tensor product of one-dimensional coordinates (filling in missing
        values with NaN). Thus this operation should be the inverse of the
        `to_series` method.

        Parameters
        ----------
        series : Series
            Pandas Series object to convert.
        sparse : bool, default: False
            If sparse=True, creates a sparse array instead of a dense NumPy array.
            Requires the pydata/sparse package.

        See Also
        --------
        DataArray.to_series
        Dataset.from_dataframe
        Z__temporary_name)rs  )r   r   r&   Zfrom_dataframer   r_   ri   )r   r  rs  Z	temp_namer  r  r   rc   rc   rf   from_series  s    zDataArray.from_seriescdms2_Variablec                 C  s   ddl m} || S )z(Convert this array into a cdms2.Variabler   )to_cdms2)xarray.convertr  )r   r  rc   rc   rf   r    s    zDataArray.to_cdms2)r   rb   c                 C  s   ddl m} ||S )z1Convert a cdms2.Variable into an xarray.DataArrayr   )
from_cdms2)r  r  )r   r   r  rc   rc   rf   r    s    zDataArray.from_cdms2	iris_Cubec                 C  s   ddl m} || S )z(Convert this array into a iris.cube.Cuber   )to_iris)r  r  )r   r  rc   rc   rf   r    s    zDataArray.to_iris)cuberb   c                 C  s   ddl m} ||S )z1Convert a iris.cube.Cube into an xarray.DataArrayr   )	from_iris)r  r  )r   r  r  rc   rc   rf   r     s    zDataArray.from_iris)r   rD  
compat_strrb   c                   s*    fdd}t j| j|j|do(|| |S )z;Helper function for equals, broadcast_equals, and identicalc                   s   t | j |jS rj   )r   r   )r  yr  rc   rf   compat*  s    z%DataArray._all_compat.<locals>.compat)r  )r   Z
dict_equivr   )r   rD  r  r  rc   r  rf   _all_compat'  s
     zDataArray._all_compatc              	   C  s.   z|  |dW S  ttfk
r(   Y dS X dS )a  Two DataArrays are broadcast equal if they are equal after
        broadcasting them against each other such that they have the same
        dimensions.

        Parameters
        ----------
        other : DataArray
            DataArray to compare to.

        Returns
        ----------
        equal : bool
            True if the two DataArrays are broadcast equal.

        See Also
        --------
        DataArray.equals
        DataArray.identical

        Examples
        --------
        >>> a = xr.DataArray([1, 2], dims="X")
        >>> b = xr.DataArray([[1, 1], [2, 2]], dims=["X", "Y"])
        >>> a
        <xarray.DataArray (X: 2)>
        array([1, 2])
        Dimensions without coordinates: X
        >>> b
        <xarray.DataArray (X: 2, Y: 2)>
        array([[1, 1],
               [2, 2]])
        Dimensions without coordinates: X, Y

        .equals returns True if two DataArrays have the same values, dimensions, and coordinates. .broadcast_equals returns True if the results of broadcasting two DataArrays against eachother have the same values, dimensions, and coordinates.

        >>> a.equals(b)
        False
        >>> a2, b2 = xr.broadcast(a, b)
        >>> a2.equals(b2)
        True
        >>> a.broadcast_equals(b)
        True
        broadcast_equalsFNr  r{   r   r  rc   rc   rf   r  1  s    ,zDataArray.broadcast_equalsc              	   C  s.   z|  |dW S  ttfk
r(   Y dS X dS )a  True if two DataArrays have the same dimensions, coordinates and
        values; otherwise False.

        DataArrays can still be equal (like pandas objects) if they have NaN
        values in the same locations.

        This method is necessary because `v1 == v2` for ``DataArray``
        does element-wise comparisons (like numpy.ndarrays).

        Parameters
        ----------
        other : DataArray
            DataArray to compare to.

        Returns
        ----------
        equal : bool
            True if the two DataArrays are equal.

        See Also
        --------
        DataArray.broadcast_equals
        DataArray.identical

        Examples
        --------
        >>> a = xr.DataArray([1, 2, 3], dims="X")
        >>> b = xr.DataArray([1, 2, 3], dims="X", attrs=dict(units="m"))
        >>> c = xr.DataArray([1, 2, 3], dims="Y")
        >>> d = xr.DataArray([3, 2, 1], dims="X")
        >>> a
        <xarray.DataArray (X: 3)>
        array([1, 2, 3])
        Dimensions without coordinates: X
        >>> b
        <xarray.DataArray (X: 3)>
        array([1, 2, 3])
        Dimensions without coordinates: X
        Attributes:
            units:    m
        >>> c
        <xarray.DataArray (Y: 3)>
        array([1, 2, 3])
        Dimensions without coordinates: Y
        >>> d
        <xarray.DataArray (X: 3)>
        array([3, 2, 1])
        Dimensions without coordinates: X

        >>> a.equals(b)
        True
        >>> a.equals(c)
        False
        >>> a.equals(d)
        False
        equalsFNr  r  rc   rc   rf   r  b  s    9zDataArray.equalsc              	   C  s:   z| j |j ko| |dW S  ttfk
r4   Y dS X dS )a_  Like equals, but also checks the array name and attributes, and
        attributes on all coordinates.

        Parameters
        ----------
        other : DataArray
            DataArray to compare to.

        Returns
        ----------
        equal : bool
            True if the two DataArrays are identical.

        See Also
        --------
        DataArray.broadcast_equals
        DataArray.equals

        Examples
        --------
        >>> a = xr.DataArray([1, 2, 3], dims="X", attrs=dict(units="m"), name="Width")
        >>> b = xr.DataArray([1, 2, 3], dims="X", attrs=dict(units="m"), name="Width")
        >>> c = xr.DataArray([1, 2, 3], dims="X", attrs=dict(units="ft"), name="Width")
        >>> a
        <xarray.DataArray 'Width' (X: 3)>
        array([1, 2, 3])
        Dimensions without coordinates: X
        Attributes:
            units:    m
        >>> b
        <xarray.DataArray 'Width' (X: 3)>
        array([1, 2, 3])
        Dimensions without coordinates: X
        Attributes:
            units:    m
        >>> c
        <xarray.DataArray 'Width' (X: 3)>
        array([1, 2, 3])
        Dimensions without coordinates: X
        Attributes:
            units:    ft

        >>> a.equals(b)
        True
        >>> a.identical(b)
        True

        >>> a.equals(c)
        True
        >>> a.identical(c)
        False
        	identicalFN)ri   r  r{   r   r  rc   rc   rf   r    s    5zDataArray.identical)rD  rb   c                 C  s,   t |dt}|tks|| jkr$| jS d S d S )Nri   )r   r7   ri   )r   rD  Z
other_namerc   rc   rf   _result_name  s    zDataArray._result_namec                 C  s   | j ||}| |S rj   )r   __array_wrap__r   )r   r   contextZnew_varrc   rc   rf   r    s    zDataArray.__array_wrap__)r   r   rb   c                 C  s
   |  |S rj   )dot)r   r   rc   rc   rf   
__matmul__  s    zDataArray.__matmul__c                 C  s   t || S rj   )r   r  r  rc   rc   rf   __rmatmul__  s    zDataArray.__rmatmul__r   )r   frb   c              
   O  s   | dd }|d krtdd}t l tdd tjddtd tjdd  | || j	j
f||}W 5 Q R X |r| j|_|W  5 Q R  S Q R X d S )	Nr  T)defaultignorez All-NaN (slice|axis) encounteredzMean of empty slicer1  )all)r   r3   r4  catch_warningsfilterwarningsRuntimeWarningr   Zerrstater  r   r   r   )r   r  r  r  r  darc   rc   rf   	_unary_op  s    

  $zDataArray._unary_op)r   rD  r  	reflexiverb   c                 C  s   ddl m} t|t|frtS t|trDtd }t| ||dd\} }t|d|}t|dd }|sl|| j	|n
||| j	}| j
||\}	}
| |}| j||	||
dS )	Nr   GroupByZarithmetic_joinF)rG  r   r   r   r   )xarray.core.groupbyr  rs   r&   NotImplementedr_   r2   r   r   r   r   Z
_merge_rawr  r   )r   rD  r  r  r  Z
align_typeother_variableother_coordsr   r   r   ri   rc   rc   rf   
_binary_op  s    


zDataArray._binary_op)r   rD  r  rb   c              
   C  s   ddl m} t||rtdt|dd }t|d|}z(| j| || j| W 5 Q R X W n, tk
r } ztd|W 5 d }~X Y nX | S )Nr   r  zNin-place operations between a DataArray and a grouped object are not permittedr   r   zAutomatic alignment is not supported for in-place operations.
Consider aligning the indices manually or using a not-in-place operation.
See https://github.com/pydata/xarray/issues/3910 for more explanations.)	r  r  rs   r{   r   r   Z_merge_inplacer   r0   )r   rD  r  r  r  r  excrc   rc   rf   _inplace_binary_op  s"    
zDataArray._inplace_binary_opzDataArray | Dataset | Variablec                 C  s   |j | _ d S rj   )r   r  rc   rc   rf   _copy_attrs_from1  s    zDataArray._copy_attrs_from2   )truncaterb   c                 C  sp   g }| j  D ]2\}}|jdkr|dj|t|jt|d qd|}t	||krl|d|d  d }|S )a`  
        If the dataarray has 1 dimensional coordinates or comes from a slice
        we can show that info in the title

        Parameters
        ----------
        truncate : int, default: 50
            maximum number of characters for title

        Returns
        -------
        title : string
            Can be used for plot titles

        r   z{dim} = {v}{unit})r   r   unitz, N   z...)
r   r|   r   rc  rY  r'   r   r>   rG  rq   )r   r  Zone_dimsr   r   titlerc   rc   rf   _title_for_slice6  s    

zDataArray._title_for_slicer   upperzLiteral[('upper', 'lower')])r   r   re   r   rb   c                 C  s   |   j|||d}| |S )a  Calculate the n-th order discrete difference along given axis.

        Parameters
        ----------
        dim : Hashable
            Dimension over which to calculate the finite difference.
        n : int, default: 1
            The number of times values are differenced.
        label : {"upper", "lower"}, default: "upper"
            The new coordinate in dimension ``dim`` will have the
            values of either the minuend's or subtrahend's coordinate
            for values 'upper' and 'lower', respectively.

        Returns
        -------
        difference : DataArray
            The n-th order finite difference of this object.

        Notes
        -----
        `n` matches numpy's behavior and is different from pandas' first argument named
        `periods`.

        Examples
        --------
        >>> arr = xr.DataArray([5, 5, 6, 6], [[1, 2, 3, 4]], ["x"])
        >>> arr.diff("x")
        <xarray.DataArray (x: 3)>
        array([0, 1, 0])
        Coordinates:
          * x        (x) int64 2 3 4
        >>> arr.diff("x", 2)
        <xarray.DataArray (x: 2)>
        array([ 1, -1])
        Coordinates:
          * x        (x) int64 3 4

        See Also
        --------
        DataArray.differentiate
        )re   r   r   )r   diffr   )r   r   re   r   r  rc   rc   rf   r  W  s    /zDataArray.diffzMapping[Any, int] | None)r   shiftsrK  shifts_kwargsrb   c                 K  s$   | j jf ||d|}| j|dS )a!  Shift this DataArray by an offset along one or more dimensions.

        Only the data is moved; coordinates stay in place. This is consistent
        with the behavior of ``shift`` in pandas.

        Values shifted from beyond array bounds will appear at one end of
        each dimension, which are filled according to `fill_value`. For periodic
        offsets instead see `roll`.

        Parameters
        ----------
        shifts : mapping of Hashable to int or None, optional
            Integer offset to shift along each of the given dimensions.
            Positive offsets shift to the right; negative offsets shift to the
            left.
        fill_value : scalar, optional
            Value to use for newly missing values
        **shifts_kwargs
            The keyword arguments form of ``shifts``.
            One of shifts or shifts_kwargs must be provided.

        Returns
        -------
        shifted : DataArray
            DataArray with the same coordinates and attributes but shifted
            data.

        See Also
        --------
        roll

        Examples
        --------
        >>> arr = xr.DataArray([5, 6, 7], dims="x")
        >>> arr.shift(x=1)
        <xarray.DataArray (x: 3)>
        array([nan,  5.,  6.])
        Dimensions without coordinates: x
        )r  rK  r(  )r   shiftr   )r   r  rK  r  r   rc   rc   rf   r    s    - zDataArray.shiftzMapping[Hashable, int] | None)r   r  roll_coordsr  rb   c                 K  s$   |   jf ||d|}| |S )a"  Roll this array by an offset along one or more dimensions.

        Unlike shift, roll treats the given dimensions as periodic, so will not
        create any missing values to be filled.

        Unlike shift, roll may rotate all variables, including coordinates
        if specified. The direction of rotation is consistent with
        :py:func:`numpy.roll`.

        Parameters
        ----------
        shifts : mapping of Hashable to int, optional
            Integer offset to rotate each of the given dimensions.
            Positive offsets roll to the right; negative offsets roll to the
            left.
        roll_coords : bool, default: False
            Indicates whether to roll the coordinates by the offset too.
        **shifts_kwargs : {dim: offset, ...}, optional
            The keyword arguments form of ``shifts``.
            One of shifts or shifts_kwargs must be provided.

        Returns
        -------
        rolled : DataArray
            DataArray with the same attributes but rolled data and coordinates.

        See Also
        --------
        shift

        Examples
        --------
        >>> arr = xr.DataArray([5, 6, 7], dims="x")
        >>> arr.roll(x=1)
        <xarray.DataArray (x: 3)>
        array([7, 5, 6])
        Dimensions without coordinates: x
        )r  r  )r   rollr   )r   r  r  r  r  rc   rc   rf   r    s    ,
 zDataArray.rollc                 C  s   |  | jjS )zk
        The real part of the array.

        See Also
        --------
        numpy.ndarray.real
        )r   r   realr   rc   rc   rf   r    s    	zDataArray.realc                 C  s   |  | jjS )zp
        The imaginary part of the array.

        See Also
        --------
        numpy.ndarray.imag
        )r   r   imagr   rc   rc   rf   r    s    	zDataArray.imag)r   rD  rn   rb   c                 C  s4   t |trtdt |ts$tdtj| ||dS )a_  Perform dot product of two DataArrays along their shared dims.

        Equivalent to taking taking tensordot over all shared dims.

        Parameters
        ----------
        other : DataArray
            The other array with which the dot product is performed.
        dims : ..., str, Iterable of Hashable or None, optional
            Which dimensions to sum over. Ellipsis (`...`) sums over all dimensions.
            If not specified, then all the common dimensions are summed over.

        Returns
        -------
        result : DataArray
            Array resulting from the dot product over all shared dimensions.

        See Also
        --------
        dot
        numpy.tensordot

        Examples
        --------
        >>> da_vals = np.arange(6 * 5 * 4).reshape((6, 5, 4))
        >>> da = xr.DataArray(da_vals, dims=["x", "y", "z"])
        >>> dm_vals = np.arange(4)
        >>> dm = xr.DataArray(dm_vals, dims=["z"])

        >>> dm.dims
        ('z',)

        >>> da.dims
        ('x', 'y', 'z')

        >>> dot_result = da.dot(dm)
        >>> dot_result.dims
        ('x', 'y')

        z8dot products are not yet supported with Dataset objects.z dot only operates on DataArrays.rm   )rs   r&   NotImplementedErrorr_   r{   r   r  )r   rD  rn   rc   rc   rf   r    s    -

zDataArray.dotz5Hashable | DataArray | Sequence[Hashable | DataArray])r   	ascendingrb   c                 C  s   |   j||d}| |S )a  Sort object by labels or values (along an axis).

        Sorts the dataarray, either along specified dimensions,
        or according to values of 1-D dataarrays that share dimension
        with calling object.

        If the input variables are dataarrays, then the dataarrays are aligned
        (via left-join) to the calling object prior to sorting by cell values.
        NaNs are sorted to the end, following Numpy convention.

        If multiple sorts along the same dimension is
        given, numpy's lexsort is performed along that dimension:
        https://numpy.org/doc/stable/reference/generated/numpy.lexsort.html
        and the FIRST key in the sequence is used as the primary sort key,
        followed by the 2nd key, etc.

        Parameters
        ----------
        variables : Hashable, DataArray, or sequence of Hashable or DataArray
            1D DataArray objects or name(s) of 1D variable(s) in
            coords whose values are used to sort this array.
        ascending : bool, default: True
            Whether to sort by ascending or descending order.

        Returns
        -------
        sorted : DataArray
            A new dataarray where all the specified dims are sorted by dim
            labels.

        See Also
        --------
        Dataset.sortby
        numpy.sort
        pandas.sort_values
        pandas.sort_index

        Examples
        --------
        >>> da = xr.DataArray(
        ...     np.random.rand(5),
        ...     coords=[pd.date_range("1/1/2000", periods=5)],
        ...     dims="time",
        ... )
        >>> da
        <xarray.DataArray (time: 5)>
        array([0.5488135 , 0.71518937, 0.60276338, 0.54488318, 0.4236548 ])
        Coordinates:
          * time     (time) datetime64[ns] 2000-01-01 2000-01-02 ... 2000-01-05

        >>> da.sortby(da)
        <xarray.DataArray (time: 5)>
        array([0.4236548 , 0.54488318, 0.5488135 , 0.60276338, 0.71518937])
        Coordinates:
          * time     (time) datetime64[ns] 2000-01-05 2000-01-04 ... 2000-01-02
        )r  )r   sortbyr   )r   r   r  r  rc   rc   rf   r  :  s    =zDataArray.sortbyrA   rU   zQuantileMethods | None)r   qr   r>  r  skipnainterpolationrb   c                 C  s$   |   j||||||d}| |S )a  Compute the qth quantile of the data along the specified dimension.

        Returns the qth quantiles(s) of the array elements.

        Parameters
        ----------
        q : float or array-like of float
            Quantile to compute, which must be between 0 and 1 inclusive.
        dim : str or Iterable of Hashable, optional
            Dimension(s) over which to apply quantile.
        method : str, default: "linear"
            This optional parameter specifies the interpolation method to use when the
            desired quantile lies between two data points. The options sorted by their R
            type as summarized in the H&F paper [1]_ are:

                1. "inverted_cdf" (*)
                2. "averaged_inverted_cdf" (*)
                3. "closest_observation" (*)
                4. "interpolated_inverted_cdf" (*)
                5. "hazen" (*)
                6. "weibull" (*)
                7. "linear"  (default)
                8. "median_unbiased" (*)
                9. "normal_unbiased" (*)

            The first three methods are discontiuous. The following discontinuous
            variations of the default "linear" (7.) option are also available:

                * "lower"
                * "higher"
                * "midpoint"
                * "nearest"

            See :py:func:`numpy.quantile` or [1]_ for details. The "method" argument
            was previously called "interpolation", renamed in accordance with numpy
            version 1.22.0.

            (*) These methods require numpy version 1.22 or newer.

        keep_attrs : bool or None, optional
            If True, the dataset's attributes (`attrs`) will be copied from
            the original object to the new one.  If False (default), the new
            object will be returned without attributes.
        skipna : bool or None, optional
            If True, skip missing values (as marked by NaN). By default, only
            skips missing values for float dtypes; other dtypes either do not
            have a sentinel missing value (int) or skipna=True has not been
            implemented (object, datetime64 or timedelta64).

        Returns
        -------
        quantiles : DataArray
            If `q` is a single quantile, then the result
            is a scalar. If multiple percentiles are given, first axis of
            the result corresponds to the quantile and a quantile dimension
            is added to the return array. The other dimensions are the
            dimensions that remain after the reduction of the array.

        See Also
        --------
        numpy.nanquantile, numpy.quantile, pandas.Series.quantile, Dataset.quantile

        Examples
        --------
        >>> da = xr.DataArray(
        ...     data=[[0.7, 4.2, 9.4, 1.5], [6.5, 7.3, 2.6, 1.9]],
        ...     coords={"x": [7, 9], "y": [1, 1.5, 2, 2.5]},
        ...     dims=("x", "y"),
        ... )
        >>> da.quantile(0)  # or da.quantile(0, dim=...)
        <xarray.DataArray ()>
        array(0.7)
        Coordinates:
            quantile  float64 0.0
        >>> da.quantile(0, dim="x")
        <xarray.DataArray (y: 4)>
        array([0.7, 4.2, 2.6, 1.5])
        Coordinates:
          * y         (y) float64 1.0 1.5 2.0 2.5
            quantile  float64 0.0
        >>> da.quantile([0, 0.5, 1])
        <xarray.DataArray (quantile: 3)>
        array([0.7, 3.4, 9.4])
        Coordinates:
          * quantile  (quantile) float64 0.0 0.5 1.0
        >>> da.quantile([0, 0.5, 1], dim="x")
        <xarray.DataArray (quantile: 3, y: 4)>
        array([[0.7 , 4.2 , 2.6 , 1.5 ],
               [3.6 , 5.75, 6.  , 1.7 ],
               [6.5 , 7.3 , 9.4 , 1.9 ]])
        Coordinates:
          * y         (y) float64 1.0 1.5 2.0 2.5
          * quantile  (quantile) float64 0.0 0.5 1.0

        References
        ----------
        .. [1] R. J. Hyndman and Y. Fan,
           "Sample quantiles in statistical packages,"
           The American Statistician, 50(4), pp. 361-365, 1996
        )r   r  r>  r  r  )r   quantiler   )r   r  r   r>  r  r  r  r  rc   rc   rf   r  z  s    nzDataArray.quantile)r   r   pctr  rb   c                 C  s   |   j|||d}| |S )a  Ranks the data.

        Equal values are assigned a rank that is the average of the ranks that
        would have been otherwise assigned to all of the values within that
        set.  Ranks begin at 1, not 0. If pct, computes percentage ranks.

        NaNs in the input array are returned as NaNs.

        The `bottleneck` library is required.

        Parameters
        ----------
        dim : Hashable
            Dimension over which to compute rank.
        pct : bool, default: False
            If True, compute percentage ranks, otherwise compute integer ranks.
        keep_attrs : bool or None, optional
            If True, the dataset's attributes (`attrs`) will be copied from
            the original object to the new one.  If False (default), the new
            object will be returned without attributes.

        Returns
        -------
        ranked : DataArray
            DataArray with the same coordinates and dtype 'float64'.

        Examples
        --------
        >>> arr = xr.DataArray([5, 6, 7], dims="x")
        >>> arr.rank("x")
        <xarray.DataArray (x: 3)>
        array([1., 2., 3.])
        Dimensions without coordinates: x
        )r  r  )r   rankr   )r   r   r  r  r  rc   rc   rf   r    s    )zDataArray.rankzLiteral[(1, 2)]rN   )r   r   
edge_orderdatetime_unitrb   c                 C  s   |   |||}| |S )a   Differentiate the array with the second order accurate central
        differences.

        .. note::
            This feature is limited to simple cartesian geometry, i.e. coord
            must be one dimensional.

        Parameters
        ----------
        coord : Hashable
            The coordinate to be used to compute the gradient.
        edge_order : {1, 2}, default: 1
            N-th order accurate differences at the boundaries.
        datetime_unit : {"Y", "M", "W", "D", "h", "m", "s", "ms",                          "us", "ns", "ps", "fs", "as", None}, optional
            Unit to compute gradient. Only valid for datetime coordinate.

        Returns
        -------
        differentiated: DataArray

        See also
        --------
        numpy.gradient: corresponding numpy function

        Examples
        --------

        >>> da = xr.DataArray(
        ...     np.arange(12).reshape(4, 3),
        ...     dims=["x", "y"],
        ...     coords={"x": [0, 0.1, 1.1, 1.2]},
        ... )
        >>> da
        <xarray.DataArray (x: 4, y: 3)>
        array([[ 0,  1,  2],
               [ 3,  4,  5],
               [ 6,  7,  8],
               [ 9, 10, 11]])
        Coordinates:
          * x        (x) float64 0.0 0.1 1.1 1.2
        Dimensions without coordinates: y
        >>>
        >>> da.differentiate("x")
        <xarray.DataArray (x: 4, y: 3)>
        array([[30.        , 30.        , 30.        ],
               [27.54545455, 27.54545455, 27.54545455],
               [27.54545455, 27.54545455, 27.54545455],
               [30.        , 30.        , 30.        ]])
        Coordinates:
          * x        (x) float64 0.0 0.1 1.1 1.2
        Dimensions without coordinates: y
        )r   differentiater   )r   r   r  r   r  rc   rc   rf   r    s    ;zDataArray.differentiate)r   r   rb   c                 C  s   |   ||}| |S )aT  Integrate along the given coordinate using the trapezoidal rule.

        .. note::
            This feature is limited to simple cartesian geometry, i.e. coord
            must be one dimensional.

        Parameters
        ----------
        coord : Hashable, or sequence of Hashable
            Coordinate(s) used for the integration.
        datetime_unit : {'Y', 'M', 'W', 'D', 'h', 'm', 's', 'ms', 'us', 'ns',                         'ps', 'fs', 'as', None}, optional
            Specify the unit if a datetime coordinate is used.

        Returns
        -------
        integrated : DataArray

        See also
        --------
        Dataset.integrate
        numpy.trapz : corresponding numpy function

        Examples
        --------

        >>> da = xr.DataArray(
        ...     np.arange(12).reshape(4, 3),
        ...     dims=["x", "y"],
        ...     coords={"x": [0, 0.1, 1.1, 1.2]},
        ... )
        >>> da
        <xarray.DataArray (x: 4, y: 3)>
        array([[ 0,  1,  2],
               [ 3,  4,  5],
               [ 6,  7,  8],
               [ 9, 10, 11]])
        Coordinates:
          * x        (x) float64 0.0 0.1 1.1 1.2
        Dimensions without coordinates: y
        >>>
        >>> da.integrate("x")
        <xarray.DataArray (y: 3)>
        array([5.4, 6.6, 7.8])
        Dimensions without coordinates: y
        )r   	integrater   r   r   r   r  rc   rc   rf   r  ^  s    3zDataArray.integratec                 C  s   |   ||}| |S )a  Integrate cumulatively along the given coordinate using the trapezoidal rule.

        .. note::
            This feature is limited to simple cartesian geometry, i.e. coord
            must be one dimensional.

            The first entry of the cumulative integral is always 0, in order to keep the
            length of the dimension unchanged between input and output.

        Parameters
        ----------
        coord : Hashable, or sequence of Hashable
            Coordinate(s) used for the integration.
        datetime_unit : {'Y', 'M', 'W', 'D', 'h', 'm', 's', 'ms', 'us', 'ns',                         'ps', 'fs', 'as', None}, optional
            Specify the unit if a datetime coordinate is used.

        Returns
        -------
        integrated : DataArray

        See also
        --------
        Dataset.cumulative_integrate
        scipy.integrate.cumulative_trapezoid : corresponding scipy function

        Examples
        --------

        >>> da = xr.DataArray(
        ...     np.arange(12).reshape(4, 3),
        ...     dims=["x", "y"],
        ...     coords={"x": [0, 0.1, 1.1, 1.2]},
        ... )
        >>> da
        <xarray.DataArray (x: 4, y: 3)>
        array([[ 0,  1,  2],
               [ 3,  4,  5],
               [ 6,  7,  8],
               [ 9, 10, 11]])
        Coordinates:
          * x        (x) float64 0.0 0.1 1.1 1.2
        Dimensions without coordinates: y
        >>>
        >>> da.cumulative_integrate("x")
        <xarray.DataArray (x: 4, y: 3)>
        array([[0.  , 0.  , 0.  ],
               [0.15, 0.25, 0.35],
               [4.65, 5.75, 6.85],
               [5.4 , 6.6 , 7.8 ]])
        Coordinates:
          * x        (x) float64 0.0 0.1 1.1 1.2
        Dimensions without coordinates: y
        )r   cumulative_integrater   r  rc   rc   rf   r    s    ;zDataArray.cumulative_integratec                 C  s   t | d S )zUnify chunk size along all chunked dimensions of this DataArray.

        Returns
        -------
        DataArray with consistent chunk sizes for all dask-array variables

        See Also
        --------
        dask.array.core.unify_chunks
        r   r"   r   rc   rc   rf   r#     s    zDataArray.unify_chunksrc   zCallable[..., T_Xarray]zSequence[Any]zDataArray | Dataset | Noner[   )r  r  r  templaterb   c                 C  s   ddl m} ||| |||S )aQ  
        Apply a function to each block of this DataArray.

        .. warning::
            This method is experimental and its signature may change.

        Parameters
        ----------
        func : callable
            User-provided function that accepts a DataArray as its first
            parameter. The function will receive a subset or 'block' of this DataArray (see below),
            corresponding to one chunk along each chunked dimension. ``func`` will be
            executed as ``func(subset_dataarray, *subset_args, **kwargs)``.

            This function must return either a single DataArray or a single Dataset.

            This function cannot add a new chunked dimension.
        args : sequence
            Passed to func after unpacking and subsetting any xarray objects by blocks.
            xarray objects in args must be aligned with this object, otherwise an error is raised.
        kwargs : mapping
            Passed verbatim to func after unpacking. xarray objects, if any, will not be
            subset to blocks. Passing dask collections in kwargs is not allowed.
        template : DataArray or Dataset, optional
            xarray object representing the final result after compute is called. If not provided,
            the function will be first run on mocked-up data, that looks like this object but
            has sizes 0, to determine properties of the returned object such as dtype,
            variable names, attributes, new dimensions and new indexes (if any).
            ``template`` must be provided if the function changes the size of existing dimensions.
            When provided, ``attrs`` on variables in `template` are copied over to the result. Any
            ``attrs`` set by ``func`` will be ignored.

        Returns
        -------
        A single DataArray or Dataset with dask backend, reassembled from the outputs of the
        function.

        Notes
        -----
        This function is designed for when ``func`` needs to manipulate a whole xarray object
        subset to each block. Each block is loaded into memory. In the more common case where
        ``func`` can work on numpy arrays, it is recommended to use ``apply_ufunc``.

        If none of the variables in this object is backed by dask arrays, calling this function is
        equivalent to calling ``func(obj, *args, **kwargs)``.

        See Also
        --------
        dask.array.map_blocks, xarray.apply_ufunc, xarray.Dataset.map_blocks
        xarray.DataArray.map_blocks

        Examples
        --------
        Calculate an anomaly from climatology using ``.groupby()``. Using
        ``xr.map_blocks()`` allows for parallel operations with knowledge of ``xarray``,
        its indices, and its methods like ``.groupby()``.

        >>> def calculate_anomaly(da, groupby_type="time.month"):
        ...     gb = da.groupby(groupby_type)
        ...     clim = gb.mean(dim="time")
        ...     return gb - clim
        ...
        >>> time = xr.cftime_range("1990-01", "1992-01", freq="M")
        >>> month = xr.DataArray(time.month, coords={"time": time}, dims=["time"])
        >>> np.random.seed(123)
        >>> array = xr.DataArray(
        ...     np.random.rand(len(time)),
        ...     dims=["time"],
        ...     coords={"time": time, "month": month},
        ... ).chunk()
        >>> array.map_blocks(calculate_anomaly, template=array).compute()
        <xarray.DataArray (time: 24)>
        array([ 0.12894847,  0.11323072, -0.0855964 , -0.09334032,  0.26848862,
                0.12382735,  0.22460641,  0.07650108, -0.07673453, -0.22865714,
               -0.19063865,  0.0590131 , -0.12894847, -0.11323072,  0.0855964 ,
                0.09334032, -0.26848862, -0.12382735, -0.22460641, -0.07650108,
                0.07673453,  0.22865714,  0.19063865, -0.0590131 ])
        Coordinates:
          * time     (time) object 1990-01-31 00:00:00 ... 1991-12-31 00:00:00
            month    (time) int64 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12

        Note that one must explicitly use ``args=[]`` and ``kwargs={}`` to pass arguments
        to the function being applied in ``xr.map_blocks()``:

        >>> array.map_blocks(
        ...     calculate_anomaly, kwargs={"groupby_type": "time.year"}, template=array
        ... )  # doctest: +ELLIPSIS
        <xarray.DataArray (time: 24)>
        dask.array<<this-array>-calculate_anomaly, shape=(24,), dtype=float64, chunksize=(24,), chunktype=numpy.ndarray>
        Coordinates:
          * time     (time) object 1990-01-31 00:00:00 ... 1991-12-31 00:00:00
            month    (time) int64 dask.array<chunksize=(24,), meta=np.ndarray>
        r   )
map_blocks)Zxarray.core.parallelr  )r   r  r  r  r  r  rc   rc   rf   r    s    dzDataArray.map_blockszfloat | NonezHashable | Any | Nonezbool | Literal['unscaled'])r   degr  rcondr  r   covrb   c              	   C  s   |   j|||||||dS )a  
        Least squares polynomial fit.

        This replicates the behaviour of `numpy.polyfit` but differs by skipping
        invalid values when `skipna = True`.

        Parameters
        ----------
        dim : Hashable
            Coordinate along which to fit the polynomials.
        deg : int
            Degree of the fitting polynomial.
        skipna : bool or None, optional
            If True, removes all invalid values before fitting each 1D slices of the array.
            Default is True if data is stored in a dask.array or if there is any
            invalid values, False otherwise.
        rcond : float or None, optional
            Relative condition number to the fit.
        w : Hashable, array-like or None, optional
            Weights to apply to the y-coordinate of the sample points.
            Can be an array-like object or the name of a coordinate in the dataset.
        full : bool, default: False
            Whether to return the residuals, matrix rank and singular values in addition
            to the coefficients.
        cov : bool or "unscaled", default: False
            Whether to return to the covariance matrix in addition to the coefficients.
            The matrix is not scaled if `cov='unscaled'`.

        Returns
        -------
        polyfit_results : Dataset
            A single dataset which contains:

            polyfit_coefficients
                The coefficients of the best fit.
            polyfit_residuals
                The residuals of the least-square computation (only included if `full=True`).
                When the matrix rank is deficient, np.nan is returned.
            [dim]_matrix_rank
                The effective rank of the scaled Vandermonde coefficient matrix (only included if `full=True`)
            [dim]_singular_value
                The singular values of the scaled Vandermonde coefficient matrix (only included if `full=True`)
            polyfit_covariance
                The covariance matrix of the polynomial coefficient estimates (only included if `full=False` and `cov=True`)

        See Also
        --------
        numpy.polyfit
        numpy.polyval
        xarray.polyval
        )r  r  r  r   r	  )r   polyfit)r   r   r  r  r  r  r   r	  rc   rc   rf   r
  J  s    =      zDataArray.polyfitconstantz*Mapping[Any, int | tuple[int, int]] | NonerS   z<int | tuple[int, int] | Mapping[Any, tuple[int, int]] | NonezFfloat | tuple[float, float] | Mapping[Any, tuple[float, float]] | NonerT   )
r   	pad_widthr  stat_lengthconstant_values
end_valuesreflect_typer  pad_width_kwargsrb   c           
   
   K  s.   |   jf |||||||d|}	| |	S )a  Pad this array along one or more dimensions.

        .. warning::
            This function is experimental and its behaviour is likely to change
            especially regarding padding of dimension coordinates (or IndexVariables).

        When using one of the modes ("edge", "reflect", "symmetric", "wrap"),
        coordinates will be padded with the same mode, otherwise coordinates
        are padded using the "constant" mode with fill_value dtypes.NA.

        Parameters
        ----------
        pad_width : mapping of Hashable to tuple of int
            Mapping with the form of {dim: (pad_before, pad_after)}
            describing the number of values padded along each dimension.
            {dim: pad} is a shortcut for pad_before = pad_after = pad
        mode : {"constant", "edge", "linear_ramp", "maximum", "mean", "median",             "minimum", "reflect", "symmetric", "wrap"}, default: "constant"
            How to pad the DataArray (taken from numpy docs):

            - "constant": Pads with a constant value.
            - "edge": Pads with the edge values of array.
            - "linear_ramp": Pads with the linear ramp between end_value and the
              array edge value.
            - "maximum": Pads with the maximum value of all or part of the
              vector along each axis.
            - "mean": Pads with the mean value of all or part of the
              vector along each axis.
            - "median": Pads with the median value of all or part of the
              vector along each axis.
            - "minimum": Pads with the minimum value of all or part of the
              vector along each axis.
            - "reflect": Pads with the reflection of the vector mirrored on
              the first and last values of the vector along each axis.
            - "symmetric": Pads with the reflection of the vector mirrored
              along the edge of the array.
            - "wrap": Pads with the wrap of the vector along the axis.
              The first values are used to pad the end and the
              end values are used to pad the beginning.

        stat_length : int, tuple or mapping of Hashable to tuple, default: None
            Used in 'maximum', 'mean', 'median', and 'minimum'.  Number of
            values at edge of each axis used to calculate the statistic value.
            {dim_1: (before_1, after_1), ... dim_N: (before_N, after_N)} unique
            statistic lengths along each dimension.
            ((before, after),) yields same before and after statistic lengths
            for each dimension.
            (stat_length,) or int is a shortcut for before = after = statistic
            length for all axes.
            Default is ``None``, to use the entire axis.
        constant_values : scalar, tuple or mapping of Hashable to tuple, default: 0
            Used in 'constant'.  The values to set the padded values for each
            axis.
            ``{dim_1: (before_1, after_1), ... dim_N: (before_N, after_N)}`` unique
            pad constants along each dimension.
            ``((before, after),)`` yields same before and after constants for each
            dimension.
            ``(constant,)`` or ``constant`` is a shortcut for ``before = after = constant`` for
            all dimensions.
            Default is 0.
        end_values : scalar, tuple or mapping of Hashable to tuple, default: 0
            Used in 'linear_ramp'.  The values used for the ending value of the
            linear_ramp and that will form the edge of the padded array.
            ``{dim_1: (before_1, after_1), ... dim_N: (before_N, after_N)}`` unique
            end values along each dimension.
            ``((before, after),)`` yields same before and after end values for each
            axis.
            ``(constant,)`` or ``constant`` is a shortcut for ``before = after = constant`` for
            all axes.
            Default is 0.
        reflect_type : {"even", "odd", None}, optional
            Used in "reflect", and "symmetric". The "even" style is the
            default with an unaltered reflection around the edge value. For
            the "odd" style, the extended part of the array is created by
            subtracting the reflected values from two times the edge value.
        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.
        **pad_width_kwargs
            The keyword arguments form of ``pad_width``.
            One of ``pad_width`` or ``pad_width_kwargs`` must be provided.

        Returns
        -------
        padded : DataArray
            DataArray with the padded coordinates and data.

        See Also
        --------
        DataArray.shift, DataArray.roll, DataArray.bfill, DataArray.ffill, numpy.pad, dask.array.pad

        Notes
        -----
        For ``mode="constant"`` and ``constant_values=None``, integer types will be
        promoted to ``float`` and padded with ``np.nan``.

        Padding coordinates will drop their corresponding index (if any) and will reset default
        indexes for dimension coordinates.

        Examples
        --------
        >>> arr = xr.DataArray([5, 6, 7], coords=[("x", [0, 1, 2])])
        >>> arr.pad(x=(1, 2), constant_values=0)
        <xarray.DataArray (x: 6)>
        array([0, 5, 6, 7, 0, 0])
        Coordinates:
          * x        (x) float64 nan 0.0 1.0 2.0 nan nan

        >>> da = xr.DataArray(
        ...     [[0, 1, 2, 3], [10, 11, 12, 13]],
        ...     dims=["x", "y"],
        ...     coords={"x": [0, 1], "y": [10, 20, 30, 40], "z": ("x", [100, 200])},
        ... )
        >>> da.pad(x=1)
        <xarray.DataArray (x: 4, y: 4)>
        array([[nan, nan, nan, nan],
               [ 0.,  1.,  2.,  3.],
               [10., 11., 12., 13.],
               [nan, nan, nan, nan]])
        Coordinates:
          * x        (x) float64 nan 0.0 1.0 nan
          * y        (y) int64 10 20 30 40
            z        (x) float64 nan 100.0 200.0 nan

        Careful, ``constant_values`` are coerced to the data type of the array which may
        lead to a loss of precision:

        >>> da.pad(x=1, constant_values=1.23456789)
        <xarray.DataArray (x: 4, y: 4)>
        array([[ 1,  1,  1,  1],
               [ 0,  1,  2,  3],
               [10, 11, 12, 13],
               [ 1,  1,  1,  1]])
        Coordinates:
          * x        (x) float64 nan 0.0 1.0 nan
          * y        (y) int64 10 20 30 40
            z        (x) float64 nan 100.0 200.0 nan
        )r  r  r  r  r  r  r  )r   padr   )
r   r  r  r  r  r  r  r  r  r  rc   rc   rf   r    s     

zDataArray.pad)r   r  rK  r  rb   c                 C  s   t j| dd ||||dS )a  Return the coordinate label of the minimum value along a dimension.

        Returns a new `DataArray` named after the dimension with the values of
        the coordinate labels along that dimension corresponding to minimum
        values along that dimension.

        In comparison to :py:meth:`~DataArray.argmin`, this returns the
        coordinate label while :py:meth:`~DataArray.argmin` returns the index.

        Parameters
        ----------
        dim : str, optional
            Dimension over which to apply `idxmin`.  This is optional for 1D
            arrays, but required for arrays with 2 or more dimensions.
        skipna : bool or None, default: None
            If True, skip missing values (as marked by NaN). By default, only
            skips missing values for ``float``, ``complex``, and ``object``
            dtypes; other dtypes either do not have a sentinel missing value
            (``int``) or ``skipna=True`` has not been implemented
            (``datetime64`` or ``timedelta64``).
        fill_value : Any, default: NaN
            Value to be filled in case all of the values along a dimension are
            null.  By default this is NaN.  The fill value and result are
            automatically converted to a compatible dtype if possible.
            Ignored if ``skipna`` is False.
        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
        -------
        reduced : DataArray
            New `DataArray` object with `idxmin` applied to its data and the
            indicated dimension removed.

        See Also
        --------
        Dataset.idxmin, DataArray.idxmax, DataArray.min, DataArray.argmin

        Examples
        --------
        >>> array = xr.DataArray(
        ...     [0, 2, 1, 0, -2], dims="x", coords={"x": ["a", "b", "c", "d", "e"]}
        ... )
        >>> array.min()
        <xarray.DataArray ()>
        array(-2)
        >>> array.argmin(...)
        {'x': <xarray.DataArray ()>
        array(4)}
        >>> array.idxmin()
        <xarray.DataArray 'x' ()>
        array('e', dtype='<U1')

        >>> array = xr.DataArray(
        ...     [
        ...         [2.0, 1.0, 2.0, 0.0, -2.0],
        ...         [-4.0, np.NaN, 2.0, np.NaN, -2.0],
        ...         [np.NaN, np.NaN, 1.0, np.NaN, np.NaN],
        ...     ],
        ...     dims=["y", "x"],
        ...     coords={"y": [-1, 0, 1], "x": np.arange(5.0) ** 2},
        ... )
        >>> array.min(dim="x")
        <xarray.DataArray (y: 3)>
        array([-2., -4.,  1.])
        Coordinates:
          * y        (y) int64 -1 0 1
        >>> array.argmin(dim="x")
        <xarray.DataArray (y: 3)>
        array([4, 0, 2])
        Coordinates:
          * y        (y) int64 -1 0 1
        >>> array.idxmin(dim="x")
        <xarray.DataArray 'x' (y: 3)>
        array([16.,  0.,  4.])
        Coordinates:
          * y        (y) int64 -1 0 1
        c                 _  s   | j ||S rj   )argminr  r  r  rc   rc   rf   r    r  z"DataArray.idxmin.<locals>.<lambda>r   r  r   r  rK  r  r   Z_calc_idxminmaxr   r   r  rK  r  rc   rc   rf   idxmin3  s    WzDataArray.idxminc                 C  s   t j| dd ||||dS )a  Return the coordinate label of the maximum value along a dimension.

        Returns a new `DataArray` named after the dimension with the values of
        the coordinate labels along that dimension corresponding to maximum
        values along that dimension.

        In comparison to :py:meth:`~DataArray.argmax`, this returns the
        coordinate label while :py:meth:`~DataArray.argmax` returns the index.

        Parameters
        ----------
        dim : Hashable, optional
            Dimension over which to apply `idxmax`.  This is optional for 1D
            arrays, but required for arrays with 2 or more dimensions.
        skipna : bool or None, default: None
            If True, skip missing values (as marked by NaN). By default, only
            skips missing values for ``float``, ``complex``, and ``object``
            dtypes; other dtypes either do not have a sentinel missing value
            (``int``) or ``skipna=True`` has not been implemented
            (``datetime64`` or ``timedelta64``).
        fill_value : Any, default: NaN
            Value to be filled in case all of the values along a dimension are
            null.  By default this is NaN.  The fill value and result are
            automatically converted to a compatible dtype if possible.
            Ignored if ``skipna`` is False.
        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
        -------
        reduced : DataArray
            New `DataArray` object with `idxmax` applied to its data and the
            indicated dimension removed.

        See Also
        --------
        Dataset.idxmax, DataArray.idxmin, DataArray.max, DataArray.argmax

        Examples
        --------
        >>> array = xr.DataArray(
        ...     [0, 2, 1, 0, -2], dims="x", coords={"x": ["a", "b", "c", "d", "e"]}
        ... )
        >>> array.max()
        <xarray.DataArray ()>
        array(2)
        >>> array.argmax(...)
        {'x': <xarray.DataArray ()>
        array(1)}
        >>> array.idxmax()
        <xarray.DataArray 'x' ()>
        array('b', dtype='<U1')

        >>> array = xr.DataArray(
        ...     [
        ...         [2.0, 1.0, 2.0, 0.0, -2.0],
        ...         [-4.0, np.NaN, 2.0, np.NaN, -2.0],
        ...         [np.NaN, np.NaN, 1.0, np.NaN, np.NaN],
        ...     ],
        ...     dims=["y", "x"],
        ...     coords={"y": [-1, 0, 1], "x": np.arange(5.0) ** 2},
        ... )
        >>> array.max(dim="x")
        <xarray.DataArray (y: 3)>
        array([2., 2., 1.])
        Coordinates:
          * y        (y) int64 -1 0 1
        >>> array.argmax(dim="x")
        <xarray.DataArray (y: 3)>
        array([0, 2, 2])
        Coordinates:
          * y        (y) int64 -1 0 1
        >>> array.idxmax(dim="x")
        <xarray.DataArray 'x' (y: 3)>
        array([0., 4., 4.])
        Coordinates:
          * y        (y) int64 -1 0 1
        c                 _  s   | j ||S rj   )argmaxr  rc   rc   rf   r    r  z"DataArray.idxmax.<locals>.<lambda>r  r  r  rc   rc   rf   idxmax  s    WzDataArray.idxmaxz%DataArray | dict[Hashable, DataArray])r   r`  r  r  rb   c                   s@    j ||||}t|tr2 fdd| D S  |S dS )aC  Index or indices of the minimum of the DataArray over one or more dimensions.

        If a sequence is passed to 'dim', then result returned as dict of DataArrays,
        which can be passed directly to isel(). If a single str is passed to 'dim' then
        returns a DataArray with dtype int.

        If there are multiple minima, the indices of the first one found will be
        returned.

        Parameters
        ----------
        dim : "...", str, Iterable of Hashable or None, optional
            The dimensions over which to find the minimum. By default, finds minimum over
            all dimensions - for now returning an int for backward compatibility, but
            this is deprecated, in future will return a dict with indices for all
            dimensions; to return a dict with all dimensions now, pass '...'.
        axis : int or None, optional
            Axis over which to apply `argmin`. Only one of the 'dim' and 'axis' arguments
            can be supplied.
        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.
        skipna : bool or None, optional
            If True, skip missing values (as marked by NaN). By default, only
            skips missing values for float dtypes; other dtypes either do not
            have a sentinel missing value (int) or skipna=True has not been
            implemented (object, datetime64 or timedelta64).

        Returns
        -------
        result : DataArray or dict of DataArray

        See Also
        --------
        Variable.argmin, DataArray.idxmin

        Examples
        --------
        >>> array = xr.DataArray([0, 2, -1, 3], dims="x")
        >>> array.min()
        <xarray.DataArray ()>
        array(-1)
        >>> array.argmin(...)
        {'x': <xarray.DataArray ()>
        array(2)}
        >>> array.isel(array.argmin(...))
        <xarray.DataArray ()>
        array(-1)

        >>> array = xr.DataArray(
        ...     [[[3, 2, 1], [3, 1, 2], [2, 1, 3]], [[1, 3, 2], [2, -5, 1], [2, 3, 1]]],
        ...     dims=("x", "y", "z"),
        ... )
        >>> array.min(dim="x")
        <xarray.DataArray (y: 3, z: 3)>
        array([[ 1,  2,  1],
               [ 2, -5,  1],
               [ 2,  1,  1]])
        Dimensions without coordinates: y, z
        >>> array.argmin(dim="x")
        <xarray.DataArray (y: 3, z: 3)>
        array([[1, 0, 0],
               [1, 1, 1],
               [0, 0, 1]])
        Dimensions without coordinates: y, z
        >>> array.argmin(dim=["x"])
        {'x': <xarray.DataArray (y: 3, z: 3)>
        array([[1, 0, 0],
               [1, 1, 1],
               [0, 0, 1]])
        Dimensions without coordinates: y, z}
        >>> array.min(dim=("x", "z"))
        <xarray.DataArray (y: 3)>
        array([ 1, -5,  1])
        Dimensions without coordinates: y
        >>> array.argmin(dim=["x", "z"])
        {'x': <xarray.DataArray (y: 3)>
        array([0, 1, 0])
        Dimensions without coordinates: y, 'z': <xarray.DataArray (y: 3)>
        array([2, 1, 1])
        Dimensions without coordinates: y}
        >>> array.isel(array.argmin(dim=["x", "z"]))
        <xarray.DataArray (y: 3)>
        array([ 1, -5,  1])
        Dimensions without coordinates: y
        c                   s   i | ]\}}|  |qS rc   r   r   r   rc   rf   r   U  s      z$DataArray.argmin.<locals>.<dictcomp>N)r   r  rs   r}   r|   r   r   r   r`  r  r  r   rc   r   rf   r    s    ^
zDataArray.argminc                   s@    j ||||}t|tr2 fdd| D S  |S dS )a1  Index or indices of the maximum of the DataArray over one or more dimensions.

        If a sequence is passed to 'dim', then result returned as dict of DataArrays,
        which can be passed directly to isel(). If a single str is passed to 'dim' then
        returns a DataArray with dtype int.

        If there are multiple maxima, the indices of the first one found will be
        returned.

        Parameters
        ----------
        dim : "...", str, Iterable of Hashable or None, optional
            The dimensions over which to find the maximum. By default, finds maximum over
            all dimensions - for now returning an int for backward compatibility, but
            this is deprecated, in future will return a dict with indices for all
            dimensions; to return a dict with all dimensions now, pass '...'.
        axis : int or None, optional
            Axis over which to apply `argmax`. Only one of the 'dim' and 'axis' arguments
            can be supplied.
        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.
        skipna : bool or None, optional
            If True, skip missing values (as marked by NaN). By default, only
            skips missing values for float dtypes; other dtypes either do not
            have a sentinel missing value (int) or skipna=True has not been
            implemented (object, datetime64 or timedelta64).

        Returns
        -------
        result : DataArray or dict of DataArray

        See Also
        --------
        Variable.argmax, DataArray.idxmax

        Examples
        --------
        >>> array = xr.DataArray([0, 2, -1, 3], dims="x")
        >>> array.max()
        <xarray.DataArray ()>
        array(3)
        >>> array.argmax(...)
        {'x': <xarray.DataArray ()>
        array(3)}
        >>> array.isel(array.argmax(...))
        <xarray.DataArray ()>
        array(3)

        >>> array = xr.DataArray(
        ...     [[[3, 2, 1], [3, 1, 2], [2, 1, 3]], [[1, 3, 2], [2, 5, 1], [2, 3, 1]]],
        ...     dims=("x", "y", "z"),
        ... )
        >>> array.max(dim="x")
        <xarray.DataArray (y: 3, z: 3)>
        array([[3, 3, 2],
               [3, 5, 2],
               [2, 3, 3]])
        Dimensions without coordinates: y, z
        >>> array.argmax(dim="x")
        <xarray.DataArray (y: 3, z: 3)>
        array([[0, 1, 1],
               [0, 1, 0],
               [0, 1, 0]])
        Dimensions without coordinates: y, z
        >>> array.argmax(dim=["x"])
        {'x': <xarray.DataArray (y: 3, z: 3)>
        array([[0, 1, 1],
               [0, 1, 0],
               [0, 1, 0]])
        Dimensions without coordinates: y, z}
        >>> array.max(dim=("x", "z"))
        <xarray.DataArray (y: 3)>
        array([3, 5, 3])
        Dimensions without coordinates: y
        >>> array.argmax(dim=["x", "z"])
        {'x': <xarray.DataArray (y: 3)>
        array([0, 1, 0])
        Dimensions without coordinates: y, 'z': <xarray.DataArray (y: 3)>
        array([0, 1, 2])
        Dimensions without coordinates: y}
        >>> array.isel(array.argmax(dim=["x", "z"]))
        <xarray.DataArray (y: 3)>
        array([3, 5, 3])
        Dimensions without coordinates: y
        c                   s   i | ]\}}|  |qS rc   r  r   r   rc   rf   r     s      z$DataArray.argmax.<locals>.<dictcomp>N)r   r  rs   r}   r|   r   r  rc   r   rf   r  [  s    ^
zDataArray.argmaxpandasrW   rV   )queriesparserr  r:  queries_kwargsrb   c                 K  s0   | j dd}|jf ||||d|}|| j S )u	  Return a new data array indexed along the specified
        dimension(s), where the indexers are given as strings containing
        Python expressions to be evaluated against the values in the array.

        Parameters
        ----------
        queries : dict-like or None, optional
            A dict-like with keys matching dimensions and values given by strings
            containing Python expressions to be evaluated against the data variables
            in the dataset. The expressions will be evaluated using the pandas
            eval() function, and can contain any valid Python expressions but cannot
            contain any Python statements.
        parser : {"pandas", "python"}, default: "pandas"
            The parser to use to construct the syntax tree from the expression.
            The default of 'pandas' parses code slightly different than standard
            Python. Alternatively, you can parse an expression using the 'python'
            parser to retain strict Python semantics.
        engine : {"python", "numexpr", None}, default: None
            The engine used to evaluate the expression. Supported engines are:

            - None: tries to use numexpr, falls back to python
            - "numexpr": evaluates expressions using numexpr
            - "python": performs operations as if you had eval’d in top level python

        missing_dims : {"raise", "warn", "ignore"}, default: "raise"
            What to do if dimensions that should be selected from are not present in the
            DataArray:

            - "raise": raise an exception
            - "warn": raise a warning, and ignore the missing dimensions
            - "ignore": ignore the missing dimensions

        **queries_kwargs : {dim: query, ...}, optional
            The keyword arguments form of ``queries``.
            One of queries or queries_kwargs must be provided.

        Returns
        -------
        obj : DataArray
            A new DataArray with the same contents as this dataset, indexed by
            the results of the appropriate queries.

        See Also
        --------
        DataArray.isel
        Dataset.query
        pandas.eval

        Examples
        --------
        >>> da = xr.DataArray(np.arange(0, 5, 1), dims="x", name="a")
        >>> da
        <xarray.DataArray 'a' (x: 5)>
        array([0, 1, 2, 3, 4])
        Dimensions without coordinates: x
        >>> da.query(x="a > 2")
        <xarray.DataArray 'a' (x: 2)>
        array([3, 4])
        Dimensions without coordinates: x
        T)r   )r  r  r  r:  )r   queryri   )r   r  r  r  r:  r   r  rc   rc   rf   r!    s    EzDataArray.queryz+str | DataArray | Iterable[str | DataArray]zdict[str, Any] | NonezSequence[str] | None)	r   r  reduce_dimsr  p0boundsparam_namesr  rb   c	           	   
   C  s   |   j||||||||dS )ag  
        Curve fitting optimization for arbitrary functions.

        Wraps `scipy.optimize.curve_fit` with `apply_ufunc`.

        Parameters
        ----------
        coords : Hashable, DataArray, or sequence of DataArray or Hashable
            Independent coordinate(s) over which to perform the curve fitting. Must share
            at least one dimension with the calling object. When fitting multi-dimensional
            functions, supply `coords` as a sequence in the same order as arguments in
            `func`. To fit along existing dimensions of the calling object, `coords` can
            also be specified as a str or sequence of strs.
        func : callable
            User specified function in the form `f(x, *params)` which returns a numpy
            array of length `len(x)`. `params` are the fittable parameters which are optimized
            by scipy curve_fit. `x` can also be specified as a sequence containing multiple
            coordinates, e.g. `f((x0, x1), *params)`.
        reduce_dims : str, Iterable of Hashable or None, optional
            Additional dimension(s) over which to aggregate while fitting. For example,
            calling `ds.curvefit(coords='time', reduce_dims=['lat', 'lon'], ...)` will
            aggregate all lat and lon points and fit the specified function along the
            time dimension.
        skipna : bool, default: True
            Whether to skip missing values when fitting. Default is True.
        p0 : dict-like or None, optional
            Optional dictionary of parameter names to initial guesses passed to the
            `curve_fit` `p0` arg. If none or only some parameters are passed, the rest will
            be assigned initial values following the default scipy behavior.
        bounds : dict-like or None, optional
            Optional dictionary of parameter names to bounding values passed to the
            `curve_fit` `bounds` arg. If none or only some parameters are passed, the rest
            will be unbounded following the default scipy behavior.
        param_names : sequence of Hashable or None, optional
            Sequence of names for the fittable parameters of `func`. If not supplied,
            this will be automatically determined by arguments of `func`. `param_names`
            should be manually supplied when fitting a function that takes a variable
            number of parameters.
        **kwargs : optional
            Additional keyword arguments to passed to scipy curve_fit.

        Returns
        -------
        curvefit_results : Dataset
            A single dataset which contains:

            [var]_curvefit_coefficients
                The coefficients of the best fit.
            [var]_curvefit_covariance
                The covariance matrix of the coefficient estimates.

        See Also
        --------
        DataArray.polyfit
        scipy.optimize.curve_fit
        )r"  r  r#  r$  r%  r  )r   curvefit)	r   r   r  r"  r  r#  r$  r%  r  rc   rc   rf   r&    s    CzDataArray.curvefitfirstz!Literal[('first', 'last', False)])r   r   keeprb   c                 C  s   |   j||d}| |S )a  Returns a new DataArray with duplicate dimension values removed.

        Parameters
        ----------
        dim : dimension label or labels
            Pass `...` to drop duplicates along all dimensions.
        keep : {"first", "last", False}, default: "first"
            Determines which duplicates (if any) to keep.

            - ``"first"`` : Drop duplicates except for the first occurrence.
            - ``"last"`` : Drop duplicates except for the last occurrence.
            - False : Drop all duplicates.

        Returns
        -------
        DataArray

        See Also
        --------
        Dataset.drop_duplicates

        Examples
        --------
        >>> da = xr.DataArray(
        ...     np.arange(25).reshape(5, 5),
        ...     dims=("x", "y"),
        ...     coords={"x": np.array([0, 0, 1, 2, 3]), "y": np.array([0, 1, 2, 3, 3])},
        ... )
        >>> da
        <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]])
        Coordinates:
          * x        (x) int64 0 0 1 2 3
          * y        (y) int64 0 1 2 3 3

        >>> da.drop_duplicates(dim="x")
        <xarray.DataArray (x: 4, y: 5)>
        array([[ 0,  1,  2,  3,  4],
               [10, 11, 12, 13, 14],
               [15, 16, 17, 18, 19],
               [20, 21, 22, 23, 24]])
        Coordinates:
          * x        (x) int64 0 1 2 3
          * y        (y) int64 0 1 2 3 3

        >>> da.drop_duplicates(dim="x", keep="last")
        <xarray.DataArray (x: 4, y: 5)>
        array([[ 5,  6,  7,  8,  9],
               [10, 11, 12, 13, 14],
               [15, 16, 17, 18, 19],
               [20, 21, 22, 23, 24]])
        Coordinates:
          * x        (x) int64 0 1 2 3
          * y        (y) int64 0 1 2 3 3

        Drop all duplicate dimension values:

        >>> da.drop_duplicates(dim=...)
        <xarray.DataArray (x: 4, y: 4)>
        array([[ 0,  1,  2,  3],
               [10, 11, 12, 13],
               [15, 16, 17, 18],
               [20, 21, 22, 23]])
        Coordinates:
          * x        (x) int64 0 1 2 3
          * y        (y) int64 0 1 2 3
        )r(  )r   drop_duplicatesr   )r   r   r(  Zdeduplicatedrc   rc   rf   r)  \  s    LzDataArray.drop_duplicatestimez
Any | None)calendarr   align_onmissing
use_cftimerb   c                 C  s   t | |||||dS )a  Convert the DataArray to another calendar.

        Only converts the individual timestamps, does not modify any data except
        in dropping invalid/surplus dates or inserting missing dates.

        If the source and target calendars are either no_leap, all_leap or a
        standard type, only the type of the time array is modified.
        When converting to a leap year from a non-leap year, the 29th of February
        is removed from the array. In the other direction the 29th of February
        will be missing in the output, unless `missing` is specified,
        in which case that value is inserted.

        For conversions involving `360_day` calendars, see Notes.

        This method is safe to use with sub-daily data as it doesn't touch the
        time part of the timestamps.

        Parameters
        ---------
        calendar : str
            The target calendar name.
        dim : str
            Name of the time coordinate.
        align_on : {None, 'date', 'year'}
            Must be specified when either source or target is a `360_day` calendar,
           ignored otherwise. See Notes.
        missing : Optional[any]
            By default, i.e. if the value is None, this method will simply attempt
            to convert the dates in the source calendar to the same dates in the
            target calendar, and drop any of those that are not possible to
            represent.  If a value is provided, a new time coordinate will be
            created in the target calendar with the same frequency as the original
            time coordinate; for any dates that are not present in the source, the
            data will be filled with this value.  Note that using this mode requires
            that the source data have an inferable frequency; for more information
            see :py:func:`xarray.infer_freq`.  For certain frequency, source, and
            target calendar combinations, this could result in many missing values, see notes.
        use_cftime : boolean, optional
            Whether to use cftime objects in the output, only used if `calendar`
            is one of {"proleptic_gregorian", "gregorian" or "standard"}.
            If True, the new time axis uses cftime objects.
            If None (default), it uses :py:class:`numpy.datetime64` values if the
            date range permits it, and :py:class:`cftime.datetime` objects if not.
            If False, it uses :py:class:`numpy.datetime64`  or fails.

        Returns
        -------
        DataArray
            Copy of the dataarray with the time coordinate converted to the
            target calendar. If 'missing' was None (default), invalid dates in
            the new calendar are dropped, but missing dates are not inserted.
            If `missing` was given, the new data is reindexed to have a time axis
            with the same frequency as the source, but in the new calendar; any
            missing datapoints are filled with `missing`.

        Notes
        -----
        Passing a value to `missing` is only usable if the source's time coordinate as an
        inferable frequencies (see :py:func:`~xarray.infer_freq`) and is only appropriate
        if the target coordinate, generated from this frequency, has dates equivalent to the
        source. It is usually **not** appropriate to use this mode with:

        - Period-end frequencies : 'A', 'Y', 'Q' or 'M', in opposition to 'AS' 'YS', 'QS' and 'MS'
        - Sub-monthly frequencies that do not divide a day evenly : 'W', 'nD' where `N != 1`
            or 'mH' where 24 % m != 0).

        If one of the source or target calendars is `"360_day"`, `align_on` must
        be specified and two options are offered.

        - "year"
            The dates are translated according to their relative position in the year,
            ignoring their original month and day information, meaning that the
            missing/surplus days are added/removed at regular intervals.

            From a `360_day` to a standard calendar, the output will be missing the
            following dates (day of year in parentheses):

            To a leap year:
                January 31st (31), March 31st (91), June 1st (153), July 31st (213),
                September 31st (275) and November 30th (335).
            To a non-leap year:
                February 6th (36), April 19th (109), July 2nd (183),
                September 12th (255), November 25th (329).

            From a standard calendar to a `"360_day"`, the following dates in the
            source array will be dropped:

            From a leap year:
                January 31st (31), April 1st (92), June 1st (153), August 1st (214),
                September 31st (275), December 1st (336)
            From a non-leap year:
                February 6th (37), April 20th (110), July 2nd (183),
                September 13th (256), November 25th (329)

            This option is best used on daily and subdaily data.

        - "date"
            The month/day information is conserved and invalid dates are dropped
            from the output. This means that when converting from a `"360_day"` to a
            standard calendar, all 31st (Jan, March, May, July, August, October and
            December) will be missing as there is no equivalent dates in the
            `"360_day"` calendar and the 29th (on non-leap years) and 30th of February
            will be dropped as there are no equivalent dates in a standard calendar.

            This option is best used with data on a frequency coarser than daily.
        )r   r,  r-  r.  )r   )r   r+  r   r,  r-  r.  rc   rc   rf   r     s    rzDataArray.convert_calendarz*pd.DatetimeIndex | CFTimeIndex | DataArray)targetr   rb   c                 C  s   t | ||dS )a  Interpolates the DataArray to another calendar based on decimal year measure.

        Each timestamp in `source` and `target` are first converted to their decimal
        year equivalent then `source` is interpolated on the target coordinate.
        The decimal year of a timestamp is its year plus its sub-year component
        converted to the fraction of its year. For example "2000-03-01 12:00" is
        2000.1653 in a standard calendar or 2000.16301 in a `"noleap"` calendar.

        This method should only be used when the time (HH:MM:SS) information of
        time coordinate is not important.

        Parameters
        ----------
        target: DataArray or DatetimeIndex or CFTimeIndex
            The target time coordinate of a valid dtype
            (np.datetime64 or cftime objects)
        dim : str
            The time coordinate name.

        Return
        ------
        DataArray
            The source interpolated on the decimal years of target,
        r   )r   )r   r/  r   rc   rc   rf   r   &  s    zDataArray.interp_calendarz$Hashable | DataArray | IndexVariablerG   )r  rx  restore_coord_dimsrb   c                 C  s6   ddl m} t|ts&td| d|| |||dS )a  Returns a DataArrayGroupBy object for performing grouped operations.

        Parameters
        ----------
        group : Hashable, DataArray or IndexVariable
            Array whose unique values should be used to group this array. If a
            Hashable, must be the name of a coordinate contained in this dataarray.
        squeeze : bool, default: True
            If "group" is a dimension of any arrays in this dataset, `squeeze`
            controls whether the subarrays have a dimension of length 1 along
            that dimension or if the dimension is squeezed out.
        restore_coord_dims : bool, default: False
            If True, also restore the dimension order of multi-dimensional
            coordinates.

        Returns
        -------
        grouped : DataArrayGroupBy
            A `DataArrayGroupBy` object patterned after `pandas.GroupBy` that can be
            iterated over in the form of `(unique_value, grouped_array)` pairs.

        Examples
        --------
        Calculate daily anomalies for daily data:

        >>> da = xr.DataArray(
        ...     np.linspace(0, 1826, num=1827),
        ...     coords=[pd.date_range("2000-01-01", "2004-12-31", freq="D")],
        ...     dims="time",
        ... )
        >>> da
        <xarray.DataArray (time: 1827)>
        array([0.000e+00, 1.000e+00, 2.000e+00, ..., 1.824e+03, 1.825e+03,
               1.826e+03])
        Coordinates:
          * time     (time) datetime64[ns] 2000-01-01 2000-01-02 ... 2004-12-31
        >>> da.groupby("time.dayofyear") - da.groupby("time.dayofyear").mean("time")
        <xarray.DataArray (time: 1827)>
        array([-730.8, -730.8, -730.8, ...,  730.2,  730.2,  730.5])
        Coordinates:
          * time       (time) datetime64[ns] 2000-01-01 2000-01-02 ... 2004-12-31
            dayofyear  (time) int64 1 2 3 4 5 6 7 8 ... 359 360 361 362 363 364 365 366

        See Also
        --------
        DataArray.groupby_bins
        Dataset.groupby
        core.groupby.DataArrayGroupBy
        pandas.DataFrame.groupby
        r   rF   z%`squeeze` must be True or False, but z was supplied)rx  r0  )r  rG   rs   r   r{   )r   r  rx  r0  rG   rc   rc   rf   groupbyE  s    8

   zDataArray.groupbyr  z!ArrayLike | Literal[False] | None)	r  binsrightr   	precisioninclude_lowestrx  r0  rb   c	           
      C  s*   ddl m}	 |	| ||||||||ddS )aK
  Returns a DataArrayGroupBy object for performing grouped operations.

        Rather than using all unique values of `group`, the values are discretized
        first by applying `pandas.cut` [1]_ to `group`.

        Parameters
        ----------
        group : Hashable, DataArray or IndexVariable
            Array whose binned values should be used to group this array. If a
            Hashable, must be the name of a coordinate contained in this dataarray.
        bins : int or array-like
            If bins is an int, it defines the number of equal-width bins in the
            range of x. However, in this case, the range of x is extended by .1%
            on each side to include the min or max values of x. If bins is a
            sequence it defines the bin edges allowing for non-uniform bin
            width. No extension of the range of x is done in this case.
        right : bool, default: True
            Indicates whether the bins include the rightmost edge or not. If
            right == True (the default), then the bins [1,2,3,4] indicate
            (1,2], (2,3], (3,4].
        labels : array-like, False or None, default: None
            Used as labels for the resulting bins. Must be of the same length as
            the resulting bins. If False, string bin labels are assigned by
            `pandas.cut`.
        precision : int, default: 3
            The precision at which to store and display the bins labels.
        include_lowest : bool, default: False
            Whether the first interval should be left-inclusive or not.
        squeeze : bool, default: True
            If "group" is a dimension of any arrays in this dataset, `squeeze`
            controls whether the subarrays have a dimension of length 1 along
            that dimension or if the dimension is squeezed out.
        restore_coord_dims : bool, default: False
            If True, also restore the dimension order of multi-dimensional
            coordinates.

        Returns
        -------
        grouped : DataArrayGroupBy
            A `DataArrayGroupBy` object patterned after `pandas.GroupBy` that can be
            iterated over in the form of `(unique_value, grouped_array)` pairs.
            The name of the group has the added suffix `_bins` in order to
            distinguish it from the original variable.

        See Also
        --------
        DataArray.groupby
        Dataset.groupby_bins
        core.groupby.DataArrayGroupBy
        pandas.DataFrame.groupby

        References
        ----------
        .. [1] http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html
        r   rF   )r3  r   r4  r5  )rx  r2  r0  Z
cut_kwargs)r  rG   )
r   r  r2  r3  r   r4  r5  rx  r0  rG   rc   rc   rf   groupby_bins  s    BzDataArray.groupby_binsr]   )weightsrb   c                 C  s   ddl m} || |S )ag  
        Weighted DataArray operations.

        Parameters
        ----------
        weights : DataArray
            An array of weights associated with the values in this Dataset.
            Each value in the data contributes to the reduction operation
            according to its associated weight.

        Notes
        -----
        ``weights`` must be a DataArray and cannot contain missing values.
        Missing values can be replaced by ``weights.fillna(0)``.

        Returns
        -------
        core.weighted.DataArrayWeighted

        See Also
        --------
        Dataset.weighted
        r   r\   )xarray.core.weightedr]   )r   r7  r]   rc   rc   rf   weighted  s    zDataArray.weightedzbool | Mapping[Any, bool]rK   )r   min_periodscenterwindow_kwargsrb   c                 K  s(   ddl m} t||d}|| |||dS )a  
        Rolling window object for DataArrays.

        Parameters
        ----------
        dim : dict, optional
            Mapping from the dimension name to create the rolling iterator
            along (e.g. `time`) to its moving window size.
        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 Mapping to int, default: False
            Set the labels at the center of the window.
        **window_kwargs : optional
            The keyword arguments form of ``dim``.
            One of dim or window_kwargs must be provided.

        Returns
        -------
        core.rolling.DataArrayRolling

        Examples
        --------
        Create rolling seasonal average of monthly data e.g. DJF, JFM, ..., SON:

        >>> 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.rolling(time=3, center=True).mean()
        <xarray.DataArray (time: 12)>
        array([nan,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10., nan])
        Coordinates:
          * time     (time) datetime64[ns] 1999-12-15 2000-01-15 ... 2000-11-15

        Remove the NaNs using ``dropna()``:

        >>> da.rolling(time=3, center=True).mean().dropna("time")
        <xarray.DataArray (time: 10)>
        array([ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10.])
        Coordinates:
          * time     (time) datetime64[ns] 2000-01-15 2000-02-15 ... 2000-10-15

        See Also
        --------
        core.rolling.DataArrayRolling
        Dataset.rolling
        r   )rK   rolling)r:  r;  )xarray.core.rollingrK   r8   )r   r   r:  r;  r<  rK   rc   rc   rf   r=    s    DzDataArray.rollingexactleftmeanrL   z'SideOptions | Mapping[Any, SideOptions]z-str | Callable | Mapping[Any, str | Callable]rJ   )r   boundaryside
coord_funcr<  rb   c                 K  s*   ddl m} t||d}|| ||||dS )a	  
        Coarsen object for DataArrays.

        Parameters
        ----------
        dim : mapping of hashable to int, optional
            Mapping from the dimension name to the window size.
        boundary : {"exact", "trim", "pad"}, default: "exact"
            If 'exact', a ValueError will be raised if dimension size is not a
            multiple of the window size. If 'trim', the excess entries are
            dropped. If 'pad', NA will be padded.
        side : {"left", "right"} or mapping of str to {"left", "right"}, default: "left"
        coord_func : str or mapping of hashable to str, default: "mean"
            function (name) that is applied to the coordinates,
            or a mapping from coordinate name to function (name).

        Returns
        -------
        core.rolling.DataArrayCoarsen

        Examples
        --------
        Coarsen the long time series by averaging over every four days.

        >>> da = xr.DataArray(
        ...     np.linspace(0, 364, num=364),
        ...     dims="time",
        ...     coords={"time": pd.date_range("1999-12-15", periods=364)},
        ... )
        >>> da  # +doctest: ELLIPSIS
        <xarray.DataArray (time: 364)>
        array([  0.        ,   1.00275482,   2.00550964,   3.00826446,
                 4.01101928,   5.0137741 ,   6.01652893,   7.01928375,
                 8.02203857,   9.02479339,  10.02754821,  11.03030303,
        ...
               356.98071625, 357.98347107, 358.9862259 , 359.98898072,
               360.99173554, 361.99449036, 362.99724518, 364.        ])
        Coordinates:
          * time     (time) datetime64[ns] 1999-12-15 1999-12-16 ... 2000-12-12
        >>> da.coarsen(time=3, boundary="trim").mean()  # +doctest: ELLIPSIS
        <xarray.DataArray (time: 121)>
        array([  1.00275482,   4.01101928,   7.01928375,  10.02754821,
                13.03581267,  16.04407713,  19.0523416 ,  22.06060606,
                25.06887052,  28.07713499,  31.08539945,  34.09366391,
        ...
               349.96143251, 352.96969697, 355.97796143, 358.9862259 ,
               361.99449036])
        Coordinates:
          * time     (time) datetime64[ns] 1999-12-16 1999-12-19 ... 2000-12-10
        >>>

        See Also
        --------
        core.rolling.DataArrayCoarsen
        Dataset.coarsen
        r   )rJ   coarsen)rB  rC  rD  )r>  rJ   r8   )r   r   rB  rC  rD  r<  rJ   rc   rc   rf   rE  E  s    @zDataArray.coarsen	start_dayzMapping[Any, str] | NonezSideOptions | Nonez.pd.Timedelta | datetime.timedelta | str | Nonezstr | DatetimeLikezdatetime.timedelta | str | NonerI   )indexerr  closedr   baseoffsetoriginr  loffsetr0  indexer_kwargsrb   c                 K  s4   ddl m} | jf ||||||||||	|
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 : Mapping of Hashable to str, 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 : str
            The keyword arguments form of ``indexer``.
            One of indexer or indexer_kwargs must be provided.

        Returns
        -------
        resampled : core.resample.DataArrayResample
            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
        --------
        Dataset.resample
        pandas.Series.resample
        pandas.DataFrame.resample

        References
        ----------
        .. [1] http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases
        r   rH   )Zresample_clsrG  r  rH  r   rI  rJ  rK  r  rL  r0  )xarray.core.resamplerI   Z	_resample)r   rG  r  rH  r   rI  rJ  rK  r  rL  r0  rM  rI   rc   rc   rf   resample  s     xzDataArray.resample)NNN)NT)N)NF)N)NF)TN)TNN)N)NFr9  )NNNF)N)N)N)N)NrR  FN)rR  FN)N)N)NN)NF)F)N)N)r   )NN)N)N)r~   N)NrR  NTNN)N)N)N)NN)T)	Nr  NNNNNTF)r  NNNNNTF)r  NNNNN)	Nr  NNNNNTF)TF)F)N)N)F)r  )r   r  )NF)N)T)NrR  NNN)FN)r   N)NN)NN)rc   NN)NNNFF)Nr  NNNNN)NNNN)NNNN)Nr  Nr9  )NTNNNN)r'  )r*  NNN)r*  )TF)TNr  FTF)NNF)Nr?  r@  rA  )
NNNNNNrF  NNN)r   r   r   __doc____annotations__r   r   ZUncachedAccessorr   dtr   r   r   classmethodr   r7   r   r   r   r   r   r   r   r   propertyri   setterr   r   r   r   r   r   r   r   r   r   r   r   r   r   rn   r   r   r   r   r  r  r  r  r   r   r  r   r  r   r   r  r  r  r  r  r  r  r  r  staticmethodr  r  r  r   r   r"  r%  r&  __hash__r'  r+  r3  r   r   r@  rB  rC  rH  rN  rP  rQ  rZ  r[  r]  r_  rb  re  rh  rj  rn  r*   rr  rt  rz  r~  r  r  r  r
  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r=   Zplotr  r  r  r  r  r  r  r  r  r  r  r  r  r#   r  r
  r  r  r  r  r  r!  r&  r)  r   r   r1  r6  r9  r=  rE  rO  r   rt   rc   rc   rc   rf   r_      s  
{
=  #  *
	

 
 V

H  R  ]   y-15N" -]       .?  b  D(  (M?D"2	"E$ $"E6 "L@    	 .}WV./!  @        4       4     :        4~"C 
1>:	 
$  4 4  1
;C    .{  / "B : >  &l    ,C      6 +"b"d   &h   &f   $S     2Q R   $~"  M     .R  &K   *M         B )
__future__r   datetimer4  osr   typingr   r   r   r   r   r	   r
   r   r   r   r   Znumpyr   r  r   Zxarray.coding.calendar_opsr   r   Zxarray.coding.cftimeindexr   Zxarray.corer   r   r   r   r   r   Zxarray.core._aggregationsr   Zxarray.core.accessor_dtr   Zxarray.core.accessor_strr   Zxarray.core.alignmentr   r   r   Zxarray.core.arithmeticr   Zxarray.core.commonr   r    r!   Zxarray.core.computationr#   Zxarray.core.coordinatesr$   r%   r   r&   Zxarray.core.formattingr'   Zxarray.core.indexesr(   r)   r*   r+   r,   Zxarray.core.indexingr-   r.   Zxarray.core.merger/   r0   r1   Zxarray.core.optionsr2   r3   Zxarray.core.utilsr4   r5   r6   r7   r8   Zxarray.core.variabler9   r:   r;   r<   Zxarray.plot.accessorr=   Zxarray.plot.utilsr>   r?   r@   Znumpy.typingrA   Zdask.delayedrB   ImportErrorZcdms2r  Z	iris.cuberC   r  r  rD   rE   r  rG   rN  rI   r>  rJ   rK   Zxarray.core.typesrL   rM   rN   rO   rP   rQ   rR   rS   rT   rU   rV   rW   rX   rY   rZ   r[   r8  r]   r^   r   r   r   r   r_   rc   rc   rc   rf   <module>   sv   4 


HN
