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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions autofit/config/visualize/plots_settings.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
124 changes: 118 additions & 6 deletions autofit/non_linear/plot/nest_plotters.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import numpy as np
import warnings
from contextlib import contextmanager

from autonerves import conf

Expand All @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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",
Expand Down
6 changes: 5 additions & 1 deletion autofit/non_linear/plot/plot_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
55 changes: 47 additions & 8 deletions autofit/non_linear/search/posterior_kind.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
28 changes: 20 additions & 8 deletions autofit/non_linear/search/updater.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -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
Expand Down
13 changes: 13 additions & 0 deletions autofit/non_linear/search/updates.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading