Write a reader plugin
This guide explains how to create a reader plugin for DEFAIR. A reader plugin lets DEFAIR read a new file format or product.
Before implementing the plugin, complete the shared setup in Plugin Development.
Prerequisites
No. 1 A product specification and representative sample
Have the target format’s specification and a representative product available for implementing and testing the reader.
Overview
Reader plugins extend the DataReaderPlugin base class and are
discovered through the defair_data.readers entry-point group. They
turn a file into a DEFAIR Dataset: an xarray dataset with CF
metadata, georeferencing and Dask chunking for streaming workflows.
The skeleton below is a minimal working example of the interface, not a
production reader: it opens a NetCDF file through the data source
abstraction and returns it lazily. It runs against DEFAIR 0.4.3, is
found by defair readers and works with Dataset.from_source().
Model a real reader on a complete built-in such as
MSG15NativeReaderPlugin, which shows binary parsing, calibration, a
projection grid, the common data model and a full set of named options.
Its source comes with DEFAIR:
python -c "import defair_data.readers.msg15.msg15_native_reader_plugin as m; print(m.__file__)"
prints where its source is installed.
Minimal Reader Plugin Skeleton
Replace the body of read(), the SUPPORTED_EXTENSIONS list and
the variables and chunks options with your own. The class name,
the read() signature with path, source and
source_kwargs, and the Dataset(...) return are the parts every
reader keeps.
from os import PathLike
from typing import ClassVar
import xarray as xr
from defair_data.core import Dataset
from defair_data.data_reader_plugin import DataReaderPlugin
class MyCustomReaderPlugin(DataReaderPlugin):
"""Reader for my custom data format."""
SUPPORTED_EXTENSIONS: ClassVar[list[str]] = [".myext"]
PRIORITY: ClassVar[int] = 50
def read(
self,
path: str | PathLike,
source: str | None = None,
source_kwargs: dict | None = None,
variables: list[str] | None = None,
chunks: dict[str, int] | None = None,
) -> Dataset:
"""Read one file and return a Dask-backed Dataset.
Args:
path: Path to the data file, local or remote
source: Data source plugin name, None picks one from the path
source_kwargs: Options for the data source plugin
variables: Variables to keep, None keeps all of them
chunks: Dask chunk sizes, overriding the defaults below
Returns:
Dataset with CF metadata and lazy arrays
"""
file_obj = self.open_file(path, source=source, source_kwargs=source_kwargs)
ds = xr.open_dataset(file_obj, chunks=chunks or {"y": 1024, "x": 1024})
if variables is not None:
ds = ds[variables]
ds.attrs["Conventions"] = "CF-1.8"
ds.attrs["source"] = "My Custom Data Source"
return Dataset(ds)
Four rules the skeleton follows, and DEFAIR enforces:
SUPPORTED_EXTENSIONSandPRIORITYare the class attributes the base class reads. The defaultcan_handle()matches the path suffix againstSUPPORTED_EXTENSIONS, so override it only when detection needs to look inside the file.Every option is a named parameter of
__init__orread(). Reader arguments are validated strictly against the signature, from Python and from a workflow file, so a**kwargscatch-all does not widen the accepted set and only lets a typo through silently. See the next section for how annotations are checked.The file handle is not closed inside
read(). Dask reads from it later, when a chunk is computed, so awith self.open_file(...) as f:block that returns the dataset fails on first use withValueError: seek of closed file. Let xarray keep the handle. It stays open until the dataset is garbage collected, andds.close()does not close it.The return value is
Dataset(ds), the DEFAIR wrapper around the xarray object, not the xarray object itself.Dataset.from_source()and the workflow runner expect the wrapper.
Option types are enforced from your annotations
Each option your __init__ and read() declare is checked against
its annotation before the reader is built, so your code never sees a
value the signature rules out. A **kwargs declaration does not widen
the set of accepted names, and an option you do not name stays untyped.
The check understands bool, int, float, str, None,
Literal, unions of those, and the containers Mapping,
Sequence, dict, list, tuple and set. Any other
annotation, a class of your own for instance, leaves the option checked
by name alone rather than being enforced or refused.
A bool requires an actual boolean, so 1 and numpy’s np.bool_
are rejected. An int rejects a boolean, because bool is a
subclass of int, and a float accepts an integer. Numpy scalars
of any width satisfy int and float, since a caller often derives
an option from array metadata. A 0-d array does not: unwrap
ds.solar_zenith.max().values with .item() before you pass it, as
the plugins that check their own numeric options expect a scalar too.
A container is checked by kind rather than by exact type, and its
contents are not inspected. Mapping and dict both mean any
mapping. Sequence, list, tuple and set all mean any
collection that is neither a string nor a mapping, so a list satisfies a
tuple annotation, as a workflow file has a single sequence form, and
so do a numpy array, a range and a .keys() view. A string is not
a sequence for this purpose, so channels="IR_108" is rejected rather
than iterated one character at a time.
Annotations are resolved with typing.get_type_hints, so postponed
evaluation (from __future__ import annotations) and forward
references both work. An annotation naming a type that cannot be
resolved at runtime, one imported only under if TYPE_CHECKING for
instance, leaves that one option unchecked rather than failing the load
or costing the rest of the signature.
Registration via Entry Points
Standalone package
A third-party reader lives in its own package with DEFAIR as a
dependency. A minimal pyproject.toml:
[project]
name = "my-defair-plugin"
version = "0.1.0"
dependencies = ["defair-data>=0.4.3"]
[project.entry-points."defair_data.readers"]
my_custom_reader = "my_defair_plugin.readers:MyCustomReaderPlugin"
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
Put the class in my_defair_plugin/readers.py, next to an empty
my_defair_plugin/__init__.py, with the my_defair_plugin/ folder
beside pyproject.toml. Hatchling builds that folder, and without it
pip install -e . fails with
Unable to determine which files to ship inside the wheel. A package
that ships several kinds of plugin lists all its entry-point tables in
the same pyproject.toml.
The entry-point key is the short name used in
Dataset.from_source(path, reader="my_custom_reader") and under
reader: name: in a workflow file, and the value is module:Class.
defair-data depends on defair and defair-ops, so one
dependency pulls the whole set, including the defair command.
Install the package in editable mode and check that DEFAIR sees it:
pip install -e .
defair readers
defair readers lists every registered reader, third-party ones
included. A reader without a catalogue entry shows - in the product
and collection columns:
Reader Product Collection ID
-------------------- ------------------------------------------------------- ------------------------
msg15nat High Rate SEVIRI Level 1.5 Image Data - MSG - 0 degree EO:EUM:DAT:MSG:HRSEVIRI
my_custom_reader - -
defair readers --format json gives the same list as JSON. From
Python, from defair.plugin_manager import list_readers, load_reader
gives the names and the loaded instance. A missing entry point raises
ValueError: Plugin 'my_custom_reader' not found in group 'defair_data.readers'.
DEFAIR caches the entry-point lookup per process, so call
defair.plugin_manager.clear_plugin_cache() if you installed the
package from a Python session that was already running.
Streaming & Dask best practices
Critical
Reader plugins must support streaming workflows for large datasets.
Use the
chunksparameter when opening datasets.Return lazy-loaded, Dask-backed arrays.
Use
self.open_file()for data source abstraction, including local and S3 sources.Keep metadata operations lightweight.
Do not call
.compute()or.load()unless absolutely necessary.Do not materialize entire datasets in memory.
Do not assume datasets fit in RAM.
Example of lazy coordinate computation:
# Correct: Lazy coordinates
ds = ds.assign_coords({
"latitude": (["y", "x"], dask.array.from_delayed(...)),
"longitude": (["y", "x"], dask.array.from_delayed(...))
})
# Wrong: Forces computation
lat_values = compute_latitude().compute() # Materializes in memory
ds = ds.assign_coords({"latitude": lat_values})
Test your reader plugin
Testing a standalone plugin
The tests live in the plugin repository and need only the installed
DEFAIR distributions and pytest. Write the sample file inside the
test so the suite carries no fixture data. Cover discovery,
can_handle(), the read, laziness and metadata:
import dask.array as da
import numpy as np
import xarray as xr
from defair.plugin_manager import list_readers, load_reader
from defair_data.core import Dataset
from my_defair_plugin.readers import MyCustomReaderPlugin
def _sample(tmp_path):
path = tmp_path / "sample.myext"
xr.Dataset({"my_variable": (["y", "x"], np.arange(16.0).reshape(4, 4))}).to_netcdf(path)
return path
def test_my_reader_discovered():
"""The entry point is installed and loads."""
assert "my_custom_reader" in list_readers()
assert isinstance(load_reader("my_custom_reader"), MyCustomReaderPlugin)
def test_my_reader_can_handle():
"""Only the declared extension is claimed."""
assert MyCustomReaderPlugin.can_handle("/path/to/file.myext") is True
assert MyCustomReaderPlugin.can_handle("/path/to/file.txt") is False
def test_my_reader_reads_lazily(tmp_path):
"""read() returns a Dask-backed Dataset with the expected content."""
ds = load_reader("my_custom_reader").read(_sample(tmp_path), chunks={"y": 2, "x": 2})
assert isinstance(ds, Dataset)
assert "my_variable" in ds.data.data_vars
assert ds.data.attrs["Conventions"] == "CF-1.8"
assert isinstance(ds.data["my_variable"].data, da.Array)
assert ds.data["my_variable"].chunks == ((2, 2), (2, 2))
assert float(ds.data["my_variable"][1, 1].compute()) == 5.0
def test_my_reader_from_source(tmp_path):
"""The public entry point finds the reader by name."""
ds = Dataset.from_source(str(_sample(tmp_path)), reader="my_custom_reader")
assert list(ds.data.data_vars) == ["my_variable"]
Run them from the plugin repository, with the plugin installed
(pip install -e .):
pytest -v
Real-World Example
For a complete implementation to model yours on, see:
MSG15NativeReaderPlugin, in the module
defair_data.readers.msg15.msg15_native_reader_plugin.
python -c "import defair_data.readers.msg15.msg15_native_reader_plugin as m; print(m.__file__)"
prints where its source is installed.
Data Source Abstraction
DEFAIR supports reading from multiple data sources (local filesystem,
S3, etc.) through data source plugins. Use self.open_file() to make
your reader compatible with all sources:
# This works for local files, S3, and any registered data source
file_obj = self.open_file(path, source=source, source_kwargs=source_kwargs)
# file_obj is a file-like object that works with xarray, netCDF4, h5py and similar
ds = xr.open_dataset(file_obj, chunks=...)
No need to handle S3 credentials, URL parsing, or filesystem differences: the data source plugin handles it. Keep the handle open for as long as the dataset is used, because Dask reads from it lazily.
Plugin Priority System
When multiple readers support the same file extension, DEFAIR uses the
PRIORITY attribute to select which plugin to use:
The plugin with the higher priority is used (0-100 scale)
Default priority: 50
Built-in readers: 10-30
Third-party/custom readers: 50-80
Override/debug readers: 90-100
Example: If you’re creating a faster alternative to an existing reader,
set PRIORITY = 60 to prefer your implementation.
CF Flag Decoding
Products describe per-pixel quality with CF flag variables: an integer
whose bits or values are named by flag_meanings, paired with
flag_masks (independent bitfields), flag_values (a mutually
exclusive enumeration), or both. defair_data.cf_flags decodes all
three forms, lazily, for every reader family.
Opting a reader in
Expansion turns each bit into its own boolean coordinate named
<variable>_<flag>. It is off by default, because adding coordinates
changes a product’s published output and consumers see the difference. A
reader opts in with a class attribute:
class MyReaderPlugin(DataReaderPlugin):
EXPAND_CF_FLAGS: ClassVar[bool] = True
then calls the helper once, where its variable inventory and metadata are final:
ds = self._expand_cf_flag_coordinates(ds)
Call it explicitly rather than expecting a base class to do it. There is
no universal post-read hook, and the obvious candidate is not universal
either: the MTG LI readers never call apply_cf_global_metadata, so
wiring expansion into CF enrichment would silently skip them.
Sentinel-3 readers set EXPAND_CF_FLAGS = True.
Enumerations are not expanded
Only flag_masks bitfields expand by default. An enumeration needs no
decoding (ds.quality == 2 is already the answer) and expanding every
value of every enumeration would add on the order of a hundred
coordinates to a Metop product. Enumerations stay reachable by name
through cf_flags.flag_mask and through the mask_filter
transformation’s mask_where. Pass enums=True to
expand_cf_flags if uniform expansion of every CF flag form is ever
required.
Keep the bitfield in its integer domain
A flag variable that declares _FillValue is promoted to float by
xarray’s default CF decoding, with NaN wherever the raw value equals the
fill. Casting that back to an integer is undefined, so the decoder
raises an error for a floating-point bitfield rather than producing
plausible nonsense.
This is not a corner case. MTG FCI pixel_quality declares
_FillValue = 0 while 0 is also the valid “no warnings raised” state,
so default decoding turns essentially the whole disk to NaN. Open such
variables with mask_and_scale=False:
ds = self._open_chunk_group(path, options, group, handles, mask_and_scale=False)
Do not write _FillValue back out as encoding on a flag variable
either: a later CF-decoding reopen would reintroduce the same collision.
Record it as a plain attribute instead.
Ancillary rasters are not science
A quality raster shares its channel’s dimensions but must not be reprojected, resampled or calibrated as a measurement. Mark it so the CDM excludes it from science ownership:
quality.attrs[AUX_METADATA_ATTR] = "true"
Geostationary image orientation
The MSG native-format reader (msg15nat), FCI L1c, FCI
projection-gridded L2 products and gridded LI reconstructions return
north-up, west-left arrays by default. This includes every resolution
grid, such as MSG HRV and mixed-resolution FCI channels. A plain
imshow(image, origin="upper") therefore uses the same compass
directions across these products.
The separate MSG CDR reader (msg15cdr) already returns north-up,
west-left arrays, but does not expose upper_right_corner.
Pass upper_right_corner to read() or Dataset.from_source()
to choose the compass corner at the array’s upper right:
from defair_data import Dataset
upright = Dataset.from_source("scene.nat", upper_right_corner="NE")
native = Dataset.from_source("scene.nat", upper_right_corner="native")
Value |
Columns |
Rows |
|---|---|---|
NE, default |
west to east |
north to south |
NW |
east to west |
north to south |
SE |
west to east |
south to north |
SW |
east to west |
south to north |
native |
Product ordering |
Product ordering |
native restores the product’s logical line and column directions.
For msg15nat it means SW; for FCI and reconstructed LI it means
SE. It retains calibration, HRV padding, missing-chunk filling and
projection-coordinate corrections. It does not return packed file bytes.
The direction follows the EUMETSAT MSG and FCI grid
definitions
and the FCI product guide, sections 5.1 and
5.2.
The option names follow Satpy’s geostationary orientation
convention.
DEFAIR chooses NE as its default so image display has one
orientation across these readers. This is a DEFAIR API decision.
EUMETSAT specifications define the source geometry rather than a Python
array default. Satpy defaults to native; sharing its option names
does not mean the two libraries share a default.
This changes array positions from earlier DEFAIR versions. MSG VIS/IR
was already NE, padded MSG HRV was SW, and FCI and gridded LI
were SE. To reproduce an old array ordering, request that explicit
corner. For a combined MSG VIS/IR and HRV read, reproducing the old
mixed ordering requires separate reads. Prefer selecting pixels by their
coordinates when comparing old and new outputs.
The msg15nat reader’s former area_extent global attribute is now
source_area_extent, with an accompanying description. It describes
the native VIS/IR source grid even in an HRV-only read; it is not an
output-array extent. Use each grid’s projection axes and CRS for output
geometry.
Orientation uses lazy axis reversals without interpolation. Coordinates, measurements, quality fields, pixel acquisition times and other variables sharing the reversed dimensions move together. The location and value of every pixel remain paired; deferred lat/lon generation uses the oriented projection axes. Each lazy variable retains its original chunk sizes, including the final partial chunk. This keeps chunked Zarr and NetCDF output compatible with the reader’s chunking request after an axis reversal.
The option applies to geostationary projection grids. Sparse and point LI observations retain their observation order. Polar swaths and FCI curvilinear segment products have scan indices and two-dimensional navigation, not east/north projection axes, and do not expose this option. Use coordinate-aware plotting or reproject them to a geographic grid for north-up display. Reversing scan indices cannot guarantee that orientation, as illustrated by the SLSTR instrument grid definition, section 4.4.3.
New geostationary readers should call orient_geostationary after
geolocation, calibration and ancillary assembly, before constructing
their public Dataset. Declare east-positive and north-positive metre
axes with CF standard names projection_x_coordinate and
projection_y_coordinate. Never infer compass orientation from an
unconverted product angle or an arbitrary dimension index.
Product-specific orientation and existing stores
FCI source x angles are west-positive. The readers convert them to east-positive projection coordinates before applying the orientation. This correction applies whatever corner you ask for.
LI accumulated products (mtg_li_af, mtg_li_afa, mtg_li_afr)
reconstruct projection coordinates from pixel indices. Their sparse
outputs retain record order. LI point products (mtg_li_lfl,
mtg_li_lgr) retain their supplied latitude and longitude in point
mode. Both families’ gridded reconstructions now have ascending x and
descending y by default. native keeps south-to-north rows on the
reconstructed grid. Sectorised mtg_li_lef has no gridded mode.
An earlier longitude correction fixed mirrored geolocation in LI accumulated products, both sparse and gridded. Outputs written before that correction need regeneration. That correction also changed the x direction of LI point-to-grid and FCI outputs while preserving their geolocation. The current orientation option operates after those corrections, and does not undo them.
FCI L1c normalises every resolution independently. With
upper_right_corner="native", its raster retains the granule’s row
and column order, matching Satpy’s native presentation. The default
NE reverses those rows for north-up display. Coordinate-based
selections still identify the same physical pixels, while positional
selections and bare imshow output change. When appending to an older
Zarr store, orient incoming data to the store’s axes or regenerate it;
the writer rejects mismatched coordinate arrays.
For a consumer that depends on source row indices, make the choice explicit:
dataset = reader.read(path, upper_right_corner="native")
The Data Cube reader contract is tested with both the default and
native, including coordinate-selected science pixels and ancillary
variables. If you switch to native, choose the display and indexing
convention your application expects. Convert existing positional crops
to that orientation, or replace them with coordinate selections.
What to do next
To add an output format for the datasets returned by your reader, continue with Write a writer plugin. For a custom processing operation, follow Write a transformation plugin.