CaMa recurrence trains on the loaded METABRIC and SCAN-B patients in the total cohort, not on bundled files; the second survival scenario is retired

This commit is contained in:
Roberto Treviño Cervantes
2026-11-22 19:51:20 -06:00
parent 5a10be44d0
commit b3e02f0980
14 changed files with 182 additions and 17113 deletions
+121 -127
View File
@@ -1,93 +1,119 @@
"""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.
"""What this module covers: CaMa's recurrence analysis (`models.cama.recurrence`) over the total cohort's timeline: each
cohort's patients read by the dictionary (`cohort.recode`), the whole dataflow (the figures of the scenarios, the tables, the
routines the registry asks for and the saved model), training a version from a build, and the import files that put the
cohorts in the platform (`cohort_import`).
Fixtures: `cohort_frame`, a long frame of 600 patients loaded from METABRIC and 600 from SCAN-B (their `fuente`), each with
her birth, an invasive biopsy in 2018-2019 with grade, estrogen receptor, size and nodes, a surgery, and her recurrence or
last contact (recurrence faster with grade 3, a large tumor and no estrogen receptor), plus 20 hospital patients with no
`fuente` that neither cohort takes; `cohort_file`, that frame as a build's Parquet file with its lineage; `mlflow_tracking`
(conftest), a SQLite-backed MLflow.
"""
from pathlib import Path
import dataclasses
import json
from datetime import date, datetime, timedelta, timezone
import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
import pytest
from models.cama.recurrence import prep
from models.cama.recurrence import cohort, cohort_import
from models.cama.recurrence.model import RecurrenceModel
from models.cama.recurrence.source import PACKAGE_DATA, ExternalCohorts
from models.dags.training import Scenario, dataflow
from models.dags.training import Scenario, dataflow, train
from models.io.contracts import COHORT_SCHEMA as SCHEMA
from models.io.storage import CohortFile
from models.steps import indexing
N = 700
N = 600
WINDOW = {"recruitment_start": "2018-01-01", "recruitment_end": "2027-01-01", "cutoff": "2026-12-31"}
LINEAGE = {"url": "cama/cohorte_total", "datos_as_of": "2026-11-21", "parametros": json.dumps(WINDOW)}
SMALL = {"horizons": [12, 36], "n_bootstrap_metabric": 2, "n_bootstrap_scanb": 2, "n_boot_calc": 3, "min_events": 5,
"ks_seconds": 2, "max_parents": 3}
def _risk(rng, grade, size, er_positive):
return 0.012 * np.exp(0.8 * (grade - 2) + 0.5 * (size > 30) - 0.5 * er_positive)
def _row(pac_id, when, first, tipo, valor=None, numero=None, source_id=None):
return {"pac_id": pac_id, "fecha_indice": first, "fecha": when, "conocida_en": datetime(2026, 11, 21, tzinfo=timezone.utc),
"clase": "medicion", "tipo": tipo, "codigo": tipo, "valor_codigo": valor, "valor_numerico": numero,
"fuente_tabla": "silver", "fuente_id": source_id or f"{pac_id}-{tipo}"}
def _patient(rng, pac_id, source):
index = date(2018, 1, 1) + timedelta(days=int(rng.integers(0, 540)))
grade, er = str(rng.choice(["G1", "G2", "G3"])), bool(rng.random() < 0.7)
size, nodes = float(rng.gamma(4, 7)), int(rng.integers(0, 9))
rate = 0.012 * np.exp(0.8 * (int(grade[1]) - 2) + 0.5 * (size > 30) - 0.5 * er)
months, followed = rng.exponential(1 / rate), rng.uniform(30, 90)
end = index + timedelta(days=int(min(months, followed) * 30.4375))
born = index - timedelta(days=int(rng.normal(60, 12) * 365.25))
rows = [_row(pac_id, born, born, "nacimiento")]
if source:
rows.append(_row(pac_id, born, born, "fuente", source))
rows += [_row(pac_id, index, born, "biopsia", "CARCINOMA_INVASOR"), _row(pac_id, index, born, "grado_nottingham", grade),
_row(pac_id, index, born, "receptor_estrogeno", "POSITIVO" if er else "NEGATIVO"),
_row(pac_id, index, born, "tamano_tumor_mm", numero=size), _row(pac_id, index, born, "ganglios_positivos", numero=float(nodes)),
_row(pac_id, index, born, "cirugia", str(rng.choice(["MASTECTOMIA_TOTAL", "SEGMENTECTOMIA"])))]
rows.append(_row(pac_id, end, born, "recurrencia" if months <= followed else "ultimo_contacto"))
return rows
@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."""
def cohort_frame():
"""METABRIC's patients are 1-600, SCAN-B's 1001-1600, and 2001-2020 are the hospital's own."""
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
rows = []
for offset, source in ((0, "METABRIC"), (1000, "SCANB")):
for i in range(1, N + 1):
rows += _patient(rng, offset + i, source)
for i in range(2001, 2021):
rows += _patient(rng, i, None)
return pd.DataFrame(rows, columns=SCHEMA.names)
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"]
@pytest.fixture
def cohort_file(cohort_frame, tmp_path):
"""The frame as build 4's file, with the lineage a dbt build gives."""
table = pa.Table.from_pandas(cohort_frame, schema=SCHEMA, preserve_index=False)
path = tmp_path / "4.parquet"
pq.write_table(table.replace_schema_metadata({**LINEAGE, "armado_id": "4"}), path)
return path
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)
def _small(scenario: Scenario) -> Scenario:
return dataclasses.replace(scenario, config={**scenario.config, "recurrence": {**scenario.config["recurrence"], **SMALL}})
r = dr.execute(["population", "metrics", "routines", "fitted_model", "prepared"])
def test_each_cohort_takes_only_the_patients_loaded_from_it(cohort_frame):
"""Pins down: METABRIC's frame has its 600 patients and SCAN-B's its own, with the follow-up in months from the biopsy,
the recurrence as the event and the dictionary's categories (the unknown one more), once the scenario's index (the first
invasive biopsy) is set; the hospital's patients are in neither. Fails if `recode` stops filtering by `fuente`, reads another index, or a rule maps a code to another category."""
model = cohort.load()
indexed = indexing.cohort(cohort_frame, LINEAGE, Scenario.load("cama", "recurrence").config["index"])
metabric = cohort.recode(indexed, model, "metabric")
scanb = cohort.recode(indexed, model, "scanb")
assert len(metabric) == N and set(metabric["paciente"]) == set(range(1, N + 1))
assert len(scanb) == N and set(scanb["paciente"]) == set(range(1001, 1001 + N))
assert (metabric["tiempo_meses"] > 0).all() and 0 < metabric["evento"].sum() < N
assert set(metabric["Grado_histologico"]) == {"1", "2", "3"}
assert set(metabric["Receptor_estrogeno"]) == {"Positive", "Negative"}
assert set(metabric["Cirugia"]) == {"MASTECTOMY", "BREAST CONSERVING"} and set(scanb["Cirugia"]) == {"Mastectomy", "Lumpectomy"}
assert set(metabric["Subtipo_PAM50"]) == {"Desconocido"}
def test_the_dataflow_gives_the_figures_the_tables_the_routines_and_the_model(cohort_frame):
"""Pins down: the dataflow over the total cohort's timeline 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 = _small(Scenario.load("cama", "recurrence"))
dr = dataflow(*scenario.modules, config=scenario.config)
r = dr.execute(["population", "metrics", "routines", "fitted_model", "prepared"],
inputs={"source_cohort": cohort_frame, "cohort_lineage": LINEAGE})
figures = r["population"]["recurrencia"]["escenarios"]
assert figures and {f["cohorte"] for f in figures} <= {"metabric", "scanb"}
@@ -95,78 +121,46 @@ def test_the_dataflow_gives_the_figures_the_tables_the_routines_and_the_model(fi
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
assert len(r["prepared"]["metabric"].cohort) == len(r["prepared"]["scanb"].cohort) == N
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
def test_a_version_trains_from_a_build_registers_and_publishes_its_figures(cohort_file, mlflow_tracking):
"""Pins down: training the scenario on a build of the total cohort registers a PROD version that carries the figures the
dashboard draws (`analisis/recurrencia.json`) and the tables. Fails if the version cannot be saved or loses its figures."""
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")
version = train(_small(Scenario.load("cama", "recurrence")), CohortFile(cohort_file), "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
def test_the_import_files_place_the_diagnoses_in_a_window_and_end_the_follow_up_at_the_censor():
"""Pins down: with `diagnosis_from` every diagnosis falls in the given span (the same day for the same patient), and with
`censor` no date is after it: a recurrence after it becomes a last contact on that day. Fails if the dictionary's fixed year
is kept, the spread depends on the row order, or a follow-up runs past the censor."""
raw = pd.DataFrame({"Patient ID": ["A", "B", "C"], "Relapse Free Status": ["1:Recurred", "0:Not Recurred", "1:Recurred"],
"Relapse Free Status (Months)": ["10", "200", "120"], "Age at Diagnosis": ["50", "61", "70"]})
model = cohort_import.load()
named = [s["metabric"]["column"] for s in model["variables"].values() if isinstance(s, dict) and "column" in s.get("metabric", {})]
raw = raw.reindex(columns=[*raw.columns, *named], fill_value="")
from models.cama.recurrence.steps import run_steps
tables = cohort_import.convert(raw, "metabric", model, diagnosis_from="2018-01-01", spread_days=540,
censor="2026-11-21")
again = cohort_import.convert(raw.iloc[::-1], "metabric", model, diagnosis_from="2018-01-01",
spread_days=540, censor="2026-11-21")
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
diagnosis = pd.to_datetime(tables["BiopsiaMama"].set_index("pac_id_hospital")["bx_fecha_reporte"])
assert diagnosis.between("2018-01-01", "2019-06-24").all()
assert diagnosis.equals(pd.to_datetime(again["BiopsiaMama"].set_index("pac_id_hospital")["bx_fecha_reporte"]).reindex(diagnosis.index))
follow = tables["SeguimientoMama"].set_index("pac_id_hospital")
assert (pd.to_datetime(follow["seg_fecha"]) <= "2026-11-21").all()
assert follow.loc["METABRIC-A", "seg_tipo"] == "recurrencia"
assert follow.loc["METABRIC-C", "seg_tipo"] == "ultimo_contacto" and follow.loc["METABRIC-C", "seg_fecha"] == "2026-11-21"