xgcm / xrft

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

_diff_coord used by fft does not work for np.datetime64 with higher than 1 second precision #203

Open aspitarl opened 4 months ago

aspitarl commented 4 months ago

I am trying to take a fft with a datarray with time data taken at millisecond precision. The coordinates have datatype np.datetime64[ns] The coordinates are processed by this line of code in _diff_coord, which converts to second precision and eventually throws an error as the coordinate difference is zero:

https://github.com/xgcm/xrft/blob/92fd1df3123ea243c61fc834747a5b378126b8ea/xrft/xrft.py#L211

ValueError: Can't take Fourier transform because spacing in coordinate time is zero

I was able to fix this by changing [s] to [ns] on that line but then then the output frequencies are off by a factor of 10^9. This is easy enough to work around, I just wanted to raise the issue. I could attempt a conversion to ns precision elsewhere, but I'm not sure what other code would need to change.

Here is the code that generates the error:

import numpy as np
import xarray as xr
import pandas as pd
import xrft
import matplotlib.pyplot as plt

# Create a time dimension
time = pd.date_range(start='2022-01-01', periods=10000, freq='ms')

# Convert time to seconds since start
time_seconds = (time - time[0]).total_seconds()

# Create a 1 Hz sine wave
freq = 1  # Frequency in Hz
omega = 2 * np.pi * freq  # Angular frequency
data = np.sin(omega * time_seconds)

# Create the DataArray
da = xr.DataArray(data, coords=[time], dims=['time'])

xrft.fft(da, dim=['time'])