336 lines
20 KiB
Python
336 lines
20 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}}
|
|
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."""
|
|
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 "Estadio_cat" in 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}
|
|
|
|
r = dev.development(members, settings)["desarrollo"]
|
|
|
|
assert r["errores"] == {}, r["errores"]
|
|
assert {"or_lr_balanceada", "hbn_arcos", "subgrupos_weibull", "prueba_edad"} <= set(r["tablas"])
|
|
assert r["figuras"] and all(isinstance(v, str) for v in r["figuras"].values())
|