"""Figures: calibration curve, precision-recall curve, decision curve and average transport plan. Each function returns the matplotlib Figure and optionally saves it. """ from __future__ import annotations from typing import Mapping, Optional, Sequence import numpy as np import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt # noqa: E402 from sklearn.calibration import calibration_curve # noqa: E402 from sklearn.metrics import average_precision_score, precision_recall_curve # noqa: E402 from .metrics import net_benefit, net_benefit_treat_all # noqa: E402 def _finish(fig, save_path: Optional[str]): fig.tight_layout() if save_path: fig.savefig(save_path, dpi=300) return fig def plot_calibration( y: np.ndarray, probs: Mapping[str, np.ndarray], n_bins: int = 10, save_path: Optional[str] = None, ): """Reliability diagram for one or more models (``{label: prob_positive}``).""" fig, ax = plt.subplots(figsize=(5, 5)) for label, p in probs.items(): frac_pos, mean_pred = calibration_curve(y, p, n_bins=n_bins) ax.plot(mean_pred, frac_pos, "o-", label=label) ax.plot([0, 1], [0, 1], "k--", label="Perfect calibration") ax.set(xlabel="Predicted probability", ylabel="Observed frequency", title="Calibration curve") ax.grid(True) ax.legend() return _finish(fig, save_path) def plot_pr_curve(y: np.ndarray, probs: Mapping[str, np.ndarray], save_path: Optional[str] = None): """Precision-recall curves with PR-AUC in the legend.""" fig, ax = plt.subplots(figsize=(5, 5)) for label, p in probs.items(): precision, recall, _ = precision_recall_curve(y, p) ax.plot(recall, precision, label=f"{label} (PR-AUC={average_precision_score(y, p):.3f})") ax.axhline(np.mean(y), color="gray", linestyle=":", label="Prevalence") ax.set(xlabel="Recall", ylabel="Precision", title="Precision-recall curve") ax.grid(True) ax.legend() return _finish(fig, save_path) def plot_decision_curve( y: np.ndarray, probs: Mapping[str, np.ndarray], thresholds: Optional[Sequence[float]] = None, save_path: Optional[str] = None, ): """Decision curve with treat-all and treat-none references.""" t = np.linspace(0.01, 0.99, 99) if thresholds is None else np.asarray(thresholds) fig, ax = plt.subplots(figsize=(7, 5)) curves = [] for label, p in probs.items(): nb = net_benefit(y, p, t) curves.append(nb) ax.plot(t, nb, linewidth=2, label=label) treat_all = net_benefit_treat_all(y, t) ax.plot(t, treat_all, "--", label="Treat all") ax.plot(t, np.zeros_like(t), "k--", label="Treat none") top = max([np.max(c) for c in curves] + [np.max(treat_all)]) ax.set_ylim(-0.05, top + 0.05) ax.set(xlabel="Threshold probability", ylabel="Net benefit", title="Decision curve analysis") ax.grid(True) ax.legend() return _finish(fig, save_path) def plot_average_transport_plan(plans: np.ndarray, save_path: Optional[str] = None): """Heatmap of the mean transport plan across samples (rows: histopathology, cols: risk).""" avg = np.mean(plans, axis=0) fig, ax = plt.subplots(figsize=(4.5, 4)) im = ax.imshow(avg, cmap="viridis") for i in range(avg.shape[0]): for j in range(avg.shape[1]): ax.text(j, i, f"{avg[i, j]:.3f}", ha="center", va="center", color="w") fig.colorbar(im, ax=ax, label="Average mass transported") ax.set_xticks([0, 1], ["Benign / low", "Malignant / high"]) ax.set_yticks([0, 1], ["Benign", "Malignant"]) ax.set(xlabel="Risk model class", ylabel="Histopathology model class", title="Average transport plan") return _finish(fig, save_path)