diff --git a/autofit/mapper/prior/abstract.py b/autofit/mapper/prior/abstract.py index 57a05cff9..bdfe434b7 100644 --- a/autofit/mapper/prior/abstract.py +++ b/autofit/mapper/prior/abstract.py @@ -238,6 +238,7 @@ def project(self, samples, log_weight_list): samples=samples, log_weight_list=log_weight_list, id_=self.id, + **self.message._support_kwargs, ) return result diff --git a/autofit/messages/abstract.py b/autofit/messages/abstract.py index 58ac2669e..3a9015ba6 100644 --- a/autofit/messages/abstract.py +++ b/autofit/messages/abstract.py @@ -76,6 +76,7 @@ def _init_kwargs(self): return dict( log_norm=self.log_norm, id_=self.id, + **self._support_kwargs, ) def check_support(self) -> np.ndarray: @@ -100,6 +101,7 @@ def copy(self): result = cls( *(copy(params) for params in self.parameters), log_norm=self.log_norm, + **self._support_kwargs, ) result.id = self.id return result @@ -153,7 +155,10 @@ def __getitem__(self, index) -> "AbstractMessage": if index == (): return self else: - return cls(*(param[index] for param in self.parameters)) + return cls( + *(param[index] for param in self.parameters), + **self._support_kwargs, + ) def __setitem__(self, index, value): self._reset_cache() @@ -166,7 +171,8 @@ def merge(self, index, value): *( update_array(param0, index, param1) for param0, param1 in zip(self.parameters, value.parameters) - ) + ), + **self._support_kwargs, ) @classmethod @@ -205,6 +211,7 @@ def __mul__(self, other: Union["AbstractMessage", Real]) -> "AbstractMessage": *self.parameters, log_norm=log_norm, id_=self.id, + **self._support_kwargs, ) def __rmul__(self, other: "AbstractMessage") -> "AbstractMessage": @@ -220,6 +227,7 @@ def __truediv__(self, other: Union["AbstractMessage", Real]) -> "AbstractMessage *self.parameters, log_norm=log_norm, id_=self.id, + **self._support_kwargs, ) def __pow__(self, other: Real) -> "AbstractMessage": @@ -230,6 +238,7 @@ def __pow__(self, other: Real) -> "AbstractMessage": new_params, log_norm=log_norm, id_=self.id, + **self._support_kwargs, ) return new @@ -362,6 +371,7 @@ def update_invalid(self, other: "AbstractMessage") -> "AbstractMessage": *valid_parameters, log_norm=self.log_norm, id_=self.id, + **self._support_kwargs, ) return new @@ -429,12 +439,16 @@ def _reconstruct( parameters: Tuple[np.ndarray, ...], log_norm: float, id_, + support_kwargs: Optional[dict] = None, *args, ): + # ``support_kwargs`` defaults to None so pickles written before the + # limits became support state (3-tuple payloads) still load. return cls( *parameters, log_norm=log_norm, id_=id_, + **(support_kwargs or {}), ) def __reduce__(self): @@ -445,6 +459,7 @@ def __reduce__(self): self.parameters, self.log_norm, self.id, + self._support_kwargs, ), ) diff --git a/autofit/messages/composed_transform.py b/autofit/messages/composed_transform.py index 344fa68a9..63a2cf58d 100644 --- a/autofit/messages/composed_transform.py +++ b/autofit/messages/composed_transform.py @@ -160,6 +160,12 @@ def __call__(self, *args, **kwargs): def copy(self): return TransformedMessage(self.base_message, *self.transforms, id_=self.id) + @property + def _support_kwargs(self) -> dict: + # The base message's (base-space) support; the transformed message's + # own ``lower_limit`` / ``upper_limit`` stay +/-inf (PyAutoFit#1527). + return self.base_message._support_kwargs + def with_base(self, message: MessageInterface) -> "TransformedMessage": """ Creates a new TransformedMessage with the same id and transforms but a new @@ -203,7 +209,11 @@ def project( PyAutoFit#1382.) """ return TransformedMessage( - self.base_message.project(self._transform(samples), log_weight_list), + self.base_message.project( + self._transform(samples), + log_weight_list, + **self.base_message._support_kwargs, + ), *self.transforms, id_=self.id, ) @@ -398,15 +408,42 @@ def logpdf_gradient(self, x: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: return log_likelihood, gradient - def from_mode(self, mode: np.ndarray, covariance: np.ndarray, **kwargs): - jac = None + def from_mode(self, mode: np.ndarray, covariance, **kwargs): + """ + Build the message from a mode and covariance given in *physical* + space. + + ``mode`` is mapped physical -> base through the transform stack + (outermost transform first, exactly as ``_transform`` does) and the + covariance is pushed through the Jacobian of *every* transform on the + way, ``jac.quad`` being the inverse of the ``invquad`` composition + that ``variance`` applies base -> physical. A ``LinearOperator`` + covariance (the 0-d or n-d ``DiagonalMatrix`` the Laplace optimiser + hands over) is reduced to its diagonal first, which is all the base + ``from_mode`` reads. + + Physical-space ``lower_limit`` / ``upper_limit`` kwargs are dropped: + the base message lives in base space and keeps its own support + (PyAutoFit#1559). + """ + from autofit.mapper.operator import LinearOperator + + if isinstance(covariance, LinearOperator): + covariance = covariance.diagonal() + covariance = np.asanyarray(covariance) + + kwargs.pop("lower_limit", None) + kwargs.pop("upper_limit", None) + for _transform in reversed(self.transforms): mode, jac = _transform.transform_jac(mode) - - if covariance.shape != (): covariance = jac.quad(covariance) - return self.with_base(self.base_message.from_mode(mode, covariance, **kwargs)) + return self.with_base( + self.base_message.from_mode( + mode, covariance, **kwargs, **self.base_message._support_kwargs + ) + ) def update_invalid(self, other: "TransformedMessage") -> "MessageInterface": return self.with_base(self.base_message.update_invalid(other.base_message)) diff --git a/autofit/messages/interface.py b/autofit/messages/interface.py index 24ae2ea08..381ea975c 100644 --- a/autofit/messages/interface.py +++ b/autofit/messages/interface.py @@ -1,3 +1,4 @@ +import math from abc import ABC, abstractmethod from typing import Tuple, Iterator from typing import Union @@ -222,6 +223,55 @@ def is_valid(self) -> Union[np.ndarray, np.bool_]: def update_invalid(self, other: "MessageInterface") -> "MessageInterface": pass + @property + def _support_kwargs(self) -> dict: + """ + Constructor keyword arguments describing the *support* of this + message -- state that is not a natural parameter and therefore must + be carried explicitly through every rebuild (``copy``, ``__pow__``, + products, quotients, ``update_invalid``, ``from_natural_parameters``, + pickling). + + Unbounded families have no such state and return ``{}``; + ``TruncatedNormalMessage`` returns its ``lower_limit`` / + ``upper_limit`` and ``TransformedMessage`` delegates to its base + message (PyAutoFit#1559). + """ + return {} + + def _combined_support(self, *dists) -> dict: + """ + Support of the product of this message's density with ``dists``. + + The product of densities is supported on the *intersection* of the + factors' supports, so a truncated message multiplied by an unbounded + one keeps its limits, equal supports are a no-op, and overlapping + finite supports narrow to their overlap. Disjoint finite supports + leave no density to represent and raise ``MessageException``. + + The result class is always this message's class (a ``NormalMessage`` + times a truncated one stays a ``NormalMessage``): inside EP every + message on a variable shares the prior's class, so the asymmetric + user-only case is documented rather than special-cased. + """ + from .. import exc + + kw = self._support_kwargs + if not kw: + return kw + lo, hi = kw["lower_limit"], kw["upper_limit"] + for dist in self._iter_dists(dists): + if not isinstance(dist, MessageInterface): + continue + other = dist._support_kwargs + lo = max(lo, other.get("lower_limit", -math.inf)) + hi = min(hi, other.get("upper_limit", math.inf)) + if not lo < hi: + raise exc.MessageException( + f"product of messages has empty support ({lo}, {hi})" + ) + return dict(lower_limit=lo, upper_limit=hi) + def sum_natural_parameters(self, *dists: "MessageInterface") -> "MessageInterface": """return the unnormalised result of multiplying the pdf of this distribution with another distribution of the same @@ -238,18 +288,24 @@ def sum_natural_parameters(self, *dists: "MessageInterface") -> "MessageInterfac return self.from_natural_parameters( new_params, id_=self.id, + **self._combined_support(*dists), ) def sub_natural_parameters(self, other: "MessageInterface") -> "MessageInterface": """return the unnormalised result of dividing the pdf of this distribution with another distribution of the same - type""" + type + + The quotient keeps this message's support: in EP a cavity division + is always between messages on the same variable, so the supports + agree and no intersection or check is needed.""" log_norm = self.log_norm - other.log_norm new_params = self.natural_parameters() - other.natural_parameters() return self.from_natural_parameters( new_params, log_norm=log_norm, id_=self.id, + **self._support_kwargs, ) @abstractmethod diff --git a/autofit/messages/truncated_normal.py b/autofit/messages/truncated_normal.py index 4c31a111a..2a1701b94 100644 --- a/autofit/messages/truncated_normal.py +++ b/autofit/messages/truncated_normal.py @@ -100,16 +100,23 @@ def __init__( f"TruncatedNormalMessage sigma cannot be negative, got sigma={sigma}." ) + # The truncation limits are *support*, not parameters: they are + # stored as attributes by ``AbstractMessage.__init__`` and carried + # through every rebuild via ``_support_kwargs`` (PyAutoFit#1559). super().__init__( mean, sigma, - float(lower_limit), - float(upper_limit), log_norm=log_norm, id_=id_, + lower_limit=lower_limit, + upper_limit=upper_limit, ) - self.mean, self.sigma, self.lower_limit, self.upper_limit = self.parameters + self.mean, self.sigma = self.parameters + + @property + def _support_kwargs(self) -> dict: + return dict(lower_limit=self.lower_limit, upper_limit=self.upper_limit) def cdf(self, x: Union[float, np.ndarray], xp=np) -> Union[float, np.ndarray]: """ diff --git a/test_autofit/graphical/hierarchical/test_truncated_support.py b/test_autofit/graphical/hierarchical/test_truncated_support.py new file mode 100644 index 000000000..f4b8c6ee3 --- /dev/null +++ b/test_autofit/graphical/hierarchical/test_truncated_support.py @@ -0,0 +1,75 @@ +""" +PyAutoFit#1559 (D4) at the EP level: a ``TruncatedGaussianPrior`` scatter +hyper-prior must keep its ``(lower_limit, upper_limit)`` through the whole +message-passing loop -- the very first ``prior.message ** (1 / (count - 1))`` +in ``message_dict`` used to reset it to ``(-inf, inf)``. +""" +import numpy as np +import pytest + +import autofit as af +from autofit.graphical import LaplaceOptimiser +from autofit.graphical.utils import StatusFlag +from autofit.messages.truncated_normal import TruncatedNormalMessage + + +class Level: + def __init__(self, x): + self.x = x + + +class GroupAnalysis(af.Analysis): + def __init__(self, y, noise): + self.y = y + self.noise = noise + + def log_likelihood_function(self, instance): + return float(-0.5 * np.sum((self.y - instance.x) ** 2) / self.noise**2) + + +def test__truncated_scatter_keeps_its_support_through_ep_sweeps(): + # The Laplace optimiser's refinement step samples the global numpy RNG + np.random.seed(0) + rng = np.random.default_rng(0) + + hf = af.HierarchicalFactor( + af.GaussianPrior, + mean=af.GaussianPrior(mean=50.0, sigma=10.0), + sigma=af.TruncatedGaussianPrior( + mean=10.0, sigma=5.0, lower_limit=0.0, upper_limit=100.0 + ), + ) + analysis_factors = [] + for truth in (45.0, 52.0, 58.0): + model = af.Model(Level) + model.x = af.GaussianPrior(50.0, 20.0) + y = truth + 2.0 * rng.standard_normal(20) + analysis_factors.append(af.AnalysisFactor(model, GroupAnalysis(y, 2.0))) + hf.add_drawn_variable(model.x) + + graph = af.FactorGraphModel(*analysis_factors, hf) + approx = graph.mean_field_approximation() + + # The starting mean field already carries the limits + start = approx.mean_field[hf.sigma] + assert isinstance(start, TruncatedNormalMessage) + assert (start.lower_limit, start.upper_limit) == (0.0, 100.0) + + # Manual factor_approximation -> optimise -> project_mean_field loop, which + # avoids EPOptimiser's DirectoryPaths output + laplace = LaplaceOptimiser() + flags = [] + for _ in range(3): + for factor in graph.graph.factors: + factor_approx = approx.factor_approximation(factor) + new_dist, status = laplace.optimise(factor_approx) + approx, status = approx.project_mean_field( + new_dist, factor_approx, status=status + ) + flags.append(status.flag) + + scatter = approx.mean_field[hf.sigma] + assert isinstance(scatter, TruncatedNormalMessage) + assert scatter.lower_limit == 0.0 + assert scatter.upper_limit == 100.0 + assert StatusFlag.EXCEPTION not in flags, flags diff --git a/test_autofit/mapper/prior/test_prior_properties.py b/test_autofit/mapper/prior/test_prior_properties.py index bca1c322e..f4413c013 100644 --- a/test_autofit/mapper/prior/test_prior_properties.py +++ b/test_autofit/mapper/prior/test_prior_properties.py @@ -17,6 +17,8 @@ (would catch the LogGaussian ``with_limits`` crash, #1331-01). - P5 ``from_mode(mode, variance)`` reproduces mean and variance at variance != 1 discriminating points (would catch the Gamma ``from_mode`` inversion, #1331-D3). +- P7 the message support survives ``**`` (would catch the truncation limits + lost on natural-parameter operations, #1559). House rule: library-level property tests stay NumPy-only; EP-level integration coverage lives with the EP framework review and complements this file. @@ -351,3 +353,25 @@ def test__strictness_flags_agree_with_the_density_at_the_bounds(prior): assert at_upper == -np.inf else: assert np.isfinite(at_upper) + + +# === P7: the message support survives natural-parameter operations === + + +@pytest.mark.parametrize("prior", all_priors(), ids=prior_id) +def test__message_power_keeps_the_support(prior): + """ + The general form of PyAutoFit#1559 (D4). EP's very first step raises every + prior message to a fractional power (``message_dict``), which rebuilds it + from natural parameters; a ``TruncatedGaussianPrior`` used to come out of + that with ``(-inf, inf)``. A transformed message's own limits stay +/-inf + (#1527), so the sweep is a no-op there and the base message is checked too. + """ + message = prior.message + + result = message ** 0.5 + + assert type(result) is type(message) + assert result.lower_limit == message.lower_limit + assert result.upper_limit == message.upper_limit + assert result._support_kwargs == message._support_kwargs diff --git a/test_autofit/messages/test_transformed_from_mode.py b/test_autofit/messages/test_transformed_from_mode.py new file mode 100644 index 000000000..122e20a2a --- /dev/null +++ b/test_autofit/messages/test_transformed_from_mode.py @@ -0,0 +1,82 @@ +""" +PyAutoFit#1559 (D5): ``TransformedMessage.from_mode`` must push the physical +covariance through the Jacobian of *every* transform in the stack, for 0-d and +n-d covariances alike, whether given as a float, an array or a ``DiagonalMatrix``. +""" +import numpy as np +import pytest + +import autofit as af +from autofit.mapper.operator import DiagonalMatrix +from autofit.mapper.variable import Variable +from autofit.mapper.variable_operator import VariableFullOperator + + +@pytest.fixture(name="log_message") +def make_log_message(): + # Physical variance 25 at mode 10 is log-space variance 0.25 (sigma 0.5) + return af.LogGaussianPrior(mean=np.log(10.0), sigma=0.5).message + + +def test__zero_d_diagonal_matrix_applies_the_jacobian(log_message): + result = log_message.from_mode(np.asarray(10.0), DiagonalMatrix(np.asarray(25.0))) + + assert result.base_message.mean == pytest.approx(np.log(10.0)) + assert result.base_message.sigma == pytest.approx(0.5) + + +def test__one_d_diagonal_matrix_matches_the_zero_d_path(log_message): + result = log_message.from_mode(np.asarray([10.0]), DiagonalMatrix(np.asarray([25.0]))) + + assert result.base_message.sigma == pytest.approx([0.5]) + + +def test__plain_float_matches_the_operator_path(log_message): + result = log_message.from_mode(np.asarray(10.0), 25.0) + + assert result.base_message.sigma == pytest.approx(0.5) + + +def test__variable_full_operator_extraction_matches(log_message): + # ``MeanField.from_mode_covariance`` hands over ``covar.get(v)``, a 0-d + # DiagonalMatrix extracted from the Laplace optimiser's full operator. + v = Variable("v") + covar = VariableFullOperator.from_diagonal({v: np.asarray(25.0)}) + + result = log_message.from_mode(np.asarray(10.0), covar[v]) + + assert result.base_message.sigma == pytest.approx(0.5) + + +def test__physical_limits_never_reach_the_base_message(log_message): + result = log_message.from_mode( + np.asarray(10.0), 25.0, lower_limit=0.0, upper_limit=np.inf + ) + + assert result.base_message.sigma == pytest.approx(0.5) + assert (result.base_message.lower_limit, result.base_message.upper_limit) == ( + -np.inf, + np.inf, + ) + + +@pytest.mark.parametrize("mode, variance", [(5.0, 0.04), (2.0, 0.01), (8.0, 0.0025)]) +def test__two_transform_stack_round_trips_the_variance(mode, variance): + # UniformPrior composes phi_transform with a LinearShiftTransform; the + # loop used to keep only the innermost Jacobian (variance 4.0 for 0.04). + u = af.UniformPrior(0.0, 10.0).message + + result = u.from_mode(np.asarray(mode), variance) + + assert result.mean == pytest.approx(mode) + assert result.variance == pytest.approx(variance) + + +def test__two_transform_stack_one_d_matches_zero_d(): + u = af.UniformPrior(0.0, 10.0).message + + one_d = u.from_mode(np.asarray([5.0]), np.asarray([0.04])) + zero_d = u.from_mode(np.asarray(5.0), DiagonalMatrix(np.asarray(0.04))) + + assert one_d.variance == pytest.approx([0.04]) + assert zero_d.variance == pytest.approx(0.04) diff --git a/test_autofit/messages/test_truncated_normal.py b/test_autofit/messages/test_truncated_normal.py index fcc8aa7c6..cd02fdd5d 100644 --- a/test_autofit/messages/test_truncated_normal.py +++ b/test_autofit/messages/test_truncated_normal.py @@ -1,7 +1,10 @@ +import pickle + import numpy as np import pytest from scipy.stats import norm +from autofit import exc from autofit.messages.normal import NormalMessage from autofit.messages.truncated_normal import ( TruncatedNaturalNormal, @@ -174,3 +177,120 @@ def test_truncated_natural_normal_uses_underlying_mu_sigma(): assert np.allclose(logl_n, logl_s) assert np.allclose(grad_n, grad_s) assert np.allclose(hess_n, hess_s) + + +# === PyAutoFit#1559: truncation limits are support state, carried through every rebuild === + + +@pytest.fixture(name="m") +def make_m(): + return TruncatedNormalMessage(10, 5, 0, 100) + + +def _support_ops(): + m = TruncatedNormalMessage(10, 5, 0, 100) + other = TruncatedNormalMessage(20, 3, 0, 100) + return [ + pytest.param(lambda m: m ** 0.2, id="pow"), + pytest.param(lambda m: m * other, id="multiply"), + pytest.param(lambda m: m / other, id="divide"), + pytest.param( + lambda m: TruncatedNormalMessage.from_natural_parameters( + m.natural_parameters(), **m._support_kwargs + ), + id="from_natural_parameters", + ), + pytest.param(lambda m: m.copy(), id="copy"), + pytest.param( + lambda m: m.update_invalid(TruncatedNormalMessage(1, 1, 0, 100)), + id="update_invalid", + ), + pytest.param(lambda m: m.natural, id="natural"), + pytest.param(lambda m: m.zeros_like(), id="zeros_like"), + pytest.param(lambda m: m * 2.0, id="scalar_multiply"), + pytest.param(lambda m: m[()], id="getitem"), + pytest.param(lambda m: pickle.loads(pickle.dumps(m)), id="pickle"), + ] + + +@pytest.mark.parametrize("op", _support_ops()) +def test__support_survives_natural_parameter_ops(m, op): + result = op(m) + + assert isinstance(result, TruncatedNormalMessage) + assert (result.lower_limit, result.upper_limit) == (0.0, 100.0) + + +def test__parameters_exclude_the_limits(m): + # The limits are support state, not parameters, so ``parameters`` and + # ``_parameter_support`` line up. + assert m.parameters == (10, 5) + assert len(m.parameters) == len(m._parameter_support) + + +def test__truncated_times_normal_keeps_truncated_support(m): + result = m * NormalMessage(20, 3) + assert isinstance(result, TruncatedNormalMessage) + assert (result.lower_limit, result.upper_limit) == (0.0, 100.0) + + # Documented asymmetry: the result takes the left operand's class, so a + # NormalMessage times a truncated one stays unbounded. Inside EP every + # message on a variable shares the prior's class, so this is user-only. + assert type(NormalMessage(20, 3) * m) is NormalMessage + + +def test__mismatched_finite_supports(): + overlap = TruncatedNormalMessage(1, 1, 0, 10) * TruncatedNormalMessage(1, 1, 5, 30) + assert (overlap.lower_limit, overlap.upper_limit) == (5.0, 10.0) + + with pytest.raises(exc.MessageException): + TruncatedNormalMessage(1, 1, 0, 10) * TruncatedNormalMessage(1, 1, 20, 30) + + +def test__divide_keeps_own_support(m): + result = m / TruncatedNormalMessage(1, 1, 5, 30) + assert (result.lower_limit, result.upper_limit) == (0.0, 100.0) + + +def test__from_mode_keeps_class_and_limits(): + result = TruncatedNormalMessage.from_mode( + 3.0, 4.0, lower_limit=0.0, upper_limit=100.0 + ) + assert type(result) is TruncatedNormalMessage + assert (result.lower_limit, result.upper_limit) == (0.0, 100.0) + assert result.mean == 3.0 + assert result.sigma == 2.0 + + +def test__update_invalid_vector_truncated(): + # Vector-shaped truncated messages used to raise TypeError here because + # the limits were positional parameters (float() of an array). + invalid = TruncatedNormalMessage( + np.array([1.0, 2.0]), np.array([1.0, np.nan]), 0, 100 + ) + safe = TruncatedNormalMessage(np.array([5.0, 5.0]), np.array([1.0, 1.0]), 0, 100) + + result = invalid.update_invalid(safe) + + assert (result.lower_limit, result.upper_limit) == (0.0, 100.0) + assert result.mean == pytest.approx([1.0, 5.0]) + assert result.sigma == pytest.approx([1.0, 1.0]) + + +def test__truncated_natural_normal_copy_keeps_limits(): + natural = TruncatedNaturalNormal(0.1, -0.5, lower_limit=0.0, upper_limit=100.0) + + for result in (natural.copy(), pickle.loads(pickle.dumps(natural))): + assert type(result) is TruncatedNaturalNormal + assert (result.lower_limit, result.upper_limit) == (0.0, 100.0) + + +def test__old_three_tuple_pickle_payload_still_loads(): + # Pickles written before #1559 carried the limits as the 3rd and 4th + # positional parameters and no support element. + result = TruncatedNormalMessage._reconstruct((10.0, 5.0, 0.0, 100.0), 0.0, 7) + assert (result.lower_limit, result.upper_limit) == (0.0, 100.0) + assert result.id == 7 + + result = TruncatedNormalMessage._reconstruct((10.0, 5.0), 0.0, 7) + assert (result.lower_limit, result.upper_limit) == (-np.inf, np.inf)