Files
models/tests/cama/test_recurrence.py
T

173 lines
11 KiB
Python

"""CaMa's recurrence analysis (`models.cama.recurrence`): the two external cohorts as Luis's preparation reads them, the whole
dataflow over small synthetic cohorts with the same columns (the figures of the scenarios, the tables, the routines the registry
asks for and the saved model), and the model's prediction. Fixtures: `files`, METABRIC- and SCAN-B-shaped files of 700 patients
each whose recurrence depends on grade, size and estrogen receptor, in a temporary folder.
"""
from pathlib import Path
import numpy as np
import pandas as pd
import pytest
from models.cama.recurrence import prep
from models.cama.recurrence.model import RecurrenceModel
from models.cama.recurrence.source import PACKAGE_DATA, ExternalCohorts
from models.dags.training import Scenario, dataflow
N = 700
def _risk(rng, grade, size, er_positive):
return 0.012 * np.exp(0.8 * (grade - 2) + 0.5 * (size > 30) - 0.5 * er_positive)
@pytest.fixture(scope="module")
def files(tmp_path_factory) -> Path:
"""Two files shaped like METABRIC's TSV and SCAN-B's metadata, recurrence exponential in months and faster with a high grade,
a large tumor and no estrogen receptor; 10 % of the SCAN-B rows are men, which the preparation leaves out."""
rng = np.random.default_rng(5)
folder = tmp_path_factory.mktemp("externas")
grade = rng.choice([1, 2, 3], N, p=[0.2, 0.45, 0.35])
size = rng.gamma(4, 7, N)
er = rng.random(N) < 0.7
months = rng.exponential(1 / _risk(rng, grade, size, er))
followed = np.minimum(months, rng.uniform(30, 150, N))
event = months <= followed
common = lambda: rng.choice(["Positive", "Negative"], N, p=[0.5, 0.5])
pd.DataFrame({
"Patient ID": [f"M{i}" for i in range(N)], "Relapse Free Status": np.where(event, "1:Recurred", "0:Not Recurred"),
"Relapse Free Status (Months)": followed, "Age at Diagnosis": rng.normal(60, 12, N).clip(25, 90), "Tumor Size": size,
"Lymph nodes examined positive": rng.integers(0, 9, N), "Neoplasm Histologic Grade": grade.astype(float),
"Mutation Count": rng.integers(1, 12, N), "ER Status": np.where(er, "Positive", "Negative"), "PR Status": common(),
"HER2 Status": rng.choice(["Positive", "Negative"], N, p=[0.15, 0.85]),
"Pam50 + Claudin-low subtype": rng.choice(["LumA", "LumB", "Basal", "Her2"], N), "Cancer Type Detailed": rng.choice(["Ductal", "Lobular"], N),
"Cellularity": rng.choice(["High", "Moderate", "Low"], N), "Inferred Menopausal State": rng.choice(["Post", "Pre"], N),
"Integrative Cluster": rng.choice(list("12345"), N), "Primary Tumor Laterality": rng.choice(["Left", "Right"], N),
"Type of Breast Surgery": rng.choice(["MASTECTOMY", "BREAST CONSERVING"], N), "Chemotherapy": rng.choice(["YES", "NO"], N),
"Radio Therapy": rng.choice(["YES", "NO"], N), "Hormone Therapy": rng.choice(["YES", "NO"], N),
}).to_csv(folder / prep.FILES["metabric"], sep="\t", index=False)
days = followed * prep.DAYS_PER_MONTH
pd.DataFrame({
"PatientName": [f"S{i}" for i in range(N)], "Gender": np.where(rng.random(N) < 0.1, "M", "F"), "RFI_event": event.astype(int),
"RFI_days": days, "OS_event": rng.integers(0, 2, N), "Age_5year_bin": rng.choice([42, 47, 52, 57, 62, 67, 72, 77], N),
"TumorSize_mm": size, "NodeMetSpec": rng.choice(["NodeNegative", "1to3", "4toX"], N), "NHG": np.array(["Grade1", "Grade2", "Grade3"])[grade - 1],
"ER": np.where(er, "Positive", "Negative"), "PR": common(), "HER2": rng.choice(["Positive", "Negative"], N, p=[0.15, 0.85]),
"Ki67": rng.choice(["High", "Low"], N), "ClinicalSubtype": rng.choice(["Luminal A", "Basal-like", "Luminal B HER2-"], N),
"Histology": rng.choice(["Ductal", "Lobular"], N), "MenopauseStatus_bin": rng.choice(["Post", "Pre"], N), "Laterality": rng.choice(["Left", "Right"], N),
"tnm_ClinicalStage": rng.choice(["I", "II", "III"], N), "SurgeryType": rng.choice(["Mastectomy", "Lumpectomy"], N),
"Chemotherapy": rng.choice(["Yes", "No"], N), "Radiation": rng.choice(["Yes", "No"], N), "Endocrine": rng.choice(["Yes", "No"], N),
"AntiHER2": rng.choice(["Yes", "No"], N),
}).to_csv(folder / prep.FILES["scanb"], sep="\t", index=False)
return folder
def test_the_real_cohorts_are_read_as_the_preparation_scripts_read_them():
"""Pins down: METABRIC gives 2,380 patients with time and status of recurrence (964 recurrences) and SCAN-B 8,847 women, with
the covariates as categories (the unknowns one more) and a redundant covariate dropped from each. Fails if a column is read
differently, a patient with no follow-up is kept, or the collinearity rule drops other covariates."""
metabric = prep.prepare_metabric(str(PACKAGE_DATA / prep.FILES["metabric"]), 0.80)
scanb = prep.prepare_scanb(str(PACKAGE_DATA / prep.FILES["scanb"]), 0.80)
assert (len(metabric.cohort), int(metabric.cohort["evento"].sum())) == (2380, 964)
assert len(scanb.cohort) == 8847 and "Gender" not in scanb.cohort
assert metabric.eliminated == ["HER2"] and "HER2" not in metabric.covariates
assert set(scanb.eliminated) == {"Receptor_estrogeno", "HER2", "Receptor_progesterona"}
assert set(metabric.cohort["Edad"]) <= {"<45", "45-59", "60-74", "75+", "Desconocido"}
assert metabric.treatment == ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"]
def test_the_dataflow_gives_the_figures_the_tables_the_routines_and_the_model(files):
"""Pins down: the dataflow over small cohorts gives a figure for each scenario with enough recurrences (the Kaplan-Meier with
its band, both Weibull and the combined recurrence-free probability at each horizon with its interval), the tables behind
them, the five routines the registry asks for and a model whose probabilities are in [0, 1]. Fails if a stage stops
feeding the next, the figures lose a curve or a routine is missing."""
scenario = Scenario.load("cama", "recurrence")
config = {"recurrence": {**scenario.config["recurrence"], "data_dir": str(files), "horizons": [12, 36], "n_bootstrap_metabric": 2,
"n_bootstrap_scanb": 2, "n_boot_calc": 3, "min_events": 5, "ks_seconds": 2, "max_parents": 3}}
dr = dataflow(*scenario.modules, config=config)
r = dr.execute(["population", "metrics", "routines", "fitted_model", "prepared"])
figures = r["population"]["recurrencia"]["escenarios"]
assert figures and {f["cohorte"] for f in figures} <= {"metabric", "scanb"}
one = figures[0]
assert set(one) >= {"escenario", "condiciones", "n", "recaidas", "km", "weibull", "weibull_fractional", "points"}
comb = one["points"]["COMB"]
assert len(comb["S"]) == 2 and all(lo <= s <= hi + 1e-9 for lo, s, hi in zip(comb["low"], comb["S"], comb["high"]))
assert len(one["km"]["S"]) == len(one["km"]["low"]) == one["observado_hasta"] + 1
assert {"auc", "factores_riesgo", "calculadora", "escenarios_resumen"} <= set(r["population"]["recurrencia_desarrollo"]["tablas"])
assert set(r["routines"]) == {"MUESTREO", "DATOS_FALTANTES", "METODO_ANALITICO", "BALANCE_CLASES", "CONFIANZA_SALIDA"}
assert r["metrics"] and all(isinstance(v, float) for v in r["metrics"].values())
assert len(r["prepared"]["scanb"].cohort) < N # the men are left out
model: RecurrenceModel = r["fitted_model"]
p = model.predict_proba(r["prepared"]["metabric"].cohort.head(50))
assert p.shape == (50, 2) and ((p >= 0) & (p <= 1)).all()
def test_the_external_cohorts_are_the_versions_reference_and_the_files_are_hashed(files):
"""Pins down: the reference the version is traced to is the hash of the two files, as a reference source and not a platform
build, and a different file is a different reference. Fails if a change in the data does not change the reference (a retrain
would then be skipped) or the version cannot be promoted for want of a cohort link."""
from models.io.lineage import COHORT_BUILD_TAG, COHORT_SOURCE_TAG
from models.io.registry import REFERENCE_SOURCE
source = ExternalCohorts(files)
before = source.reference()[COHORT_BUILD_TAG]
(files / prep.FILES["metabric"]).write_text((files / prep.FILES["metabric"]).read_text() + "\n")
assert source.reference()[COHORT_SOURCE_TAG] == REFERENCE_SOURCE and len(before) == 64
assert ExternalCohorts(files).reference()[COHORT_BUILD_TAG] != before
def test_a_version_trains_registers_and_publishes_its_figures(files, mlflow_tracking):
"""Pins down: training the scenario on its files registers a PROD version that carries the figures the dashboard draws
(`analisis/recurrencia.json`), the tables, the routines, the metrics and the saved model, linked to the files' hash, so that
only the human reports stand between it and promotion. Fails if the version cannot be saved, loses its figures, or fails a
promotion check that is not the reports."""
import dataclasses
import json
from models.dags.training import train
from models.io.registry import registry
scenario = Scenario.load("cama", "recurrence")
tiny = {**scenario.config["recurrence"], "data_dir": str(files), "horizons": [12, 36], "n_bootstrap_metabric": 2, "n_bootstrap_scanb": 2,
"n_boot_calc": 3, "min_events": 5, "ks_seconds": 2, "max_parents": 3}
scenario = dataclasses.replace(scenario, config={"recurrence": tiny})
version = train(scenario, ExternalCohorts(files), "PROD")
_, figures = registry.artifact("cama", "recurrence", version, "analisis/recurrencia.json")
_, tables = registry.artifact("cama", "recurrence", version, "analisis/recurrencia_desarrollo.json")
assert json.loads(figures)["escenarios"] and "auc" in json.loads(tables)["tablas"]
checks = {c.code: c.passed for c in registry.checks("cama", "recurrence", version)}
assert all(checks[code] for code in ("ML-02", "ML-03", "ML-01a", "ML-01b"))
assert not checks["MLD-01b"] and not checks["MLD-03"] # the reports are the human gate
def test_the_cli_trains_and_leaves_the_version_waiting_for_its_reports(files, mlflow_tracking, monkeypatch, capsys):
"""Pins down: `models run cama recurrence --train --promote` (what a governance job runs) trains the version, says "trained", then
refuses to promote it for want of its reports with the message the job reads ("not promoted, missing") and exit code 1; run
again it finds the version already trained. Fails if the entry point cannot run (a missing import), trains twice, or
promotes without the human reports."""
import argparse
import dataclasses
from models.cama.recurrence.steps import run_steps
scenario = Scenario.load("cama", "recurrence")
tiny = {**scenario.config["recurrence"], "data_dir": str(files), "horizons": [12, 36], "n_bootstrap_metabric": 2, "n_bootstrap_scanb": 2,
"n_boot_calc": 3, "min_events": 5, "ks_seconds": 2, "max_parents": 3}
monkeypatch.setattr(Scenario, "load", classmethod(lambda cls, domain, name: dataclasses.replace(scenario, config={"recurrence": tiny})))
args = argparse.Namespace(export=False, estimate=False, store=False, version=None, train=True, promote=True, environment="prod",
domain="cama", scenario="recurrence")
first = run_steps(args)
out = capsys.readouterr()
second = run_steps(args)
again = capsys.readouterr()
assert first == 1 and "trained: version 1" in out.out and "not promoted, missing" in out.err
assert second == 1 and "already trained: version 1" in again.out