CaCu models: prevalence-incidence mixture and logistic, equal to the current predictions

This commit is contained in:
Roberto Treviño
2026-11-25 00:28:42 -06:00
parent 77fc039586
commit bea3e4cd2d
6 changed files with 692 additions and 0 deletions
View File
+164
View File
@@ -0,0 +1,164 @@
"""What the CaCu models read from a patient's timeline (gold `cacu_events`): one row per
event, with the patient's cohort index date. Columns: person_id, index_date, date, type,
value_code, value_num, source_table, source_id."""
import numpy as np
import pandas as pd
from core import cacu
RESULTS = ("bethesda", "glandular", "hpv") # what a cytology sample reports
REFERRED = ("colposcopy", "biopsy") # once either happened, screening is over
MISSING = "(none)"
def prepared(events: pd.DataFrame) -> pd.DataFrame:
return events.assign(
date=pd.to_datetime(events["date"]), index_date=pd.to_datetime(events["index_date"])
)
def days(events: pd.DataFrame) -> pd.Series:
return (events["date"] - events["index_date"]).dt.days
def _worst(codes: pd.Series, cytology: dict) -> pd.Series:
"""Per patient (the index of `codes`), her most severe result as its cytology category."""
rank = {code: i for i, values in enumerate(cytology.values()) for code in values}
names = list(cytology)
worst = codes.map(rank).groupby(level=0).max()
return worst.map(lambda r: None if np.isnan(r) else names[int(r)]).astype(object)
def _referral_grade(events: pd.DataFrame, persons: pd.Series, history: dict) -> pd.Series:
"""Why she was referred: the worst result in the year before her first colposcopy."""
first = events[events["type"] == "colposcopy"].groupby("person_id")["date"].min()
before = (events["person_id"].map(first) - events["date"]).dt.days
near = events[before.between(0, history["lookback_days"])]
codes = near[near["type"].isin(["bethesda", "glandular"])].set_index("person_id")["value_code"]
worst = _worst(codes, history["cytology"]).reindex(persons).to_numpy()
hpv = near[(near["type"] == "hpv") & (near["value_code"] == "positive")]
positive = persons.isin(hpv["person_id"])
grade = np.where(np.isin(worst, history["high"]), "high", np.where(
np.isin(worst, history["low"]) | (np.isin(worst, history["low_if_hpv_positive"])
& positive.to_numpy()), "low", None)) # fmt: skip
return pd.Series(grade, index=persons.index, dtype=object)
def index_results(events: pd.DataFrame, cytology: dict, history: dict | None = None):
"""Per patient: the cytology category and HPV result of her index sample (the first
result of each kind within INDEX_SAMPLE_DAYS of the index), and the referral grade
when `history` asks for it."""
near = events[days(events).between(0, cacu.INDEX_SAMPLE_DAYS) & events["type"].isin(RESULTS)]
wide = near.sort_values("date", kind="stable").pivot_table(
index="person_id", columns="type", values="value_code", aggfunc="first"
)
members = events.groupby("person_id", as_index=False)["index_date"].first()
wide = wide.reindex(index=members["person_id"], columns=list(RESULTS))
codes = wide[["bethesda", "glandular"]].stack()
members["cytology"] = _worst(codes, cytology).reindex(members["person_id"]).to_numpy()
members["hpv_positive"] = (wide["hpv"] == "positive").astype(float).to_numpy()
if history:
members[history["feature"]] = _referral_grade(events, members["person_id"], history)
return members
def _negatives(events: pd.DataFrame, d: pd.Series, grades: list[str]) -> pd.DataFrame:
"""Days at which she was seen free of the outcome: a biopsy below `grades`, or a
negative co-test (the later day of its two results)."""
timed = events.assign(days=d.astype(float))[d >= 0]
biopsies = timed[(timed["type"] == "biopsy") & ~timed["value_code"].isin(grades)]
visits = None
for kind, values in cacu.KNOWN_NEGATIVE.items():
found = timed[(timed["type"] == kind) & timed["value_code"].isin(values)]
found = found[["person_id", "days"]]
if visits is None:
visits = found
continue
paired = pd.merge_asof(
visits.sort_values("days"), found.rename(columns={"days": kind}).sort_values(kind),
left_on="days", right_on=kind, by="person_id", direction="nearest",
tolerance=float(cacu.INDEX_SAMPLE_DAYS),
).dropna(subset=[kind]) # fmt: skip
visits = paired.assign(days=paired[["days", kind]].max(axis=1))[["person_id", "days"]]
return pd.concat([biopsies[["person_id", "days"]], visits], ignore_index=True)
def interval_coded(events: pd.DataFrame, grades: list[str], cytology: dict,
history: dict | None = None) -> pd.DataFrame: # fmt: skip
"""Index features plus the outcome as (c, l, r): prevalent (an outcome biopsy within
the prevalent window), free at the index (a negative before any outcome), or unknown;
and the years between her last negative and her outcome biopsy."""
d = days(events)
outcome = (events["type"] == "biopsy") & events["value_code"].isin(grades) & (d >= 0)
first = d[outcome].groupby(events.loc[outcome, "person_id"]).min()
negatives = _negatives(events, d, grades)
before = ~(negatives["days"] >= negatives["person_id"].map(first))
last_negative = negatives[before].groupby("person_id")["days"].max()
coded = index_results(events, cytology, history)
window = cacu.PREVALENT_WINDOW_DAYS
event_days, free_until = coded["person_id"].map(first), coded["person_id"].map(last_negative)
prevalent = event_days <= window
free = free_until.notna() & ~prevalent
later = event_days.notna() & ~prevalent
coded["c"] = np.where(prevalent, 1, np.where(free, 0, -999))
coded["l"] = np.where(free & (free_until > window), free_until / cacu.DAYS_PER_YEAR, 0.0)
coded["r"] = np.where(prevalent, 0.0,
np.where(later, event_days / cacu.DAYS_PER_YEAR, np.inf)) # fmt: skip
return coded
def last_screening_cytology(events: pd.DataFrame) -> pd.Series:
"""Per patient never referred: her latest sample with both a cytology and an HPV result."""
referred = set(events.loc[events["type"].isin(REFERRED), "person_id"])
key = ["person_id", "source_table", "source_id"]
samples = events.loc[(events["type"] == "cytology") & ~events["person_id"].isin(referred),
[*key, "date"]] # fmt: skip
results = events[events["type"].isin(RESULTS) & events["value_code"].notna()]
has = results.pivot_table(index=key, columns="type", values="value_code", aggfunc="first")
has = has.reindex(columns=list(RESULTS))
complete = has[(has["bethesda"].notna() | has["glandular"].notna()) & has["hpv"].notna()]
samples = samples.set_index(key)
samples = samples[samples.index.isin(complete.index)].reset_index()
latest = samples.sort_values(["person_id", "date", "source_id"]).groupby("person_id").last()
return latest["date"]
def split(members: pd.DataFrame, train_fraction: float) -> tuple[pd.DataFrame, pd.DataFrame]:
"""Temporal: the earliest index dates train, the latest test."""
ordered = members.sort_values(["index_date", "person_id"], kind="stable")
cut = int(len(ordered) * train_fraction)
return ordered.iloc[:cut], ordered.iloc[cut:]
def index_sample(events: pd.DataFrame, predictors: list[str]) -> pd.DataFrame:
"""Per patient: each predictor's result on her index sample, MISSING when none."""
members = events.groupby(["person_id", "index_date"], as_index=False).size()
members = members[["person_id", "index_date"]]
sample = events[(events["type"] == "cytology") & (events["date"] == events["index_date"])]
sample = sample.groupby("person_id", as_index=False)[["source_table", "source_id"]].first()
results = events.merge(sample, on=["person_id", "source_table", "source_id"])
genotype = results["type"] == "hpv_16_18"
results.loc[genotype, "value_code"] = results.loc[genotype, "value_num"].map(
{1.0: "positive", 0.0: "negative"}
)
wide = results[results["type"].isin(predictors)].pivot_table(
index="person_id", columns="type", values="value_code", aggfunc="first"
)
wide = wide.reindex(columns=list(predictors)).astype(object)
found = members.merge(wide, left_on="person_id", right_index=True, how="left")
return found.fillna(dict.fromkeys(predictors, MISSING))
def windowed_outcome(events: pd.DataFrame, grades: list[str], years: float,
follow_up_end: pd.Timestamp) -> pd.DataFrame: # fmt: skip
"""y: an outcome biopsy within `years` of the index; known: y, or followed that long."""
window = years * cacu.DAYS_PER_YEAR
outcome = (events["type"] == "biopsy") & events["value_code"].isin(grades)
outcome &= days(events).between(0, window)
members = events.groupby(["person_id", "index_date"], as_index=False).size()
members["y"] = members["person_id"].isin(events.loc[outcome, "person_id"]).astype(int)
followed = (follow_up_end - members["index_date"]).dt.days
members["known"] = (members["y"] == 1) | (followed >= window)
return members[["person_id", "y", "known"]]
+265
View File
@@ -0,0 +1,265 @@
"""Prevalence-incidence mixture for interval-censored outcomes (PIMixture, Cheung et al.).
A patient either has the outcome at the index visit (prevalence, a logistic model) or may
develop it later (incidence, a proportional-hazards model with an I-spline baseline). Each
patient is coded `c` = 1 (prevalent), 0 (known free at the index), or UNKNOWN, with the
interval (l, r] in years where an incident outcome happened. No library fits this model, so
the likelihood is written here; everything else is scipy.
"""
from dataclasses import dataclass
import numpy as np
import pandas as pd
from scipy.interpolate import BSpline
from scipy.optimize import minimize
from scipy.special import expit
from scipy.stats import norm
from sklearn.base import BaseEstimator
UNKNOWN = -999
TINY = 1e-12 # floor inside every log
FROZEN = 15.0 # a parameter this far out sits on the boundary: fixed, not estimated
HESSIAN_STEP = 1e-4
def ispline_basis(t, degree: int, knots) -> np.ndarray:
"""Integrated B-splines: monotone from 0 at the first knot to 1 at the last."""
t, knots = np.asarray(t, dtype=float), np.asarray(knots, dtype=float)
full = np.r_[np.repeat(knots[0], degree + 1), knots[1:-1], np.repeat(knots[-1], degree + 1)]
inside = np.clip(np.nan_to_num(t, posinf=knots[-1]), knots[0], knots[-1])
bsplines = BSpline.design_matrix(inside, full, degree, extrapolate=False).toarray()
basis = np.cumsum(bsplines[:, ::-1], axis=1)[:, ::-1][:, 1:]
basis[t >= knots[-1]] = 1.0
basis[t <= knots[0]] = 0.0
return basis
@dataclass(frozen=True)
class ISpline:
"""Baseline cumulative hazard: I-splines with non-negative (exp) coefficients."""
knots: tuple[float, ...]
degree: int
@classmethod
def at_quantiles(cls, l, r, n_knots: int, degree: int) -> "ISpline":
times = np.unique(np.r_[l, r[np.isfinite(r)]])
return cls(tuple(float(k) for k in np.quantile(times, np.linspace(0, 1, n_knots))), degree)
@property
def n_params(self) -> int:
return len(self.knots) + self.degree - 2
def cumulative_hazard(self, t, params) -> np.ndarray:
return ispline_basis(t, self.degree, self.knots) @ np.exp(params)
def start(self, c, l, r) -> np.ndarray:
"""Every coefficient equal, so the hazard is the crude event rate."""
at_risk, finite = c != 1, np.isfinite(r)
exposure = np.where(finite, (l + r) / 2, l)[at_risk].sum()
events = (at_risk & finite & (r > 0)).sum()
# exp(-log(...)), not a plain division: on a flat likelihood BFGS follows the start's
# last bit, and this is the start the current models were fitted from.
rate = np.exp(-np.log(max(exposure, 1e-6) / (events + 0.5)))
return np.full(self.n_params, np.log(max(rate * self.knots[-1], 1e-6) / self.n_params))
def survival(t, baseline: ISpline, baseline_params, beta, Z) -> np.ndarray:
t = np.asarray(t, dtype=float)
with np.errstate(over="ignore", invalid="ignore"):
found = np.exp(-baseline.cumulative_hazard(t, baseline_params) * np.exp(Z @ beta))
found = np.where(t <= 0, 1.0, found)
return np.where(np.isinf(t), 0.0, found)
def neg_loglik(params, c, l, r, X, Z, baseline: ISpline, w) -> float:
n_x, n_z = X.shape[1], Z.shape[1]
theta, beta, rest = params[:n_x], params[n_x : n_x + n_z], params[n_x + n_z :]
pi = expit(X @ theta)
interval = survival(l, baseline, rest, beta, Z) - survival(r, baseline, rest, beta, Z)
interval = np.maximum(interval, TINY)
row = np.zeros(len(c))
prevalent, free, unknown = c == 1, c == 0, c == UNKNOWN
row[prevalent] = np.log(pi[prevalent] + TINY)
row[free] = np.log(1 - pi[free] + TINY) + np.log(interval[free])
row[unknown] = np.log(pi[unknown] + (1 - pi[unknown]) * interval[unknown] + TINY)
return -np.sum(w * row)
def hessian(f, x, step: float = HESSIAN_STEP) -> np.ndarray:
"""Central-difference Hessian of f at x."""
p = len(x)
out = np.zeros((p, p))
for i in range(p):
for j in range(i, p):
ei, ej = np.zeros(p), np.zeros(p)
ei[i], ej[j] = step, step
value = (f(x + ei + ej) - f(x + ei - ej) - f(x - ei + ej) + f(x - ei - ej)) / (
4 * step * step
)
out[i, j] = out[j, i] = value
return out
def _ridge_logistic(c, X, ridge: float = 1e-3) -> np.ndarray:
"""Prevalence coefficients from the patients whose index status is known."""
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
@dataclass(frozen=True)
class Fit:
n_x: int
n_z: int
baseline: ISpline
params: np.ndarray
covariance: np.ndarray # NaN where a parameter is frozen
neg_loglik: float
converged: bool
def risk(self, X, Z, years, params=None) -> np.ndarray:
"""Cumulative risk at each horizon: prevalent, or incident by then."""
p = self.params if params is None else params
theta, beta, rest = (
p[: self.n_x],
p[self.n_x : self.n_x + self.n_z],
p[self.n_x + self.n_z :],
)
pi = expit(X @ theta)
return np.column_stack([
pi + (1 - pi) * (1 - survival(np.full(len(X), float(t)), self.baseline, rest, beta, Z))
for t in years
]) # fmt: skip
def risk_with_variance(self, X, Z, years) -> tuple[np.ndarray, np.ndarray]:
"""Risk and its delta-method variance (central-difference gradient)."""
gradient = np.empty((len(self.params), len(X), len(years)))
for k, value in enumerate(self.params):
step = 1e-5 * max(1.0, abs(value))
up, down = self.params.copy(), self.params.copy()
up[k] += step
down[k] -= step
gradient[k] = (self.risk(X, Z, years, up) - self.risk(X, Z, years, down)) / (2 * step)
covariance = np.nan_to_num(self.covariance, nan=0.0)
variance = np.einsum("kij,kl,lij->ij", gradient, covariance, gradient)
return self.risk(X, Z, years), np.maximum(variance, 0.0)
def fit(c, l, r, X, Z, baseline: ISpline, w) -> Fit:
"""Maximum likelihood from two starts (BFGS); covariance from the numerical Hessian."""
n_x, n_z = X.shape[1], Z.shape[1]
start = baseline.start(c, l, r)
starts = [np.r_[_ridge_logistic(c, X), np.zeros(n_z), start], np.r_[np.zeros(n_x + n_z), start]]
args = (c, l, r, X, Z, baseline, w)
results = [minimize(neg_loglik, s, args=args, method="BFGS") for s in starts]
best = min(results, key=lambda res: res.fun if np.isfinite(res.fun) else np.inf)
free = np.abs(best.x) < FROZEN
covariance = np.full((len(best.x), len(best.x)), np.nan)
h = hessian(lambda p: neg_loglik(p, *args), best.x)
try:
covariance[np.ix_(free, free)] = np.linalg.inv(h[np.ix_(free, free)])
except np.linalg.LinAlgError:
pass
converged = bool(np.max(np.abs(best.jac[free]), initial=0.0) < 1e-3)
return Fit(n_x, n_z, baseline, best.x, covariance, float(best.fun), converged)
class Mixture(BaseEstimator):
"""One mixture per stratum. Categorical features get one dummy per level after the first
level seen in the stratum (`levels` gives their order); rows at a level the stratum never
saw are left out. Every feature enters prevalence; `incidence_features` also incidence."""
def __init__(self, horizons_years, incidence_features, strata, levels, knots=3, degree=4,
interval_level=0.95): # fmt: skip
self.horizons_years = horizons_years
self.incidence_features = incidence_features
self.strata = strata
self.levels = levels
self.knots = knots
self.degree = degree
self.interval_level = interval_level
def _seen(self, X: pd.DataFrame) -> dict:
return {
f: [v for v in values if (X[f] == v).any()]
for f, values in self.levels.items()
if f in X.columns and f not in self.strata
}
def _placed(self, X: pd.DataFrame, seen: dict) -> np.ndarray:
if not seen:
return np.ones(len(X), dtype=bool)
return np.all([X[f].isin(values).to_numpy() for f, values in seen.items()], axis=0)
def _columns(self, X: pd.DataFrame, features, seen: dict) -> np.ndarray:
columns = []
for f in features:
if f in self.strata:
continue
if f in seen:
columns += [(X[f] == v).to_numpy(dtype=float) for v in seen[f][1:]]
else:
columns.append(X[f].to_numpy(dtype=float))
return np.column_stack(columns) if columns else np.zeros((len(X), 0))
def _design(self, X: pd.DataFrame, seen: dict) -> tuple[np.ndarray, np.ndarray]:
prevalence = np.column_stack([np.ones(len(X)), self._columns(X, X.columns, seen)])
return prevalence, self._columns(X, self.incidence_features, seen)
def _groups(self, X: pd.DataFrame):
if not self.strata:
return [((), np.arange(len(X)))]
groups = X.groupby(list(self.strata), sort=True).indices.items()
return [(key if isinstance(key, tuple) else (key,), rows) for key, rows in groups]
def fit(self, X: pd.DataFrame, y: pd.DataFrame):
"""X: the features; y: c, l, r. Identical rows are fitted once, weighted."""
rows = pd.concat([X.reset_index(drop=True), y[["c", "l", "r"]].reset_index(drop=True)],
axis=1).assign(w=1.0) # fmt: skip
self.fits_, self.seen_ = {}, {}
for key, index in self._groups(X):
group = rows.iloc[index]
seen = self._seen(group)
group = group[self._placed(group, seen)]
group = group.groupby([*X.columns, "c", "l", "r"], as_index=False)["w"].sum()
prevalence, incidence = self._design(group[X.columns], seen)
c, l, r = (group[k].to_numpy(dtype=float) for k in ("c", "l", "r"))
baseline = ISpline.at_quantiles(l, r, self.knots, self.degree)
self.seen_[key] = seen
self.fits_[key] = fit(c, l, r, prevalence, incidence, baseline, group["w"].to_numpy())
self.neg_loglik_ = float(sum(f.neg_loglik for f in self.fits_.values()))
self.converged_ = all(f.converged for f in self.fits_.values())
return self
def predict(self, X: pd.DataFrame) -> np.ndarray:
"""Per row and horizon: (risk, low, high) as three blocks of columns; NaN where the
row's stratum or level was never seen."""
h = len(self.horizons_years)
out = np.full((len(X), 3 * h), np.nan)
z = norm.ppf(0.5 + self.interval_level / 2)
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])
design = np.column_stack([prevalence, incidence])
unique, inverse = np.unique(design, axis=0, return_inverse=True)
n_x = prevalence.shape[1]
point, variance = self.fits_[key].risk_with_variance(
unique[:, :n_x], unique[:, n_x:], 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)]) # fmt: skip
out[index[placed]] = band[inverse.ravel()]
return out
+178
View File
@@ -0,0 +1,178 @@
"""The CaCu models: each is a spec (what it reads and how it is set) over one of two methods,
the prevalence-incidence mixture or a logistic regression. Training and scoring read the
patient timelines of the spec's cohort (see features)."""
from dataclasses import dataclass, field
from typing import Literal
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import brier_score_loss, roc_auc_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder
from core import cacu
from models.cacu import features as f
from models.cacu.pim import Mixture
HORIZONS = (0.0, 1.0, 2.0, 3.0, 4.0, 5.0)
TRAIN_FRACTION = 0.7
OUTPUT = ["person_id", "index_date", "horizon_years", "probability", "ci_low", "ci_high"]
def _rows(members: pd.DataFrame, risks: np.ndarray, horizons) -> pd.DataFrame:
"""One row per patient and horizon; patients the model can't score are left out."""
h = len(horizons)
scored = ~np.isnan(risks[:, :h]).any(axis=1)
members, risks = members[scored], risks[scored]
n = len(members)
frame = pd.DataFrame({
"person_id": np.repeat(members["person_id"].to_numpy(), h),
"index_date": np.repeat(pd.to_datetime(members["index_date"]).dt.date.to_numpy(), h),
"horizon_years": np.tile(np.asarray(horizons, dtype=float), n),
"probability": risks[:, :h].ravel(),
}) # fmt: skip
if risks.shape[1] == 3 * h:
frame["ci_low"], frame["ci_high"] = risks[:, h : 2 * h].ravel(), risks[:, 2 * h :].ravel()
else:
frame["ci_low"] = frame["ci_high"] = np.nan
return frame[OUTPUT]
@dataclass(frozen=True)
class Pim:
"""Cumulative risk of the outcome at the index and by each horizon (PIMixture)."""
name: str
cohort: str
grades: list[str]
cytology: dict[str, list[str]]
strata: tuple[str, ...]
incidence_features: tuple[str, ...]
history: dict | None = None # a feature from before the index (the referral grade)
predict_at: Literal["index", "last_screening_cytology"] = "index"
horizons: tuple[float, ...] = HORIZONS
method: str = field(default="prevalence-incidence mixture", init=False)
@property
def features(self) -> list[str]:
return ["cytology", "hpv_positive"] + ([self.history["feature"]] if self.history else [])
def _history(self) -> dict | None:
return self.history and {**self.history, "cytology": self.cytology}
def train(self, events: pd.DataFrame) -> tuple[Mixture, dict, dict]:
"""The fitted mixture, its metrics on the held-out latest patients, and the coded
members it learned from (for the reports)."""
events = f.prepared(events)
coded = f.interval_coded(events, self.grades, self.cytology, self._history())
train, test = f.split(coded, TRAIN_FRACTION)
levels = {"cytology": list(self.cytology)}
if self.history:
levels[self.history["feature"]] = list(self.history["levels"])
mixture = Mixture(self.horizons, self.incidence_features, self.strata, levels)
mixture.fit(train[self.features], train[["c", "l", "r"]])
return mixture, self.metrics(mixture, train, test), {"coded": coded}
def metrics(self, mixture: Mixture, train, test) -> dict:
found = {
"n_train": len(train),
"n_test": len(test),
"neg_loglik": mixture.neg_loglik_,
"converged": float(mixture.converged_),
}
risks = mixture.predict(test[self.features])
for column, horizon in enumerate(self.horizons):
case = (test["c"] == 1) | ((test["c"] != 1) & (test["r"] <= horizon))
free = (test["c"] == 0) & (test["l"] >= horizon) & ~case
status = np.where(case, 1.0, np.where(free, 0.0, np.nan))
known = ~np.isnan(status) & ~np.isnan(risks[:, column])
y, p, tag = status[known], risks[known, column], f"{horizon:g}y"
found[f"n_known_{tag}"] = int(known.sum())
if known.any():
found[f"observed_{tag}"] = float(y.mean())
found[f"expected_{tag}"] = float(p.mean())
found[f"brier_{tag}"] = float(np.mean((p - y) ** 2))
if len(np.unique(y)) == 2:
found[f"auc_{tag}"] = float(roc_auc_score(y, p))
return found
def predict(self, mixture: Mixture, events: pd.DataFrame) -> pd.DataFrame:
events = f.prepared(events)
if self.predict_at == "last_screening_cytology":
chosen = f.last_screening_cytology(events)
events = events[events["person_id"].isin(chosen.index)]
events = events.assign(index_date=events["person_id"].map(chosen))
members = f.index_results(events, self.cytology, self._history())
members = members.sort_values("person_id", kind="stable").reset_index(drop=True)
return _rows(members, mixture.predict(members[self.features]), self.horizons)
@dataclass(frozen=True)
class Logistic:
"""Probability of the outcome within one year of the index sample."""
name: str
cohort: str
grades: list[str]
predictors: tuple[str, ...] = ("bethesda", "hpv", "hpv_16_18")
years: float = 1.0
method: str = field(default="logistic regression", init=False)
def train(self, events: pd.DataFrame, follow_up_end) -> tuple[Pipeline, dict, dict]:
"""Patients whose outcome is unknown (followed less than a year, no outcome) are left
out. Follow-up ends at `follow_up_end`: the date the data are known to."""
events = f.prepared(events)
found = f.index_sample(events, list(self.predictors))
outcome = f.windowed_outcome(events, self.grades, self.years,
pd.Timestamp(follow_up_end)) # fmt: skip
labelled = found.merge(outcome, on="person_id")
labelled = labelled[labelled["known"]].reset_index(drop=True)
train, test = f.split(labelled, TRAIN_FRACTION)
X = list(self.predictors)
model = Pipeline([("encode", OneHotEncoder(handle_unknown="ignore")),
("classify", LogisticRegression(max_iter=1000))]) # fmt: skip
model.fit(train[X], train["y"])
p = model.predict_proba(test[X])[:, 1]
metrics = {
"n_train": len(train),
"n_test": len(test),
"auc": float(roc_auc_score(test["y"], p)),
"brier": float(brier_score_loss(test["y"], p)),
"positive_rate_train": float(train["y"].mean()),
"positive_rate_test": float(test["y"].mean()),
"mean_probability_test": float(p.mean()),
}
return model, metrics, {"labelled": labelled, "test": test.assign(p=p)}
def predict(self, model: Pipeline, events: pd.DataFrame) -> pd.DataFrame:
members = f.index_sample(f.prepared(events), list(self.predictors))
members = members.sort_values("person_id", kind="stable").reset_index(drop=True)
p = model.predict_proba(members[list(self.predictors)])[:, 1]
return _rows(members, p[:, None], (self.years,))
_REFERRAL = {
"feature": "referral_grade", "lookback_days": cacu.REFERRAL_LOOKBACK_DAYS,
"levels": ["low", "high"], "low": ["ASC-US/LSIL"], "low_if_hpv_positive": ["NILM"],
"high": ["High Grade"],
} # fmt: skip
MODELS = {
m.name: m
for m in [
Pim("cin2_pim", "cacu_cohort_surveillance", cacu.CIN2_PLUS, cacu.KPNC,
strata=("hpv_positive",), incidence_features=("cytology",),
predict_at="last_screening_cytology"),
Pim("cancer_pim", "cacu_cohort_surveillance", cacu.CANCER, cacu.KPNC,
strata=("hpv_positive",), incidence_features=("cytology",),
predict_at="last_screening_cytology"),
Pim("cin2_pim_post_colposcopy", "cacu_cohort_post_colposcopy", cacu.CIN2_PLUS,
cacu.KPNC_3, strata=("referral_grade",),
incidence_features=("cytology", "hpv_positive"), history=_REFERRAL),
Pim("cin2_pim_post_treatment", "cacu_cohort_post_treatment", cacu.CIN2_PLUS,
cacu.KPNC_3, strata=(), incidence_features=("cytology", "hpv_positive")),
Logistic("cin2_logistic", "cacu_cohort_surveillance", cacu.CIN2_PLUS),
]
} # fmt: skip
+2
View File
@@ -14,6 +14,8 @@ dependencies = [
"markitdown[docx,xlsx]>=0.1.9",
"ocrmypdf>=17.14.2",
"pdfplumber>=0.11.11",
"scikit-learn>=1.9.1",
"scipy>=1.18.1",
]
[build-system]
+83
View File
@@ -0,0 +1,83 @@
"""The CaCu models compute what the current ones compute: fed the timelines the current
platform built for its cohorts (the reference fixtures, in its codes), each rewritten model
gives the current model's predictions.
Fixed on purpose, so left out of the comparison:
- cin2_logistic's index date: the current estimator reads P(no outcome) as a date
(1970-01-01 for everyone); the rewrite returns the index sample's date.
"""
import json
from pathlib import Path
import numpy as np
import pandas as pd
import pytest
from models.cacu.specs import MODELS
REFERENCE = Path(__file__).parents[2] / "tests" / "fixtures" / "reference" / "cacu"
RTOL = 1e-6 # as captured (models.json)
# The current platform's cohort cutoff, where the logistic model's follow-up ends.
REFERENCE_CUTOFF = "2026-11-23"
TYPES = {
"citologia": "cytology", "bethesda": "bethesda", "glandular": "glandular", "vph": "hpv",
"vph_genotipo_16_18": "hpv_16_18", "biopsia": "biopsy", "colposcopia": "colposcopy",
"orden_biopsia": "biopsy_order", "tratamiento": "treatment", "antecedente": "history",
"diagnostico": "diagnosis", "nota_medica": "note", "nacimiento": "birth",
"defuncion": "death", "citologia_de_vigilancia": "surveillance_cytology", "orden": "order",
} # fmt: skip
CODES = {
"bethesda": {"NORMAL": "NILM", "LIEBG": "LSIL", "LIEAG": "HSIL"},
"biopsy": {"NORMAL": "normal", "LIEBG": "LSIL", "LIEAG": "HSIL", "CARCINOMA": "carcinoma"},
"hpv": {"POSITIVO": "positive", "NEGATIVO": "negative"},
"cytology": {"SATISFACTORIO": "satisfactory", "INSATISFACTORIO": "unsatisfactory"},
}
COHORTS = {
"cacu_cohort_surveillance": "cohorte_vigilancia",
"cacu_cohort_post_treatment": "cohorte_post_tratamiento",
}
def timelines(cohort: str) -> pd.DataFrame:
"""A reference cohort's timelines in the platform's names and codes."""
found = pd.read_parquet(REFERENCE / "cohorts" / "cacu" / cohort / "dbt" / "1.parquet")
found = found.rename(columns={
"pac_id": "person_id", "fecha_indice": "index_date", "fecha": "date", "tipo": "type",
"valor_codigo": "value_code", "valor_numerico": "value_num",
"fuente_tabla": "source_table", "fuente_id": "source_id",
}) # fmt: skip
found["type"] = found["type"].map(TYPES)
for kind, codes in CODES.items():
rows = found["type"] == kind
found.loc[rows, "value_code"] = found.loc[rows, "value_code"].replace(codes)
return found
@pytest.mark.parametrize("name", ["cin2_pim", "cancer_pim", "cin2_pim_post_treatment",
"cin2_logistic"]) # fmt: skip
def test_predictions_match_the_current_models(name):
spec = MODELS[name]
events = timelines(COHORTS[spec.cohort])
args = (REFERENCE_CUTOFF,) if spec.method == "logistic regression" else ()
model, metrics, _ = spec.train(events, *args)
reference = pd.read_parquet(REFERENCE / "ref" / f"{name}.parquet")
current = json.loads((REFERENCE / "models.json").read_text())[name]["version"]["metrics"]
assert metrics["n_train"] == current["n_train"] and metrics["n_test"] == current["n_test"]
found = spec.predict(model, events)
both = found.merge(
reference,
left_on=["person_id", "horizon_years"],
right_on=["pac_id", "horizonte_anios"],
how="outer",
indicator=True,
)
assert (both["_merge"] == "both").all(), "the same patients and horizons are scored"
for ours, theirs in [("probability", "probabilidad"), ("ci_low", "ic_bajo"),
("ci_high", "ic_alto")]: # fmt: skip
if theirs in both:
np.testing.assert_allclose(both[ours], both[theirs], rtol=RTOL, atol=0)
if spec.method != "logistic regression":
assert (pd.to_datetime(both["index_date"]) == pd.to_datetime(both["fecha_indice"])).all()