diff --git a/autolens/cluster/plot/cluster_plots.py b/autolens/cluster/plot/cluster_plots.py index 32e2aa98b..515b460f7 100644 --- a/autolens/cluster/plot/cluster_plots.py +++ b/autolens/cluster/plot/cluster_plots.py @@ -8,11 +8,9 @@ own critical curves and caustics. The helpers here encode the cluster-figure conventions of the observational literature: -- A percentile-driven ``LogNorm`` on a perceptually-ordered colormap, so one image - spans the BCG core, intra-cluster light and faint arcs without saturating. -- Per-source qualitative colouring from the Wong (2011) colour-blind-safe palette - (https://www.nature.com/articles/nmeth.1618), applied consistently across every - panel so "the orange source" means the same thing everywhere. +- A grayscale asinh stretch on the cluster image, using its native sky geometry. +- Shared family colours and marker shapes. Dense fields use the redshift palette + when redshifts are supplied, with source index colours otherwise. - Per-source-plane critical curves computed through the multi-plane ``LensCalc`` (``use_multi_plane=True, plane_j=j``): at cluster scale the critical curves of the z=1 and z=2 source planes differ visibly, and plotting only the last plane's curve @@ -39,85 +37,146 @@ helpers that run on the numpy path. """ +from types import SimpleNamespace from typing import List, Optional, Sequence, Tuple import numpy as np +import autoarray as aa + from autoarray.plot.utils import ( subplots, save_figure, tight_layout, ) -# Wong (2011) colour-blind-safe qualitative palette; per-source colours in every helper. -WONG_PALETTE = [ - "#E69F00", # orange - "#56B4E9", # sky blue - "#009E73", # bluish green - "#F0E442", # yellow - "#0072B2", # blue - "#D55E00", # vermillion - "#CC79A7", # reddish purple - "#000000", # black -] - -CLUSTER_CMAP = "gnuplot2" +from autolens.point.plot.cluster_sky import ( + angular_axes, + cluster_field, + draw_cluster_image, + family_style, +) +from autolens.point.plot.point_sources import assign_styles +from autolens.point.plot.positions_panel import image_order_from -def _image_native_and_pixel_scale(image, pixel_scales) -> Tuple[np.ndarray, float]: - """Return ``(native 2D array, pixel scale)`` for an ``Array2D`` or raw ndarray.""" - native = np.asarray(image.native if hasattr(image, "native") else image) - if pixel_scales is None: - if hasattr(image, "pixel_scales"): - pixel_scales = image.pixel_scales[0] - else: - raise ValueError( - "pixel_scales must be given when image is a raw ndarray with no " - ".pixel_scales attribute." - ) - scale = pixel_scales[0] if isinstance(pixel_scales, (tuple, list)) else pixel_scales - return native, float(scale) - +# Wong (2011) qualitative colours for source-plane curves. +WONG_PALETTE = [ + "#E69F00", + "#56B4E9", + "#009E73", + "#F0E442", + "#0072B2", + "#D55E00", + "#CC79A7", + "#000000", +] -def _lognorm_from(image_native: np.ndarray): - """Percentile-driven ``LogNorm`` (5th / 99.5th of positive pixels). - Cluster imaging has bright cores and faint arcs; fixed ``(vmin, vmax)`` bounds do - not transfer between datasets. Non-positive pixels are excluded because - ``LogNorm`` needs strictly positive bounds. - """ - from matplotlib.colors import LogNorm +def _positions_array(positions) -> np.ndarray: + """Return an (N, 2) array of (y, x) positions.""" + array = positions.array if hasattr(positions, "array") else positions + return np.asarray(array).reshape(-1, 2) - positive = image_native[image_native > 0] - if positive.size == 0: - raise ValueError("Image has no positive pixels; cannot build a LogNorm.") - vmin = float(np.percentile(positive, 5.0)) - vmax = float(np.percentile(positive, 99.5)) - return LogNorm(vmin=vmin, vmax=max(vmax, vmin * 10.0)) +def _cluster_image(image, pixel_scales): + if image is None or (hasattr(image, "geometry") and pixel_scales is None): + return image + if pixel_scales is None: + raise ValueError("pixel_scales must be given for a raw image.") + if hasattr(image, "geometry") and np.allclose(image.pixel_scales, pixel_scales): + return image + return aa.Array2D.no_mask( + values=np.asarray(getattr(image, "native", image)), + pixel_scales=pixel_scales, + origin=getattr(getattr(image, "geometry", None), "origin", (0.0, 0.0)), + ) -def _extent_from(image_native: np.ndarray, pixel_scale: float) -> Tuple: - """``imshow`` extent ``(left, right, bottom, top)`` for an origin-centred field.""" - half_y = image_native.shape[0] * pixel_scale / 2.0 - half_x = image_native.shape[1] * pixel_scale / 2.0 - return (-half_x, half_x, -half_y, half_y) +def _family_markers(positions_list, datasets, on_image): + positions_list = list(positions_list) + if datasets is not None and len(datasets) != len(positions_list): + raise ValueError("datasets must supply metadata for each position family.") + records = [ + SimpleNamespace( + k=index, + name=dataset.name if dataset is not None else f"Source {index}", + redshift=dataset.redshift if dataset is not None else None, + ) + for index, dataset in enumerate( + datasets if datasets is not None else [None] * len(positions_list) + ) + ] + redshift_styles = assign_styles(records) + for record, positions in zip(records, positions_list): + arr = _positions_array(positions) + if not len(arr): + continue + if redshift_styles is None: + bright, dark, marker = family_style(record) + else: + bright = dark = record.color + marker = record.marker + name, redshift = record.name, record.redshift + label = f"{name} · {len(arr)} {'image' if len(arr) == 1 else 'images'}" + if redshift is not None: + label += f" · z={redshift:.2f}" + yield arr, bright if on_image else dark, marker, name, label + + +def _scatter_family(ax, positions, colour, marker, size, label=None): + from matplotlib import patheffects + from matplotlib.colors import to_rgb + + artist = ax.scatter( + positions[:, 1], + positions[:, 0], + facecolors="none", + edgecolors=colour, + marker=marker, + s=size, + linewidths=1.6, + zorder=7, + label=label, + ) -def _positions_array(positions) -> np.ndarray: - """Return an ``(N, 2)`` ``[y, x]`` array from a Grid2DIrregular / list / array.""" - array = positions.array if hasattr(positions, "array") else positions - return np.atleast_2d(np.asarray(array)) + if ax.images and np.dot(to_rgb(colour), (0.2126, 0.7152, 0.0722)) < 0.35: + artist.set_path_effects( + [patheffects.withStroke(linewidth=2.6, foreground=(1, 1, 1, 0.65))] + ) -def _draw_image(ax, image, pixel_scales): - native, scale = _image_native_and_pixel_scale(image, pixel_scales) - ax.imshow( - native, - origin="lower", - cmap=CLUSTER_CMAP, - norm=_lognorm_from(native), - extent=_extent_from(native, scale), - ) +def _set_sky_field(ax, image=None, positions=None): + if image is not None: + centre, half = cluster_field( + image.geometry.extent, np.empty((0, 2)) if positions is None else positions + ) + else: + bounds = np.asarray(ax.dataLim.get_points())[:, ::-1] + if np.isfinite(bounds).all(): + centre = bounds.mean(axis=0) + half = max(float(np.ptp(bounds, axis=0).max()) * 0.56, 1.0e-4) + else: + centre, half = (0.0, 0.0), 1.0 + angular_axes(ax, centre, half) + + +def _top_legend(ax): + handles, labels = ax.get_legend_handles_labels() + if handles: + ax.legend( + handles, + labels, + loc="lower center", + bbox_to_anchor=(0.5, 1.02), + ncols=min( + 5 if len(handles) > 12 else 4 if len(handles) > 4 else 3, len(handles) + ), + frameon=False, + fontsize=8, + handletextpad=0.4, + columnspacing=1.1, + ) def _draw_centre_markers(ax, centres, halo_centres, marker_size: float): @@ -154,19 +213,19 @@ def _draw_centre_markers(ax, centres, halo_centres, marker_size: float): ) -def _draw_kpc_scale_bar(ax, redshift: float, cosmology, kpc: float): +def _draw_kpc_scale_bar(ax, redshift: float, cosmology, kpc: float, colour: str): """Draw a physical scale bar in the bottom-left corner of *ax*.""" arcsec_per_kpc = float(cosmology.arcsec_per_kpc_proper(redshift)) bar_arcsec = kpc * arcsec_per_kpc xlim, ylim = ax.get_xlim(), ax.get_ylim() x0 = xlim[0] + 0.05 * (xlim[1] - xlim[0]) y0 = ylim[0] + 0.05 * (ylim[1] - ylim[0]) - ax.plot([x0, x0 + bar_arcsec], [y0, y0], color="white", lw=3.0, zorder=5) + ax.plot([x0, x0 + bar_arcsec], [y0, y0], color=colour, lw=3.0, zorder=5) ax.text( x0 + bar_arcsec / 2.0, y0 + 0.02 * (ylim[1] - ylim[0]), f"{int(kpc)} kpc", - color="white", + color=colour, ha="center", va="bottom", fontsize=11, @@ -202,7 +261,10 @@ def _lens_calc_for_plane(tracer, plane_index: int): "tangential", "critical_curve", ): "tangential_critical_curve_list_via_zero_contour_from", - ("radial", "critical_curve"): "radial_critical_curve_list_via_zero_contour_from", + ( + "radial", + "critical_curve", + ): "radial_critical_curve_list_via_zero_contour_from", ("tangential", "caustic"): "tangential_caustic_list_via_zero_contour_from", ("radial", "caustic"): "radial_caustic_list_via_zero_contour_from", }, @@ -246,6 +308,8 @@ def plot_positions_overlay( output_path: Optional[str] = None, output_filename: str = "cluster_positions", output_format: Optional[str] = None, + *, + datasets: Optional[Sequence] = None, ): """ Plot every source's observed multiple-image positions, per-source coloured, on the @@ -255,11 +319,12 @@ def plot_positions_overlay( ---------- positions_list One ``Grid2DIrregular`` (or ``(N, 2)`` array) of image-plane positions per - source. Source ``i`` is drawn in ``WONG_PALETTE[i]`` — the same colour this - source gets in every other helper. + source. Colours and marker shapes are shared across the cluster dataset figures. + datasets + Optional point datasets in the same order, supplying family names and redshifts. image Optional background image (``Array2D`` or raw 2D ndarray) drawn with the - cluster ``LogNorm``; without it positions are drawn on a blank field. + shared grayscale asinh stretch; without it positions are drawn on a blank field. pixel_scales Arcsec per pixel of *image*; taken from ``image.pixel_scales`` when omitted and the image is an ``Array2D``. @@ -275,42 +340,43 @@ def plot_positions_overlay( output_path, output_filename, output_format Standard workspace output controls (ignored when *ax* is supplied). """ + image = _cluster_image(image, pixel_scales) + families = list( + _family_markers(positions_list, datasets, on_image=image is not None) + ) standalone = ax is None if standalone: - fig, ax = subplots(1, 1) - + fig, ax = subplots(1, 1, figsize=(10 if len(families) > 5 else 7, 7)) if image is not None: - _draw_image(ax, image, pixel_scales) + draw_cluster_image(ax, image) - for i, positions in enumerate(positions_list): - arr = _positions_array(positions) - colour = WONG_PALETTE[i % len(WONG_PALETTE)] - ax.scatter( - arr[:, 1], - arr[:, 0], - facecolors="none", - edgecolors=colour, - marker="o", - s=140, - linewidths=1.8, - zorder=6, - label=f"Source {i} images", - ) + for arr, colour, marker, _, label in families: + _scatter_family(ax, arr, colour, marker, size=95, label=label) _draw_centre_markers( ax, centres=centres, halo_centres=halo_centres, marker_size=marker_size ) + positions = [arr for arr, *_ in families] + if centres is not None: + positions.append(_positions_array(centres)) + if halo_centres is not None: + positions.append(_positions_array(halo_centres)) + _set_sky_field(ax, image, np.concatenate(positions) if positions else None) if kpc_scale_bar is not None and redshift is not None and cosmology is not None: _draw_kpc_scale_bar( - ax, redshift=redshift, cosmology=cosmology, kpc=kpc_scale_bar + ax, + redshift=redshift, + cosmology=cosmology, + kpc=kpc_scale_bar, + colour="white" if image is not None else "#282d32", ) - ax.set_xlabel('x (")') - ax.set_ylabel('y (")') - ax.set_title(title) - ax.set_aspect("equal") - ax.legend(loc="upper right", fontsize=9, framealpha=0.6) + if standalone: + fig.suptitle(title, y=0.99) + else: + ax.set_title(title, y=1.02 + 0.07 * np.ceil(len(families) / 5)) + _top_legend(ax) if standalone: tight_layout() @@ -329,6 +395,8 @@ def plot_image_group_zooms( output_path: Optional[str] = None, output_filename: str = "cluster_image_zooms", output_format: Optional[str] = None, + *, + datasets: Optional[Sequence] = None, ): """ A panel grid with one zoom per multiple image, rows grouped by source. @@ -336,7 +404,8 @@ def plot_image_group_zooms( Each panel is a ``zoom_arcsec``-wide cut-out centred on one observed image position, framed in that source's palette colour. This is how the eye verifies a model at cluster scale: full-field residuals hide a half-arcsecond position - mismatch that a 6" zoom makes obvious. + mismatch that a 6" zoom makes obvious. Image numbers follow the angular + ordering used in the point-fit figures. Parameters ---------- @@ -344,6 +413,8 @@ def plot_image_group_zooms( One ``Grid2DIrregular`` (or ``(N, 2)`` array) per source. image Background image (``Array2D`` or raw 2D ndarray). + datasets + Optional point datasets in the same order, used for family names. pixel_scales Arcsec per pixel; taken from ``image.pixel_scales`` when omitted. zoom_arcsec @@ -351,54 +422,36 @@ def plot_image_group_zooms( max_cols Maximum panels per row; a source with more images wraps onto extra rows. """ - native, scale = _image_native_and_pixel_scale(image, pixel_scales) - norm = _lognorm_from(native) - extent = _extent_from(native, scale) - half = zoom_arcsec / 2.0 - - panels = [ - (i, arr_row) - for i, positions in enumerate(positions_list) - for arr_row in _positions_array(positions) - ] - n_panels = max(len(panels), 1) - n_cols = min(max_cols, n_panels) - n_rows = int(np.ceil(n_panels / n_cols)) - - fig, axes = subplots(n_rows, n_cols) - axes = np.atleast_1d(axes).ravel() - - for ax in axes[n_panels:]: + if max_cols < 1 or zoom_arcsec <= 0: + raise ValueError("max_cols and zoom_arcsec must be positive.") + image = _cluster_image(image, pixel_scales) + families = list(_family_markers(positions_list, datasets, on_image=True)) + n_cols = min(max_cols, max((len(arr) for arr, *_ in families), default=1)) + n_rows = max(1, sum(int(np.ceil(len(arr) / n_cols)) for arr, *_ in families)) + fig, axes = subplots( + n_rows, n_cols, squeeze=False, figsize=(2.6 * n_cols, 2.7 * n_rows) + ) + for ax in axes.flat: ax.set_axis_off() - counters = {} - for ax, (source_index, (y, x)) in zip(axes, panels): - counters[source_index] = counters.get(source_index, 0) + 1 - colour = WONG_PALETTE[source_index % len(WONG_PALETTE)] - ax.imshow(native, origin="lower", cmap=CLUSTER_CMAP, norm=norm, extent=extent) - ax.scatter( - [x], - [y], - facecolors="none", - edgecolors=colour, - marker="o", - s=220, - linewidths=2.0, - ) - ax.set_xlim(x - half, x + half) - ax.set_ylim(y - half, y + half) - ax.set_title( - f"Source {source_index} image {counters[source_index]}", - color=colour, - fontsize=10, - ) - ax.set_xticks([]) - ax.set_yticks([]) - for spine in ax.spines.values(): - spine.set_edgecolor(colour) - spine.set_linewidth(2.0) - - fig.suptitle(title) + row = 0 + for positions, colour, marker, name, _ in families: + for index, position in enumerate(positions[image_order_from(positions)]): + row_offset, col = divmod(index, n_cols) + ax = axes[row + row_offset, col] + ax.set_axis_on() + draw_cluster_image(ax, image) + _scatter_family(ax, position[None, :], colour, marker, size=120) + angular_axes(ax, position, zoom_arcsec / 2, small=True) + ax.set_xlabel("") + ax.set_ylabel("") + ax.set_title(f"{name} · Image {index + 1}", fontsize=10) + for spine in ax.spines.values(): + spine.set_edgecolor(colour) + spine.set_linewidth(1.5) + row += int(np.ceil(len(positions) / n_cols)) + + fig.suptitle(title, y=1 - 0.08 / fig.get_figheight()) tight_layout() save_figure(fig, path=output_path, filename=output_filename, format=output_format) @@ -422,9 +475,8 @@ def plot_critical_curves( At cluster scale each source redshift has its own critical curves (the lensing strength D_LS / D_S differs per plane), so a z=2 source's tangential curve sits - well outside a z=1 source's. Curves are coloured per plane with the same palette - the positions helpers use for the corresponding source, and labelled with the - plane redshift. + well outside a z=1 source's. Curve colours identify the source planes and match the + caustic colours. Legend labels give each plane's redshift and curve type. The curve engine is ``general.critical_curves_method`` from the visualize config, read once per call (see the module docstring): ``marching_squares`` (default) @@ -457,10 +509,11 @@ def plot_critical_curves( """ standalone = ax is None if standalone: - fig, ax = subplots(1, 1) + fig, ax = subplots(1, 1, figsize=(8, 7)) + image = _cluster_image(image, pixel_scales) if image is not None: - _draw_image(ax, image, pixel_scales) + draw_cluster_image(ax, image) method = _critical_curves_method() @@ -499,11 +552,15 @@ def plot_critical_curves( label=f"z={redshift:.2f} radial" if k == 0 else None, ) - ax.set_xlabel('x (")') - ax.set_ylabel('y (")') - ax.set_title(title) - ax.set_aspect("equal") - ax.legend(loc="upper right", fontsize=9, framealpha=0.6) + curves = [ + np.column_stack((line.get_ydata(), line.get_xdata())) for line in ax.lines + ] + _set_sky_field(ax, image, np.concatenate(curves) if curves else None) + _top_legend(ax) + if standalone: + fig.suptitle(title, y=0.99) + else: + ax.set_title(title, y=1.14) if standalone: tight_layout() @@ -552,7 +609,7 @@ def plot_caustics( """ standalone = ax is None if standalone: - fig, ax = subplots(1, 1) + fig, ax = subplots(1, 1, figsize=(8, 7)) method = _critical_curves_method() @@ -589,11 +646,14 @@ def plot_caustics( label=f"z={redshift:.2f} radial" if k == 0 else None, ) - ax.set_xlabel('source-plane x (")') - ax.set_ylabel('source-plane y (")') - ax.set_title(title) - ax.set_aspect("equal") - ax.legend(loc="upper right", fontsize=9, framealpha=0.6) + _set_sky_field(ax) + ax.set_xlabel("Source-plane x") + ax.set_ylabel("Source-plane y") + _top_legend(ax) + if standalone: + fig.suptitle(title, y=0.99) + else: + ax.set_title(title, y=1.14) if standalone: tight_layout() @@ -615,16 +675,20 @@ def subplot_cluster_dataset( output_path: Optional[str] = None, output_filename: str = "subplot_cluster_dataset", output_format: Optional[str] = None, + *, + datasets: Optional[Sequence] = None, ): """ Combined cluster mosaic: positions overlay | per-plane critical curves (+ image). When *tracer* (and *grid*) are omitted only the positions panel is drawn. The right panel repeats the positions on top of the critical curves so image - multiplicities can be read against the curves directly. + multiplicities can be read against the curves directly. Optional ``datasets`` + supply the family names and redshifts in the same order as ``positions_list``. """ + positions_list = list(positions_list) n_cols = 2 if tracer is not None else 1 - fig, axes = subplots(1, n_cols) + fig, axes = subplots(1, n_cols, figsize=(8 * n_cols, 7)) axes = np.atleast_1d(axes).ravel() plot_positions_overlay( @@ -636,6 +700,7 @@ def subplot_cluster_dataset( kpc_scale_bar=None, ax=axes[0], title="Multiple-Image Positions", + datasets=datasets, ) if tracer is not None: @@ -650,18 +715,22 @@ def subplot_cluster_dataset( ax=axes[1], title="Per-Plane Critical Curves", ) - for i, positions in enumerate(positions_list): - arr = _positions_array(positions) - axes[1].scatter( - arr[:, 1], - arr[:, 0], - facecolors="none", - edgecolors=WONG_PALETTE[i % len(WONG_PALETTE)], - marker="o", - s=90, - linewidths=1.4, - zorder=7, - ) + families = list( + _family_markers(positions_list, datasets, on_image=image is not None) + ) + for arr, colour, marker, _, _ in families: + _scatter_family(axes[1], arr, colour, marker, size=72) + # Use the same sky field so a family can be located across both panels. + axis_limits = [ + (min(a.get_xlim()[0] for a in axes), max(a.get_xlim()[1] for a in axes)), + (min(a.get_ylim()[0] for a in axes), max(a.get_ylim()[1] for a in axes)), + ] + centre = [np.mean(limits) for limits in reversed(axis_limits)] + half = max(high - low for low, high in axis_limits) / 2 + for ax in axes: + panel_title = ax.get_title() + angular_axes(ax, centre, half) + ax.set_title(panel_title, fontsize=11) fig.suptitle(title) tight_layout() diff --git a/autolens/config/visualize/plots.yaml b/autolens/config/visualize/plots.yaml index 4b04cf9f6..00040e962 100644 --- a/autolens/config/visualize/plots.yaml +++ b/autolens/config/visualize/plots.yaml @@ -65,7 +65,8 @@ fit_point_dataset: # Settings for plots of fits to point 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_per_image_combined: true # Write /fit.png with per-image contributions and fitted-plane zooms (six zooms per page). + family_fit_single_panel: false # Show all fitted-plane positions on shared angular axes instead of individual zooms. 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). diff --git a/autolens/point/fit/positions/image/abstract.py b/autolens/point/fit/positions/image/abstract.py index 524b71d30..37a7ffa5b 100644 --- a/autolens/point/fit/positions/image/abstract.py +++ b/autolens/point/fit/positions/image/abstract.py @@ -116,11 +116,16 @@ def square_distance( """ return (coord1[0] - coord2[0]) ** 2 + (coord1[1] - coord2[1]) ** 2 + # Only a visualizer's private copy sets this. A live fit always calls its solver. + _plot_model_data = None + @property def model_data(self) -> aa.Grid2DIrregular: """ Returns the model positions, which are computed via the point solver. """ + if self._plot_model_data is not None: + return self._plot_model_data return self.solver.solve( tracer=self.tracer, source_plane_coordinate=self.source_plane_coordinate, diff --git a/autolens/point/model/plotter.py b/autolens/point/model/plotter.py index 3c341b1a0..746c20a32 100644 --- a/autolens/point/model/plotter.py +++ b/autolens/point/model/plotter.py @@ -23,7 +23,7 @@ def _setting(section, name: str, default: bool = True) -> bool: class PlotterPoint(Plotter): - def dataset_point(self, dataset: PointDataset, solver=None): + def dataset_point(self, dataset: PointDataset, solver=None, family_index=None): """ Output visualization of a `PointDataset` dataset. @@ -49,6 +49,7 @@ def should_plot(name): output_format=fmt, title_prefix=self.title_prefix, solver=solver, + family_index=family_index, ) def image_with_points( @@ -59,6 +60,7 @@ def image_with_points( image_plane_lines=None, image_plane_line_colors=None, curves=None, + family_index=None, ): """ Output an observed image of the lensed point source with the point-source positions overlaid. @@ -102,6 +104,7 @@ def image_with_points( image_plane_line_colors=image_plane_line_colors, title_prefix=self.title_prefix, curves=curves, + family_index=family_index, ) def fit_point( @@ -113,6 +116,7 @@ def fit_point( source_plane_lines=None, source_plane_line_colors=None, curves=None, + family_index=None, ): """ Visualizes a `FitPointDataset` object: ``fit.png`` (controlled by ``fit: subplot_fit``, also output on a @@ -147,20 +151,38 @@ def fit_point( source_plane_line_colors=source_plane_line_colors, title_prefix=self.title_prefix, curves=curves, + family_index=family_index, ) - def fit_per_image(self, fit_list, curves=None, solver=None, combined: bool = False): + def fit_per_image( + self, + fit_list, + curves=None, + solver=None, + combined: bool = False, + image=None, + family_index=None, + ): """ - 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/``). - - 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. + Output a cluster diagnostic per family for a combined fit, or the single dataset's + residual ranking, image-plane zoom and source-plane panel in ``fit_per_image.png``. """ name = "fit_per_image_combined" if combined else "fit_per_image" if not _setting(["fit", "fit_point_dataset"], name): return + if combined: + from autolens.point.plot.family_fit_plots import plot_family_fits + + return plot_family_fits( + fit_list, + image=image, + single_panel=_setting( + ["fit", "fit_point_dataset"], "family_fit_single_panel", default=False + ), + output_path=str(self.image_path), + output_format=self.fmt, + title_prefix=self.title_prefix, + ) multi_source_plots.subplot_fit_per_image( fit_list, curves=curves, @@ -168,9 +190,10 @@ def fit_per_image(self, fit_list, curves=None, solver=None, combined: bool = Fal output_path=str(self.image_path), output_format=self.fmt, title_prefix=self.title_prefix, + family_index=family_index, ) - def dataset_point_combined(self, dataset_list, solver=None): + def dataset_point_combined(self, dataset_list, solver=None, image_extent=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``. @@ -180,12 +203,20 @@ def dataset_point_combined(self, dataset_list, solver=None): multi_source_plots.plot_dataset_positions( dataset_list, solver=solver, + image_extent=image_extent, output_path=str(self.image_path), output_format=self.fmt, title_prefix=self.title_prefix, ) - def fit_point_combined(self, fit_list, curves=None, solver=None, quick_update: bool = False): + def fit_point_combined( + self, + fit_list, + curves=None, + solver=None, + quick_update: bool = False, + image_extent=None, + ): """ 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 @@ -197,6 +228,7 @@ def fit_point_combined(self, fit_list, curves=None, solver=None, quick_update: b return multi_source_plots.plot_fit_positions( fit_list, + image_extent=image_extent, solver=solver, curves=curves, output_path=str(self.image_path), @@ -227,7 +259,7 @@ def image_with_points_combined(self, image, dataset_list, fit_list=None, curves= title_prefix=self.title_prefix, ) - def point_solver(self, fit: FitPointDataset, image_plane_lines=None): + def point_solver(self, fit: FitPointDataset, image_plane_lines=None, family_index=None): """ Output `point_solver.png`: how the `PointSolver` refines its triangles onto the images of the fit's model. @@ -275,4 +307,5 @@ def point_solver(self, fit: FitPointDataset, image_plane_lines=None): output_path=str(self.image_path), output_format=self.fmt, title_prefix=self.title_prefix, + family_index=family_index, ) diff --git a/autolens/point/model/visualizer.py b/autolens/point/model/visualizer.py index f470bdd21..ceea0bb82 100644 --- a/autolens/point/model/visualizer.py +++ b/autolens/point/model/visualizer.py @@ -1,6 +1,9 @@ +from copy import copy + import autofit as af from autolens.point.model.plotter import PlotterPoint +from autolens.point.fit.positions.image.abstract import AbstractFitPositionsImagePair from autolens.lens.plot.critical_curves import critical_curve_grid_from from autolens.point.plot import point_sources as ps @@ -11,6 +14,7 @@ def visualize_before_fit( analysis, paths: af.AbstractPaths, model: af.AbstractPriorModel, + family_index=None, ): """ PyAutoFit calls this function immediately before the non-linear search begins. @@ -25,6 +29,8 @@ def visualize_before_fit( model The model object, which includes model components representing the galaxies that are fitted to the imaging data. + family_index + The zero-based family index when this analysis is being visualized as part of a cluster. """ plotter = PlotterPoint( @@ -32,12 +38,18 @@ def visualize_before_fit( ) plotter.dataset_point( - dataset=analysis.dataset, solver=getattr(analysis, "solver", None) + dataset=analysis.dataset, + solver=getattr(analysis, "solver", None), + family_index=family_index, ) if getattr(analysis, "image", None) is not None: # Dataset-only figure (observed positions, no model): `image_with_points.png`. - plotter.image_with_points(image=analysis.image, dataset=analysis.dataset) + plotter.image_with_points( + image=analysis.image, + dataset=analysis.dataset, + family_index=family_index, + ) @staticmethod def visualize( @@ -46,6 +58,7 @@ def visualize( instance: af.ModelInstance, during_analysis: bool, quick_update: bool = False, + family_index=None, ): """ Output images of the maximum log likelihood model inferred by the model-fit. This function is called throughout @@ -69,6 +82,8 @@ def visualize( instance An instance of the model that is being fitted to the data by this analysis (whose parameters have been set via a non-linear search). + family_index + The zero-based family index when this analysis is being visualized as part of a cluster. """ fit = analysis.fit_for_visualization(instance=instance) @@ -87,7 +102,9 @@ def visualize( 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, curves=curves) + plotter.fit_point( + fit=fit, quick_update=quick_update, curves=curves, family_index=family_index + ) # 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. @@ -99,12 +116,15 @@ def visualize( image_plane_lines=ip_lines, image_plane_line_colors=ip_colors, curves=curves, + family_index=family_index, ) if quick_update: return - plotter.fit_per_image(fit_list=[fit], curves=curves, solver=solver) + plotter.fit_per_image( + fit_list=[fit], curves=curves, solver=solver, family_index=family_index + ) plotter.tracer( tracer=tracer, @@ -122,7 +142,7 @@ def visualize( # Off by default (`fit_point_dataset: subplot_point_solver`): re-solves the best-fit model with NumPy to show # the solver's refinement steps, so it is output only for the full (not quick-update) visualization. The # figure computes the critical curves of the source's own plane on its own (per-source) extent. - plotter.point_solver(fit=fit) + plotter.point_solver(fit=fit, family_index=family_index) @staticmethod def visualize_before_fit_combined( @@ -160,8 +180,8 @@ def visualize_combined( - ``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.png``: the cluster overview, per-image contributions, fitted-plane details and the + complete source-plane view. Additional groups of six zooms use ``fit_page_02.png``, etc.; - ``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. @@ -182,7 +202,7 @@ def visualize_combined( ) fit_list = [ - analysis.fit_for_visualization(instance=single_instance) + _combined_plot_fit(analysis.fit_for_visualization(instance=single_instance)) for analysis, single_instance in pairs ] solver = getattr(analyses[0], "solver", None) or getattr( @@ -190,11 +210,15 @@ def visualize_combined( ) curves = curves_for_point_fits(fits=fit_list, solver=solver) + image = _image_from(analyses) plotter.fit_point_combined( - fit_list=fit_list, curves=curves, solver=solver, quick_update=quick_update + fit_list=fit_list, + curves=curves, + solver=solver, + quick_update=quick_update, + image_extent=image.geometry.extent if image is not None else None, ) - image = _image_from(analyses) if image is not None: plotter.image_with_points_combined( image=image, @@ -208,11 +232,24 @@ def visualize_combined( return plotter.fit_per_image( - fit_list=fit_list, curves=curves, solver=solver, combined=True + fit_list=fit_list, curves=curves, solver=solver, combined=True, image=image ) _visualize_datasets_combined(plotter, analyses) +def _combined_plot_fit(fit): + """Share a fixed image-plane solution across all panels of this visualization call.""" + positions = fit.positions + if not isinstance(positions, AbstractFitPositionsImagePair): + return fit + if type(positions).model_data is not AbstractFitPositionsImagePair.model_data: + return fit + result = copy(fit) + result.positions = copy(positions) + result.positions._plot_model_data = positions.model_data + return result + + def _is_point_analysis(analysis) -> bool: from autolens.point.model.analysis import AnalysisPoint @@ -236,8 +273,11 @@ def _image_from(analyses): 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) + plotter.dataset_point_combined( + dataset_list=dataset_list, solver=solver, + image_extent=image.geometry.extent if image is not None else None, + ) if image is not None: plotter.image_with_points_combined( image=image, dataset_list=dataset_list, solver=solver diff --git a/autolens/point/plot/cluster_sky.py b/autolens/point/plot/cluster_sky.py new file mode 100644 index 000000000..061a69d0e --- /dev/null +++ b/autolens/point/plot/cluster_sky.py @@ -0,0 +1,84 @@ +"""Shared sky coordinates, family markers and intensity stretch for cluster figures.""" + +import numpy as np +from matplotlib.colors import AsinhNorm, to_hex + +from autoarray.plot.utils import _arcsec_labels, apply_extent, apply_labels + + +AMBER_ON_IMAGE = "#ffbc53" +AMBER_ON_WHITE = "#a15b0c" + +_FAMILY_ACCENTS = ((AMBER_ON_IMAGE, AMBER_ON_WHITE, "o"), ("#5fe3ee", "#00778a", "D")) + + +def family_style(record): + """Bright and dark colours and marker for one family on image and white backgrounds.""" + if record.k < len(_FAMILY_ACCENTS): + return _FAMILY_ACCENTS[record.k] + color = to_hex(record.color) + return color, color, record.marker + + +def indexed_family_style(family_index): + """Family accents for a single analysis with an explicit cluster family index.""" + if 0 <= family_index < len(_FAMILY_ACCENTS): + return _FAMILY_ACCENTS[family_index] + + from autolens.point.plot.point_sources import MARKERS, SOURCE_PALETTE + + color = SOURCE_PALETTE[family_index % len(SOURCE_PALETTE)] + return color, color, MARKERS[family_index % len(MARKERS)] + + +def draw_cluster_image(ax, image): + """Display the native raster with row zero at the largest y coordinate.""" + pixels = np.asarray(image.native) + finite = pixels[np.isfinite(pixels)] + high = max(float(np.percentile(finite, 99.95)), 1.0e-9) if finite.size else 1.0 + ax.imshow( + pixels, + origin="upper", + extent=image.geometry.extent, + cmap="gray", + norm=AsinhNorm(linear_width=high * 0.01, vmin=0, vmax=high), + ) + ax.set_facecolor("#23282d") + + +def cluster_field(extent, positions): + """A square sky field around the cutout centre, expanded to include the supplied positions.""" + xmin, xmax, ymin, ymax = extent + centre = np.array([(ymin + ymax) / 2, (xmin + xmax) / 2]) + half = max( + 0.375 * min(xmax - xmin, ymax - ymin), + 1.12 + * np.max( + np.abs(positions[np.isfinite(positions).all(axis=1)] - centre), initial=0 + ), + ) + return centre, half + + +def angular_axes(ax, centre, half_width, half_height=None, small=False): + """Keep angular pixels square and retain precision around the physical centre.""" + half_height = half_width if half_height is None else half_height + y, x = centre + extent = (x - half_width, x + half_width, y - half_height, y + half_height) + apply_labels(ax, is_subplot=True) + apply_extent(ax, extent) + for axis, value, radius in ((ax.xaxis, x, half_width), (ax.yaxis, y, half_height)): + ticks = value + radius * np.array([-0.75, 0, 0.75]) + digits = max(1, int(np.ceil(-np.log10(radius))) + 1) + labels = _arcsec_labels(np.round(ticks, digits)) + if len(set(labels)) < len(ticks): + # Very small fields far from zero exceed the shared formatter's six significant digits. + labels = [f"{t:.{digits}f}″".replace("-", "−") for t in ticks] + axis.set_ticks(ticks, labels) + ax.set_xlim(extent[:2]) + ax.set_ylim(extent[2:]) + ax.set_aspect("equal", adjustable="box") + ax.tick_params(labelsize=8 if small else 11) + ax.tick_params(axis="y", labelrotation=90) + for label in ax.get_yticklabels(): + label.set_verticalalignment("center") diff --git a/autolens/point/plot/family_fit_plots.py b/autolens/point/plot/family_fit_plots.py new file mode 100644 index 000000000..d2ac50b99 --- /dev/null +++ b/autolens/point/plot/family_fit_plots.py @@ -0,0 +1,413 @@ +"""Cluster position-fit diagnostics, one figure per multiply imaged source.""" + +from dataclasses import dataclass +from pathlib import Path +import re + +import numpy as np +from matplotlib import patheffects +from matplotlib.lines import Line2D +from matplotlib.patches import Ellipse + +from autoarray.plot.utils import save_figure +from autolens.point.plot.cluster_sky import ( + angular_axes, + cluster_field, + draw_cluster_image, + family_style, +) +from autolens.point.plot import point_sources as ps +from autolens.point.plot import positions_panel as pp +from autolens.point.plot.family_statistics import contribution_values +from autolens.point.plot.source_plane_panel import ( + SourcePlaneData, + ellipse_from, + source_plane_data_from, +) + + +@dataclass +class Family: + record: ps.SourceRecord + source: SourcePlaneData + terms: np.ndarray + penalty: float + statistic: str + data: np.ndarray + predictions: np.ndarray + footprints: np.ndarray # semi-major, semi-minor, angle in degrees + sky_color: object + ink: object + marker: str + + @classmethod + def from_record(cls, record, by_redshift=False): + source = source_plane_data_from(record.fit.positions, numbers=record.numbers) + terms, penalty, statistic = contribution_values(record) + if source.presentation.is_source_plane: + data = source.traced + predictions = np.broadcast_to(source.centre, data.shape) + if source.presentation.weighting == "jacobian": + footprints = [ + ellipse_from(c) or (np.nan,) * 3 for c in source.covariances + ] + else: + footprints = [(r, r, 0) for r in source.magnification_radii] + else: + data = record.observed + predictions = np.full(data.shape, np.nan) + paired = record.indexes >= 0 + predictions[paired] = record.model[record.indexes[paired]] + footprints = [(r, r, 0) for r in record.sigma] + return cls( + record, + source, + terms, + penalty, + statistic, + data, + predictions, + np.asarray(footprints).reshape(-1, 3), + *((record.color, record.color, record.marker) if by_redshift else family_style(record)), + ) + + @property + def ranked(self): + return np.lexsort((self.record.numbers, -self.terms)) + + @property + def total(self): + return self.terms.sum() + self.penalty + + +def _frame(ax, positions, aspect=1.0): + positions = np.asarray(positions) + finite = positions[np.isfinite(positions).all(axis=1)] + if not len(finite): + finite = np.zeros((1, 2)) + lo, hi = finite.min(axis=0), finite.max(axis=0) + height = max(hi[0] - lo[0], (hi[1] - lo[1]) / aspect, 0.001) * 0.67 + angular_axes(ax, (lo + hi) / 2, height * aspect, height) + + +def _numbers(ax, positions, numbers, colors): + valid = np.isfinite(positions).all(axis=1) + positions, numbers = positions[valid], numbers[valid] + colors = [c for c, keep in zip(colors, valid) if keep] + extent = [*ax.get_xlim(), *ax.get_ylim()] + width, height, scale = pp._panel_size_points(ax, extent) + markers = (positions[:, ::-1] - [extent[0], extent[2]]) * scale + labels = [str(n) for n in numbers] + offsets = pp.adjacent_number_placements_from( + markers, labels, width, height, fontsize=9 + ) + for (y, x), number, color, (dx, dy, ha, va) in zip( + positions, labels, colors, offsets + ): + label = ax.annotate( + number, + (x, y), + xytext=(dx, dy), + textcoords="offset points", + ha=ha, + va=va, + color=color, + size=9, + weight="bold", + ) + label.set_path_effects( + [patheffects.withStroke(linewidth=2, foreground=ax.get_facecolor())] + ) + + +def _overview(ax, families, family, image, indices): + if image is not None: + draw_cluster_image(ax, image) + positions = np.vstack([f.record.observed for f in families]) + if image is None: + _frame(ax, positions) + else: + centre, half = cluster_field(image.geometry.extent, positions) + angular_axes(ax, centre, half) + for other in families: + record = other.record + y, x = record.observed.T + color = other.sky_color if image is not None else other.ink + z = "" if record.redshift is None else f" z = {record.redshift:g}" + label = f"{record.name}{z} {other.statistic} = {other.total:.2f}" + handle = ax.scatter( + x, + y, + s=78, + marker=other.marker, + facecolors="none", + edgecolors=color, + linewidths=1.8, + label=label if len(families) <= 8 or family is other else "_nolegend_", + ) + if image is not None: + handle.set_path_effects( + [ + patheffects.Stroke(linewidth=3, foreground="#303038"), + patheffects.Normal(), + ] + ) + if other is family: + colors = np.full(len(y), "#9ba5ae", dtype=object) + colors[indices] = color + _numbers(ax, record.observed, record.numbers, colors) + ax.set_title("Cluster fit overview", weight="bold") + ax.legend( + loc="best", + fontsize=8, + framealpha=0.92, + facecolor="#30383f" if image is not None else "white", + labelcolor="white" if image is not None else "#172f49", + ) + + +def _ranking(ax, family, highlight): + order = family.ranked + values = family.terms[order].tolist() + labels = [f"Image {family.record.numbers[i]}" for i in order] + colors = [family.ink if i in highlight else "#c4cfd6" for i in order] + if family.penalty: + values.append(family.penalty) + colors.append("#718493") + labels.append("Unmatched models") + bars = ax.barh(np.arange(len(labels)), values, color=colors, height=0.62) + ax.bar_label(bars, fmt="%.2f", padding=4, fontsize=9) + ax.set_yticks(range(len(labels)), labels) + ax.invert_yaxis() + ax.margins(x=0.2) + ax.set_xlabel(family.statistic) + ax.set_title("Per-image contribution", weight="bold") + ax.grid(axis="x", alpha=0.2) + ax.set_axisbelow(True) + + +def _detail(ax, family, i): + y, x = family.data[i] + my, mx = family.predictions[i] + major, minor, angle = family.footprints[i] + if np.isfinite([major, minor, angle]).all(): + ax.add_patch( + Ellipse( + (x, y), + 2 * major, + 2 * minor, + angle=angle, + facecolor="none", + edgecolor=family.ink, + ls=":", + lw=1.4, + ) + ) + source = family.source.presentation.is_source_plane + ax.scatter( + x, + y, + marker=family.marker, + edgecolors=family.ink, + facecolors=family.ink if source else "none", + s=35, + zorder=3, + ) + if np.isfinite([my, mx]).all(): + ax.plot([x, mx], [y, my], color="#698090", lw=1) + ax.scatter( + mx, my, marker="+" if source else "x", color="#172f49", s=56, zorder=4 + ) + + +def _page(families, family, image, indices, page, pages, shared, title_prefix): + import matplotlib.pyplot as plt + + rec = family.record + source = family.source + plane = "Source" if source.presentation.is_source_plane else "Image" + # More ranking rows need extra space, including on subsequent pages. + height = 11.2 + max(0, len(rec.numbers) - 8) * 0.25 + fig = plt.figure(figsize=(16.2, height)) + title = f"{rec.name} / {plane}-plane fit" + fig.text( + 0.08, + 0.967, + f"{title_prefix} {title}" if title_prefix else title, + size=22, + weight="bold", + ) + subtitle = f"{len(rec.numbers)} images · total {family.statistic} = {family.total:.2f}" + if rec.redshift is not None: + subtitle = f"z = {rec.redshift:g} · {subtitle}" + fig.text(0.08, 0.927, subtitle, size=12) + if pages > 1: + fig.text(0.94, 0.969, f"Page {page} of {pages}", ha="right", size=14) + sky = fig.add_axes([0.085, 0.465, 0.383, 0.415]) + _overview(sky, families, family, image, indices) + highlight = indices if pages > 1 else family.ranked[:1] + bar = fig.add_axes([0.085, 0.095, 0.383, 0.23]) + _ranking(bar, family, highlight) + summary = fig.add_axes([0.55, 0.095, 0.383, 0.23]) + aspect = 0.383 * 16.2 / (0.23 * height) + _frame(summary, np.vstack([source.traced, source.centre]), aspect) + colors = np.full(len(rec.numbers), "#718493", dtype=object) + colors[highlight] = family.ink + summary.scatter(*source.traced.T[::-1], c=colors, s=28) + summary.scatter(*source.centre[::-1], marker="+", s=96, color="#172f49") + _numbers(summary, source.traced, rec.numbers, colors) + summary.set_title("All images in the source plane", weight="bold") + fig.text(0.55, 0.025, "+ fitted source centre", fontsize=10) + + radius = np.where(np.isfinite(family.footprints[:, 0]), family.footprints[:, 0], 0) + delta = np.abs(family.predictions - family.data) + half = ( + max( + np.max(np.where(np.isfinite(delta), delta, 0), initial=0), + np.max(radius, initial=0), + 0.0005, + ) + * 1.40 + ) + if shared: + ax = fig.add_axes([0.55, 0.475, 0.383, 0.36]) + _frame( + ax, + np.vstack( + [ + family.data - radius[:, None], + family.data + radius[:, None], + family.predictions, + ( + rec.model + if not source.presentation.is_source_plane + else source.traced + ), + ] + ), + ) + for i in indices: + _detail(ax, family, i) + if not source.presentation.is_source_plane and np.any(rec.unmatched): + unmatched = rec.model[rec.unmatched] + ax.scatter( + *unmatched.T[::-1], + marker="x", + color="#718493", + s=36, + label="Unpaired model", + ) + ax.legend(loc="best", fontsize=8) + _numbers(ax, family.data, rec.numbers, [family.ink] * len(indices)) + ax.set_title( + ( + "Source-plane detail" + if source.presentation.is_source_plane + else "All images in the image plane" + ), + weight="bold", + ) + else: + columns = min(3, len(rec.numbers)) + rows = (min(6, len(rec.numbers)) + columns - 1) // columns + grid = fig.add_gridspec( + rows, + columns, + left=0.54, + right=0.96, + bottom=0.475, + top=0.837, + wspace=0.5, + hspace=0.74, + ) + fig.text(0.54, 0.881, f"{plane}-plane detail by image", size=14, weight="bold") + for slot, i in enumerate(indices): + ax = fig.add_subplot(grid[slot // columns, slot % columns]) + if not np.isfinite(family.data[i]).all(): + ax.set_axis_off() + ax.text( + 0.5, + 0.5, + f"Image {rec.numbers[i]}\nPosition unavailable", + transform=ax.transAxes, + ha="center", + ) + continue + angular_axes(ax, family.data[i], half, small=True) + _detail(ax, family, i) + ax.set_title(f"Image {rec.numbers[i]}", size=10, weight="bold") + is_source = source.presentation.is_source_plane + keys = [ + Line2D( + [], + [], + ls="", + marker=family.marker, + color=family.ink, + mfc=family.ink if is_source else "none", + ), + Line2D([], [], ls="", marker="+" if is_source else "x", color="#172f49"), + Line2D([], [], ls=":", color=family.ink), + ] + model_label = "Nearest model (mixture)" if rec.mixture else "Paired model" + labels = ( + ["Back-traced image", "Source centre", "1σ source uncertainty"] + if is_source + else ["Observed", model_label, "1σ position error"] + ) + fig.legend( + keys, + labels, + loc="lower center", + bbox_to_anchor=(0.745, 0.383), + ncol=3, + frameon=False, + fontsize=9, + ) + return fig + + +def plot_family_fits( + fits, + image=None, + single_panel=False, + output_path=None, + output_format=None, + title_prefix=None, +): + """Write each family's fit.png and, for more than six zooms, fit_page_02.png etc.""" + records = ps.records_from_fits(fits) + colormap = ps.assign_styles(records) + families = [ + Family.from_record(record, by_redshift=colormap is not None) + for record in records if len(record.observed) + ] + used = set() + for family in families: + rec = family.record + name = str(rec.name) + if not re.fullmatch(r"[\w-]+", name) or name.casefold() in used: + name = f"family_{rec.k}" + while name.casefold() in used: + name += "_" + used.add(name.casefold()) + path = str(Path(output_path) / name) if output_path else None + order = np.argsort(rec.numbers) + pages = ( + [order] + if single_panel or len(order) <= 6 + else np.array_split(family.ranked, np.arange(6, len(order), 6)) + ) + for page, indices in enumerate(pages, 1): + fig = _page( + families, + family, + image, + indices, + page, + len(pages), + single_panel, + title_prefix, + ) + filename = "fit" if page == 1 else f"fit_page_{page:02}" + save_figure(fig, path=path, filename=filename, format=output_format) diff --git a/autolens/point/plot/family_statistics.py b/autolens/point/plot/family_statistics.py new file mode 100644 index 000000000..e9760be71 --- /dev/null +++ b/autolens/point/plot/family_statistics.py @@ -0,0 +1,47 @@ +"""Per-image position-fit contributions for family plots.""" + +import numpy as np +from scipy.special import logsumexp + +from autolens.point.fit.positions.image.pair_repeat import FitPositionsImagePairRepeat +from autolens.point.fit.positions.source.separations import FitPositionsSource + + +def contribution_values(record) -> tuple[np.ndarray, float, str]: + """Return observed-image terms, the extra predicted-image penalty and a label. + + Mixture terms use the fit's Gaussian density and equal component weights. + If the solver predicts no images, they use the fit's squared residual floor. + Source-plane terms are the fit's quadratic forms, before any likelihood + normalization or marginalization. + """ + positions_fit = record.fit.positions + + if record.mixture: + noise = np.asarray(positions_fit.noise_map) + model = np.asarray(record.model) + if len(model) == 0: + terms = (positions_fit.no_image_residual / noise) ** 2 + else: + observed = np.asarray(positions_fit.data) + log_components = positions_fit.log_p( + observed.T[:, :, None], model.T[:, None, :], noise[:, None] + ) + terms = -2.0 * (logsumexp(log_components, axis=1) - np.log(len(model))) + return np.asarray(terms), 0.0, "-2 log mixture" + + terms = np.asarray(positions_fit.chi_squared_map.array) + if isinstance(positions_fit, FitPositionsSource): + return terms, 0.0, "Source-plane χ²" + + penalty = 0.0 + if ( + isinstance(positions_fit, FitPositionsImagePairRepeat) + and positions_fit.unmatched_model_policy != "ignore" + and len(record.model) > 0 + ): + noise_mean = np.mean(np.asarray(positions_fit.noise_map)) + distances = np.asarray(positions_fit.unmatched_model_penalty_map) + penalty = float(np.sum((distances / noise_mean) ** 2)) + + return terms, penalty, "Image-plane χ²" diff --git a/autolens/point/plot/fit_point_plots.py b/autolens/point/plot/fit_point_plots.py index 3a8017747..2af4e0428 100644 --- a/autolens/point/plot/fit_point_plots.py +++ b/autolens/point/plot/fit_point_plots.py @@ -19,6 +19,7 @@ def subplot_fit( title_prefix: str = None, solver=None, curves=None, + family_index=None, ): """ Produce ``fit.png`` of a `FitPointDataset`: the "Fit Positions" panel of @@ -26,7 +27,7 @@ def subplot_fit( 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 + positions (outlined amber circles, σ 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 @@ -113,6 +114,7 @@ def subplot_fit( fit.tracer, title=f"{_prefix}Fit Positions ({fit.dataset.name})", colormap=colormap, + family_index=family_index, ) if has_fluxes: @@ -211,12 +213,13 @@ def plot_image_with_points( title_prefix: str = None, curves=None, solver=None, + family_index=None, ): """ Plot an observed image of a lensed point source (e.g. a quasar) with its point-source positions overlaid. 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 as outlined amber circles on the grayscale observed image, 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. @@ -257,4 +260,5 @@ def plot_image_with_points( title_prefix=title_prefix, image_plane_lines=image_plane_lines, image_plane_line_colors=image_plane_line_colors, + family_index=family_index, ) diff --git a/autolens/point/plot/multi_source_plots.py b/autolens/point/plot/multi_source_plots.py index aeb6f59f3..bfaadd29c 100644 --- a/autolens/point/plot/multi_source_plots.py +++ b/autolens/point/plot/multi_source_plots.py @@ -3,12 +3,13 @@ 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. + Cluster maps use an outlined marker for each family and label its images ``k·i`` (family ``k``, image ``i``). + The top legend gives each family’s image count and redshift when available. - ``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 + its colour. Cluster overviews frame the observed and model positions in the same square cutout. The legend + gives the fitted statistic of each source 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. @@ -19,7 +20,7 @@ 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`` + every source's positions in the same symbols as the sky map, ``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. @@ -32,6 +33,7 @@ from autoarray.plot.utils import save_figure, subplots +from autolens.point.plot.cluster_sky import AMBER_ON_IMAGE, AMBER_ON_WHITE from autolens.point.plot import positions_panel as pp from autolens.point.plot import point_sources as ps @@ -157,6 +159,8 @@ def place_labels( obstacles=None, fontsize: float = pp.FIT_NUMBER_FONTSIZE, marker_radius: float = 7.0, + label_colors=None, + halo_color=None, ): """ Labels every point, beside its own marker when a free spot exists, otherwise pushed further out with a thin @@ -229,7 +233,7 @@ def place_labels( for i, ((c, ring), text) in enumerate(zip(results, labels)): y, x = points[i] dx, dy = c - markers[i] - ax.annotate( + annotation = ax.annotate( text, (x, y), xytext=(dx, dy), @@ -238,15 +242,19 @@ def place_labels( va="center", fontsize=fontsize, weight="bold", - color="k", + color=label_colors[i] if label_colors is not None else "k", zorder=10, - bbox=LABEL_BBOX, + bbox=LABEL_BBOX if halo_color is None else None, arrowprops=( dict(arrowstyle="-", color="0.45", lw=0.6, shrinkA=0, shrinkB=3) if ring > 0 else None ), ) + if halo_color is not None: + from matplotlib import patheffects + + annotation.set_path_effects([patheffects.withStroke(linewidth=2.5, foreground=halo_color)]) def label_records(ax, extent, records, extra_points=(), extra_labels=(), obstacles=None): @@ -285,7 +293,29 @@ def legend_location_from(extent, points) -> str: # --------------------------------------------------------------------------- -def scatter_sources(ax, records, edgecolor="k", edgewidth=0.6): +def scatter_sources(ax, records, edgecolor=None, edgewidth=None, *, on_image=False): + if len(records) == 1: + record = records[0] + if edgecolor is None: + edgecolor = AMBER_ON_IMAGE if on_image else AMBER_ON_WHITE + observed = ax.scatter( + *record.observed.T[::-1], + s=marker_size_from("o"), + marker="o", + facecolors="none", + edgecolors=edgecolor, + linewidths=1.8 if edgewidth is None else edgewidth, + zorder=5, + label="Observed", + ) + if on_image: + from matplotlib import patheffects + + observed.set_path_effects( + [patheffects.withStroke(linewidth=3, foreground="#303038")] + ) + return + for record in records: if len(record.observed) == 0: continue @@ -295,8 +325,8 @@ def scatter_sources(ax, records, edgecolor="k", edgewidth=0.6): s=marker_size_from(record.marker), c=[record.color], marker=record.marker, - edgecolors=edgecolor, - linewidths=edgewidth, + edgecolors="k" if edgecolor is None else edgecolor, + linewidths=0.6 if edgewidth is None else edgewidth, zorder=5, label="Observed", ) @@ -423,14 +453,17 @@ def merit_label_from(records) -> Optional[str]: 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 "χ²" + kinds = {r.mixture for r in records if r.chi_squared is not None} + if len(kinds) > 1: + return None + name = "−2 ln L" if True in kinds 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 = …, σ = …)``. + report the family's redshift and fitted statistic, or its positional noise for dataset figures. """ from matplotlib.lines import Line2D @@ -439,6 +472,12 @@ def observed_handles(records, edgecolor="k"): handles = [] for record in records: z = f"z = {record.redshift:g}, " if record.redshift is not None else "" + value = pp.sigma_label_from(record.sigma) + if record.chi_squared is not None: + from autolens.point.plot import source_plane_panel as spp + + statistic = _cluster_statistic(record) + value = f"{statistic} = {spp._format_chi_squared(record.chi_squared)}" handles.append( Line2D( [], @@ -449,26 +488,27 @@ def observed_handles(records, edgecolor="k"): markeredgecolor=edgecolor, markeredgewidth=0.6, markersize=9, - label=f"{record.name} ({z}{sigma_text})", + label=f"{record.name} ({z}{value})", ) ) return handles - face = "k" if len(records) == 1 else "0.6" + single = len(records) == 1 return [ Line2D( [], [], linestyle="none", marker="o", - markerfacecolor=face, - markeredgecolor=edgecolor, + markerfacecolor="none" if single else "0.6", + markeredgecolor=AMBER_ON_WHITE if single else edgecolor, + markeredgewidth=1.8 if single else 1.0, markersize=9, label=f"Observed ({sigma_text})", ) ] -def fit_handles(records, model_size, has_curves: bool, has_mass_centres: bool): +def fit_handles(records, model_size, has_curves: bool, has_mass_centres: bool, curve_label=None): from matplotlib.lines import Line2D first = records[0] @@ -532,7 +572,7 @@ def fit_handles(records, model_size, has_curves: bool, has_mass_centres: bool): [], color=CURVE_COLOR if not multi else "0.35", linewidth=CURVE_LINEWIDTH, - label="Critical curve (each source's z)" if multi else "Critical curve", + label=curve_label or ("Critical curve (each source's z)" if multi else "Critical curve"), ) ) if has_mass_centres: @@ -569,11 +609,11 @@ def add_colourbar(fig, ax, colormap, records, scale: float = 1.0): 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) + by_redshift = all(r.redshift is not None and np.isfinite(r.redshift) for r in records) + colorbar.set_label("source redshift" if by_redshift else "family index", 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) + cax.axhline(record.redshift if by_redshift else record.k, color="k", linewidth=0.5, alpha=0.6) return cax @@ -593,17 +633,45 @@ def _curve_points(records, curves) -> np.ndarray: # --------------------------------------------------------------------------- -def draw_dataset_positions(ax, records, extent, title: str, scale: float = 1.0): +def draw_dataset_positions( + ax, records, extent, title: str, scale: float = 1.0, family_index=None +): """ Draws the "Dataset Positions" panel of ``records`` on ``ax`` (styles must be assigned). """ - scatter_sources(ax, records) + if family_index is None: + scatter_sources(ax, records) + handles = observed_handles(records) + else: + from autolens.point.plot.cluster_sky import indexed_family_style + + record = records[0] + _, record.color, record.marker = indexed_family_style(family_index) + ax.scatter( + *record.observed.T[::-1], + marker=record.marker, + facecolors="none", + edgecolors=[record.color], + linewidths=1.8, + s=85, + ) + handles = [_cluster_family_handle(record, record.color, False)] draw_noise_circles(ax, records) finish_panel(ax, title, extent, scale) - label_records(ax, extent, records) + if family_index is None: + label_records(ax, extent, records) + else: + place_labels( + ax, + extent, + record.observed, + [f"{family_index}·{n}" for n in record.numbers], + label_colors=[record.color] * len(record.numbers), + halo_color="white", + ) observed = np.vstack([r.observed for r in records]) ax.legend( - handles=observed_handles(records), + handles=handles, loc=legend_location_from(extent, observed) if len(records) == 1 else "best", fontsize=LEGEND_KWARGS["fontsize"] * scale, framealpha=LEGEND_KWARGS["framealpha"], @@ -624,13 +692,14 @@ def plot_dataset_positions( output_format: str = None, filename: str = "dataset_point", title_prefix: str = None, + image_extent=None, + family_index=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. + Cluster families use outlined markers and family·image labels on the same sky field as the image + overlay when an image extent is supplied. A standalone point dataset uses its own image numbers. """ datasets = list(datasets) @@ -638,15 +707,24 @@ def plot_dataset_positions( 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)) + if len(records) > 1 or family_index is not None: + fig = _cluster_overview( + records, + {}, + image_extent if image_extent is not None else extent, + colormap, + title_prefix, + family_index=family_index, + ) + else: + 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), + ) save_figure(fig, path=output_path, filename=filename, format=output_format) @@ -665,6 +743,7 @@ def draw_fit_positions( scale: float = 1.0, legend: str = "inside", colormap=None, + family_index=None, ): """ Draws the "Fit Positions" panel of ``records`` (with fits) on ``ax``; ``legend`` is ``"inside"`` (the emptiest @@ -680,7 +759,22 @@ def draw_fit_positions( pp.plot_mass_centres( ax, tracer, size=70 if not many else 50, linewidths=1.4 ) - scatter_sources(ax, records) + if family_index is None: + scatter_sources(ax, records) + else: + from autolens.point.plot.cluster_sky import indexed_family_style + + _, family_color, family_marker = indexed_family_style(family_index) + (record,) = records + ax.scatter( + *record.observed.T[::-1], + s=marker_size_from(family_marker), + marker=family_marker, + facecolors="none", + edgecolors=family_color, + linewidths=1.8, + zorder=5, + ) draw_noise_circles(ax, records) draw_model_and_residuals(ax, records, model_size) finish_panel(ax, title, extent, scale) @@ -692,7 +786,20 @@ def draw_fit_positions( 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) + if family_index is None: + label_records(ax, extent, records, extra_points, extra_labels, obstacles=obstacles) + else: + labels = [f"{family_index}·{n}" for n in [*record.numbers, *extra_labels]] + place_labels( + ax, + extent, + [*record.observed, *extra_points], + labels, + obstacles=obstacles, + fontsize=label_fontsize_from(records), + label_colors=[family_color] * len(labels), + halo_color="white", + ) handles = observed_handles(records) + fit_handles( records, @@ -700,6 +807,11 @@ def draw_fit_positions( has_curves=bool(_curve_points(records, curves).size), has_mass_centres=bool(len(mass_centres)), ) + if family_index is not None: + handles[0].set_marker(family_marker) + handles[0].set_markerfacecolor("none") + handles[0].set_markeredgecolor(family_color) + handles[0].set_markeredgewidth(1.8) kwargs = dict( fontsize=LEGEND_KWARGS["fontsize"] * scale, framealpha=LEGEND_KWARGS["framealpha"], @@ -722,6 +834,263 @@ def draw_fit_positions( ax.legend(handles=handles, loc=legend_location_from(extent, drawn), **kwargs) +def _cluster_curves(ax, records, curves, on_image, fallback_lines): + """Return the curve key for the curves actually drawn on this map.""" + has_curves = False + for r in records: + own = r.curves_from(curves) + if own is None and curves: + own = curves.get(("source", r.k)) + if own is not None: + for line in own.tangential: + ax.plot( + line[:, 1], line[:, 0], color=r.color, lw=0.95, alpha=0.8, zorder=2 + ) + has_curves = True + if not on_image and not is_many(records): + for line in own.radial: + ax.plot( + line[:, 1], + line[:, 0], + color=r.color, + lw=0.85, + ls=":", + alpha=0.8, + zorder=2, + ) + has_curves = True + if has_curves: + return "Critical curve (each source's z)" + if fallback_lines is not None and len(fallback_lines): + for line in fallback_lines: + line = np.asarray(line) + ax.plot(line[:, 1], line[:, 0], color="white", lw=0.95, zorder=2) + return "Critical curve (last source plane)" + return None + + +def _cluster_statistic(record): + from autolens.point.plot import source_plane_panel as spp + + if record.mixture: + return "−2 ln L" + plane = spp.presentation_from(record.fit.positions) + return "Source-plane χ²" if plane.is_source_plane else "Image-plane χ²" + + +def _cluster_family_handle(record, ink, compact, mixed_statistics=False): + from matplotlib.lines import Line2D + from autolens.point.plot import source_plane_panel as spp + + details = [] + equals = "=" if compact else " = " + if record.redshift is not None: + details.append(f"z{equals}{record.redshift:g}") + if record.chi_squared is not None: + statistic = _cluster_statistic(record) + if compact and not record.mixture and not mixed_statistics: + statistic = "χ²" + details.append( + f"{statistic}{equals}{spp._format_chi_squared(record.chi_squared)}" + ) + else: + count = len(record.observed) + details.append(f"{count} image" if count == 1 else f"{count} images") + if not compact and record.fit is None: + details.append(pp.sigma_label_from(record.sigma)) + label = ( + f"{record.name} " + " ".join(details) + if compact + else f"{record.name} ({', '.join(details)})" + ) + return Line2D( + [], + [], + linestyle="none", + marker=record.marker, + markersize=8, + markerfacecolor="none", + markeredgecolor=ink, + markeredgewidth=1.8, + label=label, + ) + + +def _cluster_overview( + records, + curves, + field_extent, + colormap, + title_prefix, + image=None, + fallback_lines=None, + family_index=None, +): + """Draw a cluster dataset or fit on one shared sky field, with family and symbol keys outside the data.""" + from matplotlib import patheffects + from autolens.point.plot.cluster_sky import ( + angular_axes, + cluster_field, + draw_cluster_image, + family_style, + indexed_family_style, + ) + + on_image = image is not None + is_fit = records[0].fit is not None + many = is_many(records) + models = [r.model for r in records if r.has_model] + centre, half = cluster_field( + field_extent, np.vstack([r.observed for r in records] + models) + ) + # Leave one line per family above the map, and space below it for the fit symbols. + statistics = {_cluster_statistic(r) for r in records if r.chi_squared is not None} + mixed_statistics = len(statistics) > 1 + family_columns = 1 + if len(records) > 4: + family_columns = 4 if many and not mixed_statistics else 2 + family_rows = (len(records) + family_columns - 1) // family_columns + side = 9.0 if many else 6.8 + header = 0.52 + 0.25 * family_rows + (0.24 if many else 0) + footer = 1.05 if is_fit else 0.58 + height = side + header + footer + width = side + (1.75 if many else 0.9) + fig, ax = subplots(figsize=(width, height)) + fig.subplots_adjust( + left=0.57 / width, + right=(0.57 + side) / width, + top=(footer + side) / height, + bottom=footer / height, + ) + if on_image: + draw_cluster_image(ax, image) + angular_axes(ax, centre, half) + extent = [*ax.get_xlim(), *ax.get_ylim()] + title = "Cluster fit on the observed image" if on_image else "Cluster fit overview" + if not is_fit: + title = ( + "Cluster positions on the observed image" + if on_image + else "Cluster dataset overview" + ) + ax.set_title( + f"{_prefix(title_prefix)}{title}", + x=0, + ha="left", + y=1 + (0.23 * family_rows + 0.17 + (0.12 if many else 0)) / side, + fontsize=19, + weight="bold", + color="#172f49", + ) + points, labels, colors, handles = [], [], [], [] + for r in records: + if many: + ink = r.color + else: + bright, ink, r.marker = ( + family_style(r) + if family_index is None + else indexed_family_style(family_index) + ) + r.color = bright if on_image else ink + label_index = r.k if family_index is None else family_index + handles.append(_cluster_family_handle(r, ink, many, mixed_statistics)) + observed = ax.scatter( + *r.observed.T[::-1], + s=marker_size_from(r.marker, base=85), + marker=r.marker, + facecolors="none", + edgecolors=[r.color], + linewidths=1.8, + label="Observed", + zorder=5, + ) + if on_image: + observed.set_path_effects( + [patheffects.withStroke(linewidth=3, foreground="#303038")] + ) + points.extend(r.observed) + labels.extend(f"{label_index}·{n}" for n in r.numbers) + colors.extend([r.color] * len(r.numbers)) + points.extend(r.model[r.unmatched]) + labels.extend(f"{label_index}·{letter}" for letter in r.unmatched_labels) + colors.extend([r.color] * len(r.unmatched_labels)) + curve_key = ( + _cluster_curves(ax, records, curves, on_image, fallback_lines) + if is_fit + else None + ) + + centres = np.empty((0, 2)) + if is_fit and not on_image: + tracer = records[0].fit.tracer + centres = pp.mass_centres_from(tracer) + pp.plot_mass_centres(ax, tracer, size=40, linewidths=1) + if not on_image: + draw_noise_circles(ax, records) + size = model_size_from(records) + draw_model_and_residuals( + ax, records, size, unmatched_color=".80" if on_image else pp.UNMATCHED_COLOR + ) + place_labels( + ax, + extent, + points, + labels, + obstacles=np.vstack([centres] + models), + fontsize=9 if many else 10, + label_colors=( + ["white" if on_image else "#172f49"] * len(labels) if many else colors + ), + halo_color="#23282d" if on_image else "white", + ) + + legend_title = None + highlight = None + if many: + image_count = sum(len(r.observed) for r in records) + legend_title = f"{len(records)} families · {image_count} observed images" + if len(statistics) == 1: + legend_title = f"{next(iter(statistics))} · {legend_title}" + finite = [ + i for i, r in enumerate(records) + if r.chi_squared is not None and np.isfinite(r.chi_squared) + ] + if finite: + highlight = max(finite, key=lambda i: records[i].chi_squared) + legend = ax.legend( + handles=handles, + loc="lower left", + bbox_to_anchor=(0, 1.006, 1, 0), + mode="expand" if many else None, + title=legend_title, + alignment="left", + frameon=False, + borderaxespad=0, + fontsize=9 if many else 10, + handletextpad=0.4 if many else 0.8, + handlelength=1.25, + ncol=family_columns, + ) + if highlight is not None: + legend.get_texts()[highlight].set_weight("bold") + if is_fit: + symbols = fit_handles( + records, size, bool(curve_key), bool(len(centres)), curve_label=curve_key + ) + fig.legend( + handles=symbols, + loc="upper center", + bbox_to_anchor=((0.57 + side / 2) / width, (footer - 0.33) / height), + ncol=min(3, len(symbols)) or 1, + fontsize=9, + frameon=False, + columnspacing=1.4, + ) + add_colourbar(fig, ax, colormap, records, 0.65) + return fig + + def plot_fit_positions( fits, solver=None, @@ -730,11 +1099,13 @@ def plot_fit_positions( output_format: str = None, filename: str = "fit", title_prefix: str = None, + image_extent=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``. + For a cluster, pass ``image_extent`` to match the image-backed overview's sky field. """ fits = list(fits) @@ -746,19 +1117,24 @@ def plot_fit_positions( 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)) + if len(records) > 1: + fig = _cluster_overview( + records, + curves, + image_extent if image_extent is not None else extent, + colormap, + title_prefix, + ) + else: + fig, ax = subplots(1, 1, figsize=figsize_from(records)) + draw_fit_positions( + ax, + records, + curves, + extent, + tracer, + title=f"{_prefix(title_prefix)}Fit Positions", + ) save_figure(fig, path=output_path, filename=filename, format=output_format) @@ -784,7 +1160,9 @@ def _format_sigma(value: float) -> str: return f"{value:.1f}σ" if value >= 1 else f"{value:.2f}σ" -def draw_ranking_panel(ax, record, scales: ps.RankingScales, title: str): +def draw_ranking_panel( + ax, record, scales: ps.RankingScales, title: str, family_index=None +): """ 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 @@ -792,6 +1170,11 @@ def draw_ranking_panel(ax, record, scales: ps.RankingScales, title: str): """ from autoarray.plot.utils import apply_labels + family_color, family_marker = None, "o" + if family_index is not None: + from autolens.point.plot.cluster_sky import indexed_family_style + + _, family_color, family_marker = indexed_family_style(family_index) xmax, n_slots = scales.xmax, scales.n_slots rows = ps.ranking_rows_from(record) right = 1.32 * xmax @@ -813,13 +1196,22 @@ def draw_ranking_panel(ax, record, scales: ps.RankingScales, title: str): continue if not np.isfinite(value): continue - color = ps.image_color(record.numbers[i]) + color = family_color or 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) + ax.scatter( + x, + y, + s=120, + c=[color], + marker=family_marker, + edgecolors="k", + linewidths=0.6, + zorder=4, + ) if kind == "nomodel": ax.scatter(x, y, zorder=3, **{**NO_MODEL_RING, "s": 380}) ax.text( @@ -836,7 +1228,10 @@ def draw_ranking_panel(ax, record, scales: ps.RankingScales, title: str): 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)) + labels = [t[1] for t in rows] + if family_index is not None: + labels = [f"{family_index}·{label}" for label in labels] + labels += [""] * (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) @@ -847,7 +1242,7 @@ def draw_ranking_panel(ax, record, scales: ps.RankingScales, title: str): ax.set_box_aspect(1) -def draw_image_plane_panel(ax, record, curves, tracer, title: str): +def draw_image_plane_panel(ax, record, curves, tracer, title: str, family_index=None): """ 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 @@ -869,16 +1264,20 @@ def draw_image_plane_panel(ax, record, curves, tracer, title: str): ) 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, - ) + if family_index is None: + marker_style = dict( + c=[ps.image_color(n) for n in record.numbers], + edgecolors="k", + linewidths=0.6, + ) + else: + from autolens.point.plot.cluster_sky import indexed_family_style + + _, color, marker = indexed_family_style(family_index) + marker_style = dict( + marker=marker, facecolors="none", edgecolors=color, linewidths=1.8 + ) + ax.scatter(*record.observed.T[::-1], s=MARKER_SIZE, zorder=5, **marker_style) draw_noise_circles(ax, [record]) draw_model_and_residuals(ax, [record]) finish_panel(ax, title, extent) @@ -887,6 +1286,8 @@ def draw_image_plane_panel(ax, record, curves, tracer, title: str): if np.any(record.unmatched): points += list(record.model[record.unmatched]) labels += record.unmatched_labels + if family_index is not None: + labels = [f"{family_index}·{label}" for label in labels] place_labels( ax, extent, @@ -894,13 +1295,24 @@ def draw_image_plane_panel(ax, record, curves, tracer, title: str): labels, obstacles=record.model if record.has_model else None, fontsize=pp.FIT_NUMBER_FONTSIZE, + label_colors=None if family_index is None else [color] * len(labels), + halo_color=None if family_index is None else "white", ) -def draw_source_plane_panel(ax, record, curves, title: str): +def draw_source_plane_panel(ax, record, curves, title: str, family_index=None): from autolens.point.plot import source_plane_panel as spp - data = spp.source_plane_data_from(record.fit.positions, numbers=record.numbers) + numbers = record.numbers + colors = [ps.image_color(n) for n in numbers] + marker = "o" + if family_index is not None: + from autolens.point.plot.cluster_sky import indexed_family_style + + _, color, marker = indexed_family_style(family_index) + colors = [color] * len(numbers) + numbers = [f"{family_index}·{n}" for n in numbers] + data = spp.source_plane_data_from(record.fit.positions, numbers=numbers) plane_curves = record.curves_from(curves) spp.plot_source_plane_panel( ax, @@ -908,7 +1320,8 @@ def draw_source_plane_panel(ax, record, curves, title: str): 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], + point_colors=colors, + point_marker=marker, legend=False, ) @@ -929,7 +1342,9 @@ def _shrink_titles_to_fit(fig, axes): title.set_fontsize(title.get_fontsize() - 1) -def _fit_per_image_figure(records, curves, tracer, scales, title_prefix=None): +def _fit_per_image_figure( + records, curves, tracer, scales, title_prefix=None, family_index=None +): from autoarray.plot.utils import conf_subplot_figsize n = len(records) @@ -937,10 +1352,29 @@ def _fit_per_image_figure(records, curves, tracer, scales, title_prefix=None): 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}") + draw_ranking_panel( + axes[row, 0], + record, + scales, + title=f"{prefix}Residuals {tag}", + family_index=family_index, + ) + draw_image_plane_panel( + axes[row, 1], + record, + curves, + tracer, + title=f"{prefix}IP {tag}", + family_index=family_index, + ) try: - draw_source_plane_panel(axes[row, 2], record, curves, title=f"{prefix}SP {tag}") + draw_source_plane_panel( + axes[row, 2], + record, + curves, + title=f"{prefix}SP {tag}", + family_index=family_index, + ) except Exception: logger.warning( "The source-plane panel of fit_per_image.png could not be drawn; it is left empty.", @@ -965,6 +1399,7 @@ def subplot_fit_per_image( filename: str = "fit_per_image", title_prefix: str = None, scales: Optional[ps.RankingScales] = None, + family_index=None, ): """ Plots ``fit_per_image.png``: one row per source of "Residuals", "IP" and "SP" panels (see the module docstring). @@ -986,7 +1421,9 @@ def subplot_fit_per_image( ) if not is_many(records): - fig = _fit_per_image_figure(records, curves, tracer, scales, title_prefix) + fig = _fit_per_image_figure( + records, curves, tracer, scales, title_prefix, family_index + ) save_figure(fig, path=output_path, filename=filename, format=output_format) return @@ -1032,15 +1469,16 @@ def plot_image_with_points( title_prefix: str = None, image_plane_lines=None, image_plane_line_colors=None, + family_index=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, 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. + added (``fit_image_with_points.png``, so both figures coexist). Cluster overviews use a grayscale asinh + stretch and an external legend for every family. + Standalone images use the point-source intensity scale. ``image_plane_lines`` (pre-computed last-plane curves) are drawn only when ``curves`` cannot be computed. """ @@ -1053,7 +1491,7 @@ def plot_image_with_points( records = ps.records_from_fits(fits) else: records = ps.records_from_datasets(list(datasets)) - ps.assign_styles(records) + colormap = ps.assign_styles(records) multi = len(records) > 1 many = is_many(records) scale = font_scale_from(records) @@ -1064,11 +1502,32 @@ def plot_image_with_points( fits, records, ps.union_extent_from(records, solver=solver) ) + if multi or family_index is not None: + fig = _cluster_overview( + records, + curves, + image.geometry.extent, + colormap, + title_prefix, + image=image, + fallback_lines=image_plane_lines, + family_index=family_index, + ) + save_figure( + fig, + path=output_path, + filename="fit_image_with_points" if is_fit else "image_with_points", + format=output_format, + ) + return + 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=use_log10_from(image, multi), title=title) + plot_array( + array=image, ax=ax, colormap="gray", 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(): @@ -1123,7 +1582,7 @@ def _yx(grid): 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) + scatter_sources(ax, shown, on_image=True) if is_fit: draw_model_and_residuals(ax, shown, model_size_from(records), unmatched_color="0.85") diff --git a/autolens/point/plot/point_dataset_plots.py b/autolens/point/plot/point_dataset_plots.py index d82296a37..acd0e78ec 100644 --- a/autolens/point/plot/point_dataset_plots.py +++ b/autolens/point/plot/point_dataset_plots.py @@ -10,6 +10,7 @@ def subplot_dataset( output_format: str = None, title_prefix: str = None, solver=None, + family_index=None, ): """ Produce a subplot visualising a `PointDataset`. @@ -18,7 +19,7 @@ def subplot_dataset( measurements are present: * **Positions panel** (always shown), titled ``Dataset Positions ()``: - the observed point-source positions as large filled markers, each with a + the observed point-source positions as outlined amber circles, each with a circle at its noise-map radius (never inflated, so it may be sub-pixel) and the sigma stated in the legend, e.g. ``Observed (σ = 0.005″)``. The panel extent is the ``PointSolver`` grid extent when ``solver`` is given @@ -58,6 +59,7 @@ def subplot_dataset( output_format=output_format, filename="dataset_point", title_prefix=title_prefix, + family_index=family_index, ) return @@ -69,7 +71,11 @@ def subplot_dataset( axes_flat = list(np.array(axes).flatten()) msp.draw_dataset_positions( - axes_flat[0], records, extent, title=msp.dataset_title_from(records, title_prefix) + axes_flat[0], + records, + extent, + title=msp.dataset_title_from(records, title_prefix), + family_index=family_index, ) _prefix = f"{title_prefix.rstrip()} " if title_prefix else "" diff --git a/autolens/point/plot/point_solver_plots.py b/autolens/point/plot/point_solver_plots.py index 64143c856..5d25ae406 100644 --- a/autolens/point/plot/point_solver_plots.py +++ b/autolens/point/plot/point_solver_plots.py @@ -48,6 +48,8 @@ import numpy as np +from autolens.point.plot.cluster_sky import AMBER_ON_WHITE + from autolens.point.plot.positions_panel import ( CRITICAL_CURVE_COLOR_MAP, CRITICAL_CURVE_LINEWIDTH, @@ -66,7 +68,7 @@ UP_SAMPLED_COLOR = "#2e9e5b" CRITICAL_CURVE_COLOR = CRITICAL_CURVE_COLOR_MAP["white"] RADIAL_CRITICAL_CURVE_COLOR = CRITICAL_CURVE_COLOR_MAP["yellow"] -OBSERVED_COLOR = "k" +OBSERVED_COLOR = AMBER_ON_WHITE SOLVED_COLOR = "r" REJECTED_LABEL_COLOR = UNMATCHED_COLOR @@ -695,6 +697,16 @@ def _annotate_images(ax, data: PointSolverFigureData, panel_inches: float): ) +def _observed_style(family_index): + if family_index is None: + return OBSERVED_COLOR, "o" + + from autolens.point.plot.cluster_sky import indexed_family_style + + _, color, marker = indexed_family_style(family_index) + return color, marker + + def draw_point_solver_panel( ax, step, @@ -704,6 +716,7 @@ def draw_point_solver_panel( tick_fontsize: float = 10, title_fontsize: float = 12, annotation_fontsize: float = 10, + family_index=None, ) -> bool: """ Draws one refinement step on ``ax``: the panel shared by the 2x2 still and every animation frame. @@ -821,12 +834,14 @@ def draw_point_solver_panel( ) if data.positions is not None and len(data.positions): + observed_color, observed_marker = _observed_style(family_index) ax.scatter( data.positions[:, 1], data.positions[:, 0], s=60, facecolors="none", - edgecolors=OBSERVED_COLOR, + edgecolors=observed_color, + marker=observed_marker, linewidths=1.3, zorder=7, ) @@ -855,7 +870,9 @@ def draw_point_solver_panel( return as_markers -def legend_handles_from(data: PointSolverFigureData, marked: bool) -> list: +def legend_handles_from( + data: PointSolverFigureData, marked: bool, family_index=None +) -> list: """ Returns the legend handles shared by the still and the animation; the ``Kept (too small to draw)`` entry is included only when a panel drew its kept triangles as centroid markers. @@ -910,14 +927,15 @@ def legend_handles_from(data: PointSolverFigureData, marked: bool) -> list: ) ) if data.positions is not None and len(data.positions): + observed_color, observed_marker = _observed_style(family_index) handles.append( Line2D( [], [], - marker="o", + marker=observed_marker, ls="", mfc="none", - mec=OBSERVED_COLOR, + mec=observed_color, label="Observed", ) ) @@ -954,7 +972,9 @@ def _resolve_format(output_format) -> str: return output_format -def _save_animation(data, output_path, filename, title_prefix, dpi=100): +def _save_animation( + data, output_path, filename, title_prefix, dpi=100, family_index=None +): import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation, PillowWriter @@ -965,7 +985,7 @@ def _save_animation(data, output_path, filename, title_prefix, dpi=100): marked = any(is_too_small_to_draw(s, data, panel_inches) for s in data.steps) fig.legend( - handles=legend_handles_from(data, marked), + handles=legend_handles_from(data, marked, family_index=family_index), loc="lower center", ncol=3, fontsize=8.5, @@ -986,6 +1006,7 @@ def update(frame): panel_inches=panel_inches, title=prefix + panel_title_from(step, data, short=True), tick_fontsize=9, + family_index=family_index, ) animation = FuncAnimation(fig, update, frames=frames) @@ -1018,6 +1039,7 @@ def plot_point_solver( title_prefix: str = None, animate: bool = False, filename: str = "point_solver", + family_index=None, ): """ Plot how the ``PointSolver`` refines its triangle tiling to find the multiple images of a point source. @@ -1061,6 +1083,8 @@ def plot_point_solver( If ``True`` write the GIF animation instead of the still. filename The file name (without extension) of the output. + family_index + The zero-based cluster family index, if any. It styles the observed positions and their legend key. """ data = point_solver_data_from( solver=solver, @@ -1077,6 +1101,7 @@ def plot_point_solver( title_prefix=title_prefix, animate=animate, filename=filename, + family_index=family_index, ) @@ -1087,6 +1112,7 @@ def plot_point_solver_from_data( title_prefix: str = None, animate: bool = False, filename: str = "point_solver", + family_index=None, ): """ Draws the point-solver still or animation from data already collected by :func:`point_solver_data_from`, so @@ -1100,6 +1126,7 @@ def plot_point_solver_from_data( output_path=None if output_path is None else str(output_path), filename=filename, title_prefix=title_prefix, + family_index=family_index, ) n = len(data.steps) @@ -1120,11 +1147,12 @@ def plot_point_solver_from_data( data, panel_inches=panel_inches, title=prefix + panel_title_from(step, data), + family_index=family_index, ) hide_unused_axes(axes_flat[n:]) fig.legend( - handles=legend_handles_from(data, marked), + handles=legend_handles_from(data, marked, family_index=family_index), loc="lower center", ncol=5, fontsize=10.5, diff --git a/autolens/point/plot/point_sources.py b/autolens/point/plot/point_sources.py index 3b3647afb..59dc2b1a3 100644 --- a/autolens/point/plot/point_sources.py +++ b/autolens/point/plot/point_sources.py @@ -12,7 +12,7 @@ - :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 +- :func:`assign_styles`: the colour and marker of every source. Source 0 has a black base colour (overridden by the observed-position style); 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. diff --git a/autolens/point/plot/positions_panel.py b/autolens/point/plot/positions_panel.py index 8ae2cb075..4c8b1b80b 100644 --- a/autolens/point/plot/positions_panel.py +++ b/autolens/point/plot/positions_panel.py @@ -7,7 +7,7 @@ which the model can find images. Without a solver it falls back to the critical-curve region of :func:`~autolens.lens.plot.critical_curves.critical_curve_grid_from` (a square of twice the half-span of the positions, plus a buffer), which contains every position. -- **Markers.** Large filled markers for the observed positions, with a circle of radius equal to each position's +- **Markers.** Outlined amber circles for the observed positions, with a circle of radius equal to each position's noise-map value (one isotropic sigma per position) and the sigma always stated in the legend. The circle is drawn at its true radius and is never inflated, so at high-resolution noise and a large solver extent it is sub-pixel. - **No axis labels**, so the arc-second tick labels are not overlapped. @@ -31,7 +31,7 @@ MASS_CENTRE_COLOR = "tab:green" # The model cross is thinner and smaller than the observed marker (``s=110``), so under an exact fit the observed -# dot stays visible around it rather than being hidden. +# outline stays visible around it rather than being hidden. MODEL_MARKER_SIZE = 60 MODEL_MARKER_LINEWIDTH = 1.2 @@ -155,10 +155,11 @@ def sigma_label_from(noise_map) -> str: def plot_observed_positions(ax, positions, noise_map): """ - Draws the observed positions as large filled markers, each with a circle of radius equal to its noise-map + Draws the observed positions as outlined amber circles, each with a circle of radius equal to its noise-map value (never inflated), labelled ``Observed (σ = ...)`` in the legend. """ from matplotlib.patches import Circle + from autolens.point.plot.cluster_sky import AMBER_ON_WHITE positions = _np_grid(positions) noise = np.broadcast_to( @@ -172,7 +173,9 @@ def plot_observed_positions(ax, positions, noise_map): positions[:, 1], positions[:, 0], s=110, - c=OBSERVED_COLOR, + facecolors="none", + edgecolors=AMBER_ON_WHITE, + linewidths=1.8, marker="o", zorder=4, label=f"Observed ({sigma_label_from(noise_map)})", diff --git a/autolens/point/plot/source_plane_panel.py b/autolens/point/plot/source_plane_panel.py index 54689fc7c..459eea9ef 100644 --- a/autolens/point/plot/source_plane_panel.py +++ b/autolens/point/plot/source_plane_panel.py @@ -647,6 +647,7 @@ def plot_source_plane_panel( radial_caustics=None, point_colors=None, legend: bool = True, + point_marker: str = "o", ): """ Draws the "Fit Source Plane" panel of a positions fit on ``ax`` (see the module docstring). @@ -665,6 +666,8 @@ def plot_source_plane_panel( 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). + point_marker + The marker shape for the traced positions. """ from autoarray.plot.utils import apply_extent, apply_labels @@ -688,7 +691,7 @@ def plot_source_plane_panel( traced[:, 0], s=110, c=pp.OBSERVED_COLOR if point_colors is None else list(point_colors), - marker="o", + marker=point_marker, edgecolors="k", linewidths=0.6, zorder=4, diff --git a/test_autolens/cluster/plot/test_cluster_plots.py b/test_autolens/cluster/plot/test_cluster_plots.py index 45c5405e7..4c71bb1d8 100644 --- a/test_autolens/cluster/plot/test_cluster_plots.py +++ b/test_autolens/cluster/plot/test_cluster_plots.py @@ -373,3 +373,102 @@ def test__zero_contour_without_dependency__falls_back_to_marching_squares( ] # Read once per plot call, so one warning each. assert len(fallback_warnings) == 2 + + +def test_overlay_preserves_image_origin_and_uses_family_metadata(): + import matplotlib.pyplot as plt + from matplotlib.colors import AsinhNorm, to_hex + + fig, ax = plt.subplots() + image = aa.Array2D.no_mask( + values=np.arange(24).reshape(4, 6), + pixel_scales=(0.3, 0.2), + origin=(12.0, -7.0), + ) + datasets = [ + al.PointDataset( + name="Arc A", + positions=[(12.1, -7.2)], + positions_noise_map=0.2, + redshift=1.1, + ), + al.PointDataset( + name="Arc B", + positions=[(11.8, -6.9)], + positions_noise_map=0.2, + redshift=2.3, + ), + ] + plot_positions_overlay( + [dataset.positions for dataset in datasets], + image=image, + ax=ax, + datasets=datasets, + ) + + raster = ax.images[0] + assert raster.get_extent() == pytest.approx(image.geometry.extent) + assert raster.origin == "upper" + assert isinstance(raster.norm, AsinhNorm) + assert np.asarray( + [artist.get_offsets()[0] for artist in ax.collections] + ) == pytest.approx(np.asarray([(-7.2, 12.1), (-6.9, 11.8)])) + assert [to_hex(artist.get_edgecolors()[0]) for artist in ax.collections] == [ + "#ffbc53", + "#5fe3ee", + ] + legend = ax.get_legend() + assert legend.get_bbox_to_anchor().y0 > ax.bbox.y1 + assert [label.get_text() for label in legend.get_texts()] == [ + "Arc A · 1 image · z=1.10", + "Arc B · 1 image · z=2.30", + ] + plt.close(fig) + + +def test_zooms_start_each_family_on_its_own_row(positions_list, image, monkeypatch): + import matplotlib.pyplot as plt + + figures = [] + monkeypatch.setattr( + cluster_plots, "save_figure", lambda fig, **kwargs: figures.append(fig) + ) + plot_image_group_zooms(positions_list, image=image, max_cols=2, zoom_arcsec=0.4) + + fig = figures[0] + assert [ax.get_title() for ax in fig.axes] == [ + "Source 0 · Image 1", + "Source 0 · Image 2", + "Source 0 · Image 3", + "", + "Source 1 · Image 1", + "Source 1 · Image 2", + ] + assert not fig.axes[3].axison + # Geometric image 2 is the third position in the dataset input. + assert fig.axes[1].get_xlim() == pytest.approx((1.4, 1.8)) + assert fig.axes[1].get_ylim() == pytest.approx((0.0, 0.4)) + assert fig.axes[4].get_xlim() == pytest.approx((0.2, 0.6)) + assert fig.axes[4].get_ylim() == pytest.approx((1.9, 2.3)) + plt.close(fig) + + +def test_dense_overlay_groups_legend_in_five_columns(): + import matplotlib.pyplot as plt + from matplotlib.colors import to_hex + + fig, ax = plt.subplots(figsize=(10, 7)) + legend_positions = [[(0.0, float(index))] for index in range(20)] + plot_positions_overlay(legend_positions, ax=ax) + + colours = [to_hex(artist.get_edgecolors()[0]) for artist in ax.collections] + assert len(set(colours)) == len(legend_positions) + assert colours[0] != "#a15b0c" + assert colours[1] != "#00778a" + + fig.canvas.draw() + labels = ax.get_legend().get_texts() + y_positions = {round(label.get_window_extent().y0, 3) for label in labels} + assert len(labels) == len(legend_positions) + assert len(y_positions) == 4 + plt.close(fig) diff --git a/test_autolens/point/plot/test_family_statistics.py b/test_autolens/point/plot/test_family_statistics.py new file mode 100644 index 000000000..642d8f51a --- /dev/null +++ b/test_autolens/point/plot/test_family_statistics.py @@ -0,0 +1,89 @@ +from types import SimpleNamespace + +import numpy as np +import pytest +from scipy.stats import norm + +import autolens as al +from autolens.point.plot.family_statistics import contribution_values + + +def family_record(fit_positions_cls, model): + dataset = al.PointDataset( + name="point_0", + positions=al.Grid2DIrregular([(0.0, 0.0), (3.0, 4.0)]), + positions_noise_map=al.ArrayIrregular([0.5, 1.0]), + ) + tracer = al.Tracer( + galaxies=[ + al.Galaxy(redshift=0.5), + al.Galaxy(redshift=1.0, point_0=al.ps.Point(centre=(0.1, 0.1))), + ] + ) + solver = al.m.MockPointSolver(model_positions=al.Grid2DIrregular(model)) + fit = al.FitPointDataset( + dataset=dataset, tracer=tracer, solver=solver, fit_positions_cls=fit_positions_cls + ) + model = np.asarray(model) + return SimpleNamespace( + fit=fit, + model=model[np.isfinite(model).all(axis=1)], + mixture=isinstance(fit.positions, al.FitPositionsImagePairAll), + ) + + +@pytest.mark.parametrize( + "fit_positions_cls, expected_terms, label", + [ + (al.FitPositionsImagePair, [40.0, 2.0], "Image-plane χ²"), + (al.FitPositionsSource, [0.08, 23.62], "Source-plane χ²"), + ], +) +def test_contributions_of_position_residuals(fit_positions_cls, expected_terms, label): + record = family_record(fit_positions_cls, [(3.0, 1.0), (2.0, 3.0)]) + terms, penalty, actual_label = contribution_values(record) + + assert terms == pytest.approx(expected_terms) + assert penalty == 0.0 + assert terms.sum() == pytest.approx(record.fit.positions.chi_squared) + assert actual_label == label + + +@pytest.mark.parametrize("policy, expected_penalty", [("ignore", 0.0), ("penalize", 16.0)]) +def test_unmatched_model_penalty(policy, expected_penalty): + record = family_record( + al.FitPositionsImagePairRepeat, + [(0.5, 0.0), (3.0, 3.5), (3.0, 7.0), (np.inf, np.inf)], + ) + record.fit.positions.unmatched_model_policy = policy + terms, penalty, label = contribution_values(record) + + assert terms == pytest.approx([1.0, 0.25]) + assert penalty == pytest.approx(expected_penalty) + assert terms.sum() + penalty == pytest.approx(record.fit.positions.chi_squared) + assert label == "Image-plane χ²" + + +def test_mixture_contributions_include_component_weights_and_noise(): + record = family_record( + al.FitPositionsImagePairAll, [(0.0, 0.0), (3.0, 4.0), (np.inf, np.inf)] + ) + terms, penalty, label = contribution_values(record) + + expected_terms = -2 * np.log( + [norm(scale=sigma).pdf([0.0, 5.0]).mean() for sigma in [0.5, 1.0]] + ) + assert terms == pytest.approx(expected_terms) + assert terms.sum() == pytest.approx(record.fit.positions.chi_squared) + assert penalty == 0.0 + assert label == "-2 log mixture" + + +def test_mixture_contributions_use_the_no_image_floor(): + record = family_record(al.FitPositionsImagePairAll, [(np.inf, np.inf)]) + terms, penalty, label = contribution_values(record) + + assert terms == pytest.approx([4.0e8, 1.0e8]) + assert terms.sum() == record.fit.positions.chi_squared + assert penalty == 0.0 + assert label == "-2 log mixture" diff --git a/test_autolens/point/plot/test_multi_source_plots.py b/test_autolens/point/plot/test_multi_source_plots.py index 82fb7e475..9623afe23 100644 --- a/test_autolens/point/plot/test_multi_source_plots.py +++ b/test_autolens/point/plot/test_multi_source_plots.py @@ -1,20 +1,21 @@ -import shutil from pathlib import Path from types import SimpleNamespace import numpy as np import pytest +from matplotlib.colors import AsinhNorm, to_rgba import autolens as al from autolens.point.plot import multi_source_plots as msp from autolens.point.plot import point_sources as ps +from autolens.point.plot import source_plane_panel as spp directory = Path(__file__).resolve().parent -def _tracer(n_sources=2): +def _tracer(n_sources=2, first_centre=(0.05, 0.03)): 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)] + centres = [first_centre, (-0.04, 0.06), (0.02, -0.05), (0.0, 0.08), (-0.06, -0.02)] sources = [ al.Galaxy( redshift=z, @@ -87,13 +88,17 @@ def make_cluster(): @pytest.fixture(name="figures") def make_figures(monkeypatch): + from matplotlib import pyplot as plt + 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 + yield figures + for saved in figures: + plt.close(saved.fig) def _legend_labels(ax): @@ -156,31 +161,79 @@ def test__plot_dataset_positions__all_sources_labelled_no_curves(cluster, figure ax = figures[0].fig.axes[0] assert figures[0].filename == "dataset_point" - assert ax.get_title() == "Dataset Positions" + assert ax.get_title() == "Cluster dataset overview" labels = _legend_labels(ax) - assert labels == ["point_0 (z = 1, σ = 0.005″)", "point_1 (z = 2, σ = 0.005″)"] + for dataset, label in zip(cluster.datasets, labels): + assert label == f"{dataset.name} (z = {dataset.redshift:g}, {len(dataset.positions)} images, σ = 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__twenty_family_dataset__all_entries_above_the_sky_map(figures): + datasets = [ + al.PointDataset( + name=f"point_{k}", + redshift=1 + k / 10, + positions_noise_map=0.04, + positions=al.Grid2DIrregular(values=[(k - 10, 3), (10 - k, -3)]), + ) + for k in range(20) + ] + image = al.Array2D.ones(shape_native=(80, 80), pixel_scales=1.0) + msp.plot_dataset_positions(datasets, image_extent=image.geometry.extent) + msp.plot_image_with_points(image, datasets=datasets) + for saved in figures: + fig = saved.fig + fig.canvas.draw() + renderer = fig.canvas.get_renderer() + ax = fig.axes[0] + assert ax.get_xlim() == ax.get_ylim() == (-30.0, 30.0) + legend = ax.get_legend() + assert legend.get_title().get_text() == "20 families · 40 observed images" + assert len(legend.get_texts()) == 20 + assert {text.get_text() for text in ax.texts} == { + f"{k}·{n}" for k in range(20) for n in (1, 2) + } + assert ( + legend.get_window_extent(renderer).y0 >= ax.get_window_extent(renderer).y1 + ) + boxes = [text.get_window_extent(renderer) for text in legend.get_texts()] + assert all( + not a.overlaps(b) for i, a in enumerate(boxes) for b in boxes[i + 1 :] + ) + + +def _assert_family_legend_labels(labels, fits, statistic): + for fit in fits: + label = next(label for label in labels if label.startswith(fit.dataset.name)) + value = spp._format_chi_squared(float(fit.positions.chi_squared)) + assert f"z = {fit.dataset.redshift:g}" in label + assert f"{statistic} = {value}" in label + assert "σ" not in label + + 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] + fig = figures[0].fig + (ax,) = fig.axes 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. + assert ax.get_title() == "Cluster fit overview" + _assert_family_legend_labels( + _legend_labels(ax), cluster.fits["FitPositionsImagePair"], "Image-plane χ²" + ) + keys = [text.get_text() for legend in fig.legends for text in legend.get_texts()] + assert "Critical curve (each source's z)" in keys + assert any(label.startswith("χ² = ") for label in keys) + 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 + expected_segment = np.stack([record.observed[0], record.model[record.indexes[0]]]) + assert any( + np.allclose(line.get_xydata(), expected_segment[:, ::-1]) + for line in ax.lines + if len(line.get_xydata()) == 2 + ) def test__plot_fit_positions__mixture_shows_minus_two_ln_l(cluster, figures): @@ -188,10 +241,14 @@ def test__plot_fit_positions__mixture_shows_minus_two_ln_l(cluster, figures): 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 + fig = figures[0].fig + _assert_family_legend_labels( + _legend_labels(fig.axes[0]), cluster.fits["FitPositionsImagePairAll"], "−2 ln L" + ) + keys = [text.get_text() for legend in fig.legends for text in legend.get_texts()] + assert any(label.startswith("−2 ln L = ") for label in keys) + assert not any(label.startswith("χ²") for label in keys) + assert "Residual (nearest, soft pairing)" in keys def test__subplot_fit_per_image__rows_no_legends_sigma_values(cluster, figures): @@ -263,32 +320,126 @@ def test__subplot_fit_per_image__many_sources_one_file_each(figures): 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): +@pytest.mark.parametrize( + ("fit_name", "statistic"), + [ + (None, None), + ("FitPositionsImagePair", "Image-plane χ²"), + ("FitPositionsSource", "Source-plane χ²"), + ], +) +def test__plot_image_with_points__fitted_sources_show_fit_statistic( + cluster, figures, fit_name, statistic +): image = al.Array2D.ones(shape_native=(30, 30), pixel_scales=0.1) + fits = cluster.fits.get(fit_name) msp.plot_image_with_points( image, datasets=cluster.datasets, - fits=cluster.fits["FitPositionsImagePair"] if with_fit else None, + fits=fits, 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") + if fits is None: + assert len(_legend_labels(ax)) == len(cluster.datasets) + assert all("χ²" not in label for label in _legend_labels(ax)) + assert figures[0].filename == "image_with_points" + else: + _assert_family_legend_labels(_legend_labels(ax), fits, statistic) + assert figures[0].filename == "fit_image_with_points" + assert ax.get_title() == "Cluster fit on the observed image" texts = {t.get_text() for t in ax.texts} assert "0·1" in texts and "1·1" in texts +@pytest.mark.parametrize("far_positions", [False, True]) +def test__cluster_fit_overviews__same_physical_square( + cluster, figures, monkeypatch, far_positions +): + fits = cluster.fits["FitPositionsImagePair"] + image = al.Array2D.ones(shape_native=(80, 80), pixel_scales=1.0) + records = ps.records_from_fits(fits) + if far_positions: + records[0].observed = records[0].observed.copy() + records[0].observed[0] = (37.0, 34.0) + records[1].model = records[1].model.copy() + records[1].model[0] = (-38.0, -36.0) + monkeypatch.setattr(ps, "records_from_fits", lambda fits: records) + + msp.plot_fit_positions(fits, curves={}, image_extent=image.geometry.extent) + msp.plot_image_with_points(image, fits=fits, curves={}) + + (plain,) = figures[0].fig.axes + (sky,) = figures[1].fig.axes + assert plain.get_xlim() == pytest.approx(sky.get_xlim()) + assert plain.get_ylim() == pytest.approx(sky.get_ylim()) + assert np.ptp(sky.get_xlim()) == pytest.approx(np.ptp(sky.get_ylim())) + if far_positions: + x_min, x_max = sky.get_xlim() + y_min, y_max = sky.get_ylim() + for record in records: + for y, x in np.vstack([record.observed, record.model]): + assert x_min <= x <= x_max + assert y_min <= y <= y_max + else: + assert sky.get_xlim() == pytest.approx((-30, 30)) + assert sky.get_ylim() == pytest.approx((-30, 30)) + + assert not plain.images + (raster,) = sky.images + assert isinstance(raster.norm, AsinhNorm) + assert raster.origin == "upper" + assert raster.get_extent() == pytest.approx(image.geometry.extent) + gray = raster.cmap(0.4) + assert gray[:3] == pytest.approx([gray[0]] * 3) + for ax, colors in ( + (plain, ("#a15b0c", "#00778a")), + (sky, ("#ffbc53", "#5fe3ee")), + ): + labels = {text.get_text() for text in ax.texts} + assert {f"{r.k}·{n}" for r in records for n in r.numbers} <= labels + for record, color in zip(records, colors): + assert any( + np.allclose(ring.get_edgecolors(), to_rgba(color)) + and not ring.get_facecolors().size + and np.allclose(ring.get_offsets(), record.observed[:, ::-1]) + for ring in ax.collections + if ring.get_edgecolors().size + and ring.get_offsets().shape == record.observed.shape + ) + + +def test__cluster_fit_image__fallback_curve_labels_last_source_plane(cluster, figures): + image = al.Array2D.ones(shape_native=(80, 80), pixel_scales=1.0) + curve = np.array([[-2.0, 1.0], [-1.0, 2.0], [0.0, 3.0]]) + + msp.plot_image_with_points( + image, + fits=cluster.fits["FitPositionsImagePair"], + curves={}, + image_plane_lines=[curve], + ) + + fig = figures[0].fig + keys = [text.get_text() for legend in fig.legends for text in legend.get_texts()] + assert "Critical curve (last source plane)" in keys + assert "Critical curve (each source's z)" not in keys + (ax,) = fig.axes + assert any( + np.allclose(line.get_xydata(), curve[:, ::-1]) + for line in ax.lines + if len(line.get_xydata()) == len(curve) + ) + + def test__visualizer__combined_figures_written_for_several_point_analyses( - cluster, plot_patch + cluster, plot_patch, monkeypatch, tmp_path ): from autolens.point.model.visualizer import VisualizerPoint - plot_path = directory / "files" / "plots" / "combined" - if plot_path.exists(): - shutil.rmtree(plot_path) + plot_path = tmp_path / "combined" image = al.Array2D.ones(shape_native=(30, 30), pixel_scales=0.1) analyses = [ @@ -303,6 +454,17 @@ def test__visualizer__combined_figures_written_for_several_point_analyses( ] instance = SimpleNamespace(galaxies=cluster.tracer.galaxies) paths = SimpleNamespace(image_path=plot_path, output_path=plot_path) + solver_calls = [] + solve = cluster.solver.solve + + def track_solution(**kwargs): + solution = solve(**kwargs) + solver_calls.append( + (tuple(kwargs["source_plane_coordinate"]), kwargs["plane_redshift"]) + ) + return solution + + monkeypatch.setattr(cluster.solver, "solve", track_solution) VisualizerPoint.visualize_combined( analyses=analyses, @@ -313,13 +475,28 @@ def test__visualizer__combined_figures_written_for_several_point_analyses( for name in ( "fit.png", - "fit_per_image.png", + "point_0/fit.png", + "point_1/fit.png", "fit_image_with_points.png", "dataset_point.png", "image_with_points.png", ): assert str(plot_path / name) in plot_patch.paths + assert str(plot_path / "fit_per_image.png") not in plot_patch.paths + assert solver_calls == [((0.05, 0.03), 1.0), ((-0.04, 0.06), 2.0)] + + changed_centre = (0.07, -0.02) + changed = SimpleNamespace(galaxies=_tracer(first_centre=changed_centre).galaxies) + solver_calls.clear() + VisualizerPoint.visualize_combined( + analyses=analyses, + paths=paths, + instance=[changed, changed], + during_analysis=False, + ) + assert solver_calls == [(changed_centre, 1.0), ((-0.04, 0.06), 2.0)] + # A single point analysis has no combined figures (its own figures are output per analysis). plot_patch.paths.clear() VisualizerPoint.visualize_combined( @@ -343,3 +520,200 @@ def test__plotter__fit_per_image_toggle(cluster, plot_patch, monkeypatch): monkeypatch.setattr(plotter_module, "plot_setting", lambda section, name: False) plotter.fit_per_image(fit_list=fits, curves={}) assert plot_patch.paths == [] + + +@pytest.fixture(name="family_figures") +def make_family_figures(monkeypatch): + from matplotlib.figure import Figure + + figures = {} + + def capture(fig, filename, **kwargs): + figures[Path(filename)] = fig + + monkeypatch.setattr(Figure, "savefig", capture) + return figures + + +@pytest.mark.parametrize("family_index", [None, 1]) +def test__visualizer__single_analysis_legacy_figures_use_explicit_family_context( + cluster, family_figures, tmp_path, monkeypatch, family_index +): + from autolens.point.model.plotter import PlotterPoint + from autolens.point.model.visualizer import VisualizerPoint + + monkeypatch.setenv("PYAUTO_FAST_PLOTS", "1") + monkeypatch.setattr(PlotterPoint, "tracer", lambda *args, **kwargs: None) + monkeypatch.setattr(PlotterPoint, "galaxies", lambda *args, **kwargs: None) + dataset = cluster.datasets[1] + analysis = al.AnalysisPoint( + dataset=dataset, + solver=cluster.solver, + image=al.Array2D.ones(shape_native=(30, 30), pixel_scales=0.1), + fit_positions_cls=al.FitPositionsImagePair, + use_jax=False, + ) + paths = SimpleNamespace(image_path=tmp_path, output_path=tmp_path) + instance = SimpleNamespace(galaxies=cluster.tracer.galaxies) + + VisualizerPoint.visualize_before_fit( + analysis=analysis, paths=paths, model=None, family_index=family_index + ) + VisualizerPoint.visualize( + analysis=analysis, + paths=paths, + instance=instance, + during_analysis=False, + family_index=family_index, + ) + + image_id = "1" if family_index is None else "1·1" + for filename in ("dataset_point", "fit", "image_with_points", "fit_image_with_points"): + ax = family_figures[tmp_path / f"{filename}.png"].axes[0] + assert image_id in {text.get_text() for text in ax.texts} + on_image = "image_with_points" in filename + if on_image: + assert ax.images[0].get_cmap().name == "gray" + if family_index is None: + color = "#ffbc53" if on_image else "#a15b0c" + else: + color = "#5fe3ee" if on_image else "#00778a" + assert any( + ring.get_edgecolors().size + and np.allclose(ring.get_edgecolors(), to_rgba(color)) + and not ring.get_facecolors().size + for ring in ax.collections + ) + + ranking, image_plane, source_plane = family_figures[tmp_path / "fit_per_image.png"].axes + assert image_id in {tick.get_text() for tick in ranking.get_yticklabels()} + for ax in (image_plane, source_plane): + assert image_id in {text.get_text() for text in ax.texts} + + +@pytest.mark.parametrize("with_image", [False, True]) +def test__plot_family_fits__one_shared_detail_panel( + cluster, family_figures, tmp_path, monkeypatch, with_image +): + from autolens.point.plot.family_fit_plots import plot_family_fits + + monkeypatch.setenv("PYAUTO_FAST_PLOTS", "1") + fits = cluster.fits["FitPositionsImagePair"] + image = ( + al.Array2D.ones(shape_native=(30, 30), pixel_scales=0.1) + if with_image + else None + ) + plot_family_fits( + fits, image=image, single_panel=True, output_path=tmp_path, output_format="png" + ) + + assert set(family_figures) == { + tmp_path / "point_0" / "fit.png", + tmp_path / "point_1" / "fit.png", + } + for fig in family_figures.values(): + fig.canvas.draw() + axes = {ax.get_title(): ax for ax in fig.axes} + assert "Cluster fit overview" in axes + ranking = axes["Per-image contribution"].get_window_extent() + source_plane = axes["All images in the source plane"].get_window_extent() + assert (ranking.width, ranking.height) == pytest.approx( + (source_plane.width, source_plane.height) + ) + assert "All images in the image plane" in axes + assert not any(title.startswith("Image ") for title in axes) + assert any(ax.images for ax in fig.axes) == with_image + + +@pytest.mark.parametrize( + ("n_images", "fit_positions_cls"), + [ + (6, al.FitPositionsImagePair), + (7, al.FitPositionsImagePair), + (7, al.FitPositionsSource), + ], +) +def test__plot_family_fits__image_tiles_keep_absolute_centres_and_full_rankings( + cluster, family_figures, tmp_path, monkeypatch, n_images, fit_positions_cls +): + from autolens.point.plot.family_fit_plots import plot_family_fits + from autolens.point.plot.positions_panel import image_numbers_from + from autolens.point.plot.source_plane_panel import source_plane_data_from + + monkeypatch.setenv("PYAUTO_FAST_PLOTS", "1") + observed = [ + (0.9, 0.7), + (-0.8, 0.6), + (0.7, -0.4), + (-0.5, -0.9), + (0.3, 0.4), + (-0.1, -0.3), + (0.2, -0.7), + ][:n_images] + dataset = al.PointDataset( + name="point_0", + positions=al.Grid2DIrregular(values=observed), + positions_noise_map=0.005, + redshift=1.0, + ) + fit = al.FitPointDataset( + dataset=dataset, + tracer=cluster.tracer, + solver=cluster.solver, + fit_positions_cls=fit_positions_cls, + ) + image = al.Array2D.ones(shape_native=(100, 100), pixel_scales=0.2) + + plot_family_fits([fit], image=image, output_path=tmp_path, output_format="png") + + pages = tmp_path / dataset.name + expected_paths = {pages / "fit.png"} + if n_images > 6: + expected_paths.add(pages / "fit_page_02.png") + assert set(family_figures) == expected_paths + numbers = image_numbers_from(dataset.positions) + centres = ( + source_plane_data_from(fit.positions, numbers=numbers).traced + if fit_positions_cls is al.FitPositionsSource + else observed + ) + centres_by_title = { + f"Image {number}": (y, x) for number, (y, x) in zip(numbers, centres) + } + terms = np.asarray(fit.positions.chi_squared_map.array) + ranked_numbers = [ + number for number, _ in sorted(zip(numbers, terms), key=lambda row: (-row[1], row[0])) + ] + tile_order = sorted(numbers) if n_images == 6 else ranked_numbers + sizes = [] + rankings = [] + spans = [] + for path, fig in family_figures.items(): + fig.canvas.draw() + ranking = next( + ax for ax in fig.axes if ax.get_title() == "Per-image contribution" + ) + ranked_ids = [tick.get_text() for tick in ranking.get_yticklabels()] + assert set(centres_by_title) <= set(ranked_ids) + rankings.append(ranked_ids) + + page_tiles = [] + for ax in fig.axes: + title = ax.get_title() + if title not in centres_by_title: + continue + page_tiles.append(title) + y, x = centres_by_title[title] + assert np.mean(ax.get_xlim()) == pytest.approx(x) + assert np.mean(ax.get_ylim()) == pytest.approx(y) + spans.append((np.ptp(ax.get_xlim()), np.ptp(ax.get_ylim()))) + bounds = ax.get_window_extent() + sizes.append((bounds.width, bounds.height)) + + page_numbers = tile_order[:6] if path.name == "fit.png" else tile_order[6:] + assert page_tiles == [f"Image {number}" for number in page_numbers] + + assert all(ranking == rankings[0] for ranking in rankings) + assert np.asarray(spans) == pytest.approx(np.broadcast_to(spans[0], (n_images, 2))) + assert np.asarray(sizes) == pytest.approx(np.broadcast_to(sizes[0], (n_images, 2))) diff --git a/test_autolens/point/plot/test_point_solver_plots.py b/test_autolens/point/plot/test_point_solver_plots.py index eaea9c36d..831ff3a23 100644 --- a/test_autolens/point/plot/test_point_solver_plots.py +++ b/test_autolens/point/plot/test_point_solver_plots.py @@ -427,3 +427,35 @@ def test__critical_curves__source_plane_own_curves_when_not_given(solver, tracer labels = [h.get_label() for h in psp.legend_handles_from(data, marked=False)] assert "Critical curve" in labels + + + +def test__solver_panel__family_style_alters_only_observed_markers(data): + from dataclasses import replace + from matplotlib import pyplot as plt + from matplotlib.colors import to_rgba + + data = replace(data, positions=data.solved) + fig, axes = plt.subplots(1, 2) + try: + for ax, family_index, expected_color, expected_marker in ( + (axes[0], None, psp.OBSERVED_COLOR, "o"), + (axes[1], 1, "#00778a", "D"), + ): + marked = psp.draw_point_solver_panel( + ax, data.steps[0], data, panel_inches=4.0, family_index=family_index + ) + handles = { + h.get_label(): h + for h in psp.legend_handles_from(data, marked, family_index=family_index) + } + observed = handles["Observed"] + assert observed.get_marker() == expected_marker + assert to_rgba(observed.get_markeredgecolor()) == to_rgba(expected_color) + assert to_rgba(handles["Solved"].get_color()) == to_rgba(psp.SOLVED_COLOR) + assert {text.get_text() for text in ax.texts} >= {"1", "r1"} + observed_artist, solved_artist = ax.collections[-2:] + assert observed_artist.get_edgecolors()[0] == pytest.approx(to_rgba(expected_color)) + assert solved_artist.get_facecolors()[0] == pytest.approx(to_rgba(psp.SOLVED_COLOR)) + finally: + plt.close(fig)