Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion autolens/config/visualize/plots.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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.)?
Expand Down
5 changes: 4 additions & 1 deletion autolens/plot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down
5 changes: 5 additions & 0 deletions autolens/point/model/analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
48 changes: 48 additions & 0 deletions autolens/point/model/plotter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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,
Expand Down
13 changes: 13 additions & 0 deletions autolens/point/model/visualizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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

Expand Down
80 changes: 80 additions & 0 deletions autolens/point/plot/fit_point_plots.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
15 changes: 15 additions & 0 deletions test_autolens/point/model/test_analysis_point.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
76 changes: 76 additions & 0 deletions test_autolens/point/model/test_plotter_point.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
58 changes: 58 additions & 0 deletions test_autolens/point/plot/test_fit_point_plots.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Loading