CaMa survival: the live figure is the clinical scenario's, over the production model and the live cohort

This commit is contained in:
rockdrigo
2026-11-21 13:14:06 -06:00
parent b1006a97d7
commit e99eb499d6
2 changed files with 116 additions and 62 deletions
+56 -21
View File
@@ -422,36 +422,71 @@ def production_model(members_frame):
members_frame[FEATURES], members_frame[["months", "event"]])
def test_the_live_figure_scores_the_selected_members_with_the_production_model(members_frame, production_model):
"""Pins down: the record is for the selected members, its points are the model's mean survival for them at the model's
horizons with an interval around it, and nothing is refitted (the same selection twice gives the same record). Fails if
a filter is ignored, or the selection changes the model's horizons."""
def test_the_live_figure_scores_a_scenarios_members_with_the_production_model(members_frame, production_model, monkeypatch):
"""Pins down: the record of a scenario is for its members only (their count and deaths), its points are the model's mean
survival for them at the model's horizons with an interval around it, and nothing is refitted (the same scenario twice gives
the same record). Fails if the scenario's mask is ignored, or the scenario changes the model's horizons."""
from models.cama.survival import live
everyone = live.curves(SCENARIO, production_model, members_frame, {})
grade3 = live.curves(SCENARIO, production_model, members_frame, {"filtros": {"grade": ["G3"]}})
again = live.curves(SCENARIO, production_model, members_frame, {"filtros": {"grade": ["G3"]}})
young = np.arange(len(members_frame)) < 120
monkeypatch.setattr(live, "scenario_masks", lambda labelled: {"Primeras 120": young})
assert everyone["n"] == len(members_frame) and everyone["horizons_months"] == [6, 12, 18]
assert 0 < grade3["n"] < everyone["n"] and grade3["points"] == again["points"]
comb = grade3["points"]["COMB"]
everyone = live.curves(SCENARIO, production_model, members_frame, None)
first = live.curves(SCENARIO, production_model, members_frame, "Primeras 120")
again = live.curves(SCENARIO, production_model, members_frame, "Primeras 120")
assert everyone["n"] == len(members_frame) and everyone["escenario"] == "Toda la cohorte" and everyone["horizons_months"] == [6, 12, 18]
assert first["n"] == 120 and first["escenario"] == "Primeras 120" and first["points"] == again["points"]
comb = first["points"]["COMB"]
assert all(lo <= s <= hi for lo, s, hi in zip(comb["low"], comb["S"], comb["high"]))
assert comb["S"][0] < everyone["points"]["COMB"]["S"][0] # grade 3 does worse than everyone
assert len(grade3["km_adjusted"]["S"]) == grade3["months_max"] + 1 and len(grade3["weibull_fractional"]["S"]) == len(grade3["weibull"]["S"])
assert len(first["km_adjusted"]["S"]) == first["months_max"] + 1 and len(first["weibull_fractional"]["S"]) == len(first["weibull"]["S"])
@pytest.mark.parametrize("query", [
{"filtros": {"nope": ["x"]}},
{"filtros": {"grade": ["G1"], "er": ["NEGATIVO"], "her2": ["H3"]}},
{"periodo": {"desde": "no es fecha"}},
])
def test_a_selection_that_cannot_be_answered_says_why(members_frame, production_model, query):
"""Pins down: an unknown filter, a selection too small to say anything and an invalid date are each a `QueryError` with
a message. Fails if any of them runs and draws a meaningless figure or fails with an unreadable error."""
def test_a_patient_sees_the_scenarios_she_belongs_to_or_the_whole_cohort(members_frame, monkeypatch):
"""Pins down: a patient's scenarios are those whose mask holds her and that have enough members to draw; in none, the whole
cohort; and a patient outside the cohort is refused. Fails if a scenario too small to draw is offered, or a patient in no
scenario is left with nothing."""
from models.cama.survival import live
first, last = int(members_frame["pac_id"].iloc[0]), int(members_frame["pac_id"].iloc[-1])
inside = np.arange(len(members_frame)) < 100
tiny = np.arange(len(members_frame)) < 3
monkeypatch.setattr(live, "scenario_masks", lambda labelled: {"Grande": inside, "Diminuto": tiny})
assert live.patient_scenarios(members_frame, first) == ["Grande"] # in both; the tiny one has too few to draw
assert live.patient_scenarios(members_frame, last) == ["Toda la cohorte"] # in neither
with pytest.raises(live.QueryError):
live.patient_scenarios(members_frame, 10**9)
def test_the_scenarios_use_the_hospitals_age_and_subtype_and_none_that_needs_a_stage(members_frame):
"""Pins down: the scenario masks use the age in years and a subtype derived from the receptors (hormone receptors and
HER2 3+ / 0-1+), and a scenario that needs the stage or the surgery, which the hospital does not report, has no member.
Fails if a stage scenario includes everyone, or the subtype ignores the receptors."""
from models.cama.seer_survival import scenarios
from models.cama.survival import live
n = len(members_frame)
frame = members_frame.assign(er=np.resize(["POSITIVO", "NEGATIVO", "NEGATIVO", "POSITIVO"], n),
pr=np.resize(["POSITIVO", "NEGATIVO", "NEGATIVO", "NEGATIVO"], n),
her2=np.resize(["H1", "H3", "H0", "H2"], n))
found = live.molecular_subtype(frame).iloc[:4].tolist()
masks = live.scenario_masks(frame)
assert found == ["HR+/HER2-", "HR-/HER2+", "HR-/HER2-", "Desconocido"] # HER2 2+ is equivocal: unknown
assert set(masks) == set(scenarios.SCENARIOS)
assert not masks["Estadio IV"].any() and not masks["Triple negativo (HR−/HER2−) · estadio 0–II"].any()
@pytest.mark.parametrize("name", ["No existe", "Estadio IV"])
def test_a_scenario_that_cannot_be_answered_says_why(members_frame, production_model, name):
"""Pins down: an unknown scenario and one with too few members to say anything (every stage scenario, with the stage not
reported) are each a `QueryError` with a message. Fails if either runs and draws a meaningless figure or fails with an
unreadable error."""
from models.cama.survival import live
with pytest.raises(live.QueryError):
live.curves(SCENARIO, production_model, members_frame, query)
live.curves(SCENARIO, production_model, members_frame, name)
def test_the_monthly_curve_passes_through_the_horizons_and_never_rises():