diff --git a/autofit/non_linear/search/abstract_search.py b/autofit/non_linear/search/abstract_search.py index 9e146f390..b9f192555 100644 --- a/autofit/non_linear/search/abstract_search.py +++ b/autofit/non_linear/search/abstract_search.py @@ -583,6 +583,3 @@ def check_model(self, model: AbstractPriorModel): def __eq__(self, other): return isinstance(other, NonLinearSearch) and self.__dict__ == other.__dict__ - - def plot_results(self, samples): - raise NotImplementedError diff --git a/autofit/non_linear/search/deprecated_family.py b/autofit/non_linear/search/deprecated_family.py new file mode 100644 index 000000000..91f574066 --- /dev/null +++ b/autofit/non_linear/search/deprecated_family.py @@ -0,0 +1,22 @@ +""" +The deprecation hook of the former family bases (search-extensibility A4c, D14). + +``AbstractMCMC``, ``AbstractNest`` and ``AbstractMLE`` are no longer in any public +search's MRO. Their modules still export them, as distinct thin subclasses of +``NonLinearSearch`` that keep the former constructor defaults and plots, so external +subclasses keep working for one release; subclassing one warns. +""" + +import warnings + + +def warn_family_subclass(cls, family: str, kind: str): + warnings.warn( + f"{cls.__name__} subclasses {family}, which is deprecated and will be removed " + f"one release after search-extensibility phase A4. Subclass " + f"`autofit.NonLinearSearch` directly, declare `posterior_kind = " + f"PosteriorKind.{kind}` and apply that kind's defaults in `__init__` " + f"(`autofit.non_linear.search.posterior_kind.{kind}`).", + FutureWarning, + stacklevel=3, + ) diff --git a/autofit/non_linear/search/mcmc/abstract_mcmc.py b/autofit/non_linear/search/mcmc/abstract_mcmc.py index 49de061ec..fe0491bf7 100644 --- a/autofit/non_linear/search/mcmc/abstract_mcmc.py +++ b/autofit/non_linear/search/mcmc/abstract_mcmc.py @@ -2,20 +2,35 @@ from typing import Optional, TYPE_CHECKING -from autonerves import conf from autofit.non_linear.search.abstract_search import NonLinearSearch -from autofit.non_linear.initializer import Initializer, InitializerBall +from autofit.non_linear.initializer import Initializer +from autofit.non_linear.search.deprecated_family import warn_family_subclass from autofit.non_linear.search.mcmc.auto_correlations import AutoCorrelationsSettings -from autofit.non_linear.plot import corner_cornerpy +from autofit.non_linear.search.posterior_kind import CHAIN from autofit.non_linear.samples.mcmc import SamplesMCMC if TYPE_CHECKING: from autofit.database.sqlalchemy_ import sa + class AbstractMCMC(NonLinearSearch): + """ + **Deprecated** (search-extensibility A4c): no public search inherits it any more, + and it is removed one release later. Subclass ``NonLinearSearch`` with + ``posterior_kind = PosteriorKind.CHAIN`` and apply + ``autofit.non_linear.search.posterior_kind.CHAIN`` in ``__init__`` instead. + + Kept as a distinct class with the former defaults (``InitializerBall(0.49, 0.51)``, + ``auto_correlation_settings``, ``SamplesMCMC``, the cornerpy corner plot), so an + existing subclass behaves exactly as before; subclassing it warns. + """ samples_cls = SamplesMCMC + def __init_subclass__(cls, **kwargs): + super().__init_subclass__(**kwargs) + warn_family_subclass(cls, "AbstractMCMC", "CHAIN") + def __init__( self, name: Optional[str] = None, @@ -36,9 +51,7 @@ def __init__( name=name, path_prefix=path_prefix, unique_tag=unique_tag, - initializer=initializer or InitializerBall( - lower_limit=0.49, upper_limit=0.51 - ), + initializer=CHAIN.initializer_for(initializer), iterations_per_quick_update=iterations_per_quick_update, iterations_per_full_update=iterations_per_full_update, number_of_cores=number_of_cores, @@ -48,16 +61,4 @@ def __init__( ) def plot_results(self, samples): - - if not samples.pdf_converged: - return - - def should_plot(name): - return conf.instance["visualize"]["plots_search"]["mcmc"][name] - - if should_plot("corner_cornerpy"): - corner_cornerpy( - samples=samples, - path=self.paths.image_path / "search", - format="png", - ) + CHAIN.plot_results(self, samples) diff --git a/autofit/non_linear/search/mcmc/blackjax/nuts/search.py b/autofit/non_linear/search/mcmc/blackjax/nuts/search.py index f91c8fd15..d9e8bfd03 100644 --- a/autofit/non_linear/search/mcmc/blackjax/nuts/search.py +++ b/autofit/non_linear/search/mcmc/blackjax/nuts/search.py @@ -11,7 +11,9 @@ from autofit.non_linear.checkpoint import PICKLE_FILENAME, PickleCheckpointer from autofit.non_linear.fitness import Fitness from autofit.non_linear.initializer import Initializer -from autofit.non_linear.search.mcmc.abstract_mcmc import AbstractMCMC +from autofit.non_linear.search.abstract_search import NonLinearSearch +from autofit.non_linear.search.posterior_kind import CHAIN +from autofit.non_linear.samples.mcmc import SamplesMCMC from autofit.non_linear.search.mcmc.auto_correlations import AutoCorrelations from autofit.non_linear.search.mcmc.auto_correlations import AutoCorrelationsSettings from autofit.non_linear.search.mcmc.blackjax.chains import ( @@ -36,7 +38,9 @@ logger = logging.getLogger(__name__) -class BlackJAXNUTS(AbstractMCMC): +class BlackJAXNUTS(NonLinearSearch): + samples_cls = SamplesMCMC + # Static capabilities (see ``autofit.non_linear.search.capabilities``); mirrored # by ``search/registry.py``. Never identifier fields. jax_use = cap.JaxUse.REQUIRED @@ -81,9 +85,7 @@ def __init__( inverse_mass_matrix: InverseMassMatrixSpec = None, mass_matrix_shrinkage: float = 0.0, share_adaptation: bool = False, - auto_correlation_settings: AutoCorrelationsSettings = AutoCorrelationsSettings( - check_for_convergence=False - ), + auto_correlation_settings: Optional[AutoCorrelationsSettings] = None, iterations_per_quick_update: Optional[int] = None, iterations_per_full_update: Optional[int] = None, number_of_cores: int = 1, @@ -236,8 +238,7 @@ def __init__( name=name, path_prefix=path_prefix, unique_tag=unique_tag, - initializer=initializer, - auto_correlation_settings=auto_correlation_settings, + initializer=CHAIN.initializer_for(initializer), iterations_per_quick_update=iterations_per_quick_update, iterations_per_full_update=iterations_per_full_update, number_of_cores=number_of_cores, @@ -247,6 +248,10 @@ def __init__( **kwargs, ) + self.auto_correlation_settings = CHAIN.auto_correlation_settings_for( + auto_correlation_settings, check_for_convergence=False + ) + self.num_warmup = num_warmup self.num_samples = num_samples self.num_chains = num_chains diff --git a/autofit/non_linear/search/mcmc/blackjax/smc/search.py b/autofit/non_linear/search/mcmc/blackjax/smc/search.py index bb05e8624..249f8175b 100644 --- a/autofit/non_linear/search/mcmc/blackjax/smc/search.py +++ b/autofit/non_linear/search/mcmc/blackjax/smc/search.py @@ -3,6 +3,7 @@ import logging import math import os +import warnings from pathlib import Path from typing import List, Optional, Tuple, TYPE_CHECKING @@ -12,8 +13,8 @@ from autofit.non_linear.checkpoint import PICKLE_FILENAME, PickleCheckpointer from autofit.non_linear.objective import jax_objective from autofit.non_linear.initializer import Initializer, InitializerPrior -from autofit.non_linear.search.mcmc.abstract_mcmc import AbstractMCMC -from autofit.non_linear.search.mcmc.auto_correlations import AutoCorrelationsSettings +from autofit.non_linear.search.abstract_search import NonLinearSearch +from autofit.non_linear.search.posterior_kind import WEIGHTED from autofit.non_linear.search.mcmc.blackjax.chains import ( InverseMassMatrixSpec, SERIALISED_KINDS, @@ -53,7 +54,7 @@ VALID_KERNELS = ("mala", "hmc") -class SMC(AbstractMCMC): +class SMC(NonLinearSearch): samples_cls = SamplesSMC # Static capabilities (see ``autofit.non_linear.search.capabilities``); mirrored @@ -104,9 +105,7 @@ def __init__( seed: Optional[int] = None, initializer: Optional[Initializer] = None, inverse_mass_matrix: InverseMassMatrixSpec = None, - auto_correlation_settings: AutoCorrelationsSettings = AutoCorrelationsSettings( - check_for_convergence=False - ), + *legacy_positional, iterations_per_quick_update: Optional[int] = None, iterations_per_full_update: Optional[int] = None, number_of_cores: int = 1, @@ -258,9 +257,6 @@ def __init__( ``search.json`` records only the kind (``"none"``, ``"array"`` or ``"result"``), so a search loaded from it receives that string: ``"none"`` behaves as ``None``, while ``"array"`` / ``"result"`` raise at fit time because the covariance was not saved. - auto_correlation_settings - Kept for API parity with the other MCMC searches. SMC particles are not a chain, so no - auto-correlation diagnostics are computed and ``check_for_convergence`` defaults to ``False``. iterations_per_full_update Inherited from the autonerves config when ``None``. SMC calls ``perform_update`` once per temperature (SMC steps are coarse and few), so this does not chunk the run. @@ -271,14 +267,39 @@ def __init__( If True, the default print output of the non-linear search is silenced. session An SQLalchemy session instance. + legacy_positional + Deprecated. SMC used to take ``auto_correlation_settings`` positionally after + ``inverse_mass_matrix``; the arguments after it are now keyword-only. Old positional + calls are still bound to their former slots (the auto-correlation settings are ignored) + with a ``FutureWarning``, instead of being silently shifted one slot. """ + # SMC is a weighted-posterior search (A4c): its particles are not a chain, so it + # takes no auto-correlation settings. An old `search.json` still records them; + # they are accepted and ignored so it loads. + kwargs.pop("auto_correlation_settings", None) + + if legacy_positional: + ( + iterations_per_quick_update, + iterations_per_full_update, + number_of_cores, + silence, + session, + ) = _bind_legacy_positional( + legacy_positional, + iterations_per_quick_update=iterations_per_quick_update, + iterations_per_full_update=iterations_per_full_update, + number_of_cores=number_of_cores, + silence=silence, + session=session, + ) + super().__init__( name=name, path_prefix=path_prefix, unique_tag=unique_tag, - initializer=initializer or InitializerPrior(), - auto_correlation_settings=auto_correlation_settings, + initializer=WEIGHTED.initializer_for(initializer), iterations_per_quick_update=iterations_per_quick_update, iterations_per_full_update=iterations_per_full_update, number_of_cores=number_of_cores, @@ -1031,3 +1052,44 @@ def _build_search_internal( "max_smc_steps": max_smc_steps, "converged": bool(lambda_list) and float(lambda_list[-1]) >= 1.0, } + + +# The arguments SMC took positionally after ``inverse_mass_matrix`` before A4c removed +# ``auto_correlation_settings`` (adversary review 07, finding 4). +_LEGACY_POSITIONAL = ( + "auto_correlation_settings", + "iterations_per_quick_update", + "iterations_per_full_update", + "number_of_cores", + "silence", + "session", +) + + +def _bind_legacy_positional(legacy_positional, **current): + """ + Bind positional arguments passed after ``inverse_mass_matrix`` to the slots they had + when SMC still took ``auto_correlation_settings`` there, so an old positional call + keeps its meaning instead of shifting every value one slot. The auto-correlation + settings are dropped (SMC is a weighted search). Warns with a ``FutureWarning``; pass + these arguments by keyword instead. + """ + if len(legacy_positional) > len(_LEGACY_POSITIONAL): + raise TypeError( + f"SMC takes at most {len(_LEGACY_POSITIONAL)} deprecated positional arguments " + f"after inverse_mass_matrix ({', '.join(_LEGACY_POSITIONAL)}); got " + f"{len(legacy_positional)}. Pass them by keyword." + ) + warnings.warn( + "Passing SMC arguments positionally after `inverse_mass_matrix` is deprecated: SMC no " + "longer takes `auto_correlation_settings` (it is a weighted search, not a chain), so " + f"these slots ({', '.join(_LEGACY_POSITIONAL[: len(legacy_positional)])}) are bound " + "as they were and the auto-correlation settings are ignored. Pass them by keyword.", + FutureWarning, + stacklevel=3, + ) + bound = dict(zip(_LEGACY_POSITIONAL, legacy_positional)) + bound.pop("auto_correlation_settings", None) + return tuple( + bound.get(name, current[name]) for name in _LEGACY_POSITIONAL[1:] + ) diff --git a/autofit/non_linear/search/mcmc/emcee/search.py b/autofit/non_linear/search/mcmc/emcee/search.py index d052ae6df..2d3a6c367 100644 --- a/autofit/non_linear/search/mcmc/emcee/search.py +++ b/autofit/non_linear/search/mcmc/emcee/search.py @@ -16,7 +16,9 @@ load_emcee_backend, ) from autofit.non_linear.initializer import Initializer -from autofit.non_linear.search.mcmc.abstract_mcmc import AbstractMCMC +from autofit.non_linear.search.abstract_search import NonLinearSearch +from autofit.non_linear.search.posterior_kind import CHAIN +from autofit.non_linear.samples.mcmc import SamplesMCMC from autofit.non_linear.search.mcmc.auto_correlations import AutoCorrelationsSettings from autofit.non_linear.search.mcmc.auto_correlations import AutoCorrelations from autofit.non_linear.test_mode import is_test_mode @@ -30,7 +32,9 @@ logger = logging.getLogger(__name__) -class Emcee(AbstractMCMC): +class Emcee(NonLinearSearch): + samples_cls = SamplesMCMC + # Static capabilities (see ``autofit.non_linear.search.capabilities``); mirrored # by ``search/registry.py``. Never identifier fields. jax_use = cap.JaxUse.NONE @@ -69,7 +73,7 @@ def __init__( nwalkers: int = 50, nsteps: int = 2000, initializer: Optional[Initializer] = None, - auto_correlation_settings=AutoCorrelationsSettings(), + auto_correlation_settings: Optional[AutoCorrelationsSettings] = None, iterations_per_quick_update: int = None, iterations_per_full_update: int = None, number_of_cores: int = 1, @@ -118,8 +122,7 @@ def __init__( name=name, path_prefix=path_prefix, unique_tag=unique_tag, - initializer=initializer, - auto_correlation_settings=auto_correlation_settings, + initializer=CHAIN.initializer_for(initializer), iterations_per_quick_update=iterations_per_quick_update, iterations_per_full_update=iterations_per_full_update, number_of_cores=number_of_cores, @@ -128,6 +131,10 @@ def __init__( **kwargs, ) + self.auto_correlation_settings = CHAIN.auto_correlation_settings_for( + auto_correlation_settings + ) + self.nwalkers = nwalkers self.nsteps = nsteps diff --git a/autofit/non_linear/search/mcmc/zeus/search.py b/autofit/non_linear/search/mcmc/zeus/search.py index 4f4d8735e..97ac769ff 100644 --- a/autofit/non_linear/search/mcmc/zeus/search.py +++ b/autofit/non_linear/search/mcmc/zeus/search.py @@ -10,7 +10,9 @@ from autofit.mapper.model_mapper import ModelMapper from autofit.mapper.prior_model.abstract import AbstractPriorModel from autofit.non_linear.initializer import Initializer -from autofit.non_linear.search.mcmc.abstract_mcmc import AbstractMCMC +from autofit.non_linear.search.abstract_search import NonLinearSearch +from autofit.non_linear.search.posterior_kind import CHAIN +from autofit.non_linear.samples.mcmc import SamplesMCMC from autofit.non_linear.search.mcmc.auto_correlations import AutoCorrelationsSettings from autofit.non_linear.search.mcmc.auto_correlations import AutoCorrelations from autofit.non_linear.test_mode import is_test_mode @@ -23,7 +25,9 @@ logger = logging.getLogger(__name__) -class Zeus(AbstractMCMC): +class Zeus(NonLinearSearch): + samples_cls = SamplesMCMC + # Static capabilities (see ``autofit.non_linear.search.capabilities``); mirrored # by ``search/registry.py``. Never identifier fields. jax_use = cap.JaxUse.NONE @@ -70,7 +74,7 @@ def __init__( check_walkers: bool = True, maxcall: Optional[int] = None, initializer: Optional[Initializer] = None, - auto_correlation_settings=AutoCorrelationsSettings(), + auto_correlation_settings: Optional[AutoCorrelationsSettings] = None, iterations_per_quick_update: int = None, iterations_per_full_update: int = None, number_of_cores: int = 1, @@ -119,8 +123,7 @@ def __init__( name=name, path_prefix=path_prefix, unique_tag=unique_tag, - initializer=initializer, - auto_correlation_settings=auto_correlation_settings, + initializer=CHAIN.initializer_for(initializer), iterations_per_quick_update=iterations_per_quick_update, iterations_per_full_update=iterations_per_full_update, number_of_cores=number_of_cores, @@ -129,6 +132,10 @@ def __init__( **kwargs ) + self.auto_correlation_settings = CHAIN.auto_correlation_settings_for( + auto_correlation_settings + ) + self.nwalkers = nwalkers self.nsteps = nsteps self.tune = tune diff --git a/autofit/non_linear/search/mle/abstract_mle.py b/autofit/non_linear/search/mle/abstract_mle.py index 3cc23c779..a4f9199eb 100644 --- a/autofit/non_linear/search/mle/abstract_mle.py +++ b/autofit/non_linear/search/mle/abstract_mle.py @@ -1,64 +1,30 @@ from abc import ABC -from autonerves import conf from autofit.non_linear.search.abstract_search import NonLinearSearch -from autofit.non_linear.clipper import ClipperNone -from autofit.non_linear.initializer import InitializerBall -from autofit.non_linear.plot import ( - subplot_parameters, - log_likelihood_vs_iteration, - figure_of_merit_vs_iteration, -) +from autofit.non_linear.search.deprecated_family import warn_family_subclass +from autofit.non_linear.search.posterior_kind import POINT class AbstractMLE(NonLinearSearch, ABC): + """ + **Deprecated** (search-extensibility A4c): no public search inherits it any more, + and it is removed one release later. Subclass ``NonLinearSearch`` with + ``posterior_kind = PosteriorKind.POINT`` and apply + ``autofit.non_linear.search.posterior_kind.POINT`` in ``__init__`` instead. - def __init__(self, initializer=None, clipper=None, **kwargs): - # ``clipper`` is resolved here, at the same tier and by the same - # ``or `` pattern as ``initializer``, so every MLE search - # inherits it. The default is the no-op ``ClipperNone``: enforcing prior - # support changes where a search converges, which would shift every stored - # multi-start benchmark, so it is opt-in until that re-baseline is done. - self.clipper = clipper or ClipperNone() - - super().__init__( - initializer=initializer - or InitializerBall(lower_limit=0.49, upper_limit=0.51), - **kwargs, - ) - - def plot_results(self, samples): + Kept as a distinct class with the former defaults (``InitializerBall(0.49, 0.51)``, + a ``clipper`` defaulting to ``ClipperNone``, the MLE trace plots), so an existing + subclass behaves exactly as before; subclassing it warns. + """ - def should_plot(name): - return conf.instance["visualize"]["plots_search"]["mle"][name] + def __init_subclass__(cls, **kwargs): + super().__init_subclass__(**kwargs) + warn_family_subclass(cls, "AbstractMLE", "POINT") - plot_path = self.paths.image_path / "search" - - if should_plot("subplot_parameters"): - subplot_parameters(samples=samples, path=plot_path, format="png") - subplot_parameters( - samples=samples, use_log_y=True, path=plot_path, format="png" - ) - subplot_parameters( - samples=samples, use_last_50_percent=True, path=plot_path, format="png" - ) + def __init__(self, initializer=None, clipper=None, **kwargs): + self.clipper = POINT.clipper_for(clipper) - if should_plot("log_likelihood_vs_iteration"): - log_likelihood_vs_iteration(samples=samples, path=plot_path, format="png") - log_likelihood_vs_iteration( - samples=samples, use_log_y=True, path=plot_path, format="png" - ) - log_likelihood_vs_iteration( - samples=samples, use_last_50_percent=True, path=plot_path, format="png" - ) + super().__init__(initializer=POINT.initializer_for(initializer), **kwargs) - # No-op unless the samples carry a ``fom_history`` (the auto-convergence - # gradient searches); LBFGS / Drawer leave it absent. Default-on and - # tolerant of a config predating this key (older workspaces that shadow - # the ``mle`` plots section) so it never KeyErrors on an MLE fit. - try: - plot_figure_of_merit = should_plot("figure_of_merit_vs_iteration") - except KeyError: - plot_figure_of_merit = True - if plot_figure_of_merit: - figure_of_merit_vs_iteration(samples=samples, path=plot_path, format="png") + def plot_results(self, samples): + POINT.plot_results(self, samples) diff --git a/autofit/non_linear/search/mle/bfgs/search.py b/autofit/non_linear/search/mle/bfgs/search.py index 1b85fbd33..ba675ddfd 100644 --- a/autofit/non_linear/search/mle/bfgs/search.py +++ b/autofit/non_linear/search/mle/bfgs/search.py @@ -5,7 +5,8 @@ from autofit import exc from autofit.mapper.prior_model.abstract import AbstractPriorModel -from autofit.non_linear.search.mle.abstract_mle import AbstractMLE +from autofit.non_linear.search.abstract_search import NonLinearSearch +from autofit.non_linear.search.posterior_kind import POINT from autofit.non_linear.analysis import Analysis from autofit.non_linear.clipper import ( AbstractClipper, @@ -22,7 +23,7 @@ from autofit.database.sqlalchemy_ import sa -class AbstractBFGS(AbstractMLE): +class AbstractBFGS(NonLinearSearch): # Same contract as ``AbstractMultiStartGradient``: bounds handed to scipy # change where the fit converges, so the clipper forks the identifier here @@ -104,12 +105,13 @@ def __init__( real clipper; see ``_bounds_from``. """ + self.clipper = POINT.clipper_for(clipper) + super().__init__( name=name, path_prefix=path_prefix, unique_tag=unique_tag, - initializer=initializer, - clipper=clipper, + initializer=POINT.initializer_for(initializer), iterations_per_quick_update=iterations_per_quick_update, iterations_per_full_update=iterations_per_full_update, silence=silence, diff --git a/autofit/non_linear/search/mle/drawer/search.py b/autofit/non_linear/search/mle/drawer/search.py index 741edb52b..64031ecff 100644 --- a/autofit/non_linear/search/mle/drawer/search.py +++ b/autofit/non_linear/search/mle/drawer/search.py @@ -5,7 +5,8 @@ from autofit.mapper.prior_model.abstract import AbstractPriorModel -from autofit.non_linear.search.mle.abstract_mle import AbstractMLE +from autofit.non_linear.search.abstract_search import NonLinearSearch +from autofit.non_linear.search.posterior_kind import POINT from autofit.non_linear.initializer import AbstractInitializer from autofit.non_linear.samples.adapter import RawSamples from autofit.non_linear.search import capabilities as cap @@ -14,7 +15,7 @@ from autofit.database.sqlalchemy_ import sa -class Drawer(AbstractMLE): +class Drawer(NonLinearSearch): # Static capabilities (see ``autofit.non_linear.search.capabilities``); mirrored # by ``search/registry.py``. Never identifier fields. jax_use = cap.JaxUse.NONE @@ -49,6 +50,7 @@ def __init__( iterations_per_quick_update: int = None, silence: bool = False, session: Optional[sa.orm.Session] = None, + clipper=None, **kwargs, ): """ @@ -89,6 +91,10 @@ def __init__( Generates the initialize samples of non-linear parameter space (see autofit.non_linear.initializer). session An SQLalchemy session instance so the results of the model-fit are written to an SQLite database. + clipper + Accepted for the point-estimate searches' common interface and recorded in ``search.json``; the + drawer never uses it, so it does not enter the identifier. It is the last named argument so the + existing positional slots (``total_draws`` ... ``session``) keep their places. """ # Drawer is single-core only; drop any saved number_of_cores so a @@ -96,11 +102,16 @@ def __init__( # deserialized without colliding with the hardcoded kwarg below. kwargs.pop("number_of_cores", None) + # The point-estimate default clipper. Drawer never consumes it and it is not an + # identifier field (#1493); it is kept as an argument so `search.json` records it + # exactly as when the clipper came from the former `AbstractMLE` base. + self.clipper = POINT.clipper_for(clipper) + super().__init__( name=name, path_prefix=path_prefix, unique_tag=unique_tag, - initializer=initializer, + initializer=POINT.initializer_for(initializer), iterations_per_quick_update=iterations_per_quick_update, iterations_per_full_update=iterations_per_full_update, number_of_cores=1, diff --git a/autofit/non_linear/search/mle/multi_start_gradient/search.py b/autofit/non_linear/search/mle/multi_start_gradient/search.py index f260e9c66..e0117c146 100644 --- a/autofit/non_linear/search/mle/multi_start_gradient/search.py +++ b/autofit/non_linear/search/mle/multi_start_gradient/search.py @@ -9,7 +9,8 @@ from autofit.mapper.prior_model.abstract import AbstractPriorModel from autofit.non_linear.search.abstract_search import ITERATIONS_NEVER -from autofit.non_linear.search.mle.abstract_mle import AbstractMLE +from autofit.non_linear.search.abstract_search import NonLinearSearch +from autofit.non_linear.search.posterior_kind import POINT from autofit.non_linear.analysis import Analysis from autofit.non_linear.fitness import Fitness from autofit.non_linear.objective import chunk_slices, evaluate_in_chunks @@ -37,7 +38,7 @@ from autofit.database.sqlalchemy_ import sa -class AbstractMultiStartGradient(AbstractMLE): +class AbstractMultiStartGradient(NonLinearSearch): # The clipper changes where a lane can sit and therefore the result, so two # runs differing only in clipper must not share an output directory. This @@ -406,12 +407,13 @@ def __init__( a finite ``iterations_per_quick_update``. """ + self.clipper = POINT.clipper_for(clipper) + super().__init__( name=name, path_prefix=path_prefix, unique_tag=unique_tag, - initializer=initializer, - clipper=clipper, + initializer=POINT.initializer_for(initializer), iterations_per_quick_update=iterations_per_quick_update, iterations_per_full_update=iterations_per_full_update, silence=silence, diff --git a/autofit/non_linear/search/nest/abstract_nest.py b/autofit/non_linear/search/nest/abstract_nest.py index acefeb3b2..da70c427a 100644 --- a/autofit/non_linear/search/nest/abstract_nest.py +++ b/autofit/non_linear/search/nest/abstract_nest.py @@ -2,16 +2,11 @@ from abc import ABC from typing import Optional, TYPE_CHECKING -import warnings -from autonerves import conf from autofit.non_linear.search.abstract_search import NonLinearSearch -from autofit.non_linear.initializer import ( - InitializerPrior, - AbstractInitializer, - InitializerParamBounds, -) -from autofit.non_linear.plot import corner_anesthetic +from autofit.non_linear.initializer import AbstractInitializer +from autofit.non_linear.search.deprecated_family import warn_family_subclass +from autofit.non_linear.search.posterior_kind import WEIGHTED from autofit.non_linear.samples.nest import SamplesNest if TYPE_CHECKING: @@ -19,8 +14,23 @@ class AbstractNest(NonLinearSearch, ABC): + """ + **Deprecated** (search-extensibility A4c): no public search inherits it any more, + and it is removed one release later. Subclass ``NonLinearSearch`` with + ``posterior_kind = PosteriorKind.WEIGHTED`` and apply + ``autofit.non_linear.search.posterior_kind.WEIGHTED`` in ``__init__`` instead. + + Kept as a distinct class with the former defaults (``InitializerPrior``, the + rejection of ``InitializerParamBounds``, ``SamplesNest``, the anesthetic corner + plot), so an existing subclass behaves exactly as before; subclassing it warns. + """ + samples_cls = SamplesNest + def __init_subclass__(cls, **kwargs): + super().__init_subclass__(**kwargs) + warn_family_subclass(cls, "AbstractNest", "WEIGHTED") + def __init__( self, name: Optional[str] = None, @@ -34,27 +44,11 @@ def __init__( initializer: Optional[AbstractInitializer] = None, **kwargs ): - """ - Abstract class of a nested sampling `NonLinearSearch` (e.g. Dynesty, Nautilus, NSS). - - It defaults the initializer to `InitializerPrior` (nested sampling draws its initial live points from the - prior), rejects `InitializerParamBounds`, and provides the corner plot of the nested sampling results. - - Parameters - ---------- - session - An SQLAlchemy session instance so the results of the model-fit are written to an SQLite database. - """ - if isinstance(initializer, InitializerParamBounds): - raise ValueError( - "InitializerParamBounds cannot be used for nested sampling" - ) - super().__init__( name=name, path_prefix=path_prefix, unique_tag=unique_tag, - initializer=initializer or InitializerPrior(), + initializer=WEIGHTED.nested_initializer_for(initializer), iterations_per_quick_update=iterations_per_quick_update, iterations_per_full_update=iterations_per_full_update, number_of_cores=number_of_cores, @@ -64,15 +58,4 @@ def __init__( ) def plot_results(self, samples): - - def should_plot(name): - return conf.instance["visualize"]["plots_search"]["nest"][name] - - if should_plot("corner_anesthetic"): - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - corner_anesthetic( - samples=samples, - path=self.paths.image_path / "search", - format="png", - ) \ No newline at end of file + WEIGHTED.plot_results(self, samples) diff --git a/autofit/non_linear/search/nest/dynesty/search/abstract.py b/autofit/non_linear/search/nest/dynesty/search/abstract.py index db64303b6..e5f948113 100644 --- a/autofit/non_linear/search/nest/dynesty/search/abstract.py +++ b/autofit/non_linear/search/nest/dynesty/search/abstract.py @@ -13,7 +13,9 @@ from autofit import exc from autofit.mapper.prior_model.abstract import AbstractPriorModel -from autofit.non_linear.search.nest.abstract_nest import AbstractNest +from autofit.non_linear.search.abstract_search import NonLinearSearch +from autofit.non_linear.search.posterior_kind import WEIGHTED +from autofit.non_linear.samples.nest import SamplesNest from autofit.non_linear.samples.adapter import RawSamples from autofit.non_linear.search import capabilities as cap @@ -86,7 +88,9 @@ def prior_transform(cube, model): return cube -class AbstractDynesty(AbstractNest, ABC): +class AbstractDynesty(NonLinearSearch, ABC): + samples_cls = SamplesNest + # Static capabilities (see ``autofit.non_linear.search.capabilities``); mirrored # by ``search/registry.py``. Never identifier fields. jax_use = cap.JaxUse.OPTIONAL @@ -171,6 +175,7 @@ def __init__( name=name, path_prefix=path_prefix, unique_tag=unique_tag, + initializer=WEIGHTED.nested_initializer_for(kwargs.pop("initializer", None)), iterations_per_quick_update=iterations_per_quick_update, iterations_per_full_update=iterations_per_full_update, number_of_cores=number_of_cores, diff --git a/autofit/non_linear/search/nest/nautilus/search.py b/autofit/non_linear/search/nest/nautilus/search.py index e5177f1ea..b971ff531 100644 --- a/autofit/non_linear/search/nest/nautilus/search.py +++ b/autofit/non_linear/search/nest/nautilus/search.py @@ -15,7 +15,9 @@ from autofit.mapper.prior.vectorized import PriorVectorized from autofit.non_linear.checkpoint import DillCheckpointer, NativeFileCheckpointer from autofit.non_linear.parallel import fork_context -from autofit.non_linear.search.nest import abstract_nest +from autofit.non_linear.search.abstract_search import NonLinearSearch +from autofit.non_linear.search.posterior_kind import WEIGHTED +from autofit.non_linear.samples.nest import SamplesNest from autofit.non_linear.samples.adapter import RawSamples from autofit.non_linear.search import capabilities as cap @@ -169,7 +171,9 @@ def __exit__(self, exc_type, exc_val, exc_tb): return False -class Nautilus(abstract_nest.AbstractNest): +class Nautilus(NonLinearSearch): + samples_cls = SamplesNest + # Static capabilities (see ``autofit.non_linear.search.capabilities``); mirrored # by ``search/registry.py``. Never identifier fields. jax_use = cap.JaxUse.OPTIONAL @@ -293,6 +297,7 @@ def __init__( name=name, path_prefix=path_prefix, unique_tag=unique_tag, + initializer=WEIGHTED.nested_initializer_for(kwargs.pop("initializer", None)), iterations_per_full_update=iterations_per_full_update, iterations_per_quick_update=iterations_per_quick_update, number_of_cores=number_of_cores, diff --git a/autofit/non_linear/search/nest/nss/search.py b/autofit/non_linear/search/nest/nss/search.py index 3a6fcb43c..40a3140c3 100644 --- a/autofit/non_linear/search/nest/nss/search.py +++ b/autofit/non_linear/search/nest/nss/search.py @@ -10,7 +10,9 @@ from autofit.non_linear.checkpoint import NativeFileCheckpointer from autofit.non_linear.objective import SCALAR -from autofit.non_linear.search.nest import abstract_nest +from autofit.non_linear.search.abstract_search import NonLinearSearch +from autofit.non_linear.search.posterior_kind import WEIGHTED +from autofit.non_linear.samples.nest import SamplesNest from .samples import NSSamples from autofit.non_linear.samples.adapter import RawSamples from autofit.non_linear.search import capabilities as cap @@ -135,7 +137,7 @@ def __init__( self.seed = seed -class NSS(abstract_nest.AbstractNest): +class NSS(NonLinearSearch): samples_cls = NSSamples # Static capabilities (see ``autofit.non_linear.search.capabilities``); mirrored @@ -305,6 +307,7 @@ def __init__( name=name, path_prefix=path_prefix, unique_tag=unique_tag, + initializer=WEIGHTED.nested_initializer_for(kwargs.pop("initializer", None)), iterations_per_full_update=iterations_per_full_update, iterations_per_quick_update=iterations_per_quick_update, number_of_cores=number_of_cores, diff --git a/autofit/non_linear/search/posterior_kind.py b/autofit/non_linear/search/posterior_kind.py new file mode 100644 index 000000000..83341674e --- /dev/null +++ b/autofit/non_linear/search/posterior_kind.py @@ -0,0 +1,188 @@ +""" +Per-``posterior_kind`` defaults and plotters (search-extensibility A4c, decision D14). + +The ``AbstractMCMC`` / ``AbstractNest`` / ``AbstractMLE`` family bases carried three +defaults (initializer, clipper, auto-correlation settings) and one plot routine. They are +no longer in any public search's MRO; what they carried lives here, keyed by the +search's declared ``posterior_kind`` (``autofit.non_linear.search.capabilities``): + +- ``CHAIN`` (Emcee, Zeus, BlackJAXNUTS): ``InitializerBall(0.49, 0.51)``, default + ``AutoCorrelationsSettings``, the cornerpy corner plot once the chain is converged; +- ``WEIGHTED`` (Dynesty, Nautilus, NSS, SMC): ``InitializerPrior`` (nested samplers + also reject ``InitializerParamBounds``), the anesthetic corner plot; +- ``POINT`` (BFGS, LBFGS, MultiStart, Drawer): ``InitializerBall(0.49, 0.51)``, + ``ClipperNone``, the parameter / log-likelihood / figure-of-merit traces. + +Each concrete search applies its kind's defaults in its own ``__init__``, never on +``NonLinearSearch``: the #1493 clipper tripwire requires that the clipper never reaches +the nested samplers. ``NonLinearSearch.plot_results`` plots through ``plotter_for``. +""" + +import warnings +from typing import Optional + +from autonerves import conf + +from autofit.non_linear.search.capabilities import PosteriorKind + + +class PosteriorDefaults: + kind: PosteriorKind = None + plots_section: str = None + + def initializer_for(self, initializer=None): + """The search's initializer: ``initializer``, or this kind's default.""" + return initializer if initializer is not None else self.default_initializer() + + def default_initializer(self): + raise NotImplementedError + + def should_plot(self, name: str) -> bool: + return conf.instance["visualize"]["plots_search"][self.plots_section][name] + + def plot_results(self, search, samples): + raise NotImplementedError + + +class ChainDefaults(PosteriorDefaults): + kind = PosteriorKind.CHAIN + plots_section = "mcmc" + + def default_initializer(self): + from autofit.non_linear.initializer import InitializerBall + + return InitializerBall(lower_limit=0.49, upper_limit=0.51) + + @staticmethod + def auto_correlation_settings_for(auto_correlation_settings=None, **defaults): + """ + The chain's auto-correlation settings: ``auto_correlation_settings``, or + ``AutoCorrelationsSettings(**defaults)`` built at construction, so a run-time + ``PYAUTO_TEST_MODE`` reaches its reduced ``check_size`` (the former import-time + default instance did not). + """ + from autofit.non_linear.search.mcmc.auto_correlations import ( + AutoCorrelationsSettings, + ) + + if auto_correlation_settings is None: + return AutoCorrelationsSettings(**defaults) + return auto_correlation_settings + + def plot_results(self, search, samples): + from autofit.non_linear.plot import corner_cornerpy + + if not samples.pdf_converged: + return + + if self.should_plot("corner_cornerpy"): + corner_cornerpy( + samples=samples, + path=search.paths.image_path / "search", + format="png", + ) + + +class WeightedDefaults(PosteriorDefaults): + kind = PosteriorKind.WEIGHTED + plots_section = "nest" + + def default_initializer(self): + from autofit.non_linear.initializer import InitializerPrior + + return InitializerPrior() + + def nested_initializer_for(self, initializer=None): + """ + A nested sampler's initializer: its initial live points are drawn from the prior, + so ``InitializerParamBounds`` (a bounded start) is rejected. + """ + from autofit.non_linear.initializer import InitializerParamBounds + + if isinstance(initializer, InitializerParamBounds): + raise ValueError("InitializerParamBounds cannot be used for nested sampling") + return self.initializer_for(initializer) + + def plot_results(self, search, samples): + from autofit.non_linear.plot import corner_anesthetic + + if self.should_plot("corner_anesthetic"): + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + corner_anesthetic( + samples=samples, + path=search.paths.image_path / "search", + format="png", + ) + + +class PointDefaults(PosteriorDefaults): + kind = PosteriorKind.POINT + plots_section = "mle" + + def default_initializer(self): + from autofit.non_linear.initializer import InitializerBall + + return InitializerBall(lower_limit=0.49, upper_limit=0.51) + + @staticmethod + def clipper_for(clipper=None): + """ + The search's clipper, the no-op ``ClipperNone`` by default: enforcing prior + support changes where a search converges, so it is opt-in. + """ + from autofit.non_linear.clipper import ClipperNone + + return clipper or ClipperNone() + + def plot_results(self, search, samples): + from autofit.non_linear.plot import ( + figure_of_merit_vs_iteration, + log_likelihood_vs_iteration, + subplot_parameters, + ) + + plot_path = search.paths.image_path / "search" + + if self.should_plot("subplot_parameters"): + subplot_parameters(samples=samples, path=plot_path, format="png") + subplot_parameters( + samples=samples, use_log_y=True, path=plot_path, format="png" + ) + subplot_parameters( + samples=samples, use_last_50_percent=True, path=plot_path, format="png" + ) + + if self.should_plot("log_likelihood_vs_iteration"): + log_likelihood_vs_iteration(samples=samples, path=plot_path, format="png") + log_likelihood_vs_iteration( + samples=samples, use_log_y=True, path=plot_path, format="png" + ) + log_likelihood_vs_iteration( + samples=samples, use_last_50_percent=True, path=plot_path, format="png" + ) + + # No-op unless the samples carry a ``fom_history`` (the auto-convergence + # gradient searches); LBFGS / Drawer leave it absent. Default-on and + # tolerant of a config predating this key (older workspaces that shadow + # the ``mle`` plots section) so it never KeyErrors on an MLE fit. + try: + plot_figure_of_merit = self.should_plot("figure_of_merit_vs_iteration") + except KeyError: + plot_figure_of_merit = True + if plot_figure_of_merit: + figure_of_merit_vs_iteration(samples=samples, path=plot_path, format="png") + + +CHAIN = ChainDefaults() +WEIGHTED = WeightedDefaults() +POINT = PointDefaults() + +_BY_KIND = {defaults.kind: defaults for defaults in (CHAIN, WEIGHTED, POINT)} + + +def defaults_for(kind) -> Optional[PosteriorDefaults]: + """The defaults (and plotter) of a ``posterior_kind``, or ``None`` when undeclared.""" + if kind is None: + return None + return _BY_KIND[PosteriorKind(kind)] diff --git a/autofit/non_linear/search/updates.py b/autofit/non_linear/search/updates.py index f5715ba8a..f6acbd95e 100644 --- a/autofit/non_linear/search/updates.py +++ b/autofit/non_linear/search/updates.py @@ -182,3 +182,16 @@ def perform_visualization( search_internal=search_internal, plot_search=plot_search, ) + + def plot_results(self, samples): + """ + The search's own plots of its samples, by its declared ``posterior_kind`` + (``autofit.non_linear.search.posterior_kind``): the chain, weighted or point + plotter. A search that declares no kind plots nothing of its own. + """ + from autofit.non_linear.search.posterior_kind import defaults_for + + defaults = defaults_for(type(self).posterior_kind) + if defaults is None: + raise NotImplementedError + defaults.plot_results(self, samples) diff --git a/test_autofit/database/identifier/test_identifiers.py b/test_autofit/database/identifier/test_identifiers.py index de63b8119..cc179deb3 100644 --- a/test_autofit/database/identifier/test_identifiers.py +++ b/test_autofit/database/identifier/test_identifiers.py @@ -486,7 +486,8 @@ def test_mcmc_identifiers_unchanged_by_clipper(): def test_nested_samplers_have_no_clipper(): """ Tripwire for the hard constraint of PyAutoFit#1493: the clipper is resolved - on AbstractMLE and must stay there. Hoisting it to NonLinearSearch would put + by the point-estimate searches (``posterior_kind.POINT``, formerly + ``AbstractMLE``) and must stay there. Hoisting it to NonLinearSearch would put it within reach of the nested samplers' identifier machinery and silently re-key the nested-sampling archive; this fails loudly instead. """ @@ -505,7 +506,7 @@ def test_clipper_forks_mle_identifier(cls): def test_drawer_identifier_ignores_clipper(): """ - Drawer inherits the clipper attribute from AbstractMLE but never consumes + Drawer takes the point-estimate clipper (formerly from AbstractMLE) but never consumes it, so a setting that cannot affect its result must not re-key it. """ assert Identifier(af.Drawer()).hash_list == [ diff --git a/test_autofit/non_linear/search/conformance_roster.py b/test_autofit/non_linear/search/conformance_roster.py index 0e6d90687..fc17ec4a5 100644 --- a/test_autofit/non_linear/search/conformance_roster.py +++ b/test_autofit/non_linear/search/conformance_roster.py @@ -396,7 +396,11 @@ class Golden: | { "session", "initializer", - "auto_correlation_settings", + # auto_correlation_settings dropped in A4c: SMC is a weighted-posterior + # search, not a chain. Its former positional slot is caught by the + # deprecated `*legacy_positional` (adversary review 07, finding 4), so old + # positional calls bind as before instead of shifting one slot. + "legacy_positional", "number_of_cores", "batch_size", "inverse_mass_matrix", @@ -522,7 +526,10 @@ class Golden: "Drawer": Golden( identifier="0f80f695c0906253e9526e4c2f242dc7", identifier_fields=("total_draws",), - constructor_arguments=_COMMON | {"session", "initializer", "total_draws"}, + # `clipper` is named explicitly since A4c (it came from `AbstractMLE` before), + # so the serialized argument set is unchanged. + constructor_arguments=_COMMON + | {"session", "initializer", "total_draws", "clipper"}, ), "BFGS": Golden( identifier="979826a042aacbe511b97be84d8c2255", diff --git a/test_autofit/non_linear/search/mcmc/test_blackjax_smc.py b/test_autofit/non_linear/search/mcmc/test_blackjax_smc.py index ce3a09b66..fc509c6a9 100644 --- a/test_autofit/non_linear/search/mcmc/test_blackjax_smc.py +++ b/test_autofit/non_linear/search/mcmc/test_blackjax_smc.py @@ -101,10 +101,10 @@ def test__defaults(): assert search.backend_seed == 42 assert search.inverse_mass_matrix == "none" assert search.is_warm_start is False - # Cold SMC's evidence is only valid if the initial particles are prior draws, so — unlike every other - # `AbstractMCMC` search — the default initializer is `InitializerPrior`, not `InitializerBall`. + # Cold SMC's evidence is only valid if the initial particles are prior draws: SMC is a weighted-posterior + # search (A4c), whose default initializer is `InitializerPrior`, and it takes no auto-correlation settings. assert isinstance(search.initializer, af.InitializerPrior) - assert search.auto_correlation_settings.check_for_convergence is False + assert not hasattr(search, "auto_correlation_settings") def test__explicit_params(): diff --git a/test_autofit/non_linear/search/test_conformance.py b/test_autofit/non_linear/search/test_conformance.py index 78e186602..7bcafdf26 100644 --- a/test_autofit/non_linear/search/test_conformance.py +++ b/test_autofit/non_linear/search/test_conformance.py @@ -89,11 +89,21 @@ def test_default_construction(entry): assert isinstance(cls(), cls) +_KIND = {"mcmc": "chain", "nest": "weighted", "mle": "point"} + + @pytest.mark.parametrize("entry", _params()) def test_family_base(entry): + """ + Since A4c no public search inherits a family base (they are deprecated thin + subclasses); the family survives as the registry's documentation grouping and + the behaviour as the declared ``posterior_kind`` (SMC is ``weighted``). + """ cls = entry.resolve() - assert issubclass(cls, resolve_class_path(FAMILY_BASES[entry.family])) + assert not issubclass(cls, resolve_class_path(FAMILY_BASES[entry.family])) + expected = "weighted" if entry.name == "SMC" else _KIND[entry.family] + assert str(cls.posterior_kind) == expected @pytest.mark.parametrize("entry", _params()) diff --git a/test_autofit/non_linear/search/test_conformance_backend.py b/test_autofit/non_linear/search/test_conformance_backend.py index 52026605b..b73ee0853 100644 --- a/test_autofit/non_linear/search/test_conformance_backend.py +++ b/test_autofit/non_linear/search/test_conformance_backend.py @@ -4,9 +4,9 @@ Every case is parametrised over ``searches_under_test()`` (ids are the short names) and runs the search's real sampler at ``PYAUTO_TEST_MODE=1``, the reduced-budget mode in which each search's ``apply_test_mode`` shrinks its own budget. Budgets are reduced -only through that mode; no search is edited and no budget argument is passed. The one -constructor argument passed (``Emcee``'s ``auto_correlation_settings``) stands in for a -default built at import time; see ``DEFAULT_AUTO_CORRELATION_XFAIL``. +only through that mode; no search is edited and no constructor argument is passed +(since A4c the chain searches build their auto-correlation default at construction, so +``Emcee`` no longer needs one standing in for an import-time default). Per search the suite asserts: @@ -253,33 +253,25 @@ "NSS": "NSSamples", } -# ``Emcee``, ``Zeus``, ``BlackJAXNUTS`` and ``SMC`` take ``auto_correlation_settings= -# AutoCorrelationsSettings()`` as a default argument, built once at import time, so the -# test-mode ``check_size = 1`` reduction applies only when ``PYAUTO_TEST_MODE`` is set -# before ``autofit`` is imported. Set at run time (as here), the default keeps -# ``check_size = 100`` and a 10-step test-mode Emcee chain fails its auto-correlation -# check with ``IndexError``. Per-posterior-kind default objects and a generic -# ``apply_test_mode`` are phase A4. -DEFAULT_AUTO_CORRELATION_XFAIL = { - name: ( - "auto_correlation_settings default is built at import time, so a run-time " - "PYAUTO_TEST_MODE leaves check_size=100; per-kind defaults and a generic " - "apply_test_mode in search-extensibility phase A4." - ) - for name in ("Emcee", "Zeus", "BlackJAXNUTS", "SMC") -} +# Repaired in phase A4c: the chain searches (``Emcee``, ``Zeus``, ``BlackJAXNUTS``) build +# their default ``AutoCorrelationsSettings`` at construction (``posterior_kind.CHAIN``), +# so a run-time ``PYAUTO_TEST_MODE`` reaches the reduced ``check_size``. ``SMC`` is a +# weighted-posterior search and takes no auto-correlation settings. + + +def entry_class_kind(entry): + """The declared ``posterior_kind`` of a roster entry, read from the registry.""" + from autofit.non_linear.search.registry import entry as registry_entry + + return registry_entry(entry.name).capabilities["posterior_kind"] def _construction_overrides(entry) -> dict: """ - Constructor arguments that stand in for a default argument built at import time. - - Only ``Emcee`` needs one: it receives the ``AutoCorrelationsSettings()`` its default - would be had test mode been on at import (see ``DEFAULT_AUTO_CORRELATION_XFAIL``), - so its backend still executes here. No budget is changed. + Constructor arguments that stood in for a default argument built at import time. + None since A4c: the chain searches build their auto-correlation default at + construction (``posterior_kind.CHAIN``). """ - if entry.name == "Emcee": - return {"auto_correlation_settings": af.AutoCorrelationsSettings()} return {} @@ -623,8 +615,8 @@ def test_samples_info_key_set(entry, backend_run): "entry", [ param - for param in _params(DEFAULT_AUTO_CORRELATION_XFAIL, raises=AssertionError) - if param.values[0].family == "mcmc" + for param in _params() + if str(entry_class_kind(param.values[0])) == "chain" ], ) def test_default_auto_correlation_settings_follow_run_time_test_mode( diff --git a/test_autofit/non_linear/search/test_family_bases.py b/test_autofit/non_linear/search/test_family_bases.py new file mode 100644 index 000000000..d67df4c57 --- /dev/null +++ b/test_autofit/non_linear/search/test_family_bases.py @@ -0,0 +1,250 @@ +""" +The family bases out of the MRO (search-extensibility A4c, decision D14). + +``AbstractMCMC`` / ``AbstractNest`` / ``AbstractMLE`` are deprecated thin subclasses of +``NonLinearSearch``: subclassing one warns, and a subclass keeps the former defaults. +The public searches apply their ``posterior_kind`` defaults in their own ``__init__`` +and plot through the per-kind plotter. +""" + +import json +import warnings +from pathlib import Path + +import pytest + +import autofit as af +from autofit.non_linear.initializer import InitializerBall, InitializerPrior +from autofit.non_linear.samples.mcmc import SamplesMCMC +from autofit.non_linear.samples.nest import SamplesNest +from autofit.non_linear.search import posterior_kind +from autofit.non_linear.search.mcmc.abstract_mcmc import AbstractMCMC +from autofit.non_linear.search.mcmc.auto_correlations import AutoCorrelationsSettings +from autofit.non_linear.search.mle.abstract_mle import AbstractMLE +from autofit.non_linear.search.nest.abstract_nest import AbstractNest +from autonerves.dictable import get_class_path + +from test_autofit.non_linear.search.conformance_roster import searches_under_test + + +def _subclass(base): + """Define a minimal external search on a deprecated base, as a user would.""" + + class External(base): + __identifier_fields__ = () + + def _fit(self, model, analysis): + raise NotImplementedError + + return External + + +@pytest.mark.parametrize("base", [AbstractMCMC, AbstractNest, AbstractMLE]) +def test_subclassing_a_deprecated_family_base_warns(base): + with pytest.warns(FutureWarning, match=f"subclasses {base.__name__}"): + _subclass(base) + + +@pytest.mark.parametrize("base", [AbstractMCMC, AbstractNest, AbstractMLE]) +def test_deprecated_bases_are_distinct_classes(base): + assert base is not af.NonLinearSearch + assert issubclass(base, af.NonLinearSearch) + + +def test_deprecated_mcmc_keeps_its_defaults(): + with pytest.warns(FutureWarning): + External = _subclass(AbstractMCMC) + + search = External() + + assert isinstance(search.initializer, InitializerBall) + assert (search.initializer.lower_limit, search.initializer.upper_limit) == ( + 0.49, + 0.51, + ) + assert isinstance(search.auto_correlation_settings, AutoCorrelationsSettings) + assert External.samples_cls is SamplesMCMC + assert not hasattr(search, "clipper") + + +def test_deprecated_nest_keeps_its_defaults(): + with pytest.warns(FutureWarning): + External = _subclass(AbstractNest) + + assert isinstance(External().initializer, InitializerPrior) + assert External.samples_cls is SamplesNest + with pytest.raises(ValueError, match="nested sampling"): + External(initializer=af.InitializerParamBounds({})) + + +def test_deprecated_mle_keeps_its_defaults(): + with pytest.warns(FutureWarning): + External = _subclass(AbstractMLE) + + search = External() + + assert isinstance(search.initializer, InitializerBall) + assert isinstance(search.clipper, af.ClipperNone) + + +def test_public_searches_do_not_warn(): + with warnings.catch_warnings(): + warnings.simplefilter("error", FutureWarning) + for entry in searches_under_test(): + if not entry.missing_requirements(): + entry.resolve()() + + +@pytest.mark.parametrize( + "cls, initializer", + [ + (af.Emcee, InitializerBall), + (af.Zeus, InitializerBall), + (af.BlackJAXNUTS, InitializerBall), + (af.SMC, InitializerPrior), + (af.DynestyStatic, InitializerPrior), + (af.Nautilus, InitializerPrior), + (af.Drawer, InitializerBall), + (af.BFGS, InitializerBall), + (af.MultiStartAdam, InitializerBall), + ], +) +def test_posterior_kind_defaults_applied(cls, initializer): + assert type(cls().initializer) is initializer + + +@pytest.mark.parametrize("cls", [af.DynestyStatic, af.DynestyDynamic, af.Nautilus]) +def test_nested_samplers_still_reject_param_bounds(cls): + with pytest.raises(ValueError, match="nested sampling"): + cls(initializer=af.InitializerParamBounds({})) + + +def test_smc_is_weighted_and_takes_no_auto_correlation_settings(): + search = af.SMC() + + assert str(af.SMC.posterior_kind) == "weighted" + assert af.SMC.produces_evidence is True + assert not hasattr(search, "auto_correlation_settings") + + +def test_old_smc_search_json_with_auto_correlation_settings_loads(caplog): + golden = json.loads( + (Path(__file__).parent / "seed_golden.json").read_text() + ) + old = golden["SMC"]["main_search_json"] + assert "auto_correlation_settings" in old["arguments"] + + loaded = af.from_dict(old) + + assert isinstance(loaded, af.SMC) + assert "unknown keyword argument" not in caplog.text + + +# `samples_info["class_path"]` is the search's `samples_cls`; main 8437a3b76's values. +SAMPLES_CLASS_PATHS = { + "Emcee": "autofit.non_linear.samples.mcmc.SamplesMCMC", + "Zeus": "autofit.non_linear.samples.mcmc.SamplesMCMC", + "BlackJAXNUTS": "autofit.non_linear.samples.mcmc.SamplesMCMC", + "SMC": "autofit.non_linear.search.mcmc.blackjax.smc.samples.SamplesSMC", + "DynestyStatic": "autofit.non_linear.samples.nest.SamplesNest", + "DynestyDynamic": "autofit.non_linear.samples.nest.SamplesNest", + "Nautilus": "autofit.non_linear.samples.nest.SamplesNest", + "NSS": "autofit.non_linear.search.nest.nss.samples.NSSamples", + "Drawer": "autofit.non_linear.samples.samples.Samples", + "BFGS": "autofit.non_linear.samples.samples.Samples", + "LBFGS": "autofit.non_linear.samples.samples.Samples", + "MultiStartAdam": "autofit.non_linear.samples.samples.Samples", + "MultiStartADABelief": "autofit.non_linear.samples.samples.Samples", + "MultiStartLion": "autofit.non_linear.samples.samples.Samples", + "MultiStartProdigy": "autofit.non_linear.samples.samples.Samples", +} + + +@pytest.mark.parametrize("entry", searches_under_test(), ids=lambda e: e.name) +def test_samples_class_path_unchanged(entry): + assert get_class_path(entry.resolve().samples_cls) == SAMPLES_CLASS_PATHS[entry.name] + + +@pytest.mark.parametrize( + "cls, kind", + [(af.Emcee, posterior_kind.CHAIN), (af.SMC, posterior_kind.WEIGHTED), + (af.Nautilus, posterior_kind.WEIGHTED), (af.BFGS, posterior_kind.POINT)], +) +def test_plot_results_dispatches_on_posterior_kind(cls, kind, monkeypatch): + calls = [] + monkeypatch.setattr( + type(kind), "plot_results", lambda self, search, samples: calls.append(self) + ) + + cls().plot_results(samples=None) + + assert calls == [kind] + + +def test_search_without_a_posterior_kind_plots_nothing_of_its_own(): + with pytest.raises(NotImplementedError): + af.m.MockSearch().plot_results(samples=None) + + +# Adversary review 07, finding 4: positional constructor compatibility. + + +def test_drawer_positional_slots_are_unchanged(): + """`Drawer`'s explicit `clipper` is appended, so main's positional calls bind as before.""" + from autofit.non_linear.clipper import ClipperNone + + drawer = af.Drawer(None, None, None, 50, None, 12, 34, True) + + assert drawer.total_draws == 50 + assert drawer.iterations_per_full_update == 12 + assert drawer.iterations_per_quick_update == 34 + assert drawer.silence is True + assert isinstance(drawer.clipper, ClipperNone) + + +def test_drawer_clipper_still_accepted_by_keyword_and_serialized(): + from autofit.non_linear.clipper import ClipperNone + from autonerves.dictable import get_arguments + + assert "clipper" in get_arguments(af.Drawer) + assert isinstance(af.Drawer(clipper=None).clipper, ClipperNone) + assert "clipper" in af.to_dict(af.Drawer())["arguments"] + + +def _smc_positional_prefix(): + # name, path_prefix, unique_tag, num_particles, kernel, num_mcmc_steps, + # num_integration_steps, target_ess, step_size, whiten_inflate, max_smc_steps, + # batch_size, seed, initializer, inverse_mass_matrix + return (None, None, None, 256, "mala", 5, 8, 0.5, None, 2.0, 200, 0, None, None, None) + + +def test_smc_old_positional_auto_correlation_slot_binds_as_before(): + pytest.importorskip("blackjax") + settings = AutoCorrelationsSettings(check_for_convergence=False) + + with pytest.warns(FutureWarning, match="auto_correlation_settings"): + search = af.SMC(*_smc_positional_prefix(), settings, 3, 7, 1, True) + + assert search.iterations_per_quick_update == 3 + assert search.iterations_per_full_update == 7 + assert search.number_of_cores == 1 + assert search.silence is True + assert "auto_correlation_settings" not in af.to_dict(search)["arguments"] + + +def test_smc_too_many_positional_arguments_raise(): + pytest.importorskip("blackjax") + + with pytest.raises(TypeError, match="deprecated positional"): + af.SMC(*_smc_positional_prefix(), None, 3, 7, 1, True, None, "extra") + + +def test_smc_keyword_construction_does_not_warn(): + pytest.importorskip("blackjax") + + with warnings.catch_warnings(): + warnings.simplefilter("error", FutureWarning) + search = af.SMC(iterations_per_quick_update=3, silence=True) + + assert search.iterations_per_quick_update == 3 + assert search.silence is True