Skip to content

Commit a0e2314

Browse files
committed
Implement linear interpolation
The tests cover: 1. index is halfway between coordinates 2. index is the same as old coordinates 3. ND index
1 parent 992ac21 commit a0e2314

File tree

1 file changed

+19
-14
lines changed

1 file changed

+19
-14
lines changed

xarray/tests/test_interp.py

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -669,13 +669,13 @@ def interp_1d(data, dim, vals):
669669

670670
old_coord = data[dim]
671671

672-
lower = data.sel(**selectors, method='ffill').drop(dim)
673-
upper = data.sel(**selectors, method='bfill').drop(dim)
674-
lower_x = data[dim].sel(**selectors, method='ffill').drop(dim)
675-
upper_x = data[dim].sel(**selectors, method='bfill').drop(dim)
676-
677-
new_x = lower[dim]
678-
weight = np.abs(new_x - lower_x)/np.abs(upper_x-lower_x)
672+
lower = data.sel(**selectors, method='ffill')
673+
upper = data.sel(**selectors, method='bfill')
674+
lower_x = data[dim].sel(**selectors, method='ffill')
675+
upper_x = data[dim].sel(**selectors, method='bfill')
676+
weight = np.abs(vals - lower_x)/np.abs(upper_x-lower_x)
677+
# needed if upper and lower coordinates are identical
678+
weight = weight.fillna(1.0)
679679
ans = lower * (1-weight) + upper * weight
680680
return ans
681681

@@ -686,29 +686,34 @@ def interp_1d(data, dim, vals):
686686
def test_new_interp(dim):
687687

688688
data = xr.DataArray(np.arange(10), dims=[dim]).assign_coords({dim: np.arange(10)})
689-
new_x = np.arange(9) + .5
689+
new_x = xr.DataArray(np.arange(9) + .5, dims=['xp'])
690690
ans = interp_1d(data, dim, new_x)
691691
np.testing.assert_allclose(new_x, ans.values)
692692

693693

694694
def test_interp_1d_nd_targ():
695-
696695
data = xr.DataArray(np.arange(10), dims=['x'], coords={'x': np.arange(10)})
697-
new_x_2d = xr.DataArray(np.tile(np.r_[:10], (3, 1)), dims=['y', 'x'])
696+
new_x_2d = xr.DataArray(np.tile(np.r_[:9] + .5, (3, 1)), dims=['y', 'xp'])
698697
ans = interp_1d(data, 'x', new_x_2d)
699698
np.testing.assert_allclose(new_x_2d, ans.values)
700699

701700

701+
def test_interp_1d_nd_targ():
702+
# interp with actual coords should be an isel.
703+
data = xr.DataArray(np.arange(10), dims=['x'], coords={'x': np.arange(10)})
704+
new_x_2d = xr.DataArray(np.tile(np.r_[:9], (3, 1)), dims=['y', 'xp'])
705+
ans = interp_1d(data, 'x', new_x_2d)
706+
np.testing.assert_allclose(new_x_2d, ans.values)
707+
702708
def test_sel_nd():
703709
npdata = np.tile(np.arange(10), (5, 1))
704710
data = xr.DataArray(npdata, dims=['y', 'x'],
705711
coords={'x': np.r_[:10], 'y': np.r_[:5]})
706-
idx = xr.DataArray(npdata, dims=['z', 'x'])
712+
idx = xr.DataArray(npdata, dims=['z', 'xp'])
707713

708-
ans = data.sel(x=idx, method='bfill')
709-
assert set(ans.dims) == {'z', 'y', 'x'}
714+
ans = data.sel(x=idx)
715+
assert set(ans.dims) == {'z', 'y', 'xp'}
710716
print(ans)
711717

712718

713719

714-

0 commit comments

Comments
 (0)