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
1 change: 1 addition & 0 deletions autofit/config/general.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ output:
search_internal : false # If True, the search internal folder which contains a saved state of the non-linear search is delete, saving on hard-disk space.
samples_to_csv: true # If True, non-linear search samples are written to a .csv file.
unconverged_sample_size : 100 # If outputting results of an unconverged search, the number of samples used to estimate the median PDF values and errors.
visualize_ep_factor_searches: false # Expectation propagation only. If True, every EP factor search draws its own per-search visuals (e.g. corner plots, model-fit images) and redraws its before-fit visuals. If False, only the first search of each factor draws before-fit visuals and no factor search draws per-search visuals (samples and summaries are still written; the EP optimiser's own graph.png / ep_history output is unaffected).
parallel:
warn_environment_variables: true # If True, a warning is displayed when the search's number of CPU > 1 and enviromment variables related to threading are also > 1.
profiling:
Expand Down
38 changes: 36 additions & 2 deletions autofit/non_linear/search/abstract_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,14 @@ def decorated(self, *args, **kwargs):


class NonLinearSearch(AbstractFactorOptimiser, ABC):
# Visualization switches toggled per factor search by ``optimise`` (EP),
# governed by ``general.yaml -> output -> visualize_ep_factor_searches``.
# Class-level (not set in ``__init__``) so search doubles that skip
# ``__init__`` (e.g. the regression suite's ``StaticSearch``) still have
# them. Outside EP both are always True.
_visualize_fit = True
_visualize_before_fit = True

def __init__(
self,
name: Optional[str] = None,
Expand Down Expand Up @@ -430,7 +438,28 @@ def optimise(
is_flat=True,
)

result = self.fit(model=model, analysis=analysis)
# EP re-enters the same factor search once per EP step. By default only
# the first search of each factor draws its before-fit visuals and no
# factor search draws per-search visuals (corner plots, model-fit
# images): at small per-factor fits the plotting dominates the wall
# time and the images are overwritten every step anyway. Samples and
# summaries are still written, and the EP optimiser's own visuals
# (graph.png, ep_history) are unaffected. `.get` with a default so user
# configs that predate the key keep working.
visualize_ep_factor_searches = bool(
conf.instance["general"]["output"].get(
"visualize_ep_factor_searches", False
)
)

self._visualize_fit = visualize_ep_factor_searches
self._visualize_before_fit = visualize_ep_factor_searches or number == 0

try:
result = self.fit(model=model, analysis=analysis)
finally:
self._visualize_fit = True
self._visualize_before_fit = True

# Record the sampler's log-evidence of this tilted-distribution fit on
# the projected mean field — the per-factor Ẑₐ that README §5 documents
Expand Down Expand Up @@ -755,7 +784,9 @@ def pre_fit_output(
)
analysis.save_attributes(paths=self.paths)

if analysis.should_visualize(paths=self.paths):
if self._visualize_before_fit and analysis.should_visualize(
paths=self.paths
):
analysis.visualize_before_fit(
paths=self.paths,
model=model,
Expand Down Expand Up @@ -1469,6 +1500,9 @@ def _updater(self):
disable_output=self.disable_output,
iterations_per_full_update=self.iterations_per_full_update,
)
# Re-applied on every access: ``optimise`` toggles ``_visualize_fit``
# per EP factor search, and the cached updater must follow it.
self._search_updater.visualization_enabled = self._visualize_fit
return self._search_updater

def perform_update(
Expand Down
10 changes: 10 additions & 0 deletions autofit/non_linear/search/updater.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ def __init__(
samples_from_func: Callable[[AbstractPriorModel, ...], Samples],
disable_output: bool,
iterations_per_full_update: float,
visualization_enabled: bool = True,
):
self._paths = paths
self._timer = timer
Expand All @@ -56,6 +57,10 @@ def __init__(
self._disable_output = disable_output
self._iterations_per_full_update = iterations_per_full_update
self._iterations = 0
# When False, ``visualize`` is a no-op (analysis visuals and the
# search's ``plot_results``). Set per factor search by EP; see
# ``general.yaml -> output -> visualize_ep_factor_searches``.
self.visualization_enabled = visualization_enabled

@property
def iterations(self) -> int:
Expand Down Expand Up @@ -138,7 +143,12 @@ def visualize(

Delegates to the analysis object for model-specific plots and to the
search's ``plot_results`` for search-specific plots.

Returns immediately when ``visualization_enabled`` is False.
"""
if not self.visualization_enabled:
return

self._logger.debug("Visualizing")

paths = paths_override or self._paths
Expand Down
157 changes: 157 additions & 0 deletions test_autofit/graphical/test_ep_factor_search_visuals.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
"""
EP factor searches skip their per-search visuals by default (PyAutoFit #1642).

Expectation propagation re-enters the same factor search once per factor per EP
step. At the small per-factor fits EP is built on, a search's own visuals
(`analysis.visualize`, the corner / fit plots of `plot_results`) dominated the
wall time, and each step overwrote the previous step's images anyway.

`general.yaml -> output -> visualize_ep_factor_searches` (default False) now
governs them: off, only the first search of each factor draws its before-fit
visuals and no factor search draws per-search visuals; on, the old behaviour.
Samples, summaries and the EP optimiser's own output (`graph.info`,
`graph.png`, `ep_history.csv`) are written either way.
"""

import numpy as np
import pytest

from autonerves import conf

import autofit as af

pytestmark = [
pytest.mark.filterwarnings("ignore::FutureWarning"),
pytest.mark.filterwarnings("ignore::RuntimeWarning"),
]


# Module level (not local classes / closures) so the analysis pickles with the
# dynesty checkpoint.
CALLS = []
PLOT_CALLS = []


class RecordingVisualizer(af.Visualizer):
@staticmethod
def visualize_before_fit(analysis, paths, model):
CALLS.append(("visualize_before_fit", paths.analysis_name))

@staticmethod
def visualize(analysis, paths, instance, during_analysis):
CALLS.append(("visualize", paths.analysis_name))


class RecordingAnalysis(af.ex.Analysis):
Visualizer = RecordingVisualizer


def _run_ep(tmp_path, monkeypatch):
"""
Two AnalysisFactors sharing a centre, each fitted by a named DynestyStatic,
two EP steps.

Returns the recorded Visualizer calls, the recorded `plot_results` calls
and the EP output path.
"""
CALLS.clear()
PLOT_CALLS.clear()

def recording_plot_results(self, samples):
PLOT_CALLS.append(self.paths.analysis_name)

monkeypatch.setattr(af.DynestyStatic, "plot_results", recording_plot_results)

x = np.arange(50)
centre = af.GaussianPrior(mean=25.0, sigma=10.0)

# One search object shared by both factors, as a user would build it; the
# prior factors fall back to the Laplace default optimiser.
search = af.DynestyStatic(
name="ep_visuals", nlive=20, maxcall=200, number_of_cores=1
)

factors = []
for i in range(2):
data = af.ex.Gaussian(centre=25.0, normalization=10.0, sigma=5.0).model_data_from(
xvalues=x
)
model = af.Model(
af.ex.Gaussian,
centre=centre,
normalization=af.GaussianPrior(mean=10.0, sigma=5.0),
sigma=af.GaussianPrior(mean=5.0, sigma=2.0),
)
factors.append(
af.AnalysisFactor(
model,
analysis=RecordingAnalysis(data=data, noise_map=np.ones(50)),
name=f"factor_{i}",
optimiser=search,
)
)

factor_graph = af.FactorGraphModel(*factors)

paths = af.DirectoryPaths(name="ep_factor_search_visuals", path_prefix=str(tmp_path))

factor_graph.optimise(
af.LaplaceOptimiser(),
paths=paths,
ep_history=af.EPHistory(kl_tol=None),
max_steps=2,
)

return list(CALLS), list(PLOT_CALLS), paths.output_path


def test__default__factor_searches_skip_per_search_visuals(tmp_path, monkeypatch):
calls, plot_calls, output_path = _run_ep(tmp_path, monkeypatch)

assert [c for c in calls if c[0] == "visualize"] == []
assert plot_calls == []

# Before-fit visuals once per factor: only its first search draws them.
before = sorted(c[1] for c in calls if c[0] == "visualize_before_fit")
assert before == ["factor_0/optimization_0", "factor_1/optimization_0"]

# The EP optimiser's own output is untouched.
assert (output_path / "graph.info").exists()
assert (output_path / "graph.png").exists()
assert (output_path / "ep_history.csv").exists()


def test__key_on__factor_searches_draw_per_search_visuals(tmp_path, monkeypatch):
output = conf.instance["general"]["output"]
original = output.get("visualize_ep_factor_searches", False)
output["visualize_ep_factor_searches"] = True
try:
calls, plot_calls, _ = _run_ep(tmp_path, monkeypatch)
finally:
output["visualize_ep_factor_searches"] = original

visualized = {c[1] for c in calls if c[0] == "visualize"}
assert visualized == {
"factor_0/optimization_0",
"factor_0/optimization_1",
"factor_1/optimization_0",
"factor_1/optimization_1",
}
assert len(plot_calls) == 4

before = sorted(c[1] for c in calls if c[0] == "visualize_before_fit")
assert before == [
"factor_0/optimization_0",
"factor_0/optimization_1",
"factor_1/optimization_0",
"factor_1/optimization_1",
]


def test__visualize_switches_reset_after_optimise(tmp_path, monkeypatch):
"""`optimise` restores the switches, so the search behaves normally afterwards."""
_run_ep(tmp_path, monkeypatch)

search = af.DynestyStatic(name="after", number_of_cores=1)
assert search._visualize_fit is True
assert search._visualize_before_fit is True
32 changes: 32 additions & 0 deletions test_autofit/non_linear/search/test_updater.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,3 +203,35 @@ def test__save_samples__writes_samples_csv_when_the_best_point_is_rejected(
assert instance is None
assert (paths._files_path / "samples.csv").exists()
assert (paths._files_path / "samples_summary.json").exists()


def test__visualize__disabled_skips_all():
"""
With ``visualization_enabled=False`` (EP factor searches, #1642) neither the
analysis visuals nor the search's ``plot_results`` run, and no samples are
loaded for plotting.
"""
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,
visualization_enabled=False,
)
analysis = MagicMock()

updater.visualize(
model=MagicMock(),
analysis=analysis,
during_analysis=False,
samples_summary=MagicMock(),
)

analysis.should_visualize.assert_not_called()
analysis.visualize.assert_not_called()
analysis.visualize_combined.assert_not_called()
updater._samples_from.assert_not_called()
updater._plot_results.assert_not_called()
Loading