From 0bef0a980707f72ee23c137a08de2745b9e9439d Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Mon, 2 Nov 2026 15:35:39 +0000 Subject: [PATCH] feat: source-plane magnification maps (mesh + square pixels) LensCalc.source_plane_magnification_from traces image sub-pixels and bins the image area into square source pixels; plot_magnification_source_plane colours a reconstruction's mesh by Mapper.mesh_magnification; plot_magnification_source_plane_grid plots the square-pixel map with constant-mu contours. Also drops the stray config colour-bar unit from plot_magnification_2d. Arc phase 8b (PyAutoArray#673). Co-Authored-By: Claude Opus 5.5 --- autogalaxy/galaxy/plot/galaxies_plots.py | 194 +++++++++++++++++- autogalaxy/operate/lens_calc.py | 81 +++++++- autogalaxy/plot/__init__.py | 2 + .../galaxy/plot/test_galaxies_plotter.py | 27 +++ .../operate/test_area_magnification.py | 47 +++++ 5 files changed, 349 insertions(+), 2 deletions(-) diff --git a/autogalaxy/galaxy/plot/galaxies_plots.py b/autogalaxy/galaxy/plot/galaxies_plots.py index 7c03befb4..69901045d 100644 --- a/autogalaxy/galaxy/plot/galaxies_plots.py +++ b/autogalaxy/galaxy/plot/galaxies_plots.py @@ -3,7 +3,7 @@ import autoarray as aa from autogalaxy.galaxy.galaxies import Galaxies -from autogalaxy.util.plot_utils import _to_lines, _to_positions, plot_array, plot_grid, _save_subplot, _critical_curves_from +from autogalaxy.util.plot_utils import _to_lines, _to_positions, plot_array, plot_grid, _save_subplot, _critical_curves_from, _caustics_from from autoarray.plot.utils import subplots, hide_unused_axes, conf_subplot_figsize, tight_layout from autogalaxy import exc @@ -347,6 +347,7 @@ def plot_magnification_2d( vmin=vmin, vmax=vmax, lines=lines, + cb_unit="", ax=ax, ) @@ -400,3 +401,194 @@ def _magnification_contours(ax, log_abs_mu_array, grid, contour_levels): ax.set_xlim(xlim) ax.set_ylim(ylim) + + +def plot_magnification_source_plane( + mapper, + mass_obj=None, + grid: aa.type.Grid2DLike = None, + include_caustics: bool = True, + tangential_caustics=None, + radial_caustics=None, + vmin=None, + vmax=None, + title: str = r"Source-Plane Magnification $\mu$", + colormap="default", + output_path=None, + output_filename: str = "magnification_source_plane", + output_format=None, + ax=None, +): + """Plot the magnification of every pixel of a source reconstruction's mesh. + + Each mesh pixel is coloured by ``mapper.mesh_magnification``: the image-plane area that maps to it divided by + its source-plane area, i.e. how much the lens magnifies that region of the source, summed over all of its images. + The colour scale is logarithmic, because the magnification is largest next to the caustics. Pixels with no image + area (or no source-plane area) have zero magnification and are left blank. + + It is the source-plane counterpart of ``plot_magnification_2d``. For parametric or Multi Gaussian Expansion + sources, which have no mesh, ``plot_magnification_source_plane_grid`` makes the same map on square pixels. + + Parameters + ---------- + mapper + The mapper of the pixelized source, e.g. ``inversion.cls_list_from(cls=aa.Mapper)[0]``. + mass_obj + The mass object (``Galaxies`` or a ``Tracer``) the caustics are computed from. ``None`` draws no caustics. + grid + The image-plane grid passed to the caustic calculation (used by the ``"marching_squares"`` method). + include_caustics + If ``True`` and ``mass_obj`` is given (or caustics are passed in), overlay the caustics. + tangential_caustics, radial_caustics + Pre-computed caustics; ``None`` computes them from ``mass_obj``. + vmin, vmax + Explicit colour-bar limits on the magnification. ``None`` uses the 1st and 99th percentiles of the non-zero + pixels. + title + Title displayed above the panel. + colormap + Matplotlib colormap name, or ``"default"``. + output_path + Directory in which to save the figure. ``None`` shows it instead. + output_filename + Stem of the output file name. + output_format + File format, e.g. ``"png"``. + ax + An existing ``Axes`` to draw into. When given the figure is not saved; the caller saves it. + """ + from autoarray.plot.inversion import plot_inversion_reconstruction + + mesh_magnification = np.asarray(mapper.mesh_magnification, dtype=float) + + positive = mesh_magnification[mesh_magnification > 0.0] + if vmin is None and positive.size: + vmin = float(np.percentile(positive, 1.0)) + if vmax is None and positive.size: + vmax = float(np.percentile(positive, 99.0)) + + lines = None + if include_caustics and (mass_obj is not None or tangential_caustics is not None): + if tangential_caustics is None: + tangential_caustics, radial_caustics = _caustics_from(mass_obj, grid) + lines = _to_lines(tangential_caustics, radial_caustics) + + plot_inversion_reconstruction( + pixel_values=mesh_magnification, + mapper=mapper, + ax=ax, + title=title, + colormap=None if colormap == "default" else colormap, + vmin=vmin, + vmax=vmax, + use_log10=True, + cb_unit="", + zoom_to_brightest=False, + lines=lines, + output_path=output_path, + output_filename=output_filename, + output_format=output_format, + ) + + +def plot_magnification_source_plane_grid( + mass_obj, + grid: aa.type.Grid2DLike, + source_shape_native=(50, 50), + source_extent=None, + sub_size: int = 16, + contour_levels=(2.0, 5.0, 10.0, 20.0, 50.0, 100.0), + include_caustics: bool = True, + tangential_caustics=None, + radial_caustics=None, + vmin=None, + vmax=None, + title: str = r"Source-Plane Magnification $\log_{10}\mu$", + colormap="default", + output_path=None, + output_filename: str = "magnification_source_plane_grid", + output_format=None, + ax=None, +): + """Plot the source-plane magnification on square pixels, for sources without a mesh. + + The map is computed by ``LensCalc.source_plane_magnification_from`` (image-plane sub-pixels traced to the + source plane and binned into square source pixels) and plotted as log10 mu with labelled contours of constant mu and, + optionally, the caustics, following the conventions of ``plot_magnification_2d``. Source pixels no image area + lands in are shown at the bottom of the colour scale. + + This is the map to use for parametric and Multi Gaussian Expansion sources; for a pixelized source, + ``plot_magnification_source_plane`` shows the magnification on the reconstruction's own mesh. + + Parameters + ---------- + mass_obj + The mass object (``Galaxy``, ``Galaxies`` or a ``Tracer``). + grid + The image-plane grid whose mask defines the image area that is traced. + source_shape_native, source_extent, sub_size + See ``LensCalc.source_plane_magnification_from``. + contour_levels + The mu values at which contour lines are drawn. ``None`` or an empty sequence draws no contours. + include_caustics + If ``True``, overlay the tangential and radial caustics. + tangential_caustics, radial_caustics + Pre-computed caustics; ``None`` computes them when ``include_caustics`` is ``True``. + vmin, vmax + Explicit colour-bar limits in log10 mu. ``None`` uses the 1st and 99th percentiles of the non-zero pixels. + title, colormap, output_path, output_filename, output_format, ax + As for ``plot_magnification_2d``. + """ + from autogalaxy.operate.lens_calc import LensCalc + + magnification = LensCalc.from_mass_obj(mass_obj).source_plane_magnification_from( + mask=grid.mask, + source_shape_native=source_shape_native, + source_extent=source_extent, + sub_size=sub_size, + ) + + values = np.asarray(magnification.slim.array, dtype=float) + positive = values > 0.0 + + log_mu = np.full(values.shape, np.nan) + log_mu[positive] = np.log10(values[positive]) + + if vmin is None: + vmin = float(np.percentile(log_mu[positive], 1.0)) if np.any(positive) else 0.0 + if vmax is None: + vmax = float(np.percentile(log_mu[positive], 99.0)) if np.any(positive) else 1.0 + + log_mu[~positive] = vmin + + log_mu_array = aa.Array2D(values=log_mu, mask=magnification.mask) + source_grid = aa.Grid2D.from_mask(mask=magnification.mask) + + lines = None + if include_caustics: + if tangential_caustics is None: + tangential_caustics, radial_caustics = _caustics_from(mass_obj, grid) + lines = _to_lines(tangential_caustics, radial_caustics) + + owns_figure = ax is None + if owns_figure: + fig, ax = subplots(1, 1, figsize=conf_subplot_figsize(1, 1)) + + plot_array( + array=log_mu_array, + title=title, + colormap=colormap, + vmin=vmin, + vmax=vmax, + lines=lines, + cb_unit="", + ax=ax, + ) + + _magnification_contours( + ax=ax, log_abs_mu_array=log_mu_array, grid=source_grid, contour_levels=contour_levels + ) + + if owns_figure: + tight_layout() + _save_subplot(fig, output_path, output_filename, output_format) diff --git a/autogalaxy/operate/lens_calc.py b/autogalaxy/operate/lens_calc.py index 113e3e40a..cdf731bc3 100644 --- a/autogalaxy/operate/lens_calc.py +++ b/autogalaxy/operate/lens_calc.py @@ -21,7 +21,7 @@ import logging import warnings import numpy as np -from typing import List, Tuple, Union +from typing import List, Optional, Tuple, Union from autonerves import conf @@ -970,6 +970,85 @@ def area_magnification_list_from( for image_mask in self.image_masks_from(mask=mask) ] + def source_plane_magnification_from( + self, + mask: aa.Mask2D, + source_shape_native: Tuple[int, int] = (50, 50), + source_extent: Optional[Tuple[float, float, float, float]] = None, + sub_size: int = 16, + ) -> aa.Array2D: + """ + Returns the source-plane magnification on a uniform grid of square source-plane pixels. + + Every unmasked pixel of `mask` is split into `sub_size x sub_size` sub-pixels, which are traced to the source + plane (the grid minus the deflection angles). The image-plane area landing in each square source-plane pixel, + divided by that pixel's area, is its magnification: how much the lens magnifies that region of the source, + summed over all of its images. It is the square-pixel counterpart of a pixelized source's + `Mapper.mesh_magnification`. + + The map is a count of traced sub-pixels, so it is noisy where few land in a source pixel: a source pixel of + magnification `mu` and side `s` receives about `mu * s**2 / (pixel_scale / sub_size)**2` of them. The + defaults give a few hundred for `mu ~ 5` on a 0.1" image over a ~2.5" source-plane box. + + Only image-plane area inside `mask` is counted, so the mask should contain every image of the source region + of interest; a source pixel whose images fall partly outside it is underestimated. Source pixels no image + area lands in have a magnification of zero. + + Parameters + ---------- + mask + The image-plane mask whose unmasked area is traced to the source plane. + source_shape_native + The number of square source-plane pixels along (y, x). The pixels are square, so the shorter side of the + extent is padded. + source_extent + The `[xmin, xmax, ymin, ymax]` of the source-plane grid. `None` uses the box containing the central 98% + of the traced sub-pixels along each axis. + sub_size + The number of sub-pixels per image pixel along each axis. + """ + image_grid = aa.Grid2D.from_mask(mask=mask, over_sample_size=sub_size) + sub_grid = np.asarray(image_grid.over_sampled.array) + + deflections = self.deflections_yx_2d_from( + grid=aa.Grid2DIrregular(values=sub_grid) + ) + traced = sub_grid - np.asarray(deflections) + + if source_extent is None: + y_lo, y_hi = np.percentile(traced[:, 0], [1.0, 99.0]) + x_lo, x_hi = np.percentile(traced[:, 1], [1.0, 99.0]) + else: + x_lo, x_hi, y_lo, y_hi = source_extent + + pixel_scale = max( + (y_hi - y_lo) / source_shape_native[0], + (x_hi - x_lo) / source_shape_native[1], + ) + origin = (0.5 * (y_lo + y_hi), 0.5 * (x_lo + x_hi)) + half_y = 0.5 * pixel_scale * source_shape_native[0] + half_x = 0.5 * pixel_scale * source_shape_native[1] + + sub_area = mask.pixel_scales[0] * mask.pixel_scales[1] / sub_size**2 + + image_area, _, _ = np.histogram2d( + traced[:, 0], + traced[:, 1], + bins=source_shape_native, + range=[ + [origin[0] - half_y, origin[0] + half_y], + [origin[1] - half_x, origin[1] + half_x], + ], + weights=np.full(traced.shape[0], sub_area), + ) + + # `histogram2d` puts the lowest y in its first row; an `Array2D` puts the highest y first. + return aa.Array2D.no_mask( + values=image_area[::-1, :] / pixel_scale**2, + pixel_scales=float(pixel_scale), + origin=origin, + ) + def contour_list_from(self, grid, contour_array): grid_contour = aa.Grid2DContour( grid=grid, diff --git a/autogalaxy/plot/__init__.py b/autogalaxy/plot/__init__.py index 47f618d2c..262196064 100644 --- a/autogalaxy/plot/__init__.py +++ b/autogalaxy/plot/__init__.py @@ -31,6 +31,8 @@ subplot_galaxies, subplot_galaxy_images, plot_magnification_2d, + plot_magnification_source_plane, + plot_magnification_source_plane_grid, ) from autogalaxy.galaxy.plot.adapt_plots import ( diff --git a/test_autogalaxy/galaxy/plot/test_galaxies_plotter.py b/test_autogalaxy/galaxy/plot/test_galaxies_plotter.py index 19f59c646..83137e068 100644 --- a/test_autogalaxy/galaxy/plot/test_galaxies_plotter.py +++ b/test_autogalaxy/galaxy/plot/test_galaxies_plotter.py @@ -77,3 +77,30 @@ def test__plot_magnification_2d__contours_at_constant_mu_levels_in_range(): assert _contour_levels_on(ax) == [] plt.close("all") + + +def test__plot_magnification_source_plane__mesh_output( + rectangular_mapper_7x7_3x3, galaxies_x2_7x7, grid_2d_7x7, plot_path, plot_patch +): + aplt.plot_magnification_source_plane( + mapper=rectangular_mapper_7x7_3x3, + mass_obj=galaxies_x2_7x7, + grid=grid_2d_7x7, + output_path=plot_path, + output_format="png", + ) + assert str(plot_path / "magnification_source_plane.png") in plot_patch.paths + + +def test__plot_magnification_source_plane_grid__output( + galaxies_x2_7x7, grid_2d_7x7, plot_path, plot_patch +): + aplt.plot_magnification_source_plane_grid( + mass_obj=galaxies_x2_7x7, + grid=grid_2d_7x7, + source_shape_native=(10, 10), + sub_size=2, + output_path=plot_path, + output_format="png", + ) + assert str(plot_path / "magnification_source_plane_grid.png") in plot_patch.paths diff --git a/test_autogalaxy/operate/test_area_magnification.py b/test_autogalaxy/operate/test_area_magnification.py index a2e4788fe..dae9c84f5 100644 --- a/test_autogalaxy/operate/test_area_magnification.py +++ b/test_autogalaxy/operate/test_area_magnification.py @@ -154,3 +154,50 @@ def test__source_plane_area__correct_when_over_sampling_is_capped(monkeypatch): capped = lens_calc.source_plane_area_from(mask=mask, sub_size=4) assert capped == pytest.approx(uncapped, rel=1.0e-3) + + +def test__source_plane_magnification__sis_total_magnification_inside_the_caustic(): + """ + A source at distance `beta < theta_E` from a singular isothermal sphere has two images, at `beta + theta_E` and + `theta_E - beta`, with magnifications `(beta + theta_E) / beta` and `(theta_E - beta) / beta`. Their sum, + `2 theta_E / beta`, is the source-plane magnification, provided the mask contains both images. + """ + mask = aa.Mask2D.circular(shape_native=(120, 120), pixel_scales=0.05, radius=2.9) + + magnification = _lens_calc().source_plane_magnification_from( + mask=mask, + source_shape_native=(60, 60), + source_extent=(-0.9, 0.9, -0.9, 0.9), + sub_size=8, + ) + + grid = np.asarray(aa.Grid2D.from_mask(mask=magnification.mask).array) + beta = np.hypot(grid[:, 0], grid[:, 1]) + values = np.asarray(magnification.slim.array) + + assert magnification.shape_native == (60, 60) + + for radius in (0.4, 0.6, 0.8): + ring = np.abs(beta - radius) < 0.03 + assert np.median(values[ring]) == pytest.approx( + 2.0 * EINSTEIN_RADIUS / radius, rel=0.02 + ) + + +def test__source_plane_magnification__area_is_conserved(): + mask = aa.Mask2D.circular(shape_native=(60, 60), pixel_scales=0.1, radius=2.5) + + magnification = _lens_calc().source_plane_magnification_from( + mask=mask, + source_shape_native=(40, 40), + source_extent=(-2.0, 2.0, -2.0, 2.0), + sub_size=4, + ) + + source_pixel_area = magnification.pixel_scales[0] ** 2 + image_area = mask.pixels_in_mask * 0.1**2 + + # every traced sub-pixel of this mask lands inside the 4" box + assert np.sum(magnification.slim.array) * source_pixel_area == pytest.approx( + image_area, rel=1.0e-10 + )