24534606f1
Remove 212 Python docstrings and 118 comments, and trim prose from three noqa pragmas. The submodule had zero tracked Markdown files. Preserve the existing executable statements and lint pragmas. Use pass for class bodies that previously consisted of only a docstring.
122 lines
6.3 KiB
Python
122 lines
6.3 KiB
Python
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
|
||
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]
|
||
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
|
||
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:
|
||
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:
|
||
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:
|
||
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:
|
||
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
|