Skip to content

feat(model_figure): EP factor-graph diagnostic figure (phase 5) #1618

Closed

Description

@Jammy2211

Overview

Phase 5 of the model-figures epic. Phases 1–4 shipped the containment-style
model figure (af.ModelPlotter), including plate notation for graphical models
(PyAutoFit#1617, merged 2026-09-12). This phase draws the diagnostic view the
epic review approved as a separate figure: an explicit factor graph (factor
nodes and variable nodes, plate-grouped) with the EP run's state painted on
it — factor status, update age, and confirmed reverted updates.

Library-only task (PyAutoFit). The workspace / HowToFit EP scripts get their
figures in phase 6 (rollout). Prompt:
PyAutoMind/active/model_figures_5_ep_view.md; epic ledger:
PyAutoMind/draft/feature/autofit/model_figures_epic.md.

Plan

  • Add a new sub-package autofit/model_figure/ep/ with the same three-layer shape
    as phases 1–4: structure (spec) → overlay (state) → presentation → layout →
    render, driven by a new af.EPPlotter.
  • Structure: read EPOptimiser.factor_graph once into immutable tuples;
    infer plates at the factor level (grouping AnalysisFactors by signature and
    _HierarchicalFactors by name); hide PriorFactors by default.
  • Overlay: derive per-factor status (stale / reverting / working /
    converged), updates, sweeps and age from FactorHistory, plus the
    confirmed reverted (factor, variable) pairs — the same fact the
    reverted_variables column of ep_history.csv carries.
  • Failures are never hidden by a plate: a collapsed plate shows the modal
    status plus a note naming every exceptional member, and each exceptional member
    is expanded as its own node beside the plate.
  • Layout: networkx + matplotlib only (see the decision below) — rank by node
    kind with one stable barycentre pass, then nx.multipartite_layout; coordinates
    rounded so the figure is byte-deterministic.
  • Hook: Visualise gains the factor graph and writes graph_model.png once
    and graph_state.png on every visualise_interval tick, behind the existing
    output.yaml model_figure key and the usual blanket except so a figure
    failure can never break an EP run. optimiser.py changes 3 lines.
  • Ship with evidence: three real-EP PNGs committed under docs/images/model_figures/
    and a "Seeing the EP run" section in docs/features/graphical.md.

Human decisions taken 2026-09-12 (recorded here so a fresh session need not re-ask)

  1. Layout engine = networkx + matplotlib only. Graphviz is rejected. The
    prompt left this open and explicitly permitted graphviz for this one phase.
    It is rejected because the dot binary is absent locally, absent on the
    GitHub ubuntu-24.04 runner and usually absent on Colab, and is not
    pip-installable — a graphviz path would need a matplotlib fallback anyway, so
    it buys a second engine to maintain and nothing else. networkx==3.1 is
    already a hard dependency (pyproject.toml:56).
  2. Optional overlays are deferred. Prompt items 4–6 — variable mean ± std,
    message precision (with its signed/invalid-precision handling), and per-factor
    KL sparklines — are out of scope here and become a follow-up prompt filed
    at close-out. This phase ships the review's first three priorities: status,
    update age, confirmed reversions.
  3. Parallel-worktree waiver: granted but moot. A waiver was granted to run
    this phase alongside the open PR refactor(ep): remove ParallelEPOptimiser and its tests (#1611) #1612 (remove ParallelEPOptimiser). refactor(ep): remove ParallelEPOptimiser and its tests (#1611) #1612
    merged at 19:29 on 2026-09-12, so this task branches from a main that
    already contains it and no parallel claim is needed.
Detailed implementation plan

Work Classification

Library (PyAutoFit source only). No workspace repo is touched in this phase.

Affected Repositories

  • PyAutoFit (primary)

Branch Survey

Repository Current Branch Dirty?
./PyAutoFit main clean (at 54f464d97, includes #1612 and #1617)

Suggested branch: feature/model-figures-ep-view

Worktree root: ~/Code/PyAutoLabs-wt/model-figures-ep-view/ (created by /start_library)

worktree_check_conflict model-figures-ep-view PyAutoFit → exit 0, no conflict.

Design

New package autofit/model_figure/ep/ — no drawing imports at module level:

file role
spec.py structure: FactorNode, VariableNode, Incidence, PlateGroup, EPGraphSpec.from_factor_graph(factor_graph, show_prior_factors=False) — reads the DeclarativeFactorGraph once into tuples
state.py overlay: FactorState(status, updates, sweeps, age, reverted_variable_keys, last_flag), VariableState, EPState.from_history(spec, ep_history, model_approx=None)
presentation.py EPNode, EPEdge, EPPresentation, build_ep_presentation(spec, state=None, ...)
layout.py build_ep_layout(presentation, style) — ranks by node kind + one stable barycentre pass seeded by declaration order → nx.multipartite_layout(subset_key="rank", align="horizontal"), scaled by measure_text; coords rounded 4 dp
render.py draw(layout, style); re-exports save
plotter.py af.EPPlotter(factor_graph, ep_history=None, model_approx=None) with .spec() / .state() / .presentation(kind) / .layout() / .figure(path, filename, format, kind="model"|"state", show_prior_factors=False, width=14.0)
autofit/model_figure/config.py model_figure_enabled() lifted verbatim from autofit/non_linear/paths/directory.py:32-49; directory.py keeps _model_figure_enabled as an alias (it is imported by test_autofit/non_linear/paths/test_model_figure_output.py)

Reused unchanged: Style, measure_text, _line_height (model_figure/layout.py);
PALETTE, _box, _text, _badge_colours, _LINK_COLOURS, save (model_figure/render.py).

Deliberately not reused: build_layout / _route (the containment engine —
gutter routing and a max_links=12 cap that an edge-dominated bipartite graph
blows straight past).

Structure rules (spec.py)

  • Source of truth is EPOptimiser.factor_graph, never fgm.graph /
    model_approx.factor_graph (those rebuild and rename PriorFactors on every
    access; EPHistory is keyed by the optimiser's own factor objects).
  • Plates are inferred at factor level — phase 4's _collapse_siblings needs a
    GlobalPriorModel, which is unreachable here. AnalysisFactors group by
    signature (class name, dotted prior paths, cls names); _HierarchicalFactors
    group by factor.name (= distribution_model.name, the optimiser's own
    stale-group key). Groups of size ≥ 2 become a plate, ordered by first index in
    factor_graph.factors.
  • A variable incident on exactly one member of a plate → one node inside the
    plate badged ×N; incident on every member → one shared node outside.
  • Labels come from factor.name_for_variable(v) (skip None;
    _HierarchicalFactor → distribution_model.name) — never variable.label.
  • PriorFactors hidden by default (a small stub on the variable), drawn with
    show_prior_factors=True.

Overlay rules (state.py) — per factor from FactorHistory.history (history.py:51)

  • sweeps = len(history); updates = count(status.updated); age = sweeps since
    the last updated entry (derived — it is stored nowhere).
  • status ∈ {stale, reverting, working, converged}: stale iff
    sweeps >= 1 and updates == 0 (the complement of the condition at
    optimiser.py:488); converged via EPHistory's own convergence test;
    reverting iff the latest status has reverted variables; else working.
  • reverted_variable_keys = names with status.changed[v] is False where
    changed is not None — identical to the reverted_variables CSV column
    (diagnostics.py:147-156), which is produced only on the BAD_PROJECTION branch
    (mean_field.py:556-566). changed is None and an all-True mask are never
    reversion. Implemented as a private _reverted_names(status) in state.py
    (not lifted into diagnostics.py, whose test refactor(ep): remove ParallelEPOptimiser and its tests (#1611) #1612 touched), and pinned equal
    to a real ep_history.csv by a test. Read Status attributes directly — its
    __iter__ yields only 4 fields.
  • Plate node = modal status + a note ("1 of 3 stale: AnalysisFactor2"); every
    exceptional member (status ≠ modal, or reverted keys non-empty, or age > modal)
    is expanded as its own node beside the plate, named by factor.name. No
    aggregate is ever shown without the exceptional list.

Render encoding

Stale factor = grey node + greyed edges + badge "0 updates / N sweeps"; reverting
= dashed red edge on the reverted (factor, variable) pair; converged = green
outline; legend + footer in the phase-4 style.

Hook

visualise.py does the work; optimiser.py changes 3 lines.

  • Visualise.__init__(ep_history, output_path, factor_graph=None);
    Visualise.__call__(model_approx=None) additionally calls
    _model_figures(model_approx), which returns unless factor_graph is set and
    model_figure_enabled() and not skip_visualization(). It writes
    graph_model.png once (first call) and graph_state.png on every call; the
    whole body sits under the blanket except Exception → logger.info pattern of
    directory.py:527-537.
  • optimiser.py: :290 pass factor_graph=self.factor_graph; :607 and :615
    become self.visualiser(model_approx). stochastic.py is untouched — it calls
    the same object with no args, so the status/age/reversion overlay still renders.
  • Gate key stays output.yaml → model_figure (default false, unchanged). Never
    model_graph, which gates the graphical-model text dump.

Exports: af.EPPlotter from autofit/model_figure/__init__.py and
autofit/__init__.py, beside ModelPlotter.

Implementation Steps

  1. ep/spec.py + the model_figure/config.py lift +
    test_autofit/model_figure/ep/{__init__,conftest,test_spec}.py (~320 new lines).
    conftest mirrors test_autofit/model_figure/conftest.py (reset
    ModelObject._ids, Prior._ids, namer); fixture from
    test_autofit/graph_spec/graphical_doubles.py::hierarchical_graph().
  2. ep/state.py + test_state.py (~260). Fixtures from
    test_autofit/graphical/functionality/test_factor_failure_recovery.py:
    make_two_variable_approx + PartialRevertFit(reverting="y") (y reverted, x
    not); OverWideFit (stale, updates == 0, age == sweeps); the fixed-point
    restart graph (unchanged ≠ reverted); plus the ep_history.csv cross-check.
  3. ep/presentation.py + ep/layout.py + ep/render.py + test_presentation.py,
    test_layout.py (plate note names the failing member; exceptional member
    expanded; _count_crossings() == 0 on the hierarchical fixture; declaration
    order kept) and test_determinism.py (layout dict equal across builds and a
    fresh interpreter; PNG bytes equal) (~520).
  4. ep/plotter.py + exports + test_acceptance_ep.py — the prompt's four
    acceptance bullets asserted on the presentation/state dataclasses, plus one
    PNG smoke each (~200).
  5. Hook: visualise.py (~70) + the 3 lines in optimiser.py +
    test_autofit/graphical/functionality/test_ep_visualise_output.py — a real
    EPOptimiser.run(visualise_interval=1, max_steps=3) with
    DirectoryPaths(tmp_path) and the model_figure_key fixture pattern from
    test_model_figure_output.py:27: graph_model.png written once,
    graph_state.png rewritten per tick, nothing written with the key off or
    absent, and a raising plotter leaves the run intact.
  6. Evidence + docs: docs/images/model_figures/make_figures.py gains ep_model(),
    ep_state_stale(), ep_state_reverted() (short real EP runs with the failure
    doubles copied into the script) → docs/images/model_figures/ep_{model,state_stale,state_reverted}.png;
    docs/features/graphical.md gains a "Seeing the EP run" section using the
    raw.githubusercontent image pattern.

Minimum shippable = steps 1–5 plus the three PNGs; the step-6 prose may follow.

Key Files

  • autofit/model_figure/ — the phase 1–4 package this one extends (layout.py,
    render.py supply the reused Style / measure_text / PALETTE / save).
  • autofit/non_linear/paths/directory.py:32-49 — _model_figure_enabled, lifted
    to autofit/model_figure/config.py.
  • autofit/graphical/expectation_propagation/optimiser.py — EPOptimiser
    (:290 visualiser construction, :488 the stale condition, :607/:615 the
    visualise calls).
  • autofit/graphical/expectation_propagation/visualise.py — the hook.
  • autofit/graphical/expectation_propagation/history.py:51 — FactorHistory.history.
  • autofit/graphical/expectation_propagation/diagnostics.py:147-156 — the
    reverted_variables CSV column this overlay must equal.
  • autofit/graphical/mean_field.py:556-566 — the BAD_PROJECTION branch that is
    the only producer of a reversion.
  • test_autofit/graphical/functionality/test_factor_failure_recovery.py — the
    failure doubles used as fixtures.
  • test_autofit/graph_spec/graphical_doubles.py — hierarchical_graph().

Verification

  • Per step: targeted pytest on the new test files; black on the touched files
    only (black 25.1 reformats 263 files on main — never run it repo-wide);
    pyflakes.
  • Before ship: full pytest test_autofit (baseline 2759 passed / 2 skipped on
    main), sphinx warning count equal to docs/sphinx_warning_baseline.txt (30),
    and a human review of the three PNGs.
  • Ship via /ship_library (pending-release PR behind the Heart gate) → /prm.

Follow-ups to file at close-out

  • Optional overlays: variable values (mean ± std), message precision with
    defined signed/invalid handling, KL sparklines.
  • Phase 6 rollout: workspace expectation_propagation.py and HowToFit
    tutorial_optional_hierarchical_ep.py figures (note they need
    visualise_interval=1).

Original Prompt

Click to expand starting prompt

Model figures phase 5 — EP factor-graph view

Type: feature
Target: PyAutoFit
Repos:

  • PyAutoFit
    Themes:
  • visualization
  • graphical-ep
    Difficulty: large
    Autonomy: supervised
    Priority: normal
    Status: formalised
    Consequence: judge
    Review-minutes: 30
    Unattended: ready
    Epic: model-figures
    Phase: 5
    Filed: 2026-09-10

Phase 4 shipped 2026-09-12 — complete/2026/09/model-figures-graphical.md
(PyAutoFit#1617, autofit_workspace#153, HowToFit#51 merged); this phase is unblocked.
(Deliberately not in a Blocked-by: header: that key is graded against GitHub
refs and cannot name a Mind prompt path.)

Phase 5 of the model-figures epic. Ledger (brief, full design record, full
independent review): draft/feature/autofit/model_figures_epic.md. Phase 4
drew the teaching view; this phase draws the diagnostic one — an explicit
factor graph with the EP run's state on it. The review approved the separation:
they answer different questions and should not be one figure.

The figure

An explicit factor graph — factor nodes and variable nodes, both drawn —
plate-grouped so it survives large dataset counts, with an EP overlay.

Overlay, in the review's priority order (start with the first three; the rest
are optional detail):

  1. Factor status — converged / working / stale, from EPHistory /
    FactorHistory / Status / EPDiagnostics.
  2. Update age — how many EP iterations since this factor last successfully
    updated. A factor with zero SUCCESS updates is the STALE state the library
    now warns about (PyAutoFit#1562).
  3. Confirmed reverted updates — read the reverted_variables set
    (per-(factor, variable) tracking, PyAutoFit#1576, and present in
    ep_history.csv). Do not use Status.changed[v] is False as the
    reversion signal: "unchanged" and "reverted" are different facts requiring
    different explanations, and only reverted_variables establishes rejection.
  4. Variable mean ± std — optional detail, off by default.
  5. Message precision — optional, and only with defined handling of signed
    or invalid site precisions
    . It must not be presented casually as "how
    strongly this factor constrains the variable"; a negative or invalid site
    precision needs a stated rendering, not an accidental one.
  6. KL sparklines per factor — optional polish.

Collapsed plates must not hide failures behind an average. At large dataset
counts a collapsed plate shows status aggregates plus the exceptional
members
by name, with individual factor access available. A plate showing
"mean KL 0.02" while one member has never converged is the failure mode to
design against.

Files

  • graph_model.png beside graph.info — the static structure, written once.
  • graph_state.png — the overlay, rewritten on the visualise_interval tick.

Both gated by the same output.yaml model_figure key introduced in phase 2
(never model_graph, which gates the graphical-model text dump — see the
ledger's Trap section).

Layout engine — still open

This is the one phase where graphviz is permitted, if justified. The
containment layout that serves phases 2–4 is chosen for nesting; an explicit
factor graph is edge-dominated and rank layout may genuinely win. The
constraints that made graphviz unacceptable elsewhere still apply and must be
answered in the plan if it is chosen: the dot binary is absent locally, on the
GitHub ubuntu-24.04 runner and often on Colab, and is not pip-installable — so
a graphviz path needs a matplotlib fallback, or the figure is simply unavailable
in CI and for most users. Present both options in the plan with that cost
stated; the human decides.

Traps

  • fgm.graph rebuilds on every access and renames PriorFactors — cache it.
  • factor.name is not unique across _HierarchicalFactors; use
    factor.name_for_variable(v), never variable.label.
  • Declarative variables have plates=(); plates are inferred (phase 4's
    machinery), not read.

Acceptance

  • An EP run over a small hierarchical model produces graph_model.png and a
    sequence of graph_state.png files across visualise_interval ticks.
  • A deliberately stalled factor (zero SUCCESS updates) is visibly stale in the
    figure.
  • A run with entries in reverted_variables shows them as reverted, and a run
    with merely unchanged variables does not.
  • A collapsed plate containing one failing member names that member.

Activity

  1. Jammy2211 commented on Sep 12, 2026

    @Jammy2211
    CollaboratorAuthor

    Ship BLOCKED at the Heart readiness gate

    /ship_library ran to the readiness gate and stopped there. No PR has been
    opened.
    The branch is implemented, verified and pushed; only the gate is
    outstanding.

    Heart verdict: RED (pyauto-heart readiness --json, ts 2026-09-12T18:03:19Z)

    Exact RED reason:

    release validation FAILED (stage integrate)
    

    (Also YELLOW: workspace validation not passing (5 failed, 2 timeout,
    cloud#34099198772); manifest drift on the generated organism-map and
    front-door organ tables; profiling drift on three MGE likelihood summaries.)

    This RED is unrelated to the work on this branch — it is the standing
    release-validation integrate failure. The AUTONOMY.md corrective-PR exception
    does not apply, because this PR is not a fix scoped to that reason, and no human
    authorisation for a PR-open under RED was given within the wait window. Per the
    skill, nothing is force-shipped.

    State of the branch — ready to ship the moment the gate clears

    feature/model-figures-ep-view, 6 commits on top of 54f464d97, pushed
    (ba756b82d), working tree clean.

    • autofit/model_figure/ep/ — spec → state → presentation → layout → render
    • af.EPPlotter, the public door onto the EP factor-graph figure
    • Visualise writes graph_model.png once and graph_state.png per
      visualise_interval tick, gated by the existing output.yaml model_figure
      key (≤4-line optimiser.py diff)
    • docs/features/graphical.md → "Seeing the EP run", with three rendered figures
      built by docs/images/model_figures/make_figures.py

    API changes — additive only. New af.EPPlotter (plus the
    autofit.model_figure exports behind it); Visualise.__init__ gains an optional
    factor_graph=None and Visualise.__call__ an optional model_approx=None
    (backward compatible); _model_figure_enabled in
    autofit/non_linear/paths/directory.py is now an alias of
    autofit.model_figure.config.model_figure_enabled. Nothing removed or renamed.

    Verification — python -m pytest test_autofit/ -x: 2843 passed, 2 skipped
    (re-run at the gate, 125 s); Sphinx 30 warnings == baseline; black and
    pyflakes clean on the touched files.

    Workspace impact — option (i) new demos / follow-up. Grepping the workspaces
    for EPPlotter, graph_state.png and model_approx= returns no matches, so no
    migration is needed. Phase 6 (rollout) will add visualise_interval + the figures
    to autofit_workspace/scripts/features/expectation_propagation.py and HowToFit's
    optional hierarchical EP tutorial.

    To unblock

    Either clear the release-validation integrate RED, or authorise a PR-open under
    RED naming the reason string above — then re-run /ship_library on this task.
    Merge stays human via /prm either way.

    🤖 Generated with Claude Code

    https://claude.ai/code/session_01AmyBwcVQBrWE4jSTqdATY6

  2. added a commit that references this issue on Sep 13, 2026
  3. Jammy2211 commented on Sep 13, 2026

    @Jammy2211
    CollaboratorAuthor

    Shipped

    Merged in #1619 (6 commits, merge commit 9ad5fdfa2).

    The PR was opened 2026-09-12 22:17 under a Heart RED with explicit human authorisation — the ship-gate BLOCKED comment above is what that authorisation lifted; no PR-open comment was posted at the time, so this comment covers both.

    What shipped

    • New package autofit/model_figure/ep/ — spec.py, state.py, presentation.py, layout.py, render.py, plotter.py: the EP factor-graph view, built from the factor graph, the EP history and the model approximation.
    • autofit/model_figure/config.py lifts the _model_figure_enabled gate so both the model view and the new EP views read one switch.
    • Public door: af.EPPlotter(factor_graph, ep_history, model_approx).figure(kind="model"|"state").
    • Visualise writes graph_model.png once and graph_state.png on every visualise_interval tick, behind the model_figure key in output.yaml.
    • docs/features/graphical.md gains a "Seeing the EP run" section with three figures.

    Evidence

    • 2843 tests passed, 2 skipped.
    • Sphinx warning count 30 — equal to the baseline.
    • Tests (unittest-nojax, 3.12, 3.13) and Docs (docs-build) all green on ba756b82.

    Design notes

    • The reversion signal is status.changed[v] is False — never changed is None, which means "not yet visited".
    • A factor reads as stale when sweeps >= 1 and 0 of its updates landed.
    • Factor age comes from FactorHistory.

    Follow-ups (deferred by human decision, filed separately)

    • Optional EP overlays: mean±std, precision, KL sparklines.
    • Phase 6: roll graph_state.png out into autofit_workspace/expectation_propagation.py and the HowToFit hierarchical EP tutorial (needs visualise_interval=1).

    Rendering stays networkx + matplotlib only; graphviz was rejected as a dependency.

    Pending release: PyAutoFit (the change is merged but not yet published).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions