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: object

A 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 Grid gives two views:

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 to to_dataset().

Raises:

ValueError – If the coordinate shapes are inconsistent, or area_def has the wrong shape.

Examples

>>> 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 shape: tuple[int, int]#

Number of cells (ny, nx).

property size: int#

Total number of cells.

property is_rectilinear: bool#

True if the grid is defined by 1-D latitude and longitude vectors.

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 lat_ascending: bool#

True if latitude increases with the row index.

property lon_ascending: bool#

True if longitude increases with the column index.

property ivec: ndarray[tuple[Any, ...], dtype[int64]]#

Column indices 0 .. nx-1.

property jvec: ndarray[tuple[Any, ...], dtype[int64]]#

Row indices 0 .. ny-1.

property iarr: ndarray[tuple[Any, ...], dtype[int64]]#

2-D column index of every cell.

property jarr: ndarray[tuple[Any, ...], dtype[int64]]#

2-D row index of every cell.

property is_regular: bool#

True for a rectilinear grid with uniform latitude and longitude spacing.

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() and from_area_order().

to_area_order(data)[source]#

Reorder data from the grid’s row/column order to area_def order.

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:

ndarray[tuple[Any, …], dtype[Any]]

from_area_order(data)[source]#

Reorder data from area_def order to the grid’s own order.

The inverse of to_area_order().

Parameters:

data (array_like) – Array whose last two dimensions have the grid’s shape.

Returns:

numpy.ndarray – A view of data in the grid’s order.

Return type:

ndarray[tuple[Any, …], dtype[Any]]

property geometry: GridDefinition#

A pyresample.geometry.GridDefinition in the grid’s own order.

The definition also carries the ivec, jvec, iarr and jarr index arrays, so it can be used anywhere the old setup_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=1 this 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.ndarray of int) – Rows and columns, shape (n,) for k=1 and (n, k) (nearest first) otherwise. -1 for 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 dx: ndarray[tuple[Any, ...], dtype[float64]]#

Zonal cell width in metres, shape shape.

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 * dy otherwise.

property coords: dict[Hashable, Any]#

Coordinates for building xarray objects on this grid.

to_dataset(metrics=True)[source]#

Return the grid as an xarray.Dataset.

Parameters:

metrics (bool, optional) – Include dx, dy and area data variables. Default True.

Returns:

xarray.Dataset – Dataset with lat/lon coordinates on dims.

Return type:

Dataset

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 (tuple of str, 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:

xarray.DataArray

Return type:

DataArray

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')
isel(j=None, i=None)[source]#

Return the sub-grid of rows j and columns i.

Parameters:
  • j (slice, optional) – Row and column slices. Default: all.

  • i (slice, optional) – Row and column slices. Default: all.

Returns:

Grid

Return type:

Grid

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:

tuple[slice, slice]

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:

Grid

Return type:

Grid

See also

bbox_slices

the 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:
Returns:

Grid

Raises:

TypeError – If obj describes no grid.

Return type:

Grid

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).

Returns:

Grid – Centres at -89.75 … 89.75 and -179.75 … 179.75.

Return type:

Grid

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:

Grid

Return type:

Grid

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.Dataset or xarray.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 of lat, latitude, nav_lat, lats (and the lon equivalents) that exists.

  • lon (str, optional) – Names of the latitude and longitude variables. Default: the first of lat, latitude, nav_lat, lats (and the lon equivalents) 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:

Grid

seagrid.grids.from_settings(spec)[source]#

Build a grid from a settings entry.

A source’s settings section describes its grid with a grid key 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 (str or mapping) – The grid entry.

Returns:

Grid

Raises:

ValueError – If spec is not one of the forms above.

Return type:

Grid

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:

Grid

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:

Grid

Raises:

ValueError – If a range is not a whole number of cells.

Return type:

Grid

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

factories

Functions that build Grid objects.

grid

The Grid type: one definition of a horizontal grid for all of seagrid.

metrics

Cell metrics of horizontal grids: zonal and meridional widths and areas.