Skip to content

feat: model figures phase 4 — plate notation for graphical models #1616

Closed

Description

@Jammy2211

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.graph once; one hyper node per distribution model hoisted first; drawn priors lose their drawn_prior occurrence (no shared edge), gain Provenance("hierarchical-draw") and a DrawEdge; observed rows per analysis factor with data/dataset; graphical counts.
  • Layer 2/3: hoisted shared across datasets card, N datasets plates, centre · drawn and data · observed pills, 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.md holes filled.
  • Ship the library PR; then autofit_workspace (features/graphical_models.py placeholder + 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 · branch feature/model-figures-graphical · worktree ~/Code/PyAutoLabs-wt/model-figures-graphical/ (PyAutoFit now; both workspaces attached at start_workspace).
  • Issue on PyAutoFit: feat: model figures phase 4 — plate notation for graphical models.

Decisions (recommendations)

  1. Graphical pass lives in layer 1, keyed off model.factor. GlobalPriorModel carries self.factor (the FactorGraphModel, abstract.py:225-238); GraphSpec.from_model detects kind == "global" + a factor attribute and runs one graphical pass that reads graph = model.factor.graph exactly once (it rebuilds and renames PriorFactors per access). Nothing graphical is imported by name — duck-typed like the existing type(analysis).Latent probe.
  2. Hierarchical draws become provenance + a new edge, never sharing. The _HierarchicalFactor children (one Collection per draw, all with the same factor.name) are replaced by ONE hyper-parameter node per distribution model (deduped by distribution_model object; kind="hyper", name HierarchicalFactor0 from factor.name, cls_name the distribution class, rows = its own priors, e.g. mean, sigma). Each drawn prior's occurrence at ("k","drawn_prior") is removed from occurrences/direct_occurrences before collapse (so the plate safety condition does not break the dataset plate and no SharedEdge is emitted), and the dataset row gets Provenance("hierarchical-draw", expression="~ GaussianPrior(mean, sigma)", operands=(hyper path,)) plus a DrawEdge(source_path=hyper, target_path=("i","centre")) — a fourth edge type. The row keeps sampling="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.
  3. Observed data gets its own row. For each AnalysisFactor whose analysis exposes data or dataset (duck-typed; _HierarchicalFactor.analysis returns itself and is skipped), the dataset card gets a synthesised ParamRow(name=<attr>, sampling="observed", provenance=Provenance("observed"), in_model_info=False); presentation state observed (green, distinct from grey fixed), legend "observed data", pill text data · observed. Each dataset child node also records FactorInfo{name, kind ∈ analysis|hierarchical} for the path index.
  4. Plates read as datasets. For a global root the plate badge says N datasets and the subtitle dataset 0 - 2; the plate's repeats line is unchanged machinery.
  5. Shared priors are hoisted (layer 2). For a global root, priors in a dataset plate's shared_in_all (and any prior shared across all root-level dataset cards when there is no plate) move into a synthetic hoisted card shared across datasets drawn above the plate; the member rows keep their white pill with a ↗ shared badge and a blue link to the hoisted pill. Non-graphical models are untouched.
  6. Footer accounting separates hyper-parameters. counts gains hyper_parameters, shared_across_datasets, per_dataset, datasets; the graphical footer reads 2 hyper-parameters · 1 shared across datasets · 2 per dataset × 3 datasets · 9 unique sampled scalars (the last is model.prior_count, unchanged as the reconciling total).
  7. Draw links are violet with an arrowhead at the target pill, routed like shared links (gutter, anchored on top-level card edges); Style.max_links still applies, with ↗ HierarchicalFactor0 badges as the fallback reference.
  8. Per-search output needs no hook change: search.fit(model=factor_graph.global_prior_model, analysis=factor_graph) already hands _save_model_info the global model, and the graphical pass keys off model.factor.
  9. 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 that graph.info does not; mirrored in docs/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's config/output.yaml is left alone (model_figure absent = off; model_graph falls back to default: true there today, noted, not changed).

High-level plan

  1. 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.
  2. Tests over shared / per-dataset-copy / relational / hierarchical factor graphs (3 datasets), plus determinism and the catalogue tests 15–17 kept green.
  3. Evidence PNGs graphical_shared.png, graphical_variable.png, graphical_hierarchical.png from docs/images/model_figures/make_figures.py; docs/features/graphical.md holes filled.
  4. ship_library → PR (pending-release).
  5. 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.kind gains hyper.
  • _Extractor.__init__: self.graph = None; if _kind(model) == "global" and getattr(model, "factor", None) has a graph attribute → self.graph = model.factor.graph (once) and self.model_factors = list(model.factor.model_factors) (the same list the global model's children were built from, so index i ↔ child "i").
  • Graphical pass (run inside build_root after the raw walk, before _collapse_tree): (a) for each _HierarchicalFactor (found via graph.hierarchical_factors → hf.factors, or any model factor exposing distribution_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 _node walk; (d) strip the ("i","drawn_prior") paths from the affected priors' occurrence tuples (_occurrences/_direct_occurrences are computed from all_paths_prior_tuples; filter by path prefix); (e) re-tag every dataset row whose prior_id is a drawn prior with Provenance("hierarchical-draw", expression=f"~ {cls_name}({', '.join(hyper row names)})", operands=(dotted hyper path,)) and append a DrawEdge; (f) for each AnalysisFactor child, set FactorInfo(name=factor.name, kind="analysis") and append the observed row when getattr(factor.analysis, "data", None) / dataset exists. 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's shared_in_all or 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 the model.info "k" paths of the _HierarchicalFactor collections 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: when spec.root.kind == "global": dataset plate badge N datasets / subtitle dataset 0 - 2; hoisted shared across datasets card built from the plate's shared_in_all (owner pill moves there; members get ↗ shared); drawn pills centre · drawn with badge ↗ HierarchicalFactor0 and Link(kind="draw"); observed pills data · observed; hyper cards titled HierarchicalFactor0 · GaussianPrior; footer per decision 6. Card.kind gains hyper and hoist.
  • layout.py: route draw links like shared; render.py: violet stroke + arrowhead (FancyArrowPatch or a small triangle marker) at the target end; legend entries for drawn from a hyper-prior / observed data appear only when present (already the rule).

Tests

  • test_autofit/graph_spec/test_graphical.py: fixtures (3 datasets, _Analysis(index) with data attribute like docs/images/model_figures/make_figures.py:117-136; shared / per-dataset copies / relational / hierarchical via af.HierarchicalFactor(af.GaussianPrior, mean=..., sigma=...) + add_drawn_variable(model.centre), and reset_ids + namer.reset() like test_autofit/graphical/info/conftest.py:12-19). Assert: hierarchical → exactly one hyper node first, N DrawEdges, zero SharedEdge for the drawn prior, dataset rows provenance.kind == "hierarchical-draw" and shared is False, dataset plate still collapses to N with centre in varies/independent; shared → one plate of 3, shared_in_all holds all three priors; observed rows present per analysis factor with data, absent for NullAnalysis; graph read once (patch FactorGraphModel.graph with a counting property); counts per decision 6; to_dict deterministic across two builds and a subprocess; catalogue tests 15–17 and test_determinism::test_factor_graph_extraction_is_deterministic unchanged.
  • test_autofit/model_figure/test_graphical_presentation.py: hoisted card exists and members carry ↗ shared; hierarchical figure has a drawn pill, a draw link landing on it and no shared badge anywhere; observed pill state observed ≠ 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_hierarchical builders (reuse _factor_graph), PNGs committed.
  • docs/features/graphical.md: replace the sentence at :144 with 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 Models gains 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 :223 replace the placeholder sentence with prose + af.ModelPlotter(factor_graph.global_prior_model).figure() after the af.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. Regenerate notebooks/features/graphical_models.ipynb only (generate.py autofit from inside the workspace).
  • HowToFit/scripts/chapter_3_graphical_models/tutorial_2_graphical_model.py: replace the :197 placeholder with the figure after :217's print; tutorial_4_hierachical_models.py: figure after :215 with the "drawn, not shared" paragraph. Regenerate the two notebooks + the navigator catalogue (generate.py howtofit from inside HowToFit; commit the catalogue); tutorials 2 and 4 run in HowToFit CI on every PR, so both scripts must run headless under profile_smoke.yaml (explicit .figure() calls are unaffected by PYAUTO_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 · drawn pills with violet arrows landing on them, hyper card on top, no blue badge anywhere; shared PNG: hoisted shared across datasets card above a 3 datasets plate; 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…N containing 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 as centre_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:

  1. grouping graph.analysis_factors by prior-model isomorphism, then
  2. 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.graph rebuilds on every access and renames PriorFactors. Cache it
    once and work from the cached object, or names will drift between reads.
  • factor.name is not unique across _HierarchicalFactors. Use
    factor.name_for_variable(v); never variable.label.
  • Declarative variables have plates=() — do not expect to read plates off the
    graph.
  • with_free_parameters does not exist on the installed af.Model; the live
    multi-dataset idiom is model.copy() + af.AnalysisFactor +
    af.FactorGraphModel. In the fully-shared case all children of
    GlobalPriorModel are the same object (id == 1 for all three).
  • CompoundPrior / ComparisonAssertion are AbstractPriorModels with
    cls = float and masquerade as components; repr() of a CompoundPrior
    subclass without __str__ recurses forever (compound.py:88) — never repr
    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:

  1. autofit_workspace/scripts/features/graphical_models.py — "This is what our
    factor graph looks like:" followed by nothing.
  2. 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

https://claude.ai/code/session_0178yLU9v19GtACcRPFggjGa

Activity

  1. Jammy2211 commented on Sep 12, 2026

    @Jammy2211
    CollaboratorAuthor

    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_library step 3 (vitals faculty → Heart) returned RED.

    Branch state (all pushed, nothing dirty)

    • PyAutoFit feature/model-figures-graphical @ 447c00e92 — test_autofit 2759 passed / 2 skipped / 0 failed; black + pyflakes clean on touched files; sphinx 30 warnings == main baseline (30)
    • autofit_workspace feature/model-figures-graphical @ b85bbac — scripts/features/graphical_models.py runs headless (exit 0), notebook regenerated
    • HowToFit feature/model-figures-graphical @ e62ac27 — chapter 3 tutorials 2 and 4 run headless (exit 0), notebooks regenerated

    The gate

    pyauto-heart readiness --json (2026-09-12T17:47:15Z, verdict red, score 15) — RED reason verbatim:

    release validation FAILED (stage integrate)

    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_test scripts/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), and
    this 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)

    1. Clear the RED — re-dispatch release-integrate.yml on PyAutoHeart with the morning's
      testpypi_version + commit_shas (~75 min; the failing scripts are autolens-side), then re-run
      /ship_library → /ship_workspace; or
    2. Authorize explicitly — a contemporaneous comment on this issue quoting the RED reason above and
      approving 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-release on the unreleased PyAutoFit figure API.

    🤖 Generated with Claude Code

    https://claude.ai/code/session_01AmyBwcVQBrWE4jSTqdATY6

  2. Jammy2211 commented on Sep 12, 2026

    @Jammy2211
    CollaboratorAuthor

    Shipped to PR-open — 2026-09-12

    The human authorised opening these three pending-release feature 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

    All three carry the pending-release label (verified). Both workspace PRs are cross-referenced on the
    library 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

    /prm PyAutoFit#1617 → autofit_workspace#153 → HowToFit#51.

    PyAutoMind active.md row updated and pushed (0475e06c): status PRs 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

  3. Jammy2211 commented on Sep 12, 2026

    @Jammy2211
    CollaboratorAuthor

    Shipped

    Phase 4 of the model-figures epic — plate notation for graphical models — merged across three repos.

    PRs merged (2026-09-12)

    What changed
    af.ModelPlotter now detects graphical structure in a FactorGraphModel's global_prior_model and
    draws 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 drawn pill fed by a violet
    arrow from their HierarchicalFactor card (a draw is not sharing), observed data as its own green
    observed pill, and a footer splitting hyper-parameters, per-dataset parameters and unique sampled
    scalars. 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 the
    shared-vs-hierarchical teaching pair (HowToFit tutorials 2 and 4).

    CI at merge — every run, every leg green on each head sha:

    • PyAutoFit 447c00e92: Tests (3.12, 3.13, nojax) + Docs — 4/4
    • autofit_workspace b85bbac: Smoke (3.12, 3.13, changes) + Navigator (3 legs) — 6/6
    • HowToFit e62ac27: Smoke (3 legs) + Navigator (3 legs) + Tutorials Complete — 7/7

    Merged in gate order (library first). Heart freeze flag clear at merge (not frozen); the Heart RED
    readiness 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.

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