Skip to content

Commit

Permalink
Merge pull request #278 from larrybradley/mask-fix
Browse files Browse the repository at this point in the history
Fix corner-case issue in RegionMask.multiply()
  • Loading branch information
larrybradley committed Jun 12, 2019
2 parents ed6f495 + 76b365e commit e6a567c
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 3 deletions.
7 changes: 7 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,13 @@ New Features
- Added ``union`` and ``intersection`` methods to the ``BoundingBox``
class. [#277]

Bug Fixes
---------

- Fixed a corner-case issue where ``RegionMask.multiply()`` would not set
non-finite data values outside of the mask but within the bounding box
to zero. [#278]


0.3 (2018-09-09)
================
Expand Down
13 changes: 10 additions & 3 deletions regions/core/mask.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ def __init__(self, data, bbox):
raise ValueError('data and bounding box must have the same '
'shape.')
self.bbox = bbox
self._mask = (self.data == 0)

def __array__(self):
"""
Expand Down Expand Up @@ -158,8 +159,8 @@ def cutout(self, data, fill_value=0., copy=False):
A 2D array on which to apply the region mask.
fill_value : float, optional
The value is used to fill pixels where the region mask
does not overlap with the input ``data``. The default is 0.
The value used to fill pixels where the region mask does not
overlap with the input ``data``. The default is 0.
copy : bool, optional
If `True` then the returned cutout array will always be hold
Expand Down Expand Up @@ -245,4 +246,10 @@ def multiply(self, data, fill_value=0.):
if cutout is None:
return None
else:
return cutout * self.data
weighted_cutout = cutout * self.data

# needed to zero out non-finite data values outside of the
# mask but within the bounding box
weighted_cutout[self._mask] = 0.0

return weighted_cutout
24 changes: 24 additions & 0 deletions regions/core/tests/test_mask.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,3 +90,27 @@ def test_mask_cutout_partial_overlap(position):

image = mask.to_image(data.shape)
assert image.shape == data.shape


def test_mask_nan_in_bbox():
"""
Regression test that non-finite data values outside of the mask but
within the bounding box are set to zero.
"""

data = np.ones((101, 101))
data[33, 33] = np.nan
data[67, 67] = np.inf
data[33, 67] = -np.inf
data[22, 22] = np.nan
data[22, 23] = np.inf

radius = 20.
reg1 = CirclePixelRegion(PixCoord(50, 50), radius)
reg2 = CirclePixelRegion(PixCoord(5, 5), radius)

wdata1 = reg1.to_mask(mode='exact').multiply(data)
assert_allclose(np.sum(wdata1), np.pi * radius**2)

wdata2 = reg2.to_mask(mode='exact').multiply(data)
assert_allclose(np.sum(wdata2), 561.6040111923013)

0 comments on commit e6a567c

Please sign in to comment.