seagrid.grids#
Horizontal grid definitions for every seagrid data source.
Grid is the single grid type in seagrid. It holds the cell-centre
coordinates, computes cell metrics, and gives pyresample geometries for
resampling. Grids are built with the factories in this package rather than
by hand.
Examples
>>> from seagrid import grids
>>> g = grids.nasa_l3("9km")
>>> g.shape, g.is_regular
((2160, 4320), True)
>>> g.subset(lat_bounds=(30, 60), lon_bounds=(-40, 0)).shape
(360, 480)
- class seagrid.grids.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.
- seagrid.grids.as_grid(obj, *, lat=None, lon=None)[source]#
Return obj as a
Grid, whatever kind of grid description it is.- Parameters:
obj (
Grid,pyresample geometry,xarray.Dataset,xarray.DataArrayorsource) – AGrid(returned as is); apyresample.geometry.AreaDefinition; apyresample.geometry.GridDefinitionor anything else with 2-Dlats/lons(rectilinear ones become 1-D grids); an xarray object (seefrom_dataset()); a grid name fromNAMED_GRIDS; or a data source (itsgrid()).lat (
str, optional) – Coordinate names, for xarray objects.lon (
str, optional) – Coordinate names, for xarray objects.
- Returns:
- Raises:
TypeError – If obj describes no grid.
- Return type:
Examples
>>> import numpy as np, pyresample as pr >>> lons, lats = np.meshgrid(np.arange(-179.5, 180), np.arange(-89.5, 90)) >>> as_grid(pr.geometry.GridDefinition(lons=lons, lats=lats)).is_regular True
- seagrid.grids.cbiomes_halfdeg()[source]#
Build the CBIOMES global 0.5° climatology grid (360 × 720 cells).
- seagrid.grids.from_area_def(area_def, *, lat_ascending=True, name=None)[source]#
Build a grid from a pyresample area definition.
- Parameters:
area_def (
pyresample.geometry.AreaDefinition) – The area. A plain latitude/longitude projection gives a rectilinear grid; any other projection gives a curvilinear grid that keeps area_def (rows north to south, as in pyresample).lat_ascending (
bool, optional) – For a latitude/longitude area: order rows south to north (default) or keep pyresample’s north-to-south order.name (
str, optional) – Grid name. Default:area_def.area_id.
- Returns:
- Return type:
- seagrid.grids.from_dataset(ds, lat=None, lon=None, *, name=None)[source]#
Build the grid of an xarray Dataset or DataArray from its coordinates.
- Parameters:
ds (
xarray.Datasetorxarray.DataArray) – Object with latitude and longitude coordinates (or variables), either 1-D or 2-D.lat (
str, optional) – Names of the latitude and longitude variables. Default: the first oflat,latitude,nav_lat,lats(and thelonequivalents) that exists.lon (
str, optional) – Names of the latitude and longitude variables. Default: the first oflat,latitude,nav_lat,lats(and thelonequivalents) that exists.name (
str, optional) – Grid name.
- Returns:
Grid– In the dataset’s own row and column order.- Raises:
KeyError – If no latitude or longitude variable is found.
- Return type:
- seagrid.grids.from_settings(spec)[source]#
Build a grid from a settings entry.
A source’s settings section describes its grid with a
gridkey in one of three forms:a name from
NAMED_GRIDS:grid = "nasa_l3_4km"
a regular latitude/longitude grid:
grid = { dlat = 0.05, lat_range = [-90, 90], lon_range = [-180, 180] }
a pyresample area definition, with the arguments of
pyresample.create_area_def():grid = { projection = "EPSG:3413", shape = [448, 304], area_extent = [-3850000, -5350000, 3750000, 5850000] }
- Parameters:
spec (
strormapping) – Thegridentry.- Returns:
- Raises:
ValueError – If spec is not one of the forms above.
- Return type:
Examples
>>> from_settings("nasa_l3_9km").shape (2160, 4320) >>> from_settings({"dlat": 1.0}).shape (180, 360)
- seagrid.grids.nasa_l3(resolution='4km')[source]#
Build a NASA OBPG Level-3 mapped (equal-angle, global) grid.
Used by MODIS, VIIRS, SeaWiFS, OLCI and OC-CCI mapped products.
- Parameters:
resolution (
{"1deg", "18km", "9km", "4km", "2km", "1km"}, optional) – Nominal resolution. Default"4km"(8640 × 4320 cells).- Returns:
Grid– Latitude ascending, longitude -180 … 180.- Raises:
ValueError – If resolution is not one of
NASA_L3_COLUMNS.- Return type:
Notes
The files themselves store latitude descending; the sources flip it on open so that data and grid agree.
Examples
>>> nasa_l3("9km").shape (2160, 4320)
- seagrid.grids.regular_latlon(dlat, dlon=None, *, lat_range=(-90.0, 90.0), lon_range=(-180.0, 180.0), lat_ascending=True, name=None)[source]#
Build a regular latitude/longitude grid from its cell size and extent.
Cell centres are half a cell inside the edges of the ranges, so a global 1° grid has centres at -89.5 … 89.5 and -179.5 … 179.5.
- Parameters:
dlat (
float) – Cell height in degrees of latitude.dlon (
float, optional) – Cell width in degrees of longitude. Default: dlat.lat_range (
(float,float), optional) – Southern and northern edge of the grid. Default(-90, 90).lon_range (
(float,float), optional) – Western and eastern edge of the grid. Default(-180, 180).lat_ascending (
bool, optional) – Order rows south to north (seagrid’s convention, the default) or north to south.name (
str, optional) – Grid name. Default"regular_<dlat>x<dlon>".
- Returns:
- Raises:
ValueError – If a range is not a whole number of cells.
- Return type:
Examples
>>> grid = regular_latlon(0.25, lat_range=(-80, 90)) >>> grid.shape, float(grid.lat[0]), float(grid.lat[-1]) ((680, 1440), -79.875, 89.875)
Modules