Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 84 additions & 0 deletions autoarray/mask/mask_2d_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -515,6 +515,90 @@ def required_shape_for_kernel(
return new_y, new_x


def trimmed_shape_for_kernel(
mask_2d: np.ndarray,
kernel_shape_native: Tuple[int, int],
buffer: int = 1,
) -> Tuple[int, int]:
"""
Return the smallest shape, centred on the mask's central pixel and of the same parity as the
mask in each dimension, that holds every unmasked pixel at least a kernel half-width plus
`buffer` pixels from the array edge.

This is the frame a masked dataset can be cut down to without changing anything a fit sees:
every unmasked pixel is kept, the blurring region a kernel of this footprint reaches is kept,
and because the parity of each dimension is preserved the central pixel (the origin of the
scaled coordinate system) stays on the same pixel, so scaled coordinates, positions and
priors are unchanged. Cutting an array to this shape with ``resized_array_2d_from`` therefore
only removes masked pixels.

The `buffer` keeps a margin of masked pixels around the blurring region, so the frame is not
cut exactly at the mask plus the half-width; the default of one pixel costs nothing a fit can
measure. Pass ``buffer=0`` for the exact minimum.

The returned shape can be larger than the mask's own in a dimension where unmasked pixels sit
closer to the edge than the kernel half-width plus the buffer; the frame is then padded, as
``required_shape_for_kernel`` would.

For an even dimension the central pixel is the lower of the central pair (the convention of
``resized_array_2d_from``), so one more pixel lies after it than before it.

Parameters
----------
mask_2d
2D boolean array where False is unmasked and True is masked.
kernel_shape_native
(ky, kx) footprint of the convolution kernel.
buffer
Extra masked pixels kept on every side beyond the kernel half-width.

Returns
-------
trimmed_shape
The (ny, nx) centred shape.

Examples
--------
>>> mask = np.full((9, 9), True)
>>> mask[3:6, 3:6] = False
>>> trimmed_shape_for_kernel(mask, kernel_shape_native=(3, 3))
(7, 7)
>>> trimmed_shape_for_kernel(mask, kernel_shape_native=(3, 3), buffer=0)
(5, 5)
"""
mask_2d = np.asarray(mask_2d, dtype=bool)

ky, kx = kernel_shape_native
if ky <= 0 or kx <= 0:
raise ValueError(
f"kernel_shape_native must be positive, got {kernel_shape_native}."
)
if buffer < 0:
raise ValueError(f"buffer must be non-negative, got {buffer}.")

unmasked = np.where(~mask_2d)
if unmasked[0].size == 0:
raise ValueError(
"trimmed_shape_for_kernel requires at least one unmasked pixel."
)

shape = []
for length, indexes, pad in zip(
mask_2d.shape, unmasked, (ky // 2 + buffer, kx // 2 + buffer)
):
centre = (length - 1) // 2
before = max(centre - int(indexes.min()), 0) + pad
after = max(int(indexes.max()) - centre, 0) + pad
if length % 2:
half = max(before, after)
shape.append(2 * half + 1)
else:
half = max(before, after - 1)
shape.append(2 * half + 2)

return tuple(shape)


def blurring_mask_2d_from(
mask_2d: np.ndarray,
kernel_shape_native: Tuple[int, int],
Expand Down
109 changes: 85 additions & 24 deletions autoarray/operators/convolver.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,17 +57,26 @@ class determines how masked real-space data are embedded into a padded array,
equivalent to direct spatial convolution, with no wrap-around artefacts.

``fft_shape``
The FFT-efficient padded shape actually used for computation. Each dimension
of ``full_shape`` is independently rounded up to the next fast length for
real FFTs using ``scipy.fft.next_fast_len``. This shape defines the size of
all arrays sent to and returned from FFT space.
The FFT-efficient shape actually used for computation. Each dimension is the
larger of ``full_shape`` and the frame the unmasked (and blurring) pixels need
(``mask_2d_util.trimmed_shape_for_kernel``: the region plus a kernel half-width
and a one-pixel buffer, centred on the mask's central pixel), rounded up to the
next fast length for real FFTs using ``scipy.fft.next_fast_len``. The frame is
sized from the mask, not the native array, so a small mask on a large stamp
runs its FFTs over the region around the mask rather than the whole stamp. It
is never larger than the frame the native array would be padded to
(``mask_2d_util.required_shape_for_kernel``). This shape defines the size of
all arrays sent to and returned from FFT space; outputs are always returned on
the input mask, so it never changes the shape of any result.

Note that even FFT sizes are currently incremented to odd sizes as a
workaround for kernel-centering issues with even-sized kernels. This is an
implementation detail and should be replaced by correct internal padding
and centering logic.

After determining ``fft_shape``, the input mask is padded accordingly and a
After determining ``fft_shape``, the input mask is resized to it (padded or
cropped about its central pixel, which only removes masked pixels and so leaves
the slim ordering of the unmasked and blurring pixels unchanged) and a
*blurring mask* is derived. The blurring mask identifies pixels that are outside
the original unmasked region but receive non-zero flux due to convolution with
the kernel. These pixels must be retained when mapping results back to the
Expand All @@ -94,7 +103,10 @@ class determines how masked real-space data are embedded into a padded array,
fft_shape
The FFT-friendly padded shape used for all Fourier transforms.
mask
The input mask padded to ``fft_shape``, with masked pixels set to True.
The input mask resized (padded or cropped, centred) to ``fft_shape``, with
masked pixels set to True.
source_mask
The input mask, unchanged; used to check whether the state can be reused.
blurring_mask
A derived mask identifying pixels that are masked in the original input
but receive flux due to convolution with the kernel.
Expand All @@ -113,7 +125,7 @@ class determines how masked real-space data are embedded into a padded array,
y_min, y_max = ys.min(), ys.max()
x_min, x_max = xs.min(), xs.max()

(pad_y, pad_x) = self.kernel.shape_native
pad_y, pad_x = self.kernel.shape_native

mask_shape = (
(y_max + pad_y // 2) - (y_min - pad_y // 2),
Expand All @@ -124,34 +136,50 @@ class determines how masked real-space data are embedded into a padded array,
s1 + s2 - 1 for s1, s2 in zip(mask_shape, self.kernel.shape_native)
)
import scipy.fft
from autoarray.mask.mask_2d_util import required_shape_for_kernel
from autoarray.mask.mask_2d_util import (
required_shape_for_kernel,
trimmed_shape_for_kernel,
)

if blurring_mask is None:
min_blur_shape = required_shape_for_kernel(mask, self.kernel.shape_native)
frame_mask = np.array(mask)
else:
# The explicit blurring region can extend further than the kernel's own
# reach (its footprint is defined at image resolution and upscaled), so
# the FFT frame must be sized to keep every blurring pixel after resizing.
combined_mask = np.array(mask) & np.array(blurring_mask)
min_blur_shape = required_shape_for_kernel(
combined_mask, self.kernel.shape_native
)

fft_shape = tuple(
scipy.fft.next_fast_len(max(s, r), real=True)
for s, r in zip(full_shape, min_blur_shape)
frame_mask = np.array(mask) & np.array(blurring_mask)

# The frame the native array would be padded to (never smaller than the native
# array), and the frame trimmed to the unmasked (and blurring) region plus a
# kernel half-width and a one-pixel buffer. A small mask on a large stamp only
# needs the trimmed frame, so the FFT runs over it rather than the whole stamp;
# it is capped at the padded frame so it is never larger than before.
padded_shape = required_shape_for_kernel(frame_mask, self.kernel.shape_native)
trimmed_shape = trimmed_shape_for_kernel(
frame_mask, self.kernel.shape_native, buffer=1
)
min_frame_shape = tuple(min(t, p) for t, p in zip(trimmed_shape, padded_shape))

self.fft_shape = fft_shape
self.source_mask = mask
self.mask = mask.resized_from(self.fft_shape, pad_value=1)

if blurring_mask is None:
self.blurring_mask = self.mask.derive_mask.blurring_from(
kernel_shape_native=self.kernel.shape_native
# Cropping is centred, so it only removes masked rows and columns and the
# row-major slim ordering of the unmasked and blurring pixels is unchanged. If
# the crop ever lost one of those pixels, fall back to the padded frame.
for frame_shape in (min_frame_shape, padded_shape):
fft_shape = tuple(
scipy.fft.next_fast_len(max(s, r), real=True)
for s, r in zip(full_shape, frame_shape)
)
else:
self.blurring_mask = blurring_mask.resized_from(self.fft_shape, pad_value=1)
resized = self._resized_masks_from(
mask=mask,
blurring_mask=blurring_mask,
fft_shape=fft_shape,
)
if resized is not None:
break

self.fft_shape = fft_shape
self.mask, self.blurring_mask = resized

# Set by Convolver.state_from when convolve_over_sample_size > 1: the
# permutations from per-pixel sub-block ordering to the fine mask's
Expand All @@ -170,6 +198,39 @@ class determines how masked real-space data are embedded into a padded array,
# complex64 kernel — see that method's body for why.
self.fft_kernel_c64 = self.fft_kernel.astype(np.complex64)

def _resized_masks_from(self, mask, blurring_mask, fft_shape):
"""
The mask and blurring mask resized (padded or cropped, centred) to ``fft_shape``,
or ``None`` if resizing would lose an unmasked or blurring pixel.
"""
from autoarray.mask.mask_2d_util import min_false_distance_to_edge

resized_mask = mask.resized_from(fft_shape, pad_value=1)

if np.sum(~np.array(resized_mask)) != np.sum(~np.array(mask)):
return None

if blurring_mask is not None:
resized_blurring_mask = blurring_mask.resized_from(fft_shape, pad_value=1)

if np.sum(~np.array(resized_blurring_mask)) != np.sum(
~np.array(blurring_mask)
):
return None

return resized_mask, resized_blurring_mask

# A blurring mask derived on the frame is complete only when every unmasked
# pixel sits at least a kernel half-width from the frame edge.
distance = min_false_distance_to_edge(np.array(resized_mask))

if any(d < k // 2 for d, k in zip(distance, self.kernel.shape_native)):
return None

return resized_mask, resized_mask.derive_mask.blurring_from(
kernel_shape_native=self.kernel.shape_native
)

def is_for_mask(self, mask) -> bool:
"""
Whether this state was built from the input mask, and can therefore be reused
Expand Down
99 changes: 99 additions & 0 deletions test_autoarray/mask/test_mask_2d_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -1127,3 +1127,102 @@ def test__buffed_mask_2d_from():
]
)
).all()


def test__trimmed_shape_for_kernel__centred_square_region__shape_is_region_plus_half_kernel_plus_buffer():
mask = np.full((9, 9), True)
mask[3:6, 3:6] = False

# 3x3 region + half-kernel on each side + the default one-pixel buffer on each side.
assert util.mask_2d.trimmed_shape_for_kernel(mask, kernel_shape_native=(3, 3)) == (
7,
7,
)
assert util.mask_2d.trimmed_shape_for_kernel(mask, kernel_shape_native=(1, 1)) == (
5,
5,
)
assert util.mask_2d.trimmed_shape_for_kernel(mask, kernel_shape_native=(5, 3)) == (
9,
7,
)

# buffer=0 is the exact minimum: region + half-kernel.
assert util.mask_2d.trimmed_shape_for_kernel(
mask, kernel_shape_native=(3, 3), buffer=0
) == (5, 5)
assert util.mask_2d.trimmed_shape_for_kernel(
mask, kernel_shape_native=(1, 1), buffer=0
) == (3, 3)
assert util.mask_2d.trimmed_shape_for_kernel(
mask, kernel_shape_native=(3, 3), buffer=2
) == (9, 9)


def test__trimmed_shape_for_kernel__parity_preserved_and_centre_kept():
# Even frame: the central pixel is the lower of the central pair (3 of 0..7), and the
# unmasked 2x2 block sits on pixels 3 and 4, so it is symmetric about the pixel boundary.
mask = np.full((8, 8), True)
mask[3:5, 3:5] = False

shape = util.mask_2d.trimmed_shape_for_kernel(mask, kernel_shape_native=(3, 3))

# 2 unmasked + 1 half-kernel + 1 buffer on each side.
assert shape == (6, 6)

# Cutting to that shape about the centre keeps every unmasked pixel a half-width plus the
# buffer from the edge.
trimmed = util.array_2d.resized_array_2d_from(
array_2d=mask.astype(float), resized_shape=shape, pad_value=1.0
).astype(bool)
assert trimmed.sum() == mask.sum() - (64 - 36)
assert util.mask_2d.min_false_distance_to_edge(trimmed) == (2, 2)

assert util.mask_2d.trimmed_shape_for_kernel(
mask, kernel_shape_native=(3, 3), buffer=0
) == (4, 4)

# Odd frame, region offset from the centre: the frame grows symmetrically so the
# central pixel stays put, rather than re-centring on the region.
mask = np.full((9, 9), True)
mask[1:3, 5:8] = False

shape = util.mask_2d.trimmed_shape_for_kernel(mask, kernel_shape_native=(3, 3))

assert shape == (11, 11)
assert shape[0] % 2 == 1 and shape[1] % 2 == 1
assert util.mask_2d.trimmed_shape_for_kernel(
mask, kernel_shape_native=(3, 3), buffer=0
) == (9, 9)


def test__trimmed_shape_for_kernel__region_at_edge__frame_pads_rather_than_cuts():
mask = np.full((5, 5), True)
mask[0, 2] = False

shape = util.mask_2d.trimmed_shape_for_kernel(mask, kernel_shape_native=(5, 5))

# The pixel at row 0 needs two rows above it plus the buffer: 2 before the centre + 2 pad
# + 1 buffer, so 11 rows; the columns need the half-width plus buffer, 7.
assert shape == (11, 7)
assert util.mask_2d.trimmed_shape_for_kernel(
mask, kernel_shape_native=(5, 5), buffer=0
) == (9, 5)


def test__trimmed_shape_for_kernel__invalid_inputs_raise():
mask = np.full((5, 5), True)
mask[2, 2] = False

with pytest.raises(ValueError):
util.mask_2d.trimmed_shape_for_kernel(mask, kernel_shape_native=(0, 3))

with pytest.raises(ValueError):
util.mask_2d.trimmed_shape_for_kernel(
mask, kernel_shape_native=(3, 3), buffer=-1
)

with pytest.raises(ValueError):
util.mask_2d.trimmed_shape_for_kernel(
np.full((5, 5), True), kernel_shape_native=(3, 3)
)
Loading
Loading