Repository navigation
fix: align Emcee and Zeus log posteriors with the thinned sample chain - #1629
Merged
Merged
Conversation
`Emcee.samples_via_internal_from` took its parameters from the chain after
burn-in discard and thinning, but its log posteriors from a contiguous tail
slice of the raw, unthinned, undiscarded array:
samples_after_burn_in = search_internal.get_chain(
discard=discard, thin=thin, flat=True
)
total_samples = len(parameter_lists)
log_posterior_list = search_internal.get_log_prob(flat=True)[
-total_samples - 1 : -1
].tolist()
The two are not in correspondence, so sample `i`'s reported likelihood belonged
to a different sample. `result.max_log_likelihood_instance` was therefore the
argmax of a scrambled array — effectively a random post-burn-in draw rather than
the maximum likelihood sample — and the "Maximum Log Likelihood" line of every
Emcee `result.info` was wrong. The slice also carried an unexplained one-element
offset.
`Zeus` had the same defect in a different form: `get_log_prob(flat=True)` against
a possibly-thinned chain, with the following `zip()` silently truncating to the
shorter list.
Both now request log posteriors under the same `discard` and `thin` as the
chain. `discard`/`thin` are bound in both branches of the test-mode conditional,
and Zeus's empty-chain fallback resets them to `0`/`1` to match the
`get_chain(flat=True)` it falls back to. Both searches now raise
`exc.SamplesException` if the two lengths disagree, so a future mismatch fails
loudly instead of truncating.
emcee's `get_chain` and `get_log_prob` both delegate to the same
`get_value(name, flat, thin, discard)`, and zeus's carry identical explicit
signatures, so the discard/thin semantics are provably identical between the
two calls in each library.
Regression tests assert the invariant rather than a pinned number: the reported
maximum likelihood must equal the `Analysis` likelihood recomputed from the
reported instance. Both were confirmed to fail against the old code and pass
against the new.
No `discard`/`thin` values, auto-correlation logic, nested sampling or MLE
search behaviour changed.
Closes #1628
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0132v5TNVbbvBBESAefHwnwG
This was referenced Sep 14, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #1628.
The bug
Emcee.samples_via_internal_frombuilt each sample's likelihood from two arrays that were not in correspondence:The parameters are the chain after burn-in discard and thinning. The log posteriors are a contiguous tail slice of the raw, unthinned, undiscarded flat array, plus an unexplained one-element offset. Sample
i's likelihood belonged to a different sample.Zeushad the same defect in a different form —get_log_prob(flat=True)against a possibly-thinned chain, after whichzip()silently truncated to the shorter list, hiding the length mismatch entirely.Impact
result.max_log_likelihood_instance/samples.max_log_likelihood()returned the argmax of a scrambled array — effectively a random post-burn-in draw, not the maximum likelihood sample.result.infowas wrong.log_likelihood_listwas wrong per-sample, so anything derived from it inherited the error.Nested sampling and the MLE searches were never affected.
The error scales with how much the post-burn-in samples differ from one another, so a poorly converged chain is punished hardest — exactly the case where a trustworthy maximum-likelihood sample matters most.
Verification
Reproduced on a 1D Gaussian fit with
af.Emcee(nwalkers=20, nsteps=500), comparing the reported likelihood against the sameAnalysisrecomputed from the reported instance:After the fix, three consecutive runs gave a worst-case delta of exactly
0.000e+00.The fix
Both searches request log posteriors under the same
discardandthinas the chain.discard/thinare now bound in both branches of the test-mode conditional (test mode previously inlineddiscard=5, thin=5into itsget_chaincall), and Zeus's empty-chain fallback resets them to0/1to match theget_chain(flat=True)it falls back to.Both now raise
exc.SamplesExceptionwhen the two lengths disagree, so a future mismatch fails loudly rather than truncating — the old Zeuszip()is precisely the silent-guard pattern this repo's conventions forbid.API semantics were introspected, not assumed. emcee 3.1.6's
get_chainandget_log_probboth delegate to the sameget_value(name, flat=False, thin=1, discard=0), which applies[discard + thin - 1 : iteration : thin]and flattens identically. zeus 2.5.4's two methods carry identical explicit signatures, the same fractional-discardhandling, and matching[discard:index:thin]slices. No library-specific asymmetry, so no asymmetric handling was needed.Unchanged:
discard/thinvalues, the auto-correlation logic, nested sampling, the MLE searches.Tests
Added to the existing MCMC test modules, matching their fixtures and conventions (no JAX, seeded,
af.ex.Gaussian+af.ex.Analysis). The Zeus test is guarded byimportlib.util.find_spec("zeus")since zeus is an[optional]extra, following therequires_nautiluspattern.They assert the invariant, not a pinned number:
samples.max_log_likelihood_sample.log_likelihoodmust equal theAnalysislikelihood recomputed fromsamples.max_log_likelihood(), plus the two list lengths must match and be non-zero.Confirmed to actually catch the bug — each was run against the reverted source:
-1247.252566vs true-1247.482800-1244.796028vs true-1245.091243Both tests need
AutoCorrelationsSettings(check_for_convergence=False, check_size=5, required_length=2): with the defaultcheck_size=100against a 10-step test-mode chain,auto_correlations_fromslices to an empty array andemcee.autocorrraisesIndexErrorbefore samples are built. Pre-existing, see below.Suite
pytest test_autofit -q→ 2852 passed, 2 skipped, zero failures.Pinned values
None exist, so nothing else moved. Grepped PyAutoFit (
*.py,*.rst,*.ipynb,*.md,*.yaml) for Emcee/Zeus references co-occurring with likelihood numbers orpytest.approx, and checkedautofit_workspacetoo. The only hit is a comment naming the two searches as log-posterior searches, with no number. No test mocksget_log_proboutside the two files changed here.Found but not fixed (follow-ups)
thincan be0.thin = int(np.max(auto_correlations.times) / 2.0)is0whenever the largest auto-correlation time is below 2.0, and a zero slice step raisesValueError: slice step cannot be zeroin bothget_chainandget_log_prob. Pre-existing and unchanged here — the old code hit it onget_chainfirst. Clamping it would changethinvalues, which is a separate decision.check_size=100versus short chains.auto_correlations_fromraisesIndexErrorfromemcee.autocorrwhen the chain is shorter thancheck_size, which is always true underPYAUTO_TEST_MODE=1(nsteps=10). Zeus guards its equivalent withexcept IndexError; Emcee does not. Worked around in the tests rather than changed in the library.black --checkstill reports findings inzeus/search.pyand both test files. Every one is pre-existing onorigin/main(verified by pipinggit show origin/main:<file>through black) and none is in a hunk added here. Left alone —AGENTS.mdrecords no black gate, and fixing them would add unrelated noise.Origin
Found while calibrating HowToFit tutorial 3's MCMC budget (PyAutoLabs/HowToFit#59, PR PyAutoLabs/HowToFit#60). That tutorial work does not depend on this fix and ships independently.
🤖 Generated with Claude Code
https://claude.ai/code/session_0132v5TNVbbvBBESAefHwnwG