diff --git a/autolens/__init__.py b/autolens/__init__.py index 6fb6aa1a2..e661fbb57 100644 --- a/autolens/__init__.py +++ b/autolens/__init__.py @@ -143,6 +143,7 @@ from . import mock as m from . import util from . import potential_correction as pc +from . import twins from autonerves import conf from autonerves.fitsable import ndarray_via_hdu_from diff --git a/autolens/twins/__init__.py b/autolens/twins/__init__.py new file mode 100644 index 000000000..b67f7a6f1 --- /dev/null +++ b/autolens/twins/__init__.py @@ -0,0 +1,39 @@ +""" +``al.twins``: controlled, provenance-carrying simulations ("twins") of fitted lenses. + +A fitted lens is ingested as a ``ReferenceModel`` (tracer with solved intensities, +``ObservationSetup`` and provenance). A ``Twin`` is that tracer and setup after a +chain of ``transform`` steps, each leaving a ``TransformationRecord``; simulating a +twin with a seed gives a ``SimulatedTwin`` whose FITS files sit beside its truth +tracer and ``twin.json``. + +Three invariants: + +1. A reference model is immutable, and one reference has many twins. +2. Preserving any parent property is a recorded choice, never implicit + (``TransformationRecord.preserved`` is empty unless a transformation fills it). +3. Every simulated observation carries its ground truth, transformation chain, + seed and library versions beside the FITS. + +Default noise is the observed noise map (Gaussian, ``numpy.random.default_rng(seed)``); +Poisson noise is used only when the setup sets ``exposure_time`` and +``background_sky_level`` and ``noise="poisson"`` is requested. + +NumPy only: nothing here supports JAX. +""" + +from autolens.twins.record import TransformationRecord +from autolens.twins.setup import ObservationSetup +from autolens.twins.reference import ReferenceModel +from autolens.twins.twin import Twin +from autolens.twins.simulate import SimulatedTwin +from autolens.twins import transform + +__all__ = [ + "ObservationSetup", + "ReferenceModel", + "Twin", + "SimulatedTwin", + "TransformationRecord", + "transform", +] diff --git a/autolens/twins/_util.py b/autolens/twins/_util.py new file mode 100644 index 000000000..bd36f6043 --- /dev/null +++ b/autolens/twins/_util.py @@ -0,0 +1,172 @@ +""" +Small helpers shared by the ``al.twins`` modules: an immutability guard, library +versions for provenance, SHA-256 hashing and the FITS read/write recipe used for +masks and arrays. +""" + +import hashlib +import importlib.metadata +import json +import platform +from datetime import datetime, timezone +from pathlib import Path +from typing import Dict, Optional, Union + +import numpy as np + +import autoarray as aa +from autoarray.mask.mask_2d import Mask2DKeys +from autonerves.dictable import to_dict +from autonerves.fitsable import ndarray_via_hdu_from, output_to_fits + +VERSIONED_DISTRIBUTIONS = ( + "autonerves", + "autofit", + "autoarray", + "autogalaxy", + "autolens", + "numpy", +) + + +class Frozen: + """ + Mixin making instances immutable after ``__init__``: attribute assignment and + deletion raise ``AttributeError``. ``__init__`` sets attributes through + ``self._freeze_set``. + """ + + def _freeze_set(self, name, value): + object.__setattr__(self, name, value) + + def __setattr__(self, name, value): + raise AttributeError( + f"{type(self).__name__} is immutable; cannot set attribute '{name}'. " + f"Build a modified copy instead." + ) + + def __delattr__(self, name): + raise AttributeError( + f"{type(self).__name__} is immutable; cannot delete attribute '{name}'." + ) + + +def library_versions() -> Dict[str, Optional[str]]: + """ + The installed versions of the PyAuto stack and NumPy, plus the Python version. + A distribution that is not installed (e.g. a source checkout on ``sys.path`` + without metadata) is recorded as ``None`` rather than raising. + """ + versions = {} + for name in VERSIONED_DISTRIBUTIONS: + try: + versions[name] = importlib.metadata.version(name) + except importlib.metadata.PackageNotFoundError: + versions[name] = None + versions["python"] = platform.python_version() + return versions + + +def utc_now_iso() -> str: + """The current time as an ISO-8601 UTC string (seconds precision).""" + return datetime.now(timezone.utc).isoformat(timespec="seconds") + + +def sha256_of_file(file_path: Union[str, Path]) -> str: + digest = hashlib.sha256() + with open(file_path, "rb") as f: + for chunk in iter(lambda: f.read(1 << 20), b""): + digest.update(chunk) + return digest.hexdigest() + + +def sha256_of_object(obj) -> str: + """ + SHA-256 of the canonical (key-sorted) JSON of an object's ``autonerves.dictable`` + dictionary. Used when there is no file on disk to hash (e.g. ``from_result``). + """ + payload = json.dumps(to_dict(obj), sort_keys=True).encode("utf-8") + return hashlib.sha256(payload).hexdigest() + + +def sha256_of_arrays(*arrays) -> str: + """SHA-256 over the raw bytes (and shapes) of several arrays.""" + digest = hashlib.sha256() + for array in arrays: + values = np.ascontiguousarray(np.asarray(array, dtype="float64")) + digest.update(str(values.shape).encode("utf-8")) + digest.update(values.tobytes()) + return digest.hexdigest() + + +def native_values_from(array) -> np.ndarray: + """The native 2D NumPy values of an ``aa.Array2D`` (masked entries are zero).""" + return np.asarray(array.native.array) + + +def mask_from_hdu(hdu) -> aa.Mask2D: + """ + Rebuild a ``Mask2D`` from a FITS HDU whose header carries the pixel scales and + origin, as written by ``Mask2D.header_dict``. + + Replicates ``autogalaxy.aggregator.agg_util.mask_header_from`` (PyAutoGalaxy + ``autogalaxy/aggregator/agg_util.py``, function ``mask_header_from``): a file + written without a ``PIXSCAX`` card is assumed to have square pixels. Kept as a + copy so ``al.twins`` does not depend on the aggregator's ``af.Fit`` interface; + if that function changes, change this one too. + """ + header = hdu.header + pixel_scales_y = header[Mask2DKeys.PIXSCAY.value] + pixel_scales = ( + pixel_scales_y, + header.get(Mask2DKeys.PIXSCAX.value, pixel_scales_y), + ) + origin = ( + header[Mask2DKeys.ORIGINY.value], + header[Mask2DKeys.ORIGINX.value], + ) + return aa.Mask2D( + mask=ndarray_via_hdu_from(hdu), + pixel_scales=pixel_scales, + origin=origin, + ) + + +def output_mask_to_fits(mask: aa.Mask2D, file_path: Union[str, Path]): + output_to_fits( + values=np.asarray(mask).astype("float"), + file_path=file_path, + overwrite=True, + header_dict=mask.header_dict, + ext_name="mask", + ) + + +def output_array_to_fits( + values: np.ndarray, mask: aa.Mask2D, file_path: Union[str, Path], ext_name: str +): + """ + Write native values without the visualisation zoom (``native_for_fits``), so a + reload is bit-identical and shaped like the mask. + """ + output_to_fits( + values=np.asarray(values, dtype="float64"), + file_path=file_path, + overwrite=True, + header_dict=mask.header_dict, + ext_name=ext_name, + ) + + +def ndarray_from_fits(file_path: Union[str, Path], hdu: int = 0) -> np.ndarray: + from astropy.io import fits + + with fits.open(file_path) as hdu_list: + return ndarray_via_hdu_from(hdu_list[hdu]) + + +def mask_from_fits(file_path: Union[str, Path], hdu: int = 0) -> aa.Mask2D: + from astropy.io import fits + + with fits.open(file_path) as hdu_list: + return mask_from_hdu(hdu_list[hdu]) diff --git a/autolens/twins/record.py b/autolens/twins/record.py new file mode 100644 index 000000000..3c767f44e --- /dev/null +++ b/autolens/twins/record.py @@ -0,0 +1,76 @@ +""" +``TransformationRecord``: what one transformation of a twin asked for, how it did +it, and what it changed, as plain JSON-able data. + +``preserved`` is empty by default: preserving a parent property (e.g. the Einstein +radius) is a choice a transformation records explicitly, never an implicit +default. +""" + +import copy +from typing import Dict, List, Optional + +from autolens.twins._util import Frozen + + +class TransformationRecord(Frozen): + def __init__( + self, + name: str, + requested: Optional[Dict] = None, + procedure: Optional[Dict] = None, + changed: Optional[List] = None, + side_effects: Optional[List] = None, + preserved: Optional[List] = None, + ): + """ + The record a transformation appends to a twin's chain. + + Parameters + ---------- + name + The transformation's name, e.g. ``"Identity"``. + requested + The parameters the user asked for. + procedure + How the change was made: a ``"text"`` description plus any derived numbers. + changed + The galaxy / component paths that were changed. + side_effects + Properties that changed as a consequence (e.g. a lensing observable). + preserved + Parent properties explicitly held fixed. Empty unless a transformation + chooses to preserve something. + + ``al.from_dict`` drops ``None`` values inside dictionaries (PyAutoFit's dict + parser), so ``requested`` and ``procedure`` should not use ``None`` values. + """ + self._freeze_set("name", str(name)) + self._freeze_set("requested", copy.deepcopy(dict(requested or {}))) + self._freeze_set("procedure", copy.deepcopy(dict(procedure or {}))) + self._freeze_set("changed", list(changed or [])) + self._freeze_set("side_effects", list(side_effects or [])) + self._freeze_set("preserved", list(preserved or [])) + + def __repr__(self): + return ( + f"TransformationRecord(name={self.name!r}, changed={self.changed}, " + f"side_effects={self.side_effects}, preserved={self.preserved})" + ) + + def __eq__(self, other): + if not isinstance(other, TransformationRecord): + return NotImplemented + return all( + getattr(self, name) == getattr(other, name) + for name in ( + "name", + "requested", + "procedure", + "changed", + "side_effects", + "preserved", + ) + ) + + __hash__ = None diff --git a/autolens/twins/reference.py b/autolens/twins/reference.py new file mode 100644 index 000000000..19bc209ed --- /dev/null +++ b/autolens/twins/reference.py @@ -0,0 +1,225 @@ +""" +``ReferenceModel``: an immutable snapshot of a fitted lens (the tracer with its +solved intensities, the observation setup and a provenance record) from which any +number of twins are made. +""" + +import copy +import json +from pathlib import Path +from typing import Dict, Iterable, Optional, Union + +import yaml + +from autonerves.dictable import from_json, output_to_json + +from autolens.twins import _util +from autolens.twins._util import Frozen +from autolens.twins.setup import ObservationSetup + +PROVENANCE_DEFAULTS = { + "lens_id": None, + "labels": [], + "roles": {}, + "fit_path": None, + "dataset_sha256": None, + "tracer_sha256": None, + "ingested_at": None, + "versions": {}, +} + + +def provenance_from( + lens_id: str, + labels: Iterable[str] = (), + roles: Optional[Dict[str, str]] = None, + fit_path: Optional[str] = None, + dataset_sha256: Optional[str] = None, + tracer_sha256: Optional[str] = None, +) -> Dict: + """The provenance dictionary of a reference model, stamped now.""" + return { + "lens_id": str(lens_id), + "labels": [str(label) for label in labels], + "roles": dict(roles or {}), + "fit_path": None if fit_path is None else str(fit_path), + "dataset_sha256": dataset_sha256, + "tracer_sha256": tracer_sha256, + "ingested_at": _util.utc_now_iso(), + "versions": _util.library_versions(), + } + + +class ReferenceModel(Frozen): + def __init__(self, tracer, setup: ObservationSetup, provenance: Dict): + """ + A fitted lens frozen as the parent of twins. + + Attribute assignment raises. ``provenance`` is returned as a copy, so the + stored record cannot be edited through it. The tracer and setup are shared + objects and must be treated as read-only; ``Twin.baseline`` takes its own copy + of the tracer. + + Parameters + ---------- + tracer + The maximum-likelihood ``al.Tracer`` with solved linear intensities. + setup + How the lens was observed. + provenance + ``lens_id``, ``labels``, ``roles`` (galaxy name -> role), ``fit_path``, + ``dataset_sha256``, ``tracer_sha256``, ``ingested_at`` (ISO-8601 UTC) and + ``versions`` (library and Python versions); see ``provenance_from``. + """ + self._freeze_set("tracer", tracer) + self._freeze_set("setup", setup) + provenance = copy.deepcopy(dict(provenance)) + # `al.from_dict` drops None-valued dict entries (PyAutoFit's dict parser); + # restore the standard keys so a reloaded reference compares equal. + for key, default in PROVENANCE_DEFAULTS.items(): + provenance.setdefault(key, copy.deepcopy(default)) + if isinstance(provenance["versions"], dict): + for name in _util.VERSIONED_DISTRIBUTIONS + ("python",): + provenance["versions"].setdefault(name, None) + provenance["labels"] = list(provenance["labels"]) + self._freeze_set("_provenance", provenance) + + @property + def provenance(self) -> Dict: + return copy.deepcopy(self._provenance) + + @property + def lens_id(self) -> str: + return self._provenance.get("lens_id") + + def __repr__(self): + return ( + f"ReferenceModel(lens_id={self.lens_id!r}, " + f"fit_path={self._provenance.get('fit_path')!r})" + ) + + @classmethod + def from_fit_directory( + cls, + path: Union[str, Path], + lens_id: str, + labels: Iterable[str] = (), + roles: Optional[Dict[str, str]] = None, + ) -> "ReferenceModel": + """ + Ingest a model-fit output directory (the folder holding ``files/tracer.json`` + and ``image/dataset.fits``). The tracer is loaded from ``tracer.json`` and + therefore carries the solved linear intensities; the hashes are of the two + files' bytes. + """ + path = Path(path).resolve() + tracer_path = path / "files" / "tracer.json" + dataset_path = path / "image" / "dataset.fits" + + return cls( + tracer=from_json(file_path=tracer_path), + setup=ObservationSetup.from_fit_directory(path), + provenance=provenance_from( + lens_id=lens_id, + labels=labels, + roles=roles, + fit_path=str(path), + dataset_sha256=_util.sha256_of_file(dataset_path), + tracer_sha256=_util.sha256_of_file(tracer_path), + ), + ) + + @classmethod + def from_result( + cls, + result, + dataset, + lens_id: str, + labels: Iterable[str] = (), + roles: Optional[Dict[str, str]] = None, + fit_path: Optional[Union[str, Path]] = None, + ) -> "ReferenceModel": + """ + Ingest an in-memory result and the dataset it fitted. With no files to hash, + ``dataset_sha256`` hashes the native data, noise map, PSF kernel and mask + arrays and ``tracer_sha256`` hashes the tracer's canonical dictable JSON. + """ + tracer = result.max_log_likelihood_tracer + psf_kernel = [] if dataset.psf is None else [dataset.psf.kernel.native.array] + return cls( + tracer=tracer, + setup=ObservationSetup.from_dataset(dataset), + provenance=provenance_from( + lens_id=lens_id, + labels=labels, + roles=roles, + fit_path=None if fit_path is None else str(fit_path), + dataset_sha256=_util.sha256_of_arrays( + dataset.data.native.array, + dataset.noise_map.native.array, + dataset.mask, + *psf_kernel, + ), + tracer_sha256=_util.sha256_of_object(tracer), + ), + ) + + def output_to(self, directory: Union[str, Path]): + """ + Write ``tracer.json``, ``setup/`` (``mask.fits``, ``noise_map.fits``, + ``psf.fits`` for inspection and ``setup.json``, the complete setup that + ``from_directory`` reads), ``provenance.json`` and ``labels.yaml``. + """ + directory = Path(directory) + setup_directory = directory / "setup" + setup_directory.mkdir(parents=True, exist_ok=True) + + output_to_json(self.tracer, directory / "tracer.json") + write_setup(self.setup, setup_directory) + + with open(directory / "provenance.json", "w") as f: + json.dump(self._provenance, f, indent=4) + + with open(directory / "labels.yaml", "w") as f: + yaml.safe_dump( + { + "lens_id": self._provenance.get("lens_id"), + "labels": list(self._provenance.get("labels", [])), + "roles": dict(self._provenance.get("roles", {})), + }, + f, + sort_keys=False, + ) + + @classmethod + def from_directory(cls, directory: Union[str, Path]) -> "ReferenceModel": + """Reload a reference written by ``output_to``.""" + directory = Path(directory) + with open(directory / "provenance.json") as f: + provenance = json.load(f) + return cls( + tracer=from_json(file_path=directory / "tracer.json"), + setup=from_json(file_path=directory / "setup" / "setup.json"), + provenance=provenance, + ) + + +def write_setup(setup: ObservationSetup, directory: Path): + """``mask.fits``, ``noise_map.fits``, ``psf.fits`` and ``setup.json`` of a setup.""" + directory = Path(directory) + directory.mkdir(parents=True, exist_ok=True) + _util.output_mask_to_fits(setup.mask, directory / "mask.fits") + _util.output_array_to_fits( + _util.native_values_from(setup.noise_map), + mask=setup.mask, + file_path=directory / "noise_map.fits", + ext_name="noise_map", + ) + if setup.psf is not None: + _util.output_array_to_fits( + _util.native_values_from(setup.psf.kernel), + mask=setup.psf.kernel.mask, + file_path=directory / "psf.fits", + ext_name="psf", + ) + output_to_json(setup, directory / "setup.json") diff --git a/autolens/twins/setup.py b/autolens/twins/setup.py new file mode 100644 index 000000000..c47715fae --- /dev/null +++ b/autolens/twins/setup.py @@ -0,0 +1,334 @@ +""" +``ObservationSetup``: everything about *how* a lens is observed, separate from +*what* is observed (the tracer). + +A setup holds the mask, the PSF (an ``al.Convolver``), the observed noise map, +the pixel scales and origin, the light-profile and pixelization over-sampling, +an optional cosmology and, for the Poisson noise route only, an exposure time and +a background sky level. It is a value: ``with_(...)`` returns a modified copy and +nothing here mutates a setup in place. + +Serialisation: ``aa.Mask2D``, ``aa.Array2D``, ``aa.Convolver``, the cosmology +objects and plain ints/floats/tuples round-trip through ``autonerves.dictable`` +natively, *except* that an array loaded from FITS carries an ``aa.Header`` which +does not. The constructor therefore stores header-free copies of the mask, PSF, +noise map and over-sample arrays (``_copy``), and ``ObservationSetup`` then uses +the default constructor-argument contract, so ``al.to_dict`` / ``al.from_dict`` +work unchanged. +""" + +from pathlib import Path +from typing import Optional, Tuple, Union + +import numpy as np + +import autoarray as aa +from autonerves.dictable import from_dict, to_dict + +from autolens.twins import _util + +_FIELDS = ( + "mask", + "psf", + "noise_map", + "pixel_scales", + "origin", + "over_sample_size_lp", + "over_sample_size_pixelization", + "cosmology", + "exposure_time", + "background_sky_level", +) + + +def _clean_mask(mask: aa.Mask2D) -> aa.Mask2D: + return aa.Mask2D( + mask=np.array(mask, dtype=bool), + pixel_scales=tuple(mask.pixel_scales), + origin=tuple(mask.origin), + ) + + +def _clean_array(array: aa.Array2D) -> aa.Array2D: + return aa.Array2D( + values=np.array(array.native.array), + mask=_clean_mask(array.mask), + ) + + +def _copy(obj): + """ + A fresh, header-free copy of a mask, array or ``Convolver``. + + Arrays loaded from FITS carry an ``aa.Header`` (astropy cards) that does not + round-trip through ``autonerves.dictable``; ``Mask2D``, ``Array2D`` and + ``Convolver`` built from plain values do. Every array a setup holds goes + through this, so a setup always serialises and never shares (or has + normalised in place by ``aa.Imaging``) an array with a dataset. + """ + if obj is None or isinstance(obj, (bool, int, float, np.integer, np.floating)): + return obj + if isinstance(obj, aa.Convolver): + return aa.Convolver( + kernel=_clean_array(obj.kernel), + use_fft=obj._use_fft, + convolve_over_sample_size=obj.convolve_over_sample_size, + ) + if isinstance(obj, aa.Mask2D): + return _clean_mask(obj) + if isinstance(obj, aa.Array2D): + return _clean_array(obj) + return from_dict(to_dict(obj)) + + +class ObservationSetup: + def __init__( + self, + mask: aa.Mask2D, + psf: Optional[aa.Convolver], + noise_map: aa.Array2D, + pixel_scales: Optional[Tuple[float, float]] = None, + origin: Optional[Tuple[float, float]] = None, + over_sample_size_lp: Union[int, aa.Array2D] = 4, + over_sample_size_pixelization: Union[int, aa.Array2D] = 4, + cosmology=None, + exposure_time: Optional[float] = None, + background_sky_level: Optional[float] = None, + ): + """ + How a lens is observed: mask, PSF, observed noise map and sampling. + + Parameters + ---------- + mask + The mask of the observation; twins are simulated and stored on it. + psf + The PSF as an ``al.Convolver`` (already normalised, as held by the dataset). + noise_map + The observed noise map (standard deviation per pixel) on ``mask``. It is + the default noise of every twin (ruling R2). + pixel_scales, origin + Default to the mask's values. + over_sample_size_lp, over_sample_size_pixelization + Over-sampling of the light-profile and pixelization grids (an int or an + ``aa.Array2D`` on ``mask``), as used by the fit. + cosmology + The cosmology the twin is interpreted in; ``None`` means the tracer's own. + exposure_time, background_sky_level + Only used by the ``"poisson"`` noise route, which requires both. + """ + mask = _copy(mask) + self.mask = mask + self.psf = _copy(psf) + self.noise_map = _copy(noise_map) + self.pixel_scales = tuple( + mask.pixel_scales if pixel_scales is None else pixel_scales + ) + self.origin = tuple(mask.origin if origin is None else origin) + self.over_sample_size_lp = _copy(over_sample_size_lp) + self.over_sample_size_pixelization = _copy(over_sample_size_pixelization) + self.cosmology = cosmology + self.exposure_time = exposure_time + self.background_sky_level = background_sky_level + + def __repr__(self): + return ( + f"ObservationSetup(shape_native={self.mask.shape_native}, " + f"pixels_in_mask={self.mask.pixels_in_mask}, " + f"pixel_scales={self.pixel_scales}, " + f"exposure_time={self.exposure_time}, " + f"background_sky_level={self.background_sky_level})" + ) + + @property + def fields(self) -> dict: + """The constructor arguments of this setup, by name.""" + return {name: getattr(self, name) for name in _FIELDS} + + @classmethod + def from_dataset( + cls, + dataset: aa.Imaging, + cosmology=None, + exposure_time: Optional[float] = None, + background_sky_level: Optional[float] = None, + ) -> "ObservationSetup": + """ + The setup of a masked ``al.Imaging`` dataset: its mask, PSF, noise map and + over-sampling. The PSF and noise map are copied so later changes to the + dataset do not leak into the setup. + """ + return cls( + mask=dataset.mask, + psf=dataset.psf, + noise_map=dataset.noise_map, + over_sample_size_lp=dataset.grids.lp.over_sample_size, + over_sample_size_pixelization=dataset.grids.pixelization.over_sample_size, + cosmology=cosmology, + exposure_time=exposure_time, + background_sky_level=background_sky_level, + ) + + @staticmethod + def dataset_from_fit_directory(path: Union[str, Path]) -> aa.Imaging: + """ + Rebuild the masked, over-sampled ``Imaging`` a model-fit used from its + ``image/dataset.fits`` (HDUs: 0 mask, 1 data, 2 noise map, 3 PSF, + 4 light-profile over-sampling, 5 pixelization over-sampling), as written by + ``AnalysisImaging.save_attributes`` (``autolens/imaging/model/analysis.py``). + + This replicates PyAutoGalaxy's aggregator reload ``_imaging_from`` + (``autogalaxy/aggregator/imaging/imaging.py`` lines 29-115) and + ``agg_util.mask_header_from`` line for line, for a single (non-summed) + analysis, without needing an ``af.Fit``. If that recipe changes, change this. + """ + from astropy.io import fits + + dataset_path = Path(path) / "image" / "dataset.fits" + + with fits.open(dataset_path) as hdu_list: + mask = _util.mask_from_hdu(hdu_list[0]) + header = aa.Header(header_sci_obj=hdu_list[0].header) + + def values_from(hdu: int): + return aa.Array2D.no_mask( + values=_util.ndarray_via_hdu_from(hdu_list[hdu]), + pixel_scales=mask.pixel_scales, + header=header, + origin=mask.origin, + ) + + data = values_from(hdu=1) + noise_map = values_from(hdu=2) + + try: + psf = aa.Convolver(kernel=values_from(hdu=3)) + except (TypeError, IndexError): + psf = None + + dataset = aa.Imaging( + data=data, + noise_map=noise_map, + psf=psf, + check_noise_map=False, + ) + + dataset = dataset.apply_mask(mask=mask) + + try: + over_sample_size_lp = values_from(hdu=4).native + over_sample_size_lp = over_sample_size_lp.apply_mask(mask=mask) + except (TypeError, IndexError): + over_sample_size_lp = 1 + + try: + over_sample_size_pixelization = values_from(hdu=5).native + over_sample_size_pixelization = ( + over_sample_size_pixelization.apply_mask(mask=mask) + ) + except (TypeError, IndexError): + over_sample_size_pixelization = 1 + + return dataset.apply_over_sampling( + over_sample_size_lp=over_sample_size_lp, + over_sample_size_pixelization=over_sample_size_pixelization, + ) + + @classmethod + def from_fit_directory( + cls, + path: Union[str, Path], + cosmology=None, + exposure_time: Optional[float] = None, + background_sky_level: Optional[float] = None, + ) -> "ObservationSetup": + """ + The setup of a model-fit output directory (the folder holding ``image/`` and + ``files/``), read from ``image/dataset.fits`` exactly as the aggregator does + (see ``dataset_from_fit_directory``). + """ + return cls.from_dataset( + dataset=cls.dataset_from_fit_directory(path), + cosmology=cosmology, + exposure_time=exposure_time, + background_sky_level=background_sky_level, + ) + + def with_(self, **overrides) -> "ObservationSetup": + """ + A copy of this setup with the given fields replaced, e.g. + ``setup.with_(exposure_time=2000.0, background_sky_level=1.0)``. + + Fields that depend on the mask (noise map, array over-sampling) are not + re-derived: replacing the mask requires replacing them too. + """ + unknown = set(overrides) - set(_FIELDS) + if unknown: + raise TypeError( + f"ObservationSetup.with_ got unknown field(s) {sorted(unknown)}; " + f"valid fields are {list(_FIELDS)}." + ) + fields = self.fields + if "mask" in overrides: + fields.pop("pixel_scales") + fields.pop("origin") + fields.update(overrides) + return ObservationSetup(**fields) + + @property + def grid(self) -> aa.Grid2D: + """The masked lens-plane grid, over-sampled with ``over_sample_size_lp``.""" + return aa.Grid2D.from_mask( + mask=self.mask, over_sample_size=self.over_sample_size_lp + ) + + def _array_2d_from(self, values) -> aa.Array2D: + """Unmasked native values on the setup's pixel grid (masked entries zero).""" + if isinstance(values, aa.Array2D): + native = _util.native_values_from(values) + else: + values = np.asarray(values, dtype="float64") + if values.shape == self.mask.shape_native: + native = values + else: + native = _util.native_values_from( + aa.Array2D(values=values, mask=self.mask) + ) + if native.shape != self.mask.shape_native: + raise ValueError( + f"Array of native shape {native.shape} does not match the setup mask " + f"shape {self.mask.shape_native}." + ) + native = np.where(np.asarray(self.mask), 0.0, native) + return aa.Array2D.no_mask( + values=native, + pixel_scales=self.mask.pixel_scales, + origin=self.mask.origin, + ) + + def dataset_from(self, data, noise_map=None) -> aa.Imaging: + """ + An ``al.Imaging`` of ``data`` observed with this setup: masked with the setup + mask and over-sampled with its over-sample sizes, following the aggregator's + reload order (build unmasked, ``apply_mask`` once, ``apply_over_sampling``). + + Parameters + ---------- + data + An ``aa.Array2D`` (masked or native) or an ndarray (native or slim). + noise_map + Defaults to the setup's observed noise map. + """ + noise_map = self.noise_map if noise_map is None else noise_map + dataset = aa.Imaging( + data=self._array_2d_from(data), + noise_map=self._array_2d_from(noise_map), + psf=_copy(self.psf), + check_noise_map=False, + use_normalized_psf=False, + ) + dataset = dataset.apply_mask(mask=self.mask) + return dataset.apply_over_sampling( + over_sample_size_lp=_copy(self.over_sample_size_lp), + over_sample_size_pixelization=_copy(self.over_sample_size_pixelization), + ) diff --git a/autolens/twins/simulate.py b/autolens/twins/simulate.py new file mode 100644 index 000000000..6d057e640 --- /dev/null +++ b/autolens/twins/simulate.py @@ -0,0 +1,281 @@ +""" +``SimulatedTwin``: one noisy observation of a twin together with its ground truth, +seed, noise route, simulator settings and the twin (reference provenance plus +transformation chain) it came from. +""" + +import json +import logging +from pathlib import Path +from typing import Dict, Union + + +import autoarray as aa +from autonerves.class_path import get_class_path +from autonerves.dictable import from_dict, from_json, output_to_json, to_dict + +from autolens.twins import _util +from autolens.twins._util import Frozen +from autolens.twins.reference import ReferenceModel +from autolens.twins.setup import ObservationSetup +from autolens.twins.twin import Twin + +logger = logging.getLogger(__name__) + + +class SimulatedTwin(Frozen): + def __init__( + self, + dataset: aa.Imaging, + truth, + seed: int, + noise: str, + simulator: Dict, + twin: Twin, + ): + """ + A simulated observation of ``twin``. + + Parameters + ---------- + dataset + The simulated ``al.Imaging``, masked and over-sampled like the twin's setup. + truth + The ground-truth tracer that was observed (``twin.tracer``). + seed + The noise seed. + noise + ``"observed"`` or ``"poisson"``. + simulator + The route and settings used (``route``, ``exposure_time``, ...). + twin + The twin that was simulated. + """ + self._freeze_set("dataset", dataset) + self._freeze_set("truth", truth) + self._freeze_set("seed", int(seed)) + self._freeze_set("noise", str(noise)) + simulator = dict(simulator) + # `al.from_dict` drops None-valued dict entries (PyAutoFit's dict parser); + # restore the standard keys so a reloaded twin compares equal. + for key in ("route", "noise", "exposure_time", "background_sky_level"): + simulator.setdefault(key, None) + self._freeze_set("simulator", simulator) + self._freeze_set("twin", twin) + + def __repr__(self): + return ( + f"SimulatedTwin(lens_id={self.twin.reference.lens_id!r}, " + f"seed={self.seed}, noise={self.noise!r})" + ) + + def dict(self) -> dict: + """ + The ``autonerves.dictable`` dictionary. + + ``al.Imaging`` does not round-trip through the dictable contract, so the + ``dataset`` argument is written as a call of ``dataset_via_setup_from`` (a + function ``al.from_dict`` resolves by class path and calls with its + arguments) holding the setup, data and noise map; reloading rebuilds the + masked, over-sampled dataset with ``ObservationSetup.dataset_from``. + """ + return { + "type": "instance", + "class_path": get_class_path(type(self)), + "arguments": { + "dataset": { + "type": "instance", + "class_path": f"{dataset_via_setup_from.__module__}." + f"{dataset_via_setup_from.__qualname__}", + "arguments": { + "setup": to_dict(self.twin.setup), + "data": to_dict(self.dataset.data), + "noise_map": to_dict(self.dataset.noise_map), + }, + }, + "truth": to_dict(self.truth), + "seed": self.seed, + "noise": self.noise, + "simulator": to_dict(self.simulator), + "twin": to_dict(self.twin), + }, + } + + def resimulate(self) -> "SimulatedTwin": + """Simulate the same twin again with the stored seed and noise route.""" + return self.twin.simulate(seed=self.seed, noise=self.noise) + + def twin_json(self) -> dict: + """ + The provenance written to ``twin.json``: the reference provenance (lens id, + fit path, hashes, ingest time, labels, roles, library versions at ingest), + the library versions now, the transformation records (dictable + dictionaries), the setup fields that differ from the reference setup, and + the seed, noise route and simulator settings. + """ + return { + "reference": self.twin.reference.provenance, + "versions": _util.library_versions(), + "records": [to_dict(record) for record in self.twin.records], + "setup_overrides": self.twin.setup_overrides(), + "seed": self.seed, + "noise": self.noise, + "simulator": self.simulator, + } + + def output_to(self, directory: Union[str, Path]): + """ + Write the observation and everything needed to reproduce it: + + - ``data.fits``, ``noise_map.fits``, ``psf.fits``, ``mask.fits``: native + arrays (no visualisation zoom) with the mask's pixel scales in the header. + - ``truth_tracer.json``: the ground truth. + - ``twin.json``: see ``twin_json``. + - ``setup.json``: the twin's complete setup. The FITS files alone cannot + rebuild it (over-sampling, cosmology, exposure time and sky level are not + in them, and a Poisson noise map differs from the setup's). + - ``reference_setup.json`` / ``reference_tracer.json``: only when the twin's + setup / tracer differ from the reference's, so the reference can be + rebuilt without the original fit directory. + """ + directory = Path(directory) + directory.mkdir(parents=True, exist_ok=True) + + mask = self.dataset.mask + + _util.output_array_to_fits( + _util.native_values_from(self.dataset.data), + mask=mask, + file_path=directory / "data.fits", + ext_name="data", + ) + _util.output_array_to_fits( + _util.native_values_from(self.dataset.noise_map), + mask=mask, + file_path=directory / "noise_map.fits", + ext_name="noise_map", + ) + if self.dataset.psf is not None: + _util.output_array_to_fits( + _util.native_values_from(self.dataset.psf.kernel), + mask=self.dataset.psf.kernel.mask, + file_path=directory / "psf.fits", + ext_name="psf", + ) + _util.output_mask_to_fits(mask, directory / "mask.fits") + + output_to_json(self.truth, directory / "truth_tracer.json") + output_to_json(self.twin.setup, directory / "setup.json") + + reference = self.twin.reference + if _canonical(reference.setup) != _canonical(self.twin.setup): + output_to_json(reference.setup, directory / "reference_setup.json") + if _canonical(reference.tracer) != _canonical(self.truth): + output_to_json(reference.tracer, directory / "reference_tracer.json") + + with open(directory / "twin.json", "w") as f: + json.dump(self.twin_json(), f, indent=4) + + @classmethod + def from_directory(cls, directory: Union[str, Path]) -> "SimulatedTwin": + """ + Reload a simulated twin written by ``output_to``. + + The reference is resolved from its ``fit_path`` when that directory still + holds a ``dataset.fits`` and ``tracer.json`` whose SHA-256 match the stored + provenance (setup fields not in the FITS are taken from the stored + reference setup); otherwise it is rebuilt from the embedded provenance, the + stored reference tracer (or the truth tracer, when they are the same) and + the stored reference setup (or the twin setup). + """ + directory = Path(directory) + + with open(directory / "twin.json") as f: + twin_json = json.load(f) + + setup = from_json(file_path=directory / "setup.json") + truth = from_json(file_path=directory / "truth_tracer.json") + + reference = _reference_from( + directory=directory, + provenance=twin_json["reference"], + twin_setup=setup, + truth=truth, + ) + + twin = Twin( + reference=reference, + tracer=truth, + setup=setup, + records=[from_dict(record) for record in twin_json["records"]], + ) + + data = _util.ndarray_from_fits(directory / "data.fits") + noise_map = _util.ndarray_from_fits(directory / "noise_map.fits") + + return cls( + dataset=setup.dataset_from(data=data, noise_map=noise_map), + truth=truth, + seed=twin_json["seed"], + noise=twin_json["noise"], + simulator=twin_json["simulator"], + twin=twin, + ) + + +def dataset_via_setup_from(setup: ObservationSetup, data, noise_map) -> aa.Imaging: + """ + ``setup.dataset_from(data, noise_map)``; the reload hook ``SimulatedTwin.dict`` + points ``al.from_dict`` at. + """ + return setup.dataset_from(data=data, noise_map=noise_map) + + +def _canonical(obj) -> str: + return json.dumps(to_dict(obj), sort_keys=True) + + +def _reference_from( + directory: Path, provenance: dict, twin_setup: ObservationSetup, truth +) -> ReferenceModel: + reference_setup_path = directory / "reference_setup.json" + reference_tracer_path = directory / "reference_tracer.json" + + stored_setup = ( + from_json(file_path=reference_setup_path) + if reference_setup_path.exists() + else twin_setup + ) + + fit_path = provenance.get("fit_path") + if fit_path is not None: + fit_path = Path(fit_path) + tracer_path = fit_path / "files" / "tracer.json" + dataset_path = fit_path / "image" / "dataset.fits" + if ( + tracer_path.exists() + and dataset_path.exists() + and _util.sha256_of_file(tracer_path) == provenance.get("tracer_sha256") + and _util.sha256_of_file(dataset_path) == provenance.get("dataset_sha256") + ): + setup = ObservationSetup.from_fit_directory(fit_path).with_( + cosmology=stored_setup.cosmology, + exposure_time=stored_setup.exposure_time, + background_sky_level=stored_setup.background_sky_level, + ) + return ReferenceModel( + tracer=from_json(file_path=tracer_path), + setup=setup, + provenance=provenance, + ) + logger.info( + f"Reference fit_path {fit_path} is missing or its files changed; " + f"rebuilding the reference from the stored provenance." + ) + + tracer = ( + from_json(file_path=reference_tracer_path) + if reference_tracer_path.exists() + else truth + ) + return ReferenceModel(tracer=tracer, setup=stored_setup, provenance=provenance) diff --git a/autolens/twins/transform/__init__.py b/autolens/twins/transform/__init__.py new file mode 100644 index 000000000..2c1fd7c06 --- /dev/null +++ b/autolens/twins/transform/__init__.py @@ -0,0 +1,20 @@ +""" +Transformations of a twin. + +A transformation is any object with ``apply(twin) -> (tracer, setup, record)``: +it returns the new ground-truth tracer, the (possibly unchanged) observation setup +and a ``TransformationRecord`` describing the change. ``Twin.apply`` wraps the +result into a new ``Twin`` with the record appended; a transformation must not +mutate the twin, its tracer or its setup. +""" + +from typing import Protocol, Tuple, runtime_checkable + +from autolens.twins.transform.identity import Identity + + +@runtime_checkable +class Transformation(Protocol): + def apply(self, twin) -> Tuple[object, object, object]: + """Return ``(tracer, setup, record)`` for ``twin`` without mutating it.""" + ... diff --git a/autolens/twins/transform/identity.py b/autolens/twins/transform/identity.py new file mode 100644 index 000000000..d2f9191e5 --- /dev/null +++ b/autolens/twins/transform/identity.py @@ -0,0 +1,20 @@ +from autolens.twins.record import TransformationRecord + + +class Identity: + """ + The do-nothing transformation: returns the twin's tracer and setup unchanged + and a record named ``"Identity"`` with empty ``changed``, ``side_effects`` and + ``preserved``. It exists so the transformation chain and its JSON are exercised + before any physical transformation is available. + """ + + def apply(self, twin): + record = TransformationRecord( + name="Identity", + requested={}, + procedure={ + "text": "No change: the tracer and observation setup are returned unchanged." + }, + ) + return twin.tracer, twin.setup, record diff --git a/autolens/twins/twin.py b/autolens/twins/twin.py new file mode 100644 index 000000000..7c2c16576 --- /dev/null +++ b/autolens/twins/twin.py @@ -0,0 +1,212 @@ +""" +``Twin``: a reference model's tracer and setup after a chain of recorded +transformations. A twin is a value: ``apply`` and ``with_setup`` return new twins +and nothing mutates the reference, the tracer or the setup. +""" + +import copy +import json +from typing import Iterable, Optional + +import numpy as np + +from autonerves.dictable import to_dict + +from autolens.twins._util import Frozen +from autolens.twins.record import TransformationRecord +from autolens.twins.reference import ReferenceModel +from autolens.twins.setup import ObservationSetup + +NOISE_ROUTES = ("observed", "poisson") + +OBSERVED_ROUTE = "tracer.blurred_image_2d_from" +POISSON_ROUTE = "al.SimulatorImaging.via_tracer_from" + + +def _check_seed(seed) -> int: + if ( + isinstance(seed, bool) + or not isinstance(seed, (int, np.integer)) + or int(seed) < 0 + ): + raise ValueError( + f"seed must be a non-negative integer (got {seed!r}); a twin is always " + f"simulated with an explicit seed so it can be reproduced." + ) + return int(seed) + + +class Twin(Frozen): + def __init__( + self, + reference: ReferenceModel, + tracer=None, + setup: Optional[ObservationSetup] = None, + records: Iterable[TransformationRecord] = (), + ): + """ + A ground-truth tracer and observation setup derived from ``reference``. + + Parameters + ---------- + reference + The immutable parent. + tracer + The ground truth; defaults to a copy of the reference tracer. + setup + Defaults to the reference setup. + records + The transformation chain, oldest first. + """ + self._freeze_set("reference", reference) + self._freeze_set( + "tracer", copy.deepcopy(reference.tracer) if tracer is None else tracer + ) + self._freeze_set("setup", reference.setup if setup is None else setup) + self._freeze_set("records", tuple(records)) + + def __repr__(self): + return ( + f"Twin(lens_id={self.reference.lens_id!r}, " + f"records={[record.name for record in self.records]})" + ) + + @classmethod + def baseline(cls, reference: ReferenceModel) -> "Twin": + """The untransformed twin: a copy of the reference tracer on its setup.""" + return cls(reference=reference) + + def apply(self, transformation) -> "Twin": + """A new twin with ``transformation`` applied and its record appended.""" + tracer, setup, record = transformation.apply(self) + if not isinstance(record, TransformationRecord): + raise TypeError( + f"{type(transformation).__name__}.apply must return a " + f"TransformationRecord as its third value, got {type(record).__name__}." + ) + return Twin( + reference=self.reference, + tracer=tracer, + setup=setup, + records=self.records + (record,), + ) + + def with_setup(self, setup: ObservationSetup) -> "Twin": + """A new twin observed with ``setup`` (e.g. ``setup.with_(exposure_time=...)``).""" + return Twin( + reference=self.reference, + tracer=self.tracer, + setup=setup, + records=self.records, + ) + + def setup_overrides(self) -> dict: + """ + The setup fields that differ from the reference setup, as dictable + dictionaries (empty for a twin observed exactly like its reference). + """ + reference_fields = self.reference.setup.fields + overrides = {} + for name, value in self.setup.fields.items(): + value_dict = to_dict(value) + if json.dumps(value_dict, sort_keys=True) != json.dumps( + to_dict(reference_fields[name]), sort_keys=True + ): + overrides[name] = value_dict + return overrides + + def noise_free_image_2d(self): + """ + The PSF-convolved, noise-free image of the twin's tracer on the setup mask. + + Computed with ``tracer.blurred_image_2d_from`` on the light-profile and + blurring grids of ``setup.dataset_from(...)``: the same forward model a + ``FitImaging`` of that dataset uses, without any noise draw. + """ + dataset = self.setup.dataset_from(data=self.setup.noise_map) + return self.tracer.blurred_image_2d_from( + grid=dataset.grids.lp, + blurring_grid=dataset.grids.blurring, + psf=dataset.psf, + ) + + def simulate(self, seed: int, noise: str = "observed"): + """ + Simulate an observation of the twin. + + ``noise="observed"`` (default, ruling R2): ``noise_free_image_2d()`` plus + Gaussian noise drawn from the setup's observed noise map with + ``numpy.random.default_rng(seed)`` on unmasked pixels only. The global NumPy + random state is neither read nor changed. The noise map is the setup's. + + ``noise="poisson"``: ``al.SimulatorImaging`` with the setup's + ``exposure_time`` and ``background_sky_level`` and ``noise_seed=seed`` + (Poisson noise, noise map from the counts). Both fields must be set. This + route seeds NumPy's global random state, as the simulator does. + """ + from autolens.twins.simulate import SimulatedTwin + + seed = _check_seed(seed) + + if noise == "observed": + image = self.noise_free_image_2d() + noise_map = self.setup.noise_map + rng = np.random.default_rng(seed) + data = np.asarray(image.array) + rng.normal( + loc=0.0, scale=np.asarray(noise_map.array) + ) + dataset = self.setup.dataset_from(data=data, noise_map=noise_map) + simulator = { + "route": OBSERVED_ROUTE, + "noise": "gaussian: numpy.random.default_rng(seed).normal(0, noise_map)", + "exposure_time": None, + "background_sky_level": None, + } + elif noise == "poisson": + dataset, simulator = self._simulate_poisson(seed=seed) + else: + raise ValueError(f"noise must be one of {NOISE_ROUTES}, got {noise!r}.") + + return SimulatedTwin( + dataset=dataset, + truth=self.tracer, + seed=seed, + noise=noise, + simulator=simulator, + twin=self, + ) + + def _simulate_poisson(self, seed: int): + from autolens.imaging.simulator import SimulatorImaging + from autolens.twins.setup import _copy + + for field in ("exposure_time", "background_sky_level"): + if getattr(self.setup, field) is None: + raise ValueError( + f'noise="poisson" requires setup.{field} to be set; use ' + f"twin.with_setup(twin.setup.with_({field}=...)) or the default " + f'noise="observed".' + ) + + simulator = SimulatorImaging( + exposure_time=self.setup.exposure_time, + background_sky_level=self.setup.background_sky_level, + psf=_copy(self.setup.psf), + noise_seed=seed, + ) + # A copy, because `via_tracer_from` sets the intensity of any + # `LightProfileSNR` in place; the twin's ground truth must not change. + simulated = simulator.via_tracer_from( + tracer=copy.deepcopy(self.tracer), grid=self.setup.grid + ) + dataset = self.setup.dataset_from( + data=simulated.data.native.array, + noise_map=simulated.noise_map.native.array, + ) + settings = { + "route": POISSON_ROUTE, + "noise": "poisson: SimulatorImaging(noise_seed=seed)", + "exposure_time": self.setup.exposure_time, + "background_sky_level": self.setup.background_sky_level, + } + return dataset, settings diff --git a/docs/api/twins.rst b/docs/api/twins.rst new file mode 100644 index 000000000..a2cc34fb6 --- /dev/null +++ b/docs/api/twins.rst @@ -0,0 +1,52 @@ +===== +Twins +===== + +``al.twins`` turns a fitted lens into controlled, reproducible simulations +("twins") that carry their ground truth and provenance. + +A fit is ingested as a ``ReferenceModel`` (the tracer with its solved +intensities, the ``ObservationSetup`` -- mask, PSF, observed noise map, +over-sampling -- and a provenance record with file hashes and library +versions). A ``Twin`` is that tracer and setup after a chain of +transformations, each leaving a ``TransformationRecord``. Simulating a twin with +a seed gives a ``SimulatedTwin``, written as FITS beside its truth tracer and a +``twin.json`` provenance file. + +Three invariants: + +1. A reference model is immutable, and one reference has many twins. +2. Preserving any parent property is a recorded choice, never implicit. +3. Every simulated observation carries its ground truth, transformation chain, + seed and library versions beside the FITS. + +The default noise is the observed noise map (Gaussian noise drawn with +``numpy.random.default_rng(seed)``); Poisson noise (``noise="poisson"``) needs +the setup's ``exposure_time`` and ``background_sky_level``. + +.. code-block:: python + + import autolens as al + + reference = al.twins.ReferenceModel.from_fit_directory( + "output/lens_fit/", lens_id="lens_001" + ) + twin = al.twins.Twin.baseline(reference).apply(al.twins.transform.Identity()) + simulated = twin.simulate(seed=1) + simulated.output_to("twins/lens_001/baseline_seed_1") + reloaded = al.twins.SimulatedTwin.from_directory("twins/lens_001/baseline_seed_1") + resimulated = reloaded.resimulate() # bit-identical to reloaded.dataset.data + +.. currentmodule:: autolens.twins + +.. autosummary:: + :toctree: _autosummary + :template: custom-class-template.rst + :recursive: + + ObservationSetup + ReferenceModel + Twin + SimulatedTwin + TransformationRecord + transform.Identity diff --git a/docs/index.md b/docs/index.md index 25a719a5e..c28c05073 100644 --- a/docs/index.md +++ b/docs/index.md @@ -272,5 +272,6 @@ api/pixelization api/point api/plot api/potential_correction +api/twins api/source ``` diff --git a/test_autolens/point/test_dataset.py b/test_autolens/point/test_dataset.py index 087fadfc6..cf3ab24bd 100644 --- a/test_autolens/point/test_dataset.py +++ b/test_autolens/point/test_dataset.py @@ -1,3 +1,4 @@ +import numpy as np import pytest import autolens as al @@ -6,7 +7,7 @@ def _assert_grid_close(actual, expected): actual_pairs = [(float(p[0]), float(p[1])) for p in actual] expected_pairs = [(float(p[0]), float(p[1])) for p in expected] - assert actual_pairs == pytest.approx(expected_pairs) + assert np.array(actual_pairs) == pytest.approx(np.array(expected_pairs)) def _assert_array_close(actual, expected): diff --git a/test_autolens/twins/__init__.py b/test_autolens/twins/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/test_autolens/twins/test_twins.py b/test_autolens/twins/test_twins.py new file mode 100644 index 000000000..fc1889d80 --- /dev/null +++ b/test_autolens/twins/test_twins.py @@ -0,0 +1,441 @@ +import json +import shutil + +import numpy as np +import pytest +import yaml +from astropy.io import fits + +import autofit as af +import autolens as al +from autolens.twins.transform import Transformation + + +def _canonical(obj) -> str: + return json.dumps(al.to_dict(obj), sort_keys=True) + + +class _FitStub: + """ + The part of a `PyAutoFit` aggregator `Fit` that `_imaging_from` reads: `value("dataset")` returning the + `dataset.fits` HDU list written by `AnalysisImaging.save_attributes`. + """ + + def __init__(self, paths): + self.paths = paths + self.children = [] + + def value(self, name): + if name == "dataset": + return fits.open(self.paths.image_path / "dataset.fits") + return None + + +@pytest.fixture(name="fit_paths") +def make_fit_paths(tmp_path, analysis_imaging_7x7, tracer_x2_plane_7x7): + """ + A model-fit output directory as `AnalysisImaging` writes it: `image/dataset.fits` (via + `save_attributes`) and `files/tracer.json` (via `save_results`). + """ + model = af.Collection( + galaxies=af.Collection( + lens=al.Galaxy(redshift=0.5), source=al.Galaxy(redshift=1.0) + ) + ) + paths = af.DirectoryPaths(name="twin_fit", path_prefix=str(tmp_path / "fits")) + + analysis_imaging_7x7.save_attributes(paths=paths) + analysis_imaging_7x7.save_results( + paths=paths, + result=al.m.MockResult( + max_log_likelihood_tracer=tracer_x2_plane_7x7, model=model + ), + ) + + return paths + + +@pytest.fixture(name="reference") +def make_reference(fit_paths): + return al.twins.ReferenceModel.from_fit_directory( + fit_paths.output_path, + lens_id="lens_7x7", + labels=("fixture", "x2_plane"), + roles={"galaxy_0": "main_deflector"}, + ) + + +@pytest.fixture(name="twin") +def make_twin(reference): + return al.twins.Twin.baseline(reference) + + +def test__exports(): + for name in ( + "ObservationSetup", + "ReferenceModel", + "Twin", + "SimulatedTwin", + "TransformationRecord", + "transform", + ): + assert hasattr(al.twins, name) + assert isinstance(al.twins.transform.Identity(), Transformation) + + +def test__from_fit_directory__ingests_reference( + reference, fit_paths, tracer_x2_plane_7x7 +): + assert isinstance(reference, al.twins.ReferenceModel) + assert isinstance(reference.setup, al.twins.ObservationSetup) + assert _canonical(reference.tracer) == _canonical(tracer_x2_plane_7x7) + + provenance = reference.provenance + assert provenance["lens_id"] == "lens_7x7" + assert provenance["labels"] == ["fixture", "x2_plane"] + assert provenance["roles"] == {"galaxy_0": "main_deflector"} + assert provenance["fit_path"] == str(fit_paths.output_path.resolve()) + assert len(provenance["dataset_sha256"]) == 64 + assert len(provenance["tracer_sha256"]) == 64 + assert provenance["ingested_at"].endswith("+00:00") + for name in ("autofit", "autoarray", "autogalaxy", "autolens", "numpy", "python"): + assert name in provenance["versions"] + assert provenance["versions"]["numpy"] == np.__version__ + + +def test__reference__is_immutable(reference): + with pytest.raises(AttributeError): + reference.tracer = None + with pytest.raises(AttributeError): + reference.setup = None + with pytest.raises(AttributeError): + del reference.tracer + + provenance = reference.provenance + provenance["lens_id"] = "changed" + assert reference.provenance["lens_id"] == "lens_7x7" + + +def test__setup_from_fit_directory__matches_aggregator_reload(fit_paths, reference): + from autogalaxy.aggregator.imaging.imaging import _imaging_from + + aggregated = _imaging_from(fit=_FitStub(paths=fit_paths))[0] + rebuilt = al.twins.ObservationSetup.dataset_from_fit_directory( + fit_paths.output_path + ) + setup = reference.setup + + assert np.array_equal(rebuilt.data.native.array, aggregated.data.native.array) + assert np.array_equal( + rebuilt.noise_map.native.array, aggregated.noise_map.native.array + ) + assert np.array_equal( + rebuilt.psf.kernel.native.array, aggregated.psf.kernel.native.array + ) + assert np.array_equal(np.asarray(rebuilt.mask), np.asarray(aggregated.mask)) + + assert np.array_equal(np.asarray(setup.mask), np.asarray(aggregated.mask)) + assert setup.pixel_scales == aggregated.mask.pixel_scales + assert setup.origin == aggregated.mask.origin + assert np.array_equal( + setup.noise_map.native.array, aggregated.noise_map.native.array + ) + assert np.array_equal( + setup.psf.kernel.native.array, aggregated.psf.kernel.native.array + ) + assert np.array_equal( + np.asarray(setup.over_sample_size_lp), + np.asarray(aggregated.grids.lp.over_sample_size), + ) + + +def test__setup_from_fit_directory__matches_fitted_dataset( + reference, masked_imaging_7x7 +): + setup = reference.setup + + assert setup.mask.pixels_in_mask == masked_imaging_7x7.mask.pixels_in_mask + assert np.array_equal(setup.noise_map.array, masked_imaging_7x7.noise_map.array) + assert np.allclose( + setup.psf.kernel.native.array, masked_imaging_7x7.psf.kernel.native.array + ) + assert np.array_equal(setup.grid.array, masked_imaging_7x7.grids.lp.array) + + +def test__setup__with_returns_modified_copy(reference): + setup = reference.setup + modified = setup.with_(exposure_time=300.0, background_sky_level=0.1) + + assert modified.exposure_time == 300.0 + assert modified.background_sky_level == 0.1 + assert setup.exposure_time is None + assert np.array_equal(modified.noise_map.array, setup.noise_map.array) + + with pytest.raises(TypeError): + setup.with_(not_a_field=1) + + +def test__from_result(masked_imaging_7x7, tracer_x2_plane_7x7): + result = al.m.MockResult(max_log_likelihood_tracer=tracer_x2_plane_7x7) + + reference = al.twins.ReferenceModel.from_result( + result=result, dataset=masked_imaging_7x7, lens_id="from_result" + ) + + assert reference.tracer is tracer_x2_plane_7x7 + assert np.array_equal( + reference.setup.noise_map.array, masked_imaging_7x7.noise_map.array + ) + assert reference.provenance["fit_path"] is None + assert len(reference.provenance["dataset_sha256"]) == 64 + assert len(reference.provenance["tracer_sha256"]) == 64 + + +def test__baseline__noise_free_image_equals_simulator(twin, reference): + image = twin.noise_free_image_2d() + + simulator = al.SimulatorImaging( + exposure_time=1.0, + psf=al.twins.setup._copy(reference.setup.psf), + add_poisson_noise_to_data=False, + include_poisson_noise_in_noise_map=False, + noise_seed=1, + ) + simulated = simulator.via_tracer_from( + tracer=reference.tracer, grid=reference.setup.grid + ) + simulated = al.Array2D(values=simulated.data.native, mask=reference.setup.mask) + + assert np.array_equal(image.array, simulated.array) + + dataset = reference.setup.dataset_from(data=reference.setup.noise_map) + blurred = reference.tracer.blurred_image_2d_from( + grid=dataset.grids.lp, blurring_grid=dataset.grids.blurring, psf=dataset.psf + ) + assert np.array_equal(image.array, blurred.array) + + +def test__baseline__tracer_is_a_copy(twin, reference): + assert twin.tracer is not reference.tracer + assert _canonical(twin.tracer) == _canonical(reference.tracer) + assert twin.records == () + + +def test__simulate__seed_determinism_and_sensitivity(twin): + simulated_1 = twin.simulate(seed=1) + simulated_1_again = twin.simulate(seed=1) + simulated_2 = twin.simulate(seed=2) + + assert np.array_equal( + simulated_1.dataset.data.array, simulated_1_again.dataset.data.array + ) + assert not np.array_equal( + simulated_1.dataset.data.array, simulated_2.dataset.data.array + ) + + assert np.array_equal( + simulated_1.dataset.noise_map.array, twin.setup.noise_map.array + ) + assert simulated_1.seed == 1 + assert simulated_1.noise == "observed" + assert simulated_1.simulator["route"] == "tracer.blurred_image_2d_from" + assert simulated_1.truth is twin.tracer + assert simulated_1.dataset.mask.pixels_in_mask == twin.setup.mask.pixels_in_mask + + residual = simulated_1.dataset.data.array - twin.noise_free_image_2d().array + expected = np.random.default_rng(1).normal(0.0, twin.setup.noise_map.array) + assert np.allclose(residual, expected) + + +def test__simulate__observed_route_leaves_global_random_state(twin): + np.random.seed(5) + expected = np.random.rand() + + np.random.seed(5) + twin.simulate(seed=1) + assert np.random.rand() == expected + + +def test__simulate__noise_route_errors(twin): + with pytest.raises(ValueError, match="exposure_time"): + twin.simulate(seed=1, noise="poisson") + + no_sky = twin.with_setup(twin.setup.with_(exposure_time=300.0)) + with pytest.raises(ValueError, match="background_sky_level"): + no_sky.simulate(seed=1, noise="poisson") + + with pytest.raises(ValueError, match="noise"): + twin.simulate(seed=1, noise="gaussian") + + with pytest.raises(ValueError, match="seed"): + twin.simulate(seed=-1) + + +def test__simulate__poisson_route(twin): + poisson_twin = twin.with_setup( + twin.setup.with_(exposure_time=300.0, background_sky_level=0.1) + ) + + simulated = poisson_twin.simulate(seed=3, noise="poisson") + simulated_again = poisson_twin.simulate(seed=3, noise="poisson") + + assert np.array_equal( + simulated.dataset.data.array, simulated_again.dataset.data.array + ) + assert simulated.simulator["route"] == "al.SimulatorImaging.via_tracer_from" + assert simulated.simulator["exposure_time"] == 300.0 + assert not np.array_equal( + simulated.dataset.noise_map.array, twin.setup.noise_map.array + ) + assert poisson_twin.setup_overrides().keys() == { + "exposure_time", + "background_sky_level", + } + + +def test__identity__record_and_apply(twin): + applied = twin.apply(al.twins.transform.Identity()) + + assert len(applied.records) == 1 + record = applied.records[0] + assert record.name == "Identity" + assert record.changed == [] + assert record.side_effects == [] + assert record.preserved == [] + + assert twin.records == () + assert applied.reference is twin.reference + assert np.array_equal( + applied.noise_free_image_2d().array, twin.noise_free_image_2d().array + ) + + reloaded = al.from_dict(json.loads(json.dumps(al.to_dict(record)))) + assert reloaded == record + + +def test__apply__requires_a_record(twin): + class Broken: + def apply(self, twin): + return twin.tracer, twin.setup, {"name": "not a record"} + + with pytest.raises(TypeError): + twin.apply(Broken()) + + +def test__to_dict_from_dict__round_trips(reference, twin): + record = al.twins.TransformationRecord( + name="Example", + requested={"factor": 1.5}, + procedure={"text": "scaled", "derived": 2.0}, + changed=["galaxies.lens.mass"], + side_effects=["einstein_radius"], + ) + simulated = twin.apply(al.twins.transform.Identity()).simulate(seed=4) + + for obj in (reference.setup, reference, record, twin, simulated): + dictionary = _canonical(obj) + reloaded = al.from_dict(json.loads(dictionary)) + assert type(reloaded) is type(obj) + assert _canonical(reloaded) == dictionary + + reloaded = al.from_dict(json.loads(_canonical(simulated))) + assert np.array_equal(reloaded.dataset.data.array, simulated.dataset.data.array) + assert reloaded.dataset.mask.pixels_in_mask == simulated.dataset.mask.pixels_in_mask + assert np.array_equal( + reloaded.resimulate().dataset.data.array, simulated.dataset.data.array + ) + + +def test__reference__output_to_and_from_directory(reference, tmp_path): + reference.output_to(tmp_path / "reference") + + for name in ("tracer.json", "provenance.json", "labels.yaml"): + assert (tmp_path / "reference" / name).exists() + for name in ("mask.fits", "noise_map.fits", "psf.fits", "setup.json"): + assert (tmp_path / "reference" / "setup" / name).exists() + + with open(tmp_path / "reference" / "labels.yaml") as f: + labels = yaml.safe_load(f) + assert labels["lens_id"] == "lens_7x7" + assert labels["labels"] == ["fixture", "x2_plane"] + + reloaded = al.twins.ReferenceModel.from_directory(tmp_path / "reference") + + assert reloaded.provenance == reference.provenance + assert _canonical(reloaded.tracer) == _canonical(reference.tracer) + assert _canonical(reloaded.setup) == _canonical(reference.setup) + assert isinstance(al.from_json(tmp_path / "reference" / "tracer.json"), al.Tracer) + + +def test__simulated_twin__output_from_directory_resimulate(twin, tmp_path): + simulated = twin.simulate(seed=1) + output = tmp_path / "simulated" + simulated.output_to(output) + + for name in ( + "data.fits", + "noise_map.fits", + "psf.fits", + "mask.fits", + "truth_tracer.json", + "twin.json", + "setup.json", + ): + assert (output / name).exists() + + with open(output / "twin.json") as f: + twin_json = json.load(f) + assert twin_json["seed"] == 1 + assert twin_json["noise"] == "observed" + assert twin_json["records"] == [] + assert twin_json["setup_overrides"] == {} + assert twin_json["reference"]["lens_id"] == "lens_7x7" + assert ( + twin_json["reference"]["dataset_sha256"] + == twin.reference.provenance["dataset_sha256"] + ) + assert "autolens" in twin_json["versions"] + assert isinstance(al.from_json(output / "truth_tracer.json"), al.Tracer) + + stored = al.twins._util.ndarray_from_fits(output / "data.fits") + + reloaded = al.twins.SimulatedTwin.from_directory(output) + assert reloaded.seed == 1 + assert reloaded.noise == "observed" + assert reloaded.twin.reference.provenance == twin.reference.provenance + assert np.array_equal(reloaded.dataset.data.native.array, stored) + + resimulated = reloaded.resimulate() + assert np.array_equal(resimulated.dataset.data.native.array, stored) + + +def test__simulated_twin__from_directory_without_fit_path(twin, fit_paths, tmp_path): + transformed = twin.apply(al.twins.transform.Identity()).with_setup( + twin.setup.with_(exposure_time=300.0, background_sky_level=0.1) + ) + simulated = transformed.simulate(seed=7) + output = tmp_path / "simulated" + simulated.output_to(output) + + assert (output / "reference_setup.json").exists() + assert not (output / "reference_tracer.json").exists() + + with open(output / "twin.json") as f: + twin_json = json.load(f) + assert [record["arguments"]["name"] for record in twin_json["records"]] == [ + "Identity" + ] + assert set(twin_json["setup_overrides"]) == { + "exposure_time", + "background_sky_level", + } + + shutil.rmtree(fit_paths.output_path) + + reloaded = al.twins.SimulatedTwin.from_directory(output) + stored = al.twins._util.ndarray_from_fits(output / "data.fits") + + assert reloaded.twin.reference.setup.exposure_time is None + assert reloaded.twin.setup.exposure_time == 300.0 + assert len(reloaded.twin.records) == 1 + assert np.array_equal(reloaded.resimulate().dataset.data.native.array, stored)