A training run takes every model; the public cohorts' code lives with the tests
This commit is contained in:
@@ -0,0 +1,135 @@
|
||||
"""The two public cohorts the recurrence model is proved on, METABRIC and SCAN-B, each as a
|
||||
`Cohort` from its dataset as the `cama_reference` pipeline loads it (every value as written,
|
||||
column names as dlt names them, `line` the order the file is published in)."""
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from models.cama import recurrence
|
||||
from models.cama.recurrence import site
|
||||
from models.cama.recurrence.cohorts import (
|
||||
AGE,
|
||||
DAYS_PER_MONTH,
|
||||
GRADES,
|
||||
NODES,
|
||||
SIZE,
|
||||
Cohort,
|
||||
_band,
|
||||
_number,
|
||||
_text,
|
||||
collinear,
|
||||
)
|
||||
|
||||
SOURCES = ("metabric", "scanb")
|
||||
SAVED = "metabric"
|
||||
N_BOOTSTRAP = {"metabric": 100, "scanb": 40, "site": 40}
|
||||
LABELS = {"metabric": "METABRIC", "scanb": "SCAN-B"}
|
||||
SAMPLING = {
|
||||
"criterio": "pacientes con tiempo y estado de recaída; SCAN-B solo mujeres",
|
||||
"origen": "METABRIC y SCAN-B (externas)",
|
||||
}
|
||||
SCENARIOS = {
|
||||
"metabric": {
|
||||
"RE+ · sin ganglios · tumor ≤20 mm (bajo riesgo)": {
|
||||
"Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["0"],
|
||||
"Tamano_tumor": ["<=20 mm"]},
|
||||
"Ganglios 4+": {"Ganglios_positivos": ["4+"]},
|
||||
"Tumor >50 mm": {"Tamano_tumor": [">50 mm"]},
|
||||
"< 45 años": {"Edad": ["<45"]},
|
||||
"≥ 75 años": {"Edad": ["75+"]},
|
||||
"Basal (PAM50)": {"Subtipo_PAM50": ["Basal"]},
|
||||
"HER2 (PAM50)": {"Subtipo_PAM50": ["Her2"]},
|
||||
"Luminal B (PAM50)": {"Subtipo_PAM50": ["LumB"]},
|
||||
"RE+ · 1-3 ganglios · cirugía conservadora": {
|
||||
"Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["1-3"],
|
||||
"Cirugia": ["BREAST CONSERVING"]},
|
||||
"RE− · grado 3": {"Receptor_estrogeno": ["Negative"], "Grado_histologico": ["3"]},
|
||||
},
|
||||
"scanb": site.SCENARIOS,
|
||||
} # fmt: skip
|
||||
FIXED = {
|
||||
"metabric": ["paciente", "tiempo_meses", "evento"],
|
||||
"scanb": ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"],
|
||||
}
|
||||
TREATMENT = {
|
||||
"metabric": ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"],
|
||||
"scanb": ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"],
|
||||
}
|
||||
# Covariates taken as they come (our name: the dataset's column).
|
||||
PASSTHROUGH = {
|
||||
"metabric": {
|
||||
"Receptor_estrogeno": "er_status", "Receptor_progesterona": "pr_status",
|
||||
"HER2": "her2_status", "Subtipo_PAM50": "pam50_x_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",
|
||||
},
|
||||
"scanb": {
|
||||
"Receptor_estrogeno": "er", "Receptor_progesterona": "pr", "HER2": "her2",
|
||||
"Ki67": "ki67", "Subtipo_clinico": "clinical_subtype", "Tipo_histologico": "histology",
|
||||
"Estado_menopausico": "menopause_status_bin", "Lateralidad": "laterality",
|
||||
"Estadio_clinico": "tnm_clinical_stage", "Cirugia": "surgery_type",
|
||||
"Quimioterapia": "chemotherapy", "Radioterapia": "radiation",
|
||||
"Hormonoterapia": "endocrine", "AntiHER2": "anti_her2",
|
||||
},
|
||||
} # fmt: skip
|
||||
SCANB_NODES = {"NodeNegative": "0", "SubMicroMet": "0", "1to3": "1-3", "4toX": "4+"}
|
||||
SCANB_GRADES = {"Grade1": "1", "Grade2": "2", "Grade3": "3"}
|
||||
|
||||
|
||||
def _in_order(rows: pd.DataFrame) -> pd.DataFrame:
|
||||
return rows.sort_values("line", kind="stable").reset_index(drop=True)
|
||||
|
||||
|
||||
def _metabric(rows: pd.DataFrame) -> pd.DataFrame:
|
||||
d = _in_order(rows).dropna(subset=["relapse_free_status", "relapse_free_status_monthsx"])
|
||||
d = d.reset_index(drop=True)
|
||||
out = pd.DataFrame({"paciente": d["patient_id"]})
|
||||
out["tiempo_meses"] = _number(d["relapse_free_status_monthsx"])
|
||||
out["evento"] = d["relapse_free_status"].str.startswith("1").astype(int)
|
||||
out["Edad"] = _band(_number(d["age_at_diagnosis"]), *AGE)
|
||||
out["Tamano_tumor"] = _band(_number(d["tumor_size"]), *SIZE)
|
||||
out["Ganglios_positivos"] = _band(_number(d["lymph_nodes_examined_positive"]), *NODES)
|
||||
out["Grado_histologico"] = _text(d["neoplasm_histologic_grade"].map(GRADES))
|
||||
# Mutational load in tertiles of this cohort; a value on a cut falls in the lower band.
|
||||
load = _number(d["mutation_count"])
|
||||
q1, q2 = load.quantile([1 / 3, 2 / 3]).to_numpy()
|
||||
edges = [-1, q1 + 1e-9, q2 + 1e-9, 1e6]
|
||||
out["Carga_mutacional"] = _band(load, edges, ["baja", "media", "alta"])
|
||||
for name, column in PASSTHROUGH["metabric"].items():
|
||||
out[name] = _text(d[column])
|
||||
return out
|
||||
|
||||
|
||||
def _scanb(rows: pd.DataFrame) -> pd.DataFrame:
|
||||
d = _in_order(rows)
|
||||
d = d[d["gender"] == "F"].dropna(subset=["rfi_event", "rfi_days"]).reset_index(drop=True)
|
||||
rfi, died = _number(d["rfi_event"]), _number(d["os_event"])
|
||||
out = pd.DataFrame({"paciente": d["patient_name"]})
|
||||
out["tiempo_meses"] = _number(d["rfi_days"]) / DAYS_PER_MONTH
|
||||
out["evento"] = rfi.astype(int)
|
||||
out["muerte_sin_recaida"] = ((died == 1) & (rfi == 0)).astype(int)
|
||||
out["Edad"] = _band(_number(d["age_5year_bin"]) - 2, *AGE) # the 5-year bin's middle
|
||||
out["Tamano_tumor"] = _band(_number(d["tumor_size_mm"]), *SIZE)
|
||||
out["Ganglios_positivos"] = _text(d["node_met_spec"].map(SCANB_NODES))
|
||||
out["Grado_histologico"] = _text(d["nhg"].map(SCANB_GRADES))
|
||||
for name, column in PASSTHROUGH["scanb"].items():
|
||||
out[name] = _text(d[column])
|
||||
return out
|
||||
|
||||
|
||||
def prepare(source: str, raw: pd.DataFrame) -> Cohort:
|
||||
full = {"metabric": _metabric, "scanb": _scanb}[source](raw)
|
||||
fixed, treatment = FIXED[source], TREATMENT[source]
|
||||
covariates = [c for c in full.columns if c not in fixed]
|
||||
dropped = collinear(full, [c for c in covariates if c not in treatment])
|
||||
kept = [c for c in covariates if c not in dropped]
|
||||
return Cohort(source, full[fixed + kept], kept, [c for c in treatment if c in kept], dropped,
|
||||
LABELS[source], SCENARIOS[source], SAMPLING) # fmt: skip
|
||||
|
||||
|
||||
def train(raws: dict[str, pd.DataFrame], bootstrap: bool = True) -> tuple:
|
||||
"""Both cohorts' models, validation, calculator and risk factors; METABRIC's is kept."""
|
||||
found = {s: prepare(s, raws[s]) for s in SOURCES}
|
||||
return recurrence.fit(found, SAVED, "metabric+scanb", N_BOOTSTRAP if bootstrap else {})
|
||||
+11
-11
@@ -25,6 +25,7 @@ from pathlib import Path
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
import recurrence_reference as reference
|
||||
from joblib.externals.loky import get_reusable_executor
|
||||
from scipy.special import gammaln
|
||||
|
||||
@@ -71,14 +72,14 @@ def raws(tmp_path_factory) -> dict[str, pd.DataFrame]:
|
||||
# Each cohort's rows as the pipeline loaded them (one source node per cohort).
|
||||
out = folder / "datasets.pkl"
|
||||
platform.run("python", "-c", "import pandas as pd; from persistance import nodes; "
|
||||
"from models.cama import recurrence; pd.to_pickle({s: pd.DataFrame(nodes.rows("
|
||||
f"'cama_reference', s)) for s in recurrence.SOURCES}}, {str(out)!r})") # fmt: skip
|
||||
f"pd.to_pickle({{s: pd.DataFrame(nodes.rows('cama_reference', s)) "
|
||||
f"for s in {reference.SOURCES!r}}}, {str(out)!r})") # fmt: skip
|
||||
return pd.read_pickle(out)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def prepared(raws):
|
||||
return {s: cohorts.prepare(s, raw) for s, raw in raws.items()}
|
||||
return {s: reference.prepare(s, raw) for s, raw in raws.items()}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
@@ -155,7 +156,7 @@ def _check_figures(records: list[dict], fractional_tolerance: float):
|
||||
# ---------------------------------------------------------------- fast
|
||||
|
||||
|
||||
def test_cohorts(prepared, raws):
|
||||
def test_cohorts(prepared):
|
||||
sampling = _json("rutinas/MUESTREO.json")["cohortes"]
|
||||
missing = _json("rutinas/DATOS_FALTANTES.json")["desconocidos_por_covariable"]
|
||||
for source, c in prepared.items():
|
||||
@@ -164,18 +165,17 @@ def test_cohorts(prepared, raws):
|
||||
assert c.eliminated == sampling[source]["eliminadas_por_colinealidad"]
|
||||
assert c.covariates == list(missing[source])
|
||||
assert cohorts.unknown_shares(c) == missing[source]
|
||||
pd.testing.assert_frame_equal(recurrence.cohort(source, raws[source]), c.frame)
|
||||
assert prepared["metabric"].covariates == VERSION["model"]["covariates"]
|
||||
|
||||
|
||||
def test_routines(prepared):
|
||||
found = reports.routines(prepared, modeling.N_BOOTSTRAP)
|
||||
found = reports.routines(prepared, reference.N_BOOTSTRAP)
|
||||
for name, record in found.items():
|
||||
assert record == _json(f"rutinas/{name}.json"), name
|
||||
|
||||
|
||||
def test_c_index_and_internal_auc(fits):
|
||||
rows = [r for s in recurrence.SOURCES for r in reports.auc_rows(fits[s])]
|
||||
rows = [r for s in reference.SOURCES for r in reports.auc_rows(fits[s])]
|
||||
assert _auc_rows(rows, False) == _auc_rows(DEVELOPMENT["auc"]["filas"], False)
|
||||
metrics = reports.metrics(rows)
|
||||
assert metrics == {k: v for k, v in VERSION["metrics"].items() if "bootstrap" not in k}
|
||||
@@ -206,7 +206,7 @@ def test_saved_model(fits):
|
||||
def test_calculator(fits):
|
||||
"""All 60 table rows, and the 20 figures but their fractional Weibull's tolerance."""
|
||||
records, rows = [], []
|
||||
for source in recurrence.SOURCES:
|
||||
for source in reference.SOURCES:
|
||||
found = calculator.calculator(fits[source])
|
||||
records += found[0]
|
||||
rows += found[1]
|
||||
@@ -220,12 +220,12 @@ def test_calculator(fits):
|
||||
def test_risk_factors(fits):
|
||||
"""All 273 rows, with v1's bootstrap selection shares (the slow test computes them)."""
|
||||
table = pd.concat(
|
||||
[factors.risk_factors(fits[s], _reference_selection(s)) for s in recurrence.SOURCES],
|
||||
[factors.risk_factors(fits[s], _reference_selection(s)) for s in reference.SOURCES],
|
||||
ignore_index=True,
|
||||
)
|
||||
_same_rows(reports.table(table)["filas"], DEVELOPMENT["factores_riesgo"]["filas"],
|
||||
FACTOR_TOLERANCE) # fmt: skip
|
||||
summary = [r for s in recurrence.SOURCES for r in factors.scenario_summary(fits[s], table)]
|
||||
summary = [r for s in reference.SOURCES for r in factors.scenario_summary(fits[s], table)]
|
||||
assert reports.table(summary) == _stages(DEVELOPMENT["escenarios_resumen"])
|
||||
|
||||
|
||||
@@ -262,7 +262,7 @@ def test_fractional_weibull_solver_matches_the_series():
|
||||
@pytest.mark.slow
|
||||
@slow
|
||||
def test_train_reproduces_v1(raws):
|
||||
model, metrics, found = recurrence.train(raws, bootstrap=True)
|
||||
model, metrics, found = reference.train(raws, bootstrap=True)
|
||||
assert metrics == VERSION["metrics"]
|
||||
for h in recurrence.HORIZONS:
|
||||
mine = model.tables[h]
|
||||
|
||||
Reference in New Issue
Block a user