"""CaMa recurrence reproduces v1 (MLflow run 0e5ea82e, the reference fixtures) from the two published raw files (`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 not reproducible (v1 stopped its fit on a 60-second wall clock): within FRACTIONAL_TOLERANCE of v1's curve. The full bootstrap (420 resampled fits, ~10 min on 8 cores) is marked `slow` and runs only with RECURRENCE_SLOW=1; the default set takes about two minutes. """ import json import os from pathlib import Path import numpy as np import pandas as pd import pytest from joblib.externals.loky import get_reusable_executor from models.cama import recurrence from models.cama.recurrence import calculator, cohorts, curves, 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" FRACTIONAL_TOLERANCE = 0.05 # max |S| difference to v1's fractional Weibull curve FACTOR_TOLERANCE = 1.01e-4 pytestmark = pytest.mark.skipif( not all((RAW / f).exists() for f in cohorts.FILES.values()), 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 [] def _raws() -> dict[str, pd.DataFrame]: return {s: recurrence.read(s, RAW / f) for s, f in cohorts.FILES.items()} @pytest.fixture(scope="module") def prepared(): 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 def _same_rows(mine: list[dict], ref: list[dict], tolerance: float = 0.0): 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 = _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) 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) == 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)): np.testing.assert_allclose(curves.fractional(t, k, 1.0, 1.0, lam), curves.weibull(t, k, lam), rtol=0, atol=1e-9) # fmt: skip # ---------------------------------------------------------------- slow: the whole v1 run @pytest.mark.slow @slow def test_train_reproduces_v1(): 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"] == 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