CaMa survival: the clinical scenarios are a shared module and stage 6 lists each scenario's risk factors; the live figure drops the unused options
This commit is contained in:
@@ -151,64 +151,7 @@ xlim_sub = [] # e.g. [0, 72] to hide the extrapolation; empty
|
||||
|
||||
[survival.ylim_sub] # manual zoom of the y axis per subgroup, e.g. "Estadio I" = [0.97, 1.0]
|
||||
|
||||
# Subgroups: every condition present must hold. her2 = "pos" | "neg"; triple_negative (HR-/HER2-); age_min (>=) and
|
||||
# age_max (<) in years; stages (0..4); conservative (conservative surgery).
|
||||
[[survival.subgroups]]
|
||||
name = "HER2+ · ≥60 años · estadio III–IV (Alto)"
|
||||
her2 = "pos"
|
||||
age_min = 60
|
||||
stages = [3, 4]
|
||||
[[survival.subgroups]]
|
||||
name = "HER2+ · <60 años · estadio 0–II (Bajo)"
|
||||
her2 = "pos"
|
||||
age_max = 60
|
||||
stages = [0, 1, 2]
|
||||
[[survival.subgroups]]
|
||||
name = "Estadio IV"
|
||||
stages = [4]
|
||||
[[survival.subgroups]]
|
||||
name = "Estadio I"
|
||||
stages = [1]
|
||||
[[survival.subgroups]]
|
||||
name = "≥ 75 años"
|
||||
age_min = 75
|
||||
[[survival.subgroups]]
|
||||
name = "< 45 años"
|
||||
age_max = 45
|
||||
[[survival.subgroups]]
|
||||
name = "Jóvenes (<45) · HER2− · estadio 0–II · cirugía conservadora"
|
||||
her2 = "neg"
|
||||
age_max = 45
|
||||
stages = [0, 1, 2]
|
||||
conservative = true
|
||||
[[survival.subgroups]]
|
||||
name = "HER2− · estadio 0–II · cirugía conservadora"
|
||||
her2 = "neg"
|
||||
stages = [0, 1, 2]
|
||||
conservative = true
|
||||
[[survival.subgroups]]
|
||||
name = "HER2+ · estadio 0–II · cirugía conservadora"
|
||||
her2 = "pos"
|
||||
stages = [0, 1, 2]
|
||||
conservative = true
|
||||
[[survival.subgroups]]
|
||||
name = "Jóvenes (<45) · estadio 0–II"
|
||||
age_max = 45
|
||||
stages = [0, 1, 2]
|
||||
[[survival.subgroups]]
|
||||
name = "Jóvenes (<45) · HER2−"
|
||||
her2 = "neg"
|
||||
age_max = 45
|
||||
[[survival.subgroups]]
|
||||
name = "Triple negativo (HR−/HER2−) · estadio 0–II"
|
||||
triple_negative = true
|
||||
stages = [0, 1, 2]
|
||||
[[survival.subgroups]]
|
||||
name = "≥ 65 años · HER2− · estadio 0–II · cirugía conservadora"
|
||||
her2 = "neg"
|
||||
age_min = 65
|
||||
stages = [0, 1, 2]
|
||||
conservative = true
|
||||
# The subgroups of the survival curves, and the risk factors of each, are the clinical scenarios of `scenarios.py`.
|
||||
|
||||
[risk_factors]
|
||||
# A category is a risk factor from four criteria: c1 the multivariable OR in the natural population (95 % CI not
|
||||
|
||||
@@ -53,11 +53,12 @@ STAGES = [
|
||||
Stage("05", lambda d, s: run.run_survival(d / run.DEPURATED, d, s), (run.DEPURATED,),
|
||||
("curva_supervivencia_KM_KS_LR_HBN.png", "curva_supervivencia_puntos_LR_HBN.csv",
|
||||
"subgrupos_puntos_LR_HBN.csv", "subgrupos_KM_Weibull_fraccional.csv"),
|
||||
("survival_curves.py", "survival_models.py", "fractional_weibull.py", "settings.py", "run.py")),
|
||||
("survival_curves.py", "survival_models.py", "fractional_weibull.py", "scenarios.py", "settings.py", "run.py")),
|
||||
Stage("06", lambda d, s: run.run_risk_factors(d / run.NATURAL, d, settings=s),
|
||||
(run.NATURAL, "seleccion_bootstrap.csv", "hbn_arcos.csv"),
|
||||
("factores_riesgo.csv", "factores_riesgo_resumen_variables.csv", "asociaciones_tratamiento.csv"),
|
||||
("risk_factors.py", "risk_factor_stats.py", "settings.py", "run.py")),
|
||||
("factores_riesgo.csv", "factores_riesgo_resumen_variables.csv", "asociaciones_tratamiento.csv",
|
||||
"escenarios_factores_riesgo.csv", "escenarios_resumen.csv"),
|
||||
("risk_factors.py", "risk_factor_stats.py", "scenarios.py", "settings.py", "run.py")),
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from models.cama.seer_survival import risk_factor_stats as stats
|
||||
from models.cama.seer_survival import scenarios
|
||||
from models.cama.seer_survival.settings import RiskFactorSettings
|
||||
|
||||
CRITERIA = ["c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia"]
|
||||
@@ -233,3 +234,73 @@ def risk_criteria(risk_classification: Classification, risk_bootstrap_frequency:
|
||||
"horizonte_meses": risk_factors.horizon, "tope_meses": risk_factors.cap_months,
|
||||
"replicas_bootstrap_validas": int(risk_bootstrap_frequency.n_replicas),
|
||||
"criterios_evaluados": risk_classification.criteria, "variables_tratamiento_excluidas": risk_treatment}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- the risk factors of each clinical scenario
|
||||
|
||||
PCT_DEFINING = 0.95 # the category is in at least this share of the scenario: it defines it
|
||||
PCT_MAJORITY = 0.50
|
||||
PCT_PRESENT = 0.10
|
||||
|
||||
|
||||
@dataclass(frozen=True, eq=False)
|
||||
class ScenarioFactors:
|
||||
details: pd.DataFrame # per scenario and classified category: its share of the scenario and of the cohort
|
||||
summary: pd.DataFrame # per scenario: the risk factors, protectors and treatments that define it or are most of it
|
||||
|
||||
|
||||
def _presence(share: float) -> str:
|
||||
if share >= PCT_DEFINING:
|
||||
return "definitoria"
|
||||
if share >= PCT_MAJORITY:
|
||||
return "mayoritaria"
|
||||
return "presente" if share >= PCT_PRESENT else "minoritaria"
|
||||
|
||||
|
||||
def risk_scenario_masks(risk_natural: pd.DataFrame) -> dict[str, np.ndarray]:
|
||||
"""Each clinical scenario's mask over the natural population (`scenarios.masks`), on its raw columns."""
|
||||
return scenarios.masks(risk_natural.drop(columns=[c for c in ("Age_group", "Tumor_group") if c in risk_natural.columns]))
|
||||
|
||||
|
||||
def risk_scenario_factors(risk_classification: Classification, risk_treatment_associations: pd.DataFrame | None,
|
||||
risk_data: pd.DataFrame, risk_scenario_masks: dict[str, np.ndarray]) -> ScenarioFactors:
|
||||
"""Which of the classified risk factors, protectors and treatment associations make up each clinical scenario: a
|
||||
category that is nearly all of a scenario defines it, one that is most of it describes it."""
|
||||
table = risk_classification.table
|
||||
classified = table[table["clasificacion"].str.contains("robusto|sugerente")].copy()
|
||||
classified["tipo"] = classified["clasificacion"].str.split().str[0]
|
||||
if risk_treatment_associations is not None and len(risk_treatment_associations):
|
||||
treatment = risk_treatment_associations.copy()
|
||||
treatment["clasificacion"], treatment["tipo"] = "tratamiento (no se clasifica)", "tratamiento"
|
||||
classified = pd.concat([classified, treatment], ignore_index=True)
|
||||
details, summary = [], []
|
||||
for name, mask in risk_scenario_masks.items():
|
||||
size = int(mask.sum())
|
||||
if size == 0:
|
||||
continue
|
||||
definition = scenarios.describe(scenarios.SCENARIOS[name]) if name in scenarios.SCENARIOS else ""
|
||||
rows = []
|
||||
for _, r in classified.iterrows():
|
||||
share = float((risk_data[r["variable"]][mask] == r["categoria"]).mean())
|
||||
rows.append({"escenario": name, "definicion": definition, "n_escenario": size,
|
||||
"tipo": r["tipo"], "variable": r["variable"], "categoria": r["categoria"], "clasificacion": r["clasificacion"],
|
||||
"OR_muerte": r["OR_muerte"], "IC95_inf": r["IC95_inf"], "IC95_sup": r["IC95_sup"], "delta_S18": r["delta_S18"],
|
||||
"pct_en_escenario": share, "pct_en_cohorte": float((risk_data[r["variable"]] == r["categoria"]).mean()),
|
||||
"presencia": _presence(share)})
|
||||
found = pd.DataFrame(rows, columns=["escenario", "definicion", "n_escenario", "tipo", "variable", "categoria", "clasificacion",
|
||||
"OR_muerte", "IC95_inf", "IC95_sup", "delta_S18", "pct_en_escenario", "pct_en_cohorte", "presencia"])
|
||||
details.append(found[found["pct_en_escenario"] >= PCT_PRESENT])
|
||||
|
||||
def listed(kind, levels):
|
||||
part = found[(found["tipo"] == kind) & (found["presencia"].isin(levels))]
|
||||
return "; ".join(f"{a}={b} ({c.split()[-1] if kind != 'tratamiento' else 'asociacion'}, {p:.0%})"
|
||||
for a, b, c, p in zip(part["variable"], part["categoria"], part["clasificacion"], part["pct_en_escenario"]))
|
||||
|
||||
row = {"escenario": name, "definicion": definition, "n_escenario": size}
|
||||
for kind in ("riesgo", "protector", "tratamiento"):
|
||||
row[f"{kind}_definitorios"] = listed(kind, ["definitoria"])
|
||||
row[f"{kind}_mayoritarios"] = listed(kind, ["mayoritaria"])
|
||||
row["n_factores_riesgo_incluidos"] = int(((found["tipo"] == "riesgo") & found["presencia"].isin(["definitoria", "mayoritaria"])).sum())
|
||||
row["incluye_factor_riesgo"] = row["n_factores_riesgo_incluidos"] > 0
|
||||
summary.append(row)
|
||||
return ScenarioFactors(pd.concat(details, ignore_index=True).round(4) if details else pd.DataFrame(), pd.DataFrame(summary))
|
||||
|
||||
@@ -193,13 +193,15 @@ def run_risk_factors(natural_csv: str, output_dir: str, bootstrap_selection_csv:
|
||||
inputs = {"natural_csv": str(natural_csv),
|
||||
"bootstrap_selection_csv": str(bootstrap_selection_csv or out / "seleccion_bootstrap.csv"),
|
||||
"hbn_arcs_csv": str(hbn_arcs_csv or out / "hbn_arcos.csv"), "risk_factors": settings.risk_factors}
|
||||
r = dr.execute(["risk_factors_table", "risk_variable_summary", "risk_treatment_associations", "risk_criteria"],
|
||||
inputs=inputs)
|
||||
r = dr.execute(["risk_factors_table", "risk_variable_summary", "risk_treatment_associations", "risk_criteria",
|
||||
"risk_scenario_factors"], inputs=inputs)
|
||||
r["risk_factors_table"].to_csv(out / "factores_riesgo.csv", index=False)
|
||||
r["risk_variable_summary"].to_csv(out / "factores_riesgo_resumen_variables.csv")
|
||||
if r["risk_treatment_associations"] is not None:
|
||||
r["risk_treatment_associations"].to_csv(out / "asociaciones_tratamiento.csv", index=False)
|
||||
_dump(out / "factores_riesgo_criterios.json", r["risk_criteria"])
|
||||
r["risk_scenario_factors"].details.to_csv(out / "escenarios_factores_riesgo.csv", index=False)
|
||||
r["risk_scenario_factors"].summary.to_csv(out / "escenarios_resumen.csv", index=False)
|
||||
return r
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
"""The clinical scenarios of the survival analysis: the subgroups whose curves stage 5 draws and whose risk factors stage 6
|
||||
lists. Each is a set of conditions over the cohort's raw columns (age, stage, molecular subtype, surgery); the columns are
|
||||
found by keyword, so a cohort without one of them has no patient in the scenarios that need it. Ported from
|
||||
`escenarios_clinicos.py`.
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
|
||||
def find_col(df: pd.DataFrame, keywords) -> str | None:
|
||||
for col in df.columns:
|
||||
d = col.lower().replace("_", " ")
|
||||
if any(k in d for k in keywords):
|
||||
return col
|
||||
return None
|
||||
|
||||
|
||||
def _age(v) -> float:
|
||||
m = re.search(r"\d+", str(v))
|
||||
return float(m.group()) if m else np.nan
|
||||
|
||||
|
||||
def _stage(v) -> float:
|
||||
u = str(v).upper().replace("STAGE", "").strip()
|
||||
if u.startswith("0") or u == "IS":
|
||||
return 0
|
||||
for prefix, value in [("IV", 4), ("4", 4), ("III", 3), ("3", 3), ("II", 2), ("2", 2), ("I", 1), ("1", 1)]:
|
||||
if u.startswith(prefix):
|
||||
return value
|
||||
return np.nan
|
||||
|
||||
|
||||
def _age_column(df: pd.DataFrame) -> str | None:
|
||||
candidates = [c for c in df.columns if re.match(r"^age(\b|$)", c.lower().replace("_", " ").strip())]
|
||||
if not candidates:
|
||||
return None
|
||||
return sorted(candidates, key=lambda c: (0 if "recode" in c.lower() else 1 if c.lower() == "age" else 2))[0]
|
||||
|
||||
|
||||
def values_by_axis(df: pd.DataFrame) -> dict[str, pd.Series]:
|
||||
col_stage = "Estadio_cat" if "Estadio_cat" in df.columns else find_col(df, ["estadio", "stage"])
|
||||
col_subtype = "Subtipo_molecular_cat" if "Subtipo_molecular_cat" in df.columns else find_col(df, ["subtipo", "subtype"])
|
||||
col_surgery = "Tratamiento_quirurgico_cat" if "Tratamiento_quirurgico_cat" in df.columns else find_col(df, ["quirurg", "surg"])
|
||||
col_age = _age_column(df)
|
||||
n = len(df)
|
||||
return {
|
||||
"edad": df[col_age].map(_age).astype(float) if col_age else pd.Series(np.nan, index=df.index),
|
||||
"estadio": df[col_stage].map(_stage) if col_stage else pd.Series(np.nan, index=df.index),
|
||||
"subtipo": df[col_subtype].astype(str) if col_subtype else pd.Series([""] * n, index=df.index),
|
||||
"cirugia": df[col_surgery].astype(str).str.lower() if col_surgery else pd.Series([""] * n, index=df.index),
|
||||
}
|
||||
|
||||
|
||||
AGE_BELOW = lambda x: ("edad", "<", x)
|
||||
AGE_FROM = lambda x: ("edad", ">=", x)
|
||||
STAGE_0_II = ("estadio", "en", [0, 1, 2])
|
||||
STAGE_III_IV = ("estadio", "en", [3, 4])
|
||||
HER2_POS = ("subtipo", "contiene", "HER2+")
|
||||
HER2_NEG = ("subtipo", "contiene", "HER2-")
|
||||
TRIPLE_NEG = ("subtipo", "contiene", "HR-/HER2-")
|
||||
CONSERVATIVE = ("cirugia", "contiene", "conserv")
|
||||
|
||||
SCENARIOS = {
|
||||
"HER2+ · ≥60 años · estadio III–IV (Alto)": [HER2_POS, AGE_FROM(60), STAGE_III_IV],
|
||||
"HER2+ · <60 años · estadio 0–II (Bajo)": [HER2_POS, AGE_BELOW(60), STAGE_0_II],
|
||||
"Estadio IV": [("estadio", "en", [4])],
|
||||
"Estadio I": [("estadio", "en", [1])],
|
||||
"≥ 75 años": [AGE_FROM(75)],
|
||||
"< 45 años": [AGE_BELOW(45)],
|
||||
"Jóvenes (<45) · HER2− · estadio 0–II · cirugía conservadora": [AGE_BELOW(45), HER2_NEG, STAGE_0_II, CONSERVATIVE],
|
||||
"HER2− · estadio 0–II · cirugía conservadora": [HER2_NEG, STAGE_0_II, CONSERVATIVE],
|
||||
"HER2+ · estadio 0–II · cirugía conservadora": [HER2_POS, STAGE_0_II, CONSERVATIVE],
|
||||
"Jóvenes (<45) · estadio 0–II": [AGE_BELOW(45), STAGE_0_II],
|
||||
"Jóvenes (<45) · HER2−": [AGE_BELOW(45), HER2_NEG],
|
||||
"Triple negativo (HR−/HER2−) · estadio 0–II": [TRIPLE_NEG, STAGE_0_II],
|
||||
"≥ 65 años · HER2− · estadio 0–II · cirugía conservadora": [AGE_FROM(65), HER2_NEG, STAGE_0_II, CONSERVATIVE],
|
||||
}
|
||||
|
||||
STAGE_LABEL = {0: "0", 1: "I", 2: "II", 3: "III", 4: "IV"}
|
||||
|
||||
|
||||
def describe(conditions) -> str:
|
||||
parts = []
|
||||
for axis, op, value in conditions:
|
||||
if axis == "edad":
|
||||
parts.append(f"edad {op} {value:g}")
|
||||
elif axis == "estadio":
|
||||
parts.append("estadio " + "/".join(STAGE_LABEL[v] for v in value))
|
||||
elif axis == "subtipo":
|
||||
parts.append(f"subtipo {value}")
|
||||
elif axis == "cirugia":
|
||||
parts.append("cirugía conservadora")
|
||||
return "; ".join(parts)
|
||||
|
||||
|
||||
def masks(df: pd.DataFrame) -> dict[str, np.ndarray]:
|
||||
"""Each scenario's mask over the cohort: every condition must hold."""
|
||||
values = values_by_axis(df)
|
||||
out = {}
|
||||
for name, conditions in SCENARIOS.items():
|
||||
mask = pd.Series(True, index=df.index)
|
||||
for axis, op, value in conditions:
|
||||
s = values[axis]
|
||||
if op == "<":
|
||||
mask &= (s < value).fillna(False)
|
||||
elif op == ">=":
|
||||
mask &= (s >= value).fillna(False)
|
||||
elif op == "en":
|
||||
mask &= s.isin(value)
|
||||
else:
|
||||
mask &= s.str.contains(value, regex=False)
|
||||
out[name] = mask.values.astype(bool)
|
||||
return out
|
||||
@@ -148,7 +148,6 @@ class SurvivalSettings:
|
||||
ks_sub_max_seconds: int
|
||||
xlim_sub: tuple[float, ...]
|
||||
ylim_sub: dict
|
||||
subgroups: tuple[dict, ...]
|
||||
|
||||
@property
|
||||
def file_suffix(self) -> str:
|
||||
@@ -212,6 +211,5 @@ def load(path: Path = TOML) -> Settings:
|
||||
categorization=_group(CategorizationSettings, raw["categorization"]),
|
||||
bootstrap=_group(BootstrapSettings, raw["bootstrap"]),
|
||||
modeling=_group(ModelingSettings, raw["modeling"]),
|
||||
survival=_group(SurvivalSettings, {**raw["survival"],
|
||||
"subgroups": tuple(raw["survival"]["subgroups"])}),
|
||||
survival=_group(SurvivalSettings, raw["survival"]),
|
||||
risk_factors=_group(RiskFactorSettings, raw["risk_factors"]))
|
||||
|
||||
@@ -16,6 +16,7 @@ from matplotlib.figure import Figure
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
|
||||
from models.cama.seer_survival import fractional_weibull as fw
|
||||
from models.cama.seer_survival import scenarios
|
||||
from models.cama.seer_survival import survival_models as sm
|
||||
from models.cama.seer_survival.settings import SurvivalSettings
|
||||
|
||||
@@ -322,50 +323,9 @@ def sv_main_figure(sv_frame: SurvivalFrame, sv_km: KaplanMeier, sv_adjusted: np.
|
||||
|
||||
# ---------------------------------------------------------------- subgroups
|
||||
|
||||
def _stage(v):
|
||||
u = str(v).upper().replace("STAGE", "").strip()
|
||||
if u.startswith("0") or u == "IS":
|
||||
return 0
|
||||
for prefix, val in [("IV", 4), ("4", 4), ("III", 3), ("3", 3), ("II", 2), ("2", 2), ("I", 1), ("1", 1)]:
|
||||
if u.startswith(prefix):
|
||||
return val
|
||||
return np.nan
|
||||
|
||||
|
||||
def sv_masks(sv_frame: SurvivalFrame, survival: SurvivalSettings) -> dict[str, np.ndarray]:
|
||||
"""Each subgroup's mask over the cohort: every condition of its spec must hold."""
|
||||
df = sv_frame.df
|
||||
n = len(df)
|
||||
col_stage = "Estadio_cat" if "Estadio_cat" in df.columns else _find_col(df, ["estadio", "stage"])
|
||||
col_sub = "Subtipo_molecular_cat" if "Subtipo_molecular_cat" in df.columns else _find_col(df, ["subtipo", "subtype"])
|
||||
col_surg = "Tratamiento_quirurgico_cat" if "Tratamiento_quirurgico_cat" in df.columns else _find_col(df, ["quirurg", "surg"])
|
||||
age = df["_edad"].values.astype(float)
|
||||
stage = (df[col_stage].map(_stage) if col_stage else pd.Series(np.nan, index=df.index)).values.astype(float)
|
||||
sub = df[col_sub].astype(str) if col_sub else None
|
||||
flags = {"her2neg": sub.str.contains("HER2-", regex=False).values if sub is not None else np.zeros(n, bool),
|
||||
"triple_negative": sub.str.contains("HR-/HER2-", regex=False).values if sub is not None else np.zeros(n, bool),
|
||||
"her2pos": sub.str.contains("HER2+", regex=False).values if sub is not None else np.zeros(n, bool),
|
||||
"conservative": (df[col_surg].astype(str).str.lower().str.contains("conserv").values
|
||||
if col_surg else np.zeros(n, bool))}
|
||||
masks = {}
|
||||
for spec in survival.subgroups:
|
||||
mask = np.ones(n, bool)
|
||||
if spec.get("her2") == "pos":
|
||||
mask &= flags["her2pos"]
|
||||
if spec.get("her2") == "neg":
|
||||
mask &= flags["her2neg"]
|
||||
if spec.get("triple_negative"):
|
||||
mask &= flags["triple_negative"]
|
||||
if spec.get("conservative"):
|
||||
mask &= flags["conservative"]
|
||||
if "age_min" in spec:
|
||||
mask &= age >= spec["age_min"]
|
||||
if "age_max" in spec:
|
||||
mask &= age < spec["age_max"]
|
||||
if "stages" in spec:
|
||||
mask &= np.isin(stage, spec["stages"])
|
||||
masks[spec["name"]] = mask
|
||||
return masks
|
||||
"""Each clinical scenario's mask over the cohort (`scenarios.masks`): every condition of the scenario must hold."""
|
||||
return scenarios.masks(sv_frame.df)
|
||||
|
||||
|
||||
def sv_sub_weights(sv_cohort: sm.Cohort, sv_masks: dict, sv_oof: Oof | None,
|
||||
|
||||
@@ -24,6 +24,7 @@ TABLES = {
|
||||
"metricas_diferenciacion.csv": "metricas_diferenciacion", "auc_validacion_interna.csv": "auc_validacion_interna",
|
||||
"seleccion_bootstrap.csv": "seleccion_bootstrap", "auc_bootstrap.csv": "auc_bootstrap",
|
||||
"factores_riesgo.csv": "factores_riesgo", "factores_riesgo_resumen_variables.csv": "factores_riesgo_variables",
|
||||
"escenarios_resumen.csv": "escenarios_resumen", "escenarios_factores_riesgo.csv": "escenarios_factores_riesgo",
|
||||
"subgrupos_KM_Weibull_fraccional.csv": "subgrupos_weibull", "subgrupos_puntos_LR_HBN.csv": "subgrupos_puntos",
|
||||
"prueba_edad_resumen.csv": "prueba_edad", "comparacion_cortes_edad.csv": "cortes_edad",
|
||||
"comparacion_cortes_tumor.csv": "cortes_tumor", "pesos_combinacion_cohorte.csv": "pesos_combinacion",
|
||||
|
||||
@@ -44,21 +44,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 options(labelled: pd.DataFrame, pac_id: int | None = None) -> dict:
|
||||
"""What a reader can select: each covariate's values with their member counts, the period of the index dates and the
|
||||
smallest selection that can be answered; and, given a patient, her own value of each covariate."""
|
||||
values = {name: [{"valor": str(v), "n": int(n)} for v, n in labelled[name].fillna("NA").value_counts().sort_index().items()]
|
||||
for name in FEATURES}
|
||||
dates = pd.to_datetime(labelled["fecha_indice"])
|
||||
found = {"n": int(len(labelled)), "events": int(labelled["event"].sum()), "covariables": values,
|
||||
"periodo": {"desde": dates.min().date().isoformat(), "hasta": dates.max().date().isoformat()},
|
||||
"limites": {"miembros_min": MIN_MEMBERS, "muertes_min": MIN_EVENTS}}
|
||||
if pac_id is not None:
|
||||
mine = labelled[labelled["pac_id"] == pac_id]
|
||||
found["paciente"] = {name: str(mine.iloc[0][name]) if len(mine) and pd.notna(mine.iloc[0][name]) else "NA" for name in FEATURES} if len(mine) else None
|
||||
return found
|
||||
|
||||
|
||||
def _selection(labelled: pd.DataFrame, filters: dict, period: dict) -> pd.DataFrame:
|
||||
keep = np.ones(len(labelled), bool)
|
||||
for name, wanted in (filters or {}).items():
|
||||
|
||||
@@ -78,7 +78,6 @@ ks_max_seconds = 120
|
||||
ks_sub_max_seconds = 180
|
||||
xlim_sub = []
|
||||
ylim_sub = {}
|
||||
subgroups = []
|
||||
|
||||
# What the dashboard's survival chart says, in the clinicians' words (provisional: to be defined with them). The record a
|
||||
# training run publishes carries these, so changing one is a setting and a new run.
|
||||
|
||||
@@ -9,6 +9,7 @@ import pytest
|
||||
|
||||
from models.cama.seer_survival import (balancing_stats, categorization_stats as cs, fractional_weibull as fw, hbn,
|
||||
lr_selection, pipeline, risk_factor_stats as rf, survival_models as sm)
|
||||
from models.cama.seer_survival import risk_factors, scenarios
|
||||
from models.cama.seer_survival.settings import load
|
||||
|
||||
|
||||
@@ -20,7 +21,7 @@ def test_every_stage_has_its_settings():
|
||||
assert "Biología + tratamiento" in {s.categorization.age_final}
|
||||
assert set(s.categorization.proposals) >= {"P1_actual", "P6_clinico_fijo", "P7_cuantiles"}
|
||||
assert s.modeling.canonical_map["Age_group"] == "Edad"
|
||||
assert len(s.survival.subgroups) == 13 and s.survival.combine_active and s.survival.months_max == 24
|
||||
assert len(scenarios.SCENARIOS) == 13 and s.survival.combine_active and s.survival.months_max == 24
|
||||
assert s.risk_factors.treatment == ("Tratamiento_quirurgico", "Radioterapia", "Quimioterapia")
|
||||
|
||||
|
||||
@@ -264,3 +265,37 @@ def test_treatment_associations_are_none_when_no_treatment_variable_varies():
|
||||
follow = risk_factors.FollowUp(death=pd.Series(rng.integers(0, 2, n)), months=pd.Series(rng.uniform(1, 20, n)),
|
||||
event=pd.Series(rng.integers(0, 2, n)))
|
||||
assert risk_factors.risk_treatment_associations(data, follow, ["Grado"], ["Radioterapia"], load().risk_factors) is None
|
||||
|
||||
|
||||
def test_a_scenario_holds_the_patients_who_meet_every_condition_and_none_without_the_column():
|
||||
"""Pins down: a scenario's mask is the patients who meet all its conditions over the raw columns (age from the age column,
|
||||
stage, subtype and surgery by keyword), and a cohort without a column has nobody in the scenarios that need it. Fails if
|
||||
a condition is dropped, an age edge moves, or a missing column makes a scenario include everyone."""
|
||||
raw = pd.DataFrame({"Age recode": ["30-34 years", "60-64 years", "75-79 years", "60-64 years"],
|
||||
"Stage": ["IIA", "IIIB", "IV", "I"], "Subtype (HER2+)": ["HER2+", "HER2+", "HER2-", "HER2+"]})
|
||||
found = scenarios.masks(raw)
|
||||
|
||||
assert found["< 45 años"].tolist() == [True, False, False, False]
|
||||
assert found["≥ 75 años"].tolist() == [False, False, True, False]
|
||||
assert found["Estadio IV"].tolist() == [False, False, True, False]
|
||||
assert found["HER2+ · ≥60 años · estadio III–IV (Alto)"].tolist() == [False, True, False, False]
|
||||
assert not found["HER2− · estadio 0–II · cirugía conservadora"].any() # no surgery column: nobody
|
||||
assert not scenarios.masks(raw[["Age recode"]])["Estadio I"].any() # no stage column: nobody
|
||||
|
||||
|
||||
def test_the_risk_factors_of_a_scenario_are_the_classified_categories_most_of_it_shares():
|
||||
"""Pins down: a classified risk factor that nearly all of a scenario has is listed as defining it, a protector that most
|
||||
has as most of it, and one that few have is left out. Fails if the shares are taken over the cohort instead of the
|
||||
scenario, or a category under the presence floor is listed."""
|
||||
table = pd.DataFrame({"variable": ["Grado", "Grado", "Subtipo"], "categoria": ["G3", "G1", "A"], "clasificacion": ["riesgo robusto", "protector sugerente", "riesgo robusto"],
|
||||
"OR_muerte": [2.0, 0.5, 3.0], "IC95_inf": [1.2, 0.3, 1.1], "IC95_sup": [3.0, 0.9, 5.0], "delta_S18": [-0.1, 0.05, -0.2]})
|
||||
data = pd.DataFrame({"Grado": ["G3"] * 10 + ["G1"] * 6 + ["G3"] * 4, "Subtipo": ["A"] * 1 + ["B"] * 19})
|
||||
mask = np.array([True] * 10 + [False] * 10) # the scenario: the first ten, all grade 3 and one of subtype A
|
||||
classification = risk_factors.Classification(table, ["c1"])
|
||||
|
||||
found = risk_factors.risk_scenario_factors(classification, None, data, {"Grado 3": mask})
|
||||
|
||||
row = found.summary.iloc[0]
|
||||
assert "Grado=G3" in row["riesgo_definitorios"] and row["n_factores_riesgo_incluidos"] == 1
|
||||
assert set(found.details["variable"]) == {"Grado", "Subtipo"} # subtype A is 10 % of the scenario: present
|
||||
assert found.details[found.details["categoria"] == "G1"].empty # no scenario member has G1
|
||||
|
||||
@@ -440,21 +440,6 @@ def test_the_live_figure_scores_the_selected_members_with_the_production_model(m
|
||||
assert len(grade3["km_adjusted"]["S"]) == grade3["months_max"] + 1 and len(grade3["weibull_fractional"]["S"]) == len(grade3["weibull"]["S"])
|
||||
|
||||
|
||||
def test_the_live_options_list_the_values_the_limits_and_the_patients_own(members_frame):
|
||||
"""Pins down: the options carry every covariate's values with their member counts, the period of the index dates, the
|
||||
smallest selection that can be answered and, for a patient, her value of each covariate. Fails if a covariate is missing
|
||||
or her values are not hers."""
|
||||
from models.cama.survival import live
|
||||
|
||||
first = int(members_frame["pac_id"].iloc[0])
|
||||
found = live.options(members_frame, first)
|
||||
|
||||
assert set(found["covariables"]) == set(FEATURES)
|
||||
assert sum(v["n"] for v in found["covariables"]["grade"]) == len(members_frame)
|
||||
assert found["paciente"]["grade"] == str(members_frame["grade"].iloc[0])
|
||||
assert live.options(members_frame, 10**9)["paciente"] is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("query", [
|
||||
{"filtros": {"nope": ["x"]}},
|
||||
{"filtros": {"grade": ["G1"], "er": ["NEGATIVO"], "her2": ["H3"]}},
|
||||
|
||||
Reference in New Issue
Block a user