Every model trains on the site: EEG age curves on the children with TEA ruled out, recurrence on the site's patients (St. Gallen subtype), and the EEG–ADOS-2 association
This commit is contained in:
@@ -0,0 +1,106 @@
|
||||
"""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]
|
||||
|
||||
|
||||
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 prepare(rows: pd.DataFrame) -> Cohort:
|
||||
"""The site's cohort as a reference cohort is prepared: the nearly redundant covariates
|
||||
dropped (cohorts.collinear)."""
|
||||
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]
|
||||
return Cohort("site", rows[FIXED + kept], kept, [c for c in TREATMENT if c in kept], dropped)
|
||||
Reference in New Issue
Block a user