"""The two reports training writes for each model version (the third, the clinical validation, is a document the clinical team adds). Both are data the governance page draws. - technical validation: how the version was trained and tested, and its held-out metrics; - interpretability: what drives its predictions. For the mixture, observed against predicted risk per combination of its features: the Turnbull estimate (the nonparametric cumulative risk under interval censoring) with a bootstrap band, the model's curve with its delta-method band, and expected over observed at each horizon. For the logistic regression, its coefficients and calibration by risk decile. """ import numpy as np import pandas as pd from scipy.stats import norm from sklearn.metrics import brier_score_loss from models import survival from models.cacu.pim import Mixture from models.cacu.specs import Logistic, Pim GRID_STEP = 0.1 # years between points of a curve BOOTSTRAP = 200 SEED = 20261122 Z = norm.ppf(0.975) def technical_validation(spec: Pim | Logistic | survival.Spec, metrics: dict, data: dict) -> dict: if isinstance(spec, survival.Spec): return survival.technical_validation(spec, metrics, data) members = data.get("coded", data.get("labelled")) return { "model": spec.name, "method": spec.method, "cohort": spec.cohort, "split": "temporal: the earliest 70% of index dates train, the latest 30% test", "members": len(members), "index_dates": [str(members["index_date"].min()), str(members["index_date"].max())], "metrics": metrics, } def turnbull(c, l, r, iters: int = 5000, tol: float = 1e-10): """Turnbull's EM: support points and cumulative risk at each. A prevalent case's event is at 0; a patient free at the index has hers in (l, r]; an unknown one in [0, r].""" finite = r[np.isfinite(r)] support = np.unique(np.concatenate([[0.0], finite[finite > 0], [np.inf]])) low, high = np.where(c == 0, l, -np.inf), np.where(c == 1, 0.0, r) inside = (support[None, :] > low[:, None]) & (support[None, :] <= high[:, None]) patterns, counts = np.unique(inside, axis=0, return_counts=True) p = np.full(len(support), 1 / len(support)) for _ in range(iters): weighted = patterns * p new = (counts[:, None] * weighted / weighted.sum(1, keepdims=True)).sum(0) / counts.sum() done = np.max(np.abs(new - p)) < tol p = new if done: break return support, np.cumsum(p) def _at(support, cumulative, t) -> np.ndarray: i = np.searchsorted(support, np.asarray(t, dtype=float), side="right") - 1 return np.where(i < 0, 0.0, cumulative[np.maximum(i, 0)]) def _label(feature: str, value) -> str: if value is None or (isinstance(value, float) and np.isnan(value)): return "NA" if feature == "hpv_positive": return "positive" if float(value) == 1.0 else "negative" return str(value) def _band(curve, variance) -> tuple[list, list]: relative = np.where(curve > 0, np.sqrt(variance) / np.maximum(curve, 1e-300), 0.0) return (np.clip(curve * np.exp(-Z * relative), 0, 1).tolist(), np.clip(curve * np.exp(Z * relative), 0, 1).tolist()) # fmt: skip def _mixture_curve(mixture: Mixture, row: pd.DataFrame, years) -> tuple | None: key = tuple(row[list(mixture.strata)].iloc[0]) if mixture.strata else () if key not in mixture.fits_ or not mixture._placed(row, mixture.seen_[key]).all(): return None prevalence, incidence = mixture._design(row, mixture.seen_[key]) point, variance = mixture.fits_[key].risk_with_variance(prevalence, incidence, years) return point[0], variance[0] def interpretability(spec: Pim | Logistic | survival.Spec, model, data: dict) -> dict: if isinstance(spec, survival.Spec): return survival.interpretability(spec, model, data) if isinstance(spec, Logistic): return _logistic(model, data["test"]) coded = data["coded"] full = Mixture(spec.horizons, spec.incidence_features, spec.strata, model.levels).fit(coded[spec.features], coded[["c", "l", "r"]]) # fmt: skip members = coded.reset_index(drop=True) labels = pd.DataFrame({f: members[f].map(lambda v, f=f: _label(f, v)) for f in spec.features}) horizons = np.asarray(spec.horizons, dtype=float) grid = np.round(np.arange(0, horizons.max() + GRID_STEP / 2, GRID_STEP), 6) rng = np.random.default_rng(SEED) groups = [] for _, combination in labels.drop_duplicates().iterrows(): mask = (labels == combination).all(axis=1).to_numpy() group = members[mask] c, l, r = (group[k].to_numpy(dtype=float) for k in ("c", "l", "r")) support, cumulative = turnbull(c, l, r) boot_grid, boot_h = [], [] for _ in range(BOOTSTRAP): pick = rng.integers(0, len(group), len(group)) s, cum = turnbull(c[pick], l[pick], r[pick]) boot_grid.append(_at(s, cum, grid)) boot_h.append(_at(s, cum, horizons)) observed, var_observed = _at(support, cumulative, horizons), np.var(boot_h, axis=0, ddof=1) entry = { "combination": combination.to_dict(), "n": int(mask.sum()), "prevalent": int((c == 1).sum()), "incident": int(((c != 1) & np.isfinite(r)).sum()), "observed": {"years": grid.tolist(), "risk": _at(support, cumulative, grid).tolist(), "low": np.percentile(boot_grid, 2.5, axis=0).tolist(), "high": np.percentile(boot_grid, 97.5, axis=0).tolist()}, "predicted": None, "expected_over_observed": [], } # fmt: skip probe = group.iloc[[0]][spec.features] at_grid, at_h = _mixture_curve(full, probe, grid), _mixture_curve(full, probe, horizons) if at_grid is not None: low, high = _band(*at_grid) entry["predicted"] = {"years": grid.tolist(), "risk": at_grid[0].tolist(), "low": low, "high": high} # fmt: skip for k, h in enumerate(horizons): e = None if at_h is None else float(at_h[0][k]) ratio = {"years": float(h), "expected": e, "observed": float(observed[k]), "ratio": None, "low": None, "high": None} # fmt: skip if e and observed[k] > 0 and np.isfinite(var_observed[k]): se = np.sqrt(at_h[1][k] / e**2 + var_observed[k] / observed[k] ** 2) value = e / observed[k] ratio |= {"ratio": value, "low": value * np.exp(-Z * se), "high": value * np.exp(Z * se)} # fmt: skip entry["expected_over_observed"].append(ratio) groups.append(entry) groups.sort(key=lambda g: (-g["n"], list(g["combination"].values()))) return {"model": spec.name, "kind": "subgroups", "bootstrap": BOOTSTRAP, "seed": SEED, "groups": groups} # fmt: skip def _logistic(model, test: pd.DataFrame, bins: int = 10) -> dict: classifier, encoder = model.named_steps["classify"], model.named_steps["encode"] names = encoder.get_feature_names_out() p = test["p"] deciles = pd.qcut(p, q=min(bins, p.nunique()), duplicates="drop") table = test.groupby(deciles, observed=True).agg(n=("y", "size"), predicted=("p", "mean"), observed=("y", "mean")) # fmt: skip return { "model": "logistic regression", "kind": "coefficients", "intercept": float(classifier.intercept_[0]), "coefficients": dict(zip(map(str, names), map(float, classifier.coef_[0]), strict=True)), "calibration": { "brier": float(brier_score_loss(test["y"], p)), "bins": [ { "range": str(k), "n": int(v.n), "predicted": float(v.predicted), "observed": float(v.observed), } for k, v in table.iterrows() ], }, # fmt: skip }