Data sources: object storage, local files and the HDA

Note

Download the executable 08_data_sources.ipynb to run this tutorial in JupyterLab.

DEFAIR reads the same products from three places, and the reader does not change between them. A path decides the route: an s3:// URI reads from object storage, a local filesystem path reads from disk, and the Harmonised Data Access API reads from the DestinE catalogue.

This tutorial reads MSG SEVIRI from object storage, shows that the read stays lazy until something asks for values, streams three granules into one store, reads the same product from a local file, and points at the HDA route.

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

Prerequisites

No. 1 Input data

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

  • Three MSG SEVIRI native granules

This tutorial shows the different places DEFAIR can read from, so its first sections read from object storage on purpose. To use your own copies there, change the paths in MSG_FILES and follow Prepare data access for DEFAIR for your own object store. To read a file from your own disk, set local_granule in the “A local file” section to its path.

Set up the notebook

import time
from pathlib import Path

from defair.logging import setup_logging
from defair.plugin_manager import load_source
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")
# Three MSG repeat cycles of 26 June 2026 in the public Data Lake demo bucket,
# which anyone can read without credentials.
MSG_FILES = [
    "s3://datalake-demo-data/defair-notebook-data/msg-seviri-l15/MSG3-SEVI-MSG15-0100-NA-20260626111243.441000000Z-NA.nat",
    "s3://datalake-demo-data/defair-notebook-data/msg-seviri-l15/MSG3-SEVI-MSG15-0100-NA-20260626112743.658000000Z-NA.nat",
    "s3://datalake-demo-data/defair-notebook-data/msg-seviri-l15/MSG3-SEVI-MSG15-0100-NA-20260626125743.160000000Z-NA.nat",
]
PUBLIC_S3 = {"endpoint_url": "https://s3.central.data.destination-earth.eu", "anon": True}

# Everything written below goes to a local directory, never back to the source bucket.
OUTPUT_DIR = Path("output")
OUTPUT_DIR.mkdir(exist_ok=True)

# The windows the two reads below crop to
SPATIAL_BBOX_1 = {"lat_min": 35.0, "lat_max": 45.0, "lon_min": 0.0, "lon_max": 20.0}
SPATIAL_BBOX_2 = {"lat_min": 30.0, "lat_max": 50.0, "lon_min": -10.0, "lon_max": 30.0}

CHUNK_SIZE_MB = 10

print(f"granules: {len(MSG_FILES)}")
print(f"output:   {OUTPUT_DIR}/")
granules: 3
output:   output/

Object storage

Checking that the three granules below exist first turns a wrong path into a clear message rather than a read error.

s3 = load_source("s3", **PUBLIC_S3)

print(f"checking {len(MSG_FILES)} paths...")
for msg_file in MSG_FILES:
    if not s3.exists(msg_file):
        raise FileNotFoundError(f"S3 path does not exist: {msg_file}")
    print(f"  found: {msg_file}")
checking 3 paths...
  found: s3://datalake-demo-data/defair-notebook-data/msg-seviri-l15/MSG3-SEVI-MSG15-0100-NA-20260626111243.441000000Z-NA.nat
  found: s3://datalake-demo-data/defair-notebook-data/msg-seviri-l15/MSG3-SEVI-MSG15-0100-NA-20260626112743.658000000Z-NA.nat
  found: s3://datalake-demo-data/defair-notebook-data/msg-seviri-l15/MSG3-SEVI-MSG15-0100-NA-20260626125743.160000000Z-NA.nat

A read is lazy until you ask for values

Opening a granule reads its header and filtering it builds a task graph. No channel values have been fetched yet: the task and chunk counts below describe work still to be done, and the arrays are still Dask arrays.

dataset = Dataset.from_source(
    MSG_FILES[0], reader="msg15nat", source="s3", source_kwargs=PUBLIC_S3,
    use_channel_names=True, channels=["IR_108"],
)

# The read has taken the header; the filter takes nothing. What this builds is the graph
# whose size the counts below report.
transformed = dataset.transform("spatial_filter", **SPATIAL_BBOX_1)
channel = transformed.data["IR_108"]

print(f"variable:        {channel.name}")
print(f"array type:      {type(channel.data).__name__}")
print(f"tasks in graph:  {len(channel.data.__dask_graph__())}")
print(f"chunks:          {channel.data.npartitions}")
variable:        IR_108
array type:      Array
tasks in graph:  39
chunks:          2

Streaming many granules into one store

streaming=True defers the read. Rather than opening every granule and holding them, DEFAIR keeps a plan of the file groups, appends each transformation to that plan, and materialises one batch at a time as the writer consumes it, so the granule count stops driving how much has to be resident. The memory figures printed below come from the run that produced this notebook’s output, and depend on the machine and the batch size.

import psutil
import xarray as xr

process = psutil.Process()


def memory_mb():
    return process.memory_info().rss / 1024 / 1024


print("streaming S3 -> transform -> local Zarr")
print("=" * 70)
print(f"memory at the start: {memory_mb():.0f} MB")

# from_source returns a plan over the file groups rather than an open dataset, so this
# reads nothing. stream_batch_size=1 materialises a single granule at a time later on.
print(f"\n[1] planning a streamed read of {len(MSG_FILES)} MSG granules")
dataset = Dataset.from_source(
    MSG_FILES,
    reader="msg15nat",
    source="s3",
    source_kwargs=PUBLIC_S3,
    streaming=True,
    stream_batch_size=1,
)
print(f"  memory after planning: {memory_mb():.0f} MB")

print("\n[2] appending the spatial filter to the plan")
transformed = dataset.transform("spatial_filter", **SPATIAL_BBOX_2)
print(f"  memory after the transform: {memory_mb():.0f} MB")

print("\n[3] writing, which is what actually reads the data")
output_local_path = OUTPUT_DIR / "processed" / "msg_mediterranean.zarr"

start_write = time.time()
transformed.to_file(
    str(output_local_path),
    writer="zarrv2",
    mode="w",
    consolidated=True,
    auto_chunk=True,
    chunk_size_mb=CHUNK_SIZE_MB,
)
print(f"  write time: {time.time() - start_write:.1f} s")
print(f"  memory after the write: {memory_mb():.0f} MB")

written = xr.open_zarr(str(output_local_path), consolidated=True)
assert written.sizes["time"] == len(MSG_FILES), "the streamed write lost a granule"
print(f"\n  written to {output_local_path}")
print(f"  time steps: {written.sizes['time']}, variables: {len(written.data_vars)}")
streaming S3 -> transform -> local Zarr
======================================================================
memory at the start: 373 MB

[1] planning a streamed read of 3 MSG granules
  memory after planning: 373 MB

[2] appending the spatial filter to the plan
  memory after the transform: 373 MB

[3] writing, which is what actually reads the data
  write time: 20.5 s
  memory after the write: 703 MB

  written to output/processed/msg_mediterranean.zarr
  time steps: 3, variables: 12

A local file

The same reader, the same call, a filesystem path instead of a URI. The cell copies the first granule above from object storage into output/ and reads the copy back by path; point local_granule at any MSG native file of your own to read that instead.

import shutil

# Copy the first granule to local disk, then read it back by path. Any MSG native file of
# your own works here too.
local_granule = OUTPUT_DIR / MSG_FILES[0].split("/")[-1]
if not local_granule.exists():
    with s3.open(MSG_FILES[0]) as remote, open(local_granule, "wb") as copy:
        shutil.copyfileobj(remote, copy, length=16 * 2**20)

local = Dataset.from_source(str(local_granule), reader="msg15nat", source="local")
print(f"read from disk: {dict(local.data.sizes)}")
print(f"variables: {list(local.data.data_vars)[:6]}")
read from disk: {'time': 1, 'y': 3712, 'x': 3712, 'bnds': 2}
variables: ['ch1', 'ch2', 'ch3', 'ch4', 'ch5', 'ch6']

The Harmonised Data Access API

The third route reads from the DestinE catalogue rather than from a path you already know. The hda source resolves an HTTP(S) asset URL, a pystac.Asset, or a StacAssetRef(collection_id, item_id, asset_name) into the URL the reader then opens. The item id comes from a STAC search against https://hda.data.destination-earth.eu/stac/v2 with the same credentials, since an anonymous search returns 403. The collection below is the MTG FCI cloud mask:

from defair.plugin_manager import load_source
from defair_data.core import Dataset
from defair_data.sources.hda import StacAssetRef

hda = load_source("hda")  # credentials from DEFAIR_HDA_* or DESTINE_* variables
ref = StacAssetRef(
    collection_id="EO.EUM.DAT.MTG.FCI-CLM",
    item_id="W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+FCI-2-CLM--FD--x-x---x_C_EUMT_20250127140656_L2PF_OPE_20250127135000_20250127140000_N__C_0084_0000",
    asset_name="downloadLink",
)
[url] = hda.resolve_assets([ref])
ds = Dataset.from_source(url, source="hda", reader="mtg_l2_clm")
print(ds.data.sizes)  # {'time': 1, 'x': 5568, 'y': 5568, 'bnds': 2}

The credentials can be a DEDL service account, a DESP username and password, or a token already acquired, each read from the environment (DEFAIR_HDA_CLIENT_ID and DEFAIR_HDA_CLIENT_SECRET for the service account). They need a Destination Earth account, and this notebook carries none of them, so the example above is not executed here.

What to do next

See the HDA section of Read from S3 for the credential kinds, and for why a product is downloaded whole before it is read.

close_dask_client()