Skip to content

Invariants

samudra.invariants checks ocean data against physics it must obey: masks nest with depth, water stays above freezing, heat enters only through the surface, and conservative regridding preserves heat and salt. Use it on a dataset you built, on a model's rollout, or on the output of a pipeline step. Ocean physics explains why each invariant holds and gives reference values for the published stores.

The checks ship with samudra, so a project that builds its own emulator can add samudra as a test dependency and run them on its own data. They take xarray or NumPy inputs and return plain records, with no training code involved. Releases up to 0.2.1 on PyPI don't include them yet; until the next release, install from GitHub:

pip install "samudra @ git+https://github.com/m2lines/Samudra"

How a check reports

Every check returns a list of Violations. An empty list means the data passes. A violation names the invariant, says what failed with the numbers needed to judge it, and, when it applies, gives one example location:

import xarray as xr
from samudra.invariants import geometry, masks

store = xr.open_zarr(
    "https://nyu1.osn.mghpcc.org/m2lines-pubs/Samudra/v2026-09/om4_onedeg/OM4.zarr", chunks={}
)
violations = masks.flattened_store(store, time_index=0) + geometry.sphere_area(store.areacello.load())
for violation in violations:
    print(violation)
masks.mask_matches_ocean_fraction: mask_4 disagrees with ocean_fraction > 0 in 2 cells at {'y': 161, 'x': 55}
masks.mask_matches_ocean_fraction: mask_8 disagrees with ocean_fraction > 0 in 1 cells at {'y': 168, 'x': 52}
masks.mask_matches_ocean_fraction: mask_13 disagrees with ocean_fraction > 0 in 1 cells at {'y': 171, 'x': 98}
masks.mask_matches_ocean_fraction: mask_14 disagrees with ocean_fraction > 0 in 1 cells at {'y': 174, 'x': 256}
masks.mask_matches_ocean_fraction: mask_15 disagrees with ocean_fraction > 0 in 1 cells at {'y': 175, 'x': 210}
masks.mask_matches_ocean_fraction: mask_16 disagrees with ocean_fraction > 0 in 1 cells at {'y': 167, 'x': 356}
geometry.sphere_area: total area 5.076655e+14 m2 differs from 4 pi R^2 = 5.100645e+14 m2 by 0.470%; implied radius 6356.0 km

Both are known deviations in v2026-09. Seven Arctic land cells have an ocean_fraction of up to 3 × 10⁻⁷ (#1030), and the cell areas were computed with Earth's polar radius, 6357 km, instead of its mean radius, 6371 km (#972).

Returning records, rather than raising, lets you collect every failure from several checks before deciding what to do. In a test, pass the list to require_no_violations, which raises InvariantViolated (an AssertionError) listing all of them.

What there is to check

Single-dataset checks hold for any one correct dataset:

Module Checks
masks Masks nest with depth; ocean_fraction lies in [0, 1] and doesn't grow with depth; fields are NaN exactly on land. flattened_store runs all of these on a store laid out like ours (thetao_0 … thetao_18, mask_0 …).
bounds Temperature at or above the freezing point for its salinity and depth; values within a range; coastal cells not dragged towards a land fill value (coastal_dilution).
geometry Cell areas tile the sphere; layers tile the water column; columns and total volume match the bathymetry.
timeaxis Times strictly increase; OM4's 5-day axis with its 6-day step at each leap-year boundary; forcing and state average over the same windows, in any cftime calendar.
budgets Heat-content tendency tracks the surface heat flux; total salt doesn't drift; area-mean zos is zero.

Metamorphic checks compare two versions of the same ocean, such as one field at two resolutions, before and after a pipeline step, or two releases:

Module Checks
conservation Area, volume, heat and salt integrals agree; variance doesn't grow and no new extremes appear when coarsening; zonal spectra agree at scales both grids resolve. Also builds the area and volume weights and heat and salt content the other checks use.
coupling The state responds to its forcing at lag zero, not a step early or late; surface currents turn from the wind the way Ekman drift does.
releases Two builds of a store agree everywhere, except in variables a documented change allows to differ.

Most checks take the names of their dimensions (y, x, lev by default) and work on curvilinear grids. The ones that need a regular lat-lon grid (geometry.rectilinear_cell_area and the zonal spectra) raise on any other grid.

Checking a model rollout

samudra eval writes its predictions to predictions.zarr, stacked by depth (so with a lev dimension). The static fields that weight the integrals come from the store the model was trained on. This checks that a rollout conserves total salt about as well as the ocean it emulates:

import numpy as np
import xarray as xr
from samudra.invariants import budgets, conservation, require_no_violations

truth = xr.open_zarr(
    "https://nyu1.osn.mghpcc.org/m2lines-pubs/Samudra/v2026-09/om4_onedeg/OM4.zarr", chunks={}
)
pred = xr.open_zarr("path/to/predictions.zarr")
volume = conservation.volume_weights(truth.areacello, truth.ocean_fraction, truth.dz)

def total_salt(so):
    return conservation.salt_content(so, volume, ["lev", "y", "x"]).values

truth_so = xr.concat([truth[f"so_{k}"] for k in range(truth.sizes["lev"])], dim=truth.lev)
reference = total_salt(truth_so.sel(time=pred.time))
drift = (np.nanmax(reference) - np.nanmin(reference)) / np.nanmean(reference)

require_no_violations(budgets.salt_drift(total_salt(pred.so), max_relative=2 * drift))

The bound comes from the truth over the same period. Total salt in the stores isn't constant: it swings by about 3 × 10⁻⁶ within a year as sea ice freezes and melts, and trends because bottom cells count their full thickness (#973). A fixed bound tighter than that fails on the truth too. Calibrating every tolerance on the truth first is a good habit with any of these checks.

Tolerances and known deviations

Each check takes tolerances, with defaults that suit the published stores. Budgets close only approximately in stored data (5-day means, nominal layer thicknesses, float32), so tighten or loosen them for your data, and say why in the call.

The v2026-09 stores fail a few checks for reasons we know: cell areas use the polar radius (#972), volume is about 10% high (#973), and a handful of land cells have slightly nonzero ocean_fraction (#1030). To pin a known deviation in a test without hiding new ones, mark it as an expected failure of this exception only:

@pytest.mark.xfail(reason="#972: areacello uses the polar radius", raises=InvariantViolated, strict=True)
def test_cells_tile_the_sphere():
    require_no_violations(geometry.sphere_area(store.areacello.load(), rtol=1e-4))

With raises=InvariantViolated, a network error or a renamed variable still fails the test. With strict=True, the test fails once the deviation is fixed, which reminds you to remove the marker.

This repository's own tests are examples: the pipeline's property tests in data/tests/test_*_properties.py and the audits of the published stores in data/tests/test_om4_live.py. Contributing covers how we write and run them.

API reference

samudra.invariants.core

The violation record every invariant returns, and helpers shared by the checks.

Violation(invariant, message, where=dict()) dataclass

One failure of one invariant.

Attributes:

Name Type Description
invariant str

The check's name, e.g. "masks.nest_with_depth".

message str

What failed, with the numbers needed to judge it.

where Mapping[str, Any]

Coordinates of an example location (e.g. {"lev": 3, "y": 10}), or details of an aggregate failure. Empty when not applicable.

InvariantViolated

Bases: AssertionError

Raised by require_no_violations. An AssertionError, so tests treat it as an oracle failure.

require_no_violations(violations)

Raise InvariantViolated listing every violation, if there are any.

Source code in src/samudra/invariants/core.py
def require_no_violations(violations: Iterable[Violation]) -> None:
    """Raise `InvariantViolated` listing every violation, if there are any."""
    found = list(violations)
    if found:
        shown = "\n".join(f"  - {violation}" for violation in found[:20])
        more = f"\n  ... and {len(found) - 20} more" if len(found) > 20 else ""
        raise InvariantViolated(f"{len(found)} invariant violation(s):\n{shown}{more}")

first_location(flags)

Index of the first True element of a boolean array, keyed by dimension name.

Source code in src/samudra/invariants/core.py
def first_location(flags: xr.DataArray) -> dict[str, Any]:
    """Index of the first True element of a boolean array, keyed by dimension name."""
    values = np.asarray(flags.values)
    if not values.any():
        return {}
    index = np.unravel_index(int(np.argmax(values)), values.shape)
    return {str(dim): int(i) for dim, i in zip(flags.dims, index)}

isfinite(field)

Elementwise np.isfinite, keeping the DataArray's dimensions.

Source code in src/samudra/invariants/core.py
def isfinite(field: xr.DataArray) -> xr.DataArray:
    """Elementwise ``np.isfinite``, keeping the DataArray's dimensions."""
    return xr.apply_ufunc(np.isfinite, field, dask="allowed")

constant_along(edges, axis)

Whether 2-D cell edges repeat one value along axis, as a rectilinear grid's do.

The tolerance is 1e-6 of the smallest spacing across the other axis, so it doesn't grow with the coordinate's magnitude (as np.allclose's does).

Source code in src/samudra/invariants/core.py
def constant_along(edges, axis: int) -> bool:
    """Whether 2-D cell edges repeat one value along ``axis``, as a rectilinear grid's do.

    The tolerance is 1e-6 of the smallest spacing across the other axis, so it
    doesn't grow with the coordinate's magnitude (as ``np.allclose``'s does).
    """
    edges = np.asarray(edges, dtype=float)
    first = np.take(edges, [0], axis=axis)
    spacing = np.abs(np.diff(first, axis=1 - axis))
    scale = float(spacing[spacing > 0].min()) if (spacing > 0).any() else 1.0
    return bool(np.all(np.abs(edges - first) <= 1e-6 * scale))

same_order(first, *others)

others transposed to first's dimension order, so they can be compared position by position.

Raises:

Type Description
ValueError

if any has different dimensions or sizes from first. A size-1 dimension would otherwise broadcast against the other side.

Source code in src/samudra/invariants/core.py
def same_order(first: xr.DataArray, *others: xr.DataArray) -> list[xr.DataArray]:
    """``others`` transposed to ``first``'s dimension order, so they can be compared position by position.

    Raises:
        ValueError: if any has different dimensions or sizes from ``first``. A
            size-1 dimension would otherwise broadcast against the other side.
    """
    for other in others:
        if dict(other.sizes) != dict(first.sizes):
            raise ValueError(
                f"cannot compare values over {dict(first.sizes)} with values over "
                f"{dict(other.sizes)}"
            )
    return [first, *(other.transpose(*first.dims) for other in others)]

relative_difference(a, b)

|a - b| / max(|a|, |b|), or 0 when both are 0.

Source code in src/samudra/invariants/core.py
def relative_difference(a: float, b: float) -> float:
    """``|a - b| / max(|a|, |b|)``, or 0 when both are 0."""
    scale = max(abs(a), abs(b))
    return 0.0 if scale == 0 else abs(a - b) / scale

weighted_sum(field, weights, dims)

Sum of field * weights over dims, skipping cells where either is NaN.

NaN where no cell is valid, so a comparison of an all-NaN field fails instead of passing on 0 == 0.

Source code in src/samudra/invariants/core.py
def weighted_sum(field: xr.DataArray, weights: xr.DataArray, dims) -> xr.DataArray:
    """Sum of ``field * weights`` over ``dims``, skipping cells where either is NaN.

    NaN where no cell is valid, so a comparison of an all-NaN field fails instead
    of passing on 0 == 0.
    """
    product = (field * weights).where(field.notnull() & weights.notnull())
    return product.sum(dims, skipna=True, min_count=1)

weighted_mean(field, weights, dims)

Mean of field weighted by weights over dims, over cells where both are defined.

Source code in src/samudra/invariants/core.py
def weighted_mean(field: xr.DataArray, weights: xr.DataArray, dims) -> xr.DataArray:
    """Mean of ``field`` weighted by ``weights`` over ``dims``, over cells where both are defined."""
    valid = field.notnull() & weights.notnull()
    total_weight = weights.where(valid).sum(dims, skipna=True)
    return weighted_sum(field, weights, dims) / total_weight

samudra.invariants.masks

Masks agree with each other, with the fields, and with the grid.

A store describes where the ocean is several times over: the boolean masks, the NaN pattern of every field, ocean_fraction, and the bathymetry. These checks make every pair of descriptions agree.

nest_with_depth(wet, depth_dim='lev')

A cell that is ocean at level k+1 is ocean at level k.

Source code in src/samudra/invariants/masks.py
def nest_with_depth(wet: xr.DataArray, depth_dim: str = "lev") -> list[Violation]:
    """A cell that is ocean at level k+1 is ocean at level k."""
    wet = wet.astype(bool)
    deeper = wet.isel({depth_dim: slice(1, None)})
    shallower = wet.isel({depth_dim: slice(None, -1)})
    shallower = shallower.assign_coords({depth_dim: deeper[depth_dim]})
    orphans = deeper & ~shallower
    count = int(orphans.sum())
    if not count:
        return []
    return [
        Violation(
            "masks.nest_with_depth",
            f"{count} cells are ocean below a land cell",
            first_location(orphans),
        )
    ]

ocean_fraction_bounds(ocean_fraction, depth_dim='lev', atol=1e-06)

ocean_fraction is in [0, 1], finite, and never increases with depth.

Source code in src/samudra/invariants/masks.py
def ocean_fraction_bounds(
    ocean_fraction: xr.DataArray, depth_dim: str = "lev", atol: float = 1e-6
) -> list[Violation]:
    """`ocean_fraction` is in [0, 1], finite, and never increases with depth."""
    violations = []
    nonfinite = ~isfinite(ocean_fraction)
    if nonfinite.any():
        violations.append(
            Violation(
                "masks.ocean_fraction_finite",
                f"{int(nonfinite.sum())} non-finite values",
                first_location(nonfinite),
            )
        )
    out_of_range = (ocean_fraction < -atol) | (ocean_fraction > 1 + atol)
    if out_of_range.any():
        violations.append(
            Violation(
                "masks.ocean_fraction_in_unit_interval",
                f"{int(out_of_range.sum())} values outside [0, 1]; range "
                f"{float(ocean_fraction.min()):.6g}..{float(ocean_fraction.max()):.6g}",
                first_location(out_of_range),
            )
        )
    if depth_dim in ocean_fraction.dims:
        increase = ocean_fraction.diff(depth_dim) > atol
        if increase.any():
            violations.append(
                Violation(
                    "masks.ocean_fraction_non_increasing_with_depth",
                    f"{int(increase.sum())} cells have more ocean than the level above; "
                    f"largest increase {float(ocean_fraction.diff(depth_dim).max()):.6g}",
                    first_location(increase),
                )
            )
    return violations

nan_matches_mask(field, wet, name)

field is finite exactly where wet is True, at every time step.

wet may have fewer dimensions than field (e.g. no time); it broadcasts.

Source code in src/samudra/invariants/masks.py
def nan_matches_mask(
    field: xr.DataArray, wet: xr.DataArray, name: str
) -> list[Violation]:
    """``field`` is finite exactly where ``wet`` is True, at every time step.

    ``wet`` may have fewer dimensions than ``field`` (e.g. no time); it broadcasts.
    """
    wet = wet.astype(bool)
    finite = isfinite(field)
    land_values = finite & ~wet
    ocean_holes = ~finite & wet
    violations = []
    if land_values.any():
        violations.append(
            Violation(
                "masks.nan_on_land",
                f"{name} has {int(land_values.sum())} finite values on land",
                first_location(land_values),
            )
        )
    if ocean_holes.any():
        violations.append(
            Violation(
                "masks.finite_in_ocean",
                f"{name} has {int(ocean_holes.sum())} NaN or infinite values in the ocean",
                first_location(ocean_holes),
            )
        )
    return violations

mask_matches_fraction(wet, ocean_fraction, name, atol=1e-09)

A cell is masked as ocean exactly when some of it is ocean (ocean_fraction > atol).

Conservative regridding leaves round-off fractions (~1e-16) where a land cell's great-circle edges graze a wet neighbour; atol treats those as land.

Source code in src/samudra/invariants/masks.py
def mask_matches_fraction(
    wet: xr.DataArray, ocean_fraction: xr.DataArray, name: str, atol: float = 1e-9
) -> list[Violation]:
    """A cell is masked as ocean exactly when some of it is ocean (``ocean_fraction > atol``).

    Conservative regridding leaves round-off fractions (~1e-16) where a land
    cell's great-circle edges graze a wet neighbour; ``atol`` treats those as land.
    """
    partly_ocean = ocean_fraction > atol
    disagree = wet.astype(bool) != partly_ocean
    if not disagree.any():
        return []
    return [
        Violation(
            "masks.mask_matches_ocean_fraction",
            f"{name} disagrees with ocean_fraction > 0 in {int(disagree.sum())} cells",
            first_location(disagree),
        )
    ]

flattened_levels(ds, base)

Level indices present for a flattened variable family, e.g. thetao_0..thetao_18.

Source code in src/samudra/invariants/masks.py
def flattened_levels(ds: xr.Dataset, base: str) -> list[int]:
    """Level indices present for a flattened variable family, e.g. ``thetao_0``..``thetao_18``."""
    levels = []
    for name in ds.data_vars:
        match = LEVEL_SUFFIX.match(str(name))
        if match and match["base"] == base:
            levels.append(int(match["level"]))
    return sorted(levels)

flattened_store(ds, time_index=0, fraction_atol=1e-09)

Every mask description in a flattened store agrees with every other.

Checks, per level k: mask_k against the NaN pattern of each {var}_k, against ocean_fraction[k] > 0, and nesting of mask_k with depth. Also mask_0 against the surface fields, and that areacello (the full cell area, land included) is finite and positive everywhere.

Parameters:

Name Type Description Default
ds Dataset

A flattened store, such as a published OM4 release.

required
time_index int | None

The time step whose fields are compared with the masks, or None to compare every step (expensive for large stores).

0
fraction_atol float

Fractions at or below this count as land when compared with the masks.

1e-09
Source code in src/samudra/invariants/masks.py
def flattened_store(
    ds: xr.Dataset, time_index: int | None = 0, fraction_atol: float = 1e-9
) -> list[Violation]:
    """Every mask description in a flattened store agrees with every other.

    Checks, per level k: ``mask_k`` against the NaN pattern of each ``{var}_k``,
    against ``ocean_fraction[k] > 0``, and nesting of ``mask_k`` with depth. Also
    ``mask_0`` against the surface fields, and that ``areacello`` (the full cell
    area, land included) is finite and positive everywhere.

    Args:
        ds: A flattened store, such as a published OM4 release.
        time_index: The time step whose fields are compared with the masks, or
            None to compare every step (expensive for large stores).
        fraction_atol: Fractions at or below this count as land when compared
            with the masks.
    """
    levels = flattened_levels(ds, "mask")
    if not levels:
        return [Violation("masks.present", "no mask_k variables found")]
    sample = (
        ds
        if time_index is None or "time" not in ds.dims
        else ds.isel(time=[time_index])
    )
    masks_k = [f"mask_{k}" for k in levels]
    fields_3d = {
        k: [f"{base}_{k}" for base in STATE_3D if f"{base}_{k}" in ds] for k in levels
    }
    fields_2d = [name for name in STATE_2D if name in ds]
    extras = [name for name in ("ocean_fraction", "areacello") if name in ds]
    # One compute for everything, so a remote store's chunks download in parallel
    # instead of one request at a time.
    names = masks_k + [n for k in levels for n in fields_3d[k]] + fields_2d + extras
    loaded = sample[names].load()
    violations: list[Violation] = []

    wet = xr.concat([loaded[name] for name in masks_k], dim="lev")
    violations += nest_with_depth(wet)
    if "ocean_fraction" in loaded:
        fraction = loaded["ocean_fraction"]
        violations += ocean_fraction_bounds(fraction)
        for k in levels:
            violations += mask_matches_fraction(
                loaded[f"mask_{k}"],
                fraction.isel(lev=k),
                f"mask_{k}",
                atol=fraction_atol,
            )

    for k in levels:
        for name in fields_3d[k]:
            violations += nan_matches_mask(loaded[name], loaded[f"mask_{k}"], name)
    for name in fields_2d:
        violations += nan_matches_mask(loaded[name], loaded["mask_0"], name)

    if "areacello" in loaded.variables:
        area = loaded["areacello"]
        bad = ~isfinite(area) | (area <= 0)
        if bad.any():
            violations.append(
                Violation(
                    "masks.areacello_positive_everywhere",
                    f"{int(bad.sum())} cells have non-finite or non-positive area",
                    first_location(bad),
                )
            )
    return violations

samudra.invariants.bounds

Physical bounds, aimed at the artifacts processing leaves behind.

A plain range check rarely fails on real model output. Processing artifacts cluster at coasts: averaging a field with zero-filled land, or with a fill value, drags coastal cells towards that value. coastal_dilution compares each coastal cell with its wet neighbours, which catches that even when the result still lies in the physical range.

freezing_point(salinity, depth_m=0.0)

Freezing temperature of seawater in degrees C, linearized in salinity and depth.

Source code in src/samudra/invariants/bounds.py
def freezing_point(salinity, depth_m=0.0):
    """Freezing temperature of seawater in degrees C, linearized in salinity and depth."""
    return (
        FREEZING_INTERCEPT
        + FREEZING_SALINITY_SLOPE * salinity
        + FREEZING_PRESSURE_SLOPE * depth_m
    )

above_freezing(thetao, so, depth_m=0.0, tolerance=0.1)

Temperature is at or above the freezing point for its salinity and depth.

Source code in src/samudra/invariants/bounds.py
def above_freezing(
    thetao: xr.DataArray,
    so: xr.DataArray,
    depth_m: xr.DataArray | float = 0.0,
    tolerance: float = 0.1,
) -> list[Violation]:
    """Temperature is at or above the freezing point for its salinity and depth."""
    margin = thetao - freezing_point(so, depth_m)
    too_cold = margin < -tolerance
    if not too_cold.any():
        return []
    return [
        Violation(
            "bounds.above_freezing",
            f"{int(too_cold.sum())} cells are colder than freezing by more than "
            f"{tolerance} C; worst {float(margin.min()):.3f} C",
            first_location(too_cold),
        )
    ]

within(field, name, lower, upper)

All finite values lie in [lower, upper].

Source code in src/samudra/invariants/bounds.py
def within(
    field: xr.DataArray, name: str, lower: float, upper: float
) -> list[Violation]:
    """All finite values lie in ``[lower, upper]``."""
    outside = (field < lower) | (field > upper)
    if not outside.any():
        return []
    return [
        Violation(
            f"bounds.{name}_range",
            f"{int(outside.sum())} values outside [{lower}, {upper}]; range "
            f"{float(field.min()):.6g}..{float(field.max()):.6g}",
            first_location(outside),
        )
    ]

finite_where_wet(field, wet, name)

No NaN or infinity in the ocean. Fill values such as 1e20 count as out of range elsewhere.

Source code in src/samudra/invariants/bounds.py
def finite_where_wet(
    field: xr.DataArray, wet: xr.DataArray, name: str
) -> list[Violation]:
    """No NaN or infinity in the ocean. Fill values such as 1e20 count as out of range elsewhere."""
    bad = wet.astype(bool) & ~isfinite(field)
    if not bad.any():
        return []
    return [
        Violation(
            f"bounds.{name}_finite",
            f"{int(bad.sum())} non-finite ocean values",
            first_location(bad),
        )
    ]

wet_neighbours(field, wet, y_dim='y', x_dim='x')

For each cell, the min and max of its wet 4-neighbours, and whether it borders land.

Longitude wraps; latitude doesn't.

Source code in src/samudra/invariants/bounds.py
def wet_neighbours(
    field: xr.DataArray, wet: xr.DataArray, y_dim: str = "y", x_dim: str = "x"
) -> tuple[xr.DataArray, xr.DataArray, xr.DataArray]:
    """For each cell, the min and max of its wet 4-neighbours, and whether it borders land.

    Longitude wraps; latitude doesn't.
    """
    wet = wet.astype(bool)
    values = field.where(wet)
    shifted = [
        values.roll({x_dim: 1}, roll_coords=False),
        values.roll({x_dim: -1}, roll_coords=False),
        values.shift({y_dim: 1}),
        values.shift({y_dim: -1}),
    ]
    wet_shifted = [
        wet.roll({x_dim: 1}, roll_coords=False),
        wet.roll({x_dim: -1}, roll_coords=False),
        wet.shift({y_dim: 1}, fill_value=True),
        wet.shift({y_dim: -1}, fill_value=True),
    ]
    stacked = xr.concat(shifted, dim="neighbour")
    borders_land = ~xr.concat(wet_shifted, dim="neighbour").all("neighbour")
    return stacked.min("neighbour"), stacked.max("neighbour"), borders_land & wet

coastal_dilution(field, wet, name, toward=0.0, max_fraction=0.5, y_dim='y', x_dim='x')

Coastal cells aren't pulled towards a land value beyond their wet neighbours' range.

A coastal cell's value can lie outside its wet neighbours' range: estuaries are fresher than the sea next to them. But if averaging with land drags it towards toward (0 for zero-filled land), it ends up much closer to toward than any neighbour. This flags coastal cells whose distance from toward is below max_fraction times their nearest wet neighbour's.

Use with fields that are far from toward in the open ocean, such as salinity (toward=0) or temperature in kelvin.

Source code in src/samudra/invariants/bounds.py
def coastal_dilution(
    field: xr.DataArray,
    wet: xr.DataArray,
    name: str,
    toward: float = 0.0,
    max_fraction: float = 0.5,
    y_dim: str = "y",
    x_dim: str = "x",
) -> list[Violation]:
    """Coastal cells aren't pulled towards a land value beyond their wet neighbours' range.

    A coastal cell's value can lie outside its wet neighbours' range: estuaries
    are fresher than the sea next to them. But if averaging with land drags it
    towards ``toward`` (0 for zero-filled land), it ends up much closer to
    ``toward`` than any neighbour. This flags coastal cells whose distance from
    ``toward`` is below ``max_fraction`` times their nearest wet neighbour's.

    Use with fields that are far from ``toward`` in the open ocean, such as
    salinity (``toward=0``) or temperature in kelvin.
    """
    low, high, coastal = wet_neighbours(field, wet, y_dim, x_dim)
    distance = abs(field - toward)
    nearest_neighbour = xr.where(
        abs(low - toward) < abs(high - toward), abs(low - toward), abs(high - toward)
    )
    diluted = coastal & (distance < max_fraction * nearest_neighbour)
    if not diluted.any():
        return []
    return [
        Violation(
            f"bounds.{name}_coastal_dilution",
            f"{int(diluted.sum())} of {int(coastal.sum())} coastal cells are closer to "
            f"{toward} than {max_fraction} x their nearest wet neighbour",
            first_location(diluted),
        )
    ]

samudra.invariants.geometry

Grid geometry: areas, thicknesses and volumes add up to what the sphere and the bathymetry allow.

sphere_area(area, radius=EARTH_RADIUS_M, rtol=0.001)

A global grid's cell areas sum to the sphere's area, 4 pi R^2.

Source code in src/samudra/invariants/geometry.py
def sphere_area(
    area: xr.DataArray, radius: float = EARTH_RADIUS_M, rtol: float = 1e-3
) -> list[Violation]:
    """A global grid's cell areas sum to the sphere's area, 4 pi R^2."""
    total = float(area.sum())
    expected = 4 * np.pi * radius**2
    error = relative_difference(total, expected)
    if error <= rtol:
        return []
    implied_radius = np.sqrt(total / (4 * np.pi))
    return [
        Violation(
            "geometry.sphere_area",
            f"total area {total:.6e} m2 differs from 4 pi R^2 = {expected:.6e} m2 by "
            f"{error:.3%}; implied radius {implied_radius / 1e3:.1f} km",
        )
    ]

rectilinear_cell_area(lat_b, lon_b, radius=EARTH_RADIUS_M)

Exact spherical area of each cell of a regular lat-lon grid, from its (y_b, x_b) vertices.

Widths wrap around the globe, so a cell from 359 to 0 degrees is 1 degree wide. A cell can therefore be at most 180 degrees wide.

Source code in src/samudra/invariants/geometry.py
def rectilinear_cell_area(
    lat_b: ArrayLike, lon_b: ArrayLike, radius: float = EARTH_RADIUS_M
) -> np.ndarray:
    """Exact spherical area of each cell of a regular lat-lon grid, from its (y_b, x_b) vertices.

    Widths wrap around the globe, so a cell from 359 to 0 degrees is 1 degree
    wide. A cell can therefore be at most 180 degrees wide.
    """
    lat_b, lon_b = np.asarray(lat_b, dtype=float), np.asarray(lon_b, dtype=float)
    if not (constant_along(lat_b, axis=1) and constant_along(lon_b, axis=0)):
        raise ValueError(
            "grid is not rectilinear; need lat_b constant along x and lon_b constant along y"
        )
    lat = np.deg2rad(lat_b[:, 0])
    lon = np.deg2rad(lon_b[0, :])
    band = np.diff(np.sin(lat))
    width = (np.diff(lon) + np.pi) % (2 * np.pi) - np.pi
    return radius**2 * np.abs(np.outer(band, width))

areas_match_vertices(area, lat_b, lon_b, radius=EARTH_RADIUS_M, rtol=1e-06)

Each cell's area equals the spherical area its vertices enclose (rectilinear grids only).

Source code in src/samudra/invariants/geometry.py
def areas_match_vertices(
    area: xr.DataArray,
    lat_b: xr.DataArray,
    lon_b: xr.DataArray,
    radius: float = EARTH_RADIUS_M,
    rtol: float = 1e-6,
) -> list[Violation]:
    """Each cell's area equals the spherical area its vertices enclose (rectilinear grids only)."""
    lat = np.asarray(lat_b)
    lon = np.asarray(lon_b)
    if not (constant_along(lat, axis=1) and constant_along(lon, axis=0)):
        return [
            Violation(
                "geometry.areas_match_vertices",
                "grid is not rectilinear; this check needs lat_b constant along x and lon_b along y",
            )
        ]
    expected = rectilinear_cell_area(lat_b, lon_b, radius)
    error = np.abs(np.asarray(area) - expected) / expected
    # Written so that a NaN area, whose error is NaN, counts as bad.
    bad = ~(error <= rtol)
    if not bad.any():
        return []
    flags = xr.DataArray(bad, dims=area.dims)
    finite = np.isfinite(error)
    summary = (
        f"worst {float(error[finite].max()):.3%}, median ratio "
        f"{float(np.median((np.asarray(area) / expected)[finite])):.6f}"
        if finite.any()
        else "no finite areas"
    )
    return [
        Violation(
            "geometry.areas_match_vertices",
            f"{int(bad.sum())} cells differ from their spherical area by more than "
            f"{rtol:g} ({int((~finite).sum())} are not finite); {summary}",
            first_location(flags),
        )
    ]

layer_thickness(dz, ilev, lev=None)

Layers are positive, tile the column from the surface, and contain their centres.

dz[k] == ilev[k+1] - ilev[k], ilev[0] == 0, and ilev[k] < lev[k] < ilev[k+1].

Source code in src/samudra/invariants/geometry.py
def layer_thickness(
    dz: ArrayLike, ilev: ArrayLike, lev: ArrayLike | None = None
) -> list[Violation]:
    """Layers are positive, tile the column from the surface, and contain their centres.

    ``dz[k] == ilev[k+1] - ilev[k]``, ``ilev[0] == 0``, and ``ilev[k] < lev[k] < ilev[k+1]``.
    """
    violations = []
    dz_values = np.asarray(dz, dtype=float)
    interfaces = np.asarray(ilev, dtype=float)
    if (dz_values <= 0).any():
        violations.append(
            Violation("geometry.dz_positive", f"non-positive thicknesses: {dz_values}")
        )
    if interfaces.size != dz_values.size + 1 or not np.allclose(
        np.diff(interfaces), dz_values
    ):
        violations.append(
            Violation(
                "geometry.dz_matches_interfaces",
                f"dz {dz_values} is not diff(ilev) {np.diff(interfaces)}",
            )
        )
    if interfaces.size and interfaces[0] != 0:
        violations.append(
            Violation("geometry.surface_at_zero", f"ilev[0] = {interfaces[0]}, not 0")
        )
    centres = None if lev is None else np.asarray(lev, dtype=float)
    if centres is not None and centres.size != dz_values.size:
        violations.append(
            Violation(
                "geometry.one_centre_per_layer",
                f"{centres.size} centres for {dz_values.size} layers",
            )
        )
    elif centres is not None and interfaces.size == centres.size + 1:
        # Written so that a NaN centre counts as outside.
        outside = ~((centres > interfaces[:-1]) & (centres < interfaces[1:]))
        if outside.any():
            violations.append(
                Violation(
                    "geometry.centres_inside_layers",
                    f"levels {np.flatnonzero(outside).tolist()} have centres outside their interfaces",
                )
            )
    return violations

column_within_bathymetry(dz, wet, deptho, depth_dim='lev', atol=1.0)

A water column's thickness, summed over wet layers, doesn't exceed the sea-floor depth.

dz may vary horizontally (partial cells) or not (nominal layers). A column deeper than the bathymetry means the bottom cells count water that isn't there, which inflates ocean volume (#973).

Source code in src/samudra/invariants/geometry.py
def column_within_bathymetry(
    dz: xr.DataArray,
    wet: xr.DataArray,
    deptho: xr.DataArray,
    depth_dim: str = "lev",
    atol: float = 1.0,
) -> list[Violation]:
    """A water column's thickness, summed over wet layers, doesn't exceed the sea-floor depth.

    ``dz`` may vary horizontally (partial cells) or not (nominal layers). A
    column deeper than the bathymetry means the bottom cells count water that
    isn't there, which inflates ocean volume (#973).
    """
    column = (dz * wet.astype(bool)).sum(depth_dim)
    excess = column - deptho
    too_deep = (excess > atol) & wet.astype(bool).any(depth_dim)
    if not too_deep.any():
        return []
    return [
        Violation(
            "geometry.column_within_bathymetry",
            f"{int(too_deep.sum())} columns are deeper than the bathymetry; worst by "
            f"{float(excess.where(too_deep).max()):.1f} m",
            first_location(too_deep),
        )
    ]

ocean_volume(area, ocean_fraction, dz)

Ocean volume by the store convention: sum of area x ocean_fraction x dz.

Source code in src/samudra/invariants/geometry.py
def ocean_volume(
    area: xr.DataArray, ocean_fraction: xr.DataArray, dz: xr.DataArray
) -> float:
    """Ocean volume by the store convention: sum of area x ocean_fraction x dz."""
    return float((area * ocean_fraction * dz).sum())

volume_matches_bathymetry(area, ocean_fraction, dz, deptho, rtol=0.01)

The store's volume formula agrees with the volume under the bathymetry, sum(area x deptho).

Source code in src/samudra/invariants/geometry.py
def volume_matches_bathymetry(
    area: xr.DataArray,
    ocean_fraction: xr.DataArray,
    dz: xr.DataArray,
    deptho: xr.DataArray,
    rtol: float = 1e-2,
) -> list[Violation]:
    """The store's volume formula agrees with the volume under the bathymetry, sum(area x deptho)."""
    stored = ocean_volume(area, ocean_fraction, dz)
    bathymetric = float((area * deptho.fillna(0)).sum())
    error = relative_difference(stored, bathymetric)
    if error <= rtol:
        return []
    return [
        Violation(
            "geometry.volume_matches_bathymetry",
            f"sum(area x ocean_fraction x dz) = {stored:.6e} m3 but sum(area x deptho) = "
            f"{bathymetric:.6e} m3, {error:.2%} apart",
        )
    ]

samudra.invariants.timeaxis

Time axes, calendars and averaging windows.

Averaging bugs cluster where windows meet calendar boundaries: the end of a year, a leap day, or a change of calendar (OM4 is Julian, CM4 is no-leap, observations are proleptic Gregorian). These checks work on cftime objects of any calendar.

as_cftime(values, calendar=None)

Time values as a list of cftime datetimes, from cftime or numpy datetime64.

Source code in src/samudra/invariants/timeaxis.py
def as_cftime(values, calendar: str | None = None) -> list[cftime.datetime]:
    """Time values as a list of cftime datetimes, from cftime or numpy datetime64."""
    array = np.asarray(values)
    if array.dtype.kind == "M":
        microseconds = array.astype("datetime64[us]").astype(np.int64)
        return list(
            cftime.num2date(
                microseconds,
                "microseconds since 1970-01-01",
                calendar or "proleptic_gregorian",
            )
        )
    return list(array)

calendar_of(values)

The calendar of a time axis; numpy datetime64 counts as proleptic Gregorian.

Source code in src/samudra/invariants/timeaxis.py
def calendar_of(values) -> str:
    """The calendar of a time axis; numpy datetime64 counts as proleptic Gregorian."""
    first = np.asarray(values).ravel()[0]
    if isinstance(first, np.datetime64):
        return "proleptic_gregorian"
    return first.calendar

averaging_windows(time, time_bnds, step_days=OM4_STEP_DAYS, leap_day_gaps=False)

Each stamp is its window's midpoint and the windows tile time with no gaps or overlaps.

Parameters:

Name Type Description Default
time

The time coordinate.

required
time_bnds

Shape (time, 2): each window's start and end.

required
step_days float | None

Every window's expected length, or None to allow any length.

OM4_STEP_DAYS
leap_day_gaps bool

Allow exactly one uncovered day, December 31, at the end of each leap year. OM4's axis re-anchors every year to January 3 with 73 five-day windows, which cover 365 days.

False
Source code in src/samudra/invariants/timeaxis.py
def averaging_windows(
    time,
    time_bnds,
    step_days: float | None = OM4_STEP_DAYS,
    leap_day_gaps: bool = False,
) -> list[Violation]:
    """Each stamp is its window's midpoint and the windows tile time with no gaps or overlaps.

    Args:
        time: The time coordinate.
        time_bnds: Shape (time, 2): each window's start and end.
        step_days: Every window's expected length, or None to allow any length.
        leap_day_gaps: Allow exactly one uncovered day, December 31, at the end
            of each leap year. OM4's axis re-anchors every year to January 3
            with 73 five-day windows, which cover 365 days.
    """
    stamps = as_cftime(time)
    bounds = np.asarray(time_bnds)
    if bounds.shape != (len(stamps), 2):
        return [
            Violation(
                "time.bounds_shape",
                f"time_bnds has shape {bounds.shape}; expected ({len(stamps)}, 2)",
            )
        ]
    starts, ends = as_cftime(bounds[:, 0]), as_cftime(bounds[:, 1])
    violations = []
    for i, (stamp, start, end) in enumerate(zip(stamps, starts, ends)):
        length = seconds_between(start, end)
        if length <= 0:
            # Checked even when step_days is None: a reversed window still has
            # its stamp at the midpoint.
            violations.append(
                Violation(
                    "time.window_positive",
                    f"window [{start}, {end}] ends before it starts or is empty",
                    {"time": i},
                )
            )
            continue
        if step_days is not None and length != step_days * SECONDS_PER_DAY:
            violations.append(
                Violation(
                    "time.window_length",
                    f"window [{start}, {end}] lasts {length / SECONDS_PER_DAY:g} days, "
                    f"not {step_days:g}",
                    {"time": i},
                )
            )
        if seconds_between(start, stamp) != seconds_between(stamp, end):
            violations.append(
                Violation(
                    "time.stamp_at_midpoint",
                    f"stamp {stamp} is not the midpoint of [{start}, {end}]",
                    {"time": i},
                )
            )
    calendar = calendar_of(time)
    for i in range(1, len(stamps)):
        gap = seconds_between(ends[i - 1], starts[i])
        if gap == 0:
            continue
        leap_day = (
            leap_day_gaps
            and gap == SECONDS_PER_DAY
            and cftime.is_leap_year(ends[i - 1].year, calendar)
            and (ends[i - 1].month, ends[i - 1].day, ends[i - 1].hour) == (12, 31, 0)
        )
        if not leap_day:
            kind = "gap" if gap > 0 else "overlap"
            violations.append(
                Violation(
                    f"time.windows_contiguous",
                    f"{kind} between [{starts[i - 1]}, {ends[i - 1]}] and "
                    f"[{starts[i]}, {ends[i]}]",
                    {"time": i},
                )
            )
    return violations

om4_five_day_axis(time)

The published OM4 axis: 73 five-day steps per year, each year starting on January 3, 12:00.

365 = 73 x 5, so in a leap year the step from the year's last stamp to the next January 3 is 6 days. Any other spacing is a bug. Partial first and last years are allowed.

Source code in src/samudra/invariants/timeaxis.py
def om4_five_day_axis(time) -> list[Violation]:
    """The published OM4 axis: 73 five-day steps per year, each year starting on January 3, 12:00.

    365 = 73 x 5, so in a leap year the step from the year's last stamp to the
    next January 3 is 6 days. Any other spacing is a bug. Partial first and last
    years are allowed.
    """
    stamps = as_cftime(time)
    if not stamps:
        return [Violation("time.om4_axis", "empty time axis")]
    calendar = calendar_of(time)
    violations = strictly_increasing(time)
    by_year: dict[int, list] = {}
    for stamp in stamps:
        by_year.setdefault(stamp.year, []).append(stamp)
    years = sorted(by_year)
    for year in years:
        entries = by_year[year]
        first_expected = cftime.datetime(year, 1, 3, 12, calendar=calendar)
        if year == years[0]:
            # A partial first year may start later, but on the same 5-day steps.
            offset = seconds_between(first_expected, entries[0])
            anchored = offset >= 0 and offset % (OM4_STEP_DAYS * SECONDS_PER_DAY) == 0
        else:
            anchored = entries[0] == first_expected
        if not anchored:
            violations.append(
                Violation(
                    "time.om4_year_anchor",
                    f"{year} starts at {entries[0]}, off the 5-day steps from {first_expected}",
                    {"year": year},
                )
            )
        if year not in (years[0], years[-1]) and len(entries) != OM4_STEPS_PER_YEAR:
            violations.append(
                Violation(
                    "time.om4_steps_per_year",
                    f"{year} has {len(entries)} steps, not {OM4_STEPS_PER_YEAR}",
                    {"year": year},
                )
            )
    for i, (a, b) in enumerate(zip(stamps, stamps[1:])):
        days = seconds_between(a, b) / SECONDS_PER_DAY
        crosses_leap_year_end = b.year == a.year + 1 and cftime.is_leap_year(
            a.year, calendar
        )
        expected = OM4_STEP_DAYS + 1 if crosses_leap_year_end else OM4_STEP_DAYS
        if days != expected:
            violations.append(
                Violation(
                    "time.om4_step",
                    f"step from {a} to {b} is {days:g} days; expected {expected}",
                    {"time": i + 1},
                )
            )
    return violations

windows_match(state_bnds, forcing_bnds, state_name='state', forcing_name='forcing')

Forcing and state average over the same windows, in the same calendar.

A forcing averaged over a window shifted by one step from the state's is the alignment bug that leaves the data plausible and the emulator wrong.

Source code in src/samudra/invariants/timeaxis.py
def windows_match(
    state_bnds, forcing_bnds, state_name: str = "state", forcing_name: str = "forcing"
) -> list[Violation]:
    """Forcing and state average over the same windows, in the same calendar.

    A forcing averaged over a window shifted by one step from the state's is the
    alignment bug that leaves the data plausible and the emulator wrong.
    """
    state = np.asarray(state_bnds)
    forcing = np.asarray(forcing_bnds)
    if state.shape != forcing.shape:
        return [
            Violation(
                "time.windows_match",
                f"{state_name} has windows of shape {state.shape}, {forcing_name} {forcing.shape}",
            )
        ]
    # xarray decodes standard calendars to datetime64 and others to cftime, so one
    # side may be each; compare them as cftime.
    state = np.array(as_cftime(state.ravel()), dtype=object).reshape(state.shape)
    forcing = np.array(as_cftime(forcing.ravel()), dtype=object).reshape(forcing.shape)
    if calendar_of(state) != calendar_of(forcing):
        return [
            Violation(
                "time.windows_match",
                f"{state_name} uses the {calendar_of(state)} calendar, "
                f"{forcing_name} the {calendar_of(forcing)} calendar",
            )
        ]
    mismatched = [
        i
        for i, (s, f) in enumerate(zip(state, forcing))
        if seconds_between(s[0], f[0]) != 0 or seconds_between(s[1], f[1]) != 0
    ]
    if not mismatched:
        return []
    i = mismatched[0]
    return [
        Violation(
            "time.windows_match",
            f"{len(mismatched)} windows differ; first: {state_name} "
            f"[{state[i][0]}, {state[i][1]}] vs {forcing_name} [{forcing[i][0]}, {forcing[i][1]}]",
            {"time": i},
        )
    ]

window_mean_preserved(fine, fine_bnds, coarse, coarse_bnds, time_dim='time', rtol=1e-05, atol=1e-06)

Each coarse window's mean equals the duration-weighted mean of the fine windows inside it.

Time averaging is linear, so averaging fine windows into coarse ones must reproduce the coarse values. Fine windows straddling a coarse boundary count in proportion to their overlap.

Source code in src/samudra/invariants/timeaxis.py
def window_mean_preserved(
    fine: xr.DataArray,
    fine_bnds,
    coarse: xr.DataArray,
    coarse_bnds,
    time_dim: str = "time",
    rtol: float = 1e-5,
    atol: float = 1e-6,
) -> list[Violation]:
    """Each coarse window's mean equals the duration-weighted mean of the fine windows inside it.

    Time averaging is linear, so averaging fine windows into coarse ones must
    reproduce the coarse values. Fine windows straddling a coarse boundary count
    in proportion to their overlap.
    """
    fine_b = [(as_cftime([s])[0], as_cftime([e])[0]) for s, e in np.asarray(fine_bnds)]
    violations = []
    # Checked on their own: an overlap and a gap of equal length would otherwise
    # cancel in a coarse window's coverage.
    ordered = sorted(range(len(fine_b)), key=lambda i: fine_b[i][0])
    overlapping = [
        b for a, b in zip(ordered, ordered[1:]) if fine_b[b][0] < fine_b[a][1]
    ]
    if overlapping:
        violations.append(
            Violation(
                "time.fine_windows_overlap",
                f"{len(overlapping)} fine windows start before the previous one ends",
                {"time": overlapping[0]},
            )
        )
    coarse_b = [
        (as_cftime([s])[0], as_cftime([e])[0]) for s, e in np.asarray(coarse_bnds)
    ]
    for j, (cs, ce) in enumerate(coarse_b):
        weights = np.array(
            [max(0.0, seconds_between(max(fs, cs), min(fe, ce))) for fs, fe in fine_b]
        )
        total = weights.sum()
        length = seconds_between(cs, ce)
        if total != length:
            # Less than the window: a gap. More: fine windows overlap.
            violations.append(
                Violation(
                    "time.window_covered",
                    f"fine windows cover {total / SECONDS_PER_DAY:g} of the "
                    f"{length / SECONDS_PER_DAY:g} days in [{cs}, {ce}]",
                    {"time": j},
                )
            )
            continue
        inside = np.flatnonzero(weights)
        w = xr.DataArray(weights[inside] / total, dims=[time_dim])
        # skipna=False: a NaN inside the window makes the mean NaN, which then
        # matches only a NaN coarse value, instead of counting as zero.
        expected = (fine.isel({time_dim: inside}) * w).sum(time_dim, skipna=False)
        # np.isclose compares by position, so match the dimension order first.
        expected, actual = same_order(expected, coarse.isel({time_dim: j}))
        bad = ~np.isclose(actual, expected, rtol=rtol, atol=atol, equal_nan=True)
        if bad.any():
            difference = np.abs(np.asarray(actual - expected))
            worst = (
                f"worst by {float(np.nanmax(difference)):.3g}"
                if np.isfinite(difference).any()
                else "each is NaN on one side only"
            )
            violations.append(
                Violation(
                    "time.window_mean_preserved",
                    f"window [{cs}, {ce}]: {int(bad.sum())} values differ from the "
                    f"weighted mean of finer windows; {worst}",
                    {"time": j},
                )
            )
    return violations

samudra.invariants.budgets

Budgets: heat enters only at the surface, salt is conserved, and mean sea level is removed.

Each budget closes only approximately in the stores (5-day means, nominal layer thicknesses, float32), so the checks take tolerances. Comparing a budget's residual across resolutions is sharper than any absolute tolerance: every resolution comes from the same source, so a residual that changes with resolution comes from processing.

area_mean_sea_level(zos, ocean_area, dims=('y', 'x'), atol=0.01)

Area-mean zos is about 0 m at each step (CMIP removes the global mean).

Source code in src/samudra/invariants/budgets.py
def area_mean_sea_level(
    zos: xr.DataArray, ocean_area: xr.DataArray, dims=("y", "x"), atol: float = 0.01
) -> list[Violation]:
    """Area-mean ``zos`` is about 0 m at each step (CMIP removes the global mean)."""
    mean = np.ravel(np.asarray(weighted_mean(zos, ocean_area, list(dims))))
    bad = np.abs(mean) > atol
    if not bad.any():
        return []
    i = int(np.argmax(bad))
    return [
        Violation(
            "budgets.area_mean_sea_level",
            f"{int(bad.sum())} steps have |area-mean zos| > {atol} m; e.g. {mean[i]:.4g} m",
            {"time": i},
        )
    ]

central_tendency(series, seconds)

Central difference of a series of window means, per second; NaN at both ends.

The difference between means of windows i-1 and i+1 spans the middle of window i, so it pairs with window i's mean flux. seconds are the window centres, so a 6-day step across a leap-year boundary is divided correctly.

Source code in src/samudra/invariants/budgets.py
def central_tendency(series: np.ndarray, seconds: np.ndarray) -> np.ndarray:
    """Central difference of a series of window means, per second; NaN at both ends.

    The difference between means of windows i-1 and i+1 spans the middle of
    window i, so it pairs with window i's mean flux. ``seconds`` are the window
    centres, so a 6-day step across a leap-year boundary is divided correctly.
    """
    series = np.asarray(series, dtype=float)
    seconds = np.asarray(seconds, dtype=float)
    if seconds.shape != series.shape:
        raise ValueError(f"{seconds.shape} times for {series.shape} values")
    tendency = np.full_like(series, np.nan)
    tendency[1:-1] = (series[2:] - series[:-2]) / (seconds[2:] - seconds[:-2])
    return tendency

heat_budget(heat_content, surface_heat_flux, seconds, min_correlation=0.9, slope_range=(0.8, 1.2))

The heat-content tendency tracks the area-integrated surface heat flux.

Parameters:

Name Type Description Default
heat_content ndarray

Global (or closed-basin) heat content per step, in J.

required
surface_heat_flux ndarray

Area-integrated net surface heat flux per step, in W, positive into the ocean.

required
seconds ndarray

Centre of each window, in seconds from any origin.

required
min_correlation float

Lowest acceptable correlation between the two series.

0.9
slope_range tuple[float, float]

Acceptable regression slope of tendency on flux.

(0.8, 1.2)
Source code in src/samudra/invariants/budgets.py
def heat_budget(
    heat_content: np.ndarray,
    surface_heat_flux: np.ndarray,
    seconds: np.ndarray,
    min_correlation: float = 0.9,
    slope_range: tuple[float, float] = (0.8, 1.2),
) -> list[Violation]:
    """The heat-content tendency tracks the area-integrated surface heat flux.

    Args:
        heat_content: Global (or closed-basin) heat content per step, in J.
        surface_heat_flux: Area-integrated net surface heat flux per step, in W,
            positive into the ocean.
        seconds: Centre of each window, in seconds from any origin.
        min_correlation: Lowest acceptable correlation between the two series.
        slope_range: Acceptable regression slope of tendency on flux.
    """
    tendency = central_tendency(heat_content, seconds)
    flux = np.asarray(surface_heat_flux, dtype=float)
    ok = np.isfinite(tendency) & np.isfinite(flux)
    if ok.sum() < 3:
        return [Violation("budgets.heat_budget", f"only {int(ok.sum())} usable steps")]
    correlation = float(np.corrcoef(tendency[ok], flux[ok])[0, 1])
    slope = float(np.polyfit(flux[ok], tendency[ok], 1)[0])
    violations = []
    if not correlation >= min_correlation:
        violations.append(
            Violation(
                "budgets.heat_budget_correlation",
                f"tendency and surface flux correlate at {correlation:.3f} < {min_correlation}",
            )
        )
    if not slope_range[0] <= slope <= slope_range[1]:
        violations.append(
            Violation(
                "budgets.heat_budget_slope",
                f"regression slope of tendency on flux is {slope:.3f}, outside {slope_range}",
            )
        )
    return violations

salt_drift(salt, max_relative=1e-06)

Total salt changes by at most max_relative over the series.

Source code in src/samudra/invariants/budgets.py
def salt_drift(salt: np.ndarray, max_relative: float = 1e-6) -> list[Violation]:
    """Total salt changes by at most ``max_relative`` over the series."""
    salt = np.asarray(salt, dtype=float)
    drift = (np.nanmax(salt) - np.nanmin(salt)) / np.nanmean(salt)
    if drift <= max_relative:
        return []
    return [
        Violation(
            "budgets.salt_drift",
            f"total salt varies by {drift:.3g} (relative), more than {max_relative:g}",
        )
    ]

residuals_agree(residuals, name, atol)

A budget's residual is the same at every resolution, to within atol.

Source code in src/samudra/invariants/budgets.py
def residuals_agree(
    residuals: dict[str, float], name: str, atol: float
) -> list[Violation]:
    """A budget's residual is the same at every resolution, to within ``atol``."""
    values = list(residuals.values())
    spread = max(values) - min(values)
    if spread <= atol:
        return []
    shown = ", ".join(f"{key}: {value:.4g}" for key, value in residuals.items())
    return [
        Violation(
            f"budgets.{name}_residual_across_resolutions",
            f"residuals spread by {spread:.4g} > {atol}: {shown}",
        )
    ]

samudra.invariants.conservation

Metamorphic checks between two versions of one ocean: before and after a step, or two resolutions.

Conservative regridding and the gcm-filters smoothers are weighted averages with non-negative weights that preserve area integrals. So, between a field and its regridded or filtered version:

  • linear integrals (area, volume, heat, salt) agree,
  • variance doesn't grow (law of total variance),
  • no new extremes appear,
  • zonal power spectra agree at wavelengths both grids resolve.

The same relations hold between the published 1, 1/2 and 1/4 degree stores, which share one source.

area_weights(area, ocean_fraction)

Ocean area of each cell: full cell area times the fraction that is ocean.

Source code in src/samudra/invariants/conservation.py
def area_weights(area: xr.DataArray, ocean_fraction: xr.DataArray) -> xr.DataArray:
    """Ocean area of each cell: full cell area times the fraction that is ocean."""
    return area * ocean_fraction

volume_weights(area, ocean_fraction, dz)

Ocean volume of each cell, by the store convention area x ocean_fraction x dz.

Source code in src/samudra/invariants/conservation.py
def volume_weights(
    area: xr.DataArray, ocean_fraction: xr.DataArray, dz: xr.DataArray
) -> xr.DataArray:
    """Ocean volume of each cell, by the store convention area x ocean_fraction x dz."""
    return area * ocean_fraction * dz

heat_content(thetao, volume, dims)

Heat content relative to 0 C, in J: rho_0 c_p sum(theta dV).

Source code in src/samudra/invariants/conservation.py
def heat_content(thetao: xr.DataArray, volume: xr.DataArray, dims) -> xr.DataArray:
    """Heat content relative to 0 C, in J: rho_0 c_p sum(theta dV)."""
    return RHO_0 * CP_SW * weighted_sum(thetao, volume, dims)

salt_content(so, volume, dims)

Salt mass in kg (practical salinity as g/kg): rho_0 sum(S dV) / 1000.

Source code in src/samudra/invariants/conservation.py
def salt_content(so: xr.DataArray, volume: xr.DataArray, dims) -> xr.DataArray:
    """Salt mass in kg (practical salinity as g/kg): rho_0 sum(S dV) / 1000."""
    return RHO_0 * weighted_sum(so, volume, dims) / 1000

integral_preserved(fine, fine_weights, coarse, coarse_weights, name, dims=('y', 'x'), rtol=0.001, atol=0.0)

sum(fine * w_fine) == sum(coarse * w_coarse) over dims, for each remaining index.

rtol is relative to sum(|fine| * w_fine), not to the total, so a field whose positive and negative parts cancel (a velocity) isn't judged on round-off.

Source code in src/samudra/invariants/conservation.py
def integral_preserved(
    fine: xr.DataArray,
    fine_weights: xr.DataArray,
    coarse: xr.DataArray,
    coarse_weights: xr.DataArray,
    name: str,
    dims=("y", "x"),
    rtol: float = 1e-3,
    atol: float = 0.0,
) -> list[Violation]:
    """``sum(fine * w_fine) == sum(coarse * w_coarse)`` over ``dims``, for each remaining index.

    ``rtol`` is relative to ``sum(|fine| * w_fine)``, not to the total, so a field
    whose positive and negative parts cancel (a velocity) isn't judged on round-off.
    """
    a = weighted_sum(fine, fine_weights, list(dims))
    b = weighted_sum(coarse, coarse_weights, list(dims))
    scale = weighted_sum(abs(fine), fine_weights, list(dims))
    return _compare(a, b, scale, f"conservation.{name}_integral", rtol, atol)

mean_preserved(fine, fine_weights, coarse, coarse_weights, name, dims=('y', 'x'), rtol=0.001, atol=0.0)

Weighted means agree over dims, for each remaining index.

rtol is relative to the weighted mean of |fine|, as in integral_preserved.

Source code in src/samudra/invariants/conservation.py
def mean_preserved(
    fine: xr.DataArray,
    fine_weights: xr.DataArray,
    coarse: xr.DataArray,
    coarse_weights: xr.DataArray,
    name: str,
    dims=("y", "x"),
    rtol: float = 1e-3,
    atol: float = 0.0,
) -> list[Violation]:
    """Weighted means agree over ``dims``, for each remaining index.

    ``rtol`` is relative to the weighted mean of ``|fine|``, as in `integral_preserved`.
    """
    a = weighted_mean(fine, fine_weights, list(dims))
    b = weighted_mean(coarse, coarse_weights, list(dims))
    scale = weighted_mean(abs(fine), fine_weights, list(dims))
    return _compare(a, b, scale, f"conservation.{name}_mean", rtol, atol)

variance_not_increased(fine, fine_weights, coarse, coarse_weights, name, dims=('y', 'x'), rtol=1e-06)

Averaging can't create variance: weighted variance after <= before (law of total variance).

Source code in src/samudra/invariants/conservation.py
def variance_not_increased(
    fine: xr.DataArray,
    fine_weights: xr.DataArray,
    coarse: xr.DataArray,
    coarse_weights: xr.DataArray,
    name: str,
    dims=("y", "x"),
    rtol: float = 1e-6,
) -> list[Violation]:
    """Averaging can't create variance: weighted variance after <= before (law of total variance)."""

    def variance(field, weights):
        mean = weighted_mean(field, weights, list(dims))
        return weighted_mean((field - mean) ** 2, weights, list(dims)), mean

    (before, mean), (after, _) = (
        variance(fine, fine_weights),
        variance(coarse, coarse_weights),
    )
    before, mean, after = (
        np.ravel(np.asarray(v)) for v in same_order(before, mean, after)
    )
    # A NaN variance (no valid cells) fails, rather than passing every comparison.
    missing = ~(np.isfinite(before) & np.isfinite(after))
    # Round-off in a constant field's variance scales with the squared mean.
    grew = after > before * (1 + rtol) + 1e-12 * (mean**2 + 1e-30)
    bad = missing | grew
    if not bad.any():
        return []
    i = int(np.argmax(bad))
    detail = (
        f"variance is {before[i]:.6g} before and {after[i]:.6g} after; "
        "there is nothing to compare"
        if missing[i]
        else f"variance grew from {before[i]:.6g} to {after[i]:.6g}"
    )
    return [
        Violation(f"conservation.{name}_variance_not_increased", detail, {"index": i})
    ]

no_new_extremes(fine, coarse, name, atol=0.0)

The coarse range lies inside the fine range: weighted averages only move extremes inward.

Source code in src/samudra/invariants/conservation.py
def no_new_extremes(
    fine: xr.DataArray, coarse: xr.DataArray, name: str, atol: float = 0.0
) -> list[Violation]:
    """The coarse range lies inside the fine range: weighted averages only move extremes inward."""
    fine_min, fine_max = float(fine.min()), float(fine.max())
    coarse_min, coarse_max = float(coarse.min()), float(coarse.max())
    if coarse_min >= fine_min - atol and coarse_max <= fine_max + atol:
        return []
    return [
        Violation(
            f"conservation.{name}_no_new_extremes",
            f"range widened from {fine_min:.6g}..{fine_max:.6g} to {coarse_min:.6g}..{coarse_max:.6g}",
        )
    ]

band_zonal_spectrum(field, lat_b, band, x_dim='x', y_dim='y')

Zonal power spectrum of the area-weighted mean over a latitude band.

Each row counts with the area it shares with band, from its edges lat_b (ny + 1 values, or a (y_b, x_b) array of a rectilinear grid). Grids whose rows don't nest therefore average exactly the same band. Every row that overlaps the band must be fully wet. field must have only the y_dim and x_dim dimensions. Returns power at zonal wavenumbers 0..nx//2 (cycles per circle).

A cell holds its whole row's mean, so a row only partly inside the band adds an error that grows with the field's meridional gradient. When comparing two grids, put the band on the coarse grid's edges, so only the finer grid's thinner rows straddle it.

Source code in src/samudra/invariants/conservation.py
def band_zonal_spectrum(
    field: xr.DataArray,
    lat_b: ArrayLike,
    band: tuple[float, float],
    x_dim="x",
    y_dim="y",
) -> np.ndarray:
    """Zonal power spectrum of the area-weighted mean over a latitude band.

    Each row counts with the area it shares with ``band``, from its edges
    ``lat_b`` (``ny + 1`` values, or a ``(y_b, x_b)`` array of a rectilinear
    grid). Grids whose rows don't nest therefore average exactly the same band.
    Every row that overlaps the band must be fully wet. ``field`` must have only
    the ``y_dim`` and ``x_dim`` dimensions. Returns power at zonal wavenumbers
    0..nx//2 (cycles per circle).

    A cell holds its whole row's mean, so a row only partly inside the band adds
    an error that grows with the field's meridional gradient. When comparing two
    grids, put the band on the coarse grid's edges, so only the finer grid's
    thinner rows straddle it.
    """
    if set(field.dims) != {y_dim, x_dim}:
        raise ValueError(
            f"field has dimensions {field.dims}; select one ({y_dim}, {x_dim}) slice first"
        )
    edges = np.asarray(lat_b, dtype=float)
    if edges.ndim == 2:
        if not constant_along(edges, axis=1):
            raise ValueError(
                "grid is not rectilinear; latitude bands need lat_b constant along x"
            )
        edges = edges[:, 0]
    if edges.size != field.sizes[y_dim] + 1:
        raise ValueError(
            f"{edges.size} latitude edges for {field.sizes[y_dim]} rows; need one more"
        )
    lower = np.maximum(np.minimum(edges[:-1], edges[1:]), band[0])
    upper = np.minimum(np.maximum(edges[:-1], edges[1:]), band[1])
    overlap = np.clip(np.sin(np.deg2rad(upper)) - np.sin(np.deg2rad(lower)), 0, None)
    rows = np.flatnonzero(overlap > 0)
    if rows.size == 0:
        raise ValueError(f"no rows overlap latitude band {band}")
    selected = field.isel({y_dim: rows})
    if bool(selected.isnull().any()):
        raise ValueError(f"latitude band {band} has land; pick fully wet rows")
    weights = xr.DataArray(overlap[rows], dims=[y_dim])
    profile = (selected * weights).sum(y_dim) / weights.sum()
    nx = profile.sizes[x_dim]
    return np.abs(np.fft.rfft(np.asarray(profile), axis=-1)) ** 2 / nx**2

zonal_spectra_agree(fine, fine_lat_b, coarse, coarse_lat_b, band, name, resolved_fraction=0.125, rtol=0.05, x_dim='x', y_dim='y')

Zonal spectra of a fully wet latitude band agree at wavenumbers both grids resolve.

Block-averaging n fine columns into one multiplies wavenumber k's amplitude by sinc(k / N) for N coarse columns, so at k <= resolved_fraction N the coarse power must lie between that attenuation and the fine power, within rtol. *_lat_b are each grid's row edges (see band_zonal_spectrum).

Source code in src/samudra/invariants/conservation.py
def zonal_spectra_agree(
    fine: xr.DataArray,
    fine_lat_b: ArrayLike,
    coarse: xr.DataArray,
    coarse_lat_b: ArrayLike,
    band: tuple[float, float],
    name: str,
    resolved_fraction: float = 0.125,
    rtol: float = 0.05,
    x_dim: str = "x",
    y_dim: str = "y",
) -> list[Violation]:
    """Zonal spectra of a fully wet latitude band agree at wavenumbers both grids resolve.

    Block-averaging n fine columns into one multiplies wavenumber k's amplitude by
    sinc(k / N) for N coarse columns, so at k <= ``resolved_fraction`` N the
    coarse power must lie between that attenuation and the fine power, within
    ``rtol``. ``*_lat_b`` are each grid's row edges (see `band_zonal_spectrum`).
    """
    fine_power = band_zonal_spectrum(fine, fine_lat_b, band, x_dim, y_dim)
    coarse_power = band_zonal_spectrum(coarse, coarse_lat_b, band, x_dim, y_dim)
    n_coarse = coarse.sizes[x_dim]
    k_max = max(1, int(resolved_fraction * n_coarse))
    k = np.arange(1, k_max + 1)
    attenuation = np.sinc(k / n_coarse) ** 2
    lower = fine_power[k] * attenuation * (1 - rtol)
    upper = fine_power[k] * (1 + rtol)
    # An absolute allowance for round-off, so power the coarse field gains at a
    # wavenumber where the fine field has none is still flagged.
    floor = 1e-12 * max(
        float(fine_power[1:].max(initial=0.0)),
        float(coarse_power[1:].max(initial=0.0)),
        1e-30,
    )
    bad = (coarse_power[k] < lower - floor) | (coarse_power[k] > upper + floor)
    if not bad.any():
        return []
    i = int(np.argmax(bad))
    return [
        Violation(
            f"conservation.{name}_zonal_spectrum",
            f"{int(bad.sum())} of {k_max} resolved wavenumbers disagree; at k={k[i]}: fine "
            f"{fine_power[k[i]]:.4g}, coarse {coarse_power[k[i]]:.4g}",
            {"wavenumber": int(k[i]), "band": band},
        )
    ]

samudra.invariants.coupling

The forcing is a physically sensible fit to the ocean state it drives.

These checks catch forcing that is misaligned in time, or rotated or signed differently from the state, which leaves every field plausible on its own.

lagged_correlations(forcing, response, max_lag)

Correlation of forcing[t] with response[t + lag] for each lag in [-max_lag, max_lag].

Source code in src/samudra/invariants/coupling.py
def lagged_correlations(
    forcing: np.ndarray, response: np.ndarray, max_lag: int
) -> dict[int, float]:
    """Correlation of ``forcing[t]`` with ``response[t + lag]`` for each lag in [-max_lag, max_lag]."""
    forcing = np.asarray(forcing, dtype=float)
    response = np.asarray(response, dtype=float)
    result = {}
    for lag in range(-max_lag, max_lag + 1):
        if lag >= 0:
            a, b = forcing[: len(forcing) - lag], response[lag:]
        else:
            a, b = forcing[-lag:], response[: len(response) + lag]
        ok = np.isfinite(a) & np.isfinite(b)
        if ok.sum() >= 3 and np.std(a[ok]) > 0 and np.std(b[ok]) > 0:
            result[lag] = float(np.corrcoef(a[ok], b[ok])[0, 1])
    return result

response_peaks_at_lag_zero(forcing, response, name, max_lag=2)

The response correlates best with the forcing of the same window, not the one before or after.

Pair a flux with the central-difference tendency of what it drives (see budgets.central_tendency). A peak at lag +1 or -1 means the forcing is shifted by one step relative to the state.

Source code in src/samudra/invariants/coupling.py
def response_peaks_at_lag_zero(
    forcing: np.ndarray, response: np.ndarray, name: str, max_lag: int = 2
) -> list[Violation]:
    """The response correlates best with the forcing of the same window, not the one before or after.

    Pair a flux with the central-difference tendency of what it drives (see
    `budgets.central_tendency`). A peak at lag +1 or -1 means the forcing is
    shifted by one step relative to the state.
    """
    correlations = lagged_correlations(forcing, response, max_lag)
    if not correlations:
        return [Violation(f"coupling.{name}_lag", "too few finite steps to correlate")]
    best = max(correlations, key=lambda lag: correlations[lag])
    # A tie with lag 0 (within round-off) isn't a shift: a linear trend correlates
    # perfectly with itself at every lag.
    if 0 in correlations and correlations[0] >= correlations[best] - 1e-9:
        return []
    shown = ", ".join(
        f"{lag:+d}: {value:.3f}" for lag, value in sorted(correlations.items())
    )
    return [
        Violation(
            f"coupling.{name}_lag",
            f"correlation peaks at lag {best:+d}, not 0 ({shown})",
            {"lag": best},
        )
    ]

ekman_deflection(tauuo, tauvo, uo, vo, lat, ocean_area, min_abs_lat=15.0, dims=('y', 'x'))

Surface currents turn right of the wind in the north and left in the south.

Coriolis deflects the Ekman surface current to the right of the wind stress in the northern hemisphere and to the left in the southern. Averaged over a hemisphere, the stress-weighted cross product (tau x u) . z is negative in the north and positive in the south. A sign error or a swapped component in vector rotation flips this.

Source code in src/samudra/invariants/coupling.py
def ekman_deflection(
    tauuo: xr.DataArray,
    tauvo: xr.DataArray,
    uo: xr.DataArray,
    vo: xr.DataArray,
    lat: xr.DataArray,
    ocean_area: xr.DataArray,
    min_abs_lat: float = 15.0,
    dims=("y", "x"),
) -> list[Violation]:
    """Surface currents turn right of the wind in the north and left in the south.

    Coriolis deflects the Ekman surface current to the right of the wind stress
    in the northern hemisphere and to the left in the southern. Averaged over a
    hemisphere, the stress-weighted cross product (tau x u) . z is negative in
    the north and positive in the south. A sign error or a swapped component in
    vector rotation flips this.
    """
    cross = tauuo * vo - tauvo * uo
    violations = []
    for hemisphere, selector, expected_sign in (
        ("north", lat >= min_abs_lat, -1),
        ("south", lat <= -min_abs_lat, 1),
    ):
        mean = float(
            weighted_mean(cross.where(selector), ocean_area, list(dims)).mean()
        )
        if not np.isfinite(mean) or np.sign(mean) != expected_sign:
            violations.append(
                Violation(
                    "coupling.ekman_deflection",
                    f"{hemisphere}ern hemisphere mean (tau x u) . z is {mean:.3g}; expected "
                    f"{'negative' if expected_sign < 0 else 'positive'}",
                    {"hemisphere": hemisphere},
                )
            )
    return violations

stress_and_current_aligned(tauuo, tauvo, uo, vo, ocean_area, dims=('y', 'x'))

Surface current has a positive component along the wind stress, on average.

Ekman drift is within 90 degrees of the wind, so the area mean of tau . u is positive. A rotation applied to one pair of vectors but not the other breaks this.

Source code in src/samudra/invariants/coupling.py
def stress_and_current_aligned(
    tauuo: xr.DataArray,
    tauvo: xr.DataArray,
    uo: xr.DataArray,
    vo: xr.DataArray,
    ocean_area: xr.DataArray,
    dims=("y", "x"),
) -> list[Violation]:
    """Surface current has a positive component along the wind stress, on average.

    Ekman drift is within 90 degrees of the wind, so the area mean of tau . u is
    positive. A rotation applied to one pair of vectors but not the other breaks this.
    """
    dot = tauuo * uo + tauvo * vo
    mean = float(weighted_mean(dot, ocean_area, list(dims)).mean())
    if np.isfinite(mean) and mean > 0:
        return []
    return [
        Violation(
            "coupling.stress_and_current_aligned",
            f"area-mean tau . u is {mean:.3g}; expected positive",
        )
    ]

samudra.invariants.releases

Two builds of the same data agree, except where a documented change says otherwise.

Use it to compare two releases, or to compare a store rebuilt with the current pipeline against the published one. A difference nobody documented is either an unrecorded code change or a regression.

stores_agree(reference, candidate, variables=None, rtol=1e-05, atol=1e-06, expected_changes=frozenset())

Shared variables agree in shape, NaN pattern and value.

Parameters:

Name Type Description Default
reference Dataset

The trusted build, such as the published store.

required
candidate Dataset

The build being checked, aligned to the same times.

required
variables

Variables to compare; defaults to every variable in both.

None
rtol float

Relative tolerance for values.

1e-05
atol float

Absolute tolerance for values.

1e-06
expected_changes frozenset[str]

Variables a documented change allows to differ.

frozenset()
Source code in src/samudra/invariants/releases.py
def stores_agree(
    reference: xr.Dataset,
    candidate: xr.Dataset,
    variables=None,
    rtol: float = 1e-5,
    atol: float = 1e-6,
    expected_changes: frozenset[str] = frozenset(),
) -> list[Violation]:
    """Shared variables agree in shape, NaN pattern and value.

    Args:
        reference: The trusted build, such as the published store.
        candidate: The build being checked, aligned to the same times.
        variables: Variables to compare; defaults to every variable in both.
        rtol: Relative tolerance for values.
        atol: Absolute tolerance for values.
        expected_changes: Variables a documented change allows to differ.
    """
    names = (
        variables
        if variables is not None
        else sorted(map(str, set(reference.variables) & set(candidate.variables)))
    )
    violations = []
    for name in names:
        if name in expected_changes:
            continue
        if name not in reference.variables or name not in candidate.variables:
            violations.append(
                Violation(
                    "releases.variable_present", f"{name} is missing from one build"
                )
            )
            continue
        a, b = reference[name], candidate[name]
        if a.dims != b.dims or a.shape != b.shape:
            violations.append(
                Violation(
                    "releases.same_shape",
                    f"{name}: {dict(a.sizes)} vs {dict(b.sizes)}",
                )
            )
            continue
        if a.dtype.kind not in "fiub" or b.dtype.kind not in "fiub":
            if not np.array_equal(np.asarray(a), np.asarray(b)):
                violations.append(Violation("releases.same_values", f"{name} differs"))
            continue
        # Compare by position: xarray arithmetic would align on coordinates and
        # silently drop cells whose coordinate values differ between builds.
        a_values = np.asarray(a.load())
        b_values = np.asarray(b.load())
        nan_differs = xr.DataArray(
            np.isnan(a_values) != np.isnan(b_values), dims=a.dims
        )
        if nan_differs.any():
            violations.append(
                Violation(
                    "releases.same_nan_pattern",
                    f"{name}: NaN pattern differs in {int(nan_differs.sum())} cells",
                    first_location(nan_differs),
                )
            )
        close = np.isclose(a_values, b_values, rtol=rtol, atol=atol, equal_nan=True)
        far = xr.DataArray(~close, dims=a.dims)
        if far.any():
            worst = float(
                np.nanmax(np.abs(a_values.astype(float) - b_values.astype(float)))
            )
            violations.append(
                Violation(
                    "releases.same_values",
                    f"{name}: {int(far.sum())} values differ; worst by {worst:.4g}",
                    first_location(far),
                )
            )
    return violations