Skip to content

Commit 6611d7e

Browse files
authored
Merge pull request #744 from sunpy/rebin
Rough attempt at ignoring units for rebin
2 parents e7d5334 + 4f31352 commit 6611d7e

File tree

3 files changed

+18
-2
lines changed

3 files changed

+18
-2
lines changed

changelog/744.bugfix.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
:meth:`ndcube.NDCube.rebin` ``bin_shape`` argument now accepts a `astropy.units.Quantity` as input if the units are convertible to pixels.

ndcube/ndcube.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1019,11 +1019,12 @@ def rebin(self, bin_shape, operation=np.mean, operation_ignores_mask=False, hand
10191019
10201020
Parameters
10211021
----------
1022-
bin_shape : array-like
1022+
bin_shape : array-like, `astropy.units.Quantity`
10231023
The number of pixels in a bin in each dimension.
10241024
Must be the same length as number of dimensions in data.
10251025
Each element must be in int. If they are not they will be rounded
1026-
to the nearest int.
1026+
to the nearest int. If provided as a `~astropy.units.Quantity` the
1027+
units have to be convertible to pixels.
10271028
operation : function
10281029
Function applied to the data to derive values of the bins.
10291030
Default is `numpy.mean`
@@ -1122,6 +1123,8 @@ def my_propagate(uncertainty, data, mask, **kwargs):
11221123
"""
11231124
# Sanitize input.
11241125
new_unit = new_unit or self.unit
1126+
if isinstance(bin_shape, u.Quantity):
1127+
bin_shape = bin_shape.to_value(u.pixel)
11251128
# Make sure the input bin dimensions are integers.
11261129
bin_shape = np.rint(bin_shape).astype(int)
11271130
if np.all(bin_shape == 1):

ndcube/tests/test_ndcube.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import re
12
from inspect import signature
23
from textwrap import dedent
34

@@ -863,6 +864,17 @@ def test_rebin_dask(ndcube_2d_dask):
863864
assert isinstance(output.mask, dask_type)
864865

865866

867+
def test_rebin_bin_shape_quantity(ndcube_3d_l_ln_lt_ectime):
868+
# Confirm rebin's bin_shape argument handles being a astropy unit
869+
cube = ndcube_3d_l_ln_lt_ectime[:, 1:]
870+
cube._extra_coords = ExtraCoords(cube)
871+
bin_shape = (10, 2, 1) * u.pix
872+
output = cube.rebin(bin_shape)
873+
np.testing.assert_allclose(output.shape, cube.shape / bin_shape.to_value())
874+
with pytest.raises(u.UnitConversionError, match=re.escape("'m' (length) and 'pix' are not convertible")):
875+
cube.rebin((10, 2, 1) * u.m)
876+
877+
866878
def test_rebin_no_ec(ndcube_3d_l_ln_lt_ectime):
867879
# Confirm rebin does not try to handle extra coords when there aren't any.
868880
cube = ndcube_3d_l_ln_lt_ectime[:, 1:]

0 commit comments

Comments
 (0)