From 00ce8e19ecf0cfe93fa8536fdac2ecdefc3b08cf Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Thu, 26 Nov 2026 13:31:19 +0000 Subject: [PATCH 1/2] Shorter HilbertSNR arguments, edge_pixels on image meshes, soft_snr_map_from HilbertSNR's share arguments become background= and peak=, and adapt_image_soft_from becomes soft_snr_map_from (both unreleased since #717). Hilbert, HilbertSNR and Overlay take edge_pixels= (default 0), appending the zeroed Delaunay boundary points half a pixel beyond the circular mask's outer edge, so scripts no longer append them by hand. Phase 2 of the adapt-mesh-weighting default (PyAutoGalaxy#762). Co-Authored-By: Claude Opus 5.5 --- .../inversion/mesh/image_mesh/__init__.py | 2 +- .../inversion/mesh/image_mesh/abstract.py | 24 ++++++++++ .../inversion/mesh/image_mesh/hilbert.py | 14 +++++- .../inversion/mesh/image_mesh/hilbert_snr.py | 47 +++++++++++-------- .../inversion/mesh/image_mesh/overlay.py | 15 +++++- .../mesh/image_mesh/snr_transform.py | 2 +- .../image_mesh/test_hilbert_snr.py | 40 ++++++++++++++-- 7 files changed, 115 insertions(+), 29 deletions(-) diff --git a/autoarray/inversion/mesh/image_mesh/__init__.py b/autoarray/inversion/mesh/image_mesh/__init__.py index e9b9eb159..6a13166b0 100644 --- a/autoarray/inversion/mesh/image_mesh/__init__.py +++ b/autoarray/inversion/mesh/image_mesh/__init__.py @@ -1,6 +1,6 @@ from .hilbert import Hilbert from .hilbert_snr import HilbertSNR -from .snr_transform import soft_snr_from, adapt_image_soft_from +from .snr_transform import soft_snr_from, soft_snr_map_from from .overlay import Overlay from .kmeans import KMeans from .abstract import append_with_circle_edge_points diff --git a/autoarray/inversion/mesh/image_mesh/abstract.py b/autoarray/inversion/mesh/image_mesh/abstract.py index 74fc4b4d5..0bab5b30a 100644 --- a/autoarray/inversion/mesh/image_mesh/abstract.py +++ b/autoarray/inversion/mesh/image_mesh/abstract.py @@ -56,6 +56,30 @@ def __init__(self): def uses_adapt_images(self) -> bool: raise NotImplementedError + def with_edge_points_from(self, image_plane_mesh_grid, mask: Mask2D): + """ + Returns the mesh grid with ``self.edge_pixels`` points appended, evenly spaced on a circle outside the + circular mask (`append_with_circle_edge_points`). Delaunay pixelizations zero these points + (``zeroed_pixels``) so the source reconstruction has a fixed boundary. + + The circle lies half a pixel beyond the mask's outer edge: radius ``mask.circular_radius + + mask.pixel_scale / 2``, where ``circular_radius`` is the outer edge of the outermost unmasked pixel. For a + `Mask2D.circular` mask on an even-sized frame that is the radius the mask was made with plus half a pixel, + as the workspace scripts placed them (``radius=mask_radius + pixel_scale / 2``); on an odd-sized frame it is + half a pixel closer. + + Returns the grid unchanged when the image mesh has no ``edge_pixels`` (or zero). + """ + edge_pixels = getattr(self, "edge_pixels", 0) + if not edge_pixels: + return image_plane_mesh_grid + return append_with_circle_edge_points( + image_plane_mesh_grid=image_plane_mesh_grid, + centre=mask.mask_centre, + radius=mask.circular_radius + mask.pixel_scale / 2.0, + n_points=edge_pixels, + ) + def image_plane_mesh_grid_from( self, mask: Mask2D, diff --git a/autoarray/inversion/mesh/image_mesh/hilbert.py b/autoarray/inversion/mesh/image_mesh/hilbert.py index f622b08ad..dc40d176e 100644 --- a/autoarray/inversion/mesh/image_mesh/hilbert.py +++ b/autoarray/inversion/mesh/image_mesh/hilbert.py @@ -195,6 +195,7 @@ def __init__( pixels=10.0, weight_floor=0.0, weight_power=0.0, + edge_pixels: int = 0, ): """ Computes an image-mesh by computing the Hilbert curve of the adapt data and drawing points from it. @@ -220,6 +221,10 @@ def __init__( weight_power The power the weight values are raised too, which allows more pixels to be drawn from the higher weight regions of the adapt image. + edge_pixels + The number of points appended on a circle half a pixel beyond the circular mask's outer edge (0, the default, + appends none). A Delaunay pixelization zeroes them: pass ``pixels=image_mesh.pixels`` and + ``zeroed_pixels=image_mesh.edge_pixels`` to its mesh. image_mesh_min_mesh_pixels_per_pixel If not None, the image-mesh must place this many mesh pixels per image pixels in the N highest weighted @@ -242,6 +247,8 @@ def __init__( weight_power=weight_power, ) + self.edge_pixels = int(edge_pixels) + def image_plane_mesh_grid_from( self, mask: Mask2D, @@ -296,7 +303,12 @@ def image_plane_mesh_grid_from( gridy=grid_hb[:, 0], ) - return Grid2DIrregular(values=np.stack((drawn_y, drawn_x), axis=-1)) + return self.with_edge_points_from( + image_plane_mesh_grid=Grid2DIrregular( + values=np.stack((drawn_y, drawn_x), axis=-1) + ), + mask=mask, + ) def check_mesh_pixels_per_image_pixels( self, diff --git a/autoarray/inversion/mesh/image_mesh/hilbert_snr.py b/autoarray/inversion/mesh/image_mesh/hilbert_snr.py index 1e3f76db8..511a95d8a 100644 --- a/autoarray/inversion/mesh/image_mesh/hilbert_snr.py +++ b/autoarray/inversion/mesh/image_mesh/hilbert_snr.py @@ -13,12 +13,13 @@ class HilbertSNR(Hilbert): def __init__( self, pixels=10.0, - background_share: float = 0.25, - peak_share: float = 0.05, + background: float = 0.25, + peak: float = 0.05, peak_power: float = 8.0, snr_noise: float = 2.0, snr_soft: float = 3.0, soft_power: float = 2.0, + edge_pixels: int = 0, ): """ Computes an image-mesh by drawing points along a Hilbert curve, with the points shared out by the adapt @@ -34,18 +35,18 @@ def __init__( The weighting here gives each cell of the Hilbert curve, with S/N ``s``, the probability - background_share / n - + peak_share * (s / max(s)) ** peak_power / sum((s / max(s)) ** peak_power) - + (1 - background_share - peak_share) * soft / sum(soft) + background / n + + peak * (s / max(s)) ** peak_power / sum((s / max(s)) ** peak_power) + + (1 - background - peak) * soft / sum(soft) where ``soft = (x / (x + snr_soft)) ** soft_power`` and ``x = max(s - snr_noise, 0)`` (`soft_snr_from`): - - ``background_share`` (25%) of the points are spread evenly over the mask, so the background is always + - ``background`` (25%) of the points are spread evenly over the mask, so the background is always covered whatever the source looks like. - most of the points (70%) follow the soft S/N transform, which is in absolute S/N: zero at or below S/N ``snr_noise`` (noise), rising through S/N ``snr_noise + snr_soft`` and saturating for bright pixels. Faint but detected source emission always gets points; bright regions do not take them all. - - ``peak_share`` (5%) of the points go to the cells within roughly 25% of the peak S/N + - ``peak`` (5%) of the points go to the cells within roughly 25% of the peak S/N (``peak_power=8``), giving a bright compact feature (a bulge, a compact clump) extra resolution. With no arguments other than ``pixels`` this gives the weighting chosen in the adapt-mesh-weighting study @@ -55,7 +56,7 @@ def __init__( The ``adapt_data`` should be the source's S/N map *before* the minimum-percent floor PyAutoGalaxy applies to adapt images: above a peak S/N of 200 that floor lifts empty sky over ``snr_noise`` and the sky is then weighted as source. Negative values are treated as 0 before the map is interpolated onto the curve. To have - an adaptive regularization (e.g. `AdaptSplit`) adapt to the same signal, give it `adapt_image_soft_from` of + an adaptive regularization (e.g. `AdaptSplit`) adapt to the same signal, give it `soft_snr_map_from` of the same S/N map. Known limits, measured in that study: @@ -69,9 +70,9 @@ def __init__( ---------- pixels The total number of pixels in the image mesh and drawn from the Hilbert curve. - background_share + background Fraction of the points spread evenly over every cell of the curve inside the mask. - peak_share + peak Fraction of the points given in proportion to ``(s / max(s)) ** peak_power``. peak_power Power of the peak term; 8 restricts it to cells within roughly 25% of the peak S/N. @@ -81,17 +82,23 @@ def __init__( S/N above ``snr_noise`` at which the soft term reaches ``0.5 ** soft_power``. soft_power Power of the soft term. + edge_pixels + The number of points appended on a circle half a pixel beyond the circular mask's outer edge (0, the default, + appends none). A Delaunay pixelization zeroes them: pass ``pixels=image_mesh.pixels`` and + ``zeroed_pixels=image_mesh.edge_pixels`` to its mesh. """ - if background_share < 0.0 or peak_share < 0.0 or background_share + peak_share > 1.0: + if background < 0.0 or peak < 0.0 or background + peak > 1.0: raise ValueError( - "HilbertSNR requires background_share >= 0, peak_share >= 0 and " - f"background_share + peak_share <= 1 (got {background_share}, {peak_share})." + "HilbertSNR requires background >= 0, peak >= 0 and " + f"background + peak <= 1 (got {background}, {peak})." ) - super().__init__(pixels=pixels, weight_floor=0.0, weight_power=0.0) + super().__init__( + pixels=pixels, weight_floor=0.0, weight_power=0.0, edge_pixels=edge_pixels + ) - self.background_share = background_share - self.peak_share = peak_share + self.background = background + self.peak = peak self.peak_power = peak_power self.snr_noise = snr_noise self.snr_soft = snr_soft @@ -114,14 +121,14 @@ def weight_map_from(self, adapt_data: np.ndarray) -> np.ndarray: n = snr.size background = np.full(n, 1.0 / n) - weight_map = self.background_share * background + weight_map = self.background * background peak_value = np.max(snr) if n else 0.0 if peak_value > 0.0: peak_term = (snr / peak_value) ** self.peak_power - weight_map = weight_map + self.peak_share * peak_term / np.sum(peak_term) + weight_map = weight_map + self.peak * peak_term / np.sum(peak_term) else: - weight_map = weight_map + self.peak_share * background + weight_map = weight_map + self.peak * background soft = soft_snr_from( snr=snr, @@ -129,7 +136,7 @@ def weight_map_from(self, adapt_data: np.ndarray) -> np.ndarray: snr_soft=self.snr_soft, soft_power=self.soft_power, ) - source_share = 1.0 - self.background_share - self.peak_share + source_share = 1.0 - self.background - self.peak if np.sum(soft) > 0.0: weight_map = weight_map + source_share * soft / np.sum(soft) else: diff --git a/autoarray/inversion/mesh/image_mesh/overlay.py b/autoarray/inversion/mesh/image_mesh/overlay.py index c7ebaff91..a1e5a187f 100644 --- a/autoarray/inversion/mesh/image_mesh/overlay.py +++ b/autoarray/inversion/mesh/image_mesh/overlay.py @@ -159,7 +159,12 @@ def overlay_via_unmasked_overlaid_from( class Overlay(AbstractImageMesh): - def __init__(self, shape=(3, 3), respect_small_datasets: bool = True): + def __init__( + self, + shape=(3, 3), + respect_small_datasets: bool = True, + edge_pixels: int = 0, + ): """ Computes an image-mesh by overlaying a uniform grid of (y,x) coordinates over the masked image that the pixelization is fitting. @@ -181,6 +186,9 @@ def __init__(self, shape=(3, 3), respect_small_datasets: bool = True): When `PYAUTO_SMALL_DATASETS=1` is set, `shape` is capped per axis to the small-datasets cap, matching the cap `Grid2D.uniform` and `Mask2D.circular` apply to the data. Pass `False` to opt out for an image mesh whose resolution is load-bearing for the script. + edge_pixels + The number of points appended on a circle half a pixel beyond the (circular) mask's outer edge (0, the default, + appends none). A Delaunay pixelization zeroes them (``zeroed_pixels=image_mesh.edge_pixels``). """ super().__init__() @@ -190,6 +198,7 @@ def __init__(self, shape=(3, 3), respect_small_datasets: bool = True): ) self.shape = (int(shape[0]), int(shape[1])) + self.edge_pixels = int(edge_pixels) def image_plane_mesh_grid_from( self, @@ -251,7 +260,9 @@ def image_plane_mesh_grid_from( overlay_for_mask=overlay_for_mask, ) - return Grid2DIrregular(values=mesh_grid) + return self.with_edge_points_from( + image_plane_mesh_grid=Grid2DIrregular(values=mesh_grid), mask=mask + ) @property def uses_adapt_images(self) -> bool: diff --git a/autoarray/inversion/mesh/image_mesh/snr_transform.py b/autoarray/inversion/mesh/image_mesh/snr_transform.py index e07440a65..3c7de2360 100644 --- a/autoarray/inversion/mesh/image_mesh/snr_transform.py +++ b/autoarray/inversion/mesh/image_mesh/snr_transform.py @@ -54,7 +54,7 @@ def soft_snr_from( return (x / (x + snr_soft)) ** soft_power -def adapt_image_soft_from( +def soft_snr_map_from( snr: np.ndarray, snr_noise: float = 2.0, snr_soft: float = 3.0, diff --git a/test_autoarray/inversion/pixelization/image_mesh/test_hilbert_snr.py b/test_autoarray/inversion/pixelization/image_mesh/test_hilbert_snr.py index 97754872a..7f9ec21cc 100644 --- a/test_autoarray/inversion/pixelization/image_mesh/test_hilbert_snr.py +++ b/test_autoarray/inversion/pixelization/image_mesh/test_hilbert_snr.py @@ -27,15 +27,15 @@ def test__soft_snr_from__values(): ) -def test__adapt_image_soft_from__floor_and_blank(): +def test__soft_snr_map_from__floor_and_blank(): snr = np.array([0.0, 1.0, 3.0, 40.0]) - adapt = aa.image_mesh.adapt_image_soft_from(snr=snr) + adapt = aa.image_mesh.soft_snr_map_from(snr=snr) peak = (38.0 / 41.0) ** 2 assert adapt == pytest.approx([0.01 * peak, 0.01 * peak, 1.0 / 16.0, peak], 1.0e-8) - assert aa.image_mesh.adapt_image_soft_from(snr=np.array([0.0, 1.0, 2.0])) == pytest.approx( + assert aa.image_mesh.soft_snr_map_from(snr=np.array([0.0, 1.0, 2.0])) == pytest.approx( [1.0, 1.0, 1.0] ) @@ -85,7 +85,7 @@ def test__weight_map_from__blank_adapt_data_is_uniform(): def test__shares_validated(): with pytest.raises(ValueError): - aa.image_mesh.HilbertSNR(pixels=10, background_share=0.9, peak_share=0.2) + aa.image_mesh.HilbertSNR(pixels=10, background=0.9, peak=0.2) def _arc_plus_compact(peak): @@ -148,3 +148,35 @@ def test__image_plane_mesh_grid_from__negative_values_treated_as_zero(): ) assert np.asarray(mesh_raw) == pytest.approx(np.asarray(mesh_clipped), 1.0e-12) + + +@pytest.mark.parametrize( + "image_mesh", + [ + aa.image_mesh.HilbertSNR(pixels=50, edge_pixels=12), + aa.image_mesh.Hilbert(pixels=50, weight_power=3.5, weight_floor=0.01, edge_pixels=12), + aa.image_mesh.Overlay(shape=(10, 10), edge_pixels=12), + ], +) +def test__edge_pixels__appended_on_circle_outside_mask(image_mesh): + mask, adapt_data, arc, snr = _arc_plus_compact(25.0) + + grid = np.asarray(image_mesh.image_plane_mesh_grid_from(mask=mask, adapt_data=adapt_data)) + + edge = grid[-12:] + radius = np.sqrt(edge[:, 0] ** 2 + edge[:, 1] ** 2) + assert radius == pytest.approx(np.full(12, mask.circular_radius + 0.05), 1.0e-8) + # Even-sized frame: the radius the mask was made with (2.8) plus half a pixel, as the workspace scripts place them. + assert radius == pytest.approx(np.full(12, 2.8 + 0.05), 1.0e-8) + + without = type(image_mesh)( + **{k: v for k, v in vars(image_mesh).items() if k in ("pixels", "shape")} + ) + if isinstance(image_mesh, aa.image_mesh.Hilbert) and not isinstance( + image_mesh, aa.image_mesh.HilbertSNR + ): + without = aa.image_mesh.Hilbert(pixels=50, weight_power=3.5, weight_floor=0.01) + grid_without = np.asarray(without.image_plane_mesh_grid_from(mask=mask, adapt_data=adapt_data)) + + assert grid.shape[0] == grid_without.shape[0] + 12 + assert grid[:-12] == pytest.approx(grid_without, 1.0e-12) From 5592a309c59b8384f37d05cbd521e2db9771ccb2 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Thu, 26 Nov 2026 13:52:26 +0000 Subject: [PATCH 2/2] HilbertSNR: cap points per image pixel; opt-in frame-independent interpolation HilbertSNR(max_per_pixel=8) water-fills the Hilbert probabilities so no image pixel gets more than 8 points (faint sources had up to 61 in one pixel, hundreds within 0.05 pixels of each other). image_and_grid_from gains frame_independent: bilinear interpolation on the image's own pixel grid, so the mesh no longer depends on the frame around the mask and non-square frames work. On by default for HilbertSNR; Hilbert keeps the original griddata interpolation unless asked (frame_independent=False), so existing results are unchanged. Hilbert's normalised weight map moves into a probabilities_from hook. Co-Authored-By: Claude Opus 5.5 --- .../inversion/mesh/image_mesh/hilbert.py | 110 ++++++++++++++++- .../inversion/mesh/image_mesh/hilbert_snr.py | 88 +++++++++++++- .../image_mesh/test_hilbert_snr.py | 111 ++++++++++++++++++ 3 files changed, 302 insertions(+), 7 deletions(-) diff --git a/autoarray/inversion/mesh/image_mesh/hilbert.py b/autoarray/inversion/mesh/image_mesh/hilbert.py index dc40d176e..e508cfd6e 100644 --- a/autoarray/inversion/mesh/image_mesh/hilbert.py +++ b/autoarray/inversion/mesh/image_mesh/hilbert.py @@ -119,7 +119,13 @@ def grid_hilbert_order_from(length, mask_radius): def image_and_grid_from( - image, mask, mask_radius, pixel_scales, hilbert_length, mask_centre=(0.0, 0.0) + image, + mask, + mask_radius, + pixel_scales, + hilbert_length, + mask_centre=(0.0, 0.0), + frame_independent: bool = False, ): """ This code will create a grid in Hilbert space-filling curve order and an interpolated hyper @@ -128,8 +134,29 @@ def image_and_grid_from( The Hilbert curve is generated around the origin and filtered to a disc of radius ``mask_radius``, then translated by ``mask_centre`` so the sampling lands inside the mask's circle for offset-centre masks. For masks centred on the origin the translation is a no-op and behaviour is unchanged. + + With ``frame_independent=False`` (the original behaviour, kept so existing results do not change) the image is + interpolated with ``scipy.interpolate.griddata(method="linear")`` over a square ``(n, n)`` grid built from the + first dimension of the native image. A Delaunay triangulation of a regular lattice is degenerate (each square can + be split along either diagonal), so values between pixel centres, and through the Hilbert draw every later + mesh point, depend on the size of the frame around the mask (padding a lens's frame by 10-20 pixels moved + points by up to ~9 pixels); a non-square native image raises. + + With ``frame_independent=True`` the image is interpolated bilinearly on its own pixel grid + (``scipy.ndimage.map_coordinates(order=1)``, using the image's shape, pixel scales and origin, zero outside), + so the result depends only on the mask and the image values and is identical for any frame that contains the + mask, square or not. Values at pixel centres are the pixel values in both modes. """ + if frame_independent: + return _image_and_grid_bilinear_from( + image=image, + mask_radius=mask_radius, + pixel_scales=pixel_scales, + hilbert_length=hilbert_length, + mask_centre=mask_centre, + ) + from scipy.interpolate import griddata # For multi wavelength fits the input image may be a different resolution than the mask. @@ -164,6 +191,54 @@ def image_and_grid_from( return new_img, new_grid +def _hilbert_curve_grid_from(hilbert_length, mask_radius, mask_centre): + """The (y, x) centres of the Hilbert curve's cells inside the mask's circle, in curve order.""" + x1d_hb, y1d_hb = grid_hilbert_order_from( + length=hilbert_length, mask_radius=mask_radius + ) + + grid_hb = np.stack((y1d_hb, x1d_hb), axis=-1) + grid_hb_radius = np.sqrt(grid_hb[:, 0] ** 2.0 + grid_hb[:, 1] ** 2.0) + return grid_hb[grid_hb_radius <= mask_radius] + np.asarray(mask_centre) + + +def _image_and_grid_bilinear_from( + image, mask_radius, pixel_scales, hilbert_length, mask_centre +): + """ + The ``frame_independent=True`` branch of `image_and_grid_from`: bilinear interpolation of the native image on + its own pixel grid. Pixel (i, j) of an (ny, nx) image with pixel scales (sy, sx) and origin (oy, ox) is centred + at y = (ny / 2 - 0.5 - i) * sy + oy, x = (j - nx / 2 + 0.5) * sx + ox, the convention of `Grid2D.uniform`. + """ + from scipy.ndimage import map_coordinates + + native = np.asarray(image.native, dtype=float) + ny, nx = native.shape + + image_pixel_scales = getattr(image, "pixel_scales", None) or pixel_scales + if np.isscalar(image_pixel_scales): + image_pixel_scales = (image_pixel_scales, image_pixel_scales) + sy, sx = image_pixel_scales + + try: + oy, ox = image.origin + except AttributeError: + oy, ox = 0.0, 0.0 + + new_grid = _hilbert_curve_grid_from( + hilbert_length=hilbert_length, mask_radius=mask_radius, mask_centre=mask_centre + ) + + rows = (ny / 2.0 - 0.5) - (new_grid[:, 0] - oy) / sy + cols = (new_grid[:, 1] - ox) / sx + (nx / 2.0 - 0.5) + + new_img = map_coordinates( + native, [rows, cols], order=1, mode="constant", cval=0.0 + ) + + return new_img, new_grid + + def inverse_transform_sampling_interpolated(probabilities, n_samples, gridx, gridy): """ Given a 1d cumulative probability function, this code will generate points following the @@ -189,6 +264,10 @@ def inverse_transform_sampling_interpolated(probabilities, n_samples, gridx, gri return output_ids, output_x, output_y +# Side length, in cells, of the square Hilbert curve laid over the mask's bounding square. +HILBERT_LENGTH = 193 + + class Hilbert(AbstractImageMeshWeighted): def __init__( self, @@ -196,6 +275,7 @@ def __init__( weight_floor=0.0, weight_power=0.0, edge_pixels: int = 0, + frame_independent: bool = False, ): """ Computes an image-mesh by computing the Hilbert curve of the adapt data and drawing points from it. @@ -225,6 +305,11 @@ def __init__( The number of points appended on a circle half a pixel beyond the circular mask's outer edge (0, the default, appends none). A Delaunay pixelization zeroes them: pass ``pixels=image_mesh.pixels`` and ``zeroed_pixels=image_mesh.edge_pixels`` to its mesh. + frame_independent + If True, the adapt data is interpolated onto the Hilbert curve bilinearly on its own pixel grid, so the + mesh depends only on the mask and the adapt values, not on the size or shape of the frame around the + mask (see `image_and_grid_from`). False (the default) keeps the original `griddata` interpolation, so + existing results are unchanged. `HilbertSNR` turns it on. image_mesh_min_mesh_pixels_per_pixel If not None, the image-mesh must place this many mesh pixels per image pixels in the N highest weighted @@ -248,6 +333,7 @@ def __init__( ) self.edge_pixels = int(edge_pixels) + self.frame_independent = bool(frame_independent) def image_plane_mesh_grid_from( self, @@ -284,13 +370,12 @@ def image_plane_mesh_grid_from( mask=mask, mask_radius=mask.circular_radius, pixel_scales=mask.pixel_scales, - hilbert_length=193, + hilbert_length=HILBERT_LENGTH, mask_centre=mask.mask_centre, + frame_independent=self.frame_independent, ) - weight_map = self.weight_map_from(adapt_data=adapt_data_hb) - - weight_map /= np.sum(weight_map) + weight_map = self.probabilities_from(adapt_data_hb=adapt_data_hb, mask=mask) ( drawn_id, @@ -310,6 +395,21 @@ def image_plane_mesh_grid_from( mask=mask, ) + def probabilities_from(self, adapt_data_hb: np.ndarray, mask: Mask2D) -> np.ndarray: + """ + Returns the probability of drawing a mesh point in each cell of the Hilbert curve (summing to 1): the + weight map of the adapt values along the curve, normalised. + + Parameters + ---------- + adapt_data_hb + The adapt data interpolated onto the cells of the Hilbert curve. + mask + The circular mask the curve fills (used by subclasses that need its geometry). + """ + weight_map = self.weight_map_from(adapt_data=adapt_data_hb) + return weight_map / np.sum(weight_map) + def check_mesh_pixels_per_image_pixels( self, mask: Mask2D, diff --git a/autoarray/inversion/mesh/image_mesh/hilbert_snr.py b/autoarray/inversion/mesh/image_mesh/hilbert_snr.py index 511a95d8a..2074678c7 100644 --- a/autoarray/inversion/mesh/image_mesh/hilbert_snr.py +++ b/autoarray/inversion/mesh/image_mesh/hilbert_snr.py @@ -5,7 +5,7 @@ from autoarray.mask.mask_2d import Mask2D from autoarray.structures.arrays.uniform_2d import Array2D from autoarray.structures.grids.irregular_2d import Grid2DIrregular -from autoarray.inversion.mesh.image_mesh.hilbert import Hilbert +from autoarray.inversion.mesh.image_mesh.hilbert import HILBERT_LENGTH, Hilbert from autoarray.inversion.mesh.image_mesh.snr_transform import soft_snr_from @@ -19,7 +19,9 @@ def __init__( snr_noise: float = 2.0, snr_soft: float = 3.0, soft_power: float = 2.0, + max_per_pixel: Optional[float] = 8.0, edge_pixels: int = 0, + frame_independent: bool = True, ): """ Computes an image-mesh by drawing points along a Hilbert curve, with the points shared out by the adapt @@ -48,6 +50,11 @@ def __init__( Faint but detected source emission always gets points; bright regions do not take them all. - ``peak`` (5%) of the points go to the cells within roughly 25% of the peak S/N (``peak_power=8``), giving a bright compact feature (a bulge, a compact clump) extra resolution. + - no image pixel gets more than ``max_per_pixel`` (8) points: a cell's probability is capped and what it + cannot take is shared among the other cells in proportion to their weight. Without the cap a faint + source, with only a few pixels above ``snr_noise``, gets tens of points per image pixel (up to 61 on + the study's 20 datasets, many within 0.01 of a pixel of each other); with it the closest pair was 0.1 + of a pixel, and the median share of points on the source moved from 0.71 to 0.70. With no arguments other than ``pixels`` this gives the weighting chosen in the adapt-mesh-weighting study (PyAutoArray#714): fitted on 10 HST and 10 JWST (COWLS) lens datasets and checked offline on 19 lenses @@ -82,6 +89,13 @@ def __init__( S/N above ``snr_noise`` at which the soft term reaches ``0.5 ** soft_power``. soft_power Power of the soft term. + max_per_pixel + The most mesh points any image pixel may receive (on average over the Hilbert cells inside it). None + turns the cap off. + frame_independent + Interpolate the adapt data onto the Hilbert curve bilinearly on its own pixel grid, so the mesh does not + depend on the size or shape of the frame around the mask (`image_and_grid_from`). On by default here; + `Hilbert` keeps the original interpolation unless asked. edge_pixels The number of points appended on a circle half a pixel beyond the circular mask's outer edge (0, the default, appends none). A Delaunay pixelization zeroes them: pass ``pixels=image_mesh.pixels`` and @@ -94,7 +108,11 @@ def __init__( ) super().__init__( - pixels=pixels, weight_floor=0.0, weight_power=0.0, edge_pixels=edge_pixels + pixels=pixels, + weight_floor=0.0, + weight_power=0.0, + edge_pixels=edge_pixels, + frame_independent=frame_independent, ) self.background = background @@ -103,6 +121,7 @@ def __init__( self.snr_noise = snr_noise self.snr_soft = snr_soft self.soft_power = soft_power + self.max_per_pixel = max_per_pixel def weight_map_from(self, adapt_data: np.ndarray) -> np.ndarray: """ @@ -144,6 +163,27 @@ def weight_map_from(self, adapt_data: np.ndarray) -> np.ndarray: return weight_map + def probabilities_from(self, adapt_data_hb: np.ndarray, mask: Mask2D) -> np.ndarray: + """ + Returns the probability of drawing a mesh point in each cell of the Hilbert curve: the `weight_map_from` + probabilities, with no cell allowed more than ``max_per_pixel`` points per image pixel (water-filled, see + `capped_probabilities_from`). + + A cell's expected number of points is ``pixels * p``; one image pixel spans + ``(pixel_scale / cell_size) ** 2`` cells, with ``cell_size = 2 * mask.circular_radius / HILBERT_LENGTH``. + """ + probabilities = self.weight_map_from(adapt_data=adapt_data_hb) + probabilities = probabilities / np.sum(probabilities) + + if self.max_per_pixel is None: + return probabilities + + cell_size = 2.0 * mask.circular_radius / HILBERT_LENGTH + cells_per_pixel = (mask.pixel_scale / cell_size) ** 2 + cap = self.max_per_pixel / (self.pixels * cells_per_pixel) + + return capped_probabilities_from(probabilities=probabilities, cap=cap) + def image_plane_mesh_grid_from( self, mask: Mask2D, @@ -169,3 +209,47 @@ def image_plane_mesh_grid_from( ) return super().image_plane_mesh_grid_from(mask=mask, adapt_data=adapt_data) + + +def capped_probabilities_from(probabilities: np.ndarray, cap: float) -> np.ndarray: + """ + Returns ``probabilities`` with no entry above ``cap``, still summing to 1: capped entries are set to ``cap`` + and what they could not take is shared among the others in proportion to their probability, repeatedly + (water-filling: the result is ``min(cap, scale * probabilities)`` for the ``scale`` that makes it sum to 1, + found by bisection). + + If ``cap`` is so small that even ``cap`` everywhere sums to less than 1, the probabilities are uniform. + + Parameters + ---------- + probabilities + Non-negative values summing to 1. + cap + The largest probability any entry may have. + """ + probabilities = np.asarray(probabilities, dtype=float) + n = probabilities.size + + if cap * n <= 1.0: + return np.full(n, 1.0 / n) + if probabilities.max() <= cap: + return probabilities + + positive = probabilities > 0.0 + if cap * positive.sum() <= 1.0: + capped = np.where(positive, cap, 0.0) + capped[~positive] = (1.0 - capped.sum()) / max((~positive).sum(), 1) + return capped + + low, high = 0.0, 1.0 + while np.minimum(cap, high * probabilities).sum() < 1.0: + high *= 2.0 + for _ in range(100): + mid = 0.5 * (low + high) + if np.minimum(cap, mid * probabilities).sum() < 1.0: + low = mid + else: + high = mid + + capped = np.minimum(cap, high * probabilities) + return capped / capped.sum() diff --git a/test_autoarray/inversion/pixelization/image_mesh/test_hilbert_snr.py b/test_autoarray/inversion/pixelization/image_mesh/test_hilbert_snr.py index 7f9ec21cc..05edf2adc 100644 --- a/test_autoarray/inversion/pixelization/image_mesh/test_hilbert_snr.py +++ b/test_autoarray/inversion/pixelization/image_mesh/test_hilbert_snr.py @@ -180,3 +180,114 @@ def test__edge_pixels__appended_on_circle_outside_mask(image_mesh): assert grid.shape[0] == grid_without.shape[0] + 12 assert grid[:-12] == pytest.approx(grid_without, 1.0e-12) + + +def _padded(mask, adapt_data, pad): + mask_native = np.pad(np.asarray(mask), pad, constant_values=True) + values = np.pad(np.asarray(adapt_data.native), pad) + padded_mask = aa.Mask2D(mask=mask_native, pixel_scales=mask.pixel_scales) + return padded_mask, aa.Array2D(values=values[~mask_native], mask=padded_mask) + + +@pytest.mark.parametrize( + "image_mesh", + [ + aa.image_mesh.HilbertSNR(pixels=300), + aa.image_mesh.Hilbert(pixels=300, weight_power=3.5, weight_floor=0.01, frame_independent=True), + ], +) +def test__frame_independent__same_mesh_in_larger_and_non_square_frames(image_mesh): + mask, adapt_data, arc, snr = _arc_plus_compact(25.0) + + mesh = np.asarray(image_mesh.image_plane_mesh_grid_from(mask=mask, adapt_data=adapt_data)) + + for pad in (((10, 10), (10, 10)), ((0, 0), (8, 8)), ((6, 6), (0, 0))): + padded_mask, padded_data = _padded(mask, adapt_data, pad) + padded_mesh = np.asarray( + image_mesh.image_plane_mesh_grid_from(mask=padded_mask, adapt_data=padded_data) + ) + assert padded_mesh == pytest.approx(mesh, abs=1.0e-9) + + +def test__hilbert_default__unchanged_interpolation(): + mask, adapt_data, arc, snr = _arc_plus_compact(25.0) + + default = aa.image_mesh.Hilbert(pixels=300, weight_power=3.5, weight_floor=0.01) + assert default.frame_independent is False + + from autoarray.inversion.mesh.image_mesh.hilbert import image_and_grid_from + + values_default, grid_default = image_and_grid_from( + image=adapt_data, mask=mask, mask_radius=mask.circular_radius, + pixel_scales=mask.pixel_scales, hilbert_length=193, mask_centre=mask.mask_centre, + ) + values_bilinear, grid_bilinear = image_and_grid_from( + image=adapt_data, mask=mask, mask_radius=mask.circular_radius, + pixel_scales=mask.pixel_scales, hilbert_length=193, mask_centre=mask.mask_centre, + frame_independent=True, + ) + assert grid_bilinear == pytest.approx(grid_default, 1.0e-12) + # The two interpolations agree closely, but are not identical between pixel centres. + assert np.abs(values_bilinear - values_default).max() < 0.2 * np.abs(values_default).max() + + +def test__frame_independent__bilinear_is_exact_on_a_linear_image(): + from autoarray.inversion.mesh.image_mesh.hilbert import image_and_grid_from + + mask = aa.Mask2D.circular(shape_native=(40, 30), radius=1.0, pixel_scales=0.1) + y, x = np.indices(mask.shape_native) + y = (20 - 0.5 - y) * 0.1 + x = (x - 15 + 0.5) * 0.1 + plane = 3.0 + 2.0 * y - 1.5 * x + image = aa.Array2D(values=plane[~np.asarray(mask)], mask=mask) + + values, grid = image_and_grid_from( + image=image, mask=mask, mask_radius=mask.circular_radius, + pixel_scales=mask.pixel_scales, hilbert_length=193, mask_centre=mask.mask_centre, + frame_independent=True, + ) + + inner = np.sqrt(grid[:, 0] ** 2 + grid[:, 1] ** 2) < 0.8 + assert values[inner] == pytest.approx(3.0 + 2.0 * grid[inner, 0] - 1.5 * grid[inner, 1], 1.0e-10) + + +def test__capped_probabilities_from(): + from autoarray.inversion.mesh.image_mesh.hilbert_snr import capped_probabilities_from + + p = np.array([0.5, 0.2, 0.2, 0.1, 0.0]) + capped = capped_probabilities_from(probabilities=p, cap=0.3) + + assert capped.sum() == pytest.approx(1.0, 1.0e-12) + assert capped.max() <= 0.3 + 1.0e-12 + assert capped[0] == pytest.approx(0.3, 1.0e-10) + # The rest keep their proportions. + assert capped[1] / capped[3] == pytest.approx(2.0, 1.0e-8) + + assert capped_probabilities_from(probabilities=p, cap=0.9) == pytest.approx(p) + assert capped_probabilities_from(probabilities=p, cap=0.1) == pytest.approx(np.full(5, 0.2)) + + +@pytest.mark.parametrize("max_per_pixel", [8.0, 3.0]) +def test__max_per_pixel__caps_points_per_image_pixel(max_per_pixel): + # A faint, compact source: without the cap most points pile onto a few pixels. + mask = aa.Mask2D.circular(shape_native=(60, 60), radius=2.8, pixel_scales=0.1) + y, x = np.indices(mask.shape_native) + y = (29.5 - y) * 0.1 + x = (x - 29.5) * 0.1 + snr = 6.0 * np.exp(-0.5 * ((y - 1.0) ** 2 + x**2) / 0.08**2) + adapt_data = aa.Array2D(values=snr[~np.asarray(mask)], mask=mask) + + def most_per_pixel(image_mesh): + mesh = np.asarray(image_mesh.image_plane_mesh_grid_from(mask=mask, adapt_data=adapt_data)) + rows = np.clip(np.round(29.5 - mesh[:, 0] / 0.1).astype(int), 0, 59) + cols = np.clip(np.round(mesh[:, 1] / 0.1 + 29.5).astype(int), 0, 59) + counts = np.zeros((60, 60), dtype=int) + np.add.at(counts, (rows, cols), 1) + return counts.max() + + uncapped = most_per_pixel(aa.image_mesh.HilbertSNR(pixels=1000, max_per_pixel=None)) + capped = most_per_pixel(aa.image_mesh.HilbertSNR(pixels=1000, max_per_pixel=max_per_pixel)) + + assert uncapped > 3 * max_per_pixel + # On average over a pixel's Hilbert cells; allow one for where cell and pixel boundaries fall. + assert capped <= max_per_pixel + 1