From c6bb06bafddaef8c9eb702c098b22187179411b3 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 20:08:12 +0000 Subject: [PATCH] fix: sparse imaging inversion uses profile-subtracted data (#680) InversionImagingSparse.psf_weighted_data read sparse_operator.weight_map, which is data/noise**2 baked from the ORIGINAL image when the operator was built. A fit with a regular light profile hands the inversion the profile-subtracted data via DatasetInterface, so the sparse data vector D inverted the unsubtracted image (chi-squared/log_evidence badly wrong). psf_weighted_data is now formed from the inversion's own data/noise_map via a gather-only helper: a static [N, Ky, Kx] neighbour slim-index table (built once with NumPy from the mask) gathers data/noise**2 with a zero sentinel. A native-array scatter (.at[].set) formulation reproducibly hung the rectangular_mge vmap likelihood on CPU; the gather form does not. Witness: sparse vs dense agree on D, chi-squared and log_evidence to 1e-10 with a regular light profile (NumPy, JAX eager and jax.jit); the all-linear control is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016nhQ8MFwfRFgwBVbYjP9Xd --- .../imaging/inversion_imaging_util.py | 81 +++++++ .../inversion/inversion/imaging/sparse.py | 22 +- .../inversion/imaging/test_imaging.py | 206 ++++++++++++++++++ 3 files changed, 305 insertions(+), 4 deletions(-) diff --git a/autoarray/inversion/inversion/imaging/inversion_imaging_util.py b/autoarray/inversion/inversion/imaging/inversion_imaging_util.py index b4ce10d7c..808016fdf 100644 --- a/autoarray/inversion/inversion/imaging/inversion_imaging_util.py +++ b/autoarray/inversion/inversion/imaging/inversion_imaging_util.py @@ -4,6 +4,87 @@ from typing import Optional, List, Tuple +def psf_weighted_data_neighbour_indexes_from( + native_index_for_slim_index: np.ndarray, + shape_native, + kernel_shape_native, +) -> np.ndarray: + """ + Returns, for every unmasked image pixel, the slim indexes of the pixels a PSF kernel centred on it + covers, as an integer array of shape [image_pixels, Ky, Kx]. + + Kernel cells that fall on a masked pixel or outside the native array are given the sentinel index + `image_pixels`, which `psf_weighted_data_via_slim_from` maps to a zero weight. The table depends only + on the mask and kernel shape, so it is built once with NumPy and is a constant under `jax.jit`. + + Parameters + ---------- + native_index_for_slim_index + An array of shape [image_pixels, 2] mapping every slim index to its native (y,x) pixel. + shape_native + The 2D native shape of the mask. + kernel_shape_native + The 2D shape (Ky, Kx) of the PSF kernel. + """ + native_index_for_slim_index = np.asarray(native_index_for_slim_index) + + n_slim = native_index_for_slim_index.shape[0] + Ky, Kx = (int(k) for k in kernel_shape_native) + ph, pw = Ky // 2, Kx // 2 + + slim_for_native = np.full( + (int(shape_native[0]) + 2 * ph, int(shape_native[1]) + 2 * pw), + n_slim, + dtype=np.int64, + ) + slim_for_native[ + native_index_for_slim_index[:, 0] + ph, native_index_for_slim_index[:, 1] + pw + ] = np.arange(n_slim) + + ys = native_index_for_slim_index[:, 0] + ph + xs = native_index_for_slim_index[:, 1] + pw + + Y = ys[:, None, None] + (np.arange(Ky) - ph)[None, :, None] + X = xs[:, None, None] + (np.arange(Kx) - pw)[None, None, :] + + return slim_for_native[Y, X] + + +def psf_weighted_data_via_slim_from( + data: np.ndarray, + noise_map: np.ndarray, + kernel_native: np.ndarray, + neighbour_indexes: np.ndarray, + xp=np, +) -> np.ndarray: + """ + Returns `psf_weighted_data` (see `psf_weighted_data_from`) directly from the slim `data` and `noise_map` + of a masked dataset, which may have light profiles subtracted. + + The weights `data / noise_map**2` are gathered through the precomputed `neighbour_indexes` table + (`psf_weighted_data_neighbour_indexes_from`), whose sentinel entries read an appended zero, and + correlated with the kernel. This equals `psf_weighted_data_from` of the native weight map with zeros at + masked pixels, but is gather-only: no native array is scattered, so it stays cheap when the data is + traced under `jax.jit` or batched under `jax.vmap`. + + Parameters + ---------- + data + The slim (masked, 1D) data values. + noise_map + The slim (masked, 1D) noise-map values. + kernel_native + The two dimensional PSF kernel that `psf_weighted_data` encodes the convolution of. + neighbour_indexes + The [image_pixels, Ky, Kx] slim-index table from `psf_weighted_data_neighbour_indexes_from`. + """ + weights = xp.asarray(data) / xp.asarray(noise_map) ** 2 + weights = xp.concatenate([weights, xp.zeros(1, dtype=weights.dtype)]) + + patches = weights[neighbour_indexes] # (N, Ky, Kx) + return xp.sum(patches * xp.asarray(kernel_native)[None, :, :], axis=(1, 2)) + + def psf_weighted_data_from( weight_map_native: np.ndarray, kernel_native: np.ndarray, diff --git a/autoarray/inversion/inversion/imaging/sparse.py b/autoarray/inversion/inversion/imaging/sparse.py index b628d18f1..bf7cbfbde 100644 --- a/autoarray/inversion/inversion/imaging/sparse.py +++ b/autoarray/inversion/inversion/imaging/sparse.py @@ -60,10 +60,24 @@ def psf_weighted_data(self): "(convolve_over_sample_size > 1)." ) - return inversion_imaging_util.psf_weighted_data_from( - weight_map_native=self.dataset.sparse_operator.weight_map.array, - kernel_native=self.psf.kernel.native, - native_index_for_slim_index=self.data.mask.derive_indexes.native_for_slim, + # The weight map is formed from this inversion's own `data` and `noise_map`, NOT the + # `sparse_operator.weight_map` baked when the operator was built. A fit hands the inversion + # a `DatasetInterface` whose `data` has the ordinary light profiles subtracted, while the + # operator still carries the original image's weights (PyAutoArray#680). Only the operator's + # noise-dependent curvature terms are reused. + neighbour_indexes = ( + inversion_imaging_util.psf_weighted_data_neighbour_indexes_from( + native_index_for_slim_index=self.data.mask.derive_indexes.native_for_slim, + shape_native=self.data.mask.shape_native, + kernel_shape_native=self.psf.kernel.shape_native, + ) + ) + + return inversion_imaging_util.psf_weighted_data_via_slim_from( + data=self.data.array, + noise_map=self.noise_map.array, + kernel_native=self.psf.kernel.native.array, + neighbour_indexes=neighbour_indexes, xp=self._xp, ) diff --git a/test_autoarray/inversion/inversion/imaging/test_imaging.py b/test_autoarray/inversion/inversion/imaging/test_imaging.py index f956dbdb9..40dc7ceb0 100644 --- a/test_autoarray/inversion/inversion/imaging/test_imaging.py +++ b/test_autoarray/inversion/inversion/imaging/test_imaging.py @@ -313,6 +313,212 @@ def counted(self, *args, **kwargs): ) +def _profile_subtracted_data_from(masked_imaging): + """ + The data of `masked_imaging` with a PSF-blurred smooth "regular light profile" subtracted, as a fit with + an ordinary lens light profile and a pixelized source hands to its inversion. + """ + grid = masked_imaging.grids.lp.array + profile = aa.Array2D( + values=5.0 * np.exp(-(grid[:, 0] ** 2 + grid[:, 1] ** 2) / 0.5), + mask=masked_imaging.mask, + ) + blurred = masked_imaging.psf.convolved_image_from( + image=profile, blurring_image=None + ) + return masked_imaging.data - blurred + + +def _sparse_vs_dense_terms_from(inversion, data, noise_map, mapper): + """ + The data vector D, chi-squared and log evidence of `inversion`, the quantities the sparse and dense + inversions must agree on. + """ + from autoarray.fit import fit_util + + model = np.asarray(inversion.mapped_reconstructed_operated_data_dict[mapper].array) + chi_squared = float(np.sum(((np.asarray(data) - model) / noise_map) ** 2)) + noise_normalization = float(np.sum(np.log(2.0 * np.pi * noise_map**2))) + log_evidence = fit_util.log_evidence_from( + chi_squared=chi_squared, + regularization_term=float(inversion.regularization_term), + log_curvature_regularization_term=float( + inversion.log_det_curvature_reg_matrix_term + ), + log_regularization_term=float(inversion.log_det_regularization_matrix_term), + noise_normalization=noise_normalization, + ) + return np.asarray(inversion.data_vector), chi_squared, log_evidence + + +def test__psf_weighted_data_via_slim__matches_native_weight_map_path( + masked_imaging_7x7, +): + """ + The gather-only `psf_weighted_data_via_slim_from` equals `psf_weighted_data_from` applied to the native + weight map `data / noise**2` with zeros at masked pixels. + """ + from autoarray.inversion.inversion.imaging import inversion_imaging_util + + mask = masked_imaging_7x7.mask + native_for_slim = mask.derive_indexes.native_for_slim + kernel = np.asarray(masked_imaging_7x7.psf.kernel.native.array) + + data = np.asarray(_profile_subtracted_data_from(masked_imaging_7x7).array) + noise_map = np.asarray(masked_imaging_7x7.noise_map.array) + + weight_map_native = np.zeros(mask.shape_native) + weight_map_native[native_for_slim[:, 0], native_for_slim[:, 1]] = ( + data / noise_map**2 + ) + + expected = inversion_imaging_util.psf_weighted_data_from( + weight_map_native=weight_map_native, + kernel_native=kernel, + native_index_for_slim_index=native_for_slim, + ) + + neighbour_indexes = ( + inversion_imaging_util.psf_weighted_data_neighbour_indexes_from( + native_index_for_slim_index=native_for_slim, + shape_native=mask.shape_native, + kernel_shape_native=kernel.shape, + ) + ) + + assert inversion_imaging_util.psf_weighted_data_via_slim_from( + data=data, + noise_map=noise_map, + kernel_native=kernel, + neighbour_indexes=neighbour_indexes, + ) == pytest.approx(expected, rel=1.0e-14, abs=1.0e-14) + + +@requires_jax +@pytest.mark.parametrize("subtract_profile", [True, False]) +def test__sparse__profile_subtracted_data__matches_mapping_inversion( + masked_imaging_7x7, delaunay_mapper_9_3x3, subtract_profile +): + """ + PyAutoArray#680: the sparse operator is built once from the ORIGINAL image, but a fit with a regular + light profile hands the inversion the profile-subtracted data. The sparse data vector must be formed + from that subtracted data, so the sparse and dense inversions agree on D, chi-squared and log evidence. + The `subtract_profile=False` leg is the all-linear control, which agreed before the fix too. + """ + mapper = delaunay_mapper_9_3x3 + settings = aa.Settings(use_positive_only_solver=False) + + data = ( + _profile_subtracted_data_from(masked_imaging_7x7) + if subtract_profile + else masked_imaging_7x7.data + ) + noise_map = np.asarray(masked_imaging_7x7.noise_map.array) + + sparse_operator = masked_imaging_7x7.apply_sparse_operator().sparse_operator + + inversion_sparse = aa.Inversion( + dataset=aa.DatasetInterface( + data=data, + noise_map=masked_imaging_7x7.noise_map, + grids=masked_imaging_7x7.grids, + psf=masked_imaging_7x7.psf, + sparse_operator=sparse_operator, + ), + linear_obj_list=[mapper], + settings=settings, + ) + inversion_mapping = aa.Inversion( + dataset=aa.DatasetInterface( + data=data, + noise_map=masked_imaging_7x7.noise_map, + grids=masked_imaging_7x7.grids, + psf=masked_imaging_7x7.psf, + ), + linear_obj_list=[mapper], + settings=settings, + ) + + assert isinstance(inversion_sparse, InversionImagingSparse) + assert isinstance(inversion_mapping, aa.InversionImagingMapping) + + d_sparse, chi_squared_sparse, log_evidence_sparse = _sparse_vs_dense_terms_from( + inversion_sparse, data.array, noise_map, mapper + ) + d_mapping, chi_squared_mapping, log_evidence_mapping = _sparse_vs_dense_terms_from( + inversion_mapping, data.array, noise_map, mapper + ) + + assert np.max(np.abs(d_sparse - d_mapping)) <= 1.0e-10 * np.max(np.abs(d_mapping)) + assert chi_squared_sparse == pytest.approx(chi_squared_mapping, rel=1.0e-10) + assert log_evidence_sparse == pytest.approx(log_evidence_mapping, rel=1.0e-10) + + +@requires_jax +def test__sparse__profile_subtracted_data__matches_mapping_inversion__jax_jit( + masked_imaging_7x7, delaunay_mapper_9_3x3 +): + """ + The JAX path of PyAutoArray#680, eager and under `jax.jit` with the subtracted data traced, as a + production fit computes it. + """ + import jax + + jax.config.update("jax_enable_x64", True) + + import jax.numpy as jnp + + mapper = delaunay_mapper_9_3x3 + mapper_jax = type(mapper)( + interpolator=mapper.interpolator, + regularization=mapper.regularization, + image_plane_mesh_grid=mapper.image_plane_mesh_grid, + xp=jnp, + ) + settings = aa.Settings(use_positive_only_solver=False) + + data = _profile_subtracted_data_from(masked_imaging_7x7) + mask = masked_imaging_7x7.mask + sparse_operator = masked_imaging_7x7.apply_sparse_operator().sparse_operator + + def data_vector_from(data_values): + inversion = aa.Inversion( + dataset=aa.DatasetInterface( + data=aa.Array2D(values=data_values, mask=mask), + noise_map=masked_imaging_7x7.noise_map, + grids=masked_imaging_7x7.grids, + psf=masked_imaging_7x7.psf, + sparse_operator=sparse_operator, + ), + linear_obj_list=[mapper_jax], + settings=settings, + xp=jnp, + ) + return inversion.data_vector + + inversion_mapping = aa.Inversion( + dataset=aa.DatasetInterface( + data=data, + noise_map=masked_imaging_7x7.noise_map, + grids=masked_imaging_7x7.grids, + psf=masked_imaging_7x7.psf, + ), + linear_obj_list=[mapper], + settings=settings, + ) + d_mapping = np.asarray(inversion_mapping.data_vector) + + data_values = jnp.asarray(data.array) + + for d_sparse in ( + np.asarray(data_vector_from(data_values)), + np.asarray(jax.jit(data_vector_from)(data_values)), + ): + assert np.max(np.abs(d_sparse - d_mapping)) <= 1.0e-10 * np.max( + np.abs(d_mapping) + ) + + def _mapper_with_invalid_slots_from(mapper): """ Returns a copy of `mapper` whose stencil table carries every kind of entry