xgcm / xrft

Fourier transforms on xarray data structures
https://xrft.readthedocs.io/en/latest/
MIT License
153 stars 45 forks source link

Using 2D latitude and longitude as dims in power spectrum #198

Open vic1309 opened 1 year ago

vic1309 commented 1 year ago

Hello all

First of all, congratulations for the nice package.

I have a set of gridded variables. Latitude and longitude have NxN dimensions. A snippet is provided below:

# Define shape of the area
dx = 2.5
dy = dx

Nx = np.shape(eke[:,:])[1] # N of points in x 
Ny = np.shape(eke[:,:])[0] # N of points in y

Lx = Nx*dx
Ly = Ny*dy

x = np.arange(0, Lx, dx)
y = np.arange(0, Ly, dy)

# Build Array
LAT = df.lat.values[p0-pr:p0+pr, p1-pr:p1+pr]
LON = df.lon.values[p0-pr:p0+pr, p1-pr:p1+pr]

uo = xr.DataArray(eke, coords={'x':x, 'y':y, 'lat':(['x','y'], LAT), 'lon': (['x','y'], LON)}, dims=('x', 'y'))

where EKE is my 2D field.

When I run:

iso = xrft.isotropic_power_spectrum(uo, dim=['x','y'], detrend='linear', window=True)

I get the following error:

ValueError: The input array contains coordinate variable(s) (['lat', 'lon']) whose dims include the transform dimension(s) `x`. Please drop these coordinates (`.drop(['lat', 'lon']`) before invoking xrft.

Any ideas on how to solve it? I can provided the eke file if necessary.

rabernat commented 1 year ago

The error message is telling you what to do. Drop lat and lon, or just don't include them in the first place.

uo = uo.drop(['lat', 'lon'])

Such coordinates have no meaning after the Fourier transform, so xgcm forces you to explicitly drop them.

vic1309 commented 1 year ago

Thanks for the prompt reply, Ryan.

My goal on creating a single array also containing the coordinates is for convenience as I plan to use the same data later e.g. this example .