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
¶
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
CrossSpectrum
¶
Bases: Operator
Cross-power spectrum of ds[var_a] and ds[var_b].
Source code in packages/xrtoolz-ops/src/xrops/transforms/operators.py
Coherence
¶
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
RotarySpectrum
¶
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
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
DCT
¶
Bases: Operator
Discrete Cosine Transform of ds[variable] along dim.
Source code in packages/xrtoolz-ops/src/xrops/transforms/operators.py
DST
¶
Bases: Operator
Discrete Sine Transform of ds[variable] along dim.
Source code in packages/xrtoolz-ops/src/xrops/transforms/operators.py
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
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 |
Examples:
Source code in packages/xrtoolz-ops/src/xrops/transforms/operators.py
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 |
|
|
variables. |
Examples:
Source code in packages/xrtoolz-ops/src/xrops/transforms/operators.py
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 |
False
|
window
|
Window
|
|
'hann'
|
detrend
|
Detrend
|
What to take away first: |
'linear'
|
Returns:
| Type | Description |
|---|---|
DataArray
|
DataArray of the spectrum, named |
DataArray
|
|
DataArray
|
place of each dim, or on |
DataArray
|
spectrum NaN. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If there are more than two dims, |
Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/fourier.py
isotropic_power_spectrum
¶
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
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: |
'hann'
|
detrend
|
Detrend
|
As in :func: |
'constant'
|
Returns:
| Type | Description |
|---|---|
DataArray
|
Complex DataArray named |
DataArray
|
|
DataArray
|
covariance. |
Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/fourier.py
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: |
'hann'
|
detrend
|
Detrend
|
As in :func: |
'constant'
|
Returns:
| Type | Description |
|---|---|
DataArray
|
DataArray named |
DataArray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/fourier.py
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 |
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 |
Dataset
|
|
Dataset
|
|
Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/fourier.py
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 |
required |
Returns:
| Type | Description |
|---|---|
DataArray
|
DataArray named |
DataArray
|
|
Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/fourier.py
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 |
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
|
None
|
window
|
str | None
|
Window name or tuple for :func: |
'tukey'
|
detrend
|
Detrend
|
Per-window detrending. |
'linear'
|
Returns:
| Type | Description |
|---|---|
DataArray
|
Complex DataArray with dims |
DataArray
|
named |
Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/fourier.py
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 | |
dct
¶
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 |
2
|
norm
|
str | None
|
|
'ortho'
|
Returns:
| Type | Description |
|---|---|
DataArray
|
DataArray of the same shape, named |
Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/dct.py
idct
¶
Inverse DCT along dim. See :func:dct for arguments.
Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/dct.py
dst
¶
Discrete Sine Transform along dim. See :func:dct.
Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/dct.py
idst
¶
Inverse DST along dim. See :func:dct.
Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/dct.py
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: |
required |
wavelet
|
str
|
Wavelet name (e.g. |
'morl'
|
sampling_period
|
float
|
Sample spacing along |
1.0
|
Returns:
| Type | Description |
|---|---|
DataArray
|
Complex-valued DataArray with dims |
DataArray
|
named |
DataArray
|
along the new |
Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/wavelet.py
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'
|
level
|
int | None
|
Decomposition depth. |
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
drop_negative_frequencies
¶
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
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
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 | |
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 |
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
integral_scale
¶
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
|
Returns:
| Type | Description |
|---|---|
DataArray
|
DataArray with |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
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 |
required |
v
|
DataArray
|
Velocity component along the second, on the same grid. |
required |
dim
|
Sequence[str]
|
The |
required |
window
|
Window
|
Taper, as in :func: |
None
|
detrend
|
Detrend
|
As in :func: |
None
|
avg_dims
|
str | Sequence[str] | None
|
Optional non-spectral dims to average over, such as
|
None
|
Returns:
| Type | Description |
|---|---|
Dataset
|
Dataset with |
Dataset
|
|
Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/fourier.py
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 |
required |
v
|
DataArray
|
Velocity component along the second, on the same grid. |
required |
dim
|
Sequence[str]
|
The |
required |
window
|
Window
|
Taper, as in :func: |
None
|
detrend
|
Detrend
|
As in :func: |
None
|
avg_dims
|
str | Sequence[str] | None
|
Optional non-spectral dims to average over. |
None
|
Returns:
| Type | Description |
|---|---|
Dataset
|
Dataset with |
Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/fourier.py
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
|
class: |
XarrayEstimator
|
|
XarrayEstimator
|
|
XarrayEstimator
|
object — inputs and outputs are :class: |
Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/decompose.py
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
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
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
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 |
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,
|
None
|
Returns:
| Type | Description |
|---|---|
Dataset
|
Dataset with |
Dataset
|
|
Dataset
|
|
Dataset
|
that was removed; and the |
Dataset
|
land, is NaN in the modes and the mean. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
eof_project
¶
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: |
required |
Returns:
| Type | Description |
|---|---|
DataArray
|
The amplitudes, with |
Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/eof.py
eof_reconstruct
¶
The field that some amplitudes of the modes add up to: mean + Σ a e.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
eofs
|
Dataset
|
Output of :func: |
required |
principal_components
|
DataArray | None
|
Amplitudes on |
None
|
Returns:
| Type | Description |
|---|---|
DataArray
|
The field, with the grid in place of |
DataArray
|
( |
Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/eof.py
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 |
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
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 |
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
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 |
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
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 |
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
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 |
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
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 |
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'
|
source_coords
|
str | DataArray | None
|
Source axis values. |
None
|
extrapolate
|
Extrapolate
|
|
'nan'
|
Returns:
| Type | Description |
|---|---|
DataArray
|
|
DataArray
|
|
DataArray
|
long as |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
TypeError
|
If |
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
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 | |