Each supported geometry convention represents data differently.
The Convention class abstracts these differences away,
allowing developers to query and manipulate datasets
without worrying about the details.
See Supported dataset conventions
for a list of implemented conventions.
All conventions have the concept of a cell at a geographic location,
vertically stacked layers of cells,
and multiple timesteps of data.
A convention may support additional grids, such as face edges and vertices.
Refer to Grids for more information.
A cell can be addressed using a linear index or a native index.
A linear index is always an int,
while the native index type will depend on the specific convention.
You can convert between a linear and a native index
using ravel_index() and wind_index().
Refer to Indexing for more information.
This may check for variables of the correct dimensions,
the presence of specific attributes,
or the layout of the dataset dimensions.
Specific subclasses must implement this function.
It will be called by the convention autodetector
when guessing the correct convention for a dataset.
If the dataset matches, the return value indicates how specific the match is.
When autodetecting the correct convention implementation
the convention with the highest specicifity will be used.
Many conventions extend the CF grid conventions,
so the CF Grid convention classes will match many datasets.
However this match is very generic.
A more specific implementation such as SHOC may be supported.
The SHOC convention implementation should return a higher specicifity
than the CF grid convention.
Parameters:
dataset (xarray.Dataset) – The dataset instance to inspect.
Returns:
int, optional – If this convention implementation can handle this dataset
some integer greater than zero is returned.
The higher the number, the more specific the support.
If the dataset does not match this convention, None is returned.
Values on the Specificity enum
are used by emsarray itself to indicated specificity.
New convention implementations are free to use these values,
or use any integer value.
# Open a dataset built using the GRASS conventiondataset=xarray.open_dataset("grass-dataset.nc")# Construct a Grass instance for the dataset and bind itconvention=Grass(dataset)convention.bind()# dataset.ems is now the bound conventionassertdataset.emsisconvention
If the dataset already has a bound convention, an error is raised.
To bind a new convention to a dataset, make a copy of the dataset first:
xarray will find all time variables and convert them to numpy datetimes when opening a dataset.
The CF Conventions state that
a time variable is defined by having a units attribute
formatted according to the UDUNITS package [1].
In practice, some datasets do not follow this conventions.
emsarray will first look for a time coordinate that conforms to the CF Conventions,
but if none are found it will fall back to picking a datetime variable
that has at least one coordinate_type: time, standard_name: time, or axis: T attribute set.
The CF Conventions state that
a depth variable is identifiable by units of pressure; or
the presence of the positive attribute with value of up or down[2].
In practice, many datasets do not follow this convention.
In addition to checking for the positive attribute,
all coordinates are checked for a standard_name:"depth",
coordinate_type:"Z", or axiz:"Z".
Find the depth coordinate for a particular data array.
Some conventions will contain multiple depth coordinates,
meaning that a default depth_coordinate value can be misleading.
Parameters:
data_array (xarray.DataArray or Hashable) – A data array or the name of a data array in the dataset.
Returns:
xarray.DataArray – The depth coordinate variable for the data array.
grid_kind (GridKind, optional) – Used to indicate what kind of index is being wound,
for conventions with multiple grids.
Optional, if not provided the default grid kind will be used.
Returns:
Index – The convention native index for that same cell
Example
If the dataset used the CF Grid conventions,
across a (latitude, longitude) grid of size (30, 40):
ValueError – If the data array passed in doesn’t match any grid kind for this dataset
a ValueError is raised.
Depth coordinates or time coordinates are examples of data arrays
that will not be indexable and will raise an error.
Example
For a UGRID dataset
with temperature data defined at the cell centres
and current defined as flux through the cell edges:
ValueError – If the data array passed in doesn’t match any grid kind for this dataset
a ValueError is raised.
Depth coordinates or time coordinates are examples of data arrays
that will not be indexable and will raise an error.
Flatten the surface dimensions of a DataArray,
returning a flatter numpy.ndarray indexed in the same order as the linear index.
For DataArrays with extra dimensions such as time or depth,
only the surface dimensions are flattened.
Other dimensions are left as is.
For datasets with multiple grids,
with data defined on edges or vertices for example,
this will flatten those data arrays in the correct linear order
to be indexed by the relevant index type.
Parameters:
data_array (xarray.DataArray) – One of the data variables from this dataset.
linear_dimension (Hashable, optional) – The name of the new dimension to flatten the surface dimensions to.
Defaults to ‘index’.
Returns:
xarray.DataArray – A new data array, where all the surface dimensions
have been flattened in to one linear array.
The values for each cell, in the same order as the linear index for this dataset.
Any other dimensions, such as depth or time, will be retained.
data_array (xarray.DataArray) – One of the data variables from this dataset.
grid_kind (GridKind) – The kind of grid this data array represents,
for those conventions with multiple grid kinds.
Optional, defaults to the default grid kind.
axis (int, optional) – The axis number that should be wound.
Optional, defaults to the last axis.
Mutually exclusive with the linear_dimension parameter.
linear_dimension (Hashable, optional) – The name of the dimension in the data array that should be wound.
Optional, defaults to the last dimension.
Mutually exclusive with the axis parameter.
Returns:
xarray.DataArray – A new data array where the linear data have been wound
to match the shape of the convention.
Any other dimensions, such as depth or time, will be retained.
The coordinate reference system that coordinates in this dataset are
defined in.
Used by plotting methods when creating Artists.
Defaults to cartopy.crs.PlateCarree.
If your dataset uses a different coordinate reference system
this property can be set manually:
This method is most useful when working in Jupyter notebooks
which display figures automatically.
This method is a wrapper around plot_on_figure()
that creates and shows a Figure for you.
All arguments are passed on to plot_on_figure(),
refer to that function for details.
This method is a shortcut for quickly generating simple plots.
It is not intended to be fully featured.
See the examples for more comprehensive plotting examples.
The data array can either be passed in directly,
or the name of a data array on this Convention.dataset instance.
The data array does not have to come from the same dataset,
as long as the dimensions are the same.
This method will only plot a single time step and depth layer.
Callers are responsible for selecting a single slice before calling this method.
This method is a shortcut for quickly generating simple plots.
It is not intended to be fully featured.
See the examples for more comprehensive plotting examples.
*variables (xarray.DataArray or tuples of xarray.DataArray) – Any number of dataset variables to plot.
Scalar variables should be passed in directly,
while vector pairs should be passed in as a tuple.
These will be passed to Convention.make_artist().
scalar (dataarrayorname) – The DataArray to plot,
or the name of an existing DataArray in this Dataset.
Deprecated since version 1.0.0: Pass in variables as positional arguments instead
vector (tuple of dataarrayorname) – A tuple of the u and v components of a vector.
The components should be a DataArray,
or the name of an existing DataArray in this Dataset.
Deprecated since version 1.0.0: Pass in variables as positional arguments instead
This method is a shortcut for quickly generating simple animations.
It is not intended to be fully featured.
See the examples for more comprehensive plotting examples,
and specifically Animated plot for an animated example.
*variables (xarray.DataArray or tuples of xarray.DataArray) – Any number of dataset variables to plot.
Scalar variables should be passed in directly,
while vector pairs should be passed in as a tuple.
These will be passed to Convention.make_artist().
scalar (dataarrayorname) – The DataArray to plot,
or the name of an existing DataArray in this Dataset.
Deprecated since version 1.0.0: Pass in variables as positional arguments instead
vector (tuple of dataarrayorname) – A tuple of the u and v components of a vector.
The components should be a DataArray,
or the name of an existing DataArray in this Dataset.
Deprecated since version 1.0.0: Pass in variables as positional arguments instead
coordinate (Hashable or xarray.DataArray, optional) – The coordinate to vary across the animation.
Pass in either the name of a coordinate variable
or coordinate variable itself.
Optional, if not supplied the time coordinate
from Convention.time_coordinate is used.
Other appropriate coordinates to animate over include depth.
Make a matplotlib artists for the data array,
adding it to the Axes and returning the Artist.
This method will pick a reasonable way of drawing the variable
based on the convention and the grid that the variable is defined on.
See the documentation on each convention for specific details.
For most conventions:
scalar variables defined on a polygon grid will use
make_polygon_scalar_collection()
vector pairs defined on a polygon grid will use
make_polygon_vector_quiver()
scalar variables defined on a node grid will use
make_node_scalar_artist()
variable (dataarrayorname or tuple of dataarrayorname) – The data array, or tuple of data arrays, to make an artist for.
A sensible artist type is picked based on the data arrays passed in
and the grids they are defined on.
kwargs (Any) – Any extra kwargs are passed on to the artist
and can be used to style it.
The specific kwargs that are accepted depend on the artist that is used.
Returns:
emsarray.plot.GridArtist – The artist for the data array passed in.
The artist will already have been added to the axes.
If a DataArray is passed in,
the values of that are assigned to the PolyCollection array parameter.
Parameters:
data_array (Hashable or xarray.DataArray, optional) – A data array, or the name of a data variable in this dataset. Optional.
If given, the data array is ravelled
and passed to PolyCollection.set_array().
The data is used to colour the patches.
Refer to the matplotlib documentation for more information on styling.
**kwargs – Any keyword arguments are passed to the
PolyCollection constructor.
Returns:
PolyCollection – A PolyCollection constructed using the geometry of this dataset.
u, v (xarray.DataArray or str, optional) – The DataArrays or the names of DataArrays in this dataset
that make up the u and v components of the vector.
If omitted, a Quiver will be constructed with all components set to 0.
**kwargs – Any keyword arguments are passed on to the Quiver constructor.
Make geometry for the specified GridKind.
This should normally be accessed via Grid.geometry,
which stores a cached copy of the geometry for each grid.
Make geometry centroids for the specified GridKind.
This should normally be accessed via Grid.centroid,
which stores a cached copy of the geometry for each grid.
The returned selector is an xarray.Dataset,
but the contents of the dataset are dependent on the specific convention
and may change between versions of emsarray.
The selector should be treated as an opaque value
that is only useful when passed to xarray.Dataset.isel().
The returned selector is an xarray.Dataset,
but the contents of the dataset are dependent on the specific convention
and may change between versions of emsarray.
The selector should be treated as an opaque value
that is only useful when passed to xarray.Dataset.isel().
Return a new dataset that contains values only from a single index.
This is much like doing a xarray.Dataset.isel() on an index,
but works with convention native index types.
An index is associated with a grid kind.
The returned dataset will only contain variables that were defined on this grid,
with the single indexed point selected.
For example, if the index of a face is passed in,
the returned dataset will not contain any variables defined on an edge.
drop_geometry (bool, defaultTrue) – Whether to drop geometry variables from the returned point dataset.
If the geometry data is kept
the associated geometry data will no longer conform to the dataset convention
and may not conform to any sensible convention at all.
The format of the geometry data left after selecting points is convention-dependent.
Returns:
xarray.Dataset – A new dataset that is subset to the one index.
The returned dataset will most likely not have sufficient coordinate data
to be used with a particular Convention any more.
The dataset.ems accessor will raise an error if accessed on the new dataset.
Return a new dataset that contains values only at the selected indexes.
This is much like doing a xarray.Dataset.isel() on some indexes,
but works with convention native index types.
An index is associated with a grid kind.
The returned dataset will only contain variables that were defined on this grid,
with the indexed points selected.
For example, if the index of a face is passed in,
the returned dataset will not contain any variables defined on an edge.
Parameters:
indexes (list of Index) – The indexes to select.
The indexes must all be for the same grid kind.
index_dimension (str, optional) – The name of the new dimension added for each index to select.
Defaults to the firstunuseddimension with prefix index.
drop_geometry (bool, defaultTrue) – Whether to drop geometry variables from the returned point dataset.
If the geometry data is kept
the associated geometry data will no longer conform to the dataset convention
and may not conform to any sensible convention at all.
The format of the geometry data left after selecting points is convention-dependent.
Returns:
xarray.Dataset – A new dataset that is subset to the indexes.
The returned dataset will most likely not have sufficient coordinate data
to be used with a particular Convention any more.
The dataset.ems accessor will raise an error if accessed on the new dataset.
Return a new dataset that contains values for a single point.
This is a shortcut for querying the Grid.strtree to find intersecting geometry,
then selecting the cell using select_index().
If the point is not inside the dataset a ValueError is raised.
point_dimension (str, optional) – The name of the new dimension used to index points.
Defaults to ‘point’, or ‘point_0’, ‘point_1’, etc if those dimensions already exist.
missing_points ({'error','drop'}, default'error') – What to do if a point does not intersect the dataset.
‘raise’ will raise an error, while ‘drop’ will drop those points.
Returns:
xarray.Dataset – A dataset with values extracted from the points.
No variables not defined on the default grid and no geometry variables will be present.
Make a new Dataset that can be used to clip this dataset to only the
cells that intersect some geometry.
This dataset can be saved to a file to be reused to cut multiple
datasets with identical shapes, such as a series of files representing
multiple time series of a model.
The mask can be applied to this dataset (or other datasets identical in
shape) using apply_clip_mask().
Parameters:
clip_geometry (shapely.BaseGeometry) – The desired area to cut out. This can be any shapely geometry type,
but will most likely be a polygon
buffer (int, optional) – If set to a positive integer,
a buffer of that many cells will be added around the clip region.
This is useful if you need to clip to a particular area,
but also would like to do some interpolation on the output cells.
Apply a clip mask to this dataset, and return a new dataset.
Call make_clip_mask() to create a clip mask from a clip geometry.
The clip_mask can be saved and loaded to disk if the mask needs to
be reused across multiple datasets, such as multiple time series from
one model.
Depending on the implementation, the input dataset may be sliced in to
multiple files during cutting, and the returned Dataset
might be a multi-file Dataset built from these
temporary files. The caller must either load the dataset in to memory
using load() or compute(),
or save the dataset to disk somewhere outside of the working directory
before the working directory is cleaned up.
work_dir (str or pathlib.Path) – A directory where temporary files can be written to.
Callers must create and manage this temporary directory,
perhaps using tempfile.TemporaryDirectory.
clip_geometry (shapely.BaseGeometry) – The desired area to cut out.
This can be any shapely geometry type,
but will most likely be a polygon
work_dir (str or pathlib.Path) – A directory where temporary files can be written to.
Callers must create and manage this temporary directory,
perhaps using tempfile.TemporaryDirectory.
buffer (int, optional) – If set to a positive integer,
a buffer of that many cells will be added around the clip region.
This is useful if you need to clip to a particular area,
but also would like to do some interpolation on the output cells.
Triangulates the polygons in the dataset.
Subclasses may have improved implementations.
This requires the dataset to have a grid with polygonal geometry.
If there is an additional grid corresponding to the vertices of the polygons
then subclasses should use this information to inform the triangulation.
Returns:
tuple of vertices, triangles, and cell_indexes – A tuple of three numpy arrays is returned,
containing vertices, triangles, and cell indexes respectively.
vertices is a numpy array of shape (V, 2)
where V is the number of unique vertices in the dataset.
The vertex coordinates are in (x, y) or (lon, lat) order.
If the dataset has a vertex grid associated with the polygons
then this array replicates that data.
triangles is a numpy array of shape (T, 3)
where T is the number of triangles in the dataset.
Each triangle is a set of three vertex indexes.
cell_indexes is a numpy list of length T.
Each entry indicates which polygon from the dataset a triangle is a part of.
The geometry of this grid as a numpy.ndarray of Shapely geometries.
Different grids might have different geometrytypes.
Some elements may be None, depending on the dataset convention and
the particulars of the dataset.
A shapely.strtree.STRtree filled with the geometry of this grid.
The indexes returned when querying this STRtree correspond to the linear index of this grid.
The indexes correspond with the geometry in Grid.geometry.
Example
This example will find the linear index, native index, selector, and geometry
at a point.
The centres of the geometry of this grid as a numpy.ndarray of Shapely points.
Defaults to the shapely.centroid() of Grid.geometry,
but some conventions might have more specific ways of finding the centres.
If geometry is empty the corresponding index in this array will be None.
The centres of the geometry of this grid as a 2-dimensional numpy.ndarray
with shape (Grid.size, 2).
If geometry is empty the corresponding row in this array will be [numpy.nan, numpy.nan].
Flatten the surface dimensions of a DataArray,
returning a flatter numpy.ndarray indexed in the same order as the linear index.
For DataArrays with extra dimensions such as time or depth,
only the surface dimensions are flattened.
Other dimensions are left as is.
Parameters:
data_array (xarray.DataArray) – One of the data variables from this dataset.
linear_dimension (Hashable, optional) – The name of the new dimension to flatten the surface dimensions to.
Defaults to ‘index’.
Returns:
xarray.DataArray – A new data array where all the surface dimensions
have been flattened in to one linear array.
The values for each cell are in the same order as the linear index for this grid.
Any other dimensions, such as depth or time, will be retained.
Wind a flattened DataArray
so that it has the same shape as this grid.
By using size and wind() together
it is possible to construct new data variables for a dataset
of any arbitrary shape.
Parameters:
data_array (xarray.DataArray) – One of the data variables from this dataset.
axis (int, optional) – The axis number that should be wound.
Optional, defaults to the last axis.
Mutually exclusive with the linear_dimension parameter.
linear_dimension (Hashable, optional) – The name of the dimension in the data array that should be wound.
Optional, defaults to the last dimension.
Mutually exclusive with the axis parameter.
Returns:
xarray.DataArray – A new data array where the linear data have been wound
to match the shape of this grid.
Any other dimensions, such as depth or time, will be retained.
Examples
The following will construct a data array of the correct shape
for any convention supported by emsarray:
All datasets define variables on one or more grid.
GridKind enumerates all the available grids for a specific convention,
while Grid provides methods for introspecting a particular grid.
The GridKind for a dataset is usually an enum.Enum listing each different kind of grid.
Notes
Index values will be included in the feature properties
of exported geometry from emsarray.operations.geometry.
As the native index for a convention usually includes the grid kind,
the grid kind needs to be JSON serializable.
The easiest way to achieve this is to make your GridKind type subclass str:
An index to a specific point on a grid in this convention.
For conventions with multiple grids (e.g. cells, edges, and nodes),
this should be a tuple whos first element is GridKind.
For conventions with a single grid, GridKind is not required.
Most dataset conventions have grids that are uniquely identifiable by their dimensions.
For these conventions the DimensionConvention subclass provides many default implementations.
These details are most relevant for developers implementing new Convention subclasses.
The dimensions associated with a particular grid kind.
This is a mapping between gridkinds
and an ordered list of dimension names.
Each dimension in the dataset must be associated with at most one grid kind.
Each grid kind must be associated with at least one dimension.
The dimensions must be in the order expected in a dataset,
if order is significant.
This property may introspect the dataset
to determine which dimensions are used.
The property should be cached.
A Grid subclass that complements DimensionConvention.
Has one extra required argument dimensions,
and provides an implementation of all abstract Grid methods.
How specific a match is when autodetecting a convention.
Matches with higher specificity will be prioritised.
General conventions such as CF Grid are low specificity,
as many conventions extend and build on CF Grid conventions.
The SHOC conventions extend the CF grid conventions,
so a SHOC file will be detected as both CF Grid and SHOC.
ShocStandard should return a higher specificity
so that the correct convention implementation is used.