Python API¶
Cube I/O¶
Cube generation¶
- xcube.core.new.new_cube(title='Test Cube', width=360, height=180, x_name='lon', y_name='lat', x_dtype='float64', y_dtype=None, x_units='degrees_east', y_units='degrees_north', x_res=1.0, y_res=None, x_start=- 180.0, y_start=- 90.0, inverse_y=False, time_name='time', time_dtype='datetime64[s]', time_units='seconds since 1970-01-01T00:00:00', time_calendar='proleptic_gregorian', time_periods=5, time_freq='D', time_start='2010-01-01T00:00:00', use_cftime=False, drop_bounds=False, variables=None, crs=None, crs_name=None)[source]¶
Create a new empty cube. Useful for creating cubes templates with predefined coordinate variables and metadata. The function is also heavily used by xcube’s unit tests.
The values of the variables dictionary can be either constants, array-like objects, or functions that compute their return value from passed coordinate indexes. The expected signature is::
def my_func(time: int, y: int, x: int) -> Union[bool, int, float]
- Parameters
title (
str
) – A title. Defaults to ‘Test Cube’.width (
int
) – Horizontal number of grid cells. Defaults to 360.height (
int
) – Vertical number of grid cells. Defaults to 180.x_name (
str
) – Name of the x coordinate variable. Defaults to ‘lon’.y_name (
str
) – Name of the y coordinate variable. Defaults to ‘lat’.x_dtype (
str
) – Data type of x coordinates. Defaults to ‘float64’.y_dtype – Data type of y coordinates. Defaults to ‘float64’.
x_units (
str
) – Units of the x coordinates. Defaults to ‘degrees_east’.y_units (
str
) – Units of the y coordinates. Defaults to ‘degrees_north’.x_start (
float
) – Minimum x value. Defaults to -180.y_start (
float
) – Minimum y value. Defaults to -90.x_res (
float
) – Spatial resolution in x-direction. Defaults to 1.0.y_res – Spatial resolution in y-direction. Defaults to 1.0.
inverse_y (
bool
) – Whether to create an inverse y axis. Defaults to False.time_name (
str
) – Name of the time coordinate variable. Defaults to ‘time’.time_periods (
int
) – Number of time steps. Defaults to 5.time_freq (
str
) – Duration of each time step. Defaults to `1D’.time_start (
str
) – First time value. Defaults to ‘2010-01-01T00:00:00’.time_dtype (
str
) – Numpy data type for time coordinates. Defaults to ‘datetime64[s]’. If used, parameter ‘use_cftime’ must be False.time_units (
str
) – Units for time coordinates. Defaults to ‘seconds since 1970-01-01T00:00:00’.time_calendar (
str
) – Calender for time coordinates. Defaults to ‘proleptic_gregorian’.use_cftime (
bool
) – If True, the time will be given as data types according to the ‘cftime’ package. If used, the time_calendar parameter must be also be given with an appropriate value such as ‘gregorian’ or ‘julian’. If used, parameter ‘time_dtype’ must be None.drop_bounds (
bool
) – If True, coordinate bounds variables are not created. Defaults to False.variables – Dictionary of data variables to be added. None by default.
crs – pyproj-compatible CRS string or instance of pyproj.CRS or None
crs_name – Name of the variable that will hold the CRS information. Ignored, if crs is not given.
- Returns
A cube instance
Cube computation¶
Cube data extraction¶
Cube manipulation¶
- xcube.core.unchunk.unchunk_dataset(dataset_path: str, var_names: Optional[Sequence[str]] = None, coords_only: bool = False)[source]¶
Unchunk dataset variables in-place.
- Parameters
dataset_path (
str
) – Path to ZARR dataset directory.var_names – Optional list of variable names.
coords_only (
bool
) – Un-chunk coordinate variables only.
- xcube.core.optimize.optimize_dataset(input_path: str, output_path: Optional[str] = None, in_place: bool = False, unchunk_coords: Union[bool, str, Sequence[str]] = False, exception_type: Type[Exception] = <class 'ValueError'>)[source]¶
Optimize a dataset for faster access.
Reduces the number of metadata and coordinate data files in xcube dataset given by given by dataset_path. Consolidated cubes open much faster from remote locations, e.g. in object storage, because obviously much less HTTP requests are required to fetch initial cube meta information. That is, it merges all metadata files into a single top-level JSON file “.zmetadata”.
If unchunk_coords is given, it also removes any chunking of coordinate variables so they comprise a single binary data file instead of one file per data chunk. The primary usage of this function is to optimize data cubes for cloud object storage. The function currently works only for data cubes using Zarr format. unchunk_coords can be a name, or list of names of the coordinate variable(s) to be consolidated. If boolean
True
is used, coordinate all variables will be consolidated.- Parameters
input_path (
str
) – Path to input dataset with ZARR format.output_path (
str
) – Path to output dataset with ZARR format. May contain “{input}” template string, which is replaced by the input path’s file name without file name extension.in_place (
bool
) – Whether to modify the dataset in place. If False, a copy is made and output_path must be given.unchunk_coords – The name of a coordinate variable or a list of coordinate variables whose chunks should be consolidated. Pass
True
to consolidate chunks of all coordinate variables.exception_type – Type of exception to be used on value errors.
Cube subsetting¶
Cube masking¶
- class xcube.core.maskset.MaskSet(flag_var: xarray.DataArray)[source]¶
A set of mask variables derived from a variable flag_var with the following CF attributes:
One or both of flag_masks and flag_values
flag_meanings (always required)
See https://cfconventions.org/Data/cf-conventions/cf-conventions-1.9/cf-conventions.html#flags for details on the use of these attributes.
Each mask is represented by an xarray.DataArray, has the name of the flag, is of type numpy.unit8, and has the dimensions of the given flag_var.
- Parameters
flag_var – an xarray.DataArray that defines flag values. The CF attributes flag_meanings and one or both of flag_masks and flag_values are expected to exist and be valid.
- classmethod get_mask_sets(dataset: xarray.Dataset) Dict[str, xcube.core.maskset.MaskSet] [source]¶
For each “flag” variable in given dataset, turn it into a
MaskSet
, store it in a dictionary.- Parameters
dataset – The dataset
- Returns
A mapping of flag names to
MaskSet
. Will be empty if there
are no flag variables in dataset.
Rasterisation of Features¶
Cube metadata¶
Cube verification¶
Multi-resolution pyramids¶
Utilities¶
Plugin Development¶
- class xcube.util.extension.ExtensionRegistry[source]¶
A registry of extensions. Typically used by plugins to register extensions.
- has_extension(point: str, name: str) bool [source]¶
Test if an extension with given point and name is registered.
- Return type
bool
- Parameters
point (
str
) – extension point identifiername (
str
) – extension name
- Returns
True, if extension exists
- get_extension(point: str, name: str) Optional[xcube.util.extension.Extension] [source]¶
Get registered extension for given point and name.
- Parameters
point (
str
) – extension point identifiername (
str
) – extension name
- Returns
the extension or None, if no such exists
- get_component(point: str, name: str) Any [source]¶
Get extension component for given point and name. Raises a ValueError if no such extension exists.
- Parameters
point (
str
) – extension point identifiername (
str
) – extension name
- Returns
extension component
- find_extensions(point: str, predicate: Optional[Callable[[xcube.util.extension.Extension], bool]] = None) List[xcube.util.extension.Extension] [source]¶
Find extensions for point and optional filter function predicate.
The filter function is called with an extension and should return a truth value to indicate a match or mismatch.
- Parameters
point (
str
) – extension point identifierpredicate – optional filter function
- Returns
list of matching extensions
- find_components(point: str, predicate: Optional[Callable[[xcube.util.extension.Extension], bool]] = None) List[Any] [source]¶
Find extension components for point and optional filter function predicate.
The filter function is called with an extension and should return a truth value to indicate a match or mismatch.
- Parameters
point (
str
) – extension point identifierpredicate – optional filter function
- Returns
list of matching extension components
- add_extension(point: str, name: str, component: Optional[Any] = None, loader: Optional[Callable[[xcube.util.extension.Extension], Any]] = None, **metadata) xcube.util.extension.Extension [source]¶
Register an extension component or an extension component loader for the given extension point, name, and additional metadata.
Either component or loader must be specified, but not both.
A given loader must be a callable with one positional argument extension of type
Extension
and is expected to return the actual extension component, which may be of any type. The loader will only be called once and only when the actual extension component is requested for the first time. Consider using the functionimport_component()
to create a loader that lazily imports a component from a module and optionally executes it.- Return type
- Parameters
point (
str
) – extension point identifiername (
str
) – extension namecomponent – extension component
loader – extension component loader function
metadata – extension metadata
- Returns
a registered extension
- class xcube.util.extension.Extension(point: str, name: str, component: Optional[Any] = None, loader: Optional[Callable[[xcube.util.extension.Extension], Any]] = None, **metadata)[source]¶
An extension that provides a component of any type.
Extensions are registered in a
ExtensionRegistry
.Extension objects are not meant to be instantiated directly. Instead,
ExtensionRegistry.add_extension()
is used to register extensions.- Parameters
point – extension point identifier
name – extension name
component – extension component
loader – extension component loader function
metadata – extension metadata
- property is_lazy: bool¶
Whether this is a lazy extension that uses a loader.
- property component: Any¶
Extension component.
- property point: str¶
Extension point identifier.
- property name: str¶
Extension name.
- property metadata: Dict[str, Any]¶
Extension metadata.
- xcube.util.extension.import_component(spec: str, transform: Optional[Callable[[Any, xcube.util.extension.Extension], Any]] = None, call: bool = False, call_args: Optional[Sequence[Any]] = None, call_kwargs: Optional[Mapping[str, Any]] = None) Callable[[xcube.util.extension.Extension], Any] [source]¶
Return a component loader that imports a module or module component from spec. To import a module, spec should be the fully qualified module name. To import a component, spec must also append the component name to the fully qualified module name separated by a color (“:”) character.
An optional transform callable my be used to transform the imported component. If given, a new component is computed:
component = transform(component, extension)
If the call flag is set, the component is expected to be a callable which will be called using the given call_args and call_kwargs to produce a new component:
component = component(*call_kwargs, **call_kwargs)
Finally, the component is returned.
- Parameters
spec (
str
) – String of the form “module_path” or “module_path:component_name”transform – callable that takes two positional arguments, the imported component and the extension of type
Extension
call (
bool
) – Whether to finally call the component with given call_args and call_kwargscall_args – arguments passed to a callable component if call flag is set
call_kwargs – keyword arguments passed to callable component if call flag is set
- Returns
a component loader
- xcube.constants.EXTENSION_POINT_INPUT_PROCESSORS = 'xcube.core.gen.iproc'¶
The extension point identifier for input processor extensions
- xcube.constants.EXTENSION_POINT_DATASET_IOS = 'xcube.core.dsio'¶
The extension point identifier for dataset I/O extensions
- xcube.constants.EXTENSION_POINT_CLI_COMMANDS = 'xcube.cli'¶
The extension point identifier for CLI command extensions
- xcube.util.plugin.get_extension_registry() xcube.util.extension.ExtensionRegistry [source]¶
Get populated extension registry.