Skip to content

feat: graph_spec — semantic model extraction (model-figures phase 1) #1605

Closed

Description

@Jammy2211

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 for ComponentNode, ParamRow (a bag of independent properties: sampling status, sharing, dimensionality, provenance), PlateInfo, the three edge records and a GraphSpec root with a to_dict() serialisation and a path_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 the CompoundPrior / ComparisonAssertion impostors and the Array noise attributes.
  • Implement the collapse: R1 soft plate (class tree + prior configuration, ignoring prior identity, _label and constant values), R2 split by cross-member shared priors, and the mandatory safety condition (sharing, relations, assertions and exceptions must match across members), grouping over find_groups and recording the mapping where the figure's partition is finer than model.info's.
  • Accept an optional analysis= and attach Latent.keys(analysis) as derived rows; carry the solved field 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 GraphSpec from autofit/__init__.py; touch nothing in visualise.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

  1. autofit/graph_spec.py — data model (stdlib dataclasses, frozen=True, tuples not lists so equality and hashing are deterministic):

    • Path = Tuple[str, ...].
    • Provenance(kind, expression=None, operands=()) with kind ∈ config-default | user-prior | relation | assertion | hierarchical-draw | observed | latent. expression is the defining expression for relations (e.g. sigma * 2); operands are 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 ← a ConfigException instance in the tree (exactly what model.info prints as "Prior Missing"), solved ← carried only (phase 3 supplies domain rules; a solved_paths= argument lets a caller mark them now).
      • occurrences = every path the same Prior object appears at (from all_paths_prior_tuples); shared is a property len(occurrences) > 1, never a separate state.
      • dimensionality ∈ scalar | tuple; a tuple row carries components = one ParamRow per TuplePrior slot (centre_0, centre_1), each with its own sampling status, so partially fixed / partially shared tuples are a mixed state, never flattened.
      • prior_cls_name and value are semantic facts (legend material), not presentation.
    • PlateInfo(count, member_paths, representative_key, repeats, shared_in_all, varies_by_member): representative_key is the find_groups key ("0 - 29"); repeats is the one-line statement of what the plate repeats; shared_in_all the prior ids present in every member; varies_by_member the constant paths whose values differ.
    • ComponentNode(path, name, cls_name, kind, obj_id, rows, children, plate) with kind ∈ model | collection | global; name is 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) with counts = {unique_sampled_scalars, fixed_leaf_slots, shared_priors, missing, components_raw, components} and to_dict() (insertion-ordered, JSON-serialisable) — the determinism tests compare json.dumps(spec.to_dict()).
    • Entry points: GraphSpec.from_model(model, analysis=None, collapse=True, solved_paths=()) and module function graph_spec_from(...).
  2. 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 a CompoundPrior / ModifiedPrior / ComparisonAssertion (they subclass AbstractPriorModel with cls = float) and any Model whose cls is int/float (R7: Model(int) wrappers such as Delaunay.pixels become a row on their owner). GlobalPriorModel gets kind = global.
    • Rows per component, in declaration order, from that component's own direct attributes: direct_prior_tuples (scalars), direct_tuple_priors (tuple rows — TuplePrior is NOT an AbstractPriorModel, so it must be read here, not from the component walk), direct_instance_tuples filtered to Constant/float/int (fixed), ConfigException values (missing), plain-object instance leaves (kind = instance row on the owner, with the injected id), and Array's shape / indices on the skip-list.
    • Sharing: all_paths_prior_tuples → prior.id → occurrences; every row for that prior lists all occurrences; one SharedEdge per 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 via path_for_prior when the operand is a prior in the tree. Never call str()/repr() on a compound — CompoundPrior.__repr__ recurses (compound.py:87).
    • Assertions: model.gathered_assertions() (the method), one AssertionEdge each; operands resolved as above; excluded from the tree and from path_index (they are not in model.info).
    • Latents: if analysis is 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 of model.info paths (grouped paths where a plate collapses them, using find_groups on the member paths). Every added annotation (solved, missing, latent) is flagged in_model_info = False.
  3. Collapse (_collapse_siblings, applied per Collection/Model child list when collapse=True):

    • R1 signature per member: recursive (cls tree, per-slot sampling status, prior class + prior arguments, tuple structure, child signatures) — excluding prior id, _label and 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_comps vs 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) with PlateInfo; representative_key comes from find_groups over the member paths so the figure's 0 - 29 matches model.info's.
  4. Ordering contract, in the module docstring: visual order = the order of path_instance_tuples_for_class(..., ignore_children=True), which is the order of model.info's parameter-detail section (the structural summary, parameterization, is the other candidate; it is rejected because it reorders through find_groups(limit=0)).

  5. Public surface: from .graph_spec import GraphSpec, graph_spec_from in autofit/__init__.py. autofit/visualise.py untouched.

  6. Tests — test_autofit/graph_spec/ with a conftest.py that resets af.ModelObject._ids and af.Prior._ids (as test_visualise.py does) 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 without analysis= and presence with a stub analysis declaring Latent.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 → identical json.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, per AGENTS.md): (a) 6 components / 13 rows; (b) 11 components (12 before R7), two ×30 plates split on ell_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_factor in missing. 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 Heart lib-tests.yml matrix (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.
  • solved carried, not computed: phase 1 has no domain knowledge; the field and a solved_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 — export GraphSpec, graph_spec_from
  • autofit/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 — reuse find_groups
  • autofit/mapper/prior/arithmetic/compound.py, assertion.py — operand names, the __repr__ recursion to avoid
  • autofit/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 per Model / Collection / GlobalPriorModel. path is the full
    tuple path in the model; obj_id is the Python object identity (this is how a
    component shared across datasets is detected: the same obj.id at several
    paths).
  • ParamRow — one row per parameter slot, carrying separate properties, not
    one exclusive kind
    (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's ell_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 in model.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, while assertions is 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)

  • TuplePrior is not an AbstractPriorModel: any walk over
    direct_prior_tuples + direct_prior_model_tuples silently loses every tuple
    parameter — i.e. every centre in every lens model.
  • CompoundPrior / ComparisonAssertion are AbstractPriorModels 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
    are sm, sc, x in a hand-built relation but self/other when built by
    ArithmeticMixin.__add__.
  • repr() of a CompoundPrior subclass without __str__ recurses forever
    (compound.py:88). Never repr in a label path. (Filed separately as
    draft/bug/autofit/assertion_repr_recurses_forever.md.)
  • Prior _label carries a per-instance counter (einstein_radius2 vs
    einstein_radius4), which defeats naive equality when detecting plates.
  • fgm.graph rebuilds on every access and renames PriorFactors — cache it.
    factor.name is not unique across _HierarchicalFactors; use
    factor.name_for_variable(v), never variable.label. (Phase 4 leans on this;
    phase 1 only needs the tree.)
  • with_free_parameters does not exist on the installed af.Model; the live
    multi-dataset idiom is model.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:

  1. af.Model(Cls) with default priors.
  2. Overridden prior (m.centre = af.UniformPrior(...)) — indistinguishable
    from (1) without a config diff; assert that, and record it as a known gap.
  3. Fixed float (m.centre = 0.0, af.Model(Cls, centre=0.0)) → wrapped in
    Constant, absent from prior_tuples, present in model.info.
  4. Shared prior (m.a.x = m.b.x) — the same Prior object at two paths.
  5. Relation (m.centre = m.norm + m.sigma) → a SumPrior / CompoundPrior
    with cls == float; assert the expression string and both operands.
  6. Assertion (m.add_assertion(m.sigma > 5.0)) — in model._assertions, not in
    the tree and not in model.info.
  7. Tuple parameter → TuplePrior holding centre_0, centre_1; paths are
    ('centre','centre_0'); one row with a 2-D cue.
  8. af.Collection(a=…, b=…) — children as named attributes.
  9. af.Collection([m0, m1, m2]) — children named "0", "1", "2".
  10. Nested Collections.
  11. Multi-level af.Model(Cls, gaussian_list=[Model, Model]) — the list becomes
    a child Collection at ('gaussian_list',).
  12. Instance leaf (af.Collection(a=Model, b=instance)) — a raw Python object
    with an injected id; model.info shows Gaussian (N=0).
  13. af.Model(function) — model.cls is the function, so cls.__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.
  14. af.Array(shape=…, prior=…) — flat priors prior_0_0, prior_0_1, … plus
    shape / indices noise attributes that need a skip-list.
  15. FactorGraphModel.global_prior_model, fully shared — all children the
    same object (id == 1 for all three).
  16. Per-dataset free parameters (model.copy() + reassignment) — shared params
    keep one prior.id, free ones get new ids.
  17. Cross-dataset relation (sigma = sm*x + sc) — nested
    SumPrior(MultiplePrior(sm, x), sc); assert the operand-name provenance.
  18. 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 optional analysis= 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 the Model(int)), two ×30
    plates split on ell_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 unset areas_factor in the missing
    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

https://claude.ai/code/session_01UJ9stuFNR4e9BF5GXsqvfv

Activity

  1. Jammy2211 commented on Sep 10, 2026

    @Jammy2211
    CollaboratorAuthor

    Library PR created: #1606 (feature/model-figures-graph-spec, labelled pending-release).

    API changes: additive only — af.GraphSpec / af.graph_spec_from and the record dataclasses in autofit.graph_spec. No workspace script is affected; nothing to migrate. Next: /prm once 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_workspace scripts (autofit may not import autolens). The MGE case meets every epic invariant (11 boxes, two ×30 plates split on ell_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 fixed centre tuples) but today's group/modeling.py composition 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 target comments. Phase 3 re-runs the assertions on the real classes in PyAutoLens.


    Generated by Claude Code

  2. Jammy2211 commented on Sep 11, 2026

    @Jammy2211
    CollaboratorAuthor

    Shipped

    Merged #1606 into main (merge commit e331e33), 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, ParamRow as independent properties, shared / relation / assertion edges, the model.info path index, collapse rules R1 / R2 with the safety condition over find_groups, and 52 tests including the 18-construct catalogue and the lens acceptance doubles. Purely additive, no drawing, VisualiseGraph untouched. Labelled pending-release; phase 2 (model_figures_2_renderer) is unblocked.


    Generated by Claude Code

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