Note
Go to the end to download the full example code or to run this example in your browser via Binder.
Select data at a point, in a box, a circle or a polygon#
In this tutorial, we show how to:
get the
iselindexers of a box, a circle or a polygon, on a rectangular grid, a curvilinear grid or a cloud of points,choose between the smallest window that covers the shape and a mask (
outer), or the largest window with only points inside (inner),add a margin of grid points, down to the cell edges, or of a distance,
select a point, with scalar
lonandlat, or the nearest points to targets, among the valid ones if needed,reuse a selection for several arrays.
Distances are great circle ones, and the shapes can cross the dateline. See also: Find neighbors on the sphere.
Initialisations#
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import numpy as np
import xarray as xr
import xoa # noqa: F401
from xoa.core.grid import create_rotated_grid
from xoa.geo import GeoSelector, geosel, get_geosel, with_geosel
from xoa.plot import plot_box, plot_circle, plot_polygon
plt.rcParams.update({"font.size": 9, "axes.titlesize": 10, "axes.titleweight": "bold"})
pc = ccrs.PlateCarree()
def new_map(ncols=1, width=4.5, extent=(-7, -2, 45, 49.5)):
"""Create a figure with maps"""
fig, axes = plt.subplots(
1,
ncols,
figsize=(width * ncols, 3.8),
subplot_kw={"projection": pc},
constrained_layout=True,
squeeze=False,
)
for ax in axes[0]:
ax.set_extent(extent, crs=pc)
ax.gridlines(draw_labels=True, linewidth=0.3, color="0.5")
return fig, axes[0]
def plot_selection(ax, grid, sel, color="C3", title=None):
"""Plot the points of a grid, those selected and those masked"""
lon, lat = grid.lon, grid.lat
sub = sel.apply(grid.sst)
ax.plot(lon.values.ravel(), lat.values.ravel(), ",", color="0.7", transform=pc)
ax.plot(sub.lon.values.ravel(), sub.lat.values.ravel(), ".", color="0.4", ms=3, transform=pc)
ok = sub.notnull().values.ravel()
ax.plot(
sub.lon.values.ravel()[ok], sub.lat.values.ravel()[ok], ".", color=color, ms=3, transform=pc
)
ax.set_title(title)
Two grids are used: a rectangular one and a rotated curvilinear one, made with
xoa.core.grid.create_rotated_grid().
lon = xr.DataArray(np.arange(-7.0, -2.0, 0.1), dims="lon", name="lon")
lat = xr.DataArray(np.arange(45.0, 49.5, 0.1), dims="lat", name="lat")
rect = xr.DataArray(
np.random.default_rng(0).random((lat.size, lon.size)),
dims=("lat", "lon"),
coords={"lon": lon, "lat": lat},
name="sst",
)
grid = create_rotated_grid(50, 40, -4.5, 47.0, 25.0, 4.5, 3.5)
curv = xr.Dataset(
{"sst": (("y", "x"), np.random.default_rng(1).random(grid["lon"].shape))},
coords={"lon": (("y", "x"), grid["lon"]), "lat": (("y", "x"), grid["lat"])},
)
A box on a rectangular grid#
On a rectangular grid, a box is exactly a pair of slices, so no mask is needed.
get_geosel() returns a GeoSelection, whose isel attribute
is passed to xarray.DataArray.isel(), or that is applied directly with
apply().
The longitudes of a box can cross the dateline: lon=(170, -170).
GeoSelection(isel={'lon': slice(16, 36, None), 'lat': slice(10, 30, None)}, mask=no)
None
(20, 20)
A box on a curvilinear grid#
The same box is not a rectangle of indices anymore. With fit="outer", the smallest
window that covers the box is returned with a mask of the points that are inside it,
applied by apply() (or mask=False to keep them). With
fit="inner", the largest window with only points inside is returned, and no mask is needed.
box = dict(lon=(-5.2, -3.8), lat=(46.2, 47.4))
fig, axes = new_map(2)
for ax, fit in zip(axes, ["outer", "inner"]):
sel = get_geosel(curv, fit=fit, **box)
plot_selection(ax, curv, sel, title=f'fit="{fit}"')
ax.plot([-5.2, -3.8, -3.8, -5.2, -5.2], [46.2, 46.2, 47.4, 47.4, 46.2], "k-", transform=pc)
print(fit, sel.isel, None if sel.mask is None else int(sel.mask.sum()))

outer {'y': slice(9, 27, None), 'x': slice(15, 34, None)} 205
inner {'y': slice(13, 23, None), 'x': slice(18, 30, None)} None
Circles and polygons#
A circle is given by its center and radius, in meters or in kilometers with units,
and a polygon by its vertices. The GeoSelector class analyses the grid once,
to make several selections, which can be applied to several arrays.
selector = GeoSelector(curv)
circle = selector.select(circle=(-4.5, 47.0, 100), units="km")
polygon = selector.select(polygon=[[-6, 46], [-4, 45.5], [-3.5, 47.5], [-5, 48.5]])
fig, axes = new_map(2)
plot_selection(axes[0], curv, circle, title="Circle of 100 km")
plot_selection(axes[1], curv, polygon, title="Polygon")
sst_circle, sst_polygon = circle.apply(curv.sst), polygon.apply(curv.sst)

A cloud of points#
Scattered observations, like those of a ship or of drifters, share a single dimension.
The selection is then a single array of indices, which is what isel needs, and there is
no mask. The geosel() function selects an array directly.
A margin in grid points makes no sense here: use a distance.
rng = np.random.default_rng(2)
obs = xr.Dataset(
{"temp": ("obs", rng.normal(14, 2, 400))},
coords={"lon": ("obs", rng.uniform(-7, -2, 400)), "lat": ("obs", rng.uniform(45, 49.5, 400))},
)
box_kw = dict(lon=(-6, -4.5), lat=(46, 47.5))
circle_kw = dict(circle=(-3.5, 48, 70), units="km")
polygon_kw = dict(polygon=[[-6, 46], [-4, 45.5], [-3.5, 47.5], [-5, 48.5]])
box = geosel(obs, **box_kw)
circle = geosel(obs, **circle_kw)
polygon = geosel(obs, **polygon_kw)
padded = geosel(obs, **circle_kw, pad=30, pad_units="km")
print(box.sizes["obs"], circle.sizes["obs"], padded.sizes["obs"])
39 22 60
The shapes are drawn with plot_box(), plot_circle() and
plot_polygon(), that take the same arguments as the selection. The circle is
a great circle one, and the margin of a circle is a larger radius.
fig, axes = new_map(3, width=3.4)
for ax, sub, title in zip(axes, [box, circle, polygon], ["Box", "Circle", "Polygon"]):
ax.plot(obs.lon, obs.lat, ".", color="0.7", ms=3, transform=pc)
ax.plot(sub.lon, sub.lat, ".", color="C3", ms=4, transform=pc)
ax.set_title(title)
plot_box(**box_kw, ax=axes[0])
plot_circle(circle_kw["circle"], units="km", ax=axes[1])
plot_polygon(polygon_kw["polygon"], ax=axes[2])
axes[1].plot(padded.lon, padded.lat, ".", color="C1", ms=3, transform=pc, zorder=0.5)
plot_circle((-3.5, 48, 100), units="km", ax=axes[1], edgecolor="C1", linestyle="--")
axes[1].set_title("Circle, and with 30 km margin")

Text(0.5, 1.085809777867711, 'Circle, and with 30 km margin')
The nearest observations to targets are found the same way, and the result is a pointwise selection.
sel = get_geosel(obs, nearest=([-6.0, -4.0], [46.0, 48.0]), units="km")
print(obs.isel(sel.isel).temp.values, sel.dist.values.round(1))
[10.41753835 15.99940284] [15.5 9.5]
Margins#
The pad argument grows the shape. In grid points, with pad_units="points", it uses
a local estimate of the grid step, from the cell edges, so it follows variable and rotated
cells. pad=1 adds about one point around the shape, and pad="edges" (which is 0.5)
selects the points whose cell touches the shape, which is what is needed to draw
the selection with pcolormesh. A distance is given with pad_units="km".

Selecting a point#
Scalar lon and lat select the nearest point, like isel(lon=35, lat=45) does with
indices, on any kind of grid or on a cloud of points. The geosel() function and
the geosel() accessor method return the data at that point, without
the horizontal dimensions.
print(curv.xoa.geosel(lon=-4.5, lat=46.5))
<xarray.Dataset> Size: 24B
Dimensions: ()
Coordinates:
lon float64 8B -4.499
lat float64 8B 46.46
Data variables:
sst float64 8B 0.8626
To get the indices and the distance to the point instead, give nearest=(lon, lat) to
get_geosel(). A scalar target gives integers, like isel does.
Several targets give a pointwise selection along a target dimension, and the distances
to them.
sel = get_geosel(rect, nearest=(-4.53, 47.02), units="km")
print(sel.isel, float(sel.dist))
print(rect.isel(sel.isel).values)
targets = ([-6.0, -5.0, -4.0], [46.0, 47.0, 48.0])
sel = get_geosel(curv, nearest=targets, units="km")
print(curv.isel(sel.isel).sst.values, sel.dist.values.round(1))
{'lon': 25, 'lat': 20} 3.1811328764183946
0.3924678243761738
[0.07732382 0.30168325 0.35142922] [4.7 3.9 2.4]
The nearest valid point#
A target on land has a land point as nearest neighbor, which has no data. With valid, the
search is restricted to the points of a boolean mask, or to the points that have data with
valid="auto", as given by get_valid_mask().
land = (lon > -4.3 + 0.5 * np.sin(4 * (lat - 45))).transpose("lat", "lon")
sst = rect.where(~land)
targets = ([-3.5, -3.0], [46.0, 47.5])
fig, axes = new_map(2, width=3.4)
for ax, valid in zip(axes, [None, "auto"]):
sel = get_geosel(sst, nearest=targets, units="km", valid=valid)
near = sst.isel(sel.isel)
ax.pcolormesh(lon, lat, np.where(land, 0, 1), cmap="Blues", transform=pc, shading="nearest")
ax.plot(*targets, "k^", transform=pc)
ax.plot(near.lon, near.lat, "ro", transform=pc)
ax.set_title(f"valid={valid!r}")
print(valid, near.values, sel.dist.values.round(1))

None [nan nan] [0. 0.]
auto [0.94367777 0.14770547] [59. 81.1]
Reusing a selector, and the decorator#
The selector analyses the grid once and makes as many selections as needed, which is
also done by the get_geosel() method of the xoa accessor, that
caches it, while its geosel() method applies the selection to the
object directly. The with_geosel() decorator adds a geosel argument to any
function that takes an array or dataset as first argument.
0.5012847032599971
0.4956501109558917
(14, 14)
Total running time of the script: (0 minutes 7.431 seconds)