Skip to content

feat: add al.twins core — ReferenceModel, Twin, SimulatedTwin (lenstwin 0B) - #804

Merged
Jammy2211 merged 2 commits into
mainfrom
feature/lenstwin-p0-twins-core
Oct 28, 2026
Merged

Jammy2211 merged 2 commits into
mainfrom
feature/lenstwin-p0-twins-core

Conversation

@Jammy2211

Copy link
Copy Markdown
Collaborator

Summary

Phase 0B of the LensTwin epic (closes #803). Adds the autolens/twins/ subpackage, exported as al.twins, so a fitted lens becomes a reproducible, provenance-carrying simulation:

  • ObservationSetup — mask, PSF, observed noise map, pixel scales, over-sampling, cosmology, optional exposure time and sky; built from a dataset or from a fit directory's image/dataset.fits (the aggregator's HDU layout and mask-header logic, replicated and cited); with_(...) copies; grid; dataset_from(...).
  • ReferenceModel — immutable: the tracer with solved intensities (from files/tracer.json), the setup, and provenance (lens id, labels, roles, fit path, SHA-256 of dataset.fits and tracer.json, ingestion time, library and Python versions); from_fit_directory, from_result, output_to / from_directory.
  • Twin — a value: baseline, apply(transformation) appends a TransformationRecord, with_setup, simulate(seed, noise="observed"|"poisson").
  • SimulatedTwin — the al.Imaging dataset, truth tracer, seed, noise route and simulator settings; output_to writes data/noise_map/psf/mask.fits, truth_tracer.json, setup.json and twin.json; from_directory reloads and resimulate() reproduces the data bit for bit.
  • TransformationRecord and transform.Identity (plus the Transformation protocol) so the record chain and JSON are exercised now; real transformations arrive in phase 3.

Rulings honoured: R1 (names and placement as above) and R2 (the default twin draws Gaussian noise from the observed noise map with numpy.random.default_rng(seed); noise="poisson" is available only when exposure_time and background_sky_level are set).

"observed" route chosen: direct convolution, not SimulatorImaging. The noise-free image is tracer.blurred_image_2d_from on the setup dataset's light-profile and blurring grids (the same forward model FitImaging uses); the noise draw touches only unmasked pixels and never the global NumPy random state. SimulatorImaging.via_image_from always draws a Poisson sample from the global state even with Poisson noise off and raises on negative pixel values, so it is unsuitable for a seeded Gaussian route. A test shows the result is bit-identical to the simulator's noise-free output on the 7x7 fixtures. The Poisson route uses al.SimulatorImaging(..., noise_seed=seed) on a deep copy of the tracer so set_snr_of_snr_light_profiles cannot alter the truth. SimulatedTwin.simulator["route"] records which was used.

Serialisation notes: PyAutoFit's dictable parser bypasses a class's own from_dict and drops None entries, so SimulatedTwin.dict() encodes its dataset as a call to autolens.twins.simulate.dataset_via_setup_from, and ReferenceModel / SimulatedTwin restore their standard keys after loading; FITS-loaded arrays are stored header-free so they round-trip. Documented on the classes.

Depends on nothing in PyAutoGalaxy 0A (PyAutoLabs/PyAutoGalaxy#672) at run time; it merges after it per the epic's library-first order.

API Changes

The public API grew: a new subpackage al.twins exporting ObservationSetup, ReferenceModel, Twin, SimulatedTwin, TransformationRecord and transform (transform.Identity, transform.Transformation), plus from . import twins in autolens/__init__.py. Nothing existing was removed, renamed or changed in signature or behaviour.
See full details below.

Test Plan

  • test_autolens/twins/test_twins.py (19 tests): a fixture fit directory under tmp_path (written by AnalysisImaging.save_attributes and save_results with the 7x7 fixtures) ingests; the baseline twin's noise-free image equals both tracer.blurred_image_2d_from and the simulator's noise-free output; simulate(seed=1) twice is array_equal, seed=2 differs; output_to → from_directory → resimulate() reproduces data.fits; to_dict/from_dict for every object; Identity record serialises and apply appends one record; from_fit_directory equals what the aggregator rebuilds; Poisson without exposure time raises; unknown noise raises; negative seed raises; the reference is immutable; provenance carries versions and both hashes; the observed route leaves the global random state untouched; reference fallback when the fit directory is gone.
  • Full suite python -m pytest test_autolens/ -n auto: 946 passed, 1 skipped, 1 xfailed, 7 failed — all 7 in test_autolens/point/test_dataset.py (pytest.approx() does not support nested data structures, pytest 9.2.0 in this environment) and identical with this change stashed, so pre-existing and unrelated.
  • CI matrix (3.12, 3.13) green.
Full API Changes (for automation & release notes)

Added

  • al.twins.ObservationSetup(mask, psf, noise_map, pixel_scales=, origin=, over_sample_size_lp=, over_sample_size_pixelization=, cosmology=, exposure_time=None, background_sky_level=None) with from_dataset(imaging, cosmology=None), from_fit_directory(path), dataset_from_fit_directory(path), with_(**overrides), grid, fields, dataset_from(data, noise_map=None).
  • al.twins.ReferenceModel(tracer, setup, provenance) (immutable) with from_fit_directory(path, lens_id, labels=(), roles=None), from_result(result, dataset, lens_id, labels=(), roles=None), output_to(dir), from_directory(dir), lens_id, provenance.
  • al.twins.Twin(reference, tracer=None, setup=None, records=()) with baseline(reference), apply(transformation), with_setup(setup), setup_overrides(), noise_free_image_2d(), simulate(seed, noise="observed").
  • al.twins.SimulatedTwin(dataset, truth, seed, noise, simulator, twin) with output_to(dir), from_directory(dir), resimulate(), twin_json().
  • al.twins.TransformationRecord(name, requested=, procedure=, changed=, side_effects=, preserved=).
  • al.twins.transform.Transformation (protocol: apply(twin) -> (tracer, setup, record)) and al.twins.transform.Identity.
  • docs/api/twins.rst.

Removed

  • None.

Migration

  • None required.

Generated by the PyAutoLabs agent workflow.


Generated by Claude Code

…in 0B)

Public API grew: new subpackage `al.twins` (autolens/twins/) exporting
ObservationSetup, ReferenceModel, Twin, SimulatedTwin, TransformationRecord
and `transform` (Transformation protocol + Identity), wired in via
`from . import twins` in autolens/__init__.py. Issue #803.

Rulings honoured as taken: R1 (package placement and names as specified) and
R2 (default noise is the observed noise map, Gaussian via
numpy.random.default_rng(seed) on unmasked pixels; Poisson only for
noise="poisson" with exposure_time and background_sky_level set, otherwise
ValueError naming the missing field).

"observed" route: the noise-free image is tracer.blurred_image_2d_from on the
lp/blurring grids of setup.dataset_from(...) (the FitImaging forward model)
rather than SimulatorImaging.via_tracer_from with noise off, because the
simulator always draws a Poisson sample from NumPy's global RNG (reseeding it
when noise_seed=-1) and raises for negative pixel values. The image is
bit-identical to the simulator's noise-free output on the 7x7 fixtures
(tested). SimulatedTwin.simulator records the route.

Serialisation: Mask2D/Array2D/Convolver/cosmology round-trip natively, but
arrays loaded from FITS carry an aa.Header that does not, so ObservationSetup
stores header-free copies. SimulatedTwin.dict writes its dataset as a call of
dataset_via_setup_from (setup + data + noise map). Standard provenance and
simulator keys are restored after al.from_dict drops None-valued dict entries.

Docs: docs/api/twins.rst. Tests: test_autolens/twins (19, NumPy only).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016nhQ8MoEbXHfUW3wiH58VY
@Jammy2211 Jammy2211 added the pending-release PR queued for the next release build label Oct 28, 2026 — with Claude

Copy link
Copy Markdown
Collaborator Author

CI red, standing down on this leg. unittest / unittest-nojax on head f6800bb fails with exactly 7 tests, all in test_autolens/point/test_dataset.py (TypeError: pytest.approx() does not support nested data structures), and 913 passed. None of those files is touched by this PR; the same 7 fail locally on the untouched branch under pytest 9.2, and pytest is unpinned in pyproject.toml, so any fresh run of main on a runner that now resolves pytest 9 will fail the same way (the last main run on 2026-10-26 predates it). No fix exists yet to port; the fix is a small test-only change (compare the nested position/flux/time-delay lists with numpy.testing.assert_allclose or flatten before approx), queued as its own task rather than widened into this PR. Not re-running: it is deterministic, not a flake.

Not merged. PyAutoGalaxy 0A (PyAutoLabs/PyAutoGalaxy#672) is merged, so the library-first order is satisfied once this is green.


Generated by Claude Code

pytest 9.2 rejects nested structures in pytest.approx, so comparing a
list of (y, x) tuples raised TypeError in _assert_grid_close. Compare
numpy arrays instead, keeping elementwise tolerance and shape checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016nhQ8MLYjQFqJS7AECP9ky
(cherry picked from commit 2b063ca)

Copy link
Copy Markdown
Collaborator Author

Ported the fix: commit 2b063ca from branch ccr-b1080ef2-0tcwow ("test: fix point dataset tests for pytest 9 nested approx", a two-line change to test_autolens/point/test_dataset.py) is cherry-picked onto this branch as 1d430dc with its original authorship. It becomes a no-op once main carries the same change. Locally under pytest 9.2 the point-dataset and twins tests now pass (29 tests). CI is re-running on the new head.


Generated by Claude Code

@Jammy2211
Jammy2211 merged commit 9a85d32 into main Oct 28, 2026
4 checks passed
@Jammy2211
Jammy2211 deleted the feature/lenstwin-p0-twins-core branch October 28, 2026 13:34
@pyautolabs-bot pyautolabs-bot Bot removed the pending-release PR queued for the next release build label Oct 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

2 participants