diff --git a/autolens/config/visualize/plots.yaml b/autolens/config/visualize/plots.yaml index 174fcda51..4b04cf9f6 100644 --- a/autolens/config/visualize/plots.yaml +++ b/autolens/config/visualize/plots.yaml @@ -24,6 +24,7 @@ positions: # Settings for plots with resampling 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 middle source panel, between max zoom and no zoom? If false, show max, mid and no zoom flat-triangle panels instead. subplot_of_planes: false # Plot subplot of the model-image, subtracted image and other quantities of each plane? subplot_galaxies_images: false # Plot subplot of the image of each plane in the model? fits_fit: true # Output a .fits file containing the fit model data, residual map, normalized residual map and chi-squared? diff --git a/autolens/imaging/model/plotter.py b/autolens/imaging/model/plotter.py index 4fad58276..493e662fe 100644 --- a/autolens/imaging/model/plotter.py +++ b/autolens/imaging/model/plotter.py @@ -76,6 +76,11 @@ def should_plot(name): source_plane_lines, source_plane_line_colors, ) + # `fit.png` and `fit_log10.png` show the likelihood's interpolant in the + # middle source panel (Delaunay / kNN sources) when this is on (default); + # off restores the mid-zoom panel. + source_interpolated = should_plot("subplot_fit_source_interpolated") + # Quick updates write the normal fit subplot (plain `fit.png`, final # plane as source) regardless of plane count, so the live display # always has one canonical filename to refresh. @@ -85,6 +90,7 @@ def should_plot(name): image_plane_lines=ip_lines, image_plane_line_colors=ip_colors, source_plane_lines=sp_lines, source_plane_line_colors=sp_colors, title_prefix=self.title_prefix, + source_interpolated=source_interpolated, ) return @@ -98,6 +104,7 @@ def should_plot(name): image_plane_lines=ip_lines, image_plane_line_colors=ip_colors, source_plane_lines=sp_lines, source_plane_line_colors=sp_colors, title_prefix=self.title_prefix, + source_interpolated=source_interpolated, ) else: subplot_fit( @@ -105,6 +112,7 @@ def should_plot(name): image_plane_lines=ip_lines, image_plane_line_colors=ip_colors, source_plane_lines=sp_lines, source_plane_line_colors=sp_colors, title_prefix=self.title_prefix, + source_interpolated=source_interpolated, ) if plot_setting(section="tracer", name="subplot_tracer"): @@ -125,6 +133,7 @@ def should_plot(name): image_plane_lines=ip_lines, image_plane_line_colors=ip_colors, source_plane_lines=sp_lines, source_plane_line_colors=sp_colors, title_prefix=self.title_prefix, + source_interpolated=source_interpolated, ) else: subplot_fit_log10( @@ -132,6 +141,7 @@ def should_plot(name): image_plane_lines=ip_lines, image_plane_line_colors=ip_colors, source_plane_lines=sp_lines, source_plane_line_colors=sp_colors, title_prefix=self.title_prefix, + source_interpolated=source_interpolated, ) except ValueError: pass diff --git a/autolens/imaging/plot/fit_imaging_plots.py b/autolens/imaging/plot/fit_imaging_plots.py index 6fa8bf72a..b8ec00705 100644 --- a/autolens/imaging/plot/fit_imaging_plots.py +++ b/autolens/imaging/plot/fit_imaging_plots.py @@ -70,7 +70,7 @@ def _plot_source_plane(fit, ax, plane_index, zoom_to_brightest=True, lines=None, line_colors=None, vmax=None, zoom_extent_scale: float = 1.0, regions=None, region_alpha: float = 0.25, - region_labels=None): + region_labels=None, interpolated: bool = False): """ Plot the source-plane image (or a blank inversion placeholder) into an axes. @@ -112,6 +112,11 @@ def _plot_source_plane(fit, ax, plane_index, zoom_to_brightest=True, The alpha of each region's fill. region_labels : list of str, optional A label drawn at the centre of each region, matching its image-plane counterpart. + interpolated : bool, optional + For an inversion source on a Delaunay / kNN mesh, draw the reconstruction the + likelihood uses between mesh vertices (the mapper's own interpolant on a uniform + grid) instead of flat-shaded triangles. Ignored for parametric sources and + rectangular meshes. """ tracer = fit.tracer_linear_light_profiles_to_light_profiles if not tracer.planes[plane_index].has(cls=aa.Pixelization): @@ -168,6 +173,7 @@ def _plot_source_plane(fit, ax, plane_index, zoom_to_brightest=True, vmax=vmax, zoom_to_brightest=zoom_to_brightest, zoom_extent_scale=zoom_extent_scale, + interpolated=interpolated, lines=lines, line_colors=line_colors, regions=regions, @@ -181,6 +187,25 @@ def _plot_source_plane(fit, ax, plane_index, zoom_to_brightest=True, ax.set_title(f"Source Reconstruction (plane {plane_index})") +def _source_has_interpolated_view(fit, plane_index) -> bool: + """ + Whether the source at ``plane_index`` is a pixelization whose mesh has an + interpolated view (Delaunay / kNN / natural-neighbour), so a + ``source_interpolated`` panel differs from the flat-triangle one. + """ + from autoarray.plot.inversion import mapper_has_interpolated_view + + try: + tracer = fit.tracer_linear_light_profiles_to_light_profiles + if not tracer.planes[plane_index].has(cls=aa.Pixelization): + return False + mapper_list = fit.inversion.cls_list_from(cls=Mapper) + mapper = mapper_list[plane_index - 1] if plane_index > 0 else mapper_list[0] + return mapper_has_interpolated_view(mapper) + except Exception: + return False + + def subplot_fit( fit, output_path: Optional[str] = None, @@ -192,6 +217,7 @@ def subplot_fit( source_plane_lines=None, source_plane_line_colors=None, title_prefix: str = None, + source_interpolated: bool = True, ): """ Produce a 12-panel subplot summarising an imaging fit. @@ -212,6 +238,9 @@ def subplot_fit( * Chi-squared map * Source plane image (full extent) + With ``source_interpolated`` (default) and a Delaunay / kNN source, the + mid-zoom panel shows the interpolated reconstruction instead. + For single-plane tracers the function delegates to :func:`subplot_fit_x1_plane`, which uses a simpler 2 × 3 layout. @@ -230,6 +259,14 @@ def subplot_fit( plane_index : int, optional Index of the source plane to use for the source-scale panels. Defaults to the final plane in the tracer. + source_interpolated : bool, optional + When the source is a Delaunay / kNN pixelization, the right-hand source + panels are Source Plane (Max Zoom) as flat triangles, which show the + mesh resolution, then "Source Plane (Interpolated)" -- the + reconstruction the likelihood uses, over the max-zoom extent -- in the + middle, then Source Plane (No Zoom) bottom right. When ``False`` (or for + rectangular / parametric sources) they are max, mid and no zoom. Set by + ``plots.yaml`` ``fit: subplot_fit_source_interpolated`` (default ``True``). """ if len(fit.tracer.planes) == 1: return subplot_fit_x1_plane(fit, output_path=output_path, @@ -261,6 +298,16 @@ def subplot_fit( plot_array(array=fit.signal_to_noise_map, ax=axes_flat[2], title=_pf("Signal-To-Noise Map"), colormap=colormap) + # The right-hand column holds the three source panels. With + # `source_interpolated` (the default) and an irregular-mesh source they are: + # max zoom (3) as flat triangles, which show the mesh resolution, the + # likelihood's interpolant (7) over the max-zoom extent, so it compares + # directly with panel 3, and no zoom (11). Otherwise (switch off, or a + # rectangular / parametric source) they are max, mid and no zoom. + interpolated = source_interpolated and _source_has_interpolated_view( + fit, final_plane_index + ) + # Source plane (max zoom) _plot_source_plane(fit, axes_flat[3], final_plane_index, zoom_to_brightest=True, colormap=colormap, title=_pf("Source Plane (Max Zoom)"), @@ -302,11 +349,19 @@ def subplot_fit( else: axes_flat[6].axis("off") - # Source plane (mid zoom) — same centre as Max Zoom, 2.5x wider extent - _plot_source_plane(fit, axes_flat[7], final_plane_index, zoom_to_brightest=True, - colormap=colormap, title=_pf("Source Plane (Mid Zoom)"), - lines=source_plane_lines, line_colors=source_plane_line_colors, - vmax=source_vmax, zoom_extent_scale=2.0) + if interpolated: + # The reconstruction the likelihood uses, over the max-zoom extent (the + # mid-zoom panel is replaced, see above) + _plot_source_plane(fit, axes_flat[7], final_plane_index, zoom_to_brightest=True, + colormap=colormap, title=_pf("Source Plane (Interpolated)"), + lines=source_plane_lines, line_colors=source_plane_line_colors, + vmax=source_vmax, interpolated=True) + else: + # Source plane (mid zoom) — same centre as Max Zoom, 2.5x wider extent + _plot_source_plane(fit, axes_flat[7], final_plane_index, zoom_to_brightest=True, + colormap=colormap, title=_pf("Source Plane (Mid Zoom)"), + lines=source_plane_lines, line_colors=source_plane_line_colors, + vmax=source_vmax, zoom_extent_scale=2.0) # Normalized residual map (symmetric) norm_resid = fit.normalized_residual_map @@ -410,6 +465,7 @@ def subplot_fit_log10( source_plane_lines=None, source_plane_line_colors=None, title_prefix: str = None, + source_interpolated: bool = True, ): """ Produce a 12-panel subplot summarising an imaging fit with log10 colour scaling. @@ -423,6 +479,10 @@ def subplot_fit_log10( kept square and shrunk uniformly so all edges stay inside the No Zoom extent. + With ``source_interpolated`` (default) and a Delaunay / kNN source, the + right-hand column matches :func:`subplot_fit`: Source Plane (Max Zoom), + Source Plane (Interpolated) and Source Plane (No Zoom), all log10. + For single-plane tracers the function delegates to :func:`subplot_fit_log10_x1_plane`. @@ -440,6 +500,14 @@ def subplot_fit_log10( plane_index : int, optional Index of the source plane to use for the source-scale panels. Defaults to the final plane in the tracer. + source_interpolated : bool, optional + When the source is a Delaunay / kNN pixelization, the right-hand source + panels are Source Plane (Max Zoom) as flat triangles, then "Source Plane + (Interpolated)" -- the reconstruction the likelihood uses, over the + max-zoom extent -- in the middle, then Source Plane (No Zoom) bottom + right. When ``False`` (or for rectangular / parametric sources) they are + max, mid and no zoom. Set by ``plots.yaml`` + ``fit: subplot_fit_source_interpolated`` (default ``True``). """ if len(fit.tracer.planes) == 1: return subplot_fit_log10_x1_plane(fit, output_path=output_path, @@ -475,6 +543,14 @@ def subplot_fit_log10( except ValueError: axes_flat[2].axis("off") + # The right-hand column holds the three source panels, as in `subplot_fit`: + # max zoom (3), the likelihood's interpolant (7) and no zoom (11) for an + # irregular-mesh source with `source_interpolated`; otherwise max, mid and + # no zoom. + interpolated = source_interpolated and _source_has_interpolated_view( + fit, final_plane_index + ) + # Source plane (max zoom) _plot_source_plane(fit, axes_flat[3], final_plane_index, zoom_to_brightest=True, colormap=colormap, use_log10=True, @@ -504,12 +580,21 @@ def subplot_fit_log10( except (IndexError, AttributeError): axes_flat[6].axis("off") - # Source plane (mid zoom) — same centre as Max Zoom, 2.5x wider extent - _plot_source_plane(fit, axes_flat[7], final_plane_index, zoom_to_brightest=True, - colormap=colormap, use_log10=True, - title=_pf("Source Plane (Mid Zoom)"), - lines=source_plane_lines, line_colors=source_plane_line_colors, - vmax=source_vmax, zoom_extent_scale=2.0) + if interpolated: + # The reconstruction the likelihood uses, over the max-zoom extent (the + # mid-zoom panel is replaced, see above) + _plot_source_plane(fit, axes_flat[7], final_plane_index, zoom_to_brightest=True, + colormap=colormap, use_log10=True, + title=_pf("Source Plane (Interpolated)"), + lines=source_plane_lines, line_colors=source_plane_line_colors, + vmax=source_vmax, interpolated=True) + else: + # Source plane (mid zoom) — same centre as Max Zoom, 2.5x wider extent + _plot_source_plane(fit, axes_flat[7], final_plane_index, zoom_to_brightest=True, + colormap=colormap, use_log10=True, + title=_pf("Source Plane (Mid Zoom)"), + lines=source_plane_lines, line_colors=source_plane_line_colors, + vmax=source_vmax, zoom_extent_scale=2.0) norm_resid = fit.normalized_residual_map _abs_max = _symmetric_vmax(norm_resid) diff --git a/autolens/interferometer/model/plotter.py b/autolens/interferometer/model/plotter.py index 87bde0daf..bac57bde9 100644 --- a/autolens/interferometer/model/plotter.py +++ b/autolens/interferometer/model/plotter.py @@ -75,6 +75,10 @@ def should_plot(name): image_plane_lines=ip_lines, image_plane_line_colors=ip_colors, source_plane_lines=sp_lines, source_plane_line_colors=sp_colors, title_prefix=self.title_prefix, + # `fit.png` shows the likelihood's interpolant in the middle source + # panel (Delaunay / kNN sources) when this is on (default); off + # restores the mid-zoom panel. + source_interpolated=should_plot("subplot_fit_source_interpolated"), ) if quick_update: diff --git a/autolens/interferometer/plot/fit_interferometer_plots.py b/autolens/interferometer/plot/fit_interferometer_plots.py index 97b91f7ac..bc743bc5c 100644 --- a/autolens/interferometer/plot/fit_interferometer_plots.py +++ b/autolens/interferometer/plot/fit_interferometer_plots.py @@ -24,9 +24,41 @@ logger = logging.getLogger(__name__) +def _get_source_vmax(fit): + """ + Return the colour-scale maximum shared by the source-plane panels of an + interferometer fit. + + The interferometer counterpart of the imaging + :func:`~autolens.imaging.plot.fit_imaging_plots._get_source_vmax`: the + maximum over the source planes (index >= 1) of each plane's real-space + model image (its galaxies' entries in ``fit.galaxy_image_dict`` summed), + so every source-plane panel uses one colour scale. Returns ``None`` when + no source-plane image is available, so callers fall back to automatic + scaling. + """ + try: + galaxy_image_dict = fit.galaxy_image_dict + maxima = [] + for plane in fit.tracer.planes[1:]: + images = [ + np.asarray(getattr(galaxy_image_dict[galaxy], "array", + galaxy_image_dict[galaxy]), dtype=float) + for galaxy in plane + if galaxy in galaxy_image_dict + ] + if images: + maxima.append(float(np.max(np.sum(images, axis=0)))) + return max(maxima) if maxima else None + except Exception: + return None + + def _plot_source_plane(fit, ax, plane_index, zoom_to_brightest=True, colormap=None, use_log10=False, title=None, - lines=None, line_colors=None, vmax=None): + lines=None, line_colors=None, vmax=None, + zoom_extent_scale: float = 1.0, + interpolated: bool = False): """ Plot the source-plane image into an axes, matching the imaging subplot_fit behaviour. @@ -60,6 +92,13 @@ def _plot_source_plane(fit, ax, plane_index, zoom_to_brightest=True, Colours for each entry in *lines*. vmax : float, optional Shared colour-scale maximum. + zoom_extent_scale : float, optional + Widen the zoomed extent by this factor about the same centre (``2.0`` gives the + "Mid Zoom" panel), kept inside the no-zoom extent, as in the imaging subplot. + interpolated : bool, optional + For an inversion source on a Delaunay / kNN mesh, draw the reconstruction the + likelihood uses between mesh vertices instead of flat-shaded triangles. + Ignored for parametric sources and rectangular meshes. """ if ax is None: return @@ -77,10 +116,20 @@ def _plot_source_plane(fit, ax, plane_index, zoom_to_brightest=True, extent=zoom.extent_from(buffer=0), shape_native=zoom.shape_native, ) + zoom_extent_bounds = None + if zoom_extent_scale != 1.0: + zoom = aa.Zoom2D(mask=fit.dataset.real_space_mask) + no_zoom_grid = aa.Grid2D.from_extent( + extent=zoom.extent_from(buffer=0), + shape_native=zoom.shape_native, + ) + zoom_extent_bounds = no_zoom_grid.geometry.extent image = plane_image_from( galaxies=tracer.planes[plane_index], grid=grid, zoom_to_brightest=zoom_to_brightest, + zoom_extent_scale=zoom_extent_scale, + zoom_extent_bounds=zoom_extent_bounds, ) plot_array( array=image, ax=ax, @@ -103,6 +152,8 @@ def _plot_source_plane(fit, ax, plane_index, zoom_to_brightest=True, use_log10=use_log10, vmax=vmax, zoom_to_brightest=zoom_to_brightest, + zoom_extent_scale=zoom_extent_scale, + interpolated=interpolated, lines=lines, line_colors=line_colors, ) @@ -122,26 +173,31 @@ def subplot_fit( source_plane_lines=None, source_plane_line_colors=None, title_prefix: str = None, + source_interpolated: bool = True, ): """ Produce a 12-panel subplot summarising an interferometer fit. - Arranges the following panels in a 3 × 4 grid: + Arranges the following panels in a 3 × 4 grid, the right-hand column + holding the source plane as in the imaging ``fit.png``: * Amplitudes vs UV-distance (scatter) * Dirty image - * Dirty signal-to-noise map - * Dirty model image - * Source plane image (final plane) + * Dirty model image (with critical curves) + * Source plane image (max zoom) + * Dirty residual map * Normalised residual (real part) vs UV-distance (scatter) * Normalised residual (imaginary part) vs UV-distance (scatter) - * Source plane image zoomed (final plane) + * Source plane image (mid zoom -- same centre as max zoom, 2× wider extent) * Dirty normalised residual map * Dirty normalised residual map clipped to ± 1 σ - * (panel 9 re-used for 1σ clip — see implementation note) * Dirty chi-squared map * Source plane image (full extent) + With ``source_interpolated`` (default) and a Delaunay / kNN source, the + mid-zoom panel shows the interpolated reconstruction instead. Every + source-plane panel shares one colour scale (:func:`_get_source_vmax`). + On an array-free dataset (``fit.dataset.is_array_free``) there are no visibilities, so a 2 × 3 grid of the natural-weighted dirty image, dirty model image and dirty residual map plus the zoomed and unzoomed source plane is written to the same filename instead. @@ -157,9 +213,25 @@ def subplot_fit( Image format passed to :func:`~autoarray.plot.utils.save_figure`. colormap : str, optional Matplotlib colormap name applied to all image panels. + source_interpolated : bool, optional + When the source is a Delaunay / kNN pixelization, the right-hand source + panels are Source Plane (Max Zoom) as flat triangles, which show the + mesh resolution, then "Source Plane (Interpolated)" -- the + reconstruction the likelihood uses, over the max-zoom extent -- in the + middle, then Source Plane (No Zoom) bottom right. When ``False`` (or for + rectangular / parametric sources) they are max, mid and no zoom. The array-free 2 x 3 + layout adds the interpolated panel in its free last panel and keeps both + triangle panels. Set by ``plots.yaml`` + ``fit: subplot_fit_source_interpolated`` (default ``True``). """ + from autolens.imaging.plot.fit_imaging_plots import _source_has_interpolated_view + final_plane_index = len(fit.tracer.planes) - 1 + interpolated = source_interpolated and _source_has_interpolated_view( + fit, final_plane_index + ) + if image_plane_lines is None and source_plane_lines is None: tracer = fit.tracer_linear_light_profiles_to_light_profiles _cc_grid = fit.dataset.real_space_mask.derive_grid.all_false @@ -193,7 +265,15 @@ def subplot_fit( title=_pf("Source Plane (No Zoom)"), lines=source_plane_lines, line_colors=source_plane_line_colors) - axes_flat[5].axis("off") + if interpolated: + _plot_source_plane(fit, axes_flat[5], final_plane_index, + zoom_to_brightest=True, colormap=colormap, + title=_pf("Source Plane (Interpolated)"), + lines=source_plane_lines, + line_colors=source_plane_line_colors, + interpolated=True) + else: + axes_flat[5].axis("off") tight_layout() save_figure(fig, path=output_path, filename="fit", format=output_format) @@ -202,6 +282,8 @@ def subplot_fit( fig, axes = subplots(3, 4, figsize=conf_subplot_figsize(3, 4)) axes_flat = list(axes.flatten()) + source_vmax = _get_source_vmax(fit) + # Panel 0: amplitudes vs UV-distances plot_yx( y=np.real(fit.residual_map), @@ -215,14 +297,27 @@ def subplot_fit( plot_array(array=fit.dirty_image, ax=axes_flat[1], title=_pf("Dirty Image"), colormap=colormap) - plot_array(array=fit.dirty_signal_to_noise_map, ax=axes_flat[2], - title=_pf("Dirty Signal-To-Noise Map"), colormap=colormap) - # Panel 3 (4th): dirty model image with critical curves - plot_array(array=fit.dirty_model_image, ax=axes_flat[3], title=_pf("Dirty Model Image"), + # Panel 2: dirty model image with critical curves + plot_array(array=fit.dirty_model_image, ax=axes_flat[2], title=_pf("Dirty Model Image"), colormap=colormap, lines=image_plane_lines, line_colors=image_plane_line_colors) + # The right-hand column holds the three source panels, as in the imaging + # `fit.png`. With `source_interpolated` (the default) and an irregular-mesh + # source they are: max zoom (3) as flat triangles, which show the mesh + # resolution, the likelihood's interpolant (7) over the max-zoom extent, so + # it compares directly with panel 3, and no zoom (11). Otherwise (switch + # off, or a rectangular / parametric source) they are max, mid and no zoom. + + # Panel 3: source plane (max zoom) with caustics + _plot_source_plane(fit, axes_flat[3], final_plane_index, + zoom_to_brightest=True, colormap=colormap, + title=_pf("Source Plane (Max Zoom)"), + lines=source_plane_lines, + line_colors=source_plane_line_colors, + vmax=source_vmax) + # Panel 4: dirty residual map plot_array(array=fit.dirty_residual_map, ax=axes_flat[4], title=_pf("Dirty Residual Map"), colormap=colormap) @@ -249,12 +344,23 @@ def subplot_fit( plot_axis_type="scatter", ) - # Panel 7 (8th): source plane zoomed with caustics - _plot_source_plane(fit, axes_flat[7], final_plane_index, - zoom_to_brightest=True, colormap=colormap, - title=_pf("Source Plane (Zoomed)"), - lines=source_plane_lines, - line_colors=source_plane_line_colors) + if interpolated: + # Panel 7: the reconstruction the likelihood uses, over the max-zoom + # extent (the mid-zoom panel is replaced, see above) + _plot_source_plane(fit, axes_flat[7], final_plane_index, + zoom_to_brightest=True, colormap=colormap, + title=_pf("Source Plane (Interpolated)"), + lines=source_plane_lines, + line_colors=source_plane_line_colors, + vmax=source_vmax, interpolated=True) + else: + # Panel 7: source plane (mid zoom) -- same centre as Max Zoom, 2x wider extent + _plot_source_plane(fit, axes_flat[7], final_plane_index, + zoom_to_brightest=True, colormap=colormap, + title=_pf("Source Plane (Mid Zoom)"), + lines=source_plane_lines, + line_colors=source_plane_line_colors, + vmax=source_vmax, zoom_extent_scale=2.0) plot_array(array=fit.dirty_normalized_residual_map, ax=axes_flat[8], title=_pf("Dirty Normalized Residual Map"), colormap=colormap, cb_unit=r"$\sigma$") @@ -272,12 +378,13 @@ def subplot_fit( plot_array(array=fit.dirty_chi_squared_map, ax=axes_flat[10], title=_pf("Dirty Chi-Squared Map"), colormap=colormap, cb_unit=r"$\chi^2$") - # Panel 11 (12th): source plane not zoomed with caustics + # Panel 11: source plane not zoomed with caustics _plot_source_plane(fit, axes_flat[11], final_plane_index, zoom_to_brightest=False, colormap=colormap, title=_pf("Source Plane (No Zoom)"), lines=source_plane_lines, - line_colors=source_plane_line_colors) + line_colors=source_plane_line_colors, + vmax=source_vmax) tight_layout() save_figure(fig, path=output_path, filename="fit", format=output_format) diff --git a/test_autolens/imaging/plot/test_fit_source_interpolated.py b/test_autolens/imaging/plot/test_fit_source_interpolated.py new file mode 100644 index 000000000..9521c2262 --- /dev/null +++ b/test_autolens/imaging/plot/test_fit_source_interpolated.py @@ -0,0 +1,260 @@ +""" +`fit.png` / `fit_log10.png` source panels with the likelihood's interpolant in the +middle of the right-hand column, between max zoom and no zoom (`plots.yaml` +`fit: subplot_fit_source_interpolated`, default on, PyAutoArray#700). +""" + +import matplotlib.pyplot as plt +import pytest + +import autolens as al +from autolens import fixtures +from autolens.imaging.plot import fit_imaging_plots +from autolens.interferometer.plot import fit_interferometer_plots + + +def _delaunay_tracer_and_adapt(mask): + lens = al.Galaxy( + redshift=0.5, + mass=al.mp.Isothermal(centre=(0.1, 0.1), einstein_radius=1.0), + ) + source = al.Galaxy( + redshift=1.0, + pixelization=al.Pixelization( + mesh=al.mesh.Delaunay(pixels=9, zeroed_pixels=0), + regularization=al.reg.Constant(coefficient=0.01), + ), + ) + image_plane_mesh_grid = al.image_mesh.Overlay(shape=(3, 3)).image_plane_mesh_grid_from( + mask=mask, + ) + adapt_images = al.AdaptImages( + galaxy_image_plane_mesh_grid_dict={source: image_plane_mesh_grid}, + ) + return al.Tracer(galaxies=[lens, source]), adapt_images + + +@pytest.fixture(name="fit_imaging_delaunay") +def make_fit_imaging_delaunay(): + dataset = fixtures.make_masked_imaging_7x7() + tracer, adapt_images = _delaunay_tracer_and_adapt(dataset.mask) + return al.FitImaging(dataset=dataset, tracer=tracer, adapt_images=adapt_images) + + +@pytest.fixture(name="fit_interferometer_delaunay") +def make_fit_interferometer_delaunay(): + dataset = fixtures.make_interferometer_7() + tracer, adapt_images = _delaunay_tracer_and_adapt(dataset.real_space_mask) + return al.FitInterferometer(dataset=dataset, tracer=tracer, adapt_images=adapt_images) + + +def _titles(module, monkeypatch, subplot_fit, fit, **kwargs): + captured = {} + + def _capture(fig, *args, **kw): + captured["axes"] = { + ax.get_title(): ax for ax in fig.axes if ax.get_title() + } + plt.close(fig) + + monkeypatch.setattr(module, "save_figure", _capture) + subplot_fit(fit, **kwargs) + return captured["axes"] + + +def test__imaging__default__max_zoom__interpolated__no_zoom( + fit_imaging_delaunay, monkeypatch +): + captured = {} + + def _capture(fig, *args, **kw): + captured["fig"] = fig + + monkeypatch.setattr(fit_imaging_plots, "save_figure", _capture) + fit_imaging_plots.subplot_fit(fit_imaging_delaunay) + fig = captured["fig"] + titles = {ax.get_title(): ax for ax in fig.axes if ax.get_title()} + + assert "Source Plane (Mid Zoom)" not in titles + max_zoom = titles["Source Plane (Max Zoom)"] + no_zoom = titles["Source Plane (No Zoom)"] + interpolated = titles["Source Plane (Interpolated)"] + + # Right-hand column, top to bottom: max zoom, interpolated, no zoom. + def _y(ax): + return ax.get_position().y0 + + assert _y(max_zoom) > _y(interpolated) > _y(no_zoom) + assert max_zoom.get_position().x0 == pytest.approx(interpolated.get_position().x0) + assert max_zoom.get_position().x0 == pytest.approx(no_zoom.get_position().x0) + + assert len(max_zoom.get_images()) == 0 + assert len(no_zoom.get_images()) == 0 + assert len(interpolated.get_images()) == 1 + # The interpolated panel covers the max-zoom extent, for a direct comparison. + assert interpolated.get_xlim() == pytest.approx(max_zoom.get_xlim()) + plt.close(fig) + + +def test__imaging__switch_off__max_mid_no_zoom(fit_imaging_delaunay, monkeypatch): + axes = _titles( + fit_imaging_plots, monkeypatch, fit_imaging_plots.subplot_fit, + fit_imaging_delaunay, source_interpolated=False, + ) + assert "Source Plane (Max Zoom)" in axes + assert "Source Plane (Mid Zoom)" in axes + assert "Source Plane (No Zoom)" in axes + assert "Source Plane (Interpolated)" not in axes + + +def test__imaging__rectangular_source__keeps_max_mid_no_zoom(monkeypatch): + axes = _titles( + fit_imaging_plots, monkeypatch, fit_imaging_plots.subplot_fit, + fixtures.make_fit_imaging_x2_plane_inversion_7x7(), + ) + assert "Source Plane (Max Zoom)" in axes + assert "Source Plane (Mid Zoom)" in axes + assert "Source Plane (No Zoom)" in axes + assert "Source Plane (Interpolated)" not in axes + + +def _panel_titles(module, monkeypatch, subplot, fit, **kwargs): + """The 3 x 4 panel axes of a subplot in grid order (colorbars excluded).""" + captured = {} + + def _capture(fig, *args, **kw): + captured["axes"] = fig.axes[:12] + + monkeypatch.setattr(module, "save_figure", _capture) + subplot(fit, **kwargs) + axes = captured["axes"] + titles = [ax.get_title() for ax in axes] + plt.close(axes[0].get_figure()) + return titles, axes + + +def test__imaging_log10__default__max_zoom__interpolated__no_zoom( + fit_imaging_delaunay, monkeypatch +): + titles, axes = _panel_titles( + fit_imaging_plots, monkeypatch, fit_imaging_plots.subplot_fit_log10, + fit_imaging_delaunay, + ) + assert titles[3] == "Source Plane (Max Zoom)" + assert titles[7] == "Source Plane (Interpolated)" + assert titles[11] == "Source Plane (No Zoom)" + assert "Source Plane (Mid Zoom)" not in titles + + interpolated = axes[7] + assert len(interpolated.get_images()) == 1 + assert interpolated.get_images()[0].norm.__class__.__name__ == "LogNorm" + assert interpolated.get_xlim() == pytest.approx(axes[3].get_xlim()) + + +def test__imaging_log10__switch_off__max_mid_no_zoom(fit_imaging_delaunay, monkeypatch): + titles, _ = _panel_titles( + fit_imaging_plots, monkeypatch, fit_imaging_plots.subplot_fit_log10, + fit_imaging_delaunay, source_interpolated=False, + ) + assert titles[3] == "Source Plane (Max Zoom)" + assert titles[7] == "Source Plane (Mid Zoom)" + assert titles[11] == "Source Plane (No Zoom)" + assert "Source Plane (Interpolated)" not in titles + + +def test__imaging_log10__rectangular_source__keeps_max_mid_no_zoom(monkeypatch): + titles, _ = _panel_titles( + fit_imaging_plots, monkeypatch, fit_imaging_plots.subplot_fit_log10, + fixtures.make_fit_imaging_x2_plane_inversion_7x7(), + ) + assert titles[3] == "Source Plane (Max Zoom)" + assert titles[7] == "Source Plane (Mid Zoom)" + assert titles[11] == "Source Plane (No Zoom)" + + +_INTERFEROMETER_FIXED_PANELS = { + 0: "Amplitudes vs UV-Distance", + 1: "Dirty Image", + 2: "Dirty Model Image", + 4: "Dirty Residual Map", + 5: "Normalized Residual Map (Real)", + 6: "Normalized Residual Map (Imag)", + 8: "Dirty Normalized Residual Map", + 9: r"Normalized Residual Map $1\sigma$", + 10: "Dirty Chi-Squared Map", +} + + +def _assert_interferometer_fixed_panels(titles): + assert "Dirty Signal-To-Noise Map" not in titles + for index, title in _INTERFEROMETER_FIXED_PANELS.items(): + assert titles[index] == title + + +def _colorbar_vmax(ax): + mappables = ax.get_images() or ax.collections + return mappables[0].norm.vmax + + +def test__interferometer__default__max_zoom__interpolated__no_zoom( + fit_interferometer_delaunay, monkeypatch +): + titles, axes = _panel_titles( + fit_interferometer_plots, monkeypatch, fit_interferometer_plots.subplot_fit, + fit_interferometer_delaunay, + ) + _assert_interferometer_fixed_panels(titles) + assert titles[3] == "Source Plane (Max Zoom)" + assert titles[7] == "Source Plane (Interpolated)" + assert titles[11] == "Source Plane (No Zoom)" + + assert len(axes[3].get_images()) == 0 + assert len(axes[7].get_images()) == 1 + assert len(axes[11].get_images()) == 0 + assert axes[7].get_xlim() == pytest.approx(axes[3].get_xlim()) + + # Every source-plane panel shares one colour scale. + vmax = fit_interferometer_plots._get_source_vmax(fit_interferometer_delaunay) + assert vmax is not None + for index in (3, 7, 11): + assert _colorbar_vmax(axes[index]) == pytest.approx(vmax) + + +def test__interferometer__switch_off__max_mid_no_zoom( + fit_interferometer_delaunay, monkeypatch +): + titles, _ = _panel_titles( + fit_interferometer_plots, monkeypatch, fit_interferometer_plots.subplot_fit, + fit_interferometer_delaunay, source_interpolated=False, + ) + _assert_interferometer_fixed_panels(titles) + assert titles[3] == "Source Plane (Max Zoom)" + assert titles[7] == "Source Plane (Mid Zoom)" + assert titles[11] == "Source Plane (No Zoom)" + assert "Source Plane (Interpolated)" not in titles + + +@pytest.mark.parametrize( + "make_fit", + [ + fixtures.make_fit_interferometer_x2_plane_inversion_7x7, + fixtures.make_fit_interferometer_x2_plane_7x7, + ], + ids=["rectangular", "parametric"], +) +def test__interferometer__no_interpolated_view__max_mid_no_zoom(make_fit, monkeypatch): + titles, _ = _panel_titles( + fit_interferometer_plots, monkeypatch, fit_interferometer_plots.subplot_fit, + make_fit(), + ) + _assert_interferometer_fixed_panels(titles) + assert titles[3] == "Source Plane (Max Zoom)" + assert titles[7] == "Source Plane (Mid Zoom)" + assert titles[11] == "Source Plane (No Zoom)" + + +def test__plots_yaml__switch_defaults_on(): + from autolens.analysis.plotter import plot_setting + + assert plot_setting(section=["fit", "fit_imaging"], name="subplot_fit_source_interpolated") is True + assert plot_setting(section=["fit", "fit_interferometer"], name="subplot_fit_source_interpolated") is True