diff --git a/autolens/config/visualize/plots.yaml b/autolens/config/visualize/plots.yaml index fc2a1229ca..8ede4b51d5 100644 --- a/autolens/config/visualize/plots.yaml +++ b/autolens/config/visualize/plots.yaml @@ -55,8 +55,10 @@ fit_interferometer: # Settings for plots of fits to inter point_dataset: # Settings for plots of point source datasets (e.g. PointDatasetPlotter). subplot_dataset: true # Plot subplot containing all dataset quantities (e.g. the data, noise-map, etc.)? + image_with_points: true # Plot the observed image (if passed to AnalysisPoint) with the observed positions over it? -fit_point_dataset: {} # Settings for plots of fits to point source datasets (e.g. FitPointDatasetPlotter). +fit_point_dataset: # Settings for plots of fits to point source datasets (e.g. FitPointDatasetPlotter). + image_with_points: true # Plot the observed image (if passed to AnalysisPoint) with observed and model positions over it? weak_dataset: # Settings for plots of weak lensing shear catalogues (e.g. PlotterWeak). subplot_dataset: true # Plot subplot containing all dataset quantities (e.g. the shear field, noise-map, etc.)? diff --git a/autolens/plot/__init__.py b/autolens/plot/__init__.py index 682e61af92..f1f9f71f18 100644 --- a/autolens/plot/__init__.py +++ b/autolens/plot/__init__.py @@ -65,7 +65,10 @@ subplot_tracer_from_fit as subplot_fit_interferometer_tracer, subplot_fit_interferometer_combined, ) -from autolens.point.plot.fit_point_plots import subplot_fit as subplot_fit_point +from autolens.point.plot.fit_point_plots import ( + subplot_fit as subplot_fit_point, + plot_image_with_points, +) from autolens.point.plot.point_dataset_plots import subplot_dataset as subplot_point_dataset from autolens.cluster.plot.cluster_plots import ( diff --git a/autolens/point/model/analysis.py b/autolens/point/model/analysis.py index 4dcbe900c2..7a42d4c2b0 100644 --- a/autolens/point/model/analysis.py +++ b/autolens/point/model/analysis.py @@ -103,6 +103,10 @@ def __init__( fit_time_delays_cls The class used to fit the time delays of the point source dataset, which could be the min-subtraction (`FitTimeDelays`) or analytically-solved-reference-time (`FitTimeDelaysSolved`) fit. + image + An optional observed image of the lensed point source (e.g. a quasar), which is used only for + visualization: the observed and model point-source positions are plotted over it. It does not enter + the likelihood. cosmology The Cosmology assumed for this analysis. title_prefix @@ -117,6 +121,7 @@ def __init__( AnalysisLens.__init__(self=self, cosmology=cosmology, use_jax=self._use_jax) self.dataset = dataset + self.image = image self.solver = solver self.fit_positions_cls = fit_positions_cls diff --git a/autolens/point/model/plotter.py b/autolens/point/model/plotter.py index af743fe38a..fdaa4523dd 100644 --- a/autolens/point/model/plotter.py +++ b/autolens/point/model/plotter.py @@ -5,6 +5,7 @@ from autolens.point.fit.dataset import FitPointDataset from autolens.point.plot.fit_point_plots import subplot_fit as subplot_fit_point +from autolens.point.plot.fit_point_plots import plot_image_with_points from autolens.point.dataset import PointDataset from autolens.point.plot.point_dataset_plots import subplot_dataset @@ -32,6 +33,53 @@ def should_plot(name): subplot_dataset(dataset, output_path=output_path, output_format=fmt, title_prefix=self.title_prefix) + def image_with_points( + self, + image, + dataset: PointDataset, + fit: FitPointDataset = None, + image_plane_lines=None, + image_plane_line_colors=None, + ): + """ + Output an observed image of the lensed point source with the point-source positions overlaid. + + Before the fit (``fit=None``) only the observed positions are drawn, controlled by the + `point_dataset: image_with_points` setting. After the fit the model positions (and critical curves, + if given) are also drawn, controlled by the `fit_point_dataset: image_with_points` setting. + + Parameters + ---------- + image + The observed image of the lensed point source (e.g. a quasar), used only for visualization. + dataset + The point dataset whose observed positions are overlaid. + fit + The maximum log likelihood `FitPointDataset`, whose model positions are overlaid if given. + image_plane_lines + Pre-computed critical-curve lines to overlay on the image. + image_plane_line_colors + Colours for each image-plane line. + """ + if fit is None: + section = ["point_dataset"] + else: + section = ["fit", "fit_point_dataset"] + + if not plot_setting(section=section, name="image_with_points"): + return + + plot_image_with_points( + image=image, + dataset=dataset, + fit=fit, + output_path=str(self.image_path), + output_format=self.fmt, + image_plane_lines=image_plane_lines, + image_plane_line_colors=image_plane_line_colors, + title_prefix=self.title_prefix, + ) + def fit_point( self, fit: FitPointDataset, diff --git a/autolens/point/model/visualizer.py b/autolens/point/model/visualizer.py index 8de71210af..414ce1f6a3 100644 --- a/autolens/point/model/visualizer.py +++ b/autolens/point/model/visualizer.py @@ -33,6 +33,9 @@ def visualize_before_fit( plotter.dataset_point(dataset=analysis.dataset) + if getattr(analysis, "image", None) is not None: + plotter.image_with_points(image=analysis.image, dataset=analysis.dataset) + @staticmethod def visualize( analysis, @@ -90,6 +93,16 @@ def visualize( source_plane_line_colors=sp_colors, ) + # Output even on `quick_update`, so the observed image with model positions updates on-the-fly. + if getattr(analysis, "image", None) is not None: + plotter.image_with_points( + image=analysis.image, + dataset=fit.dataset, + fit=fit, + image_plane_lines=ip_lines, + image_plane_line_colors=ip_colors, + ) + if quick_update: return diff --git a/autolens/point/plot/fit_point_plots.py b/autolens/point/plot/fit_point_plots.py index 72adea7bce..eb28529657 100644 --- a/autolens/point/plot/fit_point_plots.py +++ b/autolens/point/plot/fit_point_plots.py @@ -86,3 +86,83 @@ def subplot_fit( save_figure(fig, path=output_path, filename="fit", format=output_format) +def plot_image_with_points( + image, + dataset, + fit=None, + output_path: Optional[str] = None, + output_format: str = None, + image_plane_lines=None, + image_plane_line_colors=None, + title_prefix: str = None, +): + """ + Plot an observed image of a lensed point source (e.g. a quasar) with its point-source positions overlaid. + + The observed positions of the `PointDataset` are drawn as hollow white rings, so they stand out against + the image without hiding the point-source emission beneath them. When a `FitPointDataset` is passed, the model-predicted positions + are drawn as red crosses (image-plane fits only, as a source-plane fit's model data lies in the source + plane), and critical curves can be overlaid via ``image_plane_lines``. + + The image is used only for visualization: it does not enter the point-source likelihood. + + Parameters + ---------- + image : Array2D + The observed image the positions are plotted over. + dataset : PointDataset + The point-source dataset whose observed positions are overlaid. + fit : FitPointDataset, optional + If given, its model positions are overlaid as red crosses. + output_path : str, optional + Directory in which to save the figure. If ``None`` the figure is + not saved to disk. + output_format : str, optional + Image format passed to :func:`~autoarray.plot.utils.save_figure`. + image_plane_lines : list, optional + Critical-curve lines overlaid on the image. + image_plane_line_colors : list, optional + Colours for each image-plane line. + """ + from autogalaxy.util.plot_utils import plot_array + from autoarray.plot.utils import conf_figsize, _overlay_yx_for_origin + + fig, ax = subplots(1, 1, figsize=conf_figsize("figures")) + + _prefix = f"{title_prefix.rstrip()} " if title_prefix else "" + plot_array( + array=image, + ax=ax, + lines=image_plane_lines, + line_colors=image_plane_line_colors, + title=f"{_prefix}{dataset.name} Image With Points", + ) + + # Positions are (y,x) arc-seconds: reflect them exactly as `plot_array` does its own overlays, using the + # extent and origin of the raster it drew, so they stay registered to the image (PyAutoArray#565). + extent, origin = (ax.images[0].get_extent(), ax.images[0].origin) if ax.images else (None, None) + + def _yx(grid): + grid = np.array(grid.array if hasattr(grid, "array") else grid).reshape(-1, 2) + return _overlay_yx_for_origin(grid, extent, origin) + + obs_grid = _yx(dataset.positions) + ax.scatter( + obs_grid[:, 1], obs_grid[:, 0], + s=150, facecolors="none", edgecolors="w", linewidths=2, zorder=6, label="Observed", + ) + + # Only image-plane fits have model positions in the image plane; a source-plane fit's model data is the + # source centre, which must not be drawn over the image. + from autolens.point.fit.positions.image.abstract import AbstractFitPositionsImagePair + + if fit is not None and isinstance(fit.positions, AbstractFitPositionsImagePair): + model_grid = _yx(fit.positions.model_data) + ax.scatter( + model_grid[:, 1], model_grid[:, 0], + s=60, c="r", marker="x", linewidths=2, zorder=7, label="Model", + ) + + ax.legend(loc="upper right", fontsize=8, framealpha=0.8) + + save_figure(fig, path=output_path, filename="image_with_points", format=output_format) diff --git a/test_autolens/point/model/test_analysis_point.py b/test_autolens/point/model/test_analysis_point.py index 7bf6d22e20..8e2bd84a55 100644 --- a/test_autolens/point/model/test_analysis_point.py +++ b/test_autolens/point/model/test_analysis_point.py @@ -272,3 +272,18 @@ def test__fit_flux_cls_and_fit_time_delays_cls_hooks__forwarded_and_default_unch assert fit.fit_flux_cls is al.FitFluxesSolved assert fit.fit_time_delays_cls is al.FitTimeDelaysSolved + + +def test__image__stored_for_visualization(point_dataset): + solver = al.m.MockPointSolver(model_positions=point_dataset.positions) + image = al.Array2D.ones(shape_native=(5, 5), pixel_scales=1.0) + + analysis = al.AnalysisPoint(dataset=point_dataset, solver=solver, use_jax=False) + + assert analysis.image is None + + analysis = al.AnalysisPoint( + dataset=point_dataset, solver=solver, image=image, use_jax=False + ) + + assert analysis.image is image diff --git a/test_autolens/point/model/test_plotter_point.py b/test_autolens/point/model/test_plotter_point.py index 2b4a8d8f4d..dca090471d 100644 --- a/test_autolens/point/model/test_plotter_point.py +++ b/test_autolens/point/model/test_plotter_point.py @@ -35,3 +35,79 @@ def test__fit_point__quick_update__writes_normal_fit_subplot( assert str(plot_path / "fit.png") in plot_patch.paths assert str(plot_path / "fit_quick.png") not in plot_patch.paths + + +def _image(): + import autolens as al + + return al.Array2D.ones(shape_native=(20, 20), pixel_scales=0.25) + + +def _visualize(fit, image, plot_path, quick_update): + from types import SimpleNamespace + + from autolens.point.model.visualizer import VisualizerPoint + + analysis = SimpleNamespace( + dataset=fit.dataset, + image=image, + title_prefix=None, + fit_for_visualization=lambda instance: fit, + ) + paths = SimpleNamespace(image_path=plot_path, output_path=plot_path) + + VisualizerPoint.visualize_before_fit(analysis=analysis, paths=paths, model=None) + VisualizerPoint.visualize( + analysis=analysis, + paths=paths, + instance=None, + during_analysis=False, + quick_update=quick_update, + ) + + +def test__image_with_points(fit_point_dataset_x2_plane, plot_path, plot_patch): + if plot_path.exists(): + shutil.rmtree(plot_path) + + plotter = PlotterPoint(image_path=plot_path) + + plotter.image_with_points(image=_image(), dataset=fit_point_dataset_x2_plane.dataset) + + assert str(plot_path / "image_with_points.png") in plot_patch.paths + + +@pytest.mark.parametrize("quick_update", [False, True]) +def test__visualizer__image_with_points_before_and_after_fit( + fit_point_dataset_x2_plane, plot_path, plot_patch, quick_update +): + if plot_path.exists(): + shutil.rmtree(plot_path) + + _visualize( + fit=fit_point_dataset_x2_plane, + image=_image(), + plot_path=plot_path, + quick_update=quick_update, + ) + + image_with_points = [ + path for path in plot_patch.paths if path == str(plot_path / "image_with_points.png") + ] + + # Once before the fit (observed positions) and once after (with model positions). + assert len(image_with_points) == 2 + + +def test__visualizer__no_image__no_image_with_points( + fit_point_dataset_x2_plane, plot_path, plot_patch +): + if plot_path.exists(): + shutil.rmtree(plot_path) + + _visualize( + fit=fit_point_dataset_x2_plane, image=None, plot_path=plot_path, quick_update=True + ) + + assert str(plot_path / "fit.png") in plot_patch.paths + assert str(plot_path / "image_with_points.png") not in plot_patch.paths diff --git a/test_autolens/point/plot/test_fit_point_plots.py b/test_autolens/point/plot/test_fit_point_plots.py index f419cfbe70..0c6039e383 100644 --- a/test_autolens/point/plot/test_fit_point_plots.py +++ b/test_autolens/point/plot/test_fit_point_plots.py @@ -19,3 +19,61 @@ def test__subplot_fit(fit_point_dataset_x2_plane, plot_path, plot_patch): output_format="png", ) assert str(plot_path / "fit.png") in plot_patch.paths + + +def test__plot_image_with_points(point_dataset, fit_point_dataset_x2_plane, plot_path, plot_patch): + import autolens as al + + from autolens.point.plot.fit_point_plots import plot_image_with_points + + image = al.Array2D.ones(shape_native=(20, 20), pixel_scales=0.25) + + plot_image_with_points( + image=image, + dataset=point_dataset, + fit=fit_point_dataset_x2_plane, + output_path=plot_path, + output_format="png", + ) + assert str(plot_path / "image_with_points.png") in plot_patch.paths + + +@pytest.mark.parametrize( + "fit_positions_cls, n_scatter", [("FitPositionsImagePair", 2), ("FitPositionsSource", 1)] +) +def test__plot_image_with_points__model_positions_only_for_image_plane_fits( + point_dataset, plot_path, plot_patch, monkeypatch, fit_positions_cls, n_scatter +): + import matplotlib.axes + + import autolens as al + from autolens import fixtures + + from autolens.point.plot.fit_point_plots import plot_image_with_points + + fit = al.FitPointDataset( + dataset=point_dataset, + tracer=fixtures.make_tracer_x2_plane_point(), + solver=fixtures.make_solver(), + fit_positions_cls=getattr(al, fit_positions_cls), + ) + + scatter_calls = [] + scatter = matplotlib.axes.Axes.scatter + + def counting_scatter(self, *args, **kwargs): + scatter_calls.append(kwargs.get("label")) + return scatter(self, *args, **kwargs) + + monkeypatch.setattr(matplotlib.axes.Axes, "scatter", counting_scatter) + + plot_image_with_points( + image=al.Array2D.ones(shape_native=(20, 20), pixel_scales=0.25), + dataset=point_dataset, + fit=fit, + output_path=plot_path, + output_format="png", + ) + + assert scatter_calls.count("Observed") == 1 + assert len([label for label in scatter_calls if label in ("Observed", "Model")]) == n_scatter