HOME


sh-3ll 1.0
DIR:/usr/local/lib/python3.6/site-packages/xarray/core/__pycache__/
Upload File :
Current File : //usr/local/lib/python3.6/site-packages/xarray/core/__pycache__/dataset.cpython-36.pyc
3

���h�D�@s�ddlZddlZddlmZddlmZddlZddlZ	ddl
mZddl
mZddl
m
Z
ddl
mZdd	l
mZdd
l
mZddl
mZdd
l
mZddlmZmZddlmZmZddl
mZmZddlmZmZddlmZmZmZm Z m!Z!ddl"m#Z#m$Z$m%Z%m&Z&m'Z'ddl(m)Z)m*Z*m+Z+m,Z,ddl-m.Z.ddddddddddd d!d"d#gZ/d$d%�Z0d&d'�Z1d5d)d*�Z2d+d,�Z3Gd-d.�d.e�Z4Gd/d0�d0e5�Z6Gd1d2�d2eee�Z7ej8e7d3d4�dS)6�N)�Mapping)�Number�)�ops)�utils)�common)�groupby)�indexing)�	alignment)�
formatting�)�conventions)�align�align_variables)�DatasetCoordinates�Indexes)�ImplementsDatasetReduce�BaseDataObject)�merge_datasets�expand_variables)�Frozen�SortedKeysDict�ChainMap�maybe_wrap_array�hashable)�as_variable�Variable�
Coordinate�broadcast_variables�default_index_coordinate)�	iteritems�
basestring�OrderedDict�dask_array_type)�concat�year�month�day�hour�minute�second�microsecondZ
nanosecond�date�timeZ	dayofyearZ
weekofyearZ	dayofweekZquarterc
Cs�t|t�st|��|jdd�}t|�dkr2t|��|\}}||}|jdkrV|j�}n |jdkrntj|j	�}nt|��|dkr�t
jdddd	g�}|j}||d
d}	n
t
||�}	||t|j|	�fS)zhGet a virtual variable (e.g., 'time.year') from a dict of
    xarray.Variable objects (if possible)
    �.rrrZseasonZDJFZMAMZJJAZSON��)�
isinstancer!�KeyError�split�len�ndim�to_index�pdZ	Timestamp�values�np�arrayr&�getattrr�dims)
�	variables�keyZ	split_key�ref_name�var_nameZref_varr,Zseasonsr&�data�rB�3/tmp/pip-build-5_djhm0z/xray/xarray/core/dataset.py�_get_virtual_variable$s$




rDc
Cs�i}i}tdd�t|�D��}x�t|�D]|\}}xrt|j|j�D]`\}}||kr\td|��||krv|||<|||<q@|||kr@td|||||||f��q@Wq(W|S)z�Calculate 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.
    css|]\}}|js|VqdS)N)r<)�.0�k�vrBrBrC�	<genexpr>Jsz"_calculate_dims.<locals>.<genexpr>z0dimension %s already exists as a scalar variablezGconflicting sizes for dimension %r: length %s on %r and length %s on %r)�setr �zipr<�shape�
ValueError)r=r<Z	last_usedZscalar_varsrF�var�dim�sizerBrBrC�_calculate_dimsBs
"rP�%scCs|rt||��dS)N)rL)�args�msgrBrBrC�
_assert_emptyZsrTcCs(t|d�r|j�}t|t�s$t|�}|S)z�Cast the given object to a Dataset.

    Handles Datasets, DataArrays and dictionaries of variables. A new Dataset
    object is only created if the provided object is not already one.
    �
to_dataset)�hasattrrUr1�Dataset)�objrBrBrC�
as_dataset_s


rYc@s<eZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
S)�
DataVariablescCs
||_dS)N)�_dataset)�self�datasetrBrBrC�__init__mszDataVariables.__init__cs�fdd��jjD�S)Nc3s|]}|�jjkr|VqdS)N)r[�_coord_names)rEr>)r\rBrCrHqsz)DataVariables.__iter__.<locals>.<genexpr>)r[�
_variables)r\rB)r\rC�__iter__pszDataVariables.__iter__cCst|jj�t|jj�S)N)r4r[r`r_)r\rBrBrC�__len__tszDataVariables.__len__cCs||jjko||jjkS)N)r[r`r_)r\r>rBrBrC�__contains__wszDataVariables.__contains__cCs"||jjkr|j|St|��dS)N)r[r_r2)r\r>rBrBrC�__getitem__{s
zDataVariables.__getitem__cCs
tj|�S)N)rZ	vars_repr)r\rBrBrC�__repr__�szDataVariables.__repr__N)	�__name__�
__module__�__qualname__r^rarbrcrdrerBrBrBrCrZlsrZc@seZdZdd�Zdd�ZdS)�_LocIndexercCs
||_dS)N)r])r\r]rBrBrCr^�sz_LocIndexer.__init__cCs tj|�std��|jjf|�S)Nz-can only lookup dictionaries from Dataset.loc)r�is_dict_like�	TypeErrorr]�sel)r\r>rBrBrCrd�s
z_LocIndexer.__getitem__N)rfrgrhr^rdrBrBrBrCri�sric@s�eZdZdZejZd�dd�Zdd�Zd�d	d
�Z	dd�Z
ed�d
d��Zdd�Z
dd�Zdd�Zdd�Zedd��Zdd�Zedd��Zejdd��Zedd��Zd d!�Zd"d#�Zed�d$d%��Ze�Zded&fd'd(�Zd�d)d*�Zd+d,�Zd-d.�Zd/d0�Z d1d2�Z!d�d3d4�Z"d5d6�Z#d7d8�Z$d9d:�Z%ed;d<��Z&ed=d>��Z'd?d@�Z(dAdB�Z)dCdD�Z*dZ+dEdF�Z,dGdH�Z-dIdJ�Z.dKdL�Z/edMdN��Z0edOdP��Z1edQdR��Z2edSdT��Z3d�dUdV�Z4d�dWdX�Z5d�dYdZ�Z6d�d\d]�Z7e8j9e7d^�Z:e8j9e7d_�Z;d`da�Z<edbdc��Z=d�dedf�Z>dgdh�Z?d�didj�Z@d�dldm�ZAd�dndo�ZBd�dpdq�ZCd�drds�ZDd�dtdu�ZEd�dvdw�ZFdxdy�ZGdzd{�ZHd|d}�ZId�d~d�ZJd&eK�dd�fd�d��ZLd�d�d��ZMd�d�d��ZNd�d��ZOd�d��ZPd�d��ZQed�d���ZRd�d�d��ZSd�d�d��ZTd�d��ZUd�d�d��ZVd&ffd�d��ZWd�d��ZXd�d�d��ZYd�d��ZZd�d��Z[ed�d���Z\e]d�d�d���Z^e]d�d�d���Z_e]d�d���Z`d�d�d��Zad�d�d��Zbd�d��Zcd�d��Zded�d���Zeed�d���ZfdS)�rWa�A multi-dimensional, in memory, array database.

    A dataset resembles an in-memory representation of a NetCDF file, and
    consists of variables, coordinates and attributes which together form a
    self describing dataset.

    Dataset implements the mapping interface with keys given by variable names
    and values given by DataArray objects for each variable name.

    One dimensional variables with name equal to their dimension are index
    coordinates used for label based indexing.
    N�broadcast_equalscKs�t�|_t�|_i|_d|_d|_|r\d|krF|jd�}tj	ddd�|r\t
dj|j����|dkrhi}|dkrvt�}|dk	s�|dk	r�|j
|||�|dk	r�||_d|_dS)a�To load data from a file or file-like object, use the `open_dataset`
        function.

        Parameters
        ----------
        data_vars : dict-like, optional
            A mapping from variable names to :py:class:`~xarray.DataArray`
            objects, :py:class:`~xarray.Variable` objects or tuples of the
            form ``(dims, data[, attrs])`` which can be used as arguments to
            create a new ``Variable``. Each dimension must have the same length
            in all variables in which it appears.
        coords : dict-like, optional
            Another mapping in the same form as the `variables` argument,
            except the each item is saved on the dataset as a "coordinate".
            These variables have an associated meaning: they describe
            constant/fixed/independent quantities, unlike the
            varying/measured/dependent quantities that belong in `variables`.
            Coordinates values may be given by 1-dimensional arrays or scalars,
            in which case `dims` do not need to be supplied: 1D arrays will be
            assumed to give index values along the dimension with the same
            name.
        attrs : dict-like, optional
            Global attributes to save on this dataset.
        compat : {'broadcast_equals', 'equals', 'identical'}, optional
            String indicating how to compare variables of the same name for
            potential conflicts:

            - 'broadcast_equals': all values must be equal when variables are
              broadcast against each other to ensure common dimensions.
            - 'equals': all values and dimensions must be the same.
            - 'identical': all values, dimensions and attributes must be the
              same.
        Nr=z,Variables kwarg is deprecated. Use data_varsr)�
stacklevelz{0} are not valid kwargsT)r"r`rIr_�_dims�_attrs�	_file_obj�pop�warnings�warnrk�format�keys�_set_init_vars_and_dims�attrs�_initialized)r\�	data_vars�coordsrx�compat�kwargsrBrBrCr^�s(#
zDataset.__init__cCs6x0t|j�D]"\}}||jkrt||�|j|<qWdS)z3Add missing coordinates to self._variables
        N)r r<r`r)r\rNrOrBrBrC�_add_missing_coords_inplace�s
z#Dataset._add_missing_coords_inplaceTcst�dkri�|r|jj�n|j}|r>t�fdd�|jD�d�|j|�t|�}||_||_|j�|jj��dS)asAdd a dictionary of new variables to this dataset.

        Raises a ValueError if any dimensions have conflicting lengths in the
        new dataset. Otherwise will update this dataset's _variables and
        _dims attributes in-place.

        Set `needs_copy=False` only if this dataset is brand-new and hence
        can be thrown away if this method fails.
        Ncsg|]}|�kr|�qSrBrB)rErF)�new_coord_namesrBrC�
<listcomp>�sz3Dataset._update_vars_and_coords.<locals>.<listcomp>z;coordinates with these names already exist as variables: %s)	r`�copyrTrz�updaterPror~r_)r\�
new_variablesr�
needs_copy�check_coord_namesr=r<rB)rrC�_update_vars_and_coords�s
zDataset._update_vars_and_coordscsZt�fdd�|D�d�t|��}t|�}t||d�\}}|j��|j||ddd�dS)zBSet the initial value of Dataset variables and dimensions
        csg|]}|�kr|�qSrBrB)rErF)r{rBrCr��sz3Dataset._set_init_vars_and_dims.<locals>.<listcomp>z'redundant variables and coordinates: %s)r|F)r�r�N)rTrrrr�r�)r\�varsr{r|r=Zalignedr�rrB)r{rCrw�s

zDataset._set_init_vars_and_dimscCs4|j�\}}|r|||�\}}|||d�}||_|S)zWCreate a new dataset from the contents of a backends.*DataStore
        object
        )rx)�loadrq)�cls�store�decoderr=�
attributesrXrBrBrC�
load_store
szDataset.load_storecCs|jdk	r|jj�d|_dS)z/Close any files linked to this dataset
        N)rq�close)r\rBrBrCr�s

z
Dataset.closecCs|S)NrB)r\rBrBrC�	__enter__szDataset.__enter__cCs|j�dS)N)r�)r\�exc_type�	exc_value�	tracebackrBrBrC�__exit__ szDataset.__exit__cCs|j�|jj�}d|d<|S)z*Always load data in-memory before picklingNrq)r��__dict__r�)r\�staterBrBrC�__getstate__#s
zDataset.__getstate__cCs
t|j�S)z^Frozen dictionary of xarray.Variable objects constituting this
        dataset's data
        )rr`)r\rBrBrCr=-szDataset.variablescCs|jdkrdSt|j�S)N)rpr")r\rBrBrC�_attrs_copy4szDataset._attrs_copycCs|jdkrt�|_|jS)z8Dictionary of global attributes on this dataset
        N)rpr")r\rBrBrCrx7s
z
Dataset.attrscCst|�|_dS)N)r"rp)r\�valuerBrBrCrx?scCstt|j��S)z�Mapping from dimension names to lengths.

        This dictionary cannot be modified directly, but is updated when adding
        new variables.
        )rrro)r\rBrBrCr<CszDataset.dimscCsrtdd�|jj�D��}tdd�|j�D��}|rnddlj}|j|j��}x"t||�D]\}}||j|_qVW|S)a�Manually trigger loading of this dataset's data from disk or a
        remote source into memory and return this dataset.

        Normally, it should not be necessary to call this method in user code,
        because all xarray functions should either work on deferred data or
        load data automatically. However, this method can be necessary when
        working with many file objects on disk.
        css|]\}}||jfVqdS)N)rA)rErFrGrBrBrCrHVszDataset.load.<locals>.<genexpr>css$|]\}}t|t�r||fVqdS)N)r1r#)rErFrGrBrBrCrHWsrN)	�dictr=�itemsZ
dask.arrayr:Zcomputer8rJrA)r\Zall_dataZ	lazy_data�daZevaluated_datarFrArBrBrCr�Ls

zDataset.loadcCstjdtdd�|j�S)NzFthe Dataset method `load_data` has been deprecated; use `load` insteadr)rn)rsrt�
FutureWarningr�)r\rBrBrC�	load_datads
zDataset.load_datacCs2tj|�}||_||_||_||_||_d|_|S)zaShortcut around __init__ for internal use when we want to skip
        costly validation
        T)�object�__new__r`r_rorprqry)r�r=�coord_namesr<rxZfile_objrXrBrBrC�_construct_directjs
zDataset._construct_directFcCstt|�}|r<||_||_|dk	r&||_||jk	r6||_|}n4|dkrN|jj�}||jkr`|j�}|j||||�}|S)a*Fastpath constructor for internal use.

        Preserves coord names and attributes; dimensions are recalculated from
        the supplied variables.

        The arguments are *not* copied when placed on the new dataset. It is up
        to the caller to ensure that they have the right type and are not used
        elsewhere.

        Parameters
        ----------
        variables : OrderedDict
        coord_names : set or None, optional
        attrs : OrderedDict or None, optional

        Returns
        -------
        new : Dataset
        N)	rPror`r_�_Dataset__default_attrsrpr�r�r�)r\r=r�rx�inplacer<rXrBrBrC�_replace_vars_and_dims{s


zDataset._replace_vars_and_dimscCsH|rtdd�t|j�D��}n
|jj�}|j||jj�|jj�|j��S)z�Returns a copy of this dataset.

        If `deep=True`, a deep copy is made of each of the component variables.
        Otherwise, a shallow copy is made, so each variable in the new dataset
        is also a variable in the original dataset.
        css"|]\}}||jdd�fVqdS)T)�deepN)r�)rErFrGrBrBrCrH�szDataset.copy.<locals>.<genexpr>)r"r r`r�r�r_ror�)r\r�r=rBrBrCr��s
zDataset.copycs�t�}x|j�D]}|j|j�qWx:�jD]0}t�j|j�|kr,�j|||<|j|�q,Wt�fdd�|D��}�j	||||�S)Nc3s|]}|�j|fVqdS)N)ro)rErF)r\rBrCrH�sz8Dataset._subset_with_all_valid_coords.<locals>.<genexpr>)
rIr8r�r<r_r=r`�addr�r�)r\r=r�rx�needed_dimsrGrFr<rB)r\rC�_subset_with_all_valid_coords�sz%Dataset._subset_with_all_valid_coordscCs�t�}t�}xb|D]Z}y|j|||<Wqtk
rjt|j|�\}}}|||<||jkrf|j|�YqXqW|j|||jj	�d�S)z�Create a new Dataset with the listed variables from this dataset and
        the all relevant coordinates. Skips all validation.
        )rx)
r"rIr`r2rDr_r�r�rxr�)r\�namesr=r��namer?r@rMrBrBrC�_copy_listed�s

zDataset._copy_listedcCs�ddlm}y|j|}Wn&tk
r@t|j|�\}}}YnXt�}t|j�}x0|jD]&}t|j	|j�|krZ|j	|||<qZW||||dd�S)z7Construct a DataArray by indexing this dataset
        r)�	DataArrayT)r�Zfastpath)
�	dataarrayr�r`r2rDr"rIr<r{r=)r\r�r��variable�_r{r�rFrBrBrC�_construct_dataarray�s
zDataset._construct_dataarraycCs|jdd�S)NF)r�)r�)r\rBrBrC�__copy__�szDataset.__copy__cCs|jdd�S)NT)r�)r�)r\�memorBrBrC�__deepcopy__�szDataset.__deepcopy__cCs
||jkS)zzThe 'in' operator will return true or false depending on whether
        'key' is an array in the dataset or not.
        )r`)r\r>rBrBrCrc�szDataset.__contains__cCs
t|j�S)N)r4r`)r\rBrBrCrb�szDataset.__len__cCs
t|j�S)N)�iterr`)r\rBrBrCra�szDataset.__iter__cCstdd�|jj�D��S)Ncss|]}|jVqdS)N)�nbytes)rErGrBrBrCrH�sz!Dataset.nbytes.<locals>.<genexpr>)�sumr=r8)r\rBrBrCr��szDataset.nbytescCst|�S)z�Attribute for location based indexing. Only supports __getitem__,
        and only when the key is a dict of the form {dim: labels}.
        )ri)r\rBrBrC�loc�szDataset.loccCs<tj|�r|jf|�St|�r(|j|�S|jtj|��SdS)z�Access variables or coordinates this dataset as a
        :py:class:`~xarray.DataArray`.

        Indexing with a list of names will return a new ``Dataset`` object.
        N)rrj�iselrr�r�r9�asarray)r\r>rBrBrCrds


zDataset.__getitem__cCs$tj|�rtd��|j||i�dS)acAdd an array to this dataset.

        If value is a `DataArray`, call its `select_vars()` method, rename it
        to `key` and merge the contents of the resulting dataset into this
        dataset.

        If value is an `Variable` object (or tuple of form
        ``(dims, data[, attrs])``), add it to this dataset as a new
        variable.
        z:cannot yet use a dictionary as a key to set Dataset valuesN)rrj�NotImplementedErrorr�)r\r>r�rBrBrC�__setitem__s
zDataset.__setitem__csX�fdd�}|����jkrT�j�=�fdd�t�j�D�}x|D]�|��qDWdS)z�Remove a variable from this dataset.

        If this variable is a dimension, all variables containing this
        dimension are also removed.
        cs�j|=�jj|�dS)N)r`r_�discard)rF)r\rBrC�remove&sz#Dataset.__delitem__.<locals>.removecsg|]\}}�|jkr|�qSrB)r<)rErFrG)r>rBrCr�.sz'Dataset.__delitem__.<locals>.<listcomp>N)ror r`)r\r>r�Zalso_deleterB)r>r\rC�__delitem__ s

zDataset.__delitem__cs,�fdd�}|j|jko*tj|j|j|d�S)z(Helper function for equals and identicalcst|��|�S)N)r;)�x�y)�
compat_strrBrCr|:sz#Dataset._all_compat.<locals>.compat)r|)r_r�
dict_equivr`)r\�otherr�r|rB)r�rC�_all_compat6szDataset._all_compatcCs*y|j|d�Sttfk
r$dSXdS)a�Two Datasets are broadcast equal if they are equal after
        broadcasting all variables against each other.

        For example, variables that are scalar in one dataset but non-scalar in
        the other dataset can still be broadcast equal if the the non-scalar
        variable is a constant.

        See Also
        --------
        Dataset.equals
        Dataset.identical
        rmFN)r�rk�AttributeError)r\r�rBrBrCrm@s
zDataset.broadcast_equalscCs*y|j|d�Sttfk
r$dSXdS)a�Two Datasets are equal if they have matching variables and
        coordinates, all of which are equal.

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

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

        See Also
        --------
        Dataset.broadcast_equals
        Dataset.identical
        �equalsFN)r�rkr�)r\r�rBrBrCr�RszDataset.equalscCs:ytj|j|j�o|j|d�Sttfk
r4dSXdS)z�Like equals, but also checks all dataset attributes and the
        attributes on all variables and coordinates.

        See Also
        --------
        Dataset.broadcast_equals
        Dataset.equals
        �	identicalFN)rr�rxr�rkr�)r\r�rBrBrCr�fs
	zDataset.identicalcCst|�S)zJOrderedDict of pandas.Index objects used for label based indexing
        )r)r\rBrBrC�indexesuszDataset.indexescCst|�S)z]Dictionary of xarray.DataArray objects corresponding to coordinate
        variables
        )r)r\rBrBrCr{{szDataset.coordscCst|�S)zODictionary of xarray.DataArray objects corresponding to data variables
        )rZ)r\rBrBrCrz�szDataset.data_varscCstjdtdd�|jS)NzHthe Dataset property `vars` has been deprecated; use `data_vars` insteadr)rn)rsrtr�rz)r\rBrBrCr��s
zDataset.varscCs:t|t�r|g}|j|�|r"|n|j�}|jj|�|S)a�Given names of one or more variables, set them as coordinates

        Parameters
        ----------
        names : str or list of str
            Name(s) of variables in this dataset to convert into coordinates.
        inplace : bool, optional
            If True, modify this dataset inplace. Otherwise, create a new
            object.

        Returns
        -------
        Dataset
        )r1r!�_assert_all_in_datasetr�r_r�)r\r�r�rXrBrBrC�
set_coords�s

zDataset.set_coordscCs�|dkr|jt|j�}n2t|t�r*|g}|j|�tt|�t|j�@d�|rT|n|j�}|jj|�|r�x|D]}|j	|=qrW|S)aWGiven names of coordinates, reset them to become variables

        Parameters
        ----------
        names : str or list of str, optional
            Name(s) of non-index coordinates in this dataset to reset into
            variables. By default, all non-index coordinates are reset.
        drop : bool, optional
            If True, remove coordinates instead of converting them into
            variables.
        inplace : bool, optional
            If True, modify this dataset inplace. Otherwise, create a new
            object.

        Returns
        -------
        Dataset
        Nz5cannot remove index coordinates with reset_coords: %s)
r_rIr<r1r!r�rTr��difference_updater`)r\r��dropr�rXr�rBrBrC�reset_coords�s


zDataset.reset_coordsc
Csz|dkri}tj|�\}}t�}x(|j�D]\}}	|	||_|j|�q*W|r\|||�\}}|j|||�|rv|j�dS)z7Store dataset contents to a backends.*DataStore object.N)r
Zencode_dataset_coordinatesrIr��encodingr�r��sync)
r\r��encoderr�r�r=rxZcheck_encodingrF�encrBrBrC�
dump_to_store�s
zDataset.dump_to_store�wc	Cs.|dkri}ddlm}||||||||d�S)a�	Write dataset contents to a netCDF file.

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

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

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

            The default format is NETCDF4 if you are saving a file to disk and
            have the netCDF4-python library available. Otherwise, xarray falls
            back to using scipy to write netCDF files and defaults to the
            NETCDF3_64BIT format (scipy does not support netCDF4).
        group : str, optional
            Path to the netCDF4 group in the given file to open (only works for
            format='NETCDF4'). The group(s) will be created if necessary.
        engine : {'netcdf4', 'scipy', 'h5netcdf'}, optional
            Engine to use when writing netCDF files. If not provided, the
            default engine is chosen based on available dependencies, with a
            preference for 'netcdf4' if writing to a file on disk.
        encoding : dict, optional
            Nested dictionary with variable names as keys and dictionaries of
            variable specific encodings as values, e.g.,
            ``{'my_variable': {'dtype': 'int16', 'scale_factor': 0.1, 'zlib': True}, ...}``
        Nr)�	to_netcdf)ru�group�enginer�)Zbackends.apir�)r\�path�moderur�r�r�r�rBrBrCr��s
.zDataset.to_netcdf�dump�dumpscCs
tj|�S)N)rZdataset_repr)r\rBrBrCreszDataset.__repr__cshi�xV|jj�D]H}|jdk	rtt|j|j��}t�fdd�|D��rNtd���j|�qWt	t
���S)z[Block dimensions for this dataset's data or None if it's not a dask
        array.
        Nc3s&|]\}}|�kr|�|kVqdS)NrB)rE�d�chunk)�chunksrBrCrH#sz!Dataset.chunks.<locals>.<genexpr>zinconsistent chunks)r=r8r��listrJr<�anyrLr�rr)r\rGZ
new_chunksrB)r�rCr�s
zDataset.chunks�xarray-c
s�yddlm�Wn$tk
r4ddl}td��YnXt�t�rNtj�j����dk	rx�fdd��D�}|rxt	d|��dd	�������fd
d��t
��fdd��jj�D��}�j
|�S)
a�Coerce all arrays in this dataset into dask arrays with the given
        chunks.

        Non-dask arrays in this dataset will be converted to dask arrays. Dask
        arrays 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 or dict, optional
            Chunk sizes along each dimension, e.g., ``5`` or
            ``{'x': 5, 'y': 5}``.
        name_prefix : str, optional
            Prefix for the name of any new dask arrays.
        token : str, optional
            Token uniquely identifying this dataset.
        lock : optional
            Passed on to :py:func:`dask.array.from_array`, if the array is not
            already as dask array.

        Returns
        -------
        chunked : xarray.Dataset
        r)�tokenizeNz)xarray requires dask version 0.6 or newercsg|]}|�jkr|�qSrB)r<)rEr�)r\rBrCr�Psz!Dataset.chunk.<locals>.<listcomp>z6some chunks keys are not dimensions on this object: %scs"�dkrdSt�fdd�|D��S)Nc3s"|]}|�kr|�|fVqdS)NrB)rEr�)�dict_rBrCrHXsz1Dataset.chunk.<locals>.selkeys.<locals>.<genexpr>)r�)r�rvrB)r�rC�selkeysUszDataset.chunk.<locals>.selkeyscsX�||j�}|sd}|jdkrP�|�r*�n|j�}d�||f}|j||�d�S|SdS)Nrz%s%s-%s)r��lock)r<r5�_datar�)r�rMr�Ztoken2Zname2)r��name_prefixr��tokenr�rBrC�maybe_chunkZs
z"Dataset.chunk.<locals>.maybe_chunkcs g|]\}}|�||��f�qSrBrB)rErFrG)r�r�rBrCr�es)Z	dask.baser��ImportError�daskr1rr��fromkeysr<rLr"r=r�r�)r\r�r�r�r�r��bad_dimsr=rB)r�r�r�r�r\r�r�r�rCr�)s"
z
Dataset.chunkcs��fdd�|D�}|r"td|��dd�t|�D�}t�}x<t�j�D].\}�t�fdd�|D��}�jf|�||<qFW�j|�S)aReturns a new dataset with each array indexed along the specified
        dimension(s).

        This method selects values from each array using its `__getitem__`
        method, except this method does not require knowing the order of
        each array's dimensions.

        Parameters
        ----------
        **indexers : {dim: indexer, ...}
            Keyword arguments with names matching dimensions and values given
            by integers, slice objects or arrays.

        Returns
        -------
        obj : Dataset
            A new Dataset with the same contents as this dataset, except each
            array and dimension is indexed by the appropriate indexers. In
            general, each array's data will be a view of the array's data
            in this dataset, unless numpy fancy indexing was triggered by using
            an array indexer, in which case the data will be a copy.

        See Also
        --------
        Dataset.sel
        Dataset.sel_points
        Dataset.isel_points
        DataArray.isel
        csg|]}|�jkr|�qSrB)r<)rErF)r\rBrCr��sz Dataset.isel.<locals>.<listcomp>zdimensions %r do not existcSs4g|],\}}|t|ttjtf�s*tj|�n|f�qSrB)r1�intr9�integer�slicer�)rErFrGrBrBrCr��sc3s$|]\}}|�jkr||fVqdS)N)r<)rErFrG)rMrBrCrH�szDataset.isel.<locals>.<genexpr>)rLr r"r`r�r�r�)r\�indexers�invalidr=r�Zvar_indexersrB)r\rMrCr�iszDataset.iselcKs|jftj||||d��S)a�Returns a new dataset with each array indexed by tick labels
        along the specified dimension(s).

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

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

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

        Parameters
        ----------
        method : {None, 'nearest', 'pad'/'ffill', 'backfill'/'bfill'}, optional
            Method to use for inexact matches (requires pandas>=0.16):

            * None (default): only exact matches
            * pad / ffill: propgate last valid index value forward
            * backfill / bfill: propagate next valid index value backward
            * nearest: use nearest valid index value
        tolerance : optional
            Maximum distance between original and new labels for inexact
            matches. The values of the index at the matching locations most
            satisfy the equation ``abs(index[indexer] - target) <= tolerance``.
            Requires pandas>=0.17.
        **indexers : {dim: indexer, ...}
            Keyword arguments with names matching dimensions and values given
            by scalars, slices or arrays of tick labels.

        Returns
        -------
        obj : Dataset
            A new Dataset with the same contents as this dataset, except each
            variable and dimension is indexed by the appropriate indexers. In
            general, each variable's data will be a view of the variable's data
            in this dataset, unless numpy fancy indexing was triggered by using
            an array indexer, in which case the data will be a copy.

        See Also
        --------
        Dataset.isel
        Dataset.sel_points
        Dataset.isel_points
        DataArray.sel
        )�method�	tolerance)r�r	�remap_label_indexers)r\r�r�r�rBrBrCrl�s3
zDataset.sel�pointsc
sHt|���fdd�}|�j�}|�j�}|j��dd�t|�D�}xL|D]D\}}|�jkrftd|��|jjdkrzt	d��|j
dkrHtd	��qHWtd
d�|D��}t|�dkr�td��t|t
�r�|�jkr�td
��n:t|d�r�|j�jkr�td��nddlm}	|	|ddd�}t�fdd��fdd�tdd�|D��D�D�|||d�S)a
Returns a new dataset with each array indexed pointwise along the
        specified dimension(s).

        This method selects pointwise values from each array and is akin to
        the NumPy indexing behavior of `arr[[0, 1], [0, 1]]`, except this
        method does not require knowing the order of each array's dimensions.

        Parameters
        ----------
        dim : str or DataArray or pandas.Index or other list-like object, optional
            Name of the dimension to concatenate along. If dim is provided as a
            string, it must be a new dimension name, in which case it is added
            along axis=0. If dim is provided as a DataArray or Index or
            list-like object, its name, which must not be present in the
            dataset, is used as the dimension to concatenate along and the
            values are added as a coordinate.
        **indexers : {dim: indexer, ...}
            Keyword arguments with names matching dimensions and values given
            by array-like objects. All indexers must be the same length and
            1 dimensional.

        Returns
        -------
        obj : Dataset
            A new Dataset with the same contents as this dataset, except each
            array and dimension is indexed by the appropriate indexers. With
            pointwise indexing, the new Dataset will always be a copy of the
            original.

        See Also
        --------
        Dataset.sel
        Dataset.isel
        Dataset.sel_points
        DataArray.isel_points
        cs�fdd�|j�D�S)Ncs,g|]$\}}t�fdd�|jD��r|�qS)c3s|]}|�kVqdS)NrB)rEr�)�indexer_dimsrBrCrH�szHDataset.isel_points.<locals>.relevant_keys.<locals>.<listcomp>.<genexpr>)r�r<)rErFrG)r�rBrCr��sz>Dataset.isel_points.<locals>.relevant_keys.<locals>.<listcomp>)r�)�mapping)r�rBrC�
relevant_keys�sz*Dataset.isel_points.<locals>.relevant_keyscSsg|]\}}|tj|�f�qSrB)r9r�)rErFrGrBrBrCr��sz'Dataset.isel_points.<locals>.<listcomp>zdimension %s does not exist�izIndexers must be integersrzIndexers must be 1 dimensionalcss|]\}}t|�VqdS)N)r4)rErFrGrBrBrCrHsz&Dataset.isel_points.<locals>.<genexpr>z$All indexers must be the same lengthzQExisting dimension names are not valid choices for the dim argument in sel_pointsr<zLExisting dimensions are not valid choices for the dim argument in sel_points)r�r�)r<r�csg|]}�jf|��qSrB)r�)rEr�)r\rBrCr�scsg|]}tt�|���qSrB)r�rJ)rEZinds)rvrBrCr� scSsg|]\}}|�qSrBrB)rErFrGrBrBrCr�!s)rNr{rz)rIrzr{rvr r<rL�dtype�kindrkr5r4r1r!rVr�r�r�r$rJ)
r\rNr�r�rzr{rFrG�lengthsr�rB)r�rvr\rC�isel_points�s8%









zDataset.isel_pointscKs&tj||||d�}|jfd|i|��S)a�Returns a new dataset with each array indexed pointwise by tick
        labels along the specified dimension(s).

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

        In contrast to `Dataset.sel`, this method selects points along the
        diagonal of multi-dimensional arrays, not the intersection.

        Parameters
        ----------
        dim : str or DataArray or pandas.Index or other list-like object, optional
            Name of the dimension to concatenate along. If dim is provided as a
            string, it must be a new dimension name, in which case it is added
            along axis=0. If dim is provided as a DataArray or Index or
            list-like object, its name, which must not be present in the
            dataset, is used as the dimension to concatenate along and the
            values are added as a coordinate.
        method : {None, 'nearest', 'pad'/'ffill', 'backfill'/'bfill'}, optional
            Method to use for inexact matches (requires pandas>=0.16):

            * None (default): only exact matches
            * pad / ffill: propagate last valid index value forward
            * backfill / bfill: propagate next valid index value backward
            * nearest: use nearest valid index value
        tolerance : optional
            Maximum distance between original and new labels for inexact
            matches. The values of the index at the matching locations most
            satisfy the equation ``abs(index[indexer] - target) <= tolerance``.
            Requires pandas>=0.17.
        **indexers : {dim: indexer, ...}
            Keyword arguments with names matching dimensions and values given
            by array-like objects. All indexers must be the same length and
            1 dimensional.

        Returns
        -------
        obj : Dataset
            A new Dataset with the same contents as this dataset, except each
            array and dimension is indexed by the appropriate indexers. With
            pointwise indexing, the new Dataset will always be a copy of the
            original.

        See Also
        --------
        Dataset.sel
        Dataset.isel
        Dataset.isel_points
        DataArray.sel_points
        )r�r�rN)r	r�r�)r\rNr�r�r�Zpos_indexersrBrBrC�
sel_points$s4zDataset.sel_pointscs4t�fdd�|jj�D��}�jf|||d�|��S)a;Conform this object onto the indexes of another object, filling
        in missing values with NaN.

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

            * None (default): don't fill gaps
            * pad / ffill: propagate last valid index value forward
            * backfill / bfill: propagate next valid index value backward
            * nearest: use nearest valid index value (requires pandas>=0.16)
        tolerance : optional
            Maximum distance between original and new labels for inexact
            matches. The values of the index at the matching locations most
            satisfy the equation ``abs(index[indexer] - target) <= tolerance``.
            Requires pandas>=0.17.
        copy : bool, optional
            If `copy=True`, the returned dataset contains only copied
            variables. If `copy=False` and no reindexing is required then
            original variables from this dataset are returned.

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

        See Also
        --------
        Dataset.reindex
        align
        c3s$|]\}}|�jkr||fVqdS)N)r<)rErFrG)r\rBrCrH�sz'Dataset.reindex_like.<locals>.<genexpr>)r�r�r�)r�r�r��reindex)r\r�r�r�r�r�rB)r\rC�reindex_like\s*zDataset.reindex_likecsltj||d�}|s&|r"�jdd�S�S�fdd�|D�}|rHtd|��tj�j�j||||d�}�j|�S)a�Conform this object onto a new set of indexes, filling in
        missing values with NaN.

        Parameters
        ----------
        indexers : dict. optional
            Dictionary with keys given by dimension names and values given by
            arrays of coordinates tick labels. Any mis-matched coordinate values
            will be filled in with NaN, and any mis-matched dimension names will
            simply be ignored.
        method : {None, 'nearest', 'pad'/'ffill', 'backfill'/'bfill'}, optional
            Method to use for filling index values in ``indexers`` not found in
            this dataset:

            * None (default): don't fill gaps
            * pad / ffill: propagate last valid index value forward
            * backfill / bfill: propagate next valid index value backward
            * nearest: use nearest valid index value (requires pandas>=0.16)
        tolerance : optional
            Maximum distance between original and new labels for inexact
            matches. The values of the index at the matching locations most
            satisfy the equation ``abs(index[indexer] - target) <= tolerance``.
            Requires pandas>=0.17.
        copy : bool, optional
            If `copy=True`, the returned dataset contains only copied
            variables. If `copy=False` and no reindexing is required then
            original variables from this dataset are returned.
        **kw_indexers : optional
            Keyword arguments in the same form as ``indexers``.

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

        See Also
        --------
        Dataset.reindex_like
        align
        pandas.Index.get_indexer
        r�T)r�csg|]}|�jkr|�qSrB)r<)rEr�)r\rBrCr��sz#Dataset.reindex.<locals>.<listcomp>zinvalid reindex dimensions: %s)r�)	rZcombine_pos_and_kw_argsr�rLr
Zreindex_variablesr=r�r�)r\r�r�r�r�Zkw_indexersr�r=rB)r\rCr��s*zDataset.reindexc
s�x<�j�D]0\}}||kr&td|��||kr
td|��q
Wt�}t�}xht|j�D]Z\}}�j||�}t�fdd�|jD��}|j	dd�}	||	_|	||<||j
krV|j|�qVW|j|||d�S)a`Returns a new object with renamed variables and dimensions.

        Parameters
        ----------
        name_dict : dict-like
            Dictionary whose keys are current variable or dimension names and
            whose values are new names.
        inplace : bool, optional
            If True, rename variables and dimensions in-place. Otherwise,
            return a new dataset object.

        Returns
        -------
        renamed : Dataset
            Dataset with renamed variables and dimensions.

        See Also
        --------

        Dataset.swap_dims
        DataArray.rename
        z=cannot rename %r because it is not a variable in this datasetzthe new name %r already existsc3s|]}�j||�VqdS)N)�get)rErN)�	name_dictrBrCrH�sz!Dataset.rename.<locals>.<genexpr>F)r�)r�)
r�rLr"rIr r`r�tupler<r�r_r�r�)
r\rr�rFrGr=r�r�r<rMrB)rrC�rename�s$
zDataset.renamec
s�xL�j�D]@\}}||jkr(td|��|j|j|fkr
td||f��q
Wt�fdd�|jD��}t�}|jj�}|j�j	��xTt
|j�D]F\}}t�fdd�|jD��}||kr�|j�n|j
�}	||	_|	||<q�W|j|||d�S)ajReturns a new object with swapped dimensions.

        Parameters
        ----------
        dims_dict : dict-like
            Dictionary whose keys are current dimension names and whose values
            are new names. Each value must already be a variable in the
            dataset.
        inplace : bool, optional
            If True, swap dimensions in-place. Otherwise, return a new dataset
            object.

        Returns
        -------
        renamed : Dataset
            Dataset with swapped dimensions.

        See Also
        --------

        Dataset.rename
        DataArray.swap_dims
        zEcannot swap from dimension %r because it is not an existing dimensionzHreplacement dimension %r is not a 1D variable along the old dimension %rc3s|]}�j||�VqdS)N)r)rErN)�	dims_dictrBrCrHsz$Dataset.swap_dims.<locals>.<genexpr>c3s|]}�j||�VqdS)N)r)rErN)rrBrCrHs)r�)r�r<rLr=rIr"r_r�r�r8r rZto_coordZto_variabler�)
r\rr�rFrGZresult_dimsr=r�r<rMrB)rrC�	swap_dims�s$

zDataset.swap_dimscs�t�}x��jj�D]�\}�||krt�fdd�|D��r��fdd�|D�}t�j�|}�fdd�|D�}�j||�}|jf||i�}	|	||<q�jdd�||<qWt	j
j�fdd�|D�|d	�}
t||
�||<t
�j�t
|�t
|g�B}�j||�S)
Nc3s|]}|�jkVqdS)N)r<)rEr�)rMrBrCrH$sz&Dataset._stack_once.<locals>.<genexpr>csg|]}|�jkr|�qSrB)r<)rEr�)rMrBrCr�%sz'Dataset._stack_once.<locals>.<listcomp>csg|]}�j|�qSrB)r<)rEr�)r\rBrCr�'sF)r�csg|]}�j|�qSrB)r�)rEr�)r\rBrCr�.s)r�)r"r=r�r�r�r<�expand_dims�stackr�r7�
MultiIndex�from_productrrIr_r�)r\r<�new_dimr=r�Zadd_dimsZvdimsrKZexp_varZstacked_var�idxr�rB)r\rMrC�_stack_once s 
zDataset._stack_oncecKs*|}x |j�D]\}}|j||�}qW|S)aS
        Stack any number of existing dimensions into a single new dimension.

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

        Parameters
        ----------
        **dimensions : keyword arguments of the form new_name=(dim1, dim2, ...)
            Names of new dimensions, and the existing dimensions that they
            replace.

        Returns
        -------
        stacked : Dataset
            Dataset with stacked data.

        See also
        --------
        Dataset.unstack
        )r�r
)r\Z
dimensions�resultrr<rBrBrCr6sz
Dataset.stackc
Cs<||jkrtd|��|j|}t|tj�s4td��tjj|j|jd�}|j	fddi||i��}|j}t
dd�|D��r�td��d	d
�|jD�}t�}xT|jj
�D]F\}}	||kr�||	jkr�tt||��}
|	jf||
i�||<q�|	||<q�Wx&t||j�D]\}}t||�||<q�Wt|j�t|g�t|�B}|j||�S)a�
        Unstack an existing dimension corresponding to a MultiIndex into
        multiple new dimensions.

        New dimensions will be added at the end.

        Parameters
        ----------
        dim : str
            Name of the existing dimension to unstack.

        Returns
        -------
        unstacked : Dataset
            Dataset with unstacked data.

        See also
        --------
        Dataset.stack
        zinvalid dimension: %sz:cannot unstack a dimension that does not have a MultiIndex)r�r�Fcss|]}|dkVqdS)NrB)rEr�rBrBrCrHrsz"Dataset.unstack.<locals>.<genexpr>z,cannot unstack dimension with unnamed levelscSsg|]
}|j�qSrB)rO)rE�levrBrBrCr�usz#Dataset.unstack.<locals>.<listcomp>)r<rLr�r1r7r	r
�levelsr�r�r�r"r=r�rJ�unstackrrIr_r�)
r\rN�index�full_idxrXZ
new_dim_namesZ
new_dim_sizesr=r�rMZnew_dimsrr�rBrBrCrQs,


zDataset.unstackcCs|j||t|�dd�S)akUpdate this dataset's variables with those from another dataset.

        Parameters
        ----------
        other : Dataset or castable to Dataset
            Dataset or variables with which to update this dataset.
        inplace : bool, optional
            If True, merge the other dataset into this dataset in-place.
            Otherwise, return a new dataset object.

        Returns
        -------
        updated : Dataset
            Updated dataset.

        Raises
        ------
        ValueError
            If any dimensions would have inconsistent sizes in the updated
            dataset.
        �left)r��overwrite_vars�join)�merger�)r\r�r�rBrBrCr��szDataset.update�outerc	Cs6t|||||d�\}}|r|n|j�}|j||�|S)a&Merge the arrays of two datasets into a single dataset.

        This method generally not allow for overriding data, with the exception
        of attributes, which are ignored on the second dataset. Variables with
        the same name are checked for conflicts via the equals or identical
        methods.

        Parameters
        ----------
        other : Dataset or castable to Dataset
            Dataset or variables to merge with this dataset.
        inplace : bool, optional
            If True, merge the other dataset into this dataset in-place.
            Otherwise, return a new dataset object.
        overwrite_vars : str or sequence, optional
            If provided, update variables of these name(s) without checking for
            conflicts in this dataset.
        compat : {'broadcast_equals', 'equals', 'identical'}, optional
            String indicating how to compare variables of the same name for
            potential conflicts:

            - 'broadcast_equals': all values must be equal when variables are
              broadcast against each other to ensure common dimensions.
            - 'equals': all values and dimensions must be the same.
            - 'identical': all values, dimensions and attributes must be the
              same.
        join : {'outer', 'inner', 'left', 'right'}, optional
            Method for joining ``self`` and ``other`` along shared dimensions:

            - 'outer': use the union of the indexes
            - 'inner': use the intersection of the indexes
            - 'left': use indexes from ``self``
            - 'right': use indexes from ``other``

        Returns
        -------
        merged : Dataset
            Merged dataset.

        Raises
        ------
        ValueError
            If any variables conflict (see ``compat``).
        )r|r)rr�r�)	r\r�r�rr|rZreplace_varsrrXrBrBrCr�s
.z
Dataset.mergecCs0t|�t|j�}|r ||j8}|r,td��dS)NzFOne or more of the specified variables cannot be found in this dataset)rIr`Zvirtual_variablesrL)r\r�Zvirtual_okayZ	bad_namesrBrBrCr��s

zDataset._assert_all_in_datasetcCsDtj|�r|g}|dkr"|j|�S|j|j|�}|j||iSdS)aDrop variables or index labels from this dataset.

        If a variable corresponding to a dimension is dropped, all variables
        that use that dimension are also dropped.

        Parameters
        ----------
        labels : str
            Names of variables or index labels to drop.
        dim : None or str, optional
            Dimension along which to drop index labels. By default (if
            ``dim is None``), drops variables rather than index labels.

        Returns
        -------
        dropped : Dataset
        N)rZ	is_scalar�
_drop_varsr�r�r�)r\�labelsrNZ	new_indexrBrBrCr��s

zDataset.dropcsr|j��t����t�fdd�t|j�D��O�t�fdd�t|j�D���t�fdd�|jD��}|j�|�S)Nc3s,|]$\}�t�fdd��D��r|VqdS)c3s|]}|�jkVqdS)N)r<)rEr�)rGrBrCrH�sz/Dataset._drop_vars.<locals>.<genexpr>.<genexpr>N)r�)rErF)r�)rGrCrH�sz%Dataset._drop_vars.<locals>.<genexpr>c3s"|]\}}|�kr||fVqdS)NrB)rErFrG)r�rBrCrH�sc3s|]}|�kr|VqdS)NrB)rErF)r=rBrCrH�s)r�rIr r`r"r_r�)r\r�r�rB)r�r�r=rCr�s
 zDataset._drop_varscGstjdtdd�|j|�S)NzFthe Dataset method `drop_vars` has been deprecated; use `drop` insteadr)rn)rsrtr�r�)r\r�rBrBrC�	drop_varss
zDataset.drop_varscsv|r,t|�t|j�Ar,td|t|j�f��|j�}x<t|j�D].\}�t�fdd�|D��}�j|�|j|<q@W|S)aKReturn a new Dataset object with all array dimensions transposed.

        Although the order of dimensions on each array will change, the dataset
        dimensions themselves will remain in fixed (sorted) order.

        Parameters
        ----------
        *dims : str, optional
            By default, reverse the dimensions on each array. Otherwise,
            reorder the dimensions to this order.

        Returns
        -------
        transposed : Dataset
            Each array in the dataset (including) coordinates will be
            transposed to the given order.

        Notes
        -----
        Although this operation returns a view of each array's data, it
        is not lazy -- the data will be fully loaded into memory.

        See Also
        --------
        numpy.transpose
        DataArray.transpose
        zDarguments to transpose (%s) must be permuted dataset dimensions (%s)c3s|]}|�jkr|VqdS)N)r<)rErN)rMrBrCrH)sz$Dataset.transpose.<locals>.<genexpr>)rIr<rLrr�r r`�	transpose)r\r<�dsr�Zvar_dimsrB)rMrCrszDataset.transposecCs|j�S)N)r)r\rBrBrC�T-sz	Dataset.TcCstj||j|�S)a�Returns a new dataset 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 : Dataset
            This dataset, but with with all or a subset of the dimensions of
            length 1 removed.

        Notes
        -----
        Although this operation returns a view of each variable's data, it is
        not lazy -- all variable data will be fully loaded.

        See Also
        --------
        numpy.squeeze
        )r�squeezer<)r\rNrBrBrCr1szDataset.squeezer�cs��jkrtd���|dkr(t�j�}tj�j�tjd�}d}x^|D]V}�j|}�|jkrH�fdd�|jD�}	||j|	�7}|tj	�fdd�|	D��7}qHW|dk	r�||k}
nB|dkr�||k}
n0|d	kr�|dk}
n|dk	r�td
|��nt
d���jf�|
i�S)aReturns a new dataset with dropped labels for missing values along
        the provided dimension.

        Parameters
        ----------
        dim : str
            Dimension along which to drop missing values. Dropping along
            multiple dimensions simultaneously is not yet supported.
        how : {'any', 'all'}, optional
            * any : if any NA values are present, drop that label
            * all : if all values are NA, drop that label
        thresh : int, default None
            If supplied, require this many non-NA values.
        subset : sequence, optional
            Subset of variables to check for missing values. By default, all
            variables in the dataset are checked.

        Returns
        -------
        Dataset
        z%%s must be a single dataset dimensionN)r�rcsg|]}|�kr|�qSrBrB)rEr�)rNrBrCr�rsz"Dataset.dropna.<locals>.<listcomp>csg|]}�j|�qSrB)r<)rEr�)r\rBrCr�tsr��allzinvalid how option: %szmust specify how or thresh)r<rLr�rzr9�zerosZint64r`�count�prodrkr�)r\rN�howZthreshZsubsetr"rOrFr:r<�maskrB)rNr\rC�dropnaLs,




 


zDataset.dropnacCs
|j|�S)a'Fill missing values in this object.

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

        Parameters
        ----------
        value : scalar, ndarray, DataArray, dict or Dataset
            Used to fill all matching missing values in this dataset's data
            variables. Scalars, ndarrays or DataArrays arguments are used to
            fill all data with aligned coordinates (for DataArrays).
            Dictionaries or datasets match data variables and then align
            coordinates if necessary.

        Returns
        -------
        Dataset
        )Z_fillna)r\r�rBrBrC�fillna�szDataset.fillnacs8t|t�rt|g��n|dkr*t�j��nt|��t�fdd��D�d�t��x�t�j�D]�\}}�fdd�|jD�}	|	s�|jr�|�jkr�|s�t	j
|jt	j�s�|jt	j
kr�t|	�dkr�|	\}	nt|	�|jkr�d}	|j|f|	||d�|���|<q\|�|<q\Wt�fdd	��jD��}
|�r&�jnd}�j�|
|�S)
aoReduce this dataset by applying `func` along some dimension(s).

        Parameters
        ----------
        func : function
            Function which can be called in the form
            `f(x, axis=axis, **kwargs)` to return the result of reducing an
            np.ndarray over an integer valued axis.
        dim : str or sequence of str, optional
            Dimension(s) over which to apply `func`.  By default `func` is
            applied over all dimensions.
        keep_attrs : bool, optional
            If True, the dataset's attributes (`attrs`) will be copied from
            the original object to the new one.  If False (default), the new
            object will be returned without attributes.
        numeric_only : bool, optional
            If True, only apply ``func`` to variables with a numeric dtype.
        **kwargs : dict
            Additional keyword arguments passed on to ``func``.

        Returns
        -------
        reduced : Dataset
            Dataset with this object's DataArrays replaced with new DataArrays
            of summarized data and the indicated dimension(s) removed.
        Ncsg|]}|�jkr|�qSrB)r<)rErN)r\rBrCr��sz"Dataset.reduce.<locals>.<listcomp>z+Dataset does not contain the dimensions: %scsg|]}|�kr|�qSrBrB)rErN)r<rBrCr��sr)rN�
keep_attrs�
allow_lazyc3s|]}|�kr|VqdS)NrB)rErF)r=rBrCrH�sz!Dataset.reduce.<locals>.<genexpr>)r1r!rIr<rTr"r r`r{r9Z
issubdtyper��numberZbool_r4r5�reducerxr�)r\�funcrNr(Znumeric_onlyr)r}r�rMZreduce_dimsr�rxrB)r<r\r=rCr+�s6


zDataset.reducecs>t���fdd�t|j�D��}|r*|jnd}t|�||d�S)a:Apply a function over the data variables in this dataset.

        Parameters
        ----------
        func : function
            Function which can be called in the form `f(x, **kwargs)` to
            transform each DataArray `x` in this dataset into another
            DataArray.
        keep_attrs : bool, optional
            If True, the dataset's attributes (`attrs`) will be copied from
            the original object to the new one. If False, the new object will
            be returned without attributes.
        args : tuple, optional
            Positional arguments passed on to `func`.
        **kwargs : dict
            Keyword arguments passed on to `func`.

        Returns
        -------
        applied : Dataset
            Resulting dataset from applying ``func`` over each data variable.
        c3s,|]$\}}|t|�|f�����fVqdS)N)r)rErFrG)rRr,r}rBrCrH�sz Dataset.apply.<locals>.<genexpr>N)rx)r"r rzrx�type)r\r,r(rRr}r=rxrB)rRr,r}rC�apply�s
z
Dataset.applycKs |j�}|j|�}|j|�|S)a8Assign new data variables to a Dataset, returning a new object
        with all the original variables in addition to the new ones.

        Parameters
        ----------
        kwargs : keyword, value pairs
            keywords are the variables names. If the values are callable, they
            are computed on the Dataset and assigned to new data variables. If
            the values are not callable, (e.g. a DataArray, scalar, or array),
            they are simply assigned.

        Returns
        -------
        ds : Dataset
            A new Dataset with the new variables in addition to all the
            existing variables.

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

        See Also
        --------
        pandas.DataFrame.assign
        )r�Z_calc_assign_resultsr�)r\r}rA�resultsrBrBrC�assign�s

zDataset.assignr�c	s|ddlm}�fdd��jD�}t|�}tjdd�|D�dd�}t�j�}t�j�||<|f|dj	}||||�j
|d�S)	a�Convert this dataset into an xarray.DataArray

        The data variables of this dataset will be broadcast against each other
        and stacked along the first axis of the new array. All coordinates of
        this dataset will remain coordinates.

        Parameters
        ----------
        dim : str, optional
            Name of the new dimension.
        name : str, optional
            Name of the new data array.

        Returns
        -------
        array : xarray.DataArray
        r)r�csg|]}�j|�qSrB)r=)rErF)r\rBrCr�2sz$Dataset.to_array.<locals>.<listcomp>cSsg|]
}|j�qSrB)rA)rE�brBrBrCr�4sr)Zaxis)rxr�)r�r�rzrrrr�r{r�r<rx)	r\rNr�r�rzZbroadcast_varsrAr{r<rB)r\rC�to_arrays
zDataset.to_arraycsJ�fdd��D�}��fdd�|D�}�jj��}tjtt||��|d�S)Ncsg|]}|�jkr|�qSrB)r<)rErF)r\rBrCr�>sz)Dataset._to_dataframe.<locals>.<listcomp>cs$g|]}�j|j��jjd��qS)r���)r`rr8�reshape)rErF)�ordered_dimsr\rBrCr�?s)r)r{r6r7Z	DataFramer"rJ)r\r5�columnsrArrB)r5r\rC�
_to_dataframe=s
zDataset._to_dataframecCs|j|j�S)z�Convert this dataset into a pandas.DataFrame.

        Non-index variables in this dataset form the columns of the
        DataFrame. The DataFrame is be indexed by the Cartesian product of
        this dataset's indices.
        )r7r<)r\rBrBrC�to_dataframeDszDataset.to_dataframecCs�|jjstd��|j}|�}t|d�r�tjj|j|j	d�}|j
|�}dd�t|j	�D�}x$t||j�D]\}}||f||<qfWdd�|jD�}n*|j
dk	r�|j
ndf}||f||d	<d}x,t|�D] \}	}
|
jj|�}||f||	<q�W|S)a%Convert a pandas.DataFrame into an xarray.Dataset

        Each column will be converted into an independent variable in the
        Dataset. If the dataframe's index is a MultiIndex, it will be expanded
        into a tensor product of one-dimensional indices (filling in missing
        values with NaN). This method will produce a Dataset very similar to
        that on which the 'to_dataframe' method was called, except with
        possibly redundant dimensions (since all dataset variables will have
        the same dimensionality).
        z0cannot convert DataFrame with non-unique columnsr)r�cSs$g|]\}}|dk	r|nd|�qS)Nzlevel_%irB)rE�nr�rBrBrCr�isz*Dataset.from_dataframe.<locals>.<listcomp>cSsg|]
}|j�qSrB)rO)rErrBrBrCr�msNrrrr3)r6Z	is_uniquerLrrVr7r	r
rr�r��	enumeraterJr�r r8r4)r�Z	dataframerrXrr<rNrrKr�ZseriesrArBrBrC�from_dataframeMs(

zDataset.from_dataframecstj����fdd��}|S)NcsF|jj�}x*|jD] }�|j|f|�|�|j|<qW�rB|j|_|S)N)r{rUrzr`rp)r\rRr}rrF)�fr(rBrCr,zs
 zDataset._unary_op.<locals>.func)�	functools�wraps)r<r(r,rB)r<r(rC�	_unary_opxszDataset._unary_op�innercs tj������fdd��}|S)Ncszt|tj�rtSt|d�rRt||�dd�\}}dd�|jj�D�}|rRtd|���sZ�n
�fdd�}|j	||�d	�}|S)
Nr�F)rr�cSsg|]\}}|dkr|�qS)rrB)rEr��srBrBrCr��sz4Dataset._binary_op.<locals>.func.<locals>.<listcomp>z-no overlapping labels for some dimensions: %scs
�||�S)NrB)r�r�)r<rBrC�<lambda>�sz2Dataset._binary_op.<locals>.func.<locals>.<lambda>)�drop_na_vars)
r1r�GroupBy�NotImplementedrVrr<r�rL�_calculate_binary_op)r\r�Z
empty_indexes�gr)rCr<r�	reflexiverBrCr,�s
z Dataset._binary_op.<locals>.func)r=r>)r<rHrrCr,rB)rCr<rrHrC�
_binary_op�s
zDataset._binary_opcstj���fdd��}|S)Ncsbt|tj�rtd��t|d�r,|j|dd�}tj��}|j||dd�}|j	|j
|j|jdd�|S)NzLin-place operations between a Dataset and a grouped object are not permittedr�F)r�T)r�)
r1rrDrkrVrrZinplace_to_noninplace_oprFr�r`r_rp)r\r�rGr)r<rBrCr,�s

z(Dataset._inplace_binary_op.<locals>.func)r=r>)r<r,rB)r<rC�_inplace_binary_op�s
zDataset._inplace_binary_opc
s����fdd�}tj|�r@t|t�r@|�j|�j|�}t|�St|dd�}�jj|�}t|t�rz|�j|j�j|j�}	n(t|d|��t	���fdd��jD��}	|j
j|	�|S)Ncs�t�}d}x^|D]V}||kr8�||||�||<d}q�rVtdt|�t|�f��q�s||||<qW|s�tdt|�t|�f��|S)NFTzUdatasets must have the same data variables for in-place arithmetic operations: %s, %sz3datasets have no overlapping data variables: %s, %s)r"rLr�)Z
lhs_data_varsZ
rhs_data_varsZlhs_varsZrhs_varsZ	dest_varsZperformed_oprF)rCr<r�rBrC�apply_over_both�s"
z5Dataset._calculate_binary_op.<locals>.apply_over_bothr{r�c3s"|]}|��j|��fVqdS)N)r=)rErF)r<�other_variabler\rBrCrH�sz/Dataset._calculate_binary_op.<locals>.<genexpr>)rrjr1rWrzr;r{rr=r"r`r�)
r\r<r�r�rCrKZ
new_data_varsZother_coordsrZnew_varsrB)rCr<r�rLr\rCrF�s


zDataset._calculate_binary_opr�uppercCs�|dkr|S|dkr"tdj|���|tdd�i}|tdd�i}|dkrL|}n|dkrZ|}ntd��t�}xbt|j�D]T\}}	||	jkr�||jkr�|	jf|�|	jf|�||<q�|	jf|�||<qt|	||<qtW|j	|�}
|dkr�|
j
||d�S|
SdS)	a�Calculate the n-th order discrete difference along given axis.

        Parameters
        ----------
        dim : str, optional
            Dimension over which to calculate the finite difference.
        n : int, optional
            The number of times values are differenced.
        label : str, optional
            The new coordinate in dimension ``dim`` will have the
            values of either the minuend's or subtrahend's coordinate
            for values 'upper' and 'lower', respectively.  Other
            values are not supported.

        Returns
        -------
        difference : same type as caller
            The n-th order finite difference of this object.

        Examples
        --------
        >>> ds = xr.Dataset({'foo': ('x', [5, 5, 6, 6])})
        >>> ds.diff('x')
        <xarray.Dataset>
        Dimensions:  (x: 3)
        Coordinates:
          * x        (x) int64 1 2 3
        Data variables:
            foo      (x) int64 0 1 0
        >>> ds.diff('x', 2)
        <xarray.Dataset>
        Dimensions:  (x: 2)
        Coordinates:
        * x        (x) int64 2 3
        Data variables:
        foo      (x) int64 1 -1

        rz*order `n` must be non-negative but got {0}NrrM�lowerz8The 'label' argument has to be either 'upper' or 'lower'r3)rLrur�r"r r=r<rzr�r��diff)r\rNr9�labelZkwargs_startZ
kwargs_endZ
kwargs_newr=r�rM�
differencerBrBrCrO�s0'



zDataset.diffcs��fdd�|D�}|r"td|��t�}xTt�j�D]F\}�|�jkrrt�fdd�|j�D��}�jf|�||<q4�||<q4W�j|�S)a�Shift this dataset by an offset along one or more dimensions.

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

        Parameters
        ----------
        **shifts : keyword arguments 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.

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

        See also
        --------
        roll

        Examples
        --------

        >>> ds = xr.Dataset({'foo': ('x', list('abcde'))})
        >>> ds.shift(x=2)
        <xarray.Dataset>
        Dimensions:  (x: 5)
        Coordinates:
          * x        (x) int64 0 1 2 3 4
        Data variables:
            foo      (x) object nan nan 'a' 'b' 'c'
        csg|]}|�jkr|�qSrB)r<)rErF)r\rBrCr�Bsz!Dataset.shift.<locals>.<listcomp>zdimensions %r do not existc3s$|]\}}|�jkr||fVqdS)N)r<)rErFrG)rMrBrCrHIsz Dataset.shift.<locals>.<genexpr>)	rLr"r r=rzr�r��shiftr�)r\�shiftsr�r=r��
var_shiftsrB)r\rMrCrRs#
z
Dataset.shiftcst�fdd�|D�}|r"td|��t�}x@t�j�D]2\}�t�fdd�|j�D��}�jf|�||<q4W�j|�S)a�Roll this dataset by an offset along one or more dimensions.

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

        Parameters
        ----------
        **shifts : keyword arguments of the form {dim: offset}
            Integer offset to rotate each of the given dimensions. Positive
            offsets roll to the right; negative offsets roll to the left.

        Returns
        -------
        rolled : Dataset
            Dataset with the same coordinates and attributes but rolled
            variables.

        See also
        --------
        shift

        Examples
        --------

        >>> ds = xr.Dataset({'foo': ('x', list('abcde'))})
        >>> ds.roll(x=2)
        <xarray.Dataset>
        Dimensions:  (x: 5)
        Coordinates:
          * x        (x) int64 3 4 0 1 2
        Data variables:
            foo      (x) object 'd' 'e' 'a' 'b' 'c'
        csg|]}|�jkr|�qSrB)r<)rErF)r\rBrCr�ssz Dataset.roll.<locals>.<listcomp>zdimensions %r do not existc3s$|]\}}|�jkr||fVqdS)N)r<)rErFrG)rMrBrCrHyszDataset.roll.<locals>.<genexpr>)rLr"r r=r�r��rollr�)r\rSr�r=r�rTrB)r\rMrCrUQs"zDataset.rollcCs|jdd�dd�|�S)NcSs|jS)N)�real)r�rBrBrCrB�szDataset.real.<locals>.<lambda>T)r()r?)r\rBrBrCrVszDataset.realcCs|jdd�dd�|�S)NcSs|jS)N)�imag)r�rBrBrCrB�szDataset.imag.<locals>.<lambda>T)r()r?)r\rBrBrCrW�szDataset.imag)NNNrm)NTT)N)N)F)N)F)NFF)NTN)Nr�NNNN)Nr�NF)NN)r�)r�NN)NNT)NNNT)F)F)T)F)N)N)r�NN)NFFF)r�N)F)Fr@T)FT)rrM)grfrgrh�__doc__rZDatasetGroupByZgroupby_clsr^r~r�rw�classmethodr�r�r�r�r��propertyr=r�rx�setterr<r�r�r�r�r�r�r�r�r�r�r�r�rcrbrar�r�rdr�r��__hash__r�rmr�r�r�r{rzr�r�r�r�r�rZfunction_aliasr�r�rer�r�r�rlr�r�rr�rrr
rrr�rIrr�r�rrrrrr&r'r+r.r0r2r7r8r;�staticmethodr?rIrJrFrOrRrUrVrWrBrBrBrCrW�s�
7

	
%




#

3
?.
6
W
8
/
8
,
16
3


'

7
A%
	+
,
M2.rWF)Z
array_only)rQ)9r=rs�collectionsrZnumbersrZnumpyr9Zpandasr7�rrrrr	r
rr
rrZcoordinatesrrrrrrrrrrrrr�rrrrrZpycompatr r!r"r#�combiner$Z_DATETIMEINDEX_COMPONENTSrDrPrTrYrZr�rirWZ!inject_all_ops_and_reduce_methodsrBrBrBrC�<module>sb