158 lines
7.1 KiB
Python
158 lines
7.1 KiB
Python
"""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 two public reference
|
||
cohorts (METABRIC and SCAN-B, models.cama.recurrence) that the platform loads with the
|
||
`cama_reference` pipeline, not on the hospital's patients; slow (its bootstraps take a
|
||
quarter of an hour), so it trains only when asked for by name."""
|
||
|
||
from dataclasses import dataclass, field
|
||
|
||
import pandas as pd
|
||
|
||
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:
|
||
"""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 ReferenceRecurrence:
|
||
"""The recurrence model over the reference cohorts the `pipeline` loaded: one source node
|
||
per cohort, named as the cohort."""
|
||
|
||
name: str
|
||
pipeline: str = "cama_reference"
|
||
cohort: None = None # trains on no gold cohort, and scores no patient
|
||
slow: bool = True
|
||
method: str = field(default="stepwise logistic regression + Bayesian network", init=False)
|
||
|
||
def train(self, events, as_of=None) -> tuple:
|
||
from models.cama import recurrence
|
||
|
||
model, metrics, reports = recurrence.train(self.datasets())
|
||
return model, metrics, reports
|
||
|
||
def datasets(self) -> dict[str, pd.DataFrame]:
|
||
"""Each reference cohort's rows, as the pipeline loaded them."""
|
||
from models.cama import recurrence
|
||
|
||
found = {s: pd.DataFrame(nodes.rows(self.pipeline, s)) for s in recurrence.SOURCES}
|
||
if any(r.empty for r in found.values()):
|
||
raise LookupError(f"load the reference cohorts first (pipeline {self.pipeline})")
|
||
return found
|
||
|
||
def predict(self, model, events) -> pd.DataFrame:
|
||
return model.predict(events)
|
||
|
||
|
||
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": ReferenceRecurrence("recurrence"),
|
||
}
|