Skip to content

Commit

Permalink
Fixed a problem with diff'ing masked_arrays with units.
Browse files Browse the repository at this point in the history
The issue occurs only, when "x" in first_derivative is a masked array
with units. As all arrays stemming from NetCDF access are basically
masked arrays, we do not have non-masked arrays in our code, even though
the mask is almost always 'False'.

I added a test case demonstrating the problem, it fails without the
contained fix.

See issue Unidata#983
  • Loading branch information
joernu76 committed Mar 31, 2020
1 parent dfd97bb commit 503d45f
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/metpy/units.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ def diff(x, **kwargs):
# Can't just use units because of how things like temperature work
it = x.flat
true_units = (next(it) - next(it)).units
return ret * true_units
return true_units * ret
else:
return np.diff(x, **kwargs)

Expand Down
14 changes: 14 additions & 0 deletions tests/calc/test_calc_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -560,6 +560,20 @@ def test_first_derivative_masked():
assert_array_equal(df_dx.mask, truth.mask)


def test_first_derivative_masked_units():
"""Test that first_derivative properly propagates masks with units."""
data = units('K') * np.ma.arange(7)
data[3] = np.ma.masked
x = units('m') * np.ma.arange(7)
df_dx = first_derivative(data, x=x)

truth = units('K / m') * np.ma.array(
[1., 1., 1., 1., 1., 1., 1.],
mask=[False, False, True, True, True, False, False])
assert_array_almost_equal(df_dx, truth)
assert_array_equal(df_dx.mask, truth.mask)


def test_second_derivative(deriv_1d_data):
"""Test second_derivative with a simple 1D array."""
d2v_dx2 = second_derivative(deriv_1d_data.values, x=deriv_1d_data.x)
Expand Down

0 comments on commit 503d45f

Please sign in to comment.