INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
r"""Implements the N-dim version of function
$$TV^{\beta}(x) = \sum_{whc} \left ( \left ( x(h, w+1, c) - x(h, w, c) \right )^{2} +
\left ( x(h+1, w, c) - x(h, w, c) \right )^{2} \right )^{\frac{\beta}{2}}$$
to return total variation for all images in the batch. | def build_loss(self):
r"""Implements the N-dim version of function
$$TV^{\beta}(x) = \sum_{whc} \left ( \left ( x(h, w+1, c) - x(h, w, c) \right )^{2} +
\left ( x(h+1, w, c) - x(h, w, c) \right )^{2} \right )^{\frac{\beta}{2}}$$
to return total variation for all images in the batch.
... |
Utility to find font file. | def _find_font_file(query):
"""Utility to find font file.
"""
return list(filter(lambda path: query.lower() in os.path.basename(path).lower(), fontman.findSystemFonts())) |
Updates `kwargs` with dict of `defaults`
Args:
defaults: A dictionary of keys and values
**kwargs: The kwargs to update.
Returns:
The updated kwargs. | def add_defaults_to_kwargs(defaults, **kwargs):
"""Updates `kwargs` with dict of `defaults`
Args:
defaults: A dictionary of keys and values
**kwargs: The kwargs to update.
Returns:
The updated kwargs.
"""
defaults = dict(defaults)
defaults.update(kwargs)
return defa... |
Helper utility to retrieve the callable function associated with a string identifier.
Args:
identifier: The identifier. Could be a string or function.
module_globals: The global objects of the module.
module_name: The module name
Returns:
The callable associated with the identi... | def get_identifier(identifier, module_globals, module_name):
"""Helper utility to retrieve the callable function associated with a string identifier.
Args:
identifier: The identifier. Could be a string or function.
module_globals: The global objects of the module.
module_name: The modul... |
Applies modifications to the model layers to create a new Graph. For example, simply changing
`model.layers[idx].activation = new activation` does not change the graph. The entire graph needs to be updated
with modified inbound and outbound tensors because of change in layer building function.
Args:
... | def apply_modifications(model, custom_objects=None):
"""Applies modifications to the model layers to create a new Graph. For example, simply changing
`model.layers[idx].activation = new activation` does not change the graph. The entire graph needs to be updated
with modified inbound and outbound tensors bec... |
Creates a uniformly distributed random array with the given `mean` and `std`.
Args:
shape: The desired shape
mean: The desired mean (Default value = 128)
std: The desired std (Default value = 20)
Returns: Random numpy array of given `shape` uniformly distributed with desired `mean` and... | def random_array(shape, mean=128., std=20.):
"""Creates a uniformly distributed random array with the given `mean` and `std`.
Args:
shape: The desired shape
mean: The desired mean (Default value = 128)
std: The desired std (Default value = 20)
Returns: Random numpy array of given `... |
Looks up the layer index corresponding to `layer_name` from `model`.
Args:
model: The `keras.models.Model` instance.
layer_name: The name of the layer to lookup.
Returns:
The layer index if found. Raises an exception otherwise. | def find_layer_idx(model, layer_name):
"""Looks up the layer index corresponding to `layer_name` from `model`.
Args:
model: The `keras.models.Model` instance.
layer_name: The name of the layer to lookup.
Returns:
The layer index if found. Raises an exception otherwise.
"""
... |
Utility function to scale the `input_array` to `input_range` throwing away high frequency artifacts.
Args:
input_array: An N-dim numpy array.
input_range: Specifies the input range as a `(min, max)` tuple to rescale the `input_array`.
Returns:
The rescaled `input_array`. | def deprocess_input(input_array, input_range=(0, 255)):
"""Utility function to scale the `input_array` to `input_range` throwing away high frequency artifacts.
Args:
input_array: An N-dim numpy array.
input_range: Specifies the input range as a `(min, max)` tuple to rescale the `input_array`.
... |
Utility function to stitch images together with a `margin`.
Args:
images: The array of 2D images to stitch.
margin: The black border margin size between images (Default value = 5)
cols: Max number of image cols. New row is created when number of images exceed the column size.
(D... | def stitch_images(images, margin=5, cols=5):
"""Utility function to stitch images together with a `margin`.
Args:
images: The array of 2D images to stitch.
margin: The black border margin size between images (Default value = 5)
cols: Max number of image cols. New row is created when num... |
Returns image shape in a backend agnostic manner.
Args:
img: An image tensor of shape: `(channels, image_dims...)` if data_format='channels_first' or
`(image_dims..., channels)` if data_format='channels_last'.
Returns:
Tuple containing image shape information in `(samples, channels... | def get_img_shape(img):
"""Returns image shape in a backend agnostic manner.
Args:
img: An image tensor of shape: `(channels, image_dims...)` if data_format='channels_first' or
`(image_dims..., channels)` if data_format='channels_last'.
Returns:
Tuple containing image shape inf... |
Utility function to load an image from disk.
Args:
path: The image file path.
grayscale: True to convert to grayscale image (Default value = False)
target_size: (w, h) to resize. (Default value = None)
Returns:
The loaded numpy image. | def load_img(path, grayscale=False, target_size=None):
"""Utility function to load an image from disk.
Args:
path: The image file path.
grayscale: True to convert to grayscale image (Default value = False)
target_size: (w, h) to resize. (Default value = None)
Returns:
The loaded ... |
Utility function to return the image net label for the final `dense` layer output index.
Args:
indices: Could be a single value or an array of indices whose labels should be looked up.
Returns:
Image net label corresponding to the image category. | def lookup_imagenet_labels(indices):
"""Utility function to return the image net label for the final `dense` layer output index.
Args:
indices: Could be a single value or an array of indices whose labels should be looked up.
Returns:
Image net label corresponding to the image category.
... |
Draws text over the image. Requires PIL.
Args:
img: The image to use.
text: The text string to overlay.
position: The text (x, y) position. (Default value = (10, 10))
font: The ttf or open type font to use. (Default value = 'FreeSans.ttf')
font_size: The text font size. (Def... | def draw_text(img, text, position=(10, 10), font='FreeSans.ttf', font_size=14, color=(0, 0, 0)):
"""Draws text over the image. Requires PIL.
Args:
img: The image to use.
text: The text string to overlay.
position: The text (x, y) position. (Default value = (10, 10))
font: The tt... |
Normalizes the numpy array to (min_value, max_value)
Args:
array: The numpy array
min_value: The min value in normalized array (Default value = 0)
max_value: The max value in normalized array (Default value = 1)
Returns:
The array normalized to range between (min_value, max_val... | def normalize(array, min_value=0., max_value=1.):
"""Normalizes the numpy array to (min_value, max_value)
Args:
array: The numpy array
min_value: The min value in normalized array (Default value = 0)
max_value: The max value in normalized array (Default value = 1)
Returns:
... |
Determines the number of filters within the given `layer`.
Args:
layer: The keras layer to use.
Returns:
Total number of filters within `layer`.
For `keras.layers.Dense` layer, this is the total number of outputs. | def get_num_filters(layer):
"""Determines the number of filters within the given `layer`.
Args:
layer: The keras layer to use.
Returns:
Total number of filters within `layer`.
For `keras.layers.Dense` layer, this is the total number of outputs.
"""
# Handle layers with no c... |
Overlays `array1` onto `array2` with `alpha` blending.
Args:
array1: The first numpy array.
array2: The second numpy array.
alpha: The alpha value of `array1` as overlayed onto `array2`. This value needs to be between [0, 1],
with 0 being `array2` only to 1 being `array1` only (... | def overlay(array1, array2, alpha=0.5):
"""Overlays `array1` onto `array2` with `alpha` blending.
Args:
array1: The first numpy array.
array2: The second numpy array.
alpha: The alpha value of `array1` as overlayed onto `array2`. This value needs to be between [0, 1],
with 0... |
All the logic for creating a new DataArray | def _infer_coords_and_dims(shape, coords, dims):
"""All the logic for creating a new DataArray"""
if (coords is not None and not utils.is_dict_like(coords) and
len(coords) != len(shape)):
raise ValueError('coords is not dict-like, but it has %s items, '
'which does ... |
Convert a DataArray to a Dataset.
Parameters
----------
dim : str, optional
Name of the dimension on this array along which to split this array
into separate variables. If not provided, this array is converted
into a Dataset of one variable.
name : st... | def to_dataset(self, dim=None, name=None):
"""Convert a DataArray to a Dataset.
Parameters
----------
dim : str, optional
Name of the dimension on this array along which to split this array
into separate variables. If not provided, this array is converted
... |
Return a mapping of all MultiIndex levels and their corresponding
coordinate name. | def _level_coords(self):
"""Return a mapping of all MultiIndex levels and their corresponding
coordinate name.
"""
level_coords = OrderedDict()
for cname, var in self._coords.items():
if var.ndim == 1 and isinstance(var, IndexVariable):
level_names = v... |
Mapping of pandas.Index objects used for label based indexing | def indexes(self):
"""Mapping of pandas.Index objects used for label based indexing
"""
if self._indexes is None:
self._indexes = default_indexes(self._coords, self.dims)
return Indexes(self._indexes) |
Given names of coordinates, reset them to become variables.
Parameters
----------
names : str or list of str, optional
Name(s) of non-index coordinates in this dataset to reset into
variables. By default, all non-index coordinates are reset.
drop : bool, optional... | def reset_coords(self, names=None, drop=False, inplace=None):
"""Given names of coordinates, reset them to become variables.
Parameters
----------
names : str or list of str, optional
Name(s) of non-index coordinates in this dataset to reset into
variables. By de... |
Trigger computation in constituent dask arrays
This keeps them as dask arrays but encourages them to keep data in
memory. This is particularly useful when on a distributed machine.
When on a single machine consider using ``.compute()`` instead.
Parameters
----------
**... | def persist(self, **kwargs):
""" Trigger computation in constituent dask arrays
This keeps them as dask arrays but encourages them to keep data in
memory. This is particularly useful when on a distributed machine.
When on a single machine consider using ``.compute()`` instead.
... |
Returns a copy of this array.
If `deep=True`, a deep copy is made of the data array.
Otherwise, a shallow copy is made, so each variable in the new
array's dataset is also a variable in this array's dataset.
Use `data` to create a new object with the same structure as
original ... | def copy(self, deep=True, data=None):
"""Returns a copy of this array.
If `deep=True`, a deep copy is made of the data array.
Otherwise, a shallow copy is made, so each variable in the new
array's dataset is also a variable in this array's dataset.
Use `data` to create a new ob... |
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_prefix='xarray-', token=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 chun... |
Return a new DataArray whose dataset is given by integer indexing
along the specified dimension(s).
See Also
--------
Dataset.isel
DataArray.sel | def isel(self, indexers=None, drop=False, **indexers_kwargs):
"""Return a new DataArray whose dataset is given by integer indexing
along the specified dimension(s).
See Also
--------
Dataset.isel
DataArray.sel
"""
indexers = either_dict_or_kwargs(indexers... |
Return a new DataArray whose dataset is given by selecting
index labels along the specified dimension(s).
.. warning::
Do not try to assign values when using any of the indexing methods
``isel`` or ``sel``::
da = xr.DataArray([0, 1, 2, 3], dims=['x'])
# DO ... | def sel(self, indexers=None, method=None, tolerance=None, drop=False,
**indexers_kwargs):
"""Return a new DataArray whose dataset is given by selecting
index labels along the specified dimension(s).
.. warning::
Do not try to assign values when using any of the indexing m... |
Return a new DataArray whose dataset is given by pointwise selection
of index labels along the specified dimension(s).
See Also
--------
Dataset.sel_points | def sel_points(self, dim='points', method=None, tolerance=None,
**indexers):
"""Return a new DataArray whose dataset is given by pointwise selection
of index labels along the specified dimension(s).
See Also
--------
Dataset.sel_points
"""
ds =... |
Return a new DataArray whose dataset is given by pointwise integer
indexing along the specified dimension(s).
See Also
--------
Dataset.isel_points | def isel_points(self, dim='points', **indexers):
"""Return a new DataArray whose dataset is given by pointwise integer
indexing along the specified dimension(s).
See Also
--------
Dataset.isel_points
"""
ds = self._to_temp_dataset().isel_points(dim=dim, **indexer... |
Conform this object onto a new set of indexes, filling in
missing values with NaN.
Parameters
----------
indexers : dict, optional
Dictionary with keys given by dimension names and values given by
arrays of coordinates tick labels. Any mis-matched coordinate
... | def reindex(self, indexers=None, method=None, tolerance=None, copy=True,
**indexers_kwargs):
"""Conform this object onto a new set of indexes, filling in
missing values with NaN.
Parameters
----------
indexers : dict, optional
Dictionary with keys giv... |
Multidimensional interpolation of variables.
coords : dict, optional
Mapping from dimension names to the new coordinates.
new coordinate can be an scalar, array-like or DataArray.
If DataArrays are passed as new coordates, their dimensions are
used for the broadc... | def interp(self, coords=None, method='linear', assume_sorted=False,
kwargs={}, **coords_kwargs):
""" Multidimensional interpolation of variables.
coords : dict, optional
Mapping from dimension names to the new coordinates.
new coordinate can be an scalar, array-li... |
Interpolate this object onto the coordinates of another object,
filling out of range values with NaN.
Parameters
----------
other : Dataset or DataArray
Object with an 'indexes' attribute giving a mapping from dimension
names to an 1d array-like, which provides c... | def interp_like(self, other, method='linear', assume_sorted=False,
kwargs={}):
"""Interpolate this object onto the coordinates of another object,
filling out of range values with NaN.
Parameters
----------
other : Dataset or DataArray
Object with ... |
Returns a new DataArray with renamed coordinates or a new name.
Parameters
----------
new_name_or_name_dict : str or dict-like, optional
If the argument is dict-like, it it used as a mapping from old
names to new names for coordinates. Otherwise, use the argument
... | def rename(self, new_name_or_name_dict=None, **names):
"""Returns a new DataArray with renamed coordinates or a new name.
Parameters
----------
new_name_or_name_dict : str or dict-like, optional
If the argument is dict-like, it it used as a mapping from old
names... |
Returns a new DataArray with swapped dimensions.
Parameters
----------
dims_dict : dict-like
Dictionary whose keys are current dimension names and whose values
are new names. Each value must already be a coordinate on this
array.
Returns
----... | def swap_dims(self, dims_dict):
"""Returns a new DataArray with swapped dimensions.
Parameters
----------
dims_dict : dict-like
Dictionary whose keys are current dimension names and whose values
are new names. Each value must already be a coordinate on this
... |
Return a new object with an additional axis (or axes) inserted at
the corresponding position in the array shape.
If dim is already a scalar coordinate, it will be promoted to a 1D
coordinate consisting of a single value.
Parameters
----------
dim : str, sequence of str,... | def expand_dims(self, dim=None, axis=None, **dim_kwargs):
"""Return a new object with an additional axis (or axes) inserted at
the corresponding position in the array shape.
If dim is already a scalar coordinate, it will be promoted to a 1D
coordinate consisting of a single value.
... |
Set DataArray (multi-)indexes using one or more existing
coordinates.
Parameters
----------
indexes : {dim: index, ...}
Mapping from names matching dimensions and values given
by (lists of) the names of existing coordinates or variables to set
as new ... | def set_index(self, indexes=None, append=False, inplace=None,
**indexes_kwargs):
"""Set DataArray (multi-)indexes using one or more existing
coordinates.
Parameters
----------
indexes : {dim: index, ...}
Mapping from names matching dimensions and va... |
Reset the specified index(es) or multi-index level(s).
Parameters
----------
dims_or_levels : str or list
Name(s) of the dimension(s) and/or multi-index level(s) that will
be reset.
drop : bool, optional
If True, remove the specified indexes and/or mu... | def reset_index(self, dims_or_levels, drop=False, inplace=None):
"""Reset the specified index(es) or multi-index level(s).
Parameters
----------
dims_or_levels : str or list
Name(s) of the dimension(s) and/or multi-index level(s) that will
be reset.
drop ... |
Rearrange index levels using input order.
Parameters
----------
dim_order : optional
Mapping from names matching dimensions and values given
by lists representing new level orders. Every given dimension
must have a multi-index.
inplace : bool, optiona... | def reorder_levels(self, dim_order=None, inplace=None,
**dim_order_kwargs):
"""Rearrange index levels using input order.
Parameters
----------
dim_order : optional
Mapping from names matching dimensions and values given
by lists representin... |
Stack any number of existing dimensions into a single new dimension.
New dimensions will be added at the end, and the corresponding
coordinate variables will be combined into a MultiIndex.
Parameters
----------
dimensions : Mapping of the 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 corresponding
coordinate variables will be combined into a MultiIndex.
Parameters
----------
... |
Unstack existing dimensions corresponding to MultiIndexes into
multiple new dimensions.
New dimensions will be added at the end.
Parameters
----------
dim : str or sequence of str, optional
Dimension(s) over which to unstack. By default unstacks all
Mult... | def unstack(self, dim=None):
"""
Unstack existing dimensions corresponding to MultiIndexes into
multiple new dimensions.
New dimensions will be added at the end.
Parameters
----------
dim : str or sequence of str, optional
Dimension(s) over which to ... |
Drop coordinates or index labels from this DataArray.
Parameters
----------
labels : scalar or list of scalars
Name(s) of coordinate variables or index labels to drop.
dim : str, optional
Dimension along which to drop index labels. By default (if
``di... | def drop(self, labels, dim=None):
"""Drop coordinates or index labels from this DataArray.
Parameters
----------
labels : scalar or list of scalars
Name(s) of coordinate variables or index labels to drop.
dim : str, optional
Dimension along which to drop ... |
Returns a new array with dropped labels for missing values along
the provided dimension.
Parameters
----------
dim : str
Dimension along which to drop missing values. Dropping along
multiple dimensions simultaneously is not yet supported.
how : {'any', 'a... | def dropna(self, dim, how='any', thresh=None):
"""Returns a new array with dropped labels for missing values along
the provided dimension.
Parameters
----------
dim : str
Dimension along which to drop missing values. Dropping along
multiple dimensions sim... |
Fill missing values in this object.
This operation follows the normal broadcasting and alignment rules that
xarray uses for binary arithmetic, except the result is aligned to this
object (``join='left'``) instead of aligned to the intersection of
index coordinates (``join='inner'``).
... | def fillna(self, value):
"""Fill missing values in this object.
This operation follows the normal broadcasting and alignment rules that
xarray uses for binary arithmetic, except the result is aligned to this
object (``join='left'``) instead of aligned to the intersection of
inde... |
Fill NaN values by propogating values forward
*Requires bottleneck.*
Parameters
----------
dim : str
Specifies the dimension along which to propagate values when
filling.
limit : int, default None
The maximum number of consecutive NaN values ... | def ffill(self, dim, limit=None):
'''Fill NaN values by propogating values forward
*Requires bottleneck.*
Parameters
----------
dim : str
Specifies the dimension along which to propagate values when
filling.
limit : int, default None
... |
Fill NaN values by propogating values backward
*Requires bottleneck.*
Parameters
----------
dim : str
Specifies the dimension along which to propagate values when
filling.
limit : int, default None
The maximum number of consecutive NaN values... | def bfill(self, dim, limit=None):
'''Fill NaN values by propogating values backward
*Requires bottleneck.*
Parameters
----------
dim : str
Specifies the dimension along which to propagate values when
filling.
limit : int, default None
... |
Reduce this array by applying `func` along some dimension(s).
Parameters
----------
func : function
Function which can be called in the form
`f(x, axis=axis, **kwargs)` to return the result of reducing an
np.ndarray over an integer valued axis.
dim : ... | def reduce(self, func, dim=None, axis=None, keep_attrs=None, **kwargs):
"""Reduce this array by applying `func` along some dimension(s).
Parameters
----------
func : function
Function which can be called in the form
`f(x, axis=axis, **kwargs)` to return the resul... |
Convert this array into a pandas object with the same shape.
The type of the returned object depends on the number of DataArray
dimensions:
* 1D -> `pandas.Series`
* 2D -> `pandas.DataFrame`
* 3D -> `pandas.Panel`
Only works for arrays with 3 or fewer dimensions.
... | def to_pandas(self):
"""Convert this array into a pandas object with the same shape.
The type of the returned object depends on the number of DataArray
dimensions:
* 1D -> `pandas.Series`
* 2D -> `pandas.DataFrame`
* 3D -> `pandas.Panel`
Only works for arrays w... |
Convert this array and its coordinates into a tidy pandas.DataFrame.
The DataFrame is indexed by the Cartesian product of index coordinates
(in the form of a :py:class:`pandas.MultiIndex`).
Other coordinates are included as columns in the DataFrame. | def to_dataframe(self, name=None):
"""Convert this array and its coordinates into a tidy pandas.DataFrame.
The DataFrame is indexed by the Cartesian product of index coordinates
(in the form of a :py:class:`pandas.MultiIndex`).
Other coordinates are included as columns in the DataFrame... |
Convert this array into a pandas.Series.
The Series is indexed by the Cartesian product of index coordinates
(in the form of a :py:class:`pandas.MultiIndex`). | def to_series(self):
"""Convert this array into a pandas.Series.
The Series is indexed by the Cartesian product of index coordinates
(in the form of a :py:class:`pandas.MultiIndex`).
"""
index = self.coords.to_index()
return pd.Series(self.values.reshape(-1), index=index... |
Convert this array into a numpy.ma.MaskedArray
Parameters
----------
copy : bool
If True (default) make a copy of the array in the result. If False,
a MaskedArray view of DataArray.values is returned.
Returns
-------
result : MaskedArray
... | def to_masked_array(self, copy=True):
"""Convert this array into a numpy.ma.MaskedArray
Parameters
----------
copy : bool
If True (default) make a copy of the array in the result. If False,
a MaskedArray view of DataArray.values is returned.
Returns
... |
Write DataArray contents to a netCDF file.
Parameters
----------
path : str or Path, optional
Path to which to save this dataset. If no path is provided, this
function returns the resulting netCDF file as a bytes object; in
this case, we need to use scipy.io.... | def to_netcdf(self, *args, **kwargs):
"""Write DataArray contents to a netCDF file.
Parameters
----------
path : str or Path, optional
Path to which to save this dataset. If no path is provided, this
function returns the resulting netCDF file as a bytes object; i... |
Convert this xarray.DataArray into 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 xarray.DataArray into 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 k... |
Convert a dictionary into an xarray.DataArray
Input dict can take several forms::
d = {'dims': ('t'), 'data': x}
d = {'coords': {'t': {'dims': 't', 'data': t,
'attrs': {'units':'s'}}},
'attrs': {'title': 'air temperature'},
... | def from_dict(cls, d):
"""
Convert a dictionary into an xarray.DataArray
Input dict can take several forms::
d = {'dims': ('t'), 'data': x}
d = {'coords': {'t': {'dims': 't', 'data': t,
'attrs': {'units':'s'}}},
'attrs... |
Convert a pandas.Series into an xarray.DataArray.
If the series's index is a MultiIndex, it will be expanded into a
tensor product of one-dimensional coordinates (filling in missing
values with NaN). Thus this operation should be the inverse of the
`to_series` method. | def from_series(cls, series):
"""Convert a pandas.Series into an xarray.DataArray.
If the series's index is a MultiIndex, it will be expanded into a
tensor product of one-dimensional coordinates (filling in missing
values with NaN). Thus this operation should be the inverse of the
... |
Helper function for equals and identical | def _all_compat(self, other, compat_str):
"""Helper function for equals and identical"""
def compat(x, y):
return getattr(x.variable, compat_str)(y.variable)
return (utils.dict_equiv(self.coords, other.coords, compat=compat) and
compat(self, other)) |
Like equals, but also checks the array name and attributes, and
attributes on all coordinates.
See Also
--------
DataArray.broadcast_equals
DataArray.equal | def identical(self, other):
"""Like equals, but also checks the array name and attributes, and
attributes on all coordinates.
See Also
--------
DataArray.broadcast_equals
DataArray.equal
"""
try:
return (self.name == other.name and
... |
If the dataarray has 1 dimensional coordinates or comes from a slice
we can show that info in the title
Parameters
----------
truncate : integer
maximum number of characters for title
Returns
-------
title : string
Can be used for plot ti... | def _title_for_slice(self, truncate=50):
"""
If the dataarray has 1 dimensional coordinates or comes from a slice
we can show that info in the title
Parameters
----------
truncate : integer
maximum number of characters for title
Returns
-----... |
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 array by an offset along one or more dimensions.
Only the data is moved; coordinates stay in place. Values shifted from
beyond array bounds are replaced by NaN. This is consistent with the
behavior of ``shift`` in pandas.
Parameters
----------
shifts : Mappin... | def shift(self, shifts=None, fill_value=dtypes.NA, **shifts_kwargs):
"""Shift this array by an offset along one or more dimensions.
Only the data is moved; coordinates stay in place. Values shifted from
beyond array bounds are replaced by NaN. This is consistent with the
behavior of ``s... |
Roll this array 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
----------
roll_coords : bool
Indicates... | def roll(self, shifts=None, roll_coords=None, **shifts_kwargs):
"""Roll this array 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`.
Par... |
Perform dot product of two DataArrays along their shared dims.
Equivalent to taking taking tensordot over all shared dims.
Parameters
----------
other : DataArray
The other array with which the dot product is performed.
dims: list of strings, optional
Al... | def dot(self, other, dims=None):
"""Perform dot product of two DataArrays along their shared dims.
Equivalent to taking taking tensordot over all shared dims.
Parameters
----------
other : DataArray
The other array with which the dot product is performed.
di... |
Sort object by labels or values (along an axis).
Sorts the dataarray, 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 ... | def sortby(self, variables, ascending=True):
"""
Sort object by labels or values (along an axis).
Sorts the dataarray, either along specified dimensions,
or according to values of 1-D dataarrays that share dimension
with calling object.
If the input variables are dataar... |
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.
dim : str ... | def quantile(self, q, dim=None, interpolation='linear', keep_attrs=None):
"""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)
... |
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 `bottl... | 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, computes percentage ranks.
NaNs ... |
Differentiate the array 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 comp... | def differentiate(self, coord, edge_order=1, datetime_unit=None):
""" Differentiate the array 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, dim, 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
... |
Convert this rolling object to xr.DataArray,
where the window dimension is stacked as a new dimension
Parameters
----------
window_dim: str
New name of the window dimension.
stride: integer, optional
Size of stride for the rolling window.
fill_val... | def construct(self, window_dim, stride=1, fill_value=dtypes.NA):
"""
Convert this rolling object to xr.DataArray,
where the window dimension is stacked as a new dimension
Parameters
----------
window_dim: str
New name of the window dimension.
stride: ... |
Reduce the items in this group by applying `func` along some
dimension(s).
Parameters
----------
func : function
Function which can be called in the form
`func(x, **kwargs)` to return the result of collapsing an
np.ndarray over an the rolling dimensio... | def reduce(self, func, **kwargs):
"""Reduce the items in this group by applying `func` along some
dimension(s).
Parameters
----------
func : function
Function which can be called in the form
`func(x, **kwargs)` to return the result of collapsing an
... |
Number of non-nan entries in each rolling window. | def _counts(self):
""" Number of non-nan entries in each rolling window. """
rolling_dim = utils.get_temp_dimname(self.obj.dims, '_rolling_dim')
# We use False as the fill_value instead of np.nan, since boolean
# array is faster to be reduced than object array.
# The use of skip... |
Methods to return a wrapped function for any function `func` for
numpy methods. | def _reduce_method(cls, func):
"""
Methods to return a wrapped function for any function `func` for
numpy methods.
"""
def wrapped_func(self, **kwargs):
return self.reduce(func, **kwargs)
return wrapped_func |
Methods to return a wrapped function for any function `func` for
bottoleneck method, except for `median`. | def _bottleneck_reduce(cls, func):
"""
Methods to return a wrapped function for any function `func` for
bottoleneck method, except for `median`.
"""
def wrapped_func(self, **kwargs):
from .dataarray import DataArray
# bottleneck doesn't allow min_count t... |
Reduce the items in this group by applying `func` along some
dimension(s).
Parameters
----------
func : function
Function which can be called in the form
`func(x, **kwargs)` to return the result of collapsing an
np.ndarray over an the rolling dimensio... | def reduce(self, func, **kwargs):
"""Reduce the items in this group by applying `func` along some
dimension(s).
Parameters
----------
func : function
Function which can be called in the form
`func(x, **kwargs)` to return the result of collapsing an
... |
Return a wrapped function for injecting numpy and bottoleneck methods.
see ops.inject_datasetrolling_methods | def _reduce_method(cls, func):
"""
Return a wrapped function for injecting numpy and bottoleneck methods.
see ops.inject_datasetrolling_methods
"""
def wrapped_func(self, **kwargs):
from .dataset import Dataset
reduced = OrderedDict()
for key,... |
Return a wrapped function for injecting numpy methods.
see ops.inject_coarsen_methods | def _reduce_method(cls, func):
"""
Return a wrapped function for injecting numpy methods.
see ops.inject_coarsen_methods
"""
def wrapped_func(self, **kwargs):
from .dataarray import DataArray
reduced = self.obj.variable.coarsen(
self.windo... |
Convert this rolling object to xr.Dataset,
where the window dimension is stacked as a new dimension
Parameters
----------
window_dim: str
New name of the window dimension.
stride: integer, optional
size of stride for the rolling window.
fill_value... | def construct(self, window_dim, stride=1, fill_value=dtypes.NA):
"""
Convert this rolling object to xr.Dataset,
where the window dimension is stacked as a new dimension
Parameters
----------
window_dim: str
New name of the window dimension.
stride: in... |
Return a wrapped function for injecting numpy methods.
see ops.inject_coarsen_methods | def _reduce_method(cls, func):
"""
Return a wrapped function for injecting numpy methods.
see ops.inject_coarsen_methods
"""
def wrapped_func(self, **kwargs):
from .dataset import Dataset
reduced = OrderedDict()
for key, da in self.obj.data_va... |
Ensure that a variable with vlen bytes is converted to fixed width. | def ensure_fixed_length_bytes(var):
"""Ensure that a variable with vlen bytes is converted to fixed width."""
dims, data, attrs, encoding = unpack_for_encoding(var)
if check_vlen_dtype(data.dtype) == bytes:
# TODO: figure out how to handle this with dask
data = np.asarray(data, dtype=np.stri... |
Convert numpy/dask arrays from fixed width bytes to characters. | def bytes_to_char(arr):
"""Convert numpy/dask arrays from fixed width bytes to characters."""
if arr.dtype.kind != 'S':
raise ValueError('argument must have a fixed-width bytes dtype')
if isinstance(arr, dask_array_type):
import dask.array as da
return da.map_blocks(_numpy_bytes_to_... |
Like netCDF4.stringtochar, but faster and more flexible. | def _numpy_bytes_to_char(arr):
"""Like netCDF4.stringtochar, but faster and more flexible.
"""
# ensure the array is contiguous
arr = np.array(arr, copy=False, order='C', dtype=np.string_)
return arr.reshape(arr.shape + (1,)).view('S1') |
Convert numpy/dask arrays from characters to fixed width bytes. | def char_to_bytes(arr):
"""Convert numpy/dask arrays from characters to fixed width bytes."""
if arr.dtype != 'S1':
raise ValueError("argument must have dtype='S1'")
if not arr.ndim:
# no dimension to concatenate along
return arr
size = arr.shape[-1]
if not size:
#... |
Like netCDF4.chartostring, but faster and more flexible. | def _numpy_char_to_bytes(arr):
"""Like netCDF4.chartostring, but faster and more flexible.
"""
# based on: http://stackoverflow.com/a/10984878/809705
arr = np.array(arr, copy=False, order='C')
dtype = 'S' + str(arr.shape[-1])
return arr.view(dtype).reshape(arr.shape[:-1]) |
Given an array, safely cast it to a pandas.Index.
If it is already a pandas.Index, return it unchanged.
Unlike pandas.Index, if the array has dtype=object or dtype=timedelta64,
this function will not attempt to do automatic type conversion but will
always return an index with dtype=object. | def safe_cast_to_index(array: Any) -> pd.Index:
"""Given an array, safely cast it to a pandas.Index.
If it is already a pandas.Index, return it unchanged.
Unlike pandas.Index, if the array has dtype=object or dtype=timedelta64,
this function will not attempt to do automatic type conversion but will
... |
Creating a MultiIndex from a product without refactorizing levels.
Keeping levels the same gives back the original labels when we unstack.
Parameters
----------
levels : sequence of pd.Index
Values for each MultiIndex level.
names : optional sequence of objects
Names for each level... | def multiindex_from_product_levels(levels: Sequence[pd.Index],
names: Optional[Sequence[str]] = None
) -> pd.MultiIndex:
"""Creating a MultiIndex from a product without refactorizing levels.
Keeping levels the same gives back the original la... |
Wrap a transformed array with __array_wrap__ is it can be done safely.
This lets us treat arbitrary functions that take and return ndarray objects
like ufuncs, as long as they return an array with the same shape. | def maybe_wrap_array(original, new_array):
"""Wrap a transformed array with __array_wrap__ is it can be done safely.
This lets us treat arbitrary functions that take and return ndarray objects
like ufuncs, as long as they return an array with the same shape.
"""
# in case func lost array's metadata... |
Compare two objects for equivalence (identity or equality), using
array_equiv if either object is an ndarray | def equivalent(first: T, second: T) -> bool:
"""Compare two objects for equivalence (identity or equality), using
array_equiv if either object is an ndarray
"""
# TODO: refactor to avoid circular import
from . import duck_array_ops
if isinstance(first, np.ndarray) or isinstance(second, np.ndarra... |
Returns the first value from iterable, as well as a new iterator with
the same content as the original iterable | def peek_at(iterable: Iterable[T]) -> Tuple[T, Iterator[T]]:
"""Returns the first value from iterable, as well as a new iterator with
the same content as the original iterable
"""
gen = iter(iterable)
peek = next(gen)
return peek, itertools.chain([peek], gen) |
Check the safety of updating one dictionary with another.
Raises ValueError if dictionaries have non-compatible values for any key,
where compatibility is determined by identity (they are the same item) or
the `compat` function.
Parameters
----------
first_dict, second_dict : dict-like
... | def update_safety_check(first_dict: MutableMapping[K, V],
second_dict: Mapping[K, V],
compat: Callable[[V, V], bool] = equivalent) -> None:
"""Check the safety of updating one dictionary with another.
Raises ValueError if dictionaries have non-compatible values f... |
Remove incompatible items from the first dictionary in-place.
Items are retained if their keys are found in both dictionaries and the
values are compatible.
Parameters
----------
first_dict, second_dict : dict-like
Mappings to merge.
compat : function, optional
Binary operator ... | def remove_incompatible_items(first_dict: MutableMapping[K, V],
second_dict: Mapping[K, V],
compat: Callable[[V, V], bool] = equivalent
) -> None:
"""Remove incompatible items from the first dictionary in-place.
Items are... |
Whether to treat a value as a scalar.
Any non-iterable, string, or 0-D array | def is_scalar(value: Any) -> bool:
"""Whether to treat a value as a scalar.
Any non-iterable, string, or 0-D array
"""
return (
getattr(value, 'ndim', None) == 0 or
isinstance(value, (str, bytes)) or not
isinstance(value, (Iterable, ) + dask_array_type)) |
Given a value, wrap it in a 0-D numpy.ndarray with dtype=object. | def to_0d_object_array(value: Any) -> np.ndarray:
"""Given a value, wrap it in a 0-D numpy.ndarray with dtype=object.
"""
result = np.empty((), dtype=object)
result[()] = value
return result |
Given a value, wrap it in a 0-D numpy.ndarray. | def to_0d_array(value: Any) -> np.ndarray:
"""Given a value, wrap it in a 0-D numpy.ndarray.
"""
if np.isscalar(value) or (isinstance(value, np.ndarray) and
value.ndim == 0):
return np.array(value)
else:
return to_0d_object_array(value) |
Test equivalence of two dict-like objects. If any of the values are
numpy arrays, compare them correctly.
Parameters
----------
first, second : dict-like
Dictionaries to compare for equality
compat : function, optional
Binary operator to determine if two values are compatible. By de... | def dict_equiv(first: Mapping[K, V], second: Mapping[K, V],
compat: Callable[[V, V], bool] = equivalent) -> bool:
"""Test equivalence of two dict-like objects. If any of the values are
numpy arrays, compare them correctly.
Parameters
----------
first, second : dict-like
Dicti... |
Return the intersection of two dictionaries as a new OrderedDict.
Items are retained if their keys are found in both dictionaries and the
values are compatible.
Parameters
----------
first_dict, second_dict : dict-like
Mappings to merge.
compat : function, optional
Binary opera... | def ordered_dict_intersection(first_dict: Mapping[K, V],
second_dict: Mapping[K, V],
compat: Callable[[V, V], bool] = equivalent
) -> MutableMapping[K, V]:
"""Return the intersection of two dictionaries as a new OrderedDict.
... |
Return True if values of an array are uniformly spaced and sorted.
>>> is_uniform_spaced(range(5))
True
>>> is_uniform_spaced([-4, 0, 100])
False
kwargs are additional arguments to ``np.isclose`` | def is_uniform_spaced(arr, **kwargs) -> bool:
"""Return True if values of an array are uniformly spaced and sorted.
>>> is_uniform_spaced(range(5))
True
>>> is_uniform_spaced([-4, 0, 100])
False
kwargs are additional arguments to ``np.isclose``
"""
arr = np.array(arr, dtype=float)
... |
Convert attribute values from numpy objects to native Python objects,
for use in to_dict | def decode_numpy_dict_values(attrs: Mapping[K, V]) -> Dict[K, V]:
"""Convert attribute values from numpy objects to native Python objects,
for use in to_dict
"""
attrs = dict(attrs)
for k, v in attrs.items():
if isinstance(v, np.ndarray):
attrs[k] = v.tolist()
elif isinst... |
Convert val out of numpy time, for use in to_dict.
Needed because of numpy bug GH#7619 | def ensure_us_time_resolution(val):
"""Convert val out of numpy time, for use in to_dict.
Needed because of numpy bug GH#7619"""
if np.issubdtype(val.dtype, np.datetime64):
val = val.astype('datetime64[us]')
elif np.issubdtype(val.dtype, np.timedelta64):
val = val.astype('timedelta64[us]... |
Get an new dimension name based on new_dim, that is not used in dims.
If the same name exists, we add an underscore(s) in the head.
Example1:
dims: ['a', 'b', 'c']
new_dim: ['_rolling']
-> ['_rolling']
Example2:
dims: ['a', 'b', 'c', '_rolling']
new_dim: ['_rolling']... | def get_temp_dimname(dims: Container[Hashable], new_dim: Hashable) -> Hashable:
""" Get an new dimension name based on new_dim, that is not used in dims.
If the same name exists, we add an underscore(s) in the head.
Example1:
dims: ['a', 'b', 'c']
new_dim: ['_rolling']
-> ['_rolling... |
Given an object array with no missing values, infer its dtype from its
first element | def _infer_dtype(array, name=None):
"""Given an object array with no missing values, infer its dtype from its
first element
"""
if array.dtype.kind != 'O':
raise TypeError('infer_type must be called on a dtype=object array')
if array.size == 0:
return np.dtype(float)
element = ... |
Create a copy of an array with the given dtype.
We use this instead of np.array() to ensure that custom object dtypes end
up on the resulting array. | def _copy_with_dtype(data, dtype):
"""Create a copy of an array with the given dtype.
We use this instead of np.array() to ensure that custom object dtypes end
up on the resulting array.
"""
result = np.empty(data.shape, dtype)
result[...] = data
return result |
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_cf_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 to... |
Decodes a variable which may hold CF encoded information.
This includes variables that have been masked and scaled, which
hold CF style time variables (this is almost always the case if
the dataset has been serialized) and which have strings encoded
as character arrays.
Parameters
----------
... | def decode_cf_variable(name, var, concat_characters=True, mask_and_scale=True,
decode_times=True, decode_endianness=True,
stack_char_dim=True, use_cftime=None):
"""
Decodes a variable which may hold CF encoded information.
This includes variables that have been... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.