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
+3
View File
@@ -74,6 +74,9 @@ def recode(events: pd.DataFrame, model: dict, cohort: str, *, of_source: bool =
result[name] = category.replace(labels).to_numpy() if labels else category.to_numpy()
elif spec.get("terciles"):
count = reader.value(spec["source"], True)
if count.notna().sum() == 0:
result[name] = spec["missing"]
continue
q = count.quantile([1 / 3, 2 / 3]).to_numpy()
result[name] = _cut(count, [-1, q[0] + 1e-9, q[1] + 1e-9, 1e6], spec["labels"], spec["missing"]).to_numpy()
else:
+25 -3
View File
@@ -1,16 +1,22 @@
"""METABRIC's and SCAN-B's clinical files as CaMa import files: one CSV per bronze entity, named by the fields the import
schemas take, to be uploaded through the platform's import like any other source.
python -m models.cama.recurrence.cohort_import metabric FILE OUT_DIR
python -m models.cama.recurrence.cohort_import metabric FILE OUT_DIR [--diagnosis-from 2018-01-01 --spread-days 540
--censor 2026-11-21]
What goes where is the dictionary's (`[variables.*]` of `cohorts.toml`): each source category is stored as the catalog value
the dictionary names and read back as the same category. The files record no calendar dates: the diagnosis is a fixed day
of its year, the birth is the diagnosis minus the age (rounded up to a whole day, so a patient on an age cut stays on its upper side), and the recurrence (or the last contact) is the diagnosis plus the
follow-up, and a discharge note closes it: the patients have been treated. A date holds whole days, so the follow-up is stored as the whole-day count nearest to the exact months that keeps
the month it falls in and its side of every horizon.
`--diagnosis-from` places the diagnoses in a window of the platform's own (spread over `--spread-days` days, the same day for
the same patient on every run) in place of the dictionary's fixed year, and `--censor` ends every follow-up by that day: a
recurrence after it is not known yet, and the patient is a last contact on that day.
"""
import argparse
import hashlib
import math
import tomllib
from pathlib import Path
@@ -49,7 +55,13 @@ def _known(raw: pd.Series) -> pd.Series:
return raw.notna() & ~raw.astype(str).str.strip().isin(UNKNOWN)
def convert(raw: pd.DataFrame, cohort: str, model: dict) -> dict[str, pd.DataFrame]:
def _spread(ids: pd.Series, days: int) -> pd.Series:
"""A day in [0, days) per patient, fixed by her identifier."""
return ids.map(lambda i: int.from_bytes(hashlib.sha256(str(i).encode()).digest()[:4], "big") % days)
def convert(raw: pd.DataFrame, cohort: str, model: dict, *, diagnosis_from: str | None = None, spread_days: int = 1,
censor: str | None = None) -> dict[str, pd.DataFrame]:
dictionary = model["variables"]
index = dictionary["index"]
cfg = dictionary["cohorts"][cohort]
@@ -77,8 +89,14 @@ def convert(raw: pd.DataFrame, cohort: str, model: dict) -> dict[str, pd.DataFra
else:
year = pd.Series(int(cfg["diagnosis_year"]), index=frame.index)
diagnosis = pd.to_datetime(year.astype(str) + "-" + cfg["diagnosis_month_day"])
if diagnosis_from:
diagnosis = pd.Timestamp(diagnosis_from) + pd.to_timedelta(_spread(frame[cfg["id"]], spread_days), unit="D")
birth = diagnosis - pd.to_timedelta(np.ceil(age * 365.25), unit="D")
end = diagnosis + pd.to_timedelta(days, unit="D")
if censor:
late = end > pd.Timestamp(censor)
event = event.where(~late, 0)
end = end.where(~late, pd.Timestamp(censor))
ident = cohort.upper() + "-" + frame[cfg["id"]].astype(str)
date = lambda s: s.dt.strftime("%Y-%m-%d")
@@ -146,11 +164,15 @@ def main(argv=None) -> None:
ap.add_argument("cohort", choices=["metabric", "scanb"])
ap.add_argument("file")
ap.add_argument("out_dir")
ap.add_argument("--diagnosis-from", help="first day of the diagnoses (YYYY-MM-DD); the dictionary's year without it")
ap.add_argument("--spread-days", type=int, default=1, help="days over which the diagnoses are spread")
ap.add_argument("--censor", help="last day of follow-up (YYYY-MM-DD)")
args = ap.parse_args(argv)
raw = pd.read_csv(args.file, sep="\t", dtype=str, low_memory=False, keep_default_na=False)
out = Path(args.out_dir)
out.mkdir(parents=True, exist_ok=True)
for entity, table in convert(raw, args.cohort, load()).items():
for entity, table in convert(raw, args.cohort, load(), diagnosis_from=args.diagnosis_from,
spread_days=args.spread_days, censor=args.censor).items():
table.to_csv(out / f"{args.cohort}_{ENTITIES[entity]}.csv", index=False)
-2
View File
@@ -50,7 +50,6 @@ last_contact_source = "ultimo_contacto"
days_per_month = 30.4375
[variables.cohorts.metabric]
file = "brca_metabric_clinical_data.tsv"
id = "Patient ID"
months = "Relapse Free Status (Months)"
event = "Relapse Free Status" # "1:Recurred" is the event; rows without status or months are dropped
@@ -62,7 +61,6 @@ diagnosis_year = 2000 # METABRIC records no year: a fixed one
# Per covariate, the source columns and category cuts as the preparation script defines them.
[variables.cohorts.scanb]
file = "scanb_clinical_metadata.txt"
id = "PatientName"
months = "RFI_days" # days, divided by days_per_month
months_divisor = 30.4375
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+18 -12
View File
@@ -1,7 +1,8 @@
"""CaMa's recurrence analysis as a scenario: the dataflow from the two external cohorts to the registered model, its results and
its routines. Each node is one stage of Luis's scripts (`prep`, `modeling`, `factors`, `calculator`); the training machinery
(`models.dags.training.train`) saves what the nodes `fitted_model`, `metrics`, `routines` and `population` give. The figures the
dashboard shows are in `population["recurrencia"]`.
"""CaMa's recurrence analysis as a scenario: the dataflow from the cohort's patients loaded from METABRIC and SCAN-B (the
`fuente` of each, indexed at her first invasive biopsy) to the registered model, its results and its routines. Each node is one
stage of Luis's scripts (`prep`, `modeling`, `factors`, `calculator`); the training machinery (`models.dags.training.train`)
saves what the nodes `fitted_model`, `metrics`, `routines` and `population` give. The figures the dashboard shows are in
`population["recurrencia"]`.
"""
import numpy as np
@@ -11,17 +12,22 @@ import statsmodels.api as sm
from models.cama.recurrence import calculator as calc
from models.cama.recurrence import factors as fac
from models.cama.recurrence import modeling
from models.cama.recurrence.prep import FILES, PREPARE, Prepared
from models.cama.recurrence.source import data_folder
from models.cama.recurrence.steps import run_steps # noqa: F401 (the CLI's own steps: not a node)
from models.cama.recurrence import cohort as timeline
from models.cama.recurrence.prep import Prepared, finish
COHORTS = ("metabric", "scanb")
def prepared(recurrence: dict) -> dict[str, Prepared]:
"""Each cohort as one table of categories with its covariates (`prep`)."""
folder = data_folder(recurrence["data_dir"])
return {name: PREPARE[name](str(folder / FILES[name]), recurrence["v_max"]) for name in COHORTS}
def dictionary() -> dict:
"""The variables, cohorts and scenarios of `cohorts.toml`."""
return timeline.load()
def prepared(cohort: pd.DataFrame, dictionary: dict, recurrence: dict) -> dict[str, Prepared]:
"""Each cohort's patients as one table of categories with its covariates (`cohort.recode`, then `prep`)."""
fixed = ["paciente", "tiempo_meses", "evento"]
return {name: finish(timeline.recode(cohort, dictionary, name), fixed, dictionary["cohorts"][name]["treatment"],
recurrence["v_max"]) for name in COHORTS}
def fits(prepared: dict[str, Prepared], recurrence: dict) -> dict[str, modeling.CohortModels]:
@@ -122,7 +128,7 @@ def routines(prepared: dict[str, Prepared], fits: dict[str, modeling.CohortModel
return {
"MUESTREO": {"cohortes": {n: {"pacientes": len(p.cohort), "recaidas": int(p.cohort["evento"].sum()), "covariables": len(p.covariates),
"eliminadas_por_colinealidad": p.eliminated} for n, p in prepared.items()},
"criterio": "pacientes con tiempo y estado de recaída; SCAN-B solo mujeres", "origen": "METABRIC y SCAN-B (externas)"},
"criterio": "pacientes con tiempo y estado de recaída; SCAN-B solo mujeres", "origen": "pacientes cargadas de METABRIC y SCAN-B (`fuente`)"},
"DATOS_FALTANTES": {"criterio": "el dato faltante es una categoría más («Desconocido»); no se imputa ni se descarta",
"desconocidos_por_covariable": {n: {c: float((p.cohort[c] == "Desconocido").mean()) for c in p.covariates} for n, p in prepared.items()}},
"METODO_ANALITICO": {"modelos": "regresión logística con selección stepwise y red bayesiana con padres del desenlace por BDeu, uno por horizonte",
+11 -8
View File
@@ -1,20 +1,18 @@
# CaMa recurrence analysis: the risk of recurrence by clinical scenario, from two external cohorts (METABRIC and SCAN-B).
# Trained from governance on the files in `data/`; the scenarios' figures are what the dashboard shows. Its covariates are the
# cohorts' own; the hospital's patient is placed in the scenarios her covariates meet.
# CaMa recurrence analysis: the risk of recurrence by clinical scenario, trained on the patients loaded from METABRIC and
# SCAN-B (`cohort_import`, through the platform's import) and read from the database by the dictionary of `cohorts.toml`.
# The scenarios' figures are what the dashboard shows; the hospital's patient is placed in the scenarios her covariates meet.
domain = "cama"
scenario = "recurrence"
cohort = "cama/externa"
cohort = "cama/cohorte_total"
outcome = "recurrencia"
external = true # trained on files, not on a dbt cohort of the platform
modules = ["models.cama.recurrence.model"]
modules = ["models.cama.recurrence.model", "models.steps.indexing"]
description = """\
Análisis de recurrencia: probabilidad de que la enfermedad regrese a los 12, 36 y 60 meses por escenario clínico, con una \
regresión logística y una red bayesiana por horizonte, entrenadas en dos cohortes externas (METABRIC y SCAN-B). Pendiente \
regresión logística y una red bayesiana por horizonte, entrenadas con las pacientes cargadas de dos cohortes externas (METABRIC y SCAN-B). Pendiente \
de validación clínica."""
requirements = ["pandas", "numpy", "scipy", "scikit-learn", "statsmodels", "pgmpy", "lifelines", "mpmath"]
[config.recurrence]
data_dir = "" # empty: the `data/` folder of this package
horizons = [12, 36, 60] # months
v_max = 0.80 # Cramér's V from which of two covariates the one with more unknowns is dropped
seed = 42
@@ -31,3 +29,8 @@ n_boot_calc = 200 # replicas of each scenario's interval
min_events = 15 # recurrences a scenario needs to be drawn
cap_months = 72 # the figure's time axis
ks_seconds = 60 # time budget of each fractional Weibull fit
[config.index]
kind = "primera_biopsia_invasora"
event_grades = ["CARCINOMA_INVASOR"]
observacion_previa_minima_dias = 0
+4 -61
View File
@@ -1,6 +1,6 @@
"""The recurrence analysis' data: the two external cohorts (METABRIC and SCAN-B) as one table each, the covariates as
categories with the unknowns as one more, and the redundant covariates (Cramér's V at or above the limit) dropped. Ported
from `01_preparacion_metabric.py` and `02_preparacion_scanb.py`.
"""The recurrence analysis' data: each cohort's patients (`cohort.recode`) as one table, the covariates as categories with
the unknowns as one more, and the redundant covariates (Cramér's V at or above the limit) dropped, as in
`01_preparacion_metabric.py` and `02_preparacion_scanb.py`.
"""
from dataclasses import dataclass
@@ -9,7 +9,6 @@ import numpy as np
import pandas as pd
from scipy.stats import chi2_contingency
DAYS_PER_MONTH = 30.4375
AGE_CUTS, AGE_LABELS = [0, 45, 60, 75, 200], ["<45", "45-59", "60-74", "75+"]
SIZE_CUTS, SIZE_LABELS = [0, 20.01, 50.01, 1e4], ["<=20 mm", "21-50 mm", ">50 mm"]
NODE_CUTS, NODE_LABELS = [0, 1, 4, 1e3], ["0", "1-3", "4+"]
@@ -23,14 +22,6 @@ class Prepared:
eliminated: list[str]
def _unknown(s: pd.Series) -> pd.Series:
return s.astype("object").where(s.notna(), "Desconocido").astype(str)
def _cut(s: pd.Series, cuts: list, labels: list) -> pd.Series:
return _unknown(pd.cut(s, cuts, labels=labels, right=False).astype("object"))
def cramer_v(a: pd.Series, b: pd.Series) -> float:
table = pd.crosstab(a, b)
chi2 = chi2_contingency(table, correction=False)[0]
@@ -54,55 +45,7 @@ def _drop_collinear(out: pd.DataFrame, covariates: list[str], treatment: list[st
return covariates, eliminated
def _finish(out: pd.DataFrame, fixed: list[str], treatment: list[str], v_max: float) -> Prepared:
def finish(out: pd.DataFrame, fixed: list[str], treatment: list[str], v_max: float) -> Prepared:
covariates = [c for c in out.columns if c not in fixed]
covariates, eliminated = _drop_collinear(out, covariates, treatment, v_max)
return Prepared(out[[*fixed, *covariates]], covariates, [c for c in treatment if c in covariates], eliminated)
def prepare_metabric(path: str, v_max: float) -> Prepared:
d = pd.read_csv(path, sep="\t")
d = d.dropna(subset=["Relapse Free Status", "Relapse Free Status (Months)"]).reset_index(drop=True)
out = pd.DataFrame({"paciente": d["Patient ID"]})
out["tiempo_meses"] = d["Relapse Free Status (Months)"].astype(float)
out["evento"] = d["Relapse Free Status"].str.startswith("1").astype(int)
out["Edad"] = _cut(d["Age at Diagnosis"], AGE_CUTS, AGE_LABELS)
out["Tamano_tumor"] = _cut(d["Tumor Size"], SIZE_CUTS, SIZE_LABELS)
out["Ganglios_positivos"] = _cut(d["Lymph nodes examined positive"], NODE_CUTS, NODE_LABELS)
out["Grado_histologico"] = _unknown(d["Neoplasm Histologic Grade"].map({1.0: "1", 2.0: "2", 3.0: "3"}))
mutations = d["Mutation Count"]
q = mutations.quantile([1 / 3, 2 / 3]).values
out["Carga_mutacional"] = _cut(mutations, [-1, q[0] + 1e-9, q[1] + 1e-9, 1e6], ["baja", "media", "alta"])
for name, column in [("Receptor_estrogeno", "ER Status"), ("Receptor_progesterona", "PR Status"), ("HER2", "HER2 Status"),
("Subtipo_PAM50", "Pam50 + Claudin-low subtype"), ("Tipo_histologico", "Cancer Type Detailed"),
("Celularidad", "Cellularity"), ("Estado_menopausico", "Inferred Menopausal State"),
("Cluster_integrativo", "Integrative Cluster"), ("Lateralidad", "Primary Tumor Laterality"),
("Cirugia", "Type of Breast Surgery"), ("Quimioterapia", "Chemotherapy"),
("Radioterapia", "Radio Therapy"), ("Hormonoterapia", "Hormone Therapy")]:
out[name] = _unknown(d[column])
return _finish(out, ["paciente", "tiempo_meses", "evento"], ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"], v_max)
def prepare_scanb(path: str, v_max: float) -> Prepared:
d = pd.read_csv(path, sep="\t", low_memory=False)
d = d[d["Gender"] == "F"].dropna(subset=["RFI_event", "RFI_days"]).reset_index(drop=True)
out = pd.DataFrame({"paciente": d["PatientName"]})
out["tiempo_meses"] = d["RFI_days"].astype(float) / DAYS_PER_MONTH
out["evento"] = d["RFI_event"].astype(int)
out["muerte_sin_recaida"] = ((d["OS_event"] == 1) & (d["RFI_event"] == 0)).astype(int)
out["Edad"] = _cut(d["Age_5year_bin"].astype(float) - 2, AGE_CUTS, AGE_LABELS)
out["Tamano_tumor"] = _cut(d["TumorSize_mm"], SIZE_CUTS, SIZE_LABELS)
out["Ganglios_positivos"] = _unknown(d["NodeMetSpec"].map({"NodeNegative": "0", "SubMicroMet": "0", "1to3": "1-3", "4toX": "4+"}))
out["Grado_histologico"] = _unknown(d["NHG"].map({"Grade1": "1", "Grade2": "2", "Grade3": "3"}))
for name, column in [("Receptor_estrogeno", "ER"), ("Receptor_progesterona", "PR"), ("HER2", "HER2"), ("Ki67", "Ki67"),
("Subtipo_clinico", "ClinicalSubtype"), ("Tipo_histologico", "Histology"),
("Estado_menopausico", "MenopauseStatus_bin"), ("Lateralidad", "Laterality"),
("Estadio_clinico", "tnm_ClinicalStage"), ("Cirugia", "SurgeryType"), ("Quimioterapia", "Chemotherapy"),
("Radioterapia", "Radiation"), ("Hormonoterapia", "Endocrine"), ("AntiHER2", "AntiHER2")]:
out[name] = _unknown(d[column])
return _finish(out, ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"],
["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"], v_max)
PREPARE = {"metabric": prepare_metabric, "scanb": prepare_scanb}
FILES = {"metabric": "brca_metabric_clinical_data.tsv", "scanb": "scanb_clinical_metadata.txt"}
-42
View File
@@ -1,42 +0,0 @@
"""The recurrence analysis' training data: two files on disk, not a cohort of the platform. It takes the part of a cohort source
(`models.io.storage.CohortSource`) for the training run: the reference the version is traced to, which is the hash of the files."""
import hashlib
from dataclasses import dataclass
from pathlib import Path
import pandas as pd
from models.cama.recurrence.prep import FILES
from models.io.lineage import COHORT_BUILD_TAG, COHORT_SOURCE_TAG, COHORT_URL_TAG
from models.io.registry import REFERENCE_SOURCE
PACKAGE_DATA = Path(__file__).parent / "data"
URL = "cama/externa/metabric+scanb"
def data_folder(configured: str) -> Path:
return Path(configured) if configured else PACKAGE_DATA
@dataclass
class ExternalCohorts:
"""The METABRIC and SCAN-B files of a folder."""
folder: Path = PACKAGE_DATA
armado_id: int | None = None
def sha256(self) -> str:
digest = hashlib.sha256()
for name in sorted(FILES.values()):
digest.update((self.folder / name).read_bytes())
return digest.hexdigest()
def frame(self) -> pd.DataFrame:
return pd.DataFrame()
def lineage(self) -> dict[str, str]:
return {"url": URL, "files": ",".join(sorted(FILES.values())), "sha256": self.sha256()}
def reference(self) -> dict[str, str]:
return {COHORT_URL_TAG: URL, COHORT_SOURCE_TAG: REFERENCE_SOURCE, COHORT_BUILD_TAG: self.sha256()}
-31
View File
@@ -1,31 +0,0 @@
"""`models run cama recurrence --train --promote`: this scenario trains on its files, not on a cohort build."""
import argparse
import sys
def run_steps(args: argparse.Namespace) -> int:
"""`models run cama recurrence --train --promote`: this scenario trains on its files, not on a cohort build."""
from models.__main__ import _promote_step
from models.cama.recurrence.source import ExternalCohorts, data_folder
from models.dags.training import Scenario, find_trained, train
if args.export or args.estimate or args.store or args.version:
print("cama/recurrence trains on its external cohorts: only --train and --promote apply", file=sys.stderr)
return 2
scenario = Scenario.load("cama", "recurrence")
source = ExternalCohorts(data_folder(scenario.config["recurrence"]["data_dir"]))
environment = args.environment.upper()
version = find_trained(scenario, source, environment)
if args.train:
if version:
print(f"already trained: version {version}, from {source.lineage()['sha256'][:12]}")
else:
version = train(scenario, source, environment)
print(f"trained: version {version}, from {source.lineage()['sha256'][:12]}")
if args.promote:
if not version:
print(f"no {environment} version trained: use --train", file=sys.stderr)
return 1
return _promote_step(args, version)
return 0
-121
View File
@@ -1,121 +0,0 @@
"""CaMa survival as a registered scenario: from the cohort's long frame to a fitted model, its metrics and the routines'
records. The six stages of the pipeline (`run.py`) are the analysis; the scenario runs the first, the depuration, over the
members' variables and fits the interval models of the survival stage (`seer_model.fit`).
Nodes: `recoded` (the dictionary applied to the cohort), `depurated` (stage 01), `fitted_model`, `metrics` and `routines`.
The cohort's own index, the first invasive biopsy, is `models.steps.indexing`'s (`[config.index]`).
"""
import tempfile
from pathlib import Path
import numpy as np
import pandas as pd
from models.cama.seer_survival import run, variables
from models.cama.seer_survival import seer_model as sm_
from models.cama.seer_survival import survival_curves as sc
from models.cama.seer_survival import survival_models as fits
from models.cama.seer_survival.settings import Settings, load
RECODED_FILE = "dataframe_recodificado.csv"
def settings() -> Settings:
return load()
def dictionary() -> dict:
return variables.load()
def recoded(cohort: pd.DataFrame, dictionary: dict) -> pd.DataFrame:
"""One row per member, in the columns of the variable dictionary."""
return variables.recode(cohort, dictionary)
def depurated(recoded: pd.DataFrame, settings: Settings) -> pd.DataFrame:
"""Stage 01 over the members: the frame without the variables the depuration drops."""
with tempfile.TemporaryDirectory() as folder:
path = Path(folder)
recoded.to_csv(path / RECODED_FILE, index=False)
run.run_depuration(path / RECODED_FILE, path / "sin_mapa.json", path, settings)
return pd.read_csv(path / run.DEPURATED, dtype=str, keep_default_na=False)
def fitted_model(recoded: pd.DataFrame, depurated: pd.DataFrame, dictionary: dict, settings: Settings,
index: dict) -> sm_.SeerSurvivalModel:
return sm_.fit(recoded, depurated, dictionary, settings.survival, index)
def metrics(fitted_model: sm_.SeerSurvivalModel) -> dict:
state = fitted_model.fit_state
return {"members": state.members, "deaths": state.deaths, "covariates": len(state.design.covariates),
"replicas": len(state.replicas),
**{f"weight_lr_interval_{i + 1}": float(w) for i, w in enumerate(state.weights)}}
def sampling(recoded: pd.DataFrame, fitted_model: sm_.SeerSurvivalModel, index_attrition: list, prior_observation: dict,
dictionary: dict) -> dict:
"""MUESTREO: who could be used (the index and each rule's attrition, their prior history), the follow-up and the
resampling."""
s, state = fitted_model.survival, fitted_model.fit_state
return {"method": "toda la cohorte indexada en su primera biopsia invasora; sin partición: la validación es de las "
f"predicciones fuera de muestra en {s.stack_folds} pliegues y de las réplicas bootstrap",
"index_attrition": [[step, int(n)] for step, n in index_attrition], "prior_observation": prior_observation,
"members": state.members, "deaths": state.deaths, "follow_up_cap_months": s.cap_months,
"bootstrap_replicas": len(state.replicas), "stack_folds": s.stack_folds}
def missing_data(recoded: pd.DataFrame, dictionary: dict) -> dict:
"""DATOS_FALTANTES: how many members lack each variable (its `missing` category), and what is done about it."""
counts = {}
for name in variables.variable_names(dictionary):
spec = dictionary[name]
if spec.get("internal"):
continue
counts[name] = int((recoded[variables.column_of(name, spec)] == spec["missing"]).sum())
return {"method": "un dato ausente es la categoría `missing` de su variable en el diccionario; nadie se excluye",
"members": len(recoded), "missing_by_variable": counts}
def analytic_method(fitted_model: sm_.SeerSurvivalModel) -> dict:
"""METODO_ANALITICO: the LR coefficients and the HBN's parents of each interval, and the weights that combine them."""
s, state = fitted_model.survival, fitted_model.fit_state
design = state.design
names = [f"{c}={k}" for c in design.covariates for k in design.sorted_categories[c][1:]]
intervals = []
for (a, b), fit, weight in zip(zip([0] + list(s.horizons[:-1]), s.horizons), state.point, state.weights):
intervals.append({"interval_months": [int(a), int(b)], "weight_lr": float(weight),
"intercept": float(fit.intercept), "coefficients": dict(zip(names, map(float, fit.coef))),
"hbn_parents": [design.covariates[j] for j in fit.parents]})
return {"method": "regresión logística y red bayesiana con tabla de probabilidad por intervalo, combinadas con el peso "
"que maximiza la verosimilitud fuera de muestra", "covariates": design.covariates, "intervals": intervals}
def class_balance(fitted_model: sm_.SeerSurvivalModel, depurated: pd.DataFrame) -> dict:
"""BALANCE_CLASES: the members at risk and the deaths of each interval; none is reweighted but the half weight of a
censoring inside an interval."""
s = fitted_model.survival
frame = sc.survival_frame(depurated, s)
months, event = frame.df["meses_int"].values, frame.df["evento"].values
rows = []
for a, b in zip([0] + list(s.horizons[:-1]), s.horizons):
at_risk = months >= a
rows.append({"interval_months": [int(a), int(b)], "at_risk": int(at_risk.sum()),
"deaths": int((event & at_risk & (months < b)).sum()),
"censored": int(((~event) & at_risk & (months < b)).sum())})
return {"method": "las clases se usan en su proporción observada; una censura dentro de un intervalo pesa la mitad",
"intervals": rows}
def output_confidence(fitted_model: sm_.SeerSurvivalModel) -> dict:
"""CONFIANZA_SALIDA: the survival at each horizon of the members of each decile of predicted survival, out of sample,
against the Kaplan-Meier of those members."""
return {"method": "calibración fuera de muestra: supervivencia predicha contra Kaplan-Meier, por deciles",
"deciles": fitted_model.fit_state.calibration}
def routines(sampling: dict, missing_data: dict, analytic_method: dict, class_balance: dict, output_confidence: dict) -> dict:
return {"MUESTREO": sampling, "DATOS_FALTANTES": missing_data, "METODO_ANALITICO": analytic_method,
"BALANCE_CLASES": class_balance, "CONFIANZA_SALIDA": output_confidence}
-30
View File
@@ -1,26 +1,4 @@
# CaMa SEER survival pipeline: settings of each stage. Paths are never here: they enter the DAG as inputs.
domain = "cama"
scenario = "seer_survival"
cohort = "cama/cohorte_total"
outcome = "survival_18m"
requirements = ["scikit-learn", "numpy", "pandas", "scipy", "statsmodels", "pgmpy", "cloudpickle"]
modules = ["models.cama.seer_survival.model", "models.steps.indexing"]
# The tables whose values make a version a different one (with `[config]`): the depuration, the survival stage's settings
# and the variable dictionary.
settings_tables = ["depuration", "survival", "variables"]
description = """
Supervivencia del cáncer de mama a 6, 12 y 18 meses desde el diagnóstico (primera biopsia con carcinoma invasor): \
regresión logística y red bayesiana por intervalo, combinadas, sobre las variables del diccionario del modelo; \
entrenado y validado con los datos de SEER."""
# The dataflow's config (`with_config`).
[config]
horizons_years = [0.5, 1.0, 1.5]
[config.index]
kind = "primera_biopsia_invasora"
observacion_previa_minima_dias = 0
[depuration]
exclude = ["Outcome_cat"] # never analysed or touched
@@ -271,14 +249,6 @@ conditions = [
{ variable = "Tratamiento_quirurgico", in = ["Conservadora"] }
]
[figure]
# The scenario figure computed on request (`SeerSurvivalModel.figure_record`): the seconds the fractional Weibull may take,
# the least members and deaths a scenario needs to be drawn, and the bootstrap replicas applied (empty: all of the model's).
ks_max_seconds = 30
min_members = 30
min_deaths = 5
n_boot = 100
[risk_factors]
# A category is a risk factor from four criteria: c1 the multivariable OR in the natural population (95 % CI not
# crossing 1 and Benjamini-Hochberg p < alpha), c2 stability: the variable enters the LR stepwise in at least freq_min
-225
View File
@@ -1,225 +0,0 @@
"""The registered CaMa survival model: the dictionary, the covariates the depuration kept, and the interval models of the
survival stage (LR and HBN per interval, the weights that combine them, and the replicas that give their intervals), fitted
on a cohort and kept. It scores any cohort's members from their timelines, and draws a clinical scenario's figure
(`figure_record`): Kaplan-Meier with its Greenwood band, the classic and the fractional Weibull, and the LR / HBN / combined
survival at the horizons with a bootstrap interval.
The fitted state is plain arrays and dictionaries; `rehydrate` puts a saved model's state into the current class, so a
version trained earlier is scored by today's code.
"""
import time
from dataclasses import dataclass, field
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator
from models.cama.seer_survival import fractional_weibull as fw
from models.cama.seer_survival import survival_curves as sc
from models.cama.seer_survival import survival_models as sm
from models.cama.seer_survival import variables
from models.cama.seer_survival.settings import SurvivalSettings
from models.steps import indexing
NO_CATEGORY = "NA"
def figure_settings() -> dict:
"""`[figure]` of `model.toml`: what `figure_record` takes besides the scenario."""
import tomllib
return tomllib.loads(variables.TOML.read_text(encoding="utf-8"))["figure"]
@dataclass(frozen=True, eq=False)
class Design:
"""The covariates' coding the fits were made with: each covariate's categories sorted (the dummies drop the first) and in
order of first appearance (the HBN's integer codes), so any frame is coded as the training cohort was."""
covariates: list[str]
sorted_categories: dict[str, list[str]]
appearance: dict[str, list[str]]
@classmethod
def of(cls, frame: sc.SurvivalFrame) -> "Design":
df = frame.df
return cls(list(frame.covariates), {c: sorted(df[c].unique()) for c in frame.covariates},
{c: list(pd.factorize(df[c])[1]) for c in frame.covariates})
@property
def levels(self) -> np.ndarray:
return np.array([len(self.appearance[c]) for c in self.covariates])
def encode(self, df: pd.DataFrame) -> tuple[np.ndarray, np.ndarray]:
"""(dummies, integer codes); a category the training cohort never had is coded as its reference."""
dummies, codes = [], []
for c in self.covariates:
values = df[c].fillna(NO_CATEGORY).astype(str).str.strip()
dummies += [(values == k).to_numpy(np.float32) for k in self.sorted_categories[c][1:]]
position = {k: i for i, k in enumerate(self.appearance[c])}
codes.append(values.map(position).fillna(0).astype(int).to_numpy())
return np.column_stack(dummies), np.column_stack(codes)
@dataclass
class Fit:
"""What `fit` leaves: the point fits, the bootstrap replicas' fits, the weights of the combination (the cohort's and each
configured scenario's) and what the cohort was."""
point: list
replicas: list
weights: np.ndarray
scenario_weights: dict
design: Design
members: int
deaths: int
calibration: list = field(default_factory=list)
class SeerSurvivalModel(BaseEstimator):
"""Scores a cohort's long frame (`predict_proba`: per member, in `pac_id` order, the risk of dying by each horizon)."""
def __init__(self, dictionary=None, survival=None, index=None, fit_state=None, kept=None, horizons_years=None):
self.dictionary = dictionary
self.survival = survival
self.index = index
self.fit_state = fit_state
self.kept = kept
self.horizons_years = horizons_years
@classmethod
def rehydrate(cls, saved) -> "SeerSurvivalModel":
"""The current class holding a saved model's state."""
model = cls.__new__(cls)
model.__dict__.update(saved.__dict__)
return model
# ------------------------------------------------------------------ from the timeline to the design
def recode(self, cohort: pd.DataFrame, *, indexed: bool = False) -> pd.DataFrame:
"""One row per member in the columns the dictionary makes; the cohort is re-indexed at the first invasive biopsy
unless it already is."""
if not indexed and self.index:
cohort = indexing.cohort(cohort, {}, self.index)
return variables.recode(cohort, self.dictionary)
def frame(self, recoded: pd.DataFrame) -> sc.SurvivalFrame:
"""The recoded members as the survival stage reads them, restricted to the covariates the depuration kept."""
columns = [c for c in recoded.columns if c in self.kept or not c.endswith("_cat")]
frame = sc.survival_frame(recoded[columns], self.survival)
covariates = [c for c in self.fit_state.design.covariates]
for c in covariates:
if c not in frame.df.columns:
frame.df[c] = NO_CATEGORY
return sc.SurvivalFrame(frame.df, covariates, frame.age_col, frame.numeric_cols)
def _survival(self, frame: sc.SurvivalFrame, weights=None) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
design = self.fit_state.design
X_dum, X_int = design.encode(frame.df)
P_lr, P_hb = sm.apply_intervals(self.fit_state.point, X_dum, X_int, design.levels)
W = self.fit_state.weights if weights is None else weights
return np.cumprod(P_lr, axis=1), np.cumprod(P_hb, axis=1), sm.mix(P_lr, P_hb, W)
def predict_proba(self, cohort: pd.DataFrame) -> np.ndarray:
recoded = self.recode(cohort)
frame = self.frame(recoded)
combined = self._survival(frame)[2]
order = np.argsort(recoded[self.dictionary["index"]["id_column"]].to_numpy())
return 1 - combined[order]
def predict(self, cohort: pd.DataFrame) -> np.ndarray:
return self.predict_proba(cohort)
# ------------------------------------------------------------------ a scenario's figure
def scenario_names(self) -> list[str]:
return [spec["name"] for spec in self.survival.subgroups]
def scenario_masks(self, frame: sc.SurvivalFrame) -> dict[str, np.ndarray]:
return sc.sv_masks(frame, self.survival, self.dictionary)
def figure_record(self, frame: sc.SurvivalFrame, scenario: str, *, ks_max_seconds: float = 30.0, n_boot: int | None = None,
min_members: int = 30, min_deaths: int = 5, extrapolate_months: int | None = None) -> dict:
"""The figure of one scenario over the members of `frame`; `None` for the parts a scenario with too few members or
deaths cannot support. The interval of each point is the percentile of the replicas' mean survival over members
resampled with replacement."""
s = self.survival
masks = self.scenario_masks(frame)
mask = masks[scenario]
df = frame.df[mask]
deaths = int(df["evento"].sum())
record = {"scenario": scenario, "members": int(len(df)), "deaths": deaths, "horizons": list(s.horizons), "points": []}
if len(df) < min_members or deaths < min_deaths:
return {**record, "drawable": False}
months, events = df["meses_int"].values, df["evento"].values
horizon = max(s.months_max, max(s.horizons))
S, lo, hi = fw.km_curva(months, events, horizon)
d, c = fw.tabla_eventos(months, events)
weibull = fw.ajustar_weibull(d, c)
fractional = fw.ajustar_ks(d, c, k_fijo=sc._fixed_k(weibull, s), lam_ref=weibull["lam"], max_seg=ks_max_seconds)
reach = extrapolate_months or s.months_extrapolated
grid = np.arange(0, reach + 1, dtype=float)
record.update(drawable=True, months=list(range(horizon + 1)), km={"S": S.tolist(), "lo": lo.tolist(), "hi": hi.tolist()},
curve_months=grid.tolist(),
weibull={"k": float(weibull["k"]), "S": np.asarray(weibull["S"](grid)).tolist()},
fractional={"k": float(fractional["k"]), "alpha": float(fractional["alpha"]), "beta": float(fractional["beta"]),
"S": np.asarray(fractional["S"](grid)).tolist()})
weights = self.fit_state.scenario_weights.get(scenario, self.fit_state.weights)
design = self.fit_state.design
X_dum, X_int = design.encode(df)
rng = np.random.default_rng(s.seed + 1)
replicas = self.fit_state.replicas[: n_boot if n_boot is not None else len(self.fit_state.replicas)]
started, boots = time.monotonic(), []
P_lr, P_hb = sm.apply_intervals(self.fit_state.point, X_dum, X_int, design.levels)
point = [np.cumprod(P_lr, axis=1).mean(0), np.cumprod(P_hb, axis=1).mean(0), sm.mix(P_lr, P_hb, weights).mean(0)]
for fits in replicas:
pick = rng.integers(0, len(df), len(df))
Pl, Ph = sm.apply_intervals(fits, X_dum[pick], X_int[pick], design.levels)
boots.append(np.concatenate([np.cumprod(Pl, axis=1).mean(0), np.cumprod(Ph, axis=1).mean(0),
sm.mix(Pl, Ph, weights).mean(0)]))
ic = np.percentile(np.array(boots), [2.5, 97.5], axis=0) if boots else np.full((2, 3 * len(s.horizons)), np.nan)
for j, name in enumerate(("LR", "HBN", "COMB")):
for i, h in enumerate(s.horizons):
k = j * len(s.horizons) + i
record["points"].append({"model": name, "months": int(h), "S": float(point[j][i]),
"low": float(ic[0, k]), "high": float(ic[1, k])})
record["seconds"] = round(time.monotonic() - started, 2)
return record
def fit(recoded: pd.DataFrame, depurated: pd.DataFrame, dictionary: dict, survival: SurvivalSettings, index: dict | None,
n_boot: int | None = None, on_progress=None) -> SeerSurvivalModel:
"""The model fitted on `recoded` members (all the dictionary's columns) whose covariates are those of `depurated`."""
s = survival
kept = [c for c in depurated.columns if c.endswith("_cat")]
frame = sc.survival_frame(depurated, s)
cohort = sc.sv_cohort(frame, s)
N = len(cohort.months)
everyone = np.arange(N)
oof_lr, oof_hb = sm.out_of_fold(cohort, s, N)
weights = sm.stacking_weights(cohort, s, np.ones(N, bool), oof_lr, oof_hb)["w_LR"].values
point = sm.fit_kept_intervals(cohort, s, everyone)
reference = [f.parents for f in point] if s.hbn_parents == "fijos" else None
masks = sc.sv_masks(frame, s, dictionary)
scenario_weights = {name: sm.stacking_weights(cohort, s, mask, oof_lr, oof_hb)["w_LR"].values for name, mask in masks.items()}
rng = np.random.default_rng(s.seed)
replicas = []
for r in range(s.n_boot if n_boot is None else n_boot):
replicas.append(sm.fit_kept_intervals(cohort, s, rng.integers(0, N, N), reference))
if on_progress:
on_progress(r + 1)
out_of_sample = sm.mix(oof_lr, oof_hb, weights)
horizon = len(s.horizons) - 1
deciles = pd.qcut(pd.Series(out_of_sample[:, horizon]).rank(method="first"), 10, labels=False)
calibration = []
for q in range(10):
pick = (deciles == q).to_numpy()
curve, _, _ = fw.km_curva(cohort.months[pick], cohort.event[pick], int(s.horizons[-1]))
calibration.append({"decile": q + 1, "members": int(pick.sum()),
"predicted": {str(h): float(out_of_sample[pick, i].mean()) for i, h in enumerate(s.horizons)},
"observed": {str(h): float(curve[int(h)]) for h in s.horizons}})
state = Fit(point, replicas, weights, scenario_weights, Design.of(frame), N, int(frame.df["evento"].sum()), calibration)
horizons = [h / 12 for h in s.horizons]
return SeerSurvivalModel(dictionary, s, index, state, kept, horizons)
+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"