Files
ISSSTELEON/tests/test_cama_recurrence_site.py
T
Roberto Treviño 50289a5b36
ci / python (push) Failing after 1h8m14s
ci / web (push) Failing after 3m53s
Training takes every model; recurrence is skipped when too few recurred
2026-11-29 21:12:38 -06:00

121 lines
6.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""CaMa recurrence on the site's own patients (models.cama.recurrence.site): the cohort table
from the timelines (time, event, St. Gallen subtype), and a roundtrip: a seeded cohort whose
recurrences grow with the positive nodes gives a model whose risk grows with them too."""
import os
from datetime import date
import numpy as np
import pandas as pd
import pytest
from models.cama import recurrence
from models.cama.jobs import JOBS
from models.cama.recurrence import calculator, reports, site
from models.cama.recurrence.cohorts import UNKNOWN
from models.cama.specs import MODELS
from models.jobs import EmptyCohort
def test_the_st_gallen_surrogate_names_the_subtype_as_scan_b():
assert site.subtype("positive", "positive", "negative", 10.0) == "Luminal A"
assert site.subtype("positive", "negative", "negative", 30.0) == "Luminal B HER2-"
assert site.subtype("negative", "positive", "positive", None) == "Luminal B HER2+"
assert site.subtype("negative", "negative", "positive", None) == "Non-luminal HER2+"
assert site.subtype("negative", "negative", "negative", None) == "Basal-like"
assert site.subtype("positive", None, "negative", None) == UNKNOWN # Ki-67 decides
assert site.subtype("negative", None, "negative", 5.0) == UNKNOWN # PR unknown
assert site.subtype("positive", "positive", None, 5.0) == UNKNOWN # HER2 unknown
def timeline(person: str, index: date, nodes: int, recurred_after: int | None,
followed: int, rng) -> list[dict]: # fmt: skip
"""One patient's events: birth, her index biopsy's results, a mastectomy, a recurrence
`recurred_after` days after the index (or none), and a last visit `followed` days on."""
day = pd.Timestamp(index)
birth = day - pd.Timedelta(days=int(rng.uniform(35, 80) * 365.25))
ki67 = float(rng.choice([8.0, 35.0]))
rows = [("birth", birth, None, None), ("biopsy", day, "invasive", None),
("er", day, "positive", None), ("pr", day, "positive", None),
("her2", day, "negative", None), ("grade", day, str(rng.integers(1, 4)), None),
("ki67_pct", day, None, ki67), ("size_mm", day, None, float(rng.uniform(5, 60))),
("positive_nodes", day, None, float(nodes)), ("stage", day, "II", None),
("treatment", day + pd.Timedelta(days=30), "mastectomy", None),
("note", day + pd.Timedelta(days=followed), "C50", None)] # fmt: skip
if recurred_after is not None:
rows.append(("recurrence", day + pd.Timedelta(days=recurred_after), "distant", None))
return [{"person_id": person, "date": d, "type": t, "value_code": c, "value_num": v,
"source_id": f"{person}-{t}", "index_date": day} for t, d, c, v in rows] # fmt: skip
def cohort(n: int = 600, seed: int = 7) -> pd.DataFrame:
rng = np.random.default_rng(seed)
events = []
for k in range(n):
nodes = int(rng.choice([0, 2, 6], p=[0.5, 0.3, 0.2]))
yearly = {0: 0.04, 2: 0.10, 6: 0.25}[nodes] # the planted effect
followed = int(rng.uniform(4, 8) * 365)
when = int(rng.exponential(365 / yearly))
start = date(2018, 1, 1) + pd.Timedelta(days=int(rng.integers(0, 700)))
recurred = when if when < followed else None
events += timeline(f"p{k:04d}", start, nodes, recurred, followed, rng)
return pd.DataFrame(events)
def test_the_cohort_table_has_each_patients_time_event_and_covariates():
events = pd.DataFrame(
timeline("a", date(2020, 1, 1), 2, 400, 1000, np.random.default_rng(1))
+ timeline("b", date(2020, 1, 1), 0, None, 1000, np.random.default_rng(2))
)
found = site.frame(events, date(2026, 1, 1)).set_index("paciente")
assert found.loc["a", "evento"] == 1 and round(found.loc["a", "tiempo_meses"], 1) == 13.1
assert found.loc["b", "evento"] == 0 and round(found.loc["b", "tiempo_meses"], 1) == 72.0
assert (
found.loc["a", "Ganglios_positivos"] == "1-3"
and found.loc["b", "Ganglios_positivos"] == "0"
)
assert found.loc["a", "Cirugia"] == "Mastectomy" and found.loc["a", "Quimioterapia"] == "No"
assert set(found["Subtipo_clinico"]) <= {"Luminal A", "Luminal B HER2-"}
def test_the_scenarios_find_their_patients_though_a_redundant_covariate_is_dropped():
rows = site.frame(cohort(200), date(2026, 1, 1))
prepared = site.prepare(rows)
assert prepared.eliminated # the subtype is the receptors and Ki-67 again
assert not set(prepared.eliminated) & set(prepared.covariates)
named = {v for cond in site.SCENARIOS.values() for v in cond}
assert named <= set(prepared.frame.columns)
found = calculator.masks(prepared.frame, site.SCENARIOS)
assert found["Luminal B HER2−"].sum() == (rows["Subtipo_clinico"] == "Luminal B HER2-").sum()
@pytest.mark.skipif(not os.environ.get("RECURRENCE_SLOW"), reason="RECURRENCE_SLOW unset")
def test_a_site_cohort_trains_and_its_risk_follows_the_planted_nodes():
"""Slow (about ten minutes: the calculator's resamples)."""
rows = site.frame(cohort(), date(2026, 1, 1))
model, metrics, reports = recurrence.train_site(rows, bootstrap=False)
assert reports["technical_validation"]["cohort"] == "site"
risk = model.predict(rows)["recurrence_60m"].groupby(rows["Ganglios_positivos"]).mean()
assert risk["0"] < risk["1-3"] < risk["4+"]
def test_the_report_says_the_cohort_is_the_sites_own():
prepared = site.prepare(site.frame(cohort(200), date(2026, 1, 1)))
sampling = reports.routines({"site": prepared}, {"site": 40})["MUESTREO"]
assert sampling["origen"] == "la sede (sus propias pacientes)"
assert sampling["cohortes"]["site"]["pacientes"] == 200
def test_a_cohort_with_too_few_recurrences_is_left_untrained():
events = cohort(120)
few = events[(events["type"] != "recurrence") | events["person_id"].isin(["p0001", "p0002"])]
assert "recurred" in site.scarce(site.frame(few, date(2026, 1, 1)))
with pytest.raises(EmptyCohort, match="cama.recurrence"):
MODELS["recurrence"].train(few, date(2026, 1, 1))
assert site.scarce(site.frame(cohort(600), date(2026, 1, 1))) is None
assert site.scarce(site.frame(few[few["type"] != "recurrence"], date(2026, 1, 1)))
def test_a_training_run_takes_every_model():
assert "recurrence" in JOBS.routine() and set(JOBS.routine()) == set(MODELS)