U
    Cvf                     @  s  d Z 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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mZmZmZmZmZmZm Z m!Z! ddl"Z#ddl$Z%erddl&m'Z'm(Z(m)Z) edZ*edZ+ed	Z,d
d
d
dddZ-dd
d
dddddZ.dd
ddddZ/ddddZ0dd Z1dd Z2d	d	d d!d"d#Z3d$d% Z4d&d'd(d)d*Z5e3fd+d+d,dd-d.d/Z6e3fd0d+d,dd-d1d2Z7d3d4d5d6d7Z8d3d d5d8d9Z9d3d:d5d;d<Z:d3d d5d=d>Z;d?d@d
dAdBdCdDZ<dEdF Z=z*ej>dGkr*ddHlm?Z? nddHl@m?Z? W n4 eAk
rl   erT ndd3d d dJdKdLZBY nX dd3d dMdJdNdLZBd3d dOdPdQZCd3dRd5dSdTZDd3dRd5dUdVZEe3fd+d+d,d dWdXdYZFe3fd+d+d,d0d-dZd[ZGe3fd+d+d,d0d-d\d]ZHG d^d_ d_ee*e+f ZId_d`dadbZJG dcdd ddee*e+f ZKG dedf dfee, ZLG dgdh dhZMG didj djeMZNG dkdl dlZOejPdmdn ZQd
d dodpdqZRddsd`dtduZSddvd`dwdxZTddvd`dydzZUd d`d{d|ZVd3dMd}d~dZWd3dd}ddZXd3dd}ddZYd+ddddZZdd Z[G dd dee*e+f Z\ddddddddZ]ddddddZ^dddddddZ_dddddddZ`edddZae!dIdIdddd dddddZbe!dIdddd dddddZbdIdIdddd d ddddZbe!dIdIdddd dddddZce!dIdddd dddddZcdIdIdddd d ddddZcddddddZdedZeG dd deee ZfG ddÄ deZgegjhZiddń Zjd d`ddǄZkd
d dȜddʄZlddd`dd̈́ZmdddτZndS )z(Internal utilities; not for external use    )annotationsN)Enum)TYPE_CHECKINGAnyCallable
Collection	ContainerGenericHashableIterableIteratorLiteralMappingMutableMapping
MutableSetSequenceTypeVarcastoverload)DimsErrorOptionsWithWarnOrderedDimsKVTstr)old_namenew_namereturnc                 C  s   |  d| dS )Nz has been deprecated. Use z	 instead. )r   r   r   r   5/tmp/pip-unpacked-wheel-h316xyqg/xarray/core/utils.pyalias_messageQ   s    r!      intNone)r   r   
stacklevelr   c                 C  s   t jt| |t|d d S )N)r%   )warningswarnr!   FutureWarning)r   r   r%   r   r   r    alias_warningU   s
      r)   zCallable[..., T])objr   r   c                   s8   t tstt  fdd}t j|_|S )Nc                    s   t  j  | |S N)r)   __name__argskwargsr*   r   r   r    wrapper^   s    zalias.<locals>.wrapper)
isinstancer   AssertionError	functoolswrapsr!   r,   __doc__)r*   r   r1   r   r0   r    alias[   s
    r7   znp.ndarray | pd.Indexarrayc                 C  sL   t | tjrtd}n0t| dr,| jj}nt| jsBtd}n| j}|S )zReturn a numpy compatible dtype from either
    a numpy array or a pandas.Index.

    Used for wrapping a pandas.Index as an xarray,Variable.

    O
categories)r2   pdZPeriodIndexnpdtypehasattrr;   is_valid_numpy_dtyper9   r>   r   r   r    get_valid_numpy_dtypeg   s    


rB   c                 C  sN   ddl m} z|j| }W n tk
r.   Y nX |jdkrJtj| |jd} | S )zmaybe coerce a pandas Index back to a nunpy array of type str

    pd.Index uses object-dtype to store str - try to avoid this for coords
    r   )dtypesZSUr>   )xarray.corerC   result_type	TypeErrorkindr=   Zasarraytype)indexZoriginal_coordsrC   rF   r   r   r    maybe_coerce_to_str{   s    
rK   c                 C  s*   t |tjr"|j| jkr"| |S |S dS )zWrap a transformed array with __array_wrap__ if it can be done safely.

    This lets us treat arbitrary functions that take and return ndarray objects
    like ufuncs, as long as they return an array with the same shape.
    N)r2   r=   ndarrayshapeZ__array_wrap__)originalZ	new_arrayr   r   r    maybe_wrap_array   s    
rO   bool)firstsecondr   c                 C  sv   ddl m} | |krdS t| tjs0t|tjr<|| |S t| tsPt|trZt| |S | |kptt	| ott	|S )zCompare two objects for equivalence (identity or equality), using
    array_equiv if either object is an ndarray. If both objects are lists,
    equivalent is sequentially called on all the elements.
    r   )duck_array_opsT)
rE   rS   r2   r=   rL   Zarray_equivlist
list_equivr<   Zisnull)rQ   rR   rS   r   r   r    
equivalent   s    
rV   c                 C  s>   d}t | t |krdS t| |D ]\}}|o6t||}q"|S )NTF)lenziprV   )rQ   rR   equivfsr   r   r    rU      s    rU   Iterable[T]ztuple[T, Iterator[T]])iterabler   c                 C  s"   t | }t|}|t|g|fS )zxReturns the first value from iterable, as well as a new iterator with
    the same content as the original iterable
    )iternext	itertoolschain)r]   genpeekr   r   r    peek_at   s    rd   Mapping[K, V]zCallable[[V, V], bool])
first_dictsecond_dictcompatr   c                 C  s:   |  D ],\}}|| kr||| | std|qdS )aH  Check the safety of updating one dictionary with another.

    Raises ValueError if dictionaries have non-compatible values for any key,
    where compatibility is determined by identity (they are the same item) or
    the `compat` function.

    Parameters
    ----------
    first_dict, second_dict : dict-like
        All items in the second dictionary are checked against for conflicts
        against items in the first dictionary.
    compat : function, optional
        Binary operator to determine if two values are compatible. By default,
        checks for equivalence.
    zHunsafe to merge dictionaries without overriding values; conflicting key N)items
ValueError)rf   rg   rh   kvr   r   r    update_safety_check   s
    rm   MutableMapping[K, V]c                 C  s2   t | D ]$}||ks&|| | || s| |= qdS )a  Remove incompatible items from the first dictionary in-place.

    Items are retained if their keys are found in both dictionaries and the
    values are compatible.

    Parameters
    ----------
    first_dict, second_dict : dict-like
        Mappings to merge.
    compat : function, optional
        Binary operator to determine if two values are compatible. By default,
        checks for equivalence.
    N)rT   )rf   rg   rh   rk   r   r   r    remove_incompatible_items   s    ro   r   zTypeGuard[Mapping]valuer   c                 C  s   t | dot | dS )Nkeys__getitem__)r?   rq   r   r   r    is_dict_like   s    ru   c                 C  s   t | to| td kS r+   )r2   slicert   r   r   r    is_full_slice   s    rw   zTypeGuard[list | tuple]c                 C  s   t | ttfS r+   )r2   rT   tuplert   r   r   r    is_list_like   s    ry   c                 C  sL   t | tjrdS t| doJt| doJt| doJt| drBt| dpJt| dS )NTndimrM   r>   __array_function__Z__array_ufunc____array_namespace__)r2   r=   rL   r?   rt   r   r   r    is_duck_array   s    
r}   zMapping[Any, T] | NonezMapping[str, T]zMapping[Hashable, T])
pos_kwargs	kw_kwargs	func_namer   c                 C  sP   | d ks| i kr"t tttf |S t| s:td| d|rLtd| | S )Nzthe first argument to .z must be a dictionaryz9cannot specify both keyword and positional arguments to .)r   r   r
   r   ru   rj   )r~   r   r   r   r   r    either_dict_or_kwargs  s    r   c                 C  sX   ddl m} |r t| dd dk}|pVt| ttfpVt| tf| pTt| dpTt| d S )Nr   )NON_NUMPY_SUPPORTED_ARRAY_TYPESrz   r{   r|   )Zxarray.core.variabler   getattrr2   r   bytesr   r?   )rq   
include_0dr   r   r   r    
_is_scalar  s    r   )r"   
   )	TypeGuardT)rq   r   r   c                 C  s
   t | |S )zfWhether to treat a value as a scalar.

            Any non-iterable, string, or 0-D array
            r   rq   r   r   r   r    	is_scalar<  s    r   zTypeGuard[Hashable]c                 C  s
   t | |S )z^Whether to treat a value as a scalar.

        Any non-iterable, string, or 0-D array
        r   r   r   r   r    r   E  s    )r>   r   c              	   C  s2   zt |  W n ttfk
r(   Y dS X dS d S )NFT)r=   r>   rG   rj   rD   r   r   r    r@   M  s
    r@   z
np.ndarrayc                 C  s   t jdtd}| |d< |S )z@Given a value, wrap it in a 0-D numpy.ndarray with dtype=object.r   rD   )r=   emptyobject)rq   resultr   r   r    to_0d_object_arrayV  s    r   c                 C  s6   t | s t| t jr*| jdkr*t | S t| S dS )z.Given a value, wrap it in a 0-D numpy.ndarray.r   N)r=   Zisscalarr2   rL   rz   r9   r   rt   r   r   r    to_0d_array]  s     
r   )rQ   rR   rh   r   c                   s@    D ]$}||ks"| | || s dS qt  fdd|D S )a  Test equivalence of two dict-like objects. If any of the values are
    numpy arrays, compare them correctly.

    Parameters
    ----------
    first, second : dict-like
        Dictionaries to compare for equality
    compat : function, optional
        Binary operator to determine if two values are compatible. By default,
        checks for equivalence.

    Returns
    -------
    equals : bool
        True if the dictionaries are equal
    Fc                 3  s   | ]}| kV  qd S r+   r   ).0rk   rQ   r   r    	<genexpr>}  s     zdict_equiv.<locals>.<genexpr>)all)rQ   rR   rh   rk   r   r   r    
dict_equive  s    r   c                 C  s   t | }t||| |S )a  Return the intersection of two dictionaries as a new dictionary.

    Items are retained if their keys are found in both dictionaries and the
    values are compatible.

    Parameters
    ----------
    first_dict, second_dict : dict-like
        Mappings to merge.
    compat : function, optional
        Binary operator to determine if two values are compatible. By default,
        checks for equivalence.

    Returns
    -------
    intersection : dict
        Intersection of the contents.
    )dictro   rf   rg   rh   Znew_dictr   r   r    compat_dict_intersection  s    r   c                 C  s"   t | }t| || || |S )a  Return the union of two dictionaries as a new dictionary.

    An exception is raised if any keys are found in both dictionaries and the
    values are not compatible.

    Parameters
    ----------
    first_dict, second_dict : dict-like
        Mappings to merge.
    compat : function, optional
        Binary operator to determine if two values are compatible. By default,
        checks for equivalence.

    Returns
    -------
    union : dict
        union of the contents.
    )r   rm   updater   r   r   r    compat_dict_union  s    
r   c                   @  sl   e Zd ZdZdZddddZdddd	d
ZddddZddddZdddddZ	ddddZ
dS )FrozenzWrapper around an object implementing the mapping interface to make it
    immutable. If you really want to modify the mapping, the mutable version is
    saved under the `mapping` attribute.
    mappingre   c                 C  s
   || _ d S r+   r   )selfr   r   r   r    __init__  s    zFrozen.__init__r   r   keyr   c                 C  s
   | j | S r+   r   r   r   r   r   r    rs     s    zFrozen.__getitem__Iterator[K]r   c                 C  s
   t | jS r+   )r^   r   r   r   r   r    __iter__  s    zFrozen.__iter__r#   c                 C  s
   t | jS r+   )rW   r   r   r   r   r    __len__  s    zFrozen.__len__r   rP   c                 C  s
   || j kS r+   r   r   r   r   r    __contains__  s    zFrozen.__contains__r   c                 C  s   t | j d| jdS N())rI   r,   r   r   r   r   r    __repr__  s    zFrozen.__repr__N)r,   
__module____qualname__r6   	__slots__r   rs   r   r   r   r   r   r   r   r    r     s   r   r   c                  O  s   t t| |S r+   )r   r   r-   r   r   r    
FrozenDict  s    r   c                   @  sP   e Zd ZdZdZdddddZdd	d
ddZddddZddddZdS )HybridMappingProxya  Implements the Mapping interface. Uses the wrapped mapping for item lookup
    and a separate wrapped keys collection for iteration.

    Can be used to construct a mapping object from another dict-like object without
    eagerly accessing its items or when a mapping object is expected but only
    iteration over keys is actually used.

    Note: HybridMappingProxy does not validate consistency of the provided `keys`
    and `mapping`. It is the caller's responsibility to ensure that they are
    suitable for the task at hand.
    _keysr   zCollection[K]re   )rr   r   c                 C  s   || _ || _d S r+   r   )r   rr   r   r   r   r    r     s    zHybridMappingProxy.__init__r   r   r   c                 C  s
   | j | S r+   r   r   r   r   r    rs     s    zHybridMappingProxy.__getitem__r   r   c                 C  s
   t | jS r+   )r^   r   r   r   r   r    r     s    zHybridMappingProxy.__iter__r#   c                 C  s
   t | jS r+   )rW   r   r   r   r   r    r     s    zHybridMappingProxy.__len__N)	r,   r   r   r6   r   r   rs   r   r   r   r   r   r    r     s   r   c                   @  s   e Zd ZU dZded< dZd#dddd	Zd
ddddZddddZddddZ	dddddZ
dddddZdddddZd dd!d"ZdS )$
OrderedSetzA simple ordered set.

    The API matches the builtin set, but it preserves insertion order of elements, like
    a dict. Note that, unlike in an OrderedDict, equality tests are not order-sensitive.
    zdict[T, None]_dr   NzIterable[T] | None)valuesc                 C  s   i | _ |d k	r| | d S r+   )r   r   )r   r   r   r   r    r      s    zOrderedSet.__init__r
   rP   rp   c                 C  s
   || j kS r+   r   r   rq   r   r   r    r     s    zOrderedSet.__contains__zIterator[T]r   c                 C  s
   t | jS r+   )r^   r   r   r   r   r    r   
  s    zOrderedSet.__iter__r#   c                 C  s
   t | jS r+   )rW   r   r   r   r   r    r     s    zOrderedSet.__len__r   r$   c                 C  s   d | j |< d S r+   r   r   r   r   r    add  s    zOrderedSet.addc                 C  s   | j |= d S r+   r   r   r   r   r    discard  s    zOrderedSet.discardr\   )r   r   c                 C  s   |D ]}d | j |< qd S r+   r   )r   r   rl   r   r   r    r     s    zOrderedSet.updater   c                 C  s   t | j dt| dS r   )rI   r,   rT   r   r   r   r    r     s    zOrderedSet.__repr__)N)r,   r   r   r6   __annotations__r   r   r   r   r   r   r   r   r   r   r   r   r    r     s   
r   c                   @  sL   e Zd ZdZdZedddddZeddddd	Zdddd
dZdS )NdimSizeLenMixinzMixin class that extends a class that defines a ``shape`` property to
    one that also defines ``ndim``, ``size`` and ``__len__``.
    r   r   r#   r   r   c                 C  s
   t | jS )zk
        Number of array dimensions.

        See Also
        --------
        numpy.ndarray.ndim
        )rW   rM   r   r   r   r    rz   '  s    	zNdimSizeLenMixin.ndimc                 C  s   t | jS )u   
        Number of elements in the array.

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

        See Also
        --------
        numpy.ndarray.size
        )mathprodrM   r   r   r   r    size2  s    zNdimSizeLenMixin.sizec                 C  s.   z| j d W S  tk
r(   tdY nX d S )Nr   zlen() of unsized object)rM   
IndexErrorrG   r   r   r   r    r   ?  s    zNdimSizeLenMixin.__len__N)	r,   r   r   r6   r   propertyrz   r   r   r   r   r   r    r      s   
r   c                   @  sZ   e Zd ZdZdZedddddZedddd	d
ZddddZdddddZ	dS )NDArrayMixina  Mixin class for making wrappers of N-dimensional arrays that conform to
    the ndarray interface required for the data argument to Variable objects.

    A subclass should set the `array` property and override one or more of
    `dtype`, `shape` and `__getitem__`.
    r   r   znp.dtyper   c                 C  s   | j jS r+   rA   r   r   r   r    r>   P  s    zNDArrayMixin.dtypeztuple[int, ...]c                 C  s   | j jS r+   )r9   rM   r   r   r   r    rM   T  s    zNDArrayMixin.shaper   c                 C  s
   | j | S r+   r8   r   r   r   r    rs   X  s    zNDArrayMixin.__getitem__r   c                 C  s   t | j d| jdS )Nz(array=r   )rI   r,   r9   r   r   r   r    r   [  s    zNDArrayMixin.__repr__N)
r,   r   r   r6   r   r   r>   rM   rs   r   r   r   r   r    r   F  s   r   c                   @  sT   e Zd ZdZdZddddZdddd	Zd
dddZddddZdd Z	dS )
ReprObjectzDObject that prints as the given value, for use with sentinel values._valuer   rt   c                 C  s
   || _ d S r+   r   r   r   r   r    r   d  s    zReprObject.__init__r   c                 C  s   | j S r+   r   r   r   r   r    r   g  s    zReprObject.__repr__rP   c                 C  s   t |tr| j|jkS dS )NF)r2   r   r   )r   otherr   r   r    __eq__j  s    
zReprObject.__eq__r#   c                 C  s   t t| | jfS r+   )hashrI   r   r   r   r   r    __hash__o  s    zReprObject.__hash__c                 C  s   ddl m} |t| | jfS )Nr   )normalize_token)Z	dask.baser   rI   r   )r   r   r   r   r    __dask_tokenize__r  s    zReprObject.__dask_tokenize__N)
r,   r   r   r6   r   r   r   r   r   r   r   r   r   r    r   _  s   r   c                 c  s.   z
dV  W n t k
r(   |    Y nX dS )zContext manager to ensure that a file opened by xarray is closed if an
    exception is raised before the user sees the file object.
    N)	Exceptionclose)rZ   r   r   r    close_on_errorx  s
    
r   )pathr   c                 C  s   t td| S )zFinds URLs of the form protocol:// or protocol::

    This also matches for http[s]://, which were the only remote URLs
    supported in <=v0.16.2.
    z^[a-z][a-z0-9]*(\://|\:\:))rP   research)r   r   r   r    is_remote_uri  s    r      r   c                 C  sf   t | tr| d | }nJt | tjrP|  dkr:| d | |}| d ntdt|  |S )Nr   z"cannot read the magic number from )	r2   r   ioIOBasetellseekreadrG   rI   Zfilename_or_objcountZmagic_numberr   r   r    read_magic_number_from_file  s    


r   zbytes | Nonec              
   C  sj   t | tst| drft| }z.t|d}t||W  5 Q R  W S Q R X W n ttfk
rd   Y nX d S )N
__fspath__rb)	r2   r   r?   osfspathopenr   FileNotFoundErrorrG   )Zpathliker   r   rZ   r   r   r    try_read_magic_number_from_path  s    
"r   c                 C  s:   t | |}|d kr6zt| |}W n tk
r4   Y nX |S r+   )r   r   rG   r   r   r   r    'try_read_magic_number_from_file_or_path  s    
r   c                 K  s4   t j| td} t | }tt j| | f|S )zReturn True if values of an array are uniformly spaced and sorted.

    >>> is_uniform_spaced(range(5))
    True
    >>> is_uniform_spaced([-4, 0, 100])
    False

    kwargs are additional arguments to ``np.isclose``
    rD   )r=   r9   floatZdiffrP   iscloseminmax)Zarrr/   Zdiffsr   r   r    is_uniform_spaced  s    

r   )rl   r   c                 C  s(   zt |  W n tk
r"   Y dS X dS )z$Determine whether `v` can be hashed.FT)r   rG   rl   r   r   r    hashable  s
    r   zTypeGuard[Iterable[Any]]c                 C  s(   zt |  W n tk
r"   Y dS X dS )z"Determine whether `v` is iterable.FT)r^   rG   r   r   r   r    r]     s
    r]   zTypeGuard[Iterable[Hashable]]c                 C  s6   zt | }W n tk
r"   Y dS X tdd |D S )z2Determine whether `v` is an Iterable of Hashables.Fc                 s  s   | ]}t |V  qd S r+   )r   )r   elmr   r   r    r     s     z'iterable_of_hashable.<locals>.<genexpr>)r^   rG   r   )rl   itr   r   r    iterable_of_hashable  s
    r   z
dict[K, V])attrsr   c                 C  sP   t | } |  D ]:\}}t|tjr2| | |< qt|tjr| | |< q| S )zaConvert attribute values from numpy objects to native Python objects,
    for use in to_dict
    )r   ri   r2   r=   rL   tolistZgenericitem)r   rk   rl   r   r   r    decode_numpy_dict_values  s    r   c                 C  s:   t | jt jr| d} nt | jt jr6| d} | S )zZConvert val out of numpy time, for use in to_dict.
    Needed because of numpy bug GH#7619zdatetime64[us]ztimedelta64[us])r=   Z
issubdtyper>   Z
datetime64ZastypeZtimedelta64)valr   r   r    ensure_us_time_resolution  s
    
r   c                   @  s   e Zd ZdZdZdddddZdd	d
ddZddd	dddZddd
ddZdd	d
ddZ	ddddZ
ddddZdS )HiddenKeyDictz6Acts like a normal dictionary, but hides certain keys._data_hidden_keysrn   zIterable[K])datahidden_keysc                 C  s   || _ t|| _d S r+   )r   	frozensetr   )r   r   r   r   r   r    r     s    zHiddenKeyDict.__init__r   r$   r   c                 C  s   || j krtd|dd S )NzKey `z` is hidden.)r   KeyErrorr   r   r   r    _raise_if_hidden  s    
zHiddenKeyDict._raise_if_hiddenr   )r   rq   r   c                 C  s   |  | || j|< d S r+   r   r   )r   r   rq   r   r   r    __setitem__  s    
zHiddenKeyDict.__setitem__c                 C  s   |  | | j| S r+   r   r   r   r   r    rs     s    
zHiddenKeyDict.__getitem__c                 C  s   |  | | j|= d S r+   r   r   r   r   r    __delitem__	  s    
zHiddenKeyDict.__delitem__r   r   c                 c  s    | j D ]}|| jkr|V  qd S r+   r   )r   rk   r   r   r    r     s    

zHiddenKeyDict.__iter__r#   c                 C  s"   t | j| j @ }t | j| S r+   )rW   r   r   rr   )r   Z
num_hiddenr   r   r    r     s    zHiddenKeyDict.__len__N)r,   r   r   r6   r   r   r   r   rs   r   r   r   r   r   r   r    r     s   r   raiser   r   r   )dims_supplieddims_allmissing_dimsr   c                 #  s   d krt t|t |kr$tdt ddkr>td fdd|D }t ||}|D ]}|dkrx|E dH  q`|V  q`n:t ||}t|t|A rt  d| d	|E dH  dS )
z
    Resolves a supplied list containing an ellipsis representing other items, to
    a generator with the 'realized' list of all items
    .&Cannot use ellipsis with repeated dims   More than one ellipsis suppliedc                   s   g | ]}| kr|qS r   r   r   dr  r   r    
<listcomp>%  s      zinfix_dims.<locals>.<listcomp>Nz must be a permuted list of z, unless `...` is included)rW   setrj   rT   r   drop_missing_dims)r  r  r  
other_dimsZexisting_dimsr	  r   r
  r    
infix_dims  s"    	
r  zContainer[Hashable]r
   )dimsnew_dimr   c                 C  s   || krdt | }q |S )a^  Get an new dimension name based on new_dim, that is not used in dims.
    If the same name exists, we add an underscore(s) in the head.

    Example1:
        dims: ['a', 'b', 'c']
        new_dim: ['_rolling']
        -> ['_rolling']
    Example2:
        dims: ['a', 'b', 'c', '_rolling']
        new_dim: ['_rolling']
        -> ['__rolling']
    _)r   )r  r  r   r   r    get_temp_dimname5  s    r  zMapping[Any, Any]z&Iterable[Hashable] | Mapping[Any, int]zMapping[Hashable, Any])indexersr  r  r   c                   s   |dkr4|   t  }|r0td| d  | S |dkrt| } |   t  }|rntd| d   |D ]}| | qr| S |dkr fdd|  D S td| d	d
S )zDepending on the setting of missing_dims, drop any dimensions from indexers that
    are not present in dims.

    Parameters
    ----------
    indexers : dict
    dims : sequence
    missing_dims : {"raise", "warn", "ignore"}
    r  Dimensions ' do not exist. Expected one or more of r'   ignorec                   s   i | ]\}}| kr||qS r   r   )r   r   r   r  r   r    
<dictcomp>o  s       z+drop_dims_from_indexers.<locals>.<dictcomp>Unrecognised option  for missing_dims argumentN)rr   r  rj   r   r&   r'   popri   )r  r  r  invalidr   r   r  r    drop_dims_from_indexersG  s,    
r  zIterable[Hashable])supplied_dimsr  r  r   c                   s   |dkr>dd | D }|t   }|r:td| d  | S |dkrt | t   }|rptd| d    fdd| D S |d	kr fd
d| D S td| ddS )a  Depending on the setting of missing_dims, drop any dimensions from supplied_dims that
    are not present in dims.

    Parameters
    ----------
    supplied_dims : Iterable of Hashable
    dims : Iterable of Hashable
    missing_dims : {"raise", "warn", "ignore"}
    r  c                 S  s   h | ]}|d k	r|qS .r   r   r   r   r   r    	<setcomp>  s      z$drop_missing_dims.<locals>.<setcomp>r  r  r'   c                   s    g | ]}| ks|d kr|qS r   r   r!  r  r   r    r    s       z%drop_missing_dims.<locals>.<listcomp>r  c                   s    g | ]}| ks|d kr|qS r   r   r!  r  r   r    r    s       r  r  N)r  rj   r&   r'   )r  r  r  Zsupplied_dims_setr  r   r  r    r  w  s(    
r  T_NoneZellipsis)check_existsreplace_nonez!str | Iterable[Hashable] | T_Noneztuple[Hashable, ...]zLiteral[True])dimall_dimsr$  r%  r   c                C  s   d S r+   r   r&  r'  r$  r%  r   r   r    
parse_dims  s    r)  )r$  zLiteral[False]ztuple[Hashable, ...] | T_Nonec                C  s   d S r+   r   r(  r   r   r    r)    s    r   z&tuple[Hashable, ...] | None | ellipsisc                C  sJ   | dks| dkr|r|S | S t | tr,| f} |rBtt| t| t| S )a  Parse one or more dimensions.

    A single dimension must be always a str, multiple dimensions
    can be Hashables. This supports e.g. using a tuple as a dimension.
    If you supply e.g. a set of dimensions the order cannot be
    conserved, but for sequences it will be.

    Parameters
    ----------
    dim : str, Iterable of Hashable, "..." or None
        Dimension(s) to parse.
    all_dims : tuple of Hashable
        All possible dimensions.
    check_exists: bool, default: True
        if True, check if dim is a subset of all_dims.
    replace_none : bool, default: True
        If True, return all_dims if dim is None or "...".

    Returns
    -------
    parsed_dims : tuple of Hashable
        Input dimensions as a tuple.
    N.)r2   r   _check_dimsr  rx   r(  r   r   r    r)    s    
z,str | Sequence[Hashable | ellipsis] | T_Nonec                C  s   d S r+   r   r(  r   r   r    parse_ordered_dims  s    r+  c                C  s   d S r+   r   r(  r   r   r    r+    s    r   c                  s   | dk	r| dk	rt | tsd| krt|  t|}|r@t | t|t|krXtdt| }|ddkrvtdt fdd|D }|d}|d| | ||d d  S t	| |||dS dS )	a  Parse one or more dimensions.

    A single dimension must be always a str, multiple dimensions
    can be Hashables. This supports e.g. using a tuple as a dimension.
    An ellipsis ("...") in a sequence of dimensions will be
    replaced with all remaining dimensions. This only makes sense when
    the input is a sequence and not e.g. a set.

    Parameters
    ----------
    dim : str, Sequence of Hashable or "...", "..." or None
        Dimension(s) to parse. If "..." appears in a Sequence
        it always gets replaced with all remaining dims
    all_dims : tuple of Hashable
        All possible dimensions.
    check_exists: bool, default: True
        if True, check if dim is a subset of all_dims.
    replace_none : bool, default: True
        If True, return all_dims if dim is None.

    Returns
    -------
    parsed_dims : tuple of Hashable
        Input dimensions as a tuple.
    N.r  r  r  c                 3  s   | ]}| kr|V  qd S r+   r   r  Zdims_setr   r    r   %  s      z%parse_ordered_dims.<locals>.<genexpr>r(  )
r2   r   r  r*  rW   rj   rx   r   rJ   r)  )r&  r'  r$  r%  Zall_dims_setr  r  idxr   r,  r    r+    s&     "

 zset[Hashable | ellipsis]zset[Hashable])r&  r'  r   c                 C  sB   | | }|r>|dhkr>d dd |D }td| d| d S )N.z, c                 s  s   | ]}d |d V  qdS )'Nr   r  r   r   r    r   5  s     z_check_dims.<locals>.<genexpr>zDimension(s) r  )joinrj   )r&  r'  Z
wrong_dimsZwrong_dims_strr   r   r    r*  2  s    r*  	_Accessorc                   @  sX   e Zd ZdZdddddZeddddd	Zed
dddd	Zddddd	ZdS )UncachedAccessorzActs like a property, but on both classes and class instances

    This class is necessary because some tools (e.g. pydoc and sphinx)
    inspect classes for which property returns itself and not the
    accessor.
    ztype[_Accessor]r$   )accessorr   c                 C  s
   || _ d S r+   	_accessor)r   r2  r   r   r    r   F  s    zUncachedAccessor.__init__)r*   r   c                 C  s   d S r+   r   r   r*   clsr   r   r    __get__I  s    zUncachedAccessor.__get__r   r0  c                 C  s   d S r+   r   r5  r   r   r    r7  M  s    zNone | objectztype[_Accessor] | _Accessorc                 C  s   |d kr| j S |  |S r+   r3  r5  r   r   r    r7  Q  s    N)r,   r   r   r6   r   r   r7  r   r   r   r    r1  >  s   r1  c                   @  s   e Zd ZdZdS )Defaultr   N)r,   r   r   tokenr   r   r   r    r8  Y  s   r8  c                 c  s.   | D ]$}t |tr"t|E d H  q|V  qd S r+   )r2   rT   iterate_nested)Znested_listr   r   r   r    r:  `  s    
r:  c                   sF   ddl m} ddlm  t| |r*|  } t fdd| j D S )zmReturns True if xarray object contains only numpy or dask arrays.

    Expects obj to be Dataset or DataArrayr   )	DataArrayis_duck_dask_arrayc                   s$   g | ]}t |jtjp |jqS r   )r2   r   r=   rL   )r   varr<  r   r    r  s  s   z/contains_only_dask_or_numpy.<locals>.<listcomp>)	Zxarray.core.dataarrayr;  Zxarray.core.pycompatr=  r2   Z_to_temp_datasetr   	variablesr   )r*   r;  r   r<  r    contains_only_dask_or_numpyh  s    

r@  )moduler   c                 C  s   t j| dk	S )a  Checks whether a module is installed without importing it.

    Use this for a lightweight check and lazy imports.

    Parameters
    ----------
    module : str
        Name of the module.

    Returns
    -------
    available : bool
        Whether the module is installed.
    N)	importlibutil	find_spec)rA  r   r   r    module_availablez  s    rE  Fc                 C  sn   ddl }tj|j}tj|d}t }d}|rjt|}|	|rj|	|rV| rj|j
}|d7 }q0qjq0|S )a  Find the first place in the stack that is not inside xarray.

    This is unless the code emanates from a test, in which case we would prefer
    to see the xarray source.

    This function is taken from pandas.

    Parameters
    ----------
    test_mode : bool
        Flag used for testing purposes to switch off the detection of test
        directories in the stack trace.

    Returns
    -------
    stacklevel : int
        First level in the stack that is not part of xarray.
    r   Ntestsr  )Zxarrayr   r   dirname__file__r/  inspectcurrentframegetfile
startswithf_back)Z	test_modeZxrZpkg_dirZtest_dirframenfnamer   r   r    find_stack_level  s    

rQ  c                 C  s   t  }tj| ||d dS )z?Emit a warning at the user level by inspecting the stack trace.)categoryr%   N)rQ  r&   r'   )messagerR  r%   r   r   r    emit_user_level_warning  s    rT  )r"   )T)T)r   )r   )r   )r  )F)N)or6   
__future__r   
contextlibr4   rB  rI  r   r`   r   r   r   sysr&   enumr   typingr   r   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   Znumpyr=   Zpandasr<   Zxarray.core.typesr   r   r   r   r   r   r!   r)   r7   rB   rK   rO   rV   rU   rd   rm   ro   ru   rw   ry   r}   r   r   version_infor   Ztyping_extensionsImportErrorr   r@   r   r   r   r   r   r   r   r   r   r   r   r   contextmanagerr   r   r   r   r   r   r   r]   r   r   r   r   r  r  r  r  r#  r)  r+  r*  r0  r1  r8  r9  _defaultr:  r@  rE  rQ  rT  r   r   r   r    <module>   s   #L
		+&
	
			
) 0,
)
7	%