7928b478f9
The figure drew proportions with no unit, which read as a risk a hundred times smaller than the table's and the patient's. Each panel now has its own y scale, so a low-risk combination isn't flattened by a high-risk one, and the methods describe Turnbull's curve by what each patient contributes to it.
280 lines
17 KiB
Python
280 lines
17 KiB
Python
"""The subgroup report of a prevalence–incidence training run (every `cin2_pim` scenario): for each combination of the
|
||
model's features (KPNC's index cytology, HPV and, with a history, its feature), the model's cumulative risk of CIN2+
|
||
with its delta-method band against the combination's own Turnbull estimate with its bootstrap band, and the ratio of
|
||
expected to observed risk (E/O) at each horizon with its interval. A version keeps the record (`analisis/subgrupos.json`,
|
||
with the methods it used) and the page (`reportes/subgrupos.html`, Plotly, self-contained).
|
||
|
||
- The model is the scenario's mixture refitted on every interval-coded member (not only the training part), so that it
|
||
and the empirical estimate describe the same members.
|
||
- The empirical estimate is Turnbull's nonparametric maximum likelihood for interval-censored data (self-consistency,
|
||
as `bayes-pim/informe/resultados/24/simular_protocolo.py`), with the members coded as the mixture's likelihood reads
|
||
them: a prevalent case is the mass at 0, a member found free is censored in `(l, r]`, and one whose baseline is
|
||
unknown in `[0, r]` (prevalent or incident). It respects the interval censoring: a CIN2+ is known only between the
|
||
last negative and the biopsy, never at a date. Its band and variance are the percentiles and variance of
|
||
`turnbull_bootstrap` resamples of the combination's members.
|
||
- The model's band is the delta method over the likelihood: Var(CR(t)) = g' Σ g, with Σ the inverse of the observed
|
||
information (the numerical Hessian `likelihood.fit` already inverts) and g the numerical gradient of CR(t) in the
|
||
stratum's parameters; a parameter at the boundary has no variance in Σ and counts as fixed. The band is on the log
|
||
scale, E exp(±1.96 SE(E)/E).
|
||
- E/O: log(E/O) taken as normal, with SE^2 = Var(E)/E^2 + Var(O)/O^2. Empty where O is 0.
|
||
|
||
Aggregates only: counts, curves and points, never a member's row.
|
||
"""
|
||
|
||
import numpy as np
|
||
import pandas as pd
|
||
|
||
from models.cacu.cin2_pim import likelihood
|
||
from models.cacu.cin2_pim.model import PrevalenceIncidenceMixture, _features, _levels
|
||
|
||
Z = 1.959963984540054 # the normal's 97.5 % quantile
|
||
GRID_STEP = 0.1 # years between the points of the model's curve
|
||
UNKNOWN = "NA"
|
||
NOTICE = "Prototipo sin validación clínica."
|
||
METHODS = {
|
||
"empirica": "curva empírica de Turnbull: el estimador no paramétrico del riesgo acumulado cuando solo se sabe entre "
|
||
"qué dos visitas apareció el CIN2+ (censura por intervalos), calculado con el algoritmo EM de Turnbull "
|
||
"(1976). Cada paciente aporta el intervalo donde pudo estar su evento: un caso prevalente, el instante "
|
||
"0 (así la curva arranca en la prevalencia observada, comparable con la del modelo); una paciente "
|
||
"vista libre de CIN2+, el intervalo entre su último negativo y su biopsia CIN2+ (o sin fin); una sin "
|
||
"negativo previo, desde 0 hasta su biopsia. Banda y varianza por bootstrap de las pacientes de la "
|
||
"combinación",
|
||
"modelo": "mezcla prevalencia-incidencia reajustada en todas las pacientes codificadas; banda por método delta sobre "
|
||
"la verosimilitud (inversa del Hessiano numérico, gradiente numérico del riesgo acumulado), en escala log; "
|
||
"un parámetro en la frontera cuenta como fijo",
|
||
"E/O": "riesgo esperado por el modelo entre el observado (Turnbull) a cada horizonte; IC 95 % suponiendo log(E/O) "
|
||
"normal, SE² = Var(E)/E² + Var(O)/O²",
|
||
}
|
||
|
||
|
||
def _turnbull(c: np.ndarray, l: np.ndarray, r: np.ndarray, iters: int = 5000, tol: float = 1e-10):
|
||
"""(support, cumulative mass) of Turnbull's estimate for members coded `(c, l, r)`: the support is 0, every finite
|
||
right end and infinity; a prevalent member's set is {0}, a free one's the points in `(l, r]`, an unknown baseline's
|
||
the points in `[0, r]`."""
|
||
finite = r[np.isfinite(r)]
|
||
support = np.unique(np.concatenate([[0.0], finite[finite > 0], [np.inf]]))
|
||
low = np.where(c == 0, l, -np.inf)
|
||
high = np.where(c == 1, 0.0, r)
|
||
A = (support[None, :] > low[:, None]) & (support[None, :] <= high[:, None])
|
||
patterns, counts = np.unique(A, 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()
|
||
if np.max(np.abs(new - p)) < tol:
|
||
p = new
|
||
break
|
||
p = new
|
||
return support, np.cumsum(p)
|
||
|
||
|
||
def _at(support: np.ndarray, cumulative: np.ndarray, t) -> np.ndarray:
|
||
"""The estimate's cumulative risk at each of `t` (a step function, right-continuous)."""
|
||
idx = np.searchsorted(support, np.asarray(t, dtype=float), side="right") - 1
|
||
return np.where(idx < 0, 0.0, cumulative[np.maximum(idx, 0)])
|
||
|
||
|
||
def _label_value(feature: str, value) -> str:
|
||
if value is None or (isinstance(value, float) and np.isnan(value)):
|
||
return UNKNOWN
|
||
if feature == "hpv_positive":
|
||
return "positivo" if float(value) == 1.0 else "negativo"
|
||
return str(value)
|
||
|
||
|
||
def report_mixture(interval_coded_members: pd.DataFrame, horizons_years: list[float], incidence: dict,
|
||
incidence_features: list[str], strata: list[str], cytology: dict,
|
||
history: dict) -> PrevalenceIncidenceMixture:
|
||
"""The scenario's mixture refitted on every interval-coded member, the model the report sets against Turnbull."""
|
||
features = _features(history)
|
||
return PrevalenceIncidenceMixture(horizons_years, tuple(incidence_features), tuple(strata), incidence,
|
||
_levels(cytology, history)).fit(interval_coded_members[features],
|
||
interval_coded_members[["c", "l", "r"]])
|
||
|
||
|
||
def _risk_with_variance(mixture: PrevalenceIncidenceMixture, row: pd.DataFrame, years: np.ndarray):
|
||
"""The model's cumulative risk of one combination (`row`, one row) at `years`, and its delta-method variance."""
|
||
key = tuple(row[list(mixture.strata)].iloc[0]) if mixture.strata else ()
|
||
if key not in mixture.fits_:
|
||
return None, None
|
||
seen = mixture.seen_[key]
|
||
if not mixture._placed(row, seen).all():
|
||
return None, None
|
||
fit = mixture.fits_[key]
|
||
X, Zd = mixture._design(row, seen)
|
||
n_x, n_z = len(fit["theta"]), len(fit["beta"])
|
||
|
||
def risk(params):
|
||
found = {"theta": params[:n_x], "beta": params[n_x:n_x + n_z], "baseline": fit["baseline"],
|
||
"baseline_params": params[n_x + n_z:]}
|
||
return likelihood.cumulative_risk(found, X, Zd, years)[0]
|
||
|
||
params = np.asarray(fit["params"], dtype=float)
|
||
point = risk(params)
|
||
gradient = np.empty((len(params), len(years)))
|
||
for k in range(len(params)):
|
||
step = 1e-5 * max(1.0, abs(params[k]))
|
||
up, down = params.copy(), params.copy()
|
||
up[k] += step
|
||
down[k] -= step
|
||
gradient[k] = (risk(up) - risk(down)) / (2 * step)
|
||
covariance = np.nan_to_num(np.asarray(fit["covariance"], dtype=float), nan=0.0)
|
||
variance = np.einsum("ki,kl,li->i", gradient, covariance, gradient)
|
||
return point, np.maximum(variance, 0.0)
|
||
|
||
|
||
def combination_risks(interval_coded_members: pd.DataFrame, report_mixture: PrevalenceIncidenceMixture,
|
||
horizons_years: list[float], history: dict, turnbull_bootstrap: int = 200) -> list[dict]:
|
||
"""Per combination of the features present among the coded members, largest first: its members and prevalent
|
||
and incident cases, its Turnbull estimate with the bootstrap band, the model's cumulative risk with the delta-method
|
||
band (none for a combination the model can't place: a cytology outside KPNC's categories, a stratum unseen) and
|
||
E/O at each horizon (see the module's docstring)."""
|
||
features = _features(history)
|
||
members = interval_coded_members.reset_index(drop=True)
|
||
labels = pd.DataFrame({f: members[f].map(lambda v, f=f: _label_value(f, v)) for f in features})
|
||
table = labels.drop_duplicates().reset_index(drop=True)
|
||
horizons = np.asarray(horizons_years, dtype=float)
|
||
grid = np.round(np.arange(0, horizons.max() + GRID_STEP / 2, GRID_STEP), 6)
|
||
rng = np.random.default_rng(20261122)
|
||
records = []
|
||
for _, row in table.iterrows():
|
||
mask = (labels == row).all(axis=1).to_numpy()
|
||
group = members[mask]
|
||
c, l, r = group["c"].to_numpy(int), group["l"].to_numpy(float), group["r"].to_numpy(float)
|
||
support, cumulative = _turnbull(c, l, r)
|
||
boot_grid, boot_h = [], []
|
||
for _ in range(turnbull_bootstrap):
|
||
pick = rng.integers(0, len(group), len(group))
|
||
s_b, c_b = _turnbull(c[pick], l[pick], r[pick])
|
||
boot_grid.append(_at(s_b, c_b, grid))
|
||
boot_h.append(_at(s_b, c_b, horizons))
|
||
boot_grid, boot_h = np.array(boot_grid), np.array(boot_h)
|
||
O = _at(support, cumulative, horizons)
|
||
var_O = boot_h.var(axis=0, ddof=1) if turnbull_bootstrap > 1 else np.full(len(horizons), np.nan)
|
||
empirical = {"years": grid.tolist(), "CR": _at(support, cumulative, grid).tolist(),
|
||
"low": np.percentile(boot_grid, 2.5, axis=0).tolist() if turnbull_bootstrap else None,
|
||
"high": np.percentile(boot_grid, 97.5, axis=0).tolist() if turnbull_bootstrap else None}
|
||
|
||
model, ratios = None, []
|
||
probe = group.iloc[[0]][features]
|
||
E, var_E = _risk_with_variance(report_mixture, probe, horizons)
|
||
curve, var_curve = _risk_with_variance(report_mixture, probe, grid)
|
||
if curve is not None:
|
||
rel = np.where(curve > 0, np.sqrt(var_curve) / np.maximum(curve, 1e-300), 0.0)
|
||
model = {"years": grid.tolist(), "CR": curve.tolist(),
|
||
"low": np.clip(curve * np.exp(-Z * rel), 0, 1).tolist(),
|
||
"high": np.clip(curve * np.exp(Z * rel), 0, 1).tolist()}
|
||
for k, h in enumerate(horizons):
|
||
entry = {"years": float(h), "E": None if E is None else float(E[k]), "O": float(O[k]),
|
||
"E_O": None, "low": None, "high": None}
|
||
if E is not None and E[k] > 0 and O[k] > 0 and np.isfinite(var_O[k]):
|
||
se = float(np.sqrt(var_E[k] / E[k] ** 2 + var_O[k] / O[k] ** 2))
|
||
value = float(E[k] / O[k])
|
||
entry.update(E_O=value, low=value * float(np.exp(-Z * se)), high=value * float(np.exp(Z * se)))
|
||
ratios.append(entry)
|
||
records.append({"combination": row.to_dict(), "n": int(mask.sum()), "prevalent": int((c == 1).sum()),
|
||
"incident": int(((c != 1) & np.isfinite(r)).sum()), "empirical": empirical,
|
||
"model": model, "e_o": ratios})
|
||
return sorted(records, key=lambda x: (-x["n"], list(x["combination"].values())))
|
||
|
||
|
||
def _label(combination: dict) -> str:
|
||
names = {"cytology": "citología", "hpv_positive": "VPH"}
|
||
return " · ".join(f"{names.get(k, k)} {v}" for k, v in combination.items())
|
||
|
||
|
||
def _percent(values) -> list[float]:
|
||
return [100 * v for v in values]
|
||
|
||
|
||
def _figure(combination_risks: list[dict], horizons_years: list[float], report_panels: int = 24):
|
||
"""The figure: one panel per combination (the `report_panels` largest), Turnbull's step curve with its band and the
|
||
model's curve with its band (a Plotly `Figure`; the page and the notebook draw it), in percent like the table and
|
||
the patient's risk. Each panel has its own y scale, so a combination of low risk isn't flattened by one of high
|
||
risk."""
|
||
import plotly.graph_objects as go
|
||
from plotly.subplots import make_subplots
|
||
|
||
shown = combination_risks[:report_panels]
|
||
columns = 3
|
||
rows = max(1, -(-len(shown) // columns))
|
||
figure = make_subplots(rows=rows, cols=columns, shared_xaxes=True, shared_yaxes=False,
|
||
subplot_titles=[f"{_label(r['combination'])}<br>n = {r['n']}, prevalentes = {r['prevalent']}, "
|
||
f"incidentes = {r['incident']}" for r in shown])
|
||
for k, record in enumerate(shown):
|
||
row, col, first = k // columns + 1, k % columns + 1, k == 0
|
||
emp, model = record["empirical"], record["model"]
|
||
if emp["low"] is not None:
|
||
figure.add_trace(go.Scatter(x=emp["years"], y=_percent(emp["high"]), mode="lines", line={"width": 0, "shape": "hv"},
|
||
hoverinfo="skip", showlegend=False), row=row, col=col)
|
||
figure.add_trace(go.Scatter(x=emp["years"], y=_percent(emp["low"]), mode="lines", line={"width": 0, "shape": "hv"},
|
||
fill="tonexty", fillcolor="rgba(120,130,140,0.30)", hoverinfo="skip",
|
||
name="IC 95 % Turnbull (bootstrap)", legendgroup="emp_band", showlegend=first),
|
||
row=row, col=col)
|
||
figure.add_trace(go.Scatter(x=emp["years"], y=_percent(emp["CR"]), mode="lines", line={"color": "#242628", "width": 2,
|
||
"shape": "hv"},
|
||
name="Turnbull", legendgroup="emp", showlegend=first,
|
||
hovertemplate="%{x:.1f} años: %{y:.2f} %<extra>Turnbull</extra>"), row=row, col=col)
|
||
if model is not None:
|
||
figure.add_trace(go.Scatter(x=model["years"], y=_percent(model["high"]), mode="lines", line={"width": 0},
|
||
hoverinfo="skip", showlegend=False), row=row, col=col)
|
||
figure.add_trace(go.Scatter(x=model["years"], y=_percent(model["low"]), mode="lines", line={"width": 0},
|
||
fill="tonexty", fillcolor="rgba(111,53,165,0.18)", hoverinfo="skip",
|
||
name="IC 95 % modelo (método delta)", legendgroup="model_band",
|
||
showlegend=first), row=row, col=col)
|
||
figure.add_trace(go.Scatter(x=model["years"], y=_percent(model["CR"]), mode="lines", line={"color": "#6f35a5",
|
||
"width": 2},
|
||
name="Mezcla prevalencia-incidencia", legendgroup="model", showlegend=first,
|
||
hovertemplate="%{x:.1f} años: %{y:.2f} %<extra>modelo</extra>"), row=row, col=col)
|
||
figure.update_xaxes(range=[0, max(horizons_years) + 0.05])
|
||
figure.update_yaxes(rangemode="tozero", ticksuffix=" %")
|
||
figure.update_yaxes(title_text="Riesgo acumulado (%)", col=1)
|
||
figure.update_layout(height=300 * rows + 120, template="plotly_white", margin={"t": 110},
|
||
title={"text": "Riesgo acumulado de CIN2+ por combinación de covariables<br>"
|
||
f"<sup>Años desde la fecha índice; {NOTICE}</sup>"},
|
||
legend={"orientation": "h", "y": 1.0, "yanchor": "bottom", "x": 0})
|
||
return figure
|
||
|
||
|
||
def _ratio(e: dict) -> str:
|
||
if e["E_O"] is None:
|
||
return "—"
|
||
flag = "" if e["low"] <= 1 <= e["high"] else " *"
|
||
return f"{e['E_O']:.2f} ({e['low']:.2f}–{e['high']:.2f}){flag}"
|
||
|
||
|
||
def _table(combination_risks: list[dict]) -> pd.DataFrame:
|
||
"""Every combination's counts and E/O at each horizon (`*`: its interval leaves out 1)."""
|
||
return pd.DataFrame([{**r["combination"], "n": r["n"], "prevalentes": r["prevalent"], "incidentes": r["incident"],
|
||
**{f"E/O {e['years']:g} a": _ratio(e) for e in r["e_o"]}} for r in combination_risks])
|
||
|
||
|
||
def subgroup_report(combination_risks: list[dict], horizons_years: list[float], report_panels: int = 24) -> str:
|
||
"""The page: the figure, the table of every combination's counts and E/O, and the methods."""
|
||
figure = _figure(combination_risks, horizons_years, report_panels)
|
||
shown = combination_risks[:report_panels]
|
||
|
||
table = _table(combination_risks)
|
||
omitted = len(combination_risks) - len(shown)
|
||
notes = (f"<p>{omitted} combinaciones más, sin panel (solo en la tabla).</p>" if omitted > 0 else "") + (
|
||
"<p>* el IC de E/O no incluye 1. — sin casos observados a ese horizonte o combinación que el modelo no "
|
||
"ubica.</p><h3>Métodos</h3><ul>" + "".join(f"<li><b>{k}</b>: {v}</li>" for k, v in METHODS.items()) + "</ul>")
|
||
return ("<!doctype html><html lang=\"es\"><head><meta charset=\"utf-8\"><title>CIN2+ por subgrupo</title></head>"
|
||
"<body style=\"font-family:sans-serif;margin:16px\">" + figure.to_html(full_html=False, include_plotlyjs=True)
|
||
+ notes + "<h3>Combinaciones</h3>" + table.to_html(index=False, border=0) + "</body></html>")
|
||
|
||
|
||
def subgroups(combination_risks: list[dict]) -> dict:
|
||
"""The report's record, with the methods it used."""
|
||
return {"version": 1, "metodos": METHODS, "combinations": combination_risks}
|
||
|
||
|
||
def population(subgroups: dict) -> dict:
|
||
"""What the saver publishes under `analisis/`, by file name."""
|
||
return {"subgrupos": subgroups}
|
||
|
||
|
||
def reports(subgroup_report: str) -> dict:
|
||
"""What the saver publishes under `reportes/`, by name."""
|
||
return {"subgrupos": subgroup_report}
|