"""The two public cohorts the recurrence model is proved on, METABRIC and SCAN-B, each as a `Cohort` from its dataset as the `cama_reference` pipeline loads it (every value as written, column names as dlt names them, `line` the order the file is published in).""" import pandas as pd from models.cama import recurrence from models.cama.recurrence import site from models.cama.recurrence.cohorts import ( AGE, DAYS_PER_MONTH, GRADES, NODES, SIZE, Cohort, _band, _number, _text, collinear, ) SOURCES = ("metabric", "scanb") SAVED = "metabric" N_BOOTSTRAP = {"metabric": 100, "scanb": 40, "site": 40} LABELS = {"metabric": "METABRIC", "scanb": "SCAN-B"} SAMPLING = { "criterio": "pacientes con tiempo y estado de recaída; SCAN-B solo mujeres", "origen": "METABRIC y SCAN-B (externas)", } SCENARIOS = { "metabric": { "RE+ · sin ganglios · tumor ≤20 mm (bajo riesgo)": { "Receptor_estrogeno": ["Positive"], "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 (PAM50)": {"Subtipo_PAM50": ["Basal"]}, "HER2 (PAM50)": {"Subtipo_PAM50": ["Her2"]}, "Luminal B (PAM50)": {"Subtipo_PAM50": ["LumB"]}, "RE+ · 1-3 ganglios · cirugía conservadora": { "Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["1-3"], "Cirugia": ["BREAST CONSERVING"]}, "RE− · grado 3": {"Receptor_estrogeno": ["Negative"], "Grado_histologico": ["3"]}, }, "scanb": site.SCENARIOS, } # fmt: skip FIXED = { "metabric": ["paciente", "tiempo_meses", "evento"], "scanb": ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"], } TREATMENT = { "metabric": ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"], "scanb": ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"], } # Covariates taken as they come (our name: the dataset's column). PASSTHROUGH = { "metabric": { "Receptor_estrogeno": "er_status", "Receptor_progesterona": "pr_status", "HER2": "her2_status", "Subtipo_PAM50": "pam50_x_claudin_low_subtype", "Tipo_histologico": "cancer_type_detailed", "Celularidad": "cellularity", "Estado_menopausico": "inferred_menopausal_state", "Cluster_integrativo": "integrative_cluster", "Lateralidad": "primary_tumor_laterality", "Cirugia": "type_of_breast_surgery", "Quimioterapia": "chemotherapy", "Radioterapia": "radio_therapy", "Hormonoterapia": "hormone_therapy", }, "scanb": { "Receptor_estrogeno": "er", "Receptor_progesterona": "pr", "HER2": "her2", "Ki67": "ki67", "Subtipo_clinico": "clinical_subtype", "Tipo_histologico": "histology", "Estado_menopausico": "menopause_status_bin", "Lateralidad": "laterality", "Estadio_clinico": "tnm_clinical_stage", "Cirugia": "surgery_type", "Quimioterapia": "chemotherapy", "Radioterapia": "radiation", "Hormonoterapia": "endocrine", "AntiHER2": "anti_her2", }, } # fmt: skip SCANB_NODES = {"NodeNegative": "0", "SubMicroMet": "0", "1to3": "1-3", "4toX": "4+"} SCANB_GRADES = {"Grade1": "1", "Grade2": "2", "Grade3": "3"} def _in_order(rows: pd.DataFrame) -> pd.DataFrame: return rows.sort_values("line", kind="stable").reset_index(drop=True) def _metabric(rows: pd.DataFrame) -> pd.DataFrame: d = _in_order(rows).dropna(subset=["relapse_free_status", "relapse_free_status_monthsx"]) d = d.reset_index(drop=True) out = pd.DataFrame({"paciente": d["patient_id"]}) out["tiempo_meses"] = _number(d["relapse_free_status_monthsx"]) out["evento"] = d["relapse_free_status"].str.startswith("1").astype(int) out["Edad"] = _band(_number(d["age_at_diagnosis"]), *AGE) out["Tamano_tumor"] = _band(_number(d["tumor_size"]), *SIZE) out["Ganglios_positivos"] = _band(_number(d["lymph_nodes_examined_positive"]), *NODES) out["Grado_histologico"] = _text(d["neoplasm_histologic_grade"].map(GRADES)) # Mutational load in tertiles of this cohort; a value on a cut falls in the lower band. load = _number(d["mutation_count"]) q1, q2 = load.quantile([1 / 3, 2 / 3]).to_numpy() edges = [-1, q1 + 1e-9, q2 + 1e-9, 1e6] out["Carga_mutacional"] = _band(load, edges, ["baja", "media", "alta"]) for name, column in PASSTHROUGH["metabric"].items(): out[name] = _text(d[column]) return out def _scanb(rows: pd.DataFrame) -> pd.DataFrame: d = _in_order(rows) d = d[d["gender"] == "F"].dropna(subset=["rfi_event", "rfi_days"]).reset_index(drop=True) rfi, died = _number(d["rfi_event"]), _number(d["os_event"]) out = pd.DataFrame({"paciente": d["patient_name"]}) out["tiempo_meses"] = _number(d["rfi_days"]) / DAYS_PER_MONTH out["evento"] = rfi.astype(int) out["muerte_sin_recaida"] = ((died == 1) & (rfi == 0)).astype(int) out["Edad"] = _band(_number(d["age_5year_bin"]) - 2, *AGE) # the 5-year bin's middle out["Tamano_tumor"] = _band(_number(d["tumor_size_mm"]), *SIZE) out["Ganglios_positivos"] = _text(d["node_met_spec"].map(SCANB_NODES)) out["Grado_histologico"] = _text(d["nhg"].map(SCANB_GRADES)) for name, column in PASSTHROUGH["scanb"].items(): out[name] = _text(d[column]) return out def prepare(source: str, raw: pd.DataFrame) -> Cohort: full = {"metabric": _metabric, "scanb": _scanb}[source](raw) fixed, treatment = FIXED[source], TREATMENT[source] covariates = [c for c in full.columns if c not in fixed] dropped = collinear(full, [c for c in covariates if c not in treatment]) kept = [c for c in covariates if c not in dropped] return Cohort(source, full[fixed + kept], kept, [c for c in treatment if c in kept], dropped, LABELS[source], SCENARIOS[source], SAMPLING) # fmt: skip def train(raws: dict[str, pd.DataFrame], bootstrap: bool = True) -> tuple: """Both cohorts' models, validation, calculator and risk factors; METABRIC's is kept.""" found = {s: prepare(s, raws[s]) for s in SOURCES} return recurrence.fit(found, SAVED, "metabric+scanb", N_BOOTSTRAP if bootstrap else {})