Skip to content

Composition

The composition primitives are carrier-agnostic and live in pipekit; the xarray-aware Operator base and the Dataset combinators are xrops:

from pipekit_ops import Sequential, Graph, Input, Node
from xrops import Augment, Operator

xrops.Operator is a thin xarray-aware subclass of pipekit_ops.Operator that adds xarray.DataTree dispatch to __call__ — every operator in the library inherits it, so all of them map leaf-wise over a DataTree for free. The xarray-Dataset-specific combinators (Augment, ApplyToEach) live in xrops.combinators.

Linear and DAG composition, same operators

from pipekit_ops import Sequential, Graph, Input
from xrops.anomaly import RemoveMean
from xrops.ocn import Streamfunction, GeostrophicVelocities

# Linear pipeline
pipe = Sequential(RemoveMean(dim=("lat", "lon")), GeostrophicVelocities())
out = pipe(ds)

# The same operators wired as a DAG
x = Input("ssh")
psi = Streamfunction()(x)
uv = GeostrophicVelocities()(psi)
graph = Graph(inputs=x, outputs=uv)

Operator base class

Operator

Bases: Operator

pipekit_ops.Operator plus xarray DataTree dispatch.

Subclasses implement _apply(carrier, *extra) exactly as they would against pipekit_ops.Operator — the override only affects __call__ dispatch, not _apply.

Example

One _apply implementation serves Dataset and DataTree callers alike — the tree case maps over every leaf:

>>> import numpy as np
>>> import xarray as xr
>>> from xrops import Operator
>>> class Scale(Operator):
...     def __init__(self, factor: float) -> None:
...         self.factor = factor
...     def _apply(self, ds: xr.Dataset) -> xr.Dataset:
...         return ds * self.factor
>>> ds = xr.Dataset({"ssh": ("x", np.arange(3.0))})
>>> Scale(10.0)(ds)["ssh"].values
array([ 0., 10., 20.])
>>> tree = xr.DataTree.from_dict({"coarse": ds, "fine": ds * 2})
>>> out = Scale(10.0)(tree)
>>> sorted(out.children), float(out["fine"]["ssh"][2])
(['coarse', 'fine'], 40.0)

Sequential pipelines

Sequential is pipekit's, documented with the geotoolz operators.

Functional Graph API

Input, Node and Graph are pipekit's, documented with the geotoolz operators.

Observation taps

Tap is a generic pass-through observer from pipekit_ops — it runs a side-effecting callback (logging, plotting, assertions) without altering the data flowing through.

It is documented with the geotoolz operators: Tap.

xarray-Dataset combinators

Augment merges an operator's output back into its input Dataset (rather than replacing it); ApplyToEach maps an operator over every data variable independently.

Augment

Augment(inner: Operator)

Bases: Operator

Run an inner Operator and merge its output back into the input.

The inner operator must accept a Dataset and return a Dataset. The return value of :class:Augment is input.merge(inner(input)) — the input's existing variables are preserved, and the inner op's new variables are added alongside.

The merge is invoked with compat="no_conflicts" (xarray's safe default), so if the inner op produces a variable name that already exists in the input and the values differ, the merge raises rather than silently overwriting. Diagnostics that share an output name with one of their inputs (rare in practice) need to be renamed before being wrapped.

The combinator is the canonical idiom for chaining diagnostics inside a Sequential: each step augments the threaded Dataset with new columns, so later diagnostics can depend on variables added by earlier ones.

Parameters:

Name Type Description Default
inner Operator

The inner :class:Operator. Must accept a single xr.Dataset and return an xr.Dataset. Standard single-input xrops.ocn diagnostics (RelativeVorticity, KineticEnergy, GeostrophicVelocities, Divergence, ...) satisfy this contract. Two-input metrics (RMSE, MAE, ...) and operators that return a DataArray rather than a Dataset do not fit and will raise at call time.

required

Raises:

Type Description
TypeError

If inner is not an :class:Operator (raised at construction), or if inner(ds) does not return a Dataset (raised at call time).

MergeError

If the inner op's output collides with an existing input variable whose values do not match.

Example

Build a single Dataset carrying every kinematic diagnostic for a velocity field::

from xrops import Augment, Sequential
from xrops.ocn.operators import (
    RelativeVorticity, KineticEnergy, OkuboWeiss,
)

diagnostics = Sequential([
    Augment(RelativeVorticity()),    # adds vort_r
    Augment(KineticEnergy()),         # adds ke
    Augment(OkuboWeiss()),            # adds ow
])
enriched = diagnostics(velocity_dataset)
# enriched has u, v, vort_r, ke, ow

Diagnostics that depend on previously-added columns work transparently because Sequential threads the merged Dataset forward::

Sequential([
    Augment(RelativeVorticity()),                # adds vort_r
    Augment(Enstrophy(variable="vort_r")),       # reads vort_r
])
See Also

:class:Sequential — chain :class:Augment calls together. :class:ApplyToEach — augment with one diagnostic across many variables.

Source code in packages/xrtoolz-ops/src/xrops/combinators.py
def __init__(self, inner: _PipekitOperator) -> None:
    # Accept any pipekit Operator (xrops.Operator is a subclass), so
    # users can wrap composites like ``Sequential`` that still live on
    # pipekit's carrier-agnostic base.
    if not isinstance(inner, _PipekitOperator):
        raise TypeError(
            f"Augment expects an Operator instance, got {type(inner).__name__}."
        )
    self.inner = inner

ApplyToEach

ApplyToEach(prototype: Operator, *, kwarg: str, values: Sequence[Any])

Bases: Operator

Re-instantiate a prototype operator per value and merge results.

Given a prototype :class:Operator, a kwarg name, and a sequence of values, :class:ApplyToEach builds and runs one new instance of the prototype's class per value, varying the chosen kwarg. Each resulting Dataset is merged into the input with the same safe compat="no_conflicts" semantics as :class:Augment.

The behaviour is equivalent to::

Sequential([
    Augment(prototype.__class__(**{**proto_config, kwarg: v}))
    for v in values
])

Each rebuilt operator runs against the threaded result, not the original input — i.e. the second pass sees the variables added by the first pass. This is what makes the equivalence with Sequential([Augment(...) for v in values]) exact, and lets later sweeps consume variables produced by earlier ones.

The prototype's get_config() is read once and used as the base kwargs dict for the rebuilt instances. The prototype's class must therefore satisfy the leaf contract cls(**proto.get_config()) — i.e. its get_config must return a dict directly usable as constructor kwargs. All single-operator Layer 1 classes in xrops satisfy this; the composite/combinator classes (Sequential, Graph, Augment, Tap, ApplyToEach itself) do not, because their configs carry serialized child records rather than live operator instances. ApplyToEach validates this contract at construction time via a sentinel rebuild and raises TypeError with a descriptive message if it fails.

Each rebuilt operator must produce uniquely-named output variables across the value sweep, otherwise the eventual merge raises. In practice most diagnostics name their output after the input variable they consume (e.g. Frontogenesis(scalar="ssh") → ssh_frontogenesis), so this is not usually a concern.

Parameters:

Name Type Description Default
prototype Operator

A configured single-operator :class:Operator instance. Composite classes such as Sequential or other combinators are not accepted (see contract above).

required
kwarg str

Name of the constructor kwarg to vary across the sweep. Must be a key of prototype.get_config().

required
values Sequence[Any]

Sequence of values to substitute for kwarg. Each entry is used to build one rebuilt operator.

required

Raises:

Type Description
TypeError

If prototype is not an :class:Operator, or if prototype.get_config() cannot be passed back to its class constructor (composite-config case), or if any rebuilt op does not return a Dataset.

ValueError

If kwarg is not present in prototype.get_config().

Example

Compute frontogenesis for three scalars in one call::

from xrops import ApplyToEach
from xrops.ocn.operators import Frontogenesis

multi_fg = ApplyToEach(
    Frontogenesis(scalar="ssh"),
    kwarg="scalar",
    values=["ssh", "thetao", "so"],
)
out = multi_fg(ds)
# out has ssh_frontogenesis, thetao_frontogenesis,
# so_frontogenesis merged in alongside the original
# variables.

Inside a Sequential that augments the dataset before and after::

Sequential([
    ValidateCoords(),
    ApplyToEach(
        Frontogenesis(scalar="ssh"),
        kwarg="scalar",
        values=["thetao", "so"],
    ),
    Augment(KineticEnergy()),
])
See Also

:class:Augment — wrap a single inner op to merge its output.

Source code in packages/xrtoolz-ops/src/xrops/combinators.py
def __init__(
    self,
    prototype: _PipekitOperator,
    *,
    kwarg: str,
    values: Sequence[Any],
) -> None:
    if not isinstance(prototype, _PipekitOperator):
        raise TypeError(
            f"ApplyToEach expects an Operator prototype, "
            f"got {type(prototype).__name__}."
        )
    base_config = prototype.get_config()
    if kwarg not in base_config:
        raise ValueError(
            f"ApplyToEach: kwarg {kwarg!r} not present in "
            f"{prototype.__class__.__name__}.get_config(); "
            f"available keys: {sorted(base_config)}."
        )
    # Fail fast if the prototype's config carries any serialized
    # child Operator records (the ``{"class", "config"}`` shape
    # used by Augment/ApplyToEach/Sequential/Graph for nested
    # operator state). Such a prototype cannot be replayed by
    # ``cls(**get_config())`` because the constructor expects
    # live Operator instances rather than dicts.
    cls = type(prototype)
    if _has_serialized_operator_record(base_config):
        raise TypeError(
            f"ApplyToEach: prototype {cls.__name__} cannot be "
            f"reconstructed from its own get_config() — its config "
            f"carries serialized child operator records "
            f'(``{{"class", "config"}}`` dicts) rather than live '
            f"Operator instances. This is a known limitation for "
            f"composite operators (Sequential, Graph, Augment, "
            f"ApplyToEach). Pass a single-operator prototype "
            f"whose get_config() returns plain constructor kwargs."
        )
    self.prototype = prototype
    self.kwarg = kwarg
    self.values = list(values)

Shape signatures

Signature is pipekit's shape descriptor (ordered (name, size) dims and a dtype), used by compute_output_signature for static shape inference across a pipeline.

Signature dataclass

Signature(dims: tuple[tuple[str, int | None], ...], dtype: str | None = None)

Immutable shape + dtype record.

Attributes:

Name Type Description
dims tuple[tuple[str, int | None], ...]

Tuple of (name, size) pairs. size may be None to mark a dim as dynamic / unknown. Order matters — it's the carrier's axis order.

dtype str | None

A dtype label (e.g. "float32", "int64") or None if the operator doesn't track dtype.

Example::

sig = Signature(dims=(("time", 12), ("y", 256), ("x", 256)), dtype="float32")
sig.format()                       # "(time=12, y=256, x=256) float32"
sig.drop_dims(("time",))           # drops the time axis
sig.replace_dims({"x": 128})       # change the x size

format

format() -> str

Return a compact "(name=size, …) dtype" string.

Source code in .venv/lib/python3.12/site-packages/pipekit_ops/carriers/_signature.py
def format(self) -> str:
    """Return a compact ``"(name=size, …) dtype"`` string."""
    parts = ", ".join(
        f"{name}={'?' if size is None else size}" for name, size in self.dims
    )
    dtype = self.dtype if self.dtype is not None else "?"
    return f"({parts}) {dtype}"

drop_dims

drop_dims(names: tuple[str, ...]) -> Signature

Return a new Signature with the given dim names removed.

Raises:

Type Description
KeyError

if a name in names isn't present.

Source code in .venv/lib/python3.12/site-packages/pipekit_ops/carriers/_signature.py
def drop_dims(self, names: tuple[str, ...]) -> Signature:
    """Return a new `Signature` with the given dim names removed.

    Raises:
        KeyError: if a name in ``names`` isn't present.
    """
    present = {n for n, _ in self.dims}
    missing = set(names) - present
    if missing:
        raise KeyError(f"drop_dims: unknown dim(s) {sorted(missing)}.")
    kept = tuple((n, s) for n, s in self.dims if n not in set(names))
    return Signature(dims=kept, dtype=self.dtype)

replace_dims

replace_dims(sizes: dict[str, int | None]) -> Signature

Return a new Signature with the listed dim sizes overridden.

Raises:

Type Description
KeyError

if a name in sizes isn't present.

Source code in .venv/lib/python3.12/site-packages/pipekit_ops/carriers/_signature.py
def replace_dims(self, sizes: dict[str, int | None]) -> Signature:
    """Return a new `Signature` with the listed dim sizes overridden.

    Raises:
        KeyError: if a name in ``sizes`` isn't present.
    """
    present = {n for n, _ in self.dims}
    missing = set(sizes) - present
    if missing:
        raise KeyError(f"replace_dims: unknown dim(s) {sorted(missing)}.")
    new = tuple((n, sizes.get(n, s)) for n, s in self.dims)
    return Signature(dims=new, dtype=self.dtype)

matches

matches(pattern: str) -> bool

Whether these dims fit a dims pattern; sizes are ignored.

A pattern is whitespace-separated dim names with at most one ..., which matches zero or more dims at its position. Names compare exactly and in order.

Parameters:

Name Type Description Default
pattern str

E.g. "band y x" (exactly these dims) or "... y x" (any leading dims, then y and x).

required

Raises:

Type Description
ValueError

if the pattern has more than one ....

Examples:

>>> sig = Signature(dims=(("time", 12), ("band", 2), ("y", 4), ("x", 4)))
>>> sig.matches("time band y x"), sig.matches("... y x")
(True, True)
>>> sig.matches("band y x"), sig.matches("time ... x")
(False, True)
Source code in .venv/lib/python3.12/site-packages/pipekit_ops/carriers/_signature.py
def matches(self, pattern: str) -> bool:
    """Whether these dims fit a dims pattern; sizes are ignored.

    A pattern is whitespace-separated dim names with at most one
    ``...``, which matches zero or more dims at its position. Names
    compare exactly and in order.

    Args:
        pattern: E.g. ``"band y x"`` (exactly these dims) or
            ``"... y x"`` (any leading dims, then ``y`` and ``x``).

    Raises:
        ValueError: if the pattern has more than one ``...``.

    Examples:
        >>> sig = Signature(dims=(("time", 12), ("band", 2), ("y", 4), ("x", 4)))
        >>> sig.matches("time band y x"), sig.matches("... y x")
        (True, True)
        >>> sig.matches("band y x"), sig.matches("time ... x")
        (False, True)
    """
    names, ellipsis = _parse_pattern(pattern)
    dims = tuple(name for name, _ in self.dims)
    if ellipsis is None:
        return dims == tuple(names)
    head = tuple(names[:ellipsis])
    tail = tuple(names[ellipsis:])
    if len(dims) < len(head) + len(tail):
        return False
    return dims[: len(head)] == head and dims[len(dims) - len(tail) :] == tail

from_pattern classmethod

from_pattern(pattern: str, dtype: str | None = None) -> Signature

A sizeless Signature from a dims pattern, for annotations.

Parameters:

Name Type Description Default
pattern str

Whitespace-separated dim names, e.g. "band y x".

required
dtype str | None

An optional dtype label.

None

Raises:

Type Description
ValueError

if the pattern has a ... (a signature needs concrete names) or repeats a name.

Example

Signature.from_pattern("band y x").dims (('band', None), ('y', None), ('x', None))

Source code in .venv/lib/python3.12/site-packages/pipekit_ops/carriers/_signature.py
@classmethod
def from_pattern(cls, pattern: str, dtype: str | None = None) -> Signature:
    """A sizeless `Signature` from a dims pattern, for annotations.

    Args:
        pattern: Whitespace-separated dim names, e.g. ``"band y x"``.
        dtype: An optional dtype label.

    Raises:
        ValueError: if the pattern has a ``...`` (a signature needs
            concrete names) or repeats a name.

    Example:
        >>> Signature.from_pattern("band y x").dims
        (('band', None), ('y', None), ('x', None))
    """
    names, ellipsis = _parse_pattern(pattern)
    if ellipsis is not None:
        raise ValueError(
            f"from_pattern needs concrete dim names, got {pattern!r} with '...'."
        )
    return cls(dims=tuple((name, None) for name in names), dtype=dtype)