Skip to content

Commit

Permalink
BUG: Fix interpolation with mixed types
Browse files Browse the repository at this point in the history
When given a DataArray and a numpy array, neither with units, a Quantity
would be passed into the core calculation, triggering an exception on
`apply_along_axis`. Instead, handle trying to convert and drop units on
a "dimensionless" Quantity, since that's what we get for a DataArray
with no units.
  • Loading branch information
dopplershift committed Jul 5, 2023
1 parent 77447f1 commit 3e018da
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/metpy/interpolate/one_dimension.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,4 +239,6 @@ def _strip_matching_units(*args):
if all(hasattr(arr, 'units') for arr in args):
return [arr.to(args[0].units).magnitude for arr in args]
else:
return args
# Handle the case where we get mixed 'dimensionless' and bare array. This happens e.g.
# when you pass in a DataArray with no units for one arg.
return [arr.m_as('dimensionless') if hasattr(arr, 'units') else arr for arr in args]
10 changes: 10 additions & 0 deletions tests/interpolate/test_one_dimension.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import numpy as np
import pytest
import xarray as xr

from metpy.interpolate import interpolate_1d, interpolate_nans_1d, log_interpolate_1d
from metpy.testing import assert_array_almost_equal
Expand Down Expand Up @@ -49,6 +50,15 @@ def test_log_interpolate_1d():
assert_array_almost_equal(y_interp, y_interp_truth, 7)


def test_log_interpolate_1d_mixed():
x_log = xr.DataArray([1e3, 1e4, 1e5, 1e6])
y_log = np.log(x_log) * 2 + 3
x_interp = np.array([5e3, 5e4, 5e5])
y_interp_truth = np.array([20.0343863828, 24.6395565688, 29.2447267548])
y_interp = log_interpolate_1d(x_interp, x_log, y_log)
assert_array_almost_equal(y_interp, y_interp_truth, 7)


def test_log_interpolate_1d_units():
"""Test interpolating with log x-scale with units."""
x_log = np.array([1e3, 1e4, 1e5, 1e6]) * units.hPa
Expand Down

0 comments on commit 3e018da

Please sign in to comment.