Skip to content

Transforms

Spectral and signal transforms on xarray data — Fourier / wavelet / cosine spectra, rotary and cross spectra, oceanographic spectral fluxes, matrix decompositions (PCA / EOF / ICA / NMF / KMeans), and binary-mask morphology. The numpy compute cores are jaxtyped; the xarray wrappers carry coordinate and attribute handling.

Spectra

PowerSpectrum

PowerSpectrum(variable: str, dim: str | Sequence[str], *, isotropic: bool = False, **kwargs: Any)

Bases: Operator

Power spectrum of ds[variable]. Set isotropic=True for the radial (2-D) variant. window= and detrend= as in :func:xrops.transforms.power_spectrum.

Source code in packages/xrtoolz-ops/src/xrops/transforms/operators.py
def __init__(
    self,
    variable: str,
    dim: str | Sequence[str],
    *,
    isotropic: bool = False,
    **kwargs: Any,
) -> None:
    self.variable = variable
    self.dim = dim
    self.isotropic = isotropic
    self.kwargs = dict(kwargs)

CrossSpectrum

CrossSpectrum(var_a: str, var_b: str, dim: str, **kwargs: Any)

Bases: Operator

Cross-power spectrum of ds[var_a] and ds[var_b].

Source code in packages/xrtoolz-ops/src/xrops/transforms/operators.py
def __init__(
    self,
    var_a: str,
    var_b: str,
    dim: str,
    **kwargs: Any,
) -> None:
    self.var_a = var_a
    self.var_b = var_b
    self.dim = dim
    self.kwargs = dict(kwargs)

Coherence

Coherence(var_a: str, var_b: str, dim: str, **kwargs: Any)

Bases: Operator

Magnitude-squared coherence of two variables, averaged over average= dims or over segments of segment= samples.

Source code in packages/xrtoolz-ops/src/xrops/transforms/operators.py
def __init__(
    self,
    var_a: str,
    var_b: str,
    dim: str,
    **kwargs: Any,
) -> None:
    self.var_a = var_a
    self.var_b = var_b
    self.dim = dim
    self.kwargs = dict(kwargs)

RotarySpectrum

RotarySpectrum(u: str, v: str, dim: str, *, avg_dims: str | Sequence[str] | None = None)

Bases: Operator

Rotary power spectrum from ds[u] / ds[v] along dim.

The operator selects the named velocity variables from the input Dataset and calls :func:rotary_spectrum on the resulting DataArrays.

Parameters:

Name Type Description Default
u str

Name of the zonal velocity variable in the input Dataset.

required
v str

Name of the meridional velocity variable in the input Dataset.

required
dim str

Dimension to Fourier transform.

required
avg_dims str | Sequence[str] | None

Optional dimension or dimensions to average in each output.

None
Source code in packages/xrtoolz-ops/src/xrops/transforms/operators.py
def __init__(
    self,
    u: str,
    v: str,
    dim: str,
    *,
    avg_dims: str | Sequence[str] | None = None,
) -> None:
    self.u = u
    self.v = v
    self.dim = dim
    self.avg_dims = avg_dims

STFT

STFT(variable: str, dim: str, *, window_size: int, hop: int | None = None, window: str | None = 'tukey', detrend: Detrend = 'linear')

Bases: Operator

Short-time Fourier transform of ds[variable] along dim.

Source code in packages/xrtoolz-ops/src/xrops/transforms/operators.py
def __init__(
    self,
    variable: str,
    dim: str,
    *,
    window_size: int,
    hop: int | None = None,
    window: str | None = "tukey",
    detrend: _fourier.Detrend = "linear",
) -> None:
    self.variable = variable
    self.dim = dim
    self.window_size = window_size
    self.hop = hop
    self.window = window
    self.detrend = detrend

DCT

DCT(variable: str, dim: str, *, type: int = 2, norm: str | None = 'ortho')

Bases: Operator

Discrete Cosine Transform of ds[variable] along dim.

Source code in packages/xrtoolz-ops/src/xrops/transforms/operators.py
def __init__(
    self,
    variable: str,
    dim: str,
    *,
    type: int = 2,
    norm: str | None = "ortho",
) -> None:
    self.variable = variable
    self.dim = dim
    self.type = type
    self.norm = norm

DST

DST(variable: str, dim: str, *, type: int = 2, norm: str | None = 'ortho')

Bases: Operator

Discrete Sine Transform of ds[variable] along dim.

Source code in packages/xrtoolz-ops/src/xrops/transforms/operators.py
def __init__(
    self,
    variable: str,
    dim: str,
    *,
    type: int = 2,
    norm: str | None = "ortho",
) -> None:
    self.variable = variable
    self.dim = dim
    self.type = type
    self.norm = norm

CWT

CWT(variable: str, dim: str, *, scales: Sequence[float], wavelet: str = 'morl', sampling_period: float = 1.0)

Bases: Operator

Continuous Wavelet Transform of ds[variable] along dim.

Source code in packages/xrtoolz-ops/src/xrops/transforms/operators.py
def __init__(
    self,
    variable: str,
    dim: str,
    *,
    scales: Sequence[float],
    wavelet: str = "morl",
    sampling_period: float = 1.0,
) -> None:
    self.variable = variable
    self.dim = dim
    self.scales = list(scales)
    self.wavelet = wavelet
    self.sampling_period = sampling_period

Spectral flux

KESpectralFlux

KESpectralFlux(u: str, v: str, dim: Sequence[str], *, window: Window = None, detrend: Detrend = None, avg_dims: str | Sequence[str] | None = None)

Bases: Operator

Kinetic-energy spectral flux from ds[u] and ds[v].

Parameters:

Name Type Description Default
u str

Name of the zonal velocity variable in the input Dataset.

required
v str

Name of the meridional velocity variable in the input Dataset.

required
dim Sequence[str]

Two spatial dimensions to Fourier transform.

required
window Window

Optional taper; a tapered flow is not a periodic box.

None
detrend Detrend

Optional detrending mode.

None
avg_dims str | Sequence[str] | None

Optional non-spectral dimensions to average.

None

Returns:

Type Description

Dataset with transfer and flux variables.

Examples:

>>> op = KESpectralFlux("u", "v", ("x", "y"), avg_dims="time")
>>> flux_ds = op(ds)
Source code in packages/xrtoolz-ops/src/xrops/transforms/operators.py
def __init__(
    self,
    u: str,
    v: str,
    dim: Sequence[str],
    *,
    window: _fourier.Window = None,
    detrend: _fourier.Detrend = None,
    avg_dims: str | Sequence[str] | None = None,
) -> None:
    self.u = u
    self.v = v
    self.dim = dim
    self.window = window
    self.detrend = detrend
    self.avg_dims = avg_dims

EnstrophySpectralFlux

EnstrophySpectralFlux(u: str, v: str, dim: Sequence[str], *, window: Window = None, detrend: Detrend = None, avg_dims: str | Sequence[str] | None = None)

Bases: Operator

Enstrophy spectral flux from ds[u] and ds[v].

Parameters:

Name Type Description Default
u str

Name of the zonal velocity variable in the input Dataset.

required
v str

Name of the meridional velocity variable in the input Dataset.

required
dim Sequence[str]

Two spatial dimensions to Fourier transform.

required
window Window

Optional taper; a tapered flow is not a periodic box.

None
detrend Detrend

Optional detrending mode.

None
avg_dims str | Sequence[str] | None

Optional non-spectral dimensions to average.

None

Returns:

Type Description

Dataset with vorticity-based enstrophy transfer and flux

variables.

Examples:

>>> op = EnstrophySpectralFlux("u", "v", ("x", "y"))
>>> flux_ds = op(ds)
Source code in packages/xrtoolz-ops/src/xrops/transforms/operators.py
def __init__(
    self,
    u: str,
    v: str,
    dim: Sequence[str],
    *,
    window: _fourier.Window = None,
    detrend: _fourier.Detrend = None,
    avg_dims: str | Sequence[str] | None = None,
) -> None:
    self.u = u
    self.v = v
    self.dim = dim
    self.window = window
    self.detrend = detrend
    self.avg_dims = avg_dims

Spectral functions

These pure functions back the operators above; each takes xr.DataArray/xr.Dataset and a dim: argument.

power_spectrum

power_spectrum(da: DataArray, dim: str | Sequence[str], *, isotropic: bool = False, window: Window = 'hann', detrend: Detrend = 'linear') -> DataArray

Power spectral density of da along one dim, or over two.

The sum of a spectrum times the step of its wavenumbers is the variance of the detrended field, on average where there is a taper.

Parameters:

Name Type Description Default
da DataArray

Input field.

required
dim str | Sequence[str]

One dim, for the one-sided spectrum from wavenumber 0, or two, for the two-sided spectrum over both (space-time spectra).

required
isotropic bool

If True, the sum over each ring of wavenumbers of two dims (diagnostix.spectra.isotropic_spectrum).

False
window Window

"hann", an array of weights with one per sample of the dims, or None.

'hann'
detrend Detrend

What to take away first: "linear" (the line or plane), "constant" (the mean) or None.

'linear'

Returns:

Type Description
DataArray

DataArray of the spectrum, named f"{da.name}_psd" (or

DataArray

f"{da.name}_iso_psd" if isotropic=True), on freq_<dim> in

DataArray

place of each dim, or on freq_r. A NaN in a field makes its

DataArray

spectrum NaN.

Raises:

Type Description
ValueError

If there are more than two dims, isotropic has not exactly two, or a coordinate is missing or not evenly spaced.

Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/fourier.py
def power_spectrum(
    da: xr.DataArray,
    dim: str | Sequence[str],
    *,
    isotropic: bool = False,
    window: Window = "hann",
    detrend: Detrend = "linear",
) -> xr.DataArray:
    """Power spectral density of ``da`` along one dim, or over two.

    The sum of a spectrum times the step of its wavenumbers is the variance of
    the detrended field, on average where there is a taper.

    Args:
        da: Input field.
        dim: One dim, for the one-sided spectrum from wavenumber 0, or two, for
            the two-sided spectrum over both (space-time spectra).
        isotropic: If ``True``, the sum over each ring of wavenumbers of two
            dims (``diagnostix.spectra.isotropic_spectrum``).
        window: ``"hann"``, an array of weights with one per sample of the
            dims, or ``None``.
        detrend: What to take away first: ``"linear"`` (the line or plane),
            ``"constant"`` (the mean) or ``None``.

    Returns:
        DataArray of the spectrum, named ``f"{da.name}_psd"`` (or
        ``f"{da.name}_iso_psd"`` if ``isotropic=True``), on ``freq_<dim>`` in
        place of each dim, or on ``freq_r``. A NaN in a field makes its
        spectrum NaN.

    Raises:
        ValueError: If there are more than two dims, ``isotropic`` has not
            exactly two, or a coordinate is missing or not evenly spaced.
    """
    dims = [dim] if isinstance(dim, str) else list(dim)
    if isotropic and len(dims) != 2:
        raise ValueError(
            f"isotropic_power_spectrum requires exactly 2 spatial dims; got dim={dims}."
        )
    if len(dims) not in (1, 2):
        raise ValueError(f"power_spectrum takes one dim or two; got dim={dims}.")
    steps = [_spacing(da, d) for d in dims]
    shape = tuple(da.sizes[d] for d in dims)
    options: dict[str, Any] = {"window": window, "detrend": detrend}
    blank = np.zeros(shape)
    if isotropic:

        def kernel(x: Any) -> tuple[Any, ...]:
            return (spectra.isotropic_spectrum(x, steps, **options).power,)

        out = {"freq_r": spectra.isotropic_spectrum(blank, steps).wavenumber}
        replace: dict[str, str] = {}
    elif len(dims) == 1:

        def kernel(x: Any) -> tuple[Any, ...]:
            return (spectra.power_spectrum(x, steps[0], **options).power,)

        out = {f"freq_{dims[0]}": spectra.power_spectrum(blank, steps[0]).wavenumber}
        replace = {dims[0]: f"freq_{dims[0]}"}
    else:

        def kernel(x: Any) -> tuple[Any, ...]:
            return (spectra.power_spectrum_2d(x, steps, **options).power,)

        plane = spectra.power_spectrum_2d(blank, steps)
        out = {
            f"freq_{dims[0]}": plane.wavenumber_y,
            f"freq_{dims[1]}": plane.wavenumber_x,
        }
        replace = {d: f"freq_{d}" for d in dims}
    (psd,) = _transform(
        kernel, da, core=dims, out=out, dtypes=[_real(da)], replace=replace
    )
    return psd.rename(_output_name(da, "iso_psd" if isotropic else "psd"))

isotropic_power_spectrum

isotropic_power_spectrum(da: DataArray, dim: Sequence[str], **kwargs: Any) -> DataArray

Isotropic 2-D power spectrum. Convenience alias of :func:power_spectrum with isotropic=True.

Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/fourier.py
def isotropic_power_spectrum(
    da: xr.DataArray,
    dim: Sequence[str],
    **kwargs: Any,
) -> xr.DataArray:
    """Isotropic 2-D power spectrum. Convenience alias of
    :func:`power_spectrum` with ``isotropic=True``."""
    return power_spectrum(da, dim=dim, isotropic=True, **kwargs)

cross_spectrum

cross_spectrum(da_a: DataArray, da_b: DataArray, dim: str, *, segment: int | None = None, overlap: float = 0.5, window: Window = 'hann', detrend: Detrend = 'constant') -> DataArray

Cross-power spectrum of da_a and da_b along dim.

Parameters:

Name Type Description Default
da_a DataArray

One series; its phase is positive where it leads.

required
da_b DataArray

The other series.

required
dim str

The dim to transform.

required
segment int | None

Length in samples of the segments to average over; the whole series by default.

None
overlap float

The share of a segment that the next one repeats.

0.5
window Window

As in :func:power_spectrum, one weight per sample of a segment.

'hann'
detrend Detrend

As in :func:power_spectrum, per segment.

'constant'

Returns:

Type Description
DataArray

Complex DataArray named f"{a.name}_{b.name}_csd", one-sided on

DataArray

freq_<dim>; the sum of its real part times the step is the

DataArray

covariance.

Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/fourier.py
def cross_spectrum(
    da_a: xr.DataArray,
    da_b: xr.DataArray,
    dim: str,
    *,
    segment: int | None = None,
    overlap: float = 0.5,
    window: Window = "hann",
    detrend: Detrend = "constant",
) -> xr.DataArray:
    """Cross-power spectrum of ``da_a`` and ``da_b`` along ``dim``.

    Args:
        da_a: One series; its phase is positive where it leads.
        da_b: The other series.
        dim: The dim to transform.
        segment: Length in samples of the segments to average over; the whole
            series by default.
        overlap: The share of a segment that the next one repeats.
        window: As in :func:`power_spectrum`, one weight per sample of a
            segment.
        detrend: As in :func:`power_spectrum`, per segment.

    Returns:
        Complex DataArray named ``f"{a.name}_{b.name}_csd"``, one-sided on
        ``freq_<dim>``; the sum of its real part times the step is the
        covariance.
    """
    step = _spacing(da_a, dim)
    options: dict[str, Any] = {
        "segment": segment,
        "overlap": overlap,
        "window": window,
        "detrend": detrend,
    }

    def kernel(a: Any, b: Any) -> tuple[Any, ...]:
        return (spectra.cross_spectrum(a, b, step, **options).cross,)

    blank = np.zeros(da_a.sizes[dim])
    k = spectra.cross_spectrum(blank, blank, step, segment=segment).wavenumber
    (csd,) = _transform(
        kernel,
        da_a,
        da_b,
        core=[dim],
        out={f"freq_{dim}": k},
        dtypes=[np.result_type(_real(da_a, da_b), np.complex64)],
        replace={dim: f"freq_{dim}"},
    )
    return csd.rename(_pair_name(da_a, da_b, "csd"))

coherence

coherence(da_a: DataArray, da_b: DataArray, dim: str, *, average: str | Sequence[str] | None = None, segment: int | None = None, overlap: float = 0.5, window: Window = 'hann', detrend: Detrend = 'constant') -> DataArray

Magnitude-squared coherence |⟨S_ab⟩|² / (⟨S_aa⟩ ⟨S_bb⟩).

Bounded in [0, 1]: 1 means the two signals share identical phase-aligned content at that frequency. Without an average it is 1 for any two signals, so one is required; independent noise gives 1 over the number of independent transforms.

Parameters:

Name Type Description Default
da_a DataArray

One series.

required
da_b DataArray

The other series.

required
dim str

The dim to transform.

required
average str | Sequence[str] | None

Dims of realisations to average over.

None
segment int | None

Length in samples of the segments to average over.

None
overlap float

The share of a segment that the next one repeats.

0.5
window Window

As in :func:cross_spectrum.

'hann'
detrend Detrend

As in :func:cross_spectrum.

'constant'

Returns:

Type Description
DataArray

DataArray named f"{a.name}_{b.name}_coh", one-sided on

DataArray

freq_<dim>, without the averaged dims.

Raises:

Type Description
ValueError

If average and segment give one transform only.

Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/fourier.py
def coherence(
    da_a: xr.DataArray,
    da_b: xr.DataArray,
    dim: str,
    *,
    average: str | Sequence[str] | None = None,
    segment: int | None = None,
    overlap: float = 0.5,
    window: Window = "hann",
    detrend: Detrend = "constant",
) -> xr.DataArray:
    """Magnitude-squared coherence ``|⟨S_ab⟩|² / (⟨S_aa⟩ ⟨S_bb⟩)``.

    Bounded in ``[0, 1]``: 1 means the two signals share identical
    phase-aligned content at that frequency. Without an average it is 1 for any
    two signals, so one is required; independent noise gives 1 over the number
    of independent transforms.

    Args:
        da_a: One series.
        da_b: The other series.
        dim: The dim to transform.
        average: Dims of realisations to average over.
        segment: Length in samples of the segments to average over.
        overlap: The share of a segment that the next one repeats.
        window: As in :func:`cross_spectrum`.
        detrend: As in :func:`cross_spectrum`.

    Returns:
        DataArray named ``f"{a.name}_{b.name}_coh"``, one-sided on
        ``freq_<dim>``, without the averaged dims.

    Raises:
        ValueError: If ``average`` and ``segment`` give one transform only.
    """
    step = _spacing(da_a, dim)
    over = _as_list(average)
    da_a, da_b = xr.broadcast(da_a, da_b)
    options: dict[str, Any] = {
        "segment": segment,
        "overlap": overlap,
        "window": window,
        "detrend": detrend,
    }

    def kernel(a: Any, b: Any) -> tuple[Any, ...]:
        axes = tuple(range(-1 - len(over), -1)) or None
        out = spectra.coherence(a, b, step, average=axes, **options)
        return (out.coherence,)

    blank = np.zeros(da_a.sizes[dim])
    k = spectra.cross_spectrum(blank, blank, step, segment=segment).wavenumber
    (coh,) = _transform(
        kernel,
        da_a,
        da_b,
        core=[*over, dim],
        out={f"freq_{dim}": k},
        dtypes=[_real(da_a, da_b)],
        replace={dim: f"freq_{dim}"},
    )
    return coh.rename(_pair_name(da_a, da_b, "coh"))

rotary_spectrum

rotary_spectrum(u: DataArray, v: DataArray, *, dim: str, avg_dims: str | Sequence[str] | None = None) -> Dataset

Rotary power spectrum from horizontal velocity components.

The variance of u + i v, split by the way it turns along dim (diagnostix.spectra.rotary_spectrum), with the mean removed and no taper: the sum of psd_cw + psd_ccw times the step of the wavenumbers is the variance of u plus that of v. Polarization is NaN where total rotary power is negligible.

Parameters:

Name Type Description Default
u DataArray

Zonal/eastward velocity DataArray.

required
v DataArray

Meridional/northward velocity DataArray on the same grid as u.

required
dim str

Dimension to Fourier transform; without a coordinate, its spacing is 1.

required
avg_dims str | Sequence[str] | None

Optional dimension or dimensions to average in each output.

None

Returns:

Type Description
Dataset

Dataset with psd_ccw, psd_cw, and polarization where

Dataset

polarization = (psd_cw - psd_ccw) / (psd_cw + psd_ccw), on

Dataset

wavenumber from 0.

Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/fourier.py
def rotary_spectrum(
    u: xr.DataArray,
    v: xr.DataArray,
    *,
    dim: str,
    avg_dims: str | Sequence[str] | None = None,
) -> xr.Dataset:
    """Rotary power spectrum from horizontal velocity components.

    The variance of ``u + i v``, split by the way it turns along ``dim``
    (``diagnostix.spectra.rotary_spectrum``), with the mean removed and no
    taper: the sum of ``psd_cw + psd_ccw`` times the step of the wavenumbers is
    the variance of ``u`` plus that of ``v``. Polarization is NaN where total
    rotary power is negligible.

    Args:
        u: Zonal/eastward velocity DataArray.
        v: Meridional/northward velocity DataArray on the same grid as ``u``.
        dim: Dimension to Fourier transform; without a coordinate, its spacing
            is 1.
        avg_dims: Optional dimension or dimensions to average in each output.

    Returns:
        Dataset with ``psd_ccw``, ``psd_cw``, and ``polarization`` where
        ``polarization = (psd_cw - psd_ccw) / (psd_cw + psd_ccw)``, on
        ``wavenumber`` from 0.
    """
    if dim not in u.dims or dim not in v.dims:
        raise ValueError(
            f"dim={dim!r} must be present on both u (dims={u.dims}) and "
            f"v (dims={v.dims})."
        )
    step = _spacing(u, dim) if dim in u.coords else 1.0

    def kernel(u_: Any, v_: Any) -> tuple[Any, ...]:
        out = spectra.rotary_spectrum(u_, v_, step)
        return out.counter_clockwise, out.clockwise

    psd_ccw, psd_cw = _transform(
        kernel,
        u,
        v,
        core=[dim],
        out={"wavenumber": np.fft.rfftfreq(u.sizes[dim], step)},
        dtypes=[_real(u, v)] * 2,
        replace={dim: "wavenumber"},
    )
    denom = psd_cw + psd_ccw
    polarization = ((psd_cw - psd_ccw) / denom).where(
        denom > float(np.finfo(denom.dtype).eps)
    )
    out = xr.Dataset(
        {"psd_ccw": psd_ccw, "psd_cw": psd_cw, "polarization": polarization}
    )
    avg = _as_list(avg_dims)
    return out.mean(dim=avg) if avg else out

compensated_spectrum

compensated_spectrum(psd: DataArray, *, wavenumber_dim: str = 'freq_r', exponent: float) -> DataArray

Return psd * k**exponent for inertial-range compensation.

Parameters:

Name Type Description Default
psd DataArray

Spectrum to compensate.

required
wavenumber_dim str

Name of the wavenumber dimension.

'freq_r'
exponent float

Power-law exponent, for example 5 / 3 for Kolmogorov scaling.

required

Returns:

Type Description
DataArray

DataArray named f"{psd.name}_compensated" that is flat where

DataArray

psd ∝ k^{-exponent}.

Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/fourier.py
def compensated_spectrum(
    psd: xr.DataArray,
    *,
    wavenumber_dim: str = "freq_r",
    exponent: float,
) -> xr.DataArray:
    """Return ``psd * k**exponent`` for inertial-range compensation.

    Args:
        psd: Spectrum to compensate.
        wavenumber_dim: Name of the wavenumber dimension.
        exponent: Power-law exponent, for example ``5 / 3`` for Kolmogorov
            scaling.

    Returns:
        DataArray named ``f"{psd.name}_compensated"`` that is flat where
        ``psd ∝ k^{-exponent}``.
    """
    out = psd * psd[wavenumber_dim] ** exponent
    out.name = _output_name(psd, "compensated", fallback="spectrum")
    return out

stft

stft(da: DataArray, dim: str, *, window_size: int, hop: int | None = None, window: str | None = 'tukey', detrend: Detrend = 'linear') -> DataArray

Short-time Fourier transform along dim.

Splits the signal into overlapping windows of length window_size spaced by hop samples (default window_size // 2), computes a Fourier transform per window, and stacks the result on a new segment axis whose coordinate is the centre time of each window. The phase is that of Σ x(t) exp(−2πi f t), with t the coordinate of dim (dates from the first).

Parameters:

Name Type Description Default
da DataArray

1-D signal (along dim) plus arbitrary extra dims that are broadcast over.

required
dim str

Time / sample dimension to slide the window along, increasing.

required
window_size int

Length (in samples) of each STFT window.

required
hop int | None

Stride between window starts. Defaults to window_size // 2 (50 % overlap).

None
window str | None

Window name or tuple for :func:scipy.signal.get_window (Tukey by default), periodic. None for no taper.

'tukey'
detrend Detrend

Per-window detrending. None to disable.

'linear'

Returns:

Type Description
DataArray

Complex DataArray with dims (segment, *outer_dims, freq_<dim>),

DataArray

named f"{da.name}_stft", with the frequencies ascending.

Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/fourier.py
def stft(
    da: xr.DataArray,
    dim: str,
    *,
    window_size: int,
    hop: int | None = None,
    window: str | None = "tukey",
    detrend: Detrend = "linear",
) -> xr.DataArray:
    """Short-time Fourier transform along ``dim``.

    Splits the signal into overlapping windows of length ``window_size``
    spaced by ``hop`` samples (default ``window_size // 2``), computes a
    Fourier transform per window, and stacks the result on a new
    ``segment`` axis whose coordinate is the centre time of each
    window. The phase is that of ``Σ x(t) exp(−2πi f t)``, with ``t`` the
    coordinate of ``dim`` (dates from the first).

    Args:
        da: 1-D signal (along ``dim``) plus arbitrary extra dims that
            are broadcast over.
        dim: Time / sample dimension to slide the window along, increasing.
        window_size: Length (in samples) of each STFT window.
        hop: Stride between window starts. Defaults to
            ``window_size // 2`` (50 % overlap).
        window: Window name or tuple for :func:`scipy.signal.get_window`
            (Tukey by default), periodic. ``None`` for no taper.
        detrend: Per-window detrending. ``None`` to disable.

    Returns:
        Complex DataArray with dims ``(segment, *outer_dims, freq_<dim>)``,
        named ``f"{da.name}_stft"``, with the frequencies ascending.
    """
    if dim not in da.dims:
        raise ValueError(f"dim={dim!r} not present on DataArray with dims={da.dims}.")
    if window_size < 2:
        raise ValueError(f"window_size must be >= 2; got {window_size}.")
    if hop is None:
        hop = window_size // 2
    if hop < 1:
        raise ValueError(f"hop must be >= 1; got {hop}.")

    n_total = da.sizes[dim]
    if window_size > n_total:
        raise ValueError(f"window_size={window_size} exceeds {dim!r} length {n_total}.")

    starts = np.arange(0, n_total - window_size + 1, hop, dtype=int)
    positions = _positions(da, dim)
    step = float((positions[-1] - positions[0]) / (n_total - 1))
    if step < 0.0:
        raise ValueError(f"coord {dim!r} must increase.")
    frequency = np.fft.fftshift(np.fft.fftfreq(window_size, step))
    taper = 1.0 if window is None else signal.get_window(window, window_size)
    # exp(−2πi f t₀) of the first sample of each window
    shift = np.exp(-2j * np.pi * frequency * positions[starts][:, None])

    def kernel(x: Any) -> Any:
        pieces = np.stack([x[..., s : s + window_size] for s in starts], axis=-2)
        if detrend is not None:
            pieces = signal.detrend(pieces, axis=-1, type=detrend)
        z = np.fft.fft(pieces * taper, axis=-1)
        return np.fft.fftshift(z, axes=-1) * shift

    freq_dim = f"freq_{dim}"
    out = xr.apply_ufunc(
        kernel,
        da,
        input_core_dims=[[dim]],
        output_core_dims=[["segment", freq_dim]],
        dask="parallelized",
        keep_attrs=False,
        output_dtypes=[np.complex128],
        dask_gufunc_kwargs={
            "allow_rechunk": True,
            "output_sizes": {"segment": starts.size, freq_dim: window_size},
        },
    )
    centres = [da[dim].values[s + window_size // 2].item() for s in starts]
    out = out.assign_coords({freq_dim: frequency, "segment": np.asarray(centres)})
    return out.transpose("segment", ...).rename(_output_name(da, "stft"))

dct

dct(da: DataArray, dim: str, *, type: int = 2, norm: str | None = 'ortho') -> DataArray

Discrete Cosine Transform along dim.

Parameters:

Name Type Description Default
da DataArray

Input field.

required
dim str

Dimension to transform.

required
type int

DCT type 1, 2, 3, 4 (default 2 — the DCT-II used by JPEG and most signal-processing applications).

2
norm str | None

"ortho" (default) makes the transform unitary so that idct(dct(x)) == x. Pass None for the unnormalised scipy default.

'ortho'

Returns:

Type Description
DataArray

DataArray of the same shape, named f"{name}_dct".

Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/dct.py
def dct(
    da: xr.DataArray,
    dim: str,
    *,
    type: int = 2,
    norm: str | None = "ortho",
) -> xr.DataArray:
    """Discrete Cosine Transform along ``dim``.

    Args:
        da: Input field.
        dim: Dimension to transform.
        type: DCT type ``1, 2, 3, 4`` (default ``2`` — the DCT-II used
            by JPEG and most signal-processing applications).
        norm: ``"ortho"`` (default) makes the transform unitary so that
            ``idct(dct(x)) == x``. Pass ``None`` for the unnormalised
            scipy default.

    Returns:
        DataArray of the same shape, named ``f"{name}_dct"``.
    """
    if dim not in da.dims:
        raise ValueError(f"dim={dim!r} not present on DataArray with dims={da.dims}.")
    axis = da.get_axis_num(dim)
    raw = _scipy_dct(da.values, type=type, axis=axis, norm=norm)
    return xr.DataArray(
        raw,
        dims=da.dims,
        coords={k: da.coords[k] for k in da.coords},
        attrs=dict(da.attrs),
        name=_output_name(da, "dct"),
    )

idct

idct(da: DataArray, dim: str, *, type: int = 2, norm: str | None = 'ortho') -> DataArray

Inverse DCT along dim. See :func:dct for arguments.

Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/dct.py
def idct(
    da: xr.DataArray,
    dim: str,
    *,
    type: int = 2,
    norm: str | None = "ortho",
) -> xr.DataArray:
    """Inverse DCT along ``dim``. See :func:`dct` for arguments."""
    if dim not in da.dims:
        raise ValueError(f"dim={dim!r} not present on DataArray with dims={da.dims}.")
    axis = da.get_axis_num(dim)
    raw = _scipy_idct(da.values, type=type, axis=axis, norm=norm)
    return xr.DataArray(
        raw,
        dims=da.dims,
        coords={k: da.coords[k] for k in da.coords},
        attrs=dict(da.attrs),
        name=_output_name(da, "idct"),
    )

dst

dst(da: DataArray, dim: str, *, type: int = 2, norm: str | None = 'ortho') -> DataArray

Discrete Sine Transform along dim. See :func:dct.

Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/dct.py
def dst(
    da: xr.DataArray,
    dim: str,
    *,
    type: int = 2,
    norm: str | None = "ortho",
) -> xr.DataArray:
    """Discrete Sine Transform along ``dim``. See :func:`dct`."""
    if dim not in da.dims:
        raise ValueError(f"dim={dim!r} not present on DataArray with dims={da.dims}.")
    axis = da.get_axis_num(dim)
    raw = _scipy_dst(da.values, type=type, axis=axis, norm=norm)
    return xr.DataArray(
        raw,
        dims=da.dims,
        coords={k: da.coords[k] for k in da.coords},
        attrs=dict(da.attrs),
        name=_output_name(da, "dst"),
    )

idst

idst(da: DataArray, dim: str, *, type: int = 2, norm: str | None = 'ortho') -> DataArray

Inverse DST along dim. See :func:dct.

Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/dct.py
def idst(
    da: xr.DataArray,
    dim: str,
    *,
    type: int = 2,
    norm: str | None = "ortho",
) -> xr.DataArray:
    """Inverse DST along ``dim``. See :func:`dct`."""
    if dim not in da.dims:
        raise ValueError(f"dim={dim!r} not present on DataArray with dims={da.dims}.")
    axis = da.get_axis_num(dim)
    raw = _scipy_idst(da.values, type=type, axis=axis, norm=norm)
    return xr.DataArray(
        raw,
        dims=da.dims,
        coords={k: da.coords[k] for k in da.coords},
        attrs=dict(da.attrs),
        name=_output_name(da, "idst"),
    )

cwt

cwt(da: DataArray, dim: str, *, scales: Sequence[float] | ndarray, wavelet: str = 'morl', sampling_period: float = 1.0) -> DataArray

Continuous Wavelet Transform along dim.

Parameters:

Name Type Description Default
da DataArray

Input field.

required
dim str

Dimension to transform.

required
scales Sequence[float] | ndarray

Wavelet scales (positive floats). Larger scale → lower frequency content. See :func:pywt.scale2frequency.

required
wavelet str

Wavelet name (e.g. "morl" for Morlet, "mexh", "cmor", "gaus1").

'morl'
sampling_period float

Sample spacing along dim in seconds (or equivalent), used to convert scales to frequencies.

1.0

Returns:

Type Description
DataArray

Complex-valued DataArray with dims (*outer_dims, scale, dim),

DataArray

named f"{name}_cwt". A frequency 1-D coord is attached

DataArray

along the new scale axis.

Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/wavelet.py
def cwt(
    da: xr.DataArray,
    dim: str,
    *,
    scales: Sequence[float] | np.ndarray,
    wavelet: str = "morl",
    sampling_period: float = 1.0,
) -> xr.DataArray:
    """Continuous Wavelet Transform along ``dim``.

    Args:
        da: Input field.
        dim: Dimension to transform.
        scales: Wavelet scales (positive floats). Larger scale → lower
            frequency content. See :func:`pywt.scale2frequency`.
        wavelet: Wavelet name (e.g. ``"morl"`` for Morlet,
            ``"mexh"``, ``"cmor"``, ``"gaus1"``).
        sampling_period: Sample spacing along ``dim`` in seconds (or
            equivalent), used to convert scales to frequencies.

    Returns:
        Complex-valued DataArray with dims ``(*outer_dims, scale, dim)``,
        named ``f"{name}_cwt"``. A ``frequency`` 1-D coord is attached
        along the new ``scale`` axis.
    """
    pywt = _import_pywt()
    if dim not in da.dims:
        raise ValueError(f"dim={dim!r} not present on DataArray with dims={da.dims}.")
    scales_arr = np.asarray(scales, dtype=float)
    if scales_arr.ndim != 1 or scales_arr.size == 0:
        raise ValueError("scales must be a non-empty 1-D sequence of positive floats.")
    if (scales_arr <= 0).any():
        raise ValueError("scales must be strictly positive.")

    axis = da.get_axis_num(dim)
    coeffs, freqs = pywt.cwt(
        da.values, scales_arr, wavelet, sampling_period=sampling_period, axis=axis
    )

    new_dims = ("scale", *da.dims)
    coords: dict = {k: da.coords[k] for k in da.coords}
    coords["scale"] = scales_arr
    coords["frequency"] = ("scale", np.asarray(freqs))

    return xr.DataArray(
        coeffs,
        dims=new_dims,
        coords=coords,
        attrs=dict(da.attrs),
        name=_output_name(da, "cwt"),
    )

dwt

dwt(da: DataArray, dim: str, *, wavelet: str = 'db4', level: int | None = None, mode: str = 'symmetric') -> dict[str, DataArray]

Multi-level discrete wavelet decomposition along dim.

Returns a dict {"approx": ..., "detail_1": ..., ..., "detail_L": ...} where L = level (or the maximum allowed by the signal length if level is None). Each entry is a DataArray with the transformed axis renamed (dim is replaced by f"{dim}_dwt_<k>") since the level-wise outputs have different lengths.

Parameters:

Name Type Description Default
da DataArray

Input field.

required
dim str

Dimension to decompose.

required
wavelet str

Wavelet name ("db4", "sym5", "haar"…).

'db4'
level int | None

Decomposition depth. None uses :func:pywt.dwt_max_level.

None
mode str

Signal-extension mode at boundaries.

'symmetric'

Returns:

Type Description
dict[str, DataArray]

Dictionary of approximation and detail coefficients as

dict[str, DataArray]

DataArrays.

Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/wavelet.py
def dwt(
    da: xr.DataArray,
    dim: str,
    *,
    wavelet: str = "db4",
    level: int | None = None,
    mode: str = "symmetric",
) -> dict[str, xr.DataArray]:
    """Multi-level discrete wavelet decomposition along ``dim``.

    Returns a dict ``{"approx": ..., "detail_1": ..., ..., "detail_L": ...}``
    where ``L = level`` (or the maximum allowed by the signal length if
    ``level`` is ``None``). Each entry is a DataArray with the
    transformed axis renamed (``dim`` is replaced by ``f"{dim}_dwt_<k>"``)
    since the level-wise outputs have different lengths.

    Args:
        da: Input field.
        dim: Dimension to decompose.
        wavelet: Wavelet name (``"db4"``, ``"sym5"``, ``"haar"``…).
        level: Decomposition depth. ``None`` uses
            :func:`pywt.dwt_max_level`.
        mode: Signal-extension mode at boundaries.

    Returns:
        Dictionary of approximation and detail coefficients as
        DataArrays.
    """
    pywt = _import_pywt()
    if dim not in da.dims:
        raise ValueError(f"dim={dim!r} not present on DataArray with dims={da.dims}.")

    axis = da.get_axis_num(dim)
    n = da.sizes[dim]
    max_level = pywt.dwt_max_level(n, pywt.Wavelet(wavelet).dec_len)
    eff_level = max_level if level is None else int(level)
    if eff_level < 1 or eff_level > max_level:
        raise ValueError(
            f"level must be in [1, {max_level}] for n={n} and wavelet={wavelet!r}; "
            f"got {eff_level}."
        )

    coeffs = pywt.wavedec(
        da.values, wavelet=wavelet, level=eff_level, mode=mode, axis=axis
    )
    # ``coeffs[0]`` is the approximation; ``coeffs[1:]`` are details
    # ordered coarsest→finest.
    out: dict[str, xr.DataArray] = {}
    other_dims = tuple(d for d in da.dims if d != dim)
    other_coords = {k: da.coords[k] for k in da.coords if k in other_dims}

    def _wrap(arr: np.ndarray, label: str) -> xr.DataArray:
        new_dim = f"{dim}_dwt_{label}"
        new_dims = tuple(new_dim if d == dim else d for d in da.dims)
        return xr.DataArray(
            arr,
            dims=new_dims,
            coords=other_coords,
            attrs=dict(da.attrs),
            name=_output_name(da, f"dwt_{label}"),
        )

    out["approx"] = _wrap(coeffs[0], "approx")
    for k, det in enumerate(coeffs[1:], start=1):
        out[f"detail_{k}"] = _wrap(det, f"detail_{k}")
    return out

drop_negative_frequencies

drop_negative_frequencies(da: T, dims: Sequence[str], *, drop: bool = True) -> T

Mean along dims after restricting every other freq axis to its positive half.

Used to collapse a multi-D spectrum onto a subset of frequency axes without contaminating the average with the zero / negative halves of the remaining axes. This is the renamed and clarified form of the historical conditional_average.

Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/fourier.py
def drop_negative_frequencies[T: xr.DataArray | xr.Dataset](
    da: T,
    dims: Sequence[str],
    *,
    drop: bool = True,
) -> T:
    """Mean along ``dims`` after restricting every other freq axis to its
    positive half.

    Used to collapse a multi-D spectrum onto a subset of frequency axes
    without contaminating the average with the zero / negative halves
    of the remaining axes. This is the renamed and clarified form of
    the historical ``conditional_average``.
    """
    dims = list(dims)
    remaining = [d for d in da.dims if d not in dims]
    if not remaining:
        return da.mean(dim=dims)

    cond = da[remaining[0]] > 0.0
    for d in remaining[1:]:
        cond = cond & (da[d] > 0.0)
    return da.mean(dim=dims).where(cond, drop=drop)

to_phase

to_phase(da: DataArray, *, time_dim: str, period: float, n_bins: int, epoch: float = 0.0) -> DataArray

Fold time_dim onto a phase axis by binning + averaging.

The time coordinate must be numeric in the same units as period. Phase is computed as ((t - epoch) / period) mod 1 and binned into n_bins evenly-spaced bins on [0, 1). Output carries a "phase" dim with coordinate values at bin centers.

The Layer-1 ToPhase operator handles Dataset selection / per-variable looping.

Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/coord_remap.py
def to_phase(
    da: xr.DataArray,
    *,
    time_dim: str,
    period: float,
    n_bins: int,
    epoch: float = 0.0,
) -> xr.DataArray:
    """Fold ``time_dim`` onto a phase axis by binning + averaging.

    The time coordinate must be numeric in the same units as ``period``.
    Phase is computed as ``((t - epoch) / period) mod 1`` and binned
    into ``n_bins`` evenly-spaced bins on ``[0, 1)``. Output carries
    a ``"phase"`` dim with coordinate values at bin centers.

    The Layer-1 ``ToPhase`` operator handles Dataset selection /
    per-variable looping.
    """
    if time_dim not in da.dims:
        raise ValueError(
            f"time_dim {time_dim!r} not in DataArray dims {tuple(da.dims)}"
        )
    if time_dim not in da.coords:
        raise ValueError(
            f"DataArray must carry a coordinate named {time_dim!r} to compute phase"
        )
    if period <= 0:
        raise ValueError(f"period must be > 0, got {period}")
    if n_bins < 1:
        raise ValueError(f"n_bins must be >= 1, got {n_bins}")
    if not np.issubdtype(da.dtype, np.number):
        raise TypeError(
            f"to_phase requires numeric data; got dtype {da.dtype}. "
            "Drop or convert the variable before calling to_phase."
        )

    t = np.asarray(da[time_dim].values, dtype=float)
    finite_t = _finite_mask(t)
    phase = np.where(finite_t, ((t - epoch) / period) % 1.0, 0.0)
    edges = np.linspace(0.0, 1.0, n_bins + 1)
    centers = 0.5 * (edges[:-1] + edges[1:])
    bin_idx = np.clip(np.searchsorted(edges, phase, side="right") - 1, 0, n_bins - 1)

    axis = da.get_axis_num(time_dim)
    moved = np.moveaxis(da.values, axis, 0)
    flat = moved.reshape(moved.shape[0], -1)
    # Use a complex accumulator if the data is complex so the imaginary
    # part isn't dropped (P1 review).
    is_complex = np.iscomplexobj(flat)
    acc_dtype = np.complex128 if is_complex else float
    # cast: with dtype resolved at runtime (complex128 or float), the
    # specialised ndarray type numpy's stubs infer would reject the row
    # assignments below.
    sums = cast(np.ndarray, np.zeros((n_bins, flat.shape[1]), dtype=acc_dtype))
    counts = np.zeros((n_bins, flat.shape[1]), dtype=float)
    # A sample is valid only if its time coord is finite AND every data
    # value is finite. Excluding NaN-time rows keeps stale rows out of
    # the phase means (P2 review). ``np.isfinite`` handles integer
    # dtypes (treated as all-finite) where ``np.isnan`` would raise.
    valid_value = (
        np.isfinite(flat)
        if not is_complex
        else (np.isfinite(flat.real) & np.isfinite(flat.imag))
    )
    valid = finite_t[:, None] & valid_value
    for b in range(n_bins):
        m = (bin_idx == b) & finite_t
        if not m.any():
            continue
        sub = flat[m]
        sub_valid = valid[m]
        zero = acc_dtype(0)
        sums[b] = np.where(sub_valid, sub, zero).sum(axis=0)
        counts[b] = sub_valid.sum(axis=0)
    with np.errstate(invalid="ignore"):
        nan_fill = (np.nan + 0j) if is_complex else np.nan
        mean = np.where(counts > 0, sums / np.where(counts > 0, counts, 1.0), nan_fill)
    out_shape = (n_bins, *moved.shape[1:])
    new_values = mean.reshape(out_shape)
    new_values = np.moveaxis(new_values, 0, axis)
    new_dims = tuple("phase" if d == time_dim else d for d in da.dims)
    new_coords = {
        cname: c
        for cname, c in da.coords.items()
        if time_dim not in c.dims and cname != time_dim
    }
    new_coords["phase"] = xr.DataArray(centers, dims=("phase",), name="phase")
    return xr.DataArray(
        new_values,
        dims=new_dims,
        coords=new_coords,
        attrs=dict(da.attrs),
        name=da.name,
    )

fit_spectral_slope

fit_spectral_slope(psd: DataArray, *, wavenumber_dim: str = 'freq_r', k_min: float, k_max: float) -> DataArray

The slope s of psd ∝ kˢ over [k_min, k_max].

The least-squares line of log(psd) against log(k) (diagnostix.spectra.spectral_slope). Use it to identify inertial-range power laws such as -5/3 inverse-cascade or -3 enstrophy-cascade scaling.

Parameters:

Name Type Description Default
psd DataArray

Spectrum with a wavenumber coordinate.

required
wavenumber_dim str

Name of the wavenumber dimension.

'freq_r'
k_min float

Lower inclusive wavenumber bound.

required
k_max float

Upper inclusive wavenumber bound.

required

Returns:

Type Description
DataArray

The slope, with wavenumber_dim removed, NaN where a bin of the band

DataArray

has no power.

Raises:

Type Description
ValueError

If the band holds fewer than two wavenumbers.

Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/fourier.py
def fit_spectral_slope(
    psd: xr.DataArray,
    *,
    wavenumber_dim: str = "freq_r",
    k_min: float,
    k_max: float,
) -> xr.DataArray:
    """The slope ``s`` of ``psd ∝ kˢ`` over ``[k_min, k_max]``.

    The least-squares line of ``log(psd)`` against ``log(k)``
    (``diagnostix.spectra.spectral_slope``). Use it to identify inertial-range
    power laws such as ``-5/3`` inverse-cascade or ``-3`` enstrophy-cascade
    scaling.

    Args:
        psd: Spectrum with a wavenumber coordinate.
        wavenumber_dim: Name of the wavenumber dimension.
        k_min: Lower inclusive wavenumber bound.
        k_max: Upper inclusive wavenumber bound.

    Returns:
        The slope, with ``wavenumber_dim`` removed, NaN where a bin of the band
        has no power.

    Raises:
        ValueError: If the band holds fewer than two wavenumbers.
    """
    k = np.asarray(psd[wavenumber_dim].values, dtype=np.float64)
    count = int(np.count_nonzero((k >= k_min) & (k <= k_max) & (k > 0)))
    if count < 2:
        raise ValueError(
            f"At least two positive wavenumbers required in [{k_min}, {k_max}]; "
            f"found {count}."
        )
    out = xr.apply_ufunc(
        lambda power: spectra.spectral_slope(
            spectra.Spectrum(k.astype(power.dtype), power), k_min, k_max
        ),
        psd.astype(_real(psd)),
        input_core_dims=[[wavenumber_dim]],
        dask="parallelized",
        keep_attrs=False,
        output_dtypes=[_real(psd)],
        dask_gufunc_kwargs={"allow_rechunk": True},
    )
    return out.rename(_output_name(psd, "slope", fallback="spectrum"))

integral_scale

integral_scale(psd: DataArray, *, wavenumber_dim: str = 'freq_r', moment: int = 1) -> DataArray

Energy-weighted integral scale or Taylor microscale.

Parameters:

Name Type Description Default
psd DataArray

Spectrum with a coordinate of evenly spaced wavenumbers.

required
wavenumber_dim str

Name of the wavenumber dimension.

'freq_r'
moment int

1 for the integral scale, 2 for the Taylor microscale.

1

Returns:

Type Description
DataArray

DataArray with wavenumber_dim removed.

Raises:

Type Description
ValueError

If moment is neither, or the wavenumbers are uneven.

Notes

(Σψ / Σkᵐψ)^(1/m) over the bins of the spectrum (diagnostix.spectra.integral_scale): a wavelength, with no 2π.

Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/fourier.py
def integral_scale(
    psd: xr.DataArray,
    *,
    wavenumber_dim: str = "freq_r",
    moment: int = 1,
) -> xr.DataArray:
    """Energy-weighted integral scale or Taylor microscale.

    Args:
        psd: Spectrum with a coordinate of evenly spaced wavenumbers.
        wavenumber_dim: Name of the wavenumber dimension.
        moment: ``1`` for the integral scale, ``2`` for the Taylor microscale.

    Returns:
        DataArray with ``wavenumber_dim`` removed.

    Raises:
        ValueError: If ``moment`` is neither, or the wavenumbers are uneven.

    Notes:
        ``(Σψ / Σkᵐψ)^(1/m)`` over the bins of the spectrum
        (``diagnostix.spectra.integral_scale``): a wavelength, with no 2π.
    """
    if moment not in (1, 2):
        raise ValueError(
            f"moment must be 1 (integral scale) or 2 (Taylor microscale); got {moment}."
        )
    out = _even_spectrum(
        lambda spectrum: spectra.integral_scale(spectrum, moment=moment),
        psd,
        wavenumber_dim,
    )
    return out.rename(_output_name(psd, f"moment{moment}_scale", fallback="spectrum"))

ke_spectral_flux

ke_spectral_flux(u: DataArray, v: DataArray, *, dim: Sequence[str], window: Window = None, detrend: Detrend = None, avg_dims: str | Sequence[str] | None = None) -> Dataset

Kinetic-energy spectral flux Π(k), positive towards small scales.

The advection is dealiased, so the transfer of a non-divergent velocity in a periodic box sums to 0 (diagnostix.spectra.kinetic_energy_flux). A taper makes no periodic box out of another: a tapered velocity is divergent, and its transfer does not sum to 0.

Parameters:

Name Type Description Default
u DataArray

Velocity component along the first of dim.

required
v DataArray

Velocity component along the second, on the same grid.

required
dim Sequence[str]

The (x, y) dims to transform.

required
window Window

Taper, as in :func:power_spectrum; none by default.

None
detrend Detrend

As in :func:power_spectrum; none by default.

None
avg_dims str | Sequence[str] | None

Optional non-spectral dims to average over, such as "time".

None

Returns:

Type Description
Dataset

Dataset with transfer, the gain of each ring of wavenumbers

Dataset

freq_r, and flux, Π(k) = Σ_{k' >= k} T(k').

Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/fourier.py
def ke_spectral_flux(
    u: xr.DataArray,
    v: xr.DataArray,
    *,
    dim: Sequence[str],
    window: Window = None,
    detrend: Detrend = None,
    avg_dims: str | Sequence[str] | None = None,
) -> xr.Dataset:
    """Kinetic-energy spectral flux ``Π(k)``, positive towards small scales.

    The advection is dealiased, so the transfer of a non-divergent velocity in
    a periodic box sums to 0 (``diagnostix.spectra.kinetic_energy_flux``). A
    taper makes no periodic box out of another: a tapered velocity is
    divergent, and its transfer does not sum to 0.

    Args:
        u: Velocity component along the first of ``dim``.
        v: Velocity component along the second, on the same grid.
        dim: The ``(x, y)`` dims to transform.
        window: Taper, as in :func:`power_spectrum`; none by default.
        detrend: As in :func:`power_spectrum`; none by default.
        avg_dims: Optional non-spectral dims to average over, such as
            ``"time"``.

    Returns:
        Dataset with ``transfer``, the gain of each ring of wavenumbers
        ``freq_r``, and ``flux``, ``Π(k) = Σ_{k' >= k} T(k')``.
    """
    return _spectral_flux(
        spectra.kinetic_energy_flux, u, v, dim, window, detrend, avg_dims
    )

enstrophy_spectral_flux

enstrophy_spectral_flux(u: DataArray, v: DataArray, *, dim: Sequence[str], window: Window = None, detrend: Detrend = None, avg_dims: str | Sequence[str] | None = None) -> Dataset

Enstrophy spectral flux Π_Z(k), positive towards small scales.

Otherwise as :func:ke_spectral_flux, with the vorticity ∂v/∂x − ∂u/∂y (diagnostix.spectra.enstrophy_flux).

Parameters:

Name Type Description Default
u DataArray

Velocity component along the first of dim.

required
v DataArray

Velocity component along the second, on the same grid.

required
dim Sequence[str]

The (x, y) dims to transform.

required
window Window

Taper, as in :func:power_spectrum; none by default.

None
detrend Detrend

As in :func:power_spectrum; none by default.

None
avg_dims str | Sequence[str] | None

Optional non-spectral dims to average over.

None

Returns:

Type Description
Dataset

Dataset with transfer and flux on freq_r.

Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/fourier.py
def enstrophy_spectral_flux(
    u: xr.DataArray,
    v: xr.DataArray,
    *,
    dim: Sequence[str],
    window: Window = None,
    detrend: Detrend = None,
    avg_dims: str | Sequence[str] | None = None,
) -> xr.Dataset:
    """Enstrophy spectral flux ``Π_Z(k)``, positive towards small scales.

    Otherwise as :func:`ke_spectral_flux`, with the vorticity ``∂v/∂x − ∂u/∂y``
    (``diagnostix.spectra.enstrophy_flux``).

    Args:
        u: Velocity component along the first of ``dim``.
        v: Velocity component along the second, on the same grid.
        dim: The ``(x, y)`` dims to transform.
        window: Taper, as in :func:`power_spectrum`; none by default.
        detrend: As in :func:`power_spectrum`; none by default.
        avg_dims: Optional non-spectral dims to average over.

    Returns:
        Dataset with ``transfer`` and ``flux`` on ``freq_r``.
    """
    return _spectral_flux(spectra.enstrophy_flux, u, v, dim, window, detrend, avg_dims)

Matrix decompositions

These return xrops.learn.XarrayEstimator instances configured for the named decomposition (see scikit-learn on xarray).

pca

pca(sample_dims: Hashable | Sequence[Hashable], n_components: int | float | str | None = None, *, whiten: bool = False, random_state: int | None = None, **kwargs: Any) -> XarrayEstimator

Principal Component Analysis on N-D xarray inputs.

Returns:

Type Description
XarrayEstimator

An unfitted :class:XarrayEstimator wrapping

XarrayEstimator

class:sklearn.decomposition.PCA. Call .fit(da) /

XarrayEstimator

.transform(da) / .fit_transform(da) /

XarrayEstimator

.inverse_transform(scores) as you would on the raw sklearn

XarrayEstimator

object — inputs and outputs are :class:xr.DataArray.

Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/decompose.py
def pca(
    sample_dims: Hashable | Sequence[Hashable],
    n_components: int | float | str | None = None,
    *,
    whiten: bool = False,
    random_state: int | None = None,
    **kwargs: Any,
) -> XarrayEstimator:
    """Principal Component Analysis on N-D xarray inputs.

    Returns:
        An unfitted :class:`XarrayEstimator` wrapping
        :class:`sklearn.decomposition.PCA`. Call ``.fit(da)`` /
        ``.transform(da)`` / ``.fit_transform(da)`` /
        ``.inverse_transform(scores)`` as you would on the raw sklearn
        object — inputs and outputs are :class:`xr.DataArray`.
    """
    return XarrayEstimator(
        _sklearn("decomposition", "PCA")(
            n_components=n_components,
            whiten=whiten,
            random_state=random_state,
            **kwargs,
        ),
        sample_dims=sample_dims,
        feature_dim="component",
    )

ica

ica(sample_dims: Hashable | Sequence[Hashable], n_components: int | None = None, *, random_state: int | None = None, **kwargs: Any) -> XarrayEstimator

Independent Component Analysis (FastICA).

Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/decompose.py
def ica(
    sample_dims: Hashable | Sequence[Hashable],
    n_components: int | None = None,
    *,
    random_state: int | None = None,
    **kwargs: Any,
) -> XarrayEstimator:
    """Independent Component Analysis (FastICA)."""
    return XarrayEstimator(
        _sklearn("decomposition", "FastICA")(
            n_components=n_components, random_state=random_state, **kwargs
        ),
        sample_dims=sample_dims,
        feature_dim="component",
    )

nmf

nmf(sample_dims: Hashable | Sequence[Hashable], n_components: int | None = None, *, init: str | None = None, random_state: int | None = None, **kwargs: Any) -> XarrayEstimator

Non-negative Matrix Factorisation. Input must be non-negative.

Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/decompose.py
def nmf(
    sample_dims: Hashable | Sequence[Hashable],
    n_components: int | None = None,
    *,
    init: str | None = None,
    random_state: int | None = None,
    **kwargs: Any,
) -> XarrayEstimator:
    """Non-negative Matrix Factorisation. Input must be non-negative."""
    return XarrayEstimator(
        _sklearn("decomposition", "NMF")(
            n_components=n_components,
            init=init,
            random_state=random_state,
            **kwargs,
        ),
        sample_dims=sample_dims,
        feature_dim="component",
    )

kmeans

kmeans(sample_dims: Hashable | Sequence[Hashable], n_clusters: int = 8, *, n_init: int | str = 'auto', random_state: int | None = None, **kwargs: Any) -> XarrayEstimator

K-Means clustering. predict(da) returns 1-D labels along sample_dims.

Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/decompose.py
def kmeans(
    sample_dims: Hashable | Sequence[Hashable],
    n_clusters: int = 8,
    *,
    n_init: int | str = "auto",
    random_state: int | None = None,
    **kwargs: Any,
) -> XarrayEstimator:
    """K-Means clustering. ``predict(da)`` returns 1-D labels along
    ``sample_dims``."""
    return XarrayEstimator(
        _sklearn("cluster", "KMeans")(
            n_clusters=n_clusters,
            n_init=n_init,
            random_state=random_state,
            **kwargs,
        ),
        sample_dims=sample_dims,
        feature_dim="component",
    )

Empirical orthogonal functions

eof

eof(da: DataArray, sample_dim: str = 'time', *, n_modes: int, weights: DataArray | None = None) -> Dataset

Leading empirical orthogonal functions (EOFs) of a field.

The thin singular value decomposition of the field without its mean along sample_dim, with each cell times the root of its weight (diagnostix.eofs.eofs). Without weights it is the principal component analysis of the cells, as :func:xrops.transforms.pca, up to the signs; the loading of each mode that is largest in size is positive.

The field is loaded: a decomposition reads all of it.

Parameters:

Name Type Description Default
da DataArray

Field with sample_dim and at least one other dim, the grid.

required
sample_dim str

Dim of the samples.

'time'
n_modes int

Number of modes, at most the smaller of the samples and the cells with data.

required
weights DataArray | None

Weight of each cell, 0 or more, on dims of the grid; the areas, cos(lat) on a lon–lat grid. 1 if not given.

None

Returns:

Type Description
Dataset

Dataset with modes (mode, grid), orthonormal under the weights;

Dataset

principal_components (sample_dim, mode);

Dataset

explained_variance (mode), the share of each mode; the mean

Dataset

that was removed; and the weights. A cell without any data, such as

Dataset

land, is NaN in the modes and the mean.

Raises:

Type Description
ValueError

If sample_dim is missing or the only dim, n_modes is out of range, the weights are not on the grid, or a cell has data at some samples only.

Example

Area-weighted modes of the anomalies of a sea-surface temperature::

modes = eof(sst, n_modes=3, weights=np.cos(np.deg2rad(sst.lat)))
sst_3 = eof_reconstruct(modes)
Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/eof.py
def eof(
    da: xr.DataArray,
    sample_dim: str = "time",
    *,
    n_modes: int,
    weights: xr.DataArray | None = None,
) -> xr.Dataset:
    """Leading empirical orthogonal functions (EOFs) of a field.

    The thin singular value decomposition of the field without its mean along
    ``sample_dim``, with each cell times the root of its weight
    (``diagnostix.eofs.eofs``). Without weights it is the principal component
    analysis of the cells, as :func:`xrops.transforms.pca`, up to the signs; the
    loading of each mode that is largest in size is positive.

    The field is loaded: a decomposition reads all of it.

    Args:
        da: Field with ``sample_dim`` and at least one other dim, the grid.
        sample_dim: Dim of the samples.
        n_modes: Number of modes, at most the smaller of the samples and the
            cells with data.
        weights: Weight of each cell, 0 or more, on dims of the grid; the areas,
            ``cos(lat)`` on a lon–lat grid. 1 if not given.

    Returns:
        Dataset with ``modes`` (``mode``, grid), orthonormal under the weights;
        ``principal_components`` (``sample_dim``, ``mode``);
        ``explained_variance`` (``mode``), the share of each mode; the ``mean``
        that was removed; and the ``weights``. A cell without any data, such as
        land, is NaN in the modes and the mean.

    Raises:
        ValueError: If ``sample_dim`` is missing or the only dim, ``n_modes`` is
            out of range, the weights are not on the grid, or a cell has data at
            some samples only.

    Example:
        Area-weighted modes of the anomalies of a sea-surface temperature::

            modes = eof(sst, n_modes=3, weights=np.cos(np.deg2rad(sst.lat)))
            sst_3 = eof_reconstruct(modes)
    """
    grid = _grid_dims(da, sample_dim)
    field = da.transpose(sample_dim, *grid).load()
    missing = np.isnan(field.values)
    valid = ~missing.all(axis=0)
    gaps = int((missing.any(axis=0) & valid).sum())
    if gaps:
        raise ValueError(
            f"{gaps} cell(s) have data at some samples only; fill the gaps, or mask "
            "the cells, before the decomposition."
        )
    mean = field.mean(sample_dim, skipna=False)
    weight = _on_grid(weights, mean)
    out = _eofs.eofs(
        (field - mean).data, n_modes=n_modes, weights=weight.data, valid=valid
    )
    mode = {"mode": np.arange(n_modes)}
    over_grid = {name: c for name, c in mean.coords.items() if name in grid}
    samples = {sample_dim: field[sample_dim]} if sample_dim in field.coords else {}
    return xr.Dataset(
        {
            "modes": (("mode", *grid), out.modes),
            "principal_components": ((sample_dim, "mode"), out.principal_components),
            "explained_variance": (("mode",), out.explained_variance),
            "mean": mean.rename(None),
            "weights": weight,
        },
        coords={**mode, **over_grid, **samples},
    )

eof_project

eof_project(da: DataArray, eofs: Dataset) -> DataArray

The amplitude of each mode in a field: Σ w (x − mean) e over the cells.

For the field the modes came from, these are its principal components (diagnostix.eofs.project).

Parameters:

Name Type Description Default
da DataArray

Field on the grid of the modes, with any other dims. A NaN in a cell that the modes have gives NaN.

required
eofs Dataset

Output of :func:eof.

required

Returns:

Type Description
DataArray

The amplitudes, with mode in place of the grid.

Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/eof.py
def eof_project(da: xr.DataArray, eofs: xr.Dataset) -> xr.DataArray:
    """The amplitude of each mode in a field: ``Σ w (x − mean) e`` over the cells.

    For the field the modes came from, these are its principal components
    (``diagnostix.eofs.project``).

    Args:
        da: Field on the grid of the modes, with any other dims. A NaN in a cell
            that the modes have gives NaN.
        eofs: Output of :func:`eof`.

    Returns:
        The amplitudes, with ``mode`` in place of the grid.
    """
    grid = list(eofs["mean"].dims)
    anomaly = da - eofs["mean"]
    record = _record(eofs)
    valid = ~np.isnan(eofs["mean"].values)
    weights = eofs["weights"].values
    out = xr.apply_ufunc(
        lambda x: _eofs.project(x, record, weights=weights, valid=valid),
        anomaly,
        input_core_dims=[grid],
        output_core_dims=[["mode"]],
        dask="parallelized",
        keep_attrs=False,
        output_dtypes=[anomaly.dtype],
        dask_gufunc_kwargs={
            "allow_rechunk": True,
            "output_sizes": {"mode": eofs.sizes["mode"]},
        },
    )
    return out.assign_coords(mode=eofs["mode"])

eof_reconstruct

eof_reconstruct(eofs: Dataset, principal_components: DataArray | None = None) -> DataArray

The field that some amplitudes of the modes add up to: mean + Σ a e.

Parameters:

Name Type Description Default
eofs Dataset

Output of :func:eof.

required
principal_components DataArray | None

Amplitudes on mode and any other dims; those of eofs if not given. A mode set to 0 is left out.

None

Returns:

Type Description
DataArray

The field, with the grid in place of mode, NaN where the modes are

DataArray

(diagnostix.eofs.reconstruct).

Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/eof.py
def eof_reconstruct(
    eofs: xr.Dataset, principal_components: xr.DataArray | None = None
) -> xr.DataArray:
    """The field that some amplitudes of the modes add up to: ``mean + Σ a e``.

    Args:
        eofs: Output of :func:`eof`.
        principal_components: Amplitudes on ``mode`` and any other dims; those
            of ``eofs`` if not given. A mode set to 0 is left out.

    Returns:
        The field, with the grid in place of ``mode``, NaN where the modes are
        (``diagnostix.eofs.reconstruct``).
    """
    if principal_components is None:
        principal_components = eofs["principal_components"]
    grid = list(eofs["mean"].dims)
    record = _record(eofs)
    out = xr.apply_ufunc(
        lambda a: _eofs.reconstruct(record, a),
        principal_components,
        input_core_dims=[["mode"]],
        output_core_dims=[grid],
        dask="parallelized",
        keep_attrs=False,
        output_dtypes=[principal_components.dtype],
        dask_gufunc_kwargs={
            "allow_rechunk": True,
            "output_sizes": {d: eofs.sizes[d] for d in grid},
        },
    )
    return out + eofs["mean"]

Mask morphology

binary_opening_2d

binary_opening_2d(mask: DataArray, *, footprint: Footprint = 1, lon: str = 'lon', lat: str = 'lat') -> DataArray

Morphologically open a 2-D boolean mask slice-by-slice.

Parameters:

Name Type Description Default
mask DataArray

Boolean mask with lat and lon dimensions.

required
footprint Footprint

Structuring element specification.

1
lon str

Longitude dimension name.

'lon'
lat str

Latitude dimension name.

'lat'

Returns:

Type Description
DataArray

Same-shaped boolean mask after erosion followed by dilation.

Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/morphology.py
def binary_opening_2d(
    mask: xr.DataArray,
    *,
    footprint: Footprint = 1,
    lon: str = "lon",
    lat: str = "lat",
) -> xr.DataArray:
    """Morphologically open a 2-D boolean mask slice-by-slice.

    Args:
        mask: Boolean mask with ``lat`` and ``lon`` dimensions.
        footprint: Structuring element specification.
        lon: Longitude dimension name.
        lat: Latitude dimension name.

    Returns:
        Same-shaped boolean mask after erosion followed by dilation.
    """
    morph = _require_skimage()
    fp = _resolve_footprint(footprint)
    return _wrap2d(
        mask,
        lon=lon,
        lat=lat,
        fn=lambda m: morph.opening(m, footprint=fp),
    )

binary_closing_2d

binary_closing_2d(mask: DataArray, *, footprint: Footprint = 1, lon: str = 'lon', lat: str = 'lat') -> DataArray

Morphologically close a 2-D boolean mask slice-by-slice.

Parameters:

Name Type Description Default
mask DataArray

Boolean mask with lat and lon dimensions.

required
footprint Footprint

Structuring element specification.

1
lon str

Longitude dimension name.

'lon'
lat str

Latitude dimension name.

'lat'

Returns:

Type Description
DataArray

Same-shaped boolean mask after dilation followed by erosion.

Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/morphology.py
def binary_closing_2d(
    mask: xr.DataArray,
    *,
    footprint: Footprint = 1,
    lon: str = "lon",
    lat: str = "lat",
) -> xr.DataArray:
    """Morphologically close a 2-D boolean mask slice-by-slice.

    Args:
        mask: Boolean mask with ``lat`` and ``lon`` dimensions.
        footprint: Structuring element specification.
        lon: Longitude dimension name.
        lat: Latitude dimension name.

    Returns:
        Same-shaped boolean mask after dilation followed by erosion.
    """
    morph = _require_skimage()
    fp = _resolve_footprint(footprint)
    return _wrap2d(
        mask,
        lon=lon,
        lat=lat,
        fn=lambda m: morph.closing(m, footprint=fp),
    )

remove_small_holes_2d

remove_small_holes_2d(mask: DataArray, *, area: int = 4, lon: str = 'lon', lat: str = 'lat') -> DataArray

Flip False connected components smaller than area to True.

True means "masked / needs filling" in xrops interpolation workflows, so this removes small unmasked islands inside larger gaps.

Parameters:

Name Type Description Default
mask DataArray

Boolean mask with lat and lon dimensions.

required
area int

False regions smaller than this pixel count are filled.

4
lon str

Longitude dimension name.

'lon'
lat str

Latitude dimension name.

'lat'

Returns:

Type Description
DataArray

Same-shaped boolean mask with small False holes filled.

Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/morphology.py
def remove_small_holes_2d(
    mask: xr.DataArray,
    *,
    area: int = 4,
    lon: str = "lon",
    lat: str = "lat",
) -> xr.DataArray:
    """Flip False connected components smaller than ``area`` to True.

    ``True`` means "masked / needs filling" in xrops interpolation
    workflows, so this removes small unmasked islands inside larger gaps.

    Args:
        mask: Boolean mask with ``lat`` and ``lon`` dimensions.
        area: False regions smaller than this pixel count are filled.
        lon: Longitude dimension name.
        lat: Latitude dimension name.

    Returns:
        Same-shaped boolean mask with small False holes filled.
    """
    _validate_area(area)
    return _wrap2d(
        mask,
        lon=lon,
        lat=lat,
        fn=lambda m: _remove_small_holes(m, area=area),
    )

remove_small_objects_2d

remove_small_objects_2d(mask: DataArray, *, area: int = 4, lon: str = 'lon', lat: str = 'lat') -> DataArray

Flip True connected components smaller than area to False.

True means "masked / needs filling" in xrops interpolation workflows, so this removes isolated masked specks.

Parameters:

Name Type Description Default
mask DataArray

Boolean mask with lat and lon dimensions.

required
area int

True regions smaller than this pixel count are dropped.

4
lon str

Longitude dimension name.

'lon'
lat str

Latitude dimension name.

'lat'

Returns:

Type Description
DataArray

Same-shaped boolean mask with small True objects removed.

Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/morphology.py
def remove_small_objects_2d(
    mask: xr.DataArray,
    *,
    area: int = 4,
    lon: str = "lon",
    lat: str = "lat",
) -> xr.DataArray:
    """Flip True connected components smaller than ``area`` to False.

    ``True`` means "masked / needs filling" in xrops interpolation
    workflows, so this removes isolated masked specks.

    Args:
        mask: Boolean mask with ``lat`` and ``lon`` dimensions.
        area: True regions smaller than this pixel count are dropped.
        lon: Longitude dimension name.
        lat: Latitude dimension name.

    Returns:
        Same-shaped boolean mask with small True objects removed.
    """
    _validate_area(area)
    return _wrap2d(
        mask,
        lon=lon,
        lat=lat,
        fn=lambda m: _remove_small_objects(m, area=area),
    )

clean_mask

clean_mask(mask: DataArray, *, fill_holes_area: int | None = 4, drop_objects_area: int | None = None, closing_footprint: Footprint | None = None, opening_footprint: Footprint | None = None, lon: str = 'lon', lat: str = 'lat') -> DataArray

Run the common mask-despeckling pipeline.

Steps run in fixed order when their corresponding keyword is not None: remove small holes, remove small objects, binary closing, then binary opening.

Parameters:

Name Type Description Default
mask DataArray

Boolean mask with lat and lon dimensions.

required
fill_holes_area int | None

Optional hole area threshold.

4
drop_objects_area int | None

Optional object area threshold.

None
closing_footprint Footprint | None

Optional binary-closing footprint.

None
opening_footprint Footprint | None

Optional binary-opening footprint.

None
lon str

Longitude dimension name.

'lon'
lat str

Latitude dimension name.

'lat'

Returns:

Type Description
DataArray

Same-shaped cleaned boolean mask.

Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/morphology.py
def clean_mask(
    mask: xr.DataArray,
    *,
    fill_holes_area: int | None = 4,
    drop_objects_area: int | None = None,
    closing_footprint: Footprint | None = None,
    opening_footprint: Footprint | None = None,
    lon: str = "lon",
    lat: str = "lat",
) -> xr.DataArray:
    """Run the common mask-despeckling pipeline.

    Steps run in fixed order when their corresponding keyword is not
    ``None``: remove small holes, remove small objects, binary closing,
    then binary opening.

    Args:
        mask: Boolean mask with ``lat`` and ``lon`` dimensions.
        fill_holes_area: Optional hole area threshold.
        drop_objects_area: Optional object area threshold.
        closing_footprint: Optional binary-closing footprint.
        opening_footprint: Optional binary-opening footprint.
        lon: Longitude dimension name.
        lat: Latitude dimension name.

    Returns:
        Same-shaped cleaned boolean mask.
    """
    out = mask
    if fill_holes_area is not None:
        out = remove_small_holes_2d(out, area=fill_holes_area, lon=lon, lat=lat)
    if drop_objects_area is not None:
        out = remove_small_objects_2d(out, area=drop_objects_area, lon=lon, lat=lat)
    if closing_footprint is not None:
        out = binary_closing_2d(out, footprint=closing_footprint, lon=lon, lat=lat)
    if opening_footprint is not None:
        out = binary_opening_2d(out, footprint=opening_footprint, lon=lon, lat=lat)
    return out

Axis remapping

remap_axis interpolates one dimension of a DataArray onto a new axis of target values. By default the source axis is the 1-D dimension coordinate and targets outside its range become NaN. Pass source_coords= (a coordinate name or a broadcastable DataArray) when the source levels vary per column — terrain-following or hybrid vertical grids — and extrapolate="nearest" to hold each column's end value beyond its own range. See the Vertical & axis remapping section of the interpolation API for the operator-level presets.

remap_axis

remap_axis(da: DataArray, *, source_dim: str, target_coords: DataArray | ndarray, target_name: str | None = None, method: str = 'linear', source_coords: str | DataArray | None = None, extrapolate: Extrapolate = 'nan') -> DataArray

Remap da along source_dim onto target_coords.

If target_coords is a :class:xr.DataArray and target_name is None, the new dim name is taken from target_coords.name; otherwise target_name (or source_dim) is used.

Every coordinate that depends on source_dim is dropped from the output; the new target coordinate is attached under the new name. The Layer-1 RemapAxis operator handles Dataset selection / per-variable looping.

Parameters:

Name Type Description Default
da DataArray

Numeric DataArray carrying source_dim.

required
source_dim str

Name of the dimension being replaced.

required
target_coords DataArray | ndarray

1-D target axis values.

required
target_name str | None

Explicit name for the new dimension.

None
method str

"linear" or "nearest".

'linear'
source_coords str | DataArray | None

Source axis values. None (default) uses the 1-D dimension coordinate da[source_dim]. A coordinate name on da or a DataArray broadcastable against da supplies per-column levels — it must carry source_dim and may vary along any of the other dims (e.g. z_agl(time, level, y, x) on a terrain-following grid). Every column must be strictly monotone along source_dim.

None
extrapolate Extrapolate

"nan" (default) — targets outside a column's range become NaN; "nearest" — they hold that column's end value.

'nan'

Returns:

Type Description
DataArray

da with source_dim replaced by the target axis. When

DataArray

source_coords is given, chunked (dask) inputs stay lazy as

DataArray

long as source_dim sits in a single chunk.

Raises:

Type Description
ValueError

If source_dim is missing, source_coords does not carry it, a column is not monotone, or extrapolate / method is unknown.

TypeError

If da is not numeric.

Example

Remap a model-level field with a 4-D height-above-ground coordinate onto fixed heights, holding the lowest / highest model level beyond each column's range:

>>> import numpy as np, xarray as xr
>>> from xrops.transforms import remap_axis
>>> level = np.arange(4)
>>> z_agl = 20.0 * (level[None, :, None, None] + 1) + np.zeros((2, 4, 3, 3))
>>> z_agl[..., 0, 0] += 15.0  # one column starts higher up
>>> t = xr.DataArray(
...     300.0 - 0.01 * z_agl,
...     dims=("time", "level", "y", "x"),
...     coords={"z_agl": (("time", "level", "y", "x"), z_agl)},
... )
>>> out = remap_axis(
...     t,
...     source_dim="level",
...     target_coords=np.array([10.0, 50.0, 90.0]),
...     target_name="height",
...     source_coords="z_agl",
...     extrapolate="nearest",
... )
>>> out.dims, out.sizes["height"]
(('time', 'height', 'y', 'x'), 3)
>>> float(out.isel(time=0, height=1, y=1, x=1))  # in range: linear
299.5
Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/coord_remap.py
def remap_axis(
    da: xr.DataArray,
    *,
    source_dim: str,
    target_coords: xr.DataArray | np.ndarray,
    target_name: str | None = None,
    method: str = "linear",
    source_coords: str | xr.DataArray | None = None,
    extrapolate: Extrapolate = "nan",
) -> xr.DataArray:
    """Remap ``da`` along ``source_dim`` onto ``target_coords``.

    If ``target_coords`` is a :class:`xr.DataArray` and ``target_name``
    is None, the new dim name is taken from ``target_coords.name``;
    otherwise ``target_name`` (or ``source_dim``) is used.

    Every coordinate that depends on ``source_dim`` is dropped from the
    output; the new target coordinate is attached under the new name.
    The Layer-1 ``RemapAxis`` operator handles Dataset selection /
    per-variable looping.

    Args:
        da: Numeric DataArray carrying ``source_dim``.
        source_dim: Name of the dimension being replaced.
        target_coords: 1-D target axis values.
        target_name: Explicit name for the new dimension.
        method: ``"linear"`` or ``"nearest"``.
        source_coords: Source axis *values*. ``None`` (default) uses the
            1-D dimension coordinate ``da[source_dim]``. A coordinate name
            on ``da`` or a DataArray broadcastable against ``da`` supplies
            per-column levels — it must carry ``source_dim`` and may vary
            along any of the other dims (e.g. ``z_agl(time, level, y, x)``
            on a terrain-following grid). Every column must be strictly
            monotone along ``source_dim``.
        extrapolate: ``"nan"`` (default) — targets outside a column's
            range become ``NaN``; ``"nearest"`` — they hold that column's
            end value.

    Returns:
        ``da`` with ``source_dim`` replaced by the target axis. When
        ``source_coords`` is given, chunked (dask) inputs stay lazy as
        long as ``source_dim`` sits in a single chunk.

    Raises:
        ValueError: If ``source_dim`` is missing, ``source_coords`` does
            not carry it, a column is not monotone, or ``extrapolate`` /
            ``method`` is unknown.
        TypeError: If ``da`` is not numeric.

    Example:
        Remap a model-level field with a 4-D height-above-ground
        coordinate onto fixed heights, holding the lowest / highest model
        level beyond each column's range:

        ```pycon
        >>> import numpy as np, xarray as xr
        >>> from xrops.transforms import remap_axis
        >>> level = np.arange(4)
        >>> z_agl = 20.0 * (level[None, :, None, None] + 1) + np.zeros((2, 4, 3, 3))
        >>> z_agl[..., 0, 0] += 15.0  # one column starts higher up
        >>> t = xr.DataArray(
        ...     300.0 - 0.01 * z_agl,
        ...     dims=("time", "level", "y", "x"),
        ...     coords={"z_agl": (("time", "level", "y", "x"), z_agl)},
        ... )
        >>> out = remap_axis(
        ...     t,
        ...     source_dim="level",
        ...     target_coords=np.array([10.0, 50.0, 90.0]),
        ...     target_name="height",
        ...     source_coords="z_agl",
        ...     extrapolate="nearest",
        ... )
        >>> out.dims, out.sizes["height"]
        (('time', 'height', 'y', 'x'), 3)
        >>> float(out.isel(time=0, height=1, y=1, x=1))  # in range: linear
        299.5

        ```
    """
    if source_dim not in da.dims:
        raise ValueError(
            f"source_dim {source_dim!r} not in DataArray dims {tuple(da.dims)}"
        )
    if extrapolate not in _kernels._EXTRAPOLATE_MODES:
        raise ValueError(
            f"unknown extrapolate {extrapolate!r}; expected one of "
            f"{_kernels._EXTRAPOLATE_MODES!r}"
        )
    if source_coords is None and source_dim not in da.coords:
        raise ValueError(
            f"DataArray must carry a coordinate named {source_dim!r} "
            "for the source axis values"
        )
    if not np.issubdtype(da.dtype, np.number):
        raise TypeError(
            f"remap_axis requires numeric data; got dtype {da.dtype}. "
            "Drop or convert the variable before calling remap_axis."
        )

    if isinstance(target_coords, xr.DataArray):
        new_name = target_name or target_coords.name or source_dim
        tgt = np.asarray(target_coords.values, dtype=float)
    else:
        new_name = target_name or source_dim
        tgt = np.asarray(target_coords, dtype=float)

    if source_coords is not None or extrapolate != "nan":
        return _remap_axis_columns(
            da,
            source_dim=source_dim,
            tgt=tgt,
            new_name=str(new_name),
            method=method,
            source_coords=source_coords,
            extrapolate=extrapolate,
        )

    src = np.asarray(da[source_dim].values, dtype=float)

    axis = da.get_axis_num(source_dim)
    new_values = _kernels.remap_axis(
        da.values,
        axis=axis,
        source_coords=src,
        target_coords=tgt,
        method=method,
    )
    new_dims = tuple(new_name if d == source_dim else d for d in da.dims)
    new_coords = {
        cname: c
        for cname, c in da.coords.items()
        if source_dim not in c.dims and cname != source_dim
    }
    new_coords[new_name] = xr.DataArray(tgt, dims=(new_name,), name=new_name)
    return xr.DataArray(
        new_values,
        dims=new_dims,
        coords=new_coords,
        attrs=dict(da.attrs),
        name=da.name,
    )