CaMa survival with stage and first-course treatment, clinical scenario report, measured against the SEER-trained original

This commit is contained in:
Roberto Treviño
2026-11-26 19:03:38 -06:00
parent 76eb8cc8af
commit 44cb0dc894
7 changed files with 370 additions and 17 deletions
+1 -1
View File
@@ -14,7 +14,7 @@ import pandas as pd
import statsmodels.api as sm
from joblib import Parallel, delayed
from models.cama.recurrence import curves
from models import curves
from models.cama.recurrence.modeling import ESS, HORIZONS, SEED, CohortFit, logit
RESAMPLES = 200
+1 -1
View File
@@ -17,8 +17,8 @@ from scipy.stats import false_discovery_control
from models.cama.recurrence.calculator import SCENARIOS, masks
from models.cama.recurrence.cohorts import UNKNOWN, at_horizon
from models.cama.recurrence.curves import life_table
from models.cama.recurrence.modeling import CohortFit, variable_of
from models.curves import life_table
ALPHA = 0.05
FREQ_MIN = 0.80
+81 -4
View File
@@ -1,7 +1,11 @@
"""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.
interval survival (models.survival) over the age at the index, that report's results
(stage among them) and the first course of treatment. The first course follows SEER's
convention: what the patient received in the TREATMENT_DAYS after the index, taken as
known at it. A patient who dies before her treatment counts as untreated (immortal-time
bias), which the technical report states.
Training and scoring read the timelines (gold `cama_events`) of `gold.cama_cohort_survival`.
- Recurrence: risk of recurrence at 12, 36 and 60 months, trained on two public reference
cohorts (METABRIC and SCAN-B, models.cama.recurrence) that the platform loads with the
@@ -12,12 +16,50 @@ from dataclasses import dataclass, field
import pandas as pd
from models.survival import Spec, age_group, band
from models.survival import DAYS_PER_YEAR, Spec, age_group, band
from persistance import nodes
# 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
TREATMENT_DAYS = 365
# Stage groups (AJCC): 0, I, II, III, IV, as the clinical scenarios name them.
STAGE_GROUP = {"0": "0", "I": "I", "IA": "I", "IB": "I", "II": "II", "IIA": "II", "IIB": "II",
"III": "III", "IIIA": "III", "IIIB": "III", "IIIC": "III", "IV": "IV"} # fmt: skip
SURGERY = ("breast_conserving_surgery", "mastectomy") # the most extensive one counts
# The clinical scenarios the survival report draws (as the SEER-trained original named them).
STAGE_0_II, STAGE_III_IV = ("stage", "in", ("0", "I", "II")), ("stage", "in", ("III", "IV"))
HER2_POS, HER2_NEG = ("her2", "==", "positive"), ("her2", "==", "negative")
TRIPLE_NEG = (("er", "==", "negative"), ("pr", "==", "negative"), HER2_NEG)
CONSERVING = ("surgery", "==", "breast_conserving_surgery")
def _younger(years):
return ("age", "<", years)
def _older(years):
return ("age", ">=", years)
SCENARIOS = {
"HER2+ · ≥60 años · estadio III–IV (Alto)": (HER2_POS, _older(60), STAGE_III_IV),
"HER2+ · <60 años · estadio 0–II (Bajo)": (HER2_POS, _younger(60), STAGE_0_II),
"Estadio IV": (("stage", "in", ("IV",)),),
"Estadio I": (("stage", "in", ("I",)),),
"≥ 75 años": (_older(75),),
"< 45 años": (_younger(45),),
"Jóvenes (<45) · HER2− · estadio 0–II · cirugía conservadora": (
_younger(45), HER2_NEG, STAGE_0_II, CONSERVING),
"HER2− · estadio 0–II · cirugía conservadora": (HER2_NEG, STAGE_0_II, CONSERVING),
"HER2+ · estadio 0–II · cirugía conservadora": (HER2_POS, STAGE_0_II, CONSERVING),
"Jóvenes (<45) · estadio 0–II": (_younger(45), STAGE_0_II),
"Jóvenes (<45) · HER2−": (_younger(45), HER2_NEG),
"Triple negativo (HR−/HER2−) · estadio 0–II": (*TRIPLE_NEG, STAGE_0_II),
"≥ 65 años · HER2− · estadio 0–II · cirugía conservadora": (
_older(65), HER2_NEG, STAGE_0_II, CONSERVING),
} # fmt: skip
def covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame:
@@ -25,6 +67,8 @@ def covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame:
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))
birth = events[events["type"] == "birth"].groupby("person_id")["date"].min()
found["age"] = (members["index_date"] - birth.reindex(members.index)).dt.days / DAYS_PER_YEAR
days = (events["date"] - events["index_date"]).dt.days
near = events[days.between(-7, RESULT_DAYS)].sort_values(["date", "source_id"])
for kind in RESULTS:
@@ -33,6 +77,14 @@ def covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame:
("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))
stage = near[near["type"] == "stage"].groupby("person_id")["value_code"].first()
found["stage"] = stage.reindex(found.index).map(STAGE_GROUP)
course = events[(events["type"] == "treatment") & days.between(0, TREATMENT_DAYS)]
given = course.groupby("person_id")["value_code"].agg(set).reindex(found.index)
given = given.apply(lambda g: g if isinstance(g, set) else set())
found["surgery"] = given.apply(lambda g: next((s for s in reversed(SURGERY) if s in g), "none"))
for name in ("chemotherapy", "radiotherapy"):
found[name] = given.apply(lambda g, n=name: "yes" if n in g else "no")
return found
@@ -70,11 +122,36 @@ MODELS = {
"survival": Spec(
name="survival",
cohort="cama_cohort_survival",
features=("age_group", *RESULTS, "ki67_group", "size_group"),
features=(
"age_group",
*RESULTS,
"ki67_group",
"size_group",
"stage",
"surgery",
"chemotherapy",
"radiotherapy",
),
covariates=covariates,
parents=("histologic_type", "age_group"),
# As the SEER-trained original: stage, histologic type and the first course, and age.
parents=(
"stage",
"histologic_type",
"surgery",
"chemotherapy",
"radiotherapy",
"age_group",
),
borders=(0, 6, 12, 18),
cap_months=24,
scenarios=SCENARIOS,
scenario_columns=("age",),
notes=(
f"Tratamiento: el primer curso (convención de SEER), lo recibido en los "
f"{TREATMENT_DAYS} días tras el índice, tomado como conocido en él. Quien muere "
"antes de su tratamiento cuenta como no tratada (sesgo de tiempo inmortal): el "
"efecto protector del tratamiento aparece mayor de lo que es.",
),
),
"recurrence": ReferenceRecurrence("recurrence"),
}
@@ -1,7 +1,7 @@
"""Recurrence-free survival curves of a group, from whole months of follow-up: Kaplan-Meier
with its Greenwood band (log-log scale), and a classic and a fractional (Kilbas-Saigo)
Weibull, both fitted by maximum likelihood on the monthly counts of recurrences and
censorings (a recurrence in month m falls between S(m) and S(m+1); a censoring there
"""Survival curves of a group (free of death, or of recurrence), from whole months of
follow-up: Kaplan-Meier with its Greenwood band (log-log scale), and a classic and a
fractional (Kilbas-Saigo) Weibull, both fitted by maximum likelihood on the monthly counts of
events and censorings (an event in month m falls between S(m) and S(m+1); a censoring there
survives to m + 1/2). Fits start from several points and run each to the optimizer's
convergence; one that doesn't converge is an error, not a curve."""
+99 -6
View File
@@ -9,7 +9,7 @@ deaths: lambda = shrink / (shrink + deaths). Covariates are categorical; a missi
category of its own (UNKNOWN).
"""
from dataclasses import dataclass
from dataclasses import dataclass, field
from itertools import pairwise
import numpy as np
@@ -260,6 +260,11 @@ class Spec:
replicas: int = 100
seed: int = 0
method: str = "interval survival"
notes: tuple[str, ...] = () # what the technical report states about the method
# Clinical scenarios the report draws: name -> conditions (column, "<" | ">=" | "==" |
# "in", value) on the members' covariates and `scenario_columns` (kept for them only).
scenarios: dict[str, tuple[tuple[str, str, object], ...]] = field(default_factory=dict)
scenario_columns: tuple[str, ...] = ()
@property
def horizons(self) -> tuple[float, ...]:
@@ -272,7 +277,8 @@ class Spec:
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)])
kept = [*self.features, *self.scenario_columns]
found = found.join(self.covariates(events, found)[kept])
return found.reset_index()
def _model(self) -> IntervalSurvival:
@@ -351,6 +357,7 @@ def technical_validation(spec: Spec, metrics: dict, data: dict) -> dict:
str(members["index_date"].max().date())],
"horizons_months": list(spec.borders[1:]),
"follow_up_cap_months": spec.cap_months,
"notes": list(spec.notes),
"metrics": metrics,
} # fmt: skip
@@ -364,10 +371,61 @@ def _curve(fitter, name: str) -> dict:
} # fmt: skip
MIN_SCENARIO_EVENTS = 5 # fewer deaths than this: no curves for the scenario
GRID_POINTS = 200
def scenario_masks(members: pd.DataFrame, scenarios: dict) -> dict[str, np.ndarray]:
"""Which members each scenario takes: all of its conditions hold (an unknown value
holds none)."""
found = {}
for name, conditions in scenarios.items():
mask = np.ones(len(members), bool)
for column, op, value in conditions:
v = members[column]
if op in ("<", ">="):
number = pd.to_numeric(v, errors="coerce")
held = number < value if op == "<" else number >= value
elif op == "in":
held = v.isin(list(value))
elif op == "==":
held = v == value
else:
raise ValueError(f"unknown condition {op!r} in scenario {name!r}")
mask &= held.fillna(False).to_numpy(bool)
found[name] = mask
return found
def _scenario_curves(months: np.ndarray, event: np.ndarray, cap_months: int) -> dict:
from models import curves
d, c, _ = curves.life_table(months, event)
k, lam = curves.fit_weibull(d, c)
fractional = curves.fit_fractional(d, c, k, lam)
grid = np.linspace(0, cap_months, GRID_POINTS)
observed = int(months.max())
km = curves.kaplan_meier(months, event, observed)
return {
"observado_hasta": observed,
"km": {"months": list(range(observed + 1)),
**{n: v.tolist() for n, v in zip(("S", "low", "high"), km, strict=True)}},
"weibull": {"t": grid.tolist(), "S": curves.weibull(grid, k, lam).tolist(),
"k": k, "lambda": lam},
"weibull_fractional": {"t": grid.tolist(),
"S": curves.fractional(grid, k, *fractional).tolist(),
"alpha": fractional[0], "beta": fractional[1],
"lambda": fractional[2]},
} # 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."""
band, the survival of each combination of the covariates, and each clinical scenario's
curves (Kaplan-Meier, Weibull, fractional Weibull) with the model's mean survival over its
members and its band. The model's mixture is its own (the original refitted it per
scenario): the points show the model as it scores."""
from lifelines import KaplanMeierFitter, WeibullFitter
train = data["train"]
@@ -378,12 +436,44 @@ def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict:
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:
# Scenarios: over every member (training first), the observed curves of those with
# enough deaths, and the model's mean survival over each, with the same bootstrap band.
members = pd.concat([train, data.get("test", train.iloc[:0])]).reset_index(drop=True)
masks = scenario_masks(members, spec.scenarios)
def mean_survival(rows: np.ndarray) -> tuple[np.ndarray, dict]:
sample = train.iloc[rows].reset_index(drop=True)
refit = spec._model().fit(sample, sample["months"], sample["event"])
return refit.survival(train).mean(axis=0)
found = refit.survival(members)
by = {n: found[m].mean(axis=0) for n, m in masks.items() if m.any()}
return found[: len(train)].mean(axis=0), by
band = np.stack(Parallel(n_jobs=-1)(delayed(mean_survival)(rows) for rows in samples))
all_months, all_event = members["months"].to_numpy(), members["event"].to_numpy(bool)
drawn = {n: m for n, m in masks.items() if all_event[m].sum() >= MIN_SCENARIO_EVENTS}
jobs = [delayed(_scenario_curves)(all_months[m], all_event[m], spec.cap_months)
for m in drawn.values()] # fmt: skip
jobs += [delayed(mean_survival)(rows) for rows in samples]
done = Parallel(n_jobs=-1)(jobs)
drawn_curves, replicas = done[: len(drawn)], done[len(drawn) :]
band = np.stack([r[0] for r in replicas])
point = model.survival(members)
scenarios = []
for (name, mask), found in zip(drawn.items(), drawn_curves, strict=True):
spread = np.array([r[1][name] for r in replicas])
low, high = np.nanpercentile(spread, [2.5, 97.5], axis=0)
scenarios.append({
"escenario": name,
"condiciones": [list(c) for c in spec.scenarios[name]],
"n": int(mask.sum()), "fallecidos": int(all_event[mask].sum()),
"horizons_months": list(spec.borders[1:]), "months_max": spec.cap_months,
**found,
"points": {"COMB": {"S": point[mask].mean(axis=0).tolist(),
"low": np.clip(low, 0, 1).tolist(),
"high": np.clip(high, 0, 1).tolist()}},
"bootstrap_replicas": len(replicas),
}) # fmt: skip
skipped = [{"escenario": n, "n": int(m.sum()), "fallecidos": int(all_event[m].sum())}
for n, m in masks.items() if n not in drawn] # fmt: skip
combinations = spec._combinations(train).value_counts().reset_index(name="members")
survival = model.survival(combinations.replace(UNKNOWN, None))
return {
@@ -403,4 +493,7 @@ def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict:
{**row, "survival": survival[i].tolist()}
for i, row in enumerate(combinations.to_dict("records"))
],
"escenarios": scenarios,
"escenarios_sin_curvas": skipped, # fewer than MIN_SCENARIO_EVENTS deaths
"min_fallecidos_escenario": MIN_SCENARIO_EVENTS,
}