Skip to content

Documents · Verb reference

anomaly

Return a pipe verb that subtracts the mean over dim.

Callable type: Grammar verb / pipe stage · Browse: Transform

Usage

from cubedynamics import verbs as v
v.anomaly(dim='time', *, over=None, keep_dim=True)

Arguments

Argument Meaning Default
dim See implementation docstring below; no parameter-specific description supplied. 'time'
over See implementation docstring below; no parameter-specific description supplied. None
keep_dim See implementation docstring below; no parameter-specific description supplied. True

Accepts

An xarray DataArray or Dataset with the dimensions required by the selected operation. VirtualCube support is operation-specific; consult the implementation notes.

Returns

A callable stage. Applying it returns the transformed xarray object (or the supported VirtualCube result).

Order / grammar behavior

Apply before reductions that remove a required dimension. Choose the reduction dimensions explicitly; keep_dim=False removes reduced axes.

Minimal example

REAL DATA · Reviewed local PRISM observations; no live request.

Reproduce: imports, checked data and setup

Run in a clone after python -m pip install -e '.[vignettes]'.

from pathlib import Path
import hashlib
import json
import numpy as np
import pandas as pd
import xarray as xr
import matplotlib.pyplot as plt
from IPython.display import display
from cubedynamics import pipe, verbs as v

# Run in the cloned repository or beside a downloaded notebook in the repo.
repo = next(p for p in (Path.cwd(), *Path.cwd().parents)
            if (p / "tests/fixtures/real_data").is_dir())

def observed_cube(stem, variable):
    path = repo / "tests/fixtures/real_data" / (stem + ".nc")
    record = json.loads(path.with_suffix(".provenance.json").read_text())
    assert hashlib.sha256(path.read_bytes()).hexdigest() == record["fixture_sha256"]
    with xr.open_dataset(path, engine="scipy") as dataset:
        assert not dataset.attrs["is_synthetic"]
        result = dataset[variable].load()  # Only this small, reviewed local extract.
        result.attrs = {**dataset.attrs, **result.attrs}
    assert result.dims == ("time", "y", "x")
    assert np.all(np.diff(result.x) > 0) and np.all(np.diff(result.y) < 0)
    assert bool(np.isfinite(result).all())
    return result

cube = observed_cube("prism_boulder_january_2024", "tmax").rename("temperature")
assert cube.attrs["units"] == "degC"

plt.rcParams.update({'font.family': 'DejaVu Sans', 'font.size': 12, 'axes.titlesize': 13, 'axes.labelsize': 12, 'figure.facecolor': 'white', 'axes.facecolor': 'white', 'savefig.facecolor': 'white', 'figure.dpi': 140})
window = (pipe(cube)
          | v.apply(lambda c: c.sel(time=slice("2024-01-10", "2024-01-20")))).unwrap()
assert window.sizes["time"] == 11

Remove the local baseline

Where was 16 January colder than each pixel’s own selected-period mean?

departures = (pipe(window) | v.anomaly(dim="time")).unwrap()

fig, axes = plt.subplots(2, 1, figsize=(5.4, 6.5), layout="constrained")
window.sel(time="2024-01-16").plot(ax=axes[0], cmap="magma", cbar_kwargs={"label": "°C"})
departures.sel(time="2024-01-16").plot(ax=axes[1], cmap="RdBu_r", center=0,
                                    cbar_kwargs={"label": "Departure (°C)"})
for ax, title in zip(axes, ["Before · absolute temperature", "After anomaly() · local departure"]):
    ax.set(title=title, xlabel="Longitude (°E)", ylabel="Latitude (°N)")
plt.show()
PRISM, Boulder, 16 January 2024: absolute maximum temperature above and anomaly below. anomaly() subtracts each pixel’s 10–20 January mean; the diverging scale is centered on zero.
PRISM, Boulder, 16 January 2024: absolute maximum temperature above and anomaly below. anomaly() subtracts each pixel’s 10–20 January mean; the diverging scale is centered on zero.

What changed? Negative departures mean colder than that pixel’s baseline. The coldest absolute location need not have the largest departure. A short event-window baseline is not a long-term climate normal.

Generating code · Figure/input provenance

Works with

An xarray DataArray or Dataset with the dimensions required by the selected operation. VirtualCube support is operation-specific; consult the implementation notes.

See also

Implementation notes

No additional implementation notes in the current docstring.

Implementation source. Signatures and descriptions on this page are generated from this checkout, not hand-maintained copies.