Repository navigation
Description
Overview
Phase 1 of the model-figures epic (ledger: PyAutoMind/draft/feature/autofit/model_figures_epic.md). PyAutoFit can print a model (model.info) but cannot draw one, and the one existing figure (af.VisualiseGraph) drops tuple priors and is blind to constants, instances and assertions. This phase builds the pure semantic layer every later phase renders over: a new autofit/graph_spec.py that turns any AbstractPriorModel into a nesting tree of components and parameter rows plus sharing / relation / assertion edges, with declaration order preserved, plates collapsed over find_groups, and an explicit model.info path index. It draws nothing and imports no matplotlib.
Plan
- Add
autofit/graph_spec.py: frozen dataclasses forComponentNode,ParamRow(a bag of independent properties: sampling status, sharing, dimensionality, provenance),PlateInfo, the three edge records and aGraphSpecroot with ato_dict()serialisation and apath_index. - Extract components, free/fixed/missing rows, tuple rows, relations and assertions using the primitives the design already verified (
path_instance_tuples_for_class,path_priors_tuples,all_paths_prior_tuples,gathered_assertions()), walking in declaration order and filtering out theCompoundPrior/ComparisonAssertionimpostors and theArraynoise attributes. - Implement the collapse: R1 soft plate (class tree + prior configuration, ignoring prior identity,
_labeland constant values), R2 split by cross-member shared priors, and the mandatory safety condition (sharing, relations, assertions and exceptions must match across members), grouping overfind_groupsand recording the mapping where the figure's partition is finer thanmodel.info's. - Accept an optional
analysis=and attachLatent.keys(analysis)as derived rows; carry thesolvedfield for phase 3 to fill. - Tests: one test per construct in the 18-construct catalogue, determinism (two extractions are byte-identical), and the three lens acceptance models built as structural doubles inside PyAutoFit (autofit may not import autolens) asserting the epic's counts.
- Export
GraphSpecfromautofit/__init__.py; touch nothing invisualise.py; no new dependencies, no config keys.
Detailed implementation plan
Affected Repositories
- PyAutoFit (primary, only)
Work Classification
Library
Branch Survey
| Repository | Current Branch | Dirty? |
|---|---|---|
./PyAutoFit (/home/user/pyautofit, web-github session clone) |
main @ 1b7c1c9 | clean |
Remote branches: main, claude/slowest-ci-tests-s81dza, experiment/jax-vmap-jit-ordering — none touch the mapper. No active.md entry claims PyAutoFit.
Suggested branch: feature/model-figures-graph-spec
Worktree root: ~/Code/PyAutoLabs-wt/model-figures-graph-spec/ (local-dev only; this session works in its clone)
Implementation Steps
-
autofit/graph_spec.py— data model (stdlibdataclasses,frozen=True, tuples not lists so equality and hashing are deterministic):Path = Tuple[str, ...].Provenance(kind, expression=None, operands=())withkind ∈ config-default | user-prior | relation | assertion | hierarchical-draw | observed | latent.expressionis the defining expression for relations (e.g.sigma * 2);operandsare operand paths (or operand names where an operand is not in the tree).ParamRow(name, path, sampling, prior_id, occurrences, dimensionality, components, provenance, value, prior_cls_name):sampling ∈ free | fixed | solved | missing;free←Prior,fixed←Constant/float/int leaf,missing← aConfigExceptioninstance in the tree (exactly whatmodel.infoprints as "Prior Missing"),solved← carried only (phase 3 supplies domain rules; asolved_paths=argument lets a caller mark them now).occurrences= every path the samePriorobject appears at (fromall_paths_prior_tuples);sharedis a propertylen(occurrences) > 1, never a separate state.dimensionality ∈ scalar | tuple; a tuple row carriescomponents= oneParamRowperTuplePriorslot (centre_0,centre_1), each with its own sampling status, so partially fixed / partially shared tuples are a mixed state, never flattened.prior_cls_nameandvalueare semantic facts (legend material), not presentation.
PlateInfo(count, member_paths, representative_key, repeats, shared_in_all, varies_by_member):representative_keyis thefind_groupskey ("0 - 29");repeatsis the one-line statement of what the plate repeats;shared_in_allthe prior ids present in every member;varies_by_memberthe constant paths whose values differ.ComponentNode(path, name, cls_name, kind, obj_id, rows, children, plate)withkind ∈ model | collection | global;nameis the exact attribute spelling / list index string.SharedEdge(prior_id, occurrences),RelationEdge(target_path, expression, operand_paths, prior_id),AssertionEdge(op, left, right, name).GraphSpec(root, shared, relations, assertions, path_index, counts)withcounts = {unique_sampled_scalars, fixed_leaf_slots, shared_priors, missing, components_raw, components}andto_dict()(insertion-ordered, JSON-serialisable) — the determinism tests comparejson.dumps(spec.to_dict()).- Entry points:
GraphSpec.from_model(model, analysis=None, collapse=True, solved_paths=())and module functiongraph_spec_from(...).
-
Extraction walk (
_extract_tree):- Components:
model.path_instance_tuples_for_class((Model, Collection), ignore_children=False), keeping walk order (=__dict__insertion order = declaration order). Drop any instance that is aCompoundPrior/ModifiedPrior/ComparisonAssertion(they subclassAbstractPriorModelwithcls = float) and anyModelwhoseclsisint/float(R7:Model(int)wrappers such asDelaunay.pixelsbecome a row on their owner).GlobalPriorModelgetskind = global. - Rows per component, in declaration order, from that component's own direct attributes:
direct_prior_tuples(scalars),direct_tuple_priors(tuple rows —TuplePrioris NOT anAbstractPriorModel, so it must be read here, not from the component walk),direct_instance_tuplesfiltered toConstant/float/int (fixed),ConfigExceptionvalues (missing), plain-object instance leaves (kind = instancerow on the owner, with the injectedid), andArray'sshape/indiceson the skip-list. - Sharing:
all_paths_prior_tuples→prior.id → occurrences; every row for that prior lists all occurrences; oneSharedEdgeper prior with >1 occurrence. - Relations:
path_instance_tuples_for_class((CompoundPrior, ModifiedPrior)); build the expression from a symbol table (SumPrior +,MultiplePrior *,DivisionPrior /,FloorDivPrior //,ModPrior %,PowerPrior **,NegativePrior,AbsolutePrior,Log,Log10) recursing through nested compounds; operand names from_left_name/_right_name/_prior_name, resolved to paths viapath_for_priorwhen the operand is a prior in the tree. Never callstr()/repr()on a compound —CompoundPrior.__repr__recurses (compound.py:87). - Assertions:
model.gathered_assertions()(the method), oneAssertionEdgeeach; operands resolved as above; excluded from the tree and frompath_index(they are not inmodel.info). - Latents: if
analysisis given,type(analysis).Latent.keys(analysis)→ split on.→ derived rows (sampling = solved,provenance = latent) attached under the component the prefix names. path_index: element id → tuple ofmodel.infopaths (grouped paths where a plate collapses them, usingfind_groupson the member paths). Every added annotation (solved,missing, latent) is flaggedin_model_info = False.
- Components:
-
Collapse (
_collapse_siblings, applied perCollection/Modelchild list whencollapse=True):- R1 signature per member: recursive (cls tree, per-slot sampling status, prior class + prior arguments, tuple structure, child signatures) — excluding prior
id,_labeland constant values. - R2: for each candidate plate, compute per member the set of prior ids shared with other members of the plate; drop ids present in every member (non-discriminating, e.g. the MGE centre); partition members by the remaining set (basis-0's
ell_compsvs basis-1's). Priors shared only inside one member never split. - Safety condition: a member whose relation set, assertion set or external-sharing profile (sharing with something outside the plate) differs from the others leaves the plate and stands alone.
- Each surviving plate becomes one
ComponentNode(the first member in declaration order as representative) withPlateInfo;representative_keycomes fromfind_groupsover the member paths so the figure's0 - 29matchesmodel.info's.
- R1 signature per member: recursive (cls tree, per-slot sampling status, prior class + prior arguments, tuple structure, child signatures) — excluding prior
-
Ordering contract, in the module docstring: visual order = the order of
path_instance_tuples_for_class(..., ignore_children=True), which is the order ofmodel.info's parameter-detail section (the structural summary,parameterization, is the other candidate; it is rejected because it reorders throughfind_groups(limit=0)). -
Public surface:
from .graph_spec import GraphSpec, graph_spec_frominautofit/__init__.py.autofit/visualise.pyuntouched. -
Tests —
test_autofit/graph_spec/with aconftest.pythat resetsaf.ModelObject._idsandaf.Prior._ids(astest_visualise.pydoes) so ids are reproducible:test_catalogue.py: one test per construct 1–18 (see the prompt's list), each asserting spec fields, not pictures. Construct 2 asserts the known gap (indistinguishable from 1) explicitly. Construct 13 supplies explicit priors. Construct 18 asserts absence withoutanalysis=and presence with a stub analysis declaringLatent.keys.test_collapse.py: R1, R2 (cross-member vs in-all vs inside-one-member), the safety condition (relation / assertion / external sharing ejects a member), fixed tuple constants inside a plate still produce a row,Model(int)becomes a row.test_determinism.py: extract twice → identicaljson.dumps(to_dict()); rebuild the model after an id reset → identical.test_acceptance_lens.py: the three lens models as structural doubles (plain classes with the same constructor signatures and explicit priors mirroring the lens config — PyAutoFit may not import autolens, perAGENTS.md): (a) 6 components / 13 rows; (b) 11 components (12 before R7), two ×30 plates split onell_comps, shared multiplicities 60, 60, 30, 30, 30, 30, 16 unique sampled scalars; (e) 15 components (16 before R7), 41 unique sampled scalars, 22 shared priors, 291 fixed leaf slots, fixed per-galaxy centre tuples present,areas_factorinmissing. Phase 3 re-runs the same assertions against the real classes in PyAutoLens.- Run:
python -m pytest test_autofit/graph_spec test_autofit/mapper -n auto; CI is the Heartlib-tests.ymlmatrix (3.12 + 3.13).
Key trade-offs
- Doubles vs real lens classes in the acceptance tests: forced by the autofit → autonerves-only import rule; the counts are pinned in the tests so a double that drifts from the real composition fails loudly, and phase 3 holds the real-class check.
- Frozen dataclasses +
to_dict()rather than a JSON schema: enough for byte-identical determinism and for phase 2 to consume; a schema can be added when a second consumer appears. solvedcarried, not computed: phase 1 has no domain knowledge; the field and asolved_paths=hook exist so phase 3 adds rules without touching the data model.
Key Files
autofit/graph_spec.py— new module (data model, extraction, collapse, path index)autofit/__init__.py— exportGraphSpec,graph_spec_fromautofit/mapper/prior_model/abstract.py— read-only:path_priors_tuples,all_paths_prior_tuples,gathered_assertions(),info()(ordering reference)autofit/mapper/model.py— read-only:path_instance_tuples_for_class(cls, ignore_class, ignore_children)autofit/mapper/prior_model/representative.py— reusefind_groupsautofit/mapper/prior/arithmetic/compound.py,assertion.py— operand names, the__repr__recursion to avoidautofit/non_linear/analysis/latent.py—Latent.keys(analysis)test_autofit/graph_spec/{conftest,test_catalogue,test_collapse,test_determinism,test_acceptance_lens}.py— new
Original Prompt
Click to expand starting prompt
Model figures phase 1 — semantic extraction
Type: feature
Target: PyAutoFit
Repos:
- PyAutoFit
Themes: - visualization
Difficulty: large
Autonomy: supervised
Priority: normal
Status: formalised
Consequence: judge
Review-minutes: 30
Unattended: ready
Epic: model-figures
Phase: 1
Filed: 2026-09-10
Phase 1 of the model-figures epic. Ledger (read it for the brief, the visual
vocabulary, the full design record and the independent review):
draft/feature/autofit/model_figures_epic.md. This phase draws nothing — it
builds the pure semantic layer everything later renders over.
What to build
A new module @PyAutoFit/autofit/graph_spec.py — pure extraction, no
drawing, no matplotlib import, no dependency beyond autofit/mapper/. It
turns any af.AbstractPriorModel (and, in phase 4, a FactorGraphModel) into
a nesting tree:
ComponentNode{path, name, cls_name, obj_id, rows, children, multiplicity}—
one node perModel/Collection/GlobalPriorModel.pathis the full
tuple path in the model;obj_idis the Python object identity (this is how a
component shared across datasets is detected: the sameobj.idat several
paths).ParamRow— one row per parameter slot, carrying separate properties, not
one exclusivekind(see below).- Edge records:
SharedEdge,RelationEdge,AssertionEdge.
The three-layer split is a hard requirement of the review: semantic
extraction (this phase) / presentation transformation (grouping, omission,
ordering, detail level) / layout and rendering (phase 2). Nothing in this
module may know about pixels, fonts or colours.
ParamRow is a bag of properties, not a single kind
The original design proposed kind ∈ free|fixed|relation|instance|pointer. The
review rejected that as too exclusive — a shared prior is still sampled, a
tuple is still free. Model each of these independently:
| Property | Values | Source |
|---|---|---|
| sampling status | free | fixed | solved | missing |
free = a Prior in the tree; fixed = a Constant; solved = a quantity the fit determines but that is absent from the model (linear light profile intensity, pixelization pixels, al.ps.PointSolved centre) — phase 3 supplies the domain rules, phase 1 only carries the field; missing = a required configuration value that is unset (e.g. areas_factor), which must never look like absence from the model. |
| sharing | prior identity (prior.id) + the list of path occurrences |
keep occurrences separately from object identity — the review is explicit that a shared prior is a property of a sampled row, not a separate state. |
| dimensionality | scalar | 2-D tuple (and the component scalars it holds) | so pill counts reconcile with the footer's "16 unique sampled scalars". A partially fixed or partially shared tuple must be representable as a mixed state, not flattened. |
| provenance | config-default | user-prior (best effort) | relation(expression) | assertion(operands) | hierarchical-draw | observed |
relations carry their defining expression (= sigma × 2); assertions carry both operand paths; a hierarchical draw is centre_i "drawn from", never a sharing marker; observed data gets its own encoding, distinct from fixed. |
name is the exact attribute spelling, preserved verbatim. Full paths stay on
the record even when the renderer shows only the name.
Ordering
Declaration order is preserved end to end. The review's point 4: in the
prototype shear floated above mass because the layout was free-form
masonry, while model.info orders bulge, mass, shear. The spec emits
children and rows in declaration order and the renderer is forbidden from
reordering them for packing. model.info itself uses different orders in its
structural summary versus its parameter-detail section — pick one, document the
choice in the module docstring, and be consistent.
Collapse rules R1/R2, with the safety condition
- R1 soft plate. Sibling
Models collapse into one plate when their class
tree and prior configuration match — ignoring prior identity, prior
_label, and constant values. - R2 shared split. Split a plate by the partition its cross-member shared
priors induce. A prior appearing in every member (the MGE centre) does not
discriminate; one appearing in a subset (basis-0'sell_comps) does, giving
Gaussian ×30+Gaussian ×30. A prior shared only inside one member never
splits the plate — without this qualifier the 8 extra galaxies of the group
model fall back to 8 separate boxes. - Safety condition (Codex review point 7, mandatory). A plate must preserve
sharing, relations, assertions and exceptions across its members, not
merely class tree + prior configuration. A repeated component is not
necessarily an independent statistical replicate. Any member that differs in
any of those four respects leaves the plate and is drawn on its own. The spec
records what the plate repeats, as a field, so the renderer can say it.
Reuse — do not re-invent — find_groups in
@PyAutoFit/autofit/mapper/prior_model/representative.py. It is the collapse
primitive model.info already uses to print 0 - 29 / 30 - 59, and the
figure must group over it rather than inventing a second, divergent notion of
sameness. Where the figure's partition is necessarily finer than
find_groups' (the figure partitions by component, model.info groups per
parameter), record the mapping rather than hiding it — phase 3 documents it.
The model.info correspondence contract
Not "line for line". The contract, in the module docstring and in the tests:
Every displayed model element resolves to its corresponding path or grouped
paths inmodel.info; every omission and every added annotation (solved,
missing) is explicit.
Emit a lightweight path index alongside the spec so a static PNG stays
navigable: element → path(s) in model.info.
Verified extraction primitives (DESIGN §5, all executed)
path_instance_tuples_for_class((Model, Collection), ignore_children=False)—
the component nodes.path_priors_tuples— free parameter slots.all_paths_prior_tuples— groups a prior with all its paths; this is the
sharing detector.path_instance_tuples_for_class((Constant, float), ignore_class=Prior)—
fixed leaves.path_instance_tuples_for_class((CompoundPrior, ModifiedPrior))— relations.gathered_assertions()— assertions (a method, whileassertionsis a
property; easy to mis-call).find_groups(mapper/prior_model/representative.py) — the collapse.
Traps for the implementer (DESIGN §6, all verified by execution)
TuplePrioris not anAbstractPriorModel: any walk over
direct_prior_tuples+direct_prior_model_tuplessilently loses every tuple
parameter — i.e. everycentrein every lens model.CompoundPrior/ComparisonAssertionareAbstractPriorModels with
cls = float, so they masquerade as components and must be filtered out of
the component walk. Their operand names come from a stack-frame
retrieve_name()(cp._left_name/cp._right_name), which is why the names
aresm,sc,xin a hand-built relation butself/otherwhen built by
ArithmeticMixin.__add__.repr()of aCompoundPriorsubclass without__str__recurses forever
(compound.py:88). Neverreprin a label path. (Filed separately as
draft/bug/autofit/assertion_repr_recurses_forever.md.)- Prior
_labelcarries a per-instance counter (einstein_radius2vs
einstein_radius4), which defeats naive equality when detecting plates. fgm.graphrebuilds on every access and renamesPriorFactors — cache it.
factor.nameis not unique across_HierarchicalFactors; use
factor.name_for_variable(v), nevervariable.label. (Phase 4 leans on this;
phase 1 only needs the tree.)with_free_parametersdoes not exist on the installedaf.Model; the live
multi-dataset idiom ismodel.copy()+af.AnalysisFactor+
af.FactorGraphModel.Model(int)wrappers (e.g.Delaunay.pixels) need special-casing: plain
int/float attributes are rows on their owner, never components.- Fixed tuple constants inside a plate produced no row at all in the
prototype (the extra-galaxy centres vanished). This is an acceptance case, not
a nice-to-have — their absence reads as absence from the model.
Tests — the 18-construct catalogue
One test per construct, each asserting the extracted spec, not a picture:
af.Model(Cls)with default priors.- Overridden prior (
m.centre = af.UniformPrior(...)) — indistinguishable
from (1) without a config diff; assert that, and record it as a known gap. - Fixed float (
m.centre = 0.0,af.Model(Cls, centre=0.0)) → wrapped in
Constant, absent fromprior_tuples, present inmodel.info. - Shared prior (
m.a.x = m.b.x) — the samePriorobject at two paths. - Relation (
m.centre = m.norm + m.sigma) → aSumPrior/CompoundPrior
withcls == float; assert the expression string and both operands. - Assertion (
m.add_assertion(m.sigma > 5.0)) — inmodel._assertions, not in
the tree and not inmodel.info. - Tuple parameter →
TuplePriorholdingcentre_0,centre_1; paths are
('centre','centre_0'); one row with a 2-D cue. af.Collection(a=…, b=…)— children as named attributes.af.Collection([m0, m1, m2])— children named"0","1","2".- Nested Collections.
- Multi-level
af.Model(Cls, gaussian_list=[Model, Model])— the list becomes
a childCollectionat('gaussian_list',). - Instance leaf (
af.Collection(a=Model, b=instance)) — a raw Python object
with an injectedid;model.infoshowsGaussian (N=0). af.Model(function)—model.clsis the function, socls.__name__works;
note that config priors crash (filed as
draft/bug/autofit/model_function_cannot_resolve_config_priors.md), so the
test supplies explicit priors.af.Array(shape=…, prior=…)— flat priorsprior_0_0,prior_0_1, … plus
shape/indicesnoise attributes that need a skip-list.FactorGraphModel.global_prior_model, fully shared — all children the
same object (id == 1for all three).- Per-dataset free parameters (
model.copy()+ reassignment) — shared params
keep oneprior.id, free ones get new ids. - Cross-dataset relation (
sigma = sm*x + sc) — nested
SumPrior(MultiplePrior(sm, x), sc); assert the operand-name provenance. - Latent variables — not part of the model at all; they live on
Analysis.Latent(autofit/non_linear/analysis/latent.py), and
Latent.keys(analysis)returns dot-separated names ("gaussian.fwhm").
The spec must accept an optionalanalysis=and attach derived rows;
without it, assert they are simply absent.
Acceptance — the three lens models
Beyond the catalogue, the spec must be asserted against the real lens models.
These are the epic's acceptance cases and the review moved them into the
phase 1–2 gate rather than leaving them to phase 3:
- (a) simple lens — Sersic + Isothermal + ExternalShear + Sersic source.
8 raw nodes / 48 info lines → 6 component boxes, 13 rows. - (b) MGE 2×30 + pixelized source — 73 raw nodes / 178 info lines. Must
yield 11 components (12 before R7 drops theModel(int)), two ×30
plates split onell_comps(never one merged ×60), 6 shared priors with
multiplicities 60, 60, 30, 30, 30, 30, and 16 unique sampled scalars. - (e) group scale, 8 extra galaxies — 166 raw nodes / 418 info lines → 15
components (16 before R7), 41 unique sampled scalars, 22 shared priors, 291
fixed leaf slots. Must render fixed per-galaxy centre tuples (the
prototype dropped them) and an unsetareas_factorin themissing
state — not "solved", not absent.
Determinism is part of acceptance: run each extraction twice and assert
byte-identical spec output, including ordering.
Out of scope
Drawing anything (phase 2), lens domain semantics (phase 3), plates over a
factor graph (phase 4), EP overlays (phase 5). af.VisualiseGraph (pyvis)
stays exactly where it is — do not touch or delete it in this phase.
🤖 Generated with Claude Code
Activity
feat: graph_spec collapse rules R1/R2 + lens acceptance cases (model-…
fix: graph_spec skips unset None attributes; black-format the new files
Jammy2211 commentedon Sep 10, 2026
Library PR created: #1606 (
feature/model-figures-graph-spec, labelledpending-release).API changes: additive only —
af.GraphSpec/af.graph_spec_fromand the record dataclasses inautofit.graph_spec. No workspace script is affected; nothing to migrate. Next:/prmonce CI is green (merge stays human).One thing to know before phase 2/3: the three lens acceptance cases are structural doubles of today's
autolens_workspacescripts (autofit may not import autolens). The MGE case meets every epic invariant (11 boxes, two ×30 plates split onell_comps, shared multiplicities 60/60/30/30/30/30, 16 unique sampled scalars,areas_factor=missing). The group-scale case holds its structural invariant (8 extra galaxies → one plate with per-galaxy fixedcentretuples) but today'sgroup/modeling.pycomposition is far smaller than the prototype's model (33 raw nodes vs 166, no shared priors vs 22), so its numeric counts are pinned as measured with# epic targetcomments. Phase 3 re-runs the assertions on the real classes in PyAutoLens.Generated by Claude Code
Jammy2211 commentedon Sep 11, 2026
Shipped
Merged #1606 into
main(merge commite331e33), CI green on 3.12 / 3.13 / no-jax / docs.What landed:
autofit/graph_spec.py— the semantic extraction layer (af.GraphSpec/af.graph_spec_from): declaration-ordered component tree,ParamRowas independent properties, shared / relation / assertion edges, themodel.infopath index, collapse rules R1 / R2 with the safety condition overfind_groups, and 52 tests including the 18-construct catalogue and the lens acceptance doubles. Purely additive, no drawing,VisualiseGraphuntouched. Labelledpending-release; phase 2 (model_figures_2_renderer) is unblocked.Generated by Claude Code