CaMa: the SEER stages see the molecular subtype; the subtype derivation is shared; the live menu reads the scenarios that can be drawn

This commit is contained in:
rockdrigo
2026-11-21 14:43:46 -06:00
parent 3fdc59df6d
commit 1b9afb22ea
3 changed files with 17 additions and 14 deletions
+3
View File
@@ -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
+10
View File
@@ -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()})
+4 -14
View File
@@ -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)