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
120 changes: 15 additions & 105 deletions autolens/analysis/analysis/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

Expand Down Expand Up @@ -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=<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); `_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
2 changes: 1 addition & 1 deletion autolens/imaging/fit_imaging.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
10 changes: 8 additions & 2 deletions autolens/interferometer/fit_interferometer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -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,
)
Expand Down
127 changes: 127 additions & 0 deletions test_autolens/aggregator/test_fit_dataset_setup.py
Original file line number Diff line number Diff line change
@@ -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
)
31 changes: 31 additions & 0 deletions test_autolens/analysis/analysis/test_setup_mixin.py
Original file line number Diff line number Diff line change
@@ -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,
)
Loading
Loading