CaCu models: no risk without HPV, hidden models untrained, inputs kept per prediction, attrition and variance diagnostics, rebuild job, opt-in Firth development evaluation

This commit is contained in:
Roberto Treviño
2026-12-05 19:42:07 -06:00
parent 69f5c20e2f
commit 20651b8d17
16 changed files with 802 additions and 68 deletions
+161
View File
@@ -0,0 +1,161 @@
"""Development only (an opt-in Dagster job; nothing registered, promoted or scored): which of
the binary encoders (models.cacu.encoders) predict CIN2+ at one year, by Firth's logistic
regression and its FLIC and FLAC corrections, chosen and judged by nested stratified
cross-validation and nested leave-one-out. Selection, coverage, rank checks and imputation
see training partitions only."""
import itertools
import math
import time
import numpy as np
import pandas as pd
from firthmodels import FirthLogisticRegression
from scipy.optimize import brentq
from scipy.special import expit, logit
from sklearn.base import BaseEstimator, ClassifierMixin, clone
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import brier_score_loss, log_loss, roc_auc_score
from sklearn.model_selection import LeaveOneOut, StratifiedKFold, cross_val_predict
from sklearn.pipeline import make_pipeline
METHODS = ("firth", "flic", "flac")
FAILED = (ValueError, np.linalg.LinAlgError, RuntimeError)
def firth(X, y, weights=None, penalty=0.5):
"""A converged Firth fit (penalty 0: maximum likelihood) and its leverages."""
model = FirthLogisticRegression(penalty_weight=penalty, max_iter=200, gtol=1e-6, xtol=1e-6)
model.fit(X, y, sample_weight=weights)
if not model.converged_:
raise RuntimeError("the Firth fit did not converge")
design = np.column_stack([np.ones(len(y)), X])
p = expit(model.intercept_ + X @ model.coef_)
w = (np.ones(len(y)) if weights is None else weights) * p * (1 - p)
information = design.T @ (w[:, None] * design)
return model, w * np.einsum("ij,ji->i", design, np.linalg.solve(information, design.T))
class Firth(ClassifierMixin, BaseEstimator):
"""Firth; FLIC (its intercept refit so the mean prediction is the outcome's); FLAC
(refit by maximum likelihood with pseudo-observations weighted by half the leverage)."""
def __init__(self, method: str = "firth"):
self.method = method
def fit(self, X, y):
X, y = np.asarray(X, float), np.asarray(y, int)
if np.linalg.matrix_rank(np.column_stack([np.ones(len(X)), X])) < X.shape[1] + 1:
raise ValueError("collinear predictors in the training partition")
model, h = firth(X, y)
self.classes_, self.coef_, self.intercept_ = np.array([0, 1]), model.coef_, model.intercept_
if self.method == "flic":
eta = X @ self.coef_
self.intercept_ = brentq(lambda a: expit(a + eta).sum() - y.sum(), -50, 50)
elif self.method == "flac":
augmented = np.column_stack([np.tile(X, (3, 1)), np.repeat([0, 1, 1], len(y))])
plain, _ = firth(augmented, np.r_[y, y, 1 - y], np.r_[np.ones(len(y)), h / 2, h / 2],
penalty=0) # fmt: skip
self.coef_, self.intercept_ = plain.coef_[:-1], plain.intercept_
return self
def predict_proba(self, X):
p = expit(self.intercept_ + np.asarray(X, float) @ self.coef_)
return np.column_stack([1 - p, p])
def same(a: pd.Series, b: pd.Series) -> bool:
return bool(((a == b) | (a.isna() & b.isna())).all())
def candidates(X: pd.DataFrame, coverage: float, limit: int) -> list[str]:
"""Binary columns known for `coverage` of the rows, best covered first, without one
identical or complementary to another, at most `limit`."""
known = X.notna().mean()
found = []
for name in sorted(X, key=lambda n: (-known[n], n)):
values = set(X[name].dropna().unique())
if known[name] < coverage or values != {0, 1}:
continue
if not any(same(X[name], X[o]) or same(X[name], 1 - X[o]) for o in found):
found.append(name)
if len(found) == limit:
break
return found
def predicted(train, y, test, columns, method, cv=None) -> np.ndarray:
"""The probabilities for `test` (or, with `cv`, out of fold for `train`)."""
if not columns:
return np.repeat(np.mean(y), len(train) if cv else len(test))
model = make_pipeline(SimpleImputer(strategy="median"), Firth(method))
if cv is not None:
return cross_val_predict(model, train[list(columns)], y, cv=cv,
method="predict_proba")[:, 1] # fmt: skip
return clone(model).fit(train[list(columns)], y).predict_proba(test[list(columns)])[:, 1]
def metrics(y, p) -> dict:
names = ("auc", "brier", "calibration_intercept", "calibration_slope", "log_loss")
if not np.isfinite(p).all() or len(np.unique(y)) != 2:
return dict.fromkeys(names)
calibration = LogisticRegression(C=1e6).fit(logit(np.clip(p, 1e-12, 1 - 1e-12))[:, None], y)
return dict(zip(names, map(float, (
roc_auc_score(y, p), brier_score_loss(y, p), calibration.intercept_[0],
calibration.coef_[0, 0], log_loss(y, p, labels=[0, 1]))), strict=True)) # fmt: skip
def evaluate(X: pd.DataFrame, y, *, coverage=0.7, candidate_limit=5, subset_limit=2,
outer_folds=3, inner_folds=2, seed=17, max_fits=100_000) -> dict: # fmt: skip
"""Per method and validation (3-fold CV, leave-one-out): the subset each outer split
chooses by inner out-of-fold log loss, the outer predictions' metrics, and every subset
tried (with why it failed)."""
X, y = X.reset_index(drop=True).apply(pd.to_numeric, errors="coerce"), np.asarray(y, int)
if min(np.bincount(y, minlength=2)) < max(outer_folds, inner_folds + 1):
raise ValueError("too few of each outcome for nested CV and leave-one-out")
subsets_max = sum(math.comb(candidate_limit, k) for k in range(subset_limit + 1))
fits = (outer_folds + len(X)) * len(METHODS) * (subsets_max * inner_folds + 1)
if fits > max_fits:
raise ValueError(f"estimated {fits} fits exceeds the limit {max_fits}")
started, attempts, validation = time.monotonic(), [], {}
inner = StratifiedKFold(inner_folds, shuffle=True, random_state=seed)
plans = {"cv": StratifiedKFold(outer_folds, shuffle=True, random_state=seed),
"loocv": LeaveOneOut()} # fmt: skip
for plan, outer in plans.items():
p = {m: np.full(len(X), np.nan) for m in METHODS}
chosen = {m: [] for m in METHODS}
for fold, (a, b) in enumerate(outer.split(X, y)):
train, test = X.iloc[a], X.iloc[b]
names = candidates(train, coverage, candidate_limit)
subsets = [c for k in range(min(len(names), subset_limit) + 1)
for c in itertools.combinations(names, k)] # fmt: skip
for method in METHODS:
ranked = []
for columns in subsets:
loss = error = None
try:
oof = predicted(train, y[a], None, columns, method, cv=inner)
loss = float(log_loss(y[a], oof, labels=[0, 1]))
ranked.append((loss, len(columns), columns))
except FAILED as e:
error = type(e).__name__
attempts.append({"validation": plan, "fold": fold, "method": method,
"variables": list(columns), "inner_log_loss": loss,
"error": error}) # fmt: skip
best = min(ranked)[2]
chosen[method].append(list(best))
try:
p[method][b] = predicted(train, y[a], test, best, method)
except FAILED:
pass
validation[plan] = {m: {
"metrics": metrics(y, p[m]), "selected": chosen[m],
"unscored": int(np.isnan(p[m]).sum()),
"stability": {n: sum(n in c for c in chosen[m]) for n in X},
} for m in METHODS} # fmt: skip
return {"development_only": True, "candidate_limit": candidate_limit,
"subset_limit": subset_limit, "coverage_minimum": coverage,
"max_subsets": subsets_max, "maximum_fits": fits,
"elapsed_seconds": time.monotonic() - started, "attempts": attempts,
"validation": validation} # fmt: skip
+159
View File
@@ -0,0 +1,159 @@
"""Binary (0/1) encoders of every variable the platform holds for a CaCu patient at her index
date, for development (models.cacu.development): NaN is missing, an absent value is never 0.
Only what was available at the index is read (`visible`). Inputs: the gold timeline with its
`evidence_date` and `source_available_at` (persistance.gold.evidence_timelines) and, for the
form fields gold doesn't carry, the cytology forms (persistance.gold.cervical_forms)."""
import numpy as np
import pandas as pd
from core import cacu, catalog
from models.cacu.features import _worst, prepared
from models.survival import age_group, band
# What was done to her before the index; the index day's own may be (or follow) the outcome.
PROCEDURES = ("biopsy", "biopsy_order", "colposcopy", "treatment", "diagnosis", "history")
EXAM_FIELDS = ("gynecologic_condition", "presenting_symptom", "cervix_appearance")
EVIDENCE = "cacu_eligibility_evidence"
FORM = catalog.studies()["cervical_cytology"].fields
FINDINGS = tuple(n for n, f in FORM.items() if n.startswith("finding_") and f.type == "boolean")
def codes(field: str) -> list[str]:
return list(FORM[field].codes)
def day(values: pd.Series) -> pd.Series:
return pd.to_datetime(values.astype("string").str[:10], format="%Y-%m-%d")
def visible(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame:
"""Her events available at her index: dated and clinically dated by it, made available
by it when the source says when (else by its date; standalone evidence then left out, as
the cohorts do), and procedures and a hysterectomy strictly before it. When the platform
loaded it (`known_at`) isn't read."""
found = events.drop(columns="index_date", errors="ignore").merge(
members[["person_id", "index_date"]], on="person_id") # fmt: skip
index = pd.to_datetime(found["index_date"]).dt.normalize()
date, clinical, available = (day(found[c]) for c in ("date", "evidence_date",
"source_available_at")) # fmt: skip
keep = (date <= index) & (clinical.isna() | (clinical <= index))
keep &= (available.isna() & (found["source_table"] != EVIDENCE)) | (available <= index)
before = (date < index) & (clinical.isna() | (clinical < index))
done = found["type"].isin(PROCEDURES) | (found["value_code"] == "hysterectomy")
return prepared(found[keep & (before | ~done)])
def flag(known: pd.Series, true: pd.Series) -> pd.Series:
return pd.Series(np.where(known, true.astype(float), np.nan), index=known.index)
def one_hot(values: pd.Series, prefix: str, of: list[str]) -> dict[str, pd.Series]:
"""A column per code; a value that is none of them is missing, not 0 in all."""
return {f"{prefix}__{c}": flag(values.isin(of), values == c) for c in of}
def present(events: pd.DataFrame, people: pd.Index) -> pd.Series:
"""1 when recorded, else missing (no record doesn't show it never happened)."""
return pd.Series(np.where(people.isin(events["person_id"]), 1.0, np.nan), index=people)
def latest(events: pd.DataFrame, kind: str, people: pd.Index) -> pd.Series:
found = events[(events["type"] == kind) & events["value_code"].notna()]
found = found.sort_values(["date", "source_id"], kind="stable")
return found.groupby("person_id")["value_code"].last().reindex(people)
def results(seen: pd.DataFrame, members: pd.DataFrame, people: pd.Index) -> dict:
"""Her age group, her latest cytology (its worst result that day) and HPV results."""
cuts = [low for low, _ in cacu.AGE_GROUPS] + [cacu.AGE_GROUPS[-1][1] + 1]
keyed = members.set_index("person_id", drop=False)
ages = age_group(seen, keyed.assign(index_date=pd.to_datetime(keyed["index_date"])), cuts)
out = one_hot(ages, "age", list(band(pd.Series([cuts[0] - 1, *cuts]), cuts)))
found = seen[(seen["type"] == "bethesda") & seen["value_code"].isin(codes("result"))]
found = found[found["date"] == found.groupby("person_id")["date"].transform("max")]
severity = {n: [n] for names in cacu.KPNC.values() for n in names if n in codes("result")}
result = _worst(found.set_index("person_id")["value_code"], severity).reindex(people)
out |= one_hot(result, "bethesda", codes("result"))
out |= {f"cytology_{name}": flag(result.notna(), result.isin(of))
for name, of in cacu.PROCEDURE_CYTOLOGY.items()} # fmt: skip
for kind in ("hpv", *cacu.HPV_GENOTYPE_FIELDS):
value = latest(seen, kind, people)
out[f"{kind}_positive"] = flag(value.isin(["positive", "negative"]), value == "positive")
# from one sample's two genotypes: positive if either is, negative only if both are
typed = seen[seen["type"].isin(cacu.HPV_GENOTYPE_FIELDS) & seen["value_code"].notna()]
wide = typed.pivot_table(index=["person_id", "date", "source_id"], columns="type",
values="value_code", aggfunc="first") # fmt: skip
wide = wide.reindex(columns=cacu.HPV_GENOTYPE_FIELDS).sort_index().reset_index()
last = wide.drop_duplicates("person_id", keep="last").set_index("person_id").reindex(people)
positive = (last[cacu.HPV_GENOTYPE_FIELDS] == "positive").any(axis=1)
negative = (last[cacu.HPV_GENOTYPE_FIELDS] == "negative").all(axis=1)
out["hpv_16_or_18_positive"] = flag(positive | negative, positive)
return out
def history(seen: pd.DataFrame, people: pd.Index) -> dict:
"""What was done to her before, the worst biopsy, and her referral's grade (the last
sample before her first colposcopy, as gold links it)."""
of = {kind: seen[seen["type"] == kind] for kind in (*PROCEDURES, "cytology")}
sampled = of["cytology"][of["cytology"]["date"] < of["cytology"]["index_date"]]
removed = seen[(seen["type"] == "gynecologic_condition")
& (seen["value_code"] == "hysterectomy")] # fmt: skip
out = {"prior_cytology_sample": present(sampled, people),
**{f"prior_{n}": present(of[k], people) for n, k in (
("biopsy_order", "biopsy_order"), ("biopsy_report", "biopsy"),
("colposcopy", "colposcopy"), ("treatment", "treatment"),
("diagnosis_note", "diagnosis"))},
"history_cancer_icd10": present(of["history"], people),
"history_hysterectomy": present(removed, people)} # fmt: skip
rank = {grade: i for i, grade in enumerate(cacu.BIOPSY_SEVERITY)}
worst = of["biopsy"]["value_code"].map(rank).groupby(of["biopsy"]["person_id"]).max()
worst = worst.reindex(people)
for name, grade in (("lsil_plus", "LSIL"), ("hsil_plus", "CIN2"), ("carcinoma", "carcinoma")):
out[f"prior_biopsy_{name}"] = flag(worst.notna(), worst >= rank[grade])
first = of["colposcopy"].groupby("person_id")["date"].min()
graded = seen[seen["type"].isin(["bethesda", "glandular"]) & seen["value_code"].notna()]
graded = graded[graded["date"] < graded["person_id"].map(first)]
graded = graded[graded["date"] == graded.groupby("person_id")["date"].transform("max")]
referral = _worst(graded.set_index("person_id")["value_code"], cacu.KPNC_3).reindex(people)
out["referral_high_grade"] = flag(referral.notna(), referral == "High Grade")
return out
def forms(found: pd.DataFrame | None, members: pd.DataFrame, people: pd.Index) -> dict:
"""The form's fields gold doesn't carry: what the sample form says counts from the
sample day, the latest report (whole: what it doesn't state is unknown) from its day."""
columns = ["person_id", "sample_date", "report_date", "screening_history", "adequacy",
*FINDINGS] # fmt: skip
found = (pd.DataFrame(columns=columns) if found is None else found[columns]).merge(
members[["person_id", "index_date"]], on="person_id") # fmt: skip
index = pd.to_datetime(found["index_date"]).dt.normalize()
found = found.assign(s=day(found["sample_date"]), r=day(found["report_date"]))
told = found[(found["s"] <= index) & found["screening_history"].notna()].sort_values("s")
said = told.groupby("person_id")["screening_history"].last().reindex(people)
report = found[(found["r"] <= index) & (found["s"] <= index)].sort_values(["r", "s"])
report = report.drop_duplicates("person_id", keep="last").set_index("person_id")
report = report.reindex(people)
out = one_hot(said, "screening_history", codes("screening_history"))
adequacy = report["adequacy"]
out["sample_unsatisfactory"] = flag(adequacy.isin(codes("adequacy")),
adequacy == "unsatisfactory") # fmt: skip
return out | {n: flag(report[n].notna(), report[n].eq(True)) for n in FINDINGS}
def encode(events: pd.DataFrame, cytology_forms: pd.DataFrame | None = None) -> pd.DataFrame:
"""One row per member (`person_id`, `index_date`, one index each) with every encoder's
column: 0.0, 1.0 or NaN."""
members = events[["person_id", "index_date"]].drop_duplicates().reset_index(drop=True)
if members["person_id"].duplicated().any():
raise ValueError("one index date per person")
people = pd.Index(members["person_id"], name="person_id")
seen = visible(events, members)
exam = seen[seen["source_table"] == "cervical_cytology"]
columns = {**results(seen, members, people), **history(seen, people),
**forms(cytology_forms, members, people)} # fmt: skip
for field in EXAM_FIELDS:
columns |= one_hot(latest(exam, field, people), field, codes(field))
values = {name: column.to_numpy(dtype=float) for name, column in columns.items()}
return pd.concat([members, pd.DataFrame(values)], axis=1)
+11 -19
View File
@@ -30,25 +30,11 @@ def _worst(codes: pd.Series, cytology: dict) -> pd.Series:
return worst.map(lambda r: None if np.isnan(r) else names[int(r)]).astype(object) 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): 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 """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 result of each kind within INDEX_SAMPLE_DAYS of the index), and the referral grade
when `history` asks for it.""" (gold's, from the cytology linked to her colposcopy) when `history` asks for it. One
without an HPV result is left out: not evaluated, never read as negative."""
near = events[days(events).between(0, cacu.INDEX_SAMPLE_DAYS) & events["type"].isin(RESULTS)] near = events[days(events).between(0, cacu.INDEX_SAMPLE_DAYS) & events["type"].isin(RESULTS)]
wide = near.sort_values("date", kind="stable").pivot_table( wide = near.sort_values("date", kind="stable").pivot_table(
index="person_id", columns="type", values="value_code", aggfunc="first" index="person_id", columns="type", values="value_code", aggfunc="first"
@@ -59,8 +45,9 @@ def index_results(events: pd.DataFrame, cytology: dict, history: dict | None = N
members["cytology"] = _worst(codes, cytology).reindex(members["person_id"]).to_numpy() members["cytology"] = _worst(codes, cytology).reindex(members["person_id"]).to_numpy()
members["hpv_positive"] = (wide["hpv"] == "positive").astype(float).to_numpy() members["hpv_positive"] = (wide["hpv"] == "positive").astype(float).to_numpy()
if history: if history:
members[history["feature"]] = _referral_grade(events, members["person_id"], history) grades = events[events["type"] == history["feature"]].groupby("person_id")["value_code"]
return members members[history["feature"]] = members["person_id"].map(grades.first()).astype(object)
return members[wide["hpv"].notna().to_numpy()].reset_index(drop=True)
def _negatives(events: pd.DataFrame, d: pd.Series, grades: list[str]) -> pd.DataFrame: def _negatives(events: pd.DataFrame, d: pd.Series, grades: list[str]) -> pd.DataFrame:
@@ -110,11 +97,16 @@ def interval_coded(events: pd.DataFrame, grades: list[str], cytology: dict,
def last_screening_cytology(events: pd.DataFrame) -> pd.Series: def last_screening_cytology(events: pd.DataFrame) -> pd.Series:
"""Per patient never referred: her latest sample with both a cytology and an HPV result.""" """Per patient never referred: her latest sample with both a cytology and an HPV result,
before any hysterectomy her cytology forms record."""
referred = set(events.loc[events["type"].isin(REFERRED), "person_id"]) referred = set(events.loc[events["type"].isin(REFERRED), "person_id"])
key = ["person_id", "source_table", "source_id"] key = ["person_id", "source_table", "source_id"]
samples = events.loc[(events["type"] == "cytology") & ~events["person_id"].isin(referred), samples = events.loc[(events["type"] == "cytology") & ~events["person_id"].isin(referred),
[*key, "date"]] # fmt: skip [*key, "date"]] # fmt: skip
removed = events[(events["type"] == "gynecologic_condition")
& (events["value_code"] == "hysterectomy")] # fmt: skip
since = samples["person_id"].map(removed.groupby("person_id")["date"].min())
samples = samples[since.isna() | (samples["date"] < since)]
results = events[events["type"].isin(RESULTS) & events["value_code"].notna()] results = events[events["type"].isin(RESULTS) & events["value_code"].notna()]
has = results.pivot_table(index=key, columns="type", values="value_code", aggfunc="first") has = results.pivot_table(index=key, columns="type", values="value_code", aggfunc="first")
has = has.reindex(columns=list(RESULTS)) has = has.reindex(columns=list(RESULTS))
+13 -2
View File
@@ -1,8 +1,19 @@
"""CaCu's training and scoring jobs (models.jobs) over its models and reports.""" """CaCu's training and scoring jobs (models.jobs) over its models and reports, with who
each cohort lost (gold.cacu_eligibility, the scenario named after the cohort)."""
from datetime import date
from models.cacu import reports from models.cacu import reports
from models.cacu.specs import MODELS from models.cacu.specs import MODELS
from models.jobs import Jobs from models.jobs import Jobs
from persistance import gold
JOBS = Jobs("cacu", MODELS, reports.technical_validation, reports.interpretability)
def attrition(spec, as_of: date) -> dict:
scenario = spec.cohort.removeprefix("cacu_cohort_")
rows = gold.eligibility(scenario, as_of)
return reports.attrition(spec.cohort, scenario, rows, gold.people("cacu_events", as_of), as_of)
JOBS = Jobs("cacu", MODELS, reports.technical_validation, reports.interpretability, attrition)
train, score = JOBS.train, JOBS.score train, score = JOBS.train, JOBS.score
+37 -5
View File
@@ -140,8 +140,16 @@ class Fit:
for t in years for t in years
]) # fmt: skip ]) # fmt: skip
def estimable(self) -> tuple[np.ndarray, bool]:
"""The estimated (not frozen) parameters; whether their covariance is positive definite."""
free = np.isfinite(np.diag(self.covariance))
block = self.covariance[np.ix_(free, free)]
finite = bool(block.size and np.isfinite(block).all() and np.allclose(block, block.T))
return free, finite and bool((np.linalg.eigvalsh(block) > 0).all())
def risk_with_variance(self, X, Z, years) -> tuple[np.ndarray, np.ndarray]: def risk_with_variance(self, X, Z, years) -> tuple[np.ndarray, np.ndarray]:
"""Risk and its delta-method variance (central-difference gradient).""" """Risk and its delta-method variance (central-difference gradient); the variance is
unknown (NaN) where the covariance isn't proper or a frozen parameter moves it."""
gradient = np.empty((len(self.params), len(X), len(years))) gradient = np.empty((len(self.params), len(X), len(years)))
for k, value in enumerate(self.params): for k, value in enumerate(self.params):
step = 1e-5 * max(1.0, abs(value)) step = 1e-5 * max(1.0, abs(value))
@@ -149,9 +157,15 @@ class Fit:
up[k] += step up[k] += step
down[k] -= step down[k] -= step
gradient[k] = (self.risk(X, Z, years, up) - self.risk(X, Z, years, down)) / (2 * 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.full((len(X), len(years)), np.nan)
variance = np.einsum("kij,kl,lij->ij", gradient, covariance, gradient) free, proper = self.estimable()
return self.risk(X, Z, years), np.maximum(variance, 0.0) if proper:
block = self.covariance[np.ix_(free, free)]
found = np.einsum("kij,kl,lij->ij", gradient[free], block, gradient[free])
moved = np.any(np.abs(gradient[~free]) > 1e-10, axis=0)
known = ~moved & np.isfinite(found) & (found >= 0)
variance[known] = found[known]
return self.risk(X, Z, years), variance
def fit(c, l, r, X, Z, baseline: ISpline, w) -> Fit: def fit(c, l, r, X, Z, baseline: ISpline, w) -> Fit:
@@ -251,6 +265,8 @@ class Mixture(BaseEstimator):
continue continue
members = X.iloc[index] members = X.iloc[index]
placed = self._placed(members, self.seen_[key]) placed = self._placed(members, self.seen_[key])
if not placed.any(): # nobody it can place
continue
prevalence, incidence = self._design(members[placed], self.seen_[key]) prevalence, incidence = self._design(members[placed], self.seen_[key])
design = np.column_stack([prevalence, incidence]) design = np.column_stack([prevalence, incidence])
unique, inverse = np.unique(design, axis=0, return_inverse=True) unique, inverse = np.unique(design, axis=0, return_inverse=True)
@@ -258,8 +274,24 @@ class Mixture(BaseEstimator):
point, variance = self.fits_[key].risk_with_variance( point, variance = self.fits_[key].risk_with_variance(
unique[:, :n_x], unique[:, n_x:], self.horizons_years unique[:, :n_x], unique[:, n_x:], self.horizons_years
) )
relative = np.where(point > 0, np.sqrt(variance) / np.maximum(point, 1e-300), 0.0) relative = np.sqrt(variance) / np.maximum(point, 1e-300) # NaN: no interval
band = np.column_stack([point, np.clip(point * np.exp(-z * relative), 0, 1), 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 np.clip(point * np.exp(z * relative), 0, 1)]) # fmt: skip
out[index[placed]] = band[inverse.ravel()] out[index[placed]] = band[inverse.ravel()]
return out return out
def variance_diagnostics(self, X: pd.DataFrame) -> dict:
"""Per stratum: its covariance's state and how many rows of `X` get no interval."""
h, found = len(self.horizons_years), []
for key, index in self._groups(X):
missing = np.isnan(self.predict(X.iloc[index])[:, h:]).any(axis=1)
f = self.fits_.get(key)
d, params = (np.diag(f.covariance), f.params) if f else (np.array([]), np.array([]))
status = "unseen_stratum" if f is None else (
"positive_definite" if f.estimable()[1] else "not_estimable") # fmt: skip
negative = np.flatnonzero(np.isfinite(d) & (d < 0)).tolist()
found.append({"stratum": [str(v) for v in key], "rows": len(index),
"rows_without_interval": int(missing.sum()), "status": status,
"frozen_parameters": np.flatnonzero(np.abs(params) >= FROZEN).tolist(),
"negative_variances": negative}) # fmt: skip
return {"strata": found, "horizons_years": list(self.horizons_years)}
+35 -1
View File
@@ -19,6 +19,15 @@ from models.cacu.pim import Mixture
from models.cacu.specs import Logistic, Pim from models.cacu.specs import Logistic, Pim
GRID_STEP = 0.1 # years between points of a curve GRID_STEP = 0.1 # years between points of a curve
# Reasons a result still to arrive could lift, and the clinical stage of each (a candidate
# may be excluded at several).
AWAITING = {"unreported_biopsy", "no_index_result"}
STAGES = {"eligibility": ("hysterectomy", "under_18", "no_birth_date", "died_by_index"),
"history": ("prior_outcome", "outcome_by_index", "cancer_history", "prior_treatment",
"outcome_before_index", "no_pretreatment_biopsy"),
"index": ("no_referral", "referral_not_graded", "no_cotest", "no_index_result",
"unreported_biopsy")} # fmt: skip
STAGE = {reason: stage for stage, reasons in STAGES.items() for reason in reasons}
BOOTSTRAP = 200 BOOTSTRAP = 200
SEED = 20261122 SEED = 20261122
Z = norm.ppf(0.975) Z = norm.ppf(0.975)
@@ -72,7 +81,7 @@ def _label(feature: str, value) -> str:
def _band(curve, variance) -> tuple[list, list]: def _band(curve, variance) -> tuple[list, list]:
relative = np.where(curve > 0, np.sqrt(variance) / np.maximum(curve, 1e-300), 0.0) relative = np.sqrt(variance) / np.maximum(curve, 1e-300) # NaN where it can't be had
return (np.clip(curve * np.exp(-Z * relative), 0, 1).tolist(), return (np.clip(curve * np.exp(-Z * relative), 0, 1).tolist(),
np.clip(curve * np.exp(Z * relative), 0, 1).tolist()) # fmt: skip np.clip(curve * np.exp(Z * relative), 0, 1).tolist()) # fmt: skip
@@ -170,3 +179,28 @@ def _logistic(model, test: pd.DataFrame, bins: int = 10) -> dict:
], ],
}, # fmt: skip }, # fmt: skip
} }
def attrition(cohort: str, scenario: str, rows: pd.DataFrame, people: int, as_of) -> dict:
"""Who a cohort lost and why by `as_of`. `rows`: its candidates' eligibility (one per
candidate and reason). A candidate with several reasons is excluded once and counted in
each reason; `pending`: the excluded whose every reason awaits a result."""
key = ["person_id", "index_date", "index_sample_id"]
rows = rows[rows["index_date"].astype(str).str[:10] <= as_of.isoformat()]
candidates = rows[key].drop_duplicates()
excluded = rows[rows["criterion"].notna()]
reasons = excluded.groupby(key, dropna=False)["criterion"].agg(set)
stages = excluded.assign(stage=excluded["criterion"].map(STAGE).fillna("unknown"))
return {
"cohort": cohort, "scenario": scenario, "as_of": as_of.isoformat(), "people": people,
"without_candidate": people - candidates["person_id"].nunique(),
"candidates": len(candidates), "eligible": len(candidates) - len(reasons),
"excluded": len(reasons), "pending": int(sum(r <= AWAITING for r in reasons)),
"by_reason": {str(r): int(n) for r, n in
excluded["criterion"].value_counts().sort_index().items()},
"by_stage": {str(s): len(g[key].drop_duplicates())
for s, g in stages.groupby("stage", sort=True)},
"stage_by_reason": {str(r): STAGE.get(r, "unknown")
for r in sorted(excluded["criterion"].unique())},
"stage_counts_overlap": True, # one candidate may be out at several stages
} # fmt: skip
+28 -13
View File
@@ -15,15 +15,17 @@ from sklearn.preprocessing import OneHotEncoder
from core import cacu from core import cacu
from models.cacu import features as f from models.cacu import features as f
from models.cacu.pim import Mixture from models.cacu.pim import Mixture
from models.survival import Spec, age_group from models.survival import Spec, age_group, band, inputs
HORIZONS = (0.0, 1.0, 2.0, 3.0, 4.0, 5.0) HORIZONS = (0.0, 1.0, 2.0, 3.0, 4.0, 5.0)
TRAIN_FRACTION = 0.7 TRAIN_FRACTION = 0.7
OUTPUT = ["person_id", "index_date", "horizon_years", "probability", "ci_low", "ci_high"] OUTPUT = ["person_id", "index_date", "horizon_years", "probability", "ci_low", "ci_high",
"input_values"] # fmt: skip
def _rows(members: pd.DataFrame, risks: np.ndarray, horizons) -> pd.DataFrame: def _rows(members: pd.DataFrame, risks: np.ndarray, horizons, read) -> pd.DataFrame:
"""One row per patient and horizon; patients the model can't score are left out.""" """One row per patient and horizon, with what her estimate `read`; patients the model
can't score are left out."""
h = len(horizons) h = len(horizons)
scored = ~np.isnan(risks[:, :h]).any(axis=1) scored = ~np.isnan(risks[:, :h]).any(axis=1)
members, risks = members[scored], risks[scored] members, risks = members[scored], risks[scored]
@@ -33,6 +35,7 @@ def _rows(members: pd.DataFrame, risks: np.ndarray, horizons) -> pd.DataFrame:
"index_date": np.repeat(pd.to_datetime(members["index_date"]).dt.date.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), "horizon_years": np.tile(np.asarray(horizons, dtype=float), n),
"probability": risks[:, :h].ravel(), "probability": risks[:, :h].ravel(),
"input_values": inputs(members, read, h),
}) # fmt: skip }) # fmt: skip
if risks.shape[1] == 3 * h: if risks.shape[1] == 3 * h:
frame["ci_low"], frame["ci_high"] = risks[:, h : 2 * h].ravel(), risks[:, 2 * h :].ravel() frame["ci_low"], frame["ci_high"] = risks[:, h : 2 * h].ravel(), risks[:, 2 * h :].ravel()
@@ -61,7 +64,7 @@ class Pim:
return ["cytology", "hpv_positive"] + ([self.history["feature"]] if self.history else []) return ["cytology", "hpv_positive"] + ([self.history["feature"]] if self.history else [])
def _history(self) -> dict | None: def _history(self) -> dict | None:
return self.history and {**self.history, "cytology": self.cytology} return self.history
def train(self, events: pd.DataFrame, as_of=None) -> tuple[Mixture, dict, dict]: def train(self, events: pd.DataFrame, as_of=None) -> tuple[Mixture, dict, dict]:
"""The fitted mixture, its metrics on the held-out latest patients, and the coded """The fitted mixture, its metrics on the held-out latest patients, and the coded
@@ -110,7 +113,8 @@ class Pim:
events = events.assign(index_date=events["person_id"].map(chosen)) events = events.assign(index_date=events["person_id"].map(chosen))
members = f.index_results(events, self.cytology, self._history()) members = f.index_results(events, self.cytology, self._history())
members = members.sort_values("person_id", kind="stable").reset_index(drop=True) members = members.sort_values("person_id", kind="stable").reset_index(drop=True)
return _rows(members, mixture.predict(members[self.features]), self.horizons) return _rows(members, mixture.predict(members[self.features]), self.horizons,
self.features) # fmt: skip
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -156,14 +160,14 @@ class Logistic:
members = f.index_sample(f.prepared(events), list(self.predictors)) members = f.index_sample(f.prepared(events), list(self.predictors))
members = members.sort_values("person_id", kind="stable").reset_index(drop=True) members = members.sort_values("person_id", kind="stable").reset_index(drop=True)
p = model.predict_proba(members[list(self.predictors)])[:, 1] p = model.predict_proba(members[list(self.predictors)])[:, 1]
return _rows(members, p[:, None], (self.years,)) return _rows(members, p[:, None], (self.years,), self.predictors)
def survival_covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame: def survival_covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame:
"""Each member's most recent observations up to her index (that day included): her age """Each member's most recent observations up to her index (that day included): her age
group, the KPNC category of her latest cytology result and her latest HPV result.""" group, the KPNC category of her latest cytology result and her latest HPV result."""
found = pd.DataFrame(index=members.index) found = pd.DataFrame(index=members.index)
found["age_group"] = age_group(events, members, (35, 45, 55)) found["age_group"] = age_group(events, members, SURVIVAL_AGE_CUTS)
prior = events[events["date"] <= events["index_date"]] prior = events[events["date"] <= events["index_date"]]
names = list(cacu.KPNC) names = list(cacu.KPNC)
severity = {code: rank for rank, codes in enumerate(cacu.KPNC.values()) for code in codes} severity = {code: rank for rank, codes in enumerate(cacu.KPNC.values()) for code in codes}
@@ -177,10 +181,14 @@ def survival_covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataF
return found.astype(object) return found.astype(object)
_REFERRAL = { _REFERRAL = {"feature": "referral_grade", "levels": ["low", "high"]} # graded in gold
"feature": "referral_grade", "lookback_days": cacu.REFERRAL_LOOKBACK_DAYS, SURVIVAL_AGE_CUTS = (35, 45, 55)
"levels": ["low", "high"], "low": ["ASC-US/LSIL"], "low_if_hpv_positive": ["NILM"], # The clinical scenarios survival's report draws, and her record with them.
"high": ["High Grade"], SURVIVAL_SCENARIOS = {
**{f"Edad al diagnóstico · {g} años": (("age_group", "==", g),)
for g in band(pd.Series([0, *SURVIVAL_AGE_CUTS]), list(SURVIVAL_AGE_CUTS))},
**{f"Citología · {g}": (("cytology", "==", g),) for g in cacu.KPNC},
"VPH positivo": (("hpv", "==", "positive"),), "VPH negativo": (("hpv", "==", "negative"),),
} # fmt: skip } # fmt: skip
MODELS = { MODELS = {
@@ -197,9 +205,16 @@ MODELS = {
incidence_features=("cytology", "hpv_positive"), history=_REFERRAL), incidence_features=("cytology", "hpv_positive"), history=_REFERRAL),
Pim("cin2_pim_post_treatment", "cacu_cohort_post_treatment", cacu.CIN2_PLUS, Pim("cin2_pim_post_treatment", "cacu_cohort_post_treatment", cacu.CIN2_PLUS,
cacu.KPNC_3, strata=(), incidence_features=("cytology", "hpv_positive")), cacu.KPNC_3, strata=(), incidence_features=("cytology", "hpv_positive")),
# Hidden (core.models.HIDDEN): CIN3+ needs biopsies that tell CIN3 from CIN2.
Pim("cin3_pim", "cacu_cohort_surveillance", cacu.CIN3_PLUS, cacu.KPNC,
strata=("hpv_positive",), incidence_features=("cytology",),
predict_at="last_screening_cytology"),
Pim("cin3_pim_post_colposcopy", "cacu_cohort_post_colposcopy", cacu.CIN3_PLUS,
cacu.KPNC_3, strata=("referral_grade",),
incidence_features=("cytology", "hpv_positive"), history=_REFERRAL),
Logistic("cin2_logistic", "cacu_cohort_surveillance", cacu.CIN2_PLUS), Logistic("cin2_logistic", "cacu_cohort_surveillance", cacu.CIN2_PLUS),
Spec("survival", "cacu_cohort_survival", ("age_group", "cytology", "hpv"), Spec("survival", "cacu_cohort_survival", ("age_group", "cytology", "hpv"),
survival_covariates, borders=(0, 12, 36, 60), cap_months=60, survival_covariates, borders=(0, 12, 36, 60), cap_months=60,
interval_level=0.95), interval_level=0.95, scenarios=SURVIVAL_SCENARIOS),
] ]
} # fmt: skip } # fmt: skip
+55 -2
View File
@@ -100,7 +100,7 @@ class Scoring(dg.Config):
def score_models(context: dg.OpExecutionContext, config: Scoring) -> dict: def score_models(context: dg.OpExecutionContext, config: Scoring) -> dict:
"""Each model's champion scores its cohort; then gold's risk tables are rebuilt.""" """Each model's champion scores its cohort; then gold's risk tables are rebuilt."""
jobs = _jobs(config.domain) jobs = _jobs(config.domain)
found = {name: jobs.score(name) for name in config.models or jobs.JOBS.scored()} found = {name: jobs.score(name) for name in config.models or jobs.JOBS.routine()}
for name, version in found.items(): for name, version in found.items():
context.log.info(f"{name}: " + (f"version {version}" if version else "no champion")) context.log.info(f"{name}: " + (f"version {version}" if version else "no champion"))
silver.build([getattr(jobs, "GOLD", f"{config.domain}_risk") + "+"]) silver.build([getattr(jobs, "GOLD", f"{config.domain}_risk") + "+"])
@@ -129,6 +129,58 @@ def analyze():
analyze_studies() analyze_studies()
class Development(dg.Config):
as_of: str
max_fits: int = 100_000
@dg.op
def evaluate_cacu_development(context: dg.OpExecutionContext, config: Development) -> str:
"""Opt-in research (models.cacu.development): which encoders predict CIN2+ at one year
in the surveillance cohort; logged to MLflow, nothing registered, promoted or scored."""
import mlflow
import pandas as pd
from core import cacu
from models.cacu import development, encoders, features
from persistance import gold, registry
as_of, cohort = date.fromisoformat(config.as_of), "cacu_cohort_surveillance"
events = gold.evidence_timelines("cacu_events", cohort, as_of)
if events.empty:
raise EmptyCohort(f"nobody in {cohort}")
outcome = features.windowed_outcome(features.prepared(events), cacu.CIN2_PLUS, 1.0,
pd.Timestamp(as_of)) # fmt: skip
rows = encoders.encode(events, gold.cervical_forms(cohort)).merge(outcome, on="person_id")
rows = rows[rows["known"]].reset_index(drop=True)
X = rows.drop(columns=["person_id", "index_date", "known", "y"])
report = development.evaluate(X, rows["y"].to_numpy(), max_fits=config.max_fits)
report |= {"cohort": cohort, "as_of": as_of.isoformat(), "outcome": "CIN2+ at one year"}
mlflow.set_experiment(registry.EXPERIMENT)
with mlflow.start_run(run_name="cacu.cin2_firth_development") as run:
mlflow.log_dict(report, "reports/development_evaluation.json")
context.log.info(f"development evaluation logged as {run.info.run_id}")
return run.info.run_id
@dg.job
def cacu_development_evaluation():
evaluate_cacu_development()
@dg.op
def build_gold(context: dg.OpExecutionContext) -> None:
"""Silver and all that derives from it, with the deployed code: an ingest's end without
ingesting (after deploying a version that changes the tables)."""
silver.build(["silver+"])
context.log.info("silver and gold rebuilt")
@dg.job(tags=WRITES)
def rebuild():
build_gold()
@dg.op @dg.op
def make_backup(context: dg.OpExecutionContext) -> str: def make_backup(context: dg.OpExecutionContext) -> str:
"""The data folder into BACKUP_DIR (persistance.backup); the newest BACKUP_KEEP stay.""" """The data folder into BACKUP_DIR (persistance.backup); the newest BACKUP_KEEP stay."""
@@ -153,4 +205,5 @@ nightly = (
else [] else []
) )
defs = dg.Definitions(jobs=[ingest, draft_job, train, score, analyze, backup], schedules=nightly) JOBS = [ingest, draft_job, train, score, analyze, rebuild, backup, cacu_development_evaluation]
defs = dg.Definitions(jobs=JOBS, schedules=nightly)
+18 -8
View File
@@ -22,6 +22,7 @@ from splink.clustering import cluster_pairwise_predictions_at_threshold
from core import catalog, concept_map, fhir_in from core import catalog, concept_map, fhir_in
from core.drafting import extract_prompt from core.drafting import extract_prompt
from core.pipeline import ( from core.pipeline import (
FIELD_EVIDENCE,
HELD, HELD,
IDENTIFIERS, IDENTIFIERS,
QUOTES, QUOTES,
@@ -186,14 +187,12 @@ def run_map(p: str, node: Map):
def run_fhir(p: str, node: Fhir): def run_fhir(p: str, node: Fhir):
"""Each Bundle's rows of the node's entity; a resource sent again is its latest.""" """The node's entity from every Bundle at its source, as one: a resource sent again is
its latest, and one Bundle may name what another sent."""
maps = [config_log.concept_map(node.concept_map)] if node.concept_map else [] maps = [config_log.concept_map(node.concept_map)] if node.concept_map else []
found: dict[str, dict] = {} sent = sorted(nodes.rows(p, node.inputs[0]), key=lambda r: str(r.get("received_at") or ""))
for row in nodes.rows(p, node.inputs[0]): bundle = fhir_in.combined(json.loads(row[node.column]) for row in sent)
bundle = json.loads(row[node.column]) return nodes.write(p, node.id, fhir_in.rows(bundle, node.entity, p, maps))
for r in fhir_in.rows(bundle, node.entity, p, maps):
found[r[RECORD]] = r
return nodes.write(p, node.id, list(found.values()))
def run_join(p: str, node: Join): def run_join(p: str, node: Join):
@@ -472,6 +471,15 @@ def run_link(p: str, node: Link):
return nodes.write(p, f"{node.id}__review", queue) return nodes.write(p, f"{node.id}__review", queue)
def provenance(study, clean, field, record: str) -> dict:
"""Where a value comes from when its source doesn't say: the day of its event, made
available with the study's report (its own event's day without one)."""
day = getattr(clean, study.events[field.event].date)
available = getattr(clean, study.events["report"].date) if "report" in study.events else day
return {"source_ref": record, "source_clinical_date": day and str(day),
"source_available_at": available and str(available)} # fmt: skip
def run_target(p: str, node: Target, kinds: dict[str, str]): def run_target(p: str, node: Target, kinds: dict[str, str]):
"""Rows of one study into silver's staging, each given its person by the link node: """Rows of one study into silver's staging, each given its person by the link node:
a clean row becomes one observation per field it has (long), keyed by its study a clean row becomes one observation per field it has (long), keyed by its study
@@ -500,9 +508,11 @@ def run_target(p: str, node: Target, kinds: dict[str, str]):
continue continue
clean = model.model_validate(values) clean = model.model_validate(values)
instance = json.dumps([str(getattr(clean, k)) for k in model.key]) instance = json.dumps([str(getattr(clean, k)) for k in model.key])
sent = json.loads(row.get(FIELD_EVIDENCE) or "{}")
for name, field in study.fields.items(): for name, field in study.fields.items():
if (value := getattr(clean, name)) is not None: if (value := getattr(clean, name)) is not None:
observations.append({**base, "instance": instance, "field": name, source = sent.get(name) or provenance(study, clean, field, row[RECORD])
observations.append({**base, **source, "instance": instance, "field": name,
catalog.value_column(field): value}) # fmt: skip catalog.value_column(field): value}) # fmt: skip
nodes.stage("observation", p, node.id, observations, silver.OBSERVATION) nodes.stage("observation", p, node.id, observations, silver.OBSERVATION)
return nodes.stage("held", p, node.id, held_rows, silver.HELD_ROWS) return nodes.stage("held", p, node.id, held_rows, silver.HELD_ROWS)
+14 -12
View File
@@ -11,6 +11,7 @@ import mlflow.pyfunc
import pandas as pd import pandas as pd
from joblib.externals.loky import get_reusable_executor from joblib.externals.loky import get_reusable_executor
from core import models
from persistance import gold, registry from persistance import gold, registry
@@ -35,18 +36,17 @@ class Jobs:
models: dict models: dict
technical_validation: Callable[..., dict] technical_validation: Callable[..., dict]
interpretability: Callable[..., dict] interpretability: Callable[..., dict]
# (spec, as_of) -> who the model's cohort lost and why, kept beside its reports (not one
# promotion asks for); None: not kept
attrition: Callable[..., dict | None] | None = None
@property @property
def events(self) -> str: def events(self) -> str:
return f"{self.domain}_events" return f"{self.domain}_events"
def routine(self) -> list[str]: def routine(self) -> list[str]:
"""The models a train run takes when none is named: all of them.""" """The models a run takes when none is named: all but the hidden ones."""
return list(self.models) return [n for n in self.models if self.registered(n) not in models.HIDDEN]
def scored(self) -> list[str]:
"""The models a score run takes when none is named: all of them."""
return list(self.models)
def registered(self, name: str) -> str: def registered(self, name: str) -> str:
return f"{self.domain}.{name}" return f"{self.domain}.{name}"
@@ -55,23 +55,25 @@ class Jobs:
"""A new registered version of the model, trained on its cohort's timelines up to """A new registered version of the model, trained on its cohort's timelines up to
`as_of` (default: today), with its metrics and its two generated reports.""" `as_of` (default: today), with its metrics and its two generated reports."""
spec, as_of = self.models[name], as_of or date.today() spec, as_of = self.models[name], as_of or date.today()
if getattr(spec, "reports", False): # trained on its cohort, with its own reports
events = gold.timelines(self.events, spec.cohort, as_of) events = gold.timelines(self.events, spec.cohort, as_of)
if events.empty: if events.empty:
raise EmptyCohort(f"{self.registered(name)}: nobody in {spec.cohort}") raise EmptyCohort(f"{self.registered(name)}: nobody in {spec.cohort}")
fitted, metrics, found = spec.train(events, as_of) fitted, metrics, found = spec.train(events, as_of)
else: if not getattr(spec, "reports", False): # else trained with its own reports
events = gold.timelines(self.events, spec.cohort, as_of) data = found
if events.empty:
raise EmptyCohort(f"{self.registered(name)}: nobody in {spec.cohort}")
fitted, metrics, data = spec.train(events, as_of)
found = { found = {
"technical_validation": self.technical_validation(spec, metrics, data), "technical_validation": self.technical_validation(spec, metrics, data),
"interpretability": self.interpretability(spec, fitted, data), "interpretability": self.interpretability(spec, fitted, data),
} }
if hasattr(fitted, "variance_diagnostics"): # where its intervals can't be had
found["variance_diagnostics"] = fitted.variance_diagnostics(
data["coded"][spec.features]
)
# Bootstraps ran on joblib's worker pool: release it now, or the job's process waits # Bootstraps ran on joblib's worker pool: release it now, or the job's process waits
# for its idle workers to time out (5 minutes) before it can end. # for its idle workers to time out (5 minutes) before it can end.
get_reusable_executor().shutdown(wait=True) get_reusable_executor().shutdown(wait=True)
if self.attrition and (lost := self.attrition(spec, as_of)) is not None:
found["attrition"] = lost
params = {"cohort": spec.cohort, "method": spec.method, "as_of": as_of.isoformat()} params = {"cohort": spec.cohort, "method": spec.method, "as_of": as_of.isoformat()}
model = Predictor(spec, fitted) model = Predictor(spec, fitted)
return registry.register(self.registered(name), model, params, metrics, found) return registry.register(self.registered(name), model, params, metrics, found)
+11 -1
View File
@@ -222,8 +222,17 @@ class IntervalSurvival(BaseEstimator):
# ---------------------------------------------------------------- a model over gold timelines # ---------------------------------------------------------------- a model over gold timelines
TRAIN_FRACTION = 0.7 TRAIN_FRACTION = 0.7
def inputs(members: pd.DataFrame, columns, repeat: int) -> np.ndarray:
"""What each member's estimate read (JSON, unknown as null), once per horizon."""
rows = members[list(columns)].astype(object).where(members[list(columns)].notna(), None)
found = [json.dumps(row, default=str) for row in rows.to_dict("records")]
return np.repeat(np.asarray(found, dtype=object), repeat)
OUTPUT = ["person_id", "index_date", "horizon_years", "probability", "ci_low", "ci_high", OUTPUT = ["person_id", "index_date", "horizon_years", "probability", "ci_low", "ci_high",
"scenarios"] # fmt: skip "scenarios", "input_values"] # fmt: skip
SCENARIO_SEPARATOR = " | " # between the names of a member's clinical scenarios SCENARIO_SEPARATOR = " | " # between the names of a member's clinical scenarios
@@ -349,6 +358,7 @@ class Spec:
"ci_low": np.array([e[0] for e in ends], dtype=float).ravel(), "ci_low": np.array([e[0] for e in ends], dtype=float).ravel(),
"ci_high": np.array([e[1] for e in ends], dtype=float).ravel(), "ci_high": np.array([e[1] for e in ends], dtype=float).ravel(),
"scenarios": np.repeat(np.asarray(scenarios, dtype=object), h), "scenarios": np.repeat(np.asarray(scenarios, dtype=object), h),
"input_values": inputs(members, self.features, h),
})[OUTPUT] # fmt: skip })[OUTPUT] # fmt: skip
+1
View File
@@ -23,6 +23,7 @@ dependencies = [
"edfio>=0.4.18", "edfio>=0.4.18",
"statsmodels>=0.15.0", "statsmodels>=0.15.0",
"pgmpy>=1.1.2", "pgmpy>=1.1.2",
"firthmodels>=0.8.2",
] ]
[project.optional-dependencies] [project.optional-dependencies]
+46
View File
@@ -0,0 +1,46 @@
"""The opt-in development evaluation (models.cacu.development): Firth and its FLIC and FLAC
corrections, and the nested selection that never looks outside its training partition."""
import numpy as np
import pandas as pd
import pytest
from models.cacu.development import METHODS, Firth, candidates, evaluate
def data(n=60, seed=0):
rng = np.random.default_rng(seed)
X = pd.DataFrame({"a": rng.integers(0, 2, n), "b": rng.integers(0, 2, n)}, dtype=float)
X.loc[:5, "a"] = np.nan
X["not_a"], X["sparse"], X["counts"] = 1 - X["a"], np.nan, rng.integers(0, 5, n)
y = (rng.random(n) < 0.15 + 0.5 * X["b"]).astype(int).to_numpy()
return X, y
def test_flic_matches_the_outcome_rate_and_flac_stays_near_firth():
X, y = data()
fitted = {m: Firth(m).fit(X[["b"]], y).predict_proba(X[["b"]])[:, 1] for m in METHODS}
assert fitted["flic"].sum() == pytest.approx(y.sum())
assert np.abs(fitted["flac"] - fitted["firth"]).max() < 0.05
with pytest.raises(ValueError, match="collinear"):
Firth().fit(np.column_stack([X["b"], X["b"]]), y)
def test_candidates_are_known_binary_and_distinguishable():
X, _ = data()
assert candidates(X, 0.7, 5) == ["b", "a"] # not_a is a's complement; the rest aren't 0/1
assert candidates(X, 0.95, 5) == ["b"]
def test_nested_selection_reports_every_method_validation_and_attempt():
X, y = data()
found = evaluate(X, y)
assert found["development_only"] and found["max_subsets"] == 16
for plan in ("cv", "loocv"):
for method in METHODS:
result = found["validation"][plan][method]
assert result["unscored"] == 0 and set(result["metrics"]) >= {"auc", "brier"}
assert all(set(chosen) <= {"a", "b"} for chosen in result["selected"])
assert {a["method"] for a in found["attempts"]} == set(METHODS)
with pytest.raises(ValueError, match="exceeds"):
evaluate(X, y, max_fits=10)
+113
View File
@@ -0,0 +1,113 @@
"""The development encoders (models.cacu.encoders) read only what was available at the index
and never turn an absent value into 0."""
import numpy as np
import pandas as pd
import pytest
from models.cacu.encoders import FINDINGS, encode
INDEX = "2025-06-10"
SAMPLE = "2025-01-10"
def ev(date, kind, code=None, *, person="p1", table="cervical_cytology", source=None,
clinical=None, available=None) -> dict: # fmt: skip
return {"person_id": person, "index_date": INDEX, "date": date, "type": kind,
"value_code": code, "value_num": np.nan, "source_table": table,
"source_id": source or date, "evidence_date": clinical,
"source_available_at": available} # fmt: skip
def encoded(events, forms=None, person="p1") -> pd.Series:
blank = dict.fromkeys(("screening_history", "adequacy", *FINDINGS))
forms = None if forms is None else pd.DataFrame([blank | f for f in forms])
found = encode(pd.DataFrame(events), forms).set_index("person_id")
return found.loc[person].drop("index_date").astype(float)
def test_an_unknown_value_is_missing_never_zero():
assert encoded([ev(INDEX, "cytology", "satisfactory")]).isna().all()
found = encoded([
ev("1980-06-11", "birth", table="person"),
*(ev("2025-01-15", k, c, source=SAMPLE) for k, c in (
("bethesda", "LSIL"), ("hpv", "positive"), ("hpv_16", "negative"))),
ev(INDEX, "cervix_appearance", "lesion"), ev(INDEX, "presenting_symptom", "other?"),
]) # fmt: skip
assert (found["age__35-44"], found["age__45-54"]) == (1, 0)
assert (found["bethesda__LSIL"], found["bethesda__HSIL"]) == (1, 0)
assert (found["cytology_ascus_plus"], found["cytology_hsil_plus"]) == (1, 0)
assert (found["hpv_positive"], found["hpv_16_positive"]) == (1, 0)
assert np.isnan(found["hpv_18_positive"])
assert np.isnan(found["hpv_16_or_18_positive"]) # one negative, the other unreported
assert (found["cervix_appearance__lesion"], found["cervix_appearance__healthy"]) == (1, 0)
assert found.filter(like="presenting_symptom").isna().all() # not one of its codes
assert found.filter(like="prior_").isna().all()
@pytest.mark.parametrize("hpv_16, hpv_18, expected", [
("positive", None, 1.0), ("negative", "negative", 0.0),
("negative", "positive", 1.0)]) # fmt: skip
def test_genotypes_of_one_sample(hpv_16, hpv_18, expected):
events = [ev("2025-01-15", "hpv_16", hpv_16)]
events += [ev("2025-01-15", "hpv_18", hpv_18)] if hpv_18 else []
assert encoded(events)["hpv_16_or_18_positive"] == expected
def test_what_was_not_available_at_the_index_is_not_read():
base = [ev(INDEX, "cytology", "satisfactory")]
later = [
ev("2025-06-20", "bethesda", "HSIL", source=INDEX), # the index sample's report
ev("2025-06-20", "hpv", "positive", source=INDEX),
ev("2025-06-01", "bethesda", "HSIL", available="2025-06-11T08:00:00-06:00"),
ev("2025-06-01", "hpv", "positive", clinical="2025-07-01"),
# the index day's procedures may be the outcome
ev(INDEX, "biopsy", "carcinoma", table="cervical_biopsy"),
ev(INDEX, "colposcopy", table="clinical_note"),
ev(INDEX, "treatment", table="clinical_note"),
ev("2025-08-01", "history", table="clinical_note"),
# standalone evidence with no availability: its onset says nothing of when it was known
ev("2020-01-01", "gynecologic_condition", "hysterectomy",
table="cacu_eligibility_evidence"),
] # fmt: skip
forms = [{"person_id": "p1", "sample_date": INDEX, "report_date": "2025-06-20",
"adequacy": "unsatisfactory", "finding_atrophy": True}] # fmt: skip
pd.testing.assert_series_equal(encoded(base + later, forms), encoded(base))
found = encoded([
ev("2025-06-01", "bethesda", "HSIL", available="2025-06-10T23:00:00-06:00"),
ev("2020-01-01", "gynecologic_condition", "hysterectomy",
table="cacu_eligibility_evidence", available="2024-01-01"),
]) # fmt: skip
assert (found["cytology_hsil_plus"], found["history_hysterectomy"]) == (1, 1)
def test_prior_procedures_and_the_referral_grade():
found = encoded([
ev("2025-01-15", "bethesda", "HSIL", source=SAMPLE),
ev("2025-03-01", "colposcopy", table="clinical_note"),
ev("2025-03-01", "biopsy_order", table="cervical_biopsy"),
ev("2025-03-10", "biopsy", "LSIL", table="cervical_biopsy"),
]) # fmt: skip
assert (found["prior_colposcopy"], found["prior_biopsy_order"]) == (1, 1)
assert (found["prior_biopsy_lsil_plus"], found["prior_biopsy_hsil_plus"]) == (1, 0)
assert found["referral_high_grade"] == 1 and np.isnan(found["prior_treatment"])
def test_the_form_is_read_from_its_latest_report_whole():
forms = [
{"person_id": "p1", "sample_date": "2024-01-10", "report_date": "2024-01-20",
"screening_history": "never", "finding_atrophy": True},
{"person_id": "p1", "sample_date": SAMPLE, "report_date": "2025-01-20",
"adequacy": "satisfactory", "finding_candida": 1},
] # fmt: skip
found = encoded([ev(INDEX, "cytology")], forms)
assert found["screening_history__never"] == 1
assert (found["sample_unsatisfactory"], found["finding_candida"]) == (0, 1)
assert np.isnan(found["finding_atrophy"])
def test_members_apart_and_a_timeline_without_availability_refused():
events = [ev("2025-01-15", "hpv", "positive"), ev(INDEX, "cytology", person="p2")]
assert np.isnan(encoded(events, person="p2")["hpv_positive"])
with pytest.raises(KeyError, match="source_available_at"):
encode(pd.DataFrame([ev(INDEX, "cytology")]).drop(columns="source_available_at"))
+21 -1
View File
@@ -5,6 +5,9 @@ gives the current model's predictions.
Fixed on purpose, so left out of the comparison: Fixed on purpose, so left out of the comparison:
- cin2_logistic's index date: the current estimator reads P(no outcome) as a date - 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. (1970-01-01 for everyone); the rewrite returns the index sample's date.
- A patient without an HPV result at the index is not evaluated; the current models read it
as negative, so a result that is not positive stands in for it here.
- An interval whose covariance can't be estimated is unknown, not the current platform's.
""" """
import json import json
@@ -14,6 +17,8 @@ import numpy as np
import pandas as pd import pandas as pd
import pytest import pytest
from core import cacu
from models.cacu.features import days, prepared
from models.cacu.specs import MODELS from models.cacu.specs import MODELS
REFERENCE = Path(__file__).parents[2] / "tests" / "fixtures" / "reference" / "cacu" REFERENCE = Path(__file__).parents[2] / "tests" / "fixtures" / "reference" / "cacu"
@@ -55,11 +60,23 @@ def timelines(cohort: str) -> pd.DataFrame:
return found return found
def assumed_hpv(events: pd.DataFrame) -> pd.DataFrame:
"""A not-positive HPV result (nor a negative one) at the index of whoever has none."""
near = days(prepared(events)).between(0, cacu.INDEX_SAMPLE_DAYS)
tested = events.loc[(events["type"] == "hpv") & near.to_numpy(), "person_id"]
index = events.groupby("person_id", as_index=False).first()
missing = index[~index["person_id"].isin(tested)]
assumed = missing.assign(date=missing["index_date"], type="hpv", value_code="assumed")
return pd.concat([events, assumed[events.columns]], ignore_index=True)
@pytest.mark.parametrize("name", ["cin2_pim", "cancer_pim", "cin2_pim_post_treatment", @pytest.mark.parametrize("name", ["cin2_pim", "cancer_pim", "cin2_pim_post_treatment",
"cin2_logistic"]) # fmt: skip "cin2_logistic"]) # fmt: skip
def test_predictions_match_the_current_models(name): def test_predictions_match_the_current_models(name):
spec = MODELS[name] spec = MODELS[name]
events = timelines(COHORTS[spec.cohort]) events = timelines(COHORTS[spec.cohort])
if spec.method != "logistic regression":
events = assumed_hpv(events)
args = (REFERENCE_CUTOFF,) if spec.method == "logistic regression" else () args = (REFERENCE_CUTOFF,) if spec.method == "logistic regression" else ()
model, metrics, _ = spec.train(events, *args) model, metrics, _ = spec.train(events, *args)
reference = pd.read_parquet(REFERENCE / "ref" / f"{name}.parquet") reference = pd.read_parquet(REFERENCE / "ref" / f"{name}.parquet")
@@ -78,7 +95,9 @@ def test_predictions_match_the_current_models(name):
for ours, theirs in [("probability", "probabilidad"), ("ci_low", "ic_bajo"), for ours, theirs in [("probability", "probabilidad"), ("ci_low", "ic_bajo"),
("ci_high", "ic_alto")]: # fmt: skip ("ci_high", "ic_alto")]: # fmt: skip
if theirs in both: if theirs in both:
np.testing.assert_allclose(both[ours], both[theirs], rtol=RTOL, atol=0) kept = both[ours].notna() | (ours == "probability") # estimable intervals
np.testing.assert_allclose(both.loc[kept, ours], both.loc[kept, theirs], rtol=RTOL,
atol=0) # fmt: skip
if spec.method != "logistic regression": if spec.method != "logistic regression":
assert (pd.to_datetime(both["index_date"]) == pd.to_datetime(both["fecha_indice"])).all() assert (pd.to_datetime(both["index_date"]) == pd.to_datetime(both["fecha_indice"])).all()
@@ -105,6 +124,7 @@ def test_survival_matches_the_current_model_with_its_index_fixed():
"stack_w_lr_36m", "stack_w_lr_60m"): # fmt: skip "stack_w_lr_36m", "stack_w_lr_60m"): # fmt: skip
assert metrics[name] == pytest.approx(current["metrics"][name], rel=RTOL), name assert metrics[name] == pytest.approx(current["metrics"][name], rel=RTOL), name
found = spec.predict(model, events) found = spec.predict(model, events)
assert all(set(json.loads(v)) == set(spec.features) for v in found["input_values"])
reference = pd.read_parquet(REFERENCE / "ref" / "survival.parquet") reference = pd.read_parquet(REFERENCE / "ref" / "survival.parquet")
both = found.merge(reference, left_on=["person_id", "horizon_years"], both = found.merge(reference, left_on=["person_id", "horizon_years"],
right_on=["pac_id", "horizonte_anios"], validate="1:1") # fmt: skip right_on=["pac_id", "horizonte_anios"], validate="1:1") # fmt: skip
+75
View File
@@ -0,0 +1,75 @@
"""What CaCu training keeps besides the models: who each cohort lost and why; that a patient
without HPV is not evaluated; and that the mixture never makes up a risk or an interval it
can't estimate (unseen levels, improper covariances, frozen parameters)."""
from datetime import date
import numpy as np
import pandas as pd
from core import cacu
from models.cacu import features, reports
from models.cacu.pim import Fit, ISpline, Mixture
BASELINE = ISpline((0.0, 1.0, 2.0), 2)
PARAMS = np.zeros(1 + BASELINE.n_params)
X1, Z0 = np.ones((1, 1)), np.empty((1, 0))
def fit(covariance) -> Fit:
return Fit(1, 0, BASELINE, PARAMS, covariance, 0.0, True)
def test_a_candidate_out_for_two_reasons_is_excluded_once():
rows = pd.DataFrame([
("eligible", "2025-01-01", None), ("two", "2025-01-01", "hysterectomy"),
("two", "2025-01-01", "under_18"), ("waiting", "2025-01-01", "no_index_result"),
("both", "2025-01-01", "no_index_result"), ("both", "2025-01-01", "prior_outcome"),
("after", "2025-07-01", "hysterectomy"),
], columns=["person_id", "index_date", "criterion"]).assign(index_sample_id=None) # fmt: skip
found = reports.attrition("cacu_cohort_surveillance", "surveillance", rows, 10,
date(2025, 6, 30)) # fmt: skip
assert (found["candidates"], found["eligible"], found["excluded"]) == (4, 1, 3)
assert (found["pending"], found["without_candidate"]) == (1, 6)
assert found["by_reason"] == {"hysterectomy": 1, "no_index_result": 2, "prior_outcome": 1,
"under_18": 1} # fmt: skip
assert found["by_stage"] == {"eligibility": 1, "history": 1, "index": 2}
assert found["stage_by_reason"]["no_index_result"] == "index"
def test_without_an_hpv_result_she_is_not_evaluated():
day = pd.Timestamp("2025-01-01")
rows = [(p, day, day, "bethesda", "NILM") for p in ("negative", "positive", "none")]
rows += [("negative", day, day, "hpv", "negative"), ("positive", day, day, "hpv", "positive")]
events = pd.DataFrame(rows, columns=["person_id", "index_date", "date", "type", "value_code"])
found = features.index_results(events, cacu.KPNC)
assert dict(zip(found["person_id"], found["hpv_positive"], strict=True)) == {
"negative": 0.0, "positive": 1.0} # fmt: skip
def test_rows_only_at_unseen_levels_get_no_risk():
X = pd.DataFrame({"cytology": ["NILM", "NILM", "ASC-US", "ASC-US"] * 10})
y = pd.DataFrame({"c": [0, 1] * 20, "l": [1.0, 0.0] * 20, "r": [np.inf, 0.0] * 20})
y.loc[::5, ["c", "l", "r"]] = [-999, 0.5, 2.0]
mixture = Mixture((1, 5), ["cytology"], (), {"cytology": ["NILM", "ASC-US", "High Grade"]})
mixture.fit(X, y)
assert np.isnan(mixture.predict(pd.DataFrame({"cytology": ["High Grade"]}))).all()
def test_an_improper_covariance_gives_no_interval_never_a_zero_width_one():
assert np.isfinite(fit(np.eye(len(PARAMS))).risk_with_variance(X1, Z0, [0, 1])[1]).all()
n = len(PARAMS)
for covariance in (np.full((n, n), np.nan), -np.eye(n), np.zeros((n, n))):
assert np.isnan(fit(covariance).risk_with_variance(X1, Z0, [0, 1])[1]).all()
frozen = np.eye(n)
frozen[1, :] = frozen[:, 1] = np.nan # a frozen parameter moves only some horizons
variance = fit(frozen).risk_with_variance(X1, Z0, [0, 1])[1]
assert np.isfinite(variance[0, 0]) and np.isnan(variance[0, 1])
def test_diagnostics_count_the_rows_without_an_interval():
model = Mixture((0, 1), (), (), {})
model.fits_, model.seen_ = {(): fit(-np.eye(len(PARAMS)))}, {(): {}}
(stratum,) = model.variance_diagnostics(pd.DataFrame(index=range(2)))["strata"]
assert stratum["rows_without_interval"] == 2 and stratum["negative_variances"]
assert stratum["status"] == "not_estimable"