When fitting a variable along a temporal dimension, results from computing the fitted "trend" with xr.polyval were very different from the original variable. It seems that the function is not evaluated on the same coordinate the fit was made on.
What did you expect to happen?
The fit should be made on the same coordinate as the evaluation.
Minimal Complete Verifiable Example
import xarray as xr
import numpy as np
import matplotlib.pyplot as plt
da = xr.DataArray(np.arange(100), dims=('time',), coords={'time': xr.date_range('2001-01-01', periods=100, freq='YS')})
fit = da.polyfit('time', deg=3)
val = xr.polyval(da.time, fit.polyfit_coefficients)
print(da[0], val[0])
# 0, 31.00174342
# The data is linear, the fit should be exact.
plt.plot(da.time, da, label='Original')
plt.plot(da.time, val, label='Fit')
MVCE confirmation
[X] Minimal example — the example is as focused as reasonably possible to demonstrate the underlying issue in xarray.
[X] Complete example — the example is self-contained, including all data and the text of any traceback.
[X] Verifiable example — the example copy & pastes into an IPython prompt or Binder notebook, returning the result.
[X] New issue — a search of GitHub Issues suggests this is not a duplicate.
[X] Recent environment — the issue occurs with the latest version of xarray and its dependencies.
The results are similar, however, in polyfit the new x starts at 0, while this offsetting is not done in polyval.
This bug was introduced in #9369 I believe. I added a review there woops :sweat:. Would it be possible to use the same function in both polyfit and polyval ?
I can make a PR. My intuition would be to use xr.core.computation._ensure_numeric in da.polyfit.
What happened?
When fitting a variable along a temporal dimension, results from computing the fitted "trend" with
xr.polyval
were very different from the original variable. It seems that the function is not evaluated on the same coordinate the fit was made on.What did you expect to happen?
The fit should be made on the same coordinate as the evaluation.
Minimal Complete Verifiable Example
MVCE confirmation
Relevant log output
No response
Anything else we need to know?
xr.polyval
transforms the temporal coordinate here : https://github.com/pydata/xarray/blob/dbb98b4a40d1679800f7f85d0dad59ef60b5b790/xarray/core/computation.py#L2070And
da.polyfit
does that here : https://github.com/pydata/xarray/blob/dbb98b4a40d1679800f7f85d0dad59ef60b5b790/xarray/core/dataset.py#L9069-L9077The results are similar, however, in
polyfit
the newx
starts at 0, while this offsetting is not done inpolyval
.This bug was introduced in #9369 I believe. I added a review there woops :sweat:. Would it be possible to use the same function in both
polyfit
andpolyval
?I can make a PR. My intuition would be to use
xr.core.computation._ensure_numeric
inda.polyfit
.Environment