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.
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.
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 = 'tukey', detrend: str | None = '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: str | None = 'tukey', detrend: str | None = 'linear', avg_dims: str | Sequence[str] | None = None, return_2d: bool = False)
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
|
str | None
|
Optional Fourier window. |
'tukey'
|
detrend
|
str | None
|
Optional Fourier detrending mode. |
'linear'
|
avg_dims
|
str | Sequence[str] | None
|
Optional non-spectral dimensions to average. |
None
|
return_2d
|
bool
|
If |
False
|
Returns:
| Type | Description |
|---|---|
|
Dataset with |
|
|
when requested. |
Examples:
Source code in packages/xrtoolz-ops/src/xrops/transforms/operators.py
EnstrophySpectralFlux
¶
EnstrophySpectralFlux(u: str, v: str, dim: Sequence[str], *, window: str | None = 'tukey', detrend: str | None = 'linear', avg_dims: str | Sequence[str] | None = None, return_2d: bool = False)
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
|
str | None
|
Optional Fourier window. |
'tukey'
|
detrend
|
str | None
|
Optional Fourier detrending mode. |
'linear'
|
avg_dims
|
str | Sequence[str] | None
|
Optional non-spectral dimensions to average. |
None
|
return_2d
|
bool
|
If |
False
|
Returns:
| Type | Description |
|---|---|
|
Dataset with vorticity-based enstrophy |
|
|
variables, plus |
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, **kwargs: Any) -> DataArray
Power spectral density of da along dim.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
da
|
DataArray
|
Input field. |
required |
dim
|
str | Sequence[str]
|
Single dim or sequence of dims to transform. Pass a single string for 1-D spectra; a tuple/list for multi-D (space-time) spectra. |
required |
isotropic
|
bool
|
If |
False
|
**kwargs
|
Any
|
Forwarded to :func: |
{}
|
Returns:
| Type | Description |
|---|---|
DataArray
|
DataArray of the spectrum, named |
DataArray
|
|
Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/fourier.py
isotropic_power_spectrum
¶
Radially-averaged 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 | Sequence[str], **kwargs: Any) -> DataArray
Cross-power spectrum of da_a and da_b along dim.
Returns:
| Type | Description |
|---|---|
DataArray
|
DataArray named |
Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/fourier.py
coherence
¶
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. Computed from the
:func:xrft.cross_spectrum and individual auto-spectra under the
same averaging window, so the three quantities are commensurable.
Returns:
| Type | Description |
|---|---|
DataArray
|
DataArray named |
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.
Computes the two-sided FFT of the complex velocity u + i v, splits
positive and negative wavenumbers into counter-clockwise and clockwise
components, then folds both onto a shared positive wavenumber axis.
The unnormalized FFT is converted to a density with dx / n scaling so
integrating psd_cw + psd_ccw over wavenumber recovers velocity variance.
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. |
required |
avg_dims
|
str | Sequence[str] | None
|
Optional dimension or dimensions to average in each output. |
None
|
Returns:
| Type | Description |
|---|---|
Dataset
|
Dataset with |
Dataset
|
|
Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/fourier.py
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 | |
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 = 'tukey', detrend: str | None = '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.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
da
|
DataArray
|
1-D signal (along |
required |
dim
|
str
|
Time / sample dimension to slide the window along. |
required |
window_size
|
int
|
Length (in samples) of each STFT window. |
required |
hop
|
int | None
|
Stride between window starts. Defaults to
|
None
|
window
|
str
|
Window name forwarded to :func: |
'tukey'
|
detrend
|
str | None
|
Per-window detrending. |
'linear'
|
Returns:
| Type | Description |
|---|---|
DataArray
|
DataArray with dims |
DataArray
|
named |
Source code in packages/xrtoolz-ops/src/xrops/transforms/_src/fourier.py
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) -> tuple[float, float]
Fit log(psd) = slope * log(k) + intercept over [k_min, k_max].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
psd
|
DataArray
|
One-dimensional positive spectrum. |
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 |
|---|---|
tuple[float, float]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If fewer than two positive finite samples remain in the requested fit window. |
Notes
Use the fitted slope to identify inertial-range power laws such as
-5/3 inverse-cascade or -3 enstrophy-cascade scaling.
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
|
One-dimensional spectrum with a wavenumber coordinate. |
required |
wavenumber_dim
|
str
|
Name of the wavenumber dimension. |
'freq_r'
|
moment
|
int
|
|
1
|
Returns:
| Type | Description |
|---|---|
DataArray
|
DataArray with |
Notes
moment=1 returns ∫ψ dk / ∫kψ dk. moment=2 returns the
Taylor microscale λ = sqrt(∫ψ dk / ∫k²ψ dk). Integrals use
xarray's coordinate-aware trapezoidal rule, so non-uniform
wavenumber grids (e.g. radially binned spectra) are handled
correctly.
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: str | None = 'tukey', detrend: str | None = 'linear', avg_dims: str | Sequence[str] | None = None, return_2d: bool = False) -> Dataset
Kinetic-energy spectral flux Π(k).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
u
|
DataArray
|
Zonal velocity component with both spatial dimensions in |
required |
v
|
DataArray
|
Meridional velocity component on the same grid as |
required |
dim
|
Sequence[str]
|
Two spatial dimensions to Fourier transform, for example
|
required |
window
|
str | None
|
Optional window forwarded to :func: |
'tukey'
|
detrend
|
str | None
|
Optional detrending forwarded to :func: |
'linear'
|
avg_dims
|
str | Sequence[str] | None
|
Optional non-spectral dimensions to average before radial
integration, for example |
None
|
return_2d
|
bool
|
If |
False
|
Returns:
| Type | Description |
|---|---|
Dataset
|
Dataset with |
Dataset
|
|
Dataset
|
when requested. |
Notes
Positive flux denotes downscale kinetic-energy transfer. The
nonlinear advection terms are formed in physical space from
Fourier-space gradients, transformed back to spectral space, radially
binned by freq_r, and accumulated from high to low wavenumber.
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: str | None = 'tukey', detrend: str | None = 'linear', avg_dims: str | Sequence[str] | None = None, return_2d: bool = False) -> Dataset
Enstrophy spectral flux Π_Z(k).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
u
|
DataArray
|
Zonal velocity component with both spatial dimensions in |
required |
v
|
DataArray
|
Meridional velocity component on the same grid as |
required |
dim
|
Sequence[str]
|
Two spatial dimensions to Fourier transform. |
required |
window
|
str | None
|
Optional window forwarded to :func: |
'tukey'
|
detrend
|
str | None
|
Optional detrending forwarded to :func: |
'linear'
|
avg_dims
|
str | Sequence[str] | None
|
Optional non-spectral dimensions to average before radial integration. |
None
|
return_2d
|
bool
|
If |
False
|
Returns:
| Type | Description |
|---|---|
Dataset
|
Dataset with radially summed enstrophy |
Dataset
|
|
Notes
Vorticity is computed spectrally as ζ̂ = 2πi(k_x v̂ - k_y û).
Positive flux denotes downscale enstrophy transfer, accumulated
from high to low radial wavenumber with the same convention as
:func:ke_spectral_flux.
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
eof
¶
eof(sample_dims: Hashable | Sequence[Hashable], n_modes: int | None = None, *, whiten: bool = False, random_state: int | None = None, **kwargs: Any) -> XarrayEstimator
Empirical Orthogonal Functions — geophysical PCA.
Identical numerics to :func:pca, but the new feature axis is
named "mode" rather than "component" to match the
geosciences convention.
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
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 | |