diff --git a/autofit/config/visualize/plots_settings.yaml b/autofit/config/visualize/plots_settings.yaml index 63ff3b3cf..9237a1cf2 100644 --- a/autofit/config/visualize/plots_settings.yaml +++ b/autofit/config/visualize/plots_settings.yaml @@ -3,5 +3,7 @@ corner_anesthetic: fontsize: 20 # The size of the font of the tick values and parameter labels on the x and y axis of the corner plot. facecolor: white # The facecolor of the corner plot. alpha: 0.9 # The alpha value of the corner plot. + max_detailed_parameters: 10 # Above this many plotted parameters the corner plot is compact: 2D histograms instead of KDE contours (about a second per panel) and no upper triangle. + max_parameters_search: 30 # A search skips its full corner plot of a model with more free parameters than this (the per-component plots are still made). corner_cornerpy: fontsize: 14 # The size of the font of the tick values and parameter labels on the x and y axis of the corner plot. \ No newline at end of file diff --git a/autofit/non_linear/plot/nest_plotters.py b/autofit/non_linear/plot/nest_plotters.py index c7eba5276..5d310b876 100644 --- a/autofit/non_linear/plot/nest_plotters.py +++ b/autofit/non_linear/plot/nest_plotters.py @@ -1,5 +1,6 @@ import numpy as np import warnings +from contextlib import contextmanager from autonerves import conf @@ -11,6 +12,88 @@ checked_kwargs, ) +# Above this many plotted parameters a corner plot is drawn in a compact style +# (2D histograms instead of KDE contours, no upper triangle) unless the caller +# or the config says otherwise. A KDE contour panel costs about a second and +# there are n(n-1)/2 of them, so 20 parameters would spend minutes on contours. +DEFAULT_MAX_DETAILED_PARAMETERS = 10 + + +def _setting(config_dict, name, default): + """A ``corner_anesthetic`` setting, or ``default`` for an older config without it.""" + try: + return config_dict[name] + except KeyError: + return default + + +@contextmanager +def _deferred_shared_axes(): + """ + Run pandas' shared-axis label pass once at the end instead of once per panel. + + Every panel anesthetic draws goes through a pandas plot call, and each one + finishes with ``handle_shared_axes``: a pass over *every* axis of the figure + that hides the tick and axis labels of inner panels. A corner plot of n + parameters makes about n^2/2 such calls over about n^2 axes, so the label + pass costs n^4 -- the bulk of a 20-parameter plot's 40+ minutes. The pass is + idempotent, so deferring it and replaying each distinct call once after the + last panel gives the same figure for a fraction of the cost: pixel-identical + for the styles ``corner_anesthetic`` draws (checked against per-panel + passes for the default, compact, subset and latent plots). A caller's own + ``kinds`` can still differ slightly in axis padding (``hist_1d`` diagonals + on two parameters), never in where the posterior is drawn. + + ``handle_shared_axes`` is private to pandas: if it is missing, or is ever + called in a form this does not recognise, the plot just runs unpatched. + """ + try: + from pandas.plotting._matplotlib import core as pandas_core + + original = pandas_core.handle_shared_axes + except (ImportError, AttributeError): + yield + return + + pending = {} + + def defer(*args, **kwargs): + try: + key = tuple( + (name, value) for name, value in kwargs.items() if name != "axarr" + ) + hash(key) + except TypeError: + key = None + + if args or key is None: + return original(*args, **kwargs) + + # Keep the latest call per argument set: its ``axarr`` covers every + # axis drawn so far. + pending.pop(key, None) + pending[key] = kwargs + + pandas_core.handle_shared_axes = defer + try: + yield + finally: + pandas_core.handle_shared_axes = original + + for kwargs in pending.values(): + original(**kwargs) + + # A diagonal panel draws its 1D curve on a twin of the panel's axes, + # which must span the same x range as the panel and its column. Run per + # panel, the label pass settled each twin's limits as it went; run once + # at the end, the last twin settles on its own curve's range and the + # curve is drawn shifted against the tick labels. Re-impose the + # parent's range, leaving every autoscale setting as it was. + for ax in kwargs.get("axarr", ()): + twin = getattr(ax, "twin", None) + if twin is not None and twin is not ax: + twin.set_xlim(ax.get_xlim(), auto=None) + @skip_in_test_mode @log_plot_exception @@ -28,6 +111,12 @@ def corner_anesthetic( or, with ``parameter_indices``, over a subset of them (the parameters of one model component, say) so that a many-parameter fit stays readable. + With more plotted parameters than the ``max_detailed_parameters`` setting + (``visualize/plots_settings``, default 10) the plot is drawn compactly: 2D + histograms instead of KDE contours in the lower triangle and no upper + triangle, as the full style would take minutes. Pass ``kinds`` or + ``upper`` to choose yourself. + Parameters ---------- samples @@ -79,13 +168,19 @@ def corner_anesthetic( # which @log_plot_exception reports as an unconverged posterior, so the plot # silently never appears. Key the columns by position, which is always unique, # and pass the LaTeX labels for display only. + # + # The labels are not attached to the samples themselves: anesthetic then keys + # its columns by a (name, label) MultiIndex and copies it for every panel, + # which is half the cost of a 20-parameter plot. The axes are labelled from + # ``labels_map`` instead, both when made and again after ``plot_2d``, which + # labels the edge panels by column name. columns = [f"p{i}" for i in range(len(labels))] + labels_map = dict(zip(columns, labels)) nested_samples = NestedSamples( parameter_array, weights=samples.weight_list, columns=columns, - labels=labels, ) try: @@ -124,23 +219,40 @@ def corner_anesthetic( ) plot_settings = dict(alpha=config_dict["alpha"], label="posterior") + + # Above ``max_detailed_parameters`` a corner plot is drawn in its compact + # style: 2D histograms in the lower triangle instead of KDE contours (about a + # second per panel) and no upper triangle, whose scatter panels repeat the + # lower triangle's pairs and double the axes to build, plot and save. A + # caller's ``kind`` / ``kinds`` / ``upper`` always wins. + max_detailed_parameters = _setting( + config_dict, "max_detailed_parameters", DEFAULT_MAX_DETAILED_PARAMETERS + ) + if len(labels) > max_detailed_parameters and not ( + {"kind", "kinds", "upper"} & set(kwargs) + ): + plot_settings["kinds"] = {"diagonal": "kde_1d", "lower": "hist_2d"} + axes_settings["upper"] = False + plot_settings.update( {key: value for key, value in kwargs.items() if key not in axes_names} ) fig, axes = make_2d_axes( columns, - labels=nested_samples.get_labels_map(), + labels=labels_map, **axes_settings, ) if SettingWithCopyWarning is not None: warnings.filterwarnings("default", category=SettingWithCopyWarning) - nested_samples.plot_2d( - axes, - **plot_settings, - ) + with _deferred_shared_axes(): + nested_samples.plot_2d( + axes, + **plot_settings, + ) + axes.set_labels(labels_map) axes.iloc[-1, 0].legend( bbox_to_anchor=(len(axes) / 2, len(axes)), loc="lower center", diff --git a/autofit/non_linear/plot/plot_util.py b/autofit/non_linear/plot/plot_util.py index 8dc55a171..f04a0e096 100644 --- a/autofit/non_linear/plot/plot_util.py +++ b/autofit/non_linear/plot/plot_util.py @@ -148,5 +148,9 @@ def output_figure(path=None, filename="figure", format="show"): elif format in ("png", "pdf"): if path is not None: os.makedirs(path, exist_ok=True) - plt.savefig(Path(path) / f"{filename}.{format}") + # ``fig.savefig``, not ``plt.savefig``: pyplot's version follows the + # save with ``canvas.draw_idle()``, which on the non-interactive Agg + # canvas renders the whole figure a second time -- 10+ s for a + # many-parameter corner plot, for a figure about to be closed. + plt.gcf().savefig(Path(path) / f"{filename}.{format}") plt.close() diff --git a/autofit/non_linear/search/posterior_kind.py b/autofit/non_linear/search/posterior_kind.py index 92fe9e435..1fc414974 100644 --- a/autofit/non_linear/search/posterior_kind.py +++ b/autofit/non_linear/search/posterior_kind.py @@ -34,6 +34,12 @@ class PosteriorDefaults: kind: PosteriorKind = None plots_section: str = None + # Whether ``plot_results`` runs at every ``iterations_per_full_update`` as + # well as once the fit is complete. Progress plots (a point search's + # likelihood against iteration) are worth watching live; a posterior's + # corner plot is not -- it needs converged samples and is the slowest plot + # a search makes -- so the chain and weighted kinds draw theirs at the end. + plots_during_fit: bool = True def initializer_for(self, initializer=None): """The search's initializer: ``initializer``, or this kind's default.""" @@ -68,6 +74,7 @@ def plot_latent_results(self, search, samples): class ChainDefaults(PosteriorDefaults): kind = PosteriorKind.CHAIN plots_section = "mcmc" + plots_during_fit = False def default_initializer(self): from autofit.non_linear.initializer import InitializerBall @@ -107,6 +114,7 @@ def plot_results(self, search, samples): class WeightedDefaults(PosteriorDefaults): kind = PosteriorKind.WEIGHTED plots_section = "nest" + plots_during_fit = False def default_initializer(self): from autofit.non_linear.initializer import InitializerPrior @@ -136,19 +144,50 @@ def plot_results(self, search, samples): corner = self.should_plot("corner_anesthetic") - if corner: - corner_anesthetic(samples=samples, path=path, format="png") - # An older config without the key: the per-component plots follow # the full one, so switching that off switches them off too. - if self.should_plot("corner_anesthetic_components", default=corner): + components = self.should_plot( + "corner_anesthetic_components", default=corner + ) + groups = samples.model.parameter_indices_by_component if components else {} + + if corner and self._too_many_parameters_for_full_corner(samples): + logger.info( + "Skipping the full corner_anesthetic plot: the model has more " + "free parameters than corner_anesthetic.max_parameters_search " + "(visualize/plots_settings). " + + ( + "The per-component corner plots are still made." + if len(groups) >= 2 + else "No corner plot is made; plot a subset with " + "corner_anesthetic(samples, parameter_indices=...)." + ) + ) + elif corner: + corner_anesthetic(samples=samples, path=path, format="png") + + if components: self._corner_per_component( - corner_anesthetic, - samples, - path, - groups=samples.model.parameter_indices_by_component, + corner_anesthetic, samples, path, groups=groups ) + @staticmethod + def _too_many_parameters_for_full_corner(samples) -> bool: + """ + Whether the model is too big for one corner plot of every parameter, + per ``corner_anesthetic.max_parameters_search`` (30 for an older config + without the key). Past that the full plot is large and slow to draw, + and the per-component plots are the readable ones anyway. + """ + total = getattr(samples.model, "total_free_parameters", None) + if not isinstance(total, int): + return False + + from autofit.non_linear.plot.nest_plotters import _setting + + settings = conf.instance["visualize"]["plots_settings"]["corner_anesthetic"] + return total > _setting(settings, "max_parameters_search", 30) + def plot_latent_results(self, search, samples): """ The corner plot(s) of the latent parameters: each component's sampled diff --git a/autofit/non_linear/search/updater.py b/autofit/non_linear/search/updater.py index a13b9da36..fe745e142 100644 --- a/autofit/non_linear/search/updater.py +++ b/autofit/non_linear/search/updater.py @@ -77,11 +77,16 @@ def __init__( iterations_per_full_update: float, visualization_enabled: bool = True, plot_latent_results_func: Optional[Callable[[Samples], None]] = None, + plot_results_during_fit: bool = True, ): self._paths = paths self._timer = timer self._logger = search_logger self._plot_results = plot_results_func + # False for searches whose plots summarise the posterior (corner plots): + # those need converged samples, so they are made once the fit is + # complete rather than at every ``iterations_per_full_update``. + self._plot_results_during_fit = plot_results_during_fit # The plots of the latent parameters, made with the other latent output # (``latent.csv``): after the fit, and during it only when # ``output.yaml``'s ``latent_during_fit`` is on. None plots nothing. @@ -178,7 +183,9 @@ def visualize( Perform visualization of the non-linear search's model-fitting results. Delegates to the analysis object for model-specific plots and to the - search's ``plot_results`` for search-specific plots. The search's + search's ``plot_results`` for search-specific plots -- at every update + for a search whose plots show progress, once the fit is complete for one + whose plots summarise the posterior (``plot_results_during_fit``). The search's ``plot_latent_results`` follows the latent-output rule rather than the ``iterations_per_full_update`` cadence: once the fit is complete, and during it only if ``output.yaml``'s ``latent_during_fit`` is on. ``update`` passes the @@ -218,8 +225,15 @@ def visualize( during_analysis=during_analysis, ) - if plot_search and analysis.should_visualize( - paths=paths, during_analysis=during_analysis + plot_results = not during_analysis or self._plot_results_during_fit + plot_latent = self._plot_latent_results is not None and ( + not during_analysis or conf.instance["output"]["latent_during_fit"] + ) + + if ( + plot_search + and (plot_results or plot_latent) + and analysis.should_visualize(paths=paths, during_analysis=during_analysis) ): if not isinstance(paths, NullPaths): try: @@ -229,12 +243,10 @@ def visualize( search_internal, ) - self._plot_results(samples=samples) + if plot_results: + self._plot_results(samples=samples) - if self._plot_latent_results is not None and ( - not during_analysis - or conf.instance["output"]["latent_during_fit"] - ): + if plot_latent: self._plot_latent_results(samples=samples) except FileNotFoundError: pass diff --git a/autofit/non_linear/search/updates.py b/autofit/non_linear/search/updates.py index 8279119c0..cf266dfe9 100644 --- a/autofit/non_linear/search/updates.py +++ b/autofit/non_linear/search/updates.py @@ -124,6 +124,7 @@ def _updater(self): timer=self.timer, search_logger=self.logger, plot_results_func=self.plot_results, + plot_results_during_fit=self.plots_results_during_fit, plot_latent_results_func=self.plot_latent_results, samples_from_func=self.samples_from, disable_output=self.disable_output, @@ -197,6 +198,18 @@ def plot_results(self, samples): raise NotImplementedError defaults.plot_results(self, samples) + @property + def plots_results_during_fit(self) -> bool: + """ + Whether ``plot_results`` runs at every ``iterations_per_full_update`` or + only once the fit is complete, by the search's ``posterior_kind`` + (``PosteriorDefaults.plots_during_fit``). + """ + from autofit.non_linear.search.posterior_kind import defaults_for + + defaults = defaults_for(type(self).posterior_kind) + return True if defaults is None else defaults.plots_during_fit + def plot_latent_results(self, samples): """ The search's plots of the model's latent parameters (the corner plot of diff --git a/test_autofit/non_linear/plot/test_nest_plotters.py b/test_autofit/non_linear/plot/test_nest_plotters.py index aea9e2f62..b5f1050f6 100644 --- a/test_autofit/non_linear/plot/test_nest_plotters.py +++ b/test_autofit/non_linear/plot/test_nest_plotters.py @@ -142,7 +142,6 @@ def test__corner_anesthetic__parameter_indices_plot_that_subset(monkeypatch, rou seen = {} def fake_plot_2d(self, axes=None, **kwargs): - seen["labels"] = list(self.get_labels()) seen["columns"] = self.shape[1] monkeypatch.setattr(NestedSamples, "plot_2d", fake_plot_2d) @@ -150,7 +149,7 @@ def fake_plot_2d(self, axes=None, **kwargs): nest_plotters.corner_anesthetic(samples=samples, parameter_indices=[0, 2]) assert seen["columns"] == 2 - assert seen["labels"] == ["$a$", "$c$"] + assert list(routed["axes"]["labels"].values()) == ["$a$", "$c$"] assert routed["axes"]["figsize"] == (8, 8) @@ -166,7 +165,6 @@ def test__corner_anesthetic__latent_plots_the_latent_set(monkeypatch, routed): seen = {} def fake_plot_2d(self, axes=None, **kwargs): - seen["labels"] = list(self.get_labels()) seen["first"] = self.to_numpy()[0, 0] monkeypatch.setattr(NestedSamples, "plot_2d", fake_plot_2d) @@ -175,6 +173,174 @@ def fake_plot_2d(self, axes=None, **kwargs): # Two parameters became one, labelled from the latent set's own names, # and the figure is sized to the latent set. - assert seen["labels"] == ["$s$", "$p$"] + assert list(routed["axes"]["labels"].values()) == ["$s$", "$p$"] assert seen["first"] == pytest.approx(sum(samples.parameter_lists[0][:2])) assert routed["axes"]["figsize"] == (8, 8) + + +def _samples_with(n_parameters, n_samples=60, seed=4): + rng = np.random.default_rng(seed) + samples = MockSamples() + samples.model = MockModel([f"$x_{i}$" for i in range(n_parameters)]) + samples.parameter_lists = rng.normal(size=(n_samples, n_parameters)).tolist() + samples.weight_list = rng.random(n_samples).tolist() + return samples + + +def test__corner_anesthetic__few_parameters_keep_anesthetic_default_style(routed): + nest_plotters.corner_anesthetic(samples=_samples_with(3)) + + assert "kinds" not in routed["plot"] + assert "upper" not in routed["axes"] + + +def test__corner_anesthetic__many_parameters_draw_the_compact_style(routed): + # A KDE contour panel costs about a second and there are n(n-1)/2 of them, + # and the upper triangle doubles the axes to build and save, so past the + # threshold the lower triangle is histograms and the upper one is dropped. + n = nest_plotters.DEFAULT_MAX_DETAILED_PARAMETERS + 1 + + nest_plotters.corner_anesthetic(samples=_samples_with(n)) + + assert routed["plot"]["kinds"] == {"diagonal": "kde_1d", "lower": "hist_2d"} + assert routed["axes"]["upper"] is False + + +@pytest.mark.parametrize( + "name, value", [("kind", "kde"), ("kinds", "kde"), ("upper", True)] +) +def test__corner_anesthetic__caller_style_wins_over_the_compact_default( + routed, name, value +): + n = nest_plotters.DEFAULT_MAX_DETAILED_PARAMETERS + 1 + + nest_plotters.corner_anesthetic(samples=_samples_with(n), **{name: value}) + + received = {**routed["axes"], **routed["plot"]} + assert received[name] == value + # anesthetic reads ``kinds`` over ``kind``, so no default may sit beside it. + assert "kinds" not in routed["plot"] or name == "kinds" + assert routed["axes"].get("upper", True) is True + + +def _label_state(fig): + # Limits as well as labels: the 1D curves sit on twin axes whose x range + # must match their panel's, or the curve is drawn against the wrong ticks. + return [ + ( + ax.xaxis.label.get_visible(), + ax.yaxis.label.get_visible(), + [label.get_visible() for label in ax.get_xticklabels()], + [label.get_visible() for label in ax.get_yticklabels()], + tuple(np.round(ax.get_xlim(), 10)), + tuple(np.round(ax.get_ylim(), 10)), + ) + for ax in fig.axes + ] + + +def _draw(samples, deferred): + import matplotlib.pyplot as plt + from anesthetic import make_2d_axes + from anesthetic.samples import NestedSamples + + n = len(samples.model.parameter_labels_with_superscripts_latex) + columns = [f"p{i}" for i in range(n)] + nested = NestedSamples( + np.asarray(samples.parameter_lists), + weights=samples.weight_list, + columns=columns, + labels=samples.model.parameter_labels_with_superscripts_latex, + ) + fig, axes = make_2d_axes(columns, labels=nested.get_labels_map()) + np.random.seed(0) # anesthetic's KDE compression draws random numbers + if deferred: + with nest_plotters._deferred_shared_axes(): + nested.plot_2d(axes) + else: + nested.plot_2d(axes) + fig.canvas.draw() + state = _label_state(fig) + plt.close(fig) + return state + + +def test__deferred_shared_axes__runs_the_label_pass_once_with_the_same_result( + monkeypatch, +): + # pandas runs its shared-axis label pass after every panel, over every axis + # of the figure: n^4 work for an n-parameter corner plot. Deferred, it runs + # once per distinct call and the inner panels' labels end up hidden just as + # before. + from pandas.plotting._matplotlib import core as pandas_core + + samples = _samples_with(4, n_samples=200) + expected = _draw(samples, deferred=False) + + real = pandas_core.handle_shared_axes + calls = [] + + def counting(*args, **kwargs): + calls.append(kwargs) + return real(*args, **kwargs) + + monkeypatch.setattr(pandas_core, "handle_shared_axes", counting) + + assert _draw(samples, deferred=True) == expected + assert len(calls) == 1 + assert pandas_core.handle_shared_axes is counting + + +def test__deferred_shared_axes__restores_pandas_when_the_plot_raises(): + from pandas.plotting._matplotlib import core as pandas_core + + real = pandas_core.handle_shared_axes + + with pytest.raises(RuntimeError): + with nest_plotters._deferred_shared_axes(): + raise RuntimeError("panel failed") + + assert pandas_core.handle_shared_axes is real + + +def test__deferred_shared_axes__positional_call_runs_straight_through(monkeypatch): + # A future pandas calling it positionally must not lose the label pass. + from pandas.plotting._matplotlib import core as pandas_core + + calls = [] + monkeypatch.setattr( + pandas_core, "handle_shared_axes", lambda *args, **kwargs: calls.append(args) + ) + + with nest_plotters._deferred_shared_axes(): + pandas_core.handle_shared_axes(1, 2) + + assert calls == [(1, 2)] + + +def test__corner_anesthetic__edge_panels_show_latex_labels_not_column_keys( + monkeypatch, +): + # The samples are keyed p0, p1, ... without labels (labelled columns are + # copied for every panel, half the cost of a big plot), so the LaTeX labels + # must be put back on the axes after plot_2d names them by column. + import matplotlib.pyplot as plt + + written = [] + monkeypatch.setattr( + nest_plotters, "output_figure", lambda *args, **kwargs: written.append(kwargs) + ) + + nest_plotters.corner_anesthetic(samples=_samples_with(3, n_samples=200), kinds="hist") + + assert written + # Inner panels keep a hidden column-name label, as before; only what is + # drawn matters. + shown = { + axis.label.get_text() + for ax in plt.gcf().axes + for axis in (ax.xaxis, ax.yaxis) + if axis.get_visible() and axis.label.get_visible() and axis.label.get_text() + } + assert shown == {"$x_0$", "$x_1$", "$x_2$"} + plt.close("all") diff --git a/test_autofit/non_linear/plot/test_plot_util.py b/test_autofit/non_linear/plot/test_plot_util.py index 004e3a165..2f56511b4 100644 --- a/test_autofit/non_linear/plot/test_plot_util.py +++ b/test_autofit/non_linear/plot/test_plot_util.py @@ -91,3 +91,31 @@ def test__plot_kwargs_error__is_importable_from_the_public_plot_module(): assert aplt.PlotKwargsError is PlotKwargsError assert issubclass(aplt.PlotKwargsError, TypeError) + + +def test__output_figure__png_renders_the_figure_once(tmp_path, monkeypatch): + # ``plt.savefig`` follows the save with ``canvas.draw_idle()``, which on Agg + # is a second full render; for a big corner plot that is 10+ s wasted. + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + from matplotlib.backends.backend_agg import FigureCanvasAgg + + from autofit.non_linear.plot.plot_util import output_figure + + renders = [] + real_draw = FigureCanvasAgg.draw + + def counting_draw(self, *args, **kwargs): + renders.append(1) + return real_draw(self, *args, **kwargs) + + monkeypatch.setattr(FigureCanvasAgg, "draw", counting_draw) + + plt.figure() + plt.plot([0, 1], [0, 1]) + output_figure(path=tmp_path, filename="line", format="png") + + assert (tmp_path / "line.png").exists() + assert len(renders) == 1 diff --git a/test_autofit/non_linear/search/test_family_bases.py b/test_autofit/non_linear/search/test_family_bases.py index 5d1acfa0d..f636efb73 100644 --- a/test_autofit/non_linear/search/test_family_bases.py +++ b/test_autofit/non_linear/search/test_family_bases.py @@ -611,3 +611,97 @@ def test_weighted_plot_latent_results_skipped_in_test_mode(monkeypatch, tmp_path ) assert not any(call.get("latent") for call in calls) + + +def test_weighted_plot_results_skips_full_corner_of_a_very_big_model( + monkeypatch, tmp_path +): + # Past corner_anesthetic.max_parameters_search the full plot is large and + # slow; the per-component plots are still made. + from autofit.non_linear.search.posterior_kind import WeightedDefaults + + monkeypatch.setattr( + WeightedDefaults, + "_too_many_parameters_for_full_corner", + staticmethod(lambda samples: True), + ) + calls = _weighted_plot_calls(_lens_like_model(), monkeypatch, tmp_path) + + assert [call.get("filename", "corner_anesthetic") for call in calls] == [ + "corner_anesthetic_lens", + "corner_anesthetic_source", + ] + + +@pytest.mark.parametrize("limit, expected", [(3, True), (4, False)]) +def test_too_many_parameters_for_full_corner_reads_config(monkeypatch, limit, expected): + from types import SimpleNamespace + from autofit.non_linear.search import posterior_kind + + monkeypatch.setattr( + posterior_kind, + "conf", + SimpleNamespace( + instance={ + "visualize": { + "plots_settings": { + "corner_anesthetic": {"max_parameters_search": limit} + } + } + } + ), + ) + samples = SimpleNamespace(model=_lens_like_model()) + + assert ( + posterior_kind.WeightedDefaults._too_many_parameters_for_full_corner(samples) + is expected + ) + + +def test_too_many_parameters_for_full_corner_older_config_defaults_to_30(monkeypatch): + from types import SimpleNamespace + from autofit.non_linear.search import posterior_kind + + monkeypatch.setattr( + posterior_kind, + "conf", + SimpleNamespace(instance={"visualize": {"plots_settings": {"corner_anesthetic": {}}}}), + ) + small = SimpleNamespace(model=SimpleNamespace(total_free_parameters=30)) + big = SimpleNamespace(model=SimpleNamespace(total_free_parameters=31)) + + assert not posterior_kind.WeightedDefaults._too_many_parameters_for_full_corner(small) + assert posterior_kind.WeightedDefaults._too_many_parameters_for_full_corner(big) + + +@pytest.mark.parametrize( + "many_components, expected", + [ + (True, "per-component corner plots are still made"), + (False, "No corner plot is made"), + ], +) +def test_skipped_full_corner_logs_what_is_actually_made( + monkeypatch, tmp_path, caplog, many_components, expected +): + # A single-component model has no per-component plots to fall back on, so + # the log must not promise them. + import logging + from autofit.non_linear.search.posterior_kind import WeightedDefaults + + monkeypatch.setattr( + WeightedDefaults, + "_too_many_parameters_for_full_corner", + staticmethod(lambda samples: True), + ) + # Built here, not at collection: component grouping reads the test config. + model = ( + _lens_like_model() + if many_components + else af.Model(af.m.MockClassx2NoSuperScript) + ) + with caplog.at_level(logging.INFO): + _weighted_plot_calls(model, monkeypatch, tmp_path) + + assert expected in caplog.text diff --git a/test_autofit/non_linear/search/test_updater.py b/test_autofit/non_linear/search/test_updater.py index 670620afb..24ef02264 100644 --- a/test_autofit/non_linear/search/test_updater.py +++ b/test_autofit/non_linear/search/test_updater.py @@ -366,3 +366,71 @@ def test__visualize__raising_latent_conversion_is_logged_not_raised( updater._plot_results.assert_called_once_with(samples=samples) assert "latent parameters could not be computed" in caplog.text + + +def _visualize(updater, during_analysis, samples): + analysis = MagicMock() + analysis.should_visualize.return_value = True + updater.visualize( + model=MagicMock(), + analysis=analysis, + during_analysis=during_analysis, + samples_summary=MagicMock(), + samples=samples, + ) + + +def test__visualize__posterior_plots_wait_for_the_end_of_the_fit(): + """ + A search whose plots summarise the posterior (corner plots: nested + sampling, MCMC) makes them once the fit is complete, not at every + ``iterations_per_full_update``: they need converged samples and are the + slowest plots a search makes. + """ + updater = SearchUpdater( + paths=MagicMock(), + timer=MagicMock(), + search_logger=logging.getLogger("test_updater"), + plot_results_func=MagicMock(), + samples_from_func=MagicMock(), + disable_output=False, + iterations_per_full_update=1.0, + plot_results_during_fit=False, + ) + samples = MagicMock() + + _visualize(updater, during_analysis=True, samples=samples) + updater._plot_results.assert_not_called() + updater._samples_from.assert_not_called() # nothing to plot, nothing converted + + _visualize(updater, during_analysis=False, samples=samples) + updater._plot_results.assert_called_once_with(samples=samples) + + +def test__visualize__progress_plots_are_made_during_the_fit(): + updater = _make_updater() + samples = MagicMock() + + _visualize(updater, during_analysis=True, samples=samples) + + updater._plot_results.assert_called_once_with(samples=samples) + + +def test__plots_during_fit__by_posterior_kind(): + from autofit.non_linear.search.posterior_kind import ( + ChainDefaults, + PointDefaults, + WeightedDefaults, + ) + + assert WeightedDefaults.plots_during_fit is False + assert ChainDefaults.plots_during_fit is False + assert PointDefaults.plots_during_fit is True + + +def test__search_passes_its_kind_rule_to_the_updater(): + search = af.Nautilus() + assert search._updater._plot_results_during_fit is False + + search = af.LBFGS() + assert search._updater._plot_results_during_fit is True