Files
models/models/cama/recurrence/site.py
T

147 lines
8.3 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 site's own recurrence cohort (the `site` source of models.cama.recurrence): the CaMa
timelines of `gold.cama_cohort_recurrence`, indexed at each patient's first invasive biopsy
report, as one table in the shape of SCAN-B's (the clinical cohort the old model learned
from), so the same fits, calculator and risk factors run on it.
- Time and event: months from the index to her first recurrence (any site) after it, else to
her death, else to the cut-off (the site records its recurrences: a patient without one is
taken as free of it up to then); `muerte_sin_recaida` when she died without one.
- Covariates, from the index report's results (a week before to RESULT_DAYS after) and the
first course of treatment (TREATMENT_DAYS), as categories (missing: UNKNOWN):
age, size and positive nodes in SCAN-B's bands, grade, ER, PR, HER2, Ki-67 (< 20 % or
more), histologic type, stage group, and the clinical subtype by the St. Gallen surrogate:
Luminal A (HR+, HER2−, Ki-67 < 20 %), Luminal B HER2− (Ki-67 ≥ 20 %), Luminal B HER2+,
Non-luminal HER2+ and Basal-like (triple negative), as SCAN-B names them."""
import numpy as np
import pandas as pd
from models.cama.recurrence import cohorts
from models.cama.recurrence.cohorts import UNKNOWN, Cohort, _band, _text, collinear
RESULT_DAYS = 30
TREATMENT_DAYS = 365
KI67_HIGH = 20.0 # %, St. Gallen's cut between Luminal A and Luminal B
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
RECEPTOR = {"positive": "Positive", "negative": "Negative"}
SURGERY = {"breast_conserving_surgery": "Lumpectomy", "mastectomy": "Mastectomy"}
TREATMENTS = {"Quimioterapia": "chemotherapy", "Radioterapia": "radiotherapy",
"Hormonoterapia": "hormone_therapy", "AntiHER2": "anti_her2"} # fmt: skip
FIXED = ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"]
TREATMENT = ["Cirugia", *TREATMENTS]
# The clinical scenarios drawn: covariate -> the categories it takes (AND across covariates).
SCENARIOS = {
"Luminal A · sin ganglios · tumor ≤20 mm (bajo riesgo)": {
"Subtipo_clinico": ["Luminal A"], "Ganglios_positivos": ["0"],
"Tamano_tumor": ["<=20 mm"]},
"Ganglios 4+": {"Ganglios_positivos": ["4+"]},
"Tumor >50 mm": {"Tamano_tumor": [">50 mm"]},
"< 45 años": {"Edad": ["<45"]},
"≥ 75 años": {"Edad": ["75+"]},
"Basal-like": {"Subtipo_clinico": ["Basal-like"]},
"HER2+ (luminal B HER2+ o no luminal)": {
"Subtipo_clinico": ["Luminal B HER2+", "Non-luminal HER2+"]},
"Luminal B HER2−": {"Subtipo_clinico": ["Luminal B HER2-"]},
"Luminal · 1-3 ganglios · lumpectomía": {
"Subtipo_clinico": ["Luminal A", "Luminal B HER2-"], "Ganglios_positivos": ["1-3"],
"Cirugia": ["Lumpectomy"]},
"Grado 3": {"Grado_histologico": ["3"]},
} # fmt: skip
MIN_PER_CLASS = 10 # recurred, and free of it, at each horizon: fewer cannot be split and fitted
SAMPLING = {
"criterio": "pacientes con un primer reporte de biopsia invasiva; sin recaída registrada, "
"libre de ella hasta su defunción o la fecha de corte",
"origen": "la sede (sus propias pacientes)",
}
def subtype(er, pr, her2, ki67) -> str:
"""The St. Gallen surrogate of the intrinsic subtype, as SCAN-B names it."""
hormone = "positive" in (er, pr)
if her2 == "positive":
return "Luminal B HER2+" if hormone else "Non-luminal HER2+"
if her2 != "negative":
return UNKNOWN
if not hormone:
return "Basal-like" if er == "negative" and pr == "negative" else UNKNOWN
if ki67 is None or ki67 != ki67:
return UNKNOWN
return "Luminal A" if ki67 < KI67_HIGH else "Luminal B HER2-"
def frame(events: pd.DataFrame, as_of) -> pd.DataFrame:
"""One row per member: her time, event and covariates, as `cohorts.prepare` gives a
reference cohort's."""
events = events.assign(date=pd.to_datetime(events["date"]),
index_date=pd.to_datetime(events["index_date"])) # fmt: skip
members = events.groupby("person_id")["index_date"].first()
days = (events["date"] - events["index_date"]).dt.days
cut = pd.Timestamp(as_of)
after = events[(days > 0) & (events["date"] <= cut)]
first_recurrence = after[after["type"] == "recurrence"].groupby("person_id")["date"].min()
death = events[(events["type"] == "death") & (events["date"] <= cut)]
death = death.groupby("person_id")["date"].min().reindex(members.index)
end = first_recurrence.reindex(members.index).fillna(death).fillna(cut)
out = pd.DataFrame(index=members.index)
out["paciente"] = members.index
out["tiempo_meses"] = (end - members).dt.days / cohorts.DAYS_PER_MONTH
out["evento"] = first_recurrence.reindex(members.index).notna().astype(int)
out["muerte_sin_recaida"] = (death.notna() & (out["evento"] == 0)).astype(int)
near = events[days.between(-7, RESULT_DAYS)].sort_values(["date", "source_id"])
code = lambda kind: near[near["type"] == kind].groupby("person_id")["value_code"].first() # noqa: E731
number = lambda kind: near[near["type"] == kind].groupby("person_id")["value_num"].first() # noqa: E731
birth = events[events["type"] == "birth"].groupby("person_id")["date"].min()
age = (members - birth.reindex(members.index)).dt.days / 365.25
out["Edad"] = _band(age, *cohorts.AGE)
out["Tamano_tumor"] = _band(number("size_mm").reindex(members.index), *cohorts.SIZE)
out["Ganglios_positivos"] = _band(number("positive_nodes").reindex(members.index),
*cohorts.NODES) # fmt: skip
out["Grado_histologico"] = _text(code("grade").reindex(members.index).map(cohorts.GRADES))
receptors = {k: code(k).reindex(members.index) for k in ("er", "pr", "her2")}
ki67 = number("ki67_pct").reindex(members.index)
out["Receptor_estrogeno"] = _text(receptors["er"].map(RECEPTOR))
out["Receptor_progesterona"] = _text(receptors["pr"].map(RECEPTOR))
out["HER2"] = _text(receptors["her2"].map(RECEPTOR))
high = np.where(ki67 < KI67_HIGH, f"<{KI67_HIGH:g}%", f">={KI67_HIGH:g}%")
out["Ki67"] = _text(pd.Series(np.where(ki67.isna(), None, high), index=members.index))
out["Subtipo_clinico"] = [subtype(*a) for a in zip(
receptors["er"], receptors["pr"], receptors["her2"], ki67, strict=True)] # fmt: skip
out["Tipo_histologico"] = _text(code("histologic_type").reindex(members.index))
out["Estadio_clinico"] = _text(code("stage").reindex(members.index).map(STAGE_GROUP))
course = events[(events["type"] == "treatment") & days.between(0, TREATMENT_DAYS)]
given = course.groupby("person_id")["value_code"].agg(set).reindex(members.index)
given = given.apply(lambda g: g if isinstance(g, set) else set())
out["Cirugia"] = given.apply(
lambda g: next((SURGERY[s] for s in reversed(SURGERY) if s in g), "None")
)
for name, kind in TREATMENTS.items():
out[name] = given.apply(lambda g, k=kind: "Yes" if k in g else "No")
return out.reset_index(drop=True)
def scarce(rows: pd.DataFrame) -> str | None:
"""Why the cohort is too small to learn from (a horizon with fewer than MIN_PER_CLASS
patients recurred by it, or known free of it), or None."""
for h in cohorts.HORIZONS:
y = cohorts.at_horizon(rows, h)["y"]
fewest = min(int(y.sum()), int((y == 0).sum()))
if fewest < MIN_PER_CLASS:
return (f"{int(y.sum())} recurred and {int((y == 0).sum())} free of it at {h} months, "
f"{MIN_PER_CLASS} of each needed") # fmt: skip
return None
def prepare(rows: pd.DataFrame) -> Cohort:
"""The site's cohort as a reference cohort is prepared: the nearly redundant covariates
dropped (cohorts.collinear) from the model, though kept in the table, since the clinical
scenarios name patients by them (the subtype, built from the receptors and Ki-67, is
redundant by construction)."""
covariates = [c for c in rows.columns if c not in FIXED]
dropped = collinear(rows, [c for c in covariates if c not in TREATMENT])
kept = [c for c in covariates if c not in dropped]
treatment = [c for c in TREATMENT if c in kept]
return Cohort("site", rows[FIXED + kept + dropped], kept, treatment, dropped, "Sitio",
SCENARIOS, SAMPLING) # fmt: skip