Reprojecting to EPSG:4326, HEALPix and Lambert
Note
Download the executable 04_reprojection_targets.ipynb to run this tutorial in JupyterLab.
A geostationary instrument sees the Earth from one point in space, so its native grid is a projection of a disc, not a map. Reprojection puts that data onto a grid you choose.
This tutorial takes one MSG SEVIRI granule and reprojects it three ways: to plate carree (EPSG:4326), the grid most tools expect; to HEALPix, the equal-area sphere tiling that machine-learning weather models use; and to Lambert Conformal Conic (EPSG:3034), a regional projection in metres. All three use the same reprojection step. Each target has its own resolution and resampling settings, and the Lambert example first cuts the disc down to Europe.
Before running this notebook, complete the shared setup in Tutorials.
Prerequisites
No. 1 Input data
The notebook reads these products from the public demo bucket of the DestinE Data Lake, without an account or credentials:
One MSG SEVIRI native file
To use your own files instead, change the path in MSG_URI and follow
Prepare data access for DEFAIR. It explains
how to read them from your own object store, from a local disk or
through HDA.
No. 2 A different HEALPix grid, if you change the example
The example uses NSIDE = 128. To choose another value, read HEALPix
nside selection before running the
reprojection. It explains the average sampling distance for each value
and the aliasing to watch for when the target is coarser than the
instrument.
Set up the notebook
import time
from pathlib import Path
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import healpy as hp
import matplotlib.pyplot as plt
import numpy as np
import pyproj
from defair.logging import setup_logging
from defair_data.core import Dataset
from defair_data.dask_manager import close_dask_client
# Readers log every step at DEBUG. WARNING keeps this notebook's output to what the
# tutorial prints, and is the level to raise when a read does something unexpected.
setup_logging(log_level="WARNING")
# cartopy, healpy and matplotlib come from the notebooks extra:
# pip install "defair[notebooks]"
# The public Data Lake demo bucket, which needs no credentials.
MSG_URI = "s3://datalake-demo-data/defair-notebook-data/msg-seviri-l15/MSG3-SEVI-MSG15-0100-NA-20260626111243.441000000Z-NA.nat"
PUBLIC_S3 = {"endpoint_url": "https://s3.central.data.destination-earth.eu", "anon": True}
CHANNEL = "IR_108" # the 10.8 micron infrared window
# EPSG:4326, in degrees because the target CRS is in degrees
EPSG_RESOLUTION = 0.05 # about 5.5 km at the equator
EPSG_RESAMPLING = "bilinear"
# HEALPix: nside 128 gives cells of about 0.46 degrees, a 50.9 km average sampling distance
NSIDE = 128
HEALPIX_RESAMPLING = "mean"
# Lambert Conformal Conic over Europe, on a 5 km grid in metres
LAMBERT_TARGET = "EPSG:3034"
LAMBERT_RESOLUTION = 5000
LAMBERT_WINDOW = {"lat_min": 33.0, "lat_max": 72.0, "lon_min": -25.0, "lon_max": 45.0}
# The display range the full-disc figures below are drawn on. The Lambert crop takes its
# own, because the shared range spans the whole disc and would flatten one region of it.
PERCENTILE_MIN, PERCENTILE_MAX = 2, 98
OUTPUT_DIR = Path("output")
OUTPUT_DIR.mkdir(exist_ok=True)
print(f"granule: {MSG_URI}")
print(f"channel: {CHANNEL}")
print(f"figures: {OUTPUT_DIR}/")
granule: s3://datalake-demo-data/defair-notebook-data/msg-seviri-l15/MSG3-SEVI-MSG15-0100-NA-20260626111243.441000000Z-NA.nat
channel: IR_108
figures: output/
The native geostationary grid
Read first, and look at what the instrument actually produces before anything is moved.
dataset_native = Dataset.from_source(
MSG_URI, reader="msg15nat", source="s3", source_kwargs=PUBLIC_S3,
use_channel_names=True, channels=[CHANNEL],
)
print(f"dimensions: {dict(dataset_native.data.sizes)}")
print(f"variables: {list(dataset_native.data.data_vars)}")
print(f"coordinates: {list(dataset_native.data.coords)}")
crs_wkt = dataset_native.data.coords["spatial_ref"].attrs["crs_wkt"]
print(f"\nnative CRS: {crs_wkt[:100]}...")
print("\nchannel metadata:")
for key in ("units", "long_name", "standard_name"):
if key in dataset_native.data[CHANNEL].attrs:
print(f" {key}: {dataset_native.data[CHANNEL].attrs[key]}")
dimensions: {'time': 1, 'y': 3712, 'x': 3712, 'bnds': 2}
variables: ['IR_108', 'geostationary']
coordinates: ['time', 'x', 'y', 'spatial_ref', 'time_bnds']
native CRS: PROJCS["unknown",GEOGCS["unknown",DATUM["unknown",SPHEROID["unknown",6378169,295.488065897014]],PRIM...
channel metadata:
units: mW m-2 sr-1 (cm-1)-1
long_name: SEVIRI infrared 10.8 micron radiance
standard_name: toa_outgoing_radiance_per_unit_wavenumber
data_native = dataset_native.data[CHANNEL].isel(time=0).compute()
vmin, vmax = (float(v) for v in np.nanpercentile(data_native.values, [PERCENTILE_MIN, PERCENTILE_MAX]))
units = data_native.attrs.get("units", "")
long_name = data_native.attrs.get("long_name", "Radiance")
print("data statistics:")
print(f" min: {float(data_native.min()):.2f}")
print(f" max: {float(data_native.max()):.2f}")
print(f" mean: {float(data_native.mean()):.2f}")
print(f" std: {float(data_native.std()):.2f}")
print(f" display range ({PERCENTILE_MIN} to {PERCENTILE_MAX} percentile): [{vmin:.2f}, {vmax:.2f}]")
figure, axis = plt.subplots(figsize=(12, 10))
# origin="upper": DEFAIR returns a canonical north-up array, so row 0 is the north.
image = axis.imshow(data_native.values, cmap="viridis", aspect="equal", origin="upper", vmin=vmin, vmax=vmax)
axis.set_title(f"MSG {CHANNEL} on the native geostationary grid\n{long_name}", fontsize=14, fontweight="bold")
axis.set_xlabel("x (pixels)")
axis.set_ylabel("y (pixels)")
figure.colorbar(image, ax=axis, label=f"radiance ({units})" if units else "radiance")
plt.tight_layout()
plt.savefig(OUTPUT_DIR / "01_native_geostationary.png", dpi=150, bbox_inches="tight")
plt.show()
data statistics:
min: 4.10
max: 175.72
mean: 91.30
std: 28.53
display range (2 to 98 percentile): [25.01, 152.75]
EPSG:4326
Plate carree: latitude and longitude as a regular grid. resolution
is in degrees here, because the target CRS is in degrees.
Each reprojection below prints one warning. geostationary is the CF
grid-mapping variable that came with the read: it describes the source
projection rather than holding data, so there is nothing in it to
resample and the reprojection skips it, writing a grid mapping for the
target grid instead.
# The transform returns a Dask array, so the elapsed time below is the cost of describing
# the warp. The warp itself runs at the .compute() in the figure cell that follows.
print("reprojecting to EPSG:4326...")
start_time = time.time()
dataset_epsg = dataset_native.transform(
name="reprojection",
target="EPSG:4326",
resolution=EPSG_RESOLUTION,
resampling=EPSG_RESAMPLING,
)
print(f"\nreprojection graph built in {time.time() - start_time:.2f} s")
print(f" dimensions: {dict(dataset_epsg.data.sizes)}")
print(f" coordinates: {list(dataset_epsg.data.coords)}")
print(f" new CRS: {dataset_epsg.data.coords['spatial_ref'].attrs['crs_wkt'][:100]}...")
reprojecting to EPSG:4326...
reprojection graph built in 0.97 s
dimensions: {'time': 1, 'lon': 3295, 'lat': 3294, 'bnds': 2}
coordinates: ['time', 'lon', 'lat', 'spatial_ref', 'time_bnds']
new CRS: GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]],PRIMEM["Greenwich",0],UNI...
# The reprojected grid must be finite and north-up: a flipped or rotated result would still
# plot, so the check is an assertion rather than an eyeball.
lat_axis = np.asarray(dataset_epsg.data["lat"].values, dtype=float)
if lat_axis.ndim == 2:
lat_axis = lat_axis[:, 0]
assert np.isfinite(lat_axis).all(), "reprojected lat contains non-finite values"
assert (np.diff(lat_axis) < 0).all(), "reprojected lat is not strictly descending (north-up)"
print("EPSG:4326 grid is finite and north-up")
EPSG:4326 grid is finite and north-up
data_epsg = dataset_epsg.data[CHANNEL].isel(time=0).compute()
lons, lats = data_epsg["lon"].values, data_epsg["lat"].values
figure = plt.figure(figsize=(14, 10))
axis = plt.axes(projection=ccrs.PlateCarree())
image = axis.pcolormesh(
lons, lats, data_epsg.values,
cmap="viridis", vmin=vmin, vmax=vmax, transform=ccrs.PlateCarree(), shading="auto",
)
axis.coastlines(resolution="50m", linewidth=1.0, color="white", alpha=0.8)
axis.add_feature(cfeature.BORDERS, linewidth=0.5, edgecolor="white", alpha=0.5)
gridlines = axis.gridlines(draw_labels=True, linewidth=0.5, alpha=0.5, linestyle="--", color="white")
gridlines.top_labels = gridlines.right_labels = False
axis.set_title(f"MSG {CHANNEL} on EPSG:4326\n{long_name}", fontsize=14, fontweight="bold")
figure.colorbar(image, ax=axis, label=f"radiance ({units})" if units else "radiance", shrink=0.8)
plt.tight_layout()
plt.savefig(OUTPUT_DIR / "02_epsg4326_geographic.png", dpi=150, bbox_inches="tight")
plt.show()
print(f"longitude range: [{lons.min():.2f}, {lons.max():.2f}] degrees")
print(f"latitude range: [{lats.min():.2f}, {lats.max():.2f}] degrees")
print(f"spacing: {abs(lons[1] - lons[0]):.4f} degrees lon, {abs(lats[1] - lats[0]):.4f} degrees lat")
longitude range: [-82.24, 82.46] degrees
latitude range: [-82.19, 82.46] degrees
spacing: 0.0500 degrees lon, 0.0500 degrees lat
HEALPix
HEALPix divides the sphere into equal-area cells, which is why it suits
models that must not weight one latitude more than another. nside
sets how finely the sphere is divided, and the guidance in HEALPix
nside selection explains how to choose one: the
average sampling distance it gives you, and the aliasing to watch for
when the target is coarser than the instrument.
# As above, this times the graph. The cell aggregation runs at the .compute() below.
print("reprojecting to HEALPix...")
start_time = time.time()
dataset_healpix = dataset_native.transform(
name="reprojection",
target=f"healpix:{NSIDE}",
resampling=HEALPIX_RESAMPLING,
)
print(f"\nreprojection graph built in {time.time() - start_time:.2f} s")
print(f" cells: {dataset_healpix.data.sizes['healpix_index']}")
print(f" average sampling distance: {hp.nside2resol(NSIDE, arcmin=True):.2f} arcmin")
print(f" dimensions: {dict(dataset_healpix.data.sizes)}")
reprojecting to HEALPix...
reprojection graph built in 2.22 s
cells: 196608
average sampling distance: 27.48 arcmin
dimensions: {'time': 1, 'healpix_index': 196608, 'bnds': 2}
data_healpix = dataset_healpix.data[CHANNEL].isel(time=0).compute()
cell_ids = dataset_healpix.data["healpix_index"]
# xdggs' grid identity, written by the reprojection: level 7 is nside 128.
actual_nside = 2 ** cell_ids.attrs["level"]
print(f"HEALPix grid: {cell_ids.attrs}, nside={actual_nside}")
# healpy draws a whole sky, so cells no geostationary instrument can see stay UNSEEN.
full_map = np.full(hp.nside2npix(actual_nside), hp.UNSEEN)
full_map[cell_ids.values] = data_healpix.values.ravel()
figure = plt.figure(figsize=(16, 8))
hp.mollview(
full_map,
title=f"MSG {CHANNEL} on HEALPix nside {actual_nside}, Mollweide\n{long_name}",
cmap="viridis", min=vmin, max=vmax, unit=units, fig=figure, cbar=True, hold=True,
flip="geo", # geographic convention: east on the right
)
hp.graticule()
plt.savefig(OUTPUT_DIR / "03_healpix_mollweide.png", dpi=150, bbox_inches="tight")
plt.show()
# half_sky=True: draw only the hemisphere this rotation faces, the one centred on Europe.
# A full-sky orthographic view would put the hemisphere turned away beside it, which is
# not the same thing as the half the satellite cannot see.
figure = plt.figure(figsize=(10, 10))
hp.orthview(
full_map,
title=f"MSG {CHANNEL} on HEALPix, orthographic over Europe\n{long_name}",
cmap="viridis", min=vmin, max=vmax, unit=units, fig=figure,
rot=[10, 45, 0], half_sky=True, hold=True, flip="geo",
)
hp.graticule()
plt.savefig(OUTPUT_DIR / "03b_healpix_orthographic.png", dpi=150, bbox_inches="tight")
plt.show()
HEALPix grid: {'grid_name': 'healpix', 'level': 7, 'indexing_scheme': 'ring'}, nside=128
Lambert Conformal Conic
EPSG:3034 is the ETRS89 Lambert Conformal Conic CRS defined for pan-European mapping at 1:500,000 and smaller, the conformal half of the INSPIRE pair whose equal-area half is EPSG:3035. DEFAIR takes any CRS rioxarray can build, so compared with the EPSG:4326 example only the target and the resolution change. The resolution is in metres here rather than degrees.
The spatial filter comes first, and belongs there. A regional projection applied to the whole disc draws a fan that reaches the limb, where one source pixel spans hundreds of kilometres and bilinear resampling onto 5 km cells exposes the source pixel boundaries as a saw-tooth edge. Cropping to Europe first is faster and is what the projection is for.
The figure below takes its own display range and colormap. The crop covers a fraction of the disc, so the range shared by the full-disc figures would flatten it.
europe = dataset_native.transform("spatial_filter", **LAMBERT_WINDOW)
dataset_lambert = europe.reproject(
LAMBERT_TARGET,
resolution=LAMBERT_RESOLUTION,
resolution_unit="meters",
resampling="bilinear",
)
print(f"Europe window: {dict(europe.data.sizes)}")
print(f"Lambert grid: {dict(dataset_lambert.data.sizes)}")
print(f"CRS: {dataset_lambert.data.rio.crs}")
Europe window: {'time': 1, 'y': 715, 'x': 1895, 'bnds': 2}
Lambert grid: {'time': 1, 'x': 1272, 'y': 916, 'bnds': 2}
CRS: EPSG:3034
field = dataset_lambert.data[CHANNEL].squeeze(drop=True).compute()
values = np.asarray(field.values, dtype=float)
finite = values[np.isfinite(values)]
# Local names. vmin and vmax hold the shared scale the three-panel comparison below draws
# every panel on, and rebinding them here would put that figure on this one's range.
lambert_vmin, lambert_vmax = np.percentile(finite, [PERCENTILE_MIN, PERCENTILE_MAX])
# Drawing on the target projection itself is what makes the orientation checkable: the
# coastlines are placed from the CRS, so they only line up if the data is where it claims.
lambert_crs = ccrs.Projection(pyproj.CRS.from_user_input(LAMBERT_TARGET))
x, y = field["x"].values, field["y"].values
half_x, half_y = abs(x[1] - x[0]) / 2, abs(y[1] - y[0]) / 2
figure = plt.figure(figsize=(10, 8))
axis = plt.axes(projection=lambert_crs)
# origin="upper" with y descending: the canonical north-up array again, row 0 in the north.
image = axis.imshow(
values, origin="upper", transform=lambert_crs, cmap="inferno",
vmin=lambert_vmin, vmax=lambert_vmax,
extent=[x[0] - half_x, x[-1] + half_x, y[-1] - half_y, y[0] + half_y],
)
axis.coastlines(resolution="50m", linewidth=0.6, color="white")
axis.gridlines(linewidth=0.2, alpha=0.5, linestyle="--", color="white")
axis.set_title(
f"MSG {CHANNEL} on the {LAMBERT_TARGET} 5 km grid over Europe", fontsize=13, fontweight="bold"
)
figure.colorbar(image, ax=axis, label=f"radiance ({units})" if units else "radiance", shrink=0.8)
plt.tight_layout()
plt.savefig(OUTPUT_DIR / "04_lambert_europe.png", dpi=150, bbox_inches="tight")
plt.show()
The three side by side
figure = plt.figure(figsize=(20, 6))
axis1 = plt.subplot(1, 3, 1)
image1 = axis1.imshow(data_native.values, cmap="viridis", aspect="equal", origin="upper", vmin=vmin, vmax=vmax)
axis1.set_title("Native geostationary\n(the instrument's own grid)", fontsize=11, fontweight="bold")
axis1.set_xlabel("x (pixels)")
axis1.set_ylabel("y (pixels)")
plt.colorbar(image1, ax=axis1, label=units, shrink=0.8)
axis2 = plt.subplot(1, 3, 2, projection=ccrs.PlateCarree())
image2 = axis2.pcolormesh(
lons, lats, data_epsg.values,
cmap="viridis", vmin=vmin, vmax=vmax, transform=ccrs.PlateCarree(), shading="auto",
)
axis2.coastlines(resolution="110m", linewidth=0.5, color="white")
axis2.gridlines(linewidth=0.3, alpha=0.5, linestyle="--", color="white")
axis2.set_title("EPSG:4326\n(geographic latitude and longitude)", fontsize=11, fontweight="bold")
plt.colorbar(image2, ax=axis2, label=units, shrink=0.8)
plt.subplot(1, 3, 3)
hp.mollview(
full_map, title="HEALPix\n(equal-area cells)", cmap="viridis", min=vmin, max=vmax,
unit=units, cbar=True, hold=True, sub=(1, 3, 3), notext=True, flip="geo",
)
plt.suptitle(f"MSG {CHANNEL}: the same data on three grids", fontsize=16, fontweight="bold", y=1.00)
# No tight_layout here: healpy's Mollweide axes are not compatible with it, and calling it
# commits a warning to the output for a layout it then leaves alone.
plt.savefig(OUTPUT_DIR / "05_projection_comparison.png", dpi=150, bbox_inches="tight")
plt.show()
What to do next
See Transform data for the resampling methods and when each is appropriate. Continue with Collocating geostationary and polar-orbiter data to put two instruments on one grid.
close_dask_client()