Repository navigation
Description
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) exportingObservationSetup,ReferenceModel,Twin,SimulatedTwin,TransformationRecord,transform; addfrom . import twinstoautolens/__init__.py. ObservationSetupfrom a dataset or a fit directory (reusing the aggregator'sdataset.fitsreload recipe), withwith_(...)copies and a masked lens-planegrid.- 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 withnumpy.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 / resimulatewithtwin.jsonprovenance; every object round-trips throughal.to_dict/al.from_dict.transform.Identityand its empty-change record so the chain and JSON are exercised now; tests on the 7x7 fixtures and adata_tempfit 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
- PyAutoLens (primary; this issue)
- PyAutoGalaxy (issue 0A, feat: aperture mass via grid and Basis.mass_basis_from (lenstwin 0A) PyAutoGalaxy#671, prerequisite:
mass_angular_within_circle_via_grid_fromandBasis.mass_basis_from— not called by phase 0 code paths but 0B's branch should be tested against 0A's branch so phase 3 has nothing to re-plumb)
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_timehas no default.al.SimulatorImaging.via_tracer_from(tracer, grid, xp=None)callstracer.set_snr_of_snr_light_profilesand 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 ownnumpy.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 anaa.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) readimage/dataset.fitsHDUs 0–3 (mask, data, noise map, PSF);AnalysisImagingwrites it atpaths.image_path / "dataset.fits"(autolens/imaging/model/analysis.py:276).al.{to_dict, from_dict, from_json, output_to_json}come fromautonerves.dictable;autolens/__init__.py:145isfrom . import potential_correction as pc.
Implementation Steps
- Package skeleton.
autolens/twins/__init__.pywith a module docstring stating the three invariants and exporting the five objects plustransform;from . import twinsafter line 145 ofautolens/__init__.py. Precedent for a self-contained subpackage:autolens/weak/. setup.py—ObservationSetup(dictable): fieldsmask(aa.Mask2D),psf(al.Convolver),noise_map(aa.Array2D, observed),pixel_scales,origin,over_sample_size_lp,over_sample_size_pixelization,cosmology, optionalexposure_time,background_sky_level.from_dataset(imaging, cosmology=None);from_fit_directory(path)readingimage/dataset.fitswith the same HDU layout andmask_header_fromlogic 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-planeaa.Grid2Dwith the setup's over-sampling.dataset_from(data)helper →al.Imagingmasked and over-sampled like the setup (used bySimulatedTwin).reference.py—ReferenceModel(frozen;dictable):tracer,setup,provenance(dict:lens_id,labels,roles,fit_path,dataset_sha256,tracer_sha256,ingested_atISO-8601 UTC,versionsviaimportlib.metadata.versionfor autofit/autoarray/autogalaxy/autolens/numpy,python).from_fit_directory(path, lens_id, labels=(), roles=None)loadsfiles/tracer.jsonviaal.from_json(solved intensities) andObservationSetup.from_fit_directory;from_result(result, dataset, lens_id, ...)usesresult.max_log_likelihood_tracerandObservationSetup.from_dataset;output_to(dir)writestracer.json,setup/(fits: mask, noise_map, psf),provenance.json,labels.yaml;from_directory(dir)inverts it. Attribute assignment raises (__setattr__guard ordataclass(frozen=True)).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__.pydefines theTransformationprotocol:apply(twin) -> (tracer, setup, record);transform/identity.pyreturns the twin's tracer and setup unchanged and a recordname="Identity"with emptychanged/side_effects/preserved.twin.py—Twin(value;dictable):reference,tracer,setup,records(tuple).Twin.baseline(reference);apply(transformation)→ newTwinwith the record appended (never mutates);with_setup(setup);simulate(seed, noise="observed")→SimulatedTwin."observed": noise-free image = PSF-convolvedtracer.image_2d_from(setup.grid)(eitheral.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 withsetup.psf— the implementer chooses andSimulatedTwin.simulatorrecords which), thendata = image + rng.normal(0, setup.noise_map)withrng = 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(...); raiseValueErrornaming the missing field when either isNone. Any othernoisevalue raises.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)writesdata.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 resolvesfit_pathwhen it exists, else the embedded provenance);resimulate()→self.twin.simulate(seed=self.seed, noise=self.noise)and the test asserts bit-identity with the storeddata.fits.- Tests
test_autolens/twins/(NumPy only; config pushed by the existingconftest.py): build a fixture fit directory underdata_tempwithaf.DirectoryPathsexactly astest_autolens/analysis/test_analysis.py:157-177does (runAnalysisImagingfar enough to writeimage/dataset.fitsandfiles/tracer.json, or write them with the analysis's own output helpers). Cases: ingest →ReferenceModel; baseline twin noise-free image equalstracer.image_2d_from(setup.grid)bit-for-bit (before PSF) and the PSF-convolved image equals the simulator's;simulate(seed=1)twice isnp.array_equal;seed=2differs;output_to→from_directory→resimulateisnp.array_equalwith the stored data;to_dict/from_dictround trip for every object;Identityrecord serialises andtwin.apply(Identity())has one record and the same tracer;from_fit_directorysetup equals whatImagingAggrebuilds (data, noise map, PSF kernel, mask);"poisson"without exposure time raises; the reference is immutable. - 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. - 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— addfrom . import twinsautolens/weak/— precedent for a self-contained subpackageautolens/imaging/simulator.py:25—SimulatorImaging.via_tracer_fromautolens/imaging/model/analysis.py:240-279— writesimage/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.DirectoryPathsfixture fit directory patterndocs/api/twins.rst— new
Trade-offs
- Replicating the few lines of the aggregator reload rather than importing a private
_imaging_fromkeepsal.twinsindependent ofaf.Fit; cite the source lines so drift is visible. "observed"noise viadefault_rngrather than the simulator's globalnp.random.seedmakes 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 anal.twins.ReferenceModel; its baselineTwinsimulates bit-identically for the same seed across two runs and differently for another seed;SimulatedTwin.from_directoryof the written output re-simulates to the same image;agprojected mass inside a circular aperture by grid integration matchesmass_angular_within_circle_fromforIsothermalandNFWSphto 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
- Projected mass inside a circular aperture for any mass object. A function (home: beside
LensCalcin@PyAutoGalaxy/autogalaxy/operate/lens_calc.py, or a smallautogalaxy/quantity-style module; the implementer chooses and says so) that takes any object exposingconvergence_2d_from(grid)— a profile, aBasis(@PyAutoGalaxy/autogalaxy/profiles/basis.py), aGalaxy, aGalaxies— 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, becauseMassProfile.mass_angular_within_circle_from(@PyAutoGalaxy/autogalaxy/profiles/mass/abstract/abstract.py:242) needsconvergence_func, whichBasisdoes not define (survey 01 §4). Tests: agreement withmass_angular_within_circle_fromforIsothermalandNFWSphto 1e-3; the circular-Gaussian closed form to 1e-4; aBasisof two Gaussians equals the sum of its members. - 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 inbasis.py) that maps everylp.Gaussianmember to anlmp.Gaussian(@PyAutoGalaxy/autogalaxy/profiles/light_and_mass_profiles.py:17) with the samecentre,ell_comps,intensity,sigmaand the sharedmass_to_light_ratio, raising for members with nolmpcounterpart. It is the instance-side twin ofmass_light_dark_basis_from(@PyAutoGalaxy/autogalaxy/analysis/chaining_util.py:467-547), which buildsaf.Models and needs aResult. Tests: the field copy matches whatmass_light_dark_basis_fromwould produce for the same solved basis; convergence of the mass basis equalsmass_to_light_ratio × imageof 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, optionalexposure_timeandbackground_sky_level.from_dataset(imaging)andfrom_fit_directory(path)— the latter reusesimage/dataset.fitsHDU layout andagg_util.mask_header_fromexactly as_imaging_fromdoes (@PyAutoGalaxy/autogalaxy/aggregator/imaging/imaging.py:29-115;@PyAutoLens/autolens/imaging/model/analysis.py:240-279writes it).with_(...)returns a modified copy.gridproperty = the masked lens-plane grid.ReferenceModel(immutable):tracer(fromfiles/tracer.jsonviaal.from_json, i.e. with solved intensities — survey 01 §2),setup,provenance(lens_id,labels,rolesmapping galaxy name → role,fit_path, SHA-256 ofdataset.fitsandtracer.json,ingested_at, library versions viaimportlib.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 newTwinwith the record appended;with_setup(setup);simulate(seed, noise="observed")→SimulatedTwin. The"observed"route draws Gaussian noise fromsetup.noise_mapwithnumpy.random.default_rng(seed)on top of the PSF-convolved noise-free image fromal.SimulatorImaging.via_tracer_fromwith noise off (@PyAutoLens/autolens/imaging/simulator.py:25); the"poisson"route passesexposure_time,background_sky_level,noise_seed=seedtoal.SimulatorImagingand requires both to be set. Verify theSimulatorImagingconstructor in PyAutoArray first (not surveyed).TransformationRecord:name,requested,procedure(text + derived numbers),changed,side_effects,preserved(empty by default — preservation is never implicit).transform.Identityproduces 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)writesdata.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 andresimulate()reproduces the image bit-for-bit.- Docs:
@PyAutoLens/docs/api/twins.rstlisting 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_timeis required with no default, so the"observed"route either constructs it withexposure_time=1.0,add_poisson_noise_to_data=False,include_poisson_noise_in_noise_map=False(noise map then a constantnoise_if_add_noise_falseto be replaced bysetup.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)callstracer.set_snr_of_snr_light_profilesfirst 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_seedseeds vianp.random.seedinpreprocess.data_eps_with_poisson_noise_added(global NumPy state,-1= random), so it is deterministic for a fixedseedbut the"observed"route must use its ownnumpy.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 anaa.Convolver(al.Convolver) everywhere, not aKernel2D.af.ModelInstance.as_model(model_classes=(), excluded_classes=())exists (autofit/mapper/model.py:522) and delegates toAbstractPriorModel.from_instance; phase 0 does not need it (the reference tracer is an instance) butReferenceModel.from_resultmay useresult.instancedirectly.- Reload recipe confirmed:
agg_util.mask_header_from(fit, name="dataset")and_imaging_from(fit)in PyAutoGalaxy's aggregator readimage/dataset.fitsHDUs 0–3 (mask, data, noise map, PSF);AnalysisImagingwrites it atpaths.image_path / "dataset.fits".al.{to_dict, from_dict, from_json, output_to_json}are re-exported fromautonerves.dictable;autolens/__init__.pyline 145 isfrom . 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
Jammy2211 commentedon Oct 28, 2026
Library PR created: #804 (branch
feature/lenstwin-p0-twins-core, labelledpending-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 withtracer.blurred_image_2d_fromrather than throughSimulatorImaging, which draws from the global random state even with Poisson noise off. Full suite: 946 passed, 1 skipped, 1 xfailed, 7 pre-existing failures intest_autolens/point/test_dataset.py(pytest 9.2 nestedapprox, 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 isjudge: a human runs/prmonce CI is green.Generated by Claude Code
Jammy2211 commentedon Oct 28, 2026
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). Labelledpending-release. The PR also carries the pytest-9 fix totest_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