diff --git a/autogalaxy/abstract_fit.py b/autogalaxy/abstract_fit.py index ac89cc6ab..90716aa70 100644 --- a/autogalaxy/abstract_fit.py +++ b/autogalaxy/abstract_fit.py @@ -1,4 +1,5 @@ from __future__ import annotations +import functools from typing import TYPE_CHECKING, Dict, Optional import numpy as np @@ -71,19 +72,44 @@ def perform_inversion(self) -> bool: return self.model_obj.perform_inversion - @property + @functools.cached_property def sparse_operator(self) -> Optional[aa.ImagingSparseOperator]: """ - Only call the `sparse_operator` property of a dataset used to perform efficient linear algebra calculations if - the Settings()` object has `use_sparse_operator=True`, to avoid unnecessary computation. + The sparse operator this fit's inversion uses for its linear algebra, or `None` for the dense + mapping-matrix route. It is the one choke point every `aa.DatasetInterface` of a fit, and the + interferometer profile-subtraction helpers, read the operator from, so the inversion and the + dirty-image correction always use the same object. + + It is `dataset.sparse_operator_for(xp, needs_operator, settings)`: + + - an operator attached to the dataset (by `apply_setup` / `apply_sparse_operator`) is returned + whatever the fit, so a fit whose light is entirely linear (linear light profiles, MGE) keeps + using it, as before; + - otherwise, with the lazy sparse operator policy on (`aa.Settings(lazy_sparse_operator="auto")`), + a fit with a pixelization (`total_mappers > 0`) on NumPy gets the operator the dataset builds + on first use and caches; a fit without a pixelization, or a JAX fit, never triggers a build; + - with the policy off (the default) it is the attached operator or `None`, exactly as before. + + A dataset without `sparse_operator_for` (e.g. a duck-typed dataset) falls back to its + `sparse_operator`. + + The value is cached on the fit. `register_instance_pytree` adds every `cached_property` to a + fit's `no_flatten` set, so JAX pytree flattening treats it as static data, never a child. Returns ------- - The sparse operator used for efficient linear algebra calculations for this inversion, if enabled. + The sparse operator used for efficient linear algebra calculations for this inversion, if any. """ - if self.dataset.sparse_operator is not None: - if self.total_mappers > 0: - return self.dataset.sparse_operator + sparse_operator_for = getattr(self.dataset, "sparse_operator_for", None) + + if sparse_operator_for is None: + return getattr(self.dataset, "sparse_operator", None) + + return sparse_operator_for( + xp=self._xp, + needs_operator=self.total_mappers > 0, + settings=self.settings, + ) @property def inversion(self) -> Optional[aa.Inversion]: diff --git a/autogalaxy/aggregator/agg_util.py b/autogalaxy/aggregator/agg_util.py index 4e6784f96..f1687d9f9 100644 --- a/autogalaxy/aggregator/agg_util.py +++ b/autogalaxy/aggregator/agg_util.py @@ -18,8 +18,12 @@ - `mesh_grids_of_planes_list_from` — Loads the pre-computed image-plane mesh grids that were saved during the fit, removing any stochastic variation when inspecting results offline. +- `dataset_with_setup_from` — Reapplies the compute setup a search wrote to + ``files/setup.json`` to a reloaded dataset, so a reloaded fit takes the same operator + route as the search. """ from __future__ import annotations +import logging import numpy as np from typing import List, Optional @@ -32,6 +36,8 @@ from autogalaxy.analysis.adapt_images.adapt_images import AdaptImages +logger = logging.getLogger(__name__) + def instance_list_from( fit: af.Fit, instance: Optional[af.ModelInstance] = None @@ -230,3 +236,53 @@ def mesh_grids_of_planes_list_from( return fit.child_values(name="preload_mesh_grids_of_planes") except AttributeError: return [None] * total_fits + + +def dataset_with_setup_from(fit: af.Fit, dataset): + """ + Returns a dataset reloaded from a model-fit with the compute setup of that search reapplied, so a fit of + the reloaded dataset takes the same operator route (e.g. the sparse operator) as the search did. + + The setup is read from ``files/setup.json`` (``fit.value(name="setup")``), the plain dict written by + `autogalaxy.analysis.setup_util.setup_dict_from` when the analysis was given a ``setup``, and applied + with ``dataset.apply_setup(setup_id)``. This is best-effort: + + - a search with no ``setup.json`` (no ``setup`` was given) returns the dataset unchanged; + - an array-free dataset (``dataset.data is None``, rebuilt by ``Interferometer.from_sparse_terms``) + already carries its operator and is returned unchanged; + - if the setup cannot be applied here (e.g. a JAX sparse setup reloaded without JAX installed, or an + unreadable file), one warning is logged and the dataset is returned unapplied. + + Parameters + ---------- + fit + A `PyAutoFit` `Fit` object (a directory output or sqlite database entry) of one analysis. + dataset + The reloaded `Imaging` / `Interferometer` dataset, already masked and over-sampled. + """ + if getattr(dataset, "data", None) is None: + return dataset + + try: + setup_dict = fit.value(name="setup") + except Exception as e: + logger.warning( + f"Aggregator: could not read files/setup.json ({e}); the dataset is reloaded without " + f"its search's compute setup." + ) + return dataset + + if setup_dict is None: + return dataset + + setup_id = setup_dict.get("setup_id") if isinstance(setup_dict, dict) else setup_dict + + try: + return dataset.apply_setup(setup_id) + except Exception as e: + logger.warning( + f"Aggregator: the search's compute setup {setup_id!r} could not be reapplied to the " + f"reloaded dataset ({type(e).__name__}: {e}); the dataset is reloaded without it, so a fit " + f"of it may take a different operator route from the search." + ) + return dataset diff --git a/autogalaxy/aggregator/imaging/imaging.py b/autogalaxy/aggregator/imaging/imaging.py index 1660dccd5..9e4348c25 100644 --- a/autogalaxy/aggregator/imaging/imaging.py +++ b/autogalaxy/aggregator/imaging/imaging.py @@ -46,6 +46,11 @@ def _imaging_from( This method combines all of these attributes and returns a `Imaging` object, has the mask applied to the `Imaging` data structure and its settings updated to the values used by the model-fit. + If the search was given a compute `setup` it wrote `files/setup.json`, which is reapplied to the reloaded + dataset (`dataset.apply_setup`, see `agg_util.dataset_with_setup_from`), so a fit of it takes the same + operator route as the search. Without the file the dataset reloads exactly as before; if the setup cannot + be reapplied a warning is logged and the dataset reloads without it. + If multiple `Imaging` objects were fitted simultaneously via analysis summing, the `fit.child_values()` method is instead used to load lists of the data, noise-map, PSF and mask and combine them into a list of `Imaging` objects. @@ -110,6 +115,8 @@ def values_from(hdu: int, cls): over_sample_size_pixelization=over_sample_size_pixelization, ) + dataset = agg_util.dataset_with_setup_from(fit=fit, dataset=dataset) + dataset_list.append(dataset) return dataset_list diff --git a/autogalaxy/aggregator/interferometer/interferometer.py b/autogalaxy/aggregator/interferometer/interferometer.py index 42f89c945..fde8c90ce 100644 --- a/autogalaxy/aggregator/interferometer/interferometer.py +++ b/autogalaxy/aggregator/interferometer/interferometer.py @@ -204,6 +204,12 @@ def _interferometer_from( This method combines all of these attributes and returns a `Interferometer` object, including having its settings updated to the values used by the model-fit. + If the search was given a compute `setup` it wrote `files/setup.json`, which is reapplied to a reloaded + in-memory dataset (`dataset.apply_setup`, see `agg_util.dataset_with_setup_from`), so a fit of it takes + the same transformer and operator route as the search. An array-free dataset already carries its operator + and is not touched. Without the file the dataset reloads exactly as before; if the setup cannot be + reapplied a warning is logged and the dataset reloads without it. + If multiple `Interferometer` objects were fitted simultaneously via analysis summing, the `fit.child_values()` method is instead used to load lists of the data, noise-map, PSF and mask and combine them into a list of `Interferometer` objects. @@ -255,6 +261,8 @@ def _interferometer_from( primary_beam=primary_beam, ) + dataset = agg_util.dataset_with_setup_from(fit=fit, dataset=dataset) + dataset_list.append(dataset) return dataset_list diff --git a/autogalaxy/analysis/analysis/dataset.py b/autogalaxy/analysis/analysis/dataset.py index fddd9772f..cafc84e0b 100644 --- a/autogalaxy/analysis/analysis/dataset.py +++ b/autogalaxy/analysis/analysis/dataset.py @@ -12,6 +12,7 @@ from autogalaxy.analysis.adapt_images.adapt_images import AdaptImages from autogalaxy.cosmology.model import LensingCosmology from autogalaxy.analysis.analysis.analysis import Analysis +from autogalaxy.analysis.analysis.setup import AnalysisSetupMixin from autogalaxy.analysis.result import ResultDataset from autogalaxy.analysis import setup_util @@ -20,7 +21,7 @@ logger.setLevel(level="INFO") -class AnalysisDataset(Analysis): +class AnalysisDataset(AnalysisSetupMixin, Analysis): # Lensing latents (e.g. effective Einstein radius via # `LensCalc.einstein_radius_jit_from`) call into `jax_zero_contour.ZeroSolver`, # which upstream documents as incompatible with `jax.vmap` (uses @@ -86,9 +87,7 @@ def __init__( **kwargs, ) - self.setup_input = setup_util.setup_input_from(setup) - self.setup = None - self.setup_chosen_by = None + self._init_setup(setup) self.dataset = dataset self.adapt_images = adapt_images @@ -147,98 +146,29 @@ def modify_before_fit(self, paths: af.DirectoryPaths, model: af.Collection): @staticmethod def _setup_environment(): """ - The detected hardware (`autonerves.environment.Environment`), or `None` if detection fails. + The detected hardware (`autonerves.environment.Environment`), or `None` if detection fails + (kept for backwards compatibility; see `setup_util.setup_environment`). """ - try: - from autonerves.environment import Environment - - return Environment.detect() - except Exception as e: - logger.debug(f"Setup: hardware detection failed: {e}") - return None + return setup_util.setup_environment() - def resolve_setup(self, model: af.Collection): + def setup_key_and_note_from(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 the rule key of the dataset and - model (see `setup_util.setup_key_from`); `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); - - is applied to the dataset (`dataset.apply_setup`), which attaches the operator it names; - - is checked against the dataset operator and backend with the inversion factory's check, so a - mismatch raises an `InversionException` here rather than rejecting every sample; - - pins the thread pools (`setup.apply_threads()`); - - is logged as the setup banner line and stored as `self.setup`. - - Parameters - ---------- - model - The model fitted by the search, which decides the rule variant (pixelization mesh or MGE). + The `(dataset_type, variant)` rule key of `aa.Setup.auto` for this analysis's dataset and the + model (see `setup_util.setup_key_and_note_from`), plus a note when the nearest rule was used. """ - setup_input = getattr(self, "setup_input", None) - - if setup_input is None: - self._log_setup_auto_would_choose(model=model) - return - - note = None - - if setup_input == setup_util.SETUP_AUTO: - environment = self._setup_environment() - key, note = setup_util.setup_key_and_note_from( - dataset=self.dataset, model=model - ) - setup = aa.Setup.auto(*key, environment=environment) - chosen_by = setup_util.chosen_by_from(setup=setup, auto=True) - else: - environment = self._setup_environment() - 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") + return setup_util.setup_key_and_note_from(dataset=self.dataset, model=model) + def _apply_resolved_setup(self, setup: aa.Setup): + """ + Apply the resolved setup to the dataset (`dataset.apply_setup`), which attaches the operator it + names, then check the operator against the setup and the resolved backend with the inversion + factory's check, so a mismatch raises an `InversionException` here rather than rejecting every + sample. Called by `resolve_setup` (`AnalysisSetupMixin`) after `_use_jax` is set. + """ self.dataset = self.dataset.apply_setup(setup) setup_util.check_setup_consistency(dataset=self.dataset, use_jax=self._use_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, - note=note, - ) - ) - - def _log_setup_auto_would_choose(self, model: af.Collection): - """ - Log one line reporting the setup `setup="auto"` would choose, applying nothing. - """ - try: - key, _ = setup_util.setup_key_and_note_from( - dataset=self.dataset, model=model - ) - setup = aa.Setup.auto(*key, environment=self._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' - ) - @staticmethod def _save_dataset_fits(paths: af.AbstractPaths, hdu_list: HDUList) -> None: """Save the dataset for directory and database aggregators.""" @@ -296,15 +226,7 @@ def save_attributes(self, paths: af.DirectoryPaths): object_dict=to_dict(self.cosmology), ) - 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 - ), - ) + self.save_setup(paths=paths) def save_results(self, paths: af.DirectoryPaths, result: ResultDataset): """ diff --git a/autogalaxy/analysis/analysis/setup.py b/autogalaxy/analysis/analysis/setup.py new file mode 100644 index 000000000..69e9c0155 --- /dev/null +++ b/autogalaxy/analysis/analysis/setup.py @@ -0,0 +1,163 @@ +""" +The one shared resolution path of an analysis's compute `setup`. + +`AnalysisSetupMixin` holds everything every analysis does with its `setup` input: store it +(`_init_setup`), resolve it against the model in `modify_before_fit` (`resolve_setup`), log what +`setup="auto"` would choose when no setup was given (`_log_setup_auto_would_choose`) and write the +resolved setup to `files/setup.json` (`save_setup`). The pure helpers it uses live in +`autogalaxy.analysis.setup_util`. + +A subclass supplies two things: + +- `setup_key_and_note_from(model)`: the `(dataset_type, variant)` rule key of `aa.Setup.auto` for + the analysis and model, plus an optional note for the banner (e.g. that a fallback rule was used). +- `_apply_resolved_setup(setup)`: what applying the resolved setup means beyond the backend and + threads, e.g. `AnalysisDataset` attaches the operator it names to the dataset and checks it. It + runs after `_use_jax` is set, so the check sees the resolved backend. The default does nothing, + for analyses whose dataset has no operator to attach. + +The mixin has no `__init__` (the subclass calls `_init_setup(setup)` in its constructor) and is not +on `autogalaxy.Analysis`, so analyses that take no `setup` are unaffected. It goes before the +`Analysis` base in a subclass's bases. +""" + +import logging +from typing import Optional, Tuple + +import autofit as af +import autoarray as aa + +from autogalaxy.analysis import setup_util + +logger = logging.getLogger(__name__) + +logger.setLevel(level="INFO") + + +class AnalysisSetupMixin: + """ + Mixin resolving the compute `setup` of an analysis (backend, device, operator, precision, + transformer, threads). + + The subclass calls `_init_setup(setup)` in its constructor, `resolve_setup(model)` first in its + `modify_before_fit` and `save_setup(paths)` in its `save_attributes`, and implements + `setup_key_and_note_from(model)`; it overrides `_apply_resolved_setup(setup)` if applying a setup + changes its dataset. + """ + + 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_and_note_from( + self, model: af.Collection + ) -> Tuple[Tuple[str, str], Optional[str]]: + """ + The `(dataset_type, variant)` rule key of `aa.Setup.auto` for this analysis and model, plus a + note for the setup banner (or `None`). + """ + raise NotImplementedError + + def _apply_resolved_setup(self, setup: aa.Setup): + """ + Apply the resolved setup to the analysis beyond its backend and threads (e.g. attach the + operator it names to the dataset). Called by `resolve_setup` after `_use_jax` is set. The + default does nothing. + """ + + 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 the rule key of the analysis and + model (`setup_key_and_note_from`); `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); + - is applied by `_apply_resolved_setup` (e.g. `AnalysisDataset` attaches the operator it names to + the dataset and checks it against the backend, so a mismatch raises here rather than rejecting + every sample); + - pins the thread pools (`setup.apply_threads()`); + - is logged as the setup banner line and stored as `self.setup`. + + Parameters + ---------- + model + The model fitted by the search, which decides the rule variant (e.g. pixelization mesh or MGE). + """ + setup_input = getattr(self, "setup_input", None) + + if setup_input is None: + self._log_setup_auto_would_choose(model=model) + return + + note = None + + environment = setup_util.setup_environment() + + if setup_input == setup_util.SETUP_AUTO: + key, note = self.setup_key_and_note_from(model) + setup = aa.Setup.auto(*key, 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") + + self._apply_resolved_setup(setup) + + 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, + note=note, + ) + ) + + def _log_setup_auto_would_choose(self, model: af.Collection): + """ + Log one line reporting the setup `setup="auto"` would choose, applying nothing. + """ + try: + key, _ = self.setup_key_and_note_from(model) + setup = aa.Setup.auto(*key, environment=setup_util.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): + """ + Write the resolved setup to `files/setup.json`, when a setup was resolved. + """ + 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 + ), + ) diff --git a/autogalaxy/analysis/setup_util.py b/autogalaxy/analysis/setup_util.py index 01c96d743..8dbb096fe 100644 --- a/autogalaxy/analysis/setup_util.py +++ b/autogalaxy/analysis/setup_util.py @@ -16,6 +16,10 @@ once, outside the likelihood, so a mismatch raises before sampling. - `setup_banner_from` / `setup_dict_from`: the banner line logged at fit start and the contents of `files/setup.json`. +- `setup_environment`: the detected hardware `aa.Setup.auto` chooses for. + +The resolution itself is `autogalaxy.analysis.analysis.setup.AnalysisSetupMixin`, shared by every +analysis that takes a `setup`. The setup decides only how the likelihood is computed (backend, device, operator, precision, transformer, threads), never the model. @@ -219,6 +223,19 @@ def setup_key_from(dataset, model, regime: str = "standard") -> Tuple[str, str]: return setup_key_and_note_from(dataset=dataset, model=model, regime=regime)[0] +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 + + def use_jax_from(use_jax: bool) -> bool: """ Resolve a requested JAX backend exactly as `af.Analysis.__init__` resolves `use_jax`: diff --git a/autogalaxy/imaging/fit_imaging.py b/autogalaxy/imaging/fit_imaging.py index 65425d54f..243b0d15c 100644 --- a/autogalaxy/imaging/fit_imaging.py +++ b/autogalaxy/imaging/fit_imaging.py @@ -145,7 +145,7 @@ def galaxies_to_inversion(self) -> GalaxiesToInversion: noise_map=self.noise_map, grids=self.grids, psf=self.dataset.psf, - sparse_operator=self.dataset.sparse_operator, + sparse_operator=self.sparse_operator, ) return GalaxiesToInversion( diff --git a/autogalaxy/interferometer/fit_interferometer.py b/autogalaxy/interferometer/fit_interferometer.py index e7e7d17db..7d4eea2c4 100644 --- a/autogalaxy/interferometer/fit_interferometer.py +++ b/autogalaxy/interferometer/fit_interferometer.py @@ -60,6 +60,7 @@ def sparse_profile_terms_from( galaxies: List[Galaxy], image: aa.Array2D, xp=np, + sparse_operator=None, ): """ Returns the sparse dirty image and chi-squared data term of the profile-subtracted visibilities @@ -88,8 +89,15 @@ def sparse_profile_terms_from( is Fourier transformed to the fit's `profile_visibilities`. xp The array module (`numpy` or `jax.numpy`). + sparse_operator + The sparse operator the fit's inversion uses (`fit.sparse_operator`, which may be one the dataset + built lazily), so the correction and the inversion use the same operator. `None` falls back to + `dataset.sparse_operator`. """ - if dataset.sparse_operator is None: + if sparse_operator is None: + sparse_operator = dataset.sparse_operator + + if sparse_operator is None: return None, None if not _has_light_profile_non_linear(galaxies=galaxies): @@ -97,7 +105,7 @@ def sparse_profile_terms_from( _, sparse_dirty_image, data_term = ( aa.util.inversion_interferometer.sparse_profile_terms_from( - sparse_operator=dataset.sparse_operator, + sparse_operator=sparse_operator, image=image, extent_index_for_masked_pixel=dataset.real_space_mask.extent_index_for_masked_pixel, xp=xp, @@ -112,6 +120,7 @@ def sparse_dirty_image_from( galaxies: List[Galaxy], image: aa.Array2D, xp=np, + sparse_operator=None, ) -> Optional[np.ndarray]: """ Returns the dirty image the sparse (w-tilde) inversion of an interferometer fit must use to form its data @@ -145,9 +154,15 @@ def sparse_dirty_image_from( is Fourier transformed to the fit's `profile_visibilities`. xp The array module (`numpy` or `jax.numpy`). + sparse_operator + The sparse operator the fit's inversion uses; `None` falls back to `dataset.sparse_operator`. """ return sparse_profile_terms_from( - dataset=dataset, galaxies=galaxies, image=image, xp=xp + dataset=dataset, + galaxies=galaxies, + image=image, + xp=xp, + sparse_operator=sparse_operator, )[0] @@ -156,6 +171,7 @@ def uses_precomputed_data_term_from( galaxies: List[Galaxy], data: aa.Visibilities, noise_map: aa.VisibilitiesNoiseMap, + sparse_operator=None, ) -> bool: """ Returns whether the inversion of an interferometer fit can read the data term `d^T N^-1 d` of its @@ -194,8 +210,13 @@ def uses_precomputed_data_term_from( The visibilities the fit is fitting (`fit.data`). noise_map The noise-map the fit uses (`fit.noise_map`). + sparse_operator + The sparse operator the fit's inversion uses (`fit.sparse_operator`). An operator the dataset built + lazily (`sparse_operator_for`) is built from the dataset's own data and noise-map, so its cached + `data_term` is valid under the same identity checks. `None` falls back to `dataset.sparse_operator`. """ - sparse_operator = getattr(dataset, "sparse_operator", None) + if sparse_operator is None: + sparse_operator = getattr(dataset, "sparse_operator", None) if getattr(sparse_operator, "data_term", None) is None: return False @@ -253,7 +274,7 @@ def _require_no_array_free_overrides(fit): ) -def sparse_chi_squared_from(fit, galaxies: List[Galaxy]): +def sparse_chi_squared_from(fit, galaxies: List[Galaxy], sparse_operator=None): """ Returns the chi-squared `sum(|d - F m|^2 / sigma^2)` of an interferometer fit computed from its dataset's `sparse_operator` without any visibility-sized array, by applying the data-term identity to the fit's total @@ -281,8 +302,15 @@ def sparse_chi_squared_from(fit, galaxies: List[Galaxy]): `perform_inversion`, `inversion` and `_xp`. galaxies The fit's galaxies, checked for ordinary light profiles. + sparse_operator + The sparse operator to use. `None` uses the fit's resolved `fit.sparse_operator` (the one its + inversion uses) when the fit has one, else `fit.dataset.sparse_operator`. """ - sparse_operator = fit.dataset.sparse_operator + if sparse_operator is None: + sparse_operator = getattr(fit, "sparse_operator", None) + + if sparse_operator is None: + sparse_operator = fit.dataset.sparse_operator if sparse_operator is None: return None @@ -438,7 +466,9 @@ def sparse_chi_squared(self): `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`, where the value is traced with the model's parameters. """ - return sparse_chi_squared_from(fit=self, galaxies=self.galaxies) + return sparse_chi_squared_from( + fit=self, galaxies=self.galaxies, sparse_operator=self.sparse_operator + ) @property def _uses_precomputed_data_term(self) -> bool: @@ -453,6 +483,7 @@ def _uses_precomputed_data_term(self) -> bool: galaxies=self.galaxies, data=self.data, noise_map=self.noise_map, + sparse_operator=self.sparse_operator, ) @property @@ -485,6 +516,7 @@ def galaxies_to_inversion(self) -> GalaxiesToInversion: galaxies=self.galaxies, image=self.profile_image, xp=self._xp, + sparse_operator=self.sparse_operator, ) if self._uses_precomputed_data_term: @@ -498,7 +530,7 @@ def galaxies_to_inversion(self) -> GalaxiesToInversion: 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_autogalaxy/aggregator/__init__.py b/test_autogalaxy/aggregator/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/test_autogalaxy/aggregator/test_dataset_setup.py b/test_autogalaxy/aggregator/test_dataset_setup.py new file mode 100644 index 000000000..a540de16c --- /dev/null +++ b/test_autogalaxy/aggregator/test_dataset_setup.py @@ -0,0 +1,164 @@ +""" +Aggregator reloads of a dataset reapply the compute setup the search wrote to `files/setup.json` +(`agg_util.dataset_with_setup_from`), so a reloaded fit takes the same operator route as the search. +""" +import logging +from types import SimpleNamespace + +import pytest + +import autoarray as aa +import autogalaxy as ag + +from autogalaxy.aggregator import agg_util +from autogalaxy.aggregator.imaging.imaging import _imaging_from +from autogalaxy.aggregator.interferometer.interferometer import _interferometer_from +from autogalaxy.analysis import setup_util +from autogalaxy.analysis.analysis.dataset import AnalysisDataset +from autogalaxy.interferometer.model.analysis import interferometer_hdu_list_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 _fake_fit(values): + """A `Fit` stand-in whose `value(name)` returns `values.get(name)` (None for a missing file).""" + return SimpleNamespace(children=[], 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__imaging_from__no_setup_json__reloads_unchanged(masked_imaging_7x7, monkeypatch): + hdu_list = _imaging_hdu_list_from(masked_imaging_7x7, monkeypatch) + + dataset = _imaging_from(fit=_fake_fit({"dataset": hdu_list}))[0] + + assert dataset.setup is None + assert dataset.sparse_operator is None + assert (dataset.data.array == masked_imaging_7x7.data.array).all() + + +def test__imaging_from__setup_json__reapplied(masked_imaging_7x7, monkeypatch): + pytest.importorskip("numba") + + hdu_list = _imaging_hdu_list_from(masked_imaging_7x7, monkeypatch) + + dataset = _imaging_from( + fit=_fake_fit( + {"dataset": hdu_list, "setup": _setup_dict("numba_cpu_sparse_fp64")} + ) + )[0] + + assert dataset.setup.setup_id == "numba_cpu_sparse_fp64" + assert dataset.sparse_operator is not None + + # The reloaded fit takes the sparse route and reproduces the search's (dense) figure of merit. + pixelization = ag.Pixelization( + mesh=ag.mesh.RectangularUniform(shape=(3, 3)), + regularization=ag.reg.Constant(coefficient=1.0), + ) + galaxies = [ag.Galaxy(redshift=0.5, pixelization=pixelization)] + + fit = ag.FitImaging(dataset=dataset, galaxies=galaxies) + fit_dense = ag.FitImaging(dataset=masked_imaging_7x7, galaxies=galaxies) + + assert fit.inversion.dataset.sparse_operator is dataset.sparse_operator + assert fit.figure_of_merit == pytest.approx(fit_dense.figure_of_merit, rel=1.0e-6) + + +def test__imaging_from__setup_reapply_fails__one_warning_and_unapplied( + masked_imaging_7x7, monkeypatch, caplog +): + hdu_list = _imaging_hdu_list_from(masked_imaging_7x7, monkeypatch) + + def raise_(self, setup, **kwargs): + raise aa.exc.DatasetException("no JAX here") + + monkeypatch.setattr(aa.Imaging, "apply_setup", raise_) + + with caplog.at_level(logging.WARNING, logger=agg_util.__name__): + dataset = _imaging_from( + fit=_fake_fit( + {"dataset": hdu_list, "setup": _setup_dict("jax_cpu_sparse_fp64")} + ) + )[0] + + warnings = [r for r in caplog.records if r.levelno == logging.WARNING] + + assert len(warnings) == 1 + assert "jax_cpu_sparse_fp64" in warnings[0].message + assert "no JAX here" in warnings[0].message + + assert dataset.setup is None + assert dataset.sparse_operator is None + + +def test__interferometer_from__setup_json__reapplied(interferometer_7): + pytest.importorskip("finufft") + + values = { + "dataset": interferometer_hdu_list_from(dataset=interferometer_7), + "transformer_class": aa.TransformerDFT, + } + + dataset = _interferometer_from(fit=_fake_fit(values))[0] + + assert dataset.setup is None + assert dataset.sparse_operator is None + + values["setup"] = _setup_dict("numba_cpu_sparse_fp64_wtilde") + + dataset = _interferometer_from(fit=_fake_fit(values))[0] + + assert dataset.setup.setup_id == "numba_cpu_sparse_fp64_wtilde" + assert dataset.sparse_operator is not None + + +def test__dataset_with_setup_from__array_free_dataset__skipped(monkeypatch): + called = [] + + dataset = SimpleNamespace( + data=None, apply_setup=lambda setup: called.append(setup) + ) + + fit = _fake_fit({"setup": {"setup_id": "numba_cpu_sparse_fp64_wtilde"}}) + + assert agg_util.dataset_with_setup_from(fit=fit, dataset=dataset) is dataset + assert called == [] + + +# The shared setup-resolution mixin. + + +def test__analysis_dataset__setup_mixin_in_mro_once(): + from autogalaxy.analysis.analysis.analysis import Analysis + from autogalaxy.analysis.analysis.setup import AnalysisSetupMixin + + for cls in (AnalysisDataset, ag.AnalysisImaging, ag.AnalysisInterferometer): + mro = cls.__mro__ + + assert mro.count(AnalysisSetupMixin) == 1 + assert mro.index(AnalysisSetupMixin) < mro.index(Analysis) + + # Analyses without a setup (e.g. the plain `Analysis` base) do not carry the mixin. + assert AnalysisSetupMixin not in Analysis.__mro__ diff --git a/test_autogalaxy/imaging/test_fit_imaging.py b/test_autogalaxy/imaging/test_fit_imaging.py index 672ac5e54..5837884c3 100644 --- a/test_autogalaxy/imaging/test_fit_imaging.py +++ b/test_autogalaxy/imaging/test_fit_imaging.py @@ -2,6 +2,7 @@ import numpy as np import pytest +import autoarray as aa import autogalaxy as ag @@ -841,3 +842,171 @@ 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`. + +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 _pixelization_galaxies(): + pixelization = ag.Pixelization( + mesh=ag.mesh.RectangularUniform(shape=(3, 3)), + regularization=ag.reg.Constant(coefficient=1.0), + ) + + return [ + ag.Galaxy(redshift=0.5, bulge=ag.lp.Sersic(intensity=0.1)), + ag.Galaxy(redshift=0.5, pixelization=pixelization), + ] + + +def test__sparse_operator__lazy_policy_on__matches_dense_built_once_and_reused( + masked_imaging_7x7, no_ambient_setup +): + pytest.importorskip("numba") + + galaxies = _pixelization_galaxies() + + fit_dense = ag.FitImaging(dataset=masked_imaging_7x7, galaxies=galaxies) + + assert fit_dense.sparse_operator is None + assert isinstance(fit_dense.inversion, aa.InversionImagingMapping) + assert masked_imaging_7x7._lazy_sparse_operator is None + + fit = ag.FitImaging( + dataset=masked_imaging_7x7, galaxies=galaxies, 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 = ag.FitImaging( + dataset=masked_imaging_7x7, galaxies=galaxies, 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 = ag.FitImaging( + dataset=masked_imaging_7x7, galaxies=_pixelization_galaxies(), 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__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) + ) + + galaxies = [ + ag.Galaxy( + redshift=0.5, + bulge=ag.lp_basis.Basis( + profile_list=[ + ag.lp_linear.Gaussian(sigma=0.5), + ag.lp_linear.Gaussian(sigma=1.5), + ] + ), + ) + ] + + fit = ag.FitImaging(dataset=masked_imaging_7x7, 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") + + built = [] + monkeypatch.setattr( + aa.Imaging, "apply_sparse_operator_cpu", lambda self: built.append(1) + ) + + import jax.numpy as jnp + + fit = ag.FitImaging( + dataset=masked_imaging_7x7, + galaxies=_pixelization_galaxies(), + 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() + + galaxies = [ + ag.Galaxy( + redshift=0.5, + bulge=ag.lp_linear.Sersic(), + disk=ag.lp_linear.Exponential(), + ) + ] + + for settings in (None, LAZY_ON): + fit = ag.FitImaging(dataset=dataset, galaxies=galaxies, 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 = ag.FitImaging( + dataset=masked_imaging_7x7, galaxies=galaxies, settings=settings + ) + + assert fit.figure_of_merit == pytest.approx( + fit_dense.figure_of_merit, rel=1.0e-6 + ) diff --git a/test_autogalaxy/interferometer/test_fit_interferometer.py b/test_autogalaxy/interferometer/test_fit_interferometer.py index 9a0b720e2..eaeed5865 100644 --- a/test_autogalaxy/interferometer/test_fit_interferometer.py +++ b/test_autogalaxy/interferometer/test_fit_interferometer.py @@ -1679,3 +1679,262 @@ def test__galaxy_image_dict__adds_ordinary_and_linear_light( with fits.open(cache_path) as hdus: assert hdus[0].header["CACHEVER"] == 1 np.testing.assert_allclose(hdus[1].data, expected.native_for_fits) + + +# The lazy sparse operator (`dataset.sparse_operator_for`) reached through `fit.sparse_operator`. + +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 _pixelization_and_light_profile_galaxies(): + pixelization = ag.Pixelization( + mesh=ag.mesh.RectangularUniform(shape=(3, 3)), + regularization=ag.reg.Constant(coefficient=1.0), + ) + + return [ + ag.Galaxy(redshift=0.5, bulge=ag.lp.Sersic(intensity=0.1, centre=(0.05, 0.05))), + ag.Galaxy(redshift=0.5, pixelization=pixelization), + ] + + +def test__sparse_operator__lazy_policy_off__dense_and_nothing_built( + interferometer_7, no_ambient_setup +): + fit = ag.FitInterferometer( + dataset=interferometer_7, galaxies=_pixelization_only_galaxies() + ) + + 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__pixelization_only__matches_dense_built_once( + interferometer_7, no_ambient_setup +): + pytest.importorskip("finufft") + + galaxies = _pixelization_only_galaxies() + + fit_dense = ag.FitInterferometer(dataset=interferometer_7, galaxies=galaxies) + + fit = ag.FitInterferometer( + dataset=interferometer_7, galaxies=galaxies, 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 = ag.FitInterferometer( + dataset=interferometer_7, galaxies=galaxies, settings=LAZY_ON + ) + + assert fit_again.sparse_operator is operator + + +def test__sparse_operator__lazy_policy_on__pixelization_and_light_profile__dirty_image_correction_matches_dense( + interferometer_7, no_ambient_setup +): + pytest.importorskip("finufft") + + galaxies = _pixelization_and_light_profile_galaxies() + + fit_dense = ag.FitInterferometer(dataset=interferometer_7, galaxies=galaxies) + + fit = ag.FitInterferometer( + dataset=interferometer_7, galaxies=galaxies, 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 ordinary light profile 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 + + expected_dirty_image = ag.interferometer.fit_interferometer.sparse_dirty_image_from( + dataset=interferometer_7, + galaxies=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__mge_only_builds_nothing( + interferometer_7, no_ambient_setup, monkeypatch +): + built = [] + monkeypatch.setattr( + aa.Interferometer, + "apply_sparse_operator", + lambda self, **kwargs: built.append(1), + ) + + galaxies = [ + ag.Galaxy( + redshift=0.5, + bulge=ag.lp_basis.Basis( + profile_list=[ + ag.lp_linear.Gaussian(sigma=0.5, centre=(0.05, 0.05)), + ag.lp_linear.Gaussian(sigma=1.5, centre=(0.05, 0.05)), + ] + ), + ) + ] + + fit = ag.FitInterferometer( + dataset=interferometer_7, galaxies=galaxies, 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 = ag.FitInterferometer( + dataset=interferometer_7, + galaxies=_pixelization_only_galaxies(), + 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) + + galaxies = [ + ag.Galaxy( + redshift=0.5, + bulge=ag.lp_linear.Gaussian(sigma=0.5, centre=(0.05, 0.05)), + disk=ag.lp_linear.Gaussian(sigma=1.5, centre=(0.05, 0.05)), + ) + ] + + for settings in (None, LAZY_ON): + fit = ag.FitInterferometer( + dataset=dataset_sparse, galaxies=galaxies, 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 = ag.FitInterferometer( + dataset=interferometer_7, galaxies=galaxies, settings=settings + ) + + assert fit.log_likelihood == pytest.approx(fit_dense.log_likelihood, rel=1.0e-8) + + +def test__interferometer_helpers__sparse_operator_argument__defaults_to_dataset_operator( + interferometer_7, +): + """ + The profile-subtraction helpers take the fit's resolved operator; called without one (as PyAutoLens does + until it passes its own) they fall back to the dataset's attached operator, exactly as before. + """ + from autogalaxy.interferometer import fit_interferometer as fi + + dataset_sparse = interferometer_7.apply_sparse_operator(use_jax=False) + + galaxies = _pixelization_and_light_profile_galaxies() + + fit = ag.FitInterferometer(dataset=dataset_sparse, galaxies=galaxies) + + default = fi.sparse_profile_terms_from( + dataset=dataset_sparse, galaxies=galaxies, image=fit.profile_image + ) + explicit = fi.sparse_profile_terms_from( + dataset=dataset_sparse, + galaxies=galaxies, + image=fit.profile_image, + sparse_operator=dataset_sparse.sparse_operator, + ) + + np.testing.assert_array_equal(default[0], explicit[0]) + assert default[1] == explicit[1] + + # Without any operator nothing is corrected. + assert fi.sparse_profile_terms_from( + dataset=interferometer_7, galaxies=galaxies, image=fit.profile_image + ) == (None, None) + + assert fi.uses_precomputed_data_term_from( + dataset=interferometer_7, + galaxies=_pixelization_only_galaxies(), + data=interferometer_7.data, + noise_map=interferometer_7.noise_map, + ) is False + assert fi.uses_precomputed_data_term_from( + dataset=interferometer_7, + galaxies=_pixelization_only_galaxies(), + data=interferometer_7.data, + noise_map=interferometer_7.noise_map, + sparse_operator=dataset_sparse.sparse_operator, + ) is True + + assert fi.sparse_chi_squared_from( + fit=fit, galaxies=galaxies + ) == pytest.approx( + fi.sparse_chi_squared_from( + fit=fit, galaxies=galaxies, sparse_operator=dataset_sparse.sparse_operator + ), + rel=1.0e-14, + )