LightningCast: Building the AI Ready Data Cube with DEFAIR
A Destination Earth / DEFAIR use case : From raw MTG products to the AI ready campaign cube
CONTENTS¶
Purpose of this notebook¶
This is the companion notebook of LightningCast_prediction_using_defair_and_deep_learning.ipynb.
The prediction notebook opens with a ready made campaign cube sitting in an S3 bucket; this
notebook shows how that cube is made. Starting from the raw MTG products of nine convective
days, it walks the DEFAIR pipeline that turns them into episode cubes, builds part of one
episode live, consolidates the nine episodes into the campaign cube and publishes it to S3,
verifying it by reading it back the way any consumer will.
The data¶
The raw products of the campaign live in the project bucket, filled once by a separate acquisition run. FCI L1C comes from the EUMETSAT Data Store (it is not served by HDA) and only the two full disc chunks covering the study area are kept per cycle, with their original MTG filenames untouched because the DEFAIR reader groups the chunks of a scene by name. GII and the LI products come from the DestinE Harmonised Data Access STAC API. All three services name a 10 minute slot by the same cycle number, and cycle numbering restarts every day, so a slot is always identified by the pair (day, cycle).
| Product | Source | Bucket prefix |
|---|---|---|
FCI L1C (channels ir_105, ir_123) | EUMETSAT Data Store | fci-orig/ |
| GII | DEDL | gii-orig/ |
| LI AF | DEDL | li-orig/ |
| LI LFL, LGR, AFA | DEDL | lfl-orig/, lgr-orig/, afa-orig/ |
⚠️ Note: Notebook execution times may vary depending on the resources available in the environment where they are run.
Prerequisites¶
The only credentials needed are the DataLake S3 keys.
import os
import gc
import time
import json
import shutil
from pathlib import Path
from getpass import getpass
import boto3 # S3 object store client
import pandas as pd
import xarray as xr
from pyproj import Transformer
from defair_data.core import Dataset # DEFAIR entry point
from defair_ops.transformations.alignment import AlignmentPlugin
from defair.logging import setup_logging
setup_logging(log_level="ERROR") # keeps the output readable; use "INFO" to inspect the pipeline or "WARNING"
# Use case configuration
os.environ["GDAL_CACHEMAX"] = "256" # MB; GDAL's default scales with the node RAM, not the 4 GiB pod quota
# Study area: NE Italy, Po Valley and northern Adriatic
BBOX = [8.0, 43.5, 17.0, 47.5] # lon_min, lat_min, lon_max, lat_max (EPSG:4326)
# Convective episodes selected by the season scan below; each episode is the afternoon
# convective window 12:00 to 18:00 UTC (36 slots of 10 min)
TRAIN_EPISODES = ["2025-06-16", "2025-06-21", "2025-06-26", "2025-07-06",
"2025-07-26", "2025-08-02", "2025-08-20", "2025-08-29"]
TEST_EPISODES = ["2025-09-16"]
EPISODES = TRAIN_EPISODES + TEST_EPISODES
# Local workspace and cube locations
CUBE_DIR = os.path.expanduser("~/use_case/data/cubes")
os.makedirs(CUBE_DIR, exist_ok=True)
LOCAL_CUBE = os.path.join(CUBE_DIR, "lightningcast_cube.zarr")
CUBE_KEY = "cubes/lightningcast_cube.zarr/"
# S3 access
#=====================================================================================
# S3 object store: edit these three lines to point at a different store!!
S3_ENDPOINT = "https://s3.central.data.destination-earth.eu"
BUCKET = "defair-use-case"
PREFIX = "" # source prefixes (fci-orig/, gii-orig/, li-orig/, lfl-orig/) and cubes/ live at the bucket root
#=====================================================================================
S3_ACCESS_KEY = getpass("S3 access key: ")
S3_SECRET_KEY = getpass("S3 secret key: ")
s3 = boto3.session.Session(
aws_access_key_id=S3_ACCESS_KEY,
aws_secret_access_key=S3_SECRET_KEY,
).client("s3", endpoint_url=S3_ENDPOINT) # endpoint_url is mandatory on DestinE
S3_SOURCE_KWARGS = {
"aws_access_key_id": S3_ACCESS_KEY,
"aws_secret_access_key": S3_SECRET_KEY,
"endpoint_url": S3_ENDPOINT,
}S3 access key: ········
S3 secret key: ········
# S3 object listing: paginated access to the bucket contents, used by every section that reads data
paginator = s3.get_paginator("list_objects_v2") # pagination is mandatory on DestinE (buckets over 1000 objects)
def s3_keys(prefix):
"""All object keys under a prefix, paginated."""
return sorted(o["Key"] for p in paginator.paginate(Bucket=BUCKET, Prefix=PREFIX + prefix)
for o in p.get("Contents", []))
Shared geometry and a temporary LI workaround¶
crop is the study window (bounding box plus a 2° margin, so reprojection has real data at
the edges) and common the target grid: EPSG:3035, the equal area European grid, at 2 km.
Both are used, unchanged, by the cube builder for every source.
Temporary workaround, remove once fixed upstream. In DEFAIR 0.4.0rc1 the LI AF
griddedreconstruction returns its data array mirrored in X relative to its own coordinates: a flash over Italy (lon +12°) is placed over the Atlantic (lon 12°W), so a plainspatial_filteron the study area returns zeros.read_li_fixedbelow crops the window mirrored across longitude 0 (cheap), flips it back in X and restores the true coordinates. Reported. when the reader is fixed, delete this function and read LI AF with plainfrom_sourceandspatial_filterlike every other source.
# Shared geometry: crop window and target grid, used by every section
MARGIN = 2.0 # degrees around the bbox, so reprojection has real data at the edges
crop = {"lat_min": BBOX[1] - MARGIN, "lat_max": BBOX[3] + MARGIN,
"lon_min": BBOX[0] - MARGIN, "lon_max": BBOX[2] + MARGIN, "drop": True}
to_laea = Transformer.from_crs("EPSG:4326", "EPSG:3035", always_xy=True)
xs, ys = zip(*[to_laea.transform(lon, lat) for lon, lat in
[(BBOX[0], BBOX[1]), (BBOX[2], BBOX[1]),
(BBOX[0], BBOX[3]), (BBOX[2], BBOX[3])]])
common = {"target": "EPSG:3035", "resampling": "bilinear",
"resolution": 2000.0, "resolution_unit": "meters",
"bounds": (min(xs), min(ys), max(xs), max(ys))}
# Temporary workaround: the LI-AF gridded reader mirrors its data in X
def read_li_fixed(uris):
"""Read LI-AF (gridded) already cropped to the study window, with the reader's
X-mirror bug undone: crop the window mirrored across longitude 0, flip it back
in X and restore the true coordinates. Returns a DEFAIR Dataset ready to reproject."""
li = Dataset.from_source(uris, reader="mtg_li_af", reconstruction="gridded",
source="s3", source_kwargs=S3_SOURCE_KWARGS)
crop_mirror = dict(crop, lon_min=-crop["lon_max"], lon_max=-crop["lon_min"])
w = li.transform("spatial_filter", **crop_mirror).data
w = w.isel(x=slice(None, None, -1))
w = w.assign_coords(x=-w["x"].values, lon=(("y", "x"), -w["lon"].values))
return Dataset(w)
The data: what the bucket holds¶
The campaign occupies six prefixes in the project bucket, one per product. The inventory below is the starting point of everything that follows.
# Inventory of the campaign bucket
total_n = total_b = 0
for prefix in ["fci-orig/", "gii-orig/", "li-orig/", "lfl-orig/", "lgr-orig/", "afa-orig/"]:
n = b = 0
for page in paginator.paginate(Bucket=BUCKET, Prefix=PREFIX + prefix):
for obj in page.get("Contents", []):
n += 1
b += obj["Size"]
total_n += n
total_b += b
print(f"{prefix:10s} {n:5d} objects {b / 1e9:6.2f} GB")
print(f"{'TOTAL':10s} {total_n:5d} objects {total_b / 1e9:6.2f} GB")
fci-orig/ 648 objects 15.48 GB
gii-orig/ 341 objects 4.03 GB
li-orig/ 341 objects 1.52 GB
lfl-orig/ 37 objects 0.03 GB
lgr-orig/ 37 objects 0.26 GB
afa-orig/ 38 objects 0.25 GB
TOTAL 1442 objects 21.57 GB
Episode selection: the season scan¶
Before a single cube can be built, the campaign needs to decide which days are worth building it for. Six months of MTG data sit in the archive, May to October 2025, and most of that time the sky over the study area was simply quiet. Building on quiet days would waste compute and teach a model nothing about lightning.
Using the Lightning Imager a long season was scanned through every single day between May and October 2025, and for each one, pulled a single 10 minute LI point file at 15:00 UTC, the heart of the afternoon convective window over Europe, and counted how many flashes it recorded inside the study area. One file, one number, one day, no cube building required. It is a deliberately cheap proxy: a single snapshot obviously understates how a storm actually behaves at 12:00 or 17:00, but as a ranking signal for where the season’s convective energy actually landed, one honest slice per day is enough to tell the noisy days from the active ones.
Roughly six months of daily counts came out of that scan, one integer per day, persisted to a JSON file so the season only had to be swept once. From that file, the ranking below is built: the days sorted by flash activity, most active first. The nine days that rose to the top became the campaign episodes, chosen not for looking dramatic on a map but for being where the season’s lightning actually was. They are spread across the full May to October window rather than clustered in one heatwave, and the single most isolated day on the calendar, 2025-09-16, was deliberately kept aside as the test episode: nothing the model trains on shares a week with it, to avoid temporal and spatial correlation.
# Season scan ranking: flashes in the study area at 15:00 UTC, top 20 days
results = json.loads((Path.home() / "use_case" / "data" / "l5_scan" / "l5_scan_results.json").read_text())
days = {k: v for k, v in results.items() if isinstance(v, int)}
for k, v in sorted(days.items(), key=lambda x: -x[1])[:20]:
print(f" {k}: {v:6d}" + (" <- campaign episode" if k in EPISODES else ""))
2025-08-29: 3043 <- campaign episode
2025-07-06: 1948 <- campaign episode
2025-07-26: 1874 <- campaign episode
2025-08-20: 1590 <- campaign episode
2025-08-02: 1299 <- campaign episode
2025-06-26: 1270 <- campaign episode
2025-06-16: 1226 <- campaign episode
2025-06-21: 1029 <- campaign episode
2025-06-14: 879
2025-08-28: 810
2025-08-21: 786
2025-07-08: 769
2025-07-02: 764
2025-06-30: 653
2025-09-16: 579 <- campaign episode
2025-07-01: 502
2025-09-05: 501
2025-06-03: 447
2025-08-19: 426
2025-05-05: 419
Building the cube¶
Each of the three products lives in its own world when it arrives from the bucket: FCI at one resolution and grid, GII at another, coarser one, LI as a set of point flashes with no grid at all. None of that can go into a model side by side until it’s brought onto common ground. That is the job of the DEFAIR pipeline, and it always comes down to the same four moves: read each source for the slot, crop it down to the study area so nothing outside it is carried along, reproject it onto one shared grid, and align the three reprojected pieces into a single dataset where every variable shares the same time, y and x. Read, crop, reproject, align. The builder below runs that sequence once per 10 minute slot, in a loop, for every cycle of the day.
Each source is read with a single wildcard call. The pattern anchors the cycle between the underscores that delimit it in the MTG product name, so it matches exactly the files of that slot: the FCI scene, which arrives split into spatial chunk files, is assembled by the reader from the same pattern, with no list building and no chunk bookkeeping in the notebook.
Two shortcuts make that loop survive on a 4 GiB pod. The LI series of the whole day is read
once, through read_li_fixed, and its twenty 30 second accumulations are collapsed before
the data is materialized: that single step turns roughly ~880 MB into ~44 MB, which is what
actually fits in memory. Each 10 minute slot then simply takes its share of that already
small series with a temporal_filter, instead of re-reading LI from scratch every time. GII
takes the opposite shortcut: its coarser grid loses valid pixels at the edges of the study
area when it is processed as a full day series, so it is read one slot at a time instead, one
file per cycle. And every slot, the moment its four stages finish, is appended straight to a
zarr store on disk. The cube is never assembled in memory all at once; it grows on disk slot
by slot as the loop advances, which is what lets it survive a run far longer than the pod’s
own memory would otherwise allow.
def day_cycles(day):
"""Cycles present in the three cube sources for one day; a slot is the pair (day, cycle)."""
tag = day.replace("-", "")
def cycles(prefix):
return {k.rsplit("_", 2)[1] for k in s3_keys(prefix) if tag in k}
return sorted(cycles("fci-orig/") & cycles("gii-orig/") & cycles("li-orig/"))
def build_episode_cube(day, store, cycles=None):
"""The cube of one episode: the LI series of the day read once, then the four DEFAIR
stages per slot, each finished slot appended to the zarr store."""
tag = day.replace("-", "")
li = read_li_fixed(f"s3://{BUCKET}/li-orig/*{tag}*.nc")
li = Dataset(li.data.sum("accumulations").load()) # collapse the 30 s accumulations first, ~44 MB
def read(prefix, cycle, **kwargs):
"""One slot of one source, cropped. The cycle is a delimited field of the MTG name,
so the pattern anchors it: an unanchored *cycle* also matches digits in the timestamps."""
return Dataset.from_source(f"s3://{BUCKET}/{prefix}-orig/*{tag}*_{cycle}_????.nc",
source="s3", source_kwargs=S3_SOURCE_KWARGS,
**kwargs).transform("spatial_filter", **crop)
for cycle in cycles or day_cycles(day):
t0 = time.time()
t = pd.Timestamp(day) + pd.Timedelta(minutes=(int(cycle) - 1) * 10)
fci = read("fci", cycle, reader="mtg_fci_l1c_nc",
channels=["ir_105", "ir_123"], calibration="auto")
gii = read("gii", cycle, reader="mtg_l2_gii")
li_slot = li.transform("temporal_filter", start_time=str(t),
end_time=str(t + pd.Timedelta(minutes=10)))
parts = [ds.transform("reprojection", **common) for ds in (fci, gii, li_slot)]
slot = AlignmentPlugin().transform(dataset=parts[0], datasets=parts[1:],
target="EPSG:3035", target_resolution=2000.0,
resolution_unit="meters").data.load()
for v in slot.variables:
slot[v].encoding = {}
slot[v].attrs.pop("_FillValue", None) # rejected by zarr on append
if os.path.exists(store):
slot.to_zarr(store, mode="a", append_dim="time")
else:
slot.time.encoding = {"units": "seconds since 2025-01-01T00:00:00", "dtype": "int64"}
slot.to_zarr(store, mode="w") # the first write fixes the time encoding for every append
print(f" {day} cycle {cycle} ({t:%H:%M} UTC) {time.time() - t0:.0f} s")
del fci, gii, li_slot, parts, slot
gc.collect()The builder, live¶
The cell below builds the first hour of the test episode, six slots, exactly as every one of the 324 slots of the campaign was built, and opens the resulting cube: six time steps, the 234 by 365 study grid, and eleven variables that arrived on three different grids now sitting in one dataset. The demonstration writes to a scratch store; the nine full episode cubes already exist on disk from the campaign run.
# Build the first hour of the test episode, live
DEMO = os.path.join(CUBE_DIR, "cube_demo.zarr")
shutil.rmtree(DEMO, ignore_errors=True)
build_episode_cube(TEST_EPISODES[0], DEMO, cycles=day_cycles(TEST_EPISODES[0])[:6])
xr.open_zarr(DEMO)
Consolidation and publication¶
The cube so far only covers one episode. The campaign is nine of them, so the next step is to wrap all nine episode cubes together end to end along time, one after another, into a single campaign cube: 324 slots in total. The combined cube is then organized into chunks of exactly one episode each, so that reading any single episode later only touches its own chunk rather than the whole cube. It is written to local disk in that layout, and finally uploaded to the bucket one file at a time.
The last cell closes the loop back to where any consumer of this data starts. It reads the
published cube straight from S3 with a single open_zarr call, the same one the prediction
notebook uses to load it. If that call returns the cube with its full shape and variables,
publication succeeded.
# Consolidation: nine episode cubes into one campaign cube, one episode per chunk
cube = xr.concat([xr.open_zarr(os.path.join(CUBE_DIR, f"cube_{d}.zarr")) for d in EPISODES],
dim="time")
for v in cube.variables:
cube[v].encoding = {}
cube = cube.chunk({"time": 36, "y": -1, "x": -1})
cube.to_zarr(LOCAL_CUBE, mode="w")
print(dict(cube.sizes))
{'time': 324, 'y': 234, 'x': 365, 'accumulations': 20}
# Publication: upload the campaign cube to the bucket
t0 = time.time()
n = 0
for root, _, files in os.walk(LOCAL_CUBE):
for f in files:
path = os.path.join(root, f)
s3.upload_file(path, BUCKET, PREFIX + CUBE_KEY + os.path.relpath(path, LOCAL_CUBE))
n += 1
print(f"{n} objects uploaded in {time.time() - t0:.0f} s")
121 objects uploaded in 10 s
# Verification: read the published cube back from S3, the way any consumer will (cube used in the prediction notebook)
storage_options = {
"key": S3_SOURCE_KWARGS["aws_access_key_id"],
"secret": S3_SOURCE_KWARGS["aws_secret_access_key"],
"client_kwargs": {"endpoint_url": S3_SOURCE_KWARGS["endpoint_url"]},
}
cube = xr.open_zarr(f"s3://{BUCKET}/{PREFIX}{CUBE_KEY}", storage_options=storage_options)
print(f"{dict(cube.sizes)}")
print(f"{len(cube.data_vars)} variables:")
for v in cube.data_vars:
print(f" {v}")
cuben = len(s3_keys(CUBE_KEY))
print("objects now in the bucket:", n)
import numpy as np
c = xr.open_zarr(f"s3://{BUCKET}/{PREFIX}{CUBE_KEY}", storage_options=storage_options)
print("first slot BT sum:", float(c["mtg_fci_level_1c_netcdf_ch14"].isel(time=0).sum()))
print("last slot BT sum: ", float(c["mtg_fci_level_1c_netcdf_ch14"].isel(time=-1).sum()))
print("LI total:", float(c["li_flash_accumulation"].sum()))objects now in the bucket: 121
first slot BT sum: 23358942.0
last slot BT sum: 21011248.0
LI total: 3648016.0
Notes from the campaign¶
The acquisition run. Filling the bucket in the first place was a separate, one time job, and its machinery is deliberately left out of this notebook because none of it teaches anything about building a cube (aginated STAC searches, checksum verified downloads from the Data Store, per collection unpacking rules, and a retry pass for anything that failed).
The campaign run. Turning raw products into a cube costs 30 to 37 seconds per slot on the
4 GiB pod, about four hours for all 324 slots, and in practice a single kernel session only
survives about one episode’s worth of that. So the campaign run wrapped the builder shown
above in an extra layer: a sidecar file tracking which cycles of each episode were already
done, so that a kernel dying mid-run never lost more than the one slot it was on, and simply
picking the notebook back up would resume exactly where it left off. That safety layer is left
out here for clarity and transparency, but the pipeline running inside it is exactly the one shown on this page.
The LI mirror bug. The very first consolidated cube came out with li_flash_accumulation
equal to zero everywhere, even though the raw LFL point records showed tens of thousands of
flashes in that same window. Tracing it down led to a bug in DEFAIR’s LI AF gridded
reconstruction: it returns its data array mirrored in X relative to its own coordinates, so
cropping to the study area was actually cropping an empty patch of the Atlantic instead. The
read_li_fixed workaround undoes that mirroring before anything else touches the data, the
builder above already uses it, and any cube built with this notebook comes out correct as a
result. The bug has been reported ,once it’s fixed in the reader itself, this function can simply
be deleted and LI AF read the same plain way as every other source.
Temporal gaps. The campaign cube’s 324 slots are indexed continuously, one after another, but they don’t represent a continuous stretch of time: they are nine separate afternoons with real gaps between them. Anything computed along the time axis, such as brightness temperature differences or the one hour lightning label used in the prediction notebook, has to be computed separately within each episode and must never be allowed to reach across the boundary into the next one.
Conclusions¶
This notebook is the making of the LightningCast campaign cube. What it showed about working with DEFAIR:
Heterogeneous sources, one interface. Three MTG products with different grids, packaging and services are all read through the same
Dataset.from_sourcecall, straight from S3, changing only the reader name.Four stages, one loop. Read, crop, reproject and align, demonstrated live, are the entire recipe: the campaign cube is that loop repeated 324 times, with the engineering effort going into memory discipline and persistence rather than into any per source logic.
The cube is the handover. One
open_zarrline at the end is the entire interface between this notebook and everything downstream.
The companion notebook, LightningCast_prediction_using_defair_and_deep_learning.ipynb, takes
the published cube from here into analysis and deep learning.