From 1ff4572c145ad7a2165b34d40d0ad3d766fd53fc Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Sun, 13 Sep 2026 11:59:56 +0100 Subject: [PATCH] Expose the swept factor graph on EPResult for the EP state figure factor_graph.optimise() builds its EPOptimiser (and so the graph it sweeps) internally and returned only the history and mean field, so a caller could not draw af.EPPlotter(kind="state") without private API: the plotter needs the optimiser's own graph, because FactorGraphModel.graph rebuilds and renames prior factors on every access and the history is keyed by the swept one. EPResult now carries factor_graph (additive, default None). Docs show the high-level form. Refs #1620 Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01DLx38vS6F1M7K5LnpVbeZ7 --- autofit/graphical/declarative/abstract.py | 1 + autofit/graphical/declarative/result.py | 9 ++ docs/features/graphical.md | 12 ++ .../graphical/gaussian/test_declarative.py | 1 + .../graphical/test_ep_result_factor_graph.py | 113 ++++++++++++++++++ 5 files changed, 136 insertions(+) create mode 100644 test_autofit/graphical/test_ep_result_factor_graph.py diff --git a/autofit/graphical/declarative/abstract.py b/autofit/graphical/declarative/abstract.py index 1d0e3e2cb..22c156299 100644 --- a/autofit/graphical/declarative/abstract.py +++ b/autofit/graphical/declarative/abstract.py @@ -211,6 +211,7 @@ def optimise( ep_history=opt.ep_history, declarative_factor=self, updated_ep_mean_field=updated_ep_mean_field, + factor_graph=opt.factor_graph, ) @property diff --git a/autofit/graphical/declarative/result.py b/autofit/graphical/declarative/result.py index d84a49c40..489280c97 100644 --- a/autofit/graphical/declarative/result.py +++ b/autofit/graphical/declarative/result.py @@ -60,6 +60,7 @@ def __init__( ep_history: EPHistory, declarative_factor, updated_ep_mean_field: EPMeanField, + factor_graph=None, ): """ The result of an EP Optimisation including its history, a declarative @@ -74,10 +75,18 @@ def __init__( A declarative representation of the factor being optimised updated_ep_mean_field An updated mean field; effectively the result of the optimisation + factor_graph + The factor graph the EP optimiser actually swept + (``EPOptimiser.factor_graph``), which is the object to hand to + ``af.EPPlotter`` for ``kind="state"``. Never + ``FactorGraphModel.graph``: that property builds a fresh graph, + renaming every prior factor, on every access, so the history's + keys would not match it. """ self.ep_history = ep_history self.declarative_factor = declarative_factor self.updated_ep_mean_field = updated_ep_mean_field + self.factor_graph = factor_graph @property def model(self) -> Collection: diff --git a/docs/features/graphical.md b/docs/features/graphical.md index 97b068d31..561bb1c23 100644 --- a/docs/features/graphical.md +++ b/docs/features/graphical.md @@ -292,6 +292,18 @@ actually swept. `kind="model"` draws the structure alone and needs no history at raises rather than quietly drawing a diagnostic figure with no diagnostics in it. The default is to show the figure; `format="png"` with a `path` writes it instead. +A fit run through the high-level `factor_graph.optimise(...)` builds that optimiser internally, so its result carries +the swept graph for exactly this purpose: + +```bash +result = factor_graph.optimise(af.LaplaceOptimiser(), max_steps=5) + +af.EPPlotter(result.factor_graph, ep_history=result.ep_history).figure(kind="state") +``` + +`result.factor_graph` is the graph the optimiser swept -- the one `result.ep_history` is keyed by -- and not a rebuild +of it. + ## Hierarchical Models A specific type of graphical model is a hierarchical model, where the shared parameter(s) of a graph are assumed diff --git a/test_autofit/graphical/gaussian/test_declarative.py b/test_autofit/graphical/gaussian/test_declarative.py index 8ed39bb18..dd2836074 100644 --- a/test_autofit/graphical/gaussian/test_declarative.py +++ b/test_autofit/graphical/gaussian/test_declarative.py @@ -119,6 +119,7 @@ def test_optimise_forwards_optional_updater(factor_model, updater, monkeypatch): class StubEPOptimiser: ep_history = None + factor_graph = None @staticmethod def run(model_approx, **kwargs): diff --git a/test_autofit/graphical/test_ep_result_factor_graph.py b/test_autofit/graphical/test_ep_result_factor_graph.py new file mode 100644 index 000000000..0259df79c --- /dev/null +++ b/test_autofit/graphical/test_ep_result_factor_graph.py @@ -0,0 +1,113 @@ +""" +``FactorGraphModel.optimise`` returns the graph it swept (PyAutoFit #1620). + +The EP state figure is drawn from the *optimiser's* factor graph, because the +``EPHistory`` is keyed by that graph's factor objects, while +``AbstractDeclarativeFactor.graph`` builds a fresh graph -- renaming every +``PriorFactor`` -- on every access. The optimiser is built inside ``optimise``, +so before ``EPResult.factor_graph`` existed a caller of the high-level API had +no way to reach it. +""" + +import numpy as np +import pytest + +import autofit as af +import autofit.graphical as g +from autofit.graphical.declarative.factor.prior import PriorFactor +from test_autofit.graphical.gaussian.model import Analysis, Gaussian, make_data + + +@pytest.fixture(name="factor_graph_model") +def make_factor_graph_model(): + """A one factor graph, small enough that two sweeps cost milliseconds.""" + x = np.arange(50) + y = make_data(Gaussian(centre=25.0, normalization=25.0, sigma=10.0), x) + + prior_model = af.Model( + Gaussian, + centre=af.GaussianPrior(mean=25, sigma=20), + normalization=af.GaussianPrior(mean=25, sigma=10), + sigma=af.GaussianPrior(mean=10, sigma=10), + ) + + return g.FactorGraphModel( + g.AnalysisFactor(prior_model, analysis=Analysis(x=x, y=y)) + ) + + +@pytest.fixture(name="ep_result") +def make_ep_result(factor_graph_model): + return factor_graph_model.optimise( + af.LaplaceOptimiser(), + paths=False, + # kl_tol=None disables the convergence check so both sweeps run. + ep_history=af.EPHistory(kl_tol=None), + max_steps=2, + ) + + +def test_result_carries_the_swept_graph(ep_result): + """ + The returned graph is the one the history is keyed by -- not a rebuild. + """ + assert ep_result.factor_graph is not None + assert isinstance(ep_result.factor_graph, g.FactorGraph) + + history_factors = set(ep_result.ep_history.history) + + assert history_factors + assert history_factors.issubset(set(ep_result.factor_graph.factors)) + + +def test_rebuilt_graph_is_not_the_swept_one(factor_graph_model, ep_result): + """ + Why the attribute has to exist: the declarative ``graph`` property builds a + new graph, renaming every ``PriorFactor``, on every access -- so it is not + the graph the history was keyed by and must not be handed to the plotter. + """ + rebuilt = factor_graph_model.graph + + assert rebuilt is not ep_result.factor_graph + assert factor_graph_model.graph is not rebuilt + + def prior_factor_names(graph): + return sorted( + factor.name for factor in graph.factors if isinstance(factor, PriorFactor) + ) + + assert prior_factor_names(rebuilt) != prior_factor_names(ep_result.factor_graph) + + +def test_state_figure_from_the_result(ep_result, tmp_path): + """ + The high-level form the docs give: plot straight off the result. + """ + plotter = af.EPPlotter( + ep_result.factor_graph, + ep_history=ep_result.ep_history, + ) + + plotter.figure(kind="state", path=tmp_path, format="png") + + assert (tmp_path / "graph_state.png").exists() + + state = plotter.state() + + assert state.factors + assert [ + factor.status for factor in state.factors if factor.status == "absent" + ] == [] + + +def test_factor_graph_defaults_to_none(): + """The argument is additive: the old three argument call still works.""" + from autofit.graphical.declarative.result import EPResult + + result = EPResult( + ep_history=af.EPHistory(), + declarative_factor=None, + updated_ep_mean_field=None, + ) + + assert result.factor_graph is None