seagrid.grids.grid#

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

Module Attributes

LONGLAT_PROJECTION

pyresample projection used for regular latitude/longitude grids.

Classes

Grid(lat, lon, *[, name, area_def, attrs])

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