From 86befdbfa1624fbaabffdd29cda09c8475612d38 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Tue, 17 Nov 2026 14:12:28 +0000 Subject: [PATCH 1/3] mask_2d_util: add trimmed_shape_for_kernel The smallest centred, parity-preserving shape that holds every unmasked pixel a kernel half-width plus a buffer from the edge. Taken from PyAutoArray#675 (commits a7f9fbc7..bbd126ce) with its unit tests; the Imaging.apply_mask and dataset:trim_to_mask changes from that PR are not brought over. Co-authored-by: samlange04 <80762641+samlange04@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- autoarray/mask/mask_2d_util.py | 84 ++++++++++++++++++++ test_autoarray/mask/test_mask_2d_util.py | 99 ++++++++++++++++++++++++ 2 files changed, 183 insertions(+) diff --git a/autoarray/mask/mask_2d_util.py b/autoarray/mask/mask_2d_util.py index 2151ae942..c7d2f3cbb 100644 --- a/autoarray/mask/mask_2d_util.py +++ b/autoarray/mask/mask_2d_util.py @@ -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], diff --git a/test_autoarray/mask/test_mask_2d_util.py b/test_autoarray/mask/test_mask_2d_util.py index 7965df89a..a6dd767ec 100644 --- a/test_autoarray/mask/test_mask_2d_util.py +++ b/test_autoarray/mask/test_mask_2d_util.py @@ -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) + ) From e5068e586c304a43b6d9fd3f837374fe07fa2f48 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Tue, 17 Nov 2026 14:16:25 +0000 Subject: [PATCH 2/3] ConvolverState: size the FFT frame from the mask, not the native array The frame was padded up from the native array, so a small mask on a large stamp ran its FFTs over the whole stamp. It is now the larger of full_shape and trimmed_shape_for_kernel (the unmasked and blurring region plus a kernel half-width and a one-pixel buffer), capped at the frame the native array would be padded to, so it is never larger than before. The internal mask and blurring mask are cropped to it about their central pixel, which only removes masked pixels and keeps the slim ordering; if a crop ever lost a pixel the state falls back to the padded frame. Outputs stay on the caller's mask, so dataset shapes, fit images, image meshes and results are unchanged. Tests: a small mask on a large stamp convolves (image and mapping matrix; numpy, JAX FFT and JAX real space; odd, even and mixed-parity frames; over sampled) identically to the same mask on a tight stamp and to the old frame, and the frame shrinks and never grows. Co-authored-by: samlange04 <80762641+samlange04@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- autoarray/operators/convolver.py | 109 ++++++-- test_autoarray/operators/test_convolver.py | 290 +++++++++++++++++++++ 2 files changed, 375 insertions(+), 24 deletions(-) diff --git a/autoarray/operators/convolver.py b/autoarray/operators/convolver.py index 7611a72fc..07cfb6bdc 100644 --- a/autoarray/operators/convolver.py +++ b/autoarray/operators/convolver.py @@ -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 @@ -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. @@ -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), @@ -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 @@ -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 diff --git a/test_autoarray/operators/test_convolver.py b/test_autoarray/operators/test_convolver.py index f0011323e..b095fd331 100644 --- a/test_autoarray/operators/test_convolver.py +++ b/test_autoarray/operators/test_convolver.py @@ -811,3 +811,293 @@ def test__convolved_mapping_matrix_from__mixed_precision__jax_fft_matches_numpy_ assert blurred.dtype == jnp.float64 assert np.asarray(blurred) == pytest.approx(reference, abs=1.0e-5) + + +# --------------------------------------------------------------------------------------- +# The ConvolverState FFT frame is sized from the mask, not the native array: a small mask +# on a large stamp convolves exactly as the same mask on a tight stamp. +# --------------------------------------------------------------------------------------- + + +def _frame_pattern(): + # An irregular unmasked region (False), so slim-ordering errors cannot cancel. + pattern = ~aa.Mask2D.circular( + shape_native=(9, 9), pixel_scales=1.0, radius=3.6 + ).array + pattern[4, 0] = False + pattern[0, 3] = True + return ~pattern + + +def _mask_on_stamp(pattern, shape, offset=None): + stamp = np.full(shape, True) + if offset is None: + offset = ( + (shape[0] - pattern.shape[0]) // 2, + (shape[1] - pattern.shape[1]) // 2, + ) + stamp[ + offset[0] : offset[0] + pattern.shape[0], + offset[1] : offset[1] + pattern.shape[1], + ] = pattern + return aa.Mask2D(mask=stamp, pixel_scales=1.0) + + +def _old_frame_state(monkeypatch, kernel, mask): + """ + The state the native-array-sized frame gives (the behaviour before the frame was + sized from the mask): a trimmed shape larger than any padded one makes the cap pick + the padded shape. + """ + from autoarray.mask import mask_2d_util + + with monkeypatch.context() as m: + m.setattr( + mask_2d_util, + "trimmed_shape_for_kernel", + lambda mask_2d, kernel_shape_native, buffer=1: (10**6, 10**6), + ) + return ConvolverState(kernel=kernel, mask=mask) + + +_FRAME_KERNELS = [(5, 5), (7, 5), (3, 7)] +_FRAME_STAMPS = [(41, 41), (40, 40), (41, 38), (60, 23)] + + +@pytest.mark.parametrize("kernel_shape", _FRAME_KERNELS) +@pytest.mark.parametrize("stamp_shape", _FRAME_STAMPS) +def test__convolver_state__fft_frame_sized_from_mask__shrinks_never_grows( + monkeypatch, kernel_shape, stamp_shape +): + pattern = _frame_pattern() + kernel = aa.Array2D.no_mask( + values=np.random.default_rng(0).random(kernel_shape), pixel_scales=1.0 + ) + + mask = _mask_on_stamp(pattern, stamp_shape) + + state = ConvolverState(kernel=kernel, mask=mask) + old_state = _old_frame_state(monkeypatch, kernel, mask) + + assert all(n <= o for n, o in zip(state.fft_shape, old_state.fft_shape)) + # The 9x9 region plus a 7-pixel kernel needs well under a 38-pixel frame. + assert all(n < s for n, s in zip(state.fft_shape, stamp_shape)) + + # Every unmasked and blurring pixel is kept, in the same slim order. + assert state.mask.pixels_in_mask == mask.pixels_in_mask + assert state.blurring_mask.pixels_in_mask == old_state.blurring_mask.pixels_in_mask + assert state.source_mask is mask + assert state.is_for_mask(mask) + + def offsets(m): + rows, cols = np.where(~np.array(m)) + return rows - rows[0], cols - cols[0] + + for new, old in [ + (state.mask, old_state.mask), + (state.blurring_mask, old_state.blurring_mask), + ]: + assert np.array_equal(offsets(new)[0], offsets(old)[0]) + assert np.array_equal(offsets(new)[1], offsets(old)[1]) + + +def test__convolver_state__mask_near_edge__frame_still_pads_as_before(monkeypatch): + mask = aa.Mask2D.circular(shape_native=(11, 11), pixel_scales=1.0, radius=5.0) + kernel = aa.Array2D.no_mask( + values=np.random.default_rng(0).random((7, 7)), pixel_scales=1.0 + ) + + state = ConvolverState(kernel=kernel, mask=mask) + old_state = _old_frame_state(monkeypatch, kernel, mask) + + assert state.fft_shape == old_state.fft_shape + + +def test__convolver_state__crop_that_would_lose_pixels__falls_back_to_padded_frame( + monkeypatch, +): + from autoarray.mask import mask_2d_util + + # The region sits in a corner of the stamp, so a centred crop to a tiny frame would + # cut it; the state must fall back to the padded frame rather than lose pixels. + mask = _mask_on_stamp(_frame_pattern(), (41, 41), offset=(1, 2)) + kernel = aa.Array2D.no_mask( + values=np.random.default_rng(0).random((5, 5)), pixel_scales=1.0 + ) + + old_state = _old_frame_state(monkeypatch, kernel, mask) + + monkeypatch.setattr( + mask_2d_util, + "trimmed_shape_for_kernel", + lambda mask_2d, kernel_shape_native, buffer=1: (1, 1), + ) + state = ConvolverState(kernel=kernel, mask=mask) + + assert state.fft_shape == old_state.fft_shape + assert state.mask.pixels_in_mask == mask.pixels_in_mask + + +def _frame_scene(stamp_shape, kernel_shape, n_columns=3): + pattern = _frame_pattern() + kernel = aa.Array2D.no_mask( + values=np.random.default_rng(1).random(kernel_shape), pixel_scales=1.0 + ) + mask = _mask_on_stamp(pattern, stamp_shape) + blurring_mask = mask.derive_mask.blurring_from(kernel_shape_native=kernel_shape) + + rng = np.random.default_rng(2) + image = rng.random(mask.pixels_in_mask) + blurring_image = rng.random(blurring_mask.pixels_in_mask) + mapping_matrix = rng.random((mask.pixels_in_mask, n_columns)) + blurring_mapping_matrix = rng.random((blurring_mask.pixels_in_mask, n_columns)) + + return ( + kernel, + mask, + blurring_mask, + image, + blurring_image, + mapping_matrix, + blurring_mapping_matrix, + ) + + +def _convolve_scene(scene, mode): + import jax.numpy as jnp + + ( + kernel, + mask, + blurring_mask, + image, + blurring_image, + mapping_matrix, + blurring_mapping_matrix, + ) = scene + + xp = np if mode == "numpy" else jnp + convolver = aa.Convolver(kernel=kernel, use_fft=mode == "jax_fft") + + convolved_image = convolver.convolved_image_from( + image=aa.Array2D(values=image, mask=mask), + blurring_image=aa.Array2D(values=blurring_image, mask=blurring_mask), + xp=xp, + ) + convolved_mapping_matrix = convolver.convolved_mapping_matrix_from( + mapping_matrix=mapping_matrix, + mask=mask, + blurring_mapping_matrix=blurring_mapping_matrix, + blurring_mask=blurring_mask, + xp=xp, + ) + + assert convolved_image.mask is mask + + return np.array(convolved_image.array), np.array(convolved_mapping_matrix) + + +@pytest.mark.parametrize("mode", ["numpy", "jax_fft", "jax_real_space"]) +@pytest.mark.parametrize("kernel_shape", [(5, 5), (7, 5)]) +@pytest.mark.parametrize( + "large_stamp, tight_stamp", + [((41, 41), (15, 15)), ((40, 40), (16, 16)), ((41, 38), (16, 15))], +) +def test__convolved_image_and_mapping_matrix__large_stamp_equals_tight_stamp( + monkeypatch, mode, kernel_shape, large_stamp, tight_stamp +): + large = _frame_scene(large_stamp, kernel_shape) + tight = _frame_scene(tight_stamp, kernel_shape) + + # The two stamps share one unmasked region and blurring region, in one slim order. + assert large[1].pixels_in_mask == tight[1].pixels_in_mask + assert large[2].pixels_in_mask == tight[2].pixels_in_mask + + image_large, mapping_large = _convolve_scene(large, mode) + image_tight, mapping_tight = _convolve_scene(tight, mode) + + assert image_large == pytest.approx(image_tight, abs=1.0e-10) + assert mapping_large == pytest.approx(mapping_tight, abs=1.0e-10) + + # And both equal the native-array-sized frame used before. + from autoarray.mask import mask_2d_util + + monkeypatch.setattr( + mask_2d_util, + "trimmed_shape_for_kernel", + lambda mask_2d, kernel_shape_native, buffer=1: (10**6, 10**6), + ) + image_old, mapping_old = _convolve_scene(large, mode) + + assert image_large == pytest.approx(image_old, abs=1.0e-10) + assert mapping_large == pytest.approx(mapping_old, abs=1.0e-10) + + +@pytest.mark.parametrize("use_jax", [False, True]) +@pytest.mark.parametrize( + "large_stamp, tight_stamp", [((41, 41), (13, 13)), ((40, 38), (14, 13))] +) +def test__convolve_over_sample_size__large_stamp_equals_tight_stamp( + monkeypatch, use_jax, large_stamp, tight_stamp +): + import jax.numpy as jnp + + s = 2 + xp = jnp if use_jax else np + fine_kernel = aa.Array2D.no_mask( + values=np.random.default_rng(4).random((9, 7)), pixel_scales=1.0 / s + ) + + def convolve(stamp_shape): + mask = _mask_on_stamp(_frame_pattern(), stamp_shape) + convolver = aa.Convolver(kernel=fine_kernel, convolve_over_sample_size=s) + blurring_mask = mask.derive_mask.blurring_from( + kernel_shape_native=convolver.kernel_shape_image_resolution, + allow_padding=True, + ) + + rng = np.random.default_rng(5) + image = rng.random(mask.pixels_in_mask * s**2) + blurring_image = rng.random(blurring_mask.pixels_in_mask * s**2) + mapping_matrix = rng.random((mask.pixels_in_mask * s**2, 2)) + blurring_mapping_matrix = rng.random((blurring_mask.pixels_in_mask * s**2, 2)) + + convolved_image = convolver.convolved_image_from( + image=image, blurring_image=blurring_image, mask=mask, xp=xp + ) + convolved_mapping_matrix = convolver.convolved_mapping_matrix_from( + mapping_matrix=mapping_matrix, + mask=mask, + blurring_mapping_matrix=blurring_mapping_matrix, + xp=xp, + ) + state = convolver.state_from(mask=mask) + + return ( + np.array(convolved_image.array), + np.array(convolved_mapping_matrix), + state.fft_shape, + blurring_mask.pixels_in_mask, + ) + + image_large, mapping_large, fft_large, n_blur_large = convolve(large_stamp) + image_tight, mapping_tight, _, n_blur_tight = convolve(tight_stamp) + + assert n_blur_large == n_blur_tight + assert all(n < 2 * l for n, l in zip(fft_large, large_stamp)) + + assert image_large == pytest.approx(image_tight, abs=1.0e-10) + assert mapping_large == pytest.approx(mapping_tight, abs=1.0e-10) + + from autoarray.mask import mask_2d_util + + monkeypatch.setattr( + mask_2d_util, + "trimmed_shape_for_kernel", + lambda mask_2d, kernel_shape_native, buffer=1: (10**6, 10**6), + ) + image_old, mapping_old, fft_old, _ = convolve(large_stamp) + + assert all(n <= o for n, o in zip(fft_large, fft_old)) + assert image_large == pytest.approx(image_old, abs=1.0e-10) + assert mapping_large == pytest.approx(mapping_old, abs=1.0e-10) From 88b391d0c1a1a3c80ede64b49e866eaea841338c Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Tue, 17 Nov 2026 15:13:34 +0000 Subject: [PATCH 3/3] test: skip the jax modes of the frame-equality tests when jax is absent The unittest-nojax leg failed with ModuleNotFoundError: the new tests imported jax.numpy unconditionally. The numpy modes still run there; the jax modes skip. Co-Authored-By: Claude Opus 5.5 --- test_autoarray/operators/test_convolver.py | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/test_autoarray/operators/test_convolver.py b/test_autoarray/operators/test_convolver.py index b095fd331..5fca022d1 100644 --- a/test_autoarray/operators/test_convolver.py +++ b/test_autoarray/operators/test_convolver.py @@ -964,8 +964,6 @@ def _frame_scene(stamp_shape, kernel_shape, n_columns=3): def _convolve_scene(scene, mode): - import jax.numpy as jnp - ( kernel, mask, @@ -976,7 +974,7 @@ def _convolve_scene(scene, mode): blurring_mapping_matrix, ) = scene - xp = np if mode == "numpy" else jnp + xp = np if mode == "numpy" else pytest.importorskip("jax.numpy") convolver = aa.Convolver(kernel=kernel, use_fft=mode == "jax_fft") convolved_image = convolver.convolved_image_from( @@ -1040,10 +1038,8 @@ def test__convolved_image_and_mapping_matrix__large_stamp_equals_tight_stamp( def test__convolve_over_sample_size__large_stamp_equals_tight_stamp( monkeypatch, use_jax, large_stamp, tight_stamp ): - import jax.numpy as jnp - s = 2 - xp = jnp if use_jax else np + xp = pytest.importorskip("jax.numpy") if use_jax else np fine_kernel = aa.Array2D.no_mask( values=np.random.default_rng(4).random((9, 7)), pixel_scales=1.0 / s )