seagrid.grids.grid#
The Grid type: one definition of a horizontal grid for all of seagrid.
Module Attributes
|
pyresample projection used for regular latitude/longitude grids. |
Classes
|
A horizontal grid: cell-centre coordinates, metrics and pyresample geometry. |
- class seagrid.grids.grid.Grid(lat, lon, *, name=None, area_def=None, attrs=None)[source]#
Bases:
objectA horizontal grid: cell-centre coordinates, metrics and pyresample geometry.
A grid is rectilinear when it is defined by 1-D latitude and longitude vectors, and curvilinear when it is defined by 2-D arrays (model grids such as GLORYS’ ORCA grid). The row and column order is always the order of the data arrays the grid describes. seagrid’s own sources return latitude ascending (south to north), but a grid built with
from_dataset()keeps whatever order the dataset has.pyresample counts rows from the north, so a
Gridgives two views:geometry: apyresample.geometry.GridDefinitionin the grid’s own row order. It is always safe to use with data arrays but holds the full 2-D coordinates in memory.area_def: apyresample.geometry.AreaDefinition, exact and cheap, for regular latitude/longitude or projected grids. Its rows run north to south; useto_area_order()andfrom_area_order()to convert data between the two orders.
- Parameters:
lat (
array_like) – Cell-centre latitudes and longitudes in degrees. Either both 1-D (rectilinear grid of shape(len(lat), len(lon))) or both 2-D with the same shape (curvilinear grid).lon (
array_like) – Cell-centre latitudes and longitudes in degrees. Either both 1-D (rectilinear grid of shape(len(lat), len(lon))) or both 2-D with the same shape (curvilinear grid).name (
str, optional) – Short identifier, e.g."nasa_l3_4km".area_def (
pyresample.geometry.AreaDefinition, optional) – The grid’s area definition, for projected grids that are not regular in latitude/longitude. Its shape must match the grid. Regular latitude/longitude grids get one automatically.attrs (
mapping, optional) – Free-form metadata, copied toto_dataset().
- Raises:
ValueError – If the coordinate shapes are inconsistent, or area_def has the wrong shape.
See also
seagrid.grids.regular_latlon,seagrid.grids.nasa_l3,seagrid.grids.from_dataset,seagrid.grids.from_area_defExamples
>>> import numpy as np >>> from seagrid.grids import Grid >>> grid = Grid(np.arange(-89.5, 90), np.arange(-179.5, 180), name="one_deg") >>> grid.shape, grid.is_rectilinear, grid.resolution ((180, 360), True, (1.0, 1.0)) >>> grid.area_def.shape (180, 360)
- property lat: ndarray[tuple[Any, ...], dtype[float64]]#
1-D for rectilinear grids, else 2-D (read-only).
- Type:
Cell-centre latitudes
- property lon: ndarray[tuple[Any, ...], dtype[float64]]#
1-D for rectilinear grids, else 2-D (read-only).
- Type:
Cell-centre longitudes
- property dims: tuple[str, str]#
("lat", "lon")if rectilinear, else("y", "x").- Type:
Dimension names
- property lats: ndarray[tuple[Any, ...], dtype[float64]]#
2-D cell-centre latitudes of shape
shape(read-only).For a rectilinear grid this is a broadcast view of
lat, so it takes no memory.
- property lons: ndarray[tuple[Any, ...], dtype[float64]]#
2-D cell-centre longitudes of shape
shape(read-only).For a rectilinear grid this is a broadcast view of
lon, so it takes no memory.
- property resolution: tuple[float, float] | None#
Cell size
(dlat, dlon)in degrees of a regular grid, else None.
- property area_def: AreaDefinition | None#
The pyresample area definition, or None for irregular/curvilinear grids.
Rows of the area definition run north to south and columns west to east, whatever the grid’s own order. Convert data with
to_area_order()andfrom_area_order().
- to_area_order(data)[source]#
Reorder data from the grid’s row/column order to
area_deforder.- Parameters:
data (
array_like) – Array whose last two dimensions have the grid’s shape.- Returns:
numpy.ndarray– A view of data with the rows (and if needed the columns) reversed, so that row 0 is the northernmost.- Raises:
ValueError – If the grid has no area definition, or data has the wrong shape.
- Return type:
- from_area_order(data)[source]#
Reorder data from
area_deforder to the grid’s own order.The inverse of
to_area_order().
- property geometry: GridDefinition#
A
pyresample.geometry.GridDefinitionin the grid’s own order.The definition also carries the
ivec,jvec,iarrandjarrindex arrays, so it can be used anywhere the oldsetup_grid()result was used. It holds the full 2-D coordinates, which is about 600 MB for a global 4 km grid.
- nearest(lon, lat, k=1)[source]#
Return the row, column and distance of the nearest cell centres.
On a regular latitude/longitude grid with
k=1this is the cell that contains the point, found by arithmetic. Otherwise a KD-tree of the cell centres on the unit sphere is searched (built once per grid), so distances are great-circle distances and the antimeridian needs no special care.- Parameters:
lon (
array_like) – Positions in decimal degrees, of the same shape (flattened).lat (
array_like) – Positions in decimal degrees, of the same shape (flattened).k (
int, optional) – Number of neighbours. Default 1.
- Returns:
j, i (
numpy.ndarrayofint) – Rows and columns, shape(n,)fork=1and(n, k)(nearest first) otherwise.-1for positions that are not finite.dist (
numpy.ndarray) – Great-circle distance to each cell centre, in metres (NaN where the index is-1).
- Return type:
tuple[ndarray[tuple[Any, …], dtype[int64]], ndarray[tuple[Any, …], dtype[int64]], ndarray[tuple[Any, …], dtype[float64]]]
Examples
>>> from seagrid.grids import regular_latlon >>> grid = regular_latlon(10.0) >>> j, i, dist = grid.nearest([179.0, -179.0], [5.0, 5.0]) >>> grid.lon[i].tolist(), grid.lat[j].tolist() ([175.0, -175.0], [5.0, 5.0])
- property dy: ndarray[tuple[Any, ...], dtype[float64]]#
Meridional cell height in metres, shape
shape.
- property area: ndarray[tuple[Any, ...], dtype[float64]]#
Cell area in m², shape
shape.Exact spherical areas for rectilinear grids,
dx * dyotherwise.
- to_dataset(metrics=True)[source]#
Return the grid as an
xarray.Dataset.- Parameters:
metrics (
bool, optional) – Includedx,dyandareadata variables. Default True.- Returns:
xarray.Dataset– Dataset withlat/loncoordinates ondims.- Return type:
- data_array(data, name=None, dims=None, attrs=None, **coords)[source]#
Wrap an array on this grid in an
xarray.DataArray.- Parameters:
data (
array_like) – Array whose last two dimensions have the grid’s shape.name (
str, optional) – Name of the DataArray.dims (
tupleofstr, optional) – Names of the leading (non-grid) dimensions, e.g.("time",). Default("dim_0", ...).attrs (
mapping, optional) – Attributes of the DataArray.**coords – Coordinates of the leading dimensions, e.g.
month=range(1, 13).
- Returns:
- Return type:
Examples
>>> from seagrid.grids import cbiomes_halfdeg >>> import numpy as np >>> grid = cbiomes_halfdeg() >>> da = grid.data_array(np.zeros((12, 360, 720)), dims=("month",), ... month=range(1, 13)) >>> da.dims ('month', 'lat', 'lon')
- bbox_slices(lat_bounds=None, lon_bounds=None)[source]#
Return the row and column slices of the cells inside a bounding box.
For a curvilinear grid the slices are those of the smallest index box that contains every cell whose centre is inside the bounding box.
- Parameters:
lat_bounds (
(float,float), optional) –(south, north)in degrees, inclusive. Default: no limit.lon_bounds (
(float,float), optional) –(west, east)in degrees, inclusive. Default: no limit.
- Returns:
j, i (
slice) – Row and column slices.- Raises:
ValueError – If no cell lies inside the bounding box.
- Return type:
- subset(lat_bounds=None, lon_bounds=None)[source]#
Return the sub-grid inside a bounding box.
- Parameters:
lat_bounds (
(float,float), optional) –(south, north)in degrees, inclusive.lon_bounds (
(float,float), optional) –(west, east)in degrees, inclusive.
- Returns:
- Return type:
See also
bbox_slicesthe index slices of the same box, for subsetting data.