From 2a13d511b0ba8f8e77da797e7cc8a2b92f84c6c5 Mon Sep 17 00:00:00 2001 From: Ryan May Date: Wed, 3 Jan 2024 16:17:09 -0700 Subject: [PATCH] BUG: Fix interpolate_to_slice unit handling (Fixes #3341) The fixup in #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. --- src/metpy/interpolate/slices.py | 4 +++- tests/interpolate/test_slices.py | 12 ++++++++++-- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/metpy/interpolate/slices.py b/src/metpy/interpolate/slices.py index b11199565e7..1dd0a6c8ea8 100644 --- a/src/metpy/interpolate/slices.py +++ b/src/metpy/interpolate/slices.py @@ -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()) @@ -49,6 +50,7 @@ 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), @@ -56,7 +58,7 @@ def interpolate_to_slice(data, points, interp_type='linear'): }, 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 diff --git a/tests/interpolate/test_slices.py b/tests/interpolate/test_slices.py index 41eb6dc01fb..5407857c0bc 100644 --- a/tests/interpolate/test_slices.py +++ b/tests/interpolate/test_slices.py @@ -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