Three sources on one grid, then an AI cloud mask

Note

Download the executable msg_mtg_era5_collocation_ai_usecase.ipynb to run this tutorial in JupyterLab.

This notebook does two things end to end. First it brings three real datasets onto a single grid: Meteosat SEVIRI, MTG FCI and ERA5 are reprojected onto MSG’s geostationary grid, cropped to a box over Europe. Then it hands that cube to the defair-ai-demo cloud-mask U-Net and trains and runs it.

Prerequisites

No. 1 Shared tutorial setup

Complete the shared tutorial setup, so that DEFAIR and the packages the notebooks use are installed in the Jupyter kernel you will run.

No. 2 AI, plotting and GRIB dependencies

A plain DEFAIR install is not enough to run this notebook. It also needs:

  • defair-ai-demo, the cloud-mask model in sections 10 to 12. It is not part of the default install, so an ordinary DEFAIR environment does not have to carry PyTorch.

  • cartopy, for the map panels in sections 8 and 12. It comes with the notebooks extra.

  • earthkit-data, which reads the ERA5 GRIB file. The pip command below installs it too.

Install the pinned packages in the environment that runs the notebook. On Linux, install only the CPU PyTorch wheel from its own index, then resolve the remaining dependencies from PyPI:

python -m pip install --upgrade pip --index-url https://pypi.org/simple
python -m pip install --no-deps "torch==2.14.1+cpu" --index-url https://download.pytorch.org/whl/cpu
python -m pip install --index-url https://pypi.org/simple "defair[notebooks]==0.4.3" "defair-ai-demo==0.4.3" "numpy==2.3.4" "xarray==2025.11.0"
python -m pip check

The full tutorial completed with DEFAIR 0.4.3 and the pinned versions above on Fedora 44 with Python 3.12 on 5 October 2026. For macOS or another PyTorch build, use the installation guide linked from the shared tutorial setup.

The map panels use plotting helpers that ship with DEFAIR as defair.notebook_helpers, so you do not need any other file next to the notebook.

No. 3 Input data

The notebook reads the following products from the public demo bucket of the DestinE Data Lake. Anyone can read this bucket, so you only need an internet connection: no account and no credentials.

  • 12 MSG SEVIRI native files, *.nat

  • 18 MTG FCI FDHSI scenes, one folder per scene with its *CHK-BODY*.nc chunk files

  • One ERA5 file, *.grib

Section 2 sets one folder for each product, and section 3 loads the files from those folders.

No. 4 Using your own data

Section 3 selects every input file by its exact name, whether it reads from S3 or from local files. Putting files of the right type in the right folders is therefore not enough. Change these settings to match your files:

  • MSG_FILES in section 3, the names of the 12 MSG granules

  • MTG_SCENE_SUFFIXES in section 3, the endings of the 18 FCI scene names

  • ERA5_FILE in section 3, the name of the ERA5 file

  • N_TIMESTEPS in section 2, the number of FCI scenes you list

The notebook pairs each FCI scene with the MSG granule and the ERA5 field closest to it in time, however far apart they are. Take your MSG and ERA5 files from the same period as your FCI scenes, or the cube combines scenes taken hours apart without any error.

To read from your own object store, also change the s3 folders in section 2 and set SOURCE_KWARGS = {} there, so DEFAIR uses your own credentials, as the Data section of the tutorials page explains. MSG SEVIRI is available through the Destination Earth HDA service, but FCI Level 1c only from the EUMETSAT Data Store.

No. 5 Local files, if you use them instead of S3

Set COLLOCATION_SOURCE=local and put the files in msg_seviri/, mtg_fci_fdhsi/ and era5/ under test-data/collocation/. You have to create that folder yourself. The notebook looks for test-data/ in its own folder, or in the folder that COLLOCATION_BASE names. The file names from No. 4 must match there too.

The three sources

Source

Read with

Role

MSG SEVIRI (HRSEVIRI)

DEFAIR reader msg15nat

defines the output grid, plus one IR channel

MTG FCI L1c (FDHSI)

DEFAIR reader mtg_fci_l1c_nc

sets the time axis, plus one IR channel

ERA5 (GRIB)

earthkit-data

a meteorological context channel

DEFAIR ships no GRIB reader, so the ERA5 leg is read with earthkit-data and handed to Dataset as an xarray object. That is the general route for any format DEFAIR has no reader for.

The output grid is just MSG’s own grid narrowed to the area of interest, so every source lands on exactly the same pixels. It stays small enough to run the whole thing on a laptop.

1. Imports

import os

# Pin native thread pools to 1 BEFORE importing numpy/rioxarray, and disable tqdm progress bars.
# Each reprojection warp runs GDAL + numpy/BLAS + blosc, which otherwise oversubscribe the cores and
# thrash the GIL, hanging multi-timestep collocation. TQDM_DISABLE keeps the AI logs to a few lines.
for _v in (
    "OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS",
    "NUMEXPR_NUM_THREADS", "GDAL_NUM_THREADS", "BLOSC_NTHREADS", "PYKDTREE_OMP_NUM_THREADS",
):
    os.environ.setdefault(_v, "1")
os.environ.setdefault("DEFAIR_MULTI_SOURCE_PARALLELISM", "1")
os.environ.setdefault("TQDM_DISABLE", "1")

import shutil
import tempfile
from collections import OrderedDict
from pathlib import Path

import dask
import earthkit.data as ekd
import numpy as np
import rioxarray  # noqa: F401  (registers the .rio accessor used to read the output CRS)
import xarray as xr
import matplotlib.pyplot as plt
from pyproj import Transformer

from defair.logging import setup_logging
from defair_data.core import Dataset
from defair_data.readers import list_readers
from defair_data.sources import list_sources
from defair.plugin_manager import load_source, load_writer
from defair_ops.transformations.alignment import AlignmentPlugin
from defair_ops.transformations.reprojection import ReferenceGrid

# The plotting helpers (cartopy) and the ML stack (defair-ai-demo + torch) both live outside the
# default install. One command provides both, so one guard names it for either failure.
try:
    from defair.notebook_helpers.alignment_plot import ax_proj_for, get_var_da, plot_field, plot_rgb
    from defair_ai_demo.preprocessing import generate_cloud_mask, prepare_dataset_for_training
    from defair_ai_demo.dataset import CloudMaskDataset, create_data_loaders
    from defair_ai_demo.model import create_model
    from defair_ai_demo.train import train_model
    from defair_ai_demo.inference import predict, create_comparison_visualization
except ImportError as exc:
    raise RuntimeError(
        "Missing an extra this notebook needs (cartopy for the map panels, defair-ai-demo and torch "
        "for the model). In the environment that runs this notebook, run: "
        "pip install 'defair[notebooks]' defair-ai-demo, then restart the kernel."
    ) from exc

setup_logging(log_level="WARNING")
print("sources:", [s for s in list_sources() if s in ("local", "s3")])
print("readers:", [r for r in list_readers() if r in ("msg15nat", "mtg_fci_l1c_nc")])
sources: ['local', 's3']
readers: ['msg15nat', 'mtg_fci_l1c_nc']

2. Settings

One fixed run, nothing to tune: 18 matching MTG scenes over Europe, one IR channel from each imager, ERA5 for context, and a short 4-epoch training. COLLOCATION_SOURCE is s3 by default, which reads the public demo bucket of the DestinE Data Lake anonymously; use local to read files under test-data/collocation/.

# Folder that holds the local inputs under test-data/ and the output/ folder. It defaults to the
# working directory, which is the notebook's own folder under Jupyter, nbconvert and papermill.
# Set COLLOCATION_BASE to use another folder.
BASE = Path(os.getenv("COLLOCATION_BASE", ".")).resolve()

SOURCE = os.getenv("COLLOCATION_SOURCE", "s3")
PREFIXES = {
    "s3": ("s3://datalake-demo-data/defair-notebook-data/msg-seviri-l15",
           "s3://datalake-demo-data/defair-notebook-data/mtg-fci-l1c-fdhsi",
           "s3://datalake-demo-data/defair-notebook-data/era5"),
    "local": (str(BASE / "test-data/collocation/msg_seviri"),
              str(BASE / "test-data/collocation/mtg_fci_fdhsi"),
              str(BASE / "test-data/collocation/era5")),
}
MSG_PREFIX, MTG_PREFIX, ERA5_PREFIX = PREFIXES[SOURCE]
# The public Data Lake demo bucket needs no credentials; the local source takes no options.
SOURCE_KWARGS = {"endpoint_url": "https://s3.central.data.destination-earth.eu", "anon": True} if SOURCE == "s3" else {}

MSG_CHANNELS = ["IR_108"]   # one thermal-IR channel per imager (~10.8 / 10.5 um)
MTG_CHANNELS = ["ir_105"]
AOI = {"lon_min": -6.0, "lon_max": 25.0, "lat_min": 35.0, "lat_max": 56.0}   # Europe
N_TIMESTEPS = 18             # MTG is the temporal master; 18 co-temporal scenes on 2025-12-15

PATCH_SIZE = 128
EPOCHS = 4
BATCH_SIZE = 8
LEARNING_RATE = 1e-3

OUT_DIR = BASE / "output/collocation_ai"
OUT_DIR.mkdir(parents=True, exist_ok=True)
COLLOCATED_ZARR = OUT_DIR / "msg_mtg_era5_msggrid.zarr"
AI_ZARR = OUT_DIR / "ai_cloudmask_input.zarr"
MODEL_PATH = OUT_DIR / "cloud_model.pt"

print(f"SOURCE={SOURCE} | timesteps={N_TIMESTEPS} | epochs={EPOCHS} | patch={PATCH_SIZE} | AOI={AOI}")
SOURCE=s3 | timesteps=18 | epochs=4 | patch=128 | AOI={'lon_min': -6.0, 'lon_max': 25.0, 'lat_min': 35.0, 'lat_max': 56.0}

3. Load the three sources

MSG and MTG come in through DEFAIR readers and ERA5 through earthkit-data, one IR channel each. MTG arrives as ~40 chunks per scene (the reader reassembles them), and ERA5 needs its longitudes re-sorted or the reprojection collapses to a sliver, both noted inline below.

src = load_source(SOURCE, **SOURCE_KWARGS)

# Every input is pinned by name so a new object under a prefix cannot change the exercise.
# The fixture manifest in the tutorials folder lists each one with its size and checksum.
MSG_FILES = tuple(
    f"MSG3-SEVI-MSG15-0100-NA-20251215{stamp}Z-NA.nat"
    for stamp in (
        "091243.405000000", "092743.675000000", "094243.946000000", "095744.218000000",
        "101243.285000000", "102743.557000000", "104243.829000000", "105744.101000000",
        "111244.371000000", "112744.641000000", "114243.105000000", "115743.377000000",
    )
)
# The 18 MTG repeat cycles from 09:00 to 11:50, pinned by the end of their scene names.
MTG_SCENE_SUFFIXES = tuple(
    f"_20251215{end}_N__O_{cycle:04d}_0000"
    for cycle, end in zip(range(55, 73), (
        "090923", "091923", "092923", "093923", "094923", "095923", "100923", "101923", "102923",
        "103923", "104923", "105923", "110923", "111923", "112923", "113923", "114923", "115923",
    ))
)
ERA5_FILE = "3d6b83d3fda49621dcb46fe1cd91256d.grib"


def pinned(paths, names, prefix):
    """Return the one path ending in each name, in the order given."""
    picked = []
    for name in names:
        matches = [p for p in paths if p.endswith(name)]
        assert len(matches) == 1, f"{name} not found once under {prefix}: {matches}"
        picked.append(matches[0])
    return picked


# MSG SEVIRI: one thermal-IR channel, selected as we read.
msg_files = pinned([str(p) for p in src.glob(f"{MSG_PREFIX}/*.nat")], MSG_FILES, MSG_PREFIX)
msg_ds = Dataset.from_source(msg_files, reader="msg15nat", source=SOURCE, source_kwargs=SOURCE_KWARGS,
                             channels=MSG_CHANNELS)

# MTG FCI: each scene is a folder of ~40 BODY chunks; gather the pinned scenes' chunks as one list
# and Dataset.from_source regroups them into N timesteps. include_latlon=False skips the full-disk
# 2-D lat/lon the reader would otherwise build (unused here; the alignment works off the grid CRS).
mtg_chunks = sorted(str(p) for p in src.glob(f"{MTG_PREFIX}/*/*CHK-BODY*.nc"))
by_scene = OrderedDict()
for chunk in mtg_chunks:
    by_scene.setdefault(chunk.rsplit("/", 1)[0], []).append(chunk)
scene_names = pinned(list(by_scene), MTG_SCENE_SUFFIXES, MTG_PREFIX)
assert len(scene_names) == N_TIMESTEPS, f"expected {N_TIMESTEPS} MTG scenes, pinned {len(scene_names)}"
mtg_bodies = [c for s in scene_names for c in by_scene[s]]
mtg_ds = Dataset.from_source(mtg_bodies, reader="mtg_fci_l1c_nc", source=SOURCE, source_kwargs=SOURCE_KWARGS,
                             channels=MTG_CHANNELS, include_latlon=False)
mtg_ds = Dataset(mtg_ds.data.sortby("time"))

# ERA5: one static context field. DEFAIR ships no GRIB reader, so this leg is read with
# earthkit-data and handed over as an xarray object. On S3 the object is fetched with
# DEFAIR's own source plugin first: earthkit's S3 source does not sign requests this
# endpoint accepts.
[era5_path] = pinned([str(p) for p in src.glob(f"{ERA5_PREFIX}/*.grib")], ("/" + ERA5_FILE,), ERA5_PREFIX)
if SOURCE == "s3":
    import atexit, shutil
    _local_grib = Path(tempfile.mkdtemp()) / "era5.grib"
    atexit.register(shutil.rmtree, _local_grib.parent, ignore_errors=True)
    with src.open(era5_path, mode="rb") as _remote, _local_grib.open("wb") as _out:
        shutil.copyfileobj(_remote, _out, length=8 * 1024 * 1024)
    era5_path = str(_local_grib)

# time_dim_mode="valid_time" because ERA5 granules mix forecast reference times and steps;
# ensure_dims keeps the time dimension on a single-step granule.
era5_xr = ekd.from_source("file", era5_path).to_xarray(
    time_dim_mode="valid_time", ensure_dims=["valid_time"], add_earthkit_attrs=False,
    chunks={"valid_time": 1}
)
era5_xr = era5_xr.rename({"valid_time": "time"})
# Longitudes come back on [0, 360); re-wrap to [-180, 180) and sort, or the geostationary
# reprojection collapses ERA5 to a thin sliver. write_crs/set_spatial_dims give alignment
# the CRS it needs, and the source attribute names the era5_* output prefix.
era5_xr = era5_xr.assign_coords(longitude=(((era5_xr.longitude + 180) % 360) - 180)).sortby("longitude")
era5_xr = era5_xr.rio.write_crs("EPSG:4326").rio.set_spatial_dims(x_dim="longitude", y_dim="latitude")
era5_xr.attrs["source"] = "ERA5"
era5_ds = Dataset(era5_xr)

assert msg_files and mtg_bodies, "no inputs found - check SOURCE / prefixes / credentials"
print(f"MSG {dict(msg_ds.data.sizes)} | MTG {dict(mtg_ds.data.sizes)} | ERA5 {dict(era5_ds.data.sizes)}")
MSG {'time': 12, 'y': 3712, 'x': 3712, 'bnds': 2} | MTG {'time': 18, 'y_2km': 5568, 'x_2km': 5568, 'bnds': 2} | ERA5 {'time': 1, 'latitude': 721, 'longitude': 1440}

4. Build the target grid

We take MSG’s own geostationary grid and narrow it to the area of interest with ReferenceGrid.from_bounds. No manual cropping: this grid is simply what every source gets reprojected onto in the next step.

# MSG's grid, windowed to Europe. Transform the AOI corners into MSG's geostationary x/y, then build
# the target grid at MSG's native resolution with ReferenceGrid.from_bounds. Passing this as target=
# reprojects every source onto this one grid, so they share identical pixels (no manual cropping).
full = ReferenceGrid.from_dataset(msg_ds)
tr = Transformer.from_crs("EPSG:4326", full.crs, always_xy=True)
xs, ys = tr.transform(
    [AOI["lon_min"], AOI["lon_max"], AOI["lon_min"], AOI["lon_max"]],
    [AOI["lat_min"], AOI["lat_min"], AOI["lat_max"], AOI["lat_max"]],
)
ref_grid = ReferenceGrid.from_bounds(full.crs, (min(xs), min(ys), max(xs), max(ys)), resolution=abs(full.transform.a))
print(f"target grid: {ref_grid.width} x {ref_grid.height}")
target grid: 881 x 463

5. Collocate the three sources

One AlignmentPlugin call puts all three onto the target grid. MTG drives the time axis; MSG and ERA5 are matched to each MTG time by nearest neighbour. We then check the result sits exactly on the grid we asked for.

with AlignmentPlugin() as alignment:
    aligned = alignment.transform(
        mtg_ds,                      # base -> output time axis = MTG's acquisitions
        target=ref_grid,             # AOI-windowed MSG grid; every source is reprojected onto it
        datasets=[msg_ds, era5_ds],  # matched to each MTG time by nearest
        spatial_method="bilinear",
        temporal_method="nearest",
        time_tolerance=None,
        time_bounds="base",
        conflict_resolution="prefix",   # namespace variables: mtg_*, msg_*, era5_*
    )

assert ReferenceGrid.from_dataset(aligned.data).hash_key() == ref_grid.hash_key(), "output is off the target grid"
print("Collocated:", dict(aligned.data.sizes), "| vars:", sorted(aligned.data.data_vars), "| grid hash matches")
Collocated: {'time': 18, 'x': 881, 'y': 463} | vars: ['era5_o3', 'msg_seviri_native_format_ch9', 'mtg_fci_level_1c_netcdf_ch14'] | grid hash matches

6. Pull it into memory

The cube is still lazy, so we compute it one timestep at a time. Each cropped frame is only a few MB, which keeps memory flat however many timesteps we use.

# Materialise ONE timestep at a time on the synchronous scheduler: computing the whole N-timestep
# cube at once would hold every scene's reprojection working set in memory simultaneously (memory
# grows with N). Each AOI timestep is only a few MB, so looping keeps the peak at a single scene's
# reprojection (~1 GB) - this is what lets the full 18-step run fit on a laptop.
parts = []
for i in range(aligned.data.sizes["time"]):
    with dask.config.set(scheduler="synchronous"):
        parts.append(aligned.data.isel(time=[i]).compute())
cube = xr.concat(parts, dim="time")
print("Collocated + windowed to AOI:", dict(cube.sizes), "| timesteps:", cube.sizes.get("time"))
Collocated + windowed to AOI: {'time': 18, 'y': 463, 'x': 881} | timesteps: 18

7. Save the analysis-ready cube

Write it to Zarr, then check every channel actually carries data (a quick guard against an empty collocation).

import shutil
if COLLOCATED_ZARR.exists():
    shutil.rmtree(COLLOCATED_ZARR)
writer = load_writer("zarrv2", mode="w", auto_chunk=True, chunk_size_mb=16)
writer.write(Dataset(cube), str(COLLOCATED_ZARR))   # cube is the computed (in-memory) AOI cube
print("Wrote collocated cube ->", COLLOCATED_ZARR)

readback = xr.open_zarr(COLLOCATED_ZARR)
print("Round-trip dims:", dict(readback.sizes), "| vars:", sorted(readback.data_vars))

# Validity guard: every channel must carry real data. Catches an empty/misaligned collocation
# (e.g. a stale grid transform that lands the AOI window off the disk -> an all-NaN cube that
# would otherwise pass silently and only surface as a degenerate, all-zero cloud mask).
for v in readback.data_vars:
    frac = float(np.isfinite(readback[v]).mean())
    print(f"  finite[{v}] = {frac:.3f}")
    assert frac > 0.01, f"channel '{v}' is ~all-NaN ({frac:.2%}); collocation landed off the data"
Wrote collocated cube -> /home/jovyan/defair-tutorials/output/collocation_ai/msg_mtg_era5_msggrid.zarr
Round-trip dims: {'time': 18, 'y': 463, 'x': 881} | vars: ['era5_o3', 'msg_seviri_native_format_ch9', 'mtg_fci_level_1c_netcdf_ch14']
  finite[era5_o3] = 1.000
  finite[msg_seviri_native_format_ch9] = 1.000
  finite[mtg_fci_level_1c_netcdf_ch14] = 1.000

8. Look at the result

The three sources and an RGB overlay, all on the same grid, for the first timestep. They line up because they share identical pixels.

# Read the small AOI cube back from Zarr and resolve the three prefixed output variables
# (alignment namespaces them msg_*/mtg_*/era5_*). get_var_da returns (name, DataArray).
cube_ds = Dataset(xr.open_zarr(COLLOCATED_ZARR).compute())
msg_var, msg_da = get_var_da(cube_ds, "msg")
mtg_var, mtg_da = get_var_da(cube_ds, "mtg")
era5_var, era5_da = get_var_da(cube_ds, "era5")
print("channels ->", {"MSG": msg_var, "MTG": mtg_var, "ERA5": era5_var})

# One 4-panel cartopy figure (source / source / context / RGB), same layout as the MR-391 showcase.
# ax_proj_for picks the grid's geostationary projection; plot_field/plot_rgb draw north-up with
# coastlines. The RGB overlay lines up exactly because every source is pinned to the same grid.
proj = ax_proj_for(msg_da, ref_grid)
panels = [(msg_da, "MSG SEVIRI IR 10.8", "inferno"),
          (mtg_da, "MTG FCI IR 10.5", "inferno"),
          (era5_da, f"ERA5 {era5_var}", "RdBu_r")]
fig = plt.figure(figsize=(22, 5.5))
for i, (da, title, cmap) in enumerate(panels):
    ax = fig.add_subplot(1, 4, i + 1, projection=proj)
    plot_field(ax, da.isel(time=0), ref_grid, f"{title}\n{da.name}", cmap=cmap)
ax_rgb = fig.add_subplot(1, 4, 4, projection=proj)
plot_rgb(ax_rgb, msg_da.isel(time=0), mtg_da.isel(time=0), era5_da.isel(time=0), ref_grid,
         "RGB composite\nR=MSG  G=MTG  B=ERA5")
fig.suptitle("MSG + MTG + ERA5 collocated on the MSG reference grid, windowed to the AOI (t=0)", fontsize=13)
fig.tight_layout()
fig.savefig(OUT_DIR / "collocation_3panel.png", dpi=130, bbox_inches="tight", facecolor="white")
plt.show()
channels -> {'MSG': 'msg_seviri_native_format_ch9', 'MTG': 'mtg_fci_level_1c_netcdf_ch14', 'ERA5': 'era5_o3'}
../../../../_images/msg_mtg_era5_collocation_ai_usecase_17_1.png

9. Hand off to the AI model

The cube becomes the input to the defair-ai-demo cloud-mask U-Net: we pick the channels, derive a simple cloud label from the MSG IR channel (colder pixels read as cloud), normalise, and save the training Zarr.

This is a plumbing demo, not a skill benchmark. The readers give radiance rather than brightness temperature, the label is a quantile-derived proxy (the coldest ~35% of the MSG IR channel — a channel the model also sees), and ERA5 is a single out-of-period field. The reported IoU/accuracy are computed over the full dataset, training patches included, so they are reconstruction scores against the proxy rule, not held-out test metrics: read them as “the pipeline works”, not “the model is good”.

collocated = xr.open_zarr(COLLOCATED_ZARR)
CHANNELS = [c for c in (msg_var, mtg_var, era5_var) if c is not None]
print("Model input channels:", CHANNELS)


def _to_tyx(da):
    # Collapse any non-(time, y, x) dim (e.g. an ERA5 level/number axis) so each channel
    # is a clean (time, y, x) field the patch loader can stack.
    for d in [d for d in da.dims if d not in ("time", "y", "x")]:
        da = da.isel({d: 0}, drop=True)
    return da


with dask.config.set(scheduler="synchronous"):
    # Materialise the small AOI cube (generate_cloud_mask's quantile needs in-memory data).
    input_ds = xr.Dataset({c: _to_tyx(collocated[c]) for c in CHANNELS}).compute()
    cloud_mask = generate_cloud_mask(input_ds, channel=msg_var, quantile=0.35, enforce_reasonable_coverage=False)
    ai_ds = prepare_dataset_for_training(input_ds, cloud_mask, normalize=True)
    ai_ds = ai_ds.chunk({d: (1 if d == "time" else ai_ds.sizes[d]) for d in ai_ds.dims})
    if AI_ZARR.exists():
        shutil.rmtree(AI_ZARR)
    # DEFAIR Zarr v2 writer (a plain ai_ds.to_zarr() defaults to v3, which rejects numcodecs Blosc).
    load_writer("zarrv2", mode="w", auto_chunk=True, chunk_size_mb=16).write(Dataset(ai_ds), str(AI_ZARR))

print("AI-ready Zarr ->", AI_ZARR)
print("  vars:", sorted(ai_ds.data_vars), "| dims:", dict(ai_ds.sizes))
print("  cloud fraction:", float(ai_ds["cloud_mask"].mean()))
Model input channels: ['msg_seviri_native_format_ch9', 'mtg_fci_level_1c_netcdf_ch14', 'era5_o3']
AI-ready Zarr -> /home/jovyan/defair-tutorials/output/collocation_ai/ai_cloudmask_input.zarr
  vars: ['cloud_mask', 'era5_o3', 'msg_seviri_native_format_ch9', 'mtg_fci_level_1c_netcdf_ch14'] | dims: {'time': 18, 'x': 881, 'y': 463}
  cloud fraction: 0.349999877421838

10. Train the cloud-mask model

A few epochs on the streamed Zarr, with a one-line summary per epoch.

import torch
device = "cuda" if torch.cuda.is_available() else "cpu"

train_loader, val_loader, info = create_data_loaders(
    zarr_path=AI_ZARR, batch_size=BATCH_SIZE, train_split=0.8,
    num_workers=0, patch_size=PATCH_SIZE, channels=CHANNELS,
)
print("dataset:", info)
assert info["train_patches"] > 0 and info["val_patches"] > 0, (
    f"degenerate train/val split ({info['train_patches']}/{info['val_patches']}); "
    "increase timesteps or reduce PATCH_SIZE"
)

model = create_model(in_channels=len(CHANNELS), device=device)
history = train_model(
    model, train_loader, val_loader,
    epochs=EPOCHS, learning_rate=LEARNING_RATE, device=device, save_path=MODEL_PATH,
)

# tqdm bars are disabled (TQDM_DISABLE); show a compact per-epoch summary instead.
for e in range(EPOCHS):
    print(f"  epoch {e + 1}/{EPOCHS}: val_iou={history['val_iou'][e]:.3f}  val_acc={history['val_acc'][e]:.3f}")
dataset: {'total_patches': 324, 'train_patches': 259, 'val_patches': 65, 'patch_size': 128, 'channels': ['msg_seviri_native_format_ch9', 'mtg_fci_level_1c_netcdf_ch14', 'era5_o3'], 'num_channels': 3}
  epoch 1/4: val_iou=0.825  val_acc=0.932
  epoch 2/4: val_iou=0.921  val_acc=0.970
  epoch 3/4: val_iou=0.943  val_acc=0.978
  epoch 4/4: val_iou=0.943  val_acc=0.978

11. Run inference

Predict a cloud mask for every timestep.

infer_ds = CloudMaskDataset(zarr_path=AI_ZARR, patch_size=PATCH_SIZE, channels=CHANNELS)
predictions = predict(model, infer_ds, device=device, batch_size=BATCH_SIZE)
print("predictions:", predictions.shape, "(time, H, W), probabilities in [0,1]")
predictions: (18, 384, 768) (time, H, W), probabilities in [0,1]

12. The cloud mask

The predicted mask next to the proxy label for the first timestep. Note the 128-px patching trims the AOI to a patch-aligned subwindow (463×881 → 384×768; the edge remainder is dropped), so every panel below shows that crop.

gt = xr.open_zarr(AI_ZARR)["cloud_mask"].values
comparison_png = OUT_DIR / "prediction_vs_truth.png"
create_comparison_visualization(
    xr.open_zarr(AI_ZARR), predictions, ground_truth=gt,
    output_path=comparison_png, channel=msg_var, threshold=0.5, time_idx=0, max_size=1024,
)
# create_comparison_visualization closes its own figure, so display the saved PNG inline.
import matplotlib.image as mpimg
plt.figure(figsize=(13, 11)); plt.imshow(mpimg.imread(str(comparison_png))); plt.axis("off")
plt.title("Cloud-mask prediction vs. proxy label (t=0) \u2014 patch-aligned subwindow"); plt.show()
../../../../_images/msg_mtg_era5_collocation_ai_usecase_25_0.png

In short

We put MSG, MTG and ERA5 on one grid using AlignmentPlugin, saved an analysis-ready Zarr, and trained a cloud-mask model on it, all locally. MSG and MTG came through DEFAIR readers and ERA5 through earthkit-data. The grid is MSG’s own, cropped to Europe, so the three sources line up pixel for pixel.

What to do next

Continue with Where to go next for the user guides, reference material and plugin-development paths.