Skip to content

Feature Request: Conversion Utilities for Complex Data – Dtype & Dimension Transformations #10213

@andrewendlinger

Description

@andrewendlinger

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:

  1. 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]})
  2. 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.
  3. 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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions