From 8d885abc1e40a75bc80047ff89dccf6912e047f3 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Wed, 21 Oct 2026 13:59:47 +0100 Subject: [PATCH] =?UTF-8?q?feat:=20point=20positions=20panels=20=E2=80=94?= =?UTF-8?q?=20solver=20extent,=20visible=20markers,=20noise=20circles,=20t?= =?UTF-8?q?itles=20(#785)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The dataset and fit "Positions" panels span the PointSolver grid extent (fallback: the #783 critical-curve square), drop the axis labels, draw large filled markers with true-radius noise circles and sigma in the legend, and are titled "Dataset Positions ()" / "Fit Positions ()". The fit panel adds model positions, residual lines from the fit's own pairing, unmatched model images, critical curves and mass centres. critical_curve_grid_from takes an optional solver and covers its grid, so curves are never broken inside the panel. Co-Authored-By: Claude Opus 5.5 --- autolens/lens/plot/critical_curves.py | 35 +- autolens/point/model/plotter.py | 23 +- autolens/point/model/visualizer.py | 12 +- autolens/point/plot/fit_point_plots.py | 99 +++-- autolens/point/plot/point_dataset_plots.py | 44 +- autolens/point/plot/positions_panel.py | 381 ++++++++++++++++++ .../point/model/test_plotter_point.py | 27 ++ .../point/plot/test_positions_panel.py | 277 +++++++++++++ 8 files changed, 850 insertions(+), 48 deletions(-) create mode 100644 autolens/point/plot/positions_panel.py create mode 100644 test_autolens/point/plot/test_positions_panel.py diff --git a/autolens/lens/plot/critical_curves.py b/autolens/lens/plot/critical_curves.py index b30523c2d7..e51cd770e9 100644 --- a/autolens/lens/plot/critical_curves.py +++ b/autolens/lens/plot/critical_curves.py @@ -68,7 +68,11 @@ def _compute_critical_curve_lines(tracer, grid): def critical_curve_grid_from( - dataset, shape_native=(100, 100), scale: float = 2.0, buffer: float = 0.1 + dataset, + shape_native=(100, 100), + scale: float = 2.0, + buffer: float = 0.1, + solver=None, ) -> "ag.Grid2D": """ Returns the grid on which the critical curves and caustics of a dataset's lens model are computed. @@ -82,6 +86,11 @@ def critical_curve_grid_from( ``dataset.extent_from`` returns ``[y_min, y_max, x_min, x_max]`` whereas ``Grid2D.from_extent`` takes the extent x first, which this function handles. + If a ``solver`` (e.g. a ``PointSolver``) with rectangular bounds is passed, the square is enlarged where needed + so it also covers the solver grid. The point-source positions panels are drawn over the solver grid's extent, + so a critical curve computed on a smaller grid would otherwise stop inside the panel as disconnected arcs; on + the enlarged grid it is only ever cut by the panel frame itself. + Parameters ---------- dataset @@ -93,12 +102,36 @@ def critical_curve_grid_from( The factor by which the grid's half-width exceeds the half-span of the positions. buffer A buffer (arc-seconds) added to the half-span of the positions. + solver + An optional solver whose ``y_min`` / ``y_max`` / ``x_min`` / ``x_max`` bounds the grid is enlarged to cover. """ y_min, y_max, x_min, x_max = dataset.extent_from(buffer=0.0) y_centre, x_centre = (y_min + y_max) / 2.0, (x_min + x_max) / 2.0 half_width = scale * (max(y_max - y_min, x_max - x_min) / 2.0 + buffer) + if solver is not None: + try: + solver_bounds = [ + float(solver.y_min), + float(solver.y_max), + float(solver.x_min), + float(solver.x_max), + ] + except (AttributeError, TypeError, ValueError): + solver_bounds = None + if solver_bounds is not None and all( + abs(bound) < float("inf") for bound in solver_bounds + ): + s_y_min, s_y_max, s_x_min, s_x_max = solver_bounds + half_width = max( + half_width, + abs(s_y_min - y_centre), + abs(s_y_max - y_centre), + abs(s_x_min - x_centre), + abs(s_x_max - x_centre), + ) + # `Grid2D.from_extent` takes the extent x first: (x0, x1, y0, y1). return ag.Grid2D.from_extent( extent=( diff --git a/autolens/point/model/plotter.py b/autolens/point/model/plotter.py index d5c52a559f..1fe343f12d 100644 --- a/autolens/point/model/plotter.py +++ b/autolens/point/model/plotter.py @@ -13,7 +13,7 @@ class PlotterPoint(Plotter): - def dataset_point(self, dataset: PointDataset): + def dataset_point(self, dataset: PointDataset, solver=None): """ Output visualization of a `PointDataset` dataset. @@ -21,6 +21,9 @@ def dataset_point(self, dataset: PointDataset): ---------- dataset The point dataset which is visualized. + solver + The `PointSolver` of the model-fit, whose grid sets the extent of the positions panel. If `None`, the + panel extent falls back to the critical-curve region around the positions. """ def should_plot(name): @@ -30,8 +33,13 @@ def should_plot(name): fmt = self.fmt if should_plot("subplot_dataset"): - subplot_dataset(dataset, output_path=output_path, output_format=fmt, - title_prefix=self.title_prefix) + subplot_dataset( + dataset, + output_path=output_path, + output_format=fmt, + title_prefix=self.title_prefix, + solver=solver, + ) def image_with_points( self, @@ -115,7 +123,9 @@ def should_plot(name): # Use pre-computed critical curves if provided, otherwise compute once here. if image_plane_lines is None and source_plane_lines is None: - grid = critical_curve_grid_from(dataset=fit.dataset) + grid = critical_curve_grid_from( + dataset=fit.dataset, solver=getattr(fit, "solver", None) + ) ip_lines, ip_colors, sp_lines, sp_colors = _compute_critical_curve_lines( fit.tracer, grid ) @@ -125,6 +135,11 @@ def should_plot(name): source_plane_lines, source_plane_line_colors, ) + # `subplot_fit` computes the curves itself when it is given none, so pass an explicit empty list when the + # model has no critical curves, rather than computing them twice. + if ip_lines is None: + ip_lines, ip_colors = [], [] + if quick_update: subplot_fit_point( fit, output_path=output_path, output_format=fmt, diff --git a/autolens/point/model/visualizer.py b/autolens/point/model/visualizer.py index 10c07ae11d..eb5bad4acd 100644 --- a/autolens/point/model/visualizer.py +++ b/autolens/point/model/visualizer.py @@ -31,7 +31,9 @@ def visualize_before_fit( image_path=paths.image_path, title_prefix=analysis.title_prefix ) - plotter.dataset_point(dataset=analysis.dataset) + plotter.dataset_point( + dataset=analysis.dataset, solver=getattr(analysis, "solver", None) + ) if getattr(analysis, "image", None) is not None: # Dataset-only figure (observed positions, no model): `image_with_points.png`. @@ -78,9 +80,13 @@ def visualize( grid = critical_curve_grid_from(dataset=fit.dataset) - # Compute critical curves and caustics once for all plot functions. + # Compute critical curves and caustics once for all plot functions, on a grid which also covers the + # solver grid, so the curves on the solver-extent positions panel are only ever cut by its frame. ip_lines, ip_colors, sp_lines, sp_colors = _compute_critical_curve_lines( - tracer, grid + tracer, + critical_curve_grid_from( + dataset=fit.dataset, solver=getattr(fit, "solver", None) + ), ) plotter.fit_point( diff --git a/autolens/point/plot/fit_point_plots.py b/autolens/point/plot/fit_point_plots.py index f0d1cf8eaa..af87e2ac61 100644 --- a/autolens/point/plot/fit_point_plots.py +++ b/autolens/point/plot/fit_point_plots.py @@ -13,6 +13,7 @@ def subplot_fit( source_plane_lines=None, source_plane_line_colors=None, title_prefix: str = None, + solver=None, ): """ Produce a subplot summarising a `FitPointDataset`. @@ -20,9 +21,27 @@ def subplot_fit( The subplot contains one or two panels depending on whether flux measurements are present in the dataset: - * **Positions panel** (always shown): observed point-source positions - plotted as a grid, with the model-predicted positions overlaid as - red scatter points. + * **Positions panel** (always shown), titled ``Fit Positions ()``. + Drawn on the same frame as the dataset positions panel (the + ``PointSolver`` grid extent, no axis labels), it shows: + + - the observed positions as large filled markers with their noise-map + circles and the sigma in the legend; + - the model positions on top as red crosses; + - a thin ``Residual`` line from each observed position to the model + position the fit's own pairing matches it to (Hungarian for + ``FitPositionsImagePair``, nearest for ``FitPositionsImagePairRepeat`` + and the dominant nearest term of ``FitPositionsImagePairAll``); + - model images no observed position is paired with as hollow grey + crosses (``Unmatched model image``); + - the tangential / radial critical curves, thin and light, clipped at the + panel edge where they extend beyond the solver grid; + - the centre of every mass profile in the tracer (``Mass centre``). + + For a source-plane fit (e.g. ``FitPositionsSource``) the model data are + the observed positions ray-traced to the source plane: they are drawn as + ``Model (source plane)`` crosses and no residual lines or unmatched images + are drawn, as there is no image-plane pairing. * **Fluxes panel** (shown only when ``fit.dataset.fluxes`` is not ``None``): a bar/line plot of the observed flux values. @@ -35,38 +54,70 @@ def subplot_fit( not saved to disk. output_format : str, optional Image format passed to :func:`~autoarray.plot.utils.save_figure`. + image_plane_lines : list, optional + Critical-curve lines drawn on the positions panel. If this and + ``source_plane_lines`` are both ``None`` they are computed from the + fit's tracer on ``critical_curve_grid_from`` (enlarged to cover the + solver grid); pass ``[]`` to draw none. + image_plane_line_colors : list, optional + Colours of each image-plane line (``"white"`` tangential, ``"yellow"`` + radial, as returned by the critical-curve helper). + source_plane_lines, source_plane_line_colors + Accepted for a uniform plotter interface; not drawn. + title_prefix : str, optional + Text prepended to every panel title. + solver : PointSolver, optional + The solver whose grid sets the positions panel extent. Defaults to + ``fit.solver``. """ - from autogalaxy.util.plot_utils import plot_grid from autoarray.plot.yx import plot_yx + from autolens.point.plot.positions_panel import ( + finish_positions_panel, + plot_critical_curves, + plot_fit_model_positions, + plot_mass_centres, + plot_observed_positions, + positions_extent_from, + ) has_fluxes = fit.dataset.fluxes is not None n = 2 if has_fluxes else 1 + if solver is None: + solver = getattr(fit, "solver", None) + + if image_plane_lines is None and source_plane_lines is None: + from autolens.lens.plot.critical_curves import ( + _compute_critical_curve_lines, + critical_curve_grid_from, + ) + + image_plane_lines, image_plane_line_colors, _, _ = ( + _compute_critical_curve_lines( + fit.tracer, critical_curve_grid_from(dataset=fit.dataset, solver=solver) + ) + ) + fig, axes = subplots(1, n, figsize=conf_subplot_figsize(1, n)) axes_flat = [axes] if n == 1 else list(np.array(axes).flatten()) + _prefix = f"{title_prefix.rstrip()} " if title_prefix else "" + # Positions panel - obs_grid = np.array( - fit.dataset.positions.array - if hasattr(fit.dataset.positions, "array") - else fit.dataset.positions - ) - model_grid = np.array( - fit.positions.model_data.array - if hasattr(fit.positions.model_data, "array") - else fit.positions.model_data + ax = axes_flat[0] + plot_critical_curves(ax, image_plane_lines, image_plane_line_colors) + plot_mass_centres(ax, fit.tracer) + plot_observed_positions( + ax=ax, + positions=fit.dataset.positions, + noise_map=fit.dataset.positions_noise_map, ) - - _prefix = f"{title_prefix.rstrip()} " if title_prefix else "" - plot_grid( - grid=obs_grid, - ax=axes_flat[0], - title=f"{_prefix}{fit.dataset.name} Fit Positions", - output_path=None, - output_filename=None, - output_format=output_format, + plot_fit_model_positions(ax, fit.positions) + finish_positions_panel( + ax=ax, + title=f"{_prefix}Fit Positions ({fit.dataset.name})", + extent=positions_extent_from(positions=fit.dataset.positions, solver=solver), ) - axes_flat[0].scatter(model_grid[:, 1], model_grid[:, 0], c="r", s=20, zorder=5) # Fluxes panel if has_fluxes and n > 1: @@ -76,7 +127,7 @@ def subplot_fit( y=y, x=x, ax=axes_flat[1], - title=f"{_prefix}{fit.dataset.name} Fit Fluxes", + title=f"{_prefix}Fit Fluxes ({fit.dataset.name})", output_path=None, output_filename="fit_point_fluxes", output_format=output_format, diff --git a/autolens/point/plot/point_dataset_plots.py b/autolens/point/plot/point_dataset_plots.py index 7ca54aa0f6..8d203521cc 100644 --- a/autolens/point/plot/point_dataset_plots.py +++ b/autolens/point/plot/point_dataset_plots.py @@ -9,6 +9,7 @@ def subplot_dataset( output_path: Optional[str] = None, output_format: str = None, title_prefix: str = None, + solver=None, ): """ Produce a subplot visualising a `PointDataset`. @@ -16,8 +17,14 @@ def subplot_dataset( The subplot contains one or two panels depending on whether flux measurements are present: - * **Positions panel** (always shown): the observed point-source - positions rendered as a grid scatter plot. + * **Positions panel** (always shown), titled ``Dataset Positions ()``: + the observed point-source positions as large filled markers, each with a + circle at its noise-map radius (never inflated, so it may be sub-pixel) + and the sigma stated in the legend, e.g. ``Observed (σ = 0.005″)``. The + panel extent is the ``PointSolver`` grid extent when ``solver`` is given + (where the model can find images), otherwise the critical-curve region of + ``critical_curve_grid_from``, so no position is clipped. There are no axis + labels, only arc-second tick labels. * **Fluxes panel** (shown only when ``dataset.fluxes`` is not ``None``): a line/bar plot of the observed flux values indexed by image position. @@ -31,9 +38,17 @@ def subplot_dataset( not saved to disk. output_format : str, optional Image format passed to :func:`~autoarray.plot.utils.save_figure`. + title_prefix : str, optional + Text prepended to every panel title. + solver : PointSolver, optional + The solver of the model-fit, whose grid sets the positions panel extent. """ - from autogalaxy.util.plot_utils import plot_grid from autoarray.plot.yx import plot_yx + from autolens.point.plot.positions_panel import ( + finish_positions_panel, + plot_observed_positions, + positions_extent_from, + ) has_fluxes = dataset.fluxes is not None n = 2 if has_fluxes else 1 @@ -41,20 +56,17 @@ def subplot_dataset( fig, axes = subplots(1, n, figsize=conf_subplot_figsize(1, n)) axes_flat = [axes] if n == 1 else list(np.array(axes).flatten()) - grid = np.array( - dataset.positions.array - if hasattr(dataset.positions, "array") - else dataset.positions - ) - _prefix = f"{title_prefix.rstrip()} " if title_prefix else "" - plot_grid( - grid=grid, + + plot_observed_positions( + ax=axes_flat[0], + positions=dataset.positions, + noise_map=dataset.positions_noise_map, + ) + finish_positions_panel( ax=axes_flat[0], - title=f"{_prefix}{dataset.name} Positions", - output_path=None, - output_filename=None, - output_format=output_format, + title=f"{_prefix}Dataset Positions ({dataset.name})", + extent=positions_extent_from(positions=dataset.positions, solver=solver), ) if has_fluxes and n > 1: @@ -64,7 +76,7 @@ def subplot_dataset( y=y, x=x, ax=axes_flat[1], - title=f"{_prefix}{dataset.name} Fluxes", + title=f"{_prefix}Dataset Fluxes ({dataset.name})", output_path=None, output_filename="point_dataset_fluxes", output_format=output_format, diff --git a/autolens/point/plot/positions_panel.py b/autolens/point/plot/positions_panel.py new file mode 100644 index 0000000000..04be55ad6a --- /dev/null +++ b/autolens/point/plot/positions_panel.py @@ -0,0 +1,381 @@ +""" +Shared drawing of the point-source "Positions" panels of ``dataset_point.png`` and ``fit.png``. + +Both panels are drawn on the same frame: + +- **Extent.** The extent of the ``PointSolver`` grid when a solver is available, so the panel shows the region in + which the model can find images. Without a solver it falls back to the critical-curve region of + :func:`~autolens.lens.plot.critical_curves.critical_curve_grid_from` (a square of twice the half-span of the + positions, plus a buffer), which contains every position. +- **Markers.** Large filled markers for the observed positions, with a circle of radius equal to each position's + noise-map value (one isotropic sigma per position) and the sigma always stated in the legend. The circle is drawn + at its true radius and is never inflated, so at high-resolution noise and a large solver extent it is sub-pixel. +- **No axis labels**, so the arc-second tick labels are not overlapped. + +The fit panel additionally draws the model positions, the residual lines of the fit's own pairing, unmatched model +images, critical curves and the centres of the tracer's mass profiles. +""" + +import numpy as np +from typing import List, Optional, Tuple + +OBSERVED_COLOR = "k" +NOISE_COLOR = "tab:orange" +MODEL_COLOR = "r" +UNMATCHED_COLOR = "0.45" +MASS_CENTRE_COLOR = "tab:green" + +# Critical-curve colours: `_compute_critical_curve_lines` returns white (tangential) and yellow (radial) lines for +# dark image backgrounds, which are invisible on the white positions panel, so they are mapped to light colours +# here that stay readable without swamping the residual lines. +CRITICAL_CURVE_COLOR_MAP = {"white": "0.6", "yellow": "tab:olive"} + + +def _np_grid(grid) -> np.ndarray: + """ + Returns a (N, 2) numpy array of (y,x) coordinates from a grid-like input. + """ + grid = grid.array if hasattr(grid, "array") else grid + return np.asarray(grid, dtype=float).reshape(-1, 2) + + +def solver_extent_from(solver) -> Optional[List[float]]: + """ + Returns the ``[x_min, x_max, y_min, y_max]`` extent of a ``PointSolver``'s grid, or ``None`` if the solver is + ``None`` or does not have finite, rectangular bounds (e.g. a custom solver). + """ + if solver is None: + return None + try: + y_min, y_max = float(solver.y_min), float(solver.y_max) + x_min, x_max = float(solver.x_min), float(solver.x_max) + except (AttributeError, TypeError, ValueError): + return None + bounds = np.array([x_min, x_max, y_min, y_max]) + if not np.all(np.isfinite(bounds)) or x_max <= x_min or y_max <= y_min: + return None + return [x_min, x_max, y_min, y_max] + + +def fallback_extent_from( + positions, scale: float = 2.0, buffer: float = 0.1 +) -> List[float]: + """ + Returns the ``[x_min, x_max, y_min, y_max]`` extent used when no solver is available. + + This is the square of :func:`~autolens.lens.plot.critical_curves.critical_curve_grid_from` (centred on the + bounding box of the positions, with half-width ``scale`` times their half-span plus ``buffer``), so the panel + covers the region the critical curves are computed on and contains every position. + """ + positions = _np_grid(positions) + y_min, y_max = positions[:, 0].min(), positions[:, 0].max() + x_min, x_max = positions[:, 1].min(), positions[:, 1].max() + y_centre, x_centre = (y_min + y_max) / 2.0, (x_min + x_max) / 2.0 + half_width = scale * (max(y_max - y_min, x_max - x_min) / 2.0 + buffer) + return [ + x_centre - half_width, + x_centre + half_width, + y_centre - half_width, + y_centre + half_width, + ] + + +def positions_extent_from(positions, solver=None) -> List[float]: + """ + Returns the ``[x_min, x_max, y_min, y_max]`` extent of a positions panel. + + With a solver this is the solver grid's extent. If an observed position lies outside it (a solver grid too + small for the data, which ``AnalysisPoint`` already warns about) the extent is enlarged just enough to contain + that position with a margin, so no observed position is ever clipped. Without a solver it is + :func:`fallback_extent_from`. + """ + extent = solver_extent_from(solver) + if extent is None: + return fallback_extent_from(positions) + + positions = _np_grid(positions) + margin = 0.05 * max(extent[1] - extent[0], extent[3] - extent[2]) + x_min, x_max, y_min, y_max = extent + if np.any(positions[:, 1] < x_min) or np.any(positions[:, 1] > x_max): + x_min = min(x_min, positions[:, 1].min() - margin) + x_max = max(x_max, positions[:, 1].max() + margin) + if np.any(positions[:, 0] < y_min) or np.any(positions[:, 0] > y_max): + y_min = min(y_min, positions[:, 0].min() - margin) + y_max = max(y_max, positions[:, 0].max() + margin) + return [x_min, x_max, y_min, y_max] + + +def _format_arcsec(value: float) -> str: + return f"{value:.3g}″" + + +def sigma_label_from(noise_map) -> str: + """ + Returns the sigma text of the observed-positions legend entry, e.g. ``σ = 0.005″``, or ``σ = 0.005–0.01″`` + when the positions have different noise-map values. + """ + noise = np.asarray( + noise_map.array if hasattr(noise_map, "array") else noise_map, dtype=float + ).ravel() + noise = noise[np.isfinite(noise)] + if noise.size == 0: + return "σ = n/a" + if np.allclose(noise, noise[0]): + return f"σ = {_format_arcsec(noise[0])}" + return f"σ = {noise.min():.3g}–{_format_arcsec(noise.max())}" + + +def plot_observed_positions(ax, positions, noise_map): + """ + Draws the observed positions as large filled markers, each with a circle of radius equal to its noise-map + value (never inflated), labelled ``Observed (σ = ...)`` in the legend. + """ + from matplotlib.patches import Circle + + positions = _np_grid(positions) + noise = np.broadcast_to( + np.asarray( + noise_map.array if hasattr(noise_map, "array") else noise_map, dtype=float + ).ravel(), + (len(positions),), + ) + + ax.scatter( + positions[:, 1], + positions[:, 0], + s=110, + c=OBSERVED_COLOR, + marker="o", + zorder=4, + label=f"Observed ({sigma_label_from(noise_map)})", + ) + for (y, x), sigma in zip(positions, noise): + if np.isfinite(sigma) and sigma > 0: + ax.add_patch( + Circle( + (x, y), + radius=sigma, + fill=False, + edgecolor=NOISE_COLOR, + linewidth=1.0, + zorder=5, + ) + ) + + +def plot_critical_curves(ax, lines, line_colors=None): + """ + Draws critical curves as thin, light lines labelled ``Critical curve`` in the legend. + + The curves are computed on :func:`~autolens.lens.plot.critical_curves.critical_curve_grid_from` passed the + solver, whose grid covers the whole panel, so a curve is never broken inside the panel: a curve which runs past + the panel edge is cut cleanly by the axes frame, which tells the reader it extends beyond the solver grid. + """ + if not lines: + return + labelled = False + for i, line in enumerate(lines): + line = np.asarray(line) + if line.ndim != 2 or len(line) == 0: + continue + color = line_colors[i] if line_colors and i < len(line_colors) else "white" + ax.plot( + line[:, 1], + line[:, 0], + color=CRITICAL_CURVE_COLOR_MAP.get(color, color), + linewidth=0.9, + alpha=0.8, + zorder=2, + label=None if labelled else "Critical curve", + ) + labelled = True + + +def mass_centres_from(tracer) -> np.ndarray: + """ + Returns the (y,x) centres of every mass profile of every galaxy in the tracer, as a (N, 2) array with + duplicates removed. + + External shear is skipped, as its ``centre`` has no physical meaning. + """ + import autogalaxy as ag + + centres = [] + for galaxy in getattr(tracer, "galaxies", []): + try: + mass_profiles = galaxy.cls_list_from(cls=ag.mp.MassProfile) + except AttributeError: + continue + for mass_profile in mass_profiles: + if isinstance(mass_profile, ag.mp.ExternalShear): + continue + centre = getattr(mass_profile, "centre", None) + if centre is None: + continue + try: + centre = (float(centre[0]), float(centre[1])) + except (TypeError, ValueError, IndexError): + continue + if np.all(np.isfinite(centre)) and centre not in centres: + centres.append(centre) + return np.asarray(centres, dtype=float).reshape(-1, 2) + + +def plot_mass_centres(ax, tracer): + """ + Draws the centre of every mass profile in the tracer as a ``+`` labelled ``Mass centre`` in the legend. + """ + centres = mass_centres_from(tracer) + if len(centres) == 0: + return + ax.scatter( + centres[:, 1], + centres[:, 0], + s=140, + c=MASS_CENTRE_COLOR, + marker="+", + linewidths=2, + zorder=4.5, + label="Mass centre", + ) + + +def model_pairing_from( + fit_positions, +) -> Optional[Tuple[np.ndarray, np.ndarray, np.ndarray]]: + """ + Returns the image-plane pairing of observed to model positions which the fit's chi-squared uses, as a tuple + ``(observed, model, model_index_per_observed)``, where ``model`` holds only the finite model positions and + ``model_index_per_observed[i]`` is the model position observed position ``i`` is paired with (``-1`` if the + model has no images). + + - ``FitPositionsImagePair``: the Hungarian (one-to-one) assignment; observed positions the assignment cannot + pair (fewer model than observed images) are paired with their nearest model position, as in its residuals. + - ``FitPositionsImagePairRepeat``: each observed position's nearest model position (repeats allowed). + - ``FitPositionsImagePairAll``: each observed position's nearest model position, the dominant term of its + all-pairs mixture likelihood (the mixture has no hard pairing). + + Source-plane fits (e.g. ``FitPositionsSource``) have no image-plane pairing, so ``None`` is returned. + """ + from autolens.point.fit.positions.image.abstract import ( + AbstractFitPositionsImagePair, + ) + from autolens.point.fit.positions.image.pair import FitPositionsImagePair + + if not isinstance(fit_positions, AbstractFitPositionsImagePair): + return None + + observed = _np_grid(fit_positions.data) + model = _np_grid(fit_positions.model_data) + model = model[np.isfinite(model).all(axis=1)] + + if len(model) == 0: + return observed, model, np.full(len(observed), -1, dtype=int) + + distances = np.linalg.norm(observed[:, None, :] - model[None, :, :], axis=2) + indexes = np.argmin(distances, axis=1) + + if isinstance(fit_positions, FitPositionsImagePair): + from scipy.optimize import linear_sum_assignment + + data_indexes, model_indexes = linear_sum_assignment(distances) + indexes[data_indexes] = model_indexes + + return observed, model, indexes + + +def unmatched_model_mask_from(model: np.ndarray, indexes: np.ndarray) -> np.ndarray: + """ + Returns a boolean mask over the (finite) model positions, true for every model image no observed position is + paired with: an image the model predicts but which is not observed. + """ + mask = np.ones(len(model), dtype=bool) + mask[indexes[indexes >= 0]] = False + return mask + + +def plot_fit_model_positions(ax, fit_positions): + """ + Draws the model positions of a positions fit on top of the observed positions. + + For an image-plane fit the matched model positions are drawn as red crosses, a thin ``Residual`` line joins + each observed position to the model position the fit pairs it with, and model images no observed position is + paired with are drawn as hollow grey crosses (``Unmatched model image``). + + For a source-plane fit (e.g. ``FitPositionsSource``) the model data are the observed positions ray-traced to + the source plane: they are drawn as red crosses labelled ``Model (source plane)`` and no residual lines are + drawn, as there is no image-plane pairing. + """ + pairing = model_pairing_from(fit_positions) + + if pairing is None: + model = _np_grid(fit_positions.model_data) + model = model[np.isfinite(model).all(axis=1)] + if len(model): + ax.scatter( + model[:, 1], + model[:, 0], + s=80, + c=MODEL_COLOR, + marker="x", + linewidths=2.5, + zorder=7, + label="Model (source plane)", + ) + return + + observed, model, indexes = pairing + + labelled = False + for obs, index in zip(observed, indexes): + if index < 0: + continue + ax.plot( + [obs[1], model[index, 1]], + [obs[0], model[index, 0]], + color=MODEL_COLOR, + linewidth=1.0, + alpha=0.7, + zorder=6, + label=None if labelled else "Residual", + ) + labelled = True + + unmatched = unmatched_model_mask_from(model, indexes) + + if np.any(~unmatched): + ax.scatter( + model[~unmatched, 1], + model[~unmatched, 0], + s=80, + c=MODEL_COLOR, + marker="x", + linewidths=2.5, + zorder=7, + label="Model", + ) + if np.any(unmatched): + ax.scatter( + model[unmatched, 1], + model[unmatched, 0], + s=110, + facecolors="none", + edgecolors=UNMATCHED_COLOR, + marker="X", + linewidths=1.5, + zorder=7, + label="Unmatched model image", + ) + + +def finish_positions_panel(ax, title: str, extent: List[float]): + """ + Applies the title, extent and arc-second ticks of a positions panel, with no axis labels, an equal aspect + ratio (so noise circles are circles) and a legend. + """ + from autoarray.plot.utils import apply_labels, apply_extent + + apply_labels(ax, title=title, xlabel="", ylabel="") + apply_extent(ax, extent) + ax.set_aspect("equal", adjustable="box") + ax.legend(loc="best", fontsize=9, framealpha=0.85, markerscale=0.7) diff --git a/test_autolens/point/model/test_plotter_point.py b/test_autolens/point/model/test_plotter_point.py index 087381c489..8cc1a5e86f 100644 --- a/test_autolens/point/model/test_plotter_point.py +++ b/test_autolens/point/model/test_plotter_point.py @@ -203,3 +203,30 @@ def test__critical_curve_grid_from__extent_is_x_first(): assert grid[:, 0].max() - grid[:, 0].min() == pytest.approx( grid[:, 1].max() - grid[:, 1].min(), abs=0.05 ) + + +def test__visualizer__before_fit__passes_analysis_solver_to_dataset_panel( + fit_point_dataset_x2_plane, plot_path, plot_patch, monkeypatch +): + from types import SimpleNamespace + + import autolens.point.model.plotter as plotter_module + from autolens.point.model.visualizer import VisualizerPoint + + solvers = [] + + def recording_subplot_dataset(dataset, **kwargs): + solvers.append(kwargs.get("solver")) + + monkeypatch.setattr(plotter_module, "subplot_dataset", recording_subplot_dataset) + + analysis = SimpleNamespace( + dataset=fit_point_dataset_x2_plane.dataset, + solver=fit_point_dataset_x2_plane.solver, + title_prefix=None, + ) + paths = SimpleNamespace(image_path=plot_path, output_path=plot_path) + + VisualizerPoint.visualize_before_fit(analysis=analysis, paths=paths, model=None) + + assert solvers == [fit_point_dataset_x2_plane.solver] diff --git a/test_autolens/point/plot/test_positions_panel.py b/test_autolens/point/plot/test_positions_panel.py new file mode 100644 index 0000000000..04a933ed86 --- /dev/null +++ b/test_autolens/point/plot/test_positions_panel.py @@ -0,0 +1,277 @@ +import numpy as np +import pytest + +import autolens as al +from autolens import fixtures +from autolens.point.plot import fit_point_plots, point_dataset_plots +from autolens.point.plot.positions_panel import ( + fallback_extent_from, + mass_centres_from, + model_pairing_from, + plot_fit_model_positions, + positions_extent_from, + sigma_label_from, + unmatched_model_mask_from, +) + + +@pytest.fixture(name="figures") +def make_figures(monkeypatch): + """ + Captures the figures the subplot functions would save, so their axes can be inspected. + """ + figures = [] + + def capture(fig, **kwargs): + figures.append(fig) + + monkeypatch.setattr(point_dataset_plots, "save_figure", capture) + monkeypatch.setattr(fit_point_plots, "save_figure", capture) + return figures + + +def _legend_labels(ax): + return [text.get_text() for text in ax.get_legend().get_texts()] + + +def _solver(pixel_scales=0.5, shape_native=(20, 20)): + return al.PointSolver.for_grid( + grid=al.Grid2D.uniform(shape_native=shape_native, pixel_scales=pixel_scales), + pixel_scale_precision=0.25, + magnification_threshold=1e-8, + ) + + +def _point_dataset(noise=0.005): + return al.PointDataset( + name="point_0", + positions=al.Grid2DIrregular([(1.0, 1.0), (-1.5, 0.5), (0.2, -2.2)]), + positions_noise_map=noise, + ) + + +def test__positions_extent_from__solver_extent_when_solver_given(): + solver = _solver() + extent = positions_extent_from(positions=_point_dataset().positions, solver=solver) + + assert extent == pytest.approx( + [solver.x_min, solver.x_max, solver.y_min, solver.y_max] + ) + + +def test__positions_extent_from__enlarged_when_a_position_is_outside_solver_grid(): + solver = _solver(pixel_scales=0.1, shape_native=(10, 10)) + positions = _point_dataset().positions + + x_min, x_max, y_min, y_max = positions_extent_from( + positions=positions, solver=solver + ) + + grid = np.asarray(positions.array) + assert np.all(grid[:, 1] > x_min) and np.all(grid[:, 1] < x_max) + assert np.all(grid[:, 0] > y_min) and np.all(grid[:, 0] < y_max) + + +def test__positions_extent_from__fallback_contains_all_positions(): + positions = _point_dataset().positions + + x_min, x_max, y_min, y_max = positions_extent_from(positions=positions, solver=None) + + assert [x_min, x_max, y_min, y_max] == fallback_extent_from(positions) + grid = np.asarray(positions.array) + assert np.all(grid[:, 1] > x_min) and np.all(grid[:, 1] < x_max) + assert np.all(grid[:, 0] > y_min) and np.all(grid[:, 0] < y_max) + + +def test__sigma_label_from(): + assert sigma_label_from(al.ArrayIrregular([0.005, 0.005])) == "σ = 0.005″" + assert sigma_label_from([0.005, 0.01]) == "σ = 0.005–0.01″" + + +def test__subplot_dataset__title_extent_sigma_legend_and_no_axis_labels(figures): + solver = _solver() + + point_dataset_plots.subplot_dataset(dataset=_point_dataset(), solver=solver) + + ax = figures[0].axes[0] + assert ax.get_title() == "Dataset Positions (point_0)" + assert ax.get_xlabel() == "" and ax.get_ylabel() == "" + assert ax.get_xlim() == pytest.approx((solver.x_min, solver.x_max)) + assert ax.get_ylim() == pytest.approx((solver.y_min, solver.y_max)) + assert _legend_labels(ax) == ["Observed (σ = 0.005″)"] + + # One noise circle per position, at the true noise-map radius (never inflated). + radii = [patch.get_radius() for patch in ax.patches] + assert radii == pytest.approx([0.005, 0.005, 0.005]) + + +def test__subplot_dataset__title_prefix(figures): + point_dataset_plots.subplot_dataset(dataset=_point_dataset(), title_prefix="Lens ") + + assert figures[0].axes[0].get_title() == "Lens Dataset Positions (point_0)" + + +def _fit(fit_positions_cls=al.FitPositionsImagePair): + return al.FitPointDataset( + dataset=fixtures.make_point_dataset(), + tracer=fixtures.make_tracer_x2_plane_point(), + solver=fixtures.make_solver(), + fit_positions_cls=fit_positions_cls, + ) + + +def test__subplot_fit__title_extent_legend_mass_centres_and_curves(figures): + fit = _fit() + curve = np.array([[0.0, 1.0], [1.0, 0.0], [0.0, -1.0]]) + + fit_point_plots.subplot_fit( + fit=fit, + image_plane_lines=[curve], + image_plane_line_colors=["white"], + ) + + ax = figures[0].axes[0] + assert ax.get_title() == "Fit Positions (point_0)" + assert figures[0].axes[1].get_title() == "Fit Fluxes (point_0)" + assert ax.get_xlabel() == "" and ax.get_ylabel() == "" + assert ax.get_xlim() == pytest.approx((fit.solver.x_min, fit.solver.x_max)) + + labels = _legend_labels(ax) + assert "Observed (σ = 1″)" in labels + assert "Critical curve" in labels + assert "Mass centre" in labels + + # The mass centre of the tracer's lens galaxy is plotted. + centres = mass_centres_from(fit.tracer) + assert len(centres) >= 1 + mass_scatter = [c for c in ax.collections if c.get_label() == "Mass centre"][0] + assert np.asarray(mass_scatter.get_offsets()) == pytest.approx(centres[:, ::-1]) + + +def test__subplot_fit__computes_critical_curves_when_none_given(figures, monkeypatch): + import autolens.lens.plot.critical_curves as critical_curves + + calls = [] + + def fake_lines(tracer, grid): + calls.append(grid) + return [np.array([[0.0, 1.0], [1.0, 0.0]])], ["white"], None, None + + monkeypatch.setattr(critical_curves, "_compute_critical_curve_lines", fake_lines) + + fit_point_plots.subplot_fit(fit=_fit()) + + assert len(calls) == 1 + assert "Critical curve" in _legend_labels(figures[0].axes[0]) + + figures.clear() + fit_point_plots.subplot_fit(fit=_fit(), image_plane_lines=[], source_plane_lines=[]) + + assert len(calls) == 1 + assert "Critical curve" not in _legend_labels(figures[0].axes[0]) + + +def test__subplot_fit__source_plane_fit_has_no_residual_lines(figures): + fit_point_plots.subplot_fit( + fit=_fit(fit_positions_cls=al.FitPositionsSource), image_plane_lines=[] + ) + + labels = _legend_labels(figures[0].axes[0]) + assert "Model (source plane)" in labels + assert "Residual" not in labels + assert "Unmatched model image" not in labels + + +def _fixed_pair_fit(cls, data, model): + """ + An image-plane positions fit of class ``cls`` with fixed observed and model positions. + """ + + class Fixed(cls): + def __init__(self): + pass + + @property + def data(self): + return al.Grid2DIrregular(data) + + @property + def model_data(self): + return al.Grid2DIrregular(model) + + return Fixed() + + +def test__model_pairing_from__each_fit_class_uses_its_own_matching(): + data = [(0.0, 0.0), (0.0, 0.4)] + model = [(0.0, 0.3), (0.0, 1.0)] + + # Nearest neighbour (repeats allowed): both observed positions pair with model 0. + _, _, indexes = model_pairing_from( + _fixed_pair_fit(al.FitPositionsImagePairRepeat, data, model) + ) + assert list(indexes) == [0, 0] + + # Hungarian one-to-one assignment: observed 0 -> model 0, observed 1 -> model 1. + _, _, indexes = model_pairing_from( + _fixed_pair_fit(al.FitPositionsImagePair, data, model) + ) + assert sorted(indexes) == [0, 1] + + # Source-plane fits have no image-plane pairing. + assert model_pairing_from(_fit(al.FitPositionsSource).positions) is None + + +def test__plot_fit_model_positions__residual_lines_and_unmatched_model_images(): + import matplotlib.pyplot as plt + + data = [(0.0, 0.0), (1.0, 1.0)] + model = [(0.0, 0.1), (1.0, 1.1), (-2.0, 2.0), (np.inf, np.inf)] + fit_positions = _fixed_pair_fit(al.FitPositionsImagePairRepeat, data, model) + + _, finite_model, indexes = model_pairing_from(fit_positions) + assert len(finite_model) == 3 + assert list(unmatched_model_mask_from(finite_model, indexes)) == [ + False, + False, + True, + ] + + fig, ax = plt.subplots() + plot_fit_model_positions(ax, fit_positions) + + residual_lines = [line for line in ax.lines] + assert len(residual_lines) == 2 + assert residual_lines[0].get_label() == "Residual" + assert np.asarray(residual_lines[0].get_xydata()) == pytest.approx( + np.array([[0.0, 0.0], [0.1, 0.0]]) + ) + + scatters = {c.get_label(): c for c in ax.collections} + assert np.asarray(scatters["Model"].get_offsets()) == pytest.approx( + np.array([[0.1, 0.0], [1.1, 1.0]]) + ) + assert np.asarray(scatters["Unmatched model image"].get_offsets()) == pytest.approx( + np.array([[2.0, -2.0]]) + ) + plt.close(fig) + + +def test__critical_curve_grid_from__covers_solver_grid(): + from autolens.lens.plot.critical_curves import critical_curve_grid_from + + dataset = _point_dataset() + solver = _solver(pixel_scales=1.0, shape_native=(20, 20)) + + grid = np.asarray(critical_curve_grid_from(dataset=dataset, solver=solver).array) + + assert grid[:, 0].min() <= solver.y_min + 1e-8 + assert grid[:, 0].max() >= solver.y_max - 1e-8 + assert grid[:, 1].min() <= solver.x_min + 1e-8 + assert grid[:, 1].max() >= solver.x_max - 1e-8 + + # A solver grid inside the default square leaves it unchanged. + small = _solver(pixel_scales=0.1, shape_native=(10, 10)) + assert np.asarray( + critical_curve_grid_from(dataset=dataset, solver=small).array + ) == pytest.approx(np.asarray(critical_curve_grid_from(dataset=dataset).array))