CaCu PIM: risk intervals, what the number is, and the surveillance risk from the latest cytology

- The registered mixture gives each risk's interval at `risk_interval_level` (delta method on the log scale, from
  the fit's inverse Hessian), so the patient's risk carries it.
- `[estimand]` in `model.toml` says what the model's number is (quantity, outcome, index date, unit of the horizons,
  interval), read into `Scenario.estimand` for the screens that show it.
- The surveillance scenario predicts from each patient's latest cytology with both cytology and HPV results, before
  any colposcopy (`prediction_index = "ultima_citologia"`): every new complete sample is a new index date, and a
  sample still missing a result gives way to the one before. Patients past a colposcopy are the post-colposcopy
  scenario's. Training keeps the first cytology in the window. The rule runs inside the registered model, so it loads
  without this repository.
This commit is contained in:
2026-11-22 07:38:39 -06:00
parent 78a4748592
commit 46bc6bcf39
6 changed files with 236 additions and 21 deletions
+116 -13
View File
@@ -22,10 +22,13 @@ frame. Settings arrive as config (`model.toml`), the cohort through a loader, an
driver's saver (`models.dags.training`).
"""
import copy
import numpy as np
import pandas as pd
import pandera.pandas as pandera
from hamilton.function_modifiers import extract_fields
from scipy.stats import norm
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.metrics import roc_auc_score
from sklearn.pipeline import Pipeline
@@ -36,6 +39,10 @@ from models.io.contracts import DAYS_PER_YEAR
from models.steps import model_fitting
FEATURES = ["cytology", "hpv_positive"]
# The member's prediction index (days since 1970-01-01), when `IndexResults` picks it: the first column of the output.
INDEX_COLUMN = "fecha_indice_modelo"
EPOCH = pd.Timestamp("1970-01-01")
PREDICTION_INDEXES = ("ultima_citologia",)
def _features(history: dict) -> list[str]:
@@ -168,12 +175,13 @@ class PrevalenceIncidenceMixture(BaseEstimator):
"""
def __init__(self, horizons_years=(0.0, 1.0, 3.0, 5.0), incidence_features=("hpv_positive",), strata=(),
incidence=None, levels=None):
incidence=None, levels=None, interval_level=None):
self.horizons_years = horizons_years
self.incidence_features = incidence_features
self.strata = strata
self.incidence = incidence
self.levels = levels
self.interval_level = interval_level
def _baseline(self, y: pd.DataFrame):
settings = dict(self.incidence or {"family": "weibull"})
@@ -232,17 +240,59 @@ class PrevalenceIncidenceMixture(BaseEstimator):
self.converged_ = all(f["converged"] for f in self.fits_.values())
return self
def risk_with_variance(self, key: tuple, prevalence: np.ndarray, incidence: np.ndarray, years) -> tuple:
"""CR(t) of each design row of stratum `key` at `years`, and its delta-method variance (central differences
of CR in every parameter, with the fit's inverse Hessian)."""
fit = self.fits_[key]
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, prevalence, incidence, years)
params = np.asarray(fit["params"], dtype=float)
gradient = np.empty((len(params), len(prevalence), 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)
return risk(params), np.maximum(np.einsum("kij,kl,lij->ij", gradient, covariance, gradient), 0.0)
def predict_proba(self, X: pd.DataFrame) -> np.ndarray:
"""One column per horizon: CR(t). The column of t = 0 is the prevalence."""
risks = np.full((len(X), len(self.horizons_years)), np.nan)
"""One column per horizon: CR(t). The column of t = 0 is the prevalence. With `INDEX_COLUMN` in `X`, its days
since 1970-01-01 come first and a member without that date gets no risk. With `interval_level`, two more
blocks of as many columns: the interval's lower and upper ends, CR · exp(∓z · SE / CR) (delta method on the
log scale, clipped to [0, 1])."""
if INDEX_COLUMN in X.columns:
dates = pd.to_datetime(X[INDEX_COLUMN])
risks = self.predict_proba(X.drop(columns=INDEX_COLUMN))
risks[dates.isna().to_numpy()] = np.nan
return np.column_stack([(dates - EPOCH).dt.days.to_numpy(dtype=float), risks])
h = len(self.horizons_years)
risks = np.full((len(X), 3 * h if self.interval_level else h), np.nan)
z = norm.ppf(0.5 + self.interval_level / 2) if self.interval_level else None
for key, index in self._groups(X):
if key not in self.fits_:
continue
members = X.iloc[index]
placed = self._placed(members, self.seen_[key])
prevalence, incidence = self._design(members[placed], self.seen_[key])
risks[index[placed]] = likelihood.cumulative_risk(self.fits_[key], prevalence, incidence,
self.horizons_years)
rows = index[placed]
if not self.interval_level:
risks[rows] = likelihood.cumulative_risk(self.fits_[key], prevalence, incidence, self.horizons_years)
continue
design = np.column_stack([prevalence, incidence])
unique, inverse = np.unique(design, axis=0, return_inverse=True)
point, variance = self.risk_with_variance(key, unique[:, :prevalence.shape[1]],
unique[:, prevalence.shape[1]:], self.horizons_years)
relative = np.where(point > 0, np.sqrt(variance) / np.maximum(point, 1e-300), 0.0)
band = np.column_stack([point, np.clip(point * np.exp(-z * relative), 0, 1),
np.clip(point * np.exp(z * relative), 0, 1)])
risks[rows] = band[inverse.ravel()]
return risks
@@ -287,23 +337,76 @@ def metrics(fitted_mixture: PrevalenceIncidenceMixture, train_set: pd.DataFrame,
return found
class IndexResults(TransformerMixin, BaseEstimator):
"""A build's long frame to the features of each member, in `pac_id` order. Learns nothing."""
RESULT_TYPES = ("bethesda", "glandular", "vph")
REFERRED = ("colposcopia", "biopsia") # a patient with either is past the surveillance model
def __init__(self, index_sample_days: int = 30, cytology=None, history=None):
def latest_precolposcopy_cytology(cohort: pd.DataFrame) -> pd.DataFrame:
"""Per patient with no colposcopy and no biopsy in the frame, the date of her latest cytology sample with a
cytology result (Bethesda or glandular) and an HPV result, linked to it by its source row: `pac_id`, `fecha`. A
sample still missing either result gives way to the one before it; a patient with none, or referred, is absent.
Self-contained: it runs inside the registered model, without this repository."""
referred = set(cohort.loc[cohort["tipo"].isin(REFERRED), "pac_id"])
key = ["pac_id", "fuente_tabla", "fuente_id"]
samples = cohort.loc[(cohort["tipo"] == "citologia") & ~cohort["pac_id"].isin(referred), [*key, "fecha"]]
results = cohort[cohort["tipo"].isin(RESULT_TYPES) & cohort["valor_codigo"].notna()]
has = results.pivot_table(index=key, columns="tipo", values="valor_codigo", aggfunc="first")
has = has.reindex(columns=list(RESULT_TYPES))
complete = has[(has["bethesda"].notna() | has["glandular"].notna()) & has["vph"].notna()].index
samples = samples.set_index(key)
samples = samples[samples.index.isin(complete)].reset_index()
latest = samples.sort_values(["pac_id", "fecha", "fuente_id"]).groupby("pac_id", as_index=False).last()
return latest[["pac_id", "fecha"]].reset_index(drop=True)
def latest_index_results(cohort: pd.DataFrame, index_sample_days: int, cytology: dict,
history: dict | None = None) -> pd.DataFrame:
"""`index_results` at each member's latest complete cytology before any colposcopy
(`latest_precolposcopy_cytology`), with that date in `INDEX_COLUMN`; one row per member in `pac_id`
order, with no features and no date for a member without such a sample."""
chosen = latest_precolposcopy_cytology(cohort).set_index("pac_id")["fecha"]
members = pd.DataFrame({"pac_id": sorted(cohort["pac_id"].unique())})
eligible = cohort[cohort["pac_id"].isin(chosen.index)]
if len(eligible):
found = index_results(eligible.assign(fecha_indice=eligible["pac_id"].map(chosen)), index_sample_days,
cytology, history)
members = members.merge(found[["pac_id", *_features(history)]], on="pac_id", how="left")
else:
members = members.assign(**{f: np.nan for f in _features(history)})
members[INDEX_COLUMN] = pd.to_datetime(members["pac_id"].map(chosen))
return members
class IndexResults(TransformerMixin, BaseEstimator):
"""A build's long frame to the features of each member, in `pac_id` order. Learns nothing. By default at the
cohort's index date, as in training; with `prediction_index = "ultima_citologia"` at each member's latest
complete cytology before any colposcopy (`latest_index_results`), with that date as `INDEX_COLUMN`."""
def __init__(self, index_sample_days: int = 30, cytology=None, history=None, prediction_index=None):
self.index_sample_days = index_sample_days
self.cytology = cytology
self.history = history
self.prediction_index = prediction_index
def fit(self, X, y=None):
return self
def transform(self, X: pd.DataFrame) -> pd.DataFrame:
return index_results(X, self.index_sample_days, self.cytology, self.history)[_features(self.history)]
if self.prediction_index is None:
return index_results(X, self.index_sample_days, self.cytology, self.history)[_features(self.history)]
if self.prediction_index not in PREDICTION_INDEXES:
raise ValueError(f"unknown prediction_index {self.prediction_index!r}; known: {PREDICTION_INDEXES}")
found = latest_index_results(X, self.index_sample_days, self.cytology, self.history)
return found[[*_features(self.history), INDEX_COLUMN]].reset_index(drop=True)
def fitted_model(fitted_mixture: PrevalenceIncidenceMixture, index_sample_days: int, cytology: dict,
history: dict) -> Pipeline:
"""What's registered: the fitted mixture behind `IndexResults`."""
return Pipeline([("index_results", IndexResults(index_sample_days, cytology, history)),
("mixture", fitted_mixture)])
history: dict, risk_interval_level: float | None = None,
prediction_index: str | None = None) -> Pipeline:
"""What's registered: the fitted mixture behind `IndexResults`, giving each risk's interval at
`risk_interval_level` when there is one (`models.dags.estimation` reads the same key from the run), from the
index `prediction_index` names (the cohort's when none)."""
registered = copy.copy(fitted_mixture)
registered.interval_level = risk_interval_level
return Pipeline([("index_results", IndexResults(index_sample_days, cytology, history, prediction_index)),
("mixture", registered)])
+15
View File
@@ -13,8 +13,23 @@ citología índice en las categorías de KPNC como covariable (Cheung et al. 202
corrección del sesgo de verificación ni validación clínica."""
# The dataflow's config (`with_config`); each key is an input of the nodes that name it.
# What the model's number is, as the patient's screen and the governance pages show it.
[estimand]
quantity = "Riesgo acumulado"
description = "Probabilidad de que la paciente tenga CIN2+ en la fecha índice o lo desarrolle antes de cada horizonte."
outcome = "CIN2+: biopsia LIEAG, CIS o carcinoma"
index_date = "la última citología con resultado de citología y de VPH, en pacientes sin colposcopía; cada citología nueva es una nueva fecha índice. Sin la historia de visitas previas (aproximación hasta reproducir la tabla 4 de KPNC)"
horizons_unit = "años"
interval = "IC 95 % por método delta (escala logarítmica), de la incertidumbre de los parámetros del modelo"
[config]
horizons_years = [0.0, 1.0, 3.0, 5.0]
# The level of each risk's interval (delta method), given with the estimate; none gives no interval.
risk_interval_level = 0.95
# From when it predicts: "ultima_citologia" is each patient's latest complete cytology (cytology and HPV results)
# before any colposcopy; patients past a colposcopy belong to the post-colposcopy scenario. Training keeps the cohort's
# index (the first cytology in the window). None predicts from the cohort's index too.
prediction_index = "ultima_citologia"
event_grades = ["LIEAG", "CIS", "CARCINOMA"]
train_fraction = 0.7
# Provisional: a CIN2+ biopsy within this window of the index date counts as prevalent.
@@ -12,8 +12,19 @@ de la referencia (bajo o alto), con el VPH y la citología (tres categorías de
como reproduce exactamente la tabla 17 (capítulo 25 de bayes-pim). CIN2+ porque la biopsia LIEAG no separa CIN2 de CIN3. Sin corrección del sesgo de verificación. PROVISIONAL: una colposcopía sin orden de biopsia (impresión normal) se toma \
sin CIN2+, lo que supone que la impresión colposcópica no omite ningún CIN2+."""
# What the model's number is, as the patient's screen and the governance pages show it.
[estimand]
quantity = "Riesgo acumulado"
description = "Probabilidad de que la paciente tenga CIN2+ en la fecha índice o lo desarrolle antes de cada horizonte."
outcome = "CIN2+: biopsia LIEAG, CIS o carcinoma"
index_date = "la primera visita de vigilancia (co-test) después de una colposcopía sin CIN2+"
horizons_unit = "años"
interval = "IC 95 % por método delta (escala logarítmica), de la incertidumbre de los parámetros del modelo"
[config]
horizons_years = [0.0, 1.0, 3.0, 5.0]
# The level of each risk's interval (delta method), given with the estimate; none gives no interval.
risk_interval_level = 0.95
event_grades = ["LIEAG", "CIS", "CARCINOMA"]
train_fraction = 0.7
prevalent_window_months = 6
@@ -12,8 +12,19 @@ base, con el VPH y la citología (tres categorías de KPNC) de esa citología co
la tabla 24 (capítulo 25 de bayes-pim). Sin estrato de la biopsia previa: \
la biopsia LIEAG no separa CIN2 de CIN3, y por lo mismo el desenlace es CIN2+. Sin corrección del sesgo de verificación."""
# What the model's number is, as the patient's screen and the governance pages show it.
[estimand]
quantity = "Riesgo acumulado"
description = "Probabilidad de que la paciente tenga CIN2+ en la fecha índice o lo desarrolle antes de cada horizonte."
outcome = "CIN2+: biopsia LIEAG, CIS o carcinoma"
index_date = "la primera citología después del tratamiento"
horizons_unit = "años"
interval = "IC 95 % por método delta (escala logarítmica), de la incertidumbre de los parámetros del modelo"
[config]
horizons_years = [0.0, 1.0, 3.0, 5.0]
# The level of each risk's interval (delta method), given with the estimate; none gives no interval.
risk_interval_level = 0.95
event_grades = ["LIEAG", "CIS", "CARCINOMA"]
train_fraction = 0.7
prevalent_window_months = 6
+6 -2
View File
@@ -17,7 +17,7 @@ import hashlib
import json
import logging
import tomllib
from dataclasses import dataclass
from dataclasses import dataclass, field
from importlib import import_module
from pathlib import Path
from types import ModuleType
@@ -47,6 +47,9 @@ class Scenario:
config: dict
folder: Path
requirements: tuple[str, ...] = ()
# What the model's number is (`[estimand]`): `quantity`, `description`, `outcome`, `index_date`, `horizons_unit`,
# `interval`; what a screen shows next to each risk.
estimand: dict = field(default_factory=dict)
@classmethod
def from_toml(cls, path: str | Path) -> "Scenario":
@@ -55,7 +58,8 @@ class Scenario:
return cls(domain=found["domain"], scenario=found["scenario"], cohort=found["cohort"],
outcome=found["outcome"], description=found.get("description", ""),
modules=tuple(import_module(name) for name in found["modules"]), config=found["config"],
folder=path.parent, requirements=tuple(found.get("requirements", ())))
folder=path.parent, requirements=tuple(found.get("requirements", ())),
estimand=dict(found.get("estimand", {})))
@classmethod
def load(cls, domain: str, scenario: str) -> "Scenario":
+77 -6
View File
@@ -163,7 +163,7 @@ def test_the_graph_takes_exactly_its_config_and_the_cohort():
"incidence_features", "index_sample_days", "known_negative", "prevalent_window_months", "strata",
"train_fraction"}
# `index` from the config (a scenario without one keeps its cohort's index); the report's settings have defaults.
assert optional == {"index", "report_panels", "turnbull_bootstrap"}
assert optional == {"index", "prediction_index", "report_panels", "risk_interval_level", "turnbull_bootstrap"}
def test_the_dataflow_gives_metrics_at_every_horizon(cohort_frame):
@@ -181,9 +181,10 @@ def test_the_dataflow_gives_metrics_at_every_horizon(cohort_frame):
def test_training_and_estimating_score_every_member_at_every_horizon(cohort_file, mlflow_tracking, tmp_path,
predict_without_repository):
"""Pins down: through the generic driver the scenario registers a version whose estimate has one row per member
and horizon, a risk that doesn't fall with the horizon, the same outside this repository, and storable metadata.
Fails if the model or the estimate go back to one horizon, or the registered model needs this repository."""
"""Pins down: through the generic driver the scenario registers a version whose estimate has one row per
precolposcopy member (no biopsy) and horizon, dated at her latest complete cytology, a risk that doesn't fall
with the horizon, the same outside this repository, and storable metadata. Fails if the model or the estimate go
back to one horizon, a biopsied member is scored, or the registered model needs this repository."""
version = training.train(SCENARIO, CohortFile(cohort_file))
registry.client.set_registered_model_alias("cacu-cin2_pim", PRODUCTION_ALIAS, version)
output = tmp_path / "estimate.parquet"
@@ -191,7 +192,12 @@ def test_training_and_estimating_score_every_member_at_every_horizon(cohort_file
estimate(SCENARIO, CohortFile(cohort_file), output)
risks = pd.read_parquet(output)
assert len(risks) == 300 * len(CONFIG["horizons_years"])
frame = pd.read_parquet(cohort_file)
biopsied = set(frame.loc[frame["tipo"] == "biopsia", "pac_id"])
assert set(risks["pac_id"]) == set(frame["pac_id"]) - biopsied
assert len(risks) == (300 - len(biopsied)) * len(CONFIG["horizons_years"])
scored = risks.dropna(subset=["ic_bajo"])
assert len(scored) and ((scored["ic_bajo"] <= scored["probabilidad"]) & (scored["probabilidad"] <= scored["ic_alto"])).all()
by_member = risks.pivot(index="pac_id", columns="horizonte_anios", values="probabilidad")
assert (by_member.diff(axis=1).iloc[:, 1:] >= -1e-12).all().all()
assert pq.read_metadata(output).metadata[b"desenlace"] == b"cin2"
@@ -199,10 +205,75 @@ def test_training_and_estimating_score_every_member_at_every_horizon(cohort_file
uri = registry.resolve("cacu", "cin2_pim", version).model_uri
outside = predict_without_repository(uri, pd.read_parquet(cohort_file))
inside = mlflow.pyfunc.load_model(uri).predict(pd.read_parquet(cohort_file))
assert outside.shape == (300, len(CONFIG["horizons_years"]))
assert outside.shape == (300, 1 + 3 * len(CONFIG["horizons_years"]))
np.testing.assert_allclose(outside.to_numpy(), inside)
def test_the_prediction_index_is_the_latest_complete_cytology_before_any_colposcopy():
"""Pins down the surveillance model's prediction index: the latest cytology with both results; one missing its
HPV gives way to the one before; a patient with a colposcopy or a biopsy gets none (the post-colposcopy scenario
scores her). Fails if the index goes back to the cohort's first cytology or a referred patient is scored."""
def sample(pac_id, day, bethesda, vph):
key = f"S{pac_id}-{day}"
rows = [_row(pac_id, INDEX, day, "citologia", sample=key), _row(pac_id, INDEX, day + 7, "bethesda", bethesda, key)]
return rows + ([_row(pac_id, INDEX, day + 7, "vph", vph, key)] if vph else [])
rows = [*sample(1, 0, "ASC-US", "NEGATIVO"), *sample(1, 700, "LIEBG", "POSITIVO"),
*sample(2, 0, "NORMAL", "NEGATIVO"), *sample(2, 900, "LIEBG", None),
*sample(3, 0, "LIEBG", "POSITIVO"), _row(3, INDEX, 40, "colposcopia"), *sample(3, 400, "NORMAL", "NEGATIVO")]
frame = pd.DataFrame(rows, columns=COHORT_SCHEMA.names)
found = model.latest_index_results(frame, CONFIG["index_sample_days"], CONFIG["cytology"])
assert found["pac_id"].tolist() == [1, 2, 3]
assert found[model.INDEX_COLUMN].dt.date.tolist()[:2] == [INDEX + timedelta(days=700), INDEX]
assert found["cytology"].tolist()[:2] == ["LSIL", "NILM"] and found["hpv_positive"].tolist()[:2] == [1.0, 0.0]
assert pd.isna(found[model.INDEX_COLUMN].iloc[2]) and pd.isna(found["cytology"].iloc[2])
def test_the_registered_model_dates_each_risk_at_its_prediction_index(cohort_frame):
"""Pins down: with `prediction_index` the registered model gives the index date first (days since 1970) and the
risk of that visit's results, and no risk to a member without one. Fails if the date column is dropped, the
risk is computed from the cohort's index, or a member without an index gets a risk."""
found = training.dataflow(*SCENARIO.modules, config=CONFIG).execute(
["fitted_model", "fitted_mixture"], inputs={"source_cohort": cohort_frame, "cohort_lineage": {}})
output = found["fitted_model"].predict_proba(cohort_frame)
features = model.latest_index_results(cohort_frame, CONFIG["index_sample_days"], CONFIG["cytology"])
h = len(CONFIG["horizons_years"])
dated = ~np.isnan(output[:, 0])
assert dated.sum() == features[model.INDEX_COLUMN].notna().sum() and np.isnan(output[~dated, 1:]).all()
np.testing.assert_allclose(output[dated, 0], (features.loc[dated, model.INDEX_COLUMN] - model.EPOCH).dt.days)
expected = found["fitted_mixture"].predict_proba(features.loc[dated, model._features(CONFIG["history"])])
np.testing.assert_allclose(output[dated, 1:1 + h], expected)
def test_the_interval_brackets_the_same_risk(cohort_frame):
"""Pins down: with `interval_level` the mixture gives the risk unchanged and, after it, the interval's lower and
upper ends around it, NaN only where the risk is. Fails if the delta method moves the point, the blocks' order
changes, or an end crosses the risk."""
found = training.dataflow(*SCENARIO.modules, config=CONFIG).execute(
["fitted_mixture", "test_set", "fitted_model"], inputs={"source_cohort": cohort_frame, "cohort_lineage": {}})
X = found["test_set"][model._features(CONFIG["history"])]
h = len(CONFIG["horizons_years"])
point = found["fitted_mixture"].predict_proba(X)
banded = found["fitted_model"].named_steps["mixture"].predict_proba(X)
assert found["fitted_mixture"].interval_level is None and banded.shape == (len(X), 3 * h)
np.testing.assert_allclose(banded[:, :h], point)
low, high, known = banded[:, h:2 * h], banded[:, 2 * h:], ~np.isnan(point)
assert (np.isnan(low) == ~known).all() and (low[known] <= point[known]).all() and (point[known] <= high[known]).all()
assert (high[known] - low[known]).max() > 0
def test_the_scenario_says_what_its_number_is():
"""Pins down: `[estimand]` reaches the scenario with what the screens show next to each risk. Fails if the key is
renamed or `Scenario.from_toml` stops reading it."""
assert SCENARIO.estimand["quantity"] == "Riesgo acumulado" and SCENARIO.estimand["horizons_unit"] == "años"
assert {"description", "outcome", "index_date", "interval"} <= set(SCENARIO.estimand)
def test_each_stratum_gets_its_own_mixture_and_an_unseen_one_gets_no_risk(cohort_frame):
"""Pins down the stratification of the TOML: one fit per HPV value, each predicting only its own members, and NaN
(not another stratum's risk) for a value absent from training. Fails if the strata are pooled or mixed up."""