INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Iterate over each element in this group
def _iter_grouped(self): """Iterate over each element in this group""" for indices in self._group_indices: yield self._obj.isel(**{self._group_dim: indices})
Our index contained empty groups (e.g., from a resampling). If we reduced on that dimension, we want to restore the full index.
def _maybe_restore_empty_groups(self, combined): """Our index contained empty groups (e.g., from a resampling). If we reduced on that dimension, we want to restore the full index. """ if (self._full_index is not None and self._group.name in combined.dims): ind...
This gets called if we are applying on an array with a multidimensional group.
def _maybe_unstack(self, obj): """This gets called if we are applying on an array with a multidimensional group.""" if self._stacked_dim is not None and self._stacked_dim in obj.dims: obj = obj.unstack(self._stacked_dim) for dim in self._inserted_dims: if ...
Return the first element of each group along the group dimension
def first(self, skipna=None, keep_attrs=None): """Return the first element of each group along the group dimension """ return self._first_or_last(duck_array_ops.first, skipna, keep_attrs)
Return the last element of each group along the group dimension
def last(self, skipna=None, keep_attrs=None): """Return the last element of each group along the group dimension """ return self._first_or_last(duck_array_ops.last, skipna, keep_attrs)
Fast version of `_iter_grouped` that yields Variables without metadata
def _iter_grouped_shortcut(self): """Fast version of `_iter_grouped` that yields Variables without metadata """ var = self._obj.variable for indices in self._group_indices: yield var[{self._group_dim: indices}]
Apply a function over each array in the group and concatenate them together into a new array. `func` is called like `func(ar, *args, **kwargs)` for each array `ar` in this group. Apply uses heuristics (like `pandas.GroupBy.apply`) to figure out how to stack together the array. ...
def apply(self, func, shortcut=False, args=(), **kwargs): """Apply a function over each array in the group and concatenate them together into a new array. `func` is called like `func(ar, *args, **kwargs)` for each array `ar` in this group. Apply uses heuristics (like `pandas.Gr...
Recombine the applied objects like the original.
def _combine(self, applied, shortcut=False): """Recombine the applied objects like the original.""" applied_example, applied = peek_at(applied) coord, dim, positions = self._infer_concat_args(applied_example) if shortcut: combined = self._concat_shortcut(applied, dim, positio...
Apply a function over each Dataset in the group and concatenate them together into a new Dataset. `func` is called like `func(ds, *args, **kwargs)` for each dataset `ds` in this group. Apply uses heuristics (like `pandas.GroupBy.apply`) to figure out how to stack together the d...
def apply(self, func, args=(), **kwargs): """Apply a function over each Dataset in the group and concatenate them together into a new Dataset. `func` is called like `func(ds, *args, **kwargs)` for each dataset `ds` in this group. Apply uses heuristics (like `pandas.GroupBy.appl...
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, axis=axis, **kwargs)` to return the result of collapsing an np.ndarray over an integer v...
def reduce(self, func, dim=None, axis=None, keep_attrs=None, shortcut=True, **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 ...
Recombine the applied objects like the original.
def _combine(self, applied): """Recombine the applied objects like the original.""" applied_example, applied = peek_at(applied) coord, dim, positions = self._infer_concat_args(applied_example) combined = concat(applied, dim) combined = _maybe_reorder(combined, dim, positions) ...
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, axis=axis, **kwargs)` to return the result of collapsing an np.ndarray over an integer v...
def reduce(self, func, dim=None, keep_attrs=None, **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, axis=axis, **kwargs)` to ret...
Return attrs that are not in ignored_attrs
def _filter_attrs(attrs, ignored_attrs): """ Return attrs that are not in ignored_attrs """ return dict((k, v) for k, v in attrs.items() if k not in ignored_attrs)
Convert a cdms2 variable into an DataArray
def from_cdms2(variable): """Convert a cdms2 variable into an DataArray """ values = np.asarray(variable) name = variable.id dims = variable.getAxisIds() coords = {} for axis in variable.getAxisList(): coords[axis.id] = DataArray( np.asarray(axis), dims=[axis.id], ...
Convert a DataArray into a cdms2 variable
def to_cdms2(dataarray, copy=True): """Convert a DataArray into a cdms2 variable """ # we don't want cdms2 to be a hard dependency import cdms2 def set_cdms2_attrs(var, attrs): for k, v in attrs.items(): setattr(var, k, v) # 1D axes axes = [] for dim in dataarray.di...
Return attrs with keys in keys list
def _pick_attrs(attrs, keys): """ Return attrs with keys in keys list """ return dict((k, v) for k, v in attrs.items() if k in keys)
Converts the xarray attrs into args that can be passed into Iris
def _get_iris_args(attrs): """ Converts the xarray attrs into args that can be passed into Iris """ # iris.unit is deprecated in Iris v1.9 import cf_units args = {'attributes': _filter_attrs(attrs, iris_forbidden_keys)} args.update(_pick_attrs(attrs, ('standard_name', 'long_name',))) unit_ar...
Convert a DataArray into a Iris Cube
def to_iris(dataarray): """ Convert a DataArray into a Iris Cube """ # Iris not a hard dependency import iris from iris.fileformats.netcdf import parse_cell_methods dim_coords = [] aux_coords = [] for coord_name in dataarray.coords: coord = encode(dataarray.coords[coord_name]) ...
Return a dictionary of attrs when given a Iris object
def _iris_obj_to_attrs(obj): """ Return a dictionary of attrs when given a Iris object """ attrs = {'standard_name': obj.standard_name, 'long_name': obj.long_name} if obj.units.calendar: attrs['calendar'] = obj.units.calendar if obj.units.origin != '1' and not obj.units.is_unkno...
Converts a Iris cell methods into a string
def _iris_cell_methods_to_str(cell_methods_obj): """ Converts a Iris cell methods into a string """ cell_methods = [] for cell_method in cell_methods_obj: names = ''.join(['{}: '.format(n) for n in cell_method.coord_names]) intervals = ' '.join(['interval: {}'.format(interval) ...
Convert a Iris cube into an DataArray
def from_iris(cube): """ Convert a Iris cube into an DataArray """ import iris.exceptions from xarray.core.pycompat import dask_array_type name = _name(cube) if name == 'unknown': name = None dims = [] for i in range(cube.ndim): try: dim_coord = cube.coord(di...
Mimicks `iris_obj.name()` but with different name resolution order. Similar to iris_obj.name() method, but using iris_obj.var_name first to enable roundtripping.
def _name(iris_obj, default='unknown'): """ Mimicks `iris_obj.name()` but with different name resolution order. Similar to iris_obj.name() method, but using iris_obj.var_name first to enable roundtripping. """ return (iris_obj.var_name or iris_obj.standard_name or iris_obj.long_name or ...
Given an array of numeric dates in netCDF format, convert it into a numpy array of date time objects. For standard (Gregorian) calendars, this function uses vectorized operations, which makes it much faster than cftime.num2date. In such a case, the returned array will be of type np.datetime64. Not...
def decode_cf_datetime(num_dates, units, calendar=None, use_cftime=None): """Given an array of numeric dates in netCDF format, convert it into a numpy array of date time objects. For standard (Gregorian) calendars, this function uses vectorized operations, which makes it much faster than cftime.num2dat...
Given an array of numeric timedeltas in netCDF format, convert it into a numpy timedelta64[ns] array.
def decode_cf_timedelta(num_timedeltas, units): """Given an array of numeric timedeltas in netCDF format, convert it into a numpy timedelta64[ns] array. """ num_timedeltas = np.asarray(num_timedeltas) units = _netcdf_to_numpy_timeunit(units) shape = num_timedeltas.shape num_timedeltas = num...
Given an array of datetimes, infer the CF calendar name
def infer_calendar_name(dates): """Given an array of datetimes, infer the CF calendar name""" if np.asarray(dates).dtype == 'datetime64[ns]': return 'proleptic_gregorian' else: return np.asarray(dates).ravel()[0].calendar
Given an array of datetimes, returns a CF compatible time-unit string of the form "{time_unit} since {date[0]}", where `time_unit` is 'days', 'hours', 'minutes' or 'seconds' (the first one that can evenly divide all unique time deltas in `dates`)
def infer_datetime_units(dates): """Given an array of datetimes, returns a CF compatible time-unit string of the form "{time_unit} since {date[0]}", where `time_unit` is 'days', 'hours', 'minutes' or 'seconds' (the first one that can evenly divide all unique time deltas in `dates`) """ dates = n...
Converts a cftime.datetime object to a string with the format: YYYY-MM-DD HH:MM:SS.UUUUUU
def format_cftime_datetime(date): """Converts a cftime.datetime object to a string with the format: YYYY-MM-DD HH:MM:SS.UUUUUU """ return '{:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}.{:06d}'.format( date.year, date.month, date.day, date.hour, date.minute, date.second, date.microsecond)
Given an array of timedeltas, returns a CF compatible time-unit from {'days', 'hours', 'minutes' 'seconds'} (the first one that can evenly divide all unique time deltas in `deltas`)
def infer_timedelta_units(deltas): """Given an array of timedeltas, returns a CF compatible time-unit from {'days', 'hours', 'minutes' 'seconds'} (the first one that can evenly divide all unique time deltas in `deltas`) """ deltas = pd.to_timedelta(np.asarray(deltas).ravel(), box=False) unique_t...
Given an array of cftime.datetime objects, return an array of numpy.datetime64 objects of the same size
def cftime_to_nptime(times): """Given an array of cftime.datetime objects, return an array of numpy.datetime64 objects of the same size""" times = np.asarray(times) new = np.empty(times.shape, dtype='M8[ns]') for i, t in np.ndenumerate(times): try: # Use pandas.Timestamp in place...
Fallback method for encoding dates using cftime. This method is more flexible than xarray's parsing using datetime64[ns] arrays but also slower because it loops over each element.
def _encode_datetime_with_cftime(dates, units, calendar): """Fallback method for encoding dates using cftime. This method is more flexible than xarray's parsing using datetime64[ns] arrays but also slower because it loops over each element. """ cftime = _import_cftime() if np.issubdtype(dates....
Given an array of datetime objects, returns the tuple `(num, units, calendar)` suitable for a CF compliant time variable. Unlike `date2num`, this function can handle datetime64 arrays. See also -------- cftime.date2num
def encode_cf_datetime(dates, units=None, calendar=None): """Given an array of datetime objects, returns the tuple `(num, units, calendar)` suitable for a CF compliant time variable. Unlike `date2num`, this function can handle datetime64 arrays. See also -------- cftime.date2num """ da...
DataArray.name and Dataset keys must be a string or None
def _validate_dataset_names(dataset): """DataArray.name and Dataset keys must be a string or None""" def check_name(name): if isinstance(name, str): if not name: raise ValueError('Invalid name for DataArray or Dataset key: ' 'string must be le...
`attrs` must have a string key and a value which is either: a number, a string, an ndarray or a list/tuple of numbers/strings.
def _validate_attrs(dataset): """`attrs` must have a string key and a value which is either: a number, a string, an ndarray or a list/tuple of numbers/strings. """ def check_attr(name, value): if isinstance(name, str): if not name: raise ValueError('Invalid name for a...
Load and decode a dataset from a file or file-like object. Parameters ---------- filename_or_obj : str, Path, file or xarray.backends.*DataStore Strings and Path objects are interpreted as a path to a netCDF file or an OpenDAP URL and opened with python-netCDF4, unless the filename ...
def open_dataset(filename_or_obj, group=None, decode_cf=True, mask_and_scale=None, decode_times=True, autoclose=None, concat_characters=True, decode_coords=True, engine=None, chunks=None, lock=None, cache=None, drop_variables=None, backend_kwargs=None,...
Open an DataArray from a netCDF file containing a single data variable. This is designed to read netCDF files with only one data variable. If multiple variables are present then a ValueError is raised. Parameters ---------- filename_or_obj : str, Path, file or xarray.backends.*DataStore St...
def open_dataarray(filename_or_obj, group=None, decode_cf=True, mask_and_scale=None, decode_times=True, autoclose=None, concat_characters=True, decode_coords=True, engine=None, chunks=None, lock=None, cache=None, drop_variables=None, backend_kw...
Open multiple files as a single dataset. Requires dask to be installed. See documentation for details on dask [1]. Attributes from the first dataset file are used for the combined dataset. Parameters ---------- paths : str or sequence Either a string glob in the form "path/to/my/files/*.nc...
def open_mfdataset(paths, chunks=None, concat_dim=_CONCAT_DIM_DEFAULT, compat='no_conflicts', preprocess=None, engine=None, lock=None, data_vars='all', coords='different', autoclose=None, parallel=False, **kwargs): """Open multiple files as a single dataset. ...
This function creates an appropriate datastore for writing a dataset to disk as a netCDF file See `Dataset.to_netcdf` for full API docs. The ``multifile`` argument is only for the private use of save_mfdataset.
def to_netcdf(dataset, path_or_file=None, mode='w', format=None, group=None, engine=None, encoding=None, unlimited_dims=None, compute=True, multifile=False): """This function creates an appropriate datastore for writing a dataset to disk as a netCDF file See `Dataset.to_netcdf` ...
Store dataset contents to a backends.*DataStore object.
def dump_to_store(dataset, store, writer=None, encoder=None, encoding=None, unlimited_dims=None): """Store dataset contents to a backends.*DataStore object.""" if writer is None: writer = ArrayWriter() if encoding is None: encoding = {} variables, attrs = conventions....
Write multiple datasets to disk as netCDF files simultaneously. This function is intended for use with datasets consisting of dask.array objects, in which case it can write the multiple datasets to disk simultaneously using a shared thread pool. When not using dask, it is no different than calling ``t...
def save_mfdataset(datasets, paths, mode='w', format=None, groups=None, engine=None, compute=True): """Write multiple datasets to disk as netCDF files simultaneously. This function is intended for use with datasets consisting of dask.array objects, in which case it can write the multiple...
This function creates an appropriate datastore for writing a dataset to a zarr ztore See `Dataset.to_zarr` for full API docs.
def to_zarr(dataset, store=None, mode='w-', synchronizer=None, group=None, encoding=None, compute=True, consolidated=False): """This function creates an appropriate datastore for writing a dataset to a zarr ztore See `Dataset.to_zarr` for full API docs. """ if isinstance(store, Path): ...
create a new MultiIndex from the current that removing unused levels, meaning that they are not expressed in the labels The resulting MultiIndex will have the same outward appearance, meaning the same .values and ordering. It will also be .equals() to the original. .. versionadded:: 0.20.0 Retur...
def remove_unused_levels(self): """ create a new MultiIndex from the current that removing unused levels, meaning that they are not expressed in the labels The resulting MultiIndex will have the same outward appearance, meaning the same .values and ordering. It will also be .equals() to the orig...
Robustly index an array, using retry logic with exponential backoff if any of the errors ``catch`` are raised. The initial_delay is measured in ms. With the default settings, the maximum delay will be in the range of 32-64 seconds.
def robust_getitem(array, key, catch=Exception, max_retries=6, initial_delay=500): """ Robustly index an array, using retry logic with exponential backoff if any of the errors ``catch`` are raised. The initial_delay is measured in ms. With the default settings, the maximum delay will...
This loads the variables and attributes simultaneously. A centralized loading function makes it easier to create data stores that do automatic encoding/decoding. For example:: class SuffixAppendingDataStore(AbstractDataStore): def load(self): va...
def load(self): """ This loads the variables and attributes simultaneously. A centralized loading function makes it easier to create data stores that do automatic encoding/decoding. For example:: class SuffixAppendingDataStore(AbstractDataStore): de...
Encode the variables and attributes in this store Parameters ---------- variables : dict-like Dictionary of key/value (variable name / xr.Variable) pairs attributes : dict-like Dictionary of key/value (attribute name / attribute) pairs Returns --...
def encode(self, variables, attributes): """ Encode the variables and attributes in this store Parameters ---------- variables : dict-like Dictionary of key/value (variable name / xr.Variable) pairs attributes : dict-like Dictionary of key/value (...
Top level method for putting data on this store, this method: - encodes variables/attributes - sets dimensions - sets variables Parameters ---------- variables : dict-like Dictionary of key/value (variable name / xr.Variable) pairs attributes : ...
def store(self, variables, attributes, check_encoding_set=frozenset(), writer=None, unlimited_dims=None): """ Top level method for putting data on this store, this method: - encodes variables/attributes - sets dimensions - sets variables Parameters ...
This provides a centralized method to set the dataset attributes on the data store. Parameters ---------- attributes : dict-like Dictionary of key/value (attribute name / attribute) pairs
def set_attributes(self, attributes): """ This provides a centralized method to set the dataset attributes on the data store. Parameters ---------- attributes : dict-like Dictionary of key/value (attribute name / attribute) pairs """ for k, v ...
This provides a centralized method to set the variables on the data store. Parameters ---------- variables : dict-like Dictionary of key/value (variable name / xr.Variable) pairs check_encoding_set : list-like List of variables that should be checked for ...
def set_variables(self, variables, check_encoding_set, writer, unlimited_dims=None): """ This provides a centralized method to set the variables on the data store. Parameters ---------- variables : dict-like Dictionary of key/value (vari...
This provides a centralized method to set the dimensions on the data store. Parameters ---------- variables : dict-like Dictionary of key/value (variable name / xr.Variable) pairs unlimited_dims : list-like List of dimension names that should be treated a...
def set_dimensions(self, variables, unlimited_dims=None): """ This provides a centralized method to set the dimensions on the data store. Parameters ---------- variables : dict-like Dictionary of key/value (variable name / xr.Variable) pairs unlimited...
Compute season (DJF, MAM, JJA, SON) from month ordinal
def _season_from_months(months): """Compute season (DJF, MAM, JJA, SON) from month ordinal """ # TODO: Move "season" accessor upstream into pandas seasons = np.array(['DJF', 'MAM', 'JJA', 'SON']) months = np.asarray(months) return seasons[(months // 3) % 4]
Coerce an array of datetime-like values to a CFTimeIndex and access requested datetime component
def _access_through_cftimeindex(values, name): """Coerce an array of datetime-like values to a CFTimeIndex and access requested datetime component """ from ..coding.cftimeindex import CFTimeIndex values_as_cftimeindex = CFTimeIndex(values.ravel()) if name == 'season': months = values_as_...
Coerce an array of datetime-like values to a pandas Series and access requested datetime component
def _access_through_series(values, name): """Coerce an array of datetime-like values to a pandas Series and access requested datetime component """ values_as_series = pd.Series(values.ravel()) if name == "season": months = values_as_series.dt.month.values field_values = _season_from_...
Indirectly access pandas' libts.get_date_field by wrapping data as a Series and calling through `.dt` attribute. Parameters ---------- values : np.ndarray or dask.array-like Array-like container of datetime-like values name : str Name of datetime field to access dtype : dtype-li...
def _get_date_field(values, name, dtype): """Indirectly access pandas' libts.get_date_field by wrapping data as a Series and calling through `.dt` attribute. Parameters ---------- values : np.ndarray or dask.array-like Array-like container of datetime-like values name : str Name...
Coerce an array of datetime-like values to a pandas Series and apply requested rounding
def _round_series(values, name, freq): """Coerce an array of datetime-like values to a pandas Series and apply requested rounding """ values_as_series = pd.Series(values.ravel()) method = getattr(values_as_series.dt, name) field_values = method(freq=freq).values return field_values.reshape(...
Indirectly access pandas rounding functions by wrapping data as a Series and calling through `.dt` attribute. Parameters ---------- values : np.ndarray or dask.array-like Array-like container of datetime-like values name : str (ceil, floor, round) Name of rounding function freq ...
def _round_field(values, name, freq): """Indirectly access pandas rounding functions by wrapping data as a Series and calling through `.dt` attribute. Parameters ---------- values : np.ndarray or dask.array-like Array-like container of datetime-like values name : str (ceil, floor, round...
Fill missing values in this object with data from the other object. Follows normal broadcasting and alignment rules. Parameters ---------- join : {'outer', 'inner', 'left', 'right'}, optional Method for joining the indexes of the passed objects along each dimension - 'outer': us...
def fillna(data, other, join="left", dataset_join="left"): """Fill missing values in this object with data from the other object. Follows normal broadcasting and alignment rules. Parameters ---------- join : {'outer', 'inner', 'left', 'right'}, optional Method for joining the indexes of the...
Return elements from `self` or `other` depending on `cond`. Parameters ---------- cond : DataArray or Dataset with boolean dtype Locations at which to preserve this objects values. other : scalar, DataArray or Dataset, optional Value to use for locations in this object where ``cond`` is...
def where_method(self, cond, other=dtypes.NA): """Return elements from `self` or `other` depending on `cond`. Parameters ---------- cond : DataArray or Dataset with boolean dtype Locations at which to preserve this objects values. other : scalar, DataArray or Dataset, optional Value...
Load a dataset from the online repository (requires internet). If a local copy is found then always use that to avoid network traffic. Parameters ---------- name : str Name of the netcdf file containing the dataset ie. 'air_temperature' cache_dir : string, optional The dire...
def open_dataset(name, cache=True, cache_dir=_default_cache_dir, github_url='https://github.com/pydata/xarray-data', branch='master', **kws): """ Load a dataset from the online repository (requires internet). If a local copy is found then always use that to avoid network t...
`load_dataset` will be removed a future version of xarray. The current behavior of this function can be achived by using `tutorial.open_dataset(...).load()`. See Also -------- open_dataset
def load_dataset(*args, **kwargs): """ `load_dataset` will be removed a future version of xarray. The current behavior of this function can be achived by using `tutorial.open_dataset(...).load()`. See Also -------- open_dataset """ warnings.warn( "load_dataset` will be remov...
Make a key for caching files in the LRU cache.
def _make_key(self): """Make a key for caching files in the LRU cache.""" value = (self._opener, self._args, 'a' if self._mode == 'w' else self._mode, tuple(sorted(self._kwargs.items()))) return _HashedSequence(value)
Acquiring a file object from the manager. A new file is only opened if it has expired from the least-recently-used cache. This method uses a lock, which ensures that it is thread-safe. You can safely acquire a file in multiple threads at the same time, as long as the underlying...
def acquire(self, needs_lock=True): """Acquiring a file object from the manager. A new file is only opened if it has expired from the least-recently-used cache. This method uses a lock, which ensures that it is thread-safe. You can safely acquire a file in multiple threads at t...
Explicitly close any associated file object (if necessary).
def close(self, needs_lock=True): """Explicitly close any associated file object (if necessary).""" # TODO: remove needs_lock if/when we have a reentrant lock in # dask.distributed: https://github.com/dask/dask/issues/3832 with self._optional_lock(needs_lock): default = None ...
Shrink the cache if necessary, evicting the oldest items.
def _enforce_size_limit(self, capacity): """Shrink the cache if necessary, evicting the oldest items.""" while len(self._cache) > capacity: key, value = self._cache.popitem(last=False) if self._on_evict is not None: self._on_evict(key, value)
Resize the cache, evicting the oldest items if necessary.
def maxsize(self, size): """Resize the cache, evicting the oldest items if necessary.""" if size < 0: raise ValueError('maxsize must be non-negative') with self._lock: self._enforce_size_limit(size) self._maxsize = size
Returns system information as a dict
def get_sys_info(): "Returns system information as a dict" blob = [] # get full commit hash commit = None if os.path.isdir(".git") and os.path.isdir("xarray"): try: pipe = subprocess.Popen('git log --format="%H" -n 1'.split(" "), stdout=subpr...
Given a key for indexing an ndarray, return an equivalent key which is a tuple with length equal to the number of dimensions. The expansion is done by replacing all `Ellipsis` items with the right number of full slices and then padding the key with full slices so that it reaches the appropriate dimensi...
def expanded_indexer(key, ndim): """Given a key for indexing an ndarray, return an equivalent key which is a tuple with length equal to the number of dimensions. The expansion is done by replacing all `Ellipsis` items with the right number of full slices and then padding the key with full slices so tha...
Convert values into a numpy array of at most 1-dimension, while preserving tuples. Adapted from pandas.core.common._asarray_tuplesafe
def _asarray_tuplesafe(values): """ Convert values into a numpy array of at most 1-dimension, while preserving tuples. Adapted from pandas.core.common._asarray_tuplesafe """ if isinstance(values, tuple): result = utils.to_0d_object_array(values) else: result = np.asarray(val...
Call pd.Index.get_indexer(labels).
def get_indexer_nd(index, labels, method=None, tolerance=None): """ Call pd.Index.get_indexer(labels). """ kwargs = _index_method_kwargs(method, tolerance) flat_labels = np.ravel(labels) flat_indexer = index.get_indexer(flat_labels, **kwargs) indexer = flat_indexer.reshape(labels.shape) return ...
Given a pandas.Index and labels (e.g., from __getitem__) for one dimension, return an indexer suitable for indexing an ndarray along that dimension. If `index` is a pandas.MultiIndex and depending on `label`, return a new pandas.Index or pandas.MultiIndex (otherwise return None).
def convert_label_indexer(index, label, index_name='', method=None, tolerance=None): """Given a pandas.Index and labels (e.g., from __getitem__) for one dimension, return an indexer suitable for indexing an ndarray along that dimension. If `index` is a pandas.MultiIndex and dependi...
Given a xarray data object and label based indexers, return a mapping of label indexers with only dimension names as keys. It groups multiple level indexers given on a multi-index dimension into a single, dictionary indexer for that dimension (Raise a ValueError if it is not possible).
def get_dim_indexers(data_obj, indexers): """Given a xarray data object and label based indexers, return a mapping of label indexers with only dimension names as keys. It groups multiple level indexers given on a multi-index dimension into a single, dictionary indexer for that dimension (Raise a ValueE...
Given an xarray data object and label based indexers, return a mapping of equivalent location based indexers. Also return a mapping of updated pandas index objects (in case of multi-index level drop).
def remap_label_indexers(data_obj, indexers, method=None, tolerance=None): """Given an xarray data object and label based indexers, return a mapping of equivalent location based indexers. Also return a mapping of updated pandas index objects (in case of multi-index level drop). """ if method is not ...
Given a slice and the size of the dimension to which it will be applied, index it with another slice to return a new slice equivalent to applying the slices sequentially
def slice_slice(old_slice, applied_slice, size): """Given a slice and the size of the dimension to which it will be applied, index it with another slice to return a new slice equivalent to applying the slices sequentially """ step = (old_slice.step or 1) * (applied_slice.step or 1) # For now, u...
This function always returns a ExplicitlyIndexed subclass, so that the vectorized indexing is always possible with the returned object.
def as_indexable(array): """ This function always returns a ExplicitlyIndexed subclass, so that the vectorized indexing is always possible with the returned object. """ if isinstance(array, ExplicitlyIndexed): return array if isinstance(array, np.ndarray): return NumpyIndexin...
Convert an OuterIndexer into an vectorized indexer. Parameters ---------- key : Outer/Basic Indexer An indexer to convert. shape : tuple Shape of the array subject to the indexing. Returns ------- VectorizedIndexer Tuple suitable for use to index a NumPy array with ...
def _outer_to_vectorized_indexer(key, shape): """Convert an OuterIndexer into an vectorized indexer. Parameters ---------- key : Outer/Basic Indexer An indexer to convert. shape : tuple Shape of the array subject to the indexing. Returns ------- VectorizedIndexer ...
Convert an OuterIndexer into an indexer for NumPy. Parameters ---------- key : Basic/OuterIndexer An indexer to convert. shape : tuple Shape of the array subject to the indexing. Returns ------- tuple Tuple suitable for use to index a NumPy array.
def _outer_to_numpy_indexer(key, shape): """Convert an OuterIndexer into an indexer for NumPy. Parameters ---------- key : Basic/OuterIndexer An indexer to convert. shape : tuple Shape of the array subject to the indexing. Returns ------- tuple Tuple suitable fo...
Combine two indexers. Parameters ---------- old_key: ExplicitIndexer The first indexer for the original array shape: tuple of ints Shape of the original array to be indexed by old_key new_key: The second indexer for indexing original[old_key]
def _combine_indexers(old_key, shape, new_key): """ Combine two indexers. Parameters ---------- old_key: ExplicitIndexer The first indexer for the original array shape: tuple of ints Shape of the original array to be indexed by old_key new_key: The second indexer for ind...
Support explicit indexing by delegating to a raw indexing method. Outer and/or vectorized indexers are supported by indexing a second time with a NumPy array. Parameters ---------- key : ExplicitIndexer Explicit indexing object. shape : Tuple[int, ...] Shape of the indexed arra...
def explicit_indexing_adapter( key, shape, indexing_support, raw_indexing_method): """Support explicit indexing by delegating to a raw indexing method. Outer and/or vectorized indexers are supported by indexing a second time with a NumPy array. Parameters ---------- key : ExplicitIndex...
convert a slice to successive two slices. The first slice always has a positive step.
def _decompose_slice(key, size): """ convert a slice to successive two slices. The first slice always has a positive step. """ start, stop, step = key.indices(size) if step > 0: # If key already has a positive step, use it as is in the backend return key, slice(None) else: ...
Decompose vectorized indexer to the successive two indexers, where the first indexer will be used to index backend arrays, while the second one is used to index loaded on-memory np.ndarray. Parameters ---------- indexer: VectorizedIndexer indexing_support: one of IndexerSupport entries Ret...
def _decompose_vectorized_indexer(indexer, shape, indexing_support): """ Decompose vectorized indexer to the successive two indexers, where the first indexer will be used to index backend arrays, while the second one is used to index loaded on-memory np.ndarray. Parameters ---------- indexe...
Decompose outer indexer to the successive two indexers, where the first indexer will be used to index backend arrays, while the second one is used to index the loaded on-memory np.ndarray. Parameters ---------- indexer: VectorizedIndexer indexing_support: One of the entries of IndexingSupport ...
def _decompose_outer_indexer(indexer, shape, indexing_support): """ Decompose outer indexer to the successive two indexers, where the first indexer will be used to index backend arrays, while the second one is used to index the loaded on-memory np.ndarray. Parameters ---------- indexer: Vec...
Return an identical vindex but slices are replaced by arrays
def _arrayize_vectorized_indexer(indexer, shape): """ Return an identical vindex but slices are replaced by arrays """ slices = [v for v in indexer.tuple if isinstance(v, slice)] if len(slices) == 0: return indexer arrays = [v for v in indexer.tuple if isinstance(v, np.ndarray)] n_dim = arr...
Create a dask array using the chunks hint for dimensions of size > 1.
def _dask_array_with_chunks_hint(array, chunks): """Create a dask array using the chunks hint for dimensions of size > 1.""" import dask.array as da if len(chunks) < array.ndim: raise ValueError('not enough chunks in hint') new_chunks = [] for chunk, size in zip(chunks, array.shape): ...
Create a mask for indexing with a fill-value. Parameters ---------- indexer : ExplicitIndexer Indexer with -1 in integer or ndarray value to indicate locations in the result that should be masked. shape : tuple Shape of the array being indexed. chunks_hint : tuple, optional ...
def create_mask(indexer, shape, chunks_hint=None): """Create a mask for indexing with a fill-value. Parameters ---------- indexer : ExplicitIndexer Indexer with -1 in integer or ndarray value to indicate locations in the result that should be masked. shape : tuple Shape of t...
Convert masked indices in a flat array to the nearest unmasked index. Parameters ---------- index : np.ndarray One dimensional ndarray with dtype=int. Returns ------- np.ndarray One dimensional ndarray with all values equal to -1 replaced by an adjacent non-masked eleme...
def _posify_mask_subindexer(index): """Convert masked indices in a flat array to the nearest unmasked index. Parameters ---------- index : np.ndarray One dimensional ndarray with dtype=int. Returns ------- np.ndarray One dimensional ndarray with all values equal to -1 repla...
Convert masked values (-1) in an indexer to nearest unmasked values. This routine is useful for dask, where it can be much faster to index adjacent points than arbitrary points from the end of an array. Parameters ---------- indexer : ExplicitIndexer Input indexer. Returns -------...
def posify_mask_indexer(indexer): """Convert masked values (-1) in an indexer to nearest unmasked values. This routine is useful for dask, where it can be much faster to index adjacent points than arbitrary points from the end of an array. Parameters ---------- indexer : ExplicitIndexer ...
import seaborn and handle deprecation of apionly module
def import_seaborn(): '''import seaborn and handle deprecation of apionly module''' with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") try: import seaborn.apionly as sns if (w and issubclass(w[-1].category, UserWarning) and ...
Build a discrete colormap and normalization of the data.
def _build_discrete_cmap(cmap, levels, extend, filled): """ Build a discrete colormap and normalization of the data. """ import matplotlib as mpl if not filled: # non-filled contour plots extend = 'max' if extend == 'both': ext_n = 2 elif extend in ['min', 'max']: ...
Use some heuristics to set good defaults for colorbar and range. Parameters ========== plot_data: Numpy array Doesn't handle xarray objects Returns ======= cmap_params : dict Use depends on the type of the plotting function
def _determine_cmap_params(plot_data, vmin=None, vmax=None, cmap=None, center=None, robust=False, extend=None, levels=None, filled=True, norm=None): """ Use some heuristics to set good defaults for colorbar and range. Parameters ========== plot_...
Determine x and y labels for showing RGB images. Attempts to infer which dimension is RGB/RGBA by size and order of dims.
def _infer_xy_labels_3d(darray, x, y, rgb): """ Determine x and y labels for showing RGB images. Attempts to infer which dimension is RGB/RGBA by size and order of dims. """ assert rgb is None or rgb != x assert rgb is None or rgb != y # Start by detecting and reporting invalid combination...
Determine x and y labels. For use in _plot2d darray must be a 2 dimensional data array, or 3d for imshow only.
def _infer_xy_labels(darray, x, y, imshow=False, rgb=None): """ Determine x and y labels. For use in _plot2d darray must be a 2 dimensional data array, or 3d for imshow only. """ assert x is None or x != y if imshow and darray.ndim == 3: return _infer_xy_labels_3d(darray, x, y, rgb) ...
Makes informative labels if variable metadata (attrs) follows CF conventions.
def label_from_attrs(da, extra=''): ''' Makes informative labels if variable metadata (attrs) follows CF conventions. ''' if da.attrs.get('long_name'): name = da.attrs['long_name'] elif da.attrs.get('standard_name'): name = da.attrs['standard_name'] elif da.name is not None: ...
Helper function to deal with a xarray consisting of pd.Intervals. Each interval is replaced with both boundaries. I.e. the length of xarray doubles. yarray is modified so it matches the new shape of xarray.
def _interval_to_double_bound_points(xarray, yarray): """ Helper function to deal with a xarray consisting of pd.Intervals. Each interval is replaced with both boundaries. I.e. the length of xarray doubles. yarray is modified so it matches the new shape of xarray. """ xarray1 = np.array([x.left...
Helper function which returns an array with the Intervals' boundaries.
def _interval_to_bound_points(array): """ Helper function which returns an array with the Intervals' boundaries. """ array_boundaries = np.array([x.left for x in array]) array_boundaries = np.concatenate( (array_boundaries, np.array([array[-1].right]))) return array_boundaries
Helper function to replace the values of a coordinate array containing pd.Interval with their mid-points or - for pcolormesh - boundaries which increases length by 1.
def _resolve_intervals_2dplot(val, func_name): """ Helper function to replace the values of a coordinate array containing pd.Interval with their mid-points or - for pcolormesh - boundaries which increases length by 1. """ label_extra = '' if _valid_other_type(val, [pd.Interval]): if ...
Do all elements of x have a type from types?
def _valid_other_type(x, types): """ Do all elements of x have a type from types? """ return all(any(isinstance(el, t) for t in types) for el in np.ravel(x))
Is any dtype from numpy_types superior to the dtype of x?
def _valid_numpy_subdtype(x, numpy_types): """ Is any dtype from numpy_types superior to the dtype of x? """ # If any of the types given in numpy_types is understood as numpy.generic, # all possible x will be considered valid. This is probably unwanted. for t in numpy_types: assert not ...
Raise exception if there is anything in args that can't be plotted on an axis by matplotlib.
def _ensure_plottable(*args): """ Raise exception if there is anything in args that can't be plotted on an axis by matplotlib. """ numpy_types = [np.floating, np.integer, np.timedelta64, np.datetime64] other_types = [datetime] try: import cftime cftime_datetime = [cftime.date...
Update axes with provided parameters
def _update_axes(ax, xincrease, yincrease, xscale=None, yscale=None, xticks=None, yticks=None, xlim=None, ylim=None): """ Update axes with provided parameters """ if xincrease is None: pass elif xincrease and ax.xaxis_inverted(): ax....
>>> _is_monotonic(np.array([0, 1, 2])) True >>> _is_monotonic(np.array([2, 1, 0])) True >>> _is_monotonic(np.array([0, 2, 1])) False
def _is_monotonic(coord, axis=0): """ >>> _is_monotonic(np.array([0, 1, 2])) True >>> _is_monotonic(np.array([2, 1, 0])) True >>> _is_monotonic(np.array([0, 2, 1])) False """ if coord.shape[axis] < 3: return True else: n = coord.shape[axis] delta_pos = (co...
>>> _infer_interval_breaks(np.arange(5)) array([-0.5, 0.5, 1.5, 2.5, 3.5, 4.5]) >>> _infer_interval_breaks([[0, 1], [3, 4]], axis=1) array([[-0.5, 0.5, 1.5], [ 2.5, 3.5, 4.5]])
def _infer_interval_breaks(coord, axis=0, check_monotonic=False): """ >>> _infer_interval_breaks(np.arange(5)) array([-0.5, 0.5, 1.5, 2.5, 3.5, 4.5]) >>> _infer_interval_breaks([[0, 1], [3, 4]], axis=1) array([[-0.5, 0.5, 1.5], [ 2.5, 3.5, 4.5]]) """ coord = np.asarray(co...
Parameters ========== func : plotting function kwargs : dict, Dictionary with arguments that need to be parsed data : ndarray, Data values Returns ======= cmap_params cbar_kwargs
def _process_cmap_cbar_kwargs(func, kwargs, data): """ Parameters ========== func : plotting function kwargs : dict, Dictionary with arguments that need to be parsed data : ndarray, Data values Returns ======= cmap_params cbar_kwargs """ cmap = kwargs.p...