From 9c7c718a7b45e0db5c19fd227d03dd9d55910b67 Mon Sep 17 00:00:00 2001 From: "luis.ramirezgrz" Date: Fri, 20 Nov 2026 13:40:06 -0600 Subject: [PATCH] Tests for the SEER survival pipeline's stages and runner --- tests/cama/test_seer_survival.py | 103 ++++++++++ tests/cama/test_seer_survival_stages.py | 252 ++++++++++++++++++++++++ 2 files changed, 355 insertions(+) create mode 100644 tests/cama/test_seer_survival.py create mode 100644 tests/cama/test_seer_survival_stages.py diff --git a/tests/cama/test_seer_survival.py b/tests/cama/test_seer_survival.py new file mode 100644 index 0000000..dfc5c2c --- /dev/null +++ b/tests/cama/test_seer_survival.py @@ -0,0 +1,103 @@ +"""The SEER survival pipeline's stages: depuration (01) and bootstrapping (03), on small synthetic frames.""" + +import dataclasses +import json + +import numpy as np +import pandas as pd +import pytest + +from models.cama.seer_survival import depuration, depuration_stats as stats, run +from models.cama.seer_survival.settings import BootstrapSettings, Settings, load + + +@pytest.fixture +def settings() -> Settings: + s = load() + return dataclasses.replace(s, depuration=dataclasses.replace(s.depuration, null_perm=5)) + + +@pytest.fixture +def recoded() -> pd.DataFrame: + """`B_cat` repeats `A_cat` under other labels; `Tumor_group` repeats `T_cat` and is the preferred of the two; `C_cat` + and `D_cat` are independent; `Outcome_cat` is never touched.""" + rng = np.random.default_rng(1) + n = 600 + a = rng.choice(list("abcd"), n) + t = rng.choice(["t1", "t2", "t3"], n) + return pd.DataFrame({ + "A_cat": a, "B_cat": pd.Series(a).map({"a": "w", "b": "x", "c": "y", "d": "z"}).values, "raw_b": a, + "T_cat": t, "Tumor_group": pd.Series(t).map({"t1": "g1", "t2": "g2", "t3": "g3"}).values, + "C_cat": rng.choice(["u", "v", "w"], n), "D_cat": rng.choice(["p", "q"], n), + "Outcome_cat": rng.choice(["0", "1"], n)}) + + +def test_the_duplicate_is_dropped_with_its_raw_column_and_the_preferred_one_is_kept(tmp_path, settings, recoded): + recoded.to_csv(tmp_path / "recoded.csv", index=False) + (tmp_path / "map.json").write_text(json.dumps({"B_cat": "raw_b"})) + + r = run.run_depuration(tmp_path / "recoded.csv", tmp_path / "map.json", tmp_path, settings, generated_at="t") + + assert sorted(r["elimination"].dropped["variable"]) == ["B_cat", "T_cat"] + assert set(r["elimination"].dropped["paso"]) == {"A duplicada"} + out = pd.read_csv(tmp_path / run.DEPURATED, dtype=str) + assert list(out.columns) == ["A_cat", "Tumor_group", "C_cat", "D_cat", "Outcome_cat"] + kept = json.loads((tmp_path / run.DEPURATION_DIR / "variables_conservadas.json").read_text()) + assert kept["crudas_eliminadas"] == ["raw_b"] + for name in ("calibracion_U_pares.csv", "calibracion_umbrales.json", "variables_eliminadas.csv"): + assert (tmp_path / run.DEPURATION_DIR / name).exists() + + +def test_the_analysis_leaves_out_excluded_and_constant_columns(settings, recoded): + recoded["K_cat"] = "same" + frame = depuration.analysis_frame(recoded, settings.depuration) + assert "Outcome_cat" not in frame and "K_cat" not in frame and "raw_b" not in frame + assert "Tumor_group" in frame + + +def test_a_protected_variable_is_never_dropped(settings, recoded): + s = dataclasses.replace(settings.depuration, protected=("B_cat",)) + frame = depuration.analysis_frame(recoded, s) + t = stats.Thresholds(s.dup_u, s.u_redund, s.gvif_drop, s.cluster_method, 0.5, 0.5, False) + dropped = stats.eliminate(frame, list(frame.columns), t, s) + assert "B_cat" not in set(dropped["variable"]) and "A_cat" in set(dropped["variable"]) + + +def test_theil_u_of_a_relabelled_copy_is_one_and_of_independent_variables_near_zero(recoded): + U = stats.theil_u_matrix(recoded, ["A_cat", "B_cat", "C_cat"]) + assert U.loc["A_cat", "B_cat"] == pytest.approx(1.0) and U.loc["B_cat", "A_cat"] == pytest.approx(1.0) + assert U.loc["A_cat", "C_cat"] < 0.05 + + +def test_auto_thresholds_take_the_calibrations_suggestions(settings, recoded): + s = dataclasses.replace(settings.depuration, thresholds_auto=True) + frame = depuration.analysis_frame(recoded, s) + c = stats.calibrate(frame, list(frame.columns), s, "t") + t = stats.thresholds_in_use(c, s) + assert t.auto and t.u_redund == c.u_suggestion["U"] and t.dup_u == c.dup_u_suggested + + +def test_calibration_needs_two_variables(settings): + frame = pd.DataFrame({"A_cat": ["a", "b"] * 50}) + with pytest.raises(ValueError, match="al menos 2"): + stats.calibrate(frame, ["A_cat"], settings.depuration, "t") + + +def test_unknown_settings_are_refused(tmp_path): + bad = tmp_path / "model.toml" + bad.write_text("[depuration]\nnope = 1\n[bootstrap]\nn_bootstrap = 1\nrandom_state = 0\n") + with pytest.raises(ValueError, match="unknown settings"): + load(bad) + + +def test_the_bootstrap_indices_are_reproducible_and_within_the_rows(tmp_path): + pd.DataFrame({"x": range(50)}).to_csv(tmp_path / "balanced.csv", index=False) + s = dataclasses.replace(load(), bootstrap=BootstrapSettings(n_bootstrap=7, random_state=3)) + + first = run.run_bootstrap(tmp_path / "balanced.csv", tmp_path, s)["bootstrap_indices"] + again = run.run_bootstrap(tmp_path / "balanced.csv", tmp_path, s)["bootstrap_indices"] + + assert first.shape == (7, 50) and first.min() >= 0 and first.max() < 50 + assert np.array_equal(first, again) and np.array_equal(np.load(tmp_path / run.BOOTSTRAP_INDICES), first) + meta = json.loads((tmp_path / run.BOOTSTRAP_METADATA).read_text()) + assert (meta["n_filas"], meta["n_bootstrap"], meta["random_state"]) == (50, 7, 3) diff --git a/tests/cama/test_seer_survival_stages.py b/tests/cama/test_seer_survival_stages.py new file mode 100644 index 0000000..32c46c6 --- /dev/null +++ b/tests/cama/test_seer_survival_stages.py @@ -0,0 +1,252 @@ +"""The numeric cores of the SEER survival pipeline's stages 02, 04, 05 and 06, and its runner, on small synthetic data.""" + +import os +import time + +import numpy as np +import pandas as pd +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.settings import load + + +# ---------------------------------------------------------------- settings + +def test_every_stage_has_its_settings(): + s = load() + assert s.balancing.mca_variant in ("con_edad", "sin_edad") + 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 s.risk_factors.treatment == ("Tratamiento_quirurgico", "Radioterapia", "Quimioterapia") + + +# ---------------------------------------------------------------- 02a balancing + +def test_age_midpoints(): + mid = balancing_stats.age_midpoint + assert mid("40-44 years") == 42 and mid("85+ years") == 90 and mid("05") == 5 and np.isnan(mid("unknown")) + + +def test_the_outcome_treats_censoring_and_incomplete_years_as_unknown(): + s = load().balancing + labels = {"m": "Survival months", "v": "Vital status", "y": "Year of diagnosis"} + df = pd.DataFrame({"m": ["30", "5", "5", "30", "40"], "v": ["Alive", "Dead", "Alive", "Dead", "Alive"], + "y": ["2000", "2000", "2000", "2001", "2001"]}) + # alive with 5 months is censored: unknown; year 2000 has 1 of 3 censored (> 10 %), so the whole year leaves + assert np.isnan(balancing_stats.outcome_values(df, labels, s)).tolist() == [True, True, True, False, False] + assert balancing_stats.outcome_values(df, labels, s)[3:].tolist() == [1.0, 1.0] + keep = balancing_stats.outcome_values(df, labels, s.__class__(**{**s.__dict__, "exclude_censored_years": False})) + assert keep[0] == 1.0 and keep[1] == 0.0 and np.isnan(keep[2]) # only the censored patient stays unknown + + +def test_the_undersampling_keeps_every_death_and_the_survivors_nearest_to_them(): + F = np.array([[0.0], [0.1], [5.0], [9.0], [0.2], [8.0]]) + outcome = np.array([0, 1, 1, 1, 0, 1]) # 0 = death (minority): rows 0 and 4 + keep, dist = balancing_stats.select_informed_undersample(F, outcome, 0, 1, target_ratio=1.0) + assert keep.tolist() == [True, True, True, False, True, False] # 2 deaths + the 2 nearest survivors + assert dist[1] == pytest.approx(0.1) and dist[3] == pytest.approx(8.8) + + +# ---------------------------------------------------------------- 02b categorization + +def _axis_frame(rng_seed=0): + """Ten levels; the category mix flips between level 4 and 5 (the only real boundary).""" + rng = np.random.default_rng(rng_seed) + levels = [f"{i:02d}" for i in range(10)] + rows = [] + for i, level in enumerate(levels): + for _ in range(300): + p = 0.9 if i < 5 else 0.1 + rows.append({"lvl": level, "X_cat": "a" if rng.random() < p else "b", + "Y_cat": "u" if rng.random() < (0.85 if i < 5 else 0.15) else "v"}) + return pd.DataFrame(rows), levels + + +def test_segmentation_finds_the_one_boundary_where_the_composition_flips(): + df, levels = _axis_frame() + axis = cs.Axis.of(df, "lvl", levels, list(range(10)), "corte_x") + s = load().categorization + result = cs.segment(df, axis, ["X", "Y"], {}, s, min_n=100) + assert result.bounds == [5] and result.segments == [(0, 5), (5, 10)] + assert result.effect_sizes["cambio_medio"].iloc[0] > 0.7 + assert cs.level_to_group(result.segments, levels)["00"] == "00 a 04" + + +def test_small_segments_are_merged_into_the_most_similar_neighbour(): + counts = {"c": pd.DataFrame([[50, 0], [50, 0], [0, 50], [0, 50], [45, 5]], columns=["a", "b"])} + segs, log = cs.fix_small_segments(counts, np.array([50, 50, 50, 50, 50]), [2, 4], 5, min_n=80) + assert all(sum(50 for _ in range(a, b)) >= 80 for a, b in segs) and log + + +def test_configurations_are_every_combination_of_blocks(): + configs = cs.configurations({"outcome": ["Outcome"], "biología": ["A", "B"], "tratamiento": ["T"]}) + assert set(configs) == {"Solo outcome", "Solo biología", "Solo tratamiento", "Outcome + biología", + "Outcome + tratamiento", "Biología + tratamiento", "Outcome + biología + tratamiento"} + assert configs["Biología + tratamiento"] == ["A", "B", "T"] + + +def test_tumor_sizes_and_levels(): + assert cs.tumor_size_mm("023") == 23.0 and np.isnan(cs.tumor_size_mm("000")) and np.isnan(cs.tumor_size_mm("999")) + assert cs.tumor_bin_label(23.0, 5, 100) == "021-025 mm" and cs.tumor_bin_label(101.0, 5, 100) == ">100 mm" + levels, mids = cs.tumor_levels(5, 100) + assert levels[0] == "001-005 mm" and levels[-1] == ">100 mm" and len(levels) == len(mids) == 21 and mids[0] == 3.0 + + +def test_quantile_and_clinical_cuts_partition_the_axis(): + assert cs.quantile_bounds(np.array([10, 10, 10, 10, 10, 10, 10, 10]), 4) == [2, 4, 6] + segs = cs.segments_from_bounds([3, 3, 0, 99, 5], 8) + assert segs == [(0, 3), (3, 5), (5, 8)] + + +def test_sensitivity_and_specificity_at_a_cut(): + idx = np.array([0, 0, 1, 1, 2, 2, 3, 3]) + death = np.array([0, 0, 0, 1, 0, 1, 1, 1], bool) + r = cs.sens_spec_at_cut(idx, death, 2) + assert r["lado_alto_riesgo"] == "arriba del corte" and r["sensibilidad"] == 0.75 and r["especificidad"] == 0.75 + + +def test_the_overlap_of_identical_distributions_is_one(): + a = pd.Series(["x", "y", "x", "y"]) + assert cs.overlap_coefficient(a, a, ["x", "y"]) == 1.0 + assert cs.overlap_coefficient(pd.Series(["x"] * 4), pd.Series(["y"] * 4), ["x", "y"]) == 0.0 + + +# ---------------------------------------------------------------- 04 modeling + +def test_the_stepwise_keeps_the_signal_and_drops_the_noise(): + rng = np.random.default_rng(3) + n = 1500 + signal, noise = rng.normal(size=n), rng.normal(size=n) + y = pd.Series((rng.random(n) < 1 / (1 + np.exp(-2 * signal))).astype(int)) + X = pd.DataFrame({"signal": signal, "noise": noise, "noise2": rng.normal(size=n)}) + assert lr_selection.stepwise_selection(X, y) == ["signal"] + + +def test_the_prefilter_sorts_by_chi_square_and_caps_the_columns(): + rng = np.random.default_rng(4) + y = pd.Series(rng.integers(0, 2, 800)) + X = pd.DataFrame({"weak": ((y.values + (rng.random(800) < 0.4)) > 0).astype(float), + "strong": ((y.values + (rng.random(800) < 0.05)) > 0).astype(float), + "none": rng.integers(0, 2, 800).astype(float)}) + assert lr_selection.prefiltered_columns(X, y, 0.10, 40) == ["strong", "weak"] + assert lr_selection.prefiltered_columns(X, y, 0.10, 1) == ["strong"] + + +def test_the_temporal_tiers_order_demography_tumor_treatment_outcome(): + s = load().modeling + tiers = hbn.temporal_order(["Estadio", "Edad", "Radioterapia", "outcome", "Rara"], s) + assert tiers == [["Rara"], ["Edad"], ["Estadio"], ["Radioterapia"], ["outcome"]] + + +# ---------------------------------------------------------------- 05 survival + +def test_the_classic_weibull_fit_recovers_its_parameters(): + rng = np.random.default_rng(5) + t = 80.0 * rng.weibull(1.4, 6000) + months = np.minimum(np.floor(t).astype(int), 40) + event = t < 40 + d, c = fw.tabla_eventos(months, event) + w = fw.ajustar_weibull(d, c) + assert w["k"] == pytest.approx(1.4, abs=0.15) and w["lam"] == pytest.approx(80.0, rel=0.12) + + +def test_the_fractional_weibull_is_a_valid_survival_function(): + t = np.array([0.0, 1.0, 5.0, 12.0, 24.0]) + S = fw.S_ks(t, k=1.0, alpha=1.0, beta=0.5, lam=60.0) + assert S[0] == 1.0 and np.all(np.diff(S) <= 1e-12) and np.all((S >= 0) & (S <= 1)) + assert fw.kilbas_saigo([0.0], 1.0, 1.0, 0.0)[0] == 1.0 + assert np.all(np.isnan(fw.S_ks(t, k=0.5, alpha=0.4, beta=1.0, lam=60.0))) # k + alpha <= 1: out of region + + +def test_kaplan_meier_with_no_censoring_is_the_survivor_fraction(): + months = np.array([1, 1, 2, 3, 3, 3, 5, 5, 6, 6]) + S, lo, hi = fw.km_curva(months, np.ones(10, bool), 6) + assert S[:7].tolist() == pytest.approx([1.0, 1.0, 0.8, 0.7, 0.4, 0.4, 0.2]) # S[m]: alive at the start of month m + assert np.all(lo <= S + 1e-12) and np.all(S <= hi + 1e-12) + + +def test_the_censoring_weights(): + m, e = np.array([2, 5, 8, 12]), np.array([True, False, True, False]) + known, y, w = sm.censoring_weights(m, e, 6, "excluir") + assert known.tolist() == [True, False, True, True] and y.tolist() == [0, 0, 1, 1] and w.tolist() == [1, 1, 1, 1] + assert sm.censoring_weights(m, e, 6, "ipcw")[2].min() >= 1.0 + + +def test_the_stacking_weight_follows_the_better_model_and_shrinks_with_few_deaths(): + rng = np.random.default_rng(6) + n = 2000 + c = sm.Cohort(months=np.full(n, 20), event=np.zeros(n, bool), X_dum=np.zeros((n, 1)), X_int=np.zeros((n, 1), int), + levels=np.array([1]), borders=[0, 6], fixed_parents=None) + truth = rng.random(n) < 0.7 # survives the interval + c = sm.Cohort(np.where(truth, 20, 3), ~truth, c.X_dum, c.X_int, c.levels, c.borders, None) + good = np.where(truth, 0.9, 0.2)[:, None] + bad = np.full((n, 1), 0.7) + s = load().survival + t = sm.stacking_weights(c, s, np.ones(n, bool), good, bad) + assert t["w_LR"].iloc[0] > 0.9 and t["w_LR_sin_contraer"].iloc[0] >= t["w_LR"].iloc[0] + assert t["decision"].iloc[0] in ("solo LR", "mezcla") + + +def test_the_fixed_hbn_parents_are_found_by_keyword_and_age_is_added(): + s = load().survival + cov = ["Estadio_cat", "Tipo_histologico_cat", "Tratamiento_quirurgico_cat", "Quimioterapia_cat", "Radioterapia_cat", + "Edad_cat", "Race"] + assert sm.fixed_parent_indices(cov, s) == [0, 1, 2, 3, 4, 5] + with pytest.raises(AssertionError, match="Estadio"): + sm.fixed_parent_indices(["Edad_cat"], s) + + +# ---------------------------------------------------------------- 06 risk factors + +def test_benjamini_hochberg(): + p = [0.01, 0.04, 0.03, 0.005] + assert rf.benjamini_hochberg(p).tolist() == pytest.approx([0.02, 0.04, 0.04, 0.02]) + + +def test_the_odds_of_a_risky_category_are_above_one_and_its_survival_lower(): + rng = np.random.default_rng(7) + n = 4000 + stage = rng.choice(["I", "IV"], n, p=[0.7, 0.3]) + death = (rng.random(n) < np.where(stage == "IV", 0.5, 0.1)).astype(int) + data = pd.DataFrame({"Estadio": stage, "Sexo": rng.choice(["f", "m"], n)}) + t = rf.fit_odds(data, death, ["Estadio", "Sexo"]) + row = t[t["termino"] == "Estadio_IV"].iloc[0] + assert row["OR_muerte"] > 5 and row["IC95_inf"] > 1 and rf.reference(data, "Estadio") == "I" + months = np.where(death == 1, 8, 24) + d = rf.survival_difference(data, months, death.astype(bool), "Estadio", "IV", "I", 18) + assert d["delta_S18"] < -0.2 and d["delta_IC95_sup"] < 0 and d["n_categoria"] == int((stage == "IV").sum()) + + +# ---------------------------------------------------------------- the runner + +def test_a_stage_is_current_only_when_its_outputs_are_newer_than_its_code_and_inputs(tmp_path): + stage = next(e for e in pipeline.STAGES if e.id == "03") + assert not pipeline.is_current(stage, tmp_path) # no outputs + for name in stage.requires + stage.produces: + (tmp_path / name).write_text("x") + future = time.time() + 3600 + for name in stage.produces: + os.utime(tmp_path / name, (future, future)) + assert pipeline.is_current(stage, tmp_path) + os.utime(tmp_path / stage.requires[0], (future + 10, future + 10)) # the input changed after the outputs + assert not pipeline.is_current(stage, tmp_path) + (tmp_path / stage.produces[0]).write_text("") # an empty output is no output + assert not pipeline.is_current(stage, tmp_path) + + +def test_the_runner_names_the_missing_inputs_and_logs_each_stage(tmp_path, monkeypatch): + with pytest.raises(FileNotFoundError, match="faltan entradas"): + pipeline.run_pipeline(tmp_path, only=["01"]) + ran = [] + stage = pipeline.Stage("99", lambda d, s: ran.append("ok"), (), ("out.csv",), ()) + monkeypatch.setattr(pipeline, "STAGES", [stage, pipeline.Stage("98", lambda d, s: ran.append("again"), (), (), ())]) + pipeline.run_pipeline(tmp_path, settings=object()) + assert ran == ["ok", "again"] + (tmp_path / "out.csv").write_text("x") + 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"