U
    Cvf                    @  sT  d dl mZ d dlZd dlZd dl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 d dlZd dlZd dlmZ d dlmZ d dlZd dlmZ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*m+Z+m,Z,m-Z-m.Z. d dl/m0Z0m1Z1 d dl2m3Z3m4Z4m5Z5 d dl6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZA e!jBejCfZDe4eEf ZFe
rd dlGmHZHmIZImJZJmKZKmLZLmMZM dZNG dd deOZPd:ddddZQdd ZRdd ZSdd ZTdd ZUd;dd ZVd!d" ZWG d#d$ d$e(e8e&ZXG d%d& d&eXZYe$ZeYd'Z[d(d) Z\d*d+ Z]d$d,d-d.d/Z^d0d1 Z_d<d4d5Z`d6d7d-d8d9ZadS )=    )annotationsN)	timedelta)	TYPE_CHECKINGAnyCallableHashableIterableLiteralMappingNoReturnSequence)	ArrayLike)Version)commondtypesduck_array_opsindexingnputilsopsutils)VariableArithmetic)AbstractArray)BasicIndexerOuterIndexerPandasIndexingAdapterVectorizedIndexeras_indexable)OPTIONS_get_keep_attrs)
array_typeinteger_typesis_duck_dask_array)FrozenNdimSizeLenMixin
OrderedSet_defaultdecode_numpy_dict_valuesdrop_dims_from_indexerseither_dict_or_kwargsensure_us_time_resolution
infix_dimsis_duck_arraymaybe_coerce_to_str)DimsErrorOptionsWithWarnPadModeOptionsPadReflectOptionsQuantileMethods
T_Variablea  Converting non-nanosecond precision {case} values to nanosecond precision. This behavior can eventually be relaxed in xarray, as it is an artifact from pandas which is now beginning to support non-nanosecond precision values. This warning is caused by passing non-nanosecond np.datetime64 or np.timedelta64 values to the DataArray or Variable constructor; it can be silenced by converting the values to nanosecond precision ahead of time.c                   @  s   e Zd ZdZdS )MissingDimensionsErrorz=Error class used when we can't safely guess a dimension name.N)__name__
__module____qualname____doc__ r8   r8   8/tmp/pip-unpacked-wheel-h316xyqg/xarray/core/variable.pyr3   P   s   r3   zVariable | IndexVariablereturnc              
   C  s  ddl m} t| |r| j} t| tr6| jdd} n"t| trt| d |rVtdzt|  } W n6 ttfk
r } z|	d
| W 5 d}~X Y nX nt| rtg | } nt| tjtfr| jdk	rt| j| } n~t| ttfrtd	|d
t| nT|dk	rJt| }|jdkr:td|d|jdt||dd} ntd| |dk	r|| jkr| jdkrt|d| jd|  } | S )aA  Convert an object into a Variable.

    Parameters
    ----------
    obj : object
        Object to convert into a Variable.

        - If the object is already a Variable, return a shallow copy.
        - Otherwise, if the object has 'dims' and 'data' attributes, convert
          it into a new Variable.
        - If all else fails, attempt to convert the object into a Variable by
          unpacking it into the arguments for creating a new Variable.
    name : str, optional
        If provided:

        - `obj` can be a 1D array, which is assumed to label coordinate values
          along a dimension of this given name.
        - Variables with name matching one of their dimensions are converted
          into `IndexVariable` objects.

    Returns
    -------
    var : Variable
        The newly created variable.

    r   	DataArrayFdeep   zpUsing a DataArray object to construct a variable is ambiguous, please extract the data using the .data property.zPCould not convert tuple of form (dims, data[, attrs, encoding]): {} to Variable.Nz	variable z has invalid type zcannot set variable z with zY-dimensional data without explicit dimension names. Pass a tuple of (dims, data) instead.TfastpathzQunable to convert object into a variable without an explicit list of dimensions: zF has more than 1-dimension and the same name as one of its dimensions zf. xarray disallows such variables because they conflict with the coordinates used to label dimensions.)xarray.core.dataarrayr=   
isinstancevariableVariablecopytuple	TypeError
ValueError	__class__formatr   	is_scalarpdIndexIndexVariablenamesetdicttypeas_compatible_datandimr3   dimsto_index_variable)objrQ   r=   errordatar8   r8   r9   as_variableW   sR    




r\   c                 C  s   t | tjrt| S | S )z
    Put pandas.Index and numpy.ndarray arguments in adapter objects to ensure
    they can be indexed properly.

    NumpyArrayAdapter, PandasIndexingAdapter and LazilyIndexedArray should
    all pass through unmodified.
    )rD   rN   rO   r   r[   r8   r8   r9   _maybe_wrap_data   s    r^   c                 C  s   | j }|jdko(t|tj o(|t dk}t|tjo>|jdk}|sH|rtt	j
dd t|tjrvtd|j}nd}| |S |jdkr|t dkrtt	j
dd | dS | S d S )	NMzdatetime64[ns]nsdatetime)Zcasemztimedelta64[ns]r   )dtypekindrD   nprN   ZDatetimeTZDtypeunitr   Zemit_user_level_warningNON_NANOSECOND_WARNINGrL   tzastype)r[   rc   Znon_ns_datetime64Znon_ns_datetime_tz_dtypeZnanosecond_precision_dtyper8   r8   r9   _as_nanosecond_precision   s$    



rj   c                 C  s4   t |  }|jjdkr"t|}t|| j	S )a  Convert arrays of datetime.datetime and datetime.timedelta objects into
    datetime64 and timedelta64, according to the pandas convention. For the time
    being, convert any non-nanosecond precision DatetimeIndex or TimedeltaIndex
    objects to nanosecond precision.  While pandas is relaxing this in version
    2.0.0, in xarray we will need to make sure we are ready to handle
    non-nanosecond precision datetimes or timedeltas in our code before allowing
    such values to pass through unchanged.  Converting to nanosecond precision
    through pandas.Series objects ensures that datetimes and timedeltas are
    within the valid date range for ns precision, as pandas will raise an error
    if they are not.
    ZmM)
rN   Seriesravelrc   rd   rj   re   asarrayreshapeshape)valuesZ	as_seriesr8   r8   r9   _possibly_convert_objects   s    rq   c                 C  s"   t | tjtjfrt| S | S dS )ai  For the time being, convert any non-nanosecond precision DatetimeIndex or
    TimedeltaIndex objects to nanosecond precision.  While pandas is relaxing
    this in version 2.0.0, in xarray we will need to make sure we are ready to
    handle non-nanosecond precision datetimes or timedeltas in our code
    before allowing such values to pass through unchanged.N)rD   rN   ZDatetimeIndexZTimedeltaIndexrj   r]   r8   r8   r9   -_possibly_convert_datetime_or_timedelta_index   s    rr   Fc                 C  sv  |rt | dddkrt| S ddlm} t| t|fr<| jS t| trVt| } t| S t| t	rjt
| } t| tjrt| jd} t| trtt | d| d} t| tjtjtjfr| j} t| tjjrtj| }| rt| j\}}tj| |d} || |< n
t| } t| tjs@t | ds<t | dr@| S t| } t| tjrn| jj!d	krnt"| } t| S )
a  Prepare and wrap data to put in a Variable.

    - If data does not have the necessary attributes, convert it to ndarray.
    - If data has dtype=datetime64, ensure that it has ns precision. If it's a
      pandas.Timestamp, convert it to datetime64.
    - If data is already a pandas or xarray object (other than an Index), just
      use the values.

    Finally, wrap it up with an adapter if necessary.
    rV   r   r<   r`   valuerc   Z__array_function__Z__array_namespace__ZOMm)#getattrr^   rC   r=   rD   rF   r[   NON_NUMPY_SUPPORTED_ARRAY_TYPESrr   rH   r   Zto_0d_object_arrayrN   Z	Timestampre   
datetime64rs   r   timedelta64rk   rO   Z	DataFramerp   maZMaskedArrayZgetmaskarrayanyr   maybe_promoterc   rm   ndarrayhasattrrd   rq   )r[   rB   r=   maskrc   
fill_valuer8   r8   r9   rU      sB    







rU   c                 C  sJ   t | } | jdkrF| jjdkr.t | d} n| jjdkrFt | d} | S )a(  Return the given values as a numpy array, or as an individual item if
    it's a 0d datetime64 or timedelta64 array.

    Importantly, this function does not copy data if it is already an ndarray -
    otherwise, it will not be possible to update Variable values in place.

    This function mostly exists because 0-dimensional ndarrays with
    dtype=datetime64 are broken :(
    https://github.com/numpy/numpy/issues/4337
    https://github.com/numpy/numpy/issues/7619

    TODO: remove this (replace with np.asarray) once these issues are fixed
    r   r_   r`   rb   )re   rm   rV   rc   rd   rw   rx   r]   r8   r8   r9   _as_array_or_item+  s    

r   c                
   @  s0  e Zd ZdZdZdddZedd Zed	d
 ZeddddZ	edd Z
eddddZejdd ZdddddddddddZdd Zdd Zdd  Zd!d" Zd#d$ Zd%d& Zed'd( Zed)d* Zd+d, Zd-d. Zd/d0 Zed1d2 Zejd3d2 Zd dd4d5Zeed6Zd7dd8d9Zeed:Zd;dd<d=Z d;dd>d?Z!dd@d@dAdBdCdDZ"edEddFdGZ#e#jdHdIdJdKdGZ#dHdEdLdMdNZ$dOdP Z%dQdR Z&dSdT Z'dUdV Z(dWdX Z)dYdZ Z*d[d\ Z+dddd]d^Z,dddd_d`Z-e.j/fdadbZ0dcdd Z1ededdfdgZ2e2jdhdIdJdidgZ2ededdjdkZ3e3jdldk Z3ddd@dmddndodpZ4ddd@dmdqddrdsdtZ5e6e6e6e6fddddudvZ7ddddwdxZ8dddqddydzd{Z9dZ:ed|dd}d~Z;eddddZ<e=> Z?i dddfddd@d@dd dddZ@ddddZAdddddZBe6e.j/fddZCdd ZDdddddddddZEdddZFe.j/fddZGde.j/fddZHdddddZIddddddddddddZJdd ZKdddZLddddd dddZMed dddZNdddZOdddddZPdddZQddd dddZRe.j/dfddd@d dÜddńZSdddǄZTddɄ ZUe.j/fdd˄ZVddd̈́ZWdddddd@d dќddӄZXeYdddׄZZe[j\fddلZ]e[j\fddۄZ^e[j\fdd݄Z_e[j`fdd߄Zad ddddddd dddZbd!ddZcde.j/fddZdd"ddZedd Zfd#ddddZgd$ddddZhedd Ziedd Zjd%ddZkdd Zld&dd Zmdd ZnddeofddZpddϐdddddd	d
Zqd'dϐdddddddZrd(dϐdddddddZsdS ()  rF   a  A netcdf-like variable consisting of dimensions, data and attributes
    which describe a single Array. A single Variable object is not fully
    described outside the context of its parent Dataset (if you want such a
    fully described object, use a DataArray instead).

    The main functional difference between Variables and numpy arrays is that
    numerical operations on Variables implement array broadcasting by dimension
    name. For example, adding an Variable with dimensions `('time',)` to
    another Variable with dimensions `('space',)` results in a new Variable
    with dimensions `('time', 'space')`. Furthermore, numpy reduce operations
    like ``mean`` or ``sum`` are overwritten to take a "dimension" argument
    instead of an "axis".

    Variables are light-weight objects used as the building block for datasets.
    They are more primitive objects, so operations with them provide marginally
    higher performance than using DataArrays. However, manipulating data in the
    form of a Dataset or DataArray should almost always be preferred, because
    they can use more complete metadata in context of coordinate labels.
    )_dims_data_attrs	_encodingNFc                 C  sF   t ||d| _| || _d| _d| _|dk	r4|| _|dk	rB|| _dS )a  
        Parameters
        ----------
        dims : str or sequence of str
            Name(s) of the the data dimension(s). Must be either a string (only
            for 1D data) or a sequence of strings with length equal to the
            number of dimensions.
        data : array_like
            Data array which supports numpy-like data access.
        attrs : dict_like or None, optional
            Attributes to assign to the new variable. If None (default), an
            empty attribute dictionary is initialized.
        encoding : dict_like or None, optional
            Dictionary specifying how to encode this array's data into a
            serialized format like netCDF4. Currently used keys (for netCDF)
            include '_FillValue', 'scale_factor', 'add_offset' and 'dtype'.
            Well-behaved code to serialize a Variable should ignore
            unrecognized encoding items.
        rA   N)rU   r   _parse_dimensionsr   r   r   attrsencodingselfrW   r[   r   r   rB   r8   r8   r9   __init__Y  s    zVariable.__init__c                 C  s   | j jS )u   
        Data-type of the array’s elements.

        See Also
        --------
        ndarray.dtype
        numpy.dtype
        )r   rc   r   r8   r8   r9   rc   v  s    
zVariable.dtypec                 C  s   | j jS )zk
        Tuple of array dimensions.

        See Also
        --------
        numpy.ndarray.shape
        )r   ro   r   r8   r8   r9   ro     s    	zVariable.shapeintr:   c                 C  s&   t | jdr| jjS | j| jj S dS )z
        Total bytes consumed by the elements of the data array.

        If the underlying data array does not include ``nbytes``, estimates
        the bytes consumed based on the ``size`` and ``dtype``.
        nbytesN)r}   r   r   sizerc   itemsizer   r8   r8   r9   r     s    zVariable.nbytesc                 C  s4   t | jtjtjtfp2t | jtjo2t | jjtj	S N)
rD   r   re   r|   numberr   r   MemoryCachedArrayarrayZNumpyIndexingAdapterr   r8   r8   r9   
_in_memory  s     zVariable._in_memoryr   c                 C  s   t | jr| jS | jS dS )z
        The Variable's data as an array. The underlying array type
        (e.g. dask, sparse, pint) is preserved.

        See Also
        --------
        Variable.to_numpy
        Variable.as_numpy
        Variable.values
        N)r+   r   rp   r   r8   r8   r9   r[     s    
zVariable.datac                 C  s6   t |}|j| jkr,td|j d| j || _d S )NzMreplacement data must match the Variable's shape. replacement data has shape z; Variable has shape )rU   ro   rJ   r   r   r[   r8   r8   r9   r[     s    T)ordercastingsubokrG   
keep_attrsr2   )r   r;   c          	      C  sD   ddl m} t||||d}dd | D }|tj| |||ddS )u  
        Copy of the Variable object, with data cast to a specified type.

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

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

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

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

        See Also
        --------
        numpy.ndarray.astype
        dask.array.Array.astype
        sparse.COO.astype
        r   apply_ufunc)r   r   r   rG   c                 S  s   i | ]\}}|d k	r||qS r   r8   .0kvr8   r8   r9   
<dictcomp>  s       z#Variable.astype.<locals>.<dictcomp>allowed)kwargsr   dask)xarray.core.computationr   rS   itemsr   ri   )	r   rc   r   r   r   rG   r   r   r   r8   r8   r9   ri     s    =zVariable.astypec                 K  s<   t | jr t| jjf || _nt| js8t| j| _| S )a  Manually trigger loading of this variable's data from disk or a
        remote source into memory and return this variable.

        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.

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

        See Also
        --------
        dask.array.compute
        )r!   r   rU   computer+   re   rm   )r   r   r8   r8   r9   load	  s
    

zVariable.loadc                 K  s   | j dd}|jf |S )a5  Manually trigger loading of this variable's data from disk or a
        remote source into memory and return a new variable. 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.

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

        See Also
        --------
        dask.array.compute
        Fr>   )rG   r   )r   r   newr8   r8   r9   r      s    zVariable.computec                 C  s&   ddl m} |t| | j| j| jfS Nr   )normalize_token)	dask.baser   rT   r   r[   r   r   r   r8   r8   r9   __dask_tokenize__5  s    zVariable.__dask_tokenize__c                 C  s   t | jr| j S d S d S r   )r!   r   __dask_graph__r   r8   r8   r9   r   <  s    

zVariable.__dask_graph__c                 C  s
   | j  S r   )r   __dask_keys__r   r8   r8   r9   r   B  s    zVariable.__dask_keys__c                 C  s
   | j  S r   )r   __dask_layers__r   r8   r8   r9   r   E  s    zVariable.__dask_layers__c                 C  s   | j jS r   )r   __dask_optimize__r   r8   r8   r9   r   H  s    zVariable.__dask_optimize__c                 C  s   | j jS r   )r   __dask_scheduler__r   r8   r8   r9   r   L  s    zVariable.__dask_scheduler__c                 C  s   | j  \}}| j|f| fS r   )r   __dask_postcompute___dask_finalizer   
array_funcZ
array_argsr8   r8   r9   r   P  s    zVariable.__dask_postcompute__c                 C  s   | j  \}}| j|f| fS r   )r   __dask_postpersist__r   r   r8   r8   r9   r   T  s    zVariable.__dask_postpersist__c                 O  s&   ||f||}t | j|| j| jdS )N)r   r   )rF   r   r   r   )r   resultsr   argsr   r[   r8   r8   r9   r   X  s    zVariable._dask_finalizec                 C  s
   t | jS )z&The variable's data as a numpy.ndarray)r   r   r   r8   r8   r9   rp   \  s    zVariable.valuesc                 C  s
   || _ d S r   r]   r   rp   r8   r8   r9   rp   a  s    c                 C  s   t | j| j| j| jddS )z.Return this variable as a base xarray.VariableTr   rB   )rF   r   r   r   r   r   r8   r8   r9   to_base_variablee  s        zVariable.to_base_variableto_variablerP   c                 C  s   t | j| j| j| jddS )/Return this variable as an xarray.IndexVariableTr   )rP   r   r   r   r   r   r8   r8   r9   rX   m  s        zVariable.to_index_variableto_coordpd.Indexc                 C  s   |    S r   )rX   	_to_indexr   r8   r8   r9   r   u  s    zVariable._to_indexc                 C  s   |    S )'Convert this variable to a pandas.Index)rX   to_indexr   r8   r8   r9   r   x  s    zVariable.to_indexboolrS   )r[   r   r;   c                 C  sX   | j t| jd}|r*t| j |d< n|t| j| j	d |rTt
| j|d< |S )z&Dictionary representation of variable.)rW   r   r[   )rc   ro   r   )rW   r&   r   r)   rp   tolistupdatestrrc   ro   rS   r   )r   r[   r   itemr8   r8   r9   to_dict|  s    zVariable.to_dictztuple[Hashable, ...]c                 C  s   | j S )z@Tuple of dimension names with which this variable is associated.)r   r   r8   r8   r9   rW     s    zVariable.dimszstr | Iterable[Hashable]None)rs   r;   c                 C  s   |  || _d S r   )r   r   r   rs   r8   r8   r9   rW     s    )rW   r;   c                 C  s@   t |tr|f}t|}t|| jkr<td| d| j |S )Nzdimensions zB must have the same length as the number of data dimensions, ndim=)rD   r   rH   lenrV   rJ   )r   rW   r8   r8   r9   r     s    
zVariable._parse_dimensionsc                   s*   t  r"t fdd| jD S  S d S )Nc                 3  s   | ]}  |td V  qd S r   getslicer   dimkeyr8   r9   	<genexpr>  s     z.Variable._item_key_to_tuple.<locals>.<genexpr>)r   is_dict_likerH   rW   )r   r   r8   r   r9   _item_key_to_tuple  s    
zVariable._item_key_to_tuplec                 C  s  |  |}t|| j}tdd |D }tdd |D }tdd |D rX| |S | | tdd |D r~| |S g }t	|| j
D ]T\}}t|trt|j
dkr| |  S ||j
d  qt|ts|| qtt|t|kr| |S | |S )a  Prepare an indexing key for an indexing operation.

        Parameters
        ----------
        key : int, slice, array-like, dict or tuple of integer, slice and array-like
            Any valid input for indexing.

        Returns
        -------
        dims : tuple
            Dimension of the resultant variable.
        indexers : IndexingTuple subclass
            Tuple of integer, array-like, or slices to use when indexing
            self._data. The type of this argument indicates the type of
            indexing to perform, either basic, outer or vectorized.
        new_order : Optional[Sequence[int]]
            Optional reordering to do on the result of indexing. If not None,
            the first len(new_order) indexing should be moved to these
            positions.
        c                 s  s0   | ](}t |tr$|jd kr$|j n|V  qdS r   N)rD   rF   rV   r[   r   r   r   r8   r8   r9   r     s    z.Variable._broadcast_indexes.<locals>.<genexpr>c                 s  s0   | ](}t |tjr$|jd kr$| n|V  qdS r   )rD   re   r|   rV   r   r   r8   r8   r9   r     s    c                 s  s   | ]}t |tV  qd S r   )rD   BASIC_INDEXING_TYPESr   r8   r8   r9   r     s     c                 s  s   | ]}t |t V  qd S r   )rD   rF   r   r8   r8   r9   r     s     r@   r   )r   r   Zexpanded_indexerrV   rH   all_broadcast_indexes_basic_validate_indexers_broadcast_indexes_outerziprW   rD   rF   r   _broadcast_indexes_vectorizedappendr    rR   )r   r   rW   r   dr8   r8   r9   _broadcast_indexes  s0    






zVariable._broadcast_indexesc                 C  s(   t dd t|| jD }|t|d fS )Nc                 s  s    | ]\}}t |ts|V  qd S r   )rD   r    r   r   r   r8   r8   r9   r     s    
 z4Variable._broadcast_indexes_basic.<locals>.<genexpr>)rH   r   rW   r   )r   r   rW   r8   r8   r9   r     s    
z!Variable._broadcast_indexes_basicc                 C  s   t | j|D ]\}}t|tst|tsJt|}|jdkrJtd	||j
jdkr| j| | t|krtd	t|t| j|jdkrtd	|jt|d|f|fkrtd	t|j|qdS )	zMake sanity checksr@   zAUnlabeled multi-dimensional array cannot be used for indexing: {}bz?Boolean array size {:d} is used to index array with shape {:s}.z2{}-dimensional boolean indexing is not supported. rW   zBoolean indexer should be unlabeled or on the same dimension to the indexed array. Indexer is on {:s} but the target dimension is {:s}.N)r   rW   rD   r   rF   re   rm   rV   
IndexErrorrL   rc   rd   ro   get_axis_numr   r   ru   )r   r   r   r   r8   r8   r9   r     s>    



 
 zVariable._validate_indexersc                 C  s   t dd t|| jD }g }|D ]`}t|tr6|j}t|tsxt|}|j	dkr`|
t}n|jjdkrxt|\}|| q"|tt |d fS )Nc                 s  s4   | ],\}}t |tst |tr(|jd  n|V  qdS r   )rD   r    rF   rW   r   r8   r8   r9   r     s   
z4Variable._broadcast_indexes_outer.<locals>.<genexpr>r   r   )rH   r   rW   rD   rF   r[   r   re   rm   r   ri   r   rc   rd   nonzeror   r   )r   r   rW   Znew_keyr   r8   r8   r9   r     s    




z!Variable._broadcast_indexes_outerc                 C  s&   t | j}tdd t|| jD S )z<Equivalent numpy's nonzero but returns a tuple of Variables.c                 s  s   | ]\}}t ||V  qd S r   rF   )r   Znzr   r8   r8   r9   r     s     z$Variable._nonzero.<locals>.<genexpr>)re   r   r[   rH   r   rW   )r   Znonzerosr8   r8   r9   _nonzero  s    zVariable._nonzeroc                   s  g }t  }t| j|D ]d\}}t|tr4|| qt|trB|n
t||d}|jj	dkrd|
 \}|| ||j qt }|D ]}||j qg }tt| j|D ]b\}	\}}t|tr||kr tj|| j|  }
||	t| t|f|
 q||	|f qzt| }W n$ tk
r@   td| Y nX dd |D }t|}t  |D ]0\}	}||	| || j|	 } | qb r fddtt|D }nd }|tt||fS )N)rQ   r   z!Dimensions of indexers mismatch: c                 S  s   g | ]
}|j qS r8   r]   )r   rE   r8   r8   r9   
<listcomp>H  s     z:Variable._broadcast_indexes_vectorized.<locals>.<listcomp>c                   s   g | ]}| kr|qS r8   r8   r   iZslice_positionsr8   r9   r   Q  s      )r$   r   rW   rD   r   addrF   r\   rc   rd   r   r   r   rR   	enumeratere   arangeindicessizesinsertr   _broadcast_compat_variablesrJ   r   rH   indexranger   )r   r   	variablesZout_dims_setr   rs   rE   Zvariable_dimsslicesr   rp   Zout_keyZout_dimsZnew_position	new_orderr8   r   r9   r     sL    





z&Variable._broadcast_indexes_vectorizedc                 C  sD   |  |\}}}t| j| }|r8t|tt||}| ||S )a_  Return a new Variable object whose contents are consistent with
        getting the provided key from the underlying data.

        NB. __getitem__ and __setitem__ implement xarray-style indexing,
        where if keys are unlabeled arrays, we index the array orthogonally
        with them. If keys are labeled array (such as Variables), they are
        broadcasted with our usual scheme and then the array is indexed with
        the broadcasted key, like numpy's fancy indexing.

        If you really want to do indexing like `x[x > 0]`, manipulate the numpy
        array `x.values` directly.
        )r   r   r   re   moveaxisr   r   _finalize_indexing_result)r   r   rW   indexerr   r[   r8   r8   r9   __getitem__W  s
    zVariable.__getitem__c                 C  s   | j ||dS )zDUsed by IndexVariable to return IndexVariable objects when possible.rW   r[   )_replacer   rW   r[   r8   r8   r9   r   j  s    z"Variable._finalize_indexing_resultc           	      C  s   |t jkrt | j}| |\}}}| jrzt| jrBt	|}n|}t
| j| }t|| j|}tt|||}n"t|| j}t|t|dd}|rt|tt||}| ||S )z3Index this Variable with -1 remapped to fill_value.ro   r8   )r   NAget_fill_valuerc   r   r   r!   r   r   Zposify_mask_indexerr   Zcreate_maskro   r   wherere   Zlogical_notbroadcast_toru   r   r   r   r   )	r   r   r   rW   r   r   Zactual_indexerr[   r~   r8   r8   r9   _getitem_with_maskn  s    


zVariable._getitem_with_maskc                 C  s   |  |\}}}t|tsxt|}|jt|krLtd|j dt| d|jdkrbtd|}nt||j d |}||j	}|rt
|}|t||j tjf tf  }t||tt|}t| j}|||< dS )z__setitem__ is overloaded to access the underlying numpy values with
        orthogonal indexing.

        See __getitem__ for more details.
        z%shape mismatch: value array of shape z0 could not be broadcast to indexing result with z dimensionsr   r8   N)r   rD   rF   rU   rV   r   rJ   ro   set_dimsr[   r   rm   re   newaxisEllipsisr   r   r   r   )r   r   rs   rW   Zindex_tupler   Z	indexabler8   r8   r9   __setitem__  s"    


 
zVariable.__setitem__zdict[Any, Any]c                 C  s   | j dkri | _ | j S )z0Dictionary of local attributes on this variable.N)r   r   r8   r8   r9   r     s    
zVariable.attrszMapping[Any, Any]c                 C  s   t || _d S r   )rS   r   r   r8   r8   r9   r     s    c                 C  s   | j dkri | _ | j S )z)Dictionary of encodings on this variable.N)r   r   r8   r8   r9   r     s    
zVariable.encodingc                 C  s0   zt || _W n tk
r*   tdY nX d S )Nz)encoding must be castable to a dictionary)rS   r   rJ   r   r8   r8   r9   r     s    ArrayLike | None)r   r?   r[   r;   c                 C  s   | j ||dS )a  Returns a copy of this object.

        If `deep=True`, the data array is loaded into memory and copied onto
        the new object. Dimensions, attributes and encodings are always copied.

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

        Parameters
        ----------
        deep : bool, default: True
            Whether the data array is 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.

        Returns
        -------
        object : Variable
            New object with dimensions, attributes, encodings, and optionally
            data copied from original.

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

        >>> var = xr.Variable(data=[1, 2, 3], dims="x")
        >>> var.copy()
        <xarray.Variable (x: 3)>
        array([1, 2, 3])
        >>> var_0 = var.copy(deep=False)
        >>> var_0[0] = 7
        >>> var_0
        <xarray.Variable (x: 3)>
        array([7, 2, 3])
        >>> var
        <xarray.Variable (x: 3)>
        array([7, 2, 3])

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

        >>> var.copy(data=[0.1, 0.2, 0.3])
        <xarray.Variable (x: 3)>
        array([0.1, 0.2, 0.3])
        >>> var
        <xarray.Variable (x: 3)>
        array([7, 2, 3])

        See Also
        --------
        pandas.DataFrame.copy
        r?   r[   _copy)r   r?   r[   r8   r8   r9   rG     s    :zVariable.copyzdict[int, Any] | None)r   r?   r[   memor;   c                 C  s   |d kr8| j }t|tjr&t|j}|r`t||}n(t|}| j|jkr`t	d
|j| j|rrt| j|n
t| j}|rt| j|n
t| j}| j|||dS )N+Data shape {} must match shape of object {}r[   r   r   )r   rD   r   r   r   rG   deepcopyrU   ro   rJ   rL   r   r   r   )r   r?   r[   r  ndatar   r   r8   r8   r9   r  	  s$     zVariable._copyc                 C  sf   |t krt| j}|t kr(t| j}|t kr<t| j}|t krPt| j}t| ||||ddS )NTrA   )r%   rG   r   r[   r   r   rT   )r   rW   r[   r   r   r8   r8   r9   r   *  s    zVariable._replacec                 C  s   | j ddS NFr>   r  r   r8   r8   r9   __copy__;  s    zVariable.__copy__)r   r  r;   c                 C  s   | j d|dS )NT)r?   r  r  )r   r  r8   r8   r9   __deepcopy__>  s    zVariable.__deepcopy__z"tuple[tuple[int, ...], ...] | Nonec                 C  s   t | jdd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
        --------
        Variable.chunk
        Variable.chunksizes
        xarray.unify_chunks
        chunksN)ru   r   r   r8   r8   r9   r  G  s    zVariable.chunkszMapping[Any, tuple[int, ...]]c                 C  s2   t | jdr*tdd t| j| jjD S i S dS )a  
        Mapping from dimension names to block lengths for this variable'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 variable.chunks because it returns a mapping of dimensions to chunk shapes
        instead of a tuple of chunk shapes.

        See Also
        --------
        Variable.chunk
        Variable.chunks
        xarray.unify_chunks
        r  c                 S  s   i | ]\}}||qS r8   r8   )r   r   cr8   r8   r9   r   f  s      z'Variable.chunksizes.<locals>.<dictcomp>N)r}   r   r"   r   rW   r[   r  r   r8   r8   r9   
chunksizesU  s    zVariable.chunksizeszrint | Literal['auto'] | tuple[int, ...] | tuple[tuple[int, ...], ...] | Mapping[Any, None | int | tuple[int, ...]]z
str | None)r  rQ   lockinline_arraychunks_kwargsr;   c           	        s   ddl m}  dkr&tjdtd i  t tttt	t
fr<nt |d t rhfdd  D  j}t|r| }nlt|tjrt|tj}dtji}ni }t rt	 fd	d
tjD  |j| f|||d|}j|dS )a  Coerce this array's data into a dask array 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, tuple or dict, optional
            Chunk sizes along each dimension, e.g., ``5``, ``(5, 5)`` or
            ``{'x': 5, 'y': 5}``.
        name : str, optional
            Used to generate the name for this array in the internal dask
            graph. Does not need not be unique.
        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.Variable

        See Also
        --------
        Variable.chunks
        Variable.chunksizes
        xarray.unify_chunks
        dask.array.from_array
        r   Nz]None value for 'chunks' is deprecated. It will raise an error in the future. Use instead '{}'categorychunkc                   s   i | ]\}}  ||qS r8   r   )r   r   r  r   r8   r9   r     s      z"Variable.chunk.<locals>.<dictcomp>metac                 3  s   | ]\}}  ||V  qd S r   )r   )r   ns)r  r8   r9   r     s     z!Variable.chunk.<locals>.<genexpr>)rQ   r  r  r]   )Z
dask.arrayr   warningswarnFutureWarningrD   floatr   r   rH   listr(   r   r   r   r   r!   rechunkr   ExplicitlyIndexedZ!ImplicitToExplicitIndexingAdapterr   re   r|   r   ro   Z
from_arrayr   )	r   r  rQ   r  r  r  dar[   r   r8   )r  r   r9   r  l  sF    5
	 
   zVariable.chunkz
np.ndarrayc                 C  sf   | j }t|dr| }t|tdr.| }t|tdrB|j}t|tdrX| }t	|}|S )z9Coerces wrapped data to numpy and returns a numpy.ndarrayr  ZcupyZpintsparse)
r[   r}   r   rD   r   r   Z	magnitudetodensere   rm   r   r8   r8   r9   to_numpy  s    

zVariable.to_numpyc                 C  s   | j |  dS )z>Coerces wrapped data into a numpy array, returning a Variable.r]   )r   r-  r   r8   r8   r9   as_numpy  s    zVariable.as_numpyc                 C  s   ddl }|tjkr$t| j\}}nt| j|}|tkr>d}zt|d|  }W n" t	k
rx   t
| dY nX || j||d}| j|dS )z.
        use sparse-array as backend.
        r   NZcooZas_z is not a valid sparse formatr   r]   )r+  r   r  r{   rc   Zresult_typer%   ru   lowerAttributeErrorrJ   r[   ri   r   )r   sparse_formatr   r+  rc   Z	as_sparser[   r8   r8   r9   
_as_sparse  s    
zVariable._as_sparsec                 C  s*   t | jdr| j| j dS | jddS )z8
        Change backend from sparse to np.array
        r,  r]   Fr>   )r}   r   r   r,  rG   r   r8   r8   r9   	_to_dense   s    zVariable._to_denseraisezMapping[Any, Any] | Noner.   )r   indexersmissing_dimsindexers_kwargsr;   c                   s:   t  |d t | j| t fdd| jD }| | S )a  Return a new array indexed along the specified dimension(s).

        Parameters
        ----------
        **indexers : {dim: indexer, ...}
            Keyword arguments with names matching dimensions and values given
            by integers, slice objects or arrays.
        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
        -------
        obj : Array object
            A new Array with the selected data and dimensions. In general,
            the new variable's data will be a view of this variable's data,
            unless numpy fancy indexing was triggered by using an array
            indexer, in which case the data will be a copy.
        iselc                 3  s   | ]}  |td V  qd S r   r   r   r6  r8   r9   r   (  s     z Variable.isel.<locals>.<genexpr>)r(   r'   rW   rH   )r   r6  r7  r8  r   r8   r:  r9   r9    s    zVariable.iselc                 C  s    t | |}| dd |D S )aG  Return a new object with squeezed data.

        Parameters
        ----------
        dim : None or str or tuple of str, optional
            Selects a subset of the length one dimensions. If a dimension is
            selected with length greater than one, an error is raised. If
            None, all length one dimensions are squeezed.

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

        See Also
        --------
        numpy.squeeze
        c                 S  s   i | ]
}|d qS )r   r8   r   r   r8   r8   r9   r   @  s      z$Variable.squeeze.<locals>.<dictcomp>)r   Zget_squeeze_dimsr9  )r   r   rW   r8   r8   r9   squeeze+  s    zVariable.squeezec                   s   |   }|dkr td | }n|dk r6t| d }ntd }| td f| |f  j}|tjkrtt| j\}}n| j}tt|| j	| }|dkr|dfnd|f fdd| j
D }	tj|||	d|d}
t|
r|
| jj}
| j|
dS )Nr   c                   s   g | ]}| krd nqS )r   r   r8   r;  r   Zdim_padr8   r9   r   U  s     z+Variable._shift_one_dim.<locals>.<listcomp>constantmodeconstant_valuesr]   )r   r   r[   r   r  r{   rc   minabsro   rW   re   padri   r!   r(  r  r   )r   r   countr   axisZkeepZtrimmed_datarc   widthpadsr[   r8   r>  r9   _shift_one_dimB  s,    

zVariable._shift_one_dimc                 K  s6   t ||d}| }| D ]\}}|j|||d}q|S )a  
        Return a new Variable with shifted data.

        Parameters
        ----------
        shifts : mapping of the form {dim: offset}
            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 : Variable
            Variable with the same dimensions and attributes but shifted data.
        shiftr/  )r(   r   rJ  )r   shiftsr   shifts_kwargsresultr   rF  r8   r8   r9   rK  f  s
    zVariable.shiftz#Mapping[Any, int | tuple[int, int]]
pad_optionc                   s6   |r" fddt | j| jjD S  fdd| jD S )Nc                   s(   g | ] \}}| kr||fn | qS r8   r8   )r   r   r!  rO  r8   r9   r     s   z6Variable._pad_options_dim_to_index.<locals>.<listcomp>c                   s    g | ]}| krd n | qS r=  r8   r;  rO  r8   r9   r     s     )r   rW   r[   ro   )r   rP  fill_with_shaper8   rO  r9   _pad_options_dim_to_index  s
    
z"Variable._pad_options_dim_to_indexr?  z*Mapping[Any, int | tuple[int, int]] | Noner/   z<int | tuple[int, int] | Mapping[Any, tuple[int, int]] | NonezFfloat | tuple[float, float] | Mapping[Any, tuple[float, float]] | Noner0   zbool | None)	pad_widthrA  stat_lengthrB  
end_valuesreflect_typer   pad_width_kwargsc                 K  sx  t ||d}|dkr8|dks&|tjkr8t| j\}	}n| j}	t|trV| j|dd}t|trj| |}t|tr~| |}|dkr|dkrdd | jj	D }|
 D ] \}
}t|tjr||f||
< q| |}i }|dk	r||d	< |dk	r||d
< |dk	r
||d< |dk	r||d< tj| jj|	dd|fd|i|}|dkrTtdd}|r`| jnd}t| | j||dS )aN  
        Return a new Variable with padded data.

        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 : str, default: "constant"
            See numpy / Dask docs
        stat_length : int, tuple or mapping of hashable to tuple
            Used in 'maximum', 'mean', 'median', and 'minimum'.  Number of
            values at edge of each axis used to calculate the statistic value.
        constant_values : scalar, tuple or mapping of hashable to tuple
            Used in 'constant'.  The values to set the padded values for each
            axis.
        end_values : scalar, tuple or mapping of hashable to tuple
            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.
        reflect_type : {"even", "odd"}, 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, 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.
        **pad_width_kwargs
            One of pad_width or pad_width_kwargs must be provided.

        Returns
        -------
        padded : Variable
            Variable with the same dimensions and attributes but padded data.
        rE  r?  NT)rQ  )maximumZmeanZmedianZminimumc                 S  s   g | ]}||fqS r8   r8   )r   r!  r8   r8   r9   r     s     z Variable.pad.<locals>.<listcomp>rT  rB  rU  rV  FrG   rA  defaultr   )r(   r   r  r{   rc   rD   rS   rR  r[   ro   r   numbersNumberre   rE  ri   r   r   rT   rW   )r   rS  rA  rT  rB  rU  rV  r   rW  rc   r   r   Zpad_width_by_indexZpad_option_kwargsr   r   r8   r8   r9   rE    sX    6
 








zVariable.padc                   s    | |j  ; }|dkr:t| d td | g}n
td g} fdd|D }t| }t|rz|jj}j	|dS )Nr   c                   s&   g | ]}t d f  |f  jqS r   )r   r[   )r   idxrG  r   r8   r9   r     s     z*Variable._roll_one_dim.<locals>.<listcomp>r]   )
r   ro   r   r   concatenater!   r(  r[   r  r   )r   r   rF  r   arraysr[   r8   r`  r9   _roll_one_dim  s    

zVariable._roll_one_dimc                 K  s2   t ||d}| }| D ]\}}|||}q|S )aF  
        Return a new Variable with rolld data.

        Parameters
        ----------
        shifts : mapping of hashable to int
            Integer offset to roll along each of the given dimensions.
            Positive offsets roll to the right; negative offsets roll to the
            left.
        **shifts_kwargs
            The keyword arguments form of ``shifts``.
            One of shifts or shifts_kwargs must be provided.

        Returns
        -------
        shifted : Variable
            Variable with the same dimensions and attributes but rolled data.
        roll)r(   r   rc  )r   rL  rM  rN  r   rF  r8   r8   r9   rd    s
    zVariable.roll)r7  zHashable | ellipsis)rW   r7  r;   c                G  sz   t |dkr| jddd }ntt|| j|}t |dk sF|| jkrR| jddS | |}t| j|}| j	||dS )a  Return a new Variable object with transposed dimensions.

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

        Returns
        -------
        transposed : Variable
            The returned object has transposed data and dimensions with the
            same attributes as the original.

        Notes
        -----
        This operation returns a view of this variable's data. It is
        lazy for dask-backed Variables but not for numpy-backed Variables.

        See Also
        --------
        numpy.transpose
        r   N   Fr>   r   )
r   rW   rH   r*   rG   r   r   r   	transposer   )r   r7  rW   axesr[   r8   r8   r9   rg  (  s    "
zVariable.transposec                 C  s   |   S r   )rg  r   r8   r8   r9   TX  s    z
Variable.Tc                   s  t |tr|g}|dkr*t|r*| }t| jt| }|rVtd|d| jt| jtfdd|D | j }| j|kr| j	}nT|dk	rt
t|| t fdd|D }t| j	|}n| j	dt|| j   }t||| j| jdd	}|j| S )
a   Return a new variable with given set of dimensions.
        This method might be used to attach new dimension(s) to variable.

        When possible, this operation does not copy this variable's data.

        Parameters
        ----------
        dims : str or sequence of str or dict
            Dimensions to include on the new variable. If a dict, values are
            used to provide the sizes of new dimensions; otherwise, new
            dimensions are inserted with length 1.

        Returns
        -------
        Variable
        Nznew dimensions z+ must be a superset of existing dimensions c                 3  s   | ]}| kr|V  qd S r   r8   r;  )	self_dimsr8   r9   r   {  s      z$Variable.set_dims.<locals>.<genexpr>c                 3  s   | ]} | V  qd S r   r8   r;  )dims_mapr8   r9   r     s     r   TrA   )rD   r   r   r   rp   rR   rW   rJ   rH   r[   rS   r   r   r  r   rV   rF   r   r   rg  )r   rW   ro   r7  Zexpanded_dimsZexpanded_dataZ	tmp_shapeZexpanded_varr8   )rk  rj  r9   r  \  s4    


    zVariable.set_dimszlist[Hashable]r   )rW   new_dimc           	        s   t  t | jks td  || jkr2tdt dkrJ| jddS  fdd| jD }|t  }| j| }|jd t| d }t	|j
|}|jd t| |f }t||| j| jd	d
S )Nzinvalid existing dimensions: Icannot create a new dimension with the same name as an existing dimensionr   Fr>   c                   s   g | ]}| kr|qS r8   r8   r;  rW   r8   r9   r     s      z(Variable._stack_once.<locals>.<listcomp>)re  TrA   )rR   rW   rJ   r   rG   r'  rg  ro   r   rn   r[   rF   r   r   )	r   rW   rl  
other_dims	dim_order	reordered	new_shapenew_datanew_dimsr8   rn  r9   _stack_once  s    

zVariable._stack_oncec                 K  s2   t ||d}| }| D ]\}}|||}q|S )aB  
        Stack any number of existing dimensions into a single new dimension.

        New dimensions will be added at the end, and the order of the data
        along each new dimension will be in contiguous (C) order.

        Parameters
        ----------
        dimensions : mapping of hashable to tuple of hashable
            Mapping of form new_name=(dim1, dim2, ...) describing the
            names of new dimensions, and the existing dimensions that
            they replace.
        **dimensions_kwargs
            The keyword arguments form of ``dimensions``.
            One of dimensions or dimensions_kwargs must be provided.

        Returns
        -------
        stacked : Variable
            Variable with the same attributes but stacked data.

        See Also
        --------
        Variable.unstack
        stack)r(   r   ru  )r   
dimensionsdimensions_kwargsrN  rl  rW   r8   r8   r9   rv    s
    zVariable.stackzMapping[Any, int])rW   old_dimr;   c                   s   t | }t | } | jkr0td  t|| jrHtdt|| j	  krdtd fdd| jD }| g }| j
| }|jdt| | }|j|}	|jdt| | }
t|
|	| j| jddS )	z
        Unstacks the variable without needing an index.

        Unlike `_unstack_once`, this function requires the existing dimension to
        contain the full product of the new dimensions.
        zinvalid existing dimension: rm  zOthe product of the new dimension sizes must equal the size of the old dimensionc                   s   g | ]}| kr|qS r8   r8   r;  ry  r8   r9   r     s      z/Variable._unstack_once_full.<locals>.<listcomp>NTrA   )rH   keysrp   rW   rJ   rR   intersectionmathprodr   rg  ro   r   r[   rn   rF   r   r   )r   rW   ry  new_dim_namesnew_dim_sizesro  rp  rq  rr  rs  rt  r8   rz  r9   _unstack_once_full  s&    	


zVariable._unstack_once_fullzpd.MultiIndex)r   r   r+  r;   c                   s~  |  d }dd |jD }|j}|j} fdd| jD }	tt|jdt|	 | }
|jdt|	 | }|t	j
krt|
t| jk}|rt	| j\}}q| j}t	|}n| j}|rPddlm} t|j }|jdkr|}n8tjd	d |jdd
 D  }t||}tdd |}|tt|j| j| ||
|jd}n tj| j||
|d}||d|< | j||dS )z
        Unstacks this variable given an index to unstack and the name of the
        dimension to which the index refers.
        .c                 S  s   g | ]
}|j qS r8   )r   )r   Zlevr8   r8   r9   r     s     z*Variable._unstack_once.<locals>.<listcomp>c                   s   g | ]}| kr|qS r8   r8   r;  r   r8   r9   r     s      Nr   )COOr@   c                 S  s   g | ]}t |qS r8   )r   )r   r"  r8   r8   r9   r     s     re  c                 S  s   t tj|  S r   )r'  	itertoolschain)xr8   r8   r9   <lambda>      z(Variable._unstack_once.<locals>.<lambda>)Zcoordsr[   r   ro   sorted)r   ro   rc   r   ).) rg  levelsnamescodesrW   rH   r'  ro   r   r   r  r}  r~  r{   rc   r  r+  r  r   rV   r  productmapre   r   ri  r[   ri   rl   Zis_monotonic_increasingZ	full_liker   )r   r   r   r   r+  rq  r  r  r   ro  rr  rt  Zis_missing_valuesrc   r  r  indexesr   Ztuple_indexesr[   r8   r  r9   _unstack_once  sJ    


	
zVariable._unstack_oncec                 K  s2   t ||d}| }| D ]\}}|||}q|S )a;  
        Unstack an existing dimension into multiple new dimensions.

        New dimensions will be added at the end, and the order of the data
        along each new dimension will be in contiguous (C) order.

        Note that unlike ``DataArray.unstack`` and ``Dataset.unstack``, this
        method requires the existing dimension to contain the full product of
        the new dimensions.

        Parameters
        ----------
        dimensions : mapping of hashable to mapping of hashable to int
            Mapping of the form old_dim={dim1: size1, ...} describing the
            names of existing dimensions, and the new dimensions and sizes
            that they map to.
        **dimensions_kwargs
            The keyword arguments form of ``dimensions``.
            One of dimensions or dimensions_kwargs must be provided.

        Returns
        -------
        unstacked : Variable
            Variable with the same attributes but unstacked data.

        See Also
        --------
        Variable.stack
        DataArray.unstack
        Dataset.unstack
        unstack)r(   r   r  )r   rw  rx  rN  ry  rW   r8   r8   r9   r  .  s
     zVariable.unstackc                 C  s   t | |S r   )r   fillnar   r8   r8   r9   r  T  s    zVariable.fillnac                 C  s   t | ||S r   )r   Zwhere_method)r   Zcondotherr8   r8   r9   r  W  s    zVariable.wherec                 C  s    ddl m} |tj| ||ddS )a  
        Return an array whose values are limited to ``[min, max]``.
        At least one of max or min must be given.

        Refer to `numpy.clip` for full documentation.

        See Also
        --------
        numpy.clip : equivalent function
        r   r   r   )r   )r   r   re   clip)r   rC  maxr   r8   r8   r9   r  Z  s    zVariable.clipzCallable[..., Any]r-   zint | Sequence[int] | None)funcr   rG  r   keepdimsr;   c              	     s  |dkrd}|dk	r$|dk	r$t d|dk	r6| |}t b tjddtd |dk	rt|trvt|dkrv|d }|| j	fd	|i|}n|| j	f|}W 5 Q R X t
|d
d| jkr| j}n|dkrt| j nt|| j  |r8t fddt| jD }	t
|d
ddkr(t||	 }n||	 }| j}nt fddt| jD }|dkrhtdd}|rt| jnd}
t|||
dS )a  Reduce this array by applying `func` along some dimension(s).

        Parameters
        ----------
        func : callable
            Function which can be called in the form
            `func(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 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
            `func(x)` without an axis argument).
        keep_attrs : bool, 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
        **kwargs : dict
            Additional keyword arguments passed on to `func`.

        Returns
        -------
        reduced : Array
            Array with summarized data and the indicated dimension(s)
            removed.
        .Nz-cannot supply both 'axis' and 'dim' argumentsignorezMean of empty slicer  r@   r   rG  ro   r8   c                 3  s&   | ]}| krt jntd d V  qd S r   )re   r  r   r   Zremoved_axesr8   r9   r     s   z"Variable.reduce.<locals>.<genexpr>c                 3  s   | ]\}}| kr|V  qd S r   r8   )r   r!  Zadimr  r8   r9   r     s     FrZ  r\  )rJ   r   r#  catch_warningsfilterwarningsRuntimeWarningrD   rH   r   r[   ru   ro   rW   r   rV   re   
atleast_1dZ
asanyarrayr   r   r   rF   )r   r  r   rG  r   r  r   r[   rW   r   r   r8   r  r9   reducei  sJ    )

  

zVariable.reduce
concat_dimoverridec                 C  s  ddl m} t|ts|j\}t|}|d }dd |D }||jkr||}	|j}
tj||	d}|dk	rt	
t|}tj|||	d}nd}	|f|j }
tj||	d}|dd |D |d}t|j}|s|D ]0}|j|jkrtd	t|j d
t|j q| |
|||S )aP  Concatenate variables along a new or existing dimension.

        Parameters
        ----------
        variables : iterable of Variable
            Arrays to stack together. Each variable is expected to have
            matching dimensions and shape except for along the stacked
            dimension.
        dim : str or DataArray, optional
            Name of the dimension to stack along. This can either be a new
            dimension name, in which case it is added along axis=0, or an
            existing dimension name, in which case the location of the
            dimension is unchanged. Where to insert the new dimension is
            determined by the first variable.
        positions : None or list of array-like, optional
            List of integer arrays which specifies the integer positions to
            which to assign each dataset along the concatenated dimension.
            If not supplied, objects are concatenated in the provided order.
        shortcut : bool, optional
            This option is used internally to speed-up groupby operations.
            If `shortcut` is True, some checks of internal consistency between
            arrays to concatenate are skipped.
        combine_attrs : {"drop", "identical", "no_conflicts", "drop_conflicts",                          "override"}, default: "override"
            String indicating how to combine attrs of the objects being merged:

            - "drop": empty attrs on returned Dataset.
            - "identical": all attrs must be the same on every object.
            - "no_conflicts": attrs from all objects are combined, any that have
              the same name must also have the same value.
            - "drop_conflicts": attrs from all objects are combined, any that have
              the same name but different values are dropped.
            - "override": skip comparing and copy attrs from the first dataset to
              the result.

        Returns
        -------
        stacked : Variable
            Concatenated Variable formed by stacking all the supplied variables
            along the given dimension.
        r   merge_attrsc                 S  s   g | ]
}|j qS r8   r]   r   r   r8   r8   r9   r     s     z#Variable.concat.<locals>.<listcomp>rG  Nc                 S  s   g | ]
}|j qS r8   r\  r   varr8   r8   r9   r     s     combine_attrszVariable has dimensions z# but first Variable has dimensions )xarray.core.merger  rD   r   rW   r'  r   r   ra  r   inverse_permutationre   takerv  rS   r   rJ   )clsr   r   	positionsshortcutr  r  	first_varrb  rG  rW   r[   r   r   r   r  r8   r8   r9   concat  s8    2


 
zVariable.concatc              	   C  sT   t |d|}z(| j|jko2| j|jkp2|| j|jW S  ttfk
rN   Y dS X dS )aO  True if two Variables have the same dimensions and values;
        otherwise False.

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

        This method is necessary because `v1 == v2` for Variables
        does element-wise comparisons (like numpy.ndarrays).
        rE   FN)ru   rW   r   r[   rI   r1  r   r  equivr8   r8   r9   equals  s    
zVariable.equalsc              	   C  s<   zt | |\} }W n ttfk
r,   Y dS X | j||dS )zTrue if two Variables have the values after being broadcast against
        each other; otherwise False.

        Variables can still be equal (like pandas objects) if they have NaN
        values in the same locations.
        Fr  )broadcast_variablesrJ   r1  r  r  r8   r8   r9   broadcast_equals1  s
    zVariable.broadcast_equalsc              	   C  s@   z t | j|jo| j||dW S  ttfk
r:   Y dS X dS )z(Like equals, but also checks attributes.r  FN)r   Z
dict_equivr   r  rI   r1  r  r8   r8   r9   	identical>  s     zVariable.identicalc                 C  s   | j ||dS )zTrue if the intersection of two Variable's non-null data is
        equal; otherwise false.

        Variables can thus still be equal if there are locations where either,
        or both, contain NaN values.
        r  )r  r  r8   r8   r9   no_conflictsG  s    zVariable.no_conflictslinearr   zstr | Sequence[Hashable] | Noner1   zQuantileMethods | None)qr   methodr   skipnainterpolationr;   c                   sz  ddl m} |dk	r4tdt |dkr0td|}|sL|dkrT| jjdkrTtj	 ntj
 |dkrltdd	}t|}ttj|tjd
}|dkr| j}t|r|g} fdd}	tddt| d d}
ttjtdkr||
|d}n&|dkr
td| d||
|d}||	| |gt|dggtjgtdt|idd|d	}|dd}|rh|d}|rv| j|_|S )aM  Compute the qth quantile of the data along the specified dimension.

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

        Parameters
        ----------
        q : float or sequence of float
            Quantile to compute, which must be between 0 and 1
            inclusive.
        dim : str or sequence of str, 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, 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.
        skipna : bool, 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 : Variable
            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, pandas.Series.quantile, Dataset.quantile
        DataArray.quantile

        References
        ----------
        .. [1] R. J. Hyndman and Y. Fan,
           "Sample quantiles in statistical packages,"
           The American Statistician, 50(4), pp. 361-365, 1996
        r   r   NzAThe `interpolation` argument to quantile was renamed to `method`.r  z.Cannot pass interpolation and method keywords!ZcfOFrZ  rt   c                   s   t  | f|ddS )Nr   re  )re   r   )Znpar   Z_quantile_funcr8   r9   _wrapper  s    z#Variable.quantile.<locals>._wrapperre  r@   z1.22.0)r  rG  r  )r  r0  ZhigherZmidpointZnearestzInterpolation method 'z-' requires numpy >= 1.22 or is not supported.)r  rG  r  quantile)Zoutput_sizesZparallelized)Zinput_core_dimsZexclude_dimsZoutput_core_dimsZoutput_dtypesZdask_gufunc_kwargsr   r   .)r   r   r#  r$  r%  rI   rc   rd   re   Znanquantiler  r   r   rM   r  rm   Zfloat64rW   r   r   r   __version__rJ   rR   rS   rg  r<  r   r   )r   r  r   r  r   r  r  r   Zscalarr  rG  r   rN  r8   r  r9   r  P  s\    P





zVariable.quantilec           	      C  s   t d stdddl}| j}t|r0tdn t|tjsPtdt	| d| 
|}| jjdkrl|jn|j}|||d	}|rtjt| |d
d}|| }t| j|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 : str
            Dimension over which to compute rank.
        pct : bool, optional
            If True, compute percentage ranks, otherwise compute integer ranks.

        Returns
        -------
        ranked : Variable

        See Also
        --------
        Dataset.rank, DataArray.rank
        Zuse_bottleneckz`rank requires bottleneck to be enabled. Call `xr.set_options(use_bottleneck=True)` to enable it.r   Nzzrank does not work for arrays stored as dask arrays. Load the data via .compute() or .load() prior to calling this method.zrank is not implemented for z	 objects.fr  T)rG  r  )r   RuntimeErrorZ
bottleneckr[   r!   rI   rD   re   r|   rT   r   rc   rd   ZnanrankdataZrankdatasumisnanrF   rW   )	r   r   ZpctZbnr[   rG  r  ZrankedrF  r8   r8   r9   rank  s&    
zVariable.rankc              
     s  |t jkr*t  j\}} j|dd}n
 j} }t|rtdddg|||gD ](\}}	t|	sTtd| d|	dqT|g}t	|}
t|r|g|
 }t|r|g|
 }t|r|g|
 }t	|t	|kst	|t	|kst	|t	|krtd	|d
|d|d|d	i }t|||D ]D\}}}|r^|d }|d | }||f||< n|d df||< q,|j
|d|d} fdd|D } jt| }t|tj|j||dS )a!  
        Make a rolling_window along dim and add a new_dim to the last place.

        Parameters
        ----------
        dim : str
            Dimension over which to compute rolling_window.
            For nd-rolling, should be list of dimensions.
        window : int
            Window size of the rolling
            For nd-rolling, should be list of integers.
        window_dim : str
            New name of the window dimension.
            For nd-rolling, should be list of strings.
        center : bool, default: False
            If True, pad fill_value for both ends. Otherwise, pad in the head
            of the axis.
        fill_value
            value to be filled.

        Returns
        -------
        Variable that is a view of the original array with a added dimension of
        size w.
        The return dim: self.dims + (window_dim, )
        The return shape: self.shape + (window, )

        Examples
        --------
        >>> v = Variable(("a", "b"), np.arange(8).reshape((2, 4)))
        >>> v.rolling_window("b", 3, "window_dim")
        <xarray.Variable (a: 2, b: 4, window_dim: 3)>
        array([[[nan, nan,  0.],
                [nan,  0.,  1.],
                [ 0.,  1.,  2.],
                [ 1.,  2.,  3.]],
        <BLANKLINE>
               [[nan, nan,  4.],
                [nan,  4.,  5.],
                [ 4.,  5.,  6.],
                [ 5.,  6.,  7.]]])

        >>> v.rolling_window("b", 3, "window_dim", center=True)
        <xarray.Variable (a: 2, b: 4, window_dim: 3)>
        array([[[nan,  0.,  1.],
                [ 0.,  1.,  2.],
                [ 1.,  2.,  3.],
                [ 2.,  3., nan]],
        <BLANKLINE>
               [[nan,  4.,  5.],
                [ 4.,  5.,  6.],
                [ 5.,  6.,  7.],
                [ 6.,  7., nan]]])
        FrY  window
window_dimcenterz	Expected =z to be a scalar like 'dim'.zR'dim', 'window', 'window_dim', and 'center' must be the same length. Received dim=z	, window=z, window_dim=z, and center=.rf  r@   r   r?  r@  c                   s   g | ]}  |qS r8   r  r;  r   r8   r9   r   }	  s     z+Variable.rolling_window.<locals>.<listcomp>)Zwindow_shaperG  )r   r  r{   rc   ri   r   rM   r   rJ   r   rE  rW   rH   rF   r   Zsliding_window_viewr[   )r   r   r  r  r  r   rc   r  rQ   argZnrollrI  r   wincentstartendZpaddedrG  rt  r8   r   r9   rolling_window	  sb    9

 






  zVariable.rolling_windowexactleftc                   s    fdd|  D }|dkr(tdd}|r4 j}nd}|sH j|dS  |||\}}	t|tr|}
tt|
d}|dkrt	|
 d j||fd|	i||d	S )
z+
        Apply reduction function.
        c                   s    i | ]\}}| j kr||qS r8   rn  r   r   r8   r9   r   	  s     
  z$Variable.coarsen.<locals>.<dictcomp>NTrZ  r\  z is not a valid method.rG  )r[   r   )
r   r   r   r   coarsen_reshaperD   r   ru   r   	NameError)r   windowsr  boundarysider   r   r   Zreshapedrh  rQ   r8   r   r9   coarsen	  s    

zVariable.coarsenc                   sb  t  s  fdd D  t s@fdd D fdd  D  fdd D  D ]$\}}|dkrttd| d| qt| } D ]"\}}|j| | }t|| } | d	kr|| |krtd
| d| dq | dkrT| dkr2||t	d|| i}n |||  }	||t	|	di}q | dkr|| | }
|
dk r|
|7 }
| dkr|d|
fi}n||
dfi}|j
|dd}qtd | qg }g }d}t|jD ]j\}}|kr:|j| }|t||   ||  |d7 }|||  n||j|  q|j|t|fS )z8
        Construct a reshaped-array for coarsen
        c                   s   i | ]
}| qS r8   r8   r;  )r  r8   r9   r   	  s      z,Variable.coarsen_reshape.<locals>.<dictcomp>c                   s   i | ]
}| qS r8   r8   r;  )r  r8   r9   r   	  s      c                   s   i | ]\}}| kr||qS r8   r8   r   r  r8   r9   r   	  s       c                   s   i | ]\}}| kr||qS r8   r8   r   r  r8   r9   r   	  s       r   zwindow must be > 0. Given z for dimension r  z&Could not coarsen a dimension of size z with window z9 and boundary='exact'. Try a different 'boundary' option.Ztrimr  NrE  r?  )rA  zE{} is invalid for boundary. Valid option is 'exact', 'trim' and 'pad'r@   )r   r   r{  r   rJ   ro   Z_get_axis_numr   r9  r   rE  rI   rL   r   rW   r   r[   rn   rH   )r   r  r  r  r   r  rE   r   r!  ZexcessrE  rS  ro   rh  Z
axis_countr   r8   )r  r  r  r9   r  	  sd    




zVariable.coarsen_reshape)r   c                 C  s0   ddl m} |dkrtdd}|tj| d|dS )a  Test each value in the array for whether it is a missing value.

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

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

        Examples
        --------
        >>> var = xr.Variable("x", [1, np.nan, 3])
        >>> var
        <xarray.Variable (x: 3)>
        array([ 1., nan,  3.])
        >>> var.isnull()
        <xarray.Variable (x: 3)>
        array([False,  True, False])
        r   r   NFrZ  r   r   r   )r   r   r   r   isnullr   r   r   r8   r8   r9   r  	  s    
zVariable.isnullc                 C  s0   ddl m} |dkrtdd}|tj| d|dS )a  Test each value in the array for whether it is not a missing value.

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

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

        Examples
        --------
        >>> var = xr.Variable("x", [1, np.nan, 3])
        >>> var
        <xarray.Variable (x: 3)>
        array([ 1., nan,  3.])
        >>> var.notnull()
        <xarray.Variable (x: 3)>
        array([ True, False,  True])
        r   r   NFrZ  r   r  )r   r   r   r   notnullr  r8   r8   r9   r  
  s    
zVariable.notnullc                 C  s   | j | jjdS )zn
        The real part of the variable.

        See Also
        --------
        numpy.ndarray.real
        r]   )r   r[   realr   r8   r8   r9   r  )
  s    	zVariable.realc                 C  s   | j | jjdS )zs
        The imaginary part of the variable.

        See Also
        --------
        numpy.ndarray.imag
        r]   )r   r[   imagr   r8   r8   r9   r  4
  s    	zVariable.imagc                 C  s   t | j|S r   )rF   rW   )r   rY   contextr8   r8   r9   __array_wrap__?
  s    zVariable.__array_wrap__c              
   O  sj   | dd }|d krtdd}tjdd6 | || jf||}|rP| j|_|W  5 Q R  S Q R X d S )Nr   TrZ  r  r   )popr   re   errstater  r[   r   )r   r  r   r   r   rN  r8   r8   r9   	_unary_opB
  s    
zVariable._unary_opc              	   C  s   t |tjtjfrtS |r>tt| t|r>t|| \}}}nt| |\}}}tdd}|rb| j	nd }t
jdd |s|||n|||}	W 5 Q R X t||	|d}
|
S )NFrZ  r  r  r\  )rD   xrr=   DatasetNotImplemented
issubclassrT   _broadcast_compat_datar   r   re   r  rF   )r   r  r  Z	reflexive
other_data	self_datarW   r   r   rs  rN  r8   r8   r9   
_binary_opL
  s    
zVariable._binary_opc              	   C  s^   t |tjrtdt| |\}}}|| jkr6tdtjdd |||| _	W 5 Q R X | S )Nz+cannot add a Dataset to a Variable in-placez0dimensions cannot change for in-place operationsr  r  )
rD   r  r  rI   r  rW   rJ   re   r  rp   )r   r  r  r  r  rW   r8   r8   r9   _inplace_binary_op\
  s    
zVariable._inplace_binary_opc                 C  s&   t | j|||}t| | j|| jS )zuA (private) method to convert datetime array to numeric dtype
        See duck_array_ops.datetime_to_numeric
        )r   Zdatetime_to_numericr[   rT   rW   r   )r   offsetZdatetime_unitrc   Znumeric_arrayr8   r8   r9   _to_numericf
  s       zVariable._to_numericr   z
int | Nonez#Variable | dict[Hashable, Variable])	argminmaxr   rG  r   r  r;   c                   s4  |dkr |dkr t jdtdd tt|}|dkr8j}|dks\|dk	s\t|tr\t|trpj	|||||dS d}d}|jkrd	| }|d7 }qx
||i}	|	jdd
  tfdd|D }
|	j	|d
|d}t|j|
} fddt||D }|dkrtdd}|r0| D ]}j|_q |S )zApply argmin or argmax over one or more dimensions, returning the result as a
        dict of DataArray that can be passed directly to isel.
        NzBehaviour of argmin/argmax with neither dim nor axis argument will change to return a dict of indices of each dimension. To get a single, flat index, please use np.argmin(da.data) or np.argmax(da.data) instead of da.argmin() or da.argmax().   )
stacklevel.)r   rG  r   r  Z_unravel_argminmax_dim_0r@   Z_unravel_argminmax_dim_re  c                 3  s   | ]} j | V  qd S r   )r   r;  r   r8   r9   r   
  s     z.Variable._unravel_argminmax.<locals>.<genexpr>)rG  r  c                   s   i | ]\}}|t  |d qS )r   r   )r   r   r   )result_dimsr8   r9   r   
  s    z/Variable._unravel_argminmax.<locals>.<dictcomp>FrZ  )r#  r$  DeprecationWarningru   r   rW   rD   r   r   r  rv  rH   Zunravel_indexr[   r   r   rp   r   )r   r  r   rG  r   r  Zargminmax_funcZ
newdimnamerF  ZstackedZreduce_shapeZresult_flat_indicesZresult_unravelled_indicesrN  r   r8   )r  r   r9   _unravel_argminmaxo
  s\    	
    


 


zVariable._unravel_argminmax)r   rG  r   r  r;   c                 C  s   |  d||||S )a  Index or indices of the minimum of the Variable over one or more dimensions.
        If a sequence is passed to 'dim', then result returned as dict of Variables,
        which can be passed directly to isel(). If a single str is passed to 'dim' then
        returns a Variable 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, optional
            Axis over which to apply `argmin`. Only one of the 'dim' and 'axis' arguments
            can be supplied.
        keep_attrs : bool, optional
            If True, the 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, 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 : Variable or dict of Variable

        See Also
        --------
        DataArray.argmin, DataArray.idxmin
        argminr  r   r   rG  r   r  r8   r8   r9   r  
  s    +zVariable.argminc                 C  s   |  d||||S )a  Index or indices of the maximum of the Variable over one or more dimensions.
        If a sequence is passed to 'dim', then result returned as dict of Variables,
        which can be passed directly to isel(). If a single str is passed to 'dim' then
        returns a Variable 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, optional
            Axis over which to apply `argmin`. Only one of the 'dim' and 'axis' arguments
            can be supplied.
        keep_attrs : bool, optional
            If True, the 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, 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 : Variable or dict of Variable

        See Also
        --------
        DataArray.argmax, DataArray.idxmax
        argmaxr  r  r8   r8   r9   r  
  s    +zVariable.argmax)NNF)TF)TN)TNN)N)Nr5  )N)F)Nr?  NNNNN)N)N)N)N)NN)NNNF)r  NFr  )Nr  NNN)F)r  r  N)N)N)N)F)NNNN)NNNN)tr4   r5   r6   r7   	__slots__r   propertyrc   ro   r   r   r[   setterri   r   r   r   r   r   r   r   r   r   r   r   rp   r   r   aliasr   rX   r   r   r   r   rW   r   r   r   r   r   r   r   r   r   r   r   r  r  r	  r   r   rG   r  r%   r   r  r  __hash__r  r  r  rF  Z_array_counterr  r-  r.  r3  r4  r9  r<  rJ  rK  rR  rE  rc  rd  rg  ri  r  ru  rv  r  r  r  r  r  r  r  classmethodr  r   Zarray_equivr  r  r  Zarray_notnull_equivr  r  r  r  r  r  r  r  r  r  r  r  r  r  r&  r  r  r  r  r8   r8   r8   r9   rF   B  sr  




K



:8(
  >  #
g
 #$      l01 )D&   ]   X	     6 
q    
C""





	$H   "/   rF   c                      sB  e Zd ZdZdZd< fdd	Zdd Zd	d
 Zej	j
dd Z	ejj
dd Zi dddfddZeefddZdd Zdd Zdd Zed=ddZd>ddd d!d"Zd? fd#d$	Zd%d& Zd d'd(d)Zeed*Zd+d'd,d-Zd+d'd.d/Zed0d'd1d2Zd3d4 Zed5d'd6d7Z e j
d8d'd9d7Z d:d; Z!  Z"S )@rP   af  Wrapper for accommodating a pandas.Index in an xarray.Variable.

    IndexVariable preserve loaded values in the form of a pandas.Index instead
    of a NumPy array. Hence, their values are immutable and must always be one-
    dimensional.

    They also have a name property, which is the name of their sole dimension
    unless another name is given.
    r8   NFc                   sN   t  ||||| | jdkr2tt| j dt| jtsJt| j| _d S )Nr@   z objects must be 1-dimensional)	superr   rV   rJ   rT   r4   rD   r   r   r   rK   r8   r9   r     s
    
zIndexVariable.__init__c                 C  s(   ddl m} |t| | j| jj| jfS r   )r   r   rT   r   r   r   r   r   r8   r8   r9   r   &  s    zIndexVariable.__dask_tokenize__c                 C  s   | S r   r8   r   r8   r8   r9   r   ,  s    zIndexVariable.loadc                 C  s   t d| jdd S )NzQCannot assign to the .data attribute of dimension coordinate a.k.a IndexVariable ]. Please use DataArray.assign_coords, Dataset.assign_coords or Dataset.assign as appropriate.rJ   rQ   r   r8   r8   r9   r[   1  s    zIndexVariable.datac                 C  s   t d| jdd S )NzSCannot assign to the .values attribute of dimension coordinate a.k.a IndexVariable r  r  r   r8   r8   r9   rp   8  s    zIndexVariable.valuesc                 C  s   | j ddS r  rY  )r   r  rQ   r  r  r8   r8   r9   r  ?  s    zIndexVariable.chunkc                 C  s   | j ddS r  rY  )r   r2  r   r8   r8   r9   r3  C  s    zIndexVariable._as_sparsec                 C  s   | j ddS r  rY  r   r8   r8   r9   r4  G  s    zIndexVariable._to_densec                 C  s4   t |dddkr"t||| j| jS | j||dS d S )NrV   r   r@   r   )ru   rF   r   r   r   r   r8   r8   r9   r   K  s    z'IndexVariable._finalize_indexing_resultc                 C  s   t t| j dd S )Nz values cannot be modified)rI   rT   r4   )r   r   rs   r8   r8   r9   r	  R  s    zIndexVariable.__setitem__r  r  c                   s   ddl m} t|ts|j\}t|}|d }t fdd|D rLtddd |D }|sdg }	n8|d |dd	 }	|d	k	rt	
t|}
|	|
}	t|	|}	|d
d |D |d}|s|D ]}|j|jkrtdqĈ |j|	|S )zSpecialized version of Variable.concat for IndexVariable objects.

        This exists because we want to avoid converting Index objects to NumPy
        arrays, if possible.
        r   r  c                 3  s   | ]}t |  V  qd S r   )rD   r  r  r8   r9   r   k  s     z'IndexVariable.concat.<locals>.<genexpr>zOIndexVariable.concat requires that all input variables be IndexVariable objectsc                 S  s   g | ]}|j jqS r8   )r   r   r  r8   r8   r9   r   q  s     z(IndexVariable.concat.<locals>.<listcomp>r@   Nc                 S  s   g | ]
}|j qS r8   r\  r  r8   r8   r9   r     s     r  zinconsistent dimensions)r  r  rD   r   rW   r'  rz   rI   r   r   r  re   ra  r  r,   rJ   )r  r   r   r  r  r  r  r  r  r[   r   r   r  r8   r  r9   r  U  s4    


 
zIndexVariable.concatTr   r
  r  c                 C  s   |dkr| j j|d}n(t|}| j|jkr@td|j| j|rPt| jn
t| j}|rlt| jn
t| j}| j	|||dS )aK  Returns a copy of this object.

        `deep` is ignored since data is stored in the form of
        pandas.Index, which is already immutable. Dimensions, attributes
        and encodings are always copied.

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

        Parameters
        ----------
        deep : bool, default: True
            Deep is ignored when data is given. Whether the data array is
            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.

        Returns
        -------
        object : Variable
            New object with dimensions, attributes, encodings, and optionally
            data copied from original.
        Nr>   r  r  )
r   rG   rU   ro   rJ   rL   r  r   r   r   )r   r?   r[   r  r   r   r8   r8   r9   rG     s     zIndexVariable.copyc              	     sZ   |d k	rt  ||S t|d|}z| j|jko8| |W S  ttfk
rT   Y dS X d S )NrE   F)r  r  ru   rW   _data_equalsrI   r1  r  r  r8   r9   r    s    zIndexVariable.equalsc                 C  s   |   |  S r   )r   r  )r   r  r8   r8   r9   r    s    zIndexVariable._data_equalsr:   c                 C  s   | j ddS )r   Fr>   rY  r   r8   r8   r9   rX     s    zIndexVariable.to_index_variabler   r   c                   sV    j dkst jj}t|tjrF fddt|jD }|	|}n|	 j
}|S )Nr@   c                   s(   g | ] \}}|p" j d   d| qS )r   Z_level_rn  )r   r   rQ   r   r8   r9   r     s   z+IndexVariable._to_index.<locals>.<listcomp>)rV   AssertionErrorr   r   rD   rN   
MultiIndexr   r  Z	set_namesrQ   )r   r   Zvalid_level_namesr8   r   r9   r     s    
zIndexVariable._to_indexc                 C  s0   |   }t| jdd}|dk	r(||S |S dS )r   levelN)r   ru   r   get_level_values)r   r   r
  r8   r8   r9   r     s
    
zIndexVariable.to_indexzlist[str] | Nonec                 C  s"   |   }t|tjr|jS dS dS )z_Return MultiIndex level names or None if this IndexVariable has no
        MultiIndex.
        N)r   rD   rN   r	  r  )r   r   r8   r8   r9   level_names  s    zIndexVariable.level_namesc                 C  s:   | j dkrtd| jd|  }t| | j||S )z9Return a new IndexVariable from a given MultiIndex level.NzIndexVariable z has no MultiIndex)r  rJ   rQ   r   rT   rW   r  )r   r
  r   r8   r8   r9   get_level_variable  s    
z IndexVariable.get_level_variabler   c                 C  s
   | j d S )Nr   rn  r   r8   r8   r9   rQ     s    zIndexVariable.namer   c                 C  s   t dd S )Nz,cannot modify name of IndexVariable in-place)r1  r   r8   r8   r9   rQ     s    c                 C  s   t dd S )NzHValues of an IndexVariable are immutable and can not be modified inplace)rI   )r   r  r  r8   r8   r9   r    s    z IndexVariable._inplace_binary_op)NNF)r  NFr  )TN)N)#r4   r5   r6   r7   r  r   r   r   rF   r[   r  rp   r  r%   r3  r4  r   r	  r  r  rG   r  r  rX   r   r  r   r   r   r  r  r  rQ   r  __classcell__r8   r8   r  r9   rP     sF   
	

    3(

rP   
Coordinatec                 C  s   i }| D ]}|j }tt|t|k r8tdt|t||jD ]B\}}||kr^|||< qD|| |krDtd|d|| |f qDq|S )Nz1broadcasting cannot handle duplicate dimensions: zLoperands cannot be broadcast together with mismatched lengths for dimension z: )rW   r   rR   rJ   r'  r   ro   )r   Zall_dimsr  Zvar_dimsr   r"  r8   r8   r9   _unified_dims  s    
r  c                    s"   t t|  t  fdd| D S )zCreate broadcast compatible variables, with the same dimensions.

    Unlike the result of broadcast_variables(), some variables may have
    dimensions of size 1 instead of the size of the broadcast dimension.
    c                 3  s&   | ]}|j  kr| n|V  qd S r   rW   r  r  rn  r8   r9   r   #  s     z._broadcast_compat_variables.<locals>.<genexpr>)rH   r  r   r8   rn  r9   r     s    r   ztuple[Variable, ...])r   r;   c                    s(   t |  t t fdd| D S )a  Given any number of variables, return variables with matching dimensions
    and broadcast data.

    The data on the returned variables will be a view of the data on the
    corresponding original arrays, but dimensions will be reordered and
    inserted so that both broadcast arrays have the same dimensions. The new
    dimensions are sorted in order of appearance in the first variable's
    dimensions followed by the second variable's dimensions.
    c                 3  s&   | ]}|j kr| n|V  qd S r   r  r  rk  Z
dims_tupler8   r9   r   2  s    z&broadcast_variables.<locals>.<genexpr>)r  rH   r  r8   r  r9   r  &  s
    
r  c                   sR   t  fdddD r8t|  \}}|j}|j}|j}n| j} }| j}|||fS )Nc                 3  s   | ]}t  |V  qd S r   )r}   )r   attrr  r8   r9   r   8  s     z)_broadcast_compat_data.<locals>.<genexpr>)rW   r[   ro   r   )r   r   r[   rW   )r   r  Znew_selfZ	new_otherr  r  rW   r8   r  r9   r  7  s    r  r  r  c                 C  sB   t | } tdd | D r,t| ||||S t| ||||S dS )a  Concatenate variables along a new or existing dimension.

    Parameters
    ----------
    variables : iterable of Variable
        Arrays to stack together. Each variable is expected to have
        matching dimensions and shape except for along the stacked
        dimension.
    dim : str or DataArray, optional
        Name of the dimension to stack along. This can either be a new
        dimension name, in which case it is added along axis=0, or an
        existing dimension name, in which case the location of the
        dimension is unchanged. Where to insert the new dimension is
        determined by the first variable.
    positions : None or list of array-like, optional
        List of integer arrays which specifies the integer positions to which
        to assign each dataset along the concatenated dimension. If not
        supplied, objects are concatenated in the provided order.
    shortcut : bool, optional
        This option is used internally to speed-up groupby operations.
        If `shortcut` is True, some checks of internal consistency between
        arrays to concatenate are skipped.
    combine_attrs : {"drop", "identical", "no_conflicts", "drop_conflicts",                      "override"}, default: "override"
        String indicating how to combine attrs of the objects being merged:

        - "drop": empty attrs on returned Dataset.
        - "identical": all attrs must be the same on every object.
        - "no_conflicts": attrs from all objects are combined, any that have
          the same name must also have the same value.
        - "drop_conflicts": attrs from all objects are combined, any that have
          the same name but different values are dropped.
        - "override": skip comparing and copy attrs from the first dataset to
          the result.

    Returns
    -------
    stacked : Variable
        Concatenated Variable formed by stacking all the supplied variables
        along the given dimension.
    c                 s  s   | ]}t |tV  qd S r   )rD   rP   r  r8   r8   r9   r   w  s     zconcat.<locals>.<genexpr>N)r'  r   rP   r  rF   )r   r   r  r  r  r8   r8   r9   r  F  s    0r  zMapping[Any, Variable]zdict[Hashable, int]c                 C  s   i }i }dd |   D }|   D ]\}}t|j|jD ]p\}}||krXtd|d||krr|||< |||< q8|| |kr8td|d| d|d||  d|
q8q"|S )	zCalculate the dimensions corresponding to a set of variables.

    Returns dictionary mapping from dimension names to sizes. Raises ValueError
    if any of the dimension sizes conflict.
    c                 S  s   h | ]\}}|j s|qS r8   rn  r   r8   r8   r9   	<setcomp>  s      z'calculate_dimensions.<locals>.<setcomp>z
dimension z$ already exists as a scalar variablez conflicting sizes for dimension z	: length z on z and length )r   r   rW   ro   rJ   )r   rW   Z	last_usedZscalar_varsr   r  r   r   r8   r8   r9   calculate_dimensions}  s"    

$r  )N)F)r  NFr  )b
__future__r   rG   r  r}  r]  r#  ra   r   typingr   r   r   r   r   r	   r
   r   r   Znumpyre   ZpandasrN   Znumpy.typingr   Zpackaging.versionr   Zxarrayr  Zxarray.corer   r   r   r   r   r   r   Zxarray.core.arithmeticr   Zxarray.core.commonr   Zxarray.core.indexingr   r   r   r   r   Zxarray.core.optionsr   r   Zxarray.core.pycompatr   r    r!   Zxarray.core.utilsr"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r)  rO   rv   r   r   Zxarray.core.typesr-   r.   r/   r0   r1   r2   rg   rJ   r3   r\   r^   rj   rq   rr   rU   r   rF   rP   r  r  r  r   r  r  r  r  r8   r8   r8   r9   <module>   s   ,$4
 

U
<                   a u
    
7