diff --git a/autogalaxy/analysis/model_util.py b/autogalaxy/analysis/model_util.py index a5f02750f..ce0de4634 100644 --- a/autogalaxy/analysis/model_util.py +++ b/autogalaxy/analysis/model_util.py @@ -18,6 +18,8 @@ def mge_model_from( ell_comps_sigma : float = 0.3, use_spherical: bool = False, sigma_min: float = 1e-4, + ell_comps_limit: float = 1.0, + order_bases: bool = False, ) -> af.Collection: """ Construct a Multi-Gaussian Expansion (MGE) for the lens or source galaxy light. @@ -87,6 +89,76 @@ def mge_model_from( of the log-spaced sigma values. Defaults to ``1e-4``. Increase it (e.g. to a tenth of the pixel scale) to stop the basis wasting components on scales the data cannot resolve. + ell_comps_limit + Half-width of the box the truncated-Gaussian ell_comps priors are truncated to, + giving ``lower_limit=-ell_comps_limit`` and ``upper_limit=+ell_comps_limit``. + Must satisfy ``0.0 < ell_comps_limit <= 1.0``; the default ``1.0`` is the full + physical range. Uniform ell_comps priors are unaffected -- their width is set by + ``ell_comps_uniform_width``. + + Callers tighten this box when the science case bounds the isophotal ellipticity: + the Euclid strong-lens pipeline uses ``0.5`` for the lens light and ``0.7`` for + the source. Setting the box *here* rather than overwriting the priors on the + returned model keeps the prior objects the ones this function built, which + matters because ``order_bases`` attaches an assertion that references them. + order_bases + If True, require the bases' shared ``ell_comps_1`` values to be strictly + decreasing, ``basis_0 > basis_1 > ... > basis_{K-1}``, via ``K - 1`` assertions + added to the returned model. Defaults to False (off until validated on + production runs). A no-op when ``gaussian_per_basis == 1``; a ``ValueError`` + when ``use_spherical=True``, which has no ``ell_comps`` to order. + + **The symmetry.** With ``gaussian_per_basis=K > 1`` every basis holds the same + ``total_gaussians`` linear Gaussians on the same fixed ``log10_sigma_list``, and + differs from its siblings only in the ellipticity pair it carries. The bases are + therefore *exchangeable*: permuting which basis holds which ``ell_comps`` leaves + the likelihood exactly unchanged, so the posterior has ``K!`` identical modes and + an unseeded search lands in whichever one it reaches first. Repeat fits of the + same data then report the same physical solution under swapped labels, which + breaks any downstream comparison that reads ``basis_0`` as a fixed component. + Ordering the bases picks one labelling and deletes the other ``K! - 1`` copies; + it removes no physical solution. + + **Why ``ell_comps_1`` and not the magnitude.** The key must separate the modes + the search actually finds. At the maximum-likelihood point either key admits + exactly one permutation, so the choice is not about which key can order a single + point -- it is about the posterior spread. The two modes are separated in the key + by ``|key(e_A) - key(e_B)|``, and when that separation is smaller than the marginal + posterior width in the key the constraint surface passes through both modes: the + retained region mixes the two labellings and the labels are still undetermined. On + the Euclid phase-4 tiles the two bases commonly sit against opposite edges of the + ell_comps box, e.g. ``(0.007, -0.500)`` and ``(-0.023, 0.497)``. For that pair the + magnitude separation is ``0.0025`` while the ``ell_comps_1`` separation is ``1.0``, + so the ``cos 2phi`` component separates the modes by far more than any plausible + marginal width and the magnitude does not. + + **Blind band.** No continuous key is exact for every configuration -- another tile + has the two bases only ``0.01`` apart in ``ell_comps_1``, a separation small + compared with a typical marginal posterior width, so there too the constraint + surface passes through both modes and ordering by ``ell_comps_1`` does not resolve + that tile. The diagnostic is a small ``|delta ell_comps_1|`` relative to the + posterior width: read such a result as undetermined labelling rather than as an + ordered answer. + + **Consequences of an assertion being part of the model.** It enters the PyAutoFit + identifier, so turning ``order_bases`` on gives an otherwise identical fit a new + ``unique_id`` and a fresh output directory -- with PyAutoFit at or after the + identifier fix that ships alongside this option (PyAutoFit#1581 follow-up); on + older PyAutoFit the ordered and unordered models share an identifier and an + ordered fit would load a completed unordered result from the same directory. It + also makes the model an invalid *target* for ``take_attributes``: PyAutoFit's + ``assert_no_assertions`` refuses to copy attributes into a model that already + carries assertions, so build the ordered model after any such prior-passing step. + Prior passing in the other direction drops the ordering altogether: ``Result.model`` + is built by ``gaussian_prior_model_for_arguments``, which clears ``_assertions`` + (``PyAutoFit/autofit/mapper/prior_model/prior_model.py``, line 601), so a model + built from a result is unordered again -- recompose the ``Basis`` with + ``order_bases=True`` when chaining fits rather than reusing the result's model. + Enforcement is backend-specific but has the same outcome -- NumPy raises + ``af.exc.FitException`` from ``check_assertions`` and the search resamples; JAX + cannot raise inside a trace and instead evaluates the assertions as a traced + boolean and maps a violating model to the resample figure of merit (PyAutoFit + #1583). Returns ------- @@ -98,11 +170,25 @@ def mge_model_from( if os.environ.get("PYAUTO_SMALL_DATASETS") == "1": total_gaussians = 2 + # A single basis leaves nothing to order, so `order_bases` degrades to a no-op + # under the small-dataset shortcut rather than changing what it asserts. gaussian_per_basis = 1 from autogalaxy.profiles.light.linear import Gaussian, GaussianSph from autogalaxy.profiles.basis import Basis + if not 0.0 < ell_comps_limit <= 1.0: + raise ValueError( + f"mge_model_from requires 0.0 < ell_comps_limit <= 1.0, got " + f"{ell_comps_limit}." + ) + + if order_bases and use_spherical: + raise ValueError( + "mge_model_from cannot order bases when use_spherical=True, because " + "spherical Gaussians have no ell_comps to order." + ) + if sigma_min <= 0.0: raise ValueError( f"mge_model_from requires sigma_min > 0.0, got {sigma_min}." @@ -151,8 +237,8 @@ def _make_ell_comps_priors(): ) else: return ( - af.TruncatedGaussianPrior(mean=0.0, sigma=ell_comps_sigma, lower_limit=-1.0, upper_limit=1.0), - af.TruncatedGaussianPrior(mean=0.0, sigma=ell_comps_sigma, lower_limit=-1.0, upper_limit=1.0), + af.TruncatedGaussianPrior(mean=0.0, sigma=ell_comps_sigma, lower_limit=-ell_comps_limit, upper_limit=ell_comps_limit), + af.TruncatedGaussianPrior(mean=0.0, sigma=ell_comps_sigma, lower_limit=-ell_comps_limit, upper_limit=ell_comps_limit), ) # Shared centre priors (used when centre_per_basis=False). @@ -161,6 +247,10 @@ def _make_ell_comps_priors(): bulge_gaussian_list = [] + # The shared `ell_comps_1` prior of each basis, in basis order, used as the ordering + # key when `order_bases` is True. + ell_comps_1_list = [] + for j in range(gaussian_per_basis): # Per-basis centre priors when requested. @@ -172,6 +262,7 @@ def _make_ell_comps_priors(): # Per-basis ell_comps priors (always independent across bases). if not use_spherical: ell_comps_0, ell_comps_1 = _make_ell_comps_priors() + ell_comps_1_list.append(ell_comps_1) gaussian_list = af.Collection( af.Model(model_cls) for _ in range(total_gaussians) @@ -189,11 +280,25 @@ def _make_ell_comps_priors(): # The Basis object groups many light profiles together into a single model component. - return af.Model( + model = af.Model( Basis, profile_list=bulge_gaussian_list, ) + # Break the label symmetry between exchangeable bases by requiring their shared + # `ell_comps_1` values to be strictly decreasing. Attaching the assertions to the + # returned `Basis` model (rather than to a parent) means they travel with the + # component, and PyAutoFit's `gathered_assertions` finds them wherever the component + # is placed in a larger model. + if order_bases: + for j in range(len(ell_comps_1_list) - 1): + model.add_assertion( + ell_comps_1_list[j] > ell_comps_1_list[j + 1], + name=f"mge_basis_{j}_ell_comps_1_gt_basis_{j + 1}", + ) + + return model + def mge_point_model_from( pixel_scales: float, diff --git a/test_autogalaxy/analysis/test_model_util.py b/test_autogalaxy/analysis/test_model_util.py index 7a830adaa..c826a7983 100644 --- a/test_autogalaxy/analysis/test_model_util.py +++ b/test_autogalaxy/analysis/test_model_util.py @@ -1,3 +1,5 @@ +import pickle + import pytest import numpy as np @@ -5,6 +7,23 @@ import autogalaxy as ag +def _ell_comps_1_vector_index(model, profile_index): + """ + The index, in a physical parameter vector, of the `ell_comps_1` prior shared by the + basis that `profile_list[profile_index]` belongs to. + + A vector is ordered by prior id (`prior_tuples_ordered_by_id`), which is what + `instance_from_vector` and `assertions_satisfied_from_vector` both map, so the index + is found by matching the prior OBJECT rather than by reading `model.paths`. The paths + are not vector-aligned: `paths` has one entry per Gaussian (24 for two bases of three + Gaussians) while the model has only 6 priors, and `unique_prior_paths` names whichever + single Gaussian each shared prior resolves through -- the LAST of each basis, not the + first -- so a path-derived index would silently drift with `total_gaussians`. + """ + ordered = [prior_tuple.prior for prior_tuple in model.prior_tuples_ordered_by_id] + return ordered.index(model.profile_list[profile_index].ell_comps.ell_comps_1) + + def test__mge_model_from__single_basis_elliptical(): model = ag.model_util.mge_model_from( mask_radius=1.0, total_gaussians=5, gaussian_per_basis=1 @@ -26,6 +45,10 @@ def test__mge_model_from__two_bases_shared_centre(): # 2 shared centre + 2 ell_comps per basis * 2 = 6 assert model.prior_count == 6 + # `order_bases` defaults to False, so the bases stay exchangeable and the model + # carries no assertions. + assert model.gathered_assertions() == [] + def test__mge_model_from__two_bases_centre_per_basis(): model = ag.model_util.mge_model_from( @@ -109,6 +132,66 @@ def test__mge_model_from__backward_compat_single_basis(): assert len(instance.profile_list) == 10 +def test__mge_model_from__positional_signature_is_unchanged(): + """ + The thirteen parameters that existed before `ell_comps_limit` and `order_bases` + were added must still be callable positionally, in their original order, with the + same result as the keyword call. `ell_comps_limit` and `order_bases` therefore sit + at the END of the signature: inserting either one earlier would silently rebind an + existing positional caller (an old positional `use_spherical=False` would arrive as + `ell_comps_limit=False` and raise, and a positional `True` would build elliptical + Gaussians instead of spherical ones). + """ + args = ( + 2.0, # mask_radius + 5, # total_gaussians + 2, # gaussian_per_basis + False, # centre_prior_is_uniform + (0.1, -0.2), # centre + None, # centre_fixed + True, # centre_per_basis + 0.4, # centre_sigma + False, # ell_comps_prior_is_uniform + 0.25, # ell_comps_uniform_width + 0.35, # ell_comps_sigma + False, # use_spherical + 1.0e-3, # sigma_min + ) + + model_positional = ag.model_util.mge_model_from(*args) + model_keyword = ag.model_util.mge_model_from( + mask_radius=args[0], + total_gaussians=args[1], + gaussian_per_basis=args[2], + centre_prior_is_uniform=args[3], + centre=args[4], + centre_fixed=args[5], + centre_per_basis=args[6], + centre_sigma=args[7], + ell_comps_prior_is_uniform=args[8], + ell_comps_uniform_width=args[9], + ell_comps_sigma=args[10], + use_spherical=args[11], + sigma_min=args[12], + ) + + assert model_positional.prior_count == model_keyword.prior_count + assert model_positional.cls is model_keyword.cls + + instance_positional = model_positional.instance_from_prior_medians() + instance_keyword = model_keyword.instance_from_prior_medians() + + assert type(instance_positional.profile_list[0]) is type( + instance_keyword.profile_list[0] + ) + assert len(instance_positional.profile_list) == len(instance_keyword.profile_list) + + # `order_bases` defaults to False whether the call is positional or keyword, so + # neither model carries assertions. + assert model_positional.gathered_assertions() == [] + assert model_keyword.gathered_assertions() == [] + + def test__mge_model_from__total_gaussians_per_basis(): """With gaussian_per_basis=2 and total_gaussians=5, should produce 10 Gaussians.""" model = ag.model_util.mge_model_from( @@ -194,6 +277,198 @@ def test__mge_model_from__default_sigma_list_is_bitwise_unchanged(): ] +def test__mge_model_from__order_bases_two_bases(): + """ + With two bases, `order_bases` adds a single assertion requiring the first basis' + shared `ell_comps_1` to exceed the second's, which deletes the exchange symmetry + between two otherwise identical bases. + + The assertion's `name` is NOT asserted: `add_assertion(assertion, name=...)` sets + `assertion.name`, but `name` is a read-only property on `AbstractPriorModel` (it + returns the class name) and `add_assertion` swallows the resulting `AttributeError`, + so every assertion reports `"GreaterThanLessThanAssertion"` whatever name is passed. + The assertion is therefore identified by its operands, which is the stronger check + anyway -- it pins WHICH priors are ordered and in which direction. + """ + total_gaussians = 5 + + model = ag.model_util.mge_model_from( + mask_radius=1.0, + total_gaussians=total_gaussians, + gaussian_per_basis=2, + order_bases=True, + ) + + assertions = model.gathered_assertions() + + assert len(assertions) == 1 + assert isinstance(assertions[0], af.GreaterThanLessThanAssertion) + + ell_comps_1_basis_0 = model.profile_list[0].ell_comps.ell_comps_1 + ell_comps_1_basis_1 = model.profile_list[total_gaussians].ell_comps.ell_comps_1 + + # `a > b` builds the assertion as (lower=b, greater=a) == (left=b, right=a). + assert assertions[0].left is ell_comps_1_basis_1 + assert assertions[0].right is ell_comps_1_basis_0 + + # Adding assertions must not add parameters. + assert model.prior_count == 6 + + index_0 = _ell_comps_1_vector_index(model, 0) + index_1 = _ell_comps_1_vector_index(model, total_gaussians) + + vector = list(model.physical_values_from_prior_medians) + vector[index_0] = 0.3 + vector[index_1] = -0.3 + + assert model.assertions_satisfied_from_vector(vector) + + instance = model.instance_from_vector(vector) + assert len(instance.profile_list) == 2 * total_gaussians + + swapped = list(vector) + swapped[index_0] = -0.3 + swapped[index_1] = 0.3 + + assert not model.assertions_satisfied_from_vector(swapped) + + # The numpy enforcement path raises, which is what the search catches and turns into + # the resample figure of merit. `instance_from_vector` is NOT used to provoke it: + # `test_autogalaxy/config/general.yaml` sets `test: exception_override: true`, which + # makes `instance_for_arguments` skip `check_assertions` entirely for the whole unit + # test suite, so the raise is invoked directly on the same arguments the vector maps. + arguments = dict( + zip( + [prior_tuple.prior for prior_tuple in model.prior_tuples_ordered_by_id], + swapped, + ) + ) + + with pytest.raises(af.exc.FitException): + model.check_assertions(arguments) + + +def test__mge_model_from__order_bases_three_bases(): + total_gaussians = 4 + + model = ag.model_util.mge_model_from( + mask_radius=1.0, + total_gaussians=total_gaussians, + gaussian_per_basis=3, + order_bases=True, + ) + + assertions = model.gathered_assertions() + + assert len(assertions) == 2 + + ell_comps_1_list = [ + model.profile_list[j * total_gaussians].ell_comps.ell_comps_1 for j in range(3) + ] + + # Assertion j orders basis j above basis j + 1, giving a strictly decreasing chain. + for j, assertion in enumerate(assertions): + assert assertion.left is ell_comps_1_list[j + 1] + assert assertion.right is ell_comps_1_list[j] + + assert model.prior_count == 8 + + vector = list(model.physical_values_from_prior_medians) + + for j, value in enumerate([0.4, 0.0, -0.4]): + vector[_ell_comps_1_vector_index(model, j * total_gaussians)] = value + + assert model.assertions_satisfied_from_vector(vector) + + # Violating only the second link is enough to fail the chain. + vector[_ell_comps_1_vector_index(model, 2 * total_gaussians)] = 0.2 + + assert not model.assertions_satisfied_from_vector(vector) + + +def test__mge_model_from__order_bases_single_basis_no_op(): + model = ag.model_util.mge_model_from( + mask_radius=1.0, total_gaussians=5, gaussian_per_basis=1, order_bases=True + ) + + # One basis cannot be permuted with anything, so there is nothing to assert. + assert model.gathered_assertions() == [] + assert model.prior_count == 4 + + +def test__mge_model_from__order_bases_spherical_raises(): + with pytest.raises(ValueError): + ag.model_util.mge_model_from( + mask_radius=1.0, + total_gaussians=5, + gaussian_per_basis=2, + use_spherical=True, + order_bases=True, + ) + + +def test__mge_model_from__order_bases_model_pickles(): + model = ag.model_util.mge_model_from( + mask_radius=1.0, total_gaussians=3, gaussian_per_basis=2, order_bases=True + ) + + assert len(pickle.dumps(model)) > 0 + + +def test__mge_model_from__ell_comps_limit(): + """ + `ell_comps_limit` sets the truncation box of the TruncatedGaussian ell_comps priors, + which callers such as the Euclid pipeline tighten to +/- 0.5 or +/- 0.7. + """ + total_gaussians = 3 + + model = ag.model_util.mge_model_from( + mask_radius=1.0, + total_gaussians=total_gaussians, + gaussian_per_basis=2, + ell_comps_limit=0.5, + ) + + for gaussian in model.profile_list: + for prior in [gaussian.ell_comps.ell_comps_0, gaussian.ell_comps.ell_comps_1]: + assert isinstance(prior, af.TruncatedGaussianPrior) + assert prior.lower_limit == pytest.approx(-0.5, 1.0e-8) + assert prior.upper_limit == pytest.approx(0.5, 1.0e-8) + + model = ag.model_util.mge_model_from( + mask_radius=1.0, total_gaussians=total_gaussians, gaussian_per_basis=2 + ) + + for gaussian in model.profile_list: + for prior in [gaussian.ell_comps.ell_comps_0, gaussian.ell_comps.ell_comps_1]: + assert prior.lower_limit == pytest.approx(-1.0, 1.0e-8) + assert prior.upper_limit == pytest.approx(1.0, 1.0e-8) + + +def test__mge_model_from__ell_comps_limit_does_not_alter_uniform_priors(): + model = ag.model_util.mge_model_from( + mask_radius=1.0, + total_gaussians=3, + ell_comps_prior_is_uniform=True, + ell_comps_uniform_width=0.2, + ell_comps_limit=0.5, + ) + + prior = model.profile_list[0].ell_comps.ell_comps_0 + + assert isinstance(prior, af.UniformPrior) + assert prior.lower_limit == pytest.approx(-0.2, 1.0e-8) + assert prior.upper_limit == pytest.approx(0.2, 1.0e-8) + + +def test__mge_model_from__ell_comps_limit_invalid_raises(): + for ell_comps_limit in [0.0, -0.5, 1.5]: + with pytest.raises(ValueError): + ag.model_util.mge_model_from( + mask_radius=1.0, total_gaussians=5, ell_comps_limit=ell_comps_limit + ) + + def test__mge_point_model_from__returns_basis_model_with_correct_gaussians(): """ mge_point_model_from should return an af.Model wrapping a Basis whose