Composition¶
The composition primitives are carrier-agnostic and live in
pipekit; the xarray-aware
Operator base and the Dataset combinators are xrops:
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: |
required |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
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
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: |
required |
kwarg
|
str
|
Name of the constructor kwarg to vary across the
sweep. Must be a key of |
required |
values
|
Sequence[Any]
|
Sequence of values to substitute for |
required |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If |
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
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
¶
Immutable shape + dtype record.
Attributes:
| Name | Type | Description |
|---|---|---|
dims |
tuple[tuple[str, int | None], ...]
|
Tuple of |
dtype |
str | None
|
A dtype label (e.g. |
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
¶
Return a compact "(name=size, …) dtype" string.
Source code in .venv/lib/python3.12/site-packages/pipekit_ops/carriers/_signature.py
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 |
Source code in .venv/lib/python3.12/site-packages/pipekit_ops/carriers/_signature.py
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 |
Source code in .venv/lib/python3.12/site-packages/pipekit_ops/carriers/_signature.py
matches
¶
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. |
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
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. |
required |
dtype
|
str | None
|
An optional dtype label. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
if the pattern has a |
Example
Signature.from_pattern("band y x").dims (('band', None), ('y', None), ('x', None))