acc8c371bc
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.
104 lines
4.8 KiB
Python
104 lines
4.8 KiB
Python
"""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)
|