From 9db2921aa832b951d558adc66630aefc31bed872 Mon Sep 17 00:00:00 2001 From: samlange04 Date: Sun, 4 Oct 2026 09:47:29 +0800 Subject: [PATCH 1/9] fix: corner_anesthetic silently produced no plot for models with repeated labels corner_anesthetic keyed anesthetic's columns by the LaTeX parameter labels, which repeat whenever a model has several components of one type: every Gaussian of a multi-Gaussian basis is labelled $\epsilon_{1}^{g}$, so a lens model with an MGE light and an MGE source repeats y, x and both ellipticity components. anesthetic then raises KeyError, @log_plot_exception reports it as "posterior estimate not yet sufficient", and the corner plot never appears -- for a 19-parameter SLaM source fit it was missing at every update and at completion. Key the columns by position (always unique) and pass the LaTeX labels to anesthetic for display, so the figure looks as before. `labels` joins the reserved kwargs, since a caller passing it would now collide with them. Tests: a model with a repeated label writes its figure and still displays the repeated label (red without the fix), and `labels` is rejected as reserved. Co-Authored-By: Claude Opus 5.5 --- autofit/non_linear/plot/nest_plotters.py | 17 ++++++++-- .../non_linear/plot/test_nest_plotters.py | 33 +++++++++++++++++++ 2 files changed, 47 insertions(+), 3 deletions(-) diff --git a/autofit/non_linear/plot/nest_plotters.py b/autofit/non_linear/plot/nest_plotters.py index 64867ed90..cc961f3c5 100644 --- a/autofit/non_linear/plot/nest_plotters.py +++ b/autofit/non_linear/plot/nest_plotters.py @@ -31,10 +31,20 @@ def corner_anesthetic(samples, path=None, filename="corner_anesthetic", format=" model.total_free_parameters * config_dict["figsize_per_parammeter"], ) + # anesthetic keys its columns by name, but LaTeX labels repeat whenever a model + # has several components of one type -- every Gaussian of a multi-Gaussian basis + # is labelled $\epsilon_{1}^{g}$. A repeated key makes plot_2d raise KeyError, + # which @log_plot_exception reports as an unconverged posterior, so the plot + # silently never appears. Key the columns by position, which is always unique, + # and pass the LaTeX labels for display only. + labels = model.parameter_labels_with_superscripts_latex + columns = [f"p{i}" for i in range(len(labels))] + nested_samples = NestedSamples( np.asarray(samples.parameter_lists), weights=samples.weight_list, - columns=model.parameter_labels_with_superscripts_latex, + columns=columns, + labels=labels, ) try: @@ -63,7 +73,7 @@ def corner_anesthetic(samples, path=None, filename="corner_anesthetic", format=" } kwargs = checked_kwargs( kwargs, - reserved=("data", "weights", "columns"), + reserved=("data", "weights", "columns", "labels"), target="anesthetic", ) @@ -78,7 +88,8 @@ def corner_anesthetic(samples, path=None, filename="corner_anesthetic", format=" ) fig, axes = make_2d_axes( - model.parameter_labels_with_superscripts_latex, + columns, + labels=nested_samples.get_labels_map(), **axes_settings, ) diff --git a/test_autofit/non_linear/plot/test_nest_plotters.py b/test_autofit/non_linear/plot/test_nest_plotters.py index 94c811e5e..ea1d600be 100644 --- a/test_autofit/non_linear/plot/test_nest_plotters.py +++ b/test_autofit/non_linear/plot/test_nest_plotters.py @@ -78,3 +78,36 @@ def test__corner_anesthetic__reserved_kwarg_is_not_swallowed_by_the_decorator(sa nest_plotters.corner_anesthetic(samples=samples, weights=[1.0]) assert "weights" in str(error.value) + + +def test__corner_anesthetic__repeated_labels_still_plot(monkeypatch): + # A model with several components of one type repeats its LaTeX labels + # (every Gaussian of a basis is "$\\epsilon_{1}^{g}$"). Keyed by label, + # anesthetic raised KeyError, @log_plot_exception logged it as an + # unconverged posterior and no plot was ever written. + rng = np.random.default_rng(1) + samples = MockSamples() + samples.model = MockModel(["$x$", "$e$", "$e$"]) + samples.parameter_lists = rng.normal(size=(200, 3)).tolist() + samples.weight_list = rng.random(200).tolist() + + written = [] + monkeypatch.setattr( + nest_plotters, "output_figure", lambda *args, **kwargs: written.append(kwargs) + ) + + import matplotlib.pyplot as plt + + nest_plotters.corner_anesthetic(samples=samples) + + assert written, "corner_anesthetic gave up without writing the figure" + ylabels = [ax.get_ylabel() for ax in plt.gcf().axes if ax.get_ylabel()] + assert ylabels.count("$e$") >= 2 # the repeated label is still what is displayed + plt.close("all") + + +def test__corner_anesthetic__labels_kwarg_is_reserved(samples): + with pytest.raises(PlotKwargsError) as error: + nest_plotters.corner_anesthetic(samples=samples, labels=["a", "b"]) + + assert "labels" in str(error.value) From 941bd9d1b0f2a68b43b6bedd04c083b3a987b43c Mon Sep 17 00:00:00 2001 From: samlange04 Date: Sat, 17 Oct 2026 21:27:29 +0800 Subject: [PATCH 2/9] feat: component-path labels, per-component and derived-parameter corner plots Looking at a 19-parameter SLaM source fit, the corner plot had three problems beyond the repeated-label crash the previous commit fixed: 1. Labels did not tell components apart. The superscript was the immediate parent name or the notation config's class abbreviation, so every Gaussian of a multi-Gaussian basis was y^g whether it sat in the lens bulge, the lens disk or the source bulge. The superscript is now the dot-joined path of the named components owning the prior (new `component_paths`): Collection containers (`galaxies`, `profile_list`), the tuple name and a list index that only distinguishes copies of a shared prior are dropped, giving y^{lens.bulge}, y^{lens.disk}, y^{source.bulge}, theta_Ein^{lens.mass}. The config's class override replaces only the component it names (`lens.ext`), and a prior directly on a root model keeps the old behaviour, so existing labels of simple models are unchanged. 2. One 19x19 plot is too dense to read. `parameter_indices_by_component` groups parameters by top-level component and `WeightedDefaults.plot_results` writes `corner_anesthetic_.png` per component beside the full plot (switch `nest.corner_anesthetic_components`, default on; none for a single-component model). `corner_anesthetic` gains `parameter_indices=`. 3. The sampled parameters are not the ones a model is read in. A component class may declare `derived_parameters = {("gamma_1", "gamma_2"): fn}`: the free parameters it replaces and a function of every parameter of the component (free ones as sample arrays, fixed ones as floats) returning the derived ones; declarations inherit down the MRO. `derived.py` applies them to a sample array in model order, keeping each component's superscript. A derived angle is returned as `Periodic(values, period)` and recentred on its weighted circular mean, so a posterior peaked at the conversion's branch cut is not drawn as two peaks. Switch `nest.corner_anesthetic_derived` (independent of the other two) writes `corner_anesthetic_derived.png` and, with the per-component switch, one per component; skipped when nothing in the model declares a conversion. `corner_anesthetic` gains `derived=`. `should_plot` takes a `default` for a key an older workspace config does not mention, so neither new switch breaks an existing config. Tests: component paths, config override scope and shared-vs-independent index (test_model_mapper), the derived set, fixed values, inheritance and periodic recentring (test_derived), subset and derived plots (test_nest_plotters), the per-component and derived plot calls and the missing-key fallback (test_family_bases). Co-Authored-By: Claude Fable 5.1 --- autofit/__init__.py | 2 +- autofit/config/visualize/plots_search.yaml | 2 + autofit/mapper/prior_model/abstract.py | 212 +++++++++++--- autofit/mapper/prior_model/derived.py | 275 ++++++++++++++++++ autofit/non_linear/plot/nest_plotters.py | 51 +++- autofit/non_linear/search/posterior_kind.py | 96 +++++- test_autofit/mapper/model/test_derived.py | 165 +++++++++++ .../mapper/model/test_model_mapper.py | 199 ++++++++++++- .../non_linear/plot/test_nest_plotters.py | 67 +++++ .../non_linear/search/test_family_bases.py | 189 +++++++++++- 10 files changed, 1192 insertions(+), 66 deletions(-) create mode 100644 autofit/mapper/prior_model/derived.py create mode 100644 test_autofit/mapper/model/test_derived.py diff --git a/autofit/__init__.py b/autofit/__init__.py index 1eda9f2f3..2257d87f6 100644 --- a/autofit/__init__.py +++ b/autofit/__init__.py @@ -47,6 +47,7 @@ from .mapper.model_mapper import ModelMapper from .mapper.model_mapper import ModelMapper as Mapper from .mapper.model_object import ModelObject +from .mapper.prior_model.derived import Periodic from .mapper.operator import DiagonalMatrix from .mapper.prior.constant import Constant from .mapper.prior.arithmetic.assertion import ComparisonAssertion @@ -142,7 +143,6 @@ from . import example as ex - for type_ in ( "model", "collection", diff --git a/autofit/config/visualize/plots_search.yaml b/autofit/config/visualize/plots_search.yaml index 24f805e1d..4ef39e568 100644 --- a/autofit/config/visualize/plots_search.yaml +++ b/autofit/config/visualize/plots_search.yaml @@ -1,5 +1,7 @@ nest: corner_anesthetic: true # Output corner figure (using anestetic) during a non-linear search fit? + corner_anesthetic_components: true # Also output one corner figure per top-level model component (e.g. per galaxy), each named corner_anesthetic_? + corner_anesthetic_derived: true # Output corner figure(s) of the derived parameters (e.g. a shear's magnitude and angle rather than gamma_1 / gamma_2), named corner_anesthetic_derived[_]? Independent of the two above. mcmc: corner_cornerpy: true # Output corner figure (using corner.py) during a non-linear search fit? mle: diff --git a/autofit/mapper/prior_model/abstract.py b/autofit/mapper/prior_model/abstract.py index 02f842663..360c842cd 100644 --- a/autofit/mapper/prior_model/abstract.py +++ b/autofit/mapper/prior_model/abstract.py @@ -745,7 +745,7 @@ def assert_no_assertions(obj): except AttributeError: pass - def instance_from_unit_vector(self, unit_vector, ignore_assertions : bool = False): + def instance_from_unit_vector(self, unit_vector, ignore_assertions: bool = False): """ Returns a ModelInstance, which has an attribute and class instance corresponding to every `Model` attributed to this instance. @@ -795,8 +795,7 @@ def instance_from_unit_vector(self, unit_vector, ignore_assertions : bool = Fals ) return self.instance_for_arguments( - arguments, - ignore_assertions=ignore_assertions + arguments, ignore_assertions=ignore_assertions ) @property @@ -1013,9 +1012,7 @@ def instance_from_vector(self, vector, ignore_assertions: bool = False, xp=np): arguments = dict(zip(priors, vector)) return self.instance_for_arguments( - arguments, - ignore_assertions=ignore_assertions, - xp=xp + arguments, ignore_assertions=ignore_assertions, xp=xp ) @frozen_cache @@ -1029,7 +1026,9 @@ def _vector_priors(self) -> tuple: name/value wrappers is skipped on the likelihood hot path. Unfrozen models recompute it on every call. """ - return tuple(prior_tuple.prior for prior_tuple in self.prior_tuples_ordered_by_id) + return tuple( + prior_tuple.prior for prior_tuple in self.prior_tuples_ordered_by_id + ) def constrained_model_tuples(self): """ @@ -1524,7 +1523,7 @@ def mapper_from_uniform_floats(self, floats, b): return self.mapper_from_prior_arguments(arguments) - def instance_from_prior_medians(self, ignore_assertions : bool = False): + def instance_from_prior_medians(self, ignore_assertions: bool = False): """ Returns a list of physical values from the median values of the priors. Returns @@ -1534,8 +1533,7 @@ def instance_from_prior_medians(self, ignore_assertions : bool = False): and not checked. """ return self.instance_from_unit_vector( - unit_vector=[0.5] * self.prior_count, - ignore_assertions=ignore_assertions + unit_vector=[0.5] * self.prior_count, ignore_assertions=ignore_assertions ) def log_prior_list_from_vector( @@ -1565,7 +1563,7 @@ def log_prior_list_from_vector( ) ) - def random_instance(self, ignore_assertions : bool = False): + def random_instance(self, ignore_assertions: bool = False): """ Returns a random instance of the model. @@ -1676,9 +1674,9 @@ def from_instance( # legitimately be passed back to it. allowed_keys = None else: - allowed_keys = { - arg for arg in spec.args if arg != "self" - } | set(spec.kwonlyargs) + allowed_keys = {arg for arg in spec.args if arg != "self"} | set( + spec.kwonlyargs + ) try: result = Model( @@ -1857,9 +1855,7 @@ def instance_for_arguments( self.check_assertions(arguments, xp=xp) return self._instance_for_arguments( - arguments, - ignore_assertions=ignore_assertions, - xp=xp + arguments, ignore_assertions=ignore_assertions, xp=xp ) def path_for_name(self, name: str) -> Tuple[str, ...]: @@ -2480,40 +2476,186 @@ def parameter_labels(self) -> List[str]: return parameter_labels + @property + def _component_name_object_pairs(self) -> List[List[Tuple[str, object]]]: + """ + For each unique prior (ordered by id), the ``(name, object)`` pairs of the + named model components that own it; see ``component_paths``. + """ + from autofit.mapper.prior_model.collection import Collection + from autofit.mapper.prior.tuple_prior import TuplePrior + + paths_by_prior = defaultdict(list) + for path, prior in self.path_priors_tuples: + paths_by_prior[prior].append(path[:-1]) + + pairs_list = [] + + for path, prior in self.unique_path_prior_tuples: + path = path[:-1] + sibling_paths = paths_by_prior[prior] + same_length = all(len(other) == len(path) for other in sibling_paths) + + pairs = [] + obj = self + for i, name in enumerate(path): + try: + obj = getattr(obj, name) + except AttributeError: + obj = obj[int(name)] + if isinstance(obj, (Collection, TuplePrior)): + continue + if same_length and any(other[i] != name for other in sibling_paths): + continue + pairs.append((name, obj)) + + pairs_list.append(pairs) + + return pairs_list + + @property + def _prior_owner_and_leaf_names(self) -> List[Tuple[object, str]]: + """ + For each unique prior (ordered by id), the model component that directly + owns it (the deepest ``Model`` on its path) and the prior's leaf name, for + example ``(, "ell_comps_0")``. + """ + from autofit.mapper.prior_model.collection import Collection + from autofit.mapper.prior.tuple_prior import TuplePrior + + owners = [] + for path in self.unique_prior_paths: + owner = self + obj = self + for name in path[:-1]: + try: + obj = getattr(obj, name) + except AttributeError: + obj = obj[int(name)] + if not isinstance(obj, (Collection, TuplePrior)): + owner = obj + owners.append((owner, path[-1])) + return owners + + def derived_parameters_from( + self, parameter_array, weights=None + ) -> "DerivedParameters": + """ + The parameters of this model after each component's declared conversions + (its ``derived_parameters`` class attribute, e.g. shear components to a + magnitude and angle) are applied to an array of samples; see + ``autofit.mapper.prior_model.derived``. + + Parameters + ---------- + parameter_array + Samples of the model's free parameters, shape ``(n_samples, prior_count)``. + weights + The weight of each sample, which centres a periodic derived parameter + (an angle) on its posterior; equal by default. + """ + from autofit.mapper.prior_model.derived import derived_parameters_from + + return derived_parameters_from(self, parameter_array, weights=weights) + + @property + def has_derived_parameters(self) -> bool: + """Whether any component of this model declares a conversion that applies to it.""" + return self.derived_parameters_from(np.zeros((1, self.prior_count))).has_derived + + @property + def component_paths(self) -> List[Path]: + """ + The named model components that own each unique prior, ordered by prior id. + + A prior's path lists everything between the model and the parameter, for + example ``galaxies.lens.bulge.profile_list.29.centre.centre_0``. Most of + that does not name a component: ``galaxies`` and ``profile_list`` are + ``Collection`` containers, ``centre`` is the tuple the parameter sits in, + and ``29`` is one of the thirty Gaussians a shared prior appears under. + Each is dropped, leaving ``("lens", "bulge")``. + + An index is kept when it distinguishes the prior from its siblings, so a + collection of components with independent priors gives ``("0",)``, + ``("1",)``; it is dropped only where the paths to a shared prior differ, + which is what makes it meaningless. + + This is what labels parameters in results and plots, and what groups them + by component (see ``parameter_indices_by_component``). + """ + return [ + tuple(name for name, _ in pairs) + for pairs in self._component_name_object_pairs + ] + + @property + def parameter_indices_by_component(self) -> Dict[str, List[int]]: + """ + The indices of the parameters belonging to each top-level model component, + keyed by the component's name and in model order, for example + ``{"lens": [0, ..., 14], "source": [15, ..., 18]}``. + + Parameters whose priors sit directly on the model (no named component) + are grouped under ``"model"``. + """ + groups = {} + for i, path in enumerate(self.component_paths): + groups.setdefault(path[0] if path else "model", []).append(i) + return groups + @property def superscripts(self) -> List[str]: """ Returns a list of the model component superscripts for every parameter in a model. + The superscript is the dot-joined path of named components that own the + parameter (see ``component_paths``): a lens model with a lens galaxy and a + source galaxy labels the Gaussians of their light with ``lens.bulge`` and + ``source.bulge``, so every parameter of every component has a distinct + label however many components share a class. - The class superscript labels are defined as the name of every model component in the `ModelMapper`. For - the example of a 1D Gaussian, if the model component name is `gaussian` three superscripts + For the example of a 1D Gaussian, if the model component name is `gaussian` three superscripts with this string (corresponding to the parameters `centre`, `normalization` and `sigma`) will be returned. - For a `Collection`, the name of the inner model components are used. - - These superscripts may be overwritten by those returned from the `superscripts_config_overwrite` property, - which optionally loads the superscripts from a `.json` config file. This allows high levels of customization - in what superscripts are used. + The name of any component whose class has an entry in the `notation/label.yaml` config + (`superscript:`) is replaced by that entry, so `ExternalShear=ext` gives `lens.ext` rather + than `lens.shear`; see the `superscripts_overwrite_via_config` property. A parameter with + no named component (a prior directly on the model) uses the entry for the model's own class. This is used for displaying model results as text and for visualization. """ + superscripts = [] - prior_paths = self.unique_prior_paths - - tuple_filter = TuplePathModifier(self) + for pairs, superscript_overwrite in zip( + self._component_name_object_pairs, self.superscripts_overwrite_via_config + ): + if not pairs: + superscripts.append(superscript_overwrite or None) + continue - prior_paths = map(tuple_filter, prior_paths) + superscripts.append( + ".".join( + self._superscript_for_component(name, obj) for name, obj in pairs + ) + ) - superscripts = [path[-2] if len(path) > 1 else None for path in prior_paths] + return superscripts - return [ - superscript if not superscript_overwrite else superscript_overwrite - for superscript, superscript_overwrite in zip( - superscripts, self.superscripts_overwrite_via_config - ) - ] + @staticmethod + def _superscript_for_component(name: str, obj) -> str: + """ + The superscript for one named component: the config entry for its class if + there is one, else its name. A list index is never replaced, since every + element of the list has the same class. + """ + if name.isdigit(): + return name + cls = getattr(obj, "cls", type(obj)) + try: + return conf.instance["notation"]["label"]["superscript"][cls.__name__] + except KeyError: + return name @property def superscripts_overwrite_via_config(self) -> List[str]: diff --git a/autofit/mapper/prior_model/derived.py b/autofit/mapper/prior_model/derived.py new file mode 100644 index 000000000..de7556a33 --- /dev/null +++ b/autofit/mapper/prior_model/derived.py @@ -0,0 +1,275 @@ +""" +Derived parameters: a model component's own re-parameterisation of some of its +free parameters, for plotting and reporting. + +Many components are *sampled* in one parameterisation and *read* in another: a +shear is fit as ``(gamma_1, gamma_2)`` but has a magnitude and an angle, an +ellipse as two elliptical components but has an axis ratio and a position +angle, a multipole as two components but has a strength and a phase. A component +class declares the conversion as a class attribute:: + + class ExternalShear: + derived_parameters = { + ("gamma_1", "gamma_2"): shear_magnitude_and_angle_dict_from, + } + +keyed by the names of the free parameters it replaces and valued by a function +that takes every parameter of the component by name (the free ones as arrays +over the samples, the fixed ones as floats) and returns a ``dict`` of derived +name to array. The declarations of a class's bases are inherited, so a subclass +adds to them rather than restating them. + +``DerivedParameters`` applies those declarations to an array of samples: the +replaced parameters go, the derived ones take their place (at the position of +the first replaced one, in model order), everything else passes through +unchanged, and each derived parameter carries the superscript of the component +it came from. A declaration whose replaced parameters are not all free in this +model is skipped, since there is nothing to convert. + +An angle is periodic, and a conversion fixes where its branch cut falls: a +position angle in ``[-45, 135)`` whose posterior peaks near 135 is split in two, +and its corner plot shows a double peak that is not there. A conversion returns +such a value as ``Periodic(angle, period)`` and the samples are recentred on +their (weighted) circular mean, so the cut sits opposite the peak. +""" + +from typing import Callable, Dict, List, Optional, Tuple + +import numpy as np + +from autonerves import conf + +from autofit.text import formatter as frm + +DerivedFunction = Callable[..., Dict[str, np.ndarray]] + + +class Periodic: + def __init__(self, values, period: float): + """ + A derived parameter that is periodic (an angle), returned by a conversion so + the samples are recentred on their circular mean; see the module docstring. + + Parameters + ---------- + values + The derived values over the samples, in whatever range the conversion gives. + period + The period, e.g. 180 for a position angle, ``360 / m`` for a multipole phase. + """ + self.values = np.asarray(values, dtype=float) + self.period = float(period) + + def recentred(self, weights=None) -> np.ndarray: + """ + The values wrapped into the period centred on their weighted circular mean, + so a posterior that straddled the branch cut is contiguous. + """ + values = self.values + if values.size == 0: + return values + theta = 2.0 * np.pi * values / self.period + weights = ( + np.ones_like(values) + if weights is None + else np.asarray(weights, dtype=float) + ) + weights = np.broadcast_to(weights, values.shape) + mean = ( + np.arctan2(np.sum(weights * np.sin(theta)), np.sum(weights * np.cos(theta))) + * self.period + / (2.0 * np.pi) + ) + half = self.period / 2.0 + return (values - mean + half) % self.period + mean - half + + +def derived_parameters_for_class(cls) -> Dict[Tuple[str, ...], DerivedFunction]: + """ + The derived-parameter declarations of a class and all of its bases, the most + derived class last so it can override an entry of a base. + """ + declarations = {} + for base in reversed(getattr(cls, "__mro__", (cls,))): + declarations.update(base.__dict__.get("derived_parameters", {}) or {}) + return declarations + + +class DerivedParameters: + def __init__( + self, + names: List[str], + superscripts: List[Optional[str]], + component_paths: List[Tuple[str, ...]], + parameter_array: np.ndarray, + derived_mask: List[bool], + ): + """ + Parameters of a model after each component's declared conversions are + applied to an array of samples; see the module docstring. + + Parameters + ---------- + names + The name of every parameter of the derived set, in order. + superscripts + The superscript of each, that of the component it belongs to. + component_paths + The named-component path of each (see ``AbstractPriorModel.component_paths``). + parameter_array + The samples of the derived set, shape ``(n_samples, len(names))``. + derived_mask + Whether each parameter was derived (``True``) or passed through. + """ + self.names = names + self.superscripts = superscripts + self.component_paths = component_paths + self.parameter_array = parameter_array + self.derived_mask = derived_mask + + @property + def has_derived(self) -> bool: + """Whether any declaration was applied, so the set differs from the model's own.""" + return any(self.derived_mask) + + @property + def parameter_labels(self) -> List[str]: + return [ + frm.convert_name_to_label(parameter_name=name, name_to_label=True) + for name in self.names + ] + + @property + def parameter_labels_with_superscripts(self) -> List[str]: + return [ + f"{label}^{{\\rm {superscript}}}" if superscript else label + for label, superscript in zip(self.parameter_labels, self.superscripts) + ] + + @property + def parameter_labels_with_superscripts_latex(self) -> List[str]: + return [f"${label}$" for label in self.parameter_labels_with_superscripts] + + @property + def parameter_indices_by_component(self) -> Dict[str, List[int]]: + """As ``AbstractPriorModel.parameter_indices_by_component``, over the derived set.""" + groups = {} + for i, path in enumerate(self.component_paths): + groups.setdefault(path[0] if path else "model", []).append(i) + return groups + + +def _flat_fixed_values(owner) -> Dict[str, float]: + """ + The fixed (non-prior) numeric attributes of a model component by leaf + parameter name, a fixed tuple ``centre=(0.0, 0.0)`` as ``centre_0``, + ``centre_1``, so a conversion can take a constant such as a multipole's order. + """ + values = {} + for name, value in vars(owner).items(): + if name.startswith("_") or name in ("cls", "id"): + continue + if isinstance(value, tuple): + for i, item in enumerate(value): + try: + values[f"{name}_{i}"] = float(item) + except (TypeError, ValueError): + pass + continue + if isinstance(value, bool): + continue + try: + values[name] = float(value) + except (TypeError, ValueError): + pass + return values + + +def derived_parameters_from( + model, parameter_array: np.ndarray, weights=None +) -> DerivedParameters: + """ + Apply every component's declared conversions to an array of samples of the + model; see the module docstring. Called through + ``AbstractPriorModel.derived_parameters_from``. + + Parameters + ---------- + weights + The weight of each sample, used to centre a ``Periodic`` derived parameter + on its posterior rather than on the prior volume; equal by default. + """ + parameter_array = np.asarray(parameter_array) + n_samples = parameter_array.shape[0] + + owners = model._prior_owner_and_leaf_names + names = model.parameter_names + superscripts = model.superscripts + component_paths = model.component_paths + + # Which free parameters each component owns, by leaf name -> model index. + indices_by_owner = {} + for i, (owner, leaf) in enumerate(owners): + indices_by_owner.setdefault(id(owner), (owner, {}))[1][leaf] = i + + # Resolve every applicable declaration first: which indices it consumes and + # what it yields, keyed by the index it is inserted at. + insert_at = {} + consumed = set() + for owner, free in indices_by_owner.values(): + cls = getattr(owner, "cls", None) + if cls is None: + continue + for replaced, function in derived_parameters_for_class(cls).items(): + if not all(name in free for name in replaced): + continue + if any(free[name] in consumed for name in replaced): + continue + values = _flat_fixed_values(owner) + values.update( + {name: parameter_array[:, index] for name, index in free.items()} + ) + derived = function(**values) + first = min(free[name] for name in replaced) + insert_at[first] = [ + ( + name, + np.broadcast_to( + ( + value.recentred(weights) + if isinstance(value, Periodic) + else np.asarray(value, dtype=float) + ), + (n_samples,), + ), + ) + for name, value in derived.items() + ] + consumed.update(free[name] for name in replaced) + + out_names, out_superscripts, out_paths, out_columns, out_mask = [], [], [], [], [] + for i in range(len(names)): + if i in insert_at: + for name, column in insert_at[i]: + out_names.append(name) + out_superscripts.append(superscripts[i]) + out_paths.append(component_paths[i]) + out_columns.append(column) + out_mask.append(True) + if i in consumed: + continue + out_names.append(names[i]) + out_superscripts.append(superscripts[i]) + out_paths.append(component_paths[i]) + out_columns.append(parameter_array[:, i]) + out_mask.append(False) + + return DerivedParameters( + names=out_names, + superscripts=out_superscripts, + component_paths=out_paths, + parameter_array=( + np.column_stack(out_columns) if out_columns else parameter_array + ), + derived_mask=out_mask, + ) diff --git a/autofit/non_linear/plot/nest_plotters.py b/autofit/non_linear/plot/nest_plotters.py index cc961f3c5..761dd24dc 100644 --- a/autofit/non_linear/plot/nest_plotters.py +++ b/autofit/non_linear/plot/nest_plotters.py @@ -14,7 +14,33 @@ @skip_in_test_mode @log_plot_exception -def corner_anesthetic(samples, path=None, filename="corner_anesthetic", format="show", **kwargs): +def corner_anesthetic( + samples, + path=None, + filename="corner_anesthetic", + format="show", + parameter_indices=None, + derived=False, + **kwargs, +): + """ + Corner plot of the posterior via anesthetic, over every parameter of the model + or, with ``parameter_indices``, over a subset of them (the parameters of one + model component, say) so that a many-parameter fit stays readable. + + Parameters + ---------- + samples + The samples of the non-linear search, whose ``model`` labels the axes. + parameter_indices + The indices (in model order, or in the derived set's order when + ``derived``) of the parameters to plot; all by default. + derived + Plot the model's derived parameters instead of its free ones: each + component's declared conversion is applied to the samples (a shear's + components become its magnitude and angle, say) and parameters without + one pass through; see ``AbstractPriorModel.derived_parameters_from``. + """ config_dict = conf.instance["visualize"]["plots_settings"]["corner_anesthetic"] from anesthetic.samples import NestedSamples @@ -26,9 +52,25 @@ def corner_anesthetic(samples, path=None, filename="corner_anesthetic", format=" model = samples.model + parameter_array = np.asarray(samples.parameter_lists) + + if derived: + derived_parameters = model.derived_parameters_from( + parameter_array, weights=samples.weight_list + ) + labels = derived_parameters.parameter_labels_with_superscripts_latex + parameter_array = derived_parameters.parameter_array + else: + labels = model.parameter_labels_with_superscripts_latex + + if parameter_indices is not None: + parameter_indices = list(parameter_indices) + labels = [labels[i] for i in parameter_indices] + parameter_array = parameter_array[:, parameter_indices] + figsize = ( - model.total_free_parameters * config_dict["figsize_per_parammeter"], - model.total_free_parameters * config_dict["figsize_per_parammeter"], + len(labels) * config_dict["figsize_per_parammeter"], + len(labels) * config_dict["figsize_per_parammeter"], ) # anesthetic keys its columns by name, but LaTeX labels repeat whenever a model @@ -37,11 +79,10 @@ def corner_anesthetic(samples, path=None, filename="corner_anesthetic", format=" # which @log_plot_exception reports as an unconverged posterior, so the plot # silently never appears. Key the columns by position, which is always unique, # and pass the LaTeX labels for display only. - labels = model.parameter_labels_with_superscripts_latex columns = [f"p{i}" for i in range(len(labels))] nested_samples = NestedSamples( - np.asarray(samples.parameter_lists), + parameter_array, weights=samples.weight_list, columns=columns, labels=labels, diff --git a/autofit/non_linear/search/posterior_kind.py b/autofit/non_linear/search/posterior_kind.py index 83341674e..231cff178 100644 --- a/autofit/non_linear/search/posterior_kind.py +++ b/autofit/non_linear/search/posterior_kind.py @@ -21,6 +21,8 @@ import warnings from typing import Optional +import numpy as np + from autonerves import conf from autofit.non_linear.search.capabilities import PosteriorKind @@ -37,8 +39,18 @@ def initializer_for(self, initializer=None): def default_initializer(self): raise NotImplementedError - def should_plot(self, name: str) -> bool: - return conf.instance["visualize"]["plots_search"][self.plots_section][name] + def should_plot(self, name: str, default: Optional[bool] = None) -> bool: + """ + Whether the ``plots_search`` config switches on the named plot. A key a + user's (older) config does not mention falls back to ``default`` when one + is given, so a new plot does not break an existing workspace. + """ + try: + return conf.instance["visualize"]["plots_search"][self.plots_section][name] + except KeyError: + if default is None: + raise + return default def plot_results(self, search, samples): raise NotImplementedError @@ -100,21 +112,85 @@ def nested_initializer_for(self, initializer=None): from autofit.non_linear.initializer import InitializerParamBounds if isinstance(initializer, InitializerParamBounds): - raise ValueError("InitializerParamBounds cannot be used for nested sampling") + raise ValueError( + "InitializerParamBounds cannot be used for nested sampling" + ) return self.initializer_for(initializer) def plot_results(self, search, samples): from autofit.non_linear.plot import corner_anesthetic - if self.should_plot("corner_anesthetic"): - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - corner_anesthetic( - samples=samples, - path=search.paths.image_path / "search", - format="png", + path = search.paths.image_path / "search" + + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + + if self.should_plot("corner_anesthetic"): + corner_anesthetic(samples=samples, path=path, format="png") + + per_component = self.should_plot( + "corner_anesthetic_components", default=True + ) + + if per_component: + self._corner_per_component( + corner_anesthetic, + samples, + path, + groups=samples.model.parameter_indices_by_component, + ) + + # The derived-parameter plots re-express each component's sampled + # parameters in the ones it is read in (a shear's magnitude and + # angle rather than gamma_1 / gamma_2), where a component declares + # the conversion. Independent of the plots above, so it can be the + # only corner plot or sit beside them; skipped when no component + # declares anything, as it would repeat the plain plot. + if self.should_plot("corner_anesthetic_derived", default=False): + derived = samples.model.derived_parameters_from( + np.asarray(samples.parameter_lists) ) + if derived.has_derived: + corner_anesthetic( + samples=samples, + path=path, + filename="corner_anesthetic_derived", + format="png", + derived=True, + ) + + if per_component: + self._corner_per_component( + corner_anesthetic, + samples, + path, + groups=derived.parameter_indices_by_component, + derived=True, + ) + + @staticmethod + def _corner_per_component(corner_anesthetic, samples, path, groups, derived=False): + """ + One corner plot per top-level model component (each galaxy of a lens + model), as the full plot of a many-parameter model is too dense to read. + A model with a single component already has it, so none is made. + """ + if len(groups) < 2: + return + + stem = "corner_anesthetic_derived" if derived else "corner_anesthetic" + + for name, parameter_indices in groups.items(): + corner_anesthetic( + samples=samples, + path=path, + filename=f"{stem}_{name}", + format="png", + parameter_indices=parameter_indices, + derived=derived, + ) + class PointDefaults(PosteriorDefaults): kind = PosteriorKind.POINT diff --git a/test_autofit/mapper/model/test_derived.py b/test_autofit/mapper/model/test_derived.py new file mode 100644 index 000000000..574b02b75 --- /dev/null +++ b/test_autofit/mapper/model/test_derived.py @@ -0,0 +1,165 @@ +import numpy as np +import pytest + +import autofit as af + + +def _polar(comp_0, comp_1, **kwargs): + return { + "strength": np.hypot(comp_0, comp_1), + "angle": np.degrees(np.arctan2(comp_0, comp_1)), + } + + +def _polar_periodic(comp_0, comp_1, **kwargs): + return { + "strength": np.hypot(comp_0, comp_1), + "angle": af.Periodic(np.degrees(np.arctan2(comp_0, comp_1)), period=360.0), + } + + +class MockPeriodicComponent: + derived_parameters = {("comp_0", "comp_1"): _polar_periodic} + + def __init__(self, centre=0.0, comp=(0.0, 0.0)): + self.centre = centre + self.comp = comp + + +def _scaled(comp_0, comp_1, scale, **kwargs): + return {"scaled": np.hypot(comp_0, comp_1) * scale} + + +class MockComponent: + # Sampled as two components, read as a strength and an angle. + derived_parameters = {("comp_0", "comp_1"): _polar} + + def __init__(self, centre=0.0, comp=(0.0, 0.0)): + self.centre = centre + self.comp = comp + + +class MockScaledComponent(MockComponent): + # A subclass adds to, and may override, what its base declares. + derived_parameters = {("comp_0", "comp_1"): _scaled} + + def __init__(self, centre=0.0, comp=(0.0, 0.0), scale=1.0): + super().__init__(centre=centre, comp=comp) + self.scale = scale + + +class MockGalaxy: + def __init__(self, light=None, mass=None): + self.light = light + self.mass = mass + + +def _component(cls, comp=None, **fixed): + # The mocks have no prior config, so their priors are given explicitly; + # assigning the tuple prior after construction keeps ``centre`` first. + from autofit.mapper.prior.tuple_prior import TuplePrior + + model = af.Model(cls, centre=af.UniformPrior(-1.0, 1.0), **fixed) + if comp is None: + comp = TuplePrior() + comp.comp_0 = af.UniformPrior(-1.0, 1.0) + comp.comp_1 = af.UniformPrior(-1.0, 1.0) + model.comp = comp + return model + + +def test__derived_parameters__replace_components_in_place(): + model = _component(MockComponent) + samples = np.array([[0.5, 3.0, 4.0], [0.1, 0.0, 1.0]]) + + derived = model.derived_parameters_from(samples) + + assert derived.has_derived + assert derived.names == ["centre", "strength", "angle"] + assert derived.derived_mask == [False, True, True] + assert derived.parameter_array[:, 0] == pytest.approx([0.5, 0.1]) + assert derived.parameter_array[:, 1] == pytest.approx([5.0, 1.0]) + assert derived.parameter_array[:, 2] == pytest.approx([36.869898, 0.0]) + + +def test__derived_parameters__fixed_values_reach_the_conversion_and_subclass_overrides(): + model = _component(MockScaledComponent, scale=2.0) + + derived = model.derived_parameters_from(np.array([[0.0, 3.0, 4.0]])) + + assert derived.names == ["centre", "scaled"] + assert derived.parameter_array[0, 1] == pytest.approx(10.0) + + +def test__derived_parameters__no_conversion_when_a_replaced_parameter_is_fixed(): + model = _component(MockComponent, comp=(0.0, 1.0)) + + derived = model.derived_parameters_from(np.array([[0.5]])) + + assert not derived.has_derived + assert not model.has_derived_parameters + assert derived.names == ["centre"] + assert derived.parameter_array.tolist() == [[0.5]] + + +def test__derived_parameters__carry_their_component_superscript_and_grouping(): + model = af.Collection( + galaxies=af.Collection( + lens=af.Model(MockGalaxy, mass=_component(MockComponent)), + source=af.Model(MockGalaxy, light=af.Model(af.m.MockClassx2NoSuperScript)), + ) + ) + rng = np.random.default_rng(0) + + derived = model.derived_parameters_from(rng.normal(size=(4, model.prior_count))) + + assert derived.names == ["centre", "strength", "angle", "one", "two"] + assert derived.superscripts == ["lens.mass"] * 3 + ["source.light"] * 2 + assert derived.parameter_indices_by_component == { + "lens": [0, 1, 2], + "source": [3, 4], + } + assert derived.parameter_labels_with_superscripts_latex[1] == r"$s^{\rm lens.mass}$" + + +def test__derived_parameters__plain_model_passes_through(): + model = af.Model(af.m.MockClassx2NoSuperScript) + samples = np.array([[1.0, 2.0]]) + + derived = model.derived_parameters_from(samples) + + assert not derived.has_derived + assert derived.names == model.parameter_names + assert derived.parameter_array.tolist() == samples.tolist() + + +def test__periodic__recentres_on_the_circular_mean(): + from autofit.mapper.prior_model.derived import Periodic + + # A posterior peaked at the branch cut of [-180, 180): half the samples + # just below 180, half just above -180. Recentred, they are contiguous + # around 180 and nothing is left at -180. + values = np.array([175.0, 178.0, -179.0, -176.0]) + + recentred = Periodic(values, period=360.0).recentred() + + assert recentred == pytest.approx([175.0, 178.0, 181.0, 184.0]) + + # Weights centre on the posterior: with all the weight on one side the + # other side is the one that moves. + recentred = Periodic(values, period=360.0).recentred(weights=[1, 1, 0, 0]) + assert recentred == pytest.approx([175.0, 178.0, 181.0, 184.0]) + recentred = Periodic(values, period=360.0).recentred(weights=[0, 0, 1, 1]) + assert recentred == pytest.approx([-185.0, -182.0, -179.0, -176.0]) + + +def test__derived_parameters__periodic_angle_is_recentred_with_the_sample_weights(): + model = _component(MockPeriodicComponent) + # arctan2(comp_0, comp_1) for these straddles +-180. + samples = np.array([[0.0, 0.1, -1.0], [0.0, -0.1, -1.0]]) + + derived = model.derived_parameters_from(samples, weights=[1.0, 1.0]) + + angle = derived.parameter_array[:, 2] + assert np.ptp(angle) == pytest.approx(11.42, abs=0.01) # not ~348 + assert derived.names == ["centre", "strength", "angle"] diff --git a/test_autofit/mapper/model/test_model_mapper.py b/test_autofit/mapper/model/test_model_mapper.py index 3a7433545..635e6bd04 100644 --- a/test_autofit/mapper/model/test_model_mapper.py +++ b/test_autofit/mapper/model/test_model_mapper.py @@ -24,6 +24,17 @@ def __init__(self, one, two, three): # noinspection PyUnresolvedReferences +class MockGalaxy: + def __init__(self, bulge=None, disk=None): + self.bulge = bulge + self.disk = disk + + +class MockBasis: + def __init__(self, profile_list=None): + self.profile_list = profile_list + + class TestRegression: def test_set_tuple_instance(self): mm = af.ModelMapper() @@ -155,6 +166,93 @@ def test__parameter_labels_with_superscripts_latex(self): r"$two_label^{\rm two}$", ] + def test__superscripts__named_components_separate_like_classes(self): + # A lens-like model: two galaxies each holding components of one class. + # The superscript is the path of named components, so the lens's bulge, + # its disk and the source's bulge are told apart; ``galaxies`` (a + # Collection) and the parameter's tuple are not components and are dropped. + model = af.Collection( + galaxies=af.Collection( + lens=af.Model( + MockGalaxy, + bulge=af.Model(af.m.MockClassx2NoSuperScript), + disk=af.Model(af.m.MockClassx2NoSuperScript), + ), + source=af.Model( + MockGalaxy, bulge=af.Model(af.m.MockClassx2NoSuperScript) + ), + ) + ) + + assert model.component_paths == [ + ("lens", "bulge"), + ("lens", "bulge"), + ("lens", "disk"), + ("lens", "disk"), + ("source", "bulge"), + ("source", "bulge"), + ] + assert model.superscripts == [ + "lens.bulge", + "lens.bulge", + "lens.disk", + "lens.disk", + "source.bulge", + "source.bulge", + ] + assert model.parameter_indices_by_component == { + "lens": [0, 1, 2, 3], + "source": [4, 5], + } + + def test__superscripts__config_replaces_the_component_it_names(self): + # ``MockClassRelativeWidth=r`` in the notation config abbreviates that + # component's own name only; the galaxy's name stays. + model = af.Collection( + galaxy=af.Model(MockGalaxy, bulge=af.Model(af.m.MockClassRelativeWidth)) + ) + + assert model.superscripts == ["galaxy.r", "galaxy.r", "galaxy.r"] + assert ( + model.parameter_labels_with_superscripts[0] == r"one_label^{\rm galaxy.r}" + ) + + # A prior directly on the model has no named component and keeps the + # config entry for the model's class. + assert af.Model(af.m.MockClassRelativeWidth).superscripts == ["r", "r", "r"] + assert af.Model(af.m.MockClassRelativeWidth).parameter_indices_by_component == { + "model": [0, 1, 2] + } + + def test__superscripts__list_index_kept_only_when_priors_are_not_shared(self): + # A basis whose profiles share one set of priors: the index is one of + # many paths to the same prior, so it says nothing and is dropped. + profile_list = af.Collection( + [af.Model(af.m.MockClassx2NoSuperScript) for _ in range(3)] + ) + for profile in profile_list[1:]: + profile.one = profile_list[0].one + profile.two = profile_list[0].two + model = af.Collection( + galaxy=af.Model( + MockGalaxy, bulge=af.Model(MockBasis, profile_list=profile_list) + ) + ) + + assert model.component_paths == [("galaxy", "bulge"), ("galaxy", "bulge")] + assert model.superscripts == ["galaxy.bulge", "galaxy.bulge"] + + # Independent priors: the index is what tells the profiles apart. + model = af.Collection( + profiles=af.Collection( + [af.Model(af.m.MockClassx2NoSuperScript) for _ in range(2)] + ) + ) + + assert model.component_paths == [("0",), ("0",), ("1",), ("1",)] + assert model.superscripts == ["0", "0", "1", "1"] + assert model.parameter_indices_by_component == {"0": [0, 1], "1": [2, 3]} + def test_name_for_prior(self): ls = af.Collection( [ @@ -524,6 +622,93 @@ def test_prior_prior_model_dict(self): == af.m.MockClassx2 ) + def test__superscripts__named_components_separate_like_classes(self): + # A lens-like model: two galaxies each holding components of one class. + # The superscript is the path of named components, so the lens's bulge, + # its disk and the source's bulge are told apart; ``galaxies`` (a + # Collection) and the parameter's tuple are not components and are dropped. + model = af.Collection( + galaxies=af.Collection( + lens=af.Model( + MockGalaxy, + bulge=af.Model(af.m.MockClassx2NoSuperScript), + disk=af.Model(af.m.MockClassx2NoSuperScript), + ), + source=af.Model( + MockGalaxy, bulge=af.Model(af.m.MockClassx2NoSuperScript) + ), + ) + ) + + assert model.component_paths == [ + ("lens", "bulge"), + ("lens", "bulge"), + ("lens", "disk"), + ("lens", "disk"), + ("source", "bulge"), + ("source", "bulge"), + ] + assert model.superscripts == [ + "lens.bulge", + "lens.bulge", + "lens.disk", + "lens.disk", + "source.bulge", + "source.bulge", + ] + assert model.parameter_indices_by_component == { + "lens": [0, 1, 2, 3], + "source": [4, 5], + } + + def test__superscripts__config_replaces_the_component_it_names(self): + # ``MockClassRelativeWidth=r`` in the notation config abbreviates that + # component's own name only; the galaxy's name stays. + model = af.Collection( + galaxy=af.Model(MockGalaxy, bulge=af.Model(af.m.MockClassRelativeWidth)) + ) + + assert model.superscripts == ["galaxy.r", "galaxy.r", "galaxy.r"] + assert ( + model.parameter_labels_with_superscripts[0] == r"one_label^{\rm galaxy.r}" + ) + + # A prior directly on the model has no named component and keeps the + # config entry for the model's class. + assert af.Model(af.m.MockClassRelativeWidth).superscripts == ["r", "r", "r"] + assert af.Model(af.m.MockClassRelativeWidth).parameter_indices_by_component == { + "model": [0, 1, 2] + } + + def test__superscripts__list_index_kept_only_when_priors_are_not_shared(self): + # A basis whose profiles share one set of priors: the index is one of + # many paths to the same prior, so it says nothing and is dropped. + profile_list = af.Collection( + [af.Model(af.m.MockClassx2NoSuperScript) for _ in range(3)] + ) + for profile in profile_list[1:]: + profile.one = profile_list[0].one + profile.two = profile_list[0].two + model = af.Collection( + galaxy=af.Model( + MockGalaxy, bulge=af.Model(MockBasis, profile_list=profile_list) + ) + ) + + assert model.component_paths == [("galaxy", "bulge"), ("galaxy", "bulge")] + assert model.superscripts == ["galaxy.bulge", "galaxy.bulge"] + + # Independent priors: the index is what tells the profiles apart. + model = af.Collection( + profiles=af.Collection( + [af.Model(af.m.MockClassx2NoSuperScript) for _ in range(2)] + ) + ) + + assert model.component_paths == [("0",), ("0",), ("1",), ("1",)] + assert model.superscripts == ["0", "0", "1", "1"] + assert model.parameter_indices_by_component == {"0": [0, 1], "1": [2, 3]} + def test_name_for_prior(self): mapper = af.ModelMapper(mock_class=af.m.MockClassx2) @@ -552,10 +737,12 @@ def test_replacing_priors_for_profile(self): result = mapper.mapper_from_prior_means([10, 5, 5]) assert isinstance( - result.mock_class.one_tuple.unique_prior_tuples[0][1], af.TruncatedGaussianPrior + result.mock_class.one_tuple.unique_prior_tuples[0][1], + af.TruncatedGaussianPrior, ) assert isinstance( - result.mock_class.one_tuple.unique_prior_tuples[1][1], af.TruncatedGaussianPrior + result.mock_class.one_tuple.unique_prior_tuples[1][1], + af.TruncatedGaussianPrior, ) assert isinstance(result.mock_class.two, af.TruncatedGaussianPrior) @@ -634,9 +821,7 @@ def test_prior_results_for_gaussian_tuples(self, list_prior_model): mapper = af.ModelMapper() mapper.list = list_prior_model - gaussian_mapper = mapper.mapper_from_prior_means( - [1, 2, 3, 4] - ) + gaussian_mapper = mapper.mapper_from_prior_means([1, 2, 3, 4]) assert len(gaussian_mapper.list) == 2 assert gaussian_mapper.list[0].one.mean == 1 @@ -654,9 +839,7 @@ def test_prior_results_for_gaussian_tuples__include_override_from_width_file( mapper = af.ModelMapper() mapper.list = list_prior_model - gaussian_mapper = mapper.mapper_from_prior_means( - [1, 2, 3, 4] - ) + gaussian_mapper = mapper.mapper_from_prior_means([1, 2, 3, 4]) assert len(gaussian_mapper.list) == 2 assert gaussian_mapper.list[0].one.mean == 1 diff --git a/test_autofit/non_linear/plot/test_nest_plotters.py b/test_autofit/non_linear/plot/test_nest_plotters.py index ea1d600be..9b9c88f1f 100644 --- a/test_autofit/non_linear/plot/test_nest_plotters.py +++ b/test_autofit/non_linear/plot/test_nest_plotters.py @@ -13,6 +13,20 @@ def __init__(self, labels): self.parameter_labels_with_superscripts_latex = labels self.total_free_parameters = len(labels) + def derived_parameters_from(self, parameter_array, weights=None): + # The derived set of this mock: the first two parameters become their sum. + from autofit.mapper.prior_model.derived import DerivedParameters + + return DerivedParameters( + names=["sum"] + ["p"] * (parameter_array.shape[1] - 2), + superscripts=[None] * (parameter_array.shape[1] - 1), + component_paths=[()] * (parameter_array.shape[1] - 1), + parameter_array=__import__("numpy").column_stack( + [parameter_array[:, 0] + parameter_array[:, 1], parameter_array[:, 2:]] + ), + derived_mask=[True] + [False] * (parameter_array.shape[1] - 2), + ) + class MockSamples: def __init__(self): @@ -111,3 +125,56 @@ def test__corner_anesthetic__labels_kwarg_is_reserved(samples): nest_plotters.corner_anesthetic(samples=samples, labels=["a", "b"]) assert "labels" in str(error.value) + + +def test__corner_anesthetic__parameter_indices_plot_that_subset(monkeypatch, routed): + # One corner plot per model component is made by passing the indices of its + # parameters: only those columns are plotted, with their own labels, and the + # figure is sized to the subset rather than the whole model. + from anesthetic.samples import NestedSamples + + rng = np.random.default_rng(2) + samples = MockSamples() + samples.model = MockModel(["$a$", "$b$", "$c$"]) + samples.parameter_lists = rng.normal(size=(60, 3)).tolist() + samples.weight_list = rng.random(60).tolist() + + seen = {} + + def fake_plot_2d(self, axes=None, **kwargs): + seen["labels"] = list(self.get_labels()) + seen["columns"] = self.shape[1] + + monkeypatch.setattr(NestedSamples, "plot_2d", fake_plot_2d) + + nest_plotters.corner_anesthetic(samples=samples, parameter_indices=[0, 2]) + + assert seen["columns"] == 2 + assert seen["labels"] == ["$a$", "$c$"] + assert routed["axes"]["figsize"] == (8, 8) + + +def test__corner_anesthetic__derived_plots_the_derived_set(monkeypatch, routed): + from anesthetic.samples import NestedSamples + + rng = np.random.default_rng(3) + samples = MockSamples() + samples.model = MockModel(["$a$", "$b$", "$c$"]) + samples.parameter_lists = rng.normal(size=(60, 3)).tolist() + samples.weight_list = rng.random(60).tolist() + + seen = {} + + def fake_plot_2d(self, axes=None, **kwargs): + seen["labels"] = list(self.get_labels()) + seen["first"] = self.to_numpy()[0, 0] + + monkeypatch.setattr(NestedSamples, "plot_2d", fake_plot_2d) + + nest_plotters.corner_anesthetic(samples=samples, derived=True) + + # Two parameters became one, labelled from the derived set's own names, + # and the figure is sized to the derived set. + assert seen["labels"] == ["$s$", "$p$"] + assert seen["first"] == pytest.approx(sum(samples.parameter_lists[0][:2])) + assert routed["axes"]["figsize"] == (8, 8) diff --git a/test_autofit/non_linear/search/test_family_bases.py b/test_autofit/non_linear/search/test_family_bases.py index d67df4c57..7c9e5734b 100644 --- a/test_autofit/non_linear/search/test_family_bases.py +++ b/test_autofit/non_linear/search/test_family_bases.py @@ -128,9 +128,7 @@ def test_smc_is_weighted_and_takes_no_auto_correlation_settings(): def test_old_smc_search_json_with_auto_correlation_settings_loads(caplog): - golden = json.loads( - (Path(__file__).parent / "seed_golden.json").read_text() - ) + golden = json.loads((Path(__file__).parent / "seed_golden.json").read_text()) old = golden["SMC"]["main_search_json"] assert "auto_correlation_settings" in old["arguments"] @@ -162,13 +160,19 @@ def test_old_smc_search_json_with_auto_correlation_settings_loads(caplog): @pytest.mark.parametrize("entry", searches_under_test(), ids=lambda e: e.name) def test_samples_class_path_unchanged(entry): - assert get_class_path(entry.resolve().samples_cls) == SAMPLES_CLASS_PATHS[entry.name] + assert ( + get_class_path(entry.resolve().samples_cls) == SAMPLES_CLASS_PATHS[entry.name] + ) @pytest.mark.parametrize( "cls, kind", - [(af.Emcee, posterior_kind.CHAIN), (af.SMC, posterior_kind.WEIGHTED), - (af.Nautilus, posterior_kind.WEIGHTED), (af.BFGS, posterior_kind.POINT)], + [ + (af.Emcee, posterior_kind.CHAIN), + (af.SMC, posterior_kind.WEIGHTED), + (af.Nautilus, posterior_kind.WEIGHTED), + (af.BFGS, posterior_kind.POINT), + ], ) def test_plot_results_dispatches_on_posterior_kind(cls, kind, monkeypatch): calls = [] @@ -215,7 +219,23 @@ def _smc_positional_prefix(): # name, path_prefix, unique_tag, num_particles, kernel, num_mcmc_steps, # num_integration_steps, target_ess, step_size, whiten_inflate, max_smc_steps, # batch_size, seed, initializer, inverse_mass_matrix - return (None, None, None, 256, "mala", 5, 8, 0.5, None, 2.0, 200, 0, None, None, None) + return ( + None, + None, + None, + 256, + "mala", + 5, + 8, + 0.5, + None, + 2.0, + 200, + 0, + None, + None, + None, + ) def test_smc_old_positional_auto_correlation_slot_binds_as_before(): @@ -248,3 +268,158 @@ def test_smc_keyword_construction_does_not_warn(): assert search.iterations_per_quick_update == 3 assert search.silence is True + + +class _MockGalaxy: + def __init__(self, light=None): + self.light = light + + +class _MockShear: + derived_parameters = { + ("gamma_1", "gamma_2"): lambda gamma_1, gamma_2, **kwargs: { + "magnitude": (gamma_1**2 + gamma_2**2) ** 0.5 + } + } + + def __init__(self, gamma_1=0.0, gamma_2=0.0): + self.gamma_1 = gamma_1 + self.gamma_2 = gamma_2 + + +def _lens_like_model(): + return af.Collection( + galaxies=af.Collection( + lens=af.Model(_MockGalaxy, light=af.Model(af.m.MockClassx2NoSuperScript)), + source=af.Model(_MockGalaxy, light=af.Model(af.m.MockClassx2NoSuperScript)), + ) + ) + + +def _weighted_plot_calls(model, monkeypatch, tmp_path): + from types import SimpleNamespace + import autofit.non_linear.plot as plot_module + from autofit.non_linear.search.posterior_kind import WeightedDefaults + + calls = [] + monkeypatch.setattr( + plot_module, "corner_anesthetic", lambda **kwargs: calls.append(kwargs) + ) + search = SimpleNamespace(paths=SimpleNamespace(image_path=tmp_path)) + samples = SimpleNamespace( + model=model, parameter_lists=[[0.1] * model.prior_count] * 3 + ) + WeightedDefaults().plot_results(search=search, samples=samples) + return calls + + +def test_weighted_plot_results_one_corner_per_component(monkeypatch, tmp_path): + # The full corner plot of a many-parameter model is too dense to read, so + # each top-level component (each galaxy here) also gets its own. + calls = _weighted_plot_calls(_lens_like_model(), monkeypatch, tmp_path) + + assert [call.get("filename", "corner_anesthetic") for call in calls] == [ + "corner_anesthetic", + "corner_anesthetic_lens", + "corner_anesthetic_source", + ] + assert "parameter_indices" not in calls[0] + assert calls[1]["parameter_indices"] == [0, 1] + assert calls[2]["parameter_indices"] == [2, 3] + + +def test_weighted_plot_results_single_component_has_no_duplicate_corner( + monkeypatch, tmp_path +): + # One component's corner plot would repeat the full one. + calls = _weighted_plot_calls( + af.Model(af.m.MockClassx2NoSuperScript), monkeypatch, tmp_path + ) + + assert [call.get("filename", "corner_anesthetic") for call in calls] == [ + "corner_anesthetic" + ] + + +def test_weighted_plot_results_components_key_missing_from_config_defaults_on( + monkeypatch, tmp_path +): + # A workspace config written before the per-component plots existed does + # not mention them; they default on rather than raising KeyError. + from autofit.non_linear.search.posterior_kind import WeightedDefaults + + real_should_plot = WeightedDefaults.should_plot + + def should_plot(self, name, default=None): + if name == "corner_anesthetic_components": + if default is None: + raise KeyError(name) + return default + return real_should_plot(self, name, default) + + monkeypatch.setattr(WeightedDefaults, "should_plot", should_plot) + + calls = _weighted_plot_calls(_lens_like_model(), monkeypatch, tmp_path) + + assert len(calls) == 3 + + +def test_weighted_plot_results_derived_corner_only_when_a_component_declares_one( + monkeypatch, tmp_path +): + # Nothing to derive: the derived plot would repeat the plain one, so none. + calls = _weighted_plot_calls(_lens_like_model(), monkeypatch, tmp_path) + assert not any("derived" in call.get("filename", "") for call in calls) + + # A shear declares its magnitude: a derived plot, and one per component + # since the per-component switch is on too. + model = af.Collection( + galaxies=af.Collection( + lens=af.Model( + _MockGalaxy, + light=af.Model( + _MockShear, + gamma_1=af.UniformPrior(-1.0, 1.0), + gamma_2=af.UniformPrior(-1.0, 1.0), + ), + ), + source=af.Model(_MockGalaxy, light=af.Model(af.m.MockClassx2NoSuperScript)), + ) + ) + calls = _weighted_plot_calls(model, monkeypatch, tmp_path) + + derived_calls = [call for call in calls if call.get("derived")] + assert [call["filename"] for call in derived_calls] == [ + "corner_anesthetic_derived", + "corner_anesthetic_derived_lens", + "corner_anesthetic_derived_source", + ] + assert derived_calls[1]["parameter_indices"] == [0] # magnitude alone + assert derived_calls[2]["parameter_indices"] == [1, 2] + + +def test_weighted_plot_results_derived_switch_is_independent(monkeypatch, tmp_path): + # Derived on, the other two off: the derived plot is the only corner plot. + from autofit.non_linear.search.posterior_kind import WeightedDefaults + + monkeypatch.setattr( + WeightedDefaults, + "should_plot", + lambda self, name, default=None: name == "corner_anesthetic_derived", + ) + model = af.Collection( + lens=af.Model( + _MockGalaxy, + light=af.Model( + _MockShear, + gamma_1=af.UniformPrior(-1.0, 1.0), + gamma_2=af.UniformPrior(-1.0, 1.0), + ), + ) + ) + + calls = _weighted_plot_calls(model, monkeypatch, tmp_path) + + assert [call.get("filename", "corner_anesthetic") for call in calls] == [ + "corner_anesthetic_derived" + ] From 43dcf0f65d7408478c219a4d5996bf8e8919d9f7 Mon Sep 17 00:00:00 2001 From: samlange04 Date: Sat, 17 Oct 2026 21:45:12 +0800 Subject: [PATCH 3/9] config: derived-parameter corner plots off by default The conversions and a second set of anesthetic figures take a while on a large sample set, so `nest.corner_anesthetic_derived` ships false and a user opts in. Co-Authored-By: Claude Fable 5.1 --- autofit/config/visualize/plots_search.yaml | 2 +- test_autofit/non_linear/search/test_family_bases.py | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/autofit/config/visualize/plots_search.yaml b/autofit/config/visualize/plots_search.yaml index 4ef39e568..52e6846c0 100644 --- a/autofit/config/visualize/plots_search.yaml +++ b/autofit/config/visualize/plots_search.yaml @@ -1,7 +1,7 @@ nest: corner_anesthetic: true # Output corner figure (using anestetic) during a non-linear search fit? corner_anesthetic_components: true # Also output one corner figure per top-level model component (e.g. per galaxy), each named corner_anesthetic_? - corner_anesthetic_derived: true # Output corner figure(s) of the derived parameters (e.g. a shear's magnitude and angle rather than gamma_1 / gamma_2), named corner_anesthetic_derived[_]? Independent of the two above. + corner_anesthetic_derived: false # Output corner figure(s) of the derived parameters (e.g. a shear's magnitude and angle rather than gamma_1 / gamma_2), named corner_anesthetic_derived[_]? Independent of the two above. mcmc: corner_cornerpy: true # Output corner figure (using corner.py) during a non-linear search fit? mle: diff --git a/test_autofit/non_linear/search/test_family_bases.py b/test_autofit/non_linear/search/test_family_bases.py index 7c9e5734b..1e6f09233 100644 --- a/test_autofit/non_linear/search/test_family_bases.py +++ b/test_autofit/non_linear/search/test_family_bases.py @@ -367,6 +367,13 @@ def should_plot(self, name, default=None): def test_weighted_plot_results_derived_corner_only_when_a_component_declares_one( monkeypatch, tmp_path ): + from autofit.non_linear.search.posterior_kind import WeightedDefaults + + # The derived plots are off by default; every switch on for this test. + monkeypatch.setattr( + WeightedDefaults, "should_plot", lambda self, name, default=None: True + ) + # Nothing to derive: the derived plot would repeat the plain one, so none. calls = _weighted_plot_calls(_lens_like_model(), monkeypatch, tmp_path) assert not any("derived" in call.get("filename", "") for call in calls) From 587a75b32b11d08c1ade41cf8f7be783299f3755 Mon Sep 17 00:00:00 2001 From: samlange04 Date: Sat, 17 Oct 2026 21:55:03 +0800 Subject: [PATCH 4/9] superscripts are the component names alone; the class abbreviation only for a bare model The notation config's per-class abbreviation (`Gaussian: g`) no longer replaces a named component's name: every component is labelled by the path of names it was given in the model, so a shear reads `lens.shear`, a basis of Gaussians `lens.bulge`, and a collection of Gaussians `gaussian_0`, `gaussian_1` rather than `g`, `g`. The abbreviation still applies to a prior directly on a bare `Model`, which has no name of its own. Co-Authored-By: Claude Fable 5.1 --- autofit/mapper/prior_model/abstract.py | 54 ++++++------------- .../mapper/model/test_model_mapper.py | 53 +++++++----------- test_autofit/text/test_samples_text.py | 41 ++++++++++---- 3 files changed, 65 insertions(+), 83 deletions(-) diff --git a/autofit/mapper/prior_model/abstract.py b/autofit/mapper/prior_model/abstract.py index 360c842cd..97146fbff 100644 --- a/autofit/mapper/prior_model/abstract.py +++ b/autofit/mapper/prior_model/abstract.py @@ -2608,54 +2608,30 @@ def superscripts(self) -> List[str]: """ Returns a list of the model component superscripts for every parameter in a model. - The superscript is the dot-joined path of named components that own the - parameter (see ``component_paths``): a lens model with a lens galaxy and a - source galaxy labels the Gaussians of their light with ``lens.bulge`` and - ``source.bulge``, so every parameter of every component has a distinct - label however many components share a class. + The superscript is the dot-joined path of the names the components owning + the parameter were given in the model (see ``component_paths``): a lens + model with a lens galaxy and a source galaxy labels the Gaussians of their + light ``lens.bulge`` and ``source.bulge``, its shear ``lens.shear``, so every + parameter of every component has a distinct label however many components + share a class. For the example of a 1D Gaussian, if the model component name is `gaussian` three superscripts with this string (corresponding to the parameters `centre`, `normalization` and `sigma`) will be returned. - The name of any component whose class has an entry in the `notation/label.yaml` config - (`superscript:`) is replaced by that entry, so `ExternalShear=ext` gives `lens.ext` rather - than `lens.shear`; see the `superscripts_overwrite_via_config` property. A parameter with - no named component (a prior directly on the model) uses the entry for the model's own class. + A prior directly on the model (a bare ``Model(Gaussian)``) has no named + component; it uses the `notation/label.yaml` config's `superscript:` entry + for the model's class if there is one (`Gaussian: g`), else no superscript. + See the `superscripts_overwrite_via_config` property. This is used for displaying model results as text and for visualization. """ - superscripts = [] - - for pairs, superscript_overwrite in zip( - self._component_name_object_pairs, self.superscripts_overwrite_via_config - ): - if not pairs: - superscripts.append(superscript_overwrite or None) - continue - - superscripts.append( - ".".join( - self._superscript_for_component(name, obj) for name, obj in pairs - ) + return [ + ".".join(path) if path else (superscript_overwrite or None) + for path, superscript_overwrite in zip( + self.component_paths, self.superscripts_overwrite_via_config ) - - return superscripts - - @staticmethod - def _superscript_for_component(name: str, obj) -> str: - """ - The superscript for one named component: the config entry for its class if - there is one, else its name. A list index is never replaced, since every - element of the list has the same class. - """ - if name.isdigit(): - return name - cls = getattr(obj, "cls", type(obj)) - try: - return conf.instance["notation"]["label"]["superscript"][cls.__name__] - except KeyError: - return name + ] @property def superscripts_overwrite_via_config(self) -> List[str]: diff --git a/test_autofit/mapper/model/test_model_mapper.py b/test_autofit/mapper/model/test_model_mapper.py index 635e6bd04..f5259fcf0 100644 --- a/test_autofit/mapper/model/test_model_mapper.py +++ b/test_autofit/mapper/model/test_model_mapper.py @@ -122,11 +122,14 @@ def test__superscripts(self): mm.one = af.m.MockClassRelativeWidth mm.two = af.m.MockClassx2NoSuperScript - assert mm.superscripts == ["r", "r", "r", "two", "two"] + assert mm.superscripts == ["one", "one", "one", "two", "two"] model = af.Collection(group=mm) - assert model.superscripts == ["r", "r", "r", "two", "two"] + assert model.superscripts == ["one", "one", "one", "two", "two"] + + # The config's class abbreviation applies only where there is no name. + assert af.Model(af.m.MockClassRelativeWidth).superscripts == ["r", "r", "r"] def test__superscript_overwrite_via_config(self): mm = af.ModelMapper() @@ -151,17 +154,17 @@ def test__parameter_labels_with_superscripts_latex(self): mm.two = af.m.MockClassx2NoSuperScript assert mm.parameter_labels_with_superscripts == [ - r"one_label^{\rm r}", - r"two_label^{\rm r}", - r"three_label^{\rm r}", + r"one_label^{\rm one}", + r"two_label^{\rm one}", + r"three_label^{\rm one}", r"one_label^{\rm two}", r"two_label^{\rm two}", ] assert mm.parameter_labels_with_superscripts_latex == [ - r"$one_label^{\rm r}$", - r"$two_label^{\rm r}$", - r"$three_label^{\rm r}$", + r"$one_label^{\rm one}$", + r"$two_label^{\rm one}$", + r"$three_label^{\rm one}$", r"$one_label^{\rm two}$", r"$two_label^{\rm two}$", ] @@ -205,20 +208,21 @@ def test__superscripts__named_components_separate_like_classes(self): "source": [4, 5], } - def test__superscripts__config_replaces_the_component_it_names(self): - # ``MockClassRelativeWidth=r`` in the notation config abbreviates that - # component's own name only; the galaxy's name stays. + def test__superscripts__named_component_ignores_the_config_abbreviation(self): + # ``MockClassRelativeWidth=r`` in the notation config: a named component + # is labelled by its names regardless, so like components stay distinct. model = af.Collection( galaxy=af.Model(MockGalaxy, bulge=af.Model(af.m.MockClassRelativeWidth)) ) - assert model.superscripts == ["galaxy.r", "galaxy.r", "galaxy.r"] + assert model.superscripts == ["galaxy.bulge"] * 3 assert ( - model.parameter_labels_with_superscripts[0] == r"one_label^{\rm galaxy.r}" + model.parameter_labels_with_superscripts[0] + == r"one_label^{\rm galaxy.bulge}" ) - # A prior directly on the model has no named component and keeps the - # config entry for the model's class. + # A prior directly on the model has no name and keeps the config entry + # for the model's class. assert af.Model(af.m.MockClassRelativeWidth).superscripts == ["r", "r", "r"] assert af.Model(af.m.MockClassRelativeWidth).parameter_indices_by_component == { "model": [0, 1, 2] @@ -661,25 +665,6 @@ def test__superscripts__named_components_separate_like_classes(self): "source": [4, 5], } - def test__superscripts__config_replaces_the_component_it_names(self): - # ``MockClassRelativeWidth=r`` in the notation config abbreviates that - # component's own name only; the galaxy's name stays. - model = af.Collection( - galaxy=af.Model(MockGalaxy, bulge=af.Model(af.m.MockClassRelativeWidth)) - ) - - assert model.superscripts == ["galaxy.r", "galaxy.r", "galaxy.r"] - assert ( - model.parameter_labels_with_superscripts[0] == r"one_label^{\rm galaxy.r}" - ) - - # A prior directly on the model has no named component and keeps the - # config entry for the model's class. - assert af.Model(af.m.MockClassRelativeWidth).superscripts == ["r", "r", "r"] - assert af.Model(af.m.MockClassRelativeWidth).parameter_indices_by_component == { - "model": [0, 1, 2] - } - def test__superscripts__list_index_kept_only_when_priors_are_not_shared(self): # A basis whose profiles share one set of priors: the index is one of # many paths to the same prior, so it says nothing and is dropped. diff --git a/test_autofit/text/test_samples_text.py b/test_autofit/text/test_samples_text.py index e5e0421b2..cbe7ce074 100644 --- a/test_autofit/text/test_samples_text.py +++ b/test_autofit/text/test_samples_text.py @@ -29,7 +29,7 @@ def make_samples(model): log_likelihood_list=log_likelihood_list, log_prior_list=[0.0, 0.0], weight_list=log_likelihood_list, - model=model + model=model, ), ) @@ -44,13 +44,26 @@ def test__summary(samples): def test__latex(samples): latex_results_at_sigma = samples_text.latex(samples=samples, sigma=3.0) - assert r"one_label^{\rm{o}} = 1.00^{+0.20}_{-0.00} & " in latex_results_at_sigma - assert r"two_label^{\rm{o}} = 2.00^{+0.20}_{-0.00}" in latex_results_at_sigma + assert ( + r"one_label^{\rm{mock_class}} = 1.00^{+0.20}_{-0.00} & " + in latex_results_at_sigma + ) + assert ( + r"two_label^{\rm{mock_class}} = 2.00^{+0.20}_{-0.00}" in latex_results_at_sigma + ) - latex_results_at_sigma = samples_text.latex(samples=samples, sigma=3.0, include_quickmath=True) + latex_results_at_sigma = samples_text.latex( + samples=samples, sigma=3.0, include_quickmath=True + ) - assert r"$one_label^{\rm{o}} = 1.00^{+0.20}_{-0.00}$ & " in latex_results_at_sigma - assert r"$two_label^{\rm{o}} = 2.00^{+0.20}_{-0.00}$" in latex_results_at_sigma + assert ( + r"$one_label^{\rm{mock_class}} = 1.00^{+0.20}_{-0.00}$ & " + in latex_results_at_sigma + ) + assert ( + r"$two_label^{\rm{mock_class}} = 2.00^{+0.20}_{-0.00}$" + in latex_results_at_sigma + ) model = af.ModelMapper(mock_class=af.m.MockClassx2FormatExp) @@ -65,11 +78,19 @@ def test__latex(samples): log_likelihood_list=log_likelihood_list, log_prior_list=[0.0, 0.0], weight_list=log_likelihood_list, - model=model + model=model, ), ) - latex_results_at_sigma = samples_text.latex(samples=samples_exp, sigma=3.0, include_quickmath=True) + latex_results_at_sigma = samples_text.latex( + samples=samples_exp, sigma=3.0, include_quickmath=True + ) - assert r"$one_label^{\rm{o}} = 1.00^{+0.20}_{-0.00}$ & " in latex_results_at_sigma - assert r"$one_label^{\rm{o}} = 1.00^{+0.20}_{-0.00}$ & $2.00^{+0.00}_{-0.00} \times 10^{2}$" in latex_results_at_sigma \ No newline at end of file + assert ( + r"$one_label^{\rm{mock_class}} = 1.00^{+0.20}_{-0.00}$ & " + in latex_results_at_sigma + ) + assert ( + r"$one_label^{\rm{mock_class}} = 1.00^{+0.20}_{-0.00}$ & $2.00^{+0.00}_{-0.00} \times 10^{2}$" + in latex_results_at_sigma + ) From 7db4b9cf85713091a4065224d0364634c2dab79f Mon Sep 17 00:00:00 2001 From: samlange04 Date: Sun, 18 Oct 2026 15:30:27 +0800 Subject: [PATCH 5/9] superscripts three or more levels deep abbreviate every name after the first A parameter owned by a component three levels down, such as a source galaxy's pixelization regularization, was labelled with the full path `source.pixelization.regularization`, which runs into the neighbouring axis labels on a corner plot. `superscript_from_component_path` now keeps the first name whole (the galaxy or plane that distinguishes the components) and cuts every later name to three characters, so the label reads `source.pix.reg`. One- and two-level paths are unchanged. Also removes two superscript tests that were duplicated verbatim into a second test class. Co-Authored-By: Claude Fable 5.1 --- autofit/mapper/prior_model/abstract.py | 27 ++++- .../mapper/model/test_model_mapper.py | 111 ++++++------------ 2 files changed, 63 insertions(+), 75 deletions(-) diff --git a/autofit/mapper/prior_model/abstract.py b/autofit/mapper/prior_model/abstract.py index 97146fbff..21d44406d 100644 --- a/autofit/mapper/prior_model/abstract.py +++ b/autofit/mapper/prior_model/abstract.py @@ -165,6 +165,22 @@ def paths_to_tree(paths: List[Tuple[str, ...]], tree: Optional[dict] = None) -> return tree +def superscript_from_component_path(path: Tuple[str, ...]) -> str: + """ + The superscript of a parameter from the path of the named components owning it. + + Paths of one or two levels are joined with dots unchanged (``lens.bulge``). + From three levels deep the first name is kept whole and every later name is + cut to its first three characters, so ``("source", "pixelization", + "regularization")`` gives ``source.pix.reg``: the first level is the plane or + galaxy that distinguishes the components, and the rest only needs to stay + recognisable in the small type of a corner-plot axis. + """ + if len(path) < 3: + return ".".join(path) + return ".".join([path[0]] + [name[:3] for name in path[1:]]) + + class AbstractPriorModel(AbstractModel): """ Abstract model that maps a set of priors to a particular class. Must be @@ -2619,6 +2635,11 @@ def superscripts(self) -> List[str]: with this string (corresponding to the parameters `centre`, `normalization` and `sigma`) will be returned. + A path three or more levels deep keeps its first name whole and cuts every + later name to three characters, so ``source.pixelization.regularization`` + is labelled ``source.pix.reg`` and the label stays readable on a corner + plot (see ``superscript_from_component_path``). + A prior directly on the model (a bare ``Model(Gaussian)``) has no named component; it uses the `notation/label.yaml` config's `superscript:` entry for the model's class if there is one (`Gaussian: g`), else no superscript. @@ -2627,7 +2648,11 @@ def superscripts(self) -> List[str]: This is used for displaying model results as text and for visualization. """ return [ - ".".join(path) if path else (superscript_overwrite or None) + ( + superscript_from_component_path(path) + if path + else (superscript_overwrite or None) + ) for path, superscript_overwrite in zip( self.component_paths, self.superscripts_overwrite_via_config ) diff --git a/test_autofit/mapper/model/test_model_mapper.py b/test_autofit/mapper/model/test_model_mapper.py index f5259fcf0..b47806bd2 100644 --- a/test_autofit/mapper/model/test_model_mapper.py +++ b/test_autofit/mapper/model/test_model_mapper.py @@ -35,6 +35,11 @@ def __init__(self, profile_list=None): self.profile_list = profile_list +class MockPixelization: + def __init__(self, regularization=None): + self.regularization = regularization + + class TestRegression: def test_set_tuple_instance(self): mm = af.ModelMapper() @@ -228,6 +233,38 @@ def test__superscripts__named_component_ignores_the_config_abbreviation(self): "model": [0, 1, 2] } + def test__superscripts__three_levels_deep_abbreviates_all_but_the_first(self): + # source.pixelization.regularization would run into its neighbours on a + # corner-plot axis: the first level (the galaxy) stays whole and every + # later name is cut to three characters. + model = af.Collection( + source=af.Model( + MockGalaxy, + bulge=af.Model( + MockPixelization, + regularization=af.Model(af.m.MockClassx2NoSuperScript), + ), + ) + ) + model.source.pixelization = model.source.bulge + del model.source.bulge + + assert ( + model.component_paths == [("source", "pixelization", "regularization")] * 2 + ) + assert model.superscripts == ["source.pix.reg", "source.pix.reg"] + + from autofit.mapper.prior_model.abstract import ( + superscript_from_component_path, + ) + + assert superscript_from_component_path(("lens",)) == "lens" + assert superscript_from_component_path(("lens", "bulge")) == "lens.bulge" + assert ( + superscript_from_component_path(("a", "bc", "defg", "hijkl")) + == "a.bc.def.hij" + ) + def test__superscripts__list_index_kept_only_when_priors_are_not_shared(self): # A basis whose profiles share one set of priors: the index is one of # many paths to the same prior, so it says nothing and is dropped. @@ -626,80 +663,6 @@ def test_prior_prior_model_dict(self): == af.m.MockClassx2 ) - def test__superscripts__named_components_separate_like_classes(self): - # A lens-like model: two galaxies each holding components of one class. - # The superscript is the path of named components, so the lens's bulge, - # its disk and the source's bulge are told apart; ``galaxies`` (a - # Collection) and the parameter's tuple are not components and are dropped. - model = af.Collection( - galaxies=af.Collection( - lens=af.Model( - MockGalaxy, - bulge=af.Model(af.m.MockClassx2NoSuperScript), - disk=af.Model(af.m.MockClassx2NoSuperScript), - ), - source=af.Model( - MockGalaxy, bulge=af.Model(af.m.MockClassx2NoSuperScript) - ), - ) - ) - - assert model.component_paths == [ - ("lens", "bulge"), - ("lens", "bulge"), - ("lens", "disk"), - ("lens", "disk"), - ("source", "bulge"), - ("source", "bulge"), - ] - assert model.superscripts == [ - "lens.bulge", - "lens.bulge", - "lens.disk", - "lens.disk", - "source.bulge", - "source.bulge", - ] - assert model.parameter_indices_by_component == { - "lens": [0, 1, 2, 3], - "source": [4, 5], - } - - def test__superscripts__list_index_kept_only_when_priors_are_not_shared(self): - # A basis whose profiles share one set of priors: the index is one of - # many paths to the same prior, so it says nothing and is dropped. - profile_list = af.Collection( - [af.Model(af.m.MockClassx2NoSuperScript) for _ in range(3)] - ) - for profile in profile_list[1:]: - profile.one = profile_list[0].one - profile.two = profile_list[0].two - model = af.Collection( - galaxy=af.Model( - MockGalaxy, bulge=af.Model(MockBasis, profile_list=profile_list) - ) - ) - - assert model.component_paths == [("galaxy", "bulge"), ("galaxy", "bulge")] - assert model.superscripts == ["galaxy.bulge", "galaxy.bulge"] - - # Independent priors: the index is what tells the profiles apart. - model = af.Collection( - profiles=af.Collection( - [af.Model(af.m.MockClassx2NoSuperScript) for _ in range(2)] - ) - ) - - assert model.component_paths == [("0",), ("0",), ("1",), ("1",)] - assert model.superscripts == ["0", "0", "1", "1"] - assert model.parameter_indices_by_component == {"0": [0, 1], "1": [2, 3]} - - def test_name_for_prior(self): - mapper = af.ModelMapper(mock_class=af.m.MockClassx2) - - assert mapper.name_for_prior(mapper.priors[0]) == "mock_class_one" - assert mapper.name_for_prior(mapper.priors[1]) == "mock_class_two" - class TestPriorReplacement: def test_prior_replacement(self): From 5d9ba5167e716ac783df77d6193050eb2fedef75 Mon Sep 17 00:00:00 2001 From: samlange04 Date: Sun, 18 Oct 2026 15:53:09 +0800 Subject: [PATCH 6/9] Derived parameters are latent parameters: latent.csv, after-fit plots PyAutoFit already calls a quantity computed from the model but not sampled a latent variable, so the component-declared conversions (a shear's magnitude and angle for gamma_1 / gamma_2) take that name: `latent_parameters` on the class, `autofit/mapper/prior_model/latent_parameters.py` (`LatentParameters`, `latent_parameters_from`), `corner_anesthetic(latent=True)`, config `corner_anesthetic_latent` and files `corner_anesthetic_latent[_].png`. They now join the analysis's latents in the latent output: `latent_samples_from` appends them under their model path (`galaxies.lens.shear.magnitude`) to `latent/samples.csv`, `latent.results` and `latent_summary.json`, with or without analysis-defined latents (`LatentParameters.paths`, `latent_items`). The latent corner plots follow the same rule as that output rather than the `iterations_per_full_update` cadence: a `plot_latent_results` hook on the search and `PosteriorDefaults`, which `SearchUpdater.visualize` calls once the fit completes and during it only if `output.yaml`'s `latent_during_fit` is on. Per-component latent plots are made only for components with a latent parameter (`parameter_indices_by_latent_component`), and not at all for a single-component model, so no plot repeats another. Co-Authored-By: Claude Fable 5.1 --- autofit/__init__.py | 2 +- autofit/config/output.yaml | 2 +- autofit/config/visualize/plots_search.yaml | 2 +- autofit/mapper/prior_model/abstract.py | 22 +-- .../{derived.py => latent_parameters.py} | 117 +++++++++++----- autofit/non_linear/analysis/latent.py | 81 ++++++++--- autofit/non_linear/plot/nest_plotters.py | 20 +-- autofit/non_linear/search/posterior_kind.py | 97 +++++++++----- autofit/non_linear/search/updater.py | 29 ++-- autofit/non_linear/search/updates.py | 16 +++ test_autofit/analysis/test_latent.py | 104 ++++++++++++++- ...t_derived.py => test_latent_parameters.py} | 102 +++++++++----- .../non_linear/plot/test_nest_plotters.py | 18 +-- .../non_linear/search/test_family_bases.py | 126 ++++++++++++++---- .../non_linear/search/test_updater.py | 77 +++++++++++ 15 files changed, 624 insertions(+), 191 deletions(-) rename autofit/mapper/prior_model/{derived.py => latent_parameters.py} (70%) rename test_autofit/mapper/model/{test_derived.py => test_latent_parameters.py} (50%) diff --git a/autofit/__init__.py b/autofit/__init__.py index 2257d87f6..add6579db 100644 --- a/autofit/__init__.py +++ b/autofit/__init__.py @@ -47,7 +47,7 @@ from .mapper.model_mapper import ModelMapper from .mapper.model_mapper import ModelMapper as Mapper from .mapper.model_object import ModelObject -from .mapper.prior_model.derived import Periodic +from .mapper.prior_model.latent_parameters import Periodic from .mapper.operator import DiagonalMatrix from .mapper.prior.constant import Constant from .mapper.prior.arithmetic.assertion import ComparisonAssertion diff --git a/autofit/config/output.yaml b/autofit/config/output.yaml index 19f16e975..cb94e2567 100644 --- a/autofit/config/output.yaml +++ b/autofit/config/output.yaml @@ -86,7 +86,7 @@ start_point: true # manually after completing a successful model-fit. This will save computational run time by not computing latent # variables during a any model-fit which is unsuccessful. -latent_during_fit: false # Whether to output the `latent.csv`, `latent.results` and `latent_summary.json` files during the fit when it performs on-the-fly output. +latent_during_fit: false # Whether to output the `latent.csv`, `latent.results` and `latent_summary.json` files during the fit when it performs on-the-fly output. Also whether the latent corner plot (`visualize/plots_search.yaml` -> `corner_anesthetic_latent`) is made during the fit; it is always made once the fit completes. latent_after_fit: true # If `latent_during_fit` is False, whether to output the `latent.csv`, `latent.results` and `latent_summary.json` files after the fit is complete. latent_draw_via_pdf : true # Whether to draw latent variable values via the PDF of every sample, which uses fewer samples to estimate latent variable errors. If False, latent variable values are drawn from every sample. latent_draw_via_pdf_size : 100 # The number of samples drawn to estimate latent variable errors if `latent_draw_via_pdf` is True. diff --git a/autofit/config/visualize/plots_search.yaml b/autofit/config/visualize/plots_search.yaml index 52e6846c0..570c38721 100644 --- a/autofit/config/visualize/plots_search.yaml +++ b/autofit/config/visualize/plots_search.yaml @@ -1,7 +1,7 @@ nest: corner_anesthetic: true # Output corner figure (using anestetic) during a non-linear search fit? corner_anesthetic_components: true # Also output one corner figure per top-level model component (e.g. per galaxy), each named corner_anesthetic_? - corner_anesthetic_derived: false # Output corner figure(s) of the derived parameters (e.g. a shear's magnitude and angle rather than gamma_1 / gamma_2), named corner_anesthetic_derived[_]? Independent of the two above. + corner_anesthetic_latent: false # Output corner figure(s) of the latent parameters (e.g. a shear's magnitude and angle rather than gamma_1 / gamma_2), named corner_anesthetic_latent[_], per component only where one has a latent parameter? Independent of the two above. Made after the fit like latent.csv (during it only if output.yaml's latent_during_fit is on). mcmc: corner_cornerpy: true # Output corner figure (using corner.py) during a non-linear search fit? mle: diff --git a/autofit/mapper/prior_model/abstract.py b/autofit/mapper/prior_model/abstract.py index 21d44406d..d6e88191d 100644 --- a/autofit/mapper/prior_model/abstract.py +++ b/autofit/mapper/prior_model/abstract.py @@ -284,8 +284,8 @@ def gathered_assertions(self) -> list: seen.add(id(model)) assertions.extend(getattr(model, "_assertions", [])) - # An assertion's operand can itself be a model carrying assertions -- `derived = p + 1` is - # a `CompoundPrior`, and `derived.add_assertion(...)` attaches to it. On numpy those fire + # An assertion's operand can itself be a model carrying assertions -- `latent = p + 1` is + # a `CompoundPrior`, and `latent.add_assertion(...)` attaches to it. On numpy those fire # when the operand is realised, so they are part of the model's contract; the tree walk # cannot see them, because the operand hangs off the assertion rather than off the model. collected = {id(assertion) for assertion in assertions} @@ -2553,31 +2553,31 @@ def _prior_owner_and_leaf_names(self) -> List[Tuple[object, str]]: owners.append((owner, path[-1])) return owners - def derived_parameters_from( + def latent_parameters_from( self, parameter_array, weights=None - ) -> "DerivedParameters": + ) -> "LatentParameters": """ The parameters of this model after each component's declared conversions - (its ``derived_parameters`` class attribute, e.g. shear components to a + (its ``latent_parameters`` class attribute, e.g. shear components to a magnitude and angle) are applied to an array of samples; see - ``autofit.mapper.prior_model.derived``. + ``autofit.mapper.prior_model.latent_parameters``. Parameters ---------- parameter_array Samples of the model's free parameters, shape ``(n_samples, prior_count)``. weights - The weight of each sample, which centres a periodic derived parameter + The weight of each sample, which centres a periodic latent parameter (an angle) on its posterior; equal by default. """ - from autofit.mapper.prior_model.derived import derived_parameters_from + from autofit.mapper.prior_model.latent_parameters import latent_parameters_from - return derived_parameters_from(self, parameter_array, weights=weights) + return latent_parameters_from(self, parameter_array, weights=weights) @property - def has_derived_parameters(self) -> bool: + def has_latent_parameters(self) -> bool: """Whether any component of this model declares a conversion that applies to it.""" - return self.derived_parameters_from(np.zeros((1, self.prior_count))).has_derived + return self.latent_parameters_from(np.zeros((1, self.prior_count))).has_latent @property def component_paths(self) -> List[Path]: diff --git a/autofit/mapper/prior_model/derived.py b/autofit/mapper/prior_model/latent_parameters.py similarity index 70% rename from autofit/mapper/prior_model/derived.py rename to autofit/mapper/prior_model/latent_parameters.py index de7556a33..96594c36e 100644 --- a/autofit/mapper/prior_model/derived.py +++ b/autofit/mapper/prior_model/latent_parameters.py @@ -1,5 +1,5 @@ """ -Derived parameters: a model component's own re-parameterisation of some of its +Latent parameters: a model component's own re-parameterisation of some of its free parameters, for plotting and reporting. Many components are *sampled* in one parameterisation and *read* in another: a @@ -9,20 +9,20 @@ class declares the conversion as a class attribute:: class ExternalShear: - derived_parameters = { + latent_parameters = { ("gamma_1", "gamma_2"): shear_magnitude_and_angle_dict_from, } keyed by the names of the free parameters it replaces and valued by a function that takes every parameter of the component by name (the free ones as arrays -over the samples, the fixed ones as floats) and returns a ``dict`` of derived +over the samples, the fixed ones as floats) and returns a ``dict`` of latent name to array. The declarations of a class's bases are inherited, so a subclass adds to them rather than restating them. -``DerivedParameters`` applies those declarations to an array of samples: the -replaced parameters go, the derived ones take their place (at the position of +``LatentParameters`` applies those declarations to an array of samples: the +replaced parameters go, the latent ones take their place (at the position of the first replaced one, in model order), everything else passes through -unchanged, and each derived parameter carries the superscript of the component +unchanged, and each latent parameter carries the superscript of the component it came from. A declaration whose replaced parameters are not all free in this model is skipped, since there is nothing to convert. @@ -41,19 +41,19 @@ class ExternalShear: from autofit.text import formatter as frm -DerivedFunction = Callable[..., Dict[str, np.ndarray]] +LatentFunction = Callable[..., Dict[str, np.ndarray]] class Periodic: def __init__(self, values, period: float): """ - A derived parameter that is periodic (an angle), returned by a conversion so + A latent parameter that is periodic (an angle), returned by a conversion so the samples are recentred on their circular mean; see the module docstring. Parameters ---------- values - The derived values over the samples, in whatever range the conversion gives. + The latent values over the samples, in whatever range the conversion gives. period The period, e.g. 180 for a position angle, ``360 / m`` for a multipole phase. """ @@ -84,25 +84,26 @@ def recentred(self, weights=None) -> np.ndarray: return (values - mean + half) % self.period + mean - half -def derived_parameters_for_class(cls) -> Dict[Tuple[str, ...], DerivedFunction]: +def latent_parameters_for_class(cls) -> Dict[Tuple[str, ...], LatentFunction]: """ - The derived-parameter declarations of a class and all of its bases, the most - derived class last so it can override an entry of a base. + The latent-parameter declarations of a class and all of its bases, the most + latent class last so it can override an entry of a base. """ declarations = {} for base in reversed(getattr(cls, "__mro__", (cls,))): - declarations.update(base.__dict__.get("derived_parameters", {}) or {}) + declarations.update(base.__dict__.get("latent_parameters", {}) or {}) return declarations -class DerivedParameters: +class LatentParameters: def __init__( self, names: List[str], superscripts: List[Optional[str]], component_paths: List[Tuple[str, ...]], parameter_array: np.ndarray, - derived_mask: List[bool], + latent_mask: List[bool], + paths: Optional[List[Tuple[str, ...]]] = None, ): """ Parameters of a model after each component's declared conversions are @@ -111,26 +112,31 @@ def __init__( Parameters ---------- names - The name of every parameter of the derived set, in order. + The name of every parameter of the latent set, in order. superscripts The superscript of each, that of the component it belongs to. component_paths The named-component path of each (see ``AbstractPriorModel.component_paths``). parameter_array - The samples of the derived set, shape ``(n_samples, len(names))``. - derived_mask - Whether each parameter was derived (``True``) or passed through. + The samples of the latent set, shape ``(n_samples, len(names))``. + latent_mask + Whether each parameter was latent (``True``) or passed through. + paths + The full model path of each (``galaxies.lens.shear.magnitude``), a + latent one under the component that declared it; the key it has in + the latent output (``latent.csv``). """ self.names = names self.superscripts = superscripts self.component_paths = component_paths self.parameter_array = parameter_array - self.derived_mask = derived_mask + self.latent_mask = latent_mask + self.paths = paths @property - def has_derived(self) -> bool: + def has_latent(self) -> bool: """Whether any declaration was applied, so the set differs from the model's own.""" - return any(self.derived_mask) + return any(self.latent_mask) @property def parameter_labels(self) -> List[str]: @@ -152,12 +158,39 @@ def parameter_labels_with_superscripts_latex(self) -> List[str]: @property def parameter_indices_by_component(self) -> Dict[str, List[int]]: - """As ``AbstractPriorModel.parameter_indices_by_component``, over the derived set.""" + """As ``AbstractPriorModel.parameter_indices_by_component``, over the latent set.""" groups = {} for i, path in enumerate(self.component_paths): groups.setdefault(path[0] if path else "model", []).append(i) return groups + @property + def parameter_indices_by_latent_component(self) -> Dict[str, List[int]]: + """ + ``parameter_indices_by_component`` restricted to the components with at + least one latent parameter: the plot of a component without one would + repeat its plain corner plot. + """ + return { + name: indices + for name, indices in self.parameter_indices_by_component.items() + if any(self.latent_mask[i] for i in indices) + } + + @property + def latent_items(self) -> List[Tuple[Tuple[str, ...], np.ndarray]]: + """ + The latent parameters alone, as ``(path, samples)`` pairs, which is what + the latent output (``latent.csv``) takes from the model. + """ + if self.paths is None: + raise ValueError("This LatentParameters was built without paths.") + return [ + (path, self.parameter_array[:, i]) + for i, (path, is_latent) in enumerate(zip(self.paths, self.latent_mask)) + if is_latent + ] + def _flat_fixed_values(owner) -> Dict[str, float]: """ @@ -185,18 +218,30 @@ def _flat_fixed_values(owner) -> Dict[str, float]: return values -def derived_parameters_from( +def _owner_path(prior_path, leaf: str) -> Tuple[str, ...]: + """ + The model path of the component owning a prior, from the prior's full path: + the leaf is stripped, and so is the tuple it sits in (``centre.centre_0``). + """ + prior_path = tuple(prior_path) + owner = prior_path[:-1] + if owner and leaf.startswith(f"{owner[-1]}_"): + owner = owner[:-1] + return owner + + +def latent_parameters_from( model, parameter_array: np.ndarray, weights=None -) -> DerivedParameters: +) -> LatentParameters: """ Apply every component's declared conversions to an array of samples of the model; see the module docstring. Called through - ``AbstractPriorModel.derived_parameters_from``. + ``AbstractPriorModel.latent_parameters_from``. Parameters ---------- weights - The weight of each sample, used to centre a ``Periodic`` derived parameter + The weight of each sample, used to centre a ``Periodic`` latent parameter on its posterior rather than on the prior volume; equal by default. """ parameter_array = np.asarray(parameter_array) @@ -206,6 +251,7 @@ def derived_parameters_from( names = model.parameter_names superscripts = model.superscripts component_paths = model.component_paths + paths = model.paths # Which free parameters each component owns, by leaf name -> model index. indices_by_owner = {} @@ -220,7 +266,7 @@ def derived_parameters_from( cls = getattr(owner, "cls", None) if cls is None: continue - for replaced, function in derived_parameters_for_class(cls).items(): + for replaced, function in latent_parameters_for_class(cls).items(): if not all(name in free for name in replaced): continue if any(free[name] in consumed for name in replaced): @@ -229,10 +275,11 @@ def derived_parameters_from( values.update( {name: parameter_array[:, index] for name, index in free.items()} ) - derived = function(**values) + latent = function(**values) first = min(free[name] for name in replaced) insert_at[first] = [ ( + _owner_path(paths[first], owners[first][1]) + (name,), name, np.broadcast_to( ( @@ -243,17 +290,19 @@ def derived_parameters_from( (n_samples,), ), ) - for name, value in derived.items() + for name, value in latent.items() ] consumed.update(free[name] for name in replaced) out_names, out_superscripts, out_paths, out_columns, out_mask = [], [], [], [], [] + out_full_paths = [] for i in range(len(names)): if i in insert_at: - for name, column in insert_at[i]: + for full_path, name, column in insert_at[i]: out_names.append(name) out_superscripts.append(superscripts[i]) out_paths.append(component_paths[i]) + out_full_paths.append(full_path) out_columns.append(column) out_mask.append(True) if i in consumed: @@ -261,15 +310,17 @@ def derived_parameters_from( out_names.append(names[i]) out_superscripts.append(superscripts[i]) out_paths.append(component_paths[i]) + out_full_paths.append(tuple(paths[i])) out_columns.append(parameter_array[:, i]) out_mask.append(False) - return DerivedParameters( + return LatentParameters( names=out_names, superscripts=out_superscripts, component_paths=out_paths, parameter_array=( np.column_stack(out_columns) if out_columns else parameter_array ), - derived_mask=out_mask, + latent_mask=out_mask, + paths=out_full_paths, ) diff --git a/autofit/non_linear/analysis/latent.py b/autofit/non_linear/analysis/latent.py index dfecd9d7a..147749fd7 100644 --- a/autofit/non_linear/analysis/latent.py +++ b/autofit/non_linear/analysis/latent.py @@ -20,6 +20,7 @@ ``Analysis.LATENT_BATCH_MODE``, so analyses that still override those keep working unchanged. New code should subclass :class:`Latent` instead. """ + import functools import logging import time @@ -74,6 +75,30 @@ def variables(analysis, parameters, model): return analysis.compute_latent_variables(parameters, model) +def _model_latent_parameters(samples: Samples): + """ + The model's declared latent parameters over the samples, recentred on the + posterior where periodic, or ``None`` when no component declares any (or + the samples carry no model that can say). + """ + model = getattr(samples, "model", None) + if model is None or not hasattr(model, "latent_parameters_from"): + return None + try: + parameter_array = np.asarray(samples.parameter_lists) + latent = model.latent_parameters_from( + parameter_array, weights=samples.weight_list + ) + except Exception: + logger.warning( + "compute_latent_samples: the model's latent parameters could not be " + "computed and are left out of the latent output.", + exc_info=True, + ) + return None + return latent if latent.has_latent else None + + def latent_samples_from( analysis, samples: Samples, batch_size: Optional[int] = None ) -> Optional[Samples]: @@ -132,7 +157,14 @@ def latent_samples_from( ) keys = latent.keys(analysis) - if not keys: + # The model's own latent parameters (a shear's magnitude and angle for its + # gamma_1 / gamma_2, declared by the component class; see + # ``autofit/mapper/prior_model/latent_parameters.py``) join the analysis's + # latents in the same output. They are vectorised over the samples and need + # no instance, so they are added after the per-sample loop below. + model_latent = _model_latent_parameters(samples) + + if not keys and model_latent is None: return None try: @@ -159,6 +191,7 @@ def _record_failure(): if analysis.is_jax: import jax import jax.numpy as jnp + if batch_mode == "vmap": # vmap traces `variables` once for the whole batch, so a # per-sample try/except is not possible here — latent functions @@ -193,14 +226,13 @@ def batched_compute_latent(parameters_batch): # sample. Transpose to a tuple of N batched arrays so the # downstream `jnp.stack(latent_values_batch, axis=-1)` # works identically to the vmap path. - sample_results = [ - _safe_jitted(p) for p in parameters_batch - ] + sample_results = [_safe_jitted(p) for p in parameters_batch] n_latents = len(sample_results[0]) return tuple( jnp.stack([s[i] for s in sample_results]) for i in range(n_latents) ) + else: raise ValueError( f"Unknown LATENT_BATCH_MODE={batch_mode!r}; expected 'vmap' or 'jit'." @@ -240,17 +272,22 @@ def batched_compute_latent(x): # retained sample shares one identical key set. all_values = [] all_samples = [] - for i in range(0, len(parameter_array), batch_size): + # No analysis latents: nothing is evaluated per sample, every sample is + # kept, and the model's latent parameters alone are written below. + for i in range(0, len(parameter_array) if keys else 0, batch_size): - batch = parameter_array[i:i + batch_size] - batch_samples = samples.sample_list[i:i + batch_size] + batch = parameter_array[i : i + batch_size] + batch_samples = samples.sample_list[i : i + batch_size] # batched JAX call on this chunk latent_values_batch = batched_compute_latent(batch) if analysis.is_jax: import jax.numpy as jnp - latent_values_batch = jnp.stack(latent_values_batch, axis=-1) # (batch, n_latents) + + latent_values_batch = jnp.stack( + latent_values_batch, axis=-1 + ) # (batch, n_latents) # Unify to NumPy so the global masking below is a single code path # for both backends (latent values are scalars, host transfer is @@ -263,7 +300,10 @@ def batched_compute_latent(x): all_values.append(latent_values_batch) all_samples.extend(batch_samples) - if all_values: + if not keys: + all_samples = list(samples.sample_list) + all_values = np.empty((len(all_samples), 0)) + elif all_values: all_values = np.concatenate(all_values, axis=0) else: all_values = np.empty((0, len(keys))) @@ -275,9 +315,7 @@ def batched_compute_latent(x): # 1. Drop a latent column that is non-finite for EVERY sample # (genuinely degenerate, e.g. a µJy latent with no magzero). kept_idx = [ - i - for i in range(all_values.shape[1]) - if np.isfinite(all_values[:, i]).any() + i for i in range(all_values.shape[1]) if np.isfinite(all_values[:, i]).any() ] # 2. Keep samples that are finite across all currently-kept latents. @@ -294,7 +332,9 @@ def batched_compute_latent(x): nan_counts = (~np.isfinite(all_values[:, kept_idx])).sum(axis=0) kept_idx.pop(int(np.argmax(nan_counts))) - print(f"Time to compute latent variables: {time.time() - start_latent} seconds for {len(samples)} samples.") + print( + f"Time to compute latent variables: {time.time() - start_latent} seconds for {len(samples)} samples." + ) n_samples = len(parameter_array) @@ -323,7 +363,7 @@ def _warn_no_latents(): "after masking; skipping latent output." ) - if not kept_idx: + if not kept_idx and model_latent is None: _warn_no_latents() return None @@ -337,14 +377,23 @@ def _warn_no_latents(): _warn_no_latents() return None + model_items = ( + [(path, column[row_mask]) for path, column in model_latent.latent_items] + if model_latent is not None + else [] + ) + latent_samples = [ Sample( log_likelihood=sample.log_likelihood, log_prior=sample.log_prior, weight=sample.weight, - kwargs={k: float(v) for k, v in zip(kept_keys, values)}, + kwargs={ + **{k: float(v) for k, v in zip(kept_keys, values)}, + **{path: float(column[j]) for path, column in model_items}, + }, ) - for sample, values in zip(kept_samples, kept_values) + for j, (sample, values) in enumerate(zip(kept_samples, kept_values)) ] return type(samples)( diff --git a/autofit/non_linear/plot/nest_plotters.py b/autofit/non_linear/plot/nest_plotters.py index 761dd24dc..840a4a116 100644 --- a/autofit/non_linear/plot/nest_plotters.py +++ b/autofit/non_linear/plot/nest_plotters.py @@ -20,7 +20,7 @@ def corner_anesthetic( filename="corner_anesthetic", format="show", parameter_indices=None, - derived=False, + latent=False, **kwargs, ): """ @@ -33,13 +33,13 @@ def corner_anesthetic( samples The samples of the non-linear search, whose ``model`` labels the axes. parameter_indices - The indices (in model order, or in the derived set's order when - ``derived``) of the parameters to plot; all by default. - derived - Plot the model's derived parameters instead of its free ones: each + The indices (in model order, or in the latent set's order when + ``latent``) of the parameters to plot; all by default. + latent + Plot the model's latent parameters instead of its free ones: each component's declared conversion is applied to the samples (a shear's components become its magnitude and angle, say) and parameters without - one pass through; see ``AbstractPriorModel.derived_parameters_from``. + one pass through; see ``AbstractPriorModel.latent_parameters_from``. """ config_dict = conf.instance["visualize"]["plots_settings"]["corner_anesthetic"] @@ -54,12 +54,12 @@ def corner_anesthetic( parameter_array = np.asarray(samples.parameter_lists) - if derived: - derived_parameters = model.derived_parameters_from( + if latent: + latent_parameters = model.latent_parameters_from( parameter_array, weights=samples.weight_list ) - labels = derived_parameters.parameter_labels_with_superscripts_latex - parameter_array = derived_parameters.parameter_array + labels = latent_parameters.parameter_labels_with_superscripts_latex + parameter_array = latent_parameters.parameter_array else: labels = model.parameter_labels_with_superscripts_latex diff --git a/autofit/non_linear/search/posterior_kind.py b/autofit/non_linear/search/posterior_kind.py index 231cff178..df0827c1d 100644 --- a/autofit/non_linear/search/posterior_kind.py +++ b/autofit/non_linear/search/posterior_kind.py @@ -55,6 +55,12 @@ def should_plot(self, name: str, default: Optional[bool] = None) -> bool: def plot_results(self, search, samples): raise NotImplementedError + def plot_latent_results(self, search, samples): + """ + The plots of the latent parameters, made once the fit is complete (see + ``WeightedDefaults.plot_latent_results``); none for most kinds. + """ + class ChainDefaults(PosteriorDefaults): kind = PosteriorKind.CHAIN @@ -140,46 +146,73 @@ def plot_results(self, search, samples): groups=samples.model.parameter_indices_by_component, ) - # The derived-parameter plots re-express each component's sampled - # parameters in the ones it is read in (a shear's magnitude and - # angle rather than gamma_1 / gamma_2), where a component declares - # the conversion. Independent of the plots above, so it can be the - # only corner plot or sit beside them; skipped when no component - # declares anything, as it would repeat the plain plot. - if self.should_plot("corner_anesthetic_derived", default=False): - derived = samples.model.derived_parameters_from( - np.asarray(samples.parameter_lists) - ) + def plot_latent_results(self, search, samples): + """ + The corner plot(s) of the latent parameters: each component's sampled + parameters re-expressed in the ones it is read in (a shear's magnitude + and angle rather than gamma_1 / gamma_2), where a component declares the + conversion (``AbstractPriorModel.latent_parameters_from``). Switched by + ``corner_anesthetic_latent`` independently of the plots above, so it can + be the only corner plot or sit beside them; skipped when no component + declares anything, as it would repeat the plain plot, and per component + only for the components that have a latent parameter. + + Latent output is made after the fit, not at every ``iterations_per_full_update`` + (``SearchUpdater.visualize``), the same rule as ``latent.csv``. + """ + from autofit.non_linear.plot import corner_anesthetic + + if not self.should_plot("corner_anesthetic_latent", default=False): + return + + path = search.paths.image_path / "search" + + with warnings.catch_warnings(): + warnings.simplefilter("ignore") - if derived.has_derived: - corner_anesthetic( - samples=samples, - path=path, - filename="corner_anesthetic_derived", - format="png", - derived=True, - ) - - if per_component: - self._corner_per_component( - corner_anesthetic, - samples, - path, - groups=derived.parameter_indices_by_component, - derived=True, - ) + latent = samples.model.latent_parameters_from( + np.asarray(samples.parameter_lists) + ) + + if not latent.has_latent: + return + + corner_anesthetic( + samples=samples, + path=path, + filename="corner_anesthetic_latent", + format="png", + latent=True, + ) + + # Per component only where the model has several (one alone would + # repeat the plot above), and only the components with a latent + # parameter (the others' plots would repeat their plain ones). + if ( + self.should_plot("corner_anesthetic_components", default=True) + and len(latent.parameter_indices_by_component) > 1 + ): + self._corner_per_component( + corner_anesthetic, + samples, + path, + groups=latent.parameter_indices_by_latent_component, + latent=True, + ) @staticmethod - def _corner_per_component(corner_anesthetic, samples, path, groups, derived=False): + def _corner_per_component(corner_anesthetic, samples, path, groups, latent=False): """ One corner plot per top-level model component (each galaxy of a lens model), as the full plot of a many-parameter model is too dense to read. - A model with a single component already has it, so none is made. + A model with a single component already has it, so none is made (the + latent plots check that on the model's components, since ``groups`` + then holds only those with a latent parameter). """ - if len(groups) < 2: + if len(groups) < 2 and not latent: return - stem = "corner_anesthetic_derived" if derived else "corner_anesthetic" + stem = "corner_anesthetic_latent" if latent else "corner_anesthetic" for name, parameter_indices in groups.items(): corner_anesthetic( @@ -188,7 +221,7 @@ def _corner_per_component(corner_anesthetic, samples, path, groups, derived=Fals filename=f"{stem}_{name}", format="png", parameter_indices=parameter_indices, - derived=derived, + latent=latent, ) diff --git a/autofit/non_linear/search/updater.py b/autofit/non_linear/search/updater.py index 2d7c2f2c1..a13b9da36 100644 --- a/autofit/non_linear/search/updater.py +++ b/autofit/non_linear/search/updater.py @@ -76,11 +76,16 @@ def __init__( disable_output: bool, iterations_per_full_update: float, visualization_enabled: bool = True, + plot_latent_results_func: Optional[Callable[[Samples], None]] = None, ): self._paths = paths self._timer = timer self._logger = search_logger self._plot_results = plot_results_func + # The plots of the latent parameters, made with the other latent output + # (``latent.csv``): after the fit, and during it only when + # ``output.yaml``'s ``latent_during_fit`` is on. None plots nothing. + self._plot_latent_results = plot_latent_results_func self._samples_from = samples_from_func self._disable_output = disable_output self._iterations_per_full_update = iterations_per_full_update @@ -173,7 +178,10 @@ def visualize( Perform visualization of the non-linear search's model-fitting results. Delegates to the analysis object for model-specific plots and to the - search's ``plot_results`` for search-specific plots. ``update`` passes the + search's ``plot_results`` for search-specific plots. The search's + ``plot_latent_results`` follows the latent-output rule rather than the + ``iterations_per_full_update`` cadence: once the fit is complete, and + during it only if ``output.yaml``'s ``latent_during_fit`` is on. ``update`` passes the ``samples`` it has already converted; without them they are converted from ``search_internal`` here. ``plot_search=False`` outputs only the analysis visuals (used for the starting point, before the search has samples). @@ -188,14 +196,12 @@ def visualize( paths = paths_override or self._paths if instance is None and samples_summary is None: - raise AssertionError( - """ + raise AssertionError(""" The search's perform_visualization method has been called without an input instance or samples_summary. This should not occur, please ensure one of these inputs is provided. - """ - ) + """) if instance is None: instance = samples_summary.instance @@ -219,10 +225,17 @@ def visualize( try: if samples is None: samples = self._samples_from( - model, search_internal, + model, + search_internal, ) self._plot_results(samples=samples) + + if self._plot_latent_results is not None and ( + not during_analysis + or conf.instance["output"]["latent_during_fit"] + ): + self._plot_latent_results(samples=samples) except FileNotFoundError: pass @@ -230,9 +243,7 @@ def _update_iteration_state(self): self._iterations += self._iterations_per_full_update if not self._disable_output: - self._logger.info( - """Fit Running: Updating results (see output folder).""" - ) + self._logger.info("""Fit Running: Updating results (see output folder).""") if self._paths.has_timer: self._timer.update() diff --git a/autofit/non_linear/search/updates.py b/autofit/non_linear/search/updates.py index f6acbd95e..8279119c0 100644 --- a/autofit/non_linear/search/updates.py +++ b/autofit/non_linear/search/updates.py @@ -124,6 +124,7 @@ def _updater(self): timer=self.timer, search_logger=self.logger, plot_results_func=self.plot_results, + plot_latent_results_func=self.plot_latent_results, samples_from_func=self.samples_from, disable_output=self.disable_output, iterations_per_full_update=self.iterations_per_full_update, @@ -195,3 +196,18 @@ def plot_results(self, samples): if defaults is None: raise NotImplementedError defaults.plot_results(self, samples) + + def plot_latent_results(self, samples): + """ + The search's plots of the model's latent parameters (the corner plot of + a shear's magnitude and angle, say), by its ``posterior_kind``; nothing + for a search without one. ``SearchUpdater.visualize`` calls this once the + fit is complete rather than at every ``iterations_per_full_update``, as + it does for ``latent.csv``. + """ + from autofit.non_linear.search.posterior_kind import defaults_for + + defaults = defaults_for(type(self).posterior_kind) + if defaults is None: + return + defaults.plot_latent_results(self, samples) diff --git a/test_autofit/analysis/test_latent.py b/test_autofit/analysis/test_latent.py index ef0092f5d..1624170b7 100644 --- a/test_autofit/analysis/test_latent.py +++ b/test_autofit/analysis/test_latent.py @@ -7,6 +7,7 @@ (``compute_latent_variables`` / ``LATENT_KEYS``) is covered by ``test_latent_variables.py``, which also exercises the back-compat shim. """ + import logging import numpy as np @@ -61,7 +62,9 @@ def test_latent_class_path_matches_method_override(): def test_latent_samples_from_callable_directly(): """The engine is usable as a free function, decoupled from the Analysis.""" - latent = latent_samples_from(FwhmAnalysis(), _samples([_sample(), _sample(centre=2.0)])) + latent = latent_samples_from( + FwhmAnalysis(), _samples([_sample(), _sample(centre=2.0)]) + ) assert latent is not None assert len(latent.sample_list) == 2 @@ -215,15 +218,19 @@ def log_likelihood_function(self, instance): def test_new_path_single_survivor_summary_does_not_crash(): latent = OneSurvivorAnalysis().compute_latent_samples( - _samples([ - _sample(centre=1.0, weight=0.5), - _sample(centre=2.0, weight=0.3), - _sample(centre=3.0, weight=0.2), - ]) + _samples( + [ + _sample(centre=1.0, weight=0.5), + _sample(centre=2.0, weight=0.3), + _sample(centre=3.0, weight=0.2), + ] + ) ) assert latent is not None assert len(latent.sample_list) == 1 - assert latent.pdf_converged # weight 0.5 <= 0.99 => median_pdf routes to quantile (n=1) + assert ( + latent.pdf_converged + ) # weight 0.5 <= 0.99 => median_pdf routes to quantile (n=1) _ = latent.summary() instance = latent.median_pdf() assert instance.fwhm == pytest.approx(FWHM_SIGMA_3) @@ -263,3 +270,86 @@ def test_none_samples_raises_via_engine_directly_and_before_latent_lookup(): with pytest.raises(af.exc.SamplesException): latent_samples_from(NoLatentAnalysis(), None) + + +class _Shear: + """A component with a latent parameter of its own (its magnitude).""" + + latent_parameters = { + ("gamma_1", "gamma_2"): lambda gamma_1, gamma_2, **kwargs: { + "magnitude": (gamma_1**2 + gamma_2**2) ** 0.5 + } + } + + def __init__(self, gamma_1=0.0, gamma_2=0.0): + self.gamma_1 = gamma_1 + self.gamma_2 = gamma_2 + + +class NoLatentAnalysis(af.Analysis): + def log_likelihood_function(self, instance): + return 1.0 + + +def _shear_samples(): + model = af.Collection( + shear=af.Model( + _Shear, + gamma_1=af.UniformPrior(-1.0, 1.0), + gamma_2=af.UniformPrior(-1.0, 1.0), + ) + ) + return SamplesPDF( + model=model, + sample_list=[ + af.Sample( + log_likelihood=1.0, + log_prior=0.0, + weight=1.0, + kwargs={"shear.gamma_1": 3.0, "shear.gamma_2": 4.0}, + ), + af.Sample( + log_likelihood=1.0, + log_prior=0.0, + weight=1.0, + kwargs={"shear.gamma_1": 0.0, "shear.gamma_2": 1.0}, + ), + ], + ) + + +def test_model_latent_parameters_are_latent_output_without_analysis_latents(): + """A component's declared latent parameters (``latent_parameters``) reach + ``latent.csv`` under their model path even when the analysis defines none.""" + latent = latent_samples_from(NoLatentAnalysis(), _shear_samples()) + + assert latent is not None + assert [s.kwargs for s in latent.sample_list] == [ + {("shear", "magnitude"): 5.0}, + {("shear", "magnitude"): 1.0}, + ] + assert latent.model.instance_from_vector([2.0]).shear.magnitude == 2.0 + + +def test_model_latent_parameters_join_the_analysis_latents(): + """With both, one row carries the analysis's latents and the model's.""" + + class BothAnalysis(af.Analysis): + LATENT_KEYS = ["sum"] + + def compute_latent_variables(self, parameters, model): + return (sum(parameters),) + + def log_likelihood_function(self, instance): + return 1.0 + + latent = latent_samples_from(BothAnalysis(), _shear_samples()) + + assert latent.sample_list[0].kwargs == { + ("sum",): 7.0, + ("shear", "magnitude"): 5.0, + } + + +def test_no_latents_anywhere_gives_none(): + assert latent_samples_from(NoLatentAnalysis(), _samples([_sample()])) is None diff --git a/test_autofit/mapper/model/test_derived.py b/test_autofit/mapper/model/test_latent_parameters.py similarity index 50% rename from test_autofit/mapper/model/test_derived.py rename to test_autofit/mapper/model/test_latent_parameters.py index 574b02b75..bdea649e2 100644 --- a/test_autofit/mapper/model/test_derived.py +++ b/test_autofit/mapper/model/test_latent_parameters.py @@ -19,7 +19,7 @@ def _polar_periodic(comp_0, comp_1, **kwargs): class MockPeriodicComponent: - derived_parameters = {("comp_0", "comp_1"): _polar_periodic} + latent_parameters = {("comp_0", "comp_1"): _polar_periodic} def __init__(self, centre=0.0, comp=(0.0, 0.0)): self.centre = centre @@ -32,7 +32,7 @@ def _scaled(comp_0, comp_1, scale, **kwargs): class MockComponent: # Sampled as two components, read as a strength and an angle. - derived_parameters = {("comp_0", "comp_1"): _polar} + latent_parameters = {("comp_0", "comp_1"): _polar} def __init__(self, centre=0.0, comp=(0.0, 0.0)): self.centre = centre @@ -41,7 +41,7 @@ def __init__(self, centre=0.0, comp=(0.0, 0.0)): class MockScaledComponent(MockComponent): # A subclass adds to, and may override, what its base declares. - derived_parameters = {("comp_0", "comp_1"): _scaled} + latent_parameters = {("comp_0", "comp_1"): _scaled} def __init__(self, centre=0.0, comp=(0.0, 0.0), scale=1.0): super().__init__(centre=centre, comp=comp) @@ -68,41 +68,41 @@ def _component(cls, comp=None, **fixed): return model -def test__derived_parameters__replace_components_in_place(): +def test__latent_parameters__replace_components_in_place(): model = _component(MockComponent) samples = np.array([[0.5, 3.0, 4.0], [0.1, 0.0, 1.0]]) - derived = model.derived_parameters_from(samples) + latent = model.latent_parameters_from(samples) - assert derived.has_derived - assert derived.names == ["centre", "strength", "angle"] - assert derived.derived_mask == [False, True, True] - assert derived.parameter_array[:, 0] == pytest.approx([0.5, 0.1]) - assert derived.parameter_array[:, 1] == pytest.approx([5.0, 1.0]) - assert derived.parameter_array[:, 2] == pytest.approx([36.869898, 0.0]) + assert latent.has_latent + assert latent.names == ["centre", "strength", "angle"] + assert latent.latent_mask == [False, True, True] + assert latent.parameter_array[:, 0] == pytest.approx([0.5, 0.1]) + assert latent.parameter_array[:, 1] == pytest.approx([5.0, 1.0]) + assert latent.parameter_array[:, 2] == pytest.approx([36.869898, 0.0]) -def test__derived_parameters__fixed_values_reach_the_conversion_and_subclass_overrides(): +def test__latent_parameters__fixed_values_reach_the_conversion_and_subclass_overrides(): model = _component(MockScaledComponent, scale=2.0) - derived = model.derived_parameters_from(np.array([[0.0, 3.0, 4.0]])) + latent = model.latent_parameters_from(np.array([[0.0, 3.0, 4.0]])) - assert derived.names == ["centre", "scaled"] - assert derived.parameter_array[0, 1] == pytest.approx(10.0) + assert latent.names == ["centre", "scaled"] + assert latent.parameter_array[0, 1] == pytest.approx(10.0) -def test__derived_parameters__no_conversion_when_a_replaced_parameter_is_fixed(): +def test__latent_parameters__no_conversion_when_a_replaced_parameter_is_fixed(): model = _component(MockComponent, comp=(0.0, 1.0)) - derived = model.derived_parameters_from(np.array([[0.5]])) + latent = model.latent_parameters_from(np.array([[0.5]])) - assert not derived.has_derived - assert not model.has_derived_parameters - assert derived.names == ["centre"] - assert derived.parameter_array.tolist() == [[0.5]] + assert not latent.has_latent + assert not model.has_latent_parameters + assert latent.names == ["centre"] + assert latent.parameter_array.tolist() == [[0.5]] -def test__derived_parameters__carry_their_component_superscript_and_grouping(): +def test__latent_parameters__carry_their_component_superscript_and_grouping(): model = af.Collection( galaxies=af.Collection( lens=af.Model(MockGalaxy, mass=_component(MockComponent)), @@ -111,30 +111,30 @@ def test__derived_parameters__carry_their_component_superscript_and_grouping(): ) rng = np.random.default_rng(0) - derived = model.derived_parameters_from(rng.normal(size=(4, model.prior_count))) + latent = model.latent_parameters_from(rng.normal(size=(4, model.prior_count))) - assert derived.names == ["centre", "strength", "angle", "one", "two"] - assert derived.superscripts == ["lens.mass"] * 3 + ["source.light"] * 2 - assert derived.parameter_indices_by_component == { + assert latent.names == ["centre", "strength", "angle", "one", "two"] + assert latent.superscripts == ["lens.mass"] * 3 + ["source.light"] * 2 + assert latent.parameter_indices_by_component == { "lens": [0, 1, 2], "source": [3, 4], } - assert derived.parameter_labels_with_superscripts_latex[1] == r"$s^{\rm lens.mass}$" + assert latent.parameter_labels_with_superscripts_latex[1] == r"$s^{\rm lens.mass}$" -def test__derived_parameters__plain_model_passes_through(): +def test__latent_parameters__plain_model_passes_through(): model = af.Model(af.m.MockClassx2NoSuperScript) samples = np.array([[1.0, 2.0]]) - derived = model.derived_parameters_from(samples) + latent = model.latent_parameters_from(samples) - assert not derived.has_derived - assert derived.names == model.parameter_names - assert derived.parameter_array.tolist() == samples.tolist() + assert not latent.has_latent + assert latent.names == model.parameter_names + assert latent.parameter_array.tolist() == samples.tolist() def test__periodic__recentres_on_the_circular_mean(): - from autofit.mapper.prior_model.derived import Periodic + from autofit.mapper.prior_model.latent_parameters import Periodic # A posterior peaked at the branch cut of [-180, 180): half the samples # just below 180, half just above -180. Recentred, they are contiguous @@ -153,13 +153,41 @@ def test__periodic__recentres_on_the_circular_mean(): assert recentred == pytest.approx([-185.0, -182.0, -179.0, -176.0]) -def test__derived_parameters__periodic_angle_is_recentred_with_the_sample_weights(): +def test__latent_parameters__periodic_angle_is_recentred_with_the_sample_weights(): model = _component(MockPeriodicComponent) # arctan2(comp_0, comp_1) for these straddles +-180. samples = np.array([[0.0, 0.1, -1.0], [0.0, -0.1, -1.0]]) - derived = model.derived_parameters_from(samples, weights=[1.0, 1.0]) + latent = model.latent_parameters_from(samples, weights=[1.0, 1.0]) - angle = derived.parameter_array[:, 2] + angle = latent.parameter_array[:, 2] assert np.ptp(angle) == pytest.approx(11.42, abs=0.01) # not ~348 - assert derived.names == ["centre", "strength", "angle"] + assert latent.names == ["centre", "strength", "angle"] + + +def test__latent_parameters__grouping_by_latent_component_and_full_paths(): + # The source has no latent parameter, so it has no group of its own in + # the latent grouping; every parameter keeps its full model path, a latent + # one under the component that declared it. + model = af.Collection( + galaxies=af.Collection( + lens=af.Model(MockGalaxy, mass=_component(MockComponent)), + source=af.Model(MockGalaxy, light=af.Model(af.m.MockClassx2NoSuperScript)), + ) + ) + rng = np.random.default_rng(1) + samples = rng.normal(size=(4, model.prior_count)) + + latent = model.latent_parameters_from(samples) + + assert latent.parameter_indices_by_latent_component == {"lens": [0, 1, 2]} + assert latent.paths == [ + ("galaxies", "lens", "mass", "centre"), + ("galaxies", "lens", "mass", "strength"), + ("galaxies", "lens", "mass", "angle"), + ("galaxies", "source", "light", "one"), + ("galaxies", "source", "light", "two"), + ] + items = latent.latent_items + assert [path for path, _ in items] == latent.paths[1:3] + assert items[0][1] == pytest.approx(latent.parameter_array[:, 1]) diff --git a/test_autofit/non_linear/plot/test_nest_plotters.py b/test_autofit/non_linear/plot/test_nest_plotters.py index 9b9c88f1f..a4c841d46 100644 --- a/test_autofit/non_linear/plot/test_nest_plotters.py +++ b/test_autofit/non_linear/plot/test_nest_plotters.py @@ -13,18 +13,18 @@ def __init__(self, labels): self.parameter_labels_with_superscripts_latex = labels self.total_free_parameters = len(labels) - def derived_parameters_from(self, parameter_array, weights=None): - # The derived set of this mock: the first two parameters become their sum. - from autofit.mapper.prior_model.derived import DerivedParameters + def latent_parameters_from(self, parameter_array, weights=None): + # The latent set of this mock: the first two parameters become their sum. + from autofit.mapper.prior_model.latent_parameters import LatentParameters - return DerivedParameters( + return LatentParameters( names=["sum"] + ["p"] * (parameter_array.shape[1] - 2), superscripts=[None] * (parameter_array.shape[1] - 1), component_paths=[()] * (parameter_array.shape[1] - 1), parameter_array=__import__("numpy").column_stack( [parameter_array[:, 0] + parameter_array[:, 1], parameter_array[:, 2:]] ), - derived_mask=[True] + [False] * (parameter_array.shape[1] - 2), + latent_mask=[True] + [False] * (parameter_array.shape[1] - 2), ) @@ -154,7 +154,7 @@ def fake_plot_2d(self, axes=None, **kwargs): assert routed["axes"]["figsize"] == (8, 8) -def test__corner_anesthetic__derived_plots_the_derived_set(monkeypatch, routed): +def test__corner_anesthetic__latent_plots_the_latent_set(monkeypatch, routed): from anesthetic.samples import NestedSamples rng = np.random.default_rng(3) @@ -171,10 +171,10 @@ def fake_plot_2d(self, axes=None, **kwargs): monkeypatch.setattr(NestedSamples, "plot_2d", fake_plot_2d) - nest_plotters.corner_anesthetic(samples=samples, derived=True) + nest_plotters.corner_anesthetic(samples=samples, latent=True) - # Two parameters became one, labelled from the derived set's own names, - # and the figure is sized to the derived set. + # Two parameters became one, labelled from the latent set's own names, + # and the figure is sized to the latent set. assert seen["labels"] == ["$s$", "$p$"] assert seen["first"] == pytest.approx(sum(samples.parameter_lists[0][:2])) assert routed["axes"]["figsize"] == (8, 8) diff --git a/test_autofit/non_linear/search/test_family_bases.py b/test_autofit/non_linear/search/test_family_bases.py index 1e6f09233..26fe4ddb7 100644 --- a/test_autofit/non_linear/search/test_family_bases.py +++ b/test_autofit/non_linear/search/test_family_bases.py @@ -276,7 +276,7 @@ def __init__(self, light=None): class _MockShear: - derived_parameters = { + latent_parameters = { ("gamma_1", "gamma_2"): lambda gamma_1, gamma_2, **kwargs: { "magnitude": (gamma_1**2 + gamma_2**2) ** 0.5 } @@ -296,7 +296,7 @@ def _lens_like_model(): ) -def _weighted_plot_calls(model, monkeypatch, tmp_path): +def _weighted_plot_calls(model, monkeypatch, tmp_path, latent=False): from types import SimpleNamespace import autofit.non_linear.plot as plot_module from autofit.non_linear.search.posterior_kind import WeightedDefaults @@ -307,9 +307,14 @@ def _weighted_plot_calls(model, monkeypatch, tmp_path): ) search = SimpleNamespace(paths=SimpleNamespace(image_path=tmp_path)) samples = SimpleNamespace( - model=model, parameter_lists=[[0.1] * model.prior_count] * 3 + model=model, + parameter_lists=[[0.1] * model.prior_count] * 3, + weight_list=[1.0] * 3, ) - WeightedDefaults().plot_results(search=search, samples=samples) + defaults = WeightedDefaults() + defaults.plot_results(search=search, samples=samples) + if latent: + defaults.plot_latent_results(search=search, samples=samples) return calls @@ -364,22 +369,23 @@ def should_plot(self, name, default=None): assert len(calls) == 3 -def test_weighted_plot_results_derived_corner_only_when_a_component_declares_one( +def test_weighted_plot_results_latent_corner_only_when_a_component_declares_one( monkeypatch, tmp_path ): from autofit.non_linear.search.posterior_kind import WeightedDefaults - # The derived plots are off by default; every switch on for this test. + # The latent plots are off by default; every switch on for this test. monkeypatch.setattr( WeightedDefaults, "should_plot", lambda self, name, default=None: True ) - # Nothing to derive: the derived plot would repeat the plain one, so none. - calls = _weighted_plot_calls(_lens_like_model(), monkeypatch, tmp_path) - assert not any("derived" in call.get("filename", "") for call in calls) + # Nothing latent: the latent plot would repeat the plain one, so none. + calls = _weighted_plot_calls(_lens_like_model(), monkeypatch, tmp_path, latent=True) + assert not any("latent" in call.get("filename", "") for call in calls) - # A shear declares its magnitude: a derived plot, and one per component - # since the per-component switch is on too. + # A shear declares its magnitude: a latent plot, and one for the lens + # since the per-component switch is on too; none for the source, which + # has no latent parameter and whose plot would repeat its plain one. model = af.Collection( galaxies=af.Collection( lens=af.Model( @@ -393,26 +399,24 @@ def test_weighted_plot_results_derived_corner_only_when_a_component_declares_one source=af.Model(_MockGalaxy, light=af.Model(af.m.MockClassx2NoSuperScript)), ) ) - calls = _weighted_plot_calls(model, monkeypatch, tmp_path) + calls = _weighted_plot_calls(model, monkeypatch, tmp_path, latent=True) - derived_calls = [call for call in calls if call.get("derived")] - assert [call["filename"] for call in derived_calls] == [ - "corner_anesthetic_derived", - "corner_anesthetic_derived_lens", - "corner_anesthetic_derived_source", + latent_calls = [call for call in calls if call.get("latent")] + assert [call["filename"] for call in latent_calls] == [ + "corner_anesthetic_latent", + "corner_anesthetic_latent_lens", ] - assert derived_calls[1]["parameter_indices"] == [0] # magnitude alone - assert derived_calls[2]["parameter_indices"] == [1, 2] + assert latent_calls[1]["parameter_indices"] == [0] # magnitude alone -def test_weighted_plot_results_derived_switch_is_independent(monkeypatch, tmp_path): - # Derived on, the other two off: the derived plot is the only corner plot. +def test_weighted_plot_results_latent_switch_is_independent(monkeypatch, tmp_path): + # Latent on, the other two off: the latent plot is the only corner plot. from autofit.non_linear.search.posterior_kind import WeightedDefaults monkeypatch.setattr( WeightedDefaults, "should_plot", - lambda self, name, default=None: name == "corner_anesthetic_derived", + lambda self, name, default=None: name == "corner_anesthetic_latent", ) model = af.Collection( lens=af.Model( @@ -425,8 +429,82 @@ def test_weighted_plot_results_derived_switch_is_independent(monkeypatch, tmp_pa ) ) - calls = _weighted_plot_calls(model, monkeypatch, tmp_path) + calls = _weighted_plot_calls(model, monkeypatch, tmp_path, latent=True) + + assert [call.get("filename", "corner_anesthetic") for call in calls] == [ + "corner_anesthetic_latent" + ] + + +def test_weighted_plot_results_never_makes_the_latent_plots(monkeypatch, tmp_path): + # The latent plots are latent output: ``plot_results`` (every + # ``iterations_per_full_update``) leaves them to ``plot_latent_results``, + # which the updater calls once the fit is complete. + from autofit.non_linear.search.posterior_kind import WeightedDefaults + + monkeypatch.setattr( + WeightedDefaults, "should_plot", lambda self, name, default=None: True + ) + model = af.Collection( + lens=af.Model( + _MockGalaxy, + light=af.Model( + _MockShear, + gamma_1=af.UniformPrior(-1.0, 1.0), + gamma_2=af.UniformPrior(-1.0, 1.0), + ), + ) + ) + + calls = _weighted_plot_calls(model, monkeypatch, tmp_path, latent=False) + + assert not any(call.get("latent") for call in calls) + + +def test_search_plot_latent_results_dispatches_on_posterior_kind(monkeypatch): + from autofit.non_linear.search import posterior_kind + + calls = [] + monkeypatch.setattr( + posterior_kind.WeightedDefaults, + "plot_latent_results", + lambda self, search, samples: calls.append(self), + ) + + af.Nautilus().plot_latent_results(samples=None) + assert calls == [posterior_kind.WEIGHTED] + + # Other kinds, and a search without one, plot nothing and do not raise. + af.Emcee().plot_latent_results(samples=None) + af.m.MockSearch().plot_latent_results(samples=None) + + +def test_weighted_plot_latent_results_single_component_has_no_duplicate( + monkeypatch, tmp_path +): + # One component with a latent parameter and no other: its per-component + # latent plot would repeat the full latent plot, so none is made. + from autofit.non_linear.search.posterior_kind import WeightedDefaults + + monkeypatch.setattr( + WeightedDefaults, "should_plot", lambda self, name, default=None: True + ) + model = af.Collection( + galaxies=af.Collection( + lens=af.Model( + _MockGalaxy, + light=af.Model( + _MockShear, + gamma_1=af.UniformPrior(-1.0, 1.0), + gamma_2=af.UniformPrior(-1.0, 1.0), + ), + ), + ) + ) + + calls = _weighted_plot_calls(model, monkeypatch, tmp_path, latent=True) assert [call.get("filename", "corner_anesthetic") for call in calls] == [ - "corner_anesthetic_derived" + "corner_anesthetic", + "corner_anesthetic_latent", ] diff --git a/test_autofit/non_linear/search/test_updater.py b/test_autofit/non_linear/search/test_updater.py index a905eb0a5..b16adb1f7 100644 --- a/test_autofit/non_linear/search/test_updater.py +++ b/test_autofit/non_linear/search/test_updater.py @@ -235,3 +235,80 @@ def test__visualize__disabled_skips_all(): analysis.visualize_combined.assert_not_called() updater._samples_from.assert_not_called() updater._plot_results.assert_not_called() + + +def _visualizing_updater(plot_latent_results_func): + updater = SearchUpdater( + paths=MagicMock(), + timer=MagicMock(), + search_logger=logging.getLogger("test_updater"), + plot_results_func=MagicMock(), + samples_from_func=MagicMock(), + disable_output=False, + iterations_per_full_update=1.0, + plot_latent_results_func=plot_latent_results_func, + ) + return updater + + +def test__visualize__latent_plots_only_once_the_fit_is_complete(): + """ + The latent corner plots follow the latent-output rule, not the + ``iterations_per_full_update`` cadence: made after the fit, and during it + only when ``output.yaml``'s ``latent_during_fit`` is on. + """ + original_during = conf.instance["output"]["latent_during_fit"] + conf.instance["output"]["latent_during_fit"] = False + try: + plot_latent = MagicMock() + updater = _visualizing_updater(plot_latent) + analysis = MagicMock() + analysis.should_visualize.return_value = True + samples = MagicMock() + + updater.visualize( + model=MagicMock(), + analysis=analysis, + during_analysis=True, + samples_summary=MagicMock(), + samples=samples, + ) + updater._plot_results.assert_called_once_with(samples=samples) + plot_latent.assert_not_called() + + updater.visualize( + model=MagicMock(), + analysis=analysis, + during_analysis=False, + samples_summary=MagicMock(), + samples=samples, + ) + plot_latent.assert_called_once_with(samples=samples) + + conf.instance["output"]["latent_during_fit"] = True + updater.visualize( + model=MagicMock(), + analysis=analysis, + during_analysis=True, + samples_summary=MagicMock(), + samples=samples, + ) + assert plot_latent.call_count == 2 + finally: + conf.instance["output"]["latent_during_fit"] = original_during + + +def test__visualize__no_latent_plotter_is_fine(): + updater = _make_updater() + analysis = MagicMock() + analysis.should_visualize.return_value = True + + updater.visualize( + model=MagicMock(), + analysis=analysis, + during_analysis=False, + samples_summary=MagicMock(), + samples=MagicMock(), + ) + + updater._plot_results.assert_called_once() From 13bd430cfe12eb63290519f9df6d408509bed70d Mon Sep 17 00:00:00 2001 From: samlange04 Date: Sun, 18 Oct 2026 16:13:32 +0800 Subject: [PATCH 7/9] Shared priors: label and latent path follow the last holder, not the common prefix A prior shared between differently named components (a power law's ellipticity linked into its multipoles, `mass` / `multipole_3` / `multipole_4`) was labelled by the components' common prefix alone, `lens`, because every differing path element was dropped. Only a list index that differs (the Gaussians of a basis) says nothing; a differing name is kept, from the path the samples column is named after (`unique_prior_paths`, the last component holding the prior), so label and column agree: `q^{lens.mass}`. `latent_parameters_from` indexed `model.paths`, which lists every path to a shared prior, instead of `unique_prior_paths`, so the latent.csv keys of such a model were misaligned. Found by running the HST project's EPLS34 model (elliptical and circular multipole classes) through labels, latent parameters, latent samples and the corner plots. Co-Authored-By: Claude Fable 5.1 --- autofit/mapper/prior_model/abstract.py | 18 ++++++++++++-- .../mapper/prior_model/latent_parameters.py | 2 +- .../mapper/model/test_latent_parameters.py | 24 +++++++++++++++++++ .../mapper/model/test_model_mapper.py | 20 ++++++++++++++++ 4 files changed, 61 insertions(+), 3 deletions(-) diff --git a/autofit/mapper/prior_model/abstract.py b/autofit/mapper/prior_model/abstract.py index d6e88191d..fe4cd6654 100644 --- a/autofit/mapper/prior_model/abstract.py +++ b/autofit/mapper/prior_model/abstract.py @@ -2521,7 +2521,18 @@ def _component_name_object_pairs(self) -> List[List[Tuple[str, object]]]: obj = obj[int(name)] if isinstance(obj, (Collection, TuplePrior)): continue - if same_length and any(other[i] != name for other in sibling_paths): + # A list index that differs between the paths to one shared + # prior (the thirty Gaussians of a basis) says nothing and is + # dropped. A *name* that differs (a power law's ellipticity + # shared with its multipoles, ``mass`` / ``multipole_3``) is + # kept: this is the path the prior's samples column is named + # after (``unique_prior_paths``, the last component holding + # it), so the label and the column agree. + if ( + same_length + and name.isdigit() + and any(other[i] != name for other in sibling_paths) + ): continue pairs.append((name, obj)) @@ -2594,7 +2605,10 @@ def component_paths(self) -> List[Path]: An index is kept when it distinguishes the prior from its siblings, so a collection of components with independent priors gives ``("0",)``, ``("1",)``; it is dropped only where the paths to a shared prior differ, - which is what makes it meaningless. + which is what makes it meaningless. A prior shared between differently + named components (a power law's ellipticity linked into its multipoles) + takes the path its samples column is named after, the last component + holding it: ``("lens", "mass")``, not ``("lens", "multipole_3")``. This is what labels parameters in results and plots, and what groups them by component (see ``parameter_indices_by_component``). diff --git a/autofit/mapper/prior_model/latent_parameters.py b/autofit/mapper/prior_model/latent_parameters.py index 96594c36e..295636e1e 100644 --- a/autofit/mapper/prior_model/latent_parameters.py +++ b/autofit/mapper/prior_model/latent_parameters.py @@ -251,7 +251,7 @@ def latent_parameters_from( names = model.parameter_names superscripts = model.superscripts component_paths = model.component_paths - paths = model.paths + paths = model.unique_prior_paths # Which free parameters each component owns, by leaf name -> model index. indices_by_owner = {} diff --git a/test_autofit/mapper/model/test_latent_parameters.py b/test_autofit/mapper/model/test_latent_parameters.py index bdea649e2..fd8e76e3a 100644 --- a/test_autofit/mapper/model/test_latent_parameters.py +++ b/test_autofit/mapper/model/test_latent_parameters.py @@ -191,3 +191,27 @@ def test__latent_parameters__grouping_by_latent_component_and_full_paths(): items = latent.latent_items assert [path for path, _ in items] == latent.paths[1:3] assert items[0][1] == pytest.approx(latent.parameter_array[:, 1]) + + +def test__latent_parameters__shared_prior_takes_the_path_of_its_samples_column(): + # The replaced priors are shared by two components; the latent ones are + # filed under the component the column is named after (the last holder), + # not under whichever path happens to come first. + mass = _component(MockComponent) + multipole = _component(MockComponent, comp=mass.comp) + multipole.centre = mass.centre + model = af.Collection( + galaxies=af.Collection( + lens=af.Model(MockGalaxy, light=multipole, mass=mass), + ) + ) + + latent = model.latent_parameters_from(np.array([[0.5, 3.0, 4.0]])) + + assert latent.names == ["centre", "strength", "angle"] + assert latent.superscripts == ["lens.mass"] * 3 + assert latent.paths == [ + ("galaxies", "lens", "mass", "centre"), + ("galaxies", "lens", "mass", "strength"), + ("galaxies", "lens", "mass", "angle"), + ] diff --git a/test_autofit/mapper/model/test_model_mapper.py b/test_autofit/mapper/model/test_model_mapper.py index b47806bd2..ffe14d80c 100644 --- a/test_autofit/mapper/model/test_model_mapper.py +++ b/test_autofit/mapper/model/test_model_mapper.py @@ -926,3 +926,23 @@ def test_no_override(self): af.ModelMapper() assert mapper.one is not None + + +def test__superscripts__prior_shared_between_named_components_keeps_the_last_holder(): + # A power law's ellipticity linked into its multipole: the samples column + # is named after the last component holding the prior (`mass`), and so is + # the label, rather than collapsing to the common `lens`. + mass = af.Model(af.m.MockClassx2NoSuperScript) + multipole = af.Model(af.m.MockClassx2NoSuperScript, one=mass.one, two=mass.two) + model = af.Collection( + galaxies=af.Collection( + lens=af.Model(MockGalaxy, bulge=multipole, disk=mass), + ) + ) + + assert model.unique_prior_paths == [ + ("galaxies", "lens", "disk", "one"), + ("galaxies", "lens", "disk", "two"), + ] + assert model.component_paths == [("lens", "disk"), ("lens", "disk")] + assert model.superscripts == ["lens.disk", "lens.disk"] From bf43aa6235cf1f7ac704883dbed82f02ae3b531a Mon Sep 17 00:00:00 2001 From: samlange04 Date: Sun, 18 Oct 2026 16:48:42 +0800 Subject: [PATCH 8/9] Resolve the LatentParameters forward reference for the docs build sphinx_autodoc_typehints could not resolve the string annotation on latent_parameters_from, three new warnings over the baseline. Co-Authored-By: Claude Fable 5.1 --- autofit/mapper/prior_model/abstract.py | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/autofit/mapper/prior_model/abstract.py b/autofit/mapper/prior_model/abstract.py index fe4cd6654..92b645e0c 100644 --- a/autofit/mapper/prior_model/abstract.py +++ b/autofit/mapper/prior_model/abstract.py @@ -5,11 +5,24 @@ import random import types from collections import defaultdict -from typing import Tuple, Optional, Dict, List, Iterable, Generator, Union, Type +from typing import ( + TYPE_CHECKING, + Tuple, + Optional, + Dict, + List, + Iterable, + Generator, + Union, + Type, +) import numpy as np from autonerves import conf + +if TYPE_CHECKING: + from autofit.mapper.prior_model.latent_parameters import LatentParameters from autonerves.exc import ConfigException from autofit import exc from autofit.mapper import model From f9377f3f6fe56237cdb62d52e93ee34e44cef565 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Wed, 21 Oct 2026 09:50:13 +0100 Subject: [PATCH 9/9] Corner plots: resolve the #1709 review (maintainer changes) - Per-component corner plots follow corner_anesthetic when an older config omits corner_anesthetic_components; latent per-component plots get their own corner_anesthetic_latent_components key. - plot_latent_results logs a raising latent conversion instead of failing the fit's final visualize, and is skipped in test mode. - output.yaml latent_model_parameters switches the model's declared latents out of latent.csv / latent.results / latent_summary.json. - Deep-path superscripts are cut consistently and only while they stay unique (superscripts_from_component_paths); no more lens.bul.she twice. - A prior shared between components is seen by every holder's declarations, so a power law's ell_comps linked into a multipole keeps its latents. - Periodic latents are recentred for plots only; latent.csv keeps the conversion's range so it does not depend on the fit. - Root group is "model_root" when a component is named model; component paths cached while the model is frozen. Refs #1710 Co-Authored-By: Claude Opus 5.5 --- autofit/config/output.yaml | 1 + autofit/config/visualize/plots_search.yaml | 5 +- autofit/mapper/prior_model/abstract.py | 264 ++++++++++++------ .../mapper/prior_model/latent_parameters.py | 102 ++++--- autofit/non_linear/analysis/latent.py | 22 +- autofit/non_linear/plot/nest_plotters.py | 2 +- autofit/non_linear/search/posterior_kind.py | 42 ++- test_autofit/analysis/test_latent.py | 13 + .../mapper/model/test_latent_parameters.py | 111 +++++++- .../mapper/model/test_model_mapper.py | 70 ++++- .../non_linear/plot/test_nest_plotters.py | 2 +- .../non_linear/search/test_family_bases.py | 103 +++++++ .../non_linear/search/test_updater.py | 54 ++++ 13 files changed, 639 insertions(+), 152 deletions(-) diff --git a/autofit/config/output.yaml b/autofit/config/output.yaml index cb94e2567..bbb2d7d48 100644 --- a/autofit/config/output.yaml +++ b/autofit/config/output.yaml @@ -92,6 +92,7 @@ latent_draw_via_pdf : true # Whether to draw latent variable values via the PDF latent_draw_via_pdf_size : 100 # The number of samples drawn to estimate latent variable errors if `latent_draw_via_pdf` is True. latent_csv: true # Whether to ouptut the `latent.csv` file. latent_results: true # Whether to output the `latent.results` file. +latent_model_parameters: true # Whether the latent parameters a model component declares (e.g. a shear's magnitude and angle for its gamma_1 / gamma_2) join the latent output (`latent.csv`, `latent.results`, `latent_summary.json`). An angle keeps the range its conversion gives it (the same in every fit); only the corner plots recentre it on the posterior. # Other Files: diff --git a/autofit/config/visualize/plots_search.yaml b/autofit/config/visualize/plots_search.yaml index 570c38721..8a1d3e44e 100644 --- a/autofit/config/visualize/plots_search.yaml +++ b/autofit/config/visualize/plots_search.yaml @@ -1,7 +1,8 @@ nest: corner_anesthetic: true # Output corner figure (using anestetic) during a non-linear search fit? - corner_anesthetic_components: true # Also output one corner figure per top-level model component (e.g. per galaxy), each named corner_anesthetic_? - corner_anesthetic_latent: false # Output corner figure(s) of the latent parameters (e.g. a shear's magnitude and angle rather than gamma_1 / gamma_2), named corner_anesthetic_latent[_], per component only where one has a latent parameter? Independent of the two above. Made after the fit like latent.csv (during it only if output.yaml's latent_during_fit is on). + corner_anesthetic_components: true # Also output one corner figure per top-level model component (e.g. per galaxy), each named corner_anesthetic_? Follows corner_anesthetic when absent. + corner_anesthetic_latent: false # Output a corner figure of the latent parameters (e.g. a shear's magnitude and angle rather than gamma_1 / gamma_2), named corner_anesthetic_latent? Independent of the two above. Made after the fit like latent.csv (during it only if output.yaml's latent_during_fit is on). + corner_anesthetic_latent_components: true # With corner_anesthetic_latent, also output one latent corner figure per top-level component that has a latent parameter, each named corner_anesthetic_latent_? Follows corner_anesthetic_latent when absent. mcmc: corner_cornerpy: true # Output corner figure (using corner.py) during a non-linear search fit? mle: diff --git a/autofit/mapper/prior_model/abstract.py b/autofit/mapper/prior_model/abstract.py index 92b645e0c..bbea7b6d0 100644 --- a/autofit/mapper/prior_model/abstract.py +++ b/autofit/mapper/prior_model/abstract.py @@ -178,20 +178,92 @@ def paths_to_tree(paths: List[Tuple[str, ...]], tree: Optional[dict] = None) -> return tree -def superscript_from_component_path(path: Tuple[str, ...]) -> str: +def superscripts_from_component_paths( + component_paths: Iterable[Tuple[str, ...]], +) -> Dict[Tuple[str, ...], str]: """ - The superscript of a parameter from the path of the named components owning it. - - Paths of one or two levels are joined with dots unchanged (``lens.bulge``). - From three levels deep the first name is kept whole and every later name is - cut to its first three characters, so ``("source", "pixelization", - "regularization")`` gives ``source.pix.reg``: the first level is the plane or - galaxy that distinguishes the components, and the rest only needs to stay - recognisable in the small type of a corner-plot axis. + The superscript of every distinct path of named components, keyed by path. + + Names are joined with dots (``lens.bulge``), unchanged in a model with no + path three levels deep. A model with such paths would run into the + neighbouring labels on a corner-plot axis, so every name below the first + level that lies on one is cut short, ``("source", "pixelization", + "regularization")`` giving + ``source.pix.reg``: the first level is the plane or galaxy that distinguishes + the components, and the rest only needs to stay recognisable. + + A name is cut the same way in every path it appears in, so the priors of a + basis and those of the profiles inside it read ``lens.bul`` and ``lens.bul.0``, + not ``lens.bulge`` and ``lens.bul.0``. It is cut to three characters unless + that would match a sibling (another name under the same parent), in which + case it keeps as many characters as tell them apart: ``bulge_inner`` and + ``bulge_outer`` become ``bulge_i`` and ``bulge_o``. Distinct paths therefore + always have distinct superscripts. """ - if len(path) < 3: - return ".".join(path) - return ".".join([path[0]] + [name[:3] for name in path[1:]]) + component_paths = {tuple(path) for path in component_paths if path} + + # Each name below the first level that lies on a path of three or more. + deep = { + path[: i + 1] + for path in component_paths + if len(path) >= 3 + for i in range(1, len(path)) + } + + siblings = defaultdict(set) + for path in component_paths: + for i in range(1, len(path)): + siblings[path[:i]].add(path[i]) + + short = {} + for parent, names in siblings.items(): + cut = {name: 3 for name in names if parent + (name,) in deep} + while True: + labels = { + name: name[: cut[name]] if name in cut else name for name in names + } + clashes = defaultdict(list) + for name, label in labels.items(): + clashes[label].append(name) + grow = [ + name + for group in clashes.values() + if len(group) > 1 + for name in group + if name in cut and cut[name] < len(name) + ] + if not grow: + break + for name in grow: + cut[name] += 1 + for name, label in labels.items(): + short[parent + (name,)] = label + + return { + path: ".".join([path[0]] + [short[path[: i + 1]] for i in range(1, len(path))]) + for path in component_paths + } + + +def indices_by_top_level_component( + component_paths: List[Tuple[str, ...]], +) -> Dict[str, List[int]]: + """ + The indices of the parameters belonging to each top-level model component, + keyed by the component's name and in model order, from the component path of + each parameter (see ``AbstractPriorModel.component_paths``). + + Parameters whose priors sit directly on the model (no named component) are + grouped under ``"model"``, or ``"model_root"`` when a component is itself + named ``model``, so the two groups (and their per-component corner plots) + stay apart. + """ + names = {path[0] for path in component_paths if path} + root = "model_root" if "model" in names else "model" + groups = {} + for i, path in enumerate(component_paths): + groups.setdefault(path[0] if path else root, []).append(i) + return groups class AbstractPriorModel(AbstractModel): @@ -2505,80 +2577,90 @@ def parameter_labels(self) -> List[str]: return parameter_labels - @property - def _component_name_object_pairs(self) -> List[List[Tuple[str, object]]]: + def _prior_holder( + self, path: Path, sibling_paths: List[Path] + ) -> Tuple[Path, Tuple[str, ...], object, str]: """ - For each unique prior (ordered by id), the ``(name, object)`` pairs of the - named model components that own it; see ``component_paths``. + One path to a prior as ``(path, component path, owner, leaf name)``: the + named model components on the path (see ``component_paths``), the model + component directly owning the prior there (the deepest ``Model`` on the + path) and the prior's leaf name, for example ``(..., ("lens", "mass"), + , "ell_comps_0")``. + + ``sibling_paths`` are the paths of the components holding every path to + the same prior, which decide whether a list index names anything. """ from autofit.mapper.prior_model.collection import Collection from autofit.mapper.prior.tuple_prior import TuplePrior - paths_by_prior = defaultdict(list) - for path, prior in self.path_priors_tuples: - paths_by_prior[prior].append(path[:-1]) - - pairs_list = [] + component_path = path[:-1] + same_length = all(len(other) == len(component_path) for other in sibling_paths) - for path, prior in self.unique_path_prior_tuples: - path = path[:-1] - sibling_paths = paths_by_prior[prior] - same_length = all(len(other) == len(path) for other in sibling_paths) + names = [] + owner = self + obj = self + for i, name in enumerate(component_path): + try: + obj = getattr(obj, name) + except AttributeError: + obj = obj[int(name)] + if isinstance(obj, (Collection, TuplePrior)): + continue + owner = obj + # A list index that differs between the paths to one shared prior + # (the thirty Gaussians of a basis) says nothing and is dropped. + if ( + same_length + and name.isdigit() + and any(other[i] != name for other in sibling_paths) + ): + continue + names.append(name) - pairs = [] - obj = self - for i, name in enumerate(path): - try: - obj = getattr(obj, name) - except AttributeError: - obj = obj[int(name)] - if isinstance(obj, (Collection, TuplePrior)): - continue - # A list index that differs between the paths to one shared - # prior (the thirty Gaussians of a basis) says nothing and is - # dropped. A *name* that differs (a power law's ellipticity - # shared with its multipoles, ``mass`` / ``multipole_3``) is - # kept: this is the path the prior's samples column is named - # after (``unique_prior_paths``, the last component holding - # it), so the label and the column agree. - if ( - same_length - and name.isdigit() - and any(other[i] != name for other in sibling_paths) - ): - continue - pairs.append((name, obj)) + return tuple(path), tuple(names), owner, path[-1] - pairs_list.append(pairs) + @property + @frozen_cache + def _prior_holders(self) -> List[List[Tuple[Path, Tuple[str, ...], object, str]]]: + """ + For each unique prior (ordered by id), every path holding it as given by + ``_prior_holder``. The first is the path the prior's samples column is + named after (``unique_prior_paths``, the last component holding it); the + others are where a prior shared between components (a power law's + ellipticity linked into its multipoles) also sits. - return pairs_list + Cached while the model is frozen (as during a fit), since the plots and + the latent output ask for it several times per update. + """ + paths_by_prior = defaultdict(list) + for path, prior in self.path_priors_tuples: + paths_by_prior[prior].append(tuple(path)) + + holders = [] + for primary, prior in self.unique_path_prior_tuples: + primary = tuple(primary) + paths = paths_by_prior[prior] + sibling_paths = [path[:-1] for path in paths] + holders.append( + [ + self._prior_holder(path, sibling_paths) + for path in [primary] + [path for path in paths if path != primary] + ] + ) + return holders @property def _prior_owner_and_leaf_names(self) -> List[Tuple[object, str]]: """ For each unique prior (ordered by id), the model component that directly - owns it (the deepest ``Model`` on its path) and the prior's leaf name, for - example ``(, "ell_comps_0")``. + owns it (the deepest ``Model`` on the path its samples column is named + after) and the prior's leaf name, for example + ``(, "ell_comps_0")``. """ - from autofit.mapper.prior_model.collection import Collection - from autofit.mapper.prior.tuple_prior import TuplePrior - - owners = [] - for path in self.unique_prior_paths: - owner = self - obj = self - for name in path[:-1]: - try: - obj = getattr(obj, name) - except AttributeError: - obj = obj[int(name)] - if not isinstance(obj, (Collection, TuplePrior)): - owner = obj - owners.append((owner, path[-1])) - return owners + return [(holders[0][2], holders[0][3]) for holders in self._prior_holders] def latent_parameters_from( - self, parameter_array, weights=None + self, parameter_array, weights=None, recentre: bool = False ) -> "LatentParameters": """ The parameters of this model after each component's declared conversions @@ -2591,12 +2673,18 @@ def latent_parameters_from( parameter_array Samples of the model's free parameters, shape ``(n_samples, prior_count)``. weights - The weight of each sample, which centres a periodic latent parameter - (an angle) on its posterior; equal by default. + The weight of each sample, which with ``recentre`` centres a periodic + latent parameter (an angle) on its posterior; equal by default. + recentre + Whether to recentre each periodic latent parameter on its circular + mean, as a plot does; the latent output keeps the range the + conversion gives it, so it does not depend on the fit. """ from autofit.mapper.prior_model.latent_parameters import latent_parameters_from - return latent_parameters_from(self, parameter_array, weights=weights) + return latent_parameters_from( + self, parameter_array, weights=weights, recentre=recentre + ) @property def has_latent_parameters(self) -> bool: @@ -2626,10 +2714,7 @@ def component_paths(self) -> List[Path]: This is what labels parameters in results and plots, and what groups them by component (see ``parameter_indices_by_component``). """ - return [ - tuple(name for name, _ in pairs) - for pairs in self._component_name_object_pairs - ] + return [holders[0][1] for holders in self._prior_holders] @property def parameter_indices_by_component(self) -> Dict[str, List[int]]: @@ -2639,12 +2724,10 @@ def parameter_indices_by_component(self) -> Dict[str, List[int]]: ``{"lens": [0, ..., 14], "source": [15, ..., 18]}``. Parameters whose priors sit directly on the model (no named component) - are grouped under ``"model"``. + are grouped under ``"model"`` (``"model_root"`` if a component is itself + named ``model``). """ - groups = {} - for i, path in enumerate(self.component_paths): - groups.setdefault(path[0] if path else "model", []).append(i) - return groups + return indices_by_top_level_component(self.component_paths) @property def superscripts(self) -> List[str]: @@ -2662,10 +2745,11 @@ def superscripts(self) -> List[str]: with this string (corresponding to the parameters `centre`, `normalization` and `sigma`) will be returned. - A path three or more levels deep keeps its first name whole and cuts every - later name to three characters, so ``source.pixelization.regularization`` - is labelled ``source.pix.reg`` and the label stays readable on a corner - plot (see ``superscript_from_component_path``). + A path three or more levels deep keeps its first name whole and cuts the + later names short, so ``source.pixelization.regularization`` is labelled + ``source.pix.reg`` and the label stays readable on a corner plot; a name is + cut only as far as it stays distinct from its siblings (see + ``superscripts_from_component_paths``). A prior directly on the model (a bare ``Model(Gaussian)``) has no named component; it uses the `notation/label.yaml` config's `superscript:` entry @@ -2674,14 +2758,12 @@ def superscripts(self) -> List[str]: This is used for displaying model results as text and for visualization. """ + component_paths = self.component_paths + labels = superscripts_from_component_paths(component_paths) return [ - ( - superscript_from_component_path(path) - if path - else (superscript_overwrite or None) - ) + labels[path] if path else (superscript_overwrite or None) for path, superscript_overwrite in zip( - self.component_paths, self.superscripts_overwrite_via_config + component_paths, self.superscripts_overwrite_via_config ) ] diff --git a/autofit/mapper/prior_model/latent_parameters.py b/autofit/mapper/prior_model/latent_parameters.py index 295636e1e..8e6e95609 100644 --- a/autofit/mapper/prior_model/latent_parameters.py +++ b/autofit/mapper/prior_model/latent_parameters.py @@ -26,19 +26,26 @@ class ExternalShear: it came from. A declaration whose replaced parameters are not all free in this model is skipped, since there is nothing to convert. +A prior shared between components (a power law's ellipticity linked into its +multipoles) is seen by the declarations of every component holding it, so each +can convert it; the same conversion of the same priors is made once, under the +component the priors' samples column is named after. + An angle is periodic, and a conversion fixes where its branch cut falls: a position angle in ``[-45, 135)`` whose posterior peaks near 135 is split in two, and its corner plot shows a double peak that is not there. A conversion returns -such a value as ``Periodic(angle, period)`` and the samples are recentred on -their (weighted) circular mean, so the cut sits opposite the peak. +such a value as ``Periodic(angle, period)``. For a plot (``recentre=True``) the +samples are recentred on their (weighted) circular mean, so the cut sits +opposite the peak. The latent output (``latent.csv``) keeps the conversion's own +range, so the same parameter has the same range in every fit and fits can be +compared; a posterior straddling the cut is then split there, and its median and +errors in ``latent.results`` with it. """ from typing import Callable, Dict, List, Optional, Tuple import numpy as np -from autonerves import conf - from autofit.text import formatter as frm LatentFunction = Callable[..., Dict[str, np.ndarray]] @@ -159,10 +166,9 @@ def parameter_labels_with_superscripts_latex(self) -> List[str]: @property def parameter_indices_by_component(self) -> Dict[str, List[int]]: """As ``AbstractPriorModel.parameter_indices_by_component``, over the latent set.""" - groups = {} - for i, path in enumerate(self.component_paths): - groups.setdefault(path[0] if path else "model", []).append(i) - return groups + from autofit.mapper.prior_model.abstract import indices_by_top_level_component + + return indices_by_top_level_component(self.component_paths) @property def parameter_indices_by_latent_component(self) -> Dict[str, List[int]]: @@ -231,7 +237,7 @@ def _owner_path(prior_path, leaf: str) -> Tuple[str, ...]: def latent_parameters_from( - model, parameter_array: np.ndarray, weights=None + model, parameter_array: np.ndarray, weights=None, recentre: bool = False ) -> LatentParameters: """ Apply every component's declared conversions to an array of samples of the @@ -241,49 +247,74 @@ def latent_parameters_from( Parameters ---------- weights - The weight of each sample, used to centre a ``Periodic`` latent parameter - on its posterior rather than on the prior volume; equal by default. + The weight of each sample, used with ``recentre`` to centre a + ``Periodic`` latent parameter on its posterior rather than on the prior + volume; equal by default. + recentre + Whether to recentre each ``Periodic`` latent parameter on its circular + mean (for a plot), rather than keep the range the conversion gives it. """ + from autofit.mapper.prior_model.abstract import superscripts_from_component_paths + parameter_array = np.asarray(parameter_array) n_samples = parameter_array.shape[0] - owners = model._prior_owner_and_leaf_names + holders = model._prior_holders names = model.parameter_names superscripts = model.superscripts component_paths = model.component_paths paths = model.unique_prior_paths - # Which free parameters each component owns, by leaf name -> model index. + # Every component holding a free parameter, with what it holds by leaf name: + # the model index and the holder (prior path, component path) there. A + # shared prior is held by each component it sits in. indices_by_owner = {} - for i, (owner, leaf) in enumerate(owners): - indices_by_owner.setdefault(id(owner), (owner, {}))[1][leaf] = i + for i, prior_holders in enumerate(holders): + for holder in prior_holders: + prior_path, component_path, owner, leaf = holder + free = indices_by_owner.setdefault(id(owner), (owner, {}))[1] + free.setdefault(leaf, (i, prior_path, component_path)) + + # A component converts its own priors before one that only shares them, so a + # conversion made by both is filed under the one the samples are named after. + def borrowed(entry): + owner, free = entry + return sum(holders[i][0][2] is not owner for i, _, _ in free.values()) # Resolve every applicable declaration first: which indices it consumes and # what it yields, keyed by the index it is inserted at. insert_at = {} consumed = set() - for owner, free in indices_by_owner.values(): + made = set() + for owner, free in sorted(indices_by_owner.values(), key=borrowed): cls = getattr(owner, "cls", None) if cls is None: continue for replaced, function in latent_parameters_for_class(cls).items(): if not all(name in free for name in replaced): continue - if any(free[name] in consumed for name in replaced): + replaced_indices = tuple(free[name][0] for name in replaced) + if (function, replaced_indices) in made: continue + made.add((function, replaced_indices)) values = _flat_fixed_values(owner) values.update( - {name: parameter_array[:, index] for name, index in free.items()} + { + name: parameter_array[:, index] + for name, (index, _, _) in free.items() + } ) latent = function(**values) - first = min(free[name] for name in replaced) - insert_at[first] = [ + first_name = min(replaced, key=lambda name: free[name][0]) + first, prior_path, component_path = free[first_name] + insert_at.setdefault(first, []).extend( ( - _owner_path(paths[first], owners[first][1]) + (name,), + _owner_path(prior_path, first_name) + (name,), + component_path, name, np.broadcast_to( ( - value.recentred(weights) + (value.recentred(weights) if recentre else value.values) if isinstance(value, Periodic) else np.asarray(value, dtype=float) ), @@ -291,20 +322,19 @@ def latent_parameters_from( ), ) for name, value in latent.items() - ] - consumed.update(free[name] for name in replaced) + ) + consumed.update(replaced_indices) out_names, out_superscripts, out_paths, out_columns, out_mask = [], [], [], [], [] out_full_paths = [] for i in range(len(names)): - if i in insert_at: - for full_path, name, column in insert_at[i]: - out_names.append(name) - out_superscripts.append(superscripts[i]) - out_paths.append(component_paths[i]) - out_full_paths.append(full_path) - out_columns.append(column) - out_mask.append(True) + for full_path, component_path, name, column in insert_at.get(i, []): + out_names.append(name) + out_superscripts.append(superscripts[i]) + out_paths.append(component_path) + out_full_paths.append(full_path) + out_columns.append(column) + out_mask.append(True) if i in consumed: continue out_names.append(names[i]) @@ -314,6 +344,14 @@ def latent_parameters_from( out_columns.append(parameter_array[:, i]) out_mask.append(False) + # A latent parameter of a component that only shares the prior is labelled + # by that component, not by the one the prior's column is named after. + labels = superscripts_from_component_paths(component_paths + out_paths) + out_superscripts = [ + labels[path] if path else superscript + for path, superscript in zip(out_paths, out_superscripts) + ] + return LatentParameters( names=out_names, superscripts=out_superscripts, diff --git a/autofit/non_linear/analysis/latent.py b/autofit/non_linear/analysis/latent.py index 147749fd7..2ce347a22 100644 --- a/autofit/non_linear/analysis/latent.py +++ b/autofit/non_linear/analysis/latent.py @@ -29,6 +29,8 @@ import numpy as np +from autonerves import conf + from autofit import exc from autofit.non_linear.jax_compile import log_on_first_compile from autofit.non_linear.samples.sample import Sample @@ -77,18 +79,24 @@ def variables(analysis, parameters, model): def _model_latent_parameters(samples: Samples): """ - The model's declared latent parameters over the samples, recentred on the - posterior where periodic, or ``None`` when no component declares any (or - the samples carry no model that can say). + The model's declared latent parameters over the samples, or ``None`` when + ``output.yaml``'s ``latent_model_parameters`` is off, no component declares + any, or the samples carry no model that can say. + + A periodic one (an angle) keeps the range its conversion gives it rather than + being recentred on this fit's posterior, so the column has the same range in + every fit (see ``autofit/mapper/prior_model/latent_parameters.py``). """ + try: + if not conf.instance["output"]["latent_model_parameters"]: + return None + except KeyError: + pass model = getattr(samples, "model", None) if model is None or not hasattr(model, "latent_parameters_from"): return None try: - parameter_array = np.asarray(samples.parameter_lists) - latent = model.latent_parameters_from( - parameter_array, weights=samples.weight_list - ) + latent = model.latent_parameters_from(np.asarray(samples.parameter_lists)) except Exception: logger.warning( "compute_latent_samples: the model's latent parameters could not be " diff --git a/autofit/non_linear/plot/nest_plotters.py b/autofit/non_linear/plot/nest_plotters.py index 840a4a116..c7eba5276 100644 --- a/autofit/non_linear/plot/nest_plotters.py +++ b/autofit/non_linear/plot/nest_plotters.py @@ -56,7 +56,7 @@ def corner_anesthetic( if latent: latent_parameters = model.latent_parameters_from( - parameter_array, weights=samples.weight_list + parameter_array, weights=samples.weight_list, recentre=True ) labels = latent_parameters.parameter_labels_with_superscripts_latex parameter_array = latent_parameters.parameter_array diff --git a/autofit/non_linear/search/posterior_kind.py b/autofit/non_linear/search/posterior_kind.py index df0827c1d..92fe9e435 100644 --- a/autofit/non_linear/search/posterior_kind.py +++ b/autofit/non_linear/search/posterior_kind.py @@ -18,6 +18,7 @@ the nested samplers. ``NonLinearSearch.plot_results`` plots through ``plotter_for``. """ +import logging import warnings from typing import Optional @@ -27,6 +28,8 @@ from autofit.non_linear.search.capabilities import PosteriorKind +logger = logging.getLogger(__name__) + class PosteriorDefaults: kind: PosteriorKind = None @@ -131,14 +134,14 @@ def plot_results(self, search, samples): with warnings.catch_warnings(): warnings.simplefilter("ignore") - if self.should_plot("corner_anesthetic"): - corner_anesthetic(samples=samples, path=path, format="png") + corner = self.should_plot("corner_anesthetic") - per_component = self.should_plot( - "corner_anesthetic_components", default=True - ) + if corner: + corner_anesthetic(samples=samples, path=path, format="png") - if per_component: + # An older config without the key: the per-component plots follow + # the full one, so switching that off switches them off too. + if self.should_plot("corner_anesthetic_components", default=corner): self._corner_per_component( corner_anesthetic, samples, @@ -155,12 +158,17 @@ def plot_latent_results(self, search, samples): ``corner_anesthetic_latent`` independently of the plots above, so it can be the only corner plot or sit beside them; skipped when no component declares anything, as it would repeat the plain plot, and per component - only for the components that have a latent parameter. + (``corner_anesthetic_latent_components``) only for the components that + have a latent parameter. Skipped in test mode like every other plot. Latent output is made after the fit, not at every ``iterations_per_full_update`` (``SearchUpdater.visualize``), the same rule as ``latent.csv``. """ from autofit.non_linear.plot import corner_anesthetic + from autofit.non_linear.test_mode import skip_visualization + + if skip_visualization(): + return if not self.should_plot("corner_anesthetic_latent", default=False): return @@ -170,9 +178,21 @@ def plot_latent_results(self, search, samples): with warnings.catch_warnings(): warnings.simplefilter("ignore") - latent = samples.model.latent_parameters_from( - np.asarray(samples.parameter_lists) - ) + # The conversions are a component's own code, run here outside the + # plot's exception handling: one that raises is logged and the fit + # carries on without the latent plots, as it does without the + # latent columns of ``latent.csv``. + try: + latent = samples.model.latent_parameters_from( + np.asarray(samples.parameter_lists) + ) + except Exception: + logger.warning( + "The model's latent parameters could not be computed, so " + "their corner plots are not made.", + exc_info=True, + ) + return if not latent.has_latent: return @@ -189,7 +209,7 @@ def plot_latent_results(self, search, samples): # repeat the plot above), and only the components with a latent # parameter (the others' plots would repeat their plain ones). if ( - self.should_plot("corner_anesthetic_components", default=True) + self.should_plot("corner_anesthetic_latent_components", default=True) and len(latent.parameter_indices_by_component) > 1 ): self._corner_per_component( diff --git a/test_autofit/analysis/test_latent.py b/test_autofit/analysis/test_latent.py index 1624170b7..4c5a348c4 100644 --- a/test_autofit/analysis/test_latent.py +++ b/test_autofit/analysis/test_latent.py @@ -353,3 +353,16 @@ def log_likelihood_function(self, instance): def test_no_latents_anywhere_gives_none(): assert latent_samples_from(NoLatentAnalysis(), _samples([_sample()])) is None + + +def test_model_latent_parameters_switched_off_in_output_config(): + """``output.yaml``'s ``latent_model_parameters: false`` leaves the model's + declared latent parameters out of the latent output.""" + from autonerves import conf + + original = conf.instance["output"]["latent_model_parameters"] + conf.instance["output"]["latent_model_parameters"] = False + try: + assert latent_samples_from(NoLatentAnalysis(), _shear_samples()) is None + finally: + conf.instance["output"]["latent_model_parameters"] = original diff --git a/test_autofit/mapper/model/test_latent_parameters.py b/test_autofit/mapper/model/test_latent_parameters.py index fd8e76e3a..ae0803d2b 100644 --- a/test_autofit/mapper/model/test_latent_parameters.py +++ b/test_autofit/mapper/model/test_latent_parameters.py @@ -158,13 +158,26 @@ def test__latent_parameters__periodic_angle_is_recentred_with_the_sample_weights # arctan2(comp_0, comp_1) for these straddles +-180. samples = np.array([[0.0, 0.1, -1.0], [0.0, -0.1, -1.0]]) - latent = model.latent_parameters_from(samples, weights=[1.0, 1.0]) + latent = model.latent_parameters_from(samples, weights=[1.0, 1.0], recentre=True) angle = latent.parameter_array[:, 2] assert np.ptp(angle) == pytest.approx(11.42, abs=0.01) # not ~348 assert latent.names == ["centre", "strength", "angle"] +def test__latent_parameters__periodic_angle_keeps_the_conversion_range_by_default(): + # The latent output is not recentred, so a column has the range the + # conversion gives it in every fit, whatever this fit's posterior. + model = _component(MockPeriodicComponent) + samples = np.array([[0.0, 0.1, -1.0], [0.0, -0.1, -1.0]]) + + latent = model.latent_parameters_from(samples, weights=[1.0, 1.0]) + + angle = latent.parameter_array[:, 2] + assert angle == pytest.approx(np.degrees(np.arctan2([0.1, -0.1], [-1.0, -1.0]))) + assert np.ptp(angle) > 340.0 + + def test__latent_parameters__grouping_by_latent_component_and_full_paths(): # The source has no latent parameter, so it has no group of its own in # the latent grouping; every parameter keeps its full model path, a latent @@ -215,3 +228,99 @@ def test__latent_parameters__shared_prior_takes_the_path_of_its_samples_column() ("galaxies", "lens", "mass", "strength"), ("galaxies", "lens", "mass", "angle"), ] + + +class MockMultipole: + # Holds the ellipticity of the mass it perturbs (linked to it) and declares + # only its own components. + latent_parameters = { + ( + "multipole_comps_0", + "multipole_comps_1", + ): lambda multipole_comps_0, multipole_comps_1, **kwargs: _polar( + multipole_comps_0, multipole_comps_1 + ) + } + + def __init__(self, ell_comps=(0.0, 0.0), multipole_comps=(0.0, 0.0)): + self.ell_comps = ell_comps + self.multipole_comps = multipole_comps + + +class MockMass: + latent_parameters = { + ("ell_comps_0", "ell_comps_1"): lambda ell_comps_0, ell_comps_1, **kwargs: { + "axis_ratio": 1.0 - np.hypot(ell_comps_0, ell_comps_1), + "angle": np.degrees(np.arctan2(ell_comps_0, ell_comps_1)), + } + } + + def __init__(self, ell_comps=(0.0, 0.0)): + self.ell_comps = ell_comps + + +def _tuple_prior(*names): + from autofit.mapper.prior.tuple_prior import TuplePrior + + prior = TuplePrior() + for name in names: + setattr(prior, name, af.UniformPrior(-1.0, 1.0)) + return prior + + +@pytest.mark.parametrize("mass_first", [True, False]) +def test__latent_parameters__shared_prior_is_converted_by_every_holder(mass_first): + # A power law's ellipticity linked into its multipole: whichever component + # the priors' samples column is named after, the mass still converts its + # ellipticity to an axis ratio and angle, and the multipole its own + # components. + mass = af.Model(MockMass) + mass.ell_comps = _tuple_prior("ell_comps_0", "ell_comps_1") + multipole = af.Model(MockMultipole) + multipole.ell_comps = mass.ell_comps + multipole.multipole_comps = _tuple_prior("multipole_comps_0", "multipole_comps_1") + components = ( + dict(mass=mass, multipole=multipole) + if mass_first + else dict(multipole=multipole, mass=mass) + ) + model = af.Collection(lens=af.Model(MockGalaxyMany, **components)) + + latent = model.latent_parameters_from(np.array([[0.3, 0.4, 0.0, 0.5]])) + + assert sorted(latent.names) == ["angle", "angle", "axis_ratio", "strength"] + by_path = dict(zip(latent.paths, latent.parameter_array[0])) + assert by_path[("lens", "mass", "axis_ratio")] == pytest.approx(0.5) + assert by_path[("lens", "mass", "angle")] == pytest.approx( + np.degrees(np.arctan2(0.3, 0.4)) + ) + assert by_path[("lens", "multipole", "strength")] == pytest.approx(0.5) + assert ( + dict(zip(latent.paths, latent.superscripts))[("lens", "mass", "axis_ratio")] + == "lens.mass" + ) + assert ( + dict(zip(latent.paths, latent.superscripts))[("lens", "multipole", "strength")] + == "lens.multipole" + ) + + +class MockGalaxyMany: + def __init__(self, mass=None, multipole=None): + self.mass = mass + self.multipole = multipole + + +def test__latent_parameters__root_group_does_not_collide_with_a_component_named_model(): + model = af.Collection( + model=af.Model(af.m.MockClassx2NoSuperScript), + ) + model.free = af.UniformPrior(0.0, 1.0) + + latent = model.latent_parameters_from(np.zeros((1, model.prior_count))) + + assert model.parameter_indices_by_component == {"model": [0, 1], "model_root": [2]} + assert latent.parameter_indices_by_component == { + "model": [0, 1], + "model_root": [2], + } diff --git a/test_autofit/mapper/model/test_model_mapper.py b/test_autofit/mapper/model/test_model_mapper.py index ffe14d80c..d9dd176fc 100644 --- a/test_autofit/mapper/model/test_model_mapper.py +++ b/test_autofit/mapper/model/test_model_mapper.py @@ -255,15 +255,73 @@ def test__superscripts__three_levels_deep_abbreviates_all_but_the_first(self): assert model.superscripts == ["source.pix.reg", "source.pix.reg"] from autofit.mapper.prior_model.abstract import ( - superscript_from_component_path, + superscripts_from_component_paths, ) - assert superscript_from_component_path(("lens",)) == "lens" - assert superscript_from_component_path(("lens", "bulge")) == "lens.bulge" - assert ( - superscript_from_component_path(("a", "bc", "defg", "hijkl")) - == "a.bc.def.hij" + assert superscripts_from_component_paths([("lens",), ("lens", "bulge")]) == { + ("lens",): "lens", + ("lens", "bulge"): "lens.bulge", + } + assert superscripts_from_component_paths([("a", "bc", "defg", "hijkl")]) == { + ("a", "bc", "defg", "hijkl"): "a.bc.def.hij" + } + + def test__superscripts__deep_paths_stay_unique(self): + # Cutting every deep name to three characters would label both shears + # lens.bul.she; each name keeps as many characters as tell it from its + # siblings instead. + from autofit.mapper.prior_model.abstract import ( + superscripts_from_component_paths, + ) + + paths = [ + ("lens", "bulge_inner", "shear"), + ("lens", "bulge_outer", "shear"), + ("lens", "disk"), + ] + labels = superscripts_from_component_paths(paths) + + assert labels == { + ("lens", "bulge_inner", "shear"): "lens.bulge_i.she", + ("lens", "bulge_outer", "shear"): "lens.bulge_o.she", + ("lens", "disk"): "lens.disk", + } + + # A name cut short is cut the same way everywhere: the basis's own + # priors and those of a profile in it read lens.bul and lens.bul.0. + labels = superscripts_from_component_paths( + [("lens", "bulge"), ("lens", "bulge", "0"), ("lens", "bul")] + ) + assert labels == { + ("lens", "bulge"): "lens.bulg", + ("lens", "bulge", "0"): "lens.bulg.0", + ("lens", "bul"): "lens.bul", + } + assert len(set(labels.values())) == len(labels) + + def test__superscripts__deep_paths_in_a_model_stay_unique(self): + model = af.Collection( + lens=af.Model( + MockGalaxy, + bulge=af.Model( + MockGalaxy, bulge=af.Model(af.m.MockClassx2NoSuperScript) + ), + disk=af.Model( + MockGalaxy, bulge=af.Model(af.m.MockClassx2NoSuperScript) + ), + ) ) + model.lens.bulge_inner = model.lens.bulge + model.lens.bulge_outer = model.lens.disk + del model.lens.bulge + del model.lens.disk + + assert model.superscripts == [ + "lens.bulge_i.bul", + "lens.bulge_i.bul", + "lens.bulge_o.bul", + "lens.bulge_o.bul", + ] def test__superscripts__list_index_kept_only_when_priors_are_not_shared(self): # A basis whose profiles share one set of priors: the index is one of diff --git a/test_autofit/non_linear/plot/test_nest_plotters.py b/test_autofit/non_linear/plot/test_nest_plotters.py index a4c841d46..aea9e2f62 100644 --- a/test_autofit/non_linear/plot/test_nest_plotters.py +++ b/test_autofit/non_linear/plot/test_nest_plotters.py @@ -13,7 +13,7 @@ def __init__(self, labels): self.parameter_labels_with_superscripts_latex = labels self.total_free_parameters = len(labels) - def latent_parameters_from(self, parameter_array, weights=None): + def latent_parameters_from(self, parameter_array, weights=None, recentre=False): # The latent set of this mock: the first two parameters become their sum. from autofit.mapper.prior_model.latent_parameters import LatentParameters diff --git a/test_autofit/non_linear/search/test_family_bases.py b/test_autofit/non_linear/search/test_family_bases.py index 26fe4ddb7..5d1acfa0d 100644 --- a/test_autofit/non_linear/search/test_family_bases.py +++ b/test_autofit/non_linear/search/test_family_bases.py @@ -508,3 +508,106 @@ def test_weighted_plot_latent_results_single_component_has_no_duplicate( "corner_anesthetic", "corner_anesthetic_latent", ] + + +def _without_key(monkeypatch, missing, values): + # A config written before ``missing`` existed (should_plot raises KeyError + # without a default), with the given value for every other key. + from autofit.non_linear.search.posterior_kind import WeightedDefaults + + def should_plot(self, name, default=None): + if name == missing: + if default is None: + raise KeyError(name) + return default + return values[name] + + monkeypatch.setattr(WeightedDefaults, "should_plot", should_plot) + + +def test_weighted_plot_results_components_follow_corner_anesthetic_when_key_absent( + monkeypatch, tmp_path +): + # Switching the corner plot off in an older config switches off the + # per-component plots it does not mention, rather than leaving them on. + _without_key( + monkeypatch, "corner_anesthetic_components", {"corner_anesthetic": False} + ) + + calls = _weighted_plot_calls(_lens_like_model(), monkeypatch, tmp_path) + + assert calls == [] + + +def _shear_model(shear_cls): + return af.Collection( + lens=af.Model( + _MockGalaxy, + light=af.Model( + shear_cls, + gamma_1=af.UniformPrior(-1.0, 1.0), + gamma_2=af.UniformPrior(-1.0, 1.0), + ), + ), + source=af.Model(_MockGalaxy, light=af.Model(af.m.MockClassx2NoSuperScript)), + ) + + +def test_weighted_plot_latent_results_components_have_their_own_switch( + monkeypatch, tmp_path +): + # The latent plot alone: its per-component plots are switched separately. + from autofit.non_linear.search.posterior_kind import WeightedDefaults + + monkeypatch.setattr( + WeightedDefaults, + "should_plot", + lambda self, name, default=None: name == "corner_anesthetic_latent", + ) + + calls = _weighted_plot_calls( + _shear_model(_MockShear), monkeypatch, tmp_path, latent=True + ) + + assert [call["filename"] for call in calls] == ["corner_anesthetic_latent"] + + +class _MockRaisingShear(_MockShear): + latent_parameters = { + ("gamma_1", "gamma_2"): lambda gamma_1, gamma_2, **kwargs: 1 / 0 + } + + +def test_weighted_plot_latent_results_logs_a_raising_conversion( + monkeypatch, tmp_path, caplog +): + # A component's conversion is its own code: one that raises is logged and + # no latent plot is made, rather than failing the fit's final output. + from autofit.non_linear.search.posterior_kind import WeightedDefaults + + monkeypatch.setattr( + WeightedDefaults, "should_plot", lambda self, name, default=None: True + ) + + with caplog.at_level("WARNING"): + calls = _weighted_plot_calls( + _shear_model(_MockRaisingShear), monkeypatch, tmp_path, latent=True + ) + + assert not any(call.get("latent") for call in calls) + assert "latent parameters could not be computed" in caplog.text + + +def test_weighted_plot_latent_results_skipped_in_test_mode(monkeypatch, tmp_path): + from autofit.non_linear.search.posterior_kind import WeightedDefaults + + monkeypatch.setattr( + WeightedDefaults, "should_plot", lambda self, name, default=None: True + ) + monkeypatch.setattr("autofit.non_linear.test_mode.skip_visualization", lambda: True) + + calls = _weighted_plot_calls( + _shear_model(_MockShear), monkeypatch, tmp_path, latent=True + ) + + assert not any(call.get("latent") for call in calls) diff --git a/test_autofit/non_linear/search/test_updater.py b/test_autofit/non_linear/search/test_updater.py index b16adb1f7..670620afb 100644 --- a/test_autofit/non_linear/search/test_updater.py +++ b/test_autofit/non_linear/search/test_updater.py @@ -312,3 +312,57 @@ def test__visualize__no_latent_plotter_is_fine(): ) updater._plot_results.assert_called_once() + + +class _MockRaisingComponent: + latent_parameters = {("one", "two"): lambda one, two, **kwargs: 1 / 0} + + def __init__(self, one=0.0, two=0.0): + self.one = one + self.two = two + + +def test__visualize__raising_latent_conversion_is_logged_not_raised( + monkeypatch, tmp_path, caplog +): + """ + The final ``visualize`` of a fit makes the latent plots; a component whose + conversion raises is logged there and the fit's output completes. + """ + from types import SimpleNamespace + from functools import partial + + import autofit as af + from autofit.non_linear.search.posterior_kind import WeightedDefaults + + monkeypatch.setattr( + WeightedDefaults, "should_plot", lambda self, name, default=None: True + ) + model = af.Collection( + component=af.Model( + _MockRaisingComponent, + one=af.UniformPrior(0.0, 1.0), + two=af.UniformPrior(0.0, 1.0), + ) + ) + samples = SimpleNamespace( + model=model, parameter_lists=[[0.1, 0.2]] * 3, weight_list=[1.0] * 3 + ) + search = SimpleNamespace(paths=SimpleNamespace(image_path=tmp_path)) + updater = _visualizing_updater( + partial(WeightedDefaults().plot_latent_results, search) + ) + analysis = MagicMock() + analysis.should_visualize.return_value = True + + with caplog.at_level(logging.WARNING): + updater.visualize( + model=model, + analysis=analysis, + during_analysis=False, + samples_summary=MagicMock(), + samples=samples, + ) + + updater._plot_results.assert_called_once_with(samples=samples) + assert "latent parameters could not be computed" in caplog.text