Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 23 additions & 11 deletions autofit/non_linear/search/mcmc/emcee/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand All @@ -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
Expand Down
68 changes: 46 additions & 22 deletions autofit/non_linear/search/mcmc/zeus/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand All @@ -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 = [
Expand Down
55 changes: 55 additions & 0 deletions test_autofit/non_linear/search/mcmc/test_emcee.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import numpy as np
import pytest

import autofit as af
Expand Down Expand Up @@ -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
)
64 changes: 64 additions & 0 deletions test_autofit/non_linear/search/mcmc/test_zeus.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import importlib.util

import numpy as np
import pytest

import autofit as af

pytestmark = pytest.mark.filterwarnings("ignore::FutureWarning")
Expand Down Expand Up @@ -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
)
Loading