Skip to content

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

@aspitarl

Description

@aspitarl

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions