"""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. """ 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 cohort, cohort_import from models.cama.recurrence.model import RecurrenceModel 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 = 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 _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 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) 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) @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 _small(scenario: Scenario) -> Scenario: return dataclasses.replace(scenario, config={**scenario.config, "recurrence": {**scenario.config["recurrence"], **SMALL}}) 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"} 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 {"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"]["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_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 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"] 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="") 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") 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"