-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Open
Labels
Description
Is your feature request related to a problem?
Description:
I’d like to propose adding utility functions to xarray to convert complex-valued DataArrays into a real-valued form with a separate dimension for real and imaginary parts, and back. Since netCDF doesn't support complex numbers yet, this would offer a practical workaround for saving, plotting, and processing complex data using existing xarray tools.
Proposed Approaches:
-
Using “to_”/“from_” Naming:
to_complex_dim
: Converts a complex dtype DataArray to a new DataArray with an extra dimension (e.g.,"complex"
) that holds the real and imaginary components. Something in the style of:def to_complex_dim(da: xr.DataArray, dim: str = "complex", labels: list = ["Real", "Imag"]) -> xr.DataArray: if not np.iscomplexobj(da.data): raise ValueError("DataArray must be complex-valued.") return xr.DataArray( np.stack([da.real, da.imag], axis=-1), dims=da.dims + (dim,), coords={**da.coords, dim: labels}, attrs=da.attrs, )
to_complex_dtype
: Reconstructs a complex dtype DataArray from a DataArray that contains real and imaginary parts along a dedicated dimension.def to_complex_dtype(da: xr.DataArray, dim: str = "complex", labels: list = ["Real", "Imag"]) -> xr.DataArray: return da.sel({dim: labels[0]}) + 1j * da.sel({dim: labels[1]})
-
Using “pack”/“unpack” Naming:
pack_complex
: “Packs” a real/imaginary DataArray (with an extra dimension) back into a complex dtype DataArray.unpack_complex
: “Unpacks” the real and imaginary parts from a complex dtype DataArray into separate values along a new dimension.
-
Accessor-Based Integration:
Alternatively, these functions could be incorporated as a DataArray accessor (?)
Would love to hear your thoughts on this.
Describe the solution you'd like
No response
Describe alternatives you've considered
No response
Additional context
No response