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:
rockdrigo
2026-11-21 13:03:19 -06:00
parent 997aebd068
commit b1006a97d7
12 changed files with 237 additions and 141 deletions
+36 -1
View File
@@ -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
-15
View File
@@ -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"]}},