diff --git a/autoarray/inversion/mesh/image_mesh/__init__.py b/autoarray/inversion/mesh/image_mesh/__init__.py index decd9cc46..e9b9eb159 100644 --- a/autoarray/inversion/mesh/image_mesh/__init__.py +++ b/autoarray/inversion/mesh/image_mesh/__init__.py @@ -1,4 +1,6 @@ from .hilbert import Hilbert +from .hilbert_snr import HilbertSNR +from .snr_transform import soft_snr_from, adapt_image_soft_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/hilbert_snr.py b/autoarray/inversion/mesh/image_mesh/hilbert_snr.py new file mode 100644 index 000000000..1e3f76db8 --- /dev/null +++ b/autoarray/inversion/mesh/image_mesh/hilbert_snr.py @@ -0,0 +1,164 @@ +from __future__ import annotations +import numpy as np +from typing import Optional + +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.snr_transform import soft_snr_from + + +class HilbertSNR(Hilbert): + def __init__( + self, + pixels=10.0, + background_share: float = 0.25, + peak_share: float = 0.05, + peak_power: float = 8.0, + snr_noise: float = 2.0, + snr_soft: float = 3.0, + soft_power: float = 2.0, + ): + """ + Computes an image-mesh by drawing points along a Hilbert curve, with the points shared out by the adapt + image's absolute signal-to-noise (S/N) under a fixed point budget. + + This is the recommended default for adaptive pixelizations. It draws points exactly as `Hilbert` does (the + same curve and deterministic inverse-transform sampling, so a region's share of the points equals its share + of the weight) but replaces `Hilbert`'s weighting, ``(adapt / max(adapt)) ** weight_power`` floored at + ``weight_floor``. That weighting is normalised by the brightest pixel, so the adaptation of the rest of the + source depends on how bright that one pixel is: with a peak S/N of 250, ``weight_power=3.5`` and + ``weight_floor=0.01``, every pixel below S/N ~67 got the floor weight, the same as empty sky. Capping the S/N + map at 3 before the weighting avoided that, but treated all source structure above S/N 3 as equal. + + 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) + + 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 + 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_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 + (PyAutoArray#714): fitted on 10 HST and 10 JWST (COWLS) lens datasets and checked offline on 19 lenses + from a peak S/N of 5 to 1000. + + 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 + the same S/N map. + + Known limits, measured in that study: + + - For a very faint source (peak S/N ~5) only a few pixels exceed ``snr_noise``, so most points cluster on + them (tens of points per image pixel) and the soft transform gives the regularization little contrast. + - For a very bright source (peak S/N of several hundred) nearly all detected emission is past the + saturation, so points spread evenly over it, arcs and faint wings alike. + + Parameters + ---------- + pixels + The total number of pixels in the image mesh and drawn from the Hilbert curve. + background_share + Fraction of the points spread evenly over every cell of the curve inside the mask. + peak_share + 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. + snr_noise + S/N at or below which a cell counts as noise and receives only the background (and peak) shares. + snr_soft + S/N above ``snr_noise`` at which the soft term reaches ``0.5 ** soft_power``. + soft_power + Power of the soft term. + """ + if background_share < 0.0 or peak_share < 0.0 or background_share + peak_share > 1.0: + raise ValueError( + "HilbertSNR requires background_share >= 0, peak_share >= 0 and " + f"background_share + peak_share <= 1 (got {background_share}, {peak_share})." + ) + + super().__init__(pixels=pixels, weight_floor=0.0, weight_power=0.0) + + self.background_share = background_share + self.peak_share = peak_share + self.peak_power = peak_power + self.snr_noise = snr_noise + self.snr_soft = snr_soft + self.soft_power = soft_power + + def weight_map_from(self, adapt_data: np.ndarray) -> np.ndarray: + """ + Returns the probability of each cell of the Hilbert curve (summing to 1), from the adapt S/N values along + the curve. See the `__init__` docstring for the formula. + + A share whose term is zero everywhere (no cell above ``snr_noise``, or no positive S/N) is given to the + background instead, so a blank adapt image gives an even mesh. + + Parameters + ---------- + adapt_data + The adapt image's S/N values on the cells of the Hilbert curve. + """ + snr = np.clip(np.asarray(adapt_data, dtype=float), 0.0, None) + n = snr.size + + background = np.full(n, 1.0 / n) + weight_map = self.background_share * 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) + else: + weight_map = weight_map + self.peak_share * background + + soft = soft_snr_from( + snr=snr, + snr_noise=self.snr_noise, + snr_soft=self.snr_soft, + soft_power=self.soft_power, + ) + source_share = 1.0 - self.background_share - self.peak_share + if np.sum(soft) > 0.0: + weight_map = weight_map + source_share * soft / np.sum(soft) + else: + weight_map = weight_map + source_share * background + + return weight_map + + def image_plane_mesh_grid_from( + self, + mask: Mask2D, + adapt_data: Optional[np.ndarray], + ) -> Grid2DIrregular: + """ + Returns the image mesh, drawn along the Hilbert curve with the `HilbertSNR` weighting. + + Negative S/N values are set to 0 on the native adapt image, before it is interpolated onto the curve, so + noise below zero does not pull interpolated source values down; the rest is `Hilbert`'s. + + Parameters + ---------- + mask + The circular mask of the data the pixelization fits. + adapt_data + The source's S/N map (before the adapt-image minimum-percent floor), on ``mask``. + """ + if adapt_data is not None: + adapt_data = Array2D( + values=np.clip(np.asarray(adapt_data.array, dtype=float), 0.0, None), + mask=adapt_data.mask, + ) + + return super().image_plane_mesh_grid_from(mask=mask, adapt_data=adapt_data) diff --git a/autoarray/inversion/mesh/image_mesh/snr_transform.py b/autoarray/inversion/mesh/image_mesh/snr_transform.py new file mode 100644 index 000000000..e07440a65 --- /dev/null +++ b/autoarray/inversion/mesh/image_mesh/snr_transform.py @@ -0,0 +1,93 @@ +""" +Soft signal-to-noise transform shared by the `HilbertSNR` image mesh and the adapt image given to adaptive +regularization schemes (e.g. `AdaptSplit`). + +Both the image mesh and the regularization adapt to the source's signal-to-noise (S/N) map. Earlier defaults +normalised that map by its brightest pixel (``(adapt / max(adapt)) ** weight_power``), so how well the rest of the +source was adapted to depended on how bright its single brightest pixel was: with a peak S/N of 250 and +``weight_power=3.5, weight_floor=0.01``, every pixel below S/N ~67 sat on the floor, the same as empty sky. + +The transform here works in absolute S/N instead. A pixel's value depends only on its own S/N: + + x = max(S/N - snr_noise, 0) + soft = (x / (x + snr_soft)) ** soft_power + +With the defaults (``snr_noise=2``, ``snr_soft=3``, ``soft_power=2``) it is 0 at or below S/N 2 (noise), 0.06 at +S/N 3, 0.36 at S/N 6.5, 0.59 at S/N 12, 0.86 at S/N 40 and tends to 1 for bright pixels. Faint but detected source +emission therefore always counts, whatever the peak, and bright regions saturate rather than dominate. + +The input should be the S/N map *before* the minimum-percent floor PyAutoGalaxy applies to adapt images +(``adapt_minimum_percent``, 1% of the maximum): above a peak S/N of 200 that floor lifts empty sky over +``snr_noise`` (sky reads S/N 2.5 at a peak of 250 and 10 at 1000) and the sky is then treated as source. +""" +import numpy as np + + +def soft_snr_from( + snr: np.ndarray, + snr_noise: float = 2.0, + snr_soft: float = 3.0, + soft_power: float = 2.0, +) -> np.ndarray: + """ + Returns the soft S/N transform ``(x / (x + snr_soft)) ** soft_power`` with ``x = max(S/N - snr_noise, 0)``, + applied value by value. + + Parameters + ---------- + snr + Signal-to-noise values (any shape). Negative values are treated as 0. + snr_noise + S/N at or below which a value counts as noise and maps to 0. + snr_soft + S/N above ``snr_noise`` at which the transform reaches ``0.5 ** soft_power``; it sets where the transform + saturates. + soft_power + Power of the saturating term; higher values suppress faint values relative to bright ones. + + Returns + ------- + The transformed values, in [0, 1), with the same shape as ``snr``. + """ + snr = np.clip(np.asarray(snr, dtype=float), 0.0, None) + x = np.clip(snr - snr_noise, 0.0, None) + return (x / (x + snr_soft)) ** soft_power + + +def adapt_image_soft_from( + snr: np.ndarray, + snr_noise: float = 2.0, + snr_soft: float = 3.0, + soft_power: float = 2.0, + minimum_percent: float = 0.01, +) -> np.ndarray: + """ + Returns the adapt image to give an adaptive regularization (e.g. `AdaptSplit`) so that it adapts to the same + signal as the `HilbertSNR` image mesh: `soft_snr_from` of the S/N map, floored at ``minimum_percent`` of its + maximum (the floor PyAutoGalaxy puts on every adapt image, which keeps the regularization's per-pixel signal + positive). + + The regularization scheme itself is unchanged: `AdaptSplit` still divides its pixel signals by their maximum and + raises them to its ``signal_scale``. Only its input changes. + + Parameters + ---------- + snr + The source's signal-to-noise map before the adapt-image floor (any shape). Negative values are treated as 0. + snr_noise, snr_soft, soft_power + As in `soft_snr_from`; keep them equal to the image mesh's so mesh and regularization adapt to one signal. + minimum_percent + Fraction of the transformed maximum below which values are raised to that floor. + + Returns + ------- + The adapt image values, with the same shape as ``snr``. A map with no value above ``snr_noise`` gives ones + (nothing to adapt to). + """ + soft = soft_snr_from( + snr=snr, snr_noise=snr_noise, snr_soft=snr_soft, soft_power=soft_power + ) + peak = np.max(soft) if soft.size else 0.0 + if peak <= 0.0: + return np.ones_like(soft) + return np.maximum(soft, minimum_percent * peak) diff --git a/test_autoarray/inversion/pixelization/image_mesh/test_hilbert_snr.py b/test_autoarray/inversion/pixelization/image_mesh/test_hilbert_snr.py new file mode 100644 index 000000000..97754872a --- /dev/null +++ b/test_autoarray/inversion/pixelization/image_mesh/test_hilbert_snr.py @@ -0,0 +1,150 @@ +import numpy as np +import pytest + +import autoarray as aa + + +def _reference_probabilities(s, background=0.25, peak=0.05, peak_power=8.0, s_noise=2.0, s0=3.0, power=2.0): + """ + The `peak_share` weighting of the adapt-mesh-weighting study (PyAutoArray#714, + `Science/development/adapt_snr_cap/scripts/mesh_weighting.py`), written out independently. + """ + s = np.clip(np.asarray(s, dtype=float), 0.0, None) + n = s.size + x = np.clip(s - s_noise, 0.0, None) + soft = (x / (x + s0)) ** power + peak_term = (s / s.max()) ** peak_power + return background / n + peak * peak_term / peak_term.sum() + (1.0 - background - peak) * soft / soft.sum() + + +def test__soft_snr_from__values(): + snr = np.array([-5.0, 0.0, 2.0, 3.0, 6.5, 12.0, 40.0]) + + soft = aa.image_mesh.soft_snr_from(snr=snr) + + assert soft == pytest.approx( + [0.0, 0.0, 0.0, 1.0 / 16.0, 0.36, (10.0 / 13.0) ** 2, (38.0 / 41.0) ** 2], 1.0e-8 + ) + + +def test__adapt_image_soft_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) + 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( + [1.0, 1.0, 1.0] + ) + + +def test__weight_map_from__matches_reference_and_sums_to_one(): + rng = np.random.default_rng(1) + s = np.abs(rng.normal(0.0, 1.0, size=500)) + s[100:140] += np.linspace(3.0, 60.0, 40) + + image_mesh = aa.image_mesh.HilbertSNR(pixels=100) + weight_map = image_mesh.weight_map_from(adapt_data=s) + + assert np.sum(weight_map) == pytest.approx(1.0, 1.0e-10) + assert weight_map == pytest.approx(_reference_probabilities(s), 1.0e-10) + + +def test__weight_map_from__scale_free_of_the_peak(): + # The source term uses absolute S/N: adding a much brighter peak elsewhere does not change how the + # source share is split among the other cells. + s = np.zeros(200) + s[20:60] = 10.0 + s_bright = s.copy() + s_bright[150] = 1000.0 + + image_mesh = aa.image_mesh.HilbertSNR(pixels=100) + w = image_mesh.weight_map_from(adapt_data=s) + w_bright = image_mesh.weight_map_from(adapt_data=s_bright) + + soft_10 = (8.0 / 11.0) ** 2 + soft_1000 = (998.0 / 1001.0) ** 2 + + # Every S/N 10 cell keeps the same soft weight; the bright cell takes one cell's (saturated) share, + # not the whole source budget as `(s / max(s)) ** 3.5` would. + assert w_bright[20:60].sum() == pytest.approx( + 0.25 * 40 / 200 + 0.70 * 40 * soft_10 / (40 * soft_10 + soft_1000), 1.0e-6 + ) + assert w_bright[20:60].sum() > 0.7 + assert w[20:60].sum() == pytest.approx(0.25 * 40 / 200 + 0.75, 1.0e-6) + + +def test__weight_map_from__blank_adapt_data_is_uniform(): + image_mesh = aa.image_mesh.HilbertSNR(pixels=10) + + assert image_mesh.weight_map_from(adapt_data=np.zeros(50)) == pytest.approx(np.full(50, 0.02)) + assert image_mesh.weight_map_from(adapt_data=-np.ones(50)) == pytest.approx(np.full(50, 0.02)) + + +def test__shares_validated(): + with pytest.raises(ValueError): + aa.image_mesh.HilbertSNR(pixels=10, background_share=0.9, peak_share=0.2) + + +def _arc_plus_compact(peak): + 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 + radius = np.sqrt(x**2 + y**2) + arc = 10.0 * np.exp(-0.5 * ((radius - 1.5) / 0.1) ** 2) * (x > 0.0) + compact = peak * np.exp(-0.5 * ((y - 1.5) ** 2 + x**2) / 0.05**2) + snr = arc + compact + adapt_data = aa.Array2D(values=snr[~np.asarray(mask)], mask=mask) + return mask, adapt_data, arc, snr + + +def _shares(mesh, mask, arc, snr): + 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) + on_arc = arc[rows, cols] >= 3.0 + on_sky = snr[rows, cols] < 1.0 + return on_arc.mean(), on_sky.mean() + + +def test__image_plane_mesh_grid_from__bright_compact_component_keeps_arc_coverage(): + for peak in (25.0, 250.0, 1000.0): + mask, adapt_data, arc, snr = _arc_plus_compact(peak) + + mesh = np.asarray( + aa.image_mesh.HilbertSNR(pixels=500).image_plane_mesh_grid_from( + mask=mask, adapt_data=adapt_data + ) + ) + arc_share, sky_share = _shares(mesh, mask, arc, snr) + + assert arc_share > 0.5 + assert sky_share < 0.3 + + # The peak-normalised `Hilbert` weighting loses the arc next to a peak S/N of 250. + mask, adapt_data, arc, snr = _arc_plus_compact(250.0) + mesh = np.asarray( + aa.image_mesh.Hilbert(pixels=500, weight_power=3.5, weight_floor=0.01).image_plane_mesh_grid_from( + mask=mask, adapt_data=adapt_data + ) + ) + arc_share, _ = _shares(mesh, mask, arc, snr) + assert arc_share < 0.2 + + +def test__image_plane_mesh_grid_from__negative_values_treated_as_zero(): + mask, adapt_data, arc, snr = _arc_plus_compact(25.0) + rng = np.random.default_rng(3) + noisy = np.asarray(adapt_data.array) + rng.normal(0.0, 1.0, size=adapt_data.shape[0]) + + image_mesh = aa.image_mesh.HilbertSNR(pixels=200) + mesh_raw = image_mesh.image_plane_mesh_grid_from( + mask=mask, adapt_data=aa.Array2D(values=noisy, mask=mask) + ) + mesh_clipped = image_mesh.image_plane_mesh_grid_from( + mask=mask, adapt_data=aa.Array2D(values=np.clip(noisy, 0.0, None), mask=mask) + ) + + assert np.asarray(mesh_raw) == pytest.approx(np.asarray(mesh_clipped), 1.0e-12)