Files
models/tests/test_recurrence.py
T

283 lines
13 KiB
Python

"""CaMa recurrence reproduces v1 (MLflow run 0e5ea82e, the reference fixtures) from the two
published datasets, loaded by the platform's `cama_reference` pipeline (the files are in
`CAMA_REFERENCE_DIR`, default ~/camaSupervivencia).
Tolerances: cohorts, terms, parents, CPT keys and every routine are exact; the saved model's
constants, coefficients and CPT values are bit-identical (== on the floats); AUCs, C-indexes
and bootstrap summaries equal v1's 4-decimal values; the calculator's table and its 4-decimal
cells are equal, the figure points equal to 1e-12, the Kaplan-Meier curves and classic Weibull
curves to 1e-12; risk-factor cells within 1.01e-4 (v1 stored them rounded to 4 places: a value
on a rounding edge may land one unit away). The fractional Weibull is fitted to convergence;
v1 stopped its fit on a 60-second wall clock, short of it, so its curve is v1's within
FRACTIONAL_TOLERANCE, not equal. The fractional curve itself is a solver's, within
SOLVER_TOLERANCE of the exact series.
The full bootstrap and the calculator (whose 40 fractional Weibull curves are fitted to
convergence, a few minutes each) are marked `slow` and run only with RECURRENCE_SLOW=1
(about an hour); the default set takes about two minutes.
"""
import json
import os
import re
from pathlib import Path
import numpy as np
import pandas as pd
import pytest
from joblib.externals.loky import get_reusable_executor
from scipy.special import gammaln
from conftest import _platform
from models import curves
from models.cama import recurrence
from models.cama.recurrence import calculator, cohorts, factors, modeling, reports
RAW = Path(os.environ.get("CAMA_REFERENCE_DIR", Path.home() / "camaSupervivencia"))
V1 = Path(__file__).parents[2] / "tests" / "fixtures" / "reference" / "cama" / "recurrence" / "v1"
# Max |S| difference to v1's fractional Weibull curve: v1 stopped its fit on a 60 s clock,
# short of the optimum this fit converges to (largest gap measured: 0.053).
FRACTIONAL_TOLERANCE = 0.06
SOLVER_TOLERANCE = 1e-6 # max |S| error of the fractional Weibull's solver (~1e-7 measured)
FACTOR_TOLERANCE = 1.01e-4
FILES = ("brca_metabric_clinical_data.tsv", "scanb_clinical_metadata.txt")
PIPELINE = Path(__file__).parents[2] / "tests" / "fixtures" / "pipelines" / "cama_reference.json"
pytestmark = pytest.mark.skipif(
not all((RAW / f).exists() for f in FILES), reason="no reference raw files"
)
slow = pytest.mark.skipif(not os.environ.get("RECURRENCE_SLOW"), reason="RECURRENCE_SLOW unset")
def _json(path: str):
return json.loads((V1 / path).read_text())
VERSION = _json("version.json") if V1.exists() else {}
DEVELOPMENT = _json("analisis/recurrencia_desarrollo.json")["tablas"] if V1.exists() else {}
FIGURES = _json("analisis/recurrencia.json")["escenarios"] if V1.exists() else []
@pytest.fixture(scope="module")
def raws(tmp_path_factory) -> dict[str, pd.DataFrame]:
"""Both datasets as the platform loads them: the `cama_reference` pipeline into a fresh
platform, read back from its tables."""
folder = tmp_path_factory.mktemp("platform")
platform = _platform("sqlite", folder)
drawn = folder / "pipeline.json"
drawn.write_text(PIPELINE.read_text().replace("{reference}", str(RAW)))
platform.save("pipelines", "cama_reference", drawn)
platform.ingest("cama_reference")
# What the training job reads (models.cama.specs), from that platform.
out = folder / "datasets.pkl"
platform.run("python", "-c", "import pandas as pd; from models.cama.specs import MODELS; "
f"pd.to_pickle(MODELS['recurrence'].datasets(), {str(out)!r})") # fmt: skip
return pd.read_pickle(out)
@pytest.fixture(scope="module")
def prepared(raws):
return {s: cohorts.prepare(s, raw) for s, raw in raws.items()}
@pytest.fixture(scope="module")
def fits(prepared):
found = modeling.fit(prepared, {})
get_reusable_executor().shutdown(wait=True)
return found
# ---------------------------------------------------------------- comparisons
# v1 read SCAN-B's clinical stage as a number, so its categories print as 0.0, 1.0...; the
# platform keeps the dataset's text (0, 1...). Same categories, in the same order.
STAGES = {f"{n}.0": str(n) for n in range(5)}
def _stages(table: dict) -> dict:
"""v1's summary with the stages as the dataset writes them."""
text = re.sub(r"Estadio_clinico=(\d)\.0", r"Estadio_clinico=\1", json.dumps(table))
return json.loads(text)
def _same_rows(mine: list[dict], ref: list[dict], tolerance: float = 0.0):
ref = [{**r, **{k: STAGES.get(r[k], r[k]) for k in ("categoria", "referencia") if k in r}}
if r.get("variable") == "Estadio_clinico" else r for r in ref] # fmt: skip
assert len(mine) == len(ref)
for i, (a, b) in enumerate(zip(mine, ref, strict=True)):
assert a.keys() == b.keys(), i
for c, z in b.items():
x = a[c]
if isinstance(z, float) and not isinstance(z, bool) and x is not None:
assert abs(x - z) <= tolerance, (i, c, x, z)
else:
assert x == z, (i, c, x, z)
def _auc_rows(rows: list[dict], with_bootstrap: bool) -> list[dict]:
keep = slice(None) if with_bootstrap else slice(0, 6)
return [dict(list(r.items())[keep]) for r in rows]
def _reference_selection(source: str) -> dict:
"""v1's bootstrap selection shares, as its risk-factor table published them."""
found = {}
for r in DEVELOPMENT["factores_riesgo"]["filas"]:
if r["cohorte"] == source and r["tipo"] == "factor de riesgo":
found.setdefault(r["horizonte_meses"], {})[r["variable"]] = r[
"freq_seleccion_bootstrap"
]
return found
def _check_figures(records: list[dict], fractional_tolerance: float):
assert [(r["cohorte"], r["escenario"]) for r in records] == [
(r["cohorte"], r["escenario"]) for r in FIGURES
]
for mine, ref in zip(records, FIGURES, strict=True):
fixed = ("condiciones", "n", "recaidas", "observado_hasta", "months_max", "cohorte_nombre")
assert {k: mine[k] for k in fixed} == {k: ref[k] for k in fixed}
assert mine["bootstrap_replicas"] == ref["bootstrap_replicas"]
assert mine["km"]["months"] == ref["km"]["months"]
for part in ("S", "low", "high"):
np.testing.assert_allclose(mine["km"][part], ref["km"][part], rtol=0, atol=1e-12)
got, want = mine["points"]["COMB"][part], ref["points"]["COMB"][part]
np.testing.assert_allclose(got, want, rtol=0, atol=1e-12)
np.testing.assert_allclose(mine["weibull"]["t"], ref["weibull"]["t"], rtol=0, atol=0)
np.testing.assert_allclose(mine["weibull"]["S"], ref["weibull"]["S"], rtol=0, atol=1e-12)
gap = np.nanmax(np.abs(np.subtract(mine["weibull_fractional"]["S"],
ref["weibull_fractional"]["S"]))) # fmt: skip
assert gap <= fractional_tolerance, (mine["escenario"], gap)
# ---------------------------------------------------------------- fast
def test_cohorts(prepared, raws):
sampling = _json("rutinas/MUESTREO.json")["cohortes"]
missing = _json("rutinas/DATOS_FALTANTES.json")["desconocidos_por_covariable"]
for source, c in prepared.items():
assert len(c.frame) == sampling[source]["pacientes"]
assert int(c.frame["evento"].sum()) == sampling[source]["recaidas"]
assert c.eliminated == sampling[source]["eliminadas_por_colinealidad"]
assert c.covariates == list(missing[source])
assert cohorts.unknown_shares(c) == missing[source]
pd.testing.assert_frame_equal(recurrence.cohort(source, raws[source]), c.frame)
assert prepared["metabric"].covariates == VERSION["model"]["covariates"]
def test_routines(prepared):
found = reports.routines(prepared, modeling.N_BOOTSTRAP)
for name, record in found.items():
assert record == _json(f"rutinas/{name}.json"), name
def test_c_index_and_internal_auc(fits):
rows = [r for s in recurrence.SOURCES for r in reports.auc_rows(fits[s])]
assert _auc_rows(rows, False) == _auc_rows(DEVELOPMENT["auc"]["filas"], False)
metrics = reports.metrics(rows)
assert metrics == {k: v for k, v in VERSION["metrics"].items() if "bootstrap" not in k}
def test_saved_model(fits):
"""METABRIC's terms (in order of entry), parents, and their whole-cohort refits."""
tables = modeling.tables(fits["metabric"])
for h, mine in tables.items():
ref = VERSION["model"]["tables"][str(h)]
cpt = {"|".join(k): v for k, v in mine["hbn_cpt"].items()}
assert {**mine, "hbn_cpt": cpt} == ref, h
frame, covariates = fits["metabric"].cohort.frame, fits["metabric"].cohort.covariates
model = recurrence.Recurrence("metabric", recurrence.HORIZONS, covariates, tables)
found = model.predict(frame.iloc[:5])
assert list(found.columns) == ["recurrence_12m", "recurrence_36m", "recurrence_60m"]
t = tables[36]
row = frame.iloc[0]
x = np.array([float(f"{v}_{row[v]}" == term) for term in t["lr_terms"]
for v in [modeling.variable_of(term, model.covariates)]]) # fmt: skip
p_lr = 1 / (1 + np.exp(-(t["lr_constant"] + x @ np.array(t["lr_coefficients"]))))
p_hbn = t["hbn_cpt"][tuple(row[p] for p in t["hbn_parents"])]
assert found["recurrence_36m"].iloc[0] == pytest.approx((p_lr + p_hbn) / 2, abs=1e-15)
@pytest.mark.slow
@slow
def test_calculator(fits):
"""All 60 table rows, and the 20 figures but their fractional Weibull's tolerance."""
records, rows = [], []
for source in recurrence.SOURCES:
found = calculator.calculator(fits[source])
records += found[0]
rows += found[1]
get_reusable_executor().shutdown(wait=True)
table = reports.table(pd.DataFrame(rows).round(4))
assert table["columnas"] == DEVELOPMENT["calculadora"]["columnas"]
_same_rows(table["filas"], DEVELOPMENT["calculadora"]["filas"])
_check_figures(records, FRACTIONAL_TOLERANCE)
def test_risk_factors(fits):
"""All 273 rows, with v1's bootstrap selection shares (the slow test computes them)."""
table = pd.concat(
[factors.risk_factors(fits[s], _reference_selection(s)) for s in recurrence.SOURCES],
ignore_index=True,
)
_same_rows(reports.table(table)["filas"], DEVELOPMENT["factores_riesgo"]["filas"],
FACTOR_TOLERANCE) # fmt: skip
summary = [r for s in recurrence.SOURCES for r in factors.scenario_summary(fits[s], table)]
assert reports.table(summary) == _stages(DEVELOPMENT["escenarios_resumen"])
def test_fractional_weibull_reproduces_the_classic_one():
"""With alpha = beta = 1 the Kilbas-Saigo survival is the classic Weibull's."""
t = np.linspace(0, 300, 61)
for k, lam in ((0.9, 476.0), (2.4, 233.6), (1.3, 60.0)):
found, want = curves.fractional(t, k, 1.0, 1.0, lam), curves.weibull(t, k, lam)
np.testing.assert_allclose(found, want, rtol=0, atol=SOLVER_TOLERANCE)
def _series(z: np.ndarray, rho: float, m: float, l: float, terms: int = 200) -> np.ndarray: # noqa: E741
"""E_{rho,m,l}(z) by its defining series, in floats: exact where |z| is small."""
j = np.arange(terms - 1)
log_c = np.concatenate([[0.0], np.cumsum(gammaln(rho * (m * j + l) + 1)
- gammaln(rho * (m * j + l + 1) + 1))]) # fmt: skip
return (np.exp(log_c)[None, :] * z[:, None] ** np.arange(terms)[None, :]).sum(axis=1)
def test_fractional_weibull_solver_matches_the_series():
"""Where the series is exact in floats (|z| < 2), the solver gives it within its error."""
t = np.linspace(0, 72, 289)
for k, a, b, lam in ((1.0, 0.5, 0.7, 80.0), (0.8, 0.9, 0.4, 150.0), (1.3, 0.3, 0.9, 60.0)):
s = k + a - 2
z = -np.exp(gammaln(k + 1) - gammaln(k + a - 1)) * (t / lam) ** (k + a + b - 2)
assert np.abs(z).max() < 2
found, want = curves.fractional(t, k, a, b, lam), _series(z, b, s / b + 1, s / b)
np.testing.assert_allclose(found, want, rtol=0, atol=SOLVER_TOLERANCE)
# ---------------------------------------------------------------- slow: the whole v1 run
@pytest.mark.slow
@slow
def test_train_reproduces_v1(raws):
model, metrics, found = recurrence.train(raws, bootstrap=True)
assert metrics == VERSION["metrics"]
for h in recurrence.HORIZONS:
mine = model.tables[h]
cpt = {"|".join(k): v for k, v in mine["hbn_cpt"].items()}
assert {**mine, "hbn_cpt": cpt} == VERSION["model"]["tables"][str(h)]
technical = found["technical_validation"]
for name, record in technical["rutinas"].items():
assert record == _json(f"rutinas/{name}.json"), name
tables = technical["recurrencia_desarrollo"]["tablas"]
_same_rows(tables["auc"]["filas"], DEVELOPMENT["auc"]["filas"])
_same_rows(tables["calculadora"]["filas"], DEVELOPMENT["calculadora"]["filas"])
_same_rows(tables["factores_riesgo"]["filas"], DEVELOPMENT["factores_riesgo"]["filas"],
FACTOR_TOLERANCE) # fmt: skip
assert tables["escenarios_resumen"] == _stages(DEVELOPMENT["escenarios_resumen"])
figures = found["interpretability"]["recurrencia"]
assert figures["horizons_months"] == [12, 36, 60]
_check_figures(figures["escenarios"], FRACTIONAL_TOLERANCE)
json.dumps(found, allow_nan=False) # JSON-able as it is