CaMa survival with stage and first-course treatment, clinical scenario report, measured against the SEER-trained original
This commit is contained in:
@@ -14,7 +14,7 @@ import pandas as pd
|
|||||||
import statsmodels.api as sm
|
import statsmodels.api as sm
|
||||||
from joblib import Parallel, delayed
|
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
|
from models.cama.recurrence.modeling import ESS, HORIZONS, SEED, CohortFit, logit
|
||||||
|
|
||||||
RESAMPLES = 200
|
RESAMPLES = 200
|
||||||
|
|||||||
@@ -17,8 +17,8 @@ from scipy.stats import false_discovery_control
|
|||||||
|
|
||||||
from models.cama.recurrence.calculator import SCENARIOS, masks
|
from models.cama.recurrence.calculator import SCENARIOS, masks
|
||||||
from models.cama.recurrence.cohorts import UNKNOWN, at_horizon
|
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.cama.recurrence.modeling import CohortFit, variable_of
|
||||||
|
from models.curves import life_table
|
||||||
|
|
||||||
ALPHA = 0.05
|
ALPHA = 0.05
|
||||||
FREQ_MIN = 0.80
|
FREQ_MIN = 0.80
|
||||||
|
|||||||
+81
-4
@@ -1,7 +1,11 @@
|
|||||||
"""The CaMa models.
|
"""The CaMa models.
|
||||||
|
|
||||||
- Survival: mortality at 6, 12 and 18 months from the first invasive biopsy report, by
|
- 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`.
|
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
|
- 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
|
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
|
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
|
from persistance import nodes
|
||||||
|
|
||||||
# The index report's results (timeline types), read from a week before to RESULT_DAYS after.
|
# The index report's results (timeline types), read from a week before to RESULT_DAYS after.
|
||||||
RESULTS = ("histologic_type", "grade", "er", "pr", "her2")
|
RESULTS = ("histologic_type", "grade", "er", "pr", "her2")
|
||||||
RESULT_DAYS = 30
|
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:
|
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)."""
|
they are numbers (Ki-67 %, tumour size in mm)."""
|
||||||
found = pd.DataFrame(index=members.index)
|
found = pd.DataFrame(index=members.index)
|
||||||
found["age_group"] = age_group(events, members, (45, 60, 75))
|
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
|
days = (events["date"] - events["index_date"]).dt.days
|
||||||
near = events[days.between(-7, RESULT_DAYS)].sort_values(["date", "source_id"])
|
near = events[days.between(-7, RESULT_DAYS)].sort_values(["date", "source_id"])
|
||||||
for kind in RESULTS:
|
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
|
("size_group", "size_mm", (20, 50))): # fmt: skip
|
||||||
value = near[near["type"] == kind].groupby("person_id")["value_num"].first()
|
value = near[near["type"] == kind].groupby("person_id")["value_num"].first()
|
||||||
found[name] = band(value.reindex(found.index), list(cuts))
|
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
|
return found
|
||||||
|
|
||||||
|
|
||||||
@@ -70,11 +122,36 @@ MODELS = {
|
|||||||
"survival": Spec(
|
"survival": Spec(
|
||||||
name="survival",
|
name="survival",
|
||||||
cohort="cama_cohort_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,
|
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),
|
borders=(0, 6, 12, 18),
|
||||||
cap_months=24,
|
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"),
|
"recurrence": ReferenceRecurrence("recurrence"),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
"""Recurrence-free survival curves of a group, from whole months of follow-up: Kaplan-Meier
|
"""Survival curves of a group (free of death, or of recurrence), from whole months of
|
||||||
with its Greenwood band (log-log scale), and a classic and a fractional (Kilbas-Saigo)
|
follow-up: Kaplan-Meier with its Greenwood band (log-log scale), and a classic and a
|
||||||
Weibull, both fitted by maximum likelihood on the monthly counts of recurrences and
|
fractional (Kilbas-Saigo) Weibull, both fitted by maximum likelihood on the monthly counts of
|
||||||
censorings (a recurrence in month m falls between S(m) and S(m+1); a censoring there
|
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
|
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."""
|
convergence; one that doesn't converge is an error, not a curve."""
|
||||||
|
|
||||||
+99
-6
@@ -9,7 +9,7 @@ deaths: lambda = shrink / (shrink + deaths). Covariates are categorical; a missi
|
|||||||
category of its own (UNKNOWN).
|
category of its own (UNKNOWN).
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass, field
|
||||||
from itertools import pairwise
|
from itertools import pairwise
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
@@ -260,6 +260,11 @@ class Spec:
|
|||||||
replicas: int = 100
|
replicas: int = 100
|
||||||
seed: int = 0
|
seed: int = 0
|
||||||
method: str = "interval survival"
|
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
|
@property
|
||||||
def horizons(self) -> tuple[float, ...]:
|
def horizons(self) -> tuple[float, ...]:
|
||||||
@@ -272,7 +277,8 @@ class Spec:
|
|||||||
found = events.groupby("person_id")[["index_date", "record_number"]].first()
|
found = events.groupby("person_id")[["index_date", "record_number"]].first()
|
||||||
death = events[events["type"] == "death"].groupby("person_id")["date"].min()
|
death = events[events["type"] == "death"].groupby("person_id")["date"].min()
|
||||||
found["death_date"] = death.reindex(found.index)
|
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()
|
return found.reset_index()
|
||||||
|
|
||||||
def _model(self) -> IntervalSurvival:
|
def _model(self) -> IntervalSurvival:
|
||||||
@@ -351,6 +357,7 @@ def technical_validation(spec: Spec, metrics: dict, data: dict) -> dict:
|
|||||||
str(members["index_date"].max().date())],
|
str(members["index_date"].max().date())],
|
||||||
"horizons_months": list(spec.borders[1:]),
|
"horizons_months": list(spec.borders[1:]),
|
||||||
"follow_up_cap_months": spec.cap_months,
|
"follow_up_cap_months": spec.cap_months,
|
||||||
|
"notes": list(spec.notes),
|
||||||
"metrics": metrics,
|
"metrics": metrics,
|
||||||
} # fmt: skip
|
} # fmt: skip
|
||||||
|
|
||||||
@@ -364,10 +371,61 @@ def _curve(fitter, name: str) -> dict:
|
|||||||
} # fmt: skip
|
} # 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:
|
def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict:
|
||||||
"""The training members' observed survival (Kaplan-Meier with its Greenwood band, and a
|
"""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
|
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
|
from lifelines import KaplanMeierFitter, WeibullFitter
|
||||||
|
|
||||||
train = data["train"]
|
train = data["train"]
|
||||||
@@ -378,12 +436,44 @@ def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict:
|
|||||||
rng = np.random.default_rng(BOOTSTRAP_SEED)
|
rng = np.random.default_rng(BOOTSTRAP_SEED)
|
||||||
samples = [rng.integers(0, len(train), len(train)) for _ in range(BOOTSTRAP)]
|
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)
|
sample = train.iloc[rows].reset_index(drop=True)
|
||||||
refit = spec._model().fit(sample, sample["months"], sample["event"])
|
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")
|
combinations = spec._combinations(train).value_counts().reset_index(name="members")
|
||||||
survival = model.survival(combinations.replace(UNKNOWN, None))
|
survival = model.survival(combinations.replace(UNKNOWN, None))
|
||||||
return {
|
return {
|
||||||
@@ -403,4 +493,7 @@ def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict:
|
|||||||
{**row, "survival": survival[i].tolist()}
|
{**row, "survival": survival[i].tolist()}
|
||||||
for i, row in enumerate(combinations.to_dict("records"))
|
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,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,8 +29,9 @@ from joblib.externals.loky import get_reusable_executor
|
|||||||
from scipy.special import gammaln
|
from scipy.special import gammaln
|
||||||
|
|
||||||
from conftest import _platform
|
from conftest import _platform
|
||||||
|
from models import curves
|
||||||
from models.cama import recurrence
|
from models.cama import recurrence
|
||||||
from models.cama.recurrence import calculator, cohorts, curves, factors, modeling, reports
|
from models.cama.recurrence import calculator, cohorts, factors, modeling, reports
|
||||||
|
|
||||||
RAW = Path(os.environ.get("CAMA_REFERENCE_DIR", Path.home() / "camaSupervivencia"))
|
RAW = Path(os.environ.get("CAMA_REFERENCE_DIR", Path.home() / "camaSupervivencia"))
|
||||||
V1 = Path(__file__).parents[2] / "tests" / "fixtures" / "reference" / "cama" / "recurrence" / "v1"
|
V1 = Path(__file__).parents[2] / "tests" / "fixtures" / "reference" / "cama" / "recurrence" / "v1"
|
||||||
|
|||||||
@@ -0,0 +1,182 @@
|
|||||||
|
"""CaMa survival measured against the SEER-trained original (Luis's pipeline,
|
||||||
|
`05_curvas_supervivencia.py`): the same model, trained on the same SEER patients, gives each
|
||||||
|
clinical scenario the same patients and deaths, the same observed curves (Kaplan-Meier,
|
||||||
|
Weibull, fractional Weibull), and model points close to the original's.
|
||||||
|
|
||||||
|
SEER is real registry data under NCI's use agreement: it is read from outside git
|
||||||
|
(SEER_FILE) and nothing of it is kept. The original's outputs are read from where it ran
|
||||||
|
(LUIS_RUN: its `subgrupos_*.csv`). Both missing: the test is skipped.
|
||||||
|
|
||||||
|
Each SEER case becomes a timeline: a first invasive biopsy at diagnosis with its report's
|
||||||
|
results, its first course of treatment a month later, and its death or last contact placed so
|
||||||
|
the platform's whole months of follow-up are SEER's survival months.
|
||||||
|
|
||||||
|
The model points are not the original's: it trains on every case, the platform on the
|
||||||
|
earliest 70% by index date (and validates on the rest), and SEER's latest diagnoses carry few
|
||||||
|
recorded deaths yet. They are checked against the survival of the cases the model learned
|
||||||
|
from; their distance to the original's is printed. Slow (a quarter of an hour): SEER_SLOW=1."""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pandas as pd
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from models import curves, survival
|
||||||
|
from models.cama.specs import MODELS
|
||||||
|
from models.survival import DAYS_PER_MONTH, DAYS_PER_YEAR, TRAIN_FRACTION, scenario_masks
|
||||||
|
|
||||||
|
SEER = Path(
|
||||||
|
os.environ.get("SEER_FILE", Path.home() / "camaSupervivencia" / "dataframe_recodificado.csv")
|
||||||
|
)
|
||||||
|
RUN = Path(os.environ.get("LUIS_RUN", Path.home() / "isssteleon-data" / "luis-run"))
|
||||||
|
AS_OF = pd.Timestamp("2023-12-31") # SEER's follow-up cutoff: survivors are followed to it
|
||||||
|
|
||||||
|
pytestmark = [
|
||||||
|
pytest.mark.skipif(
|
||||||
|
not (SEER.exists() and (RUN / "subgrupos_KM_Weibull_fraccional.csv").exists()),
|
||||||
|
reason="SEER and the original's outputs are outside git",
|
||||||
|
),
|
||||||
|
pytest.mark.skipif(not os.environ.get("SEER_SLOW"), reason="slow: SEER_SLOW=1"),
|
||||||
|
]
|
||||||
|
CURVE = 1e-3 # the fits' agreement (maximum distance to Kaplan-Meier, shape k relative)
|
||||||
|
CALIBRATION = 0.01 # the model's mean survival against its training cases' Kaplan-Meier
|
||||||
|
|
||||||
|
STAGE = {"0 (in situ)": "0", "I": "I", "II": "II", "III": "III", "IV": "IV"}
|
||||||
|
GRADE = {"G1": "1", "G2": "2", "G3": "3"}
|
||||||
|
RECEPTOR = {"Positivo": "positive", "Negativo": "negative"}
|
||||||
|
SURGERY = {"Conservadora": "breast_conserving_surgery", "Mastectomía": "mastectomy"}
|
||||||
|
|
||||||
|
|
||||||
|
def _her2(subtype: str) -> str | None:
|
||||||
|
return "positive" if "HER2+" in subtype else "negative" if "HER2-" in subtype else None
|
||||||
|
|
||||||
|
|
||||||
|
def _age(recode: str) -> float:
|
||||||
|
"""The age band's lower bound, as the original reads it ("65-69 years": 65)."""
|
||||||
|
found = re.search(r"\d+", str(recode))
|
||||||
|
return float(found.group()) if found else np.nan
|
||||||
|
|
||||||
|
|
||||||
|
def seer_events(frame: pd.DataFrame) -> pd.DataFrame:
|
||||||
|
"""SEER cases as CaMa timelines (gold `cama_events` shape, indexed at diagnosis)."""
|
||||||
|
months = pd.to_numeric(frame["Survival_months"], errors="coerce")
|
||||||
|
frame, months = frame[months.notna()], months[months.notna()]
|
||||||
|
dead = frame["Vital_status_recode_study_cutoff_used"].str.lower().str.contains("dead")
|
||||||
|
person = frame["Patient_ID"].to_numpy()
|
||||||
|
# Whole months from the index are SEER's. A survivor's index is months + 1/2 before the
|
||||||
|
# cutoff; a death's is in its year of diagnosis (spread over the year by its id, never so
|
||||||
|
# late that the death would pass the cutoff), and she dies months + 1/4 after it. So the
|
||||||
|
# index dates keep SEER's calendar, which the model's split by index date reads.
|
||||||
|
latest = AS_OF - pd.to_timedelta((months + 0.5) * DAYS_PER_MONTH, "D")
|
||||||
|
year = pd.to_datetime(frame["Year_of_diagnosis"] + "-01-01")
|
||||||
|
spread = pd.to_timedelta(frame["Patient_ID"].astype(int) % 365, "D")
|
||||||
|
index = latest.where(~dead, (year + spread).where(year + spread < latest, latest))
|
||||||
|
death = index + pd.to_timedelta((months + 0.25) * DAYS_PER_MONTH, "D")
|
||||||
|
birth = index - pd.to_timedelta((frame["Age_recode_with_1_year_olds_and_90"].map(_age) + 0.5)
|
||||||
|
* DAYS_PER_YEAR, "D") # fmt: skip
|
||||||
|
base = pd.DataFrame({"person_id": person, "index_date": index.to_numpy(),
|
||||||
|
"record_number": person}) # fmt: skip
|
||||||
|
rows = [base.assign(date=birth.to_numpy(), type="birth", value_code=None)]
|
||||||
|
rows.append(base[dead.to_numpy()].assign(date=death[dead].to_numpy(), type="death",
|
||||||
|
value_code=None)) # fmt: skip
|
||||||
|
hr_negative = frame["Subtipo_molecular_cat"].str.startswith("HR-")
|
||||||
|
hr_positive = frame["Subtipo_molecular_cat"].str.startswith("HR+")
|
||||||
|
er = frame["Receptor_estrogeno_cat"].map(RECEPTOR)
|
||||||
|
pr = frame["Receptor_progesterona_cat"].map(RECEPTOR)
|
||||||
|
both_negative = er.eq("negative") & pr.eq("negative")
|
||||||
|
results = {
|
||||||
|
"biopsy": pd.Series("invasive", index=frame.index),
|
||||||
|
"stage": frame["Estadio_cat"].map(STAGE),
|
||||||
|
"grade": frame["Grado_histologico_cat"].map(GRADE),
|
||||||
|
# Hormone receptors as SEER's subtype states them, which the original's scenarios read:
|
||||||
|
# SEER's own columns disagree in a few cases (HR+ with both recodes negative, likely
|
||||||
|
# borderline results): HR- makes both negative; HR+ with both negative leaves ER unknown.
|
||||||
|
"er": er.mask(hr_negative, "negative").mask(hr_positive & both_negative, None),
|
||||||
|
"pr": pr.mask(hr_negative, "negative"),
|
||||||
|
"her2": frame["Subtipo_molecular_cat"].map(_her2),
|
||||||
|
"histologic_type": frame["Histologic_Type_ICD_O_3"].astype(str) + "/3",
|
||||||
|
}
|
||||||
|
for kind, values in results.items():
|
||||||
|
rows.append(base.assign(date=index.to_numpy(), type=kind, value_code=values.to_numpy()))
|
||||||
|
size = pd.to_numeric(frame["Tumor_Size_Over_Time_Recode_1988"], errors="coerce")
|
||||||
|
rows.append(base.assign(date=index.to_numpy(), type="size_mm", value_code=None,
|
||||||
|
value_num=size.where(size < 990).to_numpy())) # fmt: skip
|
||||||
|
course = {
|
||||||
|
"surgery": frame["Tratamiento_quirurgico_cat"].map(SURGERY),
|
||||||
|
"chemotherapy": frame["Quimioterapia_cat"].map({"Sí": "chemotherapy"}),
|
||||||
|
"radiotherapy": frame["Radioterapia_cat"].map({"Sí": "radiotherapy"}),
|
||||||
|
}
|
||||||
|
month_later = index + pd.Timedelta(days=30)
|
||||||
|
for values in course.values():
|
||||||
|
rows.append(base.assign(date=month_later.to_numpy(), type="treatment",
|
||||||
|
value_code=values.to_numpy())) # fmt: skip
|
||||||
|
events = pd.concat(rows, ignore_index=True)
|
||||||
|
events = events[events["type"].isin(["birth", "death"]) | events["value_code"].notna()
|
||||||
|
| events.get("value_num", pd.Series(np.nan)).notna()] # fmt: skip
|
||||||
|
events["value_num"] = events.get("value_num")
|
||||||
|
events["source_table"], events["source_id"] = "seer", events["person_id"]
|
||||||
|
return events.reset_index(drop=True)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def trained():
|
||||||
|
events = seer_events(pd.read_csv(SEER, dtype=str))
|
||||||
|
spec = MODELS["survival"]
|
||||||
|
model, metrics, data = spec.train(events, AS_OF)
|
||||||
|
return spec, model, metrics, data
|
||||||
|
|
||||||
|
|
||||||
|
def _original(name: str) -> pd.DataFrame:
|
||||||
|
return pd.read_csv(RUN / name)
|
||||||
|
|
||||||
|
|
||||||
|
def test_each_scenario_takes_the_originals_patients_and_deaths(trained):
|
||||||
|
spec, _, _, data = trained
|
||||||
|
members = pd.concat([data["train"], data["test"]]).reset_index(drop=True)
|
||||||
|
masks = scenario_masks(members, spec.scenarios)
|
||||||
|
theirs = _original("subgrupos_KM_Weibull_fraccional.csv").set_index("subgrupo")
|
||||||
|
for name, row in theirs.iterrows():
|
||||||
|
mask = masks[name]
|
||||||
|
assert (int(mask.sum()), int(members["event"][mask].sum())) == (
|
||||||
|
row["n"],
|
||||||
|
row["fallecidos"],
|
||||||
|
), name
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def report(trained):
|
||||||
|
spec, model, _, data = trained
|
||||||
|
return survival.interpretability(spec, model, data)
|
||||||
|
|
||||||
|
|
||||||
|
def test_each_scenarios_observed_curves_are_the_originals(report):
|
||||||
|
theirs = _original("subgrupos_KM_Weibull_fraccional.csv").set_index("subgrupo")
|
||||||
|
assert {e["escenario"] for e in report["escenarios"]} == set(theirs.index)
|
||||||
|
for e in report["escenarios"]:
|
||||||
|
row, km = theirs.loc[e["escenario"]], np.array(e["km"]["S"])
|
||||||
|
months = np.arange(len(km))
|
||||||
|
weibull = np.interp(months, e["weibull"]["t"], e["weibull"]["S"])
|
||||||
|
fractional = np.interp(months, e["weibull_fractional"]["t"], e["weibull_fractional"]["S"])
|
||||||
|
assert e["weibull"]["k"] == pytest.approx(row["k Weibull"], rel=CURVE), e["escenario"]
|
||||||
|
assert np.abs(weibull - km).max() == pytest.approx(row["máx|KM−Weibull|"], abs=CURVE)
|
||||||
|
assert np.abs(fractional - km).max() <= row["máx|KM−fracc.|"] + CURVE, e["escenario"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_models_points_are_the_survival_of_the_cases_it_learned_from(trained, report):
|
||||||
|
spec, _, _, data = trained
|
||||||
|
train = data["train"].reset_index(drop=True)
|
||||||
|
masks = scenario_masks(train, spec.scenarios)
|
||||||
|
theirs = _original("subgrupos_puntos_LR_HBN.csv")
|
||||||
|
horizons = list(spec.borders[1:])
|
||||||
|
for e in report["escenarios"]:
|
||||||
|
mask = masks[e["escenario"]]
|
||||||
|
months, event = train["months"][mask].to_numpy(), train["event"][mask].to_numpy(bool)
|
||||||
|
km, _, _ = curves.kaplan_meier(months, event, horizons[-1])
|
||||||
|
ours = np.array(e["points"]["COMB"]["S"])
|
||||||
|
assert ours == pytest.approx(km[horizons], abs=CALIBRATION), e["escenario"]
|
||||||
|
original = theirs[(theirs["subgrupo"] == e["escenario"]) & (theirs["modelo"] == "COMB")]
|
||||||
|
gap = np.abs(ours - original.sort_values("meses")["S"].to_numpy()).max()
|
||||||
|
print(f"{e['escenario']}: {TRAIN_FRACTION:.0%} training, gap to the original {gap:.3f}")
|
||||||
Reference in New Issue
Block a user