Documents · Verb reference
threshold_state
Convert raw values to a standard state cube using a threshold.
Callable type: Grammar verb / pipe stage · Browse: State and events
Usage
from cubedynamics import verbs as v
v.threshold_state(*, threshold, direction, variable=None, name=None)
Arguments
| Argument | Meaning | Default |
|---|---|---|
| threshold | See implementation docstring below; no parameter-specific description supplied. | required |
| direction | See implementation docstring below; no parameter-specific description supplied. | required |
| variable | See implementation docstring below; no parameter-specific description supplied. | None |
| name | See implementation docstring below; no parameter-specific description supplied. | None |
Accepts
A continuous or categorical xarray field, or a summary produced by a reduction. Dataset inputs require variable= unless they contain only one data variable.
Returns
A condition Dataset with state, magnitude, and threshold variables plus explicit condition metadata.
Order / grammar behavior
Threshold then mean measures condition prevalence; mean then threshold defines a condition from an aggregate. Both are valid and intentionally distinct.
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})
From continuous values to a state
On which days did a grid cell remain at or below freezing even at its daily maximum?
cold = (pipe(cube) | v.threshold_state(threshold=0, direction="below")).unwrap()
site = cube.isel(y=12, x=12)
state = cold.state.isel(y=12, x=12)
np.testing.assert_array_equal(state, site <= 0)
fig, axes = plt.subplots(2, 1, figsize=(5.4, 5.4), sharex=True, layout="constrained")
site.plot(ax=axes[0], color="#246b70", marker="o")
axes[0].axhline(0, color="0.4", linestyle="--", label="Threshold: 0°C")
axes[0].set(title="Before · PRISM daily maximum", ylabel="Temperature (°C)", xlabel="")
axes[0].legend(frameon=False)
axes[1].step(state.time, state.astype(int), where="mid", color="#246b70")
axes[1].set(title="After threshold_state() · at or below 0°C", xlabel="Date", ylabel="State", yticks=[0, 1], ylim=(-0.1, 1.1))
plt.show()

What changed? A true state describes a criterion, not an event duration or an ecological impact. This complete fixture has no missing values; missing-data policy must be checked for other inputs.
Works with
A continuous or categorical xarray field, or a summary produced by a reduction. Dataset inputs require variable= unless they contain only one data variable.
See also
- Working Lands · Read hot-and-dry weather as two nouns
- 06 · From cold observations to event evidence
- Learn: verbs
- Noun library
- Verbs by purpose
- All public callables (A–Z)
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.