Repository navigation
Description
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 newaf.EPPlotter. - Structure: read
EPOptimiser.factor_graphonce into immutable tuples;
infer plates at the factor level (groupingAnalysisFactors by signature and
_HierarchicalFactors by name); hidePriorFactors by default. - Overlay: derive per-factor
status(stale / reverting / working /
converged),updates,sweepsandagefromFactorHistory, plus the
confirmed reverted (factor, variable) pairs — the same fact the
reverted_variablescolumn ofep_history.csvcarries. - 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, thennx.multipartite_layout; coordinates
rounded so the figure is byte-deterministic. - Hook:
Visualisegains the factor graph and writesgraph_model.pngonce
andgraph_state.pngon everyvisualise_intervaltick, behind the existing
output.yamlmodel_figurekey and the usual blanketexceptso a figure
failure can never break an EP run.optimiser.pychanges 3 lines. - Ship with evidence: three real-EP PNGs committed under
docs/images/model_figures/
and a "Seeing the EP run" section indocs/features/graphical.md.
Human decisions taken 2026-09-12 (recorded here so a fresh session need not re-ask)
- 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 thedotbinary is absent locally, absent on the
GitHububuntu-24.04runner 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.1is
already a hard dependency (pyproject.toml:56). - 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. - 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 (removeParallelEPOptimiser). refactor(ep): remove ParallelEPOptimiser and its tests (#1611) #1612
merged at 19:29 on 2026-09-12, so this task branches from amainthat
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, neverfgm.graph/
model_approx.factor_graph(those rebuild and renamePriorFactors on every
access;EPHistoryis keyed by the optimiser's own factor objects). - Plates are inferred at factor level — phase 4's
_collapse_siblingsneeds a
GlobalPriorModel, which is unreachable here.AnalysisFactors group by
signature (class name, dotted prior paths, cls names);_HierarchicalFactors
group byfactor.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)(skipNone;
_HierarchicalFactor→distribution_model.name) — nevervariable.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 lastupdatedentry (derived — it is stored nowhere).status ∈ {stale, reverting, working, converged}:staleiff
sweeps >= 1 and updates == 0(the complement of the condition at
optimiser.py:488);convergedviaEPHistory's own convergence test;
revertingiff the latest status has reverted variables; elseworking.reverted_variable_keys= names withstatus.changed[v] is Falsewhere
changed is not None— identical to thereverted_variablesCSV column
(diagnostics.py:147-156), which is produced only on the BAD_PROJECTION branch
(mean_field.py:556-566).changed is Noneand an all-Truemask are never
reversion. Implemented as a private_reverted_names(status)instate.py
(not lifted intodiagnostics.py, whose test refactor(ep): remove ParallelEPOptimiser and its tests (#1611) #1612 touched), and pinned equal
to a realep_history.csvby a test. ReadStatusattributes 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 byfactor.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 unlessfactor_graphis set and
model_figure_enabled()and notskip_visualization(). It writes
graph_model.pngonce (first call) andgraph_state.pngon every call; the
whole body sits under the blanketexcept Exception → logger.infopattern of
directory.py:527-537.optimiser.py::290passfactor_graph=self.factor_graph;:607and:615
becomeself.visualiser(model_approx).stochastic.pyis 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
ep/spec.py+ themodel_figure/config.pylift +
test_autofit/model_figure/ep/{__init__,conftest,test_spec}.py(~320 new lines).
conftestmirrorstest_autofit/model_figure/conftest.py(reset
ModelObject._ids,Prior._ids,namer); fixture from
test_autofit/graph_spec/graphical_doubles.py::hierarchical_graph().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 theep_history.csvcross-check.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() == 0on the hierarchical fixture; declaration
order kept) andtest_determinism.py(layout dict equal across builds and a
fresh interpreter; PNG bytes equal) (~520).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).- Hook:
visualise.py(~70) + the 3 lines inoptimiser.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 themodel_figure_keyfixture pattern from
test_model_figure_output.py:27:graph_model.pngwritten once,
graph_state.pngrewritten per tick, nothing written with the key off or
absent, and a raising plotter leaves the run intact. - Evidence + docs:
docs/images/model_figures/make_figures.pygainsep_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.mdgains a "Seeing the EP run" section using the
raw.githubusercontentimage 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.pysupply the reusedStyle/measure_text/PALETTE/save).autofit/non_linear/paths/directory.py:32-49—_model_figure_enabled, lifted
toautofit/model_figure/config.py.autofit/graphical/expectation_propagation/optimiser.py—EPOptimiser
(:290visualiser construction,:488the stale condition,:607/:615the
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_variablesCSV 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;
blackon the touched files
only (black 25.1 reformats 263 files onmain— never run it repo-wide);
pyflakes. - Before ship: full
pytest test_autofit(baseline 2759 passed / 2 skipped on
main), sphinx warning count equal todocs/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.pyand HowToFit
tutorial_optional_hierarchical_ep.pyfigures (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):
- Factor status — converged / working / stale, from
EPHistory/
FactorHistory/Status/EPDiagnostics. - 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). - Confirmed reverted updates — read the
reverted_variablesset
(per-(factor, variable) tracking, PyAutoFit#1576, and present in
ep_history.csv). Do not useStatus.changed[v] is Falseas the
reversion signal: "unchanged" and "reverted" are different facts requiring
different explanations, and onlyreverted_variablesestablishes rejection. - Variable
mean ± std— optional detail, off by default. - 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. - 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.pngbesidegraph.info— the static structure, written once.graph_state.png— the overlay, rewritten on thevisualise_intervaltick.
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.graphrebuilds on every access and renamesPriorFactors — cache it.factor.nameis not unique across_HierarchicalFactors; use
factor.name_for_variable(v), nevervariable.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.pngand a
sequence ofgraph_state.pngfiles acrossvisualise_intervalticks. - A deliberately stalled factor (zero SUCCESS updates) is visibly stale in the
figure. - A run with entries in
reverted_variablesshows them as reverted, and a run
with merely unchanged variables does not. - A collapsed plate containing one failing member names that member.
Activity
Jammy2211 commentedon Sep 12, 2026
Ship BLOCKED at the Heart readiness gate
/ship_libraryran to the readiness gate and stopped there. No PR has beenopened. The branch is implemented, verified and pushed; only the gate is
outstanding.
Heart verdict: RED (
pyauto-heart readiness --json, ts2026-09-12T18:03:19Z)Exact RED reason:
(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.mdcorrective-PR exceptiondoes 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 of54f464d97, pushed(
ba756b82d), working tree clean.autofit/model_figure/ep/—spec→state→presentation→layout→renderaf.EPPlotter, the public door onto the EP factor-graph figureVisualisewritesgraph_model.pngonce andgraph_state.pngpervisualise_intervaltick, gated by the existingoutput.yamlmodel_figurekey (≤4-line
optimiser.pydiff)docs/features/graphical.md→ "Seeing the EP run", with three rendered figuresbuilt by
docs/images/model_figures/make_figures.pyAPI changes — additive only. New
af.EPPlotter(plus theautofit.model_figureexports behind it);Visualise.__init__gains an optionalfactor_graph=NoneandVisualise.__call__an optionalmodel_approx=None(backward compatible);
_model_figure_enabledinautofit/non_linear/paths/directory.pyis now an alias ofautofit.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;
blackandpyflakesclean on the touched files.Workspace impact — option (i) new demos / follow-up. Grepping the workspaces
for
EPPlotter,graph_state.pngandmodel_approx=returns no matches, so nomigration is needed. Phase 6 (rollout) will add
visualise_interval+ the figuresto
autofit_workspace/scripts/features/expectation_propagation.pyand HowToFit'soptional 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_libraryon this task.Merge stays human via
/prmeither way.🤖 Generated with Claude Code
https://claude.ai/code/session_01AmyBwcVQBrWE4jSTqdATY6
Merge pull request #1619 from PyAutoLabs/feature/model-figures-ep-view
Jammy2211 commentedon Sep 13, 2026
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
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.pylifts the_model_figure_enabledgate so both the model view and the new EP views read one switch.af.EPPlotter(factor_graph, ep_history, model_approx).figure(kind="model"|"state").Visualisewritesgraph_model.pngonce andgraph_state.pngon everyvisualise_intervaltick, behind themodel_figurekey inoutput.yaml.docs/features/graphical.mdgains a "Seeing the EP run" section with three figures.Evidence
ba756b82.Design notes
status.changed[v] is False— neverchanged is None, which means "not yet visited".sweeps >= 1and 0 of its updates landed.FactorHistory.Follow-ups (deferred by human decision, filed separately)
graph_state.pngout intoautofit_workspace/expectation_propagation.pyand the HowToFit hierarchical EP tutorial (needsvisualise_interval=1).Rendering stays networkx + matplotlib only; graphviz was rejected as a dependency.
Pending release: PyAutoFit (the change is merged but not yet published).