From aeaf7493b1f332cd44bc9c9283eb5d3e596ab3c9 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Tue, 24 Nov 2026 17:05:41 +0000 Subject: [PATCH] feat: lens fits use the lazy sparse operator; point/weak on the shared setup mixin (5C-3b) FitImaging / FitInterferometer pass self.sparse_operator (resolved through sparse_operator_for) into DatasetInterface and into the interferometer chi-squared, precomputed-data-term and profile-term helpers, so the inversion and the dirty-image correction share one operator. AnalysisSetupNoOperator becomes a thin subclass of PyAutoGalaxy's AnalysisSetupMixin, removing the duplicated setup-resolution code. Closes #885 (likelihood-lifecycle phase 5C-3b). Co-Authored-By: Claude Opus 5.5 --- autolens/analysis/analysis/setup.py | 120 ++-------- autolens/imaging/fit_imaging.py | 2 +- autolens/interferometer/fit_interferometer.py | 10 +- .../aggregator/test_fit_dataset_setup.py | 127 ++++++++++ .../analysis/analysis/test_setup_mixin.py | 31 +++ test_autolens/imaging/test_fit_imaging.py | 183 +++++++++++++++ .../interferometer/test_fit_interferometer.py | 221 ++++++++++++++++++ 7 files changed, 586 insertions(+), 108 deletions(-) create mode 100644 test_autolens/aggregator/test_fit_dataset_setup.py create mode 100644 test_autolens/analysis/analysis/test_setup_mixin.py diff --git a/autolens/analysis/analysis/setup.py b/autolens/analysis/analysis/setup.py index e635731c2..839a9db4e 100644 --- a/autolens/analysis/analysis/setup.py +++ b/autolens/analysis/analysis/setup.py @@ -7,7 +7,8 @@ dataset (attaching the sparse operator it names). `AnalysisPoint` and `AnalysisWeak` do not fit an `aa.Imaging` / `aa.Interferometer`, so their setup has no operator to attach (operator `"na"` or `"dense"`); `AnalysisSetupNoOperator` resolves and applies the rest of it (backend, threads, banner, -`files/setup.json`), reusing the helpers of `autogalaxy.analysis.setup_util`. +`files/setup.json`) through PyAutoGalaxy's shared `AnalysisSetupMixin` +(`autogalaxy.analysis.analysis.setup`). `raise_if_setup_unresolved` is called at the top of every lens `log_likelihood_function`. A setup is resolved in `modify_before_fit`, which a `FactorGraphModel` does not call on its factors, so a setup @@ -20,7 +21,8 @@ import autofit as af import autoarray as aa -from autogalaxy.analysis import setup_util +from autogalaxy.analysis.analysis.setup import AnalysisSetupMixin +from autogalaxy.analysis.setup_util import setup_environment # noqa: F401 (kept importable from here) from autolens import exc @@ -75,121 +77,29 @@ def raise_if_setup_unresolved(analysis): ) -def setup_environment(): - """ - The detected hardware (`autonerves.environment.Environment`), or `None` if detection fails. - """ - try: - from autonerves.environment import Environment - - return Environment.detect() - except Exception as e: - logger.debug(f"Setup: hardware detection failed: {e}") - return None - - -class AnalysisSetupNoOperator: +class AnalysisSetupNoOperator(AnalysisSetupMixin): """ Mixin resolving the compute `setup` of an analysis whose dataset has no operator to attach (`AnalysisPoint`, `AnalysisWeak`). - The subclass calls `_init_setup(setup)` in its constructor, `resolve_setup(model)` first in its + It is a thin subclass of PyAutoGalaxy's `AnalysisSetupMixin`, which holds the one shared resolution + path (`_init_setup`, `resolve_setup`, `_log_setup_auto_would_choose`, `save_setup`). The subclass + calls `_init_setup(setup)` in its constructor, `resolve_setup(model)` first in its `modify_before_fit`, `save_setup(paths)` in its `save_attributes`, and implements `setup_key_from` - (the `(dataset_type, variant)` rule key of `aa.Setup.auto`). + (the `(dataset_type, variant)` rule key of `aa.Setup.auto`). There is no dataset operator to attach + or check, so `_apply_resolved_setup` keeps the mixin's do-nothing default and the banner has no note. """ - def _init_setup(self, setup): - """ - Store the normalised `setup` input (`None`, `"auto"` or an `aa.Setup`, see - `setup_util.setup_input_from`); the resolved setup is set by `resolve_setup`. - """ - self.setup_input = setup_util.setup_input_from(setup) - self.setup = None - self.setup_chosen_by = None - def setup_key_from(self, model: af.Collection) -> Tuple[str, str]: """ The `(dataset_type, variant)` rule key of `aa.Setup.auto` for this analysis and model. """ raise NotImplementedError - def resolve_setup(self, model: af.Collection): - """ - Resolve the `setup` input of the analysis against the model and apply it. - - With no `setup` input nothing changes: one log line reports what `setup="auto"` would choose (any - error working that out is ignored). - - With `setup="auto"` the setup is chosen by `aa.Setup.auto` from `setup_key_from(model)`; - `PYAUTO_SETUP=` overrides it. An explicit `aa.Setup` or setup_id is used as given. The - resolved setup then: - - - sets the analysis backend (`_use_jax = setup.backend == "jax"`, falling back to numpy when JAX is - disabled or not installed, as `af.Analysis` does); `_xp` follows, as it derives from `_use_jax`; - - pins the thread pools (`setup.apply_threads()`); - - is logged as the setup banner line and stored as `self.setup`. - - There is no dataset operator to attach or check. - """ - setup_input = getattr(self, "setup_input", None) - - if setup_input is None: - self._log_setup_auto_would_choose(model=model) - return - - environment = setup_environment() - - if setup_input == setup_util.SETUP_AUTO: - setup = aa.Setup.auto(*self.setup_key_from(model), environment=environment) - chosen_by = setup_util.chosen_by_from(setup=setup, auto=True) - else: - setup = setup_input - chosen_by = setup_util.chosen_by_from(setup=setup, auto=False) - - self._use_jax = setup_util.use_jax_from(setup.backend == "jax") - - setup.apply_threads() - - self.setup = setup - self.setup_chosen_by = chosen_by - - logger.info( - setup_util.setup_banner_from( - setup=setup, - chosen_by=chosen_by, - environment=environment, - ) - ) - - def _log_setup_auto_would_choose(self, model: af.Collection): - """ - Log one line reporting the setup `setup="auto"` would choose, applying nothing. - """ - try: - setup = aa.Setup.auto( - *self.setup_key_from(model), environment=setup_environment() - ) - except Exception as e: - logger.debug( - f"Setup: could not work out what setup='auto' would choose: {e}" - ) - return - - logger.info( - f"Setup: auto would choose {setup.setup_id} (rule {setup.rule_id}); " - f'pass setup="auto" to use it' - ) - - def save_setup(self, paths: af.DirectoryPaths): + def setup_key_and_note_from( + self, model: af.Collection + ) -> Tuple[Tuple[str, str], Optional[str]]: """ - Write the resolved setup to `files/setup.json`, when a setup was resolved. + The rule key of `setup_key_from(model)`, with no banner note. """ - setup: Optional[aa.Setup] = getattr(self, "setup", None) - - if setup is not None: - paths.save_json( - name="setup", - object_dict=setup_util.setup_dict_from( - setup=setup, chosen_by=self.setup_chosen_by - ), - ) + return self.setup_key_from(model), None diff --git a/autolens/imaging/fit_imaging.py b/autolens/imaging/fit_imaging.py index 4425e5ebb..971799a41 100644 --- a/autolens/imaging/fit_imaging.py +++ b/autolens/imaging/fit_imaging.py @@ -160,7 +160,7 @@ def tracer_to_inversion(self) -> TracerToInversion: noise_map=self.noise_map, grids=self.grids, psf=self.dataset.psf, - sparse_operator=self.dataset.sparse_operator, + sparse_operator=self.sparse_operator, ) return TracerToInversion( diff --git a/autolens/interferometer/fit_interferometer.py b/autolens/interferometer/fit_interferometer.py index cabcb168e..f0d873691 100644 --- a/autolens/interferometer/fit_interferometer.py +++ b/autolens/interferometer/fit_interferometer.py @@ -188,7 +188,11 @@ def sparse_chi_squared(self): `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) + return sparse_chi_squared_from( + fit=self, + galaxies=self.tracer.galaxies, + sparse_operator=self.sparse_operator, + ) @property def _uses_precomputed_data_term(self) -> bool: @@ -203,6 +207,7 @@ def _uses_precomputed_data_term(self) -> bool: galaxies=self.tracer.galaxies, data=self.data, noise_map=self.noise_map, + sparse_operator=self.sparse_operator, ) @property @@ -235,6 +240,7 @@ def tracer_to_inversion(self) -> TracerToInversion: galaxies=self.tracer.galaxies, image=self.profile_image, xp=self._xp, + sparse_operator=self.sparse_operator, ) if self._uses_precomputed_data_term: @@ -248,7 +254,7 @@ def tracer_to_inversion(self) -> TracerToInversion: noise_map=self.noise_map, grids=self.grids, transformer=self.dataset.transformer, - sparse_operator=self.dataset.sparse_operator, + sparse_operator=self.sparse_operator, sparse_dirty_image=sparse_dirty_image, data_term=data_term, ) diff --git a/test_autolens/aggregator/test_fit_dataset_setup.py b/test_autolens/aggregator/test_fit_dataset_setup.py new file mode 100644 index 000000000..65d27d632 --- /dev/null +++ b/test_autolens/aggregator/test_fit_dataset_setup.py @@ -0,0 +1,127 @@ +""" +A lens `FitImaging` / `FitInterferometer` reloaded by the aggregator reapplies the compute setup the search +wrote to `files/setup.json`: the lens aggregator loads its datasets through PyAutoGalaxy's `_imaging_from` / +`_interferometer_from`, which call `agg_util.dataset_with_setup_from`. +""" +from types import SimpleNamespace + +import pytest + +import autofit as af +import autoarray as aa +import autogalaxy as ag +import autolens as al + +from autogalaxy.analysis import setup_util +from autogalaxy.analysis.analysis.dataset import AnalysisDataset +from autogalaxy.interferometer.model.analysis import interferometer_hdu_list_from + +from autolens.aggregator.fit_imaging import _fit_imaging_from +from autolens.aggregator.fit_interferometer import _fit_interferometer_from + + +def _imaging_hdu_list_from(dataset, monkeypatch): + """The `dataset.fits` HDU list `AnalysisImaging.save_attributes` writes for `dataset`.""" + captured = [] + + monkeypatch.setattr( + AnalysisDataset, + "_save_dataset_fits", + staticmethod(lambda paths, hdu_list: captured.append(hdu_list)), + ) + + analysis = ag.AnalysisImaging(dataset=dataset, use_jax=False) + analysis.save_attributes(paths=SimpleNamespace(save_json=lambda **kwargs: None)) + + monkeypatch.undo() + + return captured[0] + + +def _lens_instance(): + pixelization = al.Pixelization( + mesh=al.mesh.RectangularUniform(shape=(3, 3)), + regularization=al.reg.Constant(coefficient=1.0), + ) + + model = af.Collection( + galaxies=af.Collection( + lens=al.Galaxy( + redshift=0.5, + bulge=al.lp.Sersic(intensity=0.1, centre=(0.05, 0.05)), + mass=al.mp.IsothermalSph(einstein_radius=0.2), + ), + source=al.Galaxy(redshift=1.0, pixelization=pixelization), + ), + ) + + return model.instance_from_prior_medians() + + +def _fake_fit(values): + """A `Fit` stand-in whose `value(name)` returns `values.get(name)` (None for a missing file).""" + return SimpleNamespace( + children=[], instance=_lens_instance(), value=lambda name: values.get(name) + ) + + +def _setup_dict(setup_id): + return setup_util.setup_dict_from( + setup=setup_util.setup_input_from(setup_id), + chosen_by=setup_util.CHOSEN_BY_EXPLICIT, + ) + + +def test__fit_imaging_from__setup_json__reapplied(masked_imaging_7x7, monkeypatch): + pytest.importorskip("numba") + + hdu_list = _imaging_hdu_list_from(masked_imaging_7x7, monkeypatch) + + fit_reloaded_no_setup = _fit_imaging_from(fit=_fake_fit({"dataset": hdu_list}))[0] + + assert fit_reloaded_no_setup.dataset.setup is None + assert fit_reloaded_no_setup.sparse_operator is None + + fit_reloaded = _fit_imaging_from( + fit=_fake_fit( + {"dataset": hdu_list, "setup": _setup_dict("numba_cpu_sparse_fp64")} + ) + )[0] + + assert fit_reloaded.dataset.setup.setup_id == "numba_cpu_sparse_fp64" + assert fit_reloaded.dataset.sparse_operator is not None + + # The reloaded lens fit takes the sparse route and reproduces the search's (dense) figure of merit. + assert fit_reloaded.inversion.dataset.sparse_operator is ( + fit_reloaded.dataset.sparse_operator + ) + assert fit_reloaded.figure_of_merit == pytest.approx( + fit_reloaded_no_setup.figure_of_merit, rel=1.0e-6 + ) + + +def test__fit_interferometer_from__setup_json__reapplied(interferometer_7): + pytest.importorskip("finufft") + + values = { + "dataset": interferometer_hdu_list_from(dataset=interferometer_7), + "transformer_class": aa.TransformerDFT, + } + + fit_reloaded_no_setup = _fit_interferometer_from(fit=_fake_fit(values))[0] + + assert fit_reloaded_no_setup.dataset.setup is None + assert fit_reloaded_no_setup.sparse_operator is None + + values["setup"] = _setup_dict("numba_cpu_sparse_fp64_wtilde") + + fit_reloaded = _fit_interferometer_from(fit=_fake_fit(values))[0] + + assert fit_reloaded.dataset.setup.setup_id == "numba_cpu_sparse_fp64_wtilde" + assert fit_reloaded.dataset.sparse_operator is not None + assert fit_reloaded.inversion.dataset.sparse_operator is ( + fit_reloaded.dataset.sparse_operator + ) + assert fit_reloaded.log_likelihood == pytest.approx( + fit_reloaded_no_setup.log_likelihood, rel=1.0e-8 + ) diff --git a/test_autolens/analysis/analysis/test_setup_mixin.py b/test_autolens/analysis/analysis/test_setup_mixin.py new file mode 100644 index 000000000..1faac862e --- /dev/null +++ b/test_autolens/analysis/analysis/test_setup_mixin.py @@ -0,0 +1,31 @@ +""" +The lens analyses share PyAutoGalaxy's one setup-resolution path (`AnalysisSetupMixin`). +""" +import autolens as al + +from autogalaxy.analysis.analysis.setup import AnalysisSetupMixin + +from autolens.analysis.analysis.setup import AnalysisSetupNoOperator + + +def test__lens_analyses__setup_mixin_in_mro_once(): + assert issubclass(AnalysisSetupNoOperator, AnalysisSetupMixin) + + for cls in ( + al.AnalysisPoint, + al.AnalysisWeak, + al.AnalysisImaging, + al.AnalysisInterferometer, + ): + assert cls.__mro__.count(AnalysisSetupMixin) == 1 + + +def test__setup_no_operator__key_and_note_from_setup_key(): + class Analysis(AnalysisSetupNoOperator): + def setup_key_from(self, model): + return ("point", "isothermal") + + assert Analysis().setup_key_and_note_from(model=None) == ( + ("point", "isothermal"), + None, + ) diff --git a/test_autolens/imaging/test_fit_imaging.py b/test_autolens/imaging/test_fit_imaging.py index ee2e6110b..eac2c8d06 100644 --- a/test_autolens/imaging/test_fit_imaging.py +++ b/test_autolens/imaging/test_fit_imaging.py @@ -3,6 +3,7 @@ import numpy as np import pytest +import autoarray as aa import autolens as al @@ -1213,3 +1214,185 @@ def test__galaxy_image_dicts__add_ordinary_and_linear_light(masked_imaging_7x7): np.testing.assert_allclose( fit.galaxy_model_image_dict[galaxy].array, fit.model_data.array ) + + +# The lazy sparse operator (`dataset.sparse_operator_for`) reached through `fit.sparse_operator`, +# which the lens fit's `tracer_to_inversion` passes to every per-plane `DatasetInterface`. + +LAZY_ON = aa.Settings(lazy_sparse_operator="auto") + + +@pytest.fixture(name="no_ambient_setup") +def make_no_ambient_setup(monkeypatch): + # An ambient `PYAUTO_SETUP=auto` turns the lazy policy on; these tests set it explicitly. + monkeypatch.delenv("PYAUTO_SETUP", raising=False) + + +def _lens_pixelized_source_tracer(): + pixelization = al.Pixelization( + mesh=al.mesh.RectangularUniform(shape=(3, 3)), + regularization=al.reg.Constant(coefficient=1.0), + ) + + lens = al.Galaxy( + redshift=0.5, + bulge=al.lp.Sersic(intensity=0.1), + mass=al.mp.IsothermalSph(einstein_radius=0.2), + ) + source = al.Galaxy(redshift=1.0, pixelization=pixelization) + + return al.Tracer(galaxies=[lens, source]) + + +def test__sparse_operator__lazy_policy_on__pixelized_source__matches_dense_built_once_and_reused( + masked_imaging_7x7, no_ambient_setup +): + pytest.importorskip("numba") + + tracer = _lens_pixelized_source_tracer() + + fit_dense = al.FitImaging(dataset=masked_imaging_7x7, tracer=tracer) + + assert fit_dense.sparse_operator is None + assert isinstance(fit_dense.inversion, aa.InversionImagingMapping) + assert masked_imaging_7x7._lazy_sparse_operator is None + + fit = al.FitImaging(dataset=masked_imaging_7x7, tracer=tracer, settings=LAZY_ON) + + operator = fit.sparse_operator + + assert operator is not None + assert masked_imaging_7x7.sparse_operator is None + assert masked_imaging_7x7._lazy_sparse_operator is operator + assert fit.inversion.dataset.sparse_operator is operator + assert not isinstance(fit.inversion, aa.InversionImagingMapping) + + assert fit.figure_of_merit == pytest.approx(fit_dense.figure_of_merit, rel=1.0e-6) + + # A second fit reuses the operator cached on the dataset rather than building another. + fit_again = al.FitImaging( + dataset=masked_imaging_7x7, tracer=tracer, settings=LAZY_ON + ) + + assert fit_again.sparse_operator is operator + assert fit_again.figure_of_merit == pytest.approx(fit.figure_of_merit, rel=1.0e-12) + + +def test__sparse_operator__lazy_policy_on__cached_per_fit( + masked_imaging_7x7, no_ambient_setup, monkeypatch +): + calls = [] + + original = aa.Imaging.sparse_operator_for + + def counting(self, *args, **kwargs): + calls.append(kwargs) + return original(self, *args, **kwargs) + + monkeypatch.setattr(aa.Imaging, "sparse_operator_for", counting) + + fit = al.FitImaging( + dataset=masked_imaging_7x7, + tracer=_lens_pixelized_source_tracer(), + settings=LAZY_ON, + ) + + fit.sparse_operator + fit.sparse_operator + + assert len(calls) == 1 + assert calls[0]["needs_operator"] is True + assert calls[0]["settings"] is LAZY_ON + + +def test__sparse_operator__lazy_policy_on__parametric_and_mge_only_builds_nothing( + masked_imaging_7x7, no_ambient_setup, monkeypatch +): + built = [] + monkeypatch.setattr( + aa.Imaging, "apply_sparse_operator_cpu", lambda self: built.append(1) + ) + + lens = al.Galaxy( + redshift=0.5, + bulge=al.lp.Sersic(intensity=0.1), + mass=al.mp.IsothermalSph(einstein_radius=0.2), + ) + source = al.Galaxy( + redshift=1.0, + bulge=al.lp_basis.Basis( + profile_list=[ + al.lp_linear.Gaussian(sigma=0.5), + al.lp_linear.Gaussian(sigma=1.5), + ] + ), + ) + + for galaxies in ([lens, al.Galaxy(redshift=1.0, bulge=al.lp.Sersic())], [lens, source]): + fit = al.FitImaging( + dataset=masked_imaging_7x7, + tracer=al.Tracer(galaxies=galaxies), + settings=LAZY_ON, + ) + + assert fit.sparse_operator is None + fit.figure_of_merit + + assert built == [] + assert masked_imaging_7x7._lazy_sparse_operator is None + + +def test__sparse_operator__lazy_policy_on__jax_xp_builds_nothing( + masked_imaging_7x7, no_ambient_setup, monkeypatch +): + pytest.importorskip("jax") + + import jax.numpy as jnp + + built = [] + monkeypatch.setattr( + aa.Imaging, "apply_sparse_operator_cpu", lambda self: built.append(1) + ) + + fit = al.FitImaging( + dataset=masked_imaging_7x7, + tracer=_lens_pixelized_source_tracer(), + settings=LAZY_ON, + xp=jnp, + ) + + assert fit.sparse_operator is None + assert built == [] + + +def test__sparse_operator__linear_light_only__attached_operator_unchanged( + masked_imaging_7x7, no_ambient_setup +): + pytest.importorskip("numba") + + dataset = masked_imaging_7x7.apply_sparse_operator_cpu() + + lens = al.Galaxy( + redshift=0.5, + bulge=al.lp_linear.Sersic(), + mass=al.mp.IsothermalSph(einstein_radius=0.2), + ) + source = al.Galaxy(redshift=1.0, bulge=al.lp_linear.Exponential()) + + tracer = al.Tracer(galaxies=[lens, source]) + + for settings in (None, LAZY_ON): + fit = al.FitImaging(dataset=dataset, tracer=tracer, settings=settings) + + # No mappers, yet the attached operator is still passed to the inversion, as before. + assert fit.total_mappers == 0 + assert fit.sparse_operator is dataset.sparse_operator + assert fit.inversion.dataset.sparse_operator is dataset.sparse_operator + + fit_dense = al.FitImaging( + dataset=masked_imaging_7x7, tracer=tracer, settings=settings + ) + + assert fit.figure_of_merit == pytest.approx( + fit_dense.figure_of_merit, rel=1.0e-6 + ) diff --git a/test_autolens/interferometer/test_fit_interferometer.py b/test_autolens/interferometer/test_fit_interferometer.py index 9a6e0bac7..9ed0afbc3 100644 --- a/test_autolens/interferometer/test_fit_interferometer.py +++ b/test_autolens/interferometer/test_fit_interferometer.py @@ -1254,3 +1254,224 @@ def test__galaxy_image_dict__adds_ordinary_and_linear_light( np.testing.assert_allclose( adapt_image.array, np.maximum(expected.array, floor * np.max(expected.array)) ) + + +# The lazy sparse operator (`dataset.sparse_operator_for`) reached through `fit.sparse_operator`, which +# the lens fit passes to its `DatasetInterface` and to the profile-subtraction helpers. + +LAZY_ON = aa.Settings(lazy_sparse_operator="auto") + + +@pytest.fixture(name="no_ambient_setup") +def make_no_ambient_setup(monkeypatch): + # An ambient `PYAUTO_SETUP=auto` turns the lazy policy on; these tests set it explicitly. + monkeypatch.delenv("PYAUTO_SETUP", raising=False) + + +def _lens_pixelized_source_tracer(lens_light: bool): + pixelization = al.Pixelization( + mesh=al.mesh.RectangularUniform(shape=(3, 3)), + regularization=al.reg.Constant(coefficient=1.0), + ) + + lens = al.Galaxy( + redshift=0.5, + bulge=( + al.lp.Sersic(intensity=0.1, centre=(0.05, 0.05)) if lens_light else None + ), + mass=al.mp.IsothermalSph(einstein_radius=0.2), + ) + source = al.Galaxy(redshift=1.0, pixelization=pixelization) + + return al.Tracer(galaxies=[lens, source]) + + +def test__sparse_operator__lazy_policy_off__dense_and_nothing_built( + interferometer_7, no_ambient_setup +): + fit = al.FitInterferometer( + dataset=interferometer_7, tracer=_lens_pixelized_source_tracer(lens_light=False) + ) + + assert fit.sparse_operator is None + assert isinstance(fit.inversion, aa.InversionInterferometerMapping) + assert interferometer_7._lazy_sparse_operator is None + + +def test__sparse_operator__lazy_policy_on__pixelized_source__matches_dense_built_once( + interferometer_7, no_ambient_setup +): + pytest.importorskip("finufft") + + tracer = _lens_pixelized_source_tracer(lens_light=False) + + fit_dense = al.FitInterferometer(dataset=interferometer_7, tracer=tracer) + + fit = al.FitInterferometer( + dataset=interferometer_7, tracer=tracer, settings=LAZY_ON + ) + + operator = fit.sparse_operator + + assert operator is not None + assert interferometer_7.sparse_operator is None + assert interferometer_7._lazy_sparse_operator is operator + assert isinstance(fit.inversion, aa.InversionInterferometerSparse) + assert fit.inversion.dataset.sparse_operator is operator + + # The lazily built operator is built from the dataset's own visibilities and noise-map, so its cached + # data term is valid and the inversion reads it instead of the visibilities. + assert fit._uses_precomputed_data_term + assert fit.inversion.dataset.data is None + + assert fit.log_likelihood == pytest.approx(fit_dense.log_likelihood, rel=1.0e-8) + assert fit.figure_of_merit == pytest.approx(fit_dense.figure_of_merit, rel=1.0e-8) + + fit_again = al.FitInterferometer( + dataset=interferometer_7, tracer=tracer, settings=LAZY_ON + ) + + assert fit_again.sparse_operator is operator + + +def test__sparse_operator__lazy_policy_on__pixelized_source_and_lens_light__dirty_image_correction_matches_dense( + interferometer_7, no_ambient_setup +): + pytest.importorskip("finufft") + + tracer = _lens_pixelized_source_tracer(lens_light=True) + + fit_dense = al.FitInterferometer(dataset=interferometer_7, tracer=tracer) + + fit = al.FitInterferometer( + dataset=interferometer_7, tracer=tracer, settings=LAZY_ON + ) + + operator = fit.sparse_operator + + assert operator is not None + assert isinstance(fit.inversion, aa.InversionInterferometerSparse) + assert fit.inversion.dataset.sparse_operator is operator + + # The lens light is subtracted, so the inversion's dirty image is corrected (`d~ - W~ i_p`) with the + # same, lazily built, operator, and the array path is kept. + assert fit.inversion.dataset.sparse_dirty_image is not None + assert not fit._uses_precomputed_data_term + assert fit.inversion.dataset.data is not None + + from autogalaxy.interferometer.fit_interferometer import sparse_dirty_image_from + + expected_dirty_image = sparse_dirty_image_from( + dataset=interferometer_7, + galaxies=tracer.galaxies, + image=fit.profile_image, + sparse_operator=operator, + ) + + np.testing.assert_allclose( + fit.inversion.dataset.sparse_dirty_image, expected_dirty_image, rtol=1.0e-12 + ) + + assert fit.log_likelihood == pytest.approx(fit_dense.log_likelihood, rel=1.0e-8) + assert fit.log_evidence == pytest.approx(fit_dense.log_evidence, rel=1.0e-8) + + # The sparse chi-squared reads the same operator and is the dense residual chi-squared. + assert fit.sparse_chi_squared == pytest.approx(fit_dense.chi_squared, rel=1.0e-8) + + +def test__sparse_operator__lazy_policy_on__parametric_and_mge_only_builds_nothing( + interferometer_7, no_ambient_setup, monkeypatch +): + built = [] + monkeypatch.setattr( + aa.Interferometer, + "apply_sparse_operator", + lambda self, **kwargs: built.append(1), + ) + + lens = al.Galaxy( + redshift=0.5, + bulge=al.lp.Sersic(intensity=0.1, centre=(0.05, 0.05)), + mass=al.mp.IsothermalSph(einstein_radius=0.2), + ) + source_mge = al.Galaxy( + redshift=1.0, + bulge=al.lp_basis.Basis( + profile_list=[ + al.lp_linear.Gaussian(sigma=0.5, centre=(0.05, 0.05)), + al.lp_linear.Gaussian(sigma=1.5, centre=(0.05, 0.05)), + ] + ), + ) + source_parametric = al.Galaxy(redshift=1.0, bulge=al.lp.Sersic(intensity=0.1)) + + for source in (source_parametric, source_mge): + fit = al.FitInterferometer( + dataset=interferometer_7, + tracer=al.Tracer(galaxies=[lens, source]), + settings=LAZY_ON, + ) + + assert fit.sparse_operator is None + fit.figure_of_merit + + assert built == [] + assert interferometer_7._lazy_sparse_operator is None + + +def test__sparse_operator__lazy_policy_on__jax_xp_builds_nothing( + interferometer_7, no_ambient_setup, monkeypatch +): + pytest.importorskip("jax") + + import jax.numpy as jnp + + built = [] + monkeypatch.setattr( + aa.Interferometer, + "apply_sparse_operator", + lambda self, **kwargs: built.append(1), + ) + + fit = al.FitInterferometer( + dataset=interferometer_7, + tracer=_lens_pixelized_source_tracer(lens_light=False), + settings=LAZY_ON, + xp=jnp, + ) + + assert fit.sparse_operator is None + assert built == [] + + +def test__sparse_operator__linear_light_only__attached_operator_unchanged( + interferometer_7, no_ambient_setup +): + dataset_sparse = interferometer_7.apply_sparse_operator(use_jax=False) + + lens = al.Galaxy( + redshift=0.5, + bulge=al.lp_linear.Gaussian(sigma=0.5, centre=(0.05, 0.05)), + mass=al.mp.IsothermalSph(einstein_radius=0.2), + ) + source = al.Galaxy( + redshift=1.0, bulge=al.lp_linear.Gaussian(sigma=1.5, centre=(0.05, 0.05)) + ) + + tracer = al.Tracer(galaxies=[lens, source]) + + for settings in (None, LAZY_ON): + fit = al.FitInterferometer( + dataset=dataset_sparse, tracer=tracer, settings=settings + ) + + assert fit.total_mappers == 0 + assert fit.sparse_operator is dataset_sparse.sparse_operator + assert fit.inversion.dataset.sparse_operator is dataset_sparse.sparse_operator + assert fit._uses_precomputed_data_term + + fit_dense = al.FitInterferometer( + dataset=interferometer_7, tracer=tracer, settings=settings + ) + + assert fit.log_likelihood == pytest.approx(fit_dense.log_likelihood, rel=1.0e-8)