Files
models/models/cama/specs.py
T

165 lines
7.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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, 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 the site's patients
(`gold.cama_cohort_recurrence`, models.cama.recurrence.site) with the old model's math
(proved on METABRIC and SCAN-B by models/tests/test_recurrence.py); slow (its bootstraps
take minutes), so it trains only when asked for by name."""
from dataclasses import dataclass, field
from datetime import date
import pandas as pd
from models.survival import DAYS_PER_YEAR, OUTPUT, SCENARIO_SEPARATOR, 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
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:
"""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))
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:
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))
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
@dataclass(frozen=True)
class SiteRecurrence:
"""The recurrence model on the site's own patients (models.cama.recurrence.site): the
cohort's timelines in, its fits, calculator and risk factors out, with its own reports;
each member scored at 12, 36 and 60 months, with the clinical scenarios she falls in."""
name: str
cohort: str = "cama_cohort_recurrence"
slow: bool = True
reports: bool = True # it writes its own reports (models.jobs)
method: str = field(default="stepwise logistic regression + Bayesian network", init=False)
def train(self, events, as_of=None) -> tuple:
from models.cama import recurrence
from models.cama.recurrence import site
return recurrence.train_site(site.frame(events, as_of or date.today()))
def predict(self, model, events) -> pd.DataFrame:
from models.cama.recurrence import calculator, site
members = site.frame(events, date.today())
found = model.predict(members)
index = events.groupby("person_id")["index_date"].first()
masks = calculator.masks(members, calculator.SCENARIOS["site"])
named = [SCENARIO_SEPARATOR.join(n for n, m in masks.items() if m[i]) or None
for i in range(len(members))] # fmt: skip
rows = []
for i, person in enumerate(members["paciente"]):
for h in model.horizons:
rows.append({"person_id": person,
"index_date": pd.Timestamp(index[person]).date(),
"horizon_years": h / 12, "probability": found[f"recurrence_{h}m"][i],
"ci_low": None, "ci_high": None, "scenarios": named[i]}) # fmt: skip
return pd.DataFrame(rows, columns=OUTPUT)
MODELS = {
"survival": Spec(
name="survival",
cohort="cama_cohort_survival",
features=(
"age_group",
*RESULTS,
"ki67_group",
"size_group",
"stage",
"surgery",
"chemotherapy",
"radiotherapy",
),
covariates=covariates,
# 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": SiteRecurrence("recurrence"),
}