Skip to content

feat: al.twins core: ReferenceModel, Twin, SimulatedTwin (lenstwin 0B) #803

Closed

Description

@Jammy2211

Overview

Phase 0B of the lenstwin epic (PyAutoMind draft/feature/autolens/lenstwin_epic.md; report lenstwin_epic_report.md §2 architecture, §2.5 provenance, §3 "Phase 0"). A fitted PyAutoLens lens is already a reloadable generative model (files/tracer.json with solved intensities, image/dataset.fits with mask, noise map and PSF), but nothing composes a fit into a simulation with a recorded ground truth, a seed, the observed noise map and a provenance record. This issue adds the autolens/twins/ subpackage (al.twins): a frozen ReferenceModel, a value-like Twin transformed functionally and simulated with a seed, SimulatedTwin with twin.json provenance, TransformationRecord, and transform.Identity. Rulings R1 (names and placement) and R2 (observed noise map by default; Poisson only when exposure_time and background_sky_level are set) are taken and not reopened here. Depends on PyAutoGalaxy 0A — PyAutoLabs/PyAutoGalaxy#671 (may develop against its same-named branch; merges after it). Three invariants: a reference model is immutable and one reference has many twins; preserving any parent property is a recorded choice, never implicit; every simulated observation carries its ground truth, transformation chain, seed and library versions beside the FITS.

Plan

  • Create autolens/twins/ (setup.py, reference.py, twin.py, record.py, simulate.py, transform/{__init__,identity}.py) exporting ObservationSetup, ReferenceModel, Twin, SimulatedTwin, TransformationRecord, transform; add from . import twins to autolens/__init__.py.
  • ObservationSetup from a dataset or a fit directory (reusing the aggregator's dataset.fits reload recipe), with with_(...) copies and a masked lens-plane grid.
  • Immutable ReferenceModel (tracer with solved intensities, setup, provenance with hashes and versions) from a fit directory or a result; output_to / from_directory.
  • Twin.baseline / apply / with_setup / simulate(seed, noise="observed"|"poisson"); "observed" draws Gaussian noise with numpy.random.default_rng(seed) from the setup noise map on the PSF-convolved noise-free image; "poisson" requires exposure time and sky.
  • SimulatedTwin.output_to / from_directory / resimulate with twin.json provenance; every object round-trips through al.to_dict / al.from_dict.
  • transform.Identity and its empty-change record so the chain and JSON are exercised now; tests on the 7x7 fixtures and a data_temp fit directory; docs/api/twins.rst.
  • Out of scope: any mass transformation, MassBudget, Einstein-radius apertures, diagnostics (phases 2–3), the science project (phase 1), workspace or assistant (phase 6).

Tier: judge — merge mode: human /prm

Detailed implementation plan

Affected Repositories

Branch Survey

Repository Current Branch Dirty?
PyAutoLens (origin/main, 4 remote branches, none twin-related) main clean
PyAutoGalaxy (origin/main, 4 remote branches, none twin-related) main clean

No active.md claim on either repo (worktree_check_conflict exit 0).

Suggested branch: feature/lenstwin-p0-twins-core (same name in PyAutoLens and PyAutoGalaxy; CI runs the same-named library branch)

Verified APIs (read from main 2026-10-28; the surveys did not cover PyAutoArray/PyAutoFit)

  • aa.SimulatorImaging(exposure_time, background_sky_level=0.0, subtract_background_sky=True, psf=None, use_real_space_convolution=True, normalize_psf=True, add_poisson_noise_to_data=True, include_poisson_noise_in_noise_map=True, noise_if_add_noise_false=0.1, noise_seed=-1, use_jax=False) — exposure_time has no default. al.SimulatorImaging.via_tracer_from(tracer, grid, xp=None) calls tracer.set_snr_of_snr_light_profiles and pads the grid for the kernel; via_image_from(image, over_sample_size=None, image_is_convolved=False, xp=None) accepts a pre-convolved image.
  • Poisson noise seeds np.random.seed(noise_seed) globally (preprocess.data_eps_with_poisson_noise_added; -1 = random). The "observed" route must use its own numpy.random.default_rng(seed), never global state.
  • aa.Imaging(data, noise_map=None, psf=None, psf_setup_state=False, noise_covariance_matrix=None, over_sample_size_lp=4, over_sample_size_pixelization=4, convolve_over_sample_size_lp=1, convolve_over_sample_size_pixelization=1, use_normalized_psf=True, check_noise_map=True, sparse_operator=None); Imaging.from_fits(pixel_scales, data_path, noise_map_path, data_hdu=0, noise_map_hdu=0, psf_path=None, psf_hdu=0, ..., psf_pixel_scales=None); apply_mask(mask) may be called once only; apply_over_sampling(over_sample_size_lp=None, over_sample_size_pixelization=None). The PSF is an aa.Convolver (al.Convolver).
  • af.ModelInstance.as_model(model_classes=(), excluded_classes=()) exists (autofit/mapper/model.py:522); phase 0 does not need it.
  • Reload recipe: agg_util.mask_header_from(fit, name="dataset") and _imaging_from(fit) (autogalaxy/aggregator/imaging/imaging.py:29) read image/dataset.fits HDUs 0–3 (mask, data, noise map, PSF); AnalysisImaging writes it at paths.image_path / "dataset.fits" (autolens/imaging/model/analysis.py:276). al.{to_dict, from_dict, from_json, output_to_json} come from autonerves.dictable; autolens/__init__.py:145 is from . import potential_correction as pc.

Implementation Steps

  1. Package skeleton. autolens/twins/__init__.py with a module docstring stating the three invariants and exporting the five objects plus transform; from . import twins after line 145 of autolens/__init__.py. Precedent for a self-contained subpackage: autolens/weak/.
  2. setup.py — ObservationSetup (dictable): fields mask (aa.Mask2D), psf (al.Convolver), noise_map (aa.Array2D, observed), pixel_scales, origin, over_sample_size_lp, over_sample_size_pixelization, cosmology, optional exposure_time, background_sky_level. from_dataset(imaging, cosmology=None); from_fit_directory(path) reading image/dataset.fits with the same HDU layout and mask_header_from logic as _imaging_from (do not import the aggregator's private function; replicate the few lines and cite them). with_(**overrides) → modified copy; grid → the masked lens-plane aa.Grid2D with the setup's over-sampling. dataset_from(data) helper → al.Imaging masked and over-sampled like the setup (used by SimulatedTwin).
  3. reference.py — ReferenceModel (frozen; dictable): tracer, setup, provenance (dict: lens_id, labels, roles, fit_path, dataset_sha256, tracer_sha256, ingested_at ISO-8601 UTC, versions via importlib.metadata.version for autofit/autoarray/autogalaxy/autolens/numpy, python). from_fit_directory(path, lens_id, labels=(), roles=None) loads files/tracer.json via al.from_json (solved intensities) and ObservationSetup.from_fit_directory; from_result(result, dataset, lens_id, ...) uses result.max_log_likelihood_tracer and ObservationSetup.from_dataset; output_to(dir) writes tracer.json, setup/ (fits: mask, noise_map, psf), provenance.json, labels.yaml; from_directory(dir) inverts it. Attribute assignment raises (__setattr__ guard or dataclass(frozen=True)).
  4. record.py — TransformationRecord (dictable): name, requested (dict), procedure (text + derived numbers dict), changed (list of galaxy/component paths), side_effects (list), preserved (list, empty by default). transform/__init__.py defines the Transformation protocol: apply(twin) -> (tracer, setup, record); transform/identity.py returns the twin's tracer and setup unchanged and a record name="Identity" with empty changed/side_effects/preserved.
  5. twin.py — Twin (value; dictable): reference, tracer, setup, records (tuple). Twin.baseline(reference); apply(transformation) → new Twin with the record appended (never mutates); with_setup(setup); simulate(seed, noise="observed") → SimulatedTwin. "observed": noise-free image = PSF-convolved tracer.image_2d_from(setup.grid) (either al.SimulatorImaging(exposure_time=1.0, psf=setup.psf, add_poisson_noise_to_data=False, include_poisson_noise_in_noise_map=False).via_tracer_from(tracer, grid) and then replace the noise map, or convolve directly with setup.psf — the implementer chooses and SimulatedTwin.simulator records which), then data = image + rng.normal(0, setup.noise_map) with rng = numpy.random.default_rng(seed), noise map = setup.noise_map. "poisson": al.SimulatorImaging(exposure_time=setup.exposure_time, background_sky_level=setup.background_sky_level, psf=setup.psf, noise_seed=seed).via_tracer_from(...); raise ValueError naming the missing field when either is None. Any other noise value raises.
  6. simulate.py — SimulatedTwin (dictable): dataset (al.Imaging, masked and over-sampled per the setup), truth (the tracer), seed, noise, simulator (dict of settings), twin. output_to(dir) writes data.fits, noise_map.fits, psf.fits, mask.fits, truth_tracer.json, twin.json = {reference: {lens_id, fit_path, dataset_sha256, ingested_at}, versions, records, setup_overrides, seed, noise, simulator}; from_directory(dir) reloads (the reference pointer resolves fit_path when it exists, else the embedded provenance); resimulate() → self.twin.simulate(seed=self.seed, noise=self.noise) and the test asserts bit-identity with the stored data.fits.
  7. Tests test_autolens/twins/ (NumPy only; config pushed by the existing conftest.py): build a fixture fit directory under data_temp with af.DirectoryPaths exactly as test_autolens/analysis/test_analysis.py:157-177 does (run AnalysisImaging far enough to write image/dataset.fits and files/tracer.json, or write them with the analysis's own output helpers). Cases: ingest → ReferenceModel; baseline twin noise-free image equals tracer.image_2d_from(setup.grid) bit-for-bit (before PSF) and the PSF-convolved image equals the simulator's; simulate(seed=1) twice is np.array_equal; seed=2 differs; output_to → from_directory → resimulate is np.array_equal with the stored data; to_dict/from_dict round trip for every object; Identity record serialises and twin.apply(Identity()) has one record and the same tracer; from_fit_directory setup equals what ImagingAgg rebuilds (data, noise map, PSF kernel, mask); "poisson" without exposure time raises; the reference is immutable.
  8. Docs: docs/api/twins.rst (autosummary of the exports, the three invariants, a 6-line usage block from report §2.2) and a line in the API index.
  9. PR body: state the public API grew (new subpackage); note R1/R2 as taken rulings; name the simulator route chosen for "observed".

Key Files

  • autolens/__init__.py:145 — add from . import twins
  • autolens/weak/ — precedent for a self-contained subpackage
  • autolens/imaging/simulator.py:25 — SimulatorImaging.via_tracer_from
  • autolens/imaging/model/analysis.py:240-279 — writes image/dataset.fits
  • PyAutoGalaxy autogalaxy/aggregator/imaging/imaging.py:29-115, autogalaxy/aggregator/agg_util.py:82 — the reload recipe to replicate
  • test_autolens/analysis/test_analysis.py:157-177 — af.DirectoryPaths fixture fit directory pattern
  • docs/api/twins.rst — new

Trade-offs

  • Replicating the few lines of the aggregator reload rather than importing a private _imaging_from keeps al.twins independent of af.Fit; cite the source lines so drift is visible.
  • "observed" noise via default_rng rather than the simulator's global np.random.seed makes two twins simulated in one process independent of call order; the Poisson route keeps the simulator's behaviour because reproducing it exactly is the point.
  • Provenance stays a plain dict in JSON (report §2.5): no schema library, no registry.

Original Prompt

Click to expand starting prompt

LensTwin phase 0: autolens/twins/ core (reference model, baseline twin, seeded simulation, provenance) and the two PyAutoGalaxy primitives it needs

Type: feature
Target: autolens
Repos:

  • PyAutoGalaxy
  • PyAutoLens
    Themes:
  • mge
    Difficulty: large
    Autonomy: supervised
    Priority: high
    Status: formalised
    Consequence: judge
    Witness: a 7x7 fixture fit directory ingests as an al.twins.ReferenceModel; its baseline Twin simulates bit-identically for the same seed across two runs and differently for another seed; SimulatedTwin.from_directory of the written output re-simulates to the same image; ag projected mass inside a circular aperture by grid integration matches mass_angular_within_circle_from for Isothermal and NFWSph to 1e-3 and the Gaussian closed form 2πΥIσ²(1−e^{−R²/2σ²}) to 1e-4
    Review-minutes: 30
    Unattended: never
    Epic: lenstwin
    Phase: 0
    Parent: draft/feature/autolens/lenstwin_epic.md
    Filed: 2026-10-28

Phase 0 of the lenstwin epic (ledger lenstwin_epic.md; report lenstwin_epic_report.md §2 architecture, §3 "Phase 0" body; surveys lenstwin_epic_surveys/01 §2–§6). Rulings R1 (package and names: accepted as written here) and R2 (default twin noise: the observed noise map; Poisson only when exposure time and sky are set) were taken by the human on 2026-10-28, so this prompt is ready for /start_dev. Library first: 0A (PyAutoGalaxy) merges before 0B (PyAutoLens); 0B may develop against 0A's same-named branch. One issue per repo.

0A — PyAutoGalaxy primitives

  1. Projected mass inside a circular aperture for any mass object. A function (home: beside LensCalc in @PyAutoGalaxy/autogalaxy/operate/lens_calc.py, or a small autogalaxy/quantity-style module; the implementer chooses and says so) that takes any object exposing convergence_2d_from(grid) — a profile, a Basis (@PyAutoGalaxy/autogalaxy/profiles/basis.py), a Galaxy, a Galaxies — plus a radius, a centre and a grid, and returns Σ κ · pixel-area inside the circle, with a finer sub-grid near the centre so the cusp of an isothermal profile converges. It is the one aperture-mass definition every twin component shares, because MassProfile.mass_angular_within_circle_from (@PyAutoGalaxy/autogalaxy/profiles/mass/abstract/abstract.py:242) needs convergence_func, which Basis does not define (survey 01 §4). Tests: agreement with mass_angular_within_circle_from for Isothermal and NFWSph to 1e-3; the circular-Gaussian closed form to 1e-4; a Basis of two Gaussians equals the sum of its members.
  2. Light basis → mass basis at a given mass-to-light ratio, instance level. Basis.mass_basis_from(mass_to_light_ratio) (or a free function in basis.py) that maps every lp.Gaussian member to an lmp.Gaussian (@PyAutoGalaxy/autogalaxy/profiles/light_and_mass_profiles.py:17) with the same centre, ell_comps, intensity, sigma and the shared mass_to_light_ratio, raising for members with no lmp counterpart. It is the instance-side twin of mass_light_dark_basis_from (@PyAutoGalaxy/autogalaxy/analysis/chaining_util.py:467-547), which builds af.Models and needs a Result. Tests: the field copy matches what mass_light_dark_basis_from would produce for the same solved basis; convergence of the mass basis equals mass_to_light_ratio × image of the light basis on a grid.

Say explicitly in the PR that the public API grew (AGENTS.md rule).

0B — PyAutoLens autolens/twins/

Subpackage @PyAutoLens/autolens/twins/ with setup.py, reference.py, twin.py, record.py, simulate.py, transform/{__init__.py, identity.py} and an __init__.py exporting ObservationSetup, ReferenceModel, Twin, SimulatedTwin, TransformationRecord, transform; from . import twins added to @PyAutoLens/autolens/__init__.py next to potential_correction (line 145). Precedents for a self-contained subpackage: @PyAutoLens/autolens/weak/. Every object implements the autonerves.dictable contract so al.to_dict / al.from_dict / al.output_to_json / al.from_json work unchanged.

  • ObservationSetup: mask, PSF (al.Convolver), observed noise map, pixel scales, origin, over-sample sizes (lp and pixelization), cosmology, optional exposure_time and background_sky_level. from_dataset(imaging) and from_fit_directory(path) — the latter reuses image/dataset.fits HDU layout and agg_util.mask_header_from exactly as _imaging_from does (@PyAutoGalaxy/autogalaxy/aggregator/imaging/imaging.py:29-115; @PyAutoLens/autolens/imaging/model/analysis.py:240-279 writes it). with_(...) returns a modified copy. grid property = the masked lens-plane grid.
  • ReferenceModel (immutable): tracer (from files/tracer.json via al.from_json, i.e. with solved intensities — survey 01 §2), setup, provenance (lens_id, labels, roles mapping galaxy name → role, fit_path, SHA-256 of dataset.fits and tracer.json, ingested_at, library versions via importlib.metadata, Python version). from_fit_directory(path, lens_id, labels=(), roles=None), from_result(result, dataset, ...), output_to(dir) / from_directory(dir).
  • Twin: reference, tracer (ground truth), setup, records. Twin.baseline(reference); apply(transformation) returns a new Twin with the record appended; with_setup(setup); simulate(seed, noise="observed") → SimulatedTwin. The "observed" route draws Gaussian noise from setup.noise_map with numpy.random.default_rng(seed) on top of the PSF-convolved noise-free image from al.SimulatorImaging.via_tracer_from with noise off (@PyAutoLens/autolens/imaging/simulator.py:25); the "poisson" route passes exposure_time, background_sky_level, noise_seed=seed to al.SimulatorImaging and requires both to be set. Verify the SimulatorImaging constructor in PyAutoArray first (not surveyed).
  • TransformationRecord: name, requested, procedure (text + derived numbers), changed, side_effects, preserved (empty by default — preservation is never implicit). transform.Identity produces a record with empty changes so the chain and JSON are exercised in phase 0.
  • SimulatedTwin: dataset (al.Imaging, masked and over-sampled like the setup), truth (the tracer), seed, noise, simulator settings, twin. output_to(dir) writes data.fits, noise_map.fits, psf.fits, mask.fits, truth_tracer.json, twin.json (reference pointer and provenance, records, setup overrides, seed, noise route, versions); from_directory(dir) reloads and resimulate() reproduces the image bit-for-bit.
  • Docs: @PyAutoLens/docs/api/twins.rst listing the exports; a short module docstring stating the three invariants from the ledger.

Tests (test_autolens/twins/, NumPy only, config pushed by the existing conftest.py): a fixture fit directory built under data_temp with af.DirectoryPaths as in @PyAutoLens/test_autolens/analysis/test_analysis.py:157-177 ingests; the baseline twin's noise-free image equals the parent tracer's image_2d_from on the setup grid bit-for-bit; seed determinism and seed sensitivity; output_to / from_directory / resimulate round trip; to_dict / from_dict for every object; Identity record serialises; from_fit_directory reproduces the dataset ImagingAgg would rebuild (data, noise map, PSF kernel, mask equal).

Verified at issue time (2026-10-28, read from main of PyAutoArray, PyAutoFit, PyAutoGalaxy, PyAutoLens; the surveys did not cover these)

  • aa.SimulatorImaging.__init__(exposure_time, background_sky_level=0.0, subtract_background_sky=True, psf=None, use_real_space_convolution=True, normalize_psf=True, add_poisson_noise_to_data=True, include_poisson_noise_in_noise_map=True, noise_if_add_noise_false=0.1, noise_seed=-1, use_jax=False) — exposure_time is required with no default, so the "observed" route either constructs it with exposure_time=1.0, add_poisson_noise_to_data=False, include_poisson_noise_in_noise_map=False (noise map then a constant noise_if_add_noise_false to be replaced by setup.noise_map) or bypasses the simulator and PSF-convolves the tracer image itself; the implementer chooses and the twin stores which. al.SimulatorImaging.via_tracer_from(tracer, grid, xp=None) calls tracer.set_snr_of_snr_light_profiles first and pads the grid for the kernel; via_image_from(image, over_sample_size=None, image_is_convolved=False, xp=None) exists for a pre-convolved image.
  • Poisson route: noise_seed seeds via np.random.seed in preprocess.data_eps_with_poisson_noise_added (global NumPy state, -1 = random), so it is deterministic for a fixed seed but the "observed" route must use its own numpy.random.default_rng(seed) and never the global state.
  • aa.Imaging.__init__(data, noise_map=None, psf=None, psf_setup_state=False, noise_covariance_matrix=None, over_sample_size_lp=4, over_sample_size_pixelization=4, convolve_over_sample_size_lp=1, convolve_over_sample_size_pixelization=1, use_normalized_psf=True, check_noise_map=True, sparse_operator=None); Imaging.from_fits(pixel_scales, data_path, noise_map_path, data_hdu=0, noise_map_hdu=0, psf_path=None, psf_hdu=0, noise_covariance_matrix=None, check_noise_map=True, over_sample_size_lp=4, over_sample_size_pixelization=4, convolve_over_sample_size_lp=1, convolve_over_sample_size_pixelization=1, psf_pixel_scales=None); apply_mask(mask) may be called once only (a second call raises — rebuild from arrays to re-mask); apply_over_sampling(over_sample_size_lp=None, over_sample_size_pixelization=None). The PSF is an aa.Convolver (al.Convolver) everywhere, not a Kernel2D.
  • af.ModelInstance.as_model(model_classes=(), excluded_classes=()) exists (autofit/mapper/model.py:522) and delegates to AbstractPriorModel.from_instance; phase 0 does not need it (the reference tracer is an instance) but ReferenceModel.from_result may use result.instance directly.
  • Reload recipe confirmed: agg_util.mask_header_from(fit, name="dataset") and _imaging_from(fit) in PyAutoGalaxy's aggregator read image/dataset.fits HDUs 0–3 (mask, data, noise map, PSF); AnalysisImaging writes it at paths.image_path / "dataset.fits". al.{to_dict, from_dict, from_json, output_to_json} are re-exported from autonerves.dictable; autolens/__init__.py line 145 is from . import potential_correction as pc.

Out of scope here: any mass transformation, MassBudget, Einstein-radius apertures, diagnostics (phases 2–3), the science project (phase 1), workspace or assistant changes (phase 6).

Activity

  1. Jammy2211 commented on Oct 28, 2026

    @Jammy2211
    CollaboratorAuthor

    Library PR created: #804 (branch feature/lenstwin-p0-twins-core, labelled pending-release). Merges after PyAutoGalaxy 0A (PyAutoLabs/PyAutoGalaxy#672), library-first.

    API change summary: one new subpackage al.twins (ObservationSetup, ReferenceModel, Twin, SimulatedTwin, TransformationRecord, transform.Identity); nothing existing changed. Rulings R1 and R2 honoured; the "observed" route convolves directly with tracer.blurred_image_2d_from rather than through SimulatorImaging, which draws from the global random state even with Poisson noise off. Full suite: 946 passed, 1 skipped, 1 xfailed, 7 pre-existing failures in test_autolens/point/test_dataset.py (pytest 9.2 nested approx, identical with the change stashed). Heart read STALE (environment-side reasons only), so the suite is the development gate.

    Workspace impact: added-only API, nothing in the workspaces references al.twins; examples arrive with the epic's phase 6. Consequence tier is judge: a human runs /prm once CI is green.


    Generated by Claude Code

  2. Jammy2211 commented on Oct 28, 2026

    @Jammy2211
    CollaboratorAuthor

    Shipped

    #804 merged 2026-10-28 (merge commit 9a85d32; head 1d430dc green on all legs: unittest 3.12, 3.13, nojax, docs-build). Adds al.twins (ObservationSetup, ReferenceModel, Twin, SimulatedTwin, TransformationRecord, transform.Identity). Labelled pending-release. The PR also carries the pytest-9 fix to test_autolens/point/test_dataset.py.

    Phase 0 of the lenstwin epic is complete with PyAutoGalaxy 0A (PyAutoLabs/PyAutoGalaxy#672). Next: phase 1 (Science/twins), after a release carries phase 0.


    Generated by Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions