INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Adds time attributes to time bounds variables. Variables handling time bounds ("Cell boundaries" in the CF conventions) do not necessarily carry the necessary attributes to be decoded. This copies the attributes from the time variable to the associated boundaries. See Also: http://cfconventio...
def _update_bounds_attributes(variables): """Adds time attributes to time bounds variables. Variables handling time bounds ("Cell boundaries" in the CF conventions) do not necessarily carry the necessary attributes to be decoded. This copies the attributes from the time variable to the associated b...
Decode the given Dataset or Datastore according to CF conventions into a new Dataset. Parameters ---------- obj : Dataset or DataStore Object to decode. concat_characters : bool, optional Should character arrays be concatenated to strings, for example: ['h', 'e', 'l', 'l', '...
def decode_cf(obj, concat_characters=True, mask_and_scale=True, decode_times=True, decode_coords=True, drop_variables=None, use_cftime=None): """Decode the given Dataset or Datastore according to CF conventions into a new Dataset. Parameters ---------- obj : Dataset or D...
Decode several CF encoded variables. See: decode_cf_variable
def decode_cf_variables(variables, attributes, concat_characters=True, mask_and_scale=True, decode_times=True, decode_coords=True, drop_variables=None, use_cftime=None): """ Decode several CF encoded variables. See: decode_cf_variable ...
Decode a set of CF encoded variables and attributes. See Also, decode_cf_variable Parameters ---------- variables : dict A dictionary mapping from variable name to xarray.Variable attributes : dict A dictionary mapping from attribute name to value concat_characters : bool ...
def cf_decoder(variables, attributes, concat_characters=True, mask_and_scale=True, decode_times=True): """ Decode a set of CF encoded variables and attributes. See Also, decode_cf_variable Parameters ---------- variables : dict A dictionary mapping from va...
Encode coordinates on the given dataset object into variable specific and global attributes. When possible, this is done according to CF conventions. Parameters ---------- dataset : Dataset Object to encode. Returns ------- variables : dict attrs : dict
def encode_dataset_coordinates(dataset): """Encode coordinates on the given dataset object into variable specific and global attributes. When possible, this is done according to CF conventions. Parameters ---------- dataset : Dataset Object to encode. Returns ------- varia...
A function which takes a dicts of variables and attributes and encodes them to conform to CF conventions as much as possible. This includes masking, scaling, character array handling, and CF-time encoding. Decode a set of CF encoded variables and attributes. See Also, decode_cf_variable Para...
def cf_encoder(variables, attributes): """ A function which takes a dicts of variables and attributes and encodes them to conform to CF conventions as much as possible. This includes masking, scaling, character array handling, and CF-time encoding. Decode a set of CF encoded variables and attr...
Coerce an array to a data type that can be stored in a netCDF-3 file This function performs the following dtype conversions: int64 -> int32 bool -> int8 Data is checked for equality, or equivalence (non-NaN values) with `np.allclose` with the default keyword arguments.
def coerce_nc3_dtype(arr): """Coerce an array to a data type that can be stored in a netCDF-3 file This function performs the following dtype conversions: int64 -> int32 bool -> int8 Data is checked for equality, or equivalence (non-NaN values) with `np.allclose` with the default keywo...
Test whether an object can be validly converted to a netCDF-3 dimension, variable or attribute name Earlier versions of the netCDF C-library reference implementation enforced a more restricted set of characters in creating new names, but permitted reading names containing arbitrary bytes. This spec...
def is_valid_nc3_name(s): """Test whether an object can be validly converted to a netCDF-3 dimension, variable or attribute name Earlier versions of the netCDF C-library reference implementation enforced a more restricted set of characters in creating new names, but permitted reading names containi...
Convert an object into a Variable. Parameters ---------- obj : object Object to convert into a Variable. - If the object is already a Variable, return a shallow copy. - Otherwise, if the object has 'dims' and 'data' attributes, convert it into a new Variable. - If...
def as_variable(obj, name=None) -> 'Union[Variable, IndexVariable]': """Convert an object into a Variable. Parameters ---------- obj : object Object to convert into a Variable. - If the object is already a Variable, return a shallow copy. - Otherwise, if the object has 'dims' a...
Convert arrays of datetime.datetime and datetime.timedelta objects into datetime64 and timedelta64, according to the pandas convention.
def _possibly_convert_objects(values): """Convert arrays of datetime.datetime and datetime.timedelta objects into datetime64 and timedelta64, according to the pandas convention. """ return np.asarray(pd.Series(values.ravel())).reshape(values.shape)
Prepare and wrap data to put in a Variable. - If data does not have the necessary attributes, convert it to ndarray. - If data has dtype=datetime64, ensure that it has ns precision. If it's a pandas.Timestamp, convert it to datetime64. - If data is already a pandas or xarray object (other than an Ind...
def as_compatible_data(data, fastpath=False): """Prepare and wrap data to put in a Variable. - If data does not have the necessary attributes, convert it to ndarray. - If data has dtype=datetime64, ensure that it has ns precision. If it's a pandas.Timestamp, convert it to datetime64. - If data is...
Return the given values as a numpy array, or as an individual item if it's a 0d datetime64 or timedelta64 array. Importantly, this function does not copy data if it is already an ndarray - otherwise, it will not be possible to update Variable values in place. This function mostly exists because 0-dime...
def _as_array_or_item(data): """Return the given values as a numpy array, or as an individual item if it's a 0d datetime64 or timedelta64 array. Importantly, this function does not copy data if it is already an ndarray - otherwise, it will not be possible to update Variable values in place. This f...
Create broadcast compatible variables, with the same dimensions. Unlike the result of broadcast_variables(), some variables may have dimensions of size 1 instead of the the size of the broadcast dimension.
def _broadcast_compat_variables(*variables): """Create broadcast compatible variables, with the same dimensions. Unlike the result of broadcast_variables(), some variables may have dimensions of size 1 instead of the the size of the broadcast dimension. """ dims = tuple(_unified_dims(variables)) ...
Given any number of variables, return variables with matching dimensions and broadcast data. The data on the returned variables will be a view of the data on the corresponding original arrays, but dimensions will be reordered and inserted so that both broadcast arrays have the same dimensions. The new ...
def broadcast_variables(*variables): """Given any number of variables, return variables with matching dimensions and broadcast data. The data on the returned variables will be a view of the data on the corresponding original arrays, but dimensions will be reordered and inserted so that both broadca...
Concatenate variables along a new or existing dimension. Parameters ---------- variables : iterable of Array Arrays to stack together. Each variable is expected to have matching dimensions and shape except for along the stacked dimension. dim : str or DataArray, optional ...
def concat(variables, dim='concat_dim', positions=None, shortcut=False): """Concatenate variables along a new or existing dimension. Parameters ---------- variables : iterable of Array Arrays to stack together. Each variable is expected to have matching dimensions and shape except for a...
Check for uniqueness of MultiIndex level names in all given variables. Not public API. Used for checking consistency of DataArray and Dataset objects.
def assert_unique_multiindex_level_names(variables): """Check for uniqueness of MultiIndex level names in all given variables. Not public API. Used for checking consistency of DataArray and Dataset objects. """ level_names = defaultdict(list) all_level_names = set() for var_name, var in...
Manually trigger loading of this variable's data from disk or a remote source into memory and return this variable. Normally, it should not be necessary to call this method in user code, because all xarray functions should either work on deferred data or load data automatically. ...
def load(self, **kwargs): """Manually trigger loading of this variable's data from disk or a remote source into memory and return this variable. Normally, it should not be necessary to call this method in user code, because all xarray functions should either work on deferred data or ...
Return this variable as a base xarray.Variable
def to_base_variable(self): """Return this variable as a base xarray.Variable""" return Variable(self.dims, self._data, self._attrs, encoding=self._encoding, fastpath=True)
Return this variable as an xarray.IndexVariable
def to_index_variable(self): """Return this variable as an xarray.IndexVariable""" return IndexVariable(self.dims, self._data, self._attrs, encoding=self._encoding, fastpath=True)
Dictionary representation of variable.
def to_dict(self, data=True): """Dictionary representation of variable.""" item = {'dims': self.dims, 'attrs': decode_numpy_dict_values(self.attrs)} if data: item['data'] = ensure_us_time_resolution(self.values).tolist() else: item.update({'dtype':...
Prepare an indexing key for an indexing operation. Parameters ----------- key: int, slice, array, dict or tuple of integer, slices and arrays Any valid input for indexing. Returns ------- dims: tuple Dimension of the resultant variable. i...
def _broadcast_indexes(self, key): """Prepare an indexing key for an indexing operation. Parameters ----------- key: int, slice, array, dict or tuple of integer, slices and arrays Any valid input for indexing. Returns ------- dims: tuple ...
Make sanity checks
def _validate_indexers(self, key): """ Make sanity checks """ for dim, k in zip(self.dims, key): if isinstance(k, BASIC_INDEXING_TYPES): pass else: if not isinstance(k, Variable): k = np.asarray(k) if k.ndim ...
Equivalent numpy's nonzero but returns a tuple of Varibles.
def _nonzero(self): """ Equivalent numpy's nonzero but returns a tuple of Varibles. """ # TODO we should replace dask's native nonzero # after https://github.com/dask/dask/issues/1076 is implemented. nonzeros = np.nonzero(self.data) return tuple(Variable((dim), nz) for nz, dim ...
Used by IndexVariable to return IndexVariable objects when possible.
def _finalize_indexing_result(self, dims, data): """Used by IndexVariable to return IndexVariable objects when possible. """ return type(self)(dims, data, self._attrs, self._encoding, fastpath=True)
Index this Variable with -1 remapped to fill_value.
def _getitem_with_mask(self, key, fill_value=dtypes.NA): """Index this Variable with -1 remapped to fill_value.""" # TODO(shoyer): expose this method in public API somewhere (isel?) and # use it for reindex. # TODO(shoyer): add a sanity check that all other integers are # non-neg...
Returns a copy of this object. If `deep=True`, the data array is loaded into memory and copied onto the new object. Dimensions, attributes and encodings are always copied. Use `data` to create a new object with the same structure as original but entirely new data. Parameters ...
def copy(self, deep=True, data=None): """Returns a copy of this object. If `deep=True`, the data array is loaded into memory and copied onto the new object. Dimensions, attributes and encodings are always copied. Use `data` to create a new object with the same structure as orig...
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 ...
def chunk(self, chunks=None, name=None, lock=False): """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 c...
Return a new array indexed along the specified dimension(s). Parameters ---------- **indexers : {dim: indexer, ...} Keyword arguments with names matching dimensions and values given by integers, slice objects or arrays. Returns ------- obj : Arra...
def isel(self, indexers=None, drop=False, **indexers_kwargs): """Return a new array indexed along the specified dimension(s). Parameters ---------- **indexers : {dim: indexer, ...} Keyword arguments with names matching dimensions and values given by integers, sli...
Return a new object with squeezed data. Parameters ---------- dim : None or str or tuple of str, optional Selects a subset of the length one dimensions. If a dimension is selected with length greater than one, an error is raised. If None, all length one dimen...
def squeeze(self, dim=None): """Return a new object with squeezed data. Parameters ---------- dim : None or str or tuple of str, optional Selects a subset of the length one dimensions. If a dimension is selected with length greater than one, an error is raised. I...
Return a new Variable with shifted data. Parameters ---------- shifts : mapping of the form {dim: offset} Integer offset to shift along each of the given dimensions. Positive offsets shift to the right; negative offsets shift to the left. fill_value: ...
def shift(self, shifts=None, fill_value=dtypes.NA, **shifts_kwargs): """ Return a new Variable with shifted data. Parameters ---------- shifts : mapping of the form {dim: offset} Integer offset to shift along each of the given dimensions. Positive offsets...
Return a new Variable with paddings. Parameters ---------- pad_width: Mapping of the form {dim: (before, after)} Number of values padded to the edges of each dimension. **pad_widths_kwargs: Keyword argument for pad_widths
def pad_with_fill_value(self, pad_widths=None, fill_value=dtypes.NA, **pad_widths_kwargs): """ Return a new Variable with paddings. Parameters ---------- pad_width: Mapping of the form {dim: (before, after)} Number of values padded to the ...
Return a new Variable with rolld data. Parameters ---------- shifts : mapping of the form {dim: offset} Integer offset to roll along each of the given dimensions. Positive offsets roll to the right; negative offsets roll to the left. **shifts_kwargs: ...
def roll(self, shifts=None, **shifts_kwargs): """ Return a new Variable with rolld data. Parameters ---------- shifts : mapping of the form {dim: offset} Integer offset to roll along each of the given dimensions. Positive offsets roll to the right; negati...
Return a new Variable object with transposed dimensions. Parameters ---------- *dims : str, optional By default, reverse the dimensions. Otherwise, reorder the dimensions to this order. Returns ------- transposed : Variable The return...
def transpose(self, *dims) -> 'Variable': """Return a new Variable object with transposed dimensions. Parameters ---------- *dims : str, optional By default, reverse the dimensions. Otherwise, reorder the dimensions to this order. Returns -------...
Return a new variable with given set of dimensions. This method might be used to attach new dimension(s) to variable. When possible, this operation does not copy this variable's data. Parameters ---------- dims : str or sequence of str or dict Dimensions to include ...
def set_dims(self, dims, shape=None): """Return a new variable with given set of dimensions. This method might be used to attach new dimension(s) to variable. When possible, this operation does not copy this variable's data. Parameters ---------- dims : str or sequence ...
Stack any number of existing dimensions into a single new dimension. New dimensions will be added at the end, and the order of the data along each new dimension will be in contiguous (C) order. Parameters ---------- dimensions : Mapping of form new_name=(dim1, dim2, ...) ...
def stack(self, dimensions=None, **dimensions_kwargs): """ Stack any number of existing dimensions into a single new dimension. New dimensions will be added at the end, and the order of the data along each new dimension will be in contiguous (C) order. Parameters ------...
Unstack an existing dimension into multiple new dimensions. New dimensions will be added at the end, and the order of the data along each new dimension will be in contiguous (C) order. Parameters ---------- dimensions : mapping of the form old_dim={dim1: size1, ...} ...
def unstack(self, dimensions=None, **dimensions_kwargs): """ Unstack an existing dimension into multiple new dimensions. New dimensions will be added at the end, and the order of the data along each new dimension will be in contiguous (C) order. Parameters ---------- ...
Reduce this array by applying `func` along some dimension(s). Parameters ---------- func : function Function which can be called in the form `func(x, axis=axis, **kwargs)` to return the result of reducing an np.ndarray over an integer valued axis. dim...
def reduce(self, func, dim=None, axis=None, keep_attrs=None, allow_lazy=False, **kwargs): """Reduce this array by applying `func` along some dimension(s). Parameters ---------- func : function Function which can be called in the form `func(x, axis=...
Concatenate variables along a new or existing dimension. Parameters ---------- variables : iterable of Array Arrays to stack together. Each variable is expected to have matching dimensions and shape except for along the stacked dimension. dim : str or...
def concat(cls, variables, dim='concat_dim', positions=None, shortcut=False): """Concatenate variables along a new or existing dimension. Parameters ---------- variables : iterable of Array Arrays to stack together. Each variable is expected to have ...
True if two Variables have the same dimensions and values; otherwise False. Variables can still be equal (like pandas objects) if they have NaN values in the same locations. This method is necessary because `v1 == v2` for Variables does element-wise comparisons (like numpy.ndar...
def equals(self, other, equiv=duck_array_ops.array_equiv): """True if two Variables have the same dimensions and values; otherwise False. Variables can still be equal (like pandas objects) if they have NaN values in the same locations. This method is necessary because `v1 == v2...
True if two Variables have the values after being broadcast against each other; otherwise False. Variables can still be equal (like pandas objects) if they have NaN values in the same locations.
def broadcast_equals(self, other, equiv=duck_array_ops.array_equiv): """True if two Variables have the values after being broadcast against each other; otherwise False. Variables can still be equal (like pandas objects) if they have NaN values in the same locations. """ ...
Like equals, but also checks attributes.
def identical(self, other): """Like equals, but also checks attributes. """ try: return (utils.dict_equiv(self.attrs, other.attrs) and self.equals(other)) except (TypeError, AttributeError): return False
Compute the qth quantile of the data along the specified dimension. Returns the qth quantiles(s) of the array elements. Parameters ---------- q : float in range of [0,1] (or sequence of floats) Quantile to compute, which must be between 0 and 1 inclusive. ...
def quantile(self, q, dim=None, interpolation='linear'): """Compute the qth quantile of the data along the specified dimension. Returns the qth quantiles(s) of the array elements. Parameters ---------- q : float in range of [0,1] (or sequence of floats) Quantile to ...
Ranks the data. Equal values are assigned a rank that is the average of the ranks that would have been otherwise assigned to all of the values within that set. Ranks begin at 1, not 0. If `pct`, computes percentage ranks. NaNs in the input array are returned as NaNs. The `bot...
def rank(self, dim, pct=False): """Ranks the data. Equal values are assigned a rank that is the average of the ranks that would have been otherwise assigned to all of the values within that set. Ranks begin at 1, not 0. If `pct`, computes percentage ranks. NaNs in the input ar...
Make a rolling_window along dim and add a new_dim to the last place. Parameters ---------- dim: str Dimension over which to compute rolling_window window: int Window size of the rolling window_dim: str New name of the window dimension. ...
def rolling_window(self, dim, window, window_dim, center=False, fill_value=dtypes.NA): """ Make a rolling_window along dim and add a new_dim to the last place. Parameters ---------- dim: str Dimension over which to compute rolling_window ...
Apply
def coarsen(self, windows, func, boundary='exact', side='left'): """ Apply """ windows = {k: v for k, v in windows.items() if k in self.dims} if not windows: return self.copy() reshaped, axes = self._coarsen_reshape(windows, boundary, side) if isinsta...
Construct a reshaped-array for corsen
def _coarsen_reshape(self, windows, boundary, side): """ Construct a reshaped-array for corsen """ if not utils.is_dict_like(boundary): boundary = {d: boundary for d in windows.keys()} if not utils.is_dict_like(side): side = {d: side for d in windows.keys...
A (private) method to convert datetime array to numeric dtype See duck_array_ops.datetime_to_numeric
def _to_numeric(self, offset=None, datetime_unit=None, dtype=float): """ A (private) method to convert datetime array to numeric dtype See duck_array_ops.datetime_to_numeric """ numeric_array = duck_array_ops.datetime_to_numeric( self.data, offset, datetime_unit, dtype) ...
Specialized version of Variable.concat for IndexVariable objects. This exists because we want to avoid converting Index objects to NumPy arrays, if possible.
def concat(cls, variables, dim='concat_dim', positions=None, shortcut=False): """Specialized version of Variable.concat for IndexVariable objects. This exists because we want to avoid converting Index objects to NumPy arrays, if possible. """ if not isinstance(dim...
Returns a copy of this object. `deep` is ignored since data is stored in the form of pandas.Index, which is already immutable. Dimensions, attributes and encodings are always copied. Use `data` to create a new object with the same structure as original but entirely new data. ...
def copy(self, deep=True, data=None): """Returns a copy of this object. `deep` is ignored since data is stored in the form of pandas.Index, which is already immutable. Dimensions, attributes and encodings are always copied. Use `data` to create a new object with the same struct...
Convert this variable to a pandas.Index
def to_index(self): """Convert this variable to a pandas.Index""" # n.b. creating a new pandas.Index from an old pandas.Index is # basically free as pandas.Index objects are immutable assert self.ndim == 1 index = self._data.array if isinstance(index, pd.MultiIndex): ...
Return MultiIndex level names or None if this IndexVariable has no MultiIndex.
def level_names(self): """Return MultiIndex level names or None if this IndexVariable has no MultiIndex. """ index = self.to_index() if isinstance(index, pd.MultiIndex): return index.names else: return None
Return a new IndexVariable from a given MultiIndex level.
def get_level_variable(self, level): """Return a new IndexVariable from a given MultiIndex level.""" if self.level_names is None: raise ValueError("IndexVariable %r has no MultiIndex" % self.name) index = self.to_index() return type(self)(self.dims, index.get_level_values(lev...
Generalization of pandas.tseries.index.DatetimeIndex._parsed_string_to_bounds for use with non-standard calendars and cftime.datetime objects.
def _parsed_string_to_bounds(date_type, resolution, parsed): """Generalization of pandas.tseries.index.DatetimeIndex._parsed_string_to_bounds for use with non-standard calendars and cftime.datetime objects. """ if resolution == 'year': return (date_type(parsed.year, 1, 1), ...
Adapted from pandas.tslib.get_date_field
def get_date_field(datetimes, field): """Adapted from pandas.tslib.get_date_field""" return np.array([getattr(date, field) for date in datetimes])
Adapted from pandas.tseries.index._field_accessor
def _field_accessor(name, docstring=None, min_cftime_version='0.0'): """Adapted from pandas.tseries.index._field_accessor""" def f(self, min_cftime_version=min_cftime_version): import cftime version = cftime.__version__ if LooseVersion(version) >= LooseVersion(min_cftime_version): ...
Create a numpy array from an array of strings. For use in generating dates from strings for use with interp. Assumes the array is either 0-dimensional or 1-dimensional. Parameters ---------- strings : array of strings Strings to convert to dates date_type : cftime.datetime type ...
def _parse_array_of_cftime_strings(strings, date_type): """Create a numpy array from an array of strings. For use in generating dates from strings for use with interp. Assumes the array is either 0-dimensional or 1-dimensional. Parameters ---------- strings : array of strings Strings ...
Adapted from pandas.tseries.index.DatetimeIndex._partial_date_slice Note that when using a CFTimeIndex, if a partial-date selection returns a single element, it will never be converted to a scalar coordinate; this is in slight contrast to the behavior when using a DatetimeIndex,...
def _partial_date_slice(self, resolution, parsed): """Adapted from pandas.tseries.index.DatetimeIndex._partial_date_slice Note that when using a CFTimeIndex, if a partial-date selection returns a single element, it will never be converted to a scalar coordinate; this is in sligh...
Adapted from pandas.tseries.index.DatetimeIndex._get_string_slice
def _get_string_slice(self, key): """Adapted from pandas.tseries.index.DatetimeIndex._get_string_slice""" parsed, resolution = _parse_iso8601_with_reso(self.date_type, key) try: loc = self._partial_date_slice(resolution, parsed) except KeyError: raise KeyError(key...
Adapted from pandas.tseries.index.DatetimeIndex.get_loc
def get_loc(self, key, method=None, tolerance=None): """Adapted from pandas.tseries.index.DatetimeIndex.get_loc""" if isinstance(key, str): return self._get_string_slice(key) else: return pd.Index.get_loc(self, key, method=method, toler...
Adapted from pandas.tseries.index.DatetimeIndex._maybe_cast_slice_bound
def _maybe_cast_slice_bound(self, label, side, kind): """Adapted from pandas.tseries.index.DatetimeIndex._maybe_cast_slice_bound""" if isinstance(label, str): parsed, resolution = _parse_iso8601_with_reso(self.date_type, label...
Adapted from pandas.tseries.index.DatetimeIndex.get_value
def get_value(self, series, key): """Adapted from pandas.tseries.index.DatetimeIndex.get_value""" if np.asarray(key).dtype == np.dtype(bool): return series.iloc[key] elif isinstance(key, slice): return series.iloc[self.slice_indexer( key.start, key.stop, k...
Shift the CFTimeIndex a multiple of the given frequency. See the documentation for :py:func:`~xarray.cftime_range` for a complete listing of valid frequency strings. Parameters ---------- n : int Periods to shift by freq : str or datetime.timedelta ...
def shift(self, n, freq): """Shift the CFTimeIndex a multiple of the given frequency. See the documentation for :py:func:`~xarray.cftime_range` for a complete listing of valid frequency strings. Parameters ---------- n : int Periods to shift by freq ...
If possible, convert this index to a pandas.DatetimeIndex. Parameters ---------- unsafe : bool Flag to turn off warning when converting from a CFTimeIndex with a non-standard calendar to a DatetimeIndex (default ``False``). Returns ------- pandas...
def to_datetimeindex(self, unsafe=False): """If possible, convert this index to a pandas.DatetimeIndex. Parameters ---------- unsafe : bool Flag to turn off warning when converting from a CFTimeIndex with a non-standard calendar to a DatetimeIndex (default ``Fals...
Create a function that dispatches to dask for dask array inputs.
def _dask_or_eager_func(name, eager_module=np, dask_module=dask_array, list_of_args=False, array_args=slice(1), requires_dask=None): """Create a function that dispatches to dask for dask array inputs.""" if dask_module is not None: def f(*args, **kwargs): ...
Cast a arrays to a shared dtype using xarray's type promotion rules.
def as_shared_dtype(scalars_or_arrays): """Cast a arrays to a shared dtype using xarray's type promotion rules.""" arrays = [asarray(x) for x in scalars_or_arrays] # Pass arrays directly instead of dtypes to result_type so scalars # get handled properly. # Note that result_type() safely gets the dty...
Like np.allclose, but also allows values to be NaN in both arrays
def allclose_or_equiv(arr1, arr2, rtol=1e-5, atol=1e-8): """Like np.allclose, but also allows values to be NaN in both arrays """ arr1, arr2 = as_like_arrays(arr1, arr2) if arr1.shape != arr2.shape: return False return bool( isclose(arr1, arr2, rtol=rtol, atol=atol, equal_nan=True).a...
Like np.array_equal, but also allows values to be NaN in both arrays
def array_equiv(arr1, arr2): """Like np.array_equal, but also allows values to be NaN in both arrays """ arr1, arr2 = as_like_arrays(arr1, arr2) if arr1.shape != arr2.shape: return False with warnings.catch_warnings(): warnings.filterwarnings('ignore', "In the future, 'NAT == x'") ...
Count the number of non-NA in this array along the given axis or axes
def count(data, axis=None): """Count the number of non-NA in this array along the given axis or axes """ return np.sum(np.logical_not(isnull(data)), axis=axis)
Convert an array containing datetime-like data to an array of floats. Parameters ---------- da : np.array Input data offset: Scalar with the same type of array or None If None, subtract minimum values to reduce round off error datetime_unit: None or any of {'Y', 'M', 'W', 'D', 'h', ...
def datetime_to_numeric(array, offset=None, datetime_unit=None, dtype=float): """Convert an array containing datetime-like data to an array of floats. Parameters ---------- da : np.array Input data offset: Scalar with the same type of array or None If None, subtract minimum values t...
Return the first non-NA elements in this array along the given axis
def first(values, axis, skipna=None): """Return the first non-NA elements in this array along the given axis """ if (skipna or skipna is None) and values.dtype.kind not in 'iSU': # only bother for dtypes that can hold NaN _fail_on_dask_array_input_skipna(values) return nanfirst(value...
inhouse mean that can handle np.datetime64 or cftime.datetime dtypes
def mean(array, axis=None, skipna=None, **kwargs): """inhouse mean that can handle np.datetime64 or cftime.datetime dtypes""" from .common import _contains_cftime_datetimes array = asarray(array) if array.dtype.kind in 'Mm': offset = min(array) # xarray always uses np.datetime64[ns]...
Return the last non-NA elements in this array along the given axis
def last(values, axis, skipna=None): """Return the last non-NA elements in this array along the given axis """ if (skipna or skipna is None) and values.dtype.kind not in 'iSU': # only bother for dtypes that can hold NaN _fail_on_dask_array_input_skipna(values) return nanlast(values, ...
Make an ndarray with a rolling window of axis-th dimension. The rolling dimension will be placed at the last dimension.
def rolling_window(array, axis, window, center, fill_value): """ Make an ndarray with a rolling window of axis-th dimension. The rolling dimension will be placed at the last dimension. """ if isinstance(array, dask_array_type): return dask_array_ops.rolling_window( array, axis, w...
Concatenate xarray objects along a new or existing dimension. Parameters ---------- objs : sequence of Dataset and DataArray objects xarray objects to concatenate together. Each object is expected to consist of variables and coordinates with matching shapes except for along the conc...
def concat(objs, dim=None, data_vars='all', coords='different', compat='equals', positions=None, indexers=None, mode=None, concat_over=None): """Concatenate xarray objects along a new or existing dimension. Parameters ---------- objs : sequence of Dataset and DataArray objects ...
Infer the dimension name and 1d coordinate variable (if appropriate) for concatenating along the new dimension.
def _calc_concat_dim_coord(dim): """ Infer the dimension name and 1d coordinate variable (if appropriate) for concatenating along the new dimension. """ from .dataarray import DataArray if isinstance(dim, str): coord = None elif not isinstance(dim, (DataArray, Variable)): di...
Determine which dataset variables need to be concatenated in the result, and which can simply be taken from the first dataset.
def _calc_concat_over(datasets, dim, data_vars, coords): """ Determine which dataset variables need to be concatenated in the result, and which can simply be taken from the first dataset. """ # Return values concat_over = set() equals = {} if dim in datasets[0]: concat_over.add(...
Concatenate a sequence of datasets along a new or existing dimension
def _dataset_concat(datasets, dim, data_vars, coords, compat, positions): """ Concatenate a sequence of datasets along a new or existing dimension """ from .dataset import Dataset if compat not in ['equals', 'identical']: raise ValueError("compat=%r invalid: must be 'equals' " ...
Given a list of lists (of lists...) of objects, returns a iterator which returns a tuple containing the index of each object in the nested list structure as the key, and the object. This can then be called by the dict constructor to create a dictionary of the objects organised by their position in the o...
def _infer_tile_ids_from_nested_list(entry, current_pos): """ Given a list of lists (of lists...) of objects, returns a iterator which returns a tuple containing the index of each object in the nested list structure as the key, and the object. This can then be called by the dict constructor to creat...
Concatenates and merges an N-dimensional structure of datasets. No checks are performed on the consistency of the datasets, concat_dims or tile_IDs, because it is assumed that this has already been done. Parameters ---------- combined_ids : Dict[Tuple[int, ...]], xarray.Dataset] Structure ...
def _combine_nd(combined_ids, concat_dims, data_vars='all', coords='different', compat='no_conflicts'): """ Concatenates and merges an N-dimensional structure of datasets. No checks are performed on the consistency of the datasets, concat_dims or tile_IDs, because it is assumed that thi...
Calls logic to decide concatenation order before concatenating.
def _auto_combine(datasets, concat_dims, compat, data_vars, coords, infer_order_from_coords, ids): """ Calls logic to decide concatenation order before concatenating. """ # Arrange datasets for concatenation if infer_order_from_coords: raise NotImplementedError # T...
Attempt to auto-magically combine the given datasets into one. This method attempts to combine a list of datasets into a single entity by inspecting metadata and using a combination of concat and merge. It does not concatenate along more than one dimension or sort data under any circumstances. It does a...
def auto_combine(datasets, concat_dim=_CONCAT_DIM_DEFAULT, compat='no_conflicts', data_vars='all', coords='different'): """Attempt to auto-magically combine the given datasets into one. This method attempts to combine a list of datasets into a single entity by inspecting metadata and using ...
Return the cftime date type for a given calendar name.
def get_date_type(calendar): """Return the cftime date type for a given calendar name.""" try: import cftime except ImportError: raise ImportError( 'cftime is required for dates with non-standard calendars') else: calendars = { 'noleap': cftime.DatetimeNoL...
Find the day in `other`'s month that satisfies a BaseCFTimeOffset's onOffset policy, as described by the `day_option` argument. Parameters ---------- other : cftime.datetime day_option : 'start', 'end' 'start': returns 1 'end': returns last day of the month Returns ------- ...
def _get_day_of_month(other, day_option): """Find the day in `other`'s month that satisfies a BaseCFTimeOffset's onOffset policy, as described by the `day_option` argument. Parameters ---------- other : cftime.datetime day_option : 'start', 'end' 'start': returns 1 'end': return...
The number of days in the month of the given date
def _days_in_month(date): """The number of days in the month of the given date""" if date.month == 12: reference = type(date)(date.year + 1, 1, 1) else: reference = type(date)(date.year, date.month + 1, 1) return (reference - timedelta(days=1)).day
Adjust the number of times a monthly offset is applied based on the day of a given date, and the reference day provided.
def _adjust_n_months(other_day, n, reference_day): """Adjust the number of times a monthly offset is applied based on the day of a given date, and the reference day provided. """ if n > 0 and other_day < reference_day: n = n - 1 elif n <= 0 and other_day > reference_day: n = n + 1 ...
Adjust the number of times an annual offset is applied based on another date, and the reference day provided
def _adjust_n_years(other, n, month, reference_day): """Adjust the number of times an annual offset is applied based on another date, and the reference day provided""" if n > 0: if other.month < month or (other.month == month and other.day < reference_day): ...
Shift the date to a month start or end a given number of months away.
def _shift_month(date, months, day_option='start'): """Shift the date to a month start or end a given number of months away. """ delta_year = (date.month + months) // 12 month = (date.month + months) % 12 if month == 0: month = 12 delta_year = delta_year - 1 year = date.year + d...
Possibly increment or decrement the number of periods to shift based on rollforward/rollbackward conventions. Parameters ---------- other : cftime.datetime n : number of periods to increment, before adjusting for rolling month : int reference month giving the first month of the year day_opt...
def roll_qtrday(other, n, month, day_option, modby=3): """Possibly increment or decrement the number of periods to shift based on rollforward/rollbackward conventions. Parameters ---------- other : cftime.datetime n : number of periods to increment, before adjusting for rolling month : int ...
Convert a frequency string to the appropriate subclass of BaseCFTimeOffset.
def to_offset(freq): """Convert a frequency string to the appropriate subclass of BaseCFTimeOffset.""" if isinstance(freq, BaseCFTimeOffset): return freq else: try: freq_data = re.match(_PATTERN, freq).groupdict() except AttributeError: raise ValueError('I...
Generate an equally-spaced sequence of cftime.datetime objects between and including two dates (whose length equals the number of periods).
def _generate_linear_range(start, end, periods): """Generate an equally-spaced sequence of cftime.datetime objects between and including two dates (whose length equals the number of periods).""" import cftime total_seconds = (end - start).total_seconds() values = np.linspace(0., total_seconds, peri...
Generate a regular range of cftime.datetime objects with a given time offset. Adapted from pandas.tseries.offsets.generate_range. Parameters ---------- start : cftime.datetime, or None Start of range end : cftime.datetime, or None End of range periods : int, or None ...
def _generate_range(start, end, periods, offset): """Generate a regular range of cftime.datetime objects with a given time offset. Adapted from pandas.tseries.offsets.generate_range. Parameters ---------- start : cftime.datetime, or None Start of range end : cftime.datetime, or Non...
Return a fixed frequency CFTimeIndex. Parameters ---------- start : str or cftime.datetime, optional Left bound for generating dates. end : str or cftime.datetime, optional Right bound for generating dates. periods : integer, optional Number of periods to generate. freq ...
def cftime_range(start=None, end=None, periods=None, freq='D', normalize=False, name=None, closed=None, calendar='standard'): """Return a fixed frequency CFTimeIndex. Parameters ---------- start : str or cftime.datetime, optional Left bound for generating dates...
Check if the given date is in the set of possible dates created using a length-one version of this offset class.
def onOffset(self, date): """Check if the given date is in the set of possible dates created using a length-one version of this offset class.""" mod_month = (date.month - self.month) % 3 return mod_month == 0 and date.day == self._get_offset_day(date)
Roll date forward to nearest start of quarter
def rollforward(self, date): """Roll date forward to nearest start of quarter""" if self.onOffset(date): return date else: return date + QuarterBegin(month=self.month)
Roll date backward to nearest start of quarter
def rollback(self, date): """Roll date backward to nearest start of quarter""" if self.onOffset(date): return date else: return date - QuarterBegin(month=self.month)
Roll date forward to nearest end of quarter
def rollforward(self, date): """Roll date forward to nearest end of quarter""" if self.onOffset(date): return date else: return date + QuarterEnd(month=self.month)
Roll date backward to nearest end of quarter
def rollback(self, date): """Roll date backward to nearest end of quarter""" if self.onOffset(date): return date else: return date - QuarterEnd(month=self.month)
Roll date forward to nearest start of year
def rollforward(self, date): """Roll date forward to nearest start of year""" if self.onOffset(date): return date else: return date + YearBegin(month=self.month)
Roll date backward to nearest start of year
def rollback(self, date): """Roll date backward to nearest start of year""" if self.onOffset(date): return date else: return date - YearBegin(month=self.month)
Check if the given date is in the set of possible dates created using a length-one version of this offset class.
def onOffset(self, date): """Check if the given date is in the set of possible dates created using a length-one version of this offset class.""" return date.day == _days_in_month(date) and date.month == self.month