# Copyright (c) 2026 CLSA contributors # SPDX-License-Identifier: MIT """Calibration and distribution-free risk control. Two objects matter: * ``conformal_threshold`` - the acceptance threshold on predicted harm, chosen on a disjoint calibration split with the finite-sample correction ceil((n+1)(1-alpha))/n. * ``selective_risk`` plus ``clopper_pearson_upper`` - the realised risk among accepted actions and its one-sided upper confidence bound. The feasibility check is implemented as ``feasibility_abstention``: when the base risk mu exceeds alpha, any distribution-free method must abstain on at least (mu - alpha)/(1 - alpha) of cases. We report the check wherever a bound is claimed, including cases where it fails. """ from __future__ import annotations import numpy as np from scipy.stats import beta def clopper_pearson_upper(k: int, n: int, delta: float = 0.05) -> float: """One-sided upper confidence bound on a binomial rate.""" if n <= 0: return 1.0 if k >= n: return 1.0 return float(beta.ppf(1 - delta, k + 1, n - k)) def conformal_threshold(scores_safe: np.ndarray, alpha: float) -> float: """Threshold on p_hat accepting actions whose risk is controlled at alpha. scores_safe are predicted harms on calibration items known to be safe. """ s = np.sort(np.asarray(scores_safe, dtype=np.float64)) n = len(s) if n == 0: return 1.0 k = int(np.ceil((n + 1) * (1 - alpha))) if k > n: return 1.0 return float(s[k - 1]) def selective_risk(p_hat: np.ndarray, harm: np.ndarray, threshold: float) -> dict: accept = p_hat <= threshold n_acc = int(accept.sum()) k_harm = int((harm[accept] > 0.5).sum()) risk = (k_harm / n_acc) if n_acc else 0.0 return { "coverage": float(n_acc / max(1, len(p_hat))), "selective_risk": float(risk), "n_accepted": n_acc, "n_harm_accepted": k_harm, "upper": clopper_pearson_upper(k_harm, n_acc, 0.05), } def feasibility_abstention(mu: float, alpha: float) -> float: """Minimum abstention fraction required when base risk exceeds alpha.""" if mu <= alpha: return 0.0 return float((mu - alpha) / (1 - alpha)) def expected_calibration_error(p: np.ndarray, y: np.ndarray, bins: int = 10) -> float: p = np.asarray(p, dtype=float) y = np.asarray(y, dtype=float) edges = np.linspace(0.0, 1.0, bins + 1) ece = 0.0 n = len(p) if n == 0: return 0.0 for i in range(bins): lo, hi = edges[i], edges[i + 1] m = (p >= lo) & (p < hi if i < bins - 1 else p <= hi) if not m.any(): continue ece += (m.sum() / n) * abs(p[m].mean() - y[m].mean()) return float(ece) def brier(p: np.ndarray, y: np.ndarray) -> float: return float(np.mean((np.asarray(p, float) - np.asarray(y, float)) ** 2)) if len(p) else 0.0 def reliability_curve(p: np.ndarray, y: np.ndarray, bins: int = 10) -> dict: p = np.asarray(p, float) y = np.asarray(y, float) edges = np.linspace(0.0, 1.0, bins + 1) xs, ys, ns = [], [], [] for i in range(bins): lo, hi = edges[i], edges[i + 1] m = (p >= lo) & (p < hi if i < bins - 1 else p <= hi) if not m.any(): continue xs.append(float(p[m].mean())) ys.append(float(y[m].mean())) ns.append(int(m.sum())) return {"pred": xs, "obs": ys, "n": ns} def episode_budget_alpha(alpha_step: float, n_steps: int) -> float: """Episode-level budget from a per-step alpha (union bound). The controller is given an episode-level budget, not a per-step one; this converts a per-step target into the episode target actually enforced. """ n_steps = max(1, int(n_steps)) return float(1.0 - (1.0 - alpha_step) ** n_steps)