CaMa survival: the SEER interval-survival pipeline as a scenario with population results
models/cama/seer_survival is the SEER survival pipeline as Hamilton dataflows, with the interval LR and network keeping their per-interval fits and surviving an interval without deaths. models/cama/survival is the scenario: it indexes the total cohort at the first invasive biopsy report (steps/indexing.py), derives the covariates and the outcome from the cohort's events, fits the interval survival, writes the five routines and publishes the population curves (analisis/curvas.json) with the version. An estimate may carry the model's own index date.
This commit is contained in:
@@ -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)
|
||||
@@ -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"
|
||||
@@ -0,0 +1,287 @@
|
||||
"""What this module covers: `models.cama.survival`: the index it takes from the total cohort (the first invasive biopsy
|
||||
report, with its rules), the covariates and outcome it derives from a build's events, the interval survival estimator
|
||||
(that it scores unseen categories and intervals without deaths, and that grade and ER move the mortality the way the
|
||||
data say), that the dataflow reaches its metrics and routines without MLflow, that training registers a version with
|
||||
its lineage and estimating with it dates each risk by the model's own index.
|
||||
|
||||
Fixtures: `cohort_frame`, a long frame of 240 members of the total cohort whose death depends on the grade and on ER,
|
||||
with members that must be left out; `cohort_file`, that frame as a build's Parquet file with its lineage (the window
|
||||
in its parameters); `mlflow_tracking` (conftest), a SQLite-backed MLflow.
|
||||
"""
|
||||
|
||||
import json
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pyarrow as pa
|
||||
import pyarrow.parquet as pq
|
||||
import pytest
|
||||
|
||||
from models.cama.survival import estimator
|
||||
from models.cama.survival.estimator import FEATURES, INDEX_COLUMN, IntervalSurvival, MemberFeatures
|
||||
from models.dags.estimation import estimate
|
||||
from models.dags.training import Scenario, dataflow, find_trained, train
|
||||
from models.io.contracts import COHORT_SCHEMA as SCHEMA
|
||||
from models.io.storage import CohortFile, read_cohort, read_metadata
|
||||
from models.steps import indexing
|
||||
|
||||
CUTOFF = date(2026, 1, 1)
|
||||
SCENARIO = Scenario.load("cama", "survival")
|
||||
CONFIG = SCENARIO.config
|
||||
WINDOW = {"recruitment_start": "2018-01-01", "recruitment_end": "2027-01-01", "cutoff": CUTOFF.isoformat()}
|
||||
LINEAGE = {"url": "cama/cohorte_total", "datos_as_of": CUTOFF.isoformat(), "parametros": json.dumps(WINDOW)}
|
||||
N = 240
|
||||
|
||||
|
||||
def _row(pac_id, when, tipo, valor=None, numero=None, source="biopsiamama", source_id=None, first=None):
|
||||
return {"pac_id": pac_id, "fecha_indice": first or when, "fecha": when,
|
||||
"conocida_en": datetime(2026, 1, 1, tzinfo=timezone.utc), "clase": "medicion", "tipo": tipo, "codigo": tipo,
|
||||
"valor_codigo": valor, "valor_numerico": numero, "fuente_tabla": source,
|
||||
"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):
|
||||
"""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),
|
||||
_row(pac_id, index, "tipo_histologico", "DUCTAL_INFILTRANTE", source_id=key, first=first),
|
||||
_row(pac_id, index, "grado_nottingham", grade, source_id=key, first=first),
|
||||
_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)]
|
||||
return rows
|
||||
|
||||
|
||||
def _person(pac_id, born, first, died=None):
|
||||
rows = [_row(pac_id, born, "nacimiento", source="persona", first=first)]
|
||||
if died:
|
||||
rows.append(_row(pac_id, died, "defuncion", source="persona", first=first))
|
||||
return rows
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def cohort_frame():
|
||||
"""240 members, each with her birth, an invasive biopsy report in 2024-01..2025-06 (grade 1 to 3, ER positive or
|
||||
negative) and, if she dies by the cut-off, her death: exponential in months, faster with grade 3 and without ER.
|
||||
Members 241 to 245 must be left out: a benign biopsy only, no birth date, a death before the report, a report
|
||||
before the window, and an invasive report after the cut-off."""
|
||||
rng = np.random.default_rng(3)
|
||||
rows = []
|
||||
for pac_id in range(1, N + 1):
|
||||
index = date(2024, 1, 1) + timedelta(days=int(rng.integers(0, 546)))
|
||||
grade, er = str(rng.choice(["G1", "G2", "G3"])), str(rng.choice(["POSITIVO", "NEGATIVO"]))
|
||||
rate = 0.012 * np.exp(1.3 * (grade == "G3") - 0.6 * (er == "POSITIVO"))
|
||||
died = index + timedelta(days=int(rng.exponential(1 / rate) * 30.4375))
|
||||
rows += _person(pac_id, date(1960, 1, 1) + timedelta(days=pac_id * 30), index - timedelta(days=10),
|
||||
died if died <= CUTOFF else None)
|
||||
rows += _report(pac_id, index, grade, er, first=index - timedelta(days=10))
|
||||
first = date(2025, 1, 1)
|
||||
rows += [_row(241, first, "biopsia", "BENIGNO", source_id="B241", first=first)]
|
||||
rows += _report(242, first, first=first)
|
||||
rows += _person(243, date(1960, 1, 1), first, died=first - timedelta(days=20)) + _report(243, first, first=first)
|
||||
rows += _person(244, date(1960, 1, 1), date(2010, 1, 1)) + _report(244, date(2010, 3, 1), first=date(2010, 1, 1))
|
||||
rows += _person(245, date(1960, 1, 1), first) + _report(245, date(2026, 3, 1), first=first)
|
||||
return pd.DataFrame(rows, columns=SCHEMA.names)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cohort_file(cohort_frame, tmp_path):
|
||||
"""The frame as build 3's file, with the lineage a dbt build gives."""
|
||||
table = pa.Table.from_pandas(cohort_frame, schema=SCHEMA, preserve_index=False)
|
||||
path = tmp_path / "3.parquet"
|
||||
pq.write_table(table.replace_schema_metadata({**LINEAGE, "armado_id": "3"}), path)
|
||||
return path
|
||||
|
||||
|
||||
def _indexed(frame):
|
||||
return indexing.cohort(frame, LINEAGE, CONFIG["index"])
|
||||
|
||||
|
||||
def test_the_index_is_the_first_invasive_biopsy_report_and_its_rules_leave_out_who_cannot_be_followed(cohort_frame):
|
||||
"""Pins down: members 1 to 240 are indexed at their invasive report; a benign biopsy has no index (241), a missing
|
||||
birth date (242), a death before the report (243) and a report outside the window (244, and 245 after the cut-off
|
||||
window end) leave the cohort, each charged to its own rule. Fails if the kind stops reading the grade, the window
|
||||
or either rule."""
|
||||
attrition = dict(indexing.index_attrition(cohort_frame, LINEAGE, CONFIG["index"]))
|
||||
|
||||
assert attrition["pacientes"] == N + 5 and attrition["indexed"] == N + 3
|
||||
assert attrition["sin_nacimiento"] == N + 2 and attrition["defuncion_hasta_el_indice"] == N + 1
|
||||
members = _indexed(cohort_frame)["pac_id"].unique()
|
||||
assert set(members) == set(range(1, N + 1)) | {245}
|
||||
reindexed = _indexed(cohort_frame).groupby("pac_id")["fecha_indice"].first()
|
||||
assert reindexed[1] == cohort_frame[(cohort_frame["pac_id"] == 1) & (cohort_frame["tipo"] == "biopsia")]["fecha"].iloc[0]
|
||||
|
||||
|
||||
def test_covariates_are_the_index_reports_results(cohort_frame):
|
||||
"""Pins down: the covariates are the results of the report on the index date: type, grade, ER, PR, HER2 and the
|
||||
Ki-67 band; a grade reported a year later does not replace them, and the age group is the age at the index. Fails
|
||||
if the covariates read another report or window, or the age is taken at another date."""
|
||||
one = cohort_frame[cohort_frame["pac_id"] == 1]
|
||||
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"])
|
||||
|
||||
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["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
|
||||
assert row["age_group"] == ("<45" if age < 45 else "45-59" if age < 60 else "60-74" if age < 75 else "≥75")
|
||||
|
||||
|
||||
def test_the_outcome_is_the_months_to_death_or_to_the_cutoff_cut_at_the_cap(cohort_frame):
|
||||
"""Pins down: a member who dies in follow-up has her whole months to the death and `event`; one without a death is
|
||||
followed to the cut-off without it; a death after `cap_months` counts as alive at the cap. Fails if the months, the
|
||||
censoring date or the cap change."""
|
||||
rows = (_person(1, date(1960, 1, 1), date(2024, 1, 1), died=date(2024, 8, 10)) + _report(1, date(2024, 1, 1))
|
||||
+ _person(2, date(1960, 1, 1), date(2025, 1, 1)) + _report(2, date(2025, 1, 1))
|
||||
+ _person(3, date(1960, 1, 1), date(2023, 1, 1), died=date(2025, 11, 1)) + _report(3, date(2023, 1, 1)))
|
||||
frame = pd.DataFrame(rows, columns=SCHEMA.names)
|
||||
|
||||
table = estimator.outcome_table(frame, CUTOFF, cap_months=24)
|
||||
|
||||
assert table.loc[1].tolist() == [7, True] # 2024-01-01 to 2024-08-10: 222 days
|
||||
assert table.loc[2].tolist() == [11, False] # 2025-01-01 to the cut-off: 365 days, 11.99 whole months
|
||||
assert table.loc[3].tolist() == [24, False] # dies after 24 months: alive at the cap
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
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"])
|
||||
return features.join(estimator.outcome_table(indexed, CUTOFF, 24)).reset_index()
|
||||
|
||||
|
||||
def test_grade_and_er_move_the_mortality_the_way_the_data_say(labelled):
|
||||
"""Pins down: fitted on members whose death depends on grade 3 and on no ER, the estimator gives grade 3 a higher
|
||||
mortality at every horizon than grade 1, and the mortality grows with the horizon and stays in 0 to 1. Fails if the
|
||||
fit stops using the covariates or the survival stops being a product of the intervals."""
|
||||
model = IntervalSurvival(CONFIG["survival"], tuple(CONFIG["horizons_years"])).fit(labelled[FEATURES],
|
||||
labelled[["months", "event"]])
|
||||
probe = labelled[FEATURES].iloc[[0, 0]].copy()
|
||||
probe["grade"] = ["G1", "G3"]
|
||||
probe["er"] = "POSITIVO"
|
||||
|
||||
mortality = model.predict_proba(probe)
|
||||
|
||||
assert mortality.shape == (2, 3) and ((0 <= mortality) & (mortality <= 1)).all()
|
||||
assert (mortality[1] > mortality[0]).all() and (np.diff(mortality, axis=1) >= 0).all()
|
||||
|
||||
|
||||
def test_a_category_unseen_in_training_and_an_interval_without_deaths_are_scored(labelled):
|
||||
"""Pins down: a grade the model never saw scores as unknown rather than failing, and a cohort where nobody dies in
|
||||
the last interval still fits (a constant stands for the logistic regression). Fails if either raises."""
|
||||
early = labelled.assign(event=labelled["event"] & (labelled["months"] < 12))
|
||||
model = IntervalSurvival(CONFIG["survival"], tuple(CONFIG["horizons_years"])).fit(early[FEATURES],
|
||||
early[["months", "event"]])
|
||||
unseen = labelled[FEATURES].iloc[[0]].assign(grade="G9")
|
||||
|
||||
mortality = model.predict_proba(unseen)
|
||||
|
||||
assert np.isfinite(mortality).all()
|
||||
assert mortality[0, 2] - mortality[0, 1] < 0.05 # nobody died in 12-18 months: only the network's smoothing remains
|
||||
|
||||
|
||||
def test_the_pipeline_takes_the_total_cohort_and_scores_only_who_the_index_leaves(cohort_frame, labelled):
|
||||
"""Pins down: the registered shape (`MemberFeatures` then the estimator) takes the unindexed frame, gives one row
|
||||
per member of the frame, and leaves empty the members the scenario leaves out, with the model's index date first for
|
||||
the rest. Fails if scoring stops indexing the build as training did."""
|
||||
from sklearn.pipeline import Pipeline
|
||||
|
||||
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"])),
|
||||
("survival", fitted)])
|
||||
|
||||
scored = pipeline.predict_proba(cohort_frame)
|
||||
|
||||
assert scored.shape == (N + 5, 4)
|
||||
assert np.isnan(scored[N:N + 4, 0]).all() and not np.isnan(scored[:N, 0]).any()
|
||||
assert not np.isnan(scored[N + 4, 0]) # member 245: indexed (her report is in the window), scored
|
||||
|
||||
|
||||
def test_the_dataflow_reaches_its_metrics_and_routines_without_mlflow(cohort_frame):
|
||||
"""Pins down: from the source cohort and its lineage the graph gives metrics that are numbers, and the five routine
|
||||
records the registry checks before promoting. Fails if a node stops producing its record or a metric is not a
|
||||
number."""
|
||||
dr = dataflow(*SCENARIO.modules, config=CONFIG)
|
||||
|
||||
result = dr.execute(["metrics", "routines", "index_attrition"],
|
||||
inputs={"source_cohort": cohort_frame, "cohort_lineage": LINEAGE})
|
||||
|
||||
assert all(isinstance(v, (int, float)) for v in result["metrics"].values())
|
||||
assert result["metrics"]["n_train"] + result["metrics"]["n_test"] == N + 1
|
||||
assert set(result["routines"]) == {"MUESTREO", "DATOS_FALTANTES", "METODO_ANALITICO", "BALANCE_CLASES",
|
||||
"CONFIANZA_SALIDA"}
|
||||
json.dumps(result["routines"])
|
||||
|
||||
|
||||
def test_training_registers_a_version_and_estimating_dates_each_risk_by_the_models_index(cohort_file, mlflow_tracking,
|
||||
tmp_path):
|
||||
"""Pins down: training on a build's file registers a version; estimating with it writes one row per scored member
|
||||
and horizon, dated by the model's index (the report), not by the cohort's, with the members the scenario leaves out
|
||||
absent. Fails if the version cannot score a build or the estimate keeps the cohort's index date."""
|
||||
version = train(SCENARIO, CohortFile(cohort_file))
|
||||
output = tmp_path / "estimate.parquet"
|
||||
|
||||
resolved, wrote = estimate(SCENARIO, CohortFile(cohort_file), output, version)
|
||||
|
||||
assert wrote and resolved.version == version and find_trained(SCENARIO, CohortFile(cohort_file)) == version
|
||||
risks = pq.read_table(output).to_pandas()
|
||||
assert set(risks["horizonte_anios"]) == {0.5, 1.0, 1.5}
|
||||
assert set(risks["pac_id"]) == set(range(1, N + 1)) | {245}
|
||||
frame = read_cohort(cohort_file)
|
||||
report = frame[(frame["tipo"] == "biopsia") & (frame["pac_id"] == 1)]["fecha"].iloc[0]
|
||||
assert risks[risks["pac_id"] == 1]["fecha_indice"].iloc[0] == report
|
||||
assert read_metadata(output)["desenlace"] == "muerte"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
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"]
|
||||
|
||||
|
||||
def test_the_population_record_has_the_figures_curves_points_and_labels(population_record):
|
||||
"""Pins down: the record the dashboard draws has the Kaplan-Meier with its band, the adjusted curve, both Weibull
|
||||
curves, LR, HBN and combined points at 6, 12 and 18 months each with a 95 % interval, and the labels from the
|
||||
settings. Fails if a curve or a series is missing, a curve rises, a band does not hold its curve, an interval is
|
||||
inverted, or the labels stop coming from `[config.etiquetas]`."""
|
||||
r = population_record
|
||||
|
||||
assert r["horizons_months"] == [6, 12, 18] and r["n"] == N + 1 and r["events"] > 20
|
||||
km = r["km"]
|
||||
assert km["months"][0] == 0 and km["S"][0] == 1.0 and np.all(np.diff(km["S"]) <= 1e-12)
|
||||
assert all(lo <= s <= hi for lo, s, hi in zip(km["low"], km["S"], km["high"]))
|
||||
for curve in (r["km_adjusted"]["S"], r["weibull"]["S"], r["weibull_fractional"]["S"]):
|
||||
assert curve[0] == pytest.approx(1.0, abs=1e-6) and np.all(np.diff(curve) <= 1e-9)
|
||||
assert set(r["points"]) == {"LR", "HBN", "COMB"}
|
||||
for series in r["points"].values():
|
||||
assert len(series["S"]) == 3 and all(0 <= lo <= hi <= 1 for lo, hi in zip(series["low"], series["high"]))
|
||||
assert series["S"] == sorted(series["S"], reverse=True)
|
||||
assert r["etiquetas"]["eje_x"] == CONFIG["etiquetas"]["eje_x"]
|
||||
json.dumps(r)
|
||||
|
||||
|
||||
def test_a_version_publishes_its_population_record(cohort_file, mlflow_tracking):
|
||||
"""Pins down: training registers the `analisis/curvas.json` file with the version, and it is the record the dataflow
|
||||
built. Fails if the saver stops logging a dataflow's `population`."""
|
||||
from models.io.registry import registry
|
||||
|
||||
version = train(SCENARIO, CohortFile(cohort_file))
|
||||
|
||||
files = [f["path"] for f in registry.artifacts("cama", "survival", version)]
|
||||
name, content = registry.artifact("cama", "survival", version, "analisis/curvas.json")
|
||||
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"}
|
||||
Reference in New Issue
Block a user