INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Convert this dataset into an xarray.DataArray The data variables of this dataset will be broadcast against each other and stacked along the first axis of the new array. All coordinates of this dataset will remain coordinates. Parameters ---------- dim : str, optional ...
def to_array(self, dim='variable', name=None): """Convert this dataset into an xarray.DataArray The data variables of this dataset will be broadcast against each other and stacked along the first axis of the new array. All coordinates of this dataset will remain coordinates. Pa...
Convert a pandas.DataFrame into an xarray.Dataset Each column will be converted into an independent variable in the Dataset. If the dataframe's index is a MultiIndex, it will be expanded into a tensor product of one-dimensional indices (filling in missing values with NaN). This method w...
def from_dataframe(cls, dataframe): """Convert a pandas.DataFrame into an xarray.Dataset Each column will be converted into an independent variable in the Dataset. If the dataframe's index is a MultiIndex, it will be expanded into a tensor product of one-dimensional indices (filling in ...
Convert this dataset into a dask.dataframe.DataFrame. The dimensions, coordinates and data variables in this dataset form the columns of the DataFrame. Parameters ---------- dim_order : list, optional Hierarchical dimension order for the resulting dataframe. All ...
def to_dask_dataframe(self, dim_order=None, set_index=False): """ Convert this dataset into a dask.dataframe.DataFrame. The dimensions, coordinates and data variables in this dataset form the columns of the DataFrame. Parameters ---------- dim_order : list, opti...
Convert this dataset to a dictionary following xarray naming conventions. Converts all variables and attributes to native Python objects Useful for coverting to json. To avoid datetime incompatibility use decode_times=False kwarg in xarrray.open_dataset. Parameters ----...
def to_dict(self, data=True): """ Convert this dataset to a dictionary following xarray naming conventions. Converts all variables and attributes to native Python objects Useful for coverting to json. To avoid datetime incompatibility use decode_times=False kwarg in xarr...
Convert a dictionary into an xarray.Dataset. Input dict can take several forms:: d = {'t': {'dims': ('t'), 'data': t}, 'a': {'dims': ('t'), 'data': x}, 'b': {'dims': ('t'), 'data': y}} d = {'coords': {'t': {'dims': 't', 'data': t, ...
def from_dict(cls, d): """ Convert a dictionary into an xarray.Dataset. Input dict can take several forms:: d = {'t': {'dims': ('t'), 'data': t}, 'a': {'dims': ('t'), 'data': x}, 'b': {'dims': ('t'), 'data': y}} d = {'coords': {'t': {'...
Calculate the n-th order discrete difference along given axis. Parameters ---------- dim : str, optional Dimension over which to calculate the finite difference. n : int, optional The number of times values are differenced. label : str, optional ...
def diff(self, dim, n=1, label='upper'): """Calculate the n-th order discrete difference along given axis. Parameters ---------- dim : str, optional Dimension over which to calculate the finite difference. n : int, optional The number of times values are ...
Shift this dataset by an offset along one or more dimensions. Only data variables are moved; coordinates stay in place. This is consistent with the behavior of ``shift`` in pandas. Parameters ---------- shifts : Mapping with the form of {dim: offset} Integer offset ...
def shift(self, shifts=None, fill_value=dtypes.NA, **shifts_kwargs): """Shift this dataset by an offset along one or more dimensions. Only data variables are moved; coordinates stay in place. This is consistent with the behavior of ``shift`` in pandas. Parameters ---------- ...
Roll this dataset by an offset along one or more dimensions. Unlike shift, roll may rotate all variables, including coordinates if specified. The direction of rotation is consistent with :py:func:`numpy.roll`. Parameters ---------- shifts : dict, optional A...
def roll(self, shifts=None, roll_coords=None, **shifts_kwargs): """Roll this dataset by an offset along one or more dimensions. Unlike shift, roll may rotate all variables, including coordinates if specified. The direction of rotation is consistent with :py:func:`numpy.roll`. P...
Sort object by labels or values (along an axis). Sorts the dataset, either along specified dimensions, or according to values of 1-D dataarrays that share dimension with calling object. If the input variables are dataarrays, then the dataarrays are aligned (via left-join) to th...
def sortby(self, variables, ascending=True): """ Sort object by labels or values (along an axis). Sorts the dataset, either along specified dimensions, or according to values of 1-D dataarrays that share dimension with calling object. If the input variables are dataarra...
Compute the qth quantile of the data along the specified dimension. Returns the qth quantiles(s) of the array elements for each variable in the Dataset. Parameters ---------- q : float in range of [0,1] (or sequence of floats) Quantile to compute, which must be betw...
def quantile(self, q, dim=None, interpolation='linear', numeric_only=False, keep_attrs=None): """Compute the qth quantile of the data along the specified dimension. Returns the qth quantiles(s) of the array elements for each variable in the Dataset. Parameters ...
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 is True, computes percentage ranks. NaNs in the input array are returned as NaNs. ...
def rank(self, dim, pct=False, keep_attrs=None): """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 is True, computes percentage ranks....
Differentiate with the second order accurate central differences. .. note:: This feature is limited to simple cartesian geometry, i.e. coord must be one dimensional. Parameters ---------- coord: str The coordinate to be used to compute the gr...
def differentiate(self, coord, edge_order=1, datetime_unit=None): """ Differentiate with the second order accurate central differences. .. note:: This feature is limited to simple cartesian geometry, i.e. coord must be one dimensional. Parameters -------...
integrate the array with the trapezoidal rule. .. note:: This feature is limited to simple cartesian geometry, i.e. coord must be one dimensional. Parameters ---------- dim: str, or a sequence of str Coordinate(s) used for the integration. da...
def integrate(self, coord, datetime_unit=None): """ integrate the array with the trapezoidal rule. .. note:: This feature is limited to simple cartesian geometry, i.e. coord must be one dimensional. Parameters ---------- dim: str, or a sequence of str ...
Returns a ``Dataset`` with variables that match specific conditions. Can pass in ``key=value`` or ``key=callable``. A Dataset is returned containing only the variables for which all the filter tests pass. These tests are either ``key=value`` for which the attribute ``key`` has the exac...
def filter_by_attrs(self, **kwargs): """Returns a ``Dataset`` with variables that match specific conditions. Can pass in ``key=value`` or ``key=callable``. A Dataset is returned containing only the variables for which all the filter tests pass. These tests are either ``key=value`` for ...
Lazily apply an element-wise function to an array. Parameters ---------- array : any valid value of Variable._data func : callable Function to apply to indexed slices of an array. For use with dask, this should be a pickle-able object. dtype : coercible to np.dtype Dtype for...
def lazy_elemwise_func(array, func, dtype): """Lazily apply an element-wise function to an array. Parameters ---------- array : any valid value of Variable._data func : callable Function to apply to indexed slices of an array. For use with dask, this should be a pickle-able object. ...
A convenience function which pops a key k from source to dest. None values are not passed on. If k already exists in dest an error is raised.
def pop_to(source, dest, key, name=None): """ A convenience function which pops a key k from source to dest. None values are not passed on. If k already exists in dest an error is raised. """ value = source.pop(key, None) if value is not None: safe_setitem(dest, key, value, name=nam...
Mask all matching values in a NumPy arrays.
def _apply_mask( data: np.ndarray, encoded_fill_values: list, decoded_fill_value: Any, dtype: Any, ) -> np.ndarray: """Mask all matching values in a NumPy arrays.""" data = np.asarray(data, dtype=dtype) condition = False for fv in encoded_fill_values: condition |= data == fv ...
Return a float dtype that can losslessly represent `dtype` values.
def _choose_float_dtype(dtype, has_offset): """Return a float dtype that can losslessly represent `dtype` values.""" # Keep float32 as-is. Upcast half-precision to single-precision, # because float16 is "intended for storage but not computation" if dtype.itemsize <= 4 and np.issubdtype(dtype, np.floati...
wrapper for datasets
def _apply_over_vars_with_dim(func, self, dim=None, **kwargs): '''wrapper for datasets''' ds = type(self)(coords=self.coords, attrs=self.attrs) for name, var in self.data_vars.items(): if dim in var.dims: ds[name] = func(var, dim=dim, **kwargs) else: ds[name] = var ...
get index to use for x values in interpolation. If use_coordinate is True, the coordinate that shares the name of the dimension along which interpolation is being performed will be used as the x values. If use_coordinate is False, the x values are set as an equally spaced sequence.
def get_clean_interp_index(arr, dim, use_coordinate=True, **kwargs): '''get index to use for x values in interpolation. If use_coordinate is True, the coordinate that shares the name of the dimension along which interpolation is being performed will be used as the x values. If use_coordinate is Fa...
Interpolate values according to different methods.
def interp_na(self, dim=None, use_coordinate=True, method='linear', limit=None, **kwargs): '''Interpolate values according to different methods.''' if dim is None: raise NotImplementedError('dim is a required argument') if limit is not None: valids = _get_valid_fill_mask(self...
helper function to apply interpolation along 1 dimension
def func_interpolate_na(interpolator, x, y, **kwargs): '''helper function to apply interpolation along 1 dimension''' # it would be nice if this wasn't necessary, works around: # "ValueError: assignment destination is read-only" in assignment below out = y.copy() nans = pd.isnull(y) nonans = ~n...
inverse of ffill
def _bfill(arr, n=None, axis=-1): '''inverse of ffill''' import bottleneck as bn arr = np.flip(arr, axis=axis) # fill arr = bn.push(arr, axis=axis, n=n) # reverse back to original return np.flip(arr, axis=axis)
forward fill missing values
def ffill(arr, dim=None, limit=None): '''forward fill missing values''' import bottleneck as bn axis = arr.get_axis_num(dim) # work around for bottleneck 178 _limit = limit if limit is not None else arr.shape[axis] return apply_ufunc(bn.push, arr, dask='parallelized', ...
backfill missing values
def bfill(arr, dim=None, limit=None): '''backfill missing values''' axis = arr.get_axis_num(dim) # work around for bottleneck 178 _limit = limit if limit is not None else arr.shape[axis] return apply_ufunc(_bfill, arr, dask='parallelized', keep_attrs=T...
helper function to select the appropriate interpolator class returns interpolator class and keyword arguments for the class
def _get_interpolator(method, vectorizeable_only=False, **kwargs): '''helper function to select the appropriate interpolator class returns interpolator class and keyword arguments for the class ''' interp1d_methods = ['linear', 'nearest', 'zero', 'slinear', 'quadratic', 'cubic',...
helper function to select the appropriate interpolator class returns interpolator class and keyword arguments for the class
def _get_interpolator_nd(method, **kwargs): '''helper function to select the appropriate interpolator class returns interpolator class and keyword arguments for the class ''' valid_methods = ['linear', 'nearest'] try: from scipy import interpolate except ImportError: raise Impo...
helper function to determine values that can be filled when limit is not None
def _get_valid_fill_mask(arr, dim, limit): '''helper function to determine values that can be filled when limit is not None''' kw = {dim: limit + 1} # we explicitly use construct method to avoid copy. new_dim = utils.get_temp_dimname(arr.dims, '_window') return (arr.isnull().rolling(min_periods=...
Speed up for linear and nearest neighbor method. Only consider a subspace that is needed for the interpolation
def _localize(var, indexes_coords): """ Speed up for linear and nearest neighbor method. Only consider a subspace that is needed for the interpolation """ indexes = {} for dim, [x, new_x] in indexes_coords.items(): index = x.to_index() imin = index.get_loc(np.min(new_x.values), metho...
Make x and new_x float. This is particulary useful for datetime dtype. x, new_x: tuple of np.ndarray
def _floatize_x(x, new_x): """ Make x and new_x float. This is particulary useful for datetime dtype. x, new_x: tuple of np.ndarray """ x = list(x) new_x = list(new_x) for i in range(len(x)): if _contains_datetime_like_objects(x[i]): # Scipy casts coordinates to np.float6...
Make an interpolation of Variable Parameters ---------- var: Variable index_coords: Mapping from dimension name to a pair of original and new coordinates. Original coordinates should be sorted in strictly ascending order. Note that all the coordinates should be Variable objects....
def interp(var, indexes_coords, method, **kwargs): """ Make an interpolation of Variable Parameters ---------- var: Variable index_coords: Mapping from dimension name to a pair of original and new coordinates. Original coordinates should be sorted in strictly ascending order. ...
multi-dimensional interpolation for array-like. Interpolated axes should be located in the last position. Parameters ---------- var: np.ndarray or dask.array.Array Array to be interpolated. The final dimension is interpolated. x: a list of 1d array. Original coordinates. Should not ...
def interp_func(var, x, new_x, method, kwargs): """ multi-dimensional interpolation for array-like. Interpolated axes should be located in the last position. Parameters ---------- var: np.ndarray or dask.array.Array Array to be interpolated. The final dimension is interpolated. x: a...
Put coord, value in template and truncate at maxchar
def _nicetitle(coord, value, maxchar, template): """ Put coord, value in template and truncate at maxchar """ prettyvalue = format_item(value, quote_strings=False) title = template.format(coord=coord, value=prettyvalue) if len(title) > maxchar: title = title[:(maxchar - 3)] + '...' ...
Convenience method to call xarray.plot.FacetGrid from 2d plotting methods kwargs are the arguments to 2d plotting method
def _easy_facetgrid(data, plotfunc, kind, x=None, y=None, row=None, col=None, col_wrap=None, sharex=True, sharey=True, aspect=None, size=None, subplot_kws=None, **kwargs): """ Convenience method to call xarray.plot.FacetGrid from 2d plotting methods kwargs are the ar...
Apply a plotting function to a 2d facet's subset of the data. This is more convenient and less general than ``FacetGrid.map`` Parameters ---------- func : callable A plotting function with the same signature as a 2d xarray plotting method such as `xarray.plot.im...
def map_dataarray(self, func, x, y, **kwargs): """ Apply a plotting function to a 2d facet's subset of the data. This is more convenient and less general than ``FacetGrid.map`` Parameters ---------- func : callable A plotting function with the same signature...
Finalize the annotations and layout.
def _finalize_grid(self, *axlabels): """Finalize the annotations and layout.""" if not self._finalized: self.set_axis_labels(*axlabels) self.set_titles() self.fig.tight_layout() for ax, namedict in zip(self.axes.flat, self.name_dicts.flat): ...
Draw a colorbar
def add_colorbar(self, **kwargs): """Draw a colorbar """ kwargs = kwargs.copy() if self._cmap_extend is not None: kwargs.setdefault('extend', self._cmap_extend) if 'label' not in kwargs: kwargs.setdefault('label', label_from_attrs(self.data)) self....
Set axis labels on the left column and bottom row of the grid.
def set_axis_labels(self, x_var=None, y_var=None): """Set axis labels on the left column and bottom row of the grid.""" if x_var is not None: if x_var in self.data.coords: self._x_var = x_var self.set_xlabels(label_from_attrs(self.data[x_var])) els...
Label the x axis on the bottom row of the grid.
def set_xlabels(self, label=None, **kwargs): """Label the x axis on the bottom row of the grid.""" if label is None: label = label_from_attrs(self.data[self._x_var]) for ax in self._bottom_axes: ax.set_xlabel(label, **kwargs) return self
Label the y axis on the left column of the grid.
def set_ylabels(self, label=None, **kwargs): """Label the y axis on the left column of the grid.""" if label is None: label = label_from_attrs(self.data[self._y_var]) for ax in self._left_axes: ax.set_ylabel(label, **kwargs) return self
Draw titles either above each facet or on the grid margins. Parameters ---------- template : string Template for plot titles containing {coord} and {value} maxchar : int Truncate titles at maxchar kwargs : keyword args additional arguments to ...
def set_titles(self, template="{coord} = {value}", maxchar=30, **kwargs): """ Draw titles either above each facet or on the grid margins. Parameters ---------- template : string Template for plot titles containing {coord} and {value} maxcha...
Set and control tick behavior Parameters ---------- max_xticks, max_yticks : int, optional Maximum number of labeled ticks to plot on x, y axes fontsize : string or int Font size as used by matplotlib text Returns ------- self : FacetGrid...
def set_ticks(self, max_xticks=_NTICKS, max_yticks=_NTICKS, fontsize=_FONTSIZE): """ Set and control tick behavior Parameters ---------- max_xticks, max_yticks : int, optional Maximum number of labeled ticks to plot on x, y axes fontsize : s...
Apply a plotting function to each facet's subset of the data. Parameters ---------- func : callable A plotting function that takes data and keyword arguments. It must plot to the currently active matplotlib Axes and take a `color` keyword argument. If facetin...
def map(self, func, *args, **kwargs): """ Apply a plotting function to each facet's subset of the data. Parameters ---------- func : callable A plotting function that takes data and keyword arguments. It must plot to the currently active matplotlib Axes a...
Obtain the bins and their respective labels for resampling operations. Parameters ---------- index : CFTimeIndex Index object to be resampled (e.g., CFTimeIndex named 'time'). freq : xarray.coding.cftime_offsets.BaseCFTimeOffset The offset object representing target conversion a.k.a. re...
def _get_time_bins(index, freq, closed, label, base): """Obtain the bins and their respective labels for resampling operations. Parameters ---------- index : CFTimeIndex Index object to be resampled (e.g., CFTimeIndex named 'time'). freq : xarray.coding.cftime_offsets.BaseCFTimeOffset ...
This is required for determining the bin edges resampling with daily frequencies greater than one day, month end, and year end frequencies. Consider the following example. Let's say you want to downsample the time series with the following coordinates to month end frequency: CFTimeIndex([2000-01-...
def _adjust_bin_edges(datetime_bins, offset, closed, index, labels): """This is required for determining the bin edges resampling with daily frequencies greater than one day, month end, and year end frequencies. Consider the following example. Let's say you want to downsample the time series with ...
Get the correct starting and ending datetimes for the resampled CFTimeIndex range. Parameters ---------- first : cftime.datetime Uncorrected starting datetime object for resampled CFTimeIndex range. Usually the min of the original CFTimeIndex. last : cftime.datetime Uncorrec...
def _get_range_edges(first, last, offset, closed='left', base=0): """ Get the correct starting and ending datetimes for the resampled CFTimeIndex range. Parameters ---------- first : cftime.datetime Uncorrected starting datetime object for resampled CFTimeIndex range. Usually the mi...
First and last offsets should be calculated from the start day to fix an error cause by resampling across multiple days when a one day period is not a multiple of the frequency. See https://github.com/pandas-dev/pandas/issues/8683 Parameters ---------- first : cftime.datetime A datetime...
def _adjust_dates_anchored(first, last, offset, closed='right', base=0): """ First and last offsets should be calculated from the start day to fix an error cause by resampling across multiple days when a one day period is not a multiple of the frequency. See https://github.com/pandas-dev/pandas/issues/8...
Meant to reproduce the results of the following grouper = pandas.Grouper(...) first_items = pd.Series(np.arange(len(index)), index).groupby(grouper).first() with index being a CFTimeIndex instead of a DatetimeIndex.
def first_items(self, index): """Meant to reproduce the results of the following grouper = pandas.Grouper(...) first_items = pd.Series(np.arange(len(index)), index).groupby(grouper).first() with index being a CFTimeIndex instead of a DatetimeIndex. ...
align(*objects, join='inner', copy=True, indexes=None, exclude=frozenset()) Given any number of Dataset and/or DataArray objects, returns new objects with aligned indexes and dimension sizes. Array from the aligned objects are suitable as input to mathematical operators, because along eac...
def align(*objects, **kwargs): """align(*objects, join='inner', copy=True, indexes=None, exclude=frozenset()) Given any number of Dataset and/or DataArray objects, returns new objects with aligned indexes and dimension sizes. Array from the aligned objects are suitable as input to mathema...
Align objects for merging, recursing into dictionary values. This function is not public API.
def deep_align(objects, join='inner', copy=True, indexes=None, exclude=frozenset(), raise_on_invalid=True): """Align objects for merging, recursing into dictionary values. This function is not public API. """ from .dataarray import DataArray from .dataset import Dataset if index...
Extract indexers to align target with other. Not public API. Parameters ---------- target : Dataset or DataArray Object to be aligned. other : Dataset or DataArray Object to be aligned with. Returns ------- Dict[Any, pandas.Index] providing indexes for reindex keyword ...
def reindex_like_indexers(target, other): """Extract indexers to align target with other. Not public API. Parameters ---------- target : Dataset or DataArray Object to be aligned. other : Dataset or DataArray Object to be aligned with. Returns ------- Dict[Any, pan...
Conform a dictionary of aligned variables onto a new set of variables, filling in missing values with NaN. Not public API. Parameters ---------- variables : dict-like Dictionary of xarray.Variable objects. sizes : dict-like Dictionary from dimension names to integer sizes. ...
def reindex_variables( variables: Mapping[Any, Variable], sizes: Mapping[Any, int], indexes: Mapping[Any, pd.Index], indexers: Mapping, method: Optional[str] = None, tolerance: Any = None, copy: bool = True, ) -> 'Tuple[OrderedDict[Any, Variable], OrderedDict[Any, pd.Index]]': """Conform...
Explicitly broadcast any number of DataArray or Dataset objects against one another. xarray objects automatically broadcast against each other in arithmetic operations, so this function should not be necessary for normal use. If no change is needed, the input data is returned to the output without ...
def broadcast(*args, **kwargs): """Explicitly broadcast any number of DataArray or Dataset objects against one another. xarray objects automatically broadcast against each other in arithmetic operations, so this function should not be necessary for normal use. If no change is needed, the input dat...
Maeke sure the dimension coordinate of obj is consistent with coords. obj: DataArray or Dataset coords: Dict-like of variables
def assert_coordinate_consistent(obj, coords): """ Maeke sure the dimension coordinate of obj is consistent with coords. obj: DataArray or Dataset coords: Dict-like of variables """ for k in obj.dims: # make sure there are no conflict in dimension coordinates if k in coords and ...
Remap **indexers from obj.coords. If indexer is an instance of DataArray and it has coordinate, then this coordinate will be attached to pos_indexers. Returns ------- pos_indexers: Same type of indexers. np.ndarray or Variable or DataArra new_indexes: mapping of new dimensional-coordina...
def remap_label_indexers(obj, indexers=None, method=None, tolerance=None, **indexers_kwargs): """ Remap **indexers from obj.coords. If indexer is an instance of DataArray and it has coordinate, then this coordinate will be attached to pos_indexers. Returns ------- p...
Convert all index coordinates into a :py:class:`pandas.Index`. Parameters ---------- ordered_dims : sequence, optional Possibly reordered version of this object's dimensions indicating the order in which dimensions should appear on the result. Returns --...
def to_index(self, ordered_dims=None): """Convert all index coordinates into a :py:class:`pandas.Index`. Parameters ---------- ordered_dims : sequence, optional Possibly reordered version of this object's dimensions indicating the order in which dimensions should...
For use with binary arithmetic.
def _merge_raw(self, other): """For use with binary arithmetic.""" if other is None: variables = OrderedDict(self.variables) else: # don't align because we already called xarray.align variables = expand_and_merge_variables( [self.variables, oth...
For use with in-place binary arithmetic.
def _merge_inplace(self, other): """For use with in-place binary arithmetic.""" if other is None: yield else: # don't include indexes in priority_vars, because we didn't align # first priority_vars = OrderedDict( kv for kv in self.v...
Provide method for the key-autocompletions in IPython.
def _ipython_key_completions_(self): """Provide method for the key-autocompletions in IPython. """ return [key for key in self._data._ipython_key_completions_() if key not in self._data.data_vars]
Merge two sets of coordinates to create a new Dataset The method implements the logic used for joining coordinates in the result of a binary operation performed on xarray objects: - If two index coordinates conflict (are not equal), an exception is raised. You must align your data be...
def merge(self, other): """Merge two sets of coordinates to create a new Dataset The method implements the logic used for joining coordinates in the result of a binary operation performed on xarray objects: - If two index coordinates conflict (are not equal), an exception is ...
wrapper to apply bottleneck moving window funcs on dask arrays
def dask_rolling_wrapper(moving_func, a, window, min_count=None, axis=-1): '''wrapper to apply bottleneck moving window funcs on dask arrays''' dtype, fill_value = dtypes.maybe_promote(a.dtype) a = a.astype(dtype) # inputs for overlap if axis < 0: axis = a.ndim + axis depth = {d: 0 for d...
Dask's equivalence to np.utils.rolling_window
def rolling_window(a, axis, window, center, fill_value): """ Dask's equivalence to np.utils.rolling_window """ orig_shape = a.shape if axis < 0: axis = a.ndim + axis depth = {d: 0 for d in range(a.ndim)} depth[axis] = int(window / 2) # For evenly sized window, we need to crop the first p...
Given encoding chunks (possibly None) and variable chunks (possibly None)
def _determine_zarr_chunks(enc_chunks, var_chunks, ndim): """ Given encoding chunks (possibly None) and variable chunks (possibly None) """ # zarr chunk spec: # chunks : int or tuple of ints, optional # Chunk shape. If not provided, will be guessed from shape and dtype. # if there are no...
Converts an Variable into an Variable which follows some of the CF conventions: - Nans are masked using _FillValue (or the deprecated missing_value) - Rescaling via: scale_factor and add_offset - datetimes are converted to the CF 'units since time' format - dtype encodings are enfor...
def encode_zarr_variable(var, needs_copy=True, name=None): """ Converts an Variable into an Variable which follows some of the CF conventions: - Nans are masked using _FillValue (or the deprecated missing_value) - Rescaling via: scale_factor and add_offset - datetimes are converted ...
Load and decode a dataset from a Zarr store. .. note:: Experimental The Zarr backend is new and experimental. Please report any unexpected behavior via github issues. The `store` object should be a valid store for a Zarr group. `store` variables must contain dimension metadata ...
def open_zarr(store, group=None, synchronizer=None, chunks='auto', decode_cf=True, mask_and_scale=True, decode_times=True, concat_characters=True, decode_coords=True, drop_variables=None, consolidated=False, overwrite_encoded_chunks=False, **kwargs): """Load a...
Extract dimension sizes from a dictionary of variables. Raises ValueError if any dimensions have different sizes.
def broadcast_dimension_size( variables: List[Variable], ) -> 'OrderedDict[Any, int]': """Extract dimension sizes from a dictionary of variables. Raises ValueError if any dimensions have different sizes. """ dims = OrderedDict() # type: OrderedDict[Any, int] for var in variables: for d...
Return the unique variable from a list of variables or raise MergeError. Parameters ---------- name : hashable Name for this variable. variables : list of xarray.Variable List of Variable objects, all of which go by the same name in different inputs. compat : {'identical', '...
def unique_variable(name, variables, compat='broadcast_equals'): # type: (Any, List[Variable], str) -> Variable """Return the unique variable from a list of variables or raise MergeError. Parameters ---------- name : hashable Name for this variable. variables : list of xarray.Variable ...
Merge dicts of variables, while resolving conflicts appropriately. Parameters ---------- lists_of_variables_dicts : list of mappings with Variable values List of mappings for which each value is a xarray.Variable object. priority_vars : mapping with Variable or None values, optional If ...
def merge_variables( list_of_variables_dicts, # type: List[Mapping[Any, Variable]] priority_vars=None, # type: Optional[Mapping[Any, Variable]] compat='minimal', # type: str ): # type: (...) -> OrderedDict[Any, Variable] """Merge dicts of variables, while resolving conflic...
Given a list of dicts with xarray object values, expand the values. Parameters ---------- list_of_variable_dicts : list of dict or Dataset objects Each value for the mappings must be of the following types: - an xarray.Variable - a tuple `(dims, data[, attrs[, encoding]])` that can ...
def expand_variable_dicts( list_of_variable_dicts: 'List[Union[Dataset, OrderedDict]]', ) -> 'List[Mapping[Any, Variable]]': """Given a list of dicts with xarray object values, expand the values. Parameters ---------- list_of_variable_dicts : list of dict or Dataset objects Each value for t...
Given a list of dicts with xarray object values, identify coordinates. Parameters ---------- list_of_variable_dicts : list of dict or Dataset objects Of the same form as the arguments to expand_variable_dicts. Returns ------- coord_names : set of variable names noncoord_names : set...
def determine_coords(list_of_variable_dicts): # type: (List[Dict]) -> Tuple[Set, Set] """Given a list of dicts with xarray object values, identify coordinates. Parameters ---------- list_of_variable_dicts : list of dict or Dataset objects Of the same form as the arguments to expand_variable...
Convert pandas values found in a list of labeled objects. Parameters ---------- objects : list of Dataset or mappings The mappings may contain any sort of objects coercible to xarray.Variables as keys, including pandas objects. Returns ------- List of Dataset or OrderedDict obj...
def coerce_pandas_values(objects): """Convert pandas values found in a list of labeled objects. Parameters ---------- objects : list of Dataset or mappings The mappings may contain any sort of objects coercible to xarray.Variables as keys, including pandas objects. Returns ----...
Merge coordinate variables without worrying about alignment. This function is used for merging variables in coordinates.py.
def merge_coords_for_inplace_math(objs, priority_vars=None): """Merge coordinate variables without worrying about alignment. This function is used for merging variables in coordinates.py. """ expanded = expand_variable_dicts(objs) variables = merge_variables(expanded, priority_vars) assert_uniq...
Extract the priority variable from a list of mappings. We need this method because in some cases the priority argument itself might have conflicting values (e.g., if it is a dict with two DataArray values with conflicting coordinate values). Parameters ---------- objects : list of dictionaries...
def _get_priority_vars(objects, priority_arg, compat='equals'): """Extract the priority variable from a list of mappings. We need this method because in some cases the priority argument itself might have conflicting values (e.g., if it is a dict with two DataArray values with conflicting coordinate val...
Merge coordinate variables without worrying about alignment. This function is used for merging variables in computation.py.
def expand_and_merge_variables(objs, priority_arg=None): """Merge coordinate variables without worrying about alignment. This function is used for merging variables in computation.py. """ expanded = expand_variable_dicts(objs) priority_vars = _get_priority_vars(objs, priority_arg) variables = m...
Merge coordinate variables. See merge_core below for argument descriptions. This works similarly to merge_core, except everything we don't worry about whether variables are coordinates or not.
def merge_coords(objs, compat='minimal', join='outer', priority_arg=None, indexes=None): """Merge coordinate variables. See merge_core below for argument descriptions. This works similarly to merge_core, except everything we don't worry about whether variables are coordinates or not. ...
Used in Dataset.__init__.
def merge_data_and_coords(data, coords, compat='broadcast_equals', join='outer'): """Used in Dataset.__init__.""" objs = [data, coords] explicit_coords = coords.keys() indexes = dict(extract_indexes(coords)) return merge_core(objs, compat, join, explicit_coords=explicit_coo...
Yields the name & index of valid indexes from a mapping of coords
def extract_indexes(coords): """Yields the name & index of valid indexes from a mapping of coords""" for name, variable in coords.items(): variable = as_variable(variable, name=name) if variable.dims == (name,): yield name, variable.to_index()
Validate explicit coordinate names/dims. Raise a MergeError if an explicit coord shares a name with a dimension but is comprised of arbitrary dimensions.
def assert_valid_explicit_coords(variables, dims, explicit_coords): """Validate explicit coordinate names/dims. Raise a MergeError if an explicit coord shares a name with a dimension but is comprised of arbitrary dimensions. """ for coord_name in explicit_coords: if coord_name in dims and v...
Core logic for merging labeled objects. This is not public API. Parameters ---------- objs : list of mappings All values must be convertable to labeled arrays. compat : {'identical', 'equals', 'broadcast_equals', 'no_conflicts'}, optional Compatibility checks to use when merging va...
def merge_core(objs, compat='broadcast_equals', join='outer', priority_arg=None, explicit_coords=None, indexes=None): """Core logic for merging labeled objects. This is not public API. Parameters ---------- objs : list of m...
Merge any number of xarray objects into a single Dataset as variables. Parameters ---------- objects : Iterable[Union[xarray.Dataset, xarray.DataArray, dict]] Merge together all variables from these objects. If any of them are DataArray objects, they must have a name. compat : {'identic...
def merge(objects, compat='no_conflicts', join='outer'): """Merge any number of xarray objects into a single Dataset as variables. Parameters ---------- objects : Iterable[Union[xarray.Dataset, xarray.DataArray, dict]] Merge together all variables from these objects. If any of them are ...
Guts of the Dataset.merge method.
def dataset_merge_method(dataset, other, overwrite_vars, compat, join): """Guts of the Dataset.merge method.""" # we are locked into supporting overwrite_vars for the Dataset.merge # method due for backwards compatibility # TODO: consider deprecating it? if isinstance(overwrite_vars, str): ...
Guts of the Dataset.update method. This drops a duplicated coordinates from `other` if `other` is not an `xarray.Dataset`, e.g., if it's a dict with DataArray values (GH2068, GH2180).
def dataset_update_method(dataset, other): """Guts of the Dataset.update method. This drops a duplicated coordinates from `other` if `other` is not an `xarray.Dataset`, e.g., if it's a dict with DataArray values (GH2068, GH2180). """ from .dataset import Dataset from .dataarray import DataA...
replace nan in a by val, and returns the replaced array and the nan position
def _replace_nan(a, val): """ replace nan in a by val, and returns the replaced array and the nan position """ mask = isnull(a) return where_method(val, mask, a), mask
xarray version of pandas.core.nanops._maybe_null_out
def _maybe_null_out(result, axis, mask, min_count=1): """ xarray version of pandas.core.nanops._maybe_null_out """ if hasattr(axis, '__len__'): # if tuple or list raise ValueError('min_count is not available for reduction ' 'with more than one dimensions.') if axis...
In house nanargmin, nanargmax for object arrays. Always return integer type
def _nan_argminmax_object(func, fill_value, value, axis=None, **kwargs): """ In house nanargmin, nanargmax for object arrays. Always return integer type """ valid_count = count(value, axis=axis) value = fillna(value, fill_value) data = _dask_or_eager_func(func)(value, axis=axis, **kwargs) #...
In house nanmin and nanmax for object array
def _nan_minmax_object(func, fill_value, value, axis=None, **kwargs): """ In house nanmin and nanmax for object array """ valid_count = count(value, axis=axis) filled_value = fillna(value, fill_value) data = getattr(np, func)(filled_value, axis=axis, **kwargs) if not hasattr(data, 'dtype'): # scala...
In house nanmean. ddof argument will be used in _nanvar method
def _nanmean_ddof_object(ddof, value, axis=None, **kwargs): """ In house nanmean. ddof argument will be used in _nanvar method """ from .duck_array_ops import (count, fillna, _dask_or_eager_func, where_method) valid_count = count(value, axis=axis) value = fillna(value, ...
Disable automatic decoding on a netCDF4.Variable. We handle these types of decoding ourselves.
def _disable_auto_decode_variable(var): """Disable automatic decoding on a netCDF4.Variable. We handle these types of decoding ourselves. """ var.set_auto_maskandscale(False) # only added in netCDF4-python v1.2.8 with suppress(AttributeError): var.set_auto_chartostring(False)
Simpler equivalent of pandas.core.common._maybe_promote Parameters ---------- dtype : np.dtype Returns ------- dtype : Promoted dtype that can hold missing values. fill_value : Valid missing value for the promoted dtype.
def maybe_promote(dtype): """Simpler equivalent of pandas.core.common._maybe_promote Parameters ---------- dtype : np.dtype Returns ------- dtype : Promoted dtype that can hold missing values. fill_value : Valid missing value for the promoted dtype. """ # N.B. these casting rul...
Return an appropriate positive infinity for this dtype. Parameters ---------- dtype : np.dtype Returns ------- fill_value : positive infinity value corresponding to this dtype.
def get_pos_infinity(dtype): """Return an appropriate positive infinity for this dtype. Parameters ---------- dtype : np.dtype Returns ------- fill_value : positive infinity value corresponding to this dtype. """ if issubclass(dtype.type, (np.floating, np.integer)): return ...
Return an appropriate positive infinity for this dtype. Parameters ---------- dtype : np.dtype Returns ------- fill_value : positive infinity value corresponding to this dtype.
def get_neg_infinity(dtype): """Return an appropriate positive infinity for this dtype. Parameters ---------- dtype : np.dtype Returns ------- fill_value : positive infinity value corresponding to this dtype. """ if issubclass(dtype.type, (np.floating, np.integer)): return ...
Check if a dtype is a subclass of the numpy datetime types
def is_datetime_like(dtype): """Check if a dtype is a subclass of the numpy datetime types """ return (np.issubdtype(dtype, np.datetime64) or np.issubdtype(dtype, np.timedelta64))
Like np.result_type, but with type promotion rules matching pandas. Examples of changed behavior: number + string -> object (not string) bytes + unicode -> object (not unicode) Parameters ---------- *arrays_and_dtypes : list of arrays and dtypes The dtype is extracted from both numpy a...
def result_type(*arrays_and_dtypes): """Like np.result_type, but with type promotion rules matching pandas. Examples of changed behavior: number + string -> object (not string) bytes + unicode -> object (not unicode) Parameters ---------- *arrays_and_dtypes : list of arrays and dtypes ...
Parse ENVI metadata into Python data structures. See the link for information on the ENVI header file format: http://www.harrisgeospatial.com/docs/enviheaderfiles.html Parameters ---------- meta : dict Dictionary of keys and str values to parse, as returned by the rasterio tags(ns=...
def _parse_envi(meta): """Parse ENVI metadata into Python data structures. See the link for information on the ENVI header file format: http://www.harrisgeospatial.com/docs/enviheaderfiles.html Parameters ---------- meta : dict Dictionary of keys and str values to parse, as returned by...
Open a file with rasterio (experimental). This should work with any file that rasterio can open (most often: geoTIFF). The x and y coordinates are generated automatically from the file's geoinformation, shifted to the center of each pixel (see `"PixelIsArea" Raster Space <http://web.archive.org/web...
def open_rasterio(filename, parse_coordinates=None, chunks=None, cache=None, lock=None): """Open a file with rasterio (experimental). This should work with any file that rasterio can open (most often: geoTIFF). The x and y coordinates are generated automatically from the file's geoinf...
Get indexer for rasterio array. Parameter --------- key: tuple of int Returns ------- band_key: an indexer for the 1st dimension window: two tuples. Each consists of (start, stop). squeeze_axis: axes to be squeezed np_ind: indexer for loaded nump...
def _get_indexer(self, key): """ Get indexer for rasterio array. Parameter --------- key: tuple of int Returns ------- band_key: an indexer for the 1st dimension window: two tuples. Each consists of (start, stop). squeeze_axis: axes to be squeeze...
Group an array by its unique values. Parameters ---------- ar : array-like Input array. This will be flattened if it is not already 1-D. sort : boolean, optional Whether or not to sort unique values. Returns ------- values : np.ndarray Sorted, unique values as retur...
def unique_value_groups(ar, sort=True): """Group an array by its unique values. Parameters ---------- ar : array-like Input array. This will be flattened if it is not already 1-D. sort : boolean, optional Whether or not to sort unique values. Returns ------- values : np...
Consolidate adjacent slices in a list of slices.
def _consolidate_slices(slices): """Consolidate adjacent slices in a list of slices. """ result = [] last_slice = slice(None) for slice_ in slices: if not isinstance(slice_, slice): raise ValueError('list element is not a slice: %r' % slice_) if (result and last_slice.sto...
Like inverse_permutation, but also handles slices. Parameters ---------- positions : list of np.ndarray or slice objects. If slice objects, all are assumed to be slices. Returns ------- np.ndarray of indices or None, if no permutation is necessary.
def _inverse_permutation_indices(positions): """Like inverse_permutation, but also handles slices. Parameters ---------- positions : list of np.ndarray or slice objects. If slice objects, all are assumed to be slices. Returns ------- np.ndarray of indices or None, if no permutation...
(copied from pandas) if loffset is set, offset the result index This is NOT an idempotent routine, it will be applied exactly once to the result. Parameters ---------- result : Series or DataFrame the result of resample
def _apply_loffset(grouper, result): """ (copied from pandas) if loffset is set, offset the result index This is NOT an idempotent routine, it will be applied exactly once to the result. Parameters ---------- result : Series or DataFrame the result of resample """ need...