# This file is part of pelagos_py.
#
# Copyright 2025-2026 National Oceanography Centre and The Contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Capture step diagnostic figures for the PDF report.
Steps draw their diagnostics with matplotlib and display them with
``plt.show()`` when ``diagnostics`` is enabled. To include those plots in the
report regardless of a step's own ``diagnostics`` setting, the pipeline
force-enables diagnostics and runs each step inside :func:`capture_figures`,
which redirects ``plt.show`` so the figures are written to disk instead of being
displayed. The saved paths are then embedded by the report writer.
"""
import atexit
import contextlib
import functools
import logging
import os
import pickle
import subprocess
import sys
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.collections import PathCollection
from matplotlib.lines import Line2D
from pelagos_py.utils import fig_spec
logger = logging.getLogger("pelagos_py.pipeline.diagnostics")
def _decimate(fig):
# thins dense lines/scatters in place; returns the original data to restore
cap = fig_spec.CAPTURE_MAX_POINTS
restore = []
for ax in fig.axes:
for artist in ax.lines:
x, y = artist.get_data()
if len(x) > cap:
idx = fig_spec.thin_idx(len(x), cap)
restore.append((artist, x, y))
artist.set_data(np.asarray(x)[idx], np.asarray(y)[idx])
for artist in ax.collections:
if not isinstance(artist, PathCollection):
continue
offsets = artist.get_offsets()
if len(offsets) > cap:
idx = fig_spec.thin_idx(len(offsets), cap)
array = artist.get_array()
restore.append((artist, offsets, array))
artist.set_offsets(offsets[idx])
if array is not None:
artist.set_array(array[idx])
return restore
@contextlib.contextmanager
def _decimated_for_save(fig):
restore = _decimate(fig)
try:
yield
finally:
for artist, a, b in restore:
if isinstance(artist, Line2D):
artist.set_data(a, b)
else:
artist.set_offsets(a)
if b is not None:
artist.set_array(b)
@contextlib.contextmanager
[docs]
def force_headless_backend():
"""Force the headless Agg backend for the whole report run.
Report figures are saved to disk, never displayed, so no GUI backend is
needed. Steps' diagnostics commonly call ``matplotlib.use("tkagg")`` to
force the interactive Tk backend; under report capture that is both
pointless and dangerous - instantiating a Tk canvas off the main thread
(e.g. when driven from an IDE/GUI) can hard-crash the process on Windows.
The backend is switched to Agg exactly once here and ``matplotlib.use()`` is
neutralised for the duration, so every step's backend switch becomes a
harmless no-op and the backend is never toggled mid-run (repeated
``use(..., force=True)`` re-initialises matplotlib's compiled backend, which
can trigger a fatal delay-load crash on Windows). Both are restored on exit.
"""
original_use = matplotlib.use
original_backend = matplotlib.get_backend()
matplotlib.use("Agg", force=True)
matplotlib.use = lambda *args, **kwargs: None
fig_spec.MAX_POINTS = fig_spec.CAPTURE_MAX_POINTS
try:
yield
finally:
fig_spec.MAX_POINTS = None
matplotlib.use = original_use
# Best-effort restore: never let backend restoration break the run.
try:
matplotlib.use(original_backend, force=True)
except Exception: # noqa: BLE001 - backend restore must never be fatal
pass
# Rasterising a PNG often costs more than the step that drew it, so headless saves go to worker subprocesses.
_SAVE_WORKERS = min(4, os.cpu_count() or 1)
_workers = [] # [proc, [pending paths]]
_next_worker = 0
def _worker(i):
if i == len(_workers):
proc = subprocess.Popen(
[
sys.executable,
os.path.join(os.path.dirname(__file__), "fig_save_worker.py"),
],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
text=True,
)
_workers.append([proc, []])
return _workers[i]
[docs]
def wait_for_saves():
"""Block until every save_figure() call has produced its file."""
for proc, pending in _workers:
while pending:
path = pending.pop(0)
reply = proc.stdout.readline() if proc.poll() is None else ""
if not reply.startswith("ok") and os.path.exists(path + ".fig"):
_retry_save(path)
def _retry_save(path):
fig = None
try:
with open(path + ".fig", "rb") as fh:
fig, kwargs = pickle.load(fh)
os.remove(path + ".fig")
fig.savefig(path, **kwargs)
except Exception as exc: # noqa: BLE001 - a lost diagnostic image must never fail the run
logger.warning("Could not save diagnostic figure %s: %s", path, exc)
finally:
if fig is not None:
plt.close(fig)
@atexit.register
def _shutdown_workers():
with contextlib.suppress(Exception):
wait_for_saves()
for proc, _ in _workers:
with contextlib.suppress(Exception):
proc.stdin.close()
proc.wait(timeout=5)
def _save_open_figures(
outdir: str, step_name: str, step_index: int, images: list, close: bool = True
) -> None:
"""Save every open matplotlib figure to ``outdir`` for the report.
Each saved path is appended to ``images``. Saving failures are swallowed so
capturing a diagnostic can never interrupt the pipeline. When ``close`` is
``True`` each figure is closed after saving so figures are neither displayed
nor leaked between steps; when ``False`` the figures are left open so they
can still be shown interactively afterwards (used for steps the user
explicitly enabled diagnostics on).
``step_index`` (the step's pipeline position) is in the filename so repeated
step names (e.g. several 'Apply QC' steps) don't overwrite each other.
"""
safe = f"{step_index:02d}_" + step_name.replace(os.sep, "_").replace(" ", "_")
for num in plt.get_fignums():
fig = plt.figure(num)
# registry figures carry their name (BaseStep.generate_diagnostics); others are numbered
suffix = getattr(fig, "_pelagos_figure", None) or str(len(images) + 1)
path = os.path.join(outdir, f"{safe}_{suffix}.png")
try:
if close:
_decimate(fig)
save_figure(fig, path, dpi=150, bbox_inches="tight")
else:
with _decimated_for_save(fig):
fig.savefig(path, dpi=150, bbox_inches="tight")
images.append(path)
except Exception: # noqa: BLE001 - a capture failure must never be fatal
pass
finally:
if close:
plt.close(fig)
@contextlib.contextmanager
[docs]
def make_diagnostics_safe(step) -> None:
"""Wrap a step's diagnostic methods so a failure never aborts the step.
Used when diagnostics are force-enabled to capture plots for the report: a
user who did not opt into diagnostics should never have the pipeline fail
because of a diagnostic-only error. The error is logged as a warning and the
step's core processing continues.
"""
for attr in ("generate_diagnostics", "plot_diagnostics"):
method = getattr(step, attr, None)
if not callable(method):
continue
@functools.wraps(method)
def safe(*args, _method=method, **kwargs):
try:
return _method(*args, **kwargs)
except Exception as exc: # noqa: BLE001 - diagnostics must never be fatal
step.logger.warning(
"Diagnostic generation for the report failed: %s",
exc,
)
return None
setattr(step, attr, safe)