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
2 changes: 1 addition & 1 deletion autofit/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@
from .text import samples_text
from .visualise import VisualiseGraph
from .graph_spec import GraphSpec, graph_spec_from
from .model_figure import ModelPlotter
from .model_figure import ModelPlotter, EPPlotter
from .interpolator import (
LinearInterpolator,
SplineInterpolator,
Expand Down
8 changes: 5 additions & 3 deletions autofit/graphical/expectation_propagation/optimiser.py
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,9 @@ def __init__(
with open(self.output_path / "graph.info", "w+") as f:
f.write(self.factor_graph.info)

self.visualiser = Visualise(self.ep_history, self.output_path)
self.visualiser = Visualise(
self.ep_history, self.output_path, factor_graph=self.factor_graph
)

@classmethod
def from_meanfield(
Expand Down Expand Up @@ -602,15 +604,15 @@ def run(

else: # If no break do next iteration
if self.visualiser and _should_visualise:
self.visualiser()
self.visualiser(model_approx)
if self.output_path and _should_output:
self._output_results(model_approx)
self._output_diagnostics()
continue
break # stop iterations

if self.paths:
self.visualiser()
self.visualiser(model_approx)
self._output_results(model_approx)
self._output_diagnostics(final=True, model_approx=model_approx)
self._warn_sigma_collapse()
Expand Down
91 changes: 81 additions & 10 deletions autofit/graphical/expectation_propagation/visualise.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,28 +9,48 @@


class Visualise:
def __init__(self, ep_history: EPHistory, output_path: Path):
def __init__(
self,
ep_history: EPHistory,
output_path: Path,
factor_graph=None,
):
"""
Handles visualisation of expectation propagation optimisation.

This includes plotting key metrics such as Evidence and KL Divergence
which are expected to converge.
which are expected to converge, and -- when the `model_figure` key is
switched on -- the factor graph itself with the run painted on it.

Parameters
----------
ep_history
A history describing previous optimisations by factor
output_path
The path that plots are written to
factor_graph
The `EPOptimiser`'s own factor graph, which `graph_model.png` and
`graph_state.png` are drawn from. `None` -- the default, and what
every caller that does not pass one gets -- writes neither.
"""
self.ep_history = ep_history
self.output_path = output_path
self.factor_graph = factor_graph
self._model_written = False

os.makedirs(output_path, exist_ok=True)

def __call__(self):
def __call__(self, model_approx=None):
"""
Save a plot of Evidence and KL Divergence for the ep_history
Save a plot of Evidence and KL Divergence for the ep_history.

Parameters
----------
model_approx
The latest `EPMeanField`, passed through to the factor graph
figure. Optional: callers which do not have one (`stochastic.py`)
still get the status, age and reversion overlay, which is read from
the history rather than the mean field.
"""
import matplotlib.pyplot as plt

Expand All @@ -46,6 +66,61 @@ def __call__(self):
plt.close()

self.plot_factors()
self._model_figures(model_approx)

def _model_figures(self, model_approx=None):
"""
Save `graph_model.png` and `graph_state.png`: the factor graph the
optimiser sweeps, and the same graph with what the run has done to each
factor drawn on it.

`graph_model.png` is structure alone and is therefore written once, on
the first call, beside `graph.info`. `graph_state.png` is rewritten on
every call, so the file always shows the sweep just finished.

Both are behind `output.yaml`'s `model_figure` key -- the same key the
per-search `model.png` is behind, read the same strict way, so a config
which has never heard of it writes nothing. Each render costs roughly a
third of a second, which is why it rides `visualise_interval` rather
than every sweep.

A figure must never kill a fit, so the whole body is guarded exactly as
`DirectoryPaths._save_model_info`'s is: anything that goes wrong is
logged and the run carries on.
"""
if self.factor_graph is None:
return

try:
from autofit.model_figure.config import model_figure_enabled
from autofit.non_linear.test_mode import skip_visualization

if not model_figure_enabled() or skip_visualization():
return

from autofit.model_figure.ep.plotter import EPPlotter, FILENAMES

if not self._model_written:
EPPlotter(self.factor_graph).figure(
path=self.output_path,
filename=FILENAMES["model"],
format="png",
kind="model",
)
self._model_written = True

EPPlotter(
self.factor_graph,
ep_history=self.ep_history,
model_approx=model_approx,
).figure(
path=self.output_path,
filename=FILENAMES["state"],
format="png",
kind="state",
)
except Exception as e:
logger.info(f"graph_model.png / graph_state.png not written: {e!r}")

def plot_factors(self):
"""
Expand All @@ -59,12 +134,8 @@ def plot_factors(self):
fig, (evidence_plot, kl_plot) = plt.subplots(2)
fig.suptitle("Per-factor Evidence and KL Divergence")
for factor, factor_history in self.ep_history.items():
evidence_plot.plot(
factor_history.evidences, label=f"{factor.name}"
)
kl_plot.plot(
factor_history.kl_divergences, label=f"{factor.name}"
)
evidence_plot.plot(factor_history.evidences, label=f"{factor.name}")
kl_plot.plot(factor_history.kl_divergences, label=f"{factor.name}")
kl_plot.set_yscale("log")
evidence_plot.legend(fontsize="small")
kl_plot.legend(fontsize="small")
Expand Down
7 changes: 6 additions & 1 deletion autofit/model_figure/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,13 @@
and is re-exported as ``af.ModelPlotter``. Importing this package does **not**
import matplotlib: every drawing import is inside a function, so
``import autofit`` stays drawing-free.

The :mod:`autofit.model_figure.ep` sub-package draws the other picture of a
graphical fit -- the factor graph an ``EPOptimiser`` sweeps, with the run's
state on it -- through :class:`~autofit.model_figure.ep.plotter.EPPlotter`.
"""

from .plotter import ModelPlotter
from .ep import EPPlotter

__all__ = ["ModelPlotter"]
__all__ = ["ModelPlotter", "EPPlotter"]
31 changes: 31 additions & 0 deletions autofit/model_figure/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
"""
The single gate every model figure is written behind.

``output.yaml``'s ``model_figure`` key is read **strictly** here so that both
the per-search ``model.png`` hook (``autofit.non_linear.paths.directory``) and
the EP factor-graph figures ask the same question of the same key.
"""

from autonerves import conf

__all__ = ["model_figure_enabled"]


def model_figure_enabled() -> bool:
"""
Whether `model.png` -- the model figure drawn beside `model.info` -- is written.

The `output.yaml` key `model_figure` is read **strictly**: an absent key means
off.

This deliberately does NOT use `autonerves.output.should_output`
(`autonerves/output.py:should_output`), which falls back to `output.yaml`'s
`default:` entry whenever a key is absent. That entry is `true` in every
workspace, so a brand new key that so far only exists in the library's own
default config would silently switch the figure ON in every config which has
not yet added it. Only a config that explicitly opts in writes the file.
"""
try:
return bool(conf.instance["output"]["model_figure"])
except KeyError:
return False
25 changes: 25 additions & 0 deletions autofit/model_figure/ep/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
"""
The EP factor-graph figure -- the *diagnostic* view of a graphical fit.

``autofit.model_figure`` draws a model's containment structure; this package
draws the **factor graph** an :class:`~autofit.graphical.EPOptimiser` actually
sweeps, with the run's state painted onto it. It follows the same three-layer
split, each layer importable and testable on its own:

* :mod:`autofit.model_figure.ep.spec` -- structure: which factor nodes, which
variable nodes, which edges, which plates.
* :mod:`autofit.model_figure.ep.state` -- overlay: what the EP run did to each
factor (updates, sweeps, age, reverted variables).
* :mod:`autofit.model_figure.ep.presentation` -- what is drawn and what it
says.
* :mod:`autofit.model_figure.ep.layout` -- where it goes, measured in inches.
* :mod:`autofit.model_figure.ep.render` -- matplotlib.

:class:`~autofit.model_figure.ep.plotter.EPPlotter` is the public entry point
and is re-exported as ``af.EPPlotter``. Nothing here imports a drawing library
at module level, so ``import autofit`` stays drawing-free.
"""

from .plotter import EPPlotter

__all__ = ["EPPlotter"]
Loading
Loading