Repository navigation
feat: add al.twins core — ReferenceModel, Twin, SimulatedTwin (lenstwin 0B) - #804
Conversation
…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
|
CI red, standing down on this leg. 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)
|
Ported the fix: commit 2b063ca from branch Generated by Claude Code |
Summary
Phase 0B of the LensTwin epic (closes #803). Adds the
autolens/twins/subpackage, exported asal.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'simage/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 (fromfiles/tracer.json), the setup, and provenance (lens id, labels, roles, fit path, SHA-256 ofdataset.fitsandtracer.json, ingestion time, library and Python versions);from_fit_directory,from_result,output_to/from_directory.Twin— a value:baseline,apply(transformation)appends aTransformationRecord,with_setup,simulate(seed, noise="observed"|"poisson").SimulatedTwin— theal.Imagingdataset, truth tracer, seed, noise route and simulator settings;output_towritesdata/noise_map/psf/mask.fits,truth_tracer.json,setup.jsonandtwin.json;from_directoryreloads andresimulate()reproduces the data bit for bit.TransformationRecordandtransform.Identity(plus theTransformationprotocol) 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 whenexposure_timeandbackground_sky_levelare set)."observed" route chosen: direct convolution, not
SimulatorImaging. The noise-free image istracer.blurred_image_2d_fromon the setup dataset's light-profile and blurring grids (the same forward modelFitImaginguses); the noise draw touches only unmasked pixels and never the global NumPy random state.SimulatorImaging.via_image_fromalways 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 usesal.SimulatorImaging(..., noise_seed=seed)on a deep copy of the tracer soset_snr_of_snr_light_profilescannot alter the truth.SimulatedTwin.simulator["route"]records which was used.Serialisation notes: PyAutoFit's dictable parser bypasses a class's own
from_dictand dropsNoneentries, soSimulatedTwin.dict()encodes its dataset as a call toautolens.twins.simulate.dataset_via_setup_from, andReferenceModel/SimulatedTwinrestore 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.twinsexportingObservationSetup,ReferenceModel,Twin,SimulatedTwin,TransformationRecordandtransform(transform.Identity,transform.Transformation), plusfrom . import twinsinautolens/__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 undertmp_path(written byAnalysisImaging.save_attributesandsave_resultswith the 7x7 fixtures) ingests; the baseline twin's noise-free image equals bothtracer.blurred_image_2d_fromand the simulator's noise-free output;simulate(seed=1)twice isarray_equal,seed=2differs;output_to→from_directory→resimulate()reproducesdata.fits;to_dict/from_dictfor every object;Identityrecord serialises andapplyappends one record;from_fit_directoryequals 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.python -m pytest test_autolens/ -n auto: 946 passed, 1 skipped, 1 xfailed, 7 failed — all 7 intest_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.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)withfrom_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) withfrom_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=())withbaseline(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)withoutput_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)) andal.twins.transform.Identity.docs/api/twins.rst.Removed
Migration
Generated by the PyAutoLabs agent workflow.
Generated by Claude Code