From d91ac7c14b2744127b6c1706f57a6e8382cca539 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roberto=20Trevi=C3=B1o=20Cervantes?= Date: Sun, 22 Nov 2026 11:36:52 -0600 Subject: [PATCH] CaMa survival: the members' stage, surgery and adjuvant treatments, read by the clinical scenarios and the development stages --- models/cama/survival/development.py | 9 +++++---- models/cama/survival/estimator.py | 17 +++++++++++++++- models/cama/survival/live.py | 7 ++++--- tests/cama/test_survival.py | 31 +++++++++++++++++++++++++++-- 4 files changed, 54 insertions(+), 10 deletions(-) diff --git a/models/cama/survival/development.py b/models/cama/survival/development.py index 3afad60..f23c17d 100644 --- a/models/cama/survival/development.py +++ b/models/cama/survival/development.py @@ -19,7 +19,8 @@ import pandas as pd from models.cama.survival.estimator import molecular_subtype -UNAVAILABLE = ("Estadio_cat", "Tratamiento_quirurgico_cat", "Radioterapia_cat", "Quimioterapia_cat") +CONTEXT_COLUMNS = {"Estadio_cat": "stage", "Tratamiento_quirurgico_cat": "surgery", "Radioterapia_cat": "radiotherapy", + "Quimioterapia_cat": "chemotherapy"} # What the dashboard reads: the file written by a stage, under the name it is published with. TABLES = { "or_lr_balanceada.csv": "or_lr_balanceada", "hbn_arcos.csv": "hbn_arcos", @@ -53,8 +54,8 @@ def _recoded_frame(labelled_members: pd.DataFrame) -> pd.DataFrame: ("HER2_IHQ_cat", "her2"), ("Ki67_cat", "ki67_group")): frame[column] = lm[source].fillna("Desconocido").astype(str).to_numpy() frame["Subtipo_molecular_cat"] = molecular_subtype(lm).to_numpy() # the scenarios of stage 5 and 6 read the subtype - for column in UNAVAILABLE: - frame[column] = "Desconocido" + for column, source in CONTEXT_COLUMNS.items(): + frame[column] = lm[source].fillna("Desconocido").astype(str).to_numpy() if source in lm else "Desconocido" return frame @@ -111,7 +112,7 @@ def development(labelled_members: pd.DataFrame, desarrollo: dict) -> dict: figures[path.stem] = base64.b64encode(raw).decode("ascii") return {"desarrollo": { "version": 1, "n": int(len(labelled_members)), "etapas": [{"etapa": s, "estado": e, "segundos": t} for s, e, t in log], - "errores": errors, "variables_no_disponibles": list(UNAVAILABLE), "tablas": tables, "figuras": figures}} + "errores": errors, "variables_no_disponibles": [c for c, s in CONTEXT_COLUMNS.items() if s not in labelled_members], "tablas": tables, "figuras": figures}} def population(population_curves: dict, development: dict) -> dict: diff --git a/models/cama/survival/estimator.py b/models/cama/survival/estimator.py index 0a89147..f4a3e0e 100644 --- a/models/cama/survival/estimator.py +++ b/models/cama/survival/estimator.py @@ -29,6 +29,13 @@ NUMERIC = ["age_years", "size_mm", "ki67_pct"] # the covariates before banding: FEATURES = ["age_group", "histologic_type", "grade", "er", "pr", "her2", "ki67_group", "size_group"] RESULTS = {"tipo_histologico": "histologic_type", "grado_nottingham": "grade", "receptor_estrogeno": "er", "receptor_progesterona": "pr", "her2": "her2"} +# What describes a member's disease and treatment without being a covariate: the clinical scenarios and the development +# stages read them. The stage is the one reported with the diagnosis; a treatment counts in the first year after it. +CONTEXT = ["stage", "surgery", "radiotherapy", "chemotherapy"] +TREATMENT_DAYS = 365 +SURGERY_LABELS = {"SEGMENTECTOMIA": "Cirugía conservadora", "ESCISIONAL": "Cirugía conservadora", + "MASTECTOMIA_TOTAL": "Mastectomía", "MASTECTOMIA_RADICAL_MODIFICADA": "Mastectomía", + "SIN_CIRUGIA": "Sin cirugía"} WINDOW_KEYS = ("recruitment_start", "recruitment_end") DEFAULT_SIZE_CUTS = (20, 50) # mm: T1 up to 20, T2 up to 50, T3 above EPOCH = pd.Timestamp("1970-01-01") @@ -78,7 +85,15 @@ def member_table(cohort: pd.DataFrame, age_cuts: list, ki67_cuts: list, result_d size = near[near["tipo"] == "tamano_tumor_mm"].groupby("pac_id")["valor_numerico"].first().reindex(members.index) members["size_group"] = _band(size, size_cuts or DEFAULT_SIZE_CUTS) members["size_mm"], members["ki67_pct"] = size, ki67 - return members[["fecha_indice", *FEATURES, *NUMERIC]] + stage = near[near["tipo"] == "estadio_clinico"].groupby("pac_id")["valor_codigo"].first().reindex(members.index) + members["stage"] = stage.map(lambda v: v[1:] if isinstance(v, str) and v.startswith("E") else v) + treated = frame[(frame["fecha"] - frame["fecha_indice"]).dt.days.between(-7, TREATMENT_DAYS)].sort_values(["fecha", "fuente_id"]) + surgery = treated[treated["tipo"] == "cirugia"].groupby("pac_id")["valor_codigo"].first().reindex(members.index) + members["surgery"] = surgery.map(lambda v: SURGERY_LABELS.get(v, "Otra cirugía") if isinstance(v, str) else None) + for kind, name in (("radioterapia", "radiotherapy"), ("quimioterapia", "chemotherapy")): + given = set(treated.loc[treated["tipo"] == kind, "pac_id"]) + members[name] = ["Sí" if pac in given else "No" for pac in members.index] + return members[["fecha_indice", *FEATURES, *NUMERIC, *CONTEXT]] def outcome_table(cohort: pd.DataFrame, cutoff, cap_months: int) -> pd.DataFrame: diff --git a/models/cama/survival/live.py b/models/cama/survival/live.py index 72b6c9b..da02269 100644 --- a/models/cama/survival/live.py +++ b/models/cama/survival/live.py @@ -47,9 +47,10 @@ def members(scenario: Scenario, frame: pd.DataFrame, lineage: dict) -> pd.DataFr def scenario_masks(labelled: pd.DataFrame) -> dict[str, np.ndarray]: - """Each scenario's mask over the members. The age and the subtype are the hospital's; stage and surgery are not reported - yet, so a scenario that needs them has no member.""" - raw = pd.DataFrame({"Age": labelled["age_years"].to_numpy(), "Subtipo_molecular_cat": molecular_subtype(labelled).to_numpy()}, index=labelled.index) + """Each scenario's mask over the members, by her age, molecular subtype, stage and surgery.""" + raw = pd.DataFrame({"Age": labelled["age_years"].to_numpy(), "Subtipo_molecular_cat": molecular_subtype(labelled).to_numpy(), + "Estadio_cat": labelled["stage"].to_numpy(), "Tratamiento_quirurgico_cat": labelled["surgery"].to_numpy()}, + index=labelled.index) return scenarios.masks(raw) diff --git a/tests/cama/test_survival.py b/tests/cama/test_survival.py index fd9cf1a..4da69d4 100644 --- a/tests/cama/test_survival.py +++ b/tests/cama/test_survival.py @@ -300,10 +300,11 @@ def development_record(cohort_frame): def test_a_stage_that_cannot_run_on_the_cohort_is_recorded_and_does_not_stop_the_others(development_record): """Pins down: on a cohort whose covariates barely vary (the 240 members here) the SEER stages that need variation publish their error in the record and the run still produces it, with every stage listed. Fails if one stage's - exception escapes the node, which would stop a version from training.""" + exception escapes the node, which would stop a version from training. The stage and the treatments come from the + members' timeline, so none of them is listed as unavailable; fails if the record stops reading them.""" assert [e["etapa"] for e in development_record["etapas"]] == ["01", "02", "03", "04", "05", "06"] assert set(development_record["errores"]) <= {"01", "02", "03", "04", "05", "06"} - assert "Estadio_cat" in development_record["variables_no_disponibles"] + assert development_record["variables_no_disponibles"] == [] def test_the_development_stages_publish_their_tables_and_figures_on_a_varied_cohort(): @@ -513,3 +514,29 @@ def test_a_saved_model_whose_class_is_older_still_scores_with_the_current_code(m for name, expected in production_model.component_survival(members_frame[FEATURES]).items(): assert again[name] == pytest.approx(expected) + + +def test_the_members_carry_their_stage_and_treatments_and_the_scenarios_read_them(): + """Pins down: a member's stage is the one reported with her diagnosis and her surgery, radiotherapy and chemotherapy are + those of the year after it, and the clinical scenarios that need a stage or a conservative surgery find her. Fails if + `member_table` stops reading them or `live.scenario_masks` goes back to age and subtype only.""" + from models.cama.survival import estimator, live + + rows = [] + for pac, (stage, surgery, her2) in enumerate([("EI", "SEGMENTECTOMIA", "H0"), ("EIV", "MASTECTOMIA_TOTAL", "H3")], start=1): + rows += [ + {"pac_id": pac, "tipo": "nacimiento", "fecha": "1950-01-01", "valor_codigo": None, "valor_numerico": None}, + {"pac_id": pac, "tipo": "biopsia", "fecha": "2025-01-10", "valor_codigo": "CARCINOMA_INVASOR", "valor_numerico": None}, + {"pac_id": pac, "tipo": "estadio_clinico", "fecha": "2025-01-10", "valor_codigo": stage, "valor_numerico": None}, + {"pac_id": pac, "tipo": "her2", "fecha": "2025-01-10", "valor_codigo": her2, "valor_numerico": None}, + {"pac_id": pac, "tipo": "receptor_estrogeno", "fecha": "2025-01-10", "valor_codigo": "NEGATIVO", "valor_numerico": None}, + {"pac_id": pac, "tipo": "receptor_progesterona", "fecha": "2025-01-10", "valor_codigo": "NEGATIVO", "valor_numerico": None}, + {"pac_id": pac, "tipo": "cirugia", "fecha": "2025-03-01", "valor_codigo": surgery, "valor_numerico": None}, + ] + rows.append({"pac_id": 1, "tipo": "radioterapia", "fecha": "2025-05-01", "valor_codigo": "ADYUVANTE", "valor_numerico": None}) + cohort = pd.DataFrame(rows).assign(fecha_indice="2025-01-10", fuente_id="x") + members = estimator.member_table(cohort, [45, 60, 75], [14, 20], 30) + assert members.loc[1, ["stage", "surgery", "radiotherapy", "chemotherapy"]].tolist() == ["I", "Cirugía conservadora", "Sí", "No"] + assert members.loc[2, ["stage", "surgery", "radiotherapy"]].tolist() == ["IV", "Mastectomía", "No"] + masks = live.scenario_masks(members.reset_index()) + assert masks["Estadio I"].tolist() == [True, False] and masks["Estadio IV"].tolist() == [False, True]