562 lines
34 KiB
Python
562 lines
34 KiB
Python
"""What this module covers: `models.cama.survival`: the index it takes from the total cohort (the first invasive biopsy
|
||
report, with its rules), the covariates and outcome it derives from a build's events, the interval survival estimator
|
||
(that it scores unseen categories and intervals without deaths, and that grade and ER move the mortality the way the
|
||
data say), that the dataflow reaches its metrics and routines without MLflow, that training registers a version with
|
||
its lineage and estimating with it dates each risk by the model's own index.
|
||
|
||
Fixtures: `cohort_frame`, a long frame of 240 members of the total cohort whose death depends on the grade and on ER,
|
||
with members that must be left out; `cohort_file`, that frame as a build's Parquet file with its lineage (the window
|
||
in its parameters); `mlflow_tracking` (conftest), a SQLite-backed MLflow.
|
||
"""
|
||
|
||
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.survival import estimator
|
||
from models.cama.survival.estimator import FEATURES, INDEX_COLUMN, IntervalSurvival, MemberFeatures
|
||
from models.dags.estimation import estimate
|
||
from models.dags.training import Scenario, dataflow, find_trained, train
|
||
from models.io.contracts import COHORT_SCHEMA as SCHEMA
|
||
from models.io.storage import CohortFile, read_cohort, read_metadata
|
||
from models.steps import indexing
|
||
|
||
CUTOFF = date(2026, 1, 1)
|
||
SCENARIO = Scenario.load("cama", "survival")
|
||
CONFIG = SCENARIO.config
|
||
WINDOW = {"recruitment_start": "2018-01-01", "recruitment_end": "2027-01-01", "cutoff": CUTOFF.isoformat()}
|
||
LINEAGE = {"url": "cama/cohorte_total", "datos_as_of": CUTOFF.isoformat(), "parametros": json.dumps(WINDOW)}
|
||
N = 240
|
||
|
||
|
||
def _row(pac_id, when, tipo, valor=None, numero=None, source="biopsiamama", source_id=None, first=None):
|
||
return {"pac_id": pac_id, "fecha_indice": first or when, "fecha": when,
|
||
"conocida_en": datetime(2026, 1, 1, tzinfo=timezone.utc), "clase": "medicion", "tipo": tipo, "codigo": tipo,
|
||
"valor_codigo": valor, "valor_numerico": numero, "fuente_tabla": source,
|
||
"fuente_id": source_id or f"{pac_id}-{tipo}"}
|
||
|
||
|
||
def _report(pac_id, index, grade="G2", er="POSITIVO", her2="H1", ki67=18.0, first=None, size=30.0):
|
||
"""The invasive biopsy report of `pac_id` on `index`, with its results."""
|
||
key = f"B{pac_id}"
|
||
rows = [_row(pac_id, index, "biopsia", "CARCINOMA_INVASOR", source_id=key, first=first),
|
||
_row(pac_id, index, "tipo_histologico", "DUCTAL_INFILTRANTE", source_id=key, first=first),
|
||
_row(pac_id, index, "grado_nottingham", grade, source_id=key, first=first),
|
||
_row(pac_id, index, "receptor_estrogeno", er, source_id=key, first=first),
|
||
_row(pac_id, index, "receptor_progesterona", er, source_id=key, first=first),
|
||
_row(pac_id, index, "her2", her2, source_id=key, first=first),
|
||
_row(pac_id, index, "ki67_pct", numero=ki67, source_id=key, first=first),
|
||
_row(pac_id, index, "tamano_tumor_mm", numero=size, source_id=key, first=first)]
|
||
return rows
|
||
|
||
|
||
def _person(pac_id, born, first, died=None):
|
||
rows = [_row(pac_id, born, "nacimiento", source="persona", first=first)]
|
||
if died:
|
||
rows.append(_row(pac_id, died, "defuncion", source="persona", first=first))
|
||
return rows
|
||
|
||
|
||
@pytest.fixture(scope="module")
|
||
def cohort_frame():
|
||
"""240 members, each with her birth, an invasive biopsy report in 2024-01..2025-06 (grade 1 to 3, ER positive or
|
||
negative) and, if she dies by the cut-off, her death: exponential in months, faster with grade 3 and without ER.
|
||
Members 241 to 245 must be left out: a benign biopsy only, no birth date, a death before the report, a report
|
||
before the window, and an invasive report after the cut-off."""
|
||
rng = np.random.default_rng(3)
|
||
rows = []
|
||
for pac_id in range(1, N + 1):
|
||
index = date(2024, 1, 1) + timedelta(days=int(rng.integers(0, 546)))
|
||
grade, er = str(rng.choice(["G1", "G2", "G3"])), str(rng.choice(["POSITIVO", "NEGATIVO"]))
|
||
rate = 0.012 * np.exp(1.3 * (grade == "G3") - 0.6 * (er == "POSITIVO"))
|
||
died = index + timedelta(days=int(rng.exponential(1 / rate) * 30.4375))
|
||
rows += _person(pac_id, date(1960, 1, 1) + timedelta(days=pac_id * 30), index - timedelta(days=10),
|
||
died if died <= CUTOFF else None)
|
||
rows += _report(pac_id, index, grade, er, first=index - timedelta(days=10))
|
||
first = date(2025, 1, 1)
|
||
rows += [_row(241, first, "biopsia", "BENIGNO", source_id="B241", first=first)]
|
||
rows += _report(242, first, first=first)
|
||
rows += _person(243, date(1960, 1, 1), first, died=first - timedelta(days=20)) + _report(243, first, first=first)
|
||
rows += _person(244, date(1960, 1, 1), date(2010, 1, 1)) + _report(244, date(2010, 3, 1), first=date(2010, 1, 1))
|
||
rows += _person(245, date(1960, 1, 1), first) + _report(245, date(2026, 3, 1), first=first)
|
||
return pd.DataFrame(rows, columns=SCHEMA.names)
|
||
|
||
|
||
@pytest.fixture
|
||
def cohort_file(cohort_frame, tmp_path):
|
||
"""The frame as build 3's file, with the lineage a dbt build gives."""
|
||
table = pa.Table.from_pandas(cohort_frame, schema=SCHEMA, preserve_index=False)
|
||
path = tmp_path / "3.parquet"
|
||
pq.write_table(table.replace_schema_metadata({**LINEAGE, "armado_id": "3"}), path)
|
||
return path
|
||
|
||
|
||
def _indexed(frame):
|
||
return indexing.cohort(frame, LINEAGE, CONFIG["index"])
|
||
|
||
|
||
def test_the_index_is_the_first_invasive_biopsy_report_and_its_rules_leave_out_who_cannot_be_followed(cohort_frame):
|
||
"""Pins down: members 1 to 240 are indexed at their invasive report; a benign biopsy has no index (241), a missing
|
||
birth date (242), a death before the report (243) and a report outside the window (244, and 245 after the cut-off
|
||
window end) leave the cohort, each charged to its own rule. Fails if the kind stops reading the grade, the window
|
||
or either rule."""
|
||
attrition = dict(indexing.index_attrition(cohort_frame, LINEAGE, CONFIG["index"]))
|
||
|
||
assert attrition["pacientes"] == N + 5 and attrition["indexed"] == N + 3
|
||
assert attrition["sin_nacimiento"] == N + 2 and attrition["defuncion_hasta_el_indice"] == N + 1
|
||
members = _indexed(cohort_frame)["pac_id"].unique()
|
||
assert set(members) == set(range(1, N + 1)) | {245}
|
||
reindexed = _indexed(cohort_frame).groupby("pac_id")["fecha_indice"].first()
|
||
assert reindexed[1] == cohort_frame[(cohort_frame["pac_id"] == 1) & (cohort_frame["tipo"] == "biopsia")]["fecha"].iloc[0]
|
||
|
||
|
||
def test_covariates_are_the_index_reports_results(cohort_frame):
|
||
"""Pins down: the covariates are the results of the report on the index date: type, grade, ER, PR, HER2 and the
|
||
Ki-67 band; a grade reported a year later does not replace them, and the age group is the age at the index. Fails
|
||
if the covariates read another report or window, or the age is taken at another date."""
|
||
one = cohort_frame[cohort_frame["pac_id"] == 1]
|
||
later = pd.DataFrame([_row(1, date(2025, 12, 1), "grado_nottingham", "G1" if one[one["tipo"] == "grado_nottingham"][
|
||
"valor_codigo"].iloc[0] != "G1" else "G3", first=one["fecha_indice"].iloc[0])], columns=SCHEMA.names)
|
||
table = estimator.member_table(_indexed(pd.concat([one, later])), CONFIG["age_cuts"], CONFIG["ki67_cuts"],
|
||
CONFIG["result_days"], CONFIG["size_cuts"])
|
||
|
||
row = table.loc[1]
|
||
reported = one[one["tipo"] == "grado_nottingham"]["valor_codigo"].iloc[0]
|
||
assert (row["histologic_type"], row["grade"], row["her2"], row["ki67_group"], row["size_group"]) == (
|
||
"DUCTAL_INFILTRANTE", reported, "H1", "14-19", "20-49")
|
||
assert row["er"] == one[one["tipo"] == "receptor_estrogeno"]["valor_codigo"].iloc[0] == row["pr"]
|
||
born, index = date(1960, 1, 1) + timedelta(days=30), table.loc[1, "fecha_indice"].date()
|
||
age = (index - born).days / 365.25
|
||
assert row["age_group"] == ("<45" if age < 45 else "45-59" if age < 60 else "60-74" if age < 75 else "≥75")
|
||
|
||
|
||
def test_the_outcome_is_the_months_to_death_or_to_the_cutoff_cut_at_the_cap(cohort_frame):
|
||
"""Pins down: a member who dies in follow-up has her whole months to the death and `event`; one without a death is
|
||
followed to the cut-off without it; a death after `cap_months` counts as alive at the cap. Fails if the months, the
|
||
censoring date or the cap change."""
|
||
rows = (_person(1, date(1960, 1, 1), date(2024, 1, 1), died=date(2024, 8, 10)) + _report(1, date(2024, 1, 1))
|
||
+ _person(2, date(1960, 1, 1), date(2025, 1, 1)) + _report(2, date(2025, 1, 1))
|
||
+ _person(3, date(1960, 1, 1), date(2023, 1, 1), died=date(2025, 11, 1)) + _report(3, date(2023, 1, 1)))
|
||
frame = pd.DataFrame(rows, columns=SCHEMA.names)
|
||
|
||
table = estimator.outcome_table(frame, CUTOFF, cap_months=24)
|
||
|
||
assert table.loc[1].tolist() == [7, True] # 2024-01-01 to 2024-08-10: 222 days
|
||
assert table.loc[2].tolist() == [11, False] # 2025-01-01 to the cut-off: 365 days, 11.99 whole months
|
||
assert table.loc[3].tolist() == [24, False] # dies after 24 months: alive at the cap
|
||
|
||
|
||
@pytest.fixture(scope="module")
|
||
def labelled(cohort_frame):
|
||
"""The 240 indexed members with their covariates and outcome, as the dataflow labels them."""
|
||
indexed = _indexed(cohort_frame)
|
||
indexed = indexed[indexed["pac_id"] <= N]
|
||
features = estimator.member_table(indexed, CONFIG["age_cuts"], CONFIG["ki67_cuts"], CONFIG["result_days"], CONFIG["size_cuts"])
|
||
return features.join(estimator.outcome_table(indexed, CUTOFF, 24)).reset_index()
|
||
|
||
|
||
def test_grade_and_er_move_the_mortality_the_way_the_data_say(labelled):
|
||
"""Pins down: fitted on members whose death depends on grade 3 and on no ER, the estimator gives grade 3 a higher
|
||
mortality at every horizon than grade 1, and the mortality grows with the horizon and stays in 0 to 1. Fails if the
|
||
fit stops using the covariates or the survival stops being a product of the intervals."""
|
||
model = IntervalSurvival(CONFIG["survival"], tuple(CONFIG["horizons_years"])).fit(labelled[FEATURES],
|
||
labelled[["months", "event"]])
|
||
probe = labelled[FEATURES].iloc[[0, 0]].copy()
|
||
probe["grade"] = ["G1", "G3"]
|
||
probe["er"] = "POSITIVO"
|
||
|
||
mortality = model.predict_proba(probe)
|
||
|
||
assert mortality.shape == (2, 3) and ((0 <= mortality) & (mortality <= 1)).all()
|
||
assert (mortality[1] > mortality[0]).all() and (np.diff(mortality, axis=1) >= 0).all()
|
||
|
||
|
||
def test_a_category_unseen_in_training_and_an_interval_without_deaths_are_scored(labelled):
|
||
"""Pins down: a grade the model never saw scores as unknown rather than failing, and a cohort where nobody dies in
|
||
the last interval still fits (a constant stands for the logistic regression). Fails if either raises."""
|
||
early = labelled.assign(event=labelled["event"] & (labelled["months"] < 12))
|
||
model = IntervalSurvival(CONFIG["survival"], tuple(CONFIG["horizons_years"])).fit(early[FEATURES],
|
||
early[["months", "event"]])
|
||
unseen = labelled[FEATURES].iloc[[0]].assign(grade="G9")
|
||
|
||
mortality = model.predict_proba(unseen)
|
||
|
||
assert np.isfinite(mortality).all()
|
||
assert mortality[0, 2] - mortality[0, 1] < 0.05 # nobody died in 12-18 months: only the network's smoothing remains
|
||
|
||
|
||
def test_the_pipeline_takes_the_total_cohort_and_scores_only_who_the_index_leaves(cohort_frame, labelled):
|
||
"""Pins down: the registered shape (`MemberFeatures` then the estimator) takes the unindexed frame, gives one row
|
||
per member of the frame, and leaves empty the members the scenario leaves out, with the model's index date first for
|
||
the rest. Fails if scoring stops indexing the build as training did."""
|
||
from sklearn.pipeline import Pipeline
|
||
|
||
fitted = IntervalSurvival(CONFIG["survival"], tuple(CONFIG["horizons_years"])).fit(labelled[FEATURES],
|
||
labelled[["months", "event"]])
|
||
pipeline = Pipeline([("members", MemberFeatures(dict(CONFIG["index"]), WINDOW, tuple(CONFIG["age_cuts"]),
|
||
tuple(CONFIG["ki67_cuts"]), CONFIG["result_days"], tuple(CONFIG["size_cuts"]))),
|
||
("survival", fitted)])
|
||
|
||
scored = pipeline.predict_proba(cohort_frame)
|
||
|
||
assert scored.shape == (N + 5, 4)
|
||
assert np.isnan(scored[N:N + 4, 0]).all() and not np.isnan(scored[:N, 0]).any()
|
||
assert not np.isnan(scored[N + 4, 0]) # member 245: indexed (her report is in the window), scored
|
||
|
||
|
||
def test_the_dataflow_reaches_its_metrics_and_routines_without_mlflow(cohort_frame):
|
||
"""Pins down: from the source cohort and its lineage the graph gives metrics that are numbers, and the five routine
|
||
records the registry checks before promoting. Fails if a node stops producing its record or a metric is not a
|
||
number."""
|
||
dr = dataflow(*SCENARIO.modules, config=CONFIG)
|
||
|
||
result = dr.execute(["metrics", "routines", "index_attrition"],
|
||
inputs={"source_cohort": cohort_frame, "cohort_lineage": LINEAGE})
|
||
|
||
assert all(isinstance(v, (int, float)) for v in result["metrics"].values())
|
||
assert result["metrics"]["n_train"] + result["metrics"]["n_test"] == N + 1
|
||
assert set(result["routines"]) == {"MUESTREO", "DATOS_FALTANTES", "METODO_ANALITICO", "BALANCE_CLASES",
|
||
"CONFIANZA_SALIDA"}
|
||
json.dumps(result["routines"])
|
||
|
||
|
||
def test_training_registers_a_version_and_estimating_dates_each_risk_by_the_models_index(cohort_file, mlflow_tracking,
|
||
tmp_path):
|
||
"""Pins down: training on a build's file registers a version; estimating with it writes one row per scored member
|
||
and horizon, dated by the model's index (the report), not by the cohort's, with the members the scenario leaves out
|
||
absent. Fails if the version cannot score a build or the estimate keeps the cohort's index date."""
|
||
version = train(SCENARIO, CohortFile(cohort_file))
|
||
output = tmp_path / "estimate.parquet"
|
||
|
||
resolved, wrote = estimate(SCENARIO, CohortFile(cohort_file), output, version)
|
||
|
||
assert wrote and resolved.version == version and find_trained(SCENARIO, CohortFile(cohort_file)) == version
|
||
risks = pq.read_table(output).to_pandas()
|
||
assert set(risks["horizonte_anios"]) == {0.5, 1.0, 1.5}
|
||
assert set(risks["pac_id"]) == set(range(1, N + 1)) | {245}
|
||
frame = read_cohort(cohort_file)
|
||
report = frame[(frame["tipo"] == "biopsia") & (frame["pac_id"] == 1)]["fecha"].iloc[0]
|
||
assert risks[risks["pac_id"] == 1]["fecha_indice"].iloc[0] == report
|
||
assert read_metadata(output)["desenlace"] == "muerte"
|
||
|
||
|
||
@pytest.fixture(scope="module")
|
||
def population_record(cohort_frame):
|
||
"""The `curvas` record the dataflow publishes for the 240 indexed members, with a small bootstrap to stay quick."""
|
||
config = {**CONFIG, "survival": {**CONFIG["survival"], "n_boot": 20, "ks_max_seconds": 5}}
|
||
dr = dataflow(*SCENARIO.modules, config=config)
|
||
return dr.execute(["population_curves"], inputs={"source_cohort": cohort_frame, "cohort_lineage": LINEAGE})["population_curves"]["curvas"]
|
||
|
||
|
||
def test_the_population_record_has_the_figures_curves_points_and_labels(population_record):
|
||
"""Pins down: the record the dashboard draws has the Kaplan-Meier with its band, the adjusted curve, both Weibull
|
||
curves, LR, HBN and combined points at 6, 12 and 18 months each with a 95 % interval, and the labels from the
|
||
settings. Fails if a curve or a series is missing, a curve rises, a band does not hold its curve, an interval is
|
||
inverted, or the labels stop coming from `[config.etiquetas]`."""
|
||
r = population_record
|
||
|
||
assert r["horizons_months"] == [6, 12, 18] and r["n"] == N + 1 and r["events"] > 20
|
||
km = r["km"]
|
||
assert km["months"][0] == 0 and km["S"][0] == 1.0 and np.all(np.diff(km["S"]) <= 1e-12)
|
||
assert all(lo <= s <= hi for lo, s, hi in zip(km["low"], km["S"], km["high"]))
|
||
for curve in (r["km_adjusted"]["S"], r["weibull"]["S"], r["weibull_fractional"]["S"]):
|
||
assert curve[0] == pytest.approx(1.0, abs=1e-6) and np.all(np.diff(curve) <= 1e-9)
|
||
assert set(r["points"]) == {"LR", "HBN", "COMB"}
|
||
for series in r["points"].values():
|
||
assert len(series["S"]) == 3 and all(0 <= lo <= hi <= 1 for lo, hi in zip(series["low"], series["high"]))
|
||
assert series["S"] == sorted(series["S"], reverse=True)
|
||
assert r["etiquetas"]["eje_x"] == CONFIG["etiquetas"]["eje_x"]
|
||
json.dumps(r)
|
||
|
||
|
||
def test_a_version_publishes_its_population_record(cohort_file, mlflow_tracking):
|
||
"""Pins down: training registers the `analisis/curvas.json` file with the version, and it is the record the dataflow
|
||
built. Fails if the saver stops logging a dataflow's `population`."""
|
||
from models.io.registry import registry
|
||
|
||
version = train(SCENARIO, CohortFile(cohort_file))
|
||
|
||
files = [f["path"] for f in registry.artifacts("cama", "survival", version)]
|
||
name, content = registry.artifact("cama", "survival", version, "analisis/curvas.json")
|
||
record = json.loads(content)
|
||
assert "analisis/curvas.json" in files and name == "curvas.json"
|
||
assert record["horizons_months"] == [6, 12, 18] and set(record["points"]) == {"LR", "HBN", "COMB"}
|
||
|
||
|
||
@pytest.fixture(scope="module")
|
||
def development_record(cohort_frame):
|
||
"""The `desarrollo` record the dataflow publishes for the 240 indexed members, with the smallest budget."""
|
||
config = {**CONFIG, "desarrollo": {**CONFIG["desarrollo"], "null_perm": 5, "n_bootstrap": 4, "bootstrap_max_seconds": 30,
|
||
"proposals_max_seconds": 20, "restarts": 1, "n_splits_proposals": 2, "bootstrap_restarts": 2}}
|
||
dr = dataflow(*SCENARIO.modules, config=config)
|
||
return dr.execute(["development"], inputs={"source_cohort": cohort_frame, "cohort_lineage": LINEAGE})["development"]["desarrollo"]
|
||
|
||
|
||
def test_a_stage_that_cannot_run_on_the_cohort_is_recorded_and_does_not_stop_the_others(development_record):
|
||
"""Pins down: on a cohort whose covariates barely vary (the 240 members here) the SEER stages that need variation
|
||
publish their error in the record and the run still produces it, with every stage listed. Fails if one stage's
|
||
exception escapes the node, which would stop a version from training. The stage and the treatments come from the
|
||
members' timeline, so none of them is listed as unavailable; fails if the record stops reading them."""
|
||
assert [e["etapa"] for e in development_record["etapas"]] == ["01", "02", "03", "04", "05", "06"]
|
||
assert set(development_record["errores"]) <= {"01", "02", "03", "04", "05", "06"}
|
||
assert development_record["variables_no_disponibles"] == []
|
||
|
||
|
||
def test_the_development_stages_publish_their_tables_and_figures_on_a_varied_cohort():
|
||
"""Pins down: on 600 members with varied covariates all six SEER stages run and publish their tables and figures.
|
||
Fails if a stage errors on a cohort of this shape or stops writing what the dashboard reads."""
|
||
from models.cama.survival import development as dev
|
||
|
||
rng = np.random.default_rng(11)
|
||
n = 600
|
||
grade = rng.choice(["G1", "G2", "G3"], n, p=[0.2, 0.5, 0.3])
|
||
er = rng.choice(["POSITIVO", "NEGATIVO"], n, p=[0.7, 0.3])
|
||
risk = 0.03 * np.exp(1.0 * (grade == "G3") - 0.6 * (er == "POSITIVO"))
|
||
months = np.minimum(rng.exponential(1 / risk), 30).round()
|
||
members = pd.DataFrame({
|
||
"fecha_indice": pd.to_datetime("2024-01-01") + pd.to_timedelta(rng.integers(0, 540, n), unit="D"),
|
||
"months": months.astype(int), "event": rng.random(n) < 1 - np.exp(-risk * 24),
|
||
"age_years": rng.normal(58, 12, n).clip(25, 90), "size_mm": rng.integers(5, 70, n).astype(float),
|
||
"histologic_type": rng.choice(["8500/3", "8520/3"], n, p=[0.85, 0.15]), "grade": grade, "er": er,
|
||
"pr": rng.choice(["POSITIVO", "NEGATIVO"], n), "her2": rng.choice(["H0", "H1", "H2", "H3"], n),
|
||
"ki67_group": rng.choice(["<14", "14-19", "≥20"], n)})
|
||
members["months"] = np.where(members["event"], np.minimum(members["months"], 23), 24)
|
||
settings = {**CONFIG["desarrollo"], "null_perm": 5, "n_bootstrap": 4, "bootstrap_max_seconds": 30,
|
||
"proposals_max_seconds": 20, "restarts": 1, "n_splits_proposals": 2, "bootstrap_restarts": 2}
|
||
|
||
r = dev.development(members, settings)["desarrollo"]
|
||
|
||
assert r["errores"] == {}, r["errores"]
|
||
assert {"or_lr_balanceada", "hbn_arcos", "subgrupos_weibull", "prueba_edad"} <= set(r["tablas"])
|
||
arcs = r["tablas"]["hbn_arcos"]
|
||
assert arcs["columnas"] == list(arcs["filas"][0]) and len(arcs["columnas"]) > 1
|
||
assert r["figuras"] and all(isinstance(v, str) for v in r["figuras"].values())
|
||
|
||
|
||
def _stage_five_table(csv_path, survival):
|
||
"""The table of the SEER pipeline's stage 5 for the main curve (`sv_table`): its own nodes over a CSV of the cohort."""
|
||
from hamilton import driver
|
||
|
||
from models.cama.seer_survival import survival_curves
|
||
|
||
dr = driver.Builder().with_modules(survival_curves).build()
|
||
return dr.execute(["sv_table"], inputs={"depurated_csv": str(csv_path), "survival": survival})["sv_table"]
|
||
|
||
|
||
@pytest.fixture(scope="module")
|
||
def members_frame(cohort_frame):
|
||
"""The 240 indexed members, labelled (covariates, follow-up, death), as the figure's nodes take them."""
|
||
return dataflow(*SCENARIO.modules, config=SCENARIO.config).execute(
|
||
["labelled_members"], inputs={"source_cohort": cohort_frame, "cohort_lineage": LINEAGE})["labelled_members"]
|
||
|
||
|
||
def test_the_published_figure_is_the_seer_pipelines_stage_five_on_the_same_members(members_frame, tmp_path):
|
||
"""Pins down: the Kaplan-Meier curve, the adjusted curve, the stacking weights, the points of LR, HBN and their
|
||
combination and their bootstrap interval in the published record are those that `models.cama.seer_survival`'s own stage 5
|
||
(`run_survival`, on a CSV of the same members and the same settings) gives. Fails if the record's code path stops being
|
||
the pipeline's, which would make the dashboard's figure another model's."""
|
||
import dataclasses
|
||
|
||
from models.cama.survival import estimator
|
||
|
||
survival = {**CONFIG["survival"], "n_boot": 6, "ks_max_seconds": 5}
|
||
config = {**CONFIG, "survival": survival}
|
||
ours = dataflow(*SCENARIO.modules, config=config).execute(
|
||
["population_curves"], inputs={"source_cohort": pd.DataFrame(), "cohort_lineage": {}},
|
||
overrides={"labelled_members": members_frame})["population_curves"]["curvas"]
|
||
|
||
csv = pd.DataFrame({"Survival months": members_frame["months"].astype(int).astype(str),
|
||
"Vital status recode (study cutoff used)": members_frame["event"].map({True: "Dead", False: "Alive"})})
|
||
for name in estimator.FEATURES:
|
||
csv[f"{name}_cat"] = members_frame[name].fillna("NA").astype(str)
|
||
csv.to_csv(tmp_path / "depurado.csv", index=False)
|
||
fixed = tuple(f"{n}_cat" for n in survival["hbn_fixed_parents"])
|
||
luis = dataclasses.replace(estimator.survival_settings(survival), hbn_fixed_parents=fixed)
|
||
theirs = _stage_five_table(tmp_path / "depurado.csv", luis)
|
||
|
||
for model in ("LR", "HBN", "COMB"):
|
||
rows = theirs[theirs["modelo"] == model]
|
||
assert ours["points"][model]["S"] == pytest.approx(rows["S"].tolist(), abs=1e-9)
|
||
assert ours["points"][model]["low"] == pytest.approx(rows["IC_inf"].tolist(), abs=1e-9)
|
||
assert ours["points"][model]["high"] == pytest.approx(rows["IC_sup"].tolist(), abs=1e-9)
|
||
km = theirs[theirs["modelo"] == "COMB"]
|
||
assert [ours["km"]["S"][m] for m in (6, 12, 18)] == pytest.approx(km["KM_crudo"].tolist(), abs=1e-9)
|
||
assert [ours["km_adjusted"]["S"][m] for m in (6, 12, 18)] == pytest.approx(km["KM_ajustada"].tolist(), abs=1e-9)
|
||
|
||
|
||
def test_the_production_model_predicts_what_the_pipelines_points_say(members_frame, tmp_path):
|
||
"""Pins down: the `IntervalSurvival` a version in production is (the model that scores each patient) gives, averaged over
|
||
the members it was fitted on, the survival at each horizon that the pipeline's stage 5 gives for LR, HBN and their
|
||
combination, exactly (the same data, the same settings). Fails if the model that scores patients drifts from the model whose
|
||
figure is published."""
|
||
import dataclasses
|
||
|
||
from models.cama.survival import estimator
|
||
from models.cama.survival.estimator import IntervalSurvival
|
||
|
||
survival = {**CONFIG["survival"], "n_boot": 0}
|
||
model = IntervalSurvival(survival, tuple(h / 12 for h in survival["horizons"])).fit(
|
||
members_frame[estimator.FEATURES], members_frame[["months", "event"]])
|
||
mean_combined = model.survival_proba(members_frame[estimator.FEATURES]).mean(axis=0)
|
||
|
||
csv = pd.DataFrame({"Survival months": members_frame["months"].astype(int).astype(str),
|
||
"Vital status recode (study cutoff used)": members_frame["event"].map({True: "Dead", False: "Alive"})})
|
||
for name in estimator.FEATURES:
|
||
csv[f"{name}_cat"] = members_frame[name].fillna("NA").astype(str)
|
||
csv.to_csv(tmp_path / "depurado.csv", index=False)
|
||
fixed = tuple(f"{n}_cat" for n in survival["hbn_fixed_parents"])
|
||
luis = dataclasses.replace(estimator.survival_settings(survival), hbn_fixed_parents=fixed)
|
||
theirs = _stage_five_table(tmp_path / "depurado.csv", luis)
|
||
|
||
assert mean_combined == pytest.approx(theirs[theirs["modelo"] == "COMB"]["S"].tolist(), abs=1e-6)
|
||
|
||
|
||
@pytest.fixture(scope="module")
|
||
def production_model(members_frame):
|
||
"""A model fitted on the 240 members: what a version in production is when the dashboard scores a selection."""
|
||
return IntervalSurvival(CONFIG["survival"], tuple(h / 12 for h in CONFIG["survival"]["horizons"])).fit(
|
||
members_frame[FEATURES], members_frame[["months", "event"]])
|
||
|
||
|
||
def test_the_live_figure_scores_a_scenarios_members_with_the_production_model(members_frame, production_model, monkeypatch):
|
||
"""Pins down: the record of a scenario is for its members only (their count and deaths), its points are the model's mean
|
||
survival for them at the model's horizons with an interval around it, and nothing is refitted (the same scenario twice gives
|
||
the same record). Fails if the scenario's mask is ignored, or the scenario changes the model's horizons."""
|
||
from models.cama.survival import live
|
||
|
||
young = np.arange(len(members_frame)) < 120
|
||
monkeypatch.setattr(live, "scenario_masks", lambda labelled: {"Primeras 120": young})
|
||
|
||
everyone = live.curves(SCENARIO, production_model, members_frame, None)
|
||
first = live.curves(SCENARIO, production_model, members_frame, "Primeras 120")
|
||
again = live.curves(SCENARIO, production_model, members_frame, "Primeras 120")
|
||
|
||
assert everyone["n"] == len(members_frame) and everyone["escenario"] == "Toda la cohorte" and everyone["horizons_months"] == [6, 12, 18]
|
||
assert first["n"] == 120 and first["escenario"] == "Primeras 120" and first["points"] == again["points"]
|
||
comb = first["points"]["COMB"]
|
||
assert all(lo <= s <= hi for lo, s, hi in zip(comb["low"], comb["S"], comb["high"]))
|
||
assert len(first["km_adjusted"]["S"]) == first["months_max"] + 1 and len(first["weibull_fractional"]["S"]) == len(first["weibull"]["S"])
|
||
|
||
|
||
def test_the_live_figure_fits_its_curves_to_the_members_deaths_and_takes_the_published_points(members_frame, production_model):
|
||
"""Pins down: the Weibull curves of a scenario's figure follow its members' own deaths (close to their Kaplan-Meier, as the
|
||
pipeline's survival stage fits a subgroup), and the points are the ones the version published for the subgroup when it did.
|
||
Fails if the curves are fitted to the model's prediction instead of the data, or the published points are ignored."""
|
||
from models.cama.survival import live
|
||
|
||
rows = [{"modelo": m, "meses": h, "S": 0.8, "IC_inf": 0.7, "IC_sup": 0.9, "subgrupo": "Toda la cohorte"}
|
||
for m in ("LR", "HBN", "COMB") for h in (6, 12, 18)]
|
||
published = live.published_points(rows, "Toda la cohorte")
|
||
|
||
record = live.curves(SCENARIO, production_model, members_frame, None, published)
|
||
|
||
km, weibull = np.asarray(record["km"]["S"]), np.asarray(record["weibull"]["S"])
|
||
at_months = np.interp(np.arange(len(km)), record["weibull"]["t"], weibull)
|
||
assert np.abs(at_months - km).max() < 0.05
|
||
assert record["points"]["COMB"] == {"S": [0.8] * 3, "low": [0.7] * 3, "high": [0.9] * 3}
|
||
assert live.published_points(rows, "Otro") is None
|
||
|
||
|
||
def test_a_patient_sees_the_scenarios_she_belongs_to_or_the_whole_cohort(members_frame, monkeypatch):
|
||
"""Pins down: a patient's scenarios are those whose mask holds her and that have enough members to draw; in none, the whole
|
||
cohort; and a patient outside the cohort is refused. Fails if a scenario too small to draw is offered, or a patient in no
|
||
scenario is left with nothing."""
|
||
from models.cama.survival import live
|
||
|
||
first, last = int(members_frame["pac_id"].iloc[0]), int(members_frame["pac_id"].iloc[-1])
|
||
inside = np.arange(len(members_frame)) < 100
|
||
tiny = np.arange(len(members_frame)) < 3
|
||
monkeypatch.setattr(live, "scenario_masks", lambda labelled: {"Grande": inside, "Diminuto": tiny})
|
||
|
||
assert live.patient_scenarios(members_frame, first) == ["Grande"] # in both; the tiny one has too few to draw
|
||
assert live.patient_scenarios(members_frame, last) == ["Toda la cohorte"] # in neither
|
||
with pytest.raises(live.QueryError):
|
||
live.patient_scenarios(members_frame, 10**9)
|
||
|
||
|
||
def test_the_scenarios_use_the_hospitals_age_and_subtype_and_none_that_needs_a_stage(members_frame):
|
||
"""Pins down: the scenario masks use the age in years and a subtype derived from the receptors (hormone receptors and
|
||
HER2 3+ / 0-1+), and a scenario that needs the stage or the surgery, which the hospital does not report, has no member.
|
||
Fails if a stage scenario includes everyone, or the subtype ignores the receptors."""
|
||
from models.cama.seer_survival import scenarios
|
||
from models.cama.survival import live
|
||
|
||
n = len(members_frame)
|
||
frame = members_frame.assign(er=np.resize(["POSITIVO", "NEGATIVO", "NEGATIVO", "POSITIVO"], n),
|
||
pr=np.resize(["POSITIVO", "NEGATIVO", "NEGATIVO", "NEGATIVO"], n),
|
||
her2=np.resize(["H1", "H3", "H0", "H2"], n))
|
||
found = live.molecular_subtype(frame).iloc[:4].tolist()
|
||
masks = live.scenario_masks(frame)
|
||
|
||
assert found == ["HR+/HER2-", "HR-/HER2+", "HR-/HER2-", "Desconocido"] # HER2 2+ is equivocal: unknown
|
||
assert set(masks) == set(scenarios.SCENARIOS)
|
||
assert not masks["Estadio IV"].any() and not masks["Triple negativo (HR−/HER2−) · estadio 0–II"].any()
|
||
|
||
|
||
@pytest.mark.parametrize("name", ["No existe", "Estadio IV"])
|
||
def test_a_scenario_that_cannot_be_answered_says_why(members_frame, production_model, name):
|
||
"""Pins down: an unknown scenario and one with too few members to say anything (every stage scenario, with the stage not
|
||
reported) are each a `QueryError` with a message. Fails if either runs and draws a meaningless figure or fails with an
|
||
unreadable error."""
|
||
from models.cama.survival import live
|
||
|
||
with pytest.raises(live.QueryError):
|
||
live.curves(SCENARIO, production_model, members_frame, name)
|
||
|
||
|
||
def test_the_monthly_curve_passes_through_the_horizons_and_never_rises():
|
||
"""Pins down: the month-by-month survival equals the model's at each horizon, starts at 1, never rises, and goes on past
|
||
the last horizon at the last interval's rate. Fails if the interpolation misses a horizon or the curve can go up."""
|
||
from models.cama.survival import live
|
||
|
||
curve = live.monthly(np.array([[0.9, 0.8, 0.6]]), [6, 12, 18], 24)[0]
|
||
|
||
assert curve[0] == 1.0 and curve[6] == pytest.approx(0.9) and curve[12] == pytest.approx(0.8) and curve[18] == pytest.approx(0.6)
|
||
assert (np.diff(curve) <= 1e-12).all() and curve[24] < curve[18]
|
||
|
||
|
||
def test_a_saved_model_whose_class_is_older_still_scores_with_the_current_code(members_frame, production_model):
|
||
"""Pins down: the fitted state of a model, put in an object of a class without the current methods (what loading a saved
|
||
model from before a code change gives), scores the same as the model itself once rehydrated. Fails if the live figure
|
||
depends on the class a version was saved with, which makes every older version unusable after a change."""
|
||
from types import SimpleNamespace
|
||
|
||
from models.cama.survival import live
|
||
|
||
stale = SimpleNamespace(**production_model.__dict__)
|
||
again = live.rehydrate(stale).component_survival(members_frame[FEATURES])
|
||
|
||
for name, expected in production_model.component_survival(members_frame[FEATURES]).items():
|
||
assert again[name] == pytest.approx(expected)
|
||
|
||
|
||
def test_the_members_carry_their_stage_and_treatments_and_the_scenarios_read_them():
|
||
"""Pins down: a member's stage is the one reported with her diagnosis and her surgery, radiotherapy and chemotherapy are
|
||
those of the year after it, and the clinical scenarios that need a stage or a conservative surgery find her. Fails if
|
||
`member_table` stops reading them or `live.scenario_masks` goes back to age and subtype only."""
|
||
from models.cama.survival import estimator, live
|
||
|
||
rows = []
|
||
for pac, (stage, surgery, her2) in enumerate([("EI", "SEGMENTECTOMIA", "H0"), ("EIV", "MASTECTOMIA_TOTAL", "H3")], start=1):
|
||
rows += [
|
||
{"pac_id": pac, "tipo": "nacimiento", "fecha": "1950-01-01", "valor_codigo": None, "valor_numerico": None},
|
||
{"pac_id": pac, "tipo": "biopsia", "fecha": "2025-01-10", "valor_codigo": "CARCINOMA_INVASOR", "valor_numerico": None},
|
||
{"pac_id": pac, "tipo": "estadio_clinico", "fecha": "2025-01-10", "valor_codigo": stage, "valor_numerico": None},
|
||
{"pac_id": pac, "tipo": "her2", "fecha": "2025-01-10", "valor_codigo": her2, "valor_numerico": None},
|
||
{"pac_id": pac, "tipo": "receptor_estrogeno", "fecha": "2025-01-10", "valor_codigo": "NEGATIVO", "valor_numerico": None},
|
||
{"pac_id": pac, "tipo": "receptor_progesterona", "fecha": "2025-01-10", "valor_codigo": "NEGATIVO", "valor_numerico": None},
|
||
{"pac_id": pac, "tipo": "cirugia", "fecha": "2025-03-01", "valor_codigo": surgery, "valor_numerico": None},
|
||
]
|
||
rows.append({"pac_id": 1, "tipo": "radioterapia", "fecha": "2025-05-01", "valor_codigo": "ADYUVANTE", "valor_numerico": None})
|
||
cohort = pd.DataFrame(rows).assign(fecha_indice="2025-01-10", fuente_id="x")
|
||
members = estimator.member_table(cohort, [45, 60, 75], [14, 20], 30)
|
||
assert members.loc[1, ["stage", "surgery", "radiotherapy", "chemotherapy"]].tolist() == ["I", "Cirugía conservadora", "Sí", "No"]
|
||
assert members.loc[2, ["stage", "surgery", "radiotherapy"]].tolist() == ["IV", "Mastectomía", "No"]
|
||
masks = live.scenario_masks(members.reset_index())
|
||
assert masks["Estadio I"].tolist() == [True, False] and masks["Estadio IV"].tolist() == [False, True]
|