diff --git a/autofit/__init__.py b/autofit/__init__.py index 59e7ef4d5..1eda9f2f3 100644 --- a/autofit/__init__.py +++ b/autofit/__init__.py @@ -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, diff --git a/autofit/graphical/expectation_propagation/optimiser.py b/autofit/graphical/expectation_propagation/optimiser.py index 6ee1dfa14..76906ee99 100644 --- a/autofit/graphical/expectation_propagation/optimiser.py +++ b/autofit/graphical/expectation_propagation/optimiser.py @@ -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( @@ -602,7 +604,7 @@ 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() @@ -610,7 +612,7 @@ def run( 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() diff --git a/autofit/graphical/expectation_propagation/visualise.py b/autofit/graphical/expectation_propagation/visualise.py index 8332e08d7..82b4e3f55 100644 --- a/autofit/graphical/expectation_propagation/visualise.py +++ b/autofit/graphical/expectation_propagation/visualise.py @@ -9,12 +9,18 @@ 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 ---------- @@ -22,15 +28,29 @@ def __init__(self, ep_history: EPHistory, output_path: Path): 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 @@ -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): """ @@ -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") diff --git a/autofit/model_figure/__init__.py b/autofit/model_figure/__init__.py index 98d8c1ecb..509286f50 100644 --- a/autofit/model_figure/__init__.py +++ b/autofit/model_figure/__init__.py @@ -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"] diff --git a/autofit/model_figure/config.py b/autofit/model_figure/config.py new file mode 100644 index 000000000..45c344445 --- /dev/null +++ b/autofit/model_figure/config.py @@ -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 diff --git a/autofit/model_figure/ep/__init__.py b/autofit/model_figure/ep/__init__.py new file mode 100644 index 000000000..1b584a537 --- /dev/null +++ b/autofit/model_figure/ep/__init__.py @@ -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"] diff --git a/autofit/model_figure/ep/layout.py b/autofit/model_figure/ep/layout.py new file mode 100644 index 000000000..06d07aea3 --- /dev/null +++ b/autofit/model_figure/ep/layout.py @@ -0,0 +1,650 @@ +""" +Layer 4 of the EP figure -- measurement and placement. + +Everything here is in **inches**, as in the model figure's own +:mod:`autofit.model_figure.layout`, so the drawing layer is a straight +transcription of the numbers this module computes. The two rules of that module +hold here too: text is **measured** (``measure_text``, a scratch Agg canvas), +never estimated, and font sizes never change with graph size. + +What is different is the shape of the problem. The model figure is a +*containment* diagram, so it nests boxes. A factor graph is a **layered +bipartite** diagram, so it ranks them: + +===== ========================================================== +rank what sits on it +===== ========================================================== +0 hyper factors -- the priors on a distribution's parameters +1 hyper variables -- the distribution's own parameters +2 hierarchical factors (one node per group) +3 the model's variables -- drawn and free +4 analysis factors (one node per plate) +5 prior stubs, in the column of the variable they wrap +===== ========================================================== + +Reading top to bottom is then reading the generative story: the hyper priors +feed the distribution, the distribution draws the per-dataset variables, and +the analyses observe them. + +Within a rank the order is **declaration order**, adjusted by one stable +barycentre pass -- a node with neighbours on the rank above slides toward their +average position, a node without stays exactly where it was declared. One pass, +not the usual sweep to convergence: the graphs are small, and a figure that +reorders itself when a factor is added is not a figure anyone can diff. + +``networkx.multipartite_layout`` supplies the base coordinates (the same +networkx that is already a hard dependency, ``pyproject.toml``; graphviz's +``dot`` is absent locally, on the GitHub runner and on Colab, so it is not an +option). Its coordinates are normalised, so they are scaled by the measured +width of the widest rank and then packed left to right, which is what +guarantees no two boxes overlap. If it raises, +:func:`_bipartite_fallback` draws the two-column layout +``autofit.graphical.factor_graphs.graph.bipartite_layout`` has always drawn. + +:meth:`EPLayout.to_dict` is the determinism artefact: every coordinate rounded +to 4 dp, so ``json.dumps`` of it is byte-stable for a given graph and state. +""" + +from dataclasses import dataclass, field +from typing import Any, Dict, List, Optional, Tuple + +from autofit.model_figure.layout import Style, _line_height, measure_text +from autofit.model_figure.ep.presentation import ( + EPPresentation, + FACTOR_NODE_KINDS, +) + +__all__ = [ + "EPNodeBox", + "EPEdgeRoute", + "EPPlateFrame", + "EPLayout", + "build_ep_layout", + "rank_of", +] + +#: Vertical space between two ranks, in inches. +RANK_GAP = 0.42 + +#: Horizontal space between two boxes on the same rank, in inches. +NODE_GAP = 0.26 + +#: Padding inside a node box. +NODE_PAD = 0.1 + +#: Padding between a plate's frame and the boxes it encloses. +PLATE_PAD = 0.16 + +#: The number of ranks. Kept explicit so :func:`rank_of` cannot silently +#: invent one. +RANKS = 6 + + +def rank_of(node, neighbour_kinds: Tuple[str, ...] = ()) -> int: + """ + The rank an :class:`~autofit.model_figure.ep.presentation.EPNode` sits on. + + A prior stub is a *hyper factor* when it wraps a distribution's own + parameter -- it belongs above that parameter, at the top of the generative + story -- and an ordinary stub otherwise, on the bottom rank in its + variable's column. A stub carries no kind of its own that says which, so + the kinds of the variables it is joined to are passed in. + """ + kind = node.kind + if kind == "prior": + return 0 if "hyper" in neighbour_kinds else RANKS - 1 + if kind == "hyper": + return 1 + if kind == "hierarchical": + return 2 + if kind in ("drawn", "free"): + return 3 + if kind in FACTOR_NODE_KINDS: + return 4 + return 3 + + +@dataclass(frozen=True) +class EPNodeBox: + """One node's box, in inches, with the origin at the top left.""" + + key: str + kind: str + title: str + subtitle: Optional[str] = None + badges: Tuple[str, ...] = () + state: Optional[str] = None + note: Optional[str] = None + rank: int = 0 + plate_key: Optional[str] = None + x: float = 0.0 + y: float = 0.0 + width: float = 0.0 + height: float = 0.0 + pad: float = NODE_PAD + title_y: float = 0.0 + badge_offset: float = 0.0 + subtitle_y: Optional[float] = None + note_y: Optional[float] = None + + @property + def centre_x(self) -> float: + return self.x + self.width / 2 + + @property + def bottom(self) -> float: + return self.y + self.height + + def to_dict(self) -> Dict[str, Any]: + return { + "key": self.key, + "kind": self.kind, + "title": self.title, + "subtitle": self.subtitle, + "badges": list(self.badges), + "state": self.state, + "note": self.note, + "rank": self.rank, + "plate_key": self.plate_key, + "x": round(self.x, 4), + "y": round(self.y, 4), + "width": round(self.width, 4), + "height": round(self.height, 4), + } + + +@dataclass(frozen=True) +class EPEdgeRoute: + """One edge, routed: two points when the ranks touch, four when they do not.""" + + source_key: str + target_key: str + kind: str + points: Tuple[Tuple[float, float], ...] = () + + def to_dict(self) -> Dict[str, Any]: + return { + "source_key": self.source_key, + "target_key": self.target_key, + "kind": self.kind, + "points": [[round(x, 4), round(y, 4)] for x, y in self.points], + } + + +@dataclass(frozen=True) +class EPPlateFrame: + """The dashed rectangle drawn around a plate's nodes.""" + + key: str + title: str + x: float = 0.0 + y: float = 0.0 + width: float = 0.0 + height: float = 0.0 + + def to_dict(self) -> Dict[str, Any]: + return { + "key": self.key, + "title": self.title, + "x": round(self.x, 4), + "y": round(self.y, 4), + "width": round(self.width, 4), + "height": round(self.height, 4), + } + + +@dataclass(frozen=True) +class EPLayout: + """Every box, line and frame of the EP figure, in inches.""" + + width: float + height: float + nodes: Tuple[EPNodeBox, ...] = () + edges: Tuple[EPEdgeRoute, ...] = () + plates: Tuple[EPPlateFrame, ...] = () + legend: str = "" + footer: str = "" + legend_y: float = 0.0 + footer_y: float = 0.0 + fallback: bool = False + style: Style = field(default_factory=Style) + + def box(self, key: str) -> EPNodeBox: + for node in self.nodes: + if node.key == key: + return node + raise KeyError(key) + + def to_dict(self) -> Dict[str, Any]: + return { + "width": round(self.width, 4), + "height": round(self.height, 4), + "nodes": [node.to_dict() for node in self.nodes], + "edges": [edge.to_dict() for edge in self.edges], + "plates": [plate.to_dict() for plate in self.plates], + "legend": self.legend, + "footer": self.footer, + "legend_y": round(self.legend_y, 4), + "footer_y": round(self.footer_y, 4), + "fallback": self.fallback, + "style": self.style.to_dict(), + } + + +# ---------------------------------------------------------------------------- +# measurement +# ---------------------------------------------------------------------------- + + +def _badge_width(badge: str, style: Style) -> float: + return round(measure_text(badge, style.badge_size)[0] + 0.12, 4) + + +def _measure(node, style: Style) -> Tuple[float, float, float, float]: + """ + ``(width, height, badge_offset, title_height)`` of one node's box. + + A variable is a pill -- smaller type, tighter padding -- and a factor is a + card, exactly as in the model figure. + """ + title_size = style.title_size if node.is_factor else style.pill_size + pad = NODE_PAD if node.is_factor else NODE_PAD * 0.75 + + title_w = measure_text( + node.title, title_size, "bold" if node.is_factor else "normal" + )[0] + badge_offset = title_w + (style.inner_gap if node.badges else 0.0) + head_w = badge_offset + sum( + _badge_width(badge, style) + style.inner_gap for badge in node.badges + ) + if node.badges: + head_w -= style.inner_gap + + widths = [head_w] + if node.subtitle: + widths.append(measure_text(node.subtitle, style.badge_size)[0]) + if node.note: + widths.append(measure_text(node.note, style.note_size)[0]) + + title_h = _line_height(title_size) + height = title_h + if node.subtitle: + height += _line_height(style.badge_size) + if node.note: + height += _line_height(style.note_size) + + return ( + round(max(widths) + 2 * pad, 4), + round(height + 2 * pad, 4), + round(pad + badge_offset, 4), + title_h, + ) + + +# ---------------------------------------------------------------------------- +# ordering +# ---------------------------------------------------------------------------- + + +def _ranked(presentation: EPPresentation, neighbours) -> Dict[int, List[str]]: + """Node keys per rank, in declaration order.""" + kinds = {node.key: node.kind for node in presentation.nodes} + ranks: Dict[int, List[str]] = {} + for node in presentation.nodes: + neighbour_kinds = tuple( + kinds[other] for other in neighbours.get(node.key, ()) if other in kinds + ) + ranks.setdefault(rank_of(node, neighbour_kinds), []).append(node.key) + return ranks + + +def _barycentre(ranks: Dict[int, List[str]], neighbours: Dict[str, List[str]]): + """ + One stable pass down the ranks. + + A node with neighbours on the rank above moves to their average position; + a node without neighbours there does not move at all -- it keeps the slot + declaration order gave it, and the movable nodes are re-dealt into the + slots they already occupied. Ties keep declaration order, so the pass is + idempotent and a graph that needs no reordering gets none. + """ + for rank in sorted(ranks)[1:]: + above = ranks.get(rank - 1) + if not above: + continue + index_above = {key: index for index, key in enumerate(above)} + order = ranks[rank] + declared = {key: index for index, key in enumerate(order)} + + centres = {} + for key in order: + positions = [ + index_above[other] + for other in neighbours.get(key, ()) + if other in index_above + ] + if positions: + centres[key] = sum(positions) / len(positions) + + slots = [index for index, key in enumerate(order) if key in centres] + if len(slots) < 2: + continue + movable = sorted(centres, key=lambda key: (centres[key], declared[key])) + for slot, key in zip(slots, movable): + order[slot] = key + return ranks + + +def _base_positions( + ranks: Dict[int, List[str]], edges +) -> Tuple[Dict[str, float], bool]: + """ + Normalised horizontal positions, from ``networkx.multipartite_layout``. + + The layout's own within-rank order is not used -- it reverses insertion + order -- so only its *slots* are taken: the sorted coordinates of a rank + are dealt out to that rank's nodes in the order + :func:`_barycentre` settled on. + """ + try: + import networkx as nx + + graph = nx.Graph() + for rank in sorted(ranks): + for key in ranks[rank]: + graph.add_node(key, rank=rank) + for edge in edges: + if edge.source_key in graph and edge.target_key in graph: + graph.add_edge(edge.source_key, edge.target_key) + + raw = nx.multipartite_layout(graph, subset_key="rank", align="horizontal") + positions = {} + for rank in sorted(ranks): + slots = sorted(float(raw[key][0]) for key in ranks[rank]) + for key, slot in zip(ranks[rank], slots): + positions[key] = slot + return positions, False + except Exception: # pragma: no cover - exercised by monkeypatching + return _bipartite_fallback(ranks), True + + +def _bipartite_fallback(ranks: Dict[int, List[str]]) -> Dict[str, float]: + """ + The two-column layout of + ``autofit.graphical.factor_graphs.graph.bipartite_layout``, flattened onto + one axis: every rank simply spreads its nodes evenly. + + Only reached if ``multipartite_layout`` raises, which it does not for any + graph autofit builds -- but a figure must never be the reason a fit fails. + """ + widest = max((len(keys) for keys in ranks.values()), default=1) + positions = {} + for keys in ranks.values(): + offset = (len(keys) - 1) / 2 + for index, key in enumerate(keys): + positions[key] = (index - offset) * widest / max(len(keys), 1) + return positions + + +# ---------------------------------------------------------------------------- +# routing +# ---------------------------------------------------------------------------- + + +def _anchor(source: EPNodeBox, target: EPNodeBox): + """Where an edge leaves one box and lands on the other.""" + if source.bottom <= target.y: + return (source.centre_x, source.bottom), (target.centre_x, target.y) + if target.bottom <= source.y: + return (source.centre_x, source.y), (target.centre_x, target.bottom) + # Same rank (only a fallback layout can do this): leave and land sideways. + if source.centre_x <= target.centre_x: + return ( + (source.x + source.width, source.y + source.height / 2), + (target.x, target.y + target.height / 2), + ) + return ( + (source.x, source.y + source.height / 2), + (target.x + target.width, target.y + target.height / 2), + ) + + +def _route(edge, source: EPNodeBox, target: EPNodeBox) -> EPEdgeRoute: + start, end = _anchor(source, target) + if abs(source.rank - target.rank) <= 1 or start[0] == end[0]: + points = (start, end) + else: + # An orthogonal elbow: a long edge that cut diagonally across a rank + # would read as an edge *to* the nodes it passes. + middle = round((start[1] + end[1]) / 2, 4) + points = (start, (start[0], middle), (end[0], middle), end) + return EPEdgeRoute( + source_key=edge.source_key, + target_key=edge.target_key, + kind=edge.kind, + points=points, + ) + + +def _segments(route: EPEdgeRoute): + return list(zip(route.points, route.points[1:])) + + +def _crosses(first, second) -> bool: + """Whether two segments properly intersect (touching at an end does not).""" + + def side(a, b, c): + value = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) + if abs(value) < 1e-9: + return 0 + return 1 if value > 0 else -1 + + (p1, p2), (p3, p4) = first, second + d1, d2 = side(p3, p4, p1), side(p3, p4, p2) + d3, d4 = side(p1, p2, p3), side(p1, p2, p4) + return d1 * d2 < 0 and d3 * d4 < 0 + + +def _count_crossings(layout: EPLayout) -> int: + """ + How many pairs of edges cross. + + Edges that share a node are not counted: three edges leaving one factor + meet at that factor by construction, and calling that a crossing would make + every bipartite figure look bad. Used by the layout tests as the quality + measure the ranking exists to keep at zero. + """ + crossings = 0 + edges = layout.edges + for index, first in enumerate(edges): + for second in edges[index + 1 :]: + if {first.source_key, first.target_key} & { + second.source_key, + second.target_key, + }: + continue + if any( + _crosses(one, other) + for one in _segments(first) + for other in _segments(second) + ): + crossings += 1 + return crossings + + +# ---------------------------------------------------------------------------- +# the build +# ---------------------------------------------------------------------------- + + +def build_ep_layout( + presentation: EPPresentation, style: Optional[Style] = None +) -> EPLayout: + """ + Measure and place an + :class:`~autofit.model_figure.ep.presentation.EPPresentation`. + + Parameters + ---------- + presentation + What is drawn, from + :func:`~autofit.model_figure.ep.presentation.build_ep_presentation`. + style + Geometry and typography. The model figure's :class:`Style` is reused + unchanged, so the two figures are visibly the same family. + + Returns + ------- + An :class:`EPLayout`: every box in inches, ready to draw verbatim. + """ + style = style or Style() + + nodes = {node.key: node for node in presentation.nodes} + neighbours: Dict[str, List[str]] = {key: [] for key in nodes} + for edge in presentation.edges: + if edge.source_key in neighbours and edge.target_key in neighbours: + neighbours[edge.source_key].append(edge.target_key) + neighbours[edge.target_key].append(edge.source_key) + + ranks = _barycentre(_ranked(presentation, neighbours), neighbours) + slots, fallback = _base_positions(ranks, presentation.edges) + + measured = {key: _measure(node, style) for key, node in nodes.items()} + + # -- place each rank: its normalised slots, scaled so the rank is exactly as + # -- wide as its measured content needs, then packed left to right so that + # -- nothing can overlap whatever the base coordinates said. + placed: Dict[str, Tuple[float, float]] = {} # key -> (left, top) + blocks: Dict[int, Tuple[float, float]] = {} + top = style.margin + for rank in sorted(ranks): + keys = ranks[rank] + row_height = max(measured[key][1] for key in keys) + span = max(slots[key] for key in keys) - min(slots[key] for key in keys) + needed = sum(measured[key][0] for key in keys) + NODE_GAP * (len(keys) - 1) + # Per rank, not per figure: one rank of long hyper-parameter names must + # not stretch every other rank across a figure of empty inches. + scale = needed / span if span > 0 else 1.0 + cursor = None + for key in keys: + width = measured[key][0] + left = slots[key] * scale - width / 2 + if cursor is not None and left < cursor + NODE_GAP: + left = cursor + NODE_GAP + placed[key] = (left, top) + cursor = left + width + blocks[rank] = ( + min(placed[key][0] for key in keys), + max(placed[key][0] + measured[key][0] for key in keys), + ) + top += row_height + RANK_GAP + + content = max(right - left for left, right in blocks.values()) + boxes: Dict[str, EPNodeBox] = {} + for rank in sorted(ranks): + left, right = blocks[rank] + offset = style.margin + (content - (right - left)) / 2 - left + for key in ranks[rank]: + node = nodes[key] + width, height, badge_offset, title_h = measured[key] + x, y = placed[key] + pad = NODE_PAD if node.is_factor else NODE_PAD * 0.75 + subtitle_y = y + pad + title_h if node.subtitle else None + note_y = ( + y + height - pad - _line_height(style.note_size) if node.note else None + ) + boxes[key] = EPNodeBox( + key=key, + kind=node.kind, + title=node.title, + subtitle=node.subtitle, + badges=node.badges, + state=node.state, + note=node.note, + rank=rank, + plate_key=node.plate_key, + x=round(x + offset, 4), + y=round(y, 4), + width=width, + height=height, + pad=pad, + title_y=round(y + pad, 4), + badge_offset=badge_offset, + subtitle_y=None if subtitle_y is None else round(subtitle_y, 4), + note_y=None if note_y is None else round(note_y, 4), + ) + + ordered = tuple(boxes[node.key] for node in presentation.nodes) + edges = tuple( + _route(edge, boxes[edge.source_key], boxes[edge.target_key]) + for edge in presentation.edges + if edge.source_key in boxes and edge.target_key in boxes + ) + + frames = [] + for plate in presentation.plates: + enclosed = [boxes[key] for key in plate.node_keys if key in boxes] + if len(enclosed) < 2: + # A frame around the plate node alone says nothing its own + # ``N members`` badge has not already said. + continue + left = min(box.x for box in enclosed) - PLATE_PAD + right = max(box.x + box.width for box in enclosed) + PLATE_PAD + top_edge = min(box.y for box in enclosed) - PLATE_PAD + bottom = max(box.bottom for box in enclosed) + PLATE_PAD + frames.append( + EPPlateFrame( + key=plate.key, + title=plate.badge, + x=round(left, 4), + y=round(top_edge, 4), + width=round(right - left, 4), + height=round(bottom - top_edge, 4), + ) + ) + + bottom = max( + (box.bottom for box in ordered), + default=style.margin, + ) + bottom = max(bottom, max((frame.y + frame.height for frame in frames), default=0.0)) + bottom += style.legend_gap + legend_y = bottom + bottom += _line_height(style.footer_size) + 0.04 + footer_y = bottom + bottom += _line_height(style.footer_size) + style.margin + + text_right = style.margin + max( + ( + measure_text(presentation.legend, style.footer_size)[0] + if presentation.legend + else 0.0 + ), + ( + measure_text(presentation.footer, style.footer_size)[0] + if presentation.footer + else 0.0 + ), + ) + right_edge = max( + (box.x + box.width for box in ordered), + default=style.margin, + ) + right_edge = max( + right_edge, max((frame.x + frame.width for frame in frames), default=0.0) + ) + width = round(max(right_edge, text_right) + style.margin, 4) + + return EPLayout( + width=width, + height=round(bottom, 4), + nodes=ordered, + edges=edges, + plates=tuple(frames), + legend=presentation.legend, + footer=presentation.footer, + legend_y=round(legend_y, 4), + footer_y=round(footer_y, 4), + fallback=fallback, + style=style, + ) diff --git a/autofit/model_figure/ep/plotter.py b/autofit/model_figure/ep/plotter.py new file mode 100644 index 000000000..b94d9ebce --- /dev/null +++ b/autofit/model_figure/ep/plotter.py @@ -0,0 +1,205 @@ +""" +The public entry point -- ``af.EPPlotter(factor_graph).figure()``. + +``af.ModelPlotter`` draws a model's containment structure; ``af.EPPlotter`` +draws the **factor graph** an :class:`~autofit.graphical.EPOptimiser` sweeps, +and -- given the optimiser's history -- what the run has done to it. The two +plotters are deliberately the same shape: the plotter owns the layers and +nothing else, each layer is exposed on its own so a test can assert the +vocabulary and the geometry without rendering a pixel, and +:meth:`EPPlotter.figure` takes ``path`` as a *directory* and ``format`` as one +of ``show | png | svg | pdf``, exactly as +``autofit/non_linear/plot/plot_util.py:output_figure`` has it. + +The two views +------------- + +``kind="model"`` + Structure only. Drawable before the first sweep, and written once per run. +``kind="state"`` + The same structure with the run painted on -- factor status, update age, + the (factor, variable) pairs whose projection was rejected. Needs an + ``ep_history``; asking for it without one raises rather than quietly + drawing the model view, because a diagnostic figure that silently contains + no diagnostics is worse than an error. + +Examples +-------- +.. code-block:: python + + optimiser = af.graphical.EPOptimiser(model.graph) + result = optimiser.run(model_approx) + + af.EPPlotter(optimiser.factor_graph).figure(path="output", format="png") + af.EPPlotter( + optimiser.factor_graph, ep_history=optimiser.ep_history + ).figure(path="output", format="png", kind="state") +""" + +from typing import Optional + +__all__ = ["EPPlotter"] + +#: ``kind -> default filename``. The names the EP hook writes into a fit's +#: output directory, so a plotter call and a fit produce the same files. +FILENAMES = {"model": "graph_model", "state": "graph_state"} + + +class EPPlotter: + """ + Draw the factor graph an EP fit sweeps, with the fit's state on it. + + Parameters + ---------- + factor_graph + ``EPOptimiser.factor_graph`` -- the graph the optimiser sweeps and the + one its ``EPHistory`` is keyed by. Never a rebuilt + ``AbstractDeclarativeFactor.graph``: that property constructs a new + graph and renames every ``PriorFactor`` on each access, and the history + would then match nothing. + ep_history + ``EPOptimiser.ep_history``. Optional: without it only the model view + can be drawn. + model_approx + The latest ``EPMeanField``. Accepted and passed through; posterior + values (mean, std, precision, KL) are a later overlay. + """ + + def __init__(self, factor_graph, ep_history=None, model_approx=None): + self.factor_graph = factor_graph + self.ep_history = ep_history + self.model_approx = model_approx + self._specs = {} + self._state = None + + # -- the layers --------------------------------------------------------- + + def spec(self, show_prior_factors: bool = False): + """Layer 1 -- the (cached) structure of the factor graph.""" + from .spec import EPGraphSpec + + if show_prior_factors not in self._specs: + self._specs[show_prior_factors] = EPGraphSpec.from_factor_graph( + self.factor_graph, show_prior_factors=show_prior_factors + ) + return self._specs[show_prior_factors] + + def state(self, show_prior_factors: bool = False): + """ + Layer 2 -- what the run did, or ``None`` when there is no history. + + Not cached across ``show_prior_factors`` settings: the overlay is + painted onto a spec's keys, and the two specs have different ones. + """ + if self.ep_history is None: + return None + + from .spec import factor_by_key + from .state import EPState + + return EPState.from_history( + self.spec(show_prior_factors=show_prior_factors), + self.ep_history, + factor_by_key(self.factor_graph), + model_approx=self.model_approx, + ) + + def presentation(self, kind: str = "model", show_prior_factors: bool = False): + """Layer 3 -- nodes, edges, plates, legend and footer.""" + from .presentation import build_ep_presentation + + return build_ep_presentation( + self.spec(show_prior_factors=show_prior_factors), + self._state_for(kind, show_prior_factors), + ) + + def layout( + self, + kind: str = "model", + show_prior_factors: bool = False, + width: float = 14.0, + style=None, + ): + """Layer 4 -- every box of the figure, in inches.""" + from autofit.model_figure.layout import Style + + from .layout import build_ep_layout + + return build_ep_layout( + self.presentation(kind=kind, show_prior_factors=show_prior_factors), + style=style or Style(width=width), + ) + + # -- the figure --------------------------------------------------------- + + def figure( + self, + path=None, + filename: Optional[str] = None, + format: str = "show", + kind: str = "model", + show_prior_factors: bool = False, + width: float = 14.0, + style=None, + ): + """ + Draw the EP figure and show or save it. + + Parameters + ---------- + path + The **directory** the file is written to (as everywhere else in + autofit). ``None`` writes nothing. + filename + The file's stem; the extension comes from ``format``. Defaults to + ``graph_model`` or ``graph_state`` by ``kind``, which are the names + a fit's own output carries. + format + ``show`` | ``png`` | ``svg`` | ``pdf``, or ``None`` to build the + figure without showing or writing it. + kind + ``model`` (the graph) or ``state`` (the graph with the run on it). + show_prior_factors + Draw the graph's ``PriorFactor``s as nodes of their own. Off by + default: there is one per prior, and they treble the node count to + say what a stub on the variable already says. + width + The width budget in inches. Text is never scaled down to fit. + + Returns + ------- + The ``matplotlib`` ``Figure``. + """ + from .render import draw, save + + layout = self.layout( + kind=kind, + show_prior_factors=show_prior_factors, + width=width, + style=style, + ) + figure = draw(layout, layout.style) + return save( + figure, + path=path, + filename=filename or FILENAMES[kind], + format=format, + ) + + # -- internals ---------------------------------------------------------- + + def _state_for(self, kind: str, show_prior_factors: bool): + if kind == "model": + return None + if kind != "state": + raise ValueError( + f"kind must be 'model' or 'state', not {kind!r}", + ) + if self.ep_history is None: + raise ValueError( + "kind='state' draws what an EP run has done to the graph, so it " + "needs the optimiser's history: " + "EPPlotter(optimiser.factor_graph, ep_history=optimiser.ep_history). " + "Without one, only kind='model' can be drawn." + ) + return self.state(show_prior_factors=show_prior_factors) diff --git a/autofit/model_figure/ep/presentation.py b/autofit/model_figure/ep/presentation.py new file mode 100644 index 000000000..ca3591577 --- /dev/null +++ b/autofit/model_figure/ep/presentation.py @@ -0,0 +1,676 @@ +""" +Layer 3 of the EP figure -- what is drawn, in words rather than coordinates. + +:class:`~autofit.model_figure.ep.spec.EPGraphSpec` says what the graph is and +:class:`~autofit.model_figure.ep.state.EPState` says what the run did to it. +This module decides what a *reader* is shown: which nodes exist after the +plates collapse, what each one is titled and badged, which member of a plate is +exceptional enough to be drawn on its own, and what the legend and footer say. + +Nothing here knows about inches or matplotlib. The same presentation is the +model view (``state=None`` -- structure only, drawable before a fit starts) and +the state view (``state`` supplied -- the same structure with the run painted +on). + +The rules +--------- + +**A plate is drawn once.** Every member of a +:class:`~autofit.model_figure.ep.spec.PlateGroup` collapses into one node, +titled by what made the group (the analysis factors' class, or the +hierarchical group's shared name) and badged ``N datasets`` / ``N members``. + +**An aggregate is never shown without its exceptions.** With a state, the +plate node carries the group's *modal* status -- and any member that differs +from the rest (a different status, a rejected projection, or an older last +update) is named in the plate's note **and** drawn as a node of its own beside +the plate. A figure that says "3 datasets, working" while one of them has not +updated since sweep 1 is worse than no figure at all. + +**A label says what the reader can look up.** Inside a plate the factor prefix +is already stripped by the spec (``centre``, not ``AnalysisFactor0.centre``); +here the same is done for a variable that every member of a plate shares, which +the spec has to leave qualified because it sits outside the plate. A +hierarchical distribution's own parameters keep their qualified names -- there +is exactly one of each, and ``HierarchicalFactor0.mean`` is what +``graph.info`` calls it. + +**An edge carries the sharpest true claim.** A stale factor's edges are stale +(the factor never landed an update at all, which subsumes any rejection); an +edge whose (factor, variable) pair the latest projection rejected is reverted; +everything else is a plain incidence. A plate's edges speak for the members the +plate still stands for -- an exceptional member is drawn beside the plate with +edges of its own -- and where several of those members disagree the more +specific claim wins. +""" + +from dataclasses import asdict, dataclass, field +from typing import Any, Dict, List, Optional, Tuple + +from autofit.model_figure.ep.spec import EPGraphSpec, _strip_prefix + +__all__ = [ + "EPNode", + "EPEdge", + "EPPlate", + "EPPresentation", + "build_ep_presentation", + "FACTOR_NODE_KINDS", + "VARIABLE_NODE_KINDS", +] + +#: Node kinds that are factors. A node's kind is the only thing that says +#: which side of the bipartite graph it is on, so the two sets never overlap. +FACTOR_NODE_KINDS = ("analysis", "hierarchical", "prior", "factor") + +#: Node kinds that are variables. +VARIABLE_NODE_KINDS = ("free", "drawn", "hyper") + +#: Edge kinds, sharpest claim first -- the order a plate edge merges by. +EDGE_KINDS = ("reverted", "stale", "incidence") + +#: Status tie-break when a plate's members are evenly split: the more alarming +#: status is the one the plate reports, because the exceptional members are +#: listed either way and a missed warning is the expensive error. +_STATUS_PRECEDENCE = ("stale", "reverting", "absent", "converged", "working") + + +def _plural(count: int, word: str) -> str: + return f"{count} {word}" if count == 1 else f"{count} {word}s" + + +@dataclass(frozen=True) +class EPNode: + """ + One node of the figure -- a factor, a plate of factors, or a variable. + + Attributes + ---------- + key + The node's identity. A plate node is keyed by its plate, every other + node by the spec node it stands for. + title + What the node reads. + subtitle + A second, quieter line -- a plate member says which member it is. + badges + Short tags drawn after the title: ``3 datasets``, ``x3``, + ``2 updates / 4 sweeps``, ``age 3``, ``BAD_PROJECTION``. + state + The factor's status from :class:`~autofit.model_figure.ep.state.EPState` + (``None`` in the model view and on every variable node). + note + A full-width line under the node -- the plate's exception list. + members + The spec factor keys this node stands for. Non-empty only on a plate + node. + kind + One of :data:`FACTOR_NODE_KINDS` or :data:`VARIABLE_NODE_KINDS`. + plate_key + The plate this node belongs to, or ``None``. + """ + + key: str + title: str + subtitle: Optional[str] = None + badges: Tuple[str, ...] = () + state: Optional[str] = None + note: Optional[str] = None + members: Tuple[str, ...] = () + kind: str = "factor" + plate_key: Optional[str] = None + + @property + def is_factor(self) -> bool: + return self.kind in FACTOR_NODE_KINDS + + @property + def is_variable(self) -> bool: + return self.kind in VARIABLE_NODE_KINDS + + def to_dict(self) -> Dict[str, Any]: + return asdict(self) + + +@dataclass(frozen=True) +class EPEdge: + """ + One line of the figure: a factor node is joined to a variable node. + + ``kind`` is one of :data:`EDGE_KINDS`. ``label`` is the name the factor + gives the variable; it is not drawn (the variable node already carries it) + but it is what a test reads to check *which* pair reverted. + """ + + source_key: str + target_key: str + kind: str = "incidence" + label: str = "" + + def to_dict(self) -> Dict[str, Any]: + return asdict(self) + + +@dataclass(frozen=True) +class EPPlate: + """ + A dashed frame and the nodes it encloses. + + ``node_keys`` is what the frame is drawn around: the plate node, the + variable nodes that live inside it, and any exceptional member expanded + beside it. An expanded member is still a member -- a frame that cut through + its box would say it was half in the group. + """ + + key: str + title: str + kind: str + count: int + badge: str = "" + member_keys: Tuple[str, ...] = () + node_keys: Tuple[str, ...] = () + + def to_dict(self) -> Dict[str, Any]: + return asdict(self) + + +@dataclass(frozen=True) +class EPPresentation: + """Everything the layout engine needs, and nothing about geometry.""" + + nodes: Tuple[EPNode, ...] = () + edges: Tuple[EPEdge, ...] = () + plates: Tuple[EPPlate, ...] = () + legend: str = "" + footer: str = "" + kind: str = "model" + + def to_dict(self) -> Dict[str, Any]: + return { + "nodes": [node.to_dict() for node in self.nodes], + "edges": [edge.to_dict() for edge in self.edges], + "plates": [plate.to_dict() for plate in self.plates], + "legend": self.legend, + "footer": self.footer, + "kind": self.kind, + } + + def node(self, key: str) -> EPNode: + """The node with ``key`` -- raises rather than returning ``None``.""" + for node in self.nodes: + if node.key == key: + return node + raise KeyError(key) + + def factor_nodes(self) -> Tuple[EPNode, ...]: + return tuple(node for node in self.nodes if node.is_factor) + + def variable_nodes(self) -> Tuple[EPNode, ...]: + return tuple(node for node in self.nodes if node.is_variable) + + +# ---------------------------------------------------------------------------- +# the transformation +# ---------------------------------------------------------------------------- + + +@dataclass +class _Group: + """A plate, its members' states, and what the collapse decided about them.""" + + plate: Any + modal_status: Optional[str] = None + modal_age: int = 0 + exceptional: Tuple[str, ...] = () + reasons: Dict[str, str] = field(default_factory=dict) + representative_state: Any = None + + +class _Context: + """Everything the rules need to see the whole spec at once.""" + + def __init__(self, spec: EPGraphSpec, state): + self.spec = spec + self.state = state + + self.factor_nodes = {factor.key: factor for factor in spec.factors} + self.variable_nodes = {variable.key: variable for variable in spec.variables} + self.plates = {plate.key: plate for plate in spec.plates} + + self.factor_state = ( + {factor.key: factor for factor in state.factors} if state else {} + ) + + #: variable key -> the factor keys incident on it + self.incident: Dict[str, List[str]] = {} + for incidence in spec.incidences: + keys = self.incident.setdefault(incidence.variable_key, []) + if incidence.factor_key not in keys: + keys.append(incidence.factor_key) + + self.groups = { + plate.key: self._group(plate) for plate in spec.plates + } # plate key -> _Group + + #: spec factor key -> the node key it collapses into + self.collapsed: Dict[str, str] = {} + for factor in spec.factors: + if factor.plate_key is not None and factor.kind != "prior": + self.collapsed[factor.key] = factor.plate_key + else: + self.collapsed[factor.key] = factor.key + + # -- plates ------------------------------------------------------------ + + def _group(self, plate) -> _Group: + group = _Group(plate=plate) + if not self.state: + return group + + states = [self.factor_state[key] for key in plate.member_keys] + group.modal_status = _mode( + [state.status for state in states], _STATUS_PRECEDENCE + ) + group.modal_age = _mode(sorted(state.age for state in states), ()) + group.representative_state = next( + state for state in states if state.status == group.modal_status + ) + + exceptional = [] + for key, state in zip(plate.member_keys, states): + reason = self._reason(state, group) + if reason is not None: + exceptional.append(key) + group.reasons[key] = reason + group.exceptional = tuple(exceptional) + return group + + @staticmethod + def _reason(state, group: _Group) -> Optional[str]: + """ + Why this member is not what the plate says -- or ``None``. + + The three tests are the plan's: a status the rest do not have, a + projection the latest sweep rejected, or a last update older than the + rest's. + """ + if state.status != group.modal_status: + return state.status + if state.reverted_variable_keys: + return "reverting" + if state.age > group.modal_age: + return "older" + return None + + # -- what a node is called --------------------------------------------- + + def plate_title(self, plate) -> str: + """ + The class the members share (analysis), or the name they share + (hierarchical) -- both are ``signature[1]``, which is exactly what made + them a group. + """ + if len(plate.signature) > 1 and isinstance(plate.signature[1], str): + return plate.signature[1] + return self.factor_nodes[plate.representative_key].name + + def plate_badge(self, plate) -> str: + word = "dataset" if plate.kind == "analysis" else "member" + return _plural(plate.count, word) + + def note(self, group: _Group) -> Optional[str]: + """ + ``1 of 3 stale: AnalysisFactor2`` -- the exception list, never omitted. + """ + if not group.exceptional: + return None + reasons = {group.reasons[key] for key in group.exceptional} + word = reasons.pop() if len(reasons) == 1 else "exceptional" + names = ", ".join(self.factor_nodes[key].name for key in group.exceptional) + return f"{len(group.exceptional)} of {group.plate.count} {word}: {names}" + + # -- badges ------------------------------------------------------------ + + def factor_badges(self, state) -> Tuple[str, ...]: + """ + What the run did, in three tags: how much it updated, how long ago, and + how the last visit ended when it did not end well. + """ + if state is None: + return () + badges = [f"{_plural(state.updates, 'update')} / {state.sweeps} sweeps"] + if state.age > 0: + badges.append(f"age {state.age}") + if state.last_flag is not None and state.last_flag != "SUCCESS": + badges.append(state.last_flag) + return tuple(badges) + + def variable_badges(self, variable) -> Tuple[str, ...]: + """ + ``hyper`` for a distribution's own parameter, ``shared x N`` for a + variable every member of a plate holds, ``xN`` for one the plate + repeats. + """ + if variable.kind == "hyper": + return ("hyper",) + if variable.plate_key is not None and variable.count > 1: + return (f"x{variable.count}",) + plate = self._shared_plate(variable) + if plate is not None: + return (f"shared x {plate.count}",) + return () + + def _shared_plate(self, variable): + """ + The plate every one of whose members is incident on ``variable``. + + This is the spec's "genuinely shared" case: the variable is drawn + outside the plate (``plate_key is None``) because it belongs to all of + them, not to one. + """ + if variable.plate_key is not None: + return None + incident = set(self.incident.get(variable.key, ())) + for plate in self.spec.plates: + if incident.issuperset(plate.member_keys): + return plate + return None + + def variable_title(self, variable) -> str: + """ + The label, with a factor prefix stripped when the plate already says + which factor it came from. + + The spec strips the prefix inside a plate; a *shared* variable sits + outside one, so the spec has to leave ``AnalysisFactor0.centre`` + qualified -- but a node joined to all three members is not + ``AnalysisFactor0``'s, and naming one member is worse than naming none. + Hyper parameters keep their qualified names: there is one of each and + the name is what ``graph.info`` prints. + """ + if variable.kind == "hyper": + return variable.label + plate = self._shared_plate(variable) + if plate is None: + return variable.label + label = variable.label + for key in plate.member_keys: + label = _strip_prefix(label, self.factor_nodes[key].name) + return label + + +def _mode(values, precedence): + """ + The most common value, ties broken by ``precedence`` then by first + appearance -- deterministic either way. + """ + values = list(values) + if not values: + return None + counts: Dict[Any, int] = {} + order: Dict[Any, int] = {} + for index, value in enumerate(values): + counts[value] = counts.get(value, 0) + 1 + order.setdefault(value, index) + + def rank(value): + try: + return precedence.index(value) + except (ValueError, AttributeError): + return order[value] + + return min(counts, key=lambda value: (-counts[value], rank(value))) + + +def _edge_kind(state, variable_key: str) -> str: + """ + The claim one (factor, variable) incidence makes. + + ``stale`` outranks ``reverted`` *within a factor* for the same reason it + outranks ``reverting`` on the node: a factor that never landed an update is + making the stronger statement about every one of its variables. + """ + if state is None: + return "incidence" + if state.status == "stale": + return "stale" + if variable_key in state.reverted_variable_keys: + return "reverted" + return "incidence" + + +def _sharpest(first: str, second: str) -> str: + """The more specific of two claims merged onto one plate edge.""" + return min((first, second), key=EDGE_KINDS.index) + + +def build_ep_presentation(spec: EPGraphSpec, state=None) -> EPPresentation: + """ + Turn a spec (and optionally a state) into the nodes, edges and plates that + are drawn. + + Parameters + ---------- + spec + The structure, from + :meth:`~autofit.model_figure.ep.spec.EPGraphSpec.from_factor_graph`. + state + The overlay, from + :meth:`~autofit.model_figure.ep.state.EPState.from_history`. ``None`` + gives the **model view**: the same figure with no run painted on it, + which is what is drawn before the first sweep. + + Returns + ------- + An :class:`EPPresentation`. + """ + context = _Context(spec, state) + + nodes: List[EPNode] = [] + plate_nodes: Dict[str, List[str]] = {plate.key: [] for plate in spec.plates} + expanded: Dict[str, str] = {} # spec factor key -> its own node key + + # -- factor nodes, in declaration order, plates in their first member's place + seen_plates = set() + for factor in spec.factors: + if factor.kind == "prior": + continue # emitted last, beside their variable + + if factor.plate_key is None: + state_of = context.factor_state.get(factor.key) + nodes.append( + EPNode( + key=factor.key, + title=factor.name, + badges=context.factor_badges(state_of), + state=state_of.status if state_of else None, + kind=factor.kind, + ) + ) + continue + + group = context.groups[factor.plate_key] + if factor.plate_key not in seen_plates: + seen_plates.add(factor.plate_key) + plate = context.plates[factor.plate_key] + nodes.append( + EPNode( + key=plate.key, + title=context.plate_title(plate), + badges=(context.plate_badge(plate),) + + context.factor_badges(group.representative_state), + state=group.modal_status, + note=context.note(group), + members=plate.member_keys, + kind=plate.kind, + plate_key=plate.key, + ) + ) + plate_nodes[plate.key].append(plate.key) + + if factor.key in group.exceptional: + # Never an aggregate without its exceptions: this member is drawn + # on its own, beside the plate, with its own edges. + state_of = context.factor_state[factor.key] + expanded[factor.key] = factor.key + plate_nodes[factor.plate_key].append(factor.key) + nodes.append( + EPNode( + key=factor.key, + title=factor.name, + subtitle=( + f"member {factor.member_index + 1} " + f"of {context.plates[factor.plate_key].count}" + ), + badges=context.factor_badges(state_of), + state=state_of.status, + kind=factor.kind, + plate_key=factor.plate_key, + ) + ) + + # -- variable nodes + for variable in spec.variables: + nodes.append( + EPNode( + key=variable.key, + title=context.variable_title(variable), + badges=context.variable_badges(variable), + kind=variable.kind, + plate_key=variable.plate_key, + ) + ) + if variable.plate_key is not None: + plate_nodes[variable.plate_key].append(variable.key) + + # -- prior stubs, last, so they sit beside the variable they wrap + for factor in spec.factors: + if factor.kind != "prior": + continue + (variable_key,) = factor.variable_keys + variable = context.variable_nodes[variable_key] + nodes.append( + EPNode( + key=factor.key, + title="prior", + badges=(f"x{variable.count}",) if variable.count > 1 else (), + kind="prior", + plate_key=factor.plate_key, + ) + ) + if factor.plate_key is not None: + plate_nodes[factor.plate_key].append(factor.key) + + # -- edges, one per incidence after the collapse + # + # A plate's edge speaks for the members the plate still stands for: an + # exceptional member is drawn beside the plate with edges of its own, so + # its claim is already on the figure and does not also colour the + # aggregate. When *every* member is exceptional the plate would otherwise + # be left floating, so then they all contribute. + contributions: Dict[Tuple[str, str], List[Tuple[str, bool, str]]] = {} + order: List[Tuple[str, str]] = [] + + def _contribute(source, variable_key, kind, exceptional, label): + edge_key = (source, variable_key) + if edge_key not in contributions: + contributions[edge_key] = [] + order.append(edge_key) + contributions[edge_key].append((kind, exceptional, label)) + + for incidence in spec.incidences: + state_of = context.factor_state.get(incidence.factor_key) + kind = _edge_kind(state_of, incidence.variable_key) + is_exceptional = incidence.factor_key in expanded + + _contribute( + context.collapsed[incidence.factor_key], + incidence.variable_key, + kind, + is_exceptional, + incidence.label, + ) + if is_exceptional: + _contribute( + incidence.factor_key, + incidence.variable_key, + kind, + False, + incidence.label, + ) + + edges = [] + for source, target in order: + entries = contributions[(source, target)] + speaking = [entry for entry in entries if not entry[1]] or entries + kind = speaking[0][0] + for other in speaking[1:]: + kind = _sharpest(kind, other[0]) + edges.append( + EPEdge( + source_key=source, + target_key=target, + kind=kind, + label=speaking[0][2], + ) + ) + edges = tuple(edges) + + plates = tuple( + EPPlate( + key=plate.key, + title=context.plate_title(plate), + kind=plate.kind, + count=plate.count, + badge=context.plate_badge(plate), + member_keys=plate.member_keys, + node_keys=tuple(plate_nodes[plate.key]), + ) + for plate in spec.plates + ) + + return EPPresentation( + nodes=tuple(nodes), + edges=edges, + plates=plates, + legend=_legend(state), + footer=_footer(spec, state), + kind="state" if state else "model", + ) + + +def _legend(state) -> str: + lines = ["box = factor", "pill = variable", "dashed frame = repeated structure"] + if state is not None: + lines += [ + "grey = stale (never updated)", + "red dashed = reverted update", + "green = converged", + ] + return " ".join(lines) + + +def _footer(spec: EPGraphSpec, state) -> str: + """ + The counts a reader checks the picture against. + + Prior stubs are excluded from the factor count: a stub stands for a group + of ``PriorFactor``s and counting it would make the footer disagree with + ``graph.info``. + """ + factors = [factor for factor in spec.factors if factor.kind != "prior"] + parts = [ + _plural(len(factors), "factor"), + _plural(len(spec.variables), "variable"), + _plural(len(spec.plates), "plate"), + ] + if state is not None: + keys = {factor.key for factor in factors} + statuses = [factor.status for factor in state.factors if factor.key in keys] + for status in ("stale", "reverting", "converged", "working"): + parts.append(f"{statuses.count(status)} {status}") + absent = statuses.count("absent") + if absent: + parts.append(f"{absent} absent") + parts.append(f"sweep {state.step}") + return " ".join(parts) diff --git a/autofit/model_figure/ep/render.py b/autofit/model_figure/ep/render.py new file mode 100644 index 000000000..0439022f0 --- /dev/null +++ b/autofit/model_figure/ep/render.py @@ -0,0 +1,331 @@ +""" +Layer 5 of the EP figure -- drawing. + +Pure matplotlib, and pure *re-use*: the palette, the rounded box, the text +helper, the badge colours, the link colours and :func:`save` all come from +:mod:`autofit.model_figure.render`, so the two figures cannot drift apart. What +this module adds is the encoding the diagnostic view needs and the model figure +has no use for -- a factor's status painted on its node, and a rejected update +painted on the edge that carries it. + +The encoding +------------ + +======================= ==================================================== +what how +======================= ==================================================== +analysis factor a tinted rounded card, as a model card is +hierarchical factor a violet card, as a hyper card is +variable a white pill +plate a dashed frame, as plate notation has it +stale factor grey fill, muted text, and its edges greyed +reverting factor a red outline; the rejected edge is dashed red with + an arrow head landing on the variable that was put + back +converged factor a green outline +working / absent the default outline +======================= ==================================================== + +There is no *observed data* node: the EP spec is read from the factor graph, +which carries no notion of the data an ``AnalysisFactor``'s analysis holds. The +model figure draws observed rows because its spec has them; inventing one here +would be a claim the figure cannot support. + +matplotlib is imported inside the functions, as everywhere else in +``model_figure``, so ``import autofit`` stays drawing-free. +""" + +from autofit.model_figure.render import ( + PALETTE, + _LINK_COLOURS, + _badge_colours, + _box, + _text, + save, +) + +__all__ = ["draw", "save", "PALETTE"] + +#: ``state -> (face, edge, text, line width)`` for a factor node. +_STATE_STYLE = { + "stale": (PALETTE["grey_fill"], PALETTE["plate_border"], PALETTE["muted"], 0.9), + "reverting": (None, PALETTE["red"], PALETTE["text"], 1.1), + "converged": (None, PALETTE["green"], PALETTE["text"], 1.0), + "working": (None, PALETTE["border"], PALETTE["text"], 0.9), + "absent": (None, PALETTE["pill_border"], PALETTE["muted"], 0.8), +} + +#: ``edge kind -> (colour, dashed, arrow head)``. +_EDGE_STYLE = { + "incidence": (PALETTE["muted"], False, False), + "stale": (PALETTE["pill_border"], False, False), + "reverted": (PALETTE["red"], True, True), +} + +#: The face colour of a factor node, before its state has a say. +_FACE = { + "analysis": PALETTE["tints"][1], + "hierarchical": PALETTE["violet_fill"], + "prior": PALETTE["tints"][2], + "factor": PALETTE["tints"][1], +} + +#: The edge colour of a factor node, before its state has a say. +_EDGE = { + "analysis": PALETTE["border"], + "hierarchical": PALETTE["violet"], + "prior": PALETTE["pill_border"], + "factor": PALETTE["border"], +} + + +def _node_colours(box): + """ + ``(face, edge, text, line width)`` for one node. + + The kind decides what the node *is*; the state decides what the run made of + it, and where the two disagree the state wins -- a stale analysis factor is + grey, not tinted, because "this never updated" is the thing the reader has + to see first. + """ + if box.kind in ("free", "drawn", "hyper"): + face = PALETTE["violet_fill"] if box.kind == "drawn" else "#ffffff" + edge = PALETTE["violet"] if box.kind == "drawn" else PALETTE["pill_border"] + return face, edge, PALETTE["text"], 0.8 + + face = _FACE.get(box.kind, _FACE["factor"]) + edge = _EDGE.get(box.kind, _EDGE["factor"]) + text = PALETTE["text"] + width = 0.9 + + state = _STATE_STYLE.get(box.state) + if state is not None: + state_face, state_edge, state_text, state_width = state + face = state_face or face + edge = state_edge + text = state_text + width = state_width + return face, edge, text, width + + +def _draw_node(ax, box, style): + from autofit.model_figure.layout import _line_height, measure_text + + face, edge, colour, width = _node_colours(box) + variable = box.kind in ("free", "drawn", "hyper") + title_size = style.pill_size if variable else style.title_size + + _box( + ax, + box.x, + box.y, + box.width, + box.height, + face=face, + edge=edge, + lw=width, + radius=0.06 if variable else 0.04, + z=20, + ) + + title_middle = box.title_y + _line_height(title_size) / 2 + _text( + ax, + box.x + box.pad, + title_middle, + box.title, + size=title_size, + colour=colour, + weight="normal" if variable else "bold", + z=40, + ) + + offset = box.badge_offset + for badge in box.badges: + fill, badge_colour = _badge_colours( + badge, "drawn" if box.kind == "drawn" else "free" + ) + badge_width = measure_text(badge, style.badge_size)[0] + 0.12 + _box( + ax, + box.x + offset, + box.y + box.pad + 0.02, + badge_width, + _line_height(title_size) - 0.04, + face=fill, + edge=fill, + radius=0.02, + z=30, + ) + _text( + ax, + box.x + offset + 0.05, + title_middle, + badge, + size=style.badge_size, + colour=badge_colour, + z=40, + ) + offset += badge_width + style.inner_gap + + if box.subtitle: + _text( + ax, + box.x + box.pad, + box.subtitle_y + _line_height(style.badge_size) / 2, + box.subtitle, + size=style.badge_size, + colour=PALETTE["muted"], + z=40, + ) + if box.note: + # The exception list is the one thing on the figure a reader must not + # skim past, so it is drawn in the reverting colour rather than muted. + _text( + ax, + box.x + box.pad, + box.note_y + _line_height(style.note_size) / 2, + box.note, + size=style.note_size, + colour=PALETTE["red"] if box.state != "stale" else PALETTE["muted"], + z=40, + ) + + +def _draw_edge(ax, route, boxes): + """ + One edge. + + A plain incidence from a hierarchical factor onto the variable it draws is + coloured with the model figure's own ``draw`` colour: it is the same claim + that figure's violet arrow makes, and the two must not say it in different + colours. + """ + from matplotlib.lines import Line2D + from matplotlib.patches import FancyArrowPatch + + colour, dashed, arrow = _EDGE_STYLE.get(route.kind, _EDGE_STYLE["incidence"]) + source = boxes.get(route.source_key) + target = boxes.get(route.target_key) + if ( + route.kind == "incidence" + and source is not None + and target is not None + and source.kind == "hierarchical" + and target.kind == "drawn" + ): + colour = _LINK_COLOURS["draw"] + xs = [x for x, _ in route.points] + ys = [y for _, y in route.points] + + ax.add_line( + Line2D( + xs[:-1] if arrow else xs, + ys[:-1] if arrow else ys, + color=colour, + linewidth=1.0 if route.kind == "reverted" else 0.8, + linestyle=(0, (2.6, 1.8)) if dashed else "solid", + solid_capstyle="round", + zorder=10, + ) + ) + if arrow: + # A reverted update is *directed*: the message was put back onto this + # variable, so the head lands on the variable's pill. + ax.add_patch( + FancyArrowPatch( + (xs[-2], ys[-2]), + (xs[-1], ys[-1]), + arrowstyle="-|>", + mutation_scale=7.0, + linewidth=1.0, + linestyle="dashed", + color=colour, + shrinkA=0.0, + shrinkB=0.0, + zorder=11, + ) + ) + + +def _draw_plate(ax, frame, style): + from autofit.model_figure.layout import _line_height, measure_text + + _box( + ax, + frame.x, + frame.y, + frame.width, + frame.height, + face="none", + edge=PALETTE["plate_border"], + dashed=True, + lw=0.9, + radius=0.05, + z=5, + ) + if frame.title: + width = measure_text(frame.title, style.badge_size)[0] + 0.1 + height = _line_height(style.badge_size) + _text( + ax, + frame.x + frame.width - width, + frame.y + frame.height - height / 2 - 0.02, + frame.title, + size=style.badge_size, + colour=PALETTE["muted"], + z=6, + ) + + +def draw(layout, style=None): + """ + Draw a measured :class:`~autofit.model_figure.ep.layout.EPLayout`. + + One axes, one inch per data unit, y inverted and the axis off -- the same + canvas the model figure uses, so every coordinate the layout computed is + used verbatim. + """ + import matplotlib.pyplot as plt + + from autofit.model_figure.layout import _line_height + + style = style or layout.style + + figure = plt.figure(figsize=(layout.width, layout.height), dpi=style.dpi) + ax = figure.add_axes([0.0, 0.0, 1.0, 1.0]) + ax.set_xlim(0.0, layout.width) + ax.set_ylim(layout.height, 0.0) + ax.set_aspect("equal") + ax.axis("off") + figure.patch.set_facecolor("#ffffff") + + for frame in layout.plates: + _draw_plate(ax, frame, style) + boxes = {box.key: box for box in layout.nodes} + for route in layout.edges: + _draw_edge(ax, route, boxes) + for box in layout.nodes: + _draw_node(ax, box, style) + + if layout.legend: + _text( + ax, + style.margin, + layout.legend_y + _line_height(style.footer_size) / 2, + layout.legend, + size=style.footer_size, + colour=PALETTE["muted"], + z=90, + ) + if layout.footer: + _text( + ax, + style.margin, + layout.footer_y + _line_height(style.footer_size) / 2, + layout.footer, + size=style.footer_size, + colour=PALETTE["text"], + z=90, + ) + return figure diff --git a/autofit/model_figure/ep/spec.py b/autofit/model_figure/ep/spec.py new file mode 100644 index 000000000..2cfefa3bf --- /dev/null +++ b/autofit/model_figure/ep/spec.py @@ -0,0 +1,644 @@ +""" +Layer 1 of the EP figure -- the structure of the factor graph. + +:class:`EPGraphSpec` is a flat, frozen, JSON-serialisable description of the +graph an :class:`~autofit.graphical.EPOptimiser` sweeps: factor nodes, variable +nodes, the edges between them, and the plates that collapse repeated structure. +It holds no live objects, so the picture it describes cannot drift while a fit +runs. + +Where the structure comes from +------------------------------ + +The source of truth is the optimiser's own ``factor_graph`` -- the +:class:`~autofit.graphical.declarative.graph.DeclarativeFactorGraph` handed to +:class:`~autofit.graphical.EPOptimiser`. It is **never** rebuilt from +``AbstractDeclarativeFactor.graph`` or ``model_approx.factor_graph``: that +property constructs a new graph on every access, renaming every +``PriorFactor`` as it goes, and ``EPHistory`` is keyed by the *optimiser's* +factor objects. So ``from_factor_graph`` iterates ``factor_graph.factors`` +exactly once, into tuples. + +Plates +------ + +Phase 4's ``_collapse_siblings`` needs a ``GlobalPriorModel`` and is therefore +unreachable here, so repetition is inferred at *factor* level: + +* ``AnalysisFactor``s are grouped by **signature** -- the factor's class name, + the tuple of dotted paths at which its prior model holds priors, and the + tuple of prior class names at those paths. Three datasets fitted with the + same ``Gaussian`` share a signature; a fourth with an extra parameter does + not. +* ``_HierarchicalFactor``s are grouped by ``factor.name``, which is + ``distribution_model.name`` -- the very key ``EPOptimiser`` itself uses to + group a hierarchical factor's members when it reports staleness. + +A group of two or more becomes a :class:`PlateGroup`, ordered by its first +member's index in ``factor_graph.factors``; members keep declaration order. + +A variable incident on **exactly one** member of a plate is drawn *inside* it +as a single :class:`VariableNode` with ``count=N``; a variable incident on +**every** member is genuinely shared and is drawn once *outside* the plate +(``plate_key is None``). A variable that qualifies for two plates -- the drawn +``centre`` of a hierarchical model belongs to one ``AnalysisFactor`` and to one +``_HierarchicalFactor`` -- is placed in the first plate in plate order, and the +other plate's edge simply crosses into it. + +Labels +------ + +Every label comes from :func:`label_for_variable`, i.e. from +``factor.name_for_variable`` -- never from ``variable.label``, which is a +global-counter form (``centre1``, ``cls3``) that means nothing to a reader. +Inside a plate the factor prefix is stripped, so ``AnalysisFactor0.centre`` +reads ``centre``. + +Keys +---- + +Every key is built from **declaration indices** -- a factor's position in +``factor_graph.factors`` and a variable's position within its owning factor. +No key contains an ``id()``, a ``Prior`` id or a ``namer`` counter, so two +builds of the same graph produce byte-identical keys. +""" + +from dataclasses import asdict, dataclass +from typing import Any, Dict, List, Optional, Tuple + +__all__ = [ + "FactorNode", + "VariableNode", + "Incidence", + "PlateGroup", + "EPGraphSpec", + "label_for_variable", + "factor_key", + "factor_by_key", +] + +#: ``FactorNode.kind`` values. +FACTOR_KINDS = ("analysis", "hierarchical", "prior", "factor") + +#: ``VariableNode.kind`` values. ``drawn`` is a variable a +#: ``HierarchicalFactor`` draws from its parent distribution; ``hyper`` is one +#: of that distribution's own parameters; everything else is ``free``. +VARIABLE_KINDS = ("free", "drawn", "hyper") + + +def factor_key(index: int) -> str: + """ + The key of the factor at ``index`` in ``factor_graph.factors``. + """ + return f"factor-{index}" + + +def factor_by_key(factor_graph) -> Dict[str, Any]: + """ + Map every spec factor key to the live factor object it describes. + + :class:`~autofit.model_figure.ep.state.EPState` needs this to look a + factor's :class:`~autofit.graphical.expectation_propagation.history.FactorHistory` + up in an ``EPHistory``, which is keyed by the factor objects themselves. + The spec deliberately holds no live objects, so the mapping is rebuilt here + from the same declaration indices the keys are built from. + + Keys for collapsed ``PriorFactor`` stubs are absent: a stub stands for a + whole group of prior factors and so has no single history. + """ + return { + factor_key(index): factor for index, factor in enumerate(factor_graph.factors) + } + + +def _model_path(factor, variable) -> Optional[str]: + """ + The dotted path at which ``factor``'s prior model holds ``variable``. + + Used only to separate variables a factor names identically -- + ``_HierarchicalFactor.name_for_variable`` returns the distribution model's + name for *every* one of its variables. ``distribution_model`` and + ``drawn_prior``, the two structural segments a ``_HierarchicalFactor``'s + internal ``Collection`` adds, are dropped, so the parent's ``mean`` reads + ``HierarchicalFactor0.mean``. + + ``None`` when there is no prior model, no path, or a path with a + positional segment (``PriorFactor``'s trivial ``Collection(prior)`` holds + its prior at ``("0",)``) -- a number is no more informative than the + factor's own name. + """ + prior_model = getattr(factor, "prior_model", None) + if prior_model is None: + return None + try: + path = prior_model.path_for_prior(variable) + except Exception: # a factor need not implement the model interface + return None + if not path: + return None + parts = [ + str(part) for part in path if part not in ("distribution_model", "drawn_prior") + ] + if not parts or not all(part.isidentifier() for part in parts): + return None + return ".".join(parts) + + +def label_for_variable(factor, variable, slot: Optional[int] = None) -> Optional[str]: + """ + The label ``factor`` gives ``variable``, or ``None`` if it no longer holds it. + + ``factor.name_for_variable`` is the only source: an ``AnalysisFactor`` + answers with its dotted path (``AnalysisFactor0.centre``), and the base + implementation answers with the factor's own name. When that base answer + comes back -- so every variable of the factor would carry the same label -- + the label is qualified, first by the factor's own prior-model path + (:func:`_model_path`), then by the variable's declared name, and finally by + its argument position. Each fallback is declaration-derived, so a label is + unique within its factor and stable across runs. + + ``variable.label`` is never consulted: it is a global-counter form. + + Parameters + ---------- + slot + The variable's position in ``factor.flat_args``. Computed when omitted; + pass it to avoid re-scanning the arguments. + """ + name = factor.name_for_variable(variable) + if name is None: + return None + if name != factor.name: + return name + + path = _model_path(factor, variable) + if path is not None: + return f"{name}.{path}" + + from autofit.mapper.prior.abstract import Prior + + if not isinstance(variable, Prior): + # A plain ``Variable`` carries the name its author gave it. + return f"{name}.{variable.name}" + + if slot is None: + slot = _slot_of(factor, variable) + if slot is None: + return name + return f"{name}.arg{slot}" + + +def _slot_of(factor, variable) -> Optional[int]: + for index, argument in enumerate(factor.flat_args): + if argument is variable: + return index + return None + + +def _strip_prefix(label: str, factor_name: str) -> str: + """ + Drop a factor's own name from the front of a label drawn inside its plate. + + ``AnalysisFactor0.centre`` reads ``centre`` inside the plate -- the plate + already says which member is which. + """ + prefix = f"{factor_name}." + if label.startswith(prefix) and len(label) > len(prefix): + return label[len(prefix) :] + return label + + +def _unique(key: str, used) -> str: + """ + Guarantee a key is not already taken, deterministically. + """ + if key not in used: + return key + suffix = 2 + while f"{key}-{suffix}" in used: + suffix += 1 + return f"{key}-{suffix}" + + +@dataclass(frozen=True) +class FactorNode: + """ + One factor in the figure. + + Attributes + ---------- + key + Declaration-derived identity, e.g. ``factor-3``. A collapsed + ``PriorFactor`` stub is keyed by the variable it wraps. + name + The factor's own name (``AnalysisFactor0``, ``HierarchicalFactor0``). + kind + One of :data:`FACTOR_KINDS`. + member_index + Position within its plate's members, or ``None`` outside a plate. + plate_key + The plate this factor is drawn inside, or ``None``. + variable_keys + Keys of the variable nodes this factor is joined to, in label order. + """ + + key: str + name: str + kind: str + member_index: Optional[int] + plate_key: Optional[str] + variable_keys: Tuple[str, ...] + + +@dataclass(frozen=True) +class VariableNode: + """ + One variable in the figure. + + Attributes + ---------- + key + Declaration-derived identity, e.g. ``plate-0/var-0``. + label + What the node reads, stripped of its factor prefix inside a plate. + kind + One of :data:`VARIABLE_KINDS`. + plate_key + The plate the node is drawn inside, or ``None`` for a shared variable. + count + How many variables this node stands for: ``N`` inside a plate whose + ``N`` members each carry their own copy, ``1`` otherwise. + """ + + key: str + label: str + kind: str + plate_key: Optional[str] + count: int + + +@dataclass(frozen=True) +class Incidence: + """ + One edge: a factor is joined to a variable, and calls it ``label``. + + Plate members each keep their own incidence onto the plate's collapsed + variable node, because the EP state overlay is per (factor, variable) pair + -- one member reverting a variable is not the plate reverting it. + """ + + factor_key: str + variable_key: str + label: str + + +@dataclass(frozen=True) +class PlateGroup: + """ + A run of factors with identical structure, drawn once with a ``x N`` badge. + + Attributes + ---------- + key + Declaration-derived identity, e.g. ``plate-0``. + kind + ``analysis`` or ``hierarchical``. + count + Number of members. + member_keys + The members' factor keys, in declaration order. + signature + What made them a group: the analysis signature, or the shared + hierarchical factor name. + representative_key + The member the plate's labels and kinds are taken from -- the first. + """ + + key: str + kind: str + count: int + member_keys: Tuple[str, ...] + signature: Tuple[Any, ...] + representative_key: str + + +@dataclass(frozen=True) +class EPGraphSpec: + """ + The whole structure, flat and serialisable. + + ``prior_factor_variable_keys`` names the variables a ``PriorFactor`` wraps + even when the prior factors themselves are hidden, so the render layer can + still draw the small stub that says "this variable has a prior" without the + graph's ``PriorFactor``s doubling its node count. + """ + + factors: Tuple[FactorNode, ...] + variables: Tuple[VariableNode, ...] + incidences: Tuple[Incidence, ...] + plates: Tuple[PlateGroup, ...] + prior_factor_variable_keys: Tuple[str, ...] = () + + def to_dict(self) -> Dict[str, Any]: + """ + A plain ``dict`` of builtins -- the determinism artefact. + + ``json.dumps`` of this is byte-stable for a given factor graph. + """ + return asdict(self) + + @classmethod + def from_factor_graph( + cls, factor_graph, show_prior_factors: bool = False + ) -> "EPGraphSpec": + """ + Read a ``DeclarativeFactorGraph`` once, into a spec. + + Parameters + ---------- + factor_graph + ``EPOptimiser.factor_graph`` -- the graph the optimiser sweeps and + the one ``EPHistory`` is keyed by. Never a rebuilt ``.graph``. + show_prior_factors + Draw the graph's ``PriorFactor``s as nodes of their own. Off by + default: there is one per prior, so they treble the node count + while saying only what a stub on the variable already says. + """ + return _Reader(factor_graph, show_prior_factors).spec() + + +class _Reader: + """ + One pass over ``factor_graph.factors``, turned into an :class:`EPGraphSpec`. + """ + + def __init__(self, factor_graph, show_prior_factors: bool): + from autofit.graphical.declarative.factor.analysis import AnalysisFactor + from autofit.graphical.declarative.factor.hierarchical import ( + _HierarchicalFactor, + ) + from autofit.graphical.declarative.factor.prior import PriorFactor + + self._analysis_cls = AnalysisFactor + self._hierarchical_cls = _HierarchicalFactor + self._prior_cls = PriorFactor + + self.show_prior_factors = show_prior_factors + + #: THE read. Everything below works from these tuples. + self.factors = tuple(factor_graph.factors) + + self.kinds = tuple(map(self._kind, self.factors)) + self.ordered: List[Tuple[Any, ...]] = [] + self.labels: List[Dict[Any, str]] = [] + for factor in self.factors: + ordered, labels = self._read_variables(factor) + self.ordered.append(ordered) + self.labels.append(labels) + + self.incident: Dict[Any, List[int]] = {} + for index, variables in enumerate(self.ordered): + for variable in variables: + self.incident.setdefault(variable, []).append(index) + + self.drawn = { + factor.drawn_prior + for factor, kind in zip(self.factors, self.kinds) + if kind == "hierarchical" + } + self.hyper = { + variable + for factor, kind, variables in zip(self.factors, self.kinds, self.ordered) + if kind == "hierarchical" + for variable in variables + if variable is not factor.drawn_prior + } + + # -- reading ----------------------------------------------------------- + + def _kind(self, factor) -> str: + if isinstance(factor, self._analysis_cls): + return "analysis" + if isinstance(factor, self._hierarchical_cls): + return "hierarchical" + if isinstance(factor, self._prior_cls): + return "prior" + return "factor" + + def _read_variables(self, factor): + """ + A factor's variables, deduplicated, in label order with their labels. + + ``flat_args`` is keyword order, which is not declaration order, so the + variables are sorted by their (declaration-derived, unique) label -- + stable between runs and independent of how the arguments were bound. + """ + labels: Dict[Any, str] = {} + for slot, variable in enumerate(factor.flat_args): + if variable in labels: + continue + label = label_for_variable(factor, variable, slot=slot) + if label is None: + # The factor no longer references this variable -- typically a + # prior replaced by a fixed scalar after the graph was built. + continue + labels[variable] = label + ordered = tuple(sorted(labels, key=lambda variable: labels[variable])) + return ordered, labels + + # -- plates ------------------------------------------------------------ + + def _signature(self, index) -> Optional[Tuple[Any, ...]]: + from autofit.mapper.prior.abstract import Prior + + factor = self.factors[index] + kind = self.kinds[index] + if kind == "hierarchical": + return "hierarchical", factor.name + if kind != "analysis": + return None + tuples = factor.prior_model.path_instance_tuples_for_class(Prior) + paths = tuple(".".join(str(part) for part in path) for path, _ in tuples) + classes = tuple(type(prior).__name__ for _, prior in tuples) + return "analysis", type(factor).__name__, paths, classes + + def _plates(self): + groups: Dict[Tuple[Any, ...], List[int]] = {} + for index in range(len(self.factors)): + signature = self._signature(index) + if signature is None: + continue + groups.setdefault(signature, []).append(index) + + plates = [] + for signature, members in sorted(groups.items(), key=lambda item: item[1][0]): + if len(members) < 2: + continue + plates.append( + ( + PlateGroup( + key=f"plate-{members[0]}", + kind=signature[0], + count=len(members), + member_keys=tuple(factor_key(index) for index in members), + signature=signature, + representative_key=factor_key(members[0]), + ), + members, + ) + ) + return plates + + # -- variable nodes ---------------------------------------------------- + + def _variable_kind(self, variable) -> str: + if variable in self.drawn: + return "drawn" + if variable in self.hyper: + return "hyper" + return "free" + + def _assign(self, plates): + """ + Decide which variable node every variable belongs to. + + Returns ``(node_key_by_variable, node_by_key)`` where each node carries + the first declaration index at which it appears, so the nodes can be + emitted in reading order. + """ + node_key: Dict[Any, str] = {} + nodes: Dict[str, VariableNode] = {} + used = set() + + for plate, members in plates: + member_set = set(members) + collapsed: Dict[str, List[Tuple[int, Any, int]]] = {} + for index in members: + for slot, variable in enumerate(self.ordered[index]): + if variable in node_key: + continue + inside = [j for j in self.incident[variable] if j in member_set] + if len(inside) != 1: + # Shared by every member (or by none but this one, via + # a factor outside the plate): not the plate's own. + continue + label = _strip_prefix( + self.labels[index][variable], self.factors[index].name + ) + collapsed.setdefault(label, []).append((index, variable, slot)) + for label, entries in collapsed.items(): + key = _unique(f"{plate.key}/var-{entries[0][2]}", used) + used.add(key) + nodes[key] = VariableNode( + key=key, + label=label, + kind=self._variable_kind(entries[0][1]), + plate_key=plate.key, + count=len(entries), + ) + for _, variable, _ in entries: + node_key[variable] = key + + for index, variables in enumerate(self.ordered): + for slot, variable in enumerate(variables): + if variable in node_key: + continue + owner = self.incident[variable][0] + owner_slot = self.ordered[owner].index(variable) + key = _unique(f"{factor_key(owner)}/var-{owner_slot}", used) + used.add(key) + nodes[key] = VariableNode( + key=key, + label=self.labels[owner][variable], + kind=self._variable_kind(variable), + plate_key=None, + count=1, + ) + node_key[variable] = key + + return node_key, nodes + + # -- assembly ---------------------------------------------------------- + + def spec(self) -> EPGraphSpec: + plates = self._plates() + node_key, nodes = self._assign(plates) + + plate_of_factor: Dict[int, Tuple[str, int]] = {} + for plate, members in plates: + for position, index in enumerate(members): + plate_of_factor[index] = (plate.key, position) + + factor_nodes: List[FactorNode] = [] + incidences: List[Incidence] = [] + emitted: List[str] = [] + variable_nodes: List[VariableNode] = [] + + prior_groups: Dict[str, List[int]] = {} + + for index, factor in enumerate(self.factors): + variables = self.ordered[index] + for variable in variables: + key = node_key[variable] + if key not in emitted: + emitted.append(key) + variable_nodes.append(nodes[key]) + + if self.kinds[index] == "prior": + for variable in variables: + prior_groups.setdefault(node_key[variable], []).append(index) + continue + + plate_key, member_index = plate_of_factor.get(index, (None, None)) + keys = [] + for variable in variables: + key = node_key[variable] + if key not in keys: + keys.append(key) + incidences.append( + Incidence( + factor_key=factor_key(index), + variable_key=key, + label=self.labels[index][variable], + ) + ) + factor_nodes.append( + FactorNode( + key=factor_key(index), + name=factor.name, + kind=self.kinds[index], + member_index=member_index, + plate_key=plate_key, + variable_keys=tuple(keys), + ) + ) + + if self.show_prior_factors: + for variable_key, members in prior_groups.items(): + first = members[0] + stub_key = f"{variable_key}/prior" + factor_nodes.append( + FactorNode( + key=stub_key, + name=self.factors[first].name, + kind="prior", + member_index=None, + plate_key=nodes[variable_key].plate_key, + variable_keys=(variable_key,), + ) + ) + incidences.append( + Incidence( + factor_key=stub_key, + variable_key=variable_key, + label=nodes[variable_key].label, + ) + ) + + return EPGraphSpec( + factors=tuple(factor_nodes), + variables=tuple(variable_nodes), + incidences=tuple(incidences), + plates=tuple(plate for plate, _ in plates), + prior_factor_variable_keys=tuple(prior_groups), + ) diff --git a/autofit/model_figure/ep/state.py b/autofit/model_figure/ep/state.py new file mode 100644 index 000000000..c87bba86a --- /dev/null +++ b/autofit/model_figure/ep/state.py @@ -0,0 +1,303 @@ +""" +Layer 2 of the EP figure -- what the run did to the structure. + +:class:`EPGraphSpec` says what the graph *is*; :class:`EPState` says what +happened to it. The two are kept apart so that the same figure can be drawn +before a fit starts (structure only) and after every sweep (structure plus +overlay), and so that the overlay can be asserted on without rendering +anything. + +Everything here is read from :class:`~autofit.graphical.expectation_propagation.history.EPHistory` +-- the optimiser's own record, keyed by its own factor objects. Nothing is +recomputed from the mean field, and nothing is stored that the history does not +already know. + +What a factor's status means +---------------------------- + +``stale`` + The factor has been visited and has never landed an update. This is the + complement of ``EPOptimiser``'s own end-of-run stale check + (``(raised | skipped) - updated``): the reported posterior for this + factor's variables is still the message it started with. +``reverting`` + The factor's latest projection was rejected for at least one of its + variables -- ``update_invalid`` put that variable's message back. The + factor as a whole updated, so no factor-level warning fires, but the + reverted variable's marginal did not move. +``converged`` + ``EPHistory``'s own convergence test passes for this factor. +``working`` + Updating, nothing rejected, not yet converged. +``absent`` + The factor is in the graph but has no history: the sweep has not reached + it yet. Every count is zero. + +``stale`` outranks ``reverting``, which outranks ``converged``. A factor that +reverts everything on every projection is both stale and reverting and the +stronger claim wins; a factor that reverted a variable on its last projection +is not reported as converged, because that rejection is precisely what the +diagnostic figure exists to show. + +Not in scope +------------ + +Posterior values -- mean, std, precision, KL sparklines -- are a separate +overlay (the epic's prompt items 4-6) and are deliberately absent here. +``model_approx`` is accepted by :meth:`EPState.from_history` so that the +signature does not have to change when they arrive, and is ignored. +""" + +import logging +from dataclasses import asdict, dataclass +from typing import Any, Dict, Optional, Tuple + +from autofit.model_figure.ep.spec import EPGraphSpec, label_for_variable + +logger = logging.getLogger(__name__) + +__all__ = [ + "FactorState", + "VariableState", + "EPState", +] + +#: ``FactorState.status`` values, strongest claim first. +FACTOR_STATUSES = ("absent", "stale", "reverting", "converged", "working") + + +def _reverted_variables(status) -> Tuple[Any, ...]: + """ + The variables whose projection this update *rejected*. + + ``Status.changed`` is a per-variable mask of whether the projection was + accepted, and it is written only on the ``BAD_PROJECTION`` branch of + ``MeanField.update_factor_mean_field``. ``None`` means the update never + reached the projection, and an all-``True`` mask means a valid projection + -- neither is a reversion. Attributes are read directly: ``Status.__iter__`` + yields four fields and ``changed`` is deliberately not one of them. + """ + changed = status.changed + if changed is None: + return () + return tuple(variable for variable, accepted in changed.items() if not accepted) + + +def _reverted_names(status) -> Tuple[str, ...]: + """ + The names of the reverted variables, sorted. + + This is the ``reverted_variables`` column of ``ep_history.csv`` + (``EPDiagnostics.snapshot``) in tuple form, and a test pins it to a real + CSV written by a real run. It is not lifted out of ``diagnostics.py``: the + CSV is a published artefact with its own tests and the two must be able to + fail independently. + """ + return tuple(sorted(variable.name for variable in _reverted_variables(status))) + + +@dataclass(frozen=True) +class FactorState: + """ + What the EP run has done to one factor. + + Attributes + ---------- + key + The :class:`~autofit.model_figure.ep.spec.FactorNode` key this + describes. + status + One of :data:`FACTOR_STATUSES`. + updates + How many of the factor's visits landed an update. + sweeps + How many times the factor has been visited. + age + Sweeps since the factor last updated -- ``sweeps`` when it never has. + reverted_variable_keys + Variable node keys whose projection the *latest* visit rejected. + last_flag + The latest visit's ``StatusFlag`` name, or ``None`` when absent. + """ + + key: str + status: str + updates: int + sweeps: int + age: int + reverted_variable_keys: Tuple[str, ...] + last_flag: Optional[str] + + +@dataclass(frozen=True) +class VariableState: + """ + What the EP run has done to one variable. + + ``reverted_by`` names the factors whose latest projection rejected this + variable. It is per-factor on purpose: one member of a hierarchical group + reverting a shared variable is not the group reverting it, and only the + per-(factor, variable) resolution can say which. + """ + + key: str + reverted_by: Tuple[str, ...] + + +@dataclass(frozen=True) +class EPState: + """ + The whole overlay, flat and serialisable. + + ``step`` is the sweep the state describes: the greatest number of history + entries any one factor has. A factor with fewer has not been visited on + every sweep. + """ + + factors: Tuple[FactorState, ...] + variables: Tuple[VariableState, ...] + step: int + + def to_dict(self) -> Dict[str, Any]: + """ + A plain ``dict`` of builtins, byte-stable for a given history. + """ + return asdict(self) + + @classmethod + def from_history( + cls, + spec: EPGraphSpec, + ep_history, + factor_by_key: Dict[str, Any], + model_approx=None, + ) -> "EPState": + """ + Read an ``EPHistory`` onto a spec. + + Parameters + ---------- + spec + The structure the overlay is painted on. + ep_history + ``EPOptimiser.ep_history``. Only ``EPHistory.history`` is read -- + never ``ep_history[factor]``, which *creates* an empty history for + any factor it is asked about and so would report a factor as + visited zero times rather than as absent. + factor_by_key + Spec factor key to live factor, from + :func:`~autofit.model_figure.ep.spec.factor_by_key`. A key that is + missing (a collapsed ``PriorFactor`` stub stands for a group and + has no single history) is reported ``absent``. + model_approx + Accepted and ignored. Posterior values are a later overlay; see + the module docstring. + """ + del model_approx + + histories = getattr(ep_history, "history", {}) + variable_key = _variable_key_lookup(spec) + + factor_states = [] + reverted_by: Dict[str, list] = {variable.key: [] for variable in spec.variables} + + for node in spec.factors: + factor = factor_by_key.get(node.key) + history = histories.get(factor) if factor is not None else None + entries = list(history.history) if history is not None else [] + + if not entries: + factor_states.append( + FactorState( + key=node.key, + status="absent", + updates=0, + sweeps=0, + age=0, + reverted_variable_keys=(), + last_flag=None, + ) + ) + continue + + sweeps = len(entries) + updated_at = [ + index for index, (_, status) in enumerate(entries) if status.updated + ] + updates = len(updated_at) + age = sweeps if not updated_at else sweeps - 1 - updated_at[-1] + + _, latest = entries[-1] + reverted = tuple( + key + for key in ( + variable_key.get((node.key, label_for_variable(factor, variable))) + for variable in _reverted_variables(latest) + ) + if key is not None + ) + for key in reverted: + reverted_by.setdefault(key, []).append(node.key) + + factor_states.append( + FactorState( + key=node.key, + status=_status(ep_history, factor, sweeps, updates, reverted), + updates=updates, + sweeps=sweeps, + age=age, + reverted_variable_keys=reverted, + last_flag=getattr(latest.flag, "name", None), + ) + ) + + return cls( + factors=tuple(factor_states), + variables=tuple( + VariableState( + key=variable.key, reverted_by=tuple(reverted_by[variable.key]) + ) + for variable in spec.variables + ), + step=max((state.sweeps for state in factor_states), default=0), + ) + + +def _variable_key_lookup(spec: EPGraphSpec) -> Dict[Tuple[str, str], str]: + """ + ``(factor key, label)`` to variable node key, from the spec's own edges. + + The spec holds no live variables, so a variable coming back on a ``Status`` + is matched by the label its factor gives it -- the same + ``name_for_variable`` route the spec built its edges from, which is why + :func:`~autofit.model_figure.ep.spec.label_for_variable` guarantees labels + are unique within a factor. + """ + return { + (incidence.factor_key, incidence.label): incidence.variable_key + for incidence in spec.incidences + } + + +def _status(ep_history, factor, sweeps: int, updates: int, reverted) -> str: + if sweeps >= 1 and updates == 0: + return "stale" + if reverted: + return "reverting" + if _is_converged(ep_history, factor): + return "converged" + return "working" + + +def _is_converged(ep_history, factor) -> bool: + """ + ``EPHistory``'s own convergence test, which is the only one EP acts on. + + A figure must never kill a fit, so a convergence test that raises on an + exotic message family reports "not converged" and says so in the log. + """ + try: + return bool(ep_history.is_converged(factor)) + except Exception as e: + logger.debug(f"EP figure: convergence test failed for {factor}: {e}") + return False diff --git a/autofit/non_linear/paths/directory.py b/autofit/non_linear/paths/directory.py index 0b432c479..2323fd250 100644 --- a/autofit/non_linear/paths/directory.py +++ b/autofit/non_linear/paths/directory.py @@ -16,6 +16,7 @@ from autofit.tools.util import open_, open_atomic, NumpyEncoder from autofit.non_linear.samples.samples import Samples +from autofit.model_figure.config import model_figure_enabled from autofit.non_linear.test_mode import skip_visualization from .abstract import AbstractPaths, _test_mode_segment @@ -29,24 +30,11 @@ logger = logging.getLogger(__name__) -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 +#: ``model_figure_enabled`` lives in ``autofit.model_figure.config`` so that the +#: per-search ``model.png`` hook below and the EP factor-graph figures read the +#: same ``output.yaml`` key through the same strict accessor. The private alias +#: is kept because it is the name this module's tests import. +_model_figure_enabled = model_figure_enabled class DirectoryPaths(AbstractPaths): diff --git a/docs/features/graphical.md b/docs/features/graphical.md index c7dcd7642..97b068d31 100644 --- a/docs/features/graphical.md +++ b/docs/features/graphical.md @@ -228,6 +228,70 @@ The following paper describes the EP framework in formal Bayesian notation: +## Seeing The EP Run + +An EP fit sweeps factor by factor for as long as it takes, and the thing that most often goes wrong is invisible in the +result: one factor whose update is rejected every sweep, whose reported posterior is therefore the message it started +with. `af.EPPlotter` draws the factor graph the `EPOptimiser` sweeps so that this is something you look at rather than +something you infer. + +An `EPOptimiser` given `paths` writes two figures into its output directory, beside `graph.info`. `graph_model.png` is +the structure alone, written once at the start of the run: + +```{image} https://raw.githubusercontent.com/PyAutoLabs/PyAutoFit/main/docs/images/model_figures/ep_model.png +:alt: The EP model figure of the hierarchical graphical model, with square factor nodes, round variable pills, a dashed plate for the three datasets and the HierarchicalFactor above it. +:width: 600 +``` + +Square boxes are factors, rounded pills are variables, and a line is an incidence: this variable is one of that +factor's arguments. The dashed frame is a plate, exactly as in the model figures above -- three `AnalysisFactor`s with +the same signature are drawn once, and a variable each of them has its own copy of is drawn once inside the plate +badged `x3`. The `HierarchicalFactor0` box collapses its three members the same way, reading `3 members`, with its own +`mean` and `sigma` as hyper-variables above it. + +`graph_state.png` is the same graph with the run painted on it, rewritten on every `visualise_interval` tick, so the +file on disk always shows the sweep that just finished. Drawing it costs about a third of a second the first time and +under a tenth thereafter, so the interval is worth setting deliberately on a long run rather than left at 1: + +```{image} https://raw.githubusercontent.com/PyAutoLabs/PyAutoFit/main/docs/images/model_figures/ep_state_stale.png +:alt: The EP state figure of a three dataset run, with the plate noting one of three stale and the stalled AnalysisFactor2 expanded beside it in grey, badged zero updates in four sweeps. +:width: 600 +``` + +Each factor carries its updates and sweeps, and its state. **Stale** is grey: the factor completed sweeps and none of +them updated it -- the same condition the optimiser prints as its `STALE FACTORS` warning at the end of a run. +**Reverted** is a dashed red edge, and it marks a `(factor, variable)` pair whose projection was confirmed rejected, +which is a stronger statement than a message that happens not to have moved: EP restarted from its own converged mean +field reproduces every message exactly and is marked nowhere. **Converged** is a green outline, from the same +convergence test `EPHistory` stops the fit on. + +A plate never hides the member that failed. It shows the aggregate -- `3 datasets`, `4 updates / 4 sweeps` -- and then +names every member that departs from it, in red beneath the title, and draws that member as a node of its own beside +the plate. The figure above says `1 of 3 stale: AnalysisFactor2` and then draws `AnalysisFactor2`, grey, badged +`0 updates / 4 sweeps` with its age and its `BAD_PROJECTION` flag. A stale factor in a plate of thirty is as visible as +one in a plate of three. + +The figures are behind `output.yaml`'s `model_figure` key -- the same key the per-search `model.png` is behind -- which +is read strictly, so a configuration that does not mention it writes neither file. Switch it on to get them: + +```bash +output: + model_figure: true +``` + +The same figure can be drawn straight from an `af.graphical.EPOptimiser` that has already run, which is the quickest way to look +at a fit that is sitting in memory: + +```bash +af.EPPlotter(optimiser.factor_graph, ep_history=optimiser.ep_history).figure(kind="state") +``` + +Pass the optimiser's own `factor_graph`, never a factor graph model's `graph` property: that property builds a new +graph, renaming every prior factor as it goes, on every access -- and the history is keyed by the graph the optimiser +actually swept. `kind="model"` draws the structure alone and needs no history at all, while `kind="state"` without one +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. + ## 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/docs/images/model_figures/ep_model.png b/docs/images/model_figures/ep_model.png new file mode 100644 index 000000000..5ad5fcb34 Binary files /dev/null and b/docs/images/model_figures/ep_model.png differ diff --git a/docs/images/model_figures/ep_state_reverted.png b/docs/images/model_figures/ep_state_reverted.png new file mode 100644 index 000000000..33c6c9fcf Binary files /dev/null and b/docs/images/model_figures/ep_state_reverted.png differ diff --git a/docs/images/model_figures/ep_state_stale.png b/docs/images/model_figures/ep_state_stale.png new file mode 100644 index 000000000..cc649ef65 Binary files /dev/null and b/docs/images/model_figures/ep_state_stale.png differ diff --git a/docs/images/model_figures/make_figures.py b/docs/images/model_figures/make_figures.py index f095938aa..39b64bdfe 100644 --- a/docs/images/model_figures/make_figures.py +++ b/docs/images/model_figures/make_figures.py @@ -27,6 +27,7 @@ from typing import List import matplotlib +import numpy as np matplotlib.use("Agg") @@ -34,6 +35,13 @@ sys.path.insert(0, str(REPO_ROOT)) import autofit as af +from autofit import graphical as graph +from autofit.graphical.expectation_propagation.factor_optimiser import ( + AbstractFactorOptimiser, +) +from autofit.mapper.variable import Variable +from autofit.messages.normal import NormalMessage +from autofit.tools.namer import namer OUTPUT_PATH = Path(__file__).resolve().parent WIDTH = 14.0 @@ -239,15 +247,15 @@ def graphical_variable(): return _factor_graph(model_list).global_prior_model -def graphical_hierarchical(): +def _hierarchical_factor_graph_model(): """ - Plate notation, **hierarchical**: three *different* centres, each drawn from - one parent ``GaussianPrior`` whose ``mean`` and ``sigma`` are themselves - free (HowToFit chapter 3, tutorial 4). + Three *different* centres, each drawn from one parent ``GaussianPrior`` + whose ``mean`` and ``sigma`` are themselves free (HowToFit chapter 3, + tutorial 4). - The teaching pair of the epic: put this figure beside ``graphical_shared`` - and the difference between "the same number" and "from a common population" - is the difference between a blue reference and a violet arrow. + Returned as the ``FactorGraphModel`` rather than its global prior model, + because the EP figures below need the factor graph an ``EPOptimiser`` + sweeps and the model figure needs the model. """ model_list = [_graphical_model() for _ in range(3)] @@ -263,14 +271,26 @@ def graphical_hierarchical(): for model in model_list: hierarchical_factor.add_drawn_variable(model.centre) - factor_graph = af.FactorGraphModel( + return af.FactorGraphModel( *[ af.AnalysisFactor(prior_model=model, analysis=_Analysis(index)) for index, model in enumerate(model_list) ], hierarchical_factor, ) - return factor_graph.global_prior_model + + +def graphical_hierarchical(): + """ + Plate notation, **hierarchical**: three *different* centres, each drawn from + one parent ``GaussianPrior`` whose ``mean`` and ``sigma`` are themselves + free (HowToFit chapter 3, tutorial 4). + + The teaching pair of the epic: put this figure beside ``graphical_shared`` + and the difference between "the same number" and "from a common population" + is the difference between a blue reference and a violet arrow. + """ + return _hierarchical_factor_graph_model().global_prior_model def composite_shared_relation_assertion(): @@ -304,6 +324,191 @@ def lens_models(): } +# -- the EP figures --------------------------------------------------------- +# +# `af.EPPlotter` draws the factor graph an `EPOptimiser` sweeps, and -- given +# the run's history -- what the run did to it. These three PNGs are the +# phase-5 evidence and the images `docs/features/graphical.md` embeds. +# +# `ep_state_reverted` is a real `EPOptimiser.run`. `ep_state_stale` is not: a +# plate only forms over `AnalysisFactor`s, and an `AnalysisFactor` needs a real +# non-linear search per factor per sweep, which is minutes for a picture whose +# content is entirely determined by the statuses the run records. Its history +# is therefore built from exactly the `Status` objects `OverWideFit` produces +# -- a projection rejected on every sweep, so the factor's message never moves +# -- which is the same thing the real run below writes for its own factor. + + +def write_ep(plotter, name: str, kind: str): + """Render one EP view to ``.png`` in this directory.""" + plotter.figure( + path=str(OUTPUT_PATH), + filename=name, + format="png", + kind=kind, + width=WIDTH, + ) + print(f"wrote {name}.png") + + +class OverWideFit(AbstractFactorOptimiser): + """ + A factor fit that comes back wider than its cavity in every variable -- the + shape a near-singular or noisy finite-difference Hessian produces. The + quotient ``q* / cavity`` then has negative precision, so ``update_invalid`` + reverts every parameter and the factor's message never moves. + + Copied from ``test_autofit/graphical/functionality/test_factor_failure_recovery.py``, + where the reversion bugs (PyAutoFit #1571, #1575, #1579) were fixed against + it, so the figures show the behaviour the tests pin. + """ + + def optimise(self, factor_approx, status=graph.Status()): + model_dist = graph.MeanField( + { + v: NormalMessage(float(m.mean), float(m.sigma) * 3.0) + for v, m in factor_approx.cavity_dist.items() + } + ) + return model_dist, graph.Status(success=True, messages=(), updated=True) + + +class PartialRevertFit(AbstractFactorOptimiser): + """ + A factor fit that is valid in one variable and over-wide in another, on + every sweep: the quotient ``q* / cavity`` has positive precision for the + first (so it updates) and negative precision for the second (so + ``update_invalid`` reverts every one of its parameters and its message never + moves). The factor updates; one of its variables never does. + """ + + def __init__(self, reverting: str): + super().__init__() + self.reverting = reverting + + def optimise(self, factor_approx, status=graph.Status()): + model_dist = graph.MeanField( + { + v: NormalMessage( + float(m.mean), + float(m.sigma) * (3.0 if v.name == self.reverting else 0.5), + ) + for v, m in factor_approx.cavity_dist.items() + } + ) + return model_dist, graph.Status(success=True, messages=(), updated=True) + + +def ep_model(): + """ + The **model** view: the hierarchical factor graph, drawable before the + first sweep and written once per run as ``graph_model.png``. + + The same model as ``graphical_hierarchical`` -- so the two figures can be + read side by side -- but drawn as the explicit factor graph EP sweeps: + square factor nodes, round variable nodes, and the edges between them. + """ + return af.EPPlotter(_hierarchical_factor_graph_model().graph), "model" + + +def ep_state_stale(): + """ + The **state** view with a stalled plate member: three datasets, one of + which never updates. + + The acceptance the epic review asked for by name -- a plate must never + report "3 datasets, working" when one of its members has done nothing. The + plate carries the count and names the failure; the failing member is + expanded beside it in grey, badged with its zero updates. + """ + from autofit.graphical.declarative.factor.analysis import AnalysisFactor + from autofit.graphical.expectation_propagation.history import ( + EPHistory, + FactorHistory, + ) + from autofit.graphical.utils import StatusFlag + + factor_graph = _hierarchical_factor_graph_model().graph + analysis_factors = [ + factor for factor in factor_graph.factors if isinstance(factor, AnalysisFactor) + ] + stalled = analysis_factors[-1] + + history = EPHistory(kl_tol=None, evidence_tol=None) + for factor in factor_graph.factors: + entry = FactorHistory(factor) + for _ in range(4): + if factor is stalled: + status = graph.Status( + success=True, + updated=False, + flag=StatusFlag.BAD_PROJECTION, + changed={variable: False for variable in factor.variables}, + ) + else: + status = graph.Status( + success=True, updated=True, flag=StatusFlag.SUCCESS + ) + entry.history.append((None, status)) + history.history[factor] = entry + + return af.EPPlotter(factor_graph, ep_history=history), "state" + + +def ep_state_reverted(): + """ + The **state** view of a real four-sweep EP run in which one factor's + projection is rejected for one of its two variables on every sweep. + + ``like_xy`` updates -- so no factor-level staleness is reported -- while + ``y``'s message never moves off the one it started with. The figure marks + the ``(factor, variable)`` pair it happened to, which is the only place + that fact is visible (PyAutoFit #1575). + """ + from autofit.graphical.expectation_propagation.factor_optimiser import ( + ExactFactorFit, + ) + from autofit.graphical.expectation_propagation.history import EPHistory + + x, y = Variable("x"), Variable("y") + + def joint(x, y): + return -0.5 * (np.sum((x - 3.0) ** 2) + np.sum((y - 2.0) ** 2)) + + prior_x = NormalMessage(1.0, 2.0).as_factor(x, name="prior_x") + prior_y = NormalMessage(1.0, 2.0).as_factor(y, name="prior_y") + likelihood = graph.Factor(joint, x, y, name="like_xy") + + factor_graph = graph.FactorGraph([prior_x, prior_y, likelihood]) + model_approx = graph.EPMeanField.from_approx_dists( + factor_graph, + {x: NormalMessage(0.0, 10.0), y: NormalMessage(0.0, 10.0)}, + ) + + optimiser = graph.EPOptimiser( + factor_graph, + factor_optimisers={ + prior_x: ExactFactorFit(), + prior_y: ExactFactorFit(), + likelihood: PartialRevertFit(reverting="y"), + }, + # `kl_tol=None` disables the convergence check: this graph is exact and + # would otherwise be declared converged after one sweep. + ep_history=EPHistory(kl_tol=None), + paths=False, + ) + optimiser.run(model_approx, max_steps=4, max_consecutive_failures=100) + + return af.EPPlotter(factor_graph, ep_history=optimiser.ep_history), "state" + + +EP_FIGURES = { + "ep_model": ep_model, + "ep_state_stale": ep_state_stale, + "ep_state_reverted": ep_state_reverted, +} + + FIGURES = { "gaussian": gaussian, "gaussian_customised": gaussian_customised, @@ -326,6 +531,24 @@ def main(): for name, model in lens_models().items(): write(model, name) + ep_main() + + +def ep_main(): + """ + The EP figures alone -- the phase-5 evidence. + + ``namer`` -- the source of a declarative factor's name + (``AnalysisFactor0``, ``HierarchicalFactor0``) -- is a global counter, so it + is reset before each figure. Otherwise the second graph built in a session + is labelled ``AnalysisFactor3`` and a reader comparing two figures is + comparing different numbers for the same thing. + """ + for name, builder in EP_FIGURES.items(): + namer.reset() + plotter, kind = builder() + write_ep(plotter, name, kind) + if __name__ == "__main__": main() diff --git a/test_autofit/graphical/functionality/test_ep_visualise_output.py b/test_autofit/graphical/functionality/test_ep_visualise_output.py new file mode 100644 index 000000000..3a423420c --- /dev/null +++ b/test_autofit/graphical/functionality/test_ep_visualise_output.py @@ -0,0 +1,199 @@ +""" +The EP hook: `graph_model.png` and `graph_state.png` beside `graph.info`. + +`Visualise` already writes the convergence curves (`graph.png`, +`graph_factors.png`) on every `visualise_interval` tick. Behind `output.yaml`'s +`model_figure` key it now also writes the factor graph itself -- once as +structure, and once per tick with the run painted on it. + +Three things are asserted here that no unit test of the figure layers can see, +because they are properties of the *run*: + +* the model view is written once and the state view every tick, so the state + file always shows the sweep that just finished; +* a config which says nothing about `model_figure` writes neither file, which + is what keeps the figure off for every existing user; +* a renderer that raises leaves the fit intact -- the run returns, the + convergence curves are still written, and the failure goes to the log. + +The graph is the two-factor, one-shared-variable double of +`test_factor_failure_recovery` fitted by exact factor fits, so a three-sweep +run is milliseconds. +""" + +import matplotlib + +matplotlib.use("Agg") + +import pytest + +from autofit import graphical as graph +from autofit.graphical.expectation_propagation.factor_optimiser import ExactFactorFit +from autofit.graphical.expectation_propagation.history import EPHistory +from autofit.non_linear.paths.directory import DirectoryPaths + +from test_autofit.graphical.functionality.test_factor_failure_recovery import ( + make_shared_variable_approx, +) +from test_autofit.non_linear.paths.test_model_figure_output import model_figure_key + +PNG_MAGIC = b"\x89PNG\r\n\x1a\n" + +MAX_STEPS = 3 + + +def run_ep(tmp_path, name="ep_figures", max_steps=MAX_STEPS): + """ + A real `EPOptimiser.run` with `visualise_interval=1`, writing into + `tmp_path`. Returns the optimiser's output directory. + """ + model_approx, factor_graph, prior, likelihood = make_shared_variable_approx() + + optimiser = graph.EPOptimiser( + factor_graph, + factor_optimisers={prior: ExactFactorFit(), likelihood: ExactFactorFit()}, + # `kl_tol=None` disables the convergence check: this graph is exact and + # would otherwise terminate after one sweep, before a second tick. + ep_history=EPHistory(kl_tol=None), + paths=DirectoryPaths(name=name, path_prefix=str(tmp_path)), + ) + optimiser.run( + model_approx, + max_steps=max_steps, + visualise_interval=1, + max_consecutive_failures=100, + ) + return optimiser.output_path + + +def written(output_path, filename): + target = output_path / filename + + assert target.exists(), f"{target} was not written" + contents = target.read_bytes() + assert contents[:8] == PNG_MAGIC + assert len(contents) > 1024, f"{target} is {len(contents)} bytes -- empty canvas" + return target + + +@pytest.fixture +def figure_kinds(monkeypatch): + """ + Every `EPPlotter.figure` call's `kind`, in order, with the real figure + still drawn. + + Call counts are what prove the state file is refreshed per tick; comparing + bytes cannot, because two sweeps of an exactly converging graph render + identically. + """ + from autofit.model_figure.ep.plotter import EPPlotter + + original = EPPlotter.figure + kinds = [] + + def spy(self, *args, **kwargs): + kinds.append(kwargs.get("kind", "model")) + return original(self, *args, **kwargs) + + monkeypatch.setattr(EPPlotter, "figure", spy) + return kinds + + +def test_both_figures_are_written_beside_the_convergence_curves(tmp_path): + with model_figure_key(True): + output_path = run_ep(tmp_path) + + written(output_path, "graph_model.png") + written(output_path, "graph_state.png") + # the curves the hook must not have displaced + assert (output_path / "graph.png").exists() + assert (output_path / "graph_factors.png").exists() + + +def test_the_model_view_is_drawn_once_and_the_state_view_every_tick( + tmp_path, figure_kinds +): + """ + Structure cannot change mid-run, so `graph_model.png` is written on the + first tick and never again; the state view is redrawn on every one. + """ + with model_figure_key(True): + run_ep(tmp_path) + + assert figure_kinds.count("model") == 1 + assert figure_kinds[0] == "model" + + # one tick per sweep plus the final call at the end of `run` + assert figure_kinds.count("state") == MAX_STEPS + 1 + assert figure_kinds.count("state") == len(figure_kinds) - 1 + + +def test_the_state_file_is_rewritten_rather_than_left_at_the_first_sweep(tmp_path): + """ + The file the last tick wrote is the one on disk: its modification time is + at or after the model view's, which only the first tick writes. + """ + with model_figure_key(True): + output_path = run_ep(tmp_path) + + model = written(output_path, "graph_model.png") + state = written(output_path, "graph_state.png") + + assert state.stat().st_mtime_ns >= model.stat().st_mtime_ns + + +@pytest.mark.parametrize("value", [False, None]) +def test_nothing_is_written_when_the_key_is_off_or_absent(tmp_path, value): + """ + `None` is the case that matters most: a config which has never heard of + `model_figure` must write no figure, even though `output.yaml`'s `default:` + is `true`. + """ + with model_figure_key(value): + output_path = run_ep(tmp_path) + + assert not (output_path / "graph_model.png").exists() + assert not (output_path / "graph_state.png").exists() + # ... and the curves are unaffected either way + assert (output_path / "graph.png").exists() + + +def test_a_raising_plotter_leaves_the_run_intact(tmp_path, monkeypatch, caplog): + """ + A figure is a diagnostic, never a dependency: if it cannot be drawn the + sweep still finishes, the run still returns and the reason goes to the log. + """ + import logging + + from autofit.model_figure.ep.plotter import EPPlotter + + def explode(self, *args, **kwargs): + raise RuntimeError("no pixels today") + + monkeypatch.setattr(EPPlotter, "figure", explode) + + with caplog.at_level(logging.INFO): + with model_figure_key(True): + output_path = run_ep(tmp_path) + + assert not (output_path / "graph_model.png").exists() + assert (output_path / "graph.png").exists() + assert any("no pixels today" in record.message for record in caplog.records) + + +def test_no_figure_is_drawn_without_a_factor_graph(tmp_path): + """ + Every other caller of `Visualise` -- `stochastic.py` -- constructs it + without a graph and calls it with no arguments. That must go on working, + and draw no factor-graph figure. + """ + from autofit.graphical.expectation_propagation.visualise import Visualise + + visualiser = Visualise(EPHistory(kl_tol=None), tmp_path) + + with model_figure_key(True): + visualiser() + + assert visualiser.factor_graph is None + assert not (tmp_path / "graph_model.png").exists() + assert (tmp_path / "graph.png").exists() diff --git a/test_autofit/model_figure/ep/__init__.py b/test_autofit/model_figure/ep/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/test_autofit/model_figure/ep/conftest.py b/test_autofit/model_figure/ep/conftest.py new file mode 100644 index 000000000..6a0cf086d --- /dev/null +++ b/test_autofit/model_figure/ep/conftest.py @@ -0,0 +1,81 @@ +import itertools + +import pytest + +import autofit as af +from autofit.tools.namer import namer + + +@pytest.fixture(autouse=True) +def reset_ids(): + """ + Model object and prior ids are global counters, and so is ``namer`` -- the + source of a declarative factor's name (``AnalysisFactor0``, + ``HierarchicalFactor0``), which the EP spec records. They are reset before + every test so that the spec is a function of the factor graph alone, which + is what the determinism assertions rely on. + """ + af.ModelObject._ids = itertools.count() + af.Prior._ids = itertools.count() + namer.reset() + + +@pytest.fixture +def hierarchical_factor_graph(): + """ + The ``DeclarativeFactorGraph`` ``EPOptimiser`` would be handed for the + phase-4 hierarchical double: three ``AnalysisFactor``s, one + ``HierarchicalFactor`` decomposed into three members, and one + ``PriorFactor`` per prior. + """ + from test_autofit.graph_spec.graphical_doubles import hierarchical_graph + + return hierarchical_graph().graph + + +@pytest.fixture +def stalled_plate(hierarchical_factor_graph): + """ + A plate of three datasets, one of which never updates. + + ``AnalysisFactor``s need a real non-linear search, so a real EP run over + this graph is far too slow for a test -- and the per-factor optimiser route + ``test_factor_failure_recovery`` uses needs one optimiser per factor, which + is the same problem. The ``EPHistory`` is therefore built by hand from the + same ``Status`` objects a run would record: two members that update on + every sweep, and one whose projection is rejected on every sweep, which is + exactly what ``OverWideFit`` produces. + + Returns ``(factor_graph, ep_history, stalled_factor)``. + """ + from autofit.graphical.expectation_propagation.history import ( + EPHistory, + FactorHistory, + ) + from autofit.graphical.utils import Status, StatusFlag + from autofit.graphical.declarative.factor.analysis import AnalysisFactor + + history = EPHistory(kl_tol=None, evidence_tol=None) + analysis_factors = [ + factor + for factor in hierarchical_factor_graph.factors + if isinstance(factor, AnalysisFactor) + ] + stalled = analysis_factors[-1] + + for factor in hierarchical_factor_graph.factors: + entry = FactorHistory(factor) + for _ in range(4): + if factor is stalled: + status = Status( + success=True, + updated=False, + flag=StatusFlag.BAD_PROJECTION, + changed={variable: False for variable in factor.variables}, + ) + else: + status = Status(success=True, updated=True, flag=StatusFlag.SUCCESS) + entry.history.append((None, status)) + history.history[factor] = entry + + return hierarchical_factor_graph, history, stalled diff --git a/test_autofit/model_figure/ep/test_acceptance_ep.py b/test_autofit/model_figure/ep/test_acceptance_ep.py new file mode 100644 index 000000000..a51e34267 --- /dev/null +++ b/test_autofit/model_figure/ep/test_acceptance_ep.py @@ -0,0 +1,305 @@ +""" +The phase-5 acceptance: the four things the EP figure exists to show. + +Each bullet of the prompt is asserted twice -- once on the presentation and +state dataclasses, which is where the claim actually lives, and once as a PNG +smoke, because a claim that cannot survive being drawn is not shipped. The PNG +check is deliberately shallow (it exists, it is a PNG, it is not an empty +canvas); the encoding itself is pinned by ``test_presentation`` and +``test_layout``, which do not have to render anything to do it. + +The doubles are the ones the reversion bugs themselves were fixed against +(``test_factor_failure_recovery``, PyAutoFit #1571, #1575, #1579), so an +acceptance failure and a graphical-behaviour failure are the same failure. +""" + +import pytest + +import autofit as af +from autofit import graphical as graph +from autofit.graphical.expectation_propagation.factor_optimiser import ExactFactorFit +from autofit.graphical.expectation_propagation.history import EPHistory +from test_autofit.graphical.functionality.test_factor_failure_recovery import ( + OverWideFit, + PartialRevertFit, + make_shared_variable_approx, + make_two_variable_approx, +) + +PNG_MAGIC = b"\x89PNG\r\n\x1a\n" + + +def _written(path, filename: str): + """The figure was really drawn: a PNG, with something on it.""" + target = path / f"{filename}.png" + + assert target.exists(), f"{target} was not written" + contents = target.read_bytes() + assert contents[:8] == PNG_MAGIC + assert len(contents) > 1024, f"{target} is {len(contents)} bytes -- an empty canvas" + return target + + +def _plotter(factor_graph, optimiser=None): + return af.EPPlotter( + factor_graph, + ep_history=None if optimiser is None else optimiser.ep_history, + ) + + +@pytest.fixture +def partial_revert(): + """ + One factor that reverts ``y`` on every projection while moving ``x``: the + partial revert of PyAutoFit #1575, run for real. + """ + model_approx, factor_graph, prior_x, prior_y, likelihood = ( + make_two_variable_approx() + ) + optimiser = graph.EPOptimiser( + factor_graph, + factor_optimisers={ + prior_x: ExactFactorFit(), + prior_y: ExactFactorFit(), + likelihood: PartialRevertFit(reverting="y"), + }, + ep_history=EPHistory(kl_tol=None), + paths=False, + ) + optimiser.run(model_approx, max_steps=4, max_consecutive_failures=100) + return optimiser, factor_graph, likelihood + + +@pytest.fixture +def over_wide(): + """A factor that reverts everything on every projection, run for real.""" + model_approx, factor_graph, prior, likelihood = make_shared_variable_approx() + optimiser = graph.EPOptimiser( + factor_graph, + factor_optimisers={prior: ExactFactorFit(), likelihood: OverWideFit()}, + ep_history=EPHistory(kl_tol=None), + paths=False, + ) + optimiser.run(model_approx, max_steps=4, max_consecutive_failures=100) + return optimiser, factor_graph, likelihood + + +# ---------------------------------------------------------------------------- +# 1. both views of a hierarchical run are drawn +# ---------------------------------------------------------------------------- + + +def test_both_views_of_a_hierarchical_graph_are_written(stalled_plate, tmp_path): + """ + The headline: one call draws the graph, another draws the run on it. + + The history here is built from the same ``Status`` objects a run records + rather than by running one, because an ``AnalysisFactor`` needs a real + non-linear search per factor per sweep -- minutes, for a picture whose + content is entirely determined by the statuses. The real-run legs are the + fixtures below, on graphs small enough to sweep in milliseconds. + """ + factor_graph, history, _ = stalled_plate + + af.EPPlotter(factor_graph).figure(path=tmp_path, format="png", kind="model") + af.EPPlotter(factor_graph, ep_history=history).figure( + path=tmp_path, format="png", kind="state" + ) + + _written(tmp_path, "graph_model") + _written(tmp_path, "graph_state") + + +def test_the_state_view_refuses_to_draw_without_a_history(stalled_plate, tmp_path): + """ + A diagnostic figure that silently contains no diagnostics is worse than an + error, so ``kind="state"`` without a history says so. + """ + factor_graph, _, _ = stalled_plate + + with pytest.raises(ValueError, match="ep_history"): + af.EPPlotter(factor_graph).figure(kind="state", format=None) + + +def test_the_model_view_is_the_same_figure_without_the_run(stalled_plate): + factor_graph, history, _ = stalled_plate + plotter = af.EPPlotter(factor_graph, ep_history=history) + + model = plotter.presentation(kind="model") + state = plotter.presentation(kind="state") + + assert plotter.state() is not None + assert af.EPPlotter(factor_graph).state() is None + assert all(node.state is None for node in model.nodes) + assert {node.key for node in model.nodes} <= {node.key for node in state.nodes} + + +# ---------------------------------------------------------------------------- +# 2. a stalled factor is drawn as stalled +# ---------------------------------------------------------------------------- + + +def test_a_stalled_factor_is_a_stale_node_badged_with_its_zero_updates( + over_wide, tmp_path +): + optimiser, factor_graph, likelihood = over_wide + presentation = _plotter(factor_graph, optimiser).presentation(kind="state") + + (node,) = [ + node for node in presentation.factor_nodes() if node.title == likelihood.name + ] + + assert node.state == "stale" + assert any("0 updates" in badge for badge in node.badges) + assert likelihood in optimiser._factors_skipped # the optimiser agrees + + _plotter(factor_graph, optimiser).figure( + path=tmp_path, filename="stale", format="png", kind="state" + ) + _written(tmp_path, "stale") + + +# ---------------------------------------------------------------------------- +# 3. a reverted update is drawn on the variable it happened to +# ---------------------------------------------------------------------------- + + +def test_a_partial_revert_marks_one_edge_and_only_one(partial_revert, tmp_path): + optimiser, factor_graph, likelihood = partial_revert + presentation = _plotter(factor_graph, optimiser).presentation(kind="state") + + reverted = [edge for edge in presentation.edges if edge.kind == "reverted"] + + assert [edge.label for edge in reverted] == ["like_xy.y"] + assert not [ + edge + for edge in presentation.edges + if edge.kind == "reverted" and edge.label.endswith(".x") + ] + + _plotter(factor_graph, optimiser).figure( + path=tmp_path, filename="reverted", format="png", kind="state" + ) + _written(tmp_path, "reverted") + + +def test_a_fixed_point_restart_marks_no_edge_at_all(tmp_path): + """ + EP restarted from its own converged mean field reproduces every message + exactly: nothing moves, and nothing is rejected. A fixed point is not a + rejection (PyAutoFit #1579), and the figure must not paint one. + """ + model_approx, factor_graph, prior, likelihood = make_shared_variable_approx() + + def run(approx, steps): + optimiser = graph.EPOptimiser( + factor_graph, + factor_optimisers={prior: ExactFactorFit(), likelihood: ExactFactorFit()}, + ep_history=EPHistory(kl_tol=None), + paths=False, + ) + return optimiser, optimiser.run( + approx, max_steps=steps, max_consecutive_failures=100 + ) + + _, converged = run(model_approx, 6) + optimiser, _ = run(converged, 4) + + presentation = _plotter(factor_graph, optimiser).presentation(kind="state") + + assert [edge for edge in presentation.edges if edge.kind == "reverted"] == [] + assert [edge for edge in presentation.edges if edge.kind == "stale"] == [] + assert optimiser._stale_factor_warnings() == [] + + _plotter(factor_graph, optimiser).figure( + path=tmp_path, filename="fixed_point", format="png", kind="state" + ) + _written(tmp_path, "fixed_point") + + +# ---------------------------------------------------------------------------- +# 4. a plate never hides the member that failed +# ---------------------------------------------------------------------------- + + +def test_a_plate_names_and_draws_the_member_that_failed(stalled_plate, tmp_path): + """ + The acceptance the epic review asked for by name: three datasets, one of + which never updates, must not be reported as "3 datasets, working". + """ + factor_graph, history, stalled = stalled_plate + model = af.EPPlotter(factor_graph).presentation(kind="model") + assert model.node("plate-0").note is None # ... not in the model view + + presentation = af.EPPlotter(factor_graph, ep_history=history).presentation( + kind="state" + ) + plate = presentation.node("plate-0") + + assert plate.members == ("factor-0", "factor-1", "factor-2") + assert stalled.name in plate.note + + (expanded,) = [ + node + for node in presentation.factor_nodes() + if node.title == stalled.name and node.key != plate.key + ] + assert expanded.state == "stale" + assert expanded.plate_key == plate.key + + af.EPPlotter(factor_graph, ep_history=history).figure( + path=tmp_path, filename="plate", format="png", kind="state" + ) + _written(tmp_path, "plate") + + +def test_the_expanded_member_is_drawn_beside_the_plate_not_on_top_of_it(stalled_plate): + factor_graph, history, _ = stalled_plate + layout = af.EPPlotter(factor_graph, ep_history=history).layout(kind="state") + + plate = layout.box("plate-0") + expanded = layout.box("factor-2") + + assert plate.rank == expanded.rank + assert plate.x + plate.width < expanded.x or expanded.x + expanded.width < plate.x + + +# ---------------------------------------------------------------------------- +# the plotter's own contract +# ---------------------------------------------------------------------------- + + +def test_the_filename_defaults_by_kind_and_the_formats_are_the_usual_four( + stalled_plate, tmp_path +): + factor_graph, history, _ = stalled_plate + plotter = af.EPPlotter(factor_graph, ep_history=history) + + plotter.figure(path=tmp_path, format="png", kind="model") + plotter.figure(path=tmp_path, format="svg", kind="state") + + assert (tmp_path / "graph_model.png").exists() + assert (tmp_path / "graph_state.svg").exists() + + with pytest.raises(ValueError): + plotter.figure(path=tmp_path, format="gif") + + +def test_format_none_builds_the_figure_and_writes_nothing(stalled_plate, tmp_path): + factor_graph, _, _ = stalled_plate + + figure = af.EPPlotter(factor_graph).figure(path=tmp_path, format=None) + + assert figure is not None + assert list(tmp_path.iterdir()) == [] + + import matplotlib.pyplot as plt + + plt.close(figure) + + +def test_an_unknown_kind_is_refused(stalled_plate): + factor_graph, history, _ = stalled_plate + + with pytest.raises(ValueError, match="kind"): + af.EPPlotter(factor_graph, ep_history=history).presentation(kind="diagnostic") diff --git a/test_autofit/model_figure/ep/test_determinism.py b/test_autofit/model_figure/ep/test_determinism.py new file mode 100644 index 000000000..734f7b2d7 --- /dev/null +++ b/test_autofit/model_figure/ep/test_determinism.py @@ -0,0 +1,160 @@ +""" +Determinism -- the same graph must give the same EP figure, twice and everywhere. + +The same acceptance as the model figure's own +``test_autofit/model_figure/test_determinism.py``, and for the same reason: a +figure that is not byte-reproducible cannot be diffed, cannot be committed as +evidence, and cannot be written every sweep of a fit without polluting the +output directory with noise. The layout dict is the artefact (every coordinate +rounded to 4 dp); the PNG bytes are checked directly. + +The EP figure has one source of drift the model figure does not -- the +``networkx`` layout it is seeded from -- which is why the fresh-interpreter leg +matters here even more than it does there. +""" + +import hashlib +import itertools +import json +import subprocess +import sys +import textwrap + +import matplotlib + +matplotlib.use("Agg") + +import autofit as af +from autofit.model_figure.ep.layout import build_ep_layout +from autofit.model_figure.ep.presentation import build_ep_presentation +from autofit.model_figure.ep.render import draw, save +from autofit.model_figure.ep.spec import EPGraphSpec +from autofit.tools.namer import namer +from test_autofit.graph_spec.graphical_doubles import hierarchical_graph + + +def _reset_ids(): + af.ModelObject._ids = itertools.count() + af.Prior._ids = itertools.count() + namer.reset() + + +def _layout(factor_graph, state=None): + return build_ep_layout( + build_ep_presentation(EPGraphSpec.from_factor_graph(factor_graph), state) + ) + + +def _layout_json(factor_graph): + return json.dumps(_layout(factor_graph).to_dict()) + + +def test_laying_out_the_same_graph_twice_is_byte_identical(hierarchical_factor_graph): + assert _layout_json(hierarchical_factor_graph) == _layout_json( + hierarchical_factor_graph + ) + + +def test_rebuilding_the_graph_is_byte_identical(): + """ + The figure is a function of the model, not of the process: a fresh build -- + new priors, new ids, new ``namer`` counters -- gives the same dictionary. + """ + _reset_ids() + first = _layout_json(hierarchical_graph().graph) + + _reset_ids() + second = _layout_json(hierarchical_graph().graph) + + assert first == second + + +def test_the_layout_is_identical_in_a_fresh_interpreter(tmp_path): + """ + Text metrics come from a scratch Agg canvas and the base coordinates come + from ``networkx``: neither may depend on anything the test session has + already done. + """ + _reset_ids() + expected = _layout_json(hierarchical_graph().graph) + + target = tmp_path / "layout.json" + script = textwrap.dedent( + f""" + import itertools, json, pathlib + import matplotlib + matplotlib.use("Agg") + import autofit as af + from autofit.model_figure.ep.layout import build_ep_layout + from autofit.model_figure.ep.presentation import build_ep_presentation + from autofit.model_figure.ep.spec import EPGraphSpec + from autofit.tools.namer import namer + from test_autofit.graph_spec.graphical_doubles import hierarchical_graph + + af.ModelObject._ids = itertools.count() + af.Prior._ids = itertools.count() + namer.reset() + + spec = EPGraphSpec.from_factor_graph(hierarchical_graph().graph) + layout = build_ep_layout(build_ep_presentation(spec)) + pathlib.Path({str(target)!r}).write_text(json.dumps(layout.to_dict())) + """ + ) + subprocess.run( + [sys.executable, "-c", script], capture_output=True, text=True, check=True + ) + + assert target.read_text() == expected + + +def test_png_bytes_are_identical_across_two_saves(hierarchical_factor_graph, tmp_path): + for filename in ("first", "second"): + save( + draw(_layout(hierarchical_factor_graph)), + path=tmp_path, + filename=filename, + format="png", + ) + + first = hashlib.sha256((tmp_path / "first.png").read_bytes()).hexdigest() + second = hashlib.sha256((tmp_path / "second.png").read_bytes()).hexdigest() + assert first == second + + +def test_a_state_view_is_deterministic_too(stalled_plate, tmp_path): + """ + The overlay is written every sweep of a fit, so it is the view that would + fill an output directory with noise if it were not stable. + """ + from autofit.model_figure.ep.spec import factor_by_key + from autofit.model_figure.ep.state import EPState + + factor_graph, history, _ = stalled_plate + spec = EPGraphSpec.from_factor_graph(factor_graph) + state = EPState.from_history(spec, history, factor_by_key(factor_graph)) + + first = json.dumps(_layout(factor_graph, state).to_dict()) + second = json.dumps(_layout(factor_graph, state).to_dict()) + + assert first == second + + +def test_importing_the_ep_package_does_not_import_matplotlib(): + """ + ``af.EPPlotter`` is exported from ``autofit/__init__.py``, so every drawing + import must sit inside a function -- otherwise every ``import autofit`` + pays for matplotlib. + """ + result = subprocess.run( + [ + sys.executable, + "-c", + "import sys, autofit.model_figure.ep; " + "print([m for m in sys.modules if m.split('.')[0] == 'matplotlib'])", + ], + capture_output=True, + text=True, + check=True, + ) + + assert result.stdout.strip() == "[]" diff --git a/test_autofit/model_figure/ep/test_layout.py b/test_autofit/model_figure/ep/test_layout.py new file mode 100644 index 000000000..3e60fce0a --- /dev/null +++ b/test_autofit/model_figure/ep/test_layout.py @@ -0,0 +1,209 @@ +""" +Layer 4 of the EP figure: where every box goes. + +The measure of a factor-graph figure is whether it can be read, and these are +the four properties that decide that: ranks that tell the generative story top +to bottom, declaration order kept inside each rank, no edge crossing another, +and no box overlapping another. Each is asserted on the phase-4 hierarchical +double, so a layout regression and a figure regression are the same failure. +""" + +import pytest + +from autofit.model_figure.ep.layout import ( + NODE_GAP, + _bipartite_fallback, + _count_crossings, + build_ep_layout, + rank_of, +) +from autofit.model_figure.ep.presentation import build_ep_presentation +from autofit.model_figure.ep.spec import EPGraphSpec + + +@pytest.fixture +def presentation(hierarchical_factor_graph): + return build_ep_presentation( + EPGraphSpec.from_factor_graph(hierarchical_factor_graph) + ) + + +@pytest.fixture +def layout(presentation): + return build_ep_layout(presentation) + + +def _overlap(first, second) -> bool: + return ( + first.x < second.x + second.width + and second.x < first.x + first.width + and first.y < second.y + second.height + and second.y < first.y + first.height + ) + + +def test_the_ranks_read_top_to_bottom_as_the_model_generates(layout): + """ + Hyper parameters, then the distribution, then the variables it draws, then + the analyses that observe them -- the generative story, in reading order. + """ + ranks = {box.key: box.rank for box in layout.nodes} + + assert ranks["factor-3/var-1"] == 1 # HierarchicalFactor0.mean + assert ranks["factor-3/var-2"] == 1 # HierarchicalFactor0.sigma + assert ranks["plate-3"] == 2 # the hierarchical group + assert ranks["plate-0/var-0"] == 3 # centre, drawn from it + assert ranks["plate-0"] == 4 # the dataset plate + + # ... and a rank really is a row: same rank, same top edge. + tops = {} + for box in layout.nodes: + tops.setdefault(box.rank, set()).add(box.y) + assert all(len(values) == 1 for values in tops.values()) + + +def test_a_prior_stub_ranks_by_the_variable_it_wraps(hierarchical_factor_graph): + """ + A stub on a distribution's own parameter is a *hyper factor* and belongs + above it; every other stub belongs at the bottom, under its variable. + """ + spec = EPGraphSpec.from_factor_graph( + hierarchical_factor_graph, show_prior_factors=True + ) + layout = build_ep_layout(build_ep_presentation(spec)) + + stubs = {box.key: box.rank for box in layout.nodes if box.kind == "prior"} + + assert stubs["factor-3/var-1/prior"] == 0 + assert stubs["plate-0/var-0/prior"] == 5 + + +def test_declaration_order_is_kept_within_a_rank(layout): + """ + Nothing is reordered to fill space. The three plate variables are laid out + in the order the spec emitted them, so adding a fourth dataset moves + nothing that was already on the figure. + """ + rank_three = [box for box in layout.nodes if box.rank == 3] + + assert [box.key for box in rank_three] == [ + "plate-0/var-0", + "plate-0/var-1", + "plate-0/var-2", + ] + assert [box.title for box in rank_three] == ["centre", "normalization", "sigma"] + assert sorted(box.x for box in rank_three) == [box.x for box in rank_three] + + +def test_no_edge_crosses_another(layout): + assert _count_crossings(layout) == 0 + + +def test_no_box_overlaps_another(layout): + boxes = list(layout.nodes) + + for index, first in enumerate(boxes): + for second in boxes[index + 1 :]: + assert not _overlap(first, second), f"{first.key} overlaps {second.key}" + + +def test_boxes_on_a_rank_are_separated_by_at_least_the_node_gap(layout): + by_rank = {} + for box in layout.nodes: + by_rank.setdefault(box.rank, []).append(box) + + for boxes in by_rank.values(): + ordered = sorted(boxes, key=lambda box: box.x) + for left, right in zip(ordered, ordered[1:]): + assert right.x - (left.x + left.width) >= NODE_GAP - 1e-6 + + +def test_a_plate_frame_encloses_its_plate_node_and_its_variables(layout): + (frame,) = [frame for frame in layout.plates if frame.key == "plate-0"] + + for key in ("plate-0", "plate-0/var-0", "plate-0/var-1", "plate-0/var-2"): + box = layout.box(key) + assert frame.x <= box.x + assert box.x + box.width <= frame.x + frame.width + assert frame.y <= box.y + assert box.y + box.height <= frame.y + frame.height + + +def test_the_figure_is_big_enough_for_its_legend_and_footer(layout): + """ + A figure sized only to its boxes clips the two lines that explain it. + """ + assert layout.height > max(box.y + box.height for box in layout.nodes) + assert layout.legend_y < layout.footer_y < layout.height + + +def test_an_edge_between_touching_ranks_is_a_straight_line(layout): + for edge in layout.edges: + source = layout.box(edge.source_key) + target = layout.box(edge.target_key) + if abs(source.rank - target.rank) <= 1: + assert len(edge.points) == 2 + + +def test_an_edge_across_a_rank_is_an_orthogonal_elbow(hierarchical_factor_graph): + """ + A long edge drawn diagonally reads as an edge *to* the nodes it passes, so + it turns instead. + """ + spec = EPGraphSpec.from_factor_graph( + hierarchical_factor_graph, show_prior_factors=True + ) + layout = build_ep_layout(build_ep_presentation(spec)) + + long_edges = [ + edge + for edge in layout.edges + if abs(layout.box(edge.source_key).rank - layout.box(edge.target_key).rank) > 1 + ] + + assert long_edges + for edge in long_edges: + assert len(edge.points) == 4 + # the two middle points share a y: the elbow is orthogonal + assert edge.points[1][1] == edge.points[2][1] + + +def test_the_fallback_layout_is_used_when_networkx_cannot_place_the_graph( + presentation, monkeypatch +): + """ + ``multipartite_layout`` does not raise on any graph autofit builds -- but a + figure must never be the reason a fit fails, so the two-column layout + ``graphical.factor_graphs.graph.bipartite_layout`` has always drawn is + there if it ever does. + """ + import networkx + + def explode(*args, **kwargs): + raise ValueError("no layout for you") + + monkeypatch.setattr(networkx, "multipartite_layout", explode) + + layout = build_ep_layout(presentation) + + assert layout.fallback is True + assert len(layout.nodes) == len(presentation.nodes) + boxes = list(layout.nodes) + for index, first in enumerate(boxes): + for second in boxes[index + 1 :]: + assert not _overlap(first, second) + + +def test_the_fallback_spreads_every_rank_around_its_centre(): + ranks = {0: ["a"], 1: ["b", "c", "d"]} + + positions = _bipartite_fallback(ranks) + + assert positions["a"] == 0 + assert positions["b"] < positions["c"] < positions["d"] + assert positions["c"] == 0 + + +def test_rank_of_never_invents_a_rank(presentation): + for node in presentation.nodes: + assert 0 <= rank_of(node) <= 5 diff --git a/test_autofit/model_figure/ep/test_presentation.py b/test_autofit/model_figure/ep/test_presentation.py new file mode 100644 index 000000000..21b8be4e3 --- /dev/null +++ b/test_autofit/model_figure/ep/test_presentation.py @@ -0,0 +1,294 @@ +""" +Layer 3 of the EP figure: what a reader is shown. + +The assertions here are the review's, not the implementation's: a plate is +drawn once, an aggregate is never shown without the members that contradict it, +a label names something the reader can look up, and an edge carries the +sharpest claim that is true of it. +""" + +import pytest + +from autofit import graphical as graph +from autofit.graphical.expectation_propagation.factor_optimiser import ExactFactorFit +from autofit.graphical.expectation_propagation.history import EPHistory +from autofit.model_figure.ep.presentation import ( + EPPresentation, + build_ep_presentation, +) +from autofit.model_figure.ep.spec import EPGraphSpec, factor_by_key +from autofit.model_figure.ep.state import EPState +from test_autofit.graph_spec.graphical_doubles import variable_graph +from test_autofit.graphical.functionality.test_factor_failure_recovery import ( + OverWideFit, + PartialRevertFit, + make_shared_variable_approx, + make_two_variable_approx, +) + + +def _presentation(factor_graph, ep_history=None) -> EPPresentation: + spec = EPGraphSpec.from_factor_graph(factor_graph) + state = ( + None + if ep_history is None + else EPState.from_history(spec, ep_history, factor_by_key(factor_graph)) + ) + return build_ep_presentation(spec, state) + + +@pytest.fixture +def model_view(hierarchical_factor_graph): + return _presentation(hierarchical_factor_graph) + + +# ---------------------------------------------------------------------------- +# the model view +# ---------------------------------------------------------------------------- + + +def test_a_plate_is_one_node_badged_with_its_count(model_view): + """ + Six factors and three datasets collapse to two factor nodes: the figure + scales with the *shape* of the graph, not with the number of datasets. + """ + factors = model_view.factor_nodes() + + assert [node.key for node in factors] == ["plate-0", "plate-3"] + assert [node.title for node in factors] == ["AnalysisFactor", "HierarchicalFactor0"] + assert factors[0].badges == ("3 datasets",) + assert factors[1].badges == ("3 members",) + assert factors[0].members == ("factor-0", "factor-1", "factor-2") + + +def test_a_plate_variable_is_badged_with_how_many_it_stands_for(model_view): + inside = [node for node in model_view.variable_nodes() if node.plate_key] + + assert [node.title for node in inside] == ["centre", "normalization", "sigma"] + assert all(node.badges == ("x3",) for node in inside) + + +def test_a_hyper_variable_keeps_its_qualified_name(model_view): + """ + There is one ``mean``, and ``HierarchicalFactor0.mean`` is what + ``graph.info`` calls it -- stripping that prefix would name nothing. + """ + hyper = [node for node in model_view.variable_nodes() if node.kind == "hyper"] + + assert [node.title for node in hyper] == [ + "HierarchicalFactor0.mean", + "HierarchicalFactor0.sigma", + ] + assert all(node.badges == ("hyper",) for node in hyper) + + +def test_a_shared_variable_loses_the_one_member_its_label_named(): + """ + ``variable_graph`` shares ``centre`` across all three datasets, so the spec + has to label it ``AnalysisFactor0.centre`` -- it sits outside the plate and + the spec strips prefixes only inside one. Naming one of three members is + worse than naming none, so the presentation strips it and says how many + share it instead. + """ + presentation = _presentation(variable_graph().graph) + + (shared,) = [node for node in presentation.variable_nodes() if not node.plate_key] + + assert shared.title == "centre" + assert shared.badges == ("shared x 3",) + + +def test_the_model_view_paints_no_state(model_view): + assert all(node.state is None for node in model_view.nodes) + assert all(node.note is None for node in model_view.nodes) + assert {edge.kind for edge in model_view.edges} == {"incidence"} + assert model_view.kind == "model" + + +def test_every_incidence_becomes_exactly_one_edge_after_the_collapse(model_view): + """ + Eighteen incidences, six edges: three from the dataset plate and three from + the hierarchical group, each drawn once however many members it stands for. + """ + assert len(model_view.edges) == 6 + assert len({(edge.source_key, edge.target_key) for edge in model_view.edges}) == 6 + + +def test_the_footer_counts_the_graph_not_the_picture(model_view): + assert model_view.footer == "6 factors 5 variables 2 plates" + + +def test_prior_stubs_are_drawn_beside_their_variable_when_asked_for( + hierarchical_factor_graph, +): + spec = EPGraphSpec.from_factor_graph( + hierarchical_factor_graph, show_prior_factors=True + ) + presentation = build_ep_presentation(spec) + + stubs = [node for node in presentation.nodes if node.kind == "prior"] + + assert len(stubs) == 5 + assert all(stub.title == "prior" for stub in stubs) + # the stub on a plate variable stands for three priors, not one + assert sorted(stub.badges for stub in stubs) == [(), (), ("x3",), ("x3",), ("x3",)] + # ... and the footer still counts the six real factors + assert presentation.footer.startswith("6 factors") + + +# ---------------------------------------------------------------------------- +# the state view +# ---------------------------------------------------------------------------- + + +def test_a_stalled_member_is_named_in_the_plates_note(stalled_plate): + """ + The rule the diagnostic figure exists for: the plate may not report "3 + datasets, working" while one of them has never landed an update. + """ + factor_graph, history, stalled = stalled_plate + presentation = _presentation(factor_graph, history) + + plate = presentation.node("plate-0") + + assert plate.state == "working" + assert plate.note == f"1 of 3 stale: {stalled.name}" + + +def test_the_stalled_member_is_also_drawn_as_a_node_of_its_own(stalled_plate): + factor_graph, history, stalled = stalled_plate + presentation = _presentation(factor_graph, history) + + expanded = presentation.node("factor-2") + + assert expanded.title == stalled.name + assert expanded.state == "stale" + assert expanded.subtitle == "member 3 of 3" + assert expanded.plate_key == "plate-0" + # the badges say why it is exceptional without the reader opening a log + assert expanded.badges == ("0 updates / 4 sweeps", "age 4", "BAD_PROJECTION") + + +def test_the_stalled_members_edges_are_stale_and_the_plates_are_not(stalled_plate): + """ + A plate's edges speak for the members it still stands for. The stale + member's own edges carry its claim -- greying the aggregate too would say + three datasets had stalled when one had. + """ + factor_graph, history, _ = stalled_plate + presentation = _presentation(factor_graph, history) + + own = [edge for edge in presentation.edges if edge.source_key == "factor-2"] + plate = [edge for edge in presentation.edges if edge.source_key == "plate-0"] + + assert len(own) == 3 + assert {edge.kind for edge in own} == {"stale"} + assert {edge.kind for edge in plate} == {"incidence"} + + +def test_the_footer_counts_every_status(stalled_plate): + factor_graph, history, _ = stalled_plate + presentation = _presentation(factor_graph, history) + + assert presentation.footer == ( + "6 factors 5 variables 2 plates " + "1 stale 0 reverting 0 converged 5 working sweep 4" + ) + assert presentation.kind == "state" + assert "red dashed = reverted update" in presentation.legend + + +def test_a_reverted_update_is_a_reverted_edge_on_that_variable_alone(tmp_path): + """ + ``PartialRevertFit`` reverts ``y`` on every projection and moves ``x``. The + figure has to separate them: the factor updated, so nothing at factor level + can see this, and an edge is the only place the claim fits. + """ + model_approx, factor_graph, prior_x, prior_y, likelihood = ( + make_two_variable_approx() + ) + optimiser = graph.EPOptimiser( + factor_graph, + factor_optimisers={ + prior_x: ExactFactorFit(), + prior_y: ExactFactorFit(), + likelihood: PartialRevertFit(reverting="y"), + }, + ep_history=EPHistory(kl_tol=None), + paths=False, + ) + optimiser.run(model_approx, max_steps=4, max_consecutive_failures=100) + + presentation = _presentation(factor_graph, optimiser.ep_history) + (joint,) = [ + node for node in presentation.factor_nodes() if node.title == likelihood.name + ] + edges = { + edge.label: edge.kind + for edge in presentation.edges + if edge.source_key == joint.key + } + + assert joint.state == "reverting" + assert edges["like_xy.y"] == "reverted" + assert edges["like_xy.x"] == "incidence" + + +def test_a_stale_factors_edges_are_stale_even_though_it_reverted(tmp_path): + """ + ``OverWideFit`` reverts everything on every projection, so the factor is + both stale and reverting -- and the node reports the stronger claim, so its + edges must not quietly report the weaker one. + """ + model_approx, factor_graph, prior, likelihood = make_shared_variable_approx() + optimiser = graph.EPOptimiser( + factor_graph, + factor_optimisers={prior: ExactFactorFit(), likelihood: OverWideFit()}, + ep_history=EPHistory(kl_tol=None), + paths=False, + ) + optimiser.run(model_approx, max_steps=4, max_consecutive_failures=100) + + presentation = _presentation(factor_graph, optimiser.ep_history) + (over_wide,) = [ + node for node in presentation.factor_nodes() if node.title == likelihood.name + ] + kinds = { + edge.kind for edge in presentation.edges if edge.source_key == over_wide.key + } + + assert over_wide.state == "stale" + assert over_wide.badges[0] == "0 updates / 4 sweeps" + assert kinds == {"stale"} + + +def test_a_plate_with_nothing_exceptional_carries_no_note(hierarchical_factor_graph): + """ + The exception list is not decoration: a plate whose members agree says + nothing extra, or the one that does would not stand out. + """ + from autofit.graphical.expectation_propagation.history import FactorHistory + from autofit.graphical.utils import Status + + history = EPHistory(kl_tol=None, evidence_tol=None) + for factor in hierarchical_factor_graph.factors: + entry = FactorHistory(factor) + entry.history.append((None, Status(success=True, updated=True))) + history.history[factor] = entry + + presentation = _presentation(hierarchical_factor_graph, history) + + assert presentation.node("plate-0").note is None + assert [node.key for node in presentation.factor_nodes()] == ["plate-0", "plate-3"] + + +def test_to_dict_is_stable_and_serialisable(stalled_plate): + import json + + factor_graph, history, _ = stalled_plate + + first = _presentation(factor_graph, history).to_dict() + second = _presentation(factor_graph, history).to_dict() + + assert first == second + assert json.dumps(first, sort_keys=True) == json.dumps(second, sort_keys=True) diff --git a/test_autofit/model_figure/ep/test_spec.py b/test_autofit/model_figure/ep/test_spec.py new file mode 100644 index 000000000..d3d7091d9 --- /dev/null +++ b/test_autofit/model_figure/ep/test_spec.py @@ -0,0 +1,339 @@ +""" +Layer 1 of the EP figure: the structure read off a ``DeclarativeFactorGraph``. + +The fixtures are the phase-4 graphical doubles, so a spec failure and a figure +regression are the same failure. They are built the way ``EPOptimiser`` builds +its graph -- ``AbstractDeclarativeFactor.graph``, once -- because that is the +object the optimiser sweeps and the one ``EPHistory`` is keyed by. +""" + +import json + +import pytest + +import autofit as af +from autofit.graphical.declarative.abstract import AbstractDeclarativeFactor +from autofit.graphical.factor_graphs.graph import FactorGraph +from autofit.model_figure.ep.spec import EPGraphSpec, factor_by_key, label_for_variable +from test_autofit.graph_spec.graphical_doubles import ( + hierarchical_graph, + shared_graph, + variable_graph, +) + + +@pytest.fixture +def hierarchical_factor_graph(): + """ + The ``DeclarativeFactorGraph`` ``EPOptimiser`` would be handed: three + ``AnalysisFactor``s, one ``HierarchicalFactor`` decomposed into three + members, and one ``PriorFactor`` per prior. + """ + return hierarchical_graph().graph + + +@pytest.fixture +def spec(hierarchical_factor_graph): + return EPGraphSpec.from_factor_graph(hierarchical_factor_graph) + + +def test_the_graph_is_read_once_and_never_rebuilt(monkeypatch): + """ + ``AbstractDeclarativeFactor.graph`` rebuilds the whole graph and renames + every ``PriorFactor`` on each access, and ``FactorGraph.graph`` builds a + networkx view; the spec must touch neither, and must walk + ``factor_graph.factors`` exactly once. + """ + rebuilds = [] + networkx_views = [] + factor_reads = [] + + declarative_graph = AbstractDeclarativeFactor.graph.fget + networkx_graph = FactorGraph.graph.fget + factors = FactorGraph.factors.fget + + def counted(log, original): + def wrapper(self): + log.append(1) + return original(self) + + return property(wrapper) + + monkeypatch.setattr( + AbstractDeclarativeFactor, "graph", counted(rebuilds, declarative_graph) + ) + monkeypatch.setattr(FactorGraph, "graph", counted(networkx_views, networkx_graph)) + monkeypatch.setattr(FactorGraph, "factors", counted(factor_reads, factors)) + + factor_graph = hierarchical_graph().graph + assert len(rebuilds) == 1 + + before = len(factor_reads) + EPGraphSpec.from_factor_graph(factor_graph) + + assert len(factor_reads) - before == 1 + assert len(rebuilds) == 1 + assert networkx_views == [] + + +def test_counts(spec): + """ + Six drawn factors (the eleven ``PriorFactor``s are hidden), five variable + nodes -- three collapsed inside the dataset plate plus the two free + hyper-parameters -- and one edge per (factor, variable) pair. + """ + assert len(spec.factors) == 6 + assert len(spec.variables) == 5 + assert len(spec.incidences) == 18 + assert len(spec.plates) == 2 + + +def test_the_three_analysis_factors_are_one_plate(spec): + (plate,) = [plate for plate in spec.plates if plate.kind == "analysis"] + + assert plate.count == 3 + assert plate.member_keys == ("factor-0", "factor-1", "factor-2") + assert plate.representative_key == "factor-0" + + members = [factor for factor in spec.factors if factor.plate_key == plate.key] + assert [factor.name for factor in members] == [ + "AnalysisFactor0", + "AnalysisFactor1", + "AnalysisFactor2", + ] + assert [factor.member_index for factor in members] == [0, 1, 2] + assert all(factor.kind == "analysis" for factor in members) + + +def test_the_three_hierarchical_factors_are_one_group(spec): + """ + A ``HierarchicalFactor`` decomposes into one factor per drawn variable, all + carrying ``distribution_model.name`` -- the optimiser's own group key. + """ + (plate,) = [plate for plate in spec.plates if plate.kind == "hierarchical"] + + assert plate.count == 3 + assert plate.member_keys == ("factor-3", "factor-4", "factor-5") + assert plate.signature == ("hierarchical", "HierarchicalFactor0") + + members = [factor for factor in spec.factors if factor.plate_key == plate.key] + assert {factor.name for factor in members} == {"HierarchicalFactor0"} + assert [factor.member_index for factor in members] == [0, 1, 2] + + +def test_a_variable_of_one_member_is_collapsed_into_the_plate(spec): + """ + Each dataset carries its own ``centre``, ``normalization`` and ``sigma``: + one node apiece, inside the plate, standing for three variables. + """ + plated = [ + variable for variable in spec.variables if variable.plate_key == "plate-0" + ] + + assert [variable.label for variable in plated] == [ + "centre", + "normalization", + "sigma", + ] + assert [variable.count for variable in plated] == [3, 3, 3] + + +def test_a_variable_of_every_member_is_shared_outside_the_plate(spec): + """ + The parent distribution's ``mean`` and ``sigma`` are incident on all three + hierarchical members, so they are drawn once, outside. + """ + shared = [variable for variable in spec.variables if variable.plate_key is None] + + assert [variable.label for variable in shared] == [ + "HierarchicalFactor0.mean", + "HierarchicalFactor0.sigma", + ] + assert [variable.count for variable in shared] == [1, 1] + assert [variable.kind for variable in shared] == ["hyper", "hyper"] + + +def test_the_drawn_variable_is_marked_as_drawn(spec): + (centre,) = [variable for variable in spec.variables if variable.label == "centre"] + assert centre.kind == "drawn" + + # ... and every hierarchical member reaches into the dataset plate for it + hierarchical = [factor for factor in spec.factors if factor.kind == "hierarchical"] + assert all(centre.key in factor.variable_keys for factor in hierarchical) + + +def test_prior_factors_are_hidden_by_default(spec): + assert [factor for factor in spec.factors if factor.kind == "prior"] == [] + assert all( + not incidence.factor_key.endswith("/prior") for incidence in spec.incidences + ) + + # but the spec still records which variables have one, so the render layer + # can draw a stub without eleven extra nodes + assert set(spec.prior_factor_variable_keys) == { + variable.key for variable in spec.variables + } + + +def test_prior_factors_are_drawn_when_asked_for(hierarchical_factor_graph): + shown = EPGraphSpec.from_factor_graph( + hierarchical_factor_graph, show_prior_factors=True + ) + + stubs = [factor for factor in shown.factors if factor.kind == "prior"] + + # one per *variable node*, not one per prior: the plate collapses the three + # copies of each per-dataset prior into one + assert len(stubs) == 5 + assert {stub.key for stub in stubs} == { + f"{variable.key}/prior" for variable in shown.variables + } + for stub in stubs: + (variable_key,) = stub.variable_keys + (variable,) = [v for v in shown.variables if v.key == variable_key] + assert stub.plate_key == variable.plate_key + + assert len(shown.incidences) == len( + EPGraphSpec.from_factor_graph(hierarchical_factor_graph).incidences + ) + len(stubs) + + +def test_variable_nodes_and_keys_do_not_move_when_prior_factors_are_shown( + hierarchical_factor_graph, +): + hidden = EPGraphSpec.from_factor_graph(hierarchical_factor_graph) + shown = EPGraphSpec.from_factor_graph( + hierarchical_factor_graph, show_prior_factors=True + ) + assert hidden.variables == shown.variables + assert hidden.plates == shown.plates + + +def test_no_label_is_a_variable_counter_form(spec, hierarchical_factor_graph): + """ + ``variable.label`` is a global-counter form -- ``centre1``, ``cls3``, + ``mean0``. It names nothing a reader of ``graph.info`` can find, so no spec + label may be one. + """ + counter_forms = { + variable.label for variable in hierarchical_factor_graph.all_variables + } + assert counter_forms # the fixture really does carry them + + labels = {variable.label for variable in spec.variables} + labels |= {incidence.label for incidence in spec.incidences} + + assert labels.isdisjoint(counter_forms) + + +def test_labels_are_unique_within_a_factor(spec): + """ + ``_HierarchicalFactor.name_for_variable`` answers with the distribution + model's name for every one of its variables; the spec has to separate them + or the figure carries three nodes reading ``HierarchicalFactor0``. + """ + for factor in spec.factors: + labels = [ + incidence.label + for incidence in spec.incidences + if incidence.factor_key == factor.key + ] + assert len(labels) == len(set(labels)) + + +def test_keys_carry_no_ids_or_namer_counters(spec): + """ + Keys are built from declaration indices alone. A prior's id or a ``namer`` + counter in a key would make the figure a function of import order. + """ + keys = ( + [factor.key for factor in spec.factors] + + [variable.key for variable in spec.variables] + + [plate.key for plate in spec.plates] + ) + for key in keys: + assert "AnalysisFactor" not in key + assert "HierarchicalFactor" not in key + assert "prior_" not in key + + +def test_factor_by_key_maps_onto_the_live_factors(hierarchical_factor_graph, spec): + mapping = factor_by_key(hierarchical_factor_graph) + + assert len(mapping) == len(hierarchical_factor_graph.factors) + for factor in spec.factors: + assert mapping[factor.key].name == factor.name + + +def test_to_dict_is_json_serialisable_and_stable(hierarchical_factor_graph): + first = EPGraphSpec.from_factor_graph(hierarchical_factor_graph).to_dict() + second = EPGraphSpec.from_factor_graph(hierarchical_factor_graph).to_dict() + + assert first == second + assert json.dumps(first, sort_keys=True) == json.dumps(second, sort_keys=True) + + +def test_two_builds_of_the_same_model_agree(): + """ + The spec is a function of the model, not of the process: a fresh build of + the same graph -- new priors, new ids -- gives the same dictionary. + """ + import itertools + + from autofit.tools.namer import namer + + def build(): + af.ModelObject._ids = itertools.count() + af.Prior._ids = itertools.count() + namer.reset() + return EPGraphSpec.from_factor_graph(hierarchical_graph().graph).to_dict() + + assert build() == build() + + +def test_shared_graph_draws_every_prior_outside_the_plate(): + """ + ``shared_graph`` gives all three datasets one model object, so every prior + is literally shared: the plate is a plate of three factors with nothing + inside it. + """ + spec = EPGraphSpec.from_factor_graph(shared_graph().graph) + + (plate,) = spec.plates + assert plate.count == 3 + assert [variable.plate_key for variable in spec.variables] == [None, None, None] + assert [variable.count for variable in spec.variables] == [1, 1, 1] + + +def test_variable_graph_splits_shared_from_per_dataset_priors(): + """ + ``variable_graph`` shares ``centre`` and gives each dataset its own + ``normalization`` and ``sigma`` -- the two halves of the plate rule on one + graph. + """ + spec = EPGraphSpec.from_factor_graph(variable_graph().graph) + + outside = [variable for variable in spec.variables if variable.plate_key is None] + inside = [variable for variable in spec.variables if variable.plate_key is not None] + + assert [variable.label for variable in outside] == ["AnalysisFactor0.centre"] + assert [variable.label for variable in inside] == ["normalization", "sigma"] + assert [variable.count for variable in inside] == [3, 3] + + +def test_label_for_variable_separates_a_plain_factors_arguments(): + """ + A plain ``Factor`` answers with its own name for every argument -- the + shape ``test_factor_failure_recovery``'s doubles take, and the one the + state overlay has to map a reverted variable through. + """ + import numpy as np + + from autofit import graphical as graph + from autofit.mapper.variable import Variable + + x, y = Variable("x"), Variable("y") + factor = graph.Factor(lambda x, y: np.sum(x + y), x, y, name="like_xy") + + assert label_for_variable(factor, x) == "like_xy.x" + assert label_for_variable(factor, y) == "like_xy.y" diff --git a/test_autofit/model_figure/ep/test_state.py b/test_autofit/model_figure/ep/test_state.py new file mode 100644 index 000000000..df2875936 --- /dev/null +++ b/test_autofit/model_figure/ep/test_state.py @@ -0,0 +1,280 @@ +""" +Layer 2 of the EP figure: the run's state, read off a real ``EPHistory``. + +Every fixture here drives a real ``EPOptimiser`` loop over the doubles that +``test_factor_failure_recovery`` wrote for the reversion bugs themselves +(PyAutoFit #1571, #1575, #1579), so the overlay is asserted against the same +behaviour those tests pin rather than against a hand-built history. They are +tiny graphs with ``max_steps=4``. +""" + +import csv +import json + +import pytest + +from autofit import graphical as graph +from autofit.graphical.expectation_propagation.factor_optimiser import ExactFactorFit +from autofit.graphical.expectation_propagation.history import EPHistory +from autofit.model_figure.ep.spec import EPGraphSpec, factor_by_key +from autofit.model_figure.ep.state import EPState, _reverted_names +from autofit.non_linear.paths.directory import DirectoryPaths +from test_autofit.graphical.functionality.test_factor_failure_recovery import ( + OverWideFit, + PartialRevertFit, + make_shared_variable_approx, + make_two_variable_approx, +) + + +def _state(optimiser, factor_graph): + spec = EPGraphSpec.from_factor_graph(factor_graph) + return spec, EPState.from_history( + spec, optimiser.ep_history, factor_by_key(factor_graph) + ) + + +def _by_name(spec, state, name): + (node,) = [factor for factor in spec.factors if factor.name == name] + (factor_state,) = [factor for factor in state.factors if factor.key == node.key] + return factor_state + + +def _variable_key(spec, label): + (variable,) = [variable for variable in spec.variables if variable.label == label] + return variable.key + + +@pytest.fixture +def partial_revert(tmp_path): + """ + One factor that reverts ``y`` on every projection while moving ``x`` -- the + partial revert of PyAutoFit #1575. The factor itself updates, so nothing at + factor level can see it. + """ + model_approx, factor_graph, prior_x, prior_y, likelihood = ( + make_two_variable_approx() + ) + + optimiser = graph.EPOptimiser( + factor_graph, + factor_optimisers={ + prior_x: ExactFactorFit(), + prior_y: ExactFactorFit(), + likelihood: PartialRevertFit(reverting="y"), + }, + ep_history=EPHistory(kl_tol=None), + paths=DirectoryPaths(name="partial_revert", path_prefix=str(tmp_path)), + ) + optimiser.run(model_approx, max_steps=4, max_consecutive_failures=100) + return optimiser, factor_graph, likelihood + + +def test_a_partial_revert_names_the_reverted_variable_and_only_it(partial_revert): + optimiser, factor_graph, _ = partial_revert + spec, state = _state(optimiser, factor_graph) + + joint = _by_name(spec, state, "like_xy") + + assert joint.status == "reverting" + assert joint.reverted_variable_keys == (_variable_key(spec, "prior_y.y"),) + assert _variable_key(spec, "prior_x.x") not in joint.reverted_variable_keys + assert joint.last_flag == "BAD_PROJECTION" + + # ... and the factor really did update, which is why nothing at factor + # level could see this + assert joint.updates >= 1 + + +def test_the_reverted_variable_carries_the_factor_that_reverted_it(partial_revert): + optimiser, factor_graph, _ = partial_revert + spec, state = _state(optimiser, factor_graph) + + joint = _by_name(spec, state, "like_xy") + by_key = {variable.key: variable for variable in state.variables} + + assert by_key[_variable_key(spec, "prior_y.y")].reverted_by == (joint.key,) + assert by_key[_variable_key(spec, "prior_x.x")].reverted_by == () + + +def test_the_exact_factors_are_not_reverting(partial_revert): + optimiser, factor_graph, _ = partial_revert + spec, state = _state(optimiser, factor_graph) + + for name in ("prior_x", "prior_y"): + factor_state = _by_name(spec, state, name) + assert factor_state.reverted_variable_keys == () + assert factor_state.status != "reverting" + + +def test_reverted_names_matches_the_ep_history_csv_column(partial_revert): + """ + ``_reverted_names`` is a private copy of the ``reverted_variables`` column + logic, so it is pinned to a real CSV written by a real run rather than to + a reading of ``diagnostics.py``. + """ + optimiser, _, likelihood = partial_revert + + with open(optimiser.output_path / "ep_history.csv", newline="") as f: + rows = list(csv.DictReader(f)) + + column = [ + row["reverted_variables"] for row in rows if row["factor"] == likelihood.name + ] + helper = [ + ";".join(_reverted_names(status)) + for _, status in optimiser.ep_history.history[likelihood].history + ] + + assert column == helper + assert column == ["y", "y", "y", "y"] + + +def test_a_factor_that_never_updates_is_stale_and_as_old_as_the_run(tmp_path): + """ + ``OverWideFit`` reverts every parameter on every projection, so the factor + is both stale and reverting -- and the stronger claim wins, because its + reported posterior is the message it started with. + """ + model_approx, factor_graph, prior, likelihood = make_shared_variable_approx() + + optimiser = graph.EPOptimiser( + factor_graph, + factor_optimisers={prior: ExactFactorFit(), likelihood: OverWideFit()}, + ep_history=EPHistory(kl_tol=None), + paths=False, + ) + optimiser.run(model_approx, max_steps=4, max_consecutive_failures=100) + + spec, state = _state(optimiser, factor_graph) + over_wide = _by_name(spec, state, "like_x") + + assert over_wide.status == "stale" + assert over_wide.updates == 0 + assert over_wide.sweeps == 4 + assert over_wide.age == over_wide.sweeps + assert over_wide.reverted_variable_keys # it is reverting too -- stale wins + + # the optimiser's own end-of-run check agrees + assert likelihood in optimiser._factors_skipped + + +def test_a_fixed_point_restart_is_neither_stale_nor_reverting(tmp_path): + """ + EP restarted from its own converged mean field reproduces every message + exactly: nothing moves, but nothing is rejected either. A fixed point is + not a rejection (PyAutoFit #1579). + """ + model_approx, factor_graph, prior, likelihood = make_shared_variable_approx() + + def run(approx, name, steps): + optimiser = graph.EPOptimiser( + factor_graph, + factor_optimisers={prior: ExactFactorFit(), likelihood: ExactFactorFit()}, + ep_history=EPHistory(kl_tol=None), + paths=DirectoryPaths(name=name, path_prefix=str(tmp_path)), + ) + return optimiser, optimiser.run( + approx, max_steps=steps, max_consecutive_failures=100 + ) + + _, converged = run(model_approx, "burn_in", 6) + optimiser, _ = run(converged, "fixed_point", 4) + + spec, state = _state(optimiser, factor_graph) + + assert optimiser._stale_factor_warnings() == [] + for factor_state in state.factors: + assert factor_state.status not in ("stale", "reverting") + assert factor_state.reverted_variable_keys == () + assert all(variable.reverted_by == () for variable in state.variables) + + +def test_a_converged_factor_is_reported_as_converged(): + """ + ``converged`` is ``EPHistory``'s own test, not a reimplementation of it -- + the same predicate the optimiser stops on. + """ + model_approx, factor_graph, prior, likelihood = make_shared_variable_approx() + + optimiser = graph.EPOptimiser( + factor_graph, + factor_optimisers={prior: ExactFactorFit(), likelihood: ExactFactorFit()}, + paths=False, + ) + optimiser.run(model_approx, max_steps=6, max_consecutive_failures=100) + + spec, state = _state(optimiser, factor_graph) + + assert optimiser.ep_history.is_converged(likelihood) is True + assert _by_name(spec, state, "like_x").status == "converged" + + +def test_a_factor_the_sweep_has_not_reached_is_absent(): + """ + ``EPHistory[factor]`` *creates* an empty history for any factor it is asked + about, so a state read through it would report a never-visited factor as + visited zero times instead of as absent. It is read through + ``EPHistory.history`` for exactly that reason. + """ + _, factor_graph, _, _ = make_shared_variable_approx() + + spec = EPGraphSpec.from_factor_graph(factor_graph) + state = EPState.from_history(spec, EPHistory(), factor_by_key(factor_graph)) + + assert {factor.status for factor in state.factors} == {"absent"} + assert all(factor.sweeps == 0 and factor.age == 0 for factor in state.factors) + assert state.step == 0 + + +def test_a_missing_factor_key_is_absent_rather_than_an_error(partial_revert): + """ + A collapsed ``PriorFactor`` stub stands for a group and has no single + history, so the mapping will not always cover every spec node. + """ + optimiser, factor_graph, _ = partial_revert + spec = EPGraphSpec.from_factor_graph(factor_graph) + + mapping = factor_by_key(factor_graph) + del mapping["factor-2"] + + state = EPState.from_history(spec, optimiser.ep_history, mapping) + + (missing,) = [factor for factor in state.factors if factor.key == "factor-2"] + assert missing.status == "absent" + + +def test_step_is_the_longest_run_of_sweeps(partial_revert): + optimiser, factor_graph, _ = partial_revert + _, state = _state(optimiser, factor_graph) + + assert state.step == max(factor.sweeps for factor in state.factors) == 4 + + +def test_model_approx_is_accepted_and_ignored(partial_revert): + """ + Posterior values are a later overlay; the argument is in the signature so + that it will not have to change when they arrive. + """ + optimiser, factor_graph, _ = partial_revert + spec = EPGraphSpec.from_factor_graph(factor_graph) + mapping = factor_by_key(factor_graph) + + without = EPState.from_history(spec, optimiser.ep_history, mapping) + with_approx = EPState.from_history( + spec, optimiser.ep_history, mapping, model_approx=object() + ) + + assert without == with_approx + + +def test_to_dict_is_json_serialisable_and_stable(partial_revert): + optimiser, factor_graph, _ = partial_revert + spec = EPGraphSpec.from_factor_graph(factor_graph) + mapping = factor_by_key(factor_graph) + + first = EPState.from_history(spec, optimiser.ep_history, mapping).to_dict() + second = EPState.from_history(spec, optimiser.ep_history, mapping).to_dict() + + assert first == second + assert json.dumps(first, sort_keys=True) == json.dumps(second, sort_keys=True)