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

���hq=�@s�ddlZddlZddlmZmZmZddlm	Z	ddl
mZGdd�de�Z
Gdd	�d	e�ZGd
d�de
�ZGdd
�d
e�ZGdd�de�Zddd�Zdd�Zdd�ZdS)�N�)�
basestring�	iteritems�suppress)�
formatting)�SortedKeysDictc@seZdZedd��ZdZdS)�ImplementsArrayReducecs&|rd�fdd�	}nd�fdd�	}|S)NFcs|j�||f||dd�|��S)NT)�
keep_attrs�skipna�
allow_lazy)�reduce)�self�dim�axisr
r	�kwargs)�func��2/tmp/pip-build-5_djhm0z/xray/xarray/core/common.py�wrapped_func
sz:ImplementsArrayReduce._reduce_method.<locals>.wrapped_funccs|j�||f|dd�|��S)NT)r	r)r)r
rrr	r)rrrrs)NNNF)NNFr)�clsr�include_skipna�numeric_onlyrr)rr�_reduce_method
s
z$ImplementsArrayReduce._reduce_methodaTdim : str or sequence of str, optional
            Dimension(s) over which to apply `{name}`.
        axis : int or sequence of int, optional
            Axis(es) over which to apply `{name}`. Only one of the 'dim'
            and 'axis' arguments can be supplied. If neither are supplied, then
            `{name}` is calculated over axes.N)�__name__�
__module__�__qualname__�classmethodr�_reduce_extra_args_docstringrrrrr	src@seZdZedd��ZdZdS)�ImplementsDatasetReducecs*|rd��fdd�	}nd��fdd�	}|S)NFcs|j�||f|�dd�|��S)NT)r
rr)r)r
rr	r
r)rrrrr%sz<ImplementsDatasetReduce._reduce_method.<locals>.wrapped_funccs|j�||f�dd�|��S)NT)rr)r)r
rr	r)rrrrr+s)NFN)NFr)rrrrrr)rrrr"sz&ImplementsDatasetReduce._reduce_methodz�dim : str or sequence of str, optional
            Dimension(s) over which to apply `func`.  By default `func` is
            applied over all dimensions.N)rrrrrrrrrrr!src@sveZdZdd�ZeZdd�Zdd�Zdd�Zd	d
�Zddd
�Z	dd�Z
dd�Zdd�Ze
dd��Zdd�Zdd�ZdS)�
AbstractArraycCs
t|j�S)N)�bool�values)r
rrr�__bool__8szAbstractArray.__bool__cCs
t|j�S)N)�floatr!)r
rrr�	__float__>szAbstractArray.__float__cCs
t|j�S)N)�intr!)r
rrr�__int__AszAbstractArray.__int__cCs
t|j�S)N)�complexr!)r
rrr�__complex__DszAbstractArray.__complex__cCs
t|j�S)N)�longr!)r
rrr�__long__GszAbstractArray.__long__NcCstj|j|d�S)N)�dtype)�np�asarrayr!)r
r+rrr�	__array__JszAbstractArray.__array__cCs
tj|�S)N)rZ
array_repr)r
rrr�__repr__MszAbstractArray.__repr__ccs$xtt|��D]}||VqWdS)N)�range�len)r
�nrrr�_iterPszAbstractArray._itercCs|jdkrtd��|j�S)Nrziteration over a 0-d array)�ndim�	TypeErrorr3)r
rrr�__iter__Ts
zAbstractArray.__iter__cCs|j�S)N)Z	transpose)r
rrr�TYszAbstractArray.Tcs.t|t�r�j|�St�fdd�|D��SdS)aVReturn axis number(s) corresponding to dimension(s) in this array.

        Parameters
        ----------
        dim : str or iterable of str
            Dimension name(s) for which to lookup axes.

        Returns
        -------
        int or tuple of int
            Axis number or numbers corresponding to the given dimensions.
        c3s|]}�j|�VqdS)N)�
_get_axis_num)�.0�d)r
rr�	<genexpr>msz-AbstractArray.get_axis_num.<locals>.<genexpr>N)�
isinstancerr8�tuple)r
rr)r
r�get_axis_num]s

zAbstractArray.get_axis_numcCs8y|jj|�Stk
r2td||jf��YnXdS)Nz#%r not found in array dimensions %r)�dims�index�
ValueError)r
rrrrr8os
zAbstractArray._get_axis_num)N)rrrr"�__nonzero__r$r&r(r*r.r/r3r6�propertyr7r>r8rrrrr7s
rc@s8eZdZdZdZedd��Zdd�Zdd�Zd	d
�Z	dS)�AttrAccessMixinz?Mixin class that allows getting keys with attribute access
    FcCs
||jgS)z:List of places to look-up items for attribute-style access)�attrs)r
rrr�
_attr_sources|szAttrAccessMixin._attr_sourcesc
CsJ|dkr0x&|jD]}tt��
||SQRXqWtdt|�j|f��dS)N�__setstate__z%r object has no attribute %r)rFr�KeyError�AttributeError�typer)r
�name�sourcerrr�__getattr__�s
zAttrAccessMixin.__getattr__cCsR|jr@y|j|�Wn*tk
r>td|t|�jf��YnXtj|||�dS)Nz�cannot set attribute %r on a %r object. Use __setitem__ style assignment (e.g., `ds['name'] = ...`) instead to assign variables.)�_initialized�__getattribute__rIrJr�object�__setattr__)r
rK�valuerrrrQ�szAttrAccessMixin.__setattr__cCs(dd�|jD�}tttt|��|��S)zZProvide method name lookup and completion. Only provide 'public'
        methods.
        cSsg|]}|D]}|�qqSrr)r9Zsublist�itemrrr�
<listcomp>�sz+AttrAccessMixin.__dir__.<locals>.<listcomp>)rF�sorted�set�dirrJ)r
Zextra_attrsrrr�__dir__�szAttrAccessMixin.__dir__N)
rrr�__doc__rNrCrFrMrQrXrrrrrDws
rDc@s@eZdZdd�Zdd�Zdd�Zddd	�Zdd
d�Zdd�ZdS)�BaseDataObjectcCs>t�}x2|j�D]&\}}t|�r.||�||<q|||<qW|S)N)r�items�callable)r
r�results�k�vrrr�_calc_assign_results�sz#BaseDataObject._calc_assign_resultscKs&|jdd�}|j|�}|jj|�|S)aNAssign new coordinates to this object, returning a new object
        with all the original data in addition to the new coordinates.

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

        Returns
        -------
        assigned : same type as caller
            A new object with the new coordinates in addition to the existing
            data.

        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_coords``
        is possible, but you cannot reference other variables created within
        the same ``assign_coords`` call.

        See also
        --------
        Dataset.assign
        F)�deep)�copyr`Zcoords�update)r
r�datar]rrr�
assign_coords�s
zBaseDataObject.assign_coordscOsPt|t�r<|\}}||kr*d|}t|��|||<|||�S||f|�|�SdS)a�
        Apply func(self, *args, **kwargs)

        This method replicates the pandas method of the same name.

        Parameters
        ----------
        func : function
            function to apply to this xarray object (Dataset/DataArray).
            ``args``, and ``kwargs`` are passed into ``func``.
            Alternatively a ``(callable, data_keyword)`` tuple where
            ``data_keyword`` is a string indicating the keyword of
            ``callable`` that expects the xarray object.
        args : positional arguments passed into ``func``.
        kwargs : a dictionary of keyword arguments passed into ``func``.

        Returns
        -------
        object : the return type of ``func``.

        Notes
        -----

        Use ``.pipe`` when chaining together functions that expect
        xarray or pandas objects, e.g., instead of writing

        >>> f(g(h(ds), arg1=a), arg2=b, arg3=c)

        You can write

        >>> (ds.pipe(h)
        ...    .pipe(g, arg1=a)
        ...    .pipe(f, arg2=b, arg3=c)
        ... )

        If you have a function that takes the data as (say) the second
        argument, pass a tuple indicating which keyword expects the
        data. For example, suppose ``f`` takes its data as ``arg2``:

        >>> (ds.pipe(h)
        ...    .pipe(g, arg1=a)
        ...    .pipe((f, 'arg2'), arg1=a, arg3=c)
        ...  )

        See Also
        --------
        pandas.DataFrame.pipe
        z1%s is both the pipe target and a keyword argumentN)r<r=rA)r
r�argsr�target�msgrrr�pipe�s1

zBaseDataObject.pipeTcCs"t|t�r||}|j|||d�S)a
Returns a GroupBy object for performing grouped operations.

        Parameters
        ----------
        group : str, DataArray or Coordinate
            Array whose unique values should be used to group this array. If a
            string, must be the name of a variable contained in this dataset.
        squeeze : boolean, optional
            If "group" is a dimension of any arrays in this dataset, `squeeze`
            controls whether the subarrays have a dimension of length 1 along
            that dimension or if the dimension is squeezed out.

        Returns
        -------
        grouped : GroupBy
            A `GroupBy` object patterned after `pandas.GroupBy` that can be
            iterated over in the form of `(unique_value, grouped_array)` pairs.
        )�squeeze)r<r�groupby_cls)r
�grouprjrrr�groupby
s
zBaseDataObject.groupby�meanNrcCs�ddlm}d}	t|t�r"||}|||	|fg|	d�}
tj|||||d�}|j||
|d�}t|t�r�t||�}
|dkr�|
|d	�}q�|
|j|d
�}n|j	||jd�}|j
|	|ji�}|S)
a-	Resample this object to a new temporal resolution.

        Handles both downsampling and upsampling. Upsampling with filling is
        not yet supported; if any intervals contain no values in the original
        object, they will be given the value ``NaN``.

        Parameters
        ----------
        freq : str
            String in the '#offset' to specify the step-size along the
            resampled dimension, where '#' is an (optional) integer multipler
            (default 1) and 'offset' is any pandas date offset alias. Examples
            of valid offsets include:

            * 'AS': year start
            * 'QS-DEC': quarterly, starting on December 1
            * 'MS': month start
            * 'D': day
            * 'H': hour
            * 'Min': minute

            The full list of these offset aliases is documented in pandas [1]_.
        dim : str
            Name of the dimension to resample along (e.g., 'time').
        how : str or func, optional
            Used for downsampling. If a string, ``how`` must be a valid
            aggregation operation supported by xarray. Otherwise, ``how`` must be
            a function that can be called like ``how(values, axis)`` to reduce
            ndarray values along the given axis. Valid choices that can be
            provided as a string include all the usual Dataset/DataArray
            aggregations (``all``, ``any``, ``argmax``, ``argmin``, ``max``,
            ``mean``, ``median``, ``min``, ``prod``, ``sum``, ``std`` and
            ``var``), as well as ``first`` and ``last``.
        skipna : bool, optional
            Whether to skip missing values when aggregating in downsampling.
        closed : 'left' or 'right', optional
            Side of each interval to treat as closed.
        label : 'left or 'right', optional
            Side of each interval to use for labeling.
        base : int, optionalt
            For frequencies that evenly subdivide 1 day, the "origin" of the
            aggregated intervals. For example, for '24H' frequency, base could
            range from 0 through 23.

        Returns
        -------
        resampled : same type as caller
            This object resampled.

        References
        ----------

        .. [1] http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases
        r)�	DataArrayZ__resample_dim__)rK)�freq�how�closed�label�base)Zgrouper�first�last)r
)rr
)r)rurv)Z	dataarrayror<r�pdZTimeGrouperrk�getattrrKr�rename)r
rprrqr
rrrsrtroZRESAMPLE_DIMrlZtime_grouper�gb�f�resultrrr�resample!s 8




zBaseDataObject.resamplecCs
|j|�S)a�Return an object of the same shape with all entries where cond is
        True and all other entries masked.

        This operation follows the normal broadcasting and alignment rules that
        xarray uses for binary arithmetic.

        Parameters
        ----------
        cond : boolean DataArray or Dataset

        Returns
        -------
        same type as caller

        Examples
        --------

        >>> import numpy as np
        >>> a = xr.DataArray(np.arange(25).reshape(5, 5), dims=('x', 'y'))
        >>> a.where((a > 6) & (a < 18))
        <xarray.DataArray (x: 5, y: 5)>
        array([[ nan,  nan,  nan,  nan,  nan],
               [ nan,  nan,   7.,   8.,   9.],
               [ 10.,  11.,  12.,  13.,  14.],
               [ 15.,  16.,  17.,  nan,  nan],
               [ nan,  nan,  nan,  nan,  nan]])
        Coordinates:
          * y        (y) int64 0 1 2 3 4
          * x        (x) int64 0 1 2 3 4
        )Z_where)r
Zcondrrr�wheremszBaseDataObject.where)T)rnNNNr)	rrrr`rerirmr}r~rrrrrZ�s	#;

KrZcsd|dkrdd�t��D�}n.t|t�r,|g}t�fdd�|D��rJtd��|jftdd�|D���S)z%Squeeze the dims of an xarray object.NcSsg|]\}}|dkr|�qS)rr)r9r:�srrrrT�szsqueeze.<locals>.<listcomp>c3s|]}�|dkVqdS)rNr)r9r^)r?rrr;�szsqueeze.<locals>.<genexpr>zJcannot select a dimension to squeeze out which has length greater than onecss|]}|dfVqdS)rNr)r9r:rrrr;�s)rr<r�anyrAZisel�dict)Z
xarray_objr?rr)r?rrj�s
rjcCsxtj|t�rtj}nVtj|t�r,t}tj}n>tj|tj�rFtjd�}n$tj|tj�r`tjd�}n
t}tj}tj|�|fS)z7Simpler equivalent of pandas.core.common._maybe_promoteZNaT)	r,Z
issubdtyper#�nanr%Z
datetime64Ztimedelta64rPr+)r+Z
fill_valuerrr�_maybe_promote�sr�cCstjtj|j���j|j�S)z�Convert arrays of datetime.datetime and datetime.timedelta objects into
    datetime64 and timedelta64, according to the pandas convention.
    )r,r-rwZSeriesZravelZreshape�shape)r!rrr�_possibly_convert_objects�sr�)N)Znumpyr,ZpandasrwZpycompatrrr�r�utilsrrPrrrrDrZrjr�r�rrrr�<module>s@+n