diff --git a/autofit/__init__.py b/autofit/__init__.py index 1eda9f2f3..add6579db 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.latent_parameters 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/output.yaml b/autofit/config/output.yaml index 19f16e975..bbb2d7d48 100644 --- a/autofit/config/output.yaml +++ b/autofit/config/output.yaml @@ -86,12 +86,13 @@ 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. 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 24f805e1d..8a1d3e44e 100644 --- a/autofit/config/visualize/plots_search.yaml +++ b/autofit/config/visualize/plots_search.yaml @@ -1,5 +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_? 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 02f842663..bbea7b6d0 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 @@ -165,6 +178,94 @@ def paths_to_tree(paths: List[Tuple[str, ...]], tree: Optional[dict] = None) -> return tree +def superscripts_from_component_paths( + component_paths: Iterable[Tuple[str, ...]], +) -> Dict[Tuple[str, ...], str]: + """ + 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. + """ + 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): """ Abstract model that maps a set of priors to a particular class. Must be @@ -268,8 +369,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} @@ -745,7 +846,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 +896,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 +1113,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 +1127,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 +1624,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 +1634,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 +1664,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 +1775,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 +1956,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,38 +2577,193 @@ def parameter_labels(self) -> List[str]: return parameter_labels + def _prior_holder( + self, path: Path, sibling_paths: List[Path] + ) -> Tuple[Path, Tuple[str, ...], object, str]: + """ + 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 + + component_path = path[:-1] + same_length = all(len(other) == len(component_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) + + return tuple(path), tuple(names), owner, path[-1] + @property - def superscripts(self) -> List[str]: + @frozen_cache + def _prior_holders(self) -> List[List[Tuple[Path, Tuple[str, ...], object, str]]]: """ - Returns a list of the model component superscripts for every parameter in a model. + 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. + 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 - 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 - with this string (corresponding to the parameters `centre`, `normalization` and `sigma`) will - be returned. + @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 the path its samples column is named + after) and the prior's leaf name, for example + ``(, "ell_comps_0")``. + """ + return [(holders[0][2], holders[0][3]) for holders in self._prior_holders] - For a `Collection`, the name of the inner model components are used. + def latent_parameters_from( + self, parameter_array, weights=None, recentre: bool = False + ) -> "LatentParameters": + """ + The parameters of this model after each component's declared conversions + (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.latent_parameters``. - 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. + Parameters + ---------- + parameter_array + Samples of the model's free parameters, shape ``(n_samples, prior_count)``. + weights + 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, recentre=recentre + ) - This is used for displaying model results as text and for visualization. + @property + def has_latent_parameters(self) -> bool: + """Whether any component of this model declares a conversion that applies to it.""" + return self.latent_parameters_from(np.zeros((1, self.prior_count))).has_latent + + @property + def component_paths(self) -> List[Path]: """ + The named model components that own each unique prior, ordered by prior id. - prior_paths = self.unique_prior_paths + 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")``. - tuple_filter = TuplePathModifier(self) + 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. 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``). + """ + return [holders[0][1] for holders in self._prior_holders] - prior_paths = map(tuple_filter, prior_paths) + @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]}``. - superscripts = [path[-2] if len(path) > 1 else None for path in prior_paths] + Parameters whose priors sit directly on the model (no named component) + are grouped under ``"model"`` (``"model_root"`` if a component is itself + named ``model``). + """ + return indices_by_top_level_component(self.component_paths) + @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 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. + + 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 + 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. + """ + component_paths = self.component_paths + labels = superscripts_from_component_paths(component_paths) return [ - superscript if not superscript_overwrite else superscript_overwrite - for superscript, superscript_overwrite in zip( - superscripts, self.superscripts_overwrite_via_config + labels[path] if path else (superscript_overwrite or None) + for path, superscript_overwrite in zip( + 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 new file mode 100644 index 000000000..8e6e95609 --- /dev/null +++ b/autofit/mapper/prior_model/latent_parameters.py @@ -0,0 +1,364 @@ +""" +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 +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: + 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 latent +name to array. The declarations of a class's bases are inherited, so a subclass +adds to them rather than restating them. + +``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 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. + +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)``. 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 autofit.text import formatter as frm + +LatentFunction = Callable[..., Dict[str, np.ndarray]] + + +class Periodic: + def __init__(self, values, period: float): + """ + 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 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. + """ + 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 latent_parameters_for_class(cls) -> Dict[Tuple[str, ...], LatentFunction]: + """ + 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("latent_parameters", {}) or {}) + return declarations + + +class LatentParameters: + def __init__( + self, + names: List[str], + superscripts: List[Optional[str]], + component_paths: List[Tuple[str, ...]], + parameter_array: np.ndarray, + latent_mask: List[bool], + paths: Optional[List[Tuple[str, ...]]] = None, + ): + """ + 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 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 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.latent_mask = latent_mask + self.paths = paths + + @property + def has_latent(self) -> bool: + """Whether any declaration was applied, so the set differs from the model's own.""" + return any(self.latent_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 latent set.""" + 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]]: + """ + ``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]: + """ + 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 _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, recentre: bool = False +) -> LatentParameters: + """ + Apply every component's declared conversions to an array of samples of the + model; see the module docstring. Called through + ``AbstractPriorModel.latent_parameters_from``. + + Parameters + ---------- + weights + 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] + + holders = model._prior_holders + names = model.parameter_names + superscripts = model.superscripts + component_paths = model.component_paths + paths = model.unique_prior_paths + + # 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, 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() + 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 + 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() + } + ) + latent = function(**values) + 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(prior_path, first_name) + (name,), + component_path, + name, + np.broadcast_to( + ( + (value.recentred(weights) if recentre else value.values) + if isinstance(value, Periodic) + else np.asarray(value, dtype=float) + ), + (n_samples,), + ), + ) + for name, value in latent.items() + ) + consumed.update(replaced_indices) + + out_names, out_superscripts, out_paths, out_columns, out_mask = [], [], [], [], [] + out_full_paths = [] + for i in range(len(names)): + 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]) + 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) + + # 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, + component_paths=out_paths, + parameter_array=( + np.column_stack(out_columns) if out_columns else parameter_array + ), + 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..2ce347a22 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 @@ -28,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 @@ -74,6 +77,36 @@ 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, 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: + 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 " + "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 +165,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 +199,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 +234,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 +280,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 +308,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 +323,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 +340,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 +371,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 +385,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 64867ed90..c7eba5276 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, + latent=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 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.latent_parameters_from``. + """ config_dict = conf.instance["visualize"]["plots_settings"]["corner_anesthetic"] from anesthetic.samples import NestedSamples @@ -26,15 +52,40 @@ def corner_anesthetic(samples, path=None, filename="corner_anesthetic", format=" model = samples.model + parameter_array = np.asarray(samples.parameter_lists) + + if latent: + latent_parameters = model.latent_parameters_from( + parameter_array, weights=samples.weight_list, recentre=True + ) + labels = latent_parameters.parameter_labels_with_superscripts_latex + parameter_array = latent_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 + # 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. + 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=model.parameter_labels_with_superscripts_latex, + columns=columns, + labels=labels, ) try: @@ -63,7 +114,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 +129,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/autofit/non_linear/search/posterior_kind.py b/autofit/non_linear/search/posterior_kind.py index 83341674e..92fe9e435 100644 --- a/autofit/non_linear/search/posterior_kind.py +++ b/autofit/non_linear/search/posterior_kind.py @@ -18,13 +18,18 @@ the nested samplers. ``NonLinearSearch.plot_results`` plots through ``plotter_for``. """ +import logging import warnings from typing import Optional +import numpy as np + from autonerves import conf from autofit.non_linear.search.capabilities import PosteriorKind +logger = logging.getLogger(__name__) + class PosteriorDefaults: kind: PosteriorKind = None @@ -37,12 +42,28 @@ 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 + 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 @@ -100,21 +121,129 @@ 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") + + corner = self.should_plot("corner_anesthetic") + + if corner: + corner_anesthetic(samples=samples, path=path, format="png") + + # 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, + path, + groups=samples.model.parameter_indices_by_component, + ) + + 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 + (``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 + + path = search.paths.image_path / "search" + + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + + # 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 + + 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_latent_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, 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 (the + latent plots check that on the model's components, since ``groups`` + then holds only those with a latent parameter). + """ + if len(groups) < 2 and not latent: + return + + stem = "corner_anesthetic_latent" if latent 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, + latent=latent, + ) + class PointDefaults(PosteriorDefaults): kind = PosteriorKind.POINT 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..4c5a348c4 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,99 @@ 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 + + +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 new file mode 100644 index 000000000..ae0803d2b --- /dev/null +++ b/test_autofit/mapper/model/test_latent_parameters.py @@ -0,0 +1,326 @@ +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: + latent_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. + latent_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. + 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) + 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__latent_parameters__replace_components_in_place(): + model = _component(MockComponent) + samples = np.array([[0.5, 3.0, 4.0], [0.1, 0.0, 1.0]]) + + latent = model.latent_parameters_from(samples) + + 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__latent_parameters__fixed_values_reach_the_conversion_and_subclass_overrides(): + model = _component(MockScaledComponent, scale=2.0) + + latent = model.latent_parameters_from(np.array([[0.0, 3.0, 4.0]])) + + assert latent.names == ["centre", "scaled"] + assert latent.parameter_array[0, 1] == pytest.approx(10.0) + + +def test__latent_parameters__no_conversion_when_a_replaced_parameter_is_fixed(): + model = _component(MockComponent, comp=(0.0, 1.0)) + + latent = model.latent_parameters_from(np.array([[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__latent_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) + + latent = model.latent_parameters_from(rng.normal(size=(4, model.prior_count))) + + 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 latent.parameter_labels_with_superscripts_latex[1] == r"$s^{\rm lens.mass}$" + + +def test__latent_parameters__plain_model_passes_through(): + model = af.Model(af.m.MockClassx2NoSuperScript) + samples = np.array([[1.0, 2.0]]) + + latent = model.latent_parameters_from(samples) + + 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.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 + # 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__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]]) + + 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 + # 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]) + + +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"), + ] + + +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 3a7433545..d9dd176fc 100644 --- a/test_autofit/mapper/model/test_model_mapper.py +++ b/test_autofit/mapper/model/test_model_mapper.py @@ -24,6 +24,22 @@ 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 MockPixelization: + def __init__(self, regularization=None): + self.regularization = regularization + + class TestRegression: def test_set_tuple_instance(self): mm = af.ModelMapper() @@ -111,11 +127,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() @@ -140,21 +159,199 @@ 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}$", ] + 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__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.bulge"] * 3 + assert ( + model.parameter_labels_with_superscripts[0] + == r"one_label^{\rm galaxy.bulge}" + ) + + # 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] + } + + 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 ( + superscripts_from_component_paths, + ) + + 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 + # 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,12 +721,6 @@ def test_prior_prior_model_dict(self): == af.m.MockClassx2 ) - 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): @@ -552,10 +743,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 +827,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 +845,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 @@ -795,3 +984,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"] diff --git a/test_autofit/non_linear/plot/test_nest_plotters.py b/test_autofit/non_linear/plot/test_nest_plotters.py index 94c811e5e..aea9e2f62 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 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 + + 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:]] + ), + latent_mask=[True] + [False] * (parameter_array.shape[1] - 2), + ) + class MockSamples: def __init__(self): @@ -78,3 +92,89 @@ 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) + + +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__latent_plots_the_latent_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, latent=True) + + # 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 d67df4c57..5d1acfa0d 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,346 @@ 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: + 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 + + +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, latent=False): + 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, + weight_list=[1.0] * 3, + ) + defaults = WeightedDefaults() + defaults.plot_results(search=search, samples=samples) + if latent: + defaults.plot_latent_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_latent_corner_only_when_a_component_declares_one( + monkeypatch, tmp_path +): + from autofit.non_linear.search.posterior_kind import WeightedDefaults + + # 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 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 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( + _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, latent=True) + + 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 latent_calls[1]["parameter_indices"] == [0] # magnitude alone + + +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_latent", + ) + 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=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", + "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 a905eb0a5..670620afb 100644 --- a/test_autofit/non_linear/search/test_updater.py +++ b/test_autofit/non_linear/search/test_updater.py @@ -235,3 +235,134 @@ 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() + + +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 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 + )