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
3 changes: 3 additions & 0 deletions autofit/non_linear/search/execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ class SearchExecutionMixin:
# Whether `ctx.start_points` makes the start-point plot. `Drawer` draws its whole
# result through the initializer, so it has no starting point to plot.
_plots_start_point = True
# Whether `ctx.start_points` lets the initializer return its test-mode samples under
# `PYAUTO_TEST_MODE=1` (`test_mode_samples`); `Zeus` draws real start points.
_start_points_in_test_mode = True

def _run_bridge(self, model: AbstractPriorModel, analysis: Analysis):
"""
Expand Down
1 change: 1 addition & 0 deletions autofit/non_linear/search/fit_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ def start_points(self, n: int):
fitness=self.fitness,
n=n,
plot=self._search._plots_start_point,
test_mode_samples=self._search._start_points_in_test_mode,
)
return np.asarray(parameter_lists), np.asarray(figure_of_merit_list)

Expand Down
72 changes: 24 additions & 48 deletions autofit/non_linear/search/mcmc/emcee/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
from autofit.non_linear.test_mode import is_test_mode
from autofit.non_linear.samples.adapter import ChainPosterior, RawSamples
from autofit.non_linear.search import capabilities as cap
from autofit.non_linear.search.seed import backend_random_state

if TYPE_CHECKING:
from autofit.database.sqlalchemy_ import sa
Expand Down Expand Up @@ -140,29 +139,24 @@ def __init__(

self.logger.debug("Creating Emcee Search")

def _fit(self, model: AbstractPriorModel, analysis):
def run(self, ctx):
"""
Fit a model using Emcee and the Analysis class which contains the data and returns the log likelihood from
instances of the model, which the `NonLinearSearch` seeks to maximize.
Run emcee (the ``run(ctx)`` hook; see ``docs/design/run_ctx.md``) and return the
``emcee.EnsembleSampler``.

emcee's HDF backend (``search_internal/search_internal.hdf``) is both the archive
and the resume state: a resumed run reopens it, continues from its last sample
and samples only the remaining steps. Likelihoods are spread over the fit's
``SneakyPool`` (``ctx.pool.sneaky``), which is ``None`` on one core.

Parameters
----------
model : ModelMapper
The model which generates instances for different points in parameter space.
analysis : Analysis
Contains the data and the log likelihood function which fits an instance of the model to the data, returning
the log likelihood the `NonLinearSearch` maximizes.

Returns
-------
A result object comprising the Samples object that inclues the maximum log likelihood instance and full
chains used by the fit.
ctx
The fit's ``FitContext``.
"""
import emcee

fitness = self.make_fitness(analysis=analysis, model=model)

pool = self.make_sneaky_pool(fitness)
model = ctx.model

try:
backend = emcee.backends.HDFBackend(filename=self.backend_filename)
Expand All @@ -172,17 +166,18 @@ def _fit(self, model: AbstractPriorModel, analysis):
search_internal = emcee.EnsembleSampler(
nwalkers=self.nwalkers,
ndim=model.prior_count,
log_prob_fn=fitness.call_wrap,
log_prob_fn=ctx.fitness.call_wrap,
backend=backend,
pool=pool,
pool=ctx.pool.sneaky(ctx.fitness),
)

# Backend stream 1 of the search-level seed (`autofit.non_linear.search.seed`);
# emcee otherwise copies numpy's global state. A resumed run restores the state
# its HDF backend saved.
random_state = backend_random_state(self)
if random_state is not None:
search_internal._random = random_state
# Backend stream 1 of the search-level seed (`ctx.rng`, whose stream 0 the
# initializer already took); emcee otherwise copies numpy's global state. A
# resumed run restores the state its HDF backend saved.
if self.seed is not None:
search_internal._random = np.random.RandomState(
np.random.MT19937(ctx.rng.spawn(1)[0])
)

try:
state = search_internal.get_last_sample()
Expand All @@ -200,32 +195,19 @@ def _fit(self, model: AbstractPriorModel, analysis):
)

except AttributeError:
(
unit_parameter_lists,
parameter_lists,
log_posterior_list,
) = self.start_points(
model=model,
fitness=fitness,
n=search_internal.nwalkers,
)

state = np.zeros(shape=(search_internal.nwalkers, model.prior_count))
state, _ = ctx.start_points(search_internal.nwalkers)

self.logger.info(
"Starting new Emcee non-linear search (no previous samples found)."
)

for index, parameters in enumerate(parameter_lists):
state[index, :] = np.asarray(parameters)

total_iterations = 0
iterations_remaining = self.nsteps

while iterations_remaining > 0:
# ``emcee``'s ``sample`` does ``range(iterations)`` internally and
# never casts, so this must be an ``int`` (PyAutoFit#1422).
iterations = self._steps_until_full_update(iterations_remaining)
iterations = ctx.schedule.next_budget(total_iterations, self.nsteps)

for sample in search_internal.sample(
initial_state=state,
Expand All @@ -252,15 +234,9 @@ def _fit(self, model: AbstractPriorModel, analysis):
iterations_remaining = 0

if iterations_remaining > 0:
self.perform_update(
model=model,
analysis=analysis,
search_internal=search_internal,
fitness=fitness,
during_analysis=True,
)
ctx.update(search_internal)

return search_internal, fitness
return search_internal

def samples_info_from(self, search_internal=None, auto_correlations=None):
search_internal = search_internal or self.backend
Expand Down
68 changes: 24 additions & 44 deletions autofit/non_linear/search/mcmc/zeus/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ class Zeus(NonLinearSearch):
test_mode_budget = {"nwalkers": 20, "nsteps": 10}
objective_target = cap.ObjectiveTarget(cap.ObjectiveQuantity.LOG_POSTERIOR, cap.CoordinateSpace.PHYSICAL)
invalid_value = -float("inf")
# Zeus has always drawn its walkers' start points through the initializer under
# ``PYAUTO_TEST_MODE=1`` too (``test_mode_samples=False``), so ``ctx.start_points``
# does not substitute the initializer's test-mode samples for it.
_start_points_in_test_mode = False

__identifier_fields__ = (
"nwalkers",
Expand Down Expand Up @@ -152,23 +156,20 @@ def __init__(

self.logger.debug("Creating Zeus Search")

def _fit(self, model: AbstractPriorModel, analysis):
def run(self, ctx):
"""
Fit a model using Zeus and the Analysis class which contains the data and returns the log likelihood from
instances of the model, which the `NonLinearSearch` seeks to maximize.
Run Zeus (the ``run(ctx)`` hook; see ``docs/design/run_ctx.md``) and return the
``zeus.EnsembleSampler``.

The sampler is archived (``search_internal.dill``) after every chunk of steps; a
rerun of an interrupted fit continues from the archived sampler's last sample.
Likelihoods are spread over the fit's pool (``ctx.pool()``, ``None`` on one
core).

Parameters
----------
model : ModelMapper
The model which generates instances for different points in parameter space.
analysis : Analysis
Contains the data and the log likelihood function which fits an instance of the model to the data, returning
the log likelihood the `NonLinearSearch` maximizes.

Returns
-------
A result object comprising the Samples object that inclues the maximum log likelihood instance and full
chains used by the fit.
ctx
The fit's ``FitContext``.
"""

try:
Expand All @@ -183,12 +184,10 @@ def _fit(self, model: AbstractPriorModel, analysis):
"----------------------"
)

pool = self.make_pool()

fitness = self.make_fitness(analysis=analysis, model=model)
model = ctx.model

try:
search_internal = self.paths.load_search_internal()
search_internal = ctx.paths.load_search_internal()

state = search_internal.get_last_sample()
log_posterior_list = search_internal.get_last_log_prob()
Expand All @@ -210,32 +209,19 @@ def _fit(self, model: AbstractPriorModel, analysis):
search_internal = zeus.EnsembleSampler(
nwalkers=self.nwalkers,
ndim=model.prior_count,
logprob_fn=fitness.call_wrap,
pool=pool,
logprob_fn=ctx.fitness.call_wrap,
pool=ctx.pool(),
)

search_internal.ncall_total = 0

(
unit_parameter_lists,
parameter_lists,
log_posterior_list,
) = self.start_points(
model=model,
fitness=fitness,
n=search_internal.nwalkers,
test_mode_samples=False,
)

state = np.zeros(shape=(search_internal.nwalkers, model.prior_count))
state, log_posterior_list = ctx.start_points(search_internal.nwalkers)
log_posterior_list = log_posterior_list.tolist()

self.logger.info(
"Starting new Zeus non-linear search (no previous samples found)."
)

for index, parameters in enumerate(parameter_lists):
state[index, :] = np.asarray(parameters)

total_iterations = 0
iterations_remaining = self.nsteps

Expand All @@ -245,7 +231,7 @@ def _fit(self, model: AbstractPriorModel, analysis):
# incremented by this value, so an uncast float would drift the
# bookkeeping away from the samples zeus actually drew
# (PyAutoFit#1422).
iterations = self._steps_until_full_update(iterations_remaining)
iterations = ctx.schedule.next_budget(total_iterations, self.nsteps)

for sample in search_internal.sample(
start=state,
Expand All @@ -257,7 +243,7 @@ def _fit(self, model: AbstractPriorModel, analysis):

search_internal.ncall_total += search_internal.ncall

self.paths.save_search_internal(
ctx.paths.save_search_internal(
obj=search_internal,
)

Expand All @@ -282,15 +268,9 @@ def _fit(self, model: AbstractPriorModel, analysis):
iterations_remaining = 0

if iterations_remaining > 0:
self.perform_update(
model=model,
analysis=analysis,
search_internal=search_internal,
fitness=fitness,
during_analysis=True,
)
ctx.update(search_internal)

return search_internal, fitness
return search_internal

def samples_info_from(self, search_internal=None, auto_correlations=None):
search_internal = search_internal or self.paths.load_search_internal()
Expand Down
Loading
Loading