Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Operators & Pipelines — a keras-style tour

Open In Colab

This notebook walks through the core composition primitives in xrtoolz — Operator, the | pipe, Sequential, two-input metric Operators, and a user-defined plot Operator — using the small air_temperature tutorial dataset that ships with xarray.

The keras analogy. If you’ve used keras, the mapping is:

kerasxrtoolz
LayerOperator
SequentialSequential
Functional APIGraph (teaser at the end)
model.get_config()op.get_config()
metric / losstwo-input Operator
Lambda / callbackpass-through Operator

Setup

Colab-friendly install + imports.

1. Load a tiny dataset

We use xr.tutorial.open_dataset("air_temperature") — NCEP/NCAR 2 m air temperature on a 2.5° grid, 4× daily for 2013–2014. Pooch caches it to ~/.cache/xarray_tutorial_data after the first download (~4 MB).

Loading...
<Figure size 700x300 with 2 Axes>

2. An Operator is just a configured callable

Like a keras layer, an Operator is an object that holds configuration and exposes __call__. The same instance can be reused on many datasets.

ValidateCoords()
config: {}
lon range after validate: -160.0 -30.0

Note how ValidateCoords flipped the longitudes from [0, 360) to (-180, 180]. The rest of the notebook works in the validated convention.

3. Composing with |

The pipe operator builds a Sequential left-to-right. Each step is a single-input transform on a Dataset.

Sequential
Loading...
<Figure size 1100x320 with 4 Axes>

4. Sequential as a “model”

Sequential([...]) is the explicit form. It exposes .describe() (a la model.summary()) and .get_config() for serialization.

Sequential([
  ValidateCoords(),
  SubsetBBox(lon_bnds=[-125, -65], lat_bnds=[25, 50], lon='lon', lat='lat'),
  ResampleTime(freq='1D', method='mean', time='time', interp_method='linear'),
])

Operator            Input sig                                       Output sig                                    
------------------------------------------------------------------------------------------------------------------
[0] ValidateCoords  Signature((time=2920, lat=25, lon=53) float64)  Signature((time=2920, lat=25, lon=53) float64)
[1] SubsetBBox      Signature((time=2920, lat=25, lon=53) float64)  Signature((time=2920, lat=?, lon=?) float64)  
[2] ResampleTime    Signature((time=2920, lat=?, lon=?) float64)    Signature((time=?, lat=?, lon=?) float64)     
{
  "operators": [
    {
      "module": "xrops.cf.operators",
      "class": "ValidateCoords",
      "config": {}
    },
    {
      "module": "xrops.geom.operators",
      "class": "SubsetBBox",
      "config": {
        "lon_bnds": [
          -125,
          -65
        ],
        "lat_bnds": [
          25,
          50
        ],
        "lon": "lon",
        "lat": "lat"
      }
    },
    {
      "module": "xrops.interpolate.operators",
      "class": "ResampleTime",
      "config": {
        "freq": "1D",
        "method": "mean",
        "time": "time",
        "interp_method": "linear"
      }
    }
  ]
}

5. Nesting pipelines

Because Sequential is itself an Operator, pipelines compose. We split the data into a 2013 “training” year (used to fit a day-of-year climatology) and a 2014 “test” year, then build an anomaly pipeline that stacks the preprocessor with the climatology removal.

climatology dims: {'dayofyear': 365, 'lat': 11, 'lon': 25}
Sequential([
  ValidateCoords(),
  SubsetBBox(lon_bnds=[-125, -65], lat_bnds=[25, 50], lon='lon', lat='lat'),
  ResampleTime(freq='1D', method='mean', time='time', interp_method='linear'),
  RemoveClimatology(climatology='<xr object>', time='time'),
])

Operator               Input sig                                       Output sig                                    
---------------------------------------------------------------------------------------------------------------------
[0] ValidateCoords     Signature((time=2920, lat=25, lon=53) float64)  Signature((time=2920, lat=25, lon=53) float64)
[1] SubsetBBox         Signature((time=2920, lat=25, lon=53) float64)  Signature((time=2920, lat=?, lon=?) float64)  
[2] ResampleTime       Signature((time=2920, lat=?, lon=?) float64)    Signature((time=?, lat=?, lon=?) float64)     
[3] RemoveClimatology  Signature((time=?, lat=?, lon=?) float64)       Signature((time=?, lat=?, lon=?) float64)     
<Figure size 800x350 with 2 Axes>

6. Metric Operators are just two-input Operators

xrtoolz ships pixel metrics (MSE, RMSE, MAE, Bias, Correlation, R2Score, PSDScore) as Operator subclasses. Their _apply takes two datasets — a prediction and a reference — so the call site looks like metric(pred, ref) rather than the single-arg pipeline form.

We build a deliberately weak baseline: predict 2014 with the 2013 climatology. (The point is the mechanics, not skill.)

daily RMSE timeseries dims: {'time': 365}
spatial RMSE map  dims: {'lat': 11, 'lon': 25}
config: {'variable': 'air', 'dims': ['lat', 'lon']}
{'RMSE': 6.026034023457552, 'Bias': -0.27575987546699765, 'Corr': 0.8639636737518275}
<Figure size 800x300 with 1 Axes>

7. A plot is also just an Operator

Subclassing Operator is the recipe for adding new behavior — exactly the keras moment when you discover layers are 30 lines. Required parts:

  1. __init__ storing config

  2. _apply(self, *args) doing the work

  3. get_config() returning a JSON-serializable dict

Plot Operators are pass-through: they do a side-effect (render a figure) and return the input unchanged so they slot anywhere inside a chain.

Use 1 — drop it into a chain as a debug “print layer”. Two figures render in a single pipeline call, before and after the climatology removal.

<Figure size 600x300 with 2 Axes>
<Figure size 600x300 with 2 Axes>

Use 2 — visualise a metric Operator’s output. The spatial RMSE map from §6 is just another DataArray, so the same PlotMap instance works.

<Figure size 600x300 with 2 Axes>
Loading...

get_config() works the same as the built-in operators.

{'variable': 'air', 'cmap': 'magma', 'title': None}

8. Stretch — Graph for branching

When the pipeline isn’t a straight line — e.g. you want to fan out from a shared preprocessed input into several heads — switch to the functional Graph API. Operators are reused; calling them on Nodes builds a DAG instead of executing eagerly.

outputs: ['test', 'anomaly']
test    air mean: 286.38612575342466
anomaly air mean: 0.27575987546699765

Wrap-up

What we covered, in keras vocabulary:

  • Operator — configured callable; same role as a keras Layer.

  • | — pipe sugar that returns a Sequential.

  • Sequential — linear pipeline; itself an Operator, so it nests.

  • get_config() / .describe() — introspection contract every Operator honours, including ones you write.

  • Two-input Operators — metrics (RMSE, Bias, ...) take (pred, ref). They have the same config shape as single-input ops.

  • Pass-through Operators — PlotMap returns its input unchanged so it drops into any chain as a debug/visualisation step.

  • Graph — for non-linear pipelines (multiple inputs, fan-out, fan-in).

The recipe for new behavior is always the same: subclass Operator, implement _apply, return a JSON-serializable get_config(), and you’re automatically composable with everything else in xrtoolz.