From cf1d621c7372561d7e9afd1473fe06428b8a4b42 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 19:03:50 +0000 Subject: [PATCH 1/4] feat: interpolated view of Delaunay/kNN source reconstructions (#700) Delaunay/kNN reconstructions are drawn as flat-shaded triangles, which show where the mesh spends resolution but are not the interpolant the likelihood uses between vertices (Discussion PyAutoLabs/.github#46). - plot_inversion_reconstruction / plot_mapper gain `interpolated=True`: a fresh interpolator of the mapper's own type (same mesh and mesh_grid) is evaluated on a uniform plot grid over the panel extent and drawn with imshow, so the figure equals mapping_matrix @ reconstruction. Barycentric for Delaunay, kNN / Sibson weights for those meshes; outside the mesh hull is transparent; log scales clip to the norm floor; rectangular meshes ignore the flag. - interpolated_reconstruction_from / mapper_has_interpolated_view helpers. - inversion_#.png panel 11: "Source Reconstruction (Interpolated)" for irregular meshes. - Flat triangles stay the default; the _plot_delaunay docstring now says plainly what they show and what they do not. - config: visualize/general.yaml inversion.interpolated_pixels (400) and plots.yaml fit.subplot_fit_source_interpolated (false), read by the PyAutoLens fit plotters. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016nhQ8MtKvVD9fBkNBqcMb4 --- autoarray/config/visualize/general.yaml | 1 + autoarray/config/visualize/plots.yaml | 1 + autoarray/inversion/plot/inversion_plots.py | 25 ++ autoarray/inversion/plot/mapper_plots.py | 10 + autoarray/plot/inversion.py | 232 +++++++++++++++++- .../plot/test_inversion_interpolated.py | 212 ++++++++++++++++ 6 files changed, 474 insertions(+), 7 deletions(-) create mode 100644 test_autoarray/plot/test_inversion_interpolated.py diff --git a/autoarray/config/visualize/general.yaml b/autoarray/config/visualize/general.yaml index 707a549c1..2717e2dbb 100644 --- a/autoarray/config/visualize/general.yaml +++ b/autoarray/config/visualize/general.yaml @@ -11,6 +11,7 @@ inversion: total_mappings: 5 # The maximum number of source clumps drawn by subplot_mappings. mappings_threshold: 0.5 # A source pixel joins a clump if its reconstructed value exceeds this fraction of the reconstruction's maximum. mappings_min_pixels: 3 # Connected groups of source pixels smaller than this are not drawn as a clump. + interpolated_pixels: 400 # Interpolated source-reconstruction panels (Delaunay / kNN meshes) evaluate the likelihood's interpolant on a grid of this many pixels per side. zoom: plane_percent: 0.01 # Fraction of peak image brightness used to determine the plotted plane extent. inversion_percent: 0.01 # Plots of an Inversion's reconstruction use the reconstructed data's bright value multiplied by this factor. diff --git a/autoarray/config/visualize/plots.yaml b/autoarray/config/visualize/plots.yaml index d18680029..e11ac7080 100644 --- a/autoarray/config/visualize/plots.yaml +++ b/autoarray/config/visualize/plots.yaml @@ -10,6 +10,7 @@ imaging: # Settings for plots of imaging datas fit: # Settings for plots of all fits (e.g. FitImaging, FitInterferometer). subplot_fit: true # Plot subplot of all fit quantities for any dataset (e.g. the model data, residual-map, etc.)? subplot_fit_log10: false # Plot subplot of all fit quantities for any dataset using log10 color maps (e.g. the model data, residual-map, etc.)? + subplot_fit_source_interpolated: false # In fit.png, draw the mid-zoom source panel as the interpolated reconstruction the likelihood uses (Delaunay/KNN meshes), instead of flat triangles? data: false # Plot individual plots of the data? noise_map: false # Plot individual plots of the noise-map? signal_to_noise_map: false # Plot individual plots of the signal-to-noise-map? diff --git a/autoarray/inversion/plot/inversion_plots.py b/autoarray/inversion/plot/inversion_plots.py index cde4de88b..a0d06e359 100644 --- a/autoarray/inversion/plot/inversion_plots.py +++ b/autoarray/inversion/plot/inversion_plots.py @@ -21,6 +21,7 @@ tight_layout, ) from autoarray.inversion.plot.mapper_plots import plot_mapper +from autoarray.plot.inversion import mapper_has_interpolated_view from autoarray.structures.arrays.uniform_2d import Array2D @@ -55,6 +56,11 @@ def subplot_of_mapper( """ 3×4 subplot showing all pixelization diagnostics for one mapper. + For Delaunay / kNN / natural-neighbour meshes the last panel (11) shows the + reconstruction as the likelihood's interpolant ("Source Reconstruction + (Interpolated)"), alongside the flat-triangle panels that show the mesh + resolution. Rectangular meshes leave it empty. + Parameters ---------- inversion @@ -257,6 +263,25 @@ def _recon_array(): except (TypeError, Exception): pass + # panel 11: the reconstruction the likelihood uses between mesh vertices. + # Panels 4-5 draw irregular meshes as flat triangles (one colour each) to + # show where the mesh spends resolution; this panel evaluates the mapper's + # own interpolant on a uniform grid. Rectangular meshes have no separate + # interpolated view, so the panel is left empty and hidden. + if mapper_has_interpolated_view(mapper): + plot_mapper( + mapper, + solution_vector=pixel_values, + ax=axes[11], + title=_pf("Source Reconstruction (Interpolated)"), + colormap=colormap, + use_log10=use_log10, + vmax=recon_vmax, + zoom_to_brightest=True, + interpolated=True, + lines=lines, + ) + hide_unused_axes(axes) tight_layout() subplot_save(fig, output_path, f"{output_filename}_{mapper_index}", output_format) diff --git a/autoarray/inversion/plot/mapper_plots.py b/autoarray/inversion/plot/mapper_plots.py index c3028bedf..fbf9716a7 100644 --- a/autoarray/inversion/plot/mapper_plots.py +++ b/autoarray/inversion/plot/mapper_plots.py @@ -36,6 +36,8 @@ def plot_mapper( title: str = "Pixelization Mesh (Source-Plane)", zoom_to_brightest: bool = True, zoom_extent_scale: float = 1.0, + interpolated: bool = False, + interpolated_shape_native=None, ax=None, ): """ @@ -74,6 +76,12 @@ def plot_mapper( Figure title. zoom_to_brightest Zoom the source plane to the brightest region. + interpolated + For Delaunay / kNN / natural-neighbour meshes, draw the interpolant the + likelihood uses (the mapper's own interpolator evaluated on a uniform + grid) instead of flat-shaded triangles. Ignored for rectangular meshes. + interpolated_shape_native + ``(y, x)`` shape of the interpolation grid; ``None`` reads the config. ax Existing ``Axes`` to draw onto. """ @@ -89,6 +97,8 @@ def plot_mapper( vmax=vmax, zoom_to_brightest=zoom_to_brightest, zoom_extent_scale=zoom_extent_scale, + interpolated=interpolated, + interpolated_shape_native=interpolated_shape_native, lines=numpy_lines(lines), line_colors=line_colors, regions=regions, diff --git a/autoarray/plot/inversion.py b/autoarray/plot/inversion.py index a109736ea..192b48f9b 100644 --- a/autoarray/plot/inversion.py +++ b/autoarray/plot/inversion.py @@ -38,6 +38,8 @@ def plot_inversion_reconstruction( zoom_to_brightest: bool = True, zoom_extent_scale: float = 1.0, arcsec_after_decimal: Optional[bool] = None, + interpolated: bool = False, + interpolated_shape_native: Optional[Tuple[int, int]] = None, # --- overlays --------------------------------------------------------------- lines: Optional[List[np.ndarray]] = None, line_colors: Optional[List] = None, @@ -84,6 +86,17 @@ def plot_inversion_reconstruction( When ``True`` the arcsecond tick labels place the ``″`` symbol over the decimal point (``3.″8``) instead of suffixing it (``3.8"``); when ``False`` the suffix form is forced. ``None`` (the default) reads the config. + interpolated + For Delaunay / kNN / natural-neighbour meshes, draw the reconstruction + the likelihood actually uses between the mesh vertices (the mapper's + own interpolant evaluated on a uniform grid, see + :func:`interpolated_reconstruction_from`) instead of flat-shaded + triangles. Ignored for rectangular meshes, whose pixels already are the + reconstruction. + interpolated_shape_native + The ``(y, x)`` shape of the uniform grid the interpolated view is + evaluated on. ``None`` reads ``visualize/general.yaml`` + ``inversion: interpolated_pixels`` (default 400 x 400). lines Line overlays (e.g. critical curves). grid @@ -153,6 +166,20 @@ def plot_inversion_reconstruction( is_subplot=is_subplot, cb_unit=cb_unit, ) + elif interpolated and isinstance( + mapper.interpolator, (InterpolatorDelaunay, InterpolatorKNearestNeighbor) + ): + _plot_interpolated( + ax, + pixel_values, + mapper, + norm, + colormap, + extent, + shape_native=interpolated_shape_native, + is_subplot=is_subplot, + cb_unit=cb_unit, + ) elif isinstance( mapper.interpolator, (InterpolatorDelaunay, InterpolatorKNearestNeighbor) ): @@ -342,13 +369,22 @@ def _plot_delaunay( ): """Render a Delaunay or KNN pixelization reconstruction onto *ax*. - Uses ``ax.tripcolor`` with its default *flat* shading: each triangle is - painted with the mean of its three vertex values. That is not the - piecewise-linear reconstruction pointwise, but its area-weighted integral - is identical to it by linearity -- the mean of the three vertices times the - triangle area is exactly the integral of the linear interpolant over that - triangle, which is the same sum the barycentric dual areas - (``mesh_geometry.areas_for_magnification``) accumulate per vertex. + This is the **default** source-plane view, and it deliberately draws the + mesh rather than a smooth image: ``ax.tripcolor`` with its default *flat* + shading paints every triangle in one colour (the mean of its three vertex + values). Small triangles are where the mesh spends its resolution and large + ones where it does not, so the figure shows at a glance how finely each + part of the source is being reconstructed -- information a smooth image + hides. + + It is **not** the reconstruction the likelihood uses between vertices. The + likelihood maps every data point to the source through the mapper's + interpolant (barycentric within each triangle for ``Delaunay``, the kNN or + natural-neighbour weights for those meshes), which varies smoothly across a + triangle rather than being constant on it. To see that reconstruction, pass + ``interpolated=True`` to :func:`plot_inversion_reconstruction` (see + :func:`interpolated_reconstruction_from`); ``inversion_#.png`` always shows + it in its last panel. The triangulation is taken from the mapper's own Delaunay tables (``mapper.interpolator.delaunay.simplices``, with the ``-1`` padded rows @@ -420,3 +456,185 @@ def _plot_delaunay( from autoarray.plot.utils import _apply_colorbar _apply_colorbar(tc, ax, cb_unit=cb_unit, is_subplot=is_subplot) + + +def mapper_has_interpolated_view(mapper) -> bool: + """ + Whether *mapper* has an interpolated view distinct from its pixel plot. + + ``True`` for irregular meshes (Delaunay, kNN, natural-neighbour), whose + likelihood interpolates between mesh vertices; ``False`` for rectangular + meshes (whose pixels already are the reconstruction) and for anything + without an interpolator. + """ + from autoarray.inversion.mesh.interpolator.delaunay import InterpolatorDelaunay + + return isinstance(getattr(mapper, "interpolator", None), InterpolatorDelaunay) + + +def _conf_interpolated_shape_native() -> Tuple[int, int]: + try: + from autonerves import conf + + pixels = int( + conf.instance["visualize"]["general"]["inversion"]["interpolated_pixels"] + ) + except Exception: + pixels = 400 + return (pixels, pixels) + + +def interpolated_reconstruction_from( + mapper, + pixel_values, + extent: Tuple[float, float, float, float], + shape_native: Optional[Tuple[int, int]] = None, +) -> np.ndarray: + """ + Evaluate an irregular-mesh reconstruction on a uniform grid using the + mapper's own interpolant -- the reconstruction the likelihood uses. + + A fresh interpolator of the mapper's interpolator type is built with the + same ``mesh`` and ``mesh_grid`` but with ``data_grid`` set to a uniform grid + of pixel centres covering *extent* (no over-sampling). Its mappings and + weights are exactly those the mapper would compute for a data point at each + grid position, so the returned image equals that interpolator's + ``mapping_matrix @ pixel_values``: barycentric interpolation for + ``Delaunay``, the kNN weights for ``KNearestNeighbor`` / + ``KNNBarycentric``, the Sibson weights for ``DelaunayNN``. + + Grid points outside the convex hull of the mesh vertices are returned as + ``NaN`` (drawn transparent), so the interpolators' nearest-vertex fill + beyond the mesh is not shown as source light. The cost is one + interpolation of ``shape_native[0] * shape_native[1]`` points (a few + neighbours each) and a triangulation of the mesh; no dense mapping matrix + is formed. + + Parameters + ---------- + mapper + A mapper whose ``interpolator`` is an irregular-mesh interpolator. + pixel_values + The reconstruction, one value per mesh vertex. + extent + ``(x_min, x_max, y_min, y_max)`` covered by the grid (pixel edges). + shape_native + ``(y, x)`` shape of the grid; ``None`` reads the visualize config + (default 400 x 400). + + Returns + ------- + np.ndarray + ``shape_native`` image, row 0 at ``y_max``. + """ + from scipy.spatial import Delaunay + + from autoarray.structures.grids.uniform_2d import Grid2D + + if shape_native is None: + shape_native = _conf_interpolated_shape_native() + + shape_native = (int(shape_native[0]), int(shape_native[1])) + + x_min, x_max, y_min, y_max = (float(e) for e in extent) + pixel_scales = ( + (y_max - y_min) / shape_native[0], + (x_max - x_min) / shape_native[1], + ) + grid = Grid2D.uniform( + shape_native=shape_native, + pixel_scales=pixel_scales, + origin=(0.5 * (y_max + y_min), 0.5 * (x_max + x_min)), + over_sample_size=1, + # The grid must cover `extent` exactly; small-dataset mode would shrink + # its shape without rescaling its pixels. + respect_small_datasets=False, + ) + + interpolator = mapper.interpolator + plot_interpolator = type(interpolator)( + mesh=interpolator.mesh, + mesh_grid=interpolator.mesh_grid, + data_grid=grid, + adapt_data=interpolator.adapt_data, + ) + + mappings, sizes, weights = plot_interpolator._mappings_sizes_weights + + mappings = np.asarray(mappings) + sizes = np.asarray(sizes) + weights = np.asarray(weights, dtype=float) + + if hasattr(pixel_values, "array"): + pixel_values = pixel_values.array + values = np.asarray(pixel_values, dtype=float) + + used = np.arange(mappings.shape[1])[None, :] < sizes[:, None] + safe_mappings = np.where(used & (mappings >= 0), mappings, 0) + image = np.sum(np.where(used, weights * values[safe_mappings], 0.0), axis=1) + + mesh_grid = np.asarray( + getattr(interpolator.mesh_grid, "array", interpolator.mesh_grid), dtype=float + ) + grid_points = np.asarray(grid.array, dtype=float) + try: + outside = Delaunay(mesh_grid).find_simplex(grid_points) < 0 + image = np.where(outside, np.nan, image) + except Exception: + # A degenerate (e.g. collinear) mesh has no hull to mask with. + pass + + return image.reshape(shape_native) + + +def _plot_interpolated( + ax, + pixel_values, + mapper, + norm, + colormap, + extent, + shape_native=None, + is_subplot=False, + cb_unit=None, +): + """Render an irregular-mesh reconstruction as the interpolant the likelihood uses. + + The image from :func:`interpolated_reconstruction_from` is drawn with + ``imshow`` over *extent*, in data coordinates (row 0 at ``y_max``), so + overlays drawn in ``(y, x)`` arcsec need no reflection and the panel lines + up with the flat-triangle view of the same mapper. The colour norm is the + one built from the vertex values, so both views share a colour scale; under + a log norm values below its floor are clipped up to it, as + :func:`~autoarray.plot.utils.norm_from` does for the vertex values. + """ + from matplotlib.colors import LogNorm + + from autoarray.plot.utils import _apply_colorbar + + xmin, xmax, ymin, ymax = extent + x_range = abs(xmax - xmin) + y_range = abs(ymax - ymin) + box_aspect = (x_range / y_range) if y_range > 0 else 1.0 + ax.set_aspect(box_aspect, adjustable="box") + + image = interpolated_reconstruction_from( + mapper=mapper, + pixel_values=pixel_values, + extent=extent, + shape_native=shape_native, + ) + + if isinstance(norm, LogNorm) and norm.vmin is not None: + image = np.where(np.isnan(image), image, np.maximum(image, norm.vmin)) + + im = ax.imshow( + image, + cmap=colormap, + norm=norm, + extent=[xmin, xmax, ymin, ymax], + origin="upper", + aspect="auto", + interpolation="nearest", + ) + _apply_colorbar(im, ax, cb_unit=cb_unit, is_subplot=is_subplot) diff --git a/test_autoarray/plot/test_inversion_interpolated.py b/test_autoarray/plot/test_inversion_interpolated.py new file mode 100644 index 000000000..61f5ea537 --- /dev/null +++ b/test_autoarray/plot/test_inversion_interpolated.py @@ -0,0 +1,212 @@ +""" +The interpolated source-reconstruction view (PyAutoArray#700): an irregular-mesh +reconstruction evaluated on a uniform grid with the mapper's own interpolant, +i.e. the reconstruction the likelihood uses between mesh vertices. +""" + +import matplotlib + +matplotlib.use("Agg") + +import matplotlib.pyplot as plt +import numpy as np +import pytest +from matplotlib.colors import LogNorm + +import autoarray as aa +import autoarray.plot # noqa: F401 (import order: autoarray.plot before autoarray.inversion.plot) +from autoarray import fixtures +from autoarray.inversion.mappers.abstract import Mapper +from autoarray.inversion.plot import inversion_plots +from autoarray.plot.inversion import ( + interpolated_reconstruction_from, + mapper_has_interpolated_view, + plot_inversion_reconstruction, +) + + +def _mesh_grid(): + """A scattered (y, x) mesh with interior vertices and a clean convex hull.""" + rng = np.random.default_rng(1) + interior = rng.uniform(-0.8, 0.8, size=(30, 2)) + corners = np.array([[-1.0, -1.0], [-1.0, 1.0], [1.0, -1.0], [1.0, 1.0]]) + return aa.Grid2DIrregular(values=np.vstack([corners, interior])) + + +def _mapper_for(mesh, mesh_grid=None): + mesh_grid = mesh_grid if mesh_grid is not None else _mesh_grid() + data_grid = aa.Grid2D.uniform( + shape_native=(10, 10), pixel_scales=0.2, over_sample_size=1 + ) + interpolator = mesh.interpolator_from( + source_plane_data_grid=data_grid, + source_plane_mesh_grid=mesh_grid, + ) + return aa.Mapper( + interpolator=interpolator, + regularization=fixtures.make_regularization_constant(), + ) + + +MESHES = [ + aa.mesh.Delaunay(pixels=34), + aa.mesh.KNearestNeighbor(pixels=34, split_neighbor_division=1), + aa.mesh.KNNBarycentric(pixels=34, split_neighbor_division=1), + aa.mesh.DelaunayNN(pixels=34), +] + + +@pytest.mark.parametrize("mesh", MESHES, ids=lambda m: type(m).__name__) +def test__interpolated_view__equals_mapping_matrix_times_reconstruction(mesh): + mapper = _mapper_for(mesh) + rng = np.random.default_rng(2) + values = rng.uniform(0.5, 2.0, size=mapper.pixels) + + extent = (-1.2, 1.2, -1.0, 1.4) + shape_native = (12, 9) + + image = interpolated_reconstruction_from( + mapper=mapper, pixel_values=values, extent=extent, shape_native=shape_native + ) + + assert image.shape == shape_native + + # The likelihood's route: a mapper of the same interpolator type whose data + # grid is the plot grid, mapping_matrix @ reconstruction. + plot_grid = aa.Grid2D.uniform( + shape_native=shape_native, + pixel_scales=(2.4 / 12, 2.4 / 9), + origin=(0.2, 0.0), + over_sample_size=1, + ) + plot_mapper = aa.Mapper( + interpolator=type(mapper.interpolator)( + mesh=mapper.interpolator.mesh, + mesh_grid=mapper.interpolator.mesh_grid, + data_grid=plot_grid, + ), + regularization=None, + ) + expected = (np.asarray(plot_mapper.mapping_matrix) @ values).reshape( + shape_native + ) + + inside = ~np.isnan(image) + assert inside.any() and (~inside).any() # the extent overhangs the mesh + assert image[inside] == pytest.approx(expected[inside], rel=1e-10, abs=1e-12) + + +@pytest.mark.parametrize( + "mesh", [aa.mesh.Delaunay(pixels=34), aa.mesh.DelaunayNN(pixels=34)] +) +def test__interpolated_view__reproduces_linear_source_exactly(mesh): + """ + The reporter's check in its simplest form: a source sampled exactly at the + vertices is recovered between them by the barycentric (and Sibson) + interpolant, which is exact for a linear source -- unlike flat triangles. + """ + mapper = _mapper_for(mesh) + mesh_grid = np.asarray(mapper.interpolator.mesh_grid.array) + + def source(y, x): + return 3.0 + 2.0 * y - 1.5 * x + + values = source(mesh_grid[:, 0], mesh_grid[:, 1]) + + extent = (-1.0, 1.0, -1.0, 1.0) + shape_native = (40, 40) + image = interpolated_reconstruction_from( + mapper=mapper, pixel_values=values, extent=extent, shape_native=shape_native + ) + + grid = aa.Grid2D.uniform( + shape_native=shape_native, pixel_scales=0.05, over_sample_size=1 + ).native.array + truth = source(grid[..., 0], grid[..., 1]) + + assert not np.isnan(image).any() # extent == hull: every pixel centre inside + assert image == pytest.approx(truth, abs=1e-9) + # Row 0 is the top of the image (largest y). + assert image[0].mean() > image[-1].mean() + + +def test__interpolated_view__log10__no_values_below_norm_floor(): + mapper = _mapper_for(aa.mesh.Delaunay(pixels=34)) + values = np.full(mapper.pixels, 1.0e-8) + values[5] = 10.0 + + fig, ax = plt.subplots() + plot_inversion_reconstruction( + pixel_values=values, + mapper=mapper, + ax=ax, + use_log10=True, + zoom_to_brightest=False, + interpolated=True, + interpolated_shape_native=(30, 30), + ) + + image = ax.get_images()[0] + assert isinstance(image.norm, LogNorm) + data = np.ma.filled(image.get_array().astype(float), np.nan) + finite = data[~np.isnan(data)] + assert finite.size > 0 + assert finite.min() >= image.norm.vmin + plt.close(fig) + + +def test__interpolated_flag__draws_raster_not_triangles(): + mapper = fixtures.make_delaunay_mapper_9_3x3() + values = np.arange(1.0, 10.0) + + fig, (ax_flat, ax_interp) = plt.subplots(1, 2) + plot_inversion_reconstruction(pixel_values=values, mapper=mapper, ax=ax_flat) + plot_inversion_reconstruction( + pixel_values=values, + mapper=mapper, + ax=ax_interp, + interpolated=True, + interpolated_shape_native=(16, 16), + ) + + assert len(ax_flat.get_images()) == 0 and len(ax_flat.collections) > 0 + assert len(ax_interp.get_images()) == 1 + plt.close(fig) + + +def test__rectangular_mapper__has_no_interpolated_view_and_flag_is_ignored(): + mapper = fixtures.make_rectangular_mapper_7x7_3x3() + assert not mapper_has_interpolated_view(mapper) + assert mapper_has_interpolated_view(fixtures.make_delaunay_mapper_9_3x3()) + assert mapper_has_interpolated_view(fixtures.make_knn_mapper_9_3x3()) + + fig, ax = plt.subplots() + plot_inversion_reconstruction( + pixel_values=np.ones(9), mapper=mapper, ax=ax, interpolated=True + ) + plt.close(fig) + + +def _subplot_titles(inversion, monkeypatch): + captured = {} + + def _capture(fig, *args, **kwargs): + captured["titles"] = [ + ax.get_title() for ax in fig.axes if ax.get_visible() and ax.get_title() + ] + plt.close(fig) + + monkeypatch.setattr(inversion_plots, "subplot_save", _capture) + inversion_plots.subplot_of_mapper(inversion=inversion, mapper_index=0) + return captured["titles"] + + +def test__subplot_of_mapper__delaunay__panel_11_is_interpolated(monkeypatch): + titles = _subplot_titles(fixtures.make_delaunay_inversion_9_3x3(), monkeypatch) + assert "Source Reconstruction (Interpolated)" in titles + + +def test__subplot_of_mapper__rectangular__no_interpolated_panel(monkeypatch): + titles = _subplot_titles(fixtures.make_rectangular_inversion_7x7_3x3(), monkeypatch) + assert "Source Reconstruction (Interpolated)" not in titles + assert "Source Plane (Zoom)" in titles From edc68b20b8323d0f7aebdc619b93dd0cebb8e424 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 22:01:15 +0000 Subject: [PATCH 2/4] feat: interpolated source panel on by default (bottom right), switch restores mid zoom fit.subplot_fit_source_interpolated now defaults to true. With an irregular-mesh source, fit.png right-hand column is max zoom, no zoom (flat triangles) and the likelihood interpolant bottom right; false (or a rectangular / parametric source) restores max, mid and no zoom. Human decision on PyAutoArray#700, 2026-11-17. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016nhQ8MtKvVD9fBkNBqcMb4 --- autoarray/config/visualize/plots.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/autoarray/config/visualize/plots.yaml b/autoarray/config/visualize/plots.yaml index e11ac7080..aa784c11c 100644 --- a/autoarray/config/visualize/plots.yaml +++ b/autoarray/config/visualize/plots.yaml @@ -10,7 +10,7 @@ imaging: # Settings for plots of imaging datas fit: # Settings for plots of all fits (e.g. FitImaging, FitInterferometer). subplot_fit: true # Plot subplot of all fit quantities for any dataset (e.g. the model data, residual-map, etc.)? subplot_fit_log10: false # Plot subplot of all fit quantities for any dataset using log10 color maps (e.g. the model data, residual-map, etc.)? - subplot_fit_source_interpolated: false # In fit.png, draw the mid-zoom source panel as the interpolated reconstruction the likelihood uses (Delaunay/KNN meshes), instead of flat triangles? + subplot_fit_source_interpolated: true # In fit.png, show the interpolated reconstruction the likelihood uses (Delaunay/KNN meshes) in the bottom-right source panel, with max zoom and no zoom above it? If false, show max, mid and no zoom flat-triangle panels instead. data: false # Plot individual plots of the data? noise_map: false # Plot individual plots of the noise-map? signal_to_noise_map: false # Plot individual plots of the signal-to-noise-map? From adc07dab35797a7a764d30974b3dd73db35ee717 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 22:06:37 +0000 Subject: [PATCH 3/4] test: skip kNN interpolated-view cases without jax The kNN interpolators import jax, so their mapping-matrix cases fail on the no-jax CI leg (unittest-nojax). Skip them there, as the repository's other jax-dependent tests do; Delaunay and DelaunayNN cases still run. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016nhQ8MtKvVD9fBkNBqcMb4 --- .../plot/test_inversion_interpolated.py | 27 ++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/test_autoarray/plot/test_inversion_interpolated.py b/test_autoarray/plot/test_inversion_interpolated.py index 61f5ea537..57c0c51f4 100644 --- a/test_autoarray/plot/test_inversion_interpolated.py +++ b/test_autoarray/plot/test_inversion_interpolated.py @@ -48,15 +48,36 @@ def _mapper_for(mesh, mesh_grid=None): ) +# The kNN interpolators are built on JAX (`knn.py` imports it), so their cases +# skip on the no-JAX CI leg, as the repository's other JAX-dependent tests do. +try: + import jax # noqa: F401 + + _HAS_JAX = True +except ImportError: + _HAS_JAX = False + +_requires_jax = pytest.mark.skipif(not _HAS_JAX, reason="kNN interpolators need jax") + MESHES = [ aa.mesh.Delaunay(pixels=34), - aa.mesh.KNearestNeighbor(pixels=34, split_neighbor_division=1), - aa.mesh.KNNBarycentric(pixels=34, split_neighbor_division=1), + pytest.param( + aa.mesh.KNearestNeighbor(pixels=34, split_neighbor_division=1), + marks=_requires_jax, + id="KNearestNeighbor", + ), + pytest.param( + aa.mesh.KNNBarycentric(pixels=34, split_neighbor_division=1), + marks=_requires_jax, + id="KNNBarycentric", + ), aa.mesh.DelaunayNN(pixels=34), ] -@pytest.mark.parametrize("mesh", MESHES, ids=lambda m: type(m).__name__) +@pytest.mark.parametrize( + "mesh", MESHES, ids=lambda m: type(m).__name__ if not isinstance(m, str) else m +) def test__interpolated_view__equals_mapping_matrix_times_reconstruction(mesh): mapper = _mapper_for(mesh) rng = np.random.default_rng(2) From e8a174a6972804185ac6d3377d074eb0bc90c1c3 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Wed, 18 Nov 2026 09:20:23 +0000 Subject: [PATCH 4/4] feat: inversion source column = max zoom / interpolated / no zoom (#700) Irregular-mesh inversion_#.png puts the source plane in the right-hand column like the lens fit.png: Source Plane (Max Zoom), Source Plane (Interpolated) over the max-zoom extent, Source Plane (No Zoom). Rectangular meshes keep their layout unchanged. The interpolated panel is now square with a full-height colorbar (imshow no longer resets the box aspect). Co-Authored-By: Claude Opus 5.5 --- autoarray/config/visualize/plots.yaml | 2 +- autoarray/inversion/plot/inversion_plots.py | 90 ++++++++++++++----- autoarray/plot/inversion.py | 9 +- .../plot/test_inversion_interpolated.py | 86 +++++++++++++++--- 4 files changed, 148 insertions(+), 39 deletions(-) diff --git a/autoarray/config/visualize/plots.yaml b/autoarray/config/visualize/plots.yaml index aa784c11c..26651579d 100644 --- a/autoarray/config/visualize/plots.yaml +++ b/autoarray/config/visualize/plots.yaml @@ -10,7 +10,7 @@ imaging: # Settings for plots of imaging datas fit: # Settings for plots of all fits (e.g. FitImaging, FitInterferometer). subplot_fit: true # Plot subplot of all fit quantities for any dataset (e.g. the model data, residual-map, etc.)? subplot_fit_log10: false # Plot subplot of all fit quantities for any dataset using log10 color maps (e.g. the model data, residual-map, etc.)? - subplot_fit_source_interpolated: true # In fit.png, show the interpolated reconstruction the likelihood uses (Delaunay/KNN meshes) in the bottom-right source panel, with max zoom and no zoom above it? If false, show max, mid and no zoom flat-triangle panels instead. + subplot_fit_source_interpolated: true # In fit.png, show the interpolated reconstruction the likelihood uses (Delaunay/KNN meshes) in the middle source panel, between max zoom and no zoom? If false, show max, mid and no zoom flat-triangle panels instead. data: false # Plot individual plots of the data? noise_map: false # Plot individual plots of the noise-map? signal_to_noise_map: false # Plot individual plots of the signal-to-noise-map? diff --git a/autoarray/inversion/plot/inversion_plots.py b/autoarray/inversion/plot/inversion_plots.py index a0d06e359..2615f583f 100644 --- a/autoarray/inversion/plot/inversion_plots.py +++ b/autoarray/inversion/plot/inversion_plots.py @@ -56,10 +56,29 @@ def subplot_of_mapper( """ 3×4 subplot showing all pixelization diagnostics for one mapper. - For Delaunay / kNN / natural-neighbour meshes the last panel (11) shows the - reconstruction as the likelihood's interpolant ("Source Reconstruction - (Interpolated)"), alongside the flat-triangle panels that show the mesh - resolution. Rectangular meshes leave it empty. + For Delaunay / kNN / natural-neighbour meshes (those with an interpolated + view, see :func:`~autoarray.plot.inversion.mapper_has_interpolated_view`) + the right-hand column holds the source plane, as in the lens ``fit.png``: + + - row 0: Data Subtracted, Reconstructed Image, Reconstructed Image (log10), + Source Plane (Max Zoom); + - row 1: Mesh Pixel Grid Overlaid, Noise-Map (No Zoom), Regularization + (No Zoom), Source Plane (Interpolated); + - row 2: Sub Pixels Per Image Pixels, Mesh Pixels Per Image Pixels, Image + Pixels Per Source Pixel, Source Plane (No Zoom). + + The max-zoom and no-zoom panels draw the mesh as flat triangles, which shows + where it spends resolution; "Source Plane (Interpolated)" shows the reconstruction + the likelihood uses between mesh vertices (the mapper's interpolant on a + uniform grid), over the same extent as the max-zoom panel. + + Rectangular meshes have no separate interpolated view and keep the layout + Data Subtracted, Reconstructed Image, Reconstructed Image (log10), Mesh + Pixel Grid Overlaid / Source Plane (Zoom), Source Plane (No Zoom), + Noise-Map, Regularization / Sub Pixels, Mesh Pixels, Image Pixels Per + Source Pixel, with the last panel left empty. + + Panels whose data the inversion cannot provide are left empty. Parameters ---------- @@ -87,6 +106,31 @@ def subplot_of_mapper( fig, axes = subplots(3, 4, figsize=conf_subplot_figsize(3, 4)) axes = axes.flatten() + # Panel positions: irregular meshes put the source plane in the right-hand + # column (Max Zoom / Interpolated / No Zoom); rectangular meshes keep the + # original order, with the last panel empty. + interpolated_view = mapper_has_interpolated_view(mapper) + + if interpolated_view: + panel = { + "mesh_grid": 4, + "source_zoom": 3, + "source_interpolated": 7, + "noise_map": 5, + "regularization": 6, + "source_no_zoom": 11, + } + source_zoom_title = "Source Plane (Max Zoom)" + else: + panel = { + "mesh_grid": 3, + "source_zoom": 4, + "source_no_zoom": 5, + "noise_map": 6, + "regularization": 7, + } + source_zoom_title = "Source Plane (Zoom)" + # panel 0: data subtracted try: array = inversion.data_subtracted_dict[mapper] @@ -107,7 +151,8 @@ def subplot_of_mapper( except (AttributeError, KeyError, exc.InversionException): pass - # panels 1-3: reconstructed operated data (plain, log10, + mesh grid overlay) + # panels 1-2 + mesh grid panel: reconstructed operated data (plain, log10, + # + mesh grid overlay) def _recon_array(): if _is_array_free_interferometer(inversion): return inversion.mapped_reconstructed_data_dict[mapper] @@ -142,7 +187,7 @@ def _recon_array(): ) plot_array( _recon_array(), - ax=axes[3], + ax=axes[panel["mesh_grid"]], title=_pf("Mesh Pixel Grid Overlaid"), colormap=colormap, use_log10=use_log10, @@ -153,7 +198,7 @@ def _recon_array(): except (AttributeError, KeyError, exc.InversionException): pass - # panels 4-5: source reconstruction zoomed / unzoomed + # source reconstruction zoomed / unzoomed pixel_values = inversion.reconstruction_dict[mapper] try: recon_vmax = float(np.max(np.asarray(_recon_array()))) @@ -162,8 +207,8 @@ def _recon_array(): plot_mapper( mapper, solution_vector=pixel_values, - ax=axes[4], - title=_pf("Source Plane (Zoom)"), + ax=axes[panel["source_zoom"]], + title=_pf(source_zoom_title), colormap=colormap, use_log10=use_log10, vmax=recon_vmax, @@ -174,7 +219,7 @@ def _recon_array(): plot_mapper( mapper, solution_vector=pixel_values, - ax=axes[5], + ax=axes[panel["source_no_zoom"]], title=_pf("Source Plane (No Zoom)"), colormap=colormap, use_log10=use_log10, @@ -184,13 +229,13 @@ def _recon_array(): lines=lines, ) - # panel 6: noise map + # noise map try: nm = inversion.reconstruction_noise_map_dict[mapper] plot_mapper( mapper, solution_vector=nm, - ax=axes[6], + ax=axes[panel["noise_map"]], title=_pf("Noise-Map (No Zoom)"), colormap=colormap, use_log10=use_log10, @@ -202,13 +247,13 @@ def _recon_array(): # `InversionException`: the matrix-free interferometer route has no noise map. pass - # panel 7: regularization weights + # regularization weights try: rw = inversion.regularization_weights_mapper_dict[mapper] plot_mapper( mapper, solution_vector=rw, - ax=axes[7], + ax=axes[panel["regularization"]], title=_pf("Regularization (No Zoom)"), colormap=colormap, use_log10=use_log10, @@ -263,17 +308,18 @@ def _recon_array(): except (TypeError, Exception): pass - # panel 11: the reconstruction the likelihood uses between mesh vertices. - # Panels 4-5 draw irregular meshes as flat triangles (one colour each) to - # show where the mesh spends resolution; this panel evaluates the mapper's - # own interpolant on a uniform grid. Rectangular meshes have no separate - # interpolated view, so the panel is left empty and hidden. - if mapper_has_interpolated_view(mapper): + # interpolated panel: the reconstruction the likelihood uses between mesh + # vertices. The zoom panels draw irregular meshes as flat triangles (one + # colour each) to show where the mesh spends resolution; this panel + # evaluates the mapper's own interpolant on a uniform grid, over the + # max-zoom extent. Rectangular meshes have no separate interpolated view, so + # they draw no such panel and their last panel is left empty and hidden. + if interpolated_view: plot_mapper( mapper, solution_vector=pixel_values, - ax=axes[11], - title=_pf("Source Reconstruction (Interpolated)"), + ax=axes[panel["source_interpolated"]], + title=_pf("Source Plane (Interpolated)"), colormap=colormap, use_log10=use_log10, vmax=recon_vmax, diff --git a/autoarray/plot/inversion.py b/autoarray/plot/inversion.py index 192b48f9b..8c0532c3d 100644 --- a/autoarray/plot/inversion.py +++ b/autoarray/plot/inversion.py @@ -384,7 +384,8 @@ def _plot_delaunay( triangle rather than being constant on it. To see that reconstruction, pass ``interpolated=True`` to :func:`plot_inversion_reconstruction` (see :func:`interpolated_reconstruction_from`); ``inversion_#.png`` always shows - it in its last panel. + it as "Source Plane (Interpolated)", the middle panel of its right-hand + column. The triangulation is taken from the mapper's own Delaunay tables (``mapper.interpolator.delaunay.simplices``, with the ``-1`` padded rows @@ -616,7 +617,6 @@ def _plot_interpolated( x_range = abs(xmax - xmin) y_range = abs(ymax - ymin) box_aspect = (x_range / y_range) if y_range > 0 else 1.0 - ax.set_aspect(box_aspect, adjustable="box") image = interpolated_reconstruction_from( mapper=mapper, @@ -634,7 +634,10 @@ def _plot_interpolated( norm=norm, extent=[xmin, xmax, ymin, ymax], origin="upper", - aspect="auto", interpolation="nearest", ) + # ``imshow`` sets the axes aspect itself, so the box aspect is applied after + # it: the panel is then square like the ``_plot_delaunay`` panels and its + # colorbar spans the full height of the axes. + ax.set_aspect(box_aspect, adjustable="box") _apply_colorbar(im, ax, cb_unit=cb_unit, is_subplot=is_subplot) diff --git a/test_autoarray/plot/test_inversion_interpolated.py b/test_autoarray/plot/test_inversion_interpolated.py index 57c0c51f4..9b244384f 100644 --- a/test_autoarray/plot/test_inversion_interpolated.py +++ b/test_autoarray/plot/test_inversion_interpolated.py @@ -208,26 +208,86 @@ def test__rectangular_mapper__has_no_interpolated_view_and_flag_is_ignored(): plt.close(fig) -def _subplot_titles(inversion, monkeypatch): +def _subplot_panels(inversion, monkeypatch): + """The 12 panel axes of ``subplot_of_mapper`` in grid order (colorbars excluded).""" captured = {} def _capture(fig, *args, **kwargs): - captured["titles"] = [ - ax.get_title() for ax in fig.axes if ax.get_visible() and ax.get_title() - ] + captured["axes"] = fig.axes[:12] plt.close(fig) monkeypatch.setattr(inversion_plots, "subplot_save", _capture) inversion_plots.subplot_of_mapper(inversion=inversion, mapper_index=0) - return captured["titles"] - + return captured["axes"] + + +def _titles(axes): + return [ax.get_title() if ax.get_visible() else None for ax in axes] + + +def test__subplot_of_mapper__delaunay__source_plane_in_right_column(monkeypatch): + axes = _subplot_panels(fixtures.make_delaunay_inversion_9_3x3(), monkeypatch) + titles = _titles(axes) + + assert titles == [ + "Data Subtracted", + "Reconstructed Image", + "Reconstructed Image (log10)", + "Source Plane (Max Zoom)", + "Mesh Pixel Grid Overlaid", + "Noise-Map (No Zoom)", + "Regularization (No Zoom)", + "Source Plane (Interpolated)", + "Sub Pixels Per Image Pixels", + "Mesh Pixels Per Image Pixels", + "Image Pixels Per Source Pixel", + "Source Plane (No Zoom)", + ] + + interpolated = axes[7] + assert len(interpolated.get_images()) == 1 + # ``imshow`` must not leave the panel at aspect 'auto': it keeps the same + # box aspect as the flat-triangle Source Plane panels. + assert interpolated.get_aspect() != "auto" + assert interpolated.get_aspect() == axes[3].get_aspect() + + +def test__subplot_of_mapper__rectangular__keeps_original_layout(monkeypatch): + titles = _titles( + _subplot_panels(fixtures.make_rectangular_inversion_7x7_3x3(), monkeypatch) + ) -def test__subplot_of_mapper__delaunay__panel_11_is_interpolated(monkeypatch): - titles = _subplot_titles(fixtures.make_delaunay_inversion_9_3x3(), monkeypatch) - assert "Source Reconstruction (Interpolated)" in titles + assert "Source Plane (Interpolated)" not in titles + assert "Source Plane (Max Zoom)" not in titles + assert titles[:9] == [ + "Data Subtracted", + "Reconstructed Image", + "Reconstructed Image (log10)", + "Mesh Pixel Grid Overlaid", + "Source Plane (Zoom)", + "Source Plane (No Zoom)", + "Noise-Map (No Zoom)", + "Regularization (No Zoom)", + "Sub Pixels Per Image Pixels", + ] + assert titles[10] == "Image Pixels Per Source Pixel" + assert not titles[11] + + +def test__interpolated_panel__axes_aspect_is_not_auto(): + mapper = fixtures.make_delaunay_mapper_9_3x3() + values = np.arange(1.0, 10.0) + fig, (ax_flat, ax_interp) = plt.subplots(1, 2) + plot_inversion_reconstruction(pixel_values=values, mapper=mapper, ax=ax_flat) + plot_inversion_reconstruction( + pixel_values=values, + mapper=mapper, + ax=ax_interp, + interpolated=True, + interpolated_shape_native=(16, 16), + ) -def test__subplot_of_mapper__rectangular__no_interpolated_panel(monkeypatch): - titles = _subplot_titles(fixtures.make_rectangular_inversion_7x7_3x3(), monkeypatch) - assert "Source Reconstruction (Interpolated)" not in titles - assert "Source Plane (Zoom)" in titles + assert ax_interp.get_aspect() != "auto" + assert ax_interp.get_aspect() == ax_flat.get_aspect() + plt.close(fig)