From 1b9afb22ead8c05345dff167ac5b98efda38f7ab Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Sat, 21 Nov 2026 14:43:46 -0600 Subject: [PATCH] CaMa: the SEER stages see the molecular subtype; the subtype derivation is shared; the live menu reads the scenarios that can be drawn --- models/cama/survival/development.py | 3 +++ models/cama/survival/estimator.py | 10 ++++++++++ models/cama/survival/live.py | 18 ++++-------------- 3 files changed, 17 insertions(+), 14 deletions(-) diff --git a/models/cama/survival/development.py b/models/cama/survival/development.py index 381c08d..3afad60 100644 --- a/models/cama/survival/development.py +++ b/models/cama/survival/development.py @@ -16,6 +16,8 @@ from pathlib import Path import numpy as np import pandas as pd +from models.cama.survival.estimator import molecular_subtype + UNAVAILABLE = ("Estadio_cat", "Tratamiento_quirurgico_cat", "Radioterapia_cat", "Quimioterapia_cat") # What the dashboard reads: the file written by a stage, under the name it is published with. @@ -50,6 +52,7 @@ def _recoded_frame(labelled_members: pd.DataFrame) -> pd.DataFrame: ("Receptor_estrogeno_cat", "er"), ("Receptor_progesterona_cat", "pr"), ("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" return frame diff --git a/models/cama/survival/estimator.py b/models/cama/survival/estimator.py index 86d9c39..0a89147 100644 --- a/models/cama/survival/estimator.py +++ b/models/cama/survival/estimator.py @@ -34,6 +34,16 @@ DEFAULT_SIZE_CUTS = (20, 50) # mm: T1 up to 20, T2 up to 50, T3 above EPOCH = pd.Timestamp("1970-01-01") +def molecular_subtype(labelled: pd.DataFrame) -> pd.Series: + """The SEER subtype string (`HR+/HER2-`...) from the receptors: hormone-positive when either is, HER2-positive at 3+ and + negative at 0 and 1+; an equivocal (2+) or missing HER2 leaves the subtype unknown, so it is in no HER2 scenario.""" + hr_positive = (labelled["er"] == "POSITIVO") | (labelled["pr"] == "POSITIVO") + hr_known = labelled["er"].isin(["POSITIVO", "NEGATIVO"]) | labelled["pr"].isin(["POSITIVO", "NEGATIVO"]) + her2 = labelled["her2"].map({"H3": "+", "H0": "-", "H1": "-"}) + subtype = np.where(hr_known & her2.notna(), np.where(hr_positive, "HR+", "HR-") + "/HER2" + her2.fillna(""), "Desconocido") + return pd.Series(subtype, index=labelled.index) + + def survival_settings(table: dict) -> SurvivalSettings: """`SurvivalSettings` from a `[config.survival]` table: lists become tuples, an unknown key is an error.""" return SurvivalSettings(**{key: tuple(value) if isinstance(value, list) else value for key, value in table.items()}) diff --git a/models/cama/survival/live.py b/models/cama/survival/live.py index 4415327..72b6c9b 100644 --- a/models/cama/survival/live.py +++ b/models/cama/survival/live.py @@ -17,7 +17,7 @@ import pandas as pd from models.cama.seer_survival import scenarios from models.cama.seer_survival import survival_curves as luis from models.cama.survival import population -from models.cama.survival.estimator import FEATURES, IntervalSurvival, survival_settings +from models.cama.survival.estimator import FEATURES, IntervalSurvival, molecular_subtype, survival_settings from models.dags.training import Scenario, dataflow MIN_MEMBERS = 30 @@ -46,16 +46,6 @@ def members(scenario: Scenario, frame: pd.DataFrame, lineage: dict) -> pd.DataFr return dr.execute(["labelled_members"], inputs={"source_cohort": frame, "cohort_lineage": lineage})["labelled_members"] -def molecular_subtype(labelled: pd.DataFrame) -> pd.Series: - """The SEER subtype string (`HR+/HER2-`...) from the receptors: hormone-positive when either is, HER2-positive at 3+ and - negative at 0 and 1+; an equivocal (2+) or missing HER2 leaves the subtype unknown, so it is in no HER2 scenario.""" - hr_positive = (labelled["er"] == "POSITIVO") | (labelled["pr"] == "POSITIVO") - hr_known = labelled["er"].isin(["POSITIVO", "NEGATIVO"]) | labelled["pr"].isin(["POSITIVO", "NEGATIVO"]) - her2 = labelled["her2"].map({"H3": "+", "H0": "-", "H1": "-"}) - subtype = np.where(hr_known & her2.notna(), np.where(hr_positive, "HR+", "HR-") + "/HER2" + her2.fillna(""), "Desconocido") - return pd.Series(subtype, index=labelled.index) - - 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.""" @@ -63,7 +53,7 @@ def scenario_masks(labelled: pd.DataFrame) -> dict[str, np.ndarray]: return scenarios.masks(raw) -def _answerable(labelled: pd.DataFrame, mask: np.ndarray) -> bool: +def answerable(labelled: pd.DataFrame, mask: np.ndarray) -> bool: return int(mask.sum()) >= MIN_MEMBERS and int(labelled["event"].to_numpy()[mask].sum()) >= MIN_EVENTS @@ -72,7 +62,7 @@ def patient_scenarios(labelled: pd.DataFrame, pac_id: int) -> list[str]: row = np.flatnonzero(labelled["pac_id"].to_numpy() == pac_id) if len(row) == 0: raise QueryError("La paciente no está en la cohorte del modelo.") - found = [name for name, mask in scenario_masks(labelled).items() if mask[row[0]] and _answerable(labelled, mask)] + found = [name for name, mask in scenario_masks(labelled).items() if mask[row[0]] and answerable(labelled, mask)] return found or [WHOLE] @@ -99,7 +89,7 @@ def curves(scenario: Scenario, model, labelled: pd.DataFrame, name: str | None) if name not in masks: raise QueryError(f"No hay un escenario clínico «{name}».") mask = masks[name] - if not _answerable(labelled, mask): + if not answerable(labelled, mask): raise QueryError(f"El escenario tiene {int(mask.sum())} pacientes y {int(labelled['event'].to_numpy()[mask].sum())} defunciones; " f"se necesitan al menos {MIN_MEMBERS} y {MIN_EVENTS}.") selected = labelled[mask].reset_index(drop=True)