diff --git a/changelog/685.feature.rst b/changelog/685.feature.rst new file mode 100644 index 000000000..f829a574b --- /dev/null +++ b/changelog/685.feature.rst @@ -0,0 +1 @@ +Enable rtruediv on`~ndcube.NDCube` such that a user can now do 1/`~ndcube.NDCube`. diff --git a/ndcube/ndcube.py b/ndcube/ndcube.py index 93bdf5659..ee730dff5 100644 --- a/ndcube/ndcube.py +++ b/ndcube/ndcube.py @@ -948,6 +948,9 @@ def __rmul__(self, value): def __truediv__(self, value): return self.__mul__(1/value) + def __rtruediv__(self, value): + return self.__pow__(-1).__mul__(value) + def __pow__(self, value): new_data = self.data ** value new_unit = self.unit if self.unit is None else self.unit ** value diff --git a/ndcube/tests/test_ndcube.py b/ndcube/tests/test_ndcube.py index eb08bd07c..dff3761ec 100644 --- a/ndcube/tests/test_ndcube.py +++ b/ndcube/tests/test_ndcube.py @@ -1101,6 +1101,20 @@ def test_cube_arithmetic_divide(ndcube_2d_ln_lt_units, value): new_cube = ndcube_2d_ln_lt_units / value check_arithmetic_value_and_units(new_cube, cube_quantity / value) +@pytest.mark.parametrize('value', [1, 2, -1]) +def test_cube_arithmetic_rdivide(ndcube_2d_ln_lt_units, value): + cube_quantity = u.Quantity(ndcube_2d_ln_lt_units.data, ndcube_2d_ln_lt_units.unit) + with np.errstate(divide='ignore'): + new_cube = value / ndcube_2d_ln_lt_units + check_arithmetic_value_and_units(new_cube, value / cube_quantity) + +@pytest.mark.parametrize('value', [1, 2, -1]) +def test_cube_arithmetic_rdivide_uncertainty(ndcube_4d_unit_uncertainty, value): + cube_quantity = u.Quantity(ndcube_4d_unit_uncertainty.data, ndcube_4d_unit_uncertainty.unit) + with pytest.warns(UserWarning, match="UnknownUncertainty does not support uncertainty propagation with correlation. Setting uncertainties to None."): + with np.errstate(divide='ignore'): + new_cube = value / ndcube_4d_unit_uncertainty + check_arithmetic_value_and_units(new_cube, value / cube_quantity) def test_cube_arithmetic_neg(ndcube_2d_ln_lt_units): check_arithmetic_value_and_units(