Repository navigation
Description
Overview
Phase 2 of the model-figures epic (PyAutoMind ledger draft/feature/autofit/model_figures_epic.md). Phase 1 (#1606) shipped autofit/graph_spec.py, the pure semantic tree of a model. This phase draws it: a pure-matplotlib containment figure ("the map") that is the visual twin of model.info ("the legend"), scaling from the toy Gaussian to MGE 2×30 + pixelized and group-scale lens models without shrinking text. It adds af.ModelPlotter, an opt-in model.png beside model.info behind a new output.yaml key model_figure (default false, read strictly), the acceptance renders as committed evidence, and figures in the PyAutoFit cookbooks (docs pages here, scripts + notebooks in a follow-up autofit_workspace PR).
Plan
- Add
autofit/model_figure/(presentation → measured layout → matplotlib drawing) over the phase-1GraphSpec, exposed asaf.ModelPlotter(model).figure(...); zero new dependencies, matplotlib imported inside functions only. - Write
model.pngnext tomodel.infofromDirectoryPaths._save_model_info, gated by a NEW strictoutput.yamlkeymodel_figure: false(absent key = off; never reusemodel_graph); a render failure is logged, never raised. - Tests over the phase-1 catalogue models and the three lens doubles: vocabulary rules, width budget, fixed text size, declaration order, determinism (layout dict + PNG bytes), file output and config gate.
- Commit the acceptance renders under
docs/images/model_figures/with the script that regenerates them; embed them indocs/cookbooks/{model,multi_level_model,multiple_datasets}.md. - Ship the library PR first; then the autofit_workspace follow-up (figure calls in the three cookbook scripts, regenerated notebooks,
model_figure: falseinconfig/output.yaml).
Detailed implementation plan
Branch survey (step 4)
| Repo | Branch | State | Claim |
|---|---|---|---|
| PyAutoFit | main = origin/main (has graph_spec) | clean | CONFLICT: remove-parallel-ep-optimiser (PR #1612, awaiting-merge, web session, no local worktree; touches only graphical/expectation_propagation/optimiser.py, graphical/README.md, AGENTS.md, 3 EP tests) |
| autofit_workspace | main = origin/main | clean | none |
File sets are disjoint (this task adds a new package + touches paths/directory.py, config/output.yaml, __init__.py, docs). Recommendation: parallel worktree, recorded as a parallel-claim: block on the active.md entry (precedent: memory feedback_repo_claim_conflict_allows_parallel_worktrees). Heart is YELLOW (workspace validation, profiling drift, no rehearsal) — none of the reasons touch autofit; ship gate will need the usual acknowledgement.
- Task name:
model-figures-renderer· branchfeature/model-figures-renderer· worktree~/Code/PyAutoLabs-wt/model-figures-renderer/(PyAutoFit now, autofit_workspace added bystart_workspace). - Issue title:
feat: model figures phase 2 — matplotlib renderer + model_figure output.
Decisions raised by the prompt (recommendations; approve or override)
- API name.
af.ModelPlotter(model, analysis=None, solved_paths=())with.figure(...). Nomodel.figure()alias: the model object stays drawing-free and the plotter noun matchesaplt.*Plotteracross the organism. (Prompt's open decision 1.) - Signature follows autofit's existing plot convention, not the prompt's sketch:
figure(path=None, filename="model", format="show", detail="names", collapse=True, max_depth=None, show_fixed=True, width=14.0)—format ∈ show|png|svg|pdfexactly likeautofit/non_linear/plot/plot_util.py:output_figure; returns theFigure.pathis a directory (as everywhere else in autofit). model_figurekey is read strictly.autonerves.output.should_outputfalls back tooutput.yaml'sdefault:(true in every workspace) when a key is absent, so a new key that is only in the library default would silently turn the figure ON in the ~15 configs that lack it. The hook reads the key with an explicit absent→False, so only configs that opt in write the file. The key is added (asfalse) to the library default,test_autofit/config, andautofit_workspace/config/output.yaml; the other 7 full-list workspace/assistant configs are left to phase 6 (rollout), which is safe under strict reading.- Per-search file is
model.pngonly (SVG/PDF via the API), written next tomodel.info, never raising: a figure failure is logged and swallowed so it can never kill a fit.
High-level plan
- Add a new package
autofit/model_figure/implementing layers 2 and 3 overGraphSpec: presentation (cards/pills/plates/detail/omission) → measured layout (Agg text metrics, width budget, row wrapping, declaration order) → matplotlib drawing (PNG/SVG/PDF), plus theaf.ModelPlotterAPI. - Gate a
model.pngsibling ofmodel.infobehind a new strictoutput.yamlkeymodel_figure: falseinDirectoryPaths._save_model_info. - Tests: layout/vocabulary tests over the phase-1 catalogue models and the three lens doubles, width-budget and fixed-text-size invariants, determinism (layout dict + PNG bytes), file-output and config-gate tests, and the graph_spec matplotlib-purity test kept green.
- Commit the acceptance renders as evidence under
docs/images/model_figures/with the small script that regenerates them, and embed them in the three PyAutoFit cookbook docs pages. ship_library(Opus) → PR; thenstart_workspace/ship_workspace(Opus): figure calls in the threeautofit_workspacecookbook scripts, notebooks regenerated, config key added.
Detailed plan — library (PyAutoFit, worktree)
New package autofit/model_figure/
__init__.py exports ModelPlotter. matplotlib is imported inside functions only (the autofit plotting convention, and it keeps import autofit.graph_spec matplotlib-free for test_determinism.py::test_importing_graph_spec_does_not_import_matplotlib).
presentation.py — layer 2 (no matplotlib). Card/Pill/Constraint/Link frozen dataclasses + build_presentation(spec, detail, max_depth, show_fixed) -> Presentation. Rules, each a small function so they are unit-testable:
- Component →
Card{title="attr · ClassName", kind model|collection|global|plate, subtitle, pills, children, badge, key}. Collections are frames (title = attribute name); root frame is dropped when it adds no branching (review nit). Plates: dashed frame, badge "N components", subtitlePlateInfo.representative_key(0 - 29) and therepeatsline. - Row →
Pill{text, state, dim2d, badge, key}withstate ∈ free|fixed|fixed-varies|relation|solved|missing|observed|drawn: white=free, grey=fixed, grey+"fixed · varies by member" when the dotted row path is inPlateInfo.varies_by_member, dashed=solved (legend "solved during fitting"), red-outlined=missing, cream with the expression text= sigma × 2.0forProvenance.kind == "relation".dimensionality == "tuple"→2Dtag; tuple components with differing states expand intoname₀/name₁pills (mixed state), never flattened.sharedrows keep the free/fixed state and add a blue badge: the first occurrence in visual order is the owner (shared across groupwhen every occurrence lies inside one plate orshared_in_all, elseshared ×k), later occurrences get a↗ owner.pathbadge and aLink. Independent repeated priors (same config, distinctprior_id) inside a plate are labelledindependent(fromrepeats). redshiftexception: a fixed scalar row namedredshifton amodelcard becomes the card subtitleredshift = 0.5; a free redshift stays a pill.detail="priors": pill text gains the prior summary (U(0, 100),N(0.5, 0.1),LogU(…), value for fixed) fromprior_cls_name/value— reuse the stringsmodel.infoalready prints (autofit/text/formatter.py,Prior.__str__) rather than reformatting.show_fixed=False: fixed pills dropped, footer gains "M fixed parameters hidden".max_depth: subtree folded into one row… N components / M priors.- Assertions →
Constraint{text="sigma > 5.0", left, right}boxes placed in the card of the operands' common ancestor: a compact label with both operand paths, no edges. Relations: expression on the pill and a thin orangeLinkto each operand path. - Legend (one line, only states present) and footer from
spec.counts:16 unique sampled scalars · 62 fixed leaf slots · 6 shared priors (unique variables) · 2 plateswith an explicit note when hidden elements are excluded. - Every card/pill carries the
path_indexkey so the picture stays navigable.
layout.py — layer 3a (measurement + placement). measure(presentation, style) -> LayoutTree using a scratch Agg canvas (matplotlib.backends.backend_agg.FigureCanvasAgg + Text.get_window_extent(renderer)) so metrics are backend-independent. Bottom-up: pill sizes → pill flow-wrap inside a card's content width (max card width = budget minus nesting padding) → card size → children stacked vertically in declaration order → top-level frames laid left→right and wrapped onto new rows at the width budget (reading order = declaration order, never masonry). Fixed font sizes from a Style dataclass (header 9 pt bold, pill 8 pt, footer 7.5 pt, three tints, padding shrinking per level, a right-hand gutter column reserved for links). Output positions in inches; figure size derived from content; DPI 100 so width=14.0 ⇒ ≤1400 px. LayoutTree.to_dict() is the determinism artefact.
render.py — layer 3b (drawing). draw(layout, style) -> Figure: one axes, equal aspect, inverted y, axis off; FancyBboxPatch for cards/pills/plates (dashed for plates and solved), text via ax.text, links routed orthogonally through the gutter (Line2D), legend + footer text. save(fig, path, filename, format) reuses output_figure's branching (show|png|svg|pdf, plt.close).
plotter.py. ModelPlotter.__init__(model, analysis=None, solved_paths=()) builds the spec lazily via GraphSpec.from_model; .figure(...) = presentation → layout → render → save/return. af.ModelPlotter exported from autofit/__init__.py next to GraphSpec.
Per-search hook — autofit/non_linear/paths/directory.py:471-503
After the model.graph block in _save_model_info: if _model_figure_enabled() (reads conf.instance["output"]["model_figure"], KeyError → False) and not test_mode.skip_visualization(): ModelPlotter(model).figure(path=self.output_path, filename="model", format="png") inside try/except Exception → logger.info (mirrors plot_util.log_plot_exception's intent). Delete the dead VisualiseGraph import + commented block at :369-371? No — prompt says leave VisualiseGraph untouched; only the comment block is left as is.
Config
autofit/config/output.yaml: appendmodel_figure: falsewith a comment ("model.png: the model figure besidemodel.info— opt-in until the phase-3 acceptance renders pass; absent key = off").test_autofit/config/output.yaml:model_figure: false.- No new dependencies; matplotlib stays unpinned (no API newer than 3.7 is used).
Tests — test_autofit/model_figure/
Module-level matplotlib.use("Agg") (the existing convention in test_autofit/non_linear/plot/*). Reuse test_autofit/graph_spec/lens_doubles.py (simple_lens_model, mge_model, group_model) and the catalogue constructions from test_catalogue.py; reset_ids fixture from test_autofit/graph_spec/conftest.py.
test_presentation.py: one test per vocabulary rule above (free/fixed/varies/shared owner+ref/relation expression/assertion label/2D/mixed tuple/missing/redshift subtitle/hidden count/max_depth fold/plate badge wording/footer wording).test_layout.py: width never exceeds budget for all acceptance models; top-level frames wrap; declaration order preserved (x/y monotone by index); font sizes identical between toy Gaussian and group-scale layouts; padding decreases with depth.test_acceptance_figures.py: (a) simple lens 6 cards; (b) MGE 11 cards, two plates badged30 components, footer contains16 unique sampled scalars; (e) group: per-galaxy fixedcentrepills present (fixed · varies by member),areas_factorpill inmissingstate; toy Gaussian; shared+relation+assertion composite renders all three encodings.test_determinism.py: layoutto_dict()byte-identical across two builds and across a subprocess; PNG bytes identical across two saves in-process.test_output.py:figure(format="png"|"svg"|"pdf")writes the file,format="show"returns a Figure without saving;_save_model_infowritesmodel.pngonly whenmodel_figure: true(monkeypatched config), never raises when rendering fails (inject a failing plotter), and is skipped when the key is absent.
Evidence + docs (library)
docs/images/model_figures/—make_figures.py(imports the test doubles + cookbook-shaped models, writes the PNGs atwidth=14) and its outputs:simple_lens.png,mge_pixelized.png,group_scale.png,gaussian.png,gaussian_collection.png,multi_level.png,multiple_datasets_shared.png,multiple_datasets_relation.png,composite_shared_relation_assertion.png. Committed as the acceptance evidence.docs/cookbooks/model.md,multi_level_model.md,multiple_datasets.md: a short "Model figure" paragraph after the correspondingmodel.infoblock with the MyST{image}directive and raw URLhttps://raw.githubusercontent.com/PyAutoLabs/PyAutoFit/main/docs/images/model_figures/<name>.png(:width: 600, real:alt:) — the pattern ofdocs/overview/python_api.md:292. Only reference files that exist (thecorner.pngdangling-reference trap).docs/api/autosummary entry forModelPlotterif the api index lists plot helpers; Sphinx warning count must not regress againstdocs/sphinx_warning_baseline.txt.
Detailed plan — workspace (autofit_workspace, after the library PR opens)
scripts/cookbooks/model.py: after themodel.infoprints at Model Customization (:233), Tuple Parameters (:288), Collection customization/assertion (:497) and Extensible (:582): a two-sentence prose cell ("the figure is the map,model.infothe legend…") +af.ModelPlotter(model).figure().scripts/cookbooks/multi_level_model.py: after:172and:251.scripts/cookbooks/multiple_datasets.py: after eachprint(factor_graph.global_prior_model.info)(:189, :336, :409) —af.ModelPlotter(factor_graph.global_prior_model).figure(); the relational one is the flagship.config/output.yaml:model_graph-style block addingmodel_figure: false.- Regenerate the three notebooks (
PYTHONPATH=../PyAutoHands/autohands python3 ../PyAutoHands/autohands/generate.py autofit, perautofit_workspace/AGENTS.md:89-107) and commit them with the scripts. Smoke-run the three scripts headless (MPLCONFIGDIR=/tmp/matplotlib). - Prose is tutorial prose → Opus (tutorial-prose split).
Delegation plan (Opus subagents, one per coherent phase, progress files + Monitor)
- Leg A — core:
presentation.py,layout.py,render.py,plotter.py,__init__export,test_presentation/test_layout/test_acceptance_figures/test_determinism. Iterates on the acceptance PNGs until the vocabulary checklist in the prompt is met; returns the PNG paths for the human/architect to eyeball. - Leg B — hook + config + evidence + docs:
directory.pyhook,output.yamlkeys,test_output.py,docs/images/model_figures/make_figures.py+ PNGs, cookbook docs pages, docs build check. - Leg C —
ship_library(tests, commit, push, PR with pre-drafted body). - Leg D —
start_workspace/ship_workspace(cookbook scripts + notebooks + config, smoke, PR behind the library-first gate).
Architect reviews the rendered PNGs between A and B (visual acceptance is a judgment call), and reviews prose in D.
Verification
source activate.sh && pytest test_autofit/model_figure test_autofit/graph_specgreen serially (no xdist), plus the full suite before ship.python -c "import autofit.graph_spec, sys; assert 'matplotlib' not in sys.modules"still holds.- All committed PNGs ≤ 1400 px wide; identical font sizes across cases (asserted in tests).
model_figure: truein a scratch config + aaf.DynestyStatictoy fit writesmodel.pngnext tomodel.info; default config writes none.- Docs build (
docs.yml) warning count ≤ baseline; the three cookbook scripts run headless end to end and their notebooks regenerate. - CI: PyAutoFit
lib-tests3.12/3.13 + no-jax leg green before the library PR is judged; workspace PR waits on the library merge (library-first gate).
Out of scope (unchanged from the prompt)
Lens domain semantics / solved_paths rules (phase 3), factor-graph plates (4), EP overlay (5), rollout of the config key and figures to other workspaces/HowTos (6), any change to af.VisualiseGraph, model.figure() alias.
Original Prompt
Click to expand starting prompt
Model figures phase 2 — matplotlib renderer
Type: feature
Target: PyAutoFit
Repos:
- PyAutoFit
- autofit_workspace
Themes: - visualization
Difficulty: large
Autonomy: supervised
Priority: normal
Status: formalised
Consequence: judge
Review-minutes: 30
Unattended: ready
Epic: model-figures
Phase: 2
Filed: 2026-09-10
Phase 1 shipped 2026-09-11 — complete/2026/09/model-figures-graph-spec.md (PyAutoFit#1606 merged); this phase is unblocked.
(Kept out of the Blocked-by: header deliberately: that key is graded against
GitHub refs and cannot name a Mind prompt path.)
Phase 2 of the model-figures epic. Ledger (brief, full design record, full
independent review): draft/feature/autofit/model_figures_epic.md. This phase
draws the figure, in pure matplotlib, over the phase-1 spec.
The renderer
A MatplotlibRenderer consuming the phase-1 GraphSpec. Zero new
dependencies. graphviz is explicitly not adopted: the dot binary is absent
locally, on the GitHub ubuntu-24.04 runner and often on Colab, is not
pip-installable, and its rank layout is wasted on a containment figure. (Phase 5
may revisit it for the edge-heavy EP graph; phases 2–4 may not.)
Containment layout:
- Measure bottom-up, place top-down. Measure text with
Text.get_window_extent— the prototype's width estimator was 11 % short on
bold headers and the figure clipped. - A width budget that wraps. Top-level frames wrap onto new rows when the
budget is exhausted; the un-budgeted group-scale figure came out 3574 px wide. - Declaration order beats packing. Never reorder children to fill space —
the prototype floatedshearabovemasswhilemodel.infosays
bulge, mass, shear, forcing the reader to choose between reading across and
reading down. - Fixed text size; collapse, never shrink. Scalability comes from collapsing
content, not from scaling the whole figure down. Padding decreases per
nesting level. At most three tint levels — boundaries, indentation and
labels carry hierarchy; tint only assists. - Outputs PNG and SVG (PDF if free).
Visual vocabulary (v2, as amended by the review)
Name-first pills inside white component cards. States must stay mutually
distinguishable: free, fixed, shared, relation, solved, drawn,
missing, observed.
- free → white pill, name only.
- fixed → grey pill. Shown by default (review point 4): fixed values
explain model structure, especially fixed centres and widths. Hiding them is
allowed but must print a visible hidden-count ("63 fixed parameters
hidden"). - shared is a property, not a state (review point 3): a shared prior is
still sampled, so it stays a white pill plus a small blue badge and a
link to its owner. The owner's badge reads "shared across group" — never
×30, which means something else. - plate badge reads "N components" (
30 components), because×30on a
plate and×30on a parameter meant two different things and newcomers could
not tell them apart. - per-member constant reads "fixed · varies by member" — a single grey
pill otherwise suggests one common fixed value. - independent repeated priors are marked as such (distinct prior objects,
identical configuration) and never confused with sharing. - solved → dashed pill, with legend wording "solved during fitting" (not
"solved", which reads as a completed fit or a known answer). Emitted only from
verified domain semantics, which arrive in phase 3. - missing → its own state for unset required configuration (
areas_factor).
Absence from the picture is not acceptable; it reads as absence from the model. - 2-D cue on tuples —
centreandell_compseach conceal two scalars, so
a small2Dannotation explains why counting pills does not reproduce the
footer count. Partially fixed or partially shared tuples expand or show a
mixed state. - relation → the pill shows its defining expression (
= sigma × 2).
Prior limits are optional detail; the expression is central and is the one
permitted piece of numeric detail on the map. - assertion → a compact constraint label carrying both operand paths,
visually distinct from dependency arrows. Long orange routes past several
junctions are not acceptable. - redshift exception → when fixed, render as
redshift = 0.5under the
galaxy header. A free redshift keeps the ordinary sampled-parameter pill. - A one-line legend (the prototype's universal legend was disproportionate),
and a footer with defined counts: prefer "16 unique sampled scalars" over
an unexplained "16 free"; state whether "shared" counts unique shared
variables or repeated references, and whether totals include hidden elements.
Minor fixes carried from the review: give cross-links a dedicated gutter (the
blue connector grazed a plate boundary); remove redundant outer framing that
adds no branching information; strengthen contrast on tiny muted labels and
footers; explain class-family header colours or keep them strictly decorative
(phase 3 decides); drop the short header stems, which read as partial wiring
when enclosure already shows ownership.
API
Proposed, mirroring the *Plotter convention used across the organism:
af.ModelPlotter(model).figure(
path=None, detail="names"|"priors", collapse=True,
max_depth=None, show_fixed=True,
)
detail="names" is the default map; detail="priors" adds the legend's
content onto the map for a single-component read. max_depth folds a subtree
into one row (… N components / M priors); collapse=False expands plates.
A model.figure() alias may be added at plan time if the human prefers it —
this is design open decision 1 and is not settled; raise it in the plan.
Per-search output
Write model.png beside model.info via DirectoryPaths._save_model_info,
gated behind a NEW output.yaml key model_figure, default false.
Do not reuse model_graph. That key was deliberately set default-false on
2026-05-15 (complete/2026/05/disable-model-graph.md, PyAutoFit#1264) to stop an
empty file being written for every non-graphical fit, and it gates the
graphical-model text model.graph / graph_info, not any image. See the
ledger's "Trap" section. model_figure stays false until the phase-3 acceptance
renders pass; adding it means adding model_figure: false to every workspace
config/output.yaml, as the 2026-05 task had to.
Leave af.VisualiseGraph (pyvis) in place as the interactive HTML extra. It may
later be reimplemented over the spec or deprecated; not in this phase.
Documentation deliverables
- Figures in the PyAutoFit cookbooks:
autofit_workspace/scripts/cookbooks/model.py,
multi_level_model.py,multiple_datasets.py. - Docs pages
@PyAutoFit/docs/cookbooks/*.md, with the PNGs committed under
docs/images/and referenced by raw URL — the patternoverview_3_features.md
already uses.
Acceptance
- The three lens acceptance figures render truthfully and their renders are
committed as evidence: (a) simple lens; (b) MGE 2×30 + pixelized — 11
components, two ×30 plates split onell_comps, footer "16 unique sampled
scalars"; (e) group scale — fixed per-galaxy centre tuples rendered, unset
areas_factorin themissingstate. - The toy Gaussian from the PyAutoFit cookbooks renders.
- A shared / relation / assertion composite model renders with all three
encodings simultaneously legible. - Deterministic output: same model → same figure, twice.
- No figure exceeds the width budget; text size is unchanged between the
smallest and largest acceptance case.
🤖 Generated with Claude Code
Activity
Jammy2211 commentedon Sep 11, 2026
Library PR Created
pending-release)API changes: added
af.ModelPlotter(model).figure(...)(newautofit.model_figurepackage) and a new default-offoutput.yamlkeymodel_figure(read strictly: absent → off). No existing symbol removed, renamed or changed.Gate: full
test_autofit2714 passed / 2 skipped (serial, worktree), black + pyflakes clean, Sphinx warnings 30 = baseline. Heart YELLOW (autolens workspace validation, profiling drift, no rehearsal — none touch PyAutoFit) acknowledged by the human.Next:
/start_workspace(linked mode) →autofit_workspacecookbook figure calls inmodel.py,multi_level_model.py,multiple_datasets.py, regenerated notebooks,model_figure: falseinconfig/output.yaml. Workspace PR merges behind the library-first gate; workspace CI runs on the same-named PyAutoFit branch.Jammy2211 commentedon Sep 11, 2026
Workspace PR Created
pending-release, cross-referenced on PyAutoFit#1614)Cookbook figure calls (
model.py×4,multi_level_model.py×2,multiple_datasets.py×3), regenerated notebooks,model_figure: falseinconfig/output.yaml. All three scripts ran headless end to end in the task worktree against the library branch.Close-out:
/prm— library PR #1614 first (CI: docs, 3.12, 3.13, no-jax), then autofit_workspace#152 behind the library-first gate; workspace CI runs on the same-named PyAutoFit branch. Phase 3 (draft/feature/autolens/model_figures_3_lens_cookbook.md) and phase 4 unblock on merge.Merge pull request #1614 from PyAutoLabs/feature/model-figures-renderer
Jammy2211 commentedon Sep 11, 2026
Shipped
pending-release)pending-release)af.ModelPlotter(model).figure(...)(newautofit/model_figure/package: presentation → measured layout → matplotlib drawing over the phase-1GraphSpec), opt-inmodel.pngbesidemodel.infobehind the new strictoutput.yamlkeymodel_figure(default false), 85 tests, 11 acceptance renders underdocs/images/model_figures/, figures in the three PyAutoFit cookbook docs pages and the three autofit_workspace cookbooks (+ notebooks, + config key).Epic
model-figures: phase 2 of 6 done; phase 3 (draft/feature/autolens/model_figures_3_lens_cookbook.md) and phase 4 are unblocked. The per-search figure stays opt-in until phase 3's acceptance renders on the real PyAutoLens models pass.