diff --git a/autofit/config/visualize/plots_settings.yaml b/autofit/config/visualize/plots_settings.yaml index 9237a1cf2..d328668fc 100644 --- a/autofit/config/visualize/plots_settings.yaml +++ b/autofit/config/visualize/plots_settings.yaml @@ -1,4 +1,5 @@ corner_anesthetic: + compact_backend: anesthetic # Opt-in 'array' accelerates supported compact plots; other styles/versions fall back. figsize_per_parammeter: 4 # The figsize of the matplotlib figure is given as the number of parameters times this value, for exmaple with 3 free parameters and a value 4 the figsize will be 3*4 = 12. 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. @@ -6,4 +7,4 @@ corner_anesthetic: 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 + fontsize: 14 # The size of the font of the tick values and parameter labels on the x and y axis of the corner plot. diff --git a/autofit/non_linear/plot/compact_corner.py b/autofit/non_linear/plot/compact_corner.py new file mode 100644 index 000000000..02dac8f6f --- /dev/null +++ b/autofit/non_linear/plot/compact_corner.py @@ -0,0 +1,165 @@ +"""Opt-in array renderer for a narrowly supported anesthetic compact corner. + +Keep the public anesthetic axes and 1D KDE. Only the repeated dataframe dispatch +and histogram range calculation are replaced. Unsupported inputs are rejected +by ``prepare`` before any artists are drawn, so callers can use the normal path. +No cache or patched library function survives a figure. +""" + +# Histogram compatibility semantics adapted from anesthetic.plot.hist_plot_2d. +# MIT License +# +# Copyright (c) 2019 Will Handley +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +from importlib.metadata import version + +import numpy as np + + +KINDS = {"diagonal": "kde_1d", "lower": "hist_2d"} +# The adapter reproduces this backend's post-processing. Other versions retain +# the established renderer until they have their own real-runtime parity tests. +VERSIONS = {"anesthetic": "2.16.0", "pandas": "3.0.6", "matplotlib": "3.11.2"} +COMMON = {"alpha", "label", "color", "q", "density"} +LOWER = COMMON | {"bins", "range", "levels", "cmin", "cmax", "vmin", "vmax", "snap"} +DIAGONAL = COMMON | {"bw_method", "bw_scale", "ngrid_kde", "order", "clip_to_zero"} + + +def prepare(data, weights, axes_settings, plot_settings): + """Return figure-local arrays/options, or None to select the full backend.""" + if any(version(package) != expected for package, expected in VERSIONS.items()): + return None + if axes_settings.get("upper") is not False: + return None + if set(axes_settings) - {"upper", "figsize", "facecolor", "dpi"}: + return None + if plot_settings.get("kinds") != KINDS: + return None + if set(plot_settings) - (COMMON | {"kinds", "lower_kwargs", "diagonal_kwargs"}): + return None + lower = plot_settings.get("lower_kwargs", {}) + diagonal = plot_settings.get("diagonal_kwargs", {}) + if not isinstance(lower, dict) or not isinstance(diagonal, dict): + return None + if set(lower) - LOWER or set(diagonal) - DIAGONAL: + return None + common = {k: v for k, v in plot_settings.items() if k in COMMON} + # Samples.plot_2d gives common kwargs precedence over panel kwargs. + lower, diagonal = {**lower, **common}, {**diagonal, **common} + # Pandas substitutes series names / stringifies None for non-string labels. + # Leave those conventions to the original dispatcher. + if any("label" in opts and not isinstance(opts["label"], str) for opts in (lower, diagonal)): + return None + from matplotlib.colors import is_color_like + + if any("color" in opts and not is_color_like(opts["color"]) for opts in (lower, diagonal)): + return None + data, weights = np.asarray(data), np.asarray(weights) + if ( + data.ndim != 2 or data.dtype != np.float64 or data.shape[0] < 2 + or data.shape[1] < 2 or weights.shape != (data.shape[0],) + or weights.dtype != np.float64 or not np.isfinite(data).all() + or not np.isfinite(weights).all() or np.any(weights < 0) + or not np.isfinite(weights.sum()) or np.count_nonzero(weights) < 2 + ): + return None + # Anesthetic jitters constant KDE columns using global random state. Keep + # that behavior on the original path rather than inventing a new policy. + if np.any(np.ptp(data[weights > 0], axis=0) == 0): + return None + from anesthetic.utils import quantile + from anesthetic.plot import quantile_plot_interval + + q = quantile_plot_interval(lower.get("q", 5)) + bounds = [quantile(column, [q[0], q[-1]], weights) for column in data.T] + return data, weights, bounds, lower, diagonal + + +def histogram(ax, x, y, weights, bounds, options): + """Weighted linear histogram with precomputed anesthetic quantile bounds.""" + from anesthetic.plot import basic_cmap + from anesthetic.utils import iso_probability_contours + from matplotlib.patches import Rectangle + + opts = options.copy() + opts.pop("q", None) + density = opts.pop("density", False) + bins = opts.pop("bins", 10) + limits = opts.pop("range", bounds) + levels = opts.pop("levels", None) + cmin, cmax = opts.pop("cmin", None), opts.pop("cmax", None) + label = opts.pop("label", None) + # Match the native color-cycle advancement, even with an explicit color. + color = opts.pop("color", ax._get_lines.get_next_color()) + cmap = basic_cmap(color) + pdf, xedges, yedges = np.histogram2d( + x, y, bins=bins, range=limits, density=density, weights=weights + ) + if levels is not None: + levels = iso_probability_contours(pdf, levels) + [pdf.max()] + pdf = np.asarray(levels)[np.digitize(pdf, levels, right=True)] + pdf = np.ma.masked_array(pdf, pdf < levels[1]) + if cmin is not None: + pdf[pdf < cmin] = np.ma.masked + if cmax is not None: + pdf[pdf > cmax] = np.ma.masked + image = ax.pcolormesh( + xedges, yedges, pdf.T, cmap=cmap, vmin=opts.pop("vmin", 0), + snap=opts.pop("snap", True), **opts + ) + ax.add_patch(Rectangle((0, 0), 0, 0, fc=cmap(.999), ec=cmap(.32), lw=2, label=label)) + return image + + +def draw(axes, prepared): + """Draw the prepared compact figure and apply the shared-axis pass once.""" + from anesthetic.plot import kde_plot_1d + from matplotlib import rcParams + from pandas.plotting._matplotlib.core import handle_shared_axes + + data, weights, bounds, lower, diagonal = prepared + columns = list(axes.columns) + for y, row in axes.iterrows(): + j = columns.index(y) + for i, (x, ax) in enumerate(row.items()): + if ax is None: + continue + if x == y: + kde_plot_1d(ax.twin, data[:, i], weights=weights, **diagonal) + ax.twin.grid(rcParams["axes.grid"]) + ax.twin.set_yticks([]) + ax.twin.set_ylim(bottom=0) + else: + histogram(ax, data[:, i], data[:, j], weights, (bounds[i], bounds[j]), lower) + ax.grid(rcParams["axes.grid"]) + ax.set_xlabel(x) + ax.set_ylabel(y) + axes._set_logticks() + fig = axes.iloc[-1, 0].figure + all_axes = [ax for ax in fig.axes if ax.get_subplotspec() is not None] + nrows = len({ax.get_position().y0 for ax in all_axes}) + ncols = len({ax.get_position().x0 for ax in all_axes}) + handle_shared_axes(axarr=all_axes, nplots=len(all_axes), naxes=nrows*ncols, + nrows=nrows, ncols=ncols, sharex=False, sharey=False) + for ax in all_axes: + twin = getattr(ax, "twin", None) + if twin is not None and twin is not ax: + twin.set_xlim(ax.get_xlim(), auto=None) diff --git a/autofit/non_linear/plot/nest_plotters.py b/autofit/non_linear/plot/nest_plotters.py index 5d310b876..11723e335 100644 --- a/autofit/non_linear/plot/nest_plotters.py +++ b/autofit/non_linear/plot/nest_plotters.py @@ -10,6 +10,7 @@ output_figure, accepted_kwarg_names, checked_kwargs, + PlotKwargsError, ) # Above this many plotted parameters a corner plot is drawn in a compact style @@ -129,8 +130,18 @@ def corner_anesthetic( component's declared conversion is applied to the samples (a shear's components become its magnitude and angle, say) and parameters without one pass through; see ``AbstractPriorModel.latent_parameters_from``. + compact_backend + Optional keyword: ``"anesthetic"`` (default) or experimental ``"array"``. + The array backend reuses weighted histogram ranges on finite float64 + compact plots. Unsupported styles, data and dependency versions use + the established anesthetic backend; no samples are thinned. """ config_dict = conf.instance["visualize"]["plots_settings"]["corner_anesthetic"] + compact_backend = kwargs.pop( + "compact_backend", _setting(config_dict, "compact_backend", "anesthetic") + ) + if compact_backend not in ("anesthetic", "array"): + raise PlotKwargsError("compact_backend must be 'anesthetic' or 'array'") from anesthetic.samples import NestedSamples from anesthetic import make_2d_axes @@ -238,6 +249,14 @@ def corner_anesthetic( {key: value for key, value in kwargs.items() if key not in axes_names} ) + prepared = None + if compact_backend == "array": + from autofit.non_linear.plot import compact_corner + + prepared = compact_corner.prepare( + parameter_array, samples.weight_list, axes_settings, plot_settings + ) + fig, axes = make_2d_axes( columns, labels=labels_map, @@ -247,11 +266,11 @@ def corner_anesthetic( if SettingWithCopyWarning is not None: warnings.filterwarnings("default", category=SettingWithCopyWarning) - with _deferred_shared_axes(): - nested_samples.plot_2d( - axes, - **plot_settings, - ) + if prepared is not None: + compact_corner.draw(axes, prepared) + else: + 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)), diff --git a/test_autofit/non_linear/plot/test_compact_corner.py b/test_autofit/non_linear/plot/test_compact_corner.py new file mode 100644 index 000000000..2003c3037 --- /dev/null +++ b/test_autofit/non_linear/plot/test_compact_corner.py @@ -0,0 +1,159 @@ +"""Exact same-runtime parity: no image tolerance is permitted by this adapter.""" +import matplotlib +import numpy as np +import pytest +from copy import deepcopy + +matplotlib.use("Agg") + +from autofit.non_linear.plot import compact_corner, nest_plotters +from autofit.non_linear.plot.plot_util import PlotKwargsError +from test_autofit.non_linear.plot.test_nest_plotters import _samples_with, _label_state + + +@pytest.fixture(autouse=True) +def cleanup(): + yield + import matplotlib.pyplot as plt + + plt.close("all") + + +def require_supported(): + if any(compact_corner.version(p) != v for p, v in compact_corner.VERSIONS.items()): + pytest.skip("Real-runtime equivalence requires the explicitly supported versions") + + +def render(samples, backend, monkeypatch, **kwargs): + import matplotlib.pyplot as plt + + written = [] + monkeypatch.setattr(nest_plotters, "output_figure", lambda **kw: written.append(kw)) + np.random.seed(10) + nest_plotters.corner_anesthetic( + samples, compact_backend=backend, kinds=compact_corner.KINDS, + upper=False, figsize=(5, 5), dpi=70, **deepcopy(kwargs) + ) + assert written, "A swallowed plotting error is not successful fallback" + fig = plt.gcf() + fig.canvas.draw() + return fig, np.asarray(fig.canvas.buffer_rgba()).copy() + + +@pytest.mark.parametrize("options", [ + {}, {"q": .8, "density": True, "color": "darkred", "alpha": .4}, + {"lower_kwargs": {"bins": 17, "q": (0.1, .9)}}, + {"lower_kwargs": {"bins": [7, 12], "range": [[-2, 2], [-3, 3]], + "levels": [.95, .68], "cmin": .01, "cmax": 100}}, + {"diagonal_kwargs": {"bw_scale": 1.5, "ngrid_kde": 64}}, + {"parameter_indices": [2, 0]}, +]) +def test_real_runtime_exact_parity(monkeypatch, options): + require_supported() + samples = _samples_with(3, n_samples=120) + samples.model.parameter_labels_with_superscripts_latex = ["$x$", "$x$", "$z$"] + samples.weight_list[0:10] = [0.] * 10 + baseline, original = render(samples, "anesthetic", monkeypatch, **options) + calls = [] + draw = compact_corner.draw + def witnessed(*args): + calls.append(True) + return draw(*args) + monkeypatch.setattr(compact_corner, "draw", witnessed) + candidate, actual = render(samples, "array", monkeypatch, **options) + assert calls == [True] + assert _label_state(candidate) == _label_state(baseline) + for a, b in zip(candidate.axes, baseline.axes): + assert len(a.lines) == len(b.lines) + assert len(a.collections) == len(b.collections) + for left, right in zip(a.lines, b.lines): + np.testing.assert_array_equal(left.get_xydata(), right.get_xydata()) + for left, right in zip(a.collections, b.collections): + np.testing.assert_array_equal(left.get_array(), right.get_array()) + np.testing.assert_array_equal(left.get_coordinates(), right.get_coordinates()) + np.testing.assert_array_equal(actual, original) + + +@pytest.mark.parametrize("mutation", ["nan", "float32", "constant", "negative", "version", "style", "label_none"]) +def test_unsupported_inputs_fall_back_before_drawing(monkeypatch, mutation): + samples = _samples_with(3, n_samples=80) + options = {} + if mutation == "nan": + samples.parameter_lists[0][0] = float("nan") + elif mutation == "float32": + samples.parameter_lists = np.asarray(samples.parameter_lists, dtype=np.float32) + elif mutation == "constant": + samples.parameter_lists = np.asarray(samples.parameter_lists) + samples.parameter_lists[:, 0] = 1. + assert compact_corner.prepare(samples.parameter_lists, samples.weight_list, + {"upper": False}, {"kinds": compact_corner.KINDS}) is None + # The baseline KDE itself fails for this degenerate fixture; the adapter + # must delegate, not present an empty figure as a successful new path. + from anesthetic.samples import NestedSamples + seen = [] + monkeypatch.setattr(NestedSamples, "plot_2d", lambda *a, **kw: seen.append(True)) + monkeypatch.setattr(compact_corner, "draw", lambda *a: pytest.fail("partial draw")) + render(samples, "array", monkeypatch) + assert seen == [True] + return + elif mutation == "negative": + # Probe preparation only: negative weights are not valid KDE data. + weights = np.asarray(samples.weight_list) + weights[0] = -1 + assert compact_corner.prepare(np.asarray(samples.parameter_lists), weights, + {"upper": False}, {"kinds": compact_corner.KINDS}) is None + return + elif mutation == "version": + monkeypatch.setattr(compact_corner, "version", lambda p: "unvalidated") + elif mutation == "label_none": + options["label"] = None + else: + options["diagonal_kwargs"] = {"linewidth": 2} + monkeypatch.setattr(compact_corner, "draw", lambda *a: pytest.fail("fallback drew partially")) + baseline, original = render(samples, "anesthetic", monkeypatch, **options) + candidate, actual = render(samples, "array", monkeypatch, **options) + np.testing.assert_array_equal(actual, original) + + +def test_invalid_backend_is_not_swallowed(): + with pytest.raises(PlotKwargsError, match="compact_backend"): + nest_plotters.corner_anesthetic(_samples_with(2), compact_backend="unknown") + + +def test_quantile_cache_is_local_and_per_column(monkeypatch): + require_supported() + import anesthetic.utils + + calls = [] + original = anesthetic.utils.quantile + def count(*args, **kwargs): + calls.append(1) + return original(*args, **kwargs) + monkeypatch.setattr(anesthetic.utils, "quantile", count) + samples = _samples_with(4) + for _ in range(2): + prepared = compact_corner.prepare(np.asarray(samples.parameter_lists), samples.weight_list, + {"upper": False}, {"kinds": compact_corner.KINDS}) + assert prepared is not None + assert len(calls) == 8 + + +def test_automatic_compact_style_and_global_state(monkeypatch): + require_supported() + import matplotlib.pyplot as plt + from pandas.plotting._matplotlib import core + + samples = _samples_with(11, n_samples=60) + samples.weight_list = [1.] * 60 + handler = core.handle_shared_axes + images = [] + monkeypatch.setattr(nest_plotters, "output_figure", lambda **kw: None) + for backend in ("anesthetic", "array"): + nest_plotters.corner_anesthetic(samples, compact_backend=backend, figsize=(6, 6), dpi=60) + fig = plt.gcf() + assert len(fig.axes) == 77 + fig.canvas.draw() + images.append(np.asarray(fig.canvas.buffer_rgba()).copy()) + assert core.handle_shared_axes is handler + plt.close(fig) + np.testing.assert_array_equal(*images)