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
1 change: 1 addition & 0 deletions autolens/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
39 changes: 39 additions & 0 deletions autolens/twins/__init__.py
Original file line number Diff line number Diff line change
@@ -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",
]
172 changes: 172 additions & 0 deletions autolens/twins/_util.py
Original file line number Diff line number Diff line change
@@ -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])
76 changes: 76 additions & 0 deletions autolens/twins/record.py
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading