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__/dataarray.cpython-36.pyc
3

���h���@s,ddlZddlZddlZddlZddlZddlmZddl	m
Z
ddl	mZddl	mZddl	m
Z
dd	lmZdd
lmZmZmZddlmZmZddlmZdd
lmZmZmZmZddlmZm Z m!Z!m"Z"m#Z#ddl$m%Z%dd�Z&Gdd�de'�Z(Gdd�de'�Z)Gdd�dee�Z*ej+e*dd�dS)�N�)�_PlotMethods�)�indexing)�groupby)�ops)�utils)�align)�
AbstractArray�BaseDataObject�squeeze)�DataArrayCoordinates�Indexes)�Dataset)�	iteritems�
basestring�OrderedDict�zip)�as_variable�Variable�as_compatible_data�
Coordinate�default_index_coordinate)�format_itemcs|dk	r<tj|�r<t|�t|�kr<tdt|�t|�f��t�t�rL�f��dkr�dd�tt|��D��|dk	r�t|�t|�kr�tj|�r�t|j���n:x8t	t
�|��D]&\}\}}t||d�j�}|j
�|<q�Wt���n$x"�D]}t|t�s�td|��q�Wt�}tj|��r@xl|j�D]\}}	t|	|dd�||<�qWnB|dk	�r�x6t
�|�D](\}}t||dd�}
|f|
_|
||<�qVWx0t
�|�D]"\}}||k�r�t||�||<�q�WxD|j�D]8\}}	t�fd	d
�|	jD���r�td||	j�f���q�W|�fS)z*All the logic for creating a new DataArrayNz`coords is not dict-like, but it has %s items, which does not match the %s dimensions of the datacSsg|]}d|�qS)zdim_%s�)�.0�nrr�5/tmp/pip-build-5_djhm0z/xray/xarray/core/dataarray.py�
<listcomp>%sz*_infer_coords_and_dims.<locals>.<listcomp>)�keyzdimension %s is not a stringT)r�copyc3s|]}|�kVqdS)Nr)r�d)�dimsrr�	<genexpr>Dsz)_infer_coords_and_dims.<locals>.<genexpr>zZcoordinate %s has dimensions %s, but these are not a subset of the DataArray dimensions %s)r�is_dict_like�len�
ValueError�
isinstancer�range�list�keys�	enumeraterrZto_coord�name�tuple�	TypeErrorr�itemsr"r�any)�shape�coordsr"r�dim�coordr!Z
new_coords�k�v�var�sizer)r"r�_infer_coords_and_dimssF






r9c@s,eZdZdd�Zdd�Zdd�Zdd�Zd	S)
�_LocIndexercCs
||_dS)N)�
data_array)�selfr;rrr�__init__Msz_LocIndexer.__init__csd�fdd��tj|�r0t�fdd�t|�D��Stj|�jj�}t�fdd�t	�jj
|�D��SdS)Ncs�jj|}tj||�S)N)r;�indexesrZconvert_label_indexer)r3�labels�index)r<rr�lookup_positionsQsz0_LocIndexer._remap_key.<locals>.lookup_positionsc3s |]\}}|�||�fVqdS)Nr)rr3r?)rArrr#Vsz)_LocIndexer._remap_key.<locals>.<genexpr>c3s|]\}}�||�VqdS)Nr)rr3r?)rArrr#[s)rr$�dictrr�expanded_indexerr;�ndimr-rr")r<rr)rAr<r�
_remap_keyPs
z_LocIndexer._remap_keycCs|j|j|�S)N)r;rE)r<rrrr�__getitem__^sz_LocIndexer.__getitem__cCs||j|j|�<dS)N)r;rE)r<r�valuerrr�__setitem__asz_LocIndexer.__setitem__N)�__name__�
__module__�__qualname__r=rErFrHrrrrr:Lsr:c@seZdZdZdd�ZdS)�
_ThisArrayz�An instance of this object is used as the key corresponding to the
    variable when converting arbitrary DataArray objects to datasets
    cCsdS)Nz<this-array>r)r<rrr�__repr__isz_ThisArray.__repr__N)rIrJrK�__doc__rMrrrrrLesrLc@s�eZdZdZejZd�dd�Ze�Z	dde	fdd�Z
e	fdd	�Ze�Z
d
d�Ze	fdd
�Zdd�Zd�dd�Zd�dd�Zedd��Zejdd��Zedd��Zedd��Zedd��Zedd��Zed d!��Zed"d#��Zd$d%�Zed&d'��Zejd(d'��Zed)d*��Zejd+d*��Zed,d-��Zd.d/�Z ed0d1��Z!e!jd2d1��Z!d3d4�Z"d5d6�Z#d7d8�Z$d9d:�Z%ed;d<��Z&d=d>�Z'ed?d@��Z(edAdB��Z)e)jdCdB��Z)edDdE��Z*e*jdFdE��Z*edGdH��Z+edIdJ��Z,d�dKdL�Z-dMdN�Z.dOdP�Z/d�dQdR�Z0dSdT�Z1d�dUdV�Z2dZ3edWdX��Z4d�dYdZ�Z5d[d\�Z6d�d]d^�Z7d�d`da�Z8d�dbdc�Z9d�ddde�Z:d�dfdg�Z;dhdi�Z<djdk�Z=dldm�Z>dndo�Z?dpdq�Z@d�drds�ZAd�dtdu�ZBd�dwdx�ZCdydz�ZDd�d{d|�ZEd}d~�ZFd�dd��ZGd�d��ZHd�d�d��ZIeJd�d���ZKd�d��ZLeJd�d���ZMd�d��ZNd�d��ZOd�d��ZPd�d��ZQe�ZRd�d�d��ZSd�d�d��ZTeUd�d���ZVeUd�d�d���ZWeUd�d���ZXed�d���ZYd�d�d��ZZd�d�d��Z[d�d��Z\d�d��Z]ed�d���Z^ed�d���Z_dS)��	DataArraya�N-dimensional array with labeled coordinates and dimensions.

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

    Additional features over raw numpy arrays:

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

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

    Attributes
    ----------
    dims : tuple
        Dimension names associated with this array.
    values : np.ndarray
        Access or modify DataArray values as a numpy array.
    coords : dict-like
        Dictionary of Coordinate objects that label values along each dimension.
    name : str or None
        Name of this array.
    attrs : OrderedDict
        Dictionary for holding arbitrary metadata.
    NFc	CsF|r.|}|dkst�|dks t�|dks,t�n�|dkr�t|dd�}t|tj�rX|jg}nNt|tj�rr|j|jg}n4t|tjt	f�r�|g}nt|tj
�r�|j|j|j
g}|dkr�t|dt|dd��}|dkr�t|dd�}|dkr�t|dd�}|dkr�t|dd�}t|�}t|j||�\}}t||||dd�}||_||_||_d|_dS)	a�
        Parameters
        ----------
        data : array_like
            Values for this array. Must be an ``numpy.ndarray``, ndarray like,
            or castable to an ``ndarray``. If a self-described xarray or pandas
            object, attempts are made to use this array's metadata to fill in
            other unspecified arguments. A view of the array's data is used
            instead of a copy if possible.
        coords : sequence or dict of array_like objects, optional
            Coordinates (tick labels) to use for indexing along each dimension.
            If dict-like, should be a mapping from dimension names to the
            corresponding coordinates.
        dims : str or sequence of str, optional
            Name(s) of the the data dimension(s). Must be either a string (only
            for 1D data) or a sequence of strings with length equal to the
            number of dimensions. If this argument is omitted, dimension names
            are taken from ``coords`` (if possible) and otherwise default to
            ``['dim_0', ... 'dim_n']``.
        name : str or None, optional
            Name of this array.
        attrs : dict_like or None, optional
            Attributes to assign to the new instance. By default, an empty
            attribute dictionary is initialized.
        encoding : dict_like or None, optional
            Dictionary specifying how to encode this array's data into a
            serialized format like netCDF4. Currently used keys (for netCDF)
            include '_FillValue', 'scale_factor', 'add_offset', 'dtype',
            'units' and 'calendar' (the later two only for datetime arrays).
            Unrecognized keys are ignored.
        Nr2r"r,�attrs�encodingT)�fastpath)�AssertionError�getattrr'�pd�Seriesr@�	DataFrame�columns�Indexr�Panelr/Z
major_axisZ
minor_axisrr9r1r�	_variable�_coords�_name�_initialized)	r<�datar2r"r,rPrQrR�variablerrrr=�s<!
zDataArray.__init__cCs@|dkr|j}|dkr|j}||jkr,|j}t|�|||dd�S)NT)r,rR)r`r\�_DataArray__defaultr,�type)r<r`r2r,rrr�_replace�s
zDataArray._replacecsF|j|jkrd}n&t|j��t�fdd�|jj�D��}|j|||�S)Nc3s(|] \}}t|j��kr||fVqdS)N)�setr")rr5r6)�allowed_dimsrrr#�sz5DataArray._replace_maybe_drop_dims.<locals>.<genexpr>)r"rdrr\r/rc)r<r`r,r2r)rer�_replace_maybe_drop_dims�s

z"DataArray._replace_maybe_drop_dimscCs|j|jdd�S)NF)r,�shallow_copy)�_to_dataset_whole�_DataArray__this_array)r<rrr�_to_temp_dataset�szDataArray._to_temp_datasetcCs"|jj|j�}|j}|j|||�S)N)�
_variables�poprirc)r<�datasetr,r`r2rrr�_from_temp_dataset�szDataArray._from_temp_datasetcsH�fdd��t��fdd��j�D��}�jj�}|�=t||�j�S)Ncs�j||ij|�}i|_|S)N)�loc�droprP)r3�label�array)r<rr�subset�sz+DataArray._to_dataset_split.<locals>.subsetcsg|]}t|���|�f�qSr)�str)rrq)r3rsrrr�sz/DataArray._to_dataset_split.<locals>.<listcomp>)rr>r2�
to_datasetrrP)r<r3�	variablesr2r)r3r<rsr�_to_dataset_split�s
zDataArray._to_dataset_splitTcCsL|dkr|j}|dkrtd��||jkr0td��|jj|d�}|j||<|S)NzSunable to convert unnamed DataArray to a Dataset without providing an explicit namezUcannot create a Dataset from a DataArray with the same name as one of its coordinates)rg)r,r&r2Z_to_datasetr`)r<r,rgrmrrrrhs

zDataArray._to_dataset_wholecCsZ|dk	r*||jkr*tjdtdd�|}d}|dk	rL|dk	rBtd��|j|�S|j|�SdS)a�Convert a DataArray to a Dataset.

        Parameters
        ----------
        dim : str, optional
            Name of the dimension on this array along which to split this array
            into separate variables. If not provided, this array is converted
            into a Dataset of one variable.
        name : str, optional
            Name to substitute for this array's name. Only valid is ``dim`` is
            not provided.

        Returns
        -------
        dataset : Dataset
        Nzuthe order of the arguments on DataArray.to_dataset has changed; you now need to supply ``name`` as a keyword argumentr)�
stacklevelz)cannot supply both dim and name arguments)r"�warnings�warn�
FutureWarningr.rwrh)r<r3r,rrrrus

zDataArray.to_datasetcCs|jS)z The name of this array.
        )r])r<rrrr,2szDataArray.namecCs
||_dS)N)r])r<rGrrrr,8scCs|jS)N)r[)r<rrrr`<szDataArray.variablecCs|jjS)N)r`�dtype)r<rrrr|@szDataArray.dtypecCs|jjS)N)r`r1)r<rrrr1DszDataArray.shapecCs|jjS)N)r`r8)r<rrrr8HszDataArray.sizecCs|jjS)N)r`�nbytes)r<rrrr}LszDataArray.nbytescCs|jjS)N)r`rD)r<rrrrDPszDataArray.ndimcCs
t|j�S)N)r%r`)r<rrr�__len__TszDataArray.__len__cCs|jjS)z)The array's data as a dask or numpy array)r`r_)r<rrrr_WszDataArray.datacCs||j_dS)N)r`r_)r<rGrrrr_\scCs|jjS)z#The array's data as a numpy.ndarray)r`�values)r<rrrr`szDataArray.valuescCs||j_dS)N)r`r)r<rGrrrrescCs|jjS)N)r`�
_in_memory)r<rrrr�iszDataArray._in_memorycCs
|jj�S)zVConvert this variable to a pandas.Index. Only possible for 1D
        arrays.
        )r`�to_index)r<rrrr�mszDataArray.to_indexcCs|jjS)z+Dimension names associated with this array.)r`r")r<rrrr"sszDataArray.dimscCstd��dS)NzMyou cannot assign dims on a DataArray. Use .rename() or .swap_dims() instead.)�AttributeError)r<rGrrrr"xscCs0tj|�r|Stj||j�}tt|j|��SdS)N)rr$rrCrDrBrr")r<rrrr�_item_key_to_dict}s
zDataArray._item_key_to_dictcCspt|t�rZddlm}y|j|}Wn&tk
rJ||j|�\}}}YnX|j||d�S|jf|j|��SdS)Nr)�_get_virtual_variable)r,)	r'rrmr�r\�KeyErrorrf�iselr�)r<rr�r7�_rrrrF�s
zDataArray.__getitem__cCs$t|t�r||j|<n
||j|<dS)N)r'rr2r`)r<rrGrrrrH�s
zDataArray.__setitem__cCs|j|=dS)N)r2)r<rrrr�__delitem__�szDataArray.__delitem__cCs|j|jgS)z:List of places to look-up items for attribute-style access)r2rP)r<rrr�
_attr_sources�szDataArray._attr_sourcescCs
||jkS)N)r\)r<rrrr�__contains__�szDataArray.__contains__cCst|�S)z;Attribute for location based indexing like pandas.
        )r:)r<rrrro�sz
DataArray.loccCs|jjS)z6Dictionary storing arbitrary metadata with this array.)r`rP)r<rrrrP�szDataArray.attrscCs||j_dS)N)r`rP)r<rGrrrrP�scCs|jjS)zWDictionary of format-specific settings for how this array should be
        serialized.)r`rQ)r<rrrrQ�szDataArray.encodingcCs||j_dS)N)r`rQ)r<rGrrrrQ�scCst|�S)zJOrderedDict of pandas.Index objects used for label based indexing
        )r)r<rrrr>�szDataArray.indexescCst|�S)z8Dictionary-like container of coordinate arrays.
        )r
)r<rrrr2�szDataArray.coordscCs�|r|rtd��|dkr.t|j�t|j�}|jj�j||�}|rb|rR|j|_q�|j|jd�Sn"|j	dkrttd��|j
||j	<|SdS)azGiven 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, or DataArray if ``drop == True``
        zIcannot reset coordinates in-place on a DataArray without ``drop == True``N)r2z<cannot reset_coords with drop=False on an unnamed DataArrray)r&rdr2r"ru�reset_coordsrkr\rcr,r`)r<�namesrpZinplacermrrrr��s


zDataArray.reset_coordscCs*|j�j�}|j|�}|j|_|j|_|S)a�Manually trigger loading of this array's data from disk or a
        remote source into memory and return this array.

        Normally, it should not be necessary to call this method in user code,
        because all xarray functions should either work on deferred data or
        load data automatically. However, this method can be necessary when
        working with many file objects on disk.
        )rj�loadrnr[r\)r<�ds�newrrrr��s
	
zDataArray.loadcCstjdtdd�|j�S)NzHthe DataArray method `load_data` has been deprecated; use `load` insteadr)rx)ryrzr{r�)r<rrr�	load_data�s
zDataArray.load_datacs6|jj�d�}t�fdd�|jj�D��}|j||�S)a
Returns a copy of this array.

        If `deep=True`, a deep copy is made of all variables in the underlying
        dataset. Otherwise, a shallow copy is made, so each variable in the new
        array's dataset is also a variable in this array's dataset.
        )�deepc3s"|]\}}||j�d�fVqdS))r�N)r )rr5r6)r�rrr#sz!DataArray.copy.<locals>.<genexpr>)r`r rr\r/rc)r<r�r`r2r)r�rr szDataArray.copycCs|jdd�S)NF)r�)r )r<rrr�__copy__szDataArray.__copy__cCs|jdd�S)NT)r�)r )r<�memorrr�__deepcopy__szDataArray.__deepcopy__cCs|jjS)zYBlock dimensions for this array's data or None if it's not a dask
        array.
        )r`�chunks)r<rrrr�szDataArray.chunkscCs6t|ttf�rtt|j|��}|j�j|�}|j|�S)a�Coerce this array's data into a dask arrays with the given chunks.

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

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

        Parameters
        ----------
        chunks : int, tuple or dict, optional
            Chunk sizes along each dimension, e.g., ``5``, ``(5, 5)`` or
            ``{'x': 5, 'y': 5}``.

        Returns
        -------
        chunked : xarray.DataArray
        )	r'r)r-rBrr"rj�chunkrn)r<r�r�rrrr�!szDataArray.chunkcKs|j�jf|�}|j|�S)z�Return a new DataArray whose dataset is given by integer indexing
        along the specified dimension(s).

        See Also
        --------
        Dataset.isel
        DataArray.sel
        )rjr�rn)r<�indexersr�rrrr�<s	zDataArray.iselcKs|jftj||||d��S)z�Return a new DataArray whose dataset is given by selecting
        index labels along the specified dimension(s).

        See Also
        --------
        Dataset.sel
        DataArray.isel
        )�method�	tolerance)r�rZremap_label_indexers)r<r�r�r�rrr�selHs	
z
DataArray.sel�pointscKs"|j�jfd|i|��}|j|�S)z�Return a new DataArray whose dataset is given by pointwise integer
        indexing along the specified dimension(s).

        See Also
        --------
        Dataset.isel_points
        r3)rj�isel_pointsrn)r<r3r�r�rrrr�TszDataArray.isel_pointscKs&|j�jf|||d�|��}|j|�S)z�Return a new DataArray whose dataset is given by pointwise selection
        of index labels along the specified dimension(s).

        See Also
        --------
        Dataset.sel_points
        )r3r�r�)rj�
sel_pointsrn)r<r3r�r�r�r�rrrr�_s	
zDataArray.sel_pointscs4t�fdd�|jj�D��}�jf|||d�|��S)aUConform 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 on this
            data array:

            * None (default): don't fill gaps
            * pad / ffill: propgate 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 array's dataset contains only copied
            variables. If `copy=False` and no reindexing is required then
            original variables from this array's dataset are returned.

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

        See Also
        --------
        DataArray.reindex
        align
        c3s$|]\}}|�jkr||fVqdS)N)r")rr5r6)r<rrr#�sz)DataArray.reindex_like.<locals>.<genexpr>)r�r�r )rBr>r/�reindex)r<�otherr�r�r r�r)r<r�reindex_likels*zDataArray.reindex_likecKs&|j�jf|||d�|��}|j|�S)a�Conform this object onto a new set of indexes, filling in
        missing values with NaN.

        Parameters
        ----------
        copy : bool, optional
            If `copy=True`, the returned array's dataset contains only copied
            variables. If `copy=False` and no reindexing is required then
            original variables from this array's dataset are returned.
        method : {None, 'nearest', 'pad'/'ffill', 'backfill'/'bfill'}, optional
            Method to use for filling index values in ``indexers`` not found on
            this data array:

            * None (default): don't fill gaps
            * pad / ffill: propgate 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.
        **indexers : dict
            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.

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

        See Also
        --------
        DataArray.reindex_like
        align
        )r�r�r )rjr�rn)r<r�r�r r�r�rrrr��s(
zDataArray.reindexcCsLtj|�r<|j�}|j|j|j�}|j�j|�}|j||�S|j|d�SdS)aSReturns a new DataArray with renamed coordinates and/or a new name.


        Parameters
        ----------
        new_name_or_name_dict : str or dict-like
            If the argument is dict-like, it it used as a mapping from old
            names to new names for coordinates (and/or this array itself).
            Otherwise, use the argument as the new name for this array.

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

        See Also
        --------
        Dataset.rename
        DataArray.swap_dims
        )r,N)	rr$r rlr,rj�renamernrc)r<Znew_name_or_name_dictZ	name_dictr,rmrrrr��s
zDataArray.renamecCs|j�j|�}|j|�S)a\Returns a new DataArray with swapped dimensions.

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

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

        See Also
        --------

        DataArray.rename
        Dataset.swap_dims
        )rj�	swap_dimsrn)r<Z	dims_dictr�rrrr��szDataArray.swap_dimscKs|j�jf|�}|j|�S)a�
        Stack any number of existing dimensions into a single new dimension.

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

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

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

        Example
        -------

        >>> arr = DataArray(np.arange(6).reshape(2, 3),
        ...                 coords=[('x', ['a', 'b']), ('y', [0, 1, 2])])
        >>> arr
        <xray.DataArray (x: 2, y: 3)>
        array([[0, 1, 2],
               [3, 4, 5]])
        Coordinates:
          * x        (x) |S1 'a' 'b'
          * y        (y) int64 0 1 2
        >>> stacked = arr.stack(z=('x', 'y'))
        >>> stacked.indexes['z']
        MultiIndex(levels=[[u'a', u'b'], [0, 1, 2]],
                   labels=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]],
                   names=[u'x', u'y'])

        See also
        --------
        DataArray.unstack
        )rj�stackrn)r<Z
dimensionsr�rrrr��s(zDataArray.stackcCs|j�j|�}|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 : DataArray
            Array with unstacked data.

        See also
        --------
        DataArray.stack
        )rj�unstackrn)r<r3r�rrrr�)szDataArray.unstackcGs|jj|�}|j|�S)a^Return a new DataArray object with transposed dimensions.

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

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

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

        See Also
        --------
        numpy.transpose
        Dataset.transpose
        )r`�	transposerc)r<r"r`rrrr�AszDataArray.transposecCst|tt|j|j��|�S)a�Return a new DataArray object with squeezed data.

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

        Returns
        -------
        squeezed : DataArray
            This array, but with with all or a subset of the dimensions of
            length 1 removed.

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

        See Also
        --------
        numpy.squeeze
        )rrBrr"r1)r<r3rrrr\szDataArray.squeezecCs*tj|�r|g}|j�j||�}|j|�S)a�Drop coordinates or index labels from this DataArray.

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

        Returns
        -------
        dropped : DataArray
        )rZ	is_scalarrjrprn)r<r?r3r�rrrrpws
zDataArray.dropr0cCs|j�j|||d�}|j|�S)acReturns a new array 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.

        Returns
        -------
        DataArray
        )�how�thresh)rj�dropnarn)r<r3r�r�r�rrrr��szDataArray.dropnacCstj|�rtd��|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 or DataArray
            Used to fill all matching missing values in this array. If the
            argument is a DataArray, it is first aligned with (reindexed to)
            this array.

        Returns
        -------
        DataArray
        zDcannot provide fill value as a dictionary with fillna on a DataArray)rr$r.Z_fillna)r<rGrrr�fillna�s
zDataArray.fillnacKs |jj||||f|�}|j|�S)aReduce this array 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`.
        axis : int or sequence of int, optional
            Axis(es) over which to repeatedly apply `func`. Only one of the
            'dim' and 'axis' arguments can be supplied. If neither are
            supplied, then the reduction is calculated over the flattened array
            (by calling `f(x)` without an axis argument).
        keep_attrs : bool, optional
            If True, the variable's attributes (`attrs`) will be copied from
            the original object to the new one.  If False (default), the new
            object will be returned without attributes.
        **kwargs : dict
            Additional keyword arguments passed on to `func`.

        Returns
        -------
        reduced : DataArray
            DataArray with this object's array replaced with an array with
            summarized data and the indicated dimension(s) removed.
        )r`�reducerf)r<�funcr3ZaxisZ
keep_attrs�kwargsr7rrrr��szDataArray.reducecCs`dd�tjtjtjd�}y||j}Wn"tk
rHtd|j��YnX||jf|jj���S)a�Convert this array into a pandas object with the same shape.

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

        * 1D -> `pandas.Series`
        * 2D -> `pandas.DataFrame`
        * 3D -> `pandas.Panel`

        Only works for arrays with 3 or fewer dimensions.

        The DataArray constructor performs the inverse transformation.
        cSs|S)Nr)�xrrr�<lambda>�sz%DataArray.to_pandas.<locals>.<lambda>)rrr�z<cannot convert arrays with %s dimensions into pandas objects)	rUrVrWrZrDr�r&rr>)r<Zconstructors�constructorrrr�	to_pandas�s
zDataArray.to_pandascsf�dkr|j��dkrtd��tt|j|j��}d�|j�d�}|j|�}��fdd�|jD�|_|S)aConvert this array and its coordinates into a tidy pandas.DataFrame.

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

        Other coordinates are included as columns in the DataFrame.
        NzNcannot convert an unnamed DataArray to a DataFrame: use the ``name`` parameterZ,__unique_name_identifier_z98xfz98xugfg73ho__)r,csg|]}|�kr�n|�qSrr)r�c)r,�unique_namerrrsz*DataArray.to_dataframe.<locals>.<listcomp>)	r,r&rrr"r1rhZ
_to_dataframerX)r<r,r"r��dfr)r,r�r�to_dataframe�s
zDataArray.to_dataframecCs$|jj�}tj|jjd�||jd�S)z�Convert this array into a pandas.Series.

        The Series is indexed by the Cartesian product of index coordinates
        (in the form of a :py:class:`pandas.MultiIndex`).
        r)r@r,���)r2r�rUrVrZreshaper,)r<r@rrr�	to_seriess
zDataArray.to_seriescCs tj|j�}tjj|j||d�S)a|Convert this array into a numpy.ma.MaskedArray

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

        Returns
        -------
        result : MaskedArray
            Masked where invalid values (nan or inf) occur.
        )r_�maskr )rU�isnullr�np�maZMaskedArray)r<r r�rrr�to_masked_arrayszDataArray.to_masked_arraycCs&|j}tj||i�}tj|�}||S)a6Convert a pandas.Series into an xarray.DataArray.

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

zDataArray.from_seriescCsddlm}||�S)z1Convert this array into a cdms2.Variable
        r)�to_cdms2)�convertr�)r<r�rrrr�8szDataArray.to_cdms2cCsddlm}||�S)z:Convert a cdms2.Variable into an xarray.DataArray
        r)�
from_cdms2)r�r�)r�r`r�rrrr�>szDataArray.from_cdms2cs*�fdd�}tj|j|j|d�o(|||�S)z(Helper function for equals and identicalcst|j��|j�S)N)rTr`)r��y)�
compat_strrr�compatGsz%DataArray._all_compat.<locals>.compat)r�)rZ
dict_equivr2)r<r�r�r�r)r�r�_all_compatEszDataArray._all_compatcCs*y|j|d�Sttfk
r$dSXdS)z�Two DataArrays are broadcast equal if they are equal after
        broadcasting them against each other such that they have the same
        dimensions.

        See Also
        --------
        DataArray.equals
        DataArray.identical
        �broadcast_equalsFN)r�r.r�)r<r�rrrr�Ls
zDataArray.broadcast_equalscCs*y|j|d�Sttfk
r$dSXdS)a�True if two DataArrays have the same dimensions, coordinates and
        values; otherwise False.

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

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

        See Also
        --------
        DataArray.broadcast_equals
        DataArray.identical
        �equalsFN)r�r.r�)r<r�rrrr�[szDataArray.equalscCs6y|j|jko|j|d�Sttfk
r0dSXdS)z�Like equals, but also checks the array name and attributes, and
        attributes on all coordinates.

        See Also
        --------
        DataArray.broadcast_equals
        DataArray.equal
        �	identicalFN)r,r�r.r�)r<r�rrrr�os
	zDataArray.identicalcCs0t|d|j�}||jks"||jkr(|jSdSdS)Nr,)rT�_DataArray__default_namer,)r<r�Z
other_namerrr�_result_name�szDataArray._result_namecCs|jj||�}|j|�S)N)r`�__array_wrap__rc)r<�obj�contextZnew_varrrrr��szDataArray.__array_wrap__cstj���fdd��}|S)Ncs|j�|jjf|�|��S)N)r�r`r_)r<�argsr�)�frrr��sz!DataArray._unary_op.<locals>.func)�	functools�wraps)r�r�r)r�r�	_unary_op�szDataArray._unary_op�innercstj�����fdd��}|S)Ncs�t|ttjf�rtSt|d�rZt||�dd�\}}dd�t|j|j	�D�}|rZt
d|��t|d|�}t|dd�}�s��|j|�n
�||j�}|j
j|�j}|j|�}|j|||�S)	Nr>F)�joinr cSsg|]\}}|dkr|�qS)rr)rr!�srrrr�sz6DataArray._binary_op.<locals>.func.<locals>.<listcomp>z-no overlapping labels for some dimensions: %sr`r2)r'rr�GroupBy�NotImplemented�hasattrr	rr"r1r&rTr`r2�mergerkr�rc)r<r�Z
empty_indexes�other_variable�other_coordsr`r2r,)r�r��	reflexiverrr��s

z"DataArray._binary_op.<locals>.func)r�r�)r�r�r�Zignored_kwargsr�r)r�r�r�r�
_binary_op�szDataArray._binary_opcstj���fdd��}|S)Nc
sTt|tj�rtd��t|dd�}t|d|�}|jj|���|j|�WdQRX|S)NzNin-place operations between a DataArray and a grouped object are not permittedr2r`)r'rr�r.rTr2Z_merge_inplacer`)r<r�r�r�)r�rrr��sz*DataArray._inplace_binary_op.<locals>.func)r�r�)r�r�r)r�r�_inplace_binary_op�s
zDataArray._inplace_binary_opcCst|�S)a>
        Access plotting functions

        >>> d = DataArray([[1, 2], [3, 4]])

        For convenience just call this directly
        >>> d.plot()

        Or use it as a namespace to use xarray.plot functions as
        DataArray methods
        >>> d.plot.imshow()  # equivalent to xarray.plot.imshow(d)

        )r)r<rrr�plot�szDataArray.plot�2cCsng}x:t|j�D],\}}|jdkr|jdj|t|j�d��qWdj|�}t|�|krj|d|d�d}|S)aW
        If the dataarray has 1 dimensional coordinates or comes from a slice
        we can show that info in the title

        Parameters
        ----------
        truncate : integer
            maximum number of characters for title

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

        rz{dim} = {v})r3r6z, Nr�z...)	rr2r8�append�formatrrr�r%)r<�truncateZone_dimsr3r4�titlerrr�_title_for_slice�s

zDataArray._title_for_slicer�uppercCs|j�j|||d�}|j|�S)a6Calculate 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 differnce of this object.

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

        )rr3rq)rj�diffrn)r<r3rrqr�rrrr��s#zDataArray.diffcKs|jjf|�}|j|�S)a�Shift this array by an offset along one or more dimensions.

        Only the data is moved; coordinates stay in place. Values shifted from
        beyond array bounds are replaced by NaN. 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 : DataArray
            DataArray with the same coordinates and attributes but shifted
            data.

        See also
        --------
        roll

        Examples
        --------

        >>> arr = xr.DataArray([5, 6, 7], dims='x')
        >>> arr.shift(x=1)
        <xarray.DataArray (x: 3)>
        array([ nan,   5.,   6.])
        Coordinates:
          * x        (x) int64 0 1 2
        )r`�shiftrc)r<�shiftsr`rrrr�s"zDataArray.shiftcKs|j�jf|�}|j|�S)ayRoll this array 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 : DataArray
            DataArray with the same attributes but rolled data and coordinates.

        See also
        --------
        shift

        Examples
        --------

        >>> arr = xr.DataArray([5, 6, 7], dims='x')
        >>> arr.roll(x=1)
        <xarray.DataArray (x: 3)>
        array([7, 5, 6])
        Coordinates:
          * x        (x) int64 2 0 1
        )rj�rollrn)r<r�r�rrrr�3szDataArray.rollcCs|j|jj�S)N)rcr`�real)r<rrrr�UszDataArray.realcCs|j|jj�S)N)rcr`�imag)r<rrrr�YszDataArray.imag)NNNNNF)NT)NN)NFF)T)N)N)NN)r�)r�NN)NNT)NNT)N)N)r0N)NNF)N)T)N)N)Fr�)r�)rr�)`rIrJrKrNrZDataArrayGroupByZgroupby_clsr=�objectrarcrfrLrirjrnrwrhru�propertyr,�setterr`r|r1r8r}rDr~r_rr�r�r"r�rFrHr�r�r�rorPrQr>r2r�r�r�r r�r��__hash__r�r�r�r�r�r�r�r�r�r�r�r�r�rrpr�r�r�r�r�r�r��classmethodr�r�r�r�r�r�r�r�r�r��staticmethodr�r�r�r�r�r�r�r�r�r�rrrrrOms�%
D		

 
%






/
,+



 
	

	


&%"rO�<)�priority),�
contextlibr�ryZnumpyr�ZpandasrUZ	plot.plotr�rrrr�	alignmentr	�commonr
rrZcoordinatesr
rrmrZpycompatrrrrr`rrrrrZ
formattingrr9r�r:rLrOZ!inject_all_ops_and_reduce_methodsrrrr�<module>s<4z