Files read by hash; fractional Weibull solved and fitted to convergence; recurrence reads its reference cohorts from the platform
This commit is contained in:
@@ -94,7 +94,7 @@ def test_a_site_reaches_bronze_once_and_its_documents_are_read(platform, tmp_pat
|
||||
assert query(corrected) == [("64000",)]
|
||||
|
||||
read = query("select id, text, ocr, error from bronze.n__site__archivos_text")
|
||||
assert all(error is None for *_, error in read)
|
||||
assert [error for *_, error in read if error is not None] == []
|
||||
space = re.compile(r"\s+")
|
||||
by_id = {i: (space.sub(" ", txt), ocr) for i, txt, ocr, _ in read}
|
||||
for r in by_place["ArchivosUni"]:
|
||||
|
||||
+77
-19
@@ -1,37 +1,49 @@
|
||||
"""CaMa recurrence reproduces v1 (MLflow run 0e5ea82e, the reference fixtures) from the two
|
||||
published raw files (`CAMA_REFERENCE_DIR`, default ~/camaSupervivencia).
|
||||
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 not reproducible (v1
|
||||
stopped its fit on a 60-second wall clock): within FRACTIONAL_TOLERANCE of v1's curve.
|
||||
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 (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.
|
||||
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.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
|
||||
# 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 cohorts.FILES.values()), reason="no reference raw files"
|
||||
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")
|
||||
|
||||
@@ -45,13 +57,26 @@ DEVELOPMENT = _json("analisis/recurrencia_desarrollo.json")["tablas"] if V1.exis
|
||||
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 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():
|
||||
return {s: cohorts.prepare(s, raw) for s, raw in _raws().items()}
|
||||
def prepared(raws):
|
||||
return {s: cohorts.prepare(s, raw) for s, raw in raws.items()}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
@@ -64,7 +89,20 @@ def fits(prepared):
|
||||
# ---------------------------------------------------------------- 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
|
||||
@@ -115,8 +153,7 @@ def _check_figures(records: list[dict], fractional_tolerance: float):
|
||||
# ---------------------------------------------------------------- fast
|
||||
|
||||
|
||||
def test_cohorts(prepared):
|
||||
raws = _raws()
|
||||
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():
|
||||
@@ -162,6 +199,8 @@ def test_saved_model(fits):
|
||||
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 = [], []
|
||||
@@ -185,15 +224,34 @@ def test_risk_factors(fits):
|
||||
_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"]
|
||||
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)):
|
||||
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
|
||||
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
|
||||
@@ -201,8 +259,8 @@ def test_fractional_weibull_reproduces_the_classic_one():
|
||||
|
||||
@pytest.mark.slow
|
||||
@slow
|
||||
def test_train_reproduces_v1():
|
||||
model, metrics, found = recurrence.train(_raws(), bootstrap=True)
|
||||
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]
|
||||
@@ -216,7 +274,7 @@ def test_train_reproduces_v1():
|
||||
_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"]
|
||||
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)
|
||||
|
||||
Reference in New Issue
Block a user