Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
aspitarl opened this issue May 3, 2024 · 0 comments

Comments

@aspitarl
Copy link
Contributor

aspitarl commented May 3, 2024

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:

return np.diff(coord).astype("timedelta64[s]").astype("f8")

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'])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant