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
104 changes: 70 additions & 34 deletions autolens/interferometer/fit_interferometer.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,10 @@
from autogalaxy.abstract_fit import AbstractFitInversion
from autogalaxy.interferometer.fit_interferometer import (
_has_light_profile_non_linear,
sparse_dirty_image_from,
_require_no_array_free_overrides,
_require_transformer,
sparse_chi_squared_from,
sparse_profile_terms_from,
uses_precomputed_data_term_from,
)

Expand Down Expand Up @@ -137,22 +140,11 @@ def profile_visibilities(self) -> Optional[aa.Visibilities]:
so it is safe under `jax.jit`.

On an array-free dataset (built by `Interferometer.from_stream` / `from_sparse_terms`, which has no
`uv_wavelengths` and so no transformer) there are no visibilities to compute: this returns `None` when
the tracer has no ordinary light profile, and raises an `exc.DatasetException` when it does, because
subtracting a light profile's visibilities needs the visibility arrays.
`uv_wavelengths` and so no transformer) there are no visibilities to compute and this returns `None`.
The likelihood never needs them there: ordinary light profiles enter through their real-space (lensed)
`profile_image` and the data-term identity (`sparse_profile_terms_from`, `sparse_chi_squared`).
"""
if self.dataset.transformer is None:
if _has_light_profile_non_linear(galaxies=self.tracer.galaxies):
raise aa.exc.DatasetException(
"This FitInterferometer's dataset is array-free (built by from_stream / "
"from_sparse_terms) and has no visibilities or transformer, so the tracer's "
"ordinary (non-linear) light profiles cannot be Fourier transformed and "
"subtracted. An array-free dataset supports pixelization-only and linear-light "
"fits; non-linear light profiles arrive in a later phase. Use the in-memory "
"constructor (`Interferometer(data=..., noise_map=..., uv_wavelengths=..., ...)`) "
"to fit them."
)

return None

if _has_light_profile_non_linear(galaxies=self.tracer.galaxies):
Expand All @@ -170,16 +162,30 @@ def profile_subtracted_visibilities(self) -> Optional[aa.Visibilities]:
Returns the interferometer dataset's visibilities with all transformed light profile images in the fit's
tracer subtracted.

On an array-free dataset there are no visibilities, so this is `None`. `profile_visibilities` is
evaluated first, so a fit with ordinary light profiles on an array-free dataset raises rather than
silently fitting the unsubtracted sparse terms.
On an array-free dataset there are no visibilities, so this is `None` (and `profile_visibilities` is not
evaluated). The inversion of such a fit instead receives the profile-subtracted dirty image and data term
(see `tracer_to_inversion`).
"""
profile_visibilities = self.profile_visibilities

if self.data is None:
return None

return self.data - profile_visibilities
return self.data - self.profile_visibilities

@property
def sparse_chi_squared(self):
"""
The chi-squared of this fit computed from the dataset's `sparse_operator` without any visibility-sized
array, which `chi_squared` (and so `log_likelihood` and, without an inversion, `figure_of_merit`) returns
on an array-free dataset (see `aa.FitInterferometer.sparse_chi_squared`).

It is `data_term - 2 m^T d~ + m^T W~ m` for the fit's total image-plane model image `m` (the tracer's
lensed ordinary light `profile_image` plus any inversion's `mapped_reconstructed_data`), so it equals the
dense `sum(|d - model_data|^2 / sigma^2)` exactly, with or without an inversion (see
`ag.interferometer.fit_interferometer.sparse_chi_squared_from`). `None` when the dataset has no
`sparse_operator`; raises a `DatasetException` if the fit overrides an array-free dataset's data or
noise-map. Every branch is structural, so it is safe under `jax.jit`.
"""
return sparse_chi_squared_from(fit=self, galaxies=self.tracer.galaxies)

@property
def _uses_precomputed_data_term(self) -> bool:
Expand All @@ -201,29 +207,47 @@ def tracer_to_inversion(self) -> TracerToInversion:
"""
Returns the object which builds this fit's inversion from its tracer's linear objects.

The inversion fits the `profile_subtracted_visibilities`, except on the sparse path when no galaxy has an
ordinary light profile (`_uses_precomputed_data_term`): nothing is then subtracted, and `data=None` is passed
so the sparse inversion takes its data vector from the operator's cached dirty image and the data term of
its `fast_chi_squared` from the operator's cached scalar, touching no visibility-sized array. The
visibilities remain available to outputs via `fit.data`.
The inversion fits the `profile_subtracted_visibilities`, except when `_uses_precomputed_data_term`, where
`data=None` is passed and the sparse inversion touches no visibility-sized array:

- With no ordinary light profile nothing is subtracted, so the inversion takes its data vector from the
operator's cached dirty image and the data term of its `fast_chi_squared` from the operator's cached
scalar.
- On an array-free dataset with ordinary light profiles (e.g. lens light), it is passed the dirty image
`d~ - W~ i_p` and data term `data_term - 2 i_p^T d~ + i_p^T W~ i_p` of the profile-subtracted
visibilities, both formed from one `W~ i_p` product (`sparse_profile_terms_from`), so the profile
visibilities `F i_p` are never formed.

On an in-memory sparse dataset with ordinary light profiles the subtracted dirty image is still supplied
(the data vector must use it) alongside the subtracted visibilities. Where the visibilities exist they
remain available to outputs via `fit.data`.

On an array-free dataset the fit's data and noise-map cannot be overridden, as the subtracted dirty image
and data term are formed from the operator's precomputed ones (`_require_no_array_free_overrides`).
"""
_require_no_array_free_overrides(fit=self)

sparse_dirty_image, data_term = sparse_profile_terms_from(
dataset=self.dataset,
galaxies=self.tracer.galaxies,
image=self.profile_image,
xp=self._xp,
)

if self._uses_precomputed_data_term:
data = None
else:
data = self.profile_subtracted_visibilities
data_term = None

dataset = aa.DatasetInterface(
data=data,
noise_map=self.noise_map,
grids=self.grids,
transformer=self.dataset.transformer,
sparse_operator=self.dataset.sparse_operator,
sparse_dirty_image=sparse_dirty_image_from(
dataset=self.dataset,
galaxies=self.tracer.galaxies,
image=self.profile_image,
xp=self._xp,
),
sparse_dirty_image=sparse_dirty_image,
data_term=data_term,
)

return TracerToInversion(
Expand Down Expand Up @@ -308,7 +332,12 @@ def model_data(self) -> aa.Visibilities:
sum of all light profile images Fourier transformed to visibilities.

If a inversion is included it is the sum of these visibilities and the inversion's reconstructed visibilities.

On an array-free dataset (built by `Interferometer.from_stream` / `from_sparse_terms`) there is no
transformer to form model visibilities with, so this raises an `aa.exc.DatasetException`; the real-space
`model_image_natural` and its natural dirty image `dirty_model_image_natural` describe the model there.
"""
_require_transformer(fit=self, quantity="model_data")

if self.perform_inversion:
return (
Expand Down Expand Up @@ -356,8 +385,7 @@ def model_image_natural(self) -> aa.Array2D:

It needs neither visibilities nor a transformer, so it is available on an array-free dataset (built by
`Interferometer.from_stream` / `from_sparse_terms`), where it is the image the natural-weighted dirty
model image `dirty_model_image_natural` is formed from. (There `profile_image` is all zeros, because a
fit with ordinary light on an array-free dataset raises before it gets here.)
model image `dirty_model_image_natural` is formed from.
"""
image = np.asarray(
getattr(self.profile_image, "array", self.profile_image), dtype=np.float64
Expand Down Expand Up @@ -437,7 +465,11 @@ def galaxy_model_visibilities_dict(self) -> Dict[ag.Galaxy, np.ndarray]:
space.
- The visibilities of all linear objects (e.g. linear light profiles / pixelizations), where the visibilities
are solved for first via the inversion.

On an array-free dataset there is no transformer and this raises an `aa.exc.DatasetException`.
"""
_require_transformer(fit=self, quantity="galaxy_model_visibilities_dict")

galaxy_model_visibilities_dict = self.tracer.galaxy_visibilities_dict_from(
grid=self.grids.lp, transformer=self.dataset.transformer, xp=self._xp
)
Expand All @@ -461,7 +493,11 @@ def model_visibilities_of_planes_list(self) -> List[aa.Visibilities]:

This is used to visualize the different contibutions of light from the image-plane, source-plane and other
planes in a fit.

On an array-free dataset there is no transformer and this raises an `aa.exc.DatasetException`.
"""
_require_transformer(fit=self, quantity="model_visibilities_of_planes_list")

galaxy_model_visibilities_dict = self.galaxy_model_visibilities_dict

model_visibilities_of_planes_list = [
Expand Down
23 changes: 23 additions & 0 deletions test_autolens/interferometer/model/test_analysis_interferometer.py
Original file line number Diff line number Diff line change
Expand Up @@ -288,3 +288,26 @@ def test__save_attributes__array_free_dataset__aggregator_round_trip(
).log_evidence

assert log_evidence_reloaded == pytest.approx(log_evidence, rel=1.0e-8)

# With lens light (fitted via the data-term identity) the reloaded dataset also reproduces the fit, with
# and without a pixelized source, and matches the in-memory dense fit.
lens_light = al.Galaxy(
redshift=0.5,
bulge=al.lp.Sersic(intensity=0.1, centre=(0.05, 0.05)),
mass=lens.mass,
)

for tracer in (
al.Tracer(galaxies=[lens_light, source]),
al.Tracer(galaxies=[lens_light, al.Galaxy(redshift=1.0)]),
):
figure_of_merit = al.FitInterferometer(
dataset=dataset, tracer=tracer
).figure_of_merit

assert al.FitInterferometer(
dataset=dataset_reloaded, tracer=tracer
).figure_of_merit == pytest.approx(figure_of_merit, rel=1.0e-8)
assert al.FitInterferometer(
dataset=interferometer_7, tracer=tracer
).figure_of_merit == pytest.approx(figure_of_merit, rel=1.0e-8)
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ def _pixelized_source_model():
)


def _visualize(dataset, image_path):
def _visualize(dataset, image_path, lens_light=False):
"""
Run the interferometer visualizer's `visualize_before_fit` and `visualize` for a lens
with a pixelized source (and positions) on `dataset`, as a non-linear search would.
Expand All @@ -100,6 +100,10 @@ def _visualize(dataset, image_path):
from autolens.interferometer.model.visualizer import VisualizerInterferometer

model = _pixelized_source_model()

if lens_light:
model.galaxies.lens.bulge = al.lp.Sersic(intensity=0.1, centre=(0.05, 0.05))

instance = model.instance_from_prior_medians()

analysis = al.AnalysisInterferometer(
Expand Down Expand Up @@ -177,6 +181,32 @@ def test__visualizer__array_free_dataset(interferometer_7, tmp_path, plot_patch)
)


def test__visualizer__array_free_dataset__lens_light_profile(
interferometer_7, tmp_path, plot_patch
):
"""
A model with lens light (an ordinary light profile) visualizes on an array-free dataset: the visualizer
reads only `model_image_natural` / `dirty_model_image_natural`, never the model visibilities.
"""
import numpy as np

dataset = _array_free_dataset_from(interferometer_7)

fit = _visualize(dataset=dataset, image_path=tmp_path, lens_light=True)

assert np.abs(fit.profile_image.array).max() > 0.0

for filename in _PNGS:
assert str(tmp_path / f"{filename}.png") in plot_patch.paths, filename

np.testing.assert_allclose(
al.ndarray_via_fits_from(file_path=tmp_path / "fit_dirty_images.fits", hdu=3),
fit.dirty_model_image_natural.native_for_fits,
rtol=1.0e-6,
atol=1.0e-12,
)


def test__visualizer__in_memory_dataset__fit_dirty_images_unchanged(
interferometer_7, tmp_path, plot_patch
):
Expand Down
Loading
Loading