Repository navigation
Description
Overview
Phase 4 of the model-figures epic (ledger PyAutoMind/draft/feature/autofit/model_figures_epic.md; phases 1–3 shipped as PyAutoFit#1606, #1614 and the six phase-3 PRs closing PyAutoLens#736). The renderer already collapses a FactorGraphModel's per-dataset models into a plate, but it is not yet plate notation and it misreports hierarchical draws: the drawn Prior is the same object as the dataset model's centre, so it is emitted as a shared edge — the review's highest-priority correction. This phase adds a graphical pass in graph_spec keyed off GlobalPriorModel.factor (hyper-parameter nodes, hierarchical-draw provenance with draw edges, observed-data rows, dataset plates, hoisted shared priors, hyper/per-dataset footer accounting), fills the three "not implemented" holes (workspace graphical_models.py, HowToFit tutorial 2, docs/features/graphical.md) and ships the shared-vs-hierarchical teaching pair.
Plan
- PyAutoFit layer 1: graphical pass reading
model.factor.graphonce; one hyper node per distribution model hoisted first; drawn priors lose theirdrawn_prioroccurrence (no shared edge), gainProvenance("hierarchical-draw")and aDrawEdge; observed rows per analysis factor withdata/dataset; graphical counts. - Layer 2/3: hoisted
shared across datasetscard,N datasetsplates,centre · drawnanddata · observedpills, violet draw arrows landing on the pill, hyper/shared/per-dataset footer. - Tests over shared / per-dataset / relational / hierarchical 3-dataset graphs; evidence PNGs;
docs/features/graphical.mdholes filled. - Ship the library PR; then autofit_workspace (
features/graphical_models.pyplaceholder + hierarchical composition) and HowToFit (tutorials 2 and 4) with regenerated notebooks and navigator catalogue, behind the library-first gate.
Detailed implementation plan
Branch survey (step 4)
PyAutoFit, autofit_workspace, HowToFit: main, clean, level with origin. worktree_check_conflict fires only on PyAutoFit (remove-parallel-ep-optimiser, #1612 still open, no local worktree, EP-optimiser files only) — same disjoint-file parallel-claim waiver as phases 2–3, recorded on the row.
- Task
model-figures-graphical· branchfeature/model-figures-graphical· worktree~/Code/PyAutoLabs-wt/model-figures-graphical/(PyAutoFit now; both workspaces attached atstart_workspace). - Issue on PyAutoFit:
feat: model figures phase 4 — plate notation for graphical models.
Decisions (recommendations)
- Graphical pass lives in layer 1, keyed off
model.factor.GlobalPriorModelcarriesself.factor(theFactorGraphModel,abstract.py:225-238);GraphSpec.from_modeldetectskind == "global"+ afactorattribute and runs one graphical pass that readsgraph = model.factor.graphexactly once (it rebuilds and renamesPriorFactors per access). Nothing graphical is imported by name — duck-typed like the existingtype(analysis).Latentprobe. - Hierarchical draws become provenance + a new edge, never sharing. The
_HierarchicalFactorchildren (oneCollectionper draw, all with the samefactor.name) are replaced by ONE hyper-parameter node per distribution model (deduped bydistribution_modelobject;kind="hyper", nameHierarchicalFactor0fromfactor.name,cls_namethe distribution class, rows = its own priors, e.g.mean,sigma). Each drawn prior's occurrence at("k","drawn_prior")is removed fromoccurrences/direct_occurrencesbefore collapse (so the plate safety condition does not break the dataset plate and noSharedEdgeis emitted), and the dataset row getsProvenance("hierarchical-draw", expression="~ GaussianPrior(mean, sigma)", operands=(hyper path,))plus aDrawEdge(source_path=hyper, target_path=("i","centre"))— a fourth edge type. The row keepssampling="free"(it is still sampled). Hyper nodes are emitted first among root children (hoisted); this is the one documented exception to declaration order and applies only to the graphical view. - Observed data gets its own row. For each
AnalysisFactorwhoseanalysisexposesdataordataset(duck-typed;_HierarchicalFactor.analysisreturns itself and is skipped), the dataset card gets a synthesisedParamRow(name=<attr>, sampling="observed", provenance=Provenance("observed"), in_model_info=False); presentation stateobserved(green, distinct from grey fixed), legend "observed data", pill textdata · observed. Each dataset child node also recordsFactorInfo{name, kind ∈ analysis|hierarchical}for the path index. - Plates read as datasets. For a
globalroot the plate badge saysN datasetsand the subtitledataset 0 - 2; the plate'srepeatsline is unchanged machinery. - Shared priors are hoisted (layer 2). For a
globalroot, priors in a dataset plate'sshared_in_all(and any prior shared across all root-level dataset cards when there is no plate) move into a synthetic hoisted cardshared across datasetsdrawn above the plate; the member rows keep their white pill with a↗ sharedbadge and a blue link to the hoisted pill. Non-graphical models are untouched. - Footer accounting separates hyper-parameters.
countsgainshyper_parameters,shared_across_datasets,per_dataset,datasets; the graphical footer reads2 hyper-parameters · 1 shared across datasets · 2 per dataset × 3 datasets · 9 unique sampled scalars(the last ismodel.prior_count, unchanged as the reconciling total). - Draw links are violet with an arrowhead at the target pill, routed like shared links (gutter, anchored on top-level card edges);
Style.max_linksstill applies, with↗ HierarchicalFactor0badges as the fallback reference. - Per-search output needs no hook change:
search.fit(model=factor_graph.global_prior_model, analysis=factor_graph)already hands_save_model_infothe global model, and the graphical pass keys offmodel.factor. - Teaching pair = HowToFit tutorial 2 (shared) + tutorial 4 (hierarchical), each with its figure after
print(factor_graph.global_prior_model.info)and one paragraph on what the figure shows thatgraph.infodoes not; mirrored indocs/features/graphical.md(shared figure replaces the sentence at:144; hierarchical figure + composition under## Hierarchical Models) and in the workspace script (placeholder at:223; the prose-only "Hierarchical Models" section gains the composition + figure, no fit). HowToFit'sconfig/output.yamlis left alone (model_figureabsent = off;model_graphfalls back todefault: truethere today, noted, not changed).
High-level plan
- PyAutoFit layer 1: graphical pass (hyper nodes, draw edges, observed rows, factor info, graphical counts); layer 2: hoisted shared card, dataset plate wording, drawn/observed pills, graphical footer; layer 3: draw links with arrowheads.
- Tests over shared / per-dataset-copy / relational / hierarchical factor graphs (3 datasets), plus determinism and the catalogue tests 15–17 kept green.
- Evidence PNGs
graphical_shared.png,graphical_variable.png,graphical_hierarchical.pngfromdocs/images/model_figures/make_figures.py;docs/features/graphical.mdholes filled. ship_library→ PR (pending-release).- Workspaces:
autofit_workspace/scripts/features/graphical_models.py(+ hierarchical composition and figure), HowToFit tutorials 2 and 4, notebooks + navigator catalogue regenerated; two PRs behind the library-first gate.
Detailed plan — PyAutoFit
autofit/graph_spec.py
DrawEdge{source_path, target_path, prior_id, expression}dataclass;GraphSpec.draws: Tuple[DrawEdge, ...];FactorInfo{name, kind};ComponentNode.factor: Optional[FactorInfo];ComponentNode.kindgainshyper._Extractor.__init__:self.graph = None; if_kind(model) == "global"andgetattr(model, "factor", None)has agraphattribute →self.graph = model.factor.graph(once) andself.model_factors = list(model.factor.model_factors)(the same list the global model's children were built from, so indexi↔ child"i").- Graphical pass (run inside
build_rootafter the raw walk, before_collapse_tree): (a) for each_HierarchicalFactor(found viagraph.hierarchical_factors→hf.factors, or any model factor exposingdistribution_model+drawn_prior), collect(distribution_model, drawn_prior); (b) drop the corresponding"i"children; (c) insert one hyper node per distinct distribution model at the front of the root's children, path(factor.name,), rows from the distribution model's own priors via the ordinary_nodewalk; (d) strip the("i","drawn_prior")paths from the affected priors' occurrence tuples (_occurrences/_direct_occurrencesare computed fromall_paths_prior_tuples; filter by path prefix); (e) re-tag every dataset row whoseprior_idis a drawn prior withProvenance("hierarchical-draw", expression=f"~ {cls_name}({', '.join(hyper row names)})", operands=(dotted hyper path,))and append aDrawEdge; (f) for eachAnalysisFactorchild, setFactorInfo(name=factor.name, kind="analysis")and append the observed row whengetattr(factor.analysis, "data", None)/datasetexists. Deterministic ordering: draws sorted by dataset index. _counts:datasets(plate count of the root or number of analysis-factor children),hyper_parameters(sampled scalars on hyper nodes),shared_across_datasets(priors in the dataset plate'sshared_in_allor shared across every dataset child),per_dataset(unique sampled scalars of one dataset member minus shared),observed(observed rows).path_index: hyper nodes map to themodel.info"k"paths of the_HierarchicalFactorcollections they replace (the correspondence contract: recorded, not hidden).- Module docstring: the graphical pass, the hoist exception to declaration order, and the "draw ≠ sharing" rule.
autofit/model_figure/presentation.py, layout.py, render.py
build_presentation: whenspec.root.kind == "global": dataset plate badgeN datasets/ subtitledataset 0 - 2; hoistedshared across datasetscard built from the plate'sshared_in_all(owner pill moves there; members get↗ shared); drawn pillscentre · drawnwith badge↗ HierarchicalFactor0andLink(kind="draw"); observed pillsdata · observed; hyper cards titledHierarchicalFactor0 · GaussianPrior; footer per decision 6.Card.kindgainshyperandhoist.layout.py: routedrawlinks likeshared;render.py: violet stroke + arrowhead (FancyArrowPatchor a small triangle marker) at the target end; legend entries fordrawn from a hyper-prior/observed dataappear only when present (already the rule).
Tests
test_autofit/graph_spec/test_graphical.py: fixtures (3 datasets,_Analysis(index)withdataattribute likedocs/images/model_figures/make_figures.py:117-136; shared / per-dataset copies / relational / hierarchical viaaf.HierarchicalFactor(af.GaussianPrior, mean=..., sigma=...)+add_drawn_variable(model.centre), andreset_ids+namer.reset()liketest_autofit/graphical/info/conftest.py:12-19). Assert: hierarchical → exactly one hyper node first, NDrawEdges, zeroSharedEdgefor the drawn prior, dataset rowsprovenance.kind == "hierarchical-draw"andshared is False, dataset plate still collapses to N withcentreinvaries/independent; shared → one plate of 3,shared_in_allholds all three priors; observed rows present per analysis factor withdata, absent forNullAnalysis;graphread once (patchFactorGraphModel.graphwith a counting property); counts per decision 6;to_dictdeterministic across two builds and a subprocess; catalogue tests 15–17 andtest_determinism::test_factor_graph_extraction_is_deterministicunchanged.test_autofit/model_figure/test_graphical_presentation.py: hoisted card exists and members carry↗ shared; hierarchical figure has adrawnpill, adrawlink landing on it and no shared badge anywhere; observed pill stateobserved≠fixed; footer string per decision 6; legend lines; PNG renders ≤ 1400 px for all four fixtures.
Evidence + docs (PyAutoFit)
docs/images/model_figures/make_figures.py:graphical_shared,graphical_variable,graphical_hierarchicalbuilders (reuse_factor_graph), PNGs committed.docs/features/graphical.md: replace the sentence at:144with the shared plate figure + one paragraph (what the figure shows that the text cannot: the plate, the hoisted shared prior, the observed data node);## Hierarchical Modelsgains the tutorial-4 composition, its figure and the shared-vs-hierarchical paragraph ("the arrow means these came from a common population, not the same number"). Sphinx warnings ≤ baseline.
Detailed plan — workspaces (after the library PR opens)
autofit_workspace/scripts/features/graphical_models.py: at:223replace the placeholder sentence with prose +af.ModelPlotter(factor_graph.global_prior_model).figure()after theaf.FactorGraphModel(...)line at:233(the placeholder cell precedes the composition, so the sentence moves to a new cell after it); the__Hierarchical Models__section (:253-258) gains the tutorial-4-style composition on the same three datasets (own centre priors,af.HierarchicalFactor,add_drawn_variable,FactorGraphModel,print(...global_prior_model.info), figure, the side-by-side paragraph) without a fit. Regeneratenotebooks/features/graphical_models.ipynbonly (generate.py autofitfrom inside the workspace).HowToFit/scripts/chapter_3_graphical_models/tutorial_2_graphical_model.py: replace the:197placeholder with the figure after:217'sprint;tutorial_4_hierachical_models.py: figure after:215with the "drawn, not shared" paragraph. Regenerate the two notebooks + the navigator catalogue (generate.py howtofitfrom inside HowToFit; commit the catalogue); tutorials 2 and 4 run in HowToFit CI on every PR, so both scripts must run headless underprofile_smoke.yaml(explicit.figure()calls are unaffected byPYAUTO_SKIP_VISUALIZATION).- Tutorial prose → Opus; architect reviews.
Delegation (Opus legs, heartbeat + Monitor)
A. PyAutoFit layers 1–3 + tests + evidence PNGs + graphical.md. B. Test gate + ship_library. C. Workspace edits (both repos) + notebooks. D. ship_workspace (two PRs). Architect reviews the three PNGs after A and the tutorial prose after C.
Verification
- Serial pytest:
test_autofit/graph_spec test_autofit/model_figure test_autofit/graphical, then the full suite; black/pyflakes. - Hierarchical PNG:
centre · drawnpills with violet arrows landing on them, hyper card on top, no blue badge anywhere; shared PNG: hoistedshared across datasetscard above a3 datasetsplate; observed pills green; footer shows the hyper/shared/per-dataset split. - Both workspace scripts run headless from their worktree roots; notebooks and the HowToFit navigator catalogue regenerated; CI green (
lib-tests×3 legs + docs; workspace smoke/navigator; HowToFit full-script CI). Merge order PyAutoFit → autofit_workspace → HowToFit via/prm.
Out of scope
The EP diagnostic factor graph and overlays (phase 5), rollout to other workspaces/HowTo chapters (phase 6), reimplementing af.VisualiseGraph, HowToFit output.yaml keys, per-search hook changes, graph_info text changes.
Original Prompt
Click to expand starting prompt
Model figures phase 4 — plate notation for graphical models
Type: feature
Target: PyAutoFit
Repos:
- PyAutoFit
- autofit_workspace
- HowToFit
Themes: - visualization
- graphical-ep
Difficulty: medium
Autonomy: supervised
Priority: normal
Status: formalised
Consequence: judge
Review-minutes: 25
Unattended: ready
Epic: model-figures
Phase: 4
Filed: 2026-09-10
Phase 2 shipped 2026-09-11 — complete/2026/09/model-figures-renderer.md (PyAutoFit#1614 merged, autofit_workspace#152 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 4 of the model-figures epic. Ledger (brief, full design record, full
independent review): draft/feature/autofit/model_figures_epic.md. This phase
adds the teaching-oriented model view for graphical models — plate notation
over a FactorGraphModel. The diagnostic EP factor graph is phase 5; the
review explicitly approved keeping them separate because they answer different
questions.
The figure
Standard plate notation, drawn with the phase-2 vocabulary:
- A shared prior hoisted above the plate, drawn once, with the plate members
pointing at it. - A dashed plate
dataset i = 1…Ncontaining one collapsed component box,
whose rows carry either a shared pointer or a per-dataset free pill. - Observed data with its own encoding — shaded
data_i. Fixed model
constants and observations are different concepts and must not share the grey
pill. - Hierarchical draws are not sharing. This is the review's first and highest
priority correction. A hierarchically drawn parameter renders ascentre_i
with a "drawn" annotation, and the parent distribution's arrow ends on
that pill, not on the dataset frame and not as a shared marker.⇄ centre
says "the same parameter across datasets"; the hierarchical arrow says
"distinct centres drawn from a common distribution". They are opposite claims. - Hyper-parameters are counted separately from the per-dataset parameters
(e.g. two free hyper-parameters plus three parameters per dataset), and the
footer says so.
Plate inference
Plates are inferred, because declarative variables carry plates=() — there
is no plate information in the model to read. Infer by:
- grouping
graph.analysis_factorsby prior-model isomorphism, then - checking, per path, the actual sharing and hierarchical membership.
Matching model shape does not establish identical priors, identical analyses,
or conditional independence — the review is explicit that inference must inspect
actual sharing and hierarchical membership, not shape alone. The phase-1 plate
safety condition applies here too: a plate must preserve sharing, relations,
assertions and exceptions across members, and the figure states what the plate
repeats.
Verified primitives and traps (DESIGN §4, §6 — executed)
fgm.graphrebuilds on every access and renamesPriorFactors. Cache it
once and work from the cached object, or names will drift between reads.factor.nameis not unique across_HierarchicalFactors. Use
factor.name_for_variable(v); nevervariable.label.- Declarative variables have
plates=()— do not expect to read plates off the
graph. with_free_parametersdoes not exist on the installedaf.Model; the live
multi-dataset idiom ismodel.copy()+af.AnalysisFactor+
af.FactorGraphModel. In the fully-shared case all children of
GlobalPriorModelare the same object (id == 1for all three).CompoundPrior/ComparisonAssertionareAbstractPriorModels with
cls = floatand masquerade as components;repr()of aCompoundPrior
subclass without__str__recurses forever (compound.py:88) — neverrepr
in a label path.
Fill the two "not implemented yet" holes
Both exist today and both say, in the text, that the picture is missing:
autofit_workspace/scripts/features/graphical_models.py— "This is what our
factor graph looks like:" followed by nothing.- HowToFit
chapter_graphical_models, tutorial 2 — "visualization of graphs
not implemented yet".
Teaching examples — shared vs hierarchical
The review made this phase's pedagogical deliverable explicit: ship a pair of
worked examples that put the two side by side, because conflating them is the
single most common misreading of a plate diagram.
- Shared: one parameter, one prior object, N datasets — the arrow means
"this is literally the same number". - Hierarchical: N distinct
centre_i, each drawn from a parent
distribution whose own parameters are free — the arrow means "these came from
a common population".
Each example carries its figure, its graph.info, and one paragraph saying what
the reader should be able to see in the figure that the text does not show.
Acceptance
- Both placeholders render a figure.
- A hierarchical model's figure shows
centre_i"drawn", with the parent arrow
landing on the pill — and no shared marker anywhere on it. - A shared model's figure hoists the shared prior above the plate.
- Observed data is visually distinct from fixed constants.
- Parameter accounting in the footer separates hyper-parameters from per-dataset
parameters.
🤖 Generated with Claude Code
Activity
Jammy2211 commentedon Sep 12, 2026
Ship attempt paused at the readiness gate — 2026-09-12
Implementation for phase 4 is complete, tested and pushed; the ship did not proceed to PR-open
because
ship_librarystep 3 (vitals faculty → Heart) returned RED.Branch state (all pushed, nothing dirty)
feature/model-figures-graphical@447c00e92—test_autofit2759 passed / 2 skipped / 0 failed;black+pyflakesclean on touched files; sphinx 30 warnings ==mainbaseline (30)feature/model-figures-graphical@b85bbac—scripts/features/graphical_models.pyruns headless (exit 0), notebook regeneratedfeature/model-figures-graphical@e62ac27— chapter 3 tutorials 2 and 4 run headless (exit 0), notebooks regeneratedThe gate
pyauto-heart readiness --json(2026-09-12T17:47:15Z, verdictred, score 15) — RED reason verbatim:YELLOW reasons (context, none of them in this task's repos): workspace validation not passing
(5 failed, 2 timeout, cloud#34099198772: autolens
notebooks/multi_dataset/modeling.ipynb,autolens
scripts/multi_dataset/modeling.py, autolens_testscripts/imaging/delaunay.py, +4 more);manifest drift ×2; profiling drift ×3.
Heart RED forbids commit / push / PR-open at every autonomy level (
PyAutoBrain/AUTONOMY.md), andthis branch is not a corrective fix for the named RED reason, so the corrective-PR exception does
not apply. No PRs were opened; nothing was merged; no code was changed to make a leg pass.
To unblock (human's call)
release-integrate.ymlon PyAutoHeart with the morning'stestpypi_version+commit_shas(~75 min; the failing scripts are autolens-side), then re-run/ship_library→/ship_workspace; orapproving PR-open for this task, after which the three PRs (PyAutoFit, then autofit_workspace and
HowToFit behind the library-first merge gate) can be opened as drafted.
Merge order when it does ship: PyAutoFit → autofit_workspace → HowToFit; both workspace PRs are
pending-releaseon the unreleased PyAutoFit figure API.🤖 Generated with Claude Code
https://claude.ai/code/session_01AmyBwcVQBrWE4jSTqdATY6
Jammy2211 commentedon Sep 12, 2026
Shipped to PR-open — 2026-09-12
The human authorised opening these three
pending-releasefeature PRs on 2026-09-12 ("Open the 3 PRs"),with the readiness verdict quoted verbatim in the previous comment (red reason: "release validation
FAILED (stage integrate)" — the failing scripts are autolens / autolens_test, unrelated to this task).
PR-open only: nothing was merged, no release was triggered, and merging remains a human act via
/prm.PRs
447c00e92)b85bbac)e62ac27)All three carry the
pending-releaselabel (verified). Both workspace PRs are cross-referenced on thelibrary PR and sit behind it under the library-first merge gate — the plate-notation figure API is
unreleased, so PyAutoFit merges (and releases) first.
Merge order once CI is green
/prmPyAutoFit#1617 → autofit_workspace#153 → HowToFit#51.PyAutoMind
active.mdrow updated and pushed (0475e06c): statusPRs open (pending-release, library-first gate; opened under Heart RED with human authorisation 2026-09-12).🤖 Generated with Claude Code
https://claude.ai/code/session_01AmyBwcVQBrWE4jSTqdATY6
Jammy2211 commentedon Sep 12, 2026
Shipped
Phase 4 of the
model-figuresepic — plate notation for graphical models — merged across three repos.PRs merged (2026-09-12)
650cb88339f6b93c0ab4c52356b866f26669e82b4f121f2a64a8a7b71f87bbe715fe0c9a7a80c5263cadd7d6303fd507ddf91c0fa03d7aaf02e3d8a6What changed
af.ModelPlotternow detects graphical structure in aFactorGraphModel'sglobal_prior_modelanddraws plate notation: a dashed dataset plate badged with the dataset count, shared priors hoisted into
a card above the plate, hierarchically drawn parameters rendered as a
drawnpill fed by a violetarrow from their
HierarchicalFactorcard (a draw is not sharing), observed data as its own greenobservedpill, and a footer splitting hyper-parameters, per-dataset parameters and unique sampledscalars. Figures of non-graphical models are unchanged; no public symbol was added, removed or
re-signatured.
This filled the three "visualization not implemented" holes —
docs/features/graphical.md,autofit_workspace/scripts/features/graphical_models.py, HowToFit chapter 3 — and shipped theshared-vs-hierarchical teaching pair (HowToFit tutorials 2 and 4).
CI at merge — every run, every leg green on each head sha:
447c00e92: Tests (3.12, 3.13, nojax) + Docs — 4/4b85bbac: Smoke (3.12, 3.13, changes) + Navigator (3 legs) — 6/6e62ac27: Smoke (3 legs) + Navigator (3 legs) + Tutorials Complete — 7/7Merged in gate order (library first). Heart freeze flag clear at merge (
not frozen); the Heart REDreadiness verdict was the human-authorised gate already judged at PR-open and was not re-run.
Pending release — PyAutoFit@#1617 is merged but unpublished; the obligation is carried into the
PyAutoMind completion record and clears only on a release that actually publishes.
Closed by
/prm.