CaCu PIM subgroup report: risks in percent, one scale per panel, the empirical method in plain words

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.
This commit is contained in:
2026-11-22 07:38:47 -06:00
parent 46bc6bcf39
commit 7928b478f9
2 changed files with 55 additions and 14 deletions
+25 -14
View File
@@ -32,9 +32,13 @@ GRID_STEP = 0.1 # years between the points of the model's curve
UNKNOWN = "NA"
NOTICE = "Prototipo sin validación clínica."
METHODS = {
"empirica": "Turnbull (estimador no paramétrico de máxima verosimilitud con censura por intervalos, autoconsistencia): "
"prevalente = masa en 0, libre de CIN2+ = censura en (l, r], basal desconocida = [0, r]; banda e "
"varianza por bootstrap de las pacientes de la combinación",
"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",
@@ -179,45 +183,52 @@ def _label(combination: dict) -> str:
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)."""
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=True,
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=emp["high"], mode="lines", line={"width": 0, "shape": "hv"},
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=emp["low"], mode="lines", line={"width": 0, "shape": "hv"},
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=emp["CR"], mode="lines", line={"color": "#242628", "width": 2,
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:.3f}<extra>Turnbull</extra>"), row=row, col=col)
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=model["high"], mode="lines", line={"width": 0},
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=model["low"], mode="lines", line={"width": 0},
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=model["CR"], mode="lines", line={"color": "#6f35a5",
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:.3f}<extra>modelo</extra>"), row=row, col=col)
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")
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>"},
+30
View File
@@ -420,6 +420,36 @@ def _run_notebook(path, cohort_file, domain, scenario, monkeypatch, **parameters
return namespace
def test_the_subgroup_figure_draws_risks_in_percent():
"""Pins down: the report's curves are in percent, like the patient's risk and the table, with the axis saying so.
Fails if the figure goes back to proportions, which read as a risk a hundred times smaller."""
from models.cacu.cin2_pim import report
curve = {"years": [0.0, 5.0], "CR": [0.1, 0.2], "low": [0.05, 0.15], "high": [0.15, 0.25]}
record = {"combination": {"cytology": "LSIL", "hpv_positive": "positivo"}, "n": 10, "prevalent": 1,
"incident": 1, "empirical": curve, "model": curve, "e_o": []}
figure = report._figure([record], [0.0, 5.0])
assert [list(t.y) for t in figure.data if t.name in ("Turnbull", "Mezcla prevalencia-incidencia")] == [[10.0, 20.0]] * 2
assert figure.layout.yaxis.ticksuffix == " %" and "%" in figure.layout.yaxis.title.text
def test_each_subgroup_panel_has_its_own_scale():
"""Pins down: panels don't share the y axis, so each combination's curves fill their panel. Fails if the
subplots go back to one shared scale, where a 0.5 % curve is a flat line next to a 50 % one."""
from models.cacu.cin2_pim import report
def record(level, risk):
curve = {"years": [0.0, 5.0], "CR": [risk, risk], "low": [risk, risk], "high": [risk, risk]}
return {"combination": {"cytology": level, "hpv_positive": "positivo"}, "n": 10, "prevalent": 1,
"incident": 1, "empirical": curve, "model": curve, "e_o": []}
figure = report._figure([record("NILM", 0.005), record("HSIL+", 0.5)], [0.0, 5.0])
assert figure.layout.yaxis2.matches is None and figure.layout.yaxis2.anchor == "x2"
def test_the_subgroup_notebook_runs_on_a_builds_file(cohort_file, monkeypatch):
"""Pins down the PIM report's notebook (`models/cacu/cin2_pim/notebooks/reporte_subgrupos.ipynb`): its cells run on a
build's file with the platform's environment, compute the same combinations the dataflow does and draw them. Fails