Shared interval survival for CaMa and CaCu, one jobs module for every domain, Dagster train and score by domain

This commit is contained in:
Roberto Treviño
2026-11-25 23:20:52 -06:00
parent d3d9cc3950
commit e2f7e95e83
12 changed files with 661 additions and 65 deletions
+4 -50
View File
@@ -1,54 +1,8 @@
"""Training and scoring of the CaCu models: what the Dagster jobs run."""
from datetime import date
import mlflow.pyfunc
import pandas as pd
"""CaCu's training and scoring jobs (models.jobs) over its models and reports."""
from models.cacu import reports
from models.cacu.specs import MODELS
from persistance import gold, registry
from models.jobs import Jobs
EVENTS = "cacu_events"
def registered(name: str) -> str:
return f"cacu.{name}"
class Predictor(mlflow.pyfunc.PythonModel):
"""A fitted CaCu model as MLflow serves it: patient timelines in (gold `cacu_events`
rows with each patient's index date), one row per patient and horizon out."""
def __init__(self, name: str, fitted):
self.name, self.fitted = name, fitted
def predict(self, context, model_input: pd.DataFrame, params=None) -> pd.DataFrame:
return MODELS[self.name].predict(self.fitted, model_input)
def train(name: str, as_of: date | None = None) -> int:
"""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."""
spec, as_of = MODELS[name], as_of or date.today()
events = gold.timelines(EVENTS, spec.cohort, as_of)
args = (as_of,) if spec.method == "logistic regression" else ()
fitted, metrics, data = spec.train(events, *args)
found = {
"technical_validation": reports.technical_validation(spec, metrics, data),
"interpretability": reports.interpretability(spec, fitted, data),
}
params = {"cohort": spec.cohort, "method": spec.method, "as_of": as_of.isoformat()}
return registry.register(registered(name), Predictor(name, fitted), params, metrics, found)
def score(name: str) -> int | None:
"""The champion's risks for today's members of the model's cohort, saved as its risk
batch; None when the model has no champion yet."""
found = registry.champion(registered(name))
if found is None:
return None
version, model = found
risks = model.predict(gold.timelines(EVENTS, MODELS[name].cohort))
gold.save_scores(registered(name), version, risks)
return version
JOBS = Jobs("cacu", MODELS, reports.technical_validation, reports.interpretability)
train, score = JOBS.train, JOBS.score
+7 -2
View File
@@ -14,6 +14,7 @@ import pandas as pd
from scipy.stats import norm
from sklearn.metrics import brier_score_loss
from models import survival
from models.cacu.pim import Mixture
from models.cacu.specs import Logistic, Pim
@@ -23,7 +24,9 @@ SEED = 20261122
Z = norm.ppf(0.975)
def technical_validation(spec: Pim | Logistic, metrics: dict, data: dict) -> dict:
def technical_validation(spec: Pim | Logistic | survival.Spec, metrics: dict, data: dict) -> dict:
if isinstance(spec, survival.Spec):
return survival.technical_validation(spec, metrics, data)
members = data.get("coded", data.get("labelled"))
return {
"model": spec.name,
@@ -83,7 +86,9 @@ def _mixture_curve(mixture: Mixture, row: pd.DataFrame, years) -> tuple | None:
return point[0], variance[0]
def interpretability(spec: Pim | Logistic, model, data: dict) -> dict:
def interpretability(spec: Pim | Logistic | survival.Spec, model, data: dict) -> dict:
if isinstance(spec, survival.Spec):
return survival.interpretability(spec, model, data)
if isinstance(spec, Logistic):
return _logistic(model, data["test"])
coded = data["coded"]
+23 -1
View File
@@ -15,6 +15,7 @@ from sklearn.preprocessing import OneHotEncoder
from core import cacu
from models.cacu import features as f
from models.cacu.pim import Mixture
from models.survival import Spec, age_group
HORIZONS = (0.0, 1.0, 2.0, 3.0, 4.0, 5.0)
TRAIN_FRACTION = 0.7
@@ -62,7 +63,7 @@ class Pim:
def _history(self) -> dict | None:
return self.history and {**self.history, "cytology": self.cytology}
def train(self, events: pd.DataFrame) -> 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
members it learned from (for the reports)."""
events = f.prepared(events)
@@ -153,6 +154,24 @@ class Logistic:
return _rows(members, p[:, None], (self.years,))
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
group, the KPNC category of her latest cytology result and her latest HPV result."""
found = pd.DataFrame(index=members.index)
found["age_group"] = age_group(events, members, (35, 45, 55))
prior = events[events["date"] <= events["index_date"]]
names = list(cacu.KPNC)
severity = {code: rank for rank, codes in enumerate(cacu.KPNC.values()) for code in codes}
results = prior[(prior["type"] == "bethesda") & prior["value_code"].notna()]
latest = results[results["date"] == results.groupby("person_id")["date"].transform("max")]
ranks = latest["value_code"].map(severity).groupby(latest["person_id"]).max()
found["cytology"] = ranks.map(lambda r: None if pd.isna(r) else names[int(r)])
hpv = prior[(prior["type"] == "hpv") & prior["value_code"].notna()]
hpv = hpv.sort_values(["date", "source_id"])
found["hpv"] = hpv.groupby("person_id")["value_code"].last()
return found.astype(object)
_REFERRAL = {
"feature": "referral_grade", "lookback_days": cacu.REFERRAL_LOOKBACK_DAYS,
"levels": ["low", "high"], "low": ["ASC-US/LSIL"], "low_if_hpv_positive": ["NILM"],
@@ -174,5 +193,8 @@ MODELS = {
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),
Spec("survival", "cacu_cohort_survival", ("age_group", "cytology", "hpv"),
survival_covariates, borders=(0, 12, 36, 60), cap_months=60,
interval_level=0.95),
]
} # fmt: skip
View File
+8
View File
@@ -0,0 +1,8 @@
"""CaMa's training and scoring jobs (models.jobs) over its models and their reports."""
from models import survival
from models.cama.specs import MODELS
from models.jobs import Jobs
JOBS = Jobs("cama", MODELS, survival.technical_validation, survival.interpretability)
train, score = JOBS.train, JOBS.score
+41
View File
@@ -0,0 +1,41 @@
"""The CaMa models. Survival: mortality at 6, 12 and 18 months from the first invasive biopsy
report, by interval survival (models.survival) over the age at the index and that report's
results. Training and scoring read the timelines (gold `cama_events`) of the members of
`gold.cama_cohort_survival`."""
import pandas as pd
from models.survival import Spec, age_group, band
# The index report's results (timeline types), read from a week before to RESULT_DAYS after.
RESULTS = ("histologic_type", "grade", "er", "pr", "her2")
RESULT_DAYS = 30
def covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame:
"""Each member's age group at the index and her index report's results, in bands where
they are numbers (Ki-67 %, tumour size in mm)."""
found = pd.DataFrame(index=members.index)
found["age_group"] = age_group(events, members, (45, 60, 75))
days = (events["date"] - events["index_date"]).dt.days
near = events[days.between(-7, RESULT_DAYS)].sort_values(["date", "source_id"])
for kind in RESULTS:
found[kind] = near[near["type"] == kind].groupby("person_id")["value_code"].first()
for name, kind, cuts in (("ki67_group", "ki67_pct", (14, 20)),
("size_group", "size_mm", (20, 50))): # fmt: skip
value = near[near["type"] == kind].groupby("person_id")["value_num"].first()
found[name] = band(value.reindex(found.index), list(cuts))
return found
MODELS = {
"survival": Spec(
name="survival",
cohort="cama_cohort_survival",
features=("age_group", *RESULTS, "ki67_group", "size_group"),
covariates=covariates,
parents=("histologic_type", "age_group"),
borders=(0, 6, 12, 18),
cap_months=24,
),
}
+23 -12
View File
@@ -1,12 +1,11 @@
"""Dagster code location: every heavy step of the platform is a job defined here."""
import importlib
from datetime import date
import dagster as dg
from models import graph
from models.cacu import jobs as cacu
from models.cacu.specs import MODELS as CACU_MODELS
from persistance import config_log, silver
WRITES = {"writes": "platform"} # dagster.yaml lets one run with this tag at a time (SQLite)
@@ -31,44 +30,56 @@ def ingest():
run_pipeline()
def _jobs(domain: str):
"""The domain's model jobs (`models.<domain>.jobs`: MODELS, train, score)."""
try:
return importlib.import_module(f"models.{domain}.jobs")
except ModuleNotFoundError as e:
raise ValueError(f"{domain} has no models") from e
class Training(dg.Config):
models: list[str] = list(CACU_MODELS)
domain: str
models: list[str] = [] # default: every model of the domain
as_of: str | None = None # the date the data are taken up to (default: today)
@dg.op
def train_models(context: dg.OpExecutionContext, config: Training) -> dict:
"""A new registered version of each model (MLflow), with its reports."""
jobs = _jobs(config.domain)
as_of = date.fromisoformat(config.as_of) if config.as_of else None
found = {}
for name in config.models:
found[name] = cacu.train(name, as_of)
context.log.info(f"{name}: version {found[name]}")
for name in config.models or list(jobs.MODELS):
found[name] = jobs.train(name, as_of)
context.log.info(f"{config.domain}.{name}: version {found[name]}")
return found
@dg.job
def train_cacu():
def train():
train_models()
class Scoring(dg.Config):
models: list[str] = list(CACU_MODELS)
domain: str
models: list[str] = [] # default: every model of the domain
@dg.op
def score_models(context: dg.OpExecutionContext, config: Scoring) -> dict:
"""Each model's champion scores its cohort; then gold's risk tables are rebuilt."""
found = {name: cacu.score(name) for name in config.models}
jobs = _jobs(config.domain)
found = {name: jobs.score(name) for name in config.models or list(jobs.MODELS)}
for name, version in found.items():
context.log.info(f"{name}: " + (f"version {version}" if version else "no champion"))
silver.build(["cacu_risk+"])
silver.build([f"{config.domain}_risk+"])
return found
@dg.job(tags=WRITES)
def score_cacu():
def score():
score_models()
defs = dg.Definitions(jobs=[ingest, train_cacu, score_cacu])
defs = dg.Definitions(jobs=[ingest, train, score])
+67
View File
@@ -0,0 +1,67 @@
"""Training and scoring of a domain's models, what the Dagster jobs run. A domain's module
`models.<domain>.jobs` binds them to its models (`MODELS`) and its reports: `train(name,
as_of)` registers a new version (MLflow) with its two generated reports; `score(name)` writes
the champion's risk batch."""
from collections.abc import Callable
from dataclasses import dataclass
from datetime import date
import mlflow.pyfunc
import pandas as pd
from joblib.externals.loky import get_reusable_executor
from persistance import gold, registry
class Predictor(mlflow.pyfunc.PythonModel):
"""A fitted model as MLflow serves it: patient timelines in (gold `<domain>_events` rows
with each patient's index date), one row per patient and horizon out."""
def __init__(self, spec, fitted):
self.spec, self.fitted = spec, fitted
def predict(self, context, model_input: pd.DataFrame, params=None) -> pd.DataFrame:
return self.spec.predict(self.fitted, model_input)
@dataclass(frozen=True)
class Jobs:
domain: str
models: dict
technical_validation: Callable[..., dict]
interpretability: Callable[..., dict]
@property
def events(self) -> str:
return f"{self.domain}_events"
def registered(self, name: str) -> str:
return f"{self.domain}.{name}"
def train(self, name: str, as_of: date | None = None) -> int:
"""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."""
spec, as_of = self.models[name], as_of or date.today()
fitted, metrics, data = spec.train(gold.timelines(self.events, spec.cohort, as_of), as_of)
found = {
"technical_validation": self.technical_validation(spec, metrics, data),
"interpretability": self.interpretability(spec, fitted, data),
}
# 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.
get_reusable_executor().shutdown(wait=True)
params = {"cohort": spec.cohort, "method": spec.method, "as_of": as_of.isoformat()}
model = Predictor(spec, fitted)
return registry.register(self.registered(name), model, params, metrics, found)
def score(self, name: str) -> int | None:
"""The champion's risks for today's members of the model's cohort, saved as its risk
batch; None when the model has no champion yet."""
found = registry.champion(self.registered(name))
if found is None:
return None
version, model = found
risks = model.predict(gold.timelines(self.events, self.models[name].cohort))
gold.save_scores(self.registered(name), version, risks)
return version
+406
View File
@@ -0,0 +1,406 @@
"""Interval survival, shared by CaMa and CaCu: the probability of surviving each interval of
follow-up, given alive at its start, by a logistic regression and by a Bayesian network with a
tabular CPT, mixed per interval; survival to a horizon is the product of the intervals' up to it.
Each interval's models fit the patients alive at its start (`months >= start`); one censored
inside the interval counts as half a risk. The mixture weight of an interval is the one that
best predicts patients out of sample (`folds` folds), shrunk toward 50/50 when there are few
deaths: lambda = shrink / (shrink + deaths). Covariates are categorical; a missing value is a
category of its own (UNKNOWN).
"""
from dataclasses import dataclass
from itertools import pairwise
import numpy as np
import pandas as pd
from joblib import Parallel, delayed
from scipy.optimize import minimize_scalar
from scipy.special import gammaln
from sklearn.base import BaseEstimator
from sklearn.linear_model import LogisticRegression
UNKNOWN = "NA"
DAYS_PER_MONTH = 30.4375
DAYS_PER_YEAR = 365.25
def outcomes(index: pd.Series, death: pd.Series, end, cap_months: int) -> pd.DataFrame:
"""Whole months from each index to her death or, alive, to `end`, and whether she died;
follow-up is cut at `cap_months` (a later death counts as alive)."""
index, death, end = pd.to_datetime(index), pd.to_datetime(death), pd.Timestamp(end)
died = (death.notna() & (death <= end)).to_numpy()
last = death.where(died, end)
days = (last - index).dt.days.to_numpy()
months = np.floor(days / DAYS_PER_MONTH).astype(int).clip(min=0)
if cap_months:
died = died & (months < cap_months)
months = np.minimum(months, cap_months)
return pd.DataFrame({"months": months, "event": died}, index=index.index)
def band(values: pd.Series, cuts: list) -> pd.Series:
"""Values in the bands the cuts make (`<c1`, `c1-(c2-1)`, ..., `≥cn`); empty stays empty."""
edges = [-np.inf, *cuts, np.inf]
labels = [f"<{cuts[0]}", *[f"{a}-{b - 1}" for a, b in pairwise(cuts)], f"≥{cuts[-1]}"]
return pd.cut(values, edges, right=False, labels=labels).astype(object)
@dataclass(frozen=True)
class Constant:
"""An interval where everyone at risk had the same outcome: the same probability for all."""
p: float
def predict_proba(self, X) -> np.ndarray:
return np.column_stack([np.full(len(X), 1 - self.p), np.full(len(X), self.p)])
def _bdeu(code, y, w, q, ess) -> float:
"""The outcome's weighted BDeu score given parent configurations `code` (of `q`)."""
n = np.bincount(code * 2 + y, weights=w, minlength=q * 2).reshape(q, 2)
aj, ajk = ess / q, ess / q / 2
return float(np.sum(gammaln(aj) - gammaln(aj + n.sum(1))
+ np.sum(gammaln(ajk + n) - gammaln(ajk), axis=1))) # fmt: skip
def _search(X, levels, y, w, ess, max_parents) -> list[int]:
"""Greedy: the covariate that most improves the outcome's BDeu, until none does."""
parents, code, q = [], np.zeros(len(y), int), 1
best = _bdeu(code, y, w, q, ess)
while len(parents) < max_parents:
found = None
for j in range(X.shape[1]):
if j in parents or q * levels[j] > 200_000:
continue
c2 = code * levels[j] + X[:, j]
score = _bdeu(c2, y, w, q * levels[j], ess)
if score > best + 1e-9 and (found is None or score > found[0]):
found = (score, j, c2, q * levels[j])
if found is None:
break
best, j, code, q = found
parents.append(j)
return parents
def _code(X, levels, parents) -> np.ndarray:
code = np.zeros(len(X), int)
for j in parents:
code = code * levels[j] + X[:, j]
return code
class IntervalSurvival(BaseEstimator):
"""Survival by intervals (`borders`, months), LR and HBN stacked per interval.
`fit(X, months, event)` takes the categorical covariates `features`; the HBN's parents
are `parents` (feature names) or, when None, learned per interval by the BDeu score.
"""
def __init__(self, features, borders=(0, 6, 12, 18), parents=None, ess=1000, max_parents=5,
folds=5, shrink=20, seed=42): # fmt: skip
self.features = features
self.borders = borders
self.parents = parents
self.ess = ess
self.max_parents = max_parents
self.folds = folds
self.shrink = shrink
self.seed = seed
# -- coding: dummies for the LR (first level alphabetically as reference), integer codes
# (in order of first appearance) for the HBN; an unseen value takes UNKNOWN's code.
def _frame(self, X: pd.DataFrame) -> pd.DataFrame:
found = X[list(self.features)].astype(object)
return found.where(found.notna(), UNKNOWN).astype(str)
def _encode(self, X: pd.DataFrame) -> tuple[np.ndarray, np.ndarray]:
frame = self._frame(X)
columns = []
for name in self.features:
known = self.categories_[name]
codes = pd.Categorical(frame[name], categories=known).codes
fallback = known.index(UNKNOWN) if UNKNOWN in known else 0
columns.append(np.where(codes < 0, fallback, codes))
dummies = pd.get_dummies(frame).reindex(columns=self.dummies_, fill_value=0)
return dummies.to_numpy(dtype=np.float32), np.column_stack(columns).astype(int)
def _fit_intervals(self, X_dum, X_int, months, event) -> list:
fitted = []
for a, b in pairwise(self.borders):
at_risk = np.where(months >= a)[0]
if len(at_risk) == 0:
fitted.append((Constant(1.0), ([], np.array([1.0]))))
continue
m, e = months[at_risk], event[at_risk]
y = np.where(e & (m < b), 0, 1) # 1 = survives the interval
w = np.where(~e & (m < b), 0.5, 1.0) # censored inside it: half a risk
if y.min() == y.max():
lr = Constant(float(y[0]))
else:
lr = LogisticRegression(C=1e6, max_iter=500)
lr.fit(X_dum[at_risk], y, sample_weight=w)
fitted.append((lr, self._hbn(X_int[at_risk], y, w)))
return fitted
def _hbn(self, X, y, w) -> tuple[list[int], np.ndarray]:
"""The parents and P(survives | parents), smoothed toward the marginal survival."""
if self.parents is None:
parents = _search(X, self.levels_, y, w, self.ess, self.max_parents)
else:
parents = [list(self.features).index(p) for p in self.parents]
q = int(np.prod([self.levels_[j] for j in parents])) if parents else 1
n = np.bincount(_code(X, self.levels_, parents) * 2 + y, weights=w,
minlength=q * 2).reshape(q, 2) # fmt: skip
aj = self.ess / q
marginal = (n[:, 1].sum() + 0.5) / (n.sum() + 1)
return parents, (n[:, 1] + aj * marginal) / (n.sum(1) + aj)
def _predict(self, fitted, X_dum, X_int) -> tuple[np.ndarray, np.ndarray]:
lr = np.column_stack([m.predict_proba(X_dum)[:, 1] for m, _ in fitted])
hbn = np.column_stack([cpt[_code(X_int, self.levels_, p)] for _, (p, cpt) in fitted])
return lr, hbn
def _weights(self, X_dum, X_int, months, event) -> np.ndarray:
"""Per interval, the LR's weight in the mixture, from out-of-fold predictions."""
n = len(months)
fold = np.random.default_rng(self.seed + 7).permutation(n) % self.folds
oof_lr, oof_hbn = np.zeros((n, len(self.borders) - 1)), np.zeros((n, len(self.borders) - 1))
for k in range(self.folds):
test, train = np.where(fold == k)[0], np.where(fold != k)[0]
fitted = self._fit_intervals(X_dum[train], X_int[train], months[train], event[train])
oof_lr[test], oof_hbn[test] = self._predict(fitted, X_dum[test], X_int[test])
weights = []
for j, (a, b) in enumerate(pairwise(self.borders)):
at_risk = np.where(months >= a)[0]
if len(at_risk) == 0:
weights.append(0.5)
continue
m, e = months[at_risk], event[at_risk]
y = np.where(e & (m < b), 0, 1)
w = np.where(~e & (m < b), 0.5, 1.0)
p1 = np.clip(oof_lr[at_risk, j], 1e-9, 1 - 1e-9)
p2 = np.clip(oof_hbn[at_risk, j], 1e-9, 1 - 1e-9)
def loss(x, p1=p1, p2=p2, y=y, w=w):
p = np.clip(x * p1 + (1 - x) * p2, 1e-9, 1 - 1e-9)
return -np.sum(w * (y * np.log(p) + (1 - y) * np.log1p(-p)))
best = float(minimize_scalar(loss, bounds=(0, 1), method="bounded").x)
shrunk = self.shrink / (self.shrink + int((y == 0).sum()))
weights.append((1 - shrunk) * best + shrunk * 0.5)
return np.array(weights)
def fit(self, X: pd.DataFrame, months, event):
frame = self._frame(X)
self.dummies_ = list(pd.get_dummies(frame, drop_first=True).columns)
self.categories_ = {name: list(pd.factorize(frame[name])[1]) for name in self.features}
X_dum, X_int = self._encode(X)
self.levels_ = X_int.max(axis=0) + 1
months, event = np.asarray(months, int), np.asarray(event, bool)
if len(X) >= 2 * self.folds:
self.weights_ = self._weights(X_dum, X_int, months, event)
else:
self.weights_ = np.full(len(self.borders) - 1, 0.5)
self.fitted_ = self._fit_intervals(X_dum, X_int, months, event)
return self
def components(self, X: pd.DataFrame) -> tuple[np.ndarray, np.ndarray]:
"""Each patient's probability of surviving each interval, by the LR and by the HBN."""
return self._predict(self.fitted_, *self._encode(X))
def survival(self, X: pd.DataFrame) -> np.ndarray:
"""Each patient's survival to the end of each interval."""
lr, hbn = self.components(X)
w = self.weights_[None, :]
return np.cumprod(w * lr + (1 - w) * hbn, axis=1)
# ---------------------------------------------------------------- a model over gold timelines
TRAIN_FRACTION = 0.7
OUTPUT = ["person_id", "index_date", "horizon_years", "probability", "ci_low", "ci_high"]
def split(members: pd.DataFrame, train_fraction: float) -> tuple[pd.DataFrame, pd.DataFrame]:
"""Temporal: the earliest index dates train, the latest test; ties in the order of the
hospital's record numbers, so the split (and every fold after it) is the same on every
platform the same data are loaded into."""
ordered = members.sort_values(["index_date", "record_number"], kind="stable")
cut = int(len(ordered) * train_fraction)
return ordered.iloc[:cut].reset_index(drop=True), ordered.iloc[cut:].reset_index(drop=True)
def age_group(events: pd.DataFrame, members: pd.DataFrame, cuts) -> pd.Series:
"""Each member's age at her index (from her birth event), in bands."""
birth = events[events["type"] == "birth"].groupby("person_id")["date"].min()
age = (members["index_date"] - birth.reindex(members.index)).dt.days / DAYS_PER_YEAR
return band(age, list(cuts))
@dataclass(frozen=True)
class Spec:
"""Mortality by each horizon from the index (1 minus the interval survival), for the
members of a gold cohort, from their timelines (`person_id`, `index_date`, `date`, `type`,
`value_code`, `value_num`, `source_table`, `source_id`, `record_number`).
`covariates(events, members)` gives each member's `features` at her index. With
`interval_level`, each combination of the covariates seen in training gets an interval:
percentiles of the mortality of `replicas` refits on bootstrap resamples (seed `seed`)."""
name: str
cohort: str
features: tuple[str, ...]
covariates: object # Callable[[pd.DataFrame, pd.DataFrame], pd.DataFrame]
parents: tuple[str, ...] | None = None
borders: tuple[int, ...] = (0, 6, 12, 18) # months
cap_months: int = 24
interval_level: float | None = None
replicas: int = 100
seed: int = 0
method: str = "interval survival"
@property
def horizons(self) -> tuple[float, ...]:
return tuple(b / 12 for b in self.borders[1:])
def members(self, events: pd.DataFrame) -> pd.DataFrame:
"""One row per member: index date, record number, death date and covariates."""
events = events.assign(date=pd.to_datetime(events["date"]),
index_date=pd.to_datetime(events["index_date"])) # fmt: skip
found = events.groupby("person_id")[["index_date", "record_number"]].first()
death = events[events["type"] == "death"].groupby("person_id")["date"].min()
found["death_date"] = death.reindex(found.index)
found = found.join(self.covariates(events, found)[list(self.features)])
return found.reset_index()
def _model(self) -> IntervalSurvival:
return IntervalSurvival(list(self.features), self.borders, self.parents)
def _combinations(self, X: pd.DataFrame) -> pd.DataFrame:
found = X[list(self.features)].astype(object)
return found.where(found.notna(), UNKNOWN).astype(str).reset_index(drop=True)
def _intervals(self, train: pd.DataFrame) -> dict[tuple, tuple[list, list]]:
combinations = self._combinations(train).drop_duplicates()
frame = combinations.replace(UNKNOWN, None)
rng = np.random.default_rng(self.seed) # resamples drawn in order, refitted in parallel
samples = [rng.integers(0, len(train), len(train)) for _ in range(self.replicas)]
def mortality(rows: np.ndarray) -> np.ndarray:
sample = train.iloc[rows].reset_index(drop=True)
refit = self._model().fit(sample, sample["months"], sample["event"])
return 1.0 - refit.survival(frame)
replicas = Parallel(n_jobs=-1)(delayed(mortality)(rows) for rows in samples)
tail = 50 * (1 - self.interval_level)
low, high = np.nanpercentile(np.stack(replicas), [tail, 100 - tail], axis=0)
rows = combinations.itertuples(index=False)
return {tuple(c): (low[i].tolist(), high[i].tolist()) for i, c in enumerate(rows)}
def train(self, events: pd.DataFrame, as_of) -> tuple:
"""Fitted on the earliest members (followed up to `as_of`), with its metrics and what
the reports draw."""
members = self.members(events)
members = members.join(
outcomes(members["index_date"], members["death_date"], as_of, self.cap_months)
)
train, test = split(members, TRAIN_FRACTION)
model = self._model().fit(train, train["months"], train["event"])
model.intervals_ = self._intervals(train) if self.interval_level else {}
weights = zip(self.borders[1:], model.weights_, strict=True)
metrics = {
"n_train": float(len(train)), "n_test": float(len(test)),
"events_train": float(train["event"].sum()), "events_test": float(test["event"].sum()),
**{f"stack_w_lr_{b}m": float(w) for b, w in weights},
} # fmt: skip
return model, metrics, {"train": train, "test": test}
def predict(self, model: IntervalSurvival, events: pd.DataFrame) -> pd.DataFrame:
"""One row per member and horizon: her mortality by it, and its interval when kept."""
members = self.members(events)
mortality = 1.0 - model.survival(members)
n, h = len(members), len(self.horizons)
empty = ([np.nan] * h, [np.nan] * h)
ends = [model.intervals_.get(tuple(c), empty)
for c in self._combinations(members).itertuples(index=False)] # fmt: skip
return pd.DataFrame({
"person_id": np.repeat(members["person_id"].to_numpy(), h),
"index_date": np.repeat(members["index_date"].dt.date.to_numpy(), h),
"horizon_years": np.tile(np.asarray(self.horizons, dtype=float), n),
"probability": mortality.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(),
})[OUTPUT] # fmt: skip
# ---------------------------------------------------------------- reports (curves)
BOOTSTRAP = 100
BOOTSTRAP_SEED = 42
def technical_validation(spec: Spec, metrics: dict, data: dict) -> dict:
members = pd.concat([data["train"], data["test"]])
return {
"model": spec.name, "method": spec.method, "cohort": spec.cohort,
"split": "temporal: the earliest 70% of index dates train, the latest 30% test",
"members": len(members),
"index_dates": [str(members["index_date"].min().date()),
str(members["index_date"].max().date())],
"horizons_months": list(spec.borders[1:]),
"follow_up_cap_months": spec.cap_months,
"metrics": metrics,
} # fmt: skip
def _curve(fitter, name: str) -> dict:
table = fitter.confidence_interval_survival_function_
return {
"months": fitter.survival_function_.index.tolist(),
"survival": fitter.survival_function_.iloc[:, 0].tolist(),
"low": table.iloc[:, 0].tolist(), "high": table.iloc[:, 1].tolist(), "name": name,
} # fmt: skip
def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict:
"""The training members' observed survival (Kaplan-Meier with its Greenwood band, and a
Weibull fit when anyone died), the model's mean survival at each horizon with a bootstrap
band, and the survival of each combination of the covariates."""
from lifelines import KaplanMeierFitter, WeibullFitter
train = data["train"]
months, event = train["months"].to_numpy(), train["event"].to_numpy()
curves = [_curve(KaplanMeierFitter().fit(months, event), "Kaplan-Meier (IC 95 % Greenwood)")]
if event.any() and (months > 0).all():
curves.append(_curve(WeibullFitter().fit(months, event), "Weibull"))
rng = np.random.default_rng(BOOTSTRAP_SEED)
samples = [rng.integers(0, len(train), len(train)) for _ in range(BOOTSTRAP)]
def mean_survival(rows: np.ndarray) -> np.ndarray:
sample = train.iloc[rows].reset_index(drop=True)
refit = spec._model().fit(sample, sample["months"], sample["event"])
return refit.survival(train).mean(axis=0)
band = np.stack(Parallel(n_jobs=-1)(delayed(mean_survival)(rows) for rows in samples))
combinations = spec._combinations(train).value_counts().reset_index(name="members")
survival = model.survival(combinations.replace(UNKNOWN, None))
return {
"model": spec.name,
"kind": "curves",
"curves": curves,
"predicted": {
"months": list(spec.borders[1:]),
"survival": model.survival(train).mean(axis=0).tolist(),
"low": np.percentile(band, 2.5, axis=0).tolist(),
"high": np.percentile(band, 97.5, axis=0).tolist(),
"name": "LR + HBN combinado (IC 95 % bootstrap)",
},
"weights_lr": model.weights_.tolist(),
"parents": [[spec.features[j] for j in parents] for _, (parents, _) in model.fitted_],
"combinations": [
{**row, "survival": survival[i].tolist()}
for i, row in enumerate(combinations.to_dict("records"))
],
}
+2
View File
@@ -16,6 +16,8 @@ dependencies = [
"pdfplumber>=0.11.11",
"scikit-learn>=1.9.1",
"scipy>=1.18.1",
"joblib>=1.6.0",
"lifelines>=0.30.0",
]
[build-system]
+31
View File
@@ -81,3 +81,34 @@ def test_predictions_match_the_current_models(name):
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()
def test_survival_matches_the_current_model_with_its_index_fixed():
"""Indexed at the first biopsy reported as carcinoma or carcinoma in situ (the current
index read only invasive carcinoma, so it indexed nobody; the reference was captured with
that fixed); out: no birth date, a death by the biopsy."""
spec = MODELS["survival"]
events = timelines("cohorte_total").drop(columns="index_date")
events["date"] = pd.to_datetime(events["date"])
events["record_number"] = "CACU" + events["person_id"].astype(str).str.zfill(4)
cases = events[(events["type"] == "biopsy") & events["value_code"].isin(["CIS", "carcinoma"])]
index = cases.groupby("person_id")["date"].min().rename("index_date")
index = index[(index >= "2018-01-01") & (index < "2027-01-01")]
born = set(events.loc[events["type"] == "birth", "person_id"])
died = events[events["type"] == "death"].groupby("person_id")["date"].min()
index = index[index.index.isin(born) & ~(died.reindex(index.index) <= index)]
events = events.merge(index, left_on="person_id", right_index=True)
model, metrics, _ = spec.train(events, pd.Timestamp(REFERENCE_CUTOFF).date())
current = json.loads((REFERENCE / "models.json").read_text())["survival"]["version"]
for name in ("n_train", "n_test", "events_train", "events_test", "stack_w_lr_12m",
"stack_w_lr_36m", "stack_w_lr_60m"): # fmt: skip
assert metrics[name] == pytest.approx(current["metrics"][name], rel=RTOL), name
found = spec.predict(model, events)
reference = pd.read_parquet(REFERENCE / "ref" / "survival.parquet")
both = found.merge(reference, left_on=["person_id", "horizon_years"],
right_on=["pac_id", "horizonte_anios"], validate="1:1") # fmt: skip
assert len(both) == len(reference) == len(found)
for ours, theirs in [("probability", "probabilidad"), ("ci_low", "ic_bajo"),
("ci_high", "ic_alto")]: # fmt: skip
np.testing.assert_allclose(both[ours], both[theirs], rtol=RTOL, equal_nan=True)
+49
View File
@@ -0,0 +1,49 @@
"""CaMa's models give the current platform's predictions on its own cohort (the reference
fixtures), read in the platform's timeline shape."""
import json
from pathlib import Path
import numpy as np
import pandas as pd
from models.cama.specs import MODELS
REFERENCE = Path(__file__).parents[2] / "tests" / "fixtures" / "reference" / "cama"
TRAINED_ON = "2026-11-24" # the day the reference was trained: its follow-up ends there
TYPES = {"nacimiento": "birth", "defuncion": "death", "biopsia": "biopsy"}
CODES = {"CARCINOMA_INVASOR": "invasive", "CARCINOMA_IN_SITU": "in_situ", "BENIGNO": "benign"}
def _timelines() -> pd.DataFrame:
"""The reference cohort's members (first invasive biopsy report in the window) with their
events, as gold.cama_events gives them."""
old = pd.read_parquet(REFERENCE / "cohorts" / "cama" / "cohorte_total" / "dbt" / "1.parquet")
old = old[old["tipo"].isin(TYPES)]
events = pd.DataFrame({
"person_id": old["pac_id"].astype(str), "date": pd.to_datetime(old["fecha"]),
"type": old["tipo"].map(TYPES), "value_code": old["valor_codigo"].map(CODES),
"value_num": old["valor_numerico"], "source_table": old["fuente_tabla"],
"source_id": old["fuente_id"],
"record_number": "CAMA" + old["pac_id"].astype(str).str.zfill(4),
}) # fmt: skip
invasive = events[(events["type"] == "biopsy") & (events["value_code"] == "invasive")]
index = invasive.groupby("person_id")["date"].min().rename("index_date")
index = index[(index >= "2018-01-01") & (index < "2027-01-01")]
return events.merge(index, left_on="person_id", right_index=True)
def test_survival_matches_the_current_model():
spec = MODELS["survival"]
events = _timelines()
model, metrics, _ = spec.train(events, pd.Timestamp(TRAINED_ON).date())
current = json.loads((REFERENCE / "models.json").read_text())["survival"]["version"]
for name in ("n_train", "n_test", "stack_w_lr_6m", "stack_w_lr_12m", "stack_w_lr_18m"):
assert metrics[name] == current["metrics"][name], name
ours = spec.predict(model, events)
ref = pd.read_parquet(REFERENCE / "ref" / "survival.parquet")
ref = ref.assign(person_id=ref["pac_id"].astype(str), horizon_years=ref["horizonte_anios"])
both = ours.merge(ref, on=["person_id", "horizon_years"], validate="1:1")
assert len(both) == len(ref) == len(ours)
assert (pd.to_datetime(both["index_date"]) == pd.to_datetime(both["fecha_indice"])).all()
np.testing.assert_allclose(both["probability"], both["probabilidad"], rtol=1e-6)