Skip to article frontmatterSkip to article content

DEDL_DEFAIR_quick_start

This notebook shows how to start working with DEFAIR (Destination Earth Framework for preparing AI-Ready Data)

🚀 Launch in JupyterHub

DEFAIR (Destination Earth Framework for preparing AI-Ready Data) - Quick Start

Contents

  • Objective: This notebook is designed as an introductory guide to DEFAIR and provides a practical, hands-on walkthrough of the fundamental concepts and workflows required to start working with DEFAIR. It is intended for new users who want to understand how DEFAIR can be used to access, process, and manage geospatial and Earth Observation data.

  • Data Sources: The examples in this notebook use sample datasets hosted in the DestinE demonstration data repository: https://s3.central.data.destination-earth.eu/swift/v1/datalake-demo-data/ These datasets are provided for testing and learning purposes and represent typical Earth Observation products that can be accessed through the DEFAIR.

  • Methods: The notebook demonstrates the following key operations:

    • Loading data - Users will learn how to connect to available data sources and access datasets accessible via the DestinE Data Lake. This step includes reading data and inspecting its structure and metadata.

    • Transforming data - Once loaded, the data can be manipulated and prepared for analysis. Examples of transformations may include filtering, subsetting, reprojection, aggregation, format conversion, or other preprocessing operations commonly required in geospatial workflows.

    • Writing outputs - The notebook shows how processed datasets can be exported and stored in supported formats. This enables users to preserve intermediate results, share outputs with other applications, or make them available for subsequent analysis steps.

    • Provenance tracking capability - The notebook demonstrates how provenance information can be inspected through the dataset’s history metadata attribute.

  • Prerequisites

Before running this notebook, ensure that the DEFAIR packages are installed and available in your execution environment.

  • Running on Insula Code

  • Running on DEDL JupyterHub

  • Running Locally

    • Follow the instructions to install DEFAIR locally.

    • Launch a local JupyterLab environment with access to the DEFAIR installation.

    • Ensure all required dependencies are installed before running the notebook.

  • Expected Output: After successfully completing this notebook, users will be able to:

    • Access and load sample datasets from the DestinE Data Lake.

    • Understand the basic purpose of DEFAIR.

    • Perform simple data transformation and preprocessing operations.

    • Save and manage processed outputs in supported formats.

    • Track the provenance of the produced outputs.

    • Gain the basic knowledge required to adapt the demonstrated workflow to their own datasets and use cases.

The notebook generates an example output in Zarr format from the input datasets and demonstrates a complete end-to-end workflow within the DEFAIR framework, from data ingestion to result generation. To avoid storage issues, the output is removed in the final notebook cell. If this cell is not executed, the generated output remains available.

⚠️ Note: Notebook execution times may vary depending on the resources available in the environment where they are run.

Imports

from pathlib import Path
import numpy as np
import xarray as xr

import defair 
print("Defair version: "+defair.__version__)

import matplotlib.pyplot as plt

try:
    import cartopy.crs as ccrs
    HAS_CARTOPY = True
except ImportError:
    HAS_CARTOPY = False
    print("cartopy not installed, maps will be drawn without coastlines")

from defair.logging import setup_logging
from defair_data.dask_manager import close_dask_client

# Human-readable output
setup_logging(log_level="ERROR")
Defair version: 0.4.3

Visualization function

Attribution: The quicklook function below was copied from the notebook “01_reading_geostationary_products/01_reading_geostationary_products.ipynb” provided by Erwan Fassot (Oxidian).


def quicklook(dataset, variable, title, cmap="viridis"):
    """Draw one variable of a DEFAIR dataset on its native geostationary grid.

    Every product below is read through the same call and drawn through this same
    helper, which is the point of the tutorial: the reader differs, the shape of the
    work does not. A geostationary read keeps the instrument's own projection grid, so
    the dataset carries x and y in projection coordinates rather than longitude and
    latitude. Plotting against those real coordinates (rather than assuming row 0 is
    always the north, the way a plain pixel image would) is what keeps this correct
    regardless of which way a reader's own row order happens to run: these readers
    return y descending (row 0 = north) by default, while a native-order read can
    ascend, and either is simply drawn at its true position -- no reader-specific
    case needed. Coastlines come from the dataset's own CRS, so a genuinely
    misplaced disc would show up as a mismatch against them, not just a guess from
    the raw pixels. The reprojection tutorial is where this native grid becomes a
    map in a fixed frame like EPSG:4326.
    """
    field = dataset.data[variable].squeeze(drop=True)
    # Reduce whatever remains to two dimensions. Products name their extra axes
    # differently (time, band, channel), so take the first index of the leading axis
    # until an image is left rather than naming the axes.
    while field.ndim > 2:
        field = field.isel({field.dims[0]: 0})
    y_dim, x_dim = field.dims

    # A quicklook does not need native resolution: HRFI's full disc at 500 m is
    # 22272x22272 (~500M cells, 2 GB in float32 before any copy). Decimate while the
    # array is still lazy, so only the pixels drawn are ever held in memory.
    max_dim = 2000
    field = field.isel({
        y_dim: slice(None, None, max(1, field.sizes[y_dim] // max_dim)),
        x_dim: slice(None, None, max(1, field.sizes[x_dim] // max_dim)),
    })
    values = np.asarray(field.compute().values, dtype=float)
    x = np.asarray(field[x_dim].values, dtype=float)
    y = np.asarray(field[y_dim].values, dtype=float)

    finite = values[np.isfinite(values)]
    if finite.size == 0:
        print(f"{title}: no finite values to draw")
        return
    vmin, vmax = np.percentile(finite, [2, 98])

    figure = plt.figure(figsize=(9, 9))
    if HAS_CARTOPY:
        attrs = dataset.data["spatial_ref"].attrs
        globe = ccrs.Globe(
            semimajor_axis=attrs["semi_major_axis"], semiminor_axis=attrs["semi_minor_axis"], ellipse=None
        )
        projection = ccrs.Geostationary(
            central_longitude=attrs["longitude_of_projection_origin"],
            satellite_height=attrs["perspective_point_height"],
            sweep_axis=attrs["sweep_angle_axis"],
            globe=globe,
        )
        axis = plt.axes(projection=projection)
        image = axis.pcolormesh(x, y, values, transform=projection, cmap=cmap, vmin=vmin, vmax=vmax, shading="auto")
        axis.coastlines(resolution="50m", linewidth=0.8, color="white")
    else:
        axis = plt.axes()
        image = axis.pcolormesh(x, y, values, cmap=cmap, vmin=vmin, vmax=vmax, shading="auto")
        axis.set_aspect("equal")
        axis.set_xlabel("x (m)")
        axis.set_ylabel("y (m)")
    axis.set_title(title, fontsize=13, fontweight="bold")
    units = dataset.data[variable].attrs.get("units", "")
    figure.colorbar(image, ax=axis, label=f"{variable} ({units})" if units else variable, shrink=0.8)
    plt.tight_layout()
    plt.show()

Loading data

Readers

DEFAIR comes with several built-in data readers that support lazy loading, enabling efficient handling of large datasets.

Use list_readers() to display all available readers and Dataset.from_source() to load data from local or remote storage. Dataset.from_source() reads a product and returns a Dataset.

Reader names generally follow a standardized naming convention:

  1. the constellation name is followed by an underscore (_);

  2. the instrument name and processing level are then appended.

The reader catalogue provides, for each available reader, information aboutct, the data provider, the provider’s original collection ID, and the equivalent collection ID available through DEDL HDA.

from pprint import pprint
from inspect import signature
from defair_data.readers import list_readers

readers = list_readers()
print("Available readers:")

pprint(readers)
Available readers:
['metop_amsul1',
 'metop_ascszf1b',
 'metop_ascszfr02',
 'metop_ascszo1b',
 'metop_ascszor02',
 'metop_ascszr1b',
 'metop_ascszrr02',
 'metop_avhrr_amv',
 'metop_avhrrl1',
 'metop_edlst',
 'metop_glbsst',
 'metop_gomel1',
 'metop_gomel1r03',
 'metop_hirs_fdr',
 'metop_hirsl1',
 'metop_iasil1c_all',
 'metop_iasisnd02',
 'metop_iasthr011',
 'metop_mhsl1',
 'metop_osi104',
 'metop_osi150a',
 'metop_osi150b',
 'metop_somo12',
 'metop_somo25',
 'msg15cdr',
 'msg15nat',
 'mtg_fci_l1c_nc',
 'mtg_fci_l2_amv',
 'mtg_l2_asr',
 'mtg_l2_clm',
 'mtg_l2_gii',
 'mtg_l2_oca',
 'mtg_l2_olr',
 'mtg_li_af',
 'mtg_li_afa',
 'mtg_li_afr',
 'mtg_li_lef',
 'mtg_li_lfl',
 'mtg_li_lgr',
 'sentinel3_aod',
 'sentinel3_frp',
 'sentinel3_ol_1_efr',
 'sentinel3_ol_1_err',
 'sentinel3_ol_2_wfr',
 'sentinel3_ol_2_wrr',
 'sentinel3_sl_1_rbt',
 'sentinel3_sr1_sra',
 'sentinel3_sr1_sra_a',
 'sentinel3_sr1_sra_bs',
 'sentinel3_sr2_wat',
 'sentinel3_wst']

Sources

Data can be loaded from different sources, local or remote storage as well as directly from DEDL HDA.

If source is omitted, DEFAIR selects the highest-priority source plugin that recognises the path:

PathAuto-detected sourceMeaning
Local path or file:// URIlocalLocal filesystem access
s3:// URIs3S3 access through s3fs, the library xarray and Dask use for object storage
http:// or https:// URIhdaHarmonised Data Access (HDA) download and local caching
Loading from S3 - Reader Auto-Detection

The code below demonstrate how DEFAIR automatically detects the appropriate reader based on file format and load the data from a remote object storage.

from defair_data.core import Dataset
msg_dataset_1 = Dataset.from_source(
    "s3://datalake-demo-data/defair-demo-data/MSG3-SEVI-MSG15-0100-NA-20260626111243.441000000Z-NA.nat",
    source="s3",
    source_kwargs={
        "endpoint_url": "https://s3.central.data.destination-earth.eu",
        "anon":True
    }
)

Inspecting data structure and metadata.

print(f"Variables: {list(msg_dataset_1.data.data_vars)}")

print(f"Dimensions: {dict(msg_dataset_1.sizes)}")
Variables: ['ch1', 'ch2', 'ch3', 'ch4', 'ch5', 'ch6', 'ch7', 'ch8', 'ch9', 'ch10', 'ch11', 'geostationary']
Dimensions: {'time': 1, 'y': 3712, 'x': 3712, 'bnds': 2}
msg_dataset_1
Loading...
quicklook(msg_dataset_1, "ch9", "MSG SEVIRI: 10.8 um infrared window", cmap="inferno_r")
<Figure size 900x900 with 2 Axes>
Loading from S3 - Explicit Reader Selection and reader-specific options

You can explicitly select a reader when automatic reader detection is unsuccessful or when a specific reader is required.

In this example, the selected product is High Rate SEVIRI Level 1.5 Image Data - MSG - 0 degree. Its corresponding HDA collection ID, EO.EUM.DAT.MSG.HRSEVIRI, can be found in the Data Portfolio on the DEDL portal (https://data.destination-earth.eu/data-portfolio/EO.EUM.DAT.MSG.HRSEVIRI).

The following example shows how to inspect the common configuration options and the reader-specific options available for the msg15nat reader for the High Rate SEVIRI Level 1.5 Image Data - MSG - 0 degree product.

from inspect import signature
from defair.plugin_manager import load_reader

reader = load_reader("msg15nat")

print("COMMON READER OPTIONS:\n---")
pprint(signature(reader.read))
print("\nSPECIFIC READER OPTIONS AND THEIR DEFAULTS VALUES:\n---")
pprint(signature(type(reader)))
#To display additional details, uncomment the following line:
#help(type(reader))
COMMON READER OPTIONS:
---
<Signature (path: str | os.PathLike, source: str | None = None, source_kwargs: dict[str, typing.Any] | None = None, channels: list[str] | None = None, visir_lines_num: int | None = None, lazy_coordinates: bool = True, include_latlon: bool | None = None, include_aux_metadata: bool = False, upper_right_corner: Literal['NE', 'NW', 'SE', 'SW', 'native'] = 'NE') -> defair_data.core.Dataset>

SPECIFIC READER OPTIONS AND THEIR DEFAULTS VALUES:
---
<Signature (dask_client_kwargs: dict[str, typing.Any] | None = None, chunks: dict[str, int] | str | None = None, calibration: str | collections.abc.Mapping[str, str] = 'radiance', use_channel_names: bool = False)>

In the cell below, we use some reader-specific options:

  • calibration: when set to “auto”, solar channels are returned as reflectance and thermal channels as brightness temperature. Calibration can also be specified independently for each channel using a mapping.

  • use_channel_names: when set to True, variables are named using their EUMETSAT identifiers (for example, HRV or IR_108).

  • channels: used here to explicitly request the HRV channel, which is provided on the 1 km grid.

We also use some common reader options:

  • reader: specifies the reader to use.

  • source: defines the data source.

  • source_kwargs: provides additional arguments for configuring the source.

# Specify reader explicitly
msg_dataset_2 = Dataset.from_source(
    "s3://datalake-demo-data/defair-demo-data/MSG3-SEVI-MSG15-0100-NA-20260626125743.160000000Z-NA.nat",
    reader="msg15nat",
    source="s3",               # common reader option
    source_kwargs={            # common reader option
        "endpoint_url": "https://s3.central.data.destination-earth.eu",
        "anon":True
    },
    calibration="auto",        # reader-specific option
    channels=["HRV","IR_108"], # reader-specific option
    use_channel_names=True     # reader-specific option
)
msg_dataset_2
Loading...
Loading from DestinE Data Lake HDA

The DestinE Harmonized Data Access (HDA) source can be accessed through the hda data source plugin.

The HDA source plugin is responsible for authenticated access to assets stored in the DestinE HDA. Asset discovery is performed separately through the HDA STAC catalog. Once a STAC Item has been identified, its assets can be passed to DEFAIR.

Unlike file-system based sources, HDA does not support directory listing or glob expansion. Instead, products must be discovered through the HDA STAC catalog and then accessed using their asset URLs or asset references.

In the example below:

  • source="hda" explicitly selects the HDA data source plugin.

  • Authentication credentials are provided through source_kwargs.

  • A product URL obtained from the HDA STAC catalog is passed as the input source.

  • The reader loads the product transparently, downloading and caching the file when required.   This mechanism allows DEFAIR readers to work directly with data stored in the DestinE HDA without requiring manual downloads.

WARNING: downloadLink assets require downloading the entire zip archive to local disk. This may require significant disk space and processes data only after the full download completes. It is recommended to use individual assets directly instead of downloadLink when available.

Asset discovery through the HDA STAC catalog

The destinelab library is used to authenticate with DESP, while the PySTAC client is used to search for the desired data. In this example, the selected collection is Cloud Mask - MTG - 0 degree. Its corresponding HDA collection ID, EO.EUM.DAT.MTG.FCI-CLM, can be found in the Data Portfolio on the DEDL portal (https://data.destination-earth.eu/data-portfolio/EO.EUM.DAT.MTG.FCI-CLM). After identifying a STAC Item, its assets can be provided directly to DEFAIR for data access and processing.

%pip install --quiet pystac_client

[notice] A new release of pip is available: 23.1.2 -> 26.2.2
[notice] To update, run: /home/jovyan/defair_venv/bin/python -m pip install --upgrade pip
Note: you may need to restart the kernel to use updated packages.
from getpass import getpass
import destinelab as deauth
DESP_USERNAME = input("Please input your DESP username or email: ")
DESP_PASSWORD = getpass("Please input your DESP password: ")

auth = deauth.AuthHandler(DESP_USERNAME, DESP_PASSWORD)
access_token = auth.get_token()
if access_token is not None:
    print("DEDL/DESP Access Token Obtained Successfully")
else:
    print("Failed to Obtain DEDL/DESP Access Token")

auth_headers = {"Authorization": f"Bearer {access_token}"}
Please input your DESP username or email:  serena.avolio
Please input your DESP password:  ········
DEDL/DESP Access Token Obtained Successfully
from pystac_client import Client

catalog = Client.open("https://hda.data.destination-earth.eu/stac/v2", headers=auth_headers)

search = catalog.search(
    collections=["EO.EUM.DAT.MTG.FCI-CLM"],
    datetime="2026-06-26T11:00:00Z/2026-06-26T12:00:00Z",
)

item = next(search.items())

item.assets.keys()
dict_keys(['EOPMetadata.xml', 'W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+FCI-2-CLM--FD------NC4E_C_EUMT_20260626110454_L2PF_OPE_20260626105000_20260626110000_N__O_0066_0000.nc', 'W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+FCI-2-CLM--FD--QCK-IMAGE---PNG_C_EUMT_20260626110454_L2PF_OPE_20260626105000_20260626110000_N__O_0066_0000.jpg', 'W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+FCI-2-CLM--FD--QCK-IMAGE---PNG_C_EUMT_20260626110454_L2PF_OPE_20260626105000_20260626110000_N__O_0066_0000.png', 'manifest.xml', 'downloadLink'])
print(item.assets["W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+FCI-2-CLM--FD------NC4E_C_EUMT_20260626110454_L2PF_OPE_20260626105000_20260626110000_N__O_0066_0000.nc"].href)
https://hda-download.leonardo.data.destination-earth.eu/data/eumetsat/EO.EUM.DAT.MTG.FCI-CLM/W_XX-EUMETSAT-Darmstadt%2CIMG%2BSAT%2CMTI1%2BFCI-2-CLM--FD--x-x---x_C_EUMT_20260626110831_L2PF_OPE_20260626105000_20260626110000_N__O_0066_0000/W_XX-EUMETSAT-Darmstadt%2CIMG%2BSAT%2CMTI1%2BFCI-2-CLM--FD------NC4E_C_EUMT_20260626110454_L2PF_OPE_20260626105000_20260626110000_N__O_0066_0000.nc
mtg_clm_dataset = Dataset.from_source(
    item.assets["W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+FCI-2-CLM--FD------NC4E_C_EUMT_20260626110454_L2PF_OPE_20260626105000_20260626110000_N__O_0066_0000.nc"].href,
    reader="mtg_l2_clm",
    source="hda",
    source_kwargs={
        "username": DESP_USERNAME,
        "password": DESP_PASSWORD,
    },
)

mtg_clm_dataset
Loading...

Loading multi-file

By default, DEFAIR creates a single logical dataset and loads array data only when it is actually needed. This lazy-loading approach allows to interact with the dataset as a whole.

In this example, the selected collection is FCI Level 1c Normal Resolution Image Data - MTG - 0 degree. Its corresponding HDA collection ID, EO.EUM.DAT.MTG.FCI-FDHSI, can be found in the Data Portfolio on the DEDL portal (https://data.destination-earth.eu/data-portfolio/EO.EUM.DAT.MTG.FCI-FDHSI).

In the following example 3 files belonging to 3 products of the FCI Level 1c Normal Resolution Image Data - MTG - 0 degree dataset are loaded in the same dataset:

  • W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+FCI-1C-RRAD-FDHSI-FD--CHK-BODY---NC4E_C_EUMT_20260626104434_IDPFI_OPE_20260626104007_20260626104024_N__O_0065_0001.nc

  • W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+FCI-1C-RRAD-FDHSI-FD--CHK-BODY---NC4E_C_EUMT_20260626112438_IDPFI_OPE_20260626112007_20260626112024_N__O_0069_0001.nc

  • W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+FCI-1C-RRAD-FDHSI-FD--CHK-BODY---NC4E_C_EUMT_20260626120443_IDPFI_OPE_20260626120007_20260626120024_N__O_0073_0001.nc

mtg_dataset = Dataset.from_source(
    "s3://datalake-demo-data/defair-demo-data/*MTI1+FCI-1C-RRAD-FDHSI*20260626*_0001.nc",
    reader="mtg_fci_l1c_nc",
    source="s3",
    source_kwargs={
        "endpoint_url": "https://s3.central.data.destination-earth.eu",
        "anon":True
    },
    use_channel_names=True,
    streaming=False
)

#print(vars(cube))
mtg_dataset
Loading...
Streaming

For very large collections of files, loading and combining the entire dataset may require too much memory. In these cases, you can enable streaming mode. Rather than assembling the complete dataset in memory, DEFAIR processes a limited number of scene groups at a time. The streaming dataset is not automatically written to disk; users can optionally persist the results by writing them incrementally to a Zarr store using the to_file() method.

Notes:

  • Streaming datasets do not expose the .data property because the complete dataset is never assembled in memory.

  • To inspect or analyse the final result, reload the generated Zarr store (stored using the to_file() method) as a new dataset.

In this example, DEFAIR processes the following 13 scenes up to three scenes at a time

  • W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+FCI-1C-RRAD-FDHSI-FD--CHK-BODY---NC4E_C_EUMT_20251214154414_IDPFI_OPE_20251214154007_20251214154017_N__O_0095_0001.nc

  • W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+FCI-1C-RRAD-FDHSI-FD--CHK-BODY---NC4E_C_EUMT_20251214155412_IDPFI_OPE_20251214155007_20251214155017_N__O_0096_0001.nc

  • W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+FCI-1C-RRAD-FDHSI-FD--CHK-BODY---NC4E_C_EUMT_20251214160420_IDPFI_OPE_20251214160007_20251214160017_N__O_0097_0001.nc

  • W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+FCI-1C-RRAD-FDHSI-FD--CHK-BODY---NC4E_C_EUMT_20251214160434_IDPFI_OPE_20251214160007_20251214160028_N__O_0097_0002.nc

  • W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+FCI-1C-RRAD-FDHSI-FD--CHK-BODY---NC4E_C_EUMT_20251214160452_IDPFI_OPE_20251214160011_20251214160042_N__O_0097_0003.nc

  • W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+FCI-1C-RRAD-FDHSI-FD--CHK-BODY---NC4E_C_EUMT_20251214160502_IDPFI_OPE_20251214160017_20251214160056_N__O_0097_0004.nc

  • W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+FCI-1C-RRAD-FDHSI-FD--CHK-BODY---NC4E_C_EUMT_20260611104428_IDPFI_OPE_20260611104007_20260611104024_N__O_0065_0001.nc

  • W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+FCI-1C-RRAD-FDHSI-FD--CHK-BODY---NC4E_C_EUMT_20260611110433_IDPFI_OPE_20260611110007_20260611110024_N__O_0067_0001.nc

  • W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+FCI-1C-RRAD-FDHSI-FD--CHK-BODY---NC4E_C_EUMT_20260611115432_IDPFI_OPE_20260611115007_20260611115024_N__O_0072_0001.nc

  • W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+FCI-1C-RRAD-FDHSI-FD--CHK-BODY---NC4E_C_EUMT_20260611120418_IDPFI_OPE_20260611120007_20260611120024_N__O_0073_0001.nc

  • W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+FCI-1C-RRAD-FDHSI-FD--CHK-BODY---NC4E_C_EUMT_20260626104434_IDPFI_OPE_20260626104007_20260626104024_N__O_0065_0001.nc

  • W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+FCI-1C-RRAD-FDHSI-FD--CHK-BODY---NC4E_C_EUMT_20260626112438_IDPFI_OPE_20260626112007_20260626112024_N__O_0069_0001.nc

  • W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+FCI-1C-RRAD-FDHSI-FD--CHK-BODY---NC4E_C_EUMT_20260626120443_IDPFI_OPE_20260626120007_20260626120024_N__O_0073_0001.nc

The output object can be transformed using the transform() method and subsequently written incrementally to a Zarr store using the to_file() method. This approach keeps memory usage predictable even when working with a large number of files.

cube = Dataset.from_source(
    "s3://datalake-demo-data/defair-demo-data/*MTI1+FCI-1C-RRAD-FDHSI*.nc",
    reader="mtg_fci_l1c_nc",
    source="s3",
    source_kwargs={
        "endpoint_url": "https://s3.central.data.destination-earth.eu",
        "anon":True
    },
    use_channel_names=True,
    streaming=True,
    stream_batch_size=3,
)

print(vars(cube))

#Uncomment the following two lines to apply a transformation and append the processed output to a Zarr store.

#cube = cube.transform("content_filter", include_vars=["vis_06", "ir_105"])
#cube.to_file("archive.zarr", writer="zarrv2")
{'_data': None, '_stream_plan': StreamingPlan(file_groups=(('s3://datalake-demo-data/defair-demo-data/W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+FCI-1C-RRAD-FDHSI-FD--CHK-BODY---NC4E_C_EUMT_20251214154414_IDPFI_OPE_20251214154007_20251214154017_N__O_0095_0001.nc',), ('s3://datalake-demo-data/defair-demo-data/W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+FCI-1C-RRAD-FDHSI-FD--CHK-BODY---NC4E_C_EUMT_20251214155412_IDPFI_OPE_20251214155007_20251214155017_N__O_0096_0001.nc',), ('s3://datalake-demo-data/defair-demo-data/W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+FCI-1C-RRAD-FDHSI-FD--CHK-BODY---NC4E_C_EUMT_20251214160420_IDPFI_OPE_20251214160007_20251214160017_N__O_0097_0001.nc', 's3://datalake-demo-data/defair-demo-data/W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+FCI-1C-RRAD-FDHSI-FD--CHK-BODY---NC4E_C_EUMT_20251214160434_IDPFI_OPE_20251214160007_20251214160028_N__O_0097_0002.nc', 's3://datalake-demo-data/defair-demo-data/W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+FCI-1C-RRAD-FDHSI-FD--CHK-BODY---NC4E_C_EUMT_20251214160452_IDPFI_OPE_20251214160011_20251214160042_N__O_0097_0003.nc', 's3://datalake-demo-data/defair-demo-data/W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+FCI-1C-RRAD-FDHSI-FD--CHK-BODY---NC4E_C_EUMT_20251214160502_IDPFI_OPE_20251214160017_20251214160056_N__O_0097_0004.nc'), ('s3://datalake-demo-data/defair-demo-data/W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+FCI-1C-RRAD-FDHSI-FD--CHK-BODY---NC4E_C_EUMT_20260611104428_IDPFI_OPE_20260611104007_20260611104024_N__O_0065_0001.nc',), ('s3://datalake-demo-data/defair-demo-data/W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+FCI-1C-RRAD-FDHSI-FD--CHK-BODY---NC4E_C_EUMT_20260611110433_IDPFI_OPE_20260611110007_20260611110024_N__O_0067_0001.nc',), ('s3://datalake-demo-data/defair-demo-data/W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+FCI-1C-RRAD-FDHSI-FD--CHK-BODY---NC4E_C_EUMT_20260611115432_IDPFI_OPE_20260611115007_20260611115024_N__O_0072_0001.nc',), ('s3://datalake-demo-data/defair-demo-data/W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+FCI-1C-RRAD-FDHSI-FD--CHK-BODY---NC4E_C_EUMT_20260611120418_IDPFI_OPE_20260611120007_20260611120024_N__O_0073_0001.nc',), ('s3://datalake-demo-data/defair-demo-data/W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+FCI-1C-RRAD-FDHSI-FD--CHK-BODY---NC4E_C_EUMT_20260626104434_IDPFI_OPE_20260626104007_20260626104024_N__O_0065_0001.nc',), ('s3://datalake-demo-data/defair-demo-data/W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+FCI-1C-RRAD-FDHSI-FD--CHK-BODY---NC4E_C_EUMT_20260626112438_IDPFI_OPE_20260626112007_20260626112024_N__O_0069_0001.nc',), ('s3://datalake-demo-data/defair-demo-data/W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+FCI-1C-RRAD-FDHSI-FD--CHK-BODY---NC4E_C_EUMT_20260626120443_IDPFI_OPE_20260626120007_20260626120024_N__O_0073_0001.nc',)), source='s3', source_kwargs={'endpoint_url': 'https://s3.central.data.destination-earth.eu', 'anon': True}, reader='mtg_fci_l1c_nc', per_file_kwargs={'use_channel_names': True, 'auto_discover_chunks': False}, concat_dim='time', transforms=(), stream_batch_size=3, on_error='raise'), '_cdm': None}

Transforming data

Once loaded, datasets can be further processed using a range of geospatial transformations.

Transformations modify existing datasets by applying operations such as spatial subsetting, channel selection, reprojection, gridding, multi-source alignment, or temporal aggregation.

Since every transformation returns a dataset, transformations can be chained together, making it straightforward to construct complex processing workflows from simple building blocks.

Each call to transform() applies a named transformation and returns a new dataset, like other DEFAIR operations, transformations are evaluated lazily and are only computed when the result is written or accessed.

Built-in transformation

Below a list of the built-in transformations

Subsetting

  • content_filter: Keep or drop variables by name.

  • spatial_filter: Keep pixels inside a latitude and longitude box or polygon.

  • temporal_filter: Keep time steps within a specified time range.

Grid operations

  • reprojection: Move data onto another map grid, including HEALPix.

  • alignment: Put multiple datasets onto a shared grid and merge them.

  • rasterise: Burn a shapefile or other vector dataset onto the dataset grid as a mask.

Aggregation

  • temporal_aggregate: Reduce the time axis to hourly, daily, or longer intervals. Temporal aggregation supports both built-in reduction methods (such as mean, max, sum, and percentile) and custom reduction functions. In addition to the predefined methods, users can provide the import path of any module-level Python function, allowing domain-specific aggregation logic to be applied to each temporal bin.

Masking and quality control

  • mask_filter: Set pixels to missing where a mask or quality flag indicates invalid data.

Derived variables

  • angles: Compute the solar zenith angle for every pixel.

from defair.plugin_manager import list_transformations

print(list_transformations())
['alignment', 'angles', 'content_filter', 'mask_filter', 'rasterise', 'reprojection', 'spatial_filter', 'temporal_aggregate', 'temporal_filter']

Chain Transformations

The following code loads SEVIRI data from S3, keeps only channels 1 and 9, extracts a geographic subset over the Mediterranean region, and reprojects the result to a regular WGS84 grid.

The transformations are chained together and executed lazily when the data is accessed.

result = (
    Dataset.from_source("s3://datalake-demo-data/defair-demo-data/MSG3-SEVI-MSG15-0100-NA-20260626*-NA.nat",
    source_kwargs={
        "endpoint_url": "https://s3.central.data.destination-earth.eu",
        "anon":True
    })
    .transform("content_filter", include_vars=["ch1", "ch9"])
    .transform("spatial_filter", lat_min=35, lat_max=55, lon_min=-10, lon_max=25)
    .transform("reprojection", target="EPSG:4326", resolution=0.05)
)
result
Loading...

Aligning and aggregating multiple datasets

Many Earth observation products describe the same phenomenon from different perspectives, but are delivered on different grids and with different temporal sampling. Before they can be analysed together, they must be brought into a common spatial and temporal framework.

Spatial alignment supports different resampling methods depending on the target grid. For latitude/longitude coordinate systems, the available methods are nearest, bilinear, and cubic. For HEALPix targets, mean, nearest, and idw are supported. Temporal alignment supports the nearest and ffill methods. The transformation:

  • Reprojects all datasets to a common target reference system or grid (for example EPSG:4326, EPSG:3035, EPSG:6933, or healpix:N).

  • Aligns observations to common timestamps. Depending on the selected method, it can associate each timestamp with the nearest available observation (nearest) or carry the latest observation forward until a new one becomes available (ffill).

  • Supports custom time grids through explicit timestamps or regular frequencies (for example, every 15 or 30 minutes).

  • Merges all variables into a single dataset while handling variable name conflicts automatically.

In the following example, we align three previously loaded datasets onto a common spatial grid and temporal axis:

DatasetObservation times (UTC)
High Rate SEVIRI Level 1.5 Image Data (MSG, 0°)2026-06-26 11:00:00
FCI Level 1c Normal Resolution Image Data - MTG - 0 degree2026-06-26 10:40:07, 2026-06-26 11:20:07, 2026-06-26 12:00:07
Cloud Mask (MTG, 0°)2026-06-26 10:50:00

The SEVIRI Level 1.5 dataset (msg_dataset_1) is used as the reference dataset. All datasets are reprojected onto a common geographic grid (target="EPSG:4326") with a spatial resolution of 0.05° (resolution=0.05), while the MTG datasets are resampled using bilinear interpolation (spatial_method="bilinear).

The output timeline is derived from the combined temporal coverage of all input datasets (time_bounds="union"). Since the earliest observation occurs at 2026-06-26 10:40:07, an hourly frequency (target_freq="1h") produces the timestamps 2026-06-26 10:40:07 and 2026-06-26 11:40:07. A third timestamp is not generated because the latest observation is 2026-06-26 12:00:07, which falls before the next hourly step (2026-06-26 12:40:07).

For each output timestamp, observations are matched using the nearest available acquisition time within a 30-minute tolerance (time_tolerance="30min").

This produces a single analysis-ready dataset in which all variables share the same spatial grid and timeline, making them directly comparable for visualisation, statistical analysis, or machine-learning workflows.

from defair_ops.transformations.alignment import AlignmentPlugin

aligned = AlignmentPlugin().transform(
msg_dataset_1,
target="EPSG:4326", resolution=0.05,
datasets=[mtg_dataset, mtg_clm_dataset], 
spatial_method="bilinear",
temporal_method = "nearest",
target_freq="1h",
time_tolerance = "30min",
time_bounds='union',
)

aligned
Loading...

Writing outputs

The processed datasets can be exported and stored in supported formats. This enables users to preserve intermediate results, share outputs with other applications, or make them available for subsequent analysis steps.

DEFAIR can write datasets to different formats such as NetCDF4, GeoTIFF, Parquet, CSV, and Zarr v3. The available writers can be listed with list_writers():


from defair_data.writers import list_writers

print(list_writers())
['csv', 'geoparquet', 'geotiff', 'hdf5', 'jpeg', 'netcdf4', 'parquet', 'png', 'zarrv2', 'zarrv3']

Write datasets to zarr stores

So far, all operations have been defined lazily. No data has been read or processed until a result is requested. Writing a dataset is one of the operations that triggers execution: DEFAIR reads the required data, applies the transformation chain, and stores the result in the chosen output format.

In this example, we save the aligned dataset as a Zarr store. Zarr is a cloud-friendly format that stores large arrays as many small chunks, making it efficient for large-scale geospatial and machine-learning workflows.


aligned.to_file(
    "aligned_dataset.zarr",
    writer="zarrv2",
    mode="w",
    consolidated=True,
)

Provenance tracking capability — the history attribute

Reproducibility is a key requirement in geospatial and Earth observation workflows. Datasets are often derived through multiple processing steps, keeping track of how a dataset was produced is essential for validating results, sharing analyses, and recreating the same workflow at a later date.

DEFAIR automatically records provenance information in the dataset’s history attribute. This includes both data access operations and output generation, providing a complete audit trail from the original source to the final product.

The provenance history contains timestamped entries describing the workflow, including read and write operations. In this example, the metadata records both the source dataset that was opened and the subsequent export to a Zarr store. This ensures that the resulting file remains self-describing and that its processing history can be inspected long after it has been generated.

aligned = xr.open_zarr(
    "aligned_dataset.zarr",
    consolidated=True
)

print("Provenance History:")
print(aligned.attrs.get("history", "No history attribute found"))

print("\nCreation Metadata:")
for key in ["date_created", "creator_name", "creator_url"]:
    if key in aligned.attrs:
        print(f"  {key}: {aligned.attrs[key]}")
Provenance History:
2026-10-29T22:58:22.334576+00:00: Read operation [DEFAIR v0.4.3:MSG15NativeReaderPlugin, channels=None, source='s3://datalake-demo-data/defair-demo-data/MSG3-S...']
2026-10-29T22:59:17.768087+00:00: Transform operation [DEFAIR v0.4.3:Reprojection, target='EPSG:4326', resampling='bilinear', backend=None, resolution_unit='degrees']
2026-10-29T22:59:06.059670+00:00: Read operation [DEFAIR v0.4.3:MTGFCIL1cNCReaderPlugin, channels=None, source='s3://datalake-demo-data/defair-demo-data/W_XX-E...']
2026-10-29T22:59:19.690021+00:00: Transform operation [DEFAIR v0.4.3:Reprojection, target='EPSG:4326', resampling='bilinear', backend=None, resolution_unit='degrees']
Original generated version
2026-10-29T22:58:56.390512+00:00: Read operation [DEFAIR v0.4.3:MTGL2CLMReaderPlugin, source='https://hda-download.leonardo.data.destination-...']
2026-10-29T22:59:21.255902+00:00: Transform operation [DEFAIR v0.4.3:Reprojection, target='EPSG:4326', resampling='bilinear', backend=None, resolution_unit='degrees']
2026-10-29T22:59:16.696914+00:00: Alignment operation [DEFAIR v0.4.3:AlignmentPlugin, target='EPSG:4326', target_resolution=None, resolution_unit='auto', temporal_method='nearest', spatial_method='bilinear', reference_dataset=None, reference_grid_id=None]
2026-10-29T22:59:21.841530+00:00: Write operation [DEFAIR v0.4.3:ZarrV2Writer, mode='w', consolidated=True, auto_chunk=True, chunk_size_mb=128, chunks=None, source='aligned_dataset.zarr']

Creation Metadata:
  date_created: 2026-10-29T22:59:21.841602+00:00
close_dask_client()
import shutil

shutil.rmtree("aligned_dataset.zarr")

Summary

This notebook provides a practical introduction to DEFAIR and demonstrates how it can be used to access, process, and export Earth observation data from the DestinE Data Lake. We explored how to load datasets from different sources, inspect their structure, and apply transformations through DEFAIR’s lazy execution model. We then combined observations from multiple products by aligning them onto a common spatial grid and temporal axis, producing an analysis-ready dataset suitable for visualisation, statistical analysis, or machine-learning applications.

Finally, we demonstrated how to persist the results using DEFAIR’s built-in writers and how to inspect the automatically generated provenance metadata. Together, these capabilities illustrate how DEFAIR simplifies the creation of reproducible geospatial processing workflows, from data access to the generation of shareable, self-describing output products.

Resources and References

DEFAIR Documentation

Datasets Used