Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions autofit/mapper/prior/abstract.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
19 changes: 17 additions & 2 deletions autofit/messages/abstract.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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
Expand Down Expand Up @@ -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()
Expand All @@ -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
Expand Down Expand Up @@ -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":
Expand All @@ -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":
Expand All @@ -230,6 +238,7 @@ def __pow__(self, other: Real) -> "AbstractMessage":
new_params,
log_norm=log_norm,
id_=self.id,
**self._support_kwargs,
)
return new

Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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):
Expand All @@ -445,6 +459,7 @@ def __reduce__(self):
self.parameters,
self.log_norm,
self.id,
self._support_kwargs,
),
)

Expand Down
49 changes: 43 additions & 6 deletions autofit/messages/composed_transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
)
Expand Down Expand Up @@ -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))
Expand Down
58 changes: 57 additions & 1 deletion autofit/messages/interface.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import math
from abc import ABC, abstractmethod
from typing import Tuple, Iterator
from typing import Union
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
13 changes: 10 additions & 3 deletions autofit/messages/truncated_normal.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]:
"""
Expand Down
75 changes: 75 additions & 0 deletions test_autofit/graphical/hierarchical/test_truncated_support.py
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading