Write a transformation plugin
This guide explains how to create a transformation plugin for DEFAIR. A transformation plugin changes a dataset: reprojection, filtering and aggregation are all transformations.
Before implementing the plugin, complete the shared setup in Plugin Development.
Prerequisites
No. 1 A small input dataset and its expected result
Prepare a dataset with a known expected result for the operation, so the tests can check the transformation’s output.
Overview
Transformation plugins extend the TransformationPlugin base class
and are discovered through the defair_ops.transformations
entry-point group. They receive a DEFAIR Dataset, operate on the
xarray object inside it and return a new Dataset, keeping Dask lazy
evaluation for streaming workflows.
The skeleton below is a minimal working example of the interface, not a
production transformation: it multiplies every data variable by a
factor. It runs against DEFAIR 0.4.3, passes workflow validation and
returns a lazy result. Model a real transformation on a complete
built-in such as SpatialFilterPlugin, which shows named options, CF
history tracking and per-coordinate-group handling. Its source comes
with DEFAIR:
python -c "import defair_ops.transformations.spatial_filter.spatial_filter_plugin as m; print(m.__file__)"
prints where its source is installed.
Minimal Transformation Plugin Skeleton
Replace the body of transform() and the my_parameter option with
your own logic and options. The class name, the name property, the
target parameter and the Dataset(...) return are the parts every
transformation keeps.
from defair_data.core import Dataset
from defair_ops.core import TransformationPlugin
class MyTransformationPlugin(TransformationPlugin):
"""Scale every floating-point data variable by a factor."""
@property
def name(self) -> str:
"""Return the operation name used in workflow configs."""
return "my_transformation"
def transform(
self,
dataset: Dataset,
target: str | None = None,
my_parameter: float = 1.0,
) -> Dataset:
"""Multiply every floating-point data variable by my_parameter.
Args:
dataset: Input dataset
target: Unused here, declared because the base class declares it
my_parameter: Scale factor, named so a workflow file can pass it
Returns:
A new Dataset whose arrays are still Dask-backed
"""
ds = dataset.data
# Flags, masks and the grid-mapping variable are integer data variables too, so leave them unscaled
result = ds.map(lambda da: da * my_parameter if da.dtype.kind == "f" else da, keep_attrs=True)
history = result.attrs.get("history", "")
result.attrs["history"] = f"{history} | Applied {self.name}".strip(" |")
return Dataset(result)
Three rules the skeleton follows, and DEFAIR enforces:
Every option is a named parameter with a type annotation. When DEFAIR loads a workflow file, it ignores
**kwargsand rejects any YAML key that is not a named parameter of__init__ortransform(). An option read fromkwargscan never be set from a workflow file: the run fails withInvalid operation parameters: ['my_parameter']. Named options are also type-checked from their annotations, somy_parameter: "two"is rejected beforetransform()runs.targetis declared asstr | None = None, matching the base class. Keep it even when unused, becauseDataset.transform()always passes it.The xarray object is
dataset.data. TheDatasetwrapper forwards methods it does not define, such ascopy()ormap(), to that object, but working ondataset.dataand wrapping the result once keeps the code explicit, as every built-in does.Dataset(result)rebuilds the common data model from the attributes the input carried, which is right only while the grid is unchanged. On a new grid it keeps a contract with no spatial group. A transformation that changes the grid either drops the contract withDataset(CommonDataModel.strip(result))(from defair_data.cdm import CommonDataModel), or builds a new one and attaches it withDataset.with_cdm, as reprojection does.
Registration via Entry Points
Standalone package
A third-party plugin 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-ops>=0.4.3"]
[project.entry-points."defair_ops.transformations"]
my_transformation = "my_defair_plugin.transformations:MyTransformationPlugin"
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
Put the class in my_defair_plugin/transformations.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 name a workflow file uses under
operation:, and the value is module:Class. defair-ops
depends on defair and defair-data, 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 .
python -c "from defair.plugin_manager import list_transformations, load_transformation
print('my_transformation' in list_transformations(), load_transformation('my_transformation').name)"
Expected output: True my_transformation. There is no defair
subcommand that lists transformations (the CLI subcommands are
readers, eda, run, validate and version), so this
two-line check is the discovery test. A missing entry point raises
ValueError: Plugin 'my_transformation' not found in group 'defair_ops.transformations'.
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.
Using the plugin
From a workflow file, the entry-point name goes under operation: and
each option under its own name:
transformations:
- operation: my_transformation
my_parameter: 2.0
From Python:
dataset.transform("my_transformation", my_parameter=2.0).
Preserving Lazy Evaluation
Critical
Transformation plugins must preserve Dask lazy evaluation for streaming workflows.
Operate on Dask arrays without forcing computation.
Use xarray operations that preserve chunking.
Return datasets with Dask-backed arrays.
Chain operations naturally, as xarray handles Dask.
Do not call
.compute(),.load(), or.valuesunless absolutely necessary.Do not materialize entire datasets in memory.
Do not break Dask task graphs.
Do not assume datasets fit in RAM.
Example of lazy operations:
# Correct: All operations stay lazy
ds = dataset.data
result = ds.copy()
result["temperature"] = result["temperature"] + 273.15 # Lazy
result["normalized"] = (result["temperature"] - result["temperature"].mean()) / result["temperature"].std() # Lazy
# Wrong: Forces computation
temp_values = ds["temperature"].values # Materializes to numpy array
result["temperature"] = temp_values + 273.15 # No longer Dask-backed
Test your transformation plugin
Testing a standalone plugin
The tests live in the plugin repository and need only the installed
DEFAIR distributions and pytest. Cover discovery, the result,
laziness and metadata:
import dask.array as da
import pytest
import xarray as xr
from defair.plugin_manager import list_transformations, load_transformation
from defair_data.core import Dataset
def _dataset() -> Dataset:
data = da.random.random((10, 10), chunks=(5, 5))
ds = xr.Dataset(
{"temperature": (["y", "x"], data, {"units": "K"})},
attrs={"Conventions": "CF-1.8", "history": "created"},
)
return Dataset(ds)
def test_my_transformation_discovered():
"""The entry point is installed and loads."""
assert "my_transformation" in list_transformations()
plugin = load_transformation("my_transformation")
assert plugin.name == "my_transformation"
def test_my_transformation_preserves_lazy():
"""The result is a Dataset whose arrays are still Dask arrays."""
dataset = _dataset()
plugin = load_transformation("my_transformation")
result = plugin.transform(dataset, my_parameter=2.0)
assert isinstance(result, Dataset)
assert isinstance(result.data["temperature"].data, da.Array)
expected = dataset.data["temperature"].isel(y=0, x=0).compute() * 2.0
assert result.data["temperature"].isel(y=0, x=0).compute() == pytest.approx(expected)
def test_my_transformation_metadata():
"""CF attributes survive and the history records the operation."""
result = load_transformation("my_transformation").transform(_dataset())
assert result.data.attrs["Conventions"] == "CF-1.8"
assert result.data["temperature"].attrs["units"] == "K"
assert "my_transformation" in result.data.attrs["history"]
def test_my_transformation_workflow_options():
"""A workflow file can pass the option by name, and a typo is rejected."""
from defair.models.workflow import TransformationConfig
TransformationConfig(operation="my_transformation", my_parameter=2.0)
with pytest.raises(ValueError, match="Invalid operation parameters"):
TransformationConfig(operation="my_transformation", my_paramter=2.0)
Run them from the plugin repository, with the plugin installed
(pip install -e .):
pytest -v
Dask Client Integration
Transformations have access to DEFAIR’s Dask client through the
dask_client property of the base class. It is acquired lazily on
first access, so a transformation that never touches it runs on Dask’s
default scheduler:
def transform(self, dataset: Dataset, target: str | None = None) -> Dataset:
"""Transform with explicit Dask client usage."""
ds = dataset.data
client = self.dask_client
# Most xarray operations use Dask on their own when the data is chunked.
# Reach for the client only for custom distributed work, for example client.scatter().
return Dataset(ds)
Note: Most transformations do not need direct client access. xarray handles Dask operations automatically.
What to do next
Follow Create a workflow file to call your registered transformation from YAML. If the operation needs distributed processing, use Run on a Dask cluster to choose and configure the execution environment.