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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 33 additions & 7 deletions autogalaxy/abstract_fit.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from __future__ import annotations
import functools
from typing import TYPE_CHECKING, Dict, Optional

import numpy as np
Expand Down Expand Up @@ -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]:
Expand Down
56 changes: 56 additions & 0 deletions autogalaxy/aggregator/agg_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Expand Down Expand Up @@ -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
7 changes: 7 additions & 0 deletions autogalaxy/aggregator/imaging/imaging.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
8 changes: 8 additions & 0 deletions autogalaxy/aggregator/interferometer/interferometer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
114 changes: 18 additions & 96 deletions autogalaxy/analysis/analysis/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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=<setup_id>` 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."""
Expand Down Expand Up @@ -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):
"""
Expand Down
Loading
Loading