diff --git a/autolens/interferometer/fit_interferometer.py b/autolens/interferometer/fit_interferometer.py index cbc9152b2..348de8f90 100644 --- a/autolens/interferometer/fit_interferometer.py +++ b/autolens/interferometer/fit_interferometer.py @@ -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, ) @@ -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): @@ -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: @@ -201,16 +207,38 @@ 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, @@ -218,12 +246,8 @@ def tracer_to_inversion(self) -> TracerToInversion: 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( @@ -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 ( @@ -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 @@ -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 ) @@ -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 = [ diff --git a/test_autolens/interferometer/model/test_analysis_interferometer.py b/test_autolens/interferometer/model/test_analysis_interferometer.py index faadcf301..9fc677040 100644 --- a/test_autolens/interferometer/model/test_analysis_interferometer.py +++ b/test_autolens/interferometer/model/test_analysis_interferometer.py @@ -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) diff --git a/test_autolens/interferometer/model/test_plotter_interferometer.py b/test_autolens/interferometer/model/test_plotter_interferometer.py index 22f7496a2..d3ea4d80d 100644 --- a/test_autolens/interferometer/model/test_plotter_interferometer.py +++ b/test_autolens/interferometer/model/test_plotter_interferometer.py @@ -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. @@ -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( @@ -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 ): diff --git a/test_autolens/interferometer/test_fit_interferometer.py b/test_autolens/interferometer/test_fit_interferometer.py index b3bb6097a..5b386f9b5 100644 --- a/test_autolens/interferometer/test_fit_interferometer.py +++ b/test_autolens/interferometer/test_fit_interferometer.py @@ -813,22 +813,265 @@ def figure_of_merit_from(coefficient, dataset, xp): ) -def test__fit_figure_of_merit__array_free_dataset__lens_light_profile__raises( - interferometer_7, +def _lens_light_tracer(intensity=0.1, source=None, coefficient=1.0): + """ + A lens with an ordinary light profile and an isothermal mass, with a source that is either absent + (`None`), an ordinary `"sersic"` (lensed ordinary light, no inversion), a `"pixelization"` or an `"mge"` + (a `Basis` of linear Gaussians). + """ + lens = al.Galaxy( + redshift=0.5, + bulge=al.lp.Sersic(intensity=intensity, centre=(0.05, 0.05)), + mass=al.mp.Isothermal(centre=(0.0, 0.0), einstein_radius=1.0), + ) + + if source is None: + return al.Tracer(galaxies=[lens, al.Galaxy(redshift=1.0)]) + + if source == "sersic": + source_galaxy = al.Galaxy( + redshift=1.0, bulge=al.lp.Sersic(intensity=0.2, centre=(0.1, 0.1)) + ) + elif source == "pixelization": + source_galaxy = al.Galaxy( + redshift=1.0, + pixelization=al.Pixelization( + mesh=al.mesh.RectangularUniform(shape=(3, 3)), + regularization=al.reg.Constant(coefficient=coefficient), + ), + ) + else: + source_galaxy = al.Galaxy( + redshift=1.0, + bulge=al.lp_basis.Basis( + profile_list=[ + al.lp_linear.Gaussian(sigma=sigma, centre=(0.1, 0.1)) + for sigma in (0.3, 1.0, 3.0) + ] + ), + ) + + return al.Tracer(galaxies=[lens, source_galaxy]) + + +@pytest.mark.parametrize("source", [None, "sersic", "pixelization", "mge"]) +def test__fit_figure_of_merit__array_free_dataset__lens_light_profile__matches_dense( + interferometer_7, source ): + """ + Lens light (and, for `"sersic"`, lensed ordinary source light) on an array-free dataset is fitted via the + data-term identity: without an inversion the chi-squared is `data_term - 2 i_p^T d~ + i_p^T W~ i_p`, with + one the inversion is passed the profile-subtracted dirty image and data term. Either way the figure of + merit equals the dense fit's, which forms and subtracts the profile visibilities. + """ dataset_array_free = _array_free_dataset_from(interferometer_7) - tracer = _pixelized_source_tracer(lens_light=True) + tracer = _lens_light_tracer(source=source) - fit = al.FitInterferometer(dataset=dataset_array_free, tracer=tracer) + fit = al.FitInterferometer(dataset=interferometer_7, tracer=tracer) + fit_array_free = al.FitInterferometer(dataset=dataset_array_free, tracer=tracer) - assert not fit._uses_precomputed_data_term + assert fit_array_free._uses_precomputed_data_term - with pytest.raises(aa.exc.DatasetException): - fit.profile_visibilities + assert fit_array_free.figure_of_merit == pytest.approx( + fit.figure_of_merit, rel=1.0e-8 + ) + # The array-free chi-squared applies the data-term identity to the total model image (lensed profile image + # plus the inversion's reconstruction), so it is the dense residual-map chi-squared exactly. + assert fit_array_free.chi_squared == pytest.approx(fit.chi_squared, rel=1.0e-8) + assert fit_array_free.log_likelihood == pytest.approx( + fit.log_likelihood, rel=1.0e-8 + ) + + if source in (None, "sersic"): + assert fit_array_free.inversion is None + assert fit_array_free.figure_of_merit == fit_array_free.log_likelihood + else: + assert isinstance(fit.inversion, aa.InversionInterferometerMapping) + assert isinstance(fit_array_free.inversion, aa.InversionInterferometerSparse) + + assert fit_array_free.inversion.dataset.data is None + assert fit_array_free.inversion.dataset.sparse_dirty_image is not None + assert fit_array_free.inversion.dataset.data_term is not None + + assert fit_array_free.log_evidence == pytest.approx( + fit.log_evidence, rel=1.0e-8 + ) + + assert "profile_visibilities" not in fit_array_free.__dict__ + assert fit_array_free.profile_visibilities is None + assert fit_array_free.profile_subtracted_visibilities is None + + with pytest.raises(aa.exc.DatasetException, match="array-free"): + fit_array_free.residual_map + + +@pytest.mark.parametrize("source", [None, "pixelization", "mge"]) +def test__fit_figure_of_merit__array_free_dataset__lens_light_profile__jax_jit_matches_numpy( + interferometer_7, source +): + jax = pytest.importorskip("jax") + import jax.numpy as jnp + + dataset_array_free = _array_free_dataset_from(interferometer_7) + + def figure_of_merit_from(intensity, dataset, xp): + return al.FitInterferometer( + dataset=dataset, + tracer=_lens_light_tracer(intensity=intensity, source=source), + xp=xp, + ).figure_of_merit + + figure_of_merit_dense = figure_of_merit_from( + intensity=0.1, dataset=interferometer_7, xp=np + ) + figure_of_merit_numpy = figure_of_merit_from( + intensity=0.1, dataset=dataset_array_free, xp=np + ) + + figure_of_merit_jit = jax.jit( + lambda intensity: figure_of_merit_from( + intensity, dataset=dataset_array_free, xp=jnp + ) + ) + + assert figure_of_merit_numpy == pytest.approx(figure_of_merit_dense, rel=1.0e-8) + assert float(figure_of_merit_jit(0.1)) == pytest.approx( + figure_of_merit_numpy, rel=1.0e-8 + ) + + # The lens light's parameter is traced into the data term, not frozen at its first value. + assert float(figure_of_merit_jit(0.2)) == pytest.approx( + figure_of_merit_from(intensity=0.2, dataset=interferometer_7, xp=np), + rel=1.0e-8, + ) - with pytest.raises(aa.exc.DatasetException): + # The log likelihood (with an inversion: the identity on the total model image) also matches under jit. + def log_likelihood_from(intensity, dataset, xp): + return al.FitInterferometer( + dataset=dataset, + tracer=_lens_light_tracer(intensity=intensity, source=source), + xp=xp, + ).log_likelihood + + log_likelihood_jit = jax.jit( + lambda intensity: log_likelihood_from( + intensity, dataset=dataset_array_free, xp=jnp + ) + ) + + for intensity in (0.1, 0.2): + assert float(log_likelihood_jit(intensity)) == pytest.approx( + log_likelihood_from(intensity=intensity, dataset=interferometer_7, xp=np), + rel=1.0e-8, + ) + + +class _FitInterferometerNoiseMapOverride(al.FitInterferometer): + """ + A fit whose `noise_map` is not the dataset's own, as a subclass scaling the noise-map would produce. + """ + + noise_map_override = None + + @property + def noise_map(self): + return self.noise_map_override + + +@pytest.mark.parametrize("source", [None, "pixelization"]) +def test__array_free_dataset__noise_map_override__raises(interferometer_7, source): + """ + An array-free dataset's likelihood terms were all precomputed from its own noise-map, so a fit overriding + the noise-map must raise rather than return a silently wrong likelihood (an unchanged chi-squared with a + switched noise normalization, or the subtracted dirty image paired with the unsubtracted data term). The + same override on the in-memory dataset is unaffected. + """ + dataset_array_free = _array_free_dataset_from(interferometer_7) + + tracer = _lens_light_tracer(source=source) + + for scale in (1.0, 2.0): + _FitInterferometerNoiseMapOverride.noise_map_override = aa.VisibilitiesNoiseMap( + interferometer_7.noise_map * scale + ) + + fit = _FitInterferometerNoiseMapOverride( + dataset=dataset_array_free, tracer=tracer + ) + + for name in ("figure_of_merit", "log_likelihood", "sparse_chi_squared"): + with pytest.raises( + aa.exc.DatasetException, match="array-free.*cannot be overridden" + ): + getattr(fit, name) + + fit_in_memory = _FitInterferometerNoiseMapOverride( + dataset=interferometer_7, tracer=tracer + ) + + assert np.isfinite(fit_in_memory.figure_of_merit) + + assert np.isfinite( al.FitInterferometer(dataset=dataset_array_free, tracer=tracer).figure_of_merit + ) + + +def test__fit_figure_of_merit__array_free_dataset__lens_light_profile__never_forms_visibilities( + interferometer_7, monkeypatch +): + dataset_array_free = _array_free_dataset_from(interferometer_7) + + calls = [] + + def spy(*args, **kwargs): + calls.append(1) + raise AssertionError("an array-free fit formed visibilities") + + monkeypatch.setattr(aa.TransformerNUFFT, "visibilities_from", spy) + monkeypatch.setattr(aa.TransformerDFT, "visibilities_from", spy) + + for source in (None, "sersic", "pixelization", "mge"): + fit = al.FitInterferometer( + dataset=dataset_array_free, tracer=_lens_light_tracer(source=source) + ) + + assert np.isfinite(fit.figure_of_merit) + assert np.isfinite(fit.log_likelihood) + assert "profile_visibilities" not in fit.__dict__ + + assert calls == [] + + +def test__model_data__array_free_dataset__raises_pointing_at_natural_images( + interferometer_7, +): + dataset_array_free = _array_free_dataset_from(interferometer_7) + + for source in (None, "pixelization"): + fit = al.FitInterferometer( + dataset=dataset_array_free, tracer=_lens_light_tracer(source=source) + ) + + for name in ( + "model_data", + "galaxy_model_visibilities_dict", + "model_visibilities_of_planes_list", + ): + with pytest.raises( + aa.exc.DatasetException, match="array-free.*model_image_natural" + ): + getattr(fit, name) + + expected = fit.profile_image.array + + if fit.inversion is not None: + expected = expected + fit.inversion.mapped_reconstructed_data.array + + assert np.abs(fit.profile_image.array).max() > 0.0 + np.testing.assert_allclose( + fit.model_image_natural.array, expected, rtol=1.0e-12 + ) def test__natural_dirty_images__array_free_pixelized_source_fit(interferometer_7):