Skip to content

Commit

Permalink
BUG: Fix interpolate_to_slice unit handling (Fixes Unidata#3341)
Browse files Browse the repository at this point in the history
The fixup in Unidata#3255 inadvertently added unit parsing to all code paths in
interpolate_to_slice. This breaks any usages that passed in data with
unknown units. Since interpolate_to_slice has no need to do any unit
handling, avoid this unless we're actually given a quantity.
  • Loading branch information
dopplershift committed Jan 3, 2024
1 parent 2be8428 commit 2a13d51
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
4 changes: 3 additions & 1 deletion src/metpy/interpolate/slices.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import xarray as xr

from ..package_tools import Exporter
from ..units import is_quantity, units
from ..xarray import check_axis

exporter = Exporter(globals())
Expand Down Expand Up @@ -49,14 +50,15 @@ def interpolate_to_slice(data, points, interp_type='linear'):
'your data has been parsed by MetPy with proper x and y '
'dimension coordinates.') from None

need_quantify = is_quantity(data.data)
data = data.metpy.dequantify()
data_sliced = data.interp({
x.name: xr.DataArray(points[:, 0], dims='index', attrs=x.attrs),
y.name: xr.DataArray(points[:, 1], dims='index', attrs=y.attrs)
}, method=interp_type)
data_sliced.coords['index'] = range(len(points))

return data_sliced.metpy.quantify()
return data_sliced.metpy.quantify() if need_quantify else data_sliced


@exporter.export
Expand Down
12 changes: 10 additions & 2 deletions tests/interpolate/test_slices.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,16 +95,24 @@ def test_ds_xy():
return ds.metpy.parse_cf()


def test_interpolate_to_slice_against_selection(test_ds_lonlat):
@pytest.mark.parametrize('bad_units', [False, True])
def test_interpolate_to_slice_against_selection(test_ds_lonlat, bad_units):
"""Test interpolate_to_slice on a simple operation."""
data = test_ds_lonlat['temperature']

# interpolate_to_slice shouldn't care about units
if bad_units:
# Needed so we can go back to using attribute metadata
data = data.metpy.dequantify()
data.attrs['units'] = 'my_bad_units'

path = np.array([[265.0, 30.],
[265.0, 36.],
[265.0, 42.]])
test_slice = interpolate_to_slice(data, path)
true_slice = data.sel({'lat': [30., 36., 42.], 'lon': 265.0})
# Coordinates differ, so just compare the data
assert_array_almost_equal(true_slice.metpy.unit_array, test_slice.metpy.unit_array, 5)
assert_array_almost_equal(true_slice.data, test_slice.data, 5)


@needs_cartopy
Expand Down

0 comments on commit 2a13d51

Please sign in to comment.