seagrid.geospatial#

Land masks, distance from land and cell areas on any Grid.

Examples

>>> import numpy as np
>>> from seagrid import geospatial, grids
>>> grid = grids.regular_latlon(10.0)
>>> land = grid.data_array(grid.lons > 150, name="land")
>>> dist = geospatial.distance_from_land(land)
>>> float(dist.sel(lat=5, lon=165))               # on land
0.0
>>> round(float(dist.sel(lat=5, lon=-175)))        # 10° east, across 180°, in km
1108
>>> round(float(dist.sel(lat=5, lon=135)))         # 20° west
2215

Module Attributes

GHRSST_LAND_BIT

GHRSST L4 mask bit for land (flag_masks = [1, 2, 4, 8, 16], "water land optional_lake_surface sea_ice optional_river_surface").

Functions

area_weighted_mask(grid[, seed])

Return a random mask whose density in each row is proportional to cell area.

cell_area(grid[, units])

Return the area of every cell of a grid.

distance_from_land(land[, grid, units])

Return the great-circle distance from every cell to the nearest land cell.

distance_from_land_ds(ds[, roll])

Return distance_from_land() of ds.landmask in km (the 2.x name).

distance_to_mask(lons, lats, mask)

Return the great-circle distance in metres from every cell to the mask.

fill_nearest(values, lons, lats, where[, empty])

Fill cells from the nearest cell that has a value.

global_land_mask([grid])

Return a land mask from the optional global-land-mask package.

landmask(elevation[, remove_islands, keep])

Return a land mask (True on land) from elevation or bathymetry.

landmask_from_elevation(elevation, grid, *)

Return a land mask on grid from a high-resolution elevation field.

landmask_from_flags(mask[, bit])

Return a land mask from a bit-flag variable such as the GHRSST L4 mask.

landmask_from_kmt(grid[, k])

Return the land mask of a model grid from its number of ocean levels.

rasterize(polygons, grid[, values, fill])

Return the polygon that contains each cell centre of grid.

sample_nearest(field, lat, lon, grid)

Return the value of the nearest cell of a regular lat/lon field on grid.

seagrid.geospatial.area_weighted_mask(grid, seed=12345)[source]#

Return a random mask whose density in each row is proportional to cell area.

Sampling the cells of a latitude/longitude grid where the mask is True gives each part of the globe a weight proportional to its area.

Parameters:
  • grid (Grid or pyresample geometry) – A rectilinear grid.

  • seed (int, optional) – Seed of the random generator. Default 12345 (as in 2.x).

Returns:

xarray.DataArray – Boolean.

Return type:

DataArray

seagrid.geospatial.cell_area(grid, units='m2')[source]#

Return the area of every cell of a grid.

Parameters:
  • grid (Grid or pyresample geometry)

  • units ({"m2", "km2"}, optional) – Default "m2".

Returns:

xarray.DataArray

Return type:

DataArray

Examples

>>> from seagrid import grids
>>> area = cell_area(grids.cbiomes_halfdeg(), units="km2")
>>> round(float(area.sum()) / 1e6)   # million km², the whole sphere
510
seagrid.geospatial.distance_from_land(land, grid=None, *, units='km')[source]#

Return the great-circle distance from every cell to the nearest land cell.

Distances are between cell centres on the sphere, so they are correct at the antimeridian and near the poles.

Parameters:
  • land (array_like or xarray.DataArray) – Boolean land mask (True on land), e.g. from landmask().

  • grid (Grid or pyresample geometry, optional) – Grid of land. Default: from the DataArray’s coordinates.

  • units ({"km", "m"}, optional) – Default "km".

Returns:

numpy.ndarray or xarray.DataArray – Distance; 0 on land. A DataArray if land is one.

Raises:

ValueError – If there is no land, or units is unknown.

Return type:

ndarray[tuple[Any, …], dtype[float64]] | DataArray

seagrid.geospatial.distance_from_land_ds(ds, roll=False)[source]#

Return distance_from_land() of ds.landmask in km (the 2.x name).

roll is ignored: distances on the sphere need no shift at the antimeridian.

Parameters:
Return type:

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

seagrid.geospatial.global_land_mask(grid=None)[source]#

Return a land mask from the optional global-land-mask package.

Parameters:

grid (Grid or pyresample geometry, optional) – Default: the CBIOMES 0.5° grid.

Returns:

xarray.DataArray – True on land.

Raises:

ImportError – If global-land-mask is not installed.

Return type:

DataArray

seagrid.geospatial.distance_to_mask(lons, lats, mask)[source]#

Return the great-circle distance in metres from every cell to the mask.

Only mask cells next to a cell outside the mask (8 neighbours, with the last axis periodic) are searched, since any other mask cell is farther away. The search is a KD-tree of unit vectors, so it is exact on curvilinear grids and across the antimeridian.

Parameters:
  • lons (array_like) – Cell-centre coordinates in degrees, the shape of mask.

  • lats (array_like) – Cell-centre coordinates in degrees, the shape of mask.

  • mask (array_like) – Boolean, 2-D: True on the cells distances are measured to (land).

Returns:

numpy.ndarray – Distance in metres; 0 inside the mask.

Raises:

ValueError – If the mask is empty.

Return type:

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

Examples

>>> import numpy as np
>>> lons, lats = np.meshgrid([0.0, 1.0, 2.0], [0.0])
>>> distance_to_mask(lons, lats, [[True, False, False]]).round(-3) / 1000
array([[  0., 111., 222.]])
seagrid.geospatial.fill_nearest(values, lons, lats, where, empty=0)[source]#

Fill cells from the nearest cell that has a value.

Parameters:
  • values (array_like) – 2-D field; empty marks cells without a value.

  • lons (array_like) – Cell-centre coordinates in degrees, the shape of values.

  • lats (array_like) – Cell-centre coordinates in degrees, the shape of values.

  • where (array_like of bool) – The cells to fill if they are empty (e.g. the ocean); other cells are left as they are.

  • empty (int, optional) – The value of empty cells. Default 0.

Returns:

numpy.ndarray – A copy of values with the empty cells in where set to the value of the nearest (great-circle) non-empty cell.

Return type:

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

Examples

>>> lons, lats = np.meshgrid([0.0, 1.0, 2.0, 3.0], [0.0])
>>> fill_nearest([[5, 0, 0, 7]], lons, lats, [[True, True, True, False]])
array([[5, 5, 7, 7]])
seagrid.geospatial.landmask(elevation, remove_islands=False, keep=6)[source]#

Return a land mask (True on land) from elevation or bathymetry.

Parameters:
  • elevation (array_like or xarray.DataArray) – Elevation in metres, positive above sea level (GEBCO convention).

  • remove_islands (bool, optional) – Keep only the keep largest connected land masses. Default False.

  • keep (int, optional) – Number of land masses kept by remove_islands. Default 6.

Returns:

numpy.ndarray or xarray.DataArray – Boolean, the same type and shape as elevation.

Return type:

ndarray[tuple[Any, …], dtype[bool]] | DataArray

seagrid.geospatial.landmask_from_elevation(elevation, grid, *, threshold=0.5)[source]#

Return a land mask on grid from a high-resolution elevation field.

The elevation (e.g. GEBCO’s 15 arc-second grid) is reduced to the land fraction of blocks about the size of a cell of grid (one pass over the field with dask, so it never has to fit in memory), and each cell of grid takes the block nearest to its centre. A cell is land when the fraction is above threshold. When the cell size of grid is a whole multiple of the elevation’s and the cells line up (all regular seagrid grids on GEBCO), the blocks are exactly the cells.

Parameters:
  • elevation (xarray.DataArray) – Elevation in metres, positive up, on 1-D lat and lon (regular, ascending; may be dask-backed).

  • grid (Grid or anything :func:`seagrid.grids.as_grid accepts`) – The grid of the mask.

  • threshold (float, optional) – Land fraction above which a cell is land. Default 0.5.

Returns:

xarray.DataArray – Boolean on grid, True on land.

Return type:

DataArray

Examples

>>> import numpy as np, xarray as xr
>>> from seagrid import grids
>>> lat = np.arange(-89.75, 90, 0.5)
>>> lon = np.arange(-179.75, 180, 0.5)
>>> elev = xr.DataArray(
...     np.where(lon > 0, 100.0, -100.0)[None, :].repeat(lat.size, 0),
...     coords={"lat": lat, "lon": lon}, dims=("lat", "lon"))
>>> land = landmask_from_elevation(elev, grids.regular_latlon(10.0))
>>> land.sel(lat=5, lon=[-5, 5]).values.tolist()
[False, True]
seagrid.geospatial.landmask_from_flags(mask, bit=GHRSST_LAND_BIT)[source]#

Return a land mask from a bit-flag variable such as the GHRSST L4 mask.

Parameters:
  • mask (array_like) – Flag values. Missing values (NaN) count as not land.

  • bit (int, optional) – The land bit. Default 2, the GHRSST L4 land flag (lakes, bit 4, are not land, as in GEBCO, where a lake surface below sea level is not land either).

Returns:

numpy.ndarray – Boolean, True where the bit is set.

Return type:

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

Examples

>>> landmask_from_flags([1, 2, 4, 10, np.nan])
array([False,  True, False,  True, False])
seagrid.geospatial.landmask_from_kmt(grid, k=1)[source]#

Return the land mask of a model grid from its number of ocean levels.

Parameters:
  • grid (xarray.Dataset) – A model grid definition (e.g. glorys.grid_definition()) with kmt, the number of ocean levels in each column (0 on land), on (y, x), and lon/lat coordinates.

  • k (int, optional) – 1-based model level. Default 1 (the surface): land is kmt == 0. Deeper, the sea floor counts as land too: kmt < k.

Returns:

xarray.DataArray – Boolean (y, x), True on land, with the grid’s lon/lat.

Raises:

ValueError – If k is below 1.

Return type:

DataArray

Examples

>>> import xarray as xr
>>> grid = xr.Dataset({"kmt": (("y", "x"), [[0, 2, 5]])})
>>> landmask_from_kmt(grid, k=3).values
array([[ True,  True, False]])
seagrid.geospatial.rasterize(polygons, grid, values=None, fill=0)[source]#

Return the polygon that contains each cell centre of grid.

Parameters:
  • polygons (sequence of shapely geometries) – Polygons or multipolygons in longitude/latitude degrees (-180–180). Where they overlap, the later one wins.

  • grid (Grid or anything :func:`seagrid.grids.as_grid accepts`) – The target grid; its longitudes may be in any range.

  • values (array_like of int, optional) – Value of each polygon. Default 1, 2, ..., len(polygons).

  • fill (int, optional) – Value of cells in no polygon. Default 0.

Returns:

xarray.DataArray – int16 on grid.

Return type:

DataArray

Examples

>>> from shapely.geometry import box
>>> from seagrid import grids
>>> out = rasterize([box(-180, -90, 0, 90), box(0, 0, 180, 90)],
...                 grids.regular_latlon(90.0))
>>> out.values.tolist()
[[1, 1, 0, 0], [1, 1, 2, 2]]
seagrid.geospatial.sample_nearest(field, lat, lon, grid)[source]#

Return the value of the nearest cell of a regular lat/lon field on grid.

Parameters:
  • field (array_like) – 2-D (lat, lon) field.

  • lat (array_like) – Its 1-D cell centres, ascending, longitude in -180–180.

  • lon (array_like) – Its 1-D cell centres, ascending, longitude in -180–180.

  • grid (Grid or anything :func:`seagrid.grids.as_grid accepts`) – Target grid; any longitude range.

Returns:

numpy.ndarray – The field on grid (the dtype of field).

Return type:

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

Examples

>>> from seagrid import grids
>>> field = np.array([[1, 2], [3, 4]])
>>> sample_nearest(field, [-45.0, 45.0], [-90.0, 90.0],
...                grids.regular_latlon(90.0)).tolist()
[[1, 1, 2, 2], [3, 3, 4, 4]]