INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Exact computation of b - a
def exact_cftime_datetime_difference(a, b): """Exact computation of b - a Assumes: a = a_0 + a_m b = b_0 + b_m Here a_0, and b_0 represent the input dates rounded down to the nearest second, and a_m, and b_m represent the remaining microseconds associated with date a and date ...
Meant to reproduce the results of the following
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 () )
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.
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.
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.
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.
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.
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.
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.
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...
Merge two sets of coordinates to create a new Dataset
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 ...
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]
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:
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
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.
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.
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.
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.
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 ).
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.
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.
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.
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
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...
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.
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...
Reduce the items in this group by applying func along some dimension ( s ).
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 ...
Apply a function over each Dataset in the group and concatenate them together into a new Dataset.
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...
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 ).
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) ...
Mimicks iris_obj. name () but with different name resolution order.
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 ...
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...
Given an array of numeric dates in netCDF format convert it into a numpy array of date time objects.
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.
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.
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.
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.
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.
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
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.
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
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 Returns ------- MultiIndex Ex...
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.
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.
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
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
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.
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 ...