CIN2+ PIM coding as KPNC's: a visit is free of CIN2+ with HPV-negative and NILM or ASC-US, a positive without histology leaves it unknown

known_negative takes lists per key; the last negative carries every earlier one, and follow-up without a test isn't
counted. docs/codificacion_pim.md gives the six example patients, each with its unit test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
This commit is contained in:
2026-11-19 20:23:36 -06:00
parent 0be622c12d
commit fe7f881ade
6 changed files with 358 additions and 62 deletions
+38 -8
View File
@@ -84,17 +84,44 @@ def numerical_hessian(f, x, step=1e-4):
return hessian
def _starting_log_scale(c, l, r):
"""log of an exponential scale: time at risk / incident events. With a rare outcome the scale is thousands of
years; starting BFGS at the median detection time (a few years) left it in a much worse local optimum."""
at_risk = c != 1
finite = np.isfinite(r)
exposure = np.where(finite, (l + r) / 2, l)[at_risk].sum()
events = (at_risk & finite & (r > 0)).sum()
return float(np.log(max(exposure, 1e-6) / (events + 0.5)))
def _starting_theta(c, X, ridge=1e-3):
"""Prevalence coefficients of a logistic regression of "prevalent" on X among the members whose baseline is
known, with a small ridge so a group with no prevalent case gets a large negative value instead of -inf."""
known = c != UNKNOWN
if not known.any():
return np.zeros(X.shape[1])
y, Xk = (c[known] == 1).astype(float), X[known]
def loss(theta):
eta = Xk @ theta
return np.sum(np.logaddexp(0, eta) - y * eta) + ridge * theta @ theta
return minimize(loss, np.zeros(X.shape[1]), method="BFGS").x
def fit(c, l, r, X, Z):
"""Maximum likelihood with scipy. Returns a dict with the estimates and their Wald standard errors."""
c, l, r = np.asarray(c), np.asarray(l, dtype=float), np.asarray(r, dtype=float)
X, Z = np.asarray(X, dtype=float), np.asarray(Z, dtype=float)
n_x, n_z = X.shape[1], Z.shape[1]
start = np.zeros(n_x + n_z + 2)
finite = r[np.isfinite(r) & (r > 0)]
start[n_x + n_z] = np.log(np.median(finite)) if len(finite) else 0.0
result = minimize(neg_loglik, start, args=(c, l, r, X, Z), method="BFGS")
# Two starts, the better optimum kept: the likelihood of a rare outcome has poor local optima (all the risk put in
# the prevalence and none in the incidence, or the other way round).
log_scale = _starting_log_scale(c, l, r)
starts = [np.r_[_starting_theta(c, X), np.zeros(n_z), log_scale, 0.0],
np.r_[np.zeros(n_x), np.zeros(n_z), log_scale, 0.0]]
results = [minimize(neg_loglik, s, args=(c, l, r, X, Z), method="BFGS") for s in starts]
result = min(results, key=lambda res: res.fun if np.isfinite(res.fun) else np.inf)
theta, beta, log_scale, log_shape = split_params(result.x, n_x, n_z)
# BFGS's own hess_inv is a rough approximation: the standard errors come from a finite-difference Hessian.
# A coefficient that ran off to the boundary (e.g. a group with no prevalent case: logit → −inf) has a flat
@@ -103,9 +130,10 @@ def fit(c, l, r, X, Z):
hessian = numerical_hessian(lambda p: neg_loglik(p, c, l, r, X, Z), result.x)
free = np.abs(result.x) < BOUNDARY
standard_errors = np.full(len(result.x), np.nan)
covariance = np.full((len(result.x), len(result.x)), np.nan)
try:
covariance = np.linalg.inv(hessian[np.ix_(free, free)])
variances = np.diag(covariance)
covariance[np.ix_(free, free)] = np.linalg.inv(hessian[np.ix_(free, free)])
variances = np.diag(covariance)[free]
standard_errors[free] = np.sqrt(np.where(variances > 0, variances, np.nan))
except np.linalg.LinAlgError:
pass
@@ -116,10 +144,12 @@ def fit(c, l, r, X, Z):
"log_shape": log_shape,
"params": result.x,
"se": standard_errors,
"covariance": covariance,
"neg_loglik": result.fun,
# BFGS with a numerical gradient often stops with "precision loss" at the optimum; what matters is that
# the gradient is ~0 there.
"converged": bool(np.max(np.abs(result.jac)) < 1e-3),
# A coefficient at the boundary (see above) keeps a small slope there; only the free ones must be flat.
"converged": bool(np.max(np.abs(result.jac[free]), initial=0.0) < 1e-3),
"message": result.message,
}
+39 -24
View File
@@ -1,25 +1,26 @@
"""CaCu CIN2+ prevalence–incidence prototype: the cumulative risk of CIN2+ at the index visit and at later horizons.
Each member becomes a code `c` and an interval `(l, r]` in years (`likelihood`'s convention), from the index sample's
results and the biopsies after it:
Each member becomes a code `c` and an interval `(l, r]` in years since the index date (`likelihood`'s convention),
from the first CIN2+ biopsy and the last time the member was found free of it before that biopsy. Found free means a
biopsy below CIN2+, or a visit whose results each take one of their `known_negative` values (HPV-negative with NILM or
ASC-US). CIN2+ is taken as absorbing
and a negative as true, so the last negative carries every earlier one:
- a CIN2+ biopsy within `prevalent_window_months`: prevalent, `c = 1`;
- otherwise, a known negative baseline (`known_negative` results, or a biopsy in the window below CIN2+): `c = 0`, with
`(0, t_event]` if a later biopsy is CIN2+ and `(follow-up, inf)` if none is;
- otherwise the baseline is unknown: `c = -999`, with `(0, t_event]` or `(0, inf)`.
- a CIN2+ biopsy within `prevalent_window_months`: prevalent, `c = 1`, `(0, 0]`;
- otherwise, found free at least once: `c = 0`, with `l` the last negative (0 if it's within the window, the baseline
workup) and `r` the CIN2+ biopsy, or infinity if there's none;
- otherwise the baseline is unknown: `c = -999`, with `(0, t_event]`, or `(0, inf)`, which carries no information.
The interval's left end is 0 for a later event: the last negative visit before it isn't looked for.
Follow-up without a test isn't counted: a member is free only as far as her last negative, never up to the cut-off.
`PrevalenceIncidenceMixture` is a scikit-learn estimator: `fit(X, y)` with the members' features and their `c`, `l`,
`r`; `predict_proba(X)` gives the cumulative risk at each horizon, CR(t) = π + (1 − π)(1 − S(t)), with the prevalence
π logistic in every feature and the incidence S(t) Weibull with proportional hazards in `incidence_features`.
`fitted_model` puts `IndexResults` in front of it, so the registered model is one `Pipeline` that takes a build's long
frame. Settings arrive as config (`model.toml`), the cohort and its lineage through loaders, and registering is the
frame. Settings arrive as config (`model.toml`), the cohort through a loader, and registering is the
driver's saver (`models.dags.training`).
"""
from datetime import date
import numpy as np
import pandas as pd
import pandera.pandas as pandera
@@ -59,31 +60,45 @@ def index_results(cohort: pd.DataFrame, index_sample_days: int) -> pd.DataFrame:
return members
def cohort_cutoff(cohort_lineage: dict) -> date:
"""The build's cut-off: no event after it is in the file."""
return date.fromisoformat(cohort_lineage["datos_as_of"])
def _negative_days(cohort: pd.DataFrame, days: pd.Series, event_grades: list[str], known_negative: dict,
index_sample_days: int) -> pd.DataFrame:
"""`pac_id` and day of every time a member was found free of CIN2+: a biopsy below CIN2+, or a visit with a result
of every `known_negative` key among its values, within `index_sample_days` of each other, dated at the last."""
timed = cohort.assign(days=days.astype(float))[days >= 0]
biopsies = timed[(timed["tipo"] == "biopsia") & ~timed["valor_codigo"].isin(event_grades)][["pac_id", "days"]]
visits = None
for name, values in known_negative.items():
found = timed[(timed["tipo"] == name) & timed["valor_codigo"].isin(values)][["pac_id", "days"]]
if visits is None:
visits = found
continue
paired = pd.merge_asof(visits.sort_values("days"), found.rename(columns={"days": name}).sort_values(name),
left_on="days", right_on=name, by="pac_id", direction="nearest",
tolerance=float(index_sample_days)).dropna(subset=[name])
visits = paired.assign(days=paired[["days", name]].max(axis=1))[["pac_id", "days"]]
return pd.concat([biopsies, visits], ignore_index=True)
@checked_frame(INTERVAL_CODED)
def interval_coded_members(cohort: pd.DataFrame, cohort_cutoff: date, event_grades: list[str],
prevalent_window_months: int, index_sample_days: int, known_negative: dict) -> pd.DataFrame:
def interval_coded_members(cohort: pd.DataFrame, event_grades: list[str], prevalent_window_months: int,
index_sample_days: int, known_negative: dict) -> pd.DataFrame:
"""Each member's features with `c`, `l` and `r` (see the module's docstring)."""
days = _days(cohort)
biopsies = cohort[(cohort["tipo"] == "biopsia") & (days >= 0)].assign(days=days)
window = prevalent_window_months * DAYS_PER_YEAR / 12
first_event = biopsies[biopsies["valor_codigo"].isin(event_grades)].groupby("pac_id")["days"].min()
negative_biopsy = biopsies[~biopsies["valor_codigo"].isin(event_grades) & (biopsies["days"] <= window)]
events = cohort[(cohort["tipo"] == "biopsia") & cohort["valor_codigo"].isin(event_grades) & (days >= 0)]
first_event = days[events.index].groupby(events["pac_id"]).min()
negatives = _negative_days(cohort, days, event_grades, known_negative, index_sample_days)
before_event = ~(negatives["days"] >= negatives["pac_id"].map(first_event))
last_negative = negatives[before_event].groupby("pac_id")["days"].max()
coded = index_results(cohort, index_sample_days)
results_negative = np.logical_and.reduce([coded[name] == value for name, value in known_negative.items()])
event_days = coded["pac_id"].map(first_event)
follow_up = (pd.Timestamp(cohort_cutoff) - pd.to_datetime(coded["fecha_indice"])).dt.days / DAYS_PER_YEAR
event_days, free_until = coded["pac_id"].map(first_event), coded["pac_id"].map(last_negative)
prevalent = event_days <= window
baseline_negative = results_negative | coded["pac_id"].isin(negative_biopsy["pac_id"])
found_free = free_until.notna() & ~prevalent
later_event = event_days.notna() & ~prevalent
coded["c"] = np.where(prevalent, 1, np.where(baseline_negative, 0, likelihood.UNKNOWN))
coded["l"] = np.where(~prevalent & baseline_negative & ~later_event, follow_up, 0.0)
coded["c"] = np.where(prevalent, 1, np.where(found_free, 0, likelihood.UNKNOWN))
coded["l"] = np.where(found_free & (free_until > window), free_until / DAYS_PER_YEAR, 0.0)
coded["r"] = np.where(prevalent, 0.0, np.where(later_event, event_days / DAYS_PER_YEAR, np.inf))
return coded
+3 -2
View File
@@ -20,5 +20,6 @@ train_fraction = 0.7
prevalent_window_months = 6
# The index sample's results: the first ones within these days of the index date.
index_sample_days = 30
# The results that make a baseline known negative without a biopsy.
known_negative = { bethesda = "NORMAL", vph = "NEGATIVO" }
# The results that make a visit free of CIN2+ without a biopsy: every key with one of its values (KPNC: HPV-negative
# with NILM or ASC-US; Cheung et al. 2020, doi:10.1097/LGT.0000000000000528).
known_negative = { bethesda = ["NORMAL", "ASC-US"], vph = ["NEGATIVO"] }