Skip to content

fix(samples): errors_at_sigma(as_instance=True) on a prior-valued model #1577

Closed

Description

@Jammy2211

Overview

Samples.errors_at_sigma(as_instance=True) — the default — crashes with TypeError: broadcast_arrays requires ndarray or scalar arguments, got <class 'tuple'> at position 0 whenever the model contains a component whose class is a Prior (e.g. the Model(af.GaussianPrior) a HierarchicalFactor contributes to FactorGraphModel.global_prior_model). The bounds list [(lower, upper), …] is fed through instance_from_vector, which then calls GaussianPrior(mean=(lo, hi), sigma=(lo, hi)) and constructs a message from a tuple. values_at_sigma(as_instance=True) hits the same path.

This is finding D6 of the analytic Gaussian benchmark (autofit_workspace_test#91) and the last open phase-1 finding of the graphical-ep campaign. It is minor but it forced analytic_autofit.py to read errors with as_instance=False and re-map them by hand.

Plan

  • Reproduce the broadcast_arrays TypeError on a hierarchical global model (FactorGraphModel.global_prior_model with a HierarchicalFactor → Model(af.GaussianPrior) component).
  • Make Model.instance_for_arguments return an attribute container instead of constructing a Prior from (lower, upper) bounds pairs.
  • Pin it with tests for errors_at_sigma and values_at_sigma (instance attributes == raw tuples), and confirm median_pdf(as_instance=True) still builds a real prior.
  • Remove the as_instance=False workaround from the analytic benchmark's autofit adapter (autofit_workspace_test); referee numbers unchanged.
Detailed implementation plan

Work Classification

Library — PyAutoFit source first; the autofit_workspace_test docstring/workaround follow-up ships second, behind the library-first merge gate.

Affected Repositories

  • PyAutoFit (primary)
  • autofit_workspace_test (workspace follow-up, same task branch, after the library PR merges)

Branch Survey

Repository Current Branch Dirty?
./PyAutoFit main clean
./autofit_workspace_test main clean

Suggested branch: feature/samples-errors-at-sigma-instance

Worktree root: ~/Code/PyAutoLabs-wt/samples-errors-at-sigma-instance/ (created later by /start_library)

Implementation Steps

  1. Root cause path (deepest frame last). autofit/non_linear/samples/pdf.py:236 errors_at_sigma returns [(lower, upper), …] → the to_instance wrapper (autofit/non_linear/samples/interface.py:56) → _instance_from_vector → Model.instance_for_arguments (autofit/mapper/prior_model/prior_model.py ~541, result = self.cls(**constructor_arguments)) → GaussianPrior(mean=(lo, hi), sigma=(lo, hi)) → NormalMessage → broadcast_arrays TypeError. values_at_sigma(as_instance=True) is tuple-valued too and crashes identically.

  2. Design decision. The prompt's option 1 (return a pair of instances, one from the lower vector and one from the upper) is rejected — it would break the public tuple-attribute instance contract already used by autofit_workspace_test/scripts/graphical/ep_parity.py:176, simultaneous.py:200 and the workspace result tutorials, all of which read instance.<param> as an (lower, upper) tuple.

  3. Fix — PyAutoFit autofit/mapper/prior_model/prior_model.py, Model.instance_for_arguments, immediately before result = self.cls(**constructor_arguments): if inspect.isclass(self.cls) and issubclass(self.cls, Prior) and any constructor argument is a tuple (a bounds pair — a Prior constructor only takes scalars, and TuplePrior centres never reach a Prior-class model), return ModelInstance(constructor_arguments) (autofit/mapper/model.py:404, dict form → .mean == (lo, hi), .sigma == (lo, hi)). Scalar vectors keep constructing the real prior. Write it as an explicit typed branch with a comment — not a try/except guard around the construction.

  4. Tests — test_autofit/non_linear/samples/test_pdf.py (pattern of test__errors_at__converged), or a new test_autofit/graphical/global/test_errors_at_sigma_instance.py using the global_prior_model fixture pattern of test_hierarchical.py:14-28:

    1. errors_at_sigma(1.0, as_instance=True) on a model with a Model(af.GaussianPrior) component does not raise, and that component's .mean / .sigma equal the as_instance=False tuples read back through model.prior_tuples_ordered_by_id; ordinary components are unchanged.
    2. The same for values_at_sigma.
    3. median_pdf(as_instance=True) still yields a real af.GaussianPrior (scalar path untouched).

    Tests (1) and (2) must fail without the fix.

  5. Verification. pytest test_autofit/non_linear/samples test_autofit/mapper test_autofit/graphical -q, then the full suite. CI legs: Tests [pull_request] 3.12 / 3.13 / nojax, plus Docs.

  6. Workspace follow-up (autofit_workspace_test, same task branch, ships after the library PR merges): scripts/graphical/analytic_autofit.py line ~212 errors_at_sigma(sigma=1.0, as_instance=False) → the instance path, removing the hand re-mapping and the module-docstring sentence (lines ~52-54) that says the instance path cannot be used. analytic_gaussian.py's [info] graphical median_pdf +/- mean|errors_at_sigma(1)| lines must print identical numbers before and after (capture both in the PR); the referee analytic_gaussian_collapse.py RECOVER 5/5 stays unchanged; Smoke Tests [pull_request] green.

Key Files

  • autofit/mapper/prior_model/prior_model.py — Model.instance_for_arguments, the fix site (~line 541)
  • autofit/mapper/model.py:404 — ModelInstance, the attribute container returned instead
  • autofit/non_linear/samples/pdf.py:236 — errors_at_sigma / values_at_sigma, the tuple-valued producers
  • autofit/non_linear/samples/interface.py:56 — the to_instance wrapper
  • autofit/mapper/prior/gaussian.py:52, autofit/messages/abstract.py:63 — where the tuple becomes a broadcast_arrays TypeError
  • test_autofit/non_linear/samples/test_pdf.py, test_autofit/graphical/global/test_hierarchical.py:14-28 — test patterns
  • autofit_workspace_test/scripts/graphical/analytic_autofit.py (~52-54, ~212) — the workaround to remove
  • autofit_workspace_test/scripts/graphical/ep_parity.py:176, simultaneous.py:200 — the tuple-attribute contract the fix must preserve

Context

Original Prompt

Click to expand starting prompt

Samples.errors_at_sigma(as_instance=True) crashes on a model whose component class is a Prior

Type: bug
Target: PyAutoFit
Repos:

  • PyAutoFit
    Themes:
  • graphical-ep
    Difficulty: small
    Autonomy: safe
    Priority: medium
    Status: formalised
    Consequence: glance
    Witness: errors_at_sigma(1.0, as_instance=True) on a FactorGraphModel global model containing Model(af.GaussianPrior) returns without raising, and its values equal the as_instance=False tuples read back through prior_tuples_ordered_by_id
    Review-minutes: 3
    Unattended: ready
    Epic: graphical-ep
    Filed: 2026-09-02

D6 of the analytic Gaussian benchmark findings (autofit_workspace_test#91).
Minor, but it forced analytic_autofit.py to read errors with
as_instance=False and re-map them by hand (see its module docstring, lines
52-54).

Why

On the hierarchical graph's global model (a HierarchicalFactor contributes a
Model(af.GaussianPrior) component), samples.errors_at_sigma(1.0) — the
as_instance=True default — raises:

TypeError: broadcast_arrays requires ndarray or scalar arguments, got <class 'tuple'> at position 0

Plain dataclass models tolerate the tuples; a Prior used as a Model class does
not, because constructing it constructs a message.

Root cause (deepest frame last)

  • errors_at_sigma (autofit/non_linear/samples/pdf.py:236-255) returns a list
    of (lower, upper) tuples per parameter.
  • The to_instance wrapper (autofit/non_linear/samples/interface.py:56) calls
    model.instance_from_vector(vector) on that tuple list.
  • prior_model.py:541 — self.cls(**constructor_arguments) for
    Model(af.GaussianPrior).
  • autofit/mapper/prior/gaussian.py:52 — NormalMessage(mean=(lo, hi), ...).
  • autofit/messages/abstract.py:63 — broadcast_arrays on the tuple -> TypeError.

Minimal repro

import autofit as af
class Level:
    def __init__(self, x): self.x = x
class A(af.Analysis):
    def log_likelihood_function(self, i): return -0.5 * (51.0 - i.x) ** 2
m = af.Model(Level); m.x = af.GaussianPrior(50, 20)
hf = af.HierarchicalFactor(af.GaussianPrior, mean=af.GaussianPrior(50, 10), sigma=af.GaussianPrior(10, 5))
hf.add_drawn_variable(m.x)
fg = af.FactorGraphModel(af.AnalysisFactor(m, A()), hf)
samples = ...  # the EP result's Samples over fg.global_prior_model, as analytic_autofit.py builds them
samples.errors_at_sigma(1.0, as_instance=False)   # fine: list of (lo, hi)
samples.errors_at_sigma(1.0)                       # TypeError from broadcast_arrays

Fix sketch

Either build two instances — instance_from_vector(lower) and
instance_from_vector(upper) — and return them as a pair (mirrors how
values_at_sigma style callers already split the bounds), or fall back to the
tuple list when the model contains prior-valued components. The first is the
cleaner contract; pick it unless it breaks an existing caller.

Acceptance

  • Unit test: a Samples over a model with a Model(af.GaussianPrior) component;
    errors_at_sigma(1.0, as_instance=True) does not raise and its bounds equal
    the as_instance=False tuples.
  • autofit_workspace_test/scripts/graphical/analytic_autofit.py: the
    as_instance=False workaround and the docstring note at lines 52-54 can be
    removed; analytic_gaussian.py's median_pdf +/- errors_at_sigma(1.0)
    information line is produced through the instance path with identical numbers
    on every row (this line is informational, not a PASS/FAIL cell).

Links

Activity

  1. Jammy2211 commented on Sep 7, 2026

    @Jammy2211
    CollaboratorAuthor

    Library PR Created

    PR: #1578 (pending-release)
    Commit: 154c87dd48aa481017810354eecd2d2e0deac2e4

    Model.instance_for_arguments now returns a ModelInstance of the constructor arguments when the model class is a Prior subclass and any argument is a tuple (the (lower, upper) bounds pair from Samples.errors_at_sigma / values_at_sigma), instead of handing the pair to the Prior constructor and raising TypeError: broadcast_arrays requires ndarray or scalar arguments, got <class 'tuple'>. Scalar vectors (median_pdf, max_log_likelihood) still construct the real prior.

    API changes

    Bug fix only — no signatures changed. errors_at_sigma / values_at_sigma with as_instance=True now return an instance on global models containing a Model(af.GaussianPrior) (any FactorGraphModel with a HierarchicalFactor) where they previously raised; the Prior-class component becomes a ModelInstance whose attributes hold the bounds pairs.

    Tests

    • test_autofit/graphical/global/test_errors_at_sigma_instance.py — 3 new tests; the two tuple-valued ones fail without the fix
    • pytest test_autofit -q: 2472 passed, 2 skipped (baseline 2469 + 3 new); graphical 278, messages 95

    Workspace impact — option (ii), migration

    grep -rn "errors_at_sigma(\|values_at_sigma(" over the workspace scripts:

    • autofit_workspace_test/scripts/graphical/analytic_autofit.py:212 — carries the as_instance=False workaround this fix removes (follow-up)
    • autofit_workspace_test/scripts/graphical/ep_parity.py:176, simultaneous.py:200 — use the instance contract, unchanged by this fix

    Next: /start_workspace — remove the as_instance=False workaround from analytic_autofit.py and verify the analytic_gaussian.py info lines are byte-identical through the instance path. The workspace PR ships after this library PR merges (library-first gate).

    Finding D6 of autofit_workspace_test#91; graphical-ep phase 1; umbrella PyAutoFit#1405.

  2. Jammy2211 commented on Sep 8, 2026

    @Jammy2211
    CollaboratorAuthor

    Workspace PR: PyAutoLabs/autofit_workspace_test#99

    scripts/graphical/analytic_autofit.py's module docstring no longer claims errors_at_sigma(as_instance=True) is unusable on the hierarchical global model; it now records that the read stays as_instance=False because read_joint_posteriors indexes the sample columns positionally through prior_tuples_ordered_by_id. Docstring only, no code change. Library-first: merges after PyAutoFit#1578.

  3. Jammy2211 commented on Sep 8, 2026

    @Jammy2211
    CollaboratorAuthor

    Shipped

    Summary. Model.instance_for_arguments constructed a Prior from the (lower, upper) bounds pairs that Samples.errors_at_sigma / values_at_sigma (as_instance=True) hand it whenever the global model holds a Model(af.GaussianPrior) component (every HierarchicalFactor graph), so NormalMessage's broadcast_arrays raised TypeError. There is now an explicit typed branch: a Prior-class model whose constructor arguments contain a tuple returns ModelInstance(constructor_arguments) (.mean == (lo, hi), .sigma == (lo, hi)); scalar vectors (median_pdf, max_log_likelihood) still build the real prior. Workspace side: the analytic_autofit.py docstring no longer claims the instance path is unusable; the raw as_instance=False read stays, because the weighted-moment comparison indexes columns positionally through prior_tuples_ordered_by_id.

    Decision. The prompt's option 1 (return a pair of instances) was rejected — it would break the public tuple-attribute instance contract used by ep_parity.py, simultaneous.py and the workspace result tutorials.

    Tests / evidence.

    • 3 new tests in test_autofit/graphical/global/test_errors_at_sigma_instance.py; the two tuple-valued ones fail without the fix.
    • Full suite 2472 passed, 2 skipped (baseline 2469 + 3); graphical 278; messages 95.
    • Referee analytic_gaussian_collapse.py: RECOVER 5/5, STALE 0/5.
    • Smoke gate 14/14.
    • Every deterministic analytic_gaussian.py cell byte-identical before/after (PARITY FAIL 38/41 on both sides — the same three autofit-EP cells, i.e. the known Laplace-on-scatter caveat).
    • CI: PyAutoFit Tests [pull_request] 3.12 / 3.13 / nojax + Docs green; autofit_workspace_test Smoke Tests [pull_request] changes / 3.12 / 3.13 green; both PRs CLEAN; library merged first.

    Side finding (filed, not fixed here). analytic_gaussian.py's graphical column is an unseeded DynestyStatic run — its PARITY count and [info] lines drift run to run (37 vs 38 of 41 on an identical tree). Drafted as draft/bug/graphical_ep/analytic_gaussian_unseeded_graphical_column.md in PyAutoMind.

    Remaining. This was finding D6 of the phase-1 analytic Gaussian benchmark (autofit_workspace_test#91) — the findings table D1–D6 is now fully shipped. analytic_gaussian.py / analytic_gaussian_priors.py stay parked NEEDS_FIX for the scatter-estimation cure (moment-matching projection, draft/feature/autofit/ep_hierarchical_scatter_moment_matching.md) — a human decision.

    Record: complete/2026/09/samples-errors-at-sigma-instance.md (PyAutoMind).

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