From 00d74e32f619ad81d082a3f396c944be9433dbbc Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Mon, 14 Sep 2026 23:21:42 +0100 Subject: [PATCH] fix: align Emcee and Zeus log posteriors with the thinned sample chain MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `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) Claude-Session: https://claude.ai/code/session_0132v5TNVbbvBBESAefHwnwG --- .../non_linear/search/mcmc/emcee/search.py | 34 +++++++--- autofit/non_linear/search/mcmc/zeus/search.py | 68 +++++++++++++------ .../non_linear/search/mcmc/test_emcee.py | 55 +++++++++++++++ .../non_linear/search/mcmc/test_zeus.py | 64 +++++++++++++++++ 4 files changed, 188 insertions(+), 33 deletions(-) diff --git a/autofit/non_linear/search/mcmc/emcee/search.py b/autofit/non_linear/search/mcmc/emcee/search.py index bd56f4714..e8963fd7b 100644 --- a/autofit/non_linear/search/mcmc/emcee/search.py +++ b/autofit/non_linear/search/mcmc/emcee/search.py @@ -9,6 +9,7 @@ from autonerves import conf +from autofit import exc from autofit.mapper.model_mapper import ModelMapper from autofit.mapper.prior_model.abstract import AbstractPriorModel from autofit.non_linear.fitness import Fitness @@ -293,9 +294,8 @@ def samples_via_internal_from(self, model, search_internal=None): search_internal = search_internal or self.backend if is_test_mode(): - samples_after_burn_in = search_internal.get_chain( - discard=5, thin=5, flat=True - ) + discard = 5 + thin = 5 else: auto_correlations = self.auto_correlations_from( @@ -304,19 +304,31 @@ def samples_via_internal_from(self, model, search_internal=None): discard = int(3.0 * np.max(auto_correlations.times)) thin = int(np.max(auto_correlations.times) / 2.0) - samples_after_burn_in = search_internal.get_chain( - discard=discard, thin=thin, flat=True - ) + + samples_after_burn_in = search_internal.get_chain( + discard=discard, thin=thin, flat=True + ) parameter_lists = samples_after_burn_in.tolist() log_prior_list = model.log_prior_list_from(parameter_lists=parameter_lists) - total_samples = len(parameter_lists) - - log_posterior_list = search_internal.get_log_prob(flat=True)[ - -total_samples - 1 : -1 - ].tolist() + # The log posteriors must be requested with the *same* `discard` and `thin` + # as the chain above, otherwise sample `i`'s parameters are paired with a + # different sample's log posterior (PyAutoFit#1628). + log_posterior_list = search_internal.get_log_prob( + discard=discard, thin=thin, flat=True + ).tolist() + + if len(parameter_lists) != len(log_posterior_list): + raise exc.SamplesException( + "The number of Emcee parameter samples does not match the number of log " + "posterior values returned by the sampler: " + f"{len(parameter_lists)} parameter samples versus " + f"{len(log_posterior_list)} log posterior values. " + "The parameters and log posteriors are therefore not in correspondence " + "and the samples cannot be built." + ) log_likelihood_list = [ log_posterior - log_prior diff --git a/autofit/non_linear/search/mcmc/zeus/search.py b/autofit/non_linear/search/mcmc/zeus/search.py index 62afce9d8..a03908cd9 100644 --- a/autofit/non_linear/search/mcmc/zeus/search.py +++ b/autofit/non_linear/search/mcmc/zeus/search.py @@ -6,6 +6,7 @@ import numpy as np import os +from autofit import exc from autofit.mapper.model_mapper import ModelMapper from autofit.mapper.prior_model.abstract import AbstractPriorModel from autofit.non_linear.fitness import Fitness @@ -335,11 +336,12 @@ def samples_via_internal_from(self, model, search_internal=None): search_internal = search_internal or self.paths.load_search_internal() - if is_test_mode(): + test_mode = is_test_mode() - samples_after_burn_in = search_internal.get_chain( - discard=5, thin=5, flat=True - ) + if test_mode: + + discard = 5 + thin = 5 else: auto_correlations = self.auto_correlations_from( @@ -348,29 +350,51 @@ def samples_via_internal_from(self, model, search_internal=None): discard = int(3.0 * np.max(auto_correlations.times)) thin = int(np.max(auto_correlations.times) / 2.0) - samples_after_burn_in = search_internal.get_chain( - discard=discard, thin=thin, flat=True + + samples_after_burn_in = search_internal.get_chain( + discard=discard, thin=thin, flat=True + ) + + if not test_mode and len(samples_after_burn_in) == 0: + + logging.info( + """ + After thinnng the Zeus samples in order to remove burn-in, no samples were left. + + To create a samples object containing samples, so that the code can continue and results + can be inspected, the full list of samples before removing burn-in has been used. This may + indicate that the sampler has not converged and therefore your results may not be reliable. + + To fix this, run Zeus with more steps to ensure convergence is achieved or change the auto + correlation settings to be less aggressive in thinning samples. + """ ) - if len(samples_after_burn_in) == 0: - - logging.info( - """ - After thinnng the Zeus samples in order to remove burn-in, no samples were left. - - To create a samples object containing samples, so that the code can continue and results - can be inspected, the full list of samples before removing burn-in has been used. This may - indicate that the sampler has not converged and therefore your results may not be reliable. - - To fix this, run Zeus with more steps to ensure convergence is achieved or change the auto - correlation settings to be less aggressive in thinning samples. - """ - ) + discard = 0 + thin = 1 - samples_after_burn_in = search_internal.get_chain(flat=True) + samples_after_burn_in = search_internal.get_chain(flat=True) parameter_lists = samples_after_burn_in.tolist() - log_posterior_list = search_internal.get_log_prob(flat=True).tolist() + + # The log posteriors must be requested with the *same* `discard` and `thin` + # as whichever branch above produced the chain, otherwise sample `i`'s + # parameters are paired with a different sample's log posterior, and the + # `zip` below silently truncates to the shorter list (PyAutoFit#1628). + log_posterior_list = search_internal.get_log_prob( + discard=discard, thin=thin, flat=True + ).tolist() + + if len(parameter_lists) != len(log_posterior_list): + raise exc.SamplesException( + "The number of Zeus parameter samples does not match the number of log " + "posterior values returned by the sampler: " + f"{len(parameter_lists)} parameter samples versus " + f"{len(log_posterior_list)} log posterior values. " + "The parameters and log posteriors are therefore not in correspondence " + "and the samples cannot be built." + ) + log_prior_list = model.log_prior_list_from(parameter_lists=parameter_lists) log_likelihood_list = [ diff --git a/test_autofit/non_linear/search/mcmc/test_emcee.py b/test_autofit/non_linear/search/mcmc/test_emcee.py index e9a413857..999f5d071 100644 --- a/test_autofit/non_linear/search/mcmc/test_emcee.py +++ b/test_autofit/non_linear/search/mcmc/test_emcee.py @@ -1,3 +1,4 @@ +import numpy as np import pytest import autofit as af @@ -41,3 +42,57 @@ def test__explicit_params(): assert search.auto_correlation_settings.required_length == 50 assert search.auto_correlation_settings.change_threshold == 0.01 assert search.number_of_cores == 1 + + +def test__log_posteriors_are_aligned_with_the_thinned_chain(monkeypatch): + """ + The parameters and the log posteriors must come out of ``emcee`` under the + *same* ``discard`` / ``thin``, so that sample ``i``'s log likelihood is the + likelihood of sample ``i``'s parameters. + + Previously the chain was requested after burn-in and thinning while the log + probabilities were a contiguous tail slice of the raw, unthinned array (plus + a one-element offset), so the two were not in correspondence and the reported + maximum log likelihood belonged to a different point in parameter space + (PyAutoFit#1628). + + The assertion below is the invariant rather than a pinned number: the log + likelihood stored against the maximum likelihood sample must equal the log + likelihood the `Analysis` computes for that sample's own parameters. + """ + monkeypatch.setenv("PYAUTO_TEST_MODE", "1") + + np.random.seed(1) + + model = af.Model(af.ex.Gaussian) + analysis = af.ex.Analysis( + data=np.full(100, 5.0), + noise_map=np.full(100, 1.0), + ) + + # Test mode 1 runs the real sampler for 10 steps with 20 walkers, so the + # auto-correlation `check_size` must be smaller than the chain for the + # auto-correlation calculation to have samples to work with. + search = af.Emcee( + name="emcee_log_prob_alignment", + unique_tag="log_prob_alignment_test", + auto_correlation_settings=af.AutoCorrelationsSettings( + check_for_convergence=False, + check_size=5, + required_length=2, + ), + number_of_cores=1, + ) + + result = search.fit(model=model, analysis=analysis) + + samples = result.samples + + assert len(samples.parameter_lists) == len(samples.log_likelihood_list) + assert len(samples.parameter_lists) > 0 + + instance = samples.max_log_likelihood() + + assert samples.max_log_likelihood_sample.log_likelihood == pytest.approx( + analysis.log_likelihood_function(instance=instance), rel=1.0e-8 + ) diff --git a/test_autofit/non_linear/search/mcmc/test_zeus.py b/test_autofit/non_linear/search/mcmc/test_zeus.py index 2c8593423..8f509e0c5 100644 --- a/test_autofit/non_linear/search/mcmc/test_zeus.py +++ b/test_autofit/non_linear/search/mcmc/test_zeus.py @@ -1,4 +1,8 @@ +import importlib.util + +import numpy as np import pytest + import autofit as af pytestmark = pytest.mark.filterwarnings("ignore::FutureWarning") @@ -43,3 +47,63 @@ def test__explicit_params(): assert search.auto_correlation_settings.required_length == 50 assert search.auto_correlation_settings.change_threshold == 0.01 assert search.number_of_cores == 1 + + +requires_zeus = pytest.mark.skipif( + importlib.util.find_spec("zeus") is None, + reason="requires zeus-mcmc (installed via the [optional] extras)", +) + + +@requires_zeus +def test__log_posteriors_are_aligned_with_the_thinned_chain(monkeypatch): + """ + The parameters and the log posteriors must come out of ``zeus`` under the + *same* ``discard`` / ``thin``, so that sample ``i``'s log likelihood is the + likelihood of sample ``i``'s parameters. + + Previously the chain was requested after burn-in and thinning while the log + probabilities were the full, unthinned array, so the two were not in + correspondence and the `zip` building the log likelihoods silently truncated + to the shorter of the two (PyAutoFit#1628). + + The assertion below is the invariant rather than a pinned number: the log + likelihood stored against the maximum likelihood sample must equal the log + likelihood the `Analysis` computes for that sample's own parameters. + """ + monkeypatch.setenv("PYAUTO_TEST_MODE", "1") + + np.random.seed(1) + + model = af.Model(af.ex.Gaussian) + analysis = af.ex.Analysis( + data=np.full(100, 5.0), + noise_map=np.full(100, 1.0), + ) + + # Test mode 1 runs the real sampler for 10 steps with 20 walkers, so the + # auto-correlation `check_size` must be smaller than the chain for the + # auto-correlation calculation to have samples to work with. + search = af.Zeus( + name="zeus_log_prob_alignment", + unique_tag="log_prob_alignment_test", + auto_correlation_settings=af.AutoCorrelationsSettings( + check_for_convergence=False, + check_size=5, + required_length=2, + ), + number_of_cores=1, + ) + + result = search.fit(model=model, analysis=analysis) + + samples = result.samples + + assert len(samples.parameter_lists) == len(samples.log_likelihood_list) + assert len(samples.parameter_lists) > 0 + + instance = samples.max_log_likelihood() + + assert samples.max_log_likelihood_sample.log_likelihood == pytest.approx( + analysis.log_likelihood_function(instance=instance), rel=1.0e-8 + )