CaMa survival: lesion-size feature and the SEER development stages published with each version

This commit is contained in:
rockdrigo
2026-11-21 03:28:13 -06:00
parent 67787adfd4
commit 9cccec5274
8 changed files with 225 additions and 25 deletions
+14
View File
@@ -250,3 +250,17 @@ def test_the_runner_names_the_missing_inputs_and_logs_each_stage(tmp_path, monke
log = pipeline.run_pipeline(tmp_path, settings=object())
assert [row[:2] for row in log] == [("99", "saltada"), ("98", "ok")] # 99's output is current; 98 has none to check
assert (tmp_path / pipeline.LOG).read_text().splitlines()[0] == "etapa,estado,segundos"
def test_treatment_associations_are_none_when_no_treatment_variable_varies():
"""Pins down: a cohort where every treatment column is a single category (as when the hospital reports none) gives
no associations, as the docstring says, and not a missing-columns error. Fails if the empty case is formatted."""
from models.cama.seer_survival import risk_factors
from models.cama.seer_survival.settings import load
rng = np.random.default_rng(8)
n = 300
data = pd.DataFrame({"Grado": rng.choice(["G1", "G3"], n), "Radioterapia": "Desconocido"})
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
+56 -8
View File
@@ -41,7 +41,7 @@ def _row(pac_id, when, tipo, valor=None, numero=None, source="biopsiamama", sour
"fuente_id": source_id or f"{pac_id}-{tipo}"}
def _report(pac_id, index, grade="G2", er="POSITIVO", her2="H1", ki67=18.0, first=None):
def _report(pac_id, index, grade="G2", er="POSITIVO", her2="H1", ki67=18.0, first=None, size=30.0):
"""The invasive biopsy report of `pac_id` on `index`, with its results."""
key = f"B{pac_id}"
rows = [_row(pac_id, index, "biopsia", "CARCINOMA_INVASOR", source_id=key, first=first),
@@ -50,7 +50,8 @@ def _report(pac_id, index, grade="G2", er="POSITIVO", her2="H1", ki67=18.0, firs
_row(pac_id, index, "receptor_estrogeno", er, source_id=key, first=first),
_row(pac_id, index, "receptor_progesterona", er, source_id=key, first=first),
_row(pac_id, index, "her2", her2, source_id=key, first=first),
_row(pac_id, index, "ki67_pct", numero=ki67, source_id=key, first=first)]
_row(pac_id, index, "ki67_pct", numero=ki67, source_id=key, first=first),
_row(pac_id, index, "tamano_tumor_mm", numero=size, source_id=key, first=first)]
return rows
@@ -122,12 +123,12 @@ def test_covariates_are_the_index_reports_results(cohort_frame):
later = pd.DataFrame([_row(1, date(2025, 12, 1), "grado_nottingham", "G1" if one[one["tipo"] == "grado_nottingham"][
"valor_codigo"].iloc[0] != "G1" else "G3", first=one["fecha_indice"].iloc[0])], columns=SCHEMA.names)
table = estimator.member_table(_indexed(pd.concat([one, later])), CONFIG["age_cuts"], CONFIG["ki67_cuts"],
CONFIG["result_days"])
CONFIG["result_days"], CONFIG["size_cuts"])
row = table.loc[1]
reported = one[one["tipo"] == "grado_nottingham"]["valor_codigo"].iloc[0]
assert (row["histologic_type"], row["grade"], row["her2"], row["ki67_group"]) == (
"DUCTAL_INFILTRANTE", reported, "H1", "14-19")
assert (row["histologic_type"], row["grade"], row["her2"], row["ki67_group"], row["size_group"]) == (
"DUCTAL_INFILTRANTE", reported, "H1", "14-19", "20-49")
assert row["er"] == one[one["tipo"] == "receptor_estrogeno"]["valor_codigo"].iloc[0] == row["pr"]
born, index = date(1960, 1, 1) + timedelta(days=30), table.loc[1, "fecha_indice"].date()
age = (index - born).days / 365.25
@@ -155,7 +156,7 @@ def labelled(cohort_frame):
"""The 240 indexed members with their covariates and outcome, as the dataflow labels them."""
indexed = _indexed(cohort_frame)
indexed = indexed[indexed["pac_id"] <= N]
features = estimator.member_table(indexed, CONFIG["age_cuts"], CONFIG["ki67_cuts"], CONFIG["result_days"])
features = estimator.member_table(indexed, CONFIG["age_cuts"], CONFIG["ki67_cuts"], CONFIG["result_days"], CONFIG["size_cuts"])
return features.join(estimator.outcome_table(indexed, CUTOFF, 24)).reset_index()
@@ -198,7 +199,7 @@ def test_the_pipeline_takes_the_total_cohort_and_scores_only_who_the_index_leave
fitted = IntervalSurvival(CONFIG["survival"], tuple(CONFIG["horizons_years"])).fit(labelled[FEATURES],
labelled[["months", "event"]])
pipeline = Pipeline([("members", MemberFeatures(dict(CONFIG["index"]), WINDOW, tuple(CONFIG["age_cuts"]),
tuple(CONFIG["ki67_cuts"]), CONFIG["result_days"])),
tuple(CONFIG["ki67_cuts"]), CONFIG["result_days"], tuple(CONFIG["size_cuts"]))),
("survival", fitted)])
scored = pipeline.predict_proba(cohort_frame)
@@ -249,7 +250,7 @@ def population_record(cohort_frame):
"""The `curvas` record the dataflow publishes for the 240 indexed members, with a small bootstrap to stay quick."""
config = {**CONFIG, "survival": {**CONFIG["survival"], "n_boot": 20, "ks_max_seconds": 5}}
dr = dataflow(*SCENARIO.modules, config=config)
return dr.execute(["population"], inputs={"source_cohort": cohort_frame, "cohort_lineage": LINEAGE})["population"]["curvas"]
return dr.execute(["population_curves"], inputs={"source_cohort": cohort_frame, "cohort_lineage": LINEAGE})["population_curves"]["curvas"]
def test_the_population_record_has_the_figures_curves_points_and_labels(population_record):
@@ -285,3 +286,50 @@ def test_a_version_publishes_its_population_record(cohort_file, mlflow_tracking)
record = json.loads(content)
assert "analisis/curvas.json" in files and name == "curvas.json"
assert record["horizons_months"] == [6, 12, 18] and set(record["points"]) == {"LR", "HBN", "COMB"}
@pytest.fixture(scope="module")
def development_record(cohort_frame):
"""The `desarrollo` record the dataflow publishes for the 240 indexed members, with the smallest budget."""
config = {**CONFIG, "desarrollo": {**CONFIG["desarrollo"], "null_perm": 5, "n_bootstrap": 4, "bootstrap_max_seconds": 30,
"proposals_max_seconds": 20, "restarts": 1}}
dr = dataflow(*SCENARIO.modules, config=config)
return dr.execute(["development"], inputs={"source_cohort": cohort_frame, "cohort_lineage": LINEAGE})["development"]["desarrollo"]
def test_a_stage_that_cannot_run_on_the_cohort_is_recorded_and_does_not_stop_the_others(development_record):
"""Pins down: on a cohort whose covariates barely vary (the 240 members here) the SEER stages that need variation
publish their error in the record and the run still produces it, with every stage listed. Fails if one stage's
exception escapes the node, which would stop a version from training."""
assert [e["etapa"] for e in development_record["etapas"]] == ["01", "02", "03", "04", "05", "06"]
assert set(development_record["errores"]) <= {"01", "02", "03", "04", "05", "06"}
assert "Estadio_cat" in development_record["variables_no_disponibles"]
def test_the_development_stages_publish_their_tables_and_figures_on_a_varied_cohort():
"""Pins down: on 600 members with varied covariates all six SEER stages run and publish their tables and figures.
Fails if a stage errors on a cohort of this shape or stops writing what the dashboard reads."""
from models.cama.survival import development as dev
rng = np.random.default_rng(11)
n = 600
grade = rng.choice(["G1", "G2", "G3"], n, p=[0.2, 0.5, 0.3])
er = rng.choice(["POSITIVO", "NEGATIVO"], n, p=[0.7, 0.3])
risk = 0.03 * np.exp(1.0 * (grade == "G3") - 0.6 * (er == "POSITIVO"))
months = np.minimum(rng.exponential(1 / risk), 30).round()
members = pd.DataFrame({
"fecha_indice": pd.to_datetime("2024-01-01") + pd.to_timedelta(rng.integers(0, 540, n), unit="D"),
"months": months.astype(int), "event": rng.random(n) < 1 - np.exp(-risk * 24),
"age_years": rng.normal(58, 12, n).clip(25, 90), "size_mm": rng.integers(5, 70, n).astype(float),
"histologic_type": rng.choice(["8500/3", "8520/3"], n, p=[0.85, 0.15]), "grade": grade, "er": er,
"pr": rng.choice(["POSITIVO", "NEGATIVO"], n), "her2": rng.choice(["H0", "H1", "H2", "H3"], n),
"ki67_group": rng.choice(["<14", "14-19", "≥20"], n)})
members["months"] = np.where(members["event"], np.minimum(members["months"], 23), 24)
settings = {**CONFIG["desarrollo"], "null_perm": 5, "n_bootstrap": 4, "bootstrap_max_seconds": 30,
"proposals_max_seconds": 20, "restarts": 1}
r = dev.development(members, settings)["desarrollo"]
assert r["errores"] == {}, r["errores"]
assert {"or_lr_balanceada", "hbn_arcos", "subgrupos_weibull", "prueba_edad"} <= set(r["tablas"])
assert r["figuras"] and all(isinstance(v, str) for v in r["figuras"].values())