From 4f5c51d28a05c27e5f2b544d1763779fb2ca990a Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Wed, 21 Oct 2026 21:57:14 +0100 Subject: [PATCH 1/2] feat: cluster/multi-source point figures with per-redshift curves (#793) Unified Dataset Positions / Fit Positions figures for one or many point sources, the new fit_per_image.png (residual ranking / IP / SP rows), multi- source image_with_points / fit_image_with_points, each source's critical curves at its own redshift from the full tracer (fast deflection-field contouring), darker/thicker curves and caustics, -2 ln L for the all-pairs mixture, and combined (factor-graph) visualization with plots.yaml toggles. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019Y6tDwGThyc8UowuncXw88 --- autolens/config/visualize/plots.yaml | 8 +- autolens/point/model/plotter.py | 155 ++- autolens/point/model/visualizer.py | 171 ++- autolens/point/plot/fit_point_plots.py | 308 ++--- autolens/point/plot/multi_source_plots.py | 1120 +++++++++++++++++ autolens/point/plot/point_dataset_plots.py | 67 +- autolens/point/plot/point_sources.py | 593 +++++++++ autolens/point/plot/positions_panel.py | 18 +- autolens/point/plot/source_plane_panel.py | 37 +- .../point/plot/test_fit_point_plots.py | 4 +- .../point/plot/test_multi_source_plots.py | 345 +++++ .../point/plot/test_positions_panel.py | 21 +- .../point/plot/test_source_plane_panel.py | 32 +- 13 files changed, 2562 insertions(+), 317 deletions(-) create mode 100644 autolens/point/plot/multi_source_plots.py create mode 100644 autolens/point/plot/point_sources.py create mode 100644 test_autolens/point/plot/test_multi_source_plots.py diff --git a/autolens/config/visualize/plots.yaml b/autolens/config/visualize/plots.yaml index 3ba95d0f0..bfb02024d 100644 --- a/autolens/config/visualize/plots.yaml +++ b/autolens/config/visualize/plots.yaml @@ -54,12 +54,18 @@ fit_interferometer: # Settings for plots of fits to inter fits_dirty_images: true # output dirty_images.fits showing the dirty image, noise-map, model-data, resiual-map, normalized residual map and chi-squared map? point_dataset: # Settings for plots of point source datasets (e.g. PointDatasetPlotter). - subplot_dataset: true # Plot subplot containing all dataset quantities (e.g. the data, noise-map, etc.)? + subplot_dataset: true # Plot the observed positions of the dataset ("Dataset Positions", numbered images, solver extent) (dataset_point.png)? image_with_points: true # Plot the observed image (if passed to AnalysisPoint) with the observed positions over it (image_with_points.png)? + subplot_dataset_combined: true # Multi-dataset (e.g. cluster) fits: plot every source's observed positions in one panel, labelled k·i, in the top-level image folder (dataset_point.png)? + image_with_points_combined: true # Multi-dataset (e.g. cluster) fits: plot the observed image with every source's positions over it, in the top-level image folder (image_with_points.png)? fit_point_dataset: # Settings for plots of fits to point source datasets (e.g. FitPointDatasetPlotter). + fit_per_image: true # Plot one row per source of its residual ranking (Δ/σ), image-plane zoom and source-plane panel (fit_per_image.png)? fit_image_with_points: true # Plot the observed image (if passed to AnalysisPoint) with observed and model positions and critical curves over it (fit_image_with_points.png)? subplot_point_solver: false # Plot how the PointSolver refines its triangles onto the best-fit model's images (point_solver.png)? Re-solves with NumPy at the best fit only, so it is off by default. + subplot_fit_combined: true # Multi-dataset (e.g. cluster) fits: plot every source's fit in one panel, each source's critical curves at its own redshift, in the top-level image folder (fit.png)? + fit_per_image_combined: true # Multi-dataset (e.g. cluster) fits: plot fit_per_image.png for every source, the ranking range shared across sources (one file per source in fit_per_image/ beyond 8 sources)? + fit_image_with_points_combined: true # Multi-dataset (e.g. cluster) fits: plot the observed image with every source's observed and model positions and critical curves over it (fit_image_with_points.png)? weak_dataset: # Settings for plots of weak lensing shear catalogues (e.g. PlotterWeak). subplot_dataset: true # Plot subplot containing all dataset quantities (e.g. the shear field, noise-map, etc.)? diff --git a/autolens/point/model/plotter.py b/autolens/point/model/plotter.py index e7ac3e379..3cfaaaad7 100644 --- a/autolens/point/model/plotter.py +++ b/autolens/point/model/plotter.py @@ -1,18 +1,27 @@ from autolens.analysis.plotter import Plotter -from autolens.imaging.plot.fit_imaging_plots import _compute_critical_curve_lines -from autolens.lens.plot.critical_curves import critical_curve_grid_from - from autolens.point.fit.dataset import FitPointDataset from autolens.point.plot.fit_point_plots import subplot_fit as subplot_fit_point from autolens.point.plot.fit_point_plots import plot_image_with_points from autolens.point.dataset import PointDataset from autolens.point.plot.point_dataset_plots import subplot_dataset from autolens.point.plot import point_solver_plots +from autolens.point.plot import multi_source_plots from autolens.analysis.plotter import plot_setting +def _setting(section, name: str, default: bool = True) -> bool: + """ + A ``plots.yaml`` toggle which falls back to ``default`` when a (e.g. older workspace) config does not have the + key. + """ + try: + return plot_setting(section=section, name=name) + except KeyError: + return default + + class PlotterPoint(Plotter): def dataset_point(self, dataset: PointDataset, solver=None): """ @@ -49,6 +58,7 @@ def image_with_points( fit: FitPointDataset = None, image_plane_lines=None, image_plane_line_colors=None, + curves=None, ): """ Output an observed image of the lensed point source with the point-source positions overlaid. @@ -70,13 +80,16 @@ def image_with_points( Pre-computed critical-curve lines to overlay on the image. image_plane_line_colors Colours for each image-plane line. + curves + The per-plane curves of :func:`~autolens.point.plot.point_sources.curves_for_planes`, so each source's + curves are drawn at its own redshift. """ if fit is None: section, name = ["point_dataset"], "image_with_points" else: section, name = ["fit", "fit_point_dataset"], "fit_image_with_points" - if not plot_setting(section=section, name=name): + if not _setting(section, name): return plot_image_with_points( @@ -88,6 +101,7 @@ def image_with_points( image_plane_lines=image_plane_lines, image_plane_line_colors=image_plane_line_colors, title_prefix=self.title_prefix, + curves=curves, ) def fit_point( @@ -98,9 +112,11 @@ def fit_point( image_plane_line_colors=None, source_plane_lines=None, source_plane_line_colors=None, + curves=None, ): """ - Visualizes a `FitPointDataset` object. + Visualizes a `FitPointDataset` object: ``fit.png`` (controlled by ``fit: subplot_fit``, also output on a + quick update). Parameters ---------- @@ -114,53 +130,102 @@ def fit_point( Pre-computed caustic lines to overlay on source-plane panels. source_plane_line_colors Colours for each source-plane line. + curves + The per-plane curves of :func:`~autolens.point.plot.point_sources.curves_for_planes`; computed if + ``None``. """ + if not quick_update and not _setting(["fit", "fit_point_dataset"], "subplot_fit"): + return - def should_plot(name): - return plot_setting(section=["fit", "fit_point_dataset"], name=name) + subplot_fit_point( + fit, + output_path=str(self.image_path), + output_format=self.fmt, + image_plane_lines=image_plane_lines, + image_plane_line_colors=image_plane_line_colors, + source_plane_lines=source_plane_lines, + source_plane_line_colors=source_plane_line_colors, + title_prefix=self.title_prefix, + curves=curves, + ) - output_path = str(self.image_path) - fmt = self.fmt + def fit_per_image(self, fit_list, curves=None, solver=None, combined: bool = False): + """ + Output ``fit_per_image.png``: one row per source of its residual ranking, image-plane zoom and source-plane + panel (beyond 8 sources, one file per source in ``fit_per_image/``). - # 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, solver=getattr(fit, "solver", None) - ) - ip_lines, ip_colors, sp_lines, sp_colors = _compute_critical_curve_lines( - fit.tracer, grid - ) - else: - ip_lines, ip_colors, sp_lines, sp_colors = ( - image_plane_lines, image_plane_line_colors, - source_plane_lines, source_plane_line_colors, - ) + Controlled by ``fit_point_dataset: fit_per_image`` for a single dataset and + ``fit_point_dataset: fit_per_image_combined`` for the all-sources figure of a multi-dataset (e.g. cluster) + fit, whose ranking range is shared by every source. + """ + name = "fit_per_image_combined" if combined else "fit_per_image" + if not _setting(["fit", "fit_point_dataset"], name): + return + multi_source_plots.subplot_fit_per_image( + fit_list, + curves=curves, + solver=solver, + output_path=str(self.image_path), + output_format=self.fmt, + title_prefix=self.title_prefix, + ) - # `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, - 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, - ) + def dataset_point_combined(self, dataset_list, solver=None): + """ + Output ``dataset_point.png`` of every point dataset of a multi-dataset (e.g. cluster) fit in one panel, + controlled by ``point_dataset: subplot_dataset_combined``. + """ + if not _setting(["point_dataset"], "subplot_dataset_combined"): return + multi_source_plots.plot_dataset_positions( + dataset_list, + solver=solver, + output_path=str(self.image_path), + output_format=self.fmt, + title_prefix=self.title_prefix, + ) - if should_plot("subplot_fit"): - subplot_fit_point( - fit, output_path=output_path, output_format=fmt, - 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, - ) + def fit_point_combined(self, fit_list, curves=None, solver=None, quick_update: bool = False): + """ + Output ``fit.png`` of every point dataset of a multi-dataset (e.g. cluster) fit in one panel ("Fit + Positions", each source's curves at its own redshift), controlled by + ``fit_point_dataset: subplot_fit_combined`` and always output on a quick update. + """ + if not quick_update and not _setting( + ["fit", "fit_point_dataset"], "subplot_fit_combined" + ): + return + multi_source_plots.plot_fit_positions( + fit_list, + solver=solver, + curves=curves, + output_path=str(self.image_path), + output_format=self.fmt, + title_prefix=self.title_prefix, + ) + + def image_with_points_combined(self, image, dataset_list, fit_list=None, curves=None, solver=None): + """ + Output ``image_with_points.png`` (no fit) or ``fit_image_with_points.png`` of every point dataset of a + multi-dataset (e.g. cluster) fit over one observed image, controlled by + ``point_dataset: image_with_points_combined`` and ``fit_point_dataset: fit_image_with_points_combined``. + """ + if fit_list is None: + section, name = ["point_dataset"], "image_with_points_combined" + else: + section, name = ["fit", "fit_point_dataset"], "fit_image_with_points_combined" + if not _setting(section, name): + return + multi_source_plots.plot_image_with_points( + image=image, + datasets=dataset_list, + fits=fit_list, + curves=curves, + solver=solver, + output_path=str(self.image_path), + output_format=self.fmt, + title_prefix=self.title_prefix, + ) def point_solver(self, fit: FitPointDataset, image_plane_lines=None): """ diff --git a/autolens/point/model/visualizer.py b/autolens/point/model/visualizer.py index 17ddca76c..9f11b0cd4 100644 --- a/autolens/point/model/visualizer.py +++ b/autolens/point/model/visualizer.py @@ -2,7 +2,7 @@ from autolens.point.model.plotter import PlotterPoint from autolens.lens.plot.critical_curves import critical_curve_grid_from -from autolens.imaging.plot.fit_imaging_plots import _compute_critical_curve_lines +from autolens.point.plot import point_sources as ps class VisualizerPoint(af.Visualizer): @@ -77,26 +77,17 @@ def visualize( ) tracer = fit.tracer + solver = getattr(fit, "solver", None) grid = critical_curve_grid_from(dataset=fit.dataset) - # 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, - critical_curve_grid_from( - dataset=fit.dataset, solver=getattr(fit, "solver", None) - ), - ) + # The critical curves and caustics of the point source's own plane (and of the last plane, for the tracer + # figures), computed once from the FULL tracer on the solver extent for every figure (the fast + # deflection-field contouring of `point_sources.curves_for_planes`). + curves = curves_for_point_fits(fits=[fit], solver=solver) + ip_lines, ip_colors, sp_lines, sp_colors = last_plane_lines_from(tracer, curves) - plotter.fit_point( - fit=fit, - quick_update=quick_update, - image_plane_lines=ip_lines, - image_plane_line_colors=ip_colors, - source_plane_lines=sp_lines, - source_plane_line_colors=sp_colors, - ) + plotter.fit_point(fit=fit, quick_update=quick_update, curves=curves) # Output even on `quick_update`, so the observed image with model positions updates on-the-fly. Saved as # `fit_image_with_points.png`, so the dataset-only `image_with_points.png` from before the fit is kept. @@ -107,11 +98,14 @@ def visualize( fit=fit, image_plane_lines=ip_lines, image_plane_line_colors=ip_colors, + curves=curves, ) if quick_update: return + plotter.fit_per_image(fit_list=[fit], curves=curves, solver=solver) + plotter.tracer( tracer=tracer, grid=grid, @@ -130,3 +124,146 @@ def visualize( plotter.point_solver( fit=fit, image_plane_lines=ip_lines if ip_lines is not None else [] ) + + @staticmethod + def visualize_before_fit_combined( + analyses, + paths: af.AbstractPaths, + model: af.AbstractPriorModel, + ): + """ + Before the fit of several point datasets (e.g. a cluster), output the figures of every source in one panel + to the top-level ``image`` folder: ``dataset_point.png`` and, if an observed image was passed to an + ``AnalysisPoint``, ``image_with_points.png``. Each dataset's own figures are output by + ``visualize_before_fit`` to its ``analyses/analysis_`` folder. + """ + analyses = _point_analyses_from(analyses) + if len(analyses) < 2: + return + + plotter = PlotterPoint( + image_path=paths.image_path, title_prefix=analyses[0].title_prefix + ) + _visualize_datasets_combined(plotter, analyses) + + @staticmethod + def visualize_combined( + analyses, + paths: af.AbstractPaths, + instance: af.ModelInstance, + during_analysis: bool, + quick_update: bool = False, + ): + """ + Output the figures of every point dataset of a multi-dataset (e.g. cluster) fit in one panel, to the + top-level ``image`` folder of the search (each dataset's own figures are output by ``visualize`` to its + ``analyses/analysis_`` folder): + + - ``fit.png``: every source's observed and model positions and its critical curves at its own redshift + (also output on a quick update); + - ``fit_per_image.png``: one row per source, with the residual ranking range shared by every source + (``fit_per_image/.png`` beyond 8 sources); + - ``fit_image_with_points.png`` if an observed image was passed to an ``AnalysisPoint``; + - the dataset figures of ``visualize_before_fit_combined`` (``dataset_point.png``, + ``image_with_points.png``), as a factor-graph fit does not call that function. + + The curves are computed once, from the FULL tracer, for every source plane. + """ + pairs = [ + (analysis, single_instance) + for analysis, single_instance in zip(analyses, instance) + if _is_point_analysis(analysis) + ] + if len(pairs) < 2: + return + + analyses = [analysis for analysis, _ in pairs] + plotter = PlotterPoint( + image_path=paths.image_path, title_prefix=analyses[0].title_prefix + ) + + fit_list = [ + analysis.fit_for_visualization(instance=single_instance) + for analysis, single_instance in pairs + ] + solver = getattr(analyses[0], "solver", None) or getattr( + fit_list[0], "solver", None + ) + curves = curves_for_point_fits(fits=fit_list, solver=solver) + + plotter.fit_point_combined( + fit_list=fit_list, curves=curves, solver=solver, quick_update=quick_update + ) + + image = _image_from(analyses) + if image is not None: + plotter.image_with_points_combined( + image=image, + dataset_list=[fit.dataset for fit in fit_list], + fit_list=fit_list, + curves=curves, + solver=solver, + ) + + if quick_update: + return + + plotter.fit_per_image( + fit_list=fit_list, curves=curves, solver=solver, combined=True + ) + _visualize_datasets_combined(plotter, analyses) + + +def _is_point_analysis(analysis) -> bool: + from autolens.point.model.analysis import AnalysisPoint + + return isinstance(analysis, AnalysisPoint) + + +def _point_analyses_from(analyses): + if analyses is None: + return [] + return [getattr(a, "analysis", a) for a in analyses if _is_point_analysis(getattr(a, "analysis", a))] + + +def _image_from(analyses): + for analysis in analyses: + image = getattr(analysis, "image", None) + if image is not None: + return image + return None + + +def _visualize_datasets_combined(plotter, analyses): + solver = getattr(analyses[0], "solver", None) + dataset_list = [analysis.dataset for analysis in analyses] + plotter.dataset_point_combined(dataset_list=dataset_list, solver=solver) + image = _image_from(analyses) + if image is not None: + plotter.image_with_points_combined( + image=image, dataset_list=dataset_list, solver=solver + ) + + +def curves_for_point_fits(fits, solver=None): + """ + The per-plane critical curves and caustics of point-source fits: every source's own plane and the last plane, + from the FULL tracer, on the extent of the positions figures (the solver grid, enlarged to contain every observed + position). + """ + records = ps.records_from_fits(fits) + extent = ps.union_extent_from(records, solver=solver) + return ps.curves_for_fits(fits, records, extent) + + +def last_plane_lines_from(tracer, curves): + """ + The last plane's curves as the ``(image_plane_lines, colors, source_plane_lines, colors)`` the tracer and galaxy + figures draw (``None`` lines when there are none). + """ + last = curves.get(len(tracer.planes) - 1) if curves else None + if last is None: + return None, None, None, None + ip_lines, ip_colors = last.image_plane_lines() + sp_lines, sp_colors = last.source_plane_lines() + return ip_lines, ip_colors, sp_lines, sp_colors diff --git a/autolens/point/plot/fit_point_plots.py b/autolens/point/plot/fit_point_plots.py index 9fb44651b..3a8017747 100644 --- a/autolens/point/plot/fit_point_plots.py +++ b/autolens/point/plot/fit_point_plots.py @@ -18,40 +18,23 @@ def subplot_fit( source_plane_line_colors=None, title_prefix: str = None, solver=None, + curves=None, ): """ - Produce a subplot summarising a `FitPointDataset`. - - The subplot is one row of two or three panels, depending on whether flux measurements are present in the - dataset: - - * **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, numbered 1..N in the order the - ``PointSolver`` figure numbers its images, each number beside its image; - - for an image-plane fit, 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``), and - 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``). - - A source-plane fit (e.g. ``FitPositionsSource``) draws no model positions here: its model data lie in the - source plane and are drawn on the source-plane panel. - * **Source-plane panel** (always shown), titled ``Fit Source Plane ()``: the observed positions - ray-traced to the point source's plane, numbered as on the positions panel, the source centre and the - caustics of that plane, zoomed onto the traced positions with an inset of the whole caustic. What it draws is - paired to the fit class (see :mod:`autolens.point.plot.source_plane_panel`): context only for an image-plane - chi-squared; the noise footprint and chi-squared of the fit's weighting for a source-plane chi-squared. - * **Fluxes panel** (shown only when ``fit.dataset.fluxes`` is not - ``None``): a bar/line plot of the observed flux values. + Produce ``fit.png`` of a `FitPointDataset`: the "Fit Positions" panel of + :func:`~autolens.point.plot.multi_source_plots.plot_fit_positions` for this one source, plus a "Fit Fluxes" + panel when the dataset has fluxes. + + The "Fit Positions" panel is drawn on the ``PointSolver`` grid extent with no axis labels. It shows the observed + positions (black dots, σ circles, σ in the legend) numbered 1..N as on every point-source figure; for an + image-plane fit the model positions (red ✕) at their true position, each joined to its observed image by a + true-length residual line of the fit's own pairing (solid for hard pairing, dashed for the soft all-pairs + mixture), and unmatched model images (hollow ✕); the critical curves of the plane the point source is in (dark + and thick); the mass centres; and the fit's figure of merit (``χ²``, or ``−2 ln L`` for the all-pairs mixture). + The legend sits in the panel's emptiest corner. + + The fit's source-plane panel and per-image residual ranking are drawn by + :func:`~autolens.point.plot.multi_source_plots.subplot_fit_per_image` (``fit_per_image.png``). Parameters ---------- @@ -62,132 +45,124 @@ 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 - Caustics drawn on the source-plane panel when the point source is in the tracer's last plane (the plane - these lines are computed for). For a point source in an earlier plane of a multi-plane tracer, or when no - lines are passed, the caustics of the point source's own plane are computed on - ``critical_curve_grid_from``. Pass ``[]`` for both line arguments to draw no curves on either panel. + image_plane_lines, image_plane_line_colors, source_plane_lines, source_plane_line_colors + Kept for API compatibility. Pass ``image_plane_lines=[]`` (or ``curves={}``) to draw no curves; otherwise + the curves of the point source's own plane are drawn (``curves``). 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``. + curves : dict, optional + The per-plane curves of :func:`~autolens.point.plot.point_sources.curves_for_planes`; computed on the + panel extent if ``None``. """ from autoarray.plot.yx import plot_yx - from autolens.lens.plot.critical_curves import critical_curve_grid_from - from autolens.point.plot.positions_panel import ( - finish_positions_panel, - image_numbers_from, - plot_critical_curves, - plot_fit_model_positions, - plot_image_numbers, - plot_mass_centres, - plot_observed_positions, - positions_extent_from, - ) - from autolens.point.plot import source_plane_panel - - has_fluxes = fit.dataset.fluxes is not None - n = 3 if has_fluxes else 2 + from autolens.point.plot import multi_source_plots as msp + from autolens.point.plot import point_sources as ps if solver is None: solver = getattr(fit, "solver", None) - lines_given = image_plane_lines is not None or source_plane_lines is not None + records = ps.records_from_fits([fit]) + colormap = ps.assign_styles(records) + extent = ps.union_extent_from(records, solver=solver) - if not lines_given: - from autolens.lens.plot.critical_curves import _compute_critical_curve_lines + no_curves_requested = ( + image_plane_lines is not None + and len(image_plane_lines) == 0 + and not source_plane_lines + ) + if curves is None: + if no_curves_requested: + curves = {} + elif image_plane_lines: + # Pre-computed lines given by the caller: draw them as this source's curves. + curves = { + records[0].plane_index: _plane_curves_from_lines( + fit, + records[0].plane_index, + image_plane_lines, + image_plane_line_colors, + source_plane_lines, + source_plane_line_colors, + ) + } + else: + curves = ps.curves_for_records(fit.tracer, records, extent) - ( - image_plane_lines, - image_plane_line_colors, - source_plane_lines, - source_plane_line_colors, - ) = _compute_critical_curve_lines( - fit.tracer, critical_curve_grid_from(dataset=fit.dataset, solver=solver) - ) + has_fluxes = fit.dataset.fluxes is not None + n = 2 if has_fluxes else 1 + + if n == 1: + from autoarray.plot.utils import conf_figsize - fig, axes = subplots(1, n, figsize=conf_subplot_figsize(1, n)) - axes_flat = list(np.array(axes).flatten()) + fig, ax = subplots(1, 1, figsize=conf_figsize("figures")) + axes_flat = [ax] + else: + fig, axes = subplots(1, n, figsize=conf_subplot_figsize(1, n)) + axes_flat = list(np.array(axes).flatten()) _prefix = f"{title_prefix.rstrip()} " if title_prefix else "" - numbers = image_numbers_from(fit.dataset.positions) - - # Positions panel - ax = axes_flat[0] - extent = positions_extent_from(positions=fit.dataset.positions, solver=solver) - 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, - ) - plot_fit_model_positions(ax, fit.positions) - finish_positions_panel( - ax=ax, + msp.draw_fit_positions( + axes_flat[0], + records, + curves, + extent, + fit.tracer, title=f"{_prefix}Fit Positions ({fit.dataset.name})", - extent=extent, + colormap=colormap, ) - plot_image_numbers(ax, fit.dataset.positions, numbers, extent) - # Source-plane panel - source_plane_title = f"{_prefix}Fit Source Plane ({fit.dataset.name})" - try: - data = source_plane_panel.source_plane_data_from( - fit.positions, numbers=numbers - ) - tangential, radial = source_plane_caustics_from( - fit=fit, - solver=solver, - lines_given=lines_given, - source_plane_lines=source_plane_lines, - source_plane_line_colors=source_plane_line_colors, - ) - source_plane_panel.plot_source_plane_panel( - ax=axes_flat[1], - data=data, - title=source_plane_title, - tangential_caustics=tangential, - radial_caustics=radial, - ) - except Exception: - # A visualization must never stop a model-fit: report the failure and leave the panel empty. - logger.warning( - "The source-plane panel of fit.png could not be drawn; it is left empty.", - exc_info=True, - ) - axes_flat[1].cla() - axes_flat[1].set_title(source_plane_title) - axes_flat[1].set_axis_off() - - # Fluxes panel if has_fluxes: y = np.array(fit.dataset.fluxes) x = np.arange(len(y)) plot_yx( y=y, x=x, - ax=axes_flat[2], + ax=axes_flat[1], title=f"{_prefix}Fit Fluxes ({fit.dataset.name})", output_path=None, output_filename="fit_point_fluxes", output_format=output_format, ) + tight_layout() - tight_layout() save_figure(fig, path=output_path, filename="fit", format=output_format) +def _plane_curves_from_lines( + fit, + plane_index, + image_plane_lines, + image_plane_line_colors, + source_plane_lines, + source_plane_line_colors, +): + """ + Wraps pre-computed critical-curve lines (``"white"`` tangential, ``"yellow"`` radial) as the ``PlaneCurves`` of + the point source's plane. + """ + from autolens.point.plot import point_sources as ps + from autolens.point.plot import source_plane_panel + + tangential, radial = source_plane_panel.caustics_from_lines( + image_plane_lines, image_plane_line_colors + ) + tangential_caustics, radial_caustics = source_plane_panel.caustics_from_lines( + source_plane_lines, source_plane_line_colors + ) + return ps.PlaneCurves( + plane_index=plane_index, + redshift=float(fit.tracer.planes[plane_index].redshift), + tangential=tangential, + radial=radial, + tangential_caustics=tangential_caustics, + radial_caustics=radial_caustics, + ) + + def source_plane_caustics_from( fit, solver=None, @@ -234,23 +209,20 @@ def plot_image_with_points( image_plane_lines=None, image_plane_line_colors=None, title_prefix: str = None, + curves=None, + solver=None, ): """ Plot an observed image of a lensed point source (e.g. a quasar) with its point-source positions overlaid. - The observed positions of the `PointDataset` are drawn as hollow white rings, so they stand out against - the image without hiding the point-source emission beneath them. When a `FitPointDataset` is passed, the model-predicted positions - are drawn as red crosses (image-plane fits only, as a source-plane fit's model data lies in the source - plane), and critical curves can be overlaid via ``image_plane_lines``. + This is :func:`~autolens.point.plot.multi_source_plots.plot_image_with_points` for one source: the observed + positions in the symbols of the positions figures (a white-edged black dot), numbered; with a fit, the model + positions (red ✕, image-plane fits only, as a source-plane fit's model data lie in the source plane) joined to + their observed image by residual lines and the critical curves of the point source's own plane. There is no + legend. - The function produces two figures, depending on whether a fit is passed: - - - ``fit=None`` (dataset-only): only the observed image and observed positions are drawn, saved as - ``image_with_points``. Use this to display the data before lens modeling, passing no fit and no - ``image_plane_lines``. - - ``fit`` given: the model positions (and critical curves, via ``image_plane_lines``) are added, the title - becomes " Fit Image With Points" and the figure is saved as ``fit_image_with_points``, so it does not - overwrite the dataset-only figure. + - ``fit=None`` (dataset-only): saved as ``image_with_points``. + - ``fit`` given: saved as ``fit_image_with_points``, so it does not overwrite the dataset-only figure. The image is used only for visualization: it does not enter the point-source likelihood. @@ -261,58 +233,28 @@ def plot_image_with_points( dataset : PointDataset The point-source dataset whose observed positions are overlaid. fit : FitPointDataset, optional - If given, its model positions are overlaid as red crosses and the figure is saved as - ``fit_image_with_points``; if ``None`` it is the dataset-only ``image_with_points``. + If given, its model positions and curves are overlaid and the figure is saved as ``fit_image_with_points``. output_path : str, optional Directory in which to save the figure. If ``None`` the figure is 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 overlaid on the image. - image_plane_line_colors : list, optional - Colours for each image-plane line. + image_plane_lines, image_plane_line_colors + Pre-computed critical-curve lines, drawn only if the per-plane ``curves`` cannot be computed. + curves : dict, optional + The per-plane curves of :func:`~autolens.point.plot.point_sources.curves_for_planes`. """ - from autogalaxy.util.plot_utils import plot_array - from autoarray.plot.utils import conf_figsize, _overlay_yx_for_origin - - fig, ax = subplots(1, 1, figsize=conf_figsize("figures")) - - _prefix = f"{title_prefix.rstrip()} " if title_prefix else "" - plot_array( - array=image, - ax=ax, - lines=image_plane_lines, - line_colors=image_plane_line_colors, - title=f"{_prefix}{dataset.name} {'Image' if fit is None else 'Fit Image'} With Points", - ) - - # Positions are (y,x) arc-seconds: reflect them exactly as `plot_array` does its own overlays, using the - # extent and origin of the raster it drew, so they stay registered to the image (PyAutoArray#565). - extent, origin = (ax.images[0].get_extent(), ax.images[0].origin) if ax.images else (None, None) - - def _yx(grid): - grid = np.array(grid.array if hasattr(grid, "array") else grid).reshape(-1, 2) - return _overlay_yx_for_origin(grid, extent, origin) - - obs_grid = _yx(dataset.positions) - ax.scatter( - obs_grid[:, 1], obs_grid[:, 0], - s=150, facecolors="none", edgecolors="w", linewidths=2, zorder=6, label="Observed", + from autolens.point.plot import multi_source_plots as msp + + msp.plot_image_with_points( + image=image, + datasets=[dataset], + fits=None if fit is None else [fit], + curves=curves, + solver=solver, + output_path=output_path, + output_format=output_format, + title_prefix=title_prefix, + image_plane_lines=image_plane_lines, + image_plane_line_colors=image_plane_line_colors, ) - - # Only image-plane fits have model positions in the image plane; a source-plane fit's model data is the - # source centre, which must not be drawn over the image. - from autolens.point.fit.positions.image.abstract import AbstractFitPositionsImagePair - - if fit is not None and isinstance(fit.positions, AbstractFitPositionsImagePair): - model_grid = _yx(fit.positions.model_data) - ax.scatter( - model_grid[:, 1], model_grid[:, 0], - s=60, c="r", marker="x", linewidths=2, zorder=7, label="Model", - ) - - ax.legend(loc="upper right", fontsize=8, framealpha=0.8) - - filename = "image_with_points" if fit is None else "fit_image_with_points" - save_figure(fig, path=output_path, filename=filename, format=output_format) diff --git a/autolens/point/plot/multi_source_plots.py b/autolens/point/plot/multi_source_plots.py new file mode 100644 index 000000000..b7014abdf --- /dev/null +++ b/autolens/point/plot/multi_source_plots.py @@ -0,0 +1,1120 @@ +""" +The point-source positions figures for any number of point sources (one for a galaxy-scale lens, many for a +cluster), drawn in one visual language: + +- ``dataset_point.png`` (:func:`plot_dataset_positions`): "Dataset Positions": every source's observed positions. + Source 0 is a black dot, further sources step through colour and marker shape; images are labelled ``i`` (one + source) or ``k·i`` (source ``k``, image ``i``). No critical curves. +- ``fit.png`` (:func:`plot_fit_positions`): "Fit Positions": the observed positions, the model positions (red ✕) at + their true position joined to their observed image by a true-length residual line (solid for hard pairing, dashed + for the soft all-pairs mixture), unmatched model images, and each source's critical curves at its OWN redshift in + its colour (darker), over the solver extent. The legend gives the σ of each source (2-8 sources) and the fit's + figure of merit: ``χ² = …``, or ``−2 ln L = …`` for the all-pairs mixture (``FitPositionsImagePairAll``), whose + value is a mixture log likelihood, not a chi-squared. Beyond 8 sources colour follows redshift (colourbar) and the + model ✕ is smaller. +- ``fit_per_image.png`` (:func:`subplot_fit_per_image`): one row per source, three square panels: "Residuals" (that + source's images ranked worst first by Δ/σ on a linear range shared by every source, clipped at a robust maximum + with off-scale values printed), "IP" (an image-plane zoom on that source's images and its own curves) and "SP" + (the source-plane panel of :mod:`autolens.point.plot.source_plane_panel`). The images of a row share one colour + per image across all three panels. Source-plane fits rank by the fit's own per-image chi. Beyond 8 sources each + source is written to its own file, ``fit_per_image/.png``, with the ranking range still shared. +- ``image_with_points.png`` / ``fit_image_with_points.png`` (:func:`plot_image_with_points`): the observed image with + every source's positions in the same symbols (white-edged so source 0's black dot shows on the image), ``k·i`` + labels and, for the fit, the model ✕ / residual lines and each source's tangential critical curves in its colour. + +The per-image figures carry no legends: the symbols are those of the dataset and fit figures. +""" + +import logging +from typing import Dict, Optional + +import numpy as np + +from autoarray.plot.utils import save_figure, subplots + +from autolens.point.plot import positions_panel as pp +from autolens.point.plot import point_sources as ps + +logger = logging.getLogger(__name__) + +# Critical curves and caustics: dark and thick, so they read against the markers. +CURVE_LINEWIDTH = 1.8 +RADIAL_CURVE_LINEWIDTH = 1.4 +CURVE_COLOR = "0.2" +RADIAL_CURVE_COLOR = "#5c5c00" + +# Every observed marker has this area (equalised across shapes by `marker_size_from`). +MARKER_SIZE = 110 + +# The image-number label style of every positions figure. +LABEL_BBOX = dict(fc="w", ec="none", alpha=0.8, pad=0.5) + +# An observed image with no model image of its own: a dashed grey ring around it. +NO_MODEL_RING = dict( + s=420, facecolors="none", edgecolors="0.3", linewidths=1.3, linestyle=(0, (2.5, 1.5)) +) + +LEGEND_KWARGS = dict(fontsize=9, framealpha=0.85, markerscale=0.7) + + +def darken(color, amount: float = 0.3): + """ + Returns ``color`` darkened by ``amount`` (black stays black), for curves drawn in a source's colour. + """ + import matplotlib.colors as mcolors + + if isinstance(color, str) and color in ("k", "black"): + return "k" + r, g, b = mcolors.to_rgb(color) + return (r * (1 - amount), g * (1 - amount), b * (1 - amount)) + + +def marker_size_from(marker: str, base: float = MARKER_SIZE) -> float: + """ + Equalises the visual area of the marker shapes: diamonds read larger and triangles smaller than circles at equal + ``s``. + """ + return base * {"D": 0.7, "^": 1.15, "v": 1.15, "<": 1.15, ">": 1.15, "P": 1.1}.get( + marker, 1.0 + ) + + +def is_many(records) -> bool: + return len(records) > ps.MAX_QUALITATIVE + + +def figsize_from(records): + """ + The library's single-figure size; 12 x 12 inches beyond 8 sources, so ~100 labels fit. + """ + from autoarray.plot.utils import conf_figsize + + return conf_figsize("figures") if not is_many(records) else (12, 12) + + +def font_scale_from(records) -> float: + """ + Beyond 8 sources the figure is 12 inches, so titles and ticks are scaled by ``12 / figsize`` to keep their + library size relative to the panel; only the image labels shrink. + """ + from autoarray.plot.utils import conf_figsize + + if not is_many(records): + return 1.0 + return 12.0 / float(conf_figsize("figures")[0]) + + +def label_fontsize_from(records) -> float: + return pp.FIT_NUMBER_FONTSIZE if not is_many(records) else 9 + + +def model_size_from(records) -> float: + return pp.MODEL_MARKER_SIZE if not is_many(records) else 30 + + +def scale_fonts(ax, scale: float): + if scale == 1.0: + return + ax.title.set_fontsize(ax.title.get_fontsize() * scale) + for tick in ax.get_xticklabels() + ax.get_yticklabels(): + tick.set_fontsize(tick.get_fontsize() * scale) + + +def finish_panel(ax, title: str, extent, scale: float = 1.0): + """ + The title, arc-second ticks and extent of a positions panel (library fonts), with an equal aspect ratio. + """ + from autoarray.plot.utils import apply_extent, apply_labels + + apply_labels(ax, title=title, xlabel="", ylabel="") + apply_extent(ax, extent) + ax.set_aspect("equal", adjustable="box") + scale_fonts(ax, scale) + + +def _prefix(title_prefix: Optional[str]) -> str: + return f"{title_prefix.rstrip()} " if title_prefix else "" + + +def _redshift_text(record) -> str: + return f", z = {record.redshift:g}" if record.redshift is not None else "" + + +def image_label_from(record, number, multi: bool) -> str: + return f"{record.k}·{number}" if multi else f"{number}" + + +# --------------------------------------------------------------------------- +# Label placement +# --------------------------------------------------------------------------- + + +def place_labels( + ax, + extent, + points, + labels, + obstacles=None, + fontsize: float = pp.FIT_NUMBER_FONTSIZE, + marker_radius: float = 7.0, +): + """ + Labels every point, beside its own marker when a free spot exists, otherwise pushed further out with a thin + leader line back to its marker (an extension of + :func:`~autolens.point.plot.positions_panel.adjacent_number_placements_from` for crowded clusters). + + Each label tries 8 directions (outward from the panel centre first) on rings of increasing distance; every + candidate is scored against all markers, the ``obstacles`` (e.g. model positions), the labels already placed and + the panel frame. Crowded markers choose first. + """ + points = np.asarray(points, dtype=float).reshape(-1, 2) + if len(points) == 0: + return + width, height, scale = pp._panel_size_points(ax, extent) + origin = np.array([extent[0], extent[2]]) + markers = (points[:, ::-1] - origin) * scale + occupied = markers + if obstacles is not None and len(obstacles): + occupied = np.vstack( + [ + markers, + (np.asarray(obstacles, dtype=float).reshape(-1, 2)[:, ::-1] - origin) + * scale, + ] + ) + centre = np.array([width, height]) / 2.0 + + density = np.array([np.sum(np.hypot(*(occupied - p).T) < 40.0) for p in markers]) + order = np.argsort(-density, kind="stable") + + placed, results = [], [None] * len(markers) + for index in order: + p = markers[index] + w = 0.62 * fontsize * len(labels[index]) + 4.0 + h = fontsize + 3.0 + out = p - centre + base = np.arctan2(out[1], out[0]) if np.hypot(*out) > 1 else np.pi * 0.75 + angles = base + np.radians([0, 45, -45, 90, -90, 135, -135, 180]) + best, best_score = None, np.inf + for ring, radius in enumerate( + ( + marker_radius + 0.5, + marker_radius + 14.0, + marker_radius + 28.0, + marker_radius + 44.0, + ) + ): + for angle in angles: + d = np.array([np.cos(angle), np.sin(angle)]) + c = p + d * radius + d * np.array([w / 2, h / 2]) + box = (c[0] - w / 2, c[1] - h / 2, c[0] + w / 2, c[1] + h / 2) + inside = ( + box[0] >= 0 and box[1] >= 0 and box[2] <= width and box[3] <= height + ) + hit_markers = int( + pp.box_overlaps_circles(box, occupied, marker_radius).sum() + ) + hit_labels = sum(pp.boxes_overlap(box, b) for b in placed) + score = ( + 10 * hit_labels + 6 * hit_markers + (0 if inside else 200) + 2.5 * ring + ) + if score < best_score: + best, best_score = (c, box, ring), score + if best_score < 2.5 * (ring + 1): + break + c, box, ring = best + placed.append(box) + results[index] = (c, ring) + + for i, ((c, ring), text) in enumerate(zip(results, labels)): + y, x = points[i] + dx, dy = c - markers[i] + ax.annotate( + text, + (x, y), + xytext=(dx, dy), + textcoords="offset points", + ha="center", + va="center", + fontsize=fontsize, + weight="bold", + color="k", + zorder=10, + bbox=LABEL_BBOX, + arrowprops=( + dict(arrowstyle="-", color="0.45", lw=0.6, shrinkA=0, shrinkB=3) + if ring > 0 + else None + ), + ) + + +def label_records(ax, extent, records, extra_points=(), extra_labels=(), obstacles=None): + multi = len(records) > 1 + points, labels = [], [] + for record in records: + for p, number in zip(record.observed, record.numbers): + points.append(p) + labels.append(image_label_from(record, number, multi)) + points += list(extra_points) + labels += list(extra_labels) + place_labels( + ax, + extent, + points, + labels, + obstacles=obstacles, + fontsize=label_fontsize_from(records), + ) + + +def legend_location_from(extent, points) -> str: + """ + The emptiest corner of a panel for its legend (the source-plane panel's corner ranking), so a legend never lands + over the images, the model or the mass centres. + """ + from autolens.point.plot import source_plane_panel as spp + + points = np.asarray(points, dtype=float).reshape(-1, 2) + (corner, _), *_ = spp.ranked_corners_from(extent, points, size=0.4) + return spp.CORNER_LOCATIONS[corner] + + +# --------------------------------------------------------------------------- +# Drawing primitives +# --------------------------------------------------------------------------- + + +def scatter_sources(ax, records, edgecolor="k", edgewidth=0.6): + for record in records: + if len(record.observed) == 0: + continue + ax.scatter( + record.observed[:, 1], + record.observed[:, 0], + s=marker_size_from(record.marker), + c=[record.color], + marker=record.marker, + edgecolors=edgecolor, + linewidths=edgewidth, + zorder=5, + label="Observed", + ) + + +def draw_noise_circles(ax, records): + from matplotlib.patches import Circle + + for record in records: + for (y, x), sigma in zip(record.observed, record.sigma): + if np.isfinite(sigma) and sigma > 0: + ax.add_patch( + Circle( + (x, y), + sigma, + fill=False, + edgecolor=pp.NOISE_COLOR, + linewidth=1.0, + zorder=5.5, + ) + ) + + +def draw_curves(ax, records, curves: Dict, single_color=None): + """ + Draws each source's critical curves at its own redshift: in the source's (darkened) colour when there are + several sources, dark grey (radial dark olive, dotted) for one. Beyond 8 sources only tangential curves are + drawn, thinner. + """ + multi = len(records) > 1 + many = is_many(records) + drawn = set() + for record in records: + plane_curves = record.curves_from(curves) + if plane_curves is None: + continue + key = (str(record.curve_key), record.plane_index, str(record.color)) + if key in drawn: + continue + drawn.add(key) + color = single_color or (darken(record.color) if multi else CURVE_COLOR) + for line in plane_curves.tangential: + ax.plot( + line[:, 1], + line[:, 0], + color=color, + linewidth=CURVE_LINEWIDTH if not many else 1.3, + zorder=2, + ) + if many: + continue + for line in plane_curves.radial: + ax.plot( + line[:, 1], + line[:, 0], + color=color if multi else RADIAL_CURVE_COLOR, + linewidth=RADIAL_CURVE_LINEWIDTH, + linestyle=":", + zorder=2, + ) + + +def draw_model_and_residuals( + ax, records, model_size=pp.MODEL_MARKER_SIZE, unmatched_color=pp.UNMATCHED_COLOR +): + """ + The model positions as red ✕ at their true position, each joined to its observed image by a true-length red + residual line (solid for hard pairing, dashed for the soft all-pairs mixture), unmatched model images as hollow + ✕ and a dashed ring round observed images with no model image of their own. + """ + for record in records: + if not record.has_model: + continue + for obs, index in zip(record.observed, record.indexes): + if index < 0: + continue + m = record.model[index] + ax.plot( + [obs[1], m[1]], + [obs[0], m[0]], + color=pp.MODEL_COLOR, + linewidth=1.2, + linestyle=record.linestyle, + alpha=0.9, + zorder=6, + ) + matched = record.model[~record.unmatched] + if len(matched): + ax.scatter( + matched[:, 1], + matched[:, 0], + s=model_size, + c=pp.MODEL_COLOR, + marker="x", + linewidths=1.6 if model_size >= pp.MODEL_MARKER_SIZE else 1.2, + zorder=8, + label="Model", + ) + unmatched = record.model[record.unmatched] + if len(unmatched): + ax.scatter( + unmatched[:, 1], + unmatched[:, 0], + s=2 * model_size, + facecolors="none", + edgecolors=unmatched_color, + marker="X", + linewidths=1.5, + zorder=7, + label="Unmatched model image", + ) + if np.any(record.no_model): + no_model = record.observed[record.no_model] + ax.scatter(no_model[:, 1], no_model[:, 0], zorder=6.5, **NO_MODEL_RING) + + +def merit_label_from(records) -> Optional[str]: + """ + The fit's figure of merit summed over the sources: ``χ² = …``, or ``−2 ln L = …`` when the fits are the + all-pairs mixture (``FitPositionsImagePairAll``), whose value is ``−2`` times a mixture log likelihood. + """ + from autolens.point.plot import source_plane_panel as spp + + values = [r.chi_squared for r in records if r.chi_squared is not None] + if not values: + return None + name = "−2 ln L" if all(r.mixture for r in records if r.fit is not None) else "χ²" + return f"{name} = {spp._format_chi_squared(float(np.sum(values)))}" + + +def observed_handles(records, edgecolor="k"): + """ + One ``Observed (σ = …)`` entry for a single source or more than 8 sources; for 2-8 sources one entry per source, + ``point_k (z = …, σ = …)``. + """ + from matplotlib.lines import Line2D + + sigma_text = pp.sigma_label_from(np.concatenate([r.sigma for r in records])) + if 1 < len(records) <= ps.MAX_QUALITATIVE: + handles = [] + for record in records: + z = f"z = {record.redshift:g}, " if record.redshift is not None else "" + handles.append( + Line2D( + [], + [], + linestyle="none", + marker=record.marker, + markerfacecolor=record.color, + markeredgecolor=edgecolor, + markeredgewidth=0.6, + markersize=9, + label=f"{record.name} ({z}{sigma_text})", + ) + ) + return handles + face = "k" if len(records) == 1 else "0.6" + return [ + Line2D( + [], + [], + linestyle="none", + marker="o", + markerfacecolor=face, + markeredgecolor=edgecolor, + markersize=9, + label=f"Observed ({sigma_text})", + ) + ] + + +def fit_handles(records, model_size, has_curves: bool, has_mass_centres: bool): + from matplotlib.lines import Line2D + + first = records[0] + multi = len(records) > 1 + handles = [] + if any(r.has_model for r in records): + handles.append( + Line2D( + [], + [], + linestyle="none", + marker="x", + color=pp.MODEL_COLOR, + markeredgewidth=1.6, + markersize=8 if model_size >= pp.MODEL_MARKER_SIZE else 6, + label=first.model_label, + ) + ) + handles.append( + Line2D( + [], + [], + color=pp.MODEL_COLOR, + linewidth=1.2, + linestyle=first.linestyle, + label=first.residual_label, + ) + ) + if any(np.any(r.unmatched) for r in records): + handles.append( + Line2D( + [], + [], + linestyle="none", + marker="X", + markerfacecolor="none", + markeredgecolor=pp.UNMATCHED_COLOR, + markeredgewidth=1.5, + markersize=9, + label="Unmatched model image", + ) + ) + if any(np.any(r.no_model) for r in records): + handles.append( + Line2D( + [], + [], + linestyle="none", + marker="o", + markerfacecolor="none", + markeredgecolor="0.3", + markeredgewidth=1.3, + markersize=15, + label="Observed, no model image", + ) + ) + if has_curves: + handles.append( + Line2D( + [], + [], + color=CURVE_COLOR if not multi else "0.35", + linewidth=CURVE_LINEWIDTH, + label="Critical curve (each source's z)" if multi else "Critical curve", + ) + ) + if has_mass_centres: + handles.append( + Line2D( + [], + [], + linestyle="none", + marker="+", + color=pp.MASS_CENTRE_COLOR, + markeredgewidth=1.5, + markersize=8, + label="Mass centre", + ) + ) + merit = merit_label_from(records) + if merit is not None: + handles.append(Line2D([], [], linestyle="none", marker="none", label=merit)) + return handles + + +def add_colourbar(fig, ax, colormap, records, scale: float = 1.0): + """ + The source-redshift colourbar of the colour-by-redshift scheme (beyond 8 sources), with a tick line at every + source's redshift. + """ + if colormap is None: + return None + import matplotlib.cm as cm + from autoarray.plot.utils import conf_mat_plot_fontsize + + cmap, norm = colormap + position = ax.get_position() + cax = fig.add_axes([position.x1 + 0.015, position.y0, 0.025, position.height]) + colorbar = fig.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), cax=cax) + fontsize = conf_mat_plot_fontsize("yticks", 22) * 0.8 * scale + colorbar.set_label("source redshift", fontsize=fontsize) + colorbar.ax.tick_params(labelsize=fontsize) + for record in records: + if record.redshift is not None: + cax.axhline(record.redshift, color="k", linewidth=0.5, alpha=0.6) + return cax + + +def _curve_points(records, curves) -> np.ndarray: + points = [] + for record in records: + plane_curves = record.curves_from(curves) + if plane_curves is None: + continue + for line in plane_curves.tangential + plane_curves.radial: + points.append(line[:: max(1, len(line) // 40)]) + return np.vstack(points) if points else np.zeros((0, 2)) + + +# --------------------------------------------------------------------------- +# dataset_point.png: Dataset Positions +# --------------------------------------------------------------------------- + + +def draw_dataset_positions(ax, records, extent, title: str, scale: float = 1.0): + """ + Draws the "Dataset Positions" panel of ``records`` on ``ax`` (styles must be assigned). + """ + scatter_sources(ax, records) + draw_noise_circles(ax, records) + finish_panel(ax, title, extent, scale) + label_records(ax, extent, records) + observed = np.vstack([r.observed for r in records]) + ax.legend( + handles=observed_handles(records), + loc=legend_location_from(extent, observed) if len(records) == 1 else "best", + fontsize=LEGEND_KWARGS["fontsize"] * scale, + framealpha=LEGEND_KWARGS["framealpha"], + markerscale=LEGEND_KWARGS["markerscale"], + ) + + +def dataset_title_from(records, title_prefix=None) -> str: + if len(records) == 1: + return f"{_prefix(title_prefix)}Dataset Positions ({records[0].name})" + return f"{_prefix(title_prefix)}Dataset Positions" + + +def plot_dataset_positions( + datasets, + solver=None, + output_path: Optional[str] = None, + output_format: str = None, + filename: str = "dataset_point", + title_prefix: str = None, +): + """ + Plots ``dataset_point.png`` ("Dataset Positions") of one or many ``PointDataset`` objects on the solver extent. + + Source 0 is a black dot, further sources step through colour and marker shape (colour by redshift with a + colourbar beyond 8 sources); images are labelled ``i`` for one source and ``k·i`` for several. No critical + curves are drawn on a dataset figure. + """ + + datasets = list(datasets) + records = ps.records_from_datasets(datasets) + colormap = ps.assign_styles(records) + extent = ps.union_extent_from(records, solver=solver) + + fig, ax = subplots(1, 1, figsize=figsize_from(records)) + draw_dataset_positions( + ax, + records, + extent, + title=dataset_title_from(records, title_prefix), + scale=font_scale_from(records), + ) + add_colourbar(fig, ax, colormap, records, font_scale_from(records)) + save_figure(fig, path=output_path, filename=filename, format=output_format) + + +# --------------------------------------------------------------------------- +# fit.png: Fit Positions +# --------------------------------------------------------------------------- + + +def draw_fit_positions( + ax, + records, + curves, + extent, + tracer, + title: str, + scale: float = 1.0, + legend: str = "inside", + colormap=None, +): + """ + Draws the "Fit Positions" panel of ``records`` (with fits) on ``ax``; ``legend`` is ``"inside"`` (the emptiest + corner) or ``"outside"`` (right of the panel, and of the colourbar if there is one). + """ + multi = len(records) > 1 + many = is_many(records) + model_size = model_size_from(records) + + draw_curves(ax, records, curves) + mass_centres = pp.mass_centres_from(tracer) if tracer is not None else np.zeros((0, 2)) + if len(mass_centres): + pp.plot_mass_centres( + ax, tracer, size=70 if not many else 50, linewidths=1.4 + ) + scatter_sources(ax, records) + draw_noise_circles(ax, records) + draw_model_and_residuals(ax, records, model_size) + finish_panel(ax, title, extent, scale) + + extra_points, extra_labels = [], [] + for record in records: + for p, letter in zip(record.model[record.unmatched], record.unmatched_labels): + extra_points.append(p) + extra_labels.append(f"{record.k}·{letter}" if multi else letter) + models = [r.model for r in records if r.has_model] + obstacles = np.vstack(models + [mass_centres]) if models else mass_centres + label_records(ax, extent, records, extra_points, extra_labels, obstacles=obstacles) + + handles = observed_handles(records) + fit_handles( + records, + model_size, + has_curves=bool(_curve_points(records, curves).size), + has_mass_centres=bool(len(mass_centres)), + ) + kwargs = dict( + fontsize=LEGEND_KWARGS["fontsize"] * scale, + framealpha=LEGEND_KWARGS["framealpha"], + markerscale=LEGEND_KWARGS["markerscale"], + ) + if legend == "outside": + ax.legend( + handles=handles, + loc="upper left", + bbox_to_anchor=(1.02 if colormap is None else 1.16, 1.0), + borderaxespad=0.0, + **kwargs, + ) + else: + drawn = np.vstack( + [r.observed for r in records] + + models + + [mass_centres, _curve_points(records, curves)] + ) + ax.legend(handles=handles, loc=legend_location_from(extent, drawn), **kwargs) + + +def plot_fit_positions( + fits, + solver=None, + curves: Optional[Dict] = None, + output_path: Optional[str] = None, + output_format: str = None, + filename: str = "fit", + title_prefix: str = None, +): + """ + Plots ``fit.png`` ("Fit Positions") of one or many ``FitPointDataset`` objects of the same lens model on the + solver extent (see the module docstring). ``curves`` are the per-plane curves of + :func:`~autolens.point.plot.point_sources.curves_for_planes`, computed if ``None``. + """ + + fits = list(fits) + records = ps.records_from_fits(fits) + colormap = ps.assign_styles(records) + solver = solver if solver is not None else getattr(fits[0], "solver", None) + extent = ps.union_extent_from(records, solver=solver) + tracer = fits[0].tracer + if curves is None: + curves = ps.curves_for_fits(fits, records, extent) + + fig, ax = subplots(1, 1, figsize=figsize_from(records)) + draw_fit_positions( + ax, + records, + curves, + extent, + tracer, + title=f"{_prefix(title_prefix)}Fit Positions", + scale=font_scale_from(records), + legend="outside" if len(records) > 1 else "inside", + colormap=colormap, + ) + add_colourbar(fig, ax, colormap, records, font_scale_from(records)) + save_figure(fig, path=output_path, filename=filename, format=output_format) + + +# --------------------------------------------------------------------------- +# fit_per_image.png +# --------------------------------------------------------------------------- + + +def zoom_extent_from(record, min_half: float = 1.0, margin: float = 0.28): + """ + A square image-plane zoom on one source's observed (and model) images. + """ + points = np.vstack([record.observed, record.model]) if record.has_model else record.observed + lo, hi = points.min(axis=0), points.max(axis=0) + half = max(0.5 * float(np.max(hi - lo)) * (1 + 2 * margin), min_half) + centre_y, centre_x = 0.5 * (lo + hi) + return [centre_x - half, centre_x + half, centre_y - half, centre_y + half] + + +def _format_sigma(value: float) -> str: + if value >= 100: + return f"{value:,.0f}σ" + return f"{value:.1f}σ" if value >= 1 else f"{value:.2f}σ" + + +def draw_ranking_panel(ax, record, scales: ps.RankingScales, title: str): + """ + The residual ranking of one source: a dot per image (worst first) at Δ/σ on the shared linear range, its value + printed to its right; an off-scale image is a ▸ at the edge with its value in bold. Unmatched model images are + listed last with their magnification. Unlabelled dashed lines mark 1σ and 3σ; there is no x axis. + """ + from autoarray.plot.utils import apply_labels + + xmax, n_slots = scales.xmax, scales.n_slots + rows = ps.ranking_rows_from(record) + right = 1.32 * xmax + for slot, (value, _, kind, i) in enumerate(rows): + y = n_slots - 1 - slot + if kind == "unmatched": + ax.scatter( + 0.0, + y, + s=130, + facecolors="none", + edgecolors=pp.UNMATCHED_COLOR, + marker="X", + linewidths=1.6, + zorder=4, + ) + mu = record.mu_model[i] if i < len(record.mu_model) else np.nan + ax.text(0.04 * right, y, f"μ = {mu:.2g}", va="center", fontsize=14, color="0.3") + continue + if not np.isfinite(value): + continue + color = ps.image_color(record.numbers[i]) + x = min(value, xmax) + ax.hlines(y, 0, x, color="0.85", linewidth=1.4, zorder=1) + if value > xmax: + ax.scatter(xmax, y, s=150, c=[color], marker=">", edgecolors="k", linewidths=0.6, zorder=4) + else: + ax.scatter(x, y, s=120, c=[color], edgecolors="k", linewidths=0.6, zorder=4) + if kind == "nomodel": + ax.scatter(x, y, zorder=3, **{**NO_MODEL_RING, "s": 380}) + ax.text( + x + 0.035 * right, + y, + _format_sigma(value), + va="center", + ha="left", + fontsize=14, + weight="bold" if value > xmax else "normal", + ) + ax.axvline(1.0, color="0.35", linewidth=1.3, linestyle="--", zorder=0) + ax.axvline(3.0, color="#c25400", linewidth=1.5, linestyle="--", zorder=0) + ax.set_xlim(-0.04 * right, right) + ax.set_ylim(-0.7, n_slots - 0.3) + apply_labels(ax, title=title, xlabel="", ylabel="") + labels = [t[1] for t in rows] + [""] * (n_slots - len(rows)) + ax.set_yticks(np.arange(n_slots)[::-1]) + ax.set_yticklabels(labels, fontweight="bold") + ax.tick_params(axis="y", labelrotation=0, length=0) + for tick, row in zip(ax.get_yticklabels(), rows): + if row[2] == "unmatched": + tick.set_color("0.4") + ax.xaxis.set_visible(False) + ax.set_box_aspect(1) + + +def draw_image_plane_panel(ax, record, curves, tracer, title: str): + """ + The image-plane zoom of one source: its own critical curves (dark grey, radial dotted olive), the mass centres, + its observed images coloured by image with their σ circles, the model ✕ and residual lines and its image numbers + (unmatched model images lettered). + """ + extent = zoom_extent_from(record) + plane_curves = record.curves_from(curves) + if plane_curves is not None: + for line in plane_curves.tangential: + ax.plot(line[:, 1], line[:, 0], color=CURVE_COLOR, linewidth=CURVE_LINEWIDTH, zorder=2) + for line in plane_curves.radial: + ax.plot( + line[:, 1], + line[:, 0], + color=RADIAL_CURVE_COLOR, + linewidth=RADIAL_CURVE_LINEWIDTH, + linestyle=":", + zorder=2, + ) + if tracer is not None: + pp.plot_mass_centres(ax, tracer, size=80, linewidths=1.5) + colors = [ps.image_color(n) for n in record.numbers] + ax.scatter( + record.observed[:, 1], + record.observed[:, 0], + s=MARKER_SIZE, + c=colors, + edgecolors="k", + linewidths=0.6, + zorder=5, + ) + draw_noise_circles(ax, [record]) + draw_model_and_residuals(ax, [record]) + finish_panel(ax, title, extent) + points = list(record.observed) + labels = [f"{n}" for n in record.numbers] + if np.any(record.unmatched): + points += list(record.model[record.unmatched]) + labels += record.unmatched_labels + place_labels( + ax, + extent, + points, + labels, + obstacles=record.model if record.has_model else None, + fontsize=pp.FIT_NUMBER_FONTSIZE, + ) + + +def draw_source_plane_panel(ax, record, curves, title: str): + from autolens.point.plot import source_plane_panel as spp + + data = spp.source_plane_data_from(record.fit.positions, numbers=record.numbers) + plane_curves = record.curves_from(curves) + spp.plot_source_plane_panel( + ax, + data, + title=title, + tangential_caustics=plane_curves.tangential_caustics if plane_curves else None, + radial_caustics=plane_curves.radial_caustics if plane_curves else None, + point_colors=[ps.image_color(n) for n in record.numbers], + legend=False, + ) + + +def _shrink_titles_to_fit(fig, axes): + """ + Shrinks any title wider than its panel until it fits (it is measured as rendered). + """ + fig.canvas.draw() + renderer = fig.canvas.get_renderer() + for ax in axes: + width = ax.get_window_extent(renderer).width + title = ax.title + while ( + title.get_window_extent(renderer).width > 1.02 * width + and title.get_fontsize() > 12 + ): + title.set_fontsize(title.get_fontsize() - 1) + + +def _fit_per_image_figure(records, curves, tracer, scales, title_prefix=None): + from autoarray.plot.utils import conf_subplot_figsize + + n = len(records) + fig, axes = subplots(n, 3, figsize=conf_subplot_figsize(n, 3), squeeze=False) + prefix = _prefix(title_prefix) + for row, record in enumerate(records): + tag = f"({record.name}{_redshift_text(record)})" + draw_ranking_panel(axes[row, 0], record, scales, title=f"{prefix}Residuals {tag}") + draw_image_plane_panel(axes[row, 1], record, curves, tracer, title=f"{prefix}IP {tag}") + try: + draw_source_plane_panel(axes[row, 2], record, curves, title=f"{prefix}SP {tag}") + except Exception: + logger.warning( + "The source-plane panel of fit_per_image.png could not be drawn; it is left empty.", + exc_info=True, + ) + axes[row, 2].cla() + axes[row, 2].set_title(f"{prefix}SP {tag}") + axes[row, 2].set_axis_off() + for ax in axes[row]: + ax.set_box_aspect(1) + fig.tight_layout() + _shrink_titles_to_fit(fig, axes.ravel()) + return fig + + +def subplot_fit_per_image( + fits, + curves: Optional[Dict] = None, + solver=None, + output_path: Optional[str] = None, + output_format: str = None, + filename: str = "fit_per_image", + title_prefix: str = None, + scales: Optional[ps.RankingScales] = None, +): + """ + Plots ``fit_per_image.png``: one row per source of "Residuals", "IP" and "SP" panels (see the module docstring). + + The ranking range is shared by every row; it is computed from all ``fits`` (pass ``scales`` to share it with + other figures). Beyond 8 sources each source is written to its own file, ``//.png``, + all on the shared range. + """ + + fits = list(fits) + records = ps.records_from_fits(fits) + ps.assign_styles(records) + tracer = fits[0].tracer + scales = scales or ps.ranking_scales_from(records) + if curves is None: + solver = solver if solver is not None else getattr(fits[0], "solver", None) + curves = ps.curves_for_fits( + fits, records, ps.union_extent_from(records, solver=solver) + ) + + if not is_many(records): + fig = _fit_per_image_figure(records, curves, tracer, scales, title_prefix) + save_figure(fig, path=output_path, filename=filename, format=output_format) + return + + from pathlib import Path + + folder = str(Path(output_path) / filename) if output_path else None + for record in records: + fig = _fit_per_image_figure([record], curves, tracer, scales, title_prefix) + save_figure(fig, path=folder, filename=record.name, format=output_format) + + +# --------------------------------------------------------------------------- +# image_with_points.png / fit_image_with_points.png +# --------------------------------------------------------------------------- + + +def plot_image_with_points( + image, + datasets=None, + fits=None, + curves: Optional[Dict] = None, + solver=None, + output_path: Optional[str] = None, + output_format: str = None, + title_prefix: str = None, + image_plane_lines=None, + image_plane_line_colors=None, +): + """ + Plots the observed image with every source's positions overlaid, in the symbols of the positions figures. + + With ``fits=None`` only the observed positions of ``datasets`` are drawn (``image_with_points.png``); with + ``fits`` the model positions, residual lines and each source's tangential critical curves at its own redshift are + added (``fit_image_with_points.png``, so both figures coexist). Clusters (several sources) use a log10 colour + scale (a bright BCG and faint arcs); a single lens keeps the linear scale. There is no legend. + + ``image_plane_lines`` (pre-computed last-plane curves) are drawn only when ``curves`` cannot be computed. + """ + from autoarray.plot.utils import _overlay_yx_for_origin + from autogalaxy.util.plot_utils import plot_array + + is_fit = fits is not None + if is_fit: + fits = list(fits) + records = ps.records_from_fits(fits) + else: + records = ps.records_from_datasets(list(datasets)) + ps.assign_styles(records) + multi = len(records) > 1 + many = is_many(records) + scale = font_scale_from(records) + + if is_fit and curves is None: + solver = solver if solver is not None else getattr(fits[0], "solver", None) + curves = ps.curves_for_fits( + fits, records, ps.union_extent_from(records, solver=solver) + ) + + name = "Fit Image With Points" if is_fit else "Image With Points" + title = f"{_prefix(title_prefix)}{name}" + (f" ({records[0].name})" if not multi else "") + + fig, ax = subplots(1, 1, figsize=figsize_from(records)) + plot_array(array=image, ax=ax, use_log10=multi, title=title) + scale_fonts(ax, scale) + for other in fig.axes[1:]: + for tick in other.get_yticklabels(): + tick.set_fontsize(tick.get_fontsize() * scale) + + # Positions are (y,x) arc-seconds: reflect them exactly as `plot_array` does its own overlays, using the + # extent and origin of the raster it drew, so they stay registered to the image (PyAutoArray#565). + raster_extent, origin = ( + (ax.images[0].get_extent(), ax.images[0].origin) if ax.images else (None, None) + ) + + def _yx(grid): + grid = np.asarray(grid, dtype=float).reshape(-1, 2) + if len(grid) == 0: + return grid + return _overlay_yx_for_origin(grid, raster_extent, origin) + + import copy + + shown = [] + for record in records: + displayed = copy.copy(record) + displayed.observed = _yx(record.observed) + displayed.model = _yx(record.model) + shown.append(displayed) + + from matplotlib import patheffects + + curve_width = CURVE_LINEWIDTH if not many else 1.3 + if is_fit: + drawn_any = False + for record in records: + plane_curves = record.curves_from(curves) + if plane_curves is None: + continue + color = "w" if (not multi or str(record.color) == "k") else record.color + for line in plane_curves.tangential: + line = _yx(line) + ax.plot( + line[:, 1], + line[:, 0], + color=color, + linewidth=curve_width, + zorder=3, + path_effects=[ + patheffects.withStroke(linewidth=curve_width + 1.6, foreground="k") + ], + ) + drawn_any = True + if not drawn_any and image_plane_lines: + for line in image_plane_lines: + line = _yx(line) + ax.plot(line[:, 1], line[:, 0], color="w", linewidth=curve_width, zorder=3) + + scatter_sources(ax, shown, edgecolor="w", edgewidth=1.0) + if is_fit: + draw_model_and_residuals(ax, shown, model_size_from(records), unmatched_color="0.85") + + extent = [*ax.get_xlim(), *ax.get_ylim()] + models = [s.model for s in shown if s.has_model] + label_records( + ax, + extent, + shown, + obstacles=np.vstack(models) if models else None, + ) + filename = "fit_image_with_points" if is_fit else "image_with_points" + save_figure(fig, path=output_path, filename=filename, format=output_format) diff --git a/autolens/point/plot/point_dataset_plots.py b/autolens/point/plot/point_dataset_plots.py index 8d203521c..d82296a37 100644 --- a/autolens/point/plot/point_dataset_plots.py +++ b/autolens/point/plot/point_dataset_plots.py @@ -24,7 +24,10 @@ def subplot_dataset( 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. + labels, only arc-second tick labels. Images are numbered 1..N as on every + point-source figure. This is the one-source case of + :func:`~autolens.point.plot.multi_source_plots.plot_dataset_positions`, + which draws every source of a cluster in one panel. * **Fluxes panel** (shown only when ``dataset.fluxes`` is not ``None``): a line/bar plot of the observed flux values indexed by image position. @@ -44,43 +47,43 @@ def subplot_dataset( The solver of the model-fit, whose grid sets the positions panel extent. """ from autoarray.plot.yx import plot_yx - from autolens.point.plot.positions_panel import ( - finish_positions_panel, - plot_observed_positions, - positions_extent_from, - ) + from autolens.point.plot import multi_source_plots as msp + from autolens.point.plot import point_sources as ps - has_fluxes = dataset.fluxes is not None - n = 2 if has_fluxes else 1 + if dataset.fluxes is None: + msp.plot_dataset_positions( + [dataset], + solver=solver, + output_path=output_path, + output_format=output_format, + filename="dataset_point", + title_prefix=title_prefix, + ) + return - fig, axes = subplots(1, n, figsize=conf_subplot_figsize(1, n)) - axes_flat = [axes] if n == 1 else list(np.array(axes).flatten()) + records = ps.records_from_datasets([dataset]) + ps.assign_styles(records) + extent = ps.union_extent_from(records, solver=solver) - _prefix = f"{title_prefix.rstrip()} " if title_prefix else "" + fig, axes = subplots(1, 2, figsize=conf_subplot_figsize(1, 2)) + axes_flat = list(np.array(axes).flatten()) - 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 Positions ({dataset.name})", - extent=positions_extent_from(positions=dataset.positions, solver=solver), + msp.draw_dataset_positions( + axes_flat[0], records, extent, title=msp.dataset_title_from(records, title_prefix) ) - if has_fluxes and n > 1: - y = np.array(dataset.fluxes) - x = np.arange(len(y)) - plot_yx( - y=y, - x=x, - ax=axes_flat[1], - title=f"{_prefix}Dataset Fluxes ({dataset.name})", - output_path=None, - output_filename="point_dataset_fluxes", - output_format=output_format, - ) + _prefix = f"{title_prefix.rstrip()} " if title_prefix else "" + y = np.array(dataset.fluxes) + x = np.arange(len(y)) + plot_yx( + y=y, + x=x, + ax=axes_flat[1], + title=f"{_prefix}Dataset Fluxes ({dataset.name})", + output_path=None, + output_filename="point_dataset_fluxes", + output_format=output_format, + ) tight_layout() save_figure(fig, path=output_path, filename="dataset_point", format=output_format) diff --git a/autolens/point/plot/point_sources.py b/autolens/point/plot/point_sources.py new file mode 100644 index 000000000..3b3647afb --- /dev/null +++ b/autolens/point/plot/point_sources.py @@ -0,0 +1,593 @@ +""" +The per-source quantities every point-source positions figure draws, for one or many point sources. + +A cluster model-fit fits several ``PointDataset`` objects (one per multiply imaged source, each at its own redshift), +so the positions figures (``dataset_point.png``, ``fit.png``, ``fit_per_image.png``, ``image_with_points.png`` and +``fit_image_with_points.png``) are drawn from a list of :class:`SourceRecord` objects, one per source. A single +point-source fit is the one-element case, so every figure uses one function and one visual language whatever the +number of sources. + +This module holds: + +- :class:`SourceRecord`: the observed positions, noise, image numbers and (for a fit) the model positions and the + fit's own pairing of a single source, built by :func:`source_record_from_dataset` or + :func:`source_record_from_fit` from the helpers of :mod:`autolens.point.plot.positions_panel`. +- :func:`assign_styles`: the colour and marker of every source. Source 0 is the library's black dot; sources 1 to 7 + step through an Okabe-Ito colour AND a marker shape. Beyond 8 sources hue cannot carry identity, so the colour + follows the source redshift (a perceptually uniform map with a colourbar) and identity is carried by the ``k·i`` + labels. +- :func:`curves_for_planes`: the critical curves and caustics of each source's OWN plane. Each source plane has its + own curves (a source at higher redshift is lensed more strongly), so drawing the last plane's curves for every + source is wrong for a multi-plane cluster. The deflection field to a plane is evaluated once on a fine grid, + differentiated numerically and contoured where the tangential / radial eigenvalue is zero (marching squares). When + every mass-bearing galaxy is in one lens plane the deflection to any later plane is the last plane's rescaled by a + distance ratio, so the field is evaluated once for all planes. This takes well under a second for a two-plane + cluster, where ``LensCalc`` takes tens of seconds per plane. The curves, magnifications and solves always use the + FULL tracer, as multi-plane deflections are normalised to the last plane. +""" + +import os +from dataclasses import dataclass, field +from typing import Dict, List, Optional + +import numpy as np + +from autolens.point.plot import positions_panel as pp + +# Sources are distinguished by colour (up to this many) and marker shape. +MAX_QUALITATIVE = 8 + +# Source 0 is black (the single-source look); then Okabe-Ito, re-ordered so source 1 (the common two-source case) is +# orange and source 2 sky blue, which read both on white panels and on the dark image-with-points colormap. +# Vermilion is absent: red is the model colour. +SOURCE_PALETTE = [ + "k", + "#E69F00", + "#56B4E9", + "#009E73", + "#CC79A7", + "#0072B2", + "#882255", + "#999933", +] + +# Marker shapes cycled per source (with colour). +MARKERS = ["o", "s", "^", "D", "v", "p", "h", "<", ">", "P"] + +# Per-image colours inside one source's row of ``fit_per_image.png`` (linking a ranking dot to its image): Okabe-Ito +# in image-number order. +IMAGE_COLORS = [ + "#0072B2", + "#E69F00", + "#009E73", + "#CC79A7", + "#56B4E9", + "#882255", + "#117733", + "#999933", +] + +# Number of grid points per side of the deflection-field grid the curves are contoured on. +CURVE_GRID_SHAPE = 400 + + +def image_color(number: int): + """ + Returns the colour of image ``number`` (1-based) within one source's row of ``fit_per_image.png``. + """ + return IMAGE_COLORS[(int(number) - 1) % len(IMAGE_COLORS)] + + +def letters_from(total: int) -> List[str]: + """ + Returns ``["a", "b", ...]``: the labels of a source's unmatched model images. + """ + return [chr(ord("a") + i) for i in range(total)] + + +@dataclass +class SourceRecord: + """ + Everything the positions figures draw for one point source. + + ``model``, ``indexes``, ``unmatched`` and ``delta`` describe the fit's own image-plane pairing (see + :func:`~autolens.point.plot.positions_panel.model_pairing_from`); they are empty / ``-1`` / ``NaN`` for a dataset + (no fit) and for a source-plane fit (whose model data are in the source plane). + """ + + k: int + name: str + redshift: Optional[float] + observed: np.ndarray + sigma: np.ndarray + numbers: np.ndarray + plane_index: Optional[int] = None + fit: object = None + model: np.ndarray = field(default_factory=lambda: np.zeros((0, 2))) + indexes: Optional[np.ndarray] = None + unmatched: np.ndarray = field(default_factory=lambda: np.zeros(0, dtype=bool)) + no_model: Optional[np.ndarray] = None + delta: Optional[np.ndarray] = None + mu_model: np.ndarray = field(default_factory=lambda: np.zeros(0)) + linestyle: str = "-" + residual_label: str = "Residual" + model_label: str = "Model" + chi_squared: Optional[float] = None + mixture: bool = False + image_plane_chi: Optional[np.ndarray] = None + color: object = "k" + marker: str = "o" + curve_key: object = None + + def __post_init__(self): + n = len(self.observed) + if self.indexes is None: + self.indexes = np.full(n, -1, dtype=int) + if self.no_model is None: + self.no_model = np.zeros(n, dtype=bool) + if self.delta is None: + self.delta = np.full(n, np.nan) + + def curves_from(self, curves) -> Optional["PlaneCurves"]: + """ + This source's curves in a dict of :func:`curves_for_planes` (keyed by plane index, or by ``curve_key`` when + the sources come from different tracers). + """ + if not curves: + return None + return curves.get(self.curve_key if self.curve_key is not None else self.plane_index) + + @property + def has_model(self) -> bool: + return len(self.model) > 0 + + @property + def unmatched_labels(self) -> List[str]: + return letters_from(int(np.sum(self.unmatched))) + + @property + def residual_sigmas(self) -> np.ndarray: + """ + The residual of every image in units of its noise, the fit's OWN per-image chi: ``|observed - paired model| + / σ`` for an image-plane fit (the nearest model image for the soft all-pairs mixture) and ``sqrt(χ²ᵢ)`` of + the fit's own source-plane chi-squared map for a source-plane fit. + """ + if self.image_plane_chi is not None: + return self.image_plane_chi + return self.delta / self.sigma + + +def _sigma_from(noise_map, total: int) -> np.ndarray: + noise = np.asarray( + noise_map.array if hasattr(noise_map, "array") else noise_map, dtype=float + ).ravel() + return np.broadcast_to(noise, (total,)).copy() + + +def source_record_from_dataset(k: int, dataset) -> SourceRecord: + """ + Returns the record of a ``PointDataset`` with no fit: its observed positions, noise and image numbers. + """ + observed = pp._np_grid(dataset.positions) + return SourceRecord( + k=k, + name=dataset.name, + redshift=getattr(dataset, "redshift", None), + observed=observed, + sigma=_sigma_from(dataset.positions_noise_map, len(observed)), + numbers=pp.image_numbers_from(dataset.positions), + ) + + +def plane_index_of(fit_positions, tracer) -> int: + """ + Returns the (non-negative) index of the plane the point source of a positions fit is in. + """ + plane_index = int(getattr(fit_positions, "plane_index", -1)) + if plane_index < 0: + plane_index = len(tracer.planes) + plane_index + return plane_index + + +def source_record_from_fit(k: int, fit) -> SourceRecord: + """ + Returns the record of a ``FitPointDataset``: the dataset's quantities plus the fit's model positions, its own + pairing, the unmatched model images, the residual of every image and the magnification of every model image. + + Observed images with no model image of their own are flagged in ``no_model``: those with no model image at all, + and, for the one-to-one ``FitPositionsImagePair``, those its assignment leaves unassigned when the model has + fewer images than are observed (the fit pairs them with their nearest model image). + """ + from autolens.point.fit.positions.image.pair import FitPositionsImagePair + from autolens.point.fit.positions.image.pair_all import FitPositionsImagePairAll + from autolens.point.plot import source_plane_panel as spp + + fit_positions = fit.positions + tracer = fit.tracer + record = source_record_from_dataset(k=k, dataset=fit.dataset) + record.fit = fit + + observed = record.observed + plane_index = plane_index_of(fit_positions, tracer) + record.plane_index = plane_index + if record.redshift is None: + record.redshift = float(tracer.planes[plane_index].redshift) + + record.linestyle, record.residual_label = pp.residual_style_from(fit_positions) + record.model_label = pp.model_label_from(fit_positions) + record.mixture = isinstance(fit_positions, FitPositionsImagePairAll) + try: + record.chi_squared = float(spp._np(fit_positions.chi_squared)) + except Exception: + record.chi_squared = None + + pairing = pp.model_pairing_from(fit_positions) + + if pairing is None: + # A source-plane fit: rank by its own per-image chi-squared. + try: + chi_squared_map = np.asarray( + spp._np(fit_positions.chi_squared_map), dtype=float + ).ravel() + record.image_plane_chi = np.sqrt(np.clip(chi_squared_map, 0.0, None)) + except Exception: + record.image_plane_chi = np.full(len(observed), np.nan) + return record + + _, model, indexes = pairing + record.model = model + record.indexes = indexes + record.unmatched = ( + pp.unmatched_model_mask_from(model, indexes) + if len(model) + else np.zeros(0, dtype=bool) + ) + + no_model = indexes < 0 + if ( + isinstance(fit_positions, FitPositionsImagePair) + and len(model) + and len(model) < len(observed) + ): + from scipy.optimize import linear_sum_assignment + + distances = np.linalg.norm(observed[:, None] - model[None], axis=2) + rows, _ = linear_sum_assignment(distances) + assigned = np.zeros(len(observed), dtype=bool) + assigned[rows] = True + no_model = no_model | ~assigned + record.no_model = no_model + + delta = np.full(len(observed), np.nan) + paired = indexes >= 0 + delta[paired] = np.linalg.norm(observed[paired] - model[indexes[paired]], axis=1) + record.delta = delta + + if len(model): + try: + record.mu_model = magnifications_at(tracer, model, plane_index) + except Exception: + record.mu_model = np.full(len(model), np.nan) + + return record + + +def assign_styles(records: List[SourceRecord]): + """ + Assigns every record its colour and marker, returning the ``(cmap, norm)`` of the colour-by-redshift scheme + used beyond ``MAX_QUALITATIVE`` sources (``None`` otherwise). + + Up to ``MAX_QUALITATIVE`` sources the colour is the fixed-order ``SOURCE_PALETTE`` (source 0 black). Beyond that + the colour follows the source redshift on viridis (truncated so the lightest yellow stays visible on white): + redshift is the physically meaningful ordering and is what sets each source's critical curve, so the nested + curves read as a family. Marker shapes cycle through ``MARKERS`` in both cases. + """ + import matplotlib as mpl + + colormap = None + if len(records) <= MAX_QUALITATIVE: + for record, color in zip(records, SOURCE_PALETTE): + record.color = color + else: + redshifts = np.array( + [r.redshift if r.redshift is not None else np.nan for r in records], + dtype=float, + ) + if not np.all(np.isfinite(redshifts)): + # No redshifts to colour by: colour by source index instead. + redshifts = np.arange(len(records), dtype=float) + vmin, vmax = float(redshifts.min()), float(redshifts.max()) + if vmax <= vmin: + vmax = vmin + 1.0 + norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax) + cmap = mpl.colors.LinearSegmentedColormap.from_list( + "viridis_trunc", mpl.colormaps["viridis"](np.linspace(0.0, 0.85, 256)) + ) + for record, z in zip(records, redshifts): + record.color = cmap(norm(z)) + colormap = (cmap, norm) + for k, record in enumerate(records): + record.marker = MARKERS[k % len(MARKERS)] + return colormap + + +def records_from_datasets(datasets) -> List[SourceRecord]: + records = [source_record_from_dataset(k, d) for k, d in enumerate(datasets)] + return records + + +def records_from_fits(fits) -> List[SourceRecord]: + return [source_record_from_fit(k, fit) for k, fit in enumerate(fits)] + + +# --------------------------------------------------------------------------- +# Per-plane critical curves and caustics +# --------------------------------------------------------------------------- + + +@dataclass +class PlaneCurves: + """ + The critical curves (image plane) and caustics (source plane) of one source plane, as lists of (N, 2) (y,x) + arrays. + """ + + plane_index: int + redshift: float + tangential: List[np.ndarray] + radial: List[np.ndarray] + tangential_caustics: List[np.ndarray] + radial_caustics: List[np.ndarray] + + def image_plane_lines(self): + """ + The curves as ``(lines, colors)`` in the format of ``_compute_critical_curve_lines`` (``"white"`` + tangential, ``"yellow"`` radial), for the figures which draw the last plane's curves over an image. + """ + lines = list(self.tangential) + list(self.radial) + colors = ["white"] * len(self.tangential) + ["yellow"] * len(self.radial) + return (lines or None), colors + + def source_plane_lines(self): + lines = list(self.tangential_caustics) + list(self.radial_caustics) + colors = ["white"] * len(self.tangential_caustics) + ["yellow"] * len( + self.radial_caustics + ) + return (lines or None), colors + + +def deflections_to_plane_from(tracer, points: np.ndarray, plane_index: int) -> np.ndarray: + """ + Returns the (N, 2) deflections of the image-plane ``points`` to plane ``plane_index`` of the FULL tracer: the + deflections the positions fit traces its observed positions with. + """ + import autoarray as aa + + grid = aa.Grid2DIrregular(values=np.asarray(points, dtype=float).reshape(-1, 2)) + if len(tracer.planes) <= 2: + deflections = tracer.deflections_yx_2d_from(grid=grid, xp=np) + else: + deflections = tracer.deflections_between_planes_from( + grid=grid, xp=np, plane_i=0, plane_j=plane_index + ) + return pp._np_grid(deflections) + + +def magnifications_at(tracer, points, plane_index: int, h: float = 1e-3) -> np.ndarray: + """ + Returns the signed magnification ``1 / det(A)`` at (y,x) ``points`` for plane ``plane_index``, by central finite + differences of the full tracer's deflections. + """ + points = np.asarray(points, dtype=float).reshape(-1, 2) + if len(points) == 0: + return np.zeros(0) + offsets = np.array([[h, 0.0], [-h, 0.0], [0.0, h], [0.0, -h]]) + stacked = np.concatenate([points + o for o in offsets]) + a = deflections_to_plane_from(tracer, stacked, plane_index).reshape(4, len(points), 2) + day_dy = (a[0, :, 0] - a[1, :, 0]) / (2 * h) + dax_dy = (a[0, :, 1] - a[1, :, 1]) / (2 * h) + day_dx = (a[2, :, 0] - a[3, :, 0]) / (2 * h) + dax_dx = (a[2, :, 1] - a[3, :, 1]) / (2 * h) + det = (1 - day_dy) * (1 - dax_dx) - day_dx * dax_dy + with np.errstate(divide="ignore"): + return 1.0 / det + + +def _contour_lines(field_, y_min, x_min, dy, dx, min_points=6): + from skimage.measure import find_contours + + lines = [] + for contour in find_contours(field_, 0.0): + if len(contour) < min_points: + continue + ys = y_min + contour[:, 0] * dy + xs = x_min + contour[:, 1] * dx + # A curve spanning fewer than 8 grid pixels is a marching-squares artefact around a singular mass centre, + # not a curve the grid resolves. + if max(np.ptp(ys), np.ptp(xs)) < 8.0 * max(dy, dx): + continue + lines.append(np.stack([ys, xs], axis=1)) + return lines + + +def curves_for_planes( + tracer, + plane_indexes, + extent: List[float], + shape: int = CURVE_GRID_SHAPE, +) -> Dict[int, PlaneCurves]: + """ + Returns the critical curves and caustics of every plane in ``plane_indexes``, keyed by plane index. + + The deflection field from the image plane to plane ``j`` of the FULL tracer is evaluated once on a + ``shape x shape`` grid covering ``extent`` (``[x_min, x_max, y_min, y_max]``), differentiated with + ``np.gradient`` into the convergence and shear, and contoured with marching squares where + ``λt = 1 - κ - γ = 0`` (tangential critical curves) and ``λr = 1 - κ + γ = 0`` (radial). Each critical curve is + ray-traced to plane ``j`` for its caustic. + + When every mass-bearing galaxy sits in one lens plane, the deflection to any later plane is the last plane's + times a distance ratio. The ratio is measured on probe points and, if the rescaling holds there, the last + plane's field is reused; otherwise the field is evaluated for that plane. + + Returns an empty dict when ``PYAUTO_FAST_PLOTS=1``. + """ + if os.environ.get("PYAUTO_FAST_PLOTS") == "1": + return {} + + last = len(tracer.planes) - 1 + indexes = sorted( + {last if (j is None or j < 0) else int(j) for j in plane_indexes} + ) + + x_min, x_max, y_min, y_max = extent + xs = np.linspace(x_min, x_max, shape) + ys = np.linspace(y_min, y_max, shape) + grid_x, grid_y = np.meshgrid(xs, ys) + points = np.stack([grid_y.ravel(), grid_x.ravel()], axis=1) + dy, dx = ys[1] - ys[0], xs[1] - xs[0] + + rng = np.random.default_rng(0) + probe = np.stack( + [rng.uniform(y_min, y_max, 64), rng.uniform(x_min, x_max, 64)], axis=1 + ) + probe_last = deflections_to_plane_from(tracer, probe, last) + field_last = None + + curves = {} + for j in indexes: + if j == last: + if field_last is None: + field_last = deflections_to_plane_from(tracer, points, last) + deflections = field_last + else: + probe_j = deflections_to_plane_from(tracer, probe, j) + usable = np.abs(probe_last) > 1e-6 + ratio = float(np.median(probe_j[usable] / probe_last[usable])) if np.any(usable) else np.nan + if np.isfinite(ratio) and np.allclose( + probe_j, ratio * probe_last, rtol=1e-6, atol=1e-9 + ): + if field_last is None: + field_last = deflections_to_plane_from(tracer, points, last) + deflections = ratio * field_last + else: + deflections = deflections_to_plane_from(tracer, points, j) + + alpha_y = deflections[:, 0].reshape(shape, shape) + alpha_x = deflections[:, 1].reshape(shape, shape) + day_dy, day_dx = np.gradient(alpha_y, dy, dx) + dax_dy, dax_dx = np.gradient(alpha_x, dy, dx) + kappa = 0.5 * (day_dy + dax_dx) + gamma = np.hypot(0.5 * (dax_dx - day_dy), 0.5 * (day_dx + dax_dy)) + + tangential = _contour_lines(1.0 - kappa - gamma, y_min, x_min, dy, dx) + radial = _contour_lines(1.0 - kappa + gamma, y_min, x_min, dy, dx) + + def _caustics(lines): + return [line - deflections_to_plane_from(tracer, line, j) for line in lines] + + curves[j] = PlaneCurves( + plane_index=j, + redshift=float(tracer.planes[j].redshift), + tangential=tangential, + radial=radial, + tangential_caustics=_caustics(tangential), + radial_caustics=_caustics(radial), + ) + return curves + + +def curves_for_records(tracer, records: List[SourceRecord], extent, shape=CURVE_GRID_SHAPE): + """ + Returns :func:`curves_for_planes` for the planes of every record (and the last plane), or an empty dict if they + cannot be computed (a visualization must never stop a model-fit). + """ + import logging + + plane_indexes = [r.plane_index for r in records if r.plane_index is not None] + plane_indexes.append(len(tracer.planes) - 1) + try: + return curves_for_planes(tracer, plane_indexes, extent, shape=shape) + except Exception: + logging.getLogger(__name__).warning( + "Point-source critical curves could not be computed; figures are drawn without them.", + exc_info=True, + ) + return {} + + +def curves_for_fits(fits, records: List[SourceRecord], extent, shape=CURVE_GRID_SHAPE): + """ + The curves of every source of several fits. Fits of one lens model (the usual cluster factor graph, where every + factor fits the same model) share their tracer's planes, so the curves are computed once from the first fit's + FULL tracer. If the fits' tracers have different planes, each source's curves are computed from its own fit and + keyed by its index (``record.curve_key``). + """ + tracers = [fit.tracer for fit in fits] + redshifts = [tuple(float(p.redshift) for p in t.planes) for t in tracers] + if all(r == redshifts[0] for r in redshifts): + return curves_for_records(tracers[0], records, extent, shape=shape) + curves = {} + for record, tracer in zip(records, tracers): + own = curves_for_records(tracer, [record], extent, shape=shape) + record.curve_key = ("source", record.k) + if record.plane_index in own: + curves[record.curve_key] = own[record.plane_index] + return curves + + +def union_extent_from(records: List[SourceRecord], solver=None) -> List[float]: + """ + Returns the ``[x_min, x_max, y_min, y_max]`` extent of a positions figure of several sources: the solver grid's + extent, enlarged to contain every observed position (:func:`positions_panel.positions_extent_from` of all the + sources' positions together). + """ + observed = np.vstack([r.observed for r in records]) + return pp.positions_extent_from(positions=observed, solver=solver) + + +def ranking_range_from(records: List[SourceRecord]) -> float: + """ + The linear Δ/σ range of the residual ranking shared by every source: 1.2 times the 90th-percentile residual of + all images (a robust maximum, so one outlier does not squash every other image), at least 4σ. Larger values are + drawn off-scale at the edge with their value printed. + """ + values = np.concatenate([r.residual_sigmas for r in records]) if records else [] + values = np.asarray(values, dtype=float) + values = values[np.isfinite(values)] + p90 = float(np.percentile(values, 90)) if len(values) else 3.0 + return max(4.0, 1.2 * p90) + + +def ranking_rows_from(record: SourceRecord): + """ + The ranking entries of a source, ``(value, label, kind, index)`` worst first, with unmatched model images (no + residual) last. ``kind`` is ``"obs"``, ``"nomodel"`` (an observed image with no model image of its own) or + ``"unmatched"``. + """ + values = record.residual_sigmas + rows = [] + for i in range(len(record.observed)): + kind = "nomodel" if record.no_model[i] else "obs" + rows.append((float(values[i]), f"{record.numbers[i]}", kind, i)) + rows.sort(key=lambda t: -(t[0] if np.isfinite(t[0]) else -1.0)) + for m, letter in zip(np.where(record.unmatched)[0], record.unmatched_labels): + rows.append((np.nan, letter, "unmatched", int(m))) + return rows + + +@dataclass +class RankingScales: + """ + The scales shared by every row of ``fit_per_image`` (and every per-source file of a many-source fit), computed + where every source is visible: the ranking range and the number of ranking slots. + """ + + xmax: float + n_slots: int + + +def ranking_scales_from(records: List[SourceRecord]) -> RankingScales: + return RankingScales( + xmax=ranking_range_from(records), + n_slots=max([len(ranking_rows_from(r)) for r in records] + [1]), + ) diff --git a/autolens/point/plot/positions_panel.py b/autolens/point/plot/positions_panel.py index 36eccf718..8ae2cb075 100644 --- a/autolens/point/plot/positions_panel.py +++ b/autolens/point/plot/positions_panel.py @@ -36,9 +36,10 @@ MODEL_MARKER_LINEWIDTH = 1.2 # 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"} +# dark image backgrounds, which are invisible on the white positions panel, so they are mapped to dark grey and dark +# olive here, drawn thick so the curves read clearly against the markers. +CRITICAL_CURVE_COLOR_MAP = {"white": "0.2", "yellow": "#5c5c00"} +CRITICAL_CURVE_LINEWIDTH = 1.8 # Candidate placements of an image number relative to its image, as (dx, dy) offsets in points plus the text's @@ -192,7 +193,7 @@ def plot_observed_positions(ax, positions, noise_map): def plot_critical_curves(ax, lines, line_colors=None): """ - Draws critical curves as thin, light lines labelled ``Critical curve`` in the legend. + Draws critical curves as thick, dark 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 @@ -210,8 +211,7 @@ def plot_critical_curves(ax, lines, line_colors=None): line[:, 1], line[:, 0], color=CRITICAL_CURVE_COLOR_MAP.get(color, color), - linewidth=0.9, - alpha=0.8, + linewidth=CRITICAL_CURVE_LINEWIDTH, zorder=2, label=None if labelled else "Critical curve", ) @@ -248,7 +248,7 @@ def mass_centres_from(tracer) -> np.ndarray: return np.asarray(centres, dtype=float).reshape(-1, 2) -def plot_mass_centres(ax, tracer): +def plot_mass_centres(ax, tracer, size: float = 140, linewidths: float = 2): """ Draws the centre of every mass profile in the tracer as a ``+`` labelled ``Mass centre`` in the legend. """ @@ -258,10 +258,10 @@ def plot_mass_centres(ax, tracer): ax.scatter( centres[:, 1], centres[:, 0], - s=140, + s=size, c=MASS_CENTRE_COLOR, marker="+", - linewidths=2, + linewidths=linewidths, zorder=4.5, label="Mass centre", ) diff --git a/autolens/point/plot/source_plane_panel.py b/autolens/point/plot/source_plane_panel.py index 6ae04123c..54689fc7c 100644 --- a/autolens/point/plot/source_plane_panel.py +++ b/autolens/point/plot/source_plane_panel.py @@ -41,8 +41,11 @@ IMAGE_PLANE = "image" SOURCE_PLANE = "source" -CAUSTIC_COLOR = "0.6" -RADIAL_CAUSTIC_COLOR = "tab:olive" +# Caustics are dark and thick (as the critical curves of the image-plane panels), so they read clearly. +CAUSTIC_COLOR = "0.2" +RADIAL_CAUSTIC_COLOR = "#5c5c00" +CAUSTIC_LINEWIDTH = 1.8 +INSET_CAUSTIC_LINEWIDTH = 1.4 CENTRE_COLOR = pp.MODEL_COLOR MAGNIFICATION_NOISE_COLOR = "tab:purple" JACOBIAN_NOISE_COLOR = pp.NOISE_COLOR @@ -454,7 +457,7 @@ def _footprint_points(data: SourcePlaneData) -> np.ndarray: return points[np.isfinite(points).all(axis=1)] -def _plot_caustics(ax, tangential, radial, linewidth=0.9, label=True): +def _plot_caustics(ax, tangential, radial, linewidth=CAUSTIC_LINEWIDTH, label=True): labelled = False for line, color in [(c, CAUSTIC_COLOR) for c in tangential] + [ (c, RADIAL_CAUSTIC_COLOR) for c in radial @@ -464,7 +467,6 @@ def _plot_caustics(ax, tangential, radial, linewidth=0.9, label=True): line[:, 0], color=color, linewidth=linewidth, - alpha=0.8, zorder=2, label="Caustic" if (label and not labelled) else None, ) @@ -599,7 +601,9 @@ def _add_inset(ax, data: SourcePlaneData, tangential, radial, zoom, bounds): return None inset = ax.inset_axes(bounds) - _plot_caustics(inset, tangential, radial, linewidth=0.8, label=False) + _plot_caustics( + inset, tangential, radial, linewidth=INSET_CAUSTIC_LINEWIDTH, label=False + ) _plot_centre(inset, data, size=50, label=False) points = np.vstack(framed + [data.traced, data.centre[None, :]]) @@ -641,6 +645,8 @@ def plot_source_plane_panel( title: str, tangential_caustics=None, radial_caustics=None, + point_colors=None, + legend: bool = True, ): """ Draws the "Fit Source Plane" panel of a positions fit on ``ax`` (see the module docstring). @@ -655,6 +661,10 @@ def plot_source_plane_panel( The panel title, e.g. ``"Fit Source Plane (point_0)"``. tangential_caustics, radial_caustics The caustics of the point source's plane, as lists of (N, 2) (y,x) arrays. + point_colors + The colour of each traced position (black if ``None``), e.g. the per-image colours of ``fit_per_image.png``. + legend + Whether the panel draws its legend (``fit_per_image.png`` draws none). """ from autoarray.plot.utils import apply_extent, apply_labels @@ -677,8 +687,10 @@ def plot_source_plane_panel( traced[:, 1], traced[:, 0], s=110, - c=pp.OBSERVED_COLOR, + c=pp.OBSERVED_COLOR if point_colors is None else list(point_colors), marker="o", + edgecolors="k", + linewidths=0.6, zorder=4, label=f"Observed, traced ({pp.sigma_label_from(data.sigma)})", ) @@ -695,12 +707,13 @@ def plot_source_plane_panel( # A handle-less entry: the chi-squared the fit uses, in the legend with the other fit-type cues. ax.plot([], [], linestyle="none", marker="none", label=chi_squared_label) - ax.legend( - loc=CORNER_LOCATIONS[legend_corner], - fontsize=8, - framealpha=0.85, - markerscale=0.6, - ) + if legend: + ax.legend( + loc=CORNER_LOCATIONS[legend_corner], + fontsize=8, + framealpha=0.85, + markerscale=0.6, + ) if has_inset: _add_inset(ax, data, tangential, radial, zoom, inset_bounds) diff --git a/test_autolens/point/plot/test_fit_point_plots.py b/test_autolens/point/plot/test_fit_point_plots.py index e629844e4..2cb62938b 100644 --- a/test_autolens/point/plot/test_fit_point_plots.py +++ b/test_autolens/point/plot/test_fit_point_plots.py @@ -79,8 +79,8 @@ def recording_plot_array(*args, **kwargs): assert scatter_labels.count("Observed") == 1 assert "Model" not in scatter_labels assert len(plot_array_kwargs) == 1 - assert plot_array_kwargs[0]["lines"] is None - assert plot_array_kwargs[0]["title"].endswith("Image With Points") + assert "lines" not in plot_array_kwargs[0] + assert plot_array_kwargs[0]["title"].startswith("Image With Points") assert "Fit Image" not in plot_array_kwargs[0]["title"] diff --git a/test_autolens/point/plot/test_multi_source_plots.py b/test_autolens/point/plot/test_multi_source_plots.py new file mode 100644 index 000000000..82fb7e475 --- /dev/null +++ b/test_autolens/point/plot/test_multi_source_plots.py @@ -0,0 +1,345 @@ +import shutil +from pathlib import Path +from types import SimpleNamespace + +import numpy as np +import pytest + +import autolens as al +from autolens.point.plot import multi_source_plots as msp +from autolens.point.plot import point_sources as ps + +directory = Path(__file__).resolve().parent + + +def _tracer(n_sources=2): + redshifts = [1.0, 2.0, 1.5, 2.5, 3.0, 1.2, 1.8, 2.2, 2.8, 3.5][:n_sources] + centres = [(0.05, 0.03), (-0.04, 0.06), (0.02, -0.05), (0.0, 0.08), (-0.06, -0.02)] + sources = [ + al.Galaxy( + redshift=z, + **{f"point_{k}": al.ps.Point(centre=centres[k % len(centres)])}, + ) + for k, z in enumerate(redshifts) + ] + return al.Tracer( + galaxies=[ + al.Galaxy( + redshift=0.5, + mass=al.mp.Isothermal( + centre=(0.0, 0.0), ell_comps=(0.05, 0.0), einstein_radius=1.0 + ), + ) + ] + + sources + ) + + +def _solver(): + return al.PointSolver.for_grid( + grid=al.Grid2D.uniform(shape_native=(60, 60), pixel_scales=0.05), + pixel_scale_precision=0.001, + magnification_threshold=0.1, + ) + + +def _datasets(tracer, solver, n_sources=2, offset=0.003): + datasets = [] + for k in range(n_sources): + plane_index = tracer.extract_plane_index_of_profile(profile_name=f"point_{k}") + centre = tracer.planes[plane_index][0].cls_list_from(cls=al.ps.Point)[0].centre + positions = solver.solve( + tracer=tracer, source_plane_coordinate=centre, plane_redshift=tracer.planes[plane_index].redshift + ) + positions = np.asarray(positions.array) + positions = positions[np.isfinite(positions).all(axis=1)] + offset + datasets.append( + al.PointDataset( + name=f"point_{k}", + positions=al.Grid2DIrregular(values=positions), + positions_noise_map=0.005, + redshift=float(tracer.planes[plane_index].redshift), + ) + ) + return datasets + + +@pytest.fixture(name="cluster", scope="module") +def make_cluster(): + tracer = _tracer() + solver = _solver() + datasets = _datasets(tracer, solver) + fits = { + cls.__name__: [ + al.FitPointDataset( + dataset=d, tracer=tracer, solver=solver, fit_positions_cls=cls + ) + for d in datasets + ] + for cls in ( + al.FitPositionsImagePair, + al.FitPositionsImagePairAll, + al.FitPositionsSource, + ) + } + return SimpleNamespace(tracer=tracer, solver=solver, datasets=datasets, fits=fits) + + +@pytest.fixture(name="figures") +def make_figures(monkeypatch): + figures = [] + + def capture(fig, path=None, filename=None, **kwargs): + figures.append(SimpleNamespace(fig=fig, path=path, filename=filename)) + + monkeypatch.setattr(msp, "save_figure", capture) + return figures + + +def _legend_labels(ax): + legend = ax.get_legend() + return [] if legend is None else [t.get_text() for t in legend.get_texts()] + + +def test__curves_for_planes__each_source_plane_matches_lens_calc(cluster): + from autogalaxy.operate.lens_calc import LensCalc + + tracer = cluster.tracer + extent = [-2.0, 2.0, -2.0, 2.0] + curves = ps.curves_for_planes(tracer, [1, 2], extent, shape=300) + + grid = al.Grid2D.uniform(shape_native=(200, 200), pixel_scales=0.02) + radii = {} + for j in (1, 2): + lens_calc = LensCalc.from_tracer( + tracer=tracer, use_multi_plane=True, plane_i=0, plane_j=j + ) + reference = np.asarray( + lens_calc.tangential_critical_curve_list_from(grid=grid)[0].array + ) + fast = curves[j].tangential[0] + assert np.median(np.hypot(*fast.T)) == pytest.approx( + np.median(np.hypot(*reference.T)), abs=0.03 + ) + radii[j] = np.median(np.hypot(*fast.T)) + # Caustics are the critical curves traced to the plane: far smaller than the curves. + assert np.max(np.abs(curves[j].tangential_caustics[0])) < 0.5 + + # The z=2 source is lensed more strongly than the z=1 source: a larger critical curve. + assert radii[2] > radii[1] + 0.05 + + +def test__curves_for_planes__fast_plots_returns_none(cluster, monkeypatch): + monkeypatch.setenv("PYAUTO_FAST_PLOTS", "1") + assert ps.curves_for_planes(cluster.tracer, [1], [-2, 2, -2, 2]) == {} + + +def test__assign_styles__black_first_then_colour_and_shape_then_redshift(): + records = [ + ps.SourceRecord( + k=k, name=f"point_{k}", redshift=1.0 + 0.1 * k, + observed=np.zeros((1, 2)), sigma=np.ones(1), numbers=np.ones(1, dtype=int), + ) + for k in range(10) + ] + assert ps.assign_styles(records[:3]) is None + assert [r.color for r in records[:3]] == ["k", "#E69F00", "#56B4E9"] + assert [r.marker for r in records[:3]] == ["o", "s", "^"] + + colormap = ps.assign_styles(records) + assert colormap is not None + assert len({tuple(r.color) for r in records}) == 10 + + +def test__plot_dataset_positions__all_sources_labelled_no_curves(cluster, figures): + msp.plot_dataset_positions(cluster.datasets, solver=cluster.solver) + + ax = figures[0].fig.axes[0] + assert figures[0].filename == "dataset_point" + assert ax.get_title() == "Dataset Positions" + labels = _legend_labels(ax) + assert labels == ["point_0 (z = 1, σ = 0.005″)", "point_1 (z = 2, σ = 0.005″)"] + texts = {t.get_text() for t in ax.texts} + assert "0·1" in texts and "1·1" in texts + assert len(ax.lines) == 0 + + +def test__plot_fit_positions__global_figure(cluster, figures): + msp.plot_fit_positions(cluster.fits["FitPositionsImagePair"], solver=cluster.solver) + + ax = figures[0].fig.axes[0] + assert figures[0].filename == "fit" + assert ax.get_title() == "Fit Positions" + labels = _legend_labels(ax) + assert "point_0 (z = 1, σ = 0.005″)" in labels + assert "Critical curve (each source's z)" in labels + assert any(label.startswith("χ² = ") for label in labels) + # Residual lines are drawn at true length (observed -> model), never exaggerated. + record = ps.source_record_from_fit(0, cluster.fits["FitPositionsImagePair"][0]) + residuals = [ + line for line in ax.lines if line.get_color() == "r" and len(line.get_xydata()) == 2 + ] + lengths = sorted(np.hypot(*np.diff(line.get_xydata(), axis=0)[0]) for line in residuals) + assert max(lengths) < 10 * np.nanmax(record.delta) + 1e-6 + + +def test__plot_fit_positions__mixture_shows_minus_two_ln_l(cluster, figures): + msp.plot_fit_positions( + cluster.fits["FitPositionsImagePairAll"], solver=cluster.solver + ) + + labels = _legend_labels(figures[0].fig.axes[0]) + assert any(label.startswith("−2 ln L = ") for label in labels) + assert not any(label.startswith("χ²") for label in labels) + assert "Residual (nearest, soft pairing)" in labels + + +def test__subplot_fit_per_image__rows_no_legends_sigma_values(cluster, figures): + msp.subplot_fit_per_image( + cluster.fits["FitPositionsImagePair"], solver=cluster.solver + ) + + fig = figures[0].fig + assert figures[0].filename == "fit_per_image" + titles = [ax.get_title() for ax in fig.axes if ax.get_title()] + assert titles == [ + "Residuals (point_0, z = 1)", + "IP (point_0, z = 1)", + "SP (point_0, z = 1)", + "Residuals (point_1, z = 2)", + "IP (point_1, z = 2)", + "SP (point_1, z = 2)", + ] + assert all(ax.get_legend() is None for ax in fig.axes) + ranking = fig.axes[0] + assert not ranking.xaxis.get_visible() + assert any(t.get_text().endswith("σ") for t in ranking.texts) + + +def test__subplot_fit_per_image__source_plane_fit_ranks_by_own_chi(cluster): + fit = cluster.fits["FitPositionsSource"][0] + record = ps.source_record_from_fit(0, fit) + chi_squared_map = np.asarray(fit.positions.chi_squared_map.array).ravel() + assert record.residual_sigmas == pytest.approx(np.sqrt(chi_squared_map)) + assert not record.has_model + + +def test__ranking_scales__shared_where_all_sources_visible_lone_source_own_range(): + def record(values, k): + n = len(values) + r = ps.SourceRecord( + k=k, name=f"point_{k}", redshift=1.0, observed=np.zeros((n, 2)), + sigma=np.ones(n), numbers=np.arange(1, n + 1), + ) + r.delta = np.asarray(values, dtype=float) + return r + + small = record([0.5, 1.0], 0) + large = record([10.0, 20.0, 30.0], 1) + + shared = ps.ranking_scales_from([small, large]) + lone = ps.ranking_scales_from([small]) + + assert shared.xmax > 20.0 + assert lone.xmax == pytest.approx(4.0) + assert shared.n_slots == 3 + + +def test__subplot_fit_per_image__many_sources_one_file_each(figures): + tracer = _tracer(n_sources=10) + solver = _solver() + fits = [ + al.FitPointDataset( + dataset=d, tracer=tracer, solver=solver, + fit_positions_cls=al.FitPositionsImagePair, + ) + for d in _datasets(tracer, solver, n_sources=10) + ] + + msp.subplot_fit_per_image(fits, curves={}, output_path="out") + + assert len(figures) == 10 + assert {f.filename for f in figures} == {f"point_{k}" for k in range(10)} + assert all(str(f.path).endswith("fit_per_image") for f in figures) + + +@pytest.mark.parametrize("with_fit", [False, True]) +def test__plot_image_with_points__all_sources_no_legend(cluster, figures, with_fit): + image = al.Array2D.ones(shape_native=(30, 30), pixel_scales=0.1) + + msp.plot_image_with_points( + image, + datasets=cluster.datasets, + fits=cluster.fits["FitPositionsImagePair"] if with_fit else None, + solver=cluster.solver, + ) + + ax = figures[0].fig.axes[0] + assert ax.get_legend() is None + assert figures[0].filename == ("fit_image_with_points" if with_fit else "image_with_points") + texts = {t.get_text() for t in ax.texts} + assert "0·1" in texts and "1·1" in texts + + +def test__visualizer__combined_figures_written_for_several_point_analyses( + cluster, plot_patch +): + from autolens.point.model.visualizer import VisualizerPoint + + plot_path = directory / "files" / "plots" / "combined" + if plot_path.exists(): + shutil.rmtree(plot_path) + + image = al.Array2D.ones(shape_native=(30, 30), pixel_scales=0.1) + analyses = [ + al.AnalysisPoint( + dataset=d, + solver=cluster.solver, + image=image, + fit_positions_cls=al.FitPositionsImagePair, + use_jax=False, + ) + for d in cluster.datasets + ] + instance = SimpleNamespace(galaxies=cluster.tracer.galaxies) + paths = SimpleNamespace(image_path=plot_path, output_path=plot_path) + + VisualizerPoint.visualize_combined( + analyses=analyses, + paths=paths, + instance=[instance, instance], + during_analysis=False, + ) + + for name in ( + "fit.png", + "fit_per_image.png", + "fit_image_with_points.png", + "dataset_point.png", + "image_with_points.png", + ): + assert str(plot_path / name) in plot_patch.paths + + # A single point analysis has no combined figures (its own figures are output per analysis). + plot_patch.paths.clear() + VisualizerPoint.visualize_combined( + analyses=analyses[:1], paths=paths, instance=[instance], during_analysis=False + ) + assert plot_patch.paths == [] + + +def test__plotter__fit_per_image_toggle(cluster, plot_patch, monkeypatch): + import autolens.point.model.plotter as plotter_module + from autolens.point.model.plotter import PlotterPoint + + plot_path = directory / "files" / "plots" / "toggle" + plotter = PlotterPoint(image_path=plot_path) + fits = cluster.fits["FitPositionsImagePair"][:1] + + plotter.fit_per_image(fit_list=fits, curves={}) + assert str(plot_path / "fit_per_image.png") in plot_patch.paths + + plot_patch.paths.clear() + monkeypatch.setattr(plotter_module, "plot_setting", lambda section, name: False) + plotter.fit_per_image(fit_list=fits, curves={}) + assert plot_patch.paths == [] diff --git a/test_autolens/point/plot/test_positions_panel.py b/test_autolens/point/plot/test_positions_panel.py index 1698ac71f..d5a070834 100644 --- a/test_autolens/point/plot/test_positions_panel.py +++ b/test_autolens/point/plot/test_positions_panel.py @@ -3,7 +3,7 @@ import autolens as al from autolens import fixtures -from autolens.point.plot import fit_point_plots, point_dataset_plots +from autolens.point.plot import fit_point_plots, multi_source_plots, point_dataset_plots from autolens.point.plot.positions_panel import ( fallback_extent_from, mass_centres_from, @@ -27,6 +27,7 @@ def capture(fig, **kwargs): monkeypatch.setattr(point_dataset_plots, "save_figure", capture) monkeypatch.setattr(fit_point_plots, "save_figure", capture) + monkeypatch.setattr(multi_source_plots, "save_figure", capture) return figures @@ -132,8 +133,8 @@ def test__subplot_fit__title_extent_legend_mass_centres_and_curves(figures): ax = figures[0].axes[0] assert ax.get_title() == "Fit Positions (point_0)" - assert figures[0].axes[1].get_title() == "Fit Source Plane (point_0)" - assert figures[0].axes[2].get_title() == "Fit Fluxes (point_0)" + # The source-plane panel moved to fit_per_image.png: fit.png is Fit Positions (+ Fit Fluxes). + 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)) @@ -150,15 +151,19 @@ def test__subplot_fit__title_extent_legend_mass_centres_and_curves(figures): def test__subplot_fit__computes_critical_curves_when_none_given(figures, monkeypatch): - import autolens.lens.plot.critical_curves as critical_curves + from autolens.point.plot import point_sources calls = [] - def fake_lines(tracer, grid): - calls.append(grid) - return [np.array([[0.0, 1.0], [1.0, 0.0]])], ["white"], None, None + def fake_curves(tracer, plane_indexes, extent, shape=400): + calls.append(list(plane_indexes)) + line = np.array([[0.0, 1.0], [1.0, 0.0], [0.0, -1.0]]) + return { + j: point_sources.PlaneCurves(j, 1.0, [line], [], [line], []) + for j in set(plane_indexes) + } - monkeypatch.setattr(critical_curves, "_compute_critical_curve_lines", fake_lines) + monkeypatch.setattr(point_sources, "curves_for_planes", fake_curves) fit_point_plots.subplot_fit(fit=_fit()) diff --git a/test_autolens/point/plot/test_source_plane_panel.py b/test_autolens/point/plot/test_source_plane_panel.py index 5482f4fec..091570947 100644 --- a/test_autolens/point/plot/test_source_plane_panel.py +++ b/test_autolens/point/plot/test_source_plane_panel.py @@ -271,9 +271,14 @@ def test__image_numbers_from__point_solver_order(): @pytest.fixture(name="figures") def make_figures(monkeypatch): figures = [] + from autolens.point.plot import multi_source_plots + monkeypatch.setattr( fit_point_plots, "save_figure", lambda fig, **kwargs: figures.append(fig) ) + monkeypatch.setattr( + multi_source_plots, "save_figure", lambda fig, **kwargs: figures.append(fig) + ) return figures @@ -298,19 +303,30 @@ def test__subplot_fit__layout_and_consistent_image_numbers( ) fit = _fit(al.FitPositionsSource, dataset, solver) + from autolens.point.plot import multi_source_plots + fit_point_plots.subplot_fit(fit=fit, image_plane_lines=[], source_plane_lines=[]) - axes = figures[0].axes - titles = [ax.get_title() for ax in axes] - expected = ["Fit Positions (point_0)", "Fit Source Plane (point_0)"] + titles = [ax.get_title() for ax in figures[0].axes] + expected = ["Fit Positions (point_0)"] if fluxes is not None: expected.append("Fit Fluxes (point_0)") assert titles == expected - - # The source-plane fit's traced positions are not drawn on the image plane. - image_labels = _legend_labels(axes[0]) + image_labels = _legend_labels(figures[0].axes[0]) assert "Model (source plane)" not in image_labels + # fit_per_image.png: the residual ranking, image-plane and source-plane panels of the source. + figures.clear() + multi_source_plots.subplot_fit_per_image([fit], curves={}) + axes = figures[0].axes + assert [ax.get_title() for ax in axes] == [ + "Residuals (point_0, z = 1)", + "IP (point_0, z = 1)", + "SP (point_0, z = 1)", + ] + # No legends on fit_per_image. + assert all(ax.get_legend() is None for ax in axes) + # Image k is the same observed position on both panels. numbers = image_numbers_from(dataset.positions) traced = spp.traced_positions_from(fit.positions) @@ -321,8 +337,8 @@ def test__subplot_fit__layout_and_consistent_image_numbers( expected_source = sorted( (str(n), tuple(np.round(p[::-1], 8))) for n, p in zip(numbers, traced) ) - assert _number_texts(axes[0]) == expected_image - assert _number_texts(axes[1]) == expected_source + assert _number_texts(axes[1]) == expected_image + assert _number_texts(axes[2]) == expected_source def _three_plane_fit(solver, dataset): From 30360d261cf089fc5d40a3d76f2d58e6dbe66190 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Wed, 21 Oct 2026 22:21:05 +0100 Subject: [PATCH 2/2] fix: log10 image scale for cluster-scale images in single-source image_with_points Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019Y6tDwGThyc8UowuncXw88 --- autolens/point/plot/multi_source_plots.py | 25 ++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/autolens/point/plot/multi_source_plots.py b/autolens/point/plot/multi_source_plots.py index b7014abdf..aeb6f59f3 100644 --- a/autolens/point/plot/multi_source_plots.py +++ b/autolens/point/plot/multi_source_plots.py @@ -1003,6 +1003,24 @@ def subplot_fit_per_image( # --------------------------------------------------------------------------- +# An image wider than this (arc-seconds) is cluster scale: a bright BCG and faint arcs need a log10 colour scale. +CLUSTER_IMAGE_WIDTH = 20.0 + + +def use_log10_from(image, multi: bool) -> bool: + """ + Clusters (several sources, or a cluster-scale image even when one source is drawn) use a log10 colour scale; + a galaxy-scale lens keeps the library's linear scale. + """ + if multi: + return True + try: + width = float(np.max(np.asarray(image.shape_native)) * np.max(image.pixel_scales)) + except Exception: + return False + return width > CLUSTER_IMAGE_WIDTH + + def plot_image_with_points( image, datasets=None, @@ -1020,8 +1038,9 @@ def plot_image_with_points( With ``fits=None`` only the observed positions of ``datasets`` are drawn (``image_with_points.png``); with ``fits`` the model positions, residual lines and each source's tangential critical curves at its own redshift are - added (``fit_image_with_points.png``, so both figures coexist). Clusters (several sources) use a log10 colour - scale (a bright BCG and faint arcs); a single lens keeps the linear scale. There is no legend. + added (``fit_image_with_points.png``, so both figures coexist). Clusters (several sources, or an image wider than + ``CLUSTER_IMAGE_WIDTH``) use a log10 colour scale (a bright BCG and faint arcs); a galaxy-scale lens keeps the + linear scale. There is no legend. ``image_plane_lines`` (pre-computed last-plane curves) are drawn only when ``curves`` cannot be computed. """ @@ -1049,7 +1068,7 @@ def plot_image_with_points( title = f"{_prefix(title_prefix)}{name}" + (f" ({records[0].name})" if not multi else "") fig, ax = subplots(1, 1, figsize=figsize_from(records)) - plot_array(array=image, ax=ax, use_log10=multi, title=title) + plot_array(array=image, ax=ax, use_log10=use_log10_from(image, multi), title=title) scale_fonts(ax, scale) for other in fig.axes[1:]: for tick in other.get_yticklabels():