Interoperability: DEFAIR datasets in satpy and earthkit

Note

Download the executable 10_interoperability.ipynb to run this tutorial in JupyterLab.

A DEFAIR dataset is an xarray dataset with a data model attached, so anything that reads xarray can read it. This tutorial hands the same MSG SEVIRI granule to satpy, which builds composites and resamples with pyresample, and hands a Metop sea surface temperature field to earthkit, which selects and subsets it with ECMWF’s field tooling and hands it back as xarray unchanged.

Before running this notebook, complete the shared setup in Tutorials.

Prerequisites

No. 1 Python version and interoperability packages

Use Python 3.11 or newer for the satpy examples. Both satpy and earthkit-data are supplied by the notebooks extra.

No. 2 Input data

The notebook reads these products from the public demo bucket of the DestinE Data Lake, without an account or credentials:

  • MSG SEVIRI native data

  • Metop global sea surface temperature

To use your own files instead, change the paths in MSG_URI and GLBSST_URI and follow Prepare data access for DEFAIR.

Set up the notebook

# Environment provenance: record the exact interpreter and package versions
# before any third-party import, so even an import failure leaves a usable log.
import sys
from importlib.metadata import PackageNotFoundError, version

print(f"python {sys.version.split()[0]}")
for pkg in (
    "defair", "defair-data", "defair-ops", "xarray", "zarr", "dask",
    "satpy", "pyresample", "earthkit-data", "earthkit-meteo",
):
    try:
        print(f"{pkg} {version(pkg)}")
    except PackageNotFoundError:
        print(f"{pkg} NOT INSTALLED")
python 3.13.12
defair 0.4.3
defair-data 0.4.3
defair-ops 0.4.3
xarray 2025.11.0
zarr 3.4.0
dask 2025.3.0
satpy 0.60.0
pyresample 1.35.0
earthkit-data 0.18.6
earthkit-meteo 0.5.1
import json
import warnings
from datetime import datetime
from pathlib import Path

import matplotlib.pyplot as plt
import numpy as np
from pyresample.geometry import AreaDefinition
from satpy import Scene

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

# satpy, pyresample, cartopy and matplotlib come from the notebooks extra:
#     pip install "defair[notebooks]"
# The public Data Lake demo bucket, which needs no credentials.
PUBLIC_S3 = {"endpoint_url": "https://s3.central.data.destination-earth.eu", "anon": True}

# A mid-morning granule: two of the three composite bands below are visible channels, and
# at 17:27 UTC in October the terminator runs through Europe, which leaves them dark.
MSG_URI = (
    "s3://datalake-demo-data/defair-notebook-data/msg-seviri-l15/"
    "msg_f997b2b630fc42_MSG3-SEVI-MSG15-0100-NA-20251210102744.394000000Z-NA.nat"
)

OUTPUT_DIR = Path("output")
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)

satpy

satpy works in Scenes. Handing it a DEFAIR dataset gives it the channels it expects, and the resampling and the radiance RGB shown here then work as they would on a file satpy opened itself. The channels stay radiances: a composite that needs brightness temperatures or reflectances, such as satpy’s own enhanced overview or a thermal difference, needs those calibrated quantities first and is not demonstrated here.

dataset = Dataset.from_source(
    MSG_URI, reader="msg15nat", source="s3", source_kwargs=PUBLIC_S3, use_channel_names=True
)

print(f"Data variables: {list(dataset.data.data_vars)}")
print(f"Coordinates: {list(dataset.data.coords)}")
Data variables: ['VIS006', 'VIS008', 'IR_016', 'IR_039', 'WV_062', 'WV_073', 'IR_087', 'IR_097', 'IR_108', 'IR_120', 'IR_134', 'geostationary']
Coordinates: ['time', 'x', 'y', 'spatial_ref', 'time_bnds']
def defair_to_satpy_scene(dataset):
    """Convert a DEFAIR Dataset to a satpy Scene with the metadata satpy expects."""
    ds = dataset.data

    # 1. Build the AreaDefinition from the pixel coordinates.
    #
    # Not from the `source_area_extent` attribute: that attribute records the extent in the
    # instrument's native scan orientation, which runs south to north and east to west, while
    # the arrays DEFAIR ships are reoriented north-up and west-first. Handing pyresample the
    # attribute together with these arrays puts row 0 in the south and column 0 in the east,
    # which point-reflects the whole scene: a composite labelled Europe comes out showing the
    # Southern Ocean. The coordinates describe the array that is actually there.
    x, y = ds["x"].values, ds["y"].values
    dx, dy = abs(x[1] - x[0]), abs(y[1] - y[0])
    # pyresample wants (lower left x, lower left y, upper right x, upper right y), measured
    # to the outer edge of the corner pixels rather than to their centres.
    area_extent = (x[0] - dx / 2, y[-1] - dy / 2, x[-1] + dx / 2, y[0] + dy / 2)
    assert area_extent[0] < area_extent[2] and area_extent[1] < area_extent[3], area_extent

    area_def = AreaDefinition(
        area_id="msg_seviri_fes",
        description=ds.attrs.get("description", "MSG SEVIRI"),
        proj_id="geos",
        projection=json.loads(ds.attrs["projection"]),
        width=ds.sizes["x"],
        height=ds.sizes["y"],
        area_extent=area_extent,
    )

    # 2. Create Scene and populate with DEFAIR DataArrays
    scn = Scene()
    SKIP_VARS = ("geostationary", "spatial_ref")
    DROP_COORDS = ("lat", "lon", "spatial_ref", "geostationary")

    for var_name in ds.data_vars:
        if var_name in SKIP_VARS:
            continue
        da = ds[var_name]
        channel_name = da.attrs.get("name", var_name)
        da = da.drop_vars([c for c in DROP_COORDS if c in da.coords])
        # Squeeze singleton time dim — SatPy expects 2D (y, x) DataArrays,
        # and pyresample's bilinear resampler fails on 3D input
        if "time" in da.dims and da.sizes["time"] == 1:
            da = da.squeeze("time", drop=False)
        da.attrs["area"] = area_def
        da.attrs.setdefault("sensor", {"seviri"})

        # Deserialize time_parameters from JSON string to dict (SatPy expects dict)
        if "time_parameters" in da.attrs and isinstance(da.attrs["time_parameters"], str):
            da.attrs["time_parameters"] = json.loads(da.attrs["time_parameters"])

        # Convert start_time/end_time from strings to datetime (SatPy convention)
        for tkey in ("start_time", "end_time"):
            if tkey in da.attrs and isinstance(da.attrs[tkey], str):
                try:
                    da.attrs[tkey] = datetime.fromisoformat(da.attrs[tkey])
                except ValueError:
                    pass  # Keep as string if unparseable

        scn[channel_name] = da

    return scn


scene = defair_to_satpy_scene(dataset)
print(f"Scene datasets: {sorted(str(k) for k in scene.keys())}")
print(f"Sensor names: {scene.sensor_names}")

area = scene["IR_108"].attrs["area"]
print(f"\narea extent from the coordinates:      {tuple(round(float(v), 1) for v in area.area_extent)}")
print(f"source_area_extent (native scan):  {dataset.data.attrs['source_area_extent']}")
Scene datasets: ["DataID(name='IR_016', resolution=3000.403165817)", "DataID(name='IR_039', resolution=3000.403165817)", "DataID(name='IR_087', resolution=3000.403165817)", "DataID(name='IR_097', resolution=3000.403165817)", "DataID(name='IR_108', resolution=3000.403165817)", "DataID(name='IR_120', resolution=3000.403165817)", "DataID(name='IR_134', resolution=3000.403165817)", "DataID(name='VIS006', resolution=3000.403165817)", "DataID(name='VIS008', resolution=3000.403165817)", "DataID(name='WV_062', resolution=3000.403165817)", "DataID(name='WV_073', resolution=3000.403165817)"]
Sensor names: {'seviri'}

area extent from the coordinates:      (-5570248.5, -5567248.1, 5567248.1, 5570248.5)
source_area_extent (native scan):  [5567248.074173927, 5570248.477339745, -5570248.477339745, -5567248.074173927]
print(f"Datasets in scene: {len(list(scene.keys()))}")
print(f"IR_108 area type: {type(scene['IR_108'].attrs.get('area', None)).__name__}")
Datasets in scene: 11
IR_108 area type: AreaDefinition
# Close Dask distributed client before resampling — pyresample's bilinear
# resampler uses pykdtree internally, which can't be serialized through
# Dask distributed. The default threaded scheduler handles it fine.
close_dask_client()

with warnings.catch_warnings():
    # pyresample evaluates the geostationary geolocation over the whole target grid, so the
    # cells that fall off the disc make cos and sin report invalid values, and pyproj warns
    # that a PROJ string cannot carry everything the WKT CRS holds. Neither affects the
    # resampled data.
    warnings.filterwarnings("ignore", message="invalid value encountered in cos")
    warnings.filterwarnings("ignore", message="invalid value encountered in sin")
    warnings.filterwarnings("ignore", message="You will likely lose important projection information")
    # overview_raw uses these three bands; resample only what the figures need.
    resampled = scene.resample("euro4", datasets=["VIS006", "VIS008", "IR_108"], resampler="bilinear")

print(f"Resampled datasets: {sorted(str(k) for k in resampled.keys())}")
print(f"IR_108 shape after resampling: {resampled['IR_108'].shape}")
Resampled datasets: ["DataID(name='IR_108', resolution=3000.403165817)", "DataID(name='VIS006', resolution=3000.403165817)", "DataID(name='VIS008', resolution=3000.403165817)"]
IR_108 shape after resampling: (1024, 1024)
resampled.load(["overview_raw", "IR_108"])

overview = resampled["overview_raw"]
print(f"Overview shape: {overview.shape}")
print(f"Bands: {list(overview.coords['bands'].values)}")
Overview shape: (3, 1024, 1024)
Bands: [np.str_('R'), np.str_('G'), np.str_('B')]
# The resampled area can hand cartopy its own CRS, so the coastlines below are placed by the
# projection rather than drawn on top of the image: they line up only if the composite is
# where the area definition says it is.
euro4_crs = overview.attrs["area"].to_cartopy_crs()

# Shape is (bands, y, x): transpose to (y, x, bands) for imshow
img = overview.values.transpose(1, 2, 0).copy()
# Build joint NaN mask: if ANY band is NaN at a pixel, mask ALL bands
nan_mask = np.any(np.isnan(img), axis=2)
img[nan_mask] = np.nan
# Each band is an independent physical channel (DEFAIR returns radiance for
# VIS006/VIS008/IR_108 alike). Stretch every band to [0, 1] on its OWN
# 2-98% percentile range: do NOT compare ranges across bands, since the
# IR radiance span dwarfs the VIS spans and would otherwise zero out R/G.
for i in range(img.shape[2]):
    band = img[:, :, i]
    valid = band[~np.isnan(band)]
    if valid.size > 0:
        vmin, vmax = np.nanpercentile(valid, [2, 98])
    else:
        vmin, vmax = 0.0, 1.0
    if vmax > vmin:
        img[:, :, i] = np.clip((band - vmin) / (vmax - vmin), 0, 1)
    else:
        img[:, :, i] = 0.0
img = np.nan_to_num(img, nan=0.0)

figure = plt.figure(figsize=(11, 10))
axis = plt.axes(projection=euro4_crs)
axis.imshow(img, transform=euro4_crs, extent=euro4_crs.bounds, origin="upper")
axis.coastlines(resolution="50m", linewidth=0.6, color="yellow")
axis.set_title(
    "satpy overview_raw composite from DEFAIR data, resampled to euro4\n"
    "red VIS006, green VIS008, blue IR_108, each radiance stretched on its own range",
    fontsize=12,
)
plt.tight_layout()
plt.savefig(OUTPUT_DIR / "overview_raw_euro4.png", dpi=150)
plt.show()
../../../../_images/10_interoperability_10_0.png

earthkit

earthkit wraps an xarray object in its own field abstraction, so a DEFAIR dataset can be listed, selected and subset with ECMWF tooling, then handed back as xarray with its values intact. The wrap is by reference rather than by copy, so the check below reads a field back through earthkit’s own selection instead of comparing the returned object.

import earthkit.data as ekd
import xarray as xr

GLBSST_URI = "s3://datalake-demo-data/defair-notebook-data/osisaf-metop-glbsst/S-OSI_-FRA_-MTOP-GLBSST_FIELD-202508010000Z"

# The window the subset below crops to
MEDITERRANEAN_BBOX = {"lat_min": 30.0, "lat_max": 46.0, "lon_min": -6.0, "lon_max": 36.0}

print(f"GLB-SST URI: {GLBSST_URI}")
GLB-SST URI: s3://datalake-demo-data/defair-notebook-data/osisaf-metop-glbsst/S-OSI_-FRA_-MTOP-GLBSST_FIELD-202508010000Z
glbsst_dataset = Dataset.from_source(
    GLBSST_URI,
    reader="metop_glbsst",
    source="s3",
    source_kwargs=PUBLIC_S3,
    variables=["sea_surface_temperature", "wind_speed"],
)

print(f"Dimensions: {dict(glbsst_dataset.data.sizes)}")
print(f"Variables: {list(glbsst_dataset.data.data_vars)}")
print(f"Coordinates: {list(glbsst_dataset.data.coords)}")
Dimensions: {'time': 1, 'lat': 3600, 'lon': 7200, 'bnds': 2}
Variables: ['sea_surface_temperature', 'wind_speed']
Coordinates: ['time', 'lat', 'lon', 'crs', 'time_bnds']
# Wrap the full Dask-backed dataset in earthkit-data
ek_glbsst_full = ekd.from_object(glbsst_dataset.data)
print(f"earthkit type: {type(ek_glbsst_full).__name__}")
print(f"Number of fields: {len(ek_glbsst_full)}")
print()
ek_glbsst_full.ls()
earthkit type: XArrayFieldList
Number of fields: 2
variable level valid_datetime units
0 sea_surface_temperature None 2025-08-01T00:00:00 kelvin
1 wind_speed None 2025-08-01T00:00:00 m s-1
# Spatial subset via earthkit's xarray accessor, which stays Dask-lazy.
# Both sides run south to north: the product's own latitude axis ascends, from -89.97 to
# 89.97, and earthkit keeps that order, so one slice reads the same window on either.
med_xr = ek_glbsst_full.to_xarray().sel(
    lat=slice(MEDITERRANEAN_BBOX["lat_min"], MEDITERRANEAN_BBOX["lat_max"]),
    lon=slice(MEDITERRANEAN_BBOX["lon_min"], MEDITERRANEAN_BBOX["lon_max"]),
)
print(f"Subsetted (still lazy): {dict(med_xr.sizes)}")
print(f"Dask-backed: {hasattr(med_xr['sea_surface_temperature'].data, 'dask')}")

# Compute the small subset (~320x840 grid points)
med_ds = med_xr.compute()
print(f"Computed: {dict(med_ds.sizes)}")

# Re-wrap computed subset in earthkit
ek_glbsst = ekd.from_object(med_ds)
print(f"\nearthkit fields: {len(ek_glbsst)}")
ek_glbsst.ls()
Subsetted (still lazy): {'time': 1, 'lat': 320, 'lon': 840, 'bnds': 2}
Dask-backed: True
Computed: {'time': 1, 'lat': 320, 'lon': 840, 'bnds': 2}

earthkit fields: 2
variable level valid_datetime units
0 sea_surface_temperature None 2025-08-01T00:00:00 kelvin
1 wind_speed None 2025-08-01T00:00:00 m s-1

The round trip

from_object wraps the xarray object rather than copying it, so to_xarray() returns the object that was handed in: ekd.from_object(ds).to_xarray() is ds is true for the earthkit-data version printed in the first code cell. Comparing the two ends of that trip cannot fail whichever side the oracle takes, so the identity is asserted as an identity. What the field abstraction does do is index the dataset by variable, so the check that can fail selects one field by name and reads it back against DEFAIR’s own subset, values, dimensions and coordinates alike.

# from_object wraps rather than copies, so to_xarray() hands back the object that went in.
roundtrip = ek_glbsst.to_xarray()
assert roundtrip is med_ds
print("to_xarray() returned the wrapped object itself, so the trip cannot alter a value")

# The same window cut from DEFAIR's own dataset, with the same south-to-north slice.
defair_subset = (
    glbsst_dataset.data.sel(
        lat=slice(MEDITERRANEAN_BBOX["lat_min"], MEDITERRANEAN_BBOX["lat_max"]),
        lon=slice(MEDITERRANEAN_BBOX["lon_min"], MEDITERRANEAN_BBOX["lon_max"]),
    )
    ["sea_surface_temperature"]
    .compute()
)

# Selecting a field by name and reading it back is what the wrapper does do, and it can
# disagree with DEFAIR on values or on axes. The field is 2-D, so the oracle is the single
# time step, and assert_equal covers dimensions and coordinates as well as values.
sst_field = ek_glbsst.sel(param="sea_surface_temperature")[0]
xr.testing.assert_equal(sst_field.to_xarray(), defair_subset.isel(time=0))
print(f"earthkit field {sst_field.metadata('param')} matches DEFAIR's own subset, axes included")
to_xarray() returned the wrapped object itself, so the trip cannot alter a value
earthkit field sea_surface_temperature matches DEFAIR's own subset, axes included

What to do next

Continue with Three sources on one grid, then an AI cloud mask for a collocated training pipeline. It needs the defair-ai-demo package and PyTorch, as its Prerequisites section explains. The tutorial index also links two machine-learning notebooks that use DEFAIR output in training pipelines.

close_dask_client()